repo_name
stringlengths
6
130
hexsha
sequence
file_path
sequence
code
sequence
apis
sequence
possible_versions
list
basbeu/PyLaia
[ "d14458484b56622204b1730a7d53220c5d0f1bc1" ]
[ "laia/utils/dortmund_image_to_tensor.py" ]
[ "from __future__ import absolute_import\nfrom __future__ import division\n\nimport cv2\nimport numpy as np\nimport torch\nfrom PIL import Image, ImageOps\n\n\ndef dortmund_distort(img, random_limits=(0.8, 1.1)):\n \"\"\"\n Creates an augmentation by computing a homography from three points in the\n image to three randomly generated points.\n \"\"\"\n y, x = img.shape[:2]\n src_point = np.float32([[x / 2, y / 3], [2 * x / 3, 2 * y / 3], [x / 3, 2 * y / 3]])\n random_shift = (np.random.rand(3, 2) - 0.5) * 2 * (\n random_limits[1] - random_limits[0]\n ) / 2 + np.mean(random_limits)\n dst_point = src_point * random_shift.astype(np.float32)\n transform = cv2.getAffineTransform(src_point, dst_point)\n if img.ndim == 3:\n border_value = np.median(\n np.reshape(img, (img.shape[0] * img.shape[1], -1)), axis=0\n )\n else:\n border_value = float(np.median(img))\n return cv2.warpAffine(img, transform, dsize=(x, y), borderValue=border_value)\n\n\nclass DortmundImageToTensor(object):\n def __init__(\n self, fixed_height=None, fixed_width=None, min_height=None, min_width=None\n ):\n assert fixed_height is None or fixed_height > 0\n assert fixed_width is None or fixed_width > 0\n assert min_height is None or min_height > 0\n assert min_width is None or min_width > 0\n self._fh = fixed_height\n self._fw = fixed_width\n self._mh = min_height\n self._mw = min_width\n\n def __call__(self, x):\n assert isinstance(x, Image.Image)\n x = x.convert(\"L\")\n x = ImageOps.invert(x)\n if self._fh or self._fw:\n # Optionally, resize image to a fixed size\n cw, ch = x.size\n nw = self._fw if self._fw else int(cw * self._fh / ch)\n nh = self._fh if self._fh else int(ch * self._fw / cw)\n x.resize((nw, nh), Image.BILINEAR)\n elif self._mh or self._mw:\n # Optionally, pad image to have the minimum size\n cw, ch = x.size\n nw = cw if self._mw is None or cw >= self._mw else self._mw\n nh = ch if self._mh is None or ch >= self._mh else self._mh\n if cw != nw or ch != nh:\n nx = Image.new(\"L\", (nw, nh))\n nx.paste(x, ((nw - cw) // 2, (nh - ch) // 2))\n x = nx\n\n x = np.asarray(x, dtype=np.float32)\n x = dortmund_distort(x / 255.0)\n if x.shape != 3:\n x = np.expand_dims(x, axis=-1)\n x = np.transpose(x, (2, 0, 1))\n return torch.from_numpy(x)\n\n\nif __name__ == \"__main__\":\n import matplotlib.pyplot as plt\n\n import laia.random\n from laia.data import TextImageFromTextTableDataset, ImageDataLoader\n from laia.plugins.arguments import add_argument, add_defaults, args\n\n add_defaults(\"seed\")\n add_argument(\"--num_images\", type=int, help=\"Show only this number of images\")\n add_argument(\"--shuffle\", action=\"store_true\", help=\"Shuffle the list of images\")\n add_argument(\"img_dir\", help=\"Directory containing images\")\n add_argument(\"txt_table\", help=\"Transcriptions of each image\")\n args = args()\n laia.random.manual_seed(args.seed)\n\n dataset = TextImageFromTextTableDataset(\n args.txt_table, args.img_dir, img_transform=DortmundImageToTensor()\n )\n dataset_loader = ImageDataLoader(\n dataset=dataset, image_channels=1, shuffle=args.shuffle\n )\n\n for i, batch in enumerate(dataset_loader, 1):\n if args.num_images and i > args.num_images:\n break\n # Note: batch['img'] is a PaddedTensor\n img = batch[\"img\"].data.squeeze().numpy()\n imgplt = plt.imshow(img, cmap=\"gray\")\n imgplt.axes.set_title(\" \".join(batch[\"txt\"][0]))\n plt.show()\n" ]
[ [ "matplotlib.pyplot.imshow", "numpy.expand_dims", "numpy.asarray", "numpy.reshape", "numpy.median", "torch.from_numpy", "numpy.mean", "numpy.random.rand", "numpy.float32", "numpy.transpose", "matplotlib.pyplot.show" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
zhoub/dldt
[ "e42c01cf6e1d3aefa55e2c5df91f1054daddc575", "e42c01cf6e1d3aefa55e2c5df91f1054daddc575", "e42c01cf6e1d3aefa55e2c5df91f1054daddc575", "e42c01cf6e1d3aefa55e2c5df91f1054daddc575" ]
[ "tools/accuracy_checker/accuracy_checker/representation/pose_estimation_representation.py", "model-optimizer/extensions/middle/RNNSequenceNormalizeToIE.py", "model-optimizer/extensions/front/image_scaler.py", "model-optimizer/extensions/front/image_scaler_test.py" ]
[ "\"\"\"\nCopyright (c) 2019 Intel Corporation\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nimport numpy as np\nfrom .base_representation import BaseRepresentation\n\n\nclass PoseEstimationRepresentation(BaseRepresentation):\n def __init__(self, identifier='', x_values=None, y_values=None, visibility=None, labels=None):\n super().__init__(identifier)\n self.x_values = x_values if np.size(x_values) > 0 else []\n self.y_values = y_values if np.size(y_values) > 0 else []\n self.visibility = visibility if np.size(visibility) > 0 else [2] * len(x_values)\n self.labels = labels if labels is not None else np.array([1]*len(x_values))\n\n @property\n def areas(self):\n areas = self.metadata.get('areas')\n if areas:\n return areas\n x_mins = np.min(self.x_values, axis=1)\n x_maxs = np.max(self.x_values, axis=1)\n y_mins = np.min(self.y_values, axis=1)\n y_maxs = np.max(self.y_values, axis=1)\n return (x_maxs - x_mins) * (y_maxs - y_mins)\n\n @property\n def bboxes(self):\n rects = self.metadata.get('rects')\n if rects:\n return rects\n x_mins = np.min(self.x_values, axis=1)\n x_maxs = np.max(self.x_values, axis=1)\n y_mins = np.min(self.y_values, axis=1)\n y_maxs = np.max(self.y_values, axis=1)\n return [[x_min, y_min, x_max, y_max] for x_min, y_min, x_max, y_max in zip(x_mins, y_mins, x_maxs, y_maxs)]\n\n @property\n def size(self):\n return len(self.x_values)\n\n\nclass PoseEstimationAnnotation(PoseEstimationRepresentation):\n pass\n\n\nclass PoseEstimationPrediction(PoseEstimationRepresentation):\n def __init__(self, identifier='', x_values=None, y_values=None, visibility=None, scores=None, labels=None):\n super().__init__(identifier, x_values, y_values, visibility, labels)\n self.scores = scores if scores.any() else []\n", "\"\"\"\n Copyright (c) 2019 Intel Corporation\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\"\"\"\nfrom copy import deepcopy\n\nimport numpy as np\n\nfrom mo.front.common.partial_infer.utils import int64_array\nfrom mo.graph.graph import Graph\nfrom mo.middle.replacement import MiddleReplacementPattern\nfrom mo.ops.const import Const\nfrom mo.ops.op import Op\nfrom mo.ops.reshape import Reshape\n\n\nclass RNNSequenceNormalize(MiddleReplacementPattern):\n \"\"\"\n This class normalize RNNSequence layers to IE-compatible from of weights, inputs and outputs.\n\n In this pass next will be done:\n 1. Weights repack (squeeze all useless shapes in all blobls and concatenate W and R together, also add\n bin param and all similar staff )\n 1. UNSqueeze num directions (in states and )\n 2. Initial states squeeze\n 4. Renumbering inputs\n 5. Ports checks\n\n After this normalization this layer will have next format of inputs:\n 0: X input data, shape [batch_size, seq_len, input_size]\n 1: WR weights blob, shape [M * hidden_size, hidden_size + input_size]\n 2: B biases blob, shape [M * hidden_size]\n 3: (optional) sequence_length, shape [batch_size]\n 4: initial hidden state, shape [batch_size, hidden_size]\n 5: (only for LSTM) initial cell state, shape [batch_size, hidden_size]\n 6: (optional for LSTM) Peepholes weights, shape [(M - 1) * hidden_size]\n\n \"\"\"\n def run_after(self):\n from extensions.middle.DecomposeBidirectionalRNNSequence import DecomposeBidirectionalRNNSequence\n return [DecomposeBidirectionalRNNSequence]\n\n def pattern(self):\n return dict(\n nodes=[\n ('rnn_layer', dict(kind='op', type='RNNSequence')),\n ('input', dict(kind='data')),\n ('W', dict(kind='data')),\n ('R', dict(kind='data')),\n ('B', dict(kind='data')),\n ],\n edges=[\n ('input', 'rnn_layer', {'in': 0}),\n ('W', 'rnn_layer', {'in': 1}),\n ('R', 'rnn_layer', {'in': 2}),\n ('B', 'rnn_layer', {'in': 3}),\n ],\n )\n\n def replace_pattern(self, graph: Graph, match: dict):\n self.repack_weights(graph, match)\n if match['rnn_layer'].has_num_directions:\n self.unsqueeze_num_directions(graph, match)\n self.squeeze_initial_states(graph, match)\n self.reordering_inputs(graph, match)\n # some additional checks for ports number and similar stuff\n\n def repack_weights(self, graph: Graph, match: dict):\n # Concat W, R in IE- format\n # Delete useless num_dir dimensions and n_cells dimensions in W, R, B (peepholes?)\n lstm = match['rnn_layer']\n W, R, B = match['W'].value.copy(), match['R'].value.copy(), match['B'].value.copy()\n\n graph.remove_edge(match['W'].id, lstm.id)\n graph.remove_edge(match['R'].id, lstm.id)\n graph.remove_edge(match['B'].id, lstm.id)\n\n # Sum component of B that correspond to W and R\n if lstm.op == 'GRU' and lstm.linear_before_reset:\n B_shape = np.array(B.shape)\n B_shape[3] = 4\n B_shape[2] = 1\n B_tmp = np.zeros(shape=B_shape)\n B_tmp[:, :, :, 0, :] = B[:, :, 0, 0, :] + B[:, :, 1, 0, :]\n B_tmp[:, :, :, 1, :] = B[:, :, 0, 1, :] + B[:, :, 1, 1, :]\n B_tmp[:, :, :, 2, :] = B[:, :, 0, 2, :][:, :, np.newaxis, :]\n B_tmp[:, :, :, 3, :] = B[:, :, 1, 2, :][:, :, np.newaxis, :]\n B = B_tmp\n else:\n B = np.add.reduce(B, axis=2, keepdims=True)\n\n # Concatenate W, R to IE-compatible format\n assert len(W.shape) == 5\n assert len(R.shape) == 5\n WR = np.concatenate([W, R], axis=4)\n\n # Squeeze useless dimensions\n assert WR.shape[0] == 1 # num_dir == 1\n assert WR.shape[1] == 1 # num_cells == 1\n assert B.shape[0] == 1\n assert B.shape[1] == 1\n WR = WR.squeeze(axis=(0, 1))\n B = B.squeeze(axis=(0, 1))\n\n # Flatten all output (0, 1) and input dimensions (2, 3)\n final_shape_WR = [WR.shape[0] * WR.shape[1], -1]\n assert final_shape_WR[0] == lstm.hidden_size * lstm.multiplier\n WR = WR.reshape(final_shape_WR)\n\n final_shape_B = final_shape_WR\n if lstm.op == 'GRU' and lstm.linear_before_reset:\n final_shape_B[0] = lstm.hidden_size * 4\n B = B.reshape(final_shape_B)\n\n # Squeeze fake dimension in B\n B = B.squeeze(axis=-1)\n\n for blob, port, name in [(WR, 1, 'weights'), (B, 2, 'biases')]:\n Op.create_and_connect_input_data_node(\n graph,\n lstm,\n {'value': blob, 'shape': np.array(blob.shape, dtype=np.int64)},\n {'in': port, 'bin': name, 'permutation': None}\n )\n\n @staticmethod\n def unsqueeze_num_directions(graph: Graph, match: dict):\n \"\"\" Assuming considered LSTM/GRU/RNN node should has num_directions in output shape and add Reshape\n to match it.\n \"\"\"\n\n rnn_layer = match['rnn_layer']\n # num_directions is at 1st position in output shape, and in 0st position in hidden and cell states\n # please refer to docs in this transform\n\n direction_dim = [1, 0, 0] # index of dimension with direction index\n for i in rnn_layer.out_nodes():\n old_data_node = rnn_layer.out_node(i)\n old_shape = old_data_node.shape.copy()\n new_shape = np.delete(old_shape, direction_dim[i])\n\n data = Op._create_data_node(graph, name=rnn_layer.name + '/Out/{}/'.format(i), attrs={'shape': new_shape})\n graph.remove_edge(rnn_layer.id, old_data_node.id)\n graph.add_edge(rnn_layer.id, data.id, key=0, out=i)\n\n reshape = Reshape(graph, dict(dim=old_shape))\n\n reshape_dim_data = Const(graph, {'name': rnn_layer.name + '/SqueezeNumDirections/{}/Dim'.format(i),\n 'value': old_shape}).create_node_with_data()\n reshape.create_node_with_data([data, reshape_dim_data],\n dict(name=rnn_layer.name + '/SqueezeNumDirections/{}'.format(i)),\n data_nodes=[old_data_node])\n\n @staticmethod\n def squeeze_initial_states(graph: Graph, match: dict):\n \"\"\"\n Squeeze input initial states of recurrent node to 2-D shape.\n \"\"\"\n hidden_init_port = 5\n cell_init_port = 6\n\n rnn_layer = match['rnn_layer']\n\n # Add input ports to rnn_layer\n rnn_layer.add_sequence_of_ports(type='in', rng=range(7))\n\n reshape = Reshape(graph, {})\n\n assert hidden_init_port in rnn_layer.in_nodes()\n init_h = rnn_layer.in_node(hidden_init_port)\n edge_attrs = deepcopy(graph.get_edge_data(init_h.id, rnn_layer.id)[0])\n edge_attrs['in'] = hidden_init_port\n graph.remove_edge(init_h.id, rnn_layer.id)\n\n new_dim = int64_array([rnn_layer.in_node(0).shape[rnn_layer.batch_dim], rnn_layer.hidden_size])\n reshape_dim_data = Const(graph, {'name': rnn_layer.name + '/HiddenStateResizeDim',\n 'value': new_dim}).create_node_with_data()\n new_init_h = reshape.create_node_with_data([init_h, reshape_dim_data], dict(name=rnn_layer.name + '/HiddenStateResize'))\n graph.add_edge(new_init_h.id, rnn_layer.id, **edge_attrs)\n\n if rnn_layer.op == 'LSTM':\n assert cell_init_port in rnn_layer.in_nodes()\n\n init_c = rnn_layer.in_node(cell_init_port)\n edge_attrs = deepcopy(graph.get_edge_data(init_c.id, rnn_layer.id)[0])\n edge_attrs['in'] = cell_init_port\n graph.remove_edge(init_c.id, rnn_layer.id)\n reshape_dim_data = Const(graph, {'name': rnn_layer.name + '/CellStateResizeDim',\n 'value': new_dim}).create_node_with_data()\n new_init_c = reshape.create_node_with_data([init_c, reshape_dim_data],\n dict(name=rnn_layer.name + '/CellStateResize'))\n graph.add_edge(new_init_c.id, rnn_layer.id, **edge_attrs)\n\n @staticmethod\n def reordering_inputs(graph: Graph, match: dict):\n \"\"\"\n Reorder (renumbering) inputs to described format. We need to renumber initial states ports.\n \"\"\"\n rnn_layer = match['rnn_layer']\n assert 5 in rnn_layer.in_nodes()\n hidden_state_edge = graph.get_edge_data(rnn_layer.in_node(5).id, rnn_layer.id)\n hidden_state_edge[0]['in'] = 4\n\n if rnn_layer.op == 'LSTM':\n assert 6 in rnn_layer.in_nodes()\n cell_state_edge = graph.get_edge_data(rnn_layer.in_node(6).id, rnn_layer.id)\n cell_state_edge[0]['in'] = 5\n\n @staticmethod\n def ports_checks(graph: Graph, match: dict):\n \"\"\"\n Check that all mandatory ports is present.\n \"\"\"\n rnn_layer = match['rnn_layer']\n mandatory_ports = [0, 1, 2, 4]\n\n if rnn_layer.op == 'LSTM':\n mandatory_ports.append(5)\n\n assert set(rnn_layer.in_nodes().keys()) >= set(mandatory_ports)", "\"\"\"\n Copyright (c) 2018-2019 Intel Corporation\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\nimport numpy as np\n\nfrom mo.front.common.replacement import FrontReplacementOp\nfrom mo.graph.graph import Graph\nfrom mo.ops.const import Const\nfrom extensions.ops.elementwise import Mul, Add\n\n\nclass ImageScaler(FrontReplacementOp):\n op = \"ImageScaler\"\n enabled = True\n\n def replace_sub_graph(self, graph: Graph, match: dict):\n # This replacer replace ImageScalar operation to Mul->Add sequence\n # Also it check that weights and biases are good\n op = match['op']\n\n # Check that weights and biases are not useless\n has_bias, has_weights = True, True\n if all([x == 1 for x in np.nditer(op.scale)]):\n has_weights = False\n if all([x == 0 for x in np.nditer(op.bias)]):\n has_bias = False\n\n assert len(op.in_ports()) == 1\n\n last_port = op.in_port(0).get_source()\n\n # Create Mul & Add nodes\n if has_weights:\n mul_weights = Const(graph, dict(value=op.scale, shape=op.scale.shape)).create_node()\n mul_op = Mul(graph, dict(name=op.id + '/mul_')).create_node()\n op.in_port(0).get_connection().set_destination(mul_op.in_port(0))\n mul_weights.out_port(0).connect(mul_op.in_port(1))\n last_port = mul_op.out_port(0)\n\n if has_bias:\n add_bias = Const(graph, dict(value=op.bias, shape=op.bias.shape)).create_node()\n add_op = Add(graph, dict(name=op.id + '/add_')).create_node()\n last_port.get_connection().set_destination(add_op.in_port(0))\n add_bias.out_port(0).connect(add_op.in_port(1))\n last_port = add_op.out_port(0)\n\n op.in_port(0).disconnect()\n op.out_port(0).get_connection().set_source(last_port)\n", "\"\"\"\n Copyright (c) 2018-2019 Intel Corporation\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\nimport unittest\n\nimport numpy as np\n\nfrom extensions.front.image_scaler import ImageScaler\nfrom mo.utils.unittest.graph import build_graph, compare_graphs\n\nnodes_attributes = {\n 'placeholder_1': {'shape': None, 'type': 'Parameter', 'kind': 'op', 'op': 'Parameter'},\n 'placeholder_1_data': {'value': None, 'shape': None, 'kind': 'data', 'data_type': None},\n # ImageScaler operation\n 'im_scaler': {'type': None, 'kind': 'op', 'op': 'ImageScaler'},\n 'im_scaler_data': {'value': None, 'shape': None, 'kind': 'data'},\n # Test operation\n 'last': {'type': None, 'value': None, 'kind': 'op', 'op': None},\n 'last_data': {'value': None, 'shape': None, 'kind': 'data'},\n # Mul and Add operations\n 'mul_1': {'type': None, 'value': None, 'kind': 'op', 'op': 'Mul'},\n 'const_mul_1_w': {'type': None, 'value': None, 'kind': 'op', 'op': 'Const'},\n 'mul_1_w': {'value': None, 'shape': None, 'kind': 'data'},\n 'mul_1_data': {'value': None, 'shape': None, 'kind': 'data'},\n 'add_1': {'type': None, 'value': None, 'kind': 'op', 'op': 'Add'},\n 'const_add_1_w': {'type': None, 'value': None, 'kind': 'op', 'op': 'Const'},\n 'add_1_w': {'value': None, 'shape': None, 'kind': 'data'},\n 'add_1_data': {'value': None, 'shape': None, 'kind': 'data'},\n}\n\n\nclass ImageScalerTest(unittest.TestCase):\n # Tests for MIDDLE stage\n # Graph with Mul and Add operations\n def test_image_scaler_test_1(self):\n graph = build_graph(nodes_attributes,\n [('placeholder_1', 'placeholder_1_data'),\n ('placeholder_1_data', 'im_scaler'),\n ('im_scaler', 'im_scaler_data'),\n ('im_scaler_data', 'last'),\n ],\n {'placeholder_1_data': {'shape': np.array([1, 227, 227, 3])},\n 'im_scaler': {'scale': np.array(2.0), 'bias': np.reshape(np.array([1, 2, 3]), [3, 1, 1])},\n }, nodes_with_edges_only=True)\n\n graph_ref = build_graph(nodes_attributes,\n [('placeholder_1', 'placeholder_1_data'),\n ('placeholder_1_data', 'mul_1'),\n ('const_mul_1_w', 'mul_1_w'),\n ('mul_1_w', 'mul_1'),\n ('mul_1', 'mul_1_data'),\n ('mul_1_data', 'add_1'),\n ('const_add_1_w', 'add_1_w'),\n ('add_1_w', 'add_1'),\n ('add_1', 'add_1_data'),\n ('add_1_data', 'last')\n ],\n {'placeholder_1_data': {'shape': np.array([1, 227, 227, 3])},\n 'const_mul_1_w': {'shape': np.array(2.0).shape, 'value': np.array(2.0)},\n 'const_add_1_w': {'shape': np.array([3, 1, 1]),\n 'value': np.reshape(np.array([1, 2, 3]), [3, 1, 1])},\n }, nodes_with_edges_only=True)\n\n graph.graph['layout'] = 'NCHW'\n graph.stage = 'middle'\n\n replacer = ImageScaler()\n replacer.find_and_replace_pattern(graph)\n\n (flag, resp) = compare_graphs(graph, graph_ref, 'last')\n self.assertTrue(flag, resp)\n\n # Graph with Add operation\n def test_image_scaler_test_2(self):\n graph = build_graph(nodes_attributes,\n [('placeholder_1', 'placeholder_1_data'),\n ('placeholder_1_data', 'im_scaler'),\n ('im_scaler', 'im_scaler_data'),\n ('im_scaler_data', 'last'),\n ],\n {'placeholder_1_data': {'shape': np.array([1, 227, 227, 3])},\n 'im_scaler': {'scale': np.array(1.0), 'bias': np.reshape(np.array([1, 2, 3]), [3, 1, 1])},\n }, nodes_with_edges_only=True)\n\n graph_ref = build_graph(nodes_attributes,\n [('placeholder_1', 'placeholder_1_data'),\n ('placeholder_1_data', 'add_1'),\n ('const_add_1_w', 'add_1_w'),\n ('add_1_w', 'add_1'),\n ('add_1', 'add_1_data'),\n ('add_1_data', 'last')\n ],\n {'placeholder_1_data': {'shape': np.array([1, 227, 227, 3])},\n 'const_add_1_w': {'shape': np.array([3, 1, 1]),\n 'value': np.reshape(np.array([1, 2, 3]), [3, 1, 1])},\n }, nodes_with_edges_only=True)\n\n graph.graph['layout'] = 'NCHW'\n graph.stage = 'middle'\n\n replacer = ImageScaler()\n replacer.find_and_replace_pattern(graph)\n\n (flag, resp) = compare_graphs(graph, graph_ref, 'last')\n self.assertTrue(flag, resp)\n\n # Graph with Mul operation\n def test_image_scaler_test_3(self):\n graph = build_graph(nodes_attributes,\n [('placeholder_1', 'placeholder_1_data'),\n ('placeholder_1_data', 'im_scaler'),\n ('im_scaler', 'im_scaler_data'),\n ('im_scaler_data', 'last'),\n ],\n {'placeholder_1_data': {'shape': np.array([1, 227, 227, 3])},\n 'im_scaler': {'scale': np.array(2.0), 'bias': np.reshape(np.array([0, 0, 0]), [3, 1, 1])},\n }, nodes_with_edges_only=True)\n\n graph_ref = build_graph(nodes_attributes,\n [('placeholder_1', 'placeholder_1_data'),\n ('placeholder_1_data', 'mul_1'),\n ('const_mul_1_w', 'mul_1_w'),\n ('mul_1_w', 'mul_1'),\n ('mul_1', 'mul_1_data'),\n ('mul_1_data', 'last')\n ],\n {'placeholder_1_data': {'shape': np.array([1, 227, 227, 3])},\n 'const_mul_1_w': {'shape': np.array(2.0).shape, 'value': np.array(2.0)},\n }, nodes_with_edges_only=True)\n\n graph.graph['layout'] = 'NCHW'\n graph.stage = 'middle'\n\n replacer = ImageScaler()\n replacer.find_and_replace_pattern(graph)\n\n (flag, resp) = compare_graphs(graph, graph_ref, 'last')\n self.assertTrue(flag, resp)\n\n # Graph without Mul and Add operations\n def test_image_scaler_test_4(self):\n graph = build_graph(nodes_attributes,\n [('placeholder_1', 'placeholder_1_data'),\n ('placeholder_1_data', 'im_scaler'),\n ('im_scaler', 'im_scaler_data'),\n ('im_scaler_data', 'last'),\n ],\n {'placeholder_1_data': {'shape': np.array([1, 227, 227, 3])},\n 'im_scaler_data': {'shape': np.array([1, 227, 227, 3])},\n 'im_scaler': {'scale': np.array(1.0), 'bias': np.reshape(np.array([0, 0, 0]), [3, 1, 1])},\n }, nodes_with_edges_only=True)\n\n graph_ref = build_graph(nodes_attributes,\n [('placeholder_1', 'placeholder_1_data'),\n ('placeholder_1_data', 'last')\n ],\n {'placeholder_1_data': {'shape': np.array([1, 227, 227, 3])},\n }, nodes_with_edges_only=True)\n\n graph.graph['layout'] = 'NCHW'\n graph.stage = 'middle'\n\n replacer = ImageScaler()\n replacer.find_and_replace_pattern(graph)\n\n (flag, resp) = compare_graphs(graph, graph_ref, 'last')\n self.assertTrue(flag, resp)\n\n # Tests for FRONT stage\n # Graph with Mul and Add operations\n def test_image_scaler_test_5(self):\n graph = build_graph(nodes_attributes,\n [('placeholder_1', 'im_scaler'),\n ('im_scaler', 'last'),\n ],\n {'placeholder_1': {'shape': np.array([1, 227, 227, 3])},\n 'im_scaler': {'scale': np.array(2.0), 'bias': np.reshape(np.array([1, 2, 3]), [3, 1, 1])},\n }, nodes_with_edges_only=True)\n\n graph_ref = build_graph(nodes_attributes,\n [('placeholder_1', 'mul_1'),\n ('const_mul_1_w', 'mul_1'),\n ('mul_1', 'add_1'),\n ('const_add_1_w', 'add_1'),\n ('add_1', 'last')\n ],\n {'placeholder_1': {'shape': np.array([1, 227, 227, 3])},\n 'const_mul_1_w': {'shape': np.array(2.0).shape, 'value': np.array(2.0)},\n 'const_add_1_w': {'shape': np.array([3, 1, 1]),\n 'value': np.reshape(np.array([1, 2, 3]), [3, 1, 1])},\n }, nodes_with_edges_only=True)\n\n graph.graph['layout'] = 'NCHW'\n graph.stage = 'front'\n\n replacer = ImageScaler()\n replacer.find_and_replace_pattern(graph)\n\n (flag, resp) = compare_graphs(graph, graph_ref, 'last')\n self.assertTrue(flag, resp)\n\n # Graph with Add operation\n def test_image_scaler_test_6(self):\n graph = build_graph(nodes_attributes,\n [('placeholder_1', 'im_scaler'),\n ('im_scaler', 'last'),\n ],\n {'placeholder_1': {'shape': np.array([1, 227, 227, 3])},\n 'im_scaler': {'scale': np.array(1.0), 'bias': np.reshape(np.array([1, 2, 3]), [3, 1, 1])},\n }, nodes_with_edges_only=True)\n\n graph_ref = build_graph(nodes_attributes,\n [('placeholder_1', 'add_1'),\n ('const_add_1_w', 'add_1'),\n ('add_1', 'last')\n ],\n {'placeholder_1': {'shape': np.array([1, 227, 227, 3])},\n 'const_add_1_w': {'shape': np.array([3, 1, 1]),\n 'value': np.reshape(np.array([1, 2, 3]), [3, 1, 1])},\n }, nodes_with_edges_only=True)\n\n graph.graph['layout'] = 'NCHW'\n graph.stage = 'front'\n\n replacer = ImageScaler()\n replacer.find_and_replace_pattern(graph)\n\n (flag, resp) = compare_graphs(graph, graph_ref, 'last')\n self.assertTrue(flag, resp)\n\n # Graph with Mul operation\n def test_image_scaler_test_7(self):\n graph = build_graph(nodes_attributes,\n [('placeholder_1', 'im_scaler'),\n ('im_scaler', 'last'),\n ],\n {'placeholder_1': {'shape': np.array([1, 227, 227, 3])},\n 'im_scaler': {'scale': np.array(2.0), 'bias': np.reshape(np.array([0, 0, 0]), [3, 1, 1])},\n }, nodes_with_edges_only=True)\n\n graph_ref = build_graph(nodes_attributes,\n [('placeholder_1', 'mul_1'),\n ('const_mul_1_w', 'mul_1'),\n ('mul_1', 'last')\n ],\n {'placeholder_1': {'shape': np.array([1, 227, 227, 3])},\n 'const_mul_1_w': {'shape': np.array(2.0).shape, 'value': np.array(2.0)},\n }, nodes_with_edges_only=True)\n\n graph.graph['layout'] = 'NCHW'\n graph.stage = 'front'\n\n replacer = ImageScaler()\n replacer.find_and_replace_pattern(graph)\n\n (flag, resp) = compare_graphs(graph, graph_ref, 'last')\n self.assertTrue(flag, resp)\n\n # Graph without Mul and Add operations\n def test_image_scaler_test_8(self):\n graph = build_graph(nodes_attributes,\n [('placeholder_1', 'im_scaler'),\n ('im_scaler', 'last'),\n ],\n {'placeholder_1': {'shape': np.array([1, 227, 227, 3])},\n 'im_scaler': {'scale': np.array(1.0), 'bias': np.reshape(np.array([0, 0, 0]), [3, 1, 1])},\n }, nodes_with_edges_only=True)\n\n graph_ref = build_graph(nodes_attributes,\n [('placeholder_1', 'last')\n ],\n {'placeholder_1': {'shape': np.array([1, 227, 227, 3])},\n }, nodes_with_edges_only=True)\n\n graph.graph['layout'] = 'NCHW'\n graph.stage = 'front'\n\n replacer = ImageScaler()\n replacer.find_and_replace_pattern(graph)\n\n (flag, resp) = compare_graphs(graph, graph_ref, 'last')\n self.assertTrue(flag, resp)\n" ]
[ [ "numpy.max", "numpy.size", "numpy.min" ], [ "numpy.add.reduce", "numpy.concatenate", "numpy.delete", "numpy.array", "numpy.zeros" ], [ "numpy.nditer" ], [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
hmaarrfk/vispy
[ "7f3f6f60c8462bb8a3a8fa03344a2e6990b86eb2", "7f3f6f60c8462bb8a3a8fa03344a2e6990b86eb2", "7f3f6f60c8462bb8a3a8fa03344a2e6990b86eb2", "7f3f6f60c8462bb8a3a8fa03344a2e6990b86eb2", "7f3f6f60c8462bb8a3a8fa03344a2e6990b86eb2", "7f3f6f60c8462bb8a3a8fa03344a2e6990b86eb2", "7f3f6f60c8462bb8a3a8fa03344a2e6990b86eb2", "7f3f6f60c8462bb8a3a8fa03344a2e6990b86eb2" ]
[ "examples/basics/scene/surface_plot.py", "examples/basics/visuals/tube.py", "examples/demo/scene/scrolling_plots.py", "vispy/gloo/texture.py", "examples/benchmark/scene_test_2.py", "vispy/scene/widgets/axis.py", "vispy/visuals/shaders/function.py", "examples/basics/visuals/arcball.py" ]
[ "# -*- coding: utf-8 -*-\n# vispy: gallery 30\n# -----------------------------------------------------------------------------\n# Copyright (c) Vispy Development Team. All Rights Reserved.\n# Distributed under the (new) BSD License. See LICENSE.txt for more info.\n# -----------------------------------------------------------------------------\n\"\"\"\nThis example demonstrates the use of the SurfacePlot visual.\n\"\"\"\n\nimport sys\nimport numpy as np\n\nfrom vispy import app, scene\nfrom vispy.util.filter import gaussian_filter\n\n\ncanvas = scene.SceneCanvas(keys='interactive', bgcolor='w')\nview = canvas.central_widget.add_view()\nview.camera = scene.TurntableCamera(up='z', fov=60)\n\n# Simple surface plot example\n# x, y values are not specified, so assumed to be 0:50\nz = np.random.normal(size=(250, 250), scale=200)\nz[100, 100] += 50000\nz = gaussian_filter(z, (10, 10))\np1 = scene.visuals.SurfacePlot(z=z, color=(0.3, 0.3, 1, 1))\np1.transform = scene.transforms.MatrixTransform()\np1.transform.scale([1/249., 1/249., 1/249.])\np1.transform.translate([-0.5, -0.5, 0])\n\nview.add(p1)\n\n# p1._update_data() # cheating.\n# cf = scene.filters.ZColormapFilter('fire', zrange=(z.max(), z.min()))\n# p1.attach(cf)\n\n\nxax = scene.Axis(pos=[[-0.5, -0.5], [0.5, -0.5]], tick_direction=(0, -1),\n font_size=16, axis_color='k', tick_color='k', text_color='k',\n parent=view.scene)\nxax.transform = scene.STTransform(translate=(0, 0, -0.2))\n\nyax = scene.Axis(pos=[[-0.5, -0.5], [-0.5, 0.5]], tick_direction=(-1, 0),\n font_size=16, axis_color='k', tick_color='k', text_color='k',\n parent=view.scene)\nyax.transform = scene.STTransform(translate=(0, 0, -0.2))\n\n# Add a 3D axis to keep us oriented\naxis = scene.visuals.XYZAxis(parent=view.scene)\n\nif __name__ == '__main__':\n canvas.show()\n if sys.flags.interactive == 0:\n app.run()\n", "\"\"\"\nDemonstration of Tube\n\"\"\"\n\nimport sys\nfrom vispy import scene\nfrom vispy.geometry.torusknot import TorusKnot\n\nfrom colorsys import hsv_to_rgb\nimport numpy as np\n\ncanvas = scene.SceneCanvas(keys='interactive')\nview = canvas.central_widget.add_view()\n\npoints1 = TorusKnot(5, 3).first_component[:-1]\npoints1[:, 0] -= 20.\npoints1[:, 2] -= 15.\n\npoints2 = points1.copy()\npoints2[:, 2] += 30.\n\npoints3 = points1.copy()\npoints3[:, 0] += 41.\npoints3[:, 2] += 30\n\npoints4 = points1.copy()\npoints4[:, 0] += 41.\n\npoints5 = points1.copy()\npoints5[:, 0] += 20.4\npoints5[:, 2] += 15\n\ncolors = np.linspace(0, 1, len(points1))\ncolors = np.array([hsv_to_rgb(c, 1, 1) for c in colors])\n\nvertex_colors = np.random.random(8 * len(points1))\nvertex_colors = np.array([hsv_to_rgb(c, 1, 1) for c in vertex_colors])\n\nl1 = scene.visuals.Tube(points1,\n shading='flat',\n color=colors, # this is overridden by\n # the vertex_colors argument\n vertex_colors=vertex_colors,\n tube_points=8)\n\nl2 = scene.visuals.Tube(points2,\n color=['red', 'green', 'blue'],\n shading='smooth',\n tube_points=8)\n\nl3 = scene.visuals.Tube(points3,\n color=colors,\n shading='flat',\n tube_points=8,\n closed=True)\n\nl4 = scene.visuals.Tube(points4,\n color=colors,\n shading='flat',\n tube_points=8,\n mode='lines')\n\n# generate sine wave radii\nradii = np.sin(2 * np.pi * 440 * np.arange(points5.shape[0]) / 44000)\nradii = (radii + 1.5) / 2\n\nl5 = scene.visuals.Tube(points5,\n radius=radii,\n color='white',\n shading='smooth',\n closed=True,\n tube_points=8)\n\nview.add(l1)\nview.add(l2)\nview.add(l3)\nview.add(l4)\nview.add(l5)\nview.camera = scene.TurntableCamera()\n# tube does not expose its limits yet\nview.camera.set_range((-20, 20), (-20, 20), (-20, 20))\ncanvas.show()\n\nif __name__ == '__main__':\n if sys.flags.interactive != 1:\n canvas.app.run()\n", "# -*- coding: utf-8 -*-\n# Copyright (c) Vispy Development Team. All Rights Reserved.\n# Distributed under the (new) BSD License. See LICENSE.txt for more info.\n# vispy: gallery 30\n\"\"\"\nShow 10,000 realtime scrolling plots\n\"\"\"\nfrom vispy import app, scene\nimport numpy as np\n\n\ncanvas = scene.SceneCanvas(keys='interactive', show=True, size=(1024, 768))\ngrid = canvas.central_widget.add_grid()\nview = grid.add_view(0, 1)\nview.camera = scene.MagnifyCamera(mag=1, size_factor=0.5, radius_ratio=0.6)\n\n# Add axes\nyax = scene.AxisWidget(orientation='left')\nyax.stretch = (0.05, 1)\ngrid.add_widget(yax, 0, 0)\nyax.link_view(view)\n\nxax = scene.AxisWidget(orientation='bottom')\nxax.stretch = (1, 0.05)\ngrid.add_widget(xax, 1, 1)\nxax.link_view(view)\n\n\nN = 4900\nM = 2000\ncols = int(N**0.5)\nview.camera.rect = (0, 0, cols, N/cols)\n\nlines = scene.ScrollingLines(n_lines=N, line_size=M, columns=cols, dx=0.8/M,\n cell_size=(1, 8), parent=view.scene)\nlines.transform = scene.STTransform(scale=(1, 1/8.))\n\n\ndef update(ev):\n m = 50\n data = np.random.normal(size=(N, m), scale=0.3)\n data[data > 1] += 4\n lines.roll_data(data)\n\ntimer = app.Timer(connect=update, interval=0)\ntimer.start()\n\n\nif __name__ == '__main__':\n import sys\n if sys.flags.interactive != 1:\n app.run()\n", "# -*- coding: utf-8 -*-\n# -----------------------------------------------------------------------------\n# Copyright (c) Vispy Development Team. All Rights Reserved.\n# Distributed under the (new) BSD License. See LICENSE.txt for more info.\n# -----------------------------------------------------------------------------\n\nimport math\n\nimport numpy as np\nimport warnings\n\nfrom .globject import GLObject\nfrom .util import check_enum\n\n\n# ----------------------------------------------------------- Texture class ---\nclass BaseTexture(GLObject):\n \"\"\"\n A Texture is used to represent a topological set of scalar values.\n\n Parameters\n ----------\n data : ndarray | tuple | None\n Texture data in the form of a numpy array (or something that\n can be turned into one). A tuple with the shape of the texture\n can also be given.\n format : str | enum | None\n The format of the texture: 'luminance', 'alpha',\n 'luminance_alpha', 'rgb', or 'rgba'. If not given the format\n is chosen automatically based on the number of channels.\n When the data has one channel, 'luminance' is assumed.\n resizable : bool\n Indicates whether texture can be resized. Default True.\n interpolation : str | None\n Interpolation mode, must be one of: 'nearest', 'linear'.\n Default 'nearest'.\n wrapping : str | None\n Wrapping mode, must be one of: 'repeat', 'clamp_to_edge',\n 'mirrored_repeat'. Default 'clamp_to_edge'.\n shape : tuple | None\n Optional. A tuple with the shape of the texture. If ``data``\n is also a tuple, it will override the value of ``shape``.\n internalformat : str | None\n Internal format to use.\n resizeable : None\n Deprecated version of `resizable`.\n \"\"\"\n _ndim = 2\n\n _formats = {\n 1: 'luminance', # or alpha, or red\n 2: 'luminance_alpha', # or rg\n 3: 'rgb',\n 4: 'rgba'\n }\n\n _inv_formats = {\n 'luminance': 1,\n 'alpha': 1,\n 'red': 1,\n 'luminance_alpha': 2,\n 'rg': 2,\n 'rgb': 3,\n 'rgba': 4\n }\n\n _inv_internalformats = dict([\n (base + suffix, channels)\n for base, channels in [('r', 1), ('rg', 2), ('rgb', 3), ('rgba', 4)]\n for suffix in ['8', '16', '16f', '32f']\n ] + [\n ('luminance', 1),\n ('alpha', 1),\n ('red', 1),\n ('luminance_alpha', 2),\n ('rg', 2),\n ('rgb', 3),\n ('rgba', 4)\n ])\n\n def __init__(self, data=None, format=None, resizable=True,\n interpolation=None, wrapping=None, shape=None,\n internalformat=None, resizeable=None):\n GLObject.__init__(self)\n if resizeable is not None:\n resizable = resizeable\n warnings.warn('resizeable has been deprecated in favor of '\n 'resizable and will be removed next release',\n DeprecationWarning)\n\n # Init shape and format\n self._resizable = True # at least while we're in init\n self._shape = tuple([0 for i in range(self._ndim+1)])\n self._format = format\n self._internalformat = internalformat\n\n # Set texture parameters (before setting data)\n self.interpolation = interpolation or 'nearest'\n self.wrapping = wrapping or 'clamp_to_edge'\n\n # Set data or shape (shape arg is for backward compat)\n if isinstance(data, tuple):\n shape, data = data, None\n if data is not None:\n if shape is not None:\n raise ValueError('Texture needs data or shape, not both.')\n data = np.array(data, copy=False)\n # So we can test the combination\n self._resize(data.shape, format, internalformat)\n self._set_data(data)\n elif shape is not None:\n self._resize(shape, format, internalformat)\n else:\n raise ValueError(\"Either data or shape must be given\")\n\n # Set resizable (at end of init)\n self._resizable = bool(resizable)\n\n def _normalize_shape(self, data_or_shape):\n # Get data and shape from input\n if isinstance(data_or_shape, np.ndarray):\n data = data_or_shape\n shape = data.shape\n else:\n assert isinstance(data_or_shape, tuple)\n data = None\n shape = data_or_shape\n # Check and correct\n if shape:\n if len(shape) < self._ndim:\n raise ValueError(\"Too few dimensions for texture\")\n elif len(shape) > self._ndim + 1:\n raise ValueError(\"Too many dimensions for texture\")\n elif len(shape) == self._ndim:\n shape = shape + (1,)\n else: # if len(shape) == self._ndim + 1:\n if shape[-1] > 4:\n raise ValueError(\"Too many channels for texture\")\n # Return\n return data.reshape(shape) if data is not None else shape\n\n @property\n def shape(self):\n \"\"\" Data shape (last dimension indicates number of color channels)\n \"\"\"\n return self._shape\n\n @property\n def format(self):\n \"\"\" The texture format (color channels).\n \"\"\"\n return self._format\n\n @property\n def wrapping(self):\n \"\"\" Texture wrapping mode \"\"\"\n value = self._wrapping\n return value[0] if all([v == value[0] for v in value]) else value\n\n @wrapping.setter\n def wrapping(self, value):\n # Convert\n if isinstance(value, int) or isinstance(value, str):\n value = (value,) * self._ndim\n elif isinstance(value, (tuple, list)):\n if len(value) != self._ndim:\n raise ValueError('Texture wrapping needs 1 or %i values' %\n self._ndim)\n else:\n raise ValueError('Invalid value for wrapping: %r' % value)\n # Check and set\n valid = 'repeat', 'clamp_to_edge', 'mirrored_repeat'\n value = tuple([check_enum(value[i], 'tex wrapping', valid)\n for i in range(self._ndim)])\n self._wrapping = value\n self._glir.command('WRAPPING', self._id, value)\n\n @property\n def interpolation(self):\n \"\"\" Texture interpolation for minification and magnification. \"\"\"\n value = self._interpolation\n return value[0] if value[0] == value[1] else value\n\n @interpolation.setter\n def interpolation(self, value):\n # Convert\n if isinstance(value, int) or isinstance(value, str):\n value = (value,) * 2\n elif isinstance(value, (tuple, list)):\n if len(value) != 2:\n raise ValueError('Texture interpolation needs 1 or 2 values')\n else:\n raise ValueError('Invalid value for interpolation: %r' % value)\n # Check and set\n valid = 'nearest', 'linear'\n value = (check_enum(value[0], 'tex interpolation', valid),\n check_enum(value[1], 'tex interpolation', valid))\n self._interpolation = value\n self._glir.command('INTERPOLATION', self._id, *value)\n\n def resize(self, shape, format=None, internalformat=None):\n \"\"\"Set the texture size and format\n\n Parameters\n ----------\n shape : tuple of integers\n New texture shape in zyx order. Optionally, an extra dimention\n may be specified to indicate the number of color channels.\n format : str | enum | None\n The format of the texture: 'luminance', 'alpha',\n 'luminance_alpha', 'rgb', or 'rgba'. If not given the format\n is chosen automatically based on the number of channels.\n When the data has one channel, 'luminance' is assumed.\n internalformat : str | enum | None\n The internal (storage) format of the texture: 'luminance',\n 'alpha', 'r8', 'r16', 'r16f', 'r32f'; 'luminance_alpha',\n 'rg8', 'rg16', 'rg16f', 'rg32f'; 'rgb', 'rgb8', 'rgb16',\n 'rgb16f', 'rgb32f'; 'rgba', 'rgba8', 'rgba16', 'rgba16f',\n 'rgba32f'. If None, the internalformat is chosen\n automatically based on the number of channels. This is a\n hint which may be ignored by the OpenGL implementation.\n \"\"\"\n return self._resize(shape, format, internalformat)\n\n def _resize(self, shape, format=None, internalformat=None):\n \"\"\"Internal method for resize.\n \"\"\"\n shape = self._normalize_shape(shape)\n\n # Check\n if not self._resizable:\n raise RuntimeError(\"Texture is not resizable\")\n\n # Determine format\n if format is None:\n format = self._formats[shape[-1]]\n # Keep current format if channels match\n if self._format and \\\n self._inv_formats[self._format] == self._inv_formats[format]:\n format = self._format\n else:\n format = check_enum(format)\n\n if internalformat is None:\n # Keep current internalformat if channels match\n if self._internalformat and \\\n self._inv_internalformats[self._internalformat] == shape[-1]:\n internalformat = self._internalformat\n else:\n\n internalformat = check_enum(internalformat)\n\n # Check\n if format not in self._inv_formats:\n raise ValueError('Invalid texture format: %r.' % format)\n elif shape[-1] != self._inv_formats[format]:\n raise ValueError('Format does not match with given shape. '\n '(format expects %d elements, data has %d)' %\n (self._inv_formats[format], shape[-1]))\n\n if internalformat is None:\n pass\n elif internalformat not in self._inv_internalformats:\n raise ValueError(\n 'Invalid texture internalformat: %r. Allowed formats: %r'\n % (internalformat, self._inv_internalformats)\n )\n elif shape[-1] != self._inv_internalformats[internalformat]:\n raise ValueError('Internalformat does not match with given shape.')\n\n # Store and send GLIR command\n self._shape = shape\n self._format = format\n self._internalformat = internalformat\n self._glir.command('SIZE', self._id, self._shape, self._format,\n self._internalformat)\n\n def set_data(self, data, offset=None, copy=False):\n \"\"\"Set texture data\n\n Parameters\n ----------\n data : ndarray\n Data to be uploaded\n offset: int | tuple of ints\n Offset in texture where to start copying data\n copy: bool\n Since the operation is deferred, data may change before\n data is actually uploaded to GPU memory. Asking explicitly\n for a copy will prevent this behavior.\n\n Notes\n -----\n This operation implicitly resizes the texture to the shape of\n the data if given offset is None.\n \"\"\"\n return self._set_data(data, offset, copy)\n\n def _set_data(self, data, offset=None, copy=False):\n \"\"\"Internal method for set_data.\n \"\"\"\n\n # Copy if needed, check/normalize shape\n data = np.array(data, copy=copy)\n data = self._normalize_shape(data)\n\n # Maybe resize to purge DATA commands?\n if offset is None:\n self._resize(data.shape)\n elif all([i == 0 for i in offset]) and data.shape == self._shape:\n self._resize(data.shape)\n\n # Convert offset to something usable\n offset = offset or tuple([0 for i in range(self._ndim)])\n assert len(offset) == self._ndim\n\n # Check if data fits\n for i in range(len(data.shape)-1):\n if offset[i] + data.shape[i] > self._shape[i]:\n raise ValueError(\"Data is too large\")\n\n # Send GLIR command\n self._glir.command('DATA', self._id, offset, data)\n\n def __setitem__(self, key, data):\n \"\"\" x.__getitem__(y) <==> x[y] \"\"\"\n\n # Make sure key is a tuple\n if isinstance(key, (int, slice)) or key == Ellipsis:\n key = (key,)\n\n # Default is to access the whole texture\n shape = self._shape\n slices = [slice(0, shape[i]) for i in range(len(shape))]\n\n # Check last key/Ellipsis to decide on the order\n keys = key[::+1]\n dims = range(0, len(key))\n if key[0] == Ellipsis:\n keys = key[::-1]\n dims = range(len(self._shape) - 1,\n len(self._shape) - 1 - len(keys), -1)\n\n # Find exact range for each key\n for k, dim in zip(keys, dims):\n size = self._shape[dim]\n if isinstance(k, int):\n if k < 0:\n k += size\n if k < 0 or k > size:\n raise IndexError(\"Texture assignment index out of range\")\n start, stop = k, k + 1\n slices[dim] = slice(start, stop, 1)\n elif isinstance(k, slice):\n start, stop, step = k.indices(size)\n if step != 1:\n raise IndexError(\"Cannot access non-contiguous data\")\n if stop < start:\n start, stop = stop, start\n slices[dim] = slice(start, stop, step)\n elif k == Ellipsis:\n pass\n else:\n raise TypeError(\"Texture indices must be integers\")\n\n offset = tuple([s.start for s in slices])[:self._ndim]\n shape = tuple([s.stop - s.start for s in slices])\n size = np.prod(shape) if len(shape) > 0 else 1\n\n # Make sure data is an array\n if not isinstance(data, np.ndarray):\n data = np.array(data, copy=False)\n # Make sure data is big enough\n if data.shape != shape:\n data = np.resize(data, shape)\n\n # Set data (deferred)\n self._set_data(data=data, offset=offset, copy=False)\n\n def __repr__(self):\n return \"<%s shape=%r format=%r at 0x%x>\" % (\n self.__class__.__name__, self._shape, self._format, id(self))\n\n\n# --------------------------------------------------------- Texture1D class ---\nclass Texture1D(BaseTexture):\n \"\"\" One dimensional texture\n\n Parameters\n ----------\n data : ndarray | tuple | None\n Texture data in the form of a numpy array (or something that\n can be turned into one). A tuple with the shape of the texture\n can also be given.\n format : str | enum | None\n The format of the texture: 'luminance', 'alpha',\n 'luminance_alpha', 'rgb', or 'rgba'. If not given the format\n is chosen automatically based on the number of channels.\n When the data has one channel, 'luminance' is assumed.\n resizable : bool\n Indicates whether texture can be resized. Default True.\n interpolation : str | None\n Interpolation mode, must be one of: 'nearest', 'linear'.\n Default 'nearest'.\n wrapping : str | None\n Wrapping mode, must be one of: 'repeat', 'clamp_to_edge',\n 'mirrored_repeat'. Default 'clamp_to_edge'.\n shape : tuple | None\n Optional. A tuple with the shape of the texture. If ``data``\n is also a tuple, it will override the value of ``shape``.\n internalformat : str | None\n Internal format to use.\n resizeable : None\n Deprecated version of `resizable`.\n \"\"\"\n _ndim = 1\n _GLIR_TYPE = 'Texture1D'\n\n def __init__(self, data=None, format=None, resizable=True,\n interpolation=None, wrapping=None, shape=None,\n internalformat=None, resizeable=None):\n BaseTexture.__init__(self, data, format, resizable, interpolation,\n wrapping, shape, internalformat, resizeable)\n\n @property\n def width(self):\n \"\"\" Texture width \"\"\"\n return self._shape[0]\n\n @property\n def glsl_type(self):\n \"\"\" GLSL declaration strings required for a variable to hold this data.\n \"\"\"\n return 'uniform', 'sampler1D'\n\n @property\n def glsl_sampler_type(self):\n \"\"\" GLSL type of the sampler.\n \"\"\"\n return 'sampler1D'\n\n @property\n def glsl_sample(self):\n \"\"\" GLSL function that samples the texture.\n \"\"\"\n return 'texture1D'\n\n\n# --------------------------------------------------------- Texture2D class ---\nclass Texture2D(BaseTexture):\n \"\"\" Two dimensional texture\n\n Parameters\n ----------\n data : ndarray\n Texture data shaped as W, or a tuple with the shape for\n the texture (W).\n format : str | enum | None\n The format of the texture: 'luminance', 'alpha',\n 'luminance_alpha', 'rgb', or 'rgba'. If not given the format\n is chosen automatically based on the number of channels.\n When the data has one channel, 'luminance' is assumed.\n resizable : bool\n Indicates whether texture can be resized. Default True.\n interpolation : str\n Interpolation mode, must be one of: 'nearest', 'linear'.\n Default 'nearest'.\n wrapping : str\n Wrapping mode, must be one of: 'repeat', 'clamp_to_edge',\n 'mirrored_repeat'. Default 'clamp_to_edge'.\n shape : tuple\n Optional. A tuple with the shape HxW. If ``data``\n is also a tuple, it will override the value of ``shape``.\n internalformat : str | None\n Internal format to use.\n resizeable : None\n Deprecated version of `resizable`.\n \"\"\"\n _ndim = 2\n _GLIR_TYPE = 'Texture2D'\n\n def __init__(self, data=None, format=None, resizable=True,\n interpolation=None, wrapping=None, shape=None,\n internalformat=None, resizeable=None):\n BaseTexture.__init__(self, data, format, resizable, interpolation,\n wrapping, shape, internalformat, resizeable)\n\n @property\n def height(self):\n \"\"\" Texture height \"\"\"\n return self._shape[0]\n\n @property\n def width(self):\n \"\"\" Texture width \"\"\"\n return self._shape[1]\n\n @property\n def glsl_type(self):\n \"\"\" GLSL declaration strings required for a variable to hold this data.\n \"\"\"\n return 'uniform', 'sampler2D'\n\n @property\n def glsl_sampler_type(self):\n \"\"\" GLSL type of the sampler.\n \"\"\"\n return 'sampler2D'\n\n @property\n def glsl_sample(self):\n \"\"\" GLSL function that samples the texture.\n \"\"\"\n return 'texture2D'\n\n\n# --------------------------------------------------------- Texture3D class ---\nclass Texture3D(BaseTexture):\n \"\"\" Three dimensional texture\n\n Parameters\n ----------\n data : ndarray | tuple | None\n Texture data in the form of a numpy array (or something that\n can be turned into one). A tuple with the shape of the texture\n can also be given.\n format : str | enum | None\n The format of the texture: 'luminance', 'alpha',\n 'luminance_alpha', 'rgb', or 'rgba'. If not given the format\n is chosen automatically based on the number of channels.\n When the data has one channel, 'luminance' is assumed.\n resizable : bool\n Indicates whether texture can be resized. Default True.\n interpolation : str | None\n Interpolation mode, must be one of: 'nearest', 'linear'.\n Default 'nearest'.\n wrapping : str | None\n Wrapping mode, must be one of: 'repeat', 'clamp_to_edge',\n 'mirrored_repeat'. Default 'clamp_to_edge'.\n shape : tuple | None\n Optional. A tuple with the shape of the texture. If ``data``\n is also a tuple, it will override the value of ``shape``.\n internalformat : str | None\n Internal format to use.\n resizeable : None\n Deprecated version of `resizable`.\n \"\"\"\n _ndim = 3\n _GLIR_TYPE = 'Texture3D'\n\n def __init__(self, data=None, format=None, resizable=True,\n interpolation=None, wrapping=None, shape=None,\n internalformat=None, resizeable=None):\n BaseTexture.__init__(self, data, format, resizable, interpolation,\n wrapping, shape, internalformat, resizeable)\n\n @property\n def width(self):\n \"\"\" Texture width \"\"\"\n return self._shape[2]\n\n @property\n def height(self):\n \"\"\" Texture height \"\"\"\n return self._shape[1]\n\n @property\n def depth(self):\n \"\"\" Texture depth \"\"\"\n return self._shape[0]\n\n @property\n def glsl_type(self):\n \"\"\" GLSL declaration strings required for a variable to hold this data.\n \"\"\"\n return 'uniform', 'sampler3D'\n\n @property\n def glsl_sampler_type(self):\n \"\"\" GLSL type of the sampler.\n \"\"\"\n return 'sampler3D'\n\n @property\n def glsl_sample(self):\n \"\"\" GLSL function that samples the texture.\n \"\"\"\n return 'texture3D'\n\n\n# --------------------------------------------------------- TextureCube class ---\nclass TextureCube(BaseTexture):\n \"\"\" Texture Cube\n\n Parameters\n ----------\n data : ndarray | tuple | None\n Texture data in the form of a numpy array (or something that\n can be turned into one). A tuple with the shape of the texture\n can also be given.\n format : str | enum | None\n The format of the texture: 'luminance', 'alpha',\n 'luminance_alpha', 'rgb', or 'rgba'. If not given the format\n is chosen automatically based on the number of channels.\n When the data has one channel, 'luminance' is assumed.\n resizable : bool\n Indicates whether texture can be resized. Default True.\n interpolation : str | None\n Interpolation mode, must be one of: 'nearest', 'linear'.\n Default 'nearest'.\n wrapping : str | None\n Wrapping mode, must be one of: 'repeat', 'clamp_to_edge',\n 'mirrored_repeat'. Default 'clamp_to_edge'.\n shape : tuple | None\n Optional. A tuple with the shape of the texture. If ``data``\n is also a tuple, it will override the value of ``shape``.\n internalformat : str | None\n Internal format to use.\n resizeable : None\n Deprecated version of `resizable`.\n \"\"\"\n _ndim = 3\n _GLIR_TYPE = 'TextureCube'\n\n def __init__(self, data=None, format=None, resizable=True,\n interpolation=None, wrapping=None, shape=None,\n internalformat=None, resizeable=None):\n BaseTexture.__init__(self, data, format, resizable, interpolation,\n wrapping, shape, internalformat, resizeable)\n if self._shape[0] != 6:\n raise ValueError(\"Texture cube require arrays first dimension to be 6 :\"\n \" {} was given.\".format(self._shape[0]))\n\n @property\n def height(self):\n \"\"\" Texture height \"\"\"\n return self._shape[1]\n\n @property\n def width(self):\n \"\"\" Texture width \"\"\"\n return self._shape[2]\n\n @property\n def depth(self):\n \"\"\" Texture depth \"\"\"\n return self._shape[0]\n\n @property\n def glsl_type(self):\n \"\"\" GLSL declaration strings required for a variable to hold this data.\n \"\"\"\n return 'uniform', 'samplerCube'\n\n @property\n def glsl_sampler_type(self):\n \"\"\" GLSL type of the sampler.\n \"\"\"\n return 'samplerCube'\n\n @property\n def glsl_sample(self):\n \"\"\" GLSL function that samples the texture.\n \"\"\"\n return 'textureCube'\n\n\n# ------------------------------------------------- TextureEmulated3D class ---\nclass TextureEmulated3D(Texture2D):\n \"\"\" Two dimensional texture that is emulating a three dimensional texture\n\n Parameters\n ----------\n data : ndarray | tuple | None\n Texture data in the form of a numpy array (or something that\n can be turned into one). A tuple with the shape of the texture\n can also be given.\n format : str | enum | None\n The format of the texture: 'luminance', 'alpha',\n 'luminance_alpha', 'rgb', or 'rgba'. If not given the format\n is chosen automatically based on the number of channels.\n When the data has one channel, 'luminance' is assumed.\n resizable : bool\n Indicates whether texture can be resized. Default True.\n interpolation : str | None\n Interpolation mode, must be one of: 'nearest', 'linear'.\n Default 'nearest'.\n wrapping : str | None\n Wrapping mode, must be one of: 'repeat', 'clamp_to_edge',\n 'mirrored_repeat'. Default 'clamp_to_edge'.\n shape : tuple | None\n Optional. A tuple with the shape of the texture. If ``data``\n is also a tuple, it will override the value of ``shape``.\n internalformat : str | None\n Internal format to use.\n resizeable : None\n Deprecated version of `resizable`.\n \"\"\"\n\n # TODO: does GL's nearest use floor or round?\n _glsl_sample_nearest = \"\"\"\n vec4 sample(sampler2D tex, vec3 texcoord) {\n // Don't let adjacent frames be interpolated into this one\n texcoord.x = min(texcoord.x * $shape.x, $shape.x - 0.5);\n texcoord.x = max(0.5, texcoord.x) / $shape.x;\n texcoord.y = min(texcoord.y * $shape.y, $shape.y - 0.5);\n texcoord.y = max(0.5, texcoord.y) / $shape.y;\n\n float index = floor(texcoord.z * $shape.z);\n\n // Do a lookup in the 2D texture\n float u = (mod(index, $r) + texcoord.x) / $r;\n float v = (floor(index / $r) + texcoord.y) / $c;\n\n return texture2D(tex, vec2(u,v));\n }\n \"\"\"\n\n _glsl_sample_linear = \"\"\"\n vec4 sample(sampler2D tex, vec3 texcoord) {\n // Don't let adjacent frames be interpolated into this one\n texcoord.x = min(texcoord.x * $shape.x, $shape.x - 0.5);\n texcoord.x = max(0.5, texcoord.x) / $shape.x;\n texcoord.y = min(texcoord.y * $shape.y, $shape.y - 0.5);\n texcoord.y = max(0.5, texcoord.y) / $shape.y;\n\n float z = texcoord.z * $shape.z;\n float zindex1 = floor(z);\n float u1 = (mod(zindex1, $r) + texcoord.x) / $r;\n float v1 = (floor(zindex1 / $r) + texcoord.y) / $c;\n\n float zindex2 = zindex1 + 1.0;\n float u2 = (mod(zindex2, $r) + texcoord.x) / $r;\n float v2 = (floor(zindex2 / $r) + texcoord.y) / $c;\n\n vec4 s1 = texture2D(tex, vec2(u1, v1));\n vec4 s2 = texture2D(tex, vec2(u2, v2));\n\n return s1 * (zindex2 - z) + s2 * (z - zindex1);\n }\n \"\"\"\n\n _gl_max_texture_size = 1024 # For now, we just set this manually\n\n def __init__(self, data=None, format=None, resizable=True,\n interpolation=None, wrapping=None, shape=None,\n internalformat=None, resizeable=None):\n from ..visuals.shaders import Function\n\n self._set_emulated_shape(data)\n Texture2D.__init__(self, self._normalize_emulated_shape(data),\n format, resizable, interpolation, wrapping,\n shape, internalformat, resizeable)\n if self.interpolation == 'nearest':\n self._glsl_sample = Function(self.__class__._glsl_sample_nearest)\n else:\n self._glsl_sample = Function(self.__class__._glsl_sample_linear)\n self._update_variables()\n\n def _set_emulated_shape(self, data_or_shape):\n if isinstance(data_or_shape, np.ndarray):\n self._emulated_shape = data_or_shape.shape\n else:\n assert isinstance(data_or_shape, tuple)\n self._emulated_shape = tuple(data_or_shape)\n\n depth, width = self._emulated_shape[0], self._emulated_shape[1]\n self._r = TextureEmulated3D._gl_max_texture_size // width\n self._c = depth // self._r\n if math.fmod(depth, self._r):\n self._c += 1\n\n def _normalize_emulated_shape(self, data_or_shape):\n if isinstance(data_or_shape, np.ndarray):\n new_shape = self._normalize_emulated_shape(data_or_shape.shape)\n new_data = np.empty(new_shape, dtype=data_or_shape.dtype)\n for j in range(self._c):\n for i in range(self._r):\n i0, i1 = i * self.width, (i+1) * self.width\n j0, j1 = j * self.height, (j+1) * self.height\n k = j * self._r + i\n if k >= self.depth:\n break\n new_data[j0:j1, i0:i1] = data_or_shape[k]\n\n return new_data\n\n assert isinstance(data_or_shape, tuple)\n return (self._c * self.height, self._r * self.width) + \\\n data_or_shape[3:]\n\n def _update_variables(self):\n self._glsl_sample['shape'] = self.shape[:3][::-1]\n # On Windows with Python 2.7, self._c can end up being a long\n # integer because Numpy array shapes return long integers. This\n # causes issues when setting the gloo variables since these are\n # expected to be native ints, so we cast the integers to ints\n # to avoid this.\n # Newer GLSL compilers do not implicitly cast types so these integers\n # must be converted to floats lastly\n self._glsl_sample['c'] = float(int(self._c))\n self._glsl_sample['r'] = float(int(self._r))\n\n def set_data(self, data, offset=None, copy=False):\n \"\"\"Set texture data\n\n Parameters\n ----------\n data : ndarray\n Data to be uploaded\n offset: int | tuple of ints\n Offset in texture where to start copying data\n copy: bool\n Since the operation is deferred, data may change before\n data is actually uploaded to GPU memory. Asking explicitly\n for a copy will prevent this behavior.\n\n Notes\n -----\n This operation implicitely resizes the texture to the shape of\n the data if given offset is None.\n \"\"\"\n self._set_emulated_shape(data)\n Texture2D.set_data(self, self._normalize_emulated_shape(data),\n offset, copy)\n self._update_variables()\n\n def resize(self, shape, format=None, internalformat=None):\n \"\"\"Set the texture size and format\n\n Parameters\n ----------\n shape : tuple of integers\n New texture shape in zyx order. Optionally, an extra dimention\n may be specified to indicate the number of color channels.\n format : str | enum | None\n The format of the texture: 'luminance', 'alpha',\n 'luminance_alpha', 'rgb', or 'rgba'. If not given the format\n is chosen automatically based on the number of channels.\n When the data has one channel, 'luminance' is assumed.\n internalformat : str | enum | None\n The internal (storage) format of the texture: 'luminance',\n 'alpha', 'r8', 'r16', 'r16f', 'r32f'; 'luminance_alpha',\n 'rg8', 'rg16', 'rg16f', 'rg32f'; 'rgb', 'rgb8', 'rgb16',\n 'rgb16f', 'rgb32f'; 'rgba', 'rgba8', 'rgba16', 'rgba16f',\n 'rgba32f'. If None, the internalformat is chosen\n automatically based on the number of channels. This is a\n hint which may be ignored by the OpenGL implementation.\n \"\"\"\n self._set_emulated_shape(shape)\n Texture2D.resize(self, self._normalize_emulated_shape(shape),\n format, internalformat)\n self._update_variables()\n\n @property\n def shape(self):\n \"\"\" Data shape (last dimension indicates number of color channels)\n \"\"\"\n return self._emulated_shape\n\n @property\n def width(self):\n \"\"\" Texture width \"\"\"\n return self._emulated_shape[2]\n\n @property\n def height(self):\n \"\"\" Texture height \"\"\"\n return self._emulated_shape[1]\n\n @property\n def depth(self):\n \"\"\" Texture depth \"\"\"\n return self._emulated_shape[0]\n\n @property\n def glsl_sample(self):\n \"\"\" GLSL function that samples the texture.\n \"\"\"\n\n return self._glsl_sample\n\n\n# ------------------------------------------------------ TextureAtlas class ---\nclass TextureAtlas(Texture2D):\n \"\"\"Group multiple small data regions into a larger texture.\n\n The algorithm is based on the article by Jukka Jylänki : \"A Thousand Ways\n to Pack the Bin - A Practical Approach to Two-Dimensional Rectangle Bin\n Packing\", February 27, 2010. More precisely, this is an implementation of\n the Skyline Bottom-Left algorithm based on C++ sources provided by Jukka\n Jylänki at: http://clb.demon.fi/files/RectangleBinPack/.\n\n Parameters\n ----------\n shape : tuple of int\n Texture shape (optional).\n dtype : numpy.dtype object\n Texture starting data type (default: float32)\n\n Notes\n -----\n This creates a 2D texture that holds 1D float32 data.\n An example of simple access:\n\n >>> atlas = TextureAtlas()\n >>> bounds = atlas.get_free_region(20, 30)\n >>> atlas.set_region(bounds, np.random.rand(20, 30).T)\n\n \"\"\"\n def __init__(self, shape=(1024, 1024), dtype=np.float32):\n shape = np.array(shape, int)\n assert shape.ndim == 1 and shape.size == 2\n shape = tuple(2 ** (np.log2(shape) + 0.5).astype(int)) + (3,)\n self._atlas_nodes = [(0, 0, shape[1])]\n data = np.zeros(shape, dtype)\n super(TextureAtlas, self).__init__(data, interpolation='linear',\n wrapping='clamp_to_edge')\n\n def get_free_region(self, width, height):\n \"\"\"Get a free region of given size and allocate it\n\n Parameters\n ----------\n width : int\n Width of region to allocate\n height : int\n Height of region to allocate\n\n Returns\n -------\n bounds : tuple | None\n A newly allocated region as (x, y, w, h) or None\n (if failed).\n \"\"\"\n best_height = best_width = np.inf\n best_index = -1\n for i in range(len(self._atlas_nodes)):\n y = self._fit(i, width, height)\n if y >= 0:\n node = self._atlas_nodes[i]\n if (y+height < best_height or\n (y+height == best_height and node[2] < best_width)):\n best_height = y+height\n best_index = i\n best_width = node[2]\n region = node[0], y, width, height\n if best_index == -1:\n return None\n\n node = region[0], region[1] + height, width\n self._atlas_nodes.insert(best_index, node)\n i = best_index+1\n while i < len(self._atlas_nodes):\n node = self._atlas_nodes[i]\n prev_node = self._atlas_nodes[i-1]\n if node[0] < prev_node[0]+prev_node[2]:\n shrink = prev_node[0]+prev_node[2] - node[0]\n x, y, w = self._atlas_nodes[i]\n self._atlas_nodes[i] = x+shrink, y, w-shrink\n if self._atlas_nodes[i][2] <= 0:\n del self._atlas_nodes[i]\n i -= 1\n else:\n break\n else:\n break\n i += 1\n\n # Merge nodes\n i = 0\n while i < len(self._atlas_nodes)-1:\n node = self._atlas_nodes[i]\n next_node = self._atlas_nodes[i+1]\n if node[1] == next_node[1]:\n self._atlas_nodes[i] = node[0], node[1], node[2]+next_node[2]\n del self._atlas_nodes[i+1]\n else:\n i += 1\n\n return region\n\n def _fit(self, index, width, height):\n \"\"\"Test if region (width, height) fit into self._atlas_nodes[index]\"\"\"\n node = self._atlas_nodes[index]\n x, y = node[0], node[1]\n width_left = width\n if x+width > self._shape[1]:\n return -1\n i = index\n while width_left > 0:\n node = self._atlas_nodes[i]\n y = max(y, node[1])\n if y+height > self._shape[0]:\n return -1\n width_left -= node[2]\n i += 1\n return y\n", "# -*- coding: utf-8 -*-\n# vispy: testskip\n# -----------------------------------------------------------------------------\n# Copyright (c) Vispy Development Team. All Rights Reserved.\n# Distributed under the (new) BSD License. See LICENSE.txt for more info.\n# -----------------------------------------------------------------------------\n\"\"\"\nCompare an optimal plot grid implementation to the same functionality\nprovided by scenegraph.\n\nUse --vispy-cprofile to see an overview of time spent in all functions.\nUse util.profiler and --vispy-profile=ClassName.method_name for more directed\nprofiling measurements.\n\"\"\"\nfrom __future__ import division\nimport numpy as np\n\nfrom vispy import gloo, app, scene, visuals\nfrom vispy.util.profiler import Profiler\n\n\nclass GridCanvas(app.Canvas):\n def __init__(self, cells, **kwargs):\n m, n = (10, 10)\n self.grid_size = (m, n)\n self.cells = cells\n super(GridCanvas, self).__init__(keys='interactive',\n show=True, **kwargs)\n\n def on_initialize(self, event):\n self.context.set_state(clear_color='black', blend=True,\n blend_func=('src_alpha', 'one_minus_src_alpha'))\n\n def on_mouse_move(self, event):\n if event.is_dragging and not event.modifiers:\n dx = (event.pos - event.last_event.pos) * [1, -1]\n i, j = event.press_event.pos / self.size\n m, n = len(self.cells), len(self.cells[0])\n cell = self.cells[int(i*m)][n - 1 - int(j*n)]\n if event.press_event.button == 1:\n offset = (np.array(cell.offset) + \n (dx / (np.array(self.size) / [m, n])) * \n (2 / np.array(cell.scale)))\n cell.set_transform(offset, cell.scale)\n \n else:\n cell.set_transform(cell.offset, cell.scale * 1.05 ** dx)\n self.update()\n\n def on_draw(self, event):\n prof = Profiler() # noqa\n self.context.clear()\n M = len(self.cells)\n N = len(self.cells[0])\n w, h = self.size\n for i in range(M):\n for j in range(N):\n self.context.set_viewport(w*i/M, h*j/N, w/M, h/N)\n self.cells[i][j].draw()\n\n\nvert = \"\"\"\nattribute vec2 pos;\nuniform vec2 offset;\nuniform vec2 scale;\n\nvoid main() {\n gl_Position = vec4((pos + offset) * scale, 0, 1);\n}\n\"\"\"\n\nfrag = \"\"\"\nvoid main() {\n gl_FragColor = vec4(1, 1, 1, 0.5);\n}\n\"\"\"\n\n\nclass Line(object):\n def __init__(self, data, offset, scale):\n self.data = gloo.VertexBuffer(data)\n self.program = gloo.Program(vert, frag)\n self.program['pos'] = self.data\n self.set_transform(offset, scale)\n \n def set_transform(self, offset, scale):\n self.offset = offset\n self.scale = scale\n self.program['offset'] = self.offset\n self.program['scale'] = self.scale\n \n def draw(self):\n self.program.draw('line_strip')\n\n\nscales = np.array((1.9 / 100., 2. / 10.))\n\n\nclass VisualCanvas(app.Canvas):\n def __init__(self, vis, **kwargs):\n super(VisualCanvas, self).__init__(keys='interactive',\n show=True, **kwargs)\n m, n = (10, 10)\n self.grid_size = (m, n)\n self.visuals = vis\n\n def on_initialize(self, event):\n self.context.set_state(clear_color='black', blend=True,\n blend_func=('src_alpha', 'one_minus_src_alpha'))\n\n def on_mouse_move(self, event):\n if event.is_dragging and not event.modifiers:\n dx = np.array(event.pos - event.last_event.pos)\n x, y = event.press_event.pos / self.size\n m, n = self.grid_size\n i, j = int(x*m), n - 1 - int(y*n)\n v = self.visuals[i][j]\n tr = v.transform\n if event.press_event.button == 1:\n tr.translate = np.array(tr.translate)[:2] + \\\n dx * scales * (1, -1)\n\n else:\n tr.scale = tr.scale[:2] * 1.05 ** (dx * (1, -1))\n self.update()\n\n def on_draw(self, event):\n prof = Profiler() # noqa\n self.context.clear()\n M, N = self.grid_size\n w, h = self.size\n for i in range(M):\n for j in range(N):\n self.context.set_viewport(w*i/M, h*j/N, w/M, h/N)\n self.visuals[i][j].draw()\n\n\nif __name__ == '__main__':\n M, N = (10, 10)\n\n data = np.empty((10000, 2), dtype=np.float32)\n data[:, 0] = np.linspace(0, 100, data.shape[0])\n data[:, 1] = np.random.normal(size=data.shape[0])\n\n # Optimized version\n cells = []\n for i in range(M):\n row = []\n cells.append(row)\n for j in range(N):\n row.append(Line(data, offset=(-50, 0), scale=scales))\n\n gcanvas = GridCanvas(cells, position=(400, 300), size=(800, 600),\n title=\"GridCanvas\")\n\n # Visual version\n vlines = []\n for i in range(M):\n row = []\n vlines.append(row)\n for j in range(N):\n v = visuals.LineVisual(pos=data, color='w', method='gl')\n v.transform = visuals.transforms.STTransform(\n translate=(-1, 0), scale=scales)\n row.append(v)\n\n vcanvas = VisualCanvas(vlines, position=(400, 300), size=(800, 600), \n title=\"VisualCanvas\")\n\n # Scenegraph version\n scanvas = scene.SceneCanvas(show=True, keys='interactive', \n title=\"SceneCanvas\")\n \n scanvas.size = 800, 600\n grid = scanvas.central_widget.add_grid(margin=0)\n\n lines = []\n for i in range(10):\n lines.append([])\n for j in range(10):\n vb = grid.add_view(camera='panzoom', row=i, col=j)\n vb.camera.set_range([0, 100], [-5, 5], margin=0)\n line = scene.visuals.Line(pos=data, color='w', method='gl')\n vb.add(line)\n scanvas.show()\n\n import sys\n if sys.flags.interactive != 1:\n app.run()\n", "# -*- coding: utf-8 -*-\n# -----------------------------------------------------------------------------\n# Copyright (c) Vispy Development Team. All Rights Reserved.\n# Distributed under the (new) BSD License. See LICENSE.txt for more info.\n# -----------------------------------------------------------------------------\nimport numpy as np\n\nfrom .widget import Widget\nfrom ...visuals import AxisVisual\n\n\nclass AxisWidget(Widget):\n \"\"\"Widget containing an axis\n\n Parameters\n ----------\n orientation : str\n Orientation of the axis, 'left' or 'bottom'.\n **kwargs : dict\n Keyword arguments to pass to AxisVisual.\n \"\"\"\n\n def __init__(self, orientation='left', **kwargs):\n if 'tick_direction' not in kwargs:\n tickdir = {'left': (-1, 0), 'right': (1, 0), 'bottom': (0, 1),\n 'top': (0, -1)}[orientation]\n kwargs['tick_direction'] = tickdir\n self.axis = AxisVisual(**kwargs)\n self.orientation = orientation\n self._linked_view = None\n Widget.__init__(self)\n self.add_subvisual(self.axis)\n\n def on_resize(self, event):\n \"\"\"Resize event handler\n\n Parameters\n ----------\n event : instance of Event\n The event.\n \"\"\"\n self._update_axis()\n\n def _update_axis(self):\n self.axis.pos = self._axis_ends()\n \n def _axis_ends(self):\n r = self.rect\n if self.orientation == 'left':\n return np.array([[r.right, r.top], [r.right, r.bottom]])\n elif self.orientation == 'bottom':\n return np.array([[r.left, r.bottom], [r.right, r.bottom]])\n elif self.orientation == 'right':\n return np.array([[r.left, r.top], [r.left, r.bottom]])\n elif self.orientation == 'top':\n return np.array([[r.left, r.top], [r.right, r.top]])\n else:\n raise RuntimeError(\n 'Orientation %s not supported.' % self.orientation)\n \n def link_view(self, view):\n \"\"\"Link this axis to a ViewBox\n\n This makes it so that the axis's domain always matches the\n visible range in the ViewBox.\n\n Parameters\n ----------\n view : instance of ViewBox\n The ViewBox to link.\n \"\"\"\n if view is self._linked_view:\n return\n if self._linked_view is not None:\n self._linked_view.scene.transform.changed.disconnect(\n self._view_changed)\n self._linked_view = view\n view.scene.transform.changed.connect(self._view_changed)\n self._view_changed()\n \n def _view_changed(self, event=None):\n \"\"\"Linked view transform has changed; update ticks.\n \"\"\"\n tr = self.node_transform(self._linked_view.scene)\n p1, p2 = tr.map(self._axis_ends())\n if self.orientation in ('left', 'right'):\n self.axis.domain = (p1[1], p2[1])\n else:\n self.axis.domain = (p1[0], p2[0])\n", "# -*- coding: utf-8 -*-\n# Copyright (c) Vispy Development Team. All Rights Reserved.\n# Distributed under the (new) BSD License. See LICENSE.txt for more info.\n\"\"\"\nClassses representing GLSL objects (functions, variables, etc) that may be\ncomposed together to create complete shaders.\nSee the docstring of Function for details.\n\nDetails\n-------\n\nA complete GLSL program is composed of ShaderObjects, each of which may be used\ninline as an expression, and some of which include a definition that must be\nincluded on the final code. ShaderObjects keep track of a hierarchy of\ndependencies so that all necessary code is included at compile time, and\nchanges made to any object may be propagated to the root of the hierarchy to\ntrigger a recompile.\n\"\"\"\n\nfrom collections import OrderedDict\nimport logging\nimport re\n\nimport numpy as np\n\nfrom ...util.eq import eq\nfrom ...util import logger\nfrom . import parsing\nfrom .shader_object import ShaderObject\nfrom .variable import Variable, Varying\nfrom .expression import TextExpression, FunctionCall\n\n\nclass Function(ShaderObject):\n \"\"\"Representation of a GLSL function\n\n Objects of this class can be used for re-using and composing GLSL\n snippets. Each Function consists of a GLSL snippet in the form of\n a function. The code may have template variables that start with\n the dollar sign. These stubs can be replaced with expressions using\n the index operation. Expressions can be:\n\n * plain text that is inserted verbatim in the code\n * a Function object or a call to a funcion\n * a Variable (or Varying) object\n * float, int, tuple are automatically turned into a uniform Variable\n * a VertexBuffer is automatically turned into an attribute Variable\n\n All functions have implicit \"$pre\" and \"$post\" placeholders that may be\n used to insert code at the beginning and end of the function.\n\n Examples\n --------\n This example shows the basic usage of the Function class::\n\n vert_code_template = Function('''\n void main() {\n gl_Position = $pos;\n gl_Position.x += $xoffset;\n gl_Position.y += $yoffset;\n }''')\n\n scale_transform = Function('''\n vec4 transform_scale(vec4 pos){\n return pos * $scale;\n }''')\n\n # If you get the function from a snippet collection, always\n # create new Function objects to ensure they are 'fresh'.\n vert_code = Function(vert_code_template)\n trans1 = Function(scale_transform)\n trans2 = Function(scale_transform) # trans2 != trans1\n\n # Three ways to assign to template variables:\n #\n # 1) Assign verbatim code\n vert_code['xoffset'] = '(3.0 / 3.1415)'\n\n # 2) Assign a value (this creates a new uniform or attribute)\n vert_code['yoffset'] = 5.0\n\n # 3) Assign a function call expression\n pos_var = Variable('attribute vec4 a_position')\n vert_code['pos'] = trans1(trans2(pos_var))\n\n # Transforms also need their variables set\n trans1['scale'] = 0.5\n trans2['scale'] = (1.0, 0.5, 1.0, 1.0)\n\n # You can actually change any code you want, but use this with care!\n vert_code.replace('gl_Position.y', 'gl_Position.z')\n\n # Finally, you can set special variables explicitly. This generates\n # a new statement at the end of the vert_code function.\n vert_code['gl_PointSize'] = '10.'\n\n\n If we use ``vert_code.compile()`` we get::\n\n attribute vec4 a_position;\n uniform float u_yoffset;\n uniform float u_scale_1;\n uniform vec4 u_scale_2;\n uniform float u_pointsize;\n\n vec4 transform_scale_1(vec4 pos){\n return pos * u_scale_1;\n }\n\n vec4 transform_scale_2(vec4 pos){\n return pos * u_scale_2;\n }\n\n void main() {\n gl_Position = transform_scale_1(transform_scale_2(a_position));\n gl_Position.x += (3.0 / 3.1415);\n gl_Position.z += u_yoffset;\n\n gl_PointSize = u_pointsize;\n }\n\n Note how the two scale function resulted in two different functions\n and two uniforms for the scale factors.\n\n Function calls\n --------------\n\n As can be seen above, the arguments with which a function is to be\n called must be specified by calling the Function object. The\n arguments can be any of the expressions mentioned earlier. If the\n signature is already specified in the template code, that function\n itself must be given.\n\n code = Function('''\n void main() {\n vec4 position = $pos;\n gl_Position = $scale(position)\n }\n ''')\n\n # Example of a function call with all possible three expressions\n vert_code['pos'] = func1('3.0', 'uniform float u_param', func2())\n\n # For scale, the sigfnature is already specified\n code['scale'] = scale_func # Must not specify args\n\n Data for uniform and attribute variables\n ----------------------------------------\n To each variable a value can be associated. In fact, in most cases\n the Function class is smart enough to be able to create a Variable\n object if only the data is given.\n\n code['offset'] = Variable('uniform float offset') # No data\n code['offset'] = Variable('uniform float offset', 3.0) # With data\n code['offset'] = 3.0 # -> Uniform Variable\n position['position'] = VertexBuffer() # -> attribute Variable\n\n # Updating variables\n code['offset'].value = 4.0\n position['position'].value.set_data(...)\n \"\"\"\n\n def __init__(self, code, dependencies=None):\n super(Function, self).__init__()\n\n # Add depencencies is given. This is to allow people to\n # manually define deps for a function that they use.\n if dependencies is not None:\n for dep in dependencies:\n self._add_dep(dep)\n\n self.code = code\n\n # Expressions replace template variables (also our dependencies)\n self._expressions = OrderedDict()\n\n # Verbatim string replacements\n self._replacements = OrderedDict()\n\n # Stuff to do at the end\n self._assignments = OrderedDict()\n\n def __setitem__(self, key, val):\n \"\"\" Setting of replacements through a dict-like syntax.\n\n Each replacement can be:\n * verbatim code: ``fun1['foo'] = '3.14159'``\n * a FunctionCall: ``fun1['foo'] = fun2()``\n * a Variable: ``fun1['foo'] = Variable(...)`` (can be auto-generated)\n \"\"\"\n # Check the key. Must be Varying, 'gl_X' or a known template variable\n if isinstance(key, Variable):\n if key.vtype == 'varying':\n if self.name != 'main':\n raise Exception(\"Varying assignment only alowed in 'main' \"\n \"function.\")\n storage = self._assignments\n else:\n raise TypeError(\"Variable assignment only allowed for \"\n \"varyings, not %s (in %s)\"\n % (key.vtype, self.name))\n elif isinstance(key, str):\n if any(map(key.startswith,\n ('gl_PointSize', 'gl_Position', 'gl_FragColor'))):\n storage = self._assignments\n elif key in self.template_vars or key in ('pre', 'post'):\n storage = self._expressions\n else:\n raise KeyError('Invalid template variable %r' % key)\n else:\n raise TypeError('In `function[key]` key must be a string or '\n 'varying.')\n\n # If values already match, bail out now\n if eq(storage.get(key), val):\n return\n\n # If we are only changing the value (and not the dtype) of a uniform,\n # we can set that value and return immediately to avoid triggering a\n # recompile.\n if val is not None and not isinstance(val, Variable):\n # We are setting a value. If there is already a variable set here,\n # try just updating its value.\n variable = storage.get(key, None)\n if isinstance(variable, Variable):\n if np.any(variable.value != val):\n variable.value = val\n self.changed(value_changed=True)\n return\n\n # Could not set variable.value directly; instead we will need\n # to create a new ShaderObject\n val = ShaderObject.create(val, ref=key)\n if variable is val:\n # This can happen if ShaderObject.create returns the same\n # object (such as when setting a Transform).\n return\n\n # Remove old references, if any\n oldval = storage.pop(key, None)\n if oldval is not None:\n for obj in (key, oldval):\n if isinstance(obj, ShaderObject):\n self._remove_dep(obj)\n\n # Add new references\n if val is not None:\n if isinstance(key, Varying):\n # tell this varying to inherit properties from\n # its source attribute / expression.\n key.link(val)\n\n # Store value and dependencies\n storage[key] = val\n for obj in (key, val):\n if isinstance(obj, ShaderObject):\n self._add_dep(obj)\n\n # In case of verbatim text, we might have added new template vars\n if isinstance(val, TextExpression):\n for var in parsing.find_template_variables(val.expression()):\n if var not in self.template_vars:\n self.template_vars.add(var.lstrip('$'))\n\n self.changed(code_changed=True, value_changed=True)\n if logger.level <= logging.DEBUG:\n import traceback\n last = traceback.format_list(traceback.extract_stack()[-2:-1])\n logger.debug(\"Assignment would trigger shader recompile:\\n\"\n \"Original: %r\\nReplacement: %r\\nSource: %s\",\n oldval, val, ''.join(last))\n\n def __getitem__(self, key):\n \"\"\" Return a reference to a program variable from this function.\n\n This allows variables between functions to be linked together::\n\n func1['var_name'] = func2['other_var_name']\n\n In the example above, the two local variables would be assigned to the\n same program variable whenever func1 and func2 are attached to the same\n program.\n \"\"\"\n\n try:\n return self._expressions[key]\n except KeyError:\n pass\n\n try:\n return self._assignments[key]\n except KeyError:\n pass\n\n if key not in self.template_vars:\n raise KeyError('Invalid template variable %r' % key)\n else:\n raise KeyError('No value known for key %r' % key)\n\n def __call__(self, *args):\n \"\"\" Set the signature for this function and return an FunctionCall\n object. Each argument can be verbatim code or a FunctionCall object.\n \"\"\"\n return FunctionCall(self, args)\n\n ## Public API methods\n\n @property\n def signature(self):\n if self._signature is None:\n try:\n self._signature = parsing.parse_function_signature(self._code)\n except Exception as err:\n raise ValueError('Invalid code: ' + str(err))\n return self._signature\n\n @property\n def name(self):\n \"\"\" The function name. The name may be mangled in the final code\n to avoid name clashes.\n \"\"\"\n return self.signature[0]\n\n @property\n def args(self):\n \"\"\"\n List of input arguments in the function signature::\n\n [(arg_name, arg_type), ...]\n \"\"\"\n return self.signature[1]\n\n @property\n def rtype(self):\n \"\"\"\n The return type of this function.\n \"\"\"\n return self.signature[2]\n\n @property\n def code(self):\n \"\"\" The template code used to generate the definition for this\n function.\n \"\"\"\n return self._code\n\n @code.setter\n def code(self, code):\n # Get and strip code\n if isinstance(code, Function):\n code = code._code\n elif not isinstance(code, str):\n raise ValueError('Function needs a string or Function; got %s.' %\n type(code))\n self._code = self._clean_code(code)\n\n # (name, args, rval)\n self._signature = None\n\n # $placeholders parsed from the code\n self._template_vars = None\n\n # Create static Variable instances for any global variables declared\n # in the code\n self._static_vars = None\n\n @property\n def template_vars(self):\n if self._template_vars is None:\n self._template_vars = self._parse_template_vars()\n return self._template_vars\n\n def static_names(self):\n if self._static_vars is None:\n self._static_vars = parsing.find_program_variables(self._code)\n return list(self._static_vars.keys()) + [arg[0] for arg in self.args]\n\n def replace(self, str1, str2):\n \"\"\" Set verbatim code replacement\n\n It is strongly recommended to use function['$foo'] = 'bar' where\n possible because template variables are less likely to changed\n than the code itself in future versions of vispy.\n\n Parameters\n ----------\n str1 : str\n String to replace\n str2 : str\n String to replace str1 with\n \"\"\"\n if str2 != self._replacements.get(str1, None):\n self._replacements[str1] = str2\n self.changed(code_changed=True)\n #self._last_changed = time.time()\n\n ## Private methods\n\n def _parse_template_vars(self):\n \"\"\" find all template variables in self._code, excluding the\n function name.\n \"\"\"\n template_vars = set()\n for var in parsing.find_template_variables(self._code):\n var = var.lstrip('$')\n if var == self.name:\n continue\n if var in ('pre', 'post'):\n raise ValueError('GLSL uses reserved template variable $%s' %\n var)\n template_vars.add(var)\n return template_vars\n\n def _get_replaced_code(self, names, version, shader):\n \"\"\" Return code, with new name, expressions, and replacements applied.\n \"\"\"\n code = self._code\n\n # Modify name\n fname = names[self]\n code = code.replace(\" \" + self.name + \"(\", \" \" + fname + \"(\")\n\n # Apply string replacements first -- these may contain $placeholders\n for key, val in self._replacements.items():\n code = code.replace(key, val)\n\n # Apply assignments to the end of the function\n\n # Collect post lines\n post_lines = []\n for key, val in self._assignments.items():\n if isinstance(key, Variable):\n key = names[key]\n if isinstance(val, ShaderObject):\n val = val.expression(names)\n line = ' %s = %s;' % (key, val)\n post_lines.append(line)\n\n # Add a default $post placeholder if needed\n if 'post' in self._expressions:\n post_lines.append(' $post')\n\n # Apply placeholders for hooks\n post_text = '\\n'.join(post_lines)\n if post_text:\n post_text = '\\n' + post_text + '\\n'\n code = code.rpartition('}')\n code = code[0] + post_text + code[1] + code[2]\n\n # Add a default $pre placeholder if needed\n if 'pre' in self._expressions:\n m = re.search(fname + r'\\s*\\([^{]*\\)\\s*{', code)\n if m is None:\n raise RuntimeError(\"Cound not find beginning of function '%s'\"\n % fname)\n ind = m.span()[1]\n code = code[:ind] + \"\\n $pre\\n\" + code[ind:]\n\n # Apply template variables\n for key, val in self._expressions.items():\n val = val.expression(names)\n search = r'\\$' + key + r'($|[^a-zA-Z0-9_])'\n code = re.sub(search, val+r'\\1', code)\n\n # Done\n if '$' in code:\n v = parsing.find_template_variables(code)\n logger.warning('Unsubstituted placeholders in code: %s\\n'\n ' replacements made: %s',\n v, list(self._expressions.keys()))\n\n return code + '\\n'\n\n def definition(self, names, version, shader):\n return self._get_replaced_code(names, version, shader)\n\n def expression(self, names):\n return names[self]\n\n def _clean_code(self, code):\n \"\"\" Return *code* with indentation and leading/trailing blank lines\n removed.\n \"\"\"\n lines = code.split(\"\\n\")\n min_indent = 100\n for line in lines:\n if line.strip() != \"\":\n indent = len(line) - len(line.lstrip())\n min_indent = min(indent, min_indent)\n if min_indent > 0:\n lines = [line[min_indent:] for line in lines]\n code = \"\\n\".join(lines)\n return code\n\n def __repr__(self):\n try:\n args = ', '.join([' '.join(arg) for arg in self.args])\n except Exception:\n return ('<%s (error parsing signature) at 0x%x>' %\n (self.__class__.__name__, id(self)))\n return '<%s \"%s %s(%s)\" at 0x%x>' % (self.__class__.__name__,\n self.rtype,\n self.name,\n args,\n id(self))\n\n\nclass MainFunction(Function):\n \"\"\" Subclass of Function that allows multiple functions and variables to\n be defined in a single code string. The code must contain a main() function\n definition.\n \"\"\"\n def __init__(self, shader_type, *args, **kwargs):\n self.shader_type = shader_type\n self._chains = {}\n Function.__init__(self, *args, **kwargs)\n\n @property\n def signature(self):\n return ('main', [], 'void')\n\n @property\n def version_pragma(self):\n \"\"\"Return version number and extra qualifiers from pragma if present.\n \"\"\"\n m = re.search(parsing.re_version_pragma, self.code)\n if m is None:\n return None\n return int(m.group(1)), m.group(2)\n\n def definition(self, obj_names, version, shader):\n code = Function.definition(self, obj_names, version, shader)\n # strip out version pragma before returning code; this will be\n # added to the final compiled code later.\n code = re.sub(parsing.re_version_pragma, '', code)\n return code\n\n def static_names(self):\n if self._static_vars is not None:\n return self._static_vars\n\n # parse static variables\n names = Function.static_names(self)\n\n # parse all function names + argument names\n funcs = parsing.find_functions(self.code)\n for f in funcs:\n if f[0] == 'main':\n continue\n names.append(f[0])\n for arg in f[1]:\n names.append(arg[1])\n\n self._static_vars = names\n return names\n\n def add_chain(self, var):\n \"\"\"\n Create a new ChainFunction and attach to $var.\n \"\"\"\n chain = FunctionChain(var, [])\n self._chains[var] = chain\n self[var] = chain\n\n def add_callback(self, hook, func):\n self._chains[hook].append(func)\n\n def remove_callback(self, hook, func):\n self._chains[hook].remove(func)\n\n\nclass FunctionChain(Function):\n \"\"\"Subclass that generates GLSL code to call Function list in order\n\n Functions may be called independently, or composed such that the\n output of each function provides the input to the next.\n\n Parameters\n ----------\n name : str\n The name of the generated function\n funcs : list of Functions\n The list of Functions that will be called by the generated GLSL code.\n\n Examples\n --------\n This creates a function chain:\n\n >>> func1 = Function('void my_func_1() {}')\n >>> func2 = Function('void my_func_2() {}')\n >>> chain = FunctionChain('my_func_chain', [func1, func2])\n\n If *chain* is included in a ModularProgram, it will generate the following\n output:\n\n void my_func_1() {}\n void my_func_2() {}\n\n void my_func_chain() {\n my_func_1();\n my_func_2();\n }\n\n The return type of the generated function is the same as the return type\n of the last function in the chain. Likewise, the arguments for the\n generated function are the same as the first function in the chain.\n\n If the return type is not 'void', then the return value of each function\n will be used to supply the first input argument of the next function in\n the chain. For example:\n\n vec3 my_func_1(vec3 input) {return input + vec3(1, 0, 0);}\n void my_func_2(vec3 input) {return input + vec3(0, 1, 0);}\n\n vec3 my_func_chain(vec3 input) {\n return my_func_2(my_func_1(input));\n }\n \"\"\"\n def __init__(self, name=None, funcs=()):\n # bypass Function.__init__ completely.\n ShaderObject.__init__(self)\n if not (name is None or isinstance(name, str)):\n raise TypeError(\"Name argument must be string or None.\")\n self._funcs = []\n self._code = None\n self._name = name or \"chain\"\n self._args = []\n self._rtype = 'void'\n self.functions = funcs\n\n @property\n def functions(self):\n return self._funcs[:]\n\n @functions.setter\n def functions(self, funcs):\n while self._funcs:\n self.remove(self._funcs[0], update=False)\n for f in funcs:\n self.append(f, update=False)\n self._update()\n\n @property\n def signature(self):\n return self._name, self._args, self._rtype\n\n def _update(self):\n funcs = self._funcs\n if len(funcs) > 0:\n self._rtype = funcs[-1].rtype\n self._args = funcs[0].args[:]\n else:\n self._rtype = 'void'\n self._args = []\n\n self.changed(code_changed=True)\n\n @property\n def code(self):\n # Code is generated at compile time; hopefully it is not requested\n # before then..\n return None\n\n @code.setter\n def code(self, c):\n raise TypeError(\"Cannot set code property on FunctionChain.\")\n\n @property\n def template_vars(self):\n return {}\n\n def append(self, function, update=True):\n \"\"\" Append a new function to the end of this chain.\n \"\"\"\n self._funcs.append(function)\n self._add_dep(function)\n if update:\n self._update()\n\n def __setitem__(self, index, func):\n self._remove_dep(self._funcs[index])\n self._add_dep(func)\n self._funcs[index] = func\n\n self._update()\n\n def __getitem__(self, k):\n return self.functions[k]\n\n def insert(self, index, function, update=True):\n \"\"\" Insert a new function into the chain at *index*.\n \"\"\"\n self._funcs.insert(index, function)\n self._add_dep(function)\n if update:\n self._update()\n\n def remove(self, function, update=True):\n \"\"\" Remove a function from the chain.\n \"\"\"\n self._funcs.remove(function)\n self._remove_dep(function)\n if update:\n self._update()\n\n def definition(self, obj_names, version, shader):\n name = obj_names[self]\n\n args = \", \".join([\"%s %s\" % arg for arg in self.args])\n code = \"%s %s(%s) {\\n\" % (self.rtype, name, args)\n\n result_index = 0\n if len(self.args) == 0:\n last_rtype = 'void'\n last_result = ''\n else:\n last_rtype, last_result = self.args[0][:2]\n\n for fn in self._funcs:\n # Use previous return value as an argument to the next function\n if last_rtype == 'void':\n args = ''\n else:\n args = last_result\n if len(fn.args) != 1 or last_rtype != fn.args[0][0]:\n raise Exception(\"Cannot chain output '%s' of function to \"\n \"input of '%s'\" %\n (last_rtype, fn.signature))\n last_rtype = fn.rtype\n\n # Store the return value of this function\n if fn.rtype == 'void':\n set_str = ''\n else:\n result_index += 1\n result = 'result_%d' % result_index\n set_str = '%s %s = ' % (fn.rtype, result)\n last_result = result\n\n code += \" %s%s(%s);\\n\" % (set_str, obj_names[fn], args)\n\n # return the last function's output\n if self.rtype != 'void':\n code += \" return result_%d;\\n\" % result_index\n\n code += \"}\\n\"\n return code\n\n def static_names(self):\n return []\n\n def __repr__(self):\n fn = \",\\n \".join(map(repr, self.functions))\n return \"<FunctionChain [%s] at 0x%x>\" % (fn, id(self))\n\n\nclass StatementList(ShaderObject):\n \"\"\"Represents a list of statements.\n \"\"\"\n def __init__(self):\n self.items = {}\n self.order = []\n ShaderObject.__init__(self)\n\n def add(self, item, position=5):\n \"\"\"Add an item to the list unless it is already present.\n\n If the item is an expression, then a semicolon will be appended to it\n in the final compiled code.\n \"\"\"\n if item in self.items:\n return\n self.items[item] = position\n self._add_dep(item)\n self.order = None\n self.changed(code_changed=True)\n\n def remove(self, item):\n \"\"\"Remove an item from the list.\n \"\"\"\n self.items.pop(item)\n self._remove_dep(item)\n self.order = None\n self.changed(code_changed=True)\n\n def expression(self, obj_names):\n if self.order is None:\n self.order = list(self.items.items())\n self.order.sort(key=lambda x: x[1])\n\n code = \"\"\n for item, pos in self.order:\n code += item.expression(obj_names) + ';\\n'\n return code\n", "# -*- coding: utf-8 -*-\n# Copyright (c) Vispy Development Team. All Rights Reserved.\n# Distributed under the (new) BSD License. See LICENSE.txt for more info.\n\n\"\"\"\nDemonstration of how to interact with visuals, here with simple\narcball-style control.\n\"\"\"\n\nimport sys\nimport numpy as np\n\nfrom vispy import app\nfrom vispy.visuals import BoxVisual, transforms\nfrom vispy.util.quaternion import Quaternion\n\n\nclass Canvas(app.Canvas):\n def __init__(self):\n app.Canvas.__init__(self, 'Cube', keys='interactive',\n size=(400, 400))\n\n self.cube = BoxVisual(1.0, 0.5, 0.25, color='red',\n edge_color='black')\n self.cube.transform = transforms.MatrixTransform()\n self.cube.transform.scale((100, 100, 0.001))\n self.cube.transform.translate((200, 200))\n\n self.quaternion = Quaternion()\n self.show()\n\n def on_resize(self, event):\n vp = (0, 0, self.physical_size[0], self.physical_size[1])\n self.context.set_viewport(*vp)\n self.cube.transforms.configure(canvas=self, viewport=vp)\n\n def on_draw(self, event):\n self.context.clear('white')\n self.cube.draw()\n\n def on_mouse_move(self, event):\n if event.button == 1 and event.last_event is not None:\n x0, y0 = event.last_event.pos\n x1, y1 = event.pos\n w, h = self.size\n self.quaternion = (self.quaternion *\n Quaternion(*_arcball(x0, y0, w, h)) *\n Quaternion(*_arcball(x1, y1, w, h)))\n self.cube.transform.matrix = self.quaternion.get_matrix()\n self.cube.transform.scale((100, 100, 0.001))\n self.cube.transform.translate((200, 200))\n self.update()\n\n\ndef _arcball(x, y, w, h):\n \"\"\"Convert x,y coordinates to w,x,y,z Quaternion parameters\n\n Adapted from:\n\n linalg library\n\n Copyright (c) 2010-2015, Renaud Blanch <rndblnch at gmail dot com>\n Licence at your convenience:\n GPLv3 or higher <http://www.gnu.org/licenses/gpl.html>\n BSD new <http://opensource.org/licenses/BSD-3-Clause>\n \"\"\"\n r = (w + h) / 2.\n x, y = -(2. * x - w) / r, -(2. * y - h) / r\n h = np.sqrt(x*x + y*y)\n return (0., x/h, y/h, 0.) if h > 1. else (0., x, y, np.sqrt(1. - h*h))\n\nif __name__ == '__main__':\n win = Canvas()\n win.show()\n if sys.flags.interactive != 1:\n win.app.run()\n" ]
[ [ "numpy.random.normal" ], [ "numpy.arange" ], [ "numpy.random.normal" ], [ "numpy.resize", "numpy.log2", "numpy.prod", "numpy.array", "numpy.zeros", "numpy.empty" ], [ "numpy.random.normal", "numpy.array", "numpy.empty", "numpy.linspace" ], [ "numpy.array" ], [ "numpy.any" ], [ "numpy.sqrt" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
trailofbits/ceo
[ "d6a1ed729f8a1e400147b99dfcb65934e1924891" ]
[ "ceo/sampling.py" ]
[ "from sklearn.model_selection import ShuffleSplit, StratifiedShuffleSplit\nfrom sklearn.utils import shuffle as skshuffle\n\ndef shuffle(x, random_state=None):\n return skshuffle(x, random_state=random_state)\n\ndef split_shuffle(X,y=None, random_state=None):\n sss = ShuffleSplit(n_splits=1, test_size=0.25, random_state=random_state)\n X_train = []\n X_test = []\n y_train = []\n y_test = []\n\n train_index, test_index = sss.split(X, y).next()\n\n for index in train_index:\n X_train.append(X[index])\n if y is not None:\n y_train.append(y[index])\n\n\n for index in test_index:\n X_test.append(X[index])\n if y is not None:\n y_test.append(y[index])\n\n if y is not None:\n return X_train, y_train, X_test, y_test\n else:\n return X_train, X_test\n\ndef stratified_shuffle(X,y, random_state=None):\n sss = StratifiedShuffleSplit(n_splits=1, test_size=0.25, random_state=random_state)\n X_train = []\n X_test = []\n y_train = []\n y_test = []\n\n\n train_index, test_index = sss.split(X, y).next()\n\n for index in train_index:\n X_train.append(X[index])\n y_train.append(y[index])\n\n\n for index in test_index:\n X_test.append(X[index])\n y_test.append(y[index])\n\n\n return X_train, y_train, X_test, y_test\n" ]
[ [ "sklearn.utils.shuffle", "sklearn.model_selection.StratifiedShuffleSplit", "sklearn.model_selection.ShuffleSplit" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
xAbdalla/Machine_Learning_Exercises-Stanford_University
[ "2b38413e91948b5d2614407ac9b62a60acd191d2" ]
[ "Python/ex3/ex3.py" ]
[ "import numpy as np\nfrom scipy.io import loadmat\nfrom scipy.optimize import fmin_cg\n\n# Ignore overflow and divide by zero of np.log() and np.exp()\n# np.seterr(divide = 'ignore')\n# np.seterr(over = 'ignore') \n\ndef sigmoid(z):\n return 1.0 / (1.0 + np.exp(-z))\n\ndef computeCost(theta, X, y, lamba=1):\n m = len(y)\n \n h = sigmoid( X.dot( theta ) )\n unreg_cost = (( np.log( h ).dot( -y ) ) - (( np.log( 1. - h ).dot( 1. - y ) ))) / m\n theta[0] = 0\n reg_cost = theta.T.dot( theta ) * lamba / (2*m)\n \n return unreg_cost + reg_cost\n\ndef gradientCost(theta, X, y, lamba=1):\n m = len(y)\n grad = X.T.dot( sigmoid(X.dot(theta)) - y) / m\n grad[1:] += (theta[1:] * lamba) / m\n \n return grad\n\ndef oneVsAll(X, y, num_labels, lamba):\n # Some useful variables\n m, n = X.shape\n \n # Add ones to the X data matrix\n X = np.insert(X, 0, 1, axis= 1)\n \n # need to return the following variables correctly \n all_theta = np.zeros((n+1, num_labels))\n \n # labels are 1-indexed instead of 0-indexed\n for i in range(0, num_labels):\n theta = np.zeros(( n+1, 1 )).reshape(-1)\n y_i = ((y == (i+1)) + 0).reshape(-1)\n \n # minimize the objective function\n fmin = fmin_cg(computeCost,\n x0= theta,\n args= (X, y_i, lamba),\n fprime= gradientCost,\n maxiter= 300,\n disp= False,\n full_output= True)\n \n all_theta[:, i] = fmin[0]\n \n # np.save( \"all_theta.txt\", all_theta )\n print (\"%2d Cost: %.5f\" % (i+1, fmin[1]))\n print('===================================================')\n return all_theta\n\ndef predictOneVsAll(X, all_theta):\n # Add ones to the X data matrix\n m, n = X.shape\n X = np.insert(X, 0, 1, axis= 1)\n \n p = sigmoid(X.dot(all_theta)) # 1-D Array\n # print(p.shape)\n p_argmax = np.matrix(p.shape) # 1-D Array\n p_argmax = np.argmax(p, axis= 1) + 1\n \n return p_argmax.reshape(m, 1) # it's important to reshape to convert it to 2-D Array.\n\n# read data\ndata = loadmat('ex3data1.mat')\nX, y = data['X'], data['y']\n\nm, n = X.shape\nnum_labels = len(np.unique(y).tolist())\ninput_layer_size = n\n\nprint('\\nDataset Details:\\n')\nprint('X Shape = ' , X.shape, type(X)) \nprint('Y Shape = ', y.shape, ' ', type(y))\nprint('===================================================')\n\nlamda = 0.1\nall_theta = oneVsAll(X, y, num_labels, lamda)\n\nprint(' X.shape = ', X.shape)\nprint(' y.shape = ', y.shape)\nprint('all_theta.shape = ', all_theta.shape)\nprint(' no. of labels = ', num_labels)\nprint(' data array = ', np.unique(data['y']))\nprint('===================================================')\n\n# Compute accuracy on our training set\np = predictOneVsAll(X, all_theta)\nprint('Training Set Accuracy: %.4f%%' %(np.mean(y == p) * 100))\nprint('===================================================')" ]
[ [ "numpy.matrix", "scipy.optimize.fmin_cg", "numpy.log", "numpy.unique", "scipy.io.loadmat", "numpy.argmax", "numpy.mean", "numpy.insert", "numpy.exp", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "1.6", "0.14", "1.10", "0.15", "1.4", "1.3", "1.9", "0.19", "1.5", "0.18", "1.2", "1.7", "0.12", "1.0", "0.17", "0.16", "1.8" ], "tensorflow": [] } ]
gtpedrosa/Python4WindEnergy
[ "8f97a5f86e81ce01d80dafb6f8104165fd3ad397", "8f97a5f86e81ce01d80dafb6f8104165fd3ad397" ]
[ "py4we/dakota.py", "py4we/hawc2_res.py" ]
[ "\"\"\" IO classes for YOUR_FILE_TYPE_NAME file types\r\n\r\nCopyright (C) 2013 DTU Wind Energy\r\n\r\nAuthor: Juan Pablo Murcia\r\nEmail: [email protected]\r\nLast revision: 28.01.2014\r\n\r\nLicense: Apache v2.0, http://www.apache.org/licenses/LICENSE-2.0\r\n\"\"\"\r\n\r\n\r\nfrom __future__ import print_function\r\nfrom we_file_io import WEFileIO, TestWEFileIO\r\nimport unittest\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\nclass DakotaTabFileIO(WEFileIO):\r\n \"\"\" Dakota tabular self.data (.dat) file class\r\n \r\n A Multilevel Parallel Object-Oriented Framework for:\r\n\r\n Design Optimization\r\n Parameter Estimation\r\n Uncertainty Quantification\r\n Sensitivity Analysis\r\n\r\n methods:\r\n --------\r\n write: write a file\r\n read: read a file\r\n\r\n \"\"\"\r\n def _write(self):\r\n \"\"\" Write a file (overrided)\r\n \"\"\"\r\n n_col = len(self.data)\r\n n_row = len(self.data[self.keys[0]])\r\n data = list()\r\n for i_row in range(n_row):\r\n data.append('')\r\n for i_col in range(n_col):\r\n if i_col == 0:\r\n data[-1] = data[-1] + format(self.data[self.keys[i_col]][i_row], '8.0f')\r\n else:\r\n data[-1] = data[-1] + ' ' + format(self.data[self.keys[i_col]][i_row], ' 1.10e')\r\n\r\n header = ''\r\n for i_col in range(n_col):\r\n if i_col == 0:\r\n header = header + format(self.keys[i_col], '<5')\r\n else:\r\n header = header + format(self.keys[i_col], '>16')\r\n\r\n data.insert(0, header)\r\n data[0] = \"%\" + data[0]\r\n\r\n out = '\\n'.join( data )\r\n with open(self.filename, 'w') as f:\r\n f.write(out)\r\n\r\n\r\n def _read(self):\r\n \"\"\" Read the file (overrided)\r\n \"\"\"\r\n\r\n with open(self.filename, 'r') as myfile:\r\n rawData = myfile.readlines()\r\n\r\n header = rawData[0]\r\n self.keys = header.split()\r\n self.keys[0] = self.keys[0][1:]\r\n n_col = len(self.keys)\r\n\r\n rawData = rawData[1:]\r\n n_row = len(rawData)\r\n\r\n # Initialize data dictionary\r\n self.data = {}\r\n for i_col in range(n_col): \r\n self.data[self.keys[i_col]] = list()\r\n # Loop over lines and extract variables of interest \r\n for i_row in range(n_row):\r\n line = rawData[i_row]\r\n columns = line.split()\r\n for i_col in range(n_col): \r\n self.data[self.keys[i_col]].append(float(columns[i_col]))\r\n\r\n # Print out something \r\n # print (self.keys) \r\n # print (self.data[ self.keys[0] ])\r\n\r\n def _plot(self,fig):\r\n\r\n n_row = len(self.keys)\r\n for i_row in range(n_row):\r\n if i_row != 0:\r\n ax = fig.add_subplot(1, n_row-1, i_row)\r\n ax.plot(self.data[self.keys[0]],self.data[self.keys[i_row]])\r\n ax.set_xlabel(self.keys[0])\r\n ax.set_ylabel(self.keys[i_row])\r\n\r\n # setting global plot configuration using the RC configuration style\r\n plt.rc('font', family='serif')\r\n plt.rc('xtick', labelsize=20) # tick labels\r\n plt.rc('ytick', labelsize=20) # tick labels\r\n plt.rc('axes', labelsize=20) # axes labels\r\n plt.rcParams['figure.figsize'] = 14, 4\r\n\r\n plt.tight_layout()\r\n\r\n def __getitem__(self, key):\r\n \"\"\" Transform the class instance into a dictionary.\"\"\"\r\n return self.data[key]\r\n\r\n## Do Some testing -------------------------------------------------------\r\nclass TestDakotaTabFileIO(TestWEFileIO):\r\n \"\"\" Test class for MyFileType class \"\"\"\r\n\r\n test_file = './test/mann/simABLupwind.inp'\r\n\r\n def test_duplication(self):\r\n self._test_duplication(DakotaTabFileIO, './test/dakota/rosen_grad_opt.dat')\r\n\r\n\r\n## Main function ---------------------------------------------------------\r\nif __name__ == '__main__':\r\n \"\"\" This is the main fuction that will run the tests automatically\r\n\r\n $> python my_file_type.py\r\n .\r\n ----------------------------------------------------------------------\r\n Ran X test in XXXs\r\n\r\n OK\r\n \"\"\"\r\n unittest.main()\r\n \r\n ''' Example uses of DakotaTabFileIO class: \r\n '''\r\n # a = DakotaTabFileIO(\"test/dakota/rosen_grad_opt.dat\") \r\n # print (type(a))\r\n # print (a.keys)\r\n # print (a.data)\r\n # print (a['x1'])\r\n # a.plot()\r\n \r\n \r\n\r\n", "# -*- coding: utf-8 -*-\n\"\"\" IO classes for YOUR_FILE_TYPE_NAME file types\n\nCopyright (C) 2013 DTU Wind Energy\n\nAuthor: Alexander Stäblein\nEmail: [email protected]\nLast revision: 20.01.2014\n\nLicense: Apache v2.0, http://www.apache.org/licenses/LICENSE-2.0\n\"\"\"\n\n\nfrom __future__ import print_function\nfrom we_file_io import WEFileIO, TestWEFileIO\nimport unittest\nimport numpy as np\n\n### Your class should look like this one ---------------------------------\n\n\nclass ResFile(WEFileIO):\n \"\"\" Description of your MyFileType class should be here.\nYou can also describe the different methods.\n\nmethods:\n--------\nwrite: write a file\nreade: read a file\n\n\"\"\"\n# def _write(self):\n# \"\"\" Write a file (overrided)\n#\"\"\"\n# # HERE DO SOMETHING TO PREPARE THE DATA TO BE WRITTEN ############\n# with open(self.filename, 'w') as f:\n# f.write(self.data)\n\n\n def _read(self):\n \"\"\" Read the file (overrided)\n\"\"\"\n # Read Scalefactor\n with open(self.filename + '.sel') as f:\n data = f.readlines()\n \n N = int(data[8].split()[0])\n Nch = int(data[8].split()[1])\n \n scalefactor = ()\n for i in range(9+Nch+5, 9+2*Nch+5):\n scalefactor = scalefactor + (float(data[i]),)\n \n # Get Data 1\n with open(self.filename + '.dat', 'rb') as f:\n self.data = np.fromfile(f, np.int16)\n \n # Scale it\n self.data = np.reshape(self.data, (Nch, N))\n self.data = self.data.T*scalefactor\n\n\n def _plot(self, fig):\n # Plot data\n channel = raw_input('Which channel should be plotted? \\n')\n ax = fig.add_subplot(1, 1, 1)\n ax.plot(self.data[:,0],self.data[:,channel])\n\n\n## Do Some testing -------------------------------------------------------\nclass TestMyDatFileIO(TestWEFileIO):\n \"\"\" Test class for MyFileType class \"\"\"\n\n def test_duplication(self):\n self._test_duplication(MyDatFileIO, './test/dat/test_file.dat')\n\n\n# Main function ---------------------------------------------------------\n#if __name__ == '__main__':\n# \"\"\" This is the main fuction that will run the tests automatically\n#$> python my_file_type.py\n#.\n#----------------------------------------------------------------------\n#Ran X test in XXXs\n#\n#OK\n#\"\"\"\n# unittest.main()\n#\n# file = ResFile('hawc2_res')\n\nif __name__ == \"__main__\":\n\n res = ResFile('hawc2_res')\n res.plot()\n" ]
[ [ "matplotlib.pyplot.tight_layout", "matplotlib.pyplot.rc" ], [ "numpy.reshape", "numpy.fromfile" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
teddylfwu/LanczosNetwork
[ "adb82d9bce4b14040952565708273eb7e6738d3c" ]
[ "runner/qm8_runner.py" ]
[ "from __future__ import (division, print_function)\nimport os\nimport numpy as np\nimport pickle\nfrom collections import defaultdict\nfrom tqdm import tqdm\n\nimport torch\nimport torch.nn as nn\nimport torch.utils.data\nimport torch.optim as optim\nfrom torch.utils.data import Dataset, DataLoader\nfrom tensorboardX import SummaryWriter\n\nfrom model import *\nfrom dataset import *\nfrom utils.logger import get_logger\nfrom utils.train_helper import data_to_gpu, snapshot, load_model, EarlyStopper\n\nlogger = get_logger('exp_logger')\n__all__ = ['QM8Runner']\n\n\nclass QM8Runner(object):\n\n def __init__(self, config):\n self.config = config\n self.dataset_conf = config.dataset\n self.model_conf = config.model\n self.train_conf = config.train\n self.test_conf = config.test\n self.use_gpu = config.use_gpu\n self.gpus = config.gpus\n self.writer = SummaryWriter(config.save_dir)\n self.meta_data = pickle.load(open(self.dataset_conf.meta_data_path, 'rb'))\n self.const_factor = self.meta_data['std'].reshape(1, -1)\n\n def train(self):\n # create data loader\n train_dataset = eval(self.dataset_conf.loader_name)(\n self.config, split='train')\n dev_dataset = eval(self.dataset_conf.loader_name)(self.config, split='dev')\n train_loader = torch.utils.data.DataLoader(\n train_dataset,\n batch_size=self.train_conf.batch_size,\n shuffle=self.train_conf.shuffle,\n num_workers=self.train_conf.num_workers,\n collate_fn=train_dataset.collate_fn,\n drop_last=False)\n dev_loader = torch.utils.data.DataLoader(\n dev_dataset,\n batch_size=self.train_conf.batch_size,\n shuffle=False,\n num_workers=self.train_conf.num_workers,\n collate_fn=dev_dataset.collate_fn,\n drop_last=False)\n\n # create models\n model = eval(self.model_conf.name)(self.config)\n\n # create optimizer\n params = filter(lambda p: p.requires_grad, model.parameters())\n if self.train_conf.optimizer == 'SGD':\n optimizer = optim.SGD(\n params,\n lr=self.train_conf.lr,\n momentum=self.train_conf.momentum,\n weight_decay=self.train_conf.wd)\n elif self.train_conf.optimizer == 'Adam':\n optimizer = optim.Adam(\n params, lr=self.train_conf.lr, weight_decay=self.train_conf.wd)\n else:\n raise ValueError(\"Non-supported optimizer!\")\n\n early_stop = EarlyStopper([0.0], win_size=10, is_decrease=False)\n\n lr_scheduler = optim.lr_scheduler.MultiStepLR(\n optimizer,\n milestones=self.train_conf.lr_decay_steps,\n gamma=self.train_conf.lr_decay)\n\n # reset gradient\n optimizer.zero_grad()\n\n # resume training\n if self.train_conf.is_resume:\n load_model(model, self.train_conf.resume_model, optimizer=optimizer)\n\n if self.use_gpu:\n model = nn.DataParallel(model, device_ids=self.gpus).cuda()\n\n # Training Loop\n iter_count = 0\n best_val_loss = np.inf\n results = defaultdict(list)\n for epoch in range(self.train_conf.max_epoch):\n # validation\n if (epoch + 1) % self.train_conf.valid_epoch == 0 or epoch == 0:\n model.eval()\n val_loss = []\n\n for data in tqdm(dev_loader):\n if self.use_gpu:\n data['node_feat'], data['node_mask'], data['label'] = data_to_gpu(\n data['node_feat'], data['node_mask'], data['label'])\n\n if self.model_conf.name == 'LanczosNet':\n data['L'], data['D'], data['V'] = data_to_gpu(\n data['L'], data['D'], data['V'])\n elif self.model_conf.name == 'GraphSAGE':\n data['nn_idx'], data['nonempty_mask'] = data_to_gpu(\n data['nn_idx'], data['nonempty_mask'])\n elif self.model_conf.name == 'GPNN':\n data['L'], data['L_cluster'], data['L_cut'] = data_to_gpu(\n data['L'], data['L_cluster'], data['L_cut'])\n else:\n data['L'] = data_to_gpu(data['L'])[0]\n\n with torch.no_grad():\n if self.model_conf.name == 'AdaLanczosNet':\n pred, _ = model(\n data['node_feat'],\n data['L'],\n label=data['label'],\n mask=data['node_mask'])\n elif self.model_conf.name == 'LanczosNet':\n pred, _ = model(\n data['node_feat'],\n data['L'],\n data['D'],\n data['V'],\n label=data['label'],\n mask=data['node_mask'])\n elif self.model_conf.name == 'GraphSAGE':\n pred, _ = model(\n data['node_feat'],\n data['nn_idx'],\n data['nonempty_mask'],\n label=data['label'],\n mask=data['node_mask'])\n elif self.model_conf.name == 'GPNN':\n pred, _ = model(\n data['node_feat'],\n data['L'],\n data['L_cluster'],\n data['L_cut'],\n label=data['label'],\n mask=data['node_mask'])\n else:\n pred, _ = model(\n data['node_feat'],\n data['L'],\n label=data['label'],\n mask=data['node_mask'])\n\n curr_loss = (\n pred - data['label']).abs().cpu().numpy() * self.const_factor\n val_loss += [curr_loss]\n\n val_loss = float(np.mean(np.concatenate(val_loss)))\n logger.info(\"Avg. Validation MAE = {}\".format(val_loss))\n self.writer.add_scalar('val_loss', val_loss, iter_count)\n results['val_loss'] += [val_loss]\n\n # save best model\n if val_loss < best_val_loss:\n best_val_loss = val_loss\n snapshot(\n model.module if self.use_gpu else model,\n optimizer,\n self.config,\n epoch + 1,\n tag='best')\n\n logger.info(\"Current Best Validation MAE = {}\".format(best_val_loss))\n\n # check early stop\n if early_stop.tick([val_loss]):\n snapshot(\n model.module if self.use_gpu else model,\n optimizer,\n self.config,\n epoch + 1,\n tag='last')\n self.writer.close()\n break\n\n # training\n model.train()\n lr_scheduler.step()\n for data in train_loader:\n optimizer.zero_grad()\n\n if self.use_gpu:\n data['node_feat'], data['node_mask'], data['label'] = data_to_gpu(\n data['node_feat'], data['node_mask'], data['label'])\n\n if self.model_conf.name == 'LanczosNet':\n data['L'], data['D'], data['V'] = data_to_gpu(\n data['L'], data['D'], data['V'])\n elif self.model_conf.name == 'GraphSAGE':\n data['nn_idx'], data['nonempty_mask'] = data_to_gpu(\n data['nn_idx'], data['nonempty_mask'])\n elif self.model_conf.name == 'GPNN':\n data['L'], data['L_cluster'], data['L_cut'] = data_to_gpu(\n data['L'], data['L_cluster'], data['L_cut'])\n else:\n data['L'] = data_to_gpu(data['L'])[0]\n\n if self.model_conf.name == 'AdaLanczosNet':\n _, train_loss = model(\n data['node_feat'],\n data['L'],\n label=data['label'],\n mask=data['node_mask'])\n elif self.model_conf.name == 'LanczosNet':\n _, train_loss = model(\n data['node_feat'],\n data['L'],\n data['D'],\n data['V'],\n label=data['label'],\n mask=data['node_mask'])\n elif self.model_conf.name == 'GraphSAGE':\n _, train_loss = model(\n data['node_feat'],\n data['nn_idx'],\n data['nonempty_mask'],\n label=data['label'],\n mask=data['node_mask'])\n elif self.model_conf.name == 'GPNN':\n _, train_loss = model(\n data['node_feat'],\n data['L'],\n data['L_cluster'],\n data['L_cut'],\n label=data['label'],\n mask=data['node_mask'])\n else:\n _, train_loss = model(\n data['node_feat'],\n data['L'],\n label=data['label'],\n mask=data['node_mask'])\n\n # assign gradient\n train_loss.backward()\n optimizer.step()\n train_loss = float(train_loss.data.cpu().numpy())\n self.writer.add_scalar('train_loss', train_loss, iter_count)\n results['train_loss'] += [train_loss]\n results['train_step'] += [iter_count]\n\n # display loss\n if (iter_count + 1) % self.train_conf.display_iter == 0:\n logger.info(\"Loss @ epoch {:04d} iteration {:08d} = {}\".format(\n epoch + 1, iter_count + 1, train_loss))\n\n iter_count += 1\n\n # snapshot model\n if (epoch + 1) % self.train_conf.snapshot_epoch == 0:\n logger.info(\"Saving Snapshot @ epoch {:04d}\".format(epoch + 1))\n snapshot(model.module\n if self.use_gpu else model, optimizer, self.config, epoch + 1)\n\n results['best_val_loss'] += [best_val_loss]\n pickle.dump(results,\n open(os.path.join(self.config.save_dir, 'train_stats.p'), 'wb'))\n self.writer.close()\n logger.info(\"Best Validation MAE = {}\".format(best_val_loss))\n\n return best_val_loss\n\n def test(self):\n test_dataset = eval(self.dataset_conf.loader_name)(\n self.config, split='test')\n # create data loader\n test_loader = torch.utils.data.DataLoader(\n test_dataset,\n batch_size=self.test_conf.batch_size,\n shuffle=False,\n num_workers=self.test_conf.num_workers,\n collate_fn=test_dataset.collate_fn,\n drop_last=False)\n\n # create models\n model = eval(self.model_conf.name)(self.config)\n load_model(model, self.test_conf.test_model)\n\n if self.use_gpu:\n model = nn.DataParallel(model, device_ids=self.gpus).cuda()\n\n model.eval()\n test_loss = []\n for data in tqdm(test_loader):\n if self.use_gpu:\n data['node_feat'], data['node_mask'], data['label'] = data_to_gpu(\n data['node_feat'], data['node_mask'], data['label'])\n\n if self.model_conf.name == 'LanczosNet':\n data['D'], data['V'] = data_to_gpu(data['D'], data['V'])\n elif self.model_conf.name == 'GraphSAGE':\n data['nn_idx'], data['nonempty_mask'] = data_to_gpu(\n data['nn_idx'], data['nonempty_mask'])\n elif self.model_conf.name == 'GPNN':\n data['L'], data['L_cluster'], data['L_cut'] = data_to_gpu(\n data['L'], data['L_cluster'], data['L_cut'])\n else:\n data['L'] = data_to_gpu(data['L'])[0]\n\n with torch.no_grad():\n if self.model_conf.name == 'AdaLanczosNet':\n pred, _ = model(\n data['node_feat'],\n data['L'],\n label=data['label'],\n mask=data['node_mask'])\n elif self.model_conf.name == 'LanczosNet':\n pred, _ = model(\n data['node_feat'],\n data['L'],\n data['D'],\n data['V'],\n label=data['label'],\n mask=data['node_mask'])\n elif self.model_conf.name == 'GraphSAGE':\n pred, _ = model(\n data['node_feat'],\n data['nn_idx'],\n data['nonempty_mask'],\n label=data['label'],\n mask=data['node_mask'])\n elif self.model_conf.name == 'GPNN':\n pred, _ = model(\n data['node_feat'],\n data['L'],\n data['L_cluster'],\n data['L_cut'],\n label=data['label'],\n mask=data['node_mask'])\n else:\n pred, _ = model(\n data['node_feat'],\n data['L'],\n label=data['label'],\n mask=data['node_mask'])\n\n curr_loss = (\n pred - data['label']).abs().cpu().numpy() * self.const_factor\n test_loss += [curr_loss]\n\n test_loss = float(np.mean(np.concatenate(test_loss)))\n logger.info(\"Test MAE = {}\".format(test_loss))\n\n return test_loss\n" ]
[ [ "torch.optim.lr_scheduler.MultiStepLR", "torch.optim.Adam", "torch.utils.data.DataLoader", "numpy.concatenate", "torch.no_grad", "torch.optim.SGD", "torch.nn.DataParallel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
zhuwenzhen/DomainBed
[ "e8e8ed831bf30887675e5b3a5117d9d66d0ee46f" ]
[ "domainbed/datasets.py" ]
[ "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\n\nimport os\nimport torch\nfrom PIL import Image, ImageFile\nfrom torchvision import transforms\nimport torchvision.datasets.folder\nfrom torch.utils.data import TensorDataset, Subset\nfrom torchvision.datasets import MNIST, ImageFolder\nfrom torchvision.transforms.functional import rotate\n\nfrom wilds.datasets.camelyon17_dataset import Camelyon17Dataset\nfrom wilds.datasets.fmow_dataset import FMoWDataset\n\nImageFile.LOAD_TRUNCATED_IMAGES = True\n\nDATASETS = [\n # Debug\n \"Debug28\",\n \"Debug224\",\n # Small images\n \"ColoredMNIST\",\n \"RotatedMNIST\",\n # Big images\n \"VLCS\",\n \"PACS\",\n \"OfficeHome\",\n \"TerraIncognita\",\n \"DomainNet\",\n \"SVIRO\",\n # WILDS datasets\n \"WILDSCamelyon\",\n \"WILDSFMoW\",\n]\n\n\ndef get_dataset_class(dataset_name):\n \"\"\"Return the dataset class with the given name.\"\"\"\n if dataset_name not in globals():\n raise NotImplementedError(\"Dataset not found: {}\".format(dataset_name))\n return globals()[dataset_name]\n\n\ndef num_environments(dataset_name):\n return len(get_dataset_class(dataset_name).ENVIRONMENTS)\n\n\nclass MultipleDomainDataset:\n N_STEPS = 5001 # Default, subclasses may override\n CHECKPOINT_FREQ = 100 # Default, subclasses may override\n N_WORKERS = 8 # Default, subclasses may override\n ENVIRONMENTS = None # Subclasses should override\n INPUT_SHAPE = None # Subclasses should override\n\n def __getitem__(self, index):\n return self.datasets[index]\n\n def __len__(self):\n return len(self.datasets)\n\n\nclass Debug(MultipleDomainDataset):\n def __init__(self, root, test_envs, hparams):\n super().__init__()\n self.input_shape = self.INPUT_SHAPE\n self.num_classes = 2\n self.datasets = []\n for _ in [0, 1, 2]:\n self.datasets.append(\n TensorDataset(\n torch.randn(16, *self.INPUT_SHAPE), torch.randint(0, self.num_classes, (16,))\n )\n )\n\n\nclass Debug28(Debug):\n INPUT_SHAPE = (3, 28, 28)\n ENVIRONMENTS = [\"0\", \"1\", \"2\"]\n\n\nclass Debug224(Debug):\n INPUT_SHAPE = (3, 224, 224)\n ENVIRONMENTS = [\"0\", \"1\", \"2\"]\n\n\nclass MultipleEnvironmentMNIST(MultipleDomainDataset):\n def __init__(self, root, environments, dataset_transform, input_shape, num_classes):\n super().__init__()\n if root is None:\n raise ValueError(\"Data directory not specified!\")\n\n original_dataset_tr = MNIST(root, train=True, download=True)\n original_dataset_te = MNIST(root, train=False, download=True)\n\n original_images = torch.cat((original_dataset_tr.data, original_dataset_te.data))\n\n original_labels = torch.cat((original_dataset_tr.targets, original_dataset_te.targets))\n\n shuffle = torch.randperm(len(original_images))\n\n original_images = original_images[shuffle]\n original_labels = original_labels[shuffle]\n\n self.datasets = []\n\n for i in range(len(environments)):\n images = original_images[i :: len(environments)]\n labels = original_labels[i :: len(environments)]\n self.datasets.append(dataset_transform(images, labels, environments[i]))\n\n self.input_shape = input_shape\n self.num_classes = num_classes\n\n\nclass ColoredMNIST(MultipleEnvironmentMNIST):\n ENVIRONMENTS = [\"+90%\", \"+80%\", \"-90%\"]\n\n def __init__(self, root, test_envs, hparams):\n super(ColoredMNIST, self).__init__(\n root,\n [0.1, 0.2, 0.9],\n self.color_dataset,\n (\n 2,\n 28,\n 28,\n ),\n 2,\n )\n\n self.input_shape = (\n 2,\n 28,\n 28,\n )\n self.num_classes = 2\n\n def color_dataset(self, images, labels, environment):\n # # Subsample 2x for computational convenience\n # images = images.reshape((-1, 28, 28))[:, ::2, ::2]\n # Assign a binary label based on the digit\n labels = (labels < 5).float()\n # Flip label with probability 0.25\n labels = self.torch_xor_(labels, self.torch_bernoulli_(0.25, len(labels)))\n\n # Assign a color based on the label; flip the color with probability e\n colors = self.torch_xor_(labels, self.torch_bernoulli_(environment, len(labels)))\n images = torch.stack([images, images], dim=1)\n # Apply the color to the image by zeroing out the other color channel\n images[torch.tensor(range(len(images))), (1 - colors).long(), :, :] *= 0\n\n x = images.float().div_(255.0)\n y = labels.view(-1).long()\n\n return TensorDataset(x, y)\n\n def torch_bernoulli_(self, p, size):\n return (torch.rand(size) < p).float()\n\n def torch_xor_(self, a, b):\n return (a - b).abs()\n\n\nclass RotatedMNIST(MultipleEnvironmentMNIST):\n ENVIRONMENTS = [\"0\", \"15\", \"30\", \"45\", \"60\", \"75\"]\n\n def __init__(self, root, test_envs, hparams):\n super(RotatedMNIST, self).__init__(\n root,\n [0, 15, 30, 45, 60, 75],\n self.rotate_dataset,\n (\n 1,\n 28,\n 28,\n ),\n 10,\n )\n\n def rotate_dataset(self, images, labels, angle):\n rotation = transforms.Compose(\n [\n transforms.ToPILImage(),\n transforms.Lambda(lambda x: rotate(x, angle, fill=(0,), resample=Image.BICUBIC)),\n transforms.ToTensor(),\n ]\n )\n\n x = torch.zeros(len(images), 1, 28, 28)\n for i in range(len(images)):\n x[i] = rotation(images[i])\n\n y = labels.view(-1)\n\n return TensorDataset(x, y)\n\n\nclass MultipleEnvironmentImageFolder(MultipleDomainDataset):\n def __init__(self, root, test_envs, augment, hparams):\n super().__init__()\n environments = [f.name for f in os.scandir(root) if f.is_dir()]\n environments = sorted(environments)\n\n transform = transforms.Compose(\n [\n transforms.Resize((224, 224)),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\n ]\n )\n\n augment_transform = transforms.Compose(\n [\n # transforms.Resize((224,224)),\n transforms.RandomResizedCrop(224, scale=(0.7, 1.0)),\n transforms.RandomHorizontalFlip(),\n transforms.ColorJitter(0.3, 0.3, 0.3, 0.3),\n transforms.RandomGrayscale(),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\n ]\n )\n\n self.datasets = []\n for i, environment in enumerate(environments):\n\n if augment and (i not in test_envs):\n env_transform = augment_transform\n else:\n env_transform = transform\n\n path = os.path.join(root, environment)\n env_dataset = ImageFolder(path, transform=env_transform)\n\n self.datasets.append(env_dataset)\n\n self.input_shape = (\n 3,\n 224,\n 224,\n )\n self.num_classes = len(self.datasets[-1].classes)\n\n\nclass VLCS(MultipleEnvironmentImageFolder):\n CHECKPOINT_FREQ = 300\n ENVIRONMENTS = [\"C\", \"L\", \"S\", \"V\"]\n\n def __init__(self, root, test_envs, hparams):\n self.dir = os.path.join(root, \"VLCS/\")\n super().__init__(self.dir, test_envs, hparams[\"data_augmentation\"], hparams)\n\n\nclass PACS(MultipleEnvironmentImageFolder):\n CHECKPOINT_FREQ = 300\n ENVIRONMENTS = [\"A\", \"C\", \"P\", \"S\"]\n\n def __init__(self, root, test_envs, hparams):\n self.dir = os.path.join(root, \"PACS/\")\n super().__init__(self.dir, test_envs, hparams[\"data_augmentation\"], hparams)\n\n\nclass DomainNet(MultipleEnvironmentImageFolder):\n CHECKPOINT_FREQ = 1000\n ENVIRONMENTS = [\"clip\", \"info\", \"paint\", \"quick\", \"real\", \"sketch\"]\n\n def __init__(self, root, test_envs, hparams):\n self.dir = os.path.join(root, \"domain_net/\")\n super().__init__(self.dir, test_envs, hparams[\"data_augmentation\"], hparams)\n\n\nclass OfficeHome(MultipleEnvironmentImageFolder):\n CHECKPOINT_FREQ = 300\n ENVIRONMENTS = [\"A\", \"C\", \"P\", \"R\"]\n\n def __init__(self, root, test_envs, hparams):\n self.dir = os.path.join(root, \"office_home/\")\n super().__init__(self.dir, test_envs, hparams[\"data_augmentation\"], hparams)\n\n\nclass TerraIncognita(MultipleEnvironmentImageFolder):\n CHECKPOINT_FREQ = 300\n ENVIRONMENTS = [\"L100\", \"L38\", \"L43\", \"L46\"]\n\n def __init__(self, root, test_envs, hparams):\n self.dir = os.path.join(root, \"terra_incognita/\")\n super().__init__(self.dir, test_envs, hparams[\"data_augmentation\"], hparams)\n\n\nclass SVIRO(MultipleEnvironmentImageFolder):\n CHECKPOINT_FREQ = 300\n ENVIRONMENTS = [\n \"aclass\",\n \"escape\",\n \"hilux\",\n \"i3\",\n \"lexus\",\n \"tesla\",\n \"tiguan\",\n \"tucson\",\n \"x5\",\n \"zoe\",\n ]\n\n def __init__(self, root, test_envs, hparams):\n self.dir = os.path.join(root, \"sviro/\")\n super().__init__(self.dir, test_envs, hparams[\"data_augmentation\"], hparams)\n\n\nclass WILDSEnvironment:\n def __init__(self, wilds_dataset, metadata_name, metadata_value, transform=None):\n self.name = metadata_name + \"_\" + str(metadata_value)\n\n metadata_index = wilds_dataset.metadata_fields.index(metadata_name)\n metadata_array = wilds_dataset.metadata_array\n subset_indices = torch.where(metadata_array[:, metadata_index] == metadata_value)[0]\n\n self.dataset = wilds_dataset\n self.indices = subset_indices\n self.transform = transform\n\n def __getitem__(self, i):\n x = self.dataset.get_input(self.indices[i])\n if type(x).__name__ != \"Image\":\n x = Image.fromarray(x)\n\n y = self.dataset.y_array[self.indices[i]]\n if self.transform is not None:\n x = self.transform(x)\n return x, y\n\n def __len__(self):\n return len(self.indices)\n\n\nclass WILDSDataset(MultipleDomainDataset):\n INPUT_SHAPE = (3, 224, 224)\n\n def __init__(self, dataset, metadata_name, test_envs, augment, hparams):\n super().__init__()\n\n transform = transforms.Compose(\n [\n transforms.Resize((224, 224)),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\n ]\n )\n\n augment_transform = transforms.Compose(\n [\n transforms.Resize((224, 224)),\n transforms.RandomResizedCrop(224, scale=(0.7, 1.0)),\n transforms.RandomHorizontalFlip(),\n transforms.ColorJitter(0.3, 0.3, 0.3, 0.3),\n transforms.RandomGrayscale(),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\n ]\n )\n\n self.datasets = []\n\n for i, metadata_value in enumerate(self.metadata_values(dataset, metadata_name)):\n if augment and (i not in test_envs):\n env_transform = augment_transform\n else:\n env_transform = transform\n\n env_dataset = WILDSEnvironment(dataset, metadata_name, metadata_value, env_transform)\n\n self.datasets.append(env_dataset)\n\n self.input_shape = (\n 3,\n 224,\n 224,\n )\n self.num_classes = dataset.n_classes\n\n def metadata_values(self, wilds_dataset, metadata_name):\n metadata_index = wilds_dataset.metadata_fields.index(metadata_name)\n metadata_vals = wilds_dataset.metadata_array[:, metadata_index]\n return sorted(list(set(metadata_vals.view(-1).tolist())))\n\n\nclass WILDSCamelyon(WILDSDataset):\n ENVIRONMENTS = [\"hospital_0\", \"hospital_1\", \"hospital_2\", \"hospital_3\", \"hospital_4\"]\n\n def __init__(self, root, test_envs, hparams):\n dataset = Camelyon17Dataset(root_dir=root)\n super().__init__(dataset, \"hospital\", test_envs, hparams[\"data_augmentation\"], hparams)\n\n\nclass WILDSFMoW(WILDSDataset):\n ENVIRONMENTS = [\"region_0\", \"region_1\", \"region_2\", \"region_3\", \"region_4\", \"region_5\"]\n\n def __init__(self, root, test_envs, hparams):\n dataset = FMoWDataset(root_dir=root)\n super().__init__(dataset, \"region\", test_envs, hparams[\"data_augmentation\"], hparams)\n" ]
[ [ "torch.randint", "torch.cat", "torch.randn", "torch.utils.data.TensorDataset", "torch.rand", "torch.where", "torch.stack" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
cemkaraoguz/reinforcement-learning-an-introduction-second-edition
[ "735bfa6b66ffb52b7cf03966164e7bc1755942de", "735bfa6b66ffb52b7cf03966164e7bc1755942de", "735bfa6b66ffb52b7cf03966164e7bc1755942de", "735bfa6b66ffb52b7cf03966164e7bc1755942de" ]
[ "chapter07/03_WindyGridWorld_nStepSARSA_OffPolicy.py", "chapter13/01_MountainCar.py", "chapter05/02_Blackjack_MCP_OffP.py", "chapter06/03_WindyGridWorld_Benchmark_alpha.py" ]
[ "'''\n03_WindyGridWorld_nStepSARSA_OffPolicy.py : n-step off-policy SARSA applied to Windy Grid World problem (Example 6.5)\n\nCem Karaoguz, 2020\nMIT License\n'''\n\nimport numpy as np\nimport pylab as pl\n\nfrom IRL.environments.Gridworlds import StochasticGridWorld\nfrom IRL.agents.TemporalDifferenceLearning import nStepOffPolicySARSA\nfrom IRL.utils.Policies import StochasticPolicy\nfrom IRL.utils.Helpers import runSimulation\n\ndef runExperiment(nEpisodes, env, agent, policy_behaviour, doUpdateBehaviourPolicy):\n reward_sums = []\n episodesvstimesteps = []\n timesteps = 0\n for e in range(nEpisodes):\n \n if(e%10==0):\n print(\"Episode : \", e)\n \n state = env.reset()\n action = policy_behaviour.sampleAction(state)\n done = False\n experiences = [{}]\n reward_sums.append(0.0)\n while not done:\n\n timesteps += 1\n \n experiences[-1]['state'] = state\n experiences[-1]['action'] = action\n experiences[-1]['done'] = done\n \n new_state, reward, done = env.step(action)\n \n #print(\"State:\", state, \"Action: \", env.actionMapping[action][1], \"Reward: \", reward, \"New state:\", new_state, \"done:\", done)\n \n new_action = policy_behaviour.sampleAction(new_state)\n \n xp = {}\n xp['state'] = new_state\n xp['reward'] = reward\n xp['done'] = done\n xp['action'] = new_action\n experiences.append(xp)\n \n agent.update(experiences[-2:], policy_behaviour)\n \n state = new_state\n action = new_action\n \n episodesvstimesteps.append([e,timesteps])\n reward_sums[-1] += reward\n \n if(doUpdateBehaviourPolicy):\n # update behaviour policy to be e-soft version of the target policy\n for idx_state in range(env.nStates):\n policy_behaviour.update(idx_state, agent.actionValueTable[idx_state,:])\n \n return reward_sums, np.array(episodesvstimesteps)\n\nif __name__==\"__main__\":\n\n exerciseID = 0\n nExperiments = 1\n nEpisodes = 800\n\n # Environment\n sizeX = 10\n sizeY = 7\n defaultReward = -1.0\n startStates = [(0,3)]\n terminalStates = [(7,3)]\n\n if exerciseID==0:\n # Example 6.5\n actionMapping = {0:(np.array([0,-1]), \"N\"), 1:(np.array([0,1]), \"S\"), 2:(np.array([1,0]), \"E\"), 3:(np.array([-1,0]), \"W\")}\n sigmaY_actionNoise = 0\n \n elif exerciseID==1:\n # Exercise 6.9 part 1\n actionMapping = {0:(np.array([0,-1]), \"N\"), 1:(np.array([0,1]), \"S\"), 2:(np.array([1,0]), \"E\"), 3:(np.array([-1,0]), \"W\"),\n 4:(np.array([1,-1]), \"NE\"), 5:(np.array([1,1]), \"SE\"), 6:(np.array([-1,-1]), \"NW\"), 7:(np.array([-1,1]), \"SW\")}\n \n # Example 6.5 and Exercise 6.9\n sigmaY_actionNoise = 0\n \n # Exercise 6.10\n sigmaY_actionNoise = 1\n \n else:\n # Exercise 6.9 part 2\n actionMapping = {0:(np.array([0,-1]), \"N\"), 1:(np.array([0,1]), \"S\"), 2:(np.array([1,0]), \"E\"), 3:(np.array([-1,0]), \"W\"),\n 4:(np.array([1,-1]), \"NE\"), 5:(np.array([1,1]), \"SE\"), 6:(np.array([-1,-1]), \"NW\"), 7:(np.array([-1,1]), \"SW\"), 8:(np.array([0,0]), \"0\")}\n sigmaY_actionNoise = 0\n\n actionNoiseParams = {}\n aux = [(x,y) for x in range(3,6) for y in range(0,7)]\n for pos in aux:\n actionNoiseParams[pos] = [0,-1,0,sigmaY_actionNoise]\n aux = [(x,y) for x in range(6,8) for y in range(0,7)]\n for pos in aux:\n actionNoiseParams[pos] = [0,-2,0,sigmaY_actionNoise]\n aux = [(8,y) for y in range(0,7)]\n for pos in aux:\n actionNoiseParams[pos] = [0,-1,0,sigmaY_actionNoise]\n \n # Agent\n alpha_nStepOPSARSA_1 = 0.1\n gamma_nStepOPSARSA_1 = 1.0\n n_nStepOPSARSA_1 = 1\n \n alpha_nStepOPSARSA_2 = 0.1\n gamma_nStepOPSARSA_2 = 1.0\n n_nStepOPSARSA_2 = 5 \n\n alpha_nStepOPSARSA_3 = 0.05\n gamma_nStepOPSARSA_3 = 1.0\n n_nStepOPSARSA_3 = 10\n \n # Policy\n doUpdateBehaviourPolicy = True\n epsilon_behaviourPolicy = 0.1\n \n env = StochasticGridWorld(sizeX, sizeY, actionNoiseParams=actionNoiseParams, startStates=startStates,\n defaultReward=defaultReward, terminalStates=terminalStates, actionMapping=actionMapping)\n\n env.printEnv()\n\n avg_reward_sums_nStepOPSARSA_1 = np.zeros(nEpisodes)\n avg_reward_sums_nStepOPSARSA_2 = np.zeros(nEpisodes)\n avg_reward_sums_nStepOPSARSA_3 = np.zeros(nEpisodes)\n for idx_experiment in range(1, nExperiments+1):\n \n print(\"Experiment : \", idx_experiment)\n \n agent_nStepOPSARSA_1 = nStepOffPolicySARSA(env.nStates, env.nActions, alpha_nStepOPSARSA_1, gamma_nStepOPSARSA_1, n_nStepOPSARSA_1)\n agent_nStepOPSARSA_2 = nStepOffPolicySARSA(env.nStates, env.nActions, alpha_nStepOPSARSA_2, gamma_nStepOPSARSA_2, n_nStepOPSARSA_2)\n agent_nStepOPSARSA_3 = nStepOffPolicySARSA(env.nStates, env.nActions, alpha_nStepOPSARSA_3, gamma_nStepOPSARSA_3, n_nStepOPSARSA_3)\n \n policy_behaviour = StochasticPolicy(env.nStates, env.nActions, policyUpdateMethod=\"esoft\", epsilon=epsilon_behaviourPolicy) \n reward_sums_nStepOPSARSA_1, evst_nStepOPSARSA_1 = runExperiment(nEpisodes, env, agent_nStepOPSARSA_1, policy_behaviour, doUpdateBehaviourPolicy)\n\n policy_behaviour = StochasticPolicy(env.nStates, env.nActions, policyUpdateMethod=\"esoft\", epsilon=epsilon_behaviourPolicy)\n reward_sums_nStepOPSARSA_2, evst_nStepOPSARSA_2 = runExperiment(nEpisodes, env, agent_nStepOPSARSA_2, policy_behaviour, doUpdateBehaviourPolicy)\n\n policy_behaviour = StochasticPolicy(env.nStates, env.nActions, policyUpdateMethod=\"esoft\", epsilon=epsilon_behaviourPolicy)\n reward_sums_nStepOPSARSA_3, evst_nStepOPSARSA_3 = runExperiment(nEpisodes, env, agent_nStepOPSARSA_3, policy_behaviour, doUpdateBehaviourPolicy)\n \n avg_reward_sums_nStepOPSARSA_1 = avg_reward_sums_nStepOPSARSA_1 + (1.0/idx_experiment)*(reward_sums_nStepOPSARSA_1 - avg_reward_sums_nStepOPSARSA_1)\n avg_reward_sums_nStepOPSARSA_2 = avg_reward_sums_nStepOPSARSA_2 + (1.0/idx_experiment)*(reward_sums_nStepOPSARSA_2 - avg_reward_sums_nStepOPSARSA_2)\n avg_reward_sums_nStepOPSARSA_3 = avg_reward_sums_nStepOPSARSA_3 + (1.0/idx_experiment)*(reward_sums_nStepOPSARSA_3 - avg_reward_sums_nStepOPSARSA_3)\n \n pl.figure()\n pl.plot(evst_nStepOPSARSA_1[:,1],evst_nStepOPSARSA_1[:,0], '-r', label=str(n_nStepOPSARSA_1)+' Step SARSA')\n pl.plot(evst_nStepOPSARSA_2[:,1],evst_nStepOPSARSA_2[:,0], '-g', label=str(n_nStepOPSARSA_2)+' Step SARSA')\n pl.plot(evst_nStepOPSARSA_3[:,1],evst_nStepOPSARSA_3[:,0], '-k', label=str(n_nStepOPSARSA_3)+' Step SARSA')\n pl.xlabel(\"Time steps\")\n pl.ylabel(\"Episodes\")\n pl.legend()\n pl.figure()\n pl.plot(avg_reward_sums_nStepOPSARSA_1, '-r', label=str(n_nStepOPSARSA_1)+' Step SARSA')\n pl.plot(avg_reward_sums_nStepOPSARSA_2, '-g', label=str(n_nStepOPSARSA_2)+' Step SARSA')\n pl.plot(avg_reward_sums_nStepOPSARSA_3, '-k', label=str(n_nStepOPSARSA_3)+' Step SARSA')\n pl.xlabel(\"Episodes\")\n pl.ylabel(\"Sum of reward during episodes\")\n pl.legend()\n pl.show()\n \n agents = [agent_nStepOPSARSA_1, agent_nStepOPSARSA_2, agent_nStepOPSARSA_3]\n for agent in agents:\n print(\"Policy for :\", agent.getName())\n env.printEnv(agent)\n\n for agent in agents:\n input(\"Press any key to simulate agent \"+agent.getName())\n agentHistory = runSimulation(env, agent) \n print(\"Simulation:\", agent.getName()) \n env.render(agentHistory)\n ", "'''\n01_MountainCar.py : Application of Actor-Critic methods to Mountain Car problem\n\nCem Karaoguz, 2020\nMIT License\n'''\n\nimport numpy as np\nimport pylab as pl\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom IRL.environments.Cars import MountainCar\nfrom IRL.agents.PolicyGradient import OneStepActorCritic, ActorCriticWithEligibilityTraces\nfrom IRL.utils.ApproximationFunctions import linearTransform, dLinearTransform, softmaxLinear, dLogSoftmaxLinear\nfrom IRL.utils.FeatureTransformations import tileCoding\nfrom IRL.utils.Helpers import runSimulation\n\ndef showCostToGo(agent, episode, nStates=20, doShowNow=False):\n state_pos = np.linspace(positionBounds[0], positionBounds[1],num=nStates)\n state_vel = np.linspace(velocityBounds[0], velocityBounds[1],num=nStates)\n cost_to_go = np.array([[-np.max(agent.getValue([p,v])) for p in state_pos] for v in state_vel])\n fig = pl.figure()\n ax = fig.add_subplot(111, projection='3d')\n (X, Y), Z = np.meshgrid(state_pos, state_vel), cost_to_go\n ax.set_xlabel('Position', fontsize=10)\n ax.set_ylabel('Velocity', fontsize=10)\n ax.set_zlabel('Cost-to-go', fontsize=10)\n ax.set_title(agent.getName()+\" Cost-to-go function in Episode \"+str(episode))\n ax.plot_surface(X, Y, Z)\n if doShowNow: pl.show()\n\ndef runExperiment(nEpisodes, env, agent, episodesToShowCostToGo, nStatesVis=50, doShowNow=False):\n nStepsPerEpisode = np.zeros(nEpisodes)\n for e in range(nEpisodes):\n \n if e%1==0:\n print(\"Episode : \", e)\n\n if e in episodesToShowCostToGo: showCostToGo(agent, e, nStatesVis, doShowNow)\n \n experiences = [{}]\n done = False\n state = env.reset()\n action = agent.selectAction(state)\n t = 0\n\n while not done: \n\n experiences[-1]['state'] = state\n experiences[-1]['action'] = action\n experiences[-1]['done'] = done\n\n new_state, reward, done = env.step(action)\n \n #print(\"Episode:\", e, \"State:\", state, \"Action: \", env.actionMapping[action][1], \"Reward: \", reward, \"New state:\", new_state, \"done:\", done)\n\n new_action = agent.selectAction(new_state)\n \n xp = {}\n xp['reward'] = reward\n xp['state'] = new_state\n xp['done'] = done\n xp['action'] = new_action\n experiences.append(xp)\n\n agent.update(experiences)\n \n state = new_state\n if(\"Expected\" in agent.getName()):\n action = agent.selectAction(new_state)\n else:\n action = new_action\n t += 1\n \n nStepsPerEpisode[e] = t\n \n return nStepsPerEpisode\n \nif __name__==\"__main__\":\n\n nEpisodes = 200\n episodesToShowCostToGo = [1, 10, 100, 199]\n \n # Environment\n positionBounds = [-1.2, 0.5]\n velocityBounds = [-0.07, 0.07]\n startPositionBounds = [-0.6, -0.4]\n env = MountainCar(positionBounds, velocityBounds, startPositionBounds)\n \n # Agents\n alpha_w = 0.5/8\n alpha_theta = 0.05\n gamma = 1.0\n lambd_w = 0.8\n lambd_theta = 0.8\n \n nActions = 3\n minStates = [positionBounds[0], velocityBounds[0]]\n maxStates = [positionBounds[1], velocityBounds[1]]\n nTilings = 8\n tilingOffsets = [[i, j] for i, j in zip(np.linspace(-0.4, 0.4,num=nTilings), np.linspace(-0.04, 0.04,num=nTilings))] # (idxTiling, dimState)\n tilingSize = [[8, 8] for _ in range(nTilings)] # (idxTiling, dimState)\n nParams_w = np.sum([np.prod(i) for i in tilingSize])\n approximationFunctionArgs = {'af':linearTransform, 'afd':dLinearTransform, 'ftf':tileCoding,\n 'minStates':minStates, 'maxStates':maxStates, 'nTilings':nTilings, \n 'tilingOffsets':tilingOffsets, 'tilingSize':tilingSize}\n\n nTilings_theta = 1\n tilingOffsets_theta = [[0, 0]] # (idxTiling, dimState)\n tilingSize_theta = [[8, 8] for _ in range(nTilings_theta)] # (idxTiling, dimState) \n nParams_theta = env.nActions * np.sum([np.prod(i) for i in tilingSize_theta])\n policyApproximationFunctionArgs = {'af':softmaxLinear, 'afd':dLogSoftmaxLinear, 'ftf':tileCoding,\n 'minStates':minStates, 'maxStates':maxStates, 'nTilings':nTilings_theta, \n 'tilingOffsets':tilingOffsets_theta, 'tilingSize':tilingSize_theta, 'nActions':env.nActions}\n\n agent_OSAC = OneStepActorCritic(alpha_w, alpha_theta, gamma, nParams_w, approximationFunctionArgs, \n nParams_theta, env.nActions, policyApproximationFunctionArgs)\n nStepsPerEpisode_OSAC = runExperiment(nEpisodes, env, agent_OSAC, episodesToShowCostToGo, doShowNow=False)\n \n agent_ACET = ActorCriticWithEligibilityTraces(alpha_w, alpha_theta, gamma, lambd_w, lambd_theta, nParams_w, approximationFunctionArgs,\n nParams_theta, env.nActions, policyApproximationFunctionArgs)\n nStepsPerEpisode_ACET = runExperiment(nEpisodes, env, agent_ACET, episodesToShowCostToGo, doShowNow=False)\n \n pl.figure()\n pl.plot(nStepsPerEpisode_OSAC, label=agent_OSAC.getName())\n pl.plot(nStepsPerEpisode_ACET, label=agent_ACET.getName())\n pl.xlabel('Episodes')\n pl.ylabel('Number of steps per episode')\n pl.legend()\n pl.show()\n \n for agent in [agent_OSAC, agent_ACET]:\n input(\"Press any key to simulate agent \"+agent.getName())\n agentHistory = runSimulation(env, agent, 500)", "'''\n02_Blackjack_MCP_OffP.py : Application of an off-policy Monte-Carlo method \nfor Blackjack prediction problem (Figure 5.1)\n\nCem Karaoguz, 2020\nMIT License\n'''\n\nimport numpy as np\nimport pylab as pl\nfrom mpl_toolkits.mplot3d import Axes3D\n\nfrom IRL.environments.Gambler import Blackjack\nfrom IRL.agents.MonteCarlo import MonteCarloOffPolicyPrediction\nfrom IRL.utils.Policies import StochasticPolicy\n\nif __name__==\"__main__\":\n\n nEpisodes = 500000\n\n # Agent\n gamma = 1.0\n \n env = Blackjack()\n agent = MonteCarloOffPolicyPrediction(env.nStates, env.nActions, gamma)\n policy_behaviour = StochasticPolicy(env.nStates, env.nActions)\n for i in range(env.nStatesPlayerSum-1, -1, -1):\n for j in range(env.nStatesDealerShowing):\n for k in [env.USABLE_ACE_YES, env.USABLE_ACE_NO]:\n idx_state = env.getLinearIndex(env.minPlayerSum+i, env.minDealerShowing+j, k)\n if(env.minPlayerSum+i<20):\n actionProb = np.zeros(env.nActions)\n actionProb[env.ACTION_HIT] = 1.0\n agent.policy.update(idx_state, actionProb)\n else:\n actionProb = np.zeros(env.nActions)\n actionProb[env.ACTION_STICK] = 1.0\n agent.policy.update(idx_state, actionProb)\n \n #env.printEnv()\n \n for e in range(nEpisodes):\n \n if(e%10000==0):\n print(\"Episode : \", e)\n\n experiences = [{}]\n state = env.reset()\n done = False\n while not done:\n \n action = policy_behaviour.sampleAction(state)\n \n experiences[-1]['state'] = state\n experiences[-1]['action'] = action\n experiences[-1]['done'] = done\n \n new_state, reward, done = env.step(action)\n\n #print(\"Episode : \", e, \" State : \", state, \" Action : \", action, \" Reward : \", reward, \" Next state : \", new_state)\n \n xp = {}\n xp['reward'] = reward\n xp['state'] = new_state\n xp['done'] = done\n experiences.append(xp)\n\n state = new_state\n \n agent.evaluate(experiences, policy_behaviour)\n\n value_usableace = np.zeros([env.nStatesPlayerSum, env.nStatesDealerShowing])\n value_nousableace = np.zeros([env.nStatesPlayerSum, env.nStatesDealerShowing])\n for i in range(env.nStatesPlayerSum-1, -1, -1):\n for j in range(env.nStatesDealerShowing):\n idx_usableace = env.getLinearIndex(env.minPlayerSum+i, env.minDealerShowing+j, env.USABLE_ACE_YES)\n idx_nousableace = env.getLinearIndex(env.minPlayerSum+i, env.minDealerShowing+j, env.USABLE_ACE_NO)\n value_usableace[j,i] = agent.getValue(idx_usableace)\n value_nousableace[j,i] = agent.getValue(idx_nousableace)\n \n X = np.arange(0, env.nStatesPlayerSum, 1)+12\n Y = np.arange(0, env.nStatesDealerShowing, 1)\n X, Y = np.meshgrid(X, Y)\n \n fig = pl.figure()\n ax = fig.add_subplot(111, projection='3d')\n surf = ax.plot_surface(X, Y, value_usableace, linewidth=0, antialiased=False)\n ax.set_zlim(-1.01, 1.01)\n ax.set_xlabel(\"Player sum\")\n ax.set_ylabel(\"Dealer showing\")\n ax.set_title(\"Usable Ace\")\n\n fig = pl.figure()\n ax = fig.add_subplot(111, projection='3d')\n surf = ax.plot_surface(X, Y, value_nousableace, linewidth=0, antialiased=False)\n ax.set_zlim(-1.01, 1.01)\n ax.set_xlabel(\"Player sum\")\n ax.set_ylabel(\"Dealer showing\")\n ax.set_title(\"No usable Ace\")\n \n pl.show()\n ", "'''\n03_WindyGridWorld_Benchmark_alpha.py : replication of Figure 6.3 with Windy Grid World example\n\nCem Karaoguz, 2020\nMIT License\n'''\n\nimport numpy as np\nimport pylab as pl\n\nfrom IRL.environments.Gridworlds import StochasticGridWorld\nfrom IRL.agents.TemporalDifferenceLearning import SARSA, QLearning, ExpectedSARSA, DoubleQLearning\n\ndef runExperiment(nEpisodes, env, agent):\n\n reward_sums = []\n episodesvstimesteps = []\n timesteps = 0\n for e in range(nEpisodes):\n \n if(e%50==0):\n print(\"Episode : \", e)\n \n state = env.reset()\n action = agent.selectAction(state) \n done = False\n reward_sums.append(0.0)\n while not done:\n\n timesteps += 1\n \n experiences = [{}]\n experiences[-1]['state'] = state\n experiences[-1]['action'] = action\n experiences[-1]['done'] = done\n \n new_state, reward, done = env.step(action)\n \n #print(\"State:\", state, \"Action: \", env.actionMapping[action][1], \"Reward: \", reward, \"New state:\", new_state)\n \n new_action = agent.selectAction(new_state)\n \n xp = {}\n xp['reward'] = reward\n xp['state'] = new_state\n xp['done'] = done\n xp['action'] = new_action\n experiences.append(xp)\n\n agent.update(experiences[-2:])\n \n state = new_state\n \n if(agent.getName()==\"SARSA\"):\n action = new_action\n else:\n action = agent.selectAction(state)\n \n episodesvstimesteps.append([e,timesteps])\n reward_sums[-1] += reward\n \n return reward_sums, np.array(episodesvstimesteps)\n \nif __name__==\"__main__\":\n\n exerciseID = 0\n nExperimentsList = [5, 1]\n nEpisodesList = [100, 10000]\n\n # Environment\n sizeX = 10\n sizeY = 7\n defaultReward = -1.0\n startStates = [(0,3)]\n terminalStates= [(7,3)]\n\n if exerciseID==0:\n # Example 6.5\n actionMapping = {0:(np.array([0,-1]), \"N\"), 1:(np.array([0,1]), \"S\"), 2:(np.array([1,0]), \"E\"), 3:(np.array([-1,0]), \"W\")}\n sigmaY_actionNoise = 0\n \n elif exerciseID==1:\n # Exercise 6.9 part 1\n actionMapping = {0:(np.array([0,-1]), \"N\"), 1:(np.array([0,1]), \"S\"), 2:(np.array([1,0]), \"E\"), 3:(np.array([-1,0]), \"W\"),\n 4:(np.array([1,-1]), \"NE\"), 5:(np.array([1,1]), \"SE\"), 6:(np.array([-1,-1]), \"NW\"), 7:(np.array([-1,1]), \"SW\")}\n \n # Example 6.5 and Exercise 6.9\n sigmaY_actionNoise = 0\n \n # Exercise 6.10\n sigmaY_actionNoise = 1\n \n else:\n # Exercise 6.9 part 2\n actionMapping = {0:(np.array([0,-1]), \"N\"), 1:(np.array([0,1]), \"S\"), 2:(np.array([1,0]), \"E\"), 3:(np.array([-1,0]), \"W\"),\n 4:(np.array([1,-1]), \"NE\"), 5:(np.array([1,1]), \"SE\"), 6:(np.array([-1,-1]), \"NW\"), 7:(np.array([-1,1]), \"SW\"), 8:(np.array([0,0]), \"0\")}\n sigmaY_actionNoise = 0\n\n actionNoiseParams = {}\n aux = [(x,y) for x in range(3,6) for y in range(0,7)]\n for pos in aux:\n actionNoiseParams[pos] = [0,-1,0,sigmaY_actionNoise]\n aux = [(x,y) for x in range(6,8) for y in range(0,7)]\n for pos in aux:\n actionNoiseParams[pos] = [0,-2,0,sigmaY_actionNoise]\n aux = [(8,y) for y in range(0,7)]\n for pos in aux:\n actionNoiseParams[pos] = [0,-1,0,sigmaY_actionNoise]\n \n # Agent\n alphas = np.arange(0.1,1.01,0.1)\n gamma_SARSA = 1.0\n gamma_QLearning = 1.0 \n gamma_ExpectedSARSA = 1.0\n gamma_DoubleQLearning = 1.0 \n \n # Policy\n epsilon_SARSA = 0.1\n epsilon_QLearning = 0.1\n epsilon_ExpectedSARSA = 0.1\n epsilon_DoubleQLearning = 0.1\n \n env = StochasticGridWorld(sizeX, sizeY, actionNoiseParams=actionNoiseParams, startStates=startStates,\n defaultReward=defaultReward, terminalStates=terminalStates, actionMapping=actionMapping)\n\n env.printEnv()\n\n avg_reward_sums_SARSA = np.zeros([len(alphas),len(nEpisodesList)])\n avg_reward_sums_QLearning = np.zeros([len(alphas),len(nEpisodesList)])\n avg_reward_sums_ExpectedSARSA = np.zeros([len(alphas),len(nEpisodesList)])\n avg_reward_sums_DoubleQLearning = np.zeros([len(alphas),len(nEpisodesList)])\n for idx_alpha, alpha in enumerate(alphas):\n for idx_nEpisodes, nEpisodes in enumerate(nEpisodesList):\n \n nExperiments = nExperimentsList[idx_nEpisodes]\n \n for idx_experiment in range(1, nExperiments+1):\n \n print(\"Alpha:\", alpha, \"nEpisodes:\", nEpisodes, \"Experiment : \", idx_experiment)\n \n agent_SARSA = SARSA(env.nStates, env.nActions, alpha, gamma_SARSA, epsilon=epsilon_SARSA)\n agent_QLearning = QLearning(env.nStates, env.nActions, alpha, gamma_QLearning, epsilon=epsilon_QLearning)\n agent_ExpectedSARSA = ExpectedSARSA(env.nStates, env.nActions, alpha, gamma_ExpectedSARSA, epsilon=epsilon_ExpectedSARSA)\n agent_DoubleQLearning = DoubleQLearning(env.nStates, env.nActions, alpha, gamma_DoubleQLearning, epsilon=epsilon_DoubleQLearning)\n \n reward_sums_SARSA, evst_SARSA = runExperiment(nEpisodes, env, agent_SARSA)\n reward_sums_QLearning, evst_QLearning = runExperiment(nEpisodes, env, agent_QLearning)\n reward_sums_ExpectedSARSA, evst_ExpectedSARSA = runExperiment(nEpisodes, env, agent_ExpectedSARSA)\n reward_sums_DoubleQLearning, evst_DoubleQLearning = runExperiment(nEpisodes, env, agent_DoubleQLearning)\n \n avg_reward_sums_SARSA[idx_alpha, idx_nEpisodes] = avg_reward_sums_SARSA[idx_alpha, idx_nEpisodes] + (1.0/idx_experiment)*(np.sum(reward_sums_SARSA)/nEpisodes - avg_reward_sums_SARSA[idx_alpha, idx_nEpisodes])\n avg_reward_sums_QLearning[idx_alpha, idx_nEpisodes] = avg_reward_sums_QLearning[idx_alpha, idx_nEpisodes] + (1.0/idx_experiment)*(np.sum(reward_sums_QLearning)/nEpisodes - avg_reward_sums_QLearning[idx_alpha, idx_nEpisodes])\n avg_reward_sums_ExpectedSARSA[idx_alpha, idx_nEpisodes] = avg_reward_sums_ExpectedSARSA[idx_alpha, idx_nEpisodes] + (1.0/idx_experiment)*(np.sum(reward_sums_ExpectedSARSA)/nEpisodes - avg_reward_sums_ExpectedSARSA[idx_alpha, idx_nEpisodes])\n avg_reward_sums_DoubleQLearning[idx_alpha, idx_nEpisodes] = avg_reward_sums_DoubleQLearning[idx_alpha, idx_nEpisodes] + (1.0/idx_experiment)*(np.sum(reward_sums_DoubleQLearning)/nEpisodes - avg_reward_sums_DoubleQLearning[idx_alpha, idx_nEpisodes])\n \n fig, ax = pl.subplots()\n ax.plot(avg_reward_sums_SARSA[:,0], '--bv', label='SARSA')\n ax.plot(avg_reward_sums_QLearning[:,0], '--ks', label='Q-Learning')\n ax.plot(avg_reward_sums_ExpectedSARSA[:,0], '--rx', label='Expected SARSA')\n ax.plot(avg_reward_sums_DoubleQLearning[:,0], '--g', label='Double Q-Learning')\n ax.plot(avg_reward_sums_SARSA[:,1], '-bv', label='SARSA')\n ax.plot(avg_reward_sums_QLearning[:,1], '-ks', label='Q-Learning')\n ax.plot(avg_reward_sums_ExpectedSARSA[:,1], '-rx', label='Expected SARSA')\n ax.plot(avg_reward_sums_DoubleQLearning[:,1], '-g', label='Double Q-Learning')\n ax.set_xlabel(\"Alpha\")\n ax.set_ylabel(\"Sum of rewards per episode\")\n ax.set_xticks(range(len(alphas)))\n ax.set_xticklabels([str(np.round(i,1)) for i in alphas])\n pl.legend() \n pl.show()\n \n agents = [agent_SARSA, agent_QLearning, agent_ExpectedSARSA, agent_DoubleQLearning]\n for agent in agents:\n print(\"Policy for :\", agent.getName())\n env.printEnv(agent)\n " ]
[ [ "numpy.array", "numpy.zeros" ], [ "numpy.prod", "numpy.meshgrid", "numpy.zeros", "numpy.linspace" ], [ "numpy.arange", "numpy.meshgrid", "numpy.zeros" ], [ "numpy.round", "numpy.arange", "numpy.array", "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
rcooke-ast/PYPIT
[ "0cb9c4cb422736b855065a35aefc2bdba6d51dd0" ]
[ "pypeit/tests/test_match.py" ]
[ "\"\"\"\nModule to run tests on sort and arsetup\n\"\"\"\nfrom IPython import embed\n\nimport pytest\n\nimport numpy as np\n\nfrom pypeit.core import framematch\nfrom pypeit.tests.tstutils import dummy_fitstbl\nfrom pypeit.pypmsgs import PypeItError\n\n\[email protected]\ndef fitstbl():\n return dummy_fitstbl()\n\n\ndef test_frame_selection(fitstbl):\n \"\"\" Test that the frame bits are successfully read\n \"\"\"\n # Sort\n assert fitstbl.find_frames('bias')[0]\n assert fitstbl.find_frames('arc')[1]\n assert fitstbl.find_frames('trace')[2]\n assert fitstbl.find_frames('standard')[4]\n assert np.sum(fitstbl.find_frames('science')) == 5\n\n\ndef test_calibration_groups(fitstbl):\n \"\"\"\n Test the frame selection specific to a provided calibration group\n \"\"\"\n calib_ID = 0\n par = fitstbl.spectrograph.default_pypeit_par()\n assert fitstbl.find_frames('arc', calib_ID=calib_ID, index=True)[0] == 1\n assert fitstbl.find_frames('standard', calib_ID=calib_ID, index=True)[0] == 4\n assert fitstbl.find_frames('trace', calib_ID=calib_ID, index=True)[0] == 2\n\n\n# TODO: This doesn't test anything\n#def test_neg_match_science(fitstbl):\n# \"\"\" Test using negative number for calibs\n# \"\"\"\n# par = fitstbl.spectrograph.default_pypeit_par()\n# # Use negative number\n# for ftype in ['arc', 'pixelflat', 'bias']:\n# par['calibrations']['{0}frame'.format(ftype)]['number'] = 1\n# par['calibrations']['traceframe']['number'] = -1\n# fitstbl.match_to_science(par['calibrations'], par['rdx']['calwin'], par['fluxcalib'])\n# assert np.sum(fitstbl.find_frames('trace')) == 2\n\n\n# TODO: Need a function that checks the calibration groups have the\n# correct number of calibration frames\n#def test_match_science_errors(fitstbl):\n# par = fitstbl.spectrograph.default_pypeit_par()\n# par['calibrations']['traceframe']['number'] = 10\n# with pytest.raises(PypeItError):\n# fitstbl.match_to_science(par['calibrations'], par['rdx']['calwin'], par['fluxcalib'])\n\n\ndef test_instr_setup(fitstbl):\n \"\"\" Test instrument setup naming convention\n Tickles most of the arsetup methods\n \"\"\"\n par = fitstbl.spectrograph.default_pypeit_par()\n\n # Check the master key\n assert fitstbl.master_key(0) == 'A_1_DET01'\n # Invalid detector\n with pytest.raises(PypeItError):\n # Shane kast blue doesn't have a second detector\n fitstbl.master_key(0, det=2)\n\n\n# TODO: Need a test that adds a calibration group and checks the result\n# # New calib set\n# # Turn exposure 9 into an arc\n# fitstbl.edit_frame_type(-1, 'arc')\n# fitstbl['sci_ID'][-1] = 2\n# # Turn off other arc\n# fitstbl['sci_ID'][1] = 1 + 4 + 8\n# # Run\n# setupID3, setup_dict = pypsetup.instr_setup(2, 1, fitstbl, setup_dict=setup_dict)\n# assert setupID3 == 'A_01_ab'\n# assert setup_dict['A']['ab']['arc'][0] == 'b009.fits.gz'\n\n\ndef test_exptime():\n exptime = np.array([0, 30, None, 900])\n assert np.array_equal(framematch.check_frame_exptime(exptime, [0,None]),\n np.array([False, True, False, True]))\n assert np.array_equal(framematch.check_frame_exptime(exptime, [None,1000]),\n np.array([True, True, False, True]))\n assert np.array_equal(framematch.check_frame_exptime(exptime, [None,None]),\n np.array([True, True, False, True]))\n assert np.array_equal(framematch.check_frame_exptime(exptime, [None,500]),\n np.array([True, True, False, False]))\n assert np.array_equal(framematch.check_frame_exptime(exptime, [10,20]),\n np.array([False, False, False, False]))\n\n\n" ]
[ [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
frandorr/PROBA-V
[ "89c1aa4dfc58d66e7747293f6738fdd4e2ba6e6f" ]
[ "debug/main.py" ]
[ "from trainClass import *\nfrom utils.loss import *\nfrom utils.utils import *\nfrom modelsTF import *\nfrom tensorflow.keras.optimizers import Adam, SGD, Nadam\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.metrics import Mean\nimport tensorflow as tf\nimport numpy as np\nimport logging\nimport os\nimport gc\n\nlogging.basicConfig(format='%(asctime)s - %(message)s', level=logging.INFO)\nlogger = logging.getLogger('__name__')\n\n\ndef main():\n\n # import data\n CLEAN_DATA_DIR = '/home/mark/DataBank/PROBA-V-CHKPT/augmentedPatchesDir'\n band = 'NIR'\n X = np.load(os.path.join(CLEAN_DATA_DIR, f'TRAINpatchesLR_{band}.npy'), allow_pickle=True)\n y = np.load(os.path.join(CLEAN_DATA_DIR, f'TRAINpatchesHR_{band}.npy'), allow_pickle=True)\n\n print(f'Input shape: {X.shape} --------> Output shape: {y.shape}')\n X_train, X_val, y_train, y_val, y_train_mask, y_val_mask = train_test_split(\n X, y, ~y.mask, test_size=0.3, random_state=17)\n\n X_train = tf.convert_to_tensor(X_train, dtype=tf.float32)\n X_val = tf.convert_to_tensor(X_val, dtype=tf.float32)\n y_train = tf.convert_to_tensor(y_train, dtype=tf.float32)\n y_val = tf.convert_to_tensor(y_val, dtype=tf.float32)\n y_train_mask = tf.convert_to_tensor(y_train_mask, dtype=tf.float32)\n y_val_mask = tf.convert_to_tensor(y_val_mask, dtype=tf.float32)\n\n y = [y_train, y_train_mask]\n valData = [X_val, y_val, y_val_mask]\n\n# model = WDSRConv3D(scale=3, numFilters=32, kernelSize=(3, 3, 3), numResBlocks=8,\n# expRate=8, decayRate=0.8, numImgLR=9, patchSizeLR=32, isGrayScale=True)\n with tf.device('/GPU:1'):\n model = WDSRConv3D(scale=3, numFilters=32, kernelSize=(3, 3, 3), numResBlocks=8,\n expRate=8, decayRate=0.8, numImgLR=9, patchSizeLR=38, isGrayScale=True)\n l = Losses()\n trainClass = ModelTrainer(model=model,\n loss=l.shiftCompensatedL1Loss,\n metric=l.shiftCompensatedcPSNR,\n optimizer=Nadam(learning_rate=5e-4),\n ckptDir=f'/home/mark/DataBank/ckpt_{band}_38',\n logDir=f'/home/mark/DataBank/logNewRed_{band}_38')\n del X\n gc.collect()\n\n trainClass.fitTrainData(X_train, y, 64, 10000, 512, valData, 1)\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "tensorflow.convert_to_tensor", "tensorflow.keras.optimizers.Nadam", "tensorflow.device", "sklearn.model_selection.train_test_split" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
Featuretools/featuretools
[ "365abd9519d2eec8eec75936644a7b865d4ef40a", "365abd9519d2eec8eec75936644a7b865d4ef40a" ]
[ "featuretools/tests/primitive_tests/test_distancetoholiday_primitive.py", "featuretools/tests/primitive_tests/test_primitive_utils.py" ]
[ "from datetime import datetime\n\nimport numpy as np\nimport pandas as pd\nimport pytest\n\nfrom featuretools.primitives.standard.datetime_transform_primitives import (\n DistanceToHoliday,\n)\n\n\ndef test_distanceholiday():\n distance_to_holiday = DistanceToHoliday(\"New Year's Day\")\n dates = pd.Series(\n [\n datetime(2010, 1, 1),\n datetime(2012, 5, 31),\n datetime(2017, 7, 31),\n datetime(2020, 12, 31),\n ]\n )\n\n expected = [0, -151, 154, 1]\n output = distance_to_holiday(dates).tolist()\n np.testing.assert_array_equal(output, expected)\n\n\ndef test_holiday_out_of_range():\n date_to_holiday = DistanceToHoliday(\"Boxing Day\", country=\"Canada\")\n\n array = pd.Series(\n [\n datetime(2010, 1, 1),\n datetime(2012, 5, 31),\n datetime(2017, 7, 31),\n datetime(2020, 12, 31),\n ]\n )\n answer = pd.Series([np.nan, 209, 148, np.nan])\n pd.testing.assert_series_equal(date_to_holiday(array), answer, check_names=False)\n\n\ndef test_unknown_country_error():\n error_text = r\"must be one of the available countries.*\"\n with pytest.raises(ValueError, match=error_text):\n DistanceToHoliday(\"Victoria Day\", country=\"UNK\")\n\n\ndef test_unknown_holiday_error():\n error_text = r\"must be one of the available holidays.*\"\n with pytest.raises(ValueError, match=error_text):\n DistanceToHoliday(\"Alteryx Day\")\n\n\ndef test_nat():\n date_to_holiday = DistanceToHoliday(\"New Year's Day\")\n case = pd.Series(\n [\n \"2010-01-01\",\n \"NaT\",\n \"2012-05-31\",\n \"NaT\",\n ]\n ).astype(\"datetime64\")\n answer = [0, np.nan, -151, np.nan]\n given_answer = date_to_holiday(case).astype(\"float\")\n np.testing.assert_array_equal(given_answer, answer)\n\n\ndef test_valid_country():\n distance_to_holiday = DistanceToHoliday(\"Victoria Day\", country=\"Canada\")\n case = pd.Series(\n [\n \"2010-01-01\",\n \"2012-05-31\",\n \"2017-07-31\",\n \"2020-12-31\",\n ]\n ).astype(\"datetime64\")\n answer = [143, -10, -70, 144]\n given_answer = distance_to_holiday(case).astype(\"float\")\n np.testing.assert_array_equal(given_answer, answer)\n\n\ndef test_with_timezone_aware_datetimes():\n df = pd.DataFrame(\n {\n \"non_timezone_aware_with_time\": pd.date_range(\n \"2018-07-03 09:00\", periods=3\n ),\n \"non_timezone_aware_no_time\": pd.date_range(\"2018-07-03\", periods=3),\n \"timezone_aware_with_time\": pd.date_range(\n \"2018-07-03 09:00\", periods=3\n ).tz_localize(tz=\"US/Eastern\"),\n \"timezone_aware_no_time\": pd.date_range(\n \"2018-07-03\", periods=3\n ).tz_localize(tz=\"US/Eastern\"),\n }\n )\n\n distance_to_holiday = DistanceToHoliday(\"Independence Day\", country=\"US\")\n expected = [1, 0, -1]\n for col in df.columns:\n actual = distance_to_holiday(df[col])\n np.testing.assert_array_equal(actual, expected)\n", "import os\n\nimport numpy as np\nimport pandas as pd\nimport pytest\n\nfrom featuretools import list_primitives\nfrom featuretools.primitives import (\n Age,\n Count,\n Day,\n GreaterThan,\n Haversine,\n Last,\n Max,\n Mean,\n Min,\n Mode,\n Month,\n MultiplyBoolean,\n NumCharacters,\n NumUnique,\n NumWords,\n PercentTrue,\n Skew,\n Std,\n Sum,\n Weekday,\n Year,\n get_aggregation_primitives,\n get_default_aggregation_primitives,\n get_default_transform_primitives,\n get_transform_primitives,\n)\nfrom featuretools.primitives.base import PrimitiveBase\nfrom featuretools.primitives.utils import (\n _apply_roll_with_offset_gap,\n _get_descriptions,\n _get_rolled_series_without_gap,\n _get_unique_input_types,\n _roll_series_with_gap,\n list_primitive_files,\n load_primitive_from_file,\n)\nfrom featuretools.tests.primitive_tests.utils import get_number_from_offset\nfrom featuretools.utils.gen_utils import Library\n\n\ndef test_list_primitives_order():\n df = list_primitives()\n all_primitives = get_transform_primitives()\n all_primitives.update(get_aggregation_primitives())\n\n for name, primitive in all_primitives.items():\n assert name in df[\"name\"].values\n row = df.loc[df[\"name\"] == name].iloc[0]\n actual_desc = _get_descriptions([primitive])[0]\n if actual_desc:\n assert actual_desc == row[\"description\"]\n assert row[\"dask_compatible\"] == (Library.DASK in primitive.compatibility)\n assert row[\"valid_inputs\"] == \", \".join(\n _get_unique_input_types(primitive.input_types)\n )\n assert row[\"return_type\"] == getattr(primitive.return_type, \"__name__\", None)\n\n types = df[\"type\"].values\n assert \"aggregation\" in types\n assert \"transform\" in types\n\n\ndef test_valid_input_types():\n actual = _get_unique_input_types(Haversine.input_types)\n assert actual == {\"<ColumnSchema (Logical Type = LatLong)>\"}\n actual = _get_unique_input_types(MultiplyBoolean.input_types)\n assert actual == {\n \"<ColumnSchema (Logical Type = Boolean)>\",\n \"<ColumnSchema (Logical Type = BooleanNullable)>\",\n }\n actual = _get_unique_input_types(Sum.input_types)\n assert actual == {\"<ColumnSchema (Semantic Tags = ['numeric'])>\"}\n\n\ndef test_descriptions():\n primitives = {\n NumCharacters: \"Calculates the number of characters in a string.\",\n Day: \"Determines the day of the month from a datetime.\",\n Last: \"Determines the last value in a list.\",\n GreaterThan: \"Determines if values in one list are greater than another list.\",\n }\n assert _get_descriptions(list(primitives.keys())) == list(primitives.values())\n\n\ndef test_get_default_aggregation_primitives():\n primitives = get_default_aggregation_primitives()\n expected_primitives = [\n Sum,\n Std,\n Max,\n Skew,\n Min,\n Mean,\n Count,\n PercentTrue,\n NumUnique,\n Mode,\n ]\n assert set(primitives) == set(expected_primitives)\n\n\ndef test_get_default_transform_primitives():\n primitives = get_default_transform_primitives()\n expected_primitives = [\n Age,\n Day,\n Year,\n Month,\n Weekday,\n Haversine,\n NumWords,\n NumCharacters,\n ]\n assert set(primitives) == set(expected_primitives)\n\n\[email protected]\ndef this_dir():\n return os.path.dirname(os.path.abspath(__file__))\n\n\[email protected]\ndef primitives_to_install_dir(this_dir):\n return os.path.join(this_dir, \"primitives_to_install\")\n\n\[email protected]\ndef bad_primitives_files_dir(this_dir):\n return os.path.join(this_dir, \"bad_primitive_files\")\n\n\ndef test_list_primitive_files(primitives_to_install_dir):\n files = list_primitive_files(primitives_to_install_dir)\n custom_max_file = os.path.join(primitives_to_install_dir, \"custom_max.py\")\n custom_mean_file = os.path.join(primitives_to_install_dir, \"custom_mean.py\")\n custom_sum_file = os.path.join(primitives_to_install_dir, \"custom_sum.py\")\n assert {custom_max_file, custom_mean_file, custom_sum_file}.issubset(set(files))\n\n\ndef test_load_primitive_from_file(primitives_to_install_dir):\n primitve_file = os.path.join(primitives_to_install_dir, \"custom_max.py\")\n primitive_name, primitive_obj = load_primitive_from_file(primitve_file)\n assert issubclass(primitive_obj, PrimitiveBase)\n\n\ndef test_errors_more_than_one_primitive_in_file(bad_primitives_files_dir):\n primitive_file = os.path.join(bad_primitives_files_dir, \"multiple_primitives.py\")\n error_text = \"More than one primitive defined in file {}\".format(primitive_file)\n with pytest.raises(RuntimeError) as excinfo:\n load_primitive_from_file(primitive_file)\n assert str(excinfo.value) == error_text\n\n\ndef test_errors_no_primitive_in_file(bad_primitives_files_dir):\n primitive_file = os.path.join(bad_primitives_files_dir, \"no_primitives.py\")\n error_text = \"No primitive defined in file {}\".format(primitive_file)\n with pytest.raises(RuntimeError) as excinfo:\n load_primitive_from_file(primitive_file)\n assert str(excinfo.value) == error_text\n\n\ndef test_get_rolled_series_without_gap(rolling_series_pd):\n # Data is daily, so number of rows should be number of days not included in the gap\n assert len(_get_rolled_series_without_gap(rolling_series_pd, \"11D\")) == 9\n assert len(_get_rolled_series_without_gap(rolling_series_pd, \"0D\")) == 20\n assert len(_get_rolled_series_without_gap(rolling_series_pd, \"48H\")) == 18\n assert len(_get_rolled_series_without_gap(rolling_series_pd, \"4H\")) == 19\n\n\ndef test_get_rolled_series_without_gap_not_uniform(rolling_series_pd):\n non_uniform_series = rolling_series_pd.iloc[[0, 2, 5, 6, 8, 9]]\n\n assert len(_get_rolled_series_without_gap(non_uniform_series, \"10D\")) == 0\n assert len(_get_rolled_series_without_gap(non_uniform_series, \"0D\")) == 6\n assert len(_get_rolled_series_without_gap(non_uniform_series, \"48H\")) == 4\n assert len(_get_rolled_series_without_gap(non_uniform_series, \"4H\")) == 5\n assert len(_get_rolled_series_without_gap(non_uniform_series, \"4D\")) == 3\n assert len(_get_rolled_series_without_gap(non_uniform_series, \"4D2H\")) == 2\n\n\ndef test_get_rolled_series_without_gap_empty_series(rolling_series_pd):\n empty_series = pd.Series()\n assert len(_get_rolled_series_without_gap(empty_series, \"1D\")) == 0\n assert len(_get_rolled_series_without_gap(empty_series, \"0D\")) == 0\n\n\ndef test_get_rolled_series_without_gap_large_bound(rolling_series_pd):\n assert len(_get_rolled_series_without_gap(rolling_series_pd, \"100D\")) == 0\n assert (\n len(\n _get_rolled_series_without_gap(\n rolling_series_pd.iloc[[0, 2, 5, 6, 8, 9]], \"20D\"\n )\n )\n == 0\n )\n\n\[email protected](\n \"window_length, gap\",\n [\n (3, 2),\n (3, 4), # gap larger than window\n (2, 0), # gap explicitly set to 0\n (\"3d\", \"2d\"), # using offset aliases\n (\"3d\", \"4d\"),\n (\"4d\", \"0d\"),\n ],\n)\ndef test_roll_series_with_gap(window_length, gap, rolling_series_pd):\n rolling_max = _roll_series_with_gap(rolling_series_pd, window_length, gap=gap).max()\n rolling_min = _roll_series_with_gap(rolling_series_pd, window_length, gap=gap).min()\n\n assert len(rolling_max) == len(rolling_series_pd)\n assert len(rolling_min) == len(rolling_series_pd)\n\n gap_num = get_number_from_offset(gap)\n window_length_num = get_number_from_offset(window_length)\n for i in range(len(rolling_series_pd)):\n start_idx = i - gap_num - window_length_num + 1\n\n if isinstance(gap, str):\n # No gap functionality is happening, so gap isn't taken account in the end index\n # it's like the gap is 0; it includes the row itself\n end_idx = i\n else:\n end_idx = i - gap_num\n\n # If start and end are negative, they're entirely before\n if start_idx < 0 and end_idx < 0:\n assert pd.isnull(rolling_max.iloc[i])\n assert pd.isnull(rolling_min.iloc[i])\n continue\n\n if start_idx < 0:\n start_idx = 0\n\n # Because the row values are a range from 0 to 20, the rolling min will be the start index\n # and the rolling max will be the end idx\n assert rolling_min.iloc[i] == start_idx\n assert rolling_max.iloc[i] == end_idx\n\n\[email protected](\"window_length\", [3, \"3d\"])\ndef test_roll_series_with_no_gap(window_length, rolling_series_pd):\n actual_rolling = _roll_series_with_gap(rolling_series_pd, window_length).mean()\n expected_rolling = rolling_series_pd.rolling(window_length, min_periods=1).mean()\n\n pd.testing.assert_series_equal(actual_rolling, expected_rolling)\n\n\[email protected](\n \"window_length, gap\",\n [\n (6, 2),\n (6, 0), # No gap - changes early values\n (\"6d\", \"0d\"), # Uses offset aliases\n (\"6d\", \"2d\"),\n ],\n)\ndef test_roll_series_with_gap_early_values(window_length, gap, rolling_series_pd):\n gap_num = get_number_from_offset(gap)\n window_length_num = get_number_from_offset(window_length)\n\n # Default min periods is 1 - will include all\n default_partial_values = _roll_series_with_gap(\n rolling_series_pd, window_length, gap=gap\n ).count()\n num_empty_aggregates = len(default_partial_values.loc[default_partial_values == 0])\n num_partial_aggregates = len(\n (default_partial_values.loc[default_partial_values != 0]).loc[\n default_partial_values < window_length_num\n ]\n )\n\n assert num_partial_aggregates == window_length_num - 1\n if isinstance(gap, str):\n # gap isn't handled, so we'll always at least include the row itself\n assert num_empty_aggregates == 0\n else:\n assert num_empty_aggregates == gap_num\n\n # Make min periods the size of the window\n no_partial_values = _roll_series_with_gap(\n rolling_series_pd, window_length, gap=gap, min_periods=window_length_num\n ).count()\n num_null_aggregates = len(no_partial_values.loc[pd.isna(no_partial_values)])\n num_partial_aggregates = len(\n no_partial_values.loc[no_partial_values < window_length_num]\n )\n\n # because we shift, gap is included as nan values in the series.\n # Count treats nans in a window as values that don't get counted,\n # so the gap rows get included in the count for whether a window has \"min periods\".\n # This is different than max, for example, which does not count nans in a window as values towards \"min periods\"\n assert num_null_aggregates == window_length_num - 1\n if isinstance(gap, str):\n # gap isn't handled, so we'll never have any partial aggregates\n assert num_partial_aggregates == 0\n else:\n assert num_partial_aggregates == gap_num\n\n\ndef test_roll_series_with_gap_nullable_types(rolling_series_pd):\n window_length = 3\n gap = 2\n # Because we're inserting nans, confirm that nullability of the dtype doesn't have an impact on the results\n nullable_series = rolling_series_pd.astype(\"Int64\")\n non_nullable_series = rolling_series_pd.astype(\"int64\")\n\n nullable_rolling_max = _roll_series_with_gap(\n nullable_series, window_length, gap=gap\n ).max()\n non_nullable_rolling_max = _roll_series_with_gap(\n non_nullable_series, window_length, gap=gap\n ).max()\n\n pd.testing.assert_series_equal(nullable_rolling_max, non_nullable_rolling_max)\n\n\ndef test_roll_series_with_gap_nullable_types_with_nans(rolling_series_pd):\n window_length = 3\n gap = 2\n nullable_floats = rolling_series_pd.astype(\"float64\").replace(\n {1: np.nan, 3: np.nan}\n )\n nullable_ints = nullable_floats.astype(\"Int64\")\n\n nullable_ints_rolling_max = _roll_series_with_gap(\n nullable_ints, window_length, gap=gap\n ).max()\n nullable_floats_rolling_max = _roll_series_with_gap(\n nullable_floats, window_length, gap=gap\n ).max()\n\n pd.testing.assert_series_equal(\n nullable_ints_rolling_max, nullable_floats_rolling_max\n )\n\n expected_early_values = [np.nan, np.nan, 0, 0, 2, 2, 4] + list(\n range(7 - gap, len(rolling_series_pd) - gap)\n )\n for i in range(len(rolling_series_pd)):\n actual = nullable_floats_rolling_max.iloc[i]\n expected = expected_early_values[i]\n\n if pd.isnull(actual):\n assert pd.isnull(expected)\n else:\n assert actual == expected\n\n\[email protected](\n \"window_length, gap\",\n [\n (\"3d\", \"2d\"),\n (\"3d\", \"4d\"),\n (\"4d\", \"0d\"),\n ],\n)\ndef test_apply_roll_with_offset_gap(window_length, gap, rolling_series_pd):\n def max_wrapper(sub_s):\n return _apply_roll_with_offset_gap(sub_s, gap, max, min_periods=1)\n\n rolling_max_obj = _roll_series_with_gap(rolling_series_pd, window_length, gap=gap)\n rolling_max_series = rolling_max_obj.apply(max_wrapper)\n\n def min_wrapper(sub_s):\n return _apply_roll_with_offset_gap(sub_s, gap, min, min_periods=1)\n\n rolling_min_obj = _roll_series_with_gap(rolling_series_pd, window_length, gap=gap)\n rolling_min_series = rolling_min_obj.apply(min_wrapper)\n\n assert len(rolling_max_series) == len(rolling_series_pd)\n assert len(rolling_min_series) == len(rolling_series_pd)\n\n gap_num = get_number_from_offset(gap)\n window_length_num = get_number_from_offset(window_length)\n for i in range(len(rolling_series_pd)):\n start_idx = i - gap_num - window_length_num + 1\n # Now that we have the _apply call, this acts as expected\n end_idx = i - gap_num\n\n # If start and end are negative, they're entirely before\n if start_idx < 0 and end_idx < 0:\n assert pd.isnull(rolling_max_series.iloc[i])\n assert pd.isnull(rolling_min_series.iloc[i])\n continue\n\n if start_idx < 0:\n start_idx = 0\n\n # Because the row values are a range from 0 to 20, the rolling min will be the start index\n # and the rolling max will be the end idx\n assert rolling_min_series.iloc[i] == start_idx\n assert rolling_max_series.iloc[i] == end_idx\n\n\[email protected](\n \"min_periods\",\n [1, 0, None],\n)\ndef test_apply_roll_with_offset_gap_default_min_periods(min_periods, rolling_series_pd):\n window_length = \"5d\"\n window_length_num = 5\n gap = \"3d\"\n gap_num = 3\n\n def count_wrapper(sub_s):\n return _apply_roll_with_offset_gap(sub_s, gap, len, min_periods=min_periods)\n\n rolling_count_obj = _roll_series_with_gap(rolling_series_pd, window_length, gap=gap)\n rolling_count_series = rolling_count_obj.apply(count_wrapper)\n\n # gap essentially creates a rolling series that has no elements; which should be nan\n # to differentiate from when a window only has null values\n num_empty_aggregates = rolling_count_series.isna().sum()\n num_partial_aggregates = len(\n (rolling_count_series.loc[rolling_count_series != 0]).loc[\n rolling_count_series < window_length_num\n ]\n )\n\n assert num_empty_aggregates == gap_num\n assert num_partial_aggregates == window_length_num - 1\n\n\[email protected](\n \"min_periods\",\n [2, 3, 4, 5],\n)\ndef test_apply_roll_with_offset_gap_min_periods(min_periods, rolling_series_pd):\n window_length = \"5d\"\n window_length_num = 5\n gap = \"3d\"\n gap_num = 3\n\n def count_wrapper(sub_s):\n return _apply_roll_with_offset_gap(sub_s, gap, len, min_periods=min_periods)\n\n rolling_count_obj = _roll_series_with_gap(rolling_series_pd, window_length, gap=gap)\n rolling_count_series = rolling_count_obj.apply(count_wrapper)\n\n # gap essentially creates rolling series that have no elements; which should be nan\n # to differentiate from when a window only has null values\n num_empty_aggregates = rolling_count_series.isna().sum()\n num_partial_aggregates = len(\n (rolling_count_series.loc[rolling_count_series != 0]).loc[\n rolling_count_series < window_length_num\n ]\n )\n\n assert num_empty_aggregates == min_periods - 1 + gap_num\n assert num_partial_aggregates == window_length_num - min_periods\n\n\ndef test_apply_roll_with_offset_gap_non_uniform():\n window_length = \"3d\"\n gap = \"3d\"\n # When the data isn't uniform, this impacts the number of values in each rolling window\n datetimes = (\n list(pd.date_range(start=\"2017-01-01\", freq=\"1d\", periods=7))\n + list(pd.date_range(start=\"2017-02-01\", freq=\"2d\", periods=7))\n + list(pd.date_range(start=\"2017-03-01\", freq=\"1d\", periods=7))\n )\n no_freq_series = pd.Series(range(len(datetimes)), index=datetimes)\n\n assert pd.infer_freq(no_freq_series.index) is None\n\n expected_series = pd.Series(\n [None, None, None, 1, 2, 3, 3]\n + [None, None, 1, 1, 1, 1, 1]\n + [None, None, None, 1, 2, 3, 3],\n index=datetimes,\n )\n\n def count_wrapper(sub_s):\n return _apply_roll_with_offset_gap(sub_s, gap, len, min_periods=1)\n\n rolling_count_obj = _roll_series_with_gap(no_freq_series, window_length, gap=gap)\n rolling_count_series = rolling_count_obj.apply(count_wrapper)\n\n pd.testing.assert_series_equal(rolling_count_series, expected_series)\n\n\ndef test_apply_roll_with_offset_data_frequency_higher_than_parameters_frequency():\n window_length = \"5D\" # 120 hours\n window_length_num = 5\n # In order for min periods to be the length of the window, we multiply 24hours*5\n min_periods = window_length_num * 24\n\n datetimes = list(pd.date_range(start=\"2017-01-01\", freq=\"1H\", periods=200))\n high_frequency_series = pd.Series(range(200), index=datetimes)\n\n # Check without gap\n gap = \"0d\"\n gap_num = 0\n\n def max_wrapper(sub_s):\n return _apply_roll_with_offset_gap(sub_s, gap, max, min_periods=min_periods)\n\n rolling_max_obj = _roll_series_with_gap(\n high_frequency_series, window_length, min_periods=min_periods, gap=gap\n )\n rolling_max_series = rolling_max_obj.apply(max_wrapper)\n\n assert rolling_max_series.isna().sum() == (min_periods - 1) + gap_num\n\n # Check with small gap\n gap = \"3H\"\n gap_num = 3\n\n def max_wrapper(sub_s):\n return _apply_roll_with_offset_gap(sub_s, gap, max, min_periods=min_periods)\n\n rolling_max_obj = _roll_series_with_gap(\n high_frequency_series, window_length, min_periods=min_periods, gap=gap\n )\n rolling_max_series = rolling_max_obj.apply(max_wrapper)\n\n assert rolling_max_series.isna().sum() == (min_periods - 1) + gap_num\n\n # Check with large gap - in terms of days, so we'll multiply by 24hours for number of nans\n gap = \"2D\"\n gap_num = 2\n\n def max_wrapper(sub_s):\n return _apply_roll_with_offset_gap(sub_s, gap, max, min_periods=min_periods)\n\n rolling_max_obj = _roll_series_with_gap(\n high_frequency_series, window_length, min_periods=min_periods, gap=gap\n )\n rolling_max_series = rolling_max_obj.apply(max_wrapper)\n\n assert rolling_max_series.isna().sum() == (min_periods - 1) + (gap_num * 24)\n\n\ndef test_apply_roll_with_offset_data_min_periods_too_big(rolling_series_pd):\n window_length = \"5D\"\n gap = \"2d\"\n\n # Since the data has a daily frequency, there will only be, at most, 5 rows in the window\n min_periods = 6\n\n def max_wrapper(sub_s):\n return _apply_roll_with_offset_gap(sub_s, gap, max, min_periods=min_periods)\n\n rolling_max_obj = _roll_series_with_gap(\n rolling_series_pd, window_length, min_periods=min_periods, gap=gap\n )\n rolling_max_series = rolling_max_obj.apply(max_wrapper)\n\n # The resulting series is comprised entirely of nans\n assert rolling_max_series.isna().sum() == len(rolling_series_pd)\n\n\ndef test_roll_series_with_gap_different_input_types_same_result_uniform(\n rolling_series_pd,\n):\n # Offset inputs will only produce the same results as numeric inputs\n # when the data has a uniform frequency\n offset_gap = \"2d\"\n offset_window_length = \"5d\"\n int_gap = 2\n int_window_length = 5\n\n # Rolling series' with matching input types\n expected_rolling_numeric = _roll_series_with_gap(\n rolling_series_pd, window_size=int_window_length, gap=int_gap\n ).max()\n\n def count_wrapper(sub_s):\n return _apply_roll_with_offset_gap(sub_s, offset_gap, max, min_periods=1)\n\n rolling_count_obj = _roll_series_with_gap(\n rolling_series_pd, window_size=offset_window_length, gap=offset_gap\n )\n expected_rolling_offset = rolling_count_obj.apply(count_wrapper)\n\n # confirm that the offset and gap results are equal to one another\n pd.testing.assert_series_equal(expected_rolling_numeric, expected_rolling_offset)\n\n # Rolling series' with mismatched input types\n mismatched_numeric_gap = _roll_series_with_gap(\n rolling_series_pd, window_size=offset_window_length, gap=int_gap\n ).max()\n # Confirm the mismatched results also produce the same results\n pd.testing.assert_series_equal(expected_rolling_numeric, mismatched_numeric_gap)\n\n\ndef test_roll_series_with_gap_incorrect_types(rolling_series_pd):\n error = \"Window length must be either an offset string or an integer.\"\n with pytest.raises(TypeError, match=error):\n _roll_series_with_gap(rolling_series_pd, window_size=4.2, gap=4)\n\n error = \"Gap must be either an offset string or an integer.\"\n with pytest.raises(TypeError, match=error):\n _roll_series_with_gap(rolling_series_pd, window_size=4, gap=4.2)\n\n\ndef test_roll_series_with_gap_negative_inputs(rolling_series_pd):\n error = \"Window length must be greater than zero.\"\n with pytest.raises(ValueError, match=error):\n _roll_series_with_gap(rolling_series_pd, window_size=-4, gap=4)\n\n error = \"Gap must be greater than or equal to zero.\"\n with pytest.raises(ValueError, match=error):\n _roll_series_with_gap(rolling_series_pd, window_size=4, gap=-4)\n\n\ndef test_roll_series_with_non_offset_string_inputs(rolling_series_pd):\n error = \"Cannot roll series. The specified gap, test, is not a valid offset alias.\"\n with pytest.raises(ValueError, match=error):\n _roll_series_with_gap(rolling_series_pd, window_size=\"4D\", gap=\"test\")\n\n error = \"Cannot roll series. The specified window length, test, is not a valid offset alias.\"\n with pytest.raises(ValueError, match=error):\n _roll_series_with_gap(rolling_series_pd, window_size=\"test\", gap=\"7D\")\n\n # Test mismatched types error\n error = (\n \"Cannot roll series with offset gap, 2d, and numeric window length, 7. \"\n \"If an offset alias is used for gap, the window length must also be defined as an offset alias. \"\n \"Please either change gap to be numeric or change window length to be an offset alias.\"\n )\n with pytest.raises(TypeError, match=error):\n _roll_series_with_gap(rolling_series_pd, window_size=7, gap=\"2d\").max()\n" ]
[ [ "numpy.testing.assert_array_equal", "pandas.Series", "pandas.date_range" ], [ "pandas.testing.assert_series_equal", "pandas.Series", "pandas.isnull", "pandas.date_range", "pandas.isna", "pandas.infer_freq" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "0.19", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.1", "1.5", "1.2", "0.24", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
Agirljustsayhello/nilmtk
[ "bf985f0f637460bd8df3bb1cbf17b81a20303826" ]
[ "nilmtk/disaggregate/hart_85.py" ]
[ "from __future__ import print_function, division\nfrom collections import OrderedDict, deque\nfrom datetime import datetime\nfrom warnings import warn\n\nimport pandas as pd\n\nfrom nilmtk.feature_detectors.cluster import hart85_means_shift_cluster\nfrom nilmtk.feature_detectors.steady_states import (\n find_steady_states_transients)\nfrom nilmtk.timeframe import merge_timeframes, TimeFrame\nfrom nilmtk.disaggregate import Disaggregator\n\n\n# Fix the seed for repeatability of experiments\nSEED = 42\nimport numpy as np\n\nnp.random.seed(SEED)\n\n\nclass MyDeque(deque):\n def popmiddle(self, pos):\n self.rotate(-pos)\n ret = self.popleft()\n self.rotate(pos)\n return ret\n\n\nclass PairBuffer(object):\n \"\"\"\n Attributes:\n * transitionList (list of tuples)\n * matchedPairs (dataframe containing matched pairs of transitions)\n \"\"\"\n\n def __init__(self, buffer_size, min_tolerance, percent_tolerance,\n large_transition, num_measurements):\n \"\"\"\n Parameters\n ----------\n buffer_size: int, optional\n size of the buffer to use for finding edges\n min_tolerance: int, optional\n variance in power draw allowed for pairing a match\n percent_tolerance: float, optional\n if transition is greater than large_transition, then use percent of large_transition\n large_transition: float, optional\n power draw of a Large transition\n num_measurements: int, optional\n 2 if only active power\n 3 if both active and reactive power\n \"\"\"\n # We use a deque here, because it allows us quick access to start and end popping\n # and additionally, we can set a maxlen which drops oldest items. This nicely\n # suits Hart's recomendation that the size should be tunable.\n self._buffer_size = buffer_size\n self._min_tol = min_tolerance\n self._percent_tol = percent_tolerance\n self._large_transition = large_transition\n self.transition_list = MyDeque([], maxlen=self._buffer_size)\n self._num_measurements = num_measurements\n if self._num_measurements == 3:\n # Both active and reactive power is available\n self.pair_columns = ['T1 Time', 'T1 Active', 'T1 Reactive',\n 'T2 Time', 'T2 Active', 'T2 Reactive']\n elif self._num_measurements == 2:\n # Only active power is available\n self.pair_columns = ['T1 Time', 'T1 Active',\n 'T2 Time', 'T2 Active']\n self.matched_pairs = pd.DataFrame(columns=self.pair_columns)\n\n def clean_buffer(self):\n # Remove any matched transactions\n for idx, entry in enumerate(self.transition_list):\n if entry[self._num_measurements]:\n self.transition_list.popmiddle(idx)\n self.clean_buffer()\n break\n # Remove oldest transaction if buffer cleaning didn't remove anything\n # if len(self.transitionList) == self._bufferSize:\n # self.transitionList.popleft()\n\n def add_transition(self, transition):\n # Check transition is as expected.\n assert isinstance(transition, (tuple, list))\n # Check that we have both active and reactive powers.\n assert len(transition) == self._num_measurements\n # Convert as appropriate\n if isinstance(transition, tuple):\n mtransition = list(transition)\n # Add transition to List of transitions (set marker as unpaired)\n mtransition.append(False)\n self.transition_list.append(mtransition)\n # checking for pairs\n # self.pairTransitions()\n # self.cleanBuffer()\n\n def pair_transitions(self):\n \"\"\"\n Hart 85, P 33.\n When searching the working buffer for pairs, the order in which \n entries are examined is very important. If an Appliance has \n on and off several times in succession, there can be many \n pairings between entries in the buffer. The algorithm must not\n allow an 0N transition to match an OFF which occurred at the end \n of a different cycle, so that only ON/OFF pairs which truly belong \n together are paired up. Otherwise the energy consumption of the \n appliance will be greatly overestimated. The most straightforward \n search procedures can make errors of this nature when faced with \n types of transition sequences.\n\n Hart 85, P 32.\n For the two-state load monitor, a pair is defined as two entries\n which meet the following four conditions:\n (1) They are on the same leg, or are both 240 V,\n (2) They are both unmarked, \n (3) The earlier has a positive real power component, and \n (4) When added together, they result in a vector in which the \n absolute value of the real power component is less than 35 \n Watts (or 3.5% of the real power, if the transitions are \n over 1000 W) and the absolute value of the reactive power \n component is less than 35 VAR (or 3.5%).\n\n ... the correct way to search the buffer is to start by checking \n elements which are close together in the buffer, and gradually \n increase the distance. First, adjacent elements are checked for \n pairs which meet all four requirements above; if any are found \n they are processed and marked. Then elements two entries apart \n are checked, then three, and so on, until the first and last \n element are checked...\n\n \"\"\"\n\n tlength = len(self.transition_list)\n pairmatched = False\n if tlength < 2:\n return pairmatched\n\n # Can we reduce the running time of this algorithm?\n # My gut feeling is no, because we can't re-order the list...\n # I wonder if we sort but then check the time... maybe. TO DO\n # (perhaps!).\n\n # Start the element distance at 1, go up to current length of buffer\n for eDistance in range(1, tlength):\n idx = 0\n while idx < tlength - 1:\n # We don't want to go beyond length of array\n compindex = idx + eDistance\n if compindex < tlength:\n val = self.transition_list[idx]\n # val[1] is the active power and\n # val[self._num_measurements] is match status\n if (val[1] > 0) and (val[self._num_measurements] is False):\n compval = self.transition_list[compindex]\n if compval[self._num_measurements] is False:\n # Add the two elements for comparison\n vsum = np.add(\n val[1:self._num_measurements],\n compval[1:self._num_measurements])\n # Set the allowable tolerance for reactive and\n # active\n matchtols = [self._min_tol, self._min_tol]\n for ix in range(1, self._num_measurements):\n matchtols[ix - 1] = self._min_tol if (max(np.fabs([val[ix], compval[ix]]))\n < self._large_transition) else (self._percent_tol\n * max(\n np.fabs([val[ix], compval[ix]])))\n if self._num_measurements == 3:\n condition = (np.fabs(vsum[0]) < matchtols[0]) and (\n np.fabs(vsum[1]) < matchtols[1])\n\n elif self._num_measurements == 2:\n condition = np.fabs(vsum[0]) < matchtols[0]\n\n if condition:\n # Mark the transition as complete\n self.transition_list[idx][\n self._num_measurements] = True\n self.transition_list[compindex][\n self._num_measurements] = True\n pairmatched = True\n\n # Append the OFF transition to the ON. Add to\n # dataframe.\n matchedpair = val[\n 0:self._num_measurements] + compval[0:self._num_measurements]\n self.matched_pairs.loc[\n len(self.matched_pairs)] = matchedpair\n\n # Iterate Index\n idx += 1\n else:\n break\n\n return pairmatched\n\n\nclass Hart85(Disaggregator):\n \"\"\"1 or 2 dimensional Hart 1985 algorithm.\n\n Attributes\n ----------\n model : dict\n Each key is either the instance integer for an ElecMeter,\n or a tuple of instances for a MeterGroup.\n Each value is a sorted list of power in different states.\n \"\"\"\n\n def __init__(self):\n self.model = {}\n self.MODEL_NAME = \"Hart85\"\n\n def train(self, metergroup, cols=[('power', 'active')],\n buffer_size=20, noise_level=70, state_threshold=15,\n min_tolerance=100, percent_tolerance=0.035,\n large_transition=1000, **kwargs):\n \"\"\"\n Train using Hart85. Places the learnt model in `model` attribute.\n\n Parameters\n ----------\n metergroup : a nilmtk.MeterGroup object\n cols: nilmtk.Measurement, should be one of the following\n [('power','active')]\n [('power','apparent')]\n [('power','reactive')]\n [('power','active'), ('power', 'reactive')]\n buffer_size: int, optional\n size of the buffer to use for finding edges\n min_tolerance: int, optional\n variance in power draw allowed for pairing a match\n percent_tolerance: float, optional\n if transition is greater than large_transition,\n then use percent of large_transition\n large_transition: float, optional\n power draw of a Large transition\n \"\"\"\n self.cols = cols\n self.state_threshold = state_threshold\n self.noise_level = noise_level\n [self.steady_states, self.transients] = find_steady_states_transients(\n metergroup, cols, noise_level, state_threshold, **kwargs)\n self.pair_df = self.pair(\n buffer_size, min_tolerance, percent_tolerance, large_transition)\n self.centroids = hart85_means_shift_cluster(self.pair_df, cols)\n\n def pair(self, buffer_size, min_tolerance, percent_tolerance,\n large_transition):\n subset = list(self.transients.itertuples())\n buffer = PairBuffer(\n min_tolerance=min_tolerance, buffer_size=buffer_size,\n percent_tolerance=percent_tolerance,\n large_transition=large_transition,\n num_measurements=len(self.transients.columns) + 1)\n for s in subset:\n # if len(buffer.transitionList) < bsize\n if len(buffer.transition_list) == buffer_size:\n buffer.clean_buffer()\n buffer.add_transition(s)\n buffer.pair_transitions()\n return buffer.matched_pairs\n\n def disaggregate_chunk(self, chunk, prev, transients):\n \"\"\"\n Parameters\n ----------\n chunk : pd.DataFrame\n mains power\n prev\n transients : returned by find_steady_state_transients\n\n Returns\n -------\n states : pd.DataFrame\n with same index as `chunk`.\n \"\"\"\n\n states = pd.DataFrame(\n -1, index=chunk.index, columns=self.centroids.index.values)\n for transient_tuple in transients.itertuples():\n if transient_tuple[0] < chunk.index[0]:\n # Transient occurs before chunk has started; do nothing\n pass\n elif transient_tuple[0] > chunk.index[-1]:\n # Transient occurs after chunk has ended; do nothing\n pass\n else:\n # Absolute value of transient\n abs_value = np.abs(transient_tuple[1:])\n positive = transient_tuple[1] > 0\n abs_value_transient_minus_centroid = pd.DataFrame(\n (self.centroids - abs_value).abs())\n if len(transient_tuple) == 2:\n # 1d data\n index_least_delta = (\n abs_value_transient_minus_centroid.idxmin().values[0])\n else:\n # 2d data.\n # Need to find absolute value before computing minimum\n columns = abs_value_transient_minus_centroid.columns\n abs_value_transient_minus_centroid[\"multidim\"] = (\n abs_value_transient_minus_centroid[columns[0]] ** 2\n +\n abs_value_transient_minus_centroid[columns[1]] ** 2)\n index_least_delta = (\n abs_value_transient_minus_centroid[\"multidim\"].argmin())\n if positive:\n # Turned on\n states.loc[transient_tuple[0]][index_least_delta] = 1\n else:\n # Turned off\n states.loc[transient_tuple[0]][index_least_delta] = 0\n prev = states.iloc[-1].to_dict()\n power_chunk_dict = self.assign_power_from_states(states, prev)\n return pd.DataFrame(power_chunk_dict, index=chunk.index)\n\n def assign_power_from_states(self, states_chunk, prev):\n di = {}\n ndim = len(self.centroids.columns)\n for appliance in states_chunk.columns:\n values = states_chunk[[appliance]].values.flatten()\n if ndim == 1:\n power = np.zeros(len(values), dtype=int)\n else:\n power = np.zeros((len(values), 2), dtype=int)\n # on = False\n i = 0\n while i < len(values) - 1:\n if values[i] == 1:\n # print(\"A\", values[i], i)\n on = True\n i = i + 1\n power[i] = self.centroids.ix[appliance].values\n while values[i] != 0 and i < len(values) - 1:\n # print(\"B\", values[i], i)\n power[i] = self.centroids.ix[appliance].values\n i = i + 1\n elif values[i] == 0:\n # print(\"C\", values[i], i)\n on = False\n i = i + 1\n power[i] = 0\n while values[i] != 1 and i < len(values) - 1:\n # print(\"D\", values[i], i)\n if ndim == 1:\n power[i] = 0\n else:\n power[i] = [0, 0]\n i = i + 1\n else:\n # print(\"E\", values[i], i)\n # Unknown state. If previously we know about this\n # appliance's state, we can\n # use that. Else, it defaults to 0\n if prev[appliance] == -1 or prev[appliance] == 0:\n # print(\"F\", values[i], i)\n on = False\n power[i] = 0\n while values[i] != 1 and i < len(values) - 1:\n # print(\"G\", values[i], i)\n if ndim == 1:\n power[i] = 0\n else:\n power[i] = [0, 0]\n i = i + 1\n else:\n # print(\"H\", values[i], i)\n on = True\n power[i] = self.centroids.ix[appliance].values\n while values[i] != 0 and i < len(values) - 1:\n # print(\"I\", values[i], i)\n power[i] = self.centroids.ix[appliance].values\n i = i + 1\n\n di[appliance] = power\n # print(power.sum())\n return di\n\n def disaggregate(self, mains, output_datastore, **load_kwargs):\n \"\"\"Disaggregate mains according to the model learnt previously.\n\n Parameters\n ----------\n mains : nilmtk.ElecMeter or nilmtk.MeterGroup\n output_datastore : instance of nilmtk.DataStore subclass\n For storing power predictions from disaggregation algorithm.\n sample_period : number, optional\n The desired sample period in seconds.\n **load_kwargs : key word arguments\n Passed to `mains.power_series(**kwargs)`\n \"\"\"\n load_kwargs = self._pre_disaggregation_checks(load_kwargs)\n\n load_kwargs.setdefault('sample_period', 60)\n load_kwargs.setdefault('sections', mains.good_sections())\n\n timeframes = []\n building_path = '/building{}'.format(mains.building())\n mains_data_location = building_path + '/elec/meter1'\n data_is_available = False\n\n [_, transients] = find_steady_states_transients(\n mains, cols=self.cols, state_threshold=self.state_threshold,\n noise_level=self.noise_level, **load_kwargs)\n\n # For now ignoring the first transient\n # transients = transients[1:]\n\n # Initially all appliances/meters are in unknown state (denoted by -1)\n prev = OrderedDict()\n learnt_meters = self.centroids.index.values\n for meter in learnt_meters:\n prev[meter] = -1\n\n timeframes = []\n # Now iterating over mains data and disaggregating chunk by chunk\n for chunk in mains.power_series(**load_kwargs):\n # Record metadata\n timeframes.append(chunk.timeframe)\n measurement = chunk.name\n power_df = self.disaggregate_chunk(\n chunk, prev, transients)\n\n cols = pd.MultiIndex.from_tuples([chunk.name])\n\n for meter in learnt_meters:\n data_is_available = True\n df = power_df[[meter]]\n df.columns = cols\n key = '{}/elec/meter{:d}'.format(building_path, meter + 2)\n output_datastore.append(key, df)\n\n output_datastore.append(key=mains_data_location,\n value=pd.DataFrame(chunk, columns=cols))\n\n if data_is_available:\n self._save_metadata_for_disaggregation(\n output_datastore=output_datastore,\n sample_period=load_kwargs['sample_period'],\n measurement=measurement,\n timeframes=timeframes,\n building=mains.building(),\n supervised=False,\n num_meters=len(self.centroids)\n )\n\n \"\"\"\n def export_model(self, filename):\n model_copy = {}\n for appliance, appliance_states in self.model.iteritems():\n model_copy[\n \"{}_{}\".format(appliance.name, appliance.instance)] = appliance_states\n j = json.dumps(model_copy)\n with open(filename, 'w+') as f:\n f.write(j)\n\n def import_model(self, filename):\n with open(filename, 'r') as f:\n temp = json.loads(f.read())\n for appliance, centroids in temp.iteritems():\n appliance_name = appliance.split(\"_\")[0].encode(\"ascii\")\n appliance_instance = int(appliance.split(\"_\")[1])\n appliance_name_instance = ApplianceID(\n appliance_name, appliance_instance)\n self.model[appliance_name_instance] = centroids\n \"\"\"\n" ]
[ [ "numpy.abs", "numpy.random.seed", "pandas.MultiIndex.from_tuples", "pandas.DataFrame", "numpy.add", "numpy.fabs" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "0.19", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] } ]
anderlli0053/SourceIO
[ "3c0c4839939ce698439987ac52154f89ee2f5341", "3c0c4839939ce698439987ac52154f89ee2f5341", "3c0c4839939ce698439987ac52154f89ee2f5341" ]
[ "library/goldsrc/mdl_v4/structs/model.py", "library/source1/mdl/structs/bone.py", "library/source1/bsp/lumps/displacement_lump.py" ]
[ "from typing import List\n\nimport numpy as np\n\nfrom .mesh import StudioMesh\nfrom .....library.utils.byte_io_mdl import ByteIO\n\n\nclass StudioModel:\n vertex_dtype = np.dtype([\n ('id', np.uint32, (1,)),\n ('pos', np.float32, (3,)),\n ])\n\n def __init__(self):\n self.name = ''\n self.unk_1 = 0\n self.unk_2 = 0\n self.bounding_radius = 0.0\n self.vertex_count = 0\n self.normal_count = 0\n self.mesh_count = 0\n\n self._vertices = np.array([])\n self._normals = np.array([])\n self.meshes: List[StudioMesh] = []\n\n @property\n def bone_vertex_info(self):\n return self._vertices['id'].flatten()\n\n @property\n def bone_normal_info(self):\n return self._normals['id'].flatten()\n\n @property\n def vertices(self):\n return self._vertices['pos']\n\n @property\n def normals(self):\n return self._normals['pos']\n\n def read(self, reader: ByteIO):\n self.name = reader.read_ascii_string(32)\n (self.unk_1, self.unk_2,\n self.bounding_radius,\n self.vertex_count,\n self.normal_count,\n self.mesh_count,\n ) = reader.read_fmt('2if3i')\n\n self._vertices = np.frombuffer(reader.read(16 * self.vertex_count), self.vertex_dtype)\n self._normals = np.frombuffer(reader.read(16 * self.normal_count), self.vertex_dtype)\n for _ in range(self.mesh_count):\n mesh = StudioMesh()\n mesh.read(reader)\n self.meshes.append(mesh)\n", "from enum import IntFlag, IntEnum\n\nimport numpy as np\n\nfrom . import Base\nfrom . import ByteIO\n\nfrom .axis_interp_rule import AxisInterpRule\nfrom .jiggle_bone import JiggleRule\nfrom .quat_interp_bone import QuatInterpRule\nfrom ....utils.math_utilities import quat_to_matrix\n\n\nclass BoneFlags(IntFlag):\n # BONE_CALCULATE_MASK = 0x1F\n PHYSICALLY_SIMULATED = 0x01 # bone is physically simulated when physics are active\n PHYSICS_PROCEDURAL = 0x02 # procedural when physics is active\n ALWAYS_PROCEDURAL = 0x04 # bone is always procedurally animated\n # bone aligns to the screen, not constrained in motion.\n SCREEN_ALIGN_SPHERE = 0x08\n # bone aligns to the screen, constrained by it's own axis.\n SCREEN_ALIGN_CYLINDER = 0x10\n\n # BONE_USED_MASK = 0x0007FF00\n USED_BY_ANYTHING = 0x0007FF00\n USED_BY_HITBOX = 0x00000100 # bone (or child) is used by a hit box\n # bone (or child) is used by an attachment point\n USED_BY_ATTACHMENT = 0x00000200\n USED_BY_VERTEX_MASK = 0x0003FC00\n # bone (or child) is used by the toplevel model via skinned vertex\n USED_BY_VERTEX_LOD0 = 0x00000400\n USED_BY_VERTEX_LOD1 = 0x00000800\n USED_BY_VERTEX_LOD2 = 0x00001000\n USED_BY_VERTEX_LOD3 = 0x00002000\n USED_BY_VERTEX_LOD4 = 0x00004000\n USED_BY_VERTEX_LOD5 = 0x00008000\n USED_BY_VERTEX_LOD6 = 0x00010000\n USED_BY_VERTEX_LOD7 = 0x00020000\n # bone is available for bone merge to occur against it\n USED_BY_BONE_MERGE = 0x00040000\n\n\nclass Contents(IntFlag):\n # EMPTY = 0 # No contents\n SOLID = 0x1 # an eye is never valid in a solid\n WINDOW = 0x2 # translucent, but not watery (glass)\n AUX = 0x4\n # alpha-tested \"grate\" textures. Bullets/sight pass through, but solids don't\n GRATE = 0x8\n SLIME = 0x10\n WATER = 0x20\n BLOCKLOS = 0x40 # block AI line of sight\n # things that cannot be seen through (may be non-solid though)\n OPAQUE = 0x80\n TESTFOGVOLUME = 0x100\n UNUSED = 0x200\n\n # unused\n # NOTE: If it's visible, grab from the top + update LAST_VISIBLE_CONTENTS\n # if not visible, then grab from the bottom.\n # OPAQUE + SURF_NODRAW count as OPAQUE (shadow-casting\n # toolsblocklight textures)\n BLOCKLIGHT = 0x400\n\n TEAM1 = 0x800 # per team contents used to differentiate collisions\n TEAM2 = 0x1000 # between players and objects on different teams\n\n # ignore OPAQUE on surfaces that have SURF_NODRAW\n IGNORE_NODRAW_OPAQUE = 0x2000\n\n # hits entities which are MOVETYPE_PUSH (doors, plats, etc.)\n MOVEABLE = 0x4000\n\n # remaining contents are non-visible, and don't eat brushes\n AREAPORTAL = 0x8000\n\n PLAYERCLIP = 0x10000\n MONSTERCLIP = 0x20000\n\n # currents can be added to any other contents, and may be mixed\n CURRENT_0 = 0x40000\n CURRENT_90 = 0x80000\n CURRENT_180 = 0x100000\n CURRENT_270 = 0x200000\n CURRENT_UP = 0x400000\n CURRENT_DOWN = 0x800000\n\n ORIGIN = 0x1000000 # removed before bsping an entity\n\n MONSTER = 0x2000000 # should never be on a brush, only in game\n DEBRIS = 0x4000000\n DETAIL = 0x8000000 # brushes to be added after vis leafs\n TRANSLUCENT = 0x10000000 # auto set if any surface has trans\n LADDER = 0x20000000\n HITBOX = 0x40000000 # use accurate hitboxes on trace\n\n # NOTE: These are stored in a short in the engine now. Don't use more\n # than 16 bits\n SURF_LIGHT = 0x0001 # value will hold the light strength\n # don't draw, indicates we should skylight + draw 2d sky but not draw the\n # 3D skybox\n SURF_SKY2D = 0x0002\n SURF_SKY = 0x0004 # don't draw, but add to skybox\n SURF_WARP = 0x0008 # turbulent water warp\n SURF_TRANS = 0x0010\n SURF_NOPORTAL = 0x0020 # the surface can not have a portal placed on it\n # FIXME: This is an xbox hack to work around elimination of trigger\n # surfaces, which breaks occluders\n SURF_TRIGGER = 0x0040\n SURF_NODRAW = 0x0080 # don't bother referencing the texture\n\n SURF_HINT = 0x0100 # make a primary bsp splitter\n\n SURF_SKIP = 0x0200 # completely ignore, allowing non-closed brushes\n SURF_NOLIGHT = 0x0400 # Don't calculate light\n SURF_BUMPLIGHT = 0x0800 # calculate three lightmaps for the surface for bumpmapping\n SURF_NOSHADOWS = 0x1000 # Don't receive shadows\n SURF_NODECALS = 0x2000 # Don't receive decals\n SURF_NOPAINT = SURF_NODECALS # the surface can not have paint placed on it\n SURF_NOCHOP = 0x4000 # Don't subdivide patches on this surface\n SURF_HITBOX = 0x8000 # surface is part of a hitbox\n\n\nclass ProceduralBoneType(IntEnum):\n AXISINTERP = 1\n QUATINTERP = 2\n AIMATBONE = 3\n AIMATATTACH = 4\n JIGGLE = 5\n\n\nclass BoneV36(Base):\n def __init__(self, bone_id: int):\n self.bone_id = bone_id\n self.name = \"\"\n self.parent_bone_index = 0\n self.bone_controller_index = []\n self.scale = 0\n self.position = []\n self.quat = []\n self.anim_channels = 0\n self.rotation = []\n self.position_scale = []\n self.rotation_scale = []\n self.pose_to_bone = []\n self.q_alignment = []\n self.flags = BoneFlags(0)\n self.procedural_rule_type = 0\n self.physics_bone_index = 0\n self.contents = Contents(0)\n self.surface_prop = ''\n\n self.procedural_rule = None\n\n @property\n def children(self):\n from ..v36.mdl_file import MdlV36\n mdl: MdlV36 = self.get_value(\"MDL\")\n childes = []\n if mdl.bones:\n bone_index = mdl.bones.index(self)\n for bone in mdl.bones:\n if bone.name == self.name:\n continue\n if bone.parent_bone_index == bone_index:\n childes.append(bone)\n return childes\n\n @property\n def matrix(self):\n r_matrix = quat_to_matrix(self.quat)\n tmp = np.identity(4)\n tmp[0, :3] = r_matrix[0]\n tmp[1, :3] = r_matrix[1]\n tmp[2, :3] = r_matrix[2]\n t_matrix = np.array([\n [1, 0, 0, self.position[0]],\n [0, 1, 0, self.position[1]],\n [0, 0, 1, self.position[2]],\n [0, 0, 0, 1],\n ], dtype=np.float32)\n\n return np.identity(4) @ t_matrix @ tmp\n\n @property\n def parent(self):\n from ..v36.mdl_file import MdlV36\n mdl: MdlV36 = self.get_value(\"MDL\")\n if mdl.bones and self.parent_bone_index != -1:\n return mdl.bones[self.parent_bone_index]\n return None\n\n def read(self, reader: ByteIO):\n entry = reader.tell()\n self.name = reader.read_source1_string(entry)\n self.parent_bone_index = reader.read_int32()\n self.bone_controller_index = reader.read_fmt('6f')\n self.position = reader.read_fmt('3f')\n self.rotation = reader.read_fmt('3f')\n self.position_scale = reader.read_fmt('3f')\n self.rotation_scale = reader.read_fmt('3f')\n\n self.pose_to_bone = np.array(reader.read_fmt('12f')).reshape((3, 4)).transpose()\n\n self.q_alignment = reader.read_fmt('4f')\n self.flags = BoneFlags(reader.read_uint32())\n self.procedural_rule_type = reader.read_uint32()\n procedural_rule_offset = reader.read_uint32()\n self.physics_bone_index = reader.read_uint32()\n self.surface_prop = reader.read_source1_string(entry)\n self.quat = reader.read_fmt('4f')\n self.contents = Contents(reader.read_uint32())\n reader.skip(3 * 4)\n\n if self.procedural_rule_type != 0 and procedural_rule_offset != 0:\n with reader.save_current_pos():\n reader.seek(entry + procedural_rule_offset)\n if self.procedural_rule_type == ProceduralBoneType.AXISINTERP:\n self.procedural_rule = AxisInterpRule()\n if self.procedural_rule_type == ProceduralBoneType.QUATINTERP:\n self.procedural_rule = QuatInterpRule()\n if self.procedural_rule_type == ProceduralBoneType.JIGGLE:\n self.procedural_rule = JiggleRule()\n if self.procedural_rule:\n self.procedural_rule.read(reader)\n\n\nclass BoneV49(BoneV36):\n\n def read(self, reader: ByteIO):\n entry = reader.tell()\n self.name = reader.read_source1_string(entry)\n self.parent_bone_index = reader.read_int32()\n self.bone_controller_index = reader.read_fmt('6f')\n self.position = reader.read_fmt('3f')\n self.quat = reader.read_fmt('4f')\n self.rotation = reader.read_fmt('3f')\n self.position_scale = reader.read_fmt('3f')\n self.rotation_scale = reader.read_fmt('3f')\n\n self.pose_to_bone = np.array(reader.read_fmt('12f')).reshape((3, 4)).transpose()\n\n self.q_alignment = reader.read_fmt('4f')\n self.flags = BoneFlags(reader.read_uint32())\n self.procedural_rule_type = reader.read_uint32()\n procedural_rule_offset = reader.read_uint32()\n self.physics_bone_index = reader.read_uint32()\n self.surface_prop = reader.read_source1_string(entry)\n self.contents = Contents(reader.read_uint32())\n if self.get_value('mdl_version') >= 44:\n _ = [reader.read_uint32() for _ in range(8)]\n if self.get_value('mdl_version') >= 53:\n reader.skip(4 * 7)\n\n if self.procedural_rule_type != 0 and procedural_rule_offset != 0:\n with reader.save_current_pos():\n reader.seek(entry + procedural_rule_offset)\n if self.procedural_rule_type == ProceduralBoneType.AXISINTERP:\n self.procedural_rule = AxisInterpRule()\n if self.procedural_rule_type == ProceduralBoneType.QUATINTERP:\n self.procedural_rule = QuatInterpRule()\n if self.procedural_rule_type == ProceduralBoneType.JIGGLE:\n self.procedural_rule = JiggleRule()\n if self.procedural_rule:\n self.procedural_rule.read(reader)\n", "from typing import List\n\nimport numpy as np\n\nfrom . import SteamAppId\nfrom .. import Lump, lump_tag\nfrom ..datatypes.displacement import DispInfo, VDispInfo\n\n\n@lump_tag(26, 'LUMP_DISPINFO')\nclass DispInfoLump(Lump):\n def __init__(self, bsp, lump_id):\n super().__init__(bsp, lump_id)\n self.infos: List[DispInfo] = []\n\n def parse(self):\n reader = self.reader\n while reader:\n self.infos.append(DispInfo(self, self._bsp).parse(reader))\n return self\n\n\n@lump_tag(26, 'LUMP_DISPINFO', steam_id=SteamAppId.VINDICTUS)\nclass VDispInfoLump(Lump):\n def __init__(self, bsp, lump_id):\n super().__init__(bsp, lump_id)\n self.infos: List[DispInfo] = []\n\n def parse(self):\n reader = self.reader\n while reader:\n self.infos.append(VDispInfo(self, self._bsp).parse(reader))\n return self\n\n\n@lump_tag(33, 'LUMP_DISP_VERTS')\nclass DispVert(Lump):\n dtype = np.dtype(\n [\n ('position', np.float32, (3,)),\n ('dist', np.float32, (1,)),\n ('alpha', np.float32, (1,)),\n\n ]\n )\n\n def __init__(self, bsp, lump_id):\n super().__init__(bsp, lump_id)\n self.vertices: np.ndarray = np.array(0, dtype=self.dtype)\n self.transformed_vertices = np.array((-1, 3))\n\n def parse(self):\n reader = self.reader\n self.vertices = np.frombuffer(reader.read(), self.dtype)\n\n self.transformed_vertices = self.vertices['position'] * self.vertices['dist']\n\n return self\n\n\n@lump_tag(61, 'LUMP_DISP_MULTIBLEND', bsp_version=20, steam_id=SteamAppId.BLACK_MESA)\n@lump_tag(63, 'LUMP_DISP_MULTIBLEND', bsp_version=21)\nclass DispMultiblend(Lump):\n dtype = np.dtype(\n [\n ('multiblend', np.float32, (4,)),\n ('alphablend', np.float32, (4,)),\n ('multiblend_colors', np.float32, (4, 3)),\n ]\n )\n\n def __init__(self, bsp, lump_id):\n super().__init__(bsp, lump_id)\n self.blends = np.ndarray([])\n\n def parse(self):\n reader = self.reader\n assert self._lump.size % self.dtype.itemsize == 0\n self.blends = np.frombuffer(reader.read(), self.dtype)\n return self\n" ]
[ [ "numpy.array", "numpy.dtype" ], [ "numpy.array", "numpy.identity" ], [ "numpy.array", "numpy.ndarray", "numpy.dtype" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
shuu-tatsu/subwordsLM
[ "baae8657e3cd2957689b2365155156cd9d18cad8" ]
[ "flair/models/language_model.py" ]
[ "import torch.nn as nn\nimport torch\nimport math\nfrom torch.autograd import Variable\nfrom typing import Dict, List\nfrom flair.data import Dictionary\n\n\nclass LanguageModel(nn.Module):\n \"\"\"Container module with an encoder, a recurrent module, and a decoder.\"\"\"\n\n def __init__(self,\n dictionary: Dictionary,\n is_forward_lm: bool,\n hidden_size: int,\n nlayers: int,\n embedding_size: int = 100,\n nout=None,\n dropout=0.5):\n\n super(LanguageModel, self).__init__()\n\n self.dictionary = dictionary\n self.is_forward_lm: bool = is_forward_lm\n\n self.dropout = dropout\n self.hidden_size = hidden_size\n self.embedding_size = embedding_size\n self.nlayers = nlayers\n\n self.drop = nn.Dropout(dropout)\n self.encoder = nn.Embedding(len(dictionary), embedding_size)\n\n if nlayers == 1:\n self.rnn = nn.LSTM(embedding_size, hidden_size, nlayers)\n else:\n self.rnn = nn.LSTM(embedding_size, hidden_size, nlayers, dropout=dropout)\n\n self.hidden = None\n\n self.nout = nout\n if nout is not None:\n self.proj = nn.Linear(hidden_size, nout)\n self.initialize(self.proj.weight)\n self.decoder = nn.Linear(nout, len(dictionary))\n else:\n self.proj = None\n self.decoder = nn.Linear(hidden_size, len(dictionary))\n\n self.init_weights()\n\n # auto-spawn on GPU if available\n if torch.cuda.is_available():\n self.cuda()\n\n\n def init_weights(self):\n initrange = 0.1\n self.encoder.weight.data.uniform_(-initrange, initrange)\n self.decoder.bias.data.fill_(0)\n self.decoder.weight.data.uniform_(-initrange, initrange)\n\n def set_hidden(self, hidden):\n self.hidden = hidden\n\n def forward(self, input, hidden, ordered_sequence_lengths=None):\n #import pdb; pdb.set_trace()\n encoded = self.encoder(input)\n emb = self.drop(encoded)\n\n output, hidden = self.rnn(emb, hidden)\n\n if self.proj is not None:\n output = self.proj(output)\n\n output = self.drop(output)\n\n decoded = self.decoder(output.view(output.size(0) * output.size(1), output.size(2)))\n\n return decoded.view(output.size(0), output.size(1), decoded.size(1)), output, hidden\n\n def init_hidden(self, bsz):\n #import pdb; pdb.set_trace()\n weight = next(self.parameters()).data\n return (Variable(weight.new(self.nlayers, bsz, self.hidden_size).zero_()),\n Variable(weight.new(self.nlayers, bsz, self.hidden_size).zero_()))\n\n def get_representation(self, strings: List[str], detach_from_lm=True):\n\n sequences_as_char_indices: List[List[int]] = []\n for string in strings:\n #char_indices = [self.dictionary.get_idx_for_item(char) for char in string]\n sub_tok = string.split('_') #add\n char_indices = [self.dictionary.get_idx_for_item(sub) for sub in sub_tok] #add\n sequences_as_char_indices.append(char_indices)\n\n batch = Variable(torch.LongTensor(sequences_as_char_indices).transpose(0, 1))\n\n if torch.cuda.is_available():\n batch = batch.cuda()\n\n hidden = self.init_hidden(len(strings))\n prediction, rnn_output, hidden = self.forward(batch, hidden)\n\n if detach_from_lm: rnn_output = self.repackage_hidden(rnn_output)\n\n return rnn_output\n\n def repackage_hidden(self, h):\n \"\"\"Wraps hidden states in new Variables, to detach them from their history.\"\"\"\n if type(h) == torch.Tensor:\n return Variable(h.data)\n else:\n return tuple(self.repackage_hidden(v) for v in h)\n\n def initialize(self, matrix):\n in_, out_ = matrix.size()\n stdv = math.sqrt(3. / (in_ + out_))\n matrix.data.uniform_(-stdv, stdv)\n\n @classmethod\n def load_language_model(cls, model_file):\n state = torch.load(model_file)\n model = LanguageModel(state['dictionary'],\n state['is_forward_lm'],\n state['hidden_size'],\n state['nlayers'],\n state['embedding_size'],\n state['nout'],\n state['dropout'])\n model.load_state_dict(state['state_dict'])\n model.eval()\n if torch.cuda.is_available():\n model.cuda()\n return model\n\n def save(self, file):\n model_state = {\n 'state_dict': self.state_dict(),\n 'dictionary': self.dictionary,\n 'is_forward_lm': self.is_forward_lm,\n 'hidden_size': self.hidden_size,\n 'nlayers': self.nlayers,\n 'embedding_size': self.embedding_size,\n 'nout': self.nout,\n 'dropout': self.dropout\n }\n torch.save(model_state, file, pickle_protocol=4)\n" ]
[ [ "torch.nn.Dropout", "torch.LongTensor", "torch.nn.LSTM", "torch.load", "torch.autograd.Variable", "torch.nn.Linear", "torch.cuda.is_available", "torch.save" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Santhanalakshmimano/SpeedBump_detection_usingCV
[ "7b68f260cf1351d757983a48c5a62e063df807c9", "7b68f260cf1351d757983a48c5a62e063df807c9", "7b68f260cf1351d757983a48c5a62e063df807c9", "7b68f260cf1351d757983a48c5a62e063df807c9", "7b68f260cf1351d757983a48c5a62e063df807c9", "7b68f260cf1351d757983a48c5a62e063df807c9" ]
[ "research/object_detection/anchor_generators/multiple_grid_anchor_generator.py", "research/object_detection/dataset_tools/create_oid_tf_record.py", "research/object_detection/utils/object_detection_evaluation.py", "research/object_detection/core/balanced_positive_negative_sampler.py", "research/object_detection/models/ssd_mobilenet_v2_feature_extractor_test.py", "research/object_detection/builders/dataset_builder.py" ]
[ "# 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\n\"\"\"Generates grid anchors on the fly corresponding to multiple CNN layers.\n\nGenerates grid anchors on the fly corresponding to multiple CNN layers as\ndescribed in:\n\"SSD: Single Shot MultiBox Detector\"\nWei Liu, Dragomir Anguelov, Dumitru Erhan, Christian Szegedy, Scott Reed,\nCheng-Yang Fu, Alexander C. Berg\n(see Section 2.2: Choosing scales and aspect ratios for default boxes)\n\"\"\"\n\nimport numpy as np\n\nimport tensorflow as tf\n\nfrom anchor_generators import grid_anchor_generator\nfrom core import anchor_generator\nfrom core import box_list_ops\n\n\nclass MultipleGridAnchorGenerator(anchor_generator.AnchorGenerator):\n \"\"\"Generate a grid of anchors for multiple CNN layers.\"\"\"\n\n def __init__(self,\n box_specs_list,\n base_anchor_size=None,\n anchor_strides=None,\n anchor_offsets=None,\n clip_window=None):\n \"\"\"Constructs a MultipleGridAnchorGenerator.\n\n To construct anchors, at multiple grid resolutions, one must provide a\n list of feature_map_shape_list (e.g., [(8, 8), (4, 4)]), and for each grid\n size, a corresponding list of (scale, aspect ratio) box specifications.\n\n For example:\n box_specs_list = [[(.1, 1.0), (.1, 2.0)], # for 8x8 grid\n [(.2, 1.0), (.3, 1.0), (.2, 2.0)]] # for 4x4 grid\n\n To support the fully convolutional setting, we pass grid sizes in at\n generation time, while scale and aspect ratios are fixed at construction\n time.\n\n Args:\n box_specs_list: list of list of (scale, aspect ratio) pairs with the\n outside list having the same number of entries as feature_map_shape_list\n (which is passed in at generation time).\n base_anchor_size: base anchor size as [height, width]\n (length-2 float tensor, default=[1.0, 1.0]).\n The height and width values are normalized to the\n minimum dimension of the input height and width, so that\n when the base anchor height equals the base anchor\n width, the resulting anchor is square even if the input\n image is not square.\n anchor_strides: list of pairs of strides in pixels (in y and x directions\n respectively). For example, setting anchor_strides=[(25, 25), (50, 50)]\n means that we want the anchors corresponding to the first layer to be\n strided by 25 pixels and those in the second layer to be strided by 50\n pixels in both y and x directions. If anchor_strides=None, they are set\n to be the reciprocal of the corresponding feature map shapes.\n anchor_offsets: list of pairs of offsets in pixels (in y and x directions\n respectively). The offset specifies where we want the center of the\n (0, 0)-th anchor to lie for each layer. For example, setting\n anchor_offsets=[(10, 10), (20, 20)]) means that we want the\n (0, 0)-th anchor of the first layer to lie at (10, 10) in pixel space\n and likewise that we want the (0, 0)-th anchor of the second layer to\n lie at (25, 25) in pixel space. If anchor_offsets=None, then they are\n set to be half of the corresponding anchor stride.\n clip_window: a tensor of shape [4] specifying a window to which all\n anchors should be clipped. If clip_window is None, then no clipping\n is performed.\n\n Raises:\n ValueError: if box_specs_list is not a list of list of pairs\n ValueError: if clip_window is not either None or a tensor of shape [4]\n \"\"\"\n if isinstance(box_specs_list, list) and all(\n [isinstance(list_item, list) for list_item in box_specs_list]):\n self._box_specs = box_specs_list\n else:\n raise ValueError('box_specs_list is expected to be a '\n 'list of lists of pairs')\n if base_anchor_size is None:\n base_anchor_size = tf.constant([256, 256], dtype=tf.float32)\n self._base_anchor_size = base_anchor_size\n self._anchor_strides = anchor_strides\n self._anchor_offsets = anchor_offsets\n if clip_window is not None and clip_window.get_shape().as_list() != [4]:\n raise ValueError('clip_window must either be None or a shape [4] tensor')\n self._clip_window = clip_window\n self._scales = []\n self._aspect_ratios = []\n for box_spec in self._box_specs:\n if not all([isinstance(entry, tuple) and len(entry) == 2\n for entry in box_spec]):\n raise ValueError('box_specs_list is expected to be a '\n 'list of lists of pairs')\n scales, aspect_ratios = zip(*box_spec)\n self._scales.append(scales)\n self._aspect_ratios.append(aspect_ratios)\n\n for arg, arg_name in zip([self._anchor_strides, self._anchor_offsets],\n ['anchor_strides', 'anchor_offsets']):\n if arg and not (isinstance(arg, list) and\n len(arg) == len(self._box_specs)):\n raise ValueError('%s must be a list with the same length '\n 'as self._box_specs' % arg_name)\n if arg and not all([\n isinstance(list_item, tuple) and len(list_item) == 2\n for list_item in arg\n ]):\n raise ValueError('%s must be a list of pairs.' % arg_name)\n\n def name_scope(self):\n return 'MultipleGridAnchorGenerator'\n\n def num_anchors_per_location(self):\n \"\"\"Returns the number of anchors per spatial location.\n\n Returns:\n a list of integers, one for each expected feature map to be passed to\n the Generate function.\n \"\"\"\n return [len(box_specs) for box_specs in self._box_specs]\n\n def _generate(self, feature_map_shape_list, im_height=1, im_width=1):\n \"\"\"Generates a collection of bounding boxes to be used as anchors.\n\n The number of anchors generated for a single grid with shape MxM where we\n place k boxes over each grid center is k*M^2 and thus the total number of\n anchors is the sum over all grids. In our box_specs_list example\n (see the constructor docstring), we would place two boxes over each grid\n point on an 8x8 grid and three boxes over each grid point on a 4x4 grid and\n thus end up with 2*8^2 + 3*4^2 = 176 anchors in total. The layout of the\n output anchors follows the order of how the grid sizes and box_specs are\n specified (with box_spec index varying the fastest, followed by width\n index, then height index, then grid index).\n\n Args:\n feature_map_shape_list: list of pairs of convnet layer resolutions in the\n format [(height_0, width_0), (height_1, width_1), ...]. For example,\n setting feature_map_shape_list=[(8, 8), (7, 7)] asks for anchors that\n correspond to an 8x8 layer followed by a 7x7 layer.\n im_height: the height of the image to generate the grid for. If both\n im_height and im_width are 1, the generated anchors default to\n absolute coordinates, otherwise normalized coordinates are produced.\n im_width: the width of the image to generate the grid for. If both\n im_height and im_width are 1, the generated anchors default to\n absolute coordinates, otherwise normalized coordinates are produced.\n\n Returns:\n boxes_list: a list of BoxLists each holding anchor boxes corresponding to\n the input feature map shapes.\n\n Raises:\n ValueError: if feature_map_shape_list, box_specs_list do not have the same\n length.\n ValueError: if feature_map_shape_list does not consist of pairs of\n integers\n \"\"\"\n if not (isinstance(feature_map_shape_list, list)\n and len(feature_map_shape_list) == len(self._box_specs)):\n raise ValueError('feature_map_shape_list must be a list with the same '\n 'length as self._box_specs')\n if not all([isinstance(list_item, tuple) and len(list_item) == 2\n for list_item in feature_map_shape_list]):\n raise ValueError('feature_map_shape_list must be a list of pairs.')\n\n im_height = tf.to_float(im_height)\n im_width = tf.to_float(im_width)\n\n if not self._anchor_strides:\n anchor_strides = [(1.0 / tf.to_float(pair[0]), 1.0 / tf.to_float(pair[1]))\n for pair in feature_map_shape_list]\n else:\n anchor_strides = [(tf.to_float(stride[0]) / im_height,\n tf.to_float(stride[1]) / im_width)\n for stride in self._anchor_strides]\n if not self._anchor_offsets:\n anchor_offsets = [(0.5 * stride[0], 0.5 * stride[1])\n for stride in anchor_strides]\n else:\n anchor_offsets = [(tf.to_float(offset[0]) / im_height,\n tf.to_float(offset[1]) / im_width)\n for offset in self._anchor_offsets]\n\n for arg, arg_name in zip([anchor_strides, anchor_offsets],\n ['anchor_strides', 'anchor_offsets']):\n if not (isinstance(arg, list) and len(arg) == len(self._box_specs)):\n raise ValueError('%s must be a list with the same length '\n 'as self._box_specs' % arg_name)\n if not all([isinstance(list_item, tuple) and len(list_item) == 2\n for list_item in arg]):\n raise ValueError('%s must be a list of pairs.' % arg_name)\n\n anchor_grid_list = []\n min_im_shape = tf.minimum(im_height, im_width)\n scale_height = min_im_shape / im_height\n scale_width = min_im_shape / im_width\n base_anchor_size = [\n scale_height * self._base_anchor_size[0],\n scale_width * self._base_anchor_size[1]\n ]\n for feature_map_index, (grid_size, scales, aspect_ratios, stride,\n offset) in enumerate(\n zip(feature_map_shape_list, self._scales,\n self._aspect_ratios, anchor_strides,\n anchor_offsets)):\n tiled_anchors = grid_anchor_generator.tile_anchors(\n grid_height=grid_size[0],\n grid_width=grid_size[1],\n scales=scales,\n aspect_ratios=aspect_ratios,\n base_anchor_size=base_anchor_size,\n anchor_stride=stride,\n anchor_offset=offset)\n if self._clip_window is not None:\n tiled_anchors = box_list_ops.clip_to_window(\n tiled_anchors, self._clip_window, filter_nonoverlapping=False)\n num_anchors_in_layer = tiled_anchors.num_boxes_static()\n if num_anchors_in_layer is None:\n num_anchors_in_layer = tiled_anchors.num_boxes()\n anchor_indices = feature_map_index * tf.ones([num_anchors_in_layer])\n tiled_anchors.add_field('feature_map_index', anchor_indices)\n anchor_grid_list.append(tiled_anchors)\n\n return anchor_grid_list\n\n\ndef create_ssd_anchors(num_layers=6,\n min_scale=0.2,\n max_scale=0.95,\n scales=None,\n aspect_ratios=(1.0, 2.0, 3.0, 1.0 / 2, 1.0 / 3),\n interpolated_scale_aspect_ratio=1.0,\n base_anchor_size=None,\n anchor_strides=None,\n anchor_offsets=None,\n reduce_boxes_in_lowest_layer=True):\n \"\"\"Creates MultipleGridAnchorGenerator for SSD anchors.\n\n This function instantiates a MultipleGridAnchorGenerator that reproduces\n ``default box`` construction proposed by Liu et al in the SSD paper.\n See Section 2.2 for details. Grid sizes are assumed to be passed in\n at generation time from finest resolution to coarsest resolution --- this is\n used to (linearly) interpolate scales of anchor boxes corresponding to the\n intermediate grid sizes.\n\n Anchors that are returned by calling the `generate` method on the returned\n MultipleGridAnchorGenerator object are always in normalized coordinates\n and clipped to the unit square: (i.e. all coordinates lie in [0, 1]x[0, 1]).\n\n Args:\n num_layers: integer number of grid layers to create anchors for (actual\n grid sizes passed in at generation time)\n min_scale: scale of anchors corresponding to finest resolution (float)\n max_scale: scale of anchors corresponding to coarsest resolution (float)\n scales: As list of anchor scales to use. When not None and not empty,\n min_scale and max_scale are not used.\n aspect_ratios: list or tuple of (float) aspect ratios to place on each\n grid point.\n interpolated_scale_aspect_ratio: An additional anchor is added with this\n aspect ratio and a scale interpolated between the scale for a layer\n and the scale for the next layer (1.0 for the last layer).\n This anchor is not included if this value is 0.\n base_anchor_size: base anchor size as [height, width].\n The height and width values are normalized to the minimum dimension of the\n input height and width, so that when the base anchor height equals the\n base anchor width, the resulting anchor is square even if the input image\n is not square.\n anchor_strides: list of pairs of strides in pixels (in y and x directions\n respectively). For example, setting anchor_strides=[(25, 25), (50, 50)]\n means that we want the anchors corresponding to the first layer to be\n strided by 25 pixels and those in the second layer to be strided by 50\n pixels in both y and x directions. If anchor_strides=None, they are set to\n be the reciprocal of the corresponding feature map shapes.\n anchor_offsets: list of pairs of offsets in pixels (in y and x directions\n respectively). The offset specifies where we want the center of the\n (0, 0)-th anchor to lie for each layer. For example, setting\n anchor_offsets=[(10, 10), (20, 20)]) means that we want the\n (0, 0)-th anchor of the first layer to lie at (10, 10) in pixel space\n and likewise that we want the (0, 0)-th anchor of the second layer to lie\n at (25, 25) in pixel space. If anchor_offsets=None, then they are set to\n be half of the corresponding anchor stride.\n reduce_boxes_in_lowest_layer: a boolean to indicate whether the fixed 3\n boxes per location is used in the lowest layer.\n\n Returns:\n a MultipleGridAnchorGenerator\n \"\"\"\n if base_anchor_size is None:\n base_anchor_size = [1.0, 1.0]\n base_anchor_size = tf.constant(base_anchor_size, dtype=tf.float32)\n box_specs_list = []\n if scales is None or not scales:\n scales = [min_scale + (max_scale - min_scale) * i / (num_layers - 1)\n for i in range(num_layers)] + [1.0]\n else:\n # Add 1.0 to the end, which will only be used in scale_next below and used\n # for computing an interpolated scale for the largest scale in the list.\n scales += [1.0]\n\n for layer, scale, scale_next in zip(\n range(num_layers), scales[:-1], scales[1:]):\n layer_box_specs = []\n if layer == 0 and reduce_boxes_in_lowest_layer:\n layer_box_specs = [(0.1, 1.0), (scale, 2.0), (scale, 0.5)]\n else:\n for aspect_ratio in aspect_ratios:\n layer_box_specs.append((scale, aspect_ratio))\n # Add one more anchor, with a scale between the current scale, and the\n # scale for the next layer, with a specified aspect ratio (1.0 by\n # default).\n if interpolated_scale_aspect_ratio > 0.0:\n layer_box_specs.append((np.sqrt(scale*scale_next),\n interpolated_scale_aspect_ratio))\n box_specs_list.append(layer_box_specs)\n\n return MultipleGridAnchorGenerator(box_specs_list, base_anchor_size,\n anchor_strides, anchor_offsets)\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\"\"\"Creates TFRecords of Open Images dataset for object detection.\n\nExample usage:\n python object_detection/dataset_tools/create_oid_tf_record.py \\\n --input_box_annotations_csv=/path/to/input/annotations-human-bbox.csv \\\n --input_image_label_annotations_csv=/path/to/input/annotations-label.csv \\\n --input_images_directory=/path/to/input/image_pixels_directory \\\n --input_label_map=/path/to/input/labels_bbox_545.labelmap \\\n --output_tf_record_path_prefix=/path/to/output/prefix.tfrecord\n\nCSVs with bounding box annotations and image metadata (including the image URLs)\ncan be downloaded from the Open Images GitHub repository:\nhttps://github.com/openimages/dataset\n\nThis script will include every image found in the input_images_directory in the\noutput TFRecord, even if the image has no corresponding bounding box annotations\nin the input_annotations_csv. If input_image_label_annotations_csv is specified,\nit will add image-level labels as well. Note that the information of whether a\nlabel is positivelly or negativelly verified is NOT added to tfrecord.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\n\nimport contextlib2\nimport pandas as pd\nimport tensorflow as tf\n\nfrom dataset_tools import oid_tfrecord_creation\nfrom dataset_tools import tf_record_creation_util\nfrom utils import label_map_util\n\ntf.flags.DEFINE_string('input_box_annotations_csv', None,\n 'Path to CSV containing image bounding box annotations')\ntf.flags.DEFINE_string('input_images_directory', None,\n 'Directory containing the image pixels '\n 'downloaded from the OpenImages GitHub repository.')\ntf.flags.DEFINE_string('input_image_label_annotations_csv', None,\n 'Path to CSV containing image-level labels annotations')\ntf.flags.DEFINE_string('input_label_map', None, 'Path to the label map proto')\ntf.flags.DEFINE_string(\n 'output_tf_record_path_prefix', None,\n 'Path to the output TFRecord. The shard index and the number of shards '\n 'will be appended for each output shard.')\ntf.flags.DEFINE_integer('num_shards', 100, 'Number of TFRecord shards')\n\nFLAGS = tf.flags.FLAGS\n\n\ndef main(_):\n tf.logging.set_verbosity(tf.logging.INFO)\n\n required_flags = [\n 'input_box_annotations_csv', 'input_images_directory', 'input_label_map',\n 'output_tf_record_path_prefix'\n ]\n for flag_name in required_flags:\n if not getattr(FLAGS, flag_name):\n raise ValueError('Flag --{} is required'.format(flag_name))\n\n label_map = label_map_util.get_label_map_dict(FLAGS.input_label_map)\n all_box_annotations = pd.read_csv(FLAGS.input_box_annotations_csv)\n if FLAGS.input_image_label_annotations_csv:\n all_label_annotations = pd.read_csv(FLAGS.input_image_label_annotations_csv)\n all_label_annotations.rename(\n columns={'Confidence': 'ConfidenceImageLabel'}, inplace=True)\n else:\n all_label_annotations = None\n all_images = tf.gfile.Glob(\n os.path.join(FLAGS.input_images_directory, '*.jpg'))\n all_image_ids = [os.path.splitext(os.path.basename(v))[0] for v in all_images]\n all_image_ids = pd.DataFrame({'ImageID': all_image_ids})\n all_annotations = pd.concat(\n [all_box_annotations, all_image_ids, all_label_annotations])\n\n tf.logging.log(tf.logging.INFO, 'Found %d images...', len(all_image_ids))\n\n with contextlib2.ExitStack() as tf_record_close_stack:\n output_tfrecords = tf_record_creation_util.open_sharded_output_tfrecords(\n tf_record_close_stack, FLAGS.output_tf_record_path_prefix,\n FLAGS.num_shards)\n\n for counter, image_data in enumerate(all_annotations.groupby('ImageID')):\n tf.logging.log_every_n(tf.logging.INFO, 'Processed %d images...', 1000,\n counter)\n\n image_id, image_annotations = image_data\n # In OID image file names are formed by appending \".jpg\" to the image ID.\n image_path = os.path.join(FLAGS.input_images_directory, image_id + '.jpg')\n with tf.gfile.Open(image_path) as image_file:\n encoded_image = image_file.read()\n\n tf_example = oid_tfrecord_creation.tf_example_from_annotations_data_frame(\n image_annotations, label_map, encoded_image)\n if tf_example:\n shard_idx = int(image_id, 16) % FLAGS.num_shards\n output_tfrecords[shard_idx].write(tf_example.SerializeToString())\n\n\nif __name__ == '__main__':\n tf.app.run()\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\"\"\"object_detection_evaluation module.\n\nObjectDetectionEvaluation is a class which manages ground truth information of a\nobject detection dataset, and computes frequently used detection metrics such as\nPrecision, Recall, CorLoc of the provided detection results.\nIt supports the following operations:\n1) Add ground truth information of images sequentially.\n2) Add detection result of images sequentially.\n3) Evaluate detection metrics on already inserted detection results.\n4) Write evaluation result into a pickle file for future processing or\n visualization.\n\nNote: This module operates on numpy boxes and box lists.\n\"\"\"\n\nfrom abc import ABCMeta\nfrom abc import abstractmethod\nimport collections\nimport logging\nimport unicodedata\nimport numpy as np\nimport tensorflow as tf\n\nfrom core import standard_fields\nfrom utils import label_map_util\nfrom utils import metrics\nfrom utils import per_image_evaluation\n\n\nclass DetectionEvaluator(object):\n \"\"\"Interface for object detection evalution classes.\n\n Example usage of the Evaluator:\n ------------------------------\n evaluator = DetectionEvaluator(categories)\n\n # Detections and groundtruth for image 1.\n evaluator.add_single_groundtruth_image_info(...)\n evaluator.add_single_detected_image_info(...)\n\n # Detections and groundtruth for image 2.\n evaluator.add_single_groundtruth_image_info(...)\n evaluator.add_single_detected_image_info(...)\n\n metrics_dict = evaluator.evaluate()\n \"\"\"\n __metaclass__ = ABCMeta\n\n def __init__(self, categories):\n \"\"\"Constructor.\n\n Args:\n categories: A list of dicts, each of which has the following keys -\n 'id': (required) an integer id uniquely identifying this category.\n 'name': (required) string representing category name e.g., 'cat', 'dog'.\n \"\"\"\n self._categories = categories\n\n @abstractmethod\n def add_single_ground_truth_image_info(self, image_id, groundtruth_dict):\n \"\"\"Adds groundtruth for a single image to be used for evaluation.\n\n Args:\n image_id: A unique string/integer identifier for the image.\n groundtruth_dict: A dictionary of groundtruth numpy arrays required\n for evaluations.\n \"\"\"\n pass\n\n @abstractmethod\n def add_single_detected_image_info(self, image_id, detections_dict):\n \"\"\"Adds detections for a single image to be used for evaluation.\n\n Args:\n image_id: A unique string/integer identifier for the image.\n detections_dict: A dictionary of detection numpy arrays required\n for evaluation.\n \"\"\"\n pass\n\n def get_estimator_eval_metric_ops(self, eval_dict):\n \"\"\"Returns dict of metrics to use with `tf.estimator.EstimatorSpec`.\n\n Note that this must only be implemented if performing evaluation with a\n `tf.estimator.Estimator`.\n\n Args:\n eval_dict: A dictionary that holds tensors for evaluating an object\n detection model, returned from\n eval_util.result_dict_for_single_example().\n\n Returns:\n A dictionary of metric names to tuple of value_op and update_op that can\n be used as eval metric ops in `tf.estimator.EstimatorSpec`.\n \"\"\"\n pass\n\n @abstractmethod\n def evaluate(self):\n \"\"\"Evaluates detections and returns a dictionary of metrics.\"\"\"\n pass\n\n @abstractmethod\n def clear(self):\n \"\"\"Clears the state to prepare for a fresh evaluation.\"\"\"\n pass\n\n\nclass ObjectDetectionEvaluator(DetectionEvaluator):\n \"\"\"A class to evaluate detections.\"\"\"\n\n def __init__(self,\n categories,\n matching_iou_threshold=0.5,\n evaluate_corlocs=False,\n evaluate_precision_recall=False,\n metric_prefix=None,\n use_weighted_mean_ap=False,\n evaluate_masks=False,\n group_of_weight=0.0):\n \"\"\"Constructor.\n\n Args:\n categories: A list of dicts, each of which has the following keys -\n 'id': (required) an integer id uniquely identifying this category.\n 'name': (required) string representing category name e.g., 'cat', 'dog'.\n matching_iou_threshold: IOU threshold to use for matching groundtruth\n boxes to detection boxes.\n evaluate_corlocs: (optional) boolean which determines if corloc scores\n are to be returned or not.\n evaluate_precision_recall: (optional) boolean which determines if\n precision and recall values are to be returned or not.\n metric_prefix: (optional) string prefix for metric name; if None, no\n prefix is used.\n use_weighted_mean_ap: (optional) boolean which determines if the mean\n average precision is computed directly from the scores and tp_fp_labels\n of all classes.\n evaluate_masks: If False, evaluation will be performed based on boxes.\n If True, mask evaluation will be performed instead.\n group_of_weight: Weight of group-of boxes.If set to 0, detections of the\n correct class within a group-of box are ignored. If weight is > 0, then\n if at least one detection falls within a group-of box with\n matching_iou_threshold, weight group_of_weight is added to true\n positives. Consequently, if no detection falls within a group-of box,\n weight group_of_weight is added to false negatives.\n\n Raises:\n ValueError: If the category ids are not 1-indexed.\n \"\"\"\n super(ObjectDetectionEvaluator, self).__init__(categories)\n self._num_classes = max([cat['id'] for cat in categories])\n if min(cat['id'] for cat in categories) < 1:\n raise ValueError('Classes should be 1-indexed.')\n self._matching_iou_threshold = matching_iou_threshold\n self._use_weighted_mean_ap = use_weighted_mean_ap\n self._label_id_offset = 1\n self._evaluate_masks = evaluate_masks\n self._group_of_weight = group_of_weight\n self._evaluation = ObjectDetectionEvaluation(\n num_groundtruth_classes=self._num_classes,\n matching_iou_threshold=self._matching_iou_threshold,\n use_weighted_mean_ap=self._use_weighted_mean_ap,\n label_id_offset=self._label_id_offset,\n group_of_weight=self._group_of_weight)\n self._image_ids = set([])\n self._evaluate_corlocs = evaluate_corlocs\n self._evaluate_precision_recall = evaluate_precision_recall\n self._metric_prefix = (metric_prefix + '_') if metric_prefix else ''\n self._expected_keys = set([\n standard_fields.InputDataFields.key,\n standard_fields.InputDataFields.groundtruth_boxes,\n standard_fields.InputDataFields.groundtruth_classes,\n standard_fields.InputDataFields.groundtruth_difficult,\n standard_fields.InputDataFields.groundtruth_instance_masks,\n standard_fields.DetectionResultFields.detection_boxes,\n standard_fields.DetectionResultFields.detection_scores,\n standard_fields.DetectionResultFields.detection_classes,\n standard_fields.DetectionResultFields.detection_masks\n ])\n self._build_metric_names()\n\n def _build_metric_names(self):\n \"\"\"Builds a list with metric names.\"\"\"\n\n self._metric_names = [\n self._metric_prefix + 'Precision/mAP@{}IOU'.format(\n self._matching_iou_threshold)\n ]\n if self._evaluate_corlocs:\n self._metric_names.append(\n self._metric_prefix +\n 'Precision/meanCorLoc@{}IOU'.format(self._matching_iou_threshold))\n\n category_index = label_map_util.create_category_index(self._categories)\n for idx in range(self._num_classes):\n if idx + self._label_id_offset in category_index:\n category_name = category_index[idx + self._label_id_offset]['name']\n try:\n category_name = unicode(category_name, 'utf-8')\n except TypeError:\n pass\n category_name = unicodedata.normalize('NFKD', category_name).encode(\n 'ascii', 'ignore')\n self._metric_names.append(\n self._metric_prefix + 'PerformanceByCategory/AP@{}IOU/{}'.format(\n self._matching_iou_threshold, category_name))\n if self._evaluate_corlocs:\n self._metric_names.append(\n self._metric_prefix + 'PerformanceByCategory/CorLoc@{}IOU/{}'\n .format(self._matching_iou_threshold, category_name))\n\n def add_single_ground_truth_image_info(self, image_id, groundtruth_dict):\n \"\"\"Adds groundtruth for a single image to be used for evaluation.\n\n Args:\n image_id: A unique string/integer identifier for the image.\n groundtruth_dict: A dictionary containing -\n standard_fields.InputDataFields.groundtruth_boxes: float32 numpy array\n of shape [num_boxes, 4] containing `num_boxes` groundtruth boxes of\n the format [ymin, xmin, ymax, xmax] in absolute image coordinates.\n standard_fields.InputDataFields.groundtruth_classes: integer numpy array\n of shape [num_boxes] containing 1-indexed groundtruth classes for the\n boxes.\n standard_fields.InputDataFields.groundtruth_difficult: Optional length\n M numpy boolean array denoting whether a ground truth box is a\n difficult instance or not. This field is optional to support the case\n that no boxes are difficult.\n standard_fields.InputDataFields.groundtruth_instance_masks: Optional\n numpy array of shape [num_boxes, height, width] with values in {0, 1}.\n\n Raises:\n ValueError: On adding groundtruth for an image more than once. Will also\n raise error if instance masks are not in groundtruth dictionary.\n \"\"\"\n if image_id in self._image_ids:\n raise ValueError('Image with id {} already added.'.format(image_id))\n\n groundtruth_classes = (\n groundtruth_dict[standard_fields.InputDataFields.groundtruth_classes] -\n self._label_id_offset)\n # If the key is not present in the groundtruth_dict or the array is empty\n # (unless there are no annotations for the groundtruth on this image)\n # use values from the dictionary or insert None otherwise.\n if (standard_fields.InputDataFields.groundtruth_difficult in\n groundtruth_dict.keys() and\n (groundtruth_dict[standard_fields.InputDataFields.groundtruth_difficult]\n .size or not groundtruth_classes.size)):\n groundtruth_difficult = groundtruth_dict[\n standard_fields.InputDataFields.groundtruth_difficult]\n else:\n groundtruth_difficult = None\n if not len(self._image_ids) % 1000:\n logging.warn(\n 'image %s does not have groundtruth difficult flag specified',\n image_id)\n groundtruth_masks = None\n if self._evaluate_masks:\n if (standard_fields.InputDataFields.groundtruth_instance_masks not in\n groundtruth_dict):\n raise ValueError('Instance masks not in groundtruth dictionary.')\n groundtruth_masks = groundtruth_dict[\n standard_fields.InputDataFields.groundtruth_instance_masks]\n self._evaluation.add_single_ground_truth_image_info(\n image_key=image_id,\n groundtruth_boxes=groundtruth_dict[\n standard_fields.InputDataFields.groundtruth_boxes],\n groundtruth_class_labels=groundtruth_classes,\n groundtruth_is_difficult_list=groundtruth_difficult,\n groundtruth_masks=groundtruth_masks)\n self._image_ids.update([image_id])\n\n def add_single_detected_image_info(self, image_id, detections_dict):\n \"\"\"Adds detections for a single image to be used for evaluation.\n\n Args:\n image_id: A unique string/integer identifier for the image.\n detections_dict: A dictionary containing -\n standard_fields.DetectionResultFields.detection_boxes: float32 numpy\n array of shape [num_boxes, 4] containing `num_boxes` detection boxes\n of the format [ymin, xmin, ymax, xmax] in absolute image coordinates.\n standard_fields.DetectionResultFields.detection_scores: float32 numpy\n array of shape [num_boxes] containing detection scores for the boxes.\n standard_fields.DetectionResultFields.detection_classes: integer numpy\n array of shape [num_boxes] containing 1-indexed detection classes for\n the boxes.\n standard_fields.DetectionResultFields.detection_masks: uint8 numpy\n array of shape [num_boxes, height, width] containing `num_boxes` masks\n of values ranging between 0 and 1.\n\n Raises:\n ValueError: If detection masks are not in detections dictionary.\n \"\"\"\n detection_classes = (\n detections_dict[standard_fields.DetectionResultFields.detection_classes]\n - self._label_id_offset)\n detection_masks = None\n if self._evaluate_masks:\n if (standard_fields.DetectionResultFields.detection_masks not in\n detections_dict):\n raise ValueError('Detection masks not in detections dictionary.')\n detection_masks = detections_dict[\n standard_fields.DetectionResultFields.detection_masks]\n self._evaluation.add_single_detected_image_info(\n image_key=image_id,\n detected_boxes=detections_dict[\n standard_fields.DetectionResultFields.detection_boxes],\n detected_scores=detections_dict[\n standard_fields.DetectionResultFields.detection_scores],\n detected_class_labels=detection_classes,\n detected_masks=detection_masks)\n\n def evaluate(self):\n \"\"\"Compute evaluation result.\n\n Returns:\n A dictionary of metrics with the following fields -\n\n 1. summary_metrics:\n '<prefix if not empty>_Precision/mAP@<matching_iou_threshold>IOU': mean\n average precision at the specified IOU threshold.\n\n 2. per_category_ap: category specific results with keys of the form\n '<prefix if not empty>_PerformanceByCategory/\n mAP@<matching_iou_threshold>IOU/category'.\n \"\"\"\n (per_class_ap, mean_ap, per_class_precision, per_class_recall,\n per_class_corloc, mean_corloc) = (\n self._evaluation.evaluate())\n pascal_metrics = {self._metric_names[0]: mean_ap}\n if self._evaluate_corlocs:\n pascal_metrics[self._metric_names[1]] = mean_corloc\n category_index = label_map_util.create_category_index(self._categories)\n for idx in range(per_class_ap.size):\n if idx + self._label_id_offset in category_index:\n category_name = category_index[idx + self._label_id_offset]['name']\n try:\n category_name = unicode(category_name, 'utf-8')\n except TypeError:\n pass\n category_name = unicodedata.normalize(\n 'NFKD', category_name).encode('ascii', 'ignore')\n display_name = (\n self._metric_prefix + 'PerformanceByCategory/AP@{}IOU/{}'.format(\n self._matching_iou_threshold, category_name))\n pascal_metrics[display_name] = per_class_ap[idx]\n\n # Optionally add precision and recall values\n if self._evaluate_precision_recall:\n display_name = (\n self._metric_prefix +\n 'PerformanceByCategory/Precision@{}IOU/{}'.format(\n self._matching_iou_threshold, category_name))\n pascal_metrics[display_name] = per_class_precision[idx]\n display_name = (\n self._metric_prefix +\n 'PerformanceByCategory/Recall@{}IOU/{}'.format(\n self._matching_iou_threshold, category_name))\n pascal_metrics[display_name] = per_class_recall[idx]\n\n # Optionally add CorLoc metrics.classes\n if self._evaluate_corlocs:\n display_name = (\n self._metric_prefix + 'PerformanceByCategory/CorLoc@{}IOU/{}'\n .format(self._matching_iou_threshold, category_name))\n pascal_metrics[display_name] = per_class_corloc[idx]\n\n return pascal_metrics\n\n def clear(self):\n \"\"\"Clears the state to prepare for a fresh evaluation.\"\"\"\n self._evaluation = ObjectDetectionEvaluation(\n num_groundtruth_classes=self._num_classes,\n matching_iou_threshold=self._matching_iou_threshold,\n use_weighted_mean_ap=self._use_weighted_mean_ap,\n label_id_offset=self._label_id_offset)\n self._image_ids.clear()\n\n def get_estimator_eval_metric_ops(self, eval_dict):\n \"\"\"Returns dict of metrics to use with `tf.estimator.EstimatorSpec`.\n\n Note that this must only be implemented if performing evaluation with a\n `tf.estimator.Estimator`.\n\n Args:\n eval_dict: A dictionary that holds tensors for evaluating an object\n detection model, returned from\n eval_util.result_dict_for_single_example(). It must contain\n standard_fields.InputDataFields.key.\n\n Returns:\n A dictionary of metric names to tuple of value_op and update_op that can\n be used as eval metric ops in `tf.estimator.EstimatorSpec`.\n \"\"\"\n # remove unexpected fields\n eval_dict_filtered = dict()\n for key, value in eval_dict.items():\n if key in self._expected_keys:\n eval_dict_filtered[key] = value\n\n eval_dict_keys = eval_dict_filtered.keys()\n\n def update_op(image_id, *eval_dict_batched_as_list):\n \"\"\"Update operation that adds batch of images to ObjectDetectionEvaluator.\n\n Args:\n image_id: image id (single id or an array)\n *eval_dict_batched_as_list: the values of the dictionary of tensors.\n \"\"\"\n if np.isscalar(image_id):\n single_example_dict = dict(\n zip(eval_dict_keys, eval_dict_batched_as_list))\n self.add_single_ground_truth_image_info(image_id, single_example_dict)\n self.add_single_detected_image_info(image_id, single_example_dict)\n else:\n for unzipped_tuple in zip(*eval_dict_batched_as_list):\n single_example_dict = dict(zip(eval_dict_keys, unzipped_tuple))\n image_id = single_example_dict[standard_fields.InputDataFields.key]\n self.add_single_ground_truth_image_info(image_id, single_example_dict)\n self.add_single_detected_image_info(image_id, single_example_dict)\n\n args = [eval_dict_filtered[standard_fields.InputDataFields.key]]\n args.extend(eval_dict_filtered.values())\n update_op = tf.py_func(update_op, args, [])\n\n def first_value_func():\n self._metrics = self.evaluate()\n self.clear()\n return np.float32(self._metrics[self._metric_names[0]])\n\n def value_func_factory(metric_name):\n\n def value_func():\n return np.float32(self._metrics[metric_name])\n\n return value_func\n\n # Ensure that the metrics are only evaluated once.\n first_value_op = tf.py_func(first_value_func, [], tf.float32)\n eval_metric_ops = {self._metric_names[0]: (first_value_op, update_op)}\n with tf.control_dependencies([first_value_op]):\n for metric_name in self._metric_names[1:]:\n eval_metric_ops[metric_name] = (tf.py_func(\n value_func_factory(metric_name), [], np.float32), update_op)\n return eval_metric_ops\n\n\nclass PascalDetectionEvaluator(ObjectDetectionEvaluator):\n \"\"\"A class to evaluate detections using PASCAL metrics.\"\"\"\n\n def __init__(self, categories, matching_iou_threshold=0.5):\n super(PascalDetectionEvaluator, self).__init__(\n categories,\n matching_iou_threshold=matching_iou_threshold,\n evaluate_corlocs=False,\n metric_prefix='PascalBoxes',\n use_weighted_mean_ap=False)\n\n\nclass WeightedPascalDetectionEvaluator(ObjectDetectionEvaluator):\n \"\"\"A class to evaluate detections using weighted PASCAL metrics.\n\n Weighted PASCAL metrics computes the mean average precision as the average\n precision given the scores and tp_fp_labels of all classes. In comparison,\n PASCAL metrics computes the mean average precision as the mean of the\n per-class average precisions.\n\n This definition is very similar to the mean of the per-class average\n precisions weighted by class frequency. However, they are typically not the\n same as the average precision is not a linear function of the scores and\n tp_fp_labels.\n \"\"\"\n\n def __init__(self, categories, matching_iou_threshold=0.5):\n super(WeightedPascalDetectionEvaluator, self).__init__(\n categories,\n matching_iou_threshold=matching_iou_threshold,\n evaluate_corlocs=False,\n metric_prefix='WeightedPascalBoxes',\n use_weighted_mean_ap=True)\n\n\nclass PascalInstanceSegmentationEvaluator(ObjectDetectionEvaluator):\n \"\"\"A class to evaluate instance masks using PASCAL metrics.\"\"\"\n\n def __init__(self, categories, matching_iou_threshold=0.5):\n super(PascalInstanceSegmentationEvaluator, self).__init__(\n categories,\n matching_iou_threshold=matching_iou_threshold,\n evaluate_corlocs=False,\n metric_prefix='PascalMasks',\n use_weighted_mean_ap=False,\n evaluate_masks=True)\n\n\nclass WeightedPascalInstanceSegmentationEvaluator(ObjectDetectionEvaluator):\n \"\"\"A class to evaluate instance masks using weighted PASCAL metrics.\n\n Weighted PASCAL metrics computes the mean average precision as the average\n precision given the scores and tp_fp_labels of all classes. In comparison,\n PASCAL metrics computes the mean average precision as the mean of the\n per-class average precisions.\n\n This definition is very similar to the mean of the per-class average\n precisions weighted by class frequency. However, they are typically not the\n same as the average precision is not a linear function of the scores and\n tp_fp_labels.\n \"\"\"\n\n def __init__(self, categories, matching_iou_threshold=0.5):\n super(WeightedPascalInstanceSegmentationEvaluator, self).__init__(\n categories,\n matching_iou_threshold=matching_iou_threshold,\n evaluate_corlocs=False,\n metric_prefix='WeightedPascalMasks',\n use_weighted_mean_ap=True,\n evaluate_masks=True)\n\n\nclass OpenImagesDetectionEvaluator(ObjectDetectionEvaluator):\n \"\"\"A class to evaluate detections using Open Images V2 metrics.\n\n Open Images V2 introduce group_of type of bounding boxes and this metric\n handles those boxes appropriately.\n \"\"\"\n\n def __init__(self,\n categories,\n matching_iou_threshold=0.5,\n evaluate_corlocs=False,\n metric_prefix='OpenImagesV2',\n group_of_weight=0.0):\n \"\"\"Constructor.\n\n Args:\n categories: A list of dicts, each of which has the following keys -\n 'id': (required) an integer id uniquely identifying this category.\n 'name': (required) string representing category name e.g., 'cat', 'dog'.\n matching_iou_threshold: IOU threshold to use for matching groundtruth\n boxes to detection boxes.\n evaluate_corlocs: if True, additionally evaluates and returns CorLoc.\n metric_prefix: Prefix name of the metric.\n group_of_weight: Weight of the group-of bounding box. If set to 0 (default\n for Open Images V2 detection protocol), detections of the correct class\n within a group-of box are ignored. If weight is > 0, then if at least\n one detection falls within a group-of box with matching_iou_threshold,\n weight group_of_weight is added to true positives. Consequently, if no\n detection falls within a group-of box, weight group_of_weight is added\n to false negatives.\n \"\"\"\n super(OpenImagesDetectionEvaluator, self).__init__(\n categories,\n matching_iou_threshold,\n evaluate_corlocs,\n metric_prefix=metric_prefix,\n group_of_weight=group_of_weight)\n self._expected_keys = set([\n standard_fields.InputDataFields.key,\n standard_fields.InputDataFields.groundtruth_boxes,\n standard_fields.InputDataFields.groundtruth_classes,\n standard_fields.InputDataFields.groundtruth_group_of,\n standard_fields.DetectionResultFields.detection_boxes,\n standard_fields.DetectionResultFields.detection_scores,\n standard_fields.DetectionResultFields.detection_classes,\n ])\n\n def add_single_ground_truth_image_info(self, image_id, groundtruth_dict):\n \"\"\"Adds groundtruth for a single image to be used for evaluation.\n\n Args:\n image_id: A unique string/integer identifier for the image.\n groundtruth_dict: A dictionary containing -\n standard_fields.InputDataFields.groundtruth_boxes: float32 numpy array\n of shape [num_boxes, 4] containing `num_boxes` groundtruth boxes of\n the format [ymin, xmin, ymax, xmax] in absolute image coordinates.\n standard_fields.InputDataFields.groundtruth_classes: integer numpy array\n of shape [num_boxes] containing 1-indexed groundtruth classes for the\n boxes.\n standard_fields.InputDataFields.groundtruth_group_of: Optional length\n M numpy boolean array denoting whether a groundtruth box contains a\n group of instances.\n\n Raises:\n ValueError: On adding groundtruth for an image more than once.\n \"\"\"\n if image_id in self._image_ids:\n raise ValueError('Image with id {} already added.'.format(image_id))\n\n groundtruth_classes = (\n groundtruth_dict[standard_fields.InputDataFields.groundtruth_classes] -\n self._label_id_offset)\n # If the key is not present in the groundtruth_dict or the array is empty\n # (unless there are no annotations for the groundtruth on this image)\n # use values from the dictionary or insert None otherwise.\n if (standard_fields.InputDataFields.groundtruth_group_of in\n groundtruth_dict.keys() and\n (groundtruth_dict[standard_fields.InputDataFields.groundtruth_group_of]\n .size or not groundtruth_classes.size)):\n groundtruth_group_of = groundtruth_dict[\n standard_fields.InputDataFields.groundtruth_group_of]\n else:\n groundtruth_group_of = None\n if not len(self._image_ids) % 1000:\n logging.warn(\n 'image %s does not have groundtruth group_of flag specified',\n image_id)\n self._evaluation.add_single_ground_truth_image_info(\n image_id,\n groundtruth_dict[standard_fields.InputDataFields.groundtruth_boxes],\n groundtruth_classes,\n groundtruth_is_difficult_list=None,\n groundtruth_is_group_of_list=groundtruth_group_of)\n self._image_ids.update([image_id])\n\n\nclass OpenImagesDetectionChallengeEvaluator(OpenImagesDetectionEvaluator):\n \"\"\"A class implements Open Images Challenge Detection metrics.\n\n Open Images Challenge Detection metric has two major changes in comparison\n with Open Images V2 detection metric:\n - a custom weight might be specified for detecting an object contained in\n a group-of box.\n - verified image-level labels should be explicitelly provided for\n evaluation: in case in image has neither positive nor negative image level\n label of class c, all detections of this class on this image will be\n ignored.\n \"\"\"\n\n def __init__(self,\n categories,\n matching_iou_threshold=0.5,\n evaluate_corlocs=False,\n group_of_weight=1.0):\n \"\"\"Constructor.\n\n Args:\n categories: A list of dicts, each of which has the following keys -\n 'id': (required) an integer id uniquely identifying this category.\n 'name': (required) string representing category name e.g., 'cat', 'dog'.\n matching_iou_threshold: IOU threshold to use for matching groundtruth\n boxes to detection boxes.\n evaluate_corlocs: if True, additionally evaluates and returns CorLoc.\n group_of_weight: weight of a group-of box. If set to 0, detections of the\n correct class within a group-of box are ignored. If weight is > 0\n (default for Open Images Detection Challenge 2018), then if at least one\n detection falls within a group-of box with matching_iou_threshold,\n weight group_of_weight is added to true positives. Consequently, if no\n detection falls within a group-of box, weight group_of_weight is added\n to false negatives.\n \"\"\"\n super(OpenImagesDetectionChallengeEvaluator, self).__init__(\n categories,\n matching_iou_threshold,\n evaluate_corlocs,\n metric_prefix='OpenImagesChallenge2018',\n group_of_weight=group_of_weight)\n\n self._evaluatable_labels = {}\n self._expected_keys = set([\n standard_fields.InputDataFields.key,\n standard_fields.InputDataFields.groundtruth_boxes,\n standard_fields.InputDataFields.groundtruth_classes,\n standard_fields.InputDataFields.groundtruth_group_of,\n standard_fields.InputDataFields.groundtruth_image_classes,\n standard_fields.DetectionResultFields.detection_boxes,\n standard_fields.DetectionResultFields.detection_scores,\n standard_fields.DetectionResultFields.detection_classes,\n ])\n\n def add_single_ground_truth_image_info(self, image_id, groundtruth_dict):\n \"\"\"Adds groundtruth for a single image to be used for evaluation.\n\n Args:\n image_id: A unique string/integer identifier for the image.\n groundtruth_dict: A dictionary containing -\n standard_fields.InputDataFields.groundtruth_boxes: float32 numpy array\n of shape [num_boxes, 4] containing `num_boxes` groundtruth boxes of\n the format [ymin, xmin, ymax, xmax] in absolute image coordinates.\n standard_fields.InputDataFields.groundtruth_classes: integer numpy array\n of shape [num_boxes] containing 1-indexed groundtruth classes for the\n boxes.\n standard_fields.InputDataFields.groundtruth_image_classes: integer 1D\n numpy array containing all classes for which labels are verified.\n standard_fields.InputDataFields.groundtruth_group_of: Optional length\n M numpy boolean array denoting whether a groundtruth box contains a\n group of instances.\n\n Raises:\n ValueError: On adding groundtruth for an image more than once.\n \"\"\"\n super(OpenImagesDetectionChallengeEvaluator,\n self).add_single_ground_truth_image_info(image_id, groundtruth_dict)\n groundtruth_classes = (\n groundtruth_dict[standard_fields.InputDataFields.groundtruth_classes] -\n self._label_id_offset)\n self._evaluatable_labels[image_id] = np.unique(\n np.concatenate(((groundtruth_dict.get(\n standard_fields.InputDataFields.groundtruth_image_classes,\n np.array([], dtype=int)) - self._label_id_offset),\n groundtruth_classes)))\n\n def add_single_detected_image_info(self, image_id, detections_dict):\n \"\"\"Adds detections for a single image to be used for evaluation.\n\n Args:\n image_id: A unique string/integer identifier for the image.\n detections_dict: A dictionary containing -\n standard_fields.DetectionResultFields.detection_boxes: float32 numpy\n array of shape [num_boxes, 4] containing `num_boxes` detection boxes\n of the format [ymin, xmin, ymax, xmax] in absolute image coordinates.\n standard_fields.DetectionResultFields.detection_scores: float32 numpy\n array of shape [num_boxes] containing detection scores for the boxes.\n standard_fields.DetectionResultFields.detection_classes: integer numpy\n array of shape [num_boxes] containing 1-indexed detection classes for\n the boxes.\n\n Raises:\n ValueError: If detection masks are not in detections dictionary.\n \"\"\"\n if image_id not in self._image_ids:\n # Since for the correct work of evaluator it is assumed that groundtruth\n # is inserted first we make sure to break the code if is it not the case.\n self._image_ids.update([image_id])\n self._evaluatable_labels[image_id] = np.array([])\n\n detection_classes = (\n detections_dict[standard_fields.DetectionResultFields.detection_classes]\n - self._label_id_offset)\n allowed_classes = np.where(\n np.isin(detection_classes, self._evaluatable_labels[image_id]))\n detection_classes = detection_classes[allowed_classes]\n detected_boxes = detections_dict[\n standard_fields.DetectionResultFields.detection_boxes][allowed_classes]\n detected_scores = detections_dict[\n standard_fields.DetectionResultFields.detection_scores][allowed_classes]\n\n self._evaluation.add_single_detected_image_info(\n image_key=image_id,\n detected_boxes=detected_boxes,\n detected_scores=detected_scores,\n detected_class_labels=detection_classes)\n\n def clear(self):\n \"\"\"Clears stored data.\"\"\"\n\n super(OpenImagesDetectionChallengeEvaluator, self).clear()\n self._evaluatable_labels.clear()\n\n\nObjectDetectionEvalMetrics = collections.namedtuple(\n 'ObjectDetectionEvalMetrics', [\n 'average_precisions', 'mean_ap', 'precisions', 'recalls', 'corlocs',\n 'mean_corloc'\n ])\n\n\nclass ObjectDetectionEvaluation(object):\n \"\"\"Internal implementation of Pascal object detection metrics.\"\"\"\n\n def __init__(self,\n num_groundtruth_classes,\n matching_iou_threshold=0.5,\n nms_iou_threshold=1.0,\n nms_max_output_boxes=10000,\n use_weighted_mean_ap=False,\n label_id_offset=0,\n group_of_weight=0.0,\n per_image_eval_class=per_image_evaluation.PerImageEvaluation):\n \"\"\"Constructor.\n\n Args:\n num_groundtruth_classes: Number of ground-truth classes.\n matching_iou_threshold: IOU threshold used for matching detected boxes\n to ground-truth boxes.\n nms_iou_threshold: IOU threshold used for non-maximum suppression.\n nms_max_output_boxes: Maximum number of boxes returned by non-maximum\n suppression.\n use_weighted_mean_ap: (optional) boolean which determines if the mean\n average precision is computed directly from the scores and tp_fp_labels\n of all classes.\n label_id_offset: The label id offset.\n group_of_weight: Weight of group-of boxes.If set to 0, detections of the\n correct class within a group-of box are ignored. If weight is > 0, then\n if at least one detection falls within a group-of box with\n matching_iou_threshold, weight group_of_weight is added to true\n positives. Consequently, if no detection falls within a group-of box,\n weight group_of_weight is added to false negatives.\n per_image_eval_class: The class that contains functions for computing\n per image metrics.\n\n Raises:\n ValueError: if num_groundtruth_classes is smaller than 1.\n \"\"\"\n if num_groundtruth_classes < 1:\n raise ValueError('Need at least 1 groundtruth class for evaluation.')\n\n self.per_image_eval = per_image_eval_class(\n num_groundtruth_classes=num_groundtruth_classes,\n matching_iou_threshold=matching_iou_threshold,\n nms_iou_threshold=nms_iou_threshold,\n nms_max_output_boxes=nms_max_output_boxes,\n group_of_weight=group_of_weight)\n self.group_of_weight = group_of_weight\n self.num_class = num_groundtruth_classes\n self.use_weighted_mean_ap = use_weighted_mean_ap\n self.label_id_offset = label_id_offset\n\n self.groundtruth_boxes = {}\n self.groundtruth_class_labels = {}\n self.groundtruth_masks = {}\n self.groundtruth_is_difficult_list = {}\n self.groundtruth_is_group_of_list = {}\n self.num_gt_instances_per_class = np.zeros(self.num_class, dtype=float)\n self.num_gt_imgs_per_class = np.zeros(self.num_class, dtype=int)\n\n self._initialize_detections()\n\n def _initialize_detections(self):\n \"\"\"Initializes internal data structures.\"\"\"\n self.detection_keys = set()\n self.scores_per_class = [[] for _ in range(self.num_class)]\n self.tp_fp_labels_per_class = [[] for _ in range(self.num_class)]\n self.num_images_correctly_detected_per_class = np.zeros(self.num_class)\n self.average_precision_per_class = np.empty(self.num_class, dtype=float)\n self.average_precision_per_class.fill(np.nan)\n self.precisions_per_class = [np.nan] * self.num_class\n self.recalls_per_class = [np.nan] * self.num_class\n\n self.corloc_per_class = np.ones(self.num_class, dtype=float)\n\n def clear_detections(self):\n self._initialize_detections()\n\n def add_single_ground_truth_image_info(self,\n image_key,\n groundtruth_boxes,\n groundtruth_class_labels,\n groundtruth_is_difficult_list=None,\n groundtruth_is_group_of_list=None,\n groundtruth_masks=None):\n \"\"\"Adds groundtruth for a single image to be used for evaluation.\n\n Args:\n image_key: A unique string/integer identifier for the image.\n groundtruth_boxes: float32 numpy array of shape [num_boxes, 4]\n containing `num_boxes` groundtruth boxes of the format\n [ymin, xmin, ymax, xmax] in absolute image coordinates.\n groundtruth_class_labels: integer numpy array of shape [num_boxes]\n containing 0-indexed groundtruth classes for the boxes.\n groundtruth_is_difficult_list: A length M numpy boolean array denoting\n whether a ground truth box is a difficult instance or not. To support\n the case that no boxes are difficult, it is by default set as None.\n groundtruth_is_group_of_list: A length M numpy boolean array denoting\n whether a ground truth box is a group-of box or not. To support\n the case that no boxes are groups-of, it is by default set as None.\n groundtruth_masks: uint8 numpy array of shape\n [num_boxes, height, width] containing `num_boxes` groundtruth masks.\n The mask values range from 0 to 1.\n \"\"\"\n if image_key in self.groundtruth_boxes:\n logging.warn(\n 'image %s has already been added to the ground truth database.',\n image_key)\n return\n\n self.groundtruth_boxes[image_key] = groundtruth_boxes\n self.groundtruth_class_labels[image_key] = groundtruth_class_labels\n self.groundtruth_masks[image_key] = groundtruth_masks\n if groundtruth_is_difficult_list is None:\n num_boxes = groundtruth_boxes.shape[0]\n groundtruth_is_difficult_list = np.zeros(num_boxes, dtype=bool)\n self.groundtruth_is_difficult_list[\n image_key] = groundtruth_is_difficult_list.astype(dtype=bool)\n if groundtruth_is_group_of_list is None:\n num_boxes = groundtruth_boxes.shape[0]\n groundtruth_is_group_of_list = np.zeros(num_boxes, dtype=bool)\n self.groundtruth_is_group_of_list[\n image_key] = groundtruth_is_group_of_list.astype(dtype=bool)\n\n self._update_ground_truth_statistics(\n groundtruth_class_labels,\n groundtruth_is_difficult_list.astype(dtype=bool),\n groundtruth_is_group_of_list.astype(dtype=bool))\n\n def add_single_detected_image_info(self, image_key, detected_boxes,\n detected_scores, detected_class_labels,\n detected_masks=None):\n \"\"\"Adds detections for a single image to be used for evaluation.\n\n Args:\n image_key: A unique string/integer identifier for the image.\n detected_boxes: float32 numpy array of shape [num_boxes, 4]\n containing `num_boxes` detection boxes of the format\n [ymin, xmin, ymax, xmax] in absolute image coordinates.\n detected_scores: float32 numpy array of shape [num_boxes] containing\n detection scores for the boxes.\n detected_class_labels: integer numpy array of shape [num_boxes] containing\n 0-indexed detection classes for the boxes.\n detected_masks: np.uint8 numpy array of shape [num_boxes, height, width]\n containing `num_boxes` detection masks with values ranging\n between 0 and 1.\n\n Raises:\n ValueError: if the number of boxes, scores and class labels differ in\n length.\n \"\"\"\n if (len(detected_boxes) != len(detected_scores) or\n len(detected_boxes) != len(detected_class_labels)):\n raise ValueError('detected_boxes, detected_scores and '\n 'detected_class_labels should all have same lengths. Got'\n '[%d, %d, %d]' % len(detected_boxes),\n len(detected_scores), len(detected_class_labels))\n\n if image_key in self.detection_keys:\n logging.warn(\n 'image %s has already been added to the detection result database',\n image_key)\n return\n\n self.detection_keys.add(image_key)\n if image_key in self.groundtruth_boxes:\n groundtruth_boxes = self.groundtruth_boxes[image_key]\n groundtruth_class_labels = self.groundtruth_class_labels[image_key]\n # Masks are popped instead of look up. The reason is that we do not want\n # to keep all masks in memory which can cause memory overflow.\n groundtruth_masks = self.groundtruth_masks.pop(\n image_key)\n groundtruth_is_difficult_list = self.groundtruth_is_difficult_list[\n image_key]\n groundtruth_is_group_of_list = self.groundtruth_is_group_of_list[\n image_key]\n else:\n groundtruth_boxes = np.empty(shape=[0, 4], dtype=float)\n groundtruth_class_labels = np.array([], dtype=int)\n if detected_masks is None:\n groundtruth_masks = None\n else:\n groundtruth_masks = np.empty(shape=[0, 1, 1], dtype=float)\n groundtruth_is_difficult_list = np.array([], dtype=bool)\n groundtruth_is_group_of_list = np.array([], dtype=bool)\n scores, tp_fp_labels, is_class_correctly_detected_in_image = (\n self.per_image_eval.compute_object_detection_metrics(\n detected_boxes=detected_boxes,\n detected_scores=detected_scores,\n detected_class_labels=detected_class_labels,\n groundtruth_boxes=groundtruth_boxes,\n groundtruth_class_labels=groundtruth_class_labels,\n groundtruth_is_difficult_list=groundtruth_is_difficult_list,\n groundtruth_is_group_of_list=groundtruth_is_group_of_list,\n detected_masks=detected_masks,\n groundtruth_masks=groundtruth_masks))\n\n for i in range(self.num_class):\n if scores[i].shape[0] > 0:\n self.scores_per_class[i].append(scores[i])\n self.tp_fp_labels_per_class[i].append(tp_fp_labels[i])\n (self.num_images_correctly_detected_per_class\n ) += is_class_correctly_detected_in_image\n\n def _update_ground_truth_statistics(self, groundtruth_class_labels,\n groundtruth_is_difficult_list,\n groundtruth_is_group_of_list):\n \"\"\"Update grouth truth statitistics.\n\n 1. Difficult boxes are ignored when counting the number of ground truth\n instances as done in Pascal VOC devkit.\n 2. Difficult boxes are treated as normal boxes when computing CorLoc related\n statitistics.\n\n Args:\n groundtruth_class_labels: An integer numpy array of length M,\n representing M class labels of object instances in ground truth\n groundtruth_is_difficult_list: A boolean numpy array of length M denoting\n whether a ground truth box is a difficult instance or not\n groundtruth_is_group_of_list: A boolean numpy array of length M denoting\n whether a ground truth box is a group-of box or not\n \"\"\"\n for class_index in range(self.num_class):\n num_gt_instances = np.sum(groundtruth_class_labels[\n ~groundtruth_is_difficult_list\n & ~groundtruth_is_group_of_list] == class_index)\n num_groupof_gt_instances = self.group_of_weight * np.sum(\n groundtruth_class_labels[groundtruth_is_group_of_list] == class_index)\n self.num_gt_instances_per_class[\n class_index] += num_gt_instances + num_groupof_gt_instances\n if np.any(groundtruth_class_labels == class_index):\n self.num_gt_imgs_per_class[class_index] += 1\n\n def evaluate(self):\n \"\"\"Compute evaluation result.\n\n Returns:\n A named tuple with the following fields -\n average_precision: float numpy array of average precision for\n each class.\n mean_ap: mean average precision of all classes, float scalar\n precisions: List of precisions, each precision is a float numpy\n array\n recalls: List of recalls, each recall is a float numpy array\n corloc: numpy float array\n mean_corloc: Mean CorLoc score for each class, float scalar\n \"\"\"\n if (self.num_gt_instances_per_class == 0).any():\n logging.warn(\n 'The following classes have no ground truth examples: %s',\n np.squeeze(np.argwhere(self.num_gt_instances_per_class == 0)) +\n self.label_id_offset)\n\n if self.use_weighted_mean_ap:\n all_scores = np.array([], dtype=float)\n all_tp_fp_labels = np.array([], dtype=bool)\n for class_index in range(self.num_class):\n if self.num_gt_instances_per_class[class_index] == 0:\n continue\n if not self.scores_per_class[class_index]:\n scores = np.array([], dtype=float)\n tp_fp_labels = np.array([], dtype=float)\n else:\n scores = np.concatenate(self.scores_per_class[class_index])\n tp_fp_labels = np.concatenate(self.tp_fp_labels_per_class[class_index])\n if self.use_weighted_mean_ap:\n all_scores = np.append(all_scores, scores)\n all_tp_fp_labels = np.append(all_tp_fp_labels, tp_fp_labels)\n precision, recall = metrics.compute_precision_recall(\n scores, tp_fp_labels, self.num_gt_instances_per_class[class_index])\n\n self.precisions_per_class[class_index] = precision\n self.recalls_per_class[class_index] = recall\n average_precision = metrics.compute_average_precision(precision, recall)\n self.average_precision_per_class[class_index] = average_precision\n logging.info('average_precision: %f', average_precision)\n\n self.corloc_per_class = metrics.compute_cor_loc(\n self.num_gt_imgs_per_class,\n self.num_images_correctly_detected_per_class)\n\n if self.use_weighted_mean_ap:\n num_gt_instances = np.sum(self.num_gt_instances_per_class)\n precision, recall = metrics.compute_precision_recall(\n all_scores, all_tp_fp_labels, num_gt_instances)\n mean_ap = metrics.compute_average_precision(precision, recall)\n else:\n mean_ap = np.nanmean(self.average_precision_per_class)\n mean_corloc = np.nanmean(self.corloc_per_class)\n return ObjectDetectionEvalMetrics(\n self.average_precision_per_class, mean_ap, self.precisions_per_class,\n self.recalls_per_class, self.corloc_per_class, mean_corloc)\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\n\"\"\"Class to subsample minibatches by balancing positives and negatives.\n\nSubsamples minibatches based on a pre-specified positive fraction in range\n[0,1]. The class presumes there are many more negatives than positive examples:\nif the desired batch_size cannot be achieved with the pre-specified positive\nfraction, it fills the rest with negative examples. If this is not sufficient\nfor obtaining the desired batch_size, it returns fewer examples.\n\nThe main function to call is Subsample(self, indicator, labels). For convenience\none can also call SubsampleWeights(self, weights, labels) which is defined in\nthe minibatch_sampler base class.\n\nWhen is_static is True, it implements a method that guarantees static shapes.\nIt also ensures the length of output of the subsample is always batch_size, even\nwhen number of examples set to True in indicator is less than batch_size.\n\"\"\"\n\nimport tensorflow as tf\n\nfrom core import minibatch_sampler\nfrom utils import ops\n\n\nclass BalancedPositiveNegativeSampler(minibatch_sampler.MinibatchSampler):\n \"\"\"Subsamples minibatches to a desired balance of positives and negatives.\"\"\"\n\n def __init__(self, positive_fraction=0.5, is_static=False):\n \"\"\"Constructs a minibatch sampler.\n\n Args:\n positive_fraction: desired fraction of positive examples (scalar in [0,1])\n in the batch.\n is_static: If True, uses an implementation with static shape guarantees.\n\n Raises:\n ValueError: if positive_fraction < 0, or positive_fraction > 1\n \"\"\"\n if positive_fraction < 0 or positive_fraction > 1:\n raise ValueError('positive_fraction should be in range [0,1]. '\n 'Received: %s.' % positive_fraction)\n self._positive_fraction = positive_fraction\n self._is_static = is_static\n\n def _get_num_pos_neg_samples(self, sorted_indices_tensor, sample_size):\n \"\"\"Counts the number of positives and negatives numbers to be sampled.\n\n Args:\n sorted_indices_tensor: A sorted int32 tensor of shape [N] which contains\n the signed indices of the examples where the sign is based on the label\n value. The examples that cannot be sampled are set to 0. It samples\n atmost sample_size*positive_fraction positive examples and remaining\n from negative examples.\n sample_size: Size of subsamples.\n\n Returns:\n A tuple containing the number of positive and negative labels in the\n subsample.\n \"\"\"\n input_length = tf.shape(sorted_indices_tensor)[0]\n valid_positive_index = tf.greater(sorted_indices_tensor,\n tf.zeros(input_length, tf.int32))\n num_sampled_pos = tf.reduce_sum(tf.cast(valid_positive_index, tf.int32))\n max_num_positive_samples = tf.constant(\n int(sample_size * self._positive_fraction), tf.int32)\n num_positive_samples = tf.minimum(max_num_positive_samples, num_sampled_pos)\n num_negative_samples = tf.constant(sample_size,\n tf.int32) - num_positive_samples\n\n return num_positive_samples, num_negative_samples\n\n def _get_values_from_start_and_end(self, input_tensor, num_start_samples,\n num_end_samples, total_num_samples):\n \"\"\"slices num_start_samples and last num_end_samples from input_tensor.\n\n Args:\n input_tensor: An int32 tensor of shape [N] to be sliced.\n num_start_samples: Number of examples to be sliced from the beginning\n of the input tensor.\n num_end_samples: Number of examples to be sliced from the end of the\n input tensor.\n total_num_samples: Sum of is num_start_samples and num_end_samples. This\n should be a scalar.\n\n Returns:\n A tensor containing the first num_start_samples and last num_end_samples\n from input_tensor.\n\n \"\"\"\n input_length = tf.shape(input_tensor)[0]\n start_positions = tf.less(tf.range(input_length), num_start_samples)\n end_positions = tf.greater_equal(\n tf.range(input_length), input_length - num_end_samples)\n selected_positions = tf.logical_or(start_positions, end_positions)\n selected_positions = tf.cast(selected_positions, tf.float32)\n indexed_positions = tf.multiply(tf.cumsum(selected_positions),\n selected_positions)\n one_hot_selector = tf.one_hot(tf.cast(indexed_positions, tf.int32) - 1,\n total_num_samples,\n dtype=tf.float32)\n return tf.cast(tf.tensordot(tf.cast(input_tensor, tf.float32),\n one_hot_selector, axes=[0, 0]), tf.int32)\n\n def _static_subsample(self, indicator, batch_size, labels):\n \"\"\"Returns subsampled minibatch.\n\n Args:\n indicator: boolean tensor of shape [N] whose True entries can be sampled.\n N should be a complie time constant.\n batch_size: desired batch size. This scalar cannot be None.\n labels: boolean tensor of shape [N] denoting positive(=True) and negative\n (=False) examples. N should be a complie time constant.\n\n Returns:\n sampled_idx_indicator: boolean tensor of shape [N], True for entries which\n are sampled. It ensures the length of output of the subsample is always\n batch_size, even when number of examples set to True in indicator is\n less than batch_size.\n\n Raises:\n ValueError: if labels and indicator are not 1D boolean tensors.\n \"\"\"\n # Check if indicator and labels have a static size.\n if not indicator.shape.is_fully_defined():\n raise ValueError('indicator must be static in shape when is_static is'\n 'True')\n if not labels.shape.is_fully_defined():\n raise ValueError('labels must be static in shape when is_static is'\n 'True')\n if not isinstance(batch_size, int):\n raise ValueError('batch_size has to be an integer when is_static is'\n 'True.')\n\n input_length = tf.shape(indicator)[0]\n\n # Set the number of examples set True in indicator to be at least\n # batch_size.\n num_true_sampled = tf.reduce_sum(tf.cast(indicator, tf.float32))\n additional_false_sample = tf.less_equal(\n tf.cumsum(tf.cast(tf.logical_not(indicator), tf.float32)),\n batch_size - num_true_sampled)\n indicator = tf.logical_or(indicator, additional_false_sample)\n\n # Shuffle indicator and label. Need to store the permutation to restore the\n # order post sampling.\n permutation = tf.random_shuffle(tf.range(input_length))\n indicator = ops.matmul_gather_on_zeroth_axis(\n tf.cast(indicator, tf.float32), permutation)\n labels = ops.matmul_gather_on_zeroth_axis(\n tf.cast(labels, tf.float32), permutation)\n\n # index (starting from 1) when indicator is True, 0 when False\n indicator_idx = tf.where(\n tf.cast(indicator, tf.bool), tf.range(1, input_length + 1),\n tf.zeros(input_length, tf.int32))\n\n # Replace -1 for negative, +1 for positive labels\n signed_label = tf.where(\n tf.cast(labels, tf.bool), tf.ones(input_length, tf.int32),\n tf.scalar_mul(-1, tf.ones(input_length, tf.int32)))\n # negative of index for negative label, positive index for positive label,\n # 0 when indicator is False.\n signed_indicator_idx = tf.multiply(indicator_idx, signed_label)\n sorted_signed_indicator_idx = tf.nn.top_k(\n signed_indicator_idx, input_length, sorted=True).values\n\n [num_positive_samples,\n num_negative_samples] = self._get_num_pos_neg_samples(\n sorted_signed_indicator_idx, batch_size)\n\n sampled_idx = self._get_values_from_start_and_end(\n sorted_signed_indicator_idx, num_positive_samples,\n num_negative_samples, batch_size)\n\n # Shift the indices to start from 0 and remove any samples that are set as\n # False.\n sampled_idx = tf.abs(sampled_idx) - tf.ones(batch_size, tf.int32)\n sampled_idx = tf.multiply(\n tf.cast(tf.greater_equal(sampled_idx, tf.constant(0)), tf.int32),\n sampled_idx)\n\n sampled_idx_indicator = tf.cast(tf.reduce_sum(\n tf.one_hot(sampled_idx, depth=input_length),\n axis=0), tf.bool)\n\n # project back the order based on stored permutations\n reprojections = tf.one_hot(permutation, depth=input_length,\n dtype=tf.float32)\n return tf.cast(tf.tensordot(\n tf.cast(sampled_idx_indicator, tf.float32),\n reprojections, axes=[0, 0]), tf.bool)\n\n def subsample(self, indicator, batch_size, labels, scope=None):\n \"\"\"Returns subsampled minibatch.\n\n Args:\n indicator: boolean tensor of shape [N] whose True entries can be sampled.\n batch_size: desired batch size. If None, keeps all positive samples and\n randomly selects negative samples so that the positive sample fraction\n matches self._positive_fraction. It cannot be None is is_static is True.\n labels: boolean tensor of shape [N] denoting positive(=True) and negative\n (=False) examples.\n scope: name scope.\n\n Returns:\n sampled_idx_indicator: boolean tensor of shape [N], True for entries which\n are sampled.\n\n Raises:\n ValueError: if labels and indicator are not 1D boolean tensors.\n \"\"\"\n if len(indicator.get_shape().as_list()) != 1:\n raise ValueError('indicator must be 1 dimensional, got a tensor of '\n 'shape %s' % indicator.get_shape())\n if len(labels.get_shape().as_list()) != 1:\n raise ValueError('labels must be 1 dimensional, got a tensor of '\n 'shape %s' % labels.get_shape())\n if labels.dtype != tf.bool:\n raise ValueError('labels should be of type bool. Received: %s' %\n labels.dtype)\n if indicator.dtype != tf.bool:\n raise ValueError('indicator should be of type bool. Received: %s' %\n indicator.dtype)\n with tf.name_scope(scope, 'BalancedPositiveNegativeSampler'):\n if self._is_static:\n return self._static_subsample(indicator, batch_size, labels)\n\n else:\n # Only sample from indicated samples\n negative_idx = tf.logical_not(labels)\n positive_idx = tf.logical_and(labels, indicator)\n negative_idx = tf.logical_and(negative_idx, indicator)\n\n # Sample positive and negative samples separately\n if batch_size is None:\n max_num_pos = tf.reduce_sum(tf.to_int32(positive_idx))\n else:\n max_num_pos = int(self._positive_fraction * batch_size)\n sampled_pos_idx = self.subsample_indicator(positive_idx, max_num_pos)\n num_sampled_pos = tf.reduce_sum(tf.cast(sampled_pos_idx, tf.int32))\n if batch_size is None:\n negative_positive_ratio = (\n 1 - self._positive_fraction) / self._positive_fraction\n max_num_neg = tf.to_int32(\n negative_positive_ratio * tf.to_float(num_sampled_pos))\n else:\n max_num_neg = batch_size - num_sampled_pos\n sampled_neg_idx = self.subsample_indicator(negative_idx, max_num_neg)\n\n return tf.logical_or(sampled_pos_idx, sampled_neg_idx)\n", "# Copyright 2018 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\n\"\"\"Tests for ssd_mobilenet_v2_feature_extractor.\"\"\"\nfrom absl.testing import parameterized\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom models import ssd_feature_extractor_test\nfrom models import ssd_mobilenet_v2_feature_extractor\nfrom models import ssd_mobilenet_v2_keras_feature_extractor\n\nslim = tf.contrib.slim\n\n\[email protected](\n {'use_keras': False},\n {'use_keras': True},\n)\nclass SsdMobilenetV2FeatureExtractorTest(\n ssd_feature_extractor_test.SsdFeatureExtractorTestBase):\n\n def _create_feature_extractor(self, depth_multiplier, pad_to_multiple,\n use_explicit_padding=False, use_keras=False):\n \"\"\"Constructs a new feature extractor.\n\n Args:\n depth_multiplier: float depth multiplier for feature extractor\n pad_to_multiple: the nearest multiple to zero pad the input height and\n width dimensions to.\n use_explicit_padding: use 'VALID' padding for convolutions, but prepad\n inputs so that the output dimensions are the same as if 'SAME' padding\n were used.\n use_keras: if True builds a keras-based feature extractor, if False builds\n a slim-based one.\n Returns:\n an ssd_meta_arch.SSDFeatureExtractor object.\n \"\"\"\n min_depth = 32\n if use_keras:\n return (ssd_mobilenet_v2_keras_feature_extractor.\n SSDMobileNetV2KerasFeatureExtractor(\n is_training=False,\n depth_multiplier=depth_multiplier,\n min_depth=min_depth,\n pad_to_multiple=pad_to_multiple,\n conv_hyperparams=self._build_conv_hyperparams(),\n freeze_batchnorm=False,\n inplace_batchnorm_update=False,\n use_explicit_padding=use_explicit_padding,\n name='MobilenetV2'))\n else:\n return ssd_mobilenet_v2_feature_extractor.SSDMobileNetV2FeatureExtractor(\n False,\n depth_multiplier,\n min_depth,\n pad_to_multiple,\n self.conv_hyperparams_fn,\n use_explicit_padding=use_explicit_padding)\n\n def test_extract_features_returns_correct_shapes_128(self, use_keras):\n image_height = 128\n image_width = 128\n depth_multiplier = 1.0\n pad_to_multiple = 1\n expected_feature_map_shape = [(2, 8, 8, 576), (2, 4, 4, 1280),\n (2, 2, 2, 512), (2, 1, 1, 256),\n (2, 1, 1, 256), (2, 1, 1, 128)]\n self.check_extract_features_returns_correct_shape(\n 2, image_height, image_width, depth_multiplier, pad_to_multiple,\n expected_feature_map_shape, use_keras=use_keras)\n\n def test_extract_features_returns_correct_shapes_128_explicit_padding(\n self, use_keras):\n image_height = 128\n image_width = 128\n depth_multiplier = 1.0\n pad_to_multiple = 1\n expected_feature_map_shape = [(2, 8, 8, 576), (2, 4, 4, 1280),\n (2, 2, 2, 512), (2, 1, 1, 256),\n (2, 1, 1, 256), (2, 1, 1, 128)]\n self.check_extract_features_returns_correct_shape(\n 2, image_height, image_width, depth_multiplier, pad_to_multiple,\n expected_feature_map_shape, use_explicit_padding=True,\n use_keras=use_keras)\n\n def test_extract_features_returns_correct_shapes_with_dynamic_inputs(\n self, use_keras):\n image_height = 128\n image_width = 128\n depth_multiplier = 1.0\n pad_to_multiple = 1\n expected_feature_map_shape = [(2, 8, 8, 576), (2, 4, 4, 1280),\n (2, 2, 2, 512), (2, 1, 1, 256),\n (2, 1, 1, 256), (2, 1, 1, 128)]\n self.check_extract_features_returns_correct_shapes_with_dynamic_inputs(\n 2, image_height, image_width, depth_multiplier, pad_to_multiple,\n expected_feature_map_shape, use_keras=use_keras)\n\n def test_extract_features_returns_correct_shapes_299(self, use_keras):\n image_height = 299\n image_width = 299\n depth_multiplier = 1.0\n pad_to_multiple = 1\n expected_feature_map_shape = [(2, 19, 19, 576), (2, 10, 10, 1280),\n (2, 5, 5, 512), (2, 3, 3, 256),\n (2, 2, 2, 256), (2, 1, 1, 128)]\n self.check_extract_features_returns_correct_shape(\n 2, image_height, image_width, depth_multiplier, pad_to_multiple,\n expected_feature_map_shape, use_keras=use_keras)\n\n def test_extract_features_returns_correct_shapes_enforcing_min_depth(\n self, use_keras):\n image_height = 299\n image_width = 299\n depth_multiplier = 0.5**12\n pad_to_multiple = 1\n expected_feature_map_shape = [(2, 19, 19, 192), (2, 10, 10, 32),\n (2, 5, 5, 32), (2, 3, 3, 32),\n (2, 2, 2, 32), (2, 1, 1, 32)]\n self.check_extract_features_returns_correct_shape(\n 2, image_height, image_width, depth_multiplier, pad_to_multiple,\n expected_feature_map_shape, use_keras=use_keras)\n\n def test_extract_features_returns_correct_shapes_with_pad_to_multiple(\n self, use_keras):\n image_height = 299\n image_width = 299\n depth_multiplier = 1.0\n pad_to_multiple = 32\n expected_feature_map_shape = [(2, 20, 20, 576), (2, 10, 10, 1280),\n (2, 5, 5, 512), (2, 3, 3, 256),\n (2, 2, 2, 256), (2, 1, 1, 128)]\n self.check_extract_features_returns_correct_shape(\n 2, image_height, image_width, depth_multiplier, pad_to_multiple,\n expected_feature_map_shape, use_keras=use_keras)\n\n def test_extract_features_raises_error_with_invalid_image_size(\n self, use_keras):\n image_height = 32\n image_width = 32\n depth_multiplier = 1.0\n pad_to_multiple = 1\n self.check_extract_features_raises_error_with_invalid_image_size(\n image_height, image_width, depth_multiplier, pad_to_multiple,\n use_keras=use_keras)\n\n def test_preprocess_returns_correct_value_range(self, use_keras):\n image_height = 128\n image_width = 128\n depth_multiplier = 1\n pad_to_multiple = 1\n test_image = np.random.rand(4, image_height, image_width, 3)\n feature_extractor = self._create_feature_extractor(depth_multiplier,\n pad_to_multiple,\n use_keras=use_keras)\n preprocessed_image = feature_extractor.preprocess(test_image)\n self.assertTrue(np.all(np.less_equal(np.abs(preprocessed_image), 1.0)))\n\n def test_variables_only_created_in_scope(self, use_keras):\n depth_multiplier = 1\n pad_to_multiple = 1\n scope_name = 'MobilenetV2'\n self.check_feature_extractor_variables_under_scope(\n depth_multiplier, pad_to_multiple, scope_name, use_keras=use_keras)\n\n def test_variable_count(self, use_keras):\n depth_multiplier = 1\n pad_to_multiple = 1\n variables = self.get_feature_extractor_variables(\n depth_multiplier, pad_to_multiple, use_keras=use_keras)\n self.assertEqual(len(variables), 292)\n\n def test_has_fused_batchnorm(self, use_keras):\n image_height = 40\n image_width = 40\n depth_multiplier = 1\n pad_to_multiple = 1\n image_placeholder = tf.placeholder(tf.float32,\n [1, image_height, image_width, 3])\n feature_extractor = self._create_feature_extractor(depth_multiplier,\n pad_to_multiple,\n use_keras=use_keras)\n preprocessed_image = feature_extractor.preprocess(image_placeholder)\n if use_keras:\n _ = feature_extractor(preprocessed_image)\n else:\n _ = feature_extractor.extract_features(preprocessed_image)\n self.assertTrue(any(op.type == 'FusedBatchNorm'\n for op in tf.get_default_graph().get_operations()))\n\n\nif __name__ == '__main__':\n tf.test.main()\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\"\"\"tf.data.Dataset builder.\n\nCreates data sources for DetectionModels from an InputReader config. See\ninput_reader.proto for options.\n\nNote: If users wishes to also use their own InputReaders with the Object\nDetection configuration framework, they should define their own builder function\nthat wraps the build function.\n\"\"\"\nimport functools\nimport tensorflow as tf\n\nfrom data_decoders import tf_example_decoder\nfrom protos import input_reader_pb2\n\n\ndef make_initializable_iterator(dataset):\n \"\"\"Creates an iterator, and initializes tables.\n\n This is useful in cases where make_one_shot_iterator wouldn't work because\n the graph contains a hash table that needs to be initialized.\n\n Args:\n dataset: A `tf.data.Dataset` object.\n\n Returns:\n A `tf.data.Iterator`.\n \"\"\"\n iterator = dataset.make_initializable_iterator()\n tf.add_to_collection(tf.GraphKeys.TABLE_INITIALIZERS, iterator.initializer)\n return iterator\n\n\ndef read_dataset(file_read_func, input_files, config):\n \"\"\"Reads a dataset, and handles repetition and shuffling.\n\n Args:\n file_read_func: Function to use in tf.contrib.data.parallel_interleave, to\n read every individual file into a tf.data.Dataset.\n input_files: A list of file paths to read.\n config: A input_reader_builder.InputReader object.\n\n Returns:\n A tf.data.Dataset of (undecoded) tf-records based on config.\n \"\"\"\n # Shard, shuffle, and read files.\n filenames = tf.gfile.Glob(input_files)\n num_readers = config.num_readers\n if num_readers > len(filenames):\n num_readers = len(filenames)\n tf.logging.warning('num_readers has been reduced to %d to match input file '\n 'shards.' % num_readers)\n filename_dataset = tf.data.Dataset.from_tensor_slices(filenames)\n if config.shuffle:\n filename_dataset = filename_dataset.shuffle(\n config.filenames_shuffle_buffer_size)\n elif num_readers > 1:\n tf.logging.warning('`shuffle` is false, but the input data stream is '\n 'still slightly shuffled since `num_readers` > 1.')\n filename_dataset = filename_dataset.repeat(config.num_epochs or None)\n records_dataset = filename_dataset.apply(\n tf.contrib.data.parallel_interleave(\n file_read_func,\n cycle_length=num_readers,\n block_length=config.read_block_length,\n sloppy=config.shuffle))\n if config.shuffle:\n records_dataset = records_dataset.shuffle(config.shuffle_buffer_size)\n return records_dataset\n\n\ndef build(input_reader_config, batch_size=None, transform_input_data_fn=None):\n \"\"\"Builds a tf.data.Dataset.\n\n Builds a tf.data.Dataset by applying the `transform_input_data_fn` on all\n records. Applies a padded batch to the resulting dataset.\n\n Args:\n input_reader_config: A input_reader_pb2.InputReader object.\n batch_size: Batch size. If batch size is None, no batching is performed.\n transform_input_data_fn: Function to apply transformation to all records,\n or None if no extra decoding is required.\n\n Returns:\n A tf.data.Dataset based on the input_reader_config.\n\n Raises:\n ValueError: On invalid input reader proto.\n ValueError: If no input paths are specified.\n \"\"\"\n if not isinstance(input_reader_config, input_reader_pb2.InputReader):\n raise ValueError('input_reader_config not of type '\n 'input_reader_pb2.InputReader.')\n\n if input_reader_config.WhichOneof('input_reader') == 'tf_record_input_reader':\n config = input_reader_config.tf_record_input_reader\n if not config.input_path:\n raise ValueError('At least one input path must be specified in '\n '`input_reader_config`.')\n\n label_map_proto_file = None\n if input_reader_config.HasField('label_map_path'):\n label_map_proto_file = input_reader_config.label_map_path\n decoder = tf_example_decoder.TfExampleDecoder(\n load_instance_masks=input_reader_config.load_instance_masks,\n instance_mask_type=input_reader_config.mask_type,\n label_map_proto_file=label_map_proto_file,\n use_display_name=input_reader_config.use_display_name,\n num_additional_channels=input_reader_config.num_additional_channels)\n\n def process_fn(value):\n \"\"\"Sets up tf graph that decodes, transforms and pads input data.\"\"\"\n processed_tensors = decoder.decode(value)\n if transform_input_data_fn is not None:\n processed_tensors = transform_input_data_fn(processed_tensors)\n return processed_tensors\n\n dataset = read_dataset(\n functools.partial(tf.data.TFRecordDataset, buffer_size=8 * 1000 * 1000),\n config.input_path[:], input_reader_config)\n if input_reader_config.sample_1_of_n_examples > 1:\n dataset = dataset.shard(input_reader_config.sample_1_of_n_examples, 0)\n # TODO(rathodv): make batch size a required argument once the old binaries\n # are deleted.\n if batch_size:\n num_parallel_calls = batch_size * input_reader_config.num_parallel_batches\n else:\n num_parallel_calls = input_reader_config.num_parallel_map_calls\n dataset = dataset.map(\n process_fn,\n num_parallel_calls=num_parallel_calls)\n if batch_size:\n dataset = dataset.apply(\n tf.contrib.data.batch_and_drop_remainder(batch_size))\n dataset = dataset.prefetch(input_reader_config.num_prefetch_batches)\n return dataset\n\n raise ValueError('Unsupported input_reader_config.')\n" ]
[ [ "tensorflow.constant", "numpy.sqrt", "tensorflow.minimum", "tensorflow.ones", "tensorflow.to_float" ], [ "pandas.concat", "pandas.read_csv", "tensorflow.gfile.Open", "tensorflow.flags.DEFINE_string", "tensorflow.logging.log_every_n", "pandas.DataFrame", "tensorflow.logging.set_verbosity", "tensorflow.flags.DEFINE_integer", "tensorflow.app.run" ], [ "numpy.isin", "tensorflow.control_dependencies", "numpy.ones", "numpy.concatenate", "numpy.argwhere", "numpy.append", "numpy.nanmean", "numpy.isscalar", "tensorflow.py_func", "numpy.float32", "numpy.any", "numpy.array", "numpy.zeros", "numpy.sum", "numpy.empty" ], [ "tensorflow.multiply", "tensorflow.constant", "tensorflow.range", "tensorflow.shape", "tensorflow.logical_or", "tensorflow.zeros", "tensorflow.logical_and", "tensorflow.minimum", "tensorflow.cast", "tensorflow.ones", "tensorflow.nn.top_k", "tensorflow.one_hot", "tensorflow.name_scope", "tensorflow.to_float", "tensorflow.to_int32", "tensorflow.logical_not", "tensorflow.abs", "tensorflow.cumsum" ], [ "numpy.abs", "tensorflow.placeholder", "tensorflow.test.main", "numpy.random.rand", "tensorflow.get_default_graph" ], [ "tensorflow.logging.warning", "tensorflow.data.Dataset.from_tensor_slices", "tensorflow.contrib.data.parallel_interleave", "tensorflow.gfile.Glob", "tensorflow.add_to_collection", "tensorflow.contrib.data.batch_and_drop_remainder" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.5", "1.7", "0.12", "1.0", "1.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [ "1.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7" ] } ]
FrancisTembo/tensorflow-models
[ "042f74690d0cf412cb6b7fc19f4a41afdf547905" ]
[ "syntaxnet/dragnn/python/wrapped_units.py" ]
[ "\"\"\"Network units wrapping TensorFlows' tf.contrib.rnn cells.\n\nPlease put all wrapping logic for tf.contrib.rnn in this module; this will help\ncollect common subroutines that prove useful.\n\"\"\"\n\nimport abc\n\nimport tensorflow as tf\n\nfrom dragnn.python import network_units as dragnn\nfrom syntaxnet.util import check\n\n\nclass BaseLSTMNetwork(dragnn.NetworkUnitInterface):\n \"\"\"Base class for wrapped LSTM networks.\n\n This LSTM network unit supports multiple layers with layer normalization.\n Because it is imported from tf.contrib.rnn, we need to capture the created\n variables during initialization time.\n\n Layers:\n ...subclass-specific layers...\n last_layer: Alias for the activations of the last hidden layer.\n logits: Logits associated with component actions.\n \"\"\"\n\n def __init__(self, component):\n \"\"\"Initializes the LSTM base class.\n\n Parameters used:\n hidden_layer_sizes: Comma-delimited number of hidden units for each layer.\n input_dropout_rate (-1.0): Input dropout rate for each layer. If < 0.0,\n use the global |dropout_rate| hyperparameter.\n recurrent_dropout_rate (0.8): Recurrent dropout rate. If < 0.0, use the\n global |recurrent_dropout_rate| hyperparameter.\n layer_norm (True): Whether or not to use layer norm.\n\n Hyperparameters used:\n dropout_rate: Input dropout rate.\n recurrent_dropout_rate: Recurrent dropout rate.\n\n Args:\n component: parent ComponentBuilderBase object.\n \"\"\"\n self._attrs = dragnn.get_attrs_with_defaults(\n component.spec.network_unit.parameters,\n defaults={\n 'layer_norm': True,\n 'input_dropout_rate': -1.0,\n 'recurrent_dropout_rate': 0.8,\n 'hidden_layer_sizes': '256',\n })\n\n self._hidden_layer_sizes = map(int,\n self._attrs['hidden_layer_sizes'].split(','))\n\n self._input_dropout_rate = self._attrs['input_dropout_rate']\n if self._input_dropout_rate < 0.0:\n self._input_dropout_rate = component.master.hyperparams.dropout_rate\n\n self._recurrent_dropout_rate = self._attrs['recurrent_dropout_rate']\n if self._recurrent_dropout_rate < 0.0:\n self._recurrent_dropout_rate = (\n component.master.hyperparams.recurrent_dropout_rate)\n if self._recurrent_dropout_rate < 0.0:\n self._recurrent_dropout_rate = component.master.hyperparams.dropout_rate\n\n tf.logging.info('[%s] input_dropout_rate=%s recurrent_dropout_rate=%s',\n component.name, self._input_dropout_rate,\n self._recurrent_dropout_rate)\n\n layers, context_layers = self.create_hidden_layers(component,\n self._hidden_layer_sizes)\n last_layer_dim = layers[-1].dim\n layers.append(\n dragnn.Layer(component, name='last_layer', dim=last_layer_dim))\n layers.append(\n dragnn.Layer(component, name='logits', dim=component.num_actions))\n\n # Provide initial layers and context layers, so the base class constructor\n # can safely use accessors like get_layer_size().\n super(BaseLSTMNetwork, self).__init__(\n component, init_layers=layers, init_context_layers=context_layers)\n\n # Allocate parameters for the softmax.\n self._params.append(\n tf.get_variable(\n 'weights_softmax', [last_layer_dim, component.num_actions],\n initializer=tf.random_normal_initializer(\n stddev=1e-4, seed=self._seed)))\n self._params.append(\n tf.get_variable(\n 'bias_softmax', [component.num_actions],\n initializer=tf.zeros_initializer()))\n\n def get_logits(self, network_tensors):\n \"\"\"Returns the logits for prediction.\"\"\"\n return network_tensors[self.get_layer_index('logits')]\n\n @abc.abstractmethod\n def create_hidden_layers(self, component, hidden_layer_sizes):\n \"\"\"Creates hidden network layers.\n\n Args:\n component: Parent ComponentBuilderBase object.\n hidden_layer_sizes: List of requested hidden layer activation sizes.\n\n Returns:\n layers: List of layers created by this network.\n context_layers: List of context layers created by this network.\n \"\"\"\n pass\n\n def _append_base_layers(self, hidden_layers):\n \"\"\"Appends layers defined by the base class to the |hidden_layers|.\"\"\"\n last_layer = hidden_layers[-1]\n\n # TODO(googleuser): Uncomment the version that uses component.get_variable()\n # and delete the uses of tf.get_variable().\n # logits = tf.nn.xw_plus_b(last_layer,\n # self._component.get_variable('weights_softmax'),\n # self._component.get_variable('bias_softmax'))\n logits = tf.nn.xw_plus_b(last_layer,\n tf.get_variable('weights_softmax'),\n tf.get_variable('bias_softmax'))\n return hidden_layers + [last_layer, logits]\n\n def _create_cell(self, num_units, during_training):\n \"\"\"Creates a single LSTM cell, possibly with dropout.\n\n Requires that BaseLSTMNetwork.__init__() was called.\n\n Args:\n num_units: Number of hidden units in the cell.\n during_training: Whether to create a cell for training (vs inference).\n\n Returns:\n A RNNCell of the requested size, possibly with dropout.\n \"\"\"\n # No dropout in inference mode.\n if not during_training:\n return tf.contrib.rnn.LayerNormBasicLSTMCell(\n num_units, layer_norm=self._attrs['layer_norm'], reuse=True)\n\n # Otherwise, apply dropout to inputs and recurrences.\n cell = tf.contrib.rnn.LayerNormBasicLSTMCell(\n num_units,\n dropout_keep_prob=self._recurrent_dropout_rate,\n layer_norm=self._attrs['layer_norm'])\n cell = tf.contrib.rnn.DropoutWrapper(\n cell, input_keep_prob=self._input_dropout_rate)\n return cell\n\n def _create_train_cells(self):\n \"\"\"Creates a list of LSTM cells for training.\"\"\"\n return [\n self._create_cell(num_units, during_training=True)\n for num_units in self._hidden_layer_sizes\n ]\n\n def _create_inference_cells(self):\n \"\"\"Creates a list of LSTM cells for inference.\"\"\"\n return [\n self._create_cell(num_units, during_training=False)\n for num_units in self._hidden_layer_sizes\n ]\n\n def _capture_variables_as_params(self, function):\n \"\"\"Captures variables created by a function in |self._params|.\n\n Args:\n function: Function whose variables should be captured. The function\n should take one argument, its enclosing variable scope.\n \"\"\"\n created_vars = {}\n\n def _custom_getter(getter, *args, **kwargs):\n \"\"\"Calls the real getter and captures its result in |created_vars|.\"\"\"\n real_variable = getter(*args, **kwargs)\n created_vars[real_variable.name] = real_variable\n return real_variable\n\n with tf.variable_scope(\n 'cell', reuse=None, custom_getter=_custom_getter) as scope:\n function(scope)\n self._params.extend(created_vars.values())\n\n def _apply_with_captured_variables(self, function):\n \"\"\"Applies a function using previously-captured variables.\n\n Args:\n function: Function to apply using captured variables. The function\n should take one argument, its enclosing variable scope.\n\n Returns:\n Results of function application.\n \"\"\"\n\n def _custom_getter(getter, *args, **kwargs):\n \"\"\"Retrieves the normal or moving-average variables.\"\"\"\n return self._component.get_variable(var_params=getter(*args, **kwargs))\n\n with tf.variable_scope(\n 'cell', reuse=True, custom_getter=_custom_getter) as scope:\n return function(scope)\n\n\nclass LayerNormBasicLSTMNetwork(BaseLSTMNetwork):\n \"\"\"Wrapper around tf.contrib.rnn.LayerNormBasicLSTMCell.\n\n Features:\n All inputs are concatenated.\n\n Subclass-specific layers:\n state_c_<n>: Cell states for the <n>'th LSTM layer (0-origin).\n state_h_<n>: Hidden states for the <n>'th LSTM layer (0-origin).\n \"\"\"\n\n def __init__(self, component):\n \"\"\"Sets up context and output layers, as well as a final softmax.\"\"\"\n super(LayerNormBasicLSTMNetwork, self).__init__(component)\n\n # Wrap lists of training and inference sub-cells into multi-layer RNN cells.\n # Note that a |MultiRNNCell| state is a tuple of per-layer sub-states.\n self._train_cell = tf.contrib.rnn.MultiRNNCell(self._create_train_cells())\n self._inference_cell = tf.contrib.rnn.MultiRNNCell(\n self._create_inference_cells())\n\n def _cell_closure(scope):\n \"\"\"Applies the LSTM cell to placeholder inputs and state.\"\"\"\n placeholder_inputs = tf.placeholder(\n dtype=tf.float32, shape=(1, self._concatenated_input_dim))\n\n placeholder_substates = []\n for num_units in self._hidden_layer_sizes:\n placeholder_substate = tf.contrib.rnn.LSTMStateTuple(\n tf.placeholder(dtype=tf.float32, shape=(1, num_units)),\n tf.placeholder(dtype=tf.float32, shape=(1, num_units)))\n placeholder_substates.append(placeholder_substate)\n placeholder_state = tuple(placeholder_substates)\n\n self._train_cell(\n inputs=placeholder_inputs, state=placeholder_state, scope=scope)\n\n self._capture_variables_as_params(_cell_closure)\n\n def create_hidden_layers(self, component, hidden_layer_sizes):\n \"\"\"See base class.\"\"\"\n # Construct the layer meta info for the DRAGNN builder. Note that the order\n # of h and c are reversed compared to the vanilla DRAGNN LSTM cell, as\n # this is the standard in tf.contrib.rnn.\n #\n # NB: The h activations of the last LSTM must be the last layer, in order\n # for _append_base_layers() to work.\n layers = []\n for index, num_units in enumerate(hidden_layer_sizes):\n layers.append(\n dragnn.Layer(component, name='state_c_%d' % index, dim=num_units))\n layers.append(\n dragnn.Layer(component, name='state_h_%d' % index, dim=num_units))\n context_layers = list(layers) # copy |layers|, don't alias it\n return layers, context_layers\n\n def create(self,\n fixed_embeddings,\n linked_embeddings,\n context_tensor_arrays,\n attention_tensor,\n during_training,\n stride=None):\n \"\"\"See base class.\"\"\"\n # NB: This cell pulls the lstm's h and c vectors from context_tensor_arrays\n # instead of through linked features.\n check.Eq(\n len(context_tensor_arrays), 2 * len(self._hidden_layer_sizes),\n 'require two context tensors per hidden layer')\n\n # Rearrange the context tensors into a tuple of LSTM sub-states.\n length = context_tensor_arrays[0].size()\n substates = []\n for index, num_units in enumerate(self._hidden_layer_sizes):\n state_c = context_tensor_arrays[2 * index].read(length - 1)\n state_h = context_tensor_arrays[2 * index + 1].read(length - 1)\n\n # Fix shapes that for some reason are not set properly for an unknown\n # reason. TODO(googleuser): Why are the shapes not set?\n state_c.set_shape([tf.Dimension(None), num_units])\n state_h.set_shape([tf.Dimension(None), num_units])\n substates.append(tf.contrib.rnn.LSTMStateTuple(state_c, state_h))\n state = tuple(substates)\n\n input_tensor = dragnn.get_input_tensor(fixed_embeddings, linked_embeddings)\n cell = self._train_cell if during_training else self._inference_cell\n\n def _cell_closure(scope):\n \"\"\"Applies the LSTM cell to the current inputs and state.\"\"\"\n return cell(input_tensor, state, scope)\n\n unused_h, state = self._apply_with_captured_variables(_cell_closure)\n\n # Return tensors to be put into the tensor arrays / used to compute\n # objective.\n output_tensors = []\n for new_substate in state:\n new_c, new_h = new_substate\n output_tensors.append(new_c)\n output_tensors.append(new_h)\n return self._append_base_layers(output_tensors)\n\n\nclass BulkBiLSTMNetwork(BaseLSTMNetwork):\n \"\"\"Bulk wrapper around tf.contrib.rnn.stack_bidirectional_dynamic_rnn().\n\n Features:\n lengths: [stride, 1] sequence lengths per batch item.\n All other features are concatenated into input activations.\n\n Subclass-specific layers:\n outputs: [stride * num_steps, self._output_dim] bi-LSTM activations.\n \"\"\"\n\n def __init__(self, component):\n super(BulkBiLSTMNetwork, self).__init__(component)\n\n check.In('lengths', self._linked_feature_dims,\n 'Missing required linked feature')\n check.Eq(self._linked_feature_dims['lengths'], 1,\n 'Wrong dimension for \"lengths\" feature')\n self._input_dim = self._concatenated_input_dim - 1 # exclude 'lengths'\n self._output_dim = self.get_layer_size('outputs')\n tf.logging.info('[%s] Bulk bi-LSTM with input_dim=%d output_dim=%d',\n component.name, self._input_dim, self._output_dim)\n\n # Create one training and inference cell per layer and direction.\n self._train_cells_forward = self._create_train_cells()\n self._train_cells_backward = self._create_train_cells()\n self._inference_cells_forward = self._create_inference_cells()\n self._inference_cells_backward = self._create_inference_cells()\n\n def _bilstm_closure(scope):\n \"\"\"Applies the bi-LSTM to placeholder inputs and lengths.\"\"\"\n # Use singleton |stride| and |steps| because their values don't affect the\n # weight variables.\n stride, steps = 1, 1\n placeholder_inputs = tf.placeholder(\n dtype=tf.float32, shape=[stride, steps, self._input_dim])\n placeholder_lengths = tf.placeholder(dtype=tf.int64, shape=[stride])\n\n # Omit the initial states and sequence lengths for simplicity; they don't\n # affect the weight variables.\n tf.contrib.rnn.stack_bidirectional_dynamic_rnn(\n self._train_cells_forward,\n self._train_cells_backward,\n placeholder_inputs,\n dtype=tf.float32,\n sequence_length=placeholder_lengths,\n scope=scope)\n\n self._capture_variables_as_params(_bilstm_closure)\n\n # Allocate parameters for the initial states. Note that an LSTM state is a\n # tuple of two substates (c, h), so there are 4 variables per layer.\n for index, num_units in enumerate(self._hidden_layer_sizes):\n for direction in ['forward', 'backward']:\n for substate in ['c', 'h']:\n self._params.append(\n tf.get_variable(\n 'initial_state_%s_%s_%d' % (direction, substate, index),\n [1, num_units], # leading 1 for later batch-wise tiling\n dtype=tf.float32,\n initializer=tf.constant_initializer(0.0)))\n\n def create_hidden_layers(self, component, hidden_layer_sizes):\n \"\"\"See base class.\"\"\"\n dim = 2 * hidden_layer_sizes[-1]\n return [dragnn.Layer(component, name='outputs', dim=dim)], []\n\n def create(self,\n fixed_embeddings,\n linked_embeddings,\n context_tensor_arrays,\n attention_tensor,\n during_training,\n stride=None):\n \"\"\"Requires |stride|; otherwise see base class.\"\"\"\n check.NotNone(stride,\n 'BulkBiLSTMNetwork requires \"stride\" and must be called '\n 'in the bulk feature extractor component.')\n\n # Flatten the lengths into a vector.\n lengths = dragnn.lookup_named_tensor('lengths', linked_embeddings)\n lengths_s = tf.squeeze(lengths.tensor, [1])\n\n # Collect all other inputs into a batched tensor.\n linked_embeddings = [\n named_tensor for named_tensor in linked_embeddings\n if named_tensor.name != 'lengths'\n ]\n inputs_sxnxd = dragnn.get_input_tensor_with_stride(\n fixed_embeddings, linked_embeddings, stride)\n\n # Since get_input_tensor_with_stride() concatenates the input embeddings, it\n # obscures the static activation dimension, which the RNN library requires.\n # Restore it using set_shape(). Note that set_shape() merges into the known\n # shape, so only specify the activation dimension.\n inputs_sxnxd.set_shape(\n [tf.Dimension(None), tf.Dimension(None), self._input_dim])\n\n initial_states_forward, initial_states_backward = (\n self._create_initial_states(stride))\n\n if during_training:\n cells_forward = self._train_cells_forward\n cells_backward = self._train_cells_backward\n else:\n cells_forward = self._inference_cells_forward\n cells_backward = self._inference_cells_backward\n\n def _bilstm_closure(scope):\n \"\"\"Applies the bi-LSTM to the current inputs.\"\"\"\n outputs_sxnxd, _, _ = tf.contrib.rnn.stack_bidirectional_dynamic_rnn(\n cells_forward,\n cells_backward,\n inputs_sxnxd,\n initial_states_fw=initial_states_forward,\n initial_states_bw=initial_states_backward,\n sequence_length=lengths_s,\n scope=scope)\n return outputs_sxnxd\n\n # Layer outputs are not batched; flatten out the batch dimension.\n outputs_sxnxd = self._apply_with_captured_variables(_bilstm_closure)\n outputs_snxd = tf.reshape(outputs_sxnxd, [-1, self._output_dim])\n return self._append_base_layers([outputs_snxd])\n\n def _create_initial_states(self, stride):\n \"\"\"Returns stacked and batched initial states for the bi-LSTM.\"\"\"\n initial_states_forward = []\n initial_states_backward = []\n for index in range(len(self._hidden_layer_sizes)):\n # Retrieve the initial states for this layer.\n states_sxd = []\n for direction in ['forward', 'backward']:\n for substate in ['c', 'h']:\n state_1xd = self._component.get_variable('initial_state_%s_%s_%d' %\n (direction, substate, index))\n state_sxd = tf.tile(state_1xd, [stride, 1]) # tile across the batch\n states_sxd.append(state_sxd)\n\n # Assemble and append forward and backward LSTM states.\n initial_states_forward.append(\n tf.contrib.rnn.LSTMStateTuple(states_sxd[0], states_sxd[1]))\n initial_states_backward.append(\n tf.contrib.rnn.LSTMStateTuple(states_sxd[2], states_sxd[3]))\n return initial_states_forward, initial_states_backward\n" ]
[ [ "tensorflow.get_variable", "tensorflow.contrib.rnn.LayerNormBasicLSTMCell", "tensorflow.contrib.rnn.stack_bidirectional_dynamic_rnn", "tensorflow.contrib.rnn.DropoutWrapper", "tensorflow.Dimension", "tensorflow.zeros_initializer", "tensorflow.reshape", "tensorflow.squeeze", "tensorflow.placeholder", "tensorflow.constant_initializer", "tensorflow.contrib.rnn.LSTMStateTuple", "tensorflow.logging.info", "tensorflow.variable_scope", "tensorflow.random_normal_initializer", "tensorflow.tile" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.4", "1.5", "1.7", "0.12", "1.0", "1.2" ] } ]
bobolee1239/levoice
[ "56f20afe15f9e171b8971e14551180180cb86cfb" ]
[ "script/model/LeVoice.py" ]
[ "# ----------------------------------\n# File: LeVoice.py\n# ----------------------------------\nimport sys \nif '..' not in sys.path:\n sys.path.append('..')\n\nimport torch\nimport torch.nn.functional as F\nimport config\n\nfrom torch import nn\n\n# -----------------------------------------\n\ndef pad_freq(x, padding):\n '''\n Args:\n --------\n - x: (N, ch, nFrm, nFreq)\n - padding: (freq_low, freq_up)\n '''\n return F.pad(x, padding, \"constant\", 0) \n\ndef pad_time(x, padding):\n '''\n Args:\n --------\n - x: (N, ch, nFrm, nFreq)\n - padding: (time_left, time_right)\n '''\n return F.pad(x, (0, 0, *padding), \"constant\", 0) \n\n\nclass LeVoice(nn.Module):\n def __init__(self, nfreq):\n super(LeVoice, self).__init__()\n\n self.nfreq = nfreq\n \n nclass = config.N_CLASS\n nhid = 128\n\n self.relu = nn.ReLU()\n\n self.conv1 = nn.Conv2d(1, 4, (3, 3))\n self.bn1 = nn.BatchNorm2d(4)\n\n self.conv2_dep = nn.Conv2d(4, 8, (3, 3), groups=4)\n self.conv2_pt = nn.Conv2d(8, 8, (1, 1))\n self.bn2 = nn.BatchNorm2d(8)\n\n self.conv3_dep = nn.Conv2d( 8, 16, (3, 1), groups=8)\n self.conv3_pt = nn.Conv2d(16, 16, (1, 1))\n self.bn3 = nn.BatchNorm2d(16)\n\n self.conv4_dep = nn.Conv2d(16, 32, (3, 1), groups=16)\n self.conv4_pt = nn.Conv2d(32, 32, (1, 1))\n self.bn4 = nn.BatchNorm2d(32)\n\n self.pre_gru_pt = nn.Conv2d(32, 8, (1, 1))\n self.tf = nn.Linear(40*8, nhid)\n\n self.gru1 = nn.GRU(nhid, nhid)\n self.gru2 = nn.GRU(nhid, nhid)\n\n self.output = nn.Sequential(\n nn.Linear(nhid, nclass)\n )\n\n def forward(self, spectra):\n '''\n Args:\n - feat: <tensor> (N, nFrm, nFreq)\n '''\n # (N, 1, nFrm, nFreq)\n spectra = spectra.unsqueeze(1)\n spectra = pad_time(spectra, (2, 6))\n spectra = pad_freq(spectra, (2, 2))\n\n spec_hid1 = self.conv1(spectra)\n spec_hid1 = self.bn1(spec_hid1)\n spec_hid1 = self.relu(spec_hid1)\n\n spec_hid2 = self.conv2_dep(spec_hid1)\n spec_hid2 = self.conv2_pt(spec_hid2)\n spec_hid2 = self.bn2(spec_hid2)\n spec_hid2 = self.relu(spec_hid2)\n\n spec_hid3 = self.conv3_dep(spec_hid2)\n spec_hid3 = self.conv3_pt(spec_hid3)\n spec_hid3 = self.bn3(spec_hid3)\n spec_hid3 = self.relu(spec_hid3)\n\n spec_hid4 = self.conv4_dep(spec_hid3)\n spec_hid4 = self.conv4_pt(spec_hid4)\n spec_hid4 = self.bn4(spec_hid4)\n spec_hid4 = self.relu(spec_hid4)\n\n # (N, 8, nFrm, nFreq)\n spec_hid5 = self.pre_gru_pt(spec_hid4)\n N, nCh, nFrm, nFreq = spec_hid5.shape \n # (nFrm, N, nFreq)\n feat = spec_hid5.permute(2, 0, 1, 3)\n feat = feat.reshape((nFrm, N, nCh*nFreq))\n hid1 = self.tf(feat)\n\n hid2, hn2 = self.gru1(hid1)\n hid3, hn3 = self.gru2(hid2)\n\n hid4 = 0.5 * (hid2 + hid3)\n pred = self.output(hid4)\n pred = pred.permute(1, 0, 2)\n\n return pred\n\n\nif __name__ == '__main__':\n import pdb\n\n nfrm = 100\n nfreq = 40\n batch = 8\n\n model = LeVoice(nfreq)\n\n x = torch.rand(batch, nfrm, nfreq)\n pred = model(x)\n\n pdb.set_trace()\n" ]
[ [ "torch.nn.Conv2d", "torch.nn.GRU", "torch.nn.Linear", "torch.rand", "torch.nn.BatchNorm2d", "torch.nn.ReLU", "torch.nn.functional.pad" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ajey091/neml
[ "23dd2cdb83057fdd17a37fa19f4592c54f821dbf", "23dd2cdb83057fdd17a37fa19f4592c54f821dbf", "23dd2cdb83057fdd17a37fa19f4592c54f821dbf" ]
[ "test/test_tensors.py", "doc/large-def/update_formula.py", "test/test_uniaxial.py" ]
[ "#!/usr/bin/env python\n\nfrom neml.math import tensors\n\nimport common\n\nimport unittest\nimport numpy as np\nimport numpy.linalg as la\n\nclass TestVector(unittest.TestCase):\n def setUp(self):\n self.a = np.array([2.2,-1.2,2.5])\n self.b = np.array([0.0,5.8,1.1])\n\n self.va = tensors.Vector(self.a)\n self.vb = tensors.Vector(self.b)\n\n self.s = 2.1\n \n def test_assign(self):\n self.vb = self.va\n self.assertTrue(np.allclose(self.vb.data, self.a))\n\n def test_norm(self):\n self.assertAlmostEqual(self.va.norm(), la.norm(self.a))\n\n def test_dot(self):\n self.assertAlmostEqual(np.dot(self.a,self.b), self.va.dot(self.vb))\n\n def test_smultiply(self):\n self.assertTrue(np.allclose(\n (self.s * self.va).data,\n self.s * self.a))\n self.assertTrue(np.allclose(\n (self.va * self.s).data,\n self.s * self.a))\n\n def test_sdivide(self):\n self.assertTrue(np.allclose(\n (self.va / self.s).data,\n self.a / self.s))\n\n def test_add(self):\n self.assertTrue(np.allclose(\n (self.va + self.vb).data,\n self.a + self.b))\n self.assertTrue(np.allclose(\n (self.vb + self.va).data,\n self.a + self.b))\n\n def test_subtract(self):\n self.assertTrue(np.allclose(\n (self.va - self.vb).data,\n self.a - self.b))\n self.assertTrue(np.allclose(\n (self.vb - self.va).data,\n self.b - self.a))\n\n def test_negate(self):\n self.assertTrue(np.allclose(\n (-self.va).data,\n -self.a))\n self.assertTrue(np.allclose(\n self.va.opposite().data,\n -self.a))\n\n def test_normalize(self):\n self.va.normalize()\n self.assertTrue(np.allclose(\n self.va.data, self.a / la.norm(self.a)))\n\n def test_cross(self):\n self.assertTrue(np.allclose(\n self.va.cross(self.vb).data,\n np.cross(self.a, self.b)))\n\n def test_equality(self):\n self.assertTrue(self.va == self.va)\n self.assertFalse(self.va == self.vb)\n\n def test_inequality(self):\n self.assertFalse(self.va != self.va)\n self.assertTrue(self.va != self.vb)\n\n def test_get(self):\n for i in range(3):\n self.assertTrue(np.isclose(self.va[i], self.a[i]))\n\n def test_set(self):\n for i in range(3):\n self.va[i] = 2.0\n self.a[i] = 2.0\n self.assertTrue(np.isclose(self.va[i], self.a[i]))\n\n def test_outer(self):\n self.assertEqual(self.va.outer(self.vb), tensors.outer(self.va, self.vb))\n self.assertEqual(tensors.RankTwo(np.outer(self.a, self.b)), \n tensors.outer(self.va, self.vb))\n\nclass TestRankTwo(unittest.TestCase):\n def setUp(self):\n self.A = np.array([[4.1,2.8,-1.2],[3.1,7.1,0.2],[4,2,3]])\n self.TA = tensors.RankTwo(self.A)\n self.B = np.array([[10.2,-9.3,2.5],[0.1,3.1,2.8],[0.1,3.2,-6.1]])\n self.TB = tensors.RankTwo(self.B)\n\n self.a = np.array([2.2,-1.2,2.5])\n self.va = tensors.Vector(self.a)\n\n self.s = 2.1\n\n def test_norm(self):\n self.assertTrue(np.isclose(self.TA.norm(), np.sqrt(np.sum(self.A*self.A))))\n\n def test_equality(self):\n self.assertEqual(self.TA, self.TA)\n\n def test_inequality(self):\n self.assertNotEqual(self.TA, self.TB)\n\n def test_get(self):\n self.assertTrue(np.isclose(self.TA[0,0], self.A[0,0]))\n\n def test_set(self):\n self.A[0,0] = 1.5\n self.assertTrue(np.isclose(self.A[0,0], 1.5))\n\n def test_scalar_mult(self):\n self.assertEqual(tensors.RankTwo(self.s*self.A), self.s * self.TA)\n self.assertEqual(tensors.RankTwo(self.A / self.s), self.TA / self.s)\n\n def test_add(self):\n self.assertEqual(tensors.RankTwo(self.A + self.B), self.TA + self.TB)\n self.assertEqual(tensors.RankTwo(self.A - self.B), self.TA - self.TB)\n\n def test_matrix_vector(self):\n self.assertEqual(tensors.Vector(np.dot(self.A, self.a)), self.TA*self.va)\n self.assertEqual(tensors.Vector(np.dot(self.a, self.A)), self.va*self.TA)\n\n def test_matrix_matrix(self):\n self.assertEqual(tensors.RankTwo(np.dot(self.A, self.B)), self.TA*self.TB)\n\n def test_inverse(self):\n self.assertEqual(tensors.RankTwo(la.inv(self.A)), self.TA.inverse())\n\n def test_transpose(self):\n self.assertEqual(tensors.RankTwo(self.A.T), self.TA.transpose())\n\nclass TestSymmetric(unittest.TestCase):\n def setUp(self):\n self.A = np.array([[4.1,2.8,-1.2],[3.1,7.1,0.2],[4,2,3]])\n self.A = 0.5*(self.A + self.A.T)\n self.TA = tensors.Symmetric(self.A)\n self.B = np.array([[10.2,-9.3,2.5],[0.1,3.1,2.8],[0.1,3.2,-6.1]])\n self.B = 0.5*(self.B + self.B.T)\n self.TB = tensors.Symmetric(self.B)\n\n self.a = np.array([2.2,-1.2,2.5])\n self.va = tensors.Vector(self.a)\n\n self.s = 2.1\n\n def test_norm(self):\n self.assertTrue(np.isclose(self.TA.norm(), np.sqrt(np.sum(self.A*self.A))))\n\n def test_equality(self):\n self.assertEqual(self.TA, self.TA)\n\n def test_inequality(self):\n self.assertNotEqual(self.TA, self.TB)\n\n def test_scalar_mult(self):\n self.assertEqual(tensors.Symmetric(self.s*self.A), self.s * self.TA)\n self.assertEqual(tensors.Symmetric(self.A / self.s), self.TA / self.s)\n\n def test_add(self):\n self.assertEqual(tensors.Symmetric(self.A + self.B), self.TA + self.TB)\n self.assertEqual(tensors.Symmetric(self.A - self.B), self.TA - self.TB)\n\n def test_matrix_vector(self):\n self.assertEqual(tensors.Vector(np.dot(self.A, self.a)), self.TA*self.va)\n self.assertEqual(tensors.Vector(np.dot(self.a, self.A)), self.va*self.TA)\n\n def test_matrix_matrix(self):\n self.assertEqual(tensors.Symmetric(np.dot(self.A, self.B)), self.TA*self.TB)\n\n def test_inverse(self):\n self.assertEqual(tensors.Symmetric(la.inv(self.A)), self.TA.inverse())\n\n def test_transpose(self):\n self.assertEqual(tensors.Symmetric(self.A.T), self.TA.transpose())\n\n def test_id(self):\n self.assertEqual(tensors.Symmetric.id(), tensors.Symmetric(np.eye(3)))\n\n def test_trace(self):\n self.assertTrue(np.isclose(self.TA.trace(), np.trace(self.A)))\n\n def test_dev(self):\n self.assertTrue(self.TA.dev(), tensors.Symmetric(\n self.A - np.trace(self.A)/3.0 * np.eye(3)))\n\nclass TestSkew(unittest.TestCase):\n def setUp(self):\n self.A = np.array([[4.1,2.8,-1.2],[3.1,7.1,0.2],[4,2,3]])\n self.A = 0.5*(self.A - self.A.T)\n self.TA = tensors.Skew(self.A)\n self.B = np.array([[10.2,-9.3,2.5],[0.1,3.1,2.8],[0.1,3.2,-6.1]])\n self.B = 0.5*(self.B - self.B.T)\n self.TB = tensors.Skew(self.B)\n\n self.a = np.array([2.2,-1.2,2.5])\n self.va = tensors.Vector(self.a)\n\n self.s = 2.1\n\n def test_equality(self):\n self.assertEqual(self.TA, self.TA)\n\n def test_inequality(self):\n self.assertNotEqual(self.TA, self.TB)\n\n def test_scalar_mult(self):\n self.assertEqual(tensors.Skew(self.s*self.A), self.s * self.TA)\n self.assertEqual(tensors.Skew(self.A / self.s), self.TA / self.s)\n\n def test_add(self):\n self.assertEqual(tensors.Skew(self.A + self.B), self.TA + self.TB)\n self.assertEqual(tensors.Skew(self.A - self.B), self.TA - self.TB)\n\n def test_matrix_vector(self):\n self.assertEqual(tensors.Vector(np.dot(self.A, self.a)), self.TA*self.va)\n self.assertEqual(tensors.Vector(np.dot(self.a, self.A)), self.va*self.TA)\n\n def test_matrix_matrix(self):\n self.assertEqual(tensors.Skew(np.dot(self.A, self.B)), self.TA*self.TB)\n\n def test_transpose(self):\n self.assertEqual(tensors.Skew(self.A.T), self.TA.transpose())\n\n# Test various multiplicative combinations of tensors\nclass TestComboTensorMultiply(unittest.TestCase):\n def setUp(self):\n self.S = np.array([[4.1,2.8,-1.2],[3.1,7.1,0.2],[4,2,3]])\n self.S = 0.5*(self.S + self.S.T)\n self.TS = tensors.Symmetric(self.S)\n self.G = np.array([[10.2,-9.3,2.5],[0.1,3.1,2.8],[0.1,3.2,-6.1]])\n self.TG = tensors.RankTwo(self.G)\n self.W = np.array([[-5.0,7.1,1.0],[-0.2,0.25,1.2],[-0.4,0.4,-2]])\n self.W = 0.5*(self.W - self.W.T)\n self.TW = tensors.Skew(self.W)\n\n def test_sym_general(self):\n self.assertEqual(tensors.RankTwo(np.dot(self.S, self.G)), self.TS * self.TG)\n\n def test_general_sym(self):\n self.assertEqual(tensors.RankTwo(np.dot(self.G, self.S)), self.TG * self.TS)\n\n def test_skew_general(self):\n self.assertEqual(tensors.RankTwo(np.dot(self.W, self.G)), self.TW * self.TG)\n\n def test_general_skew(self):\n self.assertEqual(tensors.RankTwo(np.dot(self.G, self.W)), self.TG * self.TW)\n\n def test_skew_sym(self):\n self.assertEqual(tensors.RankTwo(np.dot(self.W, self.S)), self.TW * self.TS)\n \n def test_sym_skew(self):\n self.assertEqual(tensors.RankTwo(np.dot(self.S, self.W)), self.TS * self.TW)\n\n def test_contract_general_sym(self):\n self.assertTrue(np.isclose(\n np.einsum('ij,ij', self.G, self.S),\n self.TG.contract(self.TS)))\n\n def test_contract_sym_general(self):\n self.assertTrue(np.isclose(\n np.einsum('ij,ij', self.G, self.S),\n self.TS.contract(self.TG)))\n\n def test_contract_general_skew(self):\n self.assertTrue(np.isclose(\n np.einsum('ij,ij', self.G, self.W),\n self.TG.contract(self.TW)))\n\n def test_contract_skew_general(self):\n self.assertTrue(np.isclose(\n np.einsum('ij,ij', self.G, self.W),\n self.TW.contract(self.TG)))\n\n def test_contract_skew_sym(self):\n self.assertTrue(np.isclose(\n np.einsum('ij,ij', self.W, self.S),\n self.TW.contract(self.TS)))\n\n def test_contract_sym_skew(self):\n self.assertTrue(np.isclose(\n np.einsum('ij,ij', self.W, self.S),\n self.TS.contract(self.TW)))\n\n def test_contract_general_general(self):\n self.assertTrue(np.isclose(\n np.einsum('ij,ij', self.G, self.G),\n self.TG.contract(self.TG)))\n\n def test_contract_sym_sym(self):\n self.assertTrue(np.isclose(\n np.einsum('ij,ij', self.S, self.S),\n self.TS.contract(self.TS)))\n\n def test_contract_skew_skew(self):\n self.assertTrue(np.isclose(\n np.einsum('ij,ij', self.W, self.W),\n self.TW.contract(self.TW)))\n \nclass TestComboTensorAdd(unittest.TestCase):\n def setUp(self):\n self.S = np.array([[4.1,2.8,-1.2],[3.1,7.1,0.2],[4,2,3]])\n self.S = 0.5*(self.S + self.S.T)\n self.TS = tensors.Symmetric(self.S)\n self.G = np.array([[10.2,-9.3,2.5],[0.1,3.1,2.8],[0.1,3.2,-6.1]])\n self.TG = tensors.RankTwo(self.G)\n self.W = np.array([[-5.0,7.1,1.0],[-0.2,0.25,1.2],[-0.4,0.4,-2]])\n self.W = 0.5*(self.W - self.W.T)\n self.TW = tensors.Skew(self.W)\n\n def test_add_sym_general(self):\n self.assertEqual(tensors.RankTwo(self.S + self.G), self.TS + self.TG)\n\n def test_add_general_sym(self):\n self.assertEqual(tensors.RankTwo(self.G + self.S), self.TG + self.TS)\n\n def test_add_skew_general(self):\n self.assertEqual(tensors.RankTwo(self.W + self.G), self.TW + self.TG)\n\n def test_add_general_skew(self):\n self.assertEqual(tensors.RankTwo(self.G + self.W), self.TG + self.TW)\n\n def test_sub_sym_general(self):\n self.assertEqual(tensors.RankTwo(self.S - self.G), self.TS - self.TG)\n\n def test_sub_general_sym(self):\n self.assertEqual(tensors.RankTwo(self.G - self.S), self.TG - self.TS)\n\n def test_sub_skew_general(self):\n self.assertEqual(tensors.RankTwo(self.W - self.G), self.TW - self.TG)\n\n def test_sub_general_skew(self):\n self.assertEqual(tensors.RankTwo(self.G - self.W), self.TG - self.TW)\n\nclass TestRankFour(unittest.TestCase):\n def setUp(self):\n self.R1 = np.array([[[[ 7.09627147, 9.22330744, -1.36602973],\n [-7.86118175, -1.6342633 , -5.75516189],\n [ 2.61734248, 6.40678382, 3.37981603]],\n [[ 5.65100254, -7.88797059, 7.31396665],\n [-6.35471595, 5.67698069, -8.18795178],\n [ 9.10447016, 8.91183436, -6.65254333]],\n [[ 3.20429862, 2.99308849, 4.0035241 ],\n [-4.02440197, -4.39975872, -4.33542791],\n [ 9.36746226, -2.91156335, 4.51572032]]],\n [[[-9.23675199, 8.63546962, 6.83448027],\n [ 4.35044123, 2.24508666, 9.80054664],\n [ 0.30835223, -4.05208575, 5.68966326]],\n [[ 6.40300092, -8.25998136, 5.63566553],\n [-5.02801101, 5.64005224, -7.39586166],\n [ 5.90893633, 6.02074669, 1.37112738]],\n [[-2.68485216, -4.67660156, 3.52618441],\n [-2.52484812, -0.08561168, 3.39072868],\n [ 9.11295675, 2.63102786, -4.82285415]]],\n [[[ 8.31973154, 4.76081593, 4.38377207],\n [ 6.22896742, -3.83995097, 5.37501029],\n [-0.16770967, 7.9453854 , -4.95548491]],\n [[-5.67884611, -8.44970885, -7.42037867],\n [-5.19908193, -7.87006493, 1.65949787],\n [-3.25934672, 6.27340198, 5.98643056]],\n [[-4.20166968, -2.38276224, 3.04551936],\n [ 3.68445989, -5.84357996, 3.61183543],\n [ 1.54886677, 3.3659842 , 6.43067337]]]])\n self.TR1 = tensors.RankFour(self.R1)\n\n self.R2 = np.array([[[[-8.03675620e+00, 2.58575052e+00, 2.44069661e+00],\n [ 4.75021663e+00, 1.24463394e+00, -8.69751301e-01],\n [-1.46310894e+00, -1.15053235e+00, -3.75342982e+00]],\n [[-7.64033956e+00, 4.19956720e+00, -4.87644982e+00],\n [ 1.06577507e+00, 8.94272637e+00, 6.57264250e-01],\n [-4.22613258e+00, -5.08830314e+00, 1.57718186e+00]],\n [[-4.02243082e+00, -4.75463781e+00, -8.88662152e+00],\n [-1.30383950e+00, -1.98063574e+00, -3.18963544e+00],\n [-7.52071674e+00, 1.08931933e+00, 2.86988431e+00]]],\n [[[ 5.28621060e+00, -6.83799668e+00, 8.98005935e+00],\n [-7.92741122e+00, 5.75699425e-01, 1.66782544e+00],\n [ 2.60041984e+00, -1.04476986e-02, -6.12424787e+00]],\n [[-3.73727368e+00, 6.59764771e+00, -1.18045587e+00],\n [ 4.08567441e+00, 2.66148943e+00, -6.82495588e-01],\n [-1.64417262e+00, 5.33119298e+00, 8.11045988e-03]],\n [[-5.90193883e+00, -2.63316107e+00, 5.61381825e+00],\n [-6.08591194e+00, 8.77285539e+00, -7.15230533e+00],\n [ 3.15093096e+00, 1.41350149e+00, 1.11702016e+00]]],\n [[[-9.61472764e-01, -1.91492497e+00, 9.48275324e+00],\n [ 6.68841134e+00, 3.23412041e+00, -3.41944541e+00],\n [-9.80203467e+00, 6.58425335e+00, -2.16548636e+00]],\n [[ 6.63950740e+00, 3.91551441e+00, -8.98229111e+00],\n [ 9.84606756e+00, -8.16145090e+00, 8.41929062e-01],\n [-1.93839620e+00, 7.44485127e+00, -2.70832414e+00]],\n [[ 9.79265531e+00, -1.18212395e+00, -5.39433704e+00],\n [ 4.87152614e+00, 9.47287450e+00, 5.53838514e+00],\n [ 9.30443367e+00, 1.27090319e+00, 1.60409739e+00]]]])\n self.TR2 = tensors.RankFour(self.R2)\n\n self.SS = np.array([\n [ 5.99159801, -2.24342348, 0.26667281, -0.95466199, 3.98931478, -0.10846981],\n [ 1.86468226, -4.32391908, -7.82738638, -7.45008989, 5.89874777, 0.45820648],\n [-5.92565398, 2.4862829 , -6.02112389, 6.75455965, 4.65183463, 9.96900579],\n [ 0.60378883, -3.72189328, -7.63388446, -5.76559403, -0.3119789 , -1.1527258 ],\n [ 4.56813135, -6.06783828, -6.18341368, 8.06169686, -9.56928844, 9.08114655],\n [-8.25516614, 6.30663846, 7.2084381 , -7.38280703, -5.96279902, 8.9935982 ]])\n self.SS_full = common.ms2ts(self.SS)\n self.TSS = tensors.SymSymR4(self.SS)\n\n self.SW = np.array([\n [ 5.43434005, -6.55983214, 0.29737664],\n [-4.77472172, -8.51287287, -3.19380185],\n [ 4.43407952, -6.02555614, 5.87786914],\n [ 1.89488869, -5.65383917, 8.83717547],\n [-7.18030867, 1.56100537, -9.83238641],\n [-4.52369317, -3.07284914, -7.54966999]])\n self.SW_full = common.ws2ts(self.SW)\n self.TSW = tensors.SymSkewR4(self.SW)\n\n self.WS = np.array([\n [-8.3567359 , -5.39728818, -8.00844442, -8.33365112, -0.97903364, -8.23943149],\n [-6.97125417, 4.34802055, 7.06281056, -1.57511617, 7.83359933, -9.37625432],\n [-6.0799489 , -6.0309543 , 3.68575895, 8.84296976, 6.55799427, -9.22029379]])\n self.WS_full = common.wws2ts(self.WS)\n self.TWS = tensors.SkewSymR4(self.WS)\n\n self.scalar = -2.2\n\n self.G = np.array([[ 9.50640677, 1.79084726, -2.8877036 ],\n [-1.63159958, 2.52866904, -8.71585042],\n [ 5.01859685, -8.7324075 , -0.42919134]])\n self.TG = tensors.RankTwo(self.G)\n\n self.S = np.array([[ 6.19999242, -6.95811611, -6.02901899],\n [ 8.38508084, 6.01607694, 6.79839425],\n [-4.4214246 , -2.36795313, -8.84070728]])\n self.S = 0.5*(self.S+self.S.T)\n self.TS = tensors.Symmetric(self.S)\n\n self.W = np.array([[-9.36416517, 2.95527444, 8.70983194],\n [-1.54693052, 8.7905658 , -5.10895168],\n [-8.52740468, -0.7741642 , 2.89544992]])\n self.W = 0.5 * (self.W - self.W.T)\n self.TW = tensors.Skew(self.W)\n\n def test_add(self):\n self.assertEqual(tensors.RankFour(self.R1 + self.R2), self.TR2 + self.TR1)\n self.assertEqual(tensors.RankFour(self.R1 - self.R2), self.TR1 - self.TR2)\n\n def test_equality(self):\n self.assertEqual(self.TR1, self.TR1)\n\n def test_inequality(self):\n self.assertNotEqual(self.TR1, self.TR2)\n\n def test_negate(self):\n self.assertEqual(tensors.RankFour(-self.R1), -self.TR1)\n\n def test_scalar_mult(self):\n self.assertEqual(tensors.RankFour(self.scalar * self.R1), self.scalar * self.TR1)\n self.assertEqual(tensors.RankFour(self.scalar * self.R2), self.TR2 * self.scalar)\n self.assertEqual(tensors.RankFour(self.R1 / self.scalar), self.TR1 / self.scalar)\n \n def test_double_contraction(self):\n self.assertEqual(tensors.RankFour(np.einsum('ijkl,klmn', self.R1, self.R2)), self.TR1 * self.TR2)\n\n def test_sym_sym(self):\n self.assertEqual(tensors.RankFour(np.einsum('ijkl,klmn', self.R1, self.SS_full)), self.TR1 * self.TSS)\n\n def test_sym_skew(self):\n self.assertEqual(tensors.RankFour(np.einsum('ijkl,klmn', self.R1, self.SW_full)), self.TR1 * self.TSW)\n\n def test_skew_sym(self):\n self.assertEqual(tensors.RankFour(np.einsum('ijkl,klmn', self.R1, self.WS_full)), self.TR1 * self.TWS)\n\n def test_ranktwo(self):\n self.assertEqual(tensors.RankTwo(np.einsum('ijkl,kl', self.R1, self.G)), self.TR1 * self.TG)\n\n def test_symmetric(self):\n self.assertEqual(tensors.RankTwo(np.einsum('ijkl,kl', self.R1, self.S)), self.TR1 * self.TS)\n\n def test_skew(self):\n self.assertEqual(tensors.RankTwo(np.einsum('ijkl,kl', self.R1, self.W)), self.TR1 * self.TW)\n\n def test_get(self):\n self.assertTrue(np.isclose(self.R1[1,2,0,1], self.TR1[1,2,0,1]))\n\n def test_set(self):\n self.TR1[1,1,1,1] = 4.0\n self.assertTrue(np.isclose(self.TR1[1,1,1,1],4.0))\n\nclass TestSymSymR4(unittest.TestCase):\n def setUp(self):\n self.SS1 = np.array([\n [ 5.99159801, -2.24342348, 0.26667281, -0.95466199, 3.98931478, -0.10846981],\n [ 1.86468226, -4.32391908, -7.82738638, -7.45008989, 5.89874777, 0.45820648],\n [-5.92565398, 2.4862829 , -6.02112389, 6.75455965, 4.65183463, 9.96900579],\n [ 0.60378883, -3.72189328, -7.63388446, -5.76559403, -0.3119789 , -1.1527258 ],\n [ 4.56813135, -6.06783828, -6.18341368, 8.06169686, -9.56928844, 9.08114655],\n [-8.25516614, 6.30663846, 7.2084381 , -7.38280703, -5.96279902, 8.9935982 ]])\n self.SS1_full = common.ms2ts(self.SS1)\n self.TSS1 = tensors.SymSymR4(self.SS1)\n\n self.SS2 = np.array([\n [-3.83767383, -8.63726504, -4.52095938, 9.35252323, 2.12800902, 3.26478511],\n [ 0.41705962, 3.95885105, -4.21676978, 4.12817198, 7.38839962, 5.79308578],\n [ 6.09635931, 2.31981366, -4.40237946, -5.51856189, 5.63572381, -5.55192385],\n [-0.97547288, -6.35708101, -4.35087656, -2.56567326, 4.32627031, 5.99408963],\n [ 6.30359707, 5.72926973, 2.47121354, -7.26333416, -5.08412215, -9.21872687],\n [-6.10780884, 1.01881487, -1.93491321, 6.13272186, -8.8721007, -2.97045116]])\n self.TSS2 = tensors.SymSymR4(self.SS2)\n\n self.SW = np.array([\n [ 5.43434005, -6.55983214, 0.29737664],\n [-4.77472172, -8.51287287, -3.19380185],\n [ 4.43407952, -6.02555614, 5.87786914],\n [ 1.89488869, -5.65383917, 8.83717547],\n [-7.18030867, 1.56100537, -9.83238641],\n [-4.52369317, -3.07284914, -7.54966999]])\n self.SW_full = common.ws2ts(self.SW)\n self.TSW = tensors.SymSkewR4(self.SW)\n\n self.WS = np.array([\n [-8.3567359 , -5.39728818, -8.00844442, -8.33365112, -0.97903364, -8.23943149],\n [-6.97125417, 4.34802055, 7.06281056, -1.57511617, 7.83359933, -9.37625432],\n [-6.0799489 , -6.0309543 , 3.68575895, 8.84296976, 6.55799427, -9.22029379]])\n self.WS_full = common.wws2ts(self.WS)\n self.TWS = tensors.SkewSymR4(self.WS)\n\n self.R = np.array([[[[-8.03675620e+00, 2.58575052e+00, 2.44069661e+00],\n [ 4.75021663e+00, 1.24463394e+00, -8.69751301e-01],\n [-1.46310894e+00, -1.15053235e+00, -3.75342982e+00]],\n [[-7.64033956e+00, 4.19956720e+00, -4.87644982e+00],\n [ 1.06577507e+00, 8.94272637e+00, 6.57264250e-01],\n [-4.22613258e+00, -5.08830314e+00, 1.57718186e+00]],\n [[-4.02243082e+00, -4.75463781e+00, -8.88662152e+00],\n [-1.30383950e+00, -1.98063574e+00, -3.18963544e+00],\n [-7.52071674e+00, 1.08931933e+00, 2.86988431e+00]]],\n [[[ 5.28621060e+00, -6.83799668e+00, 8.98005935e+00],\n [-7.92741122e+00, 5.75699425e-01, 1.66782544e+00],\n [ 2.60041984e+00, -1.04476986e-02, -6.12424787e+00]],\n [[-3.73727368e+00, 6.59764771e+00, -1.18045587e+00],\n [ 4.08567441e+00, 2.66148943e+00, -6.82495588e-01],\n [-1.64417262e+00, 5.33119298e+00, 8.11045988e-03]],\n [[-5.90193883e+00, -2.63316107e+00, 5.61381825e+00],\n [-6.08591194e+00, 8.77285539e+00, -7.15230533e+00],\n [ 3.15093096e+00, 1.41350149e+00, 1.11702016e+00]]],\n [[[-9.61472764e-01, -1.91492497e+00, 9.48275324e+00],\n [ 6.68841134e+00, 3.23412041e+00, -3.41944541e+00],\n [-9.80203467e+00, 6.58425335e+00, -2.16548636e+00]],\n [[ 6.63950740e+00, 3.91551441e+00, -8.98229111e+00],\n [ 9.84606756e+00, -8.16145090e+00, 8.41929062e-01],\n [-1.93839620e+00, 7.44485127e+00, -2.70832414e+00]],\n [[ 9.79265531e+00, -1.18212395e+00, -5.39433704e+00],\n [ 4.87152614e+00, 9.47287450e+00, 5.53838514e+00],\n [ 9.30443367e+00, 1.27090319e+00, 1.60409739e+00]]]])\n self.TR = tensors.RankFour(self.R)\n\n self.S = np.array([[4.1,2.8,-1.2],[3.1,7.1,0.2],[4,2,3]])\n self.S = 0.5*(self.S + self.S.T)\n self.TS = tensors.Symmetric(self.S)\n\n self.S2 = np.array([[10.2,-9.3,2.5],[0.1,3.1,2.8],[0.1,3.2,-6.1]])\n self.S2 = 0.5*(self.S2 + self.S2.T)\n self.TS2 = tensors.Symmetric(self.S2)\n\n self.scalar = 5.2\n\n self.G = np.array([[ 9.50640677, 1.79084726, -2.8877036 ],\n [-1.63159958, 2.52866904, -8.71585042],\n [ 5.01859685, -8.7324075 , -0.42919134]])\n self.TG = tensors.RankTwo(self.G)\n\n self.W = np.array([[-9.36416517, 2.95527444, 8.70983194],\n [-1.54693052, 8.7905658 , -5.10895168],\n [-8.52740468, -0.7741642 , 2.89544992]])\n self.W = 0.5 * (self.W - self.W.T)\n self.TW = tensors.Skew(self.W)\n\n def test_to_full(self):\n full_np = common.ms2ts(self.SS1)\n full_t = tensors.RankFour(full_np)\n full = self.TSS1.to_full()\n self.assertEqual(full_t, full)\n\n def test_from_full(self):\n full = self.TSS1.to_full()\n new = full.to_sym()\n self.assertEqual(self.TSS1, new)\n\n def test_add(self):\n self.assertEqual(tensors.SymSymR4(self.SS1 + self.SS2), self.TSS2 + self.TSS1)\n self.assertEqual(tensors.SymSymR4(self.SS1 - self.SS2), self.TSS1 - self.TSS2)\n\n def test_equality(self):\n self.assertEqual(self.TSS1, self.TSS1)\n\n def test_inequality(self):\n self.assertNotEqual(self.TSS1, self.TSS2)\n\n def test_negate(self):\n self.assertEqual(tensors.SymSymR4(-self.SS1), -self.TSS1)\n\n def test_scalar_mult(self):\n self.assertEqual(tensors.SymSymR4(self.scalar * self.SS1), self.scalar * self.TSS1)\n self.assertEqual(tensors.SymSymR4(self.scalar * self.SS2), self.TSS2 * self.scalar)\n self.assertEqual(tensors.SymSymR4(self.SS1 / self.scalar), self.TSS1 / self.scalar)\n\n def test_product_sym_sym(self):\n self.assertEqual(tensors.SymSymR4(np.dot(self.SS1, self.SS2)), self.TSS1 * self.TSS2)\n\n def test_product_sym_full(self):\n self.assertEqual(tensors.RankFour(np.einsum('ijkl,klmn', self.SS1_full, self.R)), self.TSS1 * self.TR)\n\n def test_product_sym_skew(self):\n self.assertEqual(tensors.RankFour(np.einsum('ijkl,klmn', self.SS1_full, self.SW_full)), self.TSS1 * self.TSW)\n\n def test_product_skew_sym(self):\n self.assertEqual(tensors.RankFour(np.einsum('ijkl,klmn', self.SS1_full, self.WS_full)), self.TSS1 * self.TWS)\n\n def test_product_symmetric(self):\n self.assertEqual(tensors.Symmetric(common.usym(np.dot(self.SS1, common.sym(self.S)))), self.TSS1 * self.TS)\n\n def test_product_general(self):\n self.assertEqual(tensors.RankTwo(np.einsum('ijkl,kl', self.SS1_full, self.G)), self.TSS1 * self.TG)\n\n def test_product_skew(self):\n self.assertEqual(tensors.RankTwo(np.einsum('ijkl,kl', self.SS1_full, self.W)), self.TSS1 * self.TW)\n\n def test_douter(self):\n self.assertEqual(tensors.SymSymR4(common.ts2ms(np.einsum('ij,kl', self.S, self.S2))), tensors.douter(self.TS, self.TS2))\n\n def test_id(self):\n id_t = tensors.SymSymR4(np.eye(6))\n self.assertEqual(id_t, tensors.SymSymR4.id())\n\n def test_id_dev(self):\n ot = np.zeros((6,6))\n ot[:3,:3] = 1.0/3.0\n id_t = tensors.SymSymR4(np.eye(6) - ot)\n self.assertEqual(id_t, tensors.SymSymR4.id_dev())\n\nclass TestSymSkewR4(unittest.TestCase):\n def setUp(self):\n self.SW1 = np.array([\n [ 5.43434005, -6.55983214, 0.29737664],\n [-4.77472172, -8.51287287, -3.19380185],\n [ 4.43407952, -6.02555614, 5.87786914],\n [ 1.89488869, -5.65383917, 8.83717547],\n [-7.18030867, 1.56100537, -9.83238641],\n [-4.52369317, -3.07284914, -7.54966999]])\n self.SW1_full = common.ws2ts(self.SW1)\n self.TSW1 = tensors.SymSkewR4(self.SW1)\n\n self.SW2 = np.array([\n [ 7.90885123, -1.89089468, -6.95528566],\n [-2.53495619, 9.47533071, -2.76302205],\n [-8.57887706, 4.21216331, -7.68619983],\n [-5.45955495, 2.0523769 , -9.71153458],\n [-5.61696943, -4.02142773, -6.41654212],\n [-8.76272792, -3.60354692, 2.7402794 ]])\n\n self.SW2_full = common.ws2ts(self.SW2)\n self.TSW2 = tensors.SymSkewR4(self.SW2)\n\n self.WS = np.array([\n [-8.3567359 , -5.39728818, -8.00844442, -8.33365112, -0.97903364, -8.23943149],\n [-6.97125417, 4.34802055, 7.06281056, -1.57511617, 7.83359933, -9.37625432],\n [-6.0799489 , -6.0309543 , 3.68575895, 8.84296976, 6.55799427, -9.22029379]])\n self.WS_full = common.wws2ts(self.WS)\n self.TWS = tensors.SkewSymR4(self.WS)\n\n self.SS = np.array([\n [ 5.99159801, -2.24342348, 0.26667281, -0.95466199, 3.98931478, -0.10846981],\n [ 1.86468226, -4.32391908, -7.82738638, -7.45008989, 5.89874777, 0.45820648],\n [-5.92565398, 2.4862829 , -6.02112389, 6.75455965, 4.65183463, 9.96900579],\n [ 0.60378883, -3.72189328, -7.63388446, -5.76559403, -0.3119789 , -1.1527258 ],\n [ 4.56813135, -6.06783828, -6.18341368, 8.06169686, -9.56928844, 9.08114655],\n [-8.25516614, 6.30663846, 7.2084381 , -7.38280703, -5.96279902, 8.9935982 ]])\n self.SS_full = common.ms2ts(self.SS)\n self.TSS = tensors.SymSymR4(self.SS)\n\n self.R = np.array([[[[-8.03675620e+00, 2.58575052e+00, 2.44069661e+00],\n [ 4.75021663e+00, 1.24463394e+00, -8.69751301e-01],\n [-1.46310894e+00, -1.15053235e+00, -3.75342982e+00]],\n [[-7.64033956e+00, 4.19956720e+00, -4.87644982e+00],\n [ 1.06577507e+00, 8.94272637e+00, 6.57264250e-01],\n [-4.22613258e+00, -5.08830314e+00, 1.57718186e+00]],\n [[-4.02243082e+00, -4.75463781e+00, -8.88662152e+00],\n [-1.30383950e+00, -1.98063574e+00, -3.18963544e+00],\n [-7.52071674e+00, 1.08931933e+00, 2.86988431e+00]]],\n [[[ 5.28621060e+00, -6.83799668e+00, 8.98005935e+00],\n [-7.92741122e+00, 5.75699425e-01, 1.66782544e+00],\n [ 2.60041984e+00, -1.04476986e-02, -6.12424787e+00]],\n [[-3.73727368e+00, 6.59764771e+00, -1.18045587e+00],\n [ 4.08567441e+00, 2.66148943e+00, -6.82495588e-01],\n [-1.64417262e+00, 5.33119298e+00, 8.11045988e-03]],\n [[-5.90193883e+00, -2.63316107e+00, 5.61381825e+00],\n [-6.08591194e+00, 8.77285539e+00, -7.15230533e+00],\n [ 3.15093096e+00, 1.41350149e+00, 1.11702016e+00]]],\n [[[-9.61472764e-01, -1.91492497e+00, 9.48275324e+00],\n [ 6.68841134e+00, 3.23412041e+00, -3.41944541e+00],\n [-9.80203467e+00, 6.58425335e+00, -2.16548636e+00]],\n [[ 6.63950740e+00, 3.91551441e+00, -8.98229111e+00],\n [ 9.84606756e+00, -8.16145090e+00, 8.41929062e-01],\n [-1.93839620e+00, 7.44485127e+00, -2.70832414e+00]],\n [[ 9.79265531e+00, -1.18212395e+00, -5.39433704e+00],\n [ 4.87152614e+00, 9.47287450e+00, 5.53838514e+00],\n [ 9.30443367e+00, 1.27090319e+00, 1.60409739e+00]]]])\n self.TR = tensors.RankFour(self.R)\n\n self.S = np.array([[4.1,2.8,-1.2],[3.1,7.1,0.2],[4,2,3]])\n self.S = 0.5*(self.S + self.S.T)\n self.TS = tensors.Symmetric(self.S)\n\n self.scalar = 5.2\n\n self.G = np.array([[ 9.50640677, 1.79084726, -2.8877036 ],\n [-1.63159958, 2.52866904, -8.71585042],\n [ 5.01859685, -8.7324075 , -0.42919134]])\n self.TG = tensors.RankTwo(self.G)\n\n self.W = np.array([[-9.36416517, 2.95527444, 8.70983194],\n [-1.54693052, 8.7905658 , -5.10895168],\n [-8.52740468, -0.7741642 , 2.89544992]])\n self.W = 0.5 * (self.W - self.W.T)\n self.TW = tensors.Skew(self.W)\n\n def test_to_full(self):\n full_np = common.ws2ts(self.SW1)\n full_t = tensors.RankFour(full_np)\n full = self.TSW1.to_full()\n self.assertEqual(full_t, full)\n\n def test_from_full(self):\n full = self.TSW1.to_full()\n new = full.to_symskew()\n self.assertEqual(self.TSW1, new)\n\n def test_add(self):\n self.assertEqual(tensors.SymSkewR4(self.SW1 + self.SW2), self.TSW2 + self.TSW1)\n self.assertEqual(tensors.SymSkewR4(self.SW1 - self.SW2), self.TSW1 - self.TSW2)\n\n def test_equality(self):\n self.assertEqual(self.TSW1, self.TSW1)\n\n def test_inequality(self):\n self.assertNotEqual(self.TSW1, self.TSW2)\n\n def test_negate(self):\n self.assertEqual(tensors.SymSkewR4(-self.SW1), -self.TSW1)\n\n def test_scalar_mult(self):\n self.assertEqual(tensors.SymSkewR4(self.scalar * self.SW1), self.scalar * self.TSW1)\n self.assertEqual(tensors.SymSkewR4(self.scalar * self.SW2), self.TSW2 * self.scalar)\n self.assertEqual(tensors.SymSkewR4(self.SW1 / self.scalar), self.TSW1 / self.scalar)\n\n def test_product_sym_sym(self):\n self.assertEqual(tensors.RankFour(np.einsum('ijkl,klmn', self.SW1_full, self.SS_full)), self.TSW1 * self.TSS)\n\n def test_product_sym_full(self):\n self.assertEqual(tensors.RankFour(np.einsum('ijkl,klmn', self.SW1_full, self.R)), self.TSW1 * self.TR)\n\n def test_product_sym_skew(self):\n self.assertEqual(tensors.RankFour(np.einsum('ijkl,klmn', self.SW1_full, self.SW2_full)), self.TSW1 * self.TSW2)\n\n def test_product_skew_sym(self):\n self.assertEqual(tensors.RankFour(np.einsum('ijkl,klmn', self.SW1_full, self.WS_full)), self.TSW1 * self.TWS)\n\n def test_product_symmetric(self):\n self.assertEqual(tensors.RankTwo(np.einsum('ijkl,kl', self.SW1_full, self.S)), self.TSW1 * self.TS)\n\n def test_product_general(self):\n self.assertEqual(tensors.RankTwo(np.einsum('ijkl,kl', self.SW1_full, self.G)), self.TSW1 * self.TG)\n\n def test_product_skew(self):\n self.assertEqual(tensors.RankTwo(np.einsum('ijkl,kl', self.SW1_full, self.W)), self.TSW1 * self.TW)\n\nclass TestSkewSymR4(unittest.TestCase):\n def setUp(self):\n self.WS1 = np.array([\n [-8.3567359 , -5.39728818, -8.00844442, -8.33365112, -0.97903364, -8.23943149],\n [-6.97125417, 4.34802055, 7.06281056, -1.57511617, 7.83359933, -9.37625432],\n [-6.0799489 , -6.0309543 , 3.68575895, 8.84296976, 6.55799427, -9.22029379]])\n self.WS1_full = common.wws2ts(self.WS1)\n self.TWS1 = tensors.SkewSymR4(self.WS1)\n\n self.WS2 = np.array([\n [-8.80662663, 0.46179936, -5.49454144, 7.91618428, 5.34053953, -6.68997405],\n [ 4.15874971, -4.59781751, 7.43746813, 8.99981425, -0.97692573, 2.5075246 ],\n [ 9.53201007, -8.03524224, 0.94329443, -6.44415877, -9.92911741, 3.51742689]])\n self.WS2_full = common.wws2ts(self.WS2)\n self.TWS2 = tensors.SkewSymR4(self.WS2)\n\n self.SW = np.array([\n [ 5.43434005, -6.55983214, 0.29737664],\n [-4.77472172, -8.51287287, -3.19380185],\n [ 4.43407952, -6.02555614, 5.87786914],\n [ 1.89488869, -5.65383917, 8.83717547],\n [-7.18030867, 1.56100537, -9.83238641],\n [-4.52369317, -3.07284914, -7.54966999]])\n self.SW_full = common.ws2ts(self.SW)\n self.TSW = tensors.SymSkewR4(self.SW)\n\n self.SS = np.array([\n [ 5.99159801, -2.24342348, 0.26667281, -0.95466199, 3.98931478, -0.10846981],\n [ 1.86468226, -4.32391908, -7.82738638, -7.45008989, 5.89874777, 0.45820648],\n [-5.92565398, 2.4862829 , -6.02112389, 6.75455965, 4.65183463, 9.96900579],\n [ 0.60378883, -3.72189328, -7.63388446, -5.76559403, -0.3119789 , -1.1527258 ],\n [ 4.56813135, -6.06783828, -6.18341368, 8.06169686, -9.56928844, 9.08114655],\n [-8.25516614, 6.30663846, 7.2084381 , -7.38280703, -5.96279902, 8.9935982 ]])\n self.SS_full = common.ms2ts(self.SS)\n self.TSS = tensors.SymSymR4(self.SS)\n\n self.R = np.array([[[[-8.03675620e+00, 2.58575052e+00, 2.44069661e+00],\n [ 4.75021663e+00, 1.24463394e+00, -8.69751301e-01],\n [-1.46310894e+00, -1.15053235e+00, -3.75342982e+00]],\n [[-7.64033956e+00, 4.19956720e+00, -4.87644982e+00],\n [ 1.06577507e+00, 8.94272637e+00, 6.57264250e-01],\n [-4.22613258e+00, -5.08830314e+00, 1.57718186e+00]],\n [[-4.02243082e+00, -4.75463781e+00, -8.88662152e+00],\n [-1.30383950e+00, -1.98063574e+00, -3.18963544e+00],\n [-7.52071674e+00, 1.08931933e+00, 2.86988431e+00]]],\n [[[ 5.28621060e+00, -6.83799668e+00, 8.98005935e+00],\n [-7.92741122e+00, 5.75699425e-01, 1.66782544e+00],\n [ 2.60041984e+00, -1.04476986e-02, -6.12424787e+00]],\n [[-3.73727368e+00, 6.59764771e+00, -1.18045587e+00],\n [ 4.08567441e+00, 2.66148943e+00, -6.82495588e-01],\n [-1.64417262e+00, 5.33119298e+00, 8.11045988e-03]],\n [[-5.90193883e+00, -2.63316107e+00, 5.61381825e+00],\n [-6.08591194e+00, 8.77285539e+00, -7.15230533e+00],\n [ 3.15093096e+00, 1.41350149e+00, 1.11702016e+00]]],\n [[[-9.61472764e-01, -1.91492497e+00, 9.48275324e+00],\n [ 6.68841134e+00, 3.23412041e+00, -3.41944541e+00],\n [-9.80203467e+00, 6.58425335e+00, -2.16548636e+00]],\n [[ 6.63950740e+00, 3.91551441e+00, -8.98229111e+00],\n [ 9.84606756e+00, -8.16145090e+00, 8.41929062e-01],\n [-1.93839620e+00, 7.44485127e+00, -2.70832414e+00]],\n [[ 9.79265531e+00, -1.18212395e+00, -5.39433704e+00],\n [ 4.87152614e+00, 9.47287450e+00, 5.53838514e+00],\n [ 9.30443367e+00, 1.27090319e+00, 1.60409739e+00]]]])\n self.TR = tensors.RankFour(self.R)\n\n self.S = np.array([[4.1,2.8,-1.2],[3.1,7.1,0.2],[4,2,3]])\n self.S = 0.5*(self.S + self.S.T)\n self.TS = tensors.Symmetric(self.S)\n\n self.scalar = 5.2\n\n self.G = np.array([[ 9.50640677, 1.79084726, -2.8877036 ],\n [-1.63159958, 2.52866904, -8.71585042],\n [ 5.01859685, -8.7324075 , -0.42919134]])\n self.TG = tensors.RankTwo(self.G)\n\n self.W = np.array([[-9.36416517, 2.95527444, 8.70983194],\n [-1.54693052, 8.7905658 , -5.10895168],\n [-8.52740468, -0.7741642 , 2.89544992]])\n self.W = 0.5 * (self.W - self.W.T)\n self.TW = tensors.Skew(self.W)\n\n def test_to_full(self):\n full_np = common.wws2ts(self.WS1)\n full_t = tensors.RankFour(full_np)\n full = self.TWS1.to_full()\n self.assertEqual(full_t, full)\n\n def test_from_full(self):\n full = self.TWS1.to_full()\n new = full.to_skewsym()\n self.assertEqual(self.TWS1, new)\n\n def test_add(self):\n self.assertEqual(tensors.SkewSymR4(self.WS1 + self.WS2), self.TWS2 + self.TWS1)\n self.assertEqual(tensors.SkewSymR4(self.WS1 - self.WS2), self.TWS1 - self.TWS2)\n\n def test_equality(self):\n self.assertEqual(self.TWS1, self.TWS1)\n\n def test_inequality(self):\n self.assertNotEqual(self.TWS1, self.TWS2)\n\n def test_negate(self):\n self.assertEqual(tensors.SkewSymR4(-self.WS1), -self.TWS1)\n\n def test_scalar_mult(self):\n self.assertEqual(tensors.SkewSymR4(self.scalar * self.WS1), self.scalar * self.TWS1)\n self.assertEqual(tensors.SkewSymR4(self.scalar * self.WS2), self.TWS2 * self.scalar)\n self.assertEqual(tensors.SkewSymR4(self.WS1 / self.scalar), self.TWS1 / self.scalar)\n\n def test_product_sym_sym(self):\n self.assertEqual(tensors.RankFour(np.einsum('ijkl,klmn', self.WS1_full, self.SS_full)), self.TWS1 * self.TSS)\n\n def test_product_sym_full(self):\n self.assertEqual(tensors.RankFour(np.einsum('ijkl,klmn', self.WS1_full, self.R)), self.TWS1 * self.TR)\n\n def test_product_sym_skew(self):\n self.assertEqual(tensors.RankFour(np.einsum('ijkl,klmn', self.WS1_full, self.SW_full)), self.TWS1 * self.TSW)\n\n def test_product_skew_sym(self):\n self.assertEqual(tensors.RankFour(np.einsum('ijkl,klmn', self.WS1_full, self.WS2_full)), self.TWS1 * self.TWS2)\n\n def test_product_symmetric(self):\n self.assertEqual(tensors.RankTwo(np.einsum('ijkl,kl', self.WS1_full, self.S)), self.TWS1 * self.TS)\n\n def test_product_general(self):\n self.assertEqual(tensors.RankTwo(np.einsum('ijkl,kl', self.WS1_full, self.G)), self.TWS1 * self.TG)\n\n def test_product_skew(self):\n self.assertEqual(tensors.RankTwo(np.einsum('ijkl,kl', self.WS1_full, self.W)), self.TWS1 * self.TW)\n\n def test_douter(self):\n self.assertEqual(tensors.SkewSymR4(common.ts2wws(np.einsum('ij,kl', self.W, self.S))), tensors.douter(self.TW, self.TS))\n\nclass TestCPSpeciality(unittest.TestCase):\n def setUp(self):\n self.SS = np.array([\n [ 5.99159801, -2.24342348, 0.26667281, -0.95466199, 3.98931478, -0.10846981],\n [ 1.86468226, -4.32391908, -7.82738638, -7.45008989, 5.89874777, 0.45820648],\n [-5.92565398, 2.4862829 , -6.02112389, 6.75455965, 4.65183463, 9.96900579],\n [ 0.60378883, -3.72189328, -7.63388446, -5.76559403, -0.3119789 , -1.1527258 ],\n [ 4.56813135, -6.06783828, -6.18341368, 8.06169686, -9.56928844, 9.08114655],\n [-8.25516614, 6.30663846, 7.2084381 , -7.38280703, -5.96279902, 8.9935982 ]])\n self.SS_full = common.ms2ts(self.SS)\n self.TSS = tensors.SymSymR4(self.SS)\n\n self.W = np.array([[-9.36416517, 2.95527444, 8.70983194],\n [-1.54693052, 8.7905658 , -5.10895168],\n [-8.52740468, -0.7741642 , 2.89544992]])\n self.W = 0.5 * (self.W - self.W.T)\n self.TW = tensors.Skew(self.W)\n\n self.S = np.array([[4.1,2.8,-1.2],[3.1,7.1,0.2],[4,2,3]])\n self.S = 0.5*(self.S + self.S.T)\n self.TS = tensors.Symmetric(self.S)\n\n self.WS = np.array([\n [-8.3567359 , -5.39728818, -8.00844442, -8.33365112, -0.97903364, -8.23943149],\n [-6.97125417, 4.34802055, 7.06281056, -1.57511617, 7.83359933, -9.37625432],\n [-6.0799489 , -6.0309543 , 3.68575895, 8.84296976, 6.55799427, -9.22029379]])\n self.WS_full = common.wws2ts(self.WS)\n self.TWS = tensors.SkewSymR4(self.WS)\n\n def test_symsymskew_skewsymsym(self):\n A1 = tensors.SymSymR4Skew_SkewSymR4SymR4(self.TSS, self.TW)\n\n A2_ten = np.einsum('kmst,ml', self.SS_full, self.W) - np.einsum('km,mlst',\n self.W, self.SS_full)\n A2 = tensors.SymSymR4(common.ts2ms(A2_ten))\n\n self.assertEqual(A1, A2)\n\n def test_symskewsym_skewsymsym(self):\n A1 = tensors.SymSkewR4Sym_SkewSymR4SymR4(self.TWS, self.TS)\n\n A2_ten = np.einsum('km,mlst', self.S, self.WS_full) - np.einsum('kmst,ml',\n self.WS_full, self.S)\n A2 = tensors.SymSymR4(common.ts2ms(A2_ten))\n\n self.assertEqual(A1, A2)\n\n def test_special(self):\n A1 = tensors.SpecialSymSymR4Sym(self.TSS, self.TS)\n A2_ten = np.einsum('ijkz,ky', self.SS_full, self.S) - np.einsum(\n 'ijyl,zl', self.SS_full, self.S)\n A2 = tensors.SymSkewR4(common.ts2sww(A2_ten))\n\n self.assertEqual(A1, A2)\n", "#!/usr/bin/env python\n\nfrom __future__ import division\n\nimport numpy as np\nimport copy\nimport itertools\n\nfrom sympy import *\n\nmandel = ((0,0),(1,1),(2,2),(1,2),(0,2),(0,1))\nmandel_mults = (1,1,1,sqrt(2),sqrt(2),sqrt(2))\n\nskew_inds = ((1,2),(0,2),(0,1))\nskew_mults = (-1,1,-1)\n\ndef object_einsum(string, *arrays):\n \"\"\"Simplified object einsum, not as much error checking\n \n does not support \"...\" or list input and will see \"...\", etc. as three times\n an axes identifier, tries normal einsum first!\n \n NOTE: This is untested, and not fast, but object type is\n never really fast anyway...\n \"\"\"\n try:\n return np.einsum(string, *arrays)\n except TypeError:\n pass\n \n s = string.split('->')\n in_op = s[0].split(',')\n out_op = None if len(s) == 1 else s[1].replace(' ', '')\n\n in_op = [axes.replace(' ', '') for axes in in_op]\n all_axes = set()\n\n for axes in in_op:\n all_axes.update(axes)\n\n if out_op is None:\n out_op = sorted(all_axes)\n else:\n all_axes.update(out_op)\n \n perm_dict = {_[1]: _[0] for _ in enumerate(all_axes)}\n \n dims = len(perm_dict)\n op_axes = []\n for axes in (in_op + list((out_op,))):\n op = [-1] * dims\n for i, ax in enumerate(axes):\n op[perm_dict[ax]] = i\n op_axes.append(op)\n \n op_flags = [('readonly',)] * len(in_op) + [('readwrite', 'allocate')]\n dtypes = [np.object_] * (len(in_op) + 1) # cast all to object\n\n nditer = np.nditer(arrays + (None,), op_axes=op_axes, flags=['buffered', 'delay_bufalloc', 'reduce_ok', 'grow_inner', 'refs_ok'], op_dtypes=dtypes, op_flags=op_flags)\n\n nditer.operands[-1][...] = 0\n nditer.reset()\n \n for vals in nditer:\n out = vals[-1]\n prod = copy.deepcopy(vals[0])\n for value in vals[1:-1]:\n prod *= value\n out += prod\n \n return nditer.operands[-1]\n\ndef zero_tensor(shape):\n l = np.prod(shape)\n return MutableDenseNDimArray([0]*l, shape)\n\ndef piece_together_fourth(Dp, Wp):\n \"\"\"\n Take the skew and symmetric parts of a algorithmic tangent and piece them back together\n \"\"\"\n sym_id = (object_einsum('ik,jl', eye(3), eye(3)) + object_einsum('jk,il', eye(3), eye(3)))/2\n skew_id = (object_einsum('ik,jl', eye(3), eye(3)) - object_einsum('jk,il', eye(3), eye(3)))/2\n\n D = sym_tensor_part(Dp)\n W = skew_tensor_part(Wp)\n res = zero_tensor((3,3,3,3))\n\n for i in range(3):\n for j in range(3):\n for k in range(3):\n for l in range(3):\n for m in range(3):\n for n in range(3):\n res[i,j,m,n] += D[i,j,k,l] * sym_id[k,l,m,n] + W[i,j,k,l] * skew_id[k,l,m,n]\n\n return res\n\ndef sym_tensor_part(C):\n \"\"\"\n Take a Mandel stiffness in my notation and convert it back to a full tensor\n \"\"\"\n Ct = zero_tensor((3,3,3,3))\n for a in range(6):\n for b in range(6):\n ind_a = itertools.permutations(mandel[a], r=2)\n ind_b = itertools.permutations(mandel[b], r=2)\n ma = mandel_mults[a]\n mb = mandel_mults[b]\n indexes = tuple(ai+bi for ai, bi in itertools.product(ind_a, ind_b))\n for ind in indexes:\n Ct[ind] = C[a,b] / ma*mb\n\n for i in range(3):\n for j in range(3):\n for k in range(3):\n for l in range(3):\n if l < k:\n Ct[i,j,k,l] = 0\n\n return Ct\n\ndef skew_tensor_part(C):\n \"\"\"\n Take a skew stiffness in my notation and convert it back to a full tensor\n \"\"\"\n Ct = zero_tensor((3,3,3,3))\n for a in range(6):\n for b in range(3):\n inds_a = mandel[a]\n inds_b = skew_inds[b]\n mult_a = mandel_mults[a]\n mult_b = skew_mults[b]\n for ord_a in ((0,1),(1,0)):\n for ord_b, f in zip(((0,1),(1,0)), (1,-1)):\n ind = tuple([inds_a[aa] for aa in ord_a] + [inds_b[bb] for bb in ord_b])\n Ct[ind] = C[a,b] * mult_a*mult_b * f\n\n for i in range(3):\n for j in range(3):\n for k in range(3):\n for l in range(3):\n if i != j:\n Ct[i,j,k,l] /= 2\n if l < k: \n Ct[i,j,k,l] = 0\n\n return Ct\n\ndef unroll_fourth(T):\n M = zeros(9,9)\n\n for i in range(3):\n for j in range(3):\n a = i*3+j\n for k in range(3):\n for l in range(3):\n b = k*3+l\n M[a,b] = T[i,j,k,l]\n\n return M\n\ndef reroll_fourth(M):\n \"\"\"\n Undo unroll_fourth\n \"\"\"\n T = zero_tensor((3,3,3,3))\n for a in range(9):\n i = a // 3\n j = a % 3\n for b in range(9):\n k = b // 3\n l = b % 3\n T[i,j,k,l] = M[a,b]\n\n return T\n\ndef unroll_second(T):\n return Matrix([T[i,j] for i in range(3) for j in range(3)])\n\ndef ms2ts(C):\n \"\"\"\n Convert a Mandel notation stiffness matrix to a full stiffness tensor.\n \"\"\"\n Ct = zero_tensor((3,3,3,3))\n for a in range(6):\n for b in range(6):\n ind_a = itertools.permutations(mandel[a], r=2)\n ind_b = itertools.permutations(mandel[b], r=2)\n ma = mandel_mults[a]\n mb = mandel_mults[b]\n indexes = tuple(ai+bi for ai, bi in itertools.product(ind_a, ind_b))\n for i,j,k,l in indexes:\n Ct[i,j,k,l] = C[a,b] / (ma*mb)\n\n return Ct\n\ndef ts2ms(C):\n \"\"\"\n Convert a stiffness tensor into a Mandel notation stiffness matrix\n \"\"\"\n Cv = zeros(6,6)\n for i in range(6):\n for j in range(6):\n ma = mandel_mults[i]\n mb = mandel_mults[j]\n Cv[i,j] = C[mandel[i]+mandel[j]] * ma * mb\n\n return Cv\n\ndef ws2ts(C):\n \"\"\"\n Convert a skew notation stiffness matrix to a full stiffness tensor.\n \"\"\"\n Ct = zero_tensor((3,3,3,3))\n for a in range(6):\n for b in range(3):\n inds_a = mandel[a]\n inds_b = skew_inds[b]\n mult_a = mandel_mults[a]\n mult_b = skew_mults[b]\n for ord_a in ((0,1),(1,0)):\n for ord_b, f in zip(((0,1),(1,0)), (1,-1)):\n ind = tuple([inds_a[aa] for aa in ord_a] + [inds_b[bb] for bb in ord_b])\n Ct[ind] = C[a,b] / (mult_a*mult_b) * f\n\n return Ct\n\ndef ts2ws(C):\n \"\"\"\n Convert a stiffness tensor into a skew notation stiffness matrix\n \"\"\"\n Cv = zeros(6,3)\n for i in range(6):\n for j in range(3):\n ma = mandel_mults[i]\n mb = skew_mults[j]\n Cv[i,j] = C[mandel[i]+skew_inds[j]] * ma * mb\n\n return Cv\n\ndef wws2ts(C):\n \"\"\"\n Convert a skew notation stiffness matrix to a full stiffness tensor.\n \"\"\"\n Ct = zero_tensor((3,3,3,3))\n for a in range(3):\n for b in range(6):\n inds_a = skew_inds[a]\n inds_b = mandel[b]\n mult_a = skew_mults[a]\n mult_b = mandel_mults[b]\n for ord_a, f in zip(((0,1),(1,0)),(1,-1)):\n for ord_b in ((0,1),(1,0)):\n ind = tuple([inds_a[aa] for aa in ord_a] + [inds_b[bb] for bb in ord_b])\n Ct[ind] = C[a,b] / (mult_a * mult_b) * f\n\n return Ct\n\ndef ts2wws(C):\n \"\"\"\n Convert a stiffness tensor into a skew notation stiffness matrix\n \"\"\"\n Cv = zeros(3,6)\n for i in range(3):\n for j in range(6):\n ma = skew_mults[i]\n mb = mandel_mults[j]\n Cv[i,j] = C[skew_inds[i] + mandel[j]] * ma * mb\n\n return Cv\n\ndef trace(X):\n return (X[0,0] + X[1,1] + X[2,2])\n\ndef sym(A):\n return [A[0,0], A[1,1], A[2,2], sqrt(2) * A[1,2], sqrt(2) * A[0,2], sqrt(2) * A[0,1]]\n\ndef update():\n W0, W1, W2 = symbols(\"W[0] W[1] W[2]\")\n D0, D1, D2, D3, D4, D5 = symbols(\"D[0] D[1] D[2] D[3] D[4] D[5]\")\n S0, S1, S2, S3, S4, S5 = symbols(\"Sn[0] Sn[1] Sn[2] Sn[3] Sn[4] Sn[5]\")\n O0, O1, O2, O3, O4, O5 = symbols(\"So[0] So[1] So[2] So[3] So[4] So[5]\")\n\n G00, G01, G02, G10, G11, G12, G20, G21, G22 = symbols(\"G00 G01 G02 G10 G11 G12 G20 G21 G22\")\n\n W = Matrix([[0,-W2,W1],[W2,0,-W0],[-W1,W0,0]])\n D = Matrix([[D0, D5/sqrt(2), D4/sqrt(2)],[D5/sqrt(2),D1,D3/sqrt(2)],[D4/sqrt(2),D3/sqrt(2),D2]])\n L = D + W\n\n S = Matrix([[S0, S5/sqrt(2), S4/sqrt(2)],[S5/sqrt(2),S1,S3/sqrt(2)],[S4/sqrt(2),S3/sqrt(2),S2]])\n O = Matrix([[O0, O5/sqrt(2), O4/sqrt(2)],[O5/sqrt(2),O1,O3/sqrt(2)],[O4/sqrt(2),O3/sqrt(2),O2]])\n\n G = Matrix([[G00,G01,G02],[G10,G11,G12],[G20,G21,G22]])\n \n V1 = simplify(O + S*(L.T) + L*S - (trace(L) * S))\n\n V11 = simplify(sym(V1))\n \n print(\"RHS\")\n for i in range(6):\n print((\"\\tSt[%i] = \" + str(V11[i]) + \";\") % i)\n print(\"\")\n\n J = object_einsum('im,jn', eye(3), eye(3)) * (1 + trace(L)) - object_einsum('im,jn', eye(3), L) - object_einsum('im,jn', L, eye(3))\n JM = simplify(unroll_fourth(J))\n \n print(\"Matrix\")\n for i in range(9):\n for j in range(9):\n print((\"\\tM[%i] = \" + str(JM[i,j]) + \";\") % (i*9+j))\n print(\"\")\n\ndef tangent():\n sym_mat = Matrix([[symbols(\"M[%i]\" % (i*6+j)) for j in range(6)] for i in range(6)])\n sym_ten = ms2ts(sym_mat)\n sym_full = unroll_fourth(sym_ten)\n\n skew_mat = Matrix([[symbols(\"M[%i]\" % (i*3+j)) for j in range(3)] for i in range(6)])\n skew_ten = ws2ts(skew_mat)\n skew_full = unroll_fourth(skew_ten)\n\n wws_mat = Matrix([[symbols(\"M[%i]\" % (i*6+j)) for j in range(6)] for i in range(3)])\n wws_ten = wws2ts(wws_mat)\n wws_full = unroll_fourth(wws_ten)\n\n A_mat = Matrix([[symbols(\"A[%i]\" % (i*9+j)) for j in range(9)] for i in range(9)])\n A_ten = reroll_fourth(A_mat)\n A_mandel = ts2ms(A_ten)\n A_skew = ts2ws(A_ten)\n A_wws = ts2wws(A_ten)\n\n print(\"Mandel->9x9\")\n for i in range(9):\n for j in range(9):\n print((\"\\tA[%i] = \" + str(sym_full[i,j]) + \";\") % (i*9+j))\n print(\"\")\n print(\"9x9->Mandel\")\n for i in range(6):\n for j in range(6):\n print((\"\\tM[%i] = \" + str(A_mandel[i,j]) + \";\") % (i*6+j))\n print(\"\")\n \n print(\"Skew->9x9\")\n for i in range(9):\n for j in range(9):\n print((\"\\tA[%i] = \" + str(skew_full[i,j]) + \";\") % (i*9+j))\n print(\"\")\n print(\"9x9->Skew\")\n for i in range(6):\n for j in range(3):\n print((\"\\tM[%i] = \" + str(A_skew[i,j]) + \";\") % (i*3+j))\n print(\"\")\n\n print(\"WWS->9x9\")\n for i in range(9):\n for j in range(9):\n print((\"\\tA[%i] = \" + str(wws_full[i,j]) + \";\") % (i*9+j))\n print(\"\")\n print(\"9x9->WWS\")\n for i in range(3):\n for j in range(6):\n print((\"\\tM[%i] = \" + str(A_wws[i,j]) + \";\") % (i*6+j))\n print(\"\")\n\n S0, S1, S2, S3, S4, S5 = symbols(\"S[0] S[1] S[2] S[3] S[4] S[5]\")\n S = Matrix([[S0, S5/sqrt(2), S4/sqrt(2)],[S5/sqrt(2),S1,S3/sqrt(2)],[S4/sqrt(2),S3/sqrt(2),S2]])\n tensor = simplify(object_einsum('in,jm', S, eye(3)) + object_einsum('im,nj', eye(3), S) - object_einsum('ij,mn', S, eye(3)))\n matrix = simplify(unroll_fourth(tensor))\n print(\"Matrix\")\n for i in range(9):\n for j in range(9):\n print((\"\\tM[%i] = \" + str(matrix[i,j]) + \";\") % (i*9+j))\n print(\"\")\n\ndef parts_to_whole():\n sym_mat = Matrix([[symbols(\"D[%i]\" % (i*6+j)) for j in range(6)] for i in range(6)])\n skew_mat = Matrix([[symbols(\"W[%i]\" % (i*3+j)) for j in range(3)] for i in range(6)])\n \n tensor = piece_together_fourth(sym_mat, skew_mat)\n matrix = simplify(unroll_fourth(tensor))\n print(\"Matrix\")\n for i in range(9):\n for j in range(9):\n print((\"\\tM[%i] = \" + str(matrix[i,j]) + \";\") % (i*9+j))\n print(\"\")\n\nif __name__ == \"__main__\":\n init_printing(use_unicode=True)\n\n #update()\n tangent()\n #parts_to_whole()\n\n\n", "import sys\nsys.path.append('..')\n\nfrom neml import interpolate, solvers, models, elasticity, ri_flow, hardening, surfaces, visco_flow, general_flow, creep, uniaxial\nfrom common import *\n\nimport unittest\nimport numpy as np\nimport numpy.linalg as la\n\nclass CommonUniaxial(object):\n \"\"\"\n Common uniaxial model tests\n \"\"\"\n def test_tangent(self):\n hn = self.umodel.init_store()\n en = 0.0\n sn = 0.0\n un = 0.0\n pn = 0.0\n tn = 0.0\n Tn = self.T0\n\n n = 100\n emax = 0.1\n\n for i in range(self.nsteps):\n enp1 = en + self.de\n Tnp1 = Tn + self.dT\n tnp1 = tn + self.dt\n snp1, hnp1, Anp1, unp1, pnp1 = self.umodel.update(enp1, en, Tnp1, Tn, \n tnp1, tn, sn, hn, un, pn)\n \n sfn = lambda e: self.umodel.update(e, en, Tnp1, Tn, tnp1, tn,\n sn, hn, un, pn)[0]\n nA = differentiate(sfn, enp1)\n \n self.assertTrue(np.isclose(nA, Anp1, rtol = 1.0e-3))\n\n sn = snp1\n hn = np.copy(hnp1)\n en = enp1\n Tn = Tnp1\n tn = tnp1\n un = unp1\n pn = pnp1\n\nclass TestUniaxialRI(CommonUniaxial, unittest.TestCase):\n \"\"\"\n Test with a simple uniaxial model\n \"\"\"\n def setUp(self):\n E = 200000.0\n nu = 0.27\n\n mu = E / (2 * (1.0 + nu))\n K = E / (3 * (1 - 2 * nu))\n\n s0 = 300.0\n Kp = 0.0\n c = [30000.0]\n r = [60.0]\n A = [0.0]\n n = [1.0]\n \n elastic = elasticity.IsotropicLinearElasticModel(mu, \"shear\",\n K, \"bulk\")\n surface = surfaces.IsoKinJ2()\n iso = hardening.LinearIsotropicHardeningRule(s0, Kp)\n gmodels = [hardening.ConstantGamma(g) for g in r]\n hrule = hardening.Chaboche(iso, c, gmodels, A, n)\n\n flow = ri_flow.RateIndependentNonAssociativeHardening(surface, hrule)\n self.model = models.SmallStrainRateIndependentPlasticity(elastic, flow, verbose = False)\n self.umodel = uniaxial.UniaxialModel(self.model)\n \n self.de = 0.001\n self.dt = 1.0\n self.dT = 0.0\n self.T0 = 0.0\n self.nsteps = 100\n" ]
[ [ "numpy.dot", "numpy.sum", "numpy.allclose", "numpy.einsum", "numpy.linalg.inv", "numpy.eye", "numpy.linalg.norm", "numpy.cross", "numpy.outer", "numpy.array", "numpy.zeros", "numpy.trace", "numpy.isclose" ], [ "numpy.einsum", "numpy.nditer", "numpy.prod" ], [ "numpy.copy", "numpy.isclose" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
dirmeier/jax
[ "9ba28d263479ed5b9cada97bf73aec92ccc69bc6", "9ba28d263479ed5b9cada97bf73aec92ccc69bc6" ]
[ "jax/core.py", "jax/api.py" ]
[ "# Copyright 2018 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\n\nimport operator\nfrom operator import attrgetter\nfrom contextlib import contextmanager, suppress\nfrom collections import namedtuple\nfrom functools import total_ordering\nimport itertools as it\nfrom weakref import ref\nimport threading\nimport types\nfrom typing import (Any, Callable, ClassVar, Dict, Generator,\n Iterator, List, NamedTuple, Optional, Sequence, Set, Tuple,\n Type, Union, cast)\n\nimport numpy as np\n\nfrom . import dtypes\nfrom .config import FLAGS, config\nfrom . import linear_util as lu\n\nfrom . import source_info_util\nfrom .util import safe_zip, safe_map, partial, curry, prod, partialmethod\nfrom .pprint_util import pp, vcat, PrettyPrint\n\n# TODO(dougalm): compilation cache breaks the leak detector. Consisder solving.\ncheck_leaks = False\n\n# Disables internal invariant checks\nskip_checks = not FLAGS.jax_enable_checks # not __debug__ # google doesn't use -O\n\n@contextmanager\ndef skipping_checks():\n \"\"\"Context manager for temporarily disabling checks.\"\"\"\n global skip_checks\n old_value, skip_checks = skip_checks, True\n try:\n yield\n finally:\n skip_checks = old_value\n\nzip = safe_zip\nmap = safe_map\n\n\n# -------------------- jaxprs --------------------\n\nclass Jaxpr:\n constvars: List['Var']\n invars: List['Var']\n outvars: List['Atom']\n eqns: List['JaxprEqn']\n\n def __init__(self, constvars: Sequence['Var'], invars: Sequence['Var'],\n outvars: Sequence['Atom'], eqns: Sequence['JaxprEqn']):\n \"\"\"\n Args:\n constvars: list of variables introduced for constants. Array constants are\n replaced with such variables while scalar constants are kept inline.\n invars: list of input variables. Together, `constvars` and `invars` are\n the inputs to the Jaxpr.\n outvars: list of output variables.\n eqns: list of equations.\n \"\"\"\n self.constvars = list(constvars)\n self.invars = list(invars)\n self.outvars = list(outvars)\n self.eqns = list(eqns)\n\n def __str__(self):\n return str(pp_jaxpr(self))\n __repr__ = __str__\n\n\ndef jaxprs_in_params(params) -> Iterator[Jaxpr]:\n for val in params.values():\n vals = val if isinstance(val, tuple) else (val,)\n for v in vals:\n if isinstance(v, Jaxpr):\n yield v\n elif isinstance(v, ClosedJaxpr):\n yield v.jaxpr\n\n\ndef subjaxprs(jaxpr: Jaxpr) -> Iterator[Jaxpr]:\n \"\"\"Generator for all subjaxprs found in the params of jaxpr.eqns.\n\n Does not descend recursively into the found subjaxprs.\n \"\"\"\n for eqn in jaxpr.eqns:\n yield from jaxprs_in_params(eqn.params)\n\n\nclass ClosedJaxpr:\n jaxpr: Jaxpr\n consts: List['Any']\n\n def __init__(self, jaxpr: Jaxpr, consts: Sequence):\n assert len(consts) == len(jaxpr.constvars)\n self.jaxpr = jaxpr\n self.consts = list(consts)\n\n @property\n def in_avals(self):\n return [v.aval for v in self.jaxpr.invars]\n\n @property\n def out_avals(self):\n return [v.aval for v in self.jaxpr.outvars]\n\n @property\n def literals(self):\n return self.consts # backwards compatible alias\n\n def __str__(self): return str(self.jaxpr)\n def __repr__(self): return repr(self.jaxpr)\n\n@curry\ndef jaxpr_as_fun(closed_jaxpr: ClosedJaxpr, *args):\n return eval_jaxpr(closed_jaxpr.jaxpr, closed_jaxpr.consts, *args)\n\n\nclass JaxprEqn(NamedTuple):\n invars: List['Atom']\n outvars: List['Var']\n primitive: 'Primitive'\n params: Dict[str, Any]\n source_info: Optional[source_info_util.Traceback]\n\n def __repr__(self): return str(pp_eqn(self)).rstrip()\n\ndef new_jaxpr_eqn(invars, outvars, primitive, params, source_info=None):\n return JaxprEqn(invars, outvars, primitive, params, source_info)\n\n\n@total_ordering\nclass Var:\n # TODO(frostig,mattjj): We don't override __eq__ or __hash__, so comparison is\n # by object id, but pretty printing might collide.\n count: int\n suffix: str\n aval: 'AbstractValue'\n\n def __init__(self, count: int, suffix: str, aval: 'AbstractValue'):\n self.count = count\n self.suffix = suffix\n self.aval = raise_to_shaped(aval)\n\n def __lt__(self, other):\n if not isinstance(other, Var):\n return NotImplemented\n else:\n return (self.count, self.suffix) < (other.count, other.suffix)\n\n def __repr__(self):\n rem = self.count\n s = ''\n while True:\n rem, i = rem // 26, rem % 26\n s = chr(97 + i % 26) + s\n if not rem:\n break\n return s + self.suffix\n\ndef _jaxpr_vars(jaxpr):\n return it.chain(\n jaxpr.invars, jaxpr.constvars,\n (v for eqn in jaxpr.eqns for v in eqn.outvars))\n\ndef gensym(jaxprs: Optional[Sequence[Jaxpr]] = None,\n suffix: str = '') -> Callable[['AbstractValue'], Var]:\n \"\"\"Produce distinct variables, printed with the optional suffix.\n\n If `jaxprs` is provided, the variables produced will be distinct from those in\n any of the given jaxprs.\n \"\"\"\n if jaxprs is None:\n start = 0\n else:\n all_vars = it.chain.from_iterable(_jaxpr_vars(j) for j in jaxprs)\n start = 1 + max((v.count for v in all_vars), default=-1)\n counter = it.count(start=start)\n return lambda aval: Var(next(counter), suffix, aval)\n\n# In a jaxpr, `dropvar` can appear in place of a bound variable to indicate that\n# the assignment is dropped, i.e. that an expression's output value will never\n# be read. In that sense, `dropvar` is not a variable, but it is convenient to\n# treat it as a special case of one. Its `aval` is similarly inexact.\nclass DropVar(Var):\n count = -1\n suffix = ''\n def __init__(self): pass\n @property\n def aval(self): return abstract_unit\n def __repr__(self): return '_'\ndropvar = DropVar()\n\nclass Literal:\n __slots__ = [\"val\", \"hash\"]\n\n val: Any\n hash: Optional[int]\n\n def __init__(self, val):\n self.val = val\n try:\n self.hash = hash(val)\n except TypeError:\n if type(val) in literalable_types:\n try:\n self.hash = hash((val.item(), val.dtype))\n except (TypeError, AttributeError, ValueError):\n self.hash = None\n\n @property\n def aval(self):\n return raise_to_shaped(get_aval(self.val))\n\n def __hash__(self):\n assert False\n\n def __repr__(self):\n if hasattr(self, 'hash'):\n return '{}'.format(self.val)\n else:\n return 'Literal(val={})'.format(self.val)\n\nliteralable_types: Set[type] = set()\n\nAtom = Union[Var, Literal]\n\nclass Primitive:\n name: str\n multiple_results = False # set for multi-output primitives\n call_primitive = False # set for call primitives processed in final style\n map_primitive = False # set for map primitives processed in final style\n\n def __init__(self, name: str):\n self.name = name\n\n def __repr__(self):\n return '{}'.format(self.name)\n\n\n def bind(self, *args, **params):\n assert skip_checks or all(isinstance(arg, Tracer)\n or valid_jaxtype(arg) for arg in args), args\n top_trace = find_top_trace(args)\n tracers = map(top_trace.full_raise, args)\n out = top_trace.process_primitive(self, tracers, params)\n return map(full_lower, out) if self.multiple_results else full_lower(out)\n\n def def_impl(self, impl):\n self.impl = impl\n return impl\n\n def def_abstract_eval(self, abstract_eval):\n self.abstract_eval = abstract_eval\n return abstract_eval\n\n def def_custom_bind(self, bind):\n self.bind = bind\n return bind\n\n def impl(self, *args, **params):\n raise NotImplementedError(\"Evaluation rule for '{}' not implemented\"\n .format(self.name))\n\n def abstract_eval(self, *args, **params):\n raise NotImplementedError(\"Abstract evaluation for '{}' not implemented\"\n .format(self.name))\n\n\n# -------------------- lifting --------------------\n\n# TODO(necula): this belongs next to pe.new_eqn_recipe, but is needed in\n# core.py. Plan to move all these utilities to jaxpr.py.\ndef extract_call_jaxpr(\n primitive: Primitive,\n params: Dict[str, Any]) -> Tuple[Optional[Jaxpr], Dict[str, Any]]:\n \"\"\"Extract the call primitive subjaxpr from the params.\n\n Returns the subjaxpr and the params without the \"call_jaxpr\" value. If this is\n not a call primitive then returns (None, params).\n \"\"\"\n if not (primitive.call_primitive or primitive.map_primitive):\n return (None, params)\n else:\n assert \"call_jaxpr\" in params\n new_params = dict(params)\n del new_params[\"call_jaxpr\"]\n return (params[\"call_jaxpr\"], new_params)\n\n\ndef eval_jaxpr(jaxpr: Jaxpr, consts, *args):\n def read(v):\n if type(v) is Literal:\n return v.val\n else:\n return env[v]\n\n def write(v, val):\n env[v] = val\n\n env: Dict[Var, Any] = {}\n write(unitvar, unit)\n map(write, jaxpr.constvars, consts)\n map(write, jaxpr.invars, args)\n for eqn in jaxpr.eqns:\n in_vals = map(read, eqn.invars)\n call_jaxpr, params = extract_call_jaxpr(eqn.primitive, eqn.params)\n if call_jaxpr:\n subfuns = [lu.wrap_init(partial(eval_jaxpr, call_jaxpr, ()))]\n else:\n subfuns = []\n with source_info_util.user_context(eqn.source_info):\n ans = eqn.primitive.bind(*(subfuns + in_vals), **params)\n if eqn.primitive.multiple_results:\n map(write, eqn.outvars, ans)\n else:\n write(eqn.outvars[0], ans)\n return map(read, jaxpr.outvars)\n\n\n# -------------------- tracing --------------------\n\n\nclass Trace:\n __slots__ = ['main', 'level', 'sublevel']\n\n main: 'MainTrace'\n level: int\n sublevel: 'Sublevel'\n\n def __init__(self, main: 'MainTrace', sublevel: 'Sublevel') -> None:\n self.main = main\n self.level = main.level\n self.sublevel = sublevel\n\n def full_raise(self, val) -> 'Tracer':\n if not isinstance(val, Tracer):\n return self.pure(val)\n val._assert_live()\n level = self.level\n sublevel = self.sublevel\n if val._trace.main is self.main:\n if val._trace.sublevel == sublevel:\n return val\n elif val._trace.sublevel < sublevel:\n return self.sublift(val)\n else:\n raise escaped_tracer_error(\"Can't lift sublevels {} to {}\"\n .format(val._trace.sublevel, sublevel))\n elif val._trace.level < level:\n if val._trace.sublevel > sublevel:\n raise escaped_tracer_error(\"Incompatible sublevel: {}, {}\"\n .format(val._trace, (level, sublevel)))\n return self.lift(val)\n elif val._trace.level > level:\n raise escaped_tracer_error(\"Can't lift level {} to {}\"\n .format(val, self))\n else: # val._trace.level == self.level:\n raise escaped_tracer_error(\"Different traces at same level: {}, {}\"\n .format(val, self))\n\n def pure(self, val):\n raise NotImplementedError(\"must override\")\n\n def lift(self, tracer):\n raise NotImplementedError(\"must override\")\n\n def sublift(self, tracer):\n raise NotImplementedError(\"must override\")\n\n def process_primitive(self, primitive, tracers, params):\n raise NotImplementedError(\"must override\")\n\n def __repr__(self):\n return '{}(level={}/{})'.format(\n self.__class__.__name__, self.level, self.sublevel)\n\n def process_call(self, call_primitive, f, tracers, params):\n msg = (f\"{type(self)} must override process_call to handle call-like \"\n \"primitives\")\n raise NotImplementedError(msg)\n\n def process_map(self, call_primitive, f, tracers, params):\n msg = (f\"{type(self)} must override process_map to handle map-like \"\n \"primitives\")\n raise NotImplementedError(msg)\n\n def process_custom_jvp_call(self, primitive, fun, jvp, tracers):\n msg = (f\"{type(self)} must override process_custom_jvp_call \"\n \"to handle custom_jvp primitives\")\n raise NotImplementedError(msg)\n\n def process_custom_vjp_call(self, primitive, fun, fwd, bwd, tracers, out_trees):\n msg = (f\"{type(self)} must override process_custom_vjp_call \"\n \"to handle custom_vjp primitives\")\n raise NotImplementedError(msg)\n\ndef escaped_tracer_error(detail=None):\n msg = (\"Encountered an unexpected tracer. Perhaps this tracer escaped \"\n \"through global state from a previously traced function.\\n\"\n \"The functions being transformed should not save traced values to \"\n \"global state.\")\n if detail:\n msg += \" Detail: {}.\".format(detail)\n return UnexpectedTracerError(msg)\n\nclass UnexpectedTracerError(Exception): pass\n\nclass Tracer:\n __array_priority__ = 1000\n __slots__ = ['_trace', '__weakref__']\n\n def __array__(self, *args, **kw):\n msg = (\"The numpy.ndarray conversion method __array__() was called on \"\n f\"the JAX Tracer object {self}.\\n\\n\"\n \"This error can occur when a JAX Tracer object is passed to a raw \"\n \"numpy function, or a method on a numpy.ndarray object. You might \"\n \"want to check that you are using `jnp` together with \"\n \"`import jax.numpy as jnp` rather than using `np` via \"\n \"`import numpy as np`. If this error arises on a line that involves \"\n \"array indexing, like `x[idx]`, it may be that the array being \"\n \"indexed `x` is a raw numpy.ndarray while the indices `idx` are a \"\n \"JAX Tracer instance; in that case, you can instead write \"\n \"`jax.device_put(x)[idx]`.\")\n raise Exception(msg)\n\n def __init__(self, trace: Trace):\n self._trace = trace\n\n def __iter__(self):\n return iter(self.aval._iter(self))\n\n def __len__(self):\n return self.aval._len(self)\n\n @property\n def aval(self):\n raise NotImplementedError(\"must override\")\n\n def _assert_live(self) -> None:\n pass # Override for liveness checking\n\n # Python looks up special methods only on classes, not instances. This means\n # these methods needs to be defined explicitly rather than relying on\n # __getattr__.\n def __neg__(self): return self.aval._neg(self)\n def __pos__(self): return self.aval._pos(self)\n def __eq__(self, other): return self.aval._eq(self, other)\n def __ne__(self, other): return self.aval._ne(self, other)\n def __lt__(self, other): return self.aval._lt(self, other)\n def __le__(self, other): return self.aval._le(self, other)\n def __gt__(self, other): return self.aval._gt(self, other)\n def __ge__(self, other): return self.aval._ge(self, other)\n def __abs__(self): return self.aval._abs(self)\n def __add__(self, other): return self.aval._add(self, other)\n def __radd__(self, other): return self.aval._radd(self, other)\n def __sub__(self, other): return self.aval._sub(self, other)\n def __rsub__(self, other): return self.aval._rsub(self, other)\n def __mul__(self, other): return self.aval._mul(self, other)\n def __rmul__(self, other): return self.aval._rmul(self, other)\n def __div__(self, other): return self.aval._div(self, other)\n def __rdiv__(self, other): return self.aval._rdiv(self, other)\n def __truediv__(self, other): return self.aval._truediv(self, other)\n def __rtruediv__(self, other): return self.aval._rtruediv(self, other)\n def __floordiv__(self, other): return self.aval._floordiv(self, other)\n def __rfloordiv__(self, other): return self.aval._rfloordiv(self, other)\n def __divmod__(self, other): return self.aval._divmod(self, other)\n def __rdivmod__(self, other): return self.aval._rdivmod(self, other)\n def __mod__(self, other): return self.aval._mod(self, other)\n def __rmod__(self, other): return self.aval._rmod(self, other)\n def __pow__(self, other): return self.aval._pow(self, other)\n def __rpow__(self, other): return self.aval._rpow(self, other)\n def __matmul__(self, other): return self.aval._matmul(self, other)\n def __rmatmul__(self, other): return self.aval._rmatmul(self, other)\n def __and__(self, other): return self.aval._and(self, other)\n def __rand__(self, other): return self.aval._rand(self, other)\n def __or__(self, other): return self.aval._or(self, other)\n def __ror__(self, other): return self.aval._ror(self, other)\n def __xor__(self, other): return self.aval._xor(self, other)\n def __rxor__(self, other): return self.aval._rxor(self, other)\n def __invert__(self): return self.aval._invert(self)\n def __lshift__(self, other): return self.aval._lshift(self, other)\n def __rlshift__(self, other): return self.aval._rlshift(self, other)\n def __rshift__(self, other): return self.aval._rshift(self, other)\n def __rrshift__(self, other): return self.aval._rrshift(self, other)\n def __getitem__(self, idx): return self.aval._getitem(self, idx)\n def __nonzero__(self): return self.aval._nonzero(self)\n def __bool__(self): return self.aval._bool(self)\n def __int__(self): return self.aval._int(self)\n def __long__(self): return self.aval._long(self)\n def __hex__(self): return self.aval._hex(self)\n def __oct__(self): return self.aval._oct(self)\n def __float__(self): return self.aval._float(self)\n def __complex__(self): return self.aval._complex(self)\n\n def __setitem__(self, idx, val):\n raise TypeError(\"JAX 'Tracer' objects do not support item assignment\")\n\n # NumPy also only looks up special methods on classes.\n def __array_module__(self, types): return self.aval._array_module(self, types)\n\n def __getattr__(self, name):\n # if the aval property raises an AttributeError, gets caught here\n assert skip_checks or name != \"aval\"\n\n try:\n attr = getattr(self.aval, name)\n except KeyError as err:\n raise AttributeError(\n \"{} has no attribute {}\".format(self.__class__.__name__, name)\n ) from err\n else:\n t = type(attr)\n if t is aval_property:\n return attr.fget(self)\n elif t is aval_method:\n return types.MethodType(attr.fun, self)\n else:\n return attr\n\n def __repr__(self):\n base = pp('Traced<{}>with<{}>'.format(self.aval, self._trace))\n contents = self._contents()\n if contents:\n base += pp(' with ') >> vcat(pp('{} = '.format(name)) >> pp_payload\n for name, pp_payload in contents)\n return str(base)\n\n def _contents(self):\n try:\n return [(name, pp(repr(getattr(self, name)))) for name in self.__slots__]\n except AttributeError:\n return ()\n\n def __copy__(self):\n return self\n\n def __deepcopy__(self, unused_memo):\n return self\n\n def _origin_msg(self) -> str:\n return \"\"\n\n# these can be used to set up forwarding of properties and instance methods from\n# Tracer instances to the underlying avals\naval_property = namedtuple(\"aval_property\", [\"fget\"])\naval_method = namedtuple(\"aval_method\", [\"fun\"])\n\n\nclass EvalTrace(Trace):\n # See comments in https://github.com/google/jax/pull/3370\n def pure(self, x): return x\n lift = sublift = pure\n\n def process_primitive(self, primitive, tracers, params):\n return primitive.impl(*tracers, **params)\n\n def process_call(self, primitive, f, tracers, params):\n return primitive.impl(f, *tracers, **params)\n process_map = process_call\n\n def process_custom_jvp_call(self, primitive, fun, jvp, tracers):\n del primitive, jvp # Unused.\n return fun.call_wrapped(*tracers)\n\n def process_custom_vjp_call(self, primitive, fun, fwd, bwd, tracers, out_trees):\n del primitive, fwd, bwd, out_trees # Unused.\n return fun.call_wrapped(*tracers)\n\n\nclass MainTrace:\n level: int\n trace_type: Type[Trace]\n\n def __init__(self, level, trace_type) -> None:\n self.level = level\n self.trace_type = trace_type\n\n def __repr__(self) -> str:\n return \"MainTrace({},{})\".format(self.level, self.trace_type.__name__)\n\n def __hash__(self) -> int:\n return hash((self.level, self.trace_type))\n\n def __eq__(self, other: object) -> bool:\n return (isinstance(other, MainTrace) and\n self.level == other.level and self.trace_type == other.trace_type)\n\nclass TraceStack:\n # See comments in https://github.com/google/jax/pull/3370\n upward: List[MainTrace]\n downward: List[MainTrace]\n\n def __init__(self):\n eval_trace = MainTrace(0, EvalTrace)\n self.stack = [eval_trace]\n self.dynamic = eval_trace\n\n def next_level(self) -> int:\n return len(self.stack)\n\n def push(self, main_trace: MainTrace) -> None:\n self.stack.append(main_trace)\n\n def pop(self) -> None:\n self.stack.pop()\n\n def __repr__(self) -> str:\n stack_str = map(' {}\\n'.format, self.stack[::-1])\n return f'Trace stack\\n{stack_str}\\n{self.dynamic}'\n\n def copy(self):\n new = self.__new__(TraceStack)\n new.stack = self.stack[:]\n new.dynamic = self.dynamic\n return new\n\nclass Sublevel(int): pass\nAxisEnvFrame = namedtuple('AxisEnvFrame', ['name', 'size', 'main_trace'])\n\nclass TraceState:\n trace_stack: TraceStack\n substack: List[Sublevel]\n axis_env: List[AxisEnvFrame]\n\n def __init__(self) -> None:\n self.trace_stack = TraceStack()\n self.substack = [Sublevel(0)]\n self.axis_env = []\n\n def copy(self):\n new = self.__new__(TraceState)\n new.trace_stack = self.trace_stack.copy()\n new.substack = self.substack[:]\n new.axis_env = self.axis_env[:]\n return new\n\n# The global state of the tracer is accessed by a thread-local object.\n# This allows concurrent tracing in separate threads; passing traced objects\n# between threads is forbidden.\nclass ThreadLocalState(threading.local):\n def __init__(self):\n self.trace_state = TraceState()\nthread_local_state = ThreadLocalState()\n\ndef trace_state_clean() -> bool:\n trace_state = thread_local_state.trace_state\n return (trace_state.substack == [Sublevel(0)] and\n trace_state.axis_env == [] and\n trace_state.trace_stack.stack == [MainTrace(0, EvalTrace)] and\n trace_state.trace_stack.dynamic == MainTrace(0, EvalTrace))\n\ndef reset_trace_state() -> bool:\n \"Reset the global trace state and return True if it was already clean.\"\n if not trace_state_clean():\n thread_local_state.trace_state.__init__() # type: ignore\n return False\n else:\n return True\n\ndef cur_sublevel() -> Sublevel:\n return thread_local_state.trace_state.substack[-1]\n\n@contextmanager\ndef new_main(trace_type: Type[Trace], dynamic: bool = False,\n ) -> Generator[MainTrace, None, None]:\n # See comments in https://github.com/google/jax/pull/3370\n stack = thread_local_state.trace_state.trace_stack\n level = stack.next_level()\n main = MainTrace(level, trace_type)\n stack.push(main)\n if dynamic:\n prev_dynamic, stack.dynamic = stack.dynamic, main\n\n try:\n yield main\n finally:\n thread_local_state.trace_state.trace_stack.pop()\n if dynamic:\n stack.dynamic = prev_dynamic\n\n if check_leaks:\n t = ref(main)\n del main\n if t() is not None:\n print(thread_local_state.trace_state.trace_stack)\n raise Exception('Leaked trace {}'.format(t()))\n\n@contextmanager\ndef new_base_main(trace_type: Type[Trace]) -> Generator[MainTrace, None, None]:\n # See comments in https://github.com/google/jax/pull/3370\n stack = thread_local_state.trace_state.trace_stack\n main = MainTrace(0, trace_type)\n prev_dynamic, stack.dynamic = stack.dynamic, main\n prev_base, stack.stack[0] = stack.stack[0], main\n try:\n yield main\n finally:\n stack.dynamic = prev_dynamic\n stack.stack[0] = prev_base\n\n@contextmanager\ndef eval_context():\n with new_base_main(EvalTrace):\n yield\n\n@contextmanager\ndef new_sublevel() -> Generator[None, None, None]:\n sublevel = Sublevel(len(thread_local_state.trace_state.substack))\n thread_local_state.trace_state.substack.append(sublevel)\n try:\n yield\n finally:\n thread_local_state.trace_state.substack.pop()\n\n if check_leaks:\n t = ref(sublevel)\n del sublevel\n if t() is not None:\n raise Exception('Leaked sublevel {}'.format(t()))\n\ndef maybe_new_sublevel(trace):\n # dynamic traces run the WrappedFun, so we raise the sublevel for them\n dynamic = thread_local_state.trace_state.trace_stack.dynamic\n return new_sublevel() if trace.main is dynamic else suppress()\n\ndef full_lower(val):\n if isinstance(val, Tracer):\n return val.full_lower()\n else:\n return val\n\ndef find_top_trace(xs) -> Trace:\n top_main = max((x._trace.main for x in xs if isinstance(x, Tracer)),\n default=None, key=attrgetter('level'))\n dynamic = thread_local_state.trace_state.trace_stack.dynamic\n top_main = (dynamic if top_main is None or dynamic.level > top_main.level\n else top_main)\n return top_main and top_main.trace_type(top_main, cur_sublevel()) # type: ignore\n\n\n# -------------------- abstract values --------------------\n\n\nclass AbstractValue:\n __slots__: List[str] = []\n _num_buffers: int = 1 # number of buffers used to represent the value.\n\n def at_least_vspace(self):\n return self\n\n def __repr__(self):\n try:\n kv_pairs = ('{}={}'.format(k, v) for k, v in self.__dict__.items())\n return '{}({})'.format(self.__class__.__name__, ','.join(kv_pairs))\n except AttributeError:\n return self.__class__.__name__\n\n def strip_weak_type(self) -> 'AbstractValue':\n return self\n\n def join(self, other):\n raise NotImplementedError(\"must override\")\n\nclass Bot(AbstractValue): pass\n\nbot = Bot()\n\nclass AbstractUnit(AbstractValue):\n # TODO(jakevdp): make it possible to set zero buffers\n # _num_buffers = 0\n def join(self, other):\n if not skip_checks:\n assert other is abstract_unit, other\n return self\n def _eq(self, self_traced, other): return get_aval(other) is self\n def str_short(self): return '*'\n\nabstract_unit = AbstractUnit()\n\ndef lattice_join(x: Optional[AbstractValue],\n y: Optional[AbstractValue]) -> AbstractValue:\n if x is None:\n return cast(AbstractValue, y)\n elif y is None:\n return cast(AbstractValue, x)\n elif isinstance(x, type(y)):\n return y.join(x)\n elif isinstance(y, type(x)):\n return x.join(y)\n else:\n raise TypeError((x, y))\n\n# For use in typing annotations to denote either a Tracer or a `valid_jaxtype`.\nValue = Any\n\ndef valid_jaxtype(x):\n try:\n concrete_aval(x)\n except TypeError:\n return False\n else:\n return True\n\ndef check_valid_jaxtype(x):\n if not valid_jaxtype(x):\n raise TypeError(f\"{x} of type {type(x)} is not a valid JAX type\")\n\n\ndef concrete_aval(x):\n for typ in type(x).mro():\n handler = pytype_aval_mappings.get(typ)\n if handler: return handler(x)\n raise TypeError(f\"{type(x)} is not a valid JAX type\")\n\n\ndef get_aval(x):\n if isinstance(x, Tracer):\n return x.aval\n else:\n return concrete_aval(x)\n\n\npytype_aval_mappings: Dict[type, Callable[[Any], AbstractValue]] = {}\n\n\nclass Unit:\n def __repr__(self): return '*'\nunit = Unit()\nliteralable_types.add(Unit)\n\nclass UnitVar(Var):\n count = -1\n suffix = ''\n def __init__(self): pass\n @property\n def aval(self): return abstract_unit\n def __repr__(self): return '*'\nunitvar = UnitVar()\n\npytype_aval_mappings[Unit] = lambda _: abstract_unit\n\nclass ConcretizationTypeError(TypeError): pass\n\ndef raise_concretization_error(val: Tracer, context=\"\"):\n msg = (\"Abstract tracer value encountered where concrete value is expected.\\n\\n\"\n + context + \"\\n\\n\"\n + val._origin_msg() + \"\\n\\n\"\n \"See https://jax.readthedocs.io/en/latest/faq.html#abstract-tracer-value-encountered-where-concrete-value-is-expected-error for more information.\\n\\n\"\n f\"Encountered tracer value: {val}\")\n raise ConcretizationTypeError(msg)\n\n\ndef concretization_function_error(fun, suggest_astype=False):\n fname = getattr(fun, \"__name__\", fun)\n fname_context = f\"The problem arose with the `{fname}` function. \"\n if suggest_astype:\n fname_context += (\"If trying to convert the data type of a value, \"\n f\"try using `x.astype({fun.__name__})` \"\n f\"or `jnp.array(x, {fun.__name__})` instead.\")\n def error(self, arg):\n raise_concretization_error(arg, fname_context)\n return error\n\n\ndef concrete_or_error(force: Any, val: Any, context=\"\"):\n \"\"\"Like force(val), but gives the context in the error message.\"\"\"\n if force is None:\n force = lambda x: x\n if isinstance(val, Tracer):\n if isinstance(val.aval, ConcreteArray):\n return force(val.aval.val)\n else:\n raise_concretization_error(val, context)\n else:\n return force(val)\n\nclass UnshapedArray(AbstractValue):\n __slots__ = ['dtype', 'weak_type']\n array_abstraction_level = 2\n\n def __init__(self, dtype, weak_type=False):\n self.dtype = np.dtype(dtypes.canonicalize_dtype(dtype))\n self.weak_type = weak_type\n\n def __eq__(self, other):\n return (type(self) is type(other) and self.dtype == other.dtype and\n self.weak_type == other.weak_type)\n\n def __ne__(self, other):\n return not self == other\n\n def __hash__(self):\n # can use hash(self.dtype) and rely on the fact that numpy reuses base dtype\n # objects, e.g. `np.zeros(3).dtype is np.zeros(4).dtype`, or we can use\n # the unique character code via hash(self.dtype.char)\n return hash((self.dtype, self.weak_type))\n\n def __repr__(self):\n return '{}({}{})'.format(self.__class__.__name__, self.str_short(),\n \", weak_type=True\" if self.weak_type else \"\")\n\n _bool = _nonzero = concretization_function_error(bool)\n _float = concretization_function_error(float, True)\n _int = concretization_function_error(int, True)\n _complex = concretization_function_error(complex, True)\n _hex = concretization_function_error(hex)\n _oct = concretization_function_error(oct)\n\n def at_least_vspace(self) -> AbstractValue:\n return UnshapedArray(primal_dtype_to_tangent_dtype(self.dtype),\n self.weak_type)\n\n def join(self, other):\n if self.dtype == other.dtype:\n if self.weak_type == other.weak_type:\n return self\n else:\n return UnshapedArray(self.dtype, weak_type=False)\n else:\n raise TypeError(self, other)\n\n def str_short(self) -> str:\n return self.dtype.name\n\n def strip_weak_type(self) -> 'UnshapedArray':\n \"\"\"Returns a copy of the aval with weak_type=False.\"\"\"\n return UnshapedArray(self.dtype) if self.weak_type else self\n\n @property\n def shape(self):\n msg = (\"UnshapedArray has no shape. Please open an issue at \"\n \"https://github.com/google/jax/issues because it's unexpected for \"\n \"UnshapedArray instances to ever be produced.\")\n raise TypeError(msg)\n\nclass ShapedArray(UnshapedArray):\n __slots__ = ['shape']\n array_abstraction_level = 1\n\n def __init__(self, shape, dtype, weak_type=False):\n super(ShapedArray, self).__init__(dtype, weak_type=weak_type)\n self.shape = canonicalize_shape(shape)\n\n ndim = property(lambda self: len(self.shape))\n size = property(lambda self: prod(self.shape))\n\n broadcast: ClassVar[Optional[aval_method]] = None\n transpose: ClassVar[Optional[aval_method]] = None\n reshape: ClassVar[Optional[aval_method]] = None\n _iter: ClassVar[Optional[staticmethod]] = None\n\n def __eq__(self, other):\n return (type(self) is type(other)\n and self.dtype == other.dtype and self.shape == other.shape\n and self.weak_type == other.weak_type)\n\n def __hash__(self):\n # can use hash(self.dtype) and rely on the fact that numpy reuses base dtype\n # objects, e.g. `np.zeros(3).dtype is np.zeros(4).dtype`, or we can use\n # the unique character code via hash(self.dtype.char)\n return hash((self.shape, self.dtype, self.weak_type))\n\n def at_least_vspace(self):\n return ShapedArray(self.shape, primal_dtype_to_tangent_dtype(self.dtype),\n self.weak_type)\n\n def join(self, other):\n if self.shape == other.shape and self.dtype == other.dtype:\n if self.weak_type == other.weak_type:\n return self\n else:\n return ShapedArray(self.shape, self.dtype, weak_type=False)\n elif self.dtype == other.dtype:\n return UnshapedArray(self.dtype)\n else:\n raise TypeError(self, other)\n\n def str_short(self):\n shapestr = ','.join(map(str, self.shape))\n return '{}[{}]'.format(self.dtype.name, shapestr)\n\n def __len__(self):\n try:\n return self.shape[0]\n except IndexError as err:\n raise TypeError(\"len() of unsized object\") from err # same as numpy error\n\n def _len(self, ignored_tracer):\n return len(self)\n\n def strip_weak_type(self):\n return ShapedArray(self.shape, self.dtype) if self.weak_type else self\n\n\ndef _forward_to_value(self, fun, ignored_tracer, *args):\n return fun(self.val, *args)\n\nclass ConcreteArray(ShapedArray):\n __slots__ = ['val']\n array_abstraction_level = 0\n\n def __init__(self, val, weak_type=False):\n super(ConcreteArray, self).__init__(np.shape(val), np.result_type(val),\n weak_type=weak_type)\n # Note: canonicalized self.dtype doesn't necessarily match self.val\n self.val = val\n assert self.dtype != np.dtype('O'), val\n\n def __eq__(self, other):\n if (type(self) is type(other) and self.dtype == other.dtype\n and self.shape == other.shape and self.weak_type == other.weak_type):\n with eval_context(): # in case self.val is a DeviceArray\n return (self.val == other.val).all()\n else:\n return False\n\n def __hash__(self):\n return id(self.val)\n\n def at_least_vspace(self):\n return ShapedArray(self.shape, primal_dtype_to_tangent_dtype(self.dtype),\n weak_type=self.weak_type)\n\n def join(self, other) -> UnshapedArray:\n if self == other:\n return self\n elif self.shape == other.shape and self.dtype == other.dtype:\n return ShapedArray(self.shape, self.dtype,\n weak_type=self.weak_type and other.weak_type)\n elif self.dtype == other.dtype:\n return UnshapedArray(self.dtype,\n weak_type=self.weak_type and other.weak_type)\n else:\n raise TypeError(self, other)\n\n def str_short(self) -> str:\n return str(self.val)\n\n def strip_weak_type(self) -> 'ConcreteArray':\n return ConcreteArray(self.val) if self.weak_type else self\n\n _bool = _nonzero = partialmethod(_forward_to_value, bool)\n _int = partialmethod(_forward_to_value, int)\n _hex = partialmethod(_forward_to_value, hex)\n _oct = partialmethod(_forward_to_value, oct)\n\n _float = concretization_function_error(float, True)\n _complex = concretization_function_error(complex, True)\n\ndef primal_dtype_to_tangent_dtype(primal_dtype):\n if not dtypes.issubdtype(primal_dtype, np.inexact):\n return dtypes.float0\n else:\n return primal_dtype\n\nclass AbstractToken(AbstractValue):\n def join(self, other):\n if isinstance(other, AbstractToken):\n return self\n else:\n assert False, f\"Cannot join {self} with {other}\"\n def str_short(self): return 'Tok'\n\nabstract_token = AbstractToken()\n\n\ndef raise_to_shaped(aval: AbstractValue, weak_type=None):\n if weak_type is None:\n weak_type = getattr(aval, 'weak_type', False)\n for typ in type(aval).mro():\n handler = raise_to_shaped_mappings.get(typ)\n if handler: return handler(aval, weak_type)\n raise TypeError(type(aval))\n\nraise_to_shaped_mappings : Dict[type, Callable] = {\n AbstractUnit: lambda aval, _: aval,\n AbstractToken: lambda aval, _: aval,\n ShapedArray: lambda aval, weak_type: ShapedArray(aval.shape, aval.dtype, weak_type=weak_type)\n}\n\n# Registry for valid dimension types. This is used by masking.Poly.\n_DIMENSION_TYPES: Set[type] = {int}\n\ndef _canonicalize_dimension(dim):\n if type(dim) in _DIMENSION_TYPES:\n return dim\n else:\n return operator.index(dim)\n\ndef canonicalize_shape(shape):\n \"\"\"Canonicalizes and checks for errors in a user-provided shape value.\n\n Args:\n shape: a Python value that represents a shape.\n\n Returns:\n A tuple of integers.\n \"\"\"\n try:\n return tuple(map(_canonicalize_dimension, shape))\n except TypeError:\n pass\n msg = (\"Shapes must be 1D sequences of concrete values of integer type, \"\n \"got {}.\")\n if any(isinstance(x, Tracer) and isinstance(get_aval(x), ShapedArray)\n and not isinstance(get_aval(x), ConcreteArray) for x in shape):\n msg += (\"\\nIf using `jit`, try using `static_argnums` or applying `jit` to \"\n \"smaller subfunctions.\")\n raise TypeError(msg.format(shape))\n\n\n# ------------------- Call -------------------\n\ndef apply_todos(todos, outs):\n todos_list = list(todos)\n while todos_list:\n outs = map(full_lower, todos_list.pop()(outs))\n return outs\n\[email protected]_with_aux\ndef process_env_traces(primitive: Union['CallPrimitive', 'MapPrimitive'],\n level: int, params_tuple: tuple, *args):\n outs = yield args, {}\n params = dict(params_tuple)\n todo = []\n while True:\n tracers = [x for x in outs if isinstance(x, Tracer)\n and (level is None or x._trace.level > level)]\n if tracers:\n ans = max(tracers, key=lambda x: x._trace.level)\n else:\n break\n trace = type(ans._trace)(ans._trace.main, cur_sublevel())\n outs = map(trace.full_raise, outs)\n outs, cur_todo = primitive.post_process(trace, outs, params)\n todo.append(cur_todo)\n yield outs, tuple(todo) # Ensure the aux output is immutable\n\ndef call_bind(primitive: Union['CallPrimitive', 'MapPrimitive'],\n fun, *args, **params):\n params_tuple = tuple(params.items())\n top_trace = find_top_trace(args)\n fun, env_trace_todo = process_env_traces(\n fun, primitive, top_trace and top_trace.level, params_tuple)\n tracers = map(top_trace.full_raise, args)\n with maybe_new_sublevel(top_trace):\n outs = primitive.process(top_trace, fun, tracers, params)\n return map(full_lower, apply_todos(env_trace_todo(), outs))\n\n\nclass CallPrimitive(Primitive):\n multiple_results = True\n call_primitive = True\n\n def bind(self, fun, *args, **params):\n return call_bind(self, fun, *args, **params)\n\n def process(self, trace, fun, tracers, params):\n return trace.process_call(self, fun, tracers, params)\n\n def post_process(self, trace, out_tracers, params):\n return trace.post_process_call(self, out_tracers, params)\n\ndef call_impl(f: lu.WrappedFun, *args, **params):\n del params # params parameterize the call primitive, not the function\n return f.call_wrapped(*args)\n\ncall_p = CallPrimitive('call')\ncall = call_p.bind\ncall_p.def_impl(call_impl)\n\n\n# ------------------- Map -------------------\n\nclass MapPrimitive(Primitive):\n multiple_results = True\n map_primitive = True\n\n def bind(self, fun, *args, **params):\n assert len(params['mapped_invars']) == len(args)\n return call_bind(self, fun, *args, **params)\n\n def process(self, trace, fun, tracers, params):\n return trace.process_map(self, fun, tracers, params)\n\n def post_process(self, trace, out_tracers, params):\n return trace.post_process_map(self, out_tracers, params)\n\n@contextmanager\ndef extend_axis_env(axis_name, size: int, tag: Any):\n frame = AxisEnvFrame(axis_name, size, tag)\n thread_local_state.trace_state.axis_env.append(frame)\n try:\n yield\n finally:\n thread_local_state.trace_state.axis_env.pop()\n\n\n# When a mapped function is given no axis name, we generate a name object based\n# on the id of the function object. Collisions aren't important because this\n# name can't be used in collectives, as user code never gets a ref to this\n# object. We don't want to use the function object itself because that might\n# persist references to the function object.\n# TODO(mattjj): revisit this unique axis name strategy\nclass _TempAxisName:\n\n def __init__(self, obj):\n self.id = id(obj)\n\n def __repr__(self):\n return f'<axis {hex(self.id)}>'\n\n def __hash__(self):\n return hash(self.id)\n\n def __eq__(self, other):\n return type(other) is _TempAxisName and self.id == other.id\n\n\ndef axis_frame(axis_name):\n frames = thread_local_state.trace_state.axis_env\n for frame in reversed(frames):\n if frame.name == axis_name:\n return frame\n\n named_axis = [\n frame.name\n for frame in reversed(frames)\n if not isinstance(frame.name, _TempAxisName)\n ]\n raise NameError(\n f'unbound axis name: {axis_name}. The following axis names (e.g. defined '\n 'by pmap) are available to collectives operations:'\n f'{named_axis}')\n\n\n# ------------------- Jaxpr checking -------------------\n\ndef mapped_aval(size: int, aval: AbstractValue) -> AbstractValue:\n if aval is abstract_unit:\n return aval\n elif isinstance(aval, ShapedArray):\n # might be raising abstraction level from Concrete here\n assert aval.shape[0] == size\n return ShapedArray(aval.shape[1:], aval.dtype)\n else:\n raise TypeError(f\"Mapped operand {aval}\")\n\ndef unmapped_aval(size: int, aval: AbstractValue) -> AbstractValue:\n if aval is abstract_unit:\n return aval\n elif isinstance(aval, ShapedArray):\n return ShapedArray((size,) + aval.shape, aval.dtype)\n else:\n raise TypeError(f\"Mapped output {aval}\")\n\ndef typecheck(aval: AbstractValue, x) -> bool:\n return typecompat(aval, get_aval(x))\n\ndef typecompat(aval_ref: AbstractValue, aval: AbstractValue) -> bool:\n \"\"\"Determine whether `aval` conforms to `aval_ref`\"\"\"\n aval_ref = raise_to_shaped(aval_ref).strip_weak_type()\n try:\n return aval_ref == lattice_join(aval_ref, aval).strip_weak_type()\n except TypeError:\n return False\n\ndef typematch(aval1: UnshapedArray, aval2: UnshapedArray) -> bool:\n return raise_to_shaped(aval1, weak_type=False) == raise_to_shaped(aval2, weak_type=False)\n\nclass JaxprTypeError(TypeError): pass\n\ndef typecheck_assert(pred, msg):\n if not pred:\n raise JaxprTypeError(msg)\n\ncustom_typechecks: Dict[Primitive, Callable] = {}\n\ndef check_jaxpr(jaxpr: Jaxpr):\n \"\"\"Checks well-formedness of a jaxpr.\n\n Specifically, check that:\n - variables that are read are bound beforehand\n - variables are typed equally throughout a jaxpr\n - variable type annotations are compatible with their binding expression\n\n Raises `TypeError` if `jaxpr` is determined invalid. Returns `None` otherwise.\n \"\"\"\n try:\n _check_jaxpr(jaxpr, [v.aval for v in jaxpr.invars])\n except JaxprTypeError as e:\n if len(e.args) == 2:\n msg, eqn_idx = e.args\n jaxpr_str = str(pp_jaxpr_eqn_range(jaxpr, eqn_idx - 10, eqn_idx + 10))\n else:\n msg, = e.args\n jaxpr_str = str(pp_jaxpr_eqn_range(jaxpr, 0, 20))\n msg = \"\\n\\n\".join([msg, \"while checking jaxpr:\", jaxpr_str])\n raise JaxprTypeError(msg) from None\n\ndef _check_jaxpr(jaxpr: Jaxpr, in_avals: Sequence[AbstractValue]):\n\n def read(v: Atom) -> AbstractValue:\n if isinstance(v, Literal):\n return raise_to_shaped(get_aval(v.val))\n else:\n typecheck_assert(v in env, f\"Variable '{v}' not defined\")\n return env[v]\n\n def write(v: Var, a: AbstractValue) -> None:\n typecheck_assert(v not in env, f\"Variable '{v}' already bound\")\n if v is not dropvar:\n typecheck_assert(typecompat(v.aval, a),\n f\"Variable '{v}' inconsistently typed as {a}, \"\n f\"bound as {v.aval}\")\n env[v] = a\n\n env : Dict[Var, AbstractValue] = {}\n\n write(unitvar, abstract_unit)\n map(write, jaxpr.constvars, [v.aval for v in jaxpr.constvars])\n map(write, jaxpr.invars, in_avals)\n\n for eqn_idx, eqn in enumerate(jaxpr.eqns):\n prim = eqn.primitive\n try:\n in_avals = map(read, eqn.invars)\n typecheck_assert(all(not isinstance(ina, ConcreteArray) for ina in in_avals),\n \"Equation given ConcreteArray type inputs\")\n if prim in custom_typechecks:\n custom_typechecks[prim](*in_avals, **eqn.params)\n if prim.call_primitive:\n out_avals = check_call(prim, in_avals, eqn.params)\n elif prim.map_primitive:\n out_avals = check_map(prim, in_avals, eqn.params)\n else:\n out_avals = check_eqn(prim, in_avals, eqn.params)\n map(write, eqn.outvars, out_avals)\n except JaxprTypeError as e:\n msg, = e.args\n src = source_info_util.summarize(eqn.source_info)\n msg = \"\\n\\n\".join([msg, \"in equation:\", str(pp_eqn(eqn).indent(2)),\n f\"from source: {src}\"])\n raise JaxprTypeError(msg, eqn_idx) from None\n\n map(read, jaxpr.outvars)\n\ndef check_eqn(prim, in_avals, params):\n for jaxpr in jaxprs_in_params(params):\n check_jaxpr(jaxpr)\n\n out_avals = prim.abstract_eval(*in_avals, **params)\n if not prim.multiple_results:\n out_avals = [out_avals]\n return out_avals\n\ndef check_call(prim, in_avals, params):\n typecheck_assert(\"call_jaxpr\" in params,\n f\"Call primitive {prim} missing 'call_jaxpr' parameter\")\n call_jaxpr = params[\"call_jaxpr\"]\n\n # These checks also happen in recursive call, but give better errors here.\n typecheck_assert(len(in_avals) == len(call_jaxpr.invars),\n f\"Call primitive {prim} with {len(call_jaxpr.invars)} \"\n f\"operands cannot call jaxpr with {len(call_jaxpr.invars)} \"\n f\"inputs\")\n binder_avals = [v.aval for v in call_jaxpr.invars]\n for binder_aval, in_aval in zip(binder_avals, in_avals):\n typecheck_assert(typecompat(binder_aval, in_aval),\n f\"Call primitive {prim} passes operand {in_aval} \"\n f\"to jaxpr expecting {binder_aval}\")\n\n _check_jaxpr(call_jaxpr, in_avals)\n\n out_avals = [v.aval for v in call_jaxpr.outvars]\n return out_avals\n\ndef check_map(prim, in_avals, params):\n typecheck_assert(\"call_jaxpr\" in params,\n f\"Map primitive {prim} missing 'call_jaxpr' parameter\")\n call_jaxpr = params[\"call_jaxpr\"]\n typecheck_assert(\"axis_size\" in params,\n f\"Map primitive {prim} missing 'axis_size' parameter\")\n axis_size = params[\"axis_size\"]\n typecheck_assert(\"mapped_invars\" in params,\n f\"Map primitive {prim} missing 'mapped_invars' parameter\")\n mapped_invars = params[\"mapped_invars\"]\n\n binder_avals = [unmapped_aval(axis_size, v.aval) if mapped else v.aval\n for v, mapped in zip(call_jaxpr.invars, mapped_invars)]\n for binder_aval, in_aval in zip(binder_avals, in_avals):\n typecheck_assert(typecompat(binder_aval, in_aval),\n f\"Call primitive {prim} passes operand {in_aval} \"\n f\"to jaxpr expecting {binder_aval}\")\n\n mapped_avals = [mapped_aval(axis_size, aval) if mapped else aval\n for aval, mapped in zip(in_avals, mapped_invars)]\n _check_jaxpr(call_jaxpr, mapped_avals)\n\n mapped_out_avals = [v.aval for v in call_jaxpr.outvars]\n out_avals = [unmapped_aval(axis_size, aval) for aval in mapped_out_avals]\n return out_avals\n\n\n# ------------------- Jaxpr printed representation -------------------\n\ndef pp_vars(vs: Sequence[Any], print_shapes: bool = False) -> str:\n if print_shapes:\n return ' '.join(f'{v}:{v.aval.str_short()}' for v in vs)\n else:\n return ' '.join(map(str, vs))\n\ndef pp_eqn_compact(primitive_name: str, params: Dict) -> PrettyPrint:\n filtered_params = {k: v for k, v in params.items()\n if (k != 'branches' and\n not isinstance(v, (Jaxpr, ClosedJaxpr)))}\n return pp(primitive_name) >> pp_kv_pairs(sorted(filtered_params.items()))\n\ndef pp_eqn(eqn: JaxprEqn, print_shapes: bool = False) -> PrettyPrint:\n lhs = pp_vars(eqn.outvars, print_shapes)\n pp_lhs = pp(f'{lhs} =')\n pp_rhs = (pp(eqn.primitive.name) >>\n pp_kv_pairs(sorted(eqn.params.items())) >> pp(' ') >>\n pp(pp_vars(eqn.invars, print_shapes)))\n if len(lhs) <= 6 or print_shapes:\n return pp_lhs >> pp(' ') >> pp_rhs\n else:\n return pp_lhs + pp_rhs.indent(2)\n\ndef pp_eqns(eqns: Sequence[JaxprEqn],\n source_info: bool = False) -> Sequence[PrettyPrint]:\n pps = map(pp_eqn, eqns)\n if source_info:\n l = max((i + len(s) for x in pps for i, s in x.lines), default=None)\n if l is not None:\n return [p.annotate(l, source_info_util.summarize(e.source_info))\n for e, p in zip(eqns, pps)]\n return pps\n\ndef pp_jaxpr(jaxpr: Jaxpr, source_info: bool = False) -> PrettyPrint:\n pps = pp_eqns(jaxpr.eqns, source_info=source_info)\n str_outvars = str(tuple(jaxpr.outvars))\n return (pp('{{ lambda {} ; {}.'.format(pp_vars(jaxpr.constvars),\n pp_vars(jaxpr.invars))) +\n ((pp('let ') >> vcat(pps))\n + pp('in {} }}'.format(str_outvars))).indent(2))\n\ndef pp_jaxpr_eqn_range(jaxpr: Jaxpr, lo: int, hi: int,\n source_info: bool = False) -> PrettyPrint:\n lo = max(lo, 0)\n hi = max(lo, min(hi, len(jaxpr.eqns)))\n eqns = jaxpr.eqns[lo:hi]\n pps = []\n if len(eqns) == 0 and len(jaxpr.eqns) != 0:\n pps.append(pp('...'))\n else:\n if lo != 0:\n pps.append(pp('...'))\n pps.extend(pp_eqns(eqns, source_info=source_info))\n if hi != len(jaxpr.eqns):\n pps.append(pp('...'))\n str_outvars = str(tuple(jaxpr.outvars))\n return (pp('{{ lambda {} ; {}.'.format(pp_vars(jaxpr.constvars),\n pp_vars(jaxpr.invars))) +\n ((pp('let ') >> vcat(pps))\n + pp('in {} }}'.format(str_outvars))).indent(2))\n\ndef pp_jaxprs(jaxprs) -> PrettyPrint:\n jaxprs = [j.jaxpr if isinstance(j, ClosedJaxpr) else j for j in jaxprs]\n return pp('( ') >> vcat(map(pp_jaxpr, jaxprs)) >> pp(' )')\n\ndef pp_kv_pair(k, v):\n if type(v) is tuple and all(isinstance(j, (Jaxpr, ClosedJaxpr)) for j in v):\n pp_v = pp_jaxprs(v)\n else:\n pp_v = pp(v)\n return pp(f'{k}=') >> pp_v\n\ndef pp_kv_pairs(kv_pairs):\n if kv_pairs:\n return pp('[ ') >> vcat([pp_kv_pair(k, v) for k, v in kv_pairs]) >> pp(' ]')\n else:\n return pp('')\n\[email protected]_omnistaging_disabler\ndef omnistaging_disabler() -> None:\n global thread_local_state, call_bind, find_top_trace, initial_style_staging, \\\n new_main, reset_trace_state, TraceStack, TraceState, extend_axis_env, \\\n eval_context\n\n class TraceStack:\n upward: List[MainTrace]\n downward: List[MainTrace]\n\n def __init__(self):\n self.upward = []\n self.downward = []\n\n def next_level(self, bottom: bool) -> int:\n if bottom:\n return - (len(self.downward) + 1)\n else:\n return len(self.upward)\n\n def push(self, main_trace: MainTrace, bottom: bool) -> None:\n if bottom:\n self.downward.append(main_trace)\n else:\n self.upward.append(main_trace)\n\n def pop(self, bottom: bool) -> None:\n if bottom:\n self.downward.pop()\n else:\n self.upward.pop()\n\n def __repr__(self) -> str:\n return 'Trace stack\\n{} ---\\n{}'.format(\n map(' {}\\n'.format, self.upward[::-1]),\n map(' {}\\n'.format, self.downward))\n\n def copy(self):\n new = TraceStack()\n new.upward = self.upward[:]\n new.downward = self.downward[:]\n return new\n\n class TraceState:\n trace_stack: TraceStack\n substack: List[Sublevel]\n initial_style: bool\n\n def __init__(self) -> None:\n self.trace_stack = TraceStack() # type: ignore\n self.substack = [Sublevel(0)]\n self.initial_style = False\n\n def copy(self):\n new = TraceState()\n new.trace_stack = self.trace_stack.copy()\n new.substack = self.substack[:]\n new.initial_style = self.initial_style\n return new\n\n thread_local_state = ThreadLocalState()\n\n def reset_trace_state() -> bool:\n \"Reset the global trace state and return True if it was already clean.\"\n if (thread_local_state.trace_state.substack != [Sublevel(0)] or\n thread_local_state.trace_state.trace_stack.downward or\n thread_local_state.trace_state.trace_stack.upward):\n thread_local_state.trace_state.__init__() # type: ignore\n return False\n else:\n return True\n\n @contextmanager\n def new_main(trace_type: Type[Trace], bottom=False) -> Generator[MainTrace, None, None]:\n level = thread_local_state.trace_state.trace_stack.next_level(bottom)\n main = MainTrace(level, trace_type)\n thread_local_state.trace_state.trace_stack.push(main, bottom)\n\n try:\n yield main\n finally:\n thread_local_state.trace_state.trace_stack.pop(bottom)\n\n if check_leaks:\n t = ref(main)\n del main\n if t() is not None:\n print(thread_local_state.trace_state.trace_stack)\n raise Exception('Leaked trace {}'.format(t()))\n\n def find_top_trace(xs) -> Optional[Trace]:\n top_trace = max((x._trace for x in xs if isinstance(x, Tracer)),\n key=attrgetter('level'), default=None)\n return top_trace and type(top_trace)(top_trace.main, cur_sublevel())\n\n @contextmanager\n def eval_context():\n yield # dummy implementation for forward compatibility\n\n def bind(self, *args, **kwargs):\n assert skip_checks or all(isinstance(arg, Tracer)\n or valid_jaxtype(arg) for arg in args), args\n top_trace = find_top_trace(args)\n if top_trace is None:\n return self.impl(*args, **kwargs)\n\n tracers = map(top_trace.full_raise, args)\n out_tracer = top_trace.process_primitive(self, tracers, kwargs)\n if self.multiple_results:\n return map(full_lower, out_tracer)\n else:\n return full_lower(out_tracer)\n Primitive.bind = bind # type: ignore\n\n def call_bind(primitive: Union['CallPrimitive', 'MapPrimitive'],\n fun: lu.WrappedFun, *args, **params):\n params_tuple = tuple(params.items())\n top_trace = find_top_trace(args)\n level = (thread_local_state.trace_state.trace_stack.next_level(True)\n if top_trace is None else top_trace.level)\n params_tuple = tuple(params.items())\n fun, env_trace_todo = process_env_traces(fun, primitive, level, params_tuple)\n if top_trace is None:\n with new_sublevel():\n outs = primitive.impl(fun, *args, **params)\n else:\n tracers = map(top_trace.full_raise, args)\n outs = primitive.process(top_trace, fun, tracers, params)\n return apply_todos(env_trace_todo(), map(full_lower, outs))\n\n @contextmanager\n def extend_axis_env(axis_name, size: int, tag: Any):\n yield\n\n @contextmanager\n def initial_style_staging():\n trace_state = thread_local_state.trace_state\n prev, trace_state.initial_style = trace_state.initial_style, True\n try:\n yield\n finally:\n trace_state.initial_style = prev\n\n# Casting float0 array to a float-valued zero array.\ndef zeros_like_float0(array, dtype=None):\n if not dtype:\n dtype = np.float\n return np.zeros(array.shape, dtype)\n", "# coding=utf-8\n# Copyright 2018 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\"\"\"JAX user-facing transformations and utilities.\n\nThe transformations here mostly wrap internal transformations, providing\nconvenience flags to control behavior and handling Python containers of\narguments and outputs. The Python containers handled are pytrees (see\ntree_util.py), which include nested tuples/lists/dicts, where the leaves are\narrays.\n\"\"\"\n\n# flake8: noqa: F401\nimport collections\nimport functools\nimport inspect\nimport itertools as it\nimport threading\nimport weakref\nfrom typing import Any, Callable, Iterable, List, NamedTuple, Optional, Sequence, Tuple, TypeVar, Union\nfrom warnings import warn\n\nimport numpy as np\nfrom contextlib import contextmanager, ExitStack\n\nfrom . import core\nfrom . import lib\nfrom . import linear_util as lu\nfrom . import ad_util\nfrom . import dtypes\nfrom .core import eval_jaxpr\nfrom .api_util import (wraps, flatten_fun, apply_flat_fun, flatten_fun_nokwargs,\n flatten_fun_nokwargs2, argnums_partial, flatten_axes,\n donation_vector, rebase_donate_argnums)\nfrom .traceback_util import api_boundary\nfrom .tree_util import (tree_map, tree_flatten, tree_unflatten, tree_structure,\n tree_transpose, tree_leaves, tree_multimap,\n treedef_is_leaf, Partial)\nfrom .util import (unzip2, curry, partial, safe_map, safe_zip, prod, split_list,\n extend_name_stack, wrap_name, cache)\nfrom .lib import jax_jit\nfrom .lib import version\nfrom .lib import xla_bridge as xb\nfrom .lib import xla_client as xc\n# Unused imports to be exported\nfrom .lib.xla_bridge import (device_count, local_device_count, devices,\n local_devices, host_id, host_ids, host_count)\nfrom .abstract_arrays import ConcreteArray, ShapedArray, raise_to_shaped\nfrom .interpreters import partial_eval as pe\nfrom .interpreters import xla\nfrom .interpreters import pxla\nfrom .interpreters import ad\nfrom .interpreters import batching\nfrom .interpreters import masking\nfrom .interpreters import invertible_ad as iad\nfrom .interpreters.invertible_ad import custom_ivjp\nfrom .custom_derivatives import custom_jvp, custom_vjp\nfrom .config import flags, config, bool_env\n\nAxisName = Any\n\n# This TypeVar is used below to express the fact that function call signatures\n# are invariant under the jit, vmap, and pmap transformations.\n# Specifically, we statically assert that the return type is invariant.\n# Until PEP-612 is implemented, we cannot express the same invariance for\n# function arguments.\n# Note that the return type annotations will generally not strictly hold\n# in JIT internals, as Tracer values are passed through the function.\n# Should this raise any type errors for the tracing code in future, we can disable\n# type checking in parts of the tracing code, or remove these annotations.\nT = TypeVar(\"T\")\n\nmap = safe_map\nzip = safe_zip\n\nFLAGS = flags.FLAGS\nflags.DEFINE_bool(\"jax_disable_jit\", bool_env(\"JAX_DISABLE_JIT\", False),\n \"Disable JIT compilation and just call original Python.\")\nflags.DEFINE_bool(\n \"experimental_cpp_jit\", bool_env(\"JAX_CPP_JIT\", False),\n \"A temporary flag enabling the C++ jax.jit fast path.\"\n \"Set this to `False` only if it crashes otherwise and report \"\n \"the error to the jax-team.\")\n\nfloat0 = dtypes.float0\n\ndef _check_callable(fun):\n if not callable(fun):\n raise TypeError(f\"Expected a callable value, got {fun}\")\n if inspect.isgeneratorfunction(fun):\n raise TypeError(f\"Expected a function, got a generator function: {fun}\")\n\n\nclass _ThreadLocalState(threading.local):\n\n def __init__(self):\n self.jit_is_disabled = False\n\n\n_thread_local_state = _ThreadLocalState()\n\n\ndef jit(fun: Callable[..., T],\n static_argnums: Union[int, Iterable[int]] = (),\n device=None,\n backend: Optional[str] = None,\n donate_argnums: Union[int, Iterable[int]] = ()) -> Callable[..., T]:\n \"\"\"Sets up ``fun`` for just-in-time compilation with XLA.\n\n Args:\n fun: Function to be jitted. Should be a pure function, as side-effects may\n only be executed once. Its arguments and return value should be arrays,\n scalars, or (nested) standard Python containers (tuple/list/dict) thereof.\n Positional arguments indicated by ``static_argnums`` can be anything at\n all, provided they are hashable and have an equality operation defined.\n Static arguments are included as part of a compilation cache key, which is\n why hash and equality operators must be defined.\n static_argnums: An int or collection of ints specifying which positional\n arguments to treat as static (compile-time constant). Operations that only\n depend on static arguments will be constant-folded in Python (during\n tracing), and so the corresponding argument values can be any Python\n object. Calling the jitted function with different values for these\n constants will trigger recompilation. If the jitted function is called\n with fewer positional arguments than indicated by ``static_argnums`` then\n an error is raised. Arguments that are not arrays or containers thereof\n must be marked as static. Defaults to ().\n device: This is an experimental feature and the API is likely to change.\n Optional, the Device the jitted function will run on. (Available devices\n can be retrieved via :py:func:`jax.devices`.) The default is inherited from\n XLA's DeviceAssignment logic and is usually to use ``jax.devices()[0]``.\n backend: This is an experimental feature and the API is likely to change.\n Optional, a string representing the XLA backend: ``'cpu'``, ``'gpu'``, or\n ``'tpu'``.\n donate_argnums: Specify which arguments are \"donated\" to the computation.\n It is safe to donate arguments if you no longer need them once the\n computation has finished. In some cases XLA can make use of donated\n buffers to reduce the amount of memory needed to perform a computation,\n for example recycling one of your input buffers to store a result. You\n should not re-use buffers that you donate to a computation, JAX will raise\n an error if you try to.\n\n Returns:\n A wrapped version of ``fun``, set up for just-in-time compilation.\n\n In the following example, ``selu`` can be compiled into a single fused kernel\n by XLA:\n\n >>> import jax\n >>>\n >>> @jax.jit\n ... def selu(x, alpha=1.67, lmbda=1.05):\n ... return lmbda * jax.numpy.where(x > 0, x, alpha * jax.numpy.exp(x) - alpha)\n >>>\n >>> key = jax.random.PRNGKey(0)\n >>> x = jax.random.normal(key, (10,))\n >>> print(selu(x)) # doctest: +SKIP\n [-0.54485 0.27744 -0.29255 -0.91421 -0.62452 -0.24748\n -0.85743 -0.78232 0.76827 0.59566 ]\n \"\"\"\n if FLAGS.experimental_cpp_jit and config.omnistaging_enabled:\n return _cpp_jit(fun, static_argnums, device, backend, donate_argnums)\n else:\n return _python_jit(fun, static_argnums, device, backend, donate_argnums)\n\n\ndef _python_jit(\n fun: Callable,\n static_argnums: Union[int, Iterable[int]] = (),\n device=None,\n backend: Optional[str] = None,\n donate_argnums: Union[int, Iterable[int]] = ()\n) -> Callable:\n \"\"\"The Python implementation of `jax.jit`, being slowly replaced by _cpp_jit.\"\"\"\n _check_callable(fun)\n static_argnums = _ensure_tuple(static_argnums)\n donate_argnums = _ensure_tuple(donate_argnums)\n donate_argnums = rebase_donate_argnums(donate_argnums, static_argnums)\n\n @wraps(fun)\n @api_boundary\n def f_jitted(*args, **kwargs):\n if _jit_is_disabled():\n return fun(*args, **kwargs)\n if max(static_argnums + donate_argnums, default=-1) >= len(args):\n msg = (\"jitted function has static_argnums={}, donate_argnums={} but \"\n \"was called with only {} positional arguments.\")\n raise ValueError(msg.format(static_argnums, donate_argnums, len(args)))\n f = lu.wrap_init(fun)\n if static_argnums:\n dyn_argnums = [i for i in range(len(args)) if i not in static_argnums]\n f, dyn_args = argnums_partial(f, dyn_argnums, args)\n else:\n dyn_args = args\n args_flat, in_tree = tree_flatten((dyn_args, kwargs))\n if donate_argnums:\n donated_invars = donation_vector(donate_argnums, dyn_args, kwargs)\n else:\n donated_invars = (False,) * len(args_flat)\n for arg in args_flat:\n _check_arg(arg)\n flat_fun, out_tree = flatten_fun(f, in_tree)\n out = xla.xla_call(\n flat_fun,\n *args_flat,\n device=device,\n backend=backend,\n name=flat_fun.__name__,\n donated_invars=donated_invars)\n return tree_unflatten(out_tree(), out)\n\n return f_jitted\n\n\nclass _BackendAndDeviceInfo(NamedTuple):\n default_device: xc.Device\n committed_to_device: bool\n\n\ndef _cpp_jit(\n fun: Callable,\n static_argnums: Union[int, Iterable[int]] = (),\n device=None,\n backend: Optional[str] = None,\n donate_argnums: Union[int, Iterable[int]] = ()) -> Callable:\n \"\"\"An implementation of `jit` that tries to do as much as possible in C++.\n\n The goal of this function is to speed up the time it takes to process the\n arguments, find the correct C++ executable, start the transfer of arguments\n and schedule the computation.\n As long as it does not support all features of the Python implementation\n the C++ code will fallback to `_python_jit` when it faces some unsupported\n feature.\n \"\"\"\n _check_callable(fun)\n static_argnums = _ensure_tuple(static_argnums)\n donate_argnums = _ensure_tuple(donate_argnums)\n donate_argnums = rebase_donate_argnums(donate_argnums, static_argnums)\n\n if device is not None and backend is not None:\n raise ValueError(\"can't specify both a device and a backend for jit, \"\n \"got device={} and backend={}\".format(device, backend))\n\n def cache_miss(*args, **kwargs):\n ### This first part is basically the same code as in _python_jit.\n # An alternative would be for cache_miss to accept from C++ the arguments\n # (dyn_args, donated_invars, args_flat, in_tree), since otherwise we have\n # work/code that is redundant between C++ and Python. We can try that later.\n f = lu.wrap_init(fun)\n if static_argnums:\n dyn_argnums = [i for i in range(len(args)) if i not in static_argnums]\n f, dyn_args = argnums_partial(f, dyn_argnums, args)\n else:\n dyn_args = args\n args_flat, in_tree = tree_flatten((dyn_args, kwargs))\n if donate_argnums:\n donated_invars = donation_vector(donate_argnums, dyn_args, kwargs)\n else:\n donated_invars = (False,) * len(args_flat)\n\n for arg in args_flat:\n _check_arg(arg)\n flat_fun, out_tree = flatten_fun(f, in_tree)\n out_flat = xla.xla_call(\n flat_fun,\n *args_flat,\n device=device,\n backend=backend,\n name=flat_fun.__name__,\n donated_invars=donated_invars)\n out_pytree_def = out_tree()\n out = tree_unflatten(out_pytree_def, out_flat)\n\n ### Decide whether we can support the C++ fast path\n # High level note: The Python tracing mechanism is complex; in particular\n # to know whether `jax.jit(f)(x)` will execute or trace, it's not enough to\n # inspect the argument x, we actually do need to execute it and look at the\n # outputs that could be tracers (if f is capturing `Tracer` by closure).\n execute: Optional[functools.partial] = (\n xla._xla_callable.most_recent_entry())\n use_fastpath = (\n # This is if we have already executed this code-path (most-recent entry\n # has been reset to None). Thus, we do not support the fast-path.\n execute is not None and\n execute.func is xla._execute_compiled and # not trivial, not pmap\n # Not supported: ShardedDeviceArray, DeviceConstant.\n all(type(x) is xla.DeviceArray for x in out_flat) and\n # TODO(mattjj): Add support for lazy-expression.\n # If the input is a DeviceArray, then it should have a trivial LazyExpr.\n all(\n type(x) is not xla.DeviceArray or xla.lazy.is_trivial(x._lazy_expr)\n for x in args_flat))\n\n ### If we can use the fastpath, we return required info to the caller.\n if use_fastpath:\n xla_executable, _, result_handlers = execute.args\n fastpath_data = (xla_executable, result_handlers, out_pytree_def)\n else:\n fastpath_data = None\n\n return out, fastpath_data\n\n def get_device_info():\n \"\"\"Backends do not exist before __main__ is being executed.\"\"\"\n committed_to_device = device is not None or backend is not None\n\n if device is not None:\n default_device = device\n else:\n backend_ = xb.get_backend(backend)\n default_device = backend_.get_default_device_assignment(1)[0]\n\n return _BackendAndDeviceInfo(default_device, committed_to_device)\n\n def get_jax_enable_x64():\n \"\"\"Returns the value of the flag after GoogleInit.\n\n We must wait until flags have been parsed (in particular for top-level\n functions decorated with jax.jit), so we delay inspecting the value\n of the jax_enable_x64 flag until JIT time.\n \"\"\"\n return FLAGS.jax_enable_x64\n\n def get_jax_disable_jit_flag():\n \"\"\"Returns the value of the `jax_disable_jit` flag.\n\n Both a flag and the `disable_jit` context manager can disable jit. We access\n the flag only once, when jitting the function, and the context manager\n modifies a C++ thread-local value.\n \"\"\"\n return config.read(\"jax_disable_jit\")\n\n cpp_jitted_f = jax_jit.jit(fun, cache_miss, get_device_info,\n get_jax_enable_x64, get_jax_disable_jit_flag,\n static_argnums)\n\n # TODO(mattjj): make cpp callable follow descriptor protocol for bound methods\n @wraps(fun)\n @api_boundary\n def f_jitted(*args, **kwargs):\n # TODO(jblespiau): Move this to C++.\n if FLAGS.jax_debug_nans and not _jit_is_disabled():\n device_arrays = cpp_jitted_f(*args, **kwargs)\n try:\n xla.check_nans(xla.xla_call_p, [\n da.device_buffer\n for da in tree_leaves(device_arrays)\n if hasattr(da, \"device_buffer\")\n ])\n return device_arrays\n except FloatingPointError:\n assert FLAGS.jax_debug_nans # compiled_fun can only raise in this case\n print(\"Invalid nan value encountered in the output of a C++-jit \"\n \"function. Calling the de-optimized version.\")\n return cache_miss(*args, **kwargs)[0] # probably won't return\n else:\n return cpp_jitted_f(*args, **kwargs)\n f_jitted._cpp_jitted_f = cpp_jitted_f\n\n return f_jitted\n\n\n@contextmanager\ndef disable_jit():\n \"\"\"Context manager that disables :py:func:`jit` behavior under its dynamic context.\n\n For debugging it is useful to have a mechanism that disables :py:func:`jit`\n everywhere in a dynamic context.\n\n Values that have a data dependence on the arguments to a jitted function are\n traced and abstracted. For example, an abstract value may be a\n :py:class:`ShapedArray` instance, representing the set of all possible arrays\n with a given shape and dtype, but not representing one concrete array with\n specific values. You might notice those if you use a benign side-effecting\n operation in a jitted function, like a print:\n\n >>> import jax\n >>>\n >>> @jax.jit\n ... def f(x):\n ... y = x * 2\n ... print(\"Value of y is\", y)\n ... return y + 3\n ...\n >>> print(f(jax.numpy.array([1, 2, 3])))\n Value of y is Traced<ShapedArray(int32[3])>with<DynamicJaxprTrace(level=0/1)>\n [5 7 9]\n\n Here ``y`` has been abstracted by :py:func:`jit` to a :py:class:`ShapedArray`,\n which represents an array with a fixed shape and type but an arbitrary value.\n The value of ``y`` is also traced. If we want to see a concrete value while\n debugging, and avoid the tracer too, we can use the :py:func:`disable_jit`\n context manager:\n\n >>> import jax\n >>>\n >>> with jax.disable_jit():\n ... print(f(jax.numpy.array([1, 2, 3])))\n ...\n Value of y is [2 4 6]\n [5 7 9]\n \"\"\"\n try:\n prev_val = _thread_local_state.jit_is_disabled\n _thread_local_state.jit_is_disabled = True\n\n prev_cpp_val = lib.jax_jit.get_disable_jit()\n lib.jax_jit.set_disable_jit(True)\n yield\n finally:\n _thread_local_state.jit_is_disabled = prev_val\n lib.jax_jit.set_disable_jit(prev_cpp_val)\n\n\ndef _jit_is_disabled():\n return _thread_local_state.jit_is_disabled or config.read(\"jax_disable_jit\")\n\n\ndef xla_computation(fun: Callable,\n static_argnums: Union[int, Iterable[int]] = (),\n axis_env: Optional[Sequence[Tuple[AxisName, int]]] = None,\n in_parts=None, out_parts=None,\n backend: Optional[str] = None,\n tuple_args: bool = False,\n instantiate_const_outputs: Optional[bool] = None,\n return_shape: bool = False,\n donate_argnums: Union[int, Iterable[int]] = ()) -> Callable:\n \"\"\"Creates a function that produces its XLA computation given example args.\n\n Args:\n fun: Function from which to form XLA computations.\n static_argnums: See the :py:func:`jax.jit` docstring.\n axis_env: Optional, a sequence of pairs where the first element is an axis\n name and the second element is a positive integer representing the size of\n the mapped axis with that name. This parameter is useful when lowering\n functions that involve parallel communication collectives, and it\n specifies the axis name/size environment that would be set up by\n applications of :py:func:`jax.pmap`. See the examples below.\n in_parts: Optional, how each argument to ``fun`` should partitioned or\n replicated. This is used to specify partitioned XLA computations, see\n ``sharded_jit`` for more info.\n out_parts: Optional, how each output of ``fun`` should partitioned or\n replicated. This is used to specify partitioned XLA computations, see\n ``sharded_jit`` for more info.\n backend: This is an experimental feature and the API is likely to change.\n Optional, a string representing the XLA backend: ``'cpu'``, ``'gpu'``, or\n ``'tpu'``.\n tuple_args: Optional bool, defaults to ``False``. If ``True``, the resulting\n XLA computation will have a single tuple argument that is unpacked into\n the specified function arguments.\n instantiate_const_outputs: Deprecated argument, does nothing.\n return_shape: Optional boolean, defaults to ``False``. If ``True``, the\n wrapped function returns a pair where the first element is the XLA\n computation and the second element is a pytree with the same structure as\n the output of ``fun`` and where the leaves are objects with ``shape`` and\n ``dtype`` attributes representing the corresponding types of the output\n leaves.\n\n Returns:\n A wrapped version of ``fun`` that when applied to example arguments returns\n a built XLA Computation (see xla_client.py), from which representations of\n the unoptimized XLA HLO computation can be extracted using methods like\n ``as_hlo_text``, ``as_serialized_hlo_module_proto``, and\n ``as_hlo_dot_graph``. If the argument ``return_shape`` is ``True``, then the\n wrapped function returns a pair where the first element is the XLA\n Computation and the second element is a pytree representing the structure,\n shapes, and dtypes of the output of ``fun``.\n\n For example:\n\n >>> import jax\n >>>\n >>> def f(x): return jax.numpy.sin(jax.numpy.cos(x))\n >>> c = jax.xla_computation(f)(3.)\n >>> print(c.as_hlo_text()) # doctest: +SKIP\n HloModule xla_computation_f.6\n <BLANKLINE>\n ENTRY xla_computation_f.6 {\n constant.2 = pred[] constant(false)\n parameter.1 = f32[] parameter(0)\n cosine.3 = f32[] cosine(parameter.1)\n sine.4 = f32[] sine(cosine.3)\n ROOT tuple.5 = (f32[]) tuple(sine.4)\n }\n <BLANKLINE>\n <BLANKLINE>\n\n\n Here's an example that involves a parallel collective and axis name:\n\n >>> def f(x): return x - jax.lax.psum(x, 'i')\n >>> c = jax.xla_computation(f, axis_env=[('i', 4)])(2)\n >>> print(c.as_hlo_text()) # doctest: +SKIP\n HloModule jaxpr_computation.9\n primitive_computation.3 {\n parameter.4 = s32[] parameter(0)\n parameter.5 = s32[] parameter(1)\n ROOT add.6 = s32[] add(parameter.4, parameter.5)\n }\n ENTRY jaxpr_computation.9 {\n tuple.1 = () tuple()\n parameter.2 = s32[] parameter(0)\n all-reduce.7 = s32[] all-reduce(parameter.2), replica_groups={{0,1,2,3}}, to_apply=primitive_computation.3\n ROOT subtract.8 = s32[] subtract(parameter.2, all-reduce.7)\n }\n <BLANKLINE>\n <BLANKLINE>\n\n Notice the ``replica_groups`` that were generated. Here's an example that\n generates more interesting ``replica_groups``:\n\n >>> from jax import lax\n >>> def g(x):\n ... rowsum = lax.psum(x, 'i')\n ... colsum = lax.psum(x, 'j')\n ... allsum = lax.psum(x, ('i', 'j'))\n ... return rowsum, colsum, allsum\n ...\n >>> axis_env = [('i', 4), ('j', 2)]\n >>> c = xla_computation(g, axis_env=axis_env)(5.)\n >>> print(c.as_hlo_text()) # doctest: +SKIP\n HloModule jaxpr_computation__1.19\n [removed uninteresting text here]\n ENTRY jaxpr_computation__1.19 {\n tuple.1 = () tuple()\n parameter.2 = f32[] parameter(0)\n all-reduce.7 = f32[] all-reduce(parameter.2), replica_groups={{0,2,4,6},{1,3,5,7}}, to_apply=primitive_computation__1.3\n all-reduce.12 = f32[] all-reduce(parameter.2), replica_groups={{0,1},{2,3},{4,5},{6,7}}, to_apply=primitive_computation__1.8\n all-reduce.17 = f32[] all-reduce(parameter.2), replica_groups={{0,1,2,3,4,5,6,7}}, to_apply=primitive_computation__1.13\n ROOT tuple.18 = (f32[], f32[], f32[]) tuple(all-reduce.7, all-reduce.12, all-reduce.17)\n }\n \"\"\"\n internal_computation_maker = _xla_computation(\n fun,\n static_argnums=static_argnums,\n axis_env=axis_env,\n in_parts=in_parts,\n out_parts=out_parts,\n backend=backend,\n tuple_args=tuple_args,\n instantiate_const_outputs=instantiate_const_outputs,\n donate_argnums=donate_argnums)\n\n def computation_maker(*args, **kwargs):\n xla_return = internal_computation_maker(*args, **kwargs)\n if return_shape:\n return xla_return.xla_computation, xla_return.out_shape\n else:\n return xla_return.xla_computation\n\n return computation_maker\n\n\nclass _XlaReturn(NamedTuple):\n xla_computation: xc.XlaComputation\n # A tree of `ShapeDtypeStruct`.\n out_shape: Any\n out_pytree_def: Any # A `PyTreeDef` object.\n lazy_expressions: Optional[List[xla.lazy.LazyExpr]]\n shaped_arrays: List[core.ShapedArray]\n parameter_is_tupled_arguments: bool\n\n\ndef _xla_computation(\n fun: Callable,\n static_argnums: Union[int, Iterable[int]] = (),\n axis_env: Optional[Sequence[Tuple[AxisName, int]]] = None,\n in_parts=None,\n out_parts=None,\n backend: Optional[str] = None,\n tuple_args: Optional[bool] = None,\n instantiate_const_outputs: Optional[bool] = True,\n donate_argnums: Union[int, Iterable[int]] = ()) -> Callable:\n \"\"\"An internal implementation for `xla_computation` and `_cpp_jit`.\n\n See `xla_computation` for the full documentation.\n\n Args:\n tuple_args: By default (None), tupling will be enabled when there are more\n than 100 arguments, since some platforms have limits on argument arity.\n\n Returns:\n An `_XlaReturn` object.\n \"\"\"\n del instantiate_const_outputs # Unused\n\n _check_callable(fun)\n static_argnums = _ensure_tuple(static_argnums)\n donate_argnums = _ensure_tuple(donate_argnums)\n donate_argnums = rebase_donate_argnums(donate_argnums, static_argnums)\n\n fun_name = getattr(fun, \"__name__\", \"unknown\")\n\n\n def make_axis_env(nreps):\n if axis_env is None:\n return xla.AxisEnv(nreps, (), (), None)\n else:\n nreps = nreps * prod(size for name, size in axis_env)\n names, sizes = unzip2(axis_env)\n return xla.AxisEnv(nreps, names, sizes, None)\n\n def abstractify(x):\n return ShapedArray(np.shape(x), dtypes.result_type(x))\n\n @wraps(fun)\n @api_boundary\n def computation_maker(*args, **kwargs):\n if max(static_argnums + donate_argnums, default=-1) >= len(args):\n msg = (\"jitted function has static_argnums={}, donate_argnums={} but \"\n \"was called with only {} positional arguments.\")\n raise ValueError(msg.format(static_argnums, donate_argnums, len(args)))\n\n f = lu.wrap_init(fun)\n if static_argnums:\n dyn_argnums = [i for i in range(len(args)) if i not in static_argnums]\n f, dyn_args = argnums_partial(f, dyn_argnums, args)\n else:\n dyn_args = args\n args_flat, in_tree = tree_flatten((dyn_args, kwargs))\n if donate_argnums:\n donated_invars = donation_vector(donate_argnums, dyn_args, kwargs)\n else:\n donated_invars = (False,) * len(args_flat)\n\n if in_parts is None:\n in_parts_flat = None\n else:\n in_parts_flat = tuple(flatten_axes(\n \"xla_computation in_parts\", in_tree.children()[0], in_parts))\n jaxtree_fun, out_tree = flatten_fun(f, in_tree)\n avals = map(abstractify, args_flat)\n if config.omnistaging_enabled:\n with ExitStack() as stack:\n for axis_name, size in axis_env or []:\n stack.enter_context(core.extend_axis_env(axis_name, size, None))\n jaxpr, out_avals, consts = pe.trace_to_jaxpr_dynamic(jaxtree_fun, avals)\n else:\n pvals = [pe.PartialVal.unknown(aval) for aval in avals]\n jaxpr, out_pvals, consts = pe.trace_to_jaxpr(\n jaxtree_fun, pvals, instantiate=True, stage_out=True) # type: ignore\n out_avals = [raise_to_shaped(pval.get_aval()) for pval in out_pvals]\n jaxpr = xla.apply_outfeed_rewriter(jaxpr)\n axis_env_ = make_axis_env(xla.jaxpr_replicas(jaxpr))\n if out_parts is None:\n out_parts_flat = None\n else:\n out_parts_flat = tuple(flatten_axes(\n \"xla_computation out_parts\", out_tree(), out_parts))\n c = xb.make_computation_builder(\"xla_computation_{}\".format(fun_name))\n xla_consts = map(partial(xb.constant, c), consts)\n should_tuple = tuple_args if tuple_args is not None else (len(avals) > 100)\n xla_args, donated_invars = xla._xla_callable_args(\n c, avals, should_tuple, partitions=in_parts_flat, donated_invars=donated_invars)\n out_nodes = xla.jaxpr_subcomp(\n c, jaxpr, backend, axis_env_, xla_consts,\n extend_name_stack(wrap_name(fun_name, \"xla_computation\")), *xla_args)\n build_out_tuple = partial(xc.ops.Tuple, c, out_nodes)\n if out_parts is not None:\n out_tuple = xb.with_sharding(c, out_parts_flat, build_out_tuple)\n else:\n out_tuple = build_out_tuple()\n\n if any(donated_invars):\n donated_invars = xla.set_up_aliases(c, xla_args, out_tuple, donated_invars,\n tuple_args)\n if any(donated_invars):\n shapes = [str(c.GetShape(a)) for a, d in zip(xla_args, donated_invars) if d]\n warn(\"Some donated buffers were not usable: {}\".format(\", \".join(shapes)))\n built = c.build(out_tuple)\n out_shapes_flat = [ShapeDtypeStruct(a.shape, a.dtype) for a in out_avals]\n out_shape = tree_unflatten(out_tree(), out_shapes_flat)\n for out_aval in out_avals:\n if not isinstance(out_aval, xla.ShapedArray):\n raise RuntimeError(\"As we want to propagate the weak_type, we need \"\n \"to get a ShapedArray, otherwise this \"\n \"information is lost\")\n\n return _XlaReturn(\n built,\n out_shape,\n out_pytree_def=out_tree(),\n lazy_expressions=[xla.lazy.array(a.shape) for a in out_avals],\n shaped_arrays=out_avals,\n parameter_is_tupled_arguments=should_tuple)\n\n return computation_maker\n\ndef grad(fun: Callable, argnums: Union[int, Sequence[int]] = 0,\n has_aux: bool = False, holomorphic: bool = False,\n allow_int: bool = False) -> Callable:\n \"\"\"Creates a function which evaluates the gradient of ``fun``.\n\n Args:\n fun: Function to be differentiated. Its arguments at positions specified by\n ``argnums`` should be arrays, scalars, or standard Python containers.\n Argument arrays in the positions specified by ``argnums`` must be of\n inexact (i.e., floating-point or complex) type. It\n should return a scalar (which includes arrays with shape ``()`` but not\n arrays with shape ``(1,)`` etc.)\n argnums: Optional, integer or sequence of integers. Specifies which\n positional argument(s) to differentiate with respect to (default 0).\n has_aux: Optional, bool. Indicates whether ``fun`` returns a pair where the\n first element is considered the output of the mathematical function to be\n differentiated and the second element is auxiliary data. Default False.\n holomorphic: Optional, bool. Indicates whether ``fun`` is promised to be\n holomorphic. If True, inputs and outputs must be complex. Default False.\n allow_int: Optional, bool. Whether to allow differentiating with\n respect to integer valued inputs. The gradient of an integer input will\n have a trivial vector-space dtype (float0). Default False.\n\n Returns:\n A function with the same arguments as ``fun``, that evaluates the gradient\n of ``fun``. If ``argnums`` is an integer then the gradient has the same\n shape and type as the positional argument indicated by that integer. If\n argnums is a tuple of integers, the gradient is a tuple of values with the\n same shapes and types as the corresponding arguments. If ``has_aux`` is True\n then a pair of (gradient, auxiliary_data) is returned.\n\n For example:\n\n >>> import jax\n >>>\n >>> grad_tanh = jax.grad(jax.numpy.tanh)\n >>> print(grad_tanh(0.2))\n 0.961043\n \"\"\"\n value_and_grad_f = value_and_grad(fun, argnums, has_aux=has_aux,\n holomorphic=holomorphic,\n allow_int=allow_int)\n\n docstr = (\"Gradient of {fun} with respect to positional argument(s) \"\n \"{argnums}. Takes the same arguments as {fun} but returns the \"\n \"gradient, which has the same shape as the arguments at \"\n \"positions {argnums}.\")\n\n @wraps(fun, docstr=docstr, argnums=argnums)\n @api_boundary\n def grad_f(*args, **kwargs):\n _, g = value_and_grad_f(*args, **kwargs)\n return g\n\n @wraps(fun, docstr=docstr, argnums=argnums)\n @api_boundary\n def grad_f_aux(*args, **kwargs):\n (_, aux), g = value_and_grad_f(*args, **kwargs)\n return g, aux\n\n return grad_f_aux if has_aux else grad_f\n\ndef value_and_grad(fun: Callable, argnums: Union[int, Sequence[int]] = 0,\n has_aux: bool = False, holomorphic: bool = False,\n allow_int: bool = False) -> Callable[..., Tuple[Any, Any]]:\n \"\"\"Create a function which evaluates both ``fun`` and the gradient of ``fun``.\n\n Args:\n fun: Function to be differentiated. Its arguments at positions specified by\n ``argnums`` should be arrays, scalars, or standard Python containers. It\n should return a scalar (which includes arrays with shape ``()`` but not\n arrays with shape ``(1,)`` etc.)\n argnums: Optional, integer or sequence of integers. Specifies which\n positional argument(s) to differentiate with respect to (default 0).\n has_aux: Optional, bool. Indicates whether ``fun`` returns a pair where the\n first element is considered the output of the mathematical function to be\n differentiated and the second element is auxiliary data. Default False.\n holomorphic: Optional, bool. Indicates whether ``fun`` is promised to be\n holomorphic. If True, inputs and outputs must be complex. Default False.\n allow_int: Optional, bool. Whether to allow differentiating with\n respect to integer valued inputs. The gradient of an integer input will\n have a trivial vector-space dtype (float0). Default False.\n\n Returns:\n A function with the same arguments as ``fun`` that evaluates both ``fun``\n and the gradient of ``fun`` and returns them as a pair (a two-element\n tuple). If ``argnums`` is an integer then the gradient has the same shape\n and type as the positional argument indicated by that integer. If argnums is\n a sequence of integers, the gradient is a tuple of values with the same\n shapes and types as the corresponding arguments.\n \"\"\"\n\n docstr = (\"Value and gradient of {fun} with respect to positional \"\n \"argument(s) {argnums}. Takes the same arguments as {fun} but \"\n \"returns a two-element tuple where the first element is the value \"\n \"of {fun} and the second element is the gradient, which has the \"\n \"same shape as the arguments at positions {argnums}.\")\n\n _check_callable(fun)\n\n @wraps(fun, docstr=docstr, argnums=argnums)\n @api_boundary\n def value_and_grad_f(*args, **kwargs):\n max_argnum = argnums if type(argnums) is int else max(argnums)\n if max_argnum >= len(args):\n msg = (\"differentiating with respect to argnums={} requires at least \"\n \"{} positional arguments to be passed by the caller, but got only \"\n \"{} positional arguments.\")\n raise TypeError(msg.format(argnums, max_argnum + 1, len(args)))\n\n f = lu.wrap_init(fun, kwargs)\n f_partial, dyn_args = argnums_partial(f, argnums, args)\n tree_map(partial(_check_input_dtype_grad, holomorphic, allow_int), dyn_args)\n if not has_aux:\n ans, vjp_py = _vjp(f_partial, *dyn_args)\n else:\n ans, vjp_py, aux = _vjp(f_partial, *dyn_args, has_aux=True)\n _check_scalar(ans)\n dtype = dtypes.result_type(ans)\n tree_map(partial(_check_output_dtype_grad, holomorphic), ans)\n g = vjp_py(np.ones((), dtype=dtype))\n g = g[0] if isinstance(argnums, int) else g\n if not has_aux:\n return ans, g\n else:\n return (ans, aux), g\n\n return value_and_grad_f\n\ndef _check_scalar(x):\n msg = \"Gradient only defined for scalar-output functions. Output {}.\".format\n try:\n aval = core.get_aval(x)\n except TypeError as e:\n raise TypeError(msg(\"was {}\".format(x))) from e\n else:\n if isinstance(aval, ShapedArray):\n if aval.shape != ():\n raise TypeError(msg(\"had shape: {}\".format(aval.shape)))\n else:\n raise TypeError(msg(\"had abstract value {}\".format(aval)))\n\ndef _check_input_dtype_revderiv(name, holomorphic, allow_int, x):\n _check_arg(x)\n aval = core.get_aval(x)\n if holomorphic:\n if not dtypes.issubdtype(aval.dtype, np.complexfloating):\n msg = (f\"{name} with holomorphic=True requires inputs with complex dtype, \"\n f\"but got {aval.dtype.name}.\")\n raise TypeError(msg)\n elif not allow_int and not (dtypes.issubdtype(aval.dtype, np.floating) or\n dtypes.issubdtype(aval.dtype, np.complexfloating)):\n msg = (f\"{name} requires real- or complex-valued inputs (input dtype that \"\n \"is a sub-dtype of np.floating or np.complexfloating), \"\n f\"but got {aval.dtype.name}. If you want to use integer-valued \"\n \"inputs, use vjp or set allow_int to True.\")\n raise TypeError(msg)\n_check_input_dtype_grad = partial(_check_input_dtype_revderiv, \"grad\")\n\ndef _check_output_dtype_revderiv(name, holomorphic, x):\n aval = core.get_aval(x)\n if holomorphic:\n if not dtypes.issubdtype(aval.dtype, np.complexfloating):\n msg = (f\"{name} with holomorphic=True requires outputs with complex dtype, \"\n f\"but got {aval.dtype.name}.\")\n raise TypeError(msg)\n elif not dtypes.issubdtype(aval.dtype, np.floating):\n msg = (f\"{name} requires real-valued outputs (output dtype that is \"\n f\"a sub-dtype of np.floating), but got {aval.dtype.name}. \"\n \"For holomorphic differentiation, pass holomorphic=True. \"\n \"For differentiation of non-holomorphic functions involving complex \"\n \"outputs, or function with integer outputs, use jax.vjp directly.\")\n raise TypeError(msg)\n_check_output_dtype_grad = partial(_check_output_dtype_revderiv, \"grad\")\n\n\ndef jacfwd(fun: Callable, argnums: Union[int, Sequence[int]] = 0,\n holomorphic: bool = False) -> Callable:\n \"\"\"Jacobian of ``fun`` evaluated column-by-column using forward-mode AD.\n\n Args:\n fun: Function whose Jacobian is to be computed.\n argnums: Optional, integer or sequence of integers. Specifies which\n positional argument(s) to differentiate with respect to (default ``0``).\n holomorphic: Optional, bool. Indicates whether ``fun`` is promised to be\n holomorphic. Default False.\n\n Returns:\n A function with the same arguments as ``fun``, that evaluates the Jacobian of\n ``fun`` using forward-mode automatic differentiation.\n\n >>> import jax\n >>> import jax.numpy as jnp\n >>>\n >>> def f(x):\n ... return jnp.asarray(\n ... [x[0], 5*x[2], 4*x[1]**2 - 2*x[2], x[2] * jnp.sin(x[0])])\n ...\n >>> print(jax.jacfwd(f)(jnp.array([1., 2., 3.])))\n [[ 1. 0. 0. ]\n [ 0. 0. 5. ]\n [ 0. 16. -2. ]\n [ 1.6209 0. 0.84147]]\n \"\"\"\n _check_callable(fun)\n\n def jacfun(*args, **kwargs):\n f = lu.wrap_init(fun, kwargs)\n f_partial, dyn_args = argnums_partial(f, argnums, args)\n tree_map(partial(_check_input_dtype_jacfwd, holomorphic), dyn_args)\n pushfwd = partial(_jvp, f_partial, dyn_args)\n y, jac = vmap(pushfwd, out_axes=(None, -1))(_std_basis(dyn_args))\n tree_map(partial(_check_output_dtype_jacfwd, holomorphic), y)\n example_args = dyn_args[0] if isinstance(argnums, int) else dyn_args\n return tree_map(partial(_unravel_array_into_pytree, example_args, -1), jac)\n\n return jacfun\n\ndef _check_input_dtype_jacfwd(holomorphic, x):\n _check_arg(x)\n aval = core.get_aval(x)\n if holomorphic:\n if not (dtypes.issubdtype(aval.dtype, np.complexfloating) and\n not dtypes.issubdtype(aval.dtype, np.floating)):\n msg = (\"jacfwd with holomorphic=True requires inputs with complex dtype, \"\n f\"but got {aval.dtype.name}.\")\n raise TypeError(msg)\n elif not dtypes.issubdtype(aval.dtype, np.floating):\n msg = (\"jacfwd requires real-valued inputs (input dtype that is \"\n f\"a sub-dtype of np.floating), but got {aval.dtype.name}. \"\n \"For holomorphic differentiation, pass holomorphic=True. \"\n \"For differentiation of non-holomorphic functions involving complex \"\n \"inputs or integer inputs, use jax.jvp directly.\")\n raise TypeError(msg)\n\ndef _check_output_dtype_jacfwd(holomorphic, x):\n aval = core.get_aval(x)\n if holomorphic:\n if not dtypes.issubdtype(aval.dtype, np.complexfloating):\n msg = (\"jacfwd with holomorphic=True requires outputs with complex dtype, \"\n f\"but got {aval.dtype.name}.\")\n raise TypeError(msg)\n\n\ndef jacrev(fun: Callable, argnums: Union[int, Sequence[int]] = 0,\n holomorphic: bool = False, allow_int: bool = False) -> Callable:\n \"\"\"Jacobian of ``fun`` evaluated row-by-row using reverse-mode AD.\n\n Args:\n fun: Function whose Jacobian is to be computed.\n argnums: Optional, integer or sequence of integers. Specifies which\n positional argument(s) to differentiate with respect to (default ``0``).\n holomorphic: Optional, bool. Indicates whether ``fun`` is promised to be\n holomorphic. Default False.\n allow_int: Optional, bool. Whether to allow differentiating with\n respect to integer valued inputs. The gradient of an integer input will\n have a trivial vector-space dtype (float0). Default False.\n\n Returns:\n A function with the same arguments as ``fun``, that evaluates the Jacobian of\n ``fun`` using reverse-mode automatic differentiation.\n\n >>> import jax\n >>> import jax.numpy as jnp\n >>>\n >>> def f(x):\n ... return jnp.asarray(\n ... [x[0], 5*x[2], 4*x[1]**2 - 2*x[2], x[2] * jnp.sin(x[0])])\n ...\n >>> print(jax.jacrev(f)(jnp.array([1., 2., 3.])))\n [[ 1. 0. 0. ]\n [ 0. 0. 5. ]\n [ 0. 16. -2. ]\n [ 1.6209 0. 0.84147]]\n \"\"\"\n _check_callable(fun)\n\n def jacfun(*args, **kwargs):\n f = lu.wrap_init(fun, kwargs)\n f_partial, dyn_args = argnums_partial(f, argnums, args)\n tree_map(partial(_check_input_dtype_jacrev, holomorphic, allow_int), dyn_args)\n y, pullback = _vjp(f_partial, *dyn_args)\n tree_map(partial(_check_output_dtype_jacrev, holomorphic), y)\n jac = vmap(pullback)(_std_basis(y))\n jac = jac[0] if isinstance(argnums, int) else jac\n example_args = dyn_args[0] if isinstance(argnums, int) else dyn_args\n jac = tree_map(partial(_unravel_array_into_pytree, y, 0), jac)\n return tree_transpose(tree_structure(example_args), tree_structure(y), jac)\n\n return jacfun\njacobian = jacrev\n\n_check_input_dtype_jacrev = partial(_check_input_dtype_revderiv, \"jacrev\")\n_check_output_dtype_jacrev = partial(_check_output_dtype_revderiv, \"jacrev\")\n\n\ndef hessian(fun: Callable, argnums: Union[int, Sequence[int]] = 0,\n holomorphic: bool = False) -> Callable:\n \"\"\"Hessian of ``fun`` as a dense array.\n\n Args:\n fun: Function whose Hessian is to be computed. Its arguments at positions\n specified by ``argnums`` should be arrays, scalars, or standard Python\n containers thereof. It should return arrays, scalars, or standard Python\n containers thereof.\n argnums: Optional, integer or sequence of integers. Specifies which\n positional argument(s) to differentiate with respect to (default ``0``).\n holomorphic: Optional, bool. Indicates whether ``fun`` is promised to be\n holomorphic. Default False.\n\n Returns:\n A function with the same arguments as ``fun``, that evaluates the Hessian of\n ``fun``.\n\n >>> import jax\n >>>\n >>> g = lambda x: x[0]**3 - 2*x[0]*x[1] - x[1]**6\n >>> print(jax.hessian(g)(jax.numpy.array([1., 2.])))\n [[ 6. -2.]\n [ -2. -480.]]\n\n :py:func:`hessian` is a generalization of the usual definition of the Hessian\n that supports nested Python containers (i.e. pytrees) as inputs and outputs.\n The tree structure of ``jax.hessian(fun)(x)`` is given by forming a tree\n product of the structure of ``fun(x)`` with a tree product of two copies of\n the structure of ``x``. A tree product of two tree structures is formed by\n replacing each leaf of the first tree with a copy of the second. For example:\n\n >>> import jax.numpy as jnp\n >>> f = lambda dct: {\"c\": jnp.power(dct[\"a\"], dct[\"b\"])}\n >>> print(jax.hessian(f)({\"a\": jnp.arange(2.) + 1., \"b\": jnp.arange(2.) + 2.}))\n {'c': {'a': {'a': DeviceArray([[[ 2., 0.], [ 0., 0.]],\n [[ 0., 0.], [ 0., 12.]]], dtype=float32),\n 'b': DeviceArray([[[ 1. , 0. ], [ 0. , 0. ]],\n [[ 0. , 0. ], [ 0. , 12.317766]]], dtype=float32)},\n 'b': {'a': DeviceArray([[[ 1. , 0. ], [ 0. , 0. ]],\n [[ 0. , 0. ], [ 0. , 12.317766]]], dtype=float32),\n 'b': DeviceArray([[[0. , 0. ], [0. , 0. ]],\n [[0. , 0. ], [0. , 3.843624]]], dtype=float32)}}}\n\n Thus each leaf in the tree structure of ``jax.hessian(fun)(x)`` corresponds to\n a leaf of ``fun(x)`` and a pair of leaves of ``x``. For each leaf in\n ``jax.hessian(fun)(x)``, if the corresponding array leaf of ``fun(x)`` has\n shape ``(out_1, out_2, ...)`` and the corresponding array leaves of ``x`` have\n shape ``(in_1_1, in_1_2, ...)`` and ``(in_2_1, in_2_2, ...)`` respectively,\n then the Hessian leaf has shape ``(out_1, out_2, ..., in_1_1, in_1_2, ...,\n in_2_1, in_2_2, ...)``. In other words, the Python tree structure represents\n the block structure of the Hessian, with blocks determined by the input and\n output pytrees.\n\n In particular, an array is produced (with no pytrees involved) when the\n function input ``x`` and output ``fun(x)`` are each a single array, as in the\n ``g`` example above. If ``fun(x)`` has shape ``(out1, out2, ...)`` and ``x``\n has shape ``(in1, in2, ...)`` then ``jax.hessian(fun)(x)`` has shape\n ``(out1, out2, ..., in1, in2, ..., in1, in2, ...)``. To flatten pytrees into\n 1D vectors, consider using :py:func:`jax.flatten_util.flatten_pytree`.\n \"\"\"\n return jacfwd(jacrev(fun, argnums, holomorphic), argnums, holomorphic)\n\ndef _std_basis(pytree):\n leaves, _ = tree_flatten(pytree)\n ndim = sum(map(np.size, leaves))\n # TODO(mattjj): use a symbolic identity matrix here\n dtype = dtypes.result_type(*leaves)\n flat_basis = np.eye(ndim, dtype=dtype)\n return _unravel_array_into_pytree(pytree, 1, flat_basis)\n\ndef _unravel_array_into_pytree(pytree, axis, arr):\n leaves, treedef = tree_flatten(pytree)\n axis = axis % arr.ndim\n shapes = [arr.shape[:axis] + np.shape(l) + arr.shape[axis+1:] for l in leaves]\n parts = _split(arr, np.cumsum(map(np.size, leaves[:-1])), axis)\n reshaped_parts = [np.reshape(x, shape) for x, shape in zip(parts, shapes)]\n return tree_unflatten(treedef, reshaped_parts)\n\ndef _split(x, indices, axis):\n if isinstance(x, np.ndarray):\n return np.split(x, indices, axis)\n else:\n return x.split(indices, axis)\n\ndef _dtype(x):\n return dtypes.canonicalize_dtype(dtypes.result_type(x))\n\n\ndef vmap(fun: Callable[..., T], in_axes=0, out_axes=0, axis_name=None) -> Callable[..., T]:\n \"\"\"Vectorizing map. Creates a function which maps ``fun`` over argument axes.\n\n Args:\n fun: Function to be mapped over additional axes.\n in_axes: An integer, None, or (nested) standard Python container\n (tuple/list/dict) thereof specifying which input array axes to map over.\n\n If each positional argument to ``fun`` is an array, then ``in_axes`` can\n be an integer, a None, or a tuple of integers and Nones with\n length equal to the number of positional arguments to ``fun``.\n An integer or ``None`` indicates which array axis to map over for all\n arguments (with ``None`` indicating not to map any axis), and a tuple\n indicates which axis to map for each corresponding positional argument.\n Axis integers must be in the range ``[-ndim, ndim)`` for each array, where\n ``ndim`` is the number of dimensions of the corresponding input array.\n\n If the positional arguments to ``fun`` are container types, the\n corresponding element of ``in_axes`` can itself be a matching container,\n so that distinct array axes can be mapped for different container\n elements. ``in_axes`` must be a container tree prefix of the positional\n argument tuple passed to ``fun``.\n\n At least one positional argument must have ``in_axes`` not None. The sizes\n of the mapped input axes for all mapped positional arguments must all\n be equal.\n\n out_axes: An integer, None, or (nested) standard Python container\n (tuple/list/dict) thereof indicating where the mapped axis should appear\n in the output. All outputs with a mapped axis must have a non-None\n ``out_axes`` specification. Axis integers must be\n in the range ``[-ndim, ndim)`` for each output array, where ``ndim`` is\n the number of dimensions of the array returned by the :func:`vmap`-ed\n function, which is one more than the number of dimensions of the\n corresponding array returned by ``fun``.\n\n Returns:\n Batched/vectorized version of ``fun`` with arguments that correspond to\n those of ``fun``, but with extra array axes at positions indicated by\n ``in_axes``, and a return value that corresponds to that of ``fun``, but\n with extra array axes at positions indicated by ``out_axes``.\n\n For example, we can implement a matrix-matrix product using a vector dot\n product:\n\n >>> import jax.numpy as jnp\n >>>\n >>> vv = lambda x, y: jnp.vdot(x, y) # ([a], [a]) -> []\n >>> mv = vmap(vv, (0, None), 0) # ([b,a], [a]) -> [b] (b is the mapped axis)\n >>> mm = vmap(mv, (None, 1), 1) # ([b,a], [a,c]) -> [b,c] (c is the mapped axis)\n\n Here we use ``[a,b]`` to indicate an array with shape (a,b). Here are some\n variants:\n\n >>> mv1 = vmap(vv, (0, 0), 0) # ([b,a], [b,a]) -> [b] (b is the mapped axis)\n >>> mv2 = vmap(vv, (0, 1), 0) # ([b,a], [a,b]) -> [b] (b is the mapped axis)\n >>> mm2 = vmap(mv2, (1, 1), 0) # ([b,c,a], [a,c,b]) -> [c,b] (c is the mapped axis)\n\n Here's an example of using container types in ``in_axes`` to specify which\n axes of the container elements to map over:\n\n >>> A, B, C, D = 2, 3, 4, 5\n >>> x = jnp.ones((A, B))\n >>> y = jnp.ones((B, C))\n >>> z = jnp.ones((C, D))\n >>> def foo(tree_arg):\n ... x, (y, z) = tree_arg\n ... return jnp.dot(x, jnp.dot(y, z))\n >>> tree = (x, (y, z))\n >>> print(foo(tree))\n [[12. 12. 12. 12. 12.]\n [12. 12. 12. 12. 12.]]\n >>> from jax import vmap\n >>> K = 6 # batch size\n >>> x = jnp.ones((K, A, B)) # batch axis in different locations\n >>> y = jnp.ones((B, K, C))\n >>> z = jnp.ones((C, D, K))\n >>> tree = (x, (y, z))\n >>> vfoo = vmap(foo, in_axes=((0, (1, 2)),))\n >>> print(vfoo(tree).shape)\n (6, 2, 5)\n\n Here's another example using container types in ``in_axes``, this time a\n dictionary, to specify the elements of the container to map over:\n\n >>> dct = {'a': 0., 'b': jnp.arange(5.)}\n >>> x = 1.\n >>> def foo(dct, x):\n ... return dct['a'] + dct['b'] + x\n >>> out = vmap(foo, in_axes=({'a': None, 'b': 0}, None))(dct, x)\n >>> print(out)\n [1. 2. 3. 4. 5.]\n\n The results of a vectorized function can be mapped or unmapped.\n For example, the function below returns a pair with the first\n element mapped and the second unmapped. Only for unmapped results\n we can specify ``out_axes`` to be ``None`` (to keep it unmapped).\n\n >>> print(vmap(lambda x, y: (x + y, y * 2.), in_axes=(0, None), out_axes=(0, None))(jnp.arange(2.), 4.))\n (DeviceArray([4., 5.], dtype=float32), 8.0)\n\n If the ``out_axes`` is specified for an unmapped result, the result is broadcast\n across the mapped axis:\n\n >>> print(vmap(lambda x, y: (x + y, y * 2.), in_axes=(0, None), out_axes=0)(jnp.arange(2.), 4.))\n (DeviceArray([4., 5.], dtype=float32), DeviceArray([8., 8.], dtype=float32))\n\n If the ``out_axes`` is specified for a mapped result, the result is\n transposed accordingly.\n \"\"\"\n _check_callable(fun)\n docstr = (\"Vectorized version of {fun}. Takes similar arguments as {fun} \"\n \"but with additional array axes over which {fun} is mapped.\")\n if fun.__doc__:\n docstr += \"\\n\\nOriginal documentation:\\n\\n\"\n docstr += fun.__doc__\n\n axis_name = core._TempAxisName(fun) if axis_name is None else axis_name\n\n if isinstance(in_axes, list):\n # To be a tree prefix of the positional args tuple, in_axes can never be a\n # list: if in_axes is not a leaf, it must be a tuple of trees. However,\n # in cases like these users expect tuples and lists to be treated\n # essentially interchangeably, so we canonicalize lists to tuples here\n # rather than raising an error. https://github.com/google/jax/issues/2367\n in_axes = tuple(in_axes)\n\n in_axes_, out_axes_ = tree_leaves(in_axes), tree_leaves(out_axes)\n if not all(isinstance(l, (type(None), int)) for l in in_axes_):\n msg = (\"vmap in_axes must be an int, None, or (nested) container with \"\n \"those types as leaves, but got {}.\")\n raise TypeError(msg.format(in_axes))\n if not all(isinstance(l, (type(None), int)) for l in out_axes_):\n msg = (\"vmap out_axes must be an int, None, or (nested) container with \"\n \"those types as leaves, but got {}.\")\n raise TypeError(msg.format(out_axes))\n del in_axes_, out_axes_\n\n @wraps(fun, docstr=docstr)\n @api_boundary\n def batched_fun(*args):\n args_flat, in_tree = tree_flatten(args)\n f = lu.wrap_init(fun)\n flat_fun, out_tree = flatten_fun_nokwargs(f, in_tree)\n in_axes_flat = flatten_axes(\"vmap in_axes\", in_tree, in_axes)\n _ = _mapped_axis_size(in_tree, args_flat, in_axes_flat, \"vmap\")\n out_flat = batching.batch(flat_fun, args_flat, in_axes_flat,\n lambda: flatten_axes(\"vmap out_axes\", out_tree(),\n out_axes),\n axis_name=axis_name)\n return tree_unflatten(out_tree(), out_flat)\n\n return batched_fun\n\ndef _mapped_axis_size(tree, vals, dims, name):\n def _get_axis_size(name: str, i:int, shape: Tuple[int, ...], axis: int):\n try:\n return shape[axis]\n except (IndexError, TypeError) as e:\n ranks = tree_unflatten(tree, [np.ndim(x) for x, d in zip(vals, dims)])\n raise ValueError(f\"{name} got arg {i} of rank {len(shape)} but axis to be mapped {axis}. \"\n f\"The tree of ranks is:\\n{ranks}\") from e\n\n mapped_axis_sizes = {_get_axis_size(name, i, np.shape(x), d)\n for i, (x, d) in enumerate(zip(vals, dims))\n if d is not None}\n try:\n size, = mapped_axis_sizes\n return size\n except ValueError as e:\n if not mapped_axis_sizes:\n raise ValueError(f\"{name} must have at least one non-None value in in_axes\") from e\n msg = \"{} got inconsistent sizes for array axes to be mapped:\\n\".format(name) + \"{}\"\n # we switch the error message based on whether args is a tuple of arrays,\n # in which case we can produce an error message based on argument indices,\n # or if it has nested containers.\n # TODO(mattjj,phawkins): add a way to inspect pytree kind more directly\n if tree == tree_flatten((core.unit,) * tree.num_leaves)[1]:\n lines1 = [\"arg {} has shape {} and axis {} is to be mapped\"\n .format(i, np.shape(x), d) for i, (x, d) in enumerate(zip(vals, dims))]\n sizes = collections.defaultdict(list)\n for i, (x, d) in enumerate(zip(vals, dims)):\n if d is not None:\n sizes[x.shape[d]].append(i)\n lines2 = [\"{} {} {} {} to be mapped of size {}\".format(\n \"args\" if len(idxs) > 1 else \"arg\",\n \", \".join(map(str, idxs)),\n \"have\" if len(idxs) > 1 else \"has\",\n \"axes\" if len(idxs) > 1 else \"an axis\",\n size)\n for size, idxs in sizes.items()]\n raise ValueError(msg.format(\"\\n\".join(lines1 + [\"so\"] + lines2))) from None\n else:\n sizes = [x.shape[d] if d is not None else None for x, d in zip(vals, dims)]\n sizes = tree_unflatten(tree, sizes)\n raise ValueError(msg.format(\"the tree of axis sizes is:\\n{}\".format(sizes))) from None\n\ndef pmap(fun: Callable[..., T],\n axis_name: Optional[AxisName] = None, *, in_axes=0,\n static_broadcasted_argnums: Union[int, Iterable[int]] = (),\n devices=None, backend: Optional[str] = None,\n axis_size: Optional[int] = None,\n donate_argnums: Union[int, Iterable[int]] = ()) -> Callable[..., T]:\n \"\"\"Parallel map with support for collective operations.\n\n The purpose of :py:func:`pmap` is to express single-program multiple-data (SPMD)\n programs. Applying :py:func:`pmap` to a function will compile the function with XLA\n (similarly to :py:func:`jit`), then execute it in parallel on XLA devices, such as\n multiple GPUs or multiple TPU cores. Semantically it is comparable to\n :py:func:`vmap` because both transformations map a function over array axes, but\n where :py:func:`vmap` vectorizes functions by pushing the mapped axis down into\n primitive operations, :py:func:`pmap` instead replicates the function and executes\n each replica on its own XLA device in parallel.\n\n Another key difference with :py:func:`vmap` is that while :py:func:`vmap` can only express\n pure maps, :py:func:`pmap` enables the use of parallel SPMD collective operations,\n like all-reduce sum.\n\n The mapped axis size must be less than or equal to the number of local XLA\n devices available, as returned by :py:func:`jax.local_device_count()` (unless\n ``devices`` is specified, see below). For nested :py:func:`pmap` calls, the product\n of the mapped axis sizes must be less than or equal to the number of XLA\n devices.\n\n .. note::\n :py:func:`pmap` compiles ``fun``, so while it can be combined with\n :py:func:`jit`, it's usually unnecessary.\n\n **Multi-host platforms:** On multi-host platforms such as TPU pods, :py:func:`pmap`\n is designed to be used in SPMD Python programs, where every host is running\n the same Python code such that all hosts run the same pmapped function in the\n same order. Each host should still call the pmapped function with mapped axis\n size equal to the number of *local* devices (unless ``devices`` is specified,\n see below), and an array of the same leading axis size will be returned as\n usual. However, any collective operations in ``fun`` will be computed over\n *all* participating devices, including those on other hosts, via\n device-to-device communication. Conceptually, this can be thought of as\n running a pmap over a single array sharded across hosts, where each host\n \"sees\" only its local shard of the input and output. The SPMD model requires\n that the same multi-host pmaps must be run in the same order on all devices,\n but they can be interspersed with arbitrary operations running on a single\n host.\n\n Args:\n fun: Function to be mapped over argument axes. Its arguments and return\n value should be arrays, scalars, or (nested) standard Python containers\n (tuple/list/dict) thereof. Positional arguments indicated by\n ``static_broadcasted_argnums`` can be anything at all, provided they are\n hashable and have an equality operation defined.\n axis_name: Optional, a hashable Python object used to identify the mapped\n axis so that parallel collectives can be applied.\n in_axes: A non-negative integer, None, or nested Python container thereof\n that specifies which axes in the input to map over (see :py:func:`vmap`).\n Currently, only 0 and None are supported axes for pmap.\n static_broadcasted_argnums: An int or collection of ints specifying which\n positional arguments to treat as static (compile-time constant).\n Operations that only depend on static arguments will be constant-folded.\n Calling the pmapped function with different values for these constants will\n trigger recompilation. If the pmapped function is called with fewer\n positional arguments than indicated by ``static_argnums`` then an error is\n raised. Each of the static arguments will be broadcasted to all devices.\n Arguments that are not arrays or containers thereof must be marked as\n static. Defaults to ().\n devices: This is an experimental feature and the API is likely to change.\n Optional, a sequence of Devices to map over. (Available devices can be\n retrieved via jax.devices()). If specified, the size of the mapped axis\n must be equal to the number of local devices in the sequence. Nested\n :py:func:`pmap` s with ``devices`` specified in either the inner or outer :py:func:`pmap`\n are not yet supported.\n backend: This is an experimental feature and the API is likely to change.\n Optional, a string representing the XLA backend. 'cpu', 'gpu', or 'tpu'.\n axis_size: Optional; the size of the mapped axis.\n donate_argnums: Specify which arguments are \"donated\" to the computation.\n It is safe to donate arguments if you no longer need them once the\n computation has finished. In some cases XLA can make use of donated\n buffers to reduce the amount of memory needed to perform a computation,\n for example recycling one of your input buffers to store a result. You\n should not re-use buffers that you donate to a computation, JAX will raise\n an error if you try to.\n\n Returns:\n A parallelized version of ``fun`` with arguments that correspond to those of\n ``fun`` but with extra array axes at positions indicated by ``in_axes``\n and with output that has an additional leading array axis (with the same\n size).\n\n For example, assuming 8 XLA devices are available, :py:func:`pmap` can be used as a\n map along a leading array axis:\n\n >>> import jax.numpy as jnp\n >>>\n >>> out = pmap(lambda x: x ** 2)(jnp.arange(8)) # doctest: +SKIP\n >>> print(out) # doctest: +SKIP\n [0, 1, 4, 9, 16, 25, 36, 49]\n\n When the leading dimension is smaller than the number of available devices JAX\n will simply run on a subset of devices:\n\n >>> x = jnp.arange(3 * 2 * 2.).reshape((3, 2, 2))\n >>> y = jnp.arange(3 * 2 * 2.).reshape((3, 2, 2)) ** 2\n >>> out = pmap(jnp.dot)(x, y) # doctest: +SKIP\n >>> print(out) # doctest: +SKIP\n [[[ 4. 9.]\n [ 12. 29.]]\n [[ 244. 345.]\n [ 348. 493.]]\n [[ 1412. 1737.]\n [ 1740. 2141.]]]\n\n If your leading dimension is larger than the number of available devices you\n will get an error:\n\n >>> pmap(lambda x: x ** 2)(jnp.arange(9)) # doctest: +SKIP\n ValueError: ... requires 9 replicas, but only 8 XLA devices are available\n\n As with :py:func:`vmap`, using ``None`` in ``in_axes`` indicates that an argument\n doesn't have an extra axis and should be broadcasted, rather than mapped,\n across the replicas:\n\n >>> x, y = jnp.arange(2.), 4.\n >>> out = pmap(lambda x, y: (x + y, y * 2.), in_axes=(0, None))(x, y) # doctest: +SKIP\n >>> print(out) # doctest: +SKIP\n ([4., 5.], [8., 8.])\n\n Note that :py:func:`pmap` always returns values mapped over their leading axis,\n equivalent to using ``out_axes=0`` in :py:func:`vmap`.\n\n In addition to expressing pure maps, :py:func:`pmap` can also be used to express\n parallel single-program multiple-data (SPMD) programs that communicate via\n collective operations. For example:\n\n >>> f = lambda x: x / jax.lax.psum(x, axis_name='i')\n >>> out = pmap(f, axis_name='i')(jnp.arange(4.)) # doctest: +SKIP\n >>> print(out) # doctest: +SKIP\n [ 0. 0.16666667 0.33333334 0.5 ]\n >>> print(out.sum()) # doctest: +SKIP\n 1.0\n\n In this example, ``axis_name`` is a string, but it can be any Python object\n with ``__hash__`` and ``__eq__`` defined.\n\n The argument ``axis_name`` to :py:func:`pmap` names the mapped axis so that\n collective operations, like :func:`jax.lax.psum`, can refer to it. Axis names\n are important particularly in the case of nested :py:func:`pmap` functions,\n where collective operations can operate over distinct axes:\n\n >>> from functools import partial\n >>> import jax\n >>>\n >>> @partial(pmap, axis_name='rows')\n ... @partial(pmap, axis_name='cols')\n ... def normalize(x):\n ... row_normed = x / jax.lax.psum(x, 'rows')\n ... col_normed = x / jax.lax.psum(x, 'cols')\n ... doubly_normed = x / jax.lax.psum(x, ('rows', 'cols'))\n ... return row_normed, col_normed, doubly_normed\n >>>\n >>> x = jnp.arange(8.).reshape((4, 2))\n >>> row_normed, col_normed, doubly_normed = normalize(x) # doctest: +SKIP\n >>> print(row_normed.sum(0)) # doctest: +SKIP\n [ 1. 1.]\n >>> print(col_normed.sum(1)) # doctest: +SKIP\n [ 1. 1. 1. 1.]\n >>> print(doubly_normed.sum((0, 1))) # doctest: +SKIP\n 1.0\n\n On multi-host platforms, collective operations operate over all devices,\n including those on other hosts. For example, assuming the following code runs\n on two hosts with 4 XLA devices each:\n\n >>> f = lambda x: x + jax.lax.psum(x, axis_name='i')\n >>> data = jnp.arange(4) if jax.host_id() == 0 else jnp.arange(4,8)\n >>> out = pmap(f, axis_name='i')(data) # doctest: +SKIP\n >>> print(out) # doctest: +SKIP\n [28 29 30 31] # on host 0\n [32 33 34 35] # on host 1\n\n Each host passes in a different length-4 array, corresponding to its 4 local\n devices, and the psum operates over all 8 values. Conceptually, the two\n length-4 arrays can be thought of as a sharded length-8 array (in this example\n equivalent to jnp.arange(8)) that is mapped over, with the length-8 mapped axis\n given name 'i'. The pmap call on each host then returns the corresponding\n length-4 output shard.\n\n The ``devices`` argument can be used to specify exactly which devices are used\n to run the parallel computation. For example, again assuming a single host\n with 8 devices, the following code defines two parallel computations, one\n which runs on the first six devices and one on the remaining two:\n\n >>> from functools import partial\n >>> @partial(pmap, axis_name='i', devices=jax.devices()[:6])\n ... def f1(x):\n ... return x / jax.lax.psum(x, axis_name='i')\n >>>\n >>> @partial(pmap, axis_name='i', devices=jax.devices()[-2:])\n ... def f2(x):\n ... return jax.lax.psum(x ** 2, axis_name='i')\n >>>\n >>> print(f1(jnp.arange(6.))) # doctest: +SKIP\n [0. 0.06666667 0.13333333 0.2 0.26666667 0.33333333]\n >>> print(f2(jnp.array([2., 3.]))) # doctest: +SKIP\n [ 13. 13.]\n \"\"\"\n # axis_size is an optional integer representing the global axis size.\n # The aggregate size (across all hosts) size of the mapped axis must match\n # the given value.\n\n _check_callable(fun)\n axis_name = core._TempAxisName(fun) if axis_name is None else axis_name\n static_broadcasted_tuple = _ensure_tuple(static_broadcasted_argnums)\n donate_tuple = rebase_donate_argnums(_ensure_tuple(donate_argnums),\n static_broadcasted_tuple)\n\n if any(axis != 0 for axis in tree_leaves(in_axes)):\n raise ValueError(f\"pmap in_axes leaves must be 0 or None, got {in_axes}\")\n\n @wraps(fun)\n @api_boundary\n def f_pmapped(*args, **kwargs):\n f = lu.wrap_init(fun)\n if static_broadcasted_tuple:\n if max(static_broadcasted_tuple) >= len(args):\n msg = (\"pmapped function has static_broadcasted_argnums={} but was \"\n \"called with only {} positional argument{}. All static \"\n \"broadcasted arguments must be passed positionally.\")\n raise ValueError(msg.format(static_broadcasted_tuple, len(args),\n \"s\" if len(args) > 1 else \"\"))\n dyn_argnums = [i for i in range(len(args))\n if i not in static_broadcasted_tuple]\n f, dyn_args = argnums_partial(f, dyn_argnums, args)\n if isinstance(in_axes, tuple):\n dyn_in_axes = tuple(in_axes[i] for i in dyn_argnums)\n else:\n dyn_in_axes = in_axes\n else:\n dyn_args, dyn_in_axes = args, in_axes\n args, in_tree = tree_flatten((dyn_args, kwargs))\n if donate_tuple:\n donated_invars = donation_vector(donate_tuple, dyn_args, kwargs)\n else:\n donated_invars = (False,) * len(args)\n in_axes_flat = flatten_axes(\"pmap in_axes\", in_tree, (dyn_in_axes, 0))\n local_axis_size = _mapped_axis_size(in_tree, args, in_axes_flat, \"pmap\")\n for arg in args: _check_arg(arg)\n flat_fun, out_tree = flatten_fun(f, in_tree)\n out = pxla.xla_pmap(\n flat_fun, *args, backend=backend, axis_name=axis_name,\n axis_size=local_axis_size, global_axis_size=axis_size,\n devices=None if devices is None else tuple(devices),\n mapped_invars=tuple(axis is not None for axis in in_axes_flat),\n name=flat_fun.__name__, donated_invars=tuple(donated_invars))\n return tree_unflatten(out_tree(), out)\n\n return f_pmapped\n\n\ndef soft_pmap(fun: Callable, axis_name: Optional[AxisName] = None, in_axes=0\n ) -> Callable:\n if not config.omnistaging_enabled:\n raise NotImplementedError(\"soft_pmap requires omnistaging.\")\n warn(\"soft_pmap is an experimental feature and probably has bugs!\")\n _check_callable(fun)\n axis_name = core._TempAxisName(fun) if axis_name is None else axis_name\n\n if any(axis != 0 for axis in tree_leaves(in_axes)):\n raise ValueError(f\"soft_pmap in_axes leaves must be 0 or None, got {in_axes}\")\n\n @wraps(fun)\n @api_boundary\n def f_pmapped(*args, **kwargs):\n f = lu.wrap_init(fun)\n args_flat, in_tree = tree_flatten((args, kwargs))\n in_axes_flat = flatten_axes(\"soft_pmap in_axes\", in_tree, (in_axes, 0))\n mapped_invars = tuple(axis is not None for axis in in_axes_flat)\n axis_size = _mapped_axis_size(in_tree, args_flat, in_axes_flat, \"soft_pmap\")\n for arg in args_flat: _check_arg(arg)\n flat_fun, out_tree = flatten_fun(f, in_tree)\n outs = pxla.soft_pmap(flat_fun, *args_flat, axis_name=axis_name,\n axis_size=axis_size, mapped_invars=mapped_invars)\n return tree_unflatten(out_tree(), outs)\n return f_pmapped\n\n\ndef mask(fun: Callable, in_shapes, out_shape=None) -> Callable:\n _check_callable(fun)\n unique_ids = masking.UniqueIds()\n\n in_specs, in_shapes_tree = tree_flatten(in_shapes)\n in_specs = map(masking.parse_spec, in_specs)\n in_specs = map(partial(masking.remap_ids, unique_ids), in_specs)\n\n if out_shape is not None:\n out_specs, out_spec_tree = tree_flatten(out_shape)\n out_specs = map(masking.parse_spec, out_specs)\n out_specs = map(partial(masking.remap_ids, unique_ids), out_specs)\n\n def wrapped_fun(args, logical_env):\n args_flat, in_tree = tree_flatten(args)\n if in_tree != in_shapes_tree:\n raise TypeError(f\"Tree mismatch: Input {in_tree} and shape spec {in_shapes_tree}.\")\n logical_env = {unique_ids[name] : val for name, val in logical_env.items()}\n in_shapes = map(masking.finalize_spec, in_specs, map(np.shape, args_flat))\n padded_env = masking.bind_shapes(in_shapes, [x.shape for x in args_flat])\n f = lu.wrap_init(fun)\n flat_fun, out_tree_thunk = flatten_fun_nokwargs(f, in_tree)\n outs, out_shapes = masking.mask_fun(\n flat_fun, logical_env, padded_env, args_flat, in_shapes)\n out_tree = out_tree_thunk()\n\n if out_shape is None:\n def logical_shape(poly_shape, padded_val):\n shape = masking.eval_poly_shape(poly_shape, logical_env)\n return ShapeDtypeStruct(shape, core.get_aval(padded_val).dtype)\n out_logicals = map(logical_shape, out_shapes, outs)\n return tree_unflatten(out_tree, outs), tree_unflatten(out_tree, out_logicals)\n else:\n masking.check_shapes(out_specs, out_spec_tree, list(out_shapes), out_tree)\n def padded_spec(shape_spec):\n return tuple(dim if dim is masking._monomorphic_dim else\n masking.eval_poly(dim, padded_env) for dim in shape_spec)\n masking.check_shapes(map(padded_spec, out_specs), out_spec_tree,\n map(np.shape, outs), out_tree, \"Padded output\")\n return tree_unflatten(out_tree, outs)\n return wrapped_fun\n\n@curry\ndef shapecheck(in_shapes, out_shape, fun: Callable):\n _check_callable(fun)\n in_shapes, in_tree = tree_flatten(in_shapes)\n in_shapes = map(masking.parse_spec, in_shapes)\n out_specs, out_spec_tree = tree_flatten(out_shape)\n out_specs = map(masking.parse_spec, out_specs)\n flat_fun, out_tree_thunk = flatten_fun_nokwargs(lu.wrap_init(fun), in_tree)\n avals = map(partial(ShapedArray, dtype=np.float32), in_shapes)\n out_shapes = [o.shape for o in pe.abstract_eval_fun(flat_fun.call_wrapped, *avals)]\n masking.check_shapes(map(tuple, out_specs), out_spec_tree,\n map(tuple, out_shapes), out_tree_thunk())\n return fun\n\ndef jvp(fun: Callable, primals, tangents) -> Tuple[Any, Any]:\n \"\"\"Computes a (forward-mode) Jacobian-vector product of ``fun``.\n\n Args:\n fun: Function to be differentiated. Its arguments should be arrays, scalars,\n or standard Python containers of arrays or scalars. It should return an\n array, scalar, or standard Python container of arrays or scalars.\n primals: The primal values at which the Jacobian of ``fun`` should be\n evaluated. Should be either a tuple or a list of arguments,\n and its length should equal to the number of positional parameters of\n ``fun``.\n tangents: The tangent vector for which the Jacobian-vector product should be\n evaluated. Should be either a tuple or a list of tangents, with the same\n tree structure and array shapes as ``primals``.\n\n Returns:\n A ``(primals_out, tangents_out)`` pair, where ``primals_out`` is\n ``fun(*primals)``, and ``tangents_out`` is the Jacobian-vector product of\n ``function`` evaluated at ``primals`` with ``tangents``. The\n ``tangents_out`` value has the same Python tree structure and shapes as\n ``primals_out``.\n\n For example:\n\n >>> import jax\n >>>\n >>> y, v = jax.jvp(jax.numpy.sin, (0.1,), (0.2,))\n >>> print(y)\n 0.09983342\n >>> print(v)\n 0.19900084\n \"\"\"\n _check_callable(fun)\n return _jvp(lu.wrap_init(fun), primals, tangents)\n\ndef _jvp(fun: lu.WrappedFun, primals, tangents):\n \"\"\"Variant of jvp() that takes an lu.WrappedFun.\"\"\"\n if (not isinstance(primals, (tuple, list)) or\n not isinstance(tangents, (tuple, list))):\n msg = (\"primal and tangent arguments to jax.jvp must be tuples or lists; \"\n \"found {} and {}.\")\n raise TypeError(msg.format(type(primals).__name__, type(tangents).__name__))\n\n ps_flat, tree_def = tree_flatten(primals)\n ts_flat, tree_def_2 = tree_flatten(tangents)\n if tree_def != tree_def_2:\n msg = (\"primal and tangent arguments to jax.jvp must have the same tree \"\n \"structure; primals have tree structure {} whereas tangents have \"\n \"tree structure {}\")\n raise TypeError(msg.format(tree_def, tree_def_2))\n for p, t in safe_zip(ps_flat, ts_flat):\n if core.primal_dtype_to_tangent_dtype(_dtype(p)) != _dtype(t):\n msg = (\"primal and tangent arguments to jax.jvp do not match; \"\n \"dtypes must be equal, or in case of int/bool primal dtype \"\n \"the tangent dtype must be float0.\"\n f\"Got primal dtype {_dtype(p)} and so expected tangent dtype \"\n f\"{core.primal_dtype_to_tangent_dtype(_dtype(p))}, but got \"\n f\"tangent dtype {_dtype(t)} instead.\")\n raise TypeError(msg)\n flat_fun, out_tree = flatten_fun_nokwargs(fun, tree_def)\n out_primals, out_tangents = ad.jvp(flat_fun).call_wrapped(ps_flat, ts_flat)\n return (tree_unflatten(out_tree(), out_primals),\n tree_unflatten(out_tree(), out_tangents))\n\ndef linearize(fun: Callable, *primals) -> Tuple[Any, Callable]:\n \"\"\"Produces a linear approximation to ``fun`` using :py:func:`jvp` and partial eval.\n\n Args:\n fun: Function to be differentiated. Its arguments should be arrays, scalars,\n or standard Python containers of arrays or scalars. It should return an\n array, scalar, or standard python container of arrays or scalars.\n primals: The primal values at which the Jacobian of ``fun`` should be\n evaluated. Should be a tuple of arrays, scalar, or standard Python\n container thereof. The length of the tuple is equal to the number of\n positional parameters of ``fun``.\n\n Returns:\n A pair where the first element is the value of ``f(*primals)`` and the\n second element is a function that evaluates the (forward-mode)\n Jacobian-vector product of ``fun`` evaluated at ``primals`` without re-doing\n the linearization work.\n\n In terms of values computed, :py:func:`linearize` behaves much like a curried\n :py:func:`jvp`, where these two code blocks compute the same values::\n\n y, out_tangent = jax.jvp(f, (x,), (in_tangent,))\n\n y, f_jvp = jax.linearize(f, x)\n out_tangent = f_jvp(in_tangent)\n\n However, the difference is that :py:func:`linearize` uses partial evaluation\n so that the function ``f`` is not re-linearized on calls to ``f_jvp``. In\n general that means the memory usage scales with the size of the computation,\n much like in reverse-mode. (Indeed, :py:func:`linearize` has a similar\n signature to :py:func:`vjp`!)\n\n This function is mainly useful if you want to apply ``f_jvp`` multiple times,\n i.e. to evaluate a pushforward for many different input tangent vectors at the\n same linearization point. Moreover if all the input tangent vectors are known\n at once, it can be more efficient to vectorize using :py:func:`vmap`, as in::\n\n pushfwd = partial(jvp, f, (x,))\n y, out_tangents = vmap(pushfwd, out_axes=(None, 0))((in_tangents,))\n\n By using :py:func:`vmap` and :py:func:`jvp` together like this we avoid the stored-linearization\n memory cost that scales with the depth of the computation, which is incurred\n by both :py:func:`linearize` and :py:func:`vjp`.\n\n Here's a more complete example of using :py:func:`linearize`:\n\n >>> import jax\n >>> import jax.numpy as jnp\n >>>\n >>> def f(x): return 3. * jnp.sin(x) + jnp.cos(x / 2.)\n ...\n >>> jax.jvp(f, (2.,), (3.,))\n (DeviceArray(3.26819, dtype=float32), DeviceArray(-5.00753, dtype=float32))\n >>> y, f_jvp = jax.linearize(f, 2.)\n >>> print(y)\n 3.2681944\n >>> print(f_jvp(3.))\n -5.007528\n >>> print(f_jvp(4.))\n -6.676704\n \"\"\"\n _check_callable(fun)\n f = lu.wrap_init(fun)\n primals_flat, in_tree = tree_flatten((primals, {}))\n jaxtree_fun, out_tree = flatten_fun(f, in_tree)\n out_primals, out_pvals, jaxpr, consts = ad.linearize(jaxtree_fun, *primals_flat)\n out_tree = out_tree()\n out_primal_py = tree_unflatten(out_tree, out_primals)\n primal_avals = list(map(core.get_aval, primals_flat))\n lifted_jvp = partial(_lift_linearized, jaxpr, primal_avals, consts,\n (in_tree, out_tree), out_pvals)\n return out_primal_py, lifted_jvp\n\ndef _lift_linearized(jaxpr, primal_avals, consts, io_tree, out_pvals, *py_args):\n def fun(*tangents):\n tangent_avals = list(map(core.get_aval, tangents))\n for primal_aval, tangent_aval in zip(primal_avals, tangent_avals):\n try:\n core.lattice_join(primal_aval.at_least_vspace(), tangent_aval)\n except TypeError as e:\n msg = (\"linearized function called on tangent values inconsistent with \"\n \"the original primal values: \"\n f\"got {tangent_aval} for primal aval {primal_aval}\")\n raise ValueError(msg)\n tangents_out = eval_jaxpr(jaxpr, consts, *tangents)\n return tuple(map(lambda out_pv, tan_out: out_pv.merge_with_known(tan_out),\n out_pvals, tangents_out))\n\n return apply_flat_fun(fun, io_tree, *py_args)\n\ndef _vjp_pullback_wrapper(cotangent_dtypes, io_tree, fun, py_args):\n in_tree_expected, out_tree = io_tree\n args, in_tree = tree_flatten(py_args)\n if in_tree != in_tree_expected:\n msg = (\"Tree structure of cotangent input {}, does not match structure of \"\n \"primal output {}\")\n raise TypeError(msg.format(in_tree, in_tree_expected))\n for arg, ct_dtype in safe_zip(args, cotangent_dtypes):\n expected_tangent_dtype = core.primal_dtype_to_tangent_dtype(_dtype(arg))\n if expected_tangent_dtype != ct_dtype:\n msg = (\"Type of cotangent input to vjp pullback function ({}) is not \"\n \"the expected tangent type ({}) of corresponding primal output \"\n \"with dtype {}.\")\n raise TypeError(msg.format(ct_dtype, expected_tangent_dtype, _dtype(arg)))\n ans = fun(*args)\n return tree_unflatten(out_tree, ans)\n\n\ndef vjp(\n fun: Callable, *primals, has_aux: bool = False,\n) -> Union[Tuple[Any, Callable], Tuple[Any, Callable, Any]]:\n \"\"\"Compute a (reverse-mode) vector-Jacobian product of ``fun``.\n\n :py:func:`grad` is implemented as a special case of :py:func:`vjp`.\n\n Args:\n fun: Function to be differentiated. Its arguments should be arrays, scalars,\n or standard Python containers of arrays or scalars. It should return an\n array, scalar, or standard Python container of arrays or scalars.\n primals: A sequence of primal values at which the Jacobian of ``fun``\n should be evaluated. The length of ``primals`` should be equal to the\n number of positional parameters to ``fun``. Each primal value should be a\n tuple of arrays, scalar, or standard Python containers thereof.\n has_aux: Optional, bool. Indicates whether ``fun`` returns a pair where the\n first element is considered the output of the mathematical function to be\n differentiated and the second element is auxiliary data. Default False.\n\n Returns:\n If ``has_aux`` is ``False``, returns a ``(primals_out, vjpfun)`` pair, where\n ``primals_out`` is ``fun(*primals)``.\n ``vjpfun`` is a function from a cotangent vector with the same shape as\n ``primals_out`` to a tuple of cotangent vectors with the same shape as\n ``primals``, representing the vector-Jacobian product of ``fun`` evaluated at\n ``primals``. If ``has_aux`` is ``True``, returns a\n ``(primals_out, vjpfun, aux)`` tuple where ``aux`` is the auxiliary data\n returned by ``fun``.\n\n >>> import jax\n >>>\n >>> def f(x, y):\n ... return jax.numpy.sin(x), jax.numpy.cos(y)\n ...\n >>> primals, f_vjp = jax.vjp(f, 0.5, 1.0)\n >>> xbar, ybar = f_vjp((-0.7, 0.3))\n >>> print(xbar)\n -0.61430776\n >>> print(ybar)\n -0.2524413\n \"\"\"\n _check_callable(fun)\n return _vjp(lu.wrap_init(fun), *primals, has_aux=has_aux)\n\ndef _vjp(fun: lu.WrappedFun, *primals, has_aux=False):\n \"\"\"Variant of vjp() that takes an lu.WrappedFun.\"\"\"\n primals_flat, in_tree = tree_flatten(primals)\n for arg in primals_flat: _check_arg(arg)\n if not has_aux:\n flat_fun, out_tree = flatten_fun_nokwargs(fun, in_tree)\n out_primal, out_vjp = ad.vjp(flat_fun, primals_flat)\n out_tree = out_tree()\n else:\n flat_fun, out_aux_trees = flatten_fun_nokwargs2(fun, in_tree)\n out_primal, out_vjp, aux = ad.vjp(flat_fun, primals_flat, has_aux=True)\n out_tree, aux_tree = out_aux_trees()\n out_primal_py = tree_unflatten(out_tree, out_primal)\n ct_dtypes = [core.primal_dtype_to_tangent_dtype(_dtype(x)) for x in out_primal]\n # Ensure that vjp_py is a PyTree so that we can pass it from the forward to the\n # backward pass in a custom VJP.\n vjp_py = Partial(partial(_vjp_pullback_wrapper,\n ct_dtypes,\n (out_tree, in_tree)),\n out_vjp)\n if not has_aux:\n return out_primal_py, vjp_py\n else:\n return out_primal_py, vjp_py, tree_unflatten(aux_tree, aux)\n\n\ndef linear_transpose(fun: Callable, *primals) -> Callable:\n \"\"\"Transpose a function that is promised to be linear.\n\n For linear functions, this transformation is equivalent to ``vjp``, but\n avoids the overhead of computing the forward pass.\n\n The outputs of the transposed function will always have the exact same dtypes\n as ``primals``, even if some values are truncated (e.g., from complex to\n float, or from float64 to float32). To avoid truncation, use dtypes in\n ``primals`` that match the full range of desired outputs from the transposed\n function. Integer dtypes are not supported.\n\n Args:\n fun: the linear function to be transposed.\n *primals: a positional argument tuple of arrays, scalars, or (nested)\n standard Python containers (tuples, lists, dicts, namedtuples, i.e.,\n pytrees) of those types used for evaluating the shape/dtype of\n ``fun(*primals)``. These arguments may be real scalars/ndarrays, but that\n is not required: only the ``shape`` and ``dtype`` attributes are accessed.\n See below for an example. (Note that the duck-typed objects cannot be\n namedtuples because those are treated as standard Python containers.)\n\n Returns:\n A callable that calculates the transpose of ``fun``. Valid input into this\n function must have the same shape/dtypes/structure as the result of\n ``fun(*primals)``. Output will be a tuple, with the same\n shape/dtypes/structure as ``primals``.\n\n >>> import jax\n >>> import types\n >>>\n >>> f = lambda x, y: 0.5 * x - 0.5 * y\n >>> scalar = types.SimpleNamespace(shape=(), dtype=np.float32)\n >>> f_transpose = jax.linear_transpose(f, scalar, scalar)\n >>> f_transpose(1.0)\n (DeviceArray(0.5, dtype=float32), DeviceArray(-0.5, dtype=float32))\n \"\"\"\n def abstractify(x):\n return core.ShapedArray(np.shape(x), dtypes.result_type(x))\n primals_flat, in_tree = tree_flatten(primals)\n flat_fun, out_tree = flatten_fun_nokwargs(lu.wrap_init(fun), in_tree)\n in_avals = map(abstractify, primals_flat)\n in_dtypes = map(dtypes.dtype, in_avals)\n if any(not np.issubdtype(dtype, np.inexact) for dtype in in_dtypes):\n raise TypeError(\"linear_transpose only supports float and complex inputs, \"\n f\"but got {in_dtypes}\")\n\n in_pvals = map(pe.PartialVal.unknown, in_avals)\n jaxpr, out_pvals, consts = pe.trace_to_jaxpr(flat_fun, in_pvals,\n instantiate=True)\n out_avals, _ = unzip2(out_pvals)\n\n def transposed_fun(out_cotangent):\n out_cotangents, out_tree2 = tree_flatten(out_cotangent)\n if out_tree() != out_tree2:\n msg = (\"cotangent tree does not match function output, \"\n f\"expected {out_tree()} but got {out_tree2}\")\n raise TypeError(msg)\n if not all(map(core.typecheck, out_avals, out_cotangents)):\n raise TypeError(\"cotangent type does not match function output, \"\n f\"expected {out_avals} but got {out_cotangents}\")\n dummies = [ad.UndefinedPrimal(a) for a in in_avals]\n in_cotangents = ad.backward_pass(jaxpr, consts, dummies, out_cotangents)\n return tree_unflatten(in_tree, in_cotangents)\n\n return transposed_fun\n\n\ndef make_jaxpr(fun: Callable,\n static_argnums: Union[int, Iterable[int]] = (),\n return_shape: bool = False,\n ) -> Callable[..., core.ClosedJaxpr]:\n \"\"\"Creates a function that produces its jaxpr given example args.\n\n Args:\n fun: The function whose ``jaxpr`` is to be computed. Its positional\n arguments and return value should be arrays, scalars, or standard Python\n containers (tuple/list/dict) thereof.\n static_argnums: See the :py:func:`jax.jit` docstring.\n return_shape: Optional boolean, defaults to ``False``. If ``True``, the\n wrapped function returns a pair where the first element is the ``jaxpr``\n and the second element is a pytree with the same structure as\n the output of ``fun`` and where the leaves are objects with ``shape`` and\n ``dtype`` attributes representing the corresponding types of the output\n leaves.\n\n Returns:\n A wrapped version of ``fun`` that when applied to example arguments returns\n a ``ClosedJaxpr`` representation of ``fun`` on those arguments. If the\n argument ``return_shape`` is ``True``, then the returned function instead\n returns a pair where the first element is the ``ClosedJaxpr``\n representation of ``fun`` and the second element is a pytree representing\n the structure, shape, and dtypes of the output of ``fun``.\n\n A ``jaxpr`` is JAX's intermediate representation for program traces. The\n ``jaxpr`` language is based on the simply-typed first-order lambda calculus\n with let-bindings. :py:func:`make_jaxpr` adapts a function to return its\n ``jaxpr``, which we can inspect to understand what JAX is doing internally.\n The ``jaxpr`` returned is a trace of ``fun`` abstracted to\n :py:class:`ShapedArray` level. Other levels of abstraction exist internally.\n\n We do not describe the semantics of the ``jaxpr`` language in detail here, but\n instead give a few examples.\n\n >>> import jax\n >>>\n >>> def f(x): return jax.numpy.sin(jax.numpy.cos(x))\n >>> print(f(3.0))\n -0.83602\n >>> jax.make_jaxpr(f)(3.0)\n { lambda ; a.\n let b = cos a\n c = sin b\n in (c,) }\n >>> jax.make_jaxpr(jax.grad(f))(3.0)\n { lambda ; a.\n let b = cos a\n c = sin a\n _ = sin b\n d = cos b\n e = mul 1.0 d\n f = neg e\n g = mul f c\n in (g,) }\n \"\"\"\n _check_callable(fun)\n if isinstance(static_argnums, int):\n static_argnums = (static_argnums,)\n\n @wraps(fun)\n @api_boundary\n def jaxpr_maker(*args, **kwargs):\n wrapped = lu.wrap_init(fun)\n if static_argnums:\n dyn_argnums = [i for i in range(len(args)) if i not in static_argnums]\n wrapped, args = argnums_partial(wrapped, dyn_argnums, args)\n jax_args, in_tree = tree_flatten((args, kwargs))\n jaxtree_fun, out_tree = flatten_fun(wrapped, in_tree)\n in_avals = [raise_to_shaped(core.get_aval(x)) for x in jax_args]\n if config.omnistaging_enabled:\n jaxpr, out_avals, consts = pe.trace_to_jaxpr_dynamic(jaxtree_fun, in_avals)\n else:\n in_pvals = [pe.PartialVal.unknown(a) for a in in_avals]\n jaxpr, out_pvals, consts = pe.trace_to_jaxpr(\n jaxtree_fun, in_pvals, instantiate=True, stage_out=True) # type: ignore\n out_avals = map(raise_to_shaped, unzip2(out_pvals)[0])\n closed_jaxpr = core.ClosedJaxpr(jaxpr, consts)\n if return_shape:\n out_shapes_flat = [ShapeDtypeStruct(a.shape, a.dtype) for a in out_avals]\n return closed_jaxpr, tree_unflatten(out_tree(), out_shapes_flat)\n return closed_jaxpr\n\n jaxpr_maker.__name__ = \"make_jaxpr({})\".format(jaxpr_maker.__name__)\n return jaxpr_maker\n\n\ndef device_put(x, device: Optional[xc.Device] = None):\n \"\"\"Transfers ``x`` to ``device``.\n\n Args:\n x: An array, scalar, or (nested) standard Python container thereof.\n device: The (optional) :py:class:`Device` to which ``x`` should be\n transferred. If given, then the result is committed to the device.\n\n If the ``device`` parameter is ``None``, then this operation behaves like the\n identity function if the operand is on any device already, otherwise it\n transfers the data to the default device, uncommitted.\n\n For more details on data placement see the\n :ref:`FAQ on data placement <faq-data-placement>`.\n\n Returns:\n A copy of ``x`` that resides on ``device``.\n \"\"\"\n return tree_map(lambda y: xla.device_put_p.bind(y, device=device), x)\n\n\ndef device_put_sharded(x: Sequence[Any], devices: Sequence[xc.Device]):\n \"\"\"Transfers pre-sharded input to the specified devices, returning ShardedDeviceArrays.\n\n Args:\n x: A sequence of arrays, scalars, or (nested) standard Python containers thereof.\n devices: A sequence of devices()\n\n Returns:\n A ShardedDeviceArray or (nested) Python container thereof containing a stacked\n version of x sharded across the specified devices.\n\n Examples:\n Passing a list of arrays results in a sharded array containing a stacked version\n of the inputs. Note that the array's leading dimension must equal the number of devices:\n\n >>> from jax import api, numpy as jnp\n >>> devices = api.local_devices()\n >>> x = [jnp.ones(5) for device in devices]\n >>> y = api.device_put_sharded(x, devices)\n >>> np.allclose(y, jnp.stack(x))\n True\n\n Sharding a list of nested objects is equivalent to sharding the list\n of each entry and repackaging the results to match the nesting. This\n requires all entries in the list to have the same structure:\n\n >>> x = [(i, jnp.arange(i, i + 4)) for i in range(len(devices))]\n >>> y = api.device_put_sharded(x, devices)\n >>> type(y)\n <class 'tuple'>\n >>> y0 = api.device_put_sharded([a for a, b in x], devices)\n >>> y1 = api.device_put_sharded([b for a, b in x], devices)\n >>> np.allclose(y[0], y0)\n True\n >>> np.allclose(y[1], y1)\n True\n\n See also:\n - device_put\n - device_put_replicated\n \"\"\"\n if not isinstance(x, Sequence):\n raise ValueError(f\"x must be a sequence; got {type(x)}\")\n # TODO(jakevdp): provide a default for devices that considers both local devices and pods\n assert len(x) == len(devices), f\"len(x) = {len(x)} must equal len(devices) = {len(devices)}.\"\n def _device_put_sharded(*xs) -> pxla.ShardedDeviceArray:\n avals = [core.raise_to_shaped(core.get_aval(x)) for x in xs]\n # We cannot check aval equality directly, because it may fail for ConcreteArray.\n assert all(aval.shape == avals[0].shape and aval.dtype == avals[0].dtype for aval in avals),\\\n f\"abstract values not compatible: {avals}\"\n x_aval = core.raise_to_shaped(avals[0])\n aval = ShapedArray((len(devices),) + x_aval.shape, x_aval.dtype)\n buffers = list(it.chain.from_iterable(xla.device_put(x, d) for x, d in zip(xs, devices)))\n return pxla.ShardedDeviceArray(aval, buffers)\n return tree_multimap(_device_put_sharded, *x)\n\n\n# TODO(mattjj): consider revising\ndef _device_get(x):\n if isinstance(x, core.Tracer):\n return x\n try:\n copy = x.copy\n except AttributeError:\n return x\n else:\n return copy()\n\ndef device_get(x):\n for y in tree_leaves(x):\n try:\n y.copy_to_host_async()\n except AttributeError:\n pass\n return tree_map(_device_get, x)\n\n\ndef _check_arg(arg):\n if not (isinstance(arg, core.Tracer) or _valid_jaxtype(arg)):\n raise TypeError(\"Argument '{}' of type {} is not a valid JAX type\"\n .format(arg, type(arg)))\n\n# TODO(necula): this duplicates code in core.valid_jaxtype\ndef _valid_jaxtype(arg):\n try:\n xla.abstractify(arg) # faster than core.get_aval\n except TypeError:\n return False\n else:\n return True\n\n\nclass ShapeDtypeStruct:\n __slots__ = [\"shape\", \"dtype\"]\n def __init__(self, shape, dtype):\n self.shape = shape\n self.dtype = np.dtype(dtype)\n\n size = property(lambda self: prod(self.shape))\n ndim = property(lambda self: len(self.shape))\n\n def __len__(self):\n try:\n return self.shape[0]\n except IndexError as e:\n raise TypeError(\"len() of unsized object\") from e # same as numpy error\n\n def __repr__(self):\n return \"{}(shape={}, dtype={})\".format(\n type(self).__name__, self.shape, self.dtype.name)\n\n __str__ = __repr__\n\n def __eq__(self, other):\n if not isinstance(other, ShapeDtypeStruct):\n return False\n else:\n return (other.shape, other.dtype) == (self.shape, self.dtype)\n\n def __hash__(self):\n return hash((self.shape, self.dtype))\n\ndef eval_shape(fun: Callable, *args, **kwargs):\n \"\"\"Compute the shape/dtype of ``fun`` without any FLOPs.\n\n This utility function is useful for performing shape inference. Its\n input/output behavior is defined by::\n\n def eval_shape(fun, *args, **kwargs):\n out = fun(*args, **kwargs)\n return jax.tree_util.tree_map(shape_dtype_struct, out)\n\n def shape_dtype_struct(x):\n return ShapeDtypeStruct(x.shape, x.dtype)\n\n class ShapeDtypeStruct:\n __slots__ = [\"shape\", \"dtype\"]\n def __init__(self, shape, dtype):\n self.shape = shape\n self.dtype = dtype\n\n In particular, the output is a pytree of objects that have ``shape`` and\n ``dtype`` attributes, but nothing else about them is guaranteed by the API.\n\n But instead of applying ``fun`` directly, which might be expensive, it uses\n JAX's abstract interpretation machinery to evaluate the shapes without doing\n any FLOPs.\n\n Using :py:func:`eval_shape` can also catch shape errors, and will raise same\n shape errors as evaluating ``fun(*args, **kwargs)``.\n\n Args:\n fun: The function whose output shape should be evaluated.\n *args: a positional argument tuple of arrays, scalars, or (nested) standard\n Python containers (tuples, lists, dicts, namedtuples, i.e. pytrees) of\n those types. Since only the ``shape`` and ``dtype`` attributes are\n accessed, only values that duck-type arrays are required, rather than real\n ndarrays. The duck-typed objects cannot be namedtuples because those are\n treated as standard Python containers. See the example below.\n **kwargs: a keyword argument dict of arrays, scalars, or (nested) standard\n Python containers (pytrees) of those types. As in ``args``, array values\n need only be duck-typed to have ``shape`` and ``dtype`` attributes.\n\n For example:\n\n >>> import jax\n >>> import jax.numpy as jnp\n >>>\n >>> f = lambda A, x: jnp.tanh(jnp.dot(A, x))\n >>> class MyArgArray(object):\n ... def __init__(self, shape, dtype):\n ... self.shape = shape\n ... self.dtype = dtype\n ...\n >>> A = MyArgArray((2000, 3000), jnp.float32)\n >>> x = MyArgArray((3000, 1000), jnp.float32)\n >>> out = jax.eval_shape(f, A, x) # no FLOPs performed\n >>> print(out.shape)\n (2000, 1000)\n >>> print(out.dtype)\n float32\n \"\"\"\n def abstractify(x):\n return ShapedArray(np.shape(x), dtypes.result_type(x))\n args_flat, in_tree = tree_flatten((args, kwargs))\n wrapped_fun, out_tree = flatten_fun(lu.wrap_init(fun), in_tree)\n out = pe.abstract_eval_fun(wrapped_fun.call_wrapped,\n *map(abstractify, args_flat))\n out = [ShapeDtypeStruct(x.shape, x.dtype) for x in out]\n return tree_unflatten(out_tree(), out)\n\n\ndef checkpoint(fun: Callable, concrete: bool = False) -> Callable:\n \"\"\"Make ``fun`` recompute internal linearization points when differentiated.\n\n The :func:`jax.checkpoint` decorator, aliased to ``jax.remat``, provides a\n way to trade off computation time and memory cost in the context of automatic\n differentiation, especially with reverse-mode autodiff like :func:`jax.grad`\n and :func:`jax.vjp` but also with :func:`jax.linearize`.\n\n When differentiating a function in reverse-mode, by default all the\n linearization points (e.g. inputs to elementwise nonlinear primitive\n operations) are stored when evaluating the forward pass so that they can be\n reused on the backward pass. This evaluation strategy can lead to a high\n memory cost, or even to poor performance on hardware accelerators where memory\n access is much more expensive than FLOPs.\n\n An alternative evaluation strategy is for some of the linearization points to\n be recomputed (i.e. rematerialized) rather than stored. This approach can\n reduce memory usage at the cost of increased computation.\n\n This function decorator produces a new version of ``fun`` which follows\n the rematerialization strategy rather than the default store-everything\n strategy. That is, it returns a new version of ``fun`` which, when\n differentiated, doesn't store any of its intermediate linearization points.\n Instead, these linearization points are recomputed from the function's saved\n inputs.\n\n See the examples below.\n\n Args:\n fun: Function for which the autodiff evaluation strategy is to be changed\n from the default of storing all intermediate linearization points to\n recomputing them. Its arguments and return value should be arrays,\n scalars, or (nested) standard Python containers (tuple/list/dict) thereof.\n concrete: Optional, boolean indicating whether ``fun`` may involve\n value-dependent Python control flow (default False). Support for such\n control flow is optional, and disabled by default, because in some\n edge-case compositions with :func:`jax.jit` it can lead to some extra\n computation.\n\n Returns:\n A function (callable) with the same input/output behavior as ``fun`` but\n which, when differentiated using e.g. :func:`jax.grad`, :func:`jax.vjp`, or\n :func:`jax.linearize`, recomputes rather than stores intermediate\n linearization points, thus potentially saving memory at the cost of extra\n computation.\n\n Here is a simple example:\n\n >>> import jax\n >>> import jax.numpy as jnp\n\n >>> @jax.checkpoint\n ... def g(x):\n ... y = jnp.sin(x)\n ... z = jnp.sin(y)\n ... return z\n ...\n >>> jax.grad(g)(2.0)\n DeviceArray(-0.25563914, dtype=float32)\n\n Here, the same value is produced whether or not the :func:`jax.checkpoint`\n decorator is present. But when using :func:`jax.checkpoint`, the value\n ``jnp.sin(2.0)`` is computed twice: once on the forward pass, and once on the\n backward pass. The values ``jnp.cos(2.0)`` and ``jnp.cos(jnp.sin(2.0))`` are\n also computed twice. Without using the decorator, both ``jnp.cos(2.0)`` and\n ``jnp.cos(jnp.sin(2.0))`` would be stored and reused.\n\n The :func:`jax.checkpoint` decorator can be applied recursively to express\n sophisticated autodiff rematerialization strategies. For example:\n\n >>> def recursive_checkpoint(funs):\n ... if len(funs) == 1:\n ... return funs[0]\n ... elif len(funs) == 2:\n ... f1, f2 = funs\n ... return lambda x: f1(f2(x))\n ... else:\n ... f1 = recursive_checkpoint(funs[:len(funs)//2])\n ... f2 = recursive_checkpoint(funs[len(funs)//2:])\n ... return lambda x: f1(jax.checkpoint(f2)(x))\n ...\n \"\"\"\n @wraps(fun)\n @api_boundary\n def fun_remat(*args, **kwargs):\n args_flat, in_tree = tree_flatten((args, kwargs))\n flat_fun, out_tree = flatten_fun(lu.wrap_init(fun), in_tree)\n out_flat = pe.remat_call(flat_fun, *args_flat, name=flat_fun.__name__,\n concrete=concrete)\n return tree_unflatten(out_tree(), out_flat)\n return fun_remat\nremat = checkpoint\n\n\n# TODO(mattjj): delete everything below here (deprecated custom_transforms)\n\nclass CustomTransformsFunction(object):\n def __init__(self, fun, prim):\n self.fun = fun\n self.prim = prim\n wraps(fun)(self)\n\n def __repr__(self):\n return '<jax.custom_transforms function {fun}>'.format(fun=self.__name__)\n\n def __call__(self, *args):\n args_flat, in_tree = tree_flatten(args)\n flat_fun, out_tree = flatten_fun_nokwargs(lu.wrap_init(self.fun), in_tree)\n in_pvals = [pe.PartialVal.unknown(raise_to_shaped(core.get_aval(x)))\n for x in args_flat]\n if config.omnistaging_enabled:\n jaxpr, _, consts = pe.trace_to_jaxpr(flat_fun, in_pvals, instantiate=True)\n else:\n with core.initial_style_staging(): # type: ignore\n jaxpr, _, consts = pe.trace_to_jaxpr(flat_fun, in_pvals, instantiate=True)\n outs = self.prim.bind(*it.chain(consts, args_flat), jaxpr=jaxpr,\n in_tree=in_tree, out_tree=out_tree(),\n num_consts=len(consts))\n return tree_unflatten(out_tree(), outs)\n\ndef custom_transforms(fun):\n \"\"\"Deprecated. See :py:func:`jax.custom_jvp` and :py:func:`jax.custom_vjp`.\"\"\"\n\n name = getattr(fun, '__name__', '<unnamed custom_transforms primitive>')\n fun_p = core.Primitive(name)\n fun_p.multiple_results = True\n\n def fun_impl(*args, **params):\n consts, args = split_list(args, [params['num_consts']])\n return core.eval_jaxpr(params['jaxpr'], consts, *args)\n fun_p.def_impl(fun_impl)\n\n def fun_jvp(primals, tangents, **params):\n return ad.jvp(lu.wrap_init(fun_impl, params)).call_wrapped(primals, tangents)\n ad.primitive_jvps[fun_p] = fun_jvp\n\n def fun_batch(args, dims, **params):\n batched, out_dims = batching.batch_fun2(lu.wrap_init(fun_impl, params), dims)\n return batched.call_wrapped(*args), out_dims()\n batching.primitive_batchers[fun_p] = fun_batch\n\n def fun_abstract_eval(*avals, **params):\n return pe.abstract_eval_fun(fun_impl, *avals, **params)\n fun_p.def_abstract_eval(fun_abstract_eval)\n\n def fun_translation(c, *xla_args, **params):\n return xla.lower_fun(fun_impl, multiple_results=True)(c, *xla_args, **params)\n xla.translations[fun_p] = fun_translation\n\n return CustomTransformsFunction(fun, fun_p)\n\ndef _check_custom_transforms_type(name, fun):\n if type(fun) is not CustomTransformsFunction:\n msg = (\"{} requires a custom_transforms function as its first argument, \"\n \"but got type {}.\")\n raise TypeError(msg.format(name, type(fun)))\n\ndef defjvp_all(fun, custom_jvp):\n \"\"\"This API is deprecated. See :py:func:`jax.custom_jvp` and :py:func:`jax.custom_vjp` instead.\"\"\"\n\n _check_custom_transforms_type(\"defjvp_all\", fun)\n def custom_transforms_jvp(primals, tangents, **params):\n num_consts, in_tree = params['num_consts'], params['in_tree']\n _, args_flat = split_list(primals, [num_consts])\n consts_dot, args_dot_flat = split_list(tangents, [num_consts])\n if not all(type(t) is ad_util.Zero for t in consts_dot):\n msg = (\"Detected differentiation with respect to closed-over values with \"\n \"custom JVP rule, which isn't supported.\")\n raise ValueError(msg)\n args_dot_flat = map(ad.instantiate_zeros, args_dot_flat)\n args = tree_unflatten(in_tree, args_flat)\n args_dot = tree_unflatten(in_tree, args_dot_flat)\n out, out_dot = custom_jvp(args, args_dot)\n out_flat, out_tree = tree_flatten(out)\n out_dot_flat, out_tree2 = tree_flatten(out_dot)\n if out_tree != out_tree2:\n msg = (\"Custom JVP rule returned different tree structures for primals \"\n \"and tangents, but they must be equal: {} and {}.\")\n raise TypeError(msg.format(out_tree, out_tree2))\n return out_flat, out_dot_flat\n ad.primitive_jvps[fun.prim] = custom_transforms_jvp\n\ndef defjvp(fun, *jvprules):\n \"\"\"This API is deprecated. See :py:func:`jax.custom_jvp` and :py:func:`jax.custom_vjp` instead.\"\"\"\n\n _check_custom_transforms_type(\"defjvp\", fun)\n def custom_jvp(primals, tangents):\n ans = fun(*primals)\n tangents_out = [rule(t, ans, *primals) for rule, t in zip(jvprules, tangents)\n if rule is not None and type(t) is not ad_util.Zero]\n return ans, functools.reduce(ad.add_tangents, tangents_out, ad_util.Zero.from_value(ans))\n defjvp_all(fun, custom_jvp)\n\ndef defvjp_all(fun, custom_vjp):\n \"\"\"This API is deprecated. See :py:func:`jax.custom_jvp` and :py:func:`jax.custom_vjp` instead.\"\"\"\n\n _check_custom_transforms_type(\"defvjp_all\", fun)\n def custom_transforms_vjp(*consts_and_args, **params):\n num_consts, in_tree = params['num_consts'], params['in_tree']\n consts, args_flat = split_list(consts_and_args, [num_consts])\n args = tree_unflatten(params['in_tree'], args_flat)\n out, vjp = custom_vjp(*args)\n out_flat, out_tree = tree_flatten(out)\n if out_tree != params['out_tree']:\n msg = (\n \"First output of `custom_vjp`: {} doesn't match the structure of \"\n \"the output of `fun`: {}\\n\"\n \"{}\\n\"\n \"vs\\n\"\n \"{}\\n\".format(custom_vjp, fun, out_tree, params['out_tree'])\n )\n raise TypeError(msg)\n def vjp_flat(*cts_flat):\n cts = tree_unflatten(out_tree, cts_flat)\n args_cts_flat, in_tree2 = tree_flatten(vjp(cts))\n if in_tree != in_tree2:\n msg = (\n \"Output of the `vjp`: {} doesn't match the structure of args of \"\n \"`fun`: {}\\n\"\n \"{}\\n\"\n \"vs\\n\"\n \"{}\\n\".format(vjp, fun, in_tree2, in_tree)\n )\n raise TypeError(msg)\n return [core.unit] * num_consts + list(args_cts_flat)\n return out_flat, vjp_flat\n ad.defvjp_all(fun.prim, custom_transforms_vjp)\n\ndef defvjp(fun, *vjprules):\n \"\"\"This API is deprecated. See :py:func:`jax.custom_jvp` and :py:func:`jax.custom_vjp` instead.\"\"\"\n\n _check_custom_transforms_type(\"defvjp\", fun)\n def custom_vjp(*primals):\n ans = fun(*primals)\n # TODO(mattjj): avoid instantiating zeros?\n def vjpfun(ct):\n return tuple(vjp(ct, ans, *primals) if vjp else ad_util.zeros_like_jaxval(x)\n for x, vjp in zip(primals, vjprules))\n return ans, vjpfun\n defvjp_all(fun, custom_vjp)\n\ndef custom_gradient(fun):\n \"\"\"This API is deprecated. See :py:func:`jax.custom_jvp` and :py:func:`jax.custom_vjp` instead.\"\"\"\n\n def primal_fun(*args, **kwargs):\n ans, _ = fun(*args, **kwargs)\n return ans\n primal_fun = custom_transforms(primal_fun)\n defvjp_all(primal_fun, fun)\n return primal_fun\n\ndef _ensure_tuple(x: Union[int, Iterable[int]]) -> Tuple[int, ...]:\n return (x,) if isinstance(x, int) else tuple(x)\n\ndef invertible(fun: Callable) -> Callable:\n \"\"\"Asserts that the decorated function is invertible.\n\n Applying reverse-mode AD to a decorated function will use a more memory efficient\n procedure than usual, which will reconstruct the necessary intermediate values\n by inverting the function. Note that this might degrade the numerical accuracy of\n obtained gradients if the inverse is unstable.\n\n Args:\n fun: The function assumed to be invertible.\n \"\"\"\n return iad.invertible(fun)\n" ]
[ [ "numpy.shape", "numpy.result_type", "numpy.zeros", "numpy.dtype" ], [ "numpy.split", "numpy.reshape", "numpy.eye", "numpy.issubdtype", "numpy.dtype", "numpy.ones", "numpy.ndim", "numpy.shape" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
douglatornell/xarray
[ "6d93a95d05bdbfc33fff24064f67d29dd891ab58", "742ed3984f437982057fd46ecfb0bce214563cb8", "6d93a95d05bdbfc33fff24064f67d29dd891ab58" ]
[ "xarray/core/pdcompat.py", "xarray/testing.py", "xarray/tests/test_cftime_offsets.py" ]
[ "# The remove_unused_levels defined here was copied based on the source code\n# defined in pandas.core.indexes.muli.py\n\n# For reference, here is a copy of the pandas copyright notice:\n\n# (c) 2011-2012, Lambda Foundry, Inc. and PyData Development Team\n# All rights reserved.\n\n# Copyright (c) 2008-2011 AQR Capital Management, LLC\n# All rights reserved.\n\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n\n# * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following\n# disclaimer in the documentation and/or other materials provided\n# with the distribution.\n\n# * Neither the name of the copyright holder nor the names of any\n# contributors may be used to endorse or promote products derived\n# from this software without specific prior written permission.\n\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\nimport numpy as np\n\n\n# for pandas 0.19\ndef remove_unused_levels(self):\n \"\"\"\n create a new MultiIndex from the current that removing\n unused levels, meaning that they are not expressed in the labels\n The resulting MultiIndex will have the same outward\n appearance, meaning the same .values and ordering. It will also\n be .equals() to the original.\n .. versionadded:: 0.20.0\n Returns\n -------\n MultiIndex\n Examples\n --------\n >>> i = pd.MultiIndex.from_product([range(2), list('ab')])\n MultiIndex(levels=[[0, 1], ['a', 'b']],\n labels=[[0, 0, 1, 1], [0, 1, 0, 1]])\n >>> i[2:]\n MultiIndex(levels=[[0, 1], ['a', 'b']],\n labels=[[1, 1], [0, 1]])\n The 0 from the first level is not represented\n and can be removed\n >>> i[2:].remove_unused_levels()\n MultiIndex(levels=[[1], ['a', 'b']],\n labels=[[0, 0], [0, 1]])\n \"\"\"\n import pandas.core.algorithms as algos\n\n new_levels = []\n new_labels = []\n\n changed = False\n for lev, lab in zip(self.levels, self.labels):\n\n # Since few levels are typically unused, bincount() is more\n # efficient than unique() - however it only accepts positive values\n # (and drops order):\n uniques = np.where(np.bincount(lab + 1) > 0)[0] - 1\n has_na = int(len(uniques) and (uniques[0] == -1))\n\n if len(uniques) != len(lev) + has_na:\n # We have unused levels\n changed = True\n\n # Recalculate uniques, now preserving order.\n # Can easily be cythonized by exploiting the already existing\n # \"uniques\" and stop parsing \"lab\" when all items are found:\n uniques = algos.unique(lab)\n if has_na:\n na_idx = np.where(uniques == -1)[0]\n # Just ensure that -1 is in first position:\n uniques[[0, na_idx[0]]] = uniques[[na_idx[0], 0]]\n\n # labels get mapped from uniques to 0:len(uniques)\n # -1 (if present) is mapped to last position\n label_mapping = np.zeros(len(lev) + has_na)\n # ... and reassigned value -1:\n label_mapping[uniques] = np.arange(len(uniques)) - has_na\n\n lab = label_mapping[lab]\n\n # new levels are simple\n lev = lev.take(uniques[has_na:])\n\n new_levels.append(lev)\n new_labels.append(lab)\n\n result = self._shallow_copy()\n\n if changed:\n result._reset_identity()\n result._set_levels(new_levels, validate=False)\n result._set_labels(new_labels, validate=False)\n\n return result\n", "\"\"\"Testing functions exposed to the user API\"\"\"\nimport numpy as np\n\nfrom xarray.core import duck_array_ops\nfrom xarray.core import formatting\n\n\ndef _decode_string_data(data):\n if data.dtype.kind == 'S':\n return np.core.defchararray.decode(data, 'utf-8', 'replace')\n return data\n\n\ndef _data_allclose_or_equiv(arr1, arr2, rtol=1e-05, atol=1e-08,\n decode_bytes=True):\n if any(arr.dtype.kind == 'S' for arr in [arr1, arr2]) and decode_bytes:\n arr1 = _decode_string_data(arr1)\n arr2 = _decode_string_data(arr2)\n exact_dtypes = ['M', 'm', 'O', 'S', 'U']\n if any(arr.dtype.kind in exact_dtypes for arr in [arr1, arr2]):\n return duck_array_ops.array_equiv(arr1, arr2)\n else:\n return duck_array_ops.allclose_or_equiv(\n arr1, arr2, rtol=rtol, atol=atol)\n\n\ndef assert_equal(a, b):\n \"\"\"Like :py:func:`numpy.testing.assert_array_equal`, but for xarray\n objects.\n\n Raises an AssertionError if two objects are not equal. This will match\n data values, dimensions and coordinates, but not names or attributes\n (except for Dataset objects for which the variable names must match).\n Arrays with NaN in the same location are considered equal.\n\n Parameters\n ----------\n a : xarray.Dataset, xarray.DataArray or xarray.Variable\n The first object to compare.\n b : xarray.Dataset, xarray.DataArray or xarray.Variable\n The second object to compare.\n\n See also\n --------\n assert_identical, assert_allclose, Dataset.equals, DataArray.equals,\n numpy.testing.assert_array_equal\n \"\"\"\n import xarray as xr\n __tracebackhide__ = True # noqa: F841\n assert type(a) == type(b) # noqa\n if isinstance(a, (xr.Variable, xr.DataArray)):\n assert a.equals(b), formatting.diff_array_repr(a, b, 'equals')\n elif isinstance(a, xr.Dataset):\n assert a.equals(b), formatting.diff_dataset_repr(a, b, 'equals')\n else:\n raise TypeError('{} not supported by assertion comparison'\n .format(type(a)))\n\n\ndef assert_identical(a, b):\n \"\"\"Like :py:func:`xarray.testing.assert_equal`, but also matches the\n objects' names and attributes.\n\n Raises an AssertionError if two objects are not identical.\n\n Parameters\n ----------\n a : xarray.Dataset, xarray.DataArray or xarray.Variable\n The first object to compare.\n b : xarray.Dataset, xarray.DataArray or xarray.Variable\n The second object to compare.\n\n See also\n --------\n assert_equal, assert_allclose, Dataset.equals, DataArray.equals\n \"\"\"\n import xarray as xr\n __tracebackhide__ = True # noqa: F841\n assert type(a) == type(b) # noqa\n if isinstance(a, xr.Variable):\n assert a.identical(b), formatting.diff_array_repr(a, b, 'identical')\n elif isinstance(a, xr.DataArray):\n assert a.name == b.name\n assert a.identical(b), formatting.diff_array_repr(a, b, 'identical')\n elif isinstance(a, (xr.Dataset, xr.Variable)):\n assert a.identical(b), formatting.diff_dataset_repr(a, b, 'identical')\n else:\n raise TypeError('{} not supported by assertion comparison'\n .format(type(a)))\n\n\ndef assert_allclose(a, b, rtol=1e-05, atol=1e-08, decode_bytes=True):\n \"\"\"Like :py:func:`numpy.testing.assert_allclose`, but for xarray objects.\n\n Raises an AssertionError if two objects are not equal up to desired\n tolerance.\n\n Parameters\n ----------\n a : xarray.Dataset, xarray.DataArray or xarray.Variable\n The first object to compare.\n b : xarray.Dataset, xarray.DataArray or xarray.Variable\n The second object to compare.\n rtol : float, optional\n Relative tolerance.\n atol : float, optional\n Absolute tolerance.\n decode_bytes : bool, optional\n Whether byte dtypes should be decoded to strings as UTF-8 or not.\n This is useful for testing serialization methods on Python 3 that\n return saved strings as bytes.\n\n See also\n --------\n assert_identical, assert_equal, numpy.testing.assert_allclose\n \"\"\"\n import xarray as xr\n __tracebackhide__ = True # noqa: F841\n assert type(a) == type(b) # noqa\n kwargs = dict(rtol=rtol, atol=atol, decode_bytes=decode_bytes)\n if isinstance(a, xr.Variable):\n assert a.dims == b.dims\n allclose = _data_allclose_or_equiv(a.values, b.values, **kwargs)\n assert allclose, '{}\\n{}'.format(a.values, b.values)\n elif isinstance(a, xr.DataArray):\n assert_allclose(a.variable, b.variable, **kwargs)\n assert set(a.coords) == set(b.coords)\n for v in a.coords.variables:\n # can't recurse with this function as coord is sometimes a\n # DataArray, so call into _data_allclose_or_equiv directly\n allclose = _data_allclose_or_equiv(a.coords[v].values,\n b.coords[v].values, **kwargs)\n assert allclose, '{}\\n{}'.format(a.coords[v].values,\n b.coords[v].values)\n elif isinstance(a, xr.Dataset):\n assert set(a.data_vars) == set(b.data_vars)\n assert set(a.coords) == set(b.coords)\n for k in list(a.variables) + list(a.coords):\n assert_allclose(a[k], b[k], **kwargs)\n\n else:\n raise TypeError('{} not supported by assertion comparison'\n .format(type(a)))\n\n\ndef assert_combined_tile_ids_equal(dict1, dict2):\n assert len(dict1) == len(dict2)\n for k, v in dict1.items():\n assert k in dict2.keys()\n assert_equal(dict1[k], dict2[k])\n", "from itertools import product\n\nimport numpy as np\nimport pandas as pd\nimport pytest\n\nfrom xarray import CFTimeIndex\nfrom xarray.coding.cftime_offsets import (\n _MONTH_ABBREVIATIONS, BaseCFTimeOffset, Day, Hour, Minute, Second,\n MonthBegin, MonthEnd, YearBegin, YearEnd, QuarterBegin, QuarterEnd,\n _days_in_month, cftime_range, get_date_type, to_cftime_datetime, to_offset)\n\ncftime = pytest.importorskip('cftime')\n\n\n_CFTIME_CALENDARS = ['365_day', '360_day', 'julian', 'all_leap',\n '366_day', 'gregorian', 'proleptic_gregorian', 'standard']\n\n\ndef _id_func(param):\n \"\"\"Called on each parameter passed to pytest.mark.parametrize\"\"\"\n return str(param)\n\n\[email protected](params=_CFTIME_CALENDARS)\ndef calendar(request):\n return request.param\n\n\[email protected](\n ('offset', 'expected_n'),\n [(BaseCFTimeOffset(), 1),\n (YearBegin(), 1),\n (YearEnd(), 1),\n (QuarterBegin(), 1),\n (QuarterEnd(), 1),\n (BaseCFTimeOffset(n=2), 2),\n (YearBegin(n=2), 2),\n (YearEnd(n=2), 2),\n (QuarterBegin(n=2), 2),\n (QuarterEnd(n=2), 2)],\n ids=_id_func\n)\ndef test_cftime_offset_constructor_valid_n(offset, expected_n):\n assert offset.n == expected_n\n\n\[email protected](\n ('offset', 'invalid_n'),\n [(BaseCFTimeOffset, 1.5),\n (YearBegin, 1.5),\n (YearEnd, 1.5),\n (QuarterBegin, 1.5),\n (QuarterEnd, 1.5)],\n ids=_id_func\n)\ndef test_cftime_offset_constructor_invalid_n(offset, invalid_n):\n with pytest.raises(TypeError):\n offset(n=invalid_n)\n\n\[email protected](\n ('offset', 'expected_month'),\n [(YearBegin(), 1),\n (YearEnd(), 12),\n (YearBegin(month=5), 5),\n (YearEnd(month=5), 5),\n (QuarterBegin(), 3),\n (QuarterEnd(), 3),\n (QuarterBegin(month=5), 5),\n (QuarterEnd(month=5), 5)],\n ids=_id_func\n)\ndef test_year_offset_constructor_valid_month(offset, expected_month):\n assert offset.month == expected_month\n\n\[email protected](\n ('offset', 'invalid_month', 'exception'),\n [(YearBegin, 0, ValueError),\n (YearEnd, 0, ValueError),\n (YearBegin, 13, ValueError,),\n (YearEnd, 13, ValueError),\n (YearBegin, 1.5, TypeError),\n (YearEnd, 1.5, TypeError),\n (QuarterBegin, 0, ValueError),\n (QuarterEnd, 0, ValueError),\n (QuarterBegin, 1.5, TypeError),\n (QuarterEnd, 1.5, TypeError),\n (QuarterBegin, 13, ValueError),\n (QuarterEnd, 13, ValueError)],\n ids=_id_func\n)\ndef test_year_offset_constructor_invalid_month(\n offset, invalid_month, exception):\n with pytest.raises(exception):\n offset(month=invalid_month)\n\n\[email protected](\n ('offset', 'expected'),\n [(BaseCFTimeOffset(), None),\n (MonthBegin(), 'MS'),\n (YearBegin(), 'AS-JAN'),\n (QuarterBegin(), 'QS-MAR')],\n ids=_id_func\n)\ndef test_rule_code(offset, expected):\n assert offset.rule_code() == expected\n\n\[email protected](\n ('offset', 'expected'),\n [(BaseCFTimeOffset(), '<BaseCFTimeOffset: n=1>'),\n (YearBegin(), '<YearBegin: n=1, month=1>'),\n (QuarterBegin(), '<QuarterBegin: n=1, month=3>')],\n ids=_id_func\n)\ndef test_str_and_repr(offset, expected):\n assert str(offset) == expected\n assert repr(offset) == expected\n\n\[email protected](\n 'offset',\n [BaseCFTimeOffset(), MonthBegin(), QuarterBegin(), YearBegin()],\n ids=_id_func\n)\ndef test_to_offset_offset_input(offset):\n assert to_offset(offset) == offset\n\n\[email protected](\n ('freq', 'expected'),\n [('M', MonthEnd()),\n ('2M', MonthEnd(n=2)),\n ('MS', MonthBegin()),\n ('2MS', MonthBegin(n=2)),\n ('D', Day()),\n ('2D', Day(n=2)),\n ('H', Hour()),\n ('2H', Hour(n=2)),\n ('T', Minute()),\n ('2T', Minute(n=2)),\n ('min', Minute()),\n ('2min', Minute(n=2)),\n ('S', Second()),\n ('2S', Second(n=2))],\n ids=_id_func\n)\ndef test_to_offset_sub_annual(freq, expected):\n assert to_offset(freq) == expected\n\n\n_ANNUAL_OFFSET_TYPES = {\n 'A': YearEnd,\n 'AS': YearBegin\n}\n\n\[email protected](('month_int', 'month_label'),\n list(_MONTH_ABBREVIATIONS.items()) + [(0, '')])\[email protected]('multiple', [None, 2])\[email protected]('offset_str', ['AS', 'A'])\ndef test_to_offset_annual(month_label, month_int, multiple, offset_str):\n freq = offset_str\n offset_type = _ANNUAL_OFFSET_TYPES[offset_str]\n if month_label:\n freq = '-'.join([freq, month_label])\n if multiple:\n freq = '{}'.format(multiple) + freq\n result = to_offset(freq)\n\n if multiple and month_int:\n expected = offset_type(n=multiple, month=month_int)\n elif multiple:\n expected = offset_type(n=multiple)\n elif month_int:\n expected = offset_type(month=month_int)\n else:\n expected = offset_type()\n assert result == expected\n\n\n_QUARTER_OFFSET_TYPES = {\n 'Q': QuarterEnd,\n 'QS': QuarterBegin\n}\n\n\[email protected](('month_int', 'month_label'),\n list(_MONTH_ABBREVIATIONS.items()) + [(0, '')])\[email protected]('multiple', [None, 2])\[email protected]('offset_str', ['QS', 'Q'])\ndef test_to_offset_quarter(month_label, month_int, multiple, offset_str):\n freq = offset_str\n offset_type = _QUARTER_OFFSET_TYPES[offset_str]\n if month_label:\n freq = '-'.join([freq, month_label])\n if multiple:\n freq = '{}'.format(multiple) + freq\n result = to_offset(freq)\n\n if multiple and month_int:\n expected = offset_type(n=multiple, month=month_int)\n elif multiple:\n if month_int:\n expected = offset_type(n=multiple)\n else:\n if offset_type == QuarterBegin:\n expected = offset_type(n=multiple, month=1)\n elif offset_type == QuarterEnd:\n expected = offset_type(n=multiple, month=12)\n elif month_int:\n expected = offset_type(month=month_int)\n else:\n if offset_type == QuarterBegin:\n expected = offset_type(month=1)\n elif offset_type == QuarterEnd:\n expected = offset_type(month=12)\n assert result == expected\n\n\[email protected]('freq', ['Z', '7min2', 'AM', 'M-', 'AS-', 'QS-',\n '1H1min'])\ndef test_invalid_to_offset_str(freq):\n with pytest.raises(ValueError):\n to_offset(freq)\n\n\[email protected](\n ('argument', 'expected_date_args'),\n [('2000-01-01', (2000, 1, 1)),\n ((2000, 1, 1), (2000, 1, 1))],\n ids=_id_func\n)\ndef test_to_cftime_datetime(calendar, argument, expected_date_args):\n date_type = get_date_type(calendar)\n expected = date_type(*expected_date_args)\n if isinstance(argument, tuple):\n argument = date_type(*argument)\n result = to_cftime_datetime(argument, calendar=calendar)\n assert result == expected\n\n\ndef test_to_cftime_datetime_error_no_calendar():\n with pytest.raises(ValueError):\n to_cftime_datetime('2000')\n\n\ndef test_to_cftime_datetime_error_type_error():\n with pytest.raises(TypeError):\n to_cftime_datetime(1)\n\n\n_EQ_TESTS_A = [\n BaseCFTimeOffset(), YearBegin(), YearEnd(), YearBegin(month=2),\n YearEnd(month=2), QuarterBegin(), QuarterEnd(), QuarterBegin(month=2),\n QuarterEnd(month=2), MonthBegin(), MonthEnd(), Day(), Hour(), Minute(),\n Second()\n]\n_EQ_TESTS_B = [\n BaseCFTimeOffset(n=2), YearBegin(n=2), YearEnd(n=2),\n YearBegin(n=2, month=2), YearEnd(n=2, month=2), QuarterBegin(n=2),\n QuarterEnd(n=2), QuarterBegin(n=2, month=2), QuarterEnd(n=2, month=2),\n MonthBegin(n=2), MonthEnd(n=2), Day(n=2), Hour(n=2), Minute(n=2),\n Second(n=2)\n]\n\n\[email protected](\n ('a', 'b'), product(_EQ_TESTS_A, _EQ_TESTS_B), ids=_id_func\n)\ndef test_neq(a, b):\n assert a != b\n\n\n_EQ_TESTS_B_COPY = [\n BaseCFTimeOffset(n=2), YearBegin(n=2), YearEnd(n=2),\n YearBegin(n=2, month=2), YearEnd(n=2, month=2), QuarterBegin(n=2),\n QuarterEnd(n=2), QuarterBegin(n=2, month=2), QuarterEnd(n=2, month=2),\n MonthBegin(n=2), MonthEnd(n=2), Day(n=2), Hour(n=2), Minute(n=2),\n Second(n=2)\n]\n\n\[email protected](\n ('a', 'b'), zip(_EQ_TESTS_B, _EQ_TESTS_B_COPY), ids=_id_func\n)\ndef test_eq(a, b):\n assert a == b\n\n\n_MUL_TESTS = [\n (BaseCFTimeOffset(), BaseCFTimeOffset(n=3)),\n (YearEnd(), YearEnd(n=3)),\n (YearBegin(), YearBegin(n=3)),\n (QuarterEnd(), QuarterEnd(n=3)),\n (QuarterBegin(), QuarterBegin(n=3)),\n (MonthEnd(), MonthEnd(n=3)),\n (MonthBegin(), MonthBegin(n=3)),\n (Day(), Day(n=3)),\n (Hour(), Hour(n=3)),\n (Minute(), Minute(n=3)),\n (Second(), Second(n=3))\n]\n\n\[email protected](('offset', 'expected'), _MUL_TESTS, ids=_id_func)\ndef test_mul(offset, expected):\n assert offset * 3 == expected\n\n\[email protected](('offset', 'expected'), _MUL_TESTS, ids=_id_func)\ndef test_rmul(offset, expected):\n assert 3 * offset == expected\n\n\[email protected](\n ('offset', 'expected'),\n [(BaseCFTimeOffset(), BaseCFTimeOffset(n=-1)),\n (YearEnd(), YearEnd(n=-1)),\n (YearBegin(), YearBegin(n=-1)),\n (QuarterEnd(), QuarterEnd(n=-1)),\n (QuarterBegin(), QuarterBegin(n=-1)),\n (MonthEnd(), MonthEnd(n=-1)),\n (MonthBegin(), MonthBegin(n=-1)),\n (Day(), Day(n=-1)),\n (Hour(), Hour(n=-1)),\n (Minute(), Minute(n=-1)),\n (Second(), Second(n=-1))],\n ids=_id_func)\ndef test_neg(offset, expected):\n assert -offset == expected\n\n\n_ADD_TESTS = [\n (Day(n=2), (1, 1, 3)),\n (Hour(n=2), (1, 1, 1, 2)),\n (Minute(n=2), (1, 1, 1, 0, 2)),\n (Second(n=2), (1, 1, 1, 0, 0, 2))\n]\n\n\[email protected](\n ('offset', 'expected_date_args'),\n _ADD_TESTS,\n ids=_id_func\n)\ndef test_add_sub_monthly(offset, expected_date_args, calendar):\n date_type = get_date_type(calendar)\n initial = date_type(1, 1, 1)\n expected = date_type(*expected_date_args)\n result = offset + initial\n assert result == expected\n\n\[email protected](\n ('offset', 'expected_date_args'),\n _ADD_TESTS,\n ids=_id_func\n)\ndef test_radd_sub_monthly(offset, expected_date_args, calendar):\n date_type = get_date_type(calendar)\n initial = date_type(1, 1, 1)\n expected = date_type(*expected_date_args)\n result = initial + offset\n assert result == expected\n\n\[email protected](\n ('offset', 'expected_date_args'),\n [(Day(n=2), (1, 1, 1)),\n (Hour(n=2), (1, 1, 2, 22)),\n (Minute(n=2), (1, 1, 2, 23, 58)),\n (Second(n=2), (1, 1, 2, 23, 59, 58))],\n ids=_id_func\n)\ndef test_rsub_sub_monthly(offset, expected_date_args, calendar):\n date_type = get_date_type(calendar)\n initial = date_type(1, 1, 3)\n expected = date_type(*expected_date_args)\n result = initial - offset\n assert result == expected\n\n\[email protected]('offset', _EQ_TESTS_A, ids=_id_func)\ndef test_sub_error(offset, calendar):\n date_type = get_date_type(calendar)\n initial = date_type(1, 1, 1)\n with pytest.raises(TypeError):\n offset - initial\n\n\[email protected](\n ('a', 'b'),\n zip(_EQ_TESTS_A, _EQ_TESTS_B),\n ids=_id_func\n)\ndef test_minus_offset(a, b):\n result = b - a\n expected = a\n assert result == expected\n\n\[email protected](\n ('a', 'b'),\n list(zip(np.roll(_EQ_TESTS_A, 1), _EQ_TESTS_B)) +\n [(YearEnd(month=1), YearEnd(month=2))],\n ids=_id_func\n)\ndef test_minus_offset_error(a, b):\n with pytest.raises(TypeError):\n b - a\n\n\ndef test_days_in_month_non_december(calendar):\n date_type = get_date_type(calendar)\n reference = date_type(1, 4, 1)\n assert _days_in_month(reference) == 30\n\n\ndef test_days_in_month_december(calendar):\n if calendar == '360_day':\n expected = 30\n else:\n expected = 31\n date_type = get_date_type(calendar)\n reference = date_type(1, 12, 5)\n assert _days_in_month(reference) == expected\n\n\[email protected](\n ('initial_date_args', 'offset', 'expected_date_args'),\n [((1, 1, 1), MonthBegin(), (1, 2, 1)),\n ((1, 1, 1), MonthBegin(n=2), (1, 3, 1)),\n ((1, 1, 7), MonthBegin(), (1, 2, 1)),\n ((1, 1, 7), MonthBegin(n=2), (1, 3, 1)),\n ((1, 3, 1), MonthBegin(n=-1), (1, 2, 1)),\n ((1, 3, 1), MonthBegin(n=-2), (1, 1, 1)),\n ((1, 3, 3), MonthBegin(n=-1), (1, 3, 1)),\n ((1, 3, 3), MonthBegin(n=-2), (1, 2, 1)),\n ((1, 2, 1), MonthBegin(n=14), (2, 4, 1)),\n ((2, 4, 1), MonthBegin(n=-14), (1, 2, 1)),\n ((1, 1, 1, 5, 5, 5, 5), MonthBegin(), (1, 2, 1, 5, 5, 5, 5)),\n ((1, 1, 3, 5, 5, 5, 5), MonthBegin(), (1, 2, 1, 5, 5, 5, 5)),\n ((1, 1, 3, 5, 5, 5, 5), MonthBegin(n=-1), (1, 1, 1, 5, 5, 5, 5))],\n ids=_id_func\n)\ndef test_add_month_begin(\n calendar, initial_date_args, offset, expected_date_args):\n date_type = get_date_type(calendar)\n initial = date_type(*initial_date_args)\n result = initial + offset\n expected = date_type(*expected_date_args)\n assert result == expected\n\n\[email protected](\n ('initial_date_args', 'offset', 'expected_year_month',\n 'expected_sub_day'),\n [((1, 1, 1), MonthEnd(), (1, 1), ()),\n ((1, 1, 1), MonthEnd(n=2), (1, 2), ()),\n ((1, 3, 1), MonthEnd(n=-1), (1, 2), ()),\n ((1, 3, 1), MonthEnd(n=-2), (1, 1), ()),\n ((1, 2, 1), MonthEnd(n=14), (2, 3), ()),\n ((2, 4, 1), MonthEnd(n=-14), (1, 2), ()),\n ((1, 1, 1, 5, 5, 5, 5), MonthEnd(), (1, 1), (5, 5, 5, 5)),\n ((1, 2, 1, 5, 5, 5, 5), MonthEnd(n=-1), (1, 1), (5, 5, 5, 5))],\n ids=_id_func\n)\ndef test_add_month_end(\n calendar, initial_date_args, offset, expected_year_month,\n expected_sub_day\n):\n date_type = get_date_type(calendar)\n initial = date_type(*initial_date_args)\n result = initial + offset\n reference_args = expected_year_month + (1,)\n reference = date_type(*reference_args)\n\n # Here the days at the end of each month varies based on the calendar used\n expected_date_args = (expected_year_month +\n (_days_in_month(reference),) + expected_sub_day)\n expected = date_type(*expected_date_args)\n assert result == expected\n\n\[email protected](\n ('initial_year_month', 'initial_sub_day', 'offset', 'expected_year_month',\n 'expected_sub_day'),\n [((1, 1), (), MonthEnd(), (1, 2), ()),\n ((1, 1), (), MonthEnd(n=2), (1, 3), ()),\n ((1, 3), (), MonthEnd(n=-1), (1, 2), ()),\n ((1, 3), (), MonthEnd(n=-2), (1, 1), ()),\n ((1, 2), (), MonthEnd(n=14), (2, 4), ()),\n ((2, 4), (), MonthEnd(n=-14), (1, 2), ()),\n ((1, 1), (5, 5, 5, 5), MonthEnd(), (1, 2), (5, 5, 5, 5)),\n ((1, 2), (5, 5, 5, 5), MonthEnd(n=-1), (1, 1), (5, 5, 5, 5))],\n ids=_id_func\n)\ndef test_add_month_end_onOffset(\n calendar, initial_year_month, initial_sub_day, offset, expected_year_month,\n expected_sub_day\n):\n date_type = get_date_type(calendar)\n reference_args = initial_year_month + (1,)\n reference = date_type(*reference_args)\n initial_date_args = (initial_year_month + (_days_in_month(reference),) +\n initial_sub_day)\n initial = date_type(*initial_date_args)\n result = initial + offset\n reference_args = expected_year_month + (1,)\n reference = date_type(*reference_args)\n\n # Here the days at the end of each month varies based on the calendar used\n expected_date_args = (expected_year_month +\n (_days_in_month(reference),) + expected_sub_day)\n expected = date_type(*expected_date_args)\n assert result == expected\n\n\[email protected](\n ('initial_date_args', 'offset', 'expected_date_args'),\n [((1, 1, 1), YearBegin(), (2, 1, 1)),\n ((1, 1, 1), YearBegin(n=2), (3, 1, 1)),\n ((1, 1, 1), YearBegin(month=2), (1, 2, 1)),\n ((1, 1, 7), YearBegin(n=2), (3, 1, 1)),\n ((2, 2, 1), YearBegin(n=-1), (2, 1, 1)),\n ((1, 1, 2), YearBegin(n=-1), (1, 1, 1)),\n ((1, 1, 1, 5, 5, 5, 5), YearBegin(), (2, 1, 1, 5, 5, 5, 5)),\n ((2, 1, 1, 5, 5, 5, 5), YearBegin(n=-1), (1, 1, 1, 5, 5, 5, 5))],\n ids=_id_func\n)\ndef test_add_year_begin(calendar, initial_date_args, offset,\n expected_date_args):\n date_type = get_date_type(calendar)\n initial = date_type(*initial_date_args)\n result = initial + offset\n expected = date_type(*expected_date_args)\n assert result == expected\n\n\[email protected](\n ('initial_date_args', 'offset', 'expected_year_month',\n 'expected_sub_day'),\n [((1, 1, 1), YearEnd(), (1, 12), ()),\n ((1, 1, 1), YearEnd(n=2), (2, 12), ()),\n ((1, 1, 1), YearEnd(month=1), (1, 1), ()),\n ((2, 3, 1), YearEnd(n=-1), (1, 12), ()),\n ((1, 3, 1), YearEnd(n=-1, month=2), (1, 2), ()),\n ((1, 1, 1, 5, 5, 5, 5), YearEnd(), (1, 12), (5, 5, 5, 5)),\n ((1, 1, 1, 5, 5, 5, 5), YearEnd(n=2), (2, 12), (5, 5, 5, 5))],\n ids=_id_func\n)\ndef test_add_year_end(\n calendar, initial_date_args, offset, expected_year_month,\n expected_sub_day\n):\n date_type = get_date_type(calendar)\n initial = date_type(*initial_date_args)\n result = initial + offset\n reference_args = expected_year_month + (1,)\n reference = date_type(*reference_args)\n\n # Here the days at the end of each month varies based on the calendar used\n expected_date_args = (expected_year_month +\n (_days_in_month(reference),) + expected_sub_day)\n expected = date_type(*expected_date_args)\n assert result == expected\n\n\[email protected](\n ('initial_year_month', 'initial_sub_day', 'offset', 'expected_year_month',\n 'expected_sub_day'),\n [((1, 12), (), YearEnd(), (2, 12), ()),\n ((1, 12), (), YearEnd(n=2), (3, 12), ()),\n ((2, 12), (), YearEnd(n=-1), (1, 12), ()),\n ((3, 12), (), YearEnd(n=-2), (1, 12), ()),\n ((1, 1), (), YearEnd(month=2), (1, 2), ()),\n ((1, 12), (5, 5, 5, 5), YearEnd(), (2, 12), (5, 5, 5, 5)),\n ((2, 12), (5, 5, 5, 5), YearEnd(n=-1), (1, 12), (5, 5, 5, 5))],\n ids=_id_func\n)\ndef test_add_year_end_onOffset(\n calendar, initial_year_month, initial_sub_day, offset, expected_year_month,\n expected_sub_day\n):\n date_type = get_date_type(calendar)\n reference_args = initial_year_month + (1,)\n reference = date_type(*reference_args)\n initial_date_args = (initial_year_month + (_days_in_month(reference),) +\n initial_sub_day)\n initial = date_type(*initial_date_args)\n result = initial + offset\n reference_args = expected_year_month + (1,)\n reference = date_type(*reference_args)\n\n # Here the days at the end of each month varies based on the calendar used\n expected_date_args = (expected_year_month +\n (_days_in_month(reference),) + expected_sub_day)\n expected = date_type(*expected_date_args)\n assert result == expected\n\n\[email protected](\n ('initial_date_args', 'offset', 'expected_date_args'),\n [((1, 1, 1), QuarterBegin(), (1, 3, 1)),\n ((1, 1, 1), QuarterBegin(n=2), (1, 6, 1)),\n ((1, 1, 1), QuarterBegin(month=2), (1, 2, 1)),\n ((1, 1, 7), QuarterBegin(n=2), (1, 6, 1)),\n ((2, 2, 1), QuarterBegin(n=-1), (1, 12, 1)),\n ((1, 3, 2), QuarterBegin(n=-1), (1, 3, 1)),\n ((1, 1, 1, 5, 5, 5, 5), QuarterBegin(), (1, 3, 1, 5, 5, 5, 5)),\n ((2, 1, 1, 5, 5, 5, 5), QuarterBegin(n=-1), (1, 12, 1, 5, 5, 5, 5))],\n ids=_id_func\n)\ndef test_add_quarter_begin(calendar, initial_date_args, offset,\n expected_date_args):\n date_type = get_date_type(calendar)\n initial = date_type(*initial_date_args)\n result = initial + offset\n expected = date_type(*expected_date_args)\n assert result == expected\n\n\[email protected](\n ('initial_date_args', 'offset', 'expected_year_month',\n 'expected_sub_day'),\n [((1, 1, 1), QuarterEnd(), (1, 3), ()),\n ((1, 1, 1), QuarterEnd(n=2), (1, 6), ()),\n ((1, 1, 1), QuarterEnd(month=1), (1, 1), ()),\n ((2, 3, 1), QuarterEnd(n=-1), (1, 12), ()),\n ((1, 3, 1), QuarterEnd(n=-1, month=2), (1, 2), ()),\n ((1, 1, 1, 5, 5, 5, 5), QuarterEnd(), (1, 3), (5, 5, 5, 5)),\n ((1, 1, 1, 5, 5, 5, 5), QuarterEnd(n=2), (1, 6), (5, 5, 5, 5))],\n ids=_id_func\n)\ndef test_add_quarter_end(\n calendar, initial_date_args, offset, expected_year_month,\n expected_sub_day\n):\n date_type = get_date_type(calendar)\n initial = date_type(*initial_date_args)\n result = initial + offset\n reference_args = expected_year_month + (1,)\n reference = date_type(*reference_args)\n\n # Here the days at the end of each month varies based on the calendar used\n expected_date_args = (expected_year_month +\n (_days_in_month(reference),) + expected_sub_day)\n expected = date_type(*expected_date_args)\n assert result == expected\n\n\[email protected](\n ('initial_year_month', 'initial_sub_day', 'offset', 'expected_year_month',\n 'expected_sub_day'),\n [((1, 12), (), QuarterEnd(), (2, 3), ()),\n ((1, 12), (), QuarterEnd(n=2), (2, 6), ()),\n ((1, 12), (), QuarterEnd(n=-1), (1, 9), ()),\n ((1, 12), (), QuarterEnd(n=-2), (1, 6), ()),\n ((1, 1), (), QuarterEnd(month=2), (1, 2), ()),\n ((1, 12), (5, 5, 5, 5), QuarterEnd(), (2, 3), (5, 5, 5, 5)),\n ((1, 12), (5, 5, 5, 5), QuarterEnd(n=-1), (1, 9), (5, 5, 5, 5))],\n ids=_id_func\n)\ndef test_add_quarter_end_onOffset(\n calendar, initial_year_month, initial_sub_day, offset, expected_year_month,\n expected_sub_day\n):\n date_type = get_date_type(calendar)\n reference_args = initial_year_month + (1,)\n reference = date_type(*reference_args)\n initial_date_args = (initial_year_month + (_days_in_month(reference),) +\n initial_sub_day)\n initial = date_type(*initial_date_args)\n result = initial + offset\n reference_args = expected_year_month + (1,)\n reference = date_type(*reference_args)\n\n # Here the days at the end of each month varies based on the calendar used\n expected_date_args = (expected_year_month +\n (_days_in_month(reference),) + expected_sub_day)\n expected = date_type(*expected_date_args)\n assert result == expected\n\n\n# Note for all sub-monthly offsets, pandas always returns True for onOffset\[email protected](\n ('date_args', 'offset', 'expected'),\n [((1, 1, 1), MonthBegin(), True),\n ((1, 1, 1, 1), MonthBegin(), True),\n ((1, 1, 5), MonthBegin(), False),\n ((1, 1, 5), MonthEnd(), False),\n ((1, 3, 1), QuarterBegin(), True),\n ((1, 3, 1, 1), QuarterBegin(), True),\n ((1, 3, 5), QuarterBegin(), False),\n ((1, 12, 1), QuarterEnd(), False),\n ((1, 1, 1), YearBegin(), True),\n ((1, 1, 1, 1), YearBegin(), True),\n ((1, 1, 5), YearBegin(), False),\n ((1, 12, 1), YearEnd(), False),\n ((1, 1, 1), Day(), True),\n ((1, 1, 1, 1), Day(), True),\n ((1, 1, 1), Hour(), True),\n ((1, 1, 1), Minute(), True),\n ((1, 1, 1), Second(), True)],\n ids=_id_func\n)\ndef test_onOffset(calendar, date_args, offset, expected):\n date_type = get_date_type(calendar)\n date = date_type(*date_args)\n result = offset.onOffset(date)\n assert result == expected\n\n\[email protected](\n ('year_month_args', 'sub_day_args', 'offset'),\n [((1, 1), (), MonthEnd()),\n ((1, 1), (1,), MonthEnd()),\n ((1, 12), (), QuarterEnd()),\n ((1, 1), (), QuarterEnd(month=1)),\n ((1, 12), (), YearEnd()),\n ((1, 1), (), YearEnd(month=1))],\n ids=_id_func\n)\ndef test_onOffset_month_or_quarter_or_year_end(\n calendar, year_month_args, sub_day_args, offset):\n date_type = get_date_type(calendar)\n reference_args = year_month_args + (1,)\n reference = date_type(*reference_args)\n date_args = (year_month_args + (_days_in_month(reference),) +\n sub_day_args)\n date = date_type(*date_args)\n result = offset.onOffset(date)\n assert result\n\n\[email protected](\n ('offset', 'initial_date_args', 'partial_expected_date_args'),\n [(YearBegin(), (1, 3, 1), (2, 1)),\n (YearBegin(), (1, 1, 1), (1, 1)),\n (YearBegin(n=2), (1, 3, 1), (2, 1)),\n (YearBegin(n=2, month=2), (1, 3, 1), (2, 2)),\n (YearEnd(), (1, 3, 1), (1, 12)),\n (YearEnd(n=2), (1, 3, 1), (1, 12)),\n (YearEnd(n=2, month=2), (1, 3, 1), (2, 2)),\n (YearEnd(n=2, month=4), (1, 4, 30), (1, 4)),\n (QuarterBegin(), (1, 3, 2), (1, 6)),\n (QuarterBegin(), (1, 4, 1), (1, 6)),\n (QuarterBegin(n=2), (1, 4, 1), (1, 6)),\n (QuarterBegin(n=2, month=2), (1, 4, 1), (1, 5)),\n (QuarterEnd(), (1, 3, 1), (1, 3)),\n (QuarterEnd(n=2), (1, 3, 1), (1, 3)),\n (QuarterEnd(n=2, month=2), (1, 3, 1), (1, 5)),\n (QuarterEnd(n=2, month=4), (1, 4, 30), (1, 4)),\n (MonthBegin(), (1, 3, 2), (1, 4)),\n (MonthBegin(), (1, 3, 1), (1, 3)),\n (MonthBegin(n=2), (1, 3, 2), (1, 4)),\n (MonthEnd(), (1, 3, 2), (1, 3)),\n (MonthEnd(), (1, 4, 30), (1, 4)),\n (MonthEnd(n=2), (1, 3, 2), (1, 3)),\n (Day(), (1, 3, 2, 1), (1, 3, 2, 1)),\n (Hour(), (1, 3, 2, 1, 1), (1, 3, 2, 1, 1)),\n (Minute(), (1, 3, 2, 1, 1, 1), (1, 3, 2, 1, 1, 1)),\n (Second(), (1, 3, 2, 1, 1, 1, 1), (1, 3, 2, 1, 1, 1, 1))],\n ids=_id_func\n)\ndef test_rollforward(calendar, offset, initial_date_args,\n partial_expected_date_args):\n date_type = get_date_type(calendar)\n initial = date_type(*initial_date_args)\n if isinstance(offset, (MonthBegin, QuarterBegin, YearBegin)):\n expected_date_args = partial_expected_date_args + (1,)\n elif isinstance(offset, (MonthEnd, QuarterEnd, YearEnd)):\n reference_args = partial_expected_date_args + (1,)\n reference = date_type(*reference_args)\n expected_date_args = (partial_expected_date_args +\n (_days_in_month(reference),))\n else:\n expected_date_args = partial_expected_date_args\n expected = date_type(*expected_date_args)\n result = offset.rollforward(initial)\n assert result == expected\n\n\[email protected](\n ('offset', 'initial_date_args', 'partial_expected_date_args'),\n [(YearBegin(), (1, 3, 1), (1, 1)),\n (YearBegin(n=2), (1, 3, 1), (1, 1)),\n (YearBegin(n=2, month=2), (1, 3, 1), (1, 2)),\n (YearBegin(), (1, 1, 1), (1, 1)),\n (YearBegin(n=2, month=2), (1, 2, 1), (1, 2)),\n (YearEnd(), (2, 3, 1), (1, 12)),\n (YearEnd(n=2), (2, 3, 1), (1, 12)),\n (YearEnd(n=2, month=2), (2, 3, 1), (2, 2)),\n (YearEnd(month=4), (1, 4, 30), (1, 4)),\n (QuarterBegin(), (1, 3, 2), (1, 3)),\n (QuarterBegin(), (1, 4, 1), (1, 3)),\n (QuarterBegin(n=2), (1, 4, 1), (1, 3)),\n (QuarterBegin(n=2, month=2), (1, 4, 1), (1, 2)),\n (QuarterEnd(), (2, 3, 1), (1, 12)),\n (QuarterEnd(n=2), (2, 3, 1), (1, 12)),\n (QuarterEnd(n=2, month=2), (2, 3, 1), (2, 2)),\n (QuarterEnd(n=2, month=4), (1, 4, 30), (1, 4)),\n (MonthBegin(), (1, 3, 2), (1, 3)),\n (MonthBegin(n=2), (1, 3, 2), (1, 3)),\n (MonthBegin(), (1, 3, 1), (1, 3)),\n (MonthEnd(), (1, 3, 2), (1, 2)),\n (MonthEnd(n=2), (1, 3, 2), (1, 2)),\n (MonthEnd(), (1, 4, 30), (1, 4)),\n (Day(), (1, 3, 2, 1), (1, 3, 2, 1)),\n (Hour(), (1, 3, 2, 1, 1), (1, 3, 2, 1, 1)),\n (Minute(), (1, 3, 2, 1, 1, 1), (1, 3, 2, 1, 1, 1)),\n (Second(), (1, 3, 2, 1, 1, 1, 1), (1, 3, 2, 1, 1, 1, 1))],\n ids=_id_func\n)\ndef test_rollback(calendar, offset, initial_date_args,\n partial_expected_date_args):\n date_type = get_date_type(calendar)\n initial = date_type(*initial_date_args)\n if isinstance(offset, (MonthBegin, QuarterBegin, YearBegin)):\n expected_date_args = partial_expected_date_args + (1,)\n elif isinstance(offset, (MonthEnd, QuarterEnd, YearEnd)):\n reference_args = partial_expected_date_args + (1,)\n reference = date_type(*reference_args)\n expected_date_args = (partial_expected_date_args +\n (_days_in_month(reference),))\n else:\n expected_date_args = partial_expected_date_args\n expected = date_type(*expected_date_args)\n result = offset.rollback(initial)\n assert result == expected\n\n\n_CFTIME_RANGE_TESTS = [\n ('0001-01-01', '0001-01-04', None, 'D', None, False,\n [(1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 1, 4)]),\n ('0001-01-01', '0001-01-04', None, 'D', 'left', False,\n [(1, 1, 1), (1, 1, 2), (1, 1, 3)]),\n ('0001-01-01', '0001-01-04', None, 'D', 'right', False,\n [(1, 1, 2), (1, 1, 3), (1, 1, 4)]),\n ('0001-01-01T01:00:00', '0001-01-04', None, 'D', None, False,\n [(1, 1, 1, 1), (1, 1, 2, 1), (1, 1, 3, 1)]),\n ('0001-01-01T01:00:00', '0001-01-04', None, 'D', None, True,\n [(1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 1, 4)]),\n ('0001-01-01', None, 4, 'D', None, False,\n [(1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 1, 4)]),\n (None, '0001-01-04', 4, 'D', None, False,\n [(1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 1, 4)]),\n ((1, 1, 1), '0001-01-04', None, 'D', None, False,\n [(1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 1, 4)]),\n ((1, 1, 1), (1, 1, 4), None, 'D', None, False,\n [(1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 1, 4)]),\n ('0001-01-30', '0011-02-01', None, '3AS-JUN', None, False,\n [(1, 6, 1), (4, 6, 1), (7, 6, 1), (10, 6, 1)]),\n ('0001-01-04', '0001-01-01', None, 'D', None, False,\n []),\n ('0010', None, 4, YearBegin(n=-2), None, False,\n [(10, 1, 1), (8, 1, 1), (6, 1, 1), (4, 1, 1)]),\n ('0001-01-01', '0001-01-04', 4, None, None, False,\n [(1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 1, 4)]),\n ('0001-06-01', None, 4, '3QS-JUN', None, False,\n [(1, 6, 1), (2, 3, 1), (2, 12, 1), (3, 9, 1)])\n]\n\n\[email protected](\n ('start', 'end', 'periods', 'freq', 'closed', 'normalize',\n 'expected_date_args'),\n _CFTIME_RANGE_TESTS, ids=_id_func\n)\ndef test_cftime_range(\n start, end, periods, freq, closed, normalize, calendar,\n expected_date_args):\n date_type = get_date_type(calendar)\n expected_dates = [date_type(*args) for args in expected_date_args]\n\n if isinstance(start, tuple):\n start = date_type(*start)\n if isinstance(end, tuple):\n end = date_type(*end)\n\n result = cftime_range(\n start=start, end=end, periods=periods, freq=freq, closed=closed,\n normalize=normalize, calendar=calendar)\n resulting_dates = result.values\n\n assert isinstance(result, CFTimeIndex)\n\n if freq is not None:\n np.testing.assert_equal(resulting_dates, expected_dates)\n else:\n # If we create a linear range of dates using cftime.num2date\n # we will not get exact round number dates. This is because\n # datetime arithmetic in cftime is accurate approximately to\n # 1 millisecond (see https://unidata.github.io/cftime/api.html).\n deltas = resulting_dates - expected_dates\n deltas = np.array([delta.total_seconds() for delta in deltas])\n assert np.max(np.abs(deltas)) < 0.001\n\n\ndef test_cftime_range_name():\n result = cftime_range(start='2000', periods=4, name='foo')\n assert result.name == 'foo'\n\n result = cftime_range(start='2000', periods=4)\n assert result.name is None\n\n\[email protected](\n ('start', 'end', 'periods', 'freq', 'closed'),\n [(None, None, 5, 'A', None),\n ('2000', None, None, 'A', None),\n (None, '2000', None, 'A', None),\n ('2000', '2001', None, None, None),\n (None, None, None, None, None),\n ('2000', '2001', None, 'A', 'up'),\n ('2000', '2001', 5, 'A', None)]\n)\ndef test_invalid_cftime_range_inputs(start, end, periods, freq, closed):\n with pytest.raises(ValueError):\n cftime_range(start, end, periods, freq, closed=closed)\n\n\n_CALENDAR_SPECIFIC_MONTH_END_TESTS = [\n ('2M', 'noleap',\n [(2, 28), (4, 30), (6, 30), (8, 31), (10, 31), (12, 31)]),\n ('2M', 'all_leap',\n [(2, 29), (4, 30), (6, 30), (8, 31), (10, 31), (12, 31)]),\n ('2M', '360_day',\n [(2, 30), (4, 30), (6, 30), (8, 30), (10, 30), (12, 30)]),\n ('2M', 'standard',\n [(2, 29), (4, 30), (6, 30), (8, 31), (10, 31), (12, 31)]),\n ('2M', 'gregorian',\n [(2, 29), (4, 30), (6, 30), (8, 31), (10, 31), (12, 31)]),\n ('2M', 'julian',\n [(2, 29), (4, 30), (6, 30), (8, 31), (10, 31), (12, 31)])\n]\n\n\[email protected](\n ('freq', 'calendar', 'expected_month_day'),\n _CALENDAR_SPECIFIC_MONTH_END_TESTS, ids=_id_func\n)\ndef test_calendar_specific_month_end(freq, calendar, expected_month_day):\n year = 2000 # Use a leap-year to highlight calendar differences\n result = cftime_range(\n start='2000-02', end='2001', freq=freq, calendar=calendar).values\n date_type = get_date_type(calendar)\n expected = [date_type(year, *args) for args in expected_month_day]\n np.testing.assert_equal(result, expected)\n\n\[email protected](\n ('calendar', 'start', 'end', 'expected_number_of_days'),\n [('noleap', '2000', '2001', 365),\n ('all_leap', '2000', '2001', 366),\n ('360_day', '2000', '2001', 360),\n ('standard', '2000', '2001', 366),\n ('gregorian', '2000', '2001', 366),\n ('julian', '2000', '2001', 366),\n ('noleap', '2001', '2002', 365),\n ('all_leap', '2001', '2002', 366),\n ('360_day', '2001', '2002', 360),\n ('standard', '2001', '2002', 365),\n ('gregorian', '2001', '2002', 365),\n ('julian', '2001', '2002', 365)]\n)\ndef test_calendar_year_length(\n calendar, start, end, expected_number_of_days):\n result = cftime_range(start, end, freq='D', closed='left',\n calendar=calendar)\n assert len(result) == expected_number_of_days\n\n\[email protected]('freq', ['A', 'M', 'D'])\ndef test_dayofweek_after_cftime_range(freq):\n pytest.importorskip('cftime', minversion='1.0.2.1')\n result = cftime_range('2000-02-01', periods=3, freq=freq).dayofweek\n expected = pd.date_range('2000-02-01', periods=3, freq=freq).dayofweek\n np.testing.assert_array_equal(result, expected)\n\n\[email protected]('freq', ['A', 'M', 'D'])\ndef test_dayofyear_after_cftime_range(freq):\n pytest.importorskip('cftime', minversion='1.0.2.1')\n result = cftime_range('2000-02-01', periods=3, freq=freq).dayofyear\n expected = pd.date_range('2000-02-01', periods=3, freq=freq).dayofyear\n np.testing.assert_array_equal(result, expected)\n\n\ndef test_cftime_range_standard_calendar_refers_to_gregorian():\n from cftime import DatetimeGregorian\n result, = cftime_range('2000', periods=1)\n assert isinstance(result, DatetimeGregorian)\n" ]
[ [ "pandas.core.algorithms.unique", "numpy.where", "numpy.bincount" ], [ "numpy.core.defchararray.decode" ], [ "numpy.testing.assert_equal", "numpy.abs", "numpy.testing.assert_array_equal", "pandas.date_range", "numpy.roll" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [ "1.10", "1.12", "1.11", "1.19", "1.24", "1.13", "1.16", "1.9", "1.18", "1.23", "1.21", "1.22", "1.20", "1.7", "1.15", "1.14", "1.17", "1.8" ], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
kiukchung/Ax
[ "0f50d94056782d304e573c3c1dde567beb44b65a", "0f50d94056782d304e573c3c1dde567beb44b65a" ]
[ "ax/core/tests/test_experiment.py", "ax/core/map_data.py" ]
[ "#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\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 logging\nfrom typing import Type\nfrom unittest.mock import patch\n\nimport pandas as pd\nfrom ax.core.arm import Arm\nfrom ax.core.base_trial import TrialStatus\nfrom ax.core.data import Data\nfrom ax.core.experiment import Experiment\nfrom ax.core.map_data import MapData\nfrom ax.core.map_metric import MapMetric\nfrom ax.core.metric import Metric\nfrom ax.core.parameter import FixedParameter, ParameterType\nfrom ax.core.search_space import SearchSpace\nfrom ax.exceptions.core import UnsupportedError\nfrom ax.metrics.branin import BraninMetric\nfrom ax.runners.synthetic import SyntheticRunner\nfrom ax.utils.common.constants import Keys, EXPERIMENT_IS_TEST_WARNING\nfrom ax.utils.common.testutils import TestCase\nfrom ax.utils.testing.core_stubs import (\n get_arm,\n get_branin_arms,\n get_branin_optimization_config,\n get_branin_search_space,\n get_branin_experiment,\n get_branin_experiment_with_timestamp_map_metric,\n get_data,\n get_experiment,\n get_experiment_with_map_data_type,\n get_optimization_config,\n get_search_space,\n get_sobol,\n get_status_quo,\n get_scalarized_outcome_constraint,\n)\n\nDUMMY_RUN_METADATA = {\"test_run_metadata_key\": \"test_run_metadata_value\"}\n\n\nclass ExperimentTest(TestCase):\n def setUp(self):\n self.experiment = get_experiment()\n\n def _setupBraninExperiment(self, n: int) -> Experiment:\n exp = Experiment(\n name=\"test3\",\n search_space=get_branin_search_space(),\n tracking_metrics=[BraninMetric(name=\"b\", param_names=[\"x1\", \"x2\"])],\n runner=SyntheticRunner(),\n )\n batch = exp.new_batch_trial()\n batch.add_arms_and_weights(arms=get_branin_arms(n=n, seed=0))\n batch.run()\n\n batch_2 = exp.new_batch_trial()\n batch_2.add_arms_and_weights(arms=get_branin_arms(n=3 * n, seed=1))\n batch_2.run()\n return exp\n\n def testExperimentInit(self):\n self.assertEqual(self.experiment.name, \"test\")\n self.assertEqual(self.experiment.description, \"test description\")\n self.assertEqual(self.experiment.name, \"test\")\n self.assertIsNotNone(self.experiment.time_created)\n self.assertEqual(self.experiment.experiment_type, None)\n self.assertEqual(self.experiment.num_abandoned_arms, 0)\n\n def testExperimentName(self):\n self.assertTrue(self.experiment.has_name)\n self.experiment.name = None\n self.assertFalse(self.experiment.has_name)\n with self.assertRaises(ValueError):\n self.experiment.name\n self.experiment.name = \"test\"\n\n def testExperimentType(self):\n self.experiment.experiment_type = \"test\"\n self.assertEqual(self.experiment.experiment_type, \"test\")\n\n def testEq(self):\n self.assertEqual(self.experiment, self.experiment)\n\n experiment2 = Experiment(\n name=\"test2\",\n search_space=get_search_space(),\n optimization_config=get_optimization_config(),\n status_quo=get_arm(),\n description=\"test description\",\n )\n self.assertNotEqual(self.experiment, experiment2)\n\n def testDBId(self):\n self.assertIsNone(self.experiment.db_id)\n some_id = 123456789\n self.experiment.db_id = some_id\n self.assertEqual(self.experiment.db_id, some_id)\n\n def testTrackingMetricsMerge(self):\n # Tracking and optimization metrics should get merged\n # m1 is on optimization_config while m3 is not\n exp = Experiment(\n name=\"test2\",\n search_space=get_search_space(),\n optimization_config=get_optimization_config(),\n tracking_metrics=[Metric(name=\"m1\"), Metric(name=\"m3\")],\n )\n self.assertEqual(len(exp.optimization_config.metrics) + 1, len(exp.metrics))\n\n def testBasicBatchCreation(self):\n batch = self.experiment.new_batch_trial()\n self.assertEqual(len(self.experiment.trials), 1)\n self.assertEqual(self.experiment.trials[0], batch)\n\n # Try (and fail) to re-attach batch\n with self.assertRaises(ValueError):\n self.experiment._attach_trial(batch)\n\n # Try (and fail) to attach batch to another experiment\n with self.assertRaises(ValueError):\n new_exp = get_experiment()\n new_exp._attach_trial(batch)\n\n def testRepr(self):\n self.assertEqual(\"Experiment(test)\", str(self.experiment))\n\n def testBasicProperties(self):\n self.assertEqual(self.experiment.status_quo, get_status_quo())\n self.assertEqual(self.experiment.search_space, get_search_space())\n self.assertEqual(self.experiment.optimization_config, get_optimization_config())\n self.assertEqual(self.experiment.is_test, True)\n\n def testMetricSetters(self):\n # Establish current metrics size\n self.assertEqual(\n len(get_optimization_config().metrics) + 1, len(self.experiment.metrics)\n )\n\n # Add optimization config with 1 different metric\n opt_config = get_optimization_config()\n opt_config.outcome_constraints[0].metric = Metric(name=\"m3\")\n self.experiment.optimization_config = opt_config\n\n # Verify total metrics size is the same.\n self.assertEqual(\n len(get_optimization_config().metrics) + 1, len(self.experiment.metrics)\n )\n\n # Add optimization config with 1 scalarized constraint composed of 2 metrics\n opt_config = get_optimization_config()\n opt_config.outcome_constraints = opt_config.outcome_constraints + [\n get_scalarized_outcome_constraint()\n ]\n self.experiment.optimization_config = opt_config\n\n # Verify total metrics size is the same.\n self.assertEqual(len(opt_config.metrics) + 1, len(self.experiment.metrics))\n self.assertEqual(\n len(get_optimization_config().metrics) + 3, len(self.experiment.metrics)\n )\n # set back\n self.experiment.optimization_config = get_optimization_config()\n\n # Test adding new tracking metric\n self.experiment.add_tracking_metric(Metric(name=\"m4\"))\n self.assertEqual(\n len(get_optimization_config().metrics) + 2, len(self.experiment.metrics)\n )\n\n # Test adding new tracking metrics\n self.experiment.add_tracking_metrics([Metric(name=\"z1\")])\n self.assertEqual(\n len(get_optimization_config().metrics) + 3, len(self.experiment.metrics)\n )\n\n # Verify update_tracking_metric updates the metric definition\n self.assertIsNone(self.experiment.metrics[\"m4\"].lower_is_better)\n self.experiment.update_tracking_metric(Metric(name=\"m4\", lower_is_better=True))\n self.assertTrue(self.experiment.metrics[\"m4\"].lower_is_better)\n\n # Verify unable to add existing metric\n with self.assertRaises(ValueError):\n self.experiment.add_tracking_metric(Metric(name=\"m4\"))\n\n # Verify unable to add existing metric\n with self.assertRaises(ValueError):\n self.experiment.add_tracking_metrics([Metric(name=\"z1\"), Metric(name=\"m4\")])\n\n # Verify unable to add metric in optimization config\n with self.assertRaises(ValueError):\n self.experiment.add_tracking_metric(Metric(name=\"m1\"))\n\n # Verify unable to add metric in optimization config\n with self.assertRaises(ValueError):\n self.experiment.add_tracking_metrics([Metric(name=\"z2\"), Metric(name=\"m1\")])\n\n # Cannot update metric not already on experiment\n with self.assertRaises(ValueError):\n self.experiment.update_tracking_metric(Metric(name=\"m5\"))\n\n # Cannot remove metric not already on experiment\n with self.assertRaises(ValueError):\n self.experiment.remove_tracking_metric(metric_name=\"m5\")\n\n def testSearchSpaceSetter(self):\n one_param_ss = SearchSpace(parameters=[get_search_space().parameters[\"w\"]])\n\n # Verify all search space ok with no trials\n self.experiment.search_space = one_param_ss\n self.assertEqual(len(self.experiment.parameters), 1)\n\n # Reset search space and add batch to trigger validations\n self.experiment.search_space = get_search_space()\n self.experiment.new_batch_trial()\n\n # Try search space with too few parameters\n with self.assertRaises(ValueError):\n self.experiment.search_space = one_param_ss\n\n # Try search space with different type\n bad_type_ss = get_search_space()\n bad_type_ss.parameters[\"x\"]._parameter_type = ParameterType.FLOAT\n with self.assertRaises(ValueError):\n self.experiment.search_space = bad_type_ss\n\n # Try search space with additional parameters\n extra_param_ss = get_search_space()\n extra_param_ss.add_parameter(FixedParameter(\"l\", ParameterType.FLOAT, 0.5))\n with self.assertRaises(ValueError):\n self.experiment.search_space = extra_param_ss\n\n def testStatusQuoSetter(self):\n sq_parameters = self.experiment.status_quo.parameters\n self.experiment.status_quo = None\n self.assertIsNone(self.experiment.status_quo)\n\n # Verify normal update\n sq_parameters[\"w\"] = 3.5\n self.experiment.status_quo = Arm(sq_parameters)\n self.assertEqual(self.experiment.status_quo.parameters[\"w\"], 3.5)\n self.assertEqual(self.experiment.status_quo.name, \"status_quo\")\n self.assertTrue(\"status_quo\" in self.experiment.arms_by_name)\n\n # Verify all None values\n self.experiment.status_quo = Arm({n: None for n in sq_parameters.keys()})\n self.assertIsNone(self.experiment.status_quo.parameters[\"w\"])\n\n # Try extra param\n sq_parameters[\"a\"] = 4\n with self.assertRaises(ValueError):\n self.experiment.status_quo = Arm(sq_parameters)\n\n # Try wrong type\n sq_parameters.pop(\"a\")\n sq_parameters[\"w\"] = \"hello\"\n with self.assertRaises(ValueError):\n self.experiment.status_quo = Arm(sq_parameters)\n\n # Verify arms_by_signature, arms_by_name only contains status_quo\n self.assertEqual(len(self.experiment.arms_by_signature), 1)\n self.assertEqual(len(self.experiment.arms_by_name), 1)\n\n # Change status quo, verify still just 1 arm\n sq_parameters[\"w\"] = 3.6\n self.experiment.status_quo = Arm(sq_parameters)\n self.assertEqual(len(self.experiment.arms_by_signature), 1)\n self.assertEqual(len(self.experiment.arms_by_name), 1)\n\n # Make a batch, add status quo to it, then change exp status quo, verify 2 arms\n batch = self.experiment.new_batch_trial()\n batch.set_status_quo_with_weight(self.experiment.status_quo, 1)\n sq_parameters[\"w\"] = 3.7\n self.experiment.status_quo = Arm(sq_parameters)\n self.assertEqual(len(self.experiment.arms_by_signature), 2)\n self.assertEqual(len(self.experiment.arms_by_name), 2)\n self.assertEqual(self.experiment.status_quo.name, \"status_quo_e0\")\n self.assertTrue(\"status_quo_e0\" in self.experiment.arms_by_name)\n\n # Try missing param\n sq_parameters.pop(\"w\")\n with self.assertRaises(ValueError):\n self.experiment.status_quo = Arm(sq_parameters)\n\n # Actually name the status quo.\n exp = Experiment(\n name=\"test3\",\n search_space=get_branin_search_space(),\n tracking_metrics=[BraninMetric(name=\"b\", param_names=[\"x1\", \"x2\"])],\n runner=SyntheticRunner(),\n )\n batch = exp.new_batch_trial()\n arms = get_branin_arms(n=1, seed=0)\n batch.add_arms_and_weights(arms=arms)\n self.assertIsNone(exp.status_quo)\n exp.status_quo = arms[0]\n self.assertEqual(exp.status_quo.name, \"0_0\")\n\n # Try setting sq to existing arm with different name\n with self.assertRaises(ValueError):\n exp.status_quo = Arm(arms[0].parameters, name=\"new_name\")\n\n def testRegisterArm(self):\n # Create a new arm, register on experiment\n parameters = self.experiment.status_quo.parameters\n parameters[\"w\"] = 3.5\n arm = Arm(name=\"my_arm_name\", parameters=parameters)\n self.experiment._register_arm(arm)\n self.assertEqual(self.experiment.arms_by_name[arm.name], arm)\n self.assertEqual(self.experiment.arms_by_signature[arm.signature], arm)\n\n def testFetchAndStoreData(self):\n n = 10\n exp = self._setupBraninExperiment(n)\n batch = exp.trials[0]\n batch.mark_completed()\n\n # Test fetch data\n batch_data = batch.fetch_data()\n self.assertEqual(len(batch_data.df), n)\n\n exp_data = exp.fetch_data()\n exp_data2 = exp.metrics[\"b\"].fetch_experiment_data(exp)\n self.assertEqual(len(exp_data2.df), 4 * n)\n self.assertEqual(len(exp_data.df), 4 * n)\n self.assertEqual(len(exp.arms_by_name), 4 * n)\n\n # Verify that `metrics` kwarg to `experiment.fetch_data` is respected.\n exp.add_tracking_metric(Metric(name=\"not_yet_on_experiment\"))\n exp.attach_data(\n Data(\n df=pd.DataFrame.from_records(\n [\n {\n \"arm_name\": \"0_0\",\n \"metric_name\": \"not_yet_on_experiment\",\n \"mean\": 3,\n \"sem\": 0,\n \"trial_index\": 0,\n }\n ]\n )\n )\n )\n self.assertEqual(\n set(\n exp.fetch_data(metrics=[Metric(name=\"not_yet_on_experiment\")])\n .df[\"metric_name\"]\n .values\n ),\n {\"not_yet_on_experiment\"},\n )\n\n # Verify data lookup includes trials attached from `fetch_data`.\n self.assertEqual(len(exp.lookup_data_for_trial(1)[0].df), 30)\n\n # Test local storage\n t1 = exp.attach_data(batch_data)\n t2 = exp.attach_data(exp_data)\n\n full_dict = exp.data_by_trial\n self.assertEqual(len(full_dict), 2) # data for 2 trials\n self.assertEqual(len(full_dict[0]), 5) # 5 data objs for batch 0\n\n # Test retrieving original batch 0 data\n self.assertEqual(len(exp.lookup_data_for_ts(t1).df), n)\n self.assertEqual(len(exp.lookup_data_for_trial(0)[0].df), n)\n\n # Test retrieving full exp data\n self.assertEqual(len(exp.lookup_data_for_ts(t2).df), 4 * n)\n\n with self.assertRaisesRegex(ValueError, \".* for metric\"):\n exp.attach_data(batch_data, combine_with_last_data=True)\n\n self.assertEqual(len(full_dict[0]), 5) # 5 data objs for batch 0\n new_data = Data(\n df=pd.DataFrame.from_records(\n [\n {\n \"arm_name\": \"0_0\",\n \"metric_name\": \"z\",\n \"mean\": 3,\n \"sem\": 0,\n \"trial_index\": 0,\n }\n ]\n )\n )\n t3 = exp.attach_data(new_data, combine_with_last_data=True)\n # still 5 data objs, since we combined last one\n self.assertEqual(len(full_dict[0]), 5)\n self.assertIn(\"z\", exp.lookup_data_for_ts(t3).df[\"metric_name\"].tolist())\n\n # Verify we don't get the data if the trial is abandoned\n batch._status = TrialStatus.ABANDONED\n self.assertEqual(len(batch.fetch_data().df), 0)\n self.assertEqual(len(exp.fetch_data().df), 3 * n)\n\n # Verify we do get the stored data if there are an unimplemented metrics.\n del exp._data_by_trial[0][t3] # Remove attached data for nonexistent metric.\n # Remove implemented metric that is `available_while_running`\n # (and therefore not pulled from cache).\n exp.remove_tracking_metric(metric_name=\"b\")\n exp.add_tracking_metric(Metric(name=\"b\")) # Add unimplemented metric.\n batch._status = TrialStatus.COMPLETED\n # Data should be getting looked up now.\n self.assertEqual(batch.fetch_data(), exp.lookup_data_for_ts(t1))\n self.assertEqual(exp.fetch_data(), exp.lookup_data_for_ts(t1))\n metrics_in_data = set(batch.fetch_data().df[\"metric_name\"].values)\n # Data for metric \"z\" should no longer be present since we removed it.\n self.assertEqual(metrics_in_data, {\"b\"})\n\n # Verify that `metrics` kwarg to `experiment.fetch_data` is respected\n # when pulling looked-up data.\n self.assertEqual(\n exp.fetch_data(metrics=[Metric(name=\"not_on_experiment\")]), Data()\n )\n\n def testOverwriteExistingData(self):\n n = 10\n exp = self._setupBraninExperiment(n)\n\n # automatically attaches data\n data = exp.fetch_data()\n\n # can't set both combine_with_last_data and overwrite_existing_data\n with self.assertRaises(UnsupportedError):\n exp.attach_data(\n data, combine_with_last_data=True, overwrite_existing_data=True\n )\n\n # data exists for two trials\n # data has been attached once for each trial\n self.assertEqual(len(exp._data_by_trial), 2)\n self.assertEqual(len(exp._data_by_trial[0]), 1)\n self.assertEqual(len(exp._data_by_trial[1]), 1)\n\n exp.attach_data(data)\n # data has been attached twice for each trial\n self.assertEqual(len(exp._data_by_trial), 2)\n self.assertEqual(len(exp._data_by_trial[0]), 2)\n self.assertEqual(len(exp._data_by_trial[1]), 2)\n\n ts = exp.attach_data(data, overwrite_existing_data=True)\n # previous two attachment are overwritten,\n # now only one data (most recent one) per trial\n self.assertEqual(len(exp._data_by_trial), 2)\n self.assertEqual(len(exp._data_by_trial[0]), 1)\n self.assertEqual(len(exp._data_by_trial[1]), 1)\n self.assertTrue(ts in exp._data_by_trial[0])\n self.assertTrue(ts in exp._data_by_trial[1])\n\n def testEmptyMetrics(self):\n empty_experiment = Experiment(\n name=\"test_experiment\", search_space=get_search_space()\n )\n self.assertEqual(empty_experiment.num_trials, 0)\n with self.assertRaises(ValueError):\n empty_experiment.fetch_data()\n batch = empty_experiment.new_batch_trial()\n batch.mark_running(no_runner_required=True)\n self.assertEqual(empty_experiment.num_trials, 1)\n with self.assertRaises(ValueError):\n batch.fetch_data()\n empty_experiment.add_tracking_metric(Metric(name=\"ax_test_metric\"))\n self.assertTrue(empty_experiment.fetch_data().df.empty)\n empty_experiment.attach_data(get_data())\n batch.mark_completed()\n self.assertFalse(empty_experiment.fetch_data().df.empty)\n\n def testNumArmsNoDeduplication(self):\n exp = Experiment(name=\"test_experiment\", search_space=get_search_space())\n arm = get_arm()\n exp.new_batch_trial().add_arm(arm)\n trial = exp.new_batch_trial().add_arm(arm)\n self.assertEqual(exp.sum_trial_sizes, 2)\n self.assertEqual(len(exp.arms_by_name), 1)\n trial.mark_arm_abandoned(trial.arms[0].name)\n self.assertEqual(exp.num_abandoned_arms, 1)\n\n def testExperimentWithoutName(self):\n exp = Experiment(\n search_space=get_branin_search_space(),\n tracking_metrics=[BraninMetric(name=\"b\", param_names=[\"x1\", \"x2\"])],\n runner=SyntheticRunner(),\n )\n self.assertEqual(\"Experiment(None)\", str(exp))\n batch = exp.new_batch_trial()\n batch.add_arms_and_weights(arms=get_branin_arms(n=5, seed=0))\n batch.run()\n self.assertEqual(batch.run_metadata, {\"name\": \"0\"})\n\n def testExperimentRunner(self):\n original_runner = SyntheticRunner()\n self.experiment.runner = original_runner\n batch = self.experiment.new_batch_trial()\n batch.run()\n self.assertEqual(batch.runner, original_runner)\n\n # Simulate a failed run/deployment, in which the runner is attached\n # but the actual run fails, and so the trial remains CANDIDATE.\n candidate_batch = self.experiment.new_batch_trial()\n candidate_batch.run()\n candidate_batch._status = TrialStatus.CANDIDATE\n self.assertEqual(self.experiment.trials_expecting_data, [batch])\n tbs = self.experiment.trials_by_status # All statuses should be present\n self.assertEqual(len(tbs), len(TrialStatus))\n self.assertEqual(tbs[TrialStatus.RUNNING], [batch])\n self.assertEqual(tbs[TrialStatus.CANDIDATE], [candidate_batch])\n tibs = self.experiment.trial_indices_by_status\n self.assertEqual(len(tibs), len(TrialStatus))\n self.assertEqual(tibs[TrialStatus.RUNNING], {0})\n self.assertEqual(tibs[TrialStatus.CANDIDATE], {1})\n\n identifier = {\"new_runner\": True}\n new_runner = SyntheticRunner(dummy_metadata=identifier)\n\n self.experiment.reset_runners(new_runner)\n # Don't update trials that have been run.\n self.assertEqual(batch.runner, original_runner)\n # Update default runner\n self.assertEqual(self.experiment.runner, new_runner)\n # Update candidate trial runners.\n self.assertEqual(self.experiment.trials[1].runner, new_runner)\n\n def testFetchTrialsData(self):\n exp = self._setupBraninExperiment(n=5)\n batch_0 = exp.trials[0]\n batch_1 = exp.trials[1]\n batch_0.mark_completed()\n batch_1.mark_completed()\n batch_0_data = exp.fetch_trials_data(trial_indices=[0])\n self.assertEqual(set(batch_0_data.df[\"trial_index\"].values), {0})\n self.assertEqual(\n set(batch_0_data.df[\"arm_name\"].values), {a.name for a in batch_0.arms}\n )\n batch_1_data = exp.fetch_trials_data(trial_indices=[1])\n self.assertEqual(set(batch_1_data.df[\"trial_index\"].values), {1})\n self.assertEqual(\n set(batch_1_data.df[\"arm_name\"].values), {a.name for a in batch_1.arms}\n )\n self.assertEqual(\n exp.fetch_trials_data(trial_indices=[0, 1]),\n Data.from_multiple_data([batch_0_data, batch_1_data]),\n )\n\n # Since NoisyFunction metric has overwrite_existing_data = False,\n # we should have two dfs per trial now\n self.assertEqual(len(exp.data_by_trial[0]), 2)\n\n with self.assertRaisesRegex(ValueError, \".* not associated .*\"):\n exp.fetch_trials_data(trial_indices=[2])\n # Try to fetch data when there are only metrics and no attached data.\n exp.remove_tracking_metric(metric_name=\"b\") # Remove implemented metric.\n exp.add_tracking_metric(Metric(name=\"b\")) # Add unimplemented metric.\n self.assertEqual(len(exp.fetch_trials_data(trial_indices=[0]).df), 5)\n # Try fetching attached data.\n exp.attach_data(batch_0_data)\n exp.attach_data(batch_1_data)\n self.assertEqual(exp.fetch_trials_data(trial_indices=[0]), batch_0_data)\n self.assertEqual(exp.fetch_trials_data(trial_indices=[1]), batch_1_data)\n self.assertEqual(set(batch_0_data.df[\"trial_index\"].values), {0})\n self.assertEqual(\n set(batch_0_data.df[\"arm_name\"].values), {a.name for a in batch_0.arms}\n )\n\n def test_immutable_search_space_and_opt_config(self):\n mutable_exp = self._setupBraninExperiment(n=5)\n self.assertFalse(mutable_exp.immutable_search_space_and_opt_config)\n immutable_exp = Experiment(\n name=\"test4\",\n search_space=get_branin_search_space(),\n tracking_metrics=[BraninMetric(name=\"b\", param_names=[\"x1\", \"x2\"])],\n optimization_config=get_branin_optimization_config(),\n runner=SyntheticRunner(),\n properties={Keys.IMMUTABLE_SEARCH_SPACE_AND_OPT_CONF: True},\n )\n self.assertTrue(immutable_exp.immutable_search_space_and_opt_config)\n immutable_exp.new_batch_trial()\n with self.assertRaises(UnsupportedError):\n immutable_exp.optimization_config = get_branin_optimization_config()\n with self.assertRaises(UnsupportedError):\n immutable_exp.search_space = get_branin_search_space()\n\n # Check that passing the property as just a string is processed\n # correctly.\n immutable_exp_2 = Experiment(\n name=\"test4\",\n search_space=get_branin_search_space(),\n tracking_metrics=[BraninMetric(name=\"b\", param_names=[\"x1\", \"x2\"])],\n runner=SyntheticRunner(),\n properties={Keys.IMMUTABLE_SEARCH_SPACE_AND_OPT_CONF.value: True},\n )\n self.assertTrue(immutable_exp_2.immutable_search_space_and_opt_config)\n\n def test_fetch_as_class(self):\n class MyMetric(Metric):\n @property\n def fetch_multi_group_by_metric(self) -> Type[Metric]:\n return Metric\n\n m = MyMetric(name=\"test_metric\")\n exp = Experiment(\n name=\"test\",\n search_space=get_branin_search_space(),\n tracking_metrics=[m],\n runner=SyntheticRunner(),\n )\n self.assertEqual(exp._metrics_by_class(), {Metric: [m]})\n\n @patch(\n # No-op mock just to record calls to `fetch_experiment_data_multi`.\n f\"{BraninMetric.__module__}.BraninMetric.fetch_experiment_data_multi\",\n side_effect=BraninMetric.fetch_experiment_data_multi,\n )\n def test_prefer_lookup_where_possible(self, mock_fetch_exp_data_multi):\n # By default, `BraninMetric` is available while trial is running.\n exp = self._setupBraninExperiment(n=5)\n exp.fetch_data()\n # Since metric is available while trial is running, we should be\n # refetching the data and no data should be attached to experiment.\n mock_fetch_exp_data_multi.assert_called_once()\n self.assertEqual(len(exp._data_by_trial), 2)\n\n with patch(\n f\"{BraninMetric.__module__}.BraninMetric.is_available_while_running\",\n return_value=False,\n ):\n exp = self._setupBraninExperiment(n=5)\n exp.fetch_data()\n # 1. No completed trials => no fetch case.\n mock_fetch_exp_data_multi.reset_mock()\n dat = exp.fetch_data()\n mock_fetch_exp_data_multi.assert_not_called()\n # Data should be empty since there are no completed trials.\n self.assertTrue(dat.df.empty)\n\n # 2. Newly completed trials => fetch case.\n mock_fetch_exp_data_multi.reset_mock()\n exp.trials.get(0).mark_completed()\n exp.trials.get(1).mark_completed()\n dat = exp.fetch_data()\n # `fetch_experiment_data_multi` should be called N=number of trials times.\n self.assertEqual(len(mock_fetch_exp_data_multi.call_args_list), 2)\n # Data should no longer be empty since there are completed trials.\n self.assertFalse(dat.df.empty)\n # Data for two trials should get attached.\n self.assertEqual(len(exp._data_by_trial), 2)\n\n # 3. Previously fetched => look up in cache case.\n mock_fetch_exp_data_multi.reset_mock()\n # All fetched data should get cached, so no fetch should happen next time.\n exp.fetch_data()\n mock_fetch_exp_data_multi.assert_not_called()\n\n def testWarmStartFromOldExperiment(self):\n # create old_experiment\n len_old_trials = 5\n i_failed_trial = 3\n old_experiment = get_branin_experiment()\n for i_old_trial in range(len_old_trials):\n sobol_run = get_sobol(search_space=old_experiment.search_space).gen(n=1)\n trial = old_experiment.new_trial(generator_run=sobol_run)\n trial.mark_running(no_runner_required=True)\n if i_old_trial == i_failed_trial:\n trial.mark_failed()\n else:\n trial.mark_completed()\n # make metric noiseless for exact reproducibility\n old_experiment.optimization_config.objective.metric.noise_sd = 0\n old_experiment.fetch_data()\n\n # should fail if new_experiment has trials\n new_experiment = get_branin_experiment(with_trial=True)\n with self.assertRaisesRegex(ValueError, \"Experiment.*has.*trials\"):\n new_experiment.warm_start_from_old_experiment(old_experiment=old_experiment)\n\n # should fail if search spaces are different\n with self.assertRaisesRegex(ValueError, \"mismatch in search space parameters\"):\n self.experiment.warm_start_from_old_experiment(\n old_experiment=old_experiment\n )\n\n # check that all non-failed trials are copied to new_experiment\n new_experiment = get_branin_experiment()\n # make metric noiseless for exact reproducibility\n new_experiment.optimization_config.objective.metric.noise_sd = 0\n for _, trial in old_experiment.trials.items():\n trial._run_metadata = DUMMY_RUN_METADATA\n new_experiment.warm_start_from_old_experiment(\n old_experiment=old_experiment, copy_run_metadata=True\n )\n self.assertEqual(len(new_experiment.trials), len(old_experiment.trials) - 1)\n i_old_trial = 0\n for _, trial in new_experiment.trials.items():\n # skip failed trial\n i_old_trial += i_old_trial == i_failed_trial\n self.assertEqual(\n trial.arm.parameters, old_experiment.trials[i_old_trial].arm.parameters\n )\n self.assertRegex(\n trial._properties[\"source\"], \"Warm start.*Experiment.*trial\"\n )\n self.assertDictEqual(trial.run_metadata, DUMMY_RUN_METADATA)\n i_old_trial += 1\n\n # Check that the data was attached for correct trials\n old_df = old_experiment.fetch_data().df\n new_df = new_experiment.fetch_data().df\n\n self.assertEqual(len(new_df), len_old_trials - 1)\n pd.testing.assert_frame_equal(\n old_df.drop([\"arm_name\", \"trial_index\"], axis=1),\n new_df.drop([\"arm_name\", \"trial_index\"], axis=1),\n )\n\n def test_is_test_warning(self):\n experiments_module = \"ax.core.experiment\"\n with self.subTest(\"it warns on construction for a test\"):\n with self.assertLogs(experiments_module, level=logging.INFO) as logger:\n exp = Experiment(\n search_space=get_search_space(),\n is_test=True,\n )\n self.assertIn(\n f\"INFO:{experiments_module}:{EXPERIMENT_IS_TEST_WARNING}\",\n logger.output,\n )\n\n with self.subTest(\"it does not warn on construction for a non test\"):\n with self.assertLogs(experiments_module, level=logging.INFO) as logger:\n logging.getLogger(experiments_module).info(\n \"there must be at least one log or the assertLogs statement fails\"\n )\n exp = Experiment(\n search_space=get_search_space(),\n is_test=False,\n )\n self.assertNotIn(\n f\"INFO:{experiments_module}:{EXPERIMENT_IS_TEST_WARNING}\",\n logger.output,\n )\n\n with self.subTest(\"it warns on setting is_test to True\"):\n with self.assertLogs(experiments_module, level=logging.INFO) as logger:\n exp.is_test = True\n self.assertIn(\n f\"INFO:{experiments_module}:{EXPERIMENT_IS_TEST_WARNING}\",\n logger.output,\n )\n\n with self.subTest(\"it does not warn on setting is_test to False\"):\n with self.assertLogs(experiments_module, level=logging.INFO) as logger:\n logging.getLogger(experiments_module).info(\n \"there must be at least one log or the assertLogs statement fails\"\n )\n exp.is_test = False\n self.assertNotIn(\n f\"INFO:{experiments_module}:{EXPERIMENT_IS_TEST_WARNING}\",\n logger.output,\n )\n\n\nclass ExperimentWithMapDataTest(TestCase):\n def setUp(self):\n self.experiment = get_experiment_with_map_data_type()\n\n def _setupBraninExperiment(self, n: int, incremental: bool = False) -> Experiment:\n exp = get_branin_experiment_with_timestamp_map_metric(incremental=incremental)\n batch = exp.new_batch_trial()\n batch.add_arms_and_weights(arms=get_branin_arms(n=n, seed=0))\n batch.run()\n\n batch_2 = exp.new_batch_trial()\n batch_2.add_arms_and_weights(arms=get_branin_arms(n=3 * n, seed=1))\n batch_2.run()\n return exp\n\n def testFetchDataWithMapData(self):\n evaluations = {\n \"0_0\": [\n ({\"epoch\": 1}, {\"no_fetch_impl_metric\": (3.7, 0.5)}),\n ({\"epoch\": 2}, {\"no_fetch_impl_metric\": (3.8, 0.5)}),\n ({\"epoch\": 3}, {\"no_fetch_impl_metric\": (3.9, 0.5)}),\n ({\"epoch\": 4}, {\"no_fetch_impl_metric\": (4.0, 0.5)}),\n ],\n }\n\n self.experiment.add_tracking_metric(\n metric=MapMetric(name=\"no_fetch_impl_metric\")\n )\n self.experiment.new_trial()\n self.experiment.trials[0].mark_running(no_runner_required=True)\n first_epoch = MapData.from_map_evaluations(\n evaluations={\n arm_name: partial_results[0:1]\n for arm_name, partial_results in evaluations.items()\n },\n trial_index=0,\n )\n self.experiment.attach_data(first_epoch)\n remaining_epochs = MapData.from_map_evaluations(\n evaluations={\n arm_name: partial_results[1:4]\n for arm_name, partial_results in evaluations.items()\n },\n trial_index=0,\n )\n self.experiment.attach_data(remaining_epochs)\n self.experiment.trials[0].mark_completed()\n\n expected_data = remaining_epochs\n actual_data = self.experiment.lookup_data()\n self.assertEqual(expected_data, actual_data)\n\n def testFetchTrialsData(self):\n exp = self._setupBraninExperiment(n=5)\n batch_0 = exp.trials[0]\n batch_1 = exp.trials[1]\n batch_0.mark_completed()\n batch_1.mark_completed()\n batch_0_data = exp.fetch_trials_data(trial_indices=[0])\n self.assertEqual(set(batch_0_data.df[\"trial_index\"].values), {0})\n self.assertEqual(\n set(batch_0_data.df[\"arm_name\"].values), {a.name for a in batch_0.arms}\n )\n batch_1_data = exp.fetch_trials_data(trial_indices=[1])\n self.assertEqual(set(batch_1_data.df[\"trial_index\"].values), {1})\n self.assertEqual(\n set(batch_1_data.df[\"arm_name\"].values), {a.name for a in batch_1.arms}\n )\n self.assertEqual(\n exp.fetch_trials_data(trial_indices=[0, 1]),\n MapData.from_multiple_data([batch_0_data, batch_1_data]),\n )\n\n # Since NoisyFunctionMap metric has overwrite_existing_data = True,\n # we should only have one df per trial now\n self.assertEqual(len(exp.data_by_trial[0]), 1)\n\n with self.assertRaisesRegex(ValueError, \".* not associated .*\"):\n exp.fetch_trials_data(trial_indices=[2])\n # Try to fetch data when there are only metrics and no attached data.\n exp.remove_tracking_metric(metric_name=\"b\") # Remove implemented metric.\n exp.add_tracking_metric(MapMetric(name=\"b\")) # Add unimplemented metric.\n self.assertEqual(len(exp.fetch_trials_data(trial_indices=[0]).df), 30)\n # Try fetching attached data.\n exp.attach_data(batch_0_data)\n exp.attach_data(batch_1_data)\n self.assertEqual(exp.fetch_trials_data(trial_indices=[0]), batch_0_data)\n self.assertEqual(exp.fetch_trials_data(trial_indices=[1]), batch_1_data)\n self.assertEqual(set(batch_0_data.df[\"trial_index\"].values), {0})\n self.assertEqual(\n set(batch_0_data.df[\"arm_name\"].values), {a.name for a in batch_0.arms}\n )\n\n def testFetchTrialsDataIncremental(self):\n exp = self._setupBraninExperiment(n=5, incremental=True)\n\n first_data = exp.fetch_trials_data(trial_indices=[0])\n self.assertEqual(set(first_data.df[\"timestamp\"].values), {0})\n\n more_data = exp.fetch_trials_data(trial_indices=[0])\n self.assertEqual(set(more_data.df[\"timestamp\"].values), {1})\n\n # Since we're using BraninIncrementalTimestampMetric,\n # which has combine_with_last_data = True,\n # the cached data should be merged and contain both timestamps\n self.assertEqual(len(exp.data_by_trial[0]), 1)\n looked_up_data = exp.lookup_data()\n self.assertEqual(set(looked_up_data.df[\"timestamp\"].values), {0, 1})\n", "#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\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\nfrom __future__ import annotations\n\nfrom typing import Any, Dict, Iterable, List, Optional\n\nimport pandas as pd\nfrom ax.core.abstract_data import AbstractDataFrameData\nfrom ax.core.data import Data\nfrom ax.core.types import TMapTrialEvaluation\n\n\nclass MapData(AbstractDataFrameData):\n \"\"\"Class storing mapping-like results for an experiment.\n\n Mapping-like results occur whenever a metric is reported as a collection\n of results, each element corresponding to a tuple of values.\n\n The simplest case is a sequence. For instance a time series is\n a mapping from the 1-tuple `(timestamp)` to (mean, sem) results.\n\n Another example: MultiFidelity results. This is a mapping from\n `(fidelity_feature_1, ..., fidelity_feature_n)` to (mean, sem) results.\n\n The dataframe is retrieved via the `df` property. The data can be stored\n to an external store for future use by attaching it to an experiment using\n `experiment.attach_data()` (this requires a description to be set.)\n \"\"\"\n\n # Note: Although the SEM (standard error of the mean) is a required column in data,\n # downstream models can infer missing SEMs. Simply specify NaN as the SEM value,\n # either in your Metric class or in Data explicitly.\n REQUIRED_COLUMNS = {\"arm_name\", \"metric_name\", \"mean\", \"sem\"}\n\n def __init__(\n self,\n df: Optional[pd.DataFrame] = None,\n map_keys: Optional[List[str]] = None,\n description: Optional[str] = None,\n ) -> None:\n \"\"\"Init `MapData`.\n\n Args:\n df: DataFrame with underlying data, and required columns.\n map_keys: List of all elements of the Tuple that makes up the\n key in MapData.\n description: Human-readable description of data.\n\n \"\"\"\n if map_keys is None and df is not None:\n raise ValueError(\n \"map_keys may only be `None` when `df` is also None \"\n \"(an empty `MapData`).\"\n )\n self._map_keys = map_keys or []\n # Represent MapData internally as a flat `DataFrame`\n # Make an empty `DataFrame with map_keys if available`\n if df is None:\n self._df = pd.DataFrame(\n columns=self.required_columns().union(self.map_keys)\n )\n else:\n columns = set(df.columns)\n missing_columns = self.required_columns() - columns\n if missing_columns:\n raise ValueError(\n f\"Dataframe must contain required columns {list(missing_columns)}.\"\n )\n extra_columns = columns - self.supported_columns(\n extra_column_names=self.map_keys\n )\n if extra_columns:\n raise ValueError(f\"Columns {list(extra_columns)} are not supported.\")\n df = df.dropna(axis=0, how=\"all\").reset_index(drop=True)\n df = self._safecast_df(df=df, extra_column_types=self.map_key_types)\n\n # Reorder the columns for easier viewing\n col_order = [\n c for c in self.column_data_types(self.map_key_types) if c in df.columns\n ]\n self._df = df[col_order]\n self.description = description\n\n @staticmethod\n # pyre-ignore [14]: `Iterable[Data]` not a supertype of overridden parameter.\n def from_multiple_data(\n data: Iterable[MapData], subset_metrics: Optional[Iterable[str]] = None\n ) -> MapData:\n \"\"\"Combines multiple data objects into one (with the concatenated\n underlying dataframe).\n\n NOTE: if one or more data objects in the iterable is of a custom\n subclass of `MapData`, object of that class will be returned. If\n the iterable contains multiple types of `Data`, an error will be\n raised.\n\n Args:\n data: Iterable of Ax `MapData` objects to combine.\n subset_metrics: If specified, combined `MapData` will only contain\n metrics, names of which appear in this iterable,\n in the underlying dataframe.\n \"\"\"\n # Filter out empty dataframes because they may not have correct map_keys.\n data = [datum for datum in data if not datum.df.empty]\n dfs = [datum.df for datum in data if not datum.df.empty]\n\n if len(dfs) == 0:\n return MapData()\n\n if subset_metrics:\n dfs = [df.loc[df[\"metric_name\"].isin(subset_metrics)] for df in dfs]\n\n # cast to list\n data = list(data)\n if not all((type(datum) is MapData) for datum in data):\n # check if all types in iterable match the first type\n raise ValueError(\"Non-MapData in inputs.\")\n # obtain map_keys of first elt in iterable (we know it's not empty)\n map_keys = data[0].map_keys\n\n if not all((set(datum.map_keys) == set(map_keys)) for datum in data):\n raise ValueError(\"Inconsistent map_keys found in data iterable.\")\n else:\n # if all validation is passed return concatenated data.\n return MapData(df=pd.concat(dfs, axis=0, sort=True), map_keys=map_keys)\n\n @property\n def map_keys(self):\n \"\"\"Return the names of fields that together make a map key.\n\n E.g. [\"timestamp\"] for a timeseries, [\"fidelity_param_1\", \"fidelity_param_2\"]\n for a multi-fidelity set of results.\n \"\"\"\n return self._map_keys\n\n @property\n def map_key_types(self):\n return {map_key: Any for map_key in self.map_keys}\n\n def update(self, new_data: MapData) -> None:\n if not new_data.map_keys == self.map_keys:\n raise ValueError(\"Inconsistent map_keys found in new data.\")\n self._df = self.df.append(new_data.df)\n\n @staticmethod\n def from_map_evaluations(\n evaluations: Dict[str, TMapTrialEvaluation],\n trial_index: int,\n map_keys: Optional[List[str]] = None,\n ) -> MapData:\n \"\"\"\n Convert dict of mapped evaluations to an Ax MapData object\n\n Args:\n evaluations: Map from arm name to metric outcomes (itself a mapping\n of metric names to tuples of mean and optionally a SEM).\n trial_index: Trial index to which this data belongs.\n map_keys: List of all elements of the Tuple that makes up the\n key in MapData.\n\n Returns:\n Ax MapData object.\n \"\"\"\n records = [\n {\n \"arm_name\": name,\n \"metric_name\": metric_name,\n \"mean\": value[0] if isinstance(value, tuple) else value,\n \"sem\": value[1] if isinstance(value, tuple) else 0.0,\n \"trial_index\": trial_index,\n **map_dict,\n }\n for name, map_dict_and_metrics_list in evaluations.items()\n for map_dict, evaluation in map_dict_and_metrics_list\n for metric_name, value in evaluation.items()\n ]\n map_keys_list = [\n list(map_dict.keys())\n for name, map_dict_and_metrics_list in evaluations.items()\n for map_dict, evaluation in map_dict_and_metrics_list\n ]\n map_keys = map_keys or map_keys_list[0]\n if not all((set(mk) == set(map_keys)) for mk in map_keys_list):\n raise ValueError(\"Inconsistent map_key sets in evaluations.\")\n return MapData(df=pd.DataFrame(records), map_keys=map_keys)\n\n def to_standard_data(self) -> Data:\n return Data(df=self.df)\n" ]
[ [ "pandas.DataFrame.from_records" ], [ "pandas.concat", "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "0.19", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] } ]
samqws-marketing/electronicarts_ava-capture
[ "a04e5f9a7ee817317d0d58ce800eefc6bf4bd150" ]
[ "capture-node/raw_file_format_readers.py" ]
[ "# Copyright (C) 2019 Electronic Arts Inc. All rights reserved.\n\nimport os\nimport struct\nimport cv2\nimport numpy as np\n\nimport lz4.block as lz4block\n\n'''\n Example Usage:\n \n # This script extracts all frames of the recorded file test.ava and outputs them as JPG and TIF images.\n\n from raw_file_format_readers import AvaSequenceFileReader\n\n reader = AvaSequenceFileReader('test.ava')\n for i in range(reader.frame_count()):\n \n img = reader.frame_as_cv2_sRGB_8bit(i)\n cv2.imwrite('test_%04d.jpg' % i, img) # Write 8bit sRGB image as JPG\n\n img = reader.frame_as_cv2_LinearRGB_16bit(i)\n cv2.imwrite('test_%04d.tif' % i, img) # Write 16bit Linear RGB image as TIF\n\n\n'''\n\ndef Linear_to_sRGB(image):\n ''' Image has to be in the 16 bit range (0-65535.0) '''\n a = 0.055\n x = image / 65535.0\n return (np.where(x <= 0.00313066844, 0, (1 + a) * cv2.pow(x, 1 / 2.4) - a) ) * 65535.0\n\ndef resize_image(img, width=None, height=None, max_side=None, interpolation=cv2.INTER_AREA):\n original_height, original_width = img.shape[:2]\n if max_side:\n if original_height>original_width:\n height = max_side\n width = None\n else:\n width = max_side\n height = None\n\n if width and height:\n # Set width and height\n return cv2.resize(img, (width, height), interpolation=interpolation)\n if width:\n # Set width and preserve ratio\n return cv2.resize(img, (width, width*original_height//original_width), interpolation=interpolation)\n if height:\n # Set height and preserve ratio\n return cv2.resize(img, (height*original_width//original_height, height), interpolation=interpolation)\n\ndef rotate_img(img, angle):\n if angle == 180:\n return cv2.flip(cv2.flip(img,0),1)\n elif angle == 90:\n return cv2.flip(cv2.transpose(img),1)\n elif angle == -90 or angle == 270:\n return cv2.transpose(cv2.flip(img,1))\n return img\n\ndef raw_processing_to_float32_linear(raw_img, bayer, blacklevel, bitcount, kB, kG, kR, resize_max_side=None):\n\n img = raw_img\n\n # Debayer\n if bayer == 'BGGR':\n img = cv2.cvtColor(img, cv2.COLOR_BAYER_RG2RGB)\n elif bayer == 'RGGB':\n img = cv2.cvtColor(img, cv2.COLOR_BAYER_BG2RGB)\n elif bayer == 'GBRG':\n img = cv2.cvtColor(img, cv2.COLOR_BAYER_GR2RGB)\n elif bayer == 'GRBG':\n img = cv2.cvtColor(img, cv2.COLOR_BAYER_GB2RGB)\n\n # Resize Image\n if resize_max_side:\n img = resize_image(img, max_side=resize_max_side)\n\n # Black point correction\n image_bpp = (8 if img.dtype==np.uint8 else 16)\n max_value = (2 ** image_bpp - 1)\n img = np.clip(img, blacklevel, max_value) - blacklevel\n\n # # 10,12,14 bit images need to be moved from LSB to MSB\n if bitcount > 8:\n if np.uint16 != img.dtype:\n raise Exception('Images with bitcount higher than 8 should be stored as 16bit')\n img = img << (16 - bitcount)\n\n # Convert image to Float32\n if img.dtype == np.uint8 or img.dtype == np.uint16:\n img = img.astype(np.float32) / float(max_value)\n else:\n raise Exception('Unknown input image format')\n\n # Color Correction\n if len(img.shape)>2:\n # COLOR\n\n mat = np.diag(np.array([kB,kG,kR])).astype(np.float32)\n #mat = mat / np.max(mat)\n img = np.matmul(img, mat)\n\n # Image is in Linear RGB, always 32 bit float\n return img # img_float32_linearRGB\n\ndef raw_processing_to_16bit_linear(raw_img, bayer, blacklevel, bitcount, kB, kG, kR, resize_max_side=None):\n\n img = raw_img\n\n # Debayer\n if bayer == 'BGGR':\n img = cv2.cvtColor(img, cv2.COLOR_BAYER_RG2RGB)\n elif bayer == 'RGGB':\n img = cv2.cvtColor(img, cv2.COLOR_BAYER_BG2RGB)\n elif bayer == 'GBRG':\n img = cv2.cvtColor(img, cv2.COLOR_BAYER_GR2RGB)\n elif bayer == 'GRBG':\n img = cv2.cvtColor(img, cv2.COLOR_BAYER_GB2RGB)\n\n # Resize Image\n if resize_max_side:\n img = resize_image(img, max_side=resize_max_side)\n\n # Black point correction\n image_bpp = (8 if img.dtype==np.uint8 else 16)\n max_value = (2 ** image_bpp - 1)\n img = np.clip(img, blacklevel, max_value) - blacklevel\n\n # # 10,12,14 bit images need to be moved from LSB to MSB\n if bitcount > 8:\n if np.uint16 != img.dtype:\n raise Exception('Images with bitcount higher than 8 should be stored as 16bit')\n img = img << (16 - bitcount)\n\n # Color Correction\n if len(img.shape)>2:\n # COLOR\n # integer color balance\n # the image always gets upgraded to 16 bit for color correction\n if np.uint8 == img.dtype:\n # input is 8 bit color\n mat = np.diag(np.array([255*kB,255*kG,255*kR])).astype(np.uint32)\n img = np.matmul(img.astype(np.uint32), mat)\n img = np.clip(img,0,65535).astype(np.uint16)\n elif np.uint16 == img.dtype:\n # input is 16 bit color\n mat = np.diag(np.array([65535*kB,65535*kG,65535*kR])).astype(np.uint32)\n img = np.matmul(img.astype(np.uint32), mat)\n img = np.clip(img >> 16,0,65535).astype(np.uint16)\n else:\n raise Exception('Invalid bit depth for raw image')\n else:\n # GRAYSCALE\n # upgrade image to 16 bit\n if np.uint8 == img.dtype:\n img = img.astype(np.uint16) << 8\n\n # Image is in Linear RGB, always 16 bit\n return img # img_uint16_linearRGB\n\nclass AvaSequenceFileReader():\n\n def __init__(self, filename, raise_error_on_missing_frame=False):\n\n self._f = None\n self._raise_error_on_missing_frame = raise_error_on_missing_frame\n self.filename = filename\n with open(self.filename, 'rb') as f:\n\n self.file_size = os.fstat(f.fileno()).st_size\n\n # File Header\n # unsigned char magic; // 0xED\n # unsigned char version; // 1\n # unsigned char channels; // 1 or 3\n # unsigned char bitcount; // 8..16\n # unsigned int width;\n # unsigned int height;\n # unsigned int blacklevel;\n # unsigned char bayer0; // first row, first pixel\n # unsigned char bayer1; // first row, second pixel\n # unsigned char bayer2; // second row, first pixel\n # unsigned char bayer3; // second row, second pixel\n # float kR;\n # float kG;\n # float kB;\n # char compression[4];\n # unsigned long long index_start_offset; // offset un bytes from the start of the file where the index will start\n\n header_format = 'BBBBiii4sfff4sQ'\n header_size = struct.calcsize(header_format)\n\n # Read Header\n header_buffer = f.read(header_size)\n magic,version,channels,self.bitcount,self.width,self.height,self.blacklevel,self.bayer,self.kR,self.kG,self.kB,compression,index_offset = struct.unpack(header_format, header_buffer)\n\n self.bayer = self.bayer.decode(\"utf-8\")\n\n if magic != 0xED:\n raise Exception('Invalid Ava Sequence file (magic)')\n if version != 1:\n raise Exception('Invalid Ava Sequence file (version)')\n if compression.decode('utf-8')[:3] != 'LZ4':\n raise Exception('Invalid Ava Sequence file (unknown compression)')\n\n self._frame_count = (self.file_size - index_offset)//8\n self.index_offset = index_offset\n\n # Read Frame index\n index_size = self.file_size - index_offset\n f.seek(index_offset)\n self._frame_indices = np.frombuffer(f.read(index_size), dtype=np.uint64)\n\n byteperpixel = 2 if self.bitcount > 8 else 1\n self._img_data_size = byteperpixel*self.width*self.height\n\n if self._frame_indices.shape[0] != self._frame_count:\n raise Exception('Invalid Ava Sequence file (invalid index size)')\n\n def frame_count(self):\n return self._frame_count\n\n def _get_frame_offset_skip(self, frame_index, is_backward=True):\n while frame_index < self._frame_count and not self._frame_indices[frame_index]:\n frame_index = frame_index + (-1 if is_backward else 1)\n if frame_index < 0 or frame_index >= self._frame_count:\n return None\n return int(self._frame_indices[frame_index])\n\n def _compute_frame_size(self, frame_index):\n # Compute size of one frame, by looking at the index of the next frame (or the index if this is the last frame)\n offset_of_next_frame = 0\n if frame_index<self._frame_count-1:\n offset_of_next_frame = self._get_frame_offset_skip(frame_index+1, is_backward=False)\n if not offset_of_next_frame:\n offset_of_next_frame = self.index_offset\n return offset_of_next_frame - self._get_frame_offset_skip(frame_index)\n\n def _read_frame(self, index):\n\n # open .ava file if needed\n if not self._f:\n self._f = open(self.filename, 'rb', 32*1024*1024)\n\n # Read one frame from .ava file\n frame_offset = self._get_frame_offset_skip(index)\n self._f.seek(frame_offset)\n buf = self._f.read(self._compute_frame_size(index))\n\n return buf\n\n def _read_one_frame_16bit_linear(self, frame_index, resize_max_side):\n\n if frame_index<0 or frame_index>=self._frame_count:\n raise Exception('Invalid frame index %s' % frame_index)\n\n if self._raise_error_on_missing_frame and not self._frame_indices[frame_index]:\n raise Exception('Missing frame index %s' % frame_index)\n\n compressed_buffer = self._read_frame(frame_index)\n\n buffer = lz4block.decompress(compressed_buffer, uncompressed_size=self._img_data_size)\n raw_img = np.fromstring(buffer, np.uint8 if self.bitcount==8 else np.uint16).reshape((self.height,self.width))\n return raw_processing_to_16bit_linear(raw_img, self.bayer, self.blacklevel, self.bitcount, self.kB, self.kG, self.kR, resize_max_side=resize_max_side)\n\n def frame_as_cv2_sRGB_8bit(self, frame_index, resize_max_side=None, rotation_angle=0):\n img_16bit_linear = self._read_one_frame_16bit_linear(frame_index, resize_max_side=resize_max_side)\n return rotate_img((np.clip(Linear_to_sRGB(img_16bit_linear).astype(np.uint16),0,65535) >> 8).astype(np.uint8), rotation_angle)\n\n def frame_as_cv2_LinearRGB_16bit(self, frame_index, resize_max_side=None, rotation_angle=0):\n return rotate_img(self._read_one_frame_16bit_linear(frame_index, resize_max_side=resize_max_side), rotation_angle)\n\nclass AvaRawImageFileReader():\n def __init__(self, filename):\n self.filename = filename\n with open(self.filename, 'rb') as f:\n buffer = f.read()\n\n # unsigned char magic; // 0xED\n # unsigned char version; // 1\n # unsigned char channels; // 1 or 3\n # unsigned char bitcount; // 8..16\n # unsigned int width;\n # unsigned int height;\n # unsigned int blacklevel;\n # unsigned char bayer0; // first row, first pixel\n # unsigned char bayer1; // first row, second pixel\n # unsigned char bayer2; // second row, first pixel\n # unsigned char bayer3; // second row, second pixel\n # float kR;\n # float kG;\n # float kB;\n\n footer_format = 'BBBBiii4sfff'\n raw_footer_size = struct.calcsize(footer_format)\n magic,version,channels,bitcount,width,height,blacklevel,bayer,kR,kG,kB = struct.unpack(footer_format, buffer[-raw_footer_size:])\n\n bayer = bayer.decode(\"utf-8\")\n\n if magic != 0xED:\n raise Exception('Invalid Ava RAW file (magic)')\n if version != 1:\n raise Exception('Invalid Ava RAW file (version)')\n if channels != 1 and channels != 3:\n raise Exception('Invalid Ava RAW file (channels)')\n\n tif_data = buffer[:len(buffer)-raw_footer_size]\n img = cv2.imdecode(np.asarray(bytearray(tif_data), dtype=np.uint8), cv2.IMREAD_UNCHANGED)\n\n # RAW Processing\n self.img_uint16_linearRGB = raw_processing_to_16bit_linear(img,\n bayer,blacklevel,bitcount,kB,kG,kR)\n self.img_float32_linearRGB = raw_processing_to_float32_linear(img,\n bayer,blacklevel,bitcount,kB,kG,kR)\n\n def as_cv2_sRGB_8bit(self, rotation_angle=0):\n return rotate_img((np.clip(Linear_to_sRGB(self.img_uint16_linearRGB).astype(np.uint16),0,65535) >> 8).astype(np.uint8), rotation_angle)\n\n def as_cv2_LinearRGB_16bit(self, rotation_angle=0):\n return rotate_img(self.img_uint16_linearRGB, rotation_angle)\n\n def as_cv2_LinearRGB_float32(self, rotation_angle=0):\n return rotate_img(self.img_float32_linearRGB, rotation_angle)\n" ]
[ [ "numpy.array", "numpy.fromstring", "numpy.matmul", "numpy.clip" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
arielsho/Table-Fact-Checking
[ "afbf987fcaa6cc002655d3fa38f95d88e2ec4f75" ]
[ "code/run.py" ]
[ "# encoding=utf8\nimport json\nimport pandas\nimport numpy\nfrom beam_search import dynamic_programming\nfrom multiprocessing import Pool\nimport multiprocessing\nimport sys\nimport time\nimport argparse\nimport os\nfrom APIs import *\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--synthesize\", default=False, action=\"store_true\", help=\"whether to synthesize data\")\nparser.add_argument(\"--sequential\", default=False, action=\"store_true\", help=\"Whether to use sequential or distributed\")\nparser.add_argument(\"--debug\", default=False, action=\"store_true\", help=\"Whether to use debugging mode\")\nparser.add_argument(\"--part\", type=int, default=0, help=\"choose a part\")\nparser.add_argument(\"--split\", type=int, default=1, help=\"how many splits\")\nparser.add_argument(\"--output\", type=str, default=\"../all_programs\", help=\"which folder to store the results\")\nargs = parser.parse_args()\n\nwith open('../tokenized_data/full_cleaned.json') as f:\n data = json.load(f)\n\nmonths_a = ['january', 'february', 'march', 'april', 'may', 'june',\n 'july', 'august', 'september', 'october', 'november', 'december']\nmonths_b = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']\n\n\ndef isnumber(string):\n return string in [numpy.dtype('int64'), numpy.dtype('int32'), numpy.dtype('float32'), numpy.dtype('float64')]\n\n\ndef list2tuple(inputs):\n mem = []\n for s in inputs:\n mem.append(tuple(s))\n return mem\n\n\ndef split(string, option):\n if option == \"row\":\n return string.split(',')[0]\n else:\n return string.split(',')[1]\n\n\nif not args.synthesize:\n count = 0\n preprocessed = []\n for idx, table_name in enumerate(data):\n t = pandas.read_csv('../data/all_csv/{}'.format(table_name), delimiter=\"#\")\n cols = t.columns\n mapping = {i: \"num\" if isnumber(t) else \"str\" for i, t in enumerate(t.dtypes)}\n entry = data[table_name]\n caption = entry[3].split(' ')\n\n for sent, label, pos_tag in zip(entry[0], entry[1], entry[2]):\n count += 1\n inside = False\n position = False\n masked_sent = ''\n position_buf, mention_buf = '', ''\n mem_num, head_num, mem_str, head_str = [], [], [], []\n ent_index = 0\n for n in range(len(sent)):\n if sent[n] == '#':\n if position:\n if position_buf.startswith('0'):\n idx = int(split(position_buf, \"col\"))\n if mapping[idx] == 'num':\n if cols[idx] not in head_num:\n head_num.append(cols[idx])\n else:\n if cols[idx] not in head_str:\n head_str.append(cols[idx])\n else:\n row = int(split(position_buf, \"row\"))\n idx = int(split(position_buf, \"col\"))\n if idx == -1:\n pass\n else:\n if mapping[idx] == 'num':\n if mention_buf.isdigit():\n mention_buf = int(mention_buf)\n else:\n try:\n mention_buf = float(mention_buf)\n except Exception:\n import pdb\n pdb.set_trace()\n val = (cols[idx], mention_buf)\n if val not in mem_num:\n mem_num.append(val)\n else:\n if len(fuzzy_match(t, cols[idx], mention_buf)) == 0:\n val = (cols[idx], mention_buf)\n else:\n val = (cols[idx], mention_buf)\n if val not in mem_str:\n mem_str.append(val)\n masked_sent += \"<ENTITY{}>\".format(ent_index)\n ent_index += 1\n position_buf = \"\"\n mention_buf = \"\"\n inside = False\n position = False\n else:\n inside = True\n elif sent[n] == ';':\n position = True\n else:\n if position:\n position_buf += sent[n]\n elif inside:\n mention_buf += sent[n]\n else:\n masked_sent += sent[n]\n\n tokens = masked_sent.split()\n i = 0\n while i < len(tokens):\n _ = tokens[i]\n if i + 1 < len(tokens):\n if _.isdigit() and (tokens[i + 1] not in [\"thousand\", \"hundred\"]):\n num = int(_)\n i += 1\n elif _.isdigit() and tokens[i + 1] in [\"thousand\", \"hundred\"]:\n if tokens[i + 1] == \"thousand\":\n num = int(_) * 1000\n i += 2\n elif tokens[i + 1] == \"hundred\":\n num = int(_) * 100\n i += 2\n elif _ == \"a\" and tokens[i + 1] in [\"thousand\", \"hundred\"]:\n if tokens[i + 1] == \"thousand\":\n num = 1000\n i += 2\n elif tokens[i + 1] == \"hundred\":\n num = 100\n i += 2\n elif '.' in tokens[i]:\n try:\n num = float(_)\n i += 1\n except Exception:\n i += 1\n continue\n else:\n i += 1\n continue\n else:\n if _.isdigit():\n num = int(_)\n i += 1\n elif '.' in tokens[i]:\n try:\n num = float(_)\n i += 1\n except Exception:\n i += 1\n continue\n else:\n i += 1\n continue\n\n features = []\n\n if tokens[i - 2] in months_b + months_a:\n features.append(-6)\n else:\n features.append(0)\n\n if any([_ in tokens for _ in [\"than\", \"over\", \"more\", \"less\"]]):\n features.append(2)\n else:\n features.append(0)\n\n if any([_ in pos_tag for _ in [\"RBR\", \"JJR\"]]):\n features.append(1)\n else:\n features.append(0)\n\n if num > 50:\n if num > 1900 and num < 2020:\n features.append(-4)\n else:\n features.append(2)\n else:\n if num > len(t):\n features.append(2)\n else:\n features.append(0)\n\n if len(head_num) > 0:\n features.append(1)\n else:\n features.append(0)\n\n flag = False\n for h in head_num:\n if h not in map(lambda x: x[0], mem_num):\n flag = True\n\n if flag:\n features.append(2)\n else:\n features.append(0)\n\n if sum(features) >= 3:\n for h in head_num:\n if any([_ == h for _ in mem_num]):\n continue\n else:\n mem_num.append((h, num))\n elif sum(features) >= 0:\n mem_num.append((\"tmp_input\", num))\n\n for k, v in mem_num:\n if k not in head_num and k != \"tmp_input\":\n head_num.append(k)\n\n for k, v in mem_str:\n if k not in head_str:\n head_str.append(k)\n\n preprocessed.append((table_name, sent, pos_tag, masked_sent, mem_str,\n mem_num, head_str, head_num, \"nt-{}\".format(len(preprocessed)), label))\n\n length = len(preprocessed) // args.split\n for i in range(args.split):\n with open('../preprocessed_data_program/preprocessed.json'.format(i), 'w') as f:\n if i == args.split - 1:\n json.dump(preprocessed[i * length:], f, indent=2)\n else:\n json.dump(preprocessed[i * length: (i + 1) * length], f, indent=2)\n\nelse:\n with open('../preprocessed_data_program/preprocessed.json'.format(args.part), 'r') as f:\n data = json.load(f)\n\n with open('../data/complex_ids.json') as f:\n complex_ids = json.load(f)\n\n if not os.path.exists(args.output):\n os.mkdir(args.output)\n\n def func(inputs):\n table_name, sent, pos_tag, masked_sent, mem_str, mem_num, head_str, head_num, idx, labels = inputs\n t = pandas.read_csv('../data/all_csv/{}'.format(table_name), delimiter=\"#\", encoding='utf-8')\n t.fillna('')\n if args.sequential:\n res = dynamic_programming(table_name, t, sent, masked_sent, pos_tag, mem_str,\n mem_num, head_str, head_num, labels, 5, debug=True)\n print(idx, res[:-1])\n for r in res[-1]:\n print(r)\n else:\n try:\n if not os.path.exists('{}/{}.json'.format(args.output, idx)):\n res = dynamic_programming(table_name, t, sent, masked_sent, pos_tag,\n mem_str, mem_num, head_str, head_num, labels, 7)\n with open('{}/{}.json'.format(args.output, idx), 'w') as f:\n json.dump(res, f, indent=2)\n except Exception:\n print(\"failed {}, {}\".format(table_name, idx))\n\n table_name = [_[0] for _ in data]\n sent = [_[1] for _ in data]\n pos_tag = [_[2] for _ in data]\n masked_sent = [_[3] for _ in data]\n mem_str = [list2tuple(_[4]) for _ in data]\n mem_num = [list2tuple(_[5]) for _ in data]\n head_str = [_[6] for _ in data]\n head_num = [_[7] for _ in data]\n idxes = [_[8] for _ in data]\n labels = [_[9] for _ in data]\n\n if args.sequential:\n for arg in zip(table_name, sent, pos_tag, masked_sent, mem_str, mem_num, head_str, head_num, idxes, labels):\n if arg[8] in [\"nt-56710\"]:\n func(arg)\n else:\n cores = multiprocessing.cpu_count()\n print(\"Using {} cores\".format(cores))\n pool = Pool(cores)\n res = pool.map(func, zip(table_name, sent, pos_tag, masked_sent,\n mem_str, mem_num, head_str, head_num, idxes, labels))\n\n pool.close()\n pool.join()\n" ]
[ [ "numpy.dtype" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
cnvrg/Blueprints
[ "e8574063605a2dd7a4c2f4d2cc18458edb2886be", "e8574063605a2dd7a4c2f4d2cc18458edb2886be" ]
[ "Recommenders/recommenders_data_validation/data_validation.py", "Recommenders/recommenders_train_test_split/TTS.py" ]
[ "import argparse\nimport pandas as pd\nimport psutil\nimport time\nfrom cnvrg import Experiment\n\ntic=time.time()\nparser = argparse.ArgumentParser(description=\"\"\"Preprocessor\"\"\")\nparser.add_argument('-f','--filename', action='store', dest='filename', default='/data/movies_rec_sys/ratings_2.csv', required=True, help=\"\"\"string. csv topics data file\"\"\")\n# parser.add_argument('--project_dir', action='store', dest='project_dir',\n# help=\"\"\"--- For inner use of cnvrg.io ---\"\"\")\n# parser.add_argument('--output_dir', action='store', dest='output_dir',\n# help=\"\"\"--- For inner use of cnvrg.io ---\"\"\")\nargs = parser.parse_args()\nFILENAME = args.filename\ndf = pd.read_csv(FILENAME)\n#if len(df['rating'].unique()) == 2:\n# df['rating'].replace(to_replace=1,value=2,inplace=True)\n# df['rating'].replace(to_replace=0,value=1,inplace=True)\n# print(\"Changed\")\n############## check column headings #############\nheaders=['user_id','item_id']\nif not all([i in df.columns for i in headers]):\n raise Exception('Data must contain |user_id|item_id| columns!')\n\nif 'rating' in df.columns: # EXPLICIT\n print('Data is in Explicit format!')\n print(df.head())\nelse: # IMPLICIT\n print('Data is in Implicit format!')\n print(df.head())\n df['rating'] = 1\n unique_users = df['user_id'].unique()\n unique_items = df['item_id'].unique()\n for user in unique_users:\n for item in unique_items:\n if not ((df['user_id'] == user) & (df['item_id'] == item)).any(): # add negative rows\n df2 = pd.DataFrame({'user_id': [user], 'item_id': [item], 'rating': [0]})\n df = pd.concat([df, df2], ignore_index=True)\n\n\n# if(all(df.columns==headers)==False):\n#\n# # raise(\"Column headings not correct!\")\n#################### CHECK NAN #############\ndf=df.dropna()\n#################### CHECK ratings are either integers or floats #############\ntry:\n df['rating']=df['rating'].astype('float')\nexcept:\n print(\"Ratings have to be either integers or floats\")\n raise()\n########## Convert user and item ids to strings ##########\n\ndf['user_id']=df['user_id'].astype('str')\n\ndf['item_id']=df['item_id'].astype('str')\n\n#################### CHECK ratings are between -10 and 10 #############\n\nif(min(df['rating'])<-10 or max(df['rating'])>10):\n print(\"ratings have to be positive\")\n raise()\n\n##########normalize the ratings globally######### \nprint('RAM GB used:', psutil.virtual_memory()[3]/(1024 * 1024 * 1024))\n \n#Create two dataframe mapping original user id and item id to internal representation and one dataframe of the original translated ratings frame\nprocessed_dataframe=pd.DataFrame(columns=['user_id','item_id','rating'])\n\ncurrent_u_index = 0\ncurrent_i_index = 0\n\nuser = []\nitem = []\nrating = []\nraw2inner_id_users = {}\nraw2inner_id_items = {}\n# user raw id, item raw id, rating\nfor urid, irid, r in df.itertuples(index=False):\n try:\n uid = raw2inner_id_users[urid]\n except KeyError:\n uid = current_u_index\n raw2inner_id_users[urid] = current_u_index\n current_u_index += 1\n try:\n iid = raw2inner_id_items[irid]\n except KeyError:\n iid = current_i_index\n raw2inner_id_items[irid] = current_i_index\n current_i_index += 1\n \n user.append(uid)\n item.append(iid)\n rating.append(r)\ndata={'originaluser_id':raw2inner_id_users.keys(),'user_id':raw2inner_id_users.values()}\nconvertuser=pd.DataFrame(data)\n###########Total input size###########\nprint('RAM GB used:', psutil.virtual_memory()[3]/(1024 * 1024 * 1024))\n\nprint(\"number of users:\",len(data))\n\ndata={'originalitem_id':raw2inner_id_items.keys(),'item_id':raw2inner_id_items.values()}\nconvertitem=pd.DataFrame(data)\n\nprint(\"number of items:\",len(data))\n\ndata={'user_id':user,'item_id':item,'rating':rating}\nprocessed_dataframe=pd.DataFrame(data) ####create a ready to use dataframe with converted values###### \n\n\nfull = \"ratingstranslated.csv\"\nitemdict = \"itemdict.csv\" \nuserdict = \"userdict.csv\" \nprocessed_dataframe.to_csv(\"/cnvrg/{}\".format(full), index=False)\nconvertitem.to_csv(\"/cnvrg/{}\".format(itemdict), index=False)\nconvertuser.to_csv(\"/cnvrg/{}\".format(userdict), index=False)\nconvertitem.to_csv('/cnvrg/itemdict_1.csv')\nconvertuser.to_csv('/cnvrg/userdict_1.csv')\n\nprint('RAM GB used:', psutil.virtual_memory()[3]/(1024 * 1024 * 1024))\ntoc=time.time()\nprint(\"time taken:\",toc-tic)\ne = Experiment()\ne.log_param(\"dataval_ram\", psutil.virtual_memory()[3]/(1024 * 1024 * 1024))\ne.log_param(\"dataval_time\", toc-tic)", "import argparse\nimport pandas as pd\nimport psutil\nimport time\nfrom cnvrg import Experiment\n\ntic=time.time()\nparser = argparse.ArgumentParser(description=\"\"\"Preprocessor\"\"\")\nparser.add_argument('-f','--filename', action='store', dest='filename', default='/data/movies_rec_sys/ratings.csv', required=True, help=\"\"\"string. csv topics data file\"\"\")\nparser.add_argument('--project_dir', action='store', dest='project_dir',\n help=\"\"\"--- For inner use of cnvrg.io ---\"\"\")\nparser.add_argument('--output_dir', action='store', dest='output_dir',\n help=\"\"\"--- For inner use of cnvrg.io ---\"\"\")\nargs = parser.parse_args()\n#FILENAME = \"/data/\"+args.dataset_name+\"/\"+args.filename\nFILENAME = args.filename\nratings = pd.read_csv(FILENAME)\n#ratings = ratings.drop(['Unnamed: 0'], axis=1)\n#ratings['user_id'] = ratings['user_id'].astype(int)\n#ratings['item_id'] = ratings['item_id'].astype(int)\n#print(len(ratings['user_id'].unique()))\n\n#train_whole = pd.DataFrame(columns=['user_id','item_id','rating'])\n#test_whole = pd.DataFrame(columns=['user_id','item_id','rating'])\ntrain_whole = ratings.groupby('user_id', group_keys=False).apply(lambda x: x.sample(frac=0.75,random_state=1).drop_duplicates())\n\ntest_whole = ratings.merge(ratings.groupby('user_id', group_keys=False).apply(lambda x: x.sample(frac=0.75,random_state=1).drop_duplicates()), on =['user_id','item_id','rating'], how='left',indicator=True).query('`_merge` == \"left_only\"').drop('_merge', axis=1)\n\ntrain_name = \"train_whole.csv\"\ntest_name = \"test_whole.csv\"\n\nprint('test dimensions are' + str(test_whole.shape[0]) + 'and train dimensions are ' + str(train_whole.shape[0]))\ntrain_whole.to_csv(\"/cnvrg/{}\".format(train_name), index=False)\ntest_whole.to_csv(\"/cnvrg/{}\".format(test_name), index=False)\n\nprint('RAM GB used:', psutil.virtual_memory()[3]/(1024 * 1024 * 1024))\ntoc=time.time()\nprint(\"time taken:\",toc-tic)\ne = Experiment()\ne.log_param(\"tts_ram\", psutil.virtual_memory()[3]/(1024 * 1024 * 1024))\ne.log_param(\"tts_time\", toc-tic)" ]
[ [ "pandas.concat", "pandas.read_csv", "pandas.DataFrame" ], [ "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
xinxin342/mmdetection-mini
[ "dad8367880a4e321b8ac64ee95d712da44d232d9" ]
[ "mmdet/apis/inference.py" ]
[ "import matplotlib.pyplot as plt\nfrom mmdet import cv_core\nimport numpy as np\nimport torch\nfrom mmdet.cv_core.parallel import collate\nfrom mmdet.cv_core.runner import load_checkpoint\n\nfrom mmdet.datasets.pipelines import Compose\nfrom mmdet.models import build_detector\nfrom mmdet.datasets import build_dataset\n\n\ndef init_detector(config, checkpoint=None, device='cuda:0'):\n \"\"\"Initialize a detector from config file.\n\n Args:\n config (str or :obj:`mmdet.cv_core.Config`): Config file path or the config\n object.\n checkpoint (str, optional): Checkpoint path. If left as None, the model\n will not load any weights.\n\n Returns:\n nn.Module: The constructed detector.\n \"\"\"\n if isinstance(config, str):\n config = cv_core.Config.fromfile(config)\n elif not isinstance(config, cv_core.Config):\n raise TypeError('config must be a filename or Config object, '\n f'but got {type(config)}')\n config.model.pretrained = None\n model = build_detector(config.model, test_cfg=config.test_cfg)\n if checkpoint is not None:\n map_loc = 'cpu' if device == 'cpu' else None\n checkpoint = load_checkpoint(model, checkpoint, map_location=map_loc)\n if 'meta' in checkpoint and 'CLASSES' in checkpoint['meta']:\n model.CLASSES = checkpoint['meta']['CLASSES']\n else:\n dataset = build_dataset(config.data.test)\n model.CLASSES = dataset.CLASSES\n\n model.cfg = config # save the config in the model for convenience\n model.to(device)\n model.eval()\n return model\n\n\nclass LoadImage(object):\n \"\"\"A simple pipeline to load image.\"\"\"\n\n def __call__(self, results):\n \"\"\"Call function to load images into results.\n\n Args:\n results (dict): A result dict contains the file name\n of the image to be read.\n\n Returns:\n dict: ``results`` will be returned containing loaded image.\n \"\"\"\n if isinstance(results['img'], str):\n results['filename'] = results['img']\n results['ori_filename'] = results['img']\n else:\n results['filename'] = None\n results['ori_filename'] = None\n img = cv_core.imread(results['img'])\n results['img'] = img\n results['img_fields'] = ['img']\n results['img_shape'] = img.shape\n results['ori_shape'] = img.shape\n return results\n\n\ndef inference_detector(model, img):\n \"\"\"Inference image(s) with the detector.\n\n Args:\n model (nn.Module): The loaded detector.\n imgs (str/ndarray or list[str/ndarray]): Either image files or loaded\n images.\n\n Returns:\n If imgs is a str, a generator will be returned, otherwise return the\n detection results directly.\n \"\"\"\n cfg = model.cfg\n data = dict(img_info=dict(filename=img), img_prefix=None)\n # build the data pipeline\n test_pipeline = Compose(cfg.data.test.pipeline)\n data = test_pipeline(data)\n data = collate([data], samples_per_gpu=1)\n if next(model.parameters()).is_cuda:\n data['img'][0] = data['img'][0].cuda()\n data['img_metas'] = data['img_metas'][0].data\n else:\n # just get the actual data from DataContainer\n data['img_metas'] = data['img_metas'][0].data\n\n # forward the model\n with torch.no_grad():\n result = model(return_loss=False, rescale=True, **data)[0]\n return result\n\n\ndef show_result_pyplot(model, img, result, score_thr=0.3, fig_size=(15, 10)):\n \"\"\"Visualize the detection results on the image.\n\n Args:\n model (nn.Module): The loaded detector.\n img (str or np.ndarray): Image filename or loaded image.\n result (tuple[list] or list): The detection result, can be either\n (bbox, segm) or just bbox.\n score_thr (float): The threshold to visualize the bboxes and masks.\n fig_size (tuple): Figure size of the pyplot figure.\n \"\"\"\n if hasattr(model, 'module'):\n model = model.module\n img = model.show_result(img, result, score_thr=score_thr, show=False)\n cv_core.imshow(img)\n # plt.figure(figsize=fig_size)\n # plt.imshow(cv_core.bgr2rgb(img))\n # plt.show()\n" ]
[ [ "torch.no_grad" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
orivej/tensorflow
[ "5ed2fc046a9e59d7fcffc1bc7202465805618aca", "5ed2fc046a9e59d7fcffc1bc7202465805618aca", "5ed2fc046a9e59d7fcffc1bc7202465805618aca" ]
[ "tensorflow/python/data/ops/dataset_ops.py", "tensorflow/python/framework/test_util.py", "tensorflow/python/keras/layers/preprocessing/index_lookup_test.py" ]
[ "# 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\"\"\"Python wrappers for Datasets.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport abc\nimport functools\nimport sys\nimport threading\nimport warnings\nimport weakref\n\nimport numpy as np\nimport six\nfrom six.moves import queue as Queue # pylint: disable=redefined-builtin\n\nfrom tensorflow.core.framework import dataset_options_pb2\nfrom tensorflow.core.framework import graph_pb2\nfrom tensorflow.python import tf2\nfrom tensorflow.python.compat import compat as tf_compat\nfrom tensorflow.python.data.experimental.ops import distribute_options\nfrom tensorflow.python.data.experimental.ops import optimization_options\nfrom tensorflow.python.data.experimental.ops import stats_options\nfrom tensorflow.python.data.experimental.ops import threading_options\nfrom tensorflow.python.data.ops import iterator_ops\nfrom tensorflow.python.data.util import convert\nfrom tensorflow.python.data.util import nest\nfrom tensorflow.python.data.util import options as options_lib\nfrom tensorflow.python.data.util import random_seed\nfrom tensorflow.python.data.util import structure\nfrom tensorflow.python.data.util import traverse\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.eager import def_function\nfrom tensorflow.python.eager import function as eager_function\nfrom tensorflow.python.framework import auto_control_deps\nfrom tensorflow.python.framework import auto_control_deps_utils as acd_utils\nfrom tensorflow.python.framework import composite_tensor\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import function\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import random_seed as core_random_seed\nfrom tensorflow.python.framework import smart_cond\nfrom tensorflow.python.framework import sparse_tensor as sparse_tensor_lib\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.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import gen_dataset_ops\nfrom tensorflow.python.ops import gen_experimental_dataset_ops as ged_ops\nfrom tensorflow.python.ops import gen_io_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import script_ops\nfrom tensorflow.python.ops import string_ops\nfrom tensorflow.python.ops.ragged import ragged_tensor\nfrom tensorflow.python.training.tracking import base as tracking_base\nfrom tensorflow.python.training.tracking import tracking\nfrom tensorflow.python.util import deprecation\nfrom tensorflow.python.util import function_utils\nfrom tensorflow.python.util import lazy_loader\nfrom tensorflow.python.util import nest as tf_nest\nfrom tensorflow.python.util.compat import collections_abc\nfrom tensorflow.python.util.tf_export import tf_export\n\n# Loaded lazily due to a circular dependency (roughly\n# tf.function->wrap_function->dataset->autograph->tf.function).\n# TODO(b/133251390): Use a regular import.\nwrap_function = lazy_loader.LazyLoader(\n \"wrap_function\", globals(),\n \"tensorflow.python.eager.wrap_function\")\n# TODO(mdan): Create a public API for this.\nautograph_ctx = lazy_loader.LazyLoader(\n \"autograph_ctx\", globals(),\n \"tensorflow.python.autograph.core.ag_ctx\")\nautograph = lazy_loader.LazyLoader(\n \"autograph\", globals(),\n \"tensorflow.python.autograph.impl.api\")\n\nops.NotDifferentiable(\"ReduceDataset\")\n\n# A constant that can be used to enable auto-tuning.\nAUTOTUNE = -1\ntf_export(\"data.AUTOTUNE\").export_constant(__name__, \"AUTOTUNE\")\n# TODO(b/168128531): Deprecate and remove this symbol.\ntf_export(\"data.experimental.AUTOTUNE\").export_constant(__name__, \"AUTOTUNE\")\n\n# Constants representing infinite and unknown cardinalities.\nINFINITE = -1\nUNKNOWN = -2\ntf_export(\"data.INFINITE_CARDINALITY\").export_constant(__name__, \"INFINITE\")\ntf_export(\"data.UNKNOWN_CARDINALITY\").export_constant(__name__, \"UNKNOWN\")\n\n\n@tf_export(\"data.Dataset\", v1=[])\[email protected]_metaclass(abc.ABCMeta)\nclass DatasetV2(collections_abc.Iterable, tracking_base.Trackable,\n composite_tensor.CompositeTensor):\n \"\"\"Represents a potentially large set of elements.\n\n The `tf.data.Dataset` API supports writing descriptive and efficient input\n pipelines. `Dataset` usage follows a common pattern:\n\n 1. Create a source dataset from your input data.\n 2. Apply dataset transformations to preprocess the data.\n 3. Iterate over the dataset and process the elements.\n\n Iteration happens in a streaming fashion, so the full dataset does not need to\n fit into memory.\n\n Source Datasets:\n\n The simplest way to create a dataset is to create it from a python `list`:\n\n >>> dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3])\n >>> for element in dataset:\n ... print(element)\n tf.Tensor(1, shape=(), dtype=int32)\n tf.Tensor(2, shape=(), dtype=int32)\n tf.Tensor(3, shape=(), dtype=int32)\n\n To process lines from files, use `tf.data.TextLineDataset`:\n\n >>> dataset = tf.data.TextLineDataset([\"file1.txt\", \"file2.txt\"])\n\n To process records written in the `TFRecord` format, use `TFRecordDataset`:\n\n >>> dataset = tf.data.TFRecordDataset([\"file1.tfrecords\", \"file2.tfrecords\"])\n\n To create a dataset of all files matching a pattern, use\n `tf.data.Dataset.list_files`:\n\n ```python\n dataset = tf.data.Dataset.list_files(\"/path/*.txt\")\n ```\n\n See `tf.data.FixedLengthRecordDataset` and `tf.data.Dataset.from_generator`\n for more ways to create datasets.\n\n Transformations:\n\n Once you have a dataset, you can apply transformations to prepare the data for\n your model:\n\n >>> dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3])\n >>> dataset = dataset.map(lambda x: x*2)\n >>> list(dataset.as_numpy_iterator())\n [2, 4, 6]\n\n Common Terms:\n\n **Element**: A single output from calling `next()` on a dataset iterator.\n Elements may be nested structures containing multiple components. For\n example, the element `(1, (3, \"apple\"))` has one tuple nested in another\n tuple. The components are `1`, `3`, and `\"apple\"`.\n\n **Component**: The leaf in the nested structure of an element.\n\n Supported types:\n\n Elements can be nested structures of tuples, named tuples, and dictionaries.\n Note that Python lists are *not* treated as nested structures of components.\n Instead, lists are converted to tensors and treated as components. For\n example, the element `(1, [1, 2, 3])` has only two components; the tensor `1`\n and the tensor `[1, 2, 3]`. Element components can be of any type\n representable by `tf.TypeSpec`, including `tf.Tensor`, `tf.data.Dataset`,\n `tf.sparse.SparseTensor`, `tf.RaggedTensor`, and `tf.TensorArray`.\n\n ```python\n a = 1 # Integer element\n b = 2.0 # Float element\n c = (1, 2) # Tuple element with 2 components\n d = {\"a\": (2, 2), \"b\": 3} # Dict element with 3 components\n Point = collections.namedtuple(\"Point\", [\"x\", \"y\"])\n e = Point(1, 2) # Named tuple\n f = tf.data.Dataset.range(10) # Dataset element\n ```\n\n For more information,\n read [this guide](https://www.tensorflow.org/guide/data).\n \"\"\"\n\n def __init__(self, variant_tensor):\n \"\"\"Creates a DatasetV2 object.\n\n This is a difference between DatasetV1 and DatasetV2. DatasetV1 does not\n take anything in its constructor whereas in the DatasetV2, we expect\n subclasses to create a variant_tensor and pass it in to the super() call.\n\n Args:\n variant_tensor: A DT_VARIANT tensor that represents the dataset.\n \"\"\"\n self._variant_tensor_attr = variant_tensor\n weak_self = weakref.proxy(self)\n self._variant_tracker = self._track_trackable(\n _VariantTracker(\n self._variant_tensor,\n # _trace_variant_creation only works when executing eagerly, so we\n # don't want to run it immediately. We also want the _VariantTracker\n # to have a weak reference to the Dataset to avoid creating\n # reference cycles and making work for the garbage collector.\n lambda: weak_self._trace_variant_creation()()), # pylint: disable=unnecessary-lambda,protected-access\n name=\"_variant_tracker\")\n self._graph_attr = ops.get_default_graph()\n\n # Initialize the options for this dataset and its inputs.\n self._options_attr = Options()\n for input_dataset in self._inputs():\n input_options = input_dataset.options()\n if input_options is not None:\n self._options_attr = self._options_attr.merge(input_options)\n self._options_attr._set_mutable(False) # pylint: disable=protected-access\n\n @property\n def _variant_tensor(self):\n return self._variant_tensor_attr\n\n @_variant_tensor.setter\n def _variant_tensor(self, _):\n raise ValueError(\"The _variant_tensor property is read-only\")\n\n @deprecation.deprecated_args(None, \"Use external_state_policy instead\",\n \"allow_stateful\")\n def _as_serialized_graph(\n self,\n allow_stateful=None,\n strip_device_assignment=None,\n external_state_policy=distribute_options.ExternalStatePolicy.WARN):\n \"\"\"Produces serialized graph representation of the dataset.\n\n Args:\n allow_stateful: If true, we allow stateful ops to be present in the graph\n def. In that case, the state in these ops would be thrown away.\n strip_device_assignment: If true, non-local (i.e. job and task) device\n assignment is stripped from ops in the serialized graph.\n external_state_policy: The ExternalStatePolicy enum that determines how we\n handle input pipelines that depend on external state. By default, its\n set to WARN.\n\n Returns:\n A scalar `tf.Tensor` of `tf.string` type, representing this dataset as a\n serialized graph.\n \"\"\"\n if external_state_policy:\n policy = external_state_policy.value\n return gen_dataset_ops.dataset_to_graph_v2(\n self._variant_tensor,\n external_state_policy=policy,\n strip_device_assignment=strip_device_assignment)\n if strip_device_assignment:\n return gen_dataset_ops.dataset_to_graph(\n self._variant_tensor,\n allow_stateful=allow_stateful,\n strip_device_assignment=strip_device_assignment)\n return gen_dataset_ops.dataset_to_graph(\n self._variant_tensor, allow_stateful=allow_stateful)\n\n def _trace_variant_creation(self):\n \"\"\"Traces a function which outputs a variant `tf.Tensor` for this dataset.\n\n Note that creating this function involves evaluating an op, and is currently\n only supported when executing eagerly.\n\n Returns:\n A zero-argument `ConcreteFunction` which outputs a variant `tf.Tensor`.\n \"\"\"\n variant = self._variant_tensor\n if not isinstance(variant, ops.EagerTensor):\n raise NotImplementedError(\n \"Can only export Datasets which were created executing eagerly. \"\n \"Please file a feature request if this is important to you.\")\n with context.eager_mode(), ops.device(\"CPU\"):\n # pylint: disable=protected-access\n graph_def = graph_pb2.GraphDef().FromString(\n self._as_serialized_graph(external_state_policy=distribute_options\n .ExternalStatePolicy.FAIL).numpy())\n output_node_name = None\n for node in graph_def.node:\n if node.op == \"_Retval\":\n if output_node_name is not None:\n raise AssertionError(\n \"Found multiple return values from the dataset's graph, expected \"\n \"only one.\")\n output_node_name, = node.input\n if output_node_name is None:\n raise AssertionError(\"Could not find the dataset's output node.\")\n # Add functions used in this Dataset to the function's graph, since they\n # need to follow it around (and for example be added to a SavedModel which\n # references the dataset).\n variant_function = wrap_function.function_from_graph_def(\n graph_def, inputs=[], outputs=output_node_name + \":0\")\n for used_function in self._functions():\n used_function.function.add_to_graph(variant_function.graph)\n return variant_function\n\n @abc.abstractmethod\n def _inputs(self):\n \"\"\"Returns a list of the input datasets of the dataset.\"\"\"\n\n raise NotImplementedError(\"Dataset._inputs\")\n\n @property\n def _graph(self):\n return self._graph_attr\n\n @_graph.setter\n def _graph(self, _):\n raise ValueError(\"The _graph property is read-only\")\n\n def _has_captured_ref(self):\n \"\"\"Whether this dataset uses a function that captures ref variables.\n\n Returns:\n A boolean, which if true indicates that the dataset or one of its inputs\n uses a function that captures ref variables.\n \"\"\"\n if context.executing_eagerly():\n # RefVariables are not supported in eager mode\n return False\n\n def is_tensor_or_parent_ref(tensor):\n if tensor.dtype._is_ref_dtype: # pylint: disable=protected-access\n return True\n # If the captured tensor is an eager tensor, we cannot trace its inputs.\n if isinstance(tensor, ops._EagerTensorBase): # pylint: disable=protected-access\n return False\n return any(is_tensor_or_parent_ref(x) for x in tensor.op.inputs)\n\n for fn in self._functions():\n if any(is_tensor_or_parent_ref(t) for t in fn.function.captured_inputs):\n return True\n\n return any(\n [input_dataset._has_captured_ref() for input_dataset in self._inputs()]) # pylint: disable=protected-access\n\n # TODO(jsimsa): Change this to be the transitive closure of functions used\n # by this dataset and its inputs.\n def _functions(self):\n \"\"\"Returns a list of functions associated with this dataset.\n\n Returns:\n A list of `StructuredFunctionWrapper` objects.\n \"\"\"\n return []\n\n def options(self):\n \"\"\"Returns the options for this dataset and its inputs.\n\n Returns:\n A `tf.data.Options` object representing the dataset options.\n \"\"\"\n return self._options_attr\n\n def _apply_options(self):\n \"\"\"Apply options, such as optimization configuration, to the dataset.\"\"\"\n\n dataset = self\n options = self.options()\n\n # (1) Apply threading options\n if options.experimental_threading is not None:\n t_options = options.experimental_threading\n if t_options.max_intra_op_parallelism is not None:\n dataset = _MaxIntraOpParallelismDataset(\n dataset, t_options.max_intra_op_parallelism)\n if t_options.private_threadpool_size is not None:\n dataset = _PrivateThreadPoolDataset(dataset,\n t_options.private_threadpool_size)\n\n # (2) Apply autotune options\n autotune, algorithm, cpu_budget, ram_budget = options._autotune_settings() # pylint: disable=protected-access\n if autotune:\n dataset = _ModelDataset(dataset, algorithm, cpu_budget, ram_budget)\n\n # (3) Apply graph rewrite options\n # pylint: disable=protected-access\n graph_rewrites = options._graph_rewrites()\n graph_rewrite_configs = options._graph_rewrite_configs(autotune)\n # pylint: enable=protected-access\n if self._has_captured_ref():\n if graph_rewrites.enabled or graph_rewrites.default:\n warnings.warn(\n \"tf.data graph rewrites are not compatible with tf.Variable. \"\n \"The following rewrites will be disabled: %s. To enable \"\n \"rewrites, use resource variables instead by calling \"\n \"`tf.enable_resource_variables()` at the start of the program.\" %\n \", \".join(graph_rewrites.enabled + graph_rewrites.default))\n elif (graph_rewrites.enabled or graph_rewrites.default or\n (options.experimental_optimization.apply_default_optimizations # pylint: disable=g-bool-id-comparison\n is not False)):\n dataset = _OptimizeDataset(dataset, graph_rewrites.enabled,\n graph_rewrites.disabled,\n graph_rewrites.default, graph_rewrite_configs)\n\n # (4) Apply stats aggregator options\n if options.experimental_stats and options.experimental_stats.aggregator: # pylint: disable=line-too-long\n dataset = _SetStatsAggregatorDataset( # pylint: disable=protected-access\n dataset, options.experimental_stats.aggregator,\n options.experimental_stats.prefix,\n options.experimental_stats.counter_prefix)\n return dataset\n\n def __iter__(self):\n \"\"\"Creates an iterator for elements of this dataset.\n\n The returned iterator implements the Python Iterator protocol.\n\n Returns:\n An `tf.data.Iterator` for the elements of this dataset.\n\n Raises:\n RuntimeError: If not inside of tf.function and not executing eagerly.\n \"\"\"\n if context.executing_eagerly() or ops.inside_function():\n with ops.colocate_with(self._variant_tensor):\n return iterator_ops.OwnedIterator(self)\n else:\n raise RuntimeError(\"__iter__() is only supported inside of tf.function \"\n \"or when eager execution is enabled.\")\n\n def __bool__(self):\n return True # Required as __len__ is defined\n\n __nonzero__ = __bool__ # Python 2 backward compatibility\n\n def __len__(self):\n \"\"\"Returns the length of the dataset if it is known and finite.\n\n This method requires that you are running in eager mode, and that the\n length of the dataset is known and non-infinite. When the length may be\n unknown or infinite, or if you are running in graph mode, use\n `tf.data.Dataset.cardinality` instead.\n\n Returns:\n An integer representing the length of the dataset.\n\n Raises:\n RuntimeError: If the dataset length is unknown or infinite, or if eager\n execution is not enabled.\n \"\"\"\n if not context.executing_eagerly():\n raise TypeError(\"__len__() is not supported while tracing functions. \"\n \"Use `tf.data.Dataset.cardinality` instead.\")\n length = self.cardinality()\n if length.numpy() == INFINITE:\n raise TypeError(\"dataset length is infinite.\")\n if length.numpy() == UNKNOWN:\n raise TypeError(\"dataset length is unknown.\")\n return length\n\n @abc.abstractproperty\n def element_spec(self):\n \"\"\"The type specification of an element of this dataset.\n\n >>> dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3])\n >>> dataset.element_spec\n TensorSpec(shape=(), dtype=tf.int32, name=None)\n\n For more information,\n read [this guide](https://www.tensorflow.org/guide/data#dataset_structure).\n\n Returns:\n A (nested) structure of `tf.TypeSpec` objects matching the structure of an\n element of this dataset and specifying the type of individual components.\n \"\"\"\n raise NotImplementedError(\"Dataset.element_spec\")\n\n def __repr__(self):\n output_shapes = nest.map_structure(str, get_legacy_output_shapes(self))\n output_shapes = str(output_shapes).replace(\"'\", \"\")\n output_types = nest.map_structure(repr, get_legacy_output_types(self))\n output_types = str(output_types).replace(\"'\", \"\")\n return (\"<%s shapes: %s, types: %s>\" % (type(self).__name__, output_shapes,\n output_types))\n\n def as_numpy_iterator(self):\n \"\"\"Returns an iterator which converts all elements of the dataset to numpy.\n\n Use `as_numpy_iterator` to inspect the content of your dataset. To see\n element shapes and types, print dataset elements directly instead of using\n `as_numpy_iterator`.\n\n >>> dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3])\n >>> for element in dataset:\n ... print(element)\n tf.Tensor(1, shape=(), dtype=int32)\n tf.Tensor(2, shape=(), dtype=int32)\n tf.Tensor(3, shape=(), dtype=int32)\n\n This method requires that you are running in eager mode and the dataset's\n element_spec contains only `TensorSpec` components.\n\n >>> dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3])\n >>> for element in dataset.as_numpy_iterator():\n ... print(element)\n 1\n 2\n 3\n\n >>> dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3])\n >>> print(list(dataset.as_numpy_iterator()))\n [1, 2, 3]\n\n `as_numpy_iterator()` will preserve the nested structure of dataset\n elements.\n\n >>> dataset = tf.data.Dataset.from_tensor_slices({'a': ([1, 2], [3, 4]),\n ... 'b': [5, 6]})\n >>> list(dataset.as_numpy_iterator()) == [{'a': (1, 3), 'b': 5},\n ... {'a': (2, 4), 'b': 6}]\n True\n\n Returns:\n An iterable over the elements of the dataset, with their tensors converted\n to numpy arrays.\n\n Raises:\n TypeError: if an element contains a non-`Tensor` value.\n RuntimeError: if eager execution is not enabled.\n \"\"\"\n if not context.executing_eagerly():\n raise RuntimeError(\"as_numpy_iterator() is not supported while tracing \"\n \"functions\")\n for component_spec in nest.flatten(self.element_spec):\n if not isinstance(\n component_spec,\n (tensor_spec.TensorSpec, ragged_tensor.RaggedTensorSpec)):\n raise TypeError(\n \"Dataset.as_numpy_iterator() does not support datasets containing \"\n + str(component_spec.value_type))\n\n return _NumpyIterator(self)\n\n @property\n def _flat_shapes(self):\n \"\"\"Returns a list `tf.TensorShapes`s for the element tensor representation.\n\n Returns:\n A list `tf.TensorShapes`s for the element tensor representation.\n \"\"\"\n return structure.get_flat_tensor_shapes(self.element_spec)\n\n @property\n def _flat_types(self):\n \"\"\"Returns a list `tf.DType`s for the element tensor representation.\n\n Returns:\n A list `tf.DType`s for the element tensor representation.\n \"\"\"\n return structure.get_flat_tensor_types(self.element_spec)\n\n @property\n def _flat_structure(self):\n \"\"\"Helper for setting `output_shapes` and `output_types` attrs of an op.\n\n Most dataset op constructors expect `output_shapes` and `output_types`\n arguments that represent the flattened structure of an element. This helper\n function generates these attrs as a keyword argument dictionary, allowing\n `Dataset._variant_tensor` implementations to pass `**self._flat_structure`\n to the op constructor.\n\n Returns:\n A dictionary of keyword arguments that can be passed to a dataset op\n constructor.\n \"\"\"\n return {\n \"output_shapes\": self._flat_shapes,\n \"output_types\": self._flat_types,\n }\n\n @property\n def _type_spec(self):\n return DatasetSpec(self.element_spec)\n\n @staticmethod\n def from_tensors(tensors):\n \"\"\"Creates a `Dataset` with a single element, comprising the given tensors.\n\n `from_tensors` produces a dataset containing only a single element. To slice\n the input tensor into multiple elements, use `from_tensor_slices` instead.\n\n >>> dataset = tf.data.Dataset.from_tensors([1, 2, 3])\n >>> list(dataset.as_numpy_iterator())\n [array([1, 2, 3], dtype=int32)]\n >>> dataset = tf.data.Dataset.from_tensors(([1, 2, 3], 'A'))\n >>> list(dataset.as_numpy_iterator())\n [(array([1, 2, 3], dtype=int32), b'A')]\n\n >>> # You can use `from_tensors` to produce a dataset which repeats\n >>> # the same example many times.\n >>> example = tf.constant([1,2,3])\n >>> dataset = tf.data.Dataset.from_tensors(example).repeat(2)\n >>> list(dataset.as_numpy_iterator())\n [array([1, 2, 3], dtype=int32), array([1, 2, 3], dtype=int32)]\n\n Note that if `tensors` contains a NumPy array, and eager execution is not\n enabled, the values will be embedded in the graph as one or more\n `tf.constant` operations. For large datasets (> 1 GB), this can waste\n memory and run into byte limits of graph serialization. If `tensors`\n contains one or more large NumPy arrays, consider the alternative described\n in [this\n guide](https://tensorflow.org/guide/data#consuming_numpy_arrays).\n\n Args:\n tensors: A dataset \"element\". Supported values are documented\n [here](https://www.tensorflow.org/guide/data#dataset_structure).\n\n Returns:\n Dataset: A `Dataset`.\n \"\"\"\n return TensorDataset(tensors)\n\n @staticmethod\n def from_tensor_slices(tensors):\n \"\"\"Creates a `Dataset` whose elements are slices of the given tensors.\n\n The given tensors are sliced along their first dimension. This operation\n preserves the structure of the input tensors, removing the first dimension\n of each tensor and using it as the dataset dimension. All input tensors\n must have the same size in their first dimensions.\n\n >>> # Slicing a 1D tensor produces scalar tensor elements.\n >>> dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3])\n >>> list(dataset.as_numpy_iterator())\n [1, 2, 3]\n\n >>> # Slicing a 2D tensor produces 1D tensor elements.\n >>> dataset = tf.data.Dataset.from_tensor_slices([[1, 2], [3, 4]])\n >>> list(dataset.as_numpy_iterator())\n [array([1, 2], dtype=int32), array([3, 4], dtype=int32)]\n\n >>> # Slicing a tuple of 1D tensors produces tuple elements containing\n >>> # scalar tensors.\n >>> dataset = tf.data.Dataset.from_tensor_slices(([1, 2], [3, 4], [5, 6]))\n >>> list(dataset.as_numpy_iterator())\n [(1, 3, 5), (2, 4, 6)]\n\n >>> # Dictionary structure is also preserved.\n >>> dataset = tf.data.Dataset.from_tensor_slices({\"a\": [1, 2], \"b\": [3, 4]})\n >>> list(dataset.as_numpy_iterator()) == [{'a': 1, 'b': 3},\n ... {'a': 2, 'b': 4}]\n True\n\n >>> # Two tensors can be combined into one Dataset object.\n >>> features = tf.constant([[1, 3], [2, 1], [3, 3]]) # ==> 3x2 tensor\n >>> labels = tf.constant(['A', 'B', 'A']) # ==> 3x1 tensor\n >>> dataset = Dataset.from_tensor_slices((features, labels))\n >>> # Both the features and the labels tensors can be converted\n >>> # to a Dataset object separately and combined after.\n >>> features_dataset = Dataset.from_tensor_slices(features)\n >>> labels_dataset = Dataset.from_tensor_slices(labels)\n >>> dataset = Dataset.zip((features_dataset, labels_dataset))\n >>> # A batched feature and label set can be converted to a Dataset\n >>> # in similar fashion.\n >>> batched_features = tf.constant([[[1, 3], [2, 3]],\n ... [[2, 1], [1, 2]],\n ... [[3, 3], [3, 2]]], shape=(3, 2, 2))\n >>> batched_labels = tf.constant([['A', 'A'],\n ... ['B', 'B'],\n ... ['A', 'B']], shape=(3, 2, 1))\n >>> dataset = Dataset.from_tensor_slices((batched_features, batched_labels))\n >>> for element in dataset.as_numpy_iterator():\n ... print(element)\n (array([[1, 3],\n [2, 3]], dtype=int32), array([[b'A'],\n [b'A']], dtype=object))\n (array([[2, 1],\n [1, 2]], dtype=int32), array([[b'B'],\n [b'B']], dtype=object))\n (array([[3, 3],\n [3, 2]], dtype=int32), array([[b'A'],\n [b'B']], dtype=object))\n\n Note that if `tensors` contains a NumPy array, and eager execution is not\n enabled, the values will be embedded in the graph as one or more\n `tf.constant` operations. For large datasets (> 1 GB), this can waste\n memory and run into byte limits of graph serialization. If `tensors`\n contains one or more large NumPy arrays, consider the alternative described\n in [this guide](\n https://tensorflow.org/guide/data#consuming_numpy_arrays).\n\n Args:\n tensors: A dataset element, whose components have the same first\n dimension. Supported values are documented\n [here](https://www.tensorflow.org/guide/data#dataset_structure).\n\n Returns:\n Dataset: A `Dataset`.\n \"\"\"\n return TensorSliceDataset(tensors)\n\n class _GeneratorState(object):\n \"\"\"Stores outstanding iterators created from a Python generator.\n\n This class keeps track of potentially multiple iterators that may have\n been created from a generator, e.g. in the case that the dataset is\n repeated, or nested within a parallel computation.\n \"\"\"\n\n def __init__(self, generator):\n self._generator = generator\n self._lock = threading.Lock()\n self._next_id = 0 # GUARDED_BY(self._lock)\n self._args = {}\n self._iterators = {}\n\n def get_next_id(self, *args):\n with self._lock:\n ret = self._next_id\n self._next_id += 1\n self._args[ret] = args\n # NOTE(mrry): Explicitly create an array of `np.int64` because implicit\n # casting in `py_func()` will create an array of `np.int32` on Windows,\n # leading to a runtime error.\n return np.array(ret, dtype=np.int64)\n\n def get_iterator(self, iterator_id):\n try:\n return self._iterators[iterator_id]\n except KeyError:\n iterator = iter(self._generator(*self._args.pop(iterator_id)))\n self._iterators[iterator_id] = iterator\n return iterator\n\n def iterator_completed(self, iterator_id):\n del self._iterators[iterator_id]\n\n @staticmethod\n @deprecation.deprecated_args(None, \"Use output_signature instead\",\n \"output_types\", \"output_shapes\")\n def from_generator(generator,\n output_types=None,\n output_shapes=None,\n args=None,\n output_signature=None):\n \"\"\"Creates a `Dataset` whose elements are generated by `generator`.\n\n The `generator` argument must be a callable object that returns\n an object that supports the `iter()` protocol (e.g. a generator function).\n\n The elements generated by `generator` must be compatible with either the\n given `output_signature` argument or with the given `output_types` and\n (optionally) `output_shapes` arguments, whichever was specified.\n\n The recommended way to call `from_generator` is to use the\n `output_signature` argument. In this case the output will be assumed to\n consist of objects with the classes, shapes and types defined by\n `tf.TypeSpec` objects from `output_signature` argument:\n\n >>> def gen():\n ... ragged_tensor = tf.ragged.constant([[1, 2], [3]])\n ... yield 42, ragged_tensor\n >>>\n >>> dataset = tf.data.Dataset.from_generator(\n ... gen,\n ... output_signature=(\n ... tf.TensorSpec(shape=(), dtype=tf.int32),\n ... tf.RaggedTensorSpec(shape=(2, None), dtype=tf.int32)))\n >>>\n >>> list(dataset.take(1))\n [(<tf.Tensor: shape=(), dtype=int32, numpy=42>,\n <tf.RaggedTensor [[1, 2], [3]]>)]\n\n There is also a deprecated way to call `from_generator` by either with\n `output_types` argument alone or together with `output_shapes` argument.\n In this case the output of the function will be assumed to consist of\n `tf.Tensor` objects with the types defined by `output_types` and with the\n shapes which are either unknown or defined by `output_shapes`.\n\n Note: The current implementation of `Dataset.from_generator()` uses\n `tf.numpy_function` and inherits the same constraints. In particular, it\n requires the dataset and iterator related operations to be placed\n on a device in the same process as the Python program that called\n `Dataset.from_generator()`. The body of `generator` will not be\n serialized in a `GraphDef`, and you should not use this method if you\n need to serialize your model and restore it in a different environment.\n\n Note: If `generator` depends on mutable global variables or other external\n state, be aware that the runtime may invoke `generator` multiple times\n (in order to support repeating the `Dataset`) and at any time\n between the call to `Dataset.from_generator()` and the production of the\n first element from the generator. Mutating global variables or external\n state can cause undefined behavior, and we recommend that you explicitly\n cache any external state in `generator` before calling\n `Dataset.from_generator()`.\n\n Args:\n generator: A callable object that returns an object that supports the\n `iter()` protocol. If `args` is not specified, `generator` must take no\n arguments; otherwise it must take as many arguments as there are values\n in `args`.\n output_types: (Optional.) A (nested) structure of `tf.DType` objects\n corresponding to each component of an element yielded by `generator`.\n output_shapes: (Optional.) A (nested) structure of `tf.TensorShape`\n objects corresponding to each component of an element yielded by\n `generator`.\n args: (Optional.) A tuple of `tf.Tensor` objects that will be evaluated\n and passed to `generator` as NumPy-array arguments.\n output_signature: (Optional.) A (nested) structure of `tf.TypeSpec`\n objects corresponding to each component of an element yielded by\n `generator`.\n\n Returns:\n Dataset: A `Dataset`.\n \"\"\"\n if not callable(generator):\n raise TypeError(\"`generator` must be callable.\")\n\n if output_signature is not None:\n if output_types is not None:\n raise TypeError(\"`output_types` can not be used together with \"\n \"`output_signature`\")\n if output_shapes is not None:\n raise TypeError(\"`output_shapes` can not be used together with \"\n \"`output_signature`\")\n if not all(\n isinstance(_, type_spec.TypeSpec)\n for _ in nest.flatten(output_signature)):\n raise TypeError(\"All the elements of `output_signature` must be \"\n \"`tf.TypeSpec` objects.\")\n else:\n if output_types is None:\n raise TypeError(\"Either `output_signature` or `output_types` must \"\n \"be specified\")\n\n if output_signature is None:\n if output_shapes is None:\n output_shapes = nest.map_structure(\n lambda _: tensor_shape.TensorShape(None), output_types)\n else:\n output_shapes = nest.map_structure_up_to(output_types,\n tensor_shape.as_shape,\n output_shapes)\n output_signature = nest.map_structure_up_to(output_types,\n tensor_spec.TensorSpec,\n output_shapes, output_types)\n if all(\n isinstance(x, tensor_spec.TensorSpec)\n for x in nest.flatten(output_signature)):\n output_types = nest.pack_sequence_as(\n output_signature, [x.dtype for x in nest.flatten(output_signature)])\n output_shapes = nest.pack_sequence_as(\n output_signature, [x.shape for x in nest.flatten(output_signature)])\n\n if args is None:\n args = ()\n else:\n args = tuple(ops.convert_n_to_tensor(args, name=\"args\"))\n\n generator_state = DatasetV2._GeneratorState(generator)\n\n def get_iterator_id_fn(unused_dummy):\n \"\"\"Creates a unique `iterator_id` for each pass over the dataset.\n\n The returned `iterator_id` disambiguates between multiple concurrently\n existing iterators.\n\n Args:\n unused_dummy: Ignored value.\n\n Returns:\n A `tf.int64` tensor whose value uniquely identifies an iterator in\n `generator_state`.\n \"\"\"\n return script_ops.numpy_function(generator_state.get_next_id, args,\n dtypes.int64)\n\n def generator_next_fn(iterator_id_t):\n \"\"\"Generates the next element from iterator with ID `iterator_id_t`.\n\n We map this function across an infinite repetition of the\n `iterator_id_t`, and raise `StopIteration` to terminate the iteration.\n\n Args:\n iterator_id_t: A `tf.int64` tensor whose value uniquely identifies the\n iterator in `generator_state` from which to generate an element.\n\n Returns:\n The next element to generate from the iterator.\n \"\"\"\n if output_types and output_shapes:\n flattened_types = [\n dtypes.as_dtype(dt) for dt in nest.flatten(output_types)\n ]\n flattened_shapes = nest.flatten(output_shapes)\n\n def generator_py_func(iterator_id):\n \"\"\"A `py_func` that will be called to invoke the iterator.\"\"\"\n # `next()` raises `StopIteration` when there are no more\n # elements remaining to be generated.\n values = next(generator_state.get_iterator(iterator_id))\n\n # Use the same _convert function from the py_func() implementation to\n # convert the returned values to arrays early, so that we can inspect\n # their values.\n try:\n flattened_values = nest.flatten_up_to(output_types, values)\n except (TypeError, ValueError):\n six.reraise(\n TypeError,\n TypeError(\n \"`generator` yielded an element that did not match the \"\n \"expected structure. The expected structure was %s, but \"\n \"the yielded element was %s.\" % (output_types, values)),\n sys.exc_info()[2])\n ret_arrays = []\n for ret, dtype in zip(flattened_values, flattened_types):\n try:\n ret_arrays.append(\n script_ops.FuncRegistry._convert( # pylint: disable=protected-access\n ret,\n dtype=dtype.as_numpy_dtype))\n except (TypeError, ValueError):\n six.reraise(\n TypeError,\n TypeError(\n \"`generator` yielded an element that could not be \"\n \"converted to the expected type. The expected type was \"\n \"%s, but the yielded element was %s.\" %\n (dtype.name, ret)),\n sys.exc_info()[2])\n\n # Additional type and shape checking to ensure that the components of\n # the generated element match the `output_types` and `output_shapes`\n # arguments.\n for (ret_array, expected_dtype,\n expected_shape) in zip(ret_arrays, flattened_types,\n flattened_shapes):\n if ret_array.dtype != expected_dtype.as_numpy_dtype:\n raise TypeError(\n \"`generator` yielded an element of type %s where an element \"\n \"of type %s was expected.\" %\n (ret_array.dtype, expected_dtype.as_numpy_dtype))\n if not expected_shape.is_compatible_with(ret_array.shape):\n raise ValueError(\n \"`generator` yielded an element of shape %s where an element \"\n \"of shape %s was expected.\" %\n (ret_array.shape, expected_shape))\n\n return ret_arrays\n\n flat_values = script_ops.numpy_function(generator_py_func,\n [iterator_id_t],\n flattened_types)\n\n # The `py_func()` op drops the inferred shapes, so we add them back in\n # here.\n if output_shapes is not None:\n for ret_t, shape in zip(flat_values, flattened_shapes):\n ret_t.set_shape(shape)\n\n return nest.pack_sequence_as(output_types, flat_values)\n else:\n flat_output_types = structure.get_flat_tensor_types(output_signature)\n\n def generator_py_func(iterator_id):\n \"\"\"A `py_func` that will be called to invoke the iterator.\"\"\"\n # `next()` raises `StopIteration` when there are no more\n # elements remaining to be generated.\n values = next(generator_state.get_iterator(iterator_id.numpy()))\n\n try:\n values = structure.normalize_element(values, output_signature)\n except (TypeError, ValueError):\n six.reraise(\n TypeError,\n TypeError(\n \"`generator` yielded an element that did not match the \"\n \"expected structure. The expected structure was %s, but \"\n \"the yielded element was %s.\" % (output_signature, values)),\n sys.exc_info()[2])\n\n values_spec = structure.type_spec_from_value(values)\n\n if not structure.are_compatible(values_spec, output_signature):\n raise TypeError(\n \"`generator` yielded an element of %s where an element \"\n \"of %s was expected.\" % (values_spec, output_signature))\n\n return structure.to_tensor_list(output_signature, values)\n\n return script_ops._eager_py_func( # pylint: disable=protected-access\n generator_py_func,\n inp=[iterator_id_t],\n Tout=flat_output_types,\n use_tape_cache=False)\n\n def finalize_fn(iterator_id_t):\n \"\"\"Releases host-side state for the iterator with ID `iterator_id_t`.\"\"\"\n\n def finalize_py_func(iterator_id):\n generator_state.iterator_completed(iterator_id)\n # We return a dummy value so that the `finalize_fn` has a valid\n # signature.\n # NOTE(mrry): Explicitly create an array of `np.int64` because implicit\n # casting in `py_func()` will create an array of `np.int32` on Windows,\n # leading to a runtime error.\n return np.array(0, dtype=np.int64)\n\n return script_ops.numpy_function(finalize_py_func, [iterator_id_t],\n dtypes.int64)\n\n # This function associates each traversal of `generator` with a unique\n # iterator ID.\n def flat_map_fn(dummy_arg):\n # The `get_iterator_id_fn` gets a unique ID for the current instance of\n # of the generator.\n # The `generator_next_fn` gets the next element from the iterator with the\n # given ID, and raises StopIteration when that iterator contains no\n # more elements.\n return _GeneratorDataset(dummy_arg, get_iterator_id_fn, generator_next_fn,\n finalize_fn, output_signature)\n\n # A single-element dataset that, each time it is evaluated, contains a\n # freshly-generated and unique (for the returned dataset) int64\n # ID that will be used to identify the appropriate Python state, which\n # is encapsulated in `generator_state`, and captured in\n # `get_iterator_id_map_fn`.\n dummy = 0\n id_dataset = Dataset.from_tensors(dummy)\n\n # A dataset that contains all of the elements generated by a\n # single iterator created from `generator`, identified by the\n # iterator ID contained in `id_dataset`. Lifting the iteration\n # into a flat_map here enables multiple repetitions and/or nested\n # versions of the returned dataset to be created, because it forces\n # the generation of a new ID for each version.\n return id_dataset.flat_map(flat_map_fn)\n\n @staticmethod\n def range(*args, **kwargs):\n \"\"\"Creates a `Dataset` of a step-separated range of values.\n\n >>> list(Dataset.range(5).as_numpy_iterator())\n [0, 1, 2, 3, 4]\n >>> list(Dataset.range(2, 5).as_numpy_iterator())\n [2, 3, 4]\n >>> list(Dataset.range(1, 5, 2).as_numpy_iterator())\n [1, 3]\n >>> list(Dataset.range(1, 5, -2).as_numpy_iterator())\n []\n >>> list(Dataset.range(5, 1).as_numpy_iterator())\n []\n >>> list(Dataset.range(5, 1, -2).as_numpy_iterator())\n [5, 3]\n >>> list(Dataset.range(2, 5, output_type=tf.int32).as_numpy_iterator())\n [2, 3, 4]\n >>> list(Dataset.range(1, 5, 2, output_type=tf.float32).as_numpy_iterator())\n [1.0, 3.0]\n\n Args:\n *args: follows the same semantics as python's xrange.\n len(args) == 1 -> start = 0, stop = args[0], step = 1.\n len(args) == 2 -> start = args[0], stop = args[1], step = 1.\n len(args) == 3 -> start = args[0], stop = args[1], step = args[2].\n **kwargs:\n - output_type: Its expected dtype. (Optional, default: `tf.int64`).\n\n Returns:\n Dataset: A `RangeDataset`.\n\n Raises:\n ValueError: if len(args) == 0.\n \"\"\"\n return RangeDataset(*args, **kwargs)\n\n @staticmethod\n def zip(datasets):\n \"\"\"Creates a `Dataset` by zipping together the given datasets.\n\n This method has similar semantics to the built-in `zip()` function\n in Python, with the main difference being that the `datasets`\n argument can be a (nested) structure of `Dataset` objects. The supported\n nesting mechanisms are documented\n [here] (https://www.tensorflow.org/guide/data#dataset_structure).\n\n >>> # The nested structure of the `datasets` argument determines the\n >>> # structure of elements in the resulting dataset.\n >>> a = tf.data.Dataset.range(1, 4) # ==> [ 1, 2, 3 ]\n >>> b = tf.data.Dataset.range(4, 7) # ==> [ 4, 5, 6 ]\n >>> ds = tf.data.Dataset.zip((a, b))\n >>> list(ds.as_numpy_iterator())\n [(1, 4), (2, 5), (3, 6)]\n >>> ds = tf.data.Dataset.zip((b, a))\n >>> list(ds.as_numpy_iterator())\n [(4, 1), (5, 2), (6, 3)]\n >>>\n >>> # The `datasets` argument may contain an arbitrary number of datasets.\n >>> c = tf.data.Dataset.range(7, 13).batch(2) # ==> [ [7, 8],\n ... # [9, 10],\n ... # [11, 12] ]\n >>> ds = tf.data.Dataset.zip((a, b, c))\n >>> for element in ds.as_numpy_iterator():\n ... print(element)\n (1, 4, array([7, 8]))\n (2, 5, array([ 9, 10]))\n (3, 6, array([11, 12]))\n >>>\n >>> # The number of elements in the resulting dataset is the same as\n >>> # the size of the smallest dataset in `datasets`.\n >>> d = tf.data.Dataset.range(13, 15) # ==> [ 13, 14 ]\n >>> ds = tf.data.Dataset.zip((a, d))\n >>> list(ds.as_numpy_iterator())\n [(1, 13), (2, 14)]\n\n Args:\n datasets: A (nested) structure of datasets.\n\n Returns:\n Dataset: A `Dataset`.\n \"\"\"\n return ZipDataset(datasets)\n\n def concatenate(self, dataset):\n \"\"\"Creates a `Dataset` by concatenating the given dataset with this dataset.\n\n >>> a = tf.data.Dataset.range(1, 4) # ==> [ 1, 2, 3 ]\n >>> b = tf.data.Dataset.range(4, 8) # ==> [ 4, 5, 6, 7 ]\n >>> ds = a.concatenate(b)\n >>> list(ds.as_numpy_iterator())\n [1, 2, 3, 4, 5, 6, 7]\n >>> # The input dataset and dataset to be concatenated should have\n >>> # compatible element specs.\n >>> c = tf.data.Dataset.zip((a, b))\n >>> a.concatenate(c)\n Traceback (most recent call last):\n TypeError: Two datasets to concatenate have different types\n <dtype: 'int64'> and (tf.int64, tf.int64)\n >>> d = tf.data.Dataset.from_tensor_slices([\"a\", \"b\", \"c\"])\n >>> a.concatenate(d)\n Traceback (most recent call last):\n TypeError: Two datasets to concatenate have different types\n <dtype: 'int64'> and <dtype: 'string'>\n\n Args:\n dataset: `Dataset` to be concatenated.\n\n Returns:\n Dataset: A `Dataset`.\n \"\"\"\n return ConcatenateDataset(self, dataset)\n\n def prefetch(self, buffer_size):\n \"\"\"Creates a `Dataset` that prefetches elements from this dataset.\n\n Most dataset input pipelines should end with a call to `prefetch`. This\n allows later elements to be prepared while the current element is being\n processed. This often improves latency and throughput, at the cost of\n using additional memory to store prefetched elements.\n\n Note: Like other `Dataset` methods, prefetch operates on the\n elements of the input dataset. It has no concept of examples vs. batches.\n `examples.prefetch(2)` will prefetch two elements (2 examples),\n while `examples.batch(20).prefetch(2)` will prefetch 2 elements\n (2 batches, of 20 examples each).\n\n >>> dataset = tf.data.Dataset.range(3)\n >>> dataset = dataset.prefetch(2)\n >>> list(dataset.as_numpy_iterator())\n [0, 1, 2]\n\n Args:\n buffer_size: A `tf.int64` scalar `tf.Tensor`, representing the maximum\n number of elements that will be buffered when prefetching. If the value\n `tf.data.AUTOTUNE` is used, then the buffer size is dynamically tuned.\n Returns:\n Dataset: A `Dataset`.\n \"\"\"\n return PrefetchDataset(self, buffer_size)\n\n @staticmethod\n def list_files(file_pattern, shuffle=None, seed=None):\n \"\"\"A dataset of all files matching one or more glob patterns.\n\n The `file_pattern` argument should be a small number of glob patterns.\n If your filenames have already been globbed, use\n `Dataset.from_tensor_slices(filenames)` instead, as re-globbing every\n filename with `list_files` may result in poor performance with remote\n storage systems.\n\n Note: The default behavior of this method is to return filenames in\n a non-deterministic random shuffled order. Pass a `seed` or `shuffle=False`\n to get results in a deterministic order.\n\n Example:\n If we had the following files on our filesystem:\n\n - /path/to/dir/a.txt\n - /path/to/dir/b.py\n - /path/to/dir/c.py\n\n If we pass \"/path/to/dir/*.py\" as the directory, the dataset\n would produce:\n\n - /path/to/dir/b.py\n - /path/to/dir/c.py\n\n Args:\n file_pattern: A string, a list of strings, or a `tf.Tensor` of string type\n (scalar or vector), representing the filename glob (i.e. shell wildcard)\n pattern(s) that will be matched.\n shuffle: (Optional.) If `True`, the file names will be shuffled randomly.\n Defaults to `True`.\n seed: (Optional.) A `tf.int64` scalar `tf.Tensor`, representing the random\n seed that will be used to create the distribution. See\n `tf.random.set_seed` for behavior.\n\n Returns:\n Dataset: A `Dataset` of strings corresponding to file names.\n \"\"\"\n with ops.name_scope(\"list_files\"):\n if shuffle is None:\n shuffle = True\n file_pattern = ops.convert_to_tensor(\n file_pattern, dtype=dtypes.string, name=\"file_pattern\")\n matching_files = gen_io_ops.matching_files(file_pattern)\n\n # Raise an exception if `file_pattern` does not match any files.\n condition = math_ops.greater(array_ops.shape(matching_files)[0], 0,\n name=\"match_not_empty\")\n\n message = math_ops.add(\n \"No files matched pattern: \",\n string_ops.reduce_join(file_pattern, separator=\", \"), name=\"message\")\n\n assert_not_empty = control_flow_ops.Assert(\n condition, [message], summarize=1, name=\"assert_not_empty\")\n with ops.control_dependencies([assert_not_empty]):\n matching_files = array_ops.identity(matching_files)\n\n dataset = Dataset.from_tensor_slices(matching_files)\n if shuffle:\n # NOTE(mrry): The shuffle buffer size must be greater than zero, but the\n # list of files might be empty.\n buffer_size = math_ops.maximum(\n array_ops.shape(matching_files, out_type=dtypes.int64)[0], 1)\n dataset = dataset.shuffle(buffer_size, seed=seed)\n return dataset\n\n def repeat(self, count=None):\n \"\"\"Repeats this dataset so each original value is seen `count` times.\n\n >>> dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3])\n >>> dataset = dataset.repeat(3)\n >>> list(dataset.as_numpy_iterator())\n [1, 2, 3, 1, 2, 3, 1, 2, 3]\n\n Note: If this dataset is a function of global state (e.g. a random number\n generator), then different repetitions may produce different elements.\n\n Args:\n count: (Optional.) A `tf.int64` scalar `tf.Tensor`, representing the\n number of times the dataset should be repeated. The default behavior (if\n `count` is `None` or `-1`) is for the dataset be repeated indefinitely.\n\n Returns:\n Dataset: A `Dataset`.\n \"\"\"\n return RepeatDataset(self, count)\n\n def enumerate(self, start=0):\n \"\"\"Enumerates the elements of this dataset.\n\n It is similar to python's `enumerate`.\n\n >>> dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3])\n >>> dataset = dataset.enumerate(start=5)\n >>> for element in dataset.as_numpy_iterator():\n ... print(element)\n (5, 1)\n (6, 2)\n (7, 3)\n\n >>> # The (nested) structure of the input dataset determines the\n >>> # structure of elements in the resulting dataset.\n >>> dataset = tf.data.Dataset.from_tensor_slices([(7, 8), (9, 10)])\n >>> dataset = dataset.enumerate()\n >>> for element in dataset.as_numpy_iterator():\n ... print(element)\n (0, array([7, 8], dtype=int32))\n (1, array([ 9, 10], dtype=int32))\n\n Args:\n start: A `tf.int64` scalar `tf.Tensor`, representing the start value for\n enumeration.\n\n Returns:\n Dataset: A `Dataset`.\n \"\"\"\n\n max_value = np.iinfo(dtypes.int64.as_numpy_dtype).max\n return Dataset.zip((Dataset.range(start, max_value), self))\n\n def shuffle(self, buffer_size, seed=None, reshuffle_each_iteration=None):\n \"\"\"Randomly shuffles the elements of this dataset.\n\n This dataset fills a buffer with `buffer_size` elements, then randomly\n samples elements from this buffer, replacing the selected elements with new\n elements. For perfect shuffling, a buffer size greater than or equal to the\n full size of the dataset is required.\n\n For instance, if your dataset contains 10,000 elements but `buffer_size` is\n set to 1,000, then `shuffle` will initially select a random element from\n only the first 1,000 elements in the buffer. Once an element is selected,\n its space in the buffer is replaced by the next (i.e. 1,001-st) element,\n maintaining the 1,000 element buffer.\n\n `reshuffle_each_iteration` controls whether the shuffle order should be\n different for each epoch. In TF 1.X, the idiomatic way to create epochs\n was through the `repeat` transformation:\n\n ```python\n dataset = tf.data.Dataset.range(3)\n dataset = dataset.shuffle(3, reshuffle_each_iteration=True)\n dataset = dataset.repeat(2)\n # [1, 0, 2, 1, 2, 0]\n\n dataset = tf.data.Dataset.range(3)\n dataset = dataset.shuffle(3, reshuffle_each_iteration=False)\n dataset = dataset.repeat(2)\n # [1, 0, 2, 1, 0, 2]\n ```\n\n In TF 2.0, `tf.data.Dataset` objects are Python iterables which makes it\n possible to also create epochs through Python iteration:\n\n ```python\n dataset = tf.data.Dataset.range(3)\n dataset = dataset.shuffle(3, reshuffle_each_iteration=True)\n list(dataset.as_numpy_iterator())\n # [1, 0, 2]\n list(dataset.as_numpy_iterator())\n # [1, 2, 0]\n ```\n\n ```python\n dataset = tf.data.Dataset.range(3)\n dataset = dataset.shuffle(3, reshuffle_each_iteration=False)\n list(dataset.as_numpy_iterator())\n # [1, 0, 2]\n list(dataset.as_numpy_iterator())\n # [1, 0, 2]\n ```\n\n Args:\n buffer_size: A `tf.int64` scalar `tf.Tensor`, representing the number of\n elements from this dataset from which the new dataset will sample.\n seed: (Optional.) A `tf.int64` scalar `tf.Tensor`, representing the random\n seed that will be used to create the distribution. See\n `tf.random.set_seed` for behavior.\n reshuffle_each_iteration: (Optional.) A boolean, which if true indicates\n that the dataset should be pseudorandomly reshuffled each time it is\n iterated over. (Defaults to `True`.)\n\n Returns:\n Dataset: A `Dataset`.\n \"\"\"\n return ShuffleDataset(self, buffer_size, seed, reshuffle_each_iteration)\n\n def cache(self, filename=\"\"):\n \"\"\"Caches the elements in this dataset.\n\n The first time the dataset is iterated over, its elements will be cached\n either in the specified file or in memory. Subsequent iterations will\n use the cached data.\n\n Note: For the cache to be finalized, the input dataset must be iterated\n through in its entirety. Otherwise, subsequent iterations will not use\n cached data.\n\n >>> dataset = tf.data.Dataset.range(5)\n >>> dataset = dataset.map(lambda x: x**2)\n >>> dataset = dataset.cache()\n >>> # The first time reading through the data will generate the data using\n >>> # `range` and `map`.\n >>> list(dataset.as_numpy_iterator())\n [0, 1, 4, 9, 16]\n >>> # Subsequent iterations read from the cache.\n >>> list(dataset.as_numpy_iterator())\n [0, 1, 4, 9, 16]\n\n When caching to a file, the cached data will persist across runs. Even the\n first iteration through the data will read from the cache file. Changing\n the input pipeline before the call to `.cache()` will have no effect until\n the cache file is removed or the filename is changed.\n\n ```python\n dataset = tf.data.Dataset.range(5)\n dataset = dataset.cache(\"/path/to/file\")\n list(dataset.as_numpy_iterator())\n # [0, 1, 2, 3, 4]\n dataset = tf.data.Dataset.range(10)\n dataset = dataset.cache(\"/path/to/file\") # Same file!\n list(dataset.as_numpy_iterator())\n # [0, 1, 2, 3, 4]\n ```\n\n Note: `cache` will produce exactly the same elements during each iteration\n through the dataset. If you wish to randomize the iteration order, make sure\n to call `shuffle` *after* calling `cache`.\n\n Args:\n filename: A `tf.string` scalar `tf.Tensor`, representing the name of a\n directory on the filesystem to use for caching elements in this Dataset.\n If a filename is not provided, the dataset will be cached in memory.\n\n Returns:\n Dataset: A `Dataset`.\n \"\"\"\n return CacheDataset(self, filename)\n\n def take(self, count):\n \"\"\"Creates a `Dataset` with at most `count` elements from this dataset.\n\n >>> dataset = tf.data.Dataset.range(10)\n >>> dataset = dataset.take(3)\n >>> list(dataset.as_numpy_iterator())\n [0, 1, 2]\n\n Args:\n count: A `tf.int64` scalar `tf.Tensor`, representing the number of\n elements of this dataset that should be taken to form the new dataset.\n If `count` is -1, or if `count` is greater than the size of this\n dataset, the new dataset will contain all elements of this dataset.\n\n Returns:\n Dataset: A `Dataset`.\n \"\"\"\n return TakeDataset(self, count)\n\n def skip(self, count):\n \"\"\"Creates a `Dataset` that skips `count` elements from this dataset.\n\n >>> dataset = tf.data.Dataset.range(10)\n >>> dataset = dataset.skip(7)\n >>> list(dataset.as_numpy_iterator())\n [7, 8, 9]\n\n Args:\n count: A `tf.int64` scalar `tf.Tensor`, representing the number of\n elements of this dataset that should be skipped to form the new dataset.\n If `count` is greater than the size of this dataset, the new dataset\n will contain no elements. If `count` is -1, skips the entire dataset.\n\n Returns:\n Dataset: A `Dataset`.\n \"\"\"\n return SkipDataset(self, count)\n\n def shard(self, num_shards, index):\n \"\"\"Creates a `Dataset` that includes only 1/`num_shards` of this dataset.\n\n `shard` is deterministic. The Dataset produced by `A.shard(n, i)` will\n contain all elements of A whose index mod n = i.\n\n >>> A = tf.data.Dataset.range(10)\n >>> B = A.shard(num_shards=3, index=0)\n >>> list(B.as_numpy_iterator())\n [0, 3, 6, 9]\n >>> C = A.shard(num_shards=3, index=1)\n >>> list(C.as_numpy_iterator())\n [1, 4, 7]\n >>> D = A.shard(num_shards=3, index=2)\n >>> list(D.as_numpy_iterator())\n [2, 5, 8]\n\n This dataset operator is very useful when running distributed training, as\n it allows each worker to read a unique subset.\n\n When reading a single input file, you can shard elements as follows:\n\n ```python\n d = tf.data.TFRecordDataset(input_file)\n d = d.shard(num_workers, worker_index)\n d = d.repeat(num_epochs)\n d = d.shuffle(shuffle_buffer_size)\n d = d.map(parser_fn, num_parallel_calls=num_map_threads)\n ```\n\n Important caveats:\n\n - Be sure to shard before you use any randomizing operator (such as\n shuffle).\n - Generally it is best if the shard operator is used early in the dataset\n pipeline. For example, when reading from a set of TFRecord files, shard\n before converting the dataset to input samples. This avoids reading every\n file on every worker. The following is an example of an efficient\n sharding strategy within a complete pipeline:\n\n ```python\n d = Dataset.list_files(pattern)\n d = d.shard(num_workers, worker_index)\n d = d.repeat(num_epochs)\n d = d.shuffle(shuffle_buffer_size)\n d = d.interleave(tf.data.TFRecordDataset,\n cycle_length=num_readers, block_length=1)\n d = d.map(parser_fn, num_parallel_calls=num_map_threads)\n ```\n\n Args:\n num_shards: A `tf.int64` scalar `tf.Tensor`, representing the number of\n shards operating in parallel.\n index: A `tf.int64` scalar `tf.Tensor`, representing the worker index.\n\n Returns:\n Dataset: A `Dataset`.\n\n Raises:\n InvalidArgumentError: if `num_shards` or `index` are illegal values.\n\n Note: error checking is done on a best-effort basis, and errors aren't\n guaranteed to be caught upon dataset creation. (e.g. providing in a\n placeholder tensor bypasses the early checking, and will instead result\n in an error during a session.run call.)\n \"\"\"\n return ShardDataset(self, num_shards, index)\n\n def batch(self,\n batch_size,\n drop_remainder=False,\n num_parallel_calls=None,\n deterministic=None):\n \"\"\"Combines consecutive elements of this dataset into batches.\n\n >>> dataset = tf.data.Dataset.range(8)\n >>> dataset = dataset.batch(3)\n >>> list(dataset.as_numpy_iterator())\n [array([0, 1, 2]), array([3, 4, 5]), array([6, 7])]\n\n >>> dataset = tf.data.Dataset.range(8)\n >>> dataset = dataset.batch(3, drop_remainder=True)\n >>> list(dataset.as_numpy_iterator())\n [array([0, 1, 2]), array([3, 4, 5])]\n\n The components of the resulting element will have an additional outer\n dimension, which will be `batch_size` (or `N % batch_size` for the last\n element if `batch_size` does not divide the number of input elements `N`\n evenly and `drop_remainder` is `False`). If your program depends on the\n batches having the same outer dimension, you should set the `drop_remainder`\n argument to `True` to prevent the smaller batch from being produced.\n\n Args:\n batch_size: A `tf.int64` scalar `tf.Tensor`, representing the number of\n consecutive elements of this dataset to combine in a single batch.\n drop_remainder: (Optional.) A `tf.bool` scalar `tf.Tensor`, representing\n whether the last batch should be dropped in the case it has fewer than\n `batch_size` elements; the default behavior is not to drop the smaller\n batch.\n num_parallel_calls: (Optional.) A `tf.int64` scalar `tf.Tensor`,\n representing the number of batches to compute asynchronously in\n parallel.\n If not specified, batches will be computed sequentially. If the value\n `tf.data.AUTOTUNE` is used, then the number of parallel\n calls is set dynamically based on available resources.\n deterministic: (Optional.) When `num_parallel_calls` is specified, if this\n boolean is specified (`True` or `False`), it controls the order in which\n the transformation produces elements. If set to `False`, the\n transformation is allowed to yield elements out of order to trade\n determinism for performance. If not specified, the\n `tf.data.Options.experimental_deterministic` option\n (`True` by default) controls the behavior.\n\n Returns:\n Dataset: A `Dataset`.\n \"\"\"\n if num_parallel_calls is None:\n if deterministic is not None:\n warnings.warn(\"The `deterministic` argument has no effect unless the \"\n \"`num_parallel_calls` argument is specified.\")\n return BatchDataset(self, batch_size, drop_remainder)\n else:\n return ParallelBatchDataset(self, batch_size, drop_remainder,\n num_parallel_calls, deterministic)\n\n def padded_batch(self,\n batch_size,\n padded_shapes=None,\n padding_values=None,\n drop_remainder=False):\n \"\"\"Combines consecutive elements of this dataset into padded batches.\n\n This transformation combines multiple consecutive elements of the input\n dataset into a single element.\n\n Like `tf.data.Dataset.batch`, the components of the resulting element will\n have an additional outer dimension, which will be `batch_size` (or\n `N % batch_size` for the last element if `batch_size` does not divide the\n number of input elements `N` evenly and `drop_remainder` is `False`). If\n your program depends on the batches having the same outer dimension, you\n should set the `drop_remainder` argument to `True` to prevent the smaller\n batch from being produced.\n\n Unlike `tf.data.Dataset.batch`, the input elements to be batched may have\n different shapes, and this transformation will pad each component to the\n respective shape in `padded_shapes`. The `padded_shapes` argument\n determines the resulting shape for each dimension of each component in an\n output element:\n\n * If the dimension is a constant, the component will be padded out to that\n length in that dimension.\n * If the dimension is unknown, the component will be padded out to the\n maximum length of all elements in that dimension.\n\n >>> A = (tf.data.Dataset\n ... .range(1, 5, output_type=tf.int32)\n ... .map(lambda x: tf.fill([x], x)))\n >>> # Pad to the smallest per-batch size that fits all elements.\n >>> B = A.padded_batch(2)\n >>> for element in B.as_numpy_iterator():\n ... print(element)\n [[1 0]\n [2 2]]\n [[3 3 3 0]\n [4 4 4 4]]\n >>> # Pad to a fixed size.\n >>> C = A.padded_batch(2, padded_shapes=5)\n >>> for element in C.as_numpy_iterator():\n ... print(element)\n [[1 0 0 0 0]\n [2 2 0 0 0]]\n [[3 3 3 0 0]\n [4 4 4 4 0]]\n >>> # Pad with a custom value.\n >>> D = A.padded_batch(2, padded_shapes=5, padding_values=-1)\n >>> for element in D.as_numpy_iterator():\n ... print(element)\n [[ 1 -1 -1 -1 -1]\n [ 2 2 -1 -1 -1]]\n [[ 3 3 3 -1 -1]\n [ 4 4 4 4 -1]]\n >>> # Components of nested elements can be padded independently.\n >>> elements = [([1, 2, 3], [10]),\n ... ([4, 5], [11, 12])]\n >>> dataset = tf.data.Dataset.from_generator(\n ... lambda: iter(elements), (tf.int32, tf.int32))\n >>> # Pad the first component of the tuple to length 4, and the second\n >>> # component to the smallest size that fits.\n >>> dataset = dataset.padded_batch(2,\n ... padded_shapes=([4], [None]),\n ... padding_values=(-1, 100))\n >>> list(dataset.as_numpy_iterator())\n [(array([[ 1, 2, 3, -1], [ 4, 5, -1, -1]], dtype=int32),\n array([[ 10, 100], [ 11, 12]], dtype=int32))]\n >>> # Pad with a single value and multiple components.\n >>> E = tf.data.Dataset.zip((A, A)).padded_batch(2, padding_values=-1)\n >>> for element in E.as_numpy_iterator():\n ... print(element)\n (array([[ 1, -1],\n [ 2, 2]], dtype=int32), array([[ 1, -1],\n [ 2, 2]], dtype=int32))\n (array([[ 3, 3, 3, -1],\n [ 4, 4, 4, 4]], dtype=int32), array([[ 3, 3, 3, -1],\n [ 4, 4, 4, 4]], dtype=int32))\n\n See also `tf.data.experimental.dense_to_sparse_batch`, which combines\n elements that may have different shapes into a `tf.sparse.SparseTensor`.\n\n Args:\n batch_size: A `tf.int64` scalar `tf.Tensor`, representing the number of\n consecutive elements of this dataset to combine in a single batch.\n padded_shapes: (Optional.) A (nested) structure of `tf.TensorShape` or\n `tf.int64` vector tensor-like objects representing the shape to which\n the respective component of each input element should be padded prior\n to batching. Any unknown dimensions will be padded to the maximum size\n of that dimension in each batch. If unset, all dimensions of all\n components are padded to the maximum size in the batch. `padded_shapes`\n must be set if any component has an unknown rank.\n padding_values: (Optional.) A (nested) structure of scalar-shaped\n `tf.Tensor`, representing the padding values to use for the respective\n components. None represents that the (nested) structure should be padded\n with default values. Defaults are `0` for numeric types and the empty\n string for string types. The `padding_values` should have the same\n (nested) structure as the input dataset. If `padding_values` is a single\n element and the input dataset has multiple components, then the same\n `padding_values` will be used to pad every component of the dataset.\n If `padding_values` is a scalar, then its value will be broadcasted\n to match the shape of each component.\n drop_remainder: (Optional.) A `tf.bool` scalar `tf.Tensor`, representing\n whether the last batch should be dropped in the case it has fewer than\n `batch_size` elements; the default behavior is not to drop the smaller\n batch.\n\n Returns:\n Dataset: A `Dataset`.\n\n Raises:\n ValueError: If a component has an unknown rank, and the `padded_shapes`\n argument is not set.\n \"\"\"\n if padded_shapes is None:\n padded_shapes = get_legacy_output_shapes(self)\n # A `tf.TensorShape` is only false if its *rank* is unknown:\n # bool(tf.TensorShape(None)) is False\n if not all(nest.flatten(padded_shapes)):\n raise ValueError(\"You must set the `padded_shapes` argument to \"\n \"`Dataset.padded_batch` if any component of its \"\n \"input has an unknown rank\")\n return PaddedBatchDataset(self, batch_size, padded_shapes, padding_values,\n drop_remainder)\n\n def map(self, map_func, num_parallel_calls=None, deterministic=None):\n \"\"\"Maps `map_func` across the elements of this dataset.\n\n This transformation applies `map_func` to each element of this dataset, and\n returns a new dataset containing the transformed elements, in the same\n order as they appeared in the input. `map_func` can be used to change both\n the values and the structure of a dataset's elements. Supported structure\n constructs are documented\n [here](https://www.tensorflow.org/guide/data#dataset_structure).\n\n For example, `map` can be used for adding 1 to each element, or projecting a\n subset of element components.\n\n >>> dataset = Dataset.range(1, 6) # ==> [ 1, 2, 3, 4, 5 ]\n >>> dataset = dataset.map(lambda x: x + 1)\n >>> list(dataset.as_numpy_iterator())\n [2, 3, 4, 5, 6]\n\n The input signature of `map_func` is determined by the structure of each\n element in this dataset.\n\n >>> dataset = Dataset.range(5)\n >>> # `map_func` takes a single argument of type `tf.Tensor` with the same\n >>> # shape and dtype.\n >>> result = dataset.map(lambda x: x + 1)\n\n >>> # Each element is a tuple containing two `tf.Tensor` objects.\n >>> elements = [(1, \"foo\"), (2, \"bar\"), (3, \"baz\")]\n >>> dataset = tf.data.Dataset.from_generator(\n ... lambda: elements, (tf.int32, tf.string))\n >>> # `map_func` takes two arguments of type `tf.Tensor`. This function\n >>> # projects out just the first component.\n >>> result = dataset.map(lambda x_int, y_str: x_int)\n >>> list(result.as_numpy_iterator())\n [1, 2, 3]\n\n >>> # Each element is a dictionary mapping strings to `tf.Tensor` objects.\n >>> elements = ([{\"a\": 1, \"b\": \"foo\"},\n ... {\"a\": 2, \"b\": \"bar\"},\n ... {\"a\": 3, \"b\": \"baz\"}])\n >>> dataset = tf.data.Dataset.from_generator(\n ... lambda: elements, {\"a\": tf.int32, \"b\": tf.string})\n >>> # `map_func` takes a single argument of type `dict` with the same keys\n >>> # as the elements.\n >>> result = dataset.map(lambda d: str(d[\"a\"]) + d[\"b\"])\n\n The value or values returned by `map_func` determine the structure of each\n element in the returned dataset.\n\n >>> dataset = tf.data.Dataset.range(3)\n >>> # `map_func` returns two `tf.Tensor` objects.\n >>> def g(x):\n ... return tf.constant(37.0), tf.constant([\"Foo\", \"Bar\", \"Baz\"])\n >>> result = dataset.map(g)\n >>> result.element_spec\n (TensorSpec(shape=(), dtype=tf.float32, name=None), TensorSpec(shape=(3,), \\\ndtype=tf.string, name=None))\n >>> # Python primitives, lists, and NumPy arrays are implicitly converted to\n >>> # `tf.Tensor`.\n >>> def h(x):\n ... return 37.0, [\"Foo\", \"Bar\"], np.array([1.0, 2.0], dtype=np.float64)\n >>> result = dataset.map(h)\n >>> result.element_spec\n (TensorSpec(shape=(), dtype=tf.float32, name=None), TensorSpec(shape=(2,), \\\ndtype=tf.string, name=None), TensorSpec(shape=(2,), dtype=tf.float64, \\\nname=None))\n >>> # `map_func` can return nested structures.\n >>> def i(x):\n ... return (37.0, [42, 16]), \"foo\"\n >>> result = dataset.map(i)\n >>> result.element_spec\n ((TensorSpec(shape=(), dtype=tf.float32, name=None),\n TensorSpec(shape=(2,), dtype=tf.int32, name=None)),\n TensorSpec(shape=(), dtype=tf.string, name=None))\n\n `map_func` can accept as arguments and return any type of dataset element.\n\n Note that irrespective of the context in which `map_func` is defined (eager\n vs. graph), tf.data traces the function and executes it as a graph. To use\n Python code inside of the function you have a few options:\n\n 1) Rely on AutoGraph to convert Python code into an equivalent graph\n computation. The downside of this approach is that AutoGraph can convert\n some but not all Python code.\n\n 2) Use `tf.py_function`, which allows you to write arbitrary Python code but\n will generally result in worse performance than 1). For example:\n\n >>> d = tf.data.Dataset.from_tensor_slices(['hello', 'world'])\n >>> # transform a string tensor to upper case string using a Python function\n >>> def upper_case_fn(t: tf.Tensor):\n ... return t.numpy().decode('utf-8').upper()\n >>> d = d.map(lambda x: tf.py_function(func=upper_case_fn,\n ... inp=[x], Tout=tf.string))\n >>> list(d.as_numpy_iterator())\n [b'HELLO', b'WORLD']\n\n 3) Use `tf.numpy_function`, which also allows you to write arbitrary\n Python code. Note that `tf.py_function` accepts `tf.Tensor` whereas\n `tf.numpy_function` accepts numpy arrays and returns only numpy arrays.\n For example:\n\n >>> d = tf.data.Dataset.from_tensor_slices(['hello', 'world'])\n >>> def upper_case_fn(t: np.ndarray):\n ... return t.decode('utf-8').upper()\n >>> d = d.map(lambda x: tf.numpy_function(func=upper_case_fn,\n ... inp=[x], Tout=tf.string))\n >>> list(d.as_numpy_iterator())\n [b'HELLO', b'WORLD']\n\n Note that the use of `tf.numpy_function` and `tf.py_function`\n in general precludes the possibility of executing user-defined\n transformations in parallel (because of Python GIL).\n\n Performance can often be improved by setting `num_parallel_calls` so that\n `map` will use multiple threads to process elements. If deterministic order\n isn't required, it can also improve performance to set\n `deterministic=False`.\n\n >>> dataset = Dataset.range(1, 6) # ==> [ 1, 2, 3, 4, 5 ]\n >>> dataset = dataset.map(lambda x: x + 1,\n ... num_parallel_calls=tf.data.AUTOTUNE,\n ... deterministic=False)\n\n The order of elements yielded by this transformation is deterministic if\n `deterministic=True`. If `map_func` contains stateful operations and\n `num_parallel_calls > 1`, the order in which that state is accessed is\n undefined, so the values of output elements may not be deterministic\n regardless of the `deterministic` flag value.\n\n Args:\n map_func: A function mapping a dataset element to another dataset element.\n num_parallel_calls: (Optional.) A `tf.int64` scalar `tf.Tensor`,\n representing the number elements to process asynchronously in parallel.\n If not specified, elements will be processed sequentially. If the value\n `tf.data.AUTOTUNE` is used, then the number of parallel\n calls is set dynamically based on available CPU.\n deterministic: (Optional.) When `num_parallel_calls` is specified, if this\n boolean is specified (`True` or `False`), it controls the order in which\n the transformation produces elements. If set to `False`, the\n transformation is allowed to yield elements out of order to trade\n determinism for performance. If not specified, the\n `tf.data.Options.experimental_deterministic` option\n (`True` by default) controls the behavior.\n\n Returns:\n Dataset: A `Dataset`.\n \"\"\"\n if num_parallel_calls is None:\n if deterministic is not None:\n warnings.warn(\"The `deterministic` argument has no effect unless the \"\n \"`num_parallel_calls` argument is specified.\")\n return MapDataset(self, map_func, preserve_cardinality=True)\n else:\n return ParallelMapDataset(\n self,\n map_func,\n num_parallel_calls,\n deterministic,\n preserve_cardinality=True)\n\n def flat_map(self, map_func):\n \"\"\"Maps `map_func` across this dataset and flattens the result.\n\n Use `flat_map` if you want to make sure that the order of your dataset\n stays the same. For example, to flatten a dataset of batches into a\n dataset of their elements:\n\n >>> dataset = tf.data.Dataset.from_tensor_slices(\n ... [[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n >>> dataset = dataset.flat_map(lambda x: Dataset.from_tensor_slices(x))\n >>> list(dataset.as_numpy_iterator())\n [1, 2, 3, 4, 5, 6, 7, 8, 9]\n\n `tf.data.Dataset.interleave()` is a generalization of `flat_map`, since\n `flat_map` produces the same output as\n `tf.data.Dataset.interleave(cycle_length=1)`\n\n Args:\n map_func: A function mapping a dataset element to a dataset.\n\n Returns:\n Dataset: A `Dataset`.\n \"\"\"\n return FlatMapDataset(self, map_func)\n\n def interleave(self,\n map_func,\n cycle_length=None,\n block_length=None,\n num_parallel_calls=None,\n deterministic=None):\n \"\"\"Maps `map_func` across this dataset, and interleaves the results.\n\n For example, you can use `Dataset.interleave()` to process many input files\n concurrently:\n\n >>> # Preprocess 4 files concurrently, and interleave blocks of 16 records\n >>> # from each file.\n >>> filenames = [\"/var/data/file1.txt\", \"/var/data/file2.txt\",\n ... \"/var/data/file3.txt\", \"/var/data/file4.txt\"]\n >>> dataset = tf.data.Dataset.from_tensor_slices(filenames)\n >>> def parse_fn(filename):\n ... return tf.data.Dataset.range(10)\n >>> dataset = dataset.interleave(lambda x:\n ... tf.data.TextLineDataset(x).map(parse_fn, num_parallel_calls=1),\n ... cycle_length=4, block_length=16)\n\n The `cycle_length` and `block_length` arguments control the order in which\n elements are produced. `cycle_length` controls the number of input elements\n that are processed concurrently. If you set `cycle_length` to 1, this\n transformation will handle one input element at a time, and will produce\n identical results to `tf.data.Dataset.flat_map`. In general,\n this transformation will apply `map_func` to `cycle_length` input elements,\n open iterators on the returned `Dataset` objects, and cycle through them\n producing `block_length` consecutive elements from each iterator, and\n consuming the next input element each time it reaches the end of an\n iterator.\n\n For example:\n\n >>> dataset = Dataset.range(1, 6) # ==> [ 1, 2, 3, 4, 5 ]\n >>> # NOTE: New lines indicate \"block\" boundaries.\n >>> dataset = dataset.interleave(\n ... lambda x: Dataset.from_tensors(x).repeat(6),\n ... cycle_length=2, block_length=4)\n >>> list(dataset.as_numpy_iterator())\n [1, 1, 1, 1,\n 2, 2, 2, 2,\n 1, 1,\n 2, 2,\n 3, 3, 3, 3,\n 4, 4, 4, 4,\n 3, 3,\n 4, 4,\n 5, 5, 5, 5,\n 5, 5]\n\n Note: The order of elements yielded by this transformation is\n deterministic, as long as `map_func` is a pure function and\n `deterministic=True`. If `map_func` contains any stateful operations, the\n order in which that state is accessed is undefined.\n\n Performance can often be improved by setting `num_parallel_calls` so that\n `interleave` will use multiple threads to fetch elements. If determinism\n isn't required, it can also improve performance to set\n `deterministic=False`.\n\n >>> filenames = [\"/var/data/file1.txt\", \"/var/data/file2.txt\",\n ... \"/var/data/file3.txt\", \"/var/data/file4.txt\"]\n >>> dataset = tf.data.Dataset.from_tensor_slices(filenames)\n >>> dataset = dataset.interleave(lambda x: tf.data.TFRecordDataset(x),\n ... cycle_length=4, num_parallel_calls=tf.data.AUTOTUNE,\n ... deterministic=False)\n\n Args:\n map_func: A function mapping a dataset element to a dataset.\n cycle_length: (Optional.) The number of input elements that will be\n processed concurrently. If not set, the tf.data runtime decides what it\n should be based on available CPU. If `num_parallel_calls` is set to\n `tf.data.AUTOTUNE`, the `cycle_length` argument identifies\n the maximum degree of parallelism.\n block_length: (Optional.) The number of consecutive elements to produce\n from each input element before cycling to another input element. If not\n set, defaults to 1.\n num_parallel_calls: (Optional.) If specified, the implementation creates a\n threadpool, which is used to fetch inputs from cycle elements\n asynchronously and in parallel. The default behavior is to fetch inputs\n from cycle elements synchronously with no parallelism. If the value\n `tf.data.AUTOTUNE` is used, then the number of parallel\n calls is set dynamically based on available CPU.\n deterministic: (Optional.) When `num_parallel_calls` is specified, if this\n boolean is specified (`True` or `False`), it controls the order in which\n the transformation produces elements. If set to `False`, the\n transformation is allowed to yield elements out of order to trade\n determinism for performance. If not specified, the\n `tf.data.Options.experimental_deterministic` option\n (`True` by default) controls the behavior.\n\n Returns:\n Dataset: A `Dataset`.\n \"\"\"\n if block_length is None:\n block_length = 1\n\n if cycle_length is None:\n cycle_length = AUTOTUNE\n\n if num_parallel_calls is None:\n if deterministic is not None:\n warnings.warn(\"The `deterministic` argument has no effect unless the \"\n \"`num_parallel_calls` argument is specified.\")\n return InterleaveDataset(self, map_func, cycle_length, block_length)\n else:\n return ParallelInterleaveDataset(\n self,\n map_func,\n cycle_length,\n block_length,\n num_parallel_calls,\n deterministic=deterministic)\n\n def filter(self, predicate):\n \"\"\"Filters this dataset according to `predicate`.\n\n >>> dataset = tf.data.Dataset.from_tensor_slices([1, 2, 3])\n >>> dataset = dataset.filter(lambda x: x < 3)\n >>> list(dataset.as_numpy_iterator())\n [1, 2]\n >>> # `tf.math.equal(x, y)` is required for equality comparison\n >>> def filter_fn(x):\n ... return tf.math.equal(x, 1)\n >>> dataset = dataset.filter(filter_fn)\n >>> list(dataset.as_numpy_iterator())\n [1]\n\n Args:\n predicate: A function mapping a dataset element to a boolean.\n\n Returns:\n Dataset: The `Dataset` containing the elements of this dataset for which\n `predicate` is `True`.\n \"\"\"\n return FilterDataset(self, predicate)\n\n def apply(self, transformation_func):\n \"\"\"Applies a transformation function to this dataset.\n\n `apply` enables chaining of custom `Dataset` transformations, which are\n represented as functions that take one `Dataset` argument and return a\n transformed `Dataset`.\n\n >>> dataset = tf.data.Dataset.range(100)\n >>> def dataset_fn(ds):\n ... return ds.filter(lambda x: x < 5)\n >>> dataset = dataset.apply(dataset_fn)\n >>> list(dataset.as_numpy_iterator())\n [0, 1, 2, 3, 4]\n\n Args:\n transformation_func: A function that takes one `Dataset` argument and\n returns a `Dataset`.\n\n Returns:\n Dataset: The `Dataset` returned by applying `transformation_func` to this\n dataset.\n \"\"\"\n dataset = transformation_func(self)\n if not isinstance(dataset, DatasetV2):\n raise TypeError(\n \"`transformation_func` must return a Dataset. Got {}.\".format(\n dataset))\n dataset._input_datasets = [self] # pylint: disable=protected-access\n return dataset\n\n def window(self, size, shift=None, stride=1, drop_remainder=False):\n \"\"\"Combines (nests of) input elements into a dataset of (nests of) windows.\n\n A \"window\" is a finite dataset of flat elements of size `size` (or possibly\n fewer if there are not enough input elements to fill the window and\n `drop_remainder` evaluates to `False`).\n\n The `shift` argument determines the number of input elements by which the\n window moves on each iteration. If windows and elements are both numbered\n starting at 0, the first element in window `k` will be element `k * shift`\n of the input dataset. In particular, the first element of the first window\n will always be the first element of the input dataset.\n\n The `stride` argument determines the stride of the input elements, and the\n `shift` argument determines the shift of the window.\n\n For example:\n\n >>> dataset = tf.data.Dataset.range(7).window(2)\n >>> for window in dataset:\n ... print(list(window.as_numpy_iterator()))\n [0, 1]\n [2, 3]\n [4, 5]\n [6]\n >>> dataset = tf.data.Dataset.range(7).window(3, 2, 1, True)\n >>> for window in dataset:\n ... print(list(window.as_numpy_iterator()))\n [0, 1, 2]\n [2, 3, 4]\n [4, 5, 6]\n >>> dataset = tf.data.Dataset.range(7).window(3, 1, 2, True)\n >>> for window in dataset:\n ... print(list(window.as_numpy_iterator()))\n [0, 2, 4]\n [1, 3, 5]\n [2, 4, 6]\n\n Note that when the `window` transformation is applied to a dataset of\n nested elements, it produces a dataset of nested windows.\n\n >>> nested = ([1, 2, 3, 4], [5, 6, 7, 8])\n >>> dataset = tf.data.Dataset.from_tensor_slices(nested).window(2)\n >>> for window in dataset:\n ... def to_numpy(ds):\n ... return list(ds.as_numpy_iterator())\n ... print(tuple(to_numpy(component) for component in window))\n ([1, 2], [5, 6])\n ([3, 4], [7, 8])\n\n >>> dataset = tf.data.Dataset.from_tensor_slices({'a': [1, 2, 3, 4]})\n >>> dataset = dataset.window(2)\n >>> for window in dataset:\n ... def to_numpy(ds):\n ... return list(ds.as_numpy_iterator())\n ... print({'a': to_numpy(window['a'])})\n {'a': [1, 2]}\n {'a': [3, 4]}\n\n Args:\n size: A `tf.int64` scalar `tf.Tensor`, representing the number of elements\n of the input dataset to combine into a window. Must be positive.\n shift: (Optional.) A `tf.int64` scalar `tf.Tensor`, representing the\n number of input elements by which the window moves in each iteration.\n Defaults to `size`. Must be positive.\n stride: (Optional.) A `tf.int64` scalar `tf.Tensor`, representing the\n stride of the input elements in the sliding window. Must be positive.\n The default value of 1 means \"retain every input element\".\n drop_remainder: (Optional.) A `tf.bool` scalar `tf.Tensor`, representing\n whether the last windows should be dropped if their size is smaller than\n `size`.\n\n Returns:\n Dataset: A `Dataset` of (nests of) windows -- a finite datasets of flat\n elements created from the (nests of) input elements.\n\n \"\"\"\n if shift is None:\n shift = size\n return WindowDataset(self, size, shift, stride, drop_remainder)\n\n def reduce(self, initial_state, reduce_func):\n \"\"\"Reduces the input dataset to a single element.\n\n The transformation calls `reduce_func` successively on every element of\n the input dataset until the dataset is exhausted, aggregating information in\n its internal state. The `initial_state` argument is used for the initial\n state and the final state is returned as the result.\n\n >>> tf.data.Dataset.range(5).reduce(np.int64(0), lambda x, _: x + 1).numpy()\n 5\n >>> tf.data.Dataset.range(5).reduce(np.int64(0), lambda x, y: x + y).numpy()\n 10\n\n Args:\n initial_state: An element representing the initial state of the\n transformation.\n reduce_func: A function that maps `(old_state, input_element)` to\n `new_state`. It must take two arguments and return a new element\n The structure of `new_state` must match the structure of\n `initial_state`.\n\n Returns:\n A dataset element corresponding to the final state of the transformation.\n\n \"\"\"\n\n with ops.name_scope(\"initial_state\"):\n initial_state = structure.normalize_element(initial_state)\n state_structure = structure.type_spec_from_value(initial_state)\n\n # Iteratively rerun the reduce function until reaching a fixed point on\n # `state_structure`.\n need_to_rerun = True\n while need_to_rerun:\n\n wrapped_func = StructuredFunctionWrapper(\n reduce_func,\n \"reduce()\",\n input_structure=(state_structure, self.element_spec),\n add_to_graph=False)\n\n # Extract and validate class information from the returned values.\n output_classes = wrapped_func.output_classes\n state_classes = nest.map_structure(\n lambda component_spec: component_spec._to_legacy_output_classes(), # pylint: disable=protected-access\n state_structure)\n for new_state_class, state_class in zip(\n nest.flatten(output_classes), nest.flatten(state_classes)):\n if not issubclass(new_state_class, state_class):\n raise TypeError(\n \"The element classes for the new state must match the initial \"\n \"state. Expected %s; got %s.\" %\n (state_classes, wrapped_func.output_classes))\n\n # Extract and validate type information from the returned values.\n output_types = wrapped_func.output_types\n state_types = nest.map_structure(\n lambda component_spec: component_spec._to_legacy_output_types(), # pylint: disable=protected-access\n state_structure)\n for new_state_type, state_type in zip(\n nest.flatten(output_types), nest.flatten(state_types)):\n if new_state_type != state_type:\n raise TypeError(\n \"The element types for the new state must match the initial \"\n \"state. Expected %s; got %s.\" %\n (state_types, wrapped_func.output_types))\n\n # Extract shape information from the returned values.\n output_shapes = wrapped_func.output_shapes\n state_shapes = nest.map_structure(\n lambda component_spec: component_spec._to_legacy_output_shapes(), # pylint: disable=protected-access\n state_structure)\n flat_state_shapes = nest.flatten(state_shapes)\n flat_new_state_shapes = nest.flatten(output_shapes)\n weakened_state_shapes = [\n original.most_specific_compatible_shape(new)\n for original, new in zip(flat_state_shapes, flat_new_state_shapes)\n ]\n\n need_to_rerun = False\n for original_shape, weakened_shape in zip(flat_state_shapes,\n weakened_state_shapes):\n if original_shape.ndims is not None and (\n weakened_shape.ndims is None or\n original_shape.as_list() != weakened_shape.as_list()):\n need_to_rerun = True\n break\n\n if need_to_rerun:\n # TODO(b/110122868): Support a \"most specific compatible structure\"\n # method for combining structures, to avoid using legacy structures\n # here.\n state_structure = structure.convert_legacy_structure(\n state_types,\n nest.pack_sequence_as(state_shapes, weakened_state_shapes),\n state_classes)\n\n reduce_func = wrapped_func.function\n reduce_func.add_to_graph(ops.get_default_graph())\n\n dataset = self._apply_options()\n\n # pylint: disable=protected-access\n return structure.from_compatible_tensor_list(\n state_structure,\n gen_dataset_ops.reduce_dataset(\n dataset._variant_tensor,\n structure.to_tensor_list(state_structure, initial_state),\n reduce_func.captured_inputs,\n f=reduce_func,\n output_shapes=structure.get_flat_tensor_shapes(state_structure),\n output_types=structure.get_flat_tensor_types(state_structure)))\n\n def unbatch(self):\n \"\"\"Splits elements of a dataset into multiple elements.\n\n For example, if elements of the dataset are shaped `[B, a0, a1, ...]`,\n where `B` may vary for each input element, then for each element in the\n dataset, the unbatched dataset will contain `B` consecutive elements\n of shape `[a0, a1, ...]`.\n\n >>> elements = [ [1, 2, 3], [1, 2], [1, 2, 3, 4] ]\n >>> dataset = tf.data.Dataset.from_generator(lambda: elements, tf.int64)\n >>> dataset = dataset.unbatch()\n >>> list(dataset.as_numpy_iterator())\n [1, 2, 3, 1, 2, 1, 2, 3, 4]\n\n Note: `unbatch` requires a data copy to slice up the batched tensor into\n smaller, unbatched tensors. When optimizing performance, try to avoid\n unnecessary usage of `unbatch`.\n\n Returns:\n A `Dataset`.\n \"\"\"\n normalized_dataset = normalize_to_dense(self)\n return _UnbatchDataset(normalized_dataset)\n\n def with_options(self, options):\n \"\"\"Returns a new `tf.data.Dataset` with the given options set.\n\n The options are \"global\" in the sense they apply to the entire dataset.\n If options are set multiple times, they are merged as long as different\n options do not use different non-default values.\n\n >>> ds = tf.data.Dataset.range(5)\n >>> ds = ds.interleave(lambda x: tf.data.Dataset.range(5),\n ... cycle_length=3,\n ... num_parallel_calls=3)\n >>> options = tf.data.Options()\n >>> # This will make the interleave order non-deterministic.\n >>> options.experimental_deterministic = False\n >>> ds = ds.with_options(options)\n\n Args:\n options: A `tf.data.Options` that identifies the options the use.\n\n Returns:\n Dataset: A `Dataset` with the given options.\n\n Raises:\n ValueError: when an option is set more than once to a non-default value\n \"\"\"\n return _OptionsDataset(self, options)\n\n def cardinality(self):\n \"\"\"Returns the cardinality of the dataset, if known.\n\n `cardinality` may return `tf.data.INFINITE_CARDINALITY` if the dataset\n contains an infinite number of elements or `tf.data.UNKNOWN_CARDINALITY` if\n the analysis fails to determine the number of elements in the dataset\n (e.g. when the dataset source is a file).\n\n >>> dataset = tf.data.Dataset.range(42)\n >>> print(dataset.cardinality().numpy())\n 42\n >>> dataset = dataset.repeat()\n >>> cardinality = dataset.cardinality()\n >>> print((cardinality == tf.data.INFINITE_CARDINALITY).numpy())\n True\n >>> dataset = dataset.filter(lambda x: True)\n >>> cardinality = dataset.cardinality()\n >>> print((cardinality == tf.data.UNKNOWN_CARDINALITY).numpy())\n True\n\n Returns:\n A scalar `tf.int64` `Tensor` representing the cardinality of the dataset.\n If the cardinality is infinite or unknown, `cardinality` returns the\n named constants `tf.data.INFINITE_CARDINALITY` and\n `tf.data.UNKNOWN_CARDINALITY` respectively.\n \"\"\"\n return gen_dataset_ops.dataset_cardinality(self._variant_tensor)\n\n\n@tf_export(v1=[\"data.Dataset\"])\nclass DatasetV1(DatasetV2):\n \"\"\"Represents a potentially large set of elements.\n\n A `Dataset` can be used to represent an input pipeline as a\n collection of elements and a \"logical plan\" of transformations that act on\n those elements.\n \"\"\"\n\n def __init__(self):\n try:\n variant_tensor = self._as_variant_tensor()\n except AttributeError as e:\n if \"_as_variant_tensor\" in str(e):\n raise AttributeError(\"Please use _variant_tensor instead of \"\n \"_as_variant_tensor() to obtain the variant \"\n \"associated with a dataset\")\n raise AttributeError(\"{}: A likely cause of this error is that the super \"\n \"call for this dataset is not the last line of the \"\n \"__init__ method. The base class causes the \"\n \"_as_variant_tensor call in its constructor and \"\n \"if that uses attributes defined in the __init__ \"\n \"method, those attrs need to be defined before the \"\n \"super call.\".format(e))\n super(DatasetV1, self).__init__(variant_tensor)\n\n @abc.abstractmethod\n def _as_variant_tensor(self):\n \"\"\"Creates a scalar `tf.Tensor` of `tf.variant` representing this dataset.\n\n Returns:\n A scalar `tf.Tensor` of `tf.variant` type, which represents this dataset.\n \"\"\"\n raise NotImplementedError(\"Dataset._as_variant_tensor\")\n\n @deprecation.deprecated(\n None, \"This is a deprecated API that should only be used in TF 1 graph \"\n \"mode and legacy TF 2 graph mode available through `tf.compat.v1`. In \"\n \"all other situations -- namely, eager mode and inside `tf.function` -- \"\n \"you can consume dataset elements using `for elem in dataset: ...` or \"\n \"by explicitly creating iterator via `iterator = iter(dataset)` and \"\n \"fetching its elements via `values = next(iterator)`. Furthermore, \"\n \"this API is not available in TF 2. During the transition from TF 1 \"\n \"to TF 2 you can use `tf.compat.v1.data.make_one_shot_iterator(dataset)` \"\n \"to create a TF 1 graph mode style iterator for a dataset created \"\n \"through TF 2 APIs. Note that this should be a transient state of your \"\n \"code base as there are in general no guarantees about the \"\n \"interoperability of TF 1 and TF 2 code.\")\n def make_one_shot_iterator(self):\n \"\"\"Creates an iterator for elements of this dataset.\n\n Note: The returned iterator will be initialized automatically.\n A \"one-shot\" iterator does not currently support re-initialization. For\n that see `make_initializable_iterator`.\n\n Example:\n\n ```python\n # Building graph ...\n dataset = ...\n next_value = dataset.make_one_shot_iterator().get_next()\n\n # ... from within a session ...\n try:\n while True:\n value = sess.run(next_value)\n ...\n except tf.errors.OutOfRangeError:\n pass\n ```\n\n Returns:\n An `tf.data.Iterator` for elements of this dataset.\n \"\"\"\n return self._make_one_shot_iterator()\n\n def _make_one_shot_iterator(self): # pylint: disable=missing-docstring\n if context.executing_eagerly():\n with ops.colocate_with(self._variant_tensor):\n return iterator_ops.OwnedIterator(self)\n\n _ensure_same_dataset_graph(self)\n # Some ops (e.g. dataset ops) are marked as stateful but are stil safe to\n # to capture by value. We must allowlist these ops so that the capturing\n # logic captures the ops instead of raising an exception.\n allowlisted_stateful_ops = traverse.obtain_capture_by_value_ops(self)\n graph_level_seed, op_level_seed = core_random_seed.get_seed(None)\n\n # NOTE(mrry): We capture by value here to ensure that `_make_dataset()` is\n # a 0-argument function.\n @function.Defun(\n capture_by_value=True,\n allowlisted_stateful_ops=allowlisted_stateful_ops)\n def _make_dataset():\n \"\"\"Factory function for a dataset.\"\"\"\n # NOTE(mrry): `Defun` does not capture the graph-level seed from the\n # enclosing graph, so if a graph-level seed is present we set the local\n # graph seed based on a combination of the graph- and op-level seeds.\n if graph_level_seed is not None:\n assert op_level_seed is not None\n core_random_seed.set_random_seed(\n (graph_level_seed + 87654321 * op_level_seed) % (2 ** 63 - 1))\n\n dataset = self._apply_options()\n return dataset._variant_tensor # pylint: disable=protected-access\n\n try:\n _make_dataset.add_to_graph(ops.get_default_graph())\n except ValueError as err:\n if \"Cannot capture a stateful node\" in str(err):\n raise ValueError(\n \"Failed to create a one-shot iterator for a dataset. \"\n \"`Dataset.make_one_shot_iterator()` does not support datasets that \"\n \"capture stateful objects, such as a `Variable` or `LookupTable`. \"\n \"In these cases, use `Dataset.make_initializable_iterator()`. \"\n \"(Original error: %s)\" % err)\n else:\n six.reraise(ValueError, err)\n\n with ops.colocate_with(self._variant_tensor):\n # pylint: disable=protected-access\n return iterator_ops.Iterator(\n gen_dataset_ops.one_shot_iterator(\n dataset_factory=_make_dataset, **self._flat_structure), None,\n get_legacy_output_types(self), get_legacy_output_shapes(self),\n get_legacy_output_classes(self))\n\n @deprecation.deprecated(\n None, \"This is a deprecated API that should only be used in TF 1 graph \"\n \"mode and legacy TF 2 graph mode available through `tf.compat.v1`. \"\n \"In all other situations -- namely, eager mode and inside `tf.function` \"\n \"-- you can consume dataset elements using `for elem in dataset: ...` \"\n \"or by explicitly creating iterator via `iterator = iter(dataset)` \"\n \"and fetching its elements via `values = next(iterator)`. \"\n \"Furthermore, this API is not available in TF 2. During the transition \"\n \"from TF 1 to TF 2 you can use \"\n \"`tf.compat.v1.data.make_initializable_iterator(dataset)` to create a TF \"\n \"1 graph mode style iterator for a dataset created through TF 2 APIs. \"\n \"Note that this should be a transient state of your code base as there \"\n \"are in general no guarantees about the interoperability of TF 1 and TF \"\n \"2 code.\")\n def make_initializable_iterator(self, shared_name=None):\n \"\"\"Creates an iterator for elements of this dataset.\n\n Note: The returned iterator will be in an uninitialized state,\n and you must run the `iterator.initializer` operation before using it:\n\n ```python\n # Building graph ...\n dataset = ...\n iterator = dataset.make_initializable_iterator()\n next_value = iterator.get_next() # This is a Tensor.\n\n # ... from within a session ...\n sess.run(iterator.initializer)\n try:\n while True:\n value = sess.run(next_value)\n ...\n except tf.errors.OutOfRangeError:\n pass\n ```\n\n Args:\n shared_name: (Optional.) If non-empty, the returned iterator will be\n shared under the given name across multiple sessions that share the same\n devices (e.g. when using a remote server).\n\n Returns:\n A `tf.data.Iterator` for elements of this dataset.\n\n Raises:\n RuntimeError: If eager execution is enabled.\n \"\"\"\n return self._make_initializable_iterator(shared_name)\n\n def _make_initializable_iterator(self, shared_name=None): # pylint: disable=missing-docstring\n if context.executing_eagerly():\n raise RuntimeError(\n \"dataset.make_initializable_iterator is not supported when eager \"\n \"execution is enabled. Use `for element in dataset` instead.\")\n _ensure_same_dataset_graph(self)\n dataset = self._apply_options()\n if shared_name is None:\n shared_name = \"\"\n\n with ops.colocate_with(self._variant_tensor):\n iterator_resource = gen_dataset_ops.iterator_v2(\n container=\"\", shared_name=shared_name, **self._flat_structure)\n\n initializer = gen_dataset_ops.make_iterator(\n dataset._variant_tensor, # pylint: disable=protected-access\n iterator_resource)\n\n # pylint: disable=protected-access\n return iterator_ops.Iterator(iterator_resource, initializer,\n get_legacy_output_types(dataset),\n get_legacy_output_shapes(dataset),\n get_legacy_output_classes(dataset))\n\n @property\n @deprecation.deprecated(\n None, \"Use `tf.compat.v1.data.get_output_classes(dataset)`.\")\n def output_classes(self):\n \"\"\"Returns the class of each component of an element of this dataset.\n\n Returns:\n A (nested) structure of Python `type` objects corresponding to each\n component of an element of this dataset.\n \"\"\"\n return nest.map_structure(\n lambda component_spec: component_spec._to_legacy_output_classes(), # pylint: disable=protected-access\n self.element_spec)\n\n @property\n @deprecation.deprecated(\n None, \"Use `tf.compat.v1.data.get_output_shapes(dataset)`.\")\n def output_shapes(self):\n \"\"\"Returns the shape of each component of an element of this dataset.\n\n Returns:\n A (nested) structure of `tf.TensorShape` objects corresponding to each\n component of an element of this dataset.\n \"\"\"\n return nest.map_structure(\n lambda component_spec: component_spec._to_legacy_output_shapes(), # pylint: disable=protected-access\n self.element_spec)\n\n @property\n @deprecation.deprecated(\n None, \"Use `tf.compat.v1.data.get_output_types(dataset)`.\")\n def output_types(self):\n \"\"\"Returns the type of each component of an element of this dataset.\n\n Returns:\n A (nested) structure of `tf.DType` objects corresponding to each component\n of an element of this dataset.\n \"\"\"\n return nest.map_structure(\n lambda component_spec: component_spec._to_legacy_output_types(), # pylint: disable=protected-access\n self.element_spec)\n\n @property\n def element_spec(self):\n # TODO(b/110122868): Remove this override once all `Dataset` instances\n # implement `element_structure`.\n return structure.convert_legacy_structure(\n self.output_types, self.output_shapes, self.output_classes)\n\n @staticmethod\n @functools.wraps(DatasetV2.from_tensors)\n def from_tensors(tensors):\n return DatasetV1Adapter(DatasetV2.from_tensors(tensors))\n\n @staticmethod\n @functools.wraps(DatasetV2.from_tensor_slices)\n def from_tensor_slices(tensors):\n return DatasetV1Adapter(DatasetV2.from_tensor_slices(tensors))\n\n @staticmethod\n @deprecation.deprecated(None, \"Use `tf.data.Dataset.from_tensor_slices()`.\")\n def from_sparse_tensor_slices(sparse_tensor):\n \"\"\"Splits each rank-N `tf.sparse.SparseTensor` in this dataset row-wise.\n\n Args:\n sparse_tensor: A `tf.sparse.SparseTensor`.\n\n Returns:\n Dataset: A `Dataset` of rank-(N-1) sparse tensors.\n \"\"\"\n return DatasetV1Adapter(SparseTensorSliceDataset(sparse_tensor))\n\n @staticmethod\n @functools.wraps(DatasetV2.from_generator)\n def from_generator(generator,\n output_types=None,\n output_shapes=None,\n args=None,\n output_signature=None):\n return DatasetV1Adapter(\n DatasetV2.from_generator(generator, output_types, output_shapes, args,\n output_signature))\n\n @staticmethod\n @functools.wraps(DatasetV2.range)\n def range(*args, **kwargs):\n return DatasetV1Adapter(DatasetV2.range(*args, **kwargs))\n\n @staticmethod\n @functools.wraps(DatasetV2.zip)\n def zip(datasets):\n return DatasetV1Adapter(DatasetV2.zip(datasets))\n\n @functools.wraps(DatasetV2.concatenate)\n def concatenate(self, dataset):\n return DatasetV1Adapter(super(DatasetV1, self).concatenate(dataset))\n\n @functools.wraps(DatasetV2.prefetch)\n def prefetch(self, buffer_size):\n return DatasetV1Adapter(super(DatasetV1, self).prefetch(buffer_size))\n\n @staticmethod\n @functools.wraps(DatasetV2.list_files)\n def list_files(file_pattern, shuffle=None, seed=None):\n return DatasetV1Adapter(DatasetV2.list_files(file_pattern, shuffle, seed))\n\n @functools.wraps(DatasetV2.repeat)\n def repeat(self, count=None):\n return DatasetV1Adapter(super(DatasetV1, self).repeat(count))\n\n @functools.wraps(DatasetV2.shuffle)\n def shuffle(self, buffer_size, seed=None, reshuffle_each_iteration=None):\n return DatasetV1Adapter(super(DatasetV1, self).shuffle(\n buffer_size, seed, reshuffle_each_iteration))\n\n @functools.wraps(DatasetV2.cache)\n def cache(self, filename=\"\"):\n return DatasetV1Adapter(super(DatasetV1, self).cache(filename))\n\n @functools.wraps(DatasetV2.take)\n def take(self, count):\n return DatasetV1Adapter(super(DatasetV1, self).take(count))\n\n @functools.wraps(DatasetV2.skip)\n def skip(self, count):\n return DatasetV1Adapter(super(DatasetV1, self).skip(count))\n\n @functools.wraps(DatasetV2.shard)\n def shard(self, num_shards, index):\n return DatasetV1Adapter(super(DatasetV1, self).shard(num_shards, index))\n\n @functools.wraps(DatasetV2.batch)\n def batch(self,\n batch_size,\n drop_remainder=False,\n num_parallel_calls=None,\n deterministic=None):\n return DatasetV1Adapter(\n super(DatasetV1, self).batch(batch_size, drop_remainder,\n num_parallel_calls, deterministic))\n\n @functools.wraps(DatasetV2.padded_batch)\n def padded_batch(self,\n batch_size,\n padded_shapes=None,\n padding_values=None,\n drop_remainder=False):\n return DatasetV1Adapter(\n super(DatasetV1, self).padded_batch(batch_size, padded_shapes,\n padding_values, drop_remainder))\n\n @functools.wraps(DatasetV2.map)\n def map(self, map_func, num_parallel_calls=None, deterministic=None):\n if num_parallel_calls is None:\n return DatasetV1Adapter(\n MapDataset(self, map_func, preserve_cardinality=False))\n else:\n return DatasetV1Adapter(\n ParallelMapDataset(\n self,\n map_func,\n num_parallel_calls,\n deterministic,\n preserve_cardinality=False))\n\n @deprecation.deprecated(None, \"Use `tf.data.Dataset.map()\")\n def map_with_legacy_function(self,\n map_func,\n num_parallel_calls=None,\n deterministic=None):\n \"\"\"Maps `map_func` across the elements of this dataset.\n\n Note: This is an escape hatch for existing uses of `map` that do not work\n with V2 functions. New uses are strongly discouraged and existing uses\n should migrate to `map` as this method will be removed in V2.\n\n Args:\n map_func: A function mapping a (nested) structure of tensors (having\n shapes and types defined by `self.output_shapes` and\n `self.output_types`) to another (nested) structure of tensors.\n num_parallel_calls: (Optional.) A `tf.int32` scalar `tf.Tensor`,\n representing the number elements to process asynchronously in parallel.\n If not specified, elements will be processed sequentially. If the value\n `tf.data.AUTOTUNE` is used, then the number of parallel\n calls is set dynamically based on available CPU.\n deterministic: (Optional.) When `num_parallel_calls` is specified, this\n boolean controls the order in which the transformation produces\n elements. If set to `False`, the transformation is allowed to yield\n elements out of order to trade determinism for performance. If not\n specified, the `tf.data.Options.experimental_deterministic` option\n (`True` by default) controls the behavior.\n\n Returns:\n Dataset: A `Dataset`.\n \"\"\"\n if num_parallel_calls is None:\n if deterministic is not None:\n warnings.warn(\"The `deterministic` argument has no effect unless the \"\n \"`num_parallel_calls` argument is specified.\")\n return DatasetV1Adapter(\n MapDataset(\n self,\n map_func,\n preserve_cardinality=False,\n use_legacy_function=True))\n else:\n return DatasetV1Adapter(\n ParallelMapDataset(\n self,\n map_func,\n num_parallel_calls,\n deterministic,\n preserve_cardinality=False,\n use_legacy_function=True))\n\n @functools.wraps(DatasetV2.flat_map)\n def flat_map(self, map_func):\n return DatasetV1Adapter(super(DatasetV1, self).flat_map(map_func))\n\n @functools.wraps(DatasetV2.interleave)\n def interleave(self,\n map_func,\n cycle_length=None,\n block_length=None,\n num_parallel_calls=None,\n deterministic=None):\n return DatasetV1Adapter(\n super(DatasetV1, self).interleave(map_func, cycle_length, block_length,\n num_parallel_calls, deterministic))\n\n @functools.wraps(DatasetV2.filter)\n def filter(self, predicate):\n return DatasetV1Adapter(super(DatasetV1, self).filter(predicate))\n\n @deprecation.deprecated(None, \"Use `tf.data.Dataset.filter()\")\n def filter_with_legacy_function(self, predicate):\n \"\"\"Filters this dataset according to `predicate`.\n\n Note: This is an escape hatch for existing uses of `filter` that do not work\n with V2 functions. New uses are strongly discouraged and existing uses\n should migrate to `filter` as this method will be removed in V2.\n\n Args:\n predicate: A function mapping a (nested) structure of tensors (having\n shapes and types defined by `self.output_shapes` and\n `self.output_types`) to a scalar `tf.bool` tensor.\n\n Returns:\n Dataset: The `Dataset` containing the elements of this dataset for which\n `predicate` is `True`.\n \"\"\"\n return FilterDataset(self, predicate, use_legacy_function=True)\n\n @functools.wraps(DatasetV2.apply)\n def apply(self, transformation_func):\n return DatasetV1Adapter(super(DatasetV1, self).apply(transformation_func))\n\n @functools.wraps(DatasetV2.window)\n def window(self, size, shift=None, stride=1, drop_remainder=False):\n return DatasetV1Adapter(super(DatasetV1, self).window(\n size, shift, stride, drop_remainder))\n\n @functools.wraps(DatasetV2.unbatch)\n def unbatch(self):\n return DatasetV1Adapter(super(DatasetV1, self).unbatch())\n\n @functools.wraps(DatasetV2.with_options)\n def with_options(self, options):\n return DatasetV1Adapter(super(DatasetV1, self).with_options(options))\n\n\nif tf2.enabled():\n Dataset = DatasetV2\nelse:\n Dataset = DatasetV1\n\n\nclass DatasetV1Adapter(DatasetV1):\n \"\"\"Wraps a V2 `Dataset` object in the `tf.compat.v1.data.Dataset` API.\"\"\"\n\n def __init__(self, dataset):\n self._dataset = dataset\n super(DatasetV1Adapter, self).__init__()\n\n def _as_variant_tensor(self):\n return self._dataset._variant_tensor # pylint: disable=protected-access\n\n def _has_captured_ref(self):\n return self._dataset._has_captured_ref() # pylint: disable=protected-access\n\n def _inputs(self):\n return self._dataset._inputs() # pylint: disable=protected-access\n\n def _functions(self):\n return self._dataset._functions() # pylint: disable=protected-access\n\n def options(self):\n return self._dataset.options()\n\n @property\n def element_spec(self):\n return self._dataset.element_spec # pylint: disable=protected-access\n\n def __iter__(self):\n return iter(self._dataset)\n\n\ndef _ensure_same_dataset_graph(dataset):\n \"\"\"Walks the dataset graph to ensure all datasets come from the same graph.\"\"\"\n # pylint: disable=protected-access\n current_graph = ops.get_default_graph()\n bfs_q = Queue.Queue()\n bfs_q.put(dataset)\n visited = []\n while not bfs_q.empty():\n ds = bfs_q.get()\n visited.append(ds)\n ds_graph = ds._graph\n if current_graph != ds_graph:\n raise ValueError(\n \"The graph (\" + str(current_graph) + \") of the iterator is different \"\n \"from the graph (\" + str(ds_graph) + \") the dataset: \" +\n str(ds._variant_tensor) + \" was created in. If you are using the \"\n \"Estimator API, make sure that no part of the dataset returned by \"\n \"the `input_fn` function is defined outside the `input_fn` function. \"\n \"Please ensure that all datasets in the pipeline are created in the \"\n \"same graph as the iterator.\")\n for input_ds in ds._inputs():\n if input_ds not in visited:\n bfs_q.put(input_ds)\n\n\n@tf_export(v1=[\"data.make_one_shot_iterator\"])\ndef make_one_shot_iterator(dataset):\n \"\"\"Creates an iterator for elements of `dataset`.\n\n Note: The returned iterator will be initialized automatically.\n A \"one-shot\" iterator does not support re-initialization.\n\n Args:\n dataset: A `tf.data.Dataset`.\n\n Returns:\n A `tf.data.Iterator` for elements of `dataset`.\n \"\"\"\n try:\n # Call the defined `_make_one_shot_iterator()` if there is one, because some\n # datasets (e.g. for prefetching) override its behavior.\n return dataset._make_one_shot_iterator() # pylint: disable=protected-access\n except AttributeError:\n return DatasetV1Adapter(dataset)._make_one_shot_iterator() # pylint: disable=protected-access\n\n\n@tf_export(v1=[\"data.make_initializable_iterator\"])\ndef make_initializable_iterator(dataset, shared_name=None):\n \"\"\"Creates an iterator for elements of `dataset`.\n\n Note: The returned iterator will be in an uninitialized state,\n and you must run the `iterator.initializer` operation before using it:\n\n ```python\n dataset = ...\n iterator = tf.compat.v1.data.make_initializable_iterator(dataset)\n # ...\n sess.run(iterator.initializer)\n ```\n\n Args:\n dataset: A `tf.data.Dataset`.\n shared_name: (Optional.) If non-empty, the returned iterator will be shared\n under the given name across multiple sessions that share the same devices\n (e.g. when using a remote server).\n\n Returns:\n A `tf.data.Iterator` for elements of `dataset`.\n\n Raises:\n RuntimeError: If eager execution is enabled.\n \"\"\"\n try:\n # Call the defined `_make_initializable_iterator()` if there is one, because\n # some datasets (e.g. for prefetching) override its behavior.\n return dataset._make_initializable_iterator(shared_name) # pylint: disable=protected-access\n except AttributeError:\n return DatasetV1Adapter(dataset)._make_initializable_iterator(shared_name) # pylint: disable=protected-access\n\n\n@tf_export(\"data.experimental.get_structure\")\ndef get_structure(dataset_or_iterator):\n \"\"\"Returns the type signature for elements of the input dataset / iterator.\n\n Args:\n dataset_or_iterator: A `tf.data.Dataset` or an `tf.data.Iterator`.\n\n Returns:\n A (nested) structure of `tf.TypeSpec` objects matching the structure of an\n element of `dataset_or_iterator` and specifying the type of individual\n components.\n\n Raises:\n TypeError: If input is not a `tf.data.Dataset` or an `tf.data.Iterator`\n object.\n \"\"\"\n try:\n return dataset_or_iterator.element_spec # pylint: disable=protected-access\n except AttributeError:\n raise TypeError(\"`dataset_or_iterator` must be a `tf.data.Dataset` or \"\n \"tf.data.Iterator object, but got %s.\" %\n type(dataset_or_iterator))\n\n\n@tf_export(v1=[\"data.get_output_classes\"])\ndef get_legacy_output_classes(dataset_or_iterator):\n \"\"\"Returns the output classes for elements of the input dataset / iterator.\n\n Args:\n dataset_or_iterator: A `tf.data.Dataset` or `tf.data.Iterator`.\n\n Returns:\n A (nested) structure of Python `type` objects matching the structure of the\n dataset / iterator elements and specifying the class of the individual\n components.\n \"\"\"\n return nest.map_structure(\n lambda component_spec: component_spec._to_legacy_output_classes(), # pylint: disable=protected-access\n get_structure(dataset_or_iterator))\n\n\n@tf_export(v1=[\"data.get_output_shapes\"])\ndef get_legacy_output_shapes(dataset_or_iterator):\n \"\"\"Returns the output shapes for elements of the input dataset / iterator.\n\n Args:\n dataset_or_iterator: A `tf.data.Dataset` or `tf.data.Iterator`.\n\n Returns:\n A (nested) structure of `tf.TensorShape` objects matching the structure of\n the dataset / iterator elements and specifying the shape of the individual\n components.\n \"\"\"\n return nest.map_structure(\n lambda component_spec: component_spec._to_legacy_output_shapes(), # pylint: disable=protected-access\n get_structure(dataset_or_iterator))\n\n\n@tf_export(v1=[\"data.get_output_types\"])\ndef get_legacy_output_types(dataset_or_iterator):\n \"\"\"Returns the output shapes for elements of the input dataset / iterator.\n\n Args:\n dataset_or_iterator: A `tf.data.Dataset` or `tf.data.Iterator`.\n\n Returns:\n A (nested) structure of `tf.DType` objects matching the structure of\n dataset / iterator elements and specifying the shape of the individual\n components.\n \"\"\"\n return nest.map_structure(\n lambda component_spec: component_spec._to_legacy_output_types(), # pylint: disable=protected-access\n get_structure(dataset_or_iterator))\n\n\n@tf_export(\"data.Options\")\nclass Options(options_lib.OptionsBase):\n \"\"\"Represents options for `tf.data.Dataset`.\n\n A `tf.data.Options` object can be, for instance, used to control which static\n optimizations to apply to the input pipeline graph or whether to use\n performance modeling to dynamically tune the parallelism of operations such as\n `tf.data.Dataset.map` or `tf.data.Dataset.interleave`.\n\n The options are set for the entire dataset and are carried over to datasets\n created through tf.data transformations.\n\n The options can be set by constructing an `Options` object and using the\n `tf.data.Dataset.with_options(options)` transformation, which returns a\n dataset with the options set.\n\n >>> dataset = tf.data.Dataset.range(42)\n >>> options = tf.data.Options()\n >>> options.experimental_deterministic = False\n >>> dataset = dataset.with_options(options)\n >>> print(dataset.options().experimental_deterministic)\n False\n\n Note: A known limitation of the `tf.data.Options` implementation is that the\n options are not preserved across tf.function boundaries. In particular, to\n set options for a dataset that is iterated within a tf.function, the options\n need to be set within the same tf.function.\n \"\"\"\n\n experimental_deterministic = options_lib.create_option(\n name=\"experimental_deterministic\",\n ty=bool,\n docstring=\n \"Whether the outputs need to be produced in deterministic order. If None,\"\n \" defaults to True.\")\n\n experimental_distribute = options_lib.create_option(\n name=\"experimental_distribute\",\n ty=distribute_options.DistributeOptions,\n docstring=\n \"The distribution strategy options associated with the dataset. See \"\n \"`tf.data.experimental.DistributeOptions` for more details.\",\n default_factory=distribute_options.DistributeOptions)\n\n experimental_optimization = options_lib.create_option(\n name=\"experimental_optimization\",\n ty=optimization_options.OptimizationOptions,\n docstring=\n \"The optimization options associated with the dataset. See \"\n \"`tf.data.experimental.OptimizationOptions` for more details.\",\n default_factory=optimization_options.OptimizationOptions)\n\n experimental_slack = options_lib.create_option(\n name=\"experimental_slack\",\n ty=bool,\n docstring=\"Whether to introduce 'slack' in the last `prefetch` of the \"\n \"input pipeline, if it exists. This may reduce CPU contention with \"\n \"accelerator host-side activity at the start of a step. The slack \"\n \"frequency is determined by the number of devices attached to this \"\n \"input pipeline. If None, defaults to False.\")\n\n experimental_stats = options_lib.create_option(\n name=\"experimental_stats\",\n ty=stats_options.StatsOptions,\n docstring=\n \"The statistics options associated with the dataset. See \"\n \"`tf.data.experimental.StatsOptions` for more details.\",\n default_factory=stats_options.StatsOptions)\n\n experimental_threading = options_lib.create_option(\n name=\"experimental_threading\",\n ty=threading_options.ThreadingOptions,\n docstring=\n \"The threading options associated with the dataset. See \"\n \"`tf.data.experimental.ThreadingOptions` for more details.\",\n default_factory=threading_options.ThreadingOptions)\n\n experimental_external_state_policy = options_lib.create_option(\n name=\"experimental_external_state_policy\",\n ty=distribute_options.ExternalStatePolicy,\n docstring=\"This option can be used to override the default policy for \"\n \"how to handle external state when serializing a dataset or \"\n \"checkpointing its iterator. There are three settings available - \"\n \"IGNORE: External state is ignored without a warning; WARN: External \"\n \"state is ignored and a warning is logged; FAIL: External state results \"\n \"in an error.\")\n\n def _to_proto(self):\n pb = dataset_options_pb2.Options()\n if self.experimental_deterministic is not None:\n pb.deterministic = self.experimental_deterministic\n pb.distribute_options.CopyFrom(self.experimental_distribute._to_proto()) # pylint: disable=protected-access\n if self.experimental_external_state_policy is not None:\n pb.external_state_policy = (\n distribute_options.ExternalStatePolicy._to_proto( # pylint: disable=protected-access\n self.experimental_external_state_policy))\n pb.optimization_options.CopyFrom(self.experimental_optimization._to_proto()) # pylint: disable=protected-access\n if self.experimental_slack is not None:\n pb.slack = self.experimental_slack\n pb.threading_options.CopyFrom(self.experimental_threading._to_proto()) # pylint: disable=protected-access\n return pb\n\n def _from_proto(self, pb):\n if pb.WhichOneof(\"optional_deterministic\") is not None:\n self.experimental_deterministic = pb.deterministic\n self.experimental_distribute._from_proto(pb.distribute_options) # pylint: disable=protected-access\n if pb.WhichOneof(\"optional_external_state_policy\") is not None:\n self.experimental_external_state_policy = (\n distribute_options.ExternalStatePolicy._from_proto( # pylint: disable=protected-access\n pb.external_state_policy))\n self.experimental_optimization._from_proto(pb.optimization_options) # pylint: disable=protected-access\n if pb.WhichOneof(\"optional_slack\") is not None:\n self.experimental_slack = pb.slack\n self.experimental_threading._from_proto(pb.threading_options) # pylint: disable=protected-access\n\n def _set_mutable(self, mutable):\n \"\"\"Change the mutability value to `mutable` on this options and children.\"\"\"\n # pylint: disable=protected-access\n object.__setattr__(self, \"_mutable\", mutable)\n self.experimental_distribute._set_mutable(mutable)\n self.experimental_optimization._set_mutable(mutable)\n self.experimental_threading._set_mutable(mutable)\n\n def _graph_rewrites(self):\n \"\"\"Produces lists of enabled, disabled, default static graph rewrites.\n\n Returns:\n result: a namedtuple with three attributes. `result.enabled` is the list\n of user enabled graph rewrites. `result.disabled` is the list of user\n disabled graph rewrites. `result.default` is the list of graph\n rewrites that are enabled by default (the user has not explicitly\n enabled or disabled them).\n \"\"\"\n if self.experimental_optimization is not None:\n result = self.experimental_optimization._graph_rewrites() # pylint: disable=protected-access\n else:\n # Apply default options\n result = optimization_options.OptimizationOptions()._graph_rewrites() # pylint: disable=protected-access\n\n if self.experimental_deterministic is False: # pylint: disable=g-bool-id-comparison\n result.enabled.append(\"make_sloppy\")\n elif self.experimental_deterministic is True: # pylint: disable=g-bool-id-comparison\n result.disabled.append(\"make_sloppy\")\n if self.experimental_stats:\n if self.experimental_stats.latency_all_edges is True: # pylint: disable=g-bool-id-comparison\n result.enabled.append(\"latency_all_edges\")\n elif self.experimental_stats.latency_all_edges is False: # pylint: disable=g-bool-id-comparison\n result.disabled.append(\"latency_all_edges\")\n if self.experimental_slack is True: # pylint: disable=g-bool-id-comparison\n result.enabled.append(\"slack\")\n elif self.experimental_slack is False: # pylint: disable=g-bool-id-comparison\n result.disabled.append(\"slack\")\n\n graph_rewrites = options_lib.graph_rewrites()\n return graph_rewrites(enabled=list(set(result.enabled)),\n disabled=list(set(result.disabled)),\n default=list(set(result.default)))\n\n def _graph_rewrite_configs(self, autotune):\n \"\"\"Produces the list of configurations for enabled graph optimizations.\"\"\"\n result = []\n if self.experimental_optimization:\n result.extend(\n self.experimental_optimization._graph_rewrite_configs(autotune)) # pylint: disable=protected-access\n\n if self.experimental_slack:\n num_devices = self.experimental_distribute.num_devices\n if num_devices is None:\n num_devices = 1\n result.append(\"slack:slack_period:%d\" % num_devices)\n return result\n\n def _autotune_settings(self):\n if self.experimental_optimization is not None:\n return self.experimental_optimization._autotune_settings() # pylint: disable=protected-access\n\n # Return default autotune options\n return optimization_options.OptimizationOptions()._autotune_settings() # pylint: disable=protected-access\n\n def merge(self, options):\n \"\"\"Merges itself with the given `tf.data.Options`.\n\n If this object and the `options` to merge set an option differently, a\n warning is generated and this object's value is updated with the `options`\n object's value.\n\n Args:\n options: a `tf.data.Options` to merge with\n\n Returns:\n New `tf.data.Options` object which is the result of merging self with\n the input `tf.data.Options`.\n \"\"\"\n return options_lib.merge_options(self, options)\n\n\nclass DatasetSource(DatasetV2):\n \"\"\"Abstract class representing a dataset with no inputs.\"\"\"\n\n def _inputs(self):\n return []\n\n\nclass UnaryDataset(DatasetV2):\n \"\"\"Abstract class representing a dataset with one input.\"\"\"\n\n def __init__(self, input_dataset, variant_tensor):\n self._input_dataset = input_dataset\n super(UnaryDataset, self).__init__(variant_tensor)\n\n def _inputs(self):\n return [self._input_dataset]\n\n\nclass UnaryUnchangedStructureDataset(UnaryDataset):\n \"\"\"Represents a unary dataset with the same input and output structure.\"\"\"\n\n def __init__(self, input_dataset, variant_tensor):\n self._input_dataset = input_dataset\n super(UnaryUnchangedStructureDataset, self).__init__(\n input_dataset, variant_tensor)\n\n @property\n def element_spec(self):\n return self._input_dataset.element_spec\n\n\nclass TensorDataset(DatasetSource):\n \"\"\"A `Dataset` with a single element.\"\"\"\n\n def __init__(self, element):\n \"\"\"See `Dataset.from_tensors()` for details.\"\"\"\n element = structure.normalize_element(element)\n self._structure = structure.type_spec_from_value(element)\n self._tensors = structure.to_tensor_list(self._structure, element)\n\n variant_tensor = gen_dataset_ops.tensor_dataset(\n self._tensors,\n output_shapes=structure.get_flat_tensor_shapes(self._structure))\n super(TensorDataset, self).__init__(variant_tensor)\n\n @property\n def element_spec(self):\n return self._structure\n\n\nclass TensorSliceDataset(DatasetSource):\n \"\"\"A `Dataset` of slices from a dataset element.\"\"\"\n\n def __init__(self, element):\n \"\"\"See `Dataset.from_tensor_slices()` for details.\"\"\"\n element = structure.normalize_element(element)\n batched_spec = structure.type_spec_from_value(element)\n self._tensors = structure.to_batched_tensor_list(batched_spec, element)\n self._structure = nest.map_structure(\n lambda component_spec: component_spec._unbatch(), batched_spec) # pylint: disable=protected-access\n\n batch_dim = tensor_shape.Dimension(tensor_shape.dimension_value(\n self._tensors[0].get_shape()[0]))\n for t in self._tensors[1:]:\n batch_dim.assert_is_compatible_with(tensor_shape.Dimension(\n tensor_shape.dimension_value(t.get_shape()[0])))\n\n variant_tensor = gen_dataset_ops.tensor_slice_dataset(\n self._tensors,\n output_shapes=structure.get_flat_tensor_shapes(self._structure))\n super(TensorSliceDataset, self).__init__(variant_tensor)\n\n @property\n def element_spec(self):\n return self._structure\n\n\nclass SparseTensorSliceDataset(DatasetSource):\n \"\"\"A `Dataset` that splits a rank-N `tf.sparse.SparseTensor` into its rows.\"\"\"\n\n def __init__(self, sparse_tensor):\n \"\"\"See `Dataset.from_sparse_tensor_slices()` for details.\"\"\"\n if not isinstance(sparse_tensor, sparse_tensor_lib.SparseTensor):\n raise TypeError(\n \"`sparse_tensor` must be a `tf.sparse.SparseTensor` object.\"\n \"Was {}.\".format(sparse_tensor))\n self._sparse_tensor = sparse_tensor\n\n indices_shape = self._sparse_tensor.indices.get_shape()\n shape_shape = self._sparse_tensor.dense_shape.get_shape()\n rank = (indices_shape.dims[1] - 1).merge_with(shape_shape.dims[0] - 1)\n self._structure = (tensor_spec.TensorSpec([None, rank], dtypes.int64),\n tensor_spec.TensorSpec([None],\n self._sparse_tensor.dtype),\n tensor_spec.TensorSpec([rank], dtypes.int64))\n\n variant_tensor = gen_dataset_ops.sparse_tensor_slice_dataset(\n self._sparse_tensor.indices, self._sparse_tensor.values,\n self._sparse_tensor.dense_shape)\n super(SparseTensorSliceDataset, self).__init__(variant_tensor)\n\n @property\n def element_spec(self):\n return self._structure\n\n\nclass _VariantDataset(DatasetV2):\n \"\"\"A Dataset wrapper around a `tf.variant`-typed function argument.\"\"\"\n\n def __init__(self, dataset_variant, structure):\n self._structure = structure\n super(_VariantDataset, self).__init__(dataset_variant)\n\n def _inputs(self):\n return []\n\n @property\n def element_spec(self):\n return self._structure\n\n\nclass _NestedVariant(composite_tensor.CompositeTensor):\n\n def __init__(self, variant_tensor, element_spec, dataset_shape):\n self._variant_tensor = variant_tensor\n self._element_spec = element_spec\n self._dataset_shape = dataset_shape\n\n @property\n def _type_spec(self):\n return DatasetSpec(self._element_spec, self._dataset_shape)\n\n\n@tf_export(\"data.experimental.from_variant\")\ndef from_variant(variant, structure):\n \"\"\"Constructs a dataset from the given variant and (nested) structure.\n\n Args:\n variant: A scalar `tf.variant` tensor representing a dataset.\n structure: A (nested) structure of `tf.TypeSpec` objects representing the\n structure of each element in the dataset.\n\n Returns:\n A `tf.data.Dataset` instance.\n \"\"\"\n return _VariantDataset(variant, structure) # pylint: disable=protected-access\n\n\n@tf_export(\"data.experimental.to_variant\")\ndef to_variant(dataset):\n \"\"\"Returns a variant representing the given dataset.\n\n Args:\n dataset: A `tf.data.Dataset`.\n\n Returns:\n A scalar `tf.variant` tensor representing the given dataset.\n \"\"\"\n return dataset._variant_tensor # pylint: disable=protected-access\n\n\n@tf_export(\n \"data.DatasetSpec\",\n v1=[\"data.DatasetSpec\", \"data.experimental.DatasetStructure\"])\nclass DatasetSpec(type_spec.BatchableTypeSpec):\n \"\"\"Type specification for `tf.data.Dataset`.\n\n See `tf.TypeSpec` for more information about TensorFlow type specifications.\n\n >>> dataset = tf.data.Dataset.range(3)\n >>> tf.data.DatasetSpec.from_value(dataset)\n DatasetSpec(TensorSpec(shape=(), dtype=tf.int64, name=None), TensorShape([]))\n \"\"\"\n\n __slots__ = [\"_element_spec\", \"_dataset_shape\"]\n\n def __init__(self, element_spec, dataset_shape=()):\n self._element_spec = element_spec\n self._dataset_shape = tensor_shape.as_shape(dataset_shape)\n\n @property\n def value_type(self):\n return Dataset\n\n @property\n def element_spec(self):\n \"\"\"The inner element spec.\"\"\"\n return self._element_spec\n\n def _serialize(self):\n return (self._element_spec, self._dataset_shape)\n\n @property\n def _component_specs(self):\n return tensor_spec.TensorSpec(self._dataset_shape, dtypes.variant)\n\n def _to_components(self, value):\n return value._variant_tensor # pylint: disable=protected-access\n\n def _from_components(self, components):\n # pylint: disable=protected-access\n if self._dataset_shape.ndims == 0:\n return _VariantDataset(components, self._element_spec)\n else:\n return _NestedVariant(components, self._element_spec, self._dataset_shape)\n\n def _to_tensor_list(self, value):\n return [\n ops.convert_to_tensor(\n tf_nest.map_structure(lambda x: x._variant_tensor, value)) # pylint: disable=protected-access\n ]\n\n @staticmethod\n def from_value(value):\n \"\"\"Creates a `DatasetSpec` for the given `tf.data.Dataset` value.\"\"\"\n return DatasetSpec(value.element_spec) # pylint: disable=protected-access\n\n def _batch(self, batch_size):\n return DatasetSpec(\n self._element_spec,\n tensor_shape.TensorShape([batch_size]).concatenate(self._dataset_shape))\n\n def _unbatch(self):\n if self._dataset_shape.ndims == 0:\n raise ValueError(\"Unbatching a dataset is only supported for rank >= 1\")\n return DatasetSpec(self._element_spec, self._dataset_shape[1:])\n\n def _to_batched_tensor_list(self, value):\n if self._dataset_shape.ndims == 0:\n raise ValueError(\"Unbatching a dataset is only supported for rank >= 1\")\n return self._to_tensor_list(value)\n\n def _to_legacy_output_types(self):\n return self\n\n def _to_legacy_output_shapes(self):\n return self\n\n def _to_legacy_output_classes(self):\n return self\n\n\nclass StructuredFunctionWrapper(object):\n \"\"\"A function wrapper that supports structured arguments and return values.\"\"\"\n\n def __init__(self,\n func,\n transformation_name,\n dataset=None,\n input_classes=None,\n input_shapes=None,\n input_types=None,\n input_structure=None,\n add_to_graph=True,\n use_legacy_function=False,\n defun_kwargs=None):\n \"\"\"Creates a new `StructuredFunctionWrapper` for the given function.\n\n Args:\n func: A function from a (nested) structure to another (nested) structure.\n transformation_name: Human-readable name of the transformation in which\n this function is being instantiated, for error messages.\n dataset: (Optional.) A `tf.data.Dataset`. If given, the structure of this\n dataset will be assumed as the structure for `func` arguments; otherwise\n `input_classes`, `input_shapes`, and `input_types` must be defined.\n input_classes: (Optional.) A (nested) structure of `type`. If given, this\n argument defines the Python types for `func` arguments.\n input_shapes: (Optional.) A (nested) structure of `tf.TensorShape`. If\n given, this argument defines the shapes and structure for `func`\n arguments.\n input_types: (Optional.) A (nested) structure of `tf.DType`. If given,\n this argument defines the element types and structure for `func`\n arguments.\n input_structure: (Optional.) A `Structure` object. If given, this argument\n defines the element types and structure for `func` arguments.\n add_to_graph: (Optional.) If `True`, the function will be added to the\n default graph, if it exists.\n use_legacy_function: (Optional.) A boolean that determines whether the\n function be created using `tensorflow.python.eager.function.defun`\n (default behavior) or `tensorflow.python.framework.function.Defun`\n (legacy behavior).\n defun_kwargs: (Optional.) A dictionary mapping string argument names to\n values. If supplied, will be passed to `function` as keyword arguments.\n\n Raises:\n ValueError: If an invalid combination of `dataset`, `input_classes`,\n `input_shapes`, and `input_types` is passed.\n \"\"\"\n # pylint: disable=protected-access\n if input_structure is None:\n if dataset is None:\n if input_classes is None or input_shapes is None or input_types is None:\n raise ValueError(\"Either `dataset`, `input_structure` or all of \"\n \"`input_classes`, `input_shapes`, and `input_types` \"\n \"must be specified.\")\n self._input_structure = structure.convert_legacy_structure(\n input_types, input_shapes, input_classes)\n else:\n if not (input_classes is None and input_shapes is None and\n input_types is None):\n raise ValueError(\"Either `dataset`, `input_structure` or all of \"\n \"`input_classes`, `input_shapes`, and `input_types` \"\n \"must be specified.\")\n self._input_structure = dataset.element_spec\n else:\n if not (dataset is None and input_classes is None and input_shapes is None\n and input_types is None):\n raise ValueError(\"Either `dataset`, `input_structure`, or all of \"\n \"`input_classes`, `input_shapes`, and `input_types` \"\n \"must be specified.\")\n self._input_structure = input_structure\n\n self._func = func\n\n # There is no graph to add in eager mode.\n add_to_graph &= not context.executing_eagerly()\n # There are some lifetime issues when a legacy function is not added to a\n # out-living graph. It's already deprecated so de-prioritizing the fix.\n add_to_graph |= use_legacy_function\n\n if defun_kwargs is None:\n defun_kwargs = {}\n\n readable_transformation_name = transformation_name.replace(\n \".\", \"_\")[:-2] if len(transformation_name) > 2 else \"\"\n\n func_name = \"_\".join(\n [readable_transformation_name,\n function_utils.get_func_name(func)])\n # Sanitize function name to remove symbols that interfere with graph\n # construction.\n for symbol in [\"<\", \">\", \"\\\\\", \"'\", \" \"]:\n func_name = func_name.replace(symbol, \"\")\n\n ag_ctx = autograph_ctx.control_status_ctx()\n\n def _warn_if_collections(transformation_name):\n \"\"\"Prints a warning if the given graph uses common graph collections.\n\n NOTE(mrry): Currently a warning is only generated for resources. Any\n variables created will be automatically hoisted out to the outermost scope\n using `init_scope()`. Some collections (such as for control-flow contexts)\n are benign and should not generate a warning.\n\n Args:\n transformation_name: A human-readable name for the transformation.\n \"\"\"\n warnings.warn(\"Creating resources inside a function passed to %s \"\n \"is not supported. Create each resource outside the \"\n \"function, and capture it inside the function to use it.\" %\n transformation_name, stacklevel=5)\n\n def _wrapper_helper(*args):\n \"\"\"Wrapper for passing nested structures to and from tf.data functions.\"\"\"\n nested_args = structure.from_compatible_tensor_list(\n self._input_structure, args)\n if not _should_unpack_args(nested_args):\n nested_args = (nested_args,)\n\n ret = autograph.tf_convert(func, ag_ctx)(*nested_args)\n # If `func` returns a list of tensors, `nest.flatten()` and\n # `ops.convert_to_tensor()` would conspire to attempt to stack\n # those tensors into a single tensor, because the customized\n # version of `nest.flatten()` does not recurse into lists. Since\n # it is more likely that the list arose from returning the\n # result of an operation (such as `tf.numpy_function()`) that returns a\n # list of not-necessarily-stackable tensors, we treat the\n # returned value is a `tuple` instead. A user wishing to pack\n # the return value into a single tensor can use an explicit\n # `tf.stack()` before returning.\n if isinstance(ret, list):\n ret = tuple(ret)\n\n try:\n self._output_structure = structure.type_spec_from_value(ret)\n except (ValueError, TypeError):\n six.reraise(\n TypeError,\n TypeError(\"Unsupported return value from function passed to \"\n \"%s: %s.\" % (transformation_name, ret)),\n sys.exc_info()[2])\n return ret\n\n if use_legacy_function:\n func_name = func_name + \"_\" + str(ops.uid())\n\n @function.Defun(\n *structure.get_flat_tensor_types(self._input_structure),\n func_name=func_name,\n **defun_kwargs)\n def wrapper_fn(*args):\n ret = _wrapper_helper(*args)\n # _warn_if_collections(transformation_name, ops.get_default_graph(), 0)\n return structure.to_tensor_list(self._output_structure, ret)\n\n self._function = wrapper_fn\n resource_tracker = tracking.ResourceTracker()\n with tracking.resource_tracker_scope(resource_tracker):\n if add_to_graph:\n self._function.add_to_graph(ops.get_default_graph())\n else:\n # Use the private method that will execute `wrapper_fn` but delay\n # adding it to the graph in case (e.g.) we need to rerun the function.\n self._function._create_definition_if_needed()\n if resource_tracker.resources:\n _warn_if_collections(transformation_name)\n\n else:\n if def_function.functions_run_eagerly():\n warnings.warn(\n \"Even though the tf.config.experimental_run_functions_eagerly \"\n \"option is set, this option does not apply to tf.data functions. \"\n \"tf.data functions are still traced and executed as graphs.\")\n\n defun_kwargs.update({\"func_name\": func_name})\n defun_kwargs.update({\"_tf_data_function\": True})\n\n # Note: _wrapper_helper will apply autograph based on context.\n @eager_function.defun_with_attributes(\n input_signature=structure.get_flat_tensor_specs(\n self._input_structure),\n autograph=False,\n attributes=defun_kwargs)\n def wrapper_fn(*args): # pylint: disable=missing-docstring\n ret = _wrapper_helper(*args)\n ret = structure.to_tensor_list(self._output_structure, ret)\n return [ops.convert_to_tensor(t) for t in ret]\n\n resource_tracker = tracking.ResourceTracker()\n with tracking.resource_tracker_scope(resource_tracker):\n # TODO(b/141462134): Switch to using garbage collection.\n self._function = wrapper_fn.get_concrete_function()\n if add_to_graph:\n self._function.add_to_graph(ops.get_default_graph())\n\n if resource_tracker.resources:\n _warn_if_collections(transformation_name)\n\n outer_graph_seed = ops.get_default_graph().seed\n if outer_graph_seed and self._function.graph.seed == outer_graph_seed:\n if self._function.graph._seed_used:\n warnings.warn(\n \"Seed %s from outer graph might be getting used by function %s, \"\n \"if the random op has not been provided any seed. Explicitly set \"\n \"the seed in the function if this is not the intended behavior.\"\n %(outer_graph_seed, func_name), stacklevel=4)\n\n @property\n def output_structure(self):\n return self._output_structure\n\n @property\n def output_classes(self):\n return nest.map_structure(\n lambda component_spec: component_spec._to_legacy_output_classes(), # pylint: disable=protected-access\n self._output_structure)\n\n @property\n def output_shapes(self):\n return nest.map_structure(\n lambda component_spec: component_spec._to_legacy_output_shapes(), # pylint: disable=protected-access\n self._output_structure)\n\n @property\n def output_types(self):\n return nest.map_structure(\n lambda component_spec: component_spec._to_legacy_output_types(), # pylint: disable=protected-access\n self._output_structure)\n\n @property\n def function(self):\n return self._function\n\n\nclass _GeneratorDataset(DatasetSource):\n \"\"\"A `Dataset` that generates elements by invoking a function.\"\"\"\n\n def __init__(self, init_args, init_func, next_func, finalize_func,\n output_signature):\n \"\"\"Constructs a `_GeneratorDataset`.\n\n Args:\n init_args: A (nested) structure representing the arguments to `init_func`.\n init_func: A TensorFlow function that will be called on `init_args` each\n time a C++ iterator over this dataset is constructed. Returns a (nested)\n structure representing the \"state\" of the dataset.\n next_func: A TensorFlow function that will be called on the result of\n `init_func` to produce each element, and that raises `OutOfRangeError`\n to terminate iteration.\n finalize_func: A TensorFlow function that will be called on the result of\n `init_func` immediately before a C++ iterator over this dataset is\n destroyed. The return value is ignored.\n output_signature: A (nested) structure of `tf.TypeSpec` objects describing\n the output of `next_func`.\n \"\"\"\n self._init_args = init_args\n\n self._init_structure = structure.type_spec_from_value(init_args)\n\n self._init_func = StructuredFunctionWrapper(\n init_func,\n self._transformation_name(),\n input_structure=self._init_structure)\n\n self._next_func = StructuredFunctionWrapper(\n next_func,\n self._transformation_name(),\n input_structure=self._init_func.output_structure)\n\n self._finalize_func = StructuredFunctionWrapper(\n finalize_func,\n self._transformation_name(),\n input_structure=self._init_func.output_structure)\n\n self._output_signature = output_signature\n\n variant_tensor = gen_dataset_ops.generator_dataset(\n structure.to_tensor_list(self._init_structure, self._init_args) +\n self._init_func.function.captured_inputs,\n self._next_func.function.captured_inputs,\n self._finalize_func.function.captured_inputs,\n init_func=self._init_func.function,\n next_func=self._next_func.function,\n finalize_func=self._finalize_func.function,\n **self._flat_structure)\n super(_GeneratorDataset, self).__init__(variant_tensor)\n\n @property\n def element_spec(self):\n return self._output_signature\n\n def _transformation_name(self):\n return \"Dataset.from_generator()\"\n\n\nclass ZipDataset(DatasetV2):\n \"\"\"A `Dataset` that zips its inputs together.\"\"\"\n\n def __init__(self, datasets):\n \"\"\"See `Dataset.zip()` for details.\"\"\"\n for ds in nest.flatten(datasets):\n if not isinstance(ds, DatasetV2):\n if isinstance(ds, list):\n message = (\"The argument to `Dataset.zip()` must be a (nested) \"\n \"structure of `Dataset` objects. Python `list` is not \"\n \"supported, please use a `tuple` instead.\")\n else:\n message = (\"The argument to `Dataset.zip()` must be a (nested) \"\n \"structure of `Dataset` objects.\")\n raise TypeError(message)\n self._datasets = datasets\n self._structure = nest.pack_sequence_as(\n self._datasets,\n [ds.element_spec for ds in nest.flatten(self._datasets)])\n variant_tensor = gen_dataset_ops.zip_dataset(\n [ds._variant_tensor for ds in nest.flatten(self._datasets)],\n **self._flat_structure)\n super(ZipDataset, self).__init__(variant_tensor)\n\n def _inputs(self):\n return nest.flatten(self._datasets)\n\n @property\n def element_spec(self):\n return self._structure\n\n\nclass ConcatenateDataset(DatasetV2):\n \"\"\"A `Dataset` that concatenates its input with given dataset.\"\"\"\n\n def __init__(self, input_dataset, dataset_to_concatenate):\n \"\"\"See `Dataset.concatenate()` for details.\"\"\"\n self._input_dataset = input_dataset\n self._dataset_to_concatenate = dataset_to_concatenate\n\n output_types = get_legacy_output_types(input_dataset)\n if output_types != get_legacy_output_types(dataset_to_concatenate):\n raise TypeError(\n \"Two datasets to concatenate have different types %s and %s\" %\n (output_types, get_legacy_output_types(dataset_to_concatenate)))\n\n output_classes = get_legacy_output_classes(input_dataset)\n if output_classes != get_legacy_output_classes(dataset_to_concatenate):\n raise TypeError(\n \"Two datasets to concatenate have different classes %s and %s\" %\n (output_classes, get_legacy_output_classes(dataset_to_concatenate)))\n\n input_shapes = get_legacy_output_shapes(self._input_dataset)\n output_shapes = nest.pack_sequence_as(input_shapes, [\n ts1.most_specific_compatible_shape(ts2)\n for (ts1, ts2) in zip(\n nest.flatten(input_shapes),\n nest.flatten(get_legacy_output_shapes(\n self._dataset_to_concatenate)))\n ])\n\n self._structure = structure.convert_legacy_structure(\n output_types, output_shapes, output_classes)\n\n self._input_datasets = [input_dataset, dataset_to_concatenate]\n # pylint: disable=protected-access\n variant_tensor = gen_dataset_ops.concatenate_dataset(\n input_dataset._variant_tensor, dataset_to_concatenate._variant_tensor,\n **self._flat_structure)\n # pylint: enable=protected-access\n super(ConcatenateDataset, self).__init__(variant_tensor)\n\n def _inputs(self):\n return self._input_datasets\n\n @property\n def element_spec(self):\n return self._structure\n\n\nclass RepeatDataset(UnaryUnchangedStructureDataset):\n \"\"\"A `Dataset` that repeats its input several times.\"\"\"\n\n def __init__(self, input_dataset, count):\n \"\"\"See `Dataset.repeat()` for details.\"\"\"\n self._input_dataset = input_dataset\n if count is None:\n self._count = constant_op.constant(-1, dtype=dtypes.int64, name=\"count\")\n else:\n self._count = ops.convert_to_tensor(\n count, dtype=dtypes.int64, name=\"count\")\n variant_tensor = gen_dataset_ops.repeat_dataset(\n input_dataset._variant_tensor, # pylint: disable=protected-access\n count=self._count,\n **self._flat_structure)\n super(RepeatDataset, self).__init__(input_dataset, variant_tensor)\n\n\nclass RangeDataset(DatasetSource):\n \"\"\"A `Dataset` of a step separated range of values.\"\"\"\n\n def __init__(self, *args, **kwargs):\n \"\"\"See `Dataset.range()` for details.\"\"\"\n self._parse_args(*args, **kwargs)\n self._structure = tensor_spec.TensorSpec([], self._output_type)\n variant_tensor = gen_dataset_ops.range_dataset(\n start=self._start,\n stop=self._stop,\n step=self._step,\n **self._flat_structure)\n super(RangeDataset, self).__init__(variant_tensor)\n\n def _parse_args(self, *args, **kwargs):\n \"\"\"Parse arguments according to the same rules as the `range()` builtin.\"\"\"\n if len(args) == 1:\n self._start = self._build_tensor(0, \"start\")\n self._stop = self._build_tensor(args[0], \"stop\")\n self._step = self._build_tensor(1, \"step\")\n elif len(args) == 2:\n self._start = self._build_tensor(args[0], \"start\")\n self._stop = self._build_tensor(args[1], \"stop\")\n self._step = self._build_tensor(1, \"step\")\n elif len(args) == 3:\n self._start = self._build_tensor(args[0], \"start\")\n self._stop = self._build_tensor(args[1], \"stop\")\n self._step = self._build_tensor(args[2], \"step\")\n else:\n raise ValueError(\"Invalid arguments to RangeDataset: %s\" % str(args))\n if \"output_type\" in kwargs:\n self._output_type = kwargs[\"output_type\"]\n else:\n self._output_type = dtypes.int64\n\n def _build_tensor(self, int64_value, name):\n return ops.convert_to_tensor(int64_value, dtype=dtypes.int64, name=name)\n\n @property\n def element_spec(self):\n return self._structure\n\n\nclass CacheDataset(UnaryUnchangedStructureDataset):\n \"\"\"A `Dataset` that caches elements of its input.\"\"\"\n\n def __init__(self, input_dataset, filename):\n \"\"\"See `Dataset.cache()` for details.\"\"\"\n self._input_dataset = input_dataset\n self._filename = ops.convert_to_tensor(\n filename, dtype=dtypes.string, name=\"filename\")\n if tf2.enabled() and (context.executing_eagerly() or ops.inside_function()):\n variant_tensor = gen_dataset_ops.cache_dataset_v2(\n input_dataset._variant_tensor, # pylint: disable=protected-access\n filename=self._filename,\n cache=gen_dataset_ops.dummy_memory_cache(),\n **self._flat_structure)\n else:\n variant_tensor = gen_dataset_ops.cache_dataset(\n input_dataset._variant_tensor, # pylint: disable=protected-access\n filename=self._filename,\n **self._flat_structure)\n super(CacheDataset, self).__init__(input_dataset, variant_tensor)\n\n\nclass ShuffleDataset(UnaryUnchangedStructureDataset):\n \"\"\"A `Dataset` that randomly shuffles the elements of its input.\"\"\"\n\n def __init__(self,\n input_dataset,\n buffer_size,\n seed=None,\n reshuffle_each_iteration=None):\n \"\"\"Randomly shuffles the elements of this dataset.\n\n Args:\n input_dataset: The input dataset.\n buffer_size: A `tf.int64` scalar `tf.Tensor`, representing the number of\n elements from this dataset from which the new dataset will sample.\n seed: (Optional.) A `tf.int64` scalar `tf.Tensor`, representing the random\n seed that will be used to create the distribution. See\n `tf.random.set_seed` for behavior.\n reshuffle_each_iteration: (Optional.) A boolean, which if true indicates\n that the dataset should be pseudorandomly reshuffled each time it is\n iterated over. (Defaults to `True`.)\n\n Returns:\n A `Dataset`.\n\n Raises:\n ValueError: if invalid arguments are provided.\n \"\"\"\n self._input_dataset = input_dataset\n self._buffer_size = ops.convert_to_tensor(\n buffer_size, dtype=dtypes.int64, name=\"buffer_size\")\n self._seed, self._seed2 = random_seed.get_seed(seed)\n if reshuffle_each_iteration is None:\n reshuffle_each_iteration = True\n self._reshuffle_each_iteration = reshuffle_each_iteration\n\n if (tf2.enabled() and\n (context.executing_eagerly() or ops.inside_function())):\n variant_tensor = gen_dataset_ops.shuffle_dataset_v3(\n input_dataset._variant_tensor, # pylint: disable=protected-access\n buffer_size=self._buffer_size,\n seed=self._seed,\n seed2=self._seed2,\n seed_generator=gen_dataset_ops.dummy_seed_generator(),\n reshuffle_each_iteration=self._reshuffle_each_iteration,\n **self._flat_structure)\n else:\n variant_tensor = gen_dataset_ops.shuffle_dataset(\n input_dataset._variant_tensor, # pylint: disable=protected-access\n buffer_size=self._buffer_size,\n seed=self._seed,\n seed2=self._seed2,\n reshuffle_each_iteration=self._reshuffle_each_iteration,\n **self._flat_structure)\n super(ShuffleDataset, self).__init__(input_dataset, variant_tensor)\n\n\nclass TakeDataset(UnaryUnchangedStructureDataset):\n \"\"\"A `Dataset` containing the first `count` elements from its input.\"\"\"\n\n def __init__(self, input_dataset, count):\n \"\"\"See `Dataset.take()` for details.\"\"\"\n self._input_dataset = input_dataset\n self._count = ops.convert_to_tensor(count, dtype=dtypes.int64, name=\"count\")\n variant_tensor = gen_dataset_ops.take_dataset(\n input_dataset._variant_tensor, # pylint: disable=protected-access\n count=self._count,\n **self._flat_structure)\n super(TakeDataset, self).__init__(input_dataset, variant_tensor)\n\n\nclass SkipDataset(UnaryUnchangedStructureDataset):\n \"\"\"A `Dataset` skipping the first `count` elements from its input.\"\"\"\n\n def __init__(self, input_dataset, count):\n \"\"\"See `Dataset.skip()` for details.\"\"\"\n self._input_dataset = input_dataset\n self._count = ops.convert_to_tensor(count, dtype=dtypes.int64, name=\"count\")\n variant_tensor = gen_dataset_ops.skip_dataset(\n input_dataset._variant_tensor, # pylint: disable=protected-access\n count=self._count,\n **self._flat_structure)\n super(SkipDataset, self).__init__(input_dataset, variant_tensor)\n\n\nclass ShardDataset(UnaryUnchangedStructureDataset):\n \"\"\"A `Dataset` for sharding its input.\"\"\"\n\n def __init__(self, input_dataset, num_shards, index):\n \"\"\"See `Dataset.shard()` for details.\"\"\"\n self._input_dataset = input_dataset\n self._num_shards = ops.convert_to_tensor(\n num_shards, dtype=dtypes.int64, name=\"num_shards\")\n self._index = ops.convert_to_tensor(index, dtype=dtypes.int64, name=\"index\")\n variant_tensor = gen_dataset_ops.shard_dataset(\n input_dataset._variant_tensor, # pylint: disable=protected-access\n num_shards=self._num_shards,\n index=self._index,\n **self._flat_structure)\n super(ShardDataset, self).__init__(input_dataset, variant_tensor)\n\n\nclass BatchDataset(UnaryDataset):\n \"\"\"A `Dataset` that batches contiguous elements from its input.\"\"\"\n\n def __init__(self, input_dataset, batch_size, drop_remainder):\n \"\"\"See `Dataset.batch()` for details.\"\"\"\n self._input_dataset = input_dataset\n self._batch_size = ops.convert_to_tensor(\n batch_size, dtype=dtypes.int64, name=\"batch_size\")\n self._drop_remainder = ops.convert_to_tensor(\n drop_remainder, dtype=dtypes.bool, name=\"drop_remainder\")\n\n constant_drop_remainder = tensor_util.constant_value(self._drop_remainder)\n # pylint: disable=protected-access\n if constant_drop_remainder:\n # NOTE(mrry): `constant_drop_remainder` may be `None` (unknown statically)\n # or `False` (explicitly retaining the remainder).\n # pylint: disable=g-long-lambda\n constant_batch_size = tensor_util.constant_value(self._batch_size)\n self._structure = nest.map_structure(\n lambda component_spec: component_spec._batch(constant_batch_size),\n input_dataset.element_spec)\n else:\n self._structure = nest.map_structure(\n lambda component_spec: component_spec._batch(None),\n input_dataset.element_spec)\n variant_tensor = gen_dataset_ops.batch_dataset_v2(\n input_dataset._variant_tensor,\n batch_size=self._batch_size,\n drop_remainder=self._drop_remainder,\n **self._flat_structure)\n super(BatchDataset, self).__init__(input_dataset, variant_tensor)\n\n @property\n def element_spec(self):\n return self._structure\n\n\nclass ParallelBatchDataset(UnaryDataset):\n \"\"\"A `Dataset` that batches contiguous elements from its input in parallel.\"\"\"\n\n def __init__(self, input_dataset, batch_size, drop_remainder,\n num_parallel_calls, deterministic):\n \"\"\"See `Dataset.batch()` for details.\"\"\"\n self._input_dataset = input_dataset\n self._batch_size = ops.convert_to_tensor(\n batch_size, dtype=dtypes.int64, name=\"batch_size\")\n self._drop_remainder = ops.convert_to_tensor(\n drop_remainder, dtype=dtypes.bool, name=\"drop_remainder\")\n self._num_parallel_calls = ops.convert_to_tensor(\n num_parallel_calls, dtype=dtypes.int64, name=\"num_parallel_calls\")\n if deterministic is None:\n self._deterministic = \"default\"\n elif deterministic:\n self._deterministic = \"true\"\n else:\n self._deterministic = \"false\"\n\n constant_drop_remainder = tensor_util.constant_value(self._drop_remainder)\n # pylint: disable=protected-access\n if constant_drop_remainder:\n # NOTE(mrry): `constant_drop_remainder` may be `None` (unknown statically)\n # or `False` (explicitly retaining the remainder).\n # pylint: disable=g-long-lambda\n constant_batch_size = tensor_util.constant_value(self._batch_size)\n self._structure = nest.map_structure(\n lambda component_spec: component_spec._batch(constant_batch_size),\n input_dataset.element_spec)\n else:\n self._structure = nest.map_structure(\n lambda component_spec: component_spec._batch(None),\n input_dataset.element_spec)\n\n if tf_compat.forward_compatible(2021, 3,\n 18) or self._deterministic != \"default\":\n variant_tensor = gen_dataset_ops.parallel_batch_dataset(\n input_dataset._variant_tensor,\n batch_size=self._batch_size,\n num_parallel_calls=self._num_parallel_calls,\n drop_remainder=self._drop_remainder,\n deterministic=self._deterministic,\n **self._flat_structure)\n else:\n variant_tensor = gen_dataset_ops.parallel_batch_dataset(\n input_dataset._variant_tensor,\n batch_size=self._batch_size,\n num_parallel_calls=self._num_parallel_calls,\n drop_remainder=self._drop_remainder,\n **self._flat_structure)\n super(ParallelBatchDataset, self).__init__(input_dataset, variant_tensor)\n\n @property\n def element_spec(self):\n return self._structure\n\n\nclass _NumpyIterator(object):\n \"\"\"Iterator over a dataset with elements converted to numpy.\"\"\"\n\n __slots__ = [\"_iterator\"]\n\n def __init__(self, dataset):\n self._iterator = iter(dataset)\n\n def __iter__(self):\n return self\n\n def __next__(self):\n\n def to_numpy(x):\n numpy = x._numpy() # pylint: disable=protected-access\n if isinstance(numpy, np.ndarray):\n # `numpy` shares the same underlying buffer as the `x` Tensor.\n # Tensors are expected to be immutable, so we disable writes.\n numpy.setflags(write=False)\n return numpy\n\n return nest.map_structure(to_numpy, next(self._iterator))\n\n def next(self):\n return self.__next__()\n\n\nclass _VariantTracker(tracking.CapturableResource):\n \"\"\"Allows export of functions capturing a Dataset in SavedModels.\n\n When saving a SavedModel, `tf.saved_model.save` traverses the object\n graph. Since Datasets reference _VariantTracker objects, that traversal will\n find a _VariantTracker for each Dataset and so know how to save and restore\n functions which reference the Dataset's variant Tensor.\n \"\"\"\n\n def __init__(self, variant_tensor, resource_creator):\n \"\"\"Record that `variant_tensor` is associated with `resource_creator`.\n\n Args:\n variant_tensor: The variant-dtype Tensor associated with the Dataset. This\n Tensor will be a captured input to functions which use the Dataset, and\n is used by saving code to identify the corresponding _VariantTracker.\n resource_creator: A zero-argument function which creates a new\n variant-dtype Tensor. This function will be included in SavedModels and\n run to re-create the Dataset's variant Tensor on restore.\n \"\"\"\n super(_VariantTracker, self).__init__(device=\"CPU\")\n self._resource_handle = variant_tensor\n self._create_resource = resource_creator\n\n\ndef _is_padded_shape_compatible_with(padded_shape, input_component_shape):\n \"\"\"Returns `True` if `input_component_shape` can be padded to `padded_shape`.\n\n Args:\n padded_shape: A `tf.TensorShape`.\n input_component_shape: A `tf.TensorShape`.\n\n Returns:\n `True` if `input_component_shape` can be padded to `padded_shape`, otherwise\n `False`.\n \"\"\"\n\n if padded_shape.dims is None or input_component_shape.dims is None:\n return True\n if len(padded_shape.dims) != len(input_component_shape.dims):\n return False\n for padded_dim, input_dim in zip(\n padded_shape.dims, input_component_shape.dims):\n if (padded_dim.value is not None and input_dim.value is not None\n and padded_dim.value < input_dim.value):\n return False\n return True\n\n\ndef _padded_shape_to_tensor(padded_shape, input_component_shape):\n \"\"\"Converts `padded_shape` to a `tf.Tensor` representing that shape.\n\n Args:\n padded_shape: A shape-like object, which may be a `tf.TensorShape`, a Python\n sequence, or a 1-D `tf.Tensor` of `tf.int64` elements.\n input_component_shape: A `tf.TensorShape`, with which `padded_shape` must\n be compatible.\n\n Returns:\n A 1-D `tf.Tensor` of `tf.int64` elements, representing `padded_shape`.\n\n Raises:\n ValueError: If `padded_shape` is not a shape or not compatible with\n `input_component_shape`.\n TypeError: If `padded_shape` is not convertible to a `tf.int64` tensor.\n \"\"\"\n try:\n # Try to convert the `padded_shape` to a `tf.TensorShape`\n padded_shape_as_shape = tensor_shape.as_shape(padded_shape)\n # We will return the \"canonical\" tensor representation, which uses\n # `-1` in place of `None`.\n ret = ops.convert_to_tensor(\n [dim if dim is not None else -1\n for dim in padded_shape_as_shape.as_list()], dtype=dtypes.int64)\n except (TypeError, ValueError):\n # The argument was not trivially convertible to a\n # `tf.TensorShape`, so fall back on the conversion to tensor\n # machinery.\n ret = ops.convert_to_tensor(padded_shape, preferred_dtype=dtypes.int64)\n if ret.shape.dims is not None and len(ret.shape.dims) != 1:\n six.reraise(ValueError, ValueError(\n \"Padded shape %s must be a 1-D tensor of tf.int64 values, but its \"\n \"shape was %s.\" % (padded_shape, ret.shape)), sys.exc_info()[2])\n if ret.dtype != dtypes.int64:\n six.reraise(\n TypeError,\n TypeError(\n \"Padded shape %s must be a 1-D tensor of tf.int64 values, but \"\n \"its element type was %s.\" % (padded_shape, ret.dtype.name)),\n sys.exc_info()[2])\n padded_shape_as_shape = tensor_util.constant_value_as_shape(ret)\n\n if not _is_padded_shape_compatible_with(padded_shape_as_shape,\n input_component_shape):\n raise ValueError(\"The padded shape %s is not compatible with the \"\n \"corresponding input component shape %s.\"\n % (padded_shape_as_shape, input_component_shape))\n\n return ret\n\n\ndef _padding_value_to_tensor(value, output_type):\n \"\"\"Converts the padding value to a tensor.\n\n Args:\n value: The padding value.\n output_type: Its expected dtype.\n\n Returns:\n A scalar `Tensor`.\n\n Raises:\n ValueError: if the padding value is not a scalar.\n TypeError: if the padding value's type does not match `output_type`.\n \"\"\"\n value = ops.convert_to_tensor(value, name=\"padding_value\")\n if not value.shape.is_compatible_with(tensor_shape.TensorShape([])):\n raise ValueError(\"Padding value should be a scalar, but is not: %s\" % value)\n if value.dtype != output_type:\n raise TypeError(\"Padding value tensor (%s) does not match output type: %s\" %\n (value, output_type))\n return value\n\n\ndef _padding_values_or_default(padding_values, input_dataset):\n \"\"\"Returns padding values with None elements replaced with default values.\"\"\"\n\n def make_zero(t):\n if t.base_dtype == dtypes.string:\n return \"\"\n elif t.base_dtype == dtypes.variant:\n error_msg = (\"Unable to create padding for field of type 'variant' \"\n \"because t.base_type == dtypes.variant == \"\n \"{}.\".format(t.base_dtype))\n raise TypeError(error_msg)\n elif t.base_dtype == dtypes.bfloat16:\n # Special case `bfloat16` because it is not supported by NumPy.\n return constant_op.constant(0, dtype=dtypes.bfloat16)\n else:\n return np.zeros_like(t.as_numpy_dtype())\n\n def value_or_default(value, default):\n return default if value is None else value\n\n default_padding = nest.map_structure(\n make_zero,\n get_legacy_output_types(input_dataset))\n return nest.map_structure_up_to(padding_values, value_or_default,\n padding_values, default_padding)\n\n\nclass PaddedBatchDataset(UnaryDataset):\n \"\"\"A `Dataset` that batches and pads contiguous elements from its input.\"\"\"\n\n def __init__(self, input_dataset, batch_size, padded_shapes, padding_values,\n drop_remainder):\n \"\"\"See `Dataset.batch()` for details.\"\"\"\n self._input_dataset = input_dataset\n\n def check_types(component_spec):\n if not isinstance(component_spec, tensor_spec.TensorSpec):\n raise TypeError(\"Padded batching of components of type \",\n type(component_spec), \" is not supported.\")\n\n nest.map_structure(check_types, input_dataset.element_spec)\n self._input_dataset = input_dataset\n self._batch_size = ops.convert_to_tensor(\n batch_size, dtype=dtypes.int64, name=\"batch_size\")\n padding_values = _padding_values_or_default(padding_values, input_dataset)\n\n input_shapes = get_legacy_output_shapes(input_dataset)\n flat_padded_shapes = nest.flatten_up_to(input_shapes, padded_shapes)\n\n flat_padded_shapes_as_tensors = []\n\n for input_component_shape, padded_shape in zip(\n nest.flatten(input_shapes), flat_padded_shapes):\n flat_padded_shapes_as_tensors.append(\n _padded_shape_to_tensor(padded_shape, input_component_shape))\n\n self._padded_shapes = nest.pack_sequence_as(input_shapes,\n flat_padded_shapes_as_tensors)\n\n # If padding_values is a single element and input_shapes is a structure,\n # \"broadcast\" padding_values to the same structure as input_shapes.\n if nest.is_sequence(input_shapes) and not nest.is_sequence(padding_values):\n padding_values = nest.map_structure(lambda _: padding_values,\n input_shapes)\n\n self._padding_values = nest.map_structure_up_to(\n input_shapes, _padding_value_to_tensor, padding_values,\n get_legacy_output_types(input_dataset))\n self._drop_remainder = ops.convert_to_tensor(\n drop_remainder, dtype=dtypes.bool, name=\"drop_remainder\")\n\n def _padded_shape_to_batch_shape(s):\n return tensor_shape.TensorShape([\n tensor_util.constant_value(self._batch_size)\n if smart_cond.smart_constant_value(self._drop_remainder) else None\n ]).concatenate(tensor_util.constant_value_as_shape(s))\n\n output_shapes = nest.map_structure(\n _padded_shape_to_batch_shape, self._padded_shapes)\n self._structure = structure.convert_legacy_structure(\n get_legacy_output_types(self._input_dataset), output_shapes,\n get_legacy_output_classes(self._input_dataset))\n\n # pylint: disable=protected-access\n # TODO(jsimsa): Switch to using v2 only any time after 6/30/2018.\n if smart_cond.smart_constant_value(self._drop_remainder) is False:\n variant_tensor = gen_dataset_ops.padded_batch_dataset(\n input_dataset._variant_tensor, # pylint: disable=protected-access\n batch_size=self._batch_size,\n padded_shapes=[\n ops.convert_to_tensor(s, dtype=dtypes.int64)\n for s in nest.flatten(self._padded_shapes)\n ],\n padding_values=nest.flatten(self._padding_values),\n output_shapes=structure.get_flat_tensor_shapes(self._structure))\n else:\n variant_tensor = gen_dataset_ops.padded_batch_dataset_v2(\n input_dataset._variant_tensor, # pylint: disable=protected-access\n batch_size=self._batch_size,\n padded_shapes=[\n ops.convert_to_tensor(s, dtype=dtypes.int64)\n for s in nest.flatten(self._padded_shapes)\n ],\n padding_values=nest.flatten(self._padding_values),\n drop_remainder=self._drop_remainder,\n output_shapes=structure.get_flat_tensor_shapes(self._structure))\n super(PaddedBatchDataset, self).__init__(input_dataset, variant_tensor)\n\n @property\n def element_spec(self):\n return self._structure\n\n\ndef _should_unpack_args(args):\n \"\"\"Returns `True` if `args` should be `*args` when passed to a callable.\"\"\"\n return type(args) is tuple # pylint: disable=unidiomatic-typecheck\n\n\nclass MapDataset(UnaryDataset):\n \"\"\"A `Dataset` that maps a function over elements in its input.\"\"\"\n\n def __init__(self,\n input_dataset,\n map_func,\n use_inter_op_parallelism=True,\n preserve_cardinality=False,\n use_legacy_function=False):\n \"\"\"See `Dataset.map()` for details.\"\"\"\n self._input_dataset = input_dataset\n self._use_inter_op_parallelism = use_inter_op_parallelism\n self._preserve_cardinality = preserve_cardinality\n self._map_func = StructuredFunctionWrapper(\n map_func,\n self._transformation_name(),\n dataset=input_dataset,\n use_legacy_function=use_legacy_function)\n variant_tensor = gen_dataset_ops.map_dataset(\n input_dataset._variant_tensor, # pylint: disable=protected-access\n self._map_func.function.captured_inputs,\n f=self._map_func.function,\n use_inter_op_parallelism=self._use_inter_op_parallelism,\n preserve_cardinality=self._preserve_cardinality,\n **self._flat_structure)\n super(MapDataset, self).__init__(input_dataset, variant_tensor)\n\n def _functions(self):\n return [self._map_func]\n\n @property\n def element_spec(self):\n return self._map_func.output_structure\n\n def _transformation_name(self):\n return \"Dataset.map()\"\n\n\nclass ParallelMapDataset(UnaryDataset):\n \"\"\"A `Dataset` that maps a function over elements in its input in parallel.\"\"\"\n\n def __init__(self,\n input_dataset,\n map_func,\n num_parallel_calls,\n deterministic,\n use_inter_op_parallelism=True,\n preserve_cardinality=False,\n use_legacy_function=False):\n \"\"\"See `Dataset.map()` for details.\"\"\"\n self._input_dataset = input_dataset\n self._use_inter_op_parallelism = use_inter_op_parallelism\n self._map_func = StructuredFunctionWrapper(\n map_func,\n self._transformation_name(),\n dataset=input_dataset,\n use_legacy_function=use_legacy_function)\n if deterministic is None:\n self._deterministic = \"default\"\n elif deterministic:\n self._deterministic = \"true\"\n else:\n self._deterministic = \"false\"\n self._preserve_cardinality = preserve_cardinality\n self._num_parallel_calls = ops.convert_to_tensor(\n num_parallel_calls, dtype=dtypes.int64, name=\"num_parallel_calls\")\n variant_tensor = gen_dataset_ops.parallel_map_dataset_v2(\n input_dataset._variant_tensor, # pylint: disable=protected-access\n self._map_func.function.captured_inputs,\n f=self._map_func.function,\n num_parallel_calls=self._num_parallel_calls,\n deterministic=self._deterministic,\n use_inter_op_parallelism=self._use_inter_op_parallelism,\n preserve_cardinality=self._preserve_cardinality,\n **self._flat_structure)\n super(ParallelMapDataset, self).__init__(input_dataset, variant_tensor)\n\n def _functions(self):\n return [self._map_func]\n\n @property\n def element_spec(self):\n return self._map_func.output_structure\n\n def _transformation_name(self):\n return \"Dataset.map()\"\n\n\nclass FlatMapDataset(UnaryDataset):\n \"\"\"A `Dataset` that maps a function over its input and flattens the result.\"\"\"\n\n def __init__(self, input_dataset, map_func):\n \"\"\"See `Dataset.flat_map()` for details.\"\"\"\n self._input_dataset = input_dataset\n self._map_func = StructuredFunctionWrapper(\n map_func, self._transformation_name(), dataset=input_dataset)\n if not isinstance(self._map_func.output_structure, DatasetSpec):\n raise TypeError(\n \"`map_func` must return a `Dataset` object. Got {}\".format(\n type(self._map_func.output_structure)))\n self._structure = self._map_func.output_structure._element_spec # pylint: disable=protected-access\n variant_tensor = gen_dataset_ops.flat_map_dataset(\n input_dataset._variant_tensor, # pylint: disable=protected-access\n self._map_func.function.captured_inputs,\n f=self._map_func.function,\n **self._flat_structure)\n super(FlatMapDataset, self).__init__(input_dataset, variant_tensor)\n\n def _functions(self):\n return [self._map_func]\n\n @property\n def element_spec(self):\n return self._structure\n\n def _transformation_name(self):\n return \"Dataset.flat_map()\"\n\n\nclass InterleaveDataset(UnaryDataset):\n \"\"\"A `Dataset` that interleaves the result of transformed inputs.\"\"\"\n\n def __init__(self, input_dataset, map_func, cycle_length, block_length):\n \"\"\"See `Dataset.interleave()` for details.\"\"\"\n\n self._input_dataset = input_dataset\n self._map_func = StructuredFunctionWrapper(\n map_func, self._transformation_name(), dataset=input_dataset)\n if not isinstance(self._map_func.output_structure, DatasetSpec):\n raise TypeError(\n \"`map_func` must return a `Dataset` object. Got {}\".format(\n type(self._map_func.output_structure)))\n self._structure = self._map_func.output_structure._element_spec # pylint: disable=protected-access\n self._cycle_length = ops.convert_to_tensor(\n cycle_length, dtype=dtypes.int64, name=\"cycle_length\")\n self._block_length = ops.convert_to_tensor(\n block_length, dtype=dtypes.int64, name=\"block_length\")\n\n variant_tensor = gen_dataset_ops.interleave_dataset(\n input_dataset._variant_tensor, # pylint: disable=protected-access\n self._map_func.function.captured_inputs, # pylint: disable=protected-access\n self._cycle_length,\n self._block_length,\n f=self._map_func.function,\n **self._flat_structure)\n super(InterleaveDataset, self).__init__(input_dataset, variant_tensor)\n\n def _functions(self):\n return [self._map_func]\n\n @property\n def element_spec(self):\n return self._structure\n\n def _transformation_name(self):\n return \"Dataset.interleave()\"\n\n\nclass ParallelInterleaveDataset(UnaryDataset):\n \"\"\"A `Dataset` that maps a function over its input and interleaves the result.\"\"\"\n\n def __init__(self,\n input_dataset,\n map_func,\n cycle_length,\n block_length,\n num_parallel_calls,\n buffer_output_elements=AUTOTUNE,\n prefetch_input_elements=AUTOTUNE,\n deterministic=None):\n \"\"\"See `Dataset.interleave()` for details.\"\"\"\n self._input_dataset = input_dataset\n self._map_func = StructuredFunctionWrapper(\n map_func, self._transformation_name(), dataset=input_dataset)\n if not isinstance(self._map_func.output_structure, DatasetSpec):\n raise TypeError(\n \"`map_func` must return a `Dataset` object. Got {}\".format(\n type(self._map_func.output_structure)))\n self._structure = self._map_func.output_structure._element_spec # pylint: disable=protected-access\n self._cycle_length = ops.convert_to_tensor(\n cycle_length, dtype=dtypes.int64, name=\"cycle_length\")\n self._block_length = ops.convert_to_tensor(\n block_length, dtype=dtypes.int64, name=\"block_length\")\n self._buffer_output_elements = ops.convert_to_tensor(\n buffer_output_elements,\n dtype=dtypes.int64,\n name=\"buffer_output_elements\")\n self._prefetch_input_elements = ops.convert_to_tensor(\n prefetch_input_elements,\n dtype=dtypes.int64,\n name=\"prefetch_input_elements\")\n\n self._num_parallel_calls = ops.convert_to_tensor(\n num_parallel_calls, dtype=dtypes.int64, name=\"num_parallel_calls\")\n if deterministic is None:\n deterministic_string = \"default\"\n elif deterministic:\n deterministic_string = \"true\"\n else:\n deterministic_string = \"false\"\n\n variant_tensor = gen_dataset_ops.parallel_interleave_dataset_v4(\n input_dataset._variant_tensor, # pylint: disable=protected-access\n self._map_func.function.captured_inputs, # pylint: disable=protected-access\n self._cycle_length,\n self._block_length,\n self._buffer_output_elements,\n self._prefetch_input_elements,\n self._num_parallel_calls,\n f=self._map_func.function,\n deterministic=deterministic_string,\n **self._flat_structure)\n super(ParallelInterleaveDataset, self).__init__(input_dataset,\n variant_tensor)\n\n def _functions(self):\n return [self._map_func]\n\n @property\n def element_spec(self):\n return self._structure\n\n def _transformation_name(self):\n return \"Dataset.interleave()\"\n\n\nclass FilterDataset(UnaryUnchangedStructureDataset):\n \"\"\"A `Dataset` that filters its input according to a predicate function.\"\"\"\n\n def __init__(self, input_dataset, predicate, use_legacy_function=False):\n \"\"\"See `Dataset.filter()` for details.\"\"\"\n self._input_dataset = input_dataset\n wrapped_func = StructuredFunctionWrapper(\n predicate,\n self._transformation_name(),\n dataset=input_dataset,\n use_legacy_function=use_legacy_function)\n if not wrapped_func.output_structure.is_compatible_with(\n tensor_spec.TensorSpec([], dtypes.bool)):\n error_msg = (\"`predicate` return type must be convertible to a scalar \"\n \"boolean tensor. Was {}.\").format(\n wrapped_func.output_structure)\n raise ValueError(error_msg)\n self._predicate = wrapped_func\n variant_tensor = gen_dataset_ops.filter_dataset(\n input_dataset._variant_tensor, # pylint: disable=protected-access\n other_arguments=self._predicate.function.captured_inputs,\n predicate=self._predicate.function,\n **self._flat_structure)\n super(FilterDataset, self).__init__(input_dataset, variant_tensor)\n\n def _functions(self):\n return [self._predicate]\n\n def _transformation_name(self):\n return \"Dataset.filter()\"\n\n\nclass PrefetchDataset(UnaryUnchangedStructureDataset):\n \"\"\"A `Dataset` that asynchronously prefetches its input.\"\"\"\n\n def __init__(self, input_dataset, buffer_size, slack_period=None):\n \"\"\"See `Dataset.prefetch()` for details.\n\n Args:\n input_dataset: The input dataset.\n buffer_size: See `Dataset.prefetch()` for details.\n slack_period: (Optional.) An integer. If non-zero, determines the number\n of GetNext calls before injecting slack into the execution. This may\n reduce CPU contention at the start of a step. Note that a tensorflow\n user should not have to set this manually; enable this behavior\n automatically via `tf.data.Options.experimental_slack` instead. Defaults\n to None.\n \"\"\"\n self._input_dataset = input_dataset\n if buffer_size is None:\n buffer_size = AUTOTUNE\n self._buffer_size = ops.convert_to_tensor(\n buffer_size, dtype=dtypes.int64, name=\"buffer_size\")\n # pylint: disable=protected-access\n # We colocate the prefetch dataset with its input as this collocation only\n # happens automatically in graph mode.\n with ops.colocate_with(input_dataset._variant_tensor):\n variant_tensor = gen_dataset_ops.prefetch_dataset(\n input_dataset._variant_tensor,\n buffer_size=self._buffer_size,\n slack_period=slack_period,\n **self._flat_structure)\n super(PrefetchDataset, self).__init__(input_dataset, variant_tensor)\n\n\nclass WindowDataset(UnaryDataset):\n \"\"\"A dataset that creates window datasets from the input elements.\"\"\"\n\n def __init__(self, input_dataset, size, shift, stride, drop_remainder):\n \"\"\"See `window_dataset()` for more details.\"\"\"\n self._input_dataset = input_dataset\n self._size = ops.convert_to_tensor(size, dtype=dtypes.int64, name=\"size\")\n self._shift = ops.convert_to_tensor(shift, dtype=dtypes.int64, name=\"shift\")\n self._stride = ops.convert_to_tensor(\n stride, dtype=dtypes.int64, name=\"stride\")\n self._drop_remainder = ops.convert_to_tensor(\n drop_remainder, dtype=dtypes.bool, name=\"drop_remainder\")\n self._structure = nest.pack_sequence_as(\n get_legacy_output_classes(input_dataset), [\n DatasetSpec( # pylint: disable=g-complex-comprehension\n structure.convert_legacy_structure(\n output_type, output_shape, output_class))\n for output_class, output_shape, output_type in zip(\n nest.flatten(get_legacy_output_classes(input_dataset)),\n nest.flatten(get_legacy_output_shapes(input_dataset)),\n nest.flatten(get_legacy_output_types(input_dataset)))\n ])\n variant_tensor = gen_dataset_ops.window_dataset(\n input_dataset._variant_tensor, # pylint: disable=protected-access\n self._size,\n self._shift,\n self._stride,\n self._drop_remainder,\n **self._flat_structure)\n super(WindowDataset, self).__init__(input_dataset, variant_tensor)\n\n @property\n def element_spec(self):\n return self._structure\n\n\nclass _OptionsDataset(UnaryUnchangedStructureDataset):\n \"\"\"An identity `Dataset` that stores options.\"\"\"\n\n def __init__(self, input_dataset, options):\n # pylint: disable=protected-access\n self._input_dataset = input_dataset\n variant_tensor = input_dataset._variant_tensor\n super(_OptionsDataset, self).__init__(input_dataset, variant_tensor)\n\n if self._options_attr:\n self._options_attr._set_mutable(True)\n self._options_attr = self._options_attr.merge(options)\n else:\n self._options_attr = options\n self._options_attr._set_mutable(False)\n\n\nclass _ModelDataset(UnaryUnchangedStructureDataset):\n \"\"\"A `Dataset` that acts as an identity, and models performance.\"\"\"\n\n def __init__(self, input_dataset, algorithm, cpu_budget, ram_budget):\n self._input_dataset = input_dataset\n variant_tensor = gen_dataset_ops.model_dataset(\n input_dataset._variant_tensor, # pylint: disable=protected-access\n algorithm=algorithm.value,\n cpu_budget=cpu_budget,\n ram_budget=ram_budget,\n **self._flat_structure)\n super(_ModelDataset, self).__init__(input_dataset, variant_tensor)\n\n\nclass _OptimizeDataset(UnaryUnchangedStructureDataset):\n \"\"\"A `Dataset` that acts as an identity, and applies optimizations.\"\"\"\n\n def __init__(self,\n input_dataset,\n optimizations_enabled,\n optimizations_disabled,\n optimizations_default,\n optimization_configs=None):\n self._input_dataset = input_dataset\n if optimization_configs is None:\n optimization_configs = []\n\n # We sort the options here before embedding as constant tensors to ensure\n # that serialization to NodeDef is determinstic.\n if optimizations_enabled:\n optimizations_enabled.sort()\n if optimizations_disabled:\n optimizations_disabled.sort()\n if optimizations_default:\n optimizations_default.sort()\n\n self._optimizations_enabled = convert.optional_param_to_tensor(\n argument_name=\"optimizations_enabled\",\n argument_value=optimizations_enabled,\n argument_default=[],\n argument_dtype=dtypes.string)\n self._optimizations_disabled = convert.optional_param_to_tensor(\n argument_name=\"optimizations_disabled\",\n argument_value=optimizations_disabled,\n argument_default=[],\n argument_dtype=dtypes.string)\n self._optimizations_default = convert.optional_param_to_tensor(\n argument_name=\"optimizations_default\",\n argument_value=optimizations_default,\n argument_default=[],\n argument_dtype=dtypes.string)\n\n variant_tensor = gen_dataset_ops.optimize_dataset_v2(\n input_dataset._variant_tensor, # pylint: disable=protected-access\n self._optimizations_enabled,\n self._optimizations_disabled,\n self._optimizations_default,\n optimization_configs=optimization_configs,\n **self._flat_structure)\n\n super(_OptimizeDataset, self).__init__(input_dataset, variant_tensor)\n\n\nclass _SetStatsAggregatorDataset(UnaryUnchangedStructureDataset):\n \"\"\"A `Dataset` that acts as an identity, and sets a stats aggregator.\"\"\"\n\n def __init__(self, input_dataset, aggregator, prefix, counter_prefix):\n self._input_dataset = input_dataset\n self._stats_aggregator = aggregator\n self._prefix = prefix\n self._counter_prefix = counter_prefix\n variant_tensor = ged_ops.set_stats_aggregator_dataset(\n input_dataset._variant_tensor, # pylint: disable=protected-access\n self._stats_aggregator._resource, # pylint: disable=protected-access\n self._prefix,\n self._counter_prefix,\n **self._flat_structure)\n super(_SetStatsAggregatorDataset, self).__init__(input_dataset,\n variant_tensor)\n\n\nclass _MaxIntraOpParallelismDataset(UnaryUnchangedStructureDataset):\n \"\"\"A `Dataset` that acts as an identity, overriding intra-op parallelism.\"\"\"\n\n def __init__(self, input_dataset, max_intra_op_parallelism):\n self._input_dataset = input_dataset\n self._max_intra_op_parallelism = ops.convert_to_tensor(\n max_intra_op_parallelism,\n dtype=dtypes.int64,\n name=\"max_intra_op_parallelism\")\n variant_tensor = ged_ops.max_intra_op_parallelism_dataset(\n input_dataset._variant_tensor, # pylint: disable=protected-access\n self._max_intra_op_parallelism,\n **self._flat_structure)\n super(_MaxIntraOpParallelismDataset, self).__init__(input_dataset,\n variant_tensor)\n\n\nclass _PrivateThreadPoolDataset(UnaryUnchangedStructureDataset):\n \"\"\"A `Dataset` that acts as an identity, setting a private threadpool.\"\"\"\n\n def __init__(self, input_dataset, num_threads):\n self._input_dataset = input_dataset\n self._num_threads = ops.convert_to_tensor(\n num_threads, dtype=dtypes.int64, name=\"num_threads\")\n variant_tensor = ged_ops.private_thread_pool_dataset(\n input_dataset._variant_tensor, # pylint: disable=protected-access\n self._num_threads,\n **self._flat_structure)\n super(_PrivateThreadPoolDataset, self).__init__(input_dataset,\n variant_tensor)\n\n\ndef normalize_to_dense(dataset):\n \"\"\"Normalizes non-tensor components in a dataset to dense representations.\n\n This is necessary for dataset transformations that slice along the batch\n dimension and are oblivious to non-tensors, e.g. `unbatch`, `rebatch`.\n\n Args:\n dataset: Dataset to normalize.\n\n Returns:\n A dataset whose sparse and ragged tensors have been normalized to their\n dense representations.\n \"\"\"\n\n # NOTE(mrry): This leads to a somewhat inefficient re-encoding step for all\n # non-tensor components.\n #\n # TODO(mrry): Consider optimizing this if it turns out to be a bottleneck.\n if _should_unpack_args(dataset.element_spec):\n def normalize(*args):\n return structure.to_batched_tensor_list(dataset.element_spec, tuple(args))\n else:\n def normalize(arg):\n return structure.to_batched_tensor_list(dataset.element_spec, arg)\n\n normalized_dataset = dataset.map(normalize)\n\n # NOTE(mrry): Our `map()` has lost information about the structure of\n # non-tensor components, so re-apply the structure of the original dataset.\n return _RestructuredDataset(normalized_dataset, dataset.element_spec)\n\n\nclass _RestructuredDataset(UnaryDataset):\n \"\"\"An internal helper for changing the element spec of a dataset.\"\"\"\n\n def __init__(self, dataset, structure):\n self._input_dataset = dataset\n self._structure = structure\n\n variant_tensor = self._input_dataset._variant_tensor # pylint: disable=protected-access\n super(_RestructuredDataset, self).__init__(dataset, variant_tensor)\n\n @property\n def element_spec(self):\n return self._structure\n\n\nclass _UnbatchDataset(UnaryDataset):\n \"\"\"A dataset that splits the elements of its input into multiple elements.\"\"\"\n\n def __init__(self, input_dataset):\n \"\"\"See `unbatch()` for more details.\"\"\"\n flat_shapes = input_dataset._flat_shapes # pylint: disable=protected-access\n if any(s.ndims == 0 for s in flat_shapes):\n raise ValueError(\"Cannot unbatch an input with scalar components.\")\n known_batch_dim = tensor_shape.Dimension(None)\n for s in flat_shapes:\n try:\n known_batch_dim = known_batch_dim.merge_with(s[0])\n except ValueError:\n raise ValueError(\"Cannot unbatch an input whose components have \"\n \"different batch sizes.\")\n self._input_dataset = input_dataset\n self._structure = nest.map_structure(\n lambda component_spec: component_spec._unbatch(), # pylint: disable=protected-access\n get_structure(input_dataset))\n variant_tensor = ged_ops.unbatch_dataset(\n self._input_dataset._variant_tensor, # pylint: disable=protected-access\n **self._flat_structure)\n super(_UnbatchDataset, self).__init__(input_dataset, variant_tensor)\n\n @property\n def element_spec(self):\n return self._structure\n\n\ndef _collect_resource_inputs(op):\n \"\"\"Collects resource inputs for the given ops (and its variant inputs).\"\"\"\n\n def _process(op_queue, seen_ops):\n \"\"\"Processes the next element of the op queue.\n\n Args:\n op_queue: Queue of Dataset operations to process.\n seen_ops: Already processed set of Operations.\n\n Returns:\n A 2-tuple containing sets of resource handles. The first tuple entry\n contains read-only handles and the second entry contains read-write\n handles.\n \"\"\"\n\n reads = []\n writes = []\n op = op_queue.pop()\n if op in seen_ops:\n return reads, writes\n seen_ops.add(op)\n # TODO(b/150139257): All resource inputs are in writes right now since we\n # have not updated the functional ops to set the special attribute that ACD\n # uses to figure out which of the op's inputs are read-only.\n reads, writes = acd_utils.get_read_write_resource_inputs(op)\n # Conservatively assume that any variant inputs are datasets.\n op_queue.extend(t.op for t in op.inputs if t.dtype == dtypes.variant)\n return reads, writes\n\n op_queue = [op]\n seen_ops = set()\n all_reads = []\n all_writes = []\n while op_queue:\n reads, writes = _process(op_queue, seen_ops)\n all_reads.extend(reads)\n all_writes.extend(writes)\n\n return all_reads, all_writes\n\n\n@auto_control_deps.register_acd_resource_resolver\ndef _resource_resolver(op, resource_reads, resource_writes):\n \"\"\"Updates resource inputs for tf.data ops with indirect dependencies.\"\"\"\n\n updated = False\n if op.type in [\n \"DatasetToSingleElement\", \"DatasetToTFRecord\", \"ReduceDataset\"\n ]:\n reads, writes = _collect_resource_inputs(op)\n for inp in reads:\n if inp not in resource_reads:\n updated = True\n resource_reads.add(inp)\n for inp in writes:\n if inp not in resource_writes:\n updated = True\n resource_writes.add(inp)\n\n if op.type in [\n \"IteratorGetNext\", \"IteratorGetNextSync\", \"IteratorGetNextAsOptional\"\n ]:\n iterator_resource = op.inputs[0]\n make_iterator_ops = [\n op for op in iterator_resource.consumers() if op.type == \"MakeIterator\"\n ]\n\n if len(make_iterator_ops) == 1:\n reads, writes = _collect_resource_inputs(make_iterator_ops[0])\n for inp in reads:\n if inp not in resource_reads:\n updated = True\n resource_reads.add(inp)\n for inp in writes:\n if inp not in resource_writes:\n updated = True\n resource_writes.add(inp)\n\n return updated\n", "# 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\n# pylint: disable=invalid-name\n\"\"\"Test utils for tensorflow.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nfrom collections import OrderedDict\nimport contextlib\nimport functools\nimport gc\nimport itertools\nimport math\nimport os\nimport random\nimport re\nimport tempfile\nimport threading\nimport time\nimport unittest\n\nfrom absl.testing import parameterized\nimport numpy as np\nimport six\n\nfrom google.protobuf import descriptor_pool\nfrom google.protobuf import text_format\n\nfrom tensorflow.core.framework import graph_pb2\nfrom tensorflow.core.protobuf import rewriter_config_pb2\nfrom tensorflow.python import tf2\nfrom tensorflow.python.client import device_lib\nfrom tensorflow.python.client import pywrap_tf_session\nfrom tensorflow.python.client import session\nfrom tensorflow.python.compat.compat import forward_compatibility_horizon\nfrom tensorflow.python.eager import backprop\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.eager import def_function\nfrom tensorflow.python.eager import tape\nfrom tensorflow.python.framework import config\nfrom tensorflow.python.framework import device as pydev\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import errors_impl\nfrom tensorflow.python.framework import gpu_util\nfrom tensorflow.python.framework import importer\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import random_seed\nfrom tensorflow.python.framework import sparse_tensor\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.framework import tensor_util\nfrom tensorflow.python.framework import tfrt_utils\nfrom tensorflow.python.framework import versions\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_util\nfrom tensorflow.python.ops import control_flow_util_v2\nfrom tensorflow.python.ops import gradients_impl\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import script_ops\nfrom tensorflow.python.ops import summary_ops_v2\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.ops.ragged import ragged_ops # pylint: disable=unused-import\nfrom tensorflow.python.ops.ragged import ragged_tensor\nfrom tensorflow.python.ops.ragged import ragged_tensor_value\nfrom tensorflow.python.platform import _pywrap_stacktrace_handler\nfrom tensorflow.python.platform import googletest\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.training import server_lib\nfrom tensorflow.python.util import _pywrap_util_port\nfrom tensorflow.python.util import compat\nfrom tensorflow.python.util import deprecation\nfrom tensorflow.python.util import nest\nfrom tensorflow.python.util import tf_decorator\nfrom tensorflow.python.util import tf_inspect\nfrom tensorflow.python.util.compat import collections_abc\nfrom tensorflow.python.util.protobuf import compare\nfrom tensorflow.python.util.tf_export import tf_export\n\n\n# If the below import is made available through the BUILD rule, then this\n# function is overridden and will instead return True and cause Tensorflow\n# graphs to be compiled with XLA.\ndef is_xla_enabled():\n return False\n\n\ntry:\n from tensorflow.python.framework.is_xla_test_true import is_xla_enabled # pylint: disable=g-import-not-at-top, unused-import\nexcept Exception: # pylint: disable=broad-except\n pass\n\n\n# Uses the same mechanism as above to selectively enable/disable MLIR\n# compilation.\ndef is_mlir_bridge_enabled():\n return None\n\n\ntry:\n from tensorflow.python.framework.is_mlir_bridge_test_false import is_mlir_bridge_enabled # pylint: disable=g-import-not-at-top, unused-import\nexcept ImportError:\n try:\n from tensorflow.python.framework.is_mlir_bridge_test_true import is_mlir_bridge_enabled # pylint: disable=g-import-not-at-top, unused-import\n except ImportError:\n pass\n\n\ndef _get_object_count_by_type(exclude=()):\n return (\n collections.Counter([type(obj).__name__ for obj in gc.get_objects()]) -\n collections.Counter([type(obj).__name__ for obj in exclude]))\n\n\n@tf_export(\"test.gpu_device_name\")\ndef gpu_device_name():\n \"\"\"Returns the name of a GPU device if available or the empty string.\"\"\"\n for x in device_lib.list_local_devices():\n if x.device_type == \"GPU\":\n return compat.as_str(x.name)\n return \"\"\n\n\ndef assert_ops_in_graph(expected_ops, graph):\n \"\"\"Assert all expected operations are found.\n\n Args:\n expected_ops: `dict<string, string>` of op name to op type.\n graph: Graph to check.\n\n Returns:\n `dict<string, node>` of node name to node.\n\n Raises:\n ValueError: If the expected ops are not present in the graph.\n \"\"\"\n actual_ops = {}\n gd = graph.as_graph_def()\n for node in gd.node:\n if node.name in expected_ops:\n if expected_ops[node.name] != node.op:\n raise ValueError(\"Expected op for node %s is different. %s vs %s\" %\n (node.name, expected_ops[node.name], node.op))\n actual_ops[node.name] = node\n if set(expected_ops.keys()) != set(actual_ops.keys()):\n raise ValueError(\"Not all expected ops are present. Expected %s, found %s\" %\n (expected_ops.keys(), actual_ops.keys()))\n return actual_ops\n\n\n@tf_export(\"test.assert_equal_graph_def\", v1=[])\ndef assert_equal_graph_def_v2(expected, actual):\n \"\"\"Asserts that two `GraphDef`s are (mostly) the same.\n\n Compares two `GraphDef` protos for equality, ignoring versions and ordering of\n nodes, attrs, and control inputs. Node names are used to match up nodes\n between the graphs, so the naming of nodes must be consistent. This function\n ignores randomized attribute values that may appear in V2 checkpoints.\n\n Args:\n expected: The `GraphDef` we expected.\n actual: The `GraphDef` we have.\n\n Raises:\n AssertionError: If the `GraphDef`s do not match.\n TypeError: If either argument is not a `GraphDef`.\n \"\"\"\n assert_equal_graph_def(actual, expected, checkpoint_v2=True,\n hash_table_shared_name=True)\n\n\n@tf_export(v1=[\"test.assert_equal_graph_def\"])\ndef assert_equal_graph_def_v1(actual, expected, checkpoint_v2=False,\n hash_table_shared_name=False):\n \"\"\"Asserts that two `GraphDef`s are (mostly) the same.\n\n Compares two `GraphDef` protos for equality, ignoring versions and ordering of\n nodes, attrs, and control inputs. Node names are used to match up nodes\n between the graphs, so the naming of nodes must be consistent.\n\n Args:\n actual: The `GraphDef` we have.\n expected: The `GraphDef` we expected.\n checkpoint_v2: boolean determining whether to ignore randomized attribute\n values that appear in V2 checkpoints.\n hash_table_shared_name: boolean determining whether to ignore randomized\n shared_names that appear in HashTableV2 op defs.\n\n Raises:\n AssertionError: If the `GraphDef`s do not match.\n TypeError: If either argument is not a `GraphDef`.\n \"\"\"\n assert_equal_graph_def(actual, expected, checkpoint_v2,\n hash_table_shared_name)\n\n\ndef assert_equal_graph_def(actual, expected, checkpoint_v2=False,\n hash_table_shared_name=False):\n if not isinstance(actual, graph_pb2.GraphDef):\n raise TypeError(\"Expected tf.GraphDef for actual, got %s\" %\n type(actual).__name__)\n if not isinstance(expected, graph_pb2.GraphDef):\n raise TypeError(\"Expected tf.GraphDef for expected, got %s\" %\n type(expected).__name__)\n\n if checkpoint_v2:\n _strip_checkpoint_v2_randomized(actual)\n _strip_checkpoint_v2_randomized(expected)\n\n if hash_table_shared_name:\n _strip_hash_table_shared_name(actual)\n _strip_hash_table_shared_name(expected)\n\n diff = pywrap_tf_session.EqualGraphDefWrapper(actual.SerializeToString(),\n expected.SerializeToString())\n if diff:\n raise AssertionError(compat.as_str(diff))\n\n\ndef assert_meta_graph_protos_equal(tester, a, b):\n \"\"\"Compares MetaGraphDefs `a` and `b` in unit test class `tester`.\"\"\"\n # Carefully check the collection_defs\n tester.assertEqual(set(a.collection_def), set(b.collection_def))\n collection_keys = a.collection_def.keys()\n for k in collection_keys:\n a_value = a.collection_def[k]\n b_value = b.collection_def[k]\n proto_type = ops.get_collection_proto_type(k)\n if proto_type:\n a_proto = proto_type()\n b_proto = proto_type()\n # Number of entries in the collections is the same\n tester.assertEqual(\n len(a_value.bytes_list.value), len(b_value.bytes_list.value))\n for (a_value_item, b_value_item) in zip(a_value.bytes_list.value,\n b_value.bytes_list.value):\n a_proto.ParseFromString(a_value_item)\n b_proto.ParseFromString(b_value_item)\n tester.assertProtoEquals(a_proto, b_proto)\n else:\n tester.assertEquals(a_value, b_value)\n # Compared the fields directly, remove their raw values from the\n # proto comparison below.\n a.ClearField(\"collection_def\")\n b.ClearField(\"collection_def\")\n\n # Check the graph_defs.\n assert_equal_graph_def(a.graph_def, b.graph_def, checkpoint_v2=True)\n # Check graph_def versions (ignored by assert_equal_graph_def).\n tester.assertProtoEquals(a.graph_def.versions, b.graph_def.versions)\n # Compared the fields directly, remove their raw values from the\n # proto comparison below.\n a.ClearField(\"graph_def\")\n b.ClearField(\"graph_def\")\n\n tester.assertProtoEquals(a, b)\n\n\n# Matches attributes named via _SHARDED_SUFFIX in\n# tensorflow/python/training/saver.py\n_SHARDED_SAVE_OP_PATTERN = \"_temp_[0-9a-z]{32}/part\"\n\n\ndef _strip_checkpoint_v2_randomized(graph_def):\n for node in graph_def.node:\n delete_keys = []\n for attr_key in node.attr:\n attr_tensor_value = node.attr[attr_key].tensor\n if attr_tensor_value and len(attr_tensor_value.string_val) == 1:\n attr_tensor_string_value = attr_tensor_value.string_val[0]\n if (attr_tensor_string_value and\n re.match(compat.as_bytes(_SHARDED_SAVE_OP_PATTERN),\n attr_tensor_string_value)):\n delete_keys.append(attr_key)\n for attr_key in delete_keys:\n del node.attr[attr_key]\n\n\n_TABLE_SHARED_NAME_PATTERN = r\"hash_table_[0-9a-z\\-]+\"\n\n\ndef _strip_hash_table_shared_name(graph_def):\n for node in graph_def.node:\n delete_keys = []\n if node.op == \"HashTableV2\" and \"shared_name\" in node.attr:\n if re.match(compat.as_bytes(_TABLE_SHARED_NAME_PATTERN),\n node.attr[\"shared_name\"].s):\n delete_keys.append(\"shared_name\")\n for attr_key in delete_keys:\n del node.attr[attr_key]\n\n\ndef IsGoogleCudaEnabled():\n return _pywrap_util_port.IsGoogleCudaEnabled()\n\n\ndef IsBuiltWithROCm():\n return _pywrap_util_port.IsBuiltWithROCm()\n\n\ndef IsBuiltWithXLA():\n return _pywrap_util_port.IsBuiltWithXLA()\n\n\ndef IsBuiltWithNvcc():\n return _pywrap_util_port.IsBuiltWithNvcc()\n\n\ndef GpuSupportsHalfMatMulAndConv():\n return _pywrap_util_port.GpuSupportsHalfMatMulAndConv()\n\n\ndef IsMklEnabled():\n return _pywrap_util_port.IsMklEnabled()\n\n\ndef InstallStackTraceHandler():\n _pywrap_stacktrace_handler.InstallStacktraceHandler()\n\n\ndef NHWCToNCHW(input_tensor):\n \"\"\"Converts the input from the NHWC format to NCHW.\n\n Args:\n input_tensor: a 3-, 4-, or 5-D tensor, or an array representing shape\n\n Returns:\n converted tensor or shape array\n \"\"\"\n # tensor dim -> new axis order\n new_axes = {3: [0, 2, 1], 4: [0, 3, 1, 2], 5: [0, 4, 1, 2, 3]}\n if isinstance(input_tensor, ops.Tensor):\n ndims = input_tensor.shape.ndims\n return array_ops.transpose(input_tensor, new_axes[ndims])\n else:\n ndims = len(input_tensor)\n return [input_tensor[a] for a in new_axes[ndims]]\n\n\ndef NHWCToNCHW_VECT_C(input_shape_or_tensor):\n \"\"\"Transforms the input from the NHWC layout to NCHW_VECT_C layout.\n\n Note: Does not include quantization or type conversion steps, which should\n be applied afterwards.\n\n Args:\n input_shape_or_tensor: a 4- or 5-D tensor, or an array representing shape\n\n Returns:\n tensor or shape array transformed into NCHW_VECT_C\n\n Raises:\n ValueError: if last dimension of `input_shape_or_tensor` is not evenly\n divisible by 4.\n \"\"\"\n permutations = {5: [0, 3, 1, 2, 4], 6: [0, 4, 1, 2, 3, 5]}\n is_tensor = isinstance(input_shape_or_tensor, ops.Tensor)\n temp_shape = (\n input_shape_or_tensor.shape.as_list()\n if is_tensor else input_shape_or_tensor)\n if temp_shape[-1] % 4 != 0:\n raise ValueError(\n \"Last dimension of input must be evenly divisible by 4 to convert to \"\n \"NCHW_VECT_C.\")\n temp_shape[-1] //= 4\n temp_shape.append(4)\n permutation = permutations[len(temp_shape)]\n if is_tensor:\n t = array_ops.reshape(input_shape_or_tensor, temp_shape)\n return array_ops.transpose(t, permutation)\n else:\n return [temp_shape[a] for a in permutation]\n\n\ndef NCHW_VECT_CToNHWC(input_shape_or_tensor):\n \"\"\"Transforms the input from the NCHW_VECT_C layout to NHWC layout.\n\n Note: Does not include de-quantization or type conversion steps, which should\n be applied beforehand.\n\n Args:\n input_shape_or_tensor: a 5- or 6-D tensor, or an array representing shape\n\n Returns:\n tensor or shape array transformed into NHWC\n\n Raises:\n ValueError: if last dimension of `input_shape_or_tensor` is not 4.\n \"\"\"\n permutations = {5: [0, 2, 3, 1, 4], 6: [0, 2, 3, 4, 1, 5]}\n is_tensor = isinstance(input_shape_or_tensor, ops.Tensor)\n input_shape = (\n input_shape_or_tensor.shape.as_list()\n if is_tensor else input_shape_or_tensor)\n if input_shape[-1] != 4:\n raise ValueError(\"Last dimension of NCHW_VECT_C must be 4.\")\n permutation = permutations[len(input_shape)]\n nhwc_shape = [input_shape[a] for a in permutation[:-1]]\n nhwc_shape[-1] *= input_shape[-1]\n if is_tensor:\n t = array_ops.transpose(input_shape_or_tensor, permutation)\n return array_ops.reshape(t, nhwc_shape)\n else:\n return nhwc_shape\n\n\ndef NCHWToNHWC(input_tensor):\n \"\"\"Converts the input from the NCHW format to NHWC.\n\n Args:\n input_tensor: a 4- or 5-D tensor, or an array representing shape\n\n Returns:\n converted tensor or shape array\n \"\"\"\n # tensor dim -> new axis order\n new_axes = {4: [0, 2, 3, 1], 5: [0, 2, 3, 4, 1]}\n if isinstance(input_tensor, ops.Tensor):\n ndims = input_tensor.shape.ndims\n return array_ops.transpose(input_tensor, new_axes[ndims])\n else:\n ndims = len(input_tensor)\n return [input_tensor[a] for a in new_axes[ndims]]\n\n\ndef skip_if(condition):\n \"\"\"Skips the decorated function if condition is or evaluates to True.\n\n Args:\n condition: Either an expression that can be used in \"if not condition\"\n statement, or a callable whose result should be a boolean.\n\n Returns:\n The wrapped function\n \"\"\"\n\n def real_skip_if(fn):\n\n def wrapper(*args, **kwargs):\n if callable(condition):\n skip = condition()\n else:\n skip = condition\n if not skip:\n return fn(*args, **kwargs)\n\n return wrapper\n\n return real_skip_if\n\n\[email protected]\ndef skip_if_error(test_obj, error_type, messages=None):\n \"\"\"Context manager to skip cases not considered failures by the tests.\n\n Note that this does not work if used in setUpClass/tearDownClass.\n Usage in setUp/tearDown works fine just like regular test methods.\n\n Args:\n test_obj: A test object provided as `self` in the test methods; this object\n is usually an instance of `unittest.TestCase`'s subclass and should have\n `skipTest` method.\n error_type: The error type to skip. Note that if `messages` are given, both\n `error_type` and `messages` need to match for the test to be skipped.\n messages: Optional, a string or list of strings. If `None`, the test will be\n skipped if `error_type` matches what is raised; otherwise, the test is\n skipped if any of the `messages` is contained in the message of the error\n raised, and `error_type` matches the error raised.\n\n Yields:\n Nothing.\n \"\"\"\n if messages:\n messages = nest.flatten(messages)\n try:\n yield\n except error_type as e:\n if not messages or any(message in str(e) for message in messages):\n test_obj.skipTest(\"Skipping error: {}: {}\".format(type(e), str(e)))\n else:\n raise\n\n\ndef enable_c_shapes(fn):\n \"\"\"No-op. TODO(b/74620627): Remove this.\"\"\"\n return fn\n\n\ndef with_c_shapes(cls):\n \"\"\"No-op. TODO(b/74620627): Remove this.\"\"\"\n return cls\n\n\ndef enable_control_flow_v2(fn):\n \"\"\"Decorator for enabling CondV2 and WhileV2 on a test.\n\n Note this enables using CondV2 and WhileV2 after running the test class's\n setup/teardown methods.\n\n In addition to this, callers must import the while_v2 module in order to set\n the _while_v2 module in control_flow_ops.\n\n Args:\n fn: the function to be wrapped\n\n Returns:\n The wrapped function\n \"\"\"\n\n def wrapper(*args, **kwargs):\n enable_control_flow_v2_old = control_flow_util.ENABLE_CONTROL_FLOW_V2\n control_flow_util.ENABLE_CONTROL_FLOW_V2 = True\n try:\n return fn(*args, **kwargs)\n finally:\n control_flow_util.ENABLE_CONTROL_FLOW_V2 = enable_control_flow_v2_old\n\n return wrapper\n\n\ndef with_control_flow_v2(cls):\n \"\"\"Adds methods that call original methods with WhileV2 and CondV2 enabled.\n\n Note this enables CondV2 and WhileV2 in new methods after running the test\n class's setup method.\n\n In addition to this, callers must import the while_v2 module in order to set\n the _while_v2 module in control_flow_ops.\n\n If a test function has _disable_control_flow_v2 attr set to True (using the\n @disable_control_flow_v2 decorator), the v2 function is not generated for it.\n\n Example:\n\n @test_util.with_control_flow_v2\n class ControlFlowTest(test.TestCase):\n\n def testEnabledForV2(self):\n ...\n\n @test_util.disable_control_flow_v2(\"b/xyzabc\")\n def testDisabledForV2(self):\n ...\n\n Generated class:\n class ControlFlowTest(test.TestCase):\n\n def testEnabledForV2(self):\n ...\n\n def testEnabledForV2WithControlFlowV2(self):\n // Enable V2 flags.\n testEnabledForV2(self)\n // Restore V2 flags.\n\n def testDisabledForV2(self):\n ...\n\n Args:\n cls: class to decorate\n\n Returns:\n cls with new test methods added\n \"\"\"\n if control_flow_util.ENABLE_CONTROL_FLOW_V2:\n return cls\n\n for name, value in cls.__dict__.copy().items():\n if (callable(value) and\n name.startswith(unittest.TestLoader.testMethodPrefix) and\n not getattr(value, \"_disable_control_flow_v2\", False)):\n setattr(cls, name + \"WithControlFlowV2\", enable_control_flow_v2(value))\n return cls\n\n\ndef disable_control_flow_v2(unused_msg):\n \"\"\"Decorator for a function in a with_control_flow_v2 enabled test class.\n\n Blocks the function from being run with v2 control flow ops.\n\n Args:\n unused_msg: Reason for disabling.\n\n Returns:\n The wrapped function with _disable_control_flow_v2 attr set to True.\n \"\"\"\n\n def wrapper(func):\n func._disable_control_flow_v2 = True\n return func\n\n return wrapper\n\n\ndef enable_output_all_intermediates(fn):\n \"\"\"Force-enable outputing all intermediates from functional control flow ops.\n\n Args:\n fn: the function to be wrapped\n\n Returns:\n The wrapped function\n \"\"\"\n\n def wrapper(*args, **kwargs):\n output_all_intermediates_old = \\\n control_flow_util_v2._EXPERIMENTAL_OUTPUT_ALL_INTERMEDIATES_OVERRIDE\n control_flow_util_v2._EXPERIMENTAL_OUTPUT_ALL_INTERMEDIATES_OVERRIDE = True\n try:\n return fn(*args, **kwargs)\n finally:\n control_flow_util_v2._EXPERIMENTAL_OUTPUT_ALL_INTERMEDIATES_OVERRIDE = \\\n output_all_intermediates_old\n\n return wrapper\n\n\ndef assert_no_new_pyobjects_executing_eagerly(func=None, warmup_iters=2):\n \"\"\"Decorator for asserting that no new Python objects persist after a test.\n\n Runs the test multiple times executing eagerly, first as a warmup and then to\n let objects accumulate. The warmup helps ignore caches which do not grow as\n the test is run repeatedly.\n\n Useful for checking that there are no missing Py_DECREFs in the C exercised by\n a bit of Python.\n\n Args:\n func: The function to test.\n warmup_iters: The numer of warmup iterations, excluded from measuring.\n\n Returns:\n The wrapped function performing the test.\n \"\"\"\n\n def wrap_f(f):\n def decorator(self, *args, **kwargs):\n \"\"\"Warms up, gets object counts, runs the test, checks for new objects.\"\"\"\n with context.eager_mode():\n gc.disable()\n # Run the test 2 times as warmup, in an attempt to fill up caches, which\n # should not grow as the test is run repeatedly below.\n #\n # TODO(b/117156879): Running warmup twice is black magic; we have seen\n # tests that fail with 1 warmup run, and pass with 2, on various\n # versions of python2.7.x.\n for _ in range(warmup_iters):\n f(self, *args, **kwargs)\n # Since we aren't in the normal test lifecycle, we need to manually run\n # cleanups to clear out their object references.\n self.doCleanups()\n\n # Some objects are newly created by _get_object_count_by_type(). So\n # create and save as a dummy variable to include it as a baseline.\n obj_count_by_type = _get_object_count_by_type()\n gc.collect()\n\n # Make sure any registered functions are cleaned up in the C++ runtime.\n registered_function_names = context.context().list_function_names()\n\n # unittest.doCleanups adds to self._outcome with each unwound call.\n # These objects are retained across gc collections so we exclude them\n # from the object count calculation.\n obj_count_by_type = _get_object_count_by_type(\n exclude=gc.get_referents(self._outcome.errors,\n self._outcome.skipped))\n\n if ops.has_default_graph():\n collection_sizes_before = {\n collection: len(ops.get_collection(collection))\n for collection in ops.get_default_graph().collections\n }\n for _ in range(3):\n f(self, *args, **kwargs)\n # Since we aren't in the normal test lifecycle, we need to manually run\n # cleanups to clear out their object references.\n self.doCleanups()\n # Note that gc.get_objects misses anything that isn't subject to garbage\n # collection (C types). Collections are a common source of leaks, so we\n # test for collection sizes explicitly.\n if ops.has_default_graph():\n for collection_key in ops.get_default_graph().collections:\n collection = ops.get_collection(collection_key)\n size_before = collection_sizes_before.get(collection_key, 0)\n if len(collection) > size_before:\n raise AssertionError(\n (\"Collection %s increased in size from \"\n \"%d to %d (current items %s).\") %\n (collection_key, size_before, len(collection), collection))\n # Make sure our collection checks don't show up as leaked memory by\n # removing references to temporary variables.\n del collection\n del collection_key\n del size_before\n del collection_sizes_before\n gc.collect()\n\n # There should be no new Python objects hanging around.\n obj_count_by_type = (\n _get_object_count_by_type(\n exclude=gc.get_referents(self._outcome.errors,\n self._outcome.skipped)) -\n obj_count_by_type)\n\n # There should be no newly registered functions hanging around.\n leftover_functions = (\n context.context().list_function_names() - registered_function_names)\n assert not leftover_functions, (\n \"The following functions were newly created: %s\" %\n leftover_functions)\n\n # In some cases (specifically on MacOS), new_count is somehow\n # smaller than previous_count.\n # Using plain assert because not all classes using this decorator\n # have assertLessEqual\n assert not obj_count_by_type, (\n \"The following objects were newly created: %s\" %\n str(obj_count_by_type))\n gc.enable()\n return decorator\n\n if func is None:\n return wrap_f\n else:\n return wrap_f(func)\n\n\ndef assert_no_new_tensors(f):\n \"\"\"Decorator for asserting that no new Tensors persist after a test.\n\n Mainly useful for checking that code using the Python C API has correctly\n manipulated reference counts.\n\n Clears the caches that it knows about, runs the garbage collector, then checks\n that there are no Tensor or Tensor-like objects still around. This includes\n Tensors to which something still has a reference (e.g. from missing\n Py_DECREFs) and uncollectable cycles (i.e. Python reference cycles where one\n of the objects has __del__ defined).\n\n Args:\n f: The test case to run.\n\n Returns:\n The decorated test case.\n \"\"\"\n\n def decorator(self, **kwargs):\n \"\"\"Finds existing Tensors, runs the test, checks for new Tensors.\"\"\"\n\n def _is_tensorflow_object(obj):\n try:\n return isinstance(obj,\n (ops.Tensor, variables.Variable,\n tensor_shape.Dimension, tensor_shape.TensorShape))\n except (ReferenceError, AttributeError):\n # If the object no longer exists, we don't care about it.\n return False\n\n tensors_before = set(\n id(obj) for obj in gc.get_objects() if _is_tensorflow_object(obj))\n outside_executed_eagerly = context.executing_eagerly()\n # Run the test in a new graph so that collections get cleared when it's\n # done, but inherit the graph key so optimizers behave.\n outside_graph_key = ops.get_default_graph()._graph_key\n with ops.Graph().as_default():\n ops.get_default_graph()._graph_key = outside_graph_key\n if outside_executed_eagerly:\n with context.eager_mode():\n result = f(self, **kwargs)\n else:\n result = f(self, **kwargs)\n # Make an effort to clear caches, which would otherwise look like leaked\n # Tensors.\n context.context()._clear_caches() # pylint: disable=protected-access\n gc.collect()\n tensors_after = [\n obj for obj in gc.get_objects()\n if _is_tensorflow_object(obj) and id(obj) not in tensors_before\n ]\n if tensors_after:\n raise AssertionError((\"%d Tensors not deallocated after test: %s\" % (\n len(tensors_after),\n str(tensors_after),\n )))\n return result\n\n return decorator\n\n\ndef _find_reference_cycle(objects, idx):\n\n def get_ignore_reason(obj, denylist):\n \"\"\"Tests whether an object should be omitted from the dependency graph.\"\"\"\n if len(denylist) > 100:\n return \"<depth limit>\"\n if tf_inspect.isframe(obj):\n if \"test_util.py\" in tf_inspect.getframeinfo(obj)[0]:\n return \"<test code>\"\n for b in denylist:\n if b is obj:\n return \"<test code>\"\n if obj is denylist:\n return \"<test code>\"\n return None\n\n # Note: this function is meant to help with diagnostics. Its output is purely\n # a human-readable representation, so you may freely modify it to suit your\n # needs.\n def describe(obj, denylist, leaves_only=False):\n \"\"\"Returns a custom human-readable summary of obj.\n\n Args:\n obj: the value to describe.\n denylist: same as denylist in get_ignore_reason.\n leaves_only: boolean flag used when calling describe recursively. Useful\n for summarizing collections.\n \"\"\"\n if get_ignore_reason(obj, denylist):\n return \"{}{}\".format(get_ignore_reason(obj, denylist), type(obj))\n if tf_inspect.isframe(obj):\n return \"frame: {}\".format(tf_inspect.getframeinfo(obj))\n elif tf_inspect.ismodule(obj):\n return \"module: {}\".format(obj.__name__)\n else:\n if leaves_only:\n return \"{}, {}\".format(type(obj), id(obj))\n elif isinstance(obj, list):\n return \"list({}): {}\".format(\n id(obj), [describe(e, denylist, leaves_only=True) for e in obj])\n elif isinstance(obj, tuple):\n return \"tuple({}): {}\".format(\n id(obj), [describe(e, denylist, leaves_only=True) for e in obj])\n elif isinstance(obj, dict):\n return \"dict({}): {} keys\".format(id(obj), len(obj.keys()))\n elif tf_inspect.isfunction(obj):\n return \"function({}) {}; globals ID: {}\".format(\n id(obj), obj.__name__, id(obj.__globals__))\n else:\n return \"{}, {}\".format(type(obj), id(obj))\n\n def build_ref_graph(obj, graph, reprs, denylist):\n \"\"\"Builds a reference graph as <referrer> -> <list of referents>.\n\n Args:\n obj: The object to start from. The graph will be built by recursively\n adding its referrers.\n graph: Dict holding the graph to be built. To avoid creating extra\n references, the graph holds object IDs rather than actual objects.\n reprs: Auxiliary structure that maps object IDs to their human-readable\n description.\n denylist: List of objects to ignore.\n \"\"\"\n referrers = gc.get_referrers(obj)\n denylist = denylist + (referrers,)\n\n obj_id = id(obj)\n for r in referrers:\n if get_ignore_reason(r, denylist) is None:\n r_id = id(r)\n if r_id not in graph:\n graph[r_id] = []\n if obj_id not in graph[r_id]:\n graph[r_id].append(obj_id)\n build_ref_graph(r, graph, reprs, denylist)\n reprs[r_id] = describe(r, denylist)\n\n def find_cycle(el, graph, reprs, path):\n \"\"\"Finds and prints a single cycle in the dependency graph.\"\"\"\n if el not in graph:\n return\n for r in graph[el]:\n if r in path:\n logging.error(\"Reference cycle sample:\")\n for p in path + (r,):\n logging.error(reprs.get(p, \"unknown object \" + str(p)))\n return True\n else:\n if find_cycle(r, graph, reprs, path + (r,)):\n return True\n return False\n\n obj = objects[idx]\n graph = {} # referrer ID -> object ID\n reprs = {} # object ID -> description\n build_ref_graph(obj, graph, reprs, (objects, graph, reprs, get_ignore_reason,\n describe, build_ref_graph, find_cycle))\n for k in graph:\n if find_cycle(k, graph, reprs, ()):\n return True\n return False\n\n\ndef assert_no_garbage_created(f):\n \"\"\"Test method decorator to assert that no garbage has been created.\n\n Note that this decorator sets DEBUG_SAVEALL, which in some Python interpreters\n cannot be un-set (i.e. will disable garbage collection for any other unit\n tests in the same file/shard).\n\n Args:\n f: The function to decorate.\n\n Returns:\n The decorated function.\n \"\"\"\n\n def decorator(self, **kwargs):\n \"\"\"Sets DEBUG_SAVEALL, runs the test, and checks for new garbage.\"\"\"\n # Force-load `distribution_strategy_context` to prevent GC at\n # test time when using eager. Remove once b/117329403 is resolved.\n tape.distribution_strategy_context.get_strategy()\n\n gc.disable()\n previous_debug_flags = gc.get_debug()\n gc.set_debug(gc.DEBUG_SAVEALL)\n gc.collect()\n previous_garbage = len(gc.garbage)\n result = f(self, **kwargs)\n gc.collect()\n new_garbage = len(gc.garbage)\n if new_garbage > previous_garbage:\n logging.error(\n \"The decorated test created work for Python's garbage collector, \"\n \"likely due to a reference cycle. New objects in cycle(s):\")\n for i, obj in enumerate(gc.garbage[previous_garbage:]):\n try:\n logging.error(\"Object %d of %d\", i,\n len(gc.garbage) - previous_garbage)\n\n def _safe_object_str(obj):\n return \"<%s %d>\" % (obj.__class__.__name__, id(obj))\n\n logging.error(\" Object type: %s\", _safe_object_str(obj))\n logging.error(\n \" Referrer types: %s\", \", \".join(\n [_safe_object_str(ref) for ref in gc.get_referrers(obj)]))\n logging.error(\n \" Referent types: %s\", \", \".join(\n [_safe_object_str(ref) for ref in gc.get_referents(obj)]))\n logging.error(\" Object attribute names: %s\", dir(obj))\n logging.error(\" Object __str__:\")\n logging.error(obj)\n logging.error(\" Object __repr__:\")\n logging.error(repr(obj))\n except Exception: # pylint: disable=broad-except\n logging.error(\"(Exception while printing object)\")\n\n # When garbage is created, this call can help identify reference cycles,\n # which are typically the cause of such garbage.\n if new_garbage > previous_garbage:\n for i in range(previous_garbage, new_garbage):\n if _find_reference_cycle(gc.garbage, i):\n break\n\n # This will fail if any garbage has been created, typically because of a\n # reference cycle.\n self.assertEqual(previous_garbage, new_garbage)\n # TODO(allenl): Figure out why this debug flag reset doesn't work. It would\n # be nice to be able to decorate arbitrary tests in a large test suite and\n # not hold on to every object in other tests.\n gc.set_debug(previous_debug_flags)\n gc.enable()\n return result\n\n return decorator\n\n\ndef _combine_named_parameters(**kwargs):\n \"\"\"Generate combinations based on its keyword arguments.\n\n Two sets of returned combinations can be concatenated using +. Their product\n can be computed using `times()`.\n\n Args:\n **kwargs: keyword arguments of form `option=[possibilities, ...]` or\n `option=the_only_possibility`.\n\n Returns:\n a list of dictionaries for each combination. Keys in the dictionaries are\n the keyword argument names. Each key has one value - one of the\n corresponding keyword argument values.\n \"\"\"\n sort_by_key = lambda k: k[0]\n combinations = []\n for key, values in sorted(kwargs.items(), key=sort_by_key):\n if not isinstance(values, list):\n values = [values]\n combinations.append([(key, value) for value in values])\n\n return [OrderedDict(result) for result in itertools.product(*combinations)]\n\n\ndef generate_combinations_with_testcase_name(**kwargs):\n \"\"\"Generate combinations based on its keyword arguments using combine().\n\n This function calls combine() and appends a testcase name to the list of\n dictionaries returned. The 'testcase_name' key is a required for named\n parameterized tests.\n\n Args:\n **kwargs: keyword arguments of form `option=[possibilities, ...]` or\n `option=the_only_possibility`.\n\n Returns:\n a list of dictionaries for each combination. Keys in the dictionaries are\n the keyword argument names. Each key has one value - one of the\n corresponding keyword argument values.\n \"\"\"\n combinations = _combine_named_parameters(**kwargs)\n named_combinations = []\n for combination in combinations:\n assert isinstance(combination, OrderedDict)\n name = \"\".join([\n \"_{}_{}\".format(\"\".join(filter(str.isalnum, key)),\n \"\".join(filter(str.isalnum, str(value))))\n for key, value in combination.items()\n ])\n named_combinations.append(\n OrderedDict(\n list(combination.items()) +\n [(\"testcase_name\", \"_test{}\".format(name))]))\n\n return named_combinations\n\n\ndef run_all_in_graph_and_eager_modes(cls):\n \"\"\"Execute all test methods in the given class with and without eager.\"\"\"\n base_decorator = run_in_graph_and_eager_modes\n for name in dir(cls):\n if (not name.startswith(unittest.TestLoader.testMethodPrefix) or\n name.startswith(\"testSkipEager\") or\n name.startswith(\"test_skip_eager\") or\n name == \"test_session\"):\n continue\n value = getattr(cls, name, None)\n if callable(value):\n setattr(cls, name, base_decorator(value))\n return cls\n\n\ndef build_as_function_and_v1_graph(func=None):\n \"\"\"Run a test case in v1 graph mode and inside tf.function in eager mode.\n\n WARNING: This decorator can only be used in test cases that statically checks\n generated graph. Attempting to evaluate graph or function results via.\n session.run() or self.evaluate() will fail.\n\n WARNING: This decorator can only be used for test cases that inherit from\n absl.testing.parameterized.TestCase.\n\n Args:\n func: Test case function to be decorated.\n\n Returns:\n Decorated test case function.\n \"\"\"\n\n def decorator(f):\n if tf_inspect.isclass(f):\n raise ValueError(\n \"`run_in_graph_mode_and_function` only supports test methods.\")\n\n @parameterized.named_parameters((\"_v1_graph\", \"v1_graph\"),\n (\"_function\", \"function\"))\n @functools.wraps(f)\n def decorated(self, run_mode, *args, **kwargs):\n if run_mode == \"v1_graph\":\n with ops.Graph().as_default():\n f(self, *args, **kwargs)\n elif run_mode == \"function\":\n\n @def_function.function\n def function_in_eager():\n f(self, *args, **kwargs)\n\n # Create a new graph for the eagerly executed version of this test for\n # better isolation.\n graph_for_eager_test = ops.Graph()\n with graph_for_eager_test.as_default(), context.eager_mode():\n function_in_eager()\n ops.dismantle_graph(graph_for_eager_test)\n else:\n return ValueError(\"Unknown run mode %s\" % run_mode)\n\n return decorated\n\n if func is not None:\n return decorator(func)\n\n return decorator\n\n\ndef run_in_async_and_sync_mode(f):\n \"\"\"Execute the test in async mode and sync mode.\"\"\"\n\n @parameterized.named_parameters([(\"Async\", True), (\"\", False)])\n @functools.wraps(f)\n def decorator(self, async_mode, *args, **kwargs):\n if async_mode:\n with context.execution_mode(context.ASYNC):\n f(self, *args, **kwargs)\n else:\n with context.execution_mode(context.SYNC):\n f(self, *args, **kwargs)\n return decorator\n\n\ndef run_in_graph_and_eager_modes(func=None,\n config=None,\n use_gpu=True,\n assert_no_eager_garbage=False):\n \"\"\"Execute the decorated test with and without enabling eager execution.\n\n This function returns a decorator intended to be applied to test methods in\n a `tf.test.TestCase` class. Doing so will cause the contents of the test\n method to be executed twice - once normally, and once with eager execution\n enabled. This allows unittests to confirm the equivalence between eager\n and graph execution (see `tf.compat.v1.enable_eager_execution`).\n\n For example, consider the following unittest:\n\n ```python\n class MyTests(tf.test.TestCase):\n\n @run_in_graph_and_eager_modes\n def test_foo(self):\n x = tf.constant([1, 2])\n y = tf.constant([3, 4])\n z = tf.add(x, y)\n self.assertAllEqual([4, 6], self.evaluate(z))\n\n if __name__ == \"__main__\":\n tf.test.main()\n ```\n\n This test validates that `tf.add()` has the same behavior when computed with\n eager execution enabled as it does when constructing a TensorFlow graph and\n executing the `z` tensor in a session.\n\n `deprecated_graph_mode_only`, `run_v1_only`, `run_v2_only`, and\n `run_in_graph_and_eager_modes` are available decorators for different\n v1/v2/eager/graph combinations.\n\n\n Args:\n func: function to be annotated. If `func` is None, this method returns a\n decorator the can be applied to a function. If `func` is not None this\n returns the decorator applied to `func`.\n config: An optional config_pb2.ConfigProto to use to configure the session\n when executing graphs.\n use_gpu: If True, attempt to run as many operations as possible on GPU.\n assert_no_eager_garbage: If True, sets DEBUG_SAVEALL on the garbage\n collector and asserts that no extra garbage has been created when running\n the test with eager execution enabled. This will fail if there are\n reference cycles (e.g. a = []; a.append(a)). Off by default because some\n tests may create garbage for legitimate reasons (e.g. they define a class\n which inherits from `object`), and because DEBUG_SAVEALL is sticky in some\n Python interpreters (meaning that tests which rely on objects being\n collected elsewhere in the unit test file will not work). Additionally,\n checks that nothing still has a reference to Tensors that the test\n allocated.\n\n Returns:\n Returns a decorator that will run the decorated test method twice:\n once by constructing and executing a graph in a session and once with\n eager execution enabled.\n \"\"\"\n\n def decorator(f):\n if tf_inspect.isclass(f):\n raise ValueError(\n \"`run_in_graph_and_eager_modes` only supports test methods. \"\n \"Did you mean to use `run_all_in_graph_and_eager_modes`?\")\n\n def decorated(self, *args, **kwargs):\n try:\n with context.graph_mode():\n with self.test_session(use_gpu=use_gpu, config=config):\n f(self, *args, **kwargs)\n except unittest.case.SkipTest:\n pass\n\n def run_eagerly(self, **kwargs):\n if not use_gpu:\n with ops.device(\"/device:CPU:0\"):\n f(self, *args, **kwargs)\n else:\n f(self, *args, **kwargs)\n\n if assert_no_eager_garbage:\n ops.reset_default_graph()\n run_eagerly = assert_no_new_tensors(\n assert_no_garbage_created(run_eagerly))\n\n # This decorator runs the wrapped test twice.\n # Reset the test environment between runs.\n self.tearDown()\n self._tempdir = None\n # Create a new graph for the eagerly executed version of this test for\n # better isolation.\n graph_for_eager_test = ops.Graph()\n with graph_for_eager_test.as_default(), context.eager_mode():\n self.setUp()\n run_eagerly(self, **kwargs)\n ops.dismantle_graph(graph_for_eager_test)\n\n return tf_decorator.make_decorator(f, decorated)\n\n if func is not None:\n return decorator(func)\n\n return decorator\n\n\ndef py_func_if_in_function(f):\n\n def decorated(*args, **kwds):\n if not ops.inside_function():\n return f(*args, **kwds)\n\n tensor_args = []\n tensor_indices = []\n for i, arg in enumerate(args):\n if isinstance(arg, (ops.Tensor, variables.Variable)):\n tensor_args.append(arg)\n tensor_indices.append(i)\n\n def inner_f(*inner_tensor_args):\n my_args = list(args)\n for i, n in zip(tensor_indices, inner_tensor_args):\n my_args[i] = n\n return f(*my_args, **kwds)\n\n return script_ops.py_func(inner_f, tensor_args, [])\n\n return tf_decorator.make_decorator(f, decorated)\n\n\ndef also_run_as_tf_function(f):\n \"\"\"Runs the decorated test twice--once as is, once inside a tf.function.\n\n This allows you to run a test both in eager execution and inside a\n tf.function, exercising the two execution modes supported in tf 2.0. The test\n assertions are automatically done inside tf.py_funcs, and tf.function ensures\n that they run in the proper order and with the proper side effects.\n\n Currently variable creation is not supported in tests annotated with this\n decorator since it's tricky to ensure the variable doesn't get repeatedly\n created when retracing the tf.function.\n\n Args:\n f: the test method to be decorated\n\n Returns:\n The decorated test method, which will run both in eager and inside a\n tf.function.\n \"\"\"\n\n def decorated(*args, **kwds):\n\n def bound_f():\n f(*args, **kwds)\n\n with context.eager_mode():\n # Running in eager mode\n bound_f()\n # Running as TF function\n # TODO(b/121143941): Remove the autograph override.\n def_function.function(bound_f, autograph=False)()\n\n return decorated\n\n\ndef deprecated_graph_mode_only(func=None):\n \"\"\"Execute the decorated test in graph mode.\n\n This function returns a decorator intended to be applied to tests that are not\n compatible with eager mode. When this decorator is applied, the test body will\n be run in an environment where API calls construct graphs instead of executing\n eagerly.\n\n `deprecated_graph_mode_only`, `run_v1_only`, `run_v2_only`, and\n `run_in_graph_and_eager_modes` are available decorators for different\n v1/v2/eager/graph combinations.\n\n Args:\n func: function to be annotated. If `func` is None, this method returns a\n decorator the can be applied to a function. If `func` is not None this\n returns the decorator applied to `func`.\n\n Returns:\n Returns a decorator that will run the decorated test method in graph mode.\n \"\"\"\n\n def decorator(f):\n if tf_inspect.isclass(f):\n setup = f.__dict__.get(\"setUp\")\n if setup is not None:\n setattr(f, \"setUp\", decorator(setup))\n\n for name, value in f.__dict__.copy().items():\n if (callable(value) and\n name.startswith(unittest.TestLoader.testMethodPrefix)):\n setattr(f, name, decorator(value))\n\n return f\n\n def decorated(self, *args, **kwargs):\n if context.executing_eagerly():\n with context.graph_mode():\n return f(self, *args, **kwargs)\n else:\n return f(self, *args, **kwargs)\n\n return decorated\n\n if func is not None:\n return decorator(func)\n\n return decorator\n\n\nrun_deprecated_v1 = deprecated_graph_mode_only\n\n\ndef run_all_in_deprecated_graph_mode_only(cls):\n \"\"\"Execute all tests in a class in graph mode.\"\"\"\n base_decorator = deprecated_graph_mode_only\n for name in dir(cls):\n if (not name.startswith(unittest.TestLoader.testMethodPrefix) or\n name == \"test_session\"):\n continue\n value = getattr(cls, name, None)\n if callable(value):\n setattr(cls, name, base_decorator(value))\n return cls\n\n\ndef run_v1_only(reason, func=None):\n \"\"\"Execute the decorated test only if running in v1 mode.\n\n This function is intended to be applied to tests that exercise v1 only\n functionality. If the test is run in v2 mode it will simply be skipped.\n\n `deprecated_graph_mode_only`, `run_v1_only`, `run_v2_only`, and\n `run_in_graph_and_eager_modes` are available decorators for different\n v1/v2/eager/graph combinations.\n\n Args:\n reason: string giving a reason for limiting the test to v1 only.\n func: function to be annotated. If `func` is None, this method returns a\n decorator the can be applied to a function. If `func` is not None this\n returns the decorator applied to `func`.\n\n Returns:\n Returns a decorator that will conditionally skip the decorated test method.\n \"\"\"\n if not isinstance(reason, str):\n raise ValueError(\"'reason' should be string, got {}\".format(type(reason)))\n\n def decorator(f):\n if tf_inspect.isclass(f):\n # To skip an entire test suite class, we only decorate the setUp method\n # to skip all tests. There are cases when setUp is not defined (not\n # overridden in subclasses of TestCase, so not available in f.__dict__\n # below). For those cases, we walk the method resolution order list and\n # pick the first setUp method we find (usually this should be the one in\n # the parent class since that's the TestCase class).\n for cls in type.mro(f):\n setup = cls.__dict__.get(\"setUp\")\n if setup is not None:\n setattr(f, \"setUp\", decorator(setup))\n break\n\n return f\n else:\n # If f is just a function, just create a decorator for it and return it\n def decorated(self, *args, **kwargs):\n if tf2.enabled():\n self.skipTest(reason)\n\n return f(self, *args, **kwargs)\n\n return decorated\n\n if func is not None:\n return decorator(func)\n\n return decorator\n\n\ndef run_v2_only(func=None):\n \"\"\"Execute the decorated test only if running in v2 mode.\n\n This function is intended to be applied to tests that exercise v2 only\n functionality. If the test is run in v1 mode it will simply be skipped.\n\n `deprecated_graph_mode_only`, `run_v1_only`, `run_v2_only`, and\n `run_in_graph_and_eager_modes` are available decorators for different\n v1/v2/eager/graph combinations.\n\n Args:\n func: function to be annotated. If `func` is None, this method returns a\n decorator the can be applied to a function. If `func` is not None this\n returns the decorator applied to `func`.\n\n Returns:\n Returns a decorator that will conditionally skip the decorated test method.\n \"\"\"\n\n def decorator(f):\n if tf_inspect.isclass(f):\n raise ValueError(\"`run_v2_only` only supports test methods.\")\n\n def decorated(self, *args, **kwargs):\n if not tf2.enabled():\n self.skipTest(\"Test is only compatible with v2\")\n\n return f(self, *args, **kwargs)\n\n return decorated\n\n if func is not None:\n return decorator(func)\n\n return decorator\n\n\ndef run_gpu_only(func=None):\n \"\"\"Execute the decorated test only if a GPU is available.\n\n This function is intended to be applied to tests that require the presence\n of a GPU. If a GPU is absent, it will simply be skipped.\n\n Args:\n func: function to be annotated. If `func` is None, this method returns a\n decorator the can be applied to a function. If `func` is not None this\n returns the decorator applied to `func`.\n\n Returns:\n Returns a decorator that will conditionally skip the decorated test method.\n \"\"\"\n\n def decorator(f):\n if tf_inspect.isclass(f):\n raise ValueError(\"`run_gpu_only` only supports test methods.\")\n\n def decorated(self, *args, **kwargs):\n if not is_gpu_available():\n self.skipTest(\"Test requires GPU\")\n\n return f(self, *args, **kwargs)\n\n return decorated\n\n if func is not None:\n return decorator(func)\n\n return decorator\n\n\ndef run_cuda_only(func=None):\n \"\"\"Execute the decorated test only if a GPU is available.\n\n This function is intended to be applied to tests that require the presence\n of a CUDA GPU. If a CUDA GPU is absent, it will simply be skipped.\n\n Args:\n func: function to be annotated. If `func` is None, this method returns a\n decorator the can be applied to a function. If `func` is not None this\n returns the decorator applied to `func`.\n\n Returns:\n Returns a decorator that will conditionally skip the decorated test method.\n \"\"\"\n\n def decorator(f):\n if tf_inspect.isclass(f):\n raise ValueError(\"`run_cuda_only` only supports test methods.\")\n\n def decorated(self, *args, **kwargs):\n if not is_gpu_available(cuda_only=True):\n self.skipTest(\"Test requires CUDA GPU\")\n\n return f(self, *args, **kwargs)\n\n return decorated\n\n if func is not None:\n return decorator(func)\n\n return decorator\n\n\ndef with_forward_compatibility_horizons(*horizons):\n \"\"\"Executes the decorated test with the specified forward-compat horizons.\n\n Args:\n *horizons: A list of (year, month, day) tuples. If the list includes\n `None`, then the test will also be run with no forward-compatibility\n horizon set.\n\n Returns:\n A decorator that will execute the test with the specified horizons.\n \"\"\"\n if not horizons:\n raise ValueError(\"Expected at least one horizon.\")\n for horizon in horizons:\n if not ((horizon is None) or\n (len(horizon) == 3 and all(isinstance(x, int) for x in horizon))):\n raise ValueError(\"Bad horizon value: %r\" % horizon)\n\n def decorator(f):\n if tf_inspect.isclass(f):\n raise ValueError(\"`with_forward_compatibility_horizons` only \"\n \"supports test methods.\")\n def decorated(self, *args, **kwargs):\n for horizon in horizons:\n if horizon is None:\n f(self, *args, **kwargs)\n else:\n (year, month, day) = horizon\n with forward_compatibility_horizon(year, month, day):\n f(self, *args, **kwargs)\n return decorated\n\n return decorator\n\n\[email protected](None,\n \"Use `tf.config.list_physical_devices('GPU')` instead.\")\n@tf_export(\"test.is_gpu_available\")\ndef is_gpu_available(cuda_only=False, min_cuda_compute_capability=None):\n \"\"\"Returns whether TensorFlow can access a GPU.\n\n Warning: if a non-GPU version of the package is installed, the function would\n also return False. Use `tf.test.is_built_with_cuda` to validate if TensorFlow\n was build with CUDA support.\n\n For example,\n >>> gpu_available = tf.test.is_gpu_available()\n >>> is_cuda_gpu_available = tf.test.is_gpu_available(cuda_only=True)\n >>> is_cuda_gpu_min_3 = tf.test.is_gpu_available(True, (3,0))\n\n Args:\n cuda_only: limit the search to CUDA GPUs.\n min_cuda_compute_capability: a (major,minor) pair that indicates the minimum\n CUDA compute capability required, or None if no requirement.\n\n Note that the keyword arg name \"cuda_only\" is misleading (since routine will\n return true when a GPU device is available irrespective of whether TF was\n built with CUDA support or ROCm support. However no changes here because\n\n ++ Changing the name \"cuda_only\" to something more generic would break\n backward compatibility\n\n ++ Adding an equivalent \"rocm_only\" would require the implementation check\n the build type. This in turn would require doing the same for CUDA and thus\n potentially break backward compatibility\n\n ++ Adding a new \"cuda_or_rocm_only\" would not break backward compatibility,\n but would require most (if not all) callers to update the call to use\n \"cuda_or_rocm_only\" instead of \"cuda_only\"\n\n Returns:\n True if a GPU device of the requested kind is available.\n \"\"\"\n\n # This was needed earlier when we had support for SYCL in TensorFlow.\n del cuda_only\n\n try:\n for local_device in device_lib.list_local_devices():\n if local_device.device_type == \"GPU\":\n gpu_info = gpu_util.compute_capability_from_device_desc(local_device)\n cc = gpu_info.compute_capability or (0, 0)\n if not min_cuda_compute_capability or cc >= min_cuda_compute_capability:\n return True\n return False\n except errors_impl.NotFoundError as e:\n if not all(x in str(e) for x in [\"CUDA\", \"not find\"]):\n raise e\n else:\n logging.error(str(e))\n return False\n\n\[email protected]\ndef device(use_gpu):\n \"\"\"Uses gpu when requested and available.\"\"\"\n if use_gpu and is_gpu_available():\n dev = \"/device:GPU:0\"\n else:\n dev = \"/device:CPU:0\"\n with ops.device(dev):\n yield\n\n\[email protected]\ndef use_gpu():\n \"\"\"Uses gpu when requested and available.\"\"\"\n with device(use_gpu=True):\n yield\n\n\[email protected]\ndef force_gpu():\n \"\"\"Force the gpu to be used.\"\"\"\n with ops.device(\"/device:GPU:0\"):\n yield\n\n\[email protected]\ndef force_cpu():\n \"\"\"Force the cpu to be used.\"\"\"\n with ops.device(\"/device:CPU:0\"):\n yield\n\n\nclass CapturedWrites(object):\n \"\"\"A utility class to load the captured writes made to a stream.\"\"\"\n\n def __init__(self, capture_location):\n self.capture_location = capture_location\n\n def contents(self):\n \"\"\"Get the captured writes as a single string.\"\"\"\n with open(self.capture_location) as tmp_file:\n output_data = \"\".join(tmp_file.readlines())\n return output_data\n\n\nclass FakeEagerSession(object):\n \"\"\"Fake session so tests that conditionally use placeholders can use eager.\n\n There are a number of tests that conditionally use placeholders for shape\n inference. The pattern is demonstrated here:\n\n ```python\n with self.cached_session() as sess:\n if static_shape:\n y = math_ops.matmul(x, ...)\n feed_dict = {}\n else:\n x_ph = array_ops.placeholder(...)\n y = math_ops.matmul(x_ph, ...)\n feed_dict = {x_ph: x}\n val = sess.run(y, feed_dict=feed_dict)\n ```\n\n Since the feed_dict is empty when not using placeholders we should be able to\n call self.evaluate(), however this requires rewriting the test case.\n This class should be considered a stop-gap solution to get tests running with\n eager with minimal changes to the actual test.\n \"\"\"\n\n def __init__(self, test_case):\n self._test_case = test_case\n\n def run(self, fetches, *args, **kwargs):\n \"\"\"Evaluate `fetches`.\n\n Fail if additional args are specified.\n\n Args:\n fetches: A Tensor or a nested list/tuple of Tensors.\n *args: Positional arguments\n **kwargs: Keyword arguments\n\n Raises:\n RuntimeError: If args or kwargs are specified.\n\n Returns:\n Tensors as numpy values.\n \"\"\"\n feed_dict = kwargs.pop(\"feed_dict\", {})\n if feed_dict:\n raise RuntimeError(\n \"feed_dict is not supported when eager execution is enabled \"\n \"(in this case, sess.run(t) is shorthand for t.numpy()\")\n\n if args or kwargs:\n raise RuntimeError(\n \"Optional args are not supported when eager execution is enabled \"\n \"(in this case, sess.run(t) is shorthand for t.numpy()\")\n\n return self._test_case.evaluate(fetches)\n\n\nclass ErrorLoggingSession(session.Session):\n \"\"\"Wrapper around a Session that logs errors in run().\"\"\"\n\n def run(self, *args, **kwargs):\n try:\n return super(ErrorLoggingSession, self).run(*args, **kwargs)\n except Exception as e: # pylint: disable=broad-except\n # Note: disable the logging for OutOfRangeError, which makes the output\n # of tf.data tests hard to read, because OutOfRangeError is used as the\n # signal completion\n if not isinstance(e, errors.OutOfRangeError):\n logging.error(str(e))\n raise\n\n\ndef disable_cudnn_autotune(func):\n \"\"\"Disable autotuning during the call to this function.\n\n Some tests want to base assertions on a graph being isomorphic with a copy.\n To ensure this, this decorator disables autotuning.\n\n Args:\n func: Function to run with CuDNN autotuning turned off.\n\n Returns:\n Decorated function.\n \"\"\"\n\n def decorator(f):\n\n def decorated(self, *args, **kwargs):\n original_tf_cudnn_use_autotune = os.environ.get(\"TF_CUDNN_USE_AUTOTUNE\")\n os.environ[\"TF_CUDNN_USE_AUTOTUNE\"] = \"false\"\n original_xla_flags = os.environ.get(\"XLA_FLAGS\")\n new_xla_flags = \"--xla_gpu_autotune_level=0\"\n if original_xla_flags:\n new_xla_flags = original_xla_flags + \" \" + new_xla_flags\n os.environ[\"XLA_FLAGS\"] = new_xla_flags\n\n result = f(self, *args, **kwargs)\n\n if (original_tf_cudnn_use_autotune is None):\n del os.environ[\"TF_CUDNN_USE_AUTOTUNE\"]\n else:\n os.environ[\"TF_CUDNN_USE_AUTOTUNE\"] = original_tf_cudnn_use_autotune\n if (original_xla_flags is None):\n del os.environ[\"XLA_FLAGS\"]\n else:\n os.environ[\"XLA_FLAGS\"] = original_xla_flags\n\n return result\n\n return decorated\n\n if func is not None:\n return decorator(func)\n\n return decorator\n\n\n# The description is just for documentation purposes.\ndef enable_tf_xla_constant_folding(description):\n\n if not isinstance(description, str):\n raise ValueError(\"'description' should be string, got {}\".format(\n type(description)))\n\n def enable_tf_xla_constant_folding_impl(func):\n \"\"\"Enable constant folding during the call to this function.\n\n Some tests fail without constant folding.\n\n Args:\n func: Function to run with constant folding turned on.\n\n Returns:\n Decorated function.\n \"\"\"\n\n def decorator(f):\n\n def decorated(self, *args, **kwargs):\n original_var = pywrap_tf_session.TF_GetXlaConstantFoldingDisabled()\n pywrap_tf_session.TF_SetXlaConstantFoldingDisabled(False)\n result = f(self, *args, **kwargs)\n pywrap_tf_session.TF_SetXlaConstantFoldingDisabled(original_var)\n return result\n\n return decorated\n\n if func is not None:\n return decorator(func)\n\n return decorator\n\n return enable_tf_xla_constant_folding_impl\n\n\n# Updates test function by selectively disabling it.\ndef _disable_test(execute_func):\n\n def disable_test_impl(func):\n\n def decorator(func):\n\n def decorated(self, *args, **kwargs):\n if execute_func:\n return func(self, *args, **kwargs)\n\n return decorated\n\n if func is not None:\n return decorator(func)\n\n return decorator\n\n return disable_test_impl\n\n\n# The description is just for documentation purposes.\ndef disable_xla(description): # pylint: disable=unused-argument\n \"\"\"Execute the test method only if xla is not enabled.\"\"\"\n execute_func = not is_xla_enabled()\n return _disable_test(execute_func)\n\n\n# The description is just for documentation purposes.\ndef disable_mlir_bridge(description): # pylint: disable=unused-argument\n \"\"\"Execute the test method only if MLIR bridge is not enabled.\"\"\"\n execute_func = not is_mlir_bridge_enabled()\n return _disable_test(execute_func)\n\n\n# The description is just for documentation purposes.\ndef disable_tfrt(unused_description):\n\n def disable_tfrt_impl(cls_or_func):\n \"\"\"Execute the test only if tfrt is not enabled.\"\"\"\n\n if tf_inspect.isclass(cls_or_func):\n if tfrt_utils.enabled():\n return None\n else:\n return cls_or_func\n else:\n def decorator(func):\n\n def decorated(self, *args, **kwargs):\n if tfrt_utils.enabled():\n return\n else:\n return func(self, *args, **kwargs)\n\n return decorated\n\n if cls_or_func is not None:\n return decorator(cls_or_func)\n\n return decorator\n\n return disable_tfrt_impl\n\n\ndef for_all_test_methods(decorator, *args, **kwargs):\n \"\"\"Generate class-level decorator from given method-level decorator.\n\n It is expected for the given decorator to take some arguments and return\n a method that is then called on the test method to produce a decorated\n method.\n\n Args:\n decorator: The decorator to apply.\n *args: Positional arguments\n **kwargs: Keyword arguments\n Returns: Function that will decorate a given classes test methods with the\n decorator.\n \"\"\"\n\n def all_test_methods_impl(cls):\n \"\"\"Apply decorator to all test methods in class.\"\"\"\n for name in dir(cls):\n value = getattr(cls, name)\n if callable(value) and name.startswith(\n \"test\") and (name != \"test_session\"):\n setattr(cls, name, decorator(*args, **kwargs)(value))\n return cls\n\n return all_test_methods_impl\n\n\n# The description is just for documentation purposes.\ndef no_xla_auto_jit(description): # pylint: disable=unused-argument\n \"\"\"This test is not intended to be run with XLA auto jit enabled.\"\"\"\n execute_func = not is_xla_enabled()\n return _disable_test(execute_func)\n\n\n# The description is just for documentation purposes.\ndef xla_allow_fallback(description): # pylint: disable=unused-argument\n\n def xla_allow_fallback_impl(func):\n \"\"\"Allow fallback to TF even though testing xla.\"\"\"\n\n def decorator(func):\n\n def decorated(self, *args, **kwargs):\n if is_xla_enabled():\n # Update the global XLABuildOpsPassFlags to enable lazy compilation,\n # which allows the compiler to fall back to TF classic. Remember the\n # old value so that we can reset it.\n old_value = pywrap_tf_session.TF_SetXlaEnableLazyCompilation(True)\n result = func(self, *args, **kwargs)\n pywrap_tf_session.TF_SetXlaEnableLazyCompilation(old_value)\n return result\n else:\n return func(self, *args, **kwargs)\n\n return decorated\n\n if func is not None:\n return decorator(func)\n\n return decorator\n\n return xla_allow_fallback_impl\n\n\n# The description is just for documentation purposes.\ndef run_without_tensor_float_32(description): # pylint: disable=unused-argument\n \"\"\"Execute test with TensorFloat-32 disabled.\n\n While almost every real-world deep learning model runs fine with\n TensorFloat-32, many tests use assertAllClose or similar methods.\n TensorFloat-32 matmuls typically will cause such methods to fail with the\n default tolerances.\n\n Args:\n description: A description used for documentation purposes, describing why\n the test requires TensorFloat-32 to be disabled.\n\n Returns:\n Decorator which runs a test with TensorFloat-32 disabled.\n \"\"\"\n\n def decorator(f):\n\n @functools.wraps(f)\n def decorated(self, *args, **kwargs):\n allowed = config.tensor_float_32_execution_enabled()\n try:\n config.enable_tensor_float_32_execution(False)\n f(self, *args, **kwargs)\n finally:\n config.enable_tensor_float_32_execution(allowed)\n\n return decorated\n\n return decorator\n\n\n# The description is just for documentation purposes.\ndef run_all_without_tensor_float_32(description): # pylint: disable=unused-argument\n \"\"\"Execute all tests in a class with TensorFloat-32 disabled.\"\"\"\n return for_all_test_methods(run_without_tensor_float_32, description)\n\n\ndef matmul_without_tf32(a, b, *args, **kwargs):\n \"\"\"Run matmul but cast float32 inputs to float64 if TensorFloat-32 is enabled.\n\n This effectively runs matmul without TensorFloat-32. It should only be used in\n tests when verifying some other op or functions works correctly, e.g. to test\n `tf.linalg.sqrtm` by matrix multiplying the output of the op by itself. In\n such cases, the matmul itself is not being tested so it's OK to run it with\n higher precision.\n\n If a matmul itself is being tested, or some other op which uses matmul, use\n `run_without_tensor_float_32` instead.\n\n This also casts complex64 inputs to complex128, since TensorFloat-32 can also\n be used with complex64\n\n Args:\n a: First input to tf.linalg.matmul\n b: Second input to tf.linalg.matmul\n args: Other positional arguments to tf.linalg.matmul\n **kwargs: Other keyword arguments to tf.linalg.matmul\n\n Returns:\n A tensor with the same type as `a`.\n \"\"\"\n if config.tensor_float_32_execution_enabled() and a.dtype == \"float32\":\n a = math_ops.cast(a, \"float64\")\n b = math_ops.cast(b, \"float64\")\n ret = math_ops.matmul(a, b, *args, **kwargs)\n return math_ops.cast(ret, a.dtype)\n elif config.tensor_float_32_execution_enabled() and a.dtype == \"complex64\":\n a = math_ops.cast(a, \"complex128\")\n b = math_ops.cast(b, \"complex128\")\n ret = math_ops.matmul(a, b, *args, **kwargs)\n return math_ops.cast(ret, a.dtype)\n else:\n return math_ops.matmul(a, b, *args, **kwargs)\n\n\nclass EagerSessionWarner(object):\n\n def __getattr__(self, attr):\n raise AttributeError(\n \"Trying to access properties or call methods on the result of \"\n \"self.session(), self.cached_session(), etc while eager execution \"\n \"is enabled. If you're porting this test case to TF 2.0, either \"\n \"adapt the test to work with eager execution or insert a call to \"\n \"tf.disable_eager_execution() in the main() function of this test \"\n \"file.\")\n\n\n@tf_export(\"test.TestCase\")\nclass TensorFlowTestCase(googletest.TestCase):\n \"\"\"Base class for tests that need to test TensorFlow.\"\"\"\n\n def __init__(self, methodName=\"runTest\"): # pylint: disable=invalid-name\n super(TensorFlowTestCase, self).__init__(methodName)\n if is_xla_enabled():\n pywrap_tf_session.TF_SetXlaAutoJitMode(\"2\")\n pywrap_tf_session.TF_SetXlaMinClusterSize(1)\n pywrap_tf_session.TF_SetXlaEnableLazyCompilation(False)\n pywrap_tf_session.TF_SetTfXlaCpuGlobalJit(True)\n # Constant folding secretly runs code on TF:Classic CPU, so we also\n # disable it here.\n pywrap_tf_session.TF_SetXlaConstantFoldingDisabled(True)\n\n # Check if the mlir bridge has been explicitly enabled or disabled. If\n # is_mlir_bridge_enabled() returns None, the user did not explictly enable\n # or disable the bridge so do not update enable_mlir_bridge.\n if is_mlir_bridge_enabled():\n context.context().enable_mlir_bridge = True\n elif is_mlir_bridge_enabled() is not None:\n context.context().enable_mlir_bridge = False\n\n self._threads = []\n self._tempdir = None\n self._cached_session = None\n self._test_start_time = None\n # This flag provides the ability to control whether the graph mode gets\n # initialized for TF1 or not. Initializing for TF1, which is what was\n # happening earlier, was preventing enablement of 'eager mode' in the test.\n self._set_default_seed = True\n\n def setUp(self):\n super(TensorFlowTestCase, self).setUp()\n self._ClearCachedSession()\n random.seed(random_seed.DEFAULT_GRAPH_SEED)\n np.random.seed(random_seed.DEFAULT_GRAPH_SEED)\n # Note: The following line is necessary because some test methods may error\n # out from within nested graph contexts (e.g., via assertRaises and\n # assertRaisesRegexp), which may leave ops._default_graph_stack non-empty\n # under certain versions of Python. That would cause\n # ops.reset_default_graph() to throw an exception if the stack were not\n # cleared first.\n ops._default_graph_stack.reset() # pylint: disable=protected-access\n ops.reset_default_graph()\n if self._set_default_seed:\n random_seed.set_random_seed(random_seed.DEFAULT_GRAPH_SEED)\n # Reset summary writer in case another test used set_as_default() with their\n # summary writer.\n summary_state = summary_ops_v2._summary_state # pylint: disable=protected-access\n summary_state.writer = None\n\n # Avoiding calling setUp() for the poorly named test_session method.\n if self.id().endswith(\".test_session\"):\n self.skipTest(\"Not a test.\")\n\n self._test_start_time = time.time()\n\n def tearDown(self):\n # If a subclass overrides setUp and doesn't call the parent class's setUp,\n # then we may not have set the start time.\n if self._test_start_time is not None:\n logging.info(\"time(%s): %ss\", self.id(),\n round(time.time() - self._test_start_time, 2))\n\n for thread in self._threads:\n thread.check_termination()\n\n self._ClearCachedSession()\n super(TensorFlowTestCase, self).tearDown()\n\n def _ClearCachedSession(self):\n if self._cached_session is not None:\n self._cached_session.close()\n self._cached_session = None\n\n def get_temp_dir(self):\n \"\"\"Returns a unique temporary directory for the test to use.\n\n If you call this method multiple times during in a test, it will return the\n same folder. However, across different runs the directories will be\n different. This will ensure that across different runs tests will not be\n able to pollute each others environment.\n If you need multiple unique directories within a single test, you should\n use tempfile.mkdtemp as follows:\n tempfile.mkdtemp(dir=self.get_temp_dir()):\n\n Returns:\n string, the path to the unique temporary directory created for this test.\n \"\"\"\n if not self._tempdir:\n self._tempdir = tempfile.mkdtemp(dir=googletest.GetTempDir())\n return self._tempdir\n\n @contextlib.contextmanager\n def captureWritesToStream(self, stream):\n \"\"\"A context manager that captures the writes to a given stream.\n\n This context manager captures all writes to a given stream inside of a\n `CapturedWrites` object. When this context manager is created, it yields\n the `CapturedWrites` object. The captured contents can be accessed by\n calling `.contents()` on the `CapturedWrites`.\n\n For this function to work, the stream must have a file descriptor that\n can be modified using `os.dup` and `os.dup2`, and the stream must support\n a `.flush()` method. The default python sys.stdout and sys.stderr are\n examples of this. Note that this does not work in Colab or Jupyter\n notebooks, because those use alternate stdout streams.\n\n Example:\n ```python\n class MyOperatorTest(test_util.TensorFlowTestCase):\n def testMyOperator(self):\n input = [1.0, 2.0, 3.0, 4.0, 5.0]\n with self.captureWritesToStream(sys.stdout) as captured:\n result = MyOperator(input).eval()\n self.assertStartsWith(captured.contents(), \"This was printed.\")\n ```\n\n Args:\n stream: The stream whose writes should be captured. This stream must have\n a file descriptor, support writing via using that file descriptor, and\n must have a `.flush()` method.\n\n Yields:\n A `CapturedWrites` object that contains all writes to the specified stream\n made during this context.\n \"\"\"\n stream.flush()\n fd = stream.fileno()\n tmp_file_path = tempfile.mktemp(dir=self.get_temp_dir())\n tmp_file = open(tmp_file_path, \"w\")\n orig_fd = os.dup(fd)\n os.dup2(tmp_file.fileno(), fd)\n try:\n yield CapturedWrites(tmp_file_path)\n finally:\n tmp_file.close()\n os.dup2(orig_fd, fd)\n\n def _AssertProtoEquals(self, a, b, msg=None):\n \"\"\"Asserts that a and b are the same proto.\n\n Uses ProtoEq() first, as it returns correct results\n for floating point attributes, and then use assertProtoEqual()\n in case of failure as it provides good error messages.\n\n Args:\n a: a proto.\n b: another proto.\n msg: Optional message to report on failure.\n \"\"\"\n if not compare.ProtoEq(a, b):\n compare.assertProtoEqual(self, a, b, normalize_numbers=True, msg=msg)\n\n def assertProtoEquals(self, expected_message_maybe_ascii, message, msg=None):\n \"\"\"Asserts that message is same as parsed expected_message_ascii.\n\n Creates another prototype of message, reads the ascii message into it and\n then compares them using self._AssertProtoEqual().\n\n Args:\n expected_message_maybe_ascii: proto message in original or ascii form.\n message: the message to validate.\n msg: Optional message to report on failure.\n \"\"\"\n if isinstance(expected_message_maybe_ascii, type(message)):\n expected_message = expected_message_maybe_ascii\n self._AssertProtoEquals(expected_message, message, msg=msg)\n elif isinstance(expected_message_maybe_ascii, (str, bytes)):\n expected_message = type(message)()\n text_format.Merge(\n expected_message_maybe_ascii,\n expected_message,\n descriptor_pool=descriptor_pool.Default())\n self._AssertProtoEquals(expected_message, message, msg=msg)\n else:\n assert False, (\"Can't compare protos of type %s and %s.\" %\n (type(expected_message_maybe_ascii), type(message)))\n\n def assertProtoEqualsVersion(\n self,\n expected,\n actual,\n producer=versions.GRAPH_DEF_VERSION,\n min_consumer=versions.GRAPH_DEF_VERSION_MIN_CONSUMER,\n msg=None):\n expected = \"versions { producer: %d min_consumer: %d };\\n%s\" % (\n producer, min_consumer, expected)\n self.assertProtoEquals(expected, actual, msg=msg)\n\n def assertStartsWith(self, actual, expected_start, msg=None):\n \"\"\"Assert that actual.startswith(expected_start) is True.\n\n Args:\n actual: str\n expected_start: str\n msg: Optional message to report on failure.\n \"\"\"\n if not actual.startswith(expected_start):\n fail_msg = \"%r does not start with %r\" % (actual, expected_start)\n fail_msg += \" : %r\" % (msg) if msg else \"\"\n self.fail(fail_msg)\n\n def _eval_tensor(self, tensor):\n if tensor is None:\n return None\n elif callable(tensor):\n return self._eval_helper(tensor())\n else:\n try:\n if sparse_tensor.is_sparse(tensor):\n return sparse_tensor.SparseTensorValue(tensor.indices.numpy(),\n tensor.values.numpy(),\n tensor.dense_shape.numpy())\n elif ragged_tensor.is_ragged(tensor):\n return ragged_tensor_value.RaggedTensorValue(\n self._eval_tensor(tensor.values),\n self._eval_tensor(tensor.row_splits))\n elif isinstance(tensor, ops.IndexedSlices):\n return ops.IndexedSlicesValue(\n values=tensor.values.numpy(),\n indices=tensor.indices.numpy(),\n dense_shape=tensor.dense_shape.numpy())\n # Convert tensors and composite tensors to numpy arrays.\n return nest.map_structure(lambda t: t.numpy(), tensor,\n expand_composites=True)\n except AttributeError as e:\n six.raise_from(ValueError(\"Unsupported type %s.\" % type(tensor)), e)\n\n def _eval_helper(self, tensors):\n if tensors is None:\n return None\n return nest.map_structure(self._eval_tensor, tensors)\n\n def evaluate(self, tensors):\n \"\"\"Evaluates tensors and returns numpy values.\n\n Args:\n tensors: A Tensor or a nested list/tuple of Tensors.\n\n Returns:\n tensors numpy values.\n \"\"\"\n if context.executing_eagerly():\n return self._eval_helper(tensors)\n else:\n sess = ops.get_default_session()\n if sess is None:\n with self.test_session() as sess:\n return sess.run(tensors)\n else:\n return sess.run(tensors)\n\n # pylint: disable=g-doc-return-or-yield\n @contextlib.contextmanager\n def session(self, graph=None, config=None, use_gpu=True, force_gpu=False):\n \"\"\"A context manager for a TensorFlow Session for use in executing tests.\n\n Note that this will set this session and the graph as global defaults.\n\n Use the `use_gpu` and `force_gpu` options to control where ops are run. If\n `force_gpu` is True, all ops are pinned to `/device:GPU:0`. Otherwise, if\n `use_gpu` is True, TensorFlow tries to run as many ops on the GPU as\n possible. If both `force_gpu and `use_gpu` are False, all ops are pinned to\n the CPU.\n\n Example:\n\n ``` python\n class MyOperatorTest(test_util.TensorFlowTestCase):\n def testMyOperator(self):\n with self.session():\n valid_input = [1.0, 2.0, 3.0, 4.0, 5.0]\n result = MyOperator(valid_input).eval()\n self.assertEqual(result, [1.0, 2.0, 3.0, 5.0, 8.0]\n invalid_input = [-1.0, 2.0, 7.0]\n with self.assertRaisesOpError(\"negative input not supported\"):\n MyOperator(invalid_input).eval()\n ```\n\n Args:\n graph: Optional graph to use during the returned session.\n config: An optional config_pb2.ConfigProto to use to configure the\n session.\n use_gpu: If True, attempt to run as many ops as possible on GPU.\n force_gpu: If True, pin all ops to `/device:GPU:0`.\n\n Yields:\n A Session object that should be used as a context manager to surround\n the graph building and execution code in a test case.\n \"\"\"\n if context.executing_eagerly():\n yield EagerSessionWarner()\n else:\n with self._create_session(graph, config, force_gpu) as sess:\n with self._constrain_devices_and_set_default(sess, use_gpu, force_gpu):\n yield sess\n\n @contextlib.contextmanager\n def cached_session(self,\n graph=None,\n config=None,\n use_gpu=True,\n force_gpu=False):\n \"\"\"Returns a TensorFlow Session for use in executing tests.\n\n This method behaves differently than self.session(): for performance reasons\n `cached_session` will by default reuse the same session within the same\n test. The session returned by this function will only be closed at the end\n of the test (in the TearDown function).\n\n Use the `use_gpu` and `force_gpu` options to control where ops are run. If\n `force_gpu` is True, all ops are pinned to `/device:GPU:0`. Otherwise, if\n `use_gpu` is True, TensorFlow tries to run as many ops on the GPU as\n possible. If both `force_gpu and `use_gpu` are False, all ops are pinned to\n the CPU.\n\n Example:\n ```python\n class MyOperatorTest(test_util.TensorFlowTestCase):\n def testMyOperator(self):\n with self.cached_session() as sess:\n valid_input = [1.0, 2.0, 3.0, 4.0, 5.0]\n result = MyOperator(valid_input).eval()\n self.assertEqual(result, [1.0, 2.0, 3.0, 5.0, 8.0]\n invalid_input = [-1.0, 2.0, 7.0]\n with self.assertRaisesOpError(\"negative input not supported\"):\n MyOperator(invalid_input).eval()\n ```\n\n Args:\n graph: Optional graph to use during the returned session.\n config: An optional config_pb2.ConfigProto to use to configure the\n session.\n use_gpu: If True, attempt to run as many ops as possible on GPU.\n force_gpu: If True, pin all ops to `/device:GPU:0`.\n\n Yields:\n A Session object that should be used as a context manager to surround\n the graph building and execution code in a test case.\n \"\"\"\n if context.executing_eagerly():\n yield FakeEagerSession(self)\n else:\n sess = self._get_cached_session(\n graph, config, force_gpu, crash_if_inconsistent_args=True)\n with self._constrain_devices_and_set_default(sess, use_gpu,\n force_gpu) as cached:\n yield cached\n\n @contextlib.contextmanager\n @deprecation.deprecated(None, \"Use `self.session()` or \"\n \"`self.cached_session()` instead.\")\n def test_session(self,\n graph=None,\n config=None,\n use_gpu=True,\n force_gpu=False):\n \"\"\"Use cached_session instead.\"\"\"\n if self.id().endswith(\".test_session\"):\n self.skipTest(\n \"Tests that have the name \\\"test_session\\\" are automatically skipped \"\n \"by TensorFlow test fixture, as the name is reserved for creating \"\n \"sessions within tests. Please rename your test if you have a test \"\n \"with this name.\")\n if context.executing_eagerly():\n yield None\n else:\n if graph is None:\n sess = self._get_cached_session(\n graph, config, force_gpu, crash_if_inconsistent_args=False)\n with self._constrain_devices_and_set_default(sess, use_gpu,\n force_gpu) as cached:\n yield cached\n else:\n with self.session(graph, config, use_gpu, force_gpu) as sess:\n yield sess\n\n # pylint: enable=g-doc-return-or-yield\n\n class _CheckedThread(object):\n \"\"\"A wrapper class for Thread that asserts successful completion.\n\n This class should be created using the TensorFlowTestCase.checkedThread()\n method.\n \"\"\"\n\n def __init__(self, testcase, target, args=None, kwargs=None):\n \"\"\"Constructs a new instance of _CheckedThread.\n\n Args:\n testcase: The TensorFlowTestCase for which this thread is being created.\n target: A callable object representing the code to be executed in the\n thread.\n args: A tuple of positional arguments that will be passed to target.\n kwargs: A dictionary of keyword arguments that will be passed to target.\n \"\"\"\n self._testcase = testcase\n self._target = target\n self._args = () if args is None else args\n self._kwargs = {} if kwargs is None else kwargs\n self._thread = threading.Thread(target=self._protected_run)\n self._exception = None\n\n self._is_thread_joined = False\n\n def _protected_run(self):\n \"\"\"Target for the wrapper thread. Sets self._exception on failure.\"\"\"\n try:\n self._target(*self._args, **self._kwargs)\n except Exception as e: # pylint: disable=broad-except\n self._exception = e\n\n def start(self):\n \"\"\"Starts the thread's activity.\n\n This must be called at most once per _CheckedThread object. It arranges\n for the object's target to be invoked in a separate thread of control.\n \"\"\"\n self._thread.start()\n\n def join(self):\n \"\"\"Blocks until the thread terminates.\n\n Raises:\n self._testcase.failureException: If the thread terminates with due to\n an exception.\n \"\"\"\n self._is_thread_joined = True\n self._thread.join()\n if self._exception is not None:\n self._testcase.fail(\"Error in checkedThread: %s\" % str(self._exception))\n\n def is_alive(self):\n \"\"\"Returns whether the thread is alive.\n\n This method returns True just before the run() method starts\n until just after the run() method terminates.\n\n Returns:\n True if the thread is alive, otherwise False.\n \"\"\"\n return self._thread.is_alive()\n\n def check_termination(self):\n \"\"\"Returns whether the checked thread was properly used and did terminate.\n\n Every checked thread should be \"join\"ed after starting, and before the\n test tears down. If it is not joined, it is possible the thread will hang\n and cause flaky failures in tests.\n\n Raises:\n self._testcase.failureException: If check_termination was called before\n thread was joined.\n\n RuntimeError: If the thread is not terminated. This means thread was not\n joined with the main thread.\n \"\"\"\n if self._is_thread_joined:\n if self.is_alive():\n raise RuntimeError(\n \"Thread was not joined with main thread, and is still running \"\n \"when the test finished.\")\n else:\n self._testcase.fail(\"A checked thread was not joined.\")\n\n def checkedThread(self, target, args=None, kwargs=None):\n \"\"\"Returns a Thread wrapper that asserts 'target' completes successfully.\n\n This method should be used to create all threads in test cases, as\n otherwise there is a risk that a thread will silently fail, and/or\n assertions made in the thread will not be respected.\n\n Args:\n target: A callable object to be executed in the thread.\n args: The argument tuple for the target invocation. Defaults to ().\n kwargs: A dictionary of keyword arguments for the target invocation.\n Defaults to {}.\n\n Returns:\n A wrapper for threading.Thread that supports start() and join() methods.\n \"\"\"\n ret = TensorFlowTestCase._CheckedThread(self, target, args, kwargs)\n self._threads.append(ret)\n return ret\n\n # pylint: enable=invalid-name\n @py_func_if_in_function\n def assertNear(self, f1, f2, err, msg=None):\n \"\"\"Asserts that two floats are near each other.\n\n Checks that |f1 - f2| < err and asserts a test failure\n if not.\n\n Args:\n f1: A float value.\n f2: A float value.\n err: A float value.\n msg: An optional string message to append to the failure message.\n \"\"\"\n # f1 == f2 is needed here as we might have: f1, f2 = inf, inf\n self.assertTrue(\n f1 == f2 or math.fabs(f1 - f2) <= err, \"%f != %f +/- %f%s\" %\n (f1, f2, err, \" (%s)\" % msg if msg is not None else \"\"))\n\n @py_func_if_in_function\n def assertArrayNear(self, farray1, farray2, err, msg=None):\n \"\"\"Asserts that two float arrays are near each other.\n\n Checks that for all elements of farray1 and farray2\n |f1 - f2| < err. Asserts a test failure if not.\n\n Args:\n farray1: a list of float values.\n farray2: a list of float values.\n err: a float value.\n msg: Optional message to report on failure.\n \"\"\"\n self.assertEqual(len(farray1), len(farray2), msg=msg)\n for f1, f2 in zip(farray1, farray2):\n self.assertNear(float(f1), float(f2), err, msg=msg)\n\n def _NDArrayNear(self, ndarray1, ndarray2, err):\n return np.linalg.norm(ndarray1 - ndarray2) < err\n\n @py_func_if_in_function\n def assertNDArrayNear(self, ndarray1, ndarray2, err, msg=None):\n \"\"\"Asserts that two numpy arrays have near values.\n\n Args:\n ndarray1: a numpy ndarray.\n ndarray2: a numpy ndarray.\n err: a float. The maximum absolute difference allowed.\n msg: Optional message to report on failure.\n \"\"\"\n self.assertTrue(self._NDArrayNear(ndarray1, ndarray2, err), msg=msg)\n\n def _GetNdArray(self, a):\n # If a is tensor-like then convert it to ndarray\n if tensor_util.is_tf_type(a):\n if isinstance(a, ops._EagerTensorBase):\n a = a.numpy()\n else:\n a = self.evaluate(a)\n if not isinstance(a, np.ndarray):\n return np.array(a)\n return a\n\n def _assertArrayLikeAllClose(self, a, b, rtol=1e-6, atol=1e-6, msg=None):\n a = self._GetNdArray(a)\n b = self._GetNdArray(b)\n # When the array rank is small, print its contents. Numpy array printing is\n # implemented using inefficient recursion so prints can cause tests to\n # time out.\n if a.shape != b.shape and (b.ndim <= 3 or b.size < 500):\n shape_mismatch_msg = (\"Shape mismatch: expected %s, got %s with contents \"\n \"%s.\") % (a.shape, b.shape, b)\n else:\n shape_mismatch_msg = \"Shape mismatch: expected %s, got %s.\" % (a.shape,\n b.shape)\n self.assertEqual(a.shape, b.shape, shape_mismatch_msg)\n\n msgs = [msg]\n # np.allclose does not always work for our custom bfloat16 extension type\n # when type promotions are involved, so we first cast any bfloat16 arrays\n # to float32.\n a_dtype = a.dtype\n a = a.astype(np.float32) if a.dtype == dtypes.bfloat16.as_numpy_dtype else a\n b = b.astype(np.float32) if b.dtype == dtypes.bfloat16.as_numpy_dtype else b\n if not np.allclose(a, b, rtol=rtol, atol=atol):\n # Adds more details to np.testing.assert_allclose.\n #\n # NOTE: numpy.allclose (and numpy.testing.assert_allclose)\n # checks whether two arrays are element-wise equal within a\n # tolerance. The relative difference (rtol * abs(b)) and the\n # absolute difference atol are added together to compare against\n # the absolute difference between a and b. Here, we want to\n # tell user which elements violate such conditions.\n cond = np.logical_or(\n np.abs(a - b) > atol + rtol * np.abs(b),\n np.isnan(a) != np.isnan(b))\n if a.ndim:\n x = a[np.where(cond)]\n y = b[np.where(cond)]\n msgs.append(\"not close where = {}\".format(np.where(cond)))\n else:\n # np.where is broken for scalars\n x, y = a, b\n msgs.append(\"not close lhs = {}\".format(x))\n msgs.append(\"not close rhs = {}\".format(y))\n msgs.append(\"not close dif = {}\".format(np.abs(x - y)))\n msgs.append(\"not close tol = {}\".format(atol + rtol * np.abs(y)))\n msgs.append(\"dtype = {}, shape = {}\".format(a_dtype, a.shape))\n # TODO(xpan): There seems to be a bug:\n # tensorflow/compiler/tests:binary_ops_test pass with float32\n # nan even though the equal_nan is False by default internally.\n np.testing.assert_allclose(\n a, b, rtol=rtol, atol=atol, err_msg=\"\\n\".join(msgs), equal_nan=True)\n\n def _assertAllCloseRecursive(self,\n a,\n b,\n rtol=1e-6,\n atol=1e-6,\n path=None,\n msg=None):\n path = path or []\n path_str = ((\"[\" + \"][\".join(str(p) for p in path) + \"]\") if path else \"\")\n msg = msg if msg else \"\"\n\n # Check if a and/or b are namedtuples.\n if hasattr(a, \"_asdict\"):\n a = a._asdict()\n if hasattr(b, \"_asdict\"):\n b = b._asdict()\n a_is_dict = isinstance(a, collections_abc.Mapping)\n if a_is_dict != isinstance(b, collections_abc.Mapping):\n raise ValueError(\"Can't compare dict to non-dict, a%s vs b%s. %s\" %\n (path_str, path_str, msg))\n if a_is_dict:\n self.assertItemsEqual(\n a.keys(),\n b.keys(),\n msg=\"mismatched keys: a%s has keys %s, but b%s has keys %s. %s\" %\n (path_str, a.keys(), path_str, b.keys(), msg))\n for k in a:\n path.append(k)\n self._assertAllCloseRecursive(\n a[k], b[k], rtol=rtol, atol=atol, path=path, msg=msg)\n del path[-1]\n elif isinstance(a, (list, tuple)):\n # Try to directly compare a, b as ndarrays; if not work, then traverse\n # through the sequence, which is more expensive.\n try:\n a_as_ndarray = self._GetNdArray(a)\n b_as_ndarray = self._GetNdArray(b)\n self._assertArrayLikeAllClose(\n a_as_ndarray,\n b_as_ndarray,\n rtol=rtol,\n atol=atol,\n msg=\"Mismatched value: a%s is different from b%s. %s\" %\n (path_str, path_str, msg))\n except (ValueError, TypeError) as e:\n if len(a) != len(b):\n raise ValueError(\n \"Mismatched length: a%s has %d items, but b%s has %d items. %s\" %\n (path_str, len(a), path_str, len(b), msg))\n for idx, (a_ele, b_ele) in enumerate(zip(a, b)):\n path.append(str(idx))\n self._assertAllCloseRecursive(\n a_ele, b_ele, rtol=rtol, atol=atol, path=path, msg=msg)\n del path[-1]\n # a and b are ndarray like objects\n else:\n try:\n self._assertArrayLikeAllClose(\n a,\n b,\n rtol=rtol,\n atol=atol,\n msg=(\"Mismatched value: a%s is different from b%s. %s\" %\n (path_str, path_str, msg)))\n except TypeError as e:\n msg = (\"Error: a%s has %s, but b%s has %s. %s\" %\n (path_str, type(a), path_str, type(b), msg))\n e.args = ((e.args[0] + \" : \" + msg,) + e.args[1:])\n raise\n\n @py_func_if_in_function\n def assertAllClose(self, a, b, rtol=1e-6, atol=1e-6, msg=None):\n \"\"\"Asserts that two structures of numpy arrays or Tensors, have near values.\n\n `a` and `b` can be arbitrarily nested structures. A layer of a nested\n structure can be a `dict`, `namedtuple`, `tuple` or `list`.\n\n Note: the implementation follows\n [`numpy.allclose`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.allclose.html)\n (and numpy.testing.assert_allclose). It checks whether two arrays are\n element-wise equal within a tolerance. The relative difference\n (`rtol * abs(b)`) and the absolute difference `atol` are added together\n to compare against the absolute difference between `a` and `b`.\n\n Args:\n a: The expected numpy `ndarray`, or anything that can be converted into a\n numpy `ndarray` (including Tensor), or any arbitrarily nested of\n structure of these.\n b: The actual numpy `ndarray`, or anything that can be converted into a\n numpy `ndarray` (including Tensor), or any arbitrarily nested of\n structure of these.\n rtol: relative tolerance.\n atol: absolute tolerance.\n msg: Optional message to report on failure.\n\n Raises:\n ValueError: if only one of `a[p]` and `b[p]` is a dict or\n `a[p]` and `b[p]` have different length, where `[p]` denotes a path\n to the nested structure, e.g. given `a = [(1, 1), {'d': (6, 7)}]` and\n `[p] = [1]['d']`, then `a[p] = (6, 7)`.\n \"\"\"\n if ragged_tensor.is_ragged(a) or ragged_tensor.is_ragged(b):\n return self._assertRaggedClose(a, b, rtol, atol, msg)\n self._assertAllCloseRecursive(a, b, rtol=rtol, atol=atol, msg=msg)\n\n @py_func_if_in_function\n def assertAllCloseAccordingToType(self,\n a,\n b,\n rtol=1e-6,\n atol=1e-6,\n float_rtol=1e-6,\n float_atol=1e-6,\n half_rtol=1e-3,\n half_atol=1e-3,\n bfloat16_rtol=1e-2,\n bfloat16_atol=1e-2,\n msg=None):\n \"\"\"Like assertAllClose, but also suitable for comparing fp16 arrays.\n\n In particular, the tolerance is reduced to 1e-3 if at least\n one of the arguments is of type float16.\n\n Args:\n a: the expected numpy ndarray or anything can be converted to one.\n b: the actual numpy ndarray or anything can be converted to one.\n rtol: relative tolerance.\n atol: absolute tolerance.\n float_rtol: relative tolerance for float32.\n float_atol: absolute tolerance for float32.\n half_rtol: relative tolerance for float16.\n half_atol: absolute tolerance for float16.\n bfloat16_rtol: relative tolerance for bfloat16.\n bfloat16_atol: absolute tolerance for bfloat16.\n msg: Optional message to report on failure.\n \"\"\"\n a = self._GetNdArray(a)\n b = self._GetNdArray(b)\n # types with lower tol are put later to overwrite previous ones.\n if (a.dtype == np.float32 or b.dtype == np.float32 or\n a.dtype == np.complex64 or b.dtype == np.complex64):\n rtol = max(rtol, float_rtol)\n atol = max(atol, float_atol)\n if a.dtype == np.float16 or b.dtype == np.float16:\n rtol = max(rtol, half_rtol)\n atol = max(atol, half_atol)\n if (a.dtype == dtypes.bfloat16.as_numpy_dtype or\n b.dtype == dtypes.bfloat16.as_numpy_dtype):\n rtol = max(rtol, bfloat16_rtol)\n atol = max(atol, bfloat16_atol)\n\n self.assertAllClose(a, b, rtol=rtol, atol=atol, msg=msg)\n\n @py_func_if_in_function\n def assertNotAllClose(self, a, b, rtol=1e-6, atol=1e-6, msg=None):\n \"\"\"Assert that two numpy arrays, or Tensors, do not have near values.\n\n Args:\n a: The expected numpy `ndarray`, or anything that can be converted into a\n numpy `ndarray` (including Tensor), or any arbitrarily nested of\n structure of these.\n b: The actual numpy `ndarray`, or anything that can be converted into a\n numpy `ndarray` (including Tensor), or any arbitrarily nested of\n structure of these.\n rtol: relative tolerance.\n atol: absolute tolerance.\n msg: Optional message to report on failure.\n\n Raises:\n AssertionError: If `a` and `b` are unexpectedly close at all elements.\n \"\"\"\n try:\n self.assertAllClose(a, b, rtol=rtol, atol=atol, msg=msg)\n except AssertionError:\n return\n msg = msg or \"\"\n raise AssertionError(\"The two values are close at all elements. %s\" % msg)\n\n @py_func_if_in_function\n def assertAllEqual(self, a, b, msg=None):\n \"\"\"Asserts that two numpy arrays or Tensors have the same values.\n\n Args:\n a: the expected numpy ndarray or anything can be converted to one.\n b: the actual numpy ndarray or anything can be converted to one.\n msg: Optional message to report on failure.\n \"\"\"\n if (ragged_tensor.is_ragged(a) or ragged_tensor.is_ragged(b)):\n return self._assertRaggedEqual(a, b, msg)\n msg = msg if msg else \"\"\n a = self._GetNdArray(a)\n b = self._GetNdArray(b)\n # Arbitrary bounds so that we don't print giant tensors.\n if (b.ndim <= 3 or b.size < 500):\n self.assertEqual(\n a.shape, b.shape, \"Shape mismatch: expected %s, got %s.\"\n \" Contents: %r. \\n%s.\" % (a.shape, b.shape, b, msg))\n else:\n self.assertEqual(\n a.shape, b.shape, \"Shape mismatch: expected %s, got %s.\"\n \" %s\" % (a.shape, b.shape, msg))\n\n same = (a == b)\n\n if (a.dtype in [\n np.float16, np.float32, np.float64, dtypes.bfloat16.as_numpy_dtype\n ]):\n same = np.logical_or(same, np.logical_and(np.isnan(a), np.isnan(b)))\n msgs = [msg]\n if not np.all(same):\n # Adds more details to np.testing.assert_array_equal.\n diff = np.logical_not(same)\n if a.ndim:\n x = a[np.where(diff)]\n y = b[np.where(diff)]\n msgs.append(\"not equal where = {}\".format(np.where(diff)))\n else:\n # np.where is broken for scalars\n x, y = a, b\n msgs.append(\"not equal lhs = %r\" % x)\n msgs.append(\"not equal rhs = %r\" % y)\n\n # Handle mixed string types as a result of PY2to3 migration. That is, the\n # mixing between bytes (b-prefix strings, PY2 default) and unicodes\n # (u-prefix strings, PY3 default).\n if six.PY3:\n if (a.dtype.kind != b.dtype.kind and\n {a.dtype.kind, b.dtype.kind}.issubset({\"U\", \"S\", \"O\"})):\n a_list = []\n b_list = []\n # OK to flatten `a` and `b` because they are guaranteed to have the\n # same shape.\n for out_list, flat_arr in [(a_list, a.flat), (b_list, b.flat)]:\n for item in flat_arr:\n if isinstance(item, str):\n out_list.append(item.encode(\"utf-8\"))\n else:\n out_list.append(item)\n a = np.array(a_list)\n b = np.array(b_list)\n\n np.testing.assert_array_equal(a, b, err_msg=\"\\n\".join(msgs))\n\n @py_func_if_in_function\n def assertNotAllEqual(self, a, b, msg=None):\n \"\"\"Asserts that two numpy arrays or Tensors do not have the same values.\n\n Args:\n a: the expected numpy ndarray or anything can be converted to one.\n b: the actual numpy ndarray or anything can be converted to one.\n msg: Optional message to report on failure.\n \"\"\"\n try:\n self.assertAllEqual(a, b)\n except AssertionError:\n return\n raise AssertionError(\"The two values are equal at all elements. %s\" % msg)\n\n @py_func_if_in_function\n def assertAllGreater(self, a, comparison_target):\n \"\"\"Assert element values are all greater than a target value.\n\n Args:\n a: The numpy `ndarray`, or anything that can be converted into a numpy\n `ndarray` (including Tensor).\n comparison_target: The target value of comparison.\n \"\"\"\n a = self._GetNdArray(a)\n self.assertGreater(np.min(a), comparison_target)\n\n @py_func_if_in_function\n def assertAllLess(self, a, comparison_target):\n \"\"\"Assert element values are all less than a target value.\n\n Args:\n a: The numpy `ndarray`, or anything that can be converted into a numpy\n `ndarray` (including Tensor).\n comparison_target: The target value of comparison.\n \"\"\"\n a = self._GetNdArray(a)\n self.assertLess(np.max(a), comparison_target)\n\n @py_func_if_in_function\n def assertAllGreaterEqual(self, a, comparison_target):\n \"\"\"Assert element values are all greater than or equal to a target value.\n\n Args:\n a: The numpy `ndarray`, or anything that can be converted into a numpy\n `ndarray` (including Tensor).\n comparison_target: The target value of comparison.\n \"\"\"\n a = self._GetNdArray(a)\n self.assertGreaterEqual(np.min(a), comparison_target)\n\n @py_func_if_in_function\n def assertAllLessEqual(self, a, comparison_target):\n \"\"\"Assert element values are all less than or equal to a target value.\n\n Args:\n a: The numpy `ndarray`, or anything that can be converted into a numpy\n `ndarray` (including Tensor).\n comparison_target: The target value of comparison.\n \"\"\"\n a = self._GetNdArray(a)\n self.assertLessEqual(np.max(a), comparison_target)\n\n def _format_subscripts(self, subscripts, value, limit=10, indent=2):\n \"\"\"Generate a summary of ndarray subscripts as a list of str.\n\n If limit == N, this method will print up to the first N subscripts on\n separate\n lines. A line of ellipses (...) will be appended at the end if the number of\n subscripts exceeds N.\n\n Args:\n subscripts: The tensor (np.ndarray) subscripts, of the same format as\n np.where()'s return value, i.e., a tuple of arrays with each array\n corresponding to a dimension. E.g., (array([1, 1]), array([0, 1])).\n value: (np.ndarray) value of the tensor.\n limit: (int) The maximum number of indices to print.\n indent: (int) Number of characters to indent at the beginning of each\n line.\n\n Returns:\n (list of str) the multi-line representation of the subscripts and values,\n potentially with omission at the end.\n \"\"\"\n lines = []\n subscripts = np.transpose(subscripts)\n prefix = \" \" * indent\n if np.ndim(value) == 0:\n return [prefix + \"[0] : \" + str(value)]\n for subscript in itertools.islice(subscripts, limit):\n lines.append(prefix + str(subscript) + \" : \" +\n str(value[tuple(subscript)]))\n if len(subscripts) > limit:\n lines.append(prefix + \"...\")\n return lines\n\n @py_func_if_in_function\n def assertAllInRange(self,\n target,\n lower_bound,\n upper_bound,\n open_lower_bound=False,\n open_upper_bound=False):\n \"\"\"Assert that elements in a Tensor are all in a given range.\n\n Args:\n target: The numpy `ndarray`, or anything that can be converted into a\n numpy `ndarray` (including Tensor).\n lower_bound: lower bound of the range\n upper_bound: upper bound of the range\n open_lower_bound: (`bool`) whether the lower bound is open (i.e., > rather\n than the default >=)\n open_upper_bound: (`bool`) whether the upper bound is open (i.e., < rather\n than the default <=)\n\n Raises:\n AssertionError:\n if the value tensor does not have an ordered numeric type (float* or\n int*), or\n if there are nan values, or\n if any of the elements do not fall in the specified range.\n \"\"\"\n target = self._GetNdArray(target)\n if not (np.issubdtype(target.dtype, np.floating) or\n np.issubdtype(target.dtype, np.integer)):\n raise AssertionError(\n \"The value of %s does not have an ordered numeric type, instead it \"\n \"has type: %s\" % (target, target.dtype))\n\n nan_subscripts = np.where(np.isnan(target))\n if np.size(nan_subscripts):\n raise AssertionError(\n \"%d of the %d element(s) are NaN. \"\n \"Subscripts(s) and value(s) of the NaN element(s):\\n\" %\n (len(nan_subscripts[0]), np.size(target)) +\n \"\\n\".join(self._format_subscripts(nan_subscripts, target)))\n\n range_str = ((\"(\" if open_lower_bound else \"[\") + str(lower_bound) + \", \" +\n str(upper_bound) + (\")\" if open_upper_bound else \"]\"))\n\n violations = (\n np.less_equal(target, lower_bound) if open_lower_bound else np.less(\n target, lower_bound))\n violations = np.logical_or(\n violations,\n np.greater_equal(target, upper_bound)\n if open_upper_bound else np.greater(target, upper_bound))\n violation_subscripts = np.where(violations)\n if np.size(violation_subscripts):\n raise AssertionError(\n \"%d of the %d element(s) are outside the range %s. \" %\n (len(violation_subscripts[0]), np.size(target), range_str) +\n \"Subscript(s) and value(s) of the offending elements:\\n\" +\n \"\\n\".join(self._format_subscripts(violation_subscripts, target)))\n\n @py_func_if_in_function\n def assertAllInSet(self, target, expected_set):\n \"\"\"Assert that elements of a Tensor are all in a given closed set.\n\n Args:\n target: The numpy `ndarray`, or anything that can be converted into a\n numpy `ndarray` (including Tensor).\n expected_set: (`list`, `tuple` or `set`) The closed set that the elements\n of the value of `target` are expected to fall into.\n\n Raises:\n AssertionError:\n if any of the elements do not fall into `expected_set`.\n \"\"\"\n target = self._GetNdArray(target)\n\n # Elements in target that are not in expected_set.\n diff = np.setdiff1d(target.flatten(), list(expected_set))\n if np.size(diff):\n raise AssertionError(\"%d unique element(s) are not in the set %s: %s\" %\n (np.size(diff), expected_set, diff))\n\n @py_func_if_in_function\n def assertDTypeEqual(self, target, expected_dtype):\n \"\"\"Assert ndarray data type is equal to expected.\n\n Args:\n target: The numpy `ndarray`, or anything that can be converted into a\n numpy `ndarray` (including Tensor).\n expected_dtype: Expected data type.\n \"\"\"\n target = self._GetNdArray(target)\n if not isinstance(target, list):\n arrays = [target]\n for arr in arrays:\n self.assertEqual(arr.dtype, expected_dtype)\n\n # pylint: disable=g-doc-return-or-yield\n @contextlib.contextmanager\n def assertRaisesWithPredicateMatch(self, exception_type,\n expected_err_re_or_predicate):\n \"\"\"Returns a context manager to enclose code expected to raise an exception.\n\n If the exception is an OpError, the op stack is also included in the message\n predicate search.\n\n Args:\n exception_type: The expected type of exception that should be raised.\n expected_err_re_or_predicate: If this is callable, it should be a function\n of one argument that inspects the passed-in exception and returns True\n (success) or False (please fail the test). Otherwise, the error message\n is expected to match this regular expression partially.\n\n Returns:\n A context manager to surround code that is expected to raise an\n exception.\n \"\"\"\n if callable(expected_err_re_or_predicate):\n predicate = expected_err_re_or_predicate\n else:\n\n def predicate(e):\n err_str = e.message if isinstance(e, errors.OpError) else str(e)\n op = e.op if isinstance(e, errors.OpError) else None\n while op is not None:\n err_str += \"\\nCaused by: \" + op.name\n op = op._original_op # pylint: disable=protected-access\n logging.info(\"Searching within error strings: '%s' within '%s'\",\n expected_err_re_or_predicate, err_str)\n return re.search(expected_err_re_or_predicate, err_str)\n\n try:\n yield\n self.fail(exception_type.__name__ + \" not raised\")\n except Exception as e: # pylint: disable=broad-except\n if not isinstance(e, exception_type) or not predicate(e):\n raise AssertionError(\"Exception of type %s: %s\" %\n (str(type(e)), str(e)))\n\n # pylint: enable=g-doc-return-or-yield\n\n def assertRaisesOpError(self, expected_err_re_or_predicate):\n return self.assertRaisesWithPredicateMatch(errors.OpError,\n expected_err_re_or_predicate)\n\n def assertRaisesIncompatibleShapesError(\n self, exception_type=errors.InvalidArgumentError):\n return self.assertRaisesWithPredicateMatch(\n exception_type, r\"Incompatible shapes|Dimensions must be equal|\"\n r\"required broadcastable shapes\")\n\n def assertShapeEqual(self, np_array, tf_tensor, msg=None):\n \"\"\"Asserts that a Numpy ndarray and a TensorFlow tensor have the same shape.\n\n Args:\n np_array: A Numpy ndarray or Numpy scalar.\n tf_tensor: A Tensor.\n msg: Optional message to report on failure.\n\n Raises:\n TypeError: If the arguments have the wrong type.\n \"\"\"\n if not isinstance(np_array, (np.ndarray, np.generic)):\n raise TypeError(\"np_array must be a Numpy ndarray or Numpy scalar\")\n if not isinstance(tf_tensor, ops.Tensor):\n raise TypeError(\"tf_tensor must be a Tensor\")\n self.assertAllEqual(\n np_array.shape, tf_tensor.get_shape().as_list(), msg=msg)\n\n def assertDeviceEqual(self, device1, device2, msg=None):\n \"\"\"Asserts that the two given devices are the same.\n\n Args:\n device1: A string device name or TensorFlow `DeviceSpec` object.\n device2: A string device name or TensorFlow `DeviceSpec` object.\n msg: Optional message to report on failure.\n \"\"\"\n device1 = pydev.canonical_name(device1)\n device2 = pydev.canonical_name(device2)\n self.assertEqual(\n device1, device2,\n \"Devices %s and %s are not equal. %s\" % (device1, device2, msg))\n\n def _GetPyList(self, a):\n \"\"\"Converts `a` to a nested python list.\"\"\"\n if isinstance(a, ragged_tensor.RaggedTensor):\n return self.evaluate(a).to_list()\n elif isinstance(a, ops.Tensor):\n a = self.evaluate(a)\n return a.tolist() if isinstance(a, np.ndarray) else a\n elif isinstance(a, np.ndarray):\n return a.tolist()\n elif isinstance(a, ragged_tensor_value.RaggedTensorValue):\n return a.to_list()\n else:\n return np.array(a).tolist()\n\n def _assertRaggedEqual(self, a, b, msg):\n \"\"\"Asserts that two ragged tensors are equal.\"\"\"\n a_list = self._GetPyList(a)\n b_list = self._GetPyList(b)\n self.assertEqual(a_list, b_list, msg)\n\n if not (isinstance(a, (list, tuple)) or isinstance(b, (list, tuple))):\n a_ragged_rank = a.ragged_rank if ragged_tensor.is_ragged(a) else 0\n b_ragged_rank = b.ragged_rank if ragged_tensor.is_ragged(b) else 0\n self.assertEqual(a_ragged_rank, b_ragged_rank, msg)\n\n def _assertRaggedClose(self, a, b, rtol, atol, msg=None):\n a_list = self._GetPyList(a)\n b_list = self._GetPyList(b)\n self._assertListCloseRecursive(a_list, b_list, rtol, atol, msg)\n\n if not (isinstance(a, (list, tuple)) or isinstance(b, (list, tuple))):\n a_ragged_rank = a.ragged_rank if ragged_tensor.is_ragged(a) else 0\n b_ragged_rank = b.ragged_rank if ragged_tensor.is_ragged(b) else 0\n self.assertEqual(a_ragged_rank, b_ragged_rank, msg)\n\n def _assertListCloseRecursive(self, a, b, rtol, atol, msg, path=\"value\"):\n self.assertEqual(type(a), type(b))\n if isinstance(a, (list, tuple)):\n self.assertLen(a, len(b), \"Length differs for %s\" % path)\n for i in range(len(a)):\n self._assertListCloseRecursive(a[i], b[i], rtol, atol, msg,\n \"%s[%s]\" % (path, i))\n else:\n self._assertAllCloseRecursive(a, b, rtol, atol, path, msg)\n\n # Fix Python 3+ compatibility issues\n if not six.PY2:\n # pylint: disable=invalid-name\n\n # Silence a deprecation warning\n assertRaisesRegexp = googletest.TestCase.assertRaisesRegex\n\n # assertItemsEqual is assertCountEqual as of 3.2.\n assertItemsEqual = googletest.TestCase.assertCountEqual\n\n # pylint: enable=invalid-name\n\n @contextlib.contextmanager\n def _constrain_devices_and_set_default(self, sess, use_gpu, force_gpu):\n \"\"\"Set the session and its graph to global default and constrain devices.\"\"\"\n if context.executing_eagerly():\n yield None\n else:\n with sess.graph.as_default(), sess.as_default():\n if force_gpu:\n # Use the name of an actual device if one is detected, or\n # '/device:GPU:0' otherwise\n gpu_name = gpu_device_name()\n if not gpu_name:\n gpu_name = \"/device:GPU:0\"\n with sess.graph.device(gpu_name):\n yield sess\n elif use_gpu:\n yield sess\n else:\n with sess.graph.device(\"/device:CPU:0\"):\n yield sess\n\n def _create_session(self, graph, config, force_gpu):\n \"\"\"See session() for details.\"\"\"\n\n def prepare_config(config):\n \"\"\"Returns a config for sessions.\n\n Args:\n config: An optional config_pb2.ConfigProto to use to configure the\n session.\n\n Returns:\n A config_pb2.ConfigProto object.\n \"\"\"\n # TODO(b/114333779): Enforce allow_soft_placement=False when\n # use_gpu=False. Currently many tests rely on the fact that any device\n # will be used even when a specific device is supposed to be used.\n allow_soft_placement = not force_gpu\n if config is None:\n config = context.context().config\n config.allow_soft_placement = allow_soft_placement\n elif not allow_soft_placement and config.allow_soft_placement:\n config_copy = context.context().config\n config = config_copy\n config.allow_soft_placement = False\n # Don't perform optimizations for tests so we don't inadvertently run\n # gpu ops on cpu\n config.graph_options.optimizer_options.opt_level = -1\n # Disable Grappler constant folding since some tests & benchmarks\n # use constant input and become meaningless after constant folding.\n # DO NOT DISABLE GRAPPLER OPTIMIZERS WITHOUT CONSULTING WITH THE\n # GRAPPLER TEAM.\n config.graph_options.rewrite_options.constant_folding = (\n rewriter_config_pb2.RewriterConfig.OFF)\n config.graph_options.rewrite_options.pin_to_host_optimization = (\n rewriter_config_pb2.RewriterConfig.OFF)\n return config\n\n return ErrorLoggingSession(graph=graph, config=prepare_config(config))\n\n def _get_cached_session(self,\n graph=None,\n config=None,\n force_gpu=False,\n crash_if_inconsistent_args=True):\n \"\"\"See cached_session() for documentation.\"\"\"\n if self._cached_session is None:\n sess = self._create_session(\n graph=graph, config=config, force_gpu=force_gpu)\n self._cached_session = sess\n self._cached_graph = graph\n self._cached_config = config\n self._cached_force_gpu = force_gpu\n return sess\n else:\n if crash_if_inconsistent_args and self._cached_graph is not graph:\n raise ValueError(\"The graph used to get the cached session is \"\n \"different than the one that was used to create the \"\n \"session. Maybe create a new session with \"\n \"self.session()\")\n if crash_if_inconsistent_args and self._cached_config is not config:\n raise ValueError(\"The config used to get the cached session is \"\n \"different than the one that was used to create the \"\n \"session. Maybe create a new session with \"\n \"self.session()\")\n if crash_if_inconsistent_args and (self._cached_force_gpu is\n not force_gpu):\n raise ValueError(\n \"The force_gpu value used to get the cached session is \"\n \"different than the one that was used to create the \"\n \"session. Maybe create a new session with \"\n \"self.session()\")\n return self._cached_session\n\n\n@tf_export(\"test.create_local_cluster\")\ndef create_local_cluster(num_workers,\n num_ps,\n protocol=\"grpc\",\n worker_config=None,\n ps_config=None):\n \"\"\"Create and start local servers and return the associated `Server` objects.\n\n \"PS\" stands for \"parameter server\": a task responsible for storing and\n updating the model's parameters. Other tasks send updates to these parameters\n as they work on optimizing the parameters. This particular division of labor\n between tasks is not required, but is common for distributed training.\n\n Read more at https://www.tensorflow.org/guide/extend/architecture\n\n ![components](https://www.tensorflow.org/images/diag1.svg \"components\")\n\n\n Figure illustrates the interaction of these components.\n \"/job:worker/task:0\" and \"/job:ps/task:0\" are both tasks with worker services.\n\n\n Example:\n ```python\n workers, _ = tf.test.create_local_cluster(num_workers=2, num_ps=2)\n\n worker_sessions = [tf.compat.v1.Session(w.target) for w in workers]\n\n with tf.device(\"/job:ps/task:0\"):\n ...\n with tf.device(\"/job:ps/task:1\"):\n ...\n with tf.device(\"/job:worker/task:0\"):\n ...\n with tf.device(\"/job:worker/task:1\"):\n ...\n\n worker_sessions[0].run(...)\n ```\n\n Args:\n num_workers: Number of worker servers to start.\n num_ps: Number of PS servers to start.\n protocol: Communication protocol. Allowed values are documented in the\n documentation of `tf.distribute.Server`.\n worker_config: (optional) `tf.ConfigProto` to initialize workers. Can be\n used to instantiate multiple devices etc.\n ps_config: (optional) `tf.ConfigProto` to initialize PS servers.\n\n Returns:\n A tuple `(worker_servers, ps_servers)`. `worker_servers` is a list\n of `num_workers` objects of type `tf.distribute.Server` (all running\n locally);\n and `ps_servers` is a list of `num_ps` objects of similar type.\n\n Raises:\n ImportError: if portpicker module was not found at load time\n \"\"\"\n import portpicker # pylint: disable=g-import-not-at-top\n worker_ports = [portpicker.pick_unused_port() for _ in range(num_workers)]\n ps_ports = [portpicker.pick_unused_port() for _ in range(num_ps)]\n cluster_dict = {\n \"worker\": [\"localhost:%s\" % port for port in worker_ports],\n \"ps\": [\"localhost:%s\" % port for port in ps_ports]\n }\n cs = server_lib.ClusterSpec(cluster_dict)\n\n workers = [\n server_lib.Server(\n cs,\n job_name=\"worker\",\n protocol=protocol,\n task_index=ix,\n config=worker_config,\n start=True) for ix in range(num_workers)\n ]\n ps_servers = [\n server_lib.Server(\n cs,\n job_name=\"ps\",\n protocol=protocol,\n task_index=ix,\n config=ps_config,\n start=True) for ix in range(num_ps)\n ]\n\n return workers, ps_servers\n\n\ndef get_node_def_from_graph(node_name, graph_def):\n \"\"\"Returns the `NodeDef` instance for given node name in the graph def.\n\n This method explores only the NodeDefs in `graph_def.node`.\n\n Args:\n node_name: Name of the NodeDef to search for.\n graph_def: An instance of `GraphDef` proto.\n\n Returns:\n the `NodeDef` instance whose name field matches the given node_name or None.\n \"\"\"\n for node_def in graph_def.node:\n if node_def.name == node_name:\n return node_def\n return None\n\n\ndef set_producer_version(graph, producer_version):\n \"\"\"Sets graph.graph_def_versions.producer to `producer_version`.\"\"\"\n # The C API doesn't expose altering GraphDefVersions. We can indirectly set\n # it via import_graph_def though.\n graph_def = graph_pb2.GraphDef()\n graph_def.versions.producer = producer_version\n with graph.as_default():\n importer.import_graph_def(graph_def)\n assert graph.graph_def_versions.producer, producer_version\n\n\[email protected]\ndef _fake_gradient_tape_context_manager():\n \"\"\"tf.gradients(...) implemented as tf.GradientTape context manager interface.\n\n This is useful to test tf.gradients() in tests that uses tf.GradientTape().\n\n Yields:\n gradient tape instance that's implemented by tf.gradients() underneath.\n \"\"\"\n try:\n class FakeGradientTape:\n\n def watch(self, x):\n pass\n\n def gradient(self, y, x, grad_ys=None):\n result = gradients_impl.gradients(y, x, grad_ys)\n\n # Unlike `tape.gradient()`, `tf.gradients()` returns a list for a single\n # element. So unpack if needed to match `tape.gradient()` behavior.\n if not isinstance(x, (list, tuple)):\n assert len(result) == 1\n return result[0]\n\n return result\n\n yield FakeGradientTape()\n finally:\n pass\n\n\nclass AbstractGradientTape:\n \"\"\"Abstract GradientTape context manager that has multiple implementations.\n\n This is useful to test both tf.GradientTape() and tf.gradients() without\n duplicating tests.\n \"\"\"\n\n def __init__(self, use_tape, persistent=False):\n self._use_tape = use_tape\n self._persistent = persistent\n\n def __enter__(self):\n if self._use_tape:\n self._tape_impl = backprop.GradientTape(persistent=self._persistent)\n else:\n self._tape_impl = _fake_gradient_tape_context_manager()\n return self._tape_impl.__enter__()\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self._tape_impl.__exit__(exc_type, exc_val, exc_tb)\n\n\[email protected]\ndef run_functions_eagerly(run_eagerly):\n \"\"\"Runs functions eagerly if `run_eagerly` is true.\n\n WARNING: Setting `run_eagerly` to True in tests running in V1 graph mode\n *WILL NOT* make the tf.function to run eagerly because eager is disabled by\n default in V1. Instead, tf.function will run as a traced graph function.\n\n Ensures that the state (for running functions eagerly) is back to the initial\n `def_function.RUN_FUNCTIONS_EAGERLY` state.\n\n Args:\n run_eagerly: Boolean determining whether to run the function eagerly or not.\n\n Raises:\n ValueError if `run_eagerly` is not a boolean.\n\n Yields:\n Nothing.\n \"\"\"\n if not isinstance(run_eagerly, bool):\n raise ValueError(\n \"Expected bool for `run_eagerly` but got {}\".format(run_eagerly))\n\n is_eager = context.executing_eagerly()\n if not is_eager and run_eagerly:\n logging.warning(\n \"Running tf.function eagerly in V1 graph mode is not supported. \"\n \"tf.function will be run as a traced graph function.\")\n\n initial_state = def_function.functions_run_eagerly()\n def_function.run_functions_eagerly(run_eagerly)\n try:\n yield\n finally:\n def_function.run_functions_eagerly(initial_state)\n", "# Copyright 2020 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 Keras text vectorization preprocessing layer.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport itertools\nimport os\nimport random\nimport string\n\nfrom absl.testing import parameterized\nimport numpy as np\n\nfrom tensorflow.python import keras\nfrom tensorflow.python import tf2\n\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import sparse_tensor\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.keras import keras_parameterized\nfrom tensorflow.python.keras import testing_utils\nfrom tensorflow.python.keras.layers.preprocessing import index_lookup\nfrom tensorflow.python.keras.layers.preprocessing import index_lookup_v1\nfrom tensorflow.python.keras.layers.preprocessing import preprocessing_test_utils\nfrom tensorflow.python.keras.saving import save\nfrom tensorflow.python.keras.utils.generic_utils import CustomObjectScope\nfrom tensorflow.python.ops import lookup_ops\nfrom tensorflow.python.ops.ragged import ragged_factory_ops\nfrom tensorflow.python.platform import gfile\nfrom tensorflow.python.platform import test\n\n\ndef get_layer_class():\n if context.executing_eagerly():\n return index_lookup.IndexLookup\n else:\n return index_lookup_v1.IndexLookup\n\n\ndef _get_end_to_end_test_cases():\n test_cases = (\n {\n \"testcase_name\":\n \"test_strings_soft_vocab_cap\",\n # Create an array where 'earth' is the most frequent term, followed by\n # 'wind', then 'and', then 'fire'. This ensures that the vocab\n # accumulator is sorting by frequency.\n \"vocab_data\":\n np.array([[\"fire\"], [\"earth\"], [\"earth\"], [\"earth\"], [\"earth\"],\n [\"wind\"], [\"wind\"], [\"wind\"], [\"and\"], [\"and\"]]),\n \"input_data\":\n np.array([[\"earth\"], [\"wind\"], [\"and\"], [\"fire\"], [\"fire\"],\n [\"and\"], [\"earth\"], [\"michigan\"]]),\n \"kwargs\": {\n \"max_tokens\": None,\n \"num_oov_indices\": 1,\n \"mask_token\": \"\",\n \"oov_token\": \"[OOV]\",\n \"dtype\": dtypes.string,\n },\n \"expected_output\": [[2], [3], [4], [5], [5], [4], [2], [1]],\n \"input_dtype\":\n dtypes.string\n },\n {\n \"testcase_name\":\n \"test_inverse_strings_soft_vocab_cap\",\n # Create an array where 'earth' is the most frequent term, followed by\n # 'wind', then 'and', then 'fire'. This ensures that the vocab\n # accumulator is sorting by frequency.\n \"vocab_data\":\n np.array([[\"fire\"], [\"earth\"], [\"earth\"], [\"earth\"], [\"earth\"],\n [\"wind\"], [\"wind\"], [\"wind\"], [\"and\"], [\"and\"]]),\n \"input_data\":\n np.array([[2], [3], [4], [1], [1], [4], [2], [5]]),\n \"kwargs\": {\n \"max_tokens\": None,\n \"num_oov_indices\": 1,\n \"mask_token\": \"\",\n \"oov_token\": \"[OOV]\",\n \"dtype\": dtypes.string,\n \"invert\": True\n },\n \"expected_output\":\n np.array([[b\"earth\"], [b\"wind\"], [b\"and\"], [b\"[OOV]\"], [b\"[OOV]\"],\n [b\"and\"], [b\"earth\"], [b\"fire\"]]),\n \"input_dtype\":\n dtypes.int64\n },\n {\n \"testcase_name\":\n \"test_strings_with_special_tokens\",\n # Mask and oov values in the vocab data should be dropped, and mapped\n # to 0 and 1 respectively when calling the layer.\n \"vocab_data\":\n np.array([[\"fire\"], [\"earth\"], [\"earth\"], [\"earth\"], [\"earth\"],\n [\"\"], [\"\"], [\"\"], [\"[OOV]\"], [\"[OOV]\"], [\"[OOV]\"],\n [\"wind\"], [\"wind\"], [\"wind\"], [\"and\"], [\"and\"]]),\n \"input_data\":\n np.array([[\"earth\"], [\"\"], [\"wind\"], [\"[OOV]\"], [\"and\"], [\"\"],\n [\"fire\"], [\"and\"], [\"[OOV]\"], [\"michigan\"]]),\n \"kwargs\": {\n \"max_tokens\": None,\n \"num_oov_indices\": 1,\n \"mask_token\": \"\",\n \"oov_token\": \"[OOV]\",\n \"dtype\": dtypes.string,\n },\n \"expected_output\": [[2], [0], [3], [1], [4], [0], [5], [4], [1], [1]],\n \"input_dtype\":\n dtypes.string\n },\n {\n \"testcase_name\":\n \"test_ints_soft_vocab_cap\",\n # Create an array where 1138 is the most frequent term, followed by\n # 1729, then 725, then 42. This ensures that the vocab accumulator\n # is sorting by frequency.\n \"vocab_data\":\n np.array([[42], [1138], [1138], [1138], [1138], [1729], [1729],\n [1729], [725], [725]],\n dtype=np.int64),\n \"input_data\":\n np.array([[1138], [1729], [725], [42], [42], [725], [1138], [4]],\n dtype=np.int64),\n \"kwargs\": {\n \"max_tokens\": None,\n \"num_oov_indices\": 1,\n \"mask_token\": 0,\n \"oov_token\": -1,\n \"dtype\": dtypes.int64,\n },\n \"expected_output\": [[2], [3], [4], [5], [5], [4], [2], [1]],\n \"input_dtype\":\n dtypes.int64\n },\n {\n \"testcase_name\":\n \"test_ints_with_special_tokens\",\n # Mask and oov values in the vocab data should be dropped, and mapped\n # to 0 and 1 respectively when calling the layer.\n \"vocab_data\":\n np.array([[42], [1138], [1138], [1138], [1138], [0], [0], [0],\n [-1], [-1], [-1], [1729], [1729], [1729], [725], [725]],\n dtype=np.int64),\n \"input_data\":\n np.array([[1138], [0], [1729], [-1], [725], [0], [42], [725],\n [-1], [4]],\n dtype=np.int64),\n \"kwargs\": {\n \"max_tokens\": None,\n \"num_oov_indices\": 1,\n \"mask_token\": 0,\n \"oov_token\": -1,\n \"dtype\": dtypes.int64,\n },\n \"expected_output\": [[2], [0], [3], [1], [4], [0], [5], [4], [1], [1]],\n \"input_dtype\":\n dtypes.int64\n },\n {\n \"testcase_name\":\n \"test_strings_hard_vocab_cap\",\n # Create an array where 'earth' is the most frequent term, followed by\n # 'wind', then 'and', then 'fire'. This ensures that the vocab\n # accumulator is sorting by frequency.\n \"vocab_data\":\n np.array([[\"fire\"], [\"earth\"], [\"earth\"], [\"earth\"], [\"earth\"],\n [\"wind\"], [\"wind\"], [\"wind\"], [\"and\"], [\"and\"]]),\n \"input_data\":\n np.array([[\"earth\"], [\"wind\"], [\"and\"], [\"fire\"], [\"fire\"],\n [\"and\"], [\"earth\"], [\"michigan\"]]),\n \"kwargs\": {\n \"max_tokens\": 5,\n \"num_oov_indices\": 1,\n \"mask_token\": \"\",\n \"oov_token\": \"[OOV]\",\n \"dtype\": dtypes.string,\n },\n \"expected_output\": [[2], [3], [4], [1], [1], [4], [2], [1]],\n \"input_dtype\":\n dtypes.string\n },\n {\n \"testcase_name\":\n \"test_inverse_strings_hard_vocab_cap\",\n # Create an array where 'earth' is the most frequent term, followed by\n # 'wind', then 'and', then 'fire'. This ensures that the vocab\n # accumulator is sorting by frequency.\n \"vocab_data\":\n np.array([[\"fire\"], [\"earth\"], [\"earth\"], [\"earth\"], [\"earth\"],\n [\"wind\"], [\"wind\"], [\"wind\"], [\"and\"], [\"and\"]]),\n \"input_data\":\n np.array([[2], [3], [4], [1], [1], [4], [2], [5]]),\n \"kwargs\": {\n \"max_tokens\": 5,\n \"num_oov_indices\": 1,\n \"mask_token\": \"\",\n \"oov_token\": \"[OOV]\",\n \"dtype\": dtypes.string,\n \"invert\": True\n },\n \"expected_output\":\n np.array([[b\"earth\"], [b\"wind\"], [b\"and\"], [b\"[OOV]\"], [b\"[OOV]\"],\n [b\"and\"], [b\"earth\"], [b\"[OOV]\"]]),\n \"input_dtype\":\n dtypes.int64\n },\n {\n \"testcase_name\":\n \"test_ints_hard_vocab_cap\",\n # Create an array where 1138 is the most frequent term, followed by\n # 1729, then 725, then 42. This ensures that the vocab accumulator\n # is sorting by frequency.\n \"vocab_data\":\n np.array([[42], [1138], [1138], [1138], [1138], [1729], [1729],\n [1729], [725], [725]],\n dtype=np.int64),\n \"input_data\":\n np.array([[1138], [1729], [725], [42], [42], [725], [1138], [4]],\n dtype=np.int64),\n \"kwargs\": {\n \"max_tokens\": 5,\n \"num_oov_indices\": 1,\n \"mask_token\": 0,\n \"oov_token\": -1,\n \"dtype\": dtypes.int64,\n },\n \"expected_output\": [[2], [3], [4], [1], [1], [4], [2], [1]],\n \"input_dtype\":\n dtypes.int64\n },\n {\n \"testcase_name\":\n \"test_ints_tf_idf_output\",\n \"vocab_data\":\n np.array([[42], [1138], [1138], [1138], [1138], [1729], [1729],\n [1729], [725], [725]]),\n \"input_data\":\n np.array([[1138], [1729], [725], [42], [42], [725], [1138], [4]]),\n \"kwargs\": {\n \"max_tokens\": 5,\n \"num_oov_indices\": 1,\n \"mask_token\": 0,\n \"oov_token\": -1,\n \"output_mode\": index_lookup.TFIDF,\n \"dtype\": dtypes.int64,\n },\n \"expected_output\": [[0, 1.098612, 0, 0, 0], [0, 0, 1.252763, 0, 0],\n [0, 0, 0, 1.466337, 0], [0, 0, 0, 0, 1.7917595],\n [0, 0, 0, 0, 1.7917595], [0, 0, 0, 1.4663371, 0],\n [0, 1.098612, 0, 0, 0], [1.402368, 0, 0, 0, 0]],\n \"input_dtype\":\n dtypes.int64\n },\n {\n \"testcase_name\":\n \"test_strings_tf_idf_output\",\n \"vocab_data\":\n np.array([[\"fire\"], [\"earth\"], [\"earth\"], [\"earth\"], [\"earth\"],\n [\"wind\"], [\"wind\"], [\"wind\"], [\"and\"], [\"and\"]]),\n \"input_data\":\n np.array([[\"earth\"], [\"wind\"], [\"and\"], [\"fire\"], [\"fire\"],\n [\"and\"], [\"earth\"], [\"michigan\"]]),\n \"kwargs\": {\n \"max_tokens\": 5,\n \"num_oov_indices\": 1,\n \"mask_token\": \"\",\n \"oov_token\": \"[OOV]\",\n \"output_mode\": index_lookup.TFIDF,\n \"dtype\": dtypes.string,\n },\n \"expected_output\": [[0, 1.098612, 0, 0, 0], [0, 0, 1.252763, 0, 0],\n [0, 0, 0, 1.466337, 0], [0, 0, 0, 0, 1.7917595],\n [0, 0, 0, 0, 1.7917595], [0, 0, 0, 1.4663371, 0],\n [0, 1.098612, 0, 0, 0], [1.402368, 0, 0, 0, 0]],\n \"input_dtype\":\n dtypes.string\n },\n )\n\n crossed_test_cases = []\n # Cross above test cases with use_dataset in (True, False)\n for use_dataset in (True, False):\n for case in test_cases:\n case = case.copy()\n if use_dataset:\n case[\"testcase_name\"] = case[\"testcase_name\"] + \"_with_dataset\"\n case[\"use_dataset\"] = use_dataset\n crossed_test_cases.append(case)\n\n return crossed_test_cases\n\n\n@keras_parameterized.run_all_keras_modes\nclass IndexLookupLayerTest(keras_parameterized.TestCase,\n preprocessing_test_utils.PreprocessingLayerTest):\n\n @parameterized.named_parameters(*_get_end_to_end_test_cases())\n def test_layer_end_to_end_with_adapt(self, vocab_data, input_data, kwargs,\n use_dataset, expected_output,\n input_dtype):\n cls = get_layer_class()\n if \"invert\" in kwargs and kwargs[\"invert\"]:\n expected_output_dtype = kwargs[\"dtype\"]\n elif \"output_mode\" in kwargs and kwargs[\"output_mode\"] != index_lookup.INT:\n expected_output_dtype = dtypes.float32\n else:\n expected_output_dtype = dtypes.int64\n\n input_shape = input_data.shape\n\n if use_dataset:\n # Keras APIs expect batched datasets.\n # TODO(rachelim): `model.predict` predicts the result on each\n # dataset batch separately, then tries to concatenate the results\n # together. When the results have different shapes on the non-concat\n # axis (which can happen in the output_mode = INT case for\n # IndexLookup), the concatenation fails. In real use cases, this may\n # not be an issue because users are likely to pipe the preprocessing layer\n # into other keras layers instead of predicting it directly. A workaround\n # for these unit tests is to have the dataset only contain one batch, so\n # no concatenation needs to happen with the result. For consistency with\n # numpy input, we should make `predict` join differently shaped results\n # together sensibly, with 0 padding.\n input_data = dataset_ops.Dataset.from_tensor_slices(input_data).batch(\n input_shape[0])\n vocab_data = dataset_ops.Dataset.from_tensor_slices(vocab_data).batch(\n input_shape[0])\n\n with CustomObjectScope({\"IndexLookup\": cls}):\n output_data = testing_utils.layer_test(\n cls,\n kwargs=kwargs,\n input_shape=input_shape,\n input_data=input_data,\n input_dtype=input_dtype,\n expected_output_dtype=expected_output_dtype,\n validate_training=False,\n adapt_data=vocab_data)\n if \"invert\" in kwargs and kwargs[\"invert\"]:\n self.assertAllEqual(expected_output, output_data)\n else:\n self.assertAllClose(expected_output, output_data)\n\n\n@keras_parameterized.run_all_keras_modes\nclass CategoricalEncodingInputTest(\n keras_parameterized.TestCase,\n preprocessing_test_utils.PreprocessingLayerTest):\n\n def test_sparse_string_input(self):\n vocab_data = [\"earth\", \"wind\", \"and\", \"fire\"]\n input_array = sparse_tensor.SparseTensor(\n indices=[[0, 0], [1, 2]],\n values=[\"fire\", \"michigan\"],\n dense_shape=[3, 4])\n\n expected_indices = [[0, 0], [1, 2]]\n expected_values = [5, 1]\n expected_dense_shape = [3, 4]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.string, sparse=True)\n layer = get_layer_class()(\n max_tokens=None,\n num_oov_indices=1,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n dtype=dtypes.string)\n layer.set_vocabulary(vocab_data)\n int_data = layer(input_data)\n model = keras.Model(inputs=input_data, outputs=int_data)\n output_data = model.predict(input_array, steps=1)\n self.assertAllEqual(expected_indices, output_data.indices)\n self.assertAllEqual(expected_values, output_data.values)\n self.assertAllEqual(expected_dense_shape, output_data.dense_shape)\n\n def test_sparse_int_input(self):\n vocab_data = np.array([10, 11, 12, 13], dtype=np.int64)\n input_array = sparse_tensor.SparseTensor(\n indices=[[0, 0], [1, 2]],\n values=np.array([13, 32], dtype=np.int64),\n dense_shape=[3, 4])\n\n expected_indices = [[0, 0], [1, 2]]\n expected_values = [5, 1]\n expected_dense_shape = [3, 4]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.int64, sparse=True)\n layer = get_layer_class()(\n max_tokens=None,\n dtype=dtypes.int64,\n num_oov_indices=1,\n mask_token=0,\n oov_token=-1)\n layer.set_vocabulary(vocab_data)\n int_data = layer(input_data)\n model = keras.Model(inputs=input_data, outputs=int_data)\n output_data = model.predict(input_array, steps=1)\n self.assertAllEqual(expected_indices, output_data.indices)\n self.assertAllEqual(expected_values, output_data.values)\n self.assertAllEqual(expected_dense_shape, output_data.dense_shape)\n\n def test_ragged_string_input(self):\n vocab_data = [\"earth\", \"wind\", \"and\", \"fire\"]\n input_array = ragged_factory_ops.constant(\n [[\"earth\", \"wind\", \"fire\"], [\"fire\", \"and\", \"earth\", \"michigan\"]])\n expected_output = [[2, 3, 5], [5, 4, 2, 1]]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.string, ragged=True)\n layer = get_layer_class()(\n max_tokens=None,\n num_oov_indices=1,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n dtype=dtypes.string)\n layer.set_vocabulary(vocab_data)\n int_data = layer(input_data)\n model = keras.Model(inputs=input_data, outputs=int_data)\n output_dataset = model.predict(input_array)\n self.assertAllEqual(expected_output, output_dataset)\n\n def test_ragged_int_input(self):\n vocab_data = np.array([10, 11, 12, 13], dtype=np.int64)\n input_array = ragged_factory_ops.constant([[10, 11, 13], [13, 12, 10, 42]],\n dtype=np.int64)\n expected_output = [[2, 3, 5], [5, 4, 2, 1]]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.int64, ragged=True)\n layer = get_layer_class()(\n max_tokens=None,\n dtype=dtypes.int64,\n num_oov_indices=1,\n mask_token=0,\n oov_token=-1)\n layer.set_vocabulary(vocab_data)\n int_data = layer(input_data)\n model = keras.Model(inputs=input_data, outputs=int_data)\n output_dataset = model.predict(input_array)\n self.assertAllEqual(expected_output, output_dataset)\n\n def test_int32_input_with_int64_keys(self):\n vocab_data = np.array([10, 11, 12, 13], dtype=np.int64)\n input_array = ragged_factory_ops.constant([[10, 11, 13], [13, 12, 10, 42]],\n dtype=np.int32)\n expected_output = [[2, 3, 5], [5, 4, 2, 1]]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.int32, ragged=True)\n layer = get_layer_class()(\n max_tokens=None,\n dtype=dtypes.int64,\n num_oov_indices=1,\n mask_token=0,\n oov_token=-1)\n layer.set_vocabulary(vocab_data)\n int_data = layer(input_data)\n model = keras.Model(inputs=input_data, outputs=int_data)\n output_dataset = model.predict(input_array)\n self.assertAllEqual(expected_output, output_dataset)\n\n\n@keras_parameterized.run_all_keras_modes\nclass CategoricalEncodingMultiOOVTest(\n keras_parameterized.TestCase,\n preprocessing_test_utils.PreprocessingLayerTest):\n\n def test_sparse_string_input_multi_bucket(self):\n vocab_data = [\"earth\", \"wind\", \"and\", \"fire\"]\n input_array = sparse_tensor.SparseTensor(\n indices=[[0, 0], [1, 2]],\n values=[\"fire\", \"ohio\"],\n dense_shape=[3, 4])\n\n expected_indices = [[0, 0], [1, 2]]\n expected_values = [6, 2]\n expected_dense_shape = [3, 4]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.string, sparse=True)\n layer = get_layer_class()(\n max_tokens=None,\n num_oov_indices=2,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n dtype=dtypes.string)\n layer.set_vocabulary(vocab_data)\n int_data = layer(input_data)\n model = keras.Model(inputs=input_data, outputs=int_data)\n output_data = model.predict(input_array, steps=1)\n self.assertAllEqual(expected_indices, output_data.indices)\n self.assertAllEqual(expected_values, output_data.values)\n self.assertAllEqual(expected_dense_shape, output_data.dense_shape)\n\n def test_sparse_int_input_multi_bucket(self):\n vocab_data = np.array([10, 11, 12, 13], dtype=np.int64)\n input_array = sparse_tensor.SparseTensor(\n indices=[[0, 0], [1, 2]],\n values=np.array([13, 133], dtype=np.int64),\n dense_shape=[3, 4])\n\n expected_indices = [[0, 0], [1, 2]]\n expected_values = [6, 2]\n expected_dense_shape = [3, 4]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.int64, sparse=True)\n layer = get_layer_class()(\n max_tokens=None,\n dtype=dtypes.int64,\n num_oov_indices=2,\n mask_token=0,\n oov_token=-1)\n layer.set_vocabulary(vocab_data)\n int_data = layer(input_data)\n model = keras.Model(inputs=input_data, outputs=int_data)\n output_data = model.predict(input_array, steps=1)\n self.assertAllEqual(expected_indices, output_data.indices)\n self.assertAllEqual(expected_values, output_data.values)\n self.assertAllEqual(expected_dense_shape, output_data.dense_shape)\n\n def test_ragged_string_input_multi_bucket(self):\n vocab_data = [\"earth\", \"wind\", \"and\", \"fire\"]\n input_array = ragged_factory_ops.constant(\n [[\"earth\", \"wind\", \"fire\"], [\"fire\", \"and\", \"earth\", \"ohio\"]])\n expected_output = [[3, 4, 6], [6, 5, 3, 2]]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.string, ragged=True)\n layer = get_layer_class()(\n max_tokens=None,\n num_oov_indices=2,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n dtype=dtypes.string)\n layer.set_vocabulary(vocab_data)\n int_data = layer(input_data)\n model = keras.Model(inputs=input_data, outputs=int_data)\n output_dataset = model.predict(input_array)\n self.assertAllEqual(expected_output, output_dataset)\n\n def test_ragged_int_input_multi_bucket(self):\n vocab_data = np.array([10, 11, 12, 13], dtype=np.int64)\n input_array = ragged_factory_ops.constant([[10, 11, 13], [13, 12, 10, 133]],\n dtype=np.int64)\n expected_output = [[3, 4, 6], [6, 5, 3, 2]]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.int64, ragged=True)\n layer = get_layer_class()(\n max_tokens=None,\n dtype=dtypes.int64,\n num_oov_indices=2,\n mask_token=0,\n oov_token=-1)\n layer.set_vocabulary(vocab_data)\n int_data = layer(input_data)\n model = keras.Model(inputs=input_data, outputs=int_data)\n output_dataset = model.predict(input_array)\n self.assertAllEqual(expected_output, output_dataset)\n\n\n@keras_parameterized.run_all_keras_modes\nclass CategoricalEncodingAdaptTest(\n keras_parameterized.TestCase,\n preprocessing_test_utils.PreprocessingLayerTest):\n\n def test_sparse_adapt(self):\n vocab_data = sparse_tensor.SparseTensor(\n indices=[[0, 0], [0, 1], [1, 2]],\n values=[\"michigan\", \"fire\", \"michigan\"],\n dense_shape=[3, 4])\n vocab_dataset = dataset_ops.Dataset.from_tensors(vocab_data)\n\n layer = get_layer_class()(\n max_tokens=None,\n num_oov_indices=1,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n dtype=dtypes.string)\n layer.adapt(vocab_dataset)\n expected_vocabulary = [\"\", \"[OOV]\", \"michigan\", \"fire\"]\n self.assertAllEqual(expected_vocabulary, layer.get_vocabulary())\n\n def test_ragged_adapt(self):\n vocab_data = ragged_factory_ops.constant([[\"michigan\"],\n [\"fire\", \"michigan\"]])\n vocab_dataset = dataset_ops.Dataset.from_tensors(vocab_data)\n\n layer = get_layer_class()(\n max_tokens=None,\n num_oov_indices=1,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n dtype=dtypes.string)\n layer.adapt(vocab_dataset)\n expected_vocabulary = [\"\", \"[OOV]\", \"michigan\", \"fire\"]\n self.assertAllEqual(expected_vocabulary, layer.get_vocabulary())\n\n def test_sparse_int_input(self):\n vocab_data = np.array([10, 11, 12, 13], dtype=np.int64)\n input_array = sparse_tensor.SparseTensor(\n indices=[[0, 0], [1, 2]],\n values=np.array([13, 32], dtype=np.int64),\n dense_shape=[3, 4])\n\n expected_indices = [[0, 0], [1, 2]]\n expected_values = [5, 1]\n expected_dense_shape = [3, 4]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.int64, sparse=True)\n layer = get_layer_class()(\n max_tokens=None,\n dtype=dtypes.int64,\n num_oov_indices=1,\n mask_token=0,\n oov_token=-1)\n layer.set_vocabulary(vocab_data)\n int_data = layer(input_data)\n model = keras.Model(inputs=input_data, outputs=int_data)\n output_data = model.predict(input_array, steps=1)\n self.assertAllEqual(expected_indices, output_data.indices)\n self.assertAllEqual(expected_values, output_data.values)\n self.assertAllEqual(expected_dense_shape, output_data.dense_shape)\n\n def test_ragged_string_input(self):\n vocab_data = [\"earth\", \"wind\", \"and\", \"fire\"]\n input_array = ragged_factory_ops.constant(\n [[\"earth\", \"wind\", \"fire\"], [\"fire\", \"and\", \"earth\", \"michigan\"]])\n expected_output = [[2, 3, 5], [5, 4, 2, 1]]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.string, ragged=True)\n layer = get_layer_class()(\n max_tokens=None,\n num_oov_indices=1,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n dtype=dtypes.string)\n layer.set_vocabulary(vocab_data)\n int_data = layer(input_data)\n model = keras.Model(inputs=input_data, outputs=int_data)\n output_dataset = model.predict(input_array)\n self.assertAllEqual(expected_output, output_dataset)\n\n def test_ragged_int_input(self):\n vocab_data = np.array([10, 11, 12, 13], dtype=np.int64)\n input_array = ragged_factory_ops.constant([[10, 11, 13], [13, 12, 10, 42]],\n dtype=np.int64)\n expected_output = [[2, 3, 5], [5, 4, 2, 1]]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.int64, ragged=True)\n layer = get_layer_class()(\n max_tokens=None,\n dtype=dtypes.int64,\n num_oov_indices=1,\n mask_token=0,\n oov_token=-1)\n layer.set_vocabulary(vocab_data)\n int_data = layer(input_data)\n model = keras.Model(inputs=input_data, outputs=int_data)\n output_dataset = model.predict(input_array)\n self.assertAllEqual(expected_output, output_dataset)\n\n def test_single_string_generator_dataset(self):\n\n def word_gen():\n for _ in itertools.count(1):\n yield \"\".join(random.choice(string.ascii_letters) for i in range(2))\n\n ds = dataset_ops.Dataset.from_generator(word_gen, dtypes.string,\n tensor_shape.TensorShape([]))\n batched_ds = ds.take(2)\n input_t = keras.Input(shape=(), dtype=dtypes.string)\n layer = get_layer_class()(\n max_tokens=10,\n num_oov_indices=0,\n mask_token=None,\n oov_token=None,\n dtype=dtypes.string)\n _ = layer(input_t)\n layer.adapt(batched_ds)\n\n\n@keras_parameterized.run_all_keras_modes\nclass IndexLookupOutputTest(keras_parameterized.TestCase,\n preprocessing_test_utils.PreprocessingLayerTest):\n\n def _write_to_temp_file(self, file_name, vocab_list):\n vocab_path = os.path.join(self.get_temp_dir(), file_name + \".txt\")\n with gfile.GFile(vocab_path, \"w\") as writer:\n for vocab in vocab_list:\n writer.write(vocab + \"\\n\")\n writer.flush()\n writer.close()\n return vocab_path\n\n def test_int_output(self):\n vocab_data = [\"earth\", \"wind\", \"and\", \"fire\"]\n input_array = np.array([[\"earth\", \"wind\", \"and\", \"fire\"],\n [\"fire\", \"and\", \"earth\", \"michigan\"]])\n expected_output = [[2, 3, 4, 5], [5, 4, 2, 1]]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.string)\n layer = get_layer_class()(\n max_tokens=None,\n num_oov_indices=1,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n dtype=dtypes.string)\n layer.set_vocabulary(vocab_data)\n int_data = layer(input_data)\n model = keras.Model(inputs=input_data, outputs=int_data)\n output_dataset = model.predict(input_array)\n self.assertAllEqual(expected_output, output_dataset)\n\n def test_int_output_shape(self):\n input_data = keras.Input(batch_size=16, shape=(4,), dtype=dtypes.string)\n layer = get_layer_class()(\n max_tokens=2,\n num_oov_indices=1,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n dtype=dtypes.string)\n int_data = layer(input_data)\n self.assertAllEqual(int_data.shape.as_list(), [16, 4])\n\n def test_int_output_no_reserved_zero(self):\n vocab_data = [\"earth\", \"wind\", \"and\", \"fire\"]\n input_array = np.array([[\"earth\", \"wind\", \"and\", \"fire\"],\n [\"fire\", \"and\", \"earth\", \"michigan\"]])\n expected_output = [[1, 2, 3, 4], [4, 3, 1, 0]]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.string)\n layer = get_layer_class()(\n max_tokens=None,\n num_oov_indices=1,\n mask_token=None,\n oov_token=\"[OOV]\",\n dtype=dtypes.string)\n layer.set_vocabulary(vocab_data)\n int_data = layer(input_data)\n model = keras.Model(inputs=input_data, outputs=int_data)\n output_dataset = model.predict(input_array)\n self.assertAllEqual(expected_output, output_dataset)\n\n def test_int_output_no_oov(self):\n vocab_data = [\"earth\", \"wind\", \"and\", \"fire\"]\n input_array = np.array([[\"earth\", \"wind\", \"and\", \"ohio\"],\n [\"fire\", \"and\", \"earth\", \"michigan\"]])\n expected_output = [[1, 2, 3, -1], [4, 3, 1, -1]]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.string)\n layer = get_layer_class()(\n max_tokens=None,\n num_oov_indices=0,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n dtype=dtypes.string)\n layer.set_vocabulary(vocab_data)\n int_data = layer(input_data)\n model = keras.Model(inputs=input_data, outputs=int_data)\n output_dataset = model.predict(input_array)\n self.assertAllEqual(expected_output, output_dataset)\n\n def test_int_output_explicit_vocab(self):\n vocab_data = [\"earth\", \"wind\", \"and\", \"fire\"]\n input_array = np.array([[\"earth\", \"wind\", \"and\", \"fire\"],\n [\"fire\", \"and\", \"earth\", \"michigan\"]])\n expected_output = [[2, 3, 4, 5], [5, 4, 2, 1]]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.string)\n layer = get_layer_class()(\n vocabulary=vocab_data,\n max_tokens=None,\n num_oov_indices=1,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n dtype=dtypes.string)\n int_data = layer(input_data)\n model = keras.Model(inputs=input_data, outputs=int_data)\n output_dataset = model.predict(input_array)\n self.assertAllEqual(expected_output, output_dataset)\n\n def test_binary_output_hard_maximum(self):\n \"\"\"Check binary output when pad_to_max_tokens=True.\"\"\"\n vocab_data = [\"earth\", \"wind\", \"and\", \"fire\"]\n input_array = np.array([[\"earth\", \"wind\", \"and\", \"fire\", \"\"],\n [\"fire\", \"fire\", \"and\", \"earth\", \"michigan\"]])\n expected_output = [\n [0, 1, 1, 1, 1, 0],\n [1, 1, 0, 1, 1, 0],\n ]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.string)\n layer = get_layer_class()(\n max_tokens=6,\n num_oov_indices=1,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n output_mode=index_lookup.BINARY,\n pad_to_max_tokens=True,\n dtype=dtypes.string)\n layer.set_vocabulary(vocab_data)\n binary_data = layer(input_data)\n model = keras.Model(inputs=input_data, outputs=binary_data)\n output_dataset = model.predict(input_array)\n self.assertAllEqual(expected_output, output_dataset)\n\n def test_binary_output_no_oov(self):\n \"\"\"Check binary output when pad_to_max_tokens=True.\"\"\"\n vocab_data = [\"earth\", \"wind\", \"and\", \"fire\"]\n input_array = np.array([[\"earth\", \"wind\", \"and\", \"fire\", \"ohio\"],\n [\"fire\", \"fire\", \"and\", \"earth\", \"michigan\"]])\n expected_output = [\n [1, 1, 1, 1, 0],\n [1, 0, 1, 1, 0],\n ]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.string)\n layer = get_layer_class()(\n max_tokens=5,\n num_oov_indices=0,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n output_mode=index_lookup.BINARY,\n pad_to_max_tokens=True,\n dtype=dtypes.string)\n layer.set_vocabulary(vocab_data)\n binary_data = layer(input_data)\n model = keras.Model(inputs=input_data, outputs=binary_data)\n output_dataset = model.predict(input_array)\n self.assertAllEqual(expected_output, output_dataset)\n\n def test_binary_output_hard_maximum_multiple_adapts(self):\n input_array = np.array([[\"earth\", \"wind\", \"and\", \"earth\"],\n [\"ohio\", \"and\", \"earth\", \"michigan\"]])\n adapt_data = [\"earth\", \"earth\", \"earth\", \"earth\", \"wind\", \"wind\", \"wind\"]\n first_expected_output = [\n [1, 1, 1, 0, 0],\n [1, 1, 0, 0, 0],\n ]\n second_adapt_data = [\n \"earth\", \"earth\", \"earth\", \"earth\", \"wind\", \"wind\", \"wind\", \"and\",\n \"and\", \"fire\"\n ]\n second_expected_output = [\n [0, 1, 1, 1, 0],\n [1, 1, 0, 1, 0],\n ]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.string)\n layer = get_layer_class()(\n max_tokens=5,\n num_oov_indices=1,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n output_mode=index_lookup.BINARY,\n pad_to_max_tokens=True,\n dtype=dtypes.string)\n int_data = layer(input_data)\n model = keras.Model(inputs=input_data, outputs=int_data)\n\n # Test the first adapt\n layer.adapt(adapt_data)\n first_output = model.predict(input_array)\n # Test the second adapt\n layer.adapt(second_adapt_data)\n second_output = model.predict(input_array)\n self.assertAllEqual(first_expected_output, first_output)\n self.assertAllEqual(second_expected_output, second_output)\n\n def test_binary_output_soft_maximum(self):\n \"\"\"Check binary output when pad_to_max_tokens=False.\"\"\"\n vocab_data = [\"earth\", \"wind\", \"and\", \"fire\"]\n input_array = np.array([[\"earth\", \"wind\", \"and\", \"fire\", \"\"],\n [\"fire\", \"and\", \"earth\", \"michigan\", \"\"]])\n expected_output = [\n [0, 1, 1, 1, 1],\n [1, 1, 0, 1, 1],\n ]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.string)\n layer = get_layer_class()(\n max_tokens=None,\n num_oov_indices=1,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n output_mode=index_lookup.BINARY,\n dtype=dtypes.string)\n layer.set_vocabulary(vocab_data)\n binary_data = layer(input_data)\n model = keras.Model(inputs=input_data, outputs=binary_data)\n output_dataset = model.predict(input_array)\n self.assertAllEqual(expected_output, output_dataset)\n\n def test_binary_output_shape(self):\n input_data = keras.Input(batch_size=16, shape=(4,), dtype=dtypes.string)\n layer = get_layer_class()(\n max_tokens=2,\n num_oov_indices=1,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n output_mode=index_lookup.BINARY,\n dtype=dtypes.string)\n binary_data = layer(input_data)\n self.assertAllEqual(binary_data.shape.as_list(), [16, 2])\n\n def test_count_output_hard_maxiumum(self):\n \"\"\"Check count output when pad_to_max_tokens=True.\"\"\"\n vocab_data = [\"earth\", \"wind\", \"and\", \"fire\"]\n input_array = np.array([[\"earth\", \"wind\", \"and\", \"wind\", \"\"],\n [\"fire\", \"fire\", \"fire\", \"michigan\", \"\"]])\n expected_output = [\n [0, 1, 2, 1, 0, 0],\n [1, 0, 0, 0, 3, 0],\n ]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.string)\n layer = get_layer_class()(\n max_tokens=6,\n num_oov_indices=1,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n output_mode=index_lookup.COUNT,\n pad_to_max_tokens=True,\n dtype=dtypes.string)\n layer.set_vocabulary(vocab_data)\n count_data = layer(input_data)\n model = keras.Model(inputs=input_data, outputs=count_data)\n output_dataset = model.predict(input_array)\n self.assertAllEqual(expected_output, output_dataset)\n\n def test_count_output_soft_maximum(self):\n \"\"\"Check count output when pad_to_max_tokens=False.\"\"\"\n vocab_data = [\"earth\", \"wind\", \"and\", \"fire\"]\n input_array = np.array([[\"earth\", \"wind\", \"and\", \"wind\", \"\"],\n [\"fire\", \"fire\", \"fire\", \"michigan\", \"\"]])\n expected_output = [\n [0, 1, 2, 1, 0],\n [1, 0, 0, 0, 3],\n ]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.string)\n layer = get_layer_class()(\n max_tokens=None,\n num_oov_indices=1,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n output_mode=index_lookup.COUNT,\n dtype=dtypes.string)\n layer.set_vocabulary(vocab_data)\n count_data = layer(input_data)\n model = keras.Model(inputs=input_data, outputs=count_data)\n output_dataset = model.predict(input_array)\n self.assertAllEqual(expected_output, output_dataset)\n\n def test_count_output_shape(self):\n input_data = keras.Input(batch_size=16, shape=(4,), dtype=dtypes.string)\n layer = get_layer_class()(\n max_tokens=2,\n num_oov_indices=1,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n output_mode=index_lookup.COUNT,\n dtype=dtypes.string)\n count_data = layer(input_data)\n self.assertAllEqual(count_data.shape.as_list(), [16, 2])\n\n def test_ifidf_output_hard_maximum(self):\n \"\"\"Check tf-idf output when pad_to_max_tokens=True.\"\"\"\n vocab_data = [\"earth\", \"wind\", \"and\", \"fire\"]\n # OOV idf weight (bucket 0) should 0.5, the average of passed weights.\n idf_weights = [.4, .25, .75, .6]\n input_array = np.array([[\"earth\", \"wind\", \"and\", \"earth\", \"\"],\n [\"ohio\", \"fire\", \"earth\", \"michigan\", \"\"]])\n expected_output = [\n [0.00, 0.80, 0.25, 0.75, 0.00, 0.00],\n [1.00, 0.40, 0.00, 0.00, 0.60, 0.00],\n ]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.string)\n layer = get_layer_class()(\n max_tokens=6,\n num_oov_indices=1,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n output_mode=index_lookup.TFIDF,\n pad_to_max_tokens=True,\n dtype=dtypes.string)\n layer.set_vocabulary(vocab_data, idf_weights=idf_weights)\n layer_output = layer(input_data)\n model = keras.Model(inputs=input_data, outputs=layer_output)\n output_dataset = model.predict(input_array)\n self.assertAllClose(expected_output, output_dataset)\n\n def test_ifidf_output_soft_maximum(self):\n \"\"\"Check tf-idf output when pad_to_max_tokens=False.\"\"\"\n vocab_data = [\"earth\", \"wind\", \"and\", \"fire\"]\n # OOV idf weight (bucket 0) should 0.5, the average of passed weights.\n idf_weights = [.4, .25, .75, .6]\n input_array = np.array([[\"earth\", \"wind\", \"and\", \"earth\", \"\"],\n [\"ohio\", \"fire\", \"earth\", \"michigan\", \"\"]])\n expected_output = [\n [0.00, 0.80, 0.25, 0.75, 0.00],\n [1.00, 0.40, 0.00, 0.00, 0.60],\n ]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.string)\n layer = get_layer_class()(\n max_tokens=None,\n num_oov_indices=1,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n output_mode=index_lookup.TFIDF,\n dtype=dtypes.string)\n layer.set_vocabulary(vocab_data, idf_weights=idf_weights)\n layer_output = layer(input_data)\n model = keras.Model(inputs=input_data, outputs=layer_output)\n output_dataset = model.predict(input_array)\n self.assertAllClose(expected_output, output_dataset)\n\n def test_ifidf_output_shape(self):\n input_data = keras.Input(batch_size=16, shape=(4,), dtype=dtypes.string)\n layer = get_layer_class()(\n max_tokens=2,\n num_oov_indices=1,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n output_mode=index_lookup.COUNT,\n dtype=dtypes.string)\n layer_output = layer(input_data)\n self.assertAllEqual(layer_output.shape.as_list(), [16, 2])\n\n def test_int_output_file_vocab(self):\n vocab_data = [\"earth\", \"wind\", \"and\", \"fire\"]\n input_array = np.array([[\"earth\", \"wind\", \"and\", \"fire\"],\n [\"fire\", \"\", \"earth\", \"michigan\"]])\n expected_output = [[2, 3, 4, 5], [5, 0, 2, 1]]\n\n vocab_file = self._write_to_temp_file(\"temp\", vocab_data)\n vocabulary_initializer = lookup_ops.TextFileInitializer(\n filename=vocab_file,\n key_dtype=dtypes.string,\n key_index=lookup_ops.TextFileIndex.WHOLE_LINE,\n value_dtype=dtypes.int64,\n value_index=lookup_ops.TextFileIndex.LINE_NUMBER,\n value_index_offset=2)\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.string)\n layer = get_layer_class()(\n vocabulary=vocabulary_initializer,\n max_tokens=None,\n num_oov_indices=1,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n dtype=dtypes.string)\n int_data = layer(input_data)\n model = keras.Model(inputs=input_data, outputs=int_data)\n output_dataset = model.predict(input_array)\n self.assertAllEqual(expected_output, output_dataset)\n\n def test_int_output_int_file_vocab(self):\n vocab_data = [\"10\", \"20\", \"30\", \"40\"]\n input_array = np.array([[10, 20, 30, 40], [40, 0, 10, 42]])\n expected_output = [[2, 3, 4, 5], [5, 0, 2, 1]]\n\n vocab_file = self._write_to_temp_file(\"temp\", vocab_data)\n vocabulary_initializer = lookup_ops.TextFileInitializer(\n filename=vocab_file,\n key_dtype=dtypes.int64,\n key_index=lookup_ops.TextFileIndex.WHOLE_LINE,\n value_dtype=dtypes.int64,\n value_index=lookup_ops.TextFileIndex.LINE_NUMBER,\n value_index_offset=2)\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.int64)\n layer = get_layer_class()(\n vocabulary=vocabulary_initializer,\n max_tokens=None,\n num_oov_indices=1,\n mask_token=0,\n oov_token=-1,\n dtype=dtypes.int64)\n int_data = layer(input_data)\n model = keras.Model(inputs=input_data, outputs=int_data)\n output_dataset = model.predict(input_array)\n self.assertAllEqual(expected_output, output_dataset)\n\n\n@keras_parameterized.run_all_keras_modes\nclass IndexLookupVocabularyTest(keras_parameterized.TestCase,\n preprocessing_test_utils.PreprocessingLayerTest\n ):\n\n def test_int_output_explicit_vocab(self):\n vocab_data = [\"earth\", \"wind\", \"and\", \"fire\"]\n input_array = np.array([[\"earth\", \"wind\", \"and\", \"fire\"],\n [\"fire\", \"and\", \"earth\", \"michigan\"]])\n expected_output = [[2, 3, 4, 5], [5, 4, 2, 1]]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.string)\n layer = get_layer_class()(\n vocabulary=vocab_data,\n max_tokens=None,\n num_oov_indices=1,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n dtype=dtypes.string)\n int_data = layer(input_data)\n model = keras.Model(inputs=input_data, outputs=int_data)\n output_dataset = model.predict(input_array)\n self.assertAllEqual(expected_output, output_dataset)\n\n def test_int_output_explicit_vocab_with_special_tokens(self):\n vocab_data = [\"\", \"[OOV]\", \"earth\", \"wind\", \"and\", \"fire\"]\n input_array = np.array([[\"earth\", \"wind\", \"and\", \"fire\"],\n [\"fire\", \"and\", \"earth\", \"michigan\"]])\n expected_output = [[2, 3, 4, 5], [5, 4, 2, 1]]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.string)\n layer = get_layer_class()(\n vocabulary=vocab_data,\n max_tokens=None,\n num_oov_indices=1,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n dtype=dtypes.string)\n int_data = layer(input_data)\n model = keras.Model(inputs=input_data, outputs=int_data)\n output_dataset = model.predict(input_array)\n self.assertAllEqual(expected_output, output_dataset)\n\n def test_vocab_with_max_cap(self):\n vocab_data = [\"\", \"[OOV]\", \"wind\", \"and\", \"fire\"]\n layer = get_layer_class()(\n max_tokens=5,\n num_oov_indices=1,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n dtype=dtypes.string)\n layer.set_vocabulary(vocab_data)\n returned_vocab = layer.get_vocabulary()\n self.assertAllEqual(vocab_data, returned_vocab)\n self.assertAllEqual(layer.vocab_size(), 5)\n\n def test_int_vocab_with_max_cap(self):\n vocab_data = [0, -1, 42, 1276, 1138]\n layer = get_layer_class()(\n max_tokens=5,\n num_oov_indices=1,\n mask_token=0,\n oov_token=-1,\n dtype=dtypes.int64)\n layer.set_vocabulary(vocab_data)\n returned_vocab = layer.get_vocabulary()\n self.assertAllEqual(vocab_data, returned_vocab)\n self.assertAllEqual(layer.vocab_size(), 5)\n\n def test_vocab_with_multiple_oov_indices(self):\n vocab_data = [\"\", \"[OOV]\", \"[OOV]\", \"[OOV]\", \"wind\"]\n layer = get_layer_class()(\n max_tokens=None,\n num_oov_indices=3,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n dtype=dtypes.string)\n layer.set_vocabulary(vocab_data)\n returned_vocab = layer.get_vocabulary()\n self.assertAllEqual(vocab_data, returned_vocab)\n\n def test_int_vocab_with_multiple_oov_indices(self):\n vocab_data = [0, -1, -1, -1, 42]\n layer = get_layer_class()(\n max_tokens=None,\n num_oov_indices=3,\n mask_token=0,\n oov_token=-1,\n dtype=dtypes.int64)\n layer.set_vocabulary(vocab_data)\n returned_vocab = layer.get_vocabulary()\n self.assertAllEqual(vocab_data, returned_vocab)\n\n def test_non_unique_vocab_fails(self):\n vocab_data = [\"earth\", \"wind\", \"and\", \"fire\", \"fire\"]\n with self.assertRaisesRegex(ValueError, \".*repeated term.*fire.*\"):\n _ = get_layer_class()(\n vocabulary=vocab_data,\n max_tokens=None,\n num_oov_indices=1,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n dtype=dtypes.string)\n\n def test_vocab_with_oov_and_wrong_mask_fails(self):\n vocab_data = [\"custom_mask\", \"[OOV]\", \"earth\", \"wind\", \"and\", \"fire\"]\n layer = get_layer_class()(\n max_tokens=None,\n num_oov_indices=1,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n dtype=dtypes.string)\n with self.assertRaisesRegex(ValueError, \".*does not have the mask token.*\"):\n layer.set_vocabulary(vocab_data)\n\n def test_vocab_with_oov_and_no_mask_fails(self):\n vocab_data = [\"[OOV]\", \"earth\", \"wind\", \"and\", \"fire\"]\n layer = get_layer_class()(\n max_tokens=None,\n num_oov_indices=1,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n dtype=dtypes.string)\n with self.assertRaisesRegex(ValueError, \".*Reserved OOV.*\"):\n layer.set_vocabulary(vocab_data)\n\n def test_vocab_with_mask_but_no_oov_fails(self):\n vocab_data = [\"\", \"earth\", \"wind\", \"and\", \"fire\"]\n layer = get_layer_class()(\n max_tokens=None,\n num_oov_indices=1,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n dtype=dtypes.string)\n with self.assertRaisesRegex(ValueError, \".*does not have the OOV token.*\"):\n layer.set_vocabulary(vocab_data)\n\n def test_vocab_with_repeated_element_fails(self):\n vocab_data = [\"earth\", \"earth\", \"wind\", \"and\", \"fire\"]\n layer = get_layer_class()(\n max_tokens=None,\n num_oov_indices=1,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n dtype=dtypes.string)\n with self.assertRaisesRegex(ValueError, \".*repeated term.*earth.*\"):\n layer.set_vocabulary(vocab_data)\n\n def test_vocab_with_reserved_oov_element_fails(self):\n vocab_data = [\"earth\", \"test\", \"[OOV]\", \"wind\", \"and\", \"fire\"]\n layer = get_layer_class()(\n max_tokens=None,\n num_oov_indices=1,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n dtype=dtypes.string)\n with self.assertRaisesRegex(ValueError, \".*Reserved OOV.*\"):\n layer.set_vocabulary(vocab_data)\n\n def test_vocab_with_reserved_mask_element_fails(self):\n vocab_data = [\"earth\", \"mask_token\", \"wind\", \"and\", \"fire\"]\n layer = get_layer_class()(\n max_tokens=None,\n num_oov_indices=1,\n mask_token=\"mask_token\",\n oov_token=\"[OOV]\",\n dtype=dtypes.string)\n with self.assertRaisesRegex(ValueError, \".*Reserved mask.*\"):\n layer.set_vocabulary(vocab_data)\n\n def test_vocab_set_after_call_pad_to_max_false_fails(self):\n vocab_data = [\"earth\", \"wind\", \"and\", \"fire\"]\n layer = get_layer_class()(\n max_tokens=None,\n num_oov_indices=1,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n pad_to_max_tokens=False,\n output_mode=index_lookup.BINARY,\n dtype=dtypes.string)\n layer.set_vocabulary(vocab_data)\n # Calling the layer should lock the vocabulary.\n _ = layer([[\"earth\"]])\n with self.assertRaisesRegex(RuntimeError, \"vocabulary cannot be changed\"):\n layer.set_vocabulary(vocab_data)\n\n def test_vocab_with_idf_weights_non_tfidf_output_fails(self):\n vocab_data = [\"earth\", \"wind\", \"and\", \"fire\"]\n weight_data = [1, 1, 1, 1, 1]\n layer = get_layer_class()(\n max_tokens=None,\n num_oov_indices=1,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n output_mode=index_lookup.BINARY,\n dtype=dtypes.string)\n with self.assertRaisesRegex(ValueError,\n \"`idf_weights` should only be set if\"):\n layer.set_vocabulary(vocab_data, idf_weights=weight_data)\n\n def test_vocab_with_idf_weights_length_mismatch_fails(self):\n vocab_data = [\"earth\", \"wind\", \"and\", \"fire\"]\n weight_data = [1, 1, 1, 1, 1] # too long\n layer = get_layer_class()(\n max_tokens=None,\n num_oov_indices=1,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n output_mode=index_lookup.TFIDF,\n dtype=dtypes.string)\n with self.assertRaisesRegex(\n ValueError, \"`idf_weights` must be the same length as vocab\"):\n layer.set_vocabulary(vocab_data, idf_weights=weight_data)\n\n def test_vocab_without_idf_weights_tfidf_output_fails(self):\n vocab_data = [\"earth\", \"wind\", \"and\", \"fire\"]\n layer = get_layer_class()(\n max_tokens=None,\n num_oov_indices=1,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n output_mode=index_lookup.TFIDF,\n dtype=dtypes.string)\n with self.assertRaisesRegex(\n ValueError, \"`idf_weights` must be set if output_mode is TFIDF\"):\n layer.set_vocabulary(vocab_data)\n\n def test_non_unique_int_vocab_fails(self):\n vocab_data = [12, 13, 14, 15, 15]\n with self.assertRaisesRegex(ValueError, \"repeated term.*15\"):\n _ = get_layer_class()(\n vocabulary=vocab_data,\n max_tokens=None,\n num_oov_indices=1,\n mask_token=0,\n oov_token=-1,\n dtype=dtypes.int64)\n\n def test_int_vocab_with_oov_and_wrong_mask_fails(self):\n vocab_data = [1234, -1, 11, 21, 13, 14]\n layer = get_layer_class()(\n max_tokens=None,\n num_oov_indices=1,\n mask_token=0,\n oov_token=-1,\n dtype=dtypes.int64)\n with self.assertRaisesRegex(ValueError, \"does not have the mask token `0`\"):\n layer.set_vocabulary(vocab_data)\n\n def test_int_vocab_with_oov_and_no_mask_fails(self):\n vocab_data = [-1, 11, 12, 13, 14]\n layer = get_layer_class()(\n max_tokens=None,\n num_oov_indices=1,\n mask_token=0,\n oov_token=-1,\n dtype=dtypes.int64)\n with self.assertRaisesRegex(ValueError, \"Reserved OOV\"):\n layer.set_vocabulary(vocab_data)\n\n def test_int_vocab_with_mask_but_no_oov_fails(self):\n vocab_data = [0, 11, 12, 13, 14]\n layer = get_layer_class()(\n max_tokens=None,\n num_oov_indices=1,\n mask_token=0,\n oov_token=-1,\n dtype=dtypes.int64)\n with self.assertRaisesRegex(ValueError, \"does not have the OOV token `-1`\"):\n layer.set_vocabulary(vocab_data)\n\n def test_int_vocab_with_repeated_element_fails(self):\n vocab_data = [11, 11, 34, 23, 124]\n layer = get_layer_class()(\n max_tokens=None,\n num_oov_indices=1,\n mask_token=0,\n oov_token=-1,\n dtype=dtypes.int64)\n with self.assertRaisesRegex(ValueError, \"repeated term.*11\"):\n layer.set_vocabulary(vocab_data)\n\n def test_int_vocab_with_reserved_oov_element_fails(self):\n vocab_data = [14, 38, -1, 34, 3, 84]\n layer = get_layer_class()(\n max_tokens=None,\n num_oov_indices=1,\n mask_token=0,\n oov_token=-1,\n dtype=dtypes.int64)\n with self.assertRaisesRegex(ValueError, \"Reserved OOV\"):\n layer.set_vocabulary(vocab_data)\n\n def test_int_vocab_with_reserved_mask_element_fails(self):\n vocab_data = [125, 0, 3, 4, 94]\n layer = get_layer_class()(\n max_tokens=None,\n num_oov_indices=1,\n mask_token=0,\n oov_token=-1,\n dtype=dtypes.int64)\n with self.assertRaisesRegex(ValueError, \"Reserved mask\"):\n layer.set_vocabulary(vocab_data)\n\n\n@keras_parameterized.run_all_keras_modes\nclass IndexLookupInverseVocabularyTest(\n keras_parameterized.TestCase,\n preprocessing_test_utils.PreprocessingLayerTest):\n\n def test_int_output_explicit_vocab(self):\n vocab_data = [\"\", \"[OOV]\", \"earth\", \"wind\", \"and\", \"fire\"]\n input_array = np.array([[2, 3, 4, 5], [5, 4, 2, 1]])\n expected_output = np.array([[\"earth\", \"wind\", \"and\", \"fire\"],\n [\"fire\", \"and\", \"earth\", \"[OOV]\"]])\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.int64)\n layer = get_layer_class()(\n vocabulary=vocab_data,\n max_tokens=None,\n num_oov_indices=1,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n dtype=dtypes.string,\n invert=True)\n int_data = layer(input_data)\n model = keras.Model(inputs=input_data, outputs=int_data)\n output_dataset = model.predict(input_array)\n self.assertAllEqual(expected_output, output_dataset)\n\n def test_vocab_with_max_cap(self):\n vocab_data = [\"\", \"[OOV]\", \"wind\", \"and\", \"fire\"]\n layer = get_layer_class()(\n max_tokens=5,\n num_oov_indices=1,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n dtype=dtypes.string,\n invert=True)\n layer.set_vocabulary(vocab_data)\n returned_vocab = layer.get_vocabulary()\n self.assertAllEqual(vocab_data, returned_vocab)\n\n def test_int_vocab_with_max_cap(self):\n vocab_data = [0, -1, 42, 1276, 1138]\n layer = get_layer_class()(\n max_tokens=5,\n num_oov_indices=1,\n mask_token=0,\n oov_token=-1,\n dtype=dtypes.int64,\n invert=True)\n layer.set_vocabulary(vocab_data)\n returned_vocab = layer.get_vocabulary()\n self.assertAllEqual(vocab_data, returned_vocab)\n\n def test_non_unique_vocab_fails(self):\n vocab_data = [\"earth\", \"wind\", \"and\", \"fire\", \"fire\"]\n with self.assertRaisesRegex(ValueError, \".*repeated term.*fire.*\"):\n _ = get_layer_class()(\n vocabulary=vocab_data,\n max_tokens=None,\n num_oov_indices=1,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n dtype=dtypes.string,\n invert=True)\n\n def test_non_int_output_fails(self):\n with self.assertRaisesRegex(ValueError, \"`output_mode` must be int\"):\n _ = get_layer_class()(\n max_tokens=None,\n num_oov_indices=1,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n dtype=dtypes.string,\n output_mode=index_lookup.COUNT,\n invert=True)\n\n def test_vocab_with_repeated_element_fails(self):\n vocab_data = [\"earth\", \"earth\", \"wind\", \"and\", \"fire\"]\n layer = get_layer_class()(\n max_tokens=None,\n num_oov_indices=1,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n dtype=dtypes.string,\n invert=True)\n with self.assertRaisesRegex(ValueError, \".*repeated term.*earth.*\"):\n layer.set_vocabulary(vocab_data)\n\n def test_vocab_with_reserved_mask_element_fails(self):\n vocab_data = [\"earth\", \"mask_token\", \"wind\", \"and\", \"fire\"]\n layer = get_layer_class()(\n max_tokens=None,\n num_oov_indices=1,\n mask_token=\"mask_token\",\n oov_token=\"[OOV]\",\n dtype=dtypes.string,\n invert=True)\n with self.assertRaisesRegex(ValueError, \".*Reserved mask.*\"):\n layer.set_vocabulary(vocab_data)\n\n def test_non_unique_int_vocab_fails(self):\n vocab_data = [12, 13, 14, 15, 15]\n with self.assertRaisesRegex(ValueError, \".*repeated term.*15.*\"):\n _ = get_layer_class()(\n vocabulary=vocab_data,\n max_tokens=None,\n num_oov_indices=1,\n mask_token=0,\n oov_token=-1,\n dtype=dtypes.int64,\n invert=True)\n\n def test_int_vocab_with_repeated_element_fails(self):\n vocab_data = [11, 11, 34, 23, 124]\n layer = get_layer_class()(\n max_tokens=None,\n num_oov_indices=1,\n mask_token=0,\n oov_token=-1,\n dtype=dtypes.int64,\n invert=True)\n with self.assertRaisesRegex(ValueError, \".*repeated term.*11.*\"):\n layer.set_vocabulary(vocab_data)\n\n\n@keras_parameterized.run_all_keras_modes(always_skip_eager=True)\nclass IndexLookupSaveableTest(keras_parameterized.TestCase,\n preprocessing_test_utils.PreprocessingLayerTest):\n\n def test_ops_are_not_added_with_multiple_get_set_weights(self):\n vocab_data = [\"earth\", \"wind\", \"and\", \"fire\"]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.string)\n layer = get_layer_class()(\n max_tokens=10,\n num_oov_indices=1,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n dtype=dtypes.string)\n layer.set_vocabulary(vocab_data)\n int_data = layer(input_data)\n model = keras.Model(inputs=input_data, outputs=int_data)\n weights = model.get_weights()\n model.set_weights(weights)\n keras.backend.get_session().graph.finalize()\n weights = model.get_weights()\n model.set_weights(weights)\n\n def test_layer_saving_with_h5(self):\n vocab_data = [\"earth\", \"wind\", \"and\", \"fire\"]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.string)\n layer = get_layer_class()(\n max_tokens=10,\n num_oov_indices=1,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n dtype=dtypes.string)\n layer.set_vocabulary(vocab_data)\n int_data = layer(input_data)\n model = keras.Model(inputs=input_data, outputs=int_data)\n path = os.path.join(self.get_temp_dir(), \"model\")\n with self.assertRaisesRegex(NotImplementedError,\n \"Save or restore weights that is not.*\"):\n save.save_model(model, path, save_format=\"h5\")\n\n\n@keras_parameterized.run_all_keras_modes\nclass IndexLookupErrorTest(keras_parameterized.TestCase,\n preprocessing_test_utils.PreprocessingLayerTest):\n\n def test_too_long_vocab_fails_in_single_setting(self):\n vocab_data = [\"earth\", \"wind\", \"and\", \"fire\"]\n\n layer = get_layer_class()(\n max_tokens=4,\n num_oov_indices=1,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n dtype=dtypes.string)\n with self.assertRaisesRegex(ValueError,\n \"vocabulary larger than the maximum vocab.*\"):\n layer.set_vocabulary(vocab_data)\n\n def test_zero_max_tokens_fails(self):\n with self.assertRaisesRegex(ValueError, \".*max_tokens.*\"):\n _ = get_layer_class()(\n max_tokens=0,\n num_oov_indices=1,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n dtype=dtypes.string)\n\n\n@keras_parameterized.run_all_keras_modes\nclass IndexLookupSavingTest(keras_parameterized.TestCase,\n preprocessing_test_utils.PreprocessingLayerTest):\n\n def test_vocabulary_persistence_across_saving(self):\n vocab_data = [\"earth\", \"wind\", \"and\", \"fire\"]\n input_array = np.array([[\"earth\", \"wind\", \"and\", \"fire\"],\n [\"fire\", \"and\", \"earth\", \"michigan\"]])\n expected_output = [[2, 3, 4, 5], [5, 4, 2, 1]]\n\n # Build and validate a golden model.\n input_data = keras.Input(shape=(None,), dtype=dtypes.string)\n layer = get_layer_class()(\n max_tokens=None,\n num_oov_indices=1,\n mask_token=\"\",\n oov_token=\"[OOV]\",\n dtype=dtypes.string)\n layer.set_vocabulary(vocab_data)\n int_data = layer(input_data)\n model = keras.Model(inputs=input_data, outputs=int_data)\n output_dataset = model.predict(input_array)\n self.assertAllEqual(output_dataset, expected_output)\n\n # Save the model to disk.\n output_path = os.path.join(self.get_temp_dir(), \"tf_keras_saved_model\")\n model.save(output_path, save_format=\"tf\")\n\n # Delete the session and graph to ensure that the loaded model is generated\n # from scratch.\n # TODO(b/149526183): Can't clear session when TF2 is disabled.\n if tf2.enabled():\n keras.backend.clear_session()\n\n loaded_model = keras.models.load_model(\n output_path, custom_objects={\"IndexLookup\": get_layer_class()})\n\n # Ensure that the loaded model is unique (so that the save/load is real)\n self.assertIsNot(model, loaded_model)\n\n # Validate correctness of the new model.\n new_output_dataset = loaded_model.predict(input_array)\n self.assertAllEqual(new_output_dataset, expected_output)\n\n\n@keras_parameterized.run_all_keras_modes\nclass IndexLookupStringCombinerTest(\n keras_parameterized.TestCase,\n preprocessing_test_utils.PreprocessingLayerTest):\n\n def compare_text_accumulators(self, a, b, msg=None):\n if a is None or b is None:\n self.assertAllEqual(a, b, msg=msg)\n\n self.assertAllEqual(a.count_dict, b.count_dict, msg=msg)\n\n compare_accumulators = compare_text_accumulators\n\n def update_accumulator(self, accumulator, data):\n accumulator.count_dict.update(dict(zip(data[\"vocab\"], data[\"counts\"])))\n\n return accumulator\n\n def test_combiner_api_compatibility_int_mode(self):\n data = np.array([[\"earth\", \"wind\", \"and\", \"fire\"],\n [\"earth\", \"wind\", \"and\", \"michigan\"]])\n combiner = index_lookup._IndexLookupCombiner()\n expected_accumulator_output = {\n \"vocab\": np.array([\"and\", \"earth\", \"wind\", \"fire\", \"michigan\"]),\n \"counts\": np.array([2, 2, 2, 1, 1]),\n }\n expected_extract_output = {\n \"vocab\": np.array([\"wind\", \"earth\", \"and\", \"michigan\", \"fire\"]),\n \"idf_weights\": None,\n }\n expected_accumulator = combiner._create_accumulator()\n expected_accumulator = self.update_accumulator(expected_accumulator,\n expected_accumulator_output)\n self.validate_accumulator_serialize_and_deserialize(combiner, data,\n expected_accumulator)\n self.validate_accumulator_uniqueness(combiner, data)\n self.validate_accumulator_extract(combiner, data, expected_extract_output)\n\n # TODO(askerryryan): Add tests confirming equivalence to behavior of\n # existing tf.keras.preprocessing.text.Tokenizer.\n @parameterized.named_parameters(\n {\n \"testcase_name\":\n \"top_k_smaller_than_full_vocab\",\n \"data\":\n np.array([[\"earth\", \"wind\"], [\"fire\", \"wind\"], [\"and\"],\n [\"fire\", \"wind\"]]),\n \"vocab_size\":\n 3,\n \"expected_accumulator_output\": {\n \"vocab\": np.array([\"wind\", \"fire\", \"earth\", \"and\"]),\n \"counts\": np.array([3, 2, 1, 1]),\n },\n \"expected_extract_output\": {\n \"vocab\": np.array([\"wind\", \"fire\", \"earth\"]),\n \"idf_weights\": None,\n },\n },\n {\n \"testcase_name\":\n \"top_k_larger_than_full_vocab\",\n \"data\":\n np.array([[\"earth\", \"wind\"], [\"fire\", \"wind\"], [\"and\"],\n [\"fire\", \"wind\"]]),\n \"vocab_size\":\n 10,\n \"expected_accumulator_output\": {\n \"vocab\": np.array([\"wind\", \"fire\", \"earth\", \"and\"]),\n \"counts\": np.array([3, 2, 1, 1]),\n },\n \"expected_extract_output\": {\n \"vocab\": np.array([\"wind\", \"fire\", \"earth\", \"and\"]),\n \"idf_weights\": None,\n },\n },\n {\n \"testcase_name\":\n \"no_top_k\",\n \"data\":\n np.array([[\"earth\", \"wind\"], [\"fire\", \"wind\"], [\"and\"],\n [\"fire\", \"wind\"]]),\n \"vocab_size\":\n None,\n \"expected_accumulator_output\": {\n \"vocab\": np.array([\"wind\", \"fire\", \"earth\", \"and\"]),\n \"counts\": np.array([3, 2, 1, 1]),\n },\n \"expected_extract_output\": {\n \"vocab\": np.array([\"wind\", \"fire\", \"earth\", \"and\"]),\n \"idf_weights\": None,\n },\n },\n {\n \"testcase_name\": \"single_element_per_row\",\n \"data\": np.array([[\"earth\"], [\"wind\"], [\"fire\"], [\"wind\"], [\"and\"]]),\n \"vocab_size\": 3,\n \"expected_accumulator_output\": {\n \"vocab\": np.array([\"wind\", \"and\", \"earth\", \"fire\"]),\n \"counts\": np.array([2, 1, 1, 1]),\n },\n \"expected_extract_output\": {\n \"vocab\": np.array([\"wind\", \"fire\", \"earth\"]),\n \"idf_weights\": None,\n },\n },\n # Which tokens are retained are based on global frequency, and thus are\n # sensitive to frequency within a document. In contrast, because idf only\n # considers the presence of a token in a document, it is insensitive\n # to the frequency of the token within the document.\n {\n \"testcase_name\":\n \"retained_tokens_sensitive_to_within_document_frequency\",\n \"data\":\n np.array([[\"earth\", \"earth\"], [\"wind\", \"wind\"], [\"fire\", \"fire\"],\n [\"wind\", \"wind\"], [\"and\", \"michigan\"]]),\n \"vocab_size\":\n 3,\n \"expected_accumulator_output\": {\n \"vocab\": np.array([\"wind\", \"earth\", \"fire\", \"and\", \"michigan\"]),\n \"counts\": np.array([4, 2, 2, 1, 1]),\n },\n \"expected_extract_output\": {\n \"vocab\": np.array([\"wind\", \"fire\", \"earth\"]),\n \"idf_weights\": None,\n },\n })\n def test_combiner_computation(self, data, vocab_size,\n expected_accumulator_output,\n expected_extract_output):\n combiner = index_lookup._IndexLookupCombiner(vocab_size=vocab_size)\n expected_accumulator = combiner._create_accumulator()\n expected_accumulator = self.update_accumulator(expected_accumulator,\n expected_accumulator_output)\n self.validate_accumulator_computation(combiner, data, expected_accumulator)\n self.validate_accumulator_extract(combiner, data, expected_extract_output)\n\n\n@keras_parameterized.run_all_keras_modes\nclass IndexLookupIntCombinerTest(keras_parameterized.TestCase,\n preprocessing_test_utils.PreprocessingLayerTest\n ):\n\n def compare_text_accumulators(self, a, b, msg=None):\n if a is None or b is None:\n self.assertAllEqual(a, b, msg=msg)\n\n self.assertAllEqual(a.count_dict, b.count_dict, msg=msg)\n\n compare_accumulators = compare_text_accumulators\n\n def update_accumulator(self, accumulator, data):\n accumulator.count_dict.update(dict(zip(data[\"vocab\"], data[\"counts\"])))\n\n return accumulator\n\n def test_combiner_api_compatibility_int_mode(self):\n data = np.array([[42, 1138, 725, 1729], [42, 1138, 725, 203]])\n combiner = index_lookup._IndexLookupCombiner()\n expected_accumulator_output = {\n \"vocab\": np.array([1138, 725, 42, 1729, 203]),\n \"counts\": np.array([2, 2, 2, 1, 1]),\n }\n expected_extract_output = {\n \"vocab\": np.array([1138, 725, 42, 1729, 203]),\n \"idf_weights\": None,\n }\n expected_accumulator = combiner._create_accumulator()\n expected_accumulator = self.update_accumulator(expected_accumulator,\n expected_accumulator_output)\n self.validate_accumulator_serialize_and_deserialize(combiner, data,\n expected_accumulator)\n self.validate_accumulator_uniqueness(combiner, data)\n self.validate_accumulator_extract(combiner, data, expected_extract_output)\n\n # TODO(askerryryan): Add tests confirming equivalence to behavior of\n # existing tf.keras.preprocessing.text.Tokenizer.\n @parameterized.named_parameters(\n {\n \"testcase_name\": \"top_k_smaller_than_full_vocab\",\n \"data\": np.array([[42, 1138], [1729, 1138], [725], [1729, 1138]]),\n \"vocab_size\": 3,\n \"expected_accumulator_output\": {\n \"vocab\": np.array([1138, 1729, 725, 42]),\n \"counts\": np.array([3, 2, 1, 1]),\n },\n \"expected_extract_output\": {\n \"vocab\": np.array([1138, 1729, 725]),\n \"idf_weights\": None,\n },\n },\n {\n \"testcase_name\": \"top_k_larger_than_full_vocab\",\n \"data\": np.array([[42, 1138], [1729, 1138], [725], [1729, 1138]]),\n \"vocab_size\": 10,\n \"expected_accumulator_output\": {\n \"vocab\": np.array([1138, 1729, 725, 42]),\n \"counts\": np.array([3, 2, 1, 1]),\n },\n \"expected_extract_output\": {\n \"vocab\": np.array([1138, 1729, 725, 42]),\n \"idf_weights\": None,\n },\n },\n {\n \"testcase_name\": \"no_top_k\",\n \"data\": np.array([[42, 1138], [1729, 1138], [725], [1729, 1138]]),\n \"vocab_size\": None,\n \"expected_accumulator_output\": {\n \"vocab\": np.array([1138, 1729, 725, 42]),\n \"counts\": np.array([3, 2, 1, 1]),\n },\n \"expected_extract_output\": {\n \"vocab\": np.array([1138, 1729, 725, 42]),\n \"idf_weights\": None,\n },\n },\n {\n \"testcase_name\": \"single_element_per_row\",\n \"data\": np.array([[42], [1138], [1729], [1138], [725]]),\n \"vocab_size\": 3,\n \"expected_accumulator_output\": {\n \"vocab\": np.array([1138, 1729, 725, 42]),\n \"counts\": np.array([2, 1, 1, 1]),\n },\n \"expected_extract_output\": {\n \"vocab\": np.array([1138, 1729, 725]),\n \"idf_weights\": None,\n },\n },\n # Which tokens are retained are based on global frequency, and thus are\n # sensitive to frequency within a document. In contrast, because idf only\n # considers the presence of a token in a document, it is insensitive\n # to the frequency of the token within the document.\n {\n \"testcase_name\":\n \"retained_tokens_sensitive_to_within_document_frequency\",\n \"data\":\n np.array([[42, 42], [1138, 1138], [1729, 1729], [1138, 1138],\n [725, 203]]),\n \"vocab_size\":\n 3,\n \"expected_accumulator_output\": {\n \"vocab\": np.array([1138, 42, 1729, 725, 203]),\n \"counts\": np.array([4, 2, 2, 1, 1]),\n },\n \"expected_extract_output\": {\n \"vocab\": np.array([1138, 1729, 42]),\n \"idf_weights\": None,\n },\n })\n def test_combiner_computation(self, data, vocab_size,\n expected_accumulator_output,\n expected_extract_output):\n combiner = index_lookup._IndexLookupCombiner(vocab_size=vocab_size)\n expected_accumulator = combiner._create_accumulator()\n expected_accumulator = self.update_accumulator(expected_accumulator,\n expected_accumulator_output)\n self.validate_accumulator_computation(combiner, data, expected_accumulator)\n self.validate_accumulator_extract(combiner, data, expected_extract_output)\n\n\nif __name__ == \"__main__\":\n test.main()\n" ]
[ [ "tensorflow.python.data.util.nest.map_structure_up_to", "tensorflow.python.ops.gen_dataset_ops.window_dataset", "tensorflow.python.data.util.structure.type_spec_from_value", "tensorflow.python.ops.gen_dataset_ops.batch_dataset_v2", "tensorflow.python.ops.gen_dataset_ops.dataset_cardinality", "tensorflow.python.ops.gen_experimental_dataset_ops.unbatch_dataset", "tensorflow.python.compat.compat.forward_compatible", "tensorflow.python.ops.gen_dataset_ops.take_dataset", "tensorflow.python.framework.smart_cond.smart_constant_value", "tensorflow.python.ops.string_ops.reduce_join", "tensorflow.python.util.tf_export.tf_export", "tensorflow.python.data.util.structure.from_compatible_tensor_list", "tensorflow.python.data.util.nest.pack_sequence_as", "tensorflow.python.ops.gen_dataset_ops.make_iterator", "tensorflow.python.data.util.structure.normalize_element", "tensorflow.python.ops.gen_dataset_ops.iterator_v2", "tensorflow.python.eager.context.eager_mode", "tensorflow.python.ops.gen_dataset_ops.concatenate_dataset", "tensorflow.python.data.util.convert.optional_param_to_tensor", "tensorflow.python.ops.gen_dataset_ops.shard_dataset", "tensorflow.python.util.deprecation.deprecated_args", "numpy.array", "tensorflow.python.framework.random_seed.set_random_seed", "tensorflow.python.ops.gen_dataset_ops.prefetch_dataset", "tensorflow.python.data.util.options.merge_options", "tensorflow.python.ops.gen_dataset_ops.repeat_dataset", "tensorflow.python.ops.gen_dataset_ops.range_dataset", "tensorflow.python.ops.gen_experimental_dataset_ops.private_thread_pool_dataset", "tensorflow.python.data.experimental.ops.distribute_options.ExternalStatePolicy._to_proto", "numpy.iinfo", "tensorflow.python.framework.random_seed.get_seed", "tensorflow.python.ops.gen_dataset_ops.parallel_interleave_dataset_v4", "tensorflow.python.ops.gen_experimental_dataset_ops.max_intra_op_parallelism_dataset", "tensorflow.python.ops.gen_dataset_ops.dummy_seed_generator", "tensorflow.python.data.util.structure.get_flat_tensor_types", "tensorflow.python.data.util.structure.get_flat_tensor_specs", "tensorflow.python.data.util.structure.get_flat_tensor_shapes", "tensorflow.python.framework.ops.colocate_with", "tensorflow.python.framework.dtypes.as_dtype", "tensorflow.python.data.util.structure.convert_legacy_structure", "tensorflow.python.framework.ops.convert_to_tensor", "tensorflow.python.data.util.nest.flatten", "tensorflow.python.ops.gen_dataset_ops.dummy_memory_cache", "tensorflow.python.ops.gen_experimental_dataset_ops.set_stats_aggregator_dataset", "tensorflow.core.framework.dataset_options_pb2.Options", "tensorflow.python.framework.tensor_spec.TensorSpec", "tensorflow.python.framework.tensor_shape.Dimension", "tensorflow.python.ops.gen_dataset_ops.parallel_batch_dataset", "tensorflow.python.data.util.options.create_option", "tensorflow.python.framework.ops.convert_n_to_tensor", "tensorflow.python.ops.script_ops.FuncRegistry._convert", "tensorflow.python.ops.gen_dataset_ops.flat_map_dataset", "tensorflow.python.ops.array_ops.shape", "tensorflow.python.framework.tensor_util.constant_value_as_shape", "tensorflow.python.data.ops.iterator_ops.OwnedIterator", "tensorflow.python.data.util.structure.to_batched_tensor_list", "tensorflow.python.eager.context.executing_eagerly", "tensorflow.python.ops.gen_dataset_ops.sparse_tensor_slice_dataset", "tensorflow.python.ops.array_ops.identity", "tensorflow.python.framework.ops.NotDifferentiable", "tensorflow.python.framework.function.Defun", "tensorflow.python.training.tracking.tracking.ResourceTracker", "tensorflow.python.eager.def_function.functions_run_eagerly", "tensorflow.python.data.util.nest.is_sequence", "tensorflow.python.data.util.structure.are_compatible", "tensorflow.python.framework.tensor_util.constant_value", "tensorflow.python.data.util.traverse.obtain_capture_by_value_ops", "tensorflow.python.ops.gen_dataset_ops.shuffle_dataset", "tensorflow.python.ops.script_ops._eager_py_func", "tensorflow.python.data.util.random_seed.get_seed", "tensorflow.python.training.tracking.tracking.resource_tracker_scope", "tensorflow.python.data.util.nest.map_structure", "tensorflow.python.ops.gen_dataset_ops.one_shot_iterator", "tensorflow.python.data.experimental.ops.distribute_options.ExternalStatePolicy._from_proto", "tensorflow.python.framework.ops.get_default_graph", "tensorflow.python.framework.ops.name_scope", "tensorflow.python.ops.gen_io_ops.matching_files", "tensorflow.python.framework.auto_control_deps_utils.get_read_write_resource_inputs", "tensorflow.python.tf2.enabled", "tensorflow.python.data.experimental.ops.optimization_options.OptimizationOptions", "tensorflow.python.ops.gen_dataset_ops.interleave_dataset", "tensorflow.python.ops.script_ops.numpy_function", "tensorflow.python.ops.gen_dataset_ops.model_dataset", "tensorflow.python.framework.tensor_shape.TensorShape", "tensorflow.python.ops.gen_dataset_ops.cache_dataset", "tensorflow.python.ops.gen_dataset_ops.filter_dataset", "tensorflow.python.ops.gen_dataset_ops.skip_dataset", "tensorflow.python.ops.gen_dataset_ops.parallel_map_dataset_v2", "tensorflow.python.ops.gen_dataset_ops.optimize_dataset_v2", "tensorflow.python.framework.ops.device", "tensorflow.python.ops.control_flow_ops.Assert", "tensorflow.python.util.function_utils.get_func_name", "tensorflow.python.framework.ops.inside_function", "tensorflow.python.ops.gen_dataset_ops.dataset_to_graph", "tensorflow.python.data.util.options.graph_rewrites", "tensorflow.python.data.util.structure.to_tensor_list", "tensorflow.python.framework.ops.control_dependencies", "tensorflow.python.util.nest.map_structure", "tensorflow.python.util.deprecation.deprecated", "tensorflow.python.data.util.nest.flatten_up_to", "tensorflow.python.framework.ops.uid", "tensorflow.python.ops.gen_dataset_ops.dataset_to_graph_v2", "tensorflow.python.ops.gen_dataset_ops.map_dataset", "tensorflow.python.framework.tensor_shape.as_shape", "tensorflow.core.framework.graph_pb2.GraphDef", "tensorflow.python.framework.constant_op.constant" ], [ "tensorflow.python.util._pywrap_util_port.IsBuiltWithNvcc", "numpy.all", "tensorflow.python.util.tf_decorator.make_decorator", "tensorflow.python.eager.context.context", "tensorflow.python.client.pywrap_tf_session.TF_SetXlaAutoJitMode", "numpy.where", "tensorflow.python.ops.gradients_impl.gradients", "tensorflow.python.util.tf_export.tf_export", "tensorflow.python.util.protobuf.compare.assertProtoEqual", "numpy.less_equal", "tensorflow.python.training.server_lib.Server", "tensorflow.python.ops.math_ops.matmul", "tensorflow.python.framework.gpu_util.compute_capability_from_device_desc", "tensorflow.python.framework.ops.dismantle_graph", "tensorflow.python.framework.ops.reset_default_graph", "tensorflow.python.util._pywrap_util_port.IsBuiltWithROCm", "tensorflow.python.eager.context.eager_mode", "tensorflow.python.platform.tf_logging.warning", "numpy.array", "tensorflow.python.framework.random_seed.set_random_seed", "tensorflow.python.util.protobuf.compare.ProtoEq", "tensorflow.python.platform.googletest.GetTempDir", "tensorflow.python.framework.tensor_util.is_tf_type", "tensorflow.python.util.nest.flatten", "tensorflow.python.client.device_lib.list_local_devices", "tensorflow.python.util.tf_inspect.ismodule", "tensorflow.python.platform._pywrap_stacktrace_handler.InstallStacktraceHandler", "tensorflow.python.ops.array_ops.transpose", "numpy.allclose", "numpy.less", "tensorflow.python.eager.context.execution_mode", "tensorflow.python.client.pywrap_tf_session.TF_SetXlaConstantFoldingDisabled", "tensorflow.python.framework.ops.get_default_session", "numpy.size", "numpy.greater_equal", "numpy.min", "tensorflow.python.eager.def_function.function", "tensorflow.python.util.tf_inspect.isfunction", "tensorflow.python.framework.is_mlir_bridge_test_true.is_mlir_bridge_enabled", "numpy.ndim", "tensorflow.python.util.tf_inspect.isclass", "tensorflow.python.util._pywrap_util_port.IsGoogleCudaEnabled", "tensorflow.python.framework.ops._default_graph_stack.reset", "tensorflow.python.client.pywrap_tf_session.TF_SetXlaEnableLazyCompilation", "tensorflow.python.util.compat.as_bytes", "tensorflow.python.util._pywrap_util_port.IsMklEnabled", "tensorflow.python.platform.tf_logging.error", "numpy.issubdtype", "tensorflow.python.framework.config.tensor_float_32_execution_enabled", "tensorflow.python.eager.backprop.GradientTape", "tensorflow.python.framework.config.enable_tensor_float_32_execution", "tensorflow.python.eager.context.executing_eagerly", "numpy.greater", "tensorflow.python.framework.ops.get_collection", "tensorflow.python.util.tf_inspect.getframeinfo", "tensorflow.python.eager.def_function.functions_run_eagerly", "tensorflow.python.util.compat.as_str", "numpy.logical_not", "tensorflow.python.client.pywrap_tf_session.TF_SetXlaMinClusterSize", "numpy.isnan", "tensorflow.python.framework.tfrt_utils.enabled", "tensorflow.python.ops.ragged.ragged_tensor.is_ragged", "tensorflow.python.framework.device.canonical_name", "numpy.transpose", "tensorflow.python.util._pywrap_util_port.IsBuiltWithXLA", "tensorflow.python.framework.sparse_tensor.is_sparse", "tensorflow.python.framework.ops.Graph", "numpy.linalg.norm", "tensorflow.python.framework.ops.get_default_graph", "tensorflow.python.ops.array_ops.reshape", "tensorflow.python.util.tf_inspect.isframe", "tensorflow.python.tf2.enabled", "tensorflow.python.framework.ops.get_collection_proto_type", "numpy.max", "tensorflow.python.framework.ops.device", "tensorflow.python.util._pywrap_util_port.GpuSupportsHalfMatMulAndConv", "tensorflow.python.framework.ops.inside_function", "tensorflow.python.framework.is_xla_test_true.is_xla_enabled", "tensorflow.python.eager.context.graph_mode", "tensorflow.python.util.nest.map_structure", "tensorflow.python.util.deprecation.deprecated", "tensorflow.python.ops.math_ops.cast", "tensorflow.python.framework.importer.import_graph_def", "tensorflow.python.eager.tape.distribution_strategy_context.get_strategy", "tensorflow.python.ops.script_ops.py_func", "tensorflow.python.training.server_lib.ClusterSpec", "tensorflow.python.framework.ops.has_default_graph", "tensorflow.python.compat.compat.forward_compatibility_horizon", "tensorflow.python.eager.def_function.run_functions_eagerly", "numpy.abs", "numpy.random.seed", "tensorflow.python.client.pywrap_tf_session.TF_SetTfXlaCpuGlobalJit", "tensorflow.python.client.pywrap_tf_session.TF_GetXlaConstantFoldingDisabled", "tensorflow.python.platform.tf_logging.info", "tensorflow.core.framework.graph_pb2.GraphDef" ], [ "tensorflow.python.data.ops.dataset_ops.Dataset.from_tensors", "tensorflow.python.framework.tensor_shape.TensorShape", "tensorflow.python.platform.gfile.GFile", "tensorflow.python.keras.utils.generic_utils.CustomObjectScope", "tensorflow.python.keras.layers.preprocessing.index_lookup._IndexLookupCombiner", "tensorflow.python.eager.context.executing_eagerly", "tensorflow.python.ops.lookup_ops.TextFileInitializer", "tensorflow.python.framework.sparse_tensor.SparseTensor", "tensorflow.python.platform.test.main", "tensorflow.python.keras.backend.get_session", "tensorflow.python.keras.saving.save.save_model", "tensorflow.python.keras.keras_parameterized.run_all_keras_modes", "tensorflow.python.data.ops.dataset_ops.Dataset.from_tensor_slices", "tensorflow.python.keras.Model", "tensorflow.python.ops.ragged.ragged_factory_ops.constant", "tensorflow.python.keras.testing_utils.layer_test", "numpy.array", "tensorflow.python.keras.Input", "tensorflow.python.tf2.enabled", "tensorflow.python.keras.backend.clear_session" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "1.12", "2.6", "2.2", "1.13", "2.3", "2.4", "1.4", "2.9", "1.5", "1.7", "2.5", "0.12", "1.0", "2.8", "1.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "2.7", "2.6", "2.4", "2.3", "2.9", "2.5", "2.2", "2.10" ] } ]
artsobolev/IWHVI
[ "3a8b5631fe5b08587c594bd0aac43f84dc261579" ]
[ "hierarchical_vae/utils.py" ]
[ "import numpy as np\nimport scipy as sp\nimport scipy.special\nfrom tqdm import tqdm\n\nimport utils\nfrom .model import HierarchicalVAE\n\n\ndef calculate_evidence(sess, data, iwhvae, iwae_samples, iwhvi_samples, batch_size, n_repeats,\n tau_force_prior=False, tqdm_desc=None):\n losses = utils.batched_run(sess, data, -iwhvae.loss, lambda x_batch, y_batch: {\n iwhvae.input_x: x_batch,\n iwhvae.output_y: y_batch,\n iwhvae.k_iwhvi_samples: iwhvi_samples,\n iwhvae.m_iwae_samples: iwae_samples,\n iwhvae.tau_force_prior: tau_force_prior\n }, batch_size, n_repeats, tqdm_desc)\n\n return np.array(list(losses))\n\n\ndef calculate_reused_sivi_bound(sess, data, iwhvae, iwae_samples, iwhvi_samples, batch_size_x, n_repeats,\n batch_size_m=None, tqdm_desc=None):\n batch_size_x = min(batch_size_x, data.num_examples) # Fix\n x_samples = data.num_examples\n total_batches_x = (x_samples - 1) // batch_size_x + 1\n\n if batch_size_m is None:\n batch_size_m = iwae_samples\n total_batches_m = (iwae_samples - 1) // batch_size_m + 1\n\n res = np.zeros(n_repeats)\n with tqdm(total=n_repeats * total_batches_x * (total_batches_m + 1), unit='run', desc=tqdm_desc) as tqdm_t:\n for rep in range(n_repeats):\n offset_x = 0\n mean_elbo = 0\n for _ in range(total_batches_x):\n batch = data.next_batch(batch_size_x)\n binarized_batch_x, binarized_batch_y = utils.binarize_batch(batch)\n actual_batch_size_x = binarized_batch_x.shape[0]\n\n psi_rest = sess.run(iwhvae._reuse_psi_rest, feed_dict={\n iwhvae.input_x: binarized_batch_x,\n iwhvae.k_iwhvi_samples: iwhvi_samples\n })\n alphas = np.zeros((iwae_samples, actual_batch_size_x))\n offset_m = 0\n for _ in range(total_batches_m):\n m_samples = min(iwae_samples - offset_m, batch_size_m)\n alpha = sess.run(iwhvae._sivi_reused_alpha, {\n iwhvae.input_x: binarized_batch_x,\n iwhvae.output_y: binarized_batch_y,\n iwhvae.m_iwae_samples: m_samples,\n iwhvae.k_iwhvi_samples: iwhvi_samples,\n iwhvae._reuse_psi_rest: psi_rest\n })\n alphas[offset_m:offset_m + m_samples, :] = alpha\n offset_m += m_samples\n tqdm_t.update()\n\n elbo = np.mean(sp.special.logsumexp(alphas, axis=0) - np.log(iwae_samples))\n offset_x += actual_batch_size_x\n mean_elbo += (elbo - mean_elbo) * actual_batch_size_x / offset_x\n tqdm_t.update()\n\n res[rep] = mean_elbo\n return res\n\n\ndef batched_calculate_evidence_q_gap_kls(sess, data, iwhvae, iwae_samples, iwhvi_samples, batch_size_x, n_repeats,\n tau_force_prior=False, batch_size_m=None, tqdm_desc=None):\n\n batch_size_x = min(batch_size_x, data.num_examples) # Fix\n x_samples = data.num_examples\n total_batches_x = (x_samples - 1) // batch_size_x + 1\n\n if batch_size_m is None:\n batch_size_m = iwae_samples\n total_batches_m = (iwae_samples - 1) // batch_size_m + 1\n\n aux = [iwhvae._q_gap_raw, *iwhvae.bounds]\n aux_size = len(aux)\n res = np.zeros((1 + aux_size, n_repeats))\n with tqdm(total=n_repeats * total_batches_x, unit='run', desc=tqdm_desc) as tqdm_t:\n for rep in range(n_repeats):\n rep_res = np.zeros((1 + aux_size, x_samples))\n offset_x = 0\n for _ in range(total_batches_x):\n batch = data.next_batch(batch_size_x)\n binarized_batch_x, binarized_batch_y = utils.binarize_batch(batch)\n actual_batch_size_x = binarized_batch_x.shape[0]\n\n zs = np.zeros((iwae_samples, actual_batch_size_x, iwhvae.z_dim))\n res_aux = np.zeros((aux_size, iwae_samples, actual_batch_size_x))\n offset_m = 0\n for _ in range(total_batches_m):\n m_samples = min(iwae_samples - offset_m, batch_size_m)\n aux_vals = sess.run(aux + [iwhvae._z], {\n iwhvae.input_x: binarized_batch_x,\n iwhvae.output_y: binarized_batch_y,\n iwhvae.m_iwae_samples: m_samples,\n iwhvae.k_iwhvi_samples: iwhvi_samples,\n iwhvae.tau_force_prior: tau_force_prior\n })\n zs[offset_m:offset_m + m_samples] = aux_vals[-1]\n res_aux[:, offset_m:offset_m + m_samples, :] = aux_vals[:-1]\n offset_m += m_samples\n\n elbos = sess.run(iwhvae.elbo, {\n iwhvae.input_x: binarized_batch_x,\n iwhvae.output_y: binarized_batch_y,\n iwhvae.m_iwae_samples: iwae_samples,\n iwhvae.k_iwhvi_samples: iwhvi_samples,\n iwhvae.tau_force_prior: tau_force_prior,\n iwhvae._z: zs,\n iwhvae.bounds[1]: res_aux[aux.index(iwhvae.bounds[1])]\n })\n\n rep_res[:, offset_x:offset_x + actual_batch_size_x] = [\n elbos,\n *np.mean(res_aux, axis=1)\n ]\n offset_x += actual_batch_size_x\n tqdm_t.update()\n\n res[:, rep] = np.mean(rep_res, axis=1)\n return res\n\n\ndef batched_calculate_p_gap(sess, data, iwhvae, iwae_samples, iwhvi_samples, batch_size_x,\n n_repeats, tau_force_prior, batch_size_m=None, tqdm_desc=None):\n\n batch_size_x = min(batch_size_x, data.num_examples) # Fix\n x_samples = data.num_examples\n total_batches_x = (x_samples - 1) // batch_size_x + 1\n\n if batch_size_m is None:\n batch_size_m = iwae_samples\n total_batches_m = (iwae_samples - 1) // batch_size_m + 1\n\n p_gaps = np.zeros(n_repeats)\n with tqdm(total=n_repeats * total_batches_x, unit='run', desc=tqdm_desc) as tqdm_t:\n for rep in range(n_repeats):\n mean_p_gap = 0\n offset_x = 0\n for _ in range(total_batches_x):\n batch = data.next_batch(batch_size_x)\n binarized_batch_x, binarized_batch_y = utils.binarize_batch(batch)\n actual_batch_size_x = binarized_batch_x.shape[0]\n\n alphas = np.zeros((iwae_samples, actual_batch_size_x))\n offset_m = 0\n for _ in range(total_batches_m):\n m_samples = min(iwae_samples - offset_m, batch_size_m)\n alpha = sess.run(iwhvae._alpha, {\n iwhvae.input_x: binarized_batch_x,\n iwhvae.output_y: binarized_batch_y,\n iwhvae.m_iwae_samples: m_samples,\n iwhvae.k_iwhvi_samples: iwhvi_samples,\n iwhvae.tau_force_prior: tau_force_prior\n })\n\n alphas[offset_m:offset_m + m_samples] = alpha\n offset_m += m_samples\n\n batch_p_gap = sp.special.logsumexp(alphas, axis=0) - np.log(alphas.shape[0]) - np.mean(alphas, axis=0)\n batch_mean_p_gap = np.mean(batch_p_gap, axis=0)\n offset_x += actual_batch_size_x\n mean_p_gap += (batch_mean_p_gap - mean_p_gap) * actual_batch_size_x / offset_x\n\n tqdm_t.update()\n\n p_gaps[rep] = mean_p_gap\n return p_gaps\n\n\ndef calculate_mi_bounds_on_p(sess, vae, n_samples, m_iwae_samples, iwae_batch_size, n_repeats, tqdm_desc):\n res = []\n with tqdm(total=n_repeats * n_samples * (m_iwae_samples + 1), desc=tqdm_desc) as tqdm_t:\n mi_lower_bound_per_sample = []\n mi_upper_bound_per_sample = []\n\n for _ in range(n_repeats):\n for _ in range(n_samples):\n x, hvm_term, log_p_x_z = sess.run([vae._mi_p_x, vae._mi_p_hvm_term, vae._mi_p_log_p_x_z])\n tqdm_t.update(1)\n\n elbos = []\n m_offset = 0\n while m_offset < m_iwae_samples:\n batch_size = min(iwae_batch_size, m_iwae_samples - m_offset)\n m_offset += batch_size\n\n elbos_subset = sess.run(vae._mi_p_elbos, feed_dict={vae._mi_p_x: x, vae.m_iwae_samples: batch_size})\n elbos.extend(elbos_subset)\n\n tqdm_t.update(batch_size)\n\n assert len(elbos) == m_iwae_samples\n log_p_lower_bound = sp.special.logsumexp(elbos) - np.log(m_iwae_samples)\n log_p_upper_bound = sp.special.logsumexp(elbos + [hvm_term]) - np.log(m_iwae_samples + 1)\n\n mi_lower_bound_per_sample.append(log_p_x_z - log_p_upper_bound)\n mi_upper_bound_per_sample.append(log_p_x_z - log_p_lower_bound)\n\n res.append((np.mean(mi_lower_bound_per_sample), np.mean(mi_upper_bound_per_sample)))\n tqdm_t.set_description(tqdm_desc + ', cur. est.: {:.3f} <= MI <= {:.3f}'.format(*np.mean(res, axis=0)))\n\n return np.array(res).T\n\n\ndef calculate_mi_bounds_on_q(sess, vae, data, batch_size_x, m_iwae_samples, iwae_batch_size, n_repeats, tqdm_desc):\n if iwae_batch_size is None:\n iwae_batch_size = m_iwae_samples\n\n total_batches_x = (data.num_examples - 1) // batch_size_x + 1\n res = []\n with tqdm(total=n_repeats * data.num_examples * (m_iwae_samples + 1), desc=tqdm_desc) as tqdm_t:\n mi_lower_bound_per_sample = []\n mi_upper_bound_per_sample = []\n\n for _ in range(n_repeats):\n for _ in range(total_batches_x):\n binarized_x, _ = utils.binarize_batch(data.next_batch(batch_size_x))\n actual_batch_size_x = binarized_x.shape[0]\n\n z, hvm_term, log_q_z_psi = sess.run([vae._mi_q_z, vae._mi_q_hvm_term, vae._mi_q_log_q_z_psi],\n feed_dict={vae.input_x: binarized_x})\n tqdm_t.update(actual_batch_size_x)\n\n elbos = np.zeros((m_iwae_samples, actual_batch_size_x))\n m_offset = 0\n while m_offset < m_iwae_samples:\n batch_size_m = min(iwae_batch_size, m_iwae_samples - m_offset)\n\n elbos_subset = sess.run(vae._mi_q_elbos, feed_dict={\n vae._mi_q_z: z,\n vae.m_iwae_samples: batch_size_m,\n vae.input_x: binarized_x\n })\n assert elbos_subset.shape == (batch_size_m, actual_batch_size_x), elbos_subset.shape\n elbos[m_offset:m_offset+batch_size_m, :] = elbos_subset\n\n tqdm_t.update(batch_size_m * actual_batch_size_x)\n m_offset += batch_size_m\n\n extended_elbos = np.concatenate([hvm_term[None, :], elbos], axis=0)\n\n assert len(elbos) == m_iwae_samples\n log_p_lower_bound = sp.special.logsumexp(elbos, axis=0) - np.log(m_iwae_samples)\n log_p_upper_bound = sp.special.logsumexp(extended_elbos, axis=0) - np.log(m_iwae_samples + 1)\n\n mi_lower_bound_per_sample.append(log_q_z_psi - log_p_upper_bound)\n mi_upper_bound_per_sample.append(log_q_z_psi - log_p_lower_bound)\n\n res.append((np.mean(mi_lower_bound_per_sample), np.mean(mi_upper_bound_per_sample)))\n tqdm_t.set_description(tqdm_desc + ', cur. est.: {:.3f} <= MI <= {:.3f}'.format(*np.mean(res, axis=0)))\n\n return np.array(res).T\n\n\ndef calculate_kl_tau_q(sess, data, iwhvae, n_samples, batch_size, n_repeats, tau_force_prior=False, tqdm_desc=None):\n kls = utils.batched_run(\n sess, data, iwhvae.kl_tau_q,\n lambda x_batch, y_batch: {\n iwhvae.input_x: x_batch,\n iwhvae.output_y: y_batch,\n iwhvae.m_iwae_samples: n_samples,\n iwhvae.tau_force_prior: tau_force_prior\n },\n batch_size, n_repeats, tqdm_desc)\n\n return np.array(list(kls))\n\n\ndef calculate_q_gap(sess, data, iwhvae, m_samples, k_iwhvi_samples, batch_size, n_repeats,\n tau_force_prior=False, tqdm_desc=None):\n gaps = utils.batched_run(sess, data, iwhvae.q_gap, lambda x_batch, y_batch: {\n iwhvae.input_x: x_batch,\n iwhvae.output_y: y_batch,\n iwhvae.m_iwae_samples: m_samples,\n iwhvae.k_iwhvi_samples: k_iwhvi_samples,\n iwhvae.tau_force_prior: tau_force_prior\n }, batch_size, n_repeats, tqdm_desc)\n\n return np.array(list(gaps))\n\n\ndef calculate_kl_bounds(sess, data, iwhvae, m_samples, k_iwhvi_samples, batch_size, n_repeats,\n tau_force_prior=False, tqdm_desc=None):\n bounds = utils.batched_run(sess, data, [iwhvae.kl_lower_bound, iwhvae.kl_upper_bound], lambda x_batch, y_batch: {\n iwhvae.input_x: x_batch,\n iwhvae.output_y: y_batch,\n iwhvae.m_iwae_samples: m_samples,\n iwhvae.k_iwhvi_samples: k_iwhvi_samples,\n iwhvae.tau_force_prior: tau_force_prior\n }, batch_size, n_repeats, tqdm_desc)\n\n avg_bounds = np.array(list(bounds))\n return avg_bounds[:, 0], avg_bounds[:, 1]\n\n\ndef add_model_args(argparser):\n argparser.add_argument('--z_dim', type=int, default=10)\n argparser.add_argument('--noise_dim', type=int, default=10)\n\n argparser.add_argument('--decoder_arch', type=int, nargs='*', default=[200, 200])\n argparser.add_argument('--encoder_arch', type=int, nargs='*', default=[200, 200])\n argparser.add_argument('--encoder_noise_arch', type=int, nargs='*', default=[])\n argparser.add_argument('--tau_arch', type=int, nargs='*', default=[200, 200])\n\n argparser.add_argument('--tau_gate_bias', type=float, default=np.nan)\n argparser.add_argument('--encoder_student', action='store_true')\n argparser.add_argument('--tau_student', action='store_true')\n argparser.add_argument('--batch_norm', action='store_true')\n\n\ndef get_model(args):\n return HierarchicalVAE(\n 28 * 28, 28 * 28, args.noise_dim, args.z_dim,\n args.decoder_arch, args.encoder_arch, args.encoder_noise_arch, args.tau_arch,\n args.tau_gate_bias, args.encoder_student, args.tau_student, args.batch_norm)\n" ]
[ [ "numpy.log", "numpy.concatenate", "numpy.mean", "numpy.array", "numpy.zeros", "scipy.special.logsumexp" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.6", "1.10", "1.4", "1.9", "0.19", "1.5", "1.2", "1.7", "1.0", "1.3", "1.8" ], "tensorflow": [] } ]
ProjetEtudeMLFI/TensorFI
[ "961a0205ec90935a238c58112e8119c34a70ba7c", "3d75830ff202fdf98cf28acd842209ad7f6e6e2a" ]
[ "Tests/nearest_neighbor.py", "experimentalTest/preprocessing.py" ]
[ "#!/usr/bin/python\n'''\nA nearest neighbor learning algorithm example using TensorFlow library.\nThis example is using the MNIST database of handwritten digits\n(http://yann.lecun.com/exdb/mnist/)\n\nAuthor: Aymeric Damien\nProject: https://github.com/aymericdamien/TensorFlow-Examples/\n'''\n\nfrom __future__ import print_function\n\nimport numpy as np\nimport tensorflow as tf\nimport TensorFI as ti\n\n# Import MNIST data\nfrom tensorflow.examples.tutorials.mnist import input_data\nmnist = input_data.read_data_sets(\"/tmp/data/\", one_hot=True)\n\n# In this example, we limit mnist data\nXtr, Ytr = mnist.train.next_batch(5000) #5000 for training (nn candidates)\nXte, Yte = mnist.test.next_batch(200) #200 for testing\n\n# tf Graph Input\nxtr = tf.placeholder(\"float\", [None, 784])\nxte = tf.placeholder(\"float\", [784])\n\n# Nearest Neighbor calculation using L1 Distance\n# Calculate L1 Distance\ndistance = tf.reduce_sum(tf.abs(tf.add(xtr, tf.negative(xte))),\n reduction_indices=1)\n# Prediction: Get min distance index (Nearest neighbor)\npred = tf.arg_min(distance, 0)\n\naccuracy = 0.\n\n# Initialize the variables (i.e. assign their default value)\ninit = tf.global_variables_initializer()\n\n# Start training\nwith tf.compat.v1.Session() as sess:\n\n # Run the initializer\n sess.run(init)\n\n # Add the fault injection code here to instrument the graph\n # We start injecting the fault right away here unlike earlier\n fi = ti.TensorFI(sess, name=\"NearestNeighbor\", logLevel=50)\n\n # loop over test data\n for i in range(len(Xte)):\n # Get nearest neighbor\n nn_index = sess.run(pred, feed_dict={xtr: Xtr, xte: Xte[i, :]})\n # Get nearest neighbor class label and compare it to its true label\n print(\"Test\", i, \"Prediction:\", np.argmax(Ytr[nn_index]), \\\n \"True Class:\", np.argmax(Yte[i]))\n # Calculate accuracy\n if np.argmax(Ytr[nn_index]) == np.argmax(Yte[i]):\n accuracy += 1. / len(Xte)\n print(\"Accuracy:\", accuracy)\n\n # Make the log files in TensorBoard\n logs_path = \"./logs\"\n logWriter = tf.summary.FileWriter(logs_path, sess.graph)\n", "# Import required libraries\nfrom sklearn.model_selection import train_test_split\nimport pandas as pd \nimport numpy as np\nimport sys, os, random \nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.pipeline import Pipeline\n\n\n###\n# Remove outliers in class label\ndef removeOutliers(data, yLabel):\n\t'''\n\tyFrequencyDic = {}\n\tfor x in data.T:\n\t\trow_y = data.T[x][yLabel]\n\t\tif row_y not in yFrequencyDic:\n\t\t\tyFrequencyDic[row_y] = 0\n\t\tyFrequencyDic[row_y] += 1\n\tfor x in data.T:\n\t\trow_y = data.T[x][yLabel]\n\t\tif yFrequencyDic[row_y] == 1:\n\t\t\tdata = data.drop(x)\n\treturn data\n\t'''\t\t\n\tclassCounts = data[yLabel].value_counts()\n\tfor value, count in enumerate(classCounts):\n\t\tif count <= 1:\n\t\t\tdata = data[data[yLabel] != classCounts.index.tolist()[value]]\n\treturn data\n\n###\n\n\n\n###\n# Convert categorical colum to int\nclass MultiColumnLabelEncoder:\n\tdef __init__(self,columns = None):\n \tself.columns = columns # array of column names to encode\n\n\tdef fit(self,X,y=None):\n \treturn self # not relevant here\n\n\tdef transform(self,X):\n \toutput = X.copy()\n \tif self.columns is not None:\n\t \tfor col in self.columns:\n \t \toutput[col] = LabelEncoder().fit_transform(output[col])\n \telse:\n \t\tfor colname,col in output.iteritems():\n \t\toutput[colname] = LabelEncoder().fit_transform(col)\n \t\treturn output\n\n\tdef fit_transform(self,X,y=None):\n \treturn self.fit(X,y).transform(X)\n\ndef convertObjectColum(data):\n\tcat_columns = data.select_dtypes(['object']).columns\n\t#data[cat_columns] = data[cat_columns].apply(lambda x: x.cat.codes)\n\tdata = MultiColumnLabelEncoder(columns = cat_columns).fit_transform(data)\n\treturn data\n\n###\n\n\n\n###\n# Fillup missing values\n\ndef fillUpMissingValues(data):\n\tdata = data.dropna(how='any') # Drop rows where all cells in that row is NA\n\tdata.fillna(0) # Fill in missing data with zeros\n\treturn data\n\n###\n\n\n###\n# Get the mapping between class label before and after preprocessing\ndef getMappingOfClass(originalData, cleanedData, yLabel):\n\tmapping = {}\n\toD = originalData[yLabel].unique()\n\tcD = cleanedData[yLabel].unique()\n\tfor x in range(0, len(oD)):\n\t\t# Given transformed label, report the original one\n\t\tmapping[str(cD[x])] = str(oD[x])\n\treturn mapping\n\n# Get the mapping of features\ndef getMappingOfFeatures(originalData, cleanedData, yLabel):\n\tmapping = {}\n\t# Only convert object type of columns\n\tcatData = originalData.select_dtypes(['object'])\n\tfor fname, values in catData.iteritems():\n\t\t# Skip class\n\t\tif fname == yLabel:\n\t\t\tcontinue\n\t\t# Features here\n\t\toD = originalData[fname].unique()\n\t\tcD = cleanedData[fname].unique()\n\t\tmapping[fname] = {}\n\t\tfor x in range(0, len(oD)):\n\t\t\t# Given original label, report the transformed one. This is different for y\n\t\t\tmapping[fname][str(oD[x])] = str(cD[x])\n\treturn mapping\n\n###\n\n\n\n\n\n#########################\ndef cleanDataForClassification(data, yLabel):\n\tdata = fillUpMissingValues(data)\n\tdata = convertObjectColum(data)\n\treturn data\n\ndef cleanDataForRegression(data, yLabel):\n\tdata = fillUpMissingValues(data)\n\tdata = convertObjectColum(data)\n\treturn data\n#########################\n" ]
[ [ "tensorflow.negative", "tensorflow.summary.FileWriter", "tensorflow.arg_min", "tensorflow.placeholder", "tensorflow.compat.v1.Session", "tensorflow.global_variables_initializer", "numpy.argmax", "tensorflow.examples.tutorials.mnist.input_data.read_data_sets" ], [ "sklearn.preprocessing.LabelEncoder" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
hpzhen/ChZhShCh
[ "a5af067e342cf734fafb827eab17462c4bd6f74d" ]
[ "chzhshch/inner_package/show.py" ]
[ "# -*- coding: UTF-8 -*-\nimport matplotlib.ticker as ticker\nimport matplotlib.pyplot as plt\nimport mpl_finance as mpf\n# from mpl_finance import quotes_historical_yahoo\nimport numpy as np\nfrom pandas import Series, DataFrame\n# http://blog.csdn.net/xiaodongxiexie/article/details/53123371\n\nclass PlotShow(object):\n\n def __init__(self, date_tickers, title):\n self.date_tickers = date_tickers\n self.xaxis_cycle = 30\n self.width = 0.3\n self.colordown ='#53c156'\n self.colorup = '#ff1717'\n self.xlabel = 'datetime'\n self.ylabel = 'value'\n self.title = title\n\n\n # 时间轴转换\n def __format_date(self, x, pos=None):\n if x < 0 or x > len(self.date_tickers) - 1:\n return ''\n return self.date_tickers[int(x)]\n\n # K画图\n def candle_show(self, stock_data, top_bottom_data):\n\n # 创建子图\n fig, ax = plt.subplots(figsize=(192.0 / 72, 108.0 / 72))\n ax.xaxis.set_major_locator(ticker.MultipleLocator(self.xaxis_cycle))\n ax.xaxis.set_major_formatter(ticker.FuncFormatter(self.__format_date))\n mpf.candlestick_ohlc(ax, stock_data, width=self.width, colordown=self.colordown, colorup=self.colorup, alpha=1)\n\n # title 各种设置\n plt.rcParams['font.sans-serif'] = ['SimHei']\n plt.rcParams['axes.unicode_minus'] = False\n\n plt.title(self.title)\n plt.xlabel(self.xlabel)\n plt.ylabel(self.ylabel)\n\n # 顶底、图例等\n if len(top_bottom_data) > 0:\n x = []\n y = []\n for i in top_bottom_data:\n x.append(i[0])\n y.append(i[1])\n plt.plot(x, y, '--y*', label='分笔')\n plt.legend() # 展示图例\n\n ax.grid(True)\n # plt.savefig('E:\\PythonChZhShCh\\\\' + code + k_type + start_date + end_date + '.png')\n plt.show()\n\n # MA 画图\n def ma_kiss_show(self, ma):\n fig, ax = plt.subplots(1, 1, figsize=(1920 / 72, 1080 / 72), sharex=True)\n\n plt.rcParams['font.sans-serif'] = ['SimHei']\n plt.rcParams['axes.unicode_minus'] = False\n\n ax.plot(ma.x_index, ma.short, color='red', linewidth=1.0, label=\"short\")\n ax.plot(ma.x_index, ma.long, color='black', linewidth=1.0, label=\"long\")\n \n # 交点打印\n ax.plot(ma.intersection_x, ma.intersection_y, 'o')\n\n # 吻打印\n ax.plot(ma.lip_kiss_x, ma.lip_kiss_y, 'o')\n\n\n ax.set_title(self.title)\n ax.set_xlabel(\"日期\")\n ax.set_ylabel(\"price\")\n\n plt.xticks(ma.int_tickers)\n plt.xticks(ma.int_tickers, ma.date_tickers)\n ax.legend()\n plt.show()\n" ]
[ [ "matplotlib.pyplot.legend", "matplotlib.ticker.MultipleLocator", "matplotlib.pyplot.title", "matplotlib.pyplot.subplots", "matplotlib.pyplot.plot", "matplotlib.ticker.FuncFormatter", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.xticks", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
vandanavk/sagemaker-debugger
[ "5246cda198295aa1dd1656ad32b30c4bb1e2aec4" ]
[ "tests/tensorflow/hooks/test_mirrored_strategy.py" ]
[ "# Copyright 2016 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\"\"\"Convolutional Neural Network Estimator for MNIST, built with tf.layers.\"\"\"\n\n# Future\nfrom __future__ import absolute_import, division, print_function\n\n# Third Party\nimport numpy as np\nimport pytest\nimport tensorflow as tf\nfrom tensorflow.python.client import device_lib\nfrom tests.tensorflow.utils import create_trial_fast_refresh\n\n# First Party\nimport smdebug.tensorflow as smd\nfrom smdebug.core.collection import CollectionKeys\nfrom smdebug.core.modes import ModeKeys\nfrom smdebug.exceptions import TensorUnavailableForStep\nfrom smdebug.tensorflow import get_hook\n\n\ndef cnn_model_fn(features, labels, mode):\n \"\"\"Model function for CNN.\"\"\"\n # Input Layer\n # Reshape X to 4-D tensor: [batch_size, width, height, channels]\n # MNIST images are 28x28 pixels, and have one color channel\n input_layer = tf.reshape(features[\"x\"], [-1, 28, 28, 1])\n\n # Convolutional Layer #1\n # Computes 32 features using a 5x5 filter with ReLU activation.\n # Padding is added to preserve width and height.\n # Input Tensor Shape: [batch_size, 28, 28, 1]\n # Output Tensor Shape: [batch_size, 28, 28, 32]\n conv1 = tf.layers.conv2d(\n inputs=input_layer, filters=32, kernel_size=[5, 5], padding=\"same\", activation=tf.nn.relu\n )\n\n # Pooling Layer #1\n # First max pooling layer with a 2x2 filter and stride of 2\n # Input Tensor Shape: [batch_size, 28, 28, 32]\n # Output Tensor Shape: [batch_size, 14, 14, 32]\n pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2)\n\n # Convolutional Layer #2\n # Computes 64 features using a 5x5 filter.\n # Padding is added to preserve width and height.\n # Input Tensor Shape: [batch_size, 14, 14, 32]\n # Output Tensor Shape: [batch_size, 14, 14, 64]\n conv2 = tf.layers.conv2d(\n inputs=pool1, filters=64, kernel_size=[5, 5], padding=\"same\", activation=tf.nn.relu\n )\n\n # Pooling Layer #2\n # Second max pooling layer with a 2x2 filter and stride of 2\n # Input Tensor Shape: [batch_size, 14, 14, 64]\n # Output Tensor Shape: [batch_size, 7, 7, 64]\n pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2)\n\n # Flatten tensor into a batch of vectors\n # Input Tensor Shape: [batch_size, 7, 7, 64]\n # Output Tensor Shape: [batch_size, 7 * 7 * 64]\n pool2_flat = tf.reshape(pool2, [-1, 7 * 7 * 64])\n\n # Dense Layer\n # Densely connected layer with 1024 neurons\n # Input Tensor Shape: [batch_size, 7 * 7 * 64]\n # Output Tensor Shape: [batch_size, 1024]\n dense = tf.layers.dense(inputs=pool2_flat, units=1024, activation=tf.nn.relu)\n\n # Add dropout operation; 0.6 probability that element will be kept\n dropout = tf.layers.dropout(\n inputs=dense, rate=0.4, training=mode == tf.estimator.ModeKeys.TRAIN\n )\n\n # Logits layer\n # Input Tensor Shape: [batch_size, 1024]\n # Output Tensor Shape: [batch_size, 10]\n logits = tf.layers.dense(inputs=dropout, units=10)\n\n predictions = {\n # Generate predictions (for PREDICT and EVAL mode)\n \"classes\": tf.argmax(input=logits, axis=1),\n # Add `softmax_tensor` to the graph. It is used for PREDICT and by the\n # `logging_hook`.\n \"probabilities\": tf.nn.softmax(logits, name=\"softmax_tensor\"),\n }\n if mode == tf.estimator.ModeKeys.PREDICT:\n return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)\n\n # Calculate Loss (for both TRAIN and EVAL modes)\n loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits)\n\n # Configure the Training Op (for TRAIN mode)\n if mode == tf.estimator.ModeKeys.TRAIN:\n optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001)\n optimizer = smd.get_hook().wrap_optimizer(optimizer)\n train_op = optimizer.minimize(loss=loss, global_step=tf.train.get_global_step())\n return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op)\n\n # Add evaluation metrics (for EVAL mode)\n eval_metric_ops = {\n \"accuracy\": tf.metrics.accuracy(labels=labels, predictions=predictions[\"classes\"])\n }\n return tf.estimator.EstimatorSpec(mode=mode, loss=loss, eval_metric_ops=eval_metric_ops)\n\n\ndef per_device_batch_size(batch_size, num_gpus):\n \"\"\"For multi-gpu, batch-size must be a multiple of the number of GPUs.\n Note that this should eventually be handled by DistributionStrategies\n directly. Multi-GPU support is currently experimental, however,\n so doing the work here until that feature is in place.\n Args:\n batch_size: Global batch size to be divided among devices. This should be\n equal to num_gpus times the single-GPU batch_size for multi-gpu training.\n num_gpus: How many GPUs are used with DistributionStrategies.\n Returns:\n Batch size per device.\n Raises:\n ValueError: if batch_size is not divisible by number of devices\n \"\"\"\n if num_gpus <= 1:\n return batch_size\n\n remainder = batch_size % num_gpus\n if remainder:\n err = (\n \"When running with multiple GPUs, batch size \"\n \"must be a multiple of the number of available GPUs. Found {} \"\n \"GPUs with a batch size of {}; try --batch_size={} instead.\"\n ).format(num_gpus, batch_size, batch_size - remainder)\n raise ValueError(err)\n return int(batch_size / num_gpus)\n\n\nclass InputFnProvider:\n def __init__(self, train_batch_size):\n self.train_batch_size = train_batch_size\n self.__load_data()\n\n def __load_data(self):\n # Load training and eval data\n mnist = tf.contrib.learn.datasets.load_dataset(\"mnist\")\n self.train_data = mnist.train.images # Returns np.array\n self.train_labels = np.asarray(mnist.train.labels, dtype=np.int32)\n self.eval_data = mnist.test.images # Returns np.array\n self.eval_labels = np.asarray(mnist.test.labels, dtype=np.int32)\n\n def train_input_fn(self):\n \"\"\"An input function for training\"\"\"\n # Shuffle, repeat, and batch the examples.\n dataset = tf.data.Dataset.from_tensor_slices(({\"x\": self.train_data}, self.train_labels))\n dataset = dataset.shuffle(1000).repeat().batch(self.train_batch_size)\n return dataset\n\n def eval_input_fn(self):\n \"\"\"An input function for evaluation or prediction\"\"\"\n dataset = tf.data.Dataset.from_tensor_slices(({\"x\": self.eval_data}, self.eval_labels))\n dataset = dataset.batch(1).repeat()\n return dataset\n\n\ndef get_available_gpus():\n local_device_protos = device_lib.list_local_devices()\n return len([x.name for x in local_device_protos if x.device_type == \"GPU\"])\n\n\ndef helper_mirrored(\n trial_dir,\n save_all=False,\n num_steps=3,\n save_config=None,\n reduction_config=None,\n include_collections=None,\n steps=None,\n zcc=False,\n eval_distributed=False,\n include_workers=\"all\",\n):\n num_gpus = get_available_gpus()\n num_devices = num_gpus if num_gpus > 0 else 1\n batch_size = 10 * num_devices\n\n # input_fn which serves Dataset\n input_fn_provider = InputFnProvider(per_device_batch_size(batch_size, num_devices))\n\n # Use multiple GPUs by MirroredStragtegy.\n # All avaiable GPUs will be used if `num_gpus` is omitted.\n # if num_devices > 1:\n distribution = tf.contrib.distribute.MirroredStrategy()\n # print(\"### Doing Multi GPU Training\")\n # else:\n # distribution = None\n # Pass to RunConfig\n config = tf.estimator.RunConfig(\n train_distribute=distribution,\n eval_distribute=distribution if eval_distributed else None,\n model_dir=\"/tmp/mnist_convnet_model\",\n )\n\n if save_config is None:\n save_config = smd.SaveConfig(save_interval=2)\n\n if include_collections is None:\n include_collections = [\n CollectionKeys.WEIGHTS,\n CollectionKeys.BIASES,\n CollectionKeys.GRADIENTS,\n CollectionKeys.LOSSES,\n ]\n\n if not zcc:\n ts_hook = smd.SessionHook(\n out_dir=trial_dir,\n save_all=save_all,\n include_collections=include_collections,\n save_config=save_config,\n reduction_config=reduction_config,\n include_workers=include_workers,\n )\n else:\n print(\"zcc is passed. ignoring include_collections and save_config\")\n\n mnist_classifier = tf.estimator.Estimator(model_fn=cnn_model_fn, config=config)\n if steps is None:\n steps = [\"train\"]\n\n for s in steps:\n if s == \"train\":\n print(\"Starting train\")\n if not zcc:\n ts_hook.set_mode(smd.modes.TRAIN)\n # Train the model\n mnist_classifier.train(\n input_fn=input_fn_provider.train_input_fn, steps=num_steps, hooks=[ts_hook]\n )\n else:\n mnist_classifier.train(input_fn=input_fn_provider.train_input_fn, steps=num_steps)\n elif s == \"eval\":\n print(\"Starting eval\")\n\n if not zcc:\n ts_hook.set_mode(smd.modes.EVAL)\n # Evaluate the model and print results\n mnist_classifier.evaluate(\n input_fn=input_fn_provider.eval_input_fn, steps=num_steps, hooks=[ts_hook]\n )\n else:\n mnist_classifier.evaluate(input_fn=input_fn_provider.eval_input_fn, steps=num_steps)\n elif s == \"predict\":\n print(\"Starting predict\")\n if not zcc:\n ts_hook.set_mode(smd.modes.PREDICT)\n # Evaluate the model and print results\n p = mnist_classifier.predict(\n input_fn=input_fn_provider.eval_input_fn, hooks=[ts_hook]\n )\n else:\n p = mnist_classifier.predict(input_fn=input_fn_provider.eval_input_fn)\n for i in range(num_steps):\n next(p)\n get_hook()._cleanup()\n return distribution\n\n\ndef skip_trial_check():\n # Skip trial check as in this case SMDebug is disabled for mirrored strategy\n # trial will not be loaded\n import tensorflow as tf\n from packaging import version\n\n if version.parse(tf.__version__) < version.parse(\"1.14.0\"):\n return True\n else:\n return False\n\n\[email protected]\ndef test_basic(out_dir, zcc=False):\n strategy = helper_mirrored(\n out_dir,\n steps=[\"train\", \"eval\", \"predict\", \"train\"],\n include_collections=[\n CollectionKeys.WEIGHTS,\n CollectionKeys.BIASES,\n CollectionKeys.GRADIENTS,\n CollectionKeys.LOSSES,\n ],\n eval_distributed=False,\n zcc=zcc,\n )\n if skip_trial_check():\n return\n\n tr = create_trial_fast_refresh(out_dir)\n # wts, grads, losses\n assert (\n len(tr.tensor_names()) == 8 + 8 + (1 * strategy.num_replicas_in_sync) + 1\n ) # 1 main loss, and 1 from each worker\n assert len(tr.steps()) == 7\n assert len(tr.steps(ModeKeys.TRAIN)) == 3\n assert len(tr.steps(ModeKeys.EVAL)) == 2\n assert len(tr.steps(ModeKeys.PREDICT)) == 2\n\n assert \"dense_1/kernel:0\" in tr.tensor_names(collection=\"weights\")\n for tname in tr.tensor_names(collection=\"weights\"):\n for s in tr.tensor(tname).steps(ModeKeys.TRAIN):\n assert len(tr.tensor(tname).workers(s, ModeKeys.TRAIN)) == strategy.num_replicas_in_sync\n for worker in tr.tensor(tname).workers(s, ModeKeys.TRAIN):\n assert tr.tensor(tname).value(s, worker=worker, mode=ModeKeys.TRAIN) is not None\n for s in tr.tensor(tname).steps(ModeKeys.EVAL):\n assert len(tr.tensor(tname).workers(s, ModeKeys.EVAL)) == 1 # as eval_dist = False\n assert tr.tensor(tname).value(s, mode=ModeKeys.EVAL) is not None\n\n tensornames = tr.tensor_names(regex=\"Identity_\\d+:0\")\n for s in tr.tensor(tensornames[0]).steps(ModeKeys.TRAIN):\n for w in tr.tensor(tensornames[0]).workers(s, ModeKeys.TRAIN):\n assert tr.tensor(tensornames[0]).value(s, worker=w, mode=ModeKeys.TRAIN) is not None\n assert (\n len(tr.tensor(tensornames[0]).workers(s, ModeKeys.TRAIN))\n == strategy.num_replicas_in_sync\n )\n\n for tname in tr.tensor_names(collection=\"losses\"):\n if tname != tensornames[0]:\n for s in tr.tensor(tname).steps(ModeKeys.TRAIN):\n assert len(tr.tensor(tname).workers(s, ModeKeys.TRAIN)) == 1, tname\n assert tr.tensor(tname).value(s, mode=ModeKeys.TRAIN) is not None\n\n tname = \"sparse_softmax_cross_entropy_loss/value:0\"\n for s in tr.tensor(tname).steps(ModeKeys.EVAL):\n assert len(tr.tensor(tname).workers(s, ModeKeys.EVAL)) == 1 # eval_dist=False\n assert tr.tensor(tname).value(s, mode=ModeKeys.EVAL) is not None\n\n\[email protected]\ndef test_eval_distributed(out_dir):\n strategy = helper_mirrored(\n out_dir,\n steps=[\"train\", \"eval\"],\n include_collections=[CollectionKeys.WEIGHTS, CollectionKeys.BIASES, CollectionKeys.LOSSES],\n eval_distributed=True,\n )\n if skip_trial_check():\n return\n tr = create_trial_fast_refresh(out_dir)\n assert len(tr.tensor_names()) == 8 + 1 * strategy.num_replicas_in_sync + 1\n assert len(tr.steps()) == 4\n assert len(tr.steps(ModeKeys.TRAIN)) == 2\n assert len(tr.steps(ModeKeys.EVAL)) == 2\n\n for tname in tr.tensor_names(collection=\"weights\"):\n for s in tr.tensor(tname).steps(ModeKeys.TRAIN):\n assert len(tr.tensor(tname).workers(s, ModeKeys.TRAIN)) == strategy.num_replicas_in_sync\n for worker in tr.tensor(tname).workers(s, ModeKeys.TRAIN):\n assert tr.tensor(tname).value(s, worker=worker, mode=ModeKeys.TRAIN) is not None\n for s in tr.tensor(tname).steps(ModeKeys.EVAL):\n assert len(tr.tensor(tname).workers(s, ModeKeys.EVAL)) == strategy.num_replicas_in_sync\n assert tr.tensor(tname).value(s, mode=ModeKeys.EVAL) is not None\n\n tensornames = tr.tensor_names(regex=\"Identity_\\d+:0\")\n for s in tr.tensor(tensornames[0]).steps(ModeKeys.TRAIN):\n for w in tr.tensor(tensornames[0]).workers(s, ModeKeys.TRAIN):\n assert tr.tensor(tensornames[0]).value(s, worker=w, mode=ModeKeys.TRAIN) is not None\n assert (\n len(tr.tensor(tensornames[0]).workers(s, ModeKeys.TRAIN))\n == strategy.num_replicas_in_sync\n )\n\n for tname in tr.tensor_names(collection=\"losses\"):\n for s in tr.tensor(tname).steps(ModeKeys.EVAL):\n assert len(tr.tensor(tname).workers(s, ModeKeys.EVAL)) == 1\n assert tr.tensor(tname).value(s, mode=ModeKeys.EVAL) is not None\n if tname != tensornames[0]:\n for s in tr.tensor(tname).steps(ModeKeys.TRAIN):\n assert len(tr.tensor(tname).workers(s, ModeKeys.EVAL)) == 1\n assert tr.tensor(tname).value(s, mode=ModeKeys.EVAL) is not None\n\n\[email protected]\ndef test_reductions(out_dir):\n strategy = helper_mirrored(\n out_dir,\n steps=[\"train\", \"eval\"],\n reduction_config=smd.ReductionConfig(\n reductions=[\"sum\", \"max\"], abs_reductions=[\"sum\", \"max\"], norms=[\"l1\"]\n ),\n include_collections=[CollectionKeys.WEIGHTS, CollectionKeys.BIASES, CollectionKeys.LOSSES],\n eval_distributed=True,\n )\n if skip_trial_check():\n return\n\n tr = create_trial_fast_refresh(out_dir)\n assert len(tr.tensor_names()) == 8 + 1 * strategy.num_replicas_in_sync + 1\n assert len(tr.steps()) == 4\n assert len(tr.steps(ModeKeys.TRAIN)) == 2\n assert len(tr.steps(ModeKeys.EVAL)) == 2\n\n for tname in tr.tensor_names(collection=\"weights\"):\n for s in tr.tensor(tname).steps(ModeKeys.TRAIN):\n try:\n tr.tensor(tname).value(s, mode=ModeKeys.TRAIN)\n assert False\n except TensorUnavailableForStep:\n # for some tensors l1 reduction can't be saved due to improper dimensions for the reduction\n assert len(tr.tensor(tname).reduction_values(s, mode=ModeKeys.TRAIN)) >= 4\n\n for s in tr.tensor(tname).steps(ModeKeys.EVAL):\n try:\n tr.tensor(tname).value(s, mode=ModeKeys.EVAL)\n assert False\n except TensorUnavailableForStep:\n # for some tensors l1 reduction can't be saved due to improper dimensions for the reduction\n assert len(tr.tensor(tname).reduction_values(s, mode=ModeKeys.EVAL)) >= 4\n\n for tname in tr.tensor_names(collection=\"losses\"):\n for s in tr.tensor(tname).steps(ModeKeys.EVAL):\n assert len(tr.tensor(tname).reduction_values(s, mode=ModeKeys.EVAL)) == 0\n assert tr.tensor(tname).value(s, mode=ModeKeys.EVAL) is not None\n\n for tname in tr.tensor_names(collection=\"losses\"):\n for s in tr.tensor(tname).steps(ModeKeys.TRAIN):\n assert len(tr.tensor(tname).reduction_values(s, mode=ModeKeys.TRAIN)) == 0\n assert tr.tensor(tname).value(s, mode=ModeKeys.TRAIN) is not None\n\n\[email protected]\ndef test_save_all(out_dir):\n strategy = helper_mirrored(\n out_dir, steps=[\"train\"], num_steps=1, save_all=True, eval_distributed=True\n )\n if skip_trial_check():\n return\n tr = create_trial_fast_refresh(out_dir)\n assert len(tr.tensor_names()) > 100\n assert len(tr.steps())\n assert len(tr.tensor_names(collection=\"weights\"))\n assert len(tr.tensor_names(collection=\"biases\"))\n assert len(tr.tensor_names(collection=\"gradients\"))\n\n\[email protected]\ndef test_save_all_worker(out_dir):\n # skip test if no gpus available\n if get_available_gpus() == 0:\n return\n strategy = helper_mirrored(\n out_dir,\n steps=[\"train\"],\n num_steps=1,\n save_all=True,\n eval_distributed=True,\n include_workers=\"all\",\n )\n tr = create_trial_fast_refresh(out_dir)\n assert len(tr.steps())\n assert len(tr.workers()) == get_available_gpus()\n assert len(tr.tensor_names(collection=\"weights\"))\n assert \"conv2d/kernel:0\" in tr.tensor_names(collection=\"weights\")\n assert len(tr.tensor(\"conv2d/kernel:0\").workers(0)) == strategy.num_replicas_in_sync\n assert len(tr.tensor_names(collection=\"biases\"))\n assert \"conv2d/bias:0\" in tr.tensor_names(collection=\"biases\")\n assert len(tr.tensor(\"conv2d/bias:0\").workers(0)) == strategy.num_replicas_in_sync\n assert len(tr.tensor_names(collection=\"gradients\"))\n\n\[email protected]\ndef test_save_one_worker(out_dir):\n strategy = helper_mirrored(\n out_dir,\n steps=[\"train\"],\n num_steps=1,\n save_all=True,\n eval_distributed=True,\n include_workers=\"one\",\n )\n tr = create_trial_fast_refresh(out_dir)\n assert len(tr.workers()) == 1\n assert len(tr.steps())\n assert len(tr.tensor_names(collection=\"weights\"))\n assert len(tr.tensor_names(collection=\"biases\"))\n assert len(tr.tensor_names(collection=\"gradients\"))\n" ]
[ [ "tensorflow.metrics.accuracy", "tensorflow.python.client.device_lib.list_local_devices", "numpy.asarray", "tensorflow.layers.dropout", "tensorflow.estimator.RunConfig", "tensorflow.contrib.distribute.MirroredStrategy", "tensorflow.layers.dense", "tensorflow.train.get_global_step", "tensorflow.argmax", "tensorflow.layers.conv2d", "tensorflow.estimator.Estimator", "tensorflow.losses.sparse_softmax_cross_entropy", "tensorflow.train.GradientDescentOptimizer", "tensorflow.contrib.learn.datasets.load_dataset", "tensorflow.nn.softmax", "tensorflow.data.Dataset.from_tensor_slices", "tensorflow.reshape", "tensorflow.layers.max_pooling2d", "tensorflow.estimator.EstimatorSpec" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
SSLAB-SSU/deep-learning-from-scratch
[ "3609360751d67085e0963ee6d7af6d49380cd965" ]
[ "ch07/simple_convnet.py" ]
[ "# coding: utf-8\nimport sys, os\nsys.path.append('/Users/hxxnhxx/Documents/development/deep-learning-from-scratch') # 親ディレクトリのファイルをインポートするための設定\nimport pickle\nimport numpy as np\nfrom collections import OrderedDict\nfrom common.layers import *\nfrom common.gradient import numerical_gradient\n\n\nclass SimpleConvNet:\n \"\"\"単純なConvNet\n\n conv - relu - pool - affine - relu - affine - softmax\n \n Parameters\n ----------\n input_size : 入力サイズ(MNISTの場合は784)\n hidden_size_list : 隠れ層のニューロンの数のリスト(e.g. [100, 100, 100])\n output_size : 出力サイズ(MNISTの場合は10)\n activation : 'relu' or 'sigmoid'\n weight_init_std : 重みの標準偏差を指定(e.g. 0.01)\n 'relu'または'he'を指定した場合は「Heの初期値」を設定\n 'sigmoid'または'xavier'を指定した場合は「Xavierの初期値」を設定\n \"\"\"\n def __init__(self, input_dim=(1, 28, 28), \n conv_param={'filter_num':30, 'filter_size':5, 'pad':0, 'stride':1},\n hidden_size=100, output_size=10, weight_init_std=0.01):\n filter_num = conv_param['filter_num']\n filter_size = conv_param['filter_size']\n filter_pad = conv_param['pad']\n filter_stride = conv_param['stride']\n input_size = input_dim[1]\n conv_output_size = (input_size - filter_size + 2*filter_pad) / filter_stride + 1\n pool_output_size = int(filter_num * (conv_output_size/2) * (conv_output_size/2))\n\n # 重みの初期化\n self.params = {}\n self.params['W1'] = weight_init_std * \\\n np.random.randn(filter_num, input_dim[0], filter_size, filter_size)\n self.params['b1'] = np.zeros(filter_num)\n self.params['W2'] = weight_init_std * \\\n np.random.randn(pool_output_size, hidden_size)\n self.params['b2'] = np.zeros(hidden_size)\n self.params['W3'] = weight_init_std * \\\n np.random.randn(hidden_size, output_size)\n self.params['b3'] = np.zeros(output_size)\n\n # レイヤの生成\n self.layers = OrderedDict()\n self.layers['Conv1'] = Convolution(self.params['W1'], self.params['b1'],\n conv_param['stride'], conv_param['pad'])\n self.layers['Relu1'] = Relu()\n self.layers['Pool1'] = Pooling(pool_h=2, pool_w=2, stride=2)\n self.layers['Affine1'] = Affine(self.params['W2'], self.params['b2'])\n self.layers['Relu2'] = Relu()\n self.layers['Affine2'] = Affine(self.params['W3'], self.params['b3'])\n\n self.last_layer = SoftmaxWithLoss()\n\n def predict(self, x):\n for layer in self.layers.values():\n x = layer.forward(x)\n\n return x\n\n def loss(self, x, t):\n \"\"\"損失関数を求める\n 引数のxは入力データ、tは教師ラベル\n \"\"\"\n y = self.predict(x)\n return self.last_layer.forward(y, t)\n\n def accuracy(self, x, t, batch_size=100):\n if t.ndim != 1 : t = np.argmax(t, axis=1)\n \n acc = 0.0\n \n for i in range(int(x.shape[0] / batch_size)):\n tx = x[i*batch_size:(i+1)*batch_size]\n tt = t[i*batch_size:(i+1)*batch_size]\n y = self.predict(tx)\n y = np.argmax(y, axis=1)\n acc += np.sum(y == tt) \n \n return acc / x.shape[0]\n\n def numerical_gradient(self, x, t):\n \"\"\"勾配を求める(数値微分)\n\n Parameters\n ----------\n x : 入力データ\n t : 教師ラベル\n\n Returns\n -------\n 各層の勾配を持ったディクショナリ変数\n grads['W1']、grads['W2']、...は各層の重み\n grads['b1']、grads['b2']、...は各層のバイアス\n \"\"\"\n loss_w = lambda w: self.loss(x, t)\n\n grads = {}\n for idx in (1, 2, 3):\n grads['W' + str(idx)] = numerical_gradient(loss_w, self.params['W' + str(idx)])\n grads['b' + str(idx)] = numerical_gradient(loss_w, self.params['b' + str(idx)])\n\n return grads\n\n def gradient(self, x, t):\n \"\"\"勾配を求める(誤差逆伝搬法)\n\n Parameters\n ----------\n x : 入力データ\n t : 教師ラベル\n\n Returns\n -------\n 各層の勾配を持ったディクショナリ変数\n grads['W1']、grads['W2']、...は各層の重み\n grads['b1']、grads['b2']、...は各層のバイアス\n \"\"\"\n # forward\n self.loss(x, t)\n\n # backward\n dout = 1\n dout = self.last_layer.backward(dout)\n\n layers = list(self.layers.values())\n layers.reverse()\n for layer in layers:\n dout = layer.backward(dout)\n\n # 設定\n grads = {}\n grads['W1'], grads['b1'] = self.layers['Conv1'].dW, self.layers['Conv1'].db\n grads['W2'], grads['b2'] = self.layers['Affine1'].dW, self.layers['Affine1'].db\n grads['W3'], grads['b3'] = self.layers['Affine2'].dW, self.layers['Affine2'].db\n\n return grads\n \n def save_params(self, file_name=\"params.pkl\"):\n params = {}\n for key, val in self.params.items():\n params[key] = val\n with open(file_name, 'wb') as f:\n pickle.dump(params, f)\n\n def load_params(self, file_name=\"params.pkl\"):\n with open(file_name, 'rb') as f:\n params = pickle.load(f)\n for key, val in params.items():\n self.params[key] = val\n\n for i, key in enumerate(['Conv1', 'Affine1', 'Affine2']):\n self.layers[key].W = self.params['W' + str(i+1)]\n self.layers[key].b = self.params['b' + str(i+1)]" ]
[ [ "numpy.random.randn", "numpy.argmax", "numpy.zeros", "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
acpadua/pycelle
[ "8ec8c474c04e115635a76d360f5f4c9613b01705" ]
[ "analyse_images.py" ]
[ "import numpy as np\r\n\r\nfrom math import sqrt\r\nfrom skimage import data\r\nfrom skimage.feature import blob_dog, blob_log, blob_doh\r\nfrom skimage.color import rgb2gray\r\nfrom pandas import DataFrame\r\nimport pandas as pd\r\n\r\nimport matplotlib.pyplot as plt\r\nimport os\r\nfrom os import path\r\nimport glob\r\nimport cv2\r\nimport time\r\nimport math\r\nimport json\r\n\r\ndef convert_to_grayscale(img, file_name, output_gray):\r\n \"\"\"\r\n This function converts the original image in a grayscale image. Then shows and saves the gray scale image.\r\n :param img: path to image of interest\r\n :param output_path: path for the output image\r\n \"\"\"\r\n # reads the image img in grayscale\r\n img_gray = cv2.imread(img,0)\r\n save_name = file_name + '_gray.jpg'\r\n\r\n cv2.imwrite(os.path.join(output_gray, save_name), img_gray)\r\n #cv2.namedWindow(file_name, cv2.WINDOW_NORMAL)\r\n #cv2.imshow(file_name, img_gray)\r\n #cv2.waitKey(2)\r\n #cv2.destroyAllWindows()\r\n print(\"converted to gray\")\r\n return img_gray\r\n\r\ndef cumsum_histogram_percentage(img, file_name, output_histograms):\r\n \"\"\"\r\n Reads the image 'img', gets the images' histogram and then the cumulative distribution.\r\n Next, normalises the cumulative distribution to be between 0 and 1. Finally, shows and saves it in a plot. \r\n :param img: path to the image of interest \r\n :param output_histograms: path where the cumulative distribution histogram will be saved. \r\n :return: cumulative distribution histogram, grayscale values, image name \r\n \"\"\"\r\n hist,bins = np.histogram(img.flatten(),256,[0,256])\r\n cdf = hist.cumsum()\r\n cdf_percentage = cdf * 1 / cdf.max()\r\n plt.plot(cdf_percentage, color = 'b')\r\n plt.xlim([0,256])\r\n plt.legend(('cdf'), loc = 'upper left')\r\n fig1=plt.gcf()\r\n #plt.show()\r\n print(img)\r\n name_fig1 = file_name + '_hist'\r\n print(name_fig1)\r\n fig1.savefig(os.path.join(output_histograms, name_fig1))\r\n print(\"histogram_done\")\r\n\r\n print(cdf_percentage)\r\n return cdf_percentage, bins\r\n\r\ndef remove_background(img, file_name, cdf_percentage, bins, output_thresh):\r\n \"\"\"\r\n Finds the value (n) of grayscale where the cumulative distribution of the image's histogram is 75 %.\r\n Then, applied a threshold (n) to the image, that converts all the values bellow n to 0 (black).\r\n :param image: path to image of interest\r\n :param file_name: name of the image of interest\r\n :param cdf_percentage: array with the values of the cumsum histogram of the image\r\n :param bins: grayscale values [0, 255]\r\n :param output_thresh_blur: path where the output image will be saved\r\n :return: image with threshold of 75 % applied\r\n \"\"\"\r\n #get array with all values > 75 % from cumsum\r\n third_quartil_cumsum = np.where(cdf_percentage > 0.75)[0]\r\n\r\n # get first value > 75 % from third quartil cumsum, which will be the position where to cut\r\n position_where_to_cut = third_quartil_cumsum[0]\r\n print(position_where_to_cut)\r\n\r\n # get gray value where to cut, which is the treshold\r\n threshold = bins[position_where_to_cut]\r\n print(threshold)\r\n\r\n ret, img_thresh_75 = cv2.threshold(img, threshold, 255, cv2.THRESH_TOZERO)\r\n save_name = file_name + '_thresh75.jpg'\r\n\r\n cv2.imwrite(os.path.join(output_thresh, save_name), img_thresh_75)\r\n #cv2.namedWindow(file_name, cv2.WINDOW_NORMAL)\r\n #cv2.imshow(save_name, img_thresh_75)\r\n #cv2.waitKey(2)\r\n #cv2.destroyAllWindows()\r\n print(\"converted to thresh75\")\r\n return img_thresh_75\r\n\r\ndef remove_white(img, file_name, output_background):\r\n \"\"\"\r\n This function converts the white pixels of the image in black pixels.\r\n \"\"\"\r\n white_px = 220\r\n black_px = 0\r\n\r\n (row, col) = img.shape\r\n img_array = np.array(img)\r\n\r\n for r in range(row):\r\n for c in range(col):\r\n px = img[r][c]\r\n if (px > white_px):\r\n img_array[r][c] = black_px\r\n\r\n print(\"end for cycle\")\r\n\r\n save_name = file_name + '_no_white.jpg'\r\n\r\n cv2.imwrite(os.path.join(output_background, save_name), img_array)\r\n cv2.namedWindow(save_name, cv2.WINDOW_NORMAL)\r\n cv2.imshow(save_name, img_array)\r\n cv2.waitKey(1)\r\n cv2.destroyAllWindows()\r\n\r\n\r\ndef get_droplets(img, file_name, parameters, output_circles):\r\n\r\n blobs_log1 = blob_log(img, min_sigma= parameters['min_sigma_value'], max_sigma= parameters['max_sigma_value'], num_sigma= parameters['num_sigma_value'], threshold= parameters['threshold_value'])\r\n\r\n blobs_log1[:, 2] = blobs_log1[:, 2] * sqrt(2)\r\n print(\"end of blob\")\r\n\r\n color = 'lime'\r\n\r\n file_name_parts = file_name.split(\"_\")\r\n\r\n image_description = []\r\n\r\n for part in file_name_parts:\r\n image_description.append(part)\r\n\r\n x_set = []\r\n y_set = []\r\n r_set = []\r\n\r\n droplets = []\r\n\r\n fig1, ax = plt.subplots(1, 1, figsize=(9, 3))\r\n\r\n for blob in blobs_log1:\r\n y, x, r = blob\r\n c = plt.Circle((x, y), r, color=color, linewidth=1, fill=False)\r\n ax.add_patch(c)\r\n\r\n x_set.append(x)\r\n y_set.append(y)\r\n r_set.append(r)\r\n ax.set_axis_off()\r\n\r\n ax.set_title(file_name)\r\n ax.imshow(img)\r\n\r\n plt.tight_layout()\r\n fig1 = plt.gcf()\r\n #plt.show(block=False)\r\n #time.sleep(0.5)\r\n #plt.close()\r\n\r\n\r\n save_name = file_name + '_min' + str(parameters['min_sigma_value']) + '_max' + str(parameters['max_sigma_value']) + '_num' + str(parameters['num_sigma_value']) + '_thresh' + str(parameters['threshold_value']) + \".svg\"\r\n fig1.savefig(os.path.join(output_circles, save_name), format='svg', dpi=1200)\r\n return x_set, y_set, r_set\r\n\r\ndef file_droplets(file_name, output_path, parameters, x_set, y_set, r_set):\r\n\r\n Droplets = {'min_sigma': parameters['min_sigma_value'], 'max_sigma': parameters['max_sigma_value'], 'num_sigma': parameters['num_sigma_value'], 'threshold': parameters['threshold_value'], 'x': x_set, 'y': y_set, 'r': r_set}\r\n\r\n df = DataFrame(Droplets, columns=['min_sigma', 'max_sigma', 'num_sigma', 'threshold', 'x', 'y', 'r'])\r\n\r\n export_csv = df.to_csv(output_path + '/files/' + file_name + '.csv', index=None, header=True) # Don't forget to add '.csv' at the end of the path\r\n\r\n print (df)\r\n\r\ndef analyse_droplets(files_path, output_files_analysis):\r\n\r\n voc =[]\r\n time = []\r\n label = []\r\n\r\n min_sigma = []\r\n max_sigma = []\r\n num_sigma = []\r\n threshold = []\r\n\r\n droplets_nr = []\r\n droplets_mean_radius = []\r\n optical_area = []\r\n\r\n droplets_nr_exp = []\r\n droplets_mean_radius_exp = []\r\n optical_area_exp = []\r\n\r\n for file in glob.glob(\"{}/*csv\".format(files_path)):\r\n df = pd.read_csv(file)\r\n name_file = os.path.basename(file)\r\n name_info = name_file.split('_')\r\n\r\n voc.append(name_info[0])\r\n time.append(name_info[1])\r\n label.append(name_info[2])\r\n\r\n r_set = ((df['r'] * 5000) / 1850)\r\n\r\n min_sigma.append(df['min_sigma'][0])\r\n max_sigma.append(df['max_sigma'][0])\r\n num_sigma.append(df['num_sigma'][0])\r\n threshold.append(df['threshold'][0])\r\n\r\n count_lines = df.shape[0]\r\n count_droplets = count_lines +1\r\n print(str(count_droplets))\r\n droplets_nr.append(count_droplets)\r\n droplets_mean_radius.append(r_set.mean())\r\n optical_area_sensor = 0\r\n\r\n for i in range(count_lines -1):\r\n optical_area_sensor += (np.pi * (df['r'][i] ** 2))\r\n optical_area_sensor_relative = (optical_area_sensor / (np.pi * (2500 ** 2)))\r\n optical_area.append(optical_area_sensor_relative)\r\n print(str(optical_area_sensor))\r\n\r\n\r\n\r\n Analysis = {'voc': voc, 'time': time, 'label': label, 'min_sigma': min_sigma, 'max_sigma': max_sigma, 'num_sigma': num_sigma,\r\n 'threshold': threshold, 'droplets_nr': droplets_nr, 'droplets_mean_radius': droplets_mean_radius, 'optical_area': optical_area}\r\n\r\n df = DataFrame(Analysis, columns=['voc', 'time', 'label', 'min_sigma', 'max_sigma', 'num_sigma', 'threshold', 'droplets_nr', 'droplets_mean_radius', 'optical_area'])\r\n\r\n save_name = 'droplets_analysis.csv'\r\n analysis_file = df.to_csv(os.path.join(output_files_analysis, save_name), index=None, header=True)\r\n return (analysis_file)\r\n\r\ndef sort_file(file, output_path):\r\n\r\n df = pd.read_csv(file)\r\n\r\n result = df.sort_values(['voc', 'time', 'label'], ascending=[1, 1, 1])\r\n result.to_csv(os.path.join(output_path, 'droplets_analysis_sorted.csv'))\r\n\r\n print(result)\r\n\r\ndef add_columns_validation(file_data, file_validation, output_path):\r\n df_a = pd.read_csv(file_data)\r\n df_e = pd.read_csv(file_validation)\r\n\r\n df_a['droplets_nr_exp'] = df_e['droplets_nr_exp']\r\n df_a['mean_diameter_exp'] = df_e['mean_diameter_exp']\r\n\r\n save_name = 'droplets_analysis_complete.csv'\r\n complete_file = df_a.to_csv(os.path.join(output_path, save_name))\r\n return complete_file\r\n\r\ndef compare_results(complete_file, output_path):\r\n\r\n df_c = pd.read_csv(complete_file)\r\n compare_nr = []\r\n compare_radius = []\r\n error = []\r\n\r\n for i, row in df_c.iterrows():\r\n sub_nr_i = (row['droplets_nr'] - row['droplets_nr_exp']) / row['droplets_nr_exp']\r\n compare_nr.append(sub_nr_i)\r\n print(sub_nr_i)\r\n\r\n mean_radius_i_a = (row['droplets_mean_radius'] * 5000) / 1400\r\n mean_radius_i_e = (row['mean_diameter_exp'] / 2)\r\n sub_radius_i = ((mean_radius_i_a - mean_radius_i_e) / mean_radius_i_e)\r\n print(sub_radius_i)\r\n compare_radius.append(sub_radius_i)\r\n\r\n error_i = math.sqrt((sub_radius_i ** 2) + (sub_radius_i ** 2))\r\n print(error_i)\r\n error.append(error_i)\r\n\r\n df_c['comparison_nr'] = compare_nr\r\n df_c['compare_raius'] = compare_radius\r\n df_c['error'] = error\r\n\r\n save_name = 'droplets_analysis_comparison.csv'\r\n complete_file = df_c.to_csv(os.path.join(output_path, save_name))\r\n return complete_file\r\n\r\ndef read_parameters(file_name):\r\n if(file_name):\r\n with open(file_name, 'r') as f:\r\n return json.load(f)\r\n\r\ndef main():\r\n #from pudb.remote import set_trace; set_trace(term_size=(160, 40), host='0.0.0.0', port=6900)\r\n input_dir = os.path.abspath('./data')\r\n output_dir = os.path.abspath('./data/output')\r\n if(path.exists(output_dir)):\r\n print(\"Output folder already exists. Please, remove output folders.\")\r\n return None\r\n #last_char = output_dir[:-1]\r\n #if(last_char.isdigit()):\r\n # nr = int(last_char) + 1\r\n # os.mkdir(os.path.abspath('/data/output' + '_' + str(nr)))\r\n # output_path = os.path.abspath('/data/output' +'_' + str(nr))\r\n #else:\r\n # nr = 2\r\n # os.mkdir(os.path.abspath('/data/output' + '_' + str(nr)))\r\n # output_path = os.path.abspath('/data/output' +'_' + str(nr))\r\n else:\r\n os.mkdir(output_dir)\r\n output_path = output_dir \r\n\r\n\r\n output_gray = os.path.join(output_path, 'gray/')\r\n os.mkdir(output_gray)\r\n\r\n output_thresh = os.path.join(output_path, 'thresh/')\r\n os.mkdir(output_thresh)\r\n output_files = os.path.join(output_path, 'files/')\r\n os.mkdir(output_files)\r\n output_files_analysis = os.path.join(output_path, 'files_analysis/')\r\n os.mkdir(output_files_analysis)\r\n\r\n output_histograms = os.path.join(output_path, 'histogram/')\r\n os.mkdir(output_histograms)\r\n\r\n output_circles = os.path.join(output_path, 'circles/')\r\n os.mkdir(output_circles)\r\n\r\n for img in glob.glob(\"{}/*jpg\".format(input_dir)):\r\n file_name = os.path.basename(img)[:-4]\r\n parameters = read_parameters(img[:-4] + '.json')\r\n\r\n print(file_name)\r\n img_gray = convert_to_grayscale(img, file_name, output_gray)\r\n cdf_percentage, bins = cumsum_histogram_percentage(img_gray, file_name, output_histograms) #confirm if histogram is well done\r\n img_thresh75 = remove_background(img_gray, file_name, cdf_percentage, bins, output_thresh)\r\n\r\n x_set, y_set, r_set = get_droplets(img_thresh75, file_name, parameters, output_circles)\r\n file_droplets(file_name, output_path, parameters, x_set, y_set, r_set)\r\n analyse_droplets(output_files, output_files_analysis)\r\n #analysis_file = 'droplets_analysis.csv'\r\n #sort_file(os.path.join(output_files_analysis, analysis_file), output_files_analysis)\r\n #analysis_file_sorted = 'droplets_analysis_sorted.csv'\r\n #validation_file = 'vocs_expected_sorted.csv'\r\n\r\n #complete_file = add_columns_validation(os.path.join(output_files_analysis, analysis_file_sorted), os.path.join(output_files_analysis, validation_file), output_files_analysis)\r\n #complete_file = os.path.join(output_files_analysis, 'droplets_analysis_complete.csv')\r\n #validation_file = os.path.join(output_files_analysis, validation_file)\r\n #compare_results(complete_file, output_files_analysis)\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n\r\n\r\n\r\n\r\n\r\n#for i in range(nr_images):\r\n" ]
[ [ "matplotlib.pyplot.legend", "matplotlib.pyplot.tight_layout", "pandas.read_csv", "matplotlib.pyplot.subplots", "pandas.DataFrame", "matplotlib.pyplot.gcf", "matplotlib.pyplot.plot", "matplotlib.pyplot.Circle", "matplotlib.pyplot.xlim", "numpy.array", "numpy.where" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
FedeClaudi/fedes_utils
[ "2ef6f037303fc426d5c5b2851d2c99f17efa4002" ]
[ "fcutils/maths/coordinates.py" ]
[ "import numpy as np\n\n\ndef R(theta):\n \"\"\"\n Returns the rotation matrix for rotating an object\n centered around the origin with a given angle\n\n Arguments:\n theta: angle in degrees\n\n Returns:\n R: 2x2 np.ndarray with rotation matrix\n \"\"\"\n theta = np.radians(theta)\n return np.array(\n [[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]]\n )\n\n\ndef M(axis=\"x\"):\n \"\"\"\n Returns a matrix to mirror an object against a given axis\n\n Arguments:\n axis: str. 'x', 'y', 'origin' or 'xy'\n\n Returns:\n M: mirror matrix\n \"\"\"\n if axis == \"x\":\n return np.array([[1, 0], [0, -1]])\n elif axis == \"y\":\n return np.array([[-1, 0], [0, 1]])\n elif axis == \"origin\":\n return np.array([[-1, 0], [0, -1]])\n elif axis == \"xy\":\n return np.array([[0, 1], [1, 0]])\n else:\n raise NotImplementedError(\n f\"Could not recognize axis of mirroring: {axis}\"\n )\n\n\ndef cart2pol(x, y):\n \"\"\"\n Cartesian to polar coordinates\n\n angles in degrees\n \"\"\"\n rho = np.hypot(x, y)\n phi = np.degrees(np.arctan2(y, x))\n return rho, phi\n\n\ndef pol2cart(rho, phi):\n \"\"\"\n Polar to cartesian coordinates\n\n angles in degrees\n \"\"\"\n x = rho * np.cos(np.radians(phi))\n y = rho * np.sin(np.radians(phi))\n return x, y\n" ]
[ [ "numpy.radians", "numpy.cos", "numpy.sin", "numpy.arctan2", "numpy.array", "numpy.hypot" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
algonommy/Analyzing-Apple-Stock-Data-to-Predict-Gain-Loss-leveraging-Machine-Learning-Models
[ "04d5b42d58f64248a45b62c7f7a0835c481c12fb" ]
[ "Dash-app/app.py" ]
[ "import dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport pandas as pd\nimport plotly.graph_objs as go\nfrom dash.dependencies import Input, Output\nimport datetime as dt\nimport pandas_datareader as web\n\n\n\napp = dash.Dash()\nserver = app.server\n\nstart = dt.datetime(2000,1,1)\nend = dt.datetime.now()\ndf = web.DataReader('AAPL','yahoo', start, end)\ndf=df.reset_index()\n\ndf[\"Date\"]=pd.to_datetime(df.Date,format=\"%Y-%m-%d\")\ndf.index=df['Date']\n\ndata=df.sort_index(ascending=True,axis=0)\nnew_data=pd.DataFrame(index=range(0,len(df)),columns=['Date','Close'])\n\nfor i in range(0,len(data)):\n new_data[\"Date\"][i]=data['Date'][i]\n new_data[\"Close\"][i]=data[\"Close\"][i]\n \nnew_data=new_data.set_index('Date')\ndataset=new_data.values\n\n\ntickers = ['TSLA','AAPL','FB','MSFT','SBUX']\ndf1 = web.DataReader(tickers, data_source='yahoo', start='2017-01-01', end=dt.datetime.now())\ndf=df1.stack().reset_index().rename(index=str, columns={\"level_1\": \"Symbols\"}).sort_values(['Symbols','Date'])\ndf[\"Date\"]=pd.to_datetime(df.Date,format=\"%Y-%m-%d\")\ndf.index=df['Date']\n\n\nD_validationData= pd.read_csv(\"LSTM_validation.csv\")\nD_train_data= pd.read_csv(\"LSTM_train.csv\")\n\n\nfig2 = go.Figure()\nfig2.add_trace(go.Scatter(x=D_validationData[\"Date\"], y=D_validationData[\"Close\"],\n mode='lines',name='Validation',line=dict(color=\"blue\",width=4)))\nfig2.add_trace(go.Scatter(x=D_validationData[\"Date\"], y=D_validationData[\"Predictions\"],\n mode='lines',name='Stock Price Predicted ',line=dict(color=\"red\",width=4)))\nfig2.add_trace(go.Scatter(x=D_train_data[\"Date\"], y=D_train_data[\"Close\"],\n mode='lines', name='Train',line=dict(color=\"darkblue\",width=4)))\n\n\nfig2.update_layout(hovermode='x unified',\n showlegend=True,\n plot_bgcolor=\"white\",\n paper_bgcolor = \"rgba(0,0,0,0)\",\n xaxis_title=\"Date\",\n yaxis_title=\"Closing Rate\",\n legend_title=\"Data:\",\n margin=dict(t=50,l=200,b=50,r=200),\n \n)\n\nfig2.update_xaxes(showline=True, linewidth=2, linecolor='white', gridcolor='lightgray')\nfig2.update_yaxes(showline=True, linewidth=2, linecolor='white', gridcolor='lightgray')\n\n\nmoving_avg= pd.read_csv(\"test_mov_avg.csv\")\n\n\nfig3 = go.Figure()\nfig3.add_trace(go.Scatter(x=moving_avg[\"date\"], y=moving_avg[\"close\"],\n mode='lines',\n name='Test',\n line=dict(color=\"darkblue\",width=3)))\nfig3.add_trace(go.Scatter(x=moving_avg[\"date\"], y=moving_avg[\"est_N2\"],\n mode='lines',\n name='Stock Price Predicted',\n line=dict(color=\"red\",width=3)))\n\nfig3.update_layout(hovermode='x unified',\n showlegend=True,\n plot_bgcolor=\"white\",\n paper_bgcolor = \"rgba(0,0,0,0)\",\n xaxis_title=\"Date\",\n yaxis_title=\"Closing Rate\",\n legend_title=\"Data:\",\n margin=dict(t=50,l=200,b=50,r=200),\n \n)\nfig3.update_xaxes(showline=True, linewidth=1, linecolor='white', gridcolor='lightgray')\nfig3.update_yaxes(showline=True, linewidth=1, linecolor='white', gridcolor='lightgray')\n\n# Import CSV tree training data\nTree_training= pd.read_csv(\"Tree_training_data.csv\")\nTree_prediction= pd.read_csv(\"Tree_model_prediction.csv\")\n\n\nfigt = go.Figure()\nfigt.add_trace(go.Scatter(x=Tree_training[\"Date\"], y=Tree_training[\"Close\"],\n mode='lines',\n name='Training ',\n line=dict(color=\"darkblue\",width=3)))\nfigt.add_trace(go.Scatter(x=Tree_prediction[\"Date\"], y=Tree_prediction[\"Close\"],\n mode='lines',\n name='Validation',\n line=dict(color=\"blue\",width=4)))\nfigt.add_trace(go.Scatter(x=Tree_prediction[\"Date\"], y=Tree_prediction[\"Predictions\"],\n mode='lines', name='Stock Price Predicted',\n line=dict(color=\"red\",width=2)))\n\n\nfigt.update_layout(hovermode='x unified',\n showlegend=True,\n plot_bgcolor=\"white\",\n paper_bgcolor = \"rgba(0,0,0,0)\",\n xaxis_title=\"Date\",\n yaxis_title=\"Closing Rate\",\n legend_title=\"Data:\",\n margin=dict(t=50,l=200,b=50,r=200),\n \n)\nfigt.update_xaxes(showline=True, linewidth=2, linecolor='white', gridcolor='lightgray')\nfigt.update_yaxes(showline=True, linewidth=2, linecolor='white', gridcolor='lightgray')\n\n\n# Linear Regression Model data\nLR_train= pd.read_csv(\"LR_train.csv\")\nLR_prediction= pd.read_csv(\"LR_prediction.csv\")\n\n# Create figure lines for Linear Regression Model\nfigLR = go.Figure()\nfigLR.add_trace(go.Scatter(x=LR_train[\"Date\"], y=LR_train[\"Close\"],\n mode='lines',\n name='Training ',\n line=dict(color=\"darkblue\",width=3)))\nfigLR.add_trace(go.Scatter(x=LR_prediction[\"Date\"], y=LR_prediction[\"Close\"],\n mode='lines',\n name='Validation',\n line=dict(color=\"blue\",width=3)))\nfigLR.add_trace(go.Scatter(x=LR_prediction[\"Date\"], y=LR_prediction[\"Predictionslr\"],\n mode='lines', name='Stock Price Predicted',\n line=dict(color=\"red\",width=3)))\n\n\n\nfigLR.update_layout(hovermode='x unified',\n showlegend=True,\n plot_bgcolor=\"white\",\n paper_bgcolor = \"rgba(0,0,0,0)\",\n xaxis_title=\"Date\",\n yaxis_title=\"Closing Rate\",\n legend_title=\"Data:\",\n margin=dict(t=50,l=200,b=50,r=200),\n \n)\n\nfigLR.update_xaxes(showline=True, linewidth=2, linecolor='white', gridcolor='lightgray')\nfigLR.update_yaxes(showline=True, linewidth=2, linecolor='white', gridcolor='lightgray')\n\n\n# Getting Info for all Models comparison\nl30=dt.datetime.now()- dt.timedelta(30)\nm_actual = web.DataReader('AAPL','yahoo', l30, dt.datetime.now())\nm_actual=m_actual.reset_index()\n\n# COMPLETE code to get models table\nl30=dt.datetime.now()- dt.timedelta(30)\n\n# Actual\nm_actual_df = web.DataReader('AAPL','yahoo', l30, dt.datetime.now())\nm_actual_df=m_actual_df.reset_index()\nm_actual=m_actual_df[['Date','Close']]\nm_actual[\"Model\"]=\"Actual Close Price\"\nm_actual.rename(columns={'Close':'Predictions'}, inplace=True)\n\n# LR\nm_LR=LR_prediction[['Date','Predictionslr']]\nm_LR[\"Model\"]=\"Linear Regression Model\"\nm_LR.rename(columns={'Predictionslr':'Predictions'}, inplace=True)\n\n\n# Tree Prediction\nm_tree=Tree_prediction[['Date','Predictions']]\nm_tree[\"Model\"]=\"Tree Model\"\n\n# Moving Average\nm_MA=moving_avg[['date','est_N2']]\nm_MA[\"Model\"]=\"Moving Average Model\"\nm_MA.rename(columns={'est_N2':'Predictions','date':\"Date\"}, inplace=True)\nm_MA[\"Date\"]=pd.to_datetime(m_MA.Date,format=\"%Y-%m-%d\")\nm_MA1 = m_MA[(m_MA['Date']>(dt.datetime.now()- dt.timedelta(30))) & (m_MA['Date']<dt.datetime.now())] \n\n# Long short-term memory\nD_validationData[\"Date\"]=pd.to_datetime(D_validationData.Date,format=\"%Y-%m-%d\")\nm_LSTM=D_validationData[['Date','Predictions']]\nm_LSTM[\"Model\"]=\"Long Short-Term Memory\"\nm_LSTM1 = m_LSTM[(m_LSTM['Date']>(dt.datetime.now()- dt.timedelta(30))) & (m_LSTM['Date']<dt.datetime.now())] \n\n\n# Model table\nframes=[m_tree,m_actual,m_LR,m_MA1,m_LSTM1]\nmodels=pd.concat(frames)\nmodels\n\n# HTML code to render results- Layout formating\n\napp.layout = html.Div([\n \n html.H1(\"Apple Stock Price Prediction- Machine Learning & Python\", style={'textAlign': 'center','color':'#07098d'}),\n html.H2(\"\", style={'textAlign': 'center','color':'#07098d'}),\n dcc.Tabs(id=\"tabs\", children=[\n \n dcc.Tab(label='LSTM',children=[\n\t\t\thtml.Div([\t\t\t\t\n\t\t\t html.H2(\"Long Short-Term Memory (LSTM)\", \n style={'textAlign': 'center'}),\n html.H3(\"On this LSTM Model 75% of the data was trained and 25% was tested to predict Apple stock price using the past 60 days closing price.\", \n style={'textAlign': 'left'}),\n html.H3(\"The data was taken from Yahoo from 2010-01-04 to 2021-03-16. The LSTM-rsme is 24.37\", \n style={'textAlign': 'left'}),\n html.H3(\"The predicted price for the March 17th = USS 123.5\", \n style={'textAlign': 'left'}),\n html.H3(\"The predicted price for the March 18th = USS 128.5 \", \n style={'textAlign': 'left'}),\n\n\n dcc.Graph(id = 'GrapLTSM',\n figure = fig2),\n ]\n ), \t\t\n ]),\n\n\n dcc.Tab(label='Moving Average',children=[\n\t\t\thtml.Div([\t\t\t\t\n\t\t\t html.H2(\"Moving Average to predict Apple Stock Price\", \n style={'textAlign': 'center'}),\n html.H3(\"The moving average is a simple technical analysis tool that smooths out price data by creating a constantly updating average.\", \n style={'textAlign': 'left'}),\n\n dcc.Graph(id = 'GrapMovingAvg',\n figure = fig3),\n ]\n ),\n ]),\n\n dcc.Tab(label='Tree Model and Linear Regression',children=[\n\t\t\thtml.Div([\t\t\t\t\n\t\t\t html.H2(\"Apple Sock Price Prediction For the Last 30 Days - Tree Prediction Model\", \n style={'textAlign': 'center'}),\n # html.H3(\"Tree Model and Linear Regression Stock Prediction Tree Model and Linear Regression Stock Prediction Tree Model and Linear Regression Stock Prediction\", \n # style={'textAlign': 'left'}),\n\n dcc.Graph(id = 'GrapTreeLR',\n figure = figt),\n \n\n html.H2(\"Apple Stock Price For The Last 30 Days - Linear Regression Model\", \n style={'textAlign': 'center'}),\n # html.H3(\"Tree Model and Linear Regression Stock Prediction Tree Model and Linear Regression Stock Prediction Tree Model and Linear Regression Stock Prediction\", \n # style={'textAlign': 'left'}),\n\n dcc.Graph(id = 'GrapLR',\n figure = figLR),\n ],className=\"container\"),\n \n ]),\n\n dcc.Tab(label='Model Comparison', children=[\n html.Div([\n html.H2(\"Select Model to compare\", \n style={'textAlign': 'center','color':'#07098d'}),\n \n dcc.Dropdown(id='my-dropdownM',\n options=[{'label': 'Long Short-Term Memory', 'value': 'Long Short-Term Memory'},\n {'label': 'Moving Average','value': 'Moving Average Model'},\n {'label': 'Tree Model','value': 'Tree Model'}, \n {'label': 'Actual Close Price','value' :'Actual Close Price'},\n {'label': 'Linear Regression', 'value': 'Linear Regression Model'}], \n multi=True,value=['Actual Close Price'],\n style={\"display\": \"block\", \"margin-left\": \"auto\", \n \"margin-right\": \"auto\", \"width\": \"60%\"}),\n dcc.Graph(id='models'),\n \n ], className=\"container\"),\n ]),\n\n\n\n dcc.Tab(label='Stock Data other Companies', children=[\n html.Div([\n html.H2(\"Stocks Price comparison High and Lows\", \n style={'textAlign': 'center','color':'#07098d'}),\n \n dcc.Dropdown(id='my-dropdown',\n options=[{'label': 'Tesla', 'value': 'TSLA'},\n {'label': 'Starbucks','value': 'SBUX'},\n {'label': 'Apple','value': 'AAPL'}, \n {'label': 'Facebook', 'value': 'FB'}, \n {'label': 'Microsoft','value': 'MSFT'}], \n multi=True,value=['SBUX'],\n style={\"display\": \"block\", \"margin-left\": \"auto\", \n \"margin-right\": \"auto\", \"width\": \"60%\"}),\n dcc.Graph(id='highlow'),\n\n html.H2(\"Stocks Market Volume\", style={'textAlign': 'center'}),\n \n dcc.Dropdown(id='my-dropdown2',\n options=[{'label': 'Tesla', 'value': 'SBUX'},\n {'label': 'Starbucks', 'value': 'SBUX'},\n {'label': 'Apple','value': 'AAPL'}, \n {'label': 'Facebook', 'value': 'FB'},\n {'label': 'Microsoft','value': 'MSFT'}], \n multi=True,value=['SBUX'],\n style={\"display\": \"block\", \"margin-left\": \"auto\", \n \"margin-right\": \"auto\", \"width\": \"60%\"}),\n dcc.Graph(id='volume')\n ], className=\"container\"),\n ])\n ])\n])\n\n\n\[email protected](Output('highlow', 'figure'),\n [Input('my-dropdown', 'value')])\ndef update_graph(selected_dropdown):\n dropdown = {\"TSLA\": \"Tesla\",\"SBUX\":\"Starbucks\",\"AAPL\": \"Apple\",\"FB\": \"Facebook\",\"MSFT\": \"Microsoft\",}\n trace1 = []\n trace2 = []\n for stock in selected_dropdown:\n trace1.append(\n go.Scatter(x=df[df[\"Symbols\"] == stock][\"Date\"],\n y=df[df[\"Symbols\"] == stock][\"High\"],\n mode='lines', opacity=0.7, \n name=f'High {dropdown[stock]}',textposition='bottom center'))\n trace2.append(\n go.Scatter(x=df[df[\"Symbols\"] == stock][\"Date\"],\n y=df[df[\"Symbols\"] == stock][\"Low\"],\n mode='lines', opacity=0.6,\n name=f'Low {dropdown[stock]}',textposition='bottom center'))\n traces = [trace1, trace2]\n data = [val for sublist in traces for val in sublist]\n figure = {'data': data,\n 'layout': go.Layout(colorway=[\"#5E0DAC\", '#FF4F00', '#375CB1', \n '#FF7400', '#FFF400', '#FF0056'],\n height=600,\n title=f\"High and Low Prices for {', '.join(str(dropdown[i]) for i in selected_dropdown)} Over Time\",\n xaxis={\"title\":\"Date\",\n 'rangeselector': {'buttons': list([{'count': 1, 'label': '1M', \n 'step': 'month', \n 'stepmode': 'backward'},\n {'count': 6, 'label': '6M', \n 'step': 'month', \n 'stepmode': 'backward'},\n {'step': 'all'}])},\n 'rangeslider': {'visible': True}, 'type': 'date'},\n yaxis={\"title\":\"Price (USD)\"})}\n return figure\n\n\[email protected](Output('volume', 'figure'),\n [Input('my-dropdown2', 'value')])\ndef update_graph(selected_dropdown_value):\n dropdown = {\"TSLA\": \"Tesla\",\"AAPL\": \"Apple\",\"FB\": \"Facebook\",\"SBUX\":\"Starbucks\",\"MSFT\": \"Microsoft\",}\n trace1 = []\n for stock in selected_dropdown_value:\n trace1.append(\n go.Scatter(x=df[df[\"Symbols\"] == stock][\"Date\"],\n y=df[df[\"Symbols\"] == stock][\"Volume\"],\n mode='lines', opacity=0.7,\n name=f'Volume {dropdown[stock]}', textposition='bottom center'))\n traces = [trace1]\n data = [val for sublist in traces for val in sublist]\n figure = {'data': data, \n 'layout': go.Layout(colorway=[\"#5E0DAC\", '#FF4F00', '#375CB1', \n '#FF7400', '#FFF400', '#FF0056'],\n height=600,\n title=f\"Market Volume for {', '.join(str(dropdown[i]) for i in selected_dropdown_value)} Over Time\",\n xaxis={\"title\":\"Date\",\n 'rangeselector': {'buttons': list([{'count': 1, 'label': '1M', \n 'step': 'month', \n 'stepmode': 'backward'},\n {'count': 6, 'label': '6M',\n 'step': 'month', \n 'stepmode': 'backward'},\n {'step': 'all'}])},\n 'rangeslider': {'visible': True}, 'type': 'date'},\n yaxis={\"title\":\"Transactions Volume\"})}\n return figure\n\[email protected](Output('models', 'figure'),\n [Input('my-dropdownM', 'value')])\n\ndef update_graph(mydropdownM):\n dropdown = {\"Actual Close Price\":\"Actual Close Price\",\"Long Short-Term Memory\": \"Long Short-Term Memory\",\"Moving Average Model\":\"Moving Average\",\"Tree Model\": \"Tree Model\",\"Linear Regression Model\": \"Linear Regression\",}\n trace1=[] \n for model in mydropdownM: \n trace1.append(\n go.Scatter(x=models[models[\"Model\"] == model][\"Date\"],\n y=models[models[\"Model\"] == model][\"Predictions\"],\n mode='lines', opacity=0.7, \n name=f' {dropdown[model]}',textposition='bottom center'))\n traces = [trace1] \n data = [val for sublist in traces for val in sublist]\n figure = {'data': data,\n 'layout': go.Layout(colorway=[\"#5E0DAC\", '#FF4F00', '#375CB1', \n '#FF7400', '#FFF400', '#FF0056'],\n height=400,\n title=f\"ML Models: {', '.join(str(dropdown[i]) for i in mydropdownM)} \",\n xaxis={\"title\":\"Date\",\n 'rangeselector': {'buttons': list([{'count': 1, 'label': '1M', \n 'step': 'month', \n 'stepmode': 'backward'},\n {'count': 6, 'label': '6M', \n 'step': 'month', \n 'stepmode': 'backward'},\n {'step': 'all'}])},\n 'rangeslider': {'visible': False}, 'type': 'date'},\n yaxis={\"title\":\"Price (USD)\"})}\n return figure\n\n\nif __name__=='__main__':\n\tapp.run_server(debug=True)" ]
[ [ "pandas.concat", "pandas.to_datetime", "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
mrmotallebi/pytorch_geometric
[ "5d768659d2a54544219c057ad05172ca55b43119", "5d768659d2a54544219c057ad05172ca55b43119", "5d768659d2a54544219c057ad05172ca55b43119", "5d768659d2a54544219c057ad05172ca55b43119", "5d768659d2a54544219c057ad05172ca55b43119" ]
[ "torch_geometric/nn/pool/asap.py", "test/utils/test_metric.py", "test/nn/dense/test_diff_pool.py", "torch_geometric/datasets/snap_dataset.py", "examples/mnist_graclus.py" ]
[ "from typing import Union, Optional, Callable\n\nimport torch\nimport torch.nn.functional as F\nfrom torch.nn import Linear\nfrom torch_scatter import scatter\nfrom torch_sparse import SparseTensor\n\nfrom torch_geometric.nn import LEConv\nfrom torch_geometric.utils import softmax\nfrom torch_geometric.nn.pool.topk_pool import topk\nfrom torch_geometric.utils import add_remaining_self_loops\n\n\nclass ASAPooling(torch.nn.Module):\n r\"\"\"The Adaptive Structure Aware Pooling operator from the\n `\"ASAP: Adaptive Structure Aware Pooling for Learning Hierarchical\n Graph Representations\" <https://arxiv.org/abs/1911.07979>`_ paper.\n\n Args:\n in_channels (int): Size of each input sample.\n ratio (float or int): Graph pooling ratio, which is used to compute\n :math:`k = \\lceil \\mathrm{ratio} \\cdot N \\rceil`, or the value\n of :math:`k` itself, depending on whether the type of :obj:`ratio`\n is :obj:`float` or :obj:`int`. (default: :obj:`0.5`)\n GNN (torch.nn.Module, optional): A graph neural network layer for\n using intra-cluster properties.\n Especially helpful for graphs with higher degree of neighborhood\n (one of :class:`torch_geometric.nn.conv.GraphConv`,\n :class:`torch_geometric.nn.conv.GCNConv` or\n any GNN which supports the :obj:`edge_weight` parameter).\n (default: :obj:`None`)\n dropout (float, optional): Dropout probability of the normalized\n attention coefficients which exposes each node to a stochastically\n sampled neighborhood during training. (default: :obj:`0`)\n negative_slope (float, optional): LeakyReLU angle of the negative\n slope. (default: :obj:`0.2`)\n add_self_loops (bool, optional): If set to :obj:`True`, will add self\n loops to the new graph connectivity. (default: :obj:`False`)\n **kwargs (optional): Additional parameters for initializing the\n graph neural network layer.\n \"\"\"\n def __init__(self, in_channels: int, ratio: Union[float, int] = 0.5,\n GNN: Optional[Callable] = None, dropout: float = 0.0,\n negative_slope: float = 0.2, add_self_loops: bool = False,\n **kwargs):\n super(ASAPooling, self).__init__()\n\n self.in_channels = in_channels\n self.ratio = ratio\n self.negative_slope = negative_slope\n self.dropout = dropout\n self.GNN = GNN\n self.add_self_loops = add_self_loops\n\n self.lin = Linear(in_channels, in_channels)\n self.att = Linear(2 * in_channels, 1)\n self.gnn_score = LEConv(self.in_channels, 1)\n if self.GNN is not None:\n self.gnn_intra_cluster = GNN(self.in_channels, self.in_channels,\n **kwargs)\n self.reset_parameters()\n\n def reset_parameters(self):\n self.lin.reset_parameters()\n self.att.reset_parameters()\n self.gnn_score.reset_parameters()\n if self.GNN is not None:\n self.gnn_intra_cluster.reset_parameters()\n\n def forward(self, x, edge_index, edge_weight=None, batch=None):\n N = x.size(0)\n\n edge_index, edge_weight = add_remaining_self_loops(\n edge_index, edge_weight, fill_value=1, num_nodes=N)\n\n if batch is None:\n batch = edge_index.new_zeros(x.size(0))\n\n x = x.unsqueeze(-1) if x.dim() == 1 else x\n\n x_pool = x\n if self.GNN is not None:\n x_pool = self.gnn_intra_cluster(x=x, edge_index=edge_index,\n edge_weight=edge_weight)\n\n x_pool_j = x_pool[edge_index[0]]\n x_q = scatter(x_pool_j, edge_index[1], dim=0, reduce='max')\n x_q = self.lin(x_q)[edge_index[1]]\n\n score = self.att(torch.cat([x_q, x_pool_j], dim=-1)).view(-1)\n score = F.leaky_relu(score, self.negative_slope)\n score = softmax(score, edge_index[1], num_nodes=N)\n\n # Sample attention coefficients stochastically.\n score = F.dropout(score, p=self.dropout, training=self.training)\n\n v_j = x[edge_index[0]] * score.view(-1, 1)\n x = scatter(v_j, edge_index[1], dim=0, reduce='add')\n\n # Cluster selection.\n fitness = self.gnn_score(x, edge_index).sigmoid().view(-1)\n perm = topk(fitness, self.ratio, batch)\n x = x[perm] * fitness[perm].view(-1, 1)\n batch = batch[perm]\n\n # Graph coarsening.\n row, col = edge_index\n A = SparseTensor(row=row, col=col, value=edge_weight,\n sparse_sizes=(N, N))\n S = SparseTensor(row=row, col=col, value=score, sparse_sizes=(N, N))\n S = S[:, perm]\n\n A = S.t() @ A @ S\n\n if self.add_self_loops:\n A = A.fill_diag(1.)\n else:\n A = A.remove_diag()\n\n row, col, edge_weight = A.coo()\n edge_index = torch.stack([row, col], dim=0)\n\n return x, edge_index, edge_weight, batch, perm\n\n def __repr__(self):\n return '{}({}, ratio={})'.format(self.__class__.__name__,\n self.in_channels, self.ratio)\n", "from __future__ import division\n\nimport torch\nfrom torch_geometric.utils import (accuracy, true_positive, true_negative,\n false_positive, false_negative, precision,\n recall, f1_score, mean_iou)\n\n\ndef test_metric():\n pred = torch.tensor([0, 0, 1, 1])\n target = torch.tensor([0, 1, 0, 1])\n\n assert accuracy(pred, target) == 0.5\n assert true_positive(pred, target, num_classes=2).tolist() == [1, 1]\n assert true_negative(pred, target, num_classes=2).tolist() == [1, 1]\n assert false_positive(pred, target, num_classes=2).tolist() == [1, 1]\n assert false_negative(pred, target, num_classes=2).tolist() == [1, 1]\n assert precision(pred, target, num_classes=2).tolist() == [0.5, 0.5]\n assert recall(pred, target, num_classes=2).tolist() == [0.5, 0.5]\n assert f1_score(pred, target, num_classes=2).tolist() == [0.5, 0.5]\n\n\ndef test_mean_iou():\n pred = torch.tensor([0, 0, 1, 1, 0, 1])\n target = torch.tensor([0, 1, 0, 1, 0, 0])\n\n out = mean_iou(pred, target, num_classes=2)\n assert out == (0.4 + 0.25) / 2\n\n batch = torch.tensor([0, 0, 0, 0, 1, 1])\n out = mean_iou(pred, target, num_classes=2, batch=batch)\n assert out.size() == (2, )\n assert out[0] == (1 / 3 + 1 / 3) / 2\n assert out[1] == 0.25\n", "import torch\nfrom torch_geometric.nn import dense_diff_pool\n\n\ndef test_dense_diff_pool():\n batch_size, num_nodes, channels, num_clusters = (2, 20, 16, 10)\n x = torch.randn((batch_size, num_nodes, channels))\n adj = torch.rand((batch_size, num_nodes, num_nodes))\n s = torch.randn((batch_size, num_nodes, num_clusters))\n mask = torch.randint(0, 2, (batch_size, num_nodes), dtype=torch.bool)\n\n x, adj, link_loss, ent_loss = dense_diff_pool(x, adj, s, mask)\n assert x.size() == (2, 10, 16)\n assert adj.size() == (2, 10, 10)\n assert link_loss.item() >= 0\n assert ent_loss.item() >= 0\n", "import os\nimport os.path as osp\n\nimport torch\nimport pandas\nimport numpy as np\nfrom torch_sparse import coalesce\nfrom torch_geometric.data import (Data, InMemoryDataset, download_url,\n extract_gz, extract_tar)\nfrom torch_geometric.data.makedirs import makedirs\n\n\nclass EgoData(Data):\n def __inc__(self, key, item):\n if key == 'circle':\n return self.num_nodes\n elif key == 'circle_batch':\n return item.max().item() + 1 if item.numel() > 0 else 0\n else:\n return super(EgoData, self).__inc__(key, item)\n\n\ndef read_ego(files, name):\n all_featnames = []\n files = [\n x for x in files if x.split('.')[-1] in\n ['circles', 'edges', 'egofeat', 'feat', 'featnames']\n ]\n for i in range(4, len(files), 5):\n featnames_file = files[i]\n with open(featnames_file, 'r') as f:\n featnames = f.read().split('\\n')[:-1]\n featnames = [' '.join(x.split(' ')[1:]) for x in featnames]\n all_featnames += featnames\n all_featnames = sorted(list(set(all_featnames)))\n all_featnames = {key: i for i, key in enumerate(all_featnames)}\n\n data_list = []\n for i in range(0, len(files), 5):\n circles_file = files[i]\n edges_file = files[i + 1]\n egofeat_file = files[i + 2]\n feat_file = files[i + 3]\n featnames_file = files[i + 4]\n\n x = None\n if name != 'gplus': # Don't read node features on g-plus:\n x_ego = pandas.read_csv(egofeat_file, sep=' ', header=None,\n dtype=np.float32)\n x_ego = torch.from_numpy(x_ego.values)\n\n x = pandas.read_csv(feat_file, sep=' ', header=None,\n dtype=np.float32)\n x = torch.from_numpy(x.values)[:, 1:]\n\n x_all = torch.cat([x, x_ego], dim=0)\n\n # Reorder `x` according to `featnames` ordering.\n x_all = torch.zeros(x.size(0), len(all_featnames))\n with open(featnames_file, 'r') as f:\n featnames = f.read().split('\\n')[:-1]\n featnames = [' '.join(x.split(' ')[1:]) for x in featnames]\n indices = [all_featnames[featname] for featname in featnames]\n x_all[:, torch.tensor(indices)] = x\n x = x_all\n\n idx = pandas.read_csv(feat_file, sep=' ', header=None, dtype=str,\n usecols=[0], squeeze=True)\n\n idx_assoc = {}\n for i, j in enumerate(idx):\n idx_assoc[j] = i\n\n circles = []\n circles_batch = []\n with open(circles_file, 'r') as f:\n for i, circle in enumerate(f.read().split('\\n')[:-1]):\n circle = [idx_assoc[c] for c in circle.split()[1:]]\n circles += circle\n circles_batch += [i] * len(circle)\n circle = torch.tensor(circles)\n circle_batch = torch.tensor(circles_batch)\n\n try:\n row = pandas.read_csv(edges_file, sep=' ', header=None, dtype=str,\n usecols=[0], squeeze=True)\n col = pandas.read_csv(edges_file, sep=' ', header=None, dtype=str,\n usecols=[1], squeeze=True)\n except: # noqa\n continue\n\n row = torch.tensor([idx_assoc[i] for i in row])\n col = torch.tensor([idx_assoc[i] for i in col])\n\n N = max(int(row.max()), int(col.max())) + 2\n N = x.size(0) if x is not None else N\n\n row_ego = torch.full((N - 1, ), N - 1, dtype=torch.long)\n col_ego = torch.arange(N - 1)\n\n # Ego node should be connected to every other node.\n row = torch.cat([row, row_ego, col_ego], dim=0)\n col = torch.cat([col, col_ego, row_ego], dim=0)\n edge_index = torch.stack([row, col], dim=0)\n\n edge_index, _ = coalesce(edge_index, None, N, N)\n data = Data(x=x, edge_index=edge_index, circle=circle,\n circle_batch=circle_batch)\n\n data_list.append(data)\n\n return data_list\n\n\ndef read_soc(files, name):\n skiprows = 4\n if name == 'pokec':\n skiprows = 0\n\n edge_index = pandas.read_csv(files[0], sep='\\t', header=None,\n skiprows=skiprows, dtype=np.int64)\n edge_index = torch.from_numpy(edge_index.values).t()\n num_nodes = edge_index.max().item() + 1\n edge_index, _ = coalesce(edge_index, None, num_nodes, num_nodes)\n\n return [Data(edge_index=edge_index, num_nodes=num_nodes)]\n\n\ndef read_wiki(files, name):\n edge_index = pandas.read_csv(files[0], sep='\\t', header=None, skiprows=4,\n dtype=np.int64)\n edge_index = torch.from_numpy(edge_index.values).t()\n\n idx = torch.unique(edge_index.flatten())\n idx_assoc = torch.full((edge_index.max() + 1, ), -1, dtype=torch.long)\n idx_assoc[idx] = torch.arange(idx.size(0))\n\n edge_index = idx_assoc[edge_index]\n num_nodes = edge_index.max().item() + 1\n edge_index, _ = coalesce(edge_index, None, num_nodes, num_nodes)\n\n return [Data(edge_index=edge_index, num_nodes=num_nodes)]\n\n\nclass SNAPDataset(InMemoryDataset):\n r\"\"\"A variety of graph datasets collected from `SNAP at Stanford University\n <https://snap.stanford.edu/data>`_.\n\n Args:\n root (string): Root directory where the dataset should be saved.\n name (string): The name of the dataset.\n transform (callable, optional): A function/transform that takes in an\n :obj:`torch_geometric.data.Data` object and returns a transformed\n version. The data object will be transformed before every access.\n (default: :obj:`None`)\n pre_transform (callable, optional): A function/transform that takes in\n an :obj:`torch_geometric.data.Data` object and returns a\n transformed version. The data object will be transformed before\n being saved to disk. (default: :obj:`None`)\n pre_filter (callable, optional): A function that takes in an\n :obj:`torch_geometric.data.Data` object and returns a boolean\n value, indicating whether the data object should be included in the\n final dataset. (default: :obj:`None`)\n \"\"\"\n\n url = 'https://snap.stanford.edu/data'\n\n available_datasets = {\n 'ego-facebook': ['facebook.tar.gz'],\n 'ego-gplus': ['gplus.tar.gz'],\n 'ego-twitter': ['twitter.tar.gz'],\n 'soc-epinions1': ['soc-Epinions1.txt.gz'],\n 'soc-livejournal1': ['soc-LiveJournal1.txt.gz'],\n 'soc-pokec': ['soc-pokec-relationships.txt.gz'],\n 'soc-slashdot0811': ['soc-Slashdot0811.txt.gz'],\n 'soc-slashdot0922': ['soc-Slashdot0902.txt.gz'],\n 'wiki-vote': ['wiki-Vote.txt.gz'],\n }\n\n def __init__(self, root, name, transform=None, pre_transform=None,\n pre_filter=None):\n self.name = name.lower()\n assert self.name in self.available_datasets.keys()\n super(SNAPDataset, self).__init__(root, transform, pre_transform,\n pre_filter)\n self.data, self.slices = torch.load(self.processed_paths[0])\n\n @property\n def raw_dir(self):\n return osp.join(self.root, self.name, 'raw')\n\n @property\n def processed_dir(self):\n return osp.join(self.root, self.name, 'processed')\n\n @property\n def processed_file_names(self):\n return 'data.pt'\n\n def _download(self):\n if osp.isdir(self.raw_dir) and len(os.listdir(self.raw_dir)) > 0:\n return\n\n makedirs(self.raw_dir)\n self.download()\n\n def download(self):\n for name in self.available_datasets[self.name]:\n path = download_url('{}/{}'.format(self.url, name), self.raw_dir)\n print(path)\n if name.endswith('.tar.gz'):\n extract_tar(path, self.raw_dir)\n elif name.endswith('.gz'):\n extract_gz(path, self.raw_dir)\n os.unlink(path)\n\n def process(self):\n raw_dir = self.raw_dir\n filenames = os.listdir(self.raw_dir)\n if len(filenames) == 1 and osp.isdir(osp.join(raw_dir, filenames[0])):\n raw_dir = osp.join(raw_dir, filenames[0])\n\n raw_files = sorted([osp.join(raw_dir, f) for f in os.listdir(raw_dir)])\n\n if self.name[:4] == 'ego-':\n data_list = read_ego(raw_files, self.name[4:])\n elif self.name[:4] == 'soc-':\n data_list = read_soc(raw_files, self.name[:4])\n elif self.name[:5] == 'wiki-':\n data_list = read_wiki(raw_files, self.name[5:])\n else:\n raise NotImplementedError\n\n if len(data_list) > 1 and self.pre_filter is not None:\n data_list = [data for data in data_list if self.pre_filter(data)]\n\n if self.pre_transform is not None:\n data_list = [self.pre_transform(data) for data in data_list]\n\n torch.save(self.collate(data_list), self.processed_paths[0])\n\n def __repr__(self):\n return 'SNAP-{}({})'.format(self.name, len(self))\n", "import os.path as osp\n\nimport torch\nimport torch.nn.functional as F\nfrom torch_geometric.datasets import MNISTSuperpixels\nimport torch_geometric.transforms as T\nfrom torch_geometric.data import DataLoader\nfrom torch_geometric.utils import normalized_cut\nfrom torch_geometric.nn import (SplineConv, graclus, max_pool, max_pool_x,\n global_mean_pool)\n\npath = osp.join(osp.dirname(osp.realpath(__file__)), '..', 'data', 'MNIST')\ntransform = T.Cartesian(cat=False)\ntrain_dataset = MNISTSuperpixels(path, True, transform=transform)\ntest_dataset = MNISTSuperpixels(path, False, transform=transform)\ntrain_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)\ntest_loader = DataLoader(test_dataset, batch_size=64)\nd = train_dataset\n\n\ndef normalized_cut_2d(edge_index, pos):\n row, col = edge_index\n edge_attr = torch.norm(pos[row] - pos[col], p=2, dim=1)\n return normalized_cut(edge_index, edge_attr, num_nodes=pos.size(0))\n\n\nclass Net(torch.nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = SplineConv(d.num_features, 32, dim=2, kernel_size=5)\n self.conv2 = SplineConv(32, 64, dim=2, kernel_size=5)\n self.fc1 = torch.nn.Linear(64, 128)\n self.fc2 = torch.nn.Linear(128, d.num_classes)\n\n def forward(self, data):\n data.x = F.elu(self.conv1(data.x, data.edge_index, data.edge_attr))\n weight = normalized_cut_2d(data.edge_index, data.pos)\n cluster = graclus(data.edge_index, weight, data.x.size(0))\n data.edge_attr = None\n data = max_pool(cluster, data, transform=transform)\n\n data.x = F.elu(self.conv2(data.x, data.edge_index, data.edge_attr))\n weight = normalized_cut_2d(data.edge_index, data.pos)\n cluster = graclus(data.edge_index, weight, data.x.size(0))\n x, batch = max_pool_x(cluster, data.x, data.batch)\n\n x = global_mean_pool(x, batch)\n x = F.elu(self.fc1(x))\n x = F.dropout(x, training=self.training)\n return F.log_softmax(self.fc2(x), dim=1)\n\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nmodel = Net().to(device)\noptimizer = torch.optim.Adam(model.parameters(), lr=0.01)\n\n\ndef train(epoch):\n model.train()\n\n if epoch == 16:\n for param_group in optimizer.param_groups:\n param_group['lr'] = 0.001\n\n if epoch == 26:\n for param_group in optimizer.param_groups:\n param_group['lr'] = 0.0001\n\n for data in train_loader:\n data = data.to(device)\n optimizer.zero_grad()\n F.nll_loss(model(data), data.y).backward()\n optimizer.step()\n\n\ndef test():\n model.eval()\n correct = 0\n\n for data in test_loader:\n data = data.to(device)\n pred = model(data).max(1)[1]\n correct += pred.eq(data.y).sum().item()\n return correct / len(test_dataset)\n\n\nfor epoch in range(1, 31):\n train(epoch)\n test_acc = test()\n print('Epoch: {:02d}, Test: {:.4f}'.format(epoch, test_acc))\n" ]
[ [ "torch.cat", "torch.nn.functional.dropout", "torch.nn.Linear", "torch.nn.functional.leaky_relu", "torch.stack" ], [ "torch.tensor" ], [ "torch.randn", "torch.randint", "torch.rand" ], [ "pandas.read_csv", "torch.full", "torch.cat", "torch.load", "torch.from_numpy", "torch.tensor", "torch.arange", "torch.stack" ], [ "torch.nn.Linear", "torch.norm", "torch.cuda.is_available", "torch.nn.functional.dropout" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jameshgrn/sliderule-python
[ "47fad1465358956a876c9680dd55e535ab5bdcb7", "47fad1465358956a876c9680dd55e535ab5bdcb7" ]
[ "sliderule/ipysliderule.py", "sliderule/icesat2.py" ]
[ "# Copyright (c) 2021, University of Washington\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the University of Washington nor the names of its\n# contributors may be used to endorse or promote products derived from this\n# software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY OF WASHINGTON AND CONTRIBUTORS\n# “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY OF WASHINGTON OR\n# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nimport os\nimport sys\nimport copy\nimport datetime\nimport numpy as np\nfrom traitlets.utils.bunch import Bunch\nimport sliderule.io\n\n# imports with warnings if not present\ntry:\n import ipywidgets\nexcept ModuleNotFoundError as e:\n sys.stderr.write(\"Warning: missing packages, some functions will throw an exception if called. (%s)\\n\" % (str(e)))\ntry:\n import tkinter.filedialog\nexcept ModuleNotFoundError as e:\n sys.stderr.write(\"Warning: missing packages, some functions will throw an exception if called. (%s)\\n\" % (str(e)))\ntry:\n import IPython.display\nexcept ModuleNotFoundError as e:\n sys.stderr.write(\"Warning: missing packages, some functions will throw an exception if called. (%s)\\n\" % (str(e)))\n\n# imports that raise error if not present\ntry:\n import ipyleaflet\nexcept ModuleNotFoundError as e:\n sys.stderr.write(\"Error: missing required packages. (%s)\\n\" % (str(e)))\n raise\n\ntry:\n import xyzservices\nexcept ModuleNotFoundError as e:\n sys.stderr.write(\"Error: missing required packages. (%s)\\n\" % (str(e)))\n raise\n\nclass widgets:\n def __init__(self):\n # dropdown menu for setting asset\n self.asset = ipywidgets.Dropdown(\n options=['atlas-local', 'atlas-s3', 'nsidc-s3'],\n value='nsidc-s3',\n description='Asset:',\n disabled=False,\n )\n\n # dropdown menu for setting data release\n self.release = ipywidgets.Dropdown(\n options=['003', '004'],\n value='004',\n description='Release:',\n disabled=False,\n )\n\n # dropdown menu for setting surface type\n # 0-land, 1-ocean, 2-sea ice, 3-land ice, 4-inland water\n surface_type_options = [\n 'Land',\n 'Ocean',\n 'Sea ice',\n 'Land ice',\n 'Inland water'\n ]\n self.surface_type = ipywidgets.Dropdown(\n options=surface_type_options,\n value='Land',\n description='Surface Type:',\n disabled=False,\n )\n\n # slider for setting length of ATL06-SR segment in meters\n self.length = ipywidgets.IntSlider(\n value=40,\n min=5,\n max=200,\n step=5,\n description='Length:',\n disabled=False,\n continuous_update=False,\n orientation='horizontal',\n readout=True,\n readout_format='d'\n )\n\n # slider for setting step distance for successive segments in meters\n self.step = ipywidgets.IntSlider(\n value=20,\n min=5,\n max=200,\n step=5,\n description='Step:',\n disabled=False,\n continuous_update=False,\n orientation='horizontal',\n readout=True,\n readout_format='d'\n )\n\n # slider for setting confidence level for PE selection\n # eventually would be good to switch this to a IntRangeSlider with value=[0,4]\n self.confidence = ipywidgets.IntSlider(\n value=4,\n min=0,\n max=4,\n step=1,\n description='Confidence:',\n disabled=False,\n continuous_update=False,\n orientation='horizontal',\n readout=True,\n readout_format='d'\n )\n\n # selection for land surface classifications\n land_options = [\n 'atl08_noise',\n 'atl08_ground',\n 'atl08_canopy',\n 'atl08_top_of_canopy',\n 'atl08_unclassified'\n ]\n self.land_class = ipywidgets.SelectMultiple(\n options=land_options,\n description='Land Class:',\n disabled=False\n )\n\n # slider for setting maximum number of iterations\n # (not including initial least-squares-fit selection)\n self.iteration = ipywidgets.IntSlider(\n value=1,\n min=0,\n max=20,\n step=1,\n description='Iterations:',\n disabled=False,\n continuous_update=False,\n orientation='horizontal',\n readout=True,\n readout_format='d'\n )\n\n # slider for setting minimum along track spread\n self.spread = ipywidgets.FloatSlider(\n value=20,\n min=1,\n max=100,\n step=0.1,\n description='Spread:',\n disabled=False,\n continuous_update=False,\n orientation='horizontal',\n readout=True,\n readout_format='0.1f'\n )\n # slider for setting minimum photon event (PE) count\n self.count = ipywidgets.IntSlider(\n value=10,\n min=1,\n max=50,\n step=1,\n description='PE Count:',\n disabled=False,\n continuous_update=False,\n orientation='horizontal',\n readout=True,\n readout_format='d'\n )\n\n # slider for setting minimum height of PE window in meters\n self.window = ipywidgets.FloatSlider(\n value=3,\n min=0.5,\n max=10,\n step=0.1,\n description='Window:',\n disabled=False,\n continuous_update=False,\n orientation='horizontal',\n readout=True,\n readout_format='0.1f'\n )\n\n # slider for setting maximum robust dispersion in meters\n self.sigma = ipywidgets.FloatSlider(\n value=5,\n min=1,\n max=10,\n step=0.1,\n description='Sigma:',\n disabled=False,\n continuous_update=False,\n orientation='horizontal',\n readout=True,\n readout_format='0.1f'\n )\n\n # dropdown menu for setting map projection for polygons\n # Global: Web Mercator (EPSG:3857)\n # North: Alaska Polar Stereographic (EPSG:5936)\n # South: Polar Stereographic South (EPSG:3031)\n projection_list = ['Global','North','South']\n self.projection = ipywidgets.Dropdown(\n options=projection_list,\n value='Global',\n description='Projection:',\n disabled=False,\n )\n\n # button and label for output file selection\n self.file = copy.copy(self.filename)\n self.savebutton = ipywidgets.Button(\n description=\"Save As\"\n )\n self.savelabel = ipywidgets.Text(\n value=self.file,\n disabled=False\n )\n # connect fileselect button with action\n self.savebutton.on_click(self.saveas_file)\n self.savelabel.observe(self.set_savefile)\n # create hbox of file selection\n if os.environ.get(\"DISPLAY\"):\n self.filesaver = ipywidgets.HBox([\n self.savebutton,\n self.savelabel\n ])\n else:\n self.filesaver = copy.copy(self.savelabel)\n\n # button and label for input file selection\n self.loadbutton = ipywidgets.Button(\n description=\"File select\"\n )\n self.loadlabel = ipywidgets.Text(\n value='',\n disabled=False\n )\n # connect fileselect button with action\n self.loadbutton.on_click(self.select_file)\n self.loadlabel.observe(self.set_loadfile)\n # create hbox of file selection\n if os.environ.get(\"DISPLAY\"):\n self.fileloader = ipywidgets.HBox([\n self.loadbutton,\n self.loadlabel\n ])\n else:\n self.fileloader = copy.copy(self.loadlabel)\n\n def saveas_file(self, b):\n \"\"\"function for file save\n \"\"\"\n IPython.display.clear_output()\n root = tkinter.Tk()\n root.withdraw()\n root.call('wm', 'attributes', '.', '-topmost', True)\n filetypes = ((\"HDF5 file\", \"*.h5\"),\n (\"netCDF file\", \"*.nc\"),\n (\"All Files\", \"*.*\"))\n b.files = tkinter.filedialog.asksaveasfilename(\n initialfile=self.file,\n defaultextension='h5',\n filetypes=filetypes)\n self.savelabel.value = b.files\n self.file = b.files\n return self\n\n def set_savefile(self, sender):\n self.file = self.savelabel.value\n\n def select_file(self, b):\n \"\"\"function for file selection\n \"\"\"\n IPython.display.clear_output()\n root = tkinter.Tk()\n root.withdraw()\n root.call('wm', 'attributes', '.', '-topmost', True)\n filetypes = ((\"HDF5 file\", \"*.h5\"),\n (\"netCDF file\", \"*.nc\"),\n (\"All Files\", \"*.*\"))\n b.files = tkinter.filedialog.askopenfilename(\n defaultextension='h5',\n filetypes=filetypes,\n multiple=False)\n self.loadlabel.value = b.files\n self.file = b.files\n return self\n\n def set_loadfile(self, sender):\n self.file = self.loadlabel.value\n\n @property\n def filename(self):\n \"\"\"default input and output file string\n \"\"\"\n # get sliderule submission time\n now = datetime.datetime.now().strftime('%Y%m%d%H%M%S')\n args = (now, self.release.value)\n return \"ATL06-SR_{0}_{1}.h5\".format(*args)\n\n @property\n def format(self):\n \"\"\"return the file format from file string\n \"\"\"\n hdf = ('h5','hdf5','hdf')\n netcdf = ('nc','netcdf','nc3')\n if self.file.endswith(hdf):\n return 'hdf'\n elif self.file.endswith(netcdf):\n return 'netcdf'\n else:\n return ''\n\n# define projections for ipyleaflet tiles\nprojections = Bunch(\n # Alaska Polar Stereographic (WGS84)\n EPSG5936=dict(\n name='EPSG5936',\n custom=True,\n proj4def=\"\"\"+proj=stere +lat_0=90 +lat_ts=90 +lon_0=-150 +k=0.994\n +x_0=2000000 +y_0=2000000 +datum=WGS84 +units=m +no_defs\"\"\",\n origin=[-2.8567784109255e+07, 3.2567784109255e+07],\n resolutions=[\n 238810.813354,\n 119405.406677,\n 59702.7033384999,\n 29851.3516692501,\n 14925.675834625,\n 7462.83791731252,\n 3731.41895865639,\n 1865.70947932806,\n 932.854739664032,\n 466.427369832148,\n 233.213684916074,\n 116.60684245803701,\n 58.30342122888621,\n 29.151710614575396,\n 14.5758553072877,\n 7.28792765351156,\n 3.64396382688807,\n 1.82198191331174,\n 0.910990956788164,\n 0.45549547826179,\n 0.227747739130895,\n 0.113873869697739,\n 0.05693693484887,\n 0.028468467424435\n ],\n bounds=[\n [-2623285.8808999992907047,-2623285.8808999992907047],\n [6623285.8803000003099442,6623285.8803000003099442]\n ]\n )\n ,\n # Polar Stereographic South (WGS84)\n EPSG3031=dict(\n name='EPSG3031',\n custom=True,\n proj4def=\"\"\"+proj=stere +lat_0=-90 +lat_ts=-71 +lon_0=0 +k=1\n +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs\"\"\",\n origin=[-3.06361E7, 3.0636099999999993E7],\n resolutions=[\n 67733.46880027094,\n 33866.73440013547,\n 16933.367200067736,\n 8466.683600033868,\n 4233.341800016934,\n 2116.670900008467,\n 1058.3354500042335,\n 529.1677250021168,\n 264.5838625010584,\n ],\n bounds=[\n [-4524583.19363305,-4524449.487765655],\n [4524449.4877656475,4524583.193633042]\n ]\n )\n)\n\n# attributions for the different basemaps\nglims_attribution = \"\"\"\nImagery reproduced from GLIMS and NSIDC (2005, updated 2018):\nGlobal Land Ice Measurements from Space glacier database. (doi:10.7265/N5V98602)\n\"\"\"\nesri_attribution = \"\"\"\nTiles &copy; Esri &mdash; Esri, DeLorme, NAVTEQ, TomTom, Intermap, iPC,\nUSGS, FAO, NPS, NRCAN, GeoBase, Kadaster NL, Ordnance Survey, Esri Japan,\nMETI, Esri China (Hong Kong), and the GIS User Community\n\"\"\"\nnoaa_attribution = \"\"\"\nImagery provided by NOAA National Centers for Environmental Information (NCEI);\nInternational Bathymetric Chart of the Southern Ocean (IBCSO);\nGeneral Bathymetric Chart of the Oceans (GEBCO).\n\"\"\"\n\n# define background ipyleaflet tiles\nbasemaps = {\n \"Esri\": {\n \"ArcticOceanBase\": {\n \"name\": 'Esri.ArcticOceanBase',\n \"crs\": projections.EPSG5936,\n \"attribution\": esri_attribution,\n \"url\": 'http://server.arcgisonline.com/ArcGIS/rest/services/Polar/Arctic_Ocean_Base/MapServer/tile/{z}/{y}/{x}'\n },\n \"ArcticOceanReference\": {\n \"name\": 'Esri.ArcticOceanReference',\n \"crs\": projections.EPSG5936,\n \"attribution\": esri_attribution,\n \"url\": 'http://server.arcgisonline.com/ArcGIS/rest/services/Polar/Arctic_Ocean_Reference/MapServer/tile/{z}/{y}/{x}'\n },\n \"AntarcticBasemap\": {\n \"name\": 'Esri.AntarcticBasemap',\n \"crs\": projections.EPSG3031,\n \"attribution\":noaa_attribution,\n \"url\": 'https://tiles.arcgis.com/tiles/C8EMgrsFcRFL6LrL/arcgis/rest/services/Antarctic_Basemap/MapServer/tile/{z}/{y}/{x}'\n }\n }\n}\n\n# define background ipyleaflet WMS layers\nlayers = Bunch(\n GLIMS = Bunch(\n glaciers = ipyleaflet.WMSLayer(\n attribution=glims_attribution,\n layers='GLIMS_GLACIERS',\n format='image/png',\n url='https://www.glims.org/mapservice'\n )\n )\n)\n\n# load basemap providers from dict\n# https://github.com/geopandas/xyzservices/blob/main/xyzservices/lib.py\ndef _load_dict(data):\n providers = Bunch()\n for provider_name in data.keys():\n provider = data[provider_name]\n if \"url\" in provider.keys():\n providers[provider_name] = xyzservices.lib.TileProvider(provider)\n else:\n providers[provider_name] = Bunch(\n {i: xyzservices.lib.TileProvider(provider[i]) for i in provider.keys()}\n )\n return providers\n\n# draw ipyleaflet map\nclass leaflet:\n def __init__(self, projection, **kwargs):\n # set default keyword arguments\n kwargs.setdefault('zoom',False)\n kwargs.setdefault('scale',True)\n kwargs.setdefault('cursor',True)\n kwargs.setdefault('center',(39,-108))\n kwargs.setdefault('color','green')\n providers = _load_dict(basemaps)\n # create basemap in projection\n if (projection == 'Global'):\n self.map = ipyleaflet.Map(center=kwargs['center'],\n zoom=9, max_zoom=15,\n basemap=ipyleaflet.basemaps.Esri.WorldTopoMap)\n self.map.add_layer(layers.GLIMS.glaciers)\n elif (projection == 'North'):\n self.map = ipyleaflet.Map(center=(90,0),\n zoom=5, max_zoom=24,\n basemap=providers.Esri.ArcticOceanBase,\n crs=projections.EPSG5936)\n self.map.add_layer(providers.Esri.ArcticOceanReference)\n elif (projection == 'South'):\n self.map = ipyleaflet.Map(center=(-90,0),\n zoom=2, max_zoom=9,\n basemap=providers.Esri.AntarcticBasemap,\n crs=projections.EPSG3031)\n # add control for zoom\n if kwargs['zoom']:\n zoom_slider = ipywidgets.IntSlider(description='Zoom level:',\n min=self.map.min_zoom, max=self.map.max_zoom, value=self.map.zoom)\n ipywidgets.jslink((zoom_slider, 'value'), (self.map, 'zoom'))\n zoom_control = ipyleaflet.WidgetControl(widget=zoom_slider,\n position='topright')\n self.map.add_control(zoom_control)\n # add scale bar\n if kwargs['scale']:\n scale_control = ipyleaflet.ScaleControl(position='topright')\n self.map.add_control(scale_control)\n # add label for cursor position\n if kwargs['cursor']:\n self.cursor = ipywidgets.Label()\n label_control = ipyleaflet.WidgetControl(widget=self.cursor,\n position='bottomright')\n self.map.add_control(label_control)\n # keep track of cursor position\n self.map.on_interaction(self.handle_interaction)\n # add control for drawing polygons or bounding boxes\n draw_control = ipyleaflet.DrawControl(polyline={},circlemarker={},\n edit=False)\n shapeOptions = {'color':kwargs['color'],'fill_color':kwargs['color']}\n draw_control.rectangle = dict(shapeOptions=shapeOptions,\n metric=['km','m'])\n draw_control.polygon = dict(shapeOptions=shapeOptions,\n allowIntersection=False,showArea=True,metric=['km','m'])\n # create regions\n self.regions = []\n draw_control.on_draw(self.handle_draw)\n self.map.add_control(draw_control)\n\n # handle cursor movements for label\n def handle_interaction(self, **kwargs):\n if (kwargs.get('type') == 'mousemove'):\n lat,lon = kwargs.get('coordinates')\n lon = sliderule.io.wrap_longitudes(lon)\n self.cursor.value = u\"\"\"Latitude: {d[0]:8.4f}\\u00B0,\n Longitude: {d[1]:8.4f}\\u00B0\"\"\".format(d=[lat,lon])\n\n # keep track of rectangles and polygons drawn on map\n def handle_draw(self, obj, action, geo_json):\n lon,lat = np.transpose(geo_json['geometry']['coordinates'])\n lon = sliderule.io.wrap_longitudes(lon)\n cx,cy = sliderule.io.centroid(lon,lat)\n wind = sliderule.io.winding(lon,lat)\n # set winding to counter-clockwise\n if (wind > 0):\n lon = lon[::-1]\n lat = lat[::-1]\n # create sliderule region from list\n region = sliderule.io.to_region(lon,lat)\n # append coordinates to list\n if (action == 'created'):\n self.regions.append(region)\n elif (action == 'deleted'):\n self.regions.remove(region)\n return self\n\n", "# Copyright (c) 2021, University of Washington\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the University of Washington nor the names of its\n# contributors may be used to endorse or promote products derived from this\n# software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY OF WASHINGTON AND CONTRIBUTORS\n# “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY OF WASHINGTON OR\n# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nimport itertools\nimport copy\nimport json\nimport ssl\nimport urllib.request\nimport datetime\nimport logging\nimport concurrent.futures\nimport warnings\nimport numpy\nimport geopandas\nfrom shapely.geometry.multipolygon import MultiPolygon\nimport sliderule\nfrom sliderule import version\n\n###############################################################################\n# GLOBALS\n###############################################################################\n\n# configuration\nSERVER_SCALE_FACTOR = 3\n\n# create logger\nlogger = logging.getLogger(__name__)\n\n# default asset\nDEFAULT_ASSET=\"nsidc-s3\"\n\n# default maximum number of resources to process in one request\nDEFAULT_MAX_REQUESTED_RESOURCES = 300\nmax_requested_resources = DEFAULT_MAX_REQUESTED_RESOURCES\n\n# icesat2 parameters\nCNF_POSSIBLE_TEP = -2\nCNF_NOT_CONSIDERED = -1\nCNF_BACKGROUND = 0\nCNF_WITHIN_10M = 1\nCNF_SURFACE_LOW = 2\nCNF_SURFACE_MEDIUM = 3\nCNF_SURFACE_HIGH = 4\nSRT_LAND = 0\nSRT_OCEAN = 1\nSRT_SEA_ICE = 2\nSRT_LAND_ICE = 3\nSRT_INLAND_WATER = 4\nALL_ROWS = -1\nMAX_COORDS_IN_POLYGON = 16384\nGT1L = 10\nGT1R = 20\nGT2L = 30\nGT2R = 40\nGT3L = 50\nGT3R = 60\nSTRONG_SPOTS = (1, 3, 5)\nWEAK_SPOTS = (2, 4, 6)\nLEFT_PAIR = 0\nRIGHT_PAIR = 1\n\n# gps-based epoch for delta times #\nATLAS_SDP_EPOCH = datetime.datetime(2018, 1, 1)\n\n###############################################################################\n# NSIDC UTILITIES\n###############################################################################\n# The functions below have been adapted from the NSIDC download script and\n# carry the following notice:\n#\n# Copyright (c) 2020 Regents of the University of Colorado\n# Permission is hereby granted, free of charge, to any person obtaining\n# a copy of this software and associated documentation files (the \"Software\"),\n# to deal in the Software without restriction, including without limitation\n# the rights to use, copy, modify, merge, publish, distribute, sublicense,\n# and/or sell copies of the Software, and to permit persons to whom the\n# Software is furnished to do so, subject to the following conditions:\n# The above copyright notice and this permission notice shall be included\n# in all copies or substantial portions of the Software.\n\nCMR_URL = 'https://cmr.earthdata.nasa.gov'\nCMR_PAGE_SIZE = 2000\nCMR_FILE_URL = ('{0}/search/granules.json?provider=NSIDC_ECS'\n '&sort_key[]=start_date&sort_key[]=producer_granule_id'\n '&scroll=true&page_size={1}'.format(CMR_URL, CMR_PAGE_SIZE))\n\ndef __build_version_query_params(version):\n desired_pad_length = 3\n if len(version) > desired_pad_length:\n raise RuntimeError('Version string too long: \"{0}\"'.format(version))\n\n version = str(int(version)) # Strip off any leading zeros\n query_params = ''\n\n while len(version) <= desired_pad_length:\n padded_version = version.zfill(desired_pad_length)\n query_params += '&version={0}'.format(padded_version)\n desired_pad_length -= 1\n return query_params\n\ndef __cmr_filter_urls(search_results):\n \"\"\"Select only the desired data files from CMR response.\"\"\"\n if 'feed' not in search_results or 'entry' not in search_results['feed']:\n return []\n\n entries = [e['links']\n for e in search_results['feed']['entry']\n if 'links' in e]\n # Flatten \"entries\" to a simple list of links\n links = list(itertools.chain(*entries))\n\n urls = []\n unique_filenames = set()\n for link in links:\n if 'href' not in link:\n # Exclude links with nothing to download\n continue\n if 'inherited' in link and link['inherited'] is True:\n # Why are we excluding these links?\n continue\n if 'rel' in link and 'data#' not in link['rel']:\n # Exclude links which are not classified by CMR as \"data\" or \"metadata\"\n continue\n\n if 'title' in link and 'opendap' in link['title'].lower():\n # Exclude OPeNDAP links--they are responsible for many duplicates\n # This is a hack; when the metadata is updated to properly identify\n # non-datapool links, we should be able to do this in a non-hack way\n continue\n\n filename = link['href'].split('/')[-1]\n if filename in unique_filenames:\n # Exclude links with duplicate filenames (they would overwrite)\n continue\n\n unique_filenames.add(filename)\n\n if \".h5\" in link['href'][-3:]:\n resource = link['href'].split(\"/\")[-1]\n urls.append(resource)\n\n return urls\n\ndef __cmr_granule_polygons(search_results):\n \"\"\"Get the polygons for CMR returned granules\"\"\"\n if 'feed' not in search_results or 'entry' not in search_results['feed']:\n return []\n granule_polygons = []\n # for each CMR entry\n for e in search_results['feed']['entry']:\n # for each polygon\n for polys in e['polygons']:\n coords = [float(i) for i in polys[0].split()]\n region = [{'lon':x,'lat':y} for y,x in zip(coords[::2],coords[1::2])]\n granule_polygons.append(region)\n # return granule polygons in sliderule region format\n return granule_polygons\n\ndef __cmr_search(short_name, version, time_start, time_end, **kwargs):\n \"\"\"Perform a scrolling CMR query for files matching input criteria.\"\"\"\n kwargs.setdefault('polygon',None)\n kwargs.setdefault('return_polygons',False)\n # build params\n params = '&short_name={0}'.format(short_name)\n params += __build_version_query_params(version)\n params += '&temporal[]={0},{1}'.format(time_start, time_end)\n if kwargs['polygon']:\n params += '&polygon={0}'.format(kwargs['polygon'])\n cmr_query_url = CMR_FILE_URL + params\n logger.debug('cmr request={0}\\n'.format(cmr_query_url))\n\n cmr_scroll_id = None\n ctx = ssl.create_default_context()\n ctx.check_hostname = False\n ctx.verify_mode = ssl.CERT_NONE\n\n urls = []\n polys = [] if kwargs['return_polygons'] else None\n while True:\n req = urllib.request.Request(cmr_query_url)\n if cmr_scroll_id:\n req.add_header('cmr-scroll-id', cmr_scroll_id)\n response = urllib.request.urlopen(req, context=ctx)\n if not cmr_scroll_id:\n # Python 2 and 3 have different case for the http headers\n headers = {k.lower(): v for k, v in dict(response.info()).items()}\n cmr_scroll_id = headers['cmr-scroll-id']\n hits = int(headers['cmr-hits'])\n search_page = response.read()\n search_page = json.loads(search_page.decode('utf-8'))\n url_scroll_results = __cmr_filter_urls(search_page)\n if not url_scroll_results:\n break\n urls += url_scroll_results\n # append granule polygons\n if kwargs['return_polygons']:\n polygon_results = __cmr_granule_polygons(search_page)\n polys.extend(polygon_results)\n\n if kwargs['return_polygons']:\n return (urls,polys)\n else:\n return urls\n\n###############################################################################\n# SLIDERULE UTILITIES\n###############################################################################\n\n#\n# __get_values\n#\ndef __get_values(data, dtype, size):\n \"\"\"\n data: tuple of bytes\n dtype: element of codedtype\n size: bytes in data\n \"\"\"\n\n raw = bytes(data)\n datatype = sliderule.basictypes[sliderule.codedtype2str[dtype]][\"nptype\"]\n num_elements = int(size / numpy.dtype(datatype).itemsize)\n slicesize = num_elements * numpy.dtype(datatype).itemsize # truncates partial bytes\n values = numpy.frombuffer(raw[:slicesize], dtype=datatype, count=num_elements)\n\n return values\n\n#\n# __query_resources\n#\ndef __query_resources(parm, version, return_polygons=False):\n\n # Check Parameters are Valid\n if (\"poly\" not in parm) and (\"t0\" not in parm) and (\"t1\" not in parm):\n logger.error(\"Must supply some bounding parameters with request (poly, t0, t1)\")\n return []\n\n # submission arguments for cmr\n kwargs = {}\n kwargs['version'] = version\n kwargs['return_polygons'] = return_polygons\n # Pull Out Polygon #\n if \"poly\" in parm:\n kwargs['polygon'] = parm[\"poly\"]\n\n # Pull Out Time Period #\n if \"t0\" in parm:\n kwargs['time_start'] = parm[\"t0\"]\n if \"t1\" in parm:\n kwargs['time_end'] = parm[\"t1\"]\n\n # Make CMR Request #\n if return_polygons:\n resources,polygons = cmr(**kwargs)\n else:\n resources = cmr(**kwargs)\n # check that resources are under limit\n if(len(resources) > max_requested_resources):\n logger.warning(\"Exceeded maximum requested resources: %d (current max is %d)\", len(resources), max_requested_resources)\n logger.warning(\"Consider using icesat2.set_max_resources to set a higher limit\")\n resources = []\n else:\n logger.info(\"Identified %d resources to process\", len(resources))\n\n # Return Resources #\n if return_polygons:\n return (resources,polygons)\n else:\n return resources\n\n#\n# __query_servers\n#\ndef __query_servers(max_workers):\n\n # Update Available Servers #\n num_servers = sliderule.update_available_servers()\n if max_workers <= 0:\n max_workers = num_servers * SERVER_SCALE_FACTOR\n\n # Check if Servers are Available #\n if max_workers <= 0:\n logger.error(\"There are no servers available to fulfill this request\")\n return 0\n else:\n logger.info(\"Allocating %d workers across %d processing nodes\", max_workers, num_servers)\n\n # Return Number of Workers #\n return max_workers\n\n#\n# __emptyframe\n#\ndef __emptyframe(**kwargs):\n # set default keyword arguments\n kwargs['crs'] = \"EPSG:4326\"\n return geopandas.GeoDataFrame(geometry=geopandas.points_from_xy([], []), crs=kwargs['crs'])\n\n#\n# __todataframe\n#\ndef __todataframe(columns, delta_time_key=\"delta_time\", lon_key=\"lon\", lat_key=\"lat\", **kwargs):\n # set default keyword arguments\n kwargs['index_key'] = \"time\"\n kwargs['crs'] = \"EPSG:4326\"\n\n # Check Empty Columns\n if len(columns) <= 0:\n return __emptyframe(**kwargs)\n\n # Generate Time Column\n delta_time = (columns[delta_time_key]*1e9).astype('timedelta64[ns]')\n atlas_sdp_epoch = numpy.datetime64(ATLAS_SDP_EPOCH)\n columns['time'] = geopandas.pd.to_datetime(atlas_sdp_epoch + delta_time)\n\n # Generate Geometry Column\n geometry = geopandas.points_from_xy(columns[lon_key], columns[lat_key])\n del columns[lon_key]\n del columns[lat_key]\n\n # Create Pandas DataFrame object\n df = geopandas.pd.DataFrame(columns)\n\n # Build GeoDataFrame (default geometry is crs=\"EPSG:4326\")\n gdf = geopandas.GeoDataFrame(df, geometry=geometry, crs=kwargs['crs'])\n\n # Set index (default is Timestamp), can add `verify_integrity=True` to check for duplicates\n # Can do this during DataFrame creation, but this allows input argument for desired column\n gdf.set_index(kwargs['index_key'], inplace=True)\n\n # Sort values for reproducible output despite async processing\n gdf.sort_index(inplace=True)\n\n # Return GeoDataFrame\n return gdf\n\n\n#\n# __atl06\n#\ndef __atl06 (parm, resource, asset, track):\n\n # Build ATL06 Request\n rqst = {\n \"atl03-asset\" : asset,\n \"resource\": resource,\n \"track\": track,\n \"parms\": parm\n }\n\n # Execute ATL06 Algorithm\n rsps = sliderule.source(\"atl06\", rqst, stream=True)\n\n # Flatten Responses\n columns = {}\n if len(rsps) <= 0:\n logger.debug(\"no response returned for %s\", resource)\n elif (rsps[0]['__rectype'] != 'atl06rec' and rsps[0]['__rectype'] != 'atl06rec-compact'):\n logger.debug(\"invalid response returned for %s: %s\", resource, rsps[0]['__rectype'])\n else:\n # Determine Record Type\n if rsps[0]['__rectype'] == 'atl06rec':\n rectype = 'atl06rec.elevation'\n else:\n rectype = 'atl06rec-compact.elevation'\n # Count Rows\n num_rows = 0\n for rsp in rsps:\n num_rows += len(rsp[\"elevation\"])\n # Build Columns\n for field in rsps[0][\"elevation\"][0].keys():\n fielddef = sliderule.get_definition(rectype, field)\n if len(fielddef) > 0:\n columns[field] = numpy.empty(num_rows, fielddef[\"nptype\"])\n # Populate Columns\n elev_cnt = 0\n for rsp in rsps:\n for elevation in rsp[\"elevation\"]:\n for field in elevation.keys():\n if field in columns:\n columns[field][elev_cnt] = elevation[field]\n elev_cnt += 1\n\n # Return Response\n return __todataframe(columns, \"delta_time\", \"lon\", \"lat\"), resource\n\n\n#\n# __atl03s\n#\ndef __atl03s (parm, resource, asset, track):\n\n # Build ATL06 Request\n rqst = {\n \"atl03-asset\" : asset,\n \"resource\": resource,\n \"track\": track,\n \"parms\": parm\n }\n\n # Execute ATL06 Algorithm\n rsps = sliderule.source(\"atl03s\", rqst, stream=True)\n\n # Flatten Responses\n columns = {}\n if len(rsps) <= 0:\n logger.debug(\"no response returned for %s\", resource)\n elif rsps[0]['__rectype'] != 'atl03rec':\n logger.debug(\"invalid response returned for %s: %s\", resource, rsps[0]['__rectype'])\n else:\n # Count Rows\n num_rows = 0\n for rsp in rsps:\n num_rows += len(rsp[\"data\"])\n # Build Columns\n for rsp in rsps:\n if len(rsp[\"data\"]) > 0:\n # Allocate Columns\n for field in rsp.keys():\n fielddef = sliderule.get_definition(\"atl03rec\", field)\n if len(fielddef) > 0:\n columns[field] = numpy.empty(num_rows, fielddef[\"nptype\"])\n for field in rsp[\"data\"][0].keys():\n fielddef = sliderule.get_definition(\"atl03rec.photons\", field)\n if len(fielddef) > 0:\n columns[field] = numpy.empty(num_rows, fielddef[\"nptype\"])\n break\n # Populate Columns\n ph_cnt = 0\n for rsp in rsps:\n ph_index = 0\n left_cnt = rsp[\"count\"][0]\n for photon in rsp[\"data\"]:\n for field in rsp.keys():\n if field in columns:\n if field == \"count\":\n if ph_index < left_cnt:\n columns[field][ph_cnt] = 0\n else:\n columns[field][ph_cnt] = 1\n elif type(rsp[field]) is tuple:\n columns[field][ph_cnt] = rsp[field][0]\n else:\n columns[field][ph_cnt] = rsp[field]\n for field in photon.keys():\n if field in columns:\n columns[field][ph_cnt] = photon[field]\n ph_cnt += 1\n ph_index += 1\n # Rename Count Column to Pair Column\n columns[\"pair\"] = columns.pop(\"count\")\n\n # Return Response\n return __todataframe(columns, \"delta_time\", \"longitude\", \"latitude\"), resource\n\n#\n# __parallelize\n#\ndef __parallelize(max_workers, block, function, parm, resources, *args):\n\n # Check Max Workers\n if max_workers <= 0:\n return {}\n\n # For Blocking Calls\n if block:\n\n # Make Parallel Processing Requests\n results = []\n with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:\n futures = [executor.submit(function, parm, resource, *args) for resource in resources]\n\n # Wait for Results\n result_cnt = 0\n for future in concurrent.futures.as_completed(futures):\n result_cnt += 1\n result, resource = future.result()\n if len(result) > 0:\n results.append(result)\n logger.info(\"%d points returned for %s (%d out of %d resources)\", len(result), resource, result_cnt, len(resources))\n\n # Return Results\n if len(results) > 0:\n results.sort(key=lambda result: result.iloc[0]['delta_time'])\n return geopandas.pd.concat(results)\n else:\n return __emptyframe()\n\n # For Non-Blocking Calls\n else:\n\n # Create Thread Pool\n executor = concurrent.futures.ThreadPoolExecutor(max_workers=max_workers)\n\n # Return List of Futures for Parallel Processing Request\n return [executor.submit(function, parm, resource, *args) for resource in resources]\n\n###############################################################################\n# APIs\n###############################################################################\n\n#\n# INIT\n#\ndef init (url, verbose=False, max_resources=DEFAULT_MAX_REQUESTED_RESOURCES, max_errors=3, loglevel=logging.CRITICAL):\n if verbose:\n loglevel = logging.INFO\n logging.basicConfig(level=loglevel)\n sliderule.set_url(url)\n sliderule.set_verbose(verbose)\n sliderule.set_max_errors(max_errors)\n set_max_resources(max_resources)\n\n#\n# SET MAX RESOURCES\n#\ndef set_max_resources (max_resources):\n global max_requested_resources\n max_requested_resources = max_resources\n\n#\n# COMMON METADATA REPOSITORY\n#\ndef cmr(**kwargs):\n \"\"\"\n polygon: list of longitude,latitude in counter-clockwise order with first and last point matching;\n - e.g. [ {\"lon\": -115.43, \"lat\": 37.40},\n {\"lon\": -109.55, \"lat\": 37.58},\n {\"lon\": -109.38, \"lat\": 43.28},\n {\"lon\": -115.29, \"lat\": 43.05},\n {\"lon\": -115.43, \"lat\": 37.40} ]\n time_*: UTC time (i.e. \"zulu\" or \"gmt\");\n expressed in the following format: <year>-<month>-<day>T<hour>:<minute>:<second>Z\n \"\"\"\n # set default keyword arguments\n kwargs.setdefault('polygon',None)\n # set default start time to start of ICESat-2 mission\n kwargs.setdefault('time_start','2018-10-13T00:00:00Z')\n # set default stop time to current time\n kwargs.setdefault('time_end',datetime.datetime.utcnow().strftime(\"%Y-%m-%dT%H:%M:%SZ\"))\n # set default version and product short name\n kwargs.setdefault('version','004')\n kwargs.setdefault('short_name','ATL03')\n # return polygons for each requested granule\n kwargs.setdefault('return_polygons',False)\n # copy polygon\n polygon = copy.copy(kwargs['polygon'])\n\n url_list = []\n poly_list = []\n\n # issue CMR request\n for tolerance in [0.0001, 0.001, 0.01, 0.1, 1.0, None]:\n\n # convert polygon list into string\n polystr = None\n if polygon:\n flatpoly = []\n for p in polygon:\n flatpoly.append(p[\"lon\"])\n flatpoly.append(p[\"lat\"])\n polystr = str(flatpoly)[1:-1]\n polystr = polystr.replace(\" \", \"\") # remove all spaces as this will be embedded in a url\n\n # call into NSIDC routines to make CMR request\n try:\n if kwargs['return_polygons']:\n url_list,poly_list = __cmr_search(kwargs['short_name'],\n kwargs['version'],\n kwargs['time_start'],\n kwargs['time_end'],\n polygon=polystr,\n return_polygons=True)\n else:\n url_list = __cmr_search(kwargs['short_name'],\n kwargs['version'],\n kwargs['time_start'],\n kwargs['time_end'],\n polygon=polystr)\n break # exit loop because cmr search was successful\n except urllib.error.HTTPError as e:\n logger.error('HTTP Request Error: {}'.format(e.reason))\n except RuntimeError as e:\n logger.error(\"Runtime Error:\", e)\n\n # simplify polygon\n if polygon and tolerance:\n raw_multi_polygon = [[(tuple([(c['lon'], c['lat']) for c in polygon]), [])]]\n shape = MultiPolygon(*raw_multi_polygon)\n buffered_shape = shape.buffer(tolerance)\n simplified_shape = buffered_shape.simplify(tolerance)\n simplified_coords = list(simplified_shape.exterior.coords)\n logger.warning('Using simplified polygon (for CMR request only!), {} points using tolerance of {}'.format(len(simplified_coords), tolerance))\n region = []\n for coord in simplified_coords:\n point = {\"lon\": coord[0], \"lat\": coord[1]}\n region.insert(0,point)\n polygon = region\n else:\n break # exit here because nothing can be done\n\n if kwargs['return_polygons']:\n return (url_list,poly_list)\n else:\n return url_list\n\n#\n# ATL06\n#\ndef atl06 (parm, resource, asset=DEFAULT_ASSET, track=0):\n\n try:\n return __atl06(parm, resource, asset, track)[0]\n except RuntimeError as e:\n logger.critical(e)\n return __emptyframe()\n\n#\n# PARALLEL ATL06\n#\ndef atl06p(parm, asset=DEFAULT_ASSET, track=0, max_workers=0, version='004', block=True, resources=None):\n\n try:\n if resources == None:\n resources = __query_resources(parm, version)\n max_workers = __query_servers(max_workers)\n return __parallelize(max_workers, block, __atl06, parm, resources, asset, track)\n except RuntimeError as e:\n logger.critical(e)\n return __emptyframe()\n\n\n#\n# Subsetted ATL03\n#\ndef atl03s (parm, resource, asset=DEFAULT_ASSET, track=0):\n\n try:\n return __atl03s(parm, resource, asset, track)[0]\n except RuntimeError as e:\n logger.critical(e)\n return __emptyframe()\n\n#\n# PARALLEL SUBSETTED ATL03\n#\ndef atl03sp(parm, asset=DEFAULT_ASSET, track=0, max_workers=0, version='004', block=True, resources=None):\n\n try:\n if resources == None:\n resources = __query_resources(parm, version)\n max_workers = __query_servers(max_workers)\n return __parallelize(max_workers, block, __atl03s, parm, resources, asset, track)\n except RuntimeError as e:\n logger.critical(e)\n return __emptyframe()\n\n#\n# H5\n#\ndef h5 (dataset, resource, asset=DEFAULT_ASSET, datatype=sliderule.datatypes[\"DYNAMIC\"], col=0, startrow=0, numrows=ALL_ROWS):\n\n # Baseline Request\n rqst = {\n \"asset\" : asset,\n \"resource\": resource,\n \"dataset\": dataset,\n \"datatype\": datatype,\n \"col\": col,\n \"startrow\": startrow,\n \"numrows\": numrows,\n \"id\": 0\n }\n\n # Read H5 File\n try:\n rsps = sliderule.source(\"h5\", rqst, stream=True)\n except RuntimeError as e:\n logger.critical(e)\n return numpy.empty(0)\n\n # Check if Data Returned\n if len(rsps) <= 0:\n return numpy.empty(0)\n\n # Build Record Data\n rsps_datatype = rsps[0][\"datatype\"]\n rsps_data = bytearray()\n rsps_size = 0\n for d in rsps:\n rsps_data += bytearray(d[\"data\"])\n rsps_size += d[\"size\"]\n\n # Get Values\n values = __get_values(rsps_data, rsps_datatype, rsps_size)\n\n # Return Response\n return values\n\n#\n# H5P\n#\ndef h5p (datasets, resource, asset=DEFAULT_ASSET):\n\n # Baseline Request\n rqst = {\n \"asset\" : asset,\n \"resource\": resource,\n \"datasets\": datasets,\n }\n\n # Read H5 File\n try:\n rsps = sliderule.source(\"h5p\", rqst, stream=True)\n except RuntimeError as e:\n logger.critical(e)\n rsps = []\n\n # Build Record Data\n results = {}\n for result in rsps:\n results[result[\"dataset\"]] = __get_values(result[\"data\"], result[\"datatype\"], result[\"size\"])\n\n # Return Results\n return results\n\n#\n# TO REGION\n#\ndef toregion (filename, tolerance=0.0):\n\n # initialize regions #\n regions = []\n\n # native format #\n if filename.find(\".json\") > 1:\n with open(filename) as regionfile:\n region = json.load(regionfile)[\"region\"]\n regions.append(region)\n\n # geojson or shapefile format #\n elif (filename.find(\".geojson\") > 1) or (filename.find(\".shp\") > 1):\n polygons = geopandas.read_file(filename)\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n polygons = polygons.buffer(tolerance)\n polygons = polygons.simplify(tolerance)\n for polygon in polygons.geometry:\n region = []\n for coord in list(polygon.exterior.coords):\n point = {\"lon\": coord[0], \"lat\": coord[1]}\n region.append(point)\n if len(region) > 0 and len(region) <= MAX_COORDS_IN_POLYGON:\n regions.append(region)\n else:\n logger.warning(\"dropping polygon with unsupported length: %d (max is %d)\", len(region), MAX_COORDS_IN_POLYGON)\n\n # determine winding of polygons #\n for r in range(len(regions)):\n region = regions[r]\n # (x2 - x1) * (y2 + y1)\n wind = sum([(region[i+1][\"lon\"] - region[i][\"lon\"]) * (region[i+1][\"lat\"] + region[i][\"lat\"]) for i in range(len(region) - 1)])\n if wind > 0:\n # reverse direction (make counter-clockwise) #\n ccw_region = []\n for i in range(len(region), 0, -1):\n ccw_region.append(region[i - 1])\n # replace region with counter-clockwise version #\n regions[r] = ccw_region\n\n # return region #\n return regions\n\n#\n# GET VERSION\n#\ndef get_version ():\n\n rsps = sliderule.source(\"version\", {})\n rsps[\"client\"] = {\"version\": version.full_version}\n return rsps\n" ]
[ [ "numpy.transpose" ], [ "numpy.frombuffer", "numpy.dtype", "numpy.empty", "numpy.datetime64" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
brosscle/CT-TIQUA
[ "d56104cd60ffa962afae9506b6bc9d4afc0d0de9" ]
[ "CT_TIQUA/blast_ct/blast_ct/models/deepmedic.py" ]
[ "import torch.nn as nn\nimport torch\nfrom ..models.base import BiomedicalBlock, DownSample, UpSample, PreActBlock, crop_center\n\nSCALE_FACTORS = ((5, 5, 5), (3, 3, 3), (1, 1, 1))\nFEATURE_MAPS = (30, 30, 40, 40, 40, 40, 50, 50)\nFULLY_CONNECTED = (250, 250)\nDROPOUT = (.0, .5, .5)\n\n\nclass Path(BiomedicalBlock):\n def __init__(self, scale_factor, input_channels, feature_maps):\n super().__init__()\n self.layers = list()\n self.scale_factor = tuple(scale_factor)\n\n self.layers.append(DownSample(self.scale_factor))\n for i, feature_map in enumerate(feature_maps):\n in_channels = feature_maps[i - 1] if i > 0 else input_channels\n self.layers.append(PreActBlock(in_channels, feature_map))\n self.layers.append(UpSample(self.scale_factor))\n\n self.path = nn.Sequential(*self.layers)\n\n def forward(self, x, output_size):\n input_size = self.calculate_input_size(output_size)\n out = crop_center(x, input_size)\n out = self.path(out)\n out = crop_center(out, output_size)\n return out\n\n\nclass DeepMedic(BiomedicalBlock):\n def __init__(self,\n input_channels,\n num_classes,\n scale_factors=SCALE_FACTORS,\n feature_maps=FEATURE_MAPS,\n fully_connected=FULLY_CONNECTED,\n dropout=DROPOUT):\n\n super().__init__()\n # assert all scale factors are equal or less than the next one\n assert all([all(l[i] >= l[i + 1] for i in range(len(l) - 1)) for l in [i for i in list(zip(*scale_factors))]])\n self.scale_factors = tuple(scale_factors)\n self.feature_maps = tuple(feature_maps)\n self.output_size = None\n\n self.paths = []\n for i, scale_factor in enumerate(scale_factors):\n path = Path(scale_factor, input_channels, feature_maps)\n self.paths.append(path)\n self.add_module('path' + str(scale_factor) + str(i), path)\n\n assert len(fully_connected) + 1 == len(dropout)\n fms = []\n channels = (feature_maps[-1] * len(self.paths),) + tuple(fully_connected) + (num_classes, )\n for i in range(len(channels[:-1])):\n fms.append(PreActBlock(channels[i], channels[i + 1], kernel_size=(1, 1, 1), dropout_prob=dropout[i]))\n\n self.fully_connected = nn.Sequential(*fms)\n\n # to calculate sizes\n self.layers = self.paths[0].layers\n\n def forward(self, image, **kwargs):\n input_size = tuple(image.shape[2:])\n output_size = self.get_output_size(input_size)\n\n activations = []\n for i, path in enumerate(self.paths):\n out = path(image, output_size)\n activations.append(out)\n\n out = torch.cat(tuple(activations), dim=1)\n out = self.fully_connected(out)\n return out, {}\n" ]
[ [ "torch.nn.Sequential" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
SemyonSinchenko/QOpt
[ "0b273a887f765a16cac706510681c1a3f5901e72" ]
[ "notebooks/ResultViewer.py" ]
[ "#%%\nimport os\nimport pylab\nimport numpy as np\n\n#%%\n\nNUM_EDGES = 2474\nEXACT_SOLUTION = 1430\nsamples = np.loadtxt(os.path.join(\"results\", \"FFNN\", \"100vertexGraph\",\"stateAdvanced_1000steps.txt\"))\n\nloaded_matrix = np.loadtxt(\"data/g05_100.0\", skiprows=0, dtype=np.int32)\nedgelist = [[loaded_matrix[i, 0] - 1, loaded_matrix[i, 1] - 1]\n for i in range(loaded_matrix.shape[0])]\n\n#%%\n\ndef score(state, edges):\n r = -NUM_EDGES\n for e in edges:\n r += state[e[0]] * state[e[1]]\n\n return -r / 2\n\nresults = []\nfor i in range(samples.shape[0]):\n results.append(score(samples[i, :], edgelist))\n\nresults = np.array(results)\n\n#%%\n\npylab.figure(figsize=(8, 4))\npylab.plot(np.arange(results.shape[0]), results, \".-\", label=\"Results\")\npylab.plot(np.arange(results.shape[0]),\n np.ones(results.shape[0]) * EXACT_SOLUTION, \"--\", label=\"Exact\")\npylab.xlabel(\"Sample number\")\npylab.ylabel(\"CutSize\")\npylab.legend()\npylab.grid()\npylab.savefig(os.path.join(\"results\", \"FFNN\", \"100vertexGraph\", \"SamplesResults.png\"))\n\n#%%" ]
[ [ "numpy.arange", "numpy.array", "numpy.loadtxt", "numpy.ones" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ericleehy/PeekingDuck
[ "8cf1be842235fa60bac13bc466cac09747a780ea", "8cf1be842235fa60bac13bc466cac09747a780ea" ]
[ "peekingduck/pipeline/nodes/dabble/keypoints_to_3d_loc.py", "peekingduck/pipeline/nodes/model/yolov4_face/yolo_face_files/detector.py" ]
[ "# Copyright 2022 AI Singapore\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\n\"\"\"\nEstimates the 3D coordinates of a person given 2D pose coordinates.\n\"\"\"\n\nfrom typing import Any, Dict\n\nimport numpy as np\n\nfrom peekingduck.pipeline.nodes.abstract_node import AbstractNode\n\nNOSE = 0\nLEFT_SHOULDER = 5\nRIGHT_SHOULDER = 6\nLEFT_PELVIS = 11\nRIGHT_PELVIS = 12\nTORSO_KEYPOINTS = [NOSE, LEFT_SHOULDER, RIGHT_SHOULDER, LEFT_PELVIS, RIGHT_PELVIS]\n\n\nclass Node(AbstractNode):\n \"\"\"Uses pose keypoint information of the torso to estimate 3D location.\n\n Inputs:\n |keypoints_data|\n\n Outputs:\n |obj_3D_locs_data|\n\n Configs:\n focal_length (:obj:`float`): **default = 1.14**. |br|\n Approximate focal length of webcam used, in metres. Example on\n measuring focal length can be found `here <https://learnopencv.com\n /approximate-focal-length-for-webcams-and-cell-phone-cameras/>`_.\n torso_factor (:obj:`float`): **default = 0.9**. |br|\n A factor used to estimate real-world distance from pixels, based on\n average human torso length in metres. The value varies across\n different camera set-ups, and calibration may be required.\n \"\"\"\n\n def __init__(self, config: Dict[str, Any] = None, **kwargs: Any) -> None:\n super().__init__(config, node_path=__name__, **kwargs)\n\n def run(self, inputs: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"Converts pose keypoints into 3D locations.\"\"\"\n locations = []\n\n for keypoints in inputs[\"keypoints\"]:\n torso_keypoints = self._get_torso_keypoints(keypoints)\n if self._enough_torso_keypoints(torso_keypoints):\n bbox = self._get_bbox(torso_keypoints)\n else:\n bbox = self._get_bbox(keypoints)\n\n point = self._get_3d_point_from_bbox(\n bbox, self.focal_length, self.torso_factor\n )\n locations.append(point)\n\n outputs = {\"obj_3D_locs\": locations}\n\n return outputs\n\n @staticmethod\n def _get_torso_keypoints(keypoints: np.ndarray) -> np.ndarray:\n \"\"\"Filter keypoints to get only selected keypoints for torso\"\"\"\n torso_keypoints = keypoints[TORSO_KEYPOINTS, :] # type: ignore\n # ignore keypoints that are '-1.' as below confidence score and are masked\n torso_keypoints = np.reshape(torso_keypoints[torso_keypoints != -1.0], (-1, 2))\n\n return torso_keypoints\n\n @staticmethod\n def _enough_torso_keypoints(torso_keypoints: np.ndarray) -> bool:\n \"\"\"Returns False if not enough keypoints to represent torso\"\"\"\n if torso_keypoints.shape[0] >= 2:\n return True\n return False\n\n @staticmethod\n def _get_bbox(keypoints: np.ndarray) -> np.ndarray:\n \"\"\"Get coordinates of a bbox around keypoints\"\"\"\n top_left_x, top_left_y = keypoints.min(axis=0)\n btm_right_x, btm_right_y = keypoints.max(axis=0)\n\n return np.array([top_left_x, top_left_y, btm_right_x, btm_right_y])\n\n @staticmethod\n def _get_3d_point_from_bbox(\n bbox: np.ndarray, focal_length: float, torso_factor: float\n ) -> np.ndarray:\n \"\"\"Get the 3d coordinates of the centre of a bounding box\"\"\"\n # Subtraction is to make the camera the origin of the coordinate system\n center_2d = ((bbox[0:2] + bbox[2:4]) * 0.5) - np.array([0.5, 0.5])\n torso_height = bbox[3] - bbox[1]\n\n z_coord = (focal_length * torso_factor) / torso_height\n x_coord = (center_2d[0] * torso_factor) / torso_height\n y_coord = (center_2d[1] * torso_factor) / torso_height\n\n return np.array([x_coord, y_coord, z_coord])\n", "# Copyright 2022 AI Singapore\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\n\"\"\"Object detection class using YOLOv4 model to detect human faces.\"\"\"\n\nimport logging\nfrom pathlib import Path\nfrom typing import Callable, Dict, List, Tuple\n\nimport cv2\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.python.saved_model import tag_constants\n\n\nclass Detector: # pylint: disable=too-few-public-methods,too-many-instance-attributes\n \"\"\"Object detection class using yolo model to find human faces.\"\"\"\n\n def __init__( # pylint: disable=too-many-arguments\n self,\n model_dir: Path,\n class_names: List[str],\n detect_ids: List[int],\n model_type: str,\n model_file: Dict[str, str],\n max_output_size_per_class: int,\n max_total_size: int,\n input_size: int,\n iou_threshold: float,\n score_threshold: float,\n ) -> None:\n self.logger = logging.getLogger(__name__)\n\n self.class_names = class_names\n self.model_type = model_type\n self.model_path = model_dir / model_file[self.model_type]\n\n self.max_output_size_per_class = max_output_size_per_class\n self.max_total_size = max_total_size\n self.input_size = (input_size, input_size)\n self.iou_threshold = iou_threshold\n self.score_threshold = score_threshold\n\n self.detect_ids = detect_ids\n self.yolo = self._create_yolo_model()\n\n def predict_object_bbox_from_image(\n self, image: np.ndarray\n ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:\n \"\"\"Predicts face bboxes, labels and scores.\n\n Args:\n image (np.ndarray): Input image.\n\n Returns:\n bboxes (np.ndarray): Detected bboxes\n labels (np.ndarray): Class labels for each detected bbox.\n scores (np.ndarray): Confidence scores for each detected bbox.\n \"\"\"\n image = self._preprocess(image)\n\n pred = self.yolo(tf.constant(image))\n pred = next(iter(pred.values()))\n\n bboxes, scores, classes = self._postprocess(pred[:, :, :4], pred[:, :, 4:])\n labels = np.array([self.class_names[int(i)] for i in classes])\n\n return bboxes, labels, scores\n\n def _create_yolo_model(self) -> Callable:\n self.logger.info(\n \"Yolo model loaded with following configs:\\n\\t\"\n f\"Model type: {self.model_type},\\n\\t\"\n f\"Input resolution: {self.input_size},\\n\\t\"\n f\"IDs being detected: {self.detect_ids},\\n\\t\"\n f\"Max detections per class: {self.max_output_size_per_class},\\n\\t\"\n f\"Max total detections: {self.max_total_size},\\n\\t\"\n f\"IOU threshold: {self.iou_threshold},\\n\\t\"\n f\"Score threshold: {self.score_threshold}\"\n )\n\n return self._load_yolo_weights()\n\n def _load_yolo_weights(self) -> Callable:\n self.model = tf.saved_model.load(\n str(self.model_path), tags=[tag_constants.SERVING]\n )\n return self.model.signatures[\"serving_default\"]\n\n def _postprocess(\n self,\n pred_boxes: tf.Tensor,\n pred_scores: tf.Tensor,\n ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:\n bboxes, scores, classes, valid_dets = tf.image.combined_non_max_suppression(\n tf.reshape(pred_boxes, (tf.shape(pred_boxes)[0], -1, 1, 4)),\n tf.reshape(\n pred_scores, (tf.shape(pred_scores)[0], -1, tf.shape(pred_scores)[-1])\n ),\n self.max_output_size_per_class,\n self.max_total_size,\n self.iou_threshold,\n self.score_threshold,\n )\n num_valid = valid_dets[0]\n\n classes = classes.numpy()[0]\n classes = classes[:num_valid]\n # only identify objects we are interested in\n mask = np.isin(classes, self.detect_ids)\n\n scores = scores.numpy()[0]\n scores = scores[:num_valid]\n scores = scores[mask]\n\n bboxes = bboxes.numpy()[0]\n bboxes = bboxes[:num_valid]\n bboxes = bboxes[mask]\n\n # swapping x and y axes\n bboxes[:, [0, 1]] = bboxes[:, [1, 0]]\n bboxes[:, [2, 3]] = bboxes[:, [3, 2]]\n\n return bboxes, scores, classes\n\n def _preprocess(self, image: np.ndarray) -> np.ndarray:\n image = cv2.resize(image, self.input_size)\n image = np.asarray([image]).astype(np.float32) / 255.0\n\n return image\n" ]
[ [ "numpy.reshape", "numpy.array" ], [ "numpy.asarray", "tensorflow.constant", "numpy.isin", "tensorflow.shape" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.5", "1.7", "0.12", "1.0", "1.2" ] } ]
hanjoo0211/deep-learning-from-scratch
[ "dae38d476cc5156d6f111179b60c30124b47e59c" ]
[ "predictNumber.py" ]
[ "import numpy as np\nfrom PIL import Image\nfrom ch08.deep_convnet import DeepConvNet\nfrom common.functions import softmax\n\n\ndef predictNumber(img):\n img = img.convert(\"L\") # 흑백처리\n img = np.array(img) / 255 # normalize 해줘야함..\n img = img * -1 + 1 # 흑백반전도 해줘야함.. 검은배경에 흰 글자로 나오도록!\n imgArray = img.reshape(1,28,28,1).transpose(0,3,1,2)\n\n network = DeepConvNet()\n network.load_params(\"./ch08/deep_convnet_params.pkl\")\n\n y = network.predict(imgArray)\n y = softmax(y)\n n = np.argmax(y, axis=1)\n \n return y, n" ]
[ [ "numpy.array", "numpy.argmax" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ErikEkstedt/Project
[ "c56b852440041775caaa242b7e86779666c0f1c3", "c56b852440041775caaa242b7e86779666c0f1c3", "c56b852440041775caaa242b7e86779666c0f1c3" ]
[ "gesture/environments/social.py", "gesture/PepperGestures/eval_pepper.py", "gesture/environments/SubProcEnv.py" ]
[ "'''\nsocial movement environment (Roboschool for poses)\n'''\nfrom roboschool.scene_abstract import Scene, SingleRobotEmptyScene\nimport os\nimport numpy as np\nimport gym\nfrom OpenGL import GLE # fix for opengl issues on desktop / nvidia\nimport cv2\n\n\nPATH_TO_CUSTOM_XML = os.path.join(os.path.dirname(__file__), \"xml_files\")\n\n\nclass MyGymEnv(gym.Env):\n ''' OpenAI zGym wrapper\n\n functions:\n\n self._reset : resets the environment (robot)\n self._step : steps, returns s, st, o, ot, reward, done, info\n self._seed : sets seed. self.np_random\n self._render : r\n '''\n\n metadata = {\n 'render.modes': ['human', 'machine', 'target', 'all', 'all_rgb_array'],\n 'video.frames_per_second': 60\n }\n def __init__(self, action_dim=2, state_dim=7, obs_dim=(600, 400, 3)):\n self.scene = None\n self.VIDEO_W = obs_dim[0]\n self.VIDEO_H = obs_dim[1]\n\n self.Human_VIDEO_W = 600 # for human render\n self.Human_VIDEO_H = 400\n\n high = np.ones([action_dim])\n self.action_space = gym.spaces.Box(-high, high)\n\n high = np.inf*np.ones([state_dim])\n self.state_space = gym.spaces.Box(-high, high)\n\n self.observation_space = gym.spaces.Box(low=0, high=255, shape=obs_dim)\n\n self.state_target = None\n self.obs_target = None\n if self.scene is None:\n ''' First reset '''\n self.scene = self.initialize_scene()\n # If load_xml_get_robot() is moved outside this condition after\n # env.reset all states become nan\n self.load_xml_get_robot()\n\n def _seed(self, seed=None):\n self.np_random, seed = gym.utils.seeding.np_random(seed)\n return [seed]\n\n def _reset(self):\n self.get_joint_dicts()\n self.robot_specific_reset()\n for r in self.mjcf:\n r.query_position()\n\n # Important Resets\n self.done = False\n self.frame = 0\n self.reward = 0\n self.camera = self.scene.cpp_world.new_camera_free_float(self.VIDEO_W,\n self.VIDEO_H,\n \"video_camera\")\n self.human_camera = self.scene.cpp_world.new_camera_free_float(self.Human_VIDEO_W,\n self.Human_VIDEO_H,\n \"human_video_camera\")\n\n if self.state_target is None:\n print('Random Targets. Use \"env.set_target(state, obs)\"')\n self.state_target = np.random.randint(4)\n self.obs_target = np.random.randint(0, 255, (100,100,3)).astype('uint8')\n\n state_robot = self.calc_state() # pos and speed\n self.potential = self.calc_potential() # potential to target\n obs = self.get_rgb() #observation\n\n return (state_robot, self.state_target, obs, self.obs_target)\n\n def _step(self, a):\n self.apply_action(a) # Singleplayer (originally in a condition)\n self.scene.global_step()\n self.frame += 1\n\n state = self.calc_state() # also calculates self.joints_at_limit\n reward = self.calc_reward(a)\n done = self.stop_condition() # max frame reached?\n self.done = done\n self.reward = reward\n\n obs = self.get_rgb()\n return (state, self.state_target, obs, self.obs_target, reward, bool(done), {})\n\n def _render(self, mode, close):\n def cv2_render(rgb, title='frame'):\n cv2.imshow(title, cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR))\n if cv2.waitKey(1) & 0xFF == ord('q'):\n print('Stop')\n return\n if close:\n return\n if mode=='human':\n self.human_camera_adjust()\n rgb, _, _, _, _ = self.human_camera.render(False, False, False) # render_depth, render_labeling, print_timing)\n rendered_rgb = np.fromstring(rgb, dtype=np.uint8).reshape( (self.Human_VIDEO_H, self.Human_VIDEO_W,3) )\n cv2_render(rendered_rgb, 'human')\n return [True, False, False]\n elif mode==\"machine\":\n self.camera_adjust()\n rgb, _, _, _, _ = self.camera.render(False, False, False) # render_depth, render_labeling, print_timing)\n rendered_rgb = np.fromstring(rgb, dtype=np.uint8).reshape( (self.VIDEO_H,self.VIDEO_W,3) )\n cv2_render(rendered_rgb, 'machine')\n return [False, True, False]\n elif mode==\"target\":\n cv2_render(self.obs_target, 'target')\n return [False, False, True]\n elif mode=='all':\n self._render('human', False)\n self._render('machine', False)\n self._render('target', False)\n return [True, True, True]\n elif mode==\"all_rgb_array\":\n self.camera_adjust()\n rgb, _, _, _, _ = self.camera.render(False, False, False) # render_depth, render_labeling, print_timing)\n machine = np.fromstring(rgb, dtype=np.uint8).reshape( (self.VIDEO_H,self.VIDEO_W,3) )\n\n self.human_camera_adjust()\n rgb, _, _, _, _ = self.human_camera.render(False, False, False) # render_depth, render_labeling, print_timing)\n human = np.fromstring(rgb, dtype=np.uint8).reshape( (self.Human_VIDEO_H, self.Human_VIDEO_W,3) )\n return human, machine, self.obs_target\n else:\n assert(0)\n\n\nclass Base(MyGymEnv):\n def __init__(self, XML_PATH=PATH_TO_CUSTOM_XML,\n robot_name='robot',\n model_xml='NOT/A/FILE.xml',\n ac=2, st=6,\n args=None):\n self.XML_PATH = XML_PATH\n self.model_xml = model_xml\n self.robot_name = robot_name\n if args is None:\n ''' Defaults '''\n self.MAX_TIME = 300\n self.potential_constant = 100\n self.electricity_cost = -2.0 # cost for using motors -- this parameter should be carefully tuned against reward for making progress, other values less improtant\n self.stall_torque_cost = -0.1 # cost for running electric current through a motor even at zero rotational speed, small\n self.joints_at_limit_cost = -0.2 # discourage stuck joints\n\n self.reward_constant1 = 1\n self.reward_constant2 = 1\n\n # Scene\n self.gravity = 9.81\n self.timestep = 0.0165/4\n self.frame_skip = 1\n\n # Robot\n self.power = 0.5\n MyGymEnv.__init__(self, action_dim=ac, state_dim=st)\n else:\n self.MAX_TIME=args.MAX_TIME\n\n # Reward penalties/values\n self.potential_constant = args.potential_constant\n self.electricity_cost = args.electricity_cost\n self.stall_torque_cost = args.stall_torque_cost\n self.joints_at_limit_cost = args.joints_at_limit_cost\n self.MAX_TIME = args.MAX_TIME\n self.reward_constant1 = args.r1\n self.reward_constant2 = args.r2\n\n # Scene\n self.gravity = args.gravity\n self.timestep = 0.0165/4\n self.frame_skip = 1\n\n # Robot\n self.power = args.power # 0.5\n MyGymEnv.__init__(self,\n action_dim=ac,\n state_dim=st,\n obs_dim=(args.video_w, args.video_h, args.video_c))\n\n def initialize_scene(self):\n return Scene(self.gravity, self.timestep, self.frame_skip)\n\n def apply_action(self, a):\n assert( np.isfinite(a).all() )\n for i, m, power in zip(range(len(self.motors)), self.motors, self.motor_power):\n m.set_motor_torque( 0.05*float(power*self.power*np.clip(a[i], -1, +1)) )\n\n def stop_condition(self):\n max_time = False\n if self.frame>=self.MAX_TIME:\n max_time = True\n return max_time\n\n def load_xml_get_robot(self, verbose=False):\n self.mjcf = self.scene.cpp_world.load_mjcf(\n os.path.join(os.path.dirname(__file__),\n \"xml_files/\",\n self.model_xml))\n self.ordered_joints = []\n self.jdict = {}\n self.parts = {}\n self.frame = 0\n self.done = 0\n self.reward = 0\n for r in self.mjcf:\n if verbose:\n print('Load XML Model')\n print('Path:', os.path.join(self.XML_PATH, self.model_xml))\n print(\"ROBOT '%s'\" % r.root_part.name)\n # store important parts\n if r.root_part.name==self.robot_name:\n self.cpp_robot = r\n self.robot_body = r.root_part\n\n for part in r.parts:\n if verbose: print(\"\\tPART '%s'\" % part.name)\n self.parts[part.name] = part\n if part.name==self.robot_name:\n self.cpp_robot = r\n self.robot_body = part\n\n for j in r.joints:\n if verbose:\n print(\"\\tALL JOINTS '%s' limits = %+0.2f..%+0.2f \\\n effort=%0.3f speed=%0.3f\" % ((j.name,) + j.limits()))\n j.power_coef = 100.0\n self.ordered_joints.append(j)\n self.jdict[j.name] = j\n\n def get_joint_dicts(self, verbose=False):\n ''' This function separates all parts/joints by containing `robot` or `target`.'''\n self.robot_joints, self.robot_parts = self.get_joints_parts_by_name('robot')\n self.target_joints, self.target_parts = self.get_joints_parts_by_name('target') # used only in SocialReacher_targets\n if verbose:\n print('{}\\n'.format(self.robot_joints))\n print('{}\\n'.format(self.robot_parts))\n print('{}\\n'.format(self.target_joints))\n assert(self.cpp_robot)\n\n def get_joints_parts_by_name(self, name):\n joints, parts = {}, {}\n for jname, joint in self.jdict.items():\n if name in jname:\n joints[jname] = joint\n for jname, part in self.parts.items():\n if name in jname:\n parts[jname] = part\n return joints, parts\n\n\nclass SocialReacher(Base):\n def __init__(self, args=None):\n Base.__init__(self, XML_PATH=PATH_TO_CUSTOM_XML,\n robot_name='robot_arm',\n model_xml='SocialPlane.xml',\n ac=2, st=6, args=args)\n print('I am', self.model_xml)\n\n def set_target(self, targets):\n ''' targets should be a\n list [numpy.ndarray, numpy.ndarray]\n\n state.shape (N,)\n obs.shape (W,H,C)\n '''\n self.state_target = targets[0]\n self.obs_target = targets[1]\n assert type(targets[0]) is np.ndarray, 'state target must be numpy'\n assert type(targets[1]) is np.ndarray, 'obs target must be numpy'\n\n def robot_specific_reset(self):\n self.motor_names = [\"robot_shoulder_joint_z\", \"robot_elbow_joint\"]\n self.motor_power = [100, 100]\n self.motors = [self.jdict[n] for n in self.motor_names]\n\n self.robot_reset()\n self.calc_robot_keypoints()\n\n def robot_reset(self):\n ''' self.np_random for correct seed. '''\n for j in self.robot_joints.values():\n j.reset_current_position(self.np_random.uniform(low=-0.01, high=0.01 ), 0)\n j.set_motor_torque(0)\n\n def calc_robot_keypoints(self):\n ''' gets hand position, target position and the vector in bewteen'''\n elbow_position = np.array(self.parts['robot_elbow'].pose().xyz())[:2]\n hand_position = np.array(self.parts['robot_hand'].pose().xyz())[:2]\n self.robot_key_points = np.concatenate((elbow_position, hand_position))\n\n def calc_reward(self, a):\n ''' Difference potential as reward '''\n potential_old = self.potential\n self.potential = self.calc_potential()\n r = self.reward_constant1 * float(self.potential - potential_old)\n return r\n\n def calc_potential(self):\n self.diff_key_points = self.state_target - self.robot_key_points\n p = -self.potential_constant*np.linalg.norm(self.diff_key_points)\n return np.array(p)\n\n def calc_state(self):\n j = np.array([j.current_relative_position()\n for j in self.robot_joints.values()],\n dtype=np.float32).flatten()\n self.joints_at_limit = np.count_nonzero(np.abs(j[0::2]) > 0.99)\n self.joint_speeds = j[1::2]\n self.calc_robot_keypoints() # calcs target_position, important_pos, to_target_vec\n return np.concatenate((self.robot_key_points, self.joint_speeds))\n\n def get_rgb(self):\n self.camera_adjust()\n rgb, _, _, _, _ = self.camera.render(False, False, False) # render_depth, render_labeling, print_timing)\n rendered_rgb = np.fromstring(rgb, dtype=np.uint8).reshape( (self.VIDEO_H,self.VIDEO_W,3) )\n return rendered_rgb\n\n def camera_adjust(self):\n ''' Vision from straight above '''\n self.camera.move_and_look_at( 0, 0, 1, 0, 0, 0.4)\n\n def human_camera_adjust(self):\n ''' Vision from straight above '''\n self.human_camera.move_and_look_at( 0, 0, 1, 0, 0, 0.4)\n\n\nclass SocialHumanoid(Base):\n def __init__(self, args=None):\n Base.__init__(self, XML_PATH=PATH_TO_CUSTOM_XML,\n robot_name='robot',\n model_xml='SocialHumanoid.xml',\n ac=6, st=18, args=args)\n print('I am', self.model_xml)\n\n def set_target(self, targets):\n ''' targets should be a\n list [numpy.ndarray, numpy.ndarray]\n\n state.shape (N,)\n obs.shape (W,H,C)\n '''\n self.state_target = targets[0]\n self.obs_target = targets[1]\n assert type(targets[0]) is np.ndarray, 'state target must be numpy'\n assert type(targets[1]) is np.ndarray, 'obs target must be numpy'\n\n def robot_specific_reset(self):\n self.motor_names = [\"robot_right_shoulder1\",\n \"robot_right_shoulder2\",\n \"robot_right_elbow\",\n \"robot_left_shoulder1\",\n \"robot_left_shoulder2\",\n \"robot_left_elbow\"]\n self.motor_power = [2000] * len(self.motor_names)\n self.motors = [self.jdict[n] for n in self.motor_names]\n\n self.robot_reset()\n self.calc_robot_keypoints()\n\n def robot_reset(self):\n ''' self.np_random for correct seed. '''\n for j in self.robot_joints.values():\n j.reset_current_position(self.np_random.uniform(low=-1.1, high=1.1 ), 0)\n j.set_motor_torque(0)\n\n def calc_robot_keypoints(self):\n ''' gets hand position, target position and the vector in bewteen'''\n left_elbow_position = np.array(self.parts['robot_left_elbow'].pose().xyz())\n left_hand_position = np.array(self.parts['robot_left_hand'].pose().xyz())\n right_elbow_position = np.array(self.parts['robot_right_elbow'].pose().xyz())\n right_hand_position = np.array(self.parts['robot_right_hand'].pose().xyz())\n self.robot_key_points = np.concatenate((left_elbow_position,\n left_hand_position,\n right_elbow_position,\n right_hand_position ))\n\n def calc_reward(self, a):\n ''' Difference potential as reward '''\n potential_old = self.potential\n self.potential = self.calc_potential()\n r = self.reward_constant1 * float(self.potential - potential_old)\n joints_at_limit_cost = float(self.joints_at_limit_cost * self.joints_at_limit)\n return r + joints_at_limit_cost\n\n def calc_potential(self):\n self.diff_key_points = self.state_target - self.robot_key_points\n p = -self.potential_constant*np.linalg.norm(self.diff_key_points)\n return np.array(p)\n\n def calc_state(self):\n j = np.array([j.current_relative_position()\n for j in self.robot_joints.values()],\n dtype=np.float32).flatten()\n self.joints_at_limit = np.count_nonzero(np.abs(j[0::2]) > 0.99)\n self.joint_speeds = j[1::2]\n self.calc_robot_keypoints() # important_pos\n return np.concatenate((self.robot_key_points, self.joint_speeds))\n\n def get_rgb(self):\n self.camera_adjust()\n rgb, _, _, _, _ = self.camera.render(False, False, False) # render_depth, render_labeling, print_timing)\n rendered_rgb = np.fromstring(rgb, dtype=np.uint8).reshape( (self.VIDEO_H,self.VIDEO_W,3) )\n return rendered_rgb\n\n def camera_adjust(self):\n ''' camera used as observation for agent default: (40,40,3)'''\n self.camera.move_and_look_at(1, 0, 0, 0, 0, 0)\n\n def human_camera_adjust(self):\n ''' Camera used for regular rendering. Default: (400, 600, 3)'''\n self.human_camera.move_and_look_at(1, 0, 0, 0, 0, 0)\n\n\n#####-------------------------\n# Nothing done on this... needed for rendering reward functions again.\nclass SocialReacherTargets(Base):\n def __init__(self, args=None):\n Base.__init__(self, XML_PATH=PATH_TO_CUSTOM_XML,\n robot_name='robot_arm',\n model_xml='SocialPlane.xml',\n ac=2, st=6, args=args)\n print('I am', self.model_xml)\n\n def set_target(self, targets):\n ''' targets should be a\n list [numpy.ndarray, numpy.ndarray]\n\n state.shape (N,)\n obs.shape (W,H,C)\n '''\n self.state_target = targets[0]\n self.obs_target = targets[1]\n assert type(targets[0]) is np.ndarray, 'state target must be numpy'\n assert type(targets[1]) is np.ndarray, 'obs target must be numpy'\n\n for j in self.target_joints.values():\n j.reset_current_position(self.np_random.uniform(low=-0.01, high=0.01 ), 0)\n j.set_motor_torque(0)\n\n def robot_specific_reset(self):\n self.motor_names = [\"robot_shoulder_joint_z\", \"robot_elbow_joint\"]\n self.motor_power = [100, 100]\n self.motors = [self.jdict[n] for n in self.motor_names]\n\n self.robot_reset()\n self.calc_robot_keypoints()\n\n def robot_reset(self):\n ''' self.np_random for correct seed. '''\n for j in self.robot_joints.values():\n j.reset_current_position(self.np_random.uniform(low=-0.01, high=0.01 ), 0)\n j.set_motor_torque(0)\n\n def calc_robot_keypoints(self):\n ''' gets hand position, target position and the vector in bewteen'''\n elbow_position = np.array(self.parts['robot_elbow'].pose().xyz())[:2]\n hand_position = np.array(self.parts['robot_hand'].pose().xyz())[:2]\n self.robot_key_points = np.concatenate((elbow_position, hand_position))\n\n def calc_reward(self, a):\n ''' Difference potential as reward '''\n potential_old = self.potential\n self.potential = self.calc_potential()\n r = self.reward_constant1 * float(self.potential - potential_old)\n return r\n\n def calc_potential(self):\n self.diff_key_points = self.state_target - self.robot_key_points\n p = -self.potential_constant*np.linalg.norm(self.diff_key_points)\n return np.array(p)\n\n def calc_state(self):\n j = np.array([j.current_relative_position()\n for j in self.robot_joints.values()],\n dtype=np.float32).flatten()\n self.joints_at_limit = np.count_nonzero(np.abs(j[0::2]) > 0.99)\n self.joint_speeds = j[1::2]\n self.calc_robot_keypoints() # calcs target_position, important_pos, to_target_vec\n return np.concatenate((self.robot_key_points, self.joint_speeds))\n\n def get_rgb(self):\n self.camera_adjust()\n rgb, _, _, _, _ = self.camera.render(False, False, False) # render_depth, render_labeling, print_timing)\n rendered_rgb = np.fromstring(rgb, dtype=np.uint8).reshape( (self.VIDEO_H,self.VIDEO_W,3) )\n return rendered_rgb\n\n def camera_adjust(self):\n ''' Vision from straight above '''\n self.camera.move_and_look_at( 0, 0, 1, 0, 0, 0.4)\n\n def human_camera_adjust(self):\n ''' Vision from straight above '''\n self.human_camera.move_and_look_at( 0, 0, 1, 0, 0, 0.4)\n\n#####-------------------------\ndef Social_multiple(Env, args):\n from gesture.environments.SubProcEnv import SubprocVecEnv_Social as SubprocVecEnv\n def multiple_envs(Env, args, rank):\n def _thunk():\n env = Env(args)\n env.seed(args.seed+rank*100)\n return env\n return _thunk\n return SubprocVecEnv([multiple_envs(Env, args, i) for i in range(args.num_proc)])\n\n\n# test functions\ndef test_social(Env, args):\n from gesture.environments.utils import random_run\n from gesture.environments.utils import random_run_with_changing_targets\n from gesture.agent.memory import Targets\n from gesture.utils.utils import load_dict\n\n # === Targets ===\n print('\\nLoading targets from:')\n print('path:\\t', args.test_target_path)\n datadict = load_dict(args.test_target_path)\n targets = Targets(args.num_proc, datadict)\n targets.remove_speed(args.njoints)\n st, ot = targets()\n\n env = Env(args)\n env.seed(args.seed)\n\n print(env)\n print('action space:', env.action_space)\n print('state space:', env.state_space)\n print('target state space:', st.shape)\n print('obs space:', env.observation_space)\n # random_run(env, render=args.render, verbose=args.verbose)\n random_run_with_changing_targets(env, targets, args)\n\n\ndef test_social_parallel(Env, args):\n from gesture.environments.utils import random_run_with_changing_targets_parallel\n from gesture.environments.utils import random_run_parallel\n from gesture.utils.utils import load_dict\n from gesture.agent.memory import Targets\n from torch import load\n\n print('path:\\t', args.test_target_path)\n datadict = load_dict(args.test_target_path)\n targets = Targets(args.num_proc, datadict)\n targets.remove_speed(args.njoints)\n st, ot = targets()[0]\n\n env = Social_multiple(Env, args)\n print(env)\n print('action space:', env.action_space)\n print('state space:', env.state_space)\n print('target state space:', st.shape)\n print('obs space:', env.observation_space)\n # random_run_parallel(env, args)\n random_run_with_changing_targets_parallel(env, targets, args)\n\n\nif __name__ == '__main__':\n from gesture.utils.arguments import get_args\n from gesture.environments.utils import env_from_args\n args = get_args()\n Env = env_from_args(args)\n\n if args.num_proc > 1:\n test_social_parallel(Env, args)\n else:\n test_social(Env, args)\n", "''' Pepper '''\nimport __future__\nimport os\nimport numpy as np\nimport datetime\nimport qi\nimport motion\nimport matplotlib.pyplot as plt\n\nfrom arguments import get_args\nfrom Pepper import Pepper_v0\nfrom train import explorationPepper as exploration\nfrom train import trainPepper as train\nfrom memory import Results, Current\nfrom storage import RolloutStoragePepper\nfrom model import MLPPolicy, VanillaCNN\n\nimport torch\nimport torch.optim as optim\nimport torch.nn as nn\n\nclass PoseDefiner(object):\n def __init__(self, thresh=0.1, done_duration=50, max_time=300, target=None):\n self.thresh = thresh\n self.done_duration = done_duration\n self.max_time = max_time\n self.target = target\n\n self.counter = 0\n self.time = 0\n self.poses_achieved = 0\n self.total_poses = 1\n\n def reset(self, target):\n self.counter = 0\n self.time = 0\n self.target = target\n self.total_poses += 1\n\n def update(self, state):\n self.time += 1\n change_target = False\n dist = np.linalg.norm(state[:len(self.target)] - self.target)\n if dist < self.thresh:\n # Pose reached!\n self.counter += 1\n if self.counter >= self.done_duration:\n # Pose achieved!\n self.poses_achieved += 1\n change_target = True\n else:\n self.counter = 0\n if self.time > self.max_time:\n change_target = True\n return dist, change_target\n\n def distance(self, state):\n return np.linalg.norm(state[:len(self.target)] - self.target)\n\n def print_result(self):\n print('\\nPoses reached/possible: {}/{}'.format(self.poses_achieved, self.total_poses))\n\n\ndef evaluate(env, pi, args, plot=False):\n if args.cuda:\n current.cuda()\n pi.cuda()\n\n name=\"Pepper\"\n if args.record:\n import skvideo.io\n vidname = name+'.mp4'\n writer = skvideo.io.FFmpegWriter(os.path.join(args.log_dir,vidname))\n\n # Initialize targets and reset env\n state, real_state_target, obs = env.reset()\n\n posedefiner = PoseDefiner(target=real_state_target, max_time=args.update_target)\n d = posedefiner.distance(state)\n X = [0]; Y = [d]\n\n ep_rew, total_reward = 0, 0\n for j in range(args.MAX_TIME):\n\n current.update(state, real_state_target, obs, obs)\n s ,st, o, _ = current()\n value, action = pi.act(s, st, o, o)\n\n if args.render:\n env.render('human')\n env.render('target')\n\n if args.record:\n record(env, writer)\n\n # Observe reward and next state\n\n cpu_actions = action.data.cpu().numpy()\n state, real_state_target, obs, reward, done = env.step(cpu_actions)\n total_reward += reward\n ep_rew += reward\n\n d, pose_done = posedefiner.update(state)\n Y.append(d)\n X.append(j)\n if plot:\n plt.plot(X,Y,'-b', X, [0.1]*len(X), '-r')\n plt.pause(1e-4)\n\n if pose_done:\n print('episode reward:', ep_rew)\n print('state: ', env.state)\n print('target: ', env.target)\n ep_rew = 0\n if args.random:\n env.set_random_target()\n state, real_state_target, obs = env.reset()\n posedefiner.reset(real_state_target)\n\n print('Total Reward: ', total_reward)\n if args.record:\n writer.close()\n\n posedefiner.print_result()\n plt.plot(X,Y,'-b', X, [0.1]*len(X), '-r')\n # plt.show()\n\n name += str(posedefiner.poses_achieved) +'of'+ str(posedefiner.total_poses)+'.png'\n name = os.path.join(args.log_dir,name)\n print('plotname',name)\n plt.savefig(name, bbox_inches='tight')\n\ndef radians_to_degrees(a):\n import math\n return a*180/math.pi\n\nif __name__ == '__main__':\n args = get_args()\n args.num_proc=1\n session = qi.Session()\n session.connect(\"{}:{}\".format(args.IP, args.PORT))\n env = Pepper_v0(session, args=args)\n\n # Create dirs\n path='/home/erik/DATA/Pepper'\n run = 0\n while os.path.exists(\"{}/run-{}\".format(path, run)):\n run += 1\n path = \"{}/run-{}\".format(path, run)\n os.mkdir(path)\n args.log_dir = path\n args.checkpoint_dir = path\n\n # ====== Goal ===============\n # \"hurray pose\"\n print('Using static Target')\n L_arm = [-0.38450, 0.81796, -0.99049, -1.18418, -1.3949, 0.0199]\n R_arm = [-0.90522, -1.03321, -0.05766, 0.84596, 1.39495, 0.01999]\n st = np.array(L_arm+R_arm).astype('float32')\n d = np.degrees(st)\n env.set_target(st)\n\n # env.set_angles(st)\n # degre = radians_to_degrees(st)\n # print(env.names)\n # print(st)\n # print(d)\n # raw_input()\n # raw_input()\n # s_shape = env.state_space.shape[0] # Joints state\n\n s_shape = 24\n st_shape = 12\n o_shape = env.observation_space.shape # RGB (W,H,C)\n o_shape = (3,64,64)\n ac_shape = env.action_space.shape[0] # Actions\n\n # === Memory ===\n result = Results(200, 10)\n current = Current(args.num_proc, args.num_stack, s_shape, st.shape[0], o_shape, o_shape, ac_shape)\n\n # === Model ===\n in_shape = current.st_shape + current.s_shape\n pi = MLPPolicy(input_size=in_shape, a_shape=current.ac_shape, args=args)\n\n print('\\n=== Continue Training ===\\n')\n print('Loading:', args.state_dict_path)\n sd = torch.load(args.state_dict_path)\n pi.load_state_dict(sd)\n\n evaluate(env, pi, args, plot=False)\n", "import numpy as np\nfrom multiprocessing import Process, Pipe\n\n# from OpenAI-baselines ´baselines/common/vec_env/subproc_vec_env.py´\n#\n# https://github.com/openai/baselines\n#\n# With added functionality for gesture\n\nclass CloudpickleWrapper(object):\n \"\"\"\n Uses cloudpickle to serialize contents (otherwise multiprocessing tries to use pickle)\n \"\"\"\n def __init__(self, x):\n self.x = x\n def __getstate__(self):\n import cloudpickle\n return cloudpickle.dumps(self.x)\n def __setstate__(self, ob):\n import pickle\n self.x = pickle.loads(ob)\n\n\ndef worker_social(remote, parent_remote, env_fn_wrapper):\n parent_remote.close()\n env = env_fn_wrapper.x()\n while True:\n cmd, data = remote.recv()\n if cmd == 'step':\n s, s_target, o, o_target, reward, done, info = env.step(data)\n if done:\n s, s_target, o, o_target = env.reset()\n remote.send((s, s_target, o, o_target, reward, done, info))\n elif cmd == 'reset':\n s, s_target, o, o_target = env.reset()\n remote.send((s, s_target, o, o_target))\n elif cmd == 'reset_task':\n ob = env.reset_task()\n remote.send(ob)\n elif cmd == 'close':\n remote.close()\n break\n elif cmd == 'get_spaces':\n remote.send((env.action_space, env.state_space, env.observation_space))\n elif cmd == 'render':\n remote.send(( env.render(data) ))\n elif cmd == 'set_target':\n remote.send(( env.set_target(data) ))\n else:\n raise NotImplementedError\n\n\nclass SubprocVecEnv_Social(object):\n def __init__(self, env_fns):\n \"\"\"\n envs: list of gym environments to run in subprocesses\n \"\"\"\n self.closed = False\n nenvs = len(env_fns)\n self.remotes, self.work_remotes = zip(*[Pipe() for _ in range(nenvs)])\n self.ps = [Process(target=worker_social, args=(work_remote, remote, CloudpickleWrapper(env_fn)))\n for (work_remote, remote, env_fn) in zip(self.work_remotes, self.remotes, env_fns)]\n for p in self.ps:\n p.daemon = True # if the main process crashes, we should not cause things to hang\n p.start()\n for remote in self.work_remotes:\n remote.close()\n\n self.remotes[0].send(('get_spaces', None))\n self.action_space, self.state_space, self.observation_space = self.remotes[0].recv()\n\n def step(self, actions):\n for remote, action in zip(self.remotes, actions):\n remote.send(('step', action))\n results = [remote.recv() for remote in self.remotes]\n state, s_target, obs, o_target, rews, dones, infos = zip(*results)\n return np.stack(state), np.stack(s_target), \\\n np.stack(obs), \\\n np.stack(o_target), \\\n np.stack(rews), \\\n np.stack(dones), \\\n infos\n\n def render(self, modes):\n for remote, mode in zip(self.remotes, modes):\n remote.send(('render', mode))\n results = [remote.recv() for remote in self.remotes]\n human, machine, target = zip(*results)\n return np.stack(human), np.stack(machine), np.stack(target)\n\n def set_target(self, targets):\n for remote, target in zip(self.remotes, targets):\n remote.send(('set_target', target))\n results = [remote.recv() for remote in self.remotes]\n\n def reset(self):\n for remote in self.remotes:\n remote.send(('reset', None))\n results = [remote.recv() for remote in self.remotes]\n s, s_target, o, o_target = zip(*results)\n return np.stack(s), np.stack(s_target), np.stack(o), np.stack(o_target)\n\n def reset_task(self):\n for remote in self.remotes:\n remote.send(('reset_task', None))\n return np.stack([remote.recv() for remote in self.remotes])\n\n def close(self):\n if self.closed:\n return\n for remote in self.remotes:\n remote.send(('close', None))\n for p in self.ps:\n p.join()\n self.closed = True\n\n @property\n def num_envs(self):\n return len(self.remotes)\n" ]
[ [ "numpy.abs", "numpy.isfinite", "numpy.clip", "numpy.linalg.norm", "numpy.ones", "numpy.concatenate", "numpy.fromstring", "numpy.array", "numpy.random.randint" ], [ "torch.load", "numpy.degrees", "matplotlib.pyplot.savefig", "numpy.array", "matplotlib.pyplot.pause" ], [ "numpy.stack" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Jamal-dev/asymproj_edge_dnn_tensorFlow2
[ "efb3a3721bc7e39dfa126d3c7af529b091bba9cb" ]
[ "create_dataset_arrays.py" ]
[ "# Copyright 2017 Google Inc. 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\"\"\"Creates dataset files to be used by `deep_edge_trainer.py`.\n\nThe input should be edge-list text file, with lines like \"node1 node2\", where\nthe nodes can be strings or ints. The line depicts a relationship node1-node2\n(undirected) or node1->node2 (directed). The node IDs (e.g. \"node1\") will be\nmapped to integers in [0, |V| - 1], where |V| is the number of graph nodes. The\nmapping will be saved in `index.pkl`.\n\nBy default, the input graph (edge-list) will be partitioned into train and test,\nboth of equal number of edges, where the train partition is connected (following\nnode2vec). \n\nThe output directory will be populated with files:\n train.txt.npy: int32.numpy array (|E|/2, 2) containing training edges.\n test.txt.npy: int32.numpy array (|E|/2, 2) containing test edges.\n train.neg.txt.npy: int32.numpy array (|E|/2, 2) containing negative trai\n edges, sampled from compliment of (train.txt.npy).\n test.neg.txt.npy: int32.numpy array (|E|/2, 2) containing negative test edges,\n sampled from compliment of (test.txt.npy union train.txt.npy)\n train.pairs.<i>.txt.npy: One or more training pair numpy arrays [size (?, 2)].\n\nSee doc of `CreateDatasetFiles()` for complete list of files and description.\n\nTo run, you should download node2vec.py from\nhttps://github.com/aditya-grover/node2vec/blob/master/src/node2vec.py\nand place in the same directory as this file. If you do not download it, it will\nautomatically be downloaded on your behalf.\n\"\"\"\n\nimport pickle as cPickle\nimport copy\nimport random\nimport networkx as nx\nimport numpy\nimport os\nimport sys\n\nimport tensorflow as tf\n\n#from tensorflow import flags\nfrom tensorflow.python.platform import flags\n\nfrom third_party.node2vec import node2vec\nimport argparse\nimport csv\n\ndef check_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--output_dir\", type=str, help=\"Directory where training files will be written.\",\n nargs='?', default=\"output/\", const=\"output/\")\n parser.add_argument(\"--directed\", type=bool, help=\"Must be set if graph is directed.\",\n nargs='?', default=False, const=False)\n parser.add_argument(\"--partition\",type=bool, help=\"If set (default), separates a test split, containing half of the edges. In which case, train graph will be connected.\",\n nargs='?', default=True, const=True)\n parser.add_argument(\"--num_walks\", type=int, help=\"Number of walks per node.\",\n nargs='?', default=5, const=5)\n parser.add_argument(\"--walk_length\", type=int, help=\"Length of each walk. Total number of pairs will be\\n O(walk_length * num_walks * num nodes * context^2)\",\n nargs='?', default=40, const=40)\n parser.add_argument(\"--context\", type=int, help=\"Size of context from each side (right and left). If \\n --directed, then context is only taken from right side\",\n nargs='?', default=3, const=3)\n parser.add_argument(\"--only_simulate_walks\", type=bool, help=\"If set, train.txt.npy will be read from --output_dir, \\n random walks will be simulated, out their output will be\\n written to --output_dir\",\n nargs='?', default=False, const=False)\n parser.add_argument(\"--input\", type=str, help=\"Path to edge-list textfile. Required unless --only_simulate_walks is set.\",\n nargs='?', default=\"datasets/CA-HepTh.txt\", const=\"datasets/CA-HepTh.txt\")\n parser.add_argument(\"--bs\", type=int, help=\"Enter the size of the batch\",\n nargs='?', default=256, const=256)\n\n args = parser.parse_args()\n input_ = args.input\n only_simulate_walks = args.only_simulate_walks\n output_dir = args.output_dir\n directed = args.directed\n partition = args.partition\n num_walks = args.num_walks\n walk_length = args.walk_length\n context = args.context\n \n \n return input_, only_simulate_walks, output_dir, directed, partition, num_walks, walk_length, context\n\n#flags.DEFINE_string('input', '',\n# 'Path to edge-list textfile. Required unless '\n# '--only_simulate_walks is set.')\n#flags.DEFINE_boolean('only_simulate_walks', False,\n# 'If set, train.txt.npy will be read from --output_dir, '\n# 'random walks will be simulated, out their output will be '\n# 'written to --output_dir')\n#flags.DEFINE_string('output_dir', '',\n# 'Directory where training files will be written.')\n#flags.DEFINE_boolean('directed', False, 'Must be set if graph is directed.')\n#flags.DEFINE_boolean('partition', True,\n# 'If set (default), separates a test split, containing '\n# 'half of the edges. In which case, train graph will be '\n# 'connected.')\n#\n#flags.DEFINE_integer('num_walks', 5, 'Number of walks per node.')\n#flags.DEFINE_integer('walk_length', 40,\n# 'Length of each walk. Total number of pairs will be '\n# 'O(walk_length * num_walks * num nodes * context^2)')\n#flags.DEFINE_integer('context', 3,\n# 'Size of context from each side (right and left). If '\n# '--directed, then context is only taken from right side')\n#\n#FLAGS = flags.FLAGS\n\n# node2vec parameters\nN2V_P = 1.0\nN2V_Q = 1.0\n\n\ndef LargestSubgraph(graph):\n \"\"\"Returns the Largest connected-component of `graph`.\"\"\"\n if graph.__class__ == nx.Graph:\n return LargestUndirectedSubgraph(graph)\n elif graph.__class__ == nx.DiGraph:\n largest_undirected_cc = LargestUndirectedSubgraph(nx.Graph(graph))\n directed_subgraph = nx.DiGraph()\n for (n1, n2) in graph.edges():\n if n2 in largest_undirected_cc and n1 in largest_undirected_cc[n2]:\n directed_subgraph.add_edge(n1, n2)\n\n return directed_subgraph\n\ndef LargestUndirectedSubgraph(graph):\n \"\"\"Returns the largest connected-component of undirected `graph`.\"\"\"\n if nx.is_connected(graph):\n return graph\n cc = (graph.subgraph(c) for c in nx.connected_components(graph))\n cc = list(cc)\n # cc = list(nx.connected_component_subgraphs(graph))\n sizes = map(len, cc)\n sizes_and_cc = zip(sizes, cc)\n sizes_and_cc = sorted(sizes_and_cc, key=lambda x: x[0])\n # changed here\n # sizes_and_cc.sort()\n sizes_and_cc = list(sizes_and_cc)\n return sizes_and_cc[-1][1]\n\ndef SampleTestEdgesAndPruneGraph(graph, remove_percent=0.5, check_every=5):\n \"\"\"Removes and returns `remove_percent` of edges from graph.\n \n Removal is random but makes sure graph stays connected.\"\"\"\n graph = copy.deepcopy(graph)\n undirected_graph = graph.to_undirected()\n edges = copy.deepcopy(graph.edges())\n edges = list(edges)\n # changed to list here\n random.shuffle(edges)\n remove_edges = int(len(edges) * remove_percent)\n num_edges_removed = 0\n currently_removing_edges = []\n removed_edges = []\n last_printed_prune_percentage = -1\n for j in range(len(edges)):\n n1, n2 = edges[j]\n graph.remove_edge(n1, n2)\n if n1 not in graph[n2]:\n undirected_graph.remove_edge(*(edges[j]))\n currently_removing_edges.append(edges[j])\n if j % check_every == 0:\n if nx.is_connected(undirected_graph):\n num_edges_removed += check_every\n removed_edges += currently_removing_edges\n currently_removing_edges = []\n else:\n for i in range(check_every):\n graph.add_edge(*(edges[j - i]))\n undirected_graph.add_edge(*(edges[j - i]))\n currently_removing_edges = []\n if not nx.is_connected(undirected_graph):\n print( ' DID NOT RECOVER :(')\n return None\n prunned_percentage = int(100 * len(removed_edges) / remove_edges)\n rounded = (prunned_percentage / 10) * 10\n if rounded != last_printed_prune_percentage:\n last_printed_prune_percentage = rounded\n print (f'Partitioning into train/test. Progress={rounded}')\n \n if len(removed_edges) >= remove_edges:\n break\n\n return graph, removed_edges\n\n\ndef SampleNegativeEdges(graph, num_edges):\n \"\"\"Samples `num_edges` edges from compliment of `graph`.\"\"\"\n random_negatives = set()\n nodes = list(graph.nodes())\n while len(random_negatives) < num_edges:\n i1 = random.randint(0, len(nodes) - 1)\n i2 = random.randint(0, len(nodes) - 1)\n if i1 == i2:\n continue\n if i1 > i2:\n i1, i2 = i2, i1\n n1 = nodes[i1]\n n2 = nodes[i2]\n if graph.has_edge(n1, n2):\n continue\n random_negatives.add((n1, n2))\n\n return random_negatives\n\n\ndef RandomNegativesPerNode(graph, negatives_per_node=400):\n \"\"\"For every node u in graph, samples 20 (u, v) where v is not in graph[u].\"\"\"\n negatives = []\n node_list = list(graph.nodes())\n num_nodes = len(node_list)\n print_every = num_nodes / 10\n for i, n in enumerate(node_list):\n found_negatives = 0\n if i % print_every == 0:\n print (f'Finished sampling negatives for {i} / {num_nodes} nodes')\n while found_negatives < negatives_per_node:\n n2 = node_list[random.randint(0, num_nodes - 1)]\n if n == n2 or n2 in graph[n]:\n continue\n negatives.append((n, n2))\n found_negatives += 1\n return negatives\n\n\ndef NumberNodes(graph):\n \"\"\"Returns a copy of `graph` where nodes are replaced by incremental ints.\"\"\"\n node_list = sorted(graph.nodes())\n index = {n: i for (i, n) in enumerate(node_list)}\n \n newgraph = graph.__class__()\n for (n1, n2) in graph.edges():\n newgraph.add_edge(index[n1], index[n2])\n\n return newgraph, index\n\n\nclass WalkPairsWriter(object):\n \"\"\"Writes one or more int numpy.array of size (S, 2).\n \n Where `S` is the size of the array, up to `self.capacity`. The total number\n of pairs should be the number of times `AddPair` is called.\n \"\"\"\n \n def __init__(self, file_format):\n \"\"\"file_format must contain %i.\"\"\"\n self.file_format = file_format\n self.capacity = 1000000 # 1 million.\n self.pairs = []\n self.next_file_id = 0\n\n def AddPair(self, n1, n2):\n self.pairs.append((n1, n2))\n if len(self.pairs) > self.capacity:\n self.Write()\n \n def Write(self):\n if len(self.pairs) == 0:\n return\n file_name = self.file_format % self.next_file_id\n random.shuffle(self.pairs)\n pairs_arr = numpy.array(self.pairs, dtype='int32')\n numpy.save(file_name, pairs_arr)\n self.pairs = []\n self.next_file_id += 1\n \n \ndef MakeDirectedNegatives(positive_edges):\n positive_set = set([(u, v) for (u, v) in list(positive_edges)])\n directed_negatives = []\n for (u, v) in positive_set:\n if (v, u) not in positive_set:\n directed_negatives.append((v, u))\n return numpy.array(directed_negatives, dtype='int32')\n\n\ndef CreateDatasetFiles(graph, output_dir, num_walks,\n context_right, context_left,\n walk_length, p, q ,partition=True):\n \"\"\"\n Writes a number of dataset files to `output_dir`.\n \n Args:\n graph: nx.Graph or nx.DiGraph to simulate walks on and extract negatives.\n output_dir: files will be written in this directory, including:\n {train, train.neg, test, test.neg}.txt.npy, index.pkl, and\n if flag --directed is set, test.directed.neg.txt.npy.\n The files {train, train.neg}.txt.npy are used for model selection;\n {test, test.neg, test.directed.neg}.txt.npy will be used for calculating\n eval metrics; index.pkl contains information about the graph (# of nodes,\n mapping from original graph IDs to new assigned integer ones in\n [0, largest_cc_size-1].\n partition: If set largest connected component will be used and data will \n separated into train/test splits.\n \n Returns:\n The training graph, after node renumbering.\n \"\"\"\n num_floats = num_walks * walk_length * len(graph)\n num_floats *= (context_left + context_right) ** 2\n print(f\"Writing up to {num_floats} training pairs, with size = {num_floats * 4/1000000.0} megabytes.\")\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n\n original_size = len(graph)\n if partition:\n graph = LargestSubgraph(graph)\n size_largest_cc = len(graph)\n else:\n size_largest_cc = -1\n graph, index = NumberNodes(graph)\n\n if partition:\n train_graph, test_edges = SampleTestEdgesAndPruneGraph(graph)\n else:\n train_graph, test_edges = graph, []\n\n # Sample negatives, to be equal to number of `test_edges` * 2.\n random_negatives = list(\n SampleNegativeEdges(graph, len(test_edges) + len(train_graph.edges())))\n random.shuffle(random_negatives)\n test_negatives = random_negatives[:len(test_edges)]\n # These are only used for evaluation, never training.\n train_eval_negatives = random_negatives[len(test_edges):]\n\n test_negatives = numpy.array(test_negatives, dtype='int32')\n test_edges = numpy.array(test_edges, dtype='int32')\n train_edges = numpy.array(train_graph.edges(), dtype='int32')\n train_eval_negatives = numpy.array(train_eval_negatives, dtype='int32')\n \n \n\n numpy.save(os.path.join(output_dir, 'train.txt'), train_edges)\n numpy.save(os.path.join(output_dir, 'train.neg.txt'), train_eval_negatives)\n numpy.save(os.path.join(output_dir, 'test.txt'), test_edges)\n numpy.save(os.path.join(output_dir, 'test.neg.txt'), test_negatives)\n # saving as csv file as well,\n # numpy.savetxt(os.path.join(output_dir, 'train.csv'), train_edges, delimiter=\",\")\n # numpy.savetxt(os.path.join(output_dir, 'train_neg.csv'), train_eval_negatives, delimiter=\",\")\n # numpy.savetxt(os.path.join(output_dir, 'test.csv'), test_edges, delimiter=\",\")\n # numpy.savetxt(os.path.join(output_dir, 'test_neg.csv'), test_negatives, delimiter=\",\")\n if directed:\n directed_negatives = MakeDirectedNegatives(\n numpy.concatenate([train_edges, test_edges], axis=0))\n directed_negatives = numpy.concatenate([directed_negatives, test_negatives],\n axis=0)\n numpy.save(\n os.path.join(output_dir, 'test.directed.neg.txt'), directed_negatives)\n # saving as csv\n # numpy.savetxt(\n # os.path.join(output_dir, 'test_directed_neg.csv'), directed_negatives,delimiter=\",\")\n\n cPickle.dump({\n 'index': index,\n 'original_num_nodes': original_size,\n 'largest_cc_num_nodes': size_largest_cc,\n 'num_pos_test_edges': len(test_edges),\n 'num_neg_test_edges': len(test_negatives),\n 'num_pos_train_edges': len(train_edges),\n 'num_neg_train_edges': len(train_eval_negatives),\n }, open(os.path.join(output_dir, 'index.pkl'), 'wb'))\n\n # saving index as csv\n # with open(os.path.join(output_dir, 'index.csv'), 'w') as csv_file: \n # writer = csv.writer(csv_file)\n # for key, value in index.items():\n # writer.writerow([key, value])\n\n return train_graph\n\n\ndef SimulateWalks(train_graph, output_dir, num_walks=10, walk_length=80,\n context_left=3, context_right=3, p=N2V_P, q=N2V_Q):\n \"\"\"Simulates Random Walks on `train_graph`, writing onto `output_dir`.\n \n Args:\n train_graph: nx.Graph or nx.DiGraph to simulate walks on and extract\n negatives.\n output_dir: files will be written in this directory, including:\n train.neg_per_node.txt.npy and train.pairs.<i>.txt.npy, for integer <i> in\n [0, num_walks - 1]. These files will be used for training the linear\n approximation of the Graph Likelihood objective.\n num_walks: Number of walks per node.\n walk_length: Walk length from every node.\n context_left: left offset from central word, inclusive.\n context_right: right offset from central word, inclusive.\n p: Node2vec's p parameter.\n q: Node2vec's q parameter.\n \"\"\"\n train_negatives_per_node = RandomNegativesPerNode(train_graph, negatives_per_node=400)\n train_negatives_per_node = numpy.array(train_negatives_per_node,dtype='int32')\n numpy.save(os.path.join(output_dir, 'train.neg_per_node.txt'),train_negatives_per_node)\n \n for edge in train_graph.edges():\n train_graph[edge[0]][edge[1]]['weight'] = 1\n directed = (train_graph.__class__ == nx.DiGraph)\n node2vec_graph = node2vec.Graph(train_graph, is_directed=directed, p=p, q=q)\n node2vec_graph.preprocess_transition_probs()\n \n pairs_writer = WalkPairsWriter(os.path.join(output_dir, 'train.pairs.%i'))\n for unused_j in range(num_walks):\n walks = node2vec_graph.simulate_walks(1, walk_length)\n \n for c, node_list in enumerate(walks):\n if c % 1000 == 0:\n print(f'Writing Walk Pairs {c} / {len(walks)}' )\n for i in range(len(node_list)):\n start_i = max(0, i - context_left)\n end_i = min(len(node_list), i + context_right + 1)\n for k in range(start_i, end_i):\n # if i == k: continue\n pairs_writer.AddPair(node_list[i], node_list[k])\n\n pairs_writer.Write()\n \n print(f'All Done. Nodes = {len(train_graph)}')\n\ndef main_exp(directed):\n if directed:\n graph = nx.DiGraph()\n else:\n graph = nx.Graph()\n\n if not only_simulate_walks:\n # Read graph\n graph = nx.read_edgelist(input_, create_using=graph)\n\n # Create dataset files.\n graph = CreateDatasetFiles(\n graph, output_dir, num_walks=num_walks,\n context_right=context, context_left=context*directed,\n walk_length=walk_length, p=N2V_P, q=N2V_Q)\n else:\n if os.path.exists(os.path.join(output_dir, 'test.directed.neg.txt.npy')):\n graph = nx.DiGraph()\n directed = True\n\n # Only simulating walks. Read graph from --output_dir\n train_edges = numpy.load(os.path.join(output_dir, 'train.txt.npy'))\n for n1, n2 in list(train_edges):\n graph.add_edge(n1, n2)\n\n left_context = context * (not directed)\n print(f'left_context = {left_context}' )\n SimulateWalks(\n graph, output_dir, num_walks=num_walks,\n context_right=context, context_left=left_context,\n walk_length=walk_length, p=N2V_P, q=N2V_Q)\n\n\nif __name__ == '__main__':\n \n \n global input_, only_simulate_walks, output_dir, directed, partition, num_walks, walk_length, context \n input_, only_simulate_walks, output_dir, directed, partition, num_walks, walk_length, context = check_args()\n main_exp(directed=directed)\n" ]
[ [ "numpy.concatenate", "numpy.array", "numpy.save" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ng390/selfstudy-adversarial-robustness
[ "e225142564793ba7799d7e76727928f72cfb769e", "e225142564793ba7799d7e76727928f72cfb769e", "e225142564793ba7799d7e76727928f72cfb769e" ]
[ "convert_pytorch.py", "defense_discretize/model.py", "training/train_ls.py" ]
[ "# Copyright 2021 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 os\nimport sys\nimport tensorflow as tf\nimport torch\nimport math\nimport numpy as np\n\nfrom common.networks import AllConvModel, AllConvModelTorch\nfrom common.framework import get_checkpoint_abs_path\n\nimport logging\ntf.get_logger().setLevel(logging.ERROR) \n\n\ndef fix(path):\n path_tf = path[:-6]\n path_torch = path_tf + \".torchmodel\"\n if os.path.exists(path_torch):\n return\n\n print()\n print(\"Converting\", path)\n \n # Get input sizes\n all_vars = tf.train.list_variables(\n get_checkpoint_abs_path(path_tf))\n\n # Is it a list of models? Or just one?\n if 'model/0' in \"\".join([x[0] for x in all_vars]):\n prefix = 'model/0'\n else:\n prefix = 'model'\n \n input_size, filter_size = [shape for name,shape in all_vars if prefix+'/layers/0/kernel' in name][0][2:]\n output_size = [shape for name,shape in all_vars if prefix+'/layers/9/kernel' in name][0][-1]\n\n num_models = sum('/0/kernel' in x for x,_ in all_vars)\n\n # Create the TF convnet\n convnet = [AllConvModel(num_classes=output_size,\n num_filters=filter_size,\n input_shape=(32, 32, input_size))\n for _ in range(num_models)]\n \n convnet_load = convnet[0] if num_models == 1 else convnet\n tf.train.Checkpoint(model=convnet_load).restore(\n get_checkpoint_abs_path(path_tf))\n\n weights = []\n for model in convnet:\n ws = []\n for layer in model.layers:\n if len(layer.weights) > 0:\n ws.append(layer.weights)\n weights.extend(ws[::-1])\n \n models = [AllConvModelTorch(10, 64, (input_size, 32, 32)) for _ in range(num_models)]\n for model in models:\n for layer in model.layers:\n if isinstance(layer, torch.nn.Conv2d):\n w, b = weights.pop()\n layer.weight = torch.nn.Parameter(torch.tensor(w.numpy().transpose((3,2,0,1))))\n layer.bias = torch.nn.Parameter(torch.tensor(b.numpy()))\n\n if len(models) == 1:\n torch.save(models[0].state_dict(), path_torch)\n else:\n torch.save([model.state_dict() for model in models], path_torch)\n\n\ndef run():\n for root,_,fs in os.walk(sys.argv[1] if len(sys.argv) > 1 else 'checkpoints'):\n for f in fs:\n if \".index\" in f:\n fix(os.path.join(root, f))\n\nif __name__ == \"__main__\":\n run()\n", "# Copyright 2021 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\n\"\"\"Model of the defense 6.\"\"\"\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom common.framework import DefenseModel, get_checkpoint_abs_path\nfrom common.networks import AllConvModel, AllConvModelTorch\n\nimport common.utils as utils\n\n\nMODEL_PATH = 'checkpoints/discretize/final_checkpoint-1'\n\n\nclass Defense(DefenseModel):\n\n def __init__(self):\n self.convnet = AllConvModel(num_classes=10,\n num_filters=64,\n input_shape=[32, 32, 3*20])\n tf.train.Checkpoint(model=self.convnet).restore(\n get_checkpoint_abs_path(MODEL_PATH))\n\n def encode(self, xs):\n thresholds = np.arange(0, 1, .05)+.05\n shape = xs.shape\n less_than_threshold = xs[:,:,:,:,None] < thresholds\n xs = np.array(less_than_threshold, dtype=np.float32)\n xs = np.reshape(xs, [-1, shape[1], shape[2], shape[3]*len(thresholds)])\n return xs\n\n def classify(self, xs, training=False):\n xs = self.encode(xs)\n return utils.to_numpy(self.convnet(xs))\n\n\nclass DefenseTorch(Defense):\n\n def __init__(self):\n import torch\n self.convnet = AllConvModelTorch(num_classes=10,\n num_filters=64,\n input_shape=[3*20, 32, 32])\n self.convnet.load_state_dict(\n torch.load(get_checkpoint_abs_path(MODEL_PATH) + \".torchmodel\"))\n\n def encode(self, xs):\n thresholds = np.arange(0, 1, .05)+.05\n shape = xs.shape\n less_than_threshold = xs[:,:,None,:,:] < thresholds[None,None,:,None,None]\n xs = np.array(less_than_threshold, dtype=np.float32)\n xs = np.reshape(xs, [-1, shape[1]*len(thresholds), shape[2], shape[3]])\n return xs\n", "# Copyright 2021 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\n\"\"\"Training code for baseline model.\"\"\"\n\nfrom absl import app\nfrom absl import flags\nfrom absl import logging\n\nimport os\nimport numpy as np\nimport tensorflow as tf\n\nimport common.data as data\n\nfrom train_baseline import TrainLoop\n\nFLAGS = flags.FLAGS\n\nclass SmoothLabelTrainLoop(TrainLoop):\n def __init__(self, num_filters, num_classes, input_shape):\n super().__init__(num_filters, num_classes, input_shape)\n\n def loss(self, model, x, y, return_preds=False, wd=1e-4):\n \"\"\"\n Compute the loss of the neural network on a given (x,y) tuple.\n \"\"\"\n logits = model(x, training=True)\n y_ls = tf.one_hot(y, 10)\n y_ls = y_ls + .125\n y_ls /= tf.reduce_sum(y_ls, axis=1, keepdims=True)\n l_xe = tf.reduce_mean(\n tf.nn.softmax_cross_entropy_with_logits(logits=logits,\n labels=y_ls))\n\n total_loss = l_xe\n \n if return_preds:\n return total_loss, logits\n else:\n return total_loss\n\n \ndef main(argv):\n del argv\n\n dataset = data.load_dataset(FLAGS.dataset)\n\n (x_train, y_train), (x_test, y_test), num_classes = dataset\n\n input_shape = x_train[0].shape\n\n loop = SmoothLabelTrainLoop(FLAGS.num_filters,\n 10, input_shape)\n\n loop.train(dataset=dataset,\n batch_size=FLAGS.batch_size,\n num_epochs=FLAGS.num_epochs,\n model_dir=os.path.join(FLAGS.model_dir, \"labelsmooth\"))\n\nif __name__ == '__main__':\n logging.set_verbosity(logging.INFO)\n app.run(main)\n" ]
[ [ "tensorflow.train.Checkpoint", "tensorflow.get_logger" ], [ "tensorflow.train.Checkpoint", "numpy.arange", "numpy.array" ], [ "tensorflow.reduce_sum", "tensorflow.nn.softmax_cross_entropy_with_logits", "tensorflow.one_hot" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
yukgu/covid-model-seiir-pipeline
[ "3433034d3f089938e7993b6321d570365bdf62db", "3433034d3f089938e7993b6321d570365bdf62db" ]
[ "src/covid_model_seiir_pipeline/pipeline/regression/task/beta_regression.py", "src/covid_model_seiir_pipeline/lib/utilities.py" ]
[ "from pathlib import Path\n\nimport click\nimport numpy as np\nimport pandas as pd\n\nfrom covid_model_seiir_pipeline.lib import (\n cli_tools,\n math,\n static_vars,\n)\nfrom covid_model_seiir_pipeline.pipeline.regression.data import RegressionDataInterface\nfrom covid_model_seiir_pipeline.pipeline.regression.specification import RegressionSpecification\nfrom covid_model_seiir_pipeline.pipeline.regression import model\n\n\nlogger = cli_tools.task_performance_logger\n\n\ndef run_beta_regression(regression_version: str, draw_id: int, progress_bar: bool) -> None:\n logger.info('Starting beta regression.', context='setup')\n # Build helper abstractions\n regression_spec_file = Path(regression_version) / static_vars.REGRESSION_SPECIFICATION_FILE\n regression_specification = RegressionSpecification.from_path(regression_spec_file)\n data_interface = RegressionDataInterface.from_specification(regression_specification)\n\n logger.info('Loading ODE fit input data', context='read')\n hierarchy = data_interface.load_hierarchy()\n past_infection_data = data_interface.load_past_infection_data(draw_id=draw_id)\n population = data_interface.load_five_year_population()\n rhos = data_interface.load_variant_prevalence()\n vaccinations = data_interface.load_vaccinations()\n\n logger.info('Prepping ODE fit parameters.', context='transform')\n infections = model.clean_infection_data_measure(past_infection_data, 'infections')\n regression_params = regression_specification.regression_parameters.to_dict()\n\n np.random.seed(draw_id)\n sampled_params = model.sample_params(\n infections.index, regression_params,\n params_to_sample=['alpha', 'sigma', 'gamma1', 'gamma2', 'kappa', 'chi', 'pi']\n )\n\n sampled_params['phi'] = pd.Series(\n np.random.normal(loc=sampled_params['chi'] + regression_params['phi_mean_shift'],\n scale=regression_params['phi_sd']),\n index=infections.index, name='phi',\n )\n sampled_params['psi'] = pd.Series(\n np.random.normal(loc=sampled_params['chi'] + regression_params['psi_mean_shift'],\n scale=regression_params['psi_sd']),\n index=infections.index, name='psi',\n )\n\n ode_parameters = model.prepare_ode_fit_parameters(\n infections,\n population,\n rhos,\n vaccinations,\n sampled_params,\n )\n\n logger.info('Running ODE fit', context='compute_ode')\n beta_fit, compartments = model.run_ode_fit(\n ode_parameters=ode_parameters,\n progress_bar=progress_bar,\n )\n\n logger.info('Loading regression input data', context='read')\n covariates = data_interface.load_covariates(list(regression_specification.covariates))\n gaussian_priors = data_interface.load_priors(regression_specification.covariates.values())\n prior_coefficients = data_interface.load_prior_run_coefficients(draw_id=draw_id)\n if gaussian_priors and prior_coefficients:\n raise NotImplementedError\n\n logger.info('Fitting beta regression', context='compute_regression')\n coefficients = model.run_beta_regression(\n beta_fit['beta'],\n covariates,\n regression_specification.covariates.values(),\n gaussian_priors,\n prior_coefficients,\n hierarchy,\n )\n log_beta_hat = math.compute_beta_hat(covariates, coefficients)\n beta_hat = np.exp(log_beta_hat).rename('beta_hat')\n\n # Format and save data.\n logger.info('Prepping outputs', context='transform')\n betas = pd.concat([beta_fit, beta_hat], axis=1).reindex(infections.index)\n deaths = model.clean_infection_data_measure(past_infection_data, 'deaths')\n ode_parameters = ode_parameters.to_df()\n\n logger.info('Writing outputs', context='write')\n data_interface.save_infections(infections, draw_id=draw_id)\n data_interface.save_deaths(deaths, draw_id=draw_id)\n data_interface.save_betas(betas, draw_id=draw_id)\n data_interface.save_compartments(compartments, draw_id=draw_id)\n data_interface.save_coefficients(coefficients, draw_id=draw_id)\n data_interface.save_ode_parameters(ode_parameters, draw_id=draw_id)\n\n logger.report()\n\n\[email protected]()\n@cli_tools.with_task_regression_version\n@cli_tools.with_draw_id\n@cli_tools.add_verbose_and_with_debugger\n@cli_tools.with_progress_bar\ndef beta_regression(regression_version: str, draw_id: int,\n progress_bar: bool, verbose: int, with_debugger: bool):\n cli_tools.configure_logging_to_terminal(verbose)\n run = cli_tools.handle_exceptions(run_beta_regression, logger, with_debugger)\n run(regression_version=regression_version,\n draw_id=draw_id,\n progress_bar=progress_bar)\n\n\nif __name__ == '__main__':\n beta_regression()\n", "from __future__ import annotations\n\nimport abc\nfrom dataclasses import asdict as asdict_, fields, is_dataclass\nfrom pathlib import Path\nfrom typing import Dict, Union, Tuple\nfrom pprint import pformat\n\nfrom covid_shared import ihme_deps\nimport numpy as np\nimport pandas as pd\nimport yaml\n\n\nclass YamlIOMixin:\n \"\"\"Mixin for reading and writing yaml files.\"\"\"\n\n @staticmethod\n def _coerce_path(path: Union[str, Path]) -> Path:\n path = Path(path)\n if path.suffix not in ['.yaml', '.yml']:\n raise ValueError('Path must point to a yaml file. '\n f'You provided {str(path)}')\n return path\n\n @classmethod\n def _load(cls, path: Union[str, Path]):\n path = cls._coerce_path(path)\n with path.open() as f:\n data = yaml.full_load(f)\n\n return data\n\n @classmethod\n def _dump(cls, data, path: Union[str, Path]) -> None:\n path = cls._coerce_path(path)\n with path.open('w') as f:\n yaml.dump(data, f, sort_keys=False)\n\n\nclass Specification(YamlIOMixin):\n \"\"\"Generic class for pipeline stage specifications.\"\"\"\n\n @classmethod\n def from_path(cls, specification_path: Union[str, Path]) -> Specification:\n \"\"\"Builds the specification from a file path.\"\"\"\n spec_dict = cls._load(specification_path)\n return cls.from_dict(spec_dict)\n\n @classmethod\n def from_dict(cls, spec_dict: Dict) -> Specification:\n \"\"\"Builds the specification from a dictionary.\"\"\"\n args = cls.parse_spec_dict(spec_dict)\n return cls(*args)\n\n @classmethod\n @abc.abstractmethod\n def parse_spec_dict(cls, specification: Dict) -> Tuple:\n \"\"\"Parses a dict representation of the specification into init args.\"\"\"\n raise NotImplementedError\n\n @abc.abstractmethod\n def to_dict(self) -> Dict:\n \"\"\"Coerce the specification to a dict.\"\"\"\n raise NotImplementedError\n\n def dump(self, path: Union[str, Path]) -> None:\n \"\"\"Writes this specification to a file.\"\"\"\n data = self.to_dict()\n self._dump(data, path)\n\n def __repr__(self):\n return f'{self.__class__.__name__}(\\n{pformat(self.to_dict())}\\n)'\n\n\ndef asdict(data_class) -> Dict:\n \"\"\"Type coerce items for easy serialization\"\"\"\n data = asdict_(data_class)\n out = {}\n for k, v in data.items():\n if isinstance(v, tuple):\n out[k] = list(v)\n elif isinstance(v, np.ndarray):\n out[k] = v.tolist()\n else:\n out[k] = v\n return out\n\n\ndef filter_to_spec_fields(spec_dict: dict, specification):\n if is_dataclass(specification):\n return {\n k: v for k, v in spec_dict.items()\n if k in [f.name for f in fields(specification)]\n }\n else:\n return spec_dict\n\n\ndef load_location_hierarchy(location_set_version_id: int = None,\n location_file: Path = None, **kwargs):\n assert ((location_set_version_id and not location_file)\n or (not location_set_version_id and location_file))\n\n if location_set_version_id:\n return ihme_deps.get_location_hierarchy_by_version(\n location_set_version_id=location_set_version_id,\n )\n else:\n return pd.read_csv(location_file)\n" ]
[ [ "numpy.random.normal", "numpy.exp", "pandas.concat", "numpy.random.seed" ], [ "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
teomotun/Restaurant-Plug
[ "1ecaab7bb60706ec0eca96c2f3efb31276c536e7" ]
[ "Model/code/training_restaurant_features.py" ]
[ "import pandas as pd\nimport h5py\n\n# Paths\nDATA_HOME = \"/content/drive/My Drive/Yelp-Restaurant-Classification/Model/data/\"\nFEATURES_HOME = '/content/drive/My Drive/Yelp-Restaurant-Classification/Model/features/'\n\n# Get photo->business mapping from the file provided\ntrain_photo_to_biz_ids = pd.read_csv(DATA_HOME + 'train_photo_to_biz_ids.csv')\n\n# Get labels for businesses in the training data\ntrain_data_business = pd.read_csv(DATA_HOME + 'train.csv').dropna()\n\n# Sort these labels in the ascending order for simplicity e.g. (0, 6, 4, 2, 5) -> (0, 2, 4, 5, 6)\ntrain_data_business['labels'] = train_data_business['labels'].apply(\n lambda feature_vector: tuple(sorted(int(feature) for feature in feature_vector.split())))\ntrain_data_business.set_index('business_id', inplace=True)\n\n# Get business ids\nbusiness_ids = train_data_business.index.unique()\nprint(\"Total train business:\", len(business_ids))\n\n# Reading stored features from h5 file\ntrain_features_file = h5py.File(FEATURES_HOME + 'train_features.h5', 'r')\ntrain_features = np.copy(train_features_file['feature'])\ntrain_features_file.close()\n\n# Create a pandas dataframe to make the data ready for training the SVM classifier in the following format\ntrain_df = pd.DataFrame(columns=['business_id', 'label', 'feature'])\n\nfor business_id in business_ids:\n \"\"\"\n For each business, write the values for the above triplet in the file viz. ['business_id', 'label', 'feature']\n \"\"\"\n business_id = int(business_id)\n\n # Get the labels for the current business\n label = train_data_business.loc[business_id]['labels']\n\n # Get all the images which represent the current business with business_id\n images_for_business_id = train_photo_to_biz_ids[train_photo_to_biz_ids['business_id'] == business_id].index.tolist()\n\n # As a feature for current business, take the average over all the images\n feature = list(np.mean(train_features[images_for_business_id], axis=0))\n\n # Put the triplet into the data frame\n train_df.loc[business_id] = [business_id, label, feature]\n\nprint(\"Train business feature extraction is completed.\")\n\n# Write the above data frame into a csv file\nwith open(FEATURES_HOME + 'train_aggregate_features.csv', 'w') as business_features_file:\n train_df.to_csv(business_features_file, index=False)" ]
[ [ "pandas.read_csv", "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
potti95/fewrel
[ "5706b45c6936a60ef94326808e24d0ed0643a579" ]
[ "train_demo.py" ]
[ "from fewshot_re_kit.data_loader import get_loader, get_loader_pair, get_loader_unsupervised\nfrom fewshot_re_kit.framework import FewShotREFramework\nfrom fewshot_re_kit.sentence_encoder import FasttextSentenceEncoder, CNNSentenceEncoder, BERTSentenceEncoder, \\\n BERTPAIRSentenceEncoder, RobertaSentenceEncoder, RobertaPAIRSentenceEncoder, BERTPAIRMULTISentenceEncoder, \\\n BertSentenceEncoderOWN\nimport models\nfrom models.proto import Proto\nfrom models.gnn import GNN\nfrom models.snail import SNAIL\nfrom models.metanet import MetaNet\nfrom models.siamese import Siamese\nfrom models.pair import Pair\nfrom models.d import Discriminator\nfrom models.mtb import Mtb\nimport sys\nimport torch\nfrom torch import optim, nn\nimport numpy as np\nimport json\nimport argparse\nimport os\nimport io\n#import fasttext\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--train', default='train_wiki', #train_wiki\n help='train file')\n parser.add_argument('--val', default='val_wiki',\n help='val file')\n parser.add_argument('--test', default='val_wiki',\n help='test file')\n parser.add_argument('--adv', default=None,\n help='adv file')\n parser.add_argument('--trainN', default=5, type=int,\n help='N in train')\n parser.add_argument('--N', default=5, type=int,\n help='N way')\n parser.add_argument('--K', default=1, type=int,\n help='K shot')\n parser.add_argument('--Q', default=1, type=int,\n help='Num of query per class')\n parser.add_argument('--batch_size', default=1, type=int,\n help='batch size')\n parser.add_argument('--train_iter', default=30000, type=int,\n help='num of iters in training')\n parser.add_argument('--val_iter', default=1000, type=int, #1000\n help='num of iters in validation')\n parser.add_argument('--test_iter', default=10000, type=int, #10000\n help='num of iters in testing')\n parser.add_argument('--val_step', default=2000, type=int,\n help='val after training how many iters')\n parser.add_argument('--model', default='proto',\n help='model name')\n parser.add_argument('--encoder', default='cnn',\n help='encoder: cnn or bert or roberta')\n parser.add_argument('--max_length', default=128, type=int,\n help='max length')\n parser.add_argument('--lr', default=-1, type=float,\n help='learning rate')\n parser.add_argument('--weight_decay', default=1e-5, type=float,\n help='weight decay')\n parser.add_argument('--dropout', default=0.0, type=float,\n help='dropout rate')\n parser.add_argument('--na_rate', default=0, type=int,\n help='NA rate (NA = Q * na_rate)')\n parser.add_argument('--grad_iter', default=1, type=int,\n help='accumulate gradient every x iterations')\n parser.add_argument('--optim', default='sgd',\n help='sgd / adam / adamw')\n parser.add_argument('--hidden_size', default=230, type=int,\n help='hidden size')\n parser.add_argument('--load_ckpt', default=None,\n help='load ckpt')\n parser.add_argument('--save_ckpt', default=None,\n help='save ckpt')\n parser.add_argument('--fp16', action='store_true',\n help='use nvidia apex fp16')\n parser.add_argument('--only_test', action='store_true',\n help='only test')\n parser.add_argument('--ckpt_name', type=str, default='',\n help='checkpoint name.')\n\n\n # only for bert / roberta\n parser.add_argument('--pair', action='store_true',\n help='use pair model')\n parser.add_argument('--pretrain_ckpt', default=None,\n help='bert / roberta pre-trained checkpoint')\n parser.add_argument('--cat_entity_rep', action='store_true',\n help='concatenate entity representation as sentence rep')\n\n # only for prototypical networks\n parser.add_argument('--dot', action='store_true', \n help='use dot instead of L2 distance for proto')\n\n # only for mtb\n parser.add_argument('--no_dropout', action='store_true',\n help='do not use dropout after BERT (still has dropout in BERT).')\n \n # experiment\n parser.add_argument('--mask_entity', action='store_true',\n help='mask entity names')\n parser.add_argument('--use_sgd_for_bert', action='store_true',\n help='use SGD instead of AdamW for BERT.')\n\n opt = parser.parse_args()\n trainN = opt.trainN\n N = opt.N\n K = opt.K\n Q = opt.Q\n batch_size = opt.batch_size\n model_name = opt.model\n encoder_name = opt.encoder\n max_length = opt.max_length\n \n print(\"{}-way-{}-shot Few-Shot Relation Classification\".format(N, K))\n print(\"model: {}\".format(model_name))\n print(\"encoder: {}\".format(encoder_name))\n print(\"max_length: {}\".format(max_length))\n\n ########################################################################saját\n #def load_vectors(fname):\n # fin = io.open(fname, 'r', encoding='utf-8', newline='\\n', errors='ignore')\n # n, d = map(int, fin.readline().split())\n # data = {}\n # for line in fin:\n # tokens = line.rstrip().split(' ')\n # data[tokens[0]] = map(float, tokens[1:])\n # return data\n #if encoder_name == 'fasttext':\n # try:\n # fasttext_mat=load_vectors('./pretrain/fasttext/wiki.hu.align.vec')\n # elsoszo=list(fasttext_mat['az'])\n # except:\n # raise Exception(\"Cannot find fasttext files.\")\n # sentence_encoder= FasttextSentenceEncoder(\n # fasttext_mat,\n # max_length\n # )\n if encoder_name == 'fasttext':\n sentence_encoder= FasttextSentenceEncoder(\n max_length\n )\n\n ###################################################################saját\n\n elif encoder_name == 'cnn':\n try:\n glove_mat = np.load('./pretrain/glove/glove_mat.npy')\n glove_word2id = json.load(open('./pretrain/glove/glove_word2id.json'))\n except:\n raise Exception(\"Cannot find glove files. Run glove/download_glove.sh to download glove files.\")\n sentence_encoder = CNNSentenceEncoder(\n glove_mat,\n glove_word2id,\n max_length)\n elif encoder_name == 'bert':\n pretrain_ckpt = opt.pretrain_ckpt or './pretrain/bert-base-uncased'\n if opt.pair:\n sentence_encoder = BERTPAIRSentenceEncoder(\n pretrain_ckpt,\n max_length)\n else:\n sentence_encoder = BertSentenceEncoderOWN(\n pretrain_ckpt,\n max_length,\n cat_entity_rep=opt.cat_entity_rep,\n mask_entity=opt.mask_entity)\n elif encoder_name == 'bertsimple':\n pretrain_ckpt = opt.pretrain_ckpt or './pretrain/bert-base-uncased-simple/proba/bert-base-uncased'\n sentence_encoder = BertSentenceEncoderOWN(\n pretrain_ckpt,\n max_length,\n cat_entity_rep=opt.cat_entity_rep,\n mask_entity=opt.mask_entity)\n elif encoder_name == 'bertmultiling':\n pretrain_ckpt = opt.pretrain_ckpt or './pretrain/bert-base-multilingual-uncased/bert-base-multilingual-uncased'\n sentence_encoder = BertSentenceEncoderOWN(\n pretrain_ckpt,\n max_length,\n cat_entity_rep=opt.cat_entity_rep,\n mask_entity=opt.mask_entity)\n elif encoder_name == 'roberta':\n pretrain_ckpt = opt.pretrain_ckpt or 'roberta-base'\n if opt.pair:\n sentence_encoder = RobertaPAIRSentenceEncoder(\n pretrain_ckpt,\n max_length)\n else:\n sentence_encoder = RobertaSentenceEncoder(\n pretrain_ckpt,\n max_length,\n cat_entity_rep=opt.cat_entity_rep)\n else:\n raise NotImplementedError\n #print(sentence_encoder) csak encoder információk, DATA LOADER HÍV MINDENT\n if opt.pair:\n train_data_loader = get_loader_pair(opt.train, sentence_encoder,\n N=trainN, K=K, Q=Q, na_rate=opt.na_rate, batch_size=batch_size, encoder_name=encoder_name)\n # val_data_loader = get_loader_pair(opt.val, sentence_encoder,\n # N=N, K=K, Q=Q, na_rate=opt.na_rate, batch_size=batch_size, encoder_name=encoder_name)\n test_data_loader = get_loader_pair(opt.test, sentence_encoder,\n N=N, K=K, Q=Q, na_rate=opt.na_rate, batch_size=batch_size, encoder_name=encoder_name)\n else:\n train_data_loader = get_loader(opt.train, sentence_encoder,\n N=trainN, K=K, Q=Q, na_rate=opt.na_rate, batch_size=batch_size)\n # val_data_loader = get_loader(opt.val, sentence_encoder,\n # N=N, K=K, Q=Q, na_rate=opt.na_rate, batch_size=batch_size)\n test_data_loader = get_loader(opt.test, sentence_encoder,\n N=N, K=K, Q=Q, na_rate=opt.na_rate, batch_size=batch_size)\n if opt.adv:\n adv_data_loader = get_loader_unsupervised(opt.adv, sentence_encoder,\n N=trainN, K=K, Q=Q, na_rate=opt.na_rate, batch_size=batch_size)\n #print(train_data_loader)\n if opt.optim == 'sgd':\n pytorch_optim = optim.SGD\n elif opt.optim == 'adam':\n pytorch_optim = optim.Adam\n elif opt.optim == 'adamw':\n from transformers import AdamW\n pytorch_optim = AdamW\n else:\n raise NotImplementedError\n if opt.adv:\n d = Discriminator(opt.hidden_size)\n framework = FewShotREFramework(train_data_loader, test_data_loader, adv_data_loader, adv=opt.adv, d=d)\n else:\n framework = FewShotREFramework(train_data_loader, test_data_loader)\n \n prefix = '-'.join([model_name, encoder_name, opt.train, opt.val, str(N), str(K)])\n if opt.adv is not None:\n prefix += '-adv_' + opt.adv\n if opt.na_rate != 0:\n prefix += '-na{}'.format(opt.na_rate)\n if opt.dot:\n prefix += '-dot'\n if opt.cat_entity_rep:\n prefix += '-catentity'\n if len(opt.ckpt_name) > 0:\n prefix += '-' + opt.ckpt_name\n \n if model_name == 'proto':\n model = Proto(sentence_encoder, dot=opt.dot)\n elif model_name == 'gnn':\n model = GNN(sentence_encoder, N, hidden_size=opt.hidden_size)\n elif model_name == 'snail':\n model = SNAIL(sentence_encoder, N, K, hidden_size=opt.hidden_size)\n elif model_name == 'metanet':\n model = MetaNet(N, K, sentence_encoder.embedding, max_length)\n elif model_name == 'siamese':\n model = Siamese(sentence_encoder, hidden_size=opt.hidden_size, dropout=opt.dropout)\n elif model_name == 'pair':\n model = Pair(sentence_encoder, hidden_size=opt.hidden_size)\n elif model_name == 'mtb':\n model = Mtb(sentence_encoder, use_dropout=not opt.no_dropout)\n else:\n raise NotImplementedError\n \n if not os.path.exists('checkpoint'):\n os.mkdir('checkpoint')\n ckpt = 'checkpoint/{}.pth.tar'.format(prefix)\n if opt.save_ckpt:\n ckpt = opt.save_ckpt\n \n if torch.cuda.is_available():\n model.cuda()\n\n if not opt.only_test:\n if encoder_name in ['bert', 'roberta']:\n bert_optim = True\n else:\n bert_optim = False\n\n if opt.lr == -1:\n if bert_optim:\n opt.lr = 2e-5\n else:\n opt.lr = 1e-1\n \n opt.train_iter = opt.train_iter * opt.grad_iter\n framework.train(model, prefix, batch_size, trainN, N, K, Q,\n pytorch_optim=pytorch_optim, load_ckpt=opt.load_ckpt, save_ckpt=ckpt,\n na_rate=opt.na_rate, val_step=opt.val_step, fp16=opt.fp16, pair=opt.pair, \n train_iter=opt.train_iter, val_iter=opt.val_iter, bert_optim=bert_optim, \n learning_rate=opt.lr, use_sgd_for_bert=opt.use_sgd_for_bert, grad_iter=opt.grad_iter)\n else:\n ckpt = opt.load_ckpt\n if ckpt is None:\n print(\"Warning: --load_ckpt is not specified. Will load Hugginface pre-trained checkpoint.\")\n ckpt = 'none'\n\n acc = framework.eval(model, batch_size, N, K, Q, opt.test_iter, na_rate=opt.na_rate, ckpt=ckpt, pair=opt.pair)\n print(\"RESULT: %.2f\" % (acc * 100))\n with open('results.txt', 'a') as f:\n print(ckpt, file=f)\n print('RESULT: %.2f' % (acc * 100), file=f)\n print('\\n', file=f)\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "numpy.load", "torch.cuda.is_available" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
v-pooja/vmaf
[ "6c6a7b085213a90c080510035546eceb21284008", "6c6a7b085213a90c080510035546eceb21284008" ]
[ "python/src/vmaf/core/niqe_train_test_model.py", "python/test/perf_metric_test.py" ]
[ "__copyright__ = \"Copyright 2016-2018, Netflix, Inc.\"\n__license__ = \"Apache, Version 2.0\"\n\nimport numpy as np\nimport scipy.linalg\n\nfrom vmaf.core.train_test_model import TrainTestModel, RegressorMixin\n\n\nclass NiqeTrainTestModel(TrainTestModel, RegressorMixin):\n\n TYPE = 'NIQE'\n VERSION = \"0.1\"\n\n @classmethod\n def _assert_dimension(cls, feature_names, results):\n # Override TrainTestModel._assert_dimension. allow input to be list\n # For each result, the dimension of each result[feature_name]\n # should be consistent\n assert isinstance(results[0][feature_names[0]], list)\n for result in results:\n len0 = len(result[feature_names[0]])\n for name in feature_names[1:]:\n assert len(result[name]) == len0\n\n @classmethod\n def get_xs_from_results(cls, results, indexs=None, aggregate=False):\n \"\"\"\n override TrainTestModel.get_xs_from_results by altering aggregate\n default to False\n \"\"\"\n return super(NiqeTrainTestModel, cls).get_xs_from_results(\n results, indexs, aggregate)\n\n @classmethod\n def get_xys_from_results(cls, results, indexs=None, aggregate=False):\n \"\"\"\n override TrainTestModel.get_xys_from_results by altering aggregate\n default to False\n \"\"\"\n return super(NiqeTrainTestModel, cls).get_xys_from_results(\n results, indexs, aggregate)\n\n def train(self, xys):\n \"\"\"\n override TrainTestModel.train\n \"\"\"\n self.model_type = self.TYPE\n\n assert 'label' in xys\n ys_vec = xys['label'] # for NIQE, ys never used for training\n\n # this makes sure the order of features are normalized, and each\n # dimension of xys_2d is consistent with feature_names\n feature_names = sorted(xys.keys())\n feature_names.remove('label')\n feature_names.remove('content_id')\n self.feature_names = feature_names\n\n num_samples = len(xys[feature_names[0]])\n\n xs_2d = []\n for i_sample in range(num_samples):\n xs_2d_ = np.vstack(map(\n lambda feature_name: xys[feature_name][i_sample], feature_names)\n ).T\n xs_2d.append(xs_2d_)\n xs_2d = np.vstack(xs_2d)\n\n # no normalization for NIQE\n self.norm_type = 'none'\n\n # compute NIQE\n mu = np.mean(xs_2d, axis=0)\n cov = np.cov(xs_2d.T)\n\n self.model = {'mu': mu, 'cov': cov}\n\n def predict(self, xs):\n \"\"\"\n override TrainTestModel.predict\n \"\"\"\n self._assert_trained()\n\n for name in self.feature_names:\n assert name in xs\n\n num_samples = len(xs[self.feature_names[0]])\n\n # predict per sample\n ys_label_pred = []\n for i_sample in range(num_samples):\n xs_2d_ = np.vstack(map(\n lambda feature_name: xs[feature_name][i_sample],\n self.feature_names)\n ).T\n\n # no normalization for NIQE\n\n if xs_2d_.shape[0] < 2:\n ys_label_pred_ = None # NIQE won't work for single patch\n else:\n ys_label_pred_ = self._predict(self.model, xs_2d_)\n\n ys_label_pred.append(ys_label_pred_)\n\n return {'ys_label_pred': ys_label_pred}\n\n @classmethod\n def _predict(cls, model, xs_2d):\n pop_mu = model['mu'].astype(float)\n pop_cov = model['cov'].astype(float)\n feats = xs_2d\n sample_mu = np.mean(feats, axis=0)\n sample_cov = np.cov(feats.T)\n X = sample_mu - pop_mu\n covmat = ((pop_cov+sample_cov)/2.0)\n pinvmat = scipy.linalg.pinv(covmat)\n d1 = np.sqrt(np.dot(np.dot(X, pinvmat), X))\n return d1", "import unittest\n\nimport numpy as np\nimport scipy.io\n\nfrom vmaf.config import VmafConfig\nfrom vmaf.core.perf_metric import RmsePerfMetric, SrccPerfMetric, PccPerfMetric, \\\n KendallPerfMetric, AucPerfMetric, ResolvingPowerPerfMetric\n\n__copyright__ = \"Copyright 2016-2018, Netflix, Inc.\"\n__license__ = \"Apache, Version 2.0\"\n\nclass AggrScorePerfMetricTest(unittest.TestCase):\n\n def setUp(self):\n pass\n\n def tearDown(self):\n pass\n\n def test_rmse_perf_metric(self):\n groundtruths = [1, 2, 3, 4]\n predictions = [1, 2, 3, 4]\n metric = RmsePerfMetric(groundtruths, predictions)\n result = metric.evaluate()\n self.assertAlmostEqual(result['score'], 0.0)\n\n def test_rmse_perf_metric_enable_mapping(self):\n groundtruths = np.arange(0, 1, 0.0001)\n predictions = np.arange(0, 1, 0.0001)\n metric = RmsePerfMetric(groundtruths, predictions)\n result = metric.evaluate(enable_mapping=True)\n self.assertAlmostEqual(result['score'], 0.022753642178052261, places=6)\n\n def test_rmse_perf_metric2(self):\n groundtruths = [1, 2, 3, 4]\n predictions = [1, 2, 3, 5]\n metric = RmsePerfMetric(groundtruths, predictions)\n result = metric.evaluate()\n self.assertAlmostEqual(result['score'], 0.5, places=6)\n\n def test_srcc_perf_metric(self):\n groundtruths = [1, 2, 3, 4]\n predictions = [1, 2, 3, 5]\n metric = SrccPerfMetric(groundtruths, predictions)\n result = metric.evaluate()\n self.assertAlmostEqual(result['score'], 1.0, places=6)\n\n def test_srcc_perf_metric2(self):\n groundtruths = [1, 2, 3, 4]\n predictions = [1, 2, 5, 3]\n metric = SrccPerfMetric(groundtruths, predictions)\n result = metric.evaluate()\n self.assertAlmostEqual(result['score'], 0.79999999999999993, places=6)\n\n def test_srcc_perf_metric_enable_mapping(self):\n groundtruths = [1, 2, 3, 4]\n predictions = [1, 2, 3, 5]\n metric = SrccPerfMetric(groundtruths, predictions)\n result = metric.evaluate(enable_mapping=True)\n self.assertAlmostEqual(result['score'], 1.0, places=6)\n\n def test_pcc_perf_metric(self):\n groundtruths = [1, 2, 3, 4]\n predictions = [1, 2, 3, 5]\n metric = PccPerfMetric(groundtruths, predictions)\n result = metric.evaluate()\n self.assertAlmostEqual(result['score'], 0.98270762982399085, places=6)\n\n def test_kendall_perf_metric(self):\n groundtruths = [1, 2, 3, 4]\n predictions = [1, 2, 3, 5]\n metric = KendallPerfMetric(groundtruths, predictions)\n result = metric.evaluate()\n self.assertAlmostEqual(result['score'], 1.0, places=6)\n\n def test_kendall_perf_metric2(self):\n groundtruths = [1, 2, 3, 4]\n predictions = [1, 2, 5, 3]\n metric = KendallPerfMetric(groundtruths, predictions)\n result = metric.evaluate()\n self.assertAlmostEqual(result['score'], 0.66666666666666663, places=6)\n\n def test_kendall_perf_metric_enable_mapping(self):\n groundtruths = [1, 2, 3, 4]\n predictions = [1, 2, 3, 5]\n metric = KendallPerfMetric(groundtruths, predictions)\n result = metric.evaluate(enable_mapping=True)\n self.assertAlmostEqual(result['score'], 1.0, places=6)\n\n def test_auc_perf_metric(self):\n np.random.seed(0)\n groundtruths = np.random.normal(0, 1.0, [4, 10]) + np.tile(np.array([1, 2, 3, 4]), [10, 1]).T\n predictions = [1, 2, 3, 4]\n metric = AucPerfMetric(groundtruths, predictions)\n result = metric.evaluate()\n self.assertAlmostEqual(result['score'], 0.95, places=6)\n self.assertAlmostEqual(result['AUC_BW'], 0.9166666666666666, places=6)\n self.assertAlmostEqual(result['AUC_DS'], 0.95, places=6)\n self.assertAlmostEqual(result['CC_0'], 1.0, places=6)\n self.assertAlmostEqual(result['THR'], 3.0, places=6)\n\n def test_auc_metrics_performance(self):\n mat_filepath = VmafConfig.test_resource_path('data_Toyama.mat')\n mat_dict = scipy.io.loadmat(mat_filepath)\n results = AucPerfMetric._metrics_performance(mat_dict['objScoDif'], mat_dict['signif'])\n self.assertAlmostEqual(np.mean(results['AUC_DS']), 0.69767003960902052, places=6)\n self.assertAlmostEqual(np.mean(results['AUC_BW']), 0.94454700301894534, places=6)\n self.assertAlmostEqual(np.mean(results['CC_0']), 0.88105386206276415, places=6)\n self.assertAlmostEqual(np.mean(results['THR']), 6.2392849606450556, places=6)\n\n def test_respow_perf_metric(self):\n np.random.seed(0)\n groundtruths = np.random.normal(0, 1.0, [4, 10]) + np.tile(np.array([1, 2, 3, 4]), [10, 1]).T\n predictions = [1, 2, 3, 4]\n metric = ResolvingPowerPerfMetric(groundtruths, predictions)\n result = metric.evaluate()\n self.assertAlmostEqual(result['resolving_power_95perc'], 1.2176359647113211, places=6)\n self.assertAlmostEqual(result['score'], 1.2176359647113211, places=6)\n\n def test_respow_perf_metric2(self):\n np.random.seed(0)\n groundtruths = np.random.normal(0, 10.0, [100, 30]) + np.tile(np.array(np.arange(100)), [30, 1]).T\n predictions = np.arange(100)\n metric = ResolvingPowerPerfMetric(groundtruths, predictions)\n result = metric.evaluate()\n self.assertAlmostEqual(result['score'], 9.0014569671225111, places=6)\n" ]
[ [ "numpy.dot", "numpy.cov", "numpy.mean", "numpy.vstack" ], [ "numpy.random.seed", "numpy.arange", "numpy.random.normal", "numpy.mean", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
cBioCenter/chell-viz-contact
[ "07edd56bea1693da76cf62d2ab7088193c86e9e2" ]
[ "utils/generate_raw_matrix_from_norm.py" ]
[ "import scipy.sparse as ssp\nimport numpy as np\ncounts = ssp.load_npz('./counts_norm.npz')\nnp.savetxt('./counts_norm.csv', counts.todense(), delimiter=',', fmt='%.3f')\n" ]
[ [ "scipy.sparse.load_npz" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.6", "1.10", "1.4", "1.9", "0.19", "1.5", "1.2", "1.7", "1.0", "1.3", "1.8" ], "tensorflow": [] } ]
sigeisler/grb
[ "c89e21076dc05d1edb87dfe2eff20c29ba6bd0c1", "c89e21076dc05d1edb87dfe2eff20c29ba6bd0c1", "c89e21076dc05d1edb87dfe2eff20c29ba6bd0c1" ]
[ "grb/model/torch/gcn.py", "grb/model/dgl/gat.py", "grb/model/torch/appnp.py" ]
[ "\"\"\"Torch module for GCN.\"\"\"\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom grb.utils.normalize import GCNAdjNorm\n\n\nclass GCN(nn.Module):\n r\"\"\"\n\n Description\n -----------\n Graph Convolutional Networks (`GCN <https://arxiv.org/abs/1609.02907>`__)\n\n Parameters\n ----------\n in_features : int\n Dimension of input features.\n out_features : int\n Dimension of output features.\n hidden_features : int or list of int\n Dimension of hidden features. List if multi-layer.\n n_layers : int\n Number of layers.\n layer_norm : bool, optional\n Whether to use layer normalization. Default: ``False``.\n activation : func of torch.nn.functional, optional\n Activation function. Default: ``torch.nn.functional.relu``.\n residual : bool, optional\n Whether to use residual connection. Default: ``False``.\n feat_norm : str, optional\n Type of features normalization, choose from [\"arctan\", \"tanh\", None]. Default: ``None``.\n adj_norm_func : func of utils.normalize, optional\n Function that normalizes adjacency matrix. Default: ``GCNAdjNorm``.\n dropout : float, optional\n Dropout rate during training. Default: ``0.0``.\n\n \"\"\"\n\n def __init__(self,\n in_features,\n out_features,\n hidden_features,\n n_layers,\n activation=F.relu,\n layer_norm=False,\n residual=False,\n feat_norm=None,\n adj_norm_func=GCNAdjNorm,\n dropout=0.0):\n super(GCN, self).__init__()\n self.in_features = in_features\n self.out_features = out_features\n self.feat_norm = feat_norm\n self.adj_norm_func = adj_norm_func\n if type(hidden_features) is int:\n hidden_features = [hidden_features] * (n_layers - 1)\n elif type(hidden_features) is list or type(hidden_features) is tuple:\n assert len(hidden_features) == (n_layers - 1), \"Incompatible sizes between hidden_features and n_layers.\"\n n_features = [in_features] + hidden_features + [out_features]\n\n self.layers = nn.ModuleList()\n for i in range(n_layers):\n if layer_norm:\n self.layers.append(nn.LayerNorm(n_features[i]))\n self.layers.append(GCNConv(in_features=n_features[i],\n out_features=n_features[i + 1],\n activation=activation if i != n_layers - 1 else None,\n residual=residual if i != n_layers - 1 else False,\n dropout=dropout if i != n_layers - 1 else 0.0))\n self.reset_parameters()\n\n @property\n def model_type(self):\n \"\"\"Indicate type of implementation.\"\"\"\n return \"torch\"\n\n @property\n def model_name(self):\n return \"gcn\"\n\n def reset_parameters(self):\n \"\"\"Reset parameters.\"\"\"\n for layer in self.layers:\n layer.reset_parameters()\n\n def forward(self, x, adj):\n r\"\"\"\n\n Parameters\n ----------\n x : torch.Tensor\n Tensor of input features.\n adj : torch.SparseTensor\n Sparse tensor of adjacency matrix.\n\n Returns\n -------\n x : torch.Tensor\n Output of model (logits without activation).\n\n \"\"\"\n\n for layer in self.layers:\n if isinstance(layer, nn.LayerNorm):\n x = layer(x)\n else:\n x = layer(x, adj)\n\n return x\n\n\nclass GCNGC(nn.Module):\n r\"\"\"\n\n Description\n -----------\n Graph Convolutional Networks (`GCN <https://arxiv.org/abs/1609.02907>`__)\n\n Parameters\n ----------\n in_features : int\n Dimension of input features.\n out_features : int\n Dimension of output features.\n hidden_features : int or list of int\n Dimension of hidden features. List if multi-layer.\n n_layers : int\n Number of layers.\n layer_norm : bool, optional\n Whether to use layer normalization. Default: ``False``.\n activation : func of torch.nn.functional, optional\n Activation function. Default: ``torch.nn.functional.relu``.\n residual : bool, optional\n Whether to use residual connection. Default: ``False``.\n feat_norm : str, optional\n Type of features normalization, choose from [\"arctan\", \"tanh\", None]. Default: ``None``.\n adj_norm_func : func of utils.normalize, optional\n Function that normalizes adjacency matrix. Default: ``GCNAdjNorm``.\n dropout : float, optional\n Dropout rate during training. Default: ``0.0``.\n\n \"\"\"\n\n def __init__(self,\n in_features,\n out_features,\n hidden_features,\n n_layers,\n activation=F.relu,\n layer_norm=False,\n residual=False,\n feat_norm=None,\n adj_norm_func=GCNAdjNorm,\n dropout=0.0):\n super(GCNGC, self).__init__()\n self.in_features = in_features\n self.out_features = out_features\n self.feat_norm = feat_norm\n self.adj_norm_func = adj_norm_func\n if type(hidden_features) is int:\n hidden_features = [hidden_features] * (n_layers - 1)\n elif type(hidden_features) is list or type(hidden_features) is tuple:\n assert len(hidden_features) == (n_layers - 1), \"Incompatible sizes between hidden_features and n_layers.\"\n n_features = [in_features] + hidden_features\n\n self.layers = nn.ModuleList()\n for i in range(n_layers - 1):\n if layer_norm:\n self.layers.append(nn.LayerNorm(n_features[i]))\n self.layers.append(GCNConv(in_features=n_features[i],\n out_features=n_features[i + 1],\n activation=activation,\n residual=residual,\n dropout=dropout))\n self.linear = nn.Linear(hidden_features[-1], out_features)\n self.dropout = nn.Dropout(dropout)\n self.reset_parameters()\n\n @property\n def model_type(self):\n \"\"\"Indicate type of implementation.\"\"\"\n return \"torch\"\n\n @property\n def model_name(self):\n return \"gcn\"\n\n def reset_parameters(self):\n \"\"\"Reset parameters.\"\"\"\n for layer in self.layers:\n layer.reset_parameters()\n\n def forward(self, x, adj, batch_index=None):\n r\"\"\"\n\n Parameters\n ----------\n x : torch.Tensor\n Tensor of input features.\n adj : torch.SparseTensor\n Sparse tensor of adjacency matrix.\n\n Returns\n -------\n x : torch.Tensor\n Output of model (logits without activation).\n\n \"\"\"\n\n for layer in self.layers:\n if isinstance(layer, nn.LayerNorm):\n x = layer(x)\n else:\n x = layer(x, adj)\n if batch_index is not None:\n batch_size = int(torch.max(batch_index)) + 1\n out = torch.zeros(batch_size, x.shape[1]).to(x.device)\n out = out.scatter_add_(dim=0, index=batch_index.view(-1, 1).repeat(1, x.shape[1]), src=x)\n else:\n out = torch.sum(x, dim=0)\n out = self.dropout(self.linear(out))\n\n return out\n\n\nclass GCNConv(nn.Module):\n r\"\"\"\n\n Description\n -----------\n GCN convolutional layer.\n\n Parameters\n ----------\n in_features : int\n Dimension of input features.\n out_features : int\n Dimension of output features.\n activation : func of torch.nn.functional, optional\n Activation function. Default: ``None``.\n residual : bool, optional\n Whether to use residual connection. Default: ``False``.\n dropout : float, optional\n Dropout rate during training. Default: ``0.0``.\n\n \"\"\"\n\n def __init__(self,\n in_features,\n out_features,\n activation=None,\n residual=False,\n dropout=0.0):\n super(GCNConv, self).__init__()\n self.in_features = in_features\n self.out_features = out_features\n self.linear = nn.Linear(in_features, out_features)\n\n if residual:\n self.residual = nn.Linear(in_features, out_features)\n else:\n self.residual = None\n self.activation = activation\n\n if dropout > 0.0:\n self.dropout = nn.Dropout(dropout)\n else:\n self.dropout = None\n\n self.reset_parameters()\n\n def reset_parameters(self):\n \"\"\"Reset parameters.\"\"\"\n if self.activation == F.leaky_relu:\n gain = nn.init.calculate_gain('leaky_relu')\n else:\n gain = nn.init.calculate_gain('relu')\n nn.init.xavier_normal_(self.linear.weight, gain=gain)\n\n def forward(self, x, adj):\n r\"\"\"\n\n Parameters\n ----------\n x : torch.Tensor\n Tensor of input features.\n adj : torch.SparseTensor\n Sparse tensor of adjacency matrix.\n\n Returns\n -------\n x : torch.Tensor\n Output of layer.\n\n \"\"\"\n\n x = self.linear(x)\n x = torch.sparse.mm(adj, x)\n if self.activation is not None:\n x = self.activation(x)\n if self.residual is not None:\n x = x + self.residual(x)\n if self.dropout is not None:\n x = self.dropout(x)\n\n return x\n", "import dgl\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom dgl.nn.pytorch import GATConv\n\nfrom grb.utils.normalize import GCNAdjNorm\n\n\nclass GAT(nn.Module):\n r\"\"\"\n\n Description\n -----------\n Graph Attention Networks (`GAT <https://arxiv.org/abs/1710.10903>`__)\n\n Parameters\n ----------\n in_features : int\n Dimension of input features.\n out_features : int\n Dimension of output features.\n hidden_features : int or list of int\n Dimension of hidden features. List if multi-layer.\n n_layers : int\n Number of layers.\n layer_norm : bool, optional\n Whether to use layer normalization. Default: ``False``.\n activation : func of torch.nn.functional, optional\n Activation function. Default: ``torch.nn.functional.leaky_relu``.\n feat_norm : str, optional\n Type of features normalization, choose from [\"arctan\", \"tanh\", None]. Default: ``None``.\n adj_norm_func : func of utils.normalize, optional\n Function that normalizes adjacency matrix. Default: ``None``.\n feat_dropout : float, optional\n Dropout rate for input features. Default: ``0.0``.\n attn_dropout : float, optional\n Dropout rate for attention. Default: ``0.0``.\n residual : bool, optional\n Whether to use residual connection. Default: ``False``.\n dropout : float, optional\n Dropout rate during training. Default: ``0.0``.\n\n \"\"\"\n def __init__(self,\n in_features,\n out_features,\n hidden_features,\n n_layers,\n n_heads,\n activation=F.leaky_relu,\n layer_norm=False,\n feat_norm=None,\n adj_norm_func=None,\n feat_dropout=0.0,\n attn_dropout=0.0,\n residual=False,\n dropout=0.0):\n super(GAT, self).__init__()\n self.in_features = in_features\n self.out_features = out_features\n self.feat_norm = feat_norm\n self.adj_norm_func = adj_norm_func\n if type(hidden_features) is int:\n hidden_features = [hidden_features] * (n_layers - 1)\n elif type(hidden_features) is list or type(hidden_features) is tuple:\n assert len(hidden_features) == (n_layers - 1), \"Incompatible sizes between hidden_features and n_layers.\"\n n_features = [in_features] + hidden_features + [out_features]\n\n self.layers = nn.ModuleList()\n for i in range(n_layers):\n if layer_norm:\n if i == 0:\n self.layers.append(nn.LayerNorm(n_features[i]))\n else:\n self.layers.append(nn.LayerNorm(n_features[i] * n_heads))\n self.layers.append(GATConv(in_feats=n_features[i] * n_heads if i != 0 else n_features[i],\n out_feats=n_features[i + 1],\n num_heads=n_heads if i != n_layers - 1 else 1,\n feat_drop=feat_dropout if i != n_layers - 1 else 0.0,\n attn_drop=attn_dropout if i != n_layers - 1 else 0.0,\n residual=residual if i != n_layers - 1 else False,\n activation=activation if i != n_layers - 1 else None))\n if dropout > 0.0:\n self.dropout = nn.Dropout(dropout)\n else:\n self.dropout = None\n\n @property\n def model_type(self):\n return \"dgl\"\n\n @property\n def model_name(self):\n return \"gat\"\n\n def forward(self, x, adj):\n r\"\"\"\n\n Parameters\n ----------\n x : torch.Tensor\n Tensor of input features.\n adj : torch.SparseTensor\n Sparse tensor of adjacency matrix.\n\n Returns\n -------\n x : torch.Tensor\n Output of layer.\n\n \"\"\"\n\n graph = dgl.from_scipy(adj).to(x.device)\n graph = dgl.remove_self_loop(graph)\n graph = dgl.add_self_loop(graph)\n graph.ndata['features'] = x\n\n for i, layer in enumerate(self.layers):\n if isinstance(layer, nn.LayerNorm):\n x = layer(x)\n else:\n x = layer(graph, x).flatten(1)\n if i != len(self.layers) - 1:\n if self.dropout is not None:\n x = self.dropout(x)\n\n return x\n", "\"\"\"Torch module for APPNP.\"\"\"\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom grb.utils.normalize import GCNAdjNorm\n\n\nclass APPNP(nn.Module):\n r\"\"\"\n\n Description\n -----------\n Approximated Personalized Propagation of Neural Predictions (`APPNP <https://arxiv.org/abs/1810.05997>`__)\n\n Parameters\n ----------\n in_features : int\n Dimension of input features.\n out_features : int\n Dimension of output features.\n hidden_features : int or list of int\n Dimension of hidden features. List if multi-layer.\n n_layers : int\n Number of layers.\n layer_norm : bool, optional\n Whether to use layer normalization. Default: ``False``.\n activation : func of torch.nn.functional, optional\n Activation function. Default: ``torch.nn.functional.relu``.\n feat_norm : str, optional\n Type of features normalization, choose from [\"arctan\", \"tanh\", None]. Default: ``None``.\n adj_norm_func : func of utils.normalize, optional\n Function that normalizes adjacency matrix. Default: ``GCNAdjNorm``.\n edge_drop : float, optional\n Rate of edge drop.\n alpha : float, optional\n Hyper-parameter, refer to original paper. Default: ``0.01``.\n k : int, optional\n Hyper-parameter, refer to original paper. Default: ``10``.\n dropout : float, optional\n Dropout rate during training. Default: ``0.0``.\n\n \"\"\"\n\n def __init__(self,\n in_features,\n out_features,\n hidden_features,\n n_layers,\n layer_norm=False,\n activation=F.relu,\n edge_drop=0.0,\n alpha=0.01,\n k=10,\n feat_norm=None,\n adj_norm_func=GCNAdjNorm,\n dropout=0.0):\n super(APPNP, self).__init__()\n self.in_features = in_features\n self.out_features = out_features\n self.feat_norm = feat_norm\n self.adj_norm_func = adj_norm_func\n if type(hidden_features) is int:\n hidden_features = [hidden_features] * (n_layers - 1)\n elif type(hidden_features) is list or type(hidden_features) is tuple:\n assert len(hidden_features) == (n_layers - 1), \"Incompatible sizes between hidden_features and n_layers.\"\n n_features = [in_features] + hidden_features + [out_features]\n\n self.layers = nn.ModuleList()\n for i in range(n_layers):\n if layer_norm:\n self.layers.append(nn.LayerNorm(n_features[i]))\n self.layers.append(nn.Linear(n_features[i], n_features[i + 1]))\n self.alpha = alpha\n self.k = k\n self.activation = activation\n if edge_drop > 0.0:\n self.edge_dropout = SparseEdgeDrop(edge_drop)\n else:\n self.edge_dropout = None\n if dropout > 0.0:\n self.dropout = nn.Dropout(dropout)\n else:\n self.dropout = None\n\n @property\n def model_type(self):\n \"\"\"Indicate type of implementation.\"\"\"\n return \"torch\"\n\n @property\n def model_name(self):\n return \"appnp\"\n\n def reset_parameters(self):\n \"\"\"Reset parameters.\"\"\"\n for layer in self.layers:\n layer.reset_parameters()\n\n def forward(self, x, adj):\n r\"\"\"\n\n Parameters\n ----------\n x : torch.Tensor\n Tensor of input features.\n adj : torch.SparseTensor\n Sparse tensor of adjacency matrix.\n\n Returns\n -------\n x : torch.Tensor\n Output of model (logits without activation).\n\n \"\"\"\n\n for layer in self.layers:\n if isinstance(layer, nn.LayerNorm):\n x = layer(x)\n else:\n x = layer(x)\n x = self.activation(x)\n if self.dropout is not None:\n x = self.dropout(x)\n for i in range(self.k):\n if self.edge_dropout is not None and self.training:\n adj = self.edge_dropout(adj)\n x = (1 - self.alpha) * torch.spmm(adj, x) + self.alpha * x\n\n return x\n\n\nclass SparseEdgeDrop(nn.Module):\n r\"\"\"\n\n Description\n -----------\n Sparse implementation of edge drop.\n\n Parameters\n ----------\n edge_drop : float\n Rate of edge drop.\n\n \"\"\"\n\n def __init__(self, edge_drop):\n super(SparseEdgeDrop, self).__init__()\n self.edge_drop = edge_drop\n\n def forward(self, adj):\n \"\"\"Sparse edge drop\"\"\"\n mask = ((torch.rand(adj._values().size()) + self.edge_drop) > 1.0)\n rc = adj._indices()\n val = adj._values().clone()\n val[mask] = 0.0\n\n return torch.sparse.FloatTensor(rc, val)\n" ]
[ [ "torch.nn.init.calculate_gain", "torch.nn.Dropout", "torch.max", "torch.zeros", "torch.nn.ModuleList", "torch.nn.init.xavier_normal_", "torch.sparse.mm", "torch.sum", "torch.nn.LayerNorm", "torch.nn.Linear" ], [ "torch.nn.Dropout", "torch.nn.ModuleList", "torch.nn.LayerNorm" ], [ "torch.nn.Dropout", "torch.nn.ModuleList", "torch.nn.LayerNorm", "torch.nn.Linear", "torch.sparse.FloatTensor", "torch.spmm" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
gucci-j/intro-deep-learning-keras
[ "ef79eb44b6080918067fe6fc38e0b79ecf88189c" ]
[ "chapter6/compare_weight_decay.py" ]
[ "from keras import Model, optimizers, initializers, regularizers\nfrom keras.layers import Input, Dense, Activation\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.utils import to_categorical\nfrom keras.datasets import fashion_mnist\nimport matplotlib.pyplot as plt\n\n# パラメータ + ハイパーパラメータ\nimg_shape = (28 * 28, )\nhidden_dim = 100\noutput_dim = 10\nbatch_size = 128\nlearning_rate = 0.01\nepochs = 15\n_init = initializers.RandomNormal(mean=0.0, stddev=0.01, seed=None)\n_wd = regularizers.l2(0.1)\n\ndef build_model(wd):\n # モデルを定義する\n if wd is True:\n _input = Input(shape=img_shape)\n _hidden = Dense(hidden_dim, kernel_initializer=_init, kernel_regularizer=_wd)(_input)\n _hidden = BatchNormalization()(_hidden)\n _hidden = Activation('relu')(_hidden)\n _hidden = Dense(hidden_dim, kernel_initializer=_init, kernel_regularizer=_wd)(_hidden)\n _hidden = BatchNormalization()(_hidden)\n _hidden = Activation('relu')(_hidden)\n _hidden = Dense(hidden_dim, kernel_initializer=_init, kernel_regularizer=_wd)(_hidden)\n _hidden = BatchNormalization()(_hidden)\n _hidden = Activation('relu')(_hidden)\n _hidden = Dense(hidden_dim, kernel_initializer=_init, kernel_regularizer=_wd)(_hidden)\n _hidden = BatchNormalization()(_hidden)\n _hidden = Activation('relu')(_hidden)\n _output = Dense(output_dim, activation='softmax')(_hidden)\n\n model = Model(inputs=_input, outputs=_output)\n return model\n\n else:\n _input = Input(shape=img_shape)\n _hidden = Dense(hidden_dim, kernel_initializer=_init)(_input)\n _hidden = BatchNormalization()(_hidden)\n _hidden = Activation('relu')(_hidden)\n _hidden = Dense(hidden_dim, kernel_initializer=_init)(_hidden)\n _hidden = BatchNormalization()(_hidden)\n _hidden = Activation('relu')(_hidden)\n _hidden = Dense(hidden_dim, kernel_initializer=_init)(_hidden)\n _hidden = BatchNormalization()(_hidden)\n _hidden = Activation('relu')(_hidden)\n _hidden = Dense(hidden_dim, kernel_initializer=_init)(_hidden)\n _hidden = BatchNormalization()(_hidden)\n _hidden = Activation('relu')(_hidden)\n _output = Dense(output_dim, activation='softmax')(_hidden)\n\n model = Model(inputs=_input, outputs=_output)\n return model\n\n\n\ndef load_data():\n # データを読み込む\n (x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()\n x_train = x_train[:30000]\n y_train = y_train[:30000]\n x_train = x_train.reshape(30000, 784)\n x_test = x_test.reshape(10000, 784)\n x_train = x_train.astype('float') / 255.\n x_test = x_test.astype('float') / 255.\n print(f'Before: {y_train.shape}')\n print(f'y_train[0]: {y_train[0]}')\n y_train = to_categorical(y_train, num_classes=output_dim)\n print(f'After: {y_train.shape}')\n print(f'y_train[0]: {y_train[0]}')\n y_test = to_categorical(y_test, num_classes=output_dim)\n\n return x_train, y_train, x_test, y_test\n\n\ndef set_flag():\n # バッチ正規化フラグの定義\n flag = {}\n flag['With Weight decay'] = True\n flag['Without Weight decay'] = False\n\n return flag\n\n\ndef main():\n x_train, y_train, x_test, y_test = load_data()\n flag = set_flag()\n\n results = {}\n for key in flag.keys():\n print(f'---Now running: {key} model---')\n model = build_model(flag[key])\n model.compile(optimizer=optimizers.SGD(lr=learning_rate), loss='categorical_crossentropy', metrics=['accuracy'])\n results[key] = model.fit(x=x_train, y=y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_data=(x_test, y_test))\n\n plt.figure()\n for key in flag.keys():\n acc = results[key].history['acc']\n val_acc = results[key].history['val_acc']\n plt.plot(range(1, epochs+1), acc, marker='.', label='train')\n plt.plot(range(1, epochs+1), val_acc, marker='.', label='test')\n plt.legend(loc='best', fontsize=10)\n plt.grid()\n plt.xlabel('Epochs')\n plt.ylabel('Accuracy')\n plt.savefig('acc_' + key + '.png')\n plt.clf()\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "matplotlib.pyplot.legend", "matplotlib.pyplot.figure", "matplotlib.pyplot.savefig", "matplotlib.pyplot.clf", "matplotlib.pyplot.grid", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.ylabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
vuanvin/pytorch
[ "9267fd8d7395074001ad7cf2a8f28082dbff6b0b", "9267fd8d7395074001ad7cf2a8f28082dbff6b0b", "9267fd8d7395074001ad7cf2a8f28082dbff6b0b", "9267fd8d7395074001ad7cf2a8f28082dbff6b0b" ]
[ "test/distributed/fsdp/test_fsdp_checkpoint.py", "torch/ao/quantization/quantize.py", "test/quantization/core/test_quantized_module.py", "torch/nn/quantizable/modules/activation.py" ]
[ "# Owner(s): [\"oncall: distributed\"]\n\nimport contextlib\nfrom copy import deepcopy\nfrom functools import partial\n\nimport torch\nimport torch.nn as nn\nfrom torch.distributed._fsdp.fully_sharded_data_parallel import (\n FullyShardedDataParallel as FSDP,\n CPUOffload,\n)\nfrom torch.distributed.algorithms._checkpoint._checkpoint_wrapper import (\n checkpoint_wrapper,\n)\nfrom torch.testing._internal.common_distributed import (\n skip_if_lt_x_gpu,\n)\nfrom torch.testing._internal.common_fsdp import (\n FSDPTest,\n _maybe_wrap_fsdp,\n)\nfrom torch.testing._internal.common_utils import (\n run_tests,\n parametrize,\n instantiate_parametrized_tests,\n)\nfrom torch.utils.checkpoint import checkpoint\n\n\nclass TestFSDPCheckpoint(FSDPTest):\n class SequentialModule(nn.Module):\n def __init__(\n self,\n checkpoint_layer=False,\n offload_activations=False,\n wrap_fsdp=False,\n *fsdp_args,\n **fsdp_kwargs,\n ):\n torch.manual_seed(0)\n torch.cuda.manual_seed(0)\n super().__init__()\n l1 = nn.Linear(3, 3).cuda()\n l2 = nn.Linear(3, 3).cuda()\n l3 = nn.Linear(3, 3).cuda()\n\n if checkpoint_layer:\n ckpt_wrapper = partial(\n checkpoint_wrapper, offload_to_cpu=offload_activations\n )\n\n l1 = ckpt_wrapper(l1)\n l2 = ckpt_wrapper(l2)\n l3 = ckpt_wrapper(l3)\n\n fsdp_wrapper = partial(\n _maybe_wrap_fsdp, wrap_fsdp=wrap_fsdp, *fsdp_args, **fsdp_kwargs\n )\n self.ffn = nn.Sequential(\n fsdp_wrapper(l1),\n fsdp_wrapper(l2),\n fsdp_wrapper(l3),\n )\n\n def forward(self, x):\n return self.ffn(x)\n\n def _verify_parity(self, losses, outputs, models):\n assert losses\n assert outputs\n assert models\n\n for (l, o) in zip(losses[1:], outputs[1:]):\n self.assertEqual(losses[0], l)\n self.assertEqual(outputs[0], o)\n\n # Verify grads\n ref_model = models[0]\n ref_grads = [p.grad for p in ref_model.parameters()]\n for m in models[1:]:\n grads = [p.grad for p in m.parameters()]\n for ref_g, g in zip(ref_grads, grads):\n self.assertEqual(ref_g, g)\n\n @skip_if_lt_x_gpu(2)\n @parametrize(\n \"cpu_offload\",\n [CPUOffload(offload_params=True), CPUOffload(offload_params=False)],\n )\n @parametrize(\"offload_activations\", [True, False])\n def test_checkpoint_fsdp_wrapping(self, cpu_offload, offload_activations):\n # Test checkpoint(FSDP(layer1), FSDP(layer2), ....)\n ckpt_sequential_wrapped_fsdp = checkpoint_wrapper(\n TestFSDPCheckpoint.SequentialModule(\n wrap_fsdp=True, cpu_offload=cpu_offload\n ),\n offload_to_cpu=offload_activations,\n )\n # Test FSDP(checkpoint(layer1)), FSDP(checkpoint(layer2)), ....\n inner_ckpt = TestFSDPCheckpoint.SequentialModule(\n checkpoint_layer=True,\n offload_activations=offload_activations,\n wrap_fsdp=True,\n cpu_offload=cpu_offload,\n )\n\n baseline = TestFSDPCheckpoint.SequentialModule(\n wrap_fsdp=True, cpu_offload=cpu_offload\n )\n\n # note that reentrant-based checkpointing requires inputs to have grad\n # flag set.\n inp = torch.randn(10, 3, device=torch.cuda.current_device(), requires_grad=True)\n\n models = [ckpt_sequential_wrapped_fsdp, inner_ckpt, baseline]\n\n offload_to_cpu_event = \"Memcpy DtoH\"\n\n for i in range(2):\n losses = []\n outputs = []\n for m in models:\n check_offload = m != baseline and i == 0 and offload_activations\n profiler_ctx = (\n torch.profiler.profile(use_cuda=True)\n if check_offload\n else contextlib.suppress()\n )\n with profiler_ctx as prof:\n out = m(inp)\n\n if check_offload:\n event_names = [event.name for event in prof.events()]\n offload_occured = any(\n offload_to_cpu_event in name for name in event_names\n )\n self.assertTrue(offload_occured)\n loss = out.sum()\n loss.backward()\n losses.append(loss)\n outputs.append(out)\n\n self._verify_parity(losses, outputs, models)\n\n @skip_if_lt_x_gpu(2)\n @parametrize(\n \"cpu_offload\",\n [CPUOffload(offload_params=True), CPUOffload(offload_params=False)],\n )\n @parametrize(\"offload_activations\", [True, False])\n def test_basic_checkpoint_end_to_end(self, cpu_offload, offload_activations):\n seq = TestFSDPCheckpoint.SequentialModule().to(torch.cuda.current_device())\n # Runs FSDP with no checkpointing\n fsdp_only_seq = FSDP(deepcopy(seq), cpu_offload=cpu_offload)\n # Runs checkpoint-wrapped FSDP\n checkpointed_fsdp = checkpoint_wrapper(\n FSDP(deepcopy(seq), cpu_offload=cpu_offload),\n offload_to_cpu=offload_activations,\n )\n # Runs FSDP-wrapped checkpointed module\n fsdp_wrapped_checkpoint = FSDP(\n checkpoint_wrapper(deepcopy(seq), offload_to_cpu=offload_activations),\n cpu_offload=cpu_offload,\n )\n # Runs FSDP with manual calls to checkpoint.\n fsdp_call_checkpoint = FSDP(deepcopy(seq), cpu_offload=cpu_offload)\n # note that reentrant-based checkpointing requires inputs to have grad\n # flag set.\n\n inp = torch.randn(10, 3, device=torch.cuda.current_device(), requires_grad=True)\n\n models = [\n fsdp_only_seq,\n checkpointed_fsdp,\n fsdp_wrapped_checkpoint,\n fsdp_call_checkpoint,\n ]\n\n offload_to_cpu_event = \"Memcpy DtoH\"\n\n for i in range(6):\n losses = []\n outputs = []\n for m in models:\n check_offload = m != fsdp_only_seq and i == 0 and offload_activations\n profiler_ctx = (\n torch.profiler.profile(use_cuda=True)\n if check_offload\n else contextlib.suppress()\n )\n with profiler_ctx as prof:\n if m == fsdp_call_checkpoint:\n offload_ctx = (\n torch.autograd.graph.save_on_cpu(pin_memory=True)\n if offload_activations\n else contextlib.suppress()\n )\n with offload_ctx:\n out = checkpoint(m, inp)\n else:\n out = m(inp)\n\n if check_offload:\n event_names = [event.name for event in prof.events()]\n offload_occured = any(\n offload_to_cpu_event in name for name in event_names\n )\n self.assertTrue(offload_occured)\n loss = out.sum()\n loss.backward()\n losses.append(loss)\n outputs.append(out)\n\n self._verify_parity(losses, outputs, models)\n\ninstantiate_parametrized_tests(TestFSDPCheckpoint)\n\nif __name__ == \"__main__\":\n run_tests()\n", "import copy\nimport itertools\nimport warnings\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.quantized as nnq\nfrom torch.nn.intrinsic import _FusedModule\n\nfrom torch.ao.quantization.quantization_mappings import (\n get_default_dynamic_quant_module_mappings,\n get_default_static_quant_module_mappings,\n get_default_qat_module_mappings,\n get_default_qconfig_propagation_list,\n no_observer_set,\n _has_special_act_post_process,\n _get_special_act_post_process,\n)\n\nfrom torch.ao.quantization.stubs import DeQuantStub, QuantWrapper\nfrom torch.ao.quantization.qconfig import (\n add_module_to_qconfig_obs_ctr,\n default_dynamic_qconfig,\n float16_dynamic_qconfig,\n float_qparams_weight_only_qconfig,\n float_qparams_weight_only_qconfig_4bit,\n activation_is_memoryless)\n\ndef is_activation_post_process(module):\n return (isinstance(module, torch.ao.quantization.ObserverBase) or\n isinstance(module, torch.ao.quantization.FakeQuantizeBase))\n\ndef _propagate_qconfig_helper(module, qconfig_dict, allow_list=None,\n qconfig_parent=None, prefix=''):\n r\"\"\"This is a helper function for `propagate_qconfig_`\n\n Args:\n module: input module\n qconfig_dict: dictionary that maps from name of submodule to quantization\n configuration\n allow_list: list of quantizable modules\n qconfig_parent: quantization config of parent module, we will fallback to\n this config when there is no specified config for current\n module\n prefix: corresponding prefix of the current module, used as key in\n qconfig_dict\n\n Return:\n None, module is modified inplace with qconfig attached\n \"\"\"\n # TODO: Add test\n if allow_list is None:\n allow_list = get_default_qconfig_propagation_list()\n\n module_qconfig = qconfig_dict.get(type(module), qconfig_parent)\n module_qconfig = qconfig_dict.get(prefix, module_qconfig)\n module_qconfig = getattr(module, 'qconfig', module_qconfig)\n\n torch.ao.quantization.qconfig.assert_valid_qconfig(module_qconfig, module)\n\n qconfig_with_device_check = add_module_to_qconfig_obs_ctr(module_qconfig, module)\n module.qconfig = qconfig_with_device_check\n\n for name, child in module.named_children():\n module_prefix = prefix + '.' + name if prefix else name\n _propagate_qconfig_helper(child, qconfig_dict, allow_list,\n qconfig_with_device_check, module_prefix)\n\ndef propagate_qconfig_(module, qconfig_dict=None, allow_list=None):\n r\"\"\"Propagate qconfig through the module hierarchy and assign `qconfig`\n attribute on each leaf module\n\n Args:\n module: input module\n qconfig_dict: dictionary that maps from name or type of submodule to\n quantization configuration, qconfig applies to all submodules of a\n given module unless qconfig for the submodules are specified (when\n the submodule already has qconfig attribute)\n allow_list: a set that lists out allowable modules to be propagated with qconfig\n\n Return:\n None, module is modified inplace with qconfig attached\n \"\"\"\n if qconfig_dict is None:\n qconfig_dict = {}\n _propagate_qconfig_helper(module, qconfig_dict, allow_list)\n\ndef _observer_forward_hook(self, input, output):\n r\"\"\"Forward hook that calls observer on the output\n \"\"\"\n return self.activation_post_process(output)\n\ndef _observer_forward_pre_hook(self, input):\n r\"\"\"Forward pre hook that calls observer on the output\n \"\"\"\n return self.activation_post_process(input[0])\n\ndef register_activation_post_process_hook(module, pre_hook=False):\n assert hasattr(module, 'activation_post_process'), \\\n 'Expect activation_post_process attribute already attached to the module'\n if pre_hook:\n handle = module.register_forward_pre_hook(_observer_forward_pre_hook)\n module._forward_pre_hooks.move_to_end(handle.id, last=False)\n else:\n handle = module.register_forward_hook(_observer_forward_hook)\n module._forward_hooks.move_to_end(handle.id, last=False)\n\ndef add_observer_(module, qconfig_propagation_list=None, non_leaf_module_list=None, device=None, custom_module_class_mapping=None):\n r\"\"\"Add observer for the leaf child of the module.\n\n This function insert observer module to all leaf child module that\n has a valid qconfig attribute.\n\n Args:\n module: input module with qconfig attributes for all the leaf modules that we want to quantize\n device: parent device, if any\n non_leaf_module_list: list of non-leaf modules we want to add observer\n\n Return:\n None, module is modified inplace with added observer modules and forward_hooks\n \"\"\"\n if qconfig_propagation_list is None:\n qconfig_propagation_list = get_default_qconfig_propagation_list()\n\n if custom_module_class_mapping is None:\n custom_module_class_mapping = {}\n\n # respect device affinity when adding observers\n if device is None:\n devices = get_unique_devices_(module)\n assert len(devices) <= 1, (\n \"add_observer_ only works with cpu or single-device CUDA modules, \"\n \"but got devices {}\".format(devices)\n )\n device = next(iter(devices)) if len(devices) > 0 else None\n\n def get_activation_post_process(qconfig, device, special_act_post_process=None):\n activation = qconfig.activation() if special_act_post_process is None else special_act_post_process()\n if device is not None:\n activation.to(device)\n return activation\n\n def needs_observation(m):\n return hasattr(m, 'qconfig') and m.qconfig is not None\n\n def insert_activation_post_process(m, special_act_post_process=None):\n \"\"\" Adds an activation post process module and register\n a pre or post hook that calls the module\n \"\"\"\n # We don't insert observer/fake_quantize for DeQuantStub\n if needs_observation(m) and not isinstance(m, DeQuantStub):\n # observer and hook will be gone after we swap the module\n m.add_module('activation_post_process', get_activation_post_process(\n m.qconfig, device, special_act_post_process))\n # Register observer as the first entry in the hook list\n # All post forward hooks are preserved and will be executed after the observer before convert\n register_activation_post_process_hook(m, pre_hook=activation_is_memoryless(m.qconfig))\n\n for name, child in module.named_children():\n if type(child) in [nnq.FloatFunctional, nnq.QFunctional]:\n if needs_observation(child):\n child.activation_post_process = get_activation_post_process(child.qconfig, device)\n elif isinstance(child, _FusedModule):\n # activation_post_process are now added directly to nn.Sequentail/_FusedModule\n if needs_observation(child):\n insert_activation_post_process(child)\n elif _has_special_act_post_process(child):\n special_act_post_process = _get_special_act_post_process(child)\n insert_activation_post_process(child, special_act_post_process)\n elif non_leaf_module_list is not None and type(child) in non_leaf_module_list:\n if needs_observation(child):\n insert_activation_post_process(child)\n elif needs_observation(child) and type(child) in custom_module_class_mapping:\n observed_child = custom_module_class_mapping[type(child)].from_float(child)\n setattr(module, name, observed_child)\n # TODO: These are the modules that cannot be observed\n # Once there are more, we should move them to a separate list\n if custom_module_class_mapping[type(child)] not in no_observer_set():\n insert_activation_post_process(observed_child)\n else:\n add_observer_(child, qconfig_propagation_list, non_leaf_module_list, device, custom_module_class_mapping)\n\n # Insert observers only for leaf nodes, note that this observer is for\n # the output of the module, for input QuantStub will observe them\n if len(module._modules) == 0 and not isinstance(module, torch.nn.Sequential) \\\n and type(module) in qconfig_propagation_list:\n insert_activation_post_process(module)\n\ndef get_unique_devices_(module):\n return {p.device for p in module.parameters()} | \\\n {p.device for p in module.buffers()}\n\ndef add_quant_dequant(module):\n r\"\"\"Wrap the leaf child module in QuantWrapper if it has a valid qconfig\n Note that this function will modify the children of module inplace and it\n can return a new module which wraps the input module as well.\n\n Args:\n module: input module with qconfig attributes for all the leaf modules\n that we want to quantize\n\n Return:\n Either the inplace modified module with submodules wrapped in\n `QuantWrapper` based on qconfig or a new `QuantWrapper` module which\n wraps the input module, the latter case only happens when the input\n module is a leaf module and we want to quantize it.\n \"\"\"\n if len(module._modules) == 0 and hasattr(module, 'qconfig') and module.qconfig:\n return QuantWrapper(module)\n\n for name, child in module.named_children():\n module._modules[name] = add_quant_dequant(child)\n return module\n\ndef prepare(model, inplace=False, allow_list=None,\n observer_non_leaf_module_list=None,\n prepare_custom_config_dict=None):\n r\"\"\"Prepares a copy of the model for quantization calibration or quantization-aware training.\n\n Quantization configuration should be assigned preemptively\n to individual submodules in `.qconfig` attribute.\n\n The model will be attached with observer or fake quant modules, and qconfig\n will be propagated.\n\n Args:\n `model`: input model to be modified in-place\n `inplace`: carry out model transformations in-place, the original module is mutated\n `allow_list`: list of quantizable modules\n `observer_non_leaf_module_list`: list of non-leaf modules we want to add observer\n `prepare_custom_config_dict`: customization configuration dictionary for prepare function\n\n .. code-block:: python\n\n # Example of prepare_custom_config_dict:\n prepare_custom_config_dict = {\n # user will manually define the corresponding observed\n # module class which has a from_float class method that converts\n # float custom module to observed custom module\n \"float_to_observed_custom_module_class\": {\n CustomModule: ObservedCustomModule\n }\n }\n\n \"\"\"\n torch._C._log_api_usage_once(\"quantization_api.quantize.prepare\")\n if prepare_custom_config_dict is None:\n prepare_custom_config_dict = {}\n custom_module_class_mapping = prepare_custom_config_dict.get(\"float_to_observed_custom_module_class\", {})\n\n if not inplace:\n model = copy.deepcopy(model)\n\n # TODO: remove allow_list\n qconfig_propagation_list = allow_list\n if qconfig_propagation_list is None:\n qconfig_propagation_list = get_default_qconfig_propagation_list()\n propagate_qconfig_(model, qconfig_dict=None)\n\n # sanity check common API misusage\n if not any(hasattr(m, 'qconfig') and m.qconfig for m in model.modules()):\n warnings.warn(\"None of the submodule got qconfig applied. Make sure you \"\n \"passed correct configuration through `qconfig_dict` or \"\n \"by assigning the `.qconfig` attribute directly on submodules\")\n\n add_observer_(\n model, qconfig_propagation_list, observer_non_leaf_module_list,\n custom_module_class_mapping=custom_module_class_mapping)\n return model\n\ndef _remove_activation_post_process(module):\n # TODO: maybe we should change activation_post_process to _activation_post_process\n # to prevent it from being used by user\n if hasattr(module, 'activation_post_process') and \\\n is_activation_post_process(module.activation_post_process):\n delattr(module, 'activation_post_process')\n\n # remove activation_post_proceess pre and post hooks\n def remove_hooks(pre_hook=False):\n hook_map = module._forward_pre_hooks if pre_hook else module._forward_hooks\n observer_hook = _observer_forward_pre_hook if pre_hook else _observer_forward_hook\n handle_ids_to_remove = set()\n for handle_id, hook_fn in hook_map.items():\n if hook_fn is observer_hook:\n handle_ids_to_remove.add(handle_id)\n for handle_id in handle_ids_to_remove:\n hook_map.pop(handle_id)\n\n remove_hooks(pre_hook=True)\n remove_hooks(pre_hook=False)\n\n# TODO: rename to something more general\ndef _remove_qconfig(module):\n r\"\"\"Clean up the qconfig left in the module so that new qconfig can be\n propagated.\n\n Args:\n module: module to be cleaned up\n \"\"\"\n for child in module.children():\n _remove_qconfig(child)\n\n if hasattr(module, \"qconfig\"):\n del module.qconfig\n\n _remove_activation_post_process(module)\n\ndef quantize(model, run_fn, run_args, mapping=None, inplace=False):\n r\"\"\"Quantize the input float model with post training static quantization.\n\n First it will prepare the model for calibration, then it calls\n `run_fn` which will run the calibration step, after that we will\n convert the model to a quantized model.\n\n Args:\n model: input float model\n run_fn: a calibration function for calibrating the prepared model\n run_args: positional arguments for `run_fn`\n inplace: carry out model transformations in-place, the original module is mutated\n mapping: correspondence between original module types and quantized counterparts\n\n Return:\n Quantized model.\n \"\"\"\n torch._C._log_api_usage_once(\"quantization_api.quantize.quantize\")\n if mapping is None:\n mapping = get_default_static_quant_module_mappings()\n if not inplace:\n model = copy.deepcopy(model)\n model.eval()\n prepare(model, inplace=True)\n run_fn(model, *run_args)\n convert(model, mapping, inplace=True)\n return model\n\ndef quantize_dynamic(model, qconfig_spec=None, dtype=torch.qint8,\n mapping=None, inplace=False):\n r\"\"\"Converts a float model to dynamic (i.e. weights-only) quantized model.\n\n Replaces specified modules with dynamic weight-only quantized versions and output the quantized model.\n\n For simplest usage provide `dtype` argument that can be float16 or qint8. Weight-only quantization\n by default is performed for layers with large weights size - i.e. Linear and RNN variants.\n\n Fine grained control is possible with `qconfig` and `mapping` that act similarly to `quantize()`.\n If `qconfig` is provided, the `dtype` argument is ignored.\n\n Args:\n model: input model\n qconfig_spec: Either:\n\n - A dictionary that maps from name or type of submodule to quantization\n configuration, qconfig applies to all submodules of a given\n module unless qconfig for the submodules are specified (when the\n submodule already has qconfig attribute). Entries in the dictionary\n need to be QConfig instances.\n\n - A set of types and/or submodule names to apply dynamic quantization to,\n in which case the `dtype` argument is used to specify the bit-width\n\n inplace: carry out model transformations in-place, the original module is mutated\n mapping: maps type of a submodule to a type of corresponding dynamically quantized version\n with which the submodule needs to be replaced\n\n \"\"\"\n torch._C._log_api_usage_once(\"quantization_api.quantize.quantize_dynamic\")\n if qconfig_spec is None:\n if dtype == torch.qint8:\n qconfig_spec = {\n nn.Linear : default_dynamic_qconfig,\n nn.LSTM : default_dynamic_qconfig,\n nn.GRU : default_dynamic_qconfig,\n nn.LSTMCell : default_dynamic_qconfig,\n nn.RNNCell : default_dynamic_qconfig,\n nn.GRUCell : default_dynamic_qconfig,\n }\n elif dtype == torch.float16:\n qconfig_spec = {\n nn.Linear : float16_dynamic_qconfig,\n nn.LSTM : float16_dynamic_qconfig,\n nn.GRU : float16_dynamic_qconfig,\n nn.LSTMCell : float16_dynamic_qconfig,\n nn.RNNCell : float16_dynamic_qconfig,\n nn.GRUCell : float16_dynamic_qconfig,\n }\n elif dtype == torch.quint8:\n qconfig_spec = {\n nn.EmbeddingBag : float_qparams_weight_only_qconfig,\n nn.Embedding : float_qparams_weight_only_qconfig,\n }\n elif dtype == torch.quint4x2:\n qconfig_spec = {\n nn.EmbeddingBag : float_qparams_weight_only_qconfig_4bit,\n }\n else:\n raise ValueError(\n \"Don't know how to quantize with default settings for {}. Provide full qconfig please\".format(dtype))\n elif isinstance(qconfig_spec, set):\n if dtype is torch.qint8:\n default_qconfig = default_dynamic_qconfig\n elif dtype is torch.float16:\n default_qconfig = float16_dynamic_qconfig\n elif dtype is torch.quint8:\n default_qconfig = float_qparams_weight_only_qconfig\n elif dtype is torch.quint4x2:\n default_qconfig = float_qparams_weight_only_qconfig_4bit\n else:\n raise RuntimeError('Unknown dtype specified for quantize_dynamic: ', str(dtype))\n qconfig_spec = dict(zip(qconfig_spec, itertools.repeat(default_qconfig)))\n\n if mapping is None:\n mapping = get_default_dynamic_quant_module_mappings()\n\n if not inplace:\n model = copy.deepcopy(model)\n model.eval()\n propagate_qconfig_(model, qconfig_spec)\n convert(model, mapping, inplace=True)\n return model\n\ndef prepare_qat(model, mapping=None, inplace=False, allow_list=None):\n r\"\"\"\n Prepares a copy of the model for quantization calibration or\n quantization-aware training and converts it to quantized version.\n\n Quantization configuration should be assigned preemptively\n to individual submodules in `.qconfig` attribute.\n\n Args:\n model: input model to be modified in-place\n mapping: dictionary that maps float modules to quantized modules to be\n replaced.\n inplace: carry out model transformations in-place, the original module\n is mutated\n allow_list: a set that lists out allowable modules to be propagated with qconfig\n \"\"\"\n torch._C._log_api_usage_once(\"quantization_api.quantize.prepare_qat\")\n assert model.training, \"prepare_qat only works on models in training mode\"\n if mapping is None:\n mapping = get_default_qat_module_mappings()\n\n if not inplace:\n model = copy.deepcopy(model)\n\n propagate_qconfig_(model, qconfig_dict=None, allow_list=allow_list)\n convert(model, mapping=mapping, inplace=True, remove_qconfig=False)\n prepare(model, observer_non_leaf_module_list=set(mapping.values()), inplace=True)\n return model\n\ndef quantize_qat(model, run_fn, run_args, inplace=False):\n r\"\"\"Do quantization aware training and output a quantized model\n\n Args:\n model: input model\n run_fn: a function for evaluating the prepared model, can be a\n function that simply runs the prepared model or a training\n loop\n run_args: positional arguments for `run_fn`\n\n Return:\n Quantized model.\n \"\"\"\n torch._C._log_api_usage_once(\"quantization_api.quantize.quantize_qat\")\n if not inplace:\n model = copy.deepcopy(model)\n model.train()\n prepare_qat(model, inplace=True)\n run_fn(model, *run_args)\n convert(model, inplace=True)\n return model\n\ndef convert(\n module, mapping=None, inplace=False, remove_qconfig=True,\n convert_custom_config_dict=None):\n r\"\"\"Converts submodules in input module to a different module according to `mapping`\n by calling `from_float` method on the target module class. And remove qconfig at the\n end if remove_qconfig is set to True.\n\n Args:\n `module`: prepared and calibrated module\n `mapping`: a dictionary that maps from source module type to target\n module type, can be overwritten to allow swapping user defined\n Modules\n `inplace`: carry out model transformations in-place, the original module\n is mutated\n `convert_custom_config_dict`: custom configuration dictionary for convert function\n\n .. code-block:: python\n\n # Example of convert_custom_config_dict:\n convert_custom_config_dict = {\n # user will manually define the corresponding quantized\n # module class which has a from_observed class method that converts\n # observed custom module to quantized custom module\n \"observed_to_quantized_custom_module_class\": {\n ObservedCustomModule: QuantizedCustomModule\n }\n }\n\n \"\"\"\n torch._C._log_api_usage_once(\"quantization_api.quantize.convert\")\n if not inplace:\n module = copy.deepcopy(module)\n _convert(\n module, mapping, inplace=True,\n convert_custom_config_dict=convert_custom_config_dict)\n if remove_qconfig:\n _remove_qconfig(module)\n return module\n\ndef _convert(\n module, mapping=None, inplace=False,\n convert_custom_config_dict=None):\n r\"\"\"Converts submodules in input module to a different module according to `mapping`\n by calling `from_float` method on the target module class\n\n Args:\n module: input module\n mapping: a dictionary that maps from source module type to target\n module type, can be overwritten to allow swapping user defined\n Modules\n inplace: carry out model transformations in-place, the original module\n is mutated\n\n \"\"\"\n if mapping is None:\n mapping = get_default_static_quant_module_mappings()\n if convert_custom_config_dict is None:\n convert_custom_config_dict = {}\n custom_module_class_mapping = convert_custom_config_dict.get(\"observed_to_quantized_custom_module_class\", {})\n\n if not inplace:\n module = copy.deepcopy(module)\n reassign = {}\n for name, mod in module.named_children():\n # both fused modules and observed custom modules are\n # swapped as one unit\n if not isinstance(mod, _FusedModule) and \\\n type(mod) not in custom_module_class_mapping:\n _convert(mod, mapping, True, # inplace\n convert_custom_config_dict)\n reassign[name] = swap_module(mod, mapping, custom_module_class_mapping)\n\n for key, value in reassign.items():\n module._modules[key] = value\n\n return module\n\ndef swap_module(mod, mapping, custom_module_class_mapping):\n r\"\"\"Swaps the module if it has a quantized counterpart and it has an\n `observer` attached.\n\n Args:\n mod: input module\n mapping: a dictionary that maps from nn module to nnq module\n\n Return:\n The corresponding quantized module of `mod`\n \"\"\"\n new_mod = mod\n if hasattr(mod, 'qconfig') and mod.qconfig is not None:\n swapped = False\n if type(mod) in custom_module_class_mapping:\n new_mod = custom_module_class_mapping[type(mod)].from_observed(mod)\n swapped = True\n elif type(mod) in mapping:\n new_mod = mapping[type(mod)].from_float(mod)\n swapped = True\n\n if swapped:\n # Preserve module's pre forward hooks. They'll be called on quantized input\n for pre_hook_fn in mod._forward_pre_hooks.values():\n new_mod.register_forward_pre_hook(pre_hook_fn)\n # Preserve module's post forward hooks except _observer_forward_hook\n # After convert they'll work with quantized output\n for hook_fn in mod._forward_hooks.values():\n if hook_fn is not _observer_forward_hook:\n new_mod.register_forward_hook(hook_fn)\n\n # respect device affinity when swapping modules\n devices = get_unique_devices_(mod)\n assert len(devices) <= 1, (\n \"swap_module only works with cpu or single-device CUDA modules, \"\n \"but got devices {}\".format(devices)\n )\n device = next(iter(devices)) if len(devices) > 0 else None\n if device:\n new_mod.to(device)\n return new_mod\n\ndef get_observer_dict(mod, target_dict, prefix=\"\"):\n r\"\"\"Traverse the modules and save all observers into dict.\n This is mainly used for quantization accuracy debug\n Args:\n mod: the top module we want to save all observers\n prefix: the prefix for the current module\n target_dict: the dictionary used to save all the observers\n \"\"\"\n def get_prefix(prefix):\n return prefix if prefix == \"\" else prefix + '.'\n\n if hasattr(mod, 'activation_post_process'):\n target_dict[get_prefix(prefix) + 'activation_post_process'] = mod.activation_post_process\n for name, child in mod.named_children():\n module_prefix = get_prefix(prefix) + name if prefix else name\n get_observer_dict(child, target_dict, module_prefix)\n", "# Owner(s): [\"oncall: quantization\"]\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.intrinsic as nni\nimport torch.nn.intrinsic.quantized as nniq\nimport torch.nn.quantized as nnq\nimport torch.nn.quantized.dynamic as nnqd\nimport torch.ao.quantization\n\nfrom torch.ao.quantization import (\n get_default_static_quant_module_mappings,\n default_float_qparams_observer,\n PerChannelMinMaxObserver,\n)\nfrom torch.testing._internal.common_quantization import (\n QuantizationTestCase,\n prepare_dynamic,\n _make_conv_test_input,\n skipIfNoFBGEMM,\n lengths_to_offsets\n)\nfrom torch.testing._internal.common_quantized import (\n _calculate_dynamic_qparams,\n override_quantized_engine,\n override_qengines,\n qengine_is_qnnpack,\n)\nfrom hypothesis import assume, given\nfrom hypothesis import strategies as st\nimport torch.testing._internal.hypothesis_utils as hu\nhu.assert_deadline_disabled()\n\nimport copy\nimport io\nimport numpy as np\nimport itertools\n\n\"\"\"\nNote that tests in this file are just API test, to make sure we wrapped the\nquantized operator implementations correctly in the user facing APIs, these are\nnot correctness test for the underlying quantized operators. For correctness\ntest please see `test/quantization/test_quantized_op.py`.\n\"\"\"\n\nclass TestStaticQuantizedModule(QuantizationTestCase):\n def test_relu(self):\n relu_module = nn.ReLU()\n relu6_module = nnq.ReLU6()\n\n x = torch.arange(-10, 10, dtype=torch.float)\n y_ref = torch.relu(x)\n y6_ref = torch.nn.modules.ReLU6()(x)\n\n qx = torch.quantize_per_tensor(x, 1.0, 0, dtype=torch.qint32)\n qy = relu_module(qx)\n qy6 = relu6_module(qx)\n\n self.assertEqual(y_ref, qy.dequantize(),\n msg=\"ReLU module API failed\")\n self.assertEqual(y6_ref, qy6.dequantize(),\n msg=\"ReLU6 module API failed\")\n\n @override_qengines\n def test_linear_api(self):\n \"\"\"test API functionality for nn.quantized.linear and nn.intrinsic.quantized.linear_relu\"\"\"\n options = itertools.product(\n [1, 5],\n [16, 32],\n [4, 8],\n [True, False],\n [True, False],\n [True, False])\n for (batch_size, in_features, out_features, use_bias,\n use_fused, per_channel) in options:\n self._test_linear_api_impl(\n batch_size, in_features, out_features, use_bias, use_fused,\n per_channel)\n\n def _test_linear_api_impl(self, batch_size, in_features, out_features, use_bias, use_fused, per_channel):\n if torch.backends.quantized.engine == 'qnnpack':\n per_channel = False\n\n # use_fused -> quantized class\n class_map = {\n True: nniq.LinearReLU,\n False: nnq.Linear,\n }\n\n W = torch.rand(out_features, in_features).float()\n if per_channel:\n scale_tensor = torch.ones(out_features, dtype=torch.double)\n zero_point_tensor = torch.zeros(out_features, dtype=torch.long)\n for i in range(len(scale_tensor)):\n scale_tensor[i] = (i + 1.0) / 255.0\n W_q = torch.quantize_per_channel(W, scales=scale_tensor,\n zero_points=zero_point_tensor,\n axis=0, dtype=torch.qint8)\n else:\n W_q = torch.quantize_per_tensor(W, 0.1, 4, torch.qint8)\n\n X = torch.rand(batch_size, in_features).float()\n X_q = torch.quantize_per_tensor(X, 0.2, 10, torch.quint8)\n B = torch.rand(out_features).float() if use_bias else None\n scale = 0.5\n zero_point = 3\n qlinear = class_map[use_fused](in_features, out_features)\n\n qlinear_copy = copy.deepcopy(qlinear)\n self.checkScriptable(qlinear_copy, [[X_q]], check_save_load=True)\n # Run module with default-initialized parameters.\n # This tests that the constructor is correct.\n qlinear(X_q)\n\n qlinear.set_weight_bias(W_q, B)\n # Simple round-trip test to ensure weight()/set_weight() API\n self.assertEqual(qlinear.weight(), W_q, atol=1e-5, rtol=0)\n\n # testing packed param implementation\n qlinear.scale = float(scale)\n qlinear.zero_point = int(zero_point)\n Z_q = qlinear(X_q)\n\n # Check if the module implementation matches calling the\n # ops directly\n W_pack = qlinear._packed_params._packed_params\n if use_fused:\n Z_ref = torch.ops.quantized.linear_relu(X_q, W_pack, scale, zero_point)\n else:\n Z_ref = torch.ops.quantized.linear(X_q, W_pack, scale, zero_point)\n\n self.assertEqual(Z_ref, Z_q)\n self.assertTrue(\n (\"QuantizedLinearReLU\" if use_fused else \"QuantizedLinear\") in str(qlinear))\n\n # Test serialization of quantized Linear Module using state_dict\n model_dict = qlinear.state_dict()\n b = io.BytesIO()\n torch.save(model_dict, b)\n b.seek(0)\n loaded_dict = torch.load(b)\n for key in model_dict:\n if isinstance(model_dict[key], torch._C.ScriptObject):\n assert isinstance(loaded_dict[key], torch._C.ScriptObject)\n w_model, b_model = torch.ops.quantized.linear_unpack(model_dict[key])\n w_loaded, b_loaded = torch.ops.quantized.linear_unpack(loaded_dict[key])\n self.assertEqual(w_model, w_loaded)\n self.assertEqual(b_model, b_loaded)\n else:\n self.assertEqual(model_dict[key], loaded_dict[key])\n\n loaded_qlinear = class_map[use_fused](\n in_features, out_features)\n loaded_qlinear.load_state_dict(loaded_dict)\n linear_unpack = torch.ops.quantized.linear_unpack\n self.assertEqual(linear_unpack(qlinear._packed_params._packed_params),\n linear_unpack(loaded_qlinear._packed_params._packed_params))\n self.assertEqual(qlinear.scale, loaded_qlinear.scale)\n self.assertEqual(qlinear.zero_point, loaded_qlinear.zero_point)\n # scripting will add __overloads__ to __dict__, which is why we script a copy\n # to be able to do the check in the next line\n self.checkScriptable(copy.deepcopy(loaded_qlinear), [[X_q]], check_save_load=True)\n self.assertTrue(dir(qlinear) == dir(loaded_qlinear))\n self.assertEqual(qlinear._weight_bias(), loaded_qlinear._weight_bias())\n self.assertEqual(qlinear._weight_bias(), torch.ops.quantized.linear_unpack(qlinear._packed_params._packed_params))\n Z_q2 = loaded_qlinear(X_q)\n self.assertEqual(Z_q, Z_q2)\n\n # Test serialization\n b = io.BytesIO()\n torch.save(qlinear, b)\n b.seek(0)\n loaded = torch.load(b)\n self.assertEqual(qlinear.weight(), loaded.weight())\n self.assertEqual(qlinear.scale, loaded.scale)\n self.assertEqual(qlinear.zero_point, loaded.zero_point)\n\n # Test copy and deepcopy\n copied_linear = copy.copy(qlinear)\n self.assertEqual(copied_linear.bias(), qlinear.bias())\n self.assertEqual(copied_linear.scale, qlinear.scale)\n self.assertEqual(copied_linear.zero_point,\n qlinear.zero_point)\n Y_copied = copied_linear(X_q)\n np.testing.assert_array_almost_equal(\n Z_q.int_repr().numpy(), Y_copied.int_repr().numpy(), decimal=0)\n\n deepcopied_linear = copy.deepcopy(qlinear)\n self.assertEqual(deepcopied_linear.bias(), qlinear.bias())\n self.assertEqual(deepcopied_linear.scale, qlinear.scale)\n self.assertEqual(deepcopied_linear.zero_point,\n qlinear.zero_point)\n Y_deepcopied = copied_linear(X_q)\n np.testing.assert_array_almost_equal(\n Z_q.int_repr().numpy(), Y_deepcopied.int_repr().numpy(), decimal=0)\n\n # Test JIT\n self.checkScriptable(qlinear, [[X_q]], check_save_load=True)\n\n # Make sure `from_float` works for all linear variants\n modules_under_test = [torch.nn.Linear, torch.nn.modules.linear.NonDynamicallyQuantizableLinear]\n\n for mut in modules_under_test:\n # Test from_float.\n float_linear = mut(in_features, out_features).float()\n float_linear.qconfig = torch.ao.quantization.default_qconfig\n torch.ao.quantization.prepare(float_linear, inplace=True)\n float_linear(X.float())\n # Sequential allows swapping using \"convert\".\n quantized_float_linear = torch.nn.Sequential(float_linear)\n quantized_float_linear = torch.ao.quantization.convert(quantized_float_linear, inplace=True)\n\n # Smoke test to make sure the module actually runs\n quantized_float_linear(X_q)\n\n # Smoke test extra_repr\n self.assertTrue('QuantizedLinear' in str(quantized_float_linear))\n\n def test_quant_dequant_api(self):\n r = torch.tensor([[1., -1.], [1., -1.]], dtype=torch.float)\n scale, zero_point, dtype = 1.0, 2, torch.qint8\n # testing Quantize API\n qr = torch.quantize_per_tensor(r, scale, zero_point, dtype)\n quant_m = nnq.Quantize(scale, zero_point, dtype)\n qr2 = quant_m(r)\n self.assertEqual(qr, qr2)\n # testing Dequantize API\n rqr = qr.dequantize()\n dequant_m = nnq.DeQuantize()\n rqr2 = dequant_m(qr2)\n self.assertEqual(rqr, rqr2)\n\n def _test_conv_api_impl(\n self, module_name, qconv_module, conv_module, batch_size,\n in_channels_per_group, input_feature_map_size, out_channels_per_group,\n groups, kernel_size, stride, padding, padding_mode, dilation,\n X_scale, X_zero_point, W_scale, W_zero_point, Y_scale, Y_zero_point,\n use_bias, use_fused, use_channelwise):\n for i in range(len(kernel_size)):\n assume(input_feature_map_size[i] + 2 * padding[i]\n >= dilation[i] * (kernel_size[i] - 1) + 1)\n\n in_channels = in_channels_per_group * groups\n out_channels = out_channels_per_group * groups\n (X, X_q, W, W_q, b) = _make_conv_test_input(\n batch_size, in_channels_per_group, input_feature_map_size,\n out_channels_per_group, groups, kernel_size, X_scale, X_zero_point,\n W_scale, W_zero_point, use_bias, use_channelwise)\n # Make sure the weight shape is correct\n self.assertTrue(qconv_module.weight().shape == W_q.shape)\n\n qconv_module.set_weight_bias(W_q, b)\n qconv_module.scale = Y_scale\n qconv_module.zero_point = Y_zero_point\n\n if use_fused:\n conv_module[0].weight.data = W\n if use_bias:\n conv_module[0].bias.data = b\n else:\n conv_module.weight.data = W\n if use_bias:\n conv_module.bias.data = b\n\n # Test members\n self.assertTrue(module_name == qconv_module._get_name(), module_name + \" \" + qconv_module._get_name())\n self.assertTrue(hasattr(qconv_module, '_packed_params'))\n self.assertTrue(hasattr(qconv_module, 'scale'))\n self.assertTrue(hasattr(qconv_module, 'zero_point'))\n\n # Test properties\n self.assertEqual(W_q, qconv_module.weight())\n if use_bias:\n self.assertEqual(b, qconv_module.bias())\n self.assertEqual(Y_scale, qconv_module.scale)\n self.assertEqual(Y_zero_point, qconv_module.zero_point)\n\n # Test forward\n Y_exp = conv_module(X)\n Y_exp = torch.quantize_per_tensor(\n Y_exp, scale=Y_scale, zero_point=Y_zero_point, dtype=torch.quint8)\n Y_act = qconv_module(X_q)\n\n # Make sure the results match\n # assert_array_almost_equal compares using the following formula:\n # abs(desired-actual) < 1.5 * 10**(-decimal)\n # (https://docs.scipy.org/doc/numpy/reference/generated/numpy.testing.assert_almost_equal.html)\n # We use decimal = 0 to ignore off-by-1 differences between reference\n # and test. Off-by-1 differences arise due to the order of round and\n # zero_point addition operation, i.e., if addition followed by round is\n # used by reference and round followed by addition is used by test, the\n # results may differ by 1.\n # For example, the result of round(2.5) + 1 is 3 while round(2.5 + 1) is\n # 4 assuming the rounding mode is round-to-nearest, ties-to-even.\n # skip numerics checking for reference module\n np.testing.assert_array_almost_equal(\n Y_exp.int_repr().numpy(), Y_act.int_repr().numpy(), decimal=0)\n\n # Test serialization of quantized Conv Module using state_dict\n model_dict = qconv_module.state_dict()\n self.assertEqual(model_dict['weight'], W_q)\n if use_bias:\n self.assertEqual(model_dict['bias'], b)\n bytes_io = io.BytesIO()\n torch.save(model_dict, bytes_io)\n bytes_io.seek(0)\n loaded_dict = torch.load(bytes_io)\n for key in loaded_dict:\n self.assertEqual(model_dict[key], loaded_dict[key])\n loaded_qconv_module = type(qconv_module)(\n in_channels, out_channels, kernel_size, stride, padding, dilation,\n groups, use_bias, padding_mode=padding_mode)\n loaded_qconv_module.load_state_dict(loaded_dict)\n\n self.assertTrue(dir(loaded_qconv_module) == dir(qconv_module))\n self.assertTrue(module_name == loaded_qconv_module._get_name())\n self.assertTrue(hasattr(loaded_qconv_module, '_packed_params'))\n self.assertTrue(hasattr(loaded_qconv_module, '_weight_bias'))\n\n self.assertEqual(qconv_module.weight(), loaded_qconv_module.weight())\n if use_bias:\n self.assertEqual(qconv_module.bias(), loaded_qconv_module.bias())\n self.assertEqual(qconv_module.scale, loaded_qconv_module.scale)\n self.assertEqual(qconv_module.zero_point,\n loaded_qconv_module.zero_point)\n Y_loaded = loaded_qconv_module(X_q)\n np.testing.assert_array_almost_equal(\n Y_exp.int_repr().numpy(), Y_loaded.int_repr().numpy(), decimal=0)\n\n # Test serialization\n b = io.BytesIO()\n torch.save(qconv_module, b)\n b.seek(0)\n loaded_conv = torch.load(b)\n\n self.assertEqual(loaded_conv.bias(), qconv_module.bias())\n self.assertEqual(loaded_conv.scale, qconv_module.scale)\n self.assertEqual(loaded_conv.zero_point,\n qconv_module.zero_point)\n\n # Test copy and deepcopy\n copied_conv = copy.copy(qconv_module)\n self.assertEqual(copied_conv.bias(), qconv_module.bias())\n self.assertEqual(copied_conv.scale, qconv_module.scale)\n self.assertEqual(copied_conv.zero_point,\n qconv_module.zero_point)\n Y_copied = copied_conv(X_q)\n np.testing.assert_array_almost_equal(\n Y_exp.int_repr().numpy(), Y_copied.int_repr().numpy(), decimal=0)\n\n deepcopied_conv = copy.deepcopy(qconv_module)\n self.assertEqual(deepcopied_conv.bias(), qconv_module.bias())\n self.assertEqual(deepcopied_conv.scale, qconv_module.scale)\n self.assertEqual(deepcopied_conv.zero_point,\n qconv_module.zero_point)\n Y_deepcopied = copied_conv(X_q)\n np.testing.assert_array_almost_equal(\n Y_exp.int_repr().numpy(), Y_deepcopied.int_repr().numpy(), decimal=0)\n\n # JIT testing\n self.checkScriptable(\n qconv_module, [[X_q]],\n check_save_load=True)\n\n # Test from_float\n fused_conv_module = torch.nn.intrinsic._FusedModule(conv_module)\n fused_conv_module.qconfig = torch.ao.quantization.default_qconfig\n torch.ao.quantization.prepare(fused_conv_module, inplace=True)\n fused_conv_module(X.float())\n converted_qconv_module = fused_conv_module\n reference_mapping = get_default_static_quant_module_mappings()\n reference_mapping[type(conv_module)] = type(qconv_module)\n torch.ao.quantization.convert(converted_qconv_module, mapping=reference_mapping, inplace=True)\n\n # Smoke test to make sure the module actually runs\n if use_bias:\n if use_fused:\n self.assertEqual(conv_module[0].bias,\n converted_qconv_module[0].bias())\n else:\n self.assertEqual(conv_module.bias,\n converted_qconv_module[0].bias())\n # Smoke test extra_repr\n self.assertTrue(module_name == converted_qconv_module[0]._get_name())\n\n @override_qengines\n def test_conv1d_api(self):\n options = itertools.product(\n [\"zeros\", \"reflect\"], # pad_mode\n [True, False], # use_bias\n [True, False], # use_fused\n [True, False], # use_channelwise\n )\n for pad_mode, use_bias, use_fused, use_channelwise in options:\n if torch.backends.quantized.engine == \"qnnpack\":\n use_channelwise = False\n batch_size = 2\n in_channels_per_group = 2\n length = 8\n out_channels_per_group = 2\n groups = 3\n kernel = 3\n stride = 2\n pad = 1\n dilation = 1\n # Tests the correctness of the conv2d module.\n in_channels = in_channels_per_group * groups\n out_channels = out_channels_per_group * groups\n input_feature_map_size = (length,)\n kernel_size = (kernel, )\n stride = (stride, )\n pad = (pad, )\n dilation = (dilation, )\n X_scale = 1.3\n X_zero_point = 2\n W_scale = [0.5]\n W_zero_point = [3]\n Y_scale = 5.0\n Y_zero_point = 4\n if torch.backends.quantized.engine == 'qnnpack':\n use_channelwise = False\n # use_fused -> quantized class\n class_map = {\n True: (nniq.ConvReLU1d, \"QuantizedConvReLU1d\"),\n False: (nnq.Conv1d, \"QuantizedConv1d\")\n }\n\n qconv_cls, module_name = class_map[use_fused]\n qconv_module = qconv_cls(\n in_channels, out_channels, kernel, stride, pad,\n dilation, groups, use_bias, padding_mode=pad_mode\n )\n\n conv_module = nn.Conv1d(\n in_channels, out_channels, kernel, stride, pad,\n dilation, groups, use_bias, padding_mode=pad_mode)\n if use_fused:\n relu_module = nn.ReLU()\n conv_module = nni.ConvReLU1d(conv_module, relu_module)\n conv_module = conv_module.float()\n\n self._test_conv_api_impl(\n module_name, qconv_module, conv_module, batch_size,\n in_channels_per_group, input_feature_map_size,\n out_channels_per_group, groups, kernel_size, stride, pad, pad_mode,\n dilation, X_scale, X_zero_point, W_scale, W_zero_point, Y_scale,\n Y_zero_point, use_bias, use_fused, use_channelwise)\n\n @override_qengines\n def test_conv2d_api(self):\n options = itertools.product(\n [\"zeros\", \"reflect\"], # pad_mode\n [True, False], # use_bias\n [True, False], # use_fused\n [True, False], # use_channelwise\n )\n for pad_mode, use_bias, use_fused, use_channelwise in options:\n if torch.backends.quantized.engine == \"qnnpack\":\n use_channelwise = False\n batch_size = 2\n in_channels_per_group = 2\n H = 8\n W = 8\n out_channels_per_group = 2\n groups = 3\n kernel_h = 3\n kernel_w = 3\n stride_h = 2\n stride_w = 2\n pad_h = 1\n pad_w = 1\n dilation = 1\n # Tests the correctness of the conv2d module.\n in_channels = in_channels_per_group * groups\n out_channels = out_channels_per_group * groups\n input_feature_map_size = (H, W)\n kernel_size = (kernel_h, kernel_w)\n stride = (stride_h, stride_w)\n padding = (pad_h, pad_w)\n dilation = (dilation, dilation)\n X_scale = 1.3\n X_zero_point = 2\n W_scale = [0.5]\n W_zero_point = [3]\n Y_scale = 5.0\n Y_zero_point = 4\n # use_fused -> quantized class\n class_map = {\n True: (nniq.ConvReLU2d, \"QuantizedConvReLU2d\"),\n False: (nnq.Conv2d, \"QuantizedConv2d\")\n }\n\n qconv_cls, module_name = class_map[use_fused]\n qconv_module = qconv_cls(\n in_channels, out_channels, kernel_size, stride, padding,\n dilation, groups, use_bias, padding_mode=pad_mode\n )\n\n conv_module = nn.Conv2d(\n in_channels, out_channels, kernel_size, stride, padding,\n dilation, groups, use_bias, padding_mode=pad_mode)\n if use_fused:\n relu_module = nn.ReLU()\n conv_module = nni.ConvReLU2d(conv_module, relu_module)\n conv_module = conv_module.float()\n\n self._test_conv_api_impl(\n module_name, qconv_module, conv_module, batch_size,\n in_channels_per_group, input_feature_map_size,\n out_channels_per_group, groups, kernel_size, stride, padding,\n pad_mode, dilation, X_scale, X_zero_point, W_scale, W_zero_point,\n Y_scale, Y_zero_point, use_bias, use_fused, use_channelwise)\n\n @skipIfNoFBGEMM\n def test_conv3d_api(self):\n options = itertools.product(\n [True, False], # use_bias\n [True, False], # use_fused\n [True, False], # use_channelwise\n )\n for use_bias, use_fused, use_channelwise in options:\n if torch.backends.quantized.engine == \"qnnpack\":\n use_channelwise = False\n batch_size = 2\n in_channels_per_group = 2\n H = 8\n W = 8\n D = 8\n out_channels_per_group = 2\n groups = 3\n kernel_h = 3\n kernel_w = 3\n kernel_d = 3\n stride_h = 2\n stride_w = 2\n stride_d = 2\n pad_mode = \"zeros\" # 3d doesn't support reflect padding\n pad_h = 1\n pad_w = 1\n pad_d = 1\n dilation = 1\n # Tests the correctness of the conv3d module.\n in_channels = in_channels_per_group * groups\n out_channels = out_channels_per_group * groups\n input_feature_map_size = (D, H, W)\n kernel_size = (kernel_d, kernel_h, kernel_w)\n stride = (stride_d, stride_h, stride_w)\n padding = (pad_d, pad_h, pad_w)\n dilation = (dilation, dilation, dilation)\n X_scale = 1.3\n X_zero_point = 2\n W_scale = [0.5]\n W_zero_point = [3]\n Y_scale = 5.0\n Y_zero_point = 4\n # use_fused -> quantized class\n class_map = {\n True: (nniq.ConvReLU3d, \"QuantizedConvReLU3d\"),\n False: (nnq.Conv3d, \"QuantizedConv3d\")\n }\n\n with override_quantized_engine('fbgemm'):\n qconv_cls, module_name = class_map[use_fused]\n qconv_module = qconv_cls(\n in_channels, out_channels, kernel_size, stride, padding,\n dilation, groups, use_bias, padding_mode=pad_mode\n )\n\n conv_module = nn.Conv3d(\n in_channels, out_channels, kernel_size, stride, padding,\n dilation, groups, use_bias, padding_mode=pad_mode)\n if use_fused:\n relu_module = nn.ReLU()\n conv_module = nni.ConvReLU3d(conv_module, relu_module)\n conv_module = conv_module.float()\n\n self._test_conv_api_impl(\n module_name, qconv_module, conv_module, batch_size,\n in_channels_per_group, input_feature_map_size,\n out_channels_per_group, groups, kernel_size, stride, padding,\n pad_mode, dilation, X_scale, X_zero_point, W_scale,\n W_zero_point, Y_scale, Y_zero_point, use_bias, use_fused,\n use_channelwise)\n\n def test_pool_api(self):\n \"\"\"Tests the correctness of the pool module.\n The correctness is defined against the functional implementation.\n \"\"\"\n N, C, H, W = 10, 10, 10, 3\n kwargs = {\n 'kernel_size': 2,\n 'stride': None,\n 'padding': 0,\n 'dilation': 1\n }\n\n scale, zero_point = 1.0 / 255, 128\n\n X = torch.randn(N, C, H, W, dtype=torch.float32)\n qX = torch.quantize_per_tensor(X, scale=scale, zero_point=zero_point,\n dtype=torch.quint8)\n qX_expect = torch.nn.functional.max_pool2d(qX, **kwargs)\n\n pool_under_test = torch.nn.quantized.MaxPool2d(**kwargs)\n qX_hat = pool_under_test(qX)\n self.assertEqual(qX_expect, qX_hat)\n\n # JIT Testing\n self.checkScriptable(pool_under_test, [[X]])\n\n def test_batch_norm2d(self):\n \"\"\"Tests the correctness of the batchnorm2d module.\n The correctness is defined against the functional implementation.\n \"\"\"\n x = torch.randn((2, 4, 6, 8), dtype=torch.float)\n float_mod = torch.nn.BatchNorm2d(4)\n float_mod.training = False\n\n y_ref = float_mod(x)\n quant_ref = torch.quantize_per_tensor(y_ref, 1.0, 0, dtype=torch.quint8)\n\n quant_mod = nnq.BatchNorm2d(4)\n qx = torch.quantize_per_tensor(x, 1.0, 0, dtype=torch.quint8)\n qy = quant_mod(qx)\n\n self.assertEqual(quant_ref.int_repr().numpy(), qy.int_repr().numpy(),\n msg=\"BatchNorm2d module API failed\")\n\n def test_batch_norm3d(self):\n \"\"\"Tests the correctness of the batchnorm3d module.\n The correctness is defined against the functional implementation.\n \"\"\"\n x = torch.randn((2, 4, 6, 8, 10), dtype=torch.float)\n float_mod = torch.nn.BatchNorm3d(4)\n float_mod.training = False\n\n y_ref = float_mod(x)\n quant_ref = torch.quantize_per_tensor(y_ref, 1.0, 0, dtype=torch.quint8)\n\n quant_mod = nnq.BatchNorm3d(4)\n qx = torch.quantize_per_tensor(x, 1.0, 0, dtype=torch.quint8)\n qy = quant_mod(qx)\n\n self.assertEqual(quant_ref.int_repr().numpy(), qy.int_repr().numpy(),\n msg=\"BatchNorm3d module API failed\")\n\n def _test_batch_norm_serialization(self, get_model, data1, data2):\n m1 = get_model()\n m1.qconfig = torch.ao.quantization.default_qconfig\n mp1 = torch.ao.quantization.prepare(m1)\n mp1(data1)\n mq1 = torch.ao.quantization.convert(mp1)\n ref1 = mq1(data2)\n\n m2 = get_model()\n m2.qconfig = torch.quantization.default_qconfig\n mp2 = torch.ao.quantization.prepare(m2)\n mq2 = torch.ao.quantization.convert(mp2)\n\n mq2.load_state_dict(mq1.state_dict())\n ref2 = mq2(data2)\n\n self.assertTrue(torch.allclose(ref1, ref2))\n\n def test_batch_norm2d_serialization(self):\n data1 = torch.randn(2, 4, 6, 8)\n data2 = torch.randn(2, 4, 6, 8)\n\n def _get_model():\n return nn.Sequential(\n torch.ao.quantization.QuantStub(),\n nn.BatchNorm2d(4),\n torch.ao.quantization.DeQuantStub()\n ).eval()\n\n self._test_batch_norm_serialization(_get_model, data1, data2)\n\n def test_batch_norm3d_serialization(self):\n data1 = torch.randn(2, 4, 6, 8, 1)\n data2 = torch.randn(2, 4, 6, 8, 1)\n\n def _get_model():\n return nn.Sequential(\n torch.ao.quantization.QuantStub(),\n nn.BatchNorm3d(4),\n torch.ao.quantization.DeQuantStub()\n ).eval()\n\n self._test_batch_norm_serialization(_get_model, data1, data2)\n\n def test_layer_norm(self):\n \"\"\"Tests the correctness of the layernorm module.\n The correctness is defined against the functional implementation.\n \"\"\"\n x_scale = 10.0 / 256\n x_zero_point = 0\n y_scale = 5.0 / 256\n y_zero_point = 127\n\n dims = (1, 4, 8)\n\n X = (torch.randn(dims, dtype=torch.float) - 0.5) * 10\n qX = torch.quantize_per_tensor(X, x_scale, x_zero_point, dtype=torch.quint8)\n dqX = qX.dequantize()\n\n float_mod = torch.nn.LayerNorm(dqX.size()[1:]).float()\n float_mod.weight = torch.nn.Parameter(torch.rand(*dims[1:]))\n float_mod.bias = torch.nn.Parameter(torch.rand(*dims[1:]))\n\n dqY_ref = float_mod(dqX)\n qY_ref = torch.quantize_per_tensor(\n dqY_ref, y_scale, y_zero_point, dtype=torch.quint8)\n\n quant_mod = nnq.LayerNorm(\n qX.size()[1:], float_mod.weight, float_mod.bias, y_scale, y_zero_point)\n qY = quant_mod(qX)\n\n self.assertEqual(qY_ref.int_repr().numpy(), qY.int_repr().numpy(),\n msg=\"LayerNorm module API failed, qY_ref\\n{} vs qY\\n{}\"\n .format(qY_ref, qY))\n\n def test_group_norm(self):\n \"\"\"Tests the correctness of the groupnorm module.\n The correctness is defined against the functional implementation.\n \"\"\"\n x_scale = 10.0 / 256\n x_zero_point = 0\n y_scale = 5.0 / 256\n y_zero_point = 127\n\n dims = (1, 4, 8)\n\n X = (torch.randn(dims, dtype=torch.float) - 0.5) * 10\n qX = torch.quantize_per_tensor(X, x_scale, x_zero_point, dtype=torch.quint8)\n dqX = qX.dequantize()\n\n float_mod = torch.nn.GroupNorm(2, 4).float()\n float_mod.weight = torch.nn.Parameter(torch.rand(dims[1]))\n float_mod.bias = torch.nn.Parameter(torch.rand(dims[1]))\n\n dqY_ref = float_mod(dqX)\n qY_ref = torch.quantize_per_tensor(\n dqY_ref, y_scale, y_zero_point, dtype=torch.quint8)\n\n quant_mod = nnq.GroupNorm(\n 2, 2, float_mod.weight, float_mod.bias, y_scale, y_zero_point)\n qY = quant_mod(qX)\n\n self.assertEqual(qY_ref.int_repr().numpy(), qY.int_repr().numpy(),\n msg=\"GroupNorm module API failed, qY_ref\\n{} vs qY\\n{}\"\n .format(qY_ref, qY))\n\n def test_instance_norm(self):\n \"\"\"Tests the correctness of the instancenorm{n}d modules.\n The correctness is defined against the functional implementation.\n \"\"\"\n x_scale = 10.0 / 256\n x_zero_point = 0\n y_scale = 5.0 / 256\n y_zero_point = 127\n\n dims_to_modules = [\n ((1, 4, 8), torch.nn.InstanceNorm1d, nnq.InstanceNorm1d),\n ((1, 4, 8, 1), torch.nn.InstanceNorm2d, nnq.InstanceNorm2d),\n ((1, 4, 8, 1, 1), torch.nn.InstanceNorm3d, nnq.InstanceNorm3d),\n ]\n\n for dim_to_modules in dims_to_modules:\n dims, float_cls, q_cls = dim_to_modules\n\n X = (torch.randn(dims, dtype=torch.float) - 0.5) * 10\n qX = torch.quantize_per_tensor(\n X, x_scale, x_zero_point, dtype=torch.quint8)\n dqX = qX.dequantize()\n\n float_mod = float_cls(dims[1]).float()\n float_mod.weight = torch.nn.Parameter(torch.rand(dims[1]))\n float_mod.bias = torch.nn.Parameter(torch.rand(dims[1]))\n\n dqY_ref = float_mod(dqX)\n qY_ref = torch.quantize_per_tensor(\n dqY_ref, y_scale, y_zero_point, dtype=torch.quint8)\n\n quant_mod = q_cls(\n dims[1], float_mod.weight, float_mod.bias, y_scale,\n y_zero_point)\n qY = quant_mod(qX)\n\n self.assertEqual(\n qY_ref.int_repr().numpy(), qY.int_repr().numpy(),\n msg=\"InstanceNorm module API failed, qY_ref\\n{} vs qY\\n{}\"\n .format(qY_ref, qY))\n\n def _test_activation_module_impl(self, name, float_module_class, quantized_module_class, extra_kwargs):\n \"\"\"Tests the correctness of the ELU module.\n The correctness is defined against the functional implementation.\n \"\"\"\n x_scale = 10.0 / 256\n x_zero_point = 0\n y_scale = 5.0 / 256\n y_zero_point = 127\n alpha = 1.5\n\n dims = (1, 4, 8)\n\n X = (torch.randn(dims, dtype=torch.float) - 0.5) * 10\n qX = torch.quantize_per_tensor(X, x_scale, x_zero_point, dtype=torch.quint8)\n dqX = qX.dequantize()\n\n float_mod = float_module_class(**extra_kwargs).float()\n\n dqY_ref = float_mod(dqX)\n qY_ref = torch.quantize_per_tensor(\n dqY_ref, y_scale, y_zero_point, dtype=torch.quint8)\n\n quant_mod = quantized_module_class(y_scale, y_zero_point, **extra_kwargs)\n qY = quant_mod(qX)\n self.assertEqual(qY_ref.int_repr().numpy(), qY.int_repr().numpy(),\n msg=\"{} module API failed, qY_ref\\n{} vs qY\\n{}\"\n .format(name, qY_ref, qY))\n\n def _test_leaky_relu_serialization(self):\n scale_original = 10.0 / 256\n zero_point_original = 1.0\n\n quant_mod_original = nnq.LeakyReLU(scale_original, zero_point_original)\n state_dict = quant_mod_original.state_dict()\n\n scale_new = 5.0 / 256\n zero_point_new = 2.0\n quant_mod_new = nnq.LeakyReLU(scale_new, zero_point_new)\n quant_mod_new.load_state_dict(state_dict)\n\n self.assertEqual(quant_mod_original.scale, quant_mod_new.scale)\n self.assertEqual(quant_mod_original.zero_point, quant_mod_new.zero_point)\n\n def test_elu(self):\n \"\"\"Tests the correctness of the ELU module.\n The correctness is defined against the functional implementation.\n \"\"\"\n self._test_activation_module_impl(\"ELU\", nn.ELU, nnq.ELU, {\"alpha\": 1.5})\n\n def test_leaky_relu(self):\n self._test_activation_module_impl(\"LeakyReLU\", nn.LeakyReLU, nnq.LeakyReLU, {\"negative_slope\": 0.2})\n self._test_leaky_relu_serialization()\n\n def test_sigmoid(self):\n self._test_activation_module_impl(\"Sigmoid\", nn.Sigmoid, nnq.Sigmoid, {})\n\n @given(\n num_embeddings=st.integers(10, 50),\n embedding_dim=st.integers(5, 50).filter(lambda x: x % 4 == 0),\n set_qconfig=st.booleans(),\n )\n @skipIfNoFBGEMM\n def test_embedding_api(self, num_embeddings, embedding_dim, set_qconfig):\n num_lengths = np.random.randint(1, 6)\n lengths = np.random.randint(0, 21, size=num_lengths).astype(np.int32)\n num_indices = np.sum(lengths)\n indices = torch.from_numpy(np.random.randint(low=0, high=num_embeddings, size=num_indices, dtype=np.int64))\n weights = torch.from_numpy((np.random.random_sample((num_embeddings, embedding_dim)) + 1).astype(np.float32))\n\n obs = default_float_qparams_observer()\n obs(weights)\n qparams = obs.calculate_qparams()\n # Quantize the weights to 8bits\n qweight = torch.quantize_per_channel(weights, qparams[0], qparams[1], axis=0, dtype=torch.quint8)\n qemb = nnq.Embedding(num_embeddings=num_embeddings, embedding_dim=embedding_dim)\n qemb.set_weight(qweight)\n qemb(indices)\n\n # Ensure the module has the correct weights\n self.assertEqual(qweight, qemb.weight())\n\n w_packed = qemb._packed_params._packed_weight\n module_out = qemb(indices)\n\n # Call the qembedding operator directly\n ref = torch.ops.quantized.embedding_byte(w_packed, indices, pruned_weights=False)\n self.assertEqual(module_out, ref)\n self.checkEmbeddingSerialization(qemb, num_embeddings, embedding_dim, indices, None, set_qconfig=False, is_emb_bag=False)\n\n\n @given(\n num_embeddings=st.integers(10, 50),\n embedding_dim=st.integers(5, 50).filter(lambda x: x % 4 == 0),\n num_offsets=st.integers(1, 20),\n set_qconfig=st.booleans(),\n )\n @skipIfNoFBGEMM\n def test_embedding_bag_api(self, num_embeddings, embedding_dim, num_offsets, set_qconfig):\n r\"\"\"Test execution and serialization for dynamic quantized embedding_bag modules on int8\n \"\"\"\n\n num_lengths = np.random.randint(1, 6)\n lengths = np.random.randint(0, 21, size=num_lengths).astype(np.int32)\n num_indices = np.sum(lengths)\n indices = torch.from_numpy(np.random.randint(low=0, high=num_embeddings, size=num_indices, dtype=np.int64))\n\n offsets = lengths_to_offsets(lengths)\n # include the last offset\n offsets = torch.cat((offsets, torch.tensor([indices.size(0)], dtype=torch.long)), 0)\n weights = torch.from_numpy((np.random.random_sample((num_embeddings, embedding_dim)) + 1).astype(np.float32))\n\n for qdtype in [torch.quint8, torch.quint4x2]:\n obs = PerChannelMinMaxObserver(dtype=qdtype, qscheme=torch.per_channel_affine_float_qparams, ch_axis=0)\n obs(weights)\n # Get the scale and zero point for the weight tensor\n qparams = obs.calculate_qparams()\n # Quantize the weights to 8bits\n qweight = torch.quantize_per_channel(weights, qparams[0], qparams[1], axis=0, dtype=qdtype)\n qemb = nnq.EmbeddingBag(num_embeddings=num_embeddings, embedding_dim=embedding_dim,\n include_last_offset=True, mode='sum', _weight=qweight, dtype=qdtype)\n qemb(indices, offsets)\n\n # Ensure the module has the correct weights\n self.assertEqual(qweight, qemb.weight())\n\n w_packed = qemb._packed_params._packed_weight\n module_out = qemb(indices, offsets)\n\n # Call the qembedding_bag operator directly\n if qdtype == torch.quint8:\n ref = torch.ops.quantized.embedding_bag_byte(w_packed, indices, offsets, mode=0,\n per_sample_weights=None,\n include_last_offset=True)\n else:\n ref = torch.ops.quantized.embedding_bag_4bit(w_packed, indices, offsets, mode=0,\n per_sample_weights=None,\n include_last_offset=True)\n\n self.assertEqual(module_out, ref)\n self.checkEmbeddingSerialization(qemb, num_embeddings, embedding_dim, indices,\n offsets, set_qconfig, is_emb_bag=True, dtype=qdtype)\n\n\nclass TestDynamicQuantizedModule(QuantizationTestCase):\n def _test_qconv_impl(self, q_mod, dq_mod, dim, dtype, bias):\n in_channels = 3\n out_channels = 10\n kernel_size = 2\n stride = 1\n padding = 0\n dilation = 1\n groups = 1\n padding_mode = 'zeros'\n\n if qengine_is_qnnpack():\n reduce_range = False\n else:\n reduce_range = True\n\n X_fp32 = torch.randn(*([in_channels] * dim))\n s, z = _calculate_dynamic_qparams(X_fp32, dtype, reduce_range)\n X_q = torch.quantize_per_tensor(X_fp32, s, z, dtype)\n X_dq = torch.dequantize(X_q)\n\n quantized_module = q_mod(in_channels, out_channels, kernel_size, stride=stride, padding=padding,\n dilation=dilation, groups=groups, bias=bias, padding_mode=padding_mode)\n dynamic_module = dq_mod(in_channels, out_channels, kernel_size, stride=stride, padding=padding,\n dilation=dilation, groups=groups, bias=bias, padding_mode=padding_mode)\n\n quantized_module.scale, quantized_module.zero_point = s, z\n dynamic_module.set_weight_bias(*quantized_module._weight_bias())\n\n Y_q_ref = quantized_module(X_q)\n Y_ref = torch.dequantize(Y_q_ref)\n\n Y = dynamic_module(X_dq, reduce_range)\n\n self.assertEqual(Y, Y_ref)\n\n # Test serialization of quantized Conv Module using state_dict\n W_q, b = dynamic_module._weight_bias()\n model_dict = dynamic_module.state_dict()\n self.assertEqual(model_dict['weight'], W_q)\n self.assertEqual(model_dict['bias'], b)\n bytes_io = io.BytesIO()\n torch.save(model_dict, bytes_io)\n bytes_io.seek(0)\n loaded_dict = torch.load(bytes_io)\n for key in loaded_dict:\n self.assertEqual(model_dict[key], loaded_dict[key])\n loaded_qconv_module = type(dynamic_module)(\n in_channels, out_channels, kernel_size, stride=stride, padding=padding,\n dilation=dilation, groups=groups, bias=bias, padding_mode=padding_mode)\n loaded_qconv_module.load_state_dict(loaded_dict)\n\n self.assertTrue(dir(loaded_qconv_module) == dir(dynamic_module))\n self.assertTrue(dynamic_module._get_name() == loaded_qconv_module._get_name())\n self.assertTrue(hasattr(loaded_qconv_module, '_packed_params'))\n self.assertTrue(hasattr(loaded_qconv_module, '_weight_bias'))\n\n self.assertEqual(dynamic_module.weight(), loaded_qconv_module.weight())\n if bias:\n self.assertEqual(dynamic_module.bias(), loaded_qconv_module.bias())\n self.assertEqual(dynamic_module.scale, loaded_qconv_module.scale)\n self.assertEqual(dynamic_module.zero_point,\n loaded_qconv_module.zero_point)\n Y_loaded = loaded_qconv_module(X_fp32, reduce_range)\n np.testing.assert_array_almost_equal(\n Y.numpy(), Y_loaded.numpy(), decimal=0)\n\n # Test serialization\n b = io.BytesIO()\n torch.save(dynamic_module, b)\n b.seek(0)\n loaded_conv = torch.load(b)\n\n self.assertEqual(loaded_conv.bias(), dynamic_module.bias())\n self.assertEqual(loaded_conv.scale, dynamic_module.scale)\n self.assertEqual(loaded_conv.zero_point,\n dynamic_module.zero_point)\n\n # Test copy and deepcopy\n copied_conv = copy.copy(dynamic_module)\n self.assertEqual(copied_conv.bias(), dynamic_module.bias())\n self.assertEqual(copied_conv.scale, dynamic_module.scale)\n self.assertEqual(copied_conv.zero_point,\n dynamic_module.zero_point)\n Y_copied = copied_conv(X_fp32, reduce_range)\n np.testing.assert_array_almost_equal(\n Y.numpy(), Y_copied.numpy(), decimal=0)\n\n deepcopied_conv = copy.deepcopy(dynamic_module)\n self.assertEqual(deepcopied_conv.bias(), dynamic_module.bias())\n self.assertEqual(deepcopied_conv.scale, dynamic_module.scale)\n self.assertEqual(deepcopied_conv.zero_point,\n dynamic_module.zero_point)\n Y_deepcopied = copied_conv(X_fp32, reduce_range)\n np.testing.assert_array_almost_equal(\n Y.numpy(), Y_deepcopied.numpy(), decimal=0)\n\n # need to fix this\n # JIT testing\n self.checkScriptable(\n dynamic_module, [[X_dq]],\n check_save_load=True)\n\n # Test from_float\n conv_module = dynamic_module._FLOAT_MODULE(in_channels, out_channels, kernel_size)\n conv_module.qconfig = torch.ao.quantization.default_dynamic_qconfig # type: ignore[assignment]\n prepare_dynamic(conv_module)\n conv_module(X_dq)\n quantized_conv_module = dq_mod.from_float(conv_module)\n\n # Smoke test to make sure the module actually runs\n quantized_conv_module(X_dq)\n\n # Smoke test extra_repr\n self.assertEqual(dynamic_module._get_name(), quantized_conv_module._get_name())\n\n @override_qengines\n def test_dynamic_conv1d(self):\n q_mod = torch.nn.quantized.Conv1d\n dq_mod = torch.nn.quantized.dynamic.Conv1d\n dim = 3\n dtype = torch.quint8\n\n for bias in [True, False]:\n self._test_qconv_impl(q_mod, dq_mod, dim, dtype, bias)\n\n @override_qengines\n def test_dynamic_conv2d(self):\n q_mod = torch.nn.quantized.Conv2d\n dq_mod = torch.nn.quantized.dynamic.Conv2d\n dim = 4\n dtype = torch.quint8\n\n for bias in [True, False]:\n self._test_qconv_impl(q_mod, dq_mod, dim, dtype, bias)\n\n @override_qengines\n def test_dynamic_conv3d(self):\n q_mod = torch.nn.quantized.Conv3d\n dq_mod = torch.nn.quantized.dynamic.Conv3d\n dim = 5\n dtype = torch.quint8\n\n if qengine_is_qnnpack():\n return # qnnpack doesn't support unpacking conv3d\n for bias in [True, False]:\n self._test_qconv_impl(q_mod, dq_mod, dim, dtype, bias)\n\n @override_qengines\n def test_dynamic_convtranspose1d(self):\n q_mod = torch.nn.quantized.ConvTranspose1d\n dq_mod = torch.nn.quantized.dynamic.ConvTranspose1d\n dim = 3\n dtype = torch.quint8\n\n for bias in [True, False]:\n self._test_qconv_impl(q_mod, dq_mod, dim, dtype, bias)\n\n @override_qengines\n def test_dynamic_convtranspose2d(self):\n q_mod = torch.nn.quantized.ConvTranspose2d\n dq_mod = torch.nn.quantized.dynamic.ConvTranspose2d\n dim = 4\n dtype = torch.quint8\n\n for bias in [True, False]:\n self._test_qconv_impl(q_mod, dq_mod, dim, dtype, bias)\n\n @override_qengines\n def test_dynamic_convtranspose3d(self):\n q_mod = torch.nn.quantized.ConvTranspose3d\n dq_mod = torch.nn.quantized.dynamic.ConvTranspose3d\n dim = 5\n dtype = torch.quint8\n\n if qengine_is_qnnpack():\n return # qnnpack doesn't support unpacking conv3d\n for bias in [True, False]:\n self._test_qconv_impl(q_mod, dq_mod, dim, dtype, bias)\n\n @given(\n batch_size=st.integers(1, 5),\n in_features=st.integers(16, 32),\n out_features=st.integers(4, 8),\n use_bias=st.booleans(),\n use_default_observer=st.booleans(),\n )\n @override_qengines\n def test_linear_api(self, batch_size, in_features, out_features, use_bias, use_default_observer):\n \"\"\"test API functionality for nn.quantized.dynamic.Linear\"\"\"\n W = torch.rand(out_features, in_features).float()\n W_scale, W_zp = _calculate_dynamic_qparams(W, torch.qint8)\n W_q = torch.quantize_per_tensor(W, W_scale, W_zp, torch.qint8)\n X = torch.rand(batch_size, in_features).float()\n B = torch.rand(out_features).float() if use_bias else None\n qlinear = nnqd.Linear(in_features, out_features)\n # Run module with default-initialized parameters.\n # This tests that the constructor is correct.\n qlinear.set_weight_bias(W_q, B)\n qlinear(X)\n\n # Simple round-trip test to ensure weight()/set_weight() API\n self.assertEqual(qlinear.weight(), W_q)\n W_pack = qlinear._packed_params._packed_params\n Z_dq = qlinear(X)\n\n # Check if the module implementation matches calling the\n # ops directly\n Z_ref = torch.ops.quantized.linear_dynamic(X, W_pack, reduce_range=True)\n self.assertEqual(Z_ref, Z_dq)\n\n # Test serialization of dynamic quantized Linear Module using state_dict\n model_dict = qlinear.state_dict()\n b = io.BytesIO()\n torch.save(model_dict, b)\n b.seek(0)\n loaded_dict = torch.load(b)\n for key in model_dict:\n if isinstance(model_dict[key], torch._C.ScriptObject):\n assert isinstance(loaded_dict[key], torch._C.ScriptObject)\n w_model, b_model = torch.ops.quantized.linear_unpack(model_dict[key])\n w_loaded, b_loaded = torch.ops.quantized.linear_unpack(loaded_dict[key])\n self.assertEqual(w_model, w_loaded)\n self.assertEqual(b_model, b_loaded)\n else:\n self.assertEqual(model_dict[key], loaded_dict[key])\n loaded_qlinear = nnqd.Linear(in_features, out_features)\n loaded_qlinear.load_state_dict(loaded_dict)\n\n linear_unpack = torch.ops.quantized.linear_unpack\n self.assertEqual(linear_unpack(qlinear._packed_params._packed_params),\n linear_unpack(loaded_qlinear._packed_params._packed_params))\n if use_bias:\n self.assertEqual(qlinear.bias(), loaded_qlinear.bias())\n self.assertTrue(dir(qlinear) == dir(loaded_qlinear))\n self.assertTrue(hasattr(qlinear, '_packed_params'))\n self.assertTrue(hasattr(loaded_qlinear, '_packed_params'))\n self.assertTrue(hasattr(qlinear, '_weight_bias'))\n self.assertTrue(hasattr(loaded_qlinear, '_weight_bias'))\n\n self.assertEqual(qlinear._weight_bias(), loaded_qlinear._weight_bias())\n self.assertEqual(qlinear._weight_bias(), torch.ops.quantized.linear_unpack(qlinear._packed_params._packed_params))\n Z_dq2 = qlinear(X)\n self.assertEqual(Z_dq, Z_dq2)\n\n b = io.BytesIO()\n torch.save(qlinear, b)\n b.seek(0)\n loaded = torch.load(b)\n self.assertEqual(qlinear.weight(), loaded.weight())\n self.assertEqual(qlinear.zero_point, loaded.zero_point)\n\n # Test JIT\n self.checkScriptable(qlinear, [[X]], check_save_load=True)\n\n modules_under_test = [torch.nn.Linear, torch.nn.modules.linear.NonDynamicallyQuantizableLinear]\n for mut in modules_under_test:\n # Test from_float\n float_linear = mut(in_features, out_features).float()\n if use_default_observer:\n float_linear.qconfig = torch.ao.quantization.default_dynamic_qconfig\n prepare_dynamic(float_linear)\n float_linear(X.float())\n quantized_float_linear = nnqd.Linear.from_float(float_linear)\n\n # Smoke test to make sure the module actually runs\n quantized_float_linear(X)\n\n # Smoke test extra_repr\n self.assertTrue('QuantizedLinear' in str(quantized_float_linear))\n\n @given(\n dtype=st.sampled_from([torch.qint8, torch.float16]),\n bidirectional=st.booleans(),\n )\n @override_qengines\n def test_lstm_api(self, dtype, bidirectional):\n r\"\"\"Test execution and serialization for dynamic quantized lstm modules on int8 and fp16\n \"\"\"\n # Check that module matches the numerics of the op and ensure that module can be\n # instantiated for all engines and dtypes\n seq_len = 4\n batch = 2\n input_size = 3\n hidden_size = 7\n num_layers = 2\n bias = True\n weight_keys = []\n bias_keys = []\n num_directions = 2 if bidirectional else 1\n for layer in range(num_layers):\n for direction in range(num_directions):\n suffix = '_reverse' if direction == 1 else ''\n key_name1 = 'weight_ih_l{layer_idx}{suffix}'.format(layer_idx=layer, suffix=suffix)\n key_name2 = 'weight_hh_l{layer_idx}{suffix}'.format(layer_idx=layer, suffix=suffix)\n weight_keys.append(key_name1)\n weight_keys.append(key_name2)\n key_name1 = 'bias_ih_l{layer_idx}{suffix}'.format(layer_idx=layer, suffix=suffix)\n key_name2 = 'bias_hh_l{layer_idx}{suffix}'.format(layer_idx=layer, suffix=suffix)\n bias_keys.append(key_name1)\n bias_keys.append(key_name2)\n\n if not (dtype == torch.float16 and torch.backends.quantized.engine == \"qnnpack\"):\n # fp16 dynamic quant is not supported for qnnpack\n x = torch.randn(seq_len, batch, input_size)\n h = torch.randn(num_layers * (bidirectional + 1), batch, hidden_size)\n c = torch.randn(num_layers * (bidirectional + 1), batch, hidden_size)\n cell_dq = torch.nn.quantized.dynamic.LSTM(input_size=input_size,\n hidden_size=hidden_size,\n num_layers=num_layers,\n bias=bias,\n batch_first=False,\n dropout=0.0,\n bidirectional=bidirectional,\n dtype=dtype)\n ref_dq = torch.nn.quantized.dynamic.LSTM(input_size=input_size,\n hidden_size=hidden_size,\n num_layers=num_layers,\n bias=bias,\n batch_first=False,\n dropout=0.0,\n bidirectional=bidirectional,\n dtype=dtype)\n\n _all_params = ([m.param for m in cell_dq._all_weight_values])\n result = torch.quantized_lstm(x, (h, c),\n _all_params,\n cell_dq.bias,\n cell_dq.num_layers,\n float(cell_dq.dropout),\n False,\n bidirectional,\n False,\n dtype=dtype,\n use_dynamic=True)\n\n\n y, (h, c) = cell_dq(x, (h, c))\n self.assertEqual(result[0], y)\n self.assertEqual(result[1], h)\n self.assertEqual(result[2], c)\n x = torch.randn(10, 20, 3)\n self.check_eager_serialization(cell_dq, ref_dq, [x])\n self.check_weight_bias_api(cell_dq, weight_keys, bias_keys)\n\n @override_qengines\n def test_gru_api(self):\n r\"\"\"Test execution and serialization for dynamic quantized lstm modules on int8 and fp16\n \"\"\"\n # Check that module matches the numerics of the op and ensure that module can be\n # instantiated for all engines and dtypes\n\n for dtype in [torch.qint8, torch.float16]:\n if dtype == torch.float16 and torch.backends.quantized.engine == \"qnnpack\":\n # fp16 dynamic quant is not supported for qnnpack\n continue\n # Test default instantiation\n seq_len = 4\n batch = 2\n input_size = 3\n hidden_size = 7\n num_layers = 2\n bias = True\n bidirectional = False\n\n x = torch.rand(seq_len, batch, input_size)\n h = torch.rand(num_layers * (bidirectional + 1), batch, hidden_size)\n\n\n cell_dq = torch.nn.quantized.dynamic.GRU(input_size=input_size,\n hidden_size=hidden_size,\n num_layers=num_layers,\n bias=bias,\n batch_first=False,\n dropout=0.0,\n bidirectional=bidirectional,\n dtype=dtype)\n\n _all_params = ([m.param for m in cell_dq._all_weight_values])\n result = torch.quantized_gru(x,\n h,\n _all_params,\n cell_dq.bias,\n cell_dq.num_layers,\n float(cell_dq.dropout),\n False,\n bidirectional,\n False)\n\n\n y, h = cell_dq(x, h)\n self.assertEqual(result[0], y, msg=\"GRU module API failed\")\n self.assertEqual(result[1], h, msg=\"GRU module API failed\")\n\n @given(\n dtype=st.sampled_from([torch.qint8, torch.float16]),\n )\n @override_qengines\n def test_cell_api(self, dtype):\n r\"\"\"Test execution and serialization for dynamic quantized lstm modules on int8 and fp16\n \"\"\"\n # Check that module matches the numerics of the op and ensure that module can be\n # instantiated for all engines and dtypes\n batch = 7\n input_size = 3\n hidden_size = 7\n bias = True\n\n x = torch.rand(batch, input_size)\n h = torch.rand(batch, hidden_size)\n cell_dict = {'LSTMCell': torch.nn.quantized.dynamic.LSTMCell,\n 'GRUCell': torch.nn.quantized.dynamic.GRUCell,\n 'RNNTanh': torch.nn.quantized.dynamic.RNNCell,\n 'RNNReLU': torch.nn.quantized.dynamic.RNNCell\n }\n state = {'LSTMCell': (h, h),\n 'GRUCell': h,\n 'RNNTanh': h,\n 'RNNReLU': h}\n\n qfn_dict = {'LSTMCell': torch.ops.quantized.quantized_lstm_cell_dynamic,\n 'GRUCell': torch.ops.quantized.quantized_gru_cell_dynamic,\n 'RNNTanh': torch.ops.quantized.quantized_rnn_tanh_cell_dynamic,\n 'RNNReLU': torch.ops.quantized.quantized_rnn_relu_cell_dynamic}\n\n for rnn_type in cell_dict.keys():\n if not (dtype == torch.float16 and torch.backends.quantized.engine == \"qnnpack\"):\n # fp16 dynamic quant is not supported for qnnpack\n kwargs = {'input_size': input_size, 'hidden_size': hidden_size, 'bias': bias, 'dtype': dtype}\n if rnn_type == 'RNNReLU':\n kwargs['nonlinearity'] = \"relu\"\n elif rnn_type == 'RNNTanh':\n kwargs['nonlinearity'] = \"tanh\"\n\n cell_dq = cell_dict[rnn_type](**kwargs)\n result = qfn_dict[rnn_type](x, state[rnn_type],\n cell_dq._packed_weight_ih, cell_dq._packed_weight_hh,\n cell_dq.bias_ih, cell_dq.bias_hh)\n result_module = cell_dq(x, state[rnn_type])\n self.assertEqual(result[0], result_module[0], msg=\"RNNCell module API failed\")\n self.assertEqual(result[1], result_module[1], msg=\"RNNCell module API failed\")\n weight_keys = ['weight_ih', 'weight_hh']\n bias_keys = ['bias_ih', 'bias_hh']\n self.check_eager_serialization(cell_dq, cell_dict[rnn_type](**kwargs), [x])\n self.check_weight_bias_api(cell_dq, weight_keys, bias_keys)\n", "import torch\nfrom torch import nn\nimport torch.nn.functional as nnF\nimport torch.nn.quantized as nnq\n\nfrom torch import Tensor\nfrom typing import Optional, Tuple\n\nimport warnings\n\nclass MultiheadAttention(nn.MultiheadAttention):\n _FLOAT_MODULE = nn.MultiheadAttention\n\n r\"\"\"Quantizable implementation of the MultiheadAttention.\n\n Note::\n Please, refer to :class:`~torch.nn.MultiheadAttention` for more\n information\n\n Allows the model to jointly attend to information from different\n representation subspaces.\n See reference: Attention Is All You Need\n\n The original MHA module is not quantizable.\n This reimplements it by explicitly instantiating the linear layers.\n\n .. math::\n \\text{MultiHead}(Q, K, V) = \\text{Concat}(head_1,\\dots,head_h)W^O\n \\text{where} head_i = \\text{Attention}(QW_i^Q, KW_i^K, VW_i^V)\n\n Args:\n embed_dim: total dimension of the model.\n num_heads: parallel attention heads.\n dropout: a Dropout layer on attn_output_weights. Default: 0.0.\n bias: add bias as module parameter. Default: True.\n add_bias_kv: add bias to the key and value sequences at dim=0.\n add_zero_attn: add a new batch of zeros to the key and\n value sequences at dim=1.\n kdim: total number of features in key. Default: None.\n vdim: total number of features in value. Default: None.\n batch_first: If ``True``, then the input and output tensors are provided\n as (batch, seq, feature). Default: ``False`` (seq, batch, feature).\n\n Note that if :attr:`kdim` and :attr:`vdim` are None, they will be set\n to :attr:`embed_dim` such that query, key, and value have the same\n number of features.\n\n Examples::\n\n >>> import torch.nn.quantizable as nnqa\n >>> multihead_attn = nnqa.MultiheadAttention(embed_dim, num_heads)\n >>> attn_output, attn_output_weights = multihead_attn(query, key, value)\n\n Note::\n Please, follow the quantization flow to convert the quantizable MHA.\n \"\"\"\n __constants__ = ['batch_first']\n\n def __init__(self, embed_dim: int, num_heads: int,\n dropout: float = 0., bias: bool = True,\n add_bias_kv: bool = False, add_zero_attn: bool = False,\n kdim: int = None, vdim: int = None, batch_first: bool = False,\n device=None, dtype=None) -> None:\n factory_kwargs = {'device': device, 'dtype': dtype}\n super(MultiheadAttention, self).__init__(embed_dim, num_heads, dropout,\n bias, add_bias_kv,\n add_zero_attn, kdim, vdim, batch_first,\n **factory_kwargs)\n self.linear_Q = nn.Linear(self.embed_dim, self.embed_dim, bias=bias, **factory_kwargs)\n self.linear_K = nn.Linear(self.kdim, self.embed_dim, bias=bias, **factory_kwargs)\n self.linear_V = nn.Linear(self.vdim, self.embed_dim, bias=bias, **factory_kwargs)\n # for the type: ignore, see https://github.com/pytorch/pytorch/issues/58969\n self.out_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=bias, **factory_kwargs) # type: ignore[assignment]\n\n # Functionals\n self.q_scaling_product = nnq.FloatFunctional()\n\n # Quant/Dequant\n self.quant_attn_output = torch.ao.quantization.QuantStub()\n self.quant_attn_output_weights = torch.ao.quantization.QuantStub()\n self.dequant_q = torch.ao.quantization.DeQuantStub()\n self.dequant_k = torch.ao.quantization.DeQuantStub()\n self.dequant_v = torch.ao.quantization.DeQuantStub()\n\n def _get_name(self):\n return 'QuantizableMultiheadAttention'\n\n @classmethod\n def from_float(cls, other):\n assert type(other) == cls._FLOAT_MODULE\n assert hasattr(other, 'qconfig'), \"The float module must have 'qconfig'\"\n # Setting the dropout to 0.0!\n observed = cls(other.embed_dim, other.num_heads, other.dropout,\n (other.in_proj_bias is not None),\n (other.bias_k is not None),\n other.add_zero_attn, other.kdim, other.vdim)\n observed.bias_k = other.bias_k\n observed.bias_v = other.bias_v\n observed.qconfig = other.qconfig\n\n # Set the linear weights\n # for the type: ignores, see https://github.com/pytorch/pytorch/issues/58969\n observed.out_proj.weight = other.out_proj.weight # type: ignore[has-type]\n observed.out_proj.bias = other.out_proj.bias # type: ignore[has-type]\n if other._qkv_same_embed_dim:\n # Use separate params\n bias = other.in_proj_bias\n _start = 0\n _end = _start + other.embed_dim\n weight = other.in_proj_weight[_start:_end, :]\n if bias is not None:\n bias = torch.nn.Parameter(bias[_start:_end], bias.requires_grad)\n observed.linear_Q.weight = torch.nn.Parameter(weight,\n weight.requires_grad)\n observed.linear_Q.bias = bias\n\n bias = other.in_proj_bias\n _start = _end\n _end = _start + other.embed_dim\n weight = other.in_proj_weight[_start:_end, :]\n if bias is not None:\n bias = torch.nn.Parameter(bias[_start:_end], bias.requires_grad)\n observed.linear_K.weight = torch.nn.Parameter(weight,\n weight.requires_grad)\n observed.linear_K.bias = bias\n\n bias = other.in_proj_bias\n _start = _end\n weight = other.in_proj_weight[_start:, :]\n if bias is not None:\n bias = torch.nn.Parameter(bias[_start:], bias.requires_grad)\n observed.linear_V.weight = torch.nn.Parameter(weight,\n weight.requires_grad)\n observed.linear_V.bias = bias\n else:\n observed.linear_Q.weight = nn.Parameter(other.q_proj_weight)\n observed.linear_K.weight = nn.Parameter(other.k_proj_weight)\n observed.linear_V.weight = nn.Parameter(other.v_proj_weight)\n if other.in_proj_bias is None:\n observed.linear_Q.bias = None # type: ignore[assignment]\n observed.linear_K.bias = None # type: ignore[assignment]\n observed.linear_V.bias = None # type: ignore[assignment]\n else:\n observed.linear_Q.bias = nn.Parameter(other.in_proj_bias[0:other.embed_dim])\n observed.linear_K.bias = nn.Parameter(other.in_proj_bias[other.embed_dim:(other.embed_dim * 2)])\n observed.linear_V.bias = nn.Parameter(other.in_proj_bias[(other.embed_dim * 2):])\n observed.eval()\n # Explicit prepare\n observed = torch.ao.quantization.prepare(observed, inplace=True)\n return observed\n\n @torch.jit.unused\n def dequantize(self):\n r\"\"\"Utility to convert the quantized MHA back to float.\n\n The motivation for this is that it is not trivial to conver the weights\n from the format that is used in the quantized version back to the\n float.\n \"\"\"\n fp = self._FLOAT_MODULE(self.embed_dim, self.num_heads, self.dropout,\n (self.in_proj_bias is not None),\n (self.bias_k is not None),\n self.add_zero_attn, self.kdim, self.vdim, self.batch_first)\n assert fp._qkv_same_embed_dim == self._qkv_same_embed_dim\n if self.bias_k is not None:\n fp.bias_k = nn.Parameter(self.bias_k.dequantize())\n if self.bias_v is not None:\n fp.bias_v = nn.Parameter(self.bias_v.dequantize())\n\n # Set the linear weights\n # Note: Because the linear layers are quantized, mypy does not nkow how\n # to deal with them -- might need to ignore the typing checks.\n # for the type: ignore[has-type], see https://github.com/pytorch/pytorch/issues/58969\n w, b = self.out_proj._weight_bias() # type: ignore[operator, has-type]\n fp.out_proj.weight = nn.Parameter(w.dequantize())\n if b is not None:\n fp.out_proj.bias = nn.Parameter(b)\n\n wQ, bQ = self.linear_Q._weight_bias() # type: ignore[operator]\n wQ = wQ.dequantize()\n wK, bK = self.linear_K._weight_bias() # type: ignore[operator]\n wK = wK.dequantize()\n wV, bV = self.linear_V._weight_bias() # type: ignore[operator]\n wV = wV.dequantize()\n if fp._qkv_same_embed_dim:\n # Use separate params\n _start = 0\n _end = _start + fp.embed_dim\n fp.in_proj_weight[_start:_end, :] = wQ\n if fp.in_proj_bias is not None:\n assert all(bQ == 0)\n fp.in_proj_bias[_start:_end] = bQ\n\n _start = _end\n _end = _start + fp.embed_dim\n fp.in_proj_weight[_start:_end, :] = wK\n if fp.in_proj_bias is not None:\n assert all(bK == 0)\n fp.in_proj_bias[_start:_end] = bK\n\n _start = _end\n fp.in_proj_weight[_start:, :] = wV\n if fp.in_proj_bias is not None:\n assert all(bV == 0)\n fp.in_proj_bias[_start:] = bV\n else:\n fp.q_proj_weight = nn.Parameter(wQ)\n fp.k_proj_weight = nn.Parameter(wK)\n fp.v_proj_weight = nn.Parameter(wV)\n if fp.in_proj_bias is None:\n self.linear_Q.bias = None\n self.linear_K.bias = None\n self.linear_V.bias = None\n else:\n fp.in_proj_bias[0:fp.embed_dim] = bQ\n fp.in_proj_bias[fp.embed_dim:(fp.embed_dim * 2)] = bK\n fp.in_proj_bias[(fp.embed_dim * 2):] = bV\n\n return fp\n\n\n @classmethod\n def from_observed(cls, other):\n converted = torch.ao.quantization.convert(other, mapping=None,\n inplace=False,\n remove_qconfig=True,\n convert_custom_config_dict=None)\n # Remove the parameters for the bias_k and bias_v to quantize them\n # TODO: This is a potential source of accuracy drop.\n # quantized cat takes the scale and zp of the first\n # element, which might lose the precision in the bias_k\n # and the bias_v (which are cat'ed with k/v being first).\n if converted.bias_k is not None:\n bias_k = converted._parameters.pop('bias_k')\n sc, zp = torch._choose_qparams_per_tensor(bias_k,\n reduce_range=False)\n bias_k = torch.quantize_per_tensor(bias_k, sc, zp, torch.quint8)\n setattr(converted, 'bias_k', bias_k) # noqa: B010\n\n if converted.bias_v is not None:\n bias_v = converted._parameters.pop('bias_v')\n sc, zp = torch._choose_qparams_per_tensor(bias_k,\n reduce_range=False)\n bias_v = torch.quantize_per_tensor(bias_v, sc, zp, torch.quint8)\n setattr(converted, 'bias_v', bias_v) # noqa: B010\n\n return converted\n\n def forward(self,\n query: Tensor,\n key: Tensor,\n value: Tensor,\n key_padding_mask: Optional[Tensor] = None,\n need_weights: bool = True,\n attn_mask: Optional[Tensor] = None,\n average_attn_weights: bool = True) -> Tuple[Tensor, Optional[Tensor]]:\n r\"\"\"\n Note::\n Please, refer to :func:`~torch.nn.MultiheadAttention.forward` for more\n information\n\n Args:\n query, key, value: map a query and a set of key-value pairs to an output.\n See \"Attention Is All You Need\" for more details.\n key_padding_mask: if provided, specified padding elements in the key will\n be ignored by the attention. When given a binary mask and a value is True,\n the corresponding value on the attention layer will be ignored. When given\n a byte mask and a value is non-zero, the corresponding value on the attention\n layer will be ignored\n need_weights: output attn_output_weights.\n attn_mask: 2D or 3D mask that prevents attention to certain positions. A 2D mask will be broadcasted for all\n the batches while a 3D mask allows to specify a different mask for the entries of each batch.\n\n Shape:\n - Inputs:\n - query: :math:`(L, N, E)` where L is the target sequence length, N is the batch size, E is\n the embedding dimension. :math:`(N, L, E)` if ``batch_first`` is ``True``.\n - key: :math:`(S, N, E)`, where S is the source sequence length, N is the batch size, E is\n the embedding dimension. :math:`(N, S, E)` if ``batch_first`` is ``True``.\n - value: :math:`(S, N, E)` where S is the source sequence length, N is the batch size, E is\n the embedding dimension. :math:`(N, S, E)` if ``batch_first`` is ``True``.\n - key_padding_mask: :math:`(N, S)` where N is the batch size, S is the source sequence length.\n If a ByteTensor is provided, the non-zero positions will be ignored while the position\n with the zero positions will be unchanged. If a BoolTensor is provided, the positions with the\n value of ``True`` will be ignored while the position with the value of ``False`` will be unchanged.\n - attn_mask: 2D mask :math:`(L, S)` where L is the target sequence length, S is the source sequence length.\n 3D mask :math:`(N*num_heads, L, S)` where N is the batch size, L is the target sequence length,\n S is the source sequence length. attn_mask ensure that position i is allowed to attend the unmasked\n positions. If a ByteTensor is provided, the non-zero positions are not allowed to attend\n while the zero positions will be unchanged. If a BoolTensor is provided, positions with ``True``\n is not allowed to attend while ``False`` values will be unchanged. If a FloatTensor\n is provided, it will be added to the attention weight.\n - average_attn_weights: If true, indicates that the returned ``attn_weights`` should be averaged across\n heads. Otherwise, ``attn_weights`` are provided separately per head. Note that this flag only has an\n effect when ``need_weights=True.``. Default: True (i.e. average weights across heads)\n\n - Outputs:\n - attn_output: :math:`(L, N, E)` where L is the target sequence length, N is the batch size,\n E is the embedding dimension. :math:`(N, L, E)` if ``batch_first`` is ``True``.\n - attn_output_weights: If ``average_attn_weights=True``, returns attention weights averaged\n across heads of shape :math:`(N, L, S)`, where N is the batch size, L is the target sequence length,\n S is the source sequence length. If ``average_weights=False``, returns attention weights per\n head of shape :math:`(N, num_heads, L, S)`.\n \"\"\"\n return self._forward_impl(query, key, value, key_padding_mask,\n need_weights, attn_mask, average_attn_weights)\n\n def _forward_impl(self,\n query: Tensor,\n key: Tensor,\n value: Tensor,\n key_padding_mask: Optional[Tensor] = None,\n need_weights: bool = True,\n attn_mask: Optional[Tensor] = None,\n average_attn_weights: bool = True) -> Tuple[Tensor, Optional[Tensor]]:\n # This version will not deal with the static key/value pairs.\n # Keeping it here for future changes.\n #\n # TODO: This method has some duplicate lines with the\n # `torch.nn.functional.multi_head_attention`. Will need to refactor.\n static_k = None\n static_v = None\n\n if self.batch_first:\n query, key, value = [x.transpose(0, 1) for x in (query, key, value)]\n\n tgt_len, bsz, embed_dim_to_check = query.size()\n assert self.embed_dim == embed_dim_to_check\n # allow MHA to have different sizes for the feature dimension\n assert key.size(0) == value.size(0) and key.size(1) == value.size(1)\n\n head_dim = self.embed_dim // self.num_heads\n assert head_dim * self.num_heads == self.embed_dim, \"embed_dim must be divisible by num_heads\"\n scaling = float(head_dim) ** -0.5\n\n q = self.linear_Q(query)\n k = self.linear_K(key)\n v = self.linear_V(value)\n\n q = self.q_scaling_product.mul_scalar(q, scaling)\n\n if attn_mask is not None:\n assert attn_mask.dtype == torch.float32 or attn_mask.dtype == torch.float64 or \\\n attn_mask.dtype == torch.float16 or attn_mask.dtype == torch.uint8 or attn_mask.dtype == torch.bool, \\\n 'Only float, byte, and bool types are supported for attn_mask, not {}'.format(attn_mask.dtype)\n if attn_mask.dtype == torch.uint8:\n warnings.warn(\"Byte tensor for attn_mask in nn.MultiheadAttention is deprecated. Use bool tensor instead.\")\n attn_mask = attn_mask.to(torch.bool)\n\n if attn_mask.dim() == 2:\n attn_mask = attn_mask.unsqueeze(0)\n if list(attn_mask.size()) != [1, query.size(0), key.size(0)]:\n raise RuntimeError('The size of the 2D attn_mask is not correct.')\n elif attn_mask.dim() == 3:\n if list(attn_mask.size()) != [bsz * self.num_heads, query.size(0), key.size(0)]:\n raise RuntimeError('The size of the 3D attn_mask is not correct.')\n else:\n raise RuntimeError(\"attn_mask's dimension {} is not supported\".format(attn_mask.dim()))\n # attn_mask's dim is 3 now.\n\n # convert ByteTensor key_padding_mask to bool\n if key_padding_mask is not None and key_padding_mask.dtype == torch.uint8:\n warnings.warn(\"Byte tensor for key_padding_mask in nn.MultiheadAttention is deprecated. Use bool tensor instead.\")\n key_padding_mask = key_padding_mask.to(torch.bool)\n if self.bias_k is not None and self.bias_v is not None:\n if static_k is None and static_v is None:\n\n # Explicitly assert that bias_k and bias_v are not None\n # in a way that TorchScript can understand.\n bias_k = self.bias_k\n assert bias_k is not None\n bias_v = self.bias_v\n assert bias_v is not None\n\n k = torch.cat([k, bias_k.repeat(1, bsz, 1)])\n v = torch.cat([v, bias_v.repeat(1, bsz, 1)])\n if attn_mask is not None:\n attn_mask = nnF.pad(attn_mask, (0, 1))\n if key_padding_mask is not None:\n key_padding_mask = nnF.pad(key_padding_mask, (0, 1))\n else:\n assert static_k is None, \"bias cannot be added to static key.\"\n assert static_v is None, \"bias cannot be added to static value.\"\n else:\n assert self.bias_k is None\n assert self.bias_v is None\n\n q = q.contiguous().view(tgt_len, bsz * self.num_heads, head_dim).transpose(0, 1)\n if k is not None:\n k = k.contiguous().view(-1, bsz * self.num_heads, head_dim).transpose(0, 1)\n if v is not None:\n v = v.contiguous().view(-1, bsz * self.num_heads, head_dim).transpose(0, 1)\n\n if static_k is not None:\n assert static_k.size(0) == bsz * self.num_heads\n assert static_k.size(2) == head_dim\n k = static_k\n\n if static_v is not None:\n assert static_v.size(0) == bsz * self.num_heads\n assert static_v.size(2) == head_dim\n v = static_v\n\n src_len = k.size(1)\n\n if key_padding_mask is not None:\n assert key_padding_mask.size(0) == bsz\n assert key_padding_mask.size(1) == src_len\n\n if self.add_zero_attn:\n src_len += 1\n k_zeros = torch.zeros((k.size(0), 1) + k.size()[2:])\n if k.is_quantized:\n k_zeros = torch.quantize_per_tensor(k_zeros, k.q_scale(), k.q_zero_point(), k.dtype)\n k = torch.cat([k, k_zeros], dim=1)\n v_zeros = torch.zeros((v.size(0), 1) + k.size()[2:])\n if v.is_quantized:\n v_zeros = torch.quantize_per_tensor(v_zeros, v.q_scale(), v.q_zero_point(), v.dtype)\n v = torch.cat([v, v_zeros], dim=1)\n\n if attn_mask is not None:\n attn_mask = nnF.pad(attn_mask, (0, 1))\n if key_padding_mask is not None:\n key_padding_mask = nnF.pad(key_padding_mask, (0, 1))\n\n # Leaving the quantized zone here\n q = self.dequant_q(q)\n k = self.dequant_k(k)\n v = self.dequant_v(v)\n attn_output_weights = torch.bmm(q, k.transpose(1, 2))\n assert list(attn_output_weights.size()) == [bsz * self.num_heads, tgt_len, src_len]\n\n if attn_mask is not None:\n if attn_mask.dtype == torch.bool:\n attn_output_weights.masked_fill_(attn_mask, float('-inf'))\n else:\n attn_output_weights += attn_mask\n\n if key_padding_mask is not None:\n attn_output_weights = attn_output_weights.view(bsz, self.num_heads, tgt_len, src_len)\n attn_output_weights = attn_output_weights.masked_fill(\n key_padding_mask.unsqueeze(1).unsqueeze(2),\n float('-inf'),\n )\n attn_output_weights = attn_output_weights.view(bsz * self.num_heads, tgt_len, src_len)\n\n attn_output_weights = nnF.softmax(\n attn_output_weights, dim=-1)\n attn_output_weights = nnF.dropout(attn_output_weights, p=self.dropout, training=self.training)\n\n attn_output = torch.bmm(attn_output_weights, v)\n assert list(attn_output.size()) == [bsz * self.num_heads, tgt_len, head_dim]\n if self.batch_first:\n attn_output = attn_output.view(bsz, tgt_len, self.embed_dim)\n else:\n attn_output = attn_output.transpose(0, 1).contiguous().view(tgt_len, bsz, self.embed_dim)\n\n # Reentering the quantized zone\n attn_output = self.quant_attn_output(attn_output)\n # for the type: ignore[has-type], see https://github.com/pytorch/pytorch/issues/58969\n attn_output = self.out_proj(attn_output) # type: ignore[has-type]\n attn_output_weights = self.quant_attn_output_weights(attn_output_weights)\n\n if need_weights:\n # average attention weights over heads\n attn_output_weights = attn_output_weights.view(bsz, self.num_heads, tgt_len, src_len)\n if average_attn_weights:\n attn_output_weights = attn_output_weights.mean(dim=1)\n return attn_output, attn_output_weights\n else:\n return attn_output, None\n" ]
[ [ "torch.distributed._fsdp.fully_sharded_data_parallel.CPUOffload", "torch.autograd.graph.save_on_cpu", "torch.cuda.manual_seed", "torch.cuda.current_device", "torch.manual_seed", "torch.profiler.profile", "torch.nn.Linear", "torch.utils.checkpoint.checkpoint", "torch.testing._internal.common_distributed.skip_if_lt_x_gpu", "torch.testing._internal.common_utils.run_tests", "torch.testing._internal.common_utils.parametrize", "torch.testing._internal.common_utils.instantiate_parametrized_tests" ], [ "torch.ao.quantization.stubs.QuantWrapper", "torch.ao.quantization.qconfig.assert_valid_qconfig", "torch.ao.quantization.quantization_mappings._has_special_act_post_process", "torch.ao.quantization.quantization_mappings.get_default_static_quant_module_mappings", "torch.ao.quantization.quantization_mappings.get_default_qconfig_propagation_list", "torch.ao.quantization.quantization_mappings.get_default_qat_module_mappings", "torch._C._log_api_usage_once", "torch.ao.quantization.qconfig.activation_is_memoryless", "torch.ao.quantization.quantization_mappings.no_observer_set", "torch.ao.quantization.quantization_mappings.get_default_dynamic_quant_module_mappings", "torch.ao.quantization.quantization_mappings._get_special_act_post_process", "torch.ao.quantization.qconfig.add_module_to_qconfig_obs_ctr" ], [ "torch.ao.quantization.prepare", "torch.testing._internal.common_quantization.lengths_to_offsets", "torch.ops.quantized.linear", "torch.load", "torch.zeros", "torch.nn.quantized.Embedding", "torch.ops.quantized.linear_dynamic", "numpy.random.random_sample", "torch.nn.quantized.dynamic.LSTM", "torch.nn.quantized.ReLU6", "torch.nn.quantized.dynamic.Linear.from_float", "torch.nn.quantized.MaxPool2d", "torch.nn.quantized.Quantize", "torch.allclose", "torch.testing._internal.common_quantized.override_quantized_engine", "torch.nn.intrinsic.ConvReLU3d", "torch.save", "numpy.random.randint", "torch.ops.quantized.linear_relu", "torch.testing._internal.common_quantized._calculate_dynamic_qparams", "torch.testing._internal.common_quantization.prepare_dynamic", "torch.ones", "torch.ao.quantization.convert", "torch.nn.quantized.EmbeddingBag", "torch.randn", "torch.ao.quantization.PerChannelMinMaxObserver", "torch.tensor", "torch.ops.quantized.embedding_bag_4bit", "torch.relu", "torch.ao.quantization.get_default_static_quant_module_mappings", "torch.quantize_per_tensor", "torch.rand", "torch.nn.quantized.LeakyReLU", "torch.arange", "torch.ao.quantization.DeQuantStub", "torch.nn.GroupNorm", "torch.nn.functional.max_pool2d", "torch.nn.Sequential", "torch.nn.modules.ReLU6", "torch.testing._internal.common_quantization._make_conv_test_input", "torch.nn.intrinsic._FusedModule", "torch.nn.Conv2d", "torch.nn.quantized.BatchNorm3d", "torch.nn.quantized.GroupNorm", "torch.nn.intrinsic.ConvReLU1d", "torch.nn.Conv3d", "torch.testing._internal.hypothesis_utils.assert_deadline_disabled", "torch.nn.quantized.BatchNorm2d", "torch.ao.quantization.QuantStub", "torch.nn.BatchNorm2d", "torch.nn.Conv1d", "numpy.sum", "torch.ops.quantized.embedding_bag_byte", "torch.nn.quantized.DeQuantize", "torch.nn.quantized.dynamic.Linear", "torch.nn.intrinsic.ConvReLU2d", "torch.testing._internal.common_quantized.qengine_is_qnnpack", "torch.ops.quantized.linear_unpack", "torch.nn.quantized.dynamic.GRU", "torch.quantize_per_channel", "torch.dequantize", "torch.ao.quantization.default_float_qparams_observer", "torch.nn.ReLU", "torch.nn.BatchNorm3d", "torch.ops.quantized.embedding_byte" ], [ "torch.ao.quantization.prepare", "torch.nn.functional.softmax", "torch.nn.Parameter", "torch._choose_qparams_per_tensor", "torch.ao.quantization.convert", "torch.nn.functional.dropout", "torch.cat", "torch.nn.Linear", "torch.ao.quantization.DeQuantStub", "torch.ao.quantization.QuantStub", "torch.bmm", "torch.quantize_per_tensor", "torch.nn.quantized.FloatFunctional", "torch.nn.functional.pad" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
AngeloMono/yolact
[ "3be8b635972cfec845eaf7e0fa7d380d7a002c27" ]
[ "train.py" ]
[ "from data import *\nfrom yolact_utils.augmentations import SSDAugmentation, BaseTransform\nfrom yolact_utils.functions import MovingAverage, SavePath\nfrom yolact_utils.logger import Log\nfrom yolact_utils import timer\nfrom layers.modules import MultiBoxLoss\nfrom yolact import Yolact\nimport os\nimport sys\nimport time\nimport math, random\nfrom pathlib import Path\nimport torch\nfrom torch.autograd import Variable\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.backends.cudnn as cudnn\nimport torch.nn.init as init\nimport torch.utils.data as data\nimport numpy as np\nimport argparse\nimport datetime\n\n# Oof\nimport eval as eval_script\n\ndef str2bool(v):\n return v.lower() in (\"yes\", \"true\", \"t\", \"1\")\n\n\nparser = argparse.ArgumentParser(\n description='Yolact Training Script')\nparser.add_argument('--batch_size', default=8, type=int,\n help='Batch size for training')\nparser.add_argument('--resume', default=None, type=str,\n help='Checkpoint state_dict file to resume training from. If this is \"interrupt\"'\\\n ', the model will resume training from the interrupt file.')\nparser.add_argument('--start_iter', default=-1, type=int,\n help='Resume training at this iter. If this is -1, the iteration will be'\\\n 'determined from the file name.')\nparser.add_argument('--num_workers', default=4, type=int,\n help='Number of workers used in dataloading')\nparser.add_argument('--cuda', default=True, type=str2bool,\n help='Use CUDA to train model')\nparser.add_argument('--lr', '--learning_rate', default=None, type=float,\n help='Initial learning rate. Leave as None to read this from the config.')\nparser.add_argument('--momentum', default=None, type=float,\n help='Momentum for SGD. Leave as None to read this from the config.')\nparser.add_argument('--decay', '--weight_decay', default=None, type=float,\n help='Weight decay for SGD. Leave as None to read this from the config.')\nparser.add_argument('--gamma', default=None, type=float,\n help='For each lr step, what to multiply the lr by. Leave as None to read this from the config.')\nparser.add_argument('--save_folder', default='weights/',\n help='Directory for saving checkpoint models.')\nparser.add_argument('--log_folder', default='logs/',\n help='Directory for saving logs.')\nparser.add_argument('--config', default=None,\n help='The config object to use.')\nparser.add_argument('--save_interval', default=10000, type=int,\n help='The number of iterations between saving the model.')\nparser.add_argument('--validation_size', default=5000, type=int,\n help='The number of images to use for validation.')\nparser.add_argument('--validation_epoch', default=2, type=int,\n help='Output validation information every n iterations. If -1, do no validation.')\nparser.add_argument('--keep_latest', dest='keep_latest', action='store_true',\n help='Only keep the latest checkpoint instead of each one.')\nparser.add_argument('--keep_latest_interval', default=100000, type=int,\n help='When --keep_latest is on, don\\'t delete the latest file at these intervals. This should be a multiple of save_interval or 0.')\nparser.add_argument('--dataset', default=None, type=str,\n help='If specified, override the dataset specified in the config with this one (example: coco2017_dataset).')\nparser.add_argument('--no_log', dest='log', action='store_false',\n help='Don\\'t log per iteration information into log_folder.')\nparser.add_argument('--log_gpu', dest='log_gpu', action='store_true',\n help='Include GPU information in the logs. Nvidia-smi tends to be slow, so set this with caution.')\nparser.add_argument('--no_interrupt', dest='interrupt', action='store_false',\n help='Don\\'t save an interrupt when KeyboardInterrupt is caught.')\nparser.add_argument('--batch_alloc', default=None, type=str,\n help='If using multiple GPUS, you can set this to be a comma separated list detailing which GPUs should get what local batch size (It should add up to your total batch size).')\nparser.add_argument('--no_autoscale', dest='autoscale', action='store_false',\n help='YOLACT will automatically scale the lr and the number of iterations depending on the batch size. Set this if you want to disable that.')\n\nparser.set_defaults(keep_latest=False, log=True, log_gpu=False, interrupt=True, autoscale=True)\nargs = parser.parse_args()\n\nif args.config is not None:\n set_cfg(args.config)\n\nif args.dataset is not None:\n set_dataset(args.dataset)\n\nif args.autoscale and args.batch_size != 8:\n factor = args.batch_size / 8\n if __name__ == '__main__':\n print('Scaling parameters by %.2f to account for a batch size of %d.' % (factor, args.batch_size))\n\n cfg.lr *= factor\n cfg.max_iter //= factor\n cfg.lr_steps = [x // factor for x in cfg.lr_steps]\n\n# Update training parameters from the config if necessary\ndef replace(name):\n if getattr(args, name) == None: setattr(args, name, getattr(cfg, name))\nreplace('lr')\nreplace('decay')\nreplace('gamma')\nreplace('momentum')\n\n# This is managed by set_lr\ncur_lr = args.lr\n\nif torch.cuda.device_count() == 0:\n print('No GPUs detected. Exiting...')\n exit(-1)\n\nif args.batch_size // torch.cuda.device_count() < 6:\n if __name__ == '__main__':\n print('Per-GPU batch size is less than the recommended limit for batch norm. Disabling batch norm.')\n cfg.freeze_bn = True\n\nloss_types = ['B', 'C', 'M', 'P', 'D', 'E', 'S', 'I']\n\nif torch.cuda.is_available():\n if args.cuda:\n torch.set_default_tensor_type('torch.cuda.FloatTensor')\n if not args.cuda:\n print(\"WARNING: It looks like you have a CUDA device, but aren't \" +\n \"using CUDA.\\nRun with --cuda for optimal training speed.\")\n torch.set_default_tensor_type('torch.FloatTensor')\nelse:\n torch.set_default_tensor_type('torch.FloatTensor')\n\nclass NetLoss(nn.Module):\n \"\"\"\n A wrapper for running the network and computing the loss\n This is so we can more efficiently use DataParallel.\n \"\"\"\n \n def __init__(self, net:Yolact, criterion:MultiBoxLoss):\n super().__init__()\n\n self.net = net\n self.criterion = criterion\n \n def forward(self, images, targets, masks, num_crowds):\n preds = self.net(images)\n losses = self.criterion(self.net, preds, targets, masks, num_crowds)\n return losses\n\nclass CustomDataParallel(nn.DataParallel):\n \"\"\"\n This is a custom version of DataParallel that works better with our training data.\n It should also be faster than the general case.\n \"\"\"\n\n def scatter(self, inputs, kwargs, device_ids):\n # More like scatter and data prep at the same time. The point is we prep the data in such a way\n # that no scatter is necessary, and there's no need to shuffle stuff around different GPUs.\n devices = ['cuda:' + str(x) for x in device_ids]\n splits = prepare_data(inputs[0], devices, allocation=args.batch_alloc)\n\n return [[split[device_idx] for split in splits] for device_idx in range(len(devices))], \\\n [kwargs] * len(devices)\n\n def gather(self, outputs, output_device):\n out = {}\n\n for k in outputs[0]:\n out[k] = torch.stack([output[k].to(output_device) for output in outputs])\n \n return out\n\ndef train():\n if not os.path.exists(args.save_folder):\n os.mkdir(args.save_folder)\n\n dataset = COCODetection(image_path=cfg.dataset.train_images,\n info_file=cfg.dataset.train_info,\n transform=SSDAugmentation(MEANS))\n \n if args.validation_epoch > 0:\n setup_eval()\n val_dataset = COCODetection(image_path=cfg.dataset.valid_images,\n info_file=cfg.dataset.valid_info,\n transform=BaseTransform(MEANS))\n\n # Parallel wraps the underlying module, but when saving and loading we don't want that\n yolact_net = Yolact()\n net = yolact_net\n net.train()\n\n if args.log:\n log = Log(cfg.name, args.log_folder, dict(args._get_kwargs()),\n overwrite=(args.resume is None), log_gpu_stats=args.log_gpu)\n\n # I don't use the timer during training (I use a different timing method).\n # Apparently there's a race condition with multiple GPUs, so disable it just to be safe.\n timer.disable_all()\n\n # Both of these can set args.resume to None, so do them before the check \n if args.resume == 'interrupt':\n args.resume = SavePath.get_interrupt(args.save_folder)\n elif args.resume == 'latest':\n args.resume = SavePath.get_latest(args.save_folder, cfg.name)\n\n if args.resume is not None:\n print('Resuming training, loading {}...'.format(args.resume))\n yolact_net.load_weights(args.resume)\n\n if args.start_iter == -1:\n args.start_iter = SavePath.from_str(args.resume).iteration\n else:\n print('Initializing weights...')\n yolact_net.init_weights(backbone_path=args.save_folder + cfg.backbone.path)\n\n optimizer = optim.SGD(net.parameters(), lr=args.lr, momentum=args.momentum,\n weight_decay=args.decay)\n criterion = MultiBoxLoss(num_classes=cfg.num_classes,\n pos_threshold=cfg.positive_iou_threshold,\n neg_threshold=cfg.negative_iou_threshold,\n negpos_ratio=cfg.ohem_negpos_ratio)\n\n if args.batch_alloc is not None:\n args.batch_alloc = [int(x) for x in args.batch_alloc.split(',')]\n if sum(args.batch_alloc) != args.batch_size:\n print('Error: Batch allocation (%s) does not sum to batch size (%s).' % (args.batch_alloc, args.batch_size))\n exit(-1)\n\n net = CustomDataParallel(NetLoss(net, criterion))\n if args.cuda:\n net = net.cuda()\n \n # Initialize everything\n if not cfg.freeze_bn: yolact_net.freeze_bn() # Freeze bn so we don't kill our means\n yolact_net(torch.zeros(1, 3, cfg.max_size, cfg.max_size).cuda())\n if not cfg.freeze_bn: yolact_net.freeze_bn(True)\n\n # loss counters\n loc_loss = 0\n conf_loss = 0\n iteration = max(args.start_iter, 0)\n last_time = time.time()\n\n epoch_size = len(dataset) // args.batch_size\n num_epochs = math.ceil(cfg.max_iter / epoch_size)\n \n # Which learning rate adjustment step are we on? lr' = lr * gamma ^ step_index\n step_index = 0\n\n data_loader = data.DataLoader(dataset, args.batch_size,\n num_workers=args.num_workers,\n shuffle=True, collate_fn=detection_collate,\n pin_memory=True)\n \n \n save_path = lambda epoch, iteration: SavePath(cfg.name, epoch, iteration).get_path(root=args.save_folder)\n time_avg = MovingAverage()\n\n global loss_types # Forms the print order\n loss_avgs = { k: MovingAverage(100) for k in loss_types }\n\n print('Begin training!')\n print()\n # try-except so you can use ctrl+c to save early and stop training\n try:\n for epoch in range(num_epochs):\n # Resume from start_iter\n if (epoch+1)*epoch_size < iteration:\n continue\n \n for datum in data_loader:\n # Stop if we've reached an epoch if we're resuming from start_iter\n if iteration == (epoch+1)*epoch_size:\n break\n\n # Stop at the configured number of iterations even if mid-epoch\n if iteration == cfg.max_iter:\n break\n\n # Change a config setting if we've reached the specified iteration\n changed = False\n for change in cfg.delayed_settings:\n if iteration >= change[0]:\n changed = True\n cfg.replace(change[1])\n\n # Reset the loss averages because things might have changed\n for avg in loss_avgs:\n avg.reset()\n \n # If a config setting was changed, remove it from the list so we don't keep checking\n if changed:\n cfg.delayed_settings = [x for x in cfg.delayed_settings if x[0] > iteration]\n\n # Warm up by linearly interpolating the learning rate from some smaller value\n if cfg.lr_warmup_until > 0 and iteration <= cfg.lr_warmup_until:\n set_lr(optimizer, (args.lr - cfg.lr_warmup_init) * (iteration / cfg.lr_warmup_until) + cfg.lr_warmup_init)\n\n # Adjust the learning rate at the given iterations, but also if we resume from past that iteration\n while step_index < len(cfg.lr_steps) and iteration >= cfg.lr_steps[step_index]:\n step_index += 1\n set_lr(optimizer, args.lr * (args.gamma ** step_index))\n \n # Zero the grad to get ready to compute gradients\n optimizer.zero_grad()\n\n # Forward Pass + Compute loss at the same time (see CustomDataParallel and NetLoss)\n losses = net(datum)\n \n losses = { k: (v).mean() for k,v in losses.items() } # Mean here because Dataparallel\n loss = sum([losses[k] for k in losses])\n \n # no_inf_mean removes some components from the loss, so make sure to backward through all of it\n # all_loss = sum([v.mean() for v in losses.values()])\n\n # Backprop\n loss.backward() # Do this to free up vram even if loss is not finite\n if torch.isfinite(loss).item():\n optimizer.step()\n \n # Add the loss to the moving average for bookkeeping\n for k in losses:\n loss_avgs[k].add(losses[k].item())\n\n cur_time = time.time()\n elapsed = cur_time - last_time\n last_time = cur_time\n\n # Exclude graph setup from the timing information\n if iteration != args.start_iter:\n time_avg.add(elapsed)\n\n if iteration % 10 == 0:\n eta_str = str(datetime.timedelta(seconds=(cfg.max_iter-iteration) * time_avg.get_avg())).split('.')[0]\n \n total = sum([loss_avgs[k].get_avg() for k in losses])\n loss_labels = sum([[k, loss_avgs[k].get_avg()] for k in loss_types if k in losses], [])\n \n print(('[%3d] %7d ||' + (' %s: %.3f |' * len(losses)) + ' T: %.3f || ETA: %s || timer: %.3f')\n % tuple([epoch, iteration] + loss_labels + [total, eta_str, elapsed]), flush=True)\n\n if args.log:\n precision = 5\n loss_info = {k: round(losses[k].item(), precision) for k in losses}\n loss_info['T'] = round(loss.item(), precision)\n\n if args.log_gpu:\n log.log_gpu_stats = (iteration % 10 == 0) # nvidia-smi is sloooow\n \n log.log('train', loss=loss_info, epoch=epoch, iter=iteration,\n lr=round(cur_lr, 10), elapsed=elapsed)\n\n log.log_gpu_stats = args.log_gpu\n \n iteration += 1\n\n if iteration % args.save_interval == 0 and iteration != args.start_iter:\n if args.keep_latest:\n latest = SavePath.get_latest(args.save_folder, cfg.name)\n\n print('Saving state, iter:', iteration)\n yolact_net.save_weights(save_path(epoch, iteration))\n\n if args.keep_latest and latest is not None:\n if args.keep_latest_interval <= 0 or iteration % args.keep_latest_interval != args.save_interval:\n print('Deleting old save...')\n os.remove(latest)\n \n # This is done per epoch\n if args.validation_epoch > 0:\n if epoch % args.validation_epoch == 0 and epoch > 0:\n compute_validation_map(epoch, iteration, yolact_net, val_dataset, log if args.log else None)\n \n # Compute validation mAP after training is finished\n compute_validation_map(epoch, iteration, yolact_net, val_dataset, log if args.log else None)\n except KeyboardInterrupt:\n if args.interrupt:\n print('Stopping early. Saving network...')\n \n # Delete previous copy of the interrupted network so we don't spam the weights folder\n SavePath.remove_interrupt(args.save_folder)\n \n yolact_net.save_weights(save_path(epoch, repr(iteration) + '_interrupt'))\n exit()\n\n yolact_net.save_weights(save_path(epoch, iteration))\n\n\ndef set_lr(optimizer, new_lr):\n for param_group in optimizer.param_groups:\n param_group['lr'] = new_lr\n \n global cur_lr\n cur_lr = new_lr\n\ndef gradinator(x):\n x.requires_grad = False\n return x\n\ndef prepare_data(datum, devices:list=None, allocation:list=None):\n with torch.no_grad():\n if devices is None:\n devices = ['cuda:0'] if args.cuda else ['cpu']\n if allocation is None:\n allocation = [args.batch_size // len(devices)] * (len(devices) - 1)\n allocation.append(args.batch_size - sum(allocation)) # The rest might need more/less\n \n images, (targets, masks, num_crowds) = datum\n\n cur_idx = 0\n for device, alloc in zip(devices, allocation):\n for _ in range(alloc):\n images[cur_idx] = gradinator(images[cur_idx].to(device))\n targets[cur_idx] = gradinator(targets[cur_idx].to(device))\n masks[cur_idx] = gradinator(masks[cur_idx].to(device))\n cur_idx += 1\n\n if cfg.preserve_aspect_ratio:\n # Choose a random size from the batch\n _, h, w = images[random.randint(0, len(images)-1)].size()\n\n for idx, (image, target, mask, num_crowd) in enumerate(zip(images, targets, masks, num_crowds)):\n images[idx], targets[idx], masks[idx], num_crowds[idx] \\\n = enforce_size(image, target, mask, num_crowd, w, h)\n \n cur_idx = 0\n split_images, split_targets, split_masks, split_numcrowds \\\n = [[None for alloc in allocation] for _ in range(4)]\n\n for device_idx, alloc in enumerate(allocation):\n split_images[device_idx] = torch.stack(images[cur_idx:cur_idx+alloc], dim=0)\n split_targets[device_idx] = targets[cur_idx:cur_idx+alloc]\n split_masks[device_idx] = masks[cur_idx:cur_idx+alloc]\n split_numcrowds[device_idx] = num_crowds[cur_idx:cur_idx+alloc]\n\n cur_idx += alloc\n\n return split_images, split_targets, split_masks, split_numcrowds\n\ndef no_inf_mean(x:torch.Tensor):\n \"\"\"\n Computes the mean of a vector, throwing out all inf values.\n If there are no non-inf values, this will return inf (i.e., just the normal mean).\n \"\"\"\n\n no_inf = [a for a in x if torch.isfinite(a)]\n\n if len(no_inf) > 0:\n return sum(no_inf) / len(no_inf)\n else:\n return x.mean()\n\ndef compute_validation_loss(net, data_loader, criterion):\n global loss_types\n\n with torch.no_grad():\n losses = {}\n \n # Don't switch to eval mode because we want to get losses\n iterations = 0\n for datum in data_loader:\n images, targets, masks, num_crowds = prepare_data(datum)\n out = net(images)\n\n wrapper = ScatterWrapper(targets, masks, num_crowds)\n _losses = criterion(out, wrapper, wrapper.make_mask())\n \n for k, v in _losses.items():\n v = v.mean().item()\n if k in losses:\n losses[k] += v\n else:\n losses[k] = v\n\n iterations += 1\n if args.validation_size <= iterations * args.batch_size:\n break\n \n for k in losses:\n losses[k] /= iterations\n \n \n loss_labels = sum([[k, losses[k]] for k in loss_types if k in losses], [])\n print(('Validation ||' + (' %s: %.3f |' * len(losses)) + ')') % tuple(loss_labels), flush=True)\n\ndef compute_validation_map(epoch, iteration, yolact_net, dataset, log:Log=None):\n with torch.no_grad():\n yolact_net.eval()\n \n start = time.time()\n print()\n print(\"Computing validation mAP (this may take a while)...\", flush=True)\n val_info = eval_script.evaluate(yolact_net, dataset, train_mode=True)\n end = time.time()\n\n if log is not None:\n log.log('val', val_info, elapsed=(end - start), epoch=epoch, iter=iteration)\n\n yolact_net.train()\n\ndef setup_eval():\n eval_script.parse_args(['--no_bar', '--max_images='+str(args.validation_size)])\n\nif __name__ == '__main__':\n train()\n" ]
[ [ "torch.set_default_tensor_type", "torch.zeros", "torch.utils.data.DataLoader", "torch.isfinite", "torch.no_grad", "torch.cuda.is_available", "torch.stack", "torch.cuda.device_count" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
IandRover/meta-gradient_RL
[ "5d2539aceb9fa68b1849feac7d37741f9e5f83a3", "5d2539aceb9fa68b1849feac7d37741f9e5f83a3" ]
[ "models.py", "utils_a2c.py" ]
[ "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass ActorNetwork(nn.Module):\n\n def __init__(self,input_size,hidden_size,action_size):\n super(ActorNetwork, self).__init__()\n self.fc1 = nn.Linear(input_size,hidden_size)\n self.fc2 = nn.Linear(hidden_size,hidden_size)\n self.fc3 = nn.Linear(hidden_size,action_size)\n\n def forward(self,x):\n out = F.relu(self.fc1(x))\n out = F.relu(self.fc2(out))\n out = F.log_softmax(self.fc3(out))\n return out\n\nclass ValueNetwork(nn.Module):\n\n def __init__(self,input_size,hidden_size,output_size):\n super(ValueNetwork, self).__init__()\n self.fc1 = nn.Linear(input_size,hidden_size)\n self.fc2 = nn.Linear(hidden_size,hidden_size)\n self.fc3 = nn.Linear(hidden_size,output_size)\n\n def forward(self,x):\n out = F.relu(self.fc1(x))\n out = F.relu(self.fc2(out))\n out = self.fc3(out)\n return out", "import torch \n\n\"\"\"Compute df/dtheta\"\"\"\ndef compute_df_dtheta(pi_, values_, return_, actor_network, value_network, gamma, c=0.5):\n\n theta1 = torch.autograd.grad(pi_, actor_network.parameters())\n theta1 = [item.view(-1) for item in theta1]\n theta1 = torch.cat(theta1)\n\n theta2 = torch.autograd.grad(values_, value_network.parameters())\n theta2 = [item.view(-1) for item in theta2]\n theta2 = torch.cat(theta2)\n\n theta_sum = theta1\n\n g_dgamma = torch.autograd.grad(return_, gamma)\n\n return g_dgamma[0], theta1, theta2\n\ndef compute_dfpron_dthetapron(pi_, values_, actor_network, value_network):\n\n theta1 = torch.autograd.grad(pi_, actor_network.parameters())\n theta1 = [item.view(-1) for item in theta1]\n theta1 = torch.cat(theta1)\n \n theta2 = torch.autograd.grad(values_, value_network.parameters())\n theta2 = [item.view(-1) for item in theta2]\n theta2 = torch.cat(theta2)\n \n return theta1, theta2\n" ]
[ [ "torch.nn.Linear" ], [ "torch.autograd.grad", "torch.cat" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
data-umbrella/sprints-dashboard
[ "f8cdbe640fbc8001172b096065a79a9efe5c2829" ]
[ "scripts/app.py" ]
[ "import dash\n#import dash_core_components as dcc\nfrom dash import dcc\nfrom dash import html\n#import dash_html_components as html\nimport dash_bootstrap_components as dbc\nfrom dash.dependencies import Input, Output\nimport plotly.express as px\nfrom plotly import graph_objects as go\nimport pandas as pd\n\n# https://dash-bootstrap-components.opensource.faculty.ai/docs/components/tabs\n# check version of library\n# https://dash.gallery/Portal/\n# https://plotly.com/python/templates/\n# https://github.com/plotly/dash-sample-apps/tree/main/apps/dash-opioid-epidemic\n# Bootstrap themes: https://dash-bootstrap-components.opensource.faculty.ai/docs/themes/explorer/\n# Layout: https://dash-bootstrap-components.opensource.faculty.ai/docs/components/layout/\n\n# to do: play with layout\n# bar: give a default value\n# add a title at the top\n# id once per sheet\n# do one copy/ paste at a time\n# stylesheets: https://bootswatch.com/\n# [\"plotly\", \"plotly_white\", \"plotly_dark\", \"ggplot2\", \"seaborn\", \"simple_white\", \"none\"]\n\ntemplate = \"seaborn\"\nexternal_stylesheets = [dbc.themes.BOOTSTRAP, dbc.themes.SOLAR]\n\ndata_url = \"https://raw.githubusercontent.com/data-umbrella/data-umbrella-sprints-dashboard/main/data/data_derived/afme2_derived.csv\"\ndf = pd.read_csv(data_url)\n\napp = dash.Dash(__name__, external_stylesheets=external_stylesheets)\n\n\npie_div = dbc.Row([\n dbc.Row([dbc.Col(html.H4(\"Dimensions:\"), width=3), \n dbc.Col(dcc.Dropdown(\n id='names', \n value='status_c', \n options=[{'value': x, 'label': x} \n for x in ['gender', 'contributor_status', 'status_c','continent_o', 'python_experience', 'country']],\n clearable=False\n )),\n dbc.Col(html.H4(\"Count:\"), width=3),\n dbc.Col(dcc.Dropdown(\n id='values', \n value='count_rows', \n options=[{'value': x, 'label': x} \n for x in ['count_rows']],\n clearable=False), width=3\n ) \n ])\n ,html.P(html.Br()), \n dcc.Graph(id=\"pie-chart\"),\n])\n\nbar_div = dbc.Row([\n dbc.Row([dbc.Col(html.H4(\"Dimensions:\"), width=3),\n dbc.Col(dcc.Dropdown(\n id='names_bar',\n value='gender',\n options=[{'value': x, 'label': x} \n for x in ['gender', 'contributor_status', 'continent_o', 'country', 'python_experience', 'primary_spoken_language', 'attendance_status','role']],\n clearable=False\n )),\n dbc.Col(html.H4(\"Count:\"), width=3),\n dbc.Col(dcc.Dropdown(\n id='values_bar',\n value='count_rows',\n options=[{'value': x, 'label': x} \n for x in ['count_rows']],\n clearable=False), width=3\n )\n ])\n ,html.P(html.Br()),\n dcc.Graph(id=\"bar-chart\"),\n])\n\n# FUNNEL CHART\nfig_funnel = go.Figure()\nfig_funnel.add_trace(go.Funnel(\n name = 'Women',\n y = [\"Applied\", \"RSVPd\", \"Attended\"],\n x = [25, 20, 14],\n textinfo = \"value+percent initial\"))\n\nfig_funnel.add_trace(go.Funnel(\n name = 'Men',\n y = [\"Applied\", \"RSVPd\", \"Attended\"],\n x = [49, 35, 26],\n textinfo = \"value+percent previous\",))\n\nfunnel_div = dbc.Row([\n dbc.Row([dbc.Col(html.H4(\"Dimensions:\"), width=3),\n dcc.Graph(figure=fig_funnel)\n ])\n])\n\n# MAP\nvariable = \"attendance_status\"\n\ndf['text'] = df['city'] + ', ' + df['country'] + ', '\n#+ df['state-province'] + ', ' \n#+ df['continent_o'] \n\nfig_map = px.scatter_geo(df, \n #locations=\"iso_alpha\", \n lat = \"lat\",\n lon = \"lng\",\n color=variable,\n hover_name=\"city\", #\"location\", \n #hover_name=\"country\", \n hover_data=[\"city\", \"country\",\"continent_o\"],\n #hover_data=[\"text\"],\n #text=\"city\",\n #text = dict (\n # size=8,\n #)\n #size=8,\n #mode = \"markers\",\n #marker = dict(\n # size = 8,\n # opacity = 0.8,\n # reversescale = True,\n # autocolorscale = False,\n # symbol = 'square',\n #),\n projection=\"natural earth\",\n title=f\"Chart: Geomap of {variable}\",\n )\n\nfig_map.update_geos(\n visible=True, resolution=50,\n showcountries=True, countrycolor=\"LightYellow\"\n)\nfig_map.update_layout(height=600, margin={\"r\":10,\"t\":0,\"l\":10,\"b\":0})\nfig_map.update_traces(marker_symbol=[\"circle-x\",\"circle-open-dot\",\"circle-dot\"]\n , selector=dict(type='scattergeo'))\n\ncard = dbc.Card(\n [\n dbc.CardHeader(\n dbc.Tabs(\n [\n dbc.Tab(label=\"AFME2 (Oct 2021)\", tab_id=\"AFME2\", tab_style={\"marginLeft\": \"left\"}),\n dbc.Tab(label=\"Tab 2\", tab_id=\"tab-2\", label_style={\"color\": \"#00AEF9\"}),\n ],\n id=\"card-tabs\",\n active_tab=\"tab-1\",\n ),\n ),\n html.Br(),\n # dbc.Tabs(\n # [\n # dbc.Tab(label=\"Tab 1\", activeTabClassName=\"fw-bold fst-italic\"),\n # dbc.Tab(label=\"Tab 2\", activeLabelClassName=\"text-success\"),\n # ]\n # ),\n dbc.CardBody(html.P(id=\"card-content\", className=\"card-text\")\n ),\n dbc.CardBody(\n [\n html.H4(\"Data Umbrella\", id=\"card-title\"),\n html.H2(\"Africa & Middle East scikit-learn Sprint\", id=\"card-value\"),\n html.P(\"October 2021\", id=\"card-description\")\n ]\n )\n ],\n)\napp.layout = html.Div([ \n dbc.Row([\n dbc.Col([card], width=12),\n ],\n align=\"center\",\n justify=\"center\"),\n dbc.Row([\n dbc.Col(html.H1(\"Pie Chart\"), width=4), \n dbc.Col(html.H1(\"Bar Chart\"), width=4),\n ],\n align=\"center\",\n justify=\"center\"), \n dbc.Row([\n dbc.Col(pie_div, width=4), \n dbc.Col(bar_div, width=4)\n ],\n align=\"center\",\n justify=\"center\"), \n # dbc.Row([\n # dbc.Col(\n # html.Div(\"A single, half-width column\"),\n # width={\"size\": 6, \"offset\": 3},\n # ),\n # dbc.Col(html.H1(\"Funnel Chart\"), width=4),\n # ],\n # align=\"center\",\n # justify=\"center\"),\n dbc.Row([\n dbc.Col(html.H1(\"Funnel Chart\"), width=4), \n dbc.Col(html.H1(\"Map\"), width=4),\n ],\n align=\"center\",\n justify=\"center\"), \n dbc.Row([\n dbc.Col(dcc.Graph(figure=fig_funnel), width=4),\n dbc.Col(dcc.Graph(figure=fig_map), width=4),\n ],\n align=\"center\",\n justify=\"center\"),\n # dbc.Row([\n # dbc.Col(html.H1(\"Map\"), width={\"size\": 6, \"offset\": 3})\n # ]), \n # dbc.Row([\n # dcc.Graph(figure=fig_map),\n # ]),\n ],\n className=\"pad-row\",\n)\n\n\n# PIE CHART\[email protected](\n Output(\"pie-chart\", \"figure\"), \n [Input(\"names\", \"value\"), \n Input(\"values\", \"value\")])\ndef generate_chart(names, values):\n fig = px.pie(df, values=values, names=names, template=template)\n fig.update_traces(textposition='inside', textinfo='value+percent+label')\n return fig\n\n# BAR CHART\[email protected](\n Output(\"bar-chart\", \"figure\"), \n [Input(\"names_bar\", \"value\"), \n Input(\"values_bar\", \"value\")])\ndef generate_chart(names, values):\n # Try 4: try to remove warning\n grouped_yr_status = df.groupby([names, 'status_c']).count().reset_index()\n df2 = grouped_yr_status[[names, 'status_c', values]] \n fig = px.bar(df2, x=values, y=names, color=\"status_c\", \n barmode=\"stack\", orientation=\"h\", text=values, template=template) \n \n fig.update_layout(barmode='stack', xaxis={'categoryorder':'total descending'})\n return fig\n\[email protected](\n Output(\"card-content\", \"children\"), [Input(\"card-tabs\", \"active_tab\")]\n)\ndef tab_content(active_tab):\n return \"This is tab: {}\".format(active_tab)\n\napp.run_server(debug=True)\n" ]
[ [ "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
Zilleplus/HML
[ "ab9510e27103bb7c14e801606bb25b7c4e17e8ea" ]
[ "HML/chapter6/ex7.py" ]
[ "# Train and fine-tune a Decision Tree for the oons dataset\n# by following these steps:\n# a. Use make_moons(n_samples=10000, noise=0.4)\n#\n# b. Use train_test_split() to split the datset in to a training\n# set and test set.\n#\n# c. Use grid search with cross-validation (with the help of the\n# GridSearchCV class) to find good hyperparameter values for a\n# DecisionTreeClassifier\n#\n# d. Train it on the ful training set using these hyper paremeters,\n# and measure your model's performance on the test set.\n# You should get roughtly 85% to 87% accuracy.\n\nfrom sklearn.datasets import make_moons\nfrom sklearn.model_selection import train_test_split, GridSearchCV\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.tree import DecisionTreeClassifier\n\nX, y = make_moons(n_samples=10000, noise=0.4)\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n\nparam_grid = {\n 'cf__max_depth': list(range(2, 10)),\n 'cf__min_samples_split': list(range(2, 10)),\n 'cf__min_samples_leaf': list(range(1, 10)),\n 'cf__min_weight_fraction_leaf': [0.0, 0.1, 0.2]\n}\npipeline = Pipeline([\n ('cf', DecisionTreeClassifier())\n])\nsearch = GridSearchCV(pipeline, param_grid, verbose=3)\nsearch.fit(X_train, y_train)\n\nbest_estimator = search.best_estimator_\n# It runs pretty quick, you get the result:\n# max_depth=7, min_samples_leaf=5\nbest_estimator\n\ny_pred_test = best_estimator.predict(X_test)\nsucc_rate = sum([1 if x == 0 else 0 for x in (y_pred_test - y_test)])\\\n / len(y_pred_test)\nsucc_rate\n" ]
[ [ "sklearn.datasets.make_moons", "sklearn.model_selection.GridSearchCV", "sklearn.model_selection.train_test_split", "sklearn.tree.DecisionTreeClassifier" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
tjpuzhaolei/yolact
[ "d27ab4d5150d7ca5d12a950f0075b0886d9b9171" ]
[ "layers/modules/multibox_loss.py" ]
[ "# -*- coding: utf-8 -*-\nimport torch\nimport pdb\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom ..box_utils import match, log_sum_exp, decode, center_size, crop\n\nfrom data import cfg, mask_type, activation_func\n\nclass MultiBoxLoss(nn.Module):\n \"\"\"SSD Weighted Loss Function\n Compute Targets:\n 1) Produce Confidence Target Indices by matching ground truth boxes\n with (default) 'priorboxes' that have jaccard index > threshold parameter\n (default threshold: 0.5).\n 2) Produce localization target by 'encoding' variance into offsets of ground\n truth boxes and their matched 'priorboxes'.\n 3) Hard negative mining to filter the excessive number of negative examples\n that comes with using a large number of default bounding boxes.\n (default negative:positive ratio 3:1)\n Objective Loss:\n L(x,c,l,g) = (Lconf(x, c) + αLloc(x,l,g)) / N\n Where, Lconf is the CrossEntropy Loss and Lloc is the SmoothL1 Loss\n weighted by α which is set to 1 by cross val.\n Args:\n c: class confidences,\n l: predicted boxes,\n g: ground truth boxes\n N: number of matched default boxes\n See: https://arxiv.org/pdf/1512.02325.pdf for more details.\n \"\"\"\n\n def __init__(self, num_classes, pos_threshold, neg_threshold, negpos_ratio):\n super(MultiBoxLoss, self).__init__()\n self.num_classes = num_classes\n \n self.pos_threshold = pos_threshold\n self.neg_threshold = neg_threshold\n self.negpos_ratio = negpos_ratio\n\n # If you output a proto mask with this area, your l1 loss will be l1_alpha\n # Note that the area is relative (so 1 would be the entire image)\n self.l1_expected_area = 20*20/70/70\n self.l1_alpha = 0.1\n\n def forward(self, predictions, wrapper, wrapper_mask):\n \"\"\"Multibox Loss\n Args:\n predictions (tuple): A tuple containing loc preds, conf preds,\n mask preds, and prior boxes from SSD net.\n loc shape: torch.size(batch_size,num_priors,4)\n conf shape: torch.size(batch_size,num_priors,num_classes)\n masks shape: torch.size(batch_size,num_priors,mask_dim)\n priors shape: torch.size(num_priors,4)\n proto* shape: torch.size(batch_size,mask_h,mask_w,mask_dim)\n\n targets (list<tensor>): Ground truth boxes and labels for a batch,\n shape: [batch_size][num_objs,5] (last idx is the label).\n\n masks (list<tensor>): Ground truth masks for each object in each image,\n shape: [batch_size][num_objs,im_height,im_width]\n\n num_crowds (list<int>): Number of crowd annotations per batch. The crowd\n annotations should be the last num_crowds elements of targets and masks.\n \n * Only if mask_type == lincomb\n \"\"\"\n\n loc_data = predictions['loc']\n conf_data = predictions['conf']\n mask_data = predictions['mask']\n priors = predictions['priors']\n\n if cfg.mask_type == mask_type.lincomb:\n proto_data = predictions['proto']\n \n if cfg.use_instance_coeff:\n inst_data = predictions['inst']\n else:\n inst_data = None\n \n targets, masks, num_crowds = wrapper.get_args(wrapper_mask)\n labels = [None] * len(targets) # Used in sem segm loss\n\n batch_size = loc_data.size(0)\n # This is necessary for training on multiple GPUs because\n # DataParallel will cat the priors from each GPU together\n priors = priors[:loc_data.size(1), :]\n num_priors = (priors.size(0))\n num_classes = self.num_classes\n\n # Match priors (default boxes) and ground truth boxes\n # These tensors will be created with the same device as loc_data\n loc_t = loc_data.new(batch_size, num_priors, 4)\n gt_box_t = loc_data.new(batch_size, num_priors, 4)\n conf_t = loc_data.new(batch_size, num_priors).long()\n idx_t = loc_data.new(batch_size, num_priors).long()\n\n defaults = priors.data\n\n if cfg.use_class_existence_loss:\n class_existence_t = loc_data.new(batch_size, num_classes-1)\n\n for idx in range(batch_size):\n truths = targets[idx][:, :-1].data\n labels[idx] = targets[idx][:, -1].data.long()\n\n if cfg.use_class_existence_loss:\n # Construct a one-hot vector for each object and collapse it into an existence vector with max\n # Also it's fine to include the crowd annotations here\n class_existence_t[idx, :] = torch.eye(num_classes-1, device=conf_t.get_device())[labels[idx]].max(dim=0)[0]\n\n # Split the crowd annotations because they come bundled in\n cur_crowds = num_crowds[idx]\n if cur_crowds > 0:\n split = lambda x: (x[-cur_crowds:], x[:-cur_crowds])\n crowd_boxes, truths = split(truths)\n\n # We don't use the crowd labels or masks\n _, labels[idx] = split(labels[idx])\n _, masks[idx] = split(masks[idx])\n else:\n crowd_boxes = None\n\n \n match(self.pos_threshold, self.neg_threshold,\n truths, defaults, labels[idx], crowd_boxes,\n loc_t, conf_t, idx_t, idx, loc_data[idx])\n \n gt_box_t[idx, :, :] = truths[idx_t[idx]]\n\n # wrap targets\n loc_t = Variable(loc_t, requires_grad=False)\n conf_t = Variable(conf_t, requires_grad=False)\n idx_t = Variable(idx_t, requires_grad=False)\n\n pos = conf_t > 0\n num_pos = pos.sum(dim=1, keepdim=True)\n \n # Shape: [batch,num_priors,4]\n pos_idx = pos.unsqueeze(pos.dim()).expand_as(loc_data)\n \n losses = {}\n\n # Localization Loss (Smooth L1)\n if cfg.train_boxes:\n loc_p = loc_data[pos_idx].view(-1, 4)\n loc_t = loc_t[pos_idx].view(-1, 4)\n losses['B'] = F.smooth_l1_loss(loc_p, loc_t, reduction='sum') * cfg.bbox_alpha\n\n if cfg.train_masks:\n if cfg.mask_type == mask_type.direct:\n if cfg.use_gt_bboxes:\n pos_masks = []\n for idx in range(batch_size):\n pos_masks.append(masks[idx][idx_t[idx, pos[idx]]])\n masks_t = torch.cat(pos_masks, 0)\n masks_p = mask_data[pos, :].view(-1, cfg.mask_dim)\n losses['M'] = F.binary_cross_entropy(torch.clamp(masks_p, 0, 1), masks_t, reduction='sum') * cfg.mask_alpha\n else:\n losses['M'] = self.direct_mask_loss(pos_idx, idx_t, loc_data, mask_data, priors, masks)\n elif cfg.mask_type == mask_type.lincomb:\n losses.update(self.lincomb_mask_loss(pos, idx_t, loc_data, mask_data, priors, proto_data, masks, gt_box_t, inst_data))\n \n if cfg.mask_proto_loss is not None:\n if cfg.mask_proto_loss == 'l1':\n losses['P'] = torch.mean(torch.abs(proto_data)) / self.l1_expected_area * self.l1_alpha\n elif cfg.mask_proto_loss == 'disj':\n losses['P'] = -torch.mean(torch.max(F.log_softmax(proto_data, dim=-1), dim=-1)[0])\n\n # Confidence loss\n if cfg.use_focal_loss:\n if cfg.use_sigmoid_focal_loss:\n losses['C'] = self.focal_conf_sigmoid_loss(conf_data, conf_t)\n elif cfg.use_objectness_score:\n losses['C'] = self.focal_conf_objectness_loss(conf_data, conf_t)\n else:\n losses['C'] = self.focal_conf_loss(conf_data, conf_t)\n else:\n losses['C'] = self.ohem_conf_loss(conf_data, conf_t, pos, batch_size)\n\n # These losses also don't depend on anchors\n if cfg.use_class_existence_loss:\n losses['E'] = self.class_existence_loss(predictions['classes'], class_existence_t)\n if cfg.use_semantic_segmentation_loss:\n losses['S'] = self.semantic_segmentation_loss(predictions['segm'], masks, labels)\n\n # Divide all losses by the number of positives.\n # Don't do it for loss[P] because that doesn't depend on the anchors.\n total_num_pos = num_pos.data.sum().float()\n for k in losses:\n if k not in ('P', 'E', 'S'):\n losses[k] /= total_num_pos\n else:\n losses[k] /= batch_size\n\n # Loss Key:\n # - B: Box Localization Loss\n # - C: Class Confidence Loss\n # - M: Mask Loss\n # - P: Prototype Loss\n # - D: Coefficient Diversity Loss\n # - E: Class Existence Loss\n # - S: Semantic Segmentation Loss\n return losses\n\n def class_existence_loss(self, class_data, class_existence_t):\n return cfg.class_existence_alpha * F.binary_cross_entropy_with_logits(class_data, class_existence_t, reduction='sum')\n\n def semantic_segmentation_loss(self, segment_data, mask_t, class_t, interpolation_mode='bilinear'):\n # Note num_classes here is without the background class so cfg.num_classes-1\n batch_size, num_classes, mask_h, mask_w = segment_data.size()\n loss_s = 0\n \n for idx in range(batch_size):\n cur_segment = segment_data[idx]\n cur_class_t = class_t[idx]\n\n with torch.no_grad():\n downsampled_masks = F.interpolate(mask_t[idx].unsqueeze(0), (mask_h, mask_w),\n mode=interpolation_mode, align_corners=False).squeeze(0)\n downsampled_masks = downsampled_masks.gt(0.5).float()\n \n # Construct Semantic Segmentation\n segment_t = torch.zeros_like(cur_segment, requires_grad=False)\n for obj_idx in range(downsampled_masks.size(0)):\n segment_t[cur_class_t[obj_idx]] = torch.max(segment_t[cur_class_t[obj_idx]], downsampled_masks[obj_idx])\n \n loss_s += F.binary_cross_entropy_with_logits(cur_segment, segment_t, reduction='sum')\n \n return loss_s / mask_h / mask_w * cfg.semantic_segmentation_alpha\n\n\n def ohem_conf_loss(self, conf_data, conf_t, pos, num):\n # Compute max conf across batch for hard negative mining\n\n batch_conf = conf_data.view(-1, self.num_classes)\n if cfg.ohem_use_most_confident:\n # i.e. max(softmax) along classes > 0 \n batch_conf = F.softmax(batch_conf, dim=1)\n loss_c, _ = batch_conf[:, 1:].max(dim=1)\n else:\n # i.e. -softmax(class 0 confidence)\n loss_c = log_sum_exp(batch_conf) - batch_conf[:, 0]\n\n # Hard Negative Mining\n # loss_c = loss_c.view(pos.size()[0], pos.size()[1]) #add line\n loss_c = loss_c.view(num, -1)\n loss_c[pos] = 0 # filter out pos boxes\n loss_c[conf_t < 0] = 0 # filter out neutrals (conf_t = -1)\n _, loss_idx = loss_c.sort(1, descending=True)\n _, idx_rank = loss_idx.sort(1)\n num_pos = pos.long().sum(1, keepdim=True)\n num_neg = torch.clamp(self.negpos_ratio*num_pos, max=pos.size(1)-1)\n neg = idx_rank < num_neg.expand_as(idx_rank)\n \n # Just in case there aren't enough negatives, don't start using positives as negatives\n neg[pos] = 0\n neg[conf_t < 0] = 0 # Filter out neutrals\n\n # Confidence Loss Including Positive and Negative Examples\n pos_idx = pos.unsqueeze(2).expand_as(conf_data)\n neg_idx = neg.unsqueeze(2).expand_as(conf_data)\n conf_p = conf_data[(pos_idx+neg_idx).gt(0)].view(-1, self.num_classes)\n targets_weighted = conf_t[(pos+neg).gt(0)]\n loss_c = F.cross_entropy(conf_p, targets_weighted, reduction='sum')\n \n return cfg.conf_alpha * loss_c\n\n def focal_conf_loss(self, conf_data, conf_t):\n \"\"\"\n Focal loss as described in https://arxiv.org/pdf/1708.02002.pdf\n Adapted from https://github.com/clcarwin/focal_loss_pytorch/blob/master/focalloss.py\n Note that this uses softmax and not the original sigmoid from the paper.\n \"\"\"\n conf_t = conf_t.view(-1) # [batch_size*num_priors]\n conf_data = conf_data.view(-1, conf_data.size(-1)) # [batch_size*num_priors, num_classes]\n\n # Ignore neutral samples (class < 0)\n keep = (conf_t >= 0).float()\n conf_t[conf_t < 0] = 0 # so that gather doesn't drum up a fuss\n\n logpt = F.log_softmax(conf_data, dim=-1)\n logpt = logpt.gather(1, conf_t.unsqueeze(-1))\n logpt = logpt.view(-1)\n pt = logpt.exp()\n\n # I adapted the alpha_t calculation here from\n # https://github.com/pytorch/pytorch/blob/master/modules/detectron/softmax_focal_loss_op.cu\n # You'd think you want all the alphas to sum to one, but in the original implementation they\n # just give background an alpha of 1-alpha and each forground an alpha of alpha.\n background = (conf_t == 0).float()\n at = (1 - cfg.focal_loss_alpha) * background + cfg.focal_loss_alpha * (1 - background)\n\n loss = -at * (1 - pt) ** cfg.focal_loss_gamma * logpt\n\n # See comment above for keep\n return cfg.conf_alpha * (loss * keep).sum()\n \n def focal_conf_sigmoid_loss(self, conf_data, conf_t):\n \"\"\"\n Focal loss but using sigmoid like the original paper.\n Note: To make things mesh easier, the network still predicts 81 class confidences in this mode.\n Because retinanet originally only predicts 80, we simply just don't use conf_data[..., 0]\n \"\"\"\n num_classes = conf_data.size(-1)\n\n conf_t = conf_t.view(-1) # [batch_size*num_priors]\n conf_data = conf_data.view(-1, num_classes) # [batch_size*num_priors, num_classes]\n\n # Ignore neutral samples (class < 0)\n keep = (conf_t >= 0).float()\n conf_t[conf_t < 0] = 0 # can't mask with -1, so filter that out\n\n # Compute a one-hot embedding of conf_t\n # From https://github.com/kuangliu/pytorch-retinanet/blob/master/utils.py\n conf_one_t = torch.eye(num_classes, device=conf_t.get_device())[conf_t]\n conf_pm_t = conf_one_t * 2 - 1 # -1 if background, +1 if forground for specific class\n\n logpt = F.logsigmoid(conf_data * conf_pm_t) # note: 1 - sigmoid(x) = sigmoid(-x)\n pt = logpt.exp()\n\n at = cfg.focal_loss_alpha * conf_one_t + (1 - cfg.focal_loss_alpha) * (1 - conf_one_t)\n at[..., 0] = 0 # Set alpha for the background class to 0 because sigmoid focal loss doesn't use it\n\n loss = -at * (1 - pt) ** cfg.focal_loss_gamma * logpt\n loss = keep * loss.sum(dim=-1)\n\n return cfg.conf_alpha * loss.sum()\n \n def focal_conf_objectness_loss(self, conf_data, conf_t):\n \"\"\"\n Instead of using softmax, use class[0] to be the objectness score and do sigmoid focal loss on that.\n Then for the rest of the classes, softmax them and apply CE for only the positive examples.\n\n If class[0] = 1 implies forground and class[0] = 0 implies background then you achieve something\n similar during test-time to softmax by setting class[1:] = softmax(class[1:]) * class[0] and invert class[0].\n \"\"\"\n\n conf_t = conf_t.view(-1) # [batch_size*num_priors]\n conf_data = conf_data.view(-1, conf_data.size(-1)) # [batch_size*num_priors, num_classes]\n\n # Ignore neutral samples (class < 0)\n keep = (conf_t >= 0).float()\n conf_t[conf_t < 0] = 0 # so that gather doesn't drum up a fuss\n\n background = (conf_t == 0).float()\n at = (1 - cfg.focal_loss_alpha) * background + cfg.focal_loss_alpha * (1 - background)\n\n logpt = F.logsigmoid(conf_data[:, 0]) * (1 - background) + F.logsigmoid(-conf_data[:, 0]) * background\n pt = logpt.exp()\n\n obj_loss = -at * (1 - pt) ** cfg.focal_loss_gamma * logpt\n\n # All that was the objectiveness loss--now time for the class confidence loss\n pos_mask = conf_t > 0\n conf_data_pos = (conf_data[:, 1:])[pos_mask] # Now this has just 80 classes\n conf_t_pos = conf_t[pos_mask] - 1 # So subtract 1 here\n\n class_loss = F.cross_entropy(conf_data_pos, conf_t_pos, reduction='sum')\n\n return cfg.conf_alpha * (class_loss + (obj_loss * keep).sum())\n\n\n def direct_mask_loss(self, pos_idx, idx_t, loc_data, mask_data, priors, masks):\n \"\"\" Crops the gt masks using the predicted bboxes, scales them down, and outputs the BCE loss. \"\"\"\n loss_m = 0\n for idx in range(mask_data.size(0)):\n with torch.no_grad():\n cur_pos_idx = pos_idx[idx, :, :]\n cur_pos_idx_squeezed = cur_pos_idx[:, 1]\n\n # Shape: [num_priors, 4], decoded predicted bboxes\n pos_bboxes = decode(loc_data[idx, :, :], priors.data, cfg.use_yolo_regressors)\n pos_bboxes = pos_bboxes[cur_pos_idx].view(-1, 4).clamp(0, 1)\n pos_lookup = idx_t[idx, cur_pos_idx_squeezed]\n\n cur_masks = masks[idx]\n pos_masks = cur_masks[pos_lookup, :, :]\n \n # Convert bboxes to absolute coordinates\n num_pos, img_height, img_width = pos_masks.size()\n\n # Take care of all the bad behavior that can be caused by out of bounds coordinates\n x1, x2 = sanitize_coordinates(pos_bboxes[:, 0], pos_bboxes[:, 2], img_width)\n y1, y2 = sanitize_coordinates(pos_bboxes[:, 1], pos_bboxes[:, 3], img_height)\n\n # Crop each gt mask with the predicted bbox and rescale to the predicted mask size\n # Note that each bounding box crop is a different size so I don't think we can vectorize this\n scaled_masks = []\n for jdx in range(num_pos):\n tmp_mask = pos_masks[jdx, y1[jdx]:y2[jdx], x1[jdx]:x2[jdx]]\n\n # Restore any dimensions we've left out because our bbox was 1px wide\n while tmp_mask.dim() < 2:\n tmp_mask = tmp_mask.unsqueeze(0)\n\n new_mask = F.adaptive_avg_pool2d(tmp_mask.unsqueeze(0), cfg.mask_size)\n scaled_masks.append(new_mask.view(1, -1))\n\n mask_t = torch.cat(scaled_masks, 0).gt(0.5).float() # Threshold downsampled mask\n \n pos_mask_data = mask_data[idx, cur_pos_idx_squeezed, :]\n loss_m += F.binary_cross_entropy(torch.clamp(pos_mask_data, 0, 1), mask_t, reduction='sum') * cfg.mask_alpha\n\n return loss_m\n \n\n def coeff_diversity_loss(self, coeffs, instance_t):\n \"\"\"\n coeffs should be size [num_pos, num_coeffs]\n instance_t should be size [num_pos] and be values from 0 to num_instances-1\n \"\"\"\n num_pos = coeffs.size(0)\n instance_t = instance_t.view(-1) # juuuust to make sure\n\n coeffs_norm = F.normalize(coeffs, dim=1)\n cos_sim = coeffs_norm @ coeffs_norm.t()\n\n inst_eq = (instance_t[:, None].expand_as(cos_sim) == instance_t[None, :].expand_as(cos_sim)).float()\n\n # Rescale to be between 0 and 1\n cos_sim = (cos_sim + 1) / 2\n\n # If they're the same instance, use cosine distance, else use cosine similarity\n loss = (1 - cos_sim) * inst_eq + cos_sim * (1 - inst_eq)\n\n # Only divide by num_pos once because we're summing over a num_pos x num_pos tensor\n # and all the losses will be divided by num_pos at the end, so just one extra time.\n return cfg.mask_proto_coeff_diversity_alpha * loss.sum() / num_pos\n\n\n def lincomb_mask_loss(self, pos, idx_t, loc_data, mask_data, priors, proto_data, masks, gt_box_t, inst_data, interpolation_mode='bilinear'):\n mask_h = proto_data.size(1)\n mask_w = proto_data.size(2)\n\n process_gt_bboxes = cfg.mask_proto_normalize_emulate_roi_pooling or cfg.mask_proto_crop\n\n if cfg.mask_proto_remove_empty_masks:\n # Make sure to store a copy of this because we edit it to get rid of all-zero masks\n pos = pos.clone()\n\n loss_m = 0\n loss_d = 0 # Coefficient diversity loss\n\n for idx in range(mask_data.size(0)):\n with torch.no_grad():\n downsampled_masks = F.interpolate(masks[idx].unsqueeze(0), (mask_h, mask_w),\n mode=interpolation_mode, align_corners=False).squeeze(0)\n downsampled_masks = downsampled_masks.permute(1, 2, 0).contiguous()\n\n if cfg.mask_proto_binarize_downsampled_gt:\n downsampled_masks = downsampled_masks.gt(0.5).float()\n\n if cfg.mask_proto_remove_empty_masks:\n # Get rid of gt masks that are so small they get downsampled away\n very_small_masks = (downsampled_masks.sum(dim=(0,1)) <= 0.0001)\n for i in range(very_small_masks.size(0)):\n if very_small_masks[i]:\n pos[idx, idx_t[idx] == i] = 0\n\n if cfg.mask_proto_reweight_mask_loss:\n # Ensure that the gt is binary\n if not cfg.mask_proto_binarize_downsampled_gt:\n bin_gt = downsampled_masks.gt(0.5).float()\n else:\n bin_gt = downsampled_masks\n\n gt_foreground_norm = bin_gt / (torch.sum(bin_gt, dim=(0,1), keepdim=True) + 0.0001)\n gt_background_norm = (1-bin_gt) / (torch.sum(1-bin_gt, dim=(0,1), keepdim=True) + 0.0001)\n\n mask_reweighting = gt_foreground_norm * cfg.mask_proto_reweight_coeff + gt_background_norm\n mask_reweighting *= mask_h * mask_w\n\n cur_pos = pos[idx]\n pos_idx_t = idx_t[idx, cur_pos]\n \n if process_gt_bboxes:\n # Note: this is in point-form\n pos_gt_box_t = gt_box_t[idx, cur_pos]\n\n if pos_idx_t.size(0) == 0:\n continue\n\n proto_masks = proto_data[idx]\n proto_coef = mask_data[idx, cur_pos, :]\n\n if cfg.mask_proto_coeff_diversity_loss:\n if inst_data is not None:\n div_coeffs = inst_data[idx, cur_pos, :]\n else:\n div_coeffs = proto_coef\n\n loss_d += self.coeff_diversity_loss(div_coeffs, pos_idx_t)\n \n # If we have over the allowed number of masks, select a random sample\n old_num_pos = proto_coef.size(0)\n if old_num_pos > cfg.masks_to_train:\n perm = torch.randperm(proto_coef.size(0))\n select = perm[:cfg.masks_to_train]\n\n proto_coef = proto_coef[select, :]\n pos_idx_t = pos_idx_t[select]\n \n if process_gt_bboxes:\n pos_gt_box_t = pos_gt_box_t[select, :]\n\n num_pos = proto_coef.size(0)\n mask_t = downsampled_masks[:, :, pos_idx_t] \n\n # Size: [mask_h, mask_w, num_pos]\n pred_masks = proto_masks @ proto_coef.t()\n pred_masks = cfg.mask_proto_mask_activation(pred_masks)\n\n if cfg.mask_proto_double_loss:\n if cfg.mask_proto_mask_activation == activation_func.sigmoid:\n pre_loss = F.binary_cross_entropy(torch.clamp(pred_masks, 0, 1), mask_t, reduction='sum')\n else:\n pre_loss = F.smooth_l1_loss(pred_masks, mask_t, reduction='sum')\n \n loss_m += cfg.mask_proto_double_loss_alpha * pre_loss\n\n if cfg.mask_proto_crop:\n pred_masks = crop(pred_masks, pos_gt_box_t)\n \n if cfg.mask_proto_mask_activation == activation_func.sigmoid:\n pre_loss = F.binary_cross_entropy(torch.clamp(pred_masks, 0, 1), mask_t, reduction='none')\n else:\n pre_loss = F.smooth_l1_loss(pred_masks, mask_t, reduction='none')\n\n if cfg.mask_proto_normalize_mask_loss_by_sqrt_area:\n gt_area = torch.sum(mask_t, dim=(0, 1), keepdim=True)\n pre_loss = pre_loss / (torch.sqrt(gt_area) + 0.0001)\n \n if cfg.mask_proto_reweight_mask_loss:\n pre_loss = pre_loss * mask_reweighting[:, :, pos_idx_t]\n \n if cfg.mask_proto_normalize_emulate_roi_pooling:\n weight = mask_h * mask_w if cfg.mask_proto_crop else 1\n pos_get_csize = center_size(pos_gt_box_t)\n gt_box_width = pos_get_csize[:, 2] * mask_w\n gt_box_height = pos_get_csize[:, 3] * mask_h\n pre_loss = pre_loss.sum(dim=(0, 1)) / gt_box_width / gt_box_height * weight\n\n\n # If the number of masks were limited scale the loss accordingly\n if old_num_pos > num_pos:\n pre_loss *= old_num_pos / num_pos\n\n loss_m += torch.sum(pre_loss)\n \n losses = {'M': loss_m * cfg.mask_alpha / mask_h / mask_w}\n \n if cfg.mask_proto_coeff_diversity_loss:\n losses['D'] = loss_d\n\n return losses\n" ]
[ [ "torch.nn.functional.normalize", "torch.abs", "torch.nn.functional.softmax", "torch.max", "torch.nn.functional.log_softmax", "torch.cat", "torch.sqrt", "torch.nn.functional.binary_cross_entropy_with_logits", "torch.nn.functional.cross_entropy", "torch.nn.functional.logsigmoid", "torch.sum", "torch.zeros_like", "torch.no_grad", "torch.nn.functional.smooth_l1_loss", "torch.clamp", "torch.autograd.Variable" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
harrisonzhu508/data
[ "a3b95ced4abad6653d20f67f3f285abeeb0c2b25" ]
[ "src/pipelines/weather/weather_pipeline.py" ]
[ "import re\nimport sys\nimport math\nfrom random import shuffle\nfrom functools import partial\nfrom typing import Any, Dict, List, Tuple\nfrom multiprocessing import cpu_count\nfrom multiprocessing.pool import ThreadPool as Pool\n\nimport numpy\nfrom tqdm.contrib import concurrent\nfrom pandas import DataFrame, Series, Int64Dtype, merge, read_csv, concat, isna\n\nfrom lib.cast import safe_int_cast\nfrom lib.pipeline import DataPipeline, DefaultPipeline, PipelineChain\nfrom lib.time import datetime_isoformat\nfrom lib.utils import ROOT\n\n\nclass WeatherPipeline(DefaultPipeline):\n\n # A bit of a circular dependency but we need the latitude and longitude to compute weather\n def fetch(self, cache: Dict[str, str], **fetch_opts) -> List[str]:\n return [ROOT / \"output\" / \"tables\" / \"geography.csv\"]\n\n @staticmethod\n def haversine_distance(\n stations: DataFrame, lat: float, lon: float, radius: float = 6373.0\n ) -> Series:\n \"\"\" Compute the distance between two <latitude, longitude> pairs in kilometers \"\"\"\n\n # Compute the pairwise deltas\n lat_diff = stations.lat - lat\n lon_diff = stations.lon - lon\n\n # Apply Haversine formula\n a = numpy.sin(lat_diff / 2) ** 2\n a += math.cos(lat) * numpy.cos(stations.lat) * numpy.sin(lon_diff / 2) ** 2\n c = numpy.arctan2(numpy.sqrt(a), numpy.sqrt(1 - a)) * 2\n\n return radius * c\n\n @staticmethod\n def nearest_station(stations, lat: float, lon: float):\n # Compute the distance with each station\n distances = WeatherPipeline.haversine_distance(stations, lat, lon)\n\n # Return the closest station and its distance\n idxmin = distances.idxmin()\n return distances.loc[idxmin], stations.loc[idxmin]\n\n @staticmethod\n def fix_temp(value: int):\n value = safe_int_cast(value)\n return None if value is None else \"%.1f\" % (value / 10.0)\n\n @staticmethod\n def station_records(station_cache: Dict[str, DataFrame], stations: DataFrame, location: Series):\n\n # Get the nearest station from our list of stations given lat and lon\n distance, nearest = WeatherPipeline.nearest_station(stations, location.lat, location.lon)\n\n # Query the cache and pull data only if not already cached\n if nearest.id not in station_cache:\n\n # Read the records from the nearest station\n station_url = (\n \"https://www.ncei.noaa.gov/data\"\n \"/global-historical-climatology-network-daily/access/{}.csv\"\n ).format(nearest.id)\n column_mapping = {\n \"DATE\": \"date\",\n \"STATION\": \"noaa_station\",\n \"TMIN\": \"minimum_temperature\",\n \"TMAX\": \"maximum_temperature\",\n \"PRCP\": \"rainfall\",\n \"SNOW\": \"snowfall\",\n }\n data = read_csv(station_url, usecols=lambda column: column in column_mapping.keys())\n data = data.rename(columns=column_mapping)\n\n # Convert temperature to correct values\n data[\"minimum_temperature\"] = data[\"minimum_temperature\"].apply(\n WeatherPipeline.fix_temp\n )\n data[\"maximum_temperature\"] = data[\"maximum_temperature\"].apply(\n WeatherPipeline.fix_temp\n )\n\n # Get only data for 2020 and add location values\n data = data[data.date > \"2019-12-31\"]\n\n # Save into the cache\n station_cache[nearest.id] = data\n\n # Get station records from the cache\n data = station_cache[nearest.id].copy()\n\n # Return all the available data from the records\n output_columns = [\n \"date\",\n \"key\",\n \"noaa_station\",\n \"noaa_distance\",\n \"minimum_temperature\",\n \"maximum_temperature\",\n \"rainfall\",\n \"snowfall\",\n ]\n data[\"key\"] = location.key\n data[\"noaa_distance\"] = \"%.03f\" % distance\n return data[[col for col in output_columns if col in data.columns]]\n\n def parse_dataframes(\n self, dataframes: List[DataFrame], aux: Dict[str, DataFrame], **parse_opts\n ):\n\n # Get all the weather stations with data up until 2020\n stations_url = \"https://www1.ncdc.noaa.gov/pub/data/ghcn/daily/ghcnd-inventory.txt\"\n stations = read_csv(\n stations_url,\n sep=r\"\\s+\",\n names=(\"id\", \"lat\", \"lon\", \"measurement\", \"year_start\", \"year_end\"),\n )\n stations = stations[stations.year_end == 2020][[\"id\", \"lat\", \"lon\", \"measurement\"]]\n\n # Filter stations that at least provide max and min temps\n measurements = [\"TMIN\", \"TMAX\"]\n stations = stations.groupby([\"id\", \"lat\", \"lon\"]).agg(lambda x: \"|\".join(x))\n stations = stations[stations.measurement.apply(lambda x: all(m in x for m in measurements))]\n stations = stations.reset_index()\n\n # Get all the POI from metadata and go through each key\n metadata = dataframes[0][[\"key\", \"latitude\", \"longitude\"]].dropna()\n\n # Convert all coordinates to radians\n stations[\"lat\"] = stations.lat.apply(math.radians)\n stations[\"lon\"] = stations.lon.apply(math.radians)\n metadata[\"lat\"] = metadata.latitude.apply(math.radians)\n metadata[\"lon\"] = metadata.longitude.apply(math.radians)\n\n # Use a cache to avoid having to query the same station multiple times\n station_cache: Dict[str, DataFrame] = {}\n\n # Make sure the stations and the cache are sent to each function call\n map_func = partial(WeatherPipeline.station_records, station_cache, stations)\n\n # We don't care about the index while iterating over each metadata item\n map_iter = [record for _, record in metadata.iterrows()]\n\n # Shuffle the iterables to try to make better use of the caching\n shuffle(map_iter)\n\n # Bottleneck is network so we can use lots of threads in parallel\n records = concurrent.thread_map(map_func, map_iter, total=len(metadata))\n\n return concat(records)\n\n\nclass WeatherPipelineChain(PipelineChain):\n\n schema: Dict[str, type] = {\n \"date\": str,\n \"key\": str,\n \"noaa_station\": str,\n \"noaa_distance\": float,\n \"minimum_temperature\": float,\n \"maximum_temperature\": float,\n \"rainfall\": float,\n \"snowfall\": float,\n }\n\n pipelines: List[Tuple[DataPipeline, Dict[str, Any]]] = [(WeatherPipeline(), {})]\n" ]
[ [ "pandas.concat", "pandas.read_csv", "numpy.sqrt", "numpy.cos", "numpy.sin" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
DCAN-Labs/abcd-bids-tfmri-pipeline
[ "358581a244887a7fc385bc73c3c22e4683a22ad5" ]
[ "src/pipeline_utilities.py" ]
[ "#!/usr/bin/env python3\n# coding: utf-8\n\n\"\"\"\nCommon source for utility functions used by ABCD-BIDS task-fmri-pipeline\nGreg Conan: [email protected]\nCreated: 2021-01-15\nUpdated: 2021-11-12\n\"\"\"\n\n# Import standard libraries\nimport argparse\nfrom datetime import datetime # for seeing how long scripts take to run\nfrom glob import glob\nimport json\nimport multiprocessing as mp\nimport os\nimport pandas as pd\nimport random # only used by rand_string\nimport shutil\nimport string # only used by rand_string\nimport subprocess\nimport sys\nimport time\n\n# Constants: Name of scanner-info command-line argument, directory containing\n# the main pipeline script, SLURM-/SBATCH-related arguments' default names, and\n# name of the argument to get the directory containing the main wrapper script\nSCAN_ARG = 'scanners_info'\nSCRIPT_DIR = os.path.dirname(os.path.dirname(__file__))\nSLURM_ARGS = ('account', 'cpus', 'memory', 'print_progress', 'sleep', 'time')\nWRAPPER_LOC = 'wrapper_location'\n\n\ndef add_arg_if_in_arg_names(arg_name, all_args, parser, *shortnames, **kwargs):\n \"\"\"\n Wrapper for argparse.ArgumentParser.add_argument. Nearly identical, but \n will only add the argument to the parser if arg_name is in all_args.\n :param arg_name: String naming the argument to (maybe) add to parser\n :param all_args: Set of strings; each names a command-line argument\n :param parser: argparse.ArgumentParser\n :param shortnames: Unpacked list of strings; each is arg_name shortened\n :param kwargs: Unpacked dictionary of argparse attributes to give the arg\n :return: parser, but (maybe) with the argument named arg_name added\n \"\"\"\n if arg_name in all_args:\n cli_arg = as_cli_arg(arg_name)\n parser.add_argument(\n cli_arg[1:], cli_arg, *shortnames, **kwargs\n )\n return parser\n\n\ndef add_lvl_args_to(parser):\n \"\"\"\n :param parser: argparse.ArgumentParser with all command-line arguments \n that the user gave to pipeline_wrapper.py\n :return: parser with all command-line arguments needed for level X analysis\n \"\"\"\n # 1) Top-level directory with pipeline_wrapper.py 2) Run number 3) Path to\n # .json file which stores the 'paths' dictionary \n # parser.add_argument('--code-dir', type=valid_readable_dir, required=True)\n parser.add_argument('--run-number', type=valid_whole_number, required=True)\n parser.add_argument('--temp-json', type=valid_readable_json, required=True)\n return parser\n\n\ndef add_slurm_args_to(parser):\n \"\"\"\n :param parser: argparse.ArgumentParser with some command-line arguments \n :return: parser with all CLI arguments needed to run parallel SLURM jobs\n \"\"\"\n default_CPUs = 1\n default_gb_mem = 8\n default_sleep = 10\n default_time_limit = \"01:00:00\"\n parser.add_argument(\n '-A', '--account',\n help=\"Name of the account to submit the SBATCH job under.\"\n )\n parser.add_argument(\n '-c', '--cpus', type=valid_whole_number, default=default_CPUs,\n help=('Number of CPUs to use for each Python job. By default, this '\n 'argument\\'s value will be {}.'.format(default_CPUs))\n )\n parser.add_argument(\n '-mem', '--memory', type=valid_whole_number, default=default_gb_mem,\n help=(\"Memory in gigabytes (GB) to assign to each sbatch job. The \"\n \"default number is {} GB.\".format(default_gb_mem))\n )\n parser.add_argument(\n '-progress', '--print-progress', action='store_true',\n help=('Include this flag for the script to print updates about its '\n 'progress at intervals defined by --sleep. This will also print '\n 'every command that is run to submit a pipeline batch job.')\n )\n parser.add_argument(\n '-sleep', '--sleep', type=valid_whole_number, default=default_sleep,\n help=(\"Number of seconds to wait between batch job submissions. The \"\n \"default number is {}.\".format(default_sleep))\n )\n parser.add_argument(\n '-time', '--time', metavar=\"SLURM_JOB_TIME_LIMIT\",\n type=valid_time_str, default=default_time_limit,\n help=(\"Time limit for each automated_subset_analysis batch job. The \"\n \"time limit must be formatted specifically as HH:MM:SS where HH \"\n \"is hours, MM is minutes, and SS is seconds. {} is the default \"\n \"time limit.\".format(default_time_limit))\n )\n return parser\n\n\ndef argify(argname, argval):\n \"\"\"\n :param argname: String naming a parameter for a script called from terminal\n :param argval: Object to assign in string form as the value of the argument\n :return: String, a parameter assignment for a script called from terminal\n \"\"\"\n return \"--{}={}\".format(argname, argval)\n\n\ndef as_cli_arg(arg_str):\n \"\"\"\n :param arg_str: String naming a stored argument taken from the command line\n :return: String which is the command-line argument form of arg_str\n \"\"\"\n return \"--\" + arg_str.replace(\"_\", \"-\")\n\n\ndef copy_and_rename_file(old_file, new_file):\n \"\"\"\n Rename a file and copy it to a new location\n :param old_file: String, valid path to an existing file to copy\n :param new_file: String, valid path to what will be a copy of old_file\n \"\"\"\n os.rename(shutil.copy2(old_file, os.path.dirname(new_file)), new_file)\n\n\ndef copy_event_files_to_default_dir(cli_args, all_event_files):\n \"\"\"\n Copy all event files into the default event files directory\n :param cli_args: Dictionary containing all command-line arguments from user\n :param all_event_files: List of strings that are valid paths to real files\n \"\"\"\n for each_EV_file in all_event_files:\n try: shutil.copy(each_EV_file, cli_args['events_dir'])\n except shutil.SameFileError: pass\n\n\ndef count_lines_in_txt_file(filepath):\n \"\"\"\n Quickly count how many lines are in a text file.\n Taken from pynative.com/python-count-number-of-lines-in-file\n :param filepath: String, valid path to an existing readable text file\n :return: Int, the number of lines in the file at filepath\n \"\"\"\n with open(filepath, 'r') as infile: # open file in read mode\n for count, _ in enumerate(infile):\n pass\n return count + 1\n\n\ndef dict_has(a_dict, a_key):\n \"\"\"\n :param a_dict: Dictionary (any)\n :param a_key: Object (any)\n :return: True if and only if a_key is mapped to something truthy in a_dict\n \"\"\"\n return a_key in a_dict and a_dict[a_key]\n\n\ndef ensure_dict_has(a_dict, a_key, new_value):\n \"\"\"\n :param a_dict: Dictionary (any)\n :param a_key: Object which will be a key in a_dict\n :param new_value: Object to become the value mapped to a_key in a_dict\n unless a_key is already mapped to a value\n :return: a_dict, but with a_key mapped to some value\n \"\"\"\n if not dict_has(a_dict, a_key):\n a_dict[a_key] = new_value\n return a_dict\n\n\ndef exit_with_time_info(start_time, exit_code=0):\n \"\"\"\n Terminate the pipeline after displaying a message showing how long it ran\n :param start_time: datetime.datetime object of when the script started\n \"\"\"\n print('The pipeline for this subject took this long to run {}: {}'\n .format('successfully' if exit_code == 0 else 'and then crashed',\n datetime.now() - start_time))\n sys.exit(exit_code)\n\n\ndef extract_from_json(json_path):\n \"\"\"\n :param json_path: String, a valid path to a real readable .json file\n :return: Dictionary, the contents of the file at json_path\n \"\"\"\n with open(json_path, 'r') as infile:\n return json.load(infile)\n\n\ndef get_all_analysis_paths(cli_args):\n \"\"\"\n Build and save paths for various variables called throughout the pipeline\n :param cli_args: Dictionary containing all command-line arguments from user\n :return: Dictionary containing paths to all of the following variables:\n AROI2, BIDS, dir_lvl, feat_name, final_smooth, lvl_2_paths,\n sub_paths, templates\n \"\"\"\n paths = {'dir_lvl': {str(lvl): os.path.join( # Feature dirs for all levels\n cli_args['output'], 'Level{}_feats'.format(lvl)\n ) for lvl in (1, 2)},\n 'feat_name': '{}.feat'.format(cli_args['study_name']),\n 'final_smooth': ('_smoothed_{}mm' # Spatial smoothing variable \n .format(cli_args['spat_smooth']))}\n for lvl in cli_args['levels']:\n tmpllv = 'template{}'.format(lvl)\n paths[tmpllv] = os.path.join(cli_args['templates'], cli_args[tmpllv])\n paths['lvl_2'] = get_lvl_paths(\n paths['dir_lvl']['2'], get_sub_base(cli_args),\n cli_args['study_name'] + '.gfeat', cli_args['runs'], 'fsf'\n )\n paths['sub_ses'] = {f_or_a: os.path.join( # Subject anat & func directories\n cli_args['study_dir'], 'derivatives',\n cli_args['bids_dir'], cli_args['subject'],\n cli_args['ses'], f_or_a\n ) for f_or_a in ('anat', 'func')} \n paths['AROI2'] = os.path.join(cli_args['templates'], 'Atlas_ROIs.2.nii.gz')\n return paths\n\n\ndef get_and_print_time_since(event_name, event_time):\n \"\"\"\n Print and return a string showing how much time has passed since the\n current running script reached a certain part of its process\n :param event_name: String to print after 'Time elapsed since '\n :param event_time: datetime object representing a time in the past\n :return: String with an easily human-readable message showing how much time\n has passed since {event_time} when {event_name} happened.\n \"\"\"\n timestamp = (\"\\nTime elapsed since {}: {}\"\n .format(event_name, datetime.now() - event_time))\n print(timestamp)\n return timestamp\n\n\ndef get_args_to_run_film_gls(**kwargs):\n \"\"\"\n :return: List of strings which are a Bash command calling film_gls\n \"\"\"\n in_arg = kwargs.pop('in_arg')\n to_call = ['film_gls', '--sa', argify('in', in_arg)] \n for argname, argval in kwargs.items():\n to_call.append(argify(argname, argval))\n return to_call\n\n\ndef get_default_ext_command(cmd_name):\n \"\"\"\n Try to get valid path to external software command file without user input\n :param cmd_name: String naming the executable command file\n :return: String, path to the command if the user has the command alias in\n their .bashrc / $PATH; otherwise None\n \"\"\"\n try: # If the command path is already defined, then use it\n cmd = subprocess.check_output((\"which\", cmd_name)\n ).decode('utf-8').split()[-1]\n except subprocess.CalledProcessError:\n cmd = None\n return cmd\n\n\ndef get_LR_functions(cli_args, paths):\n \"\"\"\n :param cli_args: Dictionary containing all command-line arguments from user\n :param paths: Dictionary of path strings, and of dictionaries of path\n strings, used throughout processing in both levels\n :return: Dictionary mapping 'surf' to a function which returns the file\n path string to a .surf.gii file, and mapping 'shape' to a function\n which returns the file path string to a .shape.gii file\n \"\"\"\n return {'surf': lambda x: os.path.join(\n paths['sub_ses']['anat'], get_subj_ses(cli_args) +\n '_hemi-{}_space-MNI_mesh-fsLR32k_midthickness.surf.gii'.format(x)\n ), 'shape': lambda y: os.path.join(\n cli_args['templates'], y + '.atlasroi.32k_fs_LR.shape.gii'\n )}\n\n\ndef get_lvl_paths(lvl_dir, sub_base, feat_name, runs, *extra_subdirs):\n \"\"\"\n Get a dictionary of paths to analysis-level-specific files for paths dict\n :param lvl_dir: String, path to the feat directory for level 1 or 2\n :param sub_base: String identifying a subject, session, and task\n :param feat_name: String naming a feature\n :param runs: List of strings or integers, each identifying a run\n :param extra_subdirs: Unpacked list of strings naming subdirectories of \n the level parent directory\n :return: Dictionary mapping string keys to string paths\n \"\"\"\n lvl_paths = {'parent': os.path.join(lvl_dir, sub_base + '_' + feat_name)}\n for run in runs:\n lvl_paths[run] = os.path.join(lvl_paths['parent'],\n 'level1_run-{}'.format(run))\n for subdr in extra_subdirs:\n lvl_paths[subdr] = os.path.join(lvl_paths['parent'], subdr + '_files')\n return lvl_paths\n\n\ndef get_main_pipeline_arg_names():\n \"\"\"\n :return: Set containing strings naming all command-line arguments included\n by default in the main script, pipeline_wrapper.py\n \"\"\"\n return {'bids_dir', 'censor', 'events_dir', 'fd', 'filter', 'fsl_dir',\n 'keep_all', 'levels', 'no_parallel', 'output', 'runs', 'ses',\n 'spat_smooth', 'subject', 'surf_smooth', 'study_dir', 'study_name',\n 'task', 'temp_dir', 'templates', 'template1', 'template2',\n 'vol_smooth', 'wb_command', WRAPPER_LOC}\n\n\ndef get_optional_cli_args(cli_args, drop_slurm=False):\n \"\"\"\n :param cli_args: Dictionary with all validated command-line arguments,\n all of which are used by this function\n :param drop_slurm: True to exclude SLURM arguments; else False\n :return: List of most cli_args optional arguments and their values\n \"\"\"\n optional_args = list()\n for arg in cli_args.keys():\n if cli_args[arg] and not (drop_slurm and arg in SLURM_ARGS):\n optional_args.append(as_cli_arg(arg))\n if isinstance(cli_args[arg], list):\n for el in cli_args[arg]:\n optional_args.append(str(el))\n elif not isinstance(cli_args[arg], bool):\n optional_args.append(str(cli_args[arg]))\n return optional_args\n \n\ndef get_pipeline_cli_argparser(arg_names=get_main_pipeline_arg_names()):\n \"\"\"\n :param arg_names: Set containing strings naming all command-line arguments\n :return: argparse.ArgumentParser with all command-line arguments \n needed to run pipeline_wrapper.py\n \"\"\"\n # Default values for user input arguments\n default_BIDS_dir = 'abcd-hcp-pipeline'\n default_censor_num = 0 # 2\n default_fd = 0.9\n default_smooth = 0\n default_study_name = 'ABCD'\n default_runs_lvls = [1, 2]\n default_temporal_filter = 100\n default_wb_command = get_default_ext_command('wb_command')\n generic_dtseries_path = os.path.join(\n '(--study-dir)', 'derivatives', '(--bids-dir)',\n '(--subject)', '(--ses)', 'func',\n 'sub-(--subject)_ses-(--ses)_task-(--task)_'\n 'run-(--runs)_bold_timeseries.dtseries.nii'\n )\n generic_output_dirpath = os.path.join('(--study-dir)', 'derivatives',\n 'abcd-bids-tfmri-pipeline',\n '(--subject)', '(--ses)')\n\n # Strings used in multiple help messages\n msg_default = ' By default, this argument\\'s value(s) will be {}.'\n msg_pipeline = 'Name of the {} that you are running the pipeline on.'\n msg_smooth = ('Millimeters of {} smoothing that has already been applied '\n 'in the minimal processing steps.')\n msg_template = 'Name (not full path) of the Level {} .fsf template file.'\n msg_whole_num = ' This argument must be a positive integer.'\n\n # Create parser with command-line arguments from user\n parser = argparse.ArgumentParser(description=(\n 'ABCD fMRI Task Prep pipeline. Inputs must be in the same format '\n 'as ABCD-HCP-Pipeline outputs after running filemap.'\n ))\n parser = add_arg_if_in_arg_names('bids_dir', arg_names, parser,\n metavar='NAME_OF_BIDS_DERIVATIVES_PIPELINE_DIRECTORY',\n default=default_BIDS_dir,\n help=('Name of the BIDS-standard file-mapped directory with subject '\n 'data in the \"derivatives\" subdirectory of your --study-dir. '\n 'This path should be valid: ' + generic_dtseries_path +\n msg_default.format(default_BIDS_dir))\n )\n # Specify how many initial frames/volumes to censor\n parser = add_arg_if_in_arg_names('censor', arg_names, parser,\n metavar='INITIAL_NUMER_OF_TIMEPOINTS_TO_CENSOR', \n default=default_censor_num, type=valid_whole_number,\n help=('The number of initial frames/volumes to censor.'\n + msg_whole_num + msg_default.format(default_censor_num))\n )\n parser = add_arg_if_in_arg_names('events_dir', arg_names, parser, \n metavar='EVENT_FILES_DIRECTORY',\n type=valid_readable_dir, \n help='Valid path to a real directory containing event .tsv files.' \n )\n # Specify framewise displacement threshold to censor volumes with high motion\n parser = add_arg_if_in_arg_names('fd', arg_names, parser, \n metavar='FRAMEWISE_DISPLACEMENT_THRESHOLD',\n default=default_fd, type=valid_float_0_to_1,\n help=('The framewise displace threshold for censoring volumes with '\n 'high motion. This must be a decimal between 0 and 1.{}'\n .format(msg_default.format(default_fd)))\n )\n # High pass temporal filter cutoff number value\n parser = add_arg_if_in_arg_names('filter', arg_names, parser, \n metavar='HIGH_PASS_TEMPORAL_FILTER_CUTOFF',\n default=default_temporal_filter, type=valid_whole_number,\n help=('High pass filter cutoff (in seconds).{}{}'.format(\n msg_whole_num, msg_default.format(default_temporal_filter)\n ))\n )\n parser = add_arg_if_in_arg_names('fsl_dir', arg_names, parser, \n '-fsl', '--fsl', dest='fsl_dir', type=valid_readable_dir,\n help=('Valid path to an existing directory containing the executable '\n 'files fsl, fslmerge, fslmaths, flameo, and feat_model from '\n 'the FMRIB Software Library (FSL).')\n )\n parser = add_arg_if_in_arg_names('keep_all', arg_names, parser, \n action='store_true',\n help=('Include this flag to keep all files generated during the '\n 'pipeline. By default, the pipeline will only keep dtseries, '\n 'dof, log, and event files.')\n )\n # Which analysis levels to run\n parser = add_arg_if_in_arg_names('levels', arg_names, parser, \n metavar='ANALYSIS_LEVELS_TO_RUN',\n nargs='*', choices=default_runs_lvls, type=valid_whole_number,\n help=('Levels to conduct the analysis on: {0} for one run, and/or '\n '{1} to merge multiple runs.'.format(*default_runs_lvls))\n )\n parser = add_arg_if_in_arg_names('no_parallel', arg_names, parser,\n action='store_true',\n help=('Include this flag to process level 1 analysis runs '\n 'sequentially. By default, the script will process the analyses '\n 'in parallel simultaneously.')\n )\n parser = add_arg_if_in_arg_names('output', arg_names, parser, \n '-out', metavar='OUTPUT_DIRECTORY', type=valid_output_dir, # required=True, \n help=('Directory path to save pipeline outputs into.'\n + msg_default.format(generic_output_dirpath))\n )\n # Specify the number of runs each subject has\n parser = add_arg_if_in_arg_names('runs', arg_names, parser, \n metavar='RUN', \n default=default_runs_lvls, type=valid_whole_number, nargs=\"+\",\n help=('Each subject\\'s number of runs. This argument must be 1 or '\n 'more positive integers provided as a space-delimited list. '\n 'For example: 1 2 3 4. By default, this argument\\'s value(s) '\n 'will be 1 2.')\n )\n parser = add_arg_if_in_arg_names(SCAN_ARG, arg_names, parser, \n type=valid_readable_file,\n help=('Path to existing .csv file listing all scanners\\' parameters. '\n + msg_default.format('scan_info/{}.csv in the code directory.'\n .format(SCAN_ARG)))\n )\n # Which session to run the pipeline on\n parser = add_arg_if_in_arg_names('ses', arg_names, parser, \n metavar='SESSION', required=True, # default=default_ses,\n type=lambda x: valid_subj_ses(x, 'ses-', 'session'), #, 'ses'),\n help=msg_pipeline.format('session')\n )\n # Desired spatial smoothing number\n parser = add_arg_if_in_arg_names('spat_smooth', arg_names, parser, \n metavar='DESIRED_SPATIAL_SMOOTHING', \n default=default_smooth, type=valid_whole_number,\n help=('Millimeters of spatial smoothing that you want for the surface '\n 'and volume data.'\n + msg_whole_num + msg_default.format(default_smooth))\n )\n parser = add_arg_if_in_arg_names('subject', arg_names, parser, \n metavar='SUBJECT_ID', required=True,\n type=lambda x: valid_subj_ses(x, 'sub-', 'subject'), #, 'NDAR', 'INV'),\n help='ID of subject to process.'\n )\n # Surface smoothing number\n parser = add_arg_if_in_arg_names('surf_smooth', arg_names, parser, \n metavar='CURRENT_SURFACE_SMOOTHING', \n default=default_smooth, type=valid_whole_number,\n help=''.join((msg_smooth.format('surface'), msg_whole_num,\n msg_default.format(default_smooth)))\n )\n # Set file path for base directory and BIDS directory\n parser = add_arg_if_in_arg_names('study_dir', arg_names, parser, \n metavar='BIDS_BASE_STUDY_DIRECTORY',\n type=valid_readable_dir, required=True, \n help='Valid path to existing base study directory.'\n )\n parser = add_arg_if_in_arg_names('study_name', arg_names, parser, \n metavar='STUDY_NAME', default=default_study_name,\n help=msg_pipeline.format('study')\n )\n # Which task you are running the pipeline on\n parser = add_arg_if_in_arg_names('task', arg_names, parser, \n metavar='TASK_NAME', required=True,\n help=msg_pipeline.format('task') # + msg_choices(choices_tasks)\n )\n parser = add_arg_if_in_arg_names('temp_dir', arg_names, parser, \n type=valid_readable_dir, metavar='TEMPORARY_DIRECTORY',\n help=('Valid path to existing directory to save temporary files into.')\n )\n parser = add_arg_if_in_arg_names('templates', arg_names, parser, \n type=valid_readable_dir, \n help='Valid path to existing directory with template .fsf files.'\n )\n for lvl in default_runs_lvls: # Specify the .fsf template files' names\n parser = add_arg_if_in_arg_names(\n 'template{}'.format(lvl), arg_names, parser, \n metavar='LEVEL_{}_TEMPLATE_NAME'.format(lvl),\n type=valid_template_filename, help=msg_template.format(lvl)\n )\n # Volume smoothing number\n parser = add_arg_if_in_arg_names('vol_smooth', arg_names, parser, \n metavar='CURRENT_VOLUME_SMOOTHING',\n default=default_smooth, type=valid_whole_number,\n help=''.join((msg_smooth.format('volume'), msg_whole_num,\n msg_default.format(default_smooth)))\n )\n # Specify path to wb_command\n parser = add_arg_if_in_arg_names('wb_command', arg_names, parser, \n default=default_wb_command, type=valid_readable_file,\n help=('Path to wb_command file to run Workbench Command. If this flag '\n 'is excluded, then the script will try to guess the path to '\n 'the wb_command file by checking the user\\'s BASH aliases. '\n 'Your default wb_command is \"{}\". If '\n 'that says \"None\", then you need to include this argument.'\n .format(default_wb_command))\n )\n # Argument used to get this script's dir\n parser = add_arg_if_in_arg_names(WRAPPER_LOC, arg_names, parser,\n type=valid_readable_dir, required=True,\n help=('Valid path to existing ABCD-BIDS-task-fmri-pipeline directory '\n 'that contains pipeline_wrapper.py')\n ) \n return parser\n\n\ndef get_region_path_vars(cli_args, paths, run):\n \"\"\"\n Build and return paths to particular brain region images' files/dirs\n by filling in the unique parts of generic path strings\n :param cli_args: Dictionary containing all command-line arguments from user\n :param paths: Dictionary of path strings, and of dictionaries of path\n strings, used throughout processing in both levels\n :param run: Whole number (as an int or a string) defining which run this is\n :return: Tuple of string generic paths: design, func_str, subcort, surf_str\n \"\"\"\n # Paths to design file base and subcortical volume stats directory\n design = os.path.join(paths['lvl_1']['fsf'],\n get_sub_base(cli_args, run) + '_level1')\n subcort = os.path.join(paths['lvl_1']['parent'], 'SubcorticalVolumeStats')\n\n # Generic strings used as templates for paths later \n func_str = os.path.join(paths['lvl_1']['intermediate'], \n '{}{}_filtered.atlasroi{}.{}.32k_fs_LR.func.gii')\n surf_str = os.path.join(paths['sub_ses']['anat'], (\n '{}_hemi-{}_space-MNI_mesh-fsLR32k_midthickness.surf.gii'\n ))\n return design, func_str, subcort, surf_str\n\n\ndef get_replacements(cli_args, **kwargs):\n \"\"\"\n :param cli_args: Dictionary containing all command-line arguments from user\n :return: Dictionary mapping variables' generic names in template files to \n those variables' actual values provided by the user\n \"\"\"\n replacements = {'SUBID': cli_args['subject'],\n 'FEAT_NAME': cli_args['study_name'], # Not paths['feat_name']\n 'FIN_SMOOTH': str(cli_args['spat_smooth']),\n 'HP_FILTER': str(cli_args['filter']), \n 'SESSION': cli_args['ses'], 'TASK': cli_args['task'],\n 'OUTPUT_DIR': cli_args['output'],\n 'EVENTS_DIR': cli_args['events_dir'],\n 'STUDY_DIR': cli_args['study_dir']}\n replacements.update(kwargs)\n return replacements\n\n\ndef get_sbatch_args(cli_args, job):\n \"\"\"\n :param cli_args: Dictionary containing all command-line arguments from user\n :param job: String 1-8 characters long naming the SBATCH job\n :return: List of strings, SLURM-related arguments to pass to the main\n script or level 1 analysis script for parallelization\n \"\"\"\n return [argify('time', cli_args['time']), '-c', str(cli_args['cpus']),\n '-J', job, argify('mem', '{}gb'.format(cli_args[\"memory\"]))]\n\n\ndef get_sub_base(cli_args, run_num=None):\n \"\"\"\n :param cli_args: Dictionary containing all command-line arguments from user\n :param run_num: Whole number as an int or string defining which run this is\n :return: String identifying a subject, session, task, and maybe run\n \"\"\"\n parts = [get_subj_ses(cli_args), 'task-' + cli_args['task']]\n if run_num is not None:\n parts.append('run-{}'.format(run_num))\n return '_'.join(parts)\n\n\ndef get_subj_ses(cli_args):\n \"\"\"\n :param cli_args: Dictionary containing all command-line arguments from user\n :return: String which combines --subject and --ses from command line\n \"\"\"\n return '_'.join((cli_args['subject'], cli_args['ses']))\n\n\ndef get_TR_and_ntpts(dtseries_path, wb_command_path):\n \"\"\"\n :param dtseries_path: String, the full path to a .dtseries.nii file\n :param wb_command_path: String, the full path to the wb_command executable\n :return: Tuple of 2 numbers, the number of timepoints and repetition time\n \"\"\"\n if not os.path.exists(dtseries_path):\n sys.exit('Error: {} does not exist'.format(dtseries_path))\n else:\n ntpts = wb_command_get_info(wb_command_path, dtseries_path,\n 'number-of-maps')\n rep_time = wb_command_get_info(wb_command_path, dtseries_path,\n 'step-interval')\n return rep_time, ntpts\n\n\ndef glob_and_copy(dest_dirpath, *path_parts_to_glob):\n \"\"\"\n Collect all files matching a glob string, then copy those files\n :param dest_dirpath: String, a valid path of a directory to copy files into\n :param path_parts_to_glob: Unpacked list of strings which join to form a\n glob string of a path to copy files from\n \"\"\"\n for file_src in glob(os.path.join(*path_parts_to_glob)):\n shutil.copy(file_src, dest_dirpath)\n\n\ndef make_and_save_confound_matrix(cli_args, desc_tsv_file, lvl_paths,\n sub_run_basename):\n \"\"\"\n Create the confound matrix and copy it to subjects fsf_paths for each run\n :param cli_args: Dictionary containing all command-line arguments from user\n :param desc_tsv_file: String naming a .tsv file in intermediate_files/ dir\n :param lvl_paths: Dictionary mapping keys to dir path strings\n :param sub_run_basename: String naming the subject and the run number (?)\n :return: String, the base name of the confound matrix .csv file\n \"\"\"\n # Local variables: File paths, step filename, adjusted variable to censor\n # initial frames based on user-specification, and result (confounds fname)\n in_file = os.path.join(lvl_paths['intermediate'], desc_tsv_file)\n def tsv_file_for_step(stepnum):\n return os.path.join(lvl_paths['intermediate'],\n ('{0}_desc-filteredincludingFD_motion_step{1}.tsv'\n .format(sub_run_basename, stepnum)))\n censor_volumes = list(range(0, cli_args['censor']))\n confounds_name = str(sub_run_basename + '_confound_matrix.tsv')\n \n # Read and write framewise displacement step1 .csv file\n df = pd.read_csv(in_file, sep='\\s+')\n df.framewise_displacement.iloc[[censor_volumes]] = 1\n df.framewise_displacement[df.framewise_displacement < cli_args['fd']] = 0\n df.framewise_displacement[df.framewise_displacement > 0] = 1\n df.framewise_displacement.to_csv(tsv_file_for_step(1), header=False,\n encoding='utf-8', sep='\\t', index=False)\n \n # Read and write step2 .csv file\n df = pd.read_csv(in_file, sep='\\s+')\n cols = ['trans_x_mm', 'trans_y_mm', 'trans_z_mm', 'rot_x_degrees',\n 'rot_y_degrees', 'rot_z_degrees', 'trans_x_mm_dt',\n 'trans_y_mm_dt', 'trans_z_mm_dt', 'rot_x_degrees_dt',\n 'rot_y_degrees_dt', 'rot_z_degrees_dt']\n df = df[cols] # the 'cols' intermediate variable is needed to avoid error\n df.to_csv(tsv_file_for_step(2), sep='\\t', encoding='utf-8',\n index=False, header=False)\n\n # Read and write step3 .csv file\n df = pd.read_csv(tsv_file_for_step(1), names=['A'], sep='\\t')\n df = pd.concat([pd.get_dummies(df[df['A'] == 1].index)\n .transpose(), df], axis=1).fillna(0)\n del df['A']\n df.to_csv(tsv_file_for_step(3), sep='\\t', encoding='utf-8',\n index=False, header=False)\n \n # Read and write confound matrix .csv file; return its name\n pd.concat([pd.read_csv(tsv_file_for_step(x), header=None, sep='\\t')\n for x in (2, 3)], axis=1).to_csv(\n os.path.join(lvl_paths['fsf'], confounds_name),\n sep='\\t', encoding='utf-8', header=None, index=False\n )\n return confounds_name\n\n\ndef individualize_subprocess_run(run_args, run, to_replace):\n \"\"\"\n Cycle through every argument in run_args and replace instances of the\n to_replace string with run, then return the arguments.\n :param run_args: List of strings, all arguments to call via subprocess\n :param run: Whole number (as an int or a string) defining which run this is\n :param to_replace: String to find and replace with each run name/id\n :return: run_args, but with to_replace replaced by run in them all\n \"\"\"\n for i in range(len(run_args)):\n run_args[i] = str(run_args[i]).replace(to_replace, str(run))\n return run_args\n\n\ndef make_fake_nifti(cli_args, generic, old_smoothed, unique_part, cmd, *args):\n \"\"\"\n Create a fake nifti from the smoothed dtseries for high-pass filtering \n :param cli_args: Dictionary containing all command-line arguments from user\n :param generic: String, new smoothed nifti file path but with a '{}' in it\n :param old_smoothed: String, the path to a real old smoothed nifti file\n :param unique_part: String/etc inserted into generic to make a valid path\n :param cmd: String which is a Bash command but with '{}'s in it to replace\n :return: String, the valid path to the now-real new smoothed nifti file\n \"\"\"\n started = datetime.now()\n new_smoothed = generic.format(unique_part)\n cmd_args = cmd.format(old_smoothed, *args, new_smoothed).split()\n if cmd_args[0] == 'wb_command':\n wb_command(cli_args, *cmd_args[1:])\n else: # if cmd_args[0] in ('fsl', 'feat_model', 'film_gls', ):\n run_fsl_tool(cli_args, *cmd_args)\n if cli_args['print_progress']:\n get_and_print_time_since('started making '\n + os.path.basename(new_smoothed), started)\n return new_smoothed\n\n\ndef merge_files_in_range(cli_args, file_names, range_to, args):\n \"\"\"\n :param cli_args: Dictionary containing all command-line arguments from user\n :param file_names: List of strings where each is a filename\n :param range_to: Integer, the number of files to merge\n :param args: List, the rest of the arguments to call merge_to_make_dtseries\n \"\"\"\n for r in range(0, range_to):\n for f in file_names:\n merge_to_make_dtseries(cli_args, str(f) + str(r + 1), *args)\n\n\ndef merge_to_make_dtseries(cli_args, fname, lvl_paths, substats, AROI2, shape):\n \"\"\"\n :param fname: String, base name of the files to merge into a dtseries\n :param lvl_paths: Dictionary mapping keys to dir path strings\n :param substats: String, the path to the subcortical stats directory\n :param AROI2: String, path to Atlas ROI file\n :param shape: Function takes 'L' or 'R' & returns path to shape.gii file\n \"\"\"\n cii_out = os.path.join(lvl_paths['GOStats'], fname + '.dtseries.nii')\n subcort_in = os.path.join(substats, fname + '.nii.gz')\n func = lambda x: os.path.join(lvl_paths['parent'], x + '_SurfaceStats',\n fname + '.func.gii')\n fake_nifti = os.path.join(lvl_paths['GOStats'], fname + '.nii.gz')\n wb_command(cli_args, '-cifti-create-dense-timeseries', cii_out, '-volume',\n subcort_in, AROI2, '-left-metric', func('L'), '-roi-left', \n shape('L'), '-right-metric', func('R'), '-roi-right', shape('R'))\n wb_command(cli_args, '-cifti-convert', '-to-nifti', cii_out, fake_nifti)\n\n\ndef organize_lvl_paths(lvl_paths, *keys_to_remove):\n \"\"\"\n :param lvl_paths: Dictionary mapping keys to dir path strings\n :param keys_to_remove: Unpacked list of strings which are lvl_paths keys\n to exclude from the return list\n :return: List of all values in lvl_paths (except the ones mapped to\n keys_to_remove), sorted alphabetically\n \"\"\"\n lvl_paths = lvl_paths.copy()\n for each_key in keys_to_remove:\n lvl_paths.pop(each_key)\n to_return = list(lvl_paths.values())\n to_return.sort(reverse=False)\n return to_return\n\n\ndef overwrite_dirs(dirs_to_overwrite, mkdir=False):\n \"\"\"\n :param dirs_to_overwrite: List of strings which are paths to directories\n to create or overwrite with empty directories\n :param mkdir: True to remake all the dirs after overwrite, else False\n \"\"\"\n for each_dir in dirs_to_overwrite:\n if os.path.isdir(each_dir):\n shutil.rmtree(each_dir)\n elif os.path.exists(each_dir):\n os.remove(each_dir)\n if mkdir:\n os.makedirs(each_dir)\n\n\ndef rand_string(L):\n \"\"\"\n :param L: Integer, length of the string to randomly generate\n :return: String (of the given length L) of random characters\n \"\"\"\n return ''.join(random.choices(string.ascii_lowercase + string.digits, k=L))\n \n\ndef rename_template_file_vars(old_template, new_template, replacements):\n \"\"\"\n :param old_template: String, path to existing template file\n :param new_template: String, path to new template file which will be \n written with old_template variables but renamed\n :param replacements: Dictionary mapping each string in old_template to the\n string to replace it with in new_template\n \"\"\"\n with open(old_template) as infile: # Open the level 1 or 2 template\n\n # Create new .fsf file; name the output \"sub-*_ses-*_task-*_level*.fsf\"\n with open(new_template, 'w') as outfile:\n for line in infile:\n\n # Use replacements dict to replace variables in the .fsf file\n for src, target in replacements.items():\n line = line.replace(src, target)\n\n # Output the new subject-, (run-,) and task-specific .fsf file\n outfile.write(line)\n\n\ndef run_fsl_tool(cli_args, toolname, *args):\n \"\"\"\n :param cli_args: Dictionary containing all command-line arguments from user\n :param toolname: String naming the executable tool in --fsl-dir to run\n :param args: Unpacked list of arguments to run toolname with\n \"\"\"\n subprocess.check_call([\n valid_readable_file(os.path.join(cli_args['fsl_dir'], toolname)), *args\n ])\n\n\ndef run_parallel_or_sequential(script_path, cli_args, runs, to_replace, \n extra_args, second_fn=None, second_args=None):\n \"\"\"\n Run a Python script via subprocess, either sequentially or in parallel\n depending on cli_args --no-parallel\n :param script_path: String, valid path to real script to run in parallel\n :param cli_args: Dictionary containing all command-line arguments from user\n :param runs: List of unique strings identifying differences between scripts\n :param to_replace: String to find and replace with each job name/id\n \"\"\"\n if cli_args['no_parallel']: # Run processes serially/sequentially\n for run in runs:\n run_python_subscript(script_path, run, to_replace, *extra_args)\n\n else: # Run processes in parallel using Python multiprocessing module\n to_run = list()\n all_args = list()\n for run in runs:\n all_args.append([script_path, run, to_replace, *extra_args])\n to_run.append(mp.Process(args=all_args[-1], name=all_args[-1][0],\n target=run_python_subscript))\n if second_fn and second_args:\n all_args.append(second_args)\n to_run.append(mp.Process(target=second_fn, args=second_args, \n name=second_args[0]))\n if dict_has(cli_args, 'print_progress'):\n print('Running parallel:\\n' + '\\n\\n'.join(str(x) for x in all_args))\n try:\n run_parallel(os.path.basename(script_path), to_run,\n cli_args['sleep'], cli_args['print_progress'])\n except Exception as e:\n sys.exit(e)\n\n\ndef run_parallel(scriptname, processes, sleep, show):\n \"\"\"\n Run a script multiple times in parallel\n :param scriptname: String describing the script being run in parallel\n :param processes: List of multiprocessing.Process objects ready to run\n :param sleep_secs: Integer, how many seconds to wait between (a) process\n submissions and (b) checking if all processes finished\n :param show: True to show the user what's running at sleep_secs intervals;\n otherwise False\n \"\"\"\n started = datetime.now()\n submitted = list()\n failed = False\n for each_process in processes:\n submitted.append(each_process.start())\n time.sleep(sleep)\n while any((p.exitcode is None) for p in processes):\n time.sleep(sleep)\n if show:\n get_and_print_time_since(scriptname + ' started', started)\n if not all(p.exitcode is None or p.exitcode == 0 for p in processes):\n failed = True\n for p in processes:\n p.terminate()\n if failed:\n sys.exit('Error: {} subprocess failed.'.format(scriptname))\n\n\ndef run_python_subscript(path_to_subscript, run, to_replace, *args):\n \"\"\"\n Use subprocess to run a Python 3.6+ script from this code base\n :param path_to_subscript: String, valid path to real Python 3.6+ script\n :param cli_args: Dictionary containing all command-line arguments from user\n :param run: Whole number (as an int or a string) defining which run this is\n :param to_replace: String to find and replace with each run name/id\n :param args: Unpacked list of parameters to run subscript with\n \"\"\"\n start_time = datetime.now()\n try:\n subprocess.check_call(individualize_subprocess_run(\n ['python3', path_to_subscript, *args], run, to_replace\n )) \n except subprocess.CalledProcessError:\n err_type, err_msg, _ = sys.exc_info() # TODO make this into a reusable function? See run_level_1_analysis.get_events_make_template\n sys.exit('\\n\\n{}: {}\\n\\n'.format(err_type.__name__, err_msg))\n get_and_print_time_since(os.path.basename(path_to_subscript)\n + ' started', start_time)\n return # Explicitly end this function so multiprocessing knows it's done\n\n\ndef save_to_json_and_get_path(a_dict, dict_name, out_dir):\n \"\"\"\n :param a_dict: Dictionary with only string keys\n :param dict_name: String naming a_dict\n :param out_dir: String, a valid path to a real directory to save\n the .json file containing a_dict into\n :return: String, the full path to the .json file containing a_dict\n \"\"\"\n json_path = os.path.join(out_dir, 'abcd-bids-pipeline-{}_{}.json'.format(\n dict_name, datetime.now().strftime('%Y-%b-%d_%H-%M')\n ))\n with open(json_path, 'w+') as json_file:\n json_file.write(json.dumps(a_dict))\n return json_path\n\n\ndef valid_float_0_to_1(val):\n \"\"\"\n :param val: Object to check, then throw an error if it is invalid\n :return: val if it is a float between 0 and 1 (otherwise invalid)\n \"\"\"\n return validate(val, lambda x: 0 <= float(x) <= 1, float,\n 'Value must be a number between 0 and 1')\n\n\ndef valid_output_dir(path):\n \"\"\"\n Try to make a folder for new files at path; throw exception if that fails\n :param path: String which is a valid (not necessarily real) folder path\n :return: String which is a validated absolute path to real writeable folder\n \"\"\"\n return validate(path, lambda x: os.access(x, os.W_OK),\n valid_readable_dir, 'Cannot create directory at {}', \n lambda y: os.makedirs(y, exist_ok=True))\n\n\ndef valid_readable_dir(path):\n \"\"\"\n :param path: Parameter to check if it represents a valid directory path\n :return: String representing a valid directory path\n \"\"\"\n return validate(path, os.path.isdir, valid_readable_file,\n 'Cannot read directory at {}')\n\n\ndef valid_readable_file(path):\n \"\"\"\n Throw exception unless parameter is a valid readable filepath string. Use\n this, not argparse.FileType('r') which leaves an open file handle.\n :param path: Parameter to check if it represents a valid filepath\n :return: String representing a valid filepath\n \"\"\"\n return validate(path, lambda x: os.access(x, os.R_OK),\n os.path.abspath, 'Cannot read file at {}')\n\n\ndef valid_readable_json(path):\n \"\"\"\n :param path: Parameter to check if it represents a valid .json file path\n :return: String representing a valid .json file path\n \"\"\"\n return validate(path, lambda x: os.path.splitext(path)[-1] == '.json',\n valid_readable_file, '{} is not a readable .json filepath')\n\n\ndef valid_subj_ses(in_arg, prefix, name): #, *keywords):\n \"\"\"\n :param in_arg: Object to check if it is a valid subject ID or session name\n :param prefix: String, 'sub-' or 'ses-'\n :param name: String describing what in_arg should be (e.g. 'subject')\n :return: True if in_arg is a valid subject ID or session name; else False\n \"\"\"\n return validate(in_arg, lambda _: True, # lambda x: any([key in x for key in [prefix, *keywords]]),\n lambda y: (y if y[:len(prefix)] == prefix else prefix + y),\n '{}' + ' is not a valid {}'.format(name))\n\n\ndef valid_template_filename(fname):\n \"\"\"\n :param fname: Parameter to check if it represents a .fsf file name\n :return: String representing the .fsf file name\n \"\"\"\n return validate(fname, lambda x: os.path.splitext(x)[-1] == '.fsf',\n lambda y: y, '{} is not an .fsf file name')\n\n\ndef valid_time_str(in_arg):\n \"\"\"\n :param in_arg: Object to check if it's a time string in the HH:MM:SS format\n :return: True if in_arg is a time limit string in that format; else False\n \"\"\"\n try:\n split = in_arg.split(\":\")\n assert len(split) == 3\n for each_num in split:\n assert each_num.isdigit()\n assert int(each_num) >= 0\n return in_arg\n except (TypeError, AssertionError, ValueError):\n raise argparse.ArgumentTypeError('Invalid time string.')\n\n\ndef valid_whole_number(to_validate):\n \"\"\"\n Throw argparse exception unless to_validate is a positive integer\n :param to_validate: Object to test whether it is a positive integer\n :return: to_validate if it is a positive integer\n \"\"\"\n return validate(to_validate, lambda x: int(x) >= 0, int, \n '{} is not a positive integer')\n\n\ndef validate(to_validate, is_real, make_valid, err_msg, prepare=None):\n \"\"\"\n Parent/base function used by different type validation functions. Raises an\n argparse.ArgumentTypeError if the input object is somehow invalid.\n :param to_validate: String to check if it represents a valid object \n :param is_real: Function which returns true iff to_validate is real\n :param make_valid: Function which returns a fully validated object\n :param err_msg: String to show to user to tell them what is invalid\n :param prepare: Function to run before validation\n :return: to_validate, but fully validated\n \"\"\"\n try:\n if prepare:\n prepare(to_validate)\n assert is_real(to_validate)\n return make_valid(to_validate)\n except (OSError, TypeError, AssertionError, ValueError, \n argparse.ArgumentTypeError):\n raise argparse.ArgumentTypeError(err_msg.format(to_validate))\n\n\ndef validate_cli_args(cli_args, parser, arg_names=set()):\n \"\"\"\n Validate types and set defaults for any arg whose validation depends on\n another arg and therefore was not possible in get_pipeline_cli_argparser\n :param cli_args: Dictionary containing all command-line arguments from user\n :param parser: argparse.ArgumentParser to raise error if anything's invalid\n :param arg_names: Set containing SCAN_ARG if that argument is needed\n :return: cli_args, but fully validated\n \"\"\"\n # Default levels, template file directory, and scanner info file path\n cli_args = ensure_dict_has(cli_args, 'levels', [1, 2]\n if len(cli_args['runs']) > 1 else [1])\n cli_args = ensure_dict_has(cli_args, 'templates',\n os.path.join(SCRIPT_DIR, 'templates'))\n if SCAN_ARG in arg_names:\n cli_args = ensure_dict_has(cli_args, SCAN_ARG, os.path.join(\n SCRIPT_DIR, 'scan_info', SCAN_ARG + '.csv'\n ))\n\n for lvl in cli_args['levels']: # Default template file names\n cli_args = ensure_dict_has(cli_args, 'template{}'.format(lvl), (\n 'template_DCAN_version_{}_level{}_UPDATED_FINAL.fsf'\n .format(cli_args['task'], lvl)\n )) \n validate_template_file(cli_args, lvl, parser)\n \n # Default paths to FSL and wb_command\n ERR_MSG = 'No {} found. Please include the {} argument.'\n if not (dict_has(cli_args, 'wb_command') and\n os.access(cli_args['wb_command'], os.X_OK)):\n parser.error(ERR_MSG.format('wb_command executable', '--wb-command'))\n if not dict_has(cli_args, 'fsl_dir'):\n fsl = get_default_ext_command('fsl')\n cli_args['fsl_dir'] = os.path.dirname(fsl) if fsl else parser.error(\n ERR_MSG.format('FSL directory', '--fsl-dir')\n )\n\n # Default output/temp/event files directories. Avoiding ensure_dict_has to\n if not dict_has(cli_args, 'output'): # prevent permissions error from\n cli_args['output'] = valid_output_dir( # valid_output_dir making dirs.\n os.path.join(cli_args['study_dir'], 'derivatives', 'abcd-bids-tfm'\n 'ri-pipeline', cli_args['subject'], cli_args['ses'])\n )\n for arg in ('temp_dir', 'events_dir'):\n if not dict_has(cli_args, arg):\n cli_args[arg] = valid_output_dir(\n os.path.join(cli_args['output'], 'level-1', arg.split('_')[0])\n )\n return cli_args\n\n\ndef validate_template_file(cli_args, lvl, parser):\n \"\"\"\n Verify that template .fsf file exists\n :param cli_args: Dictionary containing all command-line arguments from user\n :param lvl: String or int defining the analysis level, 1 or 2 or \"1\" or \"2\"\n :param parser: argparse.ArgumentParser to raise error if anything's invalid \n \"\"\"\n tmpl = 'template{}'.format(lvl)\n tmpl_fpath = os.path.join(cli_args['templates'], cli_args[tmpl])\n if not os.path.exists(tmpl_fpath):\n parser.error('{} does not exist. Please re-run with a different --{} '\n 'or --templates argument.'.format(tmpl_fpath, tmpl))\n\n\ndef wb_command(cli_args, *args):\n \"\"\"\n Call wb_command executable with any given parameters\n :param cli_args: Dictionary mapping 'wb_command' key to wb_command filepath\n :param args: List of all parameters to call wb_command with, in order\n \"\"\"\n subprocess.check_call([cli_args['wb_command'], *args])\n\n\ndef wb_command_get_info(wb_command, dtseries, arg_only):\n \"\"\"\n Call wb_command with -file-information and -no-map-info parameters\n :param wb_command: String, path to existing workbench wb_command executable\n :param dtseries: String, the path to a .dtseries.nii file with file info\n :param arg_only: String, the last part of the name of a wb_command\n argument starting with '-only-'\n :return: String representing a numerical value describing the dtseries\n \"\"\"\n return os.popen('{} -file-information {} -no-map-info -only-{}'\n .format(wb_command, dtseries, arg_only)).read().rstrip()\n\n\ndef wb_LR_pair(func_LR, arg_LR=None, after=True):\n \"\"\"\n Get wb_command left- and right- arguments\n :param func_LR: Function which accepts 'L' or 'R' and returns a filepath\n :param arg_LR: String naming the left- or right- argument\n :param after: True if arg_LR goes after the word 'left'/'right'; else False\n :return: List with 4 elements, arg name and then value for left then right\n \"\"\"\n arg_LR = '-' + arg_LR if arg_LR else ''\n arg_fmt = '-{}' + arg_LR if after else arg_LR + '-{}'\n return [arg_fmt.format('left'), func_LR('L'),\n arg_fmt.format('right'), func_LR('R')]\n" ]
[ [ "pandas.read_csv", "pandas.get_dummies" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
pranaynanda/training-data-analyst
[ "f10ab778589129239fd5b277cfdefb41638eded5", "f10ab778589129239fd5b277cfdefb41638eded5", "f10ab778589129239fd5b277cfdefb41638eded5", "f10ab778589129239fd5b277cfdefb41638eded5", "f10ab778589129239fd5b277cfdefb41638eded5", "f10ab778589129239fd5b277cfdefb41638eded5" ]
[ "courses/machine_learning/deepdive/09_sequence_keras/temperatures/utils/utils_display.py", "courses/machine_learning/deepdive/05_review/babyweight/trainer/model.py", "blogs/lightning/ltgpred/trainer/train_cnn.py", "blogs/goes16/maria/hurricanes/goes_to_jpeg.py", "blogs/lightning/ltgpred/trainer/dnn.py", "courses/machine_learning/asl/open_project/ASL_youtube8m_models/video_using_datasets/trainer/model.py" ]
[ "# Copyright 2018 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 math\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom matplotlib import transforms as plttrans\nimport utils_prettystyle\n\n\ndef picture_this_1(data, datalen):\n plt.subplot(211)\n plt.plot(data[datalen - 512:datalen + 512])\n plt.axvspan(0, 512, color='black', alpha=0.06)\n plt.axvspan(512, 1024, color='grey', alpha=0.04)\n plt.subplot(212)\n plt.plot(data[3 * datalen - 512:3 * datalen + 512])\n plt.axvspan(0, 512, color='grey', alpha=0.04)\n plt.axvspan(512, 1024, color='black', alpha=0.06)\n plt.show()\n\n\ndef picture_this_2(data, batchsize, seqlen):\n samples = np.reshape(data, [-1, batchsize, seqlen])\n rndsample = samples[np.random.choice(samples.shape[0], 8, replace=False)]\n print(\"Tensor shape of a batch of training sequences: \" +\n str(rndsample[0].shape))\n print(\"Random excerpt:\")\n subplot = 241\n for i in range(8):\n plt.subplot(subplot)\n plt.plot(rndsample[i, 0]) # first sequence in random batch\n subplot += 1\n plt.show()\n\n\ndef picture_this_3(Yout_, evaldata, evallabels, seqlen):\n subplot = 241\n colors = plt.rcParams['axes.prop_cycle'].by_key()['color']\n for i in range(8):\n plt.subplot(subplot)\n k = int(np.random.rand() * evaldata.shape[0])\n l0, = plt.plot(evaldata[k, 1:], label=\"data\")\n plt.plot([seqlen - 2, seqlen - 1], evallabels[k, -2:])\n l1, = plt.plot([seqlen - 1], [Yout_[k]],\n \"o\",\n color=\"red\",\n label='Predicted')\n l2, = plt.plot([seqlen - 1], [evallabels[k][-1]],\n \"o\",\n color=colors[1],\n label='Ground Truth')\n if i == 0:\n plt.legend(handles=[l0, l1, l2])\n subplot += 1\n plt.show()\n\n\ndef picture_this_4(temperatures, dates):\n min_temps = temperatures[:, 0]\n max_temps = temperatures[:, 1]\n interpolated = temperatures[:, 2]\n\n interpolated_sequence = False\n #plt.plot(dates, max_temps)\n for i, date in enumerate(dates):\n if interpolated[i]:\n if not interpolated_sequence:\n startdate = date\n interpolated_sequence = True\n stopdate = date\n else:\n if interpolated_sequence:\n # light shade of red just for visibility\n plt.axvspan(startdate + np.timedelta64(-5, 'D'),\n stopdate + np.timedelta64(6, 'D'),\n facecolor='#FFCCCC',\n alpha=1)\n # actual interpolated region\n plt.axvspan(startdate + np.timedelta64(-1, 'D'),\n stopdate + np.timedelta64(1, 'D'),\n facecolor='#FF8888',\n alpha=1)\n interpolated_sequence = False\n plt.fill_between(dates, min_temps, max_temps).set_zorder(10)\n plt.show()\n\n\ndef picture_this_5(visu_data, station):\n subplot = 231\n for samples, targets, dates, _, _ in visu_data:\n plt.subplot(subplot)\n h1 = plt.fill_between(dates,\n samples[station, :, 0],\n samples[station, :, 1],\n label=\"features\")\n h2 = plt.fill_between(dates,\n targets[station, :, 0],\n targets[station, :, 1],\n label=\"labels\")\n h2.set_zorder(-1)\n if subplot == 231:\n plt.legend(handles=[h1, h2])\n subplot += 1\n if subplot == 237:\n break\n plt.show()\n\n\ndef picture_this_6(evaldata, evaldates, prime_data, results, primelen, runlen,\n offset, rmselen):\n disp_data = evaldata[offset:offset + primelen + runlen]\n disp_dates = evaldates[offset:offset + primelen + runlen]\n colors = plt.rcParams['axes.prop_cycle'].by_key()['color']\n displayresults = np.ma.array(\n np.concatenate((np.zeros([primelen, 2]), results)))\n displayresults = np.ma.masked_where(displayresults == 0, displayresults)\n sp = plt.subplot(212)\n p = plt.fill_between(disp_dates, displayresults[:, 0],\n displayresults[:, 1])\n p.set_alpha(0.8)\n p.set_zorder(10)\n trans = plttrans.blended_transform_factory(sp.transData, sp.transAxes)\n plt.text(disp_dates[primelen],\n 0.05,\n \"DATA |\",\n color=colors[1],\n horizontalalignment=\"right\",\n transform=trans)\n plt.text(disp_dates[primelen],\n 0.05,\n \"| +PREDICTED\",\n color=colors[0],\n horizontalalignment=\"left\",\n transform=trans)\n plt.fill_between(disp_dates, disp_data[:, 0], disp_data[:, 1])\n plt.axvspan(disp_dates[primelen],\n disp_dates[primelen + rmselen],\n color='grey',\n alpha=0.1,\n ymin=0.05,\n ymax=0.95)\n plt.show()\n\n rmse = math.sqrt(\n np.mean((evaldata[offset + primelen:offset + primelen + rmselen] -\n results[:rmselen])**2))\n print(\"RMSE on {} predictions (shaded area): {}\".format(rmselen, rmse))\n\n\ndef picture_this_7(features):\n subplot = 231\n for i in range(6):\n plt.subplot(subplot)\n plt.plot(features[i])\n subplot += 1\n plt.show()\n\n\ndef picture_this_8(data, prime_data, results, offset, primelen, runlen,\n rmselen):\n disp_data = data[offset:offset + primelen + runlen]\n colors = plt.rcParams['axes.prop_cycle'].by_key()['color']\n plt.subplot(211)\n plt.text(primelen,\n 2.5,\n \"DATA |\",\n color=colors[1],\n horizontalalignment=\"right\")\n plt.text(primelen,\n 2.5,\n \"| PREDICTED\",\n color=colors[0],\n horizontalalignment=\"left\")\n displayresults = np.ma.array(\n np.concatenate((np.zeros([primelen]), results)))\n displayresults = np.ma.masked_where(displayresults == 0, displayresults)\n plt.plot(displayresults)\n displaydata = np.ma.array(np.concatenate((prime_data, np.zeros([runlen]))))\n displaydata = np.ma.masked_where(displaydata == 0, displaydata)\n plt.plot(displaydata)\n plt.subplot(212)\n plt.text(primelen,\n 2.5,\n \"DATA |\",\n color=colors[1],\n horizontalalignment=\"right\")\n plt.text(primelen,\n 2.5,\n \"| +PREDICTED\",\n color=colors[0],\n horizontalalignment=\"left\")\n plt.plot(displayresults)\n plt.plot(disp_data)\n plt.axvspan(primelen,\n primelen + rmselen,\n color='grey',\n alpha=0.1,\n ymin=0.05,\n ymax=0.95)\n plt.show()\n\n rmse = math.sqrt(\n np.mean((data[offset + primelen:offset + primelen + rmselen] -\n results[:rmselen])**2))\n print(\"RMSE on {} predictions (shaded area): {}\".format(rmselen, rmse))\n", "import shutil\nimport numpy as np\nimport tensorflow as tf\n\ntf.logging.set_verbosity(tf.logging.INFO)\n\nBUCKET = None # set from task.py\nPATTERN = \"of\" # gets all files\n\n# Determine CSV and label columns\nCSV_COLUMNS = \"weight_pounds,is_male,mother_age,plurality,gestation_weeks\".split(\n ',')\nLABEL_COLUMN = \"weight_pounds\"\n\n# Set default values for each CSV column\nDEFAULTS = [[0.0], [\"null\"], [0.0], [\"null\"], [0.0]]\n\n# Define some hyperparameters\nTRAIN_STEPS = 10000\nEVAL_STEPS = None\nBATCH_SIZE = 512\nNEMBEDS = 3\nNNSIZE = [64, 16, 4]\n\n\n# Create an input function reading a file using the Dataset API\n# Then provide the results to the Estimator API\ndef read_dataset(filename_pattern, mode, batch_size):\n def _input_fn():\n def decode_csv(value_column):\n columns = tf.decode_csv(records=value_column,\n record_defaults=DEFAULTS)\n features = dict(zip(CSV_COLUMNS, columns))\n label = features.pop(LABEL_COLUMN)\n return features, label\n\n # Use filename_pattern to create file path\n file_path = \"gs://{}/babyweight/preproc/{}*{}*\".format(\n BUCKET, filename_pattern, PATTERN)\n\n # Create list of files that match pattern\n file_list = tf.gfile.Glob(filename=file_path)\n\n # Create dataset from file list\n dataset = (\n tf.data.TextLineDataset(filenames=file_list) # Read text file\n .map(map_func=decode_csv)\n ) # Transform each elem by applying decode_csv fn\n\n # In training mode, shuffle the dataset and repeat indefinitely\n if mode == tf.estimator.ModeKeys.TRAIN:\n num_epochs = None # indefinitely\n dataset = dataset.shuffle(buffer_size=10 * batch_size)\n else:\n num_epochs = 1 # end-of-input after this\n\n # This will now return batches of features, label\n dataset = dataset.repeat(count=num_epochs).batch(batch_size=batch_size)\n\n return dataset\n\n return _input_fn\n\n\n# Define feature columns\ndef get_wide_deep():\n # Define column types\n fc_is_male,fc_plurality,fc_mother_age,fc_gestation_weeks = [\\\n tf.feature_column.categorical_column_with_vocabulary_list(key = \"is_male\",\n vocabulary_list = [\"True\", \"False\", \"Unknown\"]),\n tf.feature_column.categorical_column_with_vocabulary_list(key = \"plurality\",\n vocabulary_list = [\"Single(1)\", \"Twins(2)\", \"Triplets(3)\", \"Quadruplets(4)\", \"Quintuplets(5)\", \"Multiple(2+)\"]),\n tf.feature_column.numeric_column(key = \"mother_age\"),\n tf.feature_column.numeric_column(key = \"gestation_weeks\")\n ]\n\n # Bucketized columns\n fc_age_buckets = tf.feature_column.bucketized_column(\n source_column=fc_mother_age,\n boundaries=np.arange(start=15, stop=45, step=1).tolist())\n fc_gestation_buckets = tf.feature_column.bucketized_column(\n source_column=fc_gestation_weeks,\n boundaries=np.arange(start=17, stop=47, step=1).tolist())\n\n # Sparse columns are wide, have a linear relationship with the output\n wide = [fc_is_male, fc_plurality, fc_age_buckets, fc_gestation_buckets]\n\n # Feature cross all the wide columns and embed into a lower dimension\n crossed = tf.feature_column.crossed_column(keys=wide,\n hash_bucket_size=20000)\n fc_embed = tf.feature_column.embedding_column(categorical_column=crossed,\n dimension=3)\n\n # Continuous columns are deep, have a complex relationship with the output\n deep = [fc_mother_age, fc_gestation_weeks, fc_embed]\n\n return wide, deep\n\n\n# Create serving input function to be able to serve predictions later using provided inputs\ndef serving_input_fn():\n feature_placeholders = {\n \"is_male\": tf.placeholder(dtype=tf.string, shape=[None]),\n \"mother_age\": tf.placeholder(dtype=tf.float32, shape=[None]),\n \"plurality\": tf.placeholder(dtype=tf.string, shape=[None]),\n \"gestation_weeks\": tf.placeholder(dtype=tf.float32, shape=[None])\n }\n\n features = {\n key: tf.expand_dims(input=tensor, axis=-1)\n for key, tensor in feature_placeholders.items()\n }\n\n return tf.estimator.export.ServingInputReceiver(\n features=features, receiver_tensors=feature_placeholders)\n\n\n# create metric for hyperparameter tuning\ndef my_rmse(labels, predictions):\n pred_values = predictions[\"predictions\"]\n return {\n \"rmse\":\n tf.metrics.root_mean_squared_error(labels=labels,\n predictions=pred_values)\n }\n\n\n# Create estimator to train and evaluate\ndef train_and_evaluate(output_dir):\n wide, deep = get_wide_deep()\n EVAL_INTERVAL = 300 # seconds\n\n run_config = tf.estimator.RunConfig(save_checkpoints_secs=EVAL_INTERVAL,\n keep_checkpoint_max=3)\n\n estimator = tf.estimator.DNNLinearCombinedRegressor(\n model_dir=output_dir,\n linear_feature_columns=wide,\n dnn_feature_columns=deep,\n dnn_hidden_units=NNSIZE,\n config=run_config)\n\n # Illustrates how to add an extra metric\n estimator = tf.contrib.estimator.add_metrics(estimator, my_rmse)\n # For batch prediction, you need a key associated with each instance\n estimator = tf.contrib.estimator.forward_features(estimator, KEY_COLUMN)\n\n train_spec = tf.estimator.TrainSpec(input_fn=read_dataset(\n \"train\", tf.estimator.ModeKeys.TRAIN, BATCH_SIZE),\n max_steps=TRAIN_STEPS)\n\n exporter = tf.estimator.LatestExporter(\n name=\"exporter\",\n serving_input_receiver_fn=serving_input_fn,\n exports_to_keep=None)\n\n eval_spec = tf.estimator.EvalSpec(\n input_fn=read_dataset(\"eval\", tf.estimator.ModeKeys.EVAL,\n 2**15), # no need to batch in eval\n steps=EVAL_STEPS,\n start_delay_secs=60, # start evaluating after N seconds\n throttle_secs=EVAL_INTERVAL, # evaluate every N seconds\n exporters=exporter)\n\n tf.estimator.train_and_evaluate(estimator=estimator,\n train_spec=train_spec,\n eval_spec=eval_spec)\n", "#!/usr/bin/env python\n\"\"\"Train model to predict lightning using a simple convnet.\n\nCopyright Google Inc.\n2018 Licensed under the Apache License, Version 2.0 (the \"License\"); you may\nnot use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required\nby applicable law or agreed to in writing, software distributed under the\nLicense is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS\nOF ANY KIND, either express or implied. See the License for the specific\nlanguage governing permissions and limitations under the License.\n\"\"\"\nfrom __future__ import division\nfrom __future__ import print_function\nimport argparse\nimport functools\nimport hypertune\nimport logging\nimport os\nimport time\nimport tensorflow as tf\nfrom tensorflow import keras\n\nfrom . import convnet, resnet, dnn\n\n\ndef PATCH_SIZE(params):\n return (2 * params['train_patch_radius']) + 1\n\n\ndef reshape_into_image(features, params):\n \"\"\"reshape features dict containing ref, ltg channels into image.\n\n Args:\n features (dict): Looks for ref, ltg entries in dict\n params (dict): command-line parameters\n\n Returns:\n reshaped tensor with shape [2*train_patch_radius, 2*train_patch_radius, 2]\n \"\"\"\n # stack the inputs to form a 2-channel input\n # features['ref'] is [-1, height*width]\n # stacked image is [-1, height*width, n_channels]\n n_channels = 2\n print('shape of ref feature {}'.format(features['ref'].shape))\n stacked = tf.concat([features['ref'], features['ltg']], axis=1)\n height = width = PATCH_SIZE(params)\n print('shape of all features {}, will be reshaped to [{},{},{}]'.format(\n stacked.shape, height, width, n_channels))\n return tf.reshape(stacked, [height, width, n_channels])\n\n\ndef make_preprocess_fn(params):\n \"\"\"Make preprocessing function.\n\n Args:\n params (dict): command-line parameters\n\n Returns:\n function that takes tfexample and returns img, label\n \"\"\"\n\n def _sparse_to_dense(data, arrlen):\n return tf.expand_dims(\n tf.reshape(tf.sparse_tensor_to_dense(data, default_value=0),\n [arrlen]), -1)\n\n def read_and_preprocess(example_data):\n \"\"\"parses tfrecord and returns image, label.\n\n Args:\n example_data (str): tfrecord\n Returns:\n img, label\n \"\"\"\n height = width = PATCH_SIZE(params)\n parsed = tf.parse_single_example(\n example_data, {\n 'ref': tf.VarLenFeature(tf.float32),\n 'ltg': tf.VarLenFeature(tf.float32),\n 'has_ltg': tf.FixedLenFeature([], tf.int64, 1),\n })\n parsed['ref'] = _sparse_to_dense(parsed['ref'], height * width)\n parsed['ltg'] = _sparse_to_dense(parsed['ltg'], height * width)\n\n # keras wants labels to be float32\n label = tf.cast(tf.reshape(parsed['has_ltg'], shape=[]),\n dtype=tf.float32)\n print('shape of label {}'.format(label.shape))\n\n img = reshape_into_image(parsed, params)\n return img, label\n\n return read_and_preprocess\n\n\ndef engineered_features(img, halfsize):\n with tf.control_dependencies([tf.Assert(tf.is_numeric_tensor(img),\n [img])]):\n qtrsize = halfsize // 2\n ref_smbox = img[:, qtrsize:(qtrsize + halfsize +\n 1), qtrsize:(qtrsize + halfsize + 1), 0:1]\n ltg_smbox = img[:, qtrsize:(qtrsize + halfsize +\n 1), qtrsize:(qtrsize + halfsize + 1), 1:2]\n ref_bigbox = img[:, :, :, 0:1]\n ltg_bigbox = img[:, :, :, 1:2]\n engfeat = tf.concat(\n [\n tf.reduce_max(ref_bigbox, [1, 2]), # [?, 64, 64, 1] -> [?, 1]\n tf.reduce_max(ref_smbox, [1, 2]),\n tf.reduce_mean(ref_bigbox, [1, 2]),\n tf.reduce_mean(ref_smbox, [1, 2]),\n tf.reduce_mean(ltg_bigbox, [1, 2]),\n tf.reduce_mean(ltg_smbox, [1, 2])\n ],\n axis=1)\n return engfeat\n\n\ndef bias_value(img, halfsize):\n center_ref = img[:, halfsize, halfsize, 0:1] # [?]\n return tf.ones_like(center_ref)\n\n\ndef create_combined_model(params):\n # input is a 2-channel image\n height = width = PATCH_SIZE(params)\n img = keras.Input(shape=[height, width, 2])\n\n # feature engineering part of model\n engfeat = keras.layers.Lambda(lambda x: engineered_features(\n x, height // 2))(img)\n\n # deep learning part of model\n deep = {\n 'feateng':\n keras.layers.Lambda(lambda x: bias_value(x, height // 2))(img),\n 'convnet': convnet.create_cnn_model(img, params),\n 'resnet': resnet.create_resnet_model(img, params),\n 'dnn': dnn.create_dnn_model(img, params)\n }.get(params['arch'], None)\n\n # concatenate the two parts\n both = keras.layers.concatenate([deep, engfeat])\n\n ltgprob = keras.layers.Dense(1, activation='sigmoid')(both)\n\n # compile model\n model = keras.Model(img, ltgprob)\n\n def rmse(y_true, y_pred):\n import tensorflow.keras.backend as K\n return K.sqrt(K.mean(K.square(y_pred - y_true), axis=-1))\n\n optimizer = tf.keras.optimizers.Adam(lr=params['learning_rate'],\n clipnorm=1.)\n model.compile(optimizer=optimizer,\n loss='binary_crossentropy',\n metrics=['accuracy', 'mse', rmse])\n return model\n\n\ndef print_layer(layer, message, first_n=3, summarize=1024):\n return keras.layers.Lambda((lambda x: tf.Print(\n x, [x], message=message, first_n=first_n, summarize=summarize)))(layer)\n\n\ndef make_dataset(pattern, mode, batch_size, params):\n \"\"\"Make training/evaluation dataset.\n\n Args:\n pattern (str): filename pattern\n mode (int): TRAIN/EVAL/PREDICT\n default_batch_size (int): batch_size\n params (dict): transpose, num_cores\n\n Returns:\n tf.data dataset\n \"\"\"\n\n def _set_shapes(batch_size, images, labels):\n \"\"\"Statically set the batch_size dimension.\"\"\"\n if params['transpose']:\n images.set_shape(images.get_shape().merge_with(\n tf.TensorShape([None, None, None, batch_size])))\n labels.set_shape(labels.get_shape().merge_with(\n tf.TensorShape([batch_size])))\n else:\n images.set_shape(images.get_shape().merge_with(\n tf.TensorShape([batch_size, None, None, None])))\n labels.set_shape(labels.get_shape().merge_with(\n tf.TensorShape([batch_size])))\n\n # keras wants labels to be same shape as logits\n labels = tf.expand_dims(labels, -1)\n return images, labels\n\n is_training = (mode == tf.estimator.ModeKeys.TRAIN)\n\n # read the dataset\n dataset = tf.data.Dataset.list_files(pattern, shuffle=is_training)\n\n def fetch_dataset(filename):\n buffer_size = 8 * 1024 * 1024 # 8 MiB per file\n dataset = tf.data.TFRecordDataset(filename, buffer_size=buffer_size)\n return dataset\n\n dataset = dataset.apply(\n tf.contrib.data.parallel_interleave(fetch_dataset,\n cycle_length=64,\n sloppy=True))\n dataset = dataset.shuffle(batch_size * 50) # shuffle by a bit\n\n # convert features into images\n preprocess_fn = make_preprocess_fn(params)\n dataset = dataset.apply(\n tf.contrib.data.map_and_batch(preprocess_fn,\n batch_size=batch_size,\n num_parallel_batches=params['num_cores'],\n drop_remainder=True))\n\n if params['transpose']:\n dataset = dataset.map(lambda images, labels: (tf.transpose(\n images, [1, 2, 3, 0]), labels),\n num_parallel_calls=params['num_cores'])\n\n # assign static shape\n dataset = dataset.map(functools.partial(_set_shapes, batch_size))\n\n # prefetch data while training\n dataset = dataset.repeat()\n dataset = dataset.prefetch(tf.contrib.data.AUTOTUNE)\n return dataset\n\n\ndef train_and_evaluate(hparams):\n \"\"\"Main train and evaluate loop.\n\n Args:\n hparams (dict): Command-line parameters passed in\n \"\"\"\n output_dir = hparams['job_dir']\n max_steps = hparams['train_steps']\n\n # avoid overly frequent evaluation\n steps_per_epoch = min(1000, max_steps // 10)\n num_epochs = max_steps // steps_per_epoch\n\n # eval batch size has to be divisible by num_cores\n eval_batch_size = min(hparams['num_eval_records'],\n hparams['train_batch_size'])\n eval_batch_size = eval_batch_size - eval_batch_size % hparams['num_cores']\n eval_steps = hparams['num_eval_records'] // eval_batch_size\n tf.logging.info(\n 'train_batch_size=%d eval_batch_size=%d'\n ' train_steps=%d (%d x %d) eval_steps=%d', hparams['train_batch_size'],\n eval_batch_size, max_steps, steps_per_epoch, num_epochs, eval_steps)\n\n # create model\n model = create_combined_model(hparams)\n\n # resolve TPU and rewrite model for TPU if necessary\n if hparams['use_tpu'] and hparams['master']:\n tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(\n hparams['master'])\n trained_model = tf.contrib.tpu.keras_to_tpu_model(\n model,\n strategy=tf.contrib.tpu.TPUDistributionStrategy(\n tpu_cluster_resolver))\n # on a TPU, we need to provide a function that returns a dataset\n # this is so that the TPU can put the input pipeline on attached VM\n train_data = lambda: make_dataset(hparams['train_data_path'], tf.\n estimator.ModeKeys.TRAIN, hparams[\n 'train_batch_size'], hparams)\n eval_data = lambda: make_dataset(hparams[\n 'eval_data_path'], tf.estimator.ModeKeys.EVAL, eval_batch_size,\n hparams)\n else:\n trained_model = model\n train_data = make_dataset(hparams['train_data_path'],\n tf.estimator.ModeKeys.TRAIN,\n hparams['train_batch_size'], hparams)\n eval_data = make_dataset(hparams['eval_data_path'],\n tf.estimator.ModeKeys.EVAL, eval_batch_size,\n hparams)\n\n # train and evaluate\n start_timestamp = time.time()\n history = trained_model.fit(\n train_data,\n steps_per_epoch=steps_per_epoch,\n epochs=num_epochs,\n validation_data=eval_data,\n validation_steps=eval_steps,\n verbose=2 # 1=progress 2=one line per epoch\n )\n elapsed_time = int(time.time() - start_timestamp)\n tf.logging.info('Finished training up to step %d. Elapsed seconds %d.',\n max_steps, elapsed_time)\n #tf.logging.info(model.summary())\n print(\"if running interactively, graph: {}\".format(history.history.keys()))\n\n # write validation accuracy as hyperparameter tuning metric\n hpt = hypertune.HyperTune()\n hpt.report_hyperparameter_tuning_metric(\n hyperparameter_metric_tag='val_acc',\n metric_value=history.history['val_acc'][-1], # last one\n global_step=0)\n\n # Serve the model via CMLE\n export_keras(model, trained_model, output_dir, hparams)\n\n\ndef export_keras(model, trained_model, output_dir, hparams):\n # 1. multiple inputs from JSON\n height = width = PATCH_SIZE(hparams)\n json_input = [\n keras.layers.Input(name='ref',\n dtype=tf.float32,\n shape=(height * width, )),\n keras.layers.Input(name='ltg',\n dtype=tf.float32,\n shape=(height * width, )),\n ]\n\n # 2. reshape as image, which is what the model expects\n reshape_layer = keras.layers.Reshape((height, width, 1))\n img = keras.layers.concatenate(\n [reshape_layer(json_input[0]),\n reshape_layer(json_input[1])])\n\n # 3. now, use trained model to predict\n model_core = model\n model_core.set_weights(trained_model.get_weights())\n model_output = model_core(img)\n\n # 4. create serving model\n serving_model = keras.Model(json_input, model_output)\n\n # export\n if not hparams['skipexport']:\n export_path = tf.contrib.saved_model.save_keras_model(\n serving_model, os.path.join(output_dir, 'export/exporter'))\n export_path = export_path.decode('utf-8')\n tf.logging.info(\n 'Model exported successfully to {}'.format(export_path))\n else:\n print('Skipping export since --skipexport was specified')\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(\n description='Train cnn model for lightning prediction')\n parser.add_argument('--job-dir',\n required=True,\n help='output dir. could be local or on GCS')\n parser.add_argument(\n '--train_data_path',\n required=True,\n help=\n 'Pattern for training data tfrecord files. could be local or on GCS')\n parser.add_argument('--eval_data_path',\n required=True,\n help='Pattern for evaluation data tfrecord files.'\n 'could be local or on GCS')\n parser.add_argument(\n '--train_patch_radius',\n type=int,\n default=32,\n help='predict lightning based a 2Nx2N grid; has to match preprocessing'\n )\n parser.add_argument('--train_batch_size',\n help='Batch size for training steps',\n type=int,\n default=\"256\")\n parser.add_argument('--learning_rate',\n help='Initial learning rate for training',\n type=float,\n default=0.001)\n parser.add_argument('--train_steps',\n help=\"\"\"\\\n Steps to run the training job for. A step is one batch-size,\\\n \"\"\",\n type=int,\n default=100)\n parser.add_argument('--num_eval_records',\n help='Number of validation records, '\n ' has to be less than available number and'\n ' divisible by number of cores.'\n ' You can find available number from Dataflow'\n ' pipeline that created the tfrecords dataset'\n ' See: https://console.cloud.google.com/dataflow',\n type=int,\n default=128)\n\n # for Cloud TPU\n parser.add_argument(\n '--use_tpu',\n help=\n ('If specified, use TPU to execute the model for training and evaluation.'\n ' Else use whatever devices are available to'\n ' TensorFlow by default (e.g. CPU and GPU); expects --master'),\n dest='use_tpu',\n action='store_true')\n parser.add_argument(\n '--transpose',\n help=('If specified, makes the batch-size the last dimension.'\n ' This is more efficient on a TPU'),\n dest='transpose',\n action='store_true')\n parser.add_argument(\n '--skipexport',\n help=('If specified, does not export model for serving'),\n dest='skipexport',\n action='store_true')\n parser.add_argument(\n '--master',\n default=None,\n help='The Cloud TPU to use for training. This will be provided by '\n 'ML Engine is of the form grpc://ip.address.of.tpu:8470 url.')\n parser.add_argument('--num_cores',\n default=8,\n type=int,\n help='Number of TPU cores to use')\n\n # optional hyperparameters used by deep networks\n parser.add_argument('--arch',\n default='feateng',\n help='This trainer supports several architectures: '\n 'feateng (no deep learning); dnn; convnet; resnet')\n parser.add_argument('--ksize',\n help='kernel size of each layer in deep network',\n type=int,\n default=5)\n parser.add_argument('--nfil',\n help='number of filters in each layer in deep network',\n type=int,\n default=10)\n parser.add_argument('--nlayers',\n help='number of layers in deep network (<= 5)',\n type=int,\n default=3)\n parser.add_argument('--dprob',\n help='dropout probability in deep network',\n type=float,\n default=0.25)\n parser.add_argument('--batch_norm',\n help='if specified, do batch_norm for deep network',\n dest='batch_norm',\n action='store_true')\n\n logging.basicConfig(level=getattr(logging, 'INFO', None))\n parser.set_defaults(use_tpu=False, batch_norm=False, skipexport=False)\n options = parser.parse_args().__dict__\n\n # run the training job\n train_and_evaluate(options)\n", "#!/usr/bin/env python\n\"\"\"\nCopyright Google Inc. 2017\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\nhttp://www.apache.org/licenses/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nGOES_PUBLIC_BUCKET = 'gcp-public-data-goes-16'\n\n\ndef list_gcs(bucket, gcs_prefix, gcs_patterns):\n import google.cloud.storage as gcs\n bucket = gcs.Client().get_bucket(bucket)\n blobs = bucket.list_blobs(prefix=gcs_prefix, delimiter='/')\n result = []\n if gcs_patterns == None or len(gcs_patterns) == 0:\n for b in blobs:\n result.append(b)\n else:\n for b in blobs:\n match = True\n for pattern in gcs_patterns:\n if not pattern in b.path:\n match = False\n if match:\n result.append(b)\n return result\n\n\ndef copy_fromgcs(bucket, objectId, destdir):\n import os.path\n import logging\n import google.cloud.storage as gcs\n bucket = gcs.Client().get_bucket(bucket)\n blob = bucket.blob(objectId)\n basename = os.path.basename(objectId)\n logging.info('Downloading {}'.format(basename))\n dest = os.path.join(destdir, basename)\n blob.download_to_filename(dest)\n return dest\n\n\ndef copy_togcs(localfile, bucket_name, blob_name):\n import logging\n import google.cloud.storage as gcs\n bucket = gcs.Client().get_bucket(bucket_name)\n blob = bucket.blob(blob_name)\n blob.upload_from_filename(localfile)\n logging.info('{} uploaded to gs://{}/{}'.format(localfile, bucket_name,\n blob_name))\n return blob\n\n\ndef crop_image(nc, data, clat, clon):\n import logging\n import numpy as np\n from pyproj import Proj\n import pyresample as pr\n\n # output grid centered on clat, clon in equal-lat-lon\n lats = np.arange(clat - 10, clat + 10,\n 0.01) # approx 1km resolution, 2000km extent\n lons = np.arange(clon - 10, clon + 10,\n 0.01) # approx 1km resolution, 2000km extent\n lons, lats = np.meshgrid(lons, lats)\n new_grid = pr.geometry.GridDefinition(lons=lons, lats=lats)\n\n # Subsatellite_Longitude is where the GEO satellite is\n lon_0 = nc.variables['nominal_satellite_subpoint_lon'][0]\n ht_0 = nc.variables['nominal_satellite_height'][0] * 1000 # meters\n x = nc.variables['x'][:] * ht_0 #/ 1000.0\n y = nc.variables['y'][:] * ht_0 #/ 1000.0\n nx = len(x)\n ny = len(y)\n max_x = x.max()\n min_x = x.min()\n max_y = y.max()\n min_y = y.min()\n half_x = (max_x - min_x) / nx / 2.\n half_y = (max_y - min_y) / ny / 2.\n extents = (min_x - half_x, min_y - half_y, max_x + half_x, max_y + half_y)\n old_grid = pr.geometry.AreaDefinition(\n 'geos', 'goes_conus', 'geos', {\n 'proj': 'geos',\n 'h': str(ht_0),\n 'lon_0': str(lon_0),\n 'a': '6378169.0',\n 'b': '6356584.0'\n }, nx, ny, extents)\n\n # now do remapping\n logging.info('Remapping from {}'.format(old_grid))\n return pr.kd_tree.resample_nearest(old_grid,\n data,\n new_grid,\n radius_of_influence=50000)\n\n\ndef plot_image(ncfilename, outfile, clat, clon):\n import matplotlib, logging\n matplotlib.use('Agg') # headless display\n import numpy as np\n from netCDF4 import Dataset\n import matplotlib.pyplot as plt\n\n with Dataset(ncfilename, 'r') as nc:\n rad = nc.variables['Rad'][:]\n # See http://www.goes-r.gov/products/ATBDs/baseline/Imagery_v2.0_no_color.pdf\n ref = (rad * np.pi * 0.3) / 663.274497\n ref = np.minimum(np.maximum(ref, 0.0), 1.0)\n\n # crop to area of interest\n ref = crop_image(nc, ref, clat, clon)\n\n # do gamma correction to stretch the values\n ref = np.sqrt(ref)\n\n # plotting to jpg file\n fig = plt.figure()\n plt.imsave(outfile, ref, vmin=0.0, vmax=1.0,\n cmap='gist_ncar_r') # or 'Greys_r' without color\n plt.close('all')\n logging.info('Created {}'.format(outfile))\n return outfile\n return None\n\n\ndef get_objectId_at(dt, product='ABI-L1b-RadF', channel='C14'):\n import os, logging\n # get first 11-micron band (C14) at this hour\n # See: https://www.goes-r.gov/education/ABI-bands-quick-info.html\n logging.info('Looking for data collected on {}'.format(dt))\n dayno = dt.timetuple().tm_yday\n gcs_prefix = '{}/{}/{:03d}/{:02d}/'.format(product, dt.year, dayno,\n dt.hour)\n gcs_patterns = [channel, 's{}{:03d}{:02d}'.format(dt.year, dayno, dt.hour)]\n blobs = list_gcs(GOES_PUBLIC_BUCKET, gcs_prefix, gcs_patterns)\n if len(blobs) > 0:\n objectId = blobs[0].path.replace('%2F', '/').replace(\n '/b/{}/o/'.format(GOES_PUBLIC_BUCKET), '')\n logging.info('Found {} for {}'.format(objectId, dt))\n return objectId\n else:\n logging.error(\n 'No matching files found for gs://{}/{}* containing {}'.format(\n GOES_PUBLIC_BUCKET, gcs_prefix, gcs_patterns))\n return None\n\n\ndef parse_timestamp(timestamp):\n from datetime import datetime\n dt = datetime.strptime(timestamp[:19], '%Y-%m-%d %H:%M:%S')\n return dt\n\n\ndef parse_line(line):\n fields = line.split(',')\n return parse_timestamp(fields[6]), float(fields[8]), float(fields[9])\n\n\ndef goes_to_jpeg(objectId, lat, lon, outbucket, outfilename):\n import os, shutil, tempfile, subprocess, logging\n import os.path\n\n # if get_objectId_at fails, it returns None\n if objectId == None:\n logging.error(\n 'Skipping GOES object creation since no GCS file specified')\n return\n\n tmpdir = tempfile.mkdtemp()\n local_file = copy_fromgcs('gcp-public-data-goes-16', objectId, tmpdir)\n logging.info('Creating image from {} near {},{}'.format(\n os.path.basename(local_file), lat, lon))\n\n # create image in temporary dir, then move over\n jpgfile = os.path.join(tmpdir, os.path.basename(outfilename))\n jpgfile = plot_image(local_file, jpgfile, lat, lon)\n logging.info('Created {} from {}'.format(os.path.basename(jpgfile),\n os.path.basename(local_file)))\n\n # move over\n if outbucket != None:\n copy_togcs(jpgfile, outbucket, outfilename)\n outfilename = 'gs://{}/{}'.format(outbucket, outfilename)\n else:\n subprocess.check_call(['mv', jpgfile, outfilename])\n\n # cleanup\n shutil.rmtree(tmpdir)\n logging.info('Created {} from {}'.format(outfilename,\n os.path.basename(local_file)))\n\n return outfilename\n\n\ndef only_infrared(message):\n import json, logging\n try:\n # message is a string in json format, so we need to parse it as json\n #logging.debug(message)\n result = json.loads(message)\n # e.g. ABI-L2-CMIPF/2017/306/21/OR_ABI-L2-CMIPF-M4C01_G16_s20173062105222_e20173062110023_c20173062110102.nc\n if 'C14_G16' in result['name']:\n yield result['name'] #filename\n except:\n import sys\n logging.warn(sys.exc_info()[0])\n pass\n", "import tensorflow.keras as keras\n\n\ndef create_dnn_model(img, params):\n nfil = params.get('nfil', 5)\n dprob = params.get('dprob', 0.05 if params['batch_norm'] else 0.25)\n nlayers = params.get('nlayers', 3)\n x = keras.layers.BatchNormalization()(img)\n for layer in range(nlayers):\n numnodes = (nlayers - layer) * nfil # 15, 10, 5 for example\n x = keras.layers.Dense(numnodes, activation='relu')(x)\n x = keras.layers.Flatten()(x)\n x = keras.layers.Dropout(dprob)(x)\n x = keras.layers.Dense(10, activation='relu')(x)\n return x\n", "#!/usr/bin/env python\n\n# Copyright 2017 Google Inc. 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# Import libraries and modules\nimport tensorflow as tf\n\n# Set logging verbosity to INFO for richer output\ntf.logging.set_verbosity(tf.logging.INFO)\n\n# The number of video classes\nNUM_CLASSES = 4716\n\n\n# Create an input function to read our training and validation data\n# Then provide the results to the Estimator API\ndef read_dataset_video(file_pattern, mode, batch_size):\n def _input_fn():\n print(\"\\nread_dataset_video: _input_fn: file_pattern = {}\".format(\n file_pattern))\n print(\"read_dataset_video: _input_fn: mode = {}\".format(mode))\n print(\"read_dataset_video: _input_fn: batch_size = {}\".format(\n batch_size))\n\n # This function will decode frame examples from the frame level TF Records\n def decode_example(serialized_examples):\n # Create feature map\n feature_map = {\n 'video_id': tf.FixedLenFeature(shape=[], dtype=tf.string),\n 'labels': tf.VarLenFeature(dtype=tf.int64),\n 'mean_rgb': tf.FixedLenFeature(shape=[1024], dtype=tf.float32),\n 'mean_audio': tf.FixedLenFeature(shape=[128], dtype=tf.float32)\n }\n\n # Parse TF Records into our features\n features = tf.parse_single_example(serialized=serialized_examples,\n features=feature_map)\n print(\n \"\\nread_dataset_video: _input_fn: decode_example: features = {}\"\n .format(features)\n ) # shape = video_id = (), mean_rgb = (1024,), mean_audio = (128,), labels = SparseTensor object\n\n # Extract and format labels\n sparse_labels = features.pop(\"labels\") # SparseTensor object\n print(\n \"read_dataset_video: _input_fn: decode_example: sparse_labels = {}\\n\"\n .format(sparse_labels))\n labels = tf.cast(x=tf.sparse_to_dense(\n sparse_indices=sparse_labels.values,\n output_shape=(NUM_CLASSES, ),\n sparse_values=1,\n validate_indices=False),\n dtype=tf.float32)\n print(\n \"read_dataset_video: _input_fn: decode_example: labels = {}\\n\".\n format(labels)) # shape = (NUM_CLASSES,)\n\n return features, labels\n\n # Create list of files from file pattern\n file_list = tf.gfile.Glob(filename=file_pattern)\n #print(\"read_dataset_video: _input_fn: file_list = {}\".format(file_list))\n\n # Create dataset from file list\n dataset = tf.data.TFRecordDataset(filenames=file_list)\n print(\"read_dataset_video: _input_fn: dataset.TFRecordDataset = {}\".\n format(dataset))\n\n # Decode TF Record dataset examples\n dataset = dataset.map(\n map_func=lambda x: decode_example(serialized_examples=x))\n print(\n \"read_dataset_video: _input_fn: dataset.map = {}\".format(dataset))\n\n # Determine amount of times to repeat file and if we should shuffle based on if we are training or evaluating\n if mode == tf.estimator.ModeKeys.TRAIN:\n num_epochs = None # read files forever\n\n # Shuffle the dataset within a buffer\n dataset = dataset.shuffle(buffer_size=batch_size * 10, seed=None)\n print(\"read_dataset_video: _input_fn: dataset.shuffle = {}\".format(\n dataset))\n else:\n num_epochs = 1 # read files only once\n\n # Repeat files num_epoch times\n dataset = dataset.repeat(count=num_epochs)\n print(\"read_dataset_video: _input_fn: dataset.repeat = {}\".format(\n dataset))\n\n # Group the data into batches\n dataset = dataset.batch(batch_size=batch_size)\n print(\"read_dataset_video: _input_fn: dataset.batch = {}\".format(\n dataset))\n\n # Create a iterator and then pull the next batch of features and labels from the example queue\n batch_features, batch_labels = dataset.make_one_shot_iterator(\n ).get_next()\n print(\"read_dataset_video: _input_fn: batch_features = {}\".format(\n batch_features))\n print(\"read_dataset_video: _input_fn: batch_labels = {}\\n\".format(\n batch_labels))\n\n return batch_features, batch_labels\n\n return _input_fn\n\n\n# Create our model function to be used in our custom estimator\ndef video_level_model(features, labels, mode, params):\n print(\"\\nvideo_level_model: features = {}\".format(features))\n print(\"video_level_model: labels = {}\".format(labels))\n print(\"video_level_model: mode = {}\".format(mode))\n\n # 0. Configure network\n # Get dynamic batch size\n current_batch_size = tf.shape(features['mean_rgb'])[0]\n print(\"video_level_model: current_batch_size = {}\".format(\n current_batch_size))\n\n # Stack all of the features into a 3-D tensor\n combined_features = tf.concat(\n values=[features['mean_rgb'], features['mean_audio']],\n axis=1) # shape = (current_batch_size, 1024 + 128)\n print(\n \"video_level_model: combined_features = {}\".format(combined_features))\n\n # 1. Create the DNN structure now\n # Create the input layer to our frame DNN\n network = combined_features # shape = (current_batch_size, 1024 + 128)\n print(\n \"video_level_model: network = combined_features = {}\".format(network))\n\n # Add hidden layers with the given number of units/neurons per layer\n for units in params['hidden_units']:\n network = tf.layers.dense(\n inputs=network, units=units,\n activation=tf.nn.relu) # shape = (current_batch_size, units)\n print(\"video_level_model: network = {}, units = {}\".format(\n network, units))\n\n # Connect the final hidden layer to a dense layer with no activation to get the logits\n logits = tf.layers.dense(\n inputs=network, units=NUM_CLASSES,\n activation=None) # shape = (current_batch_size, NUM_CLASSES)\n print(\"video_level_model: logits = {}\".format(logits))\n\n # Select the top k logits in descending order\n top_k_logits = tf.nn.top_k(\n input=logits, k=params['top_k'],\n sorted=True) # shape = (current_batch_size, top_k)\n print(\"video_level_model: top_k_logits = {}\".format(top_k_logits))\n\n # Since this is a multi-class, multi-label problem we will apply a sigmoid, not a softmax, to each logit to get its own probability\n probabilities = tf.sigmoid(\n logits) # shape = (current_batch_size, NUM_CLASSES)\n print(\"video_level_model: probabilities = {}\".format(probabilities))\n\n # Select the top k probabilities in descending order\n top_k_probabilities = tf.sigmoid(\n top_k_logits.values) # shape = (current_batch_size, top_k)\n print(\"video_level_model: top_k_probabilities = {}\".format(\n top_k_probabilities))\n\n # Select the top k classes in descending order of likelihood\n top_k_classes = top_k_logits.indices # shape = (current_batch_size, top_k)\n print(\"video_level_model: top_k_classes = {}\".format(top_k_classes))\n\n # The 0/1 predictions based on a threshold, in this case the threshold is if the probability it greater than random chance\n predictions = tf.where(\n condition=probabilities >\n 1.0 / NUM_CLASSES, # shape = (current_batch_size, NUM_CLASSES)\n x=tf.ones_like(tensor=probabilities),\n y=tf.zeros_like(tensor=probabilities))\n print(\"video_level_model: predictions = {}\".format(predictions))\n\n top_k_predictions = tf.where(\n condition=top_k_probabilities >\n 1.0 / NUM_CLASSES, # shape = (current_batch_size, top_k)\n x=tf.ones_like(tensor=top_k_probabilities),\n y=tf.zeros_like(tensor=top_k_probabilities))\n print(\"video_level_model: top_k_predictions = {}\\n\".format(\n top_k_predictions))\n\n # 2. Loss function, training/eval ops\n if mode == tf.estimator.ModeKeys.TRAIN or mode == tf.estimator.ModeKeys.EVAL:\n # Since this is a multi-class, multi-label problem, we will use sigmoid activation and cross entropy loss\n loss = tf.losses.sigmoid_cross_entropy(multi_class_labels=labels,\n logits=logits)\n\n train_op = tf.contrib.layers.optimize_loss(\n loss=loss,\n global_step=tf.train.get_global_step(),\n learning_rate=0.01,\n optimizer=\"Adam\")\n eval_metric_ops = {\n \"accuracy\":\n tf.metrics.mean_per_class_accuracy(labels=labels,\n predictions=predictions,\n num_classes=NUM_CLASSES)\n }\n else:\n loss = None\n train_op = None\n eval_metric_ops = None\n\n # 3. Create predictions\n predictions_dict = {\n \"logits\": top_k_logits.values,\n \"probabilities\": top_k_probabilities,\n \"predictions\": top_k_predictions,\n \"classes\": top_k_classes\n }\n\n # 4. Create export outputs\n export_outputs = {\n \"predict_export_outputs\":\n tf.estimator.export.PredictOutput(outputs=predictions_dict)\n }\n\n # 5. Return EstimatorSpec\n return tf.estimator.EstimatorSpec(mode=mode,\n predictions=predictions_dict,\n loss=loss,\n train_op=train_op,\n eval_metric_ops=eval_metric_ops,\n export_outputs=export_outputs)\n\n\n# Create our serving input function to accept the data at serving and send it in the right format to our custom estimator\ndef serving_input_fn():\n # This function fixes the shape and type of our input strings\n def fix_shape_and_type_for_serving(placeholder):\n # String split each string in the batch and output the values from the resulting SparseTensors\n split_string = tf.map_fn(\n fn=lambda x: tf.string_split(source=[placeholder[x]],\n delimiter=',').values,\n elems=tf.range(start=0, limit=tf.shape(input=placeholder)[0]),\n dtype=tf.string) # shape = (batch_size, input_sequence_length)\n print(\n \"serving_input_fn: fix_shape_and_type_for_serving: split_string = {}\"\n .format(split_string))\n\n # Convert each string in the split tensor to float\n feature_tensor = tf.string_to_number(\n string_tensor=split_string,\n out_type=tf.float32) # shape = (batch_size, input_sequence_length)\n print(\n \"serving_input_fn: fix_shape_and_type_for_serving: feature_tensor = {}\"\n .format(feature_tensor))\n return feature_tensor\n\n # This function fixes dynamic shape ambiguity of last dimension so that we will be able to use it in our DNN (since tf.layers.dense require the last dimension to be known)\n def get_shape_and_set_modified_shape_2D(tensor,\n additional_dimension_sizes):\n # Get static shape for tensor and convert it to list\n shape = tensor.get_shape().as_list()\n # Set outer shape to additional_dimension_sizes[0] since we know that this is the correct size\n shape[1] = additional_dimension_sizes[0]\n # Set the shape of tensor to our modified shape\n tensor.set_shape(\n shape=shape) # shape = (batch_size, additional_dimension_sizes[0])\n print(\n \"serving_input_fn: get_shape_and_set_modified_shape_2D: tensor = {}, additional_dimension_sizes = {}\"\n .format(tensor, additional_dimension_sizes))\n return tensor\n\n # Create placeholders to accept the data sent to the model at serving time\n feature_placeholders = { # all features come in as a batch of strings, shape = (batch_size,), this was so because of passing the arrays to online ml-engine prediction\n 'video_id': tf.placeholder(dtype=tf.string, shape=[None]),\n 'mean_rgb': tf.placeholder(dtype=tf.string, shape=[None]),\n 'mean_audio': tf.placeholder(dtype=tf.string, shape=[None])\n }\n print(\"\\nserving_input_fn: feature_placeholders = {}\".format(\n feature_placeholders))\n\n # Create feature tensors\n features = {\n \"video_id\":\n feature_placeholders[\"video_id\"],\n \"mean_rgb\":\n fix_shape_and_type_for_serving(\n placeholder=feature_placeholders[\"mean_rgb\"]),\n \"mean_audio\":\n fix_shape_and_type_for_serving(\n placeholder=feature_placeholders[\"mean_audio\"])\n }\n print(\"serving_input_fn: features = {}\".format(features))\n\n # Fix dynamic shape ambiguity of feature tensors for our DNN\n features[\"mean_rgb\"] = get_shape_and_set_modified_shape_2D(\n tensor=features[\"mean_rgb\"], additional_dimension_sizes=[1024])\n features[\"mean_audio\"] = get_shape_and_set_modified_shape_2D(\n tensor=features[\"mean_audio\"], additional_dimension_sizes=[128])\n print(\"serving_input_fn: features = {}\\n\".format(features))\n\n return tf.estimator.export.ServingInputReceiver(\n features=features, receiver_tensors=feature_placeholders)\n\n\n# Create custom estimator's train and evaluate function\ndef train_and_evaluate(args):\n # Create custom estimator's train and evaluate function\n estimator = tf.estimator.Estimator(model_fn=video_level_model,\n model_dir=args['output_dir'],\n params={\n 'hidden_units':\n args['hidden_units'],\n 'top_k': args['top_k']\n })\n # Create train spec to read in our training data\n train_spec = tf.estimator.TrainSpec(input_fn=read_dataset_video(\n file_pattern=args['train_file_pattern'],\n mode=tf.estimator.ModeKeys.TRAIN,\n batch_size=args['batch_size']),\n max_steps=args['train_steps'])\n # Create exporter to save out the complete model to disk\n exporter = tf.estimator.LatestExporter(\n name='exporter', serving_input_receiver_fn=serving_input_fn)\n # Create eval spec to read in our validation data and export our model\n eval_spec = tf.estimator.EvalSpec(\n input_fn=read_dataset_video(file_pattern=args['eval_file_pattern'],\n mode=tf.estimator.ModeKeys.EVAL,\n batch_size=args['batch_size']),\n steps=None,\n exporters=exporter,\n start_delay_secs=args['start_delay_secs'],\n throttle_secs=args['throttle_secs'])\n # Create train and evaluate loop to train and evaluate our estimator\n tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec)\n" ]
[ [ "matplotlib.pyplot.legend", "numpy.random.choice", "numpy.reshape", "numpy.ma.masked_where", "matplotlib.pyplot.plot", "numpy.timedelta64", "matplotlib.pyplot.subplot", "numpy.mean", "matplotlib.pyplot.fill_between", "numpy.random.rand", "numpy.zeros", "matplotlib.pyplot.text", "matplotlib.pyplot.show", "matplotlib.transforms.blended_transform_factory", "matplotlib.pyplot.axvspan" ], [ "tensorflow.feature_column.categorical_column_with_vocabulary_list", "tensorflow.data.TextLineDataset", "tensorflow.estimator.RunConfig", "tensorflow.estimator.train_and_evaluate", "tensorflow.feature_column.embedding_column", "tensorflow.contrib.estimator.forward_features", "tensorflow.decode_csv", "numpy.arange", "tensorflow.logging.set_verbosity", "tensorflow.estimator.export.ServingInputReceiver", "tensorflow.estimator.LatestExporter", "tensorflow.metrics.root_mean_squared_error", "tensorflow.feature_column.crossed_column", "tensorflow.placeholder", "tensorflow.gfile.Glob", "tensorflow.feature_column.numeric_column", "tensorflow.contrib.estimator.add_metrics", "tensorflow.expand_dims", "tensorflow.estimator.DNNLinearCombinedRegressor" ], [ "tensorflow.contrib.cluster_resolver.TPUClusterResolver", "tensorflow.concat", "tensorflow.FixedLenFeature", "tensorflow.contrib.data.parallel_interleave", "tensorflow.data.Dataset.list_files", "tensorflow.keras.Input", "tensorflow.data.TFRecordDataset", "tensorflow.contrib.tpu.TPUDistributionStrategy", "tensorflow.keras.backend.square", "tensorflow.TensorShape", "tensorflow.Print", "tensorflow.keras.layers.Dense", "tensorflow.sparse_tensor_to_dense", "tensorflow.keras.Model", "tensorflow.logging.info", "tensorflow.VarLenFeature", "tensorflow.keras.layers.Reshape", "tensorflow.reduce_max", "tensorflow.transpose", "tensorflow.reduce_mean", "tensorflow.is_numeric_tensor", "tensorflow.reshape", "tensorflow.ones_like", "tensorflow.keras.layers.concatenate", "tensorflow.expand_dims", "tensorflow.contrib.data.map_and_batch", "tensorflow.keras.optimizers.Adam", "tensorflow.keras.layers.Input" ], [ "matplotlib.pyplot.imsave", "numpy.maximum", "numpy.sqrt", "numpy.arange", "matplotlib.use", "matplotlib.pyplot.close", "numpy.meshgrid", "matplotlib.pyplot.figure" ], [ "tensorflow.keras.layers.Dense", "tensorflow.keras.layers.Dropout", "tensorflow.keras.layers.BatchNormalization", "tensorflow.keras.layers.Flatten" ], [ "tensorflow.concat", "tensorflow.FixedLenFeature", "tensorflow.string_split", "tensorflow.string_to_number", "tensorflow.estimator.train_and_evaluate", "tensorflow.metrics.mean_per_class_accuracy", "tensorflow.sparse_to_dense", "tensorflow.estimator.export.PredictOutput", "tensorflow.data.TFRecordDataset", "tensorflow.layers.dense", "tensorflow.train.get_global_step", "tensorflow.nn.top_k", "tensorflow.logging.set_verbosity", "tensorflow.estimator.export.ServingInputReceiver", "tensorflow.parse_single_example", "tensorflow.estimator.LatestExporter", "tensorflow.estimator.Estimator", "tensorflow.shape", "tensorflow.placeholder", "tensorflow.zeros_like", "tensorflow.gfile.Glob", "tensorflow.VarLenFeature", "tensorflow.losses.sigmoid_cross_entropy", "tensorflow.sigmoid", "tensorflow.ones_like", "tensorflow.estimator.EstimatorSpec" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "2.6", "2.4", "2.3", "2.5", "2.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
josepablocam/common-code-extraction
[ "a6978fae73eee8ece6f1db09f2f38cf92f03b3ad", "a6978fae73eee8ece6f1db09f2f38cf92f03b3ad", "a6978fae73eee8ece6f1db09f2f38cf92f03b3ad", "a6978fae73eee8ece6f1db09f2f38cf92f03b3ad", "a6978fae73eee8ece6f1db09f2f38cf92f03b3ad", "a6978fae73eee8ece6f1db09f2f38cf92f03b3ad" ]
[ "downloaded_kernels/loan_data/parsed_kernels/kernel_107.py", "downloaded_kernels/house_sales/converted_notebooks/kernel_260.py", "downloaded_kernels/house_sales/converted_notebooks/kernel_117.py", "downloaded_kernels/university_rankings/parsed_kernels/kernel_31.py", "downloaded_kernels/house_sales/converted_notebooks/kernel_46.py", "downloaded_kernels/university_rankings/parsed_kernels/kernel_118.py" ]
[ "\n# coding: utf-8\n\n# **Introduction**\n# In this post, you will discover the Keras Python library that provides a clean and convenient way to create a range of deep learning models on top of Theano or TensorFlow.\n# \n# All creidts to -- \"http://machinelearningmastery.com/tutorial-first-neural-network-python-keras/\"\n# \n# Let’s get started.\n\n# **Dependencies**\n# \n# All important libraries and data set are imported below\n# \n# **Python**\n# \n# Please run this script in Python 2 \n\n# In[ ]:\n\n\nimport os, sys, re\n#import cPickle as pickle\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nimport time\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\n\nprint (time.time())\ndataset = pd.read_csv('../input/loan.csv', low_memory=False)\n\n\n# Replace all the missing entries with zeros\n\n# In[ ]:\n\n\ndataset = dataset.fillna(0) ## filling missing values with zeros\n\n\n# **Data Modification**\n# \n# Convert all kind of categorical data into integral values accordingly and 'Date Column' into real values'\n\n# In[ ]:\n\n\ndataset['application_type'] = dataset['application_type'].astype('category').cat.codes\ndataset['addr_state'] = dataset['addr_state'].astype('category').cat.codes\ndataset['earliest_cr_line'] = pd.to_datetime(dataset['earliest_cr_line'])\ndataset['earliest_cr_line'] = (dataset['earliest_cr_line']-dataset['earliest_cr_line'].min())/np.timedelta64(1,'D')\ndataset['emp_length'] = dataset['emp_length'].astype('category').cat.codes\ndataset['grade'] = dataset['grade'].astype('category').cat.codes\ndataset['home_ownership'] = dataset['home_ownership'].astype('category').cat.codes\ndataset['initial_list_status'] = dataset['initial_list_status'].astype('category').cat.codes\ndataset['issue_d'] = pd.to_datetime(dataset['issue_d'])\ndataset['issue_d'] = (dataset['issue_d']-dataset['issue_d'].min())/np.timedelta64(1,'D')\ndataset['last_credit_pull_d'] = pd.to_datetime(dataset['last_credit_pull_d'])\ndataset['last_credit_pull_d'] = (dataset['last_credit_pull_d']-dataset['last_credit_pull_d'].min())/np.timedelta64(1,'D')\ndataset['last_pymnt_d'] = pd.to_datetime(dataset['last_pymnt_d'])\ndataset['last_pymnt_d'] = (dataset['last_pymnt_d']-dataset['last_pymnt_d'].min())/np.timedelta64(1,'D')\ndataset['loan_status'] = dataset['loan_status'].astype('category').cat.codes\ndataset['next_pymnt_d'] = pd.to_datetime(dataset['next_pymnt_d'])\ndataset['next_pymnt_d'] = (dataset['next_pymnt_d']-dataset['next_pymnt_d'].min())/np.timedelta64(1,'D')\ndataset['purpose'] = dataset['purpose'].astype('category').cat.codes\ndataset['pymnt_plan'] = dataset['pymnt_plan'].astype('category').cat.codes\ndataset['sub_grade'] = dataset['sub_grade'].astype('category').cat.codes\ndataset['term'] = dataset['term'].astype('category').cat.codes\ndataset['verification_status'] = dataset['verification_status'].astype('category').cat.codes\ndataset['verification_status_joint'] = dataset['verification_status_joint'].astype('category').cat.codes\n\n\n# Storing non numeric or non real columns name in non_numerics array\n\n# In[ ]:\n\n\nnon_numerics = [x for x in dataset.columns if not (dataset[x].dtype == np.float64 or dataset[x].dtype == np.int8 or dataset[x].dtype == np.int64)]\n\n\n# Droping non_numerics column for easy modeling\n\n# In[ ]:\n\n\ndf = dataset\ndf = df.drop(non_numerics,1)\n\n\n# Converting 'loan result status' into two categories 0 and 1. 0 means loan failed or that type of person should not be given loan in future and 1 means loan passed i.e. they are good for extending the loan.\n\n# In[ ]:\n\n\ndef LoanResult(status):\n if (status == 5) or (status == 1) or (status == 7):\n return 1\n else:\n return 0\n\ndf['loan_status'] = df['loan_status'].apply(LoanResult)\n\n\n# Splitting data into train data and test data with the help of scikit library in the ratio of 3:1\n\n# In[ ]:\n\n\ntrain, test = train_test_split(df, test_size = 0.25)\n\n##running complete data set will take a lot of time, hence reduced the data set\nX_train = train.drop('loan_status',1).values[0:50000, :]\nY_train = train['loan_status'].values[0:50000]\n\nX_test = test.drop('loan_status',1).values[0:1000, :]\nY_test = test['loan_status'].values[0:1000]\n\nX_pred = test.drop('loan_status',1).values[1001:2000, :]\n\n\n# Setting the seed for pseudo random numbers generation\n\n# In[ ]:\n\n\nseed = 8 \nnp.random.seed(seed)\n\n\n# Now we will define a three layered neural network model. We create a Sequential model and add layers one at a time until we are happy with our network topology. After that we will set activation function and number of nets in each layer. These are done by heuristics and training the model several times.\n\n# In[ ]:\n\n\n# Create the model \nmodel = Sequential()\n\n# Define the three layered model\nmodel.add(Dense(110, input_dim = 68, kernel_initializer = \"uniform\", activation = \"relu\"))\nmodel.add(Dense(110, kernel_initializer = \"uniform\", activation = \"relu\"))\nmodel.add(Dense(1, kernel_initializer = \"uniform\", activation = \"sigmoid\"))\n\n\n# Now we will compile the model. In this we have to input three parameters viz. loss function, optimizer function and an evaluation metrics. These choices are again by heuristics. Here we are using \"binary_crossentropy\" as loss func, \"adam\" as optimizer func and \"accuracy\" as evaluation metrics.\n\n# In[ ]:\n\n\n#\n# Compile the model\nmodel.compile(loss=\"binary_crossentropy\", optimizer= \"adam\", metrics=['accuracy'])\n#\n\n\n# Now we have to fit the data into our model. \n# We can train or fit our model on our loaded data by calling the fit() function on the model.\n# \n# The training process will run for a fixed number of iterations through the dataset called epochs, that we must specify using the **epochs** argument. We can also set the number of instances that are evaluated before a weight update in the network is performed, called the batch size and set using the **batch_size** argument.\n\n# In[ ]:\n\n\n# Fit the model\nmodel.fit(X_train, Y_train, epochs= 50, batch_size=200)\n\n\n# **Evaluate Model**\n# \n# We have trained our neural network on the entire dataset and we can evaluate the performance of the network on the test dataset.\n\n# In[ ]:\n\n\nperformance = model.evaluate(X_test, Y_test)\nprint(\"%s: %.2f%%\" % (model.metrics_names[1], performance[1]*100))\n#\n\n\n# **Final Prediction**\n# \n# Predicting using the trained model\n\n# In[ ]:\n\n\n# Predict using the trained model\nprediction = model.predict(X_pred)\nrounded_predictions = [np.round(x) for x in prediction]\nprint(rounded_predictions)\n\n", "#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\nimport matplotlib.pyplot as plt\n\nfrom mpl_toolkits.mplot3d import Axes3D\nget_ipython().run_line_magic('matplotlib', 'inline')\n\nfrom scipy import stats, linalg\n\nimport seaborn as sns\n\nmydata = pd.read_csv(\"../input/kc_house_data.csv\", parse_dates = ['date'])\n\n#make a table of the data!\n\n#categorize/clear the data\n\n#zip codes are strings\nmydata['zipcode'] = mydata['zipcode'].astype(str)\n#the other non ratio data are \"categories\" thanks pandas :D\nmydata['waterfront'] = mydata['waterfront'].astype('category',ordered=True)\nmydata['condition'] = mydata['condition'].astype('category',ordered=True)\nmydata['view'] = mydata['view'].astype('category',ordered=True)\nmydata['grade'] = mydata['grade'].astype('category',ordered=False)\n\n#drop ID\nmydata = mydata.drop(['id', 'date'],axis=1)\nmydata = mydata.dropna()\nmydata = mydata[mydata.bedrooms < 15]\n#display a table of all the data for refernce (handy)\ndf = pd.DataFrame(data = mydata)\nstr_list = [] # empty list to contain columns with strings (words)\nfor colname, colvalue in mydata.iteritems():\n if type(colvalue[1]) == str:\n str_list.append(colname)\n# Get to the numeric columns by inversion \nnum_list = mydata.columns.difference(str_list) \n# Create Dataframe containing only numerical features\nnumData = mydata[num_list]\n\n#and then remove more stuff\ninterestingCol =['price','bedrooms','bathrooms','sqft_above','sqft_living']\nnumData = numData[interestingCol]\noriginalData = numData.copy()\n\n#reduce the number of data points\nnumData = numData.sample(n=11000, random_state = 13)\noriginalData = numData.copy()\n\nfrom sklearn.preprocessing import MinMaxScaler\n#figure out what the standardized million dollars is and save that\noneMillSTD = (numData['price'].median()-numData['price'].mean())/numData['price'].std()\nnumData =(numData - numData.mean()) / numData.std()\n\n\n# In[2]:\n\n\nnumData.fillna(method='backfill', inplace=True)\n\nnumData.describe()\nnumData.head()\nsns.set_context(\"paper\")\nsns.distplot(originalData['price'])\n\n\n# In[3]:\n\n\nX = numData.drop(['price'],axis=1)\ny = numData['price']\n\nattributeNames = list(X)\n\nclassNames = ['MillionDollarHome','notMDH']\n\nfrom sklearn import model_selection\nX, X_testglb, y, y_testglb = model_selection.train_test_split(X,y, test_size = (1/11),random_state = 42)\n\nN, M = X.shape\n\n#Then we give it classes\ndef millionDollars(money):\n #returns false if the price is less than a million\n #returns true if the price is equal to or greater than a million dollars\n if(money < oneMillSTD):\n return 0\n else:\n return 1\n\n#create the new classification data set\ny_cat = y.apply(millionDollars)\n\n\n# In[5]:\n\n\nscaler = MinMaxScaler()\n\nXmat = scaler.fit_transform(X)\n\nY = Xmat - np.ones((Xmat.shape[0],1))*Xmat.mean(0)\nU,S,V = linalg.svd(Y,full_matrices=False)\nV=V.T\n#calculate the variance from principle components\nrho = (S*S)/(S*S).sum()\n\ncumsumrho = np.cumsum(rho)\n\n\nreducedData = Xmat.dot(V)\n\nprincCompX1 = [[0],[0]]\nprincCompY1 = [[0],[1]]\n\nprincCompX2 = [[0],[1]]\nprincCompY2 = [[0],[0]]\n\nfig = plt.figure()\nax = fig.add_subplot(111)\nax.scatter(Xmat[:,1],Xmat[:,2], c=y_cat, marker='.')\n#ax.plot(princCompX1,princCompY1, c='r')\n#ax.plot(princCompX2,princCompY2, c='r')\n\nplt.title('Data plotted along two PCA components')\nplt.xlabel('PCA1')\nplt.ylabel('PCA2')\n\nplt.show()\n\n\n# <h2>it's time for GMM baby</h2>\n\n# In[6]:\n\n\nfrom sklearn import mixture\nimport itertools\n\nXgmm = Xmat\n\nlowest_bic = np.infty\nbic = []\nn_components_range = range(1, 6)\ncv_types = ['tied']\nfor cv_type in cv_types:\n for n_components in n_components_range:\n # Fit a Gaussian mixture with EM\n gmm = mixture.GaussianMixture(n_components=n_components,\n covariance_type=cv_type)\n gmm.fit(Xgmm)\n bic.append(gmm.bic(Xgmm))\n if n_components == 5:\n bic[-1] = bic[-2]+1000\n \n if bic[-1] < lowest_bic:\n lowest_bic = bic[-1]\n best_gmm = gmm\n\nbic = np.array(bic)\ncolor_iter = itertools.cycle(['cornflowerblue'])\nclf = best_gmm\nbars = []\n\n# Plot the BIC scores\nspl = plt.subplot(2, 1, 1)\nfor i, (cv_type, color) in enumerate(zip(cv_types, color_iter)):\n xpos = np.array(n_components_range) + .2 * (i - 2)\n bars.append(plt.bar(xpos, bic[i * len(n_components_range):\n (i + 1) * len(n_components_range)],\n width=.2, color=color))\nplt.xticks(n_components_range)\nplt.ylim([bic.min() * 1.01 - .01 * bic.max(), bic.max()])\nplt.title('BIC score per model')\nxpos = np.mod(bic.argmin(), len(n_components_range)) + .65 +.2 * np.floor(bic.argmin() / len(n_components_range))\nplt.text(xpos, bic.min() * 0.97 + .03 * bic.max(), '*', fontsize=14)\nspl.set_xlabel('Number of components')\n\n\n# Time to visualize the clusters (first steal the code from the class\n\n# In[7]:\n\n\nK = 3\n\nfrom sklearn.mixture import GaussianMixture\ncov_type = 'diag' \n# type of covariance, you can try out 'diag' as well\nreps = 5 \n# number of fits with different initalizations, best result will be kept\n# Fit Gaussian mixture model\ngmm = GaussianMixture(n_components=K, covariance_type=cov_type, n_init=reps).fit(X)\ncls = gmm.predict(X) \n# extract cluster labels\ncds = gmm.means_ \n# extract cluster centroids (means of gaussians)\ncovs = gmm.covariances_\n# extract cluster shapes (covariances of gaussians)\nif cov_type == 'diag': \n new_covs = np.zeros([K,M,M]) \n\ncount = 0 \nfor elem in covs: \n temp_m = np.zeros([M,M]) \n for i in range(len(elem)): \n temp_m[i][i] = elem[i] \n \n new_covs[count] = temp_m \n count += 1\n \ncovs = new_covs\n# Plot results:\n\n\n# In[8]:\n\n\nfrom matplotlib.patches import Ellipse\n\ndef draw_ellipse(position, covariance, ax=None, **kwargs):\n \"\"\"Draw an ellipse with a given position and covariance\"\"\"\n ax = ax or plt.gca()\n \n # Convert covariance to principal axes\n if covariance.shape == (2, 2):\n U, s, Vt = np.linalg.svd(covariance)\n angle = np.degrees(np.arctan2(U[1, 0], U[0, 0]))\n width, height = 2 * np.sqrt(s)\n else:\n angle = 0\n width, height = 2 * np.sqrt(covariance)\n \n # Draw the Ellipse\n for nsig in range(1, 4):\n ax.add_patch(Ellipse(position, nsig * width, nsig * height,\n angle, **kwargs))\n \ndef plot_gmm(gmm, X, label=True, ax=None):\n ax = ax or plt.gca()\n labels = gmm.fit(X).predict(X)\n if label:\n ax.scatter(X[:, 0], X[:, 1], c=labels, s=40, cmap='viridis', zorder=2)\n else:\n ax.scatter(X[:, 0], X[:, 1], s=40, zorder=2)\n ax.axis('equal')\n plt.title('GMM with K=3 clusters')\n plt.xlabel('PCA1')\n plt.ylabel('PCA2')\n w_factor = 0.2 / gmm.weights_.max()\n for pos, covar, w in zip(gmm.means_, gmm.covariances_, gmm.weights_):\n draw_ellipse(pos, covar, alpha=w * w_factor)\n\n\n# In[9]:\n\n\nplot_gmm(gmm, Xmat[:,1:3])\n\n\n# <h2>Not Amazing, but let's try it anyway</h2>\n# Time to use hierarchy as seen in exersize 9\n\n# In[10]:\n\n\ndef plotDendro(Z,method):\n plt.figure(figsize=(25, 10))\n plt.title('Hierarchical Clustering Dendrogram Using the '+method+ 'Method')\n plt.xlabel('sample index')\n plt.ylabel('distance')\n dendrogram(\n Z,\n truncate_mode='lastp', # show only the last p merged clusters\n p=20, # show only the last p merged clusters\n show_leaf_counts=False, # otherwise numbers in brackets are counts\n leaf_rotation=90.,\n leaf_font_size=8.,\n show_contracted=True, # to get a distribution impression in truncated branches\n )\n plt.show()\n\n\n# In[12]:\n\n\nfrom scipy.cluster.hierarchy import linkage, fcluster, dendrogram\nfrom scipy.cluster.hierarchy import cophenet\nfrom scipy.spatial.distance import pdist\n\nMethod = 'single'\n\nMethods = ['single','complete','average','ward']\n\ncophenetScore =[]\nfor Method in Methods:\n Z = linkage(X, method=Method)\n c, coph_dists = cophenet(Z, pdist(X))\n print(Method)\n cophenetScore.append(c)\n print(\"%.2f\" %c)\n #plotDendro(Z,Method)\n\n#too much work to recreate the plotting\n\n\n# In[13]:\n\n\nmeasures = ['cityblock', 'cosine', 'jaccard', 'mahalanobis']\n\ncophenetScore =[]\nfor measure in measures:\n Z = linkage(X, method='average',metric=measure)\n c, coph_dists = cophenet(Z, pdist(X, metric=measure))\n print(measure)\n cophenetScore.append(c)\n print(\"%.2f\" %c)\n #plotDendro(Z,Method)\n\n\n# In[14]:\n\n\nZ = linkage(X, method='average',metric='cosine')\nc, coph_dists = cophenet(Z, pdist(X, metric='cosine'))\nprint(measure)\ncophenetScore.append(c)\nprint(\"%.2f\" %c)\n#plotDendro(Z,Method)\n\n\n# In[15]:\n\n\ndef fancy_dendrogram(*args, **kwargs):\n max_d = kwargs.pop('max_d', None)\n if max_d and 'color_threshold' not in kwargs:\n kwargs['color_threshold'] = max_d\n annotate_above = kwargs.pop('annotate_above', 0)\n\n ddata = dendrogram(*args, **kwargs)\n\n if not kwargs.get('no_plot', False):\n plt.title('Hierarchical Clustering Dendrogram (truncated)')\n plt.xlabel('sample index or (cluster size)')\n plt.ylabel('distance')\n for i, d, c in zip(ddata['icoord'], ddata['dcoord'], ddata['color_list']):\n x = 0.5 * sum(i[1:3])\n y = d[1]\n if y > annotate_above:\n plt.plot(x, y, 'o', c=c)\n plt.annotate(\"%.3g\" % y, (x, y), xytext=(0, -5),\n textcoords='offset points',\n va='top', ha='center')\n if max_d:\n plt.axhline(y=max_d, c='k')\n return ddata\n\n\n# In[16]:\n\n\n\nfancy_dendrogram(\n Z,\n truncate_mode='lastp',\n p=12,\n leaf_rotation=90.,\n leaf_font_size=12.,\n show_contracted=True,\n annotate_above=10, # useful in small plots so annotations don't overlap\n max_d = .8,\n)\nplt.show()\n\n\n# In[17]:\n\n\nfrom scipy.cluster.hierarchy import fcluster\nmax_d = .8\nclusters = fcluster(Z, max_d, criterion='distance')\nplt.figure()\nplt.title('Hierarchy grouping of data with 3 branches')\nplt.xlabel('PCA1')\nplt.ylabel('PCA2')\nplt.scatter(Xmat[:,1], Xmat[:,2], c=clusters, s=40, cmap='viridis', zorder=2) # plot points with cluster dependent colors\nplt.show()\n\n\n# In[26]:\n\n\nfrom sklearn import metrics\nHscore = metrics.adjusted_rand_score(y_cat,clusters)\n\nlabels = gmm.fit(Xmat).predict(Xmat)\n\nGMMscore = metrics.adjusted_rand_score(y_cat,labels)\nprint(\"%.2f\" %Hscore)\nprint(\"%.2f\" %GMMscore)\n\n\n# In[25]:\n\n\nprint(type(labels))\n\n\n# In[ ]:\n\n\n\n\n", "#!/usr/bin/env python\n# coding: utf-8\n\n# # 最終課題\n# ### 氏名:とみなが\n# ### 選んだ課題【House Sales in King County, USA】住宅販売価格を予測する\n# - 【URL】\n# https://www.kaggle.com/harlfoxem/housesalesprediction/data\n# \n\n# ## 中間発表(Day5までの宿題)\n# - タイトル\n# - 氏名もしくはニックネーム\n# - 選んだ課題\n# - 目的変数と説明変数の関係を確認するためのグラフ。また、そのグラフからわかるこ とを文章で。\n# - 目的変数を説明するのに有効そうな説明変数。また、それらが有効だと考えた理由を 文章で。\n# - 欠測値と異常値を確認した結果。また、欠測値や異常値をが存在する場合は、その処 理方法。\n# - 使えそうなアルゴリズムの候補。\n\n# ## データの確認\n# - はじめに、どのようなデータがが含まれているのか、確認を行う。\n\n# |カラム|説明|型|\n# |:--:|:--:|:--:|\n# |id|a notation for a house|Numeric|\n# |date|Date house was sold|String|\n# |price|Price is prediction target|Numeric|\n# |bedrooms|Number of Bedrooms/House|Numeric|\n# |bathrooms|Number of bathrooms/bedrooms|Numeric|\n# |sqft_living|square footage of the home|Numeric|\n# |sqft_lot|square footage of the lot|Numeric|\n# |floors|Total floors (levels) in house|Numeric|\n# |waterfront|House which has a view to a waterfront|Numeric\n# |view|Has been viewed|Numeric|\n# |condition|How good the condition is ( Overall )|Numeric|\n# |grade|overall grade given to the housing unit, based on King County grading system|Numeric|\n# |sqft_above|square footage of house apart from basement|Numeric|\n# |sqft_basement|square footage of the basement|Numeric|\n# |yr_built|Built Year|Numeric|\n# |yr_renovated|Year when house was renovated|Numeric|\n# |zipcode|zip|Numeric|\n# |lat|Latitude coordinate|Numeric|\n# |long|Longitude coordinate|Numeric|\n# |sqft_living15|Living room area in 2015(implies-- some renovations) This might or might not have affected the lotsize area|Numeric|\n# |sqft_lot15|lotSize area in 2015(implies-- some renovations)|Numeric|\n\n# - 英語での説明がわからなかったので、日本語にしてみました。\n# \n# |カラム|説明|型|\n# |:--:|:--:|:--:|\n# |id|識別子|Numeric|\n# |date|売却された日|String|\n# |price|価格(目的変数)|Numeric|\n# |bedrooms|ベッドルームの数/家|Numeric|\n# |bathrooms|お風呂の数/家|Numeric|\n# |sqft_living|家の平方フィート(広さ)|Numeric|\n# |sqft_lot|区画(lot)の平方フィート|Numeric|\n# |floors|家の中の全フロア(レベル)|Numeric|\n# |waterfront|海辺(waterfront)を望む家|Numeric\n# |view|内見された回数?|Numeric|\n# |condition|どのくらいの状態が良いか(全体的)|Numeric|\n# |gradeloveral | 「King County grading system」に基づいて、住宅部門に与えられた格付け|Numeric|\n# |sqft_above|地下室(basement)を含まない家の平方フィート|Numeric|\n# |sqft_basement|地下室(basement)の平方フィート|Numeric|\n# |yr_built|家が建った年|Numeric|\n# |yr_renovated|家が改築された年|Numeric|\n# |zipcode|郵便番号|Numeric|\n# |lat|緯度座標(Latitude coordinate)|Numeric|\n# |long|経度座標(Longitude coordinate)|Numeric|\n# |sqft_living15|2015年のリビングルーム面積(いくつかの改装を含む)これはロットサイズの面積に影響を与えているかもしれない|Numeric|\n# |sqft_lot15|2015年のロットサイズ面積(いくつかの改装を含む)|Numeric|\n\n# In[ ]:\n\n\n# -*- coding: utf-8 -*-\n#ライブラリの読み込み\nimport pandas as pd\nfrom IPython.display import display\nfrom dateutil.parser import parse\nimport matplotlib.pyplot as plt\n\n\n# In[ ]:\n\n\n#データの読み込み\ndf_data = pd.read_csv(\"../input/kc_house_data.csv\")\n\nprint(\"\")\nprint(\"データセットの頭出し\")\ndisplay(df_data.head())\n\n\n# In[ ]:\n\n\n# date列の変換(日付の形に変更) (説明変数として使わないため、実行しない。)\n#df_data[\"date\"] = [ parse(i[:-7]).date() for i in df_data[\"date\"]]\n#display(df_data.head())\n\n\n# ## 欠損値の確認\n\n# In[ ]:\n\n\n# 欠損値のデータが含まれているかどうか確認する\npd.DataFrame(df_data.isnull().sum(), columns=[\"num of missing\"])\n\n\n# - 上記の表より、欠損値はなし。\n\n# In[ ]:\n\n\n#不要な列の削除\ndf_data_main = df_data.drop([\"id\",\"date\",\"zipcode\"], axis=1)\ndf1 = df_data_main.iloc[:,:9]\ndisplay(df1.head())\ndf2 = df_data_main.iloc[:,[0]+list(range(9,18))]\ndisplay(df2.head())\n\n\n# In[ ]:\n\n\n# describe(記述統計量の算出)\ndf_data.describe()\n\n\n# In[ ]:\n\n\n# 散布図行列\npd.plotting.scatter_matrix(df1,figsize=(10,10))\nplt.show()\npd.plotting.scatter_matrix(df2,figsize=(10,10))\nplt.show()\n\n\n# In[ ]:\n\n\nimport itertools\nli_combi = list(itertools.combinations(df_data_main.columns[0:], 2))\nfor X,Y in li_combi:\n if X=='price':\n print(\"X=%s\"%X,\"Y=%s\"%Y)\n df_data_main.plot(kind=\"scatter\",x=X,y=Y,alpha=0.7,s=10,c=\"price\",colormap=\"winter\")#散布図の作成\n plt.xlabel(X)\n plt.ylabel(Y)\n plt.tight_layout()\n plt.show()#グラフをここで描画させるための行\n\n\n# ### 相関関係の確認\n\n# In[ ]:\n\n\ndf_data_main.corr()\n\n\n# 上記の分散図と、相関関係の表より、次の変数を用いることとする(順番あり)。\n# 1. sqft_living\n# 1. grade\n# 1. sqft_above\n# 1. bathrooms\n# \n# ※「sqft_living15」も、比較的高い相関関係を示しているが、「sqft_living」との関係があるため除外。\n\n# ## 異常値の検討\n\n# ### ヒストグラムによる確認\n\n# In[ ]:\n\n\nfor col in df_data_main.columns:\n print(col)\n df_data_main[col].hist()\n plt.xlabel(col)\n plt.ylabel(\"num\")\n plt.show()\n\n\n# - データ数が多く、ヒストグラムでは、異常値が判定できなかったため、次に箱ひげ図による確認を試みる。\n\n# ### 箱ひげ図による確認\n\n# In[ ]:\n\n\nfor col in df_data_main.columns:\n print(col)\n df_data_main.boxplot(column=col)\n plt.xlabel(col)\n plt.ylabel(\"num\")\n plt.show()\n\n\n# In[ ]:\n\n\n#異常値を除外したグラフを描画する。\nfor col in df_data_main.columns:\n \n Q1 = df_data_main[col].quantile(.25)\n Q3 = df_data_main[col].quantile(.75)\n\n #print(Q1)\n #print(Q3)\n \n IQR = Q3 - Q1\n threshold = Q3 + 1.5*IQR\n\n df_outlier = df_data_main[(df_data_main[col] < threshold)]\n\n print(col)\n df_outlier.boxplot(column=col)\n plt.xlabel(col)\n plt.ylabel(\"num\")\n plt.show()\n\n\n# ### 今後取り組まなければいけないこと\n# 1. 異常値を取り除いたデータを、データフレームワークへの格納する。\n# 1. 1.で作成したデータフレームワークの、異常値への処理。\n# 1. より詳細な分析(一部、まだ言葉で説明できていない部分があるため、そちらの補足を行う。)\n\n# ### 使えそうなアルゴリズム\n# - 重回帰分析\n# - サポートベクタマシン\n# - 決定木\n# - ランダムフォレスト\n", "#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\n# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport math\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nmatplotlib.style.use('ggplot')\n\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nfrom subprocess import check_output\n# print(check_output([\"ls\", \"../input\"]).decode(\"utf8\"))\n\n# read in data\ndf_cwur = pd.read_csv('../input/cwurData.csv')\ndf_expend = pd.read_csv('../input/education_expenditure_supplementary_data.csv', sep=None)\ndf_attain = pd.read_csv('../input/educational_attainment_supplementary_data.csv', sep=None)\ndf_sac = pd.read_csv('../input/school_and_country_table.csv')\ndf_shanghai = pd.read_csv('../input/shanghaiData.csv')\ndf_times = pd.read_csv('../input/timesData.csv')\n\n# adding country data to the shanghai dataset\ndf_sac.columns = ['university_name','country']\ndf_shanghai = df_shanghai.merge(df_sac, how='left', on='university_name')\n\n# updating column name in cwur for consistency\ndf_cwur = df_cwur.rename(columns = {'institution':'university_name'})\n\n# updating country names in cwur for consistency\ndf_cwur.drop('country', inplace=True, axis=1)\ndf_cwur = df_cwur.merge(df_sac, how='left', on='university_name')\n\n# combine the 3 ranking dataframes into one dataframe\nfor df, l in [(df_times,'t'), (df_cwur,'c'), (df_shanghai,'s')]:\n a = []\n for col in df.columns.values:\n if col not in ['university_name','year']:\n a.append(l + '_' + col)\n else:\n a.append(col)\n df.columns = a\n\ndf_full = df_times.merge(df_cwur, how='outer', on=['university_name','year'])\ndf_full = df_full.merge(df_shanghai, how='outer', on=['university_name','year'])\n\n\n# In[ ]:\n\n\n# creating a dataframe that specifically looks at the rankings\ndf_ranks = df_full[['university_name','t_country','year','t_world_rank','c_world_rank',\n 's_world_rank']].copy()\n\n# convert world rank columns to float (where necessary)\nf = lambda x: int((int(x.split('-')[0]) + int(x.split('-')[1])) / 2) if len(str(x).strip()) > 3 else x\n\ndf_ranks['t_world_rank'] = df_ranks['t_world_rank'].str.replace('=','').map(\n f).astype('float')\n\ndf_ranks['s_world_rank'] = df_ranks['s_world_rank'].str.replace('=','').map(\n f).astype('float')\n\ndf_ranks.dtypes\n\n\n# In[ ]:\n\n\n# note that data is available in all datasets in 2012 - 2015\n# let's investigate 2015\ndf_ranks2015 = df_ranks[df_ranks.year == 2015].copy()\n\n# adding min_rank column to show the best rank for each school\ndef f(x):\n a = []\n for i in ['t_world_rank','s_world_rank','c_world_rank']:\n try: \n if x[i] == float(x[i]):\n a.append(x[i])\n except:\n pass\n return min(a)\n\ndf_ranks2015['min_rank'] = df_ranks2015.apply(f,axis=1)\n\n# adding average rank column\ndf_ranks2015['mean_rank'] = df_ranks2015.apply(lambda x: np.mean(\n [x['s_world_rank'],x['t_world_rank'],x['c_world_rank']]).round(), axis=1)\n\n# adding standard deviation column\ndf_ranks2015['std_dev'] = df_ranks2015.apply(lambda x: np.std(\n [x['s_world_rank'],x['t_world_rank'],x['c_world_rank']]), axis=1)\n\n# plot highest variance in schools that have at least one rank in the top 100\ndf_ranks2015[df_ranks2015['min_rank'] <=100].sort_values('std_dev',ascending=False)[0:10].iloc[::-1].plot(\n x='university_name',y='std_dev',kind='barh', figsize=(12,6), fontsize=14,\n title='Top 100 schools with the highest standard deviation in ranking')\n\nprint((df_ranks2015[df_ranks2015['min_rank'] <=100].sort_values('std_dev',ascending=False).drop(\n 't_country',axis=1)[0:10]))\n\n\n# In[ ]:\n\n\n# plot lowest variance in schools that have at least one rank in the top 100\ndf_ranks2015[df_ranks2015['min_rank'] <=100].sort_values('std_dev',ascending=True)[0:10].iloc[::-1].plot(\n x='university_name',y='std_dev',kind='barh', figsize=(12,6), fontsize=14,\n title='Top 100 schools with the lowest standard deviation in ranking')\n\nprint((df_ranks2015[df_ranks2015['min_rank'] <=100].sort_values('std_dev',ascending=True).drop(\n 't_country',axis=1)[0:10]))\n\n\n# In[ ]:\n\n\n# how do ratings change over time?\n# note rankings are only available for all 3 in years 2012-2015\ndf_rankstime = df_ranks[(df_ranks['year'] <=2015) & (df_ranks['year'] >= 2012)]\n\n# times rankings\ndf_tranks = df_rankstime.pivot('university_name','year','t_world_rank').reset_index()\ndf_tranks.columns = ['university_name','2012','2013','2014','2015']\ndf_tranks['std_dev'] = df_tranks.apply(lambda x: np.std(\n [x['2012'],x['2013'],x['2014'],x['2015']]),axis=1)\ndf_tranks['mean'] = df_tranks.apply(lambda x: np.mean(\n [x['2012'],x['2013'],x['2014'],x['2015']]),axis=1)\n\n# cwur rankings\ndf_cranks = df_rankstime.pivot('university_name','year','c_world_rank').reset_index()\ndf_cranks.columns = ['university_name','2012','2013','2014','2015']\ndf_cranks['std_dev'] = df_cranks.apply(lambda x: np.std(\n [x['2012'],x['2013'],x['2014'],x['2015']]),axis=1)\ndf_cranks['mean'] = df_cranks.apply(lambda x: np.mean(\n [x['2012'],x['2013'],x['2014'],x['2015']]),axis=1)\n\n# shanghai rankings\ndf_sranks = df_rankstime.pivot('university_name','year','s_world_rank').reset_index()\ndf_sranks.columns = ['university_name','2012','2013','2014','2015']\ndf_sranks['std_dev'] = df_sranks.apply(lambda x: np.std(\n [x['2012'],x['2013'],x['2014'],x['2015']]),axis=1)\ndf_sranks['mean'] = df_sranks.apply(lambda x: np.mean(\n [x['2012'],x['2013'],x['2014'],x['2015']]),axis=1)\n\n\n# In[ ]:\n\n\ndf_tranks[df_tranks['mean'] <= 100].sort_values('std_dev',ascending=False)[0:10].iloc[::-1].plot(\n x='university_name',y='std_dev',kind='barh', figsize=(12,6), fontsize=14,\n title='Top 100 schools with the highest standard deviation in times ranking (2012-2015)')\n\n\n# In[ ]:\n\n\ndf_cranks[df_cranks['mean'] <= 100].sort_values('std_dev',ascending=False)[0:10].iloc[::-1].plot(\n x='university_name',y='std_dev',kind='barh', figsize=(12,6), fontsize=14,\n title='Top 100 schools with the highest standard deviation in CWUR ranking (2012-2015)')\n\n\n# In[ ]:\n\n\ndf_sranks[df_sranks['mean'] <= 100].sort_values('std_dev',ascending=False)[0:10].iloc[::-1].plot(\n x='university_name',y='std_dev',kind='barh', figsize=(12,6), fontsize=14,\n title='Top 100 schools with the highest standard deviation in Shanghai ranking (2012-2015)')\n\n\n# In[ ]:\n\n\n# which ranking was the most consistent for the top 100 schools?\nprint('Which ranking was the most consistent from 2012-2015 for the top 100 schools?')\nprint('\\n')\nprint(('Below is the standard deviation for the top 100 schools from each ranking','\\n'))\nprint(('Times:', round(df_tranks[df_tranks['mean'] <= 100]['std_dev'].mean(),2)))\nprint(('CWUR:', round(df_cranks[df_cranks['mean'] <= 100]['std_dev'].mean(),2)))\nprint(('Shanghai:', round(df_sranks[df_sranks['mean'] <= 100]['std_dev'].mean(),2)))\nprint('\\n')\nprint(('The Shanghai ranking was substantially more consistent than the other two rankings. This suggests',\n 'that the Shanghai ranking is less prone to shaking up rankings just for attention.'))\n\n\n# In[ ]:\n\n\n\n\n", "#!/usr/bin/env python\n# coding: utf-8\n\n# **Author: Jiashen Liu, Data Scientist at [Quantillion](http://quantillion.io/)** \n\n# # 0. Fire up\n\n# In[ ]:\n\n\nimport pandas as pd\nimport numpy as np\ndf = pd.read_csv('../input/kc_house_data.csv')\nprint(df.shape)\n\n\n# Let's have a look first on the data we have.\n\n# In[ ]:\n\n\ndf.head()\n\n\n# Let's drop the id column and split the data set into training and testing sets.\n\n# In[ ]:\n\n\ndel df['id']\n\n\n# We quickily check: whether there are some missing values exising in our data set before move on.\n\n# In[ ]:\n\n\nNA_Count = pd.DataFrame({'Sum of NA':df.isnull().sum()}).sort_values(by=['Sum of NA'],ascending=[0])\nNA_Count['Percentage'] = NA_Count['Sum of NA']/df.shape[1]\n\n\n# In[ ]:\n\n\nsum(NA_Count['Percentage'])\n\n\n# Data is quite clean! We do not have to waste time on dealing missing values. Let's move on!\n\n# # 1. Exploratory Data Analysis\n\n# First, we split the data set into training and testing sets. EDA will be finished in training set alone.\n\n# In[ ]:\n\n\nfrom sklearn.model_selection import train_test_split\ntrain,test = train_test_split(df,test_size = 0.2,random_state=42)\n\n\n# We can have continous and categorical variables for this case.\n\n# In[ ]:\n\n\ncat = ['waterfront','view','condition','grade']\ncon = ['bedrooms','bathrooms','sqft_living','sqft_lot','floors','sqft_above','sqft_basement','yr_built','yr_renovated','sqft_living15','sqft_lot15']\n\n\n# **Lon/Lat vs Price**\n\n# In[ ]:\n\n\nfrom ggplot import *\nlonlat = ggplot(train,aes(x='long',y='lat',color='price'))+geom_point()+scale_color_gradient(low='white',high='red')+ggtitle('Color Map of Price') \nprint(lonlat)\n\n\n# In[ ]:\n\n\nlonprice = ggplot(train,aes(x='long',y='price'))+geom_point()+ggtitle('Price VS Longitude')\nprint(lonprice)\n\n\n# We do a small feature engineering here. To centralize the longtitude and take absolute values so the new values will be linear with house price. The central point we choose is -122.25.\n\n# In[ ]:\n\n\ndef centralize_long(lon):\n return np.abs(lon+122.25)*-1\n\n\n# In[ ]:\n\n\ntrain['norm_lon'] = train['long'].apply(lambda x: centralize_long(x))\ntest['norm_lon'] = test['long'].apply(lambda x: centralize_long(x))\n\n\n# In[ ]:\n\n\nlonprice2 = ggplot(train,aes(x='norm_lon',y='price'))+geom_point()+ggtitle('Price VS Centered Longitude')\nprint(lonprice2)\n\n\n# In[ ]:\n\n\nlatprice = ggplot(train,aes(x='lat',y='price'))+geom_point()+stat_smooth()+ggtitle('Price VS Latitude')\nprint(latprice)\n\n\n# **Target VS Postcode**\n\n# In[ ]:\n\n\nzipprice = ggplot(train,aes(x='zipcode',y='price'))+geom_point()+ggtitle('ZipCode VS Price')\nprint(zipprice)\n\n\n# Seems that ZipCode is not a feature that has quite obvious impact on the price. Therefore, it is not quite wise to have such a categorical variable that has so many discrete values. We will try to group those variabes by longtitude and latitude, so we can actually shrink the size of variables. \n\n# In[ ]:\n\n\nlatlonzip = ggplot(train,aes(x='long',y='lat',color='zipcode'))+geom_point()+ggtitle('Long-Lat VS ZipCode')\nprint(latlonzip)\n\n\n# We can see that, zip code in an certain area is continous. So, to simplify everything, we just turn the zipcode into five different areas by specifying their values.\n\n# In[ ]:\n\n\ndef zip2area(zipcode):\n if zipcode <= 98028:\n return 'A'\n elif zipcode>98028 and zipcode <= 98072:\n return 'B'\n elif zipcode>98072 and zipcode<98122:\n return 'C'\n else:\n return 'D'\n\n\n# In[ ]:\n\n\ntrain['Area'] = train['zipcode'].apply(lambda x:zip2area(x))\ntest['Area'] = test['zipcode'].apply(lambda x:zip2area(x))\n\n\n# **Target VS Continous Variables**\n\n# In[ ]:\n\n\ncon_train = train[con+['price']]\ncor_tar_con = []\nfor each in con:\n cor_tar_con.append(np.corrcoef(train[each],train['price'])[0][1])\ncor_label = pd.DataFrame({'Variables':con,'Correlation':cor_tar_con}).sort_values(by=['Correlation'],ascending=[0])\n\n\n# In[ ]:\n\n\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm as cm\nimport seaborn as sns\n\n\n# In[ ]:\n\n\npos_1 = np.arange(len(con))\nplt.bar(pos_1, cor_label['Correlation'], align='center', alpha=0.5)\nplt.xticks(pos_1, cor_label['Variables'],rotation='vertical')\nplt.ylabel('Correlation')\nplt.title('Correlation between price and variables') \nplt.show()\n\n\n# **Multicolinearity among continouse variables**\n\n# In[ ]:\n\n\ncorr = con_train.corr()\ncorr.style.background_gradient(cmap='viridis', low=.5, high=0).highlight_null('red')\n\n\n# We can see that: high correlation can be detected between sqft_above and sqft_living. It is suprised that sqft_living and sqft_living15 do not reveal huge correlation in between.\n\n# **Catgorical Variable vs Target**\n\n# In[ ]:\n\n\ndef box_plot(var):\n pt = a = ggplot(train,aes(x=var,y='price'))+geom_boxplot() + theme_bw()+ggtitle('Boxplot of '+var+' and price')\n return print(pt)\n\n\n# In[ ]:\n\n\nfor each in cat:\n box_plot(each)\n\n\n# Seems that grade should be treated as a continous variable\n\n# **Price VS Time**\n\n# In[ ]:\n\n\ntrain['date']=pd.to_datetime(train['date'])\ntest['date']=pd.to_datetime(test['date'])\n\n\n# In[ ]:\n\n\ndateprice = ggplot(train,aes(x='date',y='price'))+geom_line()+stat_smooth()+ggtitle('Date VS Price')\nprint(dateprice)\n\n\n# As the date data is hard to be fitted in the model, we decided to transfer them into the numeric values. We will take the oldest date in the whole data set as the benchmark and calculate the date between the actual date and it.\n\n# In[ ]:\n\n\nmin_date = min(test['date'])\ndef get_interval(date):\n return int(str(date-min_date).split()[0])\n\n\n# In[ ]:\n\n\ntrain['date_interval'] = train['date'].apply(lambda x: get_interval(x))\ntest['date_interval']=test['date'].apply(lambda x: get_interval(x))\n\n\n# **Preparing the data sets**\n\n# In[ ]:\n\n\ncolumns = con + cat + ['date_interval','norm_lon','Area']\ntrain_ = train[columns]\ntest_ = test[columns]\ntrain_['Area']=pd.factorize(train_['Area'], sort=True)[0]\ntest_['Area']=pd.factorize(test_['Area'], sort=True)[0]\n\n\n# **Choosing the labels**\n\n# In[ ]:\n\n\nimport statsmodels.api as sm\nfig=sm.qqplot(train['price'])\nplt.show()\n\n\n# The QQ Plot reveals a non-normalized distribution of the label. Let's try logrithm transform. \n\n# In[ ]:\n\n\nfig=sm.qqplot(np.log(train['price']))\nplt.show()\n\n\n# It is way better. Let's use it as the label in regression Model.\n\n# In[ ]:\n\n\ntrain_['log_price'] = np.log(train['price'])\n\n\n# # 2. Regression Models\n\n# Grid Search maybe the method we use in the process of hyper parameter tuning.\n\n# In[ ]:\n\n\nModels = []\nRMSE = []\n\n\n# ## 2.1 Linear Regression\n\n# In[ ]:\n\n\nfrom math import sqrt\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_squared_error as mse\n\n\n# In[ ]:\n\n\nModels.append('Normal Linear Regression')\nreg = LinearRegression(n_jobs=-1)\nreg.fit(train_[columns],train_['log_price'])\npred = np.exp(reg.predict(test_))\nAccuracy = sqrt(mse(pred,test['price']))\nprint('=='*20+'RMSE: '+str(Accuracy)+'=='*20)\nRMSE.append(Accuracy)\n\n\n# ## 2.2 Linear Regression With Step 2&3 Polynomial Transformation\n\n# In[ ]:\n\n\nfrom sklearn.preprocessing import PolynomialFeatures, StandardScaler\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.model_selection import GridSearchCV\npipe = Pipeline([\n('sc',StandardScaler()),\n('poly',PolynomialFeatures(include_bias=True)),\n('reg',LinearRegression())\n])\nmodel = GridSearchCV(pipe,param_grid={'poly__degree':[2,3]})\nmodel.fit(train_[columns],train_['log_price'])\ndegree = model.best_params_\nprint(degree)\npred = np.exp(model.predict(test_))\nAccuracy = sqrt(mse(pred,test['price']))\nprint('=='*20+'RMSE: '+str(Accuracy)+'=='*20)\nRMSE.append(Accuracy)\n\n\n# In[ ]:\n\n\nModels.append('LinearRegression Step2 Polynominal')\n\n\n# ## 2.3 Lasso Regression With Step 2 Polynomial Transformation\n\n# In[ ]:\n\n\nfrom sklearn.linear_model import Lasso\n\n\n# In[ ]:\n\n\npipe = Pipeline([\n('sc',StandardScaler()),\n('poly',PolynomialFeatures(degree=2,include_bias=True)),\n('las',Lasso())\n])\nmodel = GridSearchCV(pipe,param_grid={'las__alpha':[0.0005,0.001,0.01]})\nmodel.fit(train_[columns],train_['log_price'])\ndegree = model.best_params_\nprint(degree)\npred = np.exp(model.predict(test_))\nAccuracy = sqrt(mse(pred,test['price']))\nprint('=='*20+'RMSE: '+str(Accuracy)+'=='*20)\nRMSE.append(Accuracy)\nModels.append('Lasso')\n\n\n# ## 2.4 ElasticNet Regression With Step 2 Polynomial Transformation\n\n# In[ ]:\n\n\nfrom sklearn.linear_model import ElasticNet\npipe = Pipeline([\n('sc',StandardScaler()),\n('poly',PolynomialFeatures(degree=2,include_bias=True)),\n('en',ElasticNet())\n])\nmodel = GridSearchCV(pipe,param_grid={'en__alpha':[0.005,0.01,0.05,0.1],'en__l1_ratio':[0.1,0.4,0.8]})\nmodel.fit(train_[columns],train_['log_price'])\ndegree = model.best_params_\nprint(degree)\npred = np.exp(model.predict(test_))\nAccuracy = sqrt(mse(pred,test['price']))\nprint('=='*20+'RMSE: '+str(Accuracy)+'=='*20)\nRMSE.append(Accuracy)\nModels.append('ElasticNet Regression')\n\n\n# ## 2.5 Regression Model Summary\n\n# In short, we can find that, adding features by polynomial transformation can boost the performance of the model to a large extent.\n\n# In[ ]:\n\n\nRegSummary = pd.DataFrame({'Model':Models,'RMSE':RMSE})\nsummary = ggplot(RegSummary,aes(x='Model',weight='RMSE'))+geom_bar()+theme_bw()+ggtitle('Summary of Regression Model')\nprint(summary)\n\n\n# ## 3. Short Conclusion and TO-DO\n\n# We already tested different regression models. They look OK, but not good enough. Next step, We will put the L2 Regularization as a process of feature selection and put the pipeline into the tree models to see whether a combination can build a state of art model.\n\n# In[ ]:\n\n\n\n\n", "#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\n# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n\ndf = pd.read_csv(\"../input/cwurData.csv\")\n\n\n# In[ ]:\n\n\ndf\n\n\n# In[ ]:\n\n\ndf[df[\"country\"] == \"Estonia\"]\n\n\n# In[ ]:\n\n\npd.DataFrame(df.groupby(\"country\")[\"quality_of_education\"].mean()).sort_values(\"quality_of_education\", ascending=False)\n\n\n# In[ ]:\n\n\ndf.groupby(\"country\").size()\n\n\n# In[ ]:\n\n\ndf[df[\"year\"] == 2015].groupby(\"country\").size()\n\n" ]
[ [ "pandas.read_csv", "pandas.to_datetime", "numpy.random.seed", "sklearn.model_selection.train_test_split", "numpy.timedelta64", "numpy.round" ], [ "scipy.linalg.svd", "numpy.sqrt", "numpy.cumsum", "pandas.DataFrame", "numpy.arctan2", "matplotlib.pyplot.plot", "sklearn.metrics.adjusted_rand_score", "sklearn.preprocessing.MinMaxScaler", "matplotlib.pyplot.gca", "numpy.linalg.svd", "pandas.read_csv", "matplotlib.pyplot.subplot", "scipy.cluster.hierarchy.linkage", "numpy.zeros", "matplotlib.pyplot.figure", "matplotlib.pyplot.title", "matplotlib.pyplot.annotate", "sklearn.model_selection.train_test_split", "scipy.cluster.hierarchy.dendrogram", "sklearn.mixture.GaussianMixture", "numpy.array", "matplotlib.pyplot.show", "scipy.cluster.hierarchy.fcluster", "matplotlib.pyplot.ylabel", "matplotlib.patches.Ellipse", "matplotlib.pyplot.axhline", "matplotlib.pyplot.scatter", "numpy.ones", "scipy.spatial.distance.pdist", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.xticks" ], [ "pandas.read_csv", "matplotlib.pyplot.tight_layout", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.show", "pandas.plotting.scatter_matrix", "matplotlib.pyplot.ylabel" ], [ "numpy.std", "pandas.read_csv", "numpy.mean", "matplotlib.style.use" ], [ "pandas.to_datetime", "sklearn.linear_model.ElasticNet", "sklearn.preprocessing.PolynomialFeatures", "pandas.DataFrame", "sklearn.metrics.mean_squared_error", "pandas.read_csv", "sklearn.linear_model.Lasso", "numpy.log", "matplotlib.pyplot.title", "pandas.factorize", "sklearn.model_selection.train_test_split", "numpy.corrcoef", "matplotlib.pyplot.show", "matplotlib.pyplot.xticks", "matplotlib.pyplot.ylabel", "sklearn.model_selection.GridSearchCV", "numpy.abs", "sklearn.linear_model.LinearRegression", "matplotlib.pyplot.bar", "sklearn.preprocessing.StandardScaler" ], [ "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [ "0.13", "0.12", "0.14", "0.15" ], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
joelberkeley/GPflow
[ "78230b98f57c64b5ee2932ea0d2752eb9ff102ce", "78230b98f57c64b5ee2932ea0d2752eb9ff102ce", "78230b98f57c64b5ee2932ea0d2752eb9ff102ce", "78230b98f57c64b5ee2932ea0d2752eb9ff102ce" ]
[ "gpflow/models/gpr.py", "gpflow/models/gplvm.py", "gpflow/likelihoods/scalar_discrete.py", "tests/gpflow/quadrature/test_quadrature.py" ]
[ "# Copyright 2016-2020 The GPflow Contributors. 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\nfrom typing import Optional\n\nimport tensorflow as tf\n\nimport gpflow\n\nfrom .. import posteriors\nfrom ..base import InputData, MeanAndVariance, RegressionData\nfrom ..kernels import Kernel\nfrom ..logdensities import multivariate_normal\nfrom ..mean_functions import MeanFunction\nfrom ..utilities.model_utils import add_noise_cov\nfrom .model import GPModel\nfrom .training_mixins import InternalDataTrainingLossMixin\nfrom .util import data_input_to_tensor\n\n\nclass GPR_deprecated(GPModel, InternalDataTrainingLossMixin):\n r\"\"\"\n Gaussian Process Regression.\n\n This is a vanilla implementation of GP regression with a Gaussian\n likelihood. Multiple columns of Y are treated independently.\n\n The log likelihood of this model is given by\n\n .. math::\n \\log p(Y \\,|\\, \\mathbf f) =\n \\mathcal N(Y \\,|\\, 0, \\sigma_n^2 \\mathbf{I})\n\n To train the model, we maximise the log _marginal_ likelihood\n w.r.t. the likelihood variance and kernel hyperparameters theta.\n The marginal likelihood is found by integrating the likelihood\n over the prior, and has the form\n\n .. math::\n \\log p(Y \\,|\\, \\sigma_n, \\theta) =\n \\mathcal N(Y \\,|\\, 0, \\mathbf{K} + \\sigma_n^2 \\mathbf{I})\n \"\"\"\n\n def __init__(\n self,\n data: RegressionData,\n kernel: Kernel,\n mean_function: Optional[MeanFunction] = None,\n noise_variance: float = 1.0,\n ):\n likelihood = gpflow.likelihoods.Gaussian(noise_variance)\n _, Y_data = data\n super().__init__(kernel, likelihood, mean_function, num_latent_gps=Y_data.shape[-1])\n self.data = data_input_to_tensor(data)\n\n # type-ignore is because of changed method signature:\n def maximum_log_likelihood_objective(self) -> tf.Tensor: # type: ignore\n return self.log_marginal_likelihood()\n\n def _add_noise_cov(self, K: tf.Tensor) -> tf.Tensor:\n \"\"\"\n Returns K + σ² I, where σ² is the likelihood noise variance (scalar),\n and I is the corresponding identity matrix.\n \"\"\"\n return add_noise_cov(K, self.likelihood.variance)\n\n def log_marginal_likelihood(self) -> tf.Tensor:\n r\"\"\"\n Computes the log marginal likelihood.\n\n .. math::\n \\log p(Y | \\theta).\n\n \"\"\"\n X, Y = self.data\n K = self.kernel(X)\n ks = self._add_noise_cov(K)\n L = tf.linalg.cholesky(ks)\n m = self.mean_function(X)\n\n # [R,] log-likelihoods for each independent dimension of Y\n log_prob = multivariate_normal(Y, m, L)\n return tf.reduce_sum(log_prob)\n\n def predict_f(\n self, Xnew: InputData, full_cov: bool = False, full_output_cov: bool = False\n ) -> MeanAndVariance:\n r\"\"\"\n This method computes predictions at X \\in R^{N \\x D} input points\n\n .. math::\n p(F* | Y)\n\n where F* are points on the GP at new data points, Y are noisy observations at training data\n points.\n \"\"\"\n X, Y = self.data\n err = Y - self.mean_function(X)\n\n kmm = self.kernel(X)\n knn = self.kernel(Xnew, full_cov=full_cov)\n kmn = self.kernel(X, Xnew)\n kmm_plus_s = self._add_noise_cov(kmm)\n\n conditional = gpflow.conditionals.base_conditional\n f_mean_zero, f_var = conditional(\n kmn, kmm_plus_s, knn, err, full_cov=full_cov, white=False\n ) # [N, P], [N, P] or [P, N, N]\n f_mean = f_mean_zero + self.mean_function(Xnew)\n return f_mean, f_var\n\n\nclass GPR_with_posterior(GPR_deprecated):\n \"\"\"\n This is an implementation of GPR that provides a posterior() method that\n enables caching for faster subsequent predictions.\n \"\"\"\n\n def posterior(\n self,\n precompute_cache: posteriors.PrecomputeCacheType = posteriors.PrecomputeCacheType.TENSOR,\n ) -> posteriors.GPRPosterior:\n \"\"\"\n Create the Posterior object which contains precomputed matrices for\n faster prediction.\n\n precompute_cache has three settings:\n\n - `PrecomputeCacheType.TENSOR` (or `\"tensor\"`): Precomputes the cached\n quantities and stores them as tensors (which allows differentiating\n through the prediction). This is the default.\n - `PrecomputeCacheType.VARIABLE` (or `\"variable\"`): Precomputes the cached\n quantities and stores them as variables, which allows for updating\n their values without changing the compute graph (relevant for AOT\n compilation).\n - `PrecomputeCacheType.NOCACHE` (or `\"nocache\"` or `None`): Avoids\n immediate cache computation. This is useful for avoiding extraneous\n computations when you only want to call the posterior's\n `fused_predict_f` method.\n \"\"\"\n\n return posteriors.GPRPosterior(\n kernel=self.kernel,\n data=self.data,\n likelihood_variance=self.likelihood.variance,\n mean_function=self.mean_function,\n precompute_cache=precompute_cache,\n )\n\n def predict_f(\n self, Xnew: InputData, full_cov: bool = False, full_output_cov: bool = False\n ) -> MeanAndVariance:\n \"\"\"\n For backwards compatibility, GPR's predict_f uses the fused (no-cache)\n computation, which is more efficient during training.\n\n For faster (cached) prediction, predict directly from the posterior object, i.e.,:\n model.posterior().predict_f(Xnew, ...)\n \"\"\"\n return self.posterior(posteriors.PrecomputeCacheType.NOCACHE).fused_predict_f(\n Xnew, full_cov=full_cov, full_output_cov=full_output_cov\n )\n\n\nclass GPR(GPR_with_posterior):\n # subclassed to ensure __class__ == \"GPR\"\n pass\n", "# Copyright 2016-2020 The GPflow Contributors. 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\nfrom typing import Optional\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom .. import covariances, kernels, likelihoods\nfrom ..base import Parameter, RegressionData, TensorType\nfrom ..config import default_float, default_jitter\nfrom ..expectations import expectation\nfrom ..inducing_variables import InducingPoints\nfrom ..kernels import Kernel\nfrom ..mean_functions import MeanFunction, Zero\nfrom ..probability_distributions import DiagonalGaussian\nfrom ..utilities import positive, to_default_float\nfrom ..utilities.ops import pca_reduce\nfrom .gpr import GPR\nfrom .model import GPModel, MeanAndVariance\nfrom .training_mixins import InputData, InternalDataTrainingLossMixin, OutputData\nfrom .util import InducingVariablesLike, data_input_to_tensor, inducingpoint_wrapper\n\n\nclass GPLVM(GPR):\n \"\"\"\n Standard GPLVM where the likelihood can be optimised with respect to the latent X.\n \"\"\"\n\n def __init__(\n self,\n data: OutputData,\n latent_dim: int,\n X_data_mean: Optional[tf.Tensor] = None,\n kernel: Optional[Kernel] = None,\n mean_function: Optional[MeanFunction] = None,\n ):\n \"\"\"\n Initialise GPLVM object. This method only works with a Gaussian likelihood.\n\n :param data: y data matrix, size N (number of points) x D (dimensions)\n :param latent_dim: the number of latent dimensions (Q)\n :param X_data_mean: latent positions ([N, Q]), for the initialisation of the latent space.\n :param kernel: kernel specification, by default Squared Exponential\n :param mean_function: mean function, by default None.\n \"\"\"\n if X_data_mean is None:\n X_data_mean = pca_reduce(data, latent_dim)\n\n num_latent_gps = X_data_mean.shape[1]\n if num_latent_gps != latent_dim:\n msg = \"Passed in number of latent {0} does not match initial X {1}.\"\n raise ValueError(msg.format(latent_dim, num_latent_gps))\n\n if mean_function is None:\n mean_function = Zero()\n\n if kernel is None:\n kernel = kernels.SquaredExponential(lengthscales=tf.ones((latent_dim,)))\n\n if data.shape[1] < num_latent_gps:\n raise ValueError(\"More latent dimensions than observed.\")\n\n gpr_data = (Parameter(X_data_mean), data_input_to_tensor(data))\n super().__init__(gpr_data, kernel, mean_function=mean_function)\n\n\nclass BayesianGPLVM(GPModel, InternalDataTrainingLossMixin):\n def __init__(\n self,\n data: OutputData,\n X_data_mean: tf.Tensor,\n X_data_var: tf.Tensor,\n kernel: Kernel,\n num_inducing_variables: Optional[int] = None,\n inducing_variable: Optional[InducingVariablesLike] = None,\n X_prior_mean: Optional[TensorType] = None,\n X_prior_var: Optional[TensorType] = None,\n ):\n \"\"\"\n Initialise Bayesian GPLVM object. This method only works with a Gaussian likelihood.\n\n :param data: data matrix, size N (number of points) x D (dimensions)\n :param X_data_mean: initial latent positions, size N (number of points) x\n Q (latent dimensions).\n :param X_data_var: variance of latent positions ([N, Q]), for the initialisation of the\n latent space.\n :param kernel: kernel specification, by default Squared Exponential\n :param num_inducing_variables: number of inducing points, M\n :param inducing_variable: matrix of inducing points, size M (inducing points) x\n Q (latent dimensions). By default random permutation of X_data_mean.\n :param X_prior_mean: prior mean used in KL term of bound. By default 0.\n Same size as X_data_mean.\n :param X_prior_var: prior variance used in KL term of bound. By default 1.\n \"\"\"\n num_data, num_latent_gps = X_data_mean.shape\n super().__init__(kernel, likelihoods.Gaussian(), num_latent_gps=num_latent_gps)\n self.data = data_input_to_tensor(data)\n assert X_data_var.ndim == 2\n\n self.X_data_mean = Parameter(X_data_mean)\n self.X_data_var = Parameter(X_data_var, transform=positive())\n\n self.num_data = num_data\n self.output_dim = self.data.shape[-1]\n\n assert np.all(X_data_mean.shape == X_data_var.shape)\n assert X_data_mean.shape[0] == self.data.shape[0], \"X mean and Y must be same size.\"\n assert X_data_var.shape[0] == self.data.shape[0], \"X var and Y must be same size.\"\n\n if (inducing_variable is None) == (num_inducing_variables is None):\n raise ValueError(\n \"BayesianGPLVM needs exactly one of `inducing_variable` and\"\n \" `num_inducing_variables`\"\n )\n\n if inducing_variable is None:\n # By default we initialize by subset of initial latent points\n # Note that tf.random.shuffle returns a copy, it does not shuffle in-place\n Z = tf.random.shuffle(X_data_mean)[:num_inducing_variables]\n inducing_variable = InducingPoints(Z)\n\n self.inducing_variable = inducingpoint_wrapper(inducing_variable)\n\n assert X_data_mean.shape[1] == self.num_latent_gps\n\n # deal with parameters for the prior mean variance of X\n if X_prior_mean is None:\n X_prior_mean = tf.zeros((self.num_data, self.num_latent_gps), dtype=default_float())\n if X_prior_var is None:\n X_prior_var = tf.ones((self.num_data, self.num_latent_gps))\n\n self.X_prior_mean = tf.convert_to_tensor(np.atleast_1d(X_prior_mean), dtype=default_float())\n self.X_prior_var = tf.convert_to_tensor(np.atleast_1d(X_prior_var), dtype=default_float())\n\n assert self.X_prior_mean.shape[0] == self.num_data\n assert self.X_prior_mean.shape[1] == self.num_latent_gps\n assert self.X_prior_var.shape[0] == self.num_data\n assert self.X_prior_var.shape[1] == self.num_latent_gps\n\n # type-ignore is because of changed method signature:\n def maximum_log_likelihood_objective(self) -> tf.Tensor: # type: ignore\n return self.elbo()\n\n def elbo(self) -> tf.Tensor:\n \"\"\"\n Construct a tensorflow function to compute the bound on the marginal\n likelihood.\n \"\"\"\n Y_data = self.data\n\n pX = DiagonalGaussian(self.X_data_mean, self.X_data_var)\n\n num_inducing = self.inducing_variable.num_inducing\n psi0 = tf.reduce_sum(expectation(pX, self.kernel))\n psi1 = expectation(pX, (self.kernel, self.inducing_variable))\n psi2 = tf.reduce_sum(\n expectation(\n pX, (self.kernel, self.inducing_variable), (self.kernel, self.inducing_variable)\n ),\n axis=0,\n )\n cov_uu = covariances.Kuu(self.inducing_variable, self.kernel, jitter=default_jitter())\n L = tf.linalg.cholesky(cov_uu)\n sigma2 = self.likelihood.variance\n\n # Compute intermediate matrices\n A = tf.linalg.triangular_solve(L, tf.transpose(psi1), lower=True)\n tmp = tf.linalg.triangular_solve(L, psi2, lower=True)\n AAT = tf.linalg.triangular_solve(L, tf.transpose(tmp), lower=True) / sigma2\n B = AAT + tf.eye(num_inducing, dtype=default_float())\n LB = tf.linalg.cholesky(B)\n log_det_B = 2.0 * tf.reduce_sum(tf.math.log(tf.linalg.diag_part(LB)))\n c = tf.linalg.triangular_solve(LB, tf.linalg.matmul(A, Y_data), lower=True) / sigma2\n\n # KL[q(x) || p(x)]\n dX_data_var = (\n self.X_data_var\n if self.X_data_var.shape.ndims == 2\n else tf.linalg.diag_part(self.X_data_var)\n )\n NQ = to_default_float(tf.size(self.X_data_mean))\n D = to_default_float(tf.shape(Y_data)[1])\n KL = -0.5 * tf.reduce_sum(tf.math.log(dX_data_var))\n KL += 0.5 * tf.reduce_sum(tf.math.log(self.X_prior_var))\n KL -= 0.5 * NQ\n KL += 0.5 * tf.reduce_sum(\n (tf.square(self.X_data_mean - self.X_prior_mean) + dX_data_var) / self.X_prior_var\n )\n\n # compute log marginal bound\n ND = to_default_float(tf.size(Y_data))\n bound = -0.5 * ND * tf.math.log(2 * np.pi * sigma2)\n bound += -0.5 * D * log_det_B\n bound += -0.5 * tf.reduce_sum(tf.square(Y_data)) / sigma2\n bound += 0.5 * tf.reduce_sum(tf.square(c))\n bound += -0.5 * D * (tf.reduce_sum(psi0) / sigma2 - tf.reduce_sum(tf.linalg.diag_part(AAT)))\n bound -= KL\n return bound\n\n def predict_f(\n self, Xnew: InputData, full_cov: bool = False, full_output_cov: bool = False\n ) -> MeanAndVariance:\n \"\"\"\n Compute the mean and variance of the latent function at some new points.\n Note that this is very similar to the SGPR prediction, for which\n there are notes in the SGPR notebook.\n\n Note: This model does not allow full output covariances.\n\n :param Xnew: points at which to predict\n \"\"\"\n if full_output_cov:\n raise NotImplementedError\n\n pX = DiagonalGaussian(self.X_data_mean, self.X_data_var)\n\n Y_data = self.data\n num_inducing = self.inducing_variable.num_inducing\n psi1 = expectation(pX, (self.kernel, self.inducing_variable))\n psi2 = tf.reduce_sum(\n expectation(\n pX, (self.kernel, self.inducing_variable), (self.kernel, self.inducing_variable)\n ),\n axis=0,\n )\n jitter = default_jitter()\n Kus = covariances.Kuf(self.inducing_variable, self.kernel, Xnew)\n sigma2 = self.likelihood.variance\n L = tf.linalg.cholesky(covariances.Kuu(self.inducing_variable, self.kernel, jitter=jitter))\n\n A = tf.linalg.triangular_solve(L, tf.transpose(psi1), lower=True)\n tmp = tf.linalg.triangular_solve(L, psi2, lower=True)\n AAT = tf.linalg.triangular_solve(L, tf.transpose(tmp), lower=True) / sigma2\n B = AAT + tf.eye(num_inducing, dtype=default_float())\n LB = tf.linalg.cholesky(B)\n c = tf.linalg.triangular_solve(LB, tf.linalg.matmul(A, Y_data), lower=True) / sigma2\n tmp1 = tf.linalg.triangular_solve(L, Kus, lower=True)\n tmp2 = tf.linalg.triangular_solve(LB, tmp1, lower=True)\n mean = tf.linalg.matmul(tmp2, c, transpose_a=True)\n if full_cov:\n var = (\n self.kernel(Xnew)\n + tf.linalg.matmul(tmp2, tmp2, transpose_a=True)\n - tf.linalg.matmul(tmp1, tmp1, transpose_a=True)\n )\n shape = tf.stack([1, 1, tf.shape(Y_data)[1]])\n var = tf.tile(tf.expand_dims(var, 2), shape)\n else:\n var = (\n self.kernel(Xnew, full_cov=False)\n + tf.reduce_sum(tf.square(tmp2), axis=0)\n - tf.reduce_sum(tf.square(tmp1), axis=0)\n )\n shape = tf.stack([1, tf.shape(Y_data)[1]])\n var = tf.tile(tf.expand_dims(var, 1), shape)\n return mean + self.mean_function(Xnew), var\n\n def predict_log_density(\n self, data: RegressionData, full_cov: bool = False, full_output_cov: bool = False\n ) -> tf.Tensor:\n raise NotImplementedError\n", "# Copyright 2017-2020 The GPflow Contributors. 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\nfrom typing import Any, Callable\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom .. import logdensities\nfrom ..base import AnyNDArray, MeanAndVariance, Parameter, TensorType\nfrom ..config import default_float\nfrom ..utilities import positive, to_default_int\nfrom .base import ScalarLikelihood\nfrom .utils import inv_probit\n\n\nclass Poisson(ScalarLikelihood):\n r\"\"\"\n Poisson likelihood for use with count data, where the rate is given by the (transformed) GP.\n\n let g(.) be the inverse-link function, then this likelihood represents\n\n p(yᵢ | fᵢ) = Poisson(yᵢ | g(fᵢ) * binsize)\n\n Note:binsize\n For use in a Log Gaussian Cox process (doubly stochastic model) where the\n rate function of an inhomogeneous Poisson process is given by a GP. The\n intractable likelihood can be approximated via a Riemann sum (with bins\n of size 'binsize') and using this Poisson likelihood.\n \"\"\"\n\n def __init__(\n self,\n invlink: Callable[[tf.Tensor], tf.Tensor] = tf.exp,\n binsize: float = 1.0,\n **kwargs: Any,\n ) -> None:\n super().__init__(**kwargs)\n self.invlink = invlink\n self.binsize: AnyNDArray = np.array(binsize, dtype=default_float())\n\n def _scalar_log_prob(self, F: TensorType, Y: TensorType) -> tf.Tensor:\n return logdensities.poisson(Y, self.invlink(F) * self.binsize)\n\n def _conditional_variance(self, F: TensorType) -> tf.Tensor:\n return self.invlink(F) * self.binsize\n\n def _conditional_mean(self, F: TensorType) -> tf.Tensor:\n return self.invlink(F) * self.binsize\n\n def _variational_expectations(\n self, Fmu: TensorType, Fvar: TensorType, Y: TensorType\n ) -> tf.Tensor:\n if self.invlink is tf.exp:\n return tf.reduce_sum(\n Y * Fmu\n - tf.exp(Fmu + Fvar / 2) * self.binsize\n - tf.math.lgamma(Y + 1)\n + Y * tf.math.log(self.binsize),\n axis=-1,\n )\n return super()._variational_expectations(Fmu, Fvar, Y)\n\n\nclass Bernoulli(ScalarLikelihood):\n def __init__(\n self, invlink: Callable[[tf.Tensor], tf.Tensor] = inv_probit, **kwargs: Any\n ) -> None:\n super().__init__(**kwargs)\n self.invlink = invlink\n\n def _scalar_log_prob(self, F: TensorType, Y: TensorType) -> tf.Tensor:\n return logdensities.bernoulli(Y, self.invlink(F))\n\n def _predict_mean_and_var(self, Fmu: TensorType, Fvar: TensorType) -> MeanAndVariance:\n if self.invlink is inv_probit:\n p = inv_probit(Fmu / tf.sqrt(1 + Fvar))\n return p, p - tf.square(p)\n else:\n # for other invlink, use quadrature\n return super()._predict_mean_and_var(Fmu, Fvar)\n\n def _predict_log_density(self, Fmu: TensorType, Fvar: TensorType, Y: TensorType) -> tf.Tensor:\n p = self.predict_mean_and_var(Fmu, Fvar)[0]\n return tf.reduce_sum(logdensities.bernoulli(Y, p), axis=-1)\n\n def _conditional_mean(self, F: TensorType) -> tf.Tensor:\n return self.invlink(F)\n\n def _conditional_variance(self, F: TensorType) -> tf.Tensor:\n p = self.conditional_mean(F)\n return p - (p ** 2)\n\n\nclass Ordinal(ScalarLikelihood):\n \"\"\"\n A likelihood for doing ordinal regression.\n\n The data are integer values from 0 to k, and the user must specify (k-1)\n 'bin edges' which define the points at which the labels switch. Let the bin\n edges be [a₀, a₁, ... aₖ₋₁], then the likelihood is\n\n p(Y=0|F) = ɸ((a₀ - F) / σ)\n p(Y=1|F) = ɸ((a₁ - F) / σ) - ɸ((a₀ - F) / σ)\n p(Y=2|F) = ɸ((a₂ - F) / σ) - ɸ((a₁ - F) / σ)\n ...\n p(Y=K|F) = 1 - ɸ((aₖ₋₁ - F) / σ)\n\n where ɸ is the cumulative density function of a Gaussian (the inverse probit\n function) and σ is a parameter to be learned. A reference is:\n\n @article{chu2005gaussian,\n title={Gaussian processes for ordinal regression},\n author={Chu, Wei and Ghahramani, Zoubin},\n journal={Journal of Machine Learning Research},\n volume={6},\n number={Jul},\n pages={1019--1041},\n year={2005}\n }\n \"\"\"\n\n def __init__(self, bin_edges: AnyNDArray, **kwargs: Any) -> None:\n \"\"\"\n bin_edges is a numpy array specifying at which function value the\n output label should switch. If the possible Y values are 0...K, then\n the size of bin_edges should be (K-1).\n \"\"\"\n super().__init__(**kwargs)\n self.bin_edges = bin_edges\n self.num_bins = bin_edges.size + 1\n self.sigma = Parameter(1.0, transform=positive())\n\n def _scalar_log_prob(self, F: TensorType, Y: TensorType) -> tf.Tensor:\n Y = to_default_int(Y)\n scaled_bins_left = tf.concat([self.bin_edges / self.sigma, np.array([np.inf])], 0)\n scaled_bins_right = tf.concat([np.array([-np.inf]), self.bin_edges / self.sigma], 0)\n selected_bins_left = tf.gather(scaled_bins_left, Y)\n selected_bins_right = tf.gather(scaled_bins_right, Y)\n\n return tf.math.log(\n inv_probit(selected_bins_left - F / self.sigma)\n - inv_probit(selected_bins_right - F / self.sigma)\n + 1e-6\n )\n\n def _make_phi(self, F: TensorType) -> tf.Tensor:\n \"\"\"\n A helper function for making predictions. Constructs a probability\n matrix where each row output the probability of the corresponding\n label, and the rows match the entries of F.\n\n Note that a matrix of F values is flattened.\n \"\"\"\n scaled_bins_left = tf.concat([self.bin_edges / self.sigma, np.array([np.inf])], 0)\n scaled_bins_right = tf.concat([np.array([-np.inf]), self.bin_edges / self.sigma], 0)\n return inv_probit(scaled_bins_left - tf.reshape(F, (-1, 1)) / self.sigma) - inv_probit(\n scaled_bins_right - tf.reshape(F, (-1, 1)) / self.sigma\n )\n\n def _conditional_mean(self, F: TensorType) -> tf.Tensor:\n phi = self._make_phi(F)\n Ys = tf.reshape(np.arange(self.num_bins, dtype=default_float()), (-1, 1))\n return tf.reshape(tf.linalg.matmul(phi, Ys), tf.shape(F))\n\n def _conditional_variance(self, F: TensorType) -> tf.Tensor:\n phi = self._make_phi(F)\n Ys = tf.reshape(np.arange(self.num_bins, dtype=default_float()), (-1, 1))\n E_y = phi @ Ys\n E_y2 = phi @ (Ys ** 2)\n return tf.reshape(E_y2 - E_y ** 2, tf.shape(F))\n", "# Copyright 2018 the GPflow authors.\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\nfrom typing import cast\n\nimport numpy as np\nimport pytest\nimport tensorflow as tf\nfrom numpy.testing import assert_allclose\n\nimport gpflow.quadrature as quadrature\nfrom gpflow.base import AnyNDArray, TensorType\n\n\[email protected](\"mu\", [np.array([1.0, 1.3])])\[email protected](\"var\", [np.array([3.0, 3.5])])\ndef test_diagquad_1d(mu: TensorType, var: TensorType) -> None:\n num_gauss_hermite_points = 25\n quad = quadrature.ndiagquad([lambda *X: tf.exp(X[0])], num_gauss_hermite_points, [mu], [var])\n expected = np.exp(mu + var / 2)\n assert_allclose(quad[0], expected)\n\n\[email protected](\"mu1\", [np.array([1.0, 1.3])])\[email protected](\"var1\", [np.array([3.0, 3.5])])\[email protected](\"mu2\", [np.array([-2.0, 0.3])])\[email protected](\"var2\", [np.array([4.0, 4.2])])\ndef test_diagquad_2d(mu1: TensorType, var1: TensorType, mu2: TensorType, var2: TensorType) -> None:\n alpha = 2.5\n # using logspace=True we can reduce this, see test_diagquad_logspace\n num_gauss_hermite_points = 35\n quad = quadrature.ndiagquad(\n lambda *X: tf.exp(X[0] + alpha * X[1]),\n num_gauss_hermite_points,\n [mu1, mu2],\n [var1, var2],\n )\n expected = np.exp(mu1 + var1 / 2 + alpha * mu2 + alpha ** 2 * var2 / 2)\n assert_allclose(quad, expected)\n\n\[email protected](\"mu1\", [np.array([1.0, 1.3])])\[email protected](\"var1\", [np.array([3.0, 3.5])])\[email protected](\"mu2\", [np.array([-2.0, 0.3])])\[email protected](\"var2\", [np.array([4.0, 4.2])])\ndef test_diagquad_logspace(\n mu1: TensorType, var1: TensorType, mu2: TensorType, var2: TensorType\n) -> None:\n alpha = 2.5\n num_gauss_hermite_points = 25\n quad = quadrature.ndiagquad(\n lambda *X: (X[0] + alpha * X[1]),\n num_gauss_hermite_points,\n [mu1, mu2],\n [var1, var2],\n logspace=True,\n )\n expected = mu1 + var1 / 2 + alpha * mu2 + alpha ** 2 * var2 / 2\n assert_allclose(quad, expected)\n\n\[email protected](\"mu1\", [np.array([1.0, 1.3])])\[email protected](\"var1\", [np.array([3.0, 3.5])])\ndef test_diagquad_with_kwarg(mu1: TensorType, var1: TensorType) -> None:\n alpha = np.array([2.5, -1.3])\n num_gauss_hermite_points = 25\n quad = quadrature.ndiagquad(\n lambda X, Y: tf.exp(X * Y), num_gauss_hermite_points, mu1, var1, Y=alpha\n )\n expected = np.exp(alpha * mu1 + alpha ** 2 * var1 / 2)\n assert_allclose(quad, expected)\n\n\ndef test_ndiagquad_does_not_throw_error() -> None:\n \"\"\"\n Check that the autograph=False for quadrature.ndiagquad does not throw an error.\n Regression test for https://github.com/GPflow/GPflow/issues/1547.\n \"\"\"\n\n @tf.function(autograph=False)\n def func_ndiagquad_autograph_false() -> tf.Tensor:\n mu = np.array([1.0, 1.3])\n var = np.array([3.0, 3.5])\n num_gauss_hermite_points = 25\n return quadrature.ndiagquad(\n [lambda *X: tf.exp(X[0])], num_gauss_hermite_points, [mu], [var]\n )\n\n func_ndiagquad_autograph_false()\n\n\ndef test_quadrature_autograph() -> None:\n \"\"\"\n Check that the return value is equal with and without Autograph\n Regression test for https://github.com/GPflow/GPflow/issues/1547.\n \"\"\"\n\n def compute(autograph: bool) -> AnyNDArray:\n @tf.function(autograph=autograph)\n def func() -> tf.Tensor:\n mu = np.array([1.0, 1.3])\n var = np.array([3.0, 3.5])\n num_gauss_hermite_points = 25\n return quadrature.ndiagquad(\n [lambda *X: tf.exp(X[0])], num_gauss_hermite_points, [mu], [var]\n )\n\n (result,) = func()\n return cast(AnyNDArray, result.numpy())\n\n np.testing.assert_equal(\n compute(autograph=True),\n compute(autograph=False),\n )\n" ]
[ [ "tensorflow.reduce_sum", "tensorflow.linalg.cholesky" ], [ "tensorflow.linalg.diag_part", "tensorflow.transpose", "tensorflow.shape", "tensorflow.linalg.triangular_solve", "tensorflow.reduce_sum", "tensorflow.ones", "tensorflow.linalg.matmul", "tensorflow.math.log", "numpy.all", "numpy.atleast_1d", "tensorflow.random.shuffle", "tensorflow.expand_dims", "tensorflow.square", "tensorflow.linalg.cholesky", "tensorflow.size" ], [ "tensorflow.shape", "tensorflow.reshape", "tensorflow.linalg.matmul", "tensorflow.exp", "tensorflow.math.log", "tensorflow.gather", "tensorflow.square", "tensorflow.sqrt", "numpy.array", "tensorflow.math.lgamma" ], [ "tensorflow.exp", "tensorflow.function", "numpy.testing.assert_allclose", "numpy.exp", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "2.7", "2.6", "2.4", "2.3", "2.9", "2.5", "2.2", "2.10" ] } ]
gkuwanto/RBL_SK5003
[ "7da3b95afeca2aa3413993279fe13d6bb71cd5db" ]
[ "main.py" ]
[ "import argparse\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom lib.file_parser import read_csv\n\n# Set random seed\nnp.random.seed(42)\n\n# Menambahkan argumen dalam cli\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-obj\", \"--objective\",\n help=\"Specify objective function of the optimization. \"\n \"Only MSE and MAE is available\",\n default='MSE')\nparser.add_argument(\"-n_stop\", \"--n_stop\",\n help=\"Specify number of epoch with no improvement \"\n \"as stopping criteria\",\n default=5)\nargs = parser.parse_args()\n\n# Memastikan Nilai input argument\nif (args.objective) not in [\"MSE\", \"MAE\"]:\n raise ValueError(\n f\"Objective Function {args.objective} is not implemented yet\")\n\n# Membaca Data dari file\ndata_train = read_csv('data/train.csv')\ndata_test = read_csv('data/test.csv')\n\nheaders = data_train.keys()\n\n# Mengubah data dari string menjadi float\nfor col in headers:\n if col in ['date', 'id']:\n continue\n data_train[col] = [float(i) for i in data_train[col]]\n if col != 'price':\n data_test[col] = [float(i) for i in data_test[col]]\n\n\ndef onehotencode(data, col):\n key = np.unique(np.array(data[col]))\n inspect = data[col]\n value = [[0 for i in range(len(inspect))] for i in range(len(key))]\n mydict = dict(zip(key, value))\n for i in key:\n for j in range(len(inspect)):\n if inspect[j] == i:\n mydict[i][j] = 1\n del data[col]\n return {**data, **mydict}, key\n\n\ndata_train, key = onehotencode(data_train, 'zipcode')\ndata_test, _ = onehotencode(data_test, 'zipcode')\nheaders = list(headers) + list(key)\n\n# Membaca Data menjadi format numpy\nX_train = np.array([data_train[col] for col in headers\n if col not in ['date', 'id', 'price', 'zipcode']]).T\ny_train = np.array(data_train['price'])\n\n# Preprocessing X_train\nX_mean = np.mean(X_train, axis=0)\nX_std = np.std(X_train, axis=0)\nX_train = (X_train - X_mean)/X_std\nX_train = np.concatenate([X_train, np.ones(X_train[:, 0:1].shape)], axis=1)\n\n# Preprocessing y_train\ny_mean = np.mean(y_train)\ny_std = np.std(y_train)\ny_train = (y_train - y_mean)/y_std\n\n\n# Inisialisasi Parameter Model\ntheta = np.random.normal(size=X_train[0, :].shape)\n\n# Penentuan Loss dan Gradient tergantung input\nif args.objective == 'MSE':\n def loss(x, y, theta): return 0.5 * (np.dot(theta, x) - y)**2\n def gradient(x, y, theta): return (np.dot(theta, x) - y) * x\nelif args.objective == 'MAE':\n def loss(x, y, theta): return (np.abs(np.dot(theta, x)-y))\n def gradient(x, y, theta): return np.sign(np.dot(theta, x)-y) * x\n\n\n# Memulai Proses SGD\nn_epoch = 0\nstopping_criteria = False\neta = 0.00005\nloss_epoch = []\nwhile not stopping_criteria:\n epoch = n_epoch\n total_loss = 0\n total_sample = len(y_train)\n random_seq = np.random.permutation(np.arange(total_sample))\n for i in random_seq:\n total_loss += loss(X_train[i], y_train[i], theta)\n grad = gradient(X_train[i], y_train[i], theta)\n theta = theta - (eta*grad)\n loss_epoch.append(total_loss/total_sample)\n print(f\"Epoch: {epoch} \\t Loss: {total_loss/total_sample}\")\n if n_epoch > args.n_stop:\n is_lower_count = 0\n for i in range(-1, -1*args.n_stop, -1):\n if (loss_epoch[i] - loss_epoch[i-1]) < -1e-5:\n is_lower_count += 1\n stopping_criteria = (is_lower_count == 0)\n n_epoch += 1\n\n\n# Melakukan Preprocessing pada Dataset Test\nX_test = np.array([data_test[col] for col in headers\n if col not in ['date', 'id', 'price', 'zipcode']]).T\nX_test = (X_test - X_mean)/X_std\nX_test = np.concatenate([X_test, np.ones(X_test[:, 0:1].shape)], axis=1)\n\n# Menghitung Prediksi\ny_pred = np.dot(theta, X_test.T)\n# Melakukan postprocessing pada hasil prediksi\ny_pred = y_pred * y_std + y_mean\n\n# Menulis Hasil Prediksi pada suatu file\nwith open('data/prediction.csv', 'w+') as f:\n f.write('id,price\\n')\n for id, price in zip(data_test['id'], y_pred):\n f.write(f'{id},{price}\\n')\n\n# TODO: Evaluate Result\n# Read Prediction\nprediction = read_csv('data/prediction.csv')\nprice_pred = np.array(prediction['price']).astype(float)\n\n# Read True Label\ntrue_label = read_csv('data/test_true_price.csv')\nprice_true = np.array(true_label['price']).astype(float)\n\n# Print MSE / MAE\nMSE_result = np.mean((price_true - price_pred) ** 2)\nMAE_result = np.mean(np.abs(price_true - price_pred))\nprint(\"MSE :\", MSE_result)\nprint(\"MAE :\", MAE_result)\n\nX_headers = [col for col in headers\n if col not in ['date', 'id', 'price', 'zipcode']]\n\ny = y_train\nfor i in range(len(X_headers)):\n x = []\n x_mean = []\n for j in range(len(X_train)):\n input_mean = np.mean(X_train, axis=0)\n input_mean[i] = X_train[j][i]\n\n x.append(X_train[j][i])\n x_mean.append(input_mean)\n y_pred_mean = np.dot(theta, np.array(x_mean).T)\n minimum = min(y_pred_mean)\n maximum = max(y_pred_mean)\n\n plt.figure()\n plt.scatter(x, y)\n plt.ylim([minimum-1, maximum+5])\n plt.plot(x, y_pred_mean, color='r', linewidth=1.5)\n plt.xlabel(X_headers[i])\n plt.ylabel('price')\n plt.savefig(str(X_headers[i]) + ' to price.png')\n plt.close()\n\nplt.figure()\nplt.scatter(range(len(loss_epoch)), loss_epoch)\nplt.xticks(range(len(loss_epoch)))\nplt.xlabel('Epoch')\nplt.ylabel('Loss')\nplt.savefig('loss to epoch.png')\n" ]
[ [ "numpy.dot", "numpy.abs", "numpy.random.seed", "matplotlib.pyplot.scatter", "matplotlib.pyplot.ylim", "numpy.arange", "matplotlib.pyplot.savefig", "numpy.ones", "matplotlib.pyplot.plot", "numpy.std", "numpy.random.normal", "numpy.mean", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.close", "matplotlib.pyplot.xlabel", "numpy.array", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
kuonangzhe/gluon-cv
[ "f7d74019210dd0f22cb4543f061339533301c487" ]
[ "gluoncv/model_zoo/yolo/yolo3.py" ]
[ "\"\"\"You Only Look Once Object Detection v3\"\"\"\n# pylint: disable=arguments-differ\nfrom __future__ import absolute_import\nfrom __future__ import division\n\nimport os\nimport numpy as np\nimport mxnet as mx\nfrom mxnet import gluon\nfrom mxnet import autograd\nfrom mxnet.gluon import nn\nfrom .darknet import _conv2d, darknet53\nfrom .yolo_target import YOLOV3TargetMerger\nfrom ...loss import YOLOV3Loss\n\n__all__ = ['YOLOV3', 'get_yolov3',\n 'yolo3_darknet53_voc', 'yolo3_darknet53_coco', 'yolo3_darknet53_custom']\n\ndef _upsample(x, stride=2):\n \"\"\"Simple upsampling layer by stack pixel alongside horizontal and vertical directions.\n\n Parameters\n ----------\n x : mxnet.nd.NDArray or mxnet.symbol.Symbol\n The input array.\n stride : int, default is 2\n Upsampling stride\n\n \"\"\"\n return x.repeat(axis=-1, repeats=stride).repeat(axis=-2, repeats=stride)\n\n\nclass YOLOOutputV3(gluon.HybridBlock):\n \"\"\"YOLO output layer V3.\n\n Parameters\n ----------\n index : int\n Index of the yolo output layer, to avoid naming confliction only.\n num_class : int\n Number of foreground objects.\n anchors : iterable\n The anchor setting. Reference: https://arxiv.org/pdf/1804.02767.pdf.\n stride : int\n Stride of feature map.\n alloc_size : tuple of int, default is (128, 128)\n For advanced users. Define `alloc_size` to generate large enough anchor\n maps, which will later saved in parameters. During inference, we support arbitrary\n input image by cropping corresponding area of the anchor map. This allow us\n to export to symbol so we can run it in c++, Scalar, etc.\n\n \"\"\"\n def __init__(self, index, num_class, anchors, stride,\n alloc_size=(128, 128), **kwargs):\n super(YOLOOutputV3, self).__init__(**kwargs)\n anchors = np.array(anchors).astype('float32')\n self._classes = num_class\n self._num_pred = 1 + 4 + num_class # 1 objness + 4 box + num_class\n self._num_anchors = anchors.size // 2\n self._stride = stride\n with self.name_scope():\n all_pred = self._num_pred * self._num_anchors\n self.prediction = nn.Conv2D(all_pred, kernel_size=1, padding=0, strides=1)\n # anchors will be multiplied to predictions\n anchors = anchors.reshape(1, 1, -1, 2)\n self.anchors = self.params.get_constant('anchor_%d'%(index), anchors)\n # offsets will be added to predictions\n grid_x = np.arange(alloc_size[1])\n grid_y = np.arange(alloc_size[0])\n grid_x, grid_y = np.meshgrid(grid_x, grid_y)\n # stack to (n, n, 2)\n offsets = np.concatenate((grid_x[:, :, np.newaxis], grid_y[:, :, np.newaxis]), axis=-1)\n # expand dims to (1, 1, n, n, 2) so it's easier for broadcasting\n offsets = np.expand_dims(np.expand_dims(offsets, axis=0), axis=0)\n self.offsets = self.params.get_constant('offset_%d'%(index), offsets)\n\n def reset_class(self, classes):\n \"\"\"Reset class prediction.\n\n Parameters\n ----------\n classes : type\n Description of parameter `classes`.\n\n Returns\n -------\n type\n Description of returned object.\n\n \"\"\"\n self._clear_cached_op()\n self._classes = len(classes)\n self._num_pred = 1 + 4 + len(classes)\n all_pred = self._num_pred * self._num_anchors\n # TODO(zhreshold): reuse box preds, objectness\n self.prediction = nn.Conv2D(\n all_pred, kernel_size=1, padding=0, strides=1, prefix=self.prediction.prefix)\n\n\n def hybrid_forward(self, F, x, anchors, offsets):\n \"\"\"Hybrid Foward of YOLOV3Output layer.\n\n Parameters\n ----------\n F : mxnet.nd or mxnet.sym\n `F` is mxnet.sym if hybridized or mxnet.nd if not.\n x : mxnet.nd.NDArray\n Input feature map.\n anchors : mxnet.nd.NDArray\n Anchors loaded from self, no need to supply.\n offsets : mxnet.nd.NDArray\n Offsets loaded from self, no need to supply.\n\n Returns\n -------\n (tuple of) mxnet.nd.NDArray\n During training, return (bbox, raw_box_centers, raw_box_scales, objness,\n class_pred, anchors, offsets).\n During inference, return detections.\n\n \"\"\"\n # prediction flat to (batch, pred per pixel, height * width)\n pred = self.prediction(x).reshape((0, self._num_anchors * self._num_pred, -1))\n # transpose to (batch, height * width, num_anchor, num_pred)\n pred = pred.transpose(axes=(0, 2, 1)).reshape((0, -1, self._num_anchors, self._num_pred))\n # components\n raw_box_centers = pred.slice_axis(axis=-1, begin=0, end=2)\n raw_box_scales = pred.slice_axis(axis=-1, begin=2, end=4)\n objness = pred.slice_axis(axis=-1, begin=4, end=5)\n class_pred = pred.slice_axis(axis=-1, begin=5, end=None)\n\n # valid offsets, (1, 1, height, width, 2)\n offsets = F.slice_like(offsets, x * 0, axes=(2, 3))\n # reshape to (1, height*width, 1, 2)\n offsets = offsets.reshape((1, -1, 1, 2))\n\n box_centers = F.broadcast_add(F.sigmoid(raw_box_centers), offsets) * self._stride\n box_scales = F.broadcast_mul(F.exp(raw_box_scales), anchors)\n confidence = F.sigmoid(objness)\n class_score = F.broadcast_mul(F.sigmoid(class_pred), confidence)\n wh = box_scales / 2.0\n bbox = F.concat(box_centers - wh, box_centers + wh, dim=-1)\n\n if autograd.is_training():\n # during training, we don't need to convert whole bunch of info to detection results\n return (bbox.reshape((0, -1, 4)), raw_box_centers, raw_box_scales,\n objness, class_pred, anchors, offsets)\n\n # prediction per class\n bboxes = F.tile(bbox, reps=(self._classes, 1, 1, 1, 1))\n scores = F.transpose(class_score, axes=(3, 0, 1, 2)).expand_dims(axis=-1)\n ids = F.broadcast_add(scores * 0, F.arange(0, self._classes).reshape((0, 1, 1, 1, 1)))\n detections = F.concat(ids, scores, bboxes, dim=-1)\n # reshape to (B, xx, 6)\n detections = F.reshape(detections.transpose(axes=(1, 0, 2, 3, 4)), (0, -1, 6))\n return detections\n\n\nclass YOLODetectionBlockV3(gluon.HybridBlock):\n \"\"\"YOLO V3 Detection Block which does the following:\n\n - add a few conv layers\n - return the output\n - have a branch that do yolo detection.\n\n Parameters\n ----------\n channel : int\n Number of channels for 1x1 conv. 3x3 Conv will have 2*channel.\n num_sync_bn_devices : int, default is -1\n Number of devices for training. If `num_sync_bn_devices < 2`, SyncBatchNorm is disabled.\n\n \"\"\"\n def __init__(self, channel, num_sync_bn_devices=-1, **kwargs):\n super(YOLODetectionBlockV3, self).__init__(**kwargs)\n assert channel % 2 == 0, \"channel {} cannot be divided by 2\".format(channel)\n with self.name_scope():\n self.body = nn.HybridSequential(prefix='')\n for _ in range(2):\n # 1x1 reduce\n self.body.add(_conv2d(channel, 1, 0, 1, num_sync_bn_devices))\n # 3x3 expand\n self.body.add(_conv2d(channel * 2, 3, 1, 1, num_sync_bn_devices))\n self.body.add(_conv2d(channel, 1, 0, 1, num_sync_bn_devices))\n self.tip = _conv2d(channel * 2, 3, 1, 1, num_sync_bn_devices)\n\n # pylint: disable=unused-argument\n def hybrid_forward(self, F, x):\n route = self.body(x)\n tip = self.tip(route)\n return route, tip\n\n\nclass YOLOV3(gluon.HybridBlock):\n \"\"\"YOLO V3 detection network.\n Reference: https://arxiv.org/pdf/1804.02767.pdf.\n\n Parameters\n ----------\n stages : mxnet.gluon.HybridBlock\n Staged feature extraction blocks.\n For example, 3 stages and 3 YOLO output layers are used original paper.\n channels : iterable\n Number of conv channels for each appended stage.\n `len(channels)` should match `len(stages)`.\n num_class : int\n Number of foreground objects.\n anchors : iterable\n The anchor setting. `len(anchors)` should match `len(stages)`.\n strides : iterable\n Strides of feature map. `len(strides)` should match `len(stages)`.\n alloc_size : tuple of int, default is (128, 128)\n For advanced users. Define `alloc_size` to generate large enough anchor\n maps, which will later saved in parameters. During inference, we support arbitrary\n input image by cropping corresponding area of the anchor map. This allow us\n to export to symbol so we can run it in c++, Scalar, etc.\n nms_thresh : float, default is 0.45.\n Non-maximum suppression threshold. You can speficy < 0 or > 1 to disable NMS.\n nms_topk : int, default is 400\n Apply NMS to top k detection results, use -1 to disable so that every Detection\n result is used in NMS.\n post_nms : int, default is 100\n Only return top `post_nms` detection results, the rest is discarded. The number is\n based on COCO dataset which has maximum 100 objects per image. You can adjust this\n number if expecting more objects. You can use -1 to return all detections.\n pos_iou_thresh : float, default is 1.0\n IOU threshold for true anchors that match real objects.\n 'pos_iou_thresh < 1' is not implemented.\n ignore_iou_thresh : float\n Anchors that has IOU in `range(ignore_iou_thresh, pos_iou_thresh)` don't get\n penalized of objectness score.\n num_sync_bn_devices : int, default is -1\n Number of devices for training. If `num_sync_bn_devices < 2`, SyncBatchNorm is disabled.\n\n \"\"\"\n def __init__(self, stages, channels, anchors, strides, classes, alloc_size=(128, 128),\n nms_thresh=0.45, nms_topk=400, post_nms=100, pos_iou_thresh=1.0,\n ignore_iou_thresh=0.7, num_sync_bn_devices=-1, **kwargs):\n super(YOLOV3, self).__init__(**kwargs)\n self._classes = classes\n self.nms_thresh = nms_thresh\n self.nms_topk = nms_topk\n self.post_nms = post_nms\n self._pos_iou_thresh = pos_iou_thresh\n self._ignore_iou_thresh = ignore_iou_thresh\n if pos_iou_thresh >= 1:\n self._target_generator = YOLOV3TargetMerger(len(classes), ignore_iou_thresh)\n else:\n raise NotImplementedError(\n \"pos_iou_thresh({}) < 1.0 is not implemented!\".format(pos_iou_thresh))\n self._loss = YOLOV3Loss()\n with self.name_scope():\n self.stages = nn.HybridSequential()\n self.transitions = nn.HybridSequential()\n self.yolo_blocks = nn.HybridSequential()\n self.yolo_outputs = nn.HybridSequential()\n # note that anchors and strides should be used in reverse order\n for i, stage, channel, anchor, stride in zip(\n range(len(stages)), stages, channels, anchors[::-1], strides[::-1]):\n self.stages.add(stage)\n block = YOLODetectionBlockV3(channel, num_sync_bn_devices)\n self.yolo_blocks.add(block)\n output = YOLOOutputV3(i, len(classes), anchor, stride, alloc_size=alloc_size)\n self.yolo_outputs.add(output)\n if i > 0:\n self.transitions.add(_conv2d(channel, 1, 0, 1, num_sync_bn_devices))\n\n @property\n def num_class(self):\n \"\"\"Number of (non-background) categories.\n\n Returns\n -------\n int\n Number of (non-background) categories.\n\n \"\"\"\n return self._num_class\n\n @property\n def classes(self):\n \"\"\"Return names of (non-background) categories.\n\n Returns\n -------\n iterable of str\n Names of (non-background) categories.\n\n \"\"\"\n return self._classes\n\n def hybrid_forward(self, F, x, *args):\n \"\"\"YOLOV3 network hybrid forward.\n\n Parameters\n ----------\n F : mxnet.nd or mxnet.sym\n `F` is mxnet.sym if hybridized or mxnet.nd if not.\n x : mxnet.nd.NDArray\n Input data.\n *args : optional, mxnet.nd.NDArray\n During training, extra inputs are required:\n (gt_boxes, obj_t, centers_t, scales_t, weights_t, clas_t)\n These are generated by YOLOV3PrefetchTargetGenerator in dataloader transform function.\n\n Returns\n -------\n (tuple of) mxnet.nd.NDArray\n During inference, return detections in shape (B, N, 6)\n with format (cid, score, xmin, ymin, xmax, ymax)\n During training, return losses only: (obj_loss, center_loss, scale_loss, cls_loss).\n\n\n \"\"\"\n all_box_centers = []\n all_box_scales = []\n all_objectness = []\n all_class_pred = []\n all_anchors = []\n all_offsets = []\n all_feat_maps = []\n all_detections = []\n routes = []\n for stage, block, output in zip(self.stages, self.yolo_blocks, self.yolo_outputs):\n x = stage(x)\n routes.append(x)\n\n # the YOLO output layers are used in reverse order, i.e., from very deep layers to shallow\n for i, block, output in zip(range(len(routes)), self.yolo_blocks, self.yolo_outputs):\n x, tip = block(x)\n if autograd.is_training():\n dets, box_centers, box_scales, objness, class_pred, anchors, offsets = output(tip)\n all_box_centers.append(box_centers.reshape((0, -3, -1)))\n all_box_scales.append(box_scales.reshape((0, -3, -1)))\n all_objectness.append(objness.reshape((0, -3, -1)))\n all_class_pred.append(class_pred.reshape((0, -3, -1)))\n all_anchors.append(anchors)\n all_offsets.append(offsets)\n # here we use fake featmap to reduce memory consuption, only shape[2, 3] is used\n fake_featmap = F.zeros_like(tip.slice_axis(\n axis=0, begin=0, end=1).slice_axis(axis=1, begin=0, end=1))\n all_feat_maps.append(fake_featmap)\n else:\n dets = output(tip)\n all_detections.append(dets)\n if i >= len(routes) - 1:\n break\n # add transition layers\n x = self.transitions[i](x)\n # upsample feature map reverse to shallow layers\n upsample = _upsample(x, stride=2)\n route_now = routes[::-1][i + 1]\n x = F.concat(F.slice_like(upsample, route_now * 0, axes=(2, 3)), route_now, dim=1)\n\n if autograd.is_training():\n # during training, the network behaves differently since we don't need detection results\n if autograd.is_recording():\n # generate losses and return them directly\n box_preds = F.concat(*all_detections, dim=1)\n all_preds = [F.concat(*p, dim=1) for p in [\n all_objectness, all_box_centers, all_box_scales, all_class_pred]]\n all_targets = self._target_generator(box_preds, *args)\n return self._loss(*(all_preds + all_targets))\n\n # return raw predictions, this is only used in DataLoader transform function.\n return (F.concat(*all_detections, dim=1), all_anchors, all_offsets, all_feat_maps,\n F.concat(*all_box_centers, dim=1), F.concat(*all_box_scales, dim=1),\n F.concat(*all_objectness, dim=1), F.concat(*all_class_pred, dim=1))\n\n # concat all detection results from different stages\n result = F.concat(*all_detections, dim=1)\n # apply nms per class\n if self.nms_thresh > 0 and self.nms_thresh < 1:\n result = F.contrib.box_nms(\n result, overlap_thresh=self.nms_thresh, valid_thresh=0.01,\n topk=self.nms_topk, id_index=0, score_index=1, coord_start=2, force_suppress=False)\n if self.post_nms > 0:\n result = result.slice_axis(axis=1, begin=0, end=self.post_nms)\n ids = result.slice_axis(axis=-1, begin=0, end=1)\n scores = result.slice_axis(axis=-1, begin=1, end=2)\n bboxes = result.slice_axis(axis=-1, begin=2, end=None)\n return ids, scores, bboxes\n\n def set_nms(self, nms_thresh=0.45, nms_topk=400, post_nms=100):\n \"\"\"Set non-maximum suppression parameters.\n\n Parameters\n ----------\n nms_thresh : float, default is 0.45.\n Non-maximum suppression threshold. You can speficy < 0 or > 1 to disable NMS.\n nms_topk : int, default is 400\n Apply NMS to top k detection results, use -1 to disable so that every Detection\n result is used in NMS.\n post_nms : int, default is 100\n Only return top `post_nms` detection results, the rest is discarded. The number is\n based on COCO dataset which has maximum 100 objects per image. You can adjust this\n number if expecting more objects. You can use -1 to return all detections.\n\n Returns\n -------\n None\n\n \"\"\"\n self._clear_cached_op()\n self.nms_thresh = nms_thresh\n self.nms_topk = nms_topk\n self.post_nms = post_nms\n\n def reset_class(self, classes):\n \"\"\"Reset class categories and class predictors.\n\n Parameters\n ----------\n classes : iterable of str\n The new categories. ['apple', 'orange'] for example.\n\n \"\"\"\n self._clear_cached_op()\n self._classes = classes\n if self._pos_iou_thresh >= 1:\n self._target_generator = YOLOV3TargetMerger(len(classes), self._ignore_iou_thresh)\n for outputs in self.yolo_outputs:\n outputs.reset_class(classes)\n\ndef get_yolov3(name, stages, filters, anchors, strides, classes,\n dataset, pretrained=False, ctx=mx.cpu(),\n root=os.path.join('~', '.mxnet', 'models'), **kwargs):\n \"\"\"Get YOLOV3 models.\n\n Parameters\n ----------\n name : str or None\n Model name, if `None` is used, you must specify `features` to be a `HybridBlock`.\n stages : iterable of str or `HybridBlock`\n List of network internal output names, in order to specify which layers are\n used for predicting bbox values.\n If `name` is `None`, `features` must be a `HybridBlock` which generate mutliple\n outputs for prediction.\n filters : iterable of float or None\n List of convolution layer channels which is going to be appended to the base\n network feature extractor. If `name` is `None`, this is ignored.\n sizes : iterable fo float\n Sizes of anchor boxes, this should be a list of floats, in incremental order.\n The length of `sizes` must be len(layers) + 1. For example, a two stage SSD\n model can have ``sizes = [30, 60, 90]``, and it converts to `[30, 60]` and\n `[60, 90]` for the two stages, respectively. For more details, please refer\n to original paper.\n ratios : iterable of list\n Aspect ratios of anchors in each output layer. Its length must be equals\n to the number of SSD output layers.\n steps : list of int\n Step size of anchor boxes in each output layer.\n classes : iterable of str\n Names of categories.\n dataset : str\n Name of dataset. This is used to identify model name because models trained on\n differnet datasets are going to be very different.\n pretrained : bool or str\n Boolean value controls whether to load the default pretrained weights for model.\n String value represents the hashtag for a certain version of pretrained weights.\n pretrained_base : bool or str, optional, default is True\n Load pretrained base network, the extra layers are randomized. Note that\n if pretrained is `Ture`, this has no effect.\n ctx : mxnet.Context\n Context such as mx.cpu(), mx.gpu(0).\n root : str\n Model weights storing path.\n\n Returns\n -------\n HybridBlock\n A YOLOV3 detection network.\n \"\"\"\n net = YOLOV3(stages, filters, anchors, strides, classes=classes, **kwargs)\n if pretrained:\n from ..model_store import get_model_file\n full_name = '_'.join(('yolo3', name, dataset))\n net.load_params(get_model_file(full_name, tag=pretrained, root=root), ctx=ctx)\n return net\n\ndef yolo3_darknet53_voc(pretrained_base=True, pretrained=False, num_sync_bn_devices=-1, **kwargs):\n \"\"\"YOLO3 multi-scale with darknet53 base network on VOC dataset.\n\n Parameters\n ----------\n pretrained_base : bool or str\n Boolean value controls whether to load the default pretrained weights for model.\n String value represents the hashtag for a certain version of pretrained weights.\n pretrained : bool or str\n Boolean value controls whether to load the default pretrained weights for model.\n String value represents the hashtag for a certain version of pretrained weights.\n num_sync_bn_devices : int\n Number of devices for training. If `num_sync_bn_devices < 2`, SyncBatchNorm is disabled.\n\n Returns\n -------\n mxnet.gluon.HybridBlock\n Fully hybrid yolo3 network.\n\n \"\"\"\n from ...data import VOCDetection\n pretrained_base = False if pretrained else pretrained_base\n base_net = darknet53(pretrained=pretrained_base, num_sync_bn_devices=num_sync_bn_devices)\n stages = [base_net.features[:15], base_net.features[15:24], base_net.features[24:]]\n anchors = [[10, 13, 16, 30, 33, 23], [30, 61, 62, 45, 59, 119], [116, 90, 156, 198, 373, 326]]\n strides = [8, 16, 32]\n classes = VOCDetection.CLASSES\n return get_yolov3(\n 'darknet53', stages, [512, 256, 128], anchors, strides, classes, 'voc',\n pretrained=pretrained, num_sync_bn_devices=num_sync_bn_devices, **kwargs)\n\ndef yolo3_darknet53_coco(pretrained_base=True, pretrained=False, num_sync_bn_devices=-1, **kwargs):\n \"\"\"YOLO3 multi-scale with darknet53 base network on COCO dataset.\n\n Parameters\n ----------\n pretrained_base : boolean\n Whether fetch and load pretrained weights for base network.\n pretrained : bool or str\n Boolean value controls whether to load the default pretrained weights for model.\n String value represents the hashtag for a certain version of pretrained weights.\n num_sync_bn_devices : int, default is -1\n Number of devices for training. If `num_sync_bn_devices < 2`, SyncBatchNorm is disabled.\n\n Returns\n -------\n mxnet.gluon.HybridBlock\n Fully hybrid yolo3 network.\n \"\"\"\n from ...data import COCODetection\n pretrained_base = False if pretrained else pretrained_base\n base_net = darknet53(pretrained=pretrained_base, num_sync_bn_devices=num_sync_bn_devices)\n stages = [base_net.features[:15], base_net.features[15:24], base_net.features[24:]]\n anchors = [[10, 13, 16, 30, 33, 23], [30, 61, 62, 45, 59, 119], [116, 90, 156, 198, 373, 326]]\n strides = [8, 16, 32]\n classes = COCODetection.CLASSES\n return get_yolov3(\n 'darknet53', stages, [512, 256, 128], anchors, strides, classes, 'coco',\n pretrained=pretrained, num_sync_bn_devices=num_sync_bn_devices, **kwargs)\n\ndef yolo3_darknet53_custom(classes, transfer=None, pretrained_base=True, pretrained=False,\n num_sync_bn_devices=-1, **kwargs):\n \"\"\"YOLO3 multi-scale with darknet53 base network on custom dataset.\n\n Parameters\n ----------\n classes : iterable of str\n Names of custom foreground classes. `len(classes)` is the number of foreground classes.\n transfer : str or None\n If not `None`, will try to reuse pre-trained weights from SSD networks trained on other\n datasets.\n pretrained_base : boolean\n Whether fetch and load pretrained weights for base network.\n num_sync_bn_devices : int, default is -1\n Number of devices for training. If `num_sync_bn_devices < 2`, SyncBatchNorm is disabled.\n\n Returns\n -------\n mxnet.gluon.HybridBlock\n Fully hybrid yolo3 network.\n \"\"\"\n if transfer is None:\n base_net = darknet53(pretrained=pretrained_base, num_sync_bn_devices=num_sync_bn_devices)\n stages = [base_net.features[:15], base_net.features[15:24], base_net.features[24:]]\n anchors = [\n [10, 13, 16, 30, 33, 23],\n [30, 61, 62, 45, 59, 119],\n [116, 90, 156, 198, 373, 326]]\n strides = [8, 16, 32]\n net = get_yolov3(\n 'darknet53', stages, [512, 256, 128], anchors, strides, classes, 'coco',\n pretrained=pretrained, num_sync_bn_devices=num_sync_bn_devices, **kwargs)\n else:\n from ...model_zoo import get_model\n net = get_model('yolo3_darknet53_' + str(transfer), pretrained=True, **kwargs)\n net.reset_class(classes)\n return net\n" ]
[ [ "numpy.expand_dims", "numpy.meshgrid", "numpy.arange", "numpy.concatenate", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
almarklein/pirt
[ "b43a57aad89ad2638a65e58079153567a49a43f2" ]
[ "pirt/gaussfun.py" ]
[ "\"\"\"\nThe gaussfun module implements functions for diffusion and Gaussian\nderivatives for data of any dimension.\n\nContents of this module:\n\n * gaussiankernel - Create a Gaussian kernel\n * gaussiankernel2 - Create a 2D Gaussian kernel\n * diffusionkernel - Create a discrete analog to the Gaussian kernel\n * gfilter - Filter data with Gaussian (derivative) kernels\n * diffuse - Filter data with true discrete diffusion kernels\n * gfilter2 - Filter data by specifying sigma in world coordinates\n * diffuse2 - Diffuse data by specifying sigma in world coordinates\n\n\"\"\"\n\n# SHORTED VERSION WITHOUT PYRAMID STUFF\n\nimport numpy as np\nimport scipy.ndimage\n\nfrom . import Aarray\n\n\n## Kernels\n\ndef _gaussiankernel(sigma, order, t):\n \"\"\" _gaussiankernel(sigma, order, t)\n Calculate a Gaussian kernel of the given sigma and with the given\n order, using the given t-values. \n \"\"\"\n \n # if sigma 0, kernel is a single 1.\n if sigma==0:\n return np.array([1.0])\n \n # precalculate some stuff\n sigma2 = sigma**2\n sqrt2 = np.sqrt(2)\n \n # Calculate the gaussian, it is unnormalized. We'll normalize at the end.\n basegauss = np.exp(- t**2 / (2*sigma2) )\n \n # Scale the t-vector, what we actually do is H( t/(sigma*sqrt2) ), \n # where H() is the Hermite polynomial. \n x = t / (sigma*sqrt2)\n \n # Depending on the order, calculate the Hermite polynomial (physicists \n # notation). We let Mathematica calculate these, and put the first 20 \n # orders in here. 20 orders should be sufficient for most tasks :)\n if order<0: \n raise Exception(\"The order should not be negative!\") \n elif order==0:\n part = 1\n elif order==1:\n part = 2*x\n elif order==2:\n part = -2 + 4*x**2\n elif order==3:\n part = -12*x + 8*x**3\n elif order==4:\n part = 12 - 48*x**2 + 16*x**4\n elif order==5:\n part = 120*x - 160*x**3 + 32*x**5\n elif order==6:\n part = -120 + 720*x**2 - 480*x**4 + 64*x**6\n elif order==7: \n part = -1680*x + 3360*x**3 - 1344*x**5 + 128*x**7\n elif order==8: \n part = 1680 - 13440*x**2 + 13440*x**4 - 3584*x**6 + 256*x**8\n elif order==9: \n part = 30240*x - 80640*x**3 + 48384*x**5 - 9216*x**7 + 512*x**9\n elif order==10: \n part = (-30240 + 302400*x**2 - 403200*x**4 + 161280*x**6 - 23040*x**8 \n + 1024*x**10)\n elif order==11: \n part = (-665280*x + 2217600*x**3 - 1774080*x**5 + 506880*x**7 \n - 56320*x**9 + 2048*x**11)\n elif order==12: \n part = (665280 - 7983360*x**2 + 13305600*x**4 - 7096320*x**6 \n + 1520640*x**8 - 135168*x**10 + 4096*x**12)\n elif order==13: \n part = (17297280*x - 69189120*x**3 + 69189120*x**5 - 26357760*x**7 \n + 4392960*x**9 - 319488*x**11 + 8192*x**13)\n elif order==14: \n part = (-17297280 + 242161920*x**2 - 484323840*x**4 + 322882560*x**6 \n - 92252160*x**8 + 12300288*x**10 - 745472*x**12 + 16384*x**14)\n elif order==15: \n part = (-518918400*x + 2421619200*x**3 - 2905943040*x**5 \n + 1383782400*x**7 - 307507200*x**9 + 33546240*x**11 \n - 1720320*x**13 + 32768*x**15)\n elif order==16: \n part = (518918400 - 8302694400*x**2 + 19372953600*x**4 \n - 15498362880*x**6 + 5535129600*x**8 \n - 984023040*x**10 + 89456640*x**12 - 3932160*x**14 \n + 65536*x**16) \n else:\n raise Exception(\"This order is not implemented!\")\n \n \n # Apply Hermite polynomial to gauss\n k = (-1)**order * part * basegauss\n \n ## Normalize\n \n # By calculating the normalization factor by integrating the gauss, rather\n # than using the expression 1/(sigma*sqrt(2pi)), we know that the KERNEL\n # volume is 1 when the order is 0.\n norm_default = 1 / basegauss.sum()\n # == 1 / ( sigma * sqrt(2*pi) )\n\n # Here's another normalization term that we need because we use the Hermite\n # polynomials.\n norm_hermite = 1/(sigma*sqrt2)**order\n\n # A note on Gaussian derivatives: as sigma increases, the resulting\n # image (when smoothed) will have smaller intensities. To correct for\n # this (if this is necessary) a diffusion normalization term can be\n # applied: sigma**2\n\n # Normalize and return\n return k * ( norm_default * norm_hermite )\n\n\n\ndef gaussiankernel(sigma, order=0, N=None, returnt=False, warn=True):\n \"\"\" gaussiankernel(sigma, order=0, N=None, returnt=False, warn=True)\n \n Creates a 1D gaussian derivative kernel with the given sigma\n and the given order. (An order of 0 is a \"regular\" Gaussian.)\n \n The returned kernel is a column vector, thus working in the first \n dimension (in images, this often is y). \n \n The returned kernel is odd by default. Using N one can specify the\n full kernel size (if not int, the ceil operator is applied). By \n specifying a negative value for N, the tail length (number of elements\n on both sides of the center element) can be specified.\n The total kernel size than becomes ceil(-N)*2+1. Though the method\n to supply it may be a bit obscure, this measure can be handy, since \n the tail length if often related to the sigma. If not given, the \n optimal N is determined automatically, depending on sigma and order. \n \n If the given scale is a small for the given order, a warning is\n produced (unless warn==True).\n \n ----- Used Literature:\n\n Koenderink, J. J. \n The structure of images. \n Biological Cybernetics 50, 5 (1984), 363-370.\n\n Lindeberg, T. \n Scale-space for discrete signals. \n IEEE Transactions on Pattern Analysis and Machine Intelligence 12, 3 (1990), 234-254.\n\n Ter Haar Romeny, B. M., Niessen, W. J., Wilting, J., and Florack, L. M. J. \n Differential structure of images: Accuracy of representation.\n In First IEEE International Conference on Image Processing, (Austin, TX) (1994).\n \"\"\"\n \n # Check inputs\n if not N:\n # Calculate ratio that is small, but large enough to prevent errors\n ratio = 3 + 0.25 * order - 2.5/((order-6)**2+(order-9)**2)\n # Calculate N\n N = int( np.ceil( ratio*sigma ) ) * 2 + 1\n \n elif N > 0:\n if not isinstance(N, int):\n N = int( np.ceil(N) )\n \n elif N < 0:\n N = -N\n if not isinstance(N, int):\n N = int( np.ceil(N) )\n N = N * 2 + 1\n \n # Check whether given sigma is large enough \n sigmaMin = 0.5 + order**(0.62) / 5\n if warn and sigma < sigmaMin:\n print('WARNING: The scale (sigma) is very small for the given order, '\n 'better use a larger scale!')\n \n # Create t vector which indicates the x-position\n t = np.arange(-N/2.0+0.5, N/2.0, 1.0, dtype=np.float64)\n \n # Get kernel\n k = _gaussiankernel(sigma, order, t)\n \n # Done\n if returnt:\n return k, t\n else:\n return k\n\n\n\ndef gaussiankernel2(sigma, ox, oy, N=None):\n \"\"\" gaussiankernel2(sigma, ox, oy, N=-3*sigma)\n Create a 2D Gaussian kernel.\n \"\"\"\n # Default N\n if N is None:\n N = -3*sigma\n \n # Calculate kernels\n k1 = gaussiankernel(sigma, ox, N)\n k2 = gaussiankernel(sigma, oy, N)\n \n # Matrix multiply\n k = np.matrix(k1).T * np.matrix(k2)\n return k.A \n\n\ndef diffusionkernel(sigma, N=4, returnt=False):\n \"\"\" diffusionkernel(sigma, N=4, returnt=False)\n \n A discrete analog to the continuous Gaussian kernel, \n as proposed by Toni Lindeberg.\n \n N is the tail length factor (relative to sigma).\n \n \"\"\"\n \n # Make sure sigma is float\n sigma = float(sigma)\n \n # Often refered to as the scale parameter, or t\n sigma2 = sigma*sigma \n \n # Where we start, from which we go backwards\n # This is also the tail length\n if N > 0:\n nstart = int(np.ceil(N*sigma)) + 1\n else:\n nstart = abs(N) + 1\n \n # Allocate kernel and times\n t = np.arange(-nstart, nstart+1, dtype='float64')\n k = np.zeros_like(t)\n \n # Make a start\n n = nstart # center (t[nstart]==0)\n k[n+nstart] = 0\n n = n-1\n k[n+nstart] = 0.01\n \n # Iterate!\n for n in range(nstart-1,0,-1): \n # Calculate previous\n k[(n-1)+nstart] = 2*n/sigma2 * k[n+nstart] + k[(n+1)+nstart]\n \n # The part at the left can be erroneous, so let's use the right part only\n k[:nstart] = np.flipud(k[-nstart:])\n \n # Remove the tail, which is zero\n k = k[1:-1]\n t = t[1:-1]\n \n # Normalize\n k = k / k.sum()\n \n # the function T that we look for is T = e^(-sigma2) * I(n,sigma2)\n # We found I(n,sigma2) and because we normalized it, the normalization term\n # e^(-sigma2) is no longer necesary.\n \n # Done\n if returnt:\n return k, t\n else:\n return k\n\n\n## Filters\n\ndef gfilter(L, sigma, order=0, mode='constant', warn=True):\n \"\"\" gfilter(L, sigma, order=0, mode='constant', warn=True)\n \n Gaussian filterering and Gaussian derivative filters.\n \n Parameters\n ----------\n L : np.ndarray\n The input data to filter\n sigma : scalar or list-of-scalars\n The smoothing parameter, can be given for each dimension\n order : int or list-of-ints\n The order of the derivative, can be given for each dimension\n mode : {'reflect','constant','nearest','mirror', 'wrap'}\n Determines how edge effects are handled. (see scipy.ndimage.convolve1d)\n warn : boolean\n Whether to show a warning message if the sigma is too small to \n represent the required derivative.\n \n Notes\n =====\n Makes use of the seperability property of the Gaussian by convolving\n 1D kernels in each dimension. \n \n \n Example\n =======\n # Calculate the second order derivative with respect to x (Lx) (if the\n # first dimension of the image is Y).\n result1 = gfilter( im, 2, [0,2] ) \n # Calculate the first order derivative with respect to y and z (Lyz).\n result2 = gfilter( volume, 3, [0,1,1] ) \n \n \"\"\"\n \n # store original\n Lo = L\n \n # make sigma ok\n try:\n sigma = [sig for sig in sigma]\n except TypeError:\n sigma = [sigma for i in range(L.ndim)]\n \n # same for order\n if order is None:\n order = 0\n try:\n order = [o for o in order]\n except TypeError:\n order = [order for i in range(L.ndim)]\n \n # test sigma\n if len(sigma) != L.ndim:\n tmp = \"the amount of sigmas given must match the dimensions of L!\"\n raise Exception(tmp) \n # test order\n if len(order) != L.ndim:\n tmp = \"the amount of sigmas given must match the dimensions of L!\"\n raise Exception(tmp)\n \n for d in range(L.ndim):\n # get kernel\n k = gaussiankernel(sigma[d], order[d], warn=warn)\n # convolve\n L = scipy.ndimage.convolve1d(L, k, d, mode=mode)\n \n \n # Make Aarray if we can\n if hasattr(Lo, 'sampling') and hasattr(Lo, 'origin'):\n L = Aarray(L, Lo.sampling, Lo.origin)\n \n # Done\n return L\n\n\ndef diffuse(L, sigma, mode='nearest'):\n \"\"\" diffuse(L, sigma)\n \n Diffusion using a discrete variant of the diffusion operator. \n \n Parameters\n ----------\n L : np.ndarray\n The input data to filter\n sigma : scalar or list-of-scalars\n The smoothing parameter, can be given for each dimension\n \n Details\n -------\n In the continous domain, the Gaussian is the only true diffusion\n operator. However, by using a sampled Gaussian kernel in the \n discrete domain, errors are introduced, particularly if for\n small sigma. \n \n This implementation uses a a discrete variant of the diffusion\n operator, which is based on modified Bessel functions. This results\n in a better approximation of the diffusion process, particularly\n when applying the diffusion recursively. There are also advantages\n for calculating derivatives, see below.\n \n Based on:\n Lindeberg, T. \"Discrete derivative approximations with scale-space\n properties: A basis for low-level feature extraction\", \n J. of Mathematical Imaging and Vision, 3(4), pp. 349--376, 1993.\n \n Calculating derivatives\n -----------------------\n Because this imeplementation applies diffusion using a discrete \n representation of the diffusion kernel, one can calculate true\n derivatives using small-support derivative operators. For 1D:\n * Lx = 0.5 * ( L[x+1] - L[x-1] )\n * Lxx = L[x+1] - 2*L[x] + L(x-1)\n \n \"\"\"\n \n # Store original\n Lo = L\n \n # Make sigma ok\n try:\n sigma = [sig for sig in sigma]\n except TypeError:\n sigma = [sigma for i in range(L.ndim)]\n \n # Test sigma\n if len(sigma) != L.ndim:\n tmp = \"the amount of sigmas given must match the dimensions of L!\"\n raise Exception(tmp) \n \n # Diffuse\n for d in range(L.ndim):\n # get kernel\n k = diffusionkernel(sigma[d])\n # convolve\n L = scipy.ndimage.convolve1d(L, k, d, mode=mode)\n \n # Make Aarray if we can\n if hasattr(Lo, 'sampling') and hasattr(Lo, 'origin'):\n L = Aarray(L, Lo.sampling, Lo.origin)\n \n # Done\n return L\n\n\ndef gfilter2(L, scale, order=0, mode='reflect', warn=True):\n \"\"\" gfilter2(L, scale, order=0, mode='reflect', warn=True)\n \n Apply Gaussian filtering by specifying a scale in world coordinates\n rather than a sigma. This function determines the sigmas to apply,\n based on the sampling of the elements.\n \n See gfilter for more information.\n \n (If L is not an Aarray, this function yields the same result as gfilter.)\n \n \"\"\"\n \n # Determine sigmas\n if hasattr(L, 'sampling'):\n sigmas = [float(scale)/s for s in L.sampling]\n else:\n sigmas = float(scale)\n \n # Filter\n return gfilter(L, sigmas, order, mode, warn)\n\n\ndef diffuse2(L, scale, mode='nearest'):\n \"\"\" diffuse2(L, scale, mode='nearest')\n \n Apply diffusion by specifying a scale in world coordinates\n rather than a sigma. This function determines the sigmas to apply,\n based on the sampling of the elements.\n \n See diffuse for more information.\n \n (If L is not an Aarray, this function yields the same result as diffuse.)\n \n \"\"\"\n \n # Determine sigmas\n if hasattr(L, 'sampling'):\n sigmas = [float(scale)/s for s in L.sampling]\n else:\n sigmas = float(scale)\n \n # Filter\n return diffuse(L, sigmas, mode)\n\n" ]
[ [ "numpy.matrix", "numpy.sqrt", "numpy.arange", "numpy.flipud", "numpy.ceil", "numpy.zeros_like", "numpy.array", "numpy.exp" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
reichlab/jacques
[ "772e6f69de944f5ce19af16b24dfd76d023861f9" ]
[ "test/test_kernel_smooth_quantile_fn.py" ]
[ "import os\nos.environ['CUDA_VISIBLE_DEVICES'] = '-1'\n\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow_probability as tfp\nimport unittest\n\nfrom jacques import kernels\n\n\nclass Test_Kernel_Smooth_Quantile_Fn(unittest.TestCase):\n def test_quantile_smooth_bw(self):\n tau = np.concatenate(\n [np.array([0.01, 0.025])] +\n [np.linspace(0.05, 0.95, 19)] +\n [np.array([0.975, 0.99])],\n axis = 0)\n theta_b_raw = np.ones(1)\n theta_b = 0.25 * np.exp(theta_b_raw) / (1.0 + np.exp(theta_b_raw))\n \n lower_tau = tau[:9]\n central_tau = tau[9:(-9)]\n upper_tau = tau[-9:]\n expected = np.concatenate(\n [lower_tau - lower_tau**2 / (4 * theta_b)] +\n [np.full_like(central_tau, theta_b)] +\n [(1 - upper_tau) - (1 - upper_tau)**2 / (4 * theta_b)],\n axis = 0\n )\n \n actual = kernels.quantile_smooth_bw(tf.constant(tau), tf.constant(theta_b_raw))\n \n # actual matches expected\n self.assertTrue(np.all(np.abs(actual.numpy() - expected) < 1e-12))\n \n \n def test_integrated_epanechnikov(self):\n # TODO\n raise NotImplementedError\n \n \n def test_kernel_quantile_fn(self):\n tau = np.concatenate(\n [np.array([0.01, 0.025])] +\n [np.linspace(0.05, 0.95, 19)] +\n [np.array([0.975, 0.99])],\n axis = 0)\n y = np.array(\n [[1.0, 5.0, 8.0],\n [5.0, 2.0, 3.0],\n [11.0, 20.0, 15.0]]\n )\n w = np.array(\n [[[0.1, 0.5, 0.4],\n [0.333, 0.333, 0.334]],\n [[0.3, 0.2, 0.5],\n [0.0, 0.0, 1.0]],\n [[0.4, 0.4, 0.2],\n [0.2, 0.2, 0.6]]]\n )\n y_sorted = np.array(\n [[1.0, 5.0, 8.0],\n [2.0, 3.0, 5.0],\n [11.0, 15.0, 20.0]]\n )\n w_sorted = np.array(\n [[[0.1, 0.5, 0.4],\n [0.333, 0.333, 0.334]],\n [[0.2, 0.5, 0.3],\n [0.0, 1.0, 0.0]],\n [[0.4, 0.2, 0.4],\n [0.2, 0.6, 0.2]]]\n )\n theta_b_raw = np.ones(1)\n bw = kernels.quantile_smooth_bw(tf.constant(tau), tf.constant(theta_b_raw))\n \n expected = np.zeros((3, 2, 23))\n # batch\n for b in range(3):\n # test set observation\n for j in range(2):\n # quantile level\n for k in range(23):\n tau_k = tau[k]\n bw_k = bw[k]\n cw = np.concatenate([np.array([0.0]), np.cumsum(w_sorted[b, j, :])], axis=0)\n # train set observation\n for i in range(3):\n U_im1 = kernels.integrated_epanechnikov(\n (tau_k - cw[i+1-1]) / bw_k\n )\n U_i = kernels.integrated_epanechnikov(\n (tau_k - cw[i+1]) / bw_k\n )\n expected[b, j, k] = expected[b, j, k] + \\\n (U_im1 - U_i) * y_sorted[b, i]\n \n actual = kernels.kernel_quantile_fn(\n tf.constant(y),\n tf.constant(w),\n tf.constant(tau),\n tf.constant(theta_b_raw))\n \n # actual matches expected\n self.assertTrue(np.all(np.abs(actual.numpy() - expected) < 1e-12))\n\n\nif __name__ == '__main__':\n unittest.main()\n" ]
[ [ "tensorflow.constant", "numpy.linspace", "numpy.cumsum", "numpy.ones", "numpy.full_like", "numpy.exp", "numpy.array", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "1.12", "2.6", "2.2", "1.4", "2.3", "2.4", "2.9", "1.5", "1.7", "2.5", "0.12", "1.0", "2.8", "1.2", "2.10" ] } ]
JxTang-bioinformatics/Tangbio
[ "7e0f0ed45371504c65d2a7ed419aed934e26c583" ]
[ "CaMelia model/Feature extraction/unionfeature_for_train.py" ]
[ "# -*- coding: utf-8 -*-\r\nfrom __future__ import division\r\nfrom sys import argv\r\nimport pandas as pd\r\nimport numpy as np\r\nimport os,time\r\nimport warnings\r\nwarnings.filterwarnings('ignore')\r\n###########################################\r\ndef reduce_mem(df):\r\n starttime = time.time()\r\n numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']\r\n start_mem = df.memory_usage().sum() / 1024**2\r\n for col in df.columns:\r\n col_type = df[col].dtypes\r\n if col_type in numerics:\r\n c_min = df[col].min()\r\n c_max = df[col].max()\r\n if pd.isnull(c_min) or pd.isnull(c_max):\r\n continue\r\n if str(col_type)[:3] == 'int':\r\n if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:\r\n df[col] = df[col].astype(np.int8)\r\n elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:\r\n df[col] = df[col].astype(np.int16)\r\n elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:\r\n df[col] = df[col].astype(np.int32)\r\n elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:\r\n df[col] = df[col].astype(np.int64)\r\n else:\r\n if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:\r\n df[col] = df[col].astype(np.float16)\r\n elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:\r\n df[col] = df[col].astype(np.float32)\r\n else:\r\n df[col] = df[col].astype(np.float64)\r\n end_mem = df.memory_usage().sum() / 1024**2\r\n print('-- Mem. usage decreased to {:5.2f} Mb ({:.1f}% reduction),time spend:{:2.2f} min'.format(end_mem,\r\n 100*(start_mem-end_mem)/start_mem,\r\n (time.time()-starttime)/60))\r\n return df\r\n\r\n###########################################\r\nif __name__ == '__main__': \r\n \r\n #All data located in the same directory\r\n DataPath = r'%s' % argv[1]\r\n #Input data \r\n InputDataName = '%s' % argv[2] \r\n #neighboring range\r\n neighbor_region = int(argv[3])\r\n \r\n \r\n \r\n gse = DataPath\r\n ff = InputDataName\t \r\n region = neighbor_region \r\n \r\n \r\n name = ff.split('.')[0].split('_')[-1]\r\n \r\n \r\n path = r'%s/%s' % (gse,ff)\r\n data = pd.read_csv(path,header=0,sep='\\t')\r\n data = reduce_mem(data)\r\n if list(data)[0] != 'chrom':\r\n del data['%s' % list(data)[0]]\r\n \r\n cell_num = list(data)[2:( len(list(data))-1 )]\r\n \r\n \r\n file_dir = r'%s/Available_Train_dataset/region%d' % (gse,region)\r\n if not os.path.exists(file_dir):\r\n os.makedirs(file_dir) \r\n \r\n for i in range(len(cell_num)): \r\n #local_methFeature\r\n path = r'%s/region10_localmatched_morethan08/%s.txt' % (gse,cell_num[i])\r\n local_methFeature = pd.read_csv(path,header=0,sep='\\t')\r\n local_methFeature = reduce_mem(local_methFeature)\r\n local_methFeature = local_methFeature.rename(columns={'aver_meth':'local_methFeature'})\r\n local_methFeature = local_methFeature[['chrom','location','local_methFeature']]\r\n\r\n #neighbor_methFeature\r\n path = r'%s/neighbor_methFeature_%d/localRegion_%s/%s_neighbor_methFeature.txt' % (gse,region,region,cell_num[i])\r\n neighbor_methFeature = pd.read_csv(path,header=0,sep='\\t')\r\n neighbor_methFeature = reduce_mem(neighbor_methFeature)\r\n\r\n #merge-[neighbor,local]\r\n data_all = pd.merge(data[['chrom','location','%s' % cell_num[i] ]],local_methFeature)\r\n data_all = pd.merge(data_all,neighbor_methFeature,how='inner',on=['chrom','location'])\r\n \r\n data_all.to_csv(r'%s/%s.txt' % (file_dir,cell_num[i]),sep='\\t',header=True,index=False) \r\n del data_all\r\n" ]
[ [ "pandas.merge", "pandas.read_csv", "pandas.isnull", "numpy.finfo", "numpy.iinfo" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
ganik/DeepSpeed
[ "788e1c40e83beacfc4901e7daa1e097d2efb82bb", "788e1c40e83beacfc4901e7daa1e097d2efb82bb" ]
[ "tests/unit/test_partition.py", "tests/unit/test_pipe.py" ]
[ "import pytest\n\nimport torch\nimport torch.distributed as dist\n\nfrom deepspeed.runtime.utils import partition_uniform\nfrom deepspeed.runtime.utils import partition_balanced\nfrom deepspeed.runtime.utils import prefix_sum_inc\nfrom deepspeed.runtime.utils import PartitionedTensor\n\nfrom .common import distributed_test\n\n\n@distributed_test(world_size=4)\ndef test_partitioned_tensor():\n world = dist.get_world_size()\n rank = dist.get_rank()\n\n group = dist.new_group(ranks=list(range(world)))\n\n rows = world * 4\n cols = 3\n\n full = torch.rand(rows, cols).cuda()\n dist.broadcast(full, src=0, group=group)\n part = PartitionedTensor(full, group=group)\n\n assert len(part.local_size()) == 1\n assert part.local_size()[0] * world == full.numel()\n\n reconstructed = part.full()\n assert torch.equal(full, reconstructed)\n\n\n@distributed_test(world_size=4)\ndef test_partitioned_tensor_meta():\n world = dist.get_world_size()\n rank = dist.get_rank()\n\n group = dist.new_group(ranks=list(range(world)))\n\n rows = world * 7\n cols = 3\n\n full = torch.rand(rows, cols).cuda()\n dist.broadcast(full, src=0, group=group)\n part = PartitionedTensor(full, group=group)\n\n my_meta = PartitionedTensor.from_meta(part.to_meta(), part.local_data, group)\n assert torch.equal(full, my_meta.full())\n\n\ndef assert_valid_partition(weights, parts, P):\n N = len(weights)\n assert len(parts) == P + 1\n assert parts[0] == 0\n assert parts[P] == N\n for idx in range(P):\n assert parts[idx] <= parts[idx + 1]\n\n\ndef get_partition_weights(weights, parts):\n \"\"\" Return the amount of weight in each partition. \"\"\"\n costs = [0] * (len(parts) - 1)\n P = len(parts) - 1\n for p in range(P):\n start = parts[p]\n stop = parts[p + 1]\n costs[p] = sum(weights[start:stop])\n return costs\n\n\ndef test_prefix_sum():\n x = [3, 4, 5]\n psum = prefix_sum_inc(x)\n assert psum == [3, 7, 12]\n\n\ndef test_valid_partition():\n N = 10\n P = 1\n weights = [1] * N\n parts = partition_balanced(weights, P)\n assert_valid_partition(weights, parts, P)\n\n\ndef test_short_partition_uniform():\n N = 2\n P = 4\n weights = [1] * N\n parts = partition_uniform(len(weights), P)\n assert_valid_partition(weights, parts, P)\n\n\ndef test_short_partition():\n N = 2\n P = 4\n weights = [1] * N\n parts = partition_balanced(weights, P)\n assert_valid_partition(weights, parts, P)\n\n\ndef test_easy_balance_uniform():\n weights = [1] * 8\n P = 4\n parts = partition_uniform(len(weights), P)\n assert_valid_partition(weights, parts, P)\n costs = get_partition_weights(weights, parts)\n assert all(c == 2 for c in costs)\n\n\ndef test_easy_balance_balanced():\n weights = [1] * 8\n P = 4\n parts = partition_balanced(weights, P)\n assert_valid_partition(weights, parts, P)\n costs = get_partition_weights(weights, parts)\n assert all(c == 2 for c in costs), costs\n\n\ndef test_int_balanced():\n weights = [0, 1, 2, 3, 3, 3]\n P = 4\n parts = partition_balanced(weights, P)\n assert parts == [0, 3, 4, 5, 6]\n\n assert_valid_partition(weights, parts, P)\n costs = get_partition_weights(weights, parts)\n assert all(c == 3 for c in costs)\n\n\ndef test_float_balanced():\n weights = [0., 1.1, 1.9, 3., 3., 3.]\n P = 4\n parts = partition_balanced(weights, P)\n assert_valid_partition(weights, parts, P)\n assert parts == [0, 3, 4, 5, 6]\n\n\[email protected](reason=\"Variance-minimizing partitioning returns different result.\")\ndef test_float_lastheavy():\n weights = [0., 1.1, 1.9, 3., 30.]\n P = 2\n parts = partition_balanced(weights, P)\n assert_valid_partition(weights, parts, P)\n assert parts == [0, 4, 5]\n\n\ndef test_float_midheavy():\n weights = [0., 1.1, 30, 3.]\n P = 3\n parts = partition_balanced(weights, P)\n assert_valid_partition(weights, parts, P)\n assert parts == [0, 2, 3, 4]\n\n\ndef test_balance_bert():\n # Parameters per layer for a transformer model with 24 transformers and hidden dim 1024\n weights = [\n 52559872,\n 12596224,\n 12596224,\n 12596224,\n 12596224,\n 12596224,\n 12596224,\n 12596224,\n 12596224,\n 12596224,\n 12596224,\n 12596224,\n 12596224,\n 12596224,\n 12596224,\n 12596224,\n 12596224,\n 12596224,\n 12596224,\n 12596224,\n 12596224,\n 12596224,\n 12596224,\n 12596224,\n 12596224,\n 0,\n 52559872\n ]\n P = 8\n parts = partition_balanced(weights, P)\n assert_valid_partition(weights, parts, P)\n", "import os\nimport copy\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.distributed as dist\n\nimport pytest\n\nimport deepspeed\nimport deepspeed.runtime.utils as ds_utils\n\n\nfrom deepspeed.runtime.pipe.topology import PipeDataParallelTopology, PipeModelDataParallelTopology\n\nPipeTopo = PipeDataParallelTopology\nfrom deepspeed.runtime.pipe.module import PipelineModule, LayerSpec\n\nfrom .common import distributed_test\n\n\ndef rel_diff(A, B):\n return abs(A - B) / abs(A)\n\n\n# All models\nfrom .simple_model import args_from_dict\n\n\nclass AlexNet(nn.Module):\n def __init__(self, num_classes=10):\n super(AlexNet, self).__init__()\n self.features = nn.Sequential(\n nn.Conv2d(3,\n 64,\n kernel_size=11,\n stride=4,\n padding=5),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2,\n stride=2),\n nn.Conv2d(64,\n 192,\n kernel_size=5,\n padding=2),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2,\n stride=2),\n nn.Conv2d(192,\n 384,\n kernel_size=3,\n padding=1),\n nn.ReLU(inplace=True),\n nn.Conv2d(384,\n 256,\n kernel_size=3,\n padding=1),\n nn.ReLU(inplace=True),\n nn.Conv2d(256,\n 256,\n kernel_size=3,\n padding=1),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2,\n stride=2),\n )\n self.classifier = nn.Linear(256, num_classes)\n self.loss_fn = nn.CrossEntropyLoss()\n\n def forward(self, x, y):\n x = self.features(x)\n x = x.view(x.size(0), -1)\n x = self.classifier(x)\n return self.loss_fn(x, y)\n\n\nclass AlexNetPipe(AlexNet):\n def to_layers(self):\n layers = [*self.features, lambda x: x.view(x.size(0), -1), self.classifier]\n return layers\n\n\nclass AlexNetPipeSpec(PipelineModule):\n def __init__(self, num_classes=10, **kwargs):\n self.num_classes = num_classes\n specs = [\n LayerSpec(nn.Conv2d, 3, 64, kernel_size=11, stride=4, padding=5),\n LayerSpec(nn.ReLU, inplace=True),\n LayerSpec(nn.MaxPool2d, kernel_size=2, stride=2),\n LayerSpec(nn.Conv2d, 64, 192, kernel_size=5, padding=2),\n F.relu,\n LayerSpec(nn.MaxPool2d, kernel_size=2, stride=2),\n LayerSpec(nn.Conv2d, 192, 384, kernel_size=3, padding=1),\n F.relu,\n LayerSpec(nn.Conv2d, 384, 256, kernel_size=3, padding=1),\n F.relu,\n LayerSpec(nn.Conv2d, 256, 256, kernel_size=3, padding=1),\n F.relu,\n LayerSpec(nn.MaxPool2d, kernel_size=2, stride=2),\n\n lambda x: x.view(x.size(0), -1),\n LayerSpec(nn.Linear, 256, self.num_classes), # classifier\n ]\n super().__init__(layers=specs, loss_fn=nn.CrossEntropyLoss(), **kwargs)\n\n\ndef cifar_trainset(fp16=False):\n import torchvision\n import torchvision.transforms as transforms\n\n transform_list = [\n transforms.ToTensor(),\n transforms.Normalize((0.5,\n 0.5,\n 0.5),\n (0.5,\n 0.5,\n 0.5)),\n ]\n if fp16:\n transform_list.append(torchvision.transforms.Lambda(lambda x: x.half()))\n\n transform = transforms.Compose(transform_list)\n\n local_rank = torch.cuda.current_device()\n\n # Only one rank per machine downloads.\n dist.barrier()\n if local_rank != 0:\n dist.barrier()\n trainset = torchvision.datasets.CIFAR10(root='/tmp/cifar10-data',\n train=True,\n download=True,\n transform=transform)\n if local_rank == 0:\n dist.barrier()\n return trainset\n\n\ndef train_cifar(model, args, num_steps=400, average_dp_losses=True, fp16=True, seed=123):\n with torch.random.fork_rng(devices=[torch.cuda.current_device()]):\n ds_utils.set_random_seed(seed)\n\n # disable dropout\n model.eval()\n\n trainset = cifar_trainset(fp16=fp16)\n args.local_rank = dist.get_rank()\n\n engine, _, _, _ = deepspeed.initialize(\n args=args,\n model=model,\n model_parameters=[p for p in model.parameters()],\n training_data=trainset)\n\n losses = []\n for step in range(num_steps):\n loss = engine.train_batch()\n losses.append(loss.item())\n if step % 50 == 0 and dist.get_rank() == 0:\n print(f'STEP={step} LOSS={loss.item()}')\n\n if average_dp_losses:\n loss_tensor = torch.tensor(losses).cuda()\n dist.all_reduce(loss_tensor)\n loss_tensor /= dist.get_world_size()\n losses = loss_tensor.tolist()\n\n return losses\n\n\[email protected](reason=\"been seeing nondeterministic failures, skipping for now\")\[email protected]('topo',\n [\n PipeTopo(num_pp=1,\n num_dp=4),\n PipeTopo(num_pp=2,\n num_dp=2),\n PipeTopo(num_pp=4,\n num_dp=1),\n ])\ndef test_pipe_cifar10(topo, tmpdir):\n config_dict = {\n \"train_batch_size\": 16,\n \"train_micro_batch_size_per_gpu\": 4,\n \"steps_per_print\": 20,\n \"optimizer\": {\n \"type\": \"Adam\",\n \"params\": {\n \"lr\": 0.001,\n \"betas\": [0.9,\n 0.999],\n \"eps\": 1e-8,\n \"weight_decay\": 3e-7\n }\n },\n \"zero_optimization\": {\n \"stage\": 0\n },\n \"fp16\": {\n \"enabled\": False\n },\n \"pipeline\": {\n \"seed_layers\": True,\n \"activation_checkpoint_interval\": 1\n }\n }\n args = args_from_dict(tmpdir, config_dict)\n\n # Allocate model for consistent initial weights.\n init_net = AlexNetPipe()\n\n @distributed_test(world_size=4)\n def _helper(topo, tmpdir, steps=500):\n assert steps >= 100\n\n base_net = copy.deepcopy(init_net)\n base_model = PipelineModule(layers=base_net.to_layers(),\n num_stages=1,\n loss_fn=nn.CrossEntropyLoss())\n\n # Train with just data parallelism\n base_losses = train_cifar(base_model,\n args,\n num_steps=steps,\n fp16=config_dict['fp16']['enabled'])\n\n test_net = copy.deepcopy(init_net)\n test_model = PipelineModule(layers=test_net.to_layers(),\n topology=topo,\n loss_fn=nn.CrossEntropyLoss())\n\n #test_model = AlexNetPipe(num_classes=10,\n # topology=test_topo,\n # seed_layers=config_dict['pipeline']['seed_layers'])\n test_losses = train_cifar(test_model,\n args,\n num_steps=steps,\n fp16=config_dict['fp16']['enabled'])\n\n abs_diffs = [l0 - l1 for l0, l1 in zip(base_losses, test_losses)]\n rel_diffs = [rel_diff(l0, l1) for l0, l1 in zip(base_losses, test_losses)]\n if dist.get_rank() == 0:\n print(\n f'abs min={min(abs_diffs)} max={max(abs_diffs)} avg={sum(abs_diffs)/len(abs_diffs)}'\n )\n print(\n f'rel min={min(rel_diffs)} max={max(rel_diffs)} avg={sum(rel_diffs)/len(rel_diffs)}'\n )\n print(\n f'first: base={base_losses[0]} test={test_losses[0]} abs={abs_diffs[0]} rel={rel_diffs[0]}'\n )\n\n for lastX in [1, 10, 100]:\n base_avg = sum(base_losses[-lastX:]) / lastX\n test_avg = sum(test_losses[-lastX:]) / lastX\n print(\n f'last-{lastX}: base={base_avg} test={test_avg} abs={base_avg - test_avg} rel={rel_diff(base_avg, test_avg)}'\n )\n\n lastX = 100\n base = base_losses[-lastX:]\n base_avg = sum(base) / len(base)\n test = test_losses[-lastX:]\n test_avg = sum(test) / len(test)\n assert rel_diff(base_avg, test_avg) < 0.03\n\n _helper(topo, tmpdir)\n" ]
[ [ "torch.distributed.broadcast", "torch.equal", "torch.rand", "torch.distributed.get_rank", "torch.distributed.get_world_size" ], [ "torch.nn.CrossEntropyLoss", "torch.cuda.current_device", "torch.nn.Conv2d", "torch.distributed.barrier", "torch.tensor", "torch.nn.Linear", "torch.nn.MaxPool2d", "torch.distributed.get_rank", "torch.nn.ReLU", "torch.distributed.all_reduce", "torch.distributed.get_world_size" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
takumiw/nishika-cable-classification-1st-place
[ "6438c36fa607b79cd1b2dad195881dacc6a48e9d" ]
[ "src/utils_metrics.py" ]
[ "from typing import Dict, List, Optional\n\nimport numpy as np\nfrom sklearn.metrics import accuracy_score, f1_score, log_loss\n\n\ndef calc_metrics(\n y_true: np.ndarray, y_pred: np.ndarray, y_prob: Optional[np.ndarray] = None, metrics: List[str] = [\"loss\"]\n) -> Dict[str, float]:\n result = {}\n for metric in metrics:\n if metric == \"loss\":\n result[\"loss\"] = log_loss(y_true, y_prob)\n elif metric == \"accuracy\":\n result[\"accuracy\"] = accuracy_score(y_true, y_pred)\n elif metric == \"f1\":\n result[\"f1\"] = f1_score(y_true, y_pred, average=\"micro\")\n else:\n raise NameError(f\"metric {metric} is not defined\")\n return result\n" ]
[ [ "sklearn.metrics.log_loss", "sklearn.metrics.f1_score", "sklearn.metrics.accuracy_score" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
DipeshV/olympic-hero
[ "73a82f36afed429b59895c68faffe838b90fc72b" ]
[ "code.py" ]
[ "# --------------\n#Importing header files\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n#Path of the file\r\npath\r\n\r\n#Code starts here\r\ndata = pd.read_csv(path)\r\n\r\ndata.rename(columns={'Total':'Total_Medals'}, inplace=True)\r\nprint(data.head())\n\n\n# --------------\n#Code starts here\n\ndata['Better_Event'] = np.where(data['Total_Summer'] > data['Total_Winter'], 'Summer', 'Winter')\ndata['Better_Event'] = np.where(data['Total_Summer'] == data['Total_Winter'], 'Both', data['Better_Event'])\n\nbetter_event = data['Better_Event'].value_counts().index.values[0]\n\n#print(data.head(5))\nprint(better_event)\n\nassert data['Better_Event'].value_counts()['Summer'] == 143, \"Should be 143\"\n\n\n# --------------\n#Code starts here\r\ntop_countries = data[['Country_Name','Total_Summer', 'Total_Winter', 'Total_Medals']]\r\n\r\nprint(top_countries.head(5))\r\n\r\ntop_countries=top_countries[:-1]\r\n\r\ndef top_ten(data,column):\r\n country_list = []\r\n country_list=list((data.nlargest(10,column)['Country_Name']))\r\n return country_list\r\n\r\n\r\ntop_10_summer=top_ten(top_countries,'Total_Summer')\r\nprint(\"Top 10 Summer:\\n\",top_10_summer, \"\\n\")\r\ntop_10_winter=top_ten(top_countries,'Total_Winter')\r\nprint(\"Top 10 Winter:\\n\",top_10_winter, \"\\n\")\r\ntop_10=top_ten(top_countries,'Total_Medals')\r\nprint(\"Top 10 :\\n\",top_10, \"\\n\")\r\n\r\ncommon=list(set(top_10_summer) & set(top_10_winter) & set(top_10))\r\nprint(common)\n\n\n# --------------\n#Code starts here\n\n#Create dataframe anmd plot for Summer Event\nsummer_df = data[data['Country_Name'].isin(top_10_summer)]\n\n#print(summer_df)\n\nplt.figure(figsize=(20,6))\nplt.bar(summer_df['Country_Name'], summer_df['Total_Summer'])\n\nplt.title('Top 10 Summer')\nplt.xlabel('Country Name')\nplt.ylabel('Total Medals')\n\n#Create the dataframe and plot for Winter Event\n\nwinter_df = data[data['Country_Name'].isin(top_10_winter)]\n\n#print(winter_df)\n\nplt.figure(figsize=(20,6))\nplt.bar(winter_df['Country_Name'], winter_df['Total_Winter'])\n\nplt.title('Top 10 Winter')\nplt.xlabel('Country Name')\nplt.ylabel('Total Medals')\n\n#Create the dataframe and plot for Winter Event\n\ntop_df = data[data['Country_Name'].isin(top_10)]\n\n#print(top_df)\n\nplt.figure(figsize=(20,6))\nplt.bar(top_df['Country_Name'], top_df['Total_Medals'])\n\nplt.title('Top 10')\nplt.xlabel('Country Name')\nplt.ylabel('Total Medals')\n\n\n# --------------\nsummer_df['Golden_Ratio'] = summer_df['Gold_Summer'] / summer_df['Total_Summer']\n\nsummer_max_ratio = max(summer_df['Golden_Ratio'])\n\nprint(summer_df['Golden_Ratio'].idxmax())\n\nsummer_country_gold = summer_df.loc[summer_df['Golden_Ratio'].idxmax(),'Country_Name']\n\nprint(\"Top Summer Coutnry: \", summer_country_gold, \" with a ratio of %.2f\" % summer_max_ratio)\n\n# For Winter List\n\nwinter_df['Golden_Ratio'] = winter_df['Gold_Winter'] / winter_df['Total_Winter']\n\nwinter_max_ratio = max(winter_df['Golden_Ratio'])\n\nwinter_country_gold = winter_df.loc[winter_df['Golden_Ratio'].idxmax(), 'Country_Name']\n\nprint(\"Top Winter Country: \", winter_country_gold, \" with a ratio of %.2f\" % winter_max_ratio)\n\n# For Over List\n\ntop_df['Golden_Ratio'] = top_df['Gold_Total'] / top_df['Total_Medals']\n\ntop_max_ratio = max(top_df['Golden_Ratio'])\n\ntop_country_gold = top_df.loc[top_df['Golden_Ratio'].idxmax(), 'Country_Name']\n\nprint(\"Top Country: \", top_country_gold, \" with a ratio of %.2f\" % top_max_ratio)\n\n\n# --------------\n#Code starts here\r\n\r\ndata_1 = data[:-1]\r\n\r\ndata_1['Total_Points'] = data_1['Gold_Total'] * 3 + data_1['Silver_Total'] * 2 + data_1['Bronze_Total'] * 1\r\n\r\nprint(data_1.head(10))\r\n\r\nmost_points = max(data_1['Total_Points'])\r\n\r\nbest_country = data_1.loc[data_1['Total_Points'].idxmax(),'Country_Name']\r\n\r\nprint(\"The maximum points achieved is: \", most_points, \" by \", best_country)\n\n\n# --------------\n#Code starts here\n\n#Subsetting the dataframe\nbest=data[data['Country_Name']==best_country]\nbest.reset_index(drop = True, inplace = True)\nbest=best[['Gold_Total','Silver_Total','Bronze_Total']]\n\n\n#Plotting bar plot\nbest.plot.bar(stacked=True)\n\n#Changing the x-axis label\nplt.xlabel('United States')\n\n#Changing the y-axis label\nplt.ylabel('Medals Tally')\n\n#Rotating the ticks of X-axis\nplt.xticks(rotation=45)\n\n#Updating the graph legend\nl=plt.legend()\nl.get_texts()[0].set_text('Gold_Total :' + str(best['Gold_Total'].values))\nl.get_texts()[1].set_text('Silver_Total :' + str(best['Silver_Total'].values))\nl.get_texts()[2].set_text('Bronze_Total :' + str(best['Bronze_Total'].values))\n\n\n\n#Code ends here\n\n\n" ]
[ [ "matplotlib.pyplot.legend", "pandas.read_csv", "matplotlib.pyplot.title", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.bar", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.xticks", "numpy.where", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
Antolin1/DMG-Python
[ "ba3942e13006e1a32f3fe9f1b29615311f667274" ]
[ "dmg/realism/discriminativeModel.py" ]
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Sep 17 10:33:24 2021\n\n@author: Jose Antonio\n\"\"\"\n\n#of the paper Towards Char... using GNNs\n\n\nimport torch_geometric.nn as pyg_nn\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch_scatter.composite import scatter_softmax\n\nclass DiscriminativeModel(nn.Module):\n \n def __init__(self, dim_input, \n hidden_dim,dropout, \n vocab_nodes, \n vocab_edges):\n super(DiscriminativeModel, self).__init__()\n \n \n self.emb_nodes = nn.Embedding(len(vocab_nodes), dim_input)\n \n \n self.conv_1 = pyg_nn.RGCNConv(in_channels = dim_input, out_channels = hidden_dim, \n num_relations = len(vocab_edges))\n \n self.conv_2 = pyg_nn.RGCNConv(in_channels = hidden_dim, out_channels = hidden_dim, \n num_relations = len(vocab_edges))\n \n \n \n self.d_1 = nn.Dropout(dropout)\n \n self.lin = nn.Linear(hidden_dim, 1)\n \n self.attention_vector = nn.Linear(hidden_dim,1,bias=False)\n \n def forward(self,nodeTypes,edge_index, edge_attr, bs):\n \n \n nodeTypes = self.emb_nodes(nodeTypes)\n \n \n \n nodes_mess_1 = self.conv_1(nodeTypes, edge_index, edge_attr)\n nodes_mess_1 = self.d_1(F.relu(nodes_mess_1))\n \n nodes_mess_1 = F.relu(self.conv_2(nodes_mess_1, edge_index, edge_attr))\n \n \n attentions = scatter_softmax(torch.squeeze(self.attention_vector(nodes_mess_1)), bs)\n \n nodes_mess_1 = torch.unsqueeze(attentions,dim=1) * nodes_mess_1\n \n graph_emb = pyg_nn.global_add_pool(nodes_mess_1, bs)\n \n rtu = self.lin(graph_emb)\n \n return F.sigmoid(rtu)\n \n def getAttentions(self,nodeTypes,edge_index, edge_attr, bs):\n \n nodeTypes = self.emb_nodes(nodeTypes)\n nodes_mess_1 = self.conv_1(nodeTypes, edge_index, edge_attr)\n nodes_mess_1 = self.d_1(F.relu(nodes_mess_1))\n \n nodes_mess_1 = F.relu(self.conv_2(nodes_mess_1, edge_index, edge_attr))\n \n \n attentions = scatter_softmax(torch.squeeze(self.attention_vector(nodes_mess_1)), bs)\n \n return attentions\n" ]
[ [ "torch.nn.Dropout", "torch.unsqueeze", "torch.nn.Linear", "torch.nn.functional.sigmoid", "torch.nn.functional.relu" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
mitiku1/Emopy-Multi-Input-
[ "b520eb3f3d121c9d456a52315f1fd78ef43f74fd" ]
[ "train/__main__.py" ]
[ "import argparse\nfrom train import start_training\nimport cv2\nfrom skimage import feature\nimport numpy as np\nimport dlib\nimport tensorflow as tf \nimport keras \n\ndef get_cmd_args():\n \"\"\" Parse user command line arguments\"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-d\",\"--dataset_dir\",default=\"dataset\",type=str)\n parser.add_argument(\"-e\",\"--epoch\",default=10,type=int)\n parser.add_argument(\"-b\",\"--batch\",default=100,type=int)\n parser.add_argument(\"-s\",\"--step\",default=1000,type=int)\n parser.add_argument(\"-l\",\"--lr\",default=1e-4,type=float)\n parser.add_argument(\"-i\",\"--input_shape\",nargs=3,type=int,default=[48,48,1])\n parser.add_argument(\"-m\",\"--model_output\",type=str,default=\"model\")\n parser.add_argument(\"-f\",\"--features\",type=str,default=\"all\")\n\n\n args = parser.parse_args()\n return args\n\ndef main():\n \"\"\"Start of training program.\n \"\"\"\n np.random.seed(1)\n tf.set_random_seed(2)\n args = get_cmd_args()\n if args.input_shape[2]!=1:\n raise Exception(\"Currenly tested for only gray scale images. input_shape should be [height,width,1]\")\n start_training(args)\n \n\n\n\nif __name__ == '__main__':\n main()" ]
[ [ "tensorflow.set_random_seed", "numpy.random.seed" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] } ]
meliao/fourier_neural_operator
[ "216915c6f1acd0651c7203bc8f16824efc495c5f", "216915c6f1acd0651c7203bc8f16824efc495c5f", "216915c6f1acd0651c7203bc8f16824efc495c5f" ]
[ "experiments/21_use_other_frequencies/train_models.py", "experiments/28_systematic_FNO_dist/train_models_with_rescaling.py", "experiments/26_train_on_FNO_IC_distribution/plotting_utils.py" ]
[ "\"\"\"\n@author: Zongyi Li\nThis file is the Fourier Neural Operator for 1D problem such as the (time-independent) Burgers equation discussed in Section 5.1 in the [paper](https://arxiv.org/pdf/2010.08895.pdf).\n\"\"\"\n\nimport logging\nimport os\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n# import torch.fft as fft\nfrom torch.nn.parameter import Parameter\nimport scipy.io as sio\n\nimport operator\nfrom functools import reduce\nfrom functools import partial\nfrom timeit import default_timer\n\ntorch.manual_seed(0)\nnp.random.seed(0)\n\n\nclass SpectralConv1dModes(nn.Module):\n def __init__(self, in_channels, out_channels, modes1):\n super(SpectralConv1dModes, self).__init__()\n\n \"\"\"\n 1D Fourier layer. It does FFT, linear transform, and Inverse FFT.\n \"\"\"\n\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.modes_low = modes1[0] #Number of Fourier modes to multiply, at most floor(N/2) + 1\n self.modes_high = modes1[0] #Number of Fourier modes to multiply, at most floor(N/2) + 1\n self.n_modes = self.modes_high - self.modes_low + 1\n # self.n_modes = len(modes1)\n self.scale = (1 / (in_channels*out_channels))\n self.weights1 = nn.Parameter(self.scale * torch.rand(in_channels, out_channels, self.n_modes, dtype=torch.cfloat))\n\n # Complex multiplication\n def compl_mul1d(self, input, weights):\n # (batch, in_channel, x ), (in_channel, out_channel, x) -> (batch, out_channel, x)\n return torch.einsum(\"bix,iox->box\", input, weights)\n\n def forward(self, x):\n batchsize = x.shape[0]\n #Compute Fourier coeffcients up to factor of e^(- something constant)\n x_ft = torch.fft.rfft(x)\n\n # Multiply relevant Fourier modes\n out_ft = torch.zeros(batchsize, self.out_channels, x.size(-1)//2 + 1, device=x.device, dtype=torch.cfloat)\n out_ft[:, :, self.modes_low:self.modes_high] = self.compl_mul1d(x_ft[:, :, self.modes_low:self.modes_high], self.weights1)\n\n #Return to physical space\n x = torch.fft.irfft(out_ft, n=x.size(-1))\n return x\n\n\nclass FNO1dComplexChooseModes(nn.Module):\n def __init__(self, modes, width):\n super(FNO1dComplexChooseModes, self).__init__()\n\n \"\"\"\n The overall network. It contains 4 layers of the Fourier layer.\n 1. Lift the input to the desire channel dimension by self.fc0 .\n 2. 4 layers of the integral operators u' = (W + K)(u).\n W defined by self.w; K defined by self.conv .\n 3. Project from the channel space to the output space by self.fc1 and self.fc2 .\n\n input: the solution of the initial condition and location (Re(a(x)), Im(a(x)), x)\n input shape: (batchsize, x=s, c=3)\n output: the solution of a later timestep\n output shape: (batchsize, x=s, c=2)\n \"\"\"\n\n self.modes1 = modes\n self.width = width\n self.fc0 = nn.Linear(3, self.width) # input channel is 3: (Re(a(x)), Im(a(x)), x)\n\n self.conv0 = SpectralConv1dModes(self.width, self.width, self.modes1)\n self.conv1 = SpectralConv1dModes(self.width, self.width, self.modes1)\n self.conv2 = SpectralConv1dModes(self.width, self.width, self.modes1)\n self.conv3 = SpectralConv1dModes(self.width, self.width, self.modes1)\n self.w0 = nn.Conv1d(self.width, self.width, 1)\n self.w1 = nn.Conv1d(self.width, self.width, 1)\n self.w2 = nn.Conv1d(self.width, self.width, 1)\n self.w3 = nn.Conv1d(self.width, self.width, 1)\n\n\n self.fc1 = nn.Linear(self.width, 128)\n self.fc2 = nn.Linear(128, 2)\n\n def forward(self, x):\n\n x = self.fc0(x)\n x = x.permute(0, 2, 1)\n\n x1 = self.conv0(x)\n x2 = self.w0(x)\n x = x1 + x2\n x = F.relu(x)\n\n x1 = self.conv1(x)\n x2 = self.w1(x)\n x = x1 + x2\n x = F.relu(x)\n\n x1 = self.conv2(x)\n x2 = self.w2(x)\n x = x1 + x2\n x = F.relu(x)\n\n x1 = self.conv3(x)\n x2 = self.w3(x)\n x = x1 + x2\n\n x = x.permute(0, 2, 1)\n x = self.fc1(x)\n x = F.relu(x)\n x = self.fc2(x)\n return torch.view_as_complex(x)\n\nclass OneStepDataSet(torch.utils.data.Dataset):\n def __init__(self, X, t_grid, x_grid):\n super(OneStepDataSet, self).__init__()\n assert X.shape[1] == t_grid.shape[-1]\n self.X = torch.tensor(X, dtype=torch.cfloat)\n self.t = torch.tensor(t_grid.flatten(), dtype=torch.float)\n self.x_grid = torch.tensor(x_grid, dtype=torch.float).view(-1, 1)\n self.n_tsteps = self.t.shape[0] - 1\n self.n_batches = self.X.shape[0]\n self.dataset_len = self.n_tsteps * self.n_batches\n\n def make_x_train(self, x_in):\n x_in = torch.view_as_real(x_in)\n y = torch.cat([x_in, self.x_grid], axis=1)\n return y\n\n def __getitem__(self, idx):\n idx_original = idx\n t_idx = int(idx % self.n_tsteps) + 1\n idx = int(idx // self.n_tsteps)\n batch_idx = int(idx % self.n_batches)\n x = self.make_x_train(self.X[batch_idx, t_idx - 1]) #.reshape(self.output_shape)\n y = self.X[batch_idx, t_idx] #.reshape(self.output_shape)\n return x, y\n\n def __len__(self):\n return self.dataset_len\n\n def __repr__(self):\n return \"OneStepDataSet with length {}, t_grid {}, n_batches {}\".format(self.dataset_len,\n self.t,\n self.n_batches)\n\ndef write_result_to_file(fp, missing_str='', **trial):\n \"\"\"Write a line to a tab-separated file saving the results of a single\n trial.\n\n Parameters\n ----------\n fp : str\n Output filepath\n missing_str : str\n (Optional) What to print in the case of a missing trial value\n **trial : dict\n One trial result. Keys will become the file header\n Returns\n -------\n None\n\n \"\"\"\n header_lst = list(trial.keys())\n header_lst.sort()\n if not os.path.isfile(fp):\n header_line = \"\\t\".join(header_lst) + \"\\n\"\n with open(fp, 'w') as f:\n f.write(header_line)\n trial_lst = [str(trial.get(i, missing_str)) for i in header_lst]\n trial_line = \"\\t\".join(trial_lst) + \"\\n\"\n with open(fp, 'a') as f:\n f.write(trial_line)\n\ndef MSE(x, y):\n errors = x - y\n return torch.mean(torch.square(errors.abs()))\n\ndef l2_normalized_error(pred, actual):\n errors = pred - actual\n error_norms = torch.linalg.norm(errors, dim=1, ord=2)\n actual_norms = torch.linalg.norm(actual, dim=1, ord=2)\n return torch.mean(torch.divide(error_norms, actual_norms))\n\ndef train_loop(model, optimizer, scheduler, start_epoch, end_epoch, device, train_data_loader, train_df, do_testing,\n test_every_n, test_data_loader, test_df, model_path, results_dd):\n \"\"\"This is the main training loop\n\n Parameters\n ----------\n model : torch.nn.Model\n Model to train.\n optimizer : torch.optimizer\n Optimization algorithm.\n scheduler : torch.lr_scheduler\n Learning rate scheduler.\n epochs : int\n Number of full passes over the training dataset.\n device : torch.device\n Determines whether a GPU is used.\n train_data_loader : torch.DataLoader\n Object which iterates over train dataset.\n train_df : str\n Filepath to save intermediate training results.\n do_testing : bool\n Whether to test the model throughout training.\n test_every_n : int\n How often to do said testing.\n test_data_loader : torch.DataLoader\n iterates over test dataset.\n test_df : str\n Filepath to save intermediate test results.\n model_path : str\n Filepath (formattable with epoch number) to save model.\n\n Returns\n -------\n model\n Trained model.\n \"\"\"\n\n train_dd = {}\n test_dd = {}\n logging.info(\"Beginning training for {} epochs\".format(end_epoch - start_epoch))\n\n model.train()\n t0_train = default_timer()\n for ep in range(start_epoch, end_epoch):\n # model.train()\n t1 = default_timer()\n train_mse = 0\n train_l2 = 0\n for x, y in train_data_loader:\n x, y = x.to(device), y.to(device)\n # print(\"X SHAPE: {}, Y SHAPE: {}\".format(x.shape, y.shape))\n\n optimizer.zero_grad()\n out = model(x)\n\n mse = MSE(out, y)\n mse.backward()\n # loss.backward()\n optimizer.step()\n\n train_mse += mse.item()\n\n scheduler.step()\n # model.eval()\n\n train_mse /= len(train_data_loader)\n\n t2 = default_timer()\n logging.info(\"Epoch: {}, time: {:.2f}, train_mse: {:.4f}\".format(ep, t2-t1, train_mse))\n train_dd['epoch'] = ep\n train_dd['MSE'] = train_mse\n train_dd['time'] = t2-t1\n write_result_to_file(train_df, **train_dd)\n\n ########################################################\n # Intermediate testing and saving\n ########################################################\n if ep % test_every_n == 0:\n test_mse = 0.\n test_l2_norm_error = 0.\n if do_testing:\n model.eval()\n with torch.no_grad():\n for x, y in test_data_loader:\n x, y = x.to(device), y.to(device)\n\n out = model(x)\n\n mse = MSE(out, y)\n test_mse += mse.item()\n\n l2_err = l2_normalized_error(out, y)\n test_l2_norm_error += l2_err.item()\n model.train()\n\n test_mse /= len(test_data_loader)\n test_l2_norm_error /= len(test_data_loader)\n\n test_dd['test_mse'] = test_mse\n test_dd['test_l2_normalized_error'] = test_l2_norm_error\n test_dd['epoch'] = ep\n\n write_result_to_file(test_df, **test_dd)\n logging.info(\"Test: Epoch: {}, test_mse: {:.4f}\".format(ep, test_mse))\n torch.save(model, model_path.format(ep))\n\n torch.save(model, model_path.format(end_epoch))\n if end_epoch - start_epoch > 0:\n results_dd['train_mse'] = train_mse\n results_dd['test_mse'] = test_mse\n return model\n\ndef setup_training(args, device, batch_size=1024, learning_rate=0.001, step_size=100, gamma=0.5):\n\n ################################################################\n # create results_dd\n ################################################################\n results_dd = {}\n #################################################################\n # read training data\n ################################################################\n\n d = sio.loadmat(args.data_fp)\n usol = d['output'][:,[0,args.time_idx]]\n t_grid = d['t'][:,[0,args.time_idx]]\n x_grid = d['x']\n logging.info(\"USOL SHAPE {}, T_GRID SHAPE: {}, X_GRID SHAPE: {}\".format(usol.shape,\n t_grid.shape,\n x_grid.shape))\n\n train_dataset = OneStepDataSet(usol, t_grid, x_grid)\n logging.info(\"Dataset: {}\".format(train_dataset))\n results_dd['ntrain'] = len(train_dataset)\n results_dd['prediction_time'] = args.time_idx\n\n train_data_loader = torch.utils.data.DataLoader(train_dataset,\n batch_size=batch_size,\n shuffle=True)\n\n ################################################################\n # read testing data\n ################################################################\n if not args.no_test:\n\n d_test = sio.loadmat(args.test_data_fp)\n usol_test = d_test['output'][:,[0,args.time_idx]]\n t_grid_test = d_test['t'][:,[0,args.time_idx]]\n x_grid_test = d_test['x']\n\n test_dataset = OneStepDataSet(usol_test, t_grid_test, x_grid_test)\n logging.info(\"Test Dataset: {}\".format(test_dataset))\n results_dd['ntest'] = len(test_dataset)\n\n test_data_loader = torch.utils.data.DataLoader(test_dataset,\n batch_size=batch_size,\n shuffle=True)\n\n ##################################################################\n # initialize model and optimizer\n ##################################################################\n args.freq_modes[0].sort()\n model_params = {'width': args.width, 'modes':args.freq_modes[0]}\n\n model = FNO1dComplexChooseModes(width=args.width, modes=args.freq_modes[0]).to(device)\n logging.info(\"Model freq modes: {}\".format(model.modes1))\n\n results_dd.update(model_params)\n\n optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\n scheduler = torch.optim.lr_scheduler.StepLR(optimizer,\n step_size=step_size,\n gamma=gamma)\n results_dd['learning_rate'] = learning_rate\n\n ##################################################################\n # Call training loop\n ##################################################################\n logging.info(\"Starting FNO training\")\n model = train_loop(model=model,\n optimizer=optimizer,\n scheduler=scheduler,\n start_epoch=0,\n end_epoch=args.epochs,\n device=device,\n train_data_loader=train_data_loader,\n train_df=args.train_df,\n do_testing=(not args.no_test),\n test_every_n=100,\n test_data_loader=test_data_loader,\n test_df=args.test_df,\n model_path=args.model_fp,\n results_dd=results_dd)\n return model, results_dd\n\ndef main(args):\n # Figure out CUDA\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n logging.info(\"Running computation on device: {}\".format(device))\n\n ################################################################\n # Set up and do training\n ################################################################\n\n lr = (10 ** args.lr_exp)\n\n model, results_dd = setup_training(args, device, learning_rate=lr)\n\n if args.results_fp is not None:\n write_result_to_file(args.results_fp, **results_dd)\n logging.info(\"Wrote results to {}\".format(args.results_fp))\n else:\n logging.info(\"No results_fp specified, so here are the results\")\n logging.info(results_dd)\n\n logging.info(\"Finished\")\n\n\nif __name__ == '__main__':\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('--data_fp')\n parser.add_argument('--test_data_fp')\n parser.add_argument('--results_fp')\n parser.add_argument('--model_fp')\n parser.add_argument('--train_df')\n parser.add_argument('--test_df')\n parser.add_argument('--ntrain', type=int)\n parser.add_argument('--ntest', type=int)\n parser.add_argument('--time_idx', type=int, default=1)\n parser.add_argument('--lr_exp', type=int, default=-3)\n parser.add_argument('--epochs', type=int)\n parser.add_argument('--freq_modes', type=int, nargs=2, action='append')\n parser.add_argument('--width', type=int, default=64)\n parser.add_argument('--time_subsample', type=int, default=1)\n parser.add_argument('--no_test', default=False, action='store_true')\n\n args = parser.parse_args()\n fmt = \"%(asctime)s:FNO: %(levelname)s - %(message)s\"\n time_fmt = '%Y-%m-%d %H:%M:%S'\n logging.basicConfig(level=logging.INFO,\n format=fmt,\n datefmt=time_fmt)\n main(args)\n", "\"\"\"\n@author: Zongyi Li\nThis file is the Fourier Neural Operator for 1D problem such as the (time-independent) Burgers equation discussed in Section 5.1 in the [paper](https://arxiv.org/pdf/2010.08895.pdf).\n\"\"\"\n\nimport logging\nimport os\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n# import torch.fft as fft\nfrom torch.nn.parameter import Parameter\nimport scipy.io as sio\nimport scipy.interpolate as sint\n\nimport operator\nfrom functools import reduce\nfrom functools import partial\nfrom timeit import default_timer\n\ntorch.manual_seed(0)\nnp.random.seed(0)\n\n\nclass SpectralConv1d(nn.Module):\n def __init__(self, in_channels, out_channels, modes1):\n super(SpectralConv1d, self).__init__()\n\n \"\"\"\n 1D Fourier layer. It does FFT, linear transform, and Inverse FFT.\n \"\"\"\n\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.modes1 = modes1 #Number of Fourier modes to multiply, at most floor(N/2) + 1\n\n self.scale = (1 / (in_channels*out_channels))\n self.weights1 = nn.Parameter(self.scale * torch.rand(in_channels, out_channels, self.modes1, dtype=torch.cfloat))\n\n # Complex multiplication\n def compl_mul1d(self, input, weights):\n # (batch, in_channel, x ), (in_channel, out_channel, x) -> (batch, out_channel, x)\n return torch.einsum(\"bix,iox->box\", input, weights)\n\n def forward(self, x):\n batchsize = x.shape[0]\n #Compute Fourier coeffcients up to factor of e^(- something constant)\n x_ft = torch.fft.rfft(x)\n\n # Multiply relevant Fourier modes\n out_ft = torch.zeros(batchsize, self.out_channels, x.size(-1)//2 + 1, device=x.device, dtype=torch.cfloat)\n out_ft[:, :, :self.modes1] = self.compl_mul1d(x_ft[:, :, :self.modes1], self.weights1)\n\n #Return to physical space\n x = torch.fft.irfft(out_ft, n=x.size(-1))\n return x\n\n\nclass FNO1dComplexTime(nn.Module):\n def __init__(self, modes, width):\n super(FNO1dComplexTime, self).__init__()\n\n \"\"\"\n The overall network. It contains 4 layers of the Fourier layer.\n 1. Lift the input to the desire channel dimension by self.fc0 .\n 2. 4 layers of the integral operators u' = (W + K)(u).\n W defined by self.w; K defined by self.conv .\n 3. Project from the channel space to the output space by self.fc1 and self.fc2 .\n\n input: the solution of the initial condition and location (Re(a(x)), Im(a(x)), x)\n input shape: (batchsize, x=s, c=3)\n output: the solution of a later timestep\n output shape: (batchsize, x=s, c=2)\n \"\"\"\n\n self.modes1 = modes\n self.width = width\n self.fc0 = nn.Linear(4, self.width) # input channel is 3: (Re(a(x)), Im(a(x)), x)\n\n self.conv0 = SpectralConv1d(self.width, self.width, self.modes1)\n self.conv1 = SpectralConv1d(self.width, self.width, self.modes1)\n self.conv2 = SpectralConv1d(self.width, self.width, self.modes1)\n self.conv3 = SpectralConv1d(self.width, self.width, self.modes1)\n self.w0 = nn.Conv1d(self.width, self.width, 1)\n self.w1 = nn.Conv1d(self.width, self.width, 1)\n self.w2 = nn.Conv1d(self.width, self.width, 1)\n self.w3 = nn.Conv1d(self.width, self.width, 1)\n\n\n self.fc1 = nn.Linear(self.width, 128)\n self.fc2 = nn.Linear(128, 2)\n\n def forward(self, x, t):\n # print(\"INPUT X SHAPE: {} DTYPE: {}\".format(x.shape, x.dtype))\n # print(\"INPUT T SHAPE: {} DTYPE: {}\".format(t.shape, t.dtype))\n # print(\"T: {}\".format(t))\n # print(\"T0: {}\".format(t[0]))\n # print(\"T1: {}\".format(t[1]))\n # print(\"INPUT T SHAPE: {} DTYPE: {}\".format(t.shape, t.dtype))\n # o = torch.ones((1, x.size()[1]), dtype = torch.float)\n # print(\"INPUT O SHAPE: {} DTYPE: {}\".format(o.shape, o.dtype))\n # t_arr = torch.matmul(t, o)\n t = t.view(-1, 1, 1).repeat([1, x.shape[1], 1])\n x = torch.cat([x, t], dim=2)\n\n x = self.fc0(x)\n x = x.permute(0, 2, 1)\n\n x1 = self.conv0(x)\n x2 = self.w0(x)\n x = x1 + x2\n x = F.relu(x)\n\n x1 = self.conv1(x)\n x2 = self.w1(x)\n x = x1 + x2\n x = F.relu(x)\n\n x1 = self.conv2(x)\n x2 = self.w2(x)\n x = x1 + x2\n x = F.relu(x)\n\n x1 = self.conv3(x)\n x2 = self.w3(x)\n x = x1 + x2\n\n x = x.permute(0, 2, 1)\n x = self.fc1(x)\n x = F.relu(x)\n x = self.fc2(x)\n return torch.view_as_complex(x)\n\n\nclass OneStepDataSet(torch.utils.data.Dataset):\n def __init__(self, X, t_grid, x_grid):\n super(OneStepDataSet, self).__init__()\n assert X.shape[1] == t_grid.shape[-1]\n self.X = torch.tensor(X, dtype=torch.cfloat)\n self.t = torch.tensor(t_grid.flatten(), dtype=torch.float)\n self.x_grid = torch.tensor(x_grid, dtype=torch.float).view(-1, 1)\n self.n_tsteps = self.t.shape[0] - 1\n self.n_batches = self.X.shape[0]\n self.dataset_len = self.n_tsteps * self.n_batches\n\n def make_x_train(self, x_in):\n x_in = torch.view_as_real(x_in)\n y = torch.cat([x_in, self.x_grid], axis=1)\n return y\n\n def __getitem__(self, idx):\n idx_original = idx\n t_idx = int(idx % self.n_tsteps) + 1\n idx = int(idx // self.n_tsteps)\n batch_idx = int(idx % self.n_batches)\n x = self.make_x_train(self.X[batch_idx, t_idx - 1]) #.reshape(self.output_shape)\n y = self.X[batch_idx, t_idx] #.reshape(self.output_shape)\n t = self.t[1]\n return x, y, t\n\n def __len__(self):\n return self.dataset_len\n\n def __repr__(self):\n return \"OneStepDataSet with length {}, n_tsteps {}, n_batches {}\".format(self.dataset_len,\n self.n_tsteps,\n self.n_batches)\n\n\nclass TimeScalingDataSet(torch.utils.data.Dataset):\n def __init__(self, X, t_grid, x_grid, ones_vector=False, do_rescaling=True):\n \"\"\"\n u(t^2, x) = NLSSolve(t^2, g(x), r)\n u(t^2, tx) = (1/t) * NLSSolve(1, t*g(tx), r/t)\n \"\"\"\n super(TimeScalingDataSet, self).__init__()\n\n usol_n_t = X.shape[1]\n t_n_t = t_grid.shape[-1]\n assert usol_n_t == t_n_t, \"{} != {}\".format(usol_n_t, t_n_t)\n\n self.X = torch.tensor(X, dtype=torch.cfloat)\n self.t = torch.tensor(t_grid.flatten(), dtype=torch.float)\n self.x_grid = torch.tensor(x_grid, dtype=torch.float).view(-1,1)\n self.n_x = self.x_grid.shape[0]\n self.lb = torch.min(self.x_grid)\n self.ub = torch.max(self.x_grid)\n self.d_x = (self.ub - self.lb) / (self.n_x - 1)\n self.n_tsteps = self.t.shape[0] - 1\n self.n_batches = self.X.shape[0]\n self.ones_vector = ones_vector\n\n # self.time_indices is an array of tuples. (start_idx, end_idx)\n self.time_indices = [ (start, end) for end in range(1, self.t.shape[0]) for start in range(end)]\n self.n_t_pairs = len(self.time_indices)\n self.dataset_len = self.n_t_pairs * self.n_batches\n\n # rescaled_ICs has indices (batch_idx, start_t_idx, end_t_idx, grid)\n if do_rescaling:\n self.rescaled_ICs = torch.zeros(self.n_batches, usol_n_t, usol_n_t, self.n_x, dtype=torch.cfloat)\n self.make_rescaled_ICs()\n\n def make_x_train_rescaled(self, x_in, t_in):\n # root_t = torch.sqrt(t_in)\n # x_grid = torch.linspace(self.lb / root_t, self.ub / root_t, self.x_grid.shape[0]).view(-1,1)\n # x_in = root_t * x_in\n # x_in = torch.view_as_real(x_in)\n # y = torch.cat([x_in, x_grid], axis=1)\n\n root_t = torch.sqrt(t_in)\n root_t_ceil = int(np.ceil(root_t))\n x_grid = torch.linspace(self.lb * root_t_ceil / root_t, self.ub * root_t_ceil / root_t, self.n_x * root_t_ceil)\n\n vals = root_t * x_in.repeat(root_t_ceil)\n\n if root_t_ceil % 2 == 0:\n vals = torch.roll(vals, int(self.n_x/2))\n # print(\"VALS\", vals.shape)\n\n # print(\"X_GRID\", x_grid.shape)\n\n interpolation_f_real = sint.interp1d(x_grid, vals.real, kind='cubic')\n interpolation_f_imag = sint.interp1d(x_grid, vals.imag, kind='cubic')\n\n out_real = interpolation_f_real(self.x_grid)\n out_imag = interpolation_f_imag(self.x_grid)\n # print(\"OUT REAL\", out_real.shape)\n y = torch.cat([torch.tensor(out_real,dtype=torch.float),\n torch.tensor(out_imag, dtype=torch.float), self.x_grid], axis=1)\n # print(\"Y\", y.shape)\n return y\n\n def _rescale(self, x_in, t_in):\n root_t = torch.sqrt(t_in)\n root_t_ceil = int(np.ceil(root_t))\n x_grid = torch.linspace(self.lb * root_t_ceil / root_t, self.ub * root_t_ceil / root_t, self.n_x * root_t_ceil)\n\n vals = root_t * x_in.repeat(root_t_ceil)\n\n if root_t_ceil % 2 == 0:\n vals = torch.roll(vals, int(self.n_x/2))\n interpolation_f_real = sint.interp1d(x_grid, vals.real, kind='cubic')\n interpolation_f_imag = sint.interp1d(x_grid, vals.imag, kind='cubic')\n\n out_real = interpolation_f_real(self.x_grid)\n out_imag = interpolation_f_imag(self.x_grid)\n out = torch.view_as_complex(torch.cat([torch.tensor(out_real, dtype=torch.float),\n torch.tensor(out_imag, dtype=torch.float)], axis=1))\n return out\n def make_rescaled_ICs(self):\n for b_idx in range(self.n_batches):\n# X_ic = self.X[b_idx, 0]\n for start_t_idx, end_t_idx in self.time_indices:\n time_delta = self.t[end_t_idx] - self.t[start_t_idx]\n X_ic = self.X[b_idx, start_t_idx]\n self.rescaled_ICs[b_idx, start_t_idx, end_t_idx] = self._rescale(X_ic, time_delta)\n\n def make_x_train_rescaled_batched(self, x_in, t_in):\n root_t = torch.sqrt(t_in)\n # print(root_t.shape)\n x_grid = torch.linspace(self.lb / root_t, self.ub / root_t, self.x_grid.shape[0]).view(-1,1)\n # print(x_grid.shape)\n x_grid = x_grid.repeat(x_in.shape[0], 1, 1)\n # print(x_grid.shape)\n x_in = root_t * x_in\n x_in = torch.view_as_real(x_in)\n # print(x_in.shape)\n y = torch.cat([x_in, x_grid], axis=-1)\n return y\n\n def make_x_train(self, x_in):\n x_in = torch.view_as_real(x_in)\n return torch.cat([x_in, self.x_grid], axis=1)\n\n def __getitem__(self, idx):\n \"\"\"\n idx gets decomposed into t_idx and batch_idx.\n\n self.t[t_idx] gives the prediction time\n\n return: rescaled initial conditions, y, t\n \"\"\"\n print(\"IDX\", str(idx))\n idx_original = idx\n t_idx = int(idx % self.n_t_pairs)\n print(\"T_IDX\", str(t_idx))\n idx = int(idx // self.n_t_pairs)\n batch_idx = int(idx % self.n_batches)\n print(\"BATCH_IDX\", str(batch_idx))\n start_time_idx, end_time_idx = self.time_indices[t_idx]\n print(\"START_TIME_IDX, END_TIME_IDX, {}, {}\".format(start_time_idx, end_time_idx))\n x = self.make_x_train(self.rescaled_ICs[batch_idx, start_time_idx, end_time_idx])\n y = self.X[batch_idx, end_time_idx] #.reshape(self.output_shape)\n t = self.t[end_time_idx] - self.t[start_time_idx]\n if self.ones_vector:\n return x, y, t, self.t[1]\n else:\n return x, y, t\n\n def __len__(self):\n return self.dataset_len\n\n def __repr__(self):\n return \"TimeScalingDataSet with length {}, n_batches {}, t {}\".format(self.dataset_len,\n self.n_batches,\n self.t)\n\n\ndef write_result_to_file(fp, missing_str='', **trial):\n \"\"\"Write a line to a tab-separated file saving the results of a single\n trial.\n\n Parameters\n ----------\n fp : str\n Output filepath\n missing_str : str\n (Optional) What to print in the case of a missing trial value\n **trial : dict\n One trial result. Keys will become the file header\n Returns\n -------\n None\n\n \"\"\"\n header_lst = list(trial.keys())\n header_lst.sort()\n if not os.path.isfile(fp):\n header_line = \"\\t\".join(header_lst) + \"\\n\"\n with open(fp, 'w') as f:\n f.write(header_line)\n trial_lst = [str(trial.get(i, missing_str)) for i in header_lst]\n trial_line = \"\\t\".join(trial_lst) + \"\\n\"\n with open(fp, 'a') as f:\n f.write(trial_line)\n\n\ndef MSE(x, y):\n errors = x - y\n return torch.mean(torch.square(errors.abs()))\n\n\ndef l2_normalized_error(pred, actual):\n errors = pred - actual\n error_norms = torch.linalg.norm(errors, dim=1, ord=2)\n actual_norms = torch.linalg.norm(actual, dim=1, ord=2)\n return torch.mean(torch.divide(error_norms, actual_norms))\n\n\ndef train_loop(model, optimizer, scheduler, start_epoch, end_epoch, l1_weight, device, train_data_loader, train_df, do_testing,\n test_every_n, test_data_loader, test_df, model_path, results_dd):\n \"\"\"This is the main training loop\n\n Parameters\n ----------\n model : torch.nn.Model\n Model to train.\n optimizer : torch.optimizer\n Optimization algorithm.\n scheduler : torch.lr_scheduler\n Learning rate scheduler.\n epochs : int\n Number of full passes over the training dataset.\n device : torch.device\n Determines whether a GPU is used.\n train_data_loader : torch.DataLoader\n Object which iterates over train dataset.\n train_df : str\n Filepath to save intermediate training results.\n do_testing : bool\n Whether to test the model throughout training.\n test_every_n : int\n How often to do said testing.\n test_data_loader : torch.DataLoader\n iterates over test dataset.\n test_df : str\n Filepath to save intermediate test results.\n model_path : str\n Filepath (formattable with epoch number) to save model.\n\n Returns\n -------\n model\n Trained model.\n \"\"\"\n\n train_dd = {}\n test_dd = {}\n logging.info(\"Beginning training for {} epochs\".format(end_epoch - start_epoch))\n\n model.train()\n t0_train = default_timer()\n for ep in range(start_epoch, end_epoch):\n # model.train()\n t1 = default_timer()\n train_mse = 0\n train_l2 = 0\n for x, y, t_actual in train_data_loader:\n optimizer.zero_grad()\n\n x, y = x.to(device), y.to(device)\n t_actual = t_actual.to(device)\n # t_dummy = t_dummy.to(device)\n\n\n # t_actual_sqrt = torch.sqrt(t_actual)\n out = model(x, t_actual) #,t_dummy)\n t_actual_sqrt = torch.sqrt(t_actual).view(-1,1).repeat(1,out.shape[1])\n #print(t_actual_sqrt.shape, out.shape)\n # for j in range(t_actual_sqrt.shape[0]):\n # print(t_actual_sqrt[j])\n # print(t_actual_sqrt.shape, out.shape)\n out = torch.div(out, t_actual_sqrt)\n\n mse = MSE(out, y)\n # l1_nrm = torch.tensor(0.)\n # for p in model.parameters():\n # l1_nrm += p.abs().sum()\n # loss = mse + l1_weight * l1_nrm\n mse.backward()\n # loss.backward()\n optimizer.step()\n\n train_mse += mse.item()\n\n scheduler.step()\n # model.eval()\n\n train_mse /= len(train_data_loader)\n\n t2 = default_timer()\n logging.info(\"Epoch: {}, time: {:.2f}, train_mse: {:.4f}\".format(ep, t2-t1, train_mse))\n train_dd['epoch'] = ep\n train_dd['MSE'] = train_mse\n train_dd['time'] = t2-t1\n write_result_to_file(train_df, **train_dd)\n\n ########################################################\n # Intermediate testing and saving\n ########################################################\n if ep % test_every_n == 0:\n test_mse = 0.\n test_l2_norm_error = 0.\n if do_testing:\n model.eval()\n with torch.no_grad():\n for x, y, t_actual in test_data_loader:\n x, y = x.to(device), y.to(device)\n t_actual = t_actual.to(device)\n # t_dummy = t_dummy.to(device)\n\n\n t_actual_sqrt = torch.sqrt(t_actual).view(-1,1).repeat(1, out.shape[1])\n out = model(x, t_actual) #,t_dummy)\n out = torch.div(out, t_actual_sqrt)\n\n mse = MSE(out, y)\n test_mse += mse.item()\n\n l2_err = l2_normalized_error(out, y)\n test_l2_norm_error += l2_err.item()\n model.train()\n\n test_mse /= len(test_data_loader)\n test_l2_norm_error /= len(test_data_loader)\n\n test_dd['test_mse'] = test_mse\n test_dd['test_l2_normalized_error'] = test_l2_norm_error\n test_dd['epoch'] = ep\n\n write_result_to_file(test_df, **test_dd)\n logging.info(\"Test: Epoch: {}, test_mse: {:.4f}\".format(ep, test_mse))\n torch.save(model, model_path.format(ep))\n\n torch.save(model, model_path.format(end_epoch))\n if end_epoch - start_epoch > 0:\n results_dd['train_mse'] = train_mse\n results_dd['test_mse'] = test_mse\n return model\n\ndef setup_training(args, device, batch_size=1024, learning_rate=0.001, step_size=100, gamma=0.5, l1_weight=0.):\n\n ################################################################\n # create results_dd\n ################################################################\n results_dd = {}\n #################################################################\n # read training data\n ################################################################\n\n d = sio.loadmat(args.data_fp)\n usol = d['output'][:, :args.time_idx+1]\n t_grid = d['t'][:, :args.time_idx+1]\n x_grid = d['x']\n logging.info(\"USOL SHAPE {}, T_GRID SHAPE: {}, X_GRID SHAPE: {}\".format(usol.shape,\n t_grid.shape,\n x_grid.shape))\n\n train_dataset = TimeScalingDataSet(usol, t_grid, x_grid, ones_vector=False)\n logging.info(\"Dataset: {}\".format(train_dataset))\n results_dd['ntrain'] = len(train_dataset)\n results_dd['prediction_time'] = args.time_idx\n\n train_data_loader = torch.utils.data.DataLoader(train_dataset,\n batch_size=batch_size,\n shuffle=True)\n\n ################################################################\n # read testing data\n ################################################################\n if not args.no_test:\n\n d_test = sio.loadmat(args.test_data_fp)\n usol_test = d_test['output'][:,:args.time_idx+1]\n t_grid_test = d_test['t'][:,:args.time_idx+1]\n x_grid_test = d_test['x']\n\n test_dataset = TimeScalingDataSet(usol_test, t_grid_test, x_grid_test, ones_vector=False)\n logging.info(\"Test Dataset: {}\".format(test_dataset))\n results_dd['ntest'] = len(test_dataset)\n\n test_data_loader = torch.utils.data.DataLoader(test_dataset,\n batch_size=batch_size,\n shuffle=True)\n\n ##################################################################\n # initialize model and optimizer\n ##################################################################\n model_params = {'width': args.width, 'modes':args.freq_modes}\n\n model = FNO1dComplexTime(width=args.width, modes=args.freq_modes).to(device)\n\n results_dd.update(model_params)\n\n optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\n scheduler = torch.optim.lr_scheduler.StepLR(optimizer,\n step_size=step_size,\n gamma=gamma)\n results_dd['learning_rate'] = learning_rate\n\n ##################################################################\n # Call training loop\n ##################################################################\n logging.info(\"Starting FNO training\")\n model = train_loop(model=model,\n optimizer=optimizer,\n scheduler=scheduler,\n start_epoch=0,\n end_epoch=args.epochs,\n l1_weight=l1_weight,\n device=device,\n train_data_loader=train_data_loader,\n train_df=args.train_df,\n do_testing=(not args.no_test),\n test_every_n=100,\n test_data_loader=test_data_loader,\n test_df=args.test_df,\n model_path=args.model_fp,\n results_dd=results_dd)\n return model, results_dd\n\ndef main(args):\n # Figure out CUDA\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n logging.info(\"Running computation on device: {}\".format(device))\n\n ################################################################\n # Set up and do training\n ################################################################\n\n lr = (10 ** args.lr_exp)\n\n if args.l1_exp is not None:\n l1_weight = (10 ** args.l1_exp)\n else:\n l1_weight = 0.\n\n model, results_dd = setup_training(args, device, learning_rate=lr, l1_weight=l1_weight)\n\n if args.results_fp is not None:\n write_result_to_file(args.results_fp, **results_dd)\n logging.info(\"Wrote results to {}\".format(args.results_fp))\n else:\n logging.info(\"No results_fp specified, so here are the results\")\n logging.info(results_dd)\n\n logging.info(\"Finished\")\n\n\nif __name__ == '__main__':\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('--data_fp')\n parser.add_argument('--results_fp')\n parser.add_argument('--test_data_fp')\n parser.add_argument('--model_fp')\n parser.add_argument('--train_df')\n parser.add_argument('--test_df')\n parser.add_argument('--time_idx', type=int, default=1)\n parser.add_argument('--lr_exp', type=int, default=-3)\n parser.add_argument('--l1_exp', type=int, default=None)\n parser.add_argument('--epochs', type=int)\n parser.add_argument('--freq_modes', type=int, default=16)\n parser.add_argument('--width', type=int, default=64)\n parser.add_argument('--time_subsample', type=int, default=1)\n parser.add_argument('--no_test', default=False, action='store_true')\n\n args = parser.parse_args()\n fmt = \"%(asctime)s:FNO: %(levelname)s - %(message)s\"\n time_fmt = '%Y-%m-%d %H:%M:%S'\n logging.basicConfig(level=logging.INFO,\n format=fmt,\n datefmt=time_fmt)\n main(args)\n", "import matplotlib.pyplot as plt\nimport numpy as np\n\ndef plot_time_errors(errors_dd, t_grid=None, title=None, fp=None,\n log_scale=False, x_label='Time step',\n y_label='$L_2$-Normalized Errors', names_dd=None):\n \"\"\"Makes a plot visualizing an array of time-dependent errors over a set of\n test cases. Draws means and +/- 1 standard deviation error bars.\n\n Args:\n errors_dd (dict): Dictionary of 2d numpy arrays. The dictionary keys\n will be used as legend text. The numpy arrays are assumed to all be\n organized as (test_cases, time_steps).\n t_grid (iterable, optional): If specified, this will populate the x-axis\n tick labels. Defaults to None.\n title (str, optional): Figure title. Defaults to None.\n fp (str, optional): Filepath for saving. If not specified, the plot\n will be shown via `plt.show()`. Defaults to None.\n log_scale (bool, optional): Whether to plot vertical axis on log scale.\n Defaults to False.\n x_label (str, optional): X axis label. Defaults to 'Time step'.\n y_label (str, optional): Y axis label. Defaults to '$-Normalized\n Errors'.\n \"\"\"\n\n # Extract x values from the specified t_grid\n if t_grid is not None:\n x_vals = t_grid.flatten()\n n_t_steps = len(x_vals)\n else:\n # Or just make an array of integers\n keys = list(errors_dd.keys())\n data_shape = errors_dd[keys[0]].shape\n n_t_steps = data_shape[1]\n x_vals = np.arange(n_t_steps, dtype=int)\n\n fig, ax = plt.subplots()\n fig.patch.set_facecolor('white')\n\n # k is the legend text entry, v is the error array\n for k, v in errors_dd.items():\n print(\"{}: {}\".format(k, v.shape))\n if names_dd is not None:\n lab = names_dd.get(k, k)\n else:\n lab = k\n v_means = np.mean(v, axis=0)\n v_stds = np.std(v, axis=0)\n n_points = v_means.shape[-1]\n # This draws the means\n ax.plot(x_vals[:n_points], v_means, label=lab, alpha=0.7)\n # This draws the stddev bars\n ax.fill_between(x_vals[:n_points],\n v_means + v_stds,\n v_means - v_stds,\n alpha=0.3)\n ax.legend()\n\n # X axis:\n ax.set_xlabel(x_label)\n ax.set_xticks(ticks=np.arange(0, n_t_steps),)\n ax.set_xticklabels(labels=make_special_ticks(x_vals),\n rotation=45,\n ha='right'\n )\n # Y axis:\n ax.set_ylabel(y_label)\n if log_scale:\n ax.set_yscale('log')\n\n if title is not None:\n ax.set_title(title)\n fig.tight_layout()\n\n # save the figure to fp if specified, else just show it\n if fp is not None:\n plt.savefig(fp)\n else:\n plt.show()\n plt.close(fig)\n\n\ndef make_special_ticks(arr):\n \"\"\"Makes x axis tick labels for `plot_time_errors` by iterating through a\n given array\n\n Args:\n arr (iterable): The elements which will end up in the axis tick labels.\n\n Returns:\n list: the axis tick labels\n \"\"\"\n s = \"$t={} \\\\ \\\\to \\\\ t={}$\"\n return [s.format(0, i) for i in arr]\n\n\ndef plot_one_testcase_panels(preds_dd, solns, show_n_timesteps=10, alpha=0.7,\n title=None, fp=None, x_vals_dd=None,\n soln_x_vals=None, plot_errors=True):\n \"\"\"Plots a single test case solutions/predictions by producing a series of\n panels. The rows of panels each correspond to one time step, and the\n three columns are the real part, the imaginary part, and the errors.\n\n Args:\n preds_dd (dict): Dictionary of 2d numpy arrays. Each array corresponds\n to the predictions on a single test-case, and has time on the 0th\n axis and space on the 1st axis. The arrays should have matching\n shape (n_time_steps, n_grid_points). Time step 0 (assumed to be the\n initial conditions) will not be shown.\n solns (numpy array): The true solutions. 2d array with time on the 0th\n axis and space on the 1st axis. Should have shape\n (n_time_steps, n_grid_points). Time step 0 (assumed to be the\n initial conditions) will not be shown.\n show_n_timesteps (int, optional): min(show_n_timesteps, n_time_steps-1)\n will be shown. Defaults to 10.\n alpha (float, optional): Constrols satuation value. Defaults to 0.7.\n title (string, optional): Figure title. Defaults to None.\n fp (string, optional): Filepath to save the plot. If not specified, the\n plot will be shown via `plt.show`. Defaults to None.\n \"\"\"\n\n # Checking that the time axes are the same size to avoid silly off-by-one\n # plotting errors\n\n n_tsteps, grid_size = solns.shape\n for k,v in preds_dd.items():\n assert v.shape[0] == n_tsteps\n\n N_TSTEPS = min(n_tsteps - 1, show_n_timesteps)\n\n fig, ax = plt.subplots(N_TSTEPS, 2 + int(plot_errors), sharex='col', sharey=False)\n\n # This sets the figure to an image with aspect ratio 1.5x2\n fig.set_size_inches(1.5 * N_TSTEPS ,2 * N_TSTEPS)\n fig.patch.set_facecolor('white')\n ax[0,0].set_title(\"$Re(u)$\", size=20)\n ax[0,1].set_title(\"$Im(u)$\", size=20)\n if plot_errors:\n ax[0,2].set_title(\"$| u - \\\\hat u|$\", size=20)\n\n if x_vals_dd is None:\n x_vals_dd = {}\n for k,v in preds_dd.items():\n x_vals_dd[k] = np.arange(v.shape[-1]).reshape((1, v.shape[-1])).repeat(v.shape[0], axis=0)\n\n if soln_x_vals is None:\n soln_x_vals = np.arange(grid_size)\n\n for i in range(1, N_TSTEPS+1):\n # First column has Re(prediction), Re(solution)\n ax[i-1,0].plot(soln_x_vals, np.real(solns[i]), '--', alpha=alpha, label='solution')\n\n # Second column has Im(predictions), Im(solution)\n ax[i-1,1].plot(soln_x_vals, np.imag(solns[i]), '--', alpha=alpha, label='solutions')\n\n for k,v in preds_dd.items():\n ax[i-1,0].plot(x_vals_dd[k][i], np.real(v[i]), alpha=alpha, label=k)\n\n ax[i-1,1].plot(x_vals_dd[k][i], np.imag(v[i]), alpha=alpha, label=k)\n\n if plot_errors:\n # Third column has errors Abs(solns - predictions)\n ax[i-1,2].plot(np.abs(solns[i] - v[i]), alpha=alpha, label=k)\n\n ax[i-1,0].set_ylabel(\"t = {}\".format(i), size=15)\n\n if plot_errors:\n ax[i-1,2].hlines(0, xmin=0, xmax=grid_size, linestyles='dashed')\n\n\n ax[0,0].legend(fontsize=13, markerscale=2)\n ax[0,1].legend(fontsize=13, markerscale=2)\n\n if plot_errors:\n ax[0,2].legend(fontsize=13, markerscale=2)\n\n if title is not None:\n fig.suptitle(title)\n fig.tight_layout(rect=[0, 0.03, 1, 0.95])\n\n\n if fp is not None:\n plt.savefig(fp)\n else:\n plt.show()\n plt.close(fig)\n\n\ndef make_train_test_plot(df_train, df_test, fp=None, title=\"\", log_scale=False,\n y_label='MSE', df_train_col='MSE',\n df_test_col='test_mse', fig=None, ax=None, ax_title=None):\n\n if fig is None and ax is None:\n fig, ax = plt.subplots(1, 1)\n fig.patch.set_facecolor('white')\n\n #This command sets the 'suptitle' which is not connected to any one ax.\n fig.suptitle(title)\n\n\n # First panel: Train and Test MSE\n ax.plot(df_train['epoch'], df_train[df_train_col], '-', label='train')\n ax.plot(df_test['epoch'], df_test[df_test_col], '--', label='test')\n ax.set_xlabel(\"Epoch\", fontsize=13)\n if log_scale:\n ax.set_yscale('log')\n ax.set_ylabel(\"MSE\", fontsize=13)\n ax.legend(fontsize=13)\n\n if ax_title is not None:\n ax.set_title(ax_title)\n\n fig.tight_layout(rect=[0, 0.03, 1, 0.95])\n\n if fp is not None:\n plt.savefig(fp)\n else:\n plt.show()\n plt.close(fig)\n\ndef quick_prediction_plot(preds_dd, solns, alpha=0.7,\n title=None, fp=None, x_vals_dd=None,\n soln_x_vals=None, plot_errors=True):\n \"\"\"Plots a single test case solutions/predictions by producing a series of\n panels. The rows of panels each correspond to one time step, and the\n three columns are the real part, the imaginary part, and the errors.\n\n Args:\n preds_dd (dict): Dictionary of 1d numpy arrays. Each array corresponds\n to the predictions on a single test-case. The arrays should have matching\n shape (n_grid_points,).\n solns (numpy array): The true solutions. 1d array. Should have shape\n (n_grid_points, ).\n alpha (float, optional): Constrols satuation value. Defaults to 0.7.\n title (string, optional): Figure title. Defaults to None.\n fp (string, optional): Filepath to save the plot. If not specified, the\n plot will be shown via `plt.show`. Defaults to None.\n \"\"\"\n\n # Checking that the time axes are the same size to avoid silly off-by-one\n # plotting errors\n\n grid_size = solns.shape[0]\n # for k,v in preds_dd.items():\n # assert v.shape[0] == n_tsteps\n\n\n fig, ax = plt.subplots(1, 2 + int(plot_errors), sharex='col', sharey=False)\n\n # This sets the figure to an image with aspect ratio 1.5x2\n fig.set_size_inches(10, 4.5)\n\n fig.patch.set_facecolor('white')\n ax[0].set_title(\"$Re(u)$\", size=20)\n ax[1].set_title(\"$Im(u)$\", size=20)\n if plot_errors:\n ax[2].set_title(\"$| u - \\\\hat u|$\", size=20)\n\n if x_vals_dd is None:\n x_vals_dd = {}\n for k,v in preds_dd.items():\n x_vals_dd[k] = np.arange(v.shape[-1])\n\n if soln_x_vals is None:\n soln_x_vals = np.arange(grid_size)\n\n # First column has Re(prediction), Re(solution)\n ax[0].plot(soln_x_vals, np.real(solns), '--', alpha=alpha, label='solution')\n\n # Second column has Im(predictions), Im(solution)\n ax[1].plot(soln_x_vals, np.imag(solns), '--', alpha=alpha, label='solutions')\n\n for k,v in preds_dd.items():\n ax[0].plot(x_vals_dd[k], np.real(v), alpha=alpha, label=k)\n\n ax[1].plot(x_vals_dd[k], np.imag(v), alpha=alpha, label=k)\n\n if plot_errors:\n # Third column has errors Abs(solns - predictions)\n ax[2].plot(soln_x_vals, np.abs(solns - v), alpha=alpha, label=k)\n\n\n # ax[i-1,0].set_ylabel(\"t = {}\".format(i), size=15)\n\n if plot_errors:\n ax[2].hlines(0, xmin=soln_x_vals.min(), xmax=soln_x_vals.max(), linestyles='dashed', color='black')\n\n\n\n ax[0].legend(fontsize=13, markerscale=2)\n # ax[0,1].legend(fontsize=13, markerscale=2)\n\n if plot_errors:\n ax[2].legend(fontsize=13, markerscale=2)\n\n if title is not None:\n fig.suptitle(title)\n fig.tight_layout(rect=[0, 0.03, 1, 0.95])\n else:\n fig.tight_layout()\n\n if fp is not None:\n plt.savefig(fp)\n else:\n plt.show()\n plt.close(fig)\n\n\ndef Fourier_plot(data_dd, start_modes=None, end_modes=None, fp=None, title=None, fftshift=True,\n log_scale=True, names_dd=None, show_n_shifted=None):\n fig, ax = plt.subplots()\n\n if (start_modes is not None) and (end_modes is not None):\n x_data = np.arange(start_modes, end_modes)\n else:\n for sample_v in data_dd.values():\n xlen = sample_v.shape[-1]\n if fftshift:\n x_data = np.arange(-xlen/2, xlen/2)\n else:\n x_data = np.arange(sample_v.shape[-1])\n break\n for k,v in data_dd.items():\n v_dft = np.abs(np.fft.fft(v))\n\n if fftshift:\n v_dft = np.fft.fftshift(v_dft)\n\n if (start_modes is not None) and (end_modes is not None):\n v_dft = v_dft[start_modes:end_modes]\n elif show_n_shifted is not None and fftshift:\n xlen_half = int(v_dft.shape[0] / 2)\n lb = xlen_half - show_n_shifted\n ub = xlen_half + show_n_shifted\n v_dft = v_dft[lb: ub]\n x_data = np.arange(-show_n_shifted, show_n_shifted)\n\n\n if names_dd is not None:\n k_label = names_dd.get(k, k)\n else:\n k_label = k\n\n ax.plot(x_data, v_dft, label=k_label)\n\n if title is not None:\n ax.set_title(title)\n\n if log_scale:\n ax.set_yscale('log')\n\n ax.legend()\n ax.set_xlabel('Frequency')\n\n\n\n\n fig.patch.set_facecolor('white')\n if fp is not None:\n plt.savefig(fp)\n else:\n plt.show()\n plt.close(fig)\n" ]
[ [ "torch.cat", "torch.utils.data.DataLoader", "torch.no_grad", "torch.cuda.is_available", "torch.einsum", "scipy.io.loadmat", "torch.tensor", "torch.divide", "torch.nn.functional.relu", "torch.rand", "torch.optim.lr_scheduler.StepLR", "torch.linalg.norm", "torch.fft.rfft", "torch.nn.Linear", "torch.nn.Conv1d", "torch.view_as_real", "numpy.random.seed", "torch.manual_seed", "torch.view_as_complex" ], [ "torch.max", "torch.cat", "torch.zeros", "torch.utils.data.DataLoader", "torch.no_grad", "torch.cuda.is_available", "torch.sqrt", "torch.einsum", "scipy.io.loadmat", "torch.tensor", "torch.divide", "numpy.ceil", "torch.nn.functional.relu", "scipy.interpolate.interp1d", "torch.rand", "torch.optim.lr_scheduler.StepLR", "torch.div", "torch.linspace", "torch.min", "torch.linalg.norm", "torch.fft.rfft", "torch.nn.Linear", "torch.nn.Conv1d", "torch.view_as_real", "numpy.random.seed", "torch.manual_seed", "torch.view_as_complex" ], [ "numpy.imag", "numpy.abs", "numpy.fft.fft", "numpy.arange", "matplotlib.pyplot.subplots", "matplotlib.pyplot.savefig", "numpy.fft.fftshift", "numpy.std", "numpy.real", "numpy.mean", "matplotlib.pyplot.close", "matplotlib.pyplot.show" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.7", "1.0", "0.10", "1.2", "0.14", "0.19", "1.5", "0.12", "0.17", "0.13", "1.6", "1.4", "1.9", "1.3", "1.10", "0.15", "0.18", "0.16", "1.8" ], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "1.6", "0.14", "1.10", "0.15", "1.4", "1.3", "1.9", "0.19", "1.5", "0.18", "1.2", "1.7", "0.12", "1.0", "0.17", "0.16", "1.8" ], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
kingfener/espresso
[ "da8352a6e97c82e5d92c39972666a772e6bb508a" ]
[ "setup.py" ]
[ "#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\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\nfrom setuptools import setup, find_packages, Extension\nimport sys\n\n\nif sys.version_info < (3, 6):\n sys.exit('Sorry, Python >= 3.6 is required for fairseq.')\n\n\nwith open('README.md') as f:\n readme = f.read()\n\n\nif sys.platform == 'darwin':\n extra_compile_args = ['-stdlib=libc++', '-O3']\nelse:\n extra_compile_args = ['-std=c++11', '-O3']\n\n\nclass NumpyExtension(Extension):\n \"\"\"Source: https://stackoverflow.com/a/54128391\"\"\"\n\n def __init__(self, *args, **kwargs):\n self.__include_dirs = []\n super().__init__(*args, **kwargs)\n\n @property\n def include_dirs(self):\n import numpy\n return self.__include_dirs + [numpy.get_include()]\n\n @include_dirs.setter\n def include_dirs(self, dirs):\n self.__include_dirs = dirs\n\n\nextensions = [\n Extension(\n 'fairseq.libbleu',\n sources=[\n 'fairseq/clib/libbleu/libbleu.cpp',\n 'fairseq/clib/libbleu/module.cpp',\n ],\n extra_compile_args=extra_compile_args,\n ),\n NumpyExtension(\n 'fairseq.data.data_utils_fast',\n sources=['fairseq/data/data_utils_fast.pyx'],\n language='c++',\n extra_compile_args=extra_compile_args,\n ),\n NumpyExtension(\n 'fairseq.data.token_block_utils_fast',\n sources=['fairseq/data/token_block_utils_fast.pyx'],\n language='c++',\n extra_compile_args=extra_compile_args,\n ),\n]\n\n\ncmdclass = {}\n\n\ntry:\n # torch is not available when generating docs\n from torch.utils import cpp_extension\n extensions.extend([\n cpp_extension.CppExtension(\n 'fairseq.libnat',\n sources=[\n 'fairseq/clib/libnat/edit_dist.cpp',\n ],\n )\n ])\n\n if 'CUDA_HOME' in os.environ:\n extensions.extend([\n cpp_extension.CppExtension(\n 'fairseq.libnat_cuda',\n sources=[\n 'fairseq/clib/libnat_cuda/edit_dist.cu',\n 'fairseq/clib/libnat_cuda/binding.cpp'\n ],\n )])\n cmdclass['build_ext'] = cpp_extension.BuildExtension\n\nexcept ImportError:\n pass\n\n\nif 'READTHEDOCS' in os.environ:\n # don't build extensions when generating docs\n extensions = []\n if 'build_ext' in cmdclass:\n del cmdclass['build_ext']\n\n # use CPU build of PyTorch\n dependency_links = [\n 'https://download.pytorch.org/whl/cpu/torch-1.3.0%2Bcpu-cp36-cp36m-linux_x86_64.whl'\n ]\nelse:\n dependency_links = []\n\n\nif 'clean' in sys.argv[1:]:\n # Source: https://bit.ly/2NLVsgE\n print(\"deleting Cython files...\")\n import subprocess\n subprocess.run(['rm -f fairseq/*.so fairseq/**/*.so fairseq/*.pyd fairseq/**/*.pyd'], shell=True)\n\n\nsetup(\n name='fairseq',\n version='0.9.0',\n description='Facebook AI Research Sequence-to-Sequence Toolkit',\n url='https://github.com/pytorch/fairseq',\n classifiers=[\n 'Intended Audience :: Science/Research',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python :: 3.6',\n 'Topic :: Scientific/Engineering :: Artificial Intelligence',\n ],\n long_description=readme,\n long_description_content_type='text/markdown',\n setup_requires=[\n 'cython',\n 'numpy',\n 'setuptools>=18.0',\n ],\n install_requires=[\n 'cffi',\n 'cython',\n 'kaldi_io',\n 'numpy',\n 'regex',\n 'sacrebleu',\n 'torch',\n 'tqdm',\n ],\n dependency_links=dependency_links,\n packages=find_packages(exclude=['scripts', 'tests']),\n ext_modules=extensions,\n test_suite='tests',\n entry_points={\n 'console_scripts': [\n 'fairseq-eval-lm = fairseq_cli.eval_lm:cli_main',\n 'fairseq-generate = fairseq_cli.generate:cli_main',\n 'fairseq-interactive = fairseq_cli.interactive:cli_main',\n 'fairseq-preprocess = fairseq_cli.preprocess:cli_main',\n 'fairseq-score = fairseq_cli.score:cli_main',\n 'fairseq-train = fairseq_cli.train:cli_main',\n 'fairseq-validate = fairseq_cli.validate:cli_main',\n ],\n },\n cmdclass=cmdclass,\n zip_safe=False,\n)\n" ]
[ [ "numpy.get_include", "torch.utils.cpp_extension.CppExtension" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
gourav108/coreml
[ "6bc2d494dff23cff923368e735992a4f4a47483c", "6bc2d494dff23cff923368e735992a4f4a47483c", "6bc2d494dff23cff923368e735992a4f4a47483c", "6bc2d494dff23cff923368e735992a4f4a47483c", "6bc2d494dff23cff923368e735992a4f4a47483c" ]
[ "object_detection/metrics/coco_evaluation.py", "object_detection/box_coders/mean_stddev_box_coder_test.py", "object_detection/utils/shape_utils.py", "object_detection/core/box_coder_test.py", "object_detection/metrics/coco_tools_test.py" ]
[ "# 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\"\"\"Class for evaluating object detections with COCO metrics.\"\"\"\nimport numpy as np\nimport tensorflow as tf\n\nfrom core import standard_fields\nfrom metrics import coco_tools\nfrom utils import object_detection_evaluation\n\n\nclass CocoDetectionEvaluator(object_detection_evaluation.DetectionEvaluator):\n \"\"\"Class to evaluate COCO detection metrics.\"\"\"\n\n def __init__(self,\n categories,\n include_metrics_per_category=False,\n all_metrics_per_category=False):\n \"\"\"Constructor.\n\n Args:\n categories: A list of dicts, each of which has the following keys -\n 'id': (required) an integer id uniquely identifying this category.\n 'name': (required) string representing category name e.g., 'cat', 'dog'.\n include_metrics_per_category: If True, include metrics for each category.\n all_metrics_per_category: Whether to include all the summary metrics for\n each category in per_category_ap. Be careful with setting it to true if\n you have more than handful of categories, because it will pollute\n your mldash.\n \"\"\"\n super(CocoDetectionEvaluator, self).__init__(categories)\n # _image_ids is a dictionary that maps unique image ids to Booleans which\n # indicate whether a corresponding detection has been added.\n self._image_ids = {}\n self._groundtruth_list = []\n self._detection_boxes_list = []\n self._category_id_set = set([cat['id'] for cat in self._categories])\n self._annotation_id = 1\n self._metrics = None\n self._include_metrics_per_category = include_metrics_per_category\n self._all_metrics_per_category = all_metrics_per_category\n\n def clear(self):\n \"\"\"Clears the state to prepare for a fresh evaluation.\"\"\"\n self._image_ids.clear()\n self._groundtruth_list = []\n self._detection_boxes_list = []\n\n def add_single_ground_truth_image_info(self,\n image_id,\n groundtruth_dict):\n \"\"\"Adds groundtruth for a single image to be used for evaluation.\n\n If the image has already been added, a warning is logged, and groundtruth is\n ignored.\n\n Args:\n image_id: A unique string/integer identifier for the image.\n groundtruth_dict: A dictionary containing -\n InputDataFields.groundtruth_boxes: float32 numpy array of shape\n [num_boxes, 4] containing `num_boxes` groundtruth boxes of the format\n [ymin, xmin, ymax, xmax] in absolute image coordinates.\n InputDataFields.groundtruth_classes: integer numpy array of shape\n [num_boxes] containing 1-indexed groundtruth classes for the boxes.\n InputDataFields.groundtruth_is_crowd (optional): integer numpy array of\n shape [num_boxes] containing iscrowd flag for groundtruth boxes.\n \"\"\"\n if image_id in self._image_ids:\n tf.logging.warning('Ignoring ground truth with image id %s since it was '\n 'previously added', image_id)\n return\n\n groundtruth_is_crowd = groundtruth_dict.get(\n standard_fields.InputDataFields.groundtruth_is_crowd)\n # Drop groundtruth_is_crowd if empty tensor.\n if groundtruth_is_crowd is not None and not groundtruth_is_crowd.shape[0]:\n groundtruth_is_crowd = None\n\n self._groundtruth_list.extend(\n coco_tools.ExportSingleImageGroundtruthToCoco(\n image_id=image_id,\n next_annotation_id=self._annotation_id,\n category_id_set=self._category_id_set,\n groundtruth_boxes=groundtruth_dict[\n standard_fields.InputDataFields.groundtruth_boxes],\n groundtruth_classes=groundtruth_dict[\n standard_fields.InputDataFields.groundtruth_classes],\n groundtruth_is_crowd=groundtruth_is_crowd))\n self._annotation_id += groundtruth_dict[standard_fields.InputDataFields.\n groundtruth_boxes].shape[0]\n # Boolean to indicate whether a detection has been added for this image.\n self._image_ids[image_id] = False\n\n def add_single_detected_image_info(self,\n image_id,\n detections_dict):\n \"\"\"Adds detections for a single image to be used for evaluation.\n\n If a detection has already been added for this image id, a warning is\n logged, and the detection is skipped.\n\n Args:\n image_id: A unique string/integer identifier for the image.\n detections_dict: A dictionary containing -\n DetectionResultFields.detection_boxes: float32 numpy array of shape\n [num_boxes, 4] containing `num_boxes` detection boxes of the format\n [ymin, xmin, ymax, xmax] in absolute image coordinates.\n DetectionResultFields.detection_scores: float32 numpy array of shape\n [num_boxes] containing detection scores for the boxes.\n DetectionResultFields.detection_classes: integer numpy array of shape\n [num_boxes] containing 1-indexed detection classes for the boxes.\n\n Raises:\n ValueError: If groundtruth for the image_id is not available.\n \"\"\"\n if image_id not in self._image_ids:\n raise ValueError('Missing groundtruth for image id: {}'.format(image_id))\n\n if self._image_ids[image_id]:\n tf.logging.warning('Ignoring detection with image id %s since it was '\n 'previously added', image_id)\n return\n\n self._detection_boxes_list.extend(\n coco_tools.ExportSingleImageDetectionBoxesToCoco(\n image_id=image_id,\n category_id_set=self._category_id_set,\n detection_boxes=detections_dict[standard_fields.\n DetectionResultFields\n .detection_boxes],\n detection_scores=detections_dict[standard_fields.\n DetectionResultFields.\n detection_scores],\n detection_classes=detections_dict[standard_fields.\n DetectionResultFields.\n detection_classes]))\n self._image_ids[image_id] = True\n\n def evaluate(self):\n \"\"\"Evaluates the detection boxes and returns a dictionary of coco metrics.\n\n Returns:\n A dictionary holding -\n\n 1. summary_metrics:\n 'DetectionBoxes_Precision/mAP': mean average precision over classes\n averaged over IOU thresholds ranging from .5 to .95 with .05\n increments.\n 'DetectionBoxes_Precision/[email protected]': mean average precision at 50% IOU\n 'DetectionBoxes_Precision/[email protected]': mean average precision at 75% IOU\n 'DetectionBoxes_Precision/mAP (small)': mean average precision for small\n objects (area < 32^2 pixels).\n 'DetectionBoxes_Precision/mAP (medium)': mean average precision for\n medium sized objects (32^2 pixels < area < 96^2 pixels).\n 'DetectionBoxes_Precision/mAP (large)': mean average precision for large\n objects (96^2 pixels < area < 10000^2 pixels).\n 'DetectionBoxes_Recall/AR@1': average recall with 1 detection.\n 'DetectionBoxes_Recall/AR@10': average recall with 10 detections.\n 'DetectionBoxes_Recall/AR@100': average recall with 100 detections.\n 'DetectionBoxes_Recall/AR@100 (small)': average recall for small objects\n with 100.\n 'DetectionBoxes_Recall/AR@100 (medium)': average recall for medium objects\n with 100.\n 'DetectionBoxes_Recall/AR@100 (large)': average recall for large objects\n with 100 detections.\n\n 2. per_category_ap: if include_metrics_per_category is True, category\n specific results with keys of the form:\n 'Precision mAP ByCategory/category' (without the supercategory part if\n no supercategories exist). For backward compatibility\n 'PerformanceByCategory' is included in the output regardless of\n all_metrics_per_category.\n \"\"\"\n groundtruth_dict = {\n 'annotations': self._groundtruth_list,\n 'images': [{'id': image_id} for image_id in self._image_ids],\n 'categories': self._categories\n }\n coco_wrapped_groundtruth = coco_tools.COCOWrapper(groundtruth_dict)\n coco_wrapped_detections = coco_wrapped_groundtruth.LoadAnnotations(\n self._detection_boxes_list)\n box_evaluator = coco_tools.COCOEvalWrapper(\n coco_wrapped_groundtruth, coco_wrapped_detections, agnostic_mode=False)\n box_metrics, box_per_category_ap = box_evaluator.ComputeMetrics(\n include_metrics_per_category=self._include_metrics_per_category,\n all_metrics_per_category=self._all_metrics_per_category)\n box_metrics.update(box_per_category_ap)\n box_metrics = {'DetectionBoxes_'+ key: value\n for key, value in iter(box_metrics.items())}\n return box_metrics\n\n def get_estimator_eval_metric_ops(self, image_id, groundtruth_boxes,\n groundtruth_classes, detection_boxes,\n detection_scores, detection_classes):\n \"\"\"Returns a dictionary of eval metric ops to use with `tf.EstimatorSpec`.\n\n Note that once value_op is called, the detections and groundtruth added via\n update_op are cleared.\n\n Args:\n image_id: Unique string/integer identifier for the image.\n groundtruth_boxes: float32 tensor of shape [num_boxes, 4] containing\n `num_boxes` groundtruth boxes of the format\n [ymin, xmin, ymax, xmax] in absolute image coordinates.\n groundtruth_classes: int32 tensor of shape [num_boxes] containing\n 1-indexed groundtruth classes for the boxes.\n detection_boxes: float32 tensor of shape [num_boxes, 4] containing\n `num_boxes` detection boxes of the format [ymin, xmin, ymax, xmax]\n in absolute image coordinates.\n detection_scores: float32 tensor of shape [num_boxes] containing\n detection scores for the boxes.\n detection_classes: int32 tensor of shape [num_boxes] containing\n 1-indexed detection classes for the boxes.\n\n Returns:\n a dictionary of metric names to tuple of value_op and update_op that can\n be used as eval metric ops in tf.EstimatorSpec. Note that all update ops\n must be run together and similarly all value ops must be run together to\n guarantee correct behaviour.\n \"\"\"\n def update_op(\n image_id,\n groundtruth_boxes,\n groundtruth_classes,\n detection_boxes,\n detection_scores,\n detection_classes):\n self.add_single_ground_truth_image_info(\n image_id,\n {'groundtruth_boxes': groundtruth_boxes,\n 'groundtruth_classes': groundtruth_classes})\n self.add_single_detected_image_info(\n image_id,\n {'detection_boxes': detection_boxes,\n 'detection_scores': detection_scores,\n 'detection_classes': detection_classes})\n\n update_op = tf.py_func(update_op, [image_id,\n groundtruth_boxes,\n groundtruth_classes,\n detection_boxes,\n detection_scores,\n detection_classes], [])\n metric_names = ['DetectionBoxes_Precision/mAP',\n 'DetectionBoxes_Precision/[email protected]',\n 'DetectionBoxes_Precision/[email protected]',\n 'DetectionBoxes_Precision/mAP (large)',\n 'DetectionBoxes_Precision/mAP (medium)',\n 'DetectionBoxes_Precision/mAP (small)',\n 'DetectionBoxes_Recall/AR@1',\n 'DetectionBoxes_Recall/AR@10',\n 'DetectionBoxes_Recall/AR@100',\n 'DetectionBoxes_Recall/AR@100 (large)',\n 'DetectionBoxes_Recall/AR@100 (medium)',\n 'DetectionBoxes_Recall/AR@100 (small)']\n if self._include_metrics_per_category:\n for category_dict in self._categories:\n metric_names.append('DetectionBoxes_PerformanceByCategory/mAP/' +\n category_dict['name'])\n\n def first_value_func():\n self._metrics = self.evaluate()\n self.clear()\n return np.float32(self._metrics[metric_names[0]])\n\n def value_func_factory(metric_name):\n def value_func():\n return np.float32(self._metrics[metric_name])\n return value_func\n\n # Ensure that the metrics are only evaluated once.\n first_value_op = tf.py_func(first_value_func, [], tf.float32)\n eval_metric_ops = {metric_names[0]: (first_value_op, update_op)}\n with tf.control_dependencies([first_value_op]):\n for metric_name in metric_names[1:]:\n eval_metric_ops[metric_name] = (tf.py_func(\n value_func_factory(metric_name), [], np.float32), update_op)\n return eval_metric_ops\n\n\ndef _check_mask_type_and_value(array_name, masks):\n \"\"\"Checks whether mask dtype is uint8 and the values are either 0 or 1.\"\"\"\n if masks.dtype != np.uint8:\n raise ValueError('{} must be of type np.uint8. Found {}.'.format(\n array_name, masks.dtype))\n if np.any(np.logical_and(masks != 0, masks != 1)):\n raise ValueError('{} elements can only be either 0 or 1.'.format(\n array_name))\n\n\nclass CocoMaskEvaluator(object_detection_evaluation.DetectionEvaluator):\n \"\"\"Class to evaluate COCO detection metrics.\"\"\"\n\n def __init__(self, categories, include_metrics_per_category=False):\n \"\"\"Constructor.\n\n Args:\n categories: A list of dicts, each of which has the following keys -\n 'id': (required) an integer id uniquely identifying this category.\n 'name': (required) string representing category name e.g., 'cat', 'dog'.\n include_metrics_per_category: If True, include metrics for each category.\n \"\"\"\n super(CocoMaskEvaluator, self).__init__(categories)\n self._image_id_to_mask_shape_map = {}\n self._image_ids_with_detections = set([])\n self._groundtruth_list = []\n self._detection_masks_list = []\n self._category_id_set = set([cat['id'] for cat in self._categories])\n self._annotation_id = 1\n self._include_metrics_per_category = include_metrics_per_category\n\n def clear(self):\n \"\"\"Clears the state to prepare for a fresh evaluation.\"\"\"\n self._image_id_to_mask_shape_map.clear()\n self._image_ids_with_detections.clear()\n self._groundtruth_list = []\n self._detection_masks_list = []\n\n def add_single_ground_truth_image_info(self,\n image_id,\n groundtruth_dict):\n \"\"\"Adds groundtruth for a single image to be used for evaluation.\n\n If the image has already been added, a warning is logged, and groundtruth is\n ignored.\n\n Args:\n image_id: A unique string/integer identifier for the image.\n groundtruth_dict: A dictionary containing -\n InputDataFields.groundtruth_boxes: float32 numpy array of shape\n [num_boxes, 4] containing `num_boxes` groundtruth boxes of the format\n [ymin, xmin, ymax, xmax] in absolute image coordinates.\n InputDataFields.groundtruth_classes: integer numpy array of shape\n [num_boxes] containing 1-indexed groundtruth classes for the boxes.\n InputDataFields.groundtruth_instance_masks: uint8 numpy array of shape\n [num_boxes, image_height, image_width] containing groundtruth masks\n corresponding to the boxes. The elements of the array must be in\n {0, 1}.\n \"\"\"\n if image_id in self._image_id_to_mask_shape_map:\n tf.logging.warning('Ignoring ground truth with image id %s since it was '\n 'previously added', image_id)\n return\n\n groundtruth_instance_masks = groundtruth_dict[\n standard_fields.InputDataFields.groundtruth_instance_masks]\n _check_mask_type_and_value(standard_fields.InputDataFields.\n groundtruth_instance_masks,\n groundtruth_instance_masks)\n self._groundtruth_list.extend(\n coco_tools.\n ExportSingleImageGroundtruthToCoco(\n image_id=image_id,\n next_annotation_id=self._annotation_id,\n category_id_set=self._category_id_set,\n groundtruth_boxes=groundtruth_dict[standard_fields.InputDataFields.\n groundtruth_boxes],\n groundtruth_classes=groundtruth_dict[standard_fields.\n InputDataFields.\n groundtruth_classes],\n groundtruth_masks=groundtruth_instance_masks))\n self._annotation_id += groundtruth_dict[standard_fields.InputDataFields.\n groundtruth_boxes].shape[0]\n self._image_id_to_mask_shape_map[image_id] = groundtruth_dict[\n standard_fields.InputDataFields.groundtruth_instance_masks].shape\n\n def add_single_detected_image_info(self,\n image_id,\n detections_dict):\n \"\"\"Adds detections for a single image to be used for evaluation.\n\n If a detection has already been added for this image id, a warning is\n logged, and the detection is skipped.\n\n Args:\n image_id: A unique string/integer identifier for the image.\n detections_dict: A dictionary containing -\n DetectionResultFields.detection_scores: float32 numpy array of shape\n [num_boxes] containing detection scores for the boxes.\n DetectionResultFields.detection_classes: integer numpy array of shape\n [num_boxes] containing 1-indexed detection classes for the boxes.\n DetectionResultFields.detection_masks: optional uint8 numpy array of\n shape [num_boxes, image_height, image_width] containing instance\n masks corresponding to the boxes. The elements of the array must be\n in {0, 1}.\n\n Raises:\n ValueError: If groundtruth for the image_id is not available or if\n spatial shapes of groundtruth_instance_masks and detection_masks are\n incompatible.\n \"\"\"\n if image_id not in self._image_id_to_mask_shape_map:\n raise ValueError('Missing groundtruth for image id: {}'.format(image_id))\n\n if image_id in self._image_ids_with_detections:\n tf.logging.warning('Ignoring detection with image id %s since it was '\n 'previously added', image_id)\n return\n\n groundtruth_masks_shape = self._image_id_to_mask_shape_map[image_id]\n detection_masks = detections_dict[standard_fields.DetectionResultFields.\n detection_masks]\n if groundtruth_masks_shape[1:] != detection_masks.shape[1:]:\n raise ValueError('Spatial shape of groundtruth masks and detection masks '\n 'are incompatible: {} vs {}'.format(\n groundtruth_masks_shape,\n detection_masks.shape))\n _check_mask_type_and_value(standard_fields.DetectionResultFields.\n detection_masks,\n detection_masks)\n self._detection_masks_list.extend(\n coco_tools.ExportSingleImageDetectionMasksToCoco(\n image_id=image_id,\n category_id_set=self._category_id_set,\n detection_masks=detection_masks,\n detection_scores=detections_dict[standard_fields.\n DetectionResultFields.\n detection_scores],\n detection_classes=detections_dict[standard_fields.\n DetectionResultFields.\n detection_classes]))\n self._image_ids_with_detections.update([image_id])\n\n def evaluate(self):\n \"\"\"Evaluates the detection masks and returns a dictionary of coco metrics.\n\n Returns:\n A dictionary holding -\n\n 1. summary_metrics:\n 'DetectionMasks_Precision/mAP': mean average precision over classes\n averaged over IOU thresholds ranging from .5 to .95 with .05 increments.\n 'DetectionMasks_Precision/[email protected]': mean average precision at 50% IOU.\n 'DetectionMasks_Precision/[email protected]': mean average precision at 75% IOU.\n 'DetectionMasks_Precision/mAP (small)': mean average precision for small\n objects (area < 32^2 pixels).\n 'DetectionMasks_Precision/mAP (medium)': mean average precision for medium\n sized objects (32^2 pixels < area < 96^2 pixels).\n 'DetectionMasks_Precision/mAP (large)': mean average precision for large\n objects (96^2 pixels < area < 10000^2 pixels).\n 'DetectionMasks_Recall/AR@1': average recall with 1 detection.\n 'DetectionMasks_Recall/AR@10': average recall with 10 detections.\n 'DetectionMasks_Recall/AR@100': average recall with 100 detections.\n 'DetectionMasks_Recall/AR@100 (small)': average recall for small objects\n with 100 detections.\n 'DetectionMasks_Recall/AR@100 (medium)': average recall for medium objects\n with 100 detections.\n 'DetectionMasks_Recall/AR@100 (large)': average recall for large objects\n with 100 detections.\n\n 2. per_category_ap: if include_metrics_per_category is True, category\n specific results with keys of the form:\n 'Precision mAP ByCategory/category' (without the supercategory part if\n no supercategories exist). For backward compatibility\n 'PerformanceByCategory' is included in the output regardless of\n all_metrics_per_category.\n \"\"\"\n groundtruth_dict = {\n 'annotations': self._groundtruth_list,\n 'images': [{'id': image_id, 'height': shape[1], 'width': shape[2]}\n for image_id, shape in self._image_id_to_mask_shape_map.\n iteritems()],\n 'categories': self._categories\n }\n coco_wrapped_groundtruth = coco_tools.COCOWrapper(\n groundtruth_dict, detection_type='segmentation')\n coco_wrapped_detection_masks = coco_wrapped_groundtruth.LoadAnnotations(\n self._detection_masks_list)\n mask_evaluator = coco_tools.COCOEvalWrapper(\n coco_wrapped_groundtruth, coco_wrapped_detection_masks,\n agnostic_mode=False, iou_type='segm')\n mask_metrics, mask_per_category_ap = mask_evaluator.ComputeMetrics(\n include_metrics_per_category=self._include_metrics_per_category)\n mask_metrics.update(mask_per_category_ap)\n mask_metrics = {'DetectionMasks_'+ key: value\n for key, value in mask_metrics.iteritems()}\n return mask_metrics\n\n def get_estimator_eval_metric_ops(self, image_id, groundtruth_boxes,\n groundtruth_classes,\n groundtruth_instance_masks,\n detection_scores, detection_classes,\n detection_masks):\n \"\"\"Returns a dictionary of eval metric ops to use with `tf.EstimatorSpec`.\n\n Note that once value_op is called, the detections and groundtruth added via\n update_op are cleared.\n\n Args:\n image_id: Unique string/integer identifier for the image.\n groundtruth_boxes: float32 tensor of shape [num_boxes, 4] containing\n `num_boxes` groundtruth boxes of the format\n [ymin, xmin, ymax, xmax] in absolute image coordinates.\n groundtruth_classes: int32 tensor of shape [num_boxes] containing\n 1-indexed groundtruth classes for the boxes.\n groundtruth_instance_masks: uint8 tensor array of shape\n [num_boxes, image_height, image_width] containing groundtruth masks\n corresponding to the boxes. The elements of the array must be in {0, 1}.\n detection_scores: float32 tensor of shape [num_boxes] containing\n detection scores for the boxes.\n detection_classes: int32 tensor of shape [num_boxes] containing\n 1-indexed detection classes for the boxes.\n detection_masks: uint8 tensor array of shape\n [num_boxes, image_height, image_width] containing instance masks\n corresponding to the boxes. The elements of the array must be in {0, 1}.\n\n Returns:\n a dictionary of metric names to tuple of value_op and update_op that can\n be used as eval metric ops in tf.EstimatorSpec. Note that all update ops\n must be run together and similarly all value ops must be run together to\n guarantee correct behaviour.\n \"\"\"\n def update_op(\n image_id,\n groundtruth_boxes,\n groundtruth_classes,\n groundtruth_instance_masks,\n detection_scores,\n detection_classes,\n detection_masks):\n self.add_single_ground_truth_image_info(\n image_id,\n {'groundtruth_boxes': groundtruth_boxes,\n 'groundtruth_classes': groundtruth_classes,\n 'groundtruth_instance_masks': groundtruth_instance_masks})\n self.add_single_detected_image_info(\n image_id,\n {'detection_scores': detection_scores,\n 'detection_classes': detection_classes,\n 'detection_masks': detection_masks})\n\n update_op = tf.py_func(update_op, [image_id,\n groundtruth_boxes,\n groundtruth_classes,\n groundtruth_instance_masks,\n detection_scores,\n detection_classes,\n detection_masks], [])\n metric_names = ['DetectionMasks_Precision/mAP',\n 'DetectionMasks_Precision/[email protected]',\n 'DetectionMasks_Precision/[email protected]',\n 'DetectionMasks_Precision/mAP (large)',\n 'DetectionMasks_Precision/mAP (medium)',\n 'DetectionMasks_Precision/mAP (small)',\n 'DetectionMasks_Recall/AR@1',\n 'DetectionMasks_Recall/AR@10',\n 'DetectionMasks_Recall/AR@100',\n 'DetectionMasks_Recall/AR@100 (large)',\n 'DetectionMasks_Recall/AR@100 (medium)',\n 'DetectionMasks_Recall/AR@100 (small)']\n if self._include_metrics_per_category:\n for category_dict in self._categories:\n metric_names.append('DetectionMasks_PerformanceByCategory/mAP/' +\n category_dict['name'])\n\n def first_value_func():\n self._metrics = self.evaluate()\n self.clear()\n return np.float32(self._metrics[metric_names[0]])\n\n def value_func_factory(metric_name):\n def value_func():\n return np.float32(self._metrics[metric_name])\n return value_func\n\n # Ensure that the metrics are only evaluated once.\n first_value_op = tf.py_func(first_value_func, [], tf.float32)\n eval_metric_ops = {metric_names[0]: (first_value_op, update_op)}\n with tf.control_dependencies([first_value_op]):\n for metric_name in metric_names[1:]:\n eval_metric_ops[metric_name] = (tf.py_func(\n value_func_factory(metric_name), [], np.float32), update_op)\n return eval_metric_ops\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\n\"\"\"Tests for box_coder.mean_stddev_boxcoder.\"\"\"\n\nimport tensorflow as tf\n\nfrom box_coders import mean_stddev_box_coder\nfrom core import box_list\n\n\nclass MeanStddevBoxCoderTest(tf.test.TestCase):\n\n def testGetCorrectRelativeCodesAfterEncoding(self):\n box_corners = [[0.0, 0.0, 0.5, 0.5], [0.0, 0.0, 0.5, 0.5]]\n boxes = box_list.BoxList(tf.constant(box_corners))\n expected_rel_codes = [[0.0, 0.0, 0.0, 0.0], [-5.0, -5.0, -5.0, -3.0]]\n prior_means = tf.constant([[0.0, 0.0, 0.5, 0.5], [0.5, 0.5, 1.0, 0.8]])\n prior_stddevs = tf.constant(2 * [4 * [.1]])\n priors = box_list.BoxList(prior_means)\n priors.add_field('stddev', prior_stddevs)\n\n coder = mean_stddev_box_coder.MeanStddevBoxCoder()\n rel_codes = coder.encode(boxes, priors)\n with self.test_session() as sess:\n rel_codes_out = sess.run(rel_codes)\n self.assertAllClose(rel_codes_out, expected_rel_codes)\n\n def testGetCorrectBoxesAfterDecoding(self):\n rel_codes = tf.constant([[0.0, 0.0, 0.0, 0.0], [-5.0, -5.0, -5.0, -3.0]])\n expected_box_corners = [[0.0, 0.0, 0.5, 0.5], [0.0, 0.0, 0.5, 0.5]]\n prior_means = tf.constant([[0.0, 0.0, 0.5, 0.5], [0.5, 0.5, 1.0, 0.8]])\n prior_stddevs = tf.constant(2 * [4 * [.1]])\n priors = box_list.BoxList(prior_means)\n priors.add_field('stddev', prior_stddevs)\n\n coder = mean_stddev_box_coder.MeanStddevBoxCoder()\n decoded_boxes = coder.decode(rel_codes, priors)\n decoded_box_corners = decoded_boxes.get()\n with self.test_session() as sess:\n decoded_out = sess.run(decoded_box_corners)\n self.assertAllClose(decoded_out, expected_box_corners)\n\n\nif __name__ == '__main__':\n tf.test.main()\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\n\"\"\"Utils used to manipulate tensor shapes.\"\"\"\n\nimport tensorflow as tf\n\nfrom utils import static_shape\n\n\ndef _is_tensor(t):\n \"\"\"Returns a boolean indicating whether the input is a tensor.\n\n Args:\n t: the input to be tested.\n\n Returns:\n a boolean that indicates whether t is a tensor.\n \"\"\"\n return isinstance(t, (tf.Tensor, tf.SparseTensor, tf.Variable))\n\n\ndef _set_dim_0(t, d0):\n \"\"\"Sets the 0-th dimension of the input tensor.\n\n Args:\n t: the input tensor, assuming the rank is at least 1.\n d0: an integer indicating the 0-th dimension of the input tensor.\n\n Returns:\n the tensor t with the 0-th dimension set.\n \"\"\"\n t_shape = t.get_shape().as_list()\n t_shape[0] = d0\n t.set_shape(t_shape)\n return t\n\n\ndef pad_tensor(t, length):\n \"\"\"Pads the input tensor with 0s along the first dimension up to the length.\n\n Args:\n t: the input tensor, assuming the rank is at least 1.\n length: a tensor of shape [1] or an integer, indicating the first dimension\n of the input tensor t after padding, assuming length <= t.shape[0].\n\n Returns:\n padded_t: the padded tensor, whose first dimension is length. If the length\n is an integer, the first dimension of padded_t is set to length\n statically.\n \"\"\"\n t_rank = tf.rank(t)\n t_shape = tf.shape(t)\n t_d0 = t_shape[0]\n pad_d0 = tf.expand_dims(length - t_d0, 0)\n pad_shape = tf.cond(\n tf.greater(t_rank, 1), lambda: tf.concat([pad_d0, t_shape[1:]], 0),\n lambda: tf.expand_dims(length - t_d0, 0))\n padded_t = tf.concat([t, tf.zeros(pad_shape, dtype=t.dtype)], 0)\n if not _is_tensor(length):\n padded_t = _set_dim_0(padded_t, length)\n return padded_t\n\n\ndef clip_tensor(t, length):\n \"\"\"Clips the input tensor along the first dimension up to the length.\n\n Args:\n t: the input tensor, assuming the rank is at least 1.\n length: a tensor of shape [1] or an integer, indicating the first dimension\n of the input tensor t after clipping, assuming length <= t.shape[0].\n\n Returns:\n clipped_t: the clipped tensor, whose first dimension is length. If the\n length is an integer, the first dimension of clipped_t is set to length\n statically.\n \"\"\"\n clipped_t = tf.gather(t, tf.range(length))\n if not _is_tensor(length):\n clipped_t = _set_dim_0(clipped_t, length)\n return clipped_t\n\n\ndef pad_or_clip_tensor(t, length):\n \"\"\"Pad or clip the input tensor along the first dimension.\n\n Args:\n t: the input tensor, assuming the rank is at least 1.\n length: a tensor of shape [1] or an integer, indicating the first dimension\n of the input tensor t after processing.\n\n Returns:\n processed_t: the processed tensor, whose first dimension is length. If the\n length is an integer, the first dimension of the processed tensor is set\n to length statically.\n \"\"\"\n processed_t = tf.cond(\n tf.greater(tf.shape(t)[0], length),\n lambda: clip_tensor(t, length),\n lambda: pad_tensor(t, length))\n if not _is_tensor(length):\n processed_t = _set_dim_0(processed_t, length)\n return processed_t\n\n\ndef combined_static_and_dynamic_shape(tensor):\n \"\"\"Returns a list containing static and dynamic values for the dimensions.\n\n Returns a list of static and dynamic values for shape dimensions. This is\n useful to preserve static shapes when available in reshape operation.\n\n Args:\n tensor: A tensor of any type.\n\n Returns:\n A list of size tensor.shape.ndims containing integers or a scalar tensor.\n \"\"\"\n static_tensor_shape = tensor.shape.as_list()\n dynamic_tensor_shape = tf.shape(tensor)\n combined_shape = []\n for index, dim in enumerate(static_tensor_shape):\n if dim is not None:\n combined_shape.append(dim)\n else:\n combined_shape.append(dynamic_tensor_shape[index])\n return combined_shape\n\n\ndef static_or_dynamic_map_fn(fn, elems, dtype=None,\n parallel_iterations=32, back_prop=True):\n \"\"\"Runs map_fn as a (static) for loop when possible.\n\n This function rewrites the map_fn as an explicit unstack input -> for loop\n over function calls -> stack result combination. This allows our graphs to\n be acyclic when the batch size is static.\n For comparison, see https://www.tensorflow.org/api_docs/python/tf/map_fn.\n\n Note that `static_or_dynamic_map_fn` currently is not *fully* interchangeable\n with the default tf.map_fn function as it does not accept nested inputs (only\n Tensors or lists of Tensors). Likewise, the output of `fn` can only be a\n Tensor or list of Tensors.\n\n TODO(jonathanhuang): make this function fully interchangeable with tf.map_fn.\n\n Args:\n fn: The callable to be performed. It accepts one argument, which will have\n the same structure as elems. Its output must have the\n same structure as elems.\n elems: A tensor or list of tensors, each of which will\n be unpacked along their first dimension. The sequence of the\n resulting slices will be applied to fn.\n dtype: (optional) The output type(s) of fn. If fn returns a structure of\n Tensors differing from the structure of elems, then dtype is not optional\n and must have the same structure as the output of fn.\n parallel_iterations: (optional) number of batch items to process in\n parallel. This flag is only used if the native tf.map_fn is used\n and defaults to 32 instead of 10 (unlike the standard tf.map_fn default).\n back_prop: (optional) True enables support for back propagation.\n This flag is only used if the native tf.map_fn is used.\n\n Returns:\n A tensor or sequence of tensors. Each tensor packs the\n results of applying fn to tensors unpacked from elems along the first\n dimension, from first to last.\n Raises:\n ValueError: if `elems` a Tensor or a list of Tensors.\n ValueError: if `fn` does not return a Tensor or list of Tensors\n \"\"\"\n if isinstance(elems, list):\n for elem in elems:\n if not isinstance(elem, tf.Tensor):\n raise ValueError('`elems` must be a Tensor or list of Tensors.')\n\n elem_shapes = [elem.shape.as_list() for elem in elems]\n # Fall back on tf.map_fn if shapes of each entry of `elems` are None or fail\n # to all be the same size along the batch dimension.\n for elem_shape in elem_shapes:\n if (not elem_shape or not elem_shape[0]\n or elem_shape[0] != elem_shapes[0][0]):\n return tf.map_fn(fn, elems, dtype, parallel_iterations, back_prop)\n arg_tuples = zip(*[tf.unstack(elem) for elem in elems])\n outputs = [fn(arg_tuple) for arg_tuple in arg_tuples]\n else:\n if not isinstance(elems, tf.Tensor):\n raise ValueError('`elems` must be a Tensor or list of Tensors.')\n elems_shape = elems.shape.as_list()\n if not elems_shape or not elems_shape[0]:\n return tf.map_fn(fn, elems, dtype, parallel_iterations, back_prop)\n outputs = [fn(arg) for arg in tf.unstack(elems)]\n # Stack `outputs`, which is a list of Tensors or list of lists of Tensors\n if all([isinstance(output, tf.Tensor) for output in outputs]):\n return tf.stack(outputs)\n else:\n if all([isinstance(output, list) for output in outputs]):\n if all([all(\n [isinstance(entry, tf.Tensor) for entry in output_list])\n for output_list in outputs]):\n return [tf.stack(output_tuple) for output_tuple in zip(*outputs)]\n raise ValueError('`fn` should return a Tensor or a list of Tensors.')\n\n\ndef check_min_image_dim(min_dim, image_tensor):\n \"\"\"Checks that the image width/height are greater than some number.\n\n This function is used to check that the width and height of an image are above\n a certain value. If the image shape is static, this function will perform the\n check at graph construction time. Otherwise, if the image shape varies, an\n Assertion control dependency will be added to the graph.\n\n Args:\n min_dim: The minimum number of pixels along the width and height of the\n image.\n image_tensor: The image tensor to check size for.\n\n Returns:\n If `image_tensor` has dynamic size, return `image_tensor` with a Assert\n control dependency. Otherwise returns image_tensor.\n\n Raises:\n ValueError: if `image_tensor`'s' width or height is smaller than `min_dim`.\n \"\"\"\n image_shape = image_tensor.get_shape()\n image_height = static_shape.get_height(image_shape)\n image_width = static_shape.get_width(image_shape)\n if image_height is None or image_width is None:\n shape_assert = tf.Assert(\n tf.logical_and(tf.greater_equal(tf.shape(image_tensor)[1], min_dim),\n tf.greater_equal(tf.shape(image_tensor)[2], min_dim)),\n ['image size must be >= {} in both height and width.'.format(min_dim)])\n with tf.control_dependencies([shape_assert]):\n return tf.identity(image_tensor)\n\n if image_height < min_dim or image_width < min_dim:\n raise ValueError(\n 'image size must be >= %d in both height and width; image dim = %d,%d' %\n (min_dim, image_height, image_width))\n\n return image_tensor\n\n\ndef assert_shape_equal(shape_a, shape_b):\n \"\"\"Asserts that shape_a and shape_b are equal.\n\n If the shapes are static, raises a ValueError when the shapes\n mismatch.\n\n If the shapes are dynamic, raises a tf InvalidArgumentError when the shapes\n mismatch.\n\n Args:\n shape_a: a list containing shape of the first tensor.\n shape_b: a list containing shape of the second tensor.\n\n Returns:\n Either a tf.no_op() when shapes are all static and a tf.assert_equal() op\n when the shapes are dynamic.\n\n Raises:\n ValueError: When shapes are both static and unequal.\n \"\"\"\n if (all(isinstance(dim, int) for dim in shape_a) and\n all(isinstance(dim, int) for dim in shape_b)):\n if shape_a != shape_b:\n raise ValueError('Unequal shapes {}, {}'.format(shape_a, shape_b))\n else: return tf.no_op()\n else:\n return tf.assert_equal(shape_a, shape_b)\n\n\ndef assert_shape_equal_along_first_dimension(shape_a, shape_b):\n \"\"\"Asserts that shape_a and shape_b are the same along the 0th-dimension.\n\n If the shapes are static, raises a ValueError when the shapes\n mismatch.\n\n If the shapes are dynamic, raises a tf InvalidArgumentError when the shapes\n mismatch.\n\n Args:\n shape_a: a list containing shape of the first tensor.\n shape_b: a list containing shape of the second tensor.\n\n Returns:\n Either a tf.no_op() when shapes are all static and a tf.assert_equal() op\n when the shapes are dynamic.\n\n Raises:\n ValueError: When shapes are both static and unequal.\n \"\"\"\n if isinstance(shape_a[0], int) and isinstance(shape_b[0], int):\n if shape_a[0] != shape_b[0]:\n raise ValueError('Unequal first dimension {}, {}'.format(\n shape_a[0], shape_b[0]))\n else: return tf.no_op()\n else:\n return tf.assert_equal(shape_a[0], shape_b[0])\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\n\"\"\"Tests for core.box_coder.\"\"\"\n\nimport tensorflow as tf\n\nfrom core import box_coder\nfrom core import box_list\n\n\nclass MockBoxCoder(box_coder.BoxCoder):\n \"\"\"Test BoxCoder that encodes/decodes using the multiply-by-two function.\"\"\"\n\n def code_size(self):\n return 4\n\n def _encode(self, boxes, anchors):\n return 2.0 * boxes.get()\n\n def _decode(self, rel_codes, anchors):\n return box_list.BoxList(rel_codes / 2.0)\n\n\nclass BoxCoderTest(tf.test.TestCase):\n\n def test_batch_decode(self):\n mock_anchor_corners = tf.constant(\n [[0, 0.1, 0.2, 0.3], [0.2, 0.4, 0.4, 0.6]], tf.float32)\n mock_anchors = box_list.BoxList(mock_anchor_corners)\n mock_box_coder = MockBoxCoder()\n\n expected_boxes = [[[0.0, 0.1, 0.5, 0.6], [0.5, 0.6, 0.7, 0.8]],\n [[0.1, 0.2, 0.3, 0.4], [0.7, 0.8, 0.9, 1.0]]]\n\n encoded_boxes_list = [mock_box_coder.encode(\n box_list.BoxList(tf.constant(boxes)), mock_anchors)\n for boxes in expected_boxes]\n encoded_boxes = tf.stack(encoded_boxes_list)\n decoded_boxes = box_coder.batch_decode(\n encoded_boxes, mock_box_coder, mock_anchors)\n\n with self.test_session() as sess:\n decoded_boxes_result = sess.run(decoded_boxes)\n self.assertAllClose(expected_boxes, decoded_boxes_result)\n\n\nif __name__ == '__main__':\n tf.test.main()\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 tensorflow_model.metrics.coco_tools.\"\"\"\nimport json\nimport os\nimport re\nimport numpy as np\n\nfrom pycocotools import mask\n\nimport tensorflow as tf\n\nfrom metrics import coco_tools\n\n\nclass CocoToolsTest(tf.test.TestCase):\n\n def setUp(self):\n groundtruth_annotations_list = [\n {\n 'id': 1,\n 'image_id': 'first',\n 'category_id': 1,\n 'bbox': [100., 100., 100., 100.],\n 'area': 100.**2,\n 'iscrowd': 0\n },\n {\n 'id': 2,\n 'image_id': 'second',\n 'category_id': 1,\n 'bbox': [50., 50., 50., 50.],\n 'area': 50.**2,\n 'iscrowd': 0\n },\n ]\n image_list = [{'id': 'first'}, {'id': 'second'}]\n category_list = [{'id': 0, 'name': 'person'},\n {'id': 1, 'name': 'cat'},\n {'id': 2, 'name': 'dog'}]\n self._groundtruth_dict = {\n 'annotations': groundtruth_annotations_list,\n 'images': image_list,\n 'categories': category_list\n }\n\n self._detections_list = [\n {\n 'image_id': 'first',\n 'category_id': 1,\n 'bbox': [100., 100., 100., 100.],\n 'score': .8\n },\n {\n 'image_id': 'second',\n 'category_id': 1,\n 'bbox': [50., 50., 50., 50.],\n 'score': .7\n },\n ]\n\n def testCocoWrappers(self):\n groundtruth = coco_tools.COCOWrapper(self._groundtruth_dict)\n detections = groundtruth.LoadAnnotations(self._detections_list)\n evaluator = coco_tools.COCOEvalWrapper(groundtruth, detections)\n summary_metrics, _ = evaluator.ComputeMetrics()\n self.assertAlmostEqual(1.0, summary_metrics['Precision/mAP'])\n\n def testExportGroundtruthToCOCO(self):\n image_ids = ['first', 'second']\n groundtruth_boxes = [np.array([[100, 100, 200, 200]], np.float),\n np.array([[50, 50, 100, 100]], np.float)]\n groundtruth_classes = [np.array([1], np.int32), np.array([1], np.int32)]\n categories = [{'id': 0, 'name': 'person'},\n {'id': 1, 'name': 'cat'},\n {'id': 2, 'name': 'dog'}]\n output_path = os.path.join(tf.test.get_temp_dir(), 'groundtruth.json')\n result = coco_tools.ExportGroundtruthToCOCO(\n image_ids,\n groundtruth_boxes,\n groundtruth_classes,\n categories,\n output_path=output_path)\n self.assertDictEqual(result, self._groundtruth_dict)\n with tf.gfile.GFile(output_path, 'r') as f:\n written_result = f.read()\n # The json output should have floats written to 4 digits of precision.\n matcher = re.compile(r'\"bbox\":\\s+\\[\\n\\s+\\d+.\\d\\d\\d\\d,', re.MULTILINE)\n self.assertTrue(matcher.findall(written_result))\n written_result = json.loads(written_result)\n self.assertAlmostEqual(result, written_result)\n\n def testExportDetectionsToCOCO(self):\n image_ids = ['first', 'second']\n detections_boxes = [np.array([[100, 100, 200, 200]], np.float),\n np.array([[50, 50, 100, 100]], np.float)]\n detections_scores = [np.array([.8], np.float), np.array([.7], np.float)]\n detections_classes = [np.array([1], np.int32), np.array([1], np.int32)]\n categories = [{'id': 0, 'name': 'person'},\n {'id': 1, 'name': 'cat'},\n {'id': 2, 'name': 'dog'}]\n output_path = os.path.join(tf.test.get_temp_dir(), 'detections.json')\n result = coco_tools.ExportDetectionsToCOCO(\n image_ids,\n detections_boxes,\n detections_scores,\n detections_classes,\n categories,\n output_path=output_path)\n self.assertListEqual(result, self._detections_list)\n with tf.gfile.GFile(output_path, 'r') as f:\n written_result = f.read()\n # The json output should have floats written to 4 digits of precision.\n matcher = re.compile(r'\"bbox\":\\s+\\[\\n\\s+\\d+.\\d\\d\\d\\d,', re.MULTILINE)\n self.assertTrue(matcher.findall(written_result))\n written_result = json.loads(written_result)\n self.assertAlmostEqual(result, written_result)\n\n def testExportSegmentsToCOCO(self):\n image_ids = ['first', 'second']\n detection_masks = [np.array(\n [[[0, 1, 0, 1], [0, 1, 1, 0], [0, 0, 0, 1], [0, 1, 0, 1]]],\n dtype=np.uint8), np.array(\n [[[0, 1, 0, 1], [0, 1, 1, 0], [0, 0, 0, 1], [0, 1, 0, 1]]],\n dtype=np.uint8)]\n\n for i, detection_mask in enumerate(detection_masks):\n detection_masks[i] = detection_mask[:, :, :, None]\n\n detection_scores = [np.array([.8], np.float), np.array([.7], np.float)]\n detection_classes = [np.array([1], np.int32), np.array([1], np.int32)]\n\n categories = [{'id': 0, 'name': 'person'},\n {'id': 1, 'name': 'cat'},\n {'id': 2, 'name': 'dog'}]\n output_path = os.path.join(tf.test.get_temp_dir(), 'segments.json')\n result = coco_tools.ExportSegmentsToCOCO(\n image_ids,\n detection_masks,\n detection_scores,\n detection_classes,\n categories,\n output_path=output_path)\n with tf.gfile.GFile(output_path, 'r') as f:\n written_result = f.read()\n written_result = json.loads(written_result)\n mask_load = mask.decode([written_result[0]['segmentation']])\n self.assertTrue(np.allclose(mask_load, detection_masks[0]))\n self.assertAlmostEqual(result, written_result)\n\n def testExportKeypointsToCOCO(self):\n image_ids = ['first', 'second']\n detection_keypoints = [\n np.array(\n [[[100, 200], [300, 400], [500, 600]],\n [[50, 150], [250, 350], [450, 550]]], dtype=np.int32),\n np.array(\n [[[110, 210], [310, 410], [510, 610]],\n [[60, 160], [260, 360], [460, 560]]], dtype=np.int32)]\n\n detection_scores = [np.array([.8, 0.2], np.float),\n np.array([.7, 0.3], np.float)]\n detection_classes = [np.array([1, 1], np.int32), np.array([1, 1], np.int32)]\n\n categories = [{'id': 1, 'name': 'person', 'num_keypoints': 3},\n {'id': 2, 'name': 'cat'},\n {'id': 3, 'name': 'dog'}]\n\n output_path = os.path.join(tf.test.get_temp_dir(), 'keypoints.json')\n result = coco_tools.ExportKeypointsToCOCO(\n image_ids,\n detection_keypoints,\n detection_scores,\n detection_classes,\n categories,\n output_path=output_path)\n\n with tf.gfile.GFile(output_path, 'r') as f:\n written_result = f.read()\n written_result = json.loads(written_result)\n self.assertAlmostEqual(result, written_result)\n\n def testSingleImageDetectionBoxesExport(self):\n boxes = np.array([[0, 0, 1, 1],\n [0, 0, .5, .5],\n [.5, .5, 1, 1]], dtype=np.float32)\n classes = np.array([1, 2, 3], dtype=np.int32)\n scores = np.array([0.8, 0.2, 0.7], dtype=np.float32)\n coco_boxes = np.array([[0, 0, 1, 1],\n [0, 0, .5, .5],\n [.5, .5, .5, .5]], dtype=np.float32)\n coco_annotations = coco_tools.ExportSingleImageDetectionBoxesToCoco(\n image_id='first_image',\n category_id_set=set([1, 2, 3]),\n detection_boxes=boxes,\n detection_classes=classes,\n detection_scores=scores)\n for i, annotation in enumerate(coco_annotations):\n self.assertEqual(annotation['image_id'], 'first_image')\n self.assertEqual(annotation['category_id'], classes[i])\n self.assertAlmostEqual(annotation['score'], scores[i])\n self.assertTrue(np.all(np.isclose(annotation['bbox'], coco_boxes[i])))\n\n def testSingleImageDetectionMaskExport(self):\n masks = np.array(\n [[[1, 1,], [1, 1]],\n [[0, 0], [0, 1]],\n [[0, 0], [0, 0]]], dtype=np.uint8)\n classes = np.array([1, 2, 3], dtype=np.int32)\n scores = np.array([0.8, 0.2, 0.7], dtype=np.float32)\n coco_annotations = coco_tools.ExportSingleImageDetectionMasksToCoco(\n image_id='first_image',\n category_id_set=set([1, 2, 3]),\n detection_classes=classes,\n detection_scores=scores,\n detection_masks=masks)\n expected_counts = ['04', '31', '4']\n for i, mask_annotation in enumerate(coco_annotations):\n self.assertEqual(mask_annotation['segmentation']['counts'],\n expected_counts[i])\n self.assertTrue(np.all(np.equal(mask.decode(\n mask_annotation['segmentation']), masks[i])))\n self.assertEqual(mask_annotation['image_id'], 'first_image')\n self.assertEqual(mask_annotation['category_id'], classes[i])\n self.assertAlmostEqual(mask_annotation['score'], scores[i])\n\n def testSingleImageGroundtruthExport(self):\n masks = np.array(\n [[[1, 1,], [1, 1]],\n [[0, 0], [0, 1]],\n [[0, 0], [0, 0]]], dtype=np.uint8)\n boxes = np.array([[0, 0, 1, 1],\n [0, 0, .5, .5],\n [.5, .5, 1, 1]], dtype=np.float32)\n coco_boxes = np.array([[0, 0, 1, 1],\n [0, 0, .5, .5],\n [.5, .5, .5, .5]], dtype=np.float32)\n classes = np.array([1, 2, 3], dtype=np.int32)\n is_crowd = np.array([0, 1, 0], dtype=np.int32)\n next_annotation_id = 1\n expected_counts = ['04', '31', '4']\n\n # Tests exporting without passing in is_crowd (for backward compatibility).\n coco_annotations = coco_tools.ExportSingleImageGroundtruthToCoco(\n image_id='first_image',\n category_id_set=set([1, 2, 3]),\n next_annotation_id=next_annotation_id,\n groundtruth_boxes=boxes,\n groundtruth_classes=classes,\n groundtruth_masks=masks)\n for i, annotation in enumerate(coco_annotations):\n self.assertEqual(annotation['segmentation']['counts'],\n expected_counts[i])\n self.assertTrue(np.all(np.equal(mask.decode(\n annotation['segmentation']), masks[i])))\n self.assertTrue(np.all(np.isclose(annotation['bbox'], coco_boxes[i])))\n self.assertEqual(annotation['image_id'], 'first_image')\n self.assertEqual(annotation['category_id'], classes[i])\n self.assertEqual(annotation['id'], i + next_annotation_id)\n\n # Tests exporting with is_crowd.\n coco_annotations = coco_tools.ExportSingleImageGroundtruthToCoco(\n image_id='first_image',\n category_id_set=set([1, 2, 3]),\n next_annotation_id=next_annotation_id,\n groundtruth_boxes=boxes,\n groundtruth_classes=classes,\n groundtruth_masks=masks,\n groundtruth_is_crowd=is_crowd)\n for i, annotation in enumerate(coco_annotations):\n self.assertEqual(annotation['segmentation']['counts'],\n expected_counts[i])\n self.assertTrue(np.all(np.equal(mask.decode(\n annotation['segmentation']), masks[i])))\n self.assertTrue(np.all(np.isclose(annotation['bbox'], coco_boxes[i])))\n self.assertEqual(annotation['image_id'], 'first_image')\n self.assertEqual(annotation['category_id'], classes[i])\n self.assertEqual(annotation['iscrowd'], is_crowd[i])\n self.assertEqual(annotation['id'], i + next_annotation_id)\n\n\nif __name__ == '__main__':\n tf.test.main()\n" ]
[ [ "tensorflow.logging.warning", "tensorflow.control_dependencies", "numpy.float32", "numpy.logical_and", "tensorflow.py_func" ], [ "tensorflow.constant", "tensorflow.test.main" ], [ "tensorflow.concat", "tensorflow.range", "tensorflow.greater", "tensorflow.shape", "tensorflow.stack", "tensorflow.zeros", "tensorflow.control_dependencies", "tensorflow.identity", "tensorflow.expand_dims", "tensorflow.assert_equal", "tensorflow.unstack", "tensorflow.map_fn", "tensorflow.no_op", "tensorflow.rank" ], [ "tensorflow.stack", "tensorflow.constant", "tensorflow.test.main" ], [ "numpy.allclose", "tensorflow.gfile.GFile", "tensorflow.test.main", "numpy.array", "tensorflow.test.get_temp_dir", "numpy.isclose" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
cemac/UNRESP_AQSensorTools
[ "0c73eb48ccd1680da866dc344ab22bc40ef899fb" ]
[ "aqtools/getAQMeshData.py" ]
[ "#!/usr/bin/env python\n\"\"\"\nScript name: getAQMeshData.py\nAuthor: JO'N/ CEMAC (University of Leeds)\nDate: March 2018\nPurpose: Download data from an AQMesh pod using the API tool\nUsage: ./getAQMeshData.py <stationID> <startDate> <endDate> <variables> <outFreq>\n <stationID> - Unique ID of the AQMesh station from which you want to download data\n <startDate> - Start date/time (UTC) of data to download, in format YYYY-MM-DDTHH:MM:SS. Or type 'start' to get data from the earliest possible time.\n <endDate> - End date/time (UTC) of data to download, in format YYYY-MM-DDTHH:MM:SS. Or type 'end' to get data from the latest possible time.\n <variables> - List of variables to download, in single quotes separated by spaces, e.g. 'NO PM10 SO2'. Or specify 'ALL' to download all variables\n <outFreq> - \"Frequency of output files. Type 'all' for all data in one file, 'daily' for one calendar day per file, or 'monthly' for one calendar month per file\nOutput: One or multiple csv data files (depending on chosen output frequency) with naming convention: AQMeshData_[stationID]_[dateRange]_[variables].csv\n\"\"\"\n\nimport pandas as pd\nfrom pandas.io.json import json_normalize\nimport json\nimport requests\nfrom dateutil.parser import parse\nimport pytz\nimport datetime as dt\nimport os\n\n\ndef main(stationID, startDate, endDate, variables, outFreq):\n\n pyDir = os.path.dirname(os.path.realpath(__file__))\n\n # PARAMETERS\n allFreqs = ['all', 'daily', 'monthly']\n allVars = ['AIRPRES', 'HUM', 'NO', 'NO2', 'O3', 'PARTICULE_COUNT', 'PM1',\n 'PM10', 'PM2.5', 'PMTOTAL', 'SO2', 'TEMP', 'VOLTAGE']\n colOrder = ['TBTimestamp', 'TETimestamp', 'SensorLabel', 'SensorName',\n 'PreScaled', 'Slope', 'Offset', 'Scaled', 'UnitName', 'Status']\n # READ IN ACCOUNT INFO\n codesFile = os.path.join(pyDir, 'AQMeshCodes.txt')\n assert os.path.exists(\n codesFile), \"Can't find file AQMeshCodes.txt in same directory as python script\"\n f = open(codesFile, 'r')\n lines = f.readlines()\n f.close()\n assert len(\n lines) == 3, \"AQMeshCodes.txt should contain exactly 3 lines: A comment line, Account ID, Licence Key\"\n accountID = lines[1].strip()\n licenceKey = lines[2].strip()\n # CHECK VARIABLES\n if variables == 'ALL':\n vars = allVars\n varStr = 'AllVars'\n else:\n vars = [s for s in variables.split()]\n for v in vars:\n assert v in allVars, \"Variable name '\" + v + \\\n \"' not valid. Full list of available variables: \" + \\\n str(allVars)\n varStr = '-'.join(vars)\n # CHECK OUTPUT FREQUENCY\n assert outFreq in allFreqs, \"Output frequency '\" + outFreq + \\\n \"' not valid. List of available options: \" + str(allFreqs)\n # GET VALID TIME RANGE AND CHECK START/END DATES\n # API documentation here: https://api.airmonitors.net/3.5/documentation?key=D73341AM\n try:\n url = \"https://api.airmonitors.net/3.5/GET/\" + accountID + \\\n \"/\" + licenceKey + \"/stationdata/Period/\" + stationID\n rawText = requests.get(url=url)\n rawJson = json.loads(rawText.text)\n except:\n print(\"Couldn't access data. Are you online? Are the codes in AQMeshCodes.txt correct?\")\n raise\n validStart = parse(rawJson[0]['FirstTETimestamp'])\n validEnd = parse(rawJson[0]['LastTBTimestamp'])\n if startDate == 'start':\n start = validStart\n else:\n try:\n start = pytz.utc.localize(parse(startDate))\n except:\n print(\"Could not interpret start date - check the format\")\n raise\n if endDate == 'end':\n end = validEnd\n else:\n try:\n end = pytz.utc.localize(parse(endDate))\n except:\n print(\"Could not interpret end date - check the format\")\n raise\n assert (start - validStart).seconds >= 0, \"The start date/time must come after \" + str(validStart)\n assert (\n validEnd - end).seconds >= 0, \"The end date/time must come before \" + str(validEnd)\n assert (\n end - start).seconds >= 0, \"The start date/time must come before the end date/time\"\n #####\n\n # SPLIT TIME RANGE INTO DAYS FOR DOWNLOAD\n startDay = dt.datetime(start.year, start.month, start.day, tzinfo=pytz.UTC)\n nextDay = startDay + dt.timedelta(days=1)\n dateDays = [start]\n while nextDay < end:\n dateDays.append(nextDay)\n nextDay += dt.timedelta(days=1)\n dateDays.append(end)\n startDays = dateDays[0:-1]\n endDays = dateDays[1:]\n if(len(endDays) > 1):\n for d, day in enumerate(endDays[:-1]):\n endDays[d] -= dt.timedelta(seconds=1)\n startDaysStr = [t.strftime('%Y-%m-%dT%H:%M:%S') for t in startDays]\n endDaysStr = [t.strftime('%Y-%m-%dT%H:%M:%S') for t in endDays]\n #####\n\n # LOAD IN DATA AND WRITE TO CSV\n allData = pd.DataFrame(columns=colOrder)\n print('Script started on ' + dt.datetime.now().strftime('%c'))\n for i in range(len(startDays)):\n foundData = False\n print('Attempting to download data from ' +\n startDays[i].strftime('%Y-%m-%d'))\n url = \"https://api.airmonitors.net/3.5/GET/\" + accountID + \"/\" + licenceKey + \\\n \"/stationdata/\" + startDaysStr[i] + \\\n \"/\" + endDaysStr[i] + \"/\" + stationID\n if variables != 'ALL':\n url = url + \"/\" + varStr\n rawText = requests.get(url=url)\n if not rawText.text == 'NO DATA WAS FOUND FOR YOUR GIVEN PARAMETERS':\n foundData = True\n rawJson = json.loads(rawText.text)\n rawDF = json_normalize(rawJson, record_path=['Channels'], meta=[\n 'TBTimestamp', 'TETimestamp'])\n procDF = rawDF.drop(['Channel'], axis=1) # Drop channel column\n procDF = procDF[colOrder] # Reorder columns\n # flip row so oldest date first\n procDF = procDF.reindex(index=procDF.index[::-1])\n if outFreq == 'daily':\n if foundData:\n fname = 'AQMeshData_' + stationID + '_' + \\\n startDays[i].strftime('%Y-%m-%d') + '_' + varStr + '.csv'\n print('Writing data to file ' + fname)\n procDF.to_csv(os.path.join(pyDir, fname), index=False)\n elif foundData:\n allData = allData.append(procDF)\n if not foundData:\n print('No data found for this day')\n if outFreq == 'monthly' and (startDays[i].month != (startDays[i] + dt.timedelta(days=1)).month or i == len(startDays) - 1):\n if allData.shape[0] == 0:\n print('No data found for this day')\n else:\n fname = 'AQMeshData_' + stationID + '_' + \\\n startDays[i].strftime('%Y-%m') + '_' + varStr + '.csv'\n print('Writing data to file ' + fname)\n allData.to_csv(os.path.join(pyDir, fname), index=False)\n allData = pd.DataFrame(columns=colOrder)\n if outFreq == 'all':\n if allData.shape[0] == 0:\n print('No data found in entire specified period')\n else:\n fname = 'AQMeshData_' + stationID + '_' + \\\n start.strftime('%Y-%m-%dT%H-%M-%S') + '_to_' + \\\n end.strftime('%Y-%m-%dT%H-%M-%S') + '_' + varStr + '.csv'\n print('Writing data to file ' + fname)\n allData.to_csv(os.path.join(pyDir, fname), index=False)\n print('Script ended on ' + dt.datetime.now().strftime('%c'))\n\n\nif __name__ == '__main__':\n # READ IN COMMAND LINE ARGUMENTS\n import argparse\n parser = argparse.ArgumentParser(description=\"Script to download data from an AQMesh pod using the API tool\",\n epilog=\"Example of use: ./getAQMeshData.py 1733150 2018-01-01T00:00:00 2018-01-31T23:59:59 'SO2 NO2' daily\")\n parser.add_argument(\n \"stationID\", help=\"Unique ID of the AQMesh station from which you want to download data, e.g. 1733150 for El Panama\", type=str)\n parser.add_argument(\n \"startDate\", help=\"Start date/time (UTC) of data to download, in format YYYY-MM-DDTHH:MM:SS, e.g. 2018-01-01T00:00:00. Or type 'start' to get data from the earliest possible time.\", type=str)\n parser.add_argument(\n \"endDate\", help=\"End date/time (UTC) of data to download, in format YYYY-MM-DDTHH:MM:SS, e.g. 2018-01-31T23:59:59. Or type 'end' to get data up to the latest possible time.\", type=str)\n parser.add_argument(\"variables\", help=\"List of variables to download, in single quotes separated by spaces, e.g. 'NO PM10 SO2'. Or specify 'ALL'\\\n to download all variables. Full list of available variables: AIRPRES, HUM, NO, NO2, O3, PARTICULE_COUNT, PM1, PM10, PM2.5, PMTOTAL, SO2,\\\n TEMP, VOLTAGE\", type=str)\n parser.add_argument(\"outFreq\", help=\"Frequency of output files. Type 'all' to generate one output file containing all data,\\\n 'daily' to generate one output file per calendar day, or 'monthly' to generate one output file per calendar month\", type=str)\n args = parser.parse_args()\n # CALL MAIN ROUTINE\n main(args.stationID, args.startDate,\n args.endDate, args.variables, args.outFreq)\n" ]
[ [ "pandas.io.json.json_normalize", "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "0.19", "0.24", "0.20", "0.25" ], "scipy": [], "tensorflow": [] } ]
JONGHYEOK667/Udacity_SelfDrivingCar_P4
[ "6cee1afbd33d704fd594c40ce80c893024f6d022" ]
[ "model.py" ]
[ "#!/usr/bin/env python\n# coding: utf-8\n\n# ---\n\n\n\n\n# In[1]: Setting GPU w/ Tensorflow running\n\n\nimport tensorflow as tf\nprint(tf.__version__)\n\nimport keras\nprint(keras.__version__)\ngpus = tf.config.experimental.list_physical_devices('GPU')\nif gpus:\n try:\n # Currently, memory growth needs to be the same across GPUs\n for gpu in gpus:\n tf.config.experimental.set_memory_growth(gpu, True)\n logical_gpus = tf.config.experimental.list_logical_devices('GPU')\n print(len(gpus), \"Physical GPUs,\", len(logical_gpus), \"Logical GPUs\")\n except RuntimeError as e:\n # Memory rowth must be set before GPUs have been initialized\n print(e)\n \n# config = tf.ConfigProto()\n# config.gpu_option.per_process_gpu_memory_fraction = 0.4\n# session = tf.Session(config=config)\n# session.close()\n\n# In[2]: Import modules\n\n\nimport csv\nimport cv2\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport numpy as np\nfrom tensorflow import keras\nfrom sklearn.utils import shuffle\nimport seaborn as sns\n\n\n\n# In[3]: Load Data (Camera image and steering angle value)\n\n\n\nlines = []\ncenter_img, left_img, right_img, steer_val = [],[],[],[]\n\npath = '0.driving_data/driving_log.csv' ## data path need\n\nwith open(path) as csvfile:\n reader = csv.reader(csvfile)\n for line in reader:\n if float(line[3]) != 0.0:\n center_img.append(line[0])\n left_img.append(line[1])\n right_img.append(line[2])\n steer_val.append(float(line[3]))\n \n else:\n prob = np.random.uniform()\n if prob <= 0.2:\n center_img.append(line[0])\n left_img.append(line[1])\n right_img.append(line[2])\n steer_val.append(float(line[3]))\n \n \n\n \n# In[4]: plot histogram for steering value on logging data (option)\n \n \nf = plt.hist(steer_val, bins = 40, edgecolor='black', linewidth = 1.2)\nplt.title('Collected data', fontsize = 10)\nplt.xlabel('Steering value (scaled)')\nplt.ylabel('counts')\n# plt.savefig('output_fig/1.collected_data.jpg')\n\nsteer_val = np.array(steer_val)\nsteer_val = np.around(steer_val,3)\n\n\n\n\n# In[5]: helper function for this project\n\n\n\ndef BGR2RGB(img):\n img_RGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n return img_RGB\n\n\ndef extract_array(img_path):\n images = []\n for line in img_path:\n source_path = line\n filename = source_path.split('\\\\')[-1]\n current_path = '0.driving_data/IMG/' + filename ## IMG path need!!\n image = cv2.imread(current_path)\n image = BGR2RGB(image)\n images.append(image)\n return images\n\n\n\ndef Flip(imgs):\n images = []\n for img in imgs:\n image = cv2.flip(img,1)\n images.append(image)\n \n return images\n\n\n\n\n# In[6]: Extract Image array data and callibration steering value \n# depends on each camera (left / center / right)\n\n\n## make left / center / right img, steer data\n\noffset = 0.1\n\nimages_left = extract_array(left_img)\nsteers_left = steer_val + offset\n\nimages_center = extract_array(center_img)\nsteers_center = steer_val\n\nimages_right = extract_array(right_img)\nsteers_right = steer_val - offset\n\n\n# In[7]: Flip image and steering value for augment input data\n\n\nimages_left_flip = Flip(images_left)\nsteers_left_flip = -steers_left\n\n\nimages_center_flip = Flip(images_center)\nsteers_center_flip = -steers_center\n\n\nimages_right_flip = Flip(images_right)\nsteers_right_flip = -steers_right\n\n\n# In[8]: select images and steering value for figure (option)\n\n\nindex = np.random.randint(len(steer_val)+1)\n\nimage_left = images_left[index]\nimage_center = images_center[index]\nimage_right = images_right[index]\n\nsteer_left = steers_left[index]\nsteer_center = steers_center[index]\nsteer_right = steers_right[index]\n\n\nimage_left_flip = images_left_flip[index]\nimage_center_flip = images_center_flip[index]\nimage_right_flip = images_right_flip[index]\n\nsteer_left_flip = steers_left_flip[index]\nsteer_center_flip = steers_center_flip[index]\nsteer_right_flip = steers_right_flip[index]\n\n\n\n# In[9]: plot sample input image and steering value (3 camera and fliped)\n# on logging data (option)\n\n\nf, ((ax1,ax2,ax3),(ax4,ax5,ax6)) = plt.subplots(2, 3, figsize=(15, 10))\nax1.imshow(image_left)\nax1.set_title('left, '+'steer('+str(np.around(steer_left,3))+')', fontsize=20)\nax2.imshow(image_center)\nax2.set_title('center, '+'steer('+str(np.around(steer_center,3))+')', fontsize=20)\nax3.imshow(image_right)\nax3.set_title('right, '+'steer('+str(np.around(steer_right,3))+')', fontsize=20)\nax4.imshow(image_left_flip)\nax4.set_title('left_flip, '+'steer('+str(np.around(steer_left_flip,3))+')', fontsize=20)\nax5.imshow(image_center_flip)\nax5.set_title('center_flip, '+'steer('+str(np.around(steer_center_flip,3))+')', fontsize=20)\nax6.imshow(image_right_flip)\nax6.set_title('right_flip, '+'steer('+str(np.around(steer_right_flip,3))+')', fontsize=20)\n\nf.tight_layout()\nf.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.0)\n# f.savefig('output_fig/2.Augmented_Image(BiasedRecover).jpg')\n\n\n\n# In[10]: Make input data (image array) and label (steering value)\n\n\nimages = images_left + images_center + images_right + images_left_flip + images_center_flip + images_right_flip\nimages = np.array(images)\n\nsteers = np.append(steers_left,steers_center)\nsteers = np.append(steers,steers_right)\nsteers = np.append(steers,steers_left_flip)\nsteers = np.append(steers,steers_center_flip)\nsteers = np.append(steers,steers_right_flip)\n\n# images = images_center + images_center_flip \n# images = np.array(images)\n\n# steers = np.append(steers_center,steers_center_flip)\n\n\n# In[11]: plot histogram for all steering value (option)\n\n\nf = plt.hist(steers, bins = 40, edgecolor='black', linewidth = 1.2)\nplt.title('Augmented data', fontsize = 10)\nplt.xlabel('Steering value (scaled)')\nplt.ylabel('counts')\n# plt.savefig('output_fig/3.Augmented_data.jpg')\n\n\n# In[12]: shffle data\n\n\nindex = np.random.choice(steers.shape[0], int(steers.shape[0]/1), replace = False)\nx_suffle = images[index]\ny_suffle = steers[index]\n\n\n# In[13]: split train / valid data\n\n\nx_train = x_suffle[0:int(7*steers.shape[0]/10)]\ny_train = y_suffle[0:int(7*steers.shape[0]/10)]\n\nx_val = x_suffle[int(7*steers.shape[0]/10):]\ny_val = y_suffle[int(7*steers.shape[0]/10):]\n\n\n\n\n# In[14]: define generator\n\n\ndef generator(feature, label, batch_size = 32):\n num_sample = feature.shape[0]\n while 1 :\n for offset in range(0, num_sample, batch_size):\n x_train = feature[offset:offset+batch_size]\n y_train = label[offset:offset+batch_size]\n\n yield (x_train, y_train) \n \n\n\n# In[15]: setting generator parameter and input\n\n\nbatch_size = 256\ntrain_generator = generator(x_train, y_train, batch_size = batch_size)\nval_generator = generator(x_val, y_val, batch_size = batch_size)\n\n\n# In[16]:stack CNN model\n\n\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Flatten, Dense, Lambda, Cropping2D\n\ndrop_rate = 0.4\n\nmodel = keras.models.Sequential([\n keras.layers.Cropping2D(cropping=((70,25),(0,0)),input_shape = (160, 320, 3)),\n keras.layers.Lambda(lambda x : x/255.0 - 0.5),\n keras.layers.Conv2D(filters = 24,kernel_size = (5,5), strides = (2,2), padding = 'same'),\n keras.layers.Activation('relu'),\n keras.layers.Conv2D(filters = 36,kernel_size = (5,5), strides = (2,2), padding = 'same'),\n keras.layers.Activation('relu'),\n keras.layers.Conv2D(filters = 48,kernel_size = (5,5), strides = (2,2), padding = 'same'),\n keras.layers.Activation('relu'),\n keras.layers.Conv2D(filters = 64,kernel_size = (3,3), strides = (1,1), padding = 'same'),\n keras.layers.Activation('relu'),\n keras.layers.Dropout(rate=0.2),\n keras.layers.Conv2D(filters = 64,kernel_size = (3,3), strides = (1,1), padding = 'same'),\n keras.layers.Activation('relu'),\n keras.layers.Flatten(),\n keras.layers.Dense(100, activation = 'relu'),\n keras.layers.Dropout(rate=0.4),\n keras.layers.Dense(50, activation = 'relu'),\n keras.layers.Dropout(rate=0.4),\n keras.layers.Dense(10, activation = 'relu'),\n keras.layers.Dense(1)\n])\n\n\nmodel.summary()\nmodel.compile(optimizer = keras.optimizers.Adam(),\n loss = 'mse', metrics = ['mae'])\n\n\n# In[17]:\n\n\nfrom math import ceil\n\nsteps_per_epoch = ceil(x_train.shape[0]/batch_size)\nvalidation_steps = ceil(x_val.shape[0]/batch_size)\n\n\n\n# In[18]:Fit model\n\n\nhistory = model.fit_generator(train_generator, \n steps_per_epoch = steps_per_epoch,\n validation_data = val_generator,\n validation_steps = validation_steps,\n epochs = 100,\n callbacks = [keras.callbacks.EarlyStopping(patience=5,monitor='val_loss',mode = 'min',verbose = 1 )],\n verbose = 1)\n\n\n# In[19]:plot history for training CNN network (option)\n\n\nhistory.history\nf, (ax1,ax2) = plt.subplots(1, 2, figsize=(15, 6))\nax1.plot(history.history['loss'], '-b', label = 'loss')\nax1.plot(history.history['val_loss'], '--b', label = 'val_loss')\nax2.plot(history.history['mae'], '-r', label = 'mae')\nax2.plot(history.history['val_mae'], '--r', label = 'val_mae')\nax1.set_title('loss (mse)', fontsize=20)\nax1.set_xlabel('Epoch')\nax2.set_title('mae', fontsize=20)\nax2.set_xlabel('Epoch')\nf.tight_layout()\nf.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.1)\n# f.savefig('output_fig/4.Train_History.jpg')\n\n\n# In[20]:save trained model\n\n\nmodel.save('model_temp.h5')\n\n\n" ]
[ [ "numpy.around", "tensorflow.keras.layers.Lambda", "tensorflow.config.experimental.set_memory_growth", "tensorflow.keras.layers.Conv2D", "tensorflow.keras.callbacks.EarlyStopping", "tensorflow.keras.layers.Flatten", "tensorflow.config.experimental.list_logical_devices", "matplotlib.pyplot.title", "tensorflow.keras.layers.Dense", "tensorflow.config.experimental.list_physical_devices", "numpy.append", "matplotlib.pyplot.xlabel", "numpy.array", "matplotlib.pyplot.hist", "matplotlib.pyplot.ylabel", "tensorflow.keras.layers.Activation", "matplotlib.pyplot.subplots", "numpy.random.uniform", "tensorflow.keras.layers.Cropping2D", "tensorflow.keras.optimizers.Adam", "tensorflow.keras.layers.Dropout" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "2.6", "2.4", "2.3", "2.5", "2.2" ] } ]
mikedeltalima/python-qinfer
[ "8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3", "8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3", "8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3" ]
[ "src/qinfer/utils.py", "src/qinfer/parallel.py", "src/qinfer/finite_difference.py" ]
[ "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n##\n# utils.py : some auxiliary functions\n##\n# © 2017, Chris Ferrie ([email protected]) and\n# Christopher Granade ([email protected]).\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the copyright holder nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n##\n\n## FEATURES ###################################################################\n\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nfrom __future__ import division\n\n## IMPORTS ####################################################################\n\nfrom builtins import range\n\nimport warnings\n\nimport numpy as np\nimport numpy.linalg as la\n\nfrom scipy.linalg import eigh\n\nfrom scipy.stats import logistic, binom\nfrom scipy.special import gammaln, gamma, expit, logit\nfrom scipy.linalg import sqrtm\n\nfrom numpy.testing import assert_almost_equal\n\nfrom qinfer._due import due, Doi\nfrom qinfer._exceptions import ApproximationWarning\n\n## FUNCTIONS ##################################################################\n\ndef get_qutip_module(required_version='3.2'):\n \"\"\"\n Attempts to return the qutip module, but\n silently returns ``None`` if it can't be\n imported, or doesn't have version at\n least ``required_version``.\n\n :param str required_version: Valid input to\n ``distutils.version.LooseVersion``.\n :return: The qutip module or ``None``.\n :rtype: ``module`` or ``NoneType``\n \"\"\"\n try:\n import qutip as qt\n from distutils.version import LooseVersion\n _qt_version = LooseVersion(qt.version.version)\n if _qt_version < LooseVersion(required_version):\n return None\n except ImportError:\n return None\n\n return qt\n\ndef check_qutip_version(required_version='3.2'):\n \"\"\"\n Returns ``true`` iff the imported qutip\n version exists and has ``LooseVersion``\n of at least ``required_version``.\n\n :param str required_version: Valid input to\n ``distutils.version.LooseVersion``.\n :rtype: ``bool``\n \"\"\"\n try:\n qt = get_qutip_module(required_version)\n return qt is not None\n except:\n # In any other case (including something other\n # than ImportError) we say it's not good enough\n return False\n\n\ndef binomial_pdf(N,n,p):\n r\"\"\"\n Returns the PDF of the binomial distribution\n :math:`\\operatorname{Bin}(N, p)` evaluated at :math:`n`.\n \"\"\"\n return binom(N, p).pmf(n)\n\ndef multinomial_pdf(n,p):\n r\"\"\"\n Returns the PDF of the multinomial distribution\n :math:`\\operatorname{Multinomial}(N, n, p)=\n \\frac{N!}{n_1!\\cdots n_k!}p_1^{n_1}\\cdots p_k^{n_k}`\n\n :param np.ndarray n : Array of outcome integers\n of shape ``(sides, ...)`` where sides is the number of\n sides on the dice and summing over this index indicates\n the number of rolls for the given experiment.\n :param np.ndarray p : Array of (assumed) probabilities\n of shape ``(sides, ...)`` or ``(sides-1,...)``\n with the rest of the dimensions the same as ``n``.\n If ``sides-1``, the last probability is chosen so that the\n probabilities of all sides sums to 1. If ``sides``\n is the last index, these probabilities are assumed\n to sum to 1.\n\n Note that the numbers of experiments don't need to be given because\n they are implicit in the sum over the 0 index of ``n``.\n \"\"\"\n\n # work in log space to avoid overflow\n log_N_fac = gammaln(np.sum(n, axis=0) + 1)[np.newaxis,...]\n log_n_fac_sum = np.sum(gammaln(n + 1), axis=0)\n\n # since working in log space, we need special\n # consideration at p=0. deal with p=0, n>0 later.\n def nlogp(n,p):\n result = np.zeros(p.shape)\n mask = p!=0\n result[mask] = n[mask] * np.log(p[mask])\n return result\n\n if p.shape[0] == n.shape[0] - 1:\n ep = np.empty(n.shape)\n ep[:p.shape[0],...] = p\n ep[-1,...] = 1-np.sum(p,axis=0)\n else:\n ep = p\n log_p_sum = np.sum(nlogp(n, ep), axis=0)\n\n probs = np.exp(log_N_fac - log_n_fac_sum + log_p_sum)\n\n # if n_k>0 but p_k=0, the whole probability must be 0\n mask = np.sum(np.logical_and(n!=0, ep==0), axis=0) == 0\n probs = mask * probs\n\n return probs[0,...]\n\ndef sample_multinomial(N, p, size=None):\n r\"\"\"\n Draws fixed number of samples N from different\n multinomial distributions (with the same number dice sides).\n\n :param int N: How many samples to draw from each distribution.\n :param np.ndarray p: Probabilities specifying each distribution.\n Sum along axis 0 should be 1.\n :param size: Output shape. ``int`` or tuple of\n ``int``s. If the given shape is,\n e.g., ``(m, n, k)``, then m * n * k samples are drawn\n for each distribution.\n Default is None, in which case a single value\n is returned for each distribution.\n\n :rtype: np.ndarray\n :return: Array of shape ``(p.shape, size)`` or p.shape if\n size is ``None``.\n \"\"\"\n # ensure s is array\n s = np.array([1]) if size is None else np.array([size]).flatten()\n\n def take_samples(ps):\n # we have to flatten to make apply_along_axis work.\n return np.random.multinomial(N, ps, np.prod(s)).flatten()\n\n # should have shape (prod(size)*ps.shape[0], ps.shape[1:])\n samples = np.apply_along_axis(take_samples, 0, p)\n # should have shape (size, p.shape)\n samples = samples.reshape(np.concatenate([s, p.shape]))\n # should have shape (p.shape, size)\n samples = samples.transpose(np.concatenate(\n [np.arange(s.ndim, p.ndim+s.ndim), np.arange(s.ndim)]\n ))\n\n if size is None:\n # get rid of trailing singleton dimension.\n samples = samples[...,0]\n\n return samples\n\n\ndef outer_product(vec):\n r\"\"\"\n Returns the outer product of a vector :math:`v`\n with itself, :math:`v v^\\T`.\n \"\"\"\n return (\n np.dot(vec[:, np.newaxis], vec[np.newaxis, :])\n if len(vec.shape) == 1 else\n np.dot(vec, vec.T)\n )\n\ndef particle_meanfn(weights, locations, fn=None):\n r\"\"\"\n Returns the mean of a function :math:`f` over model\n parameters.\n\n :param numpy.ndarray weights: Weights of each particle.\n :param numpy.ndarray locations: Locations of each\n particle.\n :param callable fn: Function of model parameters to\n take the mean of. If `None`, the identity function\n is assumed.\n \"\"\"\n warnings.warn('particle_meanfn is deprecated, please use distributions.ParticleDistribution',\n DeprecationWarning)\n fn_vals = fn(locations) if fn is not None else locations\n return np.sum(weights * fn_vals.transpose([1, 0]),\n axis=1)\n\n\ndef particle_covariance_mtx(weights,locations):\n \"\"\"\n Returns an estimate of the covariance of a distribution\n represented by a given set of SMC particle.\n\n :param weights: An array containing the weights of each\n particle.\n :param location: An array containing the locations of\n each particle.\n :rtype: :class:`numpy.ndarray`, shape\n ``(n_modelparams, n_modelparams)``.\n :returns: An array containing the estimated covariance matrix.\n \"\"\"\n # TODO: add shapes to docstring.\n warnings.warn('particle_covariance_mtx is deprecated, please use distributions.ParticleDistribution',\n DeprecationWarning)\n\n # Find the mean model vector, shape (n_modelparams, ).\n mu = particle_meanfn(weights, locations)\n\n # Transpose the particle locations to have shape\n # (n_modelparams, n_particles).\n xs = locations.transpose([1, 0])\n # Give a shorter name to the particle weights, shape (n_particles, ).\n ws = weights\n\n cov = (\n # This sum is a reduction over the particle index, chosen to be\n # axis=2. Thus, the sum represents an expectation value over the\n # outer product $x . x^T$.\n #\n # All three factors have the particle index as the rightmost\n # index, axis=2. Using the Einstein summation convention (ESC),\n # we can reduce over the particle index easily while leaving\n # the model parameter index to vary between the two factors\n # of xs.\n #\n # This corresponds to evaluating A_{m,n} = w_{i} x_{m,i} x_{n,i}\n # using the ESC, where A_{m,n} is the temporary array created.\n np.einsum('i,mi,ni', ws, xs, xs)\n # We finish by subracting from the above expectation value\n # the outer product $mu . mu^T$.\n - np.dot(mu[..., np.newaxis], mu[np.newaxis, ...])\n )\n\n # The SMC approximation is not guaranteed to produce a\n # positive-semidefinite covariance matrix. If a negative eigenvalue\n # is produced, we should warn the caller of this.\n assert np.all(np.isfinite(cov))\n if not np.all(la.eig(cov)[0] >= 0):\n warnings.warn('Numerical error in covariance estimation causing positive semidefinite violation.', ApproximationWarning)\n\n return cov\n\n\ndef ellipsoid_volume(A=None, invA=None):\n \"\"\"\n Returns the volume of an ellipsoid given either its\n matrix or the inverse of its matrix.\n \"\"\"\n\n if invA is None and A is None:\n raise ValueError(\"Must pass either inverse(A) or A.\")\n\n if invA is None and A is not None:\n invA = la.inv(A)\n\n # Find the unit sphere volume.\n # http://en.wikipedia.org/wiki/Unit_sphere#General_area_and_volume_formulas\n n = invA.shape[0]\n Vn = (np.pi ** (n/2)) / gamma(1 + (n/2))\n\n return Vn * la.det(sqrtm(invA))\n\[email protected](\n Doi(\"10.1016/j.dam.2007.02.013\"),\n description=\"Khachiyan algorithm\",\n tags=[\"implementation\"]\n)\ndef mvee(points, tol=0.001):\n \"\"\"\n Returns the minimum-volume enclosing ellipse (MVEE)\n of a set of points, using the Khachiyan algorithm.\n \"\"\"\n\n # This function is a port of the matlab function by\n # Nima Moshtagh found here:\n # https://www.mathworks.com/matlabcentral/fileexchange/9542-minimum-volume-enclosing-ellipsoid\n # with accompanying writup here:\n # https://www.researchgate.net/profile/Nima_Moshtagh/publication/254980367_MINIMUM_VOLUME_ENCLOSING_ELLIPSOIDS/links/54aab5260cf25c4c472f487a.pdf\n\n N, d = points.shape\n\n Q = np.zeros([N,d+1])\n Q[:,0:d] = points[0:N,0:d]\n Q[:,d] = np.ones([1,N])\n\n Q = np.transpose(Q)\n points = np.transpose(points)\n count = 1\n err = 1\n u = (1/N) * np.ones(shape = (N,))\n\n while err > tol:\n\n X = np.dot(np.dot(Q, np.diag(u)), np.transpose(Q))\n M = np.diag( np.dot(np.dot(np.transpose(Q), la.inv(X)),Q))\n jdx = np.argmax(M)\n step_size = (M[jdx] - d - 1)/((d+1)*(M[jdx] - 1))\n new_u = (1 - step_size)*u\n new_u[jdx] = new_u[jdx] + step_size\n count = count + 1\n err = la.norm(new_u - u)\n u = new_u\n\n U = np.diag(u)\n c = np.dot(points,u)\n A = (1/d) * la.inv(np.dot(np.dot(points,U), np.transpose(points)) - np.outer(c,c) )\n return A, np.transpose(c)\n\ndef in_ellipsoid(x, A, c):\n \"\"\"\n Determines which of the points ``x`` are in the\n closed ellipsoid with shape matrix ``A`` centered at ``c``.\n For a single point ``x``, this is computed as\n\n .. math::\n (c-x)^T\\cdot A^{-1}\\cdot (c-x) \\leq 1\n\n :param np.ndarray x: Shape ``(n_points, dim)`` or ``n_points``.\n :param np.ndarray A: Shape ``(dim, dim)``, positive definite\n :param np.ndarray c: Shape ``(dim)``\n :return: `bool` or array of bools of length ``n_points``\n \"\"\"\n if x.ndim == 1:\n y = c - x\n return np.einsum('j,jl,l', y, np.linalg.inv(A), y) <= 1\n else:\n y = c[np.newaxis,:] - x\n return np.einsum('ij,jl,il->i', y, np.linalg.inv(A), y) <= 1\n\ndef uniquify(seq):\n \"\"\"\n Returns the unique elements of a sequence ``seq``.\n \"\"\"\n #from http://stackoverflow.com/a/480227/1205799\n seen = set()\n seen_add = seen.add\n return [ x for x in seq if x not in seen and not seen_add(x)]\n\ndef assert_sigfigs_equal(x, y, sigfigs=3):\n \"\"\"\n Tests if all elements in x and y\n agree up to a certain number of\n significant figures.\n\n :param np.ndarray x: Array of numbers.\n :param np.ndarray y: Array of numbers you want to\n be equal to ``x``.\n :param int sigfigs: How many significant\n figures you demand that they share.\n Default is 3.\n \"\"\"\n # determine which power of 10 best describes x\n xpow = np.floor(np.log10(x))\n # now rescale 1 \\leq x < 9\n x = x * 10**(- xpow)\n # scale y by the same amount\n y = y * 10**(- xpow)\n\n # now test if abs(x-y) < 0.5 * 10**(-sigfigs)\n assert_almost_equal(x, y, sigfigs)\n\ndef format_uncertainty(value, uncertianty, scinotn_break=4):\n \"\"\"\n Given a value and its uncertianty, format as a LaTeX string\n for pretty-printing.\n\n :param int scinotn_break: How many decimal points to print\n before breaking into scientific notation.\n \"\"\"\n if uncertianty == 0:\n # Return the exact number, without the ± annotation as a fixed point\n # number, since all digits matter.\n # FIXME: this assumes a precision of 6; need to select that dynamically.\n return \"{0:f}\".format(value)\n else:\n # Return a string of the form \"0.00 \\pm 0.01\".\n mag_unc = int(np.log10(np.abs(uncertianty)))\n # Zero should be printed as a single digit; that is, as wide as str \"1\".\n mag_val = int(np.log10(np.abs(value))) if value != 0 else 0\n n_digits = max(mag_val - mag_unc, 0)\n\n\n if abs(mag_val) < abs(mag_unc) and abs(mag_unc) > scinotn_break:\n # We're formatting something close to zero, so recale uncertianty\n # accordingly.\n scale = 10**mag_unc\n return r\"({{0:0.{0}f}} \\pm {{1:0.{0}f}}) \\times 10^{{2}}\".format(\n n_digits\n ).format(\n value / scale,\n uncertianty / scale,\n mag_unc\n )\n if abs(mag_val) <= scinotn_break:\n return r\"{{0:0.{n_digits}f}} \\pm {{1:0.{n_digits}f}}\".format(n_digits=n_digits).format(value, uncertianty)\n else:\n scale = 10**mag_val\n return r\"({{0:0.{0}f}} \\pm {{1:0.{0}f}}) \\times 10^{{2}}\".format(\n n_digits\n ).format(\n value / scale,\n uncertianty / scale,\n mag_val\n )\n\ndef compactspace(scale, n):\n r\"\"\"\n Returns points :math:`x` spaced in the open interval\n :math:`(-\\infty, \\infty)` by linearly spacing in the compactified\n coordinate :math:`s(x) = e^{-\\alpha x} / (1 + e^{-\\alpha x})^2`,\n where :math:`\\alpha` is a scale factor.\n \"\"\"\n logit = logistic(scale=scale).ppf\n compact_xs = np.linspace(0, 1, n + 2)[1:-1]\n return logit(compact_xs)\n\ndef to_simplex(y):\n r\"\"\"\n Interprets the last index of ``y`` as stick breaking fractions \n in logit space and returns a non-negative array of \n the same shape where the last dimension always sums to unity.\n \n A unit simplex is a list of non-negative numbers :math:`(x_1,...,x_K)`\n that sum to one, :math:`\\sum_{k=1}^K x_k=1`, for example, the \n probabilities of an K-sided die.\n It is sometimes desireable to parameterize this object with variables \n that are unconstrained and \"decorrelated\".\n To this end, we imagine :math:`\\vec{x}` as a partition of the unit \n stick :math:`[0,1]` with :math:`K-1` break points between \n :math:`K` successive intervals of respective lengths :math:`(x_1,...,x_K)`.\n Instead of storing the interval lengths, we start from the left-most break \n point and iteratively store the breaking fractions, :math:`z_k`, \n of the remaining stick.\n This gives the formula \n :math:`z_k=x_k / (1-\\sum_{k'=1}^{k-1}x_k)` with the convention \n :math:`x_0:=0`, \n which has an inverse formula :math:`x_k = z_k(1-z_{k-1})\\cdots(1-z_1)`.\n Note that :math:`z_K=1` since the last stick is not broken; this is the \n result of the redundant information imposed by :math:`\\sum_{k=1}^K x_k=1`.\n To unbound the parameters :math:`z_k` into the real line, \n we pass through the logit function, \n :math:`\\operatorname{logit}(p)=\\log\\frac{p}{1-p}`, \n to end up with the parameterization \n :math:`y_k=\\operatorname{logit}(z_k)+\\log(K-k)`, with the convention \n :math:`y_K=0`.\n The shift by :math:`\\log(K-k)` is largely asthetic and causes the \n uniform simplex :math:`\\vec{x}=(1/K,1/K,...,1/K)` to be mapped to \n :math:`\\vec{x}=(0,0,...,0)`.\n\n Inverse to :func:`from_simplex`.\n\n :param np.ndarray: Array of logit space stick breaking \n fractions along the last index.\n\n :rtype: ``np.ndarray``\n \"\"\"\n n = y.shape[-1]\n # z are the stick breaking fractions in [0,1]\n z = expit(y - np.log(n - np.arange(1, n+1)))\n x = np.empty(y.shape)\n x[..., 0] = z[..., 0]\n x[..., 1:] = z[..., 1:] * (1 - z[..., :-1]).cumprod(axis=-1)\n return x\n\ndef from_simplex(x):\n r\"\"\"\n Inteprets the last index of x as unit simplices and returns a\n real array of the sampe shape in logit space.\n\n Inverse to :func:`to_simplex` ; see that function for more details.\n\n :param np.ndarray: Array of unit simplices along the last index.\n \n :rtype: ``np.ndarray``\n \"\"\"\n n = x.shape[-1]\n # z are the stick breaking fractions in [0,1]\n # the last one is always 1, so don't worry about it\n z = np.empty(shape=x.shape)\n z[..., 0] = x[..., 0]\n z[..., 1:-1] = x[..., 1:-1] / (1 - x[..., :-2].cumsum(axis=-1))\n\n # now z are the logit-transformed breaking fractions\n z[..., :-1] = logit(z[..., :-1]) - logit(1 / (n - np.arange(n-1, dtype=np.float)))\n # set this to 0 manually to avoid subtracting inf-inf\n z[..., -1] = 0\n return z\n\ndef pretty_time(secs, force_h=False, force_m=False):\n if secs > 86400:\n return \"{d} days, \".format(d=int(secs//86400)) + pretty_time(secs % 86400, force_h=True)\n elif force_h or secs > 3600:\n return \"{h}:\".format(h=int(secs//3600)) + pretty_time(secs % 3600, force_m=True)\n elif force_m or secs > 60:\n return (\n \"{m:0>2}:{s:0>2}\" if force_m else \"{m}:{s:0>2}\"\n ).format(m=int(secs//60), s=int(secs%60))\n else:\n return \"{0:0.2f} seconds\".format(secs)\n\ndef safe_shape(arr, idx=0, default=1):\n shape = np.shape(arr)\n return shape[idx] if idx < len(shape) else default\n\ndef join_struct_arrays(arrays):\n \"\"\"\n Takes a list of possibly structured arrays, concatenates their\n dtypes, and returns one big array with that dtype. Does the\n inverse of ``separate_struct_array``.\n\n :param list arrays: List of ``np.ndarray``s\n \"\"\"\n # taken from http://stackoverflow.com/questions/5355744/numpy-joining-structured-arrays\n sizes = np.array([a.itemsize for a in arrays])\n offsets = np.r_[0, sizes.cumsum()]\n shape = arrays[0].shape\n joint = np.empty(shape + (offsets[-1],), dtype=np.uint8)\n for a, size, offset in zip(arrays, sizes, offsets):\n joint[...,offset:offset+size] = np.atleast_1d(a).view(np.uint8).reshape(shape + (size,))\n dtype = sum((a.dtype.descr for a in arrays), [])\n return joint.ravel().view(dtype)\n\ndef separate_struct_array(array, dtypes):\n \"\"\"\n Takes an array with a structured dtype, and separates it out into\n a list of arrays with dtypes coming from the input ``dtypes``.\n Does the inverse of ``join_struct_arrays``.\n\n :param np.ndarray array: Structured array.\n :param dtypes: List of ``np.dtype``, or just a ``np.dtype`` and the number of\n them is figured out automatically by counting bytes.\n \"\"\"\n try:\n offsets = np.cumsum([np.dtype(dtype).itemsize for dtype in dtypes])\n except TypeError:\n dtype_size = np.dtype(dtypes).itemsize\n num_fields = int(array.nbytes / (array.size * dtype_size))\n offsets = np.cumsum([dtype_size] * num_fields)\n dtypes = [dtypes] * num_fields\n offsets = np.concatenate([[0], offsets]).astype(int)\n uint_array = array.view(np.uint8).reshape(array.shape + (-1,))\n return [\n uint_array[..., offsets[idx]:offsets[idx+1]].flatten().view(dtype)\n for idx, dtype in enumerate(dtypes)\n ]\n\ndef sqrtm_psd(A, est_error=True, check_finite=True):\n \"\"\"\n Returns the matrix square root of a positive semidefinite matrix,\n truncating negative eigenvalues.\n \"\"\"\n w, v = eigh(A, check_finite=check_finite)\n mask = w <= 0\n w[mask] = 0\n np.sqrt(w, out=w)\n A_sqrt = (v * w).dot(v.conj().T)\n\n if est_error:\n return A_sqrt, np.linalg.norm(np.dot(A_sqrt, A_sqrt) - A, 'fro')\n else:\n return A_sqrt\n\ndef decorate_init(init_decorator):\n \"\"\"\n Given a class definition and a decorator that acts on methods,\n applies that decorator to the class' __init__ method.\n Useful for decorating __init__ while still allowing __init__ to be\n inherited.\n \"\"\"\n\n def class_decorator(cls):\n cls.__init__ = init_decorator(cls.__init__)\n return cls\n\n return class_decorator\n\n#==============================================================================\n#Test Code\nif __name__ == \"__main__\":\n\n from mpl_toolkits.mplot3d import Axes3D\n from mpl_toolkits.mplot3d.art3d import Poly3DCollection\n import matplotlib.pyplot as plt\n from scipy.spatial import Delaunay\n\n #some random points\n points = np.array([[ 0.53135758, -0.25818091, -0.32382715],\n [ 0.58368177, -0.3286576, -0.23854156,],\n [ 0.18741533, 0.03066228, -0.94294771],\n [ 0.65685862, -0.09220681, -0.60347573],\n [ 0.63137604, -0.22978685, -0.27479238],\n [ 0.59683195, -0.15111101, -0.40536606],\n [ 0.68646128, 0.0046802, -0.68407367],\n [ 0.62311759, 0.0101013, -0.75863324]])\n\n # compute mvee\n A, centroid = mvee(points)\n print(A)\n\n # point it and some other stuff\n U, D, V = la.svd(A)\n\n rx, ry, rz = [1/np.sqrt(d) for d in D]\n u, v = np.mgrid[0:2*np.pi:20j,-np.pi/2:np.pi/2:10j]\n\n x=rx*np.cos(u)*np.cos(v)\n y=ry*np.sin(u)*np.cos(v)\n z=rz*np.sin(v)\n\n for idx in range(x.shape[0]):\n for idy in range(y.shape[1]):\n x[idx,idy],y[idx,idy],z[idx,idy] = np.dot(np.transpose(V),np.array([x[idx,idy],y[idx,idy],z[idx,idy]])) + centroid\n\n\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n ax.scatter(points[:,0],points[:,1],points[:,2])\n ax.plot_surface(x, y, z, cstride = 1, rstride = 1, alpha = 0.1)\n plt.show()\n\ndef binom_est_p(n, N, hedge=float(0)):\n r\"\"\"\n Given a number of successes :math:`n` and a number of trials :math:`N`,\n estimates the binomial distribution parameter :math:`p` using the\n hedged maximum likelihood estimator of [FB12]_.\n\n :param n: Number of successes.\n :type n: `numpy.ndarray` or `int`\n :param int N: Number of trials.\n :param float hedge: Hedging parameter :math:`\\beta`.\n :rtype: `float` or `numpy.ndarray`.\n :return: The estimated binomial distribution parameter :math:`p` for each\n value of :math:`n`.\n \"\"\"\n return (n + hedge) / (N + 2 * hedge)\n\ndef binom_est_error(p, N, hedge = float(0)):\n r\"\"\"\n \"\"\"\n\n # asymptotic np.sqrt(p * (1 - p) / N)\n return np.sqrt(p*(1-p)/(N+2*hedge+1))\n", "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n##\n# parallel.py: Tools for distributing computation.\n##\n# © 2017, Chris Ferrie ([email protected]) and\n# Christopher Granade ([email protected]).\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the copyright holder nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n##\n\n## FEATURES ##################################################################\n\nfrom __future__ import absolute_import\nfrom __future__ import division # Ensures that a/b is always a float.\n\n## EXPORTS ###################################################################\n\n__all__ = ['DirectViewParallelizedModel']\n\n## IMPORTS ###################################################################\n\nimport numpy as np\nfrom qinfer.derived_models import DerivedModel\n\nimport warnings\n\ntry:\n import ipyparallel as ipp\n interactive = ipp.interactive\nexcept ImportError:\n try:\n import IPython.parallel as ipp\n interactive = ipp.interactive\n except (ImportError, AttributeError):\n import warnings\n warnings.warn(\n \"Could not import IPython parallel. \"\n \"Parallelization support will be disabled.\"\n )\n ipp = None\n interactive = lambda fn: fn\n\n## LOGGING ###################################################################\n\nimport logging\nlogger = logging.getLogger(__name__)\nlogger.addHandler(logging.NullHandler())\n \n## CLASSES ###################################################################\n\nclass DirectViewParallelizedModel(DerivedModel):\n r\"\"\"\n Given an instance of a :class:`Model`, parallelizes execution of that model's\n likelihood by breaking the ``modelparams`` array into segments and\n executing a segment on each member of a :class:`~ipyparallel.DirectView`.\n \n This :class:`Model` assumes that it has ownership over the DirectView, such\n that no other processes will send tasks during the lifetime of the Model.\n\n If you are having trouble pickling your model, consider switching to \n ``dill`` by calling ``direct_view.use_dill()``. This mode gives more support \n for closures.\n \n :param qinfer.Model serial_model: Model to be parallelized. This\n model will be distributed to the engines in the direct view, such that\n the model must support pickling.\n :param ipyparallel.DirectView direct_view: Direct view onto the engines\n that will be used to parallelize evaluation of the model's likelihood\n function.\n :param bool purge_client: If ``True``, then this model will purge results\n and metadata from the IPython client whenever the model cache is cleared.\n This is useful for solving memory leaks caused by very large numbers of\n calls to ``likelihood``. By default, this is disabled, since enabling\n this option can cause data loss if the client is being sent other tasks\n during the operation of this model.\n :param int serial_threshold: Sets the number of model vectors below which\n the serial model is to be preferred. By default, this is set to ``10 *\n n_engines``, where ``n_engines`` is the number of engines exposed by\n ``direct_view``.\n \"\"\"\n \n ## INITIALIZER ##\n \n def __init__(self, serial_model, direct_view, purge_client=False, serial_threshold=None):\n if ipp is None:\n raise RuntimeError(\n \"This model requires IPython parallelization support, \"\n \"but an error was raised importing IPython.parallel.\"\n )\n\n self._dv = direct_view\n self._purge_client = purge_client\n self._serial_threshold = (\n 10 * self.n_engines\n if serial_threshold is None else int(serial_threshold)\n )\n \n super(DirectViewParallelizedModel, self).__init__(serial_model)\n \n ## SPECIAL METHODS ##\n \n def __getstate__(self):\n # Since instances of this class will be pickled as they are passed to\n # remote engines, we need to be careful not to include _dv\n return {\n '_underlying_model': self._underlying_model,\n '_dv': None,\n '_call_count': self._call_count,\n '_sim_count': self._sim_count,\n '_serial_threshold': self._serial_threshold\n }\n \n ## PROPERTIES ##\n\n # Provide _serial_model as a back-compat.\n @property\n def _serial_model(self):\n warnings.warn(\"_serial_model is deprecated in favor of _underlying_model.\",\n DeprecationWarning\n )\n return self._underlying_model\n @_serial_model.setter\n def _serial_model(self, value):\n warnings.warn(\"_serial_model is deprecated in favor of _underlying_model.\",\n DeprecationWarning\n )\n self._underlying_model = value\n \n\n @property\n def n_engines(self):\n \"\"\"\n The number of engines seen by the direct view owned by this parallelized\n model.\n\n :rtype: int\n \"\"\"\n return len(self._dv) if self._dv is not None else 0\n \n ## METHODS ##\n \n def clear_cache(self):\n \"\"\"\n Clears any cache associated with the serial model and the engines\n seen by the direct view.\n \"\"\"\n self.underlying_model.clear_cache()\n try:\n logger.info('DirectView results has {} items. Clearing.'.format(\n len(self._dv.results)\n ))\n self._dv.purge_results('all')\n if self._purge_client:\n self._dv.client.purge_everything()\n except:\n pass\n \n def likelihood(self, outcomes, modelparams, expparams):\n \"\"\"\n Returns the likelihood for the underlying (serial) model, distributing\n the model parameter array across the engines controlled by this\n parallelized model. Returns what the serial model would return, see\n :attr:`~Model.likelihood`\n \"\"\"\n # By calling the superclass implementation, we can consolidate\n # call counting there.\n super(DirectViewParallelizedModel, self).likelihood(outcomes, modelparams, expparams)\n\n # If there's less models than some threshold, just use the serial model.\n # By default, we'll set that threshold to be the number of engines * 10.\n if modelparams.shape[0] <= self._serial_threshold:\n return self.underlying_model.likelihood(outcomes, modelparams, expparams)\n \n if self._dv is None:\n raise RuntimeError(\n \"No direct view provided; this may be because the instance was \"\n \"loaded from a pickle or NumPy saved array without providing a \"\n \"new direct view.\"\n )\n\n # Need to decorate with interactive to overcome namespace issues with\n # remote engines.\n @interactive\n def serial_likelihood(mps, sm, os, eps):\n return sm.likelihood(os, mps, eps)\n\n # TODO: check whether there's a better way to pass the extra parameters\n # that doesn't use so much memory.\n # The trick is that serial_likelihood will be pickled, so we need to be\n # careful about closures.\n L = self._dv.map_sync(\n serial_likelihood,\n np.array_split(modelparams, self.n_engines, axis=0),\n [self.underlying_model] * self.n_engines,\n [outcomes] * self.n_engines,\n [expparams] * self.n_engines\n )\n\n return np.concatenate(L, axis=1)\n\n def simulate_experiment(self, modelparams, expparams, repeat=1, split_by_modelparams=True):\n \"\"\"\n Simulates the underlying (serial) model using the parallel \n engines. Returns what the serial model would return, see\n :attr:`~Simulatable.simulate_experiment`\n\n :param bool split_by_modelparams: If ``True``, splits up\n ``modelparams`` into `n_engines` chunks and distributes \n across engines. If ``False``, splits up ``expparams``.\n \"\"\"\n # By calling the superclass implementation, we can consolidate\n # simulation counting there.\n super(DirectViewParallelizedModel, self).simulate_experiment(modelparams, expparams, repeat=repeat)\n\n if self._dv is None:\n raise RuntimeError(\n \"No direct view provided; this may be because the instance was \"\n \"loaded from a pickle or NumPy saved array without providing a \"\n \"new direct view.\"\n )\n\n # Need to decorate with interactive to overcome namespace issues with\n # remote engines.\n @interactive\n def serial_simulator(sm, mps, eps, r):\n return sm.simulate_experiment(mps, eps, repeat=r)\n\n if split_by_modelparams:\n # If there's less models than some threshold, just use the serial model.\n # By default, we'll set that threshold to be the number of engines * 10.\n if modelparams.shape[0] <= self._serial_threshold:\n return self.underlying_model.simulate_experiment(modelparams, expparams, repeat=repeat)\n\n # The trick is that serial_likelihood will be pickled, so we need to be\n # careful about closures.\n os = self._dv.map_sync(\n serial_simulator,\n [self.underlying_model] * self.n_engines,\n np.array_split(modelparams, self.n_engines, axis=0),\n [expparams] * self.n_engines,\n [repeat] * self.n_engines\n )\n\n return np.concatenate(os, axis=0)\n\n else:\n # If there's less models than some threshold, just use the serial model.\n # By default, we'll set that threshold to be the number of engines * 10.\n if expparams.shape[0] <= self._serial_threshold:\n return self.underlying_model.simulate_experiment(modelparams, expparams, repeat=repeat)\n\n # The trick is that serial_likelihood will be pickled, so we need to be\n # careful about closures.\n os = self._dv.map_sync(\n serial_simulator,\n [self.underlying_model] * self.n_engines,\n [modelparams] * self.n_engines,\n np.array_split(expparams, self.n_engines, axis=0),\n [repeat] * self.n_engines\n )\n\n return np.concatenate(os, axis=1)\n\n", "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n##\n# finite_difference.py: Implementation of central finite difference\n# approximator for first derivatives.\n##\n# © 2017, Chris Ferrie ([email protected]) and\n# Christopher Granade ([email protected]).\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the copyright holder nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n##\n\n## FEATURES ###################################################################\n\nfrom __future__ import absolute_import\nfrom __future__ import division\n\n## ALL ########################################################################\n\n# We use __all__ to restrict what globals are visible to external modules.\n__all__ = [\n 'FiniteDifference'\n]\n\n## IMPORTS ####################################################################\n\nfrom builtins import range\n\nimport numpy as np\n\n## CLASSES ####################################################################\n\nclass FiniteDifference(object):\n \"\"\"\n Calculates finite differences of a scalar function of multiple\n variables.\n \n :param func: Function to take finite differences of.\n :type func: Function taking a single argument, an array of shape\n ``(n_points, n_args)``, and returning an array of shape\n ``(n_points,)``.\n :param int n_args: Number of arguments represented by ``func``.\n :param h: Step sizes to be used in calculating finite differences.\n :type h: Scalar, or array of shape ``(n_args,)``.\n \"\"\"\n\n # TODO: add order parameter to generalize to higher orders.\n def __init__(self, func, n_args, h=1e-10):\n self.func = func\n self.n_args = n_args\n if np.isscalar(h): \n self.h = h * np.ones((n_args,))\n else:\n self.h = h\n \n def central(self, xs):\n grad = np.zeros((self.n_args,))\n f = self.func\n \n for idx_arg in range(self.n_args):\n step = np.zeros((self.n_args,))\n step[idx_arg] = self.h[idx_arg]\n grad[idx_arg] = f(xs + step / 2) - f(xs - step / 2)\n \n return grad / self.h\n \n __call__ = central\n \n" ]
[ [ "numpy.diag", "numpy.dot", "numpy.sqrt", "numpy.einsum", "numpy.linspace", "numpy.cumsum", "numpy.dtype", "numpy.concatenate", "scipy.special.logit", "numpy.exp", "numpy.linalg.svd", "numpy.arange", "numpy.linalg.eig", "numpy.sin", "numpy.atleast_1d", "numpy.testing.assert_almost_equal", "scipy.linalg.eigh", "numpy.apply_along_axis", "numpy.argmax", "numpy.outer", "numpy.zeros", "matplotlib.pyplot.figure", "numpy.log", "scipy.special.gamma", "numpy.linalg.inv", "numpy.log10", "scipy.stats.binom", "scipy.special.gammaln", "numpy.transpose", "matplotlib.pyplot.show", "numpy.array", "numpy.sum", "numpy.logical_and", "scipy.stats.logistic", "numpy.abs", "numpy.isfinite", "numpy.linalg.norm", "numpy.cos", "numpy.ones", "numpy.shape", "numpy.prod", "scipy.linalg.sqrtm", "numpy.empty" ], [ "numpy.concatenate", "numpy.array_split" ], [ "numpy.zeros", "numpy.isscalar", "numpy.ones" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "0.12", "0.14", "0.15" ], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
TheJacksonLaboratory/JAX_Microbiome_Workshop
[ "800dffdec753b7b1c2a08b0e0ef29d85e54eb5cc" ]
[ "scripts/create-table.py" ]
[ "import pandas as pd\nimport sys\nimport os\nimport re\nimport shutil\nimport subprocess\n\ninputs=sys.argv[1]\noutput=sys.argv[2]\n#names=[\"Username\", \"IP\", \"Terminal 1\", \"Terminal 2\", \"RStudio\", \"Jupyter\", \"Download Files\"]\ndf = pd.read_csv(inputs, sep=\",\", header=None, names=[\"Username\", \"IP\"])\ndf['Terminal 1'] = df[\"IP\"].map(lambda beta_value: \"<a href='{}/terminal/' target='_blank'>terminal 1</a>\".format(beta_value))\ndf['Terminal 2'] = df[\"IP\"].map(lambda beta_value: \"<a href='{}/terminal2/' target='_blank'>terminal 2</a>\".format(beta_value))\ndf['RStudio'] = df[\"IP\"].map(lambda beta_value: \"<a href='{}/rstudio' target='_blank'>rstudio</a>\".format(beta_value))\ndf['Download Files'] = df[\"IP\"].map(lambda beta_value: \"<a href='{}' target='_blank'>download files</a>\".format(beta_value))\n\nprint(df)\nprint(df.columns)\ndel df['IP']\ndf.to_csv(\"csv-intermediate-file-csv\", index=False, header=[\"User\", \"Terminal 1\", \"Terminal 2\", \"RStudio\", \"Download Files\"])\n\ndef csvtomd(output):\n return subprocess.Popen(\n 'csvtomd csv-intermediate-file-csv > {}; rm csv-intermediate-file-csv'.format(output),\n stdout=subprocess.PIPE, shell=True)\ncsvtomd(output)\n" ]
[ [ "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
samuelfneumann/rllab
[ "ccd80547380b25344b1b091e730beb646d12d192" ]
[ "rllab/optimizers/conjugate_gradient_optimizer.py" ]
[ "from rllab.misc import ext\nfrom rllab.misc import krylov\nfrom rllab.misc import logger\nfrom rllab.core.serializable import Serializable\nimport theano.tensor as TT\nimport theano\nimport itertools\nimport numpy as np\nfrom rllab.misc.ext import sliced_fun\nfrom ast import Num\n\n\nclass PerlmutterHvp(Serializable):\n\n def __init__(self, num_slices=1):\n Serializable.quick_init(self, locals())\n self.target = None\n self.reg_coeff = None\n self.opt_fun = None\n self._num_slices = num_slices\n\n def update_opt(self, f, target, inputs, reg_coeff):\n self.target = target\n self.reg_coeff = reg_coeff\n params = target.get_params(trainable=True)\n\n constraint_grads = theano.grad(\n f, wrt=params, disconnected_inputs='warn')\n xs = tuple([ext.new_tensor_like(\"%s x\" % p.name, p) for p in params])\n\n def Hx_plain():\n Hx_plain_splits = TT.grad(\n TT.sum([TT.sum(g * x)\n for g, x in zip(constraint_grads, xs)]),\n wrt=params,\n disconnected_inputs='warn'\n )\n return TT.concatenate([TT.flatten(s) for s in Hx_plain_splits])\n\n self.opt_fun = ext.lazydict(\n f_Hx_plain=lambda: ext.compile_function(\n inputs=inputs + xs,\n outputs=Hx_plain(),\n log_name=\"f_Hx_plain\",\n ),\n )\n\n def build_eval(self, inputs):\n def eval(x):\n xs = tuple(self.target.flat_to_params(x, trainable=True))\n ret = sliced_fun(self.opt_fun[\"f_Hx_plain\"], self._num_slices)(\n inputs, xs) + self.reg_coeff * x\n return ret\n\n return eval\n\n\nclass FiniteDifferenceHvp(Serializable):\n\n def __init__(self, base_eps=1e-8, symmetric=True, grad_clip=None, num_slices=1):\n Serializable.quick_init(self, locals())\n self.base_eps = base_eps\n self.symmetric = symmetric\n self.grad_clip = grad_clip\n self._num_slices = num_slices\n\n def update_opt(self, f, target, inputs, reg_coeff):\n self.target = target\n self.reg_coeff = reg_coeff\n\n params = target.get_params(trainable=True)\n\n constraint_grads = theano.grad(\n f, wrt=params, disconnected_inputs='warn')\n flat_grad = ext.flatten_tensor_variables(constraint_grads)\n\n def f_Hx_plain(*args):\n inputs_ = args[:len(inputs)]\n xs = args[len(inputs):]\n flat_xs = np.concatenate([np.reshape(x, (-1,)) for x in xs])\n param_val = self.target.get_param_values(trainable=True)\n eps = np.cast['float32'](\n self.base_eps / (np.linalg.norm(param_val) + 1e-8))\n self.target.set_param_values(\n param_val + eps * flat_xs, trainable=True)\n flat_grad_dvplus = self.opt_fun[\"f_grad\"](*inputs_)\n if self.symmetric:\n self.target.set_param_values(\n param_val - eps * flat_xs, trainable=True)\n flat_grad_dvminus = self.opt_fun[\"f_grad\"](*inputs_)\n hx = (flat_grad_dvplus - flat_grad_dvminus) / (2 * eps)\n self.target.set_param_values(param_val, trainable=True)\n else:\n self.target.set_param_values(param_val, trainable=True)\n flat_grad = self.opt_fun[\"f_grad\"](*inputs_)\n hx = (flat_grad_dvplus - flat_grad) / eps\n return hx\n\n self.opt_fun = ext.lazydict(\n f_grad=lambda: ext.compile_function(\n inputs=inputs,\n outputs=flat_grad,\n log_name=\"f_grad\",\n ),\n f_Hx_plain=lambda: f_Hx_plain,\n )\n\n def build_eval(self, inputs):\n def eval(x):\n xs = tuple(self.target.flat_to_params(x, trainable=True))\n ret = sliced_fun(self.opt_fun[\"f_Hx_plain\"], self._num_slices)(\n inputs, xs) + self.reg_coeff * x\n return ret\n\n return eval\n\n\nclass ConjugateGradientOptimizer(Serializable):\n \"\"\"\n Performs constrained optimization via line search. The search direction is computed using a conjugate gradient\n algorithm, which gives x = A^{-1}g, where A is a second order approximation of the constraint and g is the gradient\n of the loss function.\n \"\"\"\n\n def __init__(\n self,\n cg_iters=10,\n reg_coeff=1e-5,\n subsample_factor=1.,\n backtrack_ratio=0.8,\n max_backtracks=15,\n accept_violation=False,\n hvp_approach=None,\n num_slices=1):\n \"\"\"\n\n :param cg_iters: The number of CG iterations used to calculate A^-1 g\n :param reg_coeff: A small value so that A -> A + reg*I\n :param subsample_factor: Subsampling factor to reduce samples when using \"conjugate gradient. Since the\n computation time for the descent direction dominates, this can greatly reduce the overall computation time.\n :param accept_violation: whether to accept the descent step if it violates the line search condition after\n exhausting all backtracking budgets\n :return:\n \"\"\"\n Serializable.quick_init(self, locals())\n self._cg_iters = cg_iters\n self._reg_coeff = reg_coeff\n self._subsample_factor = subsample_factor\n self._backtrack_ratio = backtrack_ratio\n self._max_backtracks = max_backtracks\n self._num_slices = num_slices\n\n self._opt_fun = None\n self._target = None\n self._max_constraint_val = None\n self._constraint_name = None\n self._accept_violation = accept_violation\n if hvp_approach is None:\n hvp_approach = PerlmutterHvp(num_slices)\n self._hvp_approach = hvp_approach\n\n def update_opt(self, loss, target, leq_constraint, inputs, extra_inputs=None, constraint_name=\"constraint\", *args,\n **kwargs):\n \"\"\"\n :param loss: Symbolic expression for the loss function.\n :param target: A parameterized object to optimize over. It should implement methods of the\n :class:`rllab.core.paramerized.Parameterized` class.\n :param leq_constraint: A constraint provided as a tuple (f, epsilon), of the form f(*inputs) <= epsilon.\n :param inputs: A list of symbolic variables as inputs, which could be subsampled if needed. It is assumed\n that the first dimension of these inputs should correspond to the number of data points\n :param extra_inputs: A list of symbolic variables as extra inputs which should not be subsampled\n :return: No return value.\n \"\"\"\n\n inputs = tuple(inputs)\n if extra_inputs is None:\n extra_inputs = tuple()\n else:\n extra_inputs = tuple(extra_inputs)\n\n constraint_term, constraint_value = leq_constraint\n\n params = target.get_params(trainable=True)\n grads = theano.grad(loss, wrt=params, disconnected_inputs='warn')\n flat_grad = ext.flatten_tensor_variables(grads)\n\n self._hvp_approach.update_opt(f=constraint_term, target=target, inputs=inputs + extra_inputs,\n reg_coeff=self._reg_coeff)\n\n self._target = target\n self._max_constraint_val = constraint_value\n self._constraint_name = constraint_name\n\n self._opt_fun = ext.lazydict(\n f_loss=lambda: ext.compile_function(\n inputs=inputs + extra_inputs,\n outputs=loss,\n log_name=\"f_loss\",\n ),\n f_grad=lambda: ext.compile_function(\n inputs=inputs + extra_inputs,\n outputs=flat_grad,\n log_name=\"f_grad\",\n ),\n f_constraint=lambda: ext.compile_function(\n inputs=inputs + extra_inputs,\n outputs=constraint_term,\n log_name=\"constraint\",\n ),\n f_loss_constraint=lambda: ext.compile_function(\n inputs=inputs + extra_inputs,\n outputs=[loss, constraint_term],\n log_name=\"f_loss_constraint\",\n ),\n )\n\n def loss(self, inputs, extra_inputs=None):\n inputs = tuple(inputs)\n if extra_inputs is None:\n extra_inputs = tuple()\n return sliced_fun(self._opt_fun[\"f_loss\"], self._num_slices)(inputs, extra_inputs)\n\n def constraint_val(self, inputs, extra_inputs=None):\n inputs = tuple(inputs)\n if extra_inputs is None:\n extra_inputs = tuple()\n return sliced_fun(self._opt_fun[\"f_constraint\"], self._num_slices)(inputs, extra_inputs)\n\n def optimize(self, inputs, extra_inputs=None, subsample_grouped_inputs=None):\n\n inputs = tuple(inputs)\n if extra_inputs is None:\n extra_inputs = tuple()\n\n if self._subsample_factor < 1:\n if subsample_grouped_inputs is None:\n subsample_grouped_inputs = [inputs]\n subsample_inputs = tuple()\n for inputs_grouped in subsample_grouped_inputs:\n n_samples = len(inputs_grouped[0])\n inds = np.random.choice(\n n_samples, int(n_samples * self._subsample_factor), replace=False)\n subsample_inputs += tuple([x[inds] for x in inputs_grouped])\n else:\n subsample_inputs = inputs\n\n logger.log(\"computing loss before\")\n loss_before = sliced_fun(self._opt_fun[\"f_loss\"], self._num_slices)(\n inputs, extra_inputs)\n logger.log(\"performing update\")\n logger.log(\"computing descent direction\")\n\n flat_g = sliced_fun(self._opt_fun[\"f_grad\"], self._num_slices)(\n inputs, extra_inputs)\n\n Hx = self._hvp_approach.build_eval(subsample_inputs + extra_inputs)\n\n descent_direction = krylov.cg(Hx, flat_g, cg_iters=self._cg_iters)\n\n initial_step_size = np.sqrt(\n 2.0 * self._max_constraint_val *\n (1. / (descent_direction.dot(Hx(descent_direction)) + 1e-8))\n )\n if np.isnan(initial_step_size):\n initial_step_size = 1.\n flat_descent_step = initial_step_size * descent_direction\n\n logger.log(\"descent direction computed\")\n\n prev_param = np.copy(self._target.get_param_values(trainable=True))\n n_iter = 0\n for n_iter, ratio in enumerate(self._backtrack_ratio ** np.arange(self._max_backtracks)):\n cur_step = ratio * flat_descent_step\n cur_param = prev_param - cur_step\n self._target.set_param_values(cur_param, trainable=True)\n loss, constraint_val = sliced_fun(\n self._opt_fun[\"f_loss_constraint\"], self._num_slices)(inputs, extra_inputs)\n if loss < loss_before and constraint_val <= self._max_constraint_val:\n break\n if (np.isnan(loss) or np.isnan(constraint_val) or loss >= loss_before or constraint_val >=\n self._max_constraint_val) and not self._accept_violation:\n logger.log(\"Line search condition violated. Rejecting the step!\")\n if np.isnan(loss):\n logger.log(\"Violated because loss is NaN\")\n if np.isnan(constraint_val):\n logger.log(\"Violated because constraint %s is NaN\" %\n self._constraint_name)\n if loss >= loss_before:\n logger.log(\"Violated because loss not improving\")\n if constraint_val >= self._max_constraint_val:\n logger.log(\n \"Violated because constraint %s is violated\" % self._constraint_name)\n self._target.set_param_values(prev_param, trainable=True)\n logger.log(\"backtrack iters: %d\" % n_iter)\n logger.log(\"computing loss after\")\n logger.log(\"optimization finished\")\n" ]
[ [ "numpy.isnan", "numpy.arange", "numpy.linalg.norm", "numpy.reshape" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
cjm-sfw/multi-parsing
[ "439e8624c0183fdb7d70973fa91911b8f2087834" ]
[ "mmdet/datasets/densepose.py" ]
[ "import numpy as np\nfrom pycocotools.coco import COCO\n\nfrom .custom import CustomDataset\nfrom .registry import DATASETS\n\n\[email protected]_module\nclass DensePose(CustomDataset):\n\n CLASSES = ('person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus',\n 'train', 'truck', 'boat', 'traffic_light', 'fire_hydrant',\n 'stop_sign', 'parking_meter', 'bench', 'bird', 'cat', 'dog',\n 'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe',\n 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee',\n 'skis', 'snowboard', 'sports_ball', 'kite', 'baseball_bat',\n 'baseball_glove', 'skateboard', 'surfboard', 'tennis_racket',\n 'bottle', 'wine_glass', 'cup', 'fork', 'knife', 'spoon', 'bowl',\n 'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot',\n 'hot_dog', 'pizza', 'donut', 'cake', 'chair', 'couch',\n 'potted_plant', 'bed', 'dining_table', 'toilet', 'tv', 'laptop',\n 'mouse', 'remote', 'keyboard', 'cell_phone', 'microwave',\n 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock',\n 'vase', 'scissors', 'teddy_bear', 'hair_drier', 'toothbrush')\n \n PARSING_CLASSES = ('Torso', 'Right Hand', 'Left Hand', 'Left Foot', 'Right Foot', \n 'Upper Leg Right', 'Upper Leg Left', 'Lower Leg Right', 'Lower Leg Left', \n 'Upper Arm Left', 'Upper Arm Right', 'Lower Arm Left', 'Lower Arm Right', 'Head')\n\n def load_annotations(self, ann_file):\n self.coco = COCO(ann_file)\n self.cat_ids = self.coco.getCatIds('person')\n self.cat2label = {\n cat_id: i + 1\n for i, cat_id in enumerate(self.cat_ids)\n }\n self.img_ids = self.coco.getImgIds(catIds=self.cat_ids)\n \n img_infos = []\n \n for i in self.img_ids:\n info = self.coco.loadImgs([i])[0]\n info['filename'] = info['file_name'].replace('COCO_train2014_', '')\n img_infos.append(info)\n return img_infos\n\n def get_ann_info(self, idx):\n img_id = self.img_infos[idx]['id']\n ann_ids = self.coco.getAnnIds(imgIds=[img_id])\n ann_info = self.coco.loadAnns(ann_ids)\n return self._parse_ann_info(self.img_infos[idx], ann_info)\n\n def _filter_imgs(self, min_size=32):\n \"\"\"Filter images too small or without ground truths.\"\"\"\n valid_inds = []\n ids_with_ann = set(_['image_id'] for _ in self.coco.anns.values())\n for i, img_info in enumerate(self.img_infos):\n if self.filter_empty_gt and self.img_ids[i] not in ids_with_ann:\n continue\n if min(img_info['width'], img_info['height']) >= min_size:\n valid_inds.append(i)\n return valid_inds\n \n\n def _parse_ann_info(self, img_info, ann_info):\n \"\"\"Parse bbox and mask annotation.\n\n Args:\n ann_info (list[dict]): Annotation info of an image.\n with_mask (bool): Whether to parse mask annotations.\n\n Returns:\n dict: A dict containing the following keys: bboxes, bboxes_ignore,\n labels, masks, seg_map. \"masks\" are raw annotations and not\n decoded into binary masks.\n \"\"\"\n \n gt_bboxes = []\n gt_labels = []\n gt_bboxes_ignore = []\n gt_masks_ann = []\n gt_parsing = []\n\n for i, ann in enumerate(ann_info):\n if ann.get('ignore', False):\n continue\n x1, y1, w, h = ann['bbox']\n if ann['area'] <= 0 or w < 1 or h < 1:\n continue\n bbox = [x1, y1, x1 + w - 1, y1 + h - 1]\n if ann.get('iscrowd', False):\n gt_bboxes_ignore.append(bbox)\n else:\n gt_bboxes.append(bbox)\n gt_labels.append(self.cat2label[ann['category_id']])\n gt_masks_ann.append(ann['segmentation'])\n if ann.get('dp_masks'):\n gt_parsing.append(ann['dp_masks'])\n else:\n gt_parsing.append([])\n\n if gt_bboxes:\n gt_bboxes = np.array(gt_bboxes, dtype=np.float32)\n gt_labels = np.array(gt_labels, dtype=np.int64)\n else:\n gt_bboxes = np.zeros((0, 4), dtype=np.float32)\n gt_labels = np.array([], dtype=np.int64)\n\n if gt_bboxes_ignore:\n gt_bboxes_ignore = np.array(gt_bboxes_ignore, dtype=np.float32)\n else:\n gt_bboxes_ignore = np.zeros((0, 4), dtype=np.float32)\n\n seg_map = img_info['filename'].replace('jpg', 'png')\n \n ann = dict(\n bboxes=gt_bboxes,\n labels=gt_labels,\n bboxes_ignore=gt_bboxes_ignore,\n masks=gt_masks_ann,\n parsing = gt_parsing,\n seg_map=seg_map)\n\n return ann\n" ]
[ [ "numpy.array", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
gh-determined-ai/determined
[ "9a1ab33a3a356b69681b3351629fef4ab98ddb56", "9a1ab33a3a356b69681b3351629fef4ab98ddb56" ]
[ "model_hub/examples/huggingface/text-classification/glue_trial.py", "harness/tests/experiment/utils.py" ]
[ "\"\"\"\nThis example is largely based on the GLUE text-classification example in the huggingface\ntransformers library. The license for the transformer's library is reproduced below.\n\n==================================================================================================\n\nCopyright 2020 The HuggingFace Team. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nimport functools\nimport logging\nfrom typing import Dict, Union\n\nimport attrdict\nimport datasets\nimport numpy as np\nimport transformers\n\nimport determined.pytorch as det_torch\nimport model_hub.huggingface as hf\nimport model_hub.utils as utils\n\ntask_to_keys = {\n \"cola\": (\"sentence\", None),\n \"mnli\": (\"premise\", \"hypothesis\"),\n \"mrpc\": (\"sentence1\", \"sentence2\"),\n \"qnli\": (\"question\", \"sentence\"),\n \"qqp\": (\"question1\", \"question2\"),\n \"rte\": (\"sentence1\", \"sentence2\"),\n \"sst2\": (\"sentence\", None),\n \"stsb\": (\"sentence1\", \"sentence2\"),\n \"wnli\": (\"sentence1\", \"sentence2\"),\n}\n\n\nclass GLUETrial(hf.BaseTransformerTrial):\n def __init__(self, context: det_torch.PyTorchTrialContext) -> None:\n self.logger = logging.getLogger(__name__)\n self.hparams = attrdict.AttrDict(context.get_hparams())\n self.data_config = attrdict.AttrDict(context.get_data_config())\n self.context = context\n\n # Load dataset and get metadata.\n # This needs to be done before we initialize the HF config, tokenizer, and model\n # because we need to know num_labels before doing so.\n\n # For CSV/JSON files, this example will use as labels the column called `label` and as pair\n # of sentences the sentences in columns called `sentence1` and `sentence2` if such column\n # exists or the first two columns not named label if at least two columns are provided.\n #\n # If the CSVs/JSONs contain only one non-label column, the example will do single sentence\n # classification on this single column.\n\n # See more about loading any type of standard or custom dataset at\n # https://huggingface.co/docs/datasets/loading_datasets.html.\n\n self.raw_datasets = hf.default_load_dataset(self.data_config)\n\n if self.hparams.finetuning_task is not None:\n is_regression = self.hparams.finetuning_task == \"stsb\"\n if not is_regression:\n label_list = self.raw_datasets[\"train\"].features[\"label\"].names\n num_labels = len(label_list)\n else:\n num_labels = 1\n else:\n # Trying to have good defaults here, don't hesitate to tweak to your needs.\n is_regression = self.raw_datasets[\"train\"].features[\"label\"].dtype in [\n \"float32\",\n \"float64\",\n ]\n if is_regression:\n num_labels = 1\n else:\n # A useful fast method is datasets.Dataset.unique from\n # https://huggingface.co/docs/datasets/package_reference/main_classes.html\n label_list = self.raw_datasets[\"train\"].unique(\"label\")\n label_list.sort() # Let's sort it for determinism\n num_labels = len(label_list)\n self.is_regression = is_regression\n self.hparams.num_labels = num_labels\n if not self.is_regression:\n self.label_list = label_list\n\n super(GLUETrial, self).__init__(context)\n self.logger.info(self.config)\n\n # We need to create the tokenized dataset after init because we need to model and\n # tokenizer to be available.\n self.tokenized_datasets = self.build_datasets()\n train_length = len(self.tokenized_datasets[\"train\"])\n self.logger.info(\"training records: {}\".format(train_length))\n if (\n \"records_per_epoch\" in self.exp_config\n and train_length != self.exp_config[\"records_per_epoch\"]\n ):\n self.logger.warning(\n \"number of train records {} does not match records_per_epoch of {}\".format(\n train_length, self.exp_config[\"records_per_epoch\"]\n )\n )\n\n # Create metric reducer\n metric = datasets.load_metric(\"glue\", self.hparams.finetuning_task)\n\n # You can define your custom compute_metrics function. It takes an `EvalPrediction` object\n # (a namedtuple with a predictions and label_ids field) and has to return a dictionary\n # mapping string to float.\n def compute_metrics(pred_labels) -> Dict:\n preds, labels = zip(*pred_labels)\n preds = utils.expand_like(preds)\n labels = utils.expand_like(labels)\n preds = np.squeeze(preds) if is_regression else np.argmax(preds, axis=1)\n if self.hparams.finetuning_task is not None:\n result = metric.compute(predictions=preds, references=labels)\n if len(result) > 1:\n result[\"combined_score\"] = np.mean(list(result.values())).item()\n return result\n elif is_regression:\n return {\"mse\": ((preds - labels) ** 2).mean().item()}\n else:\n return {\"accuracy\": (preds == labels).astype(np.float32).mean().item()}\n\n self.reducer = context.wrap_reducer(compute_metrics, for_training=False)\n\n def build_datasets(self) -> Union[datasets.Dataset, datasets.DatasetDict]:\n # Preprocessing the datasets\n if self.hparams.finetuning_task is not None:\n sentence1_key, sentence2_key = task_to_keys[self.hparams.finetuning_task]\n else:\n # We try to have some nice defaults but don't hesitate to tweak to your use case.\n non_label_column_names = [\n name for name in self.raw_datasets[\"train\"].column_names if name != \"label\"\n ]\n if \"sentence1\" in non_label_column_names and \"sentence2\" in non_label_column_names:\n sentence1_key, sentence2_key = \"sentence1\", \"sentence2\"\n else:\n if len(non_label_column_names) >= 2:\n sentence1_key, sentence2_key = non_label_column_names[:2]\n else:\n sentence1_key, sentence2_key = non_label_column_names[0], None\n\n # Padding strategy\n if self.data_config.pad_to_max_length:\n padding = \"max_length\"\n else:\n # We will pad later, dynamically at batch creation to the max_seq_length in each batch.\n padding = False\n\n # Some models have set the order of the labels to use, so let's make sure we do use it.\n label_to_id = None\n if (\n self.model.config.label2id\n != transformers.PretrainedConfig(num_labels=self.hparams.num_labels).label2id\n and self.hparams.finetuning_task is not None\n and not self.is_regression\n ):\n # Some have all caps in their config, some don't.\n label_name_to_id = {k.lower(): v for k, v in self.model.config.label2id.items()}\n if sorted(label_name_to_id.keys()) == sorted(self.label_list):\n label_to_id = {\n i: label_name_to_id[self.label_list[i]] for i in range(self.hparams.num_labels)\n }\n else:\n self.logger.warning(\n \"Your model seems to have been trained with labels, but they don't match the \"\n f\"dataset: model labels: {sorted(label_name_to_id.keys())}, \"\n f\"dataset labels: {sorted(self.label_list)}.\"\n \"\\nIgnoring the model labels as a result.\",\n )\n elif self.hparams.finetuning_task is None and not self.is_regression:\n label_to_id = {v: i for i, v in enumerate(self.label_list)}\n\n if self.data_config.max_seq_length > self.tokenizer.model_max_length:\n self.logger.warning(\n f\"The max_seq_length passed ({self.data_config.max_seq_length}) is larger than \"\n f\"the maximum length for the model ({self.tokenizer.model_max_length}). Using \"\n f\"max_seq_length={self.tokenizer.model_max_length}.\"\n )\n max_seq_length = min(self.data_config.max_seq_length, self.tokenizer.model_max_length)\n\n # We cannot use self.tokenizer as a non-local variable in the preprocess_function if we\n # want map to be able to cache the output of the tokenizer. Hence, the preprocess_function\n # takes a tokenizer explicitly as an input and we create a closure using functools.partial.\n def preprocess_function(tokenizer, padding, max_seq_length, examples):\n # Tokenize the texts\n args = (\n (examples[sentence1_key],)\n if sentence2_key is None\n else (examples[sentence1_key], examples[sentence2_key])\n )\n result = tokenizer(*args, padding=padding, max_length=max_seq_length, truncation=True)\n\n # Map labels to IDs (not necessary for GLUE tasks)\n if label_to_id is not None and \"label\" in examples:\n result[\"label\"] = [label_to_id[label] for label in examples[\"label\"]]\n return result\n\n tokenized_datasets = self.raw_datasets.map(\n functools.partial(preprocess_function, self.tokenizer, padding, max_seq_length),\n batched=True,\n load_from_cache_file=not self.data_config.overwrite_cache,\n )\n for _, data in tokenized_datasets.items():\n hf.remove_unused_columns(self.model, data)\n\n # Data collator will default to DataCollatorWithPadding, so we change it if we already\n # did the padding.\n if self.data_config.pad_to_max_length:\n self.collator = transformers.default_data_collator\n elif self.hparams.use_apex_amp:\n collator = transformers.DataCollatorWithPadding(self.tokenizer, pad_to_multiple_of=8)\n self.collator = lambda x: collator(x).data\n else:\n self.collator = None\n return tokenized_datasets\n\n def build_training_data_loader(self) -> det_torch.DataLoader:\n return det_torch.DataLoader(\n self.tokenized_datasets[\"train\"],\n batch_size=self.context.get_per_slot_batch_size(),\n collate_fn=self.collator,\n )\n\n def build_validation_data_loader(self) -> det_torch.DataLoader:\n eval_dataset = self.tokenized_datasets[\n \"validation_matched\" if self.hparams.finetuning_task == \"mnli\" else \"validation\"\n ]\n return det_torch.DataLoader(\n eval_dataset,\n batch_size=self.context.get_per_slot_batch_size(),\n collate_fn=self.collator,\n )\n\n def evaluate_batch(self, batch: det_torch.TorchData, batch_idx: int) -> Dict:\n outputs = self.model(**batch)\n tmp_eval_loss, logits = outputs[:2]\n preds = logits.detach().cpu().numpy()\n out_label_ids = batch[\"labels\"].detach().cpu().numpy()\n self.reducer.update((preds, out_label_ids))\n # We will return just the metrics outputed by the reducer.\n return {}\n", "import os\nimport pathlib\nfrom typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Type\n\nimport numpy as np\nimport pytest\nfrom mypy_extensions import DefaultNamedArg\nfrom tensorflow.keras import utils as keras_utils\n\nimport determined as det\nfrom determined import core, gpu, keras, workload\n\n\nclass TrainAndValidate:\n \"\"\"\n Offer a similar interface as WorkloadResponseInterceptor, execpt let send() yield a whole\n progression of RUN_STEP and COMPUTE_VALIDATION_METRICS, and let result() return the accumulated\n metrics from each.\n \"\"\"\n\n def __init__(self, request_stop_step_id: Optional[int] = None) -> None:\n self._training_metrics = None # type: Optional[List[Dict[str, Any]]]\n self._avg_training_metrics = None # type: Optional[List[Dict[str, Any]]]\n self._validation_metrics = None # type: Optional[List[Dict[str, Any]]]\n self.request_stop_step_id = request_stop_step_id\n self._steps_completed = 0\n\n def send(\n self,\n steps: int,\n validation_freq: int,\n initial_step_id: int = 1,\n scheduling_unit: int = 1,\n train_batch_calls: int = 1,\n ) -> workload.Stream:\n self._training_metrics = []\n self._avg_training_metrics = []\n self._validation_metrics = []\n self._steps_completed = 0\n interceptor = workload.WorkloadResponseInterceptor()\n\n for step_id in range(initial_step_id, initial_step_id + steps):\n stop_requested = False\n yield from interceptor.send(\n workload.train_workload(\n step_id,\n num_batches=scheduling_unit,\n total_batches_processed=self._steps_completed,\n ),\n )\n metrics = interceptor.metrics_result()\n batch_metrics = metrics[\"metrics\"][\"batch_metrics\"]\n assert len(batch_metrics) == scheduling_unit * train_batch_calls\n self._training_metrics.extend(batch_metrics)\n self._avg_training_metrics.append(metrics[\"metrics\"][\"avg_metrics\"])\n self._steps_completed += scheduling_unit\n if metrics.get(\"stop_requested\"):\n assert step_id == self.request_stop_step_id, (step_id, self)\n stop_requested = True\n\n if step_id % validation_freq == 0:\n yield from interceptor.send(\n workload.validation_workload(\n step_id, total_batches_processed=self._steps_completed\n ),\n )\n validation = interceptor.metrics_result()\n v_metrics = validation[\"metrics\"][\"validation_metrics\"]\n self._validation_metrics.append(v_metrics)\n if validation.get(\"stop_requested\"):\n assert step_id == self.request_stop_step_id\n stop_requested = True\n\n if stop_requested:\n break\n else:\n assert step_id != self.request_stop_step_id\n\n def result(self) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:\n assert self._training_metrics is not None\n assert self._validation_metrics is not None\n return self._training_metrics, self._validation_metrics\n\n def get_steps_completed(self) -> int:\n return self._steps_completed\n\n def get_avg_training_metrics(self) -> List[Dict[str, Any]]:\n assert self._avg_training_metrics is not None\n return self._avg_training_metrics\n\n\ndef make_default_exp_config(\n hparams: Dict[str, Any],\n scheduling_unit: int,\n searcher_metric: str,\n checkpoint_dir: Optional[str] = None,\n) -> Dict:\n return {\n \"scheduling_unit\": scheduling_unit,\n \"resources\": {\"native_parallel\": False, \"slots_per_trial\": 1},\n \"hyperparameters\": hparams,\n \"optimizations\": {\n \"mixed_precision\": \"O0\",\n \"aggregation_frequency\": 1,\n \"gradient_compression\": False,\n \"average_training_metrics\": False,\n \"auto_tune_tensor_fusion\": False,\n \"tensor_fusion_threshold\": 100,\n \"tensor_fusion_cycle_time\": 3.5,\n },\n \"data_layer\": {\"type\": \"shared_fs\"},\n \"checkpoint_storage\": {\n \"type\": \"shared_fs\",\n \"host_path\": checkpoint_dir or \"/tmp\",\n },\n \"searcher\": {\n \"metric\": searcher_metric,\n },\n }\n\n\ndef make_default_env_context(\n hparams: Dict[str, Any],\n experiment_config: Dict,\n trial_seed: int = 0,\n latest_checkpoint: Optional[str] = None,\n steps_completed: int = 0,\n expose_gpus: bool = False,\n) -> det.EnvContext:\n assert (latest_checkpoint is None) == (steps_completed == 0)\n\n if expose_gpus:\n gpu_uuids = gpu.get_gpu_uuids()\n use_gpu = bool(gpu_uuids)\n else:\n gpu_uuids = []\n use_gpu = False\n\n return det.EnvContext(\n experiment_config=experiment_config,\n master_url=\"\",\n master_cert_file=None,\n master_cert_name=None,\n hparams=hparams,\n latest_checkpoint=latest_checkpoint,\n steps_completed=steps_completed,\n use_gpu=use_gpu,\n container_gpus=gpu_uuids,\n slot_ids=[],\n debug=False,\n det_trial_unique_port_offset=0,\n det_trial_id=\"1\",\n det_experiment_id=\"1\",\n det_agent_id=\"1\",\n det_cluster_id=\"uuid-123\",\n trial_seed=trial_seed,\n trial_run_id=1,\n allocation_id=\"\",\n managed_training=True,\n test_mode=False,\n on_cluster=False,\n )\n\n\ndef fixtures_path(path: str) -> str:\n return os.path.join(os.path.dirname(__file__), \"fixtures\", path)\n\n\ndef repo_path(path: str) -> str:\n return os.path.join(os.path.dirname(__file__), \"../../../\", path)\n\n\ndef assert_equivalent_metrics(metrics_A: Dict[str, Any], metrics_B: Dict[str, Any]) -> None:\n \"\"\"\n Helper function to verify that two dictionaries of metrics are equivalent\n to each other.\n \"\"\"\n assert set(metrics_A.keys()) == set(metrics_B.keys())\n for key in metrics_A.keys():\n if isinstance(metrics_A[key], (float, np.float)):\n assert metrics_A[key] == pytest.approx(metrics_B[key])\n elif isinstance(metrics_A[key], np.ndarray):\n assert np.array_equal(metrics_A[key], metrics_B[key])\n else:\n assert metrics_A[key] == metrics_B[key]\n\n\ndef xor_data(dtype: np.dtype = np.int64) -> Tuple[np.ndarray, np.ndarray]:\n training_data = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=dtype)\n training_labels = np.array([0, 1, 1, 0], dtype=dtype)\n return training_data, training_labels\n\n\ndef make_xor_data_sequences(\n shuffle: bool = False,\n seed: Optional[int] = None,\n dtype: np.dtype = np.int64,\n multi_input_output: bool = False,\n batch_size: int = 1,\n) -> Tuple[keras_utils.Sequence, keras_utils.Sequence]:\n \"\"\"\n Generates data loaders for the toy XOR problem. The dataset only has four\n possible inputs. For the purposes of testing, the validation set is the\n same as the training dataset.\n \"\"\"\n training_data, training_labels = xor_data(dtype)\n\n if shuffle:\n if seed is not None:\n np.random.seed(seed)\n idxs = np.random.permutation(4)\n training_data = training_data[idxs]\n training_labels = training_labels[idxs]\n\n return (\n keras._ArrayLikeAdapter(training_data, training_labels, batch_size=batch_size),\n keras._ArrayLikeAdapter(training_data, training_labels, batch_size=batch_size),\n )\n\n\ndef make_trial_controller_from_trial_implementation(\n trial_class: Type[det.Trial],\n hparams: Dict,\n workloads: workload.Stream,\n scheduling_unit: int = 1,\n trial_seed: int = 0,\n exp_config: Optional[Dict] = None,\n checkpoint_dir: Optional[str] = None,\n latest_checkpoint: Optional[str] = None,\n steps_completed: int = 0,\n expose_gpus: bool = False,\n) -> det.TrialController:\n if not exp_config:\n assert hasattr(\n trial_class, \"_searcher_metric\"\n ), \"Trial classes for unit tests should be annotated with a _searcher_metric attribute\"\n searcher_metric = trial_class._searcher_metric # type: ignore\n exp_config = make_default_exp_config(\n hparams, scheduling_unit, searcher_metric, checkpoint_dir=checkpoint_dir\n )\n env = make_default_env_context(\n hparams=hparams,\n experiment_config=exp_config,\n trial_seed=trial_seed,\n latest_checkpoint=latest_checkpoint,\n steps_completed=steps_completed,\n expose_gpus=expose_gpus,\n )\n\n storage_manager = det.common.storage.SharedFSStorageManager(checkpoint_dir or \"/tmp\")\n core_context = core._dummy_init(storage_manager=storage_manager)\n\n distributed_backend = det._DistributedBackend()\n\n controller_class = trial_class.trial_controller_class\n assert controller_class is not None\n controller_class.pre_execute_hook(env, distributed_backend)\n\n trial_context = trial_class.trial_context_class(core_context, env)\n trial_inst = trial_class(trial_context)\n\n return controller_class.from_trial(\n trial_inst=trial_inst,\n context=trial_context,\n env=env,\n workloads=workloads,\n )\n\n\ndef reproducibility_test(\n controller_fn: Callable[[workload.Stream], det.TrialController],\n steps: int,\n validation_freq: int,\n seed: int = 123,\n scheduling_unit: int = 1,\n) -> Tuple[\n Tuple[Sequence[Dict[str, Any]], Sequence[Dict[str, Any]]],\n Tuple[Sequence[Dict[str, Any]], Sequence[Dict[str, Any]]],\n]:\n training_metrics = {}\n validation_metrics = {}\n\n def make_workloads(tag: str) -> workload.Stream:\n nonlocal training_metrics\n nonlocal validation_metrics\n\n trainer = TrainAndValidate()\n\n yield from trainer.send(steps, validation_freq, scheduling_unit=scheduling_unit)\n tm, vm = trainer.result()\n\n training_metrics[tag] = tm\n validation_metrics[tag] = vm\n\n # Trial A\n os.environ[\"DET_TRIAL_SEED\"] = str(seed)\n controller_A = controller_fn(make_workloads(\"A\"))\n controller_A.run()\n\n # Trial B\n assert os.environ[\"DET_TRIAL_SEED\"] == str(seed)\n controller_B = controller_fn(make_workloads(\"B\"))\n controller_B.run()\n\n assert len(training_metrics[\"A\"]) == len(training_metrics[\"B\"])\n for A, B in zip(training_metrics[\"A\"], training_metrics[\"B\"]):\n assert_equivalent_metrics(A, B)\n\n assert len(validation_metrics[\"A\"]) == len(validation_metrics[\"B\"])\n for A, B in zip(validation_metrics[\"A\"], validation_metrics[\"B\"]):\n assert_equivalent_metrics(A, B)\n\n return (\n (training_metrics[\"A\"], validation_metrics[\"A\"]),\n (training_metrics[\"B\"], validation_metrics[\"B\"]),\n )\n\n\nRestorableMakeControllerFn = Callable[\n [\n workload.Stream,\n DefaultNamedArg(Optional[str], \"checkpoint_dir\"), # noqa: F821\n DefaultNamedArg(Optional[str], \"latest_checkpoint\"), # noqa: F821\n DefaultNamedArg(int, \"steps_completed\"), # noqa: F821\n ],\n det.TrialController,\n]\n\n\ndef train_and_validate(\n make_trial_controller_fn: Callable[[workload.Stream], det.TrialController],\n steps: int = 2,\n) -> Tuple[Sequence[Dict[str, Any]], Sequence[Dict[str, Any]]]:\n metrics: Dict[str, Any] = {\"training\": [], \"validation\": []}\n\n def make_workloads(steps: int) -> workload.Stream:\n trainer = TrainAndValidate()\n\n yield from trainer.send(steps, validation_freq=1, scheduling_unit=10)\n tm, vm = trainer.result()\n metrics[\"training\"] += tm\n metrics[\"validation\"] += vm\n\n controller = make_trial_controller_fn(make_workloads(steps))\n controller.run()\n\n return (metrics[\"training\"], metrics[\"validation\"])\n\n\ndef checkpointing_and_restoring_test(\n make_trial_controller_fn: RestorableMakeControllerFn, tmp_path: pathlib.Path\n) -> Tuple[Sequence[Dict[str, Any]], Sequence[Dict[str, Any]]]:\n \"\"\"\n Tests if a trial controller of any framework can checkpoint and restore from that checkpoint\n without state changes.\n\n This test runs two trials.\n 1) Trial A runs for one steps of 100 batches, checkpoints itself, and restores from\n that checkpoint.\n 2) Trial B runs for two steps of 100 batches.\n\n This test compares the training and validation metrics history of the two trials.\n \"\"\"\n\n training_metrics = {\"A\": [], \"B\": []} # type: Dict[str, List[workload.Metrics]]\n validation_metrics = {\"A\": [], \"B\": []} # type: Dict[str, List[workload.Metrics]]\n checkpoint_dir = str(tmp_path.joinpath(\"checkpoint\"))\n latest_checkpoint = None\n steps_completed = 0\n\n def make_workloads(steps: int, tag: str, checkpoint: bool) -> workload.Stream:\n trainer = TrainAndValidate()\n\n yield from trainer.send(steps, validation_freq=1, scheduling_unit=100)\n tm, vm = trainer.result()\n training_metrics[tag] += tm\n validation_metrics[tag] += vm\n\n if checkpoint is not None:\n interceptor = workload.WorkloadResponseInterceptor()\n yield from interceptor.send(workload.checkpoint_workload())\n nonlocal latest_checkpoint, steps_completed\n latest_checkpoint = interceptor.metrics_result()[\"uuid\"]\n steps_completed = trainer.get_steps_completed()\n\n controller_A1 = make_trial_controller_fn(\n make_workloads(1, \"A\", True),\n checkpoint_dir=checkpoint_dir,\n )\n controller_A1.run()\n assert latest_checkpoint is not None, \"make_workloads did not set the latest_checkpoint\"\n\n controller_A2 = make_trial_controller_fn(\n make_workloads(1, \"A\", False),\n checkpoint_dir=checkpoint_dir,\n latest_checkpoint=latest_checkpoint,\n steps_completed=steps_completed,\n )\n controller_A2.run()\n\n controller_B = make_trial_controller_fn(make_workloads(2, \"B\", False))\n controller_B.run()\n\n for A, B in zip(training_metrics[\"A\"], training_metrics[\"B\"]):\n assert_equivalent_metrics(A, B)\n\n for A, B in zip(validation_metrics[\"A\"], validation_metrics[\"B\"]):\n assert_equivalent_metrics(A, B)\n\n return (training_metrics[\"A\"], training_metrics[\"B\"])\n\n\ndef list_all_files(directory: str) -> List[str]:\n return [f for _, _, files in os.walk(directory) for f in files]\n\n\ndef ensure_requires_global_batch_size(\n trial_class: Type[det.Trial],\n hparams: Dict[str, Any],\n) -> None:\n bad_hparams = dict(hparams)\n del bad_hparams[\"global_batch_size\"]\n\n def make_workloads() -> workload.Stream:\n trainer = TrainAndValidate()\n yield from trainer.send(steps=1, validation_freq=1)\n\n # Catch missing global_batch_size.\n with pytest.raises(det.errors.InvalidExperimentException, match=\"is a required hyperparameter\"):\n _ = make_trial_controller_from_trial_implementation(\n trial_class,\n bad_hparams,\n make_workloads(),\n )\n" ]
[ [ "numpy.squeeze", "numpy.argmax" ], [ "numpy.random.permutation", "numpy.array_equal", "numpy.array", "numpy.random.seed" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
wuyifan2233/Tencent_WWF
[ "2b248a810295f95cb0483837cb8cb8797c144821", "2b248a810295f95cb0483837cb8cb8797c144821", "2b248a810295f95cb0483837cb8cb8797c144821", "2b248a810295f95cb0483837cb8cb8797c144821" ]
[ "Final_data_building/video_based_split/split_vid_top14_p123.py", "Ori_data_cleaning/mapping.py", "Final_data_building/video_based_split/select_rest_vid.py", "Final_data_building/video_based_split/modality/imageio-top14-sup.py" ]
[ "# -*- coding: UTF-8 -*-\nfrom math import e, inf\nimport os\nfrom numpy.lib.type_check import _imag_dispatcher\nimport pandas as pd\nimport shutil\nimport numpy as np\nimport cv2\nimport random\nfrom tqdm import tqdm\nimport pyfastcopy\nimport json,sklearn\nfrom sklearn.model_selection import train_test_split\n\n\n\ndef main():\n #test\n data_stat_path='D:\\WWF_Det\\WWF_Det\\Raw_data_stat/top14-p1-p2-p3-merged/top14-p123-combine.csv'\n critiria_path='D:/WWF_Det/WWF_Det/Raw_data_stat/top14-all/split_critiria.csv'\n save_base='D:/WWF_Det/WWF_Det/Final_data_stat/top14-p123/'\n if not os.path.exists(save_base): os.makedirs(save_base)\n save_path=save_base+'video_split.csv'\n df=pd.read_csv(data_stat_path)\n df['label']=None\n id_list=df.index.values.tolist()\n df_cri=pd.read_csv(critiria_path)\n cate_list=np.unique(df['cate'].values)\n np.random.seed(2021)\n \n for cate in cate_list:\n \n infra_index=df.loc[(df['cate'] == cate)&(df['modality'] == 'Infra')].sample(frac=1).index.values.tolist()\n rgb_index=df.loc[(df['cate'] == cate)&(df['modality'] == 'RGB')].sample(frac=1).index.values.tolist()\n infra_test_num=int(df_cri.loc[df_cri['cate']==cate]['infra_test'])\n rgb_test_num=int(df_cri.loc[df_cri['cate']==cate]['rgb_test'])\n infra_test_index=infra_index[:infra_test_num]\n rgb_test_index=rgb_index[:rgb_test_num]\n\n test_index_all=list(infra_test_index+rgb_test_index)\n \n train_index_all=[i for i in infra_index+rgb_index if i not in test_index_all]\n #print(len(test_index_all))\n for ID in test_index_all:\n \n df.loc[ID,'label']='test'\n ori_dir=df.loc[ID,'video_path']\n cate=df.loc[ID,'cate']\n target_base=os.path.join('D:/WWF_Det/WWF_Data/Final_Data/valset-vid-v1/',cate)\n target_dir=os.path.join(target_base,ori_dir.split('/')[-1])\n if not os.path.exists(target_base): os.makedirs(target_base)\n shutil.copyfile(ori_dir,target_dir)\n for ID in train_index_all:\n df.loc[ID,'label']='train'\n #print(df)\n \n #break\n # df.to_csv(save_path,index=False)\n\nif __name__ == \"__main__\":\n \n main()", "# -*- coding: UTF-8 -*-\nimport os\nimport pandas as pd\nimport shutil\nimport numpy as np\nfrom tqdm import tqdm\nimport pyfastcopy\n\ndef stat_count(dir):\n csv_list=os.listdir(dir)\n df_store=pd.DataFrame(columns=['Categories','Path','Frames'])\n modify_class=['misssing','wufashibei','gongzuorengyuan','qitarenyuan','konpai','gongzuorenyuan']\n modified_class=['missing','wufashibie','person','person','kongpai','person']\n drop_class=['cuowu','wufashibie','kongpai','missing']\n for csv in csv_list:\n df=pd.read_csv(dir+csv)\n for a,b in zip(modify_class,modified_class):\n df.loc[df['Categories']==a,'Categories']=b\n \n cat_list=df['Categories'].values\n \n for i,cate in enumerate(cat_list):\n if cate not in df_store['Categories'].values and cate not in drop_class:\n df_store=df_store.append([{'Categories':cate}], ignore_index=True)\n index = df_store[df_store.Categories == cate].index.tolist()[0]\n\n df_store.loc[index,'Path']=[df.loc[i,'Path']]\n df_store.loc[index,'Frames']=df.loc[i,'Frames']\n \n elif cate in df_store['Categories'].values and cate not in drop_class:\n index = df_store[df_store.Categories == cate].index.tolist()[0]\n #['[path]', '[path2]','[path3]']\n\n df_store.loc[index,'Path']+=[df.loc[i,'Path']]\n df_store.loc[index,'Frames']+=df.loc[i,'Frames']\n \n \n df_store=df_store.sort_values(by=\"Frames\" , ascending=False)\n df_store=df_store.reset_index().drop(['index'], axis=1)\n \n return df_store\n\n\n\ndef main():\n df_store=pd.DataFrame(columns=['Categories','Source_Path','Desti_Path'])\n\n new_df=stat_count('E:\\All_CSV\\csv/')[14:30]\n count_all=0\n for cate,file_list in tqdm(zip(new_df['Categories'].values,new_df['Path'].values)):\n image_folder='D:/mid15-dataset/'+cate+'/images/'\n video_folder='D:/mid15-dataset/'+cate+'/videos/'\n count_image=0\n count_video=0\n if not os.path.exists(image_folder):\n os.makedirs(image_folder)\n if not os.path.exists(video_folder):\n os.makedirs(video_folder)\n for mini_list in tqdm(file_list):\n source_list=mini_list[1:-1].split(',')\n for s_item in source_list:\n source=s_item.strip()[1:-1]\n \n if source.lower().strip().endswith('.jpg') or source.lower().strip().endswith('.png') :\n count_image+=1\n target=image_folder+'%05d' % (count_image) +os.path.splitext(source)[1]\n elif source.lower().strip().endswith('.mov') or source.lower().strip().endswith('.avi') or source.lower().strip().endswith('.mp4'):\n count_video+=1\n target=video_folder+'%05d' % (count_video) +os.path.splitext(source)[1]\n df_store.loc[count_all]=[cate,source,target]\n count_all+=1\n #shutil.copyfile(source,target)\n #print(target)\n df_store.to_csv('mid15-mapping.csv',index=False,encoding=\"utf_8_sig\")\n return df_store\nif __name__ == \"__main__\":\n print(main())", "# -*- coding: UTF-8 -*-\nfrom math import e\nimport os\n\nfrom numpy.lib.type_check import _imag_dispatcher\nimport pandas as pd\nimport shutil\nimport numpy as np\nimport cv2\nimport random\nfrom tqdm import tqdm\nimport pyfastcopy\nimport json,sklearn\nfrom sklearn.model_selection import train_test_split\n\npos_data_base='D:/WWF_Det/WWF_Data/Pos_Data/'\nraw_data_base='D:/WWF_Det/WWF_Data/Raw_Data/'\n\nannotation_base='D:/WWF_Det/WWF_Det/Raw_annoations/'\n\nFinal_data_base='D:/WWF_Det/WWF_Data/Final_Data/rest-vid-clean/'\ntry:\n os.makedirs(Final_data_base)\nexcept:\n pass\n\ncombine_data_list=['rest-part1','rest-part2']\n\n\nfor dataset in combine_data_list:\n source_vid_path_all=[]\n target_vid_path_all=[]\n valuableset_dir=pos_data_base+dataset+'/allset/visualizations/'\n source_base=raw_data_base+dataset+'/'\n source_base=source_base.replace('part','p')\n annotation_dir=annotation_base+dataset+'.csv'\n df=pd.read_csv(annotation_dir)\n pic_id_list=[i.replace('.jpg','',1) for i in os.listdir(valuableset_dir)]\n for pic_id in tqdm(pic_id_list):\n\n pic_df=df.loc[df['题目ID']== int(pic_id)]\n timu_str=pic_df['题目数据'].values[0]\n timu_data=json.loads(timu_str)\n video_path_list=timu_data['video_path'].split('/')\n vid_path=video_path_list[-3]+'/'+video_path_list[-2]+'/'+video_path_list[-1]\n source_vid_path_all.append(vid_path)\n target_vid_path_all.append(video_path_list[-3]+'-'+video_path_list[-1])\n source_vid_path_all=np.unique(np.array(source_vid_path_all)).tolist()\n target_vid_path_all=np.unique(np.array(target_vid_path_all)).tolist()\n\n for source_vid,target_vid in zip(source_vid_path_all,target_vid_path_all):\n shutil.copyfile(source_base+source_vid,Final_data_base+target_vid) ", "# -*- coding: UTF-8 -*-\nimport os\nimport pandas as pd\nimport shutil\nimport numpy as np\nimport cv2\nfrom tqdm import tqdm\nimport pyfastcopy\nimport json\nimport imageio,skimage\nfrom xml.etree import ElementTree\nfrom PIL import Image, ImageDraw, ImageFont\n\ndef imageio_stat(video_path):\n vid = imageio.get_reader(video_path, 'ffmpeg')\n first=True\n for i in vid:\n im=i\n first=False\n if not first:\n break\n data = skimage.img_as_float(im)\n data = data / data.max() #normalizes data in range 0 - 255\n data = 255 * data\n frame = data.astype(np.uint8)\n b, g, r = cv2.split(frame)\n if np.mean(b-g)<5:\n modality=\"Infra\"\n else: modality=\"RGB\"\n return modality\ndef main():\n dataset_name='top14-all/'\n save_base='D:/WWF_Det/WWF_Det/Raw_data_stat/'+dataset_name\n df_path=save_base+'top14-all-modality.csv'\n df_pos=save_base+'top14-all-pos.csv'\n df=pd.read_csv(df_path)\n null_df=df[df.isnull().T.any()]\n for index, row in null_df.iterrows():\n video_path=row['video_path']\n try:\n modality=imageio_stat(video_path)\n except:\n print(video_path)\n continue\n else:\n df.loc[index,'modality']=modality\n\n print(df[df.isnull().T.any()])\n df.to_csv(df_pos,index=False)\nif __name__ == \"__main__\":\n main()" ]
[ [ "pandas.read_csv", "numpy.random.seed", "numpy.unique" ], [ "pandas.read_csv", "pandas.DataFrame" ], [ "numpy.array", "pandas.read_csv" ], [ "pandas.read_csv", "numpy.mean" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
trsvchn/captum
[ "38b57082d22854013c0a0b80a51c0b85269afdaf" ]
[ "tests/attr/neuron/test_neuron_deeplift.py" ]
[ "#!/usr/bin/env python3\n\nfrom __future__ import print_function\n\nfrom typing import Tuple, Union\n\nimport torch\nfrom captum._utils.typing import TensorOrTupleOfTensorsGeneric\nfrom captum.attr._core.neuron.neuron_deep_lift import NeuronDeepLift, NeuronDeepLiftShap\nfrom tests.attr.layer.test_layer_deeplift import (\n _create_inps_and_base_for_deeplift_neuron_layer_testing,\n _create_inps_and_base_for_deepliftshap_neuron_layer_testing,\n)\nfrom tests.helpers.basic import BaseTest, assertTensorAlmostEqual\nfrom tests.helpers.basic_models import (\n BasicModel_ConvNet,\n BasicModel_ConvNet_MaxPool3d,\n LinearMaxPoolLinearModel,\n ReLULinearModel,\n)\nfrom torch import Tensor\n\n\nclass Test(BaseTest):\n def test_relu_neuron_deeplift(self) -> None:\n model = ReLULinearModel(inplace=True)\n\n x1 = torch.tensor([[-10.0, 1.0, -5.0]], requires_grad=True)\n x2 = torch.tensor([[3.0, 3.0, 1.0]], requires_grad=True)\n\n inputs = (x1, x2)\n\n neuron_dl = NeuronDeepLift(model, model.relu)\n attributions = neuron_dl.attribute(inputs, 0, attribute_to_neuron_input=False)\n assertTensorAlmostEqual(self, attributions[0], [[0.0, 0.0, 0.0]])\n assertTensorAlmostEqual(self, attributions[1], [[0.0, 0.0, 0.0]])\n\n def test_deeplift_compare_with_and_without_inplace(self) -> None:\n model1 = ReLULinearModel(inplace=True)\n model2 = ReLULinearModel()\n x1 = torch.tensor([[-10.0, 1.0, -5.0]], requires_grad=True)\n x2 = torch.tensor([[3.0, 3.0, 1.0]], requires_grad=True)\n inputs = (x1, x2)\n neuron_dl1 = NeuronDeepLift(model1, model1.relu)\n attributions1 = neuron_dl1.attribute(inputs, 0, attribute_to_neuron_input=False)\n\n neuron_dl2 = NeuronDeepLift(model2, model2.relu)\n attributions2 = neuron_dl2.attribute(inputs, 0, attribute_to_neuron_input=False)\n\n assertTensorAlmostEqual(self, attributions1[0], attributions2[0])\n assertTensorAlmostEqual(self, attributions1[1], attributions2[1])\n\n def test_linear_neuron_deeplift(self) -> None:\n model = ReLULinearModel()\n inputs, baselines = _create_inps_and_base_for_deeplift_neuron_layer_testing()\n\n neuron_dl = NeuronDeepLift(model, model.l3)\n attributions = neuron_dl.attribute(\n inputs, 0, baselines, attribute_to_neuron_input=True\n )\n assertTensorAlmostEqual(self, attributions[0], [[-0.0, 0.0, -0.0]])\n assertTensorAlmostEqual(self, attributions[1], [[0.0, 0.0, 0.0]])\n\n attributions = neuron_dl.attribute(\n inputs, 0, baselines, attribute_to_neuron_input=False\n )\n self.assertTrue(neuron_dl.multiplies_by_inputs)\n assertTensorAlmostEqual(self, attributions[0], [[-0.0, 0.0, -0.0]])\n assertTensorAlmostEqual(self, attributions[1], [[6.0, 9.0, 0.0]])\n\n def test_linear_neuron_deeplift_wo_inp_marginal_effects(self) -> None:\n model = ReLULinearModel()\n inputs, baselines = _create_inps_and_base_for_deeplift_neuron_layer_testing()\n\n neuron_dl = NeuronDeepLift(model, model.l3, multiply_by_inputs=False)\n attributions = neuron_dl.attribute(\n inputs, 0, baselines, attribute_to_neuron_input=False\n )\n assertTensorAlmostEqual(self, attributions[0], [[-0.0, 0.0, -0.0]])\n assertTensorAlmostEqual(self, attributions[1], [[2.0, 3.0, 0.0]])\n\n def test_relu_deeplift_with_custom_attr_func(self) -> None:\n model = ReLULinearModel()\n inputs, baselines = _create_inps_and_base_for_deeplift_neuron_layer_testing()\n neuron_dl = NeuronDeepLift(model, model.l3)\n expected = ([0.0, 0.0, 0.0], [0.0, 0.0, 0.0])\n self._relu_custom_attr_func_assert(neuron_dl, inputs, baselines, expected)\n\n def test_relu_neuron_deeplift_shap(self) -> None:\n model = ReLULinearModel()\n (\n inputs,\n baselines,\n ) = _create_inps_and_base_for_deepliftshap_neuron_layer_testing()\n\n neuron_dl = NeuronDeepLiftShap(model, model.relu)\n\n attributions = neuron_dl.attribute(\n inputs, 0, baselines, attribute_to_neuron_input=False\n )\n assertTensorAlmostEqual(self, attributions[0], [[0.0, 0.0, 0.0]])\n assertTensorAlmostEqual(self, attributions[1], [[0.0, 0.0, 0.0]])\n\n def test_linear_neuron_deeplift_shap(self) -> None:\n model = ReLULinearModel()\n (\n inputs,\n baselines,\n ) = _create_inps_and_base_for_deepliftshap_neuron_layer_testing()\n\n neuron_dl = NeuronDeepLiftShap(model, model.l3)\n attributions = neuron_dl.attribute(\n inputs, 0, baselines, attribute_to_neuron_input=True\n )\n assertTensorAlmostEqual(self, attributions[0], [[-0.0, 0.0, -0.0]])\n assertTensorAlmostEqual(self, attributions[1], [[0.0, 0.0, 0.0]])\n\n attributions = neuron_dl.attribute(\n inputs, 0, baselines, attribute_to_neuron_input=False\n )\n\n self.assertTrue(neuron_dl.multiplies_by_inputs)\n assertTensorAlmostEqual(self, attributions[0], [[-0.0, 0.0, -0.0]])\n assertTensorAlmostEqual(self, attributions[1], [[6.0, 9.0, 0.0]])\n\n def test_linear_neuron_deeplift_shap_wo_inp_marginal_effects(self) -> None:\n model = ReLULinearModel()\n (\n inputs,\n baselines,\n ) = _create_inps_and_base_for_deepliftshap_neuron_layer_testing()\n\n neuron_dl = NeuronDeepLiftShap(model, model.l3, multiply_by_inputs=False)\n attributions = neuron_dl.attribute(\n inputs, 0, baselines, attribute_to_neuron_input=False\n )\n\n assertTensorAlmostEqual(self, attributions[0], [[-0.0, 0.0, -0.0]])\n assertTensorAlmostEqual(self, attributions[1], [[2.0, 3.0, 0.0]])\n\n attributions = neuron_dl.attribute(\n inputs, lambda x: x[:, 0], baselines, attribute_to_neuron_input=False\n )\n\n assertTensorAlmostEqual(self, attributions[0], [[-0.0, 0.0, -0.0]])\n assertTensorAlmostEqual(self, attributions[1], [[2.0, 3.0, 0.0]])\n\n def test_relu_deepliftshap_with_custom_attr_func(self) -> None:\n model = ReLULinearModel()\n (\n inputs,\n baselines,\n ) = _create_inps_and_base_for_deepliftshap_neuron_layer_testing()\n neuron_dl = NeuronDeepLiftShap(model, model.l3)\n expected = (torch.zeros(3, 3), torch.zeros(3, 3))\n self._relu_custom_attr_func_assert(neuron_dl, inputs, baselines, expected)\n\n def _relu_custom_attr_func_assert(\n self,\n attr_method: Union[NeuronDeepLift, NeuronDeepLiftShap],\n inputs: TensorOrTupleOfTensorsGeneric,\n baselines,\n expected,\n ) -> None:\n def custom_attr_func(\n multipliers: Tuple[Tensor, ...],\n inputs: Tuple[Tensor, ...],\n baselines: Union[None, Tuple[Union[Tensor, int, float], ...]] = None,\n ) -> Tuple[Tensor, ...]:\n return tuple(multiplier * 0.0 for multiplier in multipliers)\n\n attr = attr_method.attribute(\n inputs, 0, baselines, custom_attribution_func=custom_attr_func\n )\n assertTensorAlmostEqual(self, attr[0], expected[0], 0.0)\n assertTensorAlmostEqual(self, attr[1], expected[1], 0.0)\n\n def test_lin_maxpool_lin_classification(self) -> None:\n inputs = torch.ones(2, 4)\n baselines = torch.tensor([[1, 2, 3, 9], [4, 8, 6, 7]]).float()\n\n model = LinearMaxPoolLinearModel()\n ndl = NeuronDeepLift(model, model.pool1)\n attr = ndl.attribute(inputs, neuron_selector=(0), baselines=baselines)\n\n ndl2 = NeuronDeepLift(model, model.lin2)\n attr2 = ndl2.attribute(\n inputs,\n neuron_selector=(0),\n baselines=baselines,\n attribute_to_neuron_input=True,\n )\n assertTensorAlmostEqual(self, attr, attr2)\n\n def test_convnet_maxpool2d_classification(self) -> None:\n inputs = 100 * torch.randn(2, 1, 10, 10)\n model = BasicModel_ConvNet()\n\n ndl = NeuronDeepLift(model, model.pool1)\n attr = ndl.attribute(inputs, neuron_selector=(0, 0, 0))\n\n ndl2 = NeuronDeepLift(model, model.conv2)\n attr2 = ndl2.attribute(\n inputs, neuron_selector=(0, 0, 0), attribute_to_neuron_input=True\n )\n\n assertTensorAlmostEqual(self, attr.sum(), attr2.sum())\n\n def test_convnet_maxpool3d_classification(self) -> None:\n inputs = 100 * torch.randn(2, 1, 10, 10, 10)\n model = BasicModel_ConvNet_MaxPool3d()\n\n ndl = NeuronDeepLift(model, model.pool1)\n attr = ndl.attribute(inputs, neuron_selector=(0, 0, 0, 0))\n\n ndl2 = NeuronDeepLift(model, model.conv2)\n attr2 = ndl2.attribute(\n inputs, neuron_selector=(0, 0, 0, 0), attribute_to_neuron_input=True\n )\n\n assertTensorAlmostEqual(self, attr.sum(), attr2.sum())\n" ]
[ [ "torch.randn", "torch.zeros", "torch.ones", "torch.tensor" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
minnieteng/smoke_project
[ "cc3c8f16f7759fe29e46d3cec32a3ed6ca86bd5f" ]
[ "smoke/noaa/plot_grid.py" ]
[ "import matplotlib.pyplot as plt\nimport numpy as np\n\n\ngrid2D = np.load(r\"C:\\temp\\10km_grids\\20180808-23.npy\")\n\nfig, ax = plt.subplots(figsize=(16.2, 16))\nim = ax.imshow(grid2D)\nax.set_xlabel(\"Cols\")\nax.set_ylabel(\"Rows\")\nplt.colorbar(im)\n\nplt.savefig('grid2D.png')\n" ]
[ [ "numpy.load", "matplotlib.pyplot.savefig", "matplotlib.pyplot.subplots", "matplotlib.pyplot.colorbar" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
sherry-1001/dgl-ke
[ "2d2542a21f9725f764e9b927ed257c575f374f47" ]
[ "python/dglke/dataloader/sampler.py" ]
[ "# -*- coding: utf-8 -*-\n#\n# sampler.py\n#\n# Copyright 2020 Amazon.com, Inc. or its affiliates. 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\nimport math\nimport numpy as np\nimport scipy as sp\nimport dgl.backend as F\nimport dgl\nimport os\nimport sys\nimport pickle\nimport time\n\nfrom dgl.base import NID, EID\n\ndef SoftRelationPartition(edges, n, threshold=0.05):\n \"\"\"This partitions a list of edges to n partitions according to their\n relation types. For any relation with number of edges larger than the\n threshold, its edges will be evenly distributed into all partitions.\n For any relation with number of edges smaller than the threshold, its\n edges will be put into one single partition.\n\n Algo:\n For r in relations:\n if r.size() > threadold\n Evenly divide edges of r into n parts and put into each relation.\n else\n Find partition with fewest edges, and put edges of r into \n this partition.\n\n Parameters\n ----------\n edges : (heads, rels, tails) triple\n Edge list to partition\n n : int\n Number of partitions\n threshold : float\n The threshold of whether a relation is LARGE or SMALL\n Default: 5%\n\n Returns\n -------\n List of np.array\n Edges of each partition\n List of np.array\n Edge types of each partition\n bool\n Whether there exists some relations belongs to multiple partitions\n \"\"\"\n heads, rels, tails = edges\n print('relation partition {} edges into {} parts'.format(len(heads), n))\n uniq, cnts = np.unique(rels, return_counts=True)\n idx = np.flip(np.argsort(cnts))\n cnts = cnts[idx]\n uniq = uniq[idx]\n assert cnts[0] > cnts[-1]\n edge_cnts = np.zeros(shape=(n,), dtype=np.int64)\n rel_cnts = np.zeros(shape=(n,), dtype=np.int64)\n rel_dict = {}\n rel_parts = []\n cross_rel_part = []\n for _ in range(n):\n rel_parts.append([])\n\n large_threshold = int(len(rels) * threshold)\n capacity_per_partition = int(len(rels) / n)\n # ensure any relation larger than the partition capacity will be split\n large_threshold = capacity_per_partition if capacity_per_partition < large_threshold \\\n else large_threshold\n num_cross_part = 0\n for i in range(len(cnts)):\n cnt = cnts[i]\n r = uniq[i]\n r_parts = []\n if cnt > large_threshold:\n avg_part_cnt = (cnt // n) + 1\n num_cross_part += 1\n for j in range(n):\n part_cnt = avg_part_cnt if cnt > avg_part_cnt else cnt\n r_parts.append([j, part_cnt])\n rel_parts[j].append(r)\n edge_cnts[j] += part_cnt\n rel_cnts[j] += 1\n cnt -= part_cnt\n cross_rel_part.append(r)\n else:\n idx = np.argmin(edge_cnts)\n r_parts.append([idx, cnt])\n rel_parts[idx].append(r)\n edge_cnts[idx] += cnt\n rel_cnts[idx] += 1\n rel_dict[r] = r_parts\n\n for i, edge_cnt in enumerate(edge_cnts):\n print('part {} has {} edges and {} relations'.format(i, edge_cnt, rel_cnts[i]))\n print('{}/{} duplicated relation across partitions'.format(num_cross_part, len(cnts)))\n\n parts = []\n for i in range(n):\n parts.append([])\n rel_parts[i] = np.array(rel_parts[i])\n\n for i, r in enumerate(rels):\n r_part = rel_dict[r][0]\n part_idx = r_part[0]\n cnt = r_part[1]\n parts[part_idx].append(i)\n cnt -= 1\n if cnt == 0:\n rel_dict[r].pop(0)\n else:\n rel_dict[r][0][1] = cnt\n\n for i, part in enumerate(parts):\n parts[i] = np.array(part, dtype=np.int64)\n shuffle_idx = np.concatenate(parts)\n heads[:] = heads[shuffle_idx]\n rels[:] = rels[shuffle_idx]\n tails[:] = tails[shuffle_idx]\n\n off = 0\n for i, part in enumerate(parts):\n parts[i] = np.arange(off, off + len(part))\n off += len(part)\n cross_rel_part = np.array(cross_rel_part)\n\n return parts, rel_parts, num_cross_part > 0, cross_rel_part\n\ndef BalancedRelationPartition(edges, n):\n \"\"\"This partitions a list of edges based on relations to make sure\n each partition has roughly the same number of edges and relations.\n Algo:\n For r in relations:\n Find partition with fewest edges\n if r.size() > num_of empty_slot\n put edges of r into this partition to fill the partition,\n find next partition with fewest edges to put r in.\n else\n put edges of r into this partition.\n\n Parameters\n ----------\n edges : (heads, rels, tails) triple\n Edge list to partition\n n : int\n number of partitions\n\n Returns\n -------\n List of np.array\n Edges of each partition\n List of np.array\n Edge types of each partition\n bool\n Whether there exists some relations belongs to multiple partitions\n \"\"\"\n heads, rels, tails = edges\n print('relation partition {} edges into {} parts'.format(len(heads), n))\n uniq, cnts = np.unique(rels, return_counts=True)\n idx = np.flip(np.argsort(cnts))\n cnts = cnts[idx]\n uniq = uniq[idx]\n assert cnts[0] > cnts[-1]\n edge_cnts = np.zeros(shape=(n,), dtype=np.int64)\n rel_cnts = np.zeros(shape=(n,), dtype=np.int64)\n rel_dict = {}\n rel_parts = []\n for _ in range(n):\n rel_parts.append([])\n\n max_edges = (len(rels) // n) + 1\n num_cross_part = 0\n for i in range(len(cnts)):\n cnt = cnts[i]\n r = uniq[i]\n r_parts = []\n\n while cnt > 0:\n idx = np.argmin(edge_cnts)\n if edge_cnts[idx] + cnt <= max_edges:\n r_parts.append([idx, cnt])\n rel_parts[idx].append(r)\n edge_cnts[idx] += cnt\n rel_cnts[idx] += 1\n cnt = 0\n else:\n cur_cnt = max_edges - edge_cnts[idx]\n r_parts.append([idx, cur_cnt])\n rel_parts[idx].append(r)\n edge_cnts[idx] += cur_cnt\n rel_cnts[idx] += 1\n num_cross_part += 1\n cnt -= cur_cnt\n rel_dict[r] = r_parts\n\n for i, edge_cnt in enumerate(edge_cnts):\n print('part {} has {} edges and {} relations'.format(i, edge_cnt, rel_cnts[i]))\n print('{}/{} duplicated relation across partitions'.format(num_cross_part, len(cnts)))\n\n parts = []\n for i in range(n):\n parts.append([])\n rel_parts[i] = np.array(rel_parts[i])\n\n for i, r in enumerate(rels):\n r_part = rel_dict[r][0]\n part_idx = r_part[0]\n cnt = r_part[1]\n parts[part_idx].append(i)\n cnt -= 1\n if cnt == 0:\n rel_dict[r].pop(0)\n else:\n rel_dict[r][0][1] = cnt\n\n for i, part in enumerate(parts):\n parts[i] = np.array(part, dtype=np.int64)\n shuffle_idx = np.concatenate(parts)\n heads[:] = heads[shuffle_idx]\n rels[:] = rels[shuffle_idx]\n tails[:] = tails[shuffle_idx]\n\n off = 0\n for i, part in enumerate(parts):\n parts[i] = np.arange(off, off + len(part))\n off += len(part)\n\n return parts, rel_parts, num_cross_part > 0\n\ndef RandomPartition(edges, n):\n \"\"\"This partitions a list of edges randomly across n partitions\n\n Parameters\n ----------\n edges : (heads, rels, tails) triple\n Edge list to partition\n n : int\n number of partitions\n\n Returns\n -------\n List of np.array\n Edges of each partition\n \"\"\"\n heads, rels, tails = edges\n print('random partition {} edges into {} parts'.format(len(heads), n))\n idx = np.random.permutation(len(heads))\n heads[:] = heads[idx]\n rels[:] = rels[idx]\n tails[:] = tails[idx]\n\n part_size = int(math.ceil(len(idx) / n))\n parts = []\n for i in range(n):\n start = part_size * i\n end = min(part_size * (i + 1), len(idx))\n parts.append(idx[start:end])\n print('part {} has {} edges'.format(i, len(parts[-1])))\n return parts\n\ndef ConstructGraph(edges, n_entities, args):\n \"\"\"Construct Graph for training\n\n Parameters\n ----------\n edges : (heads, rels, tails) triple\n Edge list\n n_entities : int\n number of entities\n args :\n Global configs.\n \"\"\"\n src, etype_id, dst = edges\n coo = sp.sparse.coo_matrix((np.ones(len(src)), (src, dst)), shape=[n_entities, n_entities])\n g = dgl.DGLGraph(coo, readonly=True, multigraph=True, sort_csr=True)\n g.edata['tid'] = F.tensor(etype_id, F.int64)\n return g\n\nclass TrainDataset(object):\n \"\"\"Dataset for training\n\n Parameters\n ----------\n dataset : KGDataset\n Original dataset.\n args :\n Global configs.\n ranks:\n Number of partitions.\n \"\"\"\n def __init__(self, dataset, args, ranks=64):\n triples = dataset.train\n num_train = len(triples[0])\n print('|Train|:', num_train)\n\n if ranks > 1 and args.rel_part:\n self.edge_parts, self.rel_parts, self.cross_part, self.cross_rels = \\\n SoftRelationPartition(triples, ranks)\n elif ranks > 1:\n self.edge_parts = RandomPartition(triples, ranks)\n self.cross_part = True\n else:\n self.edge_parts = [np.arange(num_train)]\n self.rel_parts = [np.arange(dataset.n_relations)]\n self.cross_part = False\n\n self.g = ConstructGraph(triples, dataset.n_entities, args)\n\n def create_sampler(self, batch_size, neg_sample_size=2, neg_chunk_size=None, mode='head', num_workers=32,\n shuffle=True, exclude_positive=False, rank=0):\n \"\"\"Create sampler for training\n\n Parameters\n ----------\n batch_size : int\n Batch size of each mini batch.\n neg_sample_size : int\n How many negative edges sampled for each node.\n neg_chunk_size : int\n How many edges in one chunk. We split one batch into chunks.\n mode : str\n Sampling mode.\n number_workers: int\n Number of workers used in parallel for this sampler\n shuffle : bool\n If True, shuffle the seed edges.\n If False, do not shuffle the seed edges.\n Default: False\n exclude_positive : bool\n If True, exlucde true positive edges in sampled negative edges\n If False, return all sampled negative edges even there are positive edges\n Default: False\n rank : int\n Which partition to sample.\n\n Returns\n -------\n dgl.contrib.sampling.EdgeSampler\n Edge sampler\n \"\"\"\n EdgeSampler = getattr(dgl.contrib.sampling, 'EdgeSampler')\n assert batch_size % neg_sample_size == 0, 'batch_size should be divisible by B'\n return EdgeSampler(self.g,\n seed_edges=F.tensor(self.edge_parts[rank]),\n batch_size=batch_size,\n neg_sample_size=int(neg_sample_size/neg_chunk_size),\n chunk_size=neg_chunk_size,\n negative_mode=mode,\n num_workers=num_workers,\n shuffle=shuffle,\n exclude_positive=exclude_positive,\n return_false_neg=False)\n\n\nclass ChunkNegEdgeSubgraph(dgl.DGLGraph):\n \"\"\"Wrapper for negative graph\n\n Parameters\n ----------\n neg_g : DGLGraph\n Graph holding negative edges.\n num_chunks : int\n Number of chunks in sampled graph.\n chunk_size : int\n Info of chunk_size.\n neg_sample_size : int\n Info of neg_sample_size.\n neg_head : bool\n If True, negative_mode is 'head'\n If False, negative_mode is 'tail'\n \"\"\"\n def __init__(self, subg, num_chunks, chunk_size,\n neg_sample_size, neg_head):\n super(ChunkNegEdgeSubgraph, self).__init__(graph_data=subg.sgi.graph,\n readonly=True,\n parent=subg._parent)\n self.ndata[NID] = subg.sgi.induced_nodes.tousertensor()\n self.edata[EID] = subg.sgi.induced_edges.tousertensor()\n self.subg = subg\n self.num_chunks = num_chunks\n self.chunk_size = chunk_size\n self.neg_sample_size = neg_sample_size\n self.neg_head = neg_head\n\n @property\n def head_nid(self):\n return self.subg.head_nid\n\n @property\n def tail_nid(self):\n return self.subg.tail_nid\n\n\ndef create_neg_subgraph(pos_g, neg_g, chunk_size, neg_sample_size, is_chunked,\n neg_head, num_nodes):\n \"\"\"KG models need to know the number of chunks, the chunk size and negative sample size\n of a negative subgraph to perform the computation more efficiently.\n This function tries to infer all of these information of the negative subgraph\n and create a wrapper class that contains all of the information.\n\n Parameters\n ----------\n pos_g : DGLGraph\n Graph holding positive edges.\n neg_g : DGLGraph\n Graph holding negative edges.\n chunk_size : int\n Chunk size of negative subgrap.\n neg_sample_size : int\n Negative sample size of negative subgrap.\n is_chunked : bool\n If True, the sampled batch is chunked.\n neg_head : bool\n If True, negative_mode is 'head'\n If False, negative_mode is 'tail'\n num_nodes: int\n Total number of nodes in the whole graph.\n\n Returns\n -------\n ChunkNegEdgeSubgraph\n Negative graph wrapper\n \"\"\"\n assert neg_g.number_of_edges() % pos_g.number_of_edges() == 0\n # We use all nodes to create negative edges. Regardless of the sampling algorithm,\n # we can always view the subgraph with one chunk.\n if (neg_head and len(neg_g.head_nid) == num_nodes) \\\n or (not neg_head and len(neg_g.tail_nid) == num_nodes):\n num_chunks = 1\n chunk_size = pos_g.number_of_edges()\n elif is_chunked:\n # This is probably for evaluation.\n if pos_g.number_of_edges() < chunk_size \\\n and neg_g.number_of_edges() % neg_sample_size == 0:\n num_chunks = 1\n chunk_size = pos_g.number_of_edges()\n # This is probably the last batch in the training. Let's ignore it.\n elif pos_g.number_of_edges() % chunk_size > 0:\n return None\n else:\n num_chunks = int(pos_g.number_of_edges() / chunk_size)\n assert num_chunks * chunk_size == pos_g.number_of_edges()\n else:\n num_chunks = pos_g.number_of_edges()\n chunk_size = 1\n return ChunkNegEdgeSubgraph(neg_g, num_chunks, chunk_size,\n neg_sample_size, neg_head)\n\nclass EvalSampler(object):\n \"\"\"Sampler for validation and testing\n\n Parameters\n ----------\n g : DGLGraph\n Graph containing KG graph\n edges : tensor\n Seed edges\n batch_size : int\n Batch size of each mini batch.\n neg_sample_size : int\n How many negative edges sampled for each node.\n neg_chunk_size : int\n How many edges in one chunk. We split one batch into chunks.\n mode : str\n Sampling mode.\n number_workers: int\n Number of workers used in parallel for this sampler\n filter_false_neg : bool\n If True, exlucde true positive edges in sampled negative edges\n If False, return all sampled negative edges even there are positive edges\n Default: True\n \"\"\"\n def __init__(self, g, edges, batch_size, neg_sample_size, neg_chunk_size, mode, num_workers=32,\n filter_false_neg=True):\n EdgeSampler = getattr(dgl.contrib.sampling, 'EdgeSampler')\n self.sampler = EdgeSampler(g,\n batch_size=batch_size,\n seed_edges=edges,\n neg_sample_size=neg_sample_size,\n chunk_size=neg_chunk_size,\n negative_mode=mode,\n num_workers=num_workers,\n shuffle=False,\n exclude_positive=False,\n relations=g.edata['tid'],\n return_false_neg=filter_false_neg)\n self.sampler_iter = iter(self.sampler)\n self.mode = mode\n self.neg_head = 'head' in mode\n self.g = g\n self.filter_false_neg = filter_false_neg\n self.neg_chunk_size = neg_chunk_size\n self.neg_sample_size = neg_sample_size\n\n def __iter__(self):\n return self\n\n def __next__(self):\n \"\"\"Get next batch\n\n Returns\n -------\n DGLGraph\n Sampled positive graph\n ChunkNegEdgeSubgraph\n Negative graph wrapper\n \"\"\"\n while True:\n pos_g, neg_g = next(self.sampler_iter)\n if self.filter_false_neg:\n neg_positive = neg_g.edata['false_neg']\n neg_g = create_neg_subgraph(pos_g, neg_g, \n self.neg_chunk_size, \n self.neg_sample_size, \n 'chunk' in self.mode, \n self.neg_head, \n self.g.number_of_nodes())\n if neg_g is not None:\n break\n\n pos_g.ndata['id'] = pos_g.parent_nid\n neg_g.ndata['id'] = neg_g.parent_nid\n pos_g.edata['id'] = pos_g._parent.edata['tid'][pos_g.parent_eid]\n if self.filter_false_neg:\n neg_g.edata['bias'] = F.astype(-neg_positive, F.float32)\n return pos_g, neg_g\n\n def reset(self):\n \"\"\"Reset the sampler\n \"\"\"\n self.sampler_iter = iter(self.sampler)\n return self\n\nclass EvalDataset(object):\n \"\"\"Dataset for validation or testing\n\n Parameters\n ----------\n dataset : KGDataset\n Original dataset.\n args :\n Global configs.\n \"\"\"\n def __init__(self, dataset, args):\n src = [dataset.train[0]]\n etype_id = [dataset.train[1]]\n dst = [dataset.train[2]]\n self.num_train = len(dataset.train[0])\n if dataset.valid is not None:\n src.append(dataset.valid[0])\n etype_id.append(dataset.valid[1])\n dst.append(dataset.valid[2])\n self.num_valid = len(dataset.valid[0])\n else:\n self.num_valid = 0\n if dataset.test is not None:\n src.append(dataset.test[0])\n etype_id.append(dataset.test[1])\n dst.append(dataset.test[2])\n self.num_test = len(dataset.test[0])\n else:\n self.num_test = 0\n assert len(src) > 1, \"we need to have at least validation set or test set.\"\n src = np.concatenate(src)\n etype_id = np.concatenate(etype_id)\n dst = np.concatenate(dst)\n\n coo = sp.sparse.coo_matrix((np.ones(len(src)), (src, dst)),\n shape=[dataset.n_entities, dataset.n_entities])\n g = dgl.DGLGraph(coo, readonly=True, multigraph=True, sort_csr=True)\n g.edata['tid'] = F.tensor(etype_id, F.int64)\n self.g = g\n\n if args.eval_percent < 1:\n self.valid = np.random.randint(0, self.num_valid,\n size=(int(self.num_valid * args.eval_percent),)) + self.num_train\n else:\n self.valid = np.arange(self.num_train, self.num_train + self.num_valid)\n print('|valid|:', len(self.valid))\n\n if args.eval_percent < 1:\n self.test = np.random.randint(0, self.num_test,\n size=(int(self.num_test * args.eval_percent,)))\n self.test += self.num_train + self.num_valid\n else:\n self.test = np.arange(self.num_train + self.num_valid, self.g.number_of_edges())\n print('|test|:', len(self.test))\n\n def get_edges(self, eval_type):\n \"\"\" Get all edges in this dataset\n\n Parameters\n ----------\n eval_type : str\n Sampling type, 'valid' for validation and 'test' for testing\n\n Returns\n -------\n np.array\n Edges\n \"\"\"\n if eval_type == 'valid':\n return self.valid\n elif eval_type == 'test':\n return self.test\n else:\n raise Exception('get invalid type: ' + eval_type)\n\n def create_sampler(self, eval_type, batch_size, neg_sample_size, neg_chunk_size,\n filter_false_neg, mode='head', num_workers=32, rank=0, ranks=1):\n \"\"\"Create sampler for validation or testing\n\n Parameters\n ----------\n eval_type : str\n Sampling type, 'valid' for validation and 'test' for testing\n batch_size : int\n Batch size of each mini batch.\n neg_sample_size : int\n How many negative edges sampled for each node.\n neg_chunk_size : int\n How many edges in one chunk. We split one batch into chunks.\n filter_false_neg : bool\n If True, exlucde true positive edges in sampled negative edges\n If False, return all sampled negative edges even there are positive edges\n mode : str\n Sampling mode.\n number_workers: int\n Number of workers used in parallel for this sampler\n rank : int\n Which partition to sample.\n ranks : int\n Total number of partitions.\n\n Returns\n -------\n dgl.contrib.sampling.EdgeSampler\n Edge sampler\n \"\"\"\n edges = self.get_edges(eval_type)\n beg = edges.shape[0] * rank // ranks\n end = min(edges.shape[0] * (rank + 1) // ranks, edges.shape[0])\n edges = edges[beg: end]\n return EvalSampler(self.g, edges, batch_size, neg_sample_size, neg_chunk_size,\n mode, num_workers, filter_false_neg)\n\nclass NewBidirectionalOneShotIterator:\n \"\"\"Grouped samper iterator\n\n Parameters\n ----------\n dataloader_head : dgl.contrib.sampling.EdgeSampler\n EdgeSampler in head mode\n dataloader_tail : dgl.contrib.sampling.EdgeSampler\n EdgeSampler in tail mode\n neg_chunk_size : int\n How many edges in one chunk. We split one batch into chunks.\n neg_sample_size : int\n How many negative edges sampled for each node.\n is_chunked : bool\n If True, the sampled batch is chunked.\n num_nodes : int\n Total number of nodes in the whole graph.\n \"\"\"\n def __init__(self, dataloader_head, dataloader_tail, neg_chunk_size, neg_sample_size,\n is_chunked, num_nodes):\n self.sampler_head = dataloader_head\n self.sampler_tail = dataloader_tail\n self.iterator_head = self.one_shot_iterator(dataloader_head, neg_chunk_size,\n neg_sample_size, is_chunked,\n True, num_nodes)\n self.iterator_tail = self.one_shot_iterator(dataloader_tail, neg_chunk_size,\n neg_sample_size, is_chunked,\n False, num_nodes)\n self.step = 0\n\n def __next__(self):\n self.step += 1\n if self.step % 2 == 0:\n pos_g, neg_g = next(self.iterator_head)\n else:\n pos_g, neg_g = next(self.iterator_tail)\n return pos_g, neg_g\n\n @staticmethod\n def one_shot_iterator(dataloader, neg_chunk_size, neg_sample_size, is_chunked,\n neg_head, num_nodes):\n while True:\n for pos_g, neg_g in dataloader:\n neg_g = create_neg_subgraph(pos_g, neg_g, neg_chunk_size, neg_sample_size,\n is_chunked, neg_head, num_nodes)\n if neg_g is None:\n continue\n\n pos_g.ndata['id'] = pos_g.parent_nid\n neg_g.ndata['id'] = neg_g.parent_nid\n pos_g.edata['id'] = pos_g._parent.edata['tid'][pos_g.parent_eid]\n yield pos_g, neg_g\n" ]
[ [ "numpy.unique", "numpy.arange", "numpy.concatenate", "numpy.argmin", "numpy.argsort", "numpy.array", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
hanqiu-hq/cvpods
[ "597fa669151fdad87c250fa118a9e3a555f4fb5e", "597fa669151fdad87c250fa118a9e3a555f4fb5e", "597fa669151fdad87c250fa118a9e3a555f4fb5e", "597fa669151fdad87c250fa118a9e3a555f4fb5e", "597fa669151fdad87c250fa118a9e3a555f4fb5e" ]
[ "cvpods/layers/tree_filter_v2.py", "cvpods/layers/splat.py", "cvpods/data/transforms/transform.py", "cvpods/modeling/backbone/dynamic_arch/dynamic_cell.py", "cvpods/layers/activation_funcs.py" ]
[ "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n# Copyright (C) 2019-2021 Megvii Inc. All rights reserved.\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom .tree_filter_core import MinimumSpanningTree, RandomSpanningTree, TreeFilter2D\n\n\nclass TreeFilterV2(nn.Module):\n def __init__(self, guide_channels, in_channels, embed_channels, num_groups=1, eps=1e-8):\n super(TreeFilterV2, self).__init__()\n ''' Hyper Parameters '''\n self.eps = eps\n self.guide_channels = guide_channels\n self.in_channels = in_channels\n self.embed_channels = embed_channels\n self.num_groups = num_groups\n\n ''' Embedding Layers '''\n self.embed_layer = nn.Conv2d(in_channels, embed_channels, kernel_size=1, bias=False)\n self.conf_layer = nn.Conv2d(in_channels, num_groups, kernel_size=1, bias=False)\n self.guide_layer = nn.Conv2d(guide_channels, self.embed_channels, kernel_size=1, bias=False)\n self.beta = nn.Parameter(torch.zeros(num_groups))\n self.gamma = nn.Parameter(torch.zeros(1))\n\n '''Core of Tree Filter'''\n self.rst_layer = RandomSpanningTree(TreeFilter2D.norm2_distance, torch.exp)\n self.mst_layer = MinimumSpanningTree(TreeFilter2D.norm2_distance, torch.exp)\n self.tree_filter_layer = TreeFilter2D(groups=num_groups)\n\n ''' Parameters init '''\n self.reset_parameter()\n\n def reset_parameter(self):\n nn.init.constant_(self.conf_layer.weight, 0)\n nn.init.normal_(self.embed_layer.weight, std=0.01)\n nn.init.normal_(self.guide_layer.weight, std=0.01)\n nn.init.constant_(self.gamma, 0)\n nn.init.constant_(self.beta, 0)\n\n def split_groups(self, x):\n x = x.reshape(x.shape[0] * self.num_groups, -1, *x.shape[2:])\n return x\n\n def expand_groups(self, x):\n target_dim = max(self.num_groups // x.shape[1], 1)\n x = x.unsqueeze(2)\n x = x.expand(*x.shape[:2], target_dim, *x.shape[3:])\n x = x.reshape(x.shape[0], -1, *x.shape[3:])\n return x\n\n def forward(self, feature, guide):\n latent = feature\n\n ''' Compute embedding features '''\n embed = self.embed_layer(feature)\n\n ''' Spanning tree process '''\n guide = F.adaptive_avg_pool2d(guide, feature.shape[-2:])\n guide_embed = self.guide_layer(guide)\n if self.training:\n tree = self.rst_layer(guide_embed)\n else:\n tree = self.mst_layer(guide_embed)\n\n ''' Reshape beta '''\n beta = self.beta.reshape(1, -1, 1, 1)\n beta = beta.expand(embed.shape[0], self.num_groups, *embed.shape[2:])\n\n ''' Compute confidence '''\n conf = self.conf_layer(feature).sigmoid()\n conf = self.expand_groups(conf)\n conf_norm = self.tree_filter_layer(conf, embed, tree, guide_embed, beta)\n\n ''' Feature transform '''\n feature = (self.split_groups(feature) * self.split_groups(conf)).reshape_as(feature)\n feature = self.tree_filter_layer(feature, embed, tree, guide_embed, beta)\n feature_size = feature.size()\n feature = self.split_groups(feature) / (self.eps + self.split_groups(conf_norm))\n feature = feature.reshape(feature_size)\n\n ''' Projection '''\n feature = self.gamma * feature\n feature = feature + latent\n\n return feature\n", "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n# Copyright (C) zhanghang1989. All rights reserved.\n# https://github.com/zhanghang1989/ResNeSt/blob/43c1c4b5c91898c75a50fd70867f32c6cd9aeef5/resnest/torch/models/splat.py # noqa\n\n\"\"\"Split-Attention\"\"\"\nimport torch\nimport torch.nn.functional as F\nfrom torch.nn import Module, ReLU\nfrom torch.nn.modules.utils import _pair\n\nfrom cvpods.layers import Conv2d, get_norm\n\n__all__ = ['SplAtConv2d']\n\n\nclass RFConv2d(object):\n def __init__(self, *args, **kwargs):\n raise NotImplementedError\n\n\nclass DropBlock2D(RFConv2d):\n pass\n\n\nclass SplAtConv2d(Module):\n \"\"\"Split-Attention Conv2d\n \"\"\"\n\n def __init__(self,\n in_channels,\n channels,\n kernel_size,\n stride=(1, 1),\n padding=(0, 0),\n dilation=(1, 1),\n groups=1,\n bias=True,\n radix=2,\n reduction_factor=4,\n rectify=False,\n rectify_avg=False,\n norm=None,\n dropblock_prob=0.0,\n **kwargs):\n super(SplAtConv2d, self).__init__()\n padding = _pair(padding)\n self.rectify = rectify and (padding[0] > 0 or padding[1] > 0)\n self.rectify_avg = rectify_avg\n inter_channels = max(in_channels * radix // reduction_factor, 32)\n self.radix = radix\n self.cardinality = groups\n self.channels = channels\n self.dropblock_prob = dropblock_prob\n if self.rectify:\n self.conv = RFConv2d(in_channels,\n channels * radix,\n kernel_size,\n stride,\n padding,\n dilation,\n groups=groups * radix,\n bias=bias,\n average_mode=rectify_avg,\n **kwargs)\n else:\n self.conv = Conv2d(in_channels,\n channels * radix,\n kernel_size,\n stride,\n padding,\n dilation,\n groups=groups * radix,\n bias=bias,\n **kwargs)\n self.use_bn = norm is not None\n self.bn0 = get_norm(norm, channels * radix)\n self.relu = ReLU(inplace=True)\n self.fc1 = Conv2d(channels, inter_channels, 1, groups=self.cardinality)\n self.bn1 = get_norm(norm, inter_channels)\n self.fc2 = Conv2d(inter_channels, channels * radix, 1, groups=self.cardinality)\n if dropblock_prob > 0.0:\n self.dropblock = DropBlock2D(dropblock_prob, 3)\n\n def forward(self, x):\n x = self.conv(x)\n if self.use_bn:\n x = self.bn0(x)\n if self.dropblock_prob > 0.0:\n x = self.dropblock(x)\n x = self.relu(x)\n\n batch, channel = x.shape[:2]\n if self.radix > 1:\n splited = torch.split(x, channel // self.radix, dim=1)\n gap = sum(splited)\n else:\n gap = x\n gap = F.adaptive_avg_pool2d(gap, 1)\n gap = self.fc1(gap)\n\n if self.use_bn:\n gap = self.bn1(gap)\n gap = self.relu(gap)\n\n atten = self.fc2(gap).view((batch, self.radix, self.channels))\n if self.radix > 1:\n atten = F.softmax(atten, dim=1).view(batch, -1, 1, 1)\n else:\n atten = F.sigmoid(atten, dim=1).view(batch, -1, 1, 1)\n\n if self.radix > 1:\n atten = torch.split(atten, channel // self.radix, dim=1)\n out = sum([att * split for (att, split) in zip(atten, splited)])\n else:\n out = atten * x\n return out.contiguous()\n", "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.\n# This file has been modified by Megvii (\"Megvii Modifications\").\n# All Megvii Modifications are Copyright (C) 2019-2021 Megvii Inc. All rights reserved.\n\nimport inspect\nimport random\nfrom abc import ABCMeta, abstractmethod\nfrom typing import Callable, TypeVar\n\nimport cv2\nimport numpy as np\nfrom PIL import Image, ImageFilter, ImageOps\nimport pycocotools.mask as mask_util\n\nimport torch\nimport torchvision.transforms as transforms\n\nimport cvpods\nfrom cvpods.structures import BoxMode\n\nfrom .transform_util import to_float_tensor, to_numpy\n\n__all__ = [\n \"ExpandTransform\",\n \"AffineTransform\",\n \"BlendTransform\",\n \"IoUCropTransform\",\n \"CropTransform\",\n \"CropPadTransform\",\n \"GridSampleTransform\",\n \"RotationTransform\",\n \"HFlipTransform\",\n \"VFlipTransform\",\n \"NoOpTransform\",\n \"ScaleTransform\",\n \"DistortTransform\",\n \"Transform\",\n \"TransformList\",\n \"ExtentTransform\",\n \"ResizeTransform\",\n \"TorchTransform\",\n \"PILColorTransform\",\n # Transform used in ssl\n \"LightningTransform\",\n \"GaussianBlurTransform\",\n \"GaussianBlurConvTransform\",\n \"SolarizationTransform\",\n \"ComposeTransform\",\n \"JigsawCropTransform\",\n \"LabSpaceTransform\",\n \"PadTransform\",\n \"FiveCropTransform\",\n]\n\n# NOTE: to document methods in subclasses, it's sufficient to only document those whose\n# implemenation needs special attention.\n\n\nclass Transform(metaclass=ABCMeta):\n \"\"\"\n Base class for implementations of __deterministic__ transformations for\n image and other data structures. \"Deterministic\" requires that the output of\n all methods of this class are deterministic w.r.t their input arguments. In\n training, there should be a higher-level policy that generates (likely with\n random variations) these transform ops. Each transform op may handle several\n data types, e.g.: image, coordinates, segmentation, bounding boxes. Some of\n them have a default implementation, but can be overwritten if the default\n isn't appropriate. The implementation of each method may choose to modify\n its input data in-place for efficient transformation.\n \"\"\"\n def _set_attributes(self, params: list = None):\n \"\"\"\n Set attributes from the input list of parameters.\n\n Args:\n params (list): list of parameters.\n \"\"\"\n\n if params:\n for k, v in params.items():\n if k != \"self\" and not k.startswith(\"_\"):\n setattr(self, k, v)\n\n @abstractmethod\n def apply_image(self, img: np.ndarray):\n \"\"\"\n Apply the transform on an image.\n\n Args:\n img (ndarray): of shape NxHxWxC, or HxWxC or HxW. The array can be\n of type uint8 in range [0, 255], or floating point in range\n [0, 1] or [0, 255].\n Returns:\n ndarray: image after apply the transformation.\n \"\"\"\n pass\n\n @abstractmethod\n def apply_coords(self, coords: np.ndarray):\n \"\"\"\n Apply the transform on coordinates.\n\n Args:\n coords (ndarray): floating point array of shape Nx2. Each row is (x, y).\n\n Returns:\n ndarray: coordinates after apply the transformation.\n\n Note:\n The coordinates are not pixel indices. Coordinates on an image of\n shape (H, W) are in range [0, W] or [0, H].\n \"\"\"\n\n pass\n\n def apply_segmentation(self, segmentation: np.ndarray) -> np.ndarray:\n \"\"\"\n Apply the transform on a full-image segmentation.\n By default will just perform \"apply_image\".\n\n Args:\n segmentation (ndarray): of shape HxW. The array should have integer\n or bool dtype.\n\n Returns:\n ndarray: segmentation after apply the transformation.\n \"\"\"\n return self.apply_image(segmentation)\n\n def apply_box(self, box: np.ndarray) -> np.ndarray:\n \"\"\"\n Apply the transform on an axis-aligned box.\n By default will transform the corner points and use their\n minimum/maximum to create a new axis-aligned box.\n Note that this default may change the size of your box, e.g. in\n rotations.\n\n Args:\n box (ndarray): Nx4 floating point array of XYXY format in absolute\n coordinates.\n Returns:\n ndarray: box after apply the transformation.\n\n Note:\n The coordinates are not pixel indices. Coordinates on an image of\n shape (H, W) are in range [0, W] or [0, H].\n \"\"\"\n # Indexes of converting (x0, y0, x1, y1) box into 4 coordinates of\n # ([x0, y0], [x1, y0], [x0, y1], [x1, y1]).\n idxs = np.array([(0, 1), (2, 1), (0, 3), (2, 3)]).flatten()\n coords = np.asarray(box).reshape(-1, 4)[:, idxs].reshape(-1, 2)\n coords = self.apply_coords(coords).reshape((-1, 4, 2))\n minxy = coords.min(axis=1)\n maxxy = coords.max(axis=1)\n trans_boxes = np.concatenate((minxy, maxxy), axis=1)\n return trans_boxes\n\n def apply_polygons(self, polygons: list) -> list:\n \"\"\"\n Apply the transform on a list of polygons, each represented by a Nx2\n array.\n By default will just transform all the points.\n\n Args:\n polygon (list[ndarray]): each is a Nx2 floating point array of\n (x, y) format in absolute coordinates.\n Returns:\n list[ndarray]: polygon after apply the transformation.\n\n Note:\n The coordinates are not pixel indices. Coordinates on an image of\n shape (H, W) are in range [0, W] or [0, H].\n \"\"\"\n return [self.apply_coords(p) for p in polygons]\n\n def __call__(self, image, annotations=None, **kwargs):\n \"\"\"\n Apply transfrom to images and annotations (if exist)\n \"\"\"\n image_size = image.shape[:2] # h, w\n image = self.apply_image(image)\n\n if annotations is not None:\n for annotation in annotations:\n if \"bbox\" in annotation:\n if len(annotation[\"bbox\"]) == 4:\n box_mode = BoxMode.XYXY_ABS\n func = self.apply_box\n elif len(annotation[\"bbox\"]) == 5:\n box_mode = BoxMode.XYWHA_ABS\n func = self.apply_rotated_box\n else:\n raise ValueError(\"bbox length must be 4 or 5\")\n\n bbox = BoxMode.convert(\n annotation[\"bbox\"], annotation[\"bbox_mode\"], box_mode)\n # Note that bbox is 1d (per-instance bounding box)\n annotation[\"bbox\"] = func([bbox])[0]\n annotation[\"bbox_mode\"] = box_mode\n\n if \"segmentation\" in annotation:\n # each instance contains 1 or more polygons\n segm = annotation[\"segmentation\"]\n if isinstance(segm, list):\n # polygons\n polygons = [np.asarray(p).reshape(-1, 2) for p in segm]\n annotation[\"segmentation\"] = [\n p.reshape(-1) for p in self.apply_polygons(polygons)\n ]\n elif isinstance(segm, dict):\n # RLE\n mask = mask_util.decode(segm)\n mask = self.apply_segmentation(mask)\n assert tuple(mask.shape[:2]) == image_size\n annotation[\"segmentation\"] = mask\n else:\n raise ValueError(\n \"Cannot transform segmentation of type '{}'!\"\n \"Supported types are: polygons as list[list[float] or ndarray],\"\n \" COCO-style RLE as a dict.\".format(type(segm)))\n\n if \"keypoints\" in annotation:\n \"\"\"\n Transform keypoint annotation of an image.\n\n Args:\n keypoints (list[float]): Nx3 float in cvpods Dataset format.\n transforms (TransformList):\n image_size (tuple): the height, width of the transformed image\n keypoint_hflip_indices (ndarray[int]): see `create_keypoint_hflip_indices`.\n \"\"\"\n # (N*3,) -> (N, 3)\n keypoints = annotation[\"keypoints\"]\n keypoints = np.asarray(keypoints, dtype=\"float64\").reshape(-1, 3)\n keypoints[:, :2] = self.apply_coords(keypoints[:, :2])\n\n # This assumes that HorizFlipTransform is the only one that does flip\n do_hflip = isinstance(self, cvpods.data.transforms.transform.HFlipTransform)\n\n # Alternative way: check if probe points was horizontally flipped.\n # probe = np.asarray([[0.0, 0.0], [image_width, 0.0]])\n # probe_aug = transforms.apply_coords(probe.copy())\n # do_hflip = np.sign(probe[1][0] - probe[0][0]) != np.sign(probe_aug[1][0] - probe_aug[0][0]) # noqa\n\n # If flipped, swap each keypoint with its opposite-handed equivalent\n if do_hflip:\n if \"keypoint_hflip_indices\" in kwargs:\n keypoints = keypoints[kwargs[\"keypoint_hflip_indices\"], :]\n\n # Maintain COCO convention that if visibility == 0, then x, y = 0\n # TODO may need to reset visibility for cropped keypoints,\n # but it does not matter for our existing algorithms\n keypoints[keypoints[:, 2] == 0] = 0\n\n annotation[\"keypoints\"] = keypoints\n\n # For sem seg task\n if \"sem_seg\" in annotation:\n sem_seg = annotation[\"sem_seg\"]\n if isinstance(sem_seg, np.ndarray):\n sem_seg = self.apply_segmentation(sem_seg)\n assert tuple(sem_seg.shape[:2]) == tuple(image.shape[:2]), (\n f\"Image shape is {image.shape[:2]}, \"\n f\"but sem_seg shape is {sem_seg.shape[:2]}.\"\n )\n annotation[\"sem_seg\"] = sem_seg\n else:\n raise ValueError(\n \"Cannot transform segmentation of type '{}'!\"\n \"Supported type is ndarray.\".format(type(sem_seg)))\n return image, annotations\n\n @classmethod\n def register_type(cls, data_type: str, func: Callable):\n \"\"\"\n Register the given function as a handler that this transform will use\n for a specific data type.\n\n Args:\n data_type (str): the name of the data type (e.g., box)\n func (callable): takes a transform and a data, returns the\n transformed data.\n\n Examples:\n\n .. code-block:: python\n\n def func(flip_transform, voxel_data):\n return transformed_voxel_data\n HFlipTransform.register_type(\"voxel\", func)\n\n # ...\n transform = HFlipTransform(...)\n transform.apply_voxel(voxel_data) # func will be called\n \"\"\"\n assert callable(\n func\n ), \"You can only register a callable to a Transform. Got {} instead.\".format(\n func)\n argspec = inspect.getfullargspec(func)\n assert len(argspec.args) == 2, (\n \"You can only register a function that takes two positional \"\n \"arguments to a Transform! Got a function with spec {}\".format(\n str(argspec)))\n setattr(cls, \"apply_\" + data_type, func)\n\n\n_T = TypeVar(\"_T\")\n\n\nclass ComposeTransform(object):\n \"\"\"\n Composes several transforms together.\n \"\"\"\n\n def __init__(self, tfms):\n \"\"\"\n Args:\n transforms (list[Transform]): list of transforms to compose.\n \"\"\"\n super().__init__()\n self.transforms = tfms\n\n def __eq__(self, other):\n if not isinstance(other, ComposeTransform):\n return False\n return self.transforms == other.transforms\n\n def __call__(self, img, annotations=None, **kwargs):\n for tfm in self.transforms:\n img, annotations = tfm(img, annotations, **kwargs)\n return img, annotations\n\n def __repr__(self):\n return \"\".join([tfm for tfm in self.transforms])\n\n\nclass TorchTransform(Transform):\n \"\"\"\n Convert a transform from torchvision into cvpods-fashion.\n \"\"\"\n def __init__(self, tfm):\n super().__init__()\n self.tfm = tfm\n\n def apply_image(self, img: np.ndarray) -> np.ndarray:\n pil_image = Image.fromarray(img)\n return np.array(self.tfm(pil_image))\n\n def apply_coords(self, coords: np.ndarray) -> np.ndarray:\n return coords\n\n\nclass PILColorTransform(Transform):\n \"\"\"\n Generic wrapper for PIL Photometric image transforms,\n which affect the color space and not the coordinate\n space of the image\n \"\"\"\n\n def __init__(self, trm):\n \"\"\"\n Args:\n trm (Callable): operation to be applied to the image,\n which takes in a PIL Image and returns a transformed\n PIL Image.\n For reference on possible operations see:\n - https://pillow.readthedocs.io/en/stable/\n \"\"\"\n if not callable(trm):\n raise ValueError(\"trm parameter should be callable\")\n super().__init__()\n self._set_attributes(locals())\n\n def apply_image(self, img):\n img = Image.fromarray(img)\n return np.asarray(self.trm(img))\n\n def apply_coords(self, coords: np.ndarray) -> np.ndarray:\n return coords\n\n\n# TODO: Deprecated\n# pyre-ignore-all-errors\nclass TransformList:\n \"\"\"\n Maintain a list of transform operations which will be applied in sequence.\n Attributes:\n transforms (list[Transform])\n \"\"\"\n def __init__(self, transforms: list):\n \"\"\"\n Args:\n transforms (list[Transform]): list of transforms to perform.\n \"\"\"\n super().__init__()\n for t in transforms:\n assert isinstance(t, Transform), t\n self.transforms = transforms\n\n def _apply(self, x: _T, meth: str) -> _T:\n \"\"\"\n Apply the transforms on the input.\n Args:\n x: input to apply the transform operations.\n meth (str): meth.\n Returns:\n x: after apply the transformation.\n \"\"\"\n for t in self.transforms:\n x = getattr(t, meth)(x)\n return x\n\n def __getattr__(self, name: str):\n \"\"\"\n Args:\n name (str): name of the attribute.\n \"\"\"\n if name.startswith(\"apply_\"):\n return lambda x: self._apply(x, name)\n raise AttributeError(\n \"TransformList object has no attribute {}\".format(name))\n\n def __add__(self, other: \"TransformList\") -> \"TransformList\":\n \"\"\"\n Args:\n other (TransformList): transformation to add.\n Returns:\n TransformList: list of transforms.\n \"\"\"\n others = (other.transforms\n if isinstance(other, TransformList) else [other])\n return TransformList(self.transforms + others)\n\n def __iadd__(self, other: \"TransformList\") -> \"TransformList\":\n \"\"\"\n Args:\n other (TransformList): transformation to add.\n Returns:\n TransformList: list of transforms.\n \"\"\"\n others = (other.transforms\n if isinstance(other, TransformList) else [other])\n self.transforms.extend(others)\n return self\n\n def __radd__(self, other: \"TransformList\") -> \"TransformList\":\n \"\"\"\n Args:\n other (TransformList): transformation to add.\n Returns:\n TransformList: list of transforms.\n \"\"\"\n others = (other.transforms\n if isinstance(other, TransformList) else [other])\n return TransformList(others + self.transforms)\n\n def insert(self, idx: int, other: \"TransformList\") -> \"TransformList\":\n \"\"\"\n Args:\n idx (int): insert position.\n other (TransformList): transformation to insert.\n Returns:\n None\n \"\"\"\n assert idx in range(len(self.transforms))\n others = (other.transforms\n if isinstance(other, TransformList) else [other])\n self.transforms = self.transforms[:idx] + others + self.transforms[idx:]\n\n\nclass DistortTransform(Transform):\n \"\"\"\n Distort image w.r.t hue, saturation and exposure.\n \"\"\"\n\n def __init__(self, hue, saturation, exposure, image_format):\n super().__init__()\n self._set_attributes(locals())\n self.cvt_code = {\n \"RGB\": (cv2.COLOR_RGB2HSV, cv2.COLOR_HSV2RGB),\n \"BGR\": (cv2.COLOR_BGR2HSV, cv2.COLOR_HSV2BGR),\n }[image_format]\n if saturation > 1.0:\n saturation /= 255. # in range [0, 1]\n\n def apply_image(self, img: np.ndarray) -> np.ndarray:\n \"\"\"\n Args:\n img (ndarray): of shape HxW, HxWxC, or NxHxWxC. The array can be\n of type uint8 in range [0, 255], or floating point in range\n [0, 1] or [0, 255].\n\n Returns:\n ndarray: the distorted image(s).\n \"\"\"\n dhue = np.random.uniform(low=-self.hue, high=self.hue)\n dsat = self._rand_scale(self.saturation)\n dexp = self._rand_scale(self.exposure)\n\n dtype = img.dtype\n img = cv2.cvtColor(img, self.cvt_code[0])\n img = np.asarray(img, dtype=np.float32) / 255.\n img[:, :, 1] *= dsat\n img[:, :, 2] *= dexp\n H = img[:, :, 0] + dhue\n\n if dhue > 0:\n H[H > 1.0] -= 1.0\n else:\n H[H < 0.0] += 1.0\n\n img[:, :, 0] = H\n img = (img * 255).clip(0, 255).astype(np.uint8)\n img = cv2.cvtColor(img, self.cvt_code[1])\n img = np.asarray(img, dtype=dtype)\n\n return img\n\n def apply_coords(self, coords: np.ndarray) -> np.ndarray:\n return coords\n\n def _rand_scale(self, upper_bound):\n \"\"\"\n Calculate random scaling factor.\n\n Args:\n upper_bound (float): range of the random scale.\n Returns:\n random scaling factor (float) whose range is\n from 1 / s to s .\n \"\"\"\n scale = np.random.uniform(low=1, high=upper_bound)\n if np.random.rand() > 0.5:\n return scale\n return 1 / scale\n\n def apply_segmentation(self, segmentation: np.ndarray) -> np.ndarray:\n return segmentation\n\n\nclass AffineTransform(Transform):\n \"\"\"\n Augmentation from CenterNet\n \"\"\"\n def __init__(self, src, dst, output_size, pad_value=[0, 0, 0]):\n \"\"\"\n output_size:(w, h)\n \"\"\"\n super().__init__()\n affine = cv2.getAffineTransform(np.float32(src), np.float32(dst))\n self._set_attributes(locals())\n\n def apply_image(self, img: np.ndarray) -> np.ndarray:\n \"\"\"\n Apply AffineTransform for the image(s).\n\n Args:\n img (ndarray): of shape HxW, HxWxC, or NxHxWxC. The array can be\n of type uint8 in range [0, 255], or floating point in range\n [0, 1] or [0, 255].\n Returns:\n ndarray: the image(s) after applying affine transform.\n \"\"\"\n return cv2.warpAffine(img,\n self.affine,\n self.output_size,\n flags=cv2.INTER_LINEAR,\n borderValue=self.pad_value)\n\n def apply_coords(self, coords: np.ndarray) -> np.ndarray:\n \"\"\"\n Affine the coordinates.\n\n Args:\n coords (ndarray): floating point array of shape Nx2. Each row is\n (x, y).\n Returns:\n ndarray: the flipped coordinates.\n\n Note:\n The inputs are floating point coordinates, not pixel indices.\n Therefore they are flipped by `(W - x, H - y)`, not\n `(W - 1 - x, H 1 - y)`.\n \"\"\"\n # aug_coord (N, 3) shape, self.affine (2, 3) shape\n w, h = self.output_size\n aug_coords = np.column_stack((coords, np.ones(coords.shape[0])))\n coords = np.dot(aug_coords, self.affine.T)\n coords[..., 0] = np.clip(coords[..., 0], 0, w - 1)\n coords[..., 1] = np.clip(coords[..., 1], 0, h - 1)\n return coords\n\n\nclass RotationTransform(Transform):\n \"\"\"\n This method returns a copy of this image, rotated the given\n number of degrees counter clockwise around its center.\n \"\"\"\n\n def __init__(self, h, w, angle, expand=True, center=None, interp=None):\n \"\"\"\n Args:\n h, w (int): original image size\n angle (float): degrees for rotation\n expand (bool): choose if the image should be resized to fit the whole\n rotated image (default), or simply cropped\n center (tuple (width, height)): coordinates of the rotation center\n if left to None, the center will be fit to the center of each image\n center has no effect if expand=True because it only affects shifting\n interp: cv2 interpolation method, default cv2.INTER_LINEAR\n \"\"\"\n super().__init__()\n image_center = np.array((w / 2, h / 2))\n if center is None:\n center = image_center\n if interp is None:\n interp = cv2.INTER_LINEAR\n abs_cos, abs_sin = (abs(np.cos(np.deg2rad(angle))), abs(np.sin(np.deg2rad(angle))))\n if expand:\n # find the new width and height bounds\n bound_w, bound_h = np.rint(\n [h * abs_sin + w * abs_cos, h * abs_cos + w * abs_sin]\n ).astype(int)\n else:\n bound_w, bound_h = w, h\n\n self._set_attributes(locals())\n self.rm_coords = self.create_rotation_matrix()\n # Needed because of this problem https://github.com/opencv/opencv/issues/11784\n self.rm_image = self.create_rotation_matrix(offset=-0.5)\n\n def apply_image(self, img, interp=None):\n \"\"\"\n img should be a numpy array, formatted as Height * Width * Nchannels\n \"\"\"\n if len(img) == 0 or self.angle % 360 == 0:\n return img\n assert img.shape[:2] == (self.h, self.w)\n interp = interp if interp is not None else self.interp\n return cv2.warpAffine(img, self.rm_image, (self.bound_w, self.bound_h), flags=interp)\n\n def apply_coords(self, coords):\n \"\"\"\n coords should be a N * 2 array-like, containing N couples of (x, y) points\n \"\"\"\n coords = np.asarray(coords, dtype=float)\n if len(coords) == 0 or self.angle % 360 == 0:\n return coords\n return cv2.transform(coords[:, np.newaxis, :], self.rm_coords)[:, 0, :]\n\n def apply_segmentation(self, segmentation):\n segmentation = self.apply_image(segmentation, interp=cv2.INTER_NEAREST)\n return segmentation\n\n def create_rotation_matrix(self, offset=0):\n center = (self.center[0] + offset, self.center[1] + offset)\n rm = cv2.getRotationMatrix2D(tuple(center), self.angle, 1)\n if self.expand:\n # Find the coordinates of the center of rotation in the new image\n # The only point for which we know the future coordinates is the center of the image\n rot_im_center = cv2.transform(self.image_center[None, None, :] + offset, rm)[0, 0, :]\n new_center = np.array([self.bound_w / 2, self.bound_h / 2]) + offset - rot_im_center\n # shift the rotation center to the new coordinates\n rm[:, 2] += new_center\n return rm\n\n def inverse(self):\n \"\"\"\n The inverse is to rotate it back with expand, and crop to get the original shape.\n \"\"\"\n if not self.expand: # Not possible to inverse if a part of the image is lost\n raise NotImplementedError()\n rotation = RotationTransform(\n self.bound_h, self.bound_w, -self.angle, True, None, self.interp\n )\n crop = CropTransform(\n (rotation.bound_w - self.w) // 2, (rotation.bound_h - self.h) // 2, self.w, self.h\n )\n return TransformList([rotation, crop])\n\n\nclass HFlipTransform(Transform):\n \"\"\"\n Perform horizontal flip.\n \"\"\"\n\n def __init__(self, width: int):\n super().__init__()\n self._set_attributes(locals())\n\n def apply_image(self, img: np.ndarray) -> np.ndarray:\n \"\"\"\n Flip the image(s).\n\n Args:\n img (ndarray): of shape HxW, HxWxC, or NxHxWxC. The array can be\n of type uint8 in range [0, 255], or floating point in range\n [0, 1] or [0, 255].\n\n Returns:\n ndarray: the flipped image(s).\n \"\"\"\n tensor = torch.from_numpy(np.ascontiguousarray(img).copy())\n if len(tensor.shape) == 2:\n # For dimension of HxW.\n tensor = tensor.flip((-1))\n elif len(tensor.shape) > 2:\n # For dimension of HxWxC, NxHxWxC.\n tensor = tensor.flip((-2))\n return tensor.numpy()\n\n def apply_coords(self, coords: np.ndarray) -> np.ndarray:\n \"\"\"\n Flip the coordinates.\n\n Args:\n coords (ndarray): floating point array of shape Nx2. Each row is (x, y).\n\n Returns:\n ndarray: the flipped coordinates.\n\n Note:\n The inputs are floating point coordinates, not pixel indices.\n Therefore they are flipped by `(W - x, H - y)`, not\n `(W - 1 - x, H 1 - y)`.\n \"\"\"\n coords[:, 0] = self.width - coords[:, 0]\n return coords\n\n\nclass VFlipTransform(Transform):\n \"\"\"\n Perform vertical flip.\n \"\"\"\n\n def __init__(self, height: int):\n super().__init__()\n self._set_attributes(locals())\n\n def apply_image(self, img: np.ndarray) -> np.ndarray:\n \"\"\"\n Flip the image(s).\n\n Args:\n img (ndarray): of shape HxW, HxWxC, or NxHxWxC. The array can be\n of type uint8 in range [0, 255], or floating point in range\n [0, 1] or [0, 255].\n\n Returns:\n ndarray: the flipped image(s).\n \"\"\"\n tensor = torch.from_numpy(np.ascontiguousarray(img).copy())\n if len(tensor.shape) == 2:\n # For dimension of HxW.\n tensor = tensor.flip((-2))\n elif len(tensor.shape) > 2:\n # For dimension of HxWxC, NxHxWxC.\n tensor = tensor.flip((-3))\n return tensor.numpy()\n\n def apply_coords(self, coords: np.ndarray) -> np.ndarray:\n \"\"\"\n Flip the coordinates.\n\n Args:\n coords (ndarray): floating point array of shape Nx2. Each row is (x, y).\n\n Returns:\n ndarray: the flipped coordinates.\n\n Note:\n The inputs are floating point coordinates, not pixel indices.\n Therefore they are flipped by `(W - x, H - y)`, not\n `(W - 1 - x, H - 1 - y)`.\n \"\"\"\n coords[:, 1] = self.height - coords[:, 1]\n return coords\n\n\nclass NoOpTransform(Transform):\n \"\"\"\n A transform that does nothing.\n \"\"\"\n def __init__(self):\n super().__init__()\n\n def apply_image(self, img: np.ndarray) -> np.ndarray:\n return img\n\n def apply_coords(self, coords: np.ndarray) -> np.ndarray:\n return coords\n\n\nclass GaussianBlurTransform(Transform):\n \"\"\"\n GaussianBlur using PIL.ImageFilter.GaussianBlur\n \"\"\"\n def __init__(self, sigma, p=1.0):\n \"\"\"\n Args:\n sigma (List(float)): sigma of gaussian\n p (float): probability of perform this augmentation\n \"\"\"\n super().__init__()\n self._set_attributes(locals())\n\n def apply_image(self, img: np.ndarray) -> np.ndarray:\n if np.random.random() < self.p:\n sigma = random.uniform(self.sigma[0], self.sigma[1])\n img = Image.fromarray(img).filter(ImageFilter.GaussianBlur(radius=sigma))\n return np.array(img)\n\n def apply_coords(self, coords: np.ndarray) -> np.ndarray:\n return coords\n\n\nclass SolarizationTransform(Transform):\n def __init__(self, thresh=128, p=0.5):\n super().__init__()\n self.thresh = thresh\n self.p = p\n\n def apply_image(self, img: np.ndarray) -> np.ndarray:\n if np.random.random() < self.p:\n return np.array(ImageOps.solarize(Image.fromarray(img), self.thresh))\n else:\n return img\n\n def apply_coords(self, coords: np.ndarray) -> np.ndarray:\n return coords\n\n\nclass GaussianBlurConvTransform(Transform):\n def __init__(self, kernel_size, p=1.0):\n super().__init__()\n self._set_attributes(locals())\n radias = kernel_size // 2\n kernel_size = radias * 2 + 1\n self.blur_h = torch.nn.Conv2d(3, 3, kernel_size=(kernel_size, 1),\n stride=1, padding=0, bias=False, groups=3)\n self.blur_v = torch.nn.Conv2d(3, 3, kernel_size=(1, kernel_size),\n stride=1, padding=0, bias=False, groups=3)\n self.k = kernel_size\n self.r = radias\n\n self.blur = torch.nn.Sequential(\n torch.nn.ReflectionPad2d(radias),\n self.blur_h,\n self.blur_v\n )\n\n self.pil_to_tensor = transforms.ToTensor()\n self.tensor_to_pil = transforms.ToPILImage()\n\n def apply_image(self, img: np.ndarray) -> np.ndarray:\n if np.random.random() < self.p:\n img = self.pil_to_tensor(Image.fromarray(img)).unsqueeze(0)\n\n sigma = np.random.uniform(0.1, 2.0)\n x = np.arange(-self.r, self.r + 1)\n x = np.exp(-np.power(x, 2) / (2 * sigma * sigma))\n x = x / x.sum()\n x = torch.from_numpy(x).view(1, -1).repeat(3, 1)\n\n self.blur_h.weight.data.copy_(x.view(3, 1, self.k, 1))\n self.blur_v.weight.data.copy_(x.view(3, 1, 1, self.k))\n\n with torch.no_grad():\n img = self.blur(img)\n img = img.squeeze()\n\n img = np.array(self.tensor_to_pil(img))\n return img\n\n def apply_coords(self, coords: np.ndarray) -> np.ndarray:\n return coords\n\n\nclass LabSpaceTransform(Transform):\n \"\"\"\n Convert image from RGB into Lab color space\n \"\"\"\n def __init__(self):\n super().__init__()\n self._set_attributes(locals())\n\n def apply_image(self, img: np.ndarray) -> np.ndarray:\n assert len(img.shape) == 3, 'Image should have dim H x W x 3'\n assert img.shape[2] == 3, 'Image should have dim H x W x 3'\n img_lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)\n img_lab = img_lab.astype(np.float32)\n img_lab[:, :, 0] = (img_lab[:, :, 0] * (100.0 / 255.0)) - 50.0\n img_lab[:, :, 1:] = img_lab[:, :, 1:] - 128.0\n return img_lab\n\n def apply_coords(self, coords: np.ndarray) -> np.ndarray:\n return coords\n\n\nclass PadTransform(Transform):\n \"\"\"\n Pad image with `pad_value` to the specified `target_h` and `target_w`.\n\n Adds `top` rows of `pad_value` on top, `left` columns of `pad_value` on the left,\n and then pads the image on the bottom and right with `pad_value` until it has\n dimensions `target_h`, `target_w`.\n\n This op does nothing if `top` and `left` is zero and the image already has size\n `target_h` by `target_w`.\n \"\"\"\n\n def __init__(self,\n top: int,\n left: int,\n target_h: int,\n target_w: int,\n pad_value=0,\n seg_value=255,\n ):\n \"\"\"\n Args:\n top (int): number of rows of `pad_value` to add on top.\n left (int): number of columns of `pad_value` to add on the left.\n target_h (int): height of output image.\n target_w (int): width of output image.\n pad_value (int): the value used to pad the image.\n seg_value (int): the value used to pad the semantic seg annotaions.\n \"\"\"\n super().__init__()\n self._set_attributes(locals())\n\n def apply_image(self, img: np.ndarray, pad_value=None) -> np.ndarray:\n if pad_value is None:\n pad_value = self.pad_value\n\n if len(img.shape) == 2: # semantic segmentation mask\n shape = (self.target_h, self.target_w)\n else:\n shape = (self.target_h, self.target_w, 3)\n\n pad_img = np.full(shape=shape, fill_value=pad_value).astype(img.dtype)\n\n rest_h = self.target_h - self.top\n rest_w = self.target_w - self.left\n\n img_h, img_w = img.shape[:2]\n paste_h, paste_w = min(rest_h, img_h), min(rest_w, img_w)\n pad_img[self.top:self.top + paste_h,\n self.left:self.left + paste_w] = img[:paste_h, :paste_w]\n return pad_img\n\n def apply_coords(self, coords: np.ndarray) -> np.ndarray:\n coords[:, 0] = coords[:, 0] + self.left\n coords[:, 1] = coords[:, 1] + self.top\n return coords\n\n def apply_segmentation(self, segmentation: np.ndarray) -> np.ndarray:\n \"\"\"\n Apply pad transform on the full-image segmentation.\n Args:\n segmentation (ndarray): of shape HxW. The array should have integer\n or bool dtype.\n Returns:\n ndarray: padded segmentation.\n \"\"\"\n segmentation = self.apply_image(segmentation, pad_value=self.seg_value)\n return segmentation\n\n\nclass FiveCropTransform(Transform):\n \"\"\"\n Generate five crops from a given image.\n The order of the crops are:\n 0: ceneter\n 1: top left\n 2: top right\n 3: bottom left\n 4: bottom right\n \"\"\"\n def __init__(self, size, rand_in=[0, 1, 2, 3, 4]):\n \"\"\"\n Args:\n size (int): crop size.\n rand_in (List[int]): indexes to be random select.\n \"\"\"\n super().__init__()\n self._set_attributes(locals())\n self.center_crop = transforms.CenterCrop(self.size)\n\n def apply_image(self, image: np.ndarray) -> np.ndarray:\n height = image.shape[0]\n width = image.shape[1]\n\n idx = np.random.choice(self.rand_in)\n\n if idx == 0:\n # given an image, crop the 4 corners and center of given size\n return np.array(self.center_crop(Image.fromarray(image)))\n elif idx == 1:\n # crop the top left corner:\n return image[0:self.size, 0:self.size, :]\n elif idx == 2:\n # crop the top right corner\n return image[0:self.size, width - self.size:width, :]\n elif idx == 3:\n # crop bottom left corner\n return image[height - self.size:height, 0:self.size, :]\n elif idx == 4 or idx == -4:\n # crop bottom right corner\n return image[height - self.size:height, width - self.size:width, :]\n else:\n raise NotImplementedError\n\n def apply_coords(self, coords: np.ndarray) -> np.ndarray:\n return coords\n\n\nclass JigsawCropTransform(Transform):\n \"\"\"\n Typical JigsawCrop Transform.\n First resize image into img_size, then crop out n_grid x n_grid patches.\n \"\"\"\n def __init__(self, n_grid=3, img_size=255, crop_size=64):\n \"\"\"\n Args:\n n_grid (int): crop image into n_grid x n_grid crops.\n img_size (int): image scale size.\n crop_size (int): crop size.\n \"\"\"\n super().__init__()\n self._set_attributes(locals())\n self.grid_size = int(img_size / 3)\n self.side = self.grid_size - self.crop_size\n\n yy, xx = np.meshgrid(np.arange(n_grid), np.arange(n_grid))\n self.yy = np.reshape(yy * self.grid_size, (n_grid * n_grid,))\n self.xx = np.reshape(xx * self.grid_size, (n_grid * n_grid,))\n\n def apply_image(self, img: np.ndarray) -> np.ndarray:\n r_x = np.random.randint(0, self.side + 1, self.n_grid * self.n_grid)\n r_y = np.random.randint(0, self.side + 1, self.n_grid * self.n_grid)\n img = np.asarray(img, np.uint8)\n crops = []\n for i in range(self.n_grid * self.n_grid):\n crops.append(img[self.xx[i] + r_x[i]: self.xx[i] + r_x[i] + self.crop_size,\n self.yy[i] + r_y[i]: self.yy[i] + r_y[i] + self.crop_size, :])\n crops = [Image.fromarray(crop) for crop in crops]\n return crops\n\n def apply_coords(self, coords: np.ndarray) -> np.ndarray:\n return coords\n\n\nclass LightningTransform(Transform):\n \"\"\"\n Lightning Transform, usually used in imagenet classification.\n\n .. code-block:: python\n tfm = LightningTransform(\n alpha_std=0.1,\n eig_val=np.array([[0.2175, 0.0188, 0.0045]]),\n eig_vec=np.array([\n [-0.5675, 0.7192, 0.4009],\n [-0.5808, -0.0045, -0.8140],\n [-0.5836, -0.6948, 0.4203]\n ]),\n )\n \"\"\"\n def __init__(self, alpha_std, eig_val, eig_vec):\n super().__init__()\n self._set_attributes(locals())\n\n def apply_image(self, img: np.ndarray) -> np.ndarray:\n \"\"\"Performs AlexNet-style PCA jitter (CHW format).\"\"\"\n if self.alpha_std == 0:\n return img\n alpha = np.random.normal(0, self.alpha_std, size=(1, 3))\n rgb = np.sum(\n self.eig_vec * np.repeat(alpha, 3, axis=0)\n * np.repeat(self.eig_val, 3, axis=0), axis=1\n )\n img = img.transpose((2, 0, 1)) # HWC -> CHW\n for i in range(img.shape[0]):\n img[i] = img[i] + rgb[2 - i]\n\n return img.transpose((1, 2, 0))\n\n def apply_coords(self, coords: np.ndarray) -> np.ndarray:\n return coords\n\n\nclass ScaleTransform(Transform):\n \"\"\"\n Resize the image to a target size.\n \"\"\"\n\n def __init__(self,\n h: int,\n w: int,\n new_h: int,\n new_w: int,\n interp: str = \"BILINEAR\"):\n \"\"\"\n Args:\n h, w (int): original image size.\n new_h, new_w (int): new image size.\n interp (str): the interpolation method. Options includes:\n * \"NEAREST\"\n * \"BILINEAR\"\n * \"BICUBIC\"\n * \"LANCZOS\"\n * \"HAMMING\"\n * \"BOX\"\n \"\"\"\n super().__init__()\n self._set_attributes(locals())\n _str_to_pil_interpolation = {\n \"NEAREST\": Image.NEAREST,\n \"BILINEAR\": Image.BILINEAR,\n \"BICUBIC\": Image.BICUBIC,\n \"LANCZOS\": Image.LANCZOS,\n \"HAMMING\": Image.HAMMING,\n \"BOX\": Image.BOX,\n }\n assert (interp in _str_to_pil_interpolation.keys(\n )), \"This interpolation mode ({}) is not currently supported!\".format(\n interp)\n self.interp = _str_to_pil_interpolation[interp]\n\n def apply_image(self, img: np.ndarray, interp: str = None) -> np.ndarray:\n \"\"\"\n Resize the image(s).\n\n Args:\n img (ndarray): of shape NxHxWxC, or HxWxC or HxW. The array can be\n of type uint8 in range [0, 255], or floating point in range\n [0, 1] or [0, 255].\n\n Returns:\n ndarray: resized image(s).\n \"\"\"\n # Method 1: second fastest\n # img = cv2.resize(img, (self.new_w, self.new_h), interpolation=cv2.INTER_LINEAR)\n\n # Method 2: fastest\n pil_image = Image.fromarray(img)\n interp_method = interp if interp is not None else self.interp\n pil_image = pil_image.resize((self.new_w, self.new_h), interp_method)\n img = np.asarray(pil_image)\n\n return img\n\n def apply_coords(self, coords: np.ndarray) -> np.ndarray:\n \"\"\"\n Compute the coordinates after resize.\n\n Args:\n coords (ndarray): floating point array of shape Nx2. Each row is\n (x, y).\n Returns:\n ndarray: resized coordinates.\n \"\"\"\n coords[:, 0] = coords[:, 0] * (self.new_w * 1.0 / self.w)\n coords[:, 1] = coords[:, 1] * (self.new_h * 1.0 / self.h)\n return coords\n\n def apply_segmentation(self, segmentation: np.ndarray) -> np.ndarray:\n \"\"\"\n Apply resize on the full-image segmentation.\n\n Args:\n segmentation (ndarray): of shape HxW. The array should have integer\n or bool dtype.\n Returns:\n ndarray: resized segmentation.\n \"\"\"\n segmentation = self.apply_image(segmentation, interp=Image.NEAREST)\n return segmentation\n\n\nclass GridSampleTransform(Transform):\n def __init__(self, grid: np.ndarray, interp: str):\n \"\"\"\n Args:\n grid (ndarray): grid has x and y input pixel locations which are\n used to compute output. Grid has values in the range of [-1, 1],\n which is normalized by the input height and width. The dimension\n is `N x H x W x 2`.\n interp (str): interpolation methods. Options include `nearest` and\n `bilinear`.\n \"\"\"\n super().__init__()\n self._set_attributes(locals())\n\n def apply_image(self, img: np.ndarray, interp: str = None) -> np.ndarray:\n \"\"\"\n Apply grid sampling on the image(s).\n\n Args:\n img (ndarray): of shape NxHxWxC, or HxWxC or HxW. The array can be\n of type uint8 in range [0, 255], or floating point in range\n [0, 1] or [0, 255].\n interp (str): interpolation methods. Options include `nearest` and\n `bilinear`.\n Returns:\n ndarray: grid sampled image(s).\n \"\"\"\n interp_method = interp if interp is not None else self.interp\n float_tensor = torch.nn.functional.grid_sample(\n to_float_tensor(img), # NxHxWxC -> NxCxHxW.\n torch.from_numpy(self.grid),\n mode=interp_method,\n padding_mode=\"border\",\n align_corners=False,\n )\n return to_numpy(float_tensor, img.shape, img.dtype)\n\n def apply_coords(self, coords: np.ndarray):\n \"\"\"\n Not supported.\n \"\"\"\n raise NotImplementedError()\n\n def apply_segmentation(self, segmentation: np.ndarray) -> np.ndarray:\n \"\"\"\n Apply grid sampling on the full-image segmentation.\n\n Args:\n segmentation (ndarray): of shape HxW. The array should have integer\n or bool dtype.\n Returns:\n ndarray: grid sampled segmentation.\n \"\"\"\n segmentation = self.apply_image(segmentation, interp=Image.NEAREST)\n return segmentation\n\n\nclass IoUCropTransform(Transform):\n \"\"\"\n Perform crop operations on images.\n\n This crop operation will checks whether the center of each instance's bbox\n is in the cropped image.\n \"\"\"\n\n def __init__(self, x0: int, y0: int, w: int, h: int):\n \"\"\"\n Args:\n x0, y0, w, h (int): crop the image(s) by img[y0:y0+h, x0:x0+w].\n \"\"\"\n super().__init__()\n self._set_attributes(locals())\n\n def apply_image(self, img: np.ndarray) -> np.ndarray:\n \"\"\"\n Crop the image(s).\n\n Args:\n img (ndarray): of shape NxHxWxC, or HxWxC or HxW. The array can be\n of type uint8 in range [0, 255], or floating point in range\n [0, 1] or [0, 255].\n\n Returns:\n ndarray: cropped image(s).\n \"\"\"\n if len(img.shape) <= 3:\n return img[self.y0:self.y0 + self.h, self.x0:self.x0 + self.w]\n else:\n return img[..., self.y0:self.y0 + self.h,\n self.x0:self.x0 + self.w, :]\n\n def apply_box(self, box: np.ndarray) -> np.ndarray:\n \"\"\"\n Apply the transform on an axis-aligned box.\n By default will transform the corner points and use their\n minimum/maximum to create a new axis-aligned box.\n Note that this default may change the size of your box, e.g. in\n rotations.\n\n Args:\n box (ndarray): Nx4 floating point array of XYXY format in absolute\n coordinates.\n\n Returns:\n ndarray: box after apply the transformation.\n\n Note:\n The coordinates are not pixel indices. Coordinates on an image of\n shape (H, W) are in range [0, W] or [0, H].\n \"\"\"\n # Indexes of converting (x0, y0, x1, y1) box into 4 coordinates of\n # ([x0, y0], [x1, y0], [x0, y1], [x1, y1]).\n box = np.array(box).reshape(-1, 4)\n center = (box[:, :2] + box[:, 2:]) / 2\n mask = ((center[:, 0] > self.x0) * (center[:, 0] < self.x0 + self.w)\n * (center[:, 1] > self.y0) * (center[:, 1] < self.y0 + self.h))\n if not mask.any():\n return np.zeros_like(box)\n\n tl = np.array([self.x0, self.y0])\n box[:, :2] = np.maximum(box[:, :2], tl)\n box[:, :2] -= tl\n\n box[:, 2:] = np.minimum(box[:, 2:],\n np.array([self.x0 + self.w, self.y0 + self.h]))\n box[:, 2:] -= tl\n\n return box\n\n def apply_coords(self, coords: np.ndarray) -> np.ndarray:\n \"\"\"\n Apply crop transform on coordinates.\n\n Args:\n coords (ndarray): floating point array of shape Nx2. Each row is (x, y).\n\n Returns:\n ndarray: cropped coordinates.\n \"\"\"\n coords[:, 0] -= self.x0\n coords[:, 1] -= self.y0\n return coords\n\n def apply_polygons(self, polygons: list) -> list:\n \"\"\"\n Apply crop transform on a list of polygons, each represented by a Nx2 array.\n It will crop the polygon with the box, therefore the number of points in the\n polygon might change.\n\n Args:\n polygon (list[ndarray]): each is a Nx2 floating point array of\n (x, y) format in absolute coordinates.\n\n Returns:\n ndarray: cropped polygons.\n \"\"\"\n import shapely.geometry as geometry\n\n # Create a window that will be used to crop\n crop_box = geometry.box(self.x0, self.y0, self.x0 + self.w,\n self.y0 + self.h).buffer(0.0)\n\n cropped_polygons = []\n\n for polygon in polygons:\n polygon = geometry.Polygon(polygon).buffer(0.0)\n # polygon must be valid to perform intersection.\n assert polygon.is_valid, polygon\n cropped = polygon.intersection(crop_box)\n if cropped.is_empty:\n continue\n if not isinstance(cropped,\n geometry.collection.BaseMultipartGeometry):\n cropped = [cropped]\n # one polygon may be cropped to multiple ones\n for poly in cropped:\n # It could produce lower dimensional objects like lines or\n # points, which we want to ignore\n if not isinstance(poly, geometry.Polygon) or not poly.is_valid:\n continue\n coords = np.asarray(poly.exterior.coords)\n # NOTE This process will produce an extra identical vertex at\n # the end. So we remove it. This is tested by\n # `tests/test_data_transform.py`\n cropped_polygons.append(coords[:-1])\n return [self.apply_coords(p) for p in cropped_polygons]\n\n\nclass CropTransform(Transform):\n \"\"\"\n Perform crop operations on images.\n \"\"\"\n\n def __init__(self, x0: int, y0: int, w: int, h: int):\n \"\"\"\n Args:\n x0, y0, w, h (int): crop the image(s) by img[y0:y0+h, x0:x0+w].\n \"\"\"\n super().__init__()\n self._set_attributes(locals())\n\n def apply_image(self, img: np.ndarray) -> np.ndarray:\n \"\"\"\n Crop the image(s).\n\n Args:\n img (ndarray): of shape NxHxWxC, or HxWxC or HxW. The array can be\n of type uint8 in range [0, 255], or floating point in range\n [0, 1] or [0, 255].\n\n Returns:\n ndarray: cropped image(s).\n \"\"\"\n if len(img.shape) <= 3:\n return img[self.y0:self.y0 + self.h, self.x0:self.x0 + self.w]\n else:\n return img[..., self.y0:self.y0 + self.h,\n self.x0:self.x0 + self.w, :]\n\n def apply_coords(self, coords: np.ndarray) -> np.ndarray:\n \"\"\"\n Apply crop transform on coordinates.\n\n Args:\n coords (ndarray): floating point array of shape Nx2. Each row is (x, y).\n\n Returns:\n ndarray: cropped coordinates.\n \"\"\"\n coords[:, 0] -= self.x0\n coords[:, 1] -= self.y0\n return coords\n\n def apply_polygons(self, polygons: list) -> list:\n \"\"\"\n Apply crop transform on a list of polygons, each represented by a Nx2 array.\n It will crop the polygon with the box, therefore the number of points in the\n polygon might change.\n\n Args:\n polygon (list[ndarray]): each is a Nx2 floating point array of\n (x, y) format in absolute coordinates.\n\n Returns:\n ndarray: cropped polygons.\n \"\"\"\n import shapely.geometry as geometry\n\n # Create a window that will be used to crop\n crop_box = geometry.box(self.x0, self.y0, self.x0 + self.w,\n self.y0 + self.h).buffer(0.0)\n\n cropped_polygons = []\n\n for polygon in polygons:\n polygon = geometry.Polygon(polygon).buffer(0.0)\n # polygon must be valid to perform intersection.\n assert polygon.is_valid, polygon\n cropped = polygon.intersection(crop_box)\n if cropped.is_empty:\n continue\n if not isinstance(cropped,\n geometry.collection.BaseMultipartGeometry):\n cropped = [cropped]\n # one polygon may be cropped to multiple ones\n for poly in cropped:\n # It could produce lower dimensional objects like lines or\n # points, which we want to ignore\n if not isinstance(poly, geometry.Polygon) or not poly.is_valid:\n continue\n coords = np.asarray(poly.exterior.coords)\n # NOTE This process will produce an extra identical vertex at\n # the end. So we remove it. This is tested by\n # `tests/test_data_transform.py`\n cropped_polygons.append(coords[:-1])\n return [self.apply_coords(p) for p in cropped_polygons]\n\n\nclass CropPadTransform(Transform):\n def __init__(self,\n x0: int,\n y0: int,\n w: int,\n h: int,\n new_w: int,\n new_h: int,\n img_value=None,\n seg_value=None):\n super().__init__()\n self._set_attributes(locals())\n self.crop_trans = CropTransform(x0, y0, w, h)\n pad_top_offset = self.get_pad_offset(h, new_h)\n pad_left_offset = self.get_pad_offset(w, new_w)\n self.pad_trans = PadTransform(\n pad_top_offset, pad_left_offset, new_h, new_w, img_value, seg_value)\n\n def get_pad_offset(self, ori: int, tar: int):\n pad_length = max(tar - ori, 0)\n pad_offset = pad_length // 2\n return pad_offset\n\n def apply_image(self, img: np.ndarray) -> np.ndarray:\n \"\"\"\n Crop and Pad the image(s).\n Args:\n img (ndarray): of shape NxHxWxC, or HxWxC or HxW. The array can be\n of type uint8 in range [0, 255], or floating point in range\n [0, 1] or [0, 255].\n Returns:\n ndarray: cropped and padded image(s).\n \"\"\"\n img = self.crop_trans.apply_image(img)\n img = self.pad_trans.apply_image(img)\n return img\n\n def apply_coords(self, coords: np.ndarray) -> np.ndarray:\n \"\"\"\n Apply crop and pad transform on coordinates.\n Args:\n coords (ndarray): floating point array of shape Nx2. Each row is\n (x, y).\n Returns:\n ndarray: cropped and padded coordinates.\n \"\"\"\n coords = self.crop_trans.apply_coords(coords)\n coords = self.pad_trans.apply_coords(coords)\n return coords\n\n def apply_polygons(self, polygons: list) -> list:\n \"\"\"\n Apply crop and pad transform on a list of polygons, each represented by a Nx2 array.\n Args:\n polygon (list[ndarray]): each is a Nx2 floating point array of\n (x, y) format in absolute coordinates.\n Returns:\n ndarray: cropped and padded polygons.\n \"\"\"\n polygons = self.crop_trans.apply_polygons(polygons)\n polygons = self.pad_trans.apply_polygons(polygons)\n return polygons\n\n def apply_segmentation(self, segmentation: np.ndarray) -> np.ndarray:\n \"\"\"\n Apply crop and pad transform on the full-image segmentation.\n Args:\n segmentation (ndarray): of shape HxW. The array should have integer\n or bool dtype.\n Returns:\n ndarray: cropped and padded segmentation.\n \"\"\"\n segmentation = self.crop_trans.apply_segmentation(segmentation)\n segmentation = self.pad_trans.apply_segmentation(segmentation)\n return segmentation\n\n\nclass BlendTransform(Transform):\n \"\"\"\n Transforms pixel colors with PIL enhance functions.\n \"\"\"\n\n def __init__(self, src_image: np.ndarray, src_weight: float,\n dst_weight: float):\n \"\"\"\n Blends the input image (dst_image) with the src_image using formula:\n ``src_weight * src_image + dst_weight * dst_image``\n\n Args:\n src_image (ndarray): Input image is blended with this image\n src_weight (float): Blend weighting of src_image\n dst_weight (float): Blend weighting of dst_image\n \"\"\"\n super().__init__()\n self._set_attributes(locals())\n\n def apply_image(self, img: np.ndarray, interp: str = None) -> np.ndarray:\n \"\"\"\n Apply blend transform on the image(s).\n\n Args:\n img (ndarray): of shape NxHxWxC, or HxWxC or HxW. The array can be\n of type uint8 in range [0, 255], or floating point in range\n [0, 1] or [0, 255].\n interp (str): keep this option for consistency, perform blend would not\n require interpolation.\n Returns:\n ndarray: blended image(s).\n \"\"\"\n if img.dtype == np.uint8:\n img = img.astype(np.float32)\n img = self.src_weight * self.src_image + self.dst_weight * img\n return np.clip(img, 0, 255).astype(np.uint8)\n else:\n return self.src_weight * self.src_image + self.dst_weight * img\n\n def apply_coords(self, coords: np.ndarray) -> np.ndarray:\n \"\"\"\n Apply no transform on the coordinates.\n \"\"\"\n return coords\n\n def apply_segmentation(self, segmentation: np.ndarray) -> np.ndarray:\n \"\"\"\n Apply no transform on the full-image segmentation.\n \"\"\"\n return segmentation\n\n\nclass RandomSwapChannelsTransform(Transform):\n \"\"\"\n Randomly swap image channels.\n \"\"\"\n\n def __init__(self):\n super().__init__()\n\n def apply_image(self, img):\n assert len(img.shape) > 2\n return img[..., np.random.permutation(3)]\n\n def apply_coords(self, coords: np.ndarray) -> np.ndarray:\n \"\"\"\n Apply no transform on the coordinates.\n \"\"\"\n return coords\n\n def apply_segmentation(self, segmentation: np.ndarray) -> np.ndarray:\n \"\"\"\n Apply no transform on the full-image segmentation.\n \"\"\"\n return segmentation\n\n\nclass ExpandTransform(Transform):\n \"\"\"\n Expand the image and boxes according the specified expand ratio.\n \"\"\"\n\n def __init__(self, left, top, ratio, mean=(0, 0, 0)):\n \"\"\"\n Args:\n left, top (int): crop the image by img[top: top+h, left:left+w].\n ratio (float): image expand ratio.\n mean (tuple): mean value of dataset.\n \"\"\"\n super().__init__()\n self._set_attributes(locals())\n\n def apply_image(self, img):\n \"\"\"\n Randomly place the original image on a canvas of 'ratio' x original image\n size filled with mean values. The ratio is in the range of ratio_range.\n \"\"\"\n h, w, c = img.shape\n expand_img = np.full((int(h * self.ratio), int(w * self.ratio), c),\n self.mean).astype(img.dtype)\n expand_img[self.top:self.top + h, self.left:self.left + w] = img\n return expand_img\n\n def apply_coords(self, coords: np.ndarray) -> np.ndarray:\n \"\"\"\n Apply expand transform on coordinates.\n\n Args:\n coords (ndarray): floating point array of shape Nx2. Each row is\n (x, y).\n Returns:\n ndarray: expand coordinates.\n \"\"\"\n coords[:, 0] += self.left\n coords[:, 1] += self.top\n return coords\n\n\nclass ExtentTransform(Transform):\n \"\"\"\n Extracts a subregion from the source image and scales it to the output size.\n\n The fill color is used to map pixels from the source rect that fall outside\n the source image.\n\n See: https://pillow.readthedocs.io/en/latest/PIL.html#PIL.ImageTransform.ExtentTransform\n \"\"\"\n def __init__(self, src_rect, output_size, interp=Image.LINEAR, fill=0):\n \"\"\"\n Args:\n src_rect (x0, y0, x1, y1): src coordinates\n output_size (h, w): dst image size\n interp: PIL interpolation methods\n fill: Fill color used when src_rect extends outside image\n \"\"\"\n super().__init__()\n self._set_attributes(locals())\n\n def apply_image(self, img, interp=None):\n h, w = self.output_size\n ret = Image.fromarray(img).transform(\n size=(w, h),\n method=Image.EXTENT,\n data=self.src_rect,\n resample=interp if interp else self.interp,\n fill=self.fill,\n )\n return np.asarray(ret)\n\n def apply_coords(self, coords):\n # Transform image center from source coordinates into output coordinates\n # and then map the new origin to the corner of the output image.\n h, w = self.output_size\n x0, y0, x1, y1 = self.src_rect\n new_coords = coords.astype(np.float32)\n new_coords[:, 0] -= 0.5 * (x0 + x1)\n new_coords[:, 1] -= 0.5 * (y0 + y1)\n new_coords[:, 0] *= w / (x1 - x0)\n new_coords[:, 1] *= h / (y1 - y0)\n new_coords[:, 0] += 0.5 * w\n new_coords[:, 1] += 0.5 * h\n return new_coords\n\n def apply_segmentation(self, segmentation):\n segmentation = self.apply_image(segmentation, interp=Image.NEAREST)\n return segmentation\n\n\nclass ResizeTransform(Transform):\n \"\"\"\n Resize the image to a target size.\n \"\"\"\n def __init__(self, h, w, new_h, new_w, interp):\n \"\"\"\n Args:\n h, w (int): original image size\n new_h, new_w (int): new image size\n interp: PIL interpolation methods\n \"\"\"\n # TODO decide on PIL vs opencv\n super().__init__()\n self._set_attributes(locals())\n\n def apply_image(self, img, interp=None):\n assert img.shape[:2] == (self.h, self.w)\n pil_image = Image.fromarray(img)\n interp_method = interp if interp is not None else self.interp\n pil_image = pil_image.resize((self.new_w, self.new_h), interp_method)\n ret = np.asarray(pil_image)\n return ret\n\n def apply_coords(self, coords):\n coords[:, 0] = coords[:, 0] * (self.new_w * 1.0 / self.w)\n coords[:, 1] = coords[:, 1] * (self.new_h * 1.0 / self.h)\n return coords\n\n def apply_segmentation(self, segmentation):\n segmentation = self.apply_image(segmentation, interp=Image.NEAREST)\n return segmentation\n\n\ndef HFlip_rotated_box(transform, rotated_boxes):\n \"\"\"\n Apply the horizontal flip transform on rotated boxes.\n\n Args:\n rotated_boxes (ndarray): Nx5 floating point array of\n (x_center, y_center, width, height, angle_degrees) format\n in absolute coordinates.\n \"\"\"\n rotated_boxes = np.asarray(rotated_boxes)\n # Transform x_center\n rotated_boxes[:, 0] = transform.width - rotated_boxes[:, 0]\n # Transform angle\n rotated_boxes[:, 4] = -rotated_boxes[:, 4]\n return rotated_boxes\n\n\ndef Resize_rotated_box(transform, rotated_boxes):\n \"\"\"\n Apply the resizing transform on rotated boxes. For details of how these (approximation)\n formulas are derived, please refer to :meth:`RotatedBoxes.scale`.\n\n Args:\n rotated_boxes (ndarray): Nx5 floating point array of\n (x_center, y_center, width, height, angle_degrees) format\n in absolute coordinates.\n \"\"\"\n rotated_boxes = np.asarray(rotated_boxes)\n scale_factor_x = transform.new_w * 1.0 / transform.w\n scale_factor_y = transform.new_h * 1.0 / transform.h\n rotated_boxes[:, 0] *= scale_factor_x\n rotated_boxes[:, 1] *= scale_factor_y\n theta = rotated_boxes[:, 4] * np.pi / 180.0\n c = np.cos(theta)\n s = np.sin(theta)\n rotated_boxes[:, 2] *= np.sqrt(\n np.square(scale_factor_x * c) + np.square(scale_factor_y * s))\n rotated_boxes[:, 3] *= np.sqrt(\n np.square(scale_factor_x * s) + np.square(scale_factor_y * c))\n rotated_boxes[:, 4] = np.arctan2(scale_factor_x * s,\n scale_factor_y * c) * 180 / np.pi\n\n return rotated_boxes\n\n\nHFlipTransform.register_type(\"rotated_box\", HFlip_rotated_box)\nNoOpTransform.register_type(\"rotated_box\", lambda t, x: x)\nResizeTransform.register_type(\"rotated_box\", Resize_rotated_box)\n", "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n# Copyright (C) 2019-2021 Megvii Inc. All rights reserved.\n\n# network file -> build Cell for Dynamic Backbone\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom cvpods.layers import Conv2d, get_norm\nfrom cvpods.modeling.backbone.dynamic_arch import cal_op_flops\nfrom cvpods.modeling.nn_utils import weight_init\n\nfrom .op_with_flops import OPS, Identity\n\n__all__ = [\"Mixed_OP\", \"Cell\"]\n\n\n# soft gate for path choice\ndef soft_gate(x, x_t=None, momentum=0.1, is_update=False):\n if is_update:\n # using momentum for weight update\n y = (1 - momentum) * x.data + momentum * x_t\n tanh_value = torch.tanh(y)\n return F.relu(tanh_value), y.data\n else:\n tanh_value = torch.tanh(x)\n return F.relu(tanh_value)\n\n\n# Scheduled Drop Path\ndef drop_path(x, drop_prob, layer_rate, step_rate):\n \"\"\"\n :param x: input feature\n :param drop_prob: drop path prob\n :param layer_rate: current_layer/total_layer\n :param step_rate: current_step/total_step\n :return: output feature\n \"\"\"\n if drop_prob > 0.:\n keep_prob = 1. - drop_prob\n keep_prob = 1. - layer_rate * (1. - keep_prob)\n keep_prob = 1. - step_rate * (1. - keep_prob)\n mask = torch.cuda.FloatTensor(x.size(0), 1, 1, 1).bernoulli_(keep_prob)\n x.div_(keep_prob)\n x.mul_(mask)\n return x\n\n\nclass Mixed_OP(nn.Module):\n \"\"\"\n Sum up operations according to their weights.\n \"\"\"\n def __init__(\n self, inplanes, outplanes, stride, cell_type,\n norm='', affine=True, input_size=None\n ):\n super(Mixed_OP, self).__init__()\n self._ops = nn.ModuleList()\n self.op_flops = []\n for key in cell_type:\n op = OPS[key](\n inplanes, outplanes, stride, norm_layer=norm,\n affine=affine, input_size=input_size\n )\n self._ops.append(op)\n self.op_flops.append(op.flops)\n self.real_flops = sum(op_flop for op_flop in self.op_flops)\n\n def forward(self, x, is_drop_path=False, drop_prob=0.0, layer_rate=0.0, step_rate=0.0):\n if is_drop_path:\n y = []\n for op in self._ops:\n if not isinstance(op, Identity):\n y.append(drop_path(op(x), drop_prob, layer_rate, step_rate))\n else:\n y.append(op(x))\n return sum(y)\n else:\n # using sum up rather than random choose one branch.\n return sum(op(x) for op in self._ops)\n\n @property\n def flops(self):\n return self.real_flops.squeeze()\n\n\nclass Cell(nn.Module):\n def __init__( # noqa:C901\n self, C_in, C_out, norm, allow_up, allow_down, input_size,\n cell_type, cal_flops=True, using_gate=False,\n small_gate=False, gate_bias=1.5, affine=True\n ):\n super(Cell, self).__init__()\n self.channel_in = C_in\n self.channel_out = C_out\n self.allow_up = allow_up\n self.allow_down = allow_down\n self.cal_flops = cal_flops\n self.using_gate = using_gate\n self.small_gate = small_gate\n\n self.cell_ops = Mixed_OP(\n inplanes=self.channel_in, outplanes=self.channel_out,\n stride=1, cell_type=cell_type, norm=norm,\n affine=affine, input_size=input_size\n )\n self.cell_flops = self.cell_ops.flops\n # resolution keep\n self.res_keep = nn.ReLU()\n self.res_keep_flops = cal_op_flops.count_ReLU_flop(\n input_size[0], input_size[1], self.channel_out\n )\n # resolution up and dim down\n if self.allow_up:\n self.res_up = nn.Sequential(\n nn.ReLU(),\n Conv2d(\n self.channel_out, self.channel_out // 2, kernel_size=1,\n stride=1, padding=0, bias=False,\n norm=get_norm(norm, self.channel_out // 2),\n activation=nn.ReLU()\n )\n )\n # calculate Flops\n self.res_up_flops = cal_op_flops.count_ReLU_flop(\n input_size[0], input_size[1], self.channel_out\n ) + cal_op_flops.count_ConvBNReLU_flop(\n input_size[0], input_size[1], self.channel_out,\n self.channel_out // 2, [1, 1], is_affine=affine\n )\n # using Kaiming init\n for m in self.res_up.modules():\n if isinstance(m, nn.Conv2d):\n weight_init.kaiming_init(m, mode='fan_in')\n elif isinstance(m, (nn.BatchNorm2d, nn.SyncBatchNorm)):\n if m.weight is not None:\n nn.init.constant_(m.weight, 1)\n if m.bias is not None:\n nn.init.constant_(m.bias, 0)\n # resolution down and dim up\n if self.allow_down:\n self.res_down = nn.Sequential(\n nn.ReLU(),\n Conv2d(\n self.channel_out, 2 * self.channel_out,\n kernel_size=1, stride=2, padding=0, bias=False,\n norm=get_norm(norm, 2 * self.channel_out),\n activation=nn.ReLU()\n )\n )\n # calculate Flops\n self.res_down_flops = cal_op_flops.count_ReLU_flop(\n input_size[0], input_size[1], self.channel_out\n ) + cal_op_flops.count_ConvBNReLU_flop(\n input_size[0], input_size[1], self.channel_out,\n 2 * self.channel_out, [1, 1], stride=2, is_affine=affine\n )\n # using Kaiming init\n for m in self.res_down.modules():\n if isinstance(m, nn.Conv2d):\n weight_init.kaiming_init(m, mode='fan_in')\n elif isinstance(m, (nn.BatchNorm2d, nn.SyncBatchNorm)):\n if m.weight is not None:\n nn.init.constant_(m.weight, 1)\n if m.bias is not None:\n nn.init.constant_(m.bias, 0)\n if self.allow_up and self.allow_down:\n self.gate_num = 3\n elif self.allow_up or self.allow_down:\n self.gate_num = 2\n else:\n self.gate_num = 1\n if self.using_gate:\n self.gate_conv_beta = nn.Sequential(\n Conv2d(\n self.channel_in, self.channel_in // 2, kernel_size=1,\n stride=1, padding=0, bias=False,\n norm=get_norm(norm, self.channel_in // 2),\n activation=nn.ReLU()\n ),\n nn.AdaptiveAvgPool2d((1, 1)),\n Conv2d(\n self.channel_in // 2, self.gate_num, kernel_size=1,\n stride=1, padding=0, bias=True\n )\n )\n if self.small_gate:\n input_size = input_size // 4\n self.gate_flops = cal_op_flops.count_ConvBNReLU_flop(\n input_size[0], input_size[1], self.channel_in,\n self.channel_in // 2, [1, 1], is_affine=affine\n ) + cal_op_flops.count_Pool2d_flop(\n input_size[0], input_size[1], self.channel_in // 2, [1, 1], 1\n ) + cal_op_flops.count_Conv_flop(\n 1, 1, self.channel_in // 2, self.gate_num, [1, 1]\n )\n # using Kaiming init and predefined bias for gate\n for m in self.gate_conv_beta.modules():\n if isinstance(m, nn.Conv2d):\n weight_init.kaiming_init(m, mode='fan_in', bias=gate_bias)\n elif isinstance(m, (nn.BatchNorm2d, nn.SyncBatchNorm)):\n if m.weight is not None:\n nn.init.constant_(m.weight, 1)\n if m.bias is not None:\n nn.init.constant_(m.bias, 0)\n else:\n self.register_buffer(\n 'gate_weights_beta', torch.ones(1, self.gate_num, 1, 1).cuda()\n )\n self.gate_flops = 0.0\n\n def forward(\n self, h_l1, flops_in_expt=None, flops_in_real=None,\n is_drop_path=False, drop_prob=0.0,\n layer_rate=0.0, step_rate=0.0\n ):\n \"\"\"\n :param h_l1: # the former hidden layer output\n :return: current hidden cell result h_l\n \"\"\"\n drop_cell = False\n # drop the cell if input type is float\n if not isinstance(h_l1, float):\n # calculate soft conditional gate\n if self.using_gate:\n if self.small_gate:\n h_l1_gate = F.interpolate(\n input=h_l1, scale_factor=0.25,\n mode='bilinear', align_corners=False\n )\n else:\n h_l1_gate = h_l1\n gate_feat_beta = self.gate_conv_beta(h_l1_gate)\n gate_weights_beta = soft_gate(gate_feat_beta)\n else:\n gate_weights_beta = self.gate_weights_beta\n else:\n drop_cell = True\n # use for inference\n if not self.training:\n if not drop_cell:\n drop_cell = gate_weights_beta.sum() < 0.0001\n if drop_cell:\n result_list = [[0.0], [h_l1], [0.0]]\n weights_list_beta = [[0.0], [0.0], [0.0]]\n trans_flops_expt = [[0.0], [0.0], [0.0]]\n trans_flops_real = [[0.0], [0.0], [0.0]]\n if self.cal_flops:\n h_l_flops = flops_in_expt\n h_l_flops_real = flops_in_real + self.gate_flops\n return (\n result_list, weights_list_beta, h_l_flops,\n h_l_flops_real, trans_flops_expt, trans_flops_real\n )\n else:\n return (\n result_list, weights_list_beta,\n trans_flops_expt, trans_flops_real\n )\n\n h_l = self.cell_ops(h_l1, is_drop_path, drop_prob, layer_rate, step_rate)\n\n # resolution and dimension change\n # resolution: [up, keep, down]\n h_l_keep = self.res_keep(h_l)\n gate_weights_beta_keep = gate_weights_beta[:, 0].unsqueeze(-1)\n # using residual connection if drop cell\n gate_mask = (gate_weights_beta.sum(dim=1, keepdim=True) < 0.0001).float()\n result_list = [[], [gate_mask * h_l1 + gate_weights_beta_keep * h_l_keep], []]\n weights_list_beta = [[], [gate_mask * 1.0 + gate_weights_beta_keep], []]\n # calculate flops for keep res\n gate_mask_keep = (gate_weights_beta_keep > 0.0001).float()\n trans_flops_real = [[], [gate_mask_keep * self.res_keep_flops], []]\n # calculate trans flops\n trans_flops_expt = [[], [self.res_keep_flops * gate_weights_beta_keep], []]\n\n if self.allow_up:\n h_l_up = self.res_up(h_l)\n h_l_up = F.interpolate(\n input=h_l_up, scale_factor=2, mode='bilinear', align_corners=False\n )\n gate_weights_beta_up = gate_weights_beta[:, 1].unsqueeze(-1)\n result_list[0].append(h_l_up * gate_weights_beta_up)\n weights_list_beta[0].append(gate_weights_beta_up)\n trans_flops_expt[0].append(self.res_up_flops * gate_weights_beta_up)\n # calculate flops for up res\n gate_mask_up = (gate_weights_beta_up > 0.0001).float()\n trans_flops_real[0].append(gate_mask_up * self.res_up_flops)\n\n if self.allow_down:\n h_l_down = self.res_down(h_l)\n gate_weights_beta_down = gate_weights_beta[:, -1].unsqueeze(-1)\n result_list[2].append(h_l_down * gate_weights_beta_down)\n weights_list_beta[2].append(gate_weights_beta_down)\n trans_flops_expt[2].append(self.res_down_flops * gate_weights_beta_down)\n # calculate flops for down res\n gate_mask_down = (gate_weights_beta_down > 0.0001).float()\n trans_flops_real[2].append(gate_mask_down * self.res_down_flops)\n\n if self.cal_flops:\n cell_flops = gate_weights_beta.max(dim=1, keepdim=True)[0] * self.cell_flops\n cell_flops_real = (\n gate_weights_beta.sum(dim=1, keepdim=True) > 0.0001\n ).float() * self.cell_flops\n h_l_flops = cell_flops + flops_in_expt\n h_l_flops_real = cell_flops_real + flops_in_real + self.gate_flops\n return (\n result_list, weights_list_beta, h_l_flops,\n h_l_flops_real, trans_flops_expt, trans_flops_real\n )\n else:\n return result_list, weights_list_beta, trans_flops_expt, trans_flops_real\n", "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n# Copyright (C) 2019-2021 Megvii Inc. All rights reserved.\n\nimport torch\nimport torch.nn as nn\n\n\n# Ref:\n# https://medium.com/the-artificial-impostor/more-memory-efficient-swish-activation-function-e07c22c12a76\nclass SwishImplementation(torch.autograd.Function):\n \"\"\"\n Swish activation function memory-efficient implementation.\n\n This implementation explicitly processes the gradient, it keeps a copy of the input tensor,\n and uses it to calculate the gradient during the back-propagation phase.\n \"\"\"\n @staticmethod\n def forward(ctx, i):\n result = i * torch.sigmoid(i)\n ctx.save_for_backward(i)\n return result\n\n @staticmethod\n def backward(ctx, grad_output):\n i = ctx.saved_variables[0]\n sigmoid_i = torch.sigmoid(i)\n return grad_output * (sigmoid_i * (1 + i * (1 - sigmoid_i)))\n\n\nclass MemoryEfficientSwish(nn.Module):\n def forward(self, x):\n return SwishImplementation.apply(x)\n\n\nclass Swish(nn.Module):\n \"\"\"\n Implement the Swish activation function.\n See: https://arxiv.org/abs/1710.05941 for more details.\n \"\"\"\n def forward(self, x):\n return x * torch.sigmoid(x)\n" ]
[ [ "torch.zeros", "torch.nn.init.constant_", "torch.nn.Conv2d", "torch.nn.functional.adaptive_avg_pool2d", "torch.nn.init.normal_" ], [ "torch.nn.functional.softmax", "torch.nn.modules.utils._pair", "torch.nn.functional.adaptive_avg_pool2d", "torch.nn.functional.sigmoid", "torch.split", "torch.nn.ReLU" ], [ "numpy.dot", "numpy.asarray", "numpy.concatenate", "numpy.arctan2", "numpy.zeros_like", "torch.no_grad", "numpy.random.randint", "numpy.square", "numpy.clip", "numpy.reshape", "numpy.arange", "torch.from_numpy", "numpy.sin", "numpy.full", "numpy.float32", "numpy.repeat", "numpy.random.choice", "numpy.ascontiguousarray", "numpy.power", "torch.nn.Conv2d", "numpy.rint", "numpy.deg2rad", "numpy.random.rand", "numpy.array", "torch.nn.ReflectionPad2d", "numpy.maximum", "numpy.random.random", "numpy.cos", "numpy.ones", "numpy.random.normal", "numpy.random.permutation", "numpy.random.uniform" ], [ "torch.ones", "torch.nn.init.constant_", "torch.nn.ModuleList", "torch.tanh", "torch.nn.functional.relu", "torch.nn.AdaptiveAvgPool2d", "torch.nn.functional.interpolate", "torch.nn.ReLU" ], [ "torch.sigmoid" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
live4dao/RLtrading
[ "c1655a7bfe1220c1d7ae5c0d46814bf3884e6cdb" ]
[ "__main__.py" ]
[ "import numpy as np\nimport pandas as pd\nimport trading_env\n\nfrom datetime import datetime\nst = datetime.now()\n## need to refactor the testcase\n\n# df = pd.read_csv('trading_env/test/data/SGXTWsample.csv', index_col=0, parse_dates=['datetime'])\ndf = pd.read_hdf('D:\\[AIA]\\TradingGym\\dataset\\SGXTWsample.h5', 'STW')\n\nenv = trading_env.make(env_id='training_v1', obs_data_len=256, step_len=128,\n df=df, fee=0.1, max_position=5, deal_col_name='Price', \n feature_names=['Price', 'Volume', \n 'Ask_price','Bid_price', \n 'Ask_deal_vol','Bid_deal_vol',\n 'Bid/Ask_deal', 'Updown'], \n fluc_div=100.0)\n\nenv.reset()\nenv.render()\nprint(env.df_sample['datetime'].iloc[0].date())\nfor i in range(500):\n # print(i)\n state, reward, done, info = env.step(np.random.randint(3))\n # print(state, reward)\n # env.render()\n if done:\n break\nprint(datetime.now() - st)" ]
[ [ "pandas.read_hdf", "numpy.random.randint" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
dbis-uibk/NLP4MusA2020
[ "1d0ab42a7aea416110fbacd632e5bce359b863e8" ]
[ "src/nlp4musa2020/analytics.py" ]
[ "\"\"\"Module providing common functions used for analytics.\"\"\"\nimport os.path\n\nfrom dbispipeline.analytics import extract_gridsearch_parameters\nfrom dbispipeline.db import DB\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n\ndef get_results(project_name, filter_git_dirty=True):\n \"\"\"Returns the results stored in the databes as a pandas dataframe.\n\n Args:\n project_name: The project name to fetch results.\n filter_git_dirty: defines if dirty commits are filterd.\n \"\"\"\n results = pd.read_sql_table(table_name='results', con=DB.engine)\n\n if filter_git_dirty:\n results = results[results['git_is_dirty'] == False] # noqa: E712\n\n return results[results['project_name'] == project_name]\n\n\ndef extract_best_result(result, score):\n \"\"\"Extracts the max value result for a given score column.\n\n Args:\n result: dataframe to extract results from.\n score: the column used to select the max value.\n \"\"\"\n result = result[result[score] >= result[score].max()]\n return result\n\n\ndef get_best_results(score_name, score_prefix='mean_test_', max_value=None):\n \"\"\"Returns the best results for a given score.\n\n Args:\n score_name: the name of the score that is prefixed with score_prefix.\n The result is the column used to extract the results.\n score_prefix: the prefix of the score name.\n max_value: If not None, include only results that have scores lower\n than this value.\n \"\"\"\n data = get_results(project_name='nlp4musa2020')\n\n score = score_prefix + score_name\n\n result = pd.DataFrame()\n for _, group in data.groupby(['sourcefile']):\n outcome = None\n try:\n outcome = extract_gridsearch_parameters(group, score_name=score)\n except KeyError:\n continue\n # FIXME: Remove after updating the dbispipeline\n outcome[score] = outcome['score']\n if '_neg_' in score:\n outcome[score] *= -1\n\n result = result.append(extract_best_result(outcome, score=score))\n\n if max_value is not None:\n result = result[result[score] < max_value]\n\n if len(result) < 1:\n raise Exception('No results found.')\n\n return result\n\n\ndef plot_best_results(score_name,\n score_prefix='mean_test_',\n max_value=None,\n result_path=None,\n file_ext='pdf'):\n \"\"\"Plots the to results for a given metric.\n\n Args:\n score_name: the name of the score that is prefixed with score_prefix.\n The result is the column used to extract the results.\n score_prefix: the prefix of the score name.\n max_value: If not None, include only results that have scores lower\n than this value.\n result_path: the path used to store result files.\n file_ext: the file extension used for the plots.\n \"\"\"\n result = get_best_results(score_name, score_prefix, max_value)\n\n score = score_prefix + score_name\n result[['sourcefile', score]].plot.bar(\n x='sourcefile',\n title=score_name,\n grid=True,\n figsize=(30, 10),\n )\n\n file_name = 'best_results_' + score_name + '.' + file_ext\n if result_path is not None:\n file_name = os.path.join(result_path, file_name)\n\n plt.savefig(file_name)\n" ]
[ [ "pandas.read_sql_table", "matplotlib.pyplot.savefig", "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "0.19", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] } ]
afiolmahon/ducky25
[ "c740931bee73526e0edb22f3a1f9bf3d71287b1a" ]
[ "catkin_ws/src/lane_filter/src/lane_filter_node.py" ]
[ "#!/usr/bin/env python\nimport rospy\nimport numpy as np\nfrom cv_bridge import CvBridge, CvBridgeError\nfrom sensor_msgs.msg import Image\nfrom std_msgs.msg import Float32\nfrom duckietown_msgs.msg import SegmentList, Segment, Pixel, LanePose, BoolStamped, Twist2DStamped\nfrom scipy.stats import multivariate_normal, entropy\nfrom scipy.ndimage.filters import gaussian_filter\nfrom math import floor, atan2, pi, cos, sin, sqrt\nimport time\n\n\nclass LaneFilterNode(object):\n \"\"\"\n \nLane Filter Node\n\nAuthor: Liam Paull\n\nInputs: SegmentList from line detector\n\nOutputs: LanePose - the d (lateral displacement) and phi (relative angle) \nof the car in the lane\n\nFor more info on algorithm and parameters please refer to the google doc:\n https://drive.google.com/open?id=0B49dGT7ubfmSX1k5ZVN1dEU4M2M\n\n \"\"\"\n def __init__(self):\n self.node_name = \"Lane Filter\"\n self.active = True\n self.updateParams(None)\n \n self.d,self.phi = np.mgrid[self.d_min:self.d_max:self.delta_d,self.phi_min:self.phi_max:self.delta_phi]\n self.beliefRV=np.empty(self.d.shape)\n self.initializeBelief()\n self.lanePose = LanePose()\n self.lanePose.d=self.mean_0[0]\n self.lanePose.phi=self.mean_0[1]\n\n self.dwa = -(self.zero_val*self.l_peak**2 + self.zero_val*self.l_max**2 - self.l_max**2*self.peak_val - 2*self.zero_val*self.l_peak*self.l_max + 2*self.l_peak*self.l_max*self.peak_val)/(self.l_peak**2*self.l_max*(self.l_peak - self.l_max)**2)\n self.dwb = (2*self.zero_val*self.l_peak**3 + self.zero_val*self.l_max**3 - self.l_max**3*self.peak_val - 3*self.zero_val*self.l_peak**2*self.l_max + 3*self.l_peak**2*self.l_max*self.peak_val)/(self.l_peak**2*self.l_max*(self.l_peak - self.l_max)**2)\n self.dwc = -(self.zero_val*self.l_peak**3 + 2*self.zero_val*self.l_max**3 - 2*self.l_max**3*self.peak_val - 3*self.zero_val*self.l_peak*self.l_max**2 + 3*self.l_peak*self.l_max**2*self.peak_val)/(self.l_peak*self.l_max*(self.l_peak - self.l_max)**2)\n\n\n self.t_last_update = rospy.get_time()\n self.v_current = 0\n self.w_current = 0\n self.v_last = 0\n self.w_last = 0\n self.v_avg = 0\n self.w_avg = 0\n\n # Subscribers\n if self.use_propagation:\n self.sub_velocity = rospy.Subscriber(\"~velocity\", Twist2DStamped, self.updateVelocity)\n self.sub = rospy.Subscriber(\"~segment_list\", SegmentList, self.processSegments, queue_size=1)\n\n # Publishers\n self.pub_lane_pose = rospy.Publisher(\"~lane_pose\", LanePose, queue_size=1)\n self.pub_belief_img = rospy.Publisher(\"~belief_img\", Image, queue_size=1)\n self.pub_entropy = rospy.Publisher(\"~entropy\",Float32, queue_size=1)\n \t#self.pub_prop_img = rospy.Publisher(\"~prop_img\", Image, queue_size=1)\n self.pub_in_lane = rospy.Publisher(\"~in_lane\",BoolStamped, queue_size=1)\n self.sub_switch = rospy.Subscriber(\"~switch\", BoolStamped, self.cbSwitch, queue_size=1)\n\n self.timer = rospy.Timer(rospy.Duration.from_sec(1.0), self.updateParams)\n\n\n def updateParams(self, event):\n self.mean_0 = [rospy.get_param(\"~mean_d_0\",0) , rospy.get_param(\"~mean_phi_0\",0)]\n self.cov_0 = [ [rospy.get_param(\"~sigma_d_0\",0.1) , 0] , [0, rospy.get_param(\"~sigma_phi_0\",0.01)] ]\n self.delta_d = rospy.get_param(\"~delta_d\",0.02) # in meters\n self.delta_phi = rospy.get_param(\"~delta_phi\",0.02) # in radians\n self.d_max = rospy.get_param(\"~d_max\",0.5)\n self.d_min = rospy.get_param(\"~d_min\",-0.7)\n self.phi_min = rospy.get_param(\"~phi_min\",-pi/2)\n self.phi_max = rospy.get_param(\"~phi_max\",pi/2)\n\n self.cov_v = rospy.get_param(\"~cov_v\",0.5) # linear velocity \"input\"\n self.cov_omega = rospy.get_param(\"~cov_omega\",0.01) # angular velocity \"input\"\n self.linewidth_white = rospy.get_param(\"~linewidth_white\",0.04)\n self.linewidth_yellow = rospy.get_param(\"~linewidth_yellow\",0.02)\n self.lanewidth = rospy.get_param(\"~lanewidth\",0.4)\n self.min_max = rospy.get_param(\"~min_max\", 0.3) # nats\n # For use of distance weighting (dw) function\n self.use_distance_weighting = rospy.get_param(\"~use_distance_weighting\",False)\n self.zero_val = rospy.get_param(\"~zero_val\",1)\n self.l_peak = rospy.get_param(\"~l_peak\",1)\n self.peak_val = rospy.get_param(\"~peak_val\",10)\n self.l_max = rospy.get_param(\"~l_max\",2)\n\n # For use of maximum segment distance\n self.use_max_segment_dist = rospy.get_param(\"~use_max_segment_dist\",False)\n self.max_segment_dist = rospy.get_param(\"~max_segment_dist\",1.0)\n\n # For use of minimum segment count\n self.use_min_segs = rospy.get_param(\"~use_min_segs\",False)\n self.min_segs = rospy.get_param(\"~min_segs\", 10)\n\n # For propagation\n self.use_propagation = rospy.get_param(\"~use_propagation\",False)\n self.cov_mask = [rospy.get_param(\"~sigma_d_mask\",0.05) , rospy.get_param(\"~sigma_phi_mask\",0.05)]\n\n def cbSwitch(self, switch_msg):\n self.active = switch_msg.data\n\n def processSegments(self,segment_list_msg):\n if not self.active:\n return\n t_start = rospy.get_time()\n\n if self.use_propagation:\n self.propagateBelief()\n self.t_last_update = rospy.get_time()\n\n # initialize measurement likelihood\n measurement_likelihood = np.zeros(self.d.shape)\n\n for segment in segment_list_msg.segments:\n if segment.color != segment.WHITE and segment.color != segment.YELLOW:\n continue\n if segment.points[0].x < 0 or segment.points[1].x < 0:\n continue\n\n d_i,phi_i,l_i = self.generateVote(segment)\n if d_i > self.d_max or d_i < self.d_min or phi_i < self.phi_min or phi_i>self.phi_max:\n continue\n if self.use_max_segment_dist and (l_i > self.max_segment_dist):\n continue\n\n i = int(floor((d_i - self.d_min)/self.delta_d))\n j = int(floor((phi_i - self.phi_min)/self.delta_phi))\n\n if self.use_distance_weighting: \n dist_weight = self.dwa*l_i**3+self.dwb*l_i**2+self.dwc*l_i+self.zero_val\n if dist_weight < 0:\n continue\n measurement_likelihood[i,j] = measurement_likelihood[i,j] + dist_weight\n else:\n measurement_likelihood[i,j] = measurement_likelihood[i,j] + 1/(l_i)\n\n\n if np.linalg.norm(measurement_likelihood) == 0:\n return\n measurement_likelihood = measurement_likelihood/np.sum(measurement_likelihood)\n\n if self.use_propagation:\n self.updateBelief(measurement_likelihood)\n else:\n self.beliefRV = measurement_likelihood\n\n # TODO entropy test:\n #print self.beliefRV.argmax()\n\n maxids = np.unravel_index(self.beliefRV.argmax(),self.beliefRV.shape)\n # rospy.loginfo('maxids: %s' % maxids)\n self.lanePose.header.stamp = segment_list_msg.header.stamp\n self.lanePose.d = self.d_min + maxids[0]*self.delta_d\n self.lanePose.phi = self.phi_min + maxids[1]*self.delta_phi\n self.lanePose.status = self.lanePose.NORMAL\n\n # publish the belief image\n bridge = CvBridge()\n belief_img = bridge.cv2_to_imgmsg((255*self.beliefRV).astype('uint8'), \"mono8\")\n belief_img.header.stamp = segment_list_msg.header.stamp\n \n max_val = self.beliefRV.max()\n self.lanePose.in_lane = max_val > self.min_max and len(segment_list_msg.segments) > self.min_segs and np.linalg.norm(measurement_likelihood) != 0\n self.pub_lane_pose.publish(self.lanePose)\n self.pub_belief_img.publish(belief_img)\n\n # print \"time to process segments:\"\n # print rospy.get_time() - t_start\n\n # Publish in_lane according to the ent\n in_lane_msg = BoolStamped()\n in_lane_msg.header.stamp = segment_list_msg.header.stamp\n in_lane_msg.data = self.lanePose.in_lane\n # ent = entropy(self.beliefRV)\n # if (ent < self.max_entropy):\n # in_lane_msg.data = True\n # else:\n # in_lane_msg.data = False\n self.pub_in_lane.publish(in_lane_msg)\n\n def updateVelocity(self,twist_msg):\n self.v_current = twist_msg.v\n self.w_current = twist_msg.omega\n \n #self.v_avg = (self.v_current + self.v_last)/2.0\n #self.w_avg = (self.w_current + self.w_last)/2.0\n\n #self.v_last = v_current\n #self.w_last = w_current\n\n def initializeBelief(self):\n pos = np.empty(self.d.shape + (2,))\n pos[:,:,0]=self.d\n pos[:,:,1]=self.phi\n self.cov_0\n RV = multivariate_normal(self.mean_0,self.cov_0)\n self.beliefRV=RV.pdf(pos)\n\n def propagateBelief(self):\n delta_t = rospy.get_time() - self.t_last_update\n\n d_t = self.d + self.v_current*delta_t*np.sin(self.phi)\n phi_t = self.phi + self.w_current*delta_t\n\n p_beliefRV = np.zeros(self.beliefRV.shape)\n\n for i in range(self.beliefRV.shape[0]):\n for j in range(self.beliefRV.shape[1]):\n if self.beliefRV[i,j] > 0:\n if d_t[i,j] > self.d_max or d_t[i,j] < self.d_min or phi_t[i,j] < self.phi_min or phi_t[i,j] > self.phi_max:\n continue\n i_new = floor((d_t[i,j] - self.d_min)/self.delta_d)\n j_new = floor((phi_t[i,j] - self.phi_min)/self.delta_phi)\n p_beliefRV[i_new,j_new] += self.beliefRV[i,j]\n\n s_beliefRV = np.zeros(self.beliefRV.shape)\n gaussian_filter(100*p_beliefRV, self.cov_mask, output=s_beliefRV, mode='constant')\n\n if np.sum(s_beliefRV) == 0:\n return\n self.beliefRV = s_beliefRV/np.sum(s_beliefRV)\n\n \t#bridge = CvBridge()\n #prop_img = bridge.cv2_to_imgmsg((255*self.beliefRV).astype('uint8'), \"mono8\")\n #self.pub_prop_img.publish(prop_img)\n \n return\n\n def updateBelief(self,measurement_likelihood):\n self.beliefRV=np.multiply(self.beliefRV+1,measurement_likelihood+1)-1\n self.beliefRV=self.beliefRV/np.sum(self.beliefRV)#np.linalg.norm(self.beliefRV)\n\n def generateVote(self,segment):\n p1 = np.array([segment.points[0].x, segment.points[0].y])\n p2 = np.array([segment.points[1].x, segment.points[1].y])\n t_hat = (p2-p1)/np.linalg.norm(p2-p1)\n n_hat = np.array([-t_hat[1],t_hat[0]])\n d1 = np.inner(n_hat,p1)\n d2 = np.inner(n_hat,p2)\n l1 = np.inner(t_hat,p1)\n l2 = np.inner(t_hat,p2)\n if (l1 < 0):\n l1 = -l1;\n if (l2 < 0):\n l2 = -l2;\n l_i = (l1+l2)/2\n d_i = (d1+d2)/2\n phi_i = np.arcsin(t_hat[1])\n if segment.color == segment.WHITE: # right lane is white\n if(p1[0] > p2[0]): # right edge of white lane\n d_i = d_i - self.linewidth_white\n else: # left edge of white lane\n d_i = - d_i\n phi_i = -phi_i\n d_i = d_i - self.lanewidth/2\n\n elif segment.color == segment.YELLOW: # left lane is yellow\n if (p2[0] > p1[0]): # left edge of yellow lane\n d_i = d_i - self.linewidth_yellow\n phi_i = -phi_i\n else: # right edge of white lane\n d_i = -d_i\n d_i = self.lanewidth/2 - d_i\n\n return d_i, phi_i, l_i\n\n def getSegmentDistance(self, segment):\n x_c = (segment.points[0].x + segment.points[1].x)/2\n y_c = (segment.points[0].y + segment.points[1].y)/2\n\n return sqrt(x_c**2 + y_c**2)\n\n def onShutdown(self):\n rospy.loginfo(\"[LaneFilterNode] Shutdown.\")\n\n\nif __name__ == '__main__':\n rospy.init_node('lane_filter',anonymous=False)\n lane_filter_node = LaneFilterNode()\n rospy.on_shutdown(lane_filter_node.onShutdown)\n rospy.spin()\n" ]
[ [ "numpy.inner", "numpy.multiply", "numpy.arcsin", "numpy.linalg.norm", "numpy.sin", "scipy.stats.multivariate_normal", "scipy.ndimage.filters.gaussian_filter", "numpy.array", "numpy.zeros", "numpy.sum", "numpy.empty" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "1.6", "0.14", "0.15", "1.4", "0.16", "1.0", "0.19", "1.5", "0.18", "1.2", "1.7", "0.12", "0.10", "0.17", "1.3" ], "tensorflow": [] } ]
Lisennlp/distributed_train_pytorch
[ "da43ac6b5f4484b5f7bc92e3c778539b9017cb82" ]
[ "main.py" ]
[ "import argparse\nimport os\nimport random\n\nimport torch\nfrom torch import distributed as dist\nfrom torch.utils.data import DataLoader\nfrom torch.nn.parallel import DistributedDataParallel as DDP\nfrom torch.utils.data.distributed import DistributedSampler\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\n\n\nclass LinModel(nn.Module):\n\n def __init__(self, in_dim, out_dim):\n super(LinModel, self).__init__()\n self.linear = nn.Linear(in_dim, out_dim)\n\n def forward(self, x):\n out = self.linear(x)\n out = F.softmax(out, dim=-1)\n return out\n\n\ndef reduce_loss(tensor, rank, world_size):\n with torch.no_grad():\n dist.reduce(tensor, dst=0)\n if rank == 0:\n tensor /= world_size\n\n\ndef build_fake_data(size=1000):\n x1 = [(random.uniform(0, 0.5), 0) for i in range(size // 2)]\n x2 = [(random.uniform(0.5, 1), 1) for i in range(size // 2)]\n return x1 + x2\n\n\ndef evaluate(valid_loader):\n net.eval()\n with torch.no_grad():\n cnt = 0\n total = 0\n for inputs, labels in valid_loader:\n inputs, labels = inputs.unsqueeze(1).float().cuda(), labels.long().cuda()\n output = net(inputs)\n predict = torch.argmax(output, dim=1)\n cnt += (predict == labels).sum().item()\n total += len(labels)\n # print(f'right = {(predict == labels).sum()}')\n cnt = torch.Tensor([cnt]).to(inputs.device)\n total = torch.Tensor([total]).to(inputs.device)\n reduced_param = torch.cat((cnt.view(1), total.view(1)))\n cnt = reduced_param[0].item()\n total = reduced_param[1].item()\n return cnt, total\n\n\ndef set_random_seed(seed):\n \"\"\"Set random seed for reproducability.\"\"\"\n if seed is not None and seed > 0:\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--local_rank', type=int, default=-1, help=\"local gpu id\")\nparser.add_argument('--batch_size', type=int, default=128, help=\"batch size\")\nparser.add_argument('--lr', type=float, default=0.1, help=\"learn rate\")\nparser.add_argument('--epochs', type=int, default=5, help=\"train epoch\")\nparser.add_argument('--seed', type=int, default=40, help=\"train epoch\")\n\n\nargs = parser.parse_args()\nargs.world_size = int(os.getenv(\"WORLD_SIZE\", '1'))\n\nset_random_seed(args.seed)\ndist.init_process_group(backend='nccl', init_method='env://')\ntorch.cuda.set_device(args.local_rank)\nglobal_rank = dist.get_rank()\n\nprint(f'global_rank = {global_rank} local_rank = {args.local_rank} world_size = {args.world_size}')\n\nnet = LinModel(1, 2)\nnet.cuda()\nnet = torch.nn.SyncBatchNorm.convert_sync_batchnorm(net)\nnet = DDP(net, device_ids=[args.local_rank], output_device=args.local_rank)\n\ntrainset = build_fake_data(size=10000)\nvalidset = build_fake_data(size=10000)\n\ntrain_sampler = DistributedSampler(trainset)\nvalid_sampler = DistributedSampler(validset)\n\ntrain_loader = DataLoader(trainset,\n batch_size=args.batch_size,\n shuffle=False,\n pin_memory=True,\n sampler=train_sampler)\n\nvalid_loader = DataLoader(validset,\n batch_size=args.batch_size,\n shuffle=False,\n pin_memory=True,\n sampler=valid_sampler)\n\ncriterion = torch.nn.CrossEntropyLoss()\nopt = torch.optim.Adam(net.parameters(), lr=args.lr)\n\nnet.train()\nfor e in range(int(args.epochs)):\n\n for idx, (inputs, labels) in enumerate(train_loader):\n inputs = inputs.unsqueeze(1).float().cuda()\n labels = labels.long().cuda()\n output = net(inputs)\n loss = criterion(output, labels)\n opt.zero_grad()\n loss.backward()\n opt.step()\n reduce_loss(loss, global_rank, args.world_size)\n # if idx % 10 == 0 and global_rank == 0:\n # print('Epoch: {} step: {} loss: {}'.format(e, idx, loss.item()))\n cnt, total = evaluate(valid_loader)\n if global_rank == 0:\n print(f'epoch {e} || eval accuracy: {cnt / total}')\n\n# if global_rank == 0:\n# print(f'net weight = {net.state_dict()}')\n" ]
[ [ "torch.nn.CrossEntropyLoss", "torch.nn.functional.softmax", "torch.distributed.init_process_group", "torch.cuda.set_device", "torch.utils.data.distributed.DistributedSampler", "numpy.random.seed", "torch.manual_seed", "torch.cuda.manual_seed", "torch.Tensor", "torch.utils.data.DataLoader", "torch.nn.SyncBatchNorm.convert_sync_batchnorm", "torch.nn.Linear", "torch.distributed.reduce", "torch.no_grad", "torch.distributed.get_rank", "torch.nn.parallel.DistributedDataParallel", "torch.argmax" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
dvd42/synbols
[ "3f12a4d9354c7e05313fe0028a108b29409b7171" ]
[ "synbols/visualization.py" ]
[ "from matplotlib import pyplot as plt\n\nfrom .utils import make_img_grid\n\n\ndef plot_dataset(x, y, h_axis=\"char\", v_axis=\"font\", n_row=20, n_col=40, hide_axis=False):\n img_grid, h_values, v_values = make_img_grid(x, y, h_axis, v_axis, n_row, n_col)\n\n plt.tight_layout()\n\n plt.imshow(img_grid)\n\n plt.xlabel(h_axis)\n plt.ylabel(v_axis)\n\n if hide_axis:\n ax = plt.gca()\n\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n\n plt.gcf().tight_layout()\n return h_values, v_values\n" ]
[ [ "matplotlib.pyplot.gca", "matplotlib.pyplot.imshow", "matplotlib.pyplot.tight_layout", "matplotlib.pyplot.gcf", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.ylabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ashutom/tensorflow-upstream
[ "3457a2b122e50b4d44ceaaed5a663d635e5c22df", "3457a2b122e50b4d44ceaaed5a663d635e5c22df", "3457a2b122e50b4d44ceaaed5a663d635e5c22df", "3457a2b122e50b4d44ceaaed5a663d635e5c22df", "c16069c19de9e286dd664abb78d0ea421e9f32d4", "3457a2b122e50b4d44ceaaed5a663d635e5c22df", "3457a2b122e50b4d44ceaaed5a663d635e5c22df", "3457a2b122e50b4d44ceaaed5a663d635e5c22df", "3457a2b122e50b4d44ceaaed5a663d635e5c22df", "3457a2b122e50b4d44ceaaed5a663d635e5c22df", "be084bd7a4dd241eb781fc704f57bcacc5c9b6dd", "3457a2b122e50b4d44ceaaed5a663d635e5c22df", "3457a2b122e50b4d44ceaaed5a663d635e5c22df", "3457a2b122e50b4d44ceaaed5a663d635e5c22df", "3457a2b122e50b4d44ceaaed5a663d635e5c22df", "3457a2b122e50b4d44ceaaed5a663d635e5c22df", "3457a2b122e50b4d44ceaaed5a663d635e5c22df", "c16069c19de9e286dd664abb78d0ea421e9f32d4", "3457a2b122e50b4d44ceaaed5a663d635e5c22df", "3457a2b122e50b4d44ceaaed5a663d635e5c22df", "c16069c19de9e286dd664abb78d0ea421e9f32d4", "c16069c19de9e286dd664abb78d0ea421e9f32d4", "3457a2b122e50b4d44ceaaed5a663d635e5c22df", "3457a2b122e50b4d44ceaaed5a663d635e5c22df", "c16069c19de9e286dd664abb78d0ea421e9f32d4", "3457a2b122e50b4d44ceaaed5a663d635e5c22df", "be084bd7a4dd241eb781fc704f57bcacc5c9b6dd", "c16069c19de9e286dd664abb78d0ea421e9f32d4", "c16069c19de9e286dd664abb78d0ea421e9f32d4", "c16069c19de9e286dd664abb78d0ea421e9f32d4", "3457a2b122e50b4d44ceaaed5a663d635e5c22df", "c16069c19de9e286dd664abb78d0ea421e9f32d4", "3457a2b122e50b4d44ceaaed5a663d635e5c22df", "3457a2b122e50b4d44ceaaed5a663d635e5c22df", "3457a2b122e50b4d44ceaaed5a663d635e5c22df", "c16069c19de9e286dd664abb78d0ea421e9f32d4" ]
[ "tensorflow/python/autograph/pyct/transpiler.py", "tensorflow/python/keras/saving/saved_model/load.py", "tensorflow/python/framework/device_test.py", "tensorflow/python/tpu/datasets.py", "tensorflow/python/distribute/tpu_strategy_test.py", "tensorflow/python/keras/benchmarks/benchmark_util.py", "tensorflow/python/keras/tests/model_subclassing_test.py", "tensorflow/python/kernel_tests/linalg_grad_test.py", "tensorflow/python/kernel_tests/linalg/sparse/csr_sparse_matrix_grad_test.py", "tensorflow/python/tools/api/generator/create_python_api.py", "tensorflow/python/kernel_tests/decode_raw_op_test.py", "tensorflow/python/keras/distribute/distribute_coordinator_utils.py", "tensorflow/python/training/sync_replicas_optimizer.py", "tensorflow/python/keras/legacy_tf_layers/variable_scope_shim.py", "tensorflow/python/training/py_checkpoint_reader.py", "tensorflow/python/grappler/cluster.py", "tensorflow/python/keras/legacy_tf_layers/normalization_test.py", "tensorflow/tools/docs/generate2.py", "tensorflow/python/ops/bincount_ops_test.py", "tensorflow/python/kernel_tests/norm_op_test.py", "tensorflow/python/ops/numpy_ops/np_array_ops.py", "tensorflow/python/ops/stateful_random_ops.py", "tensorflow/python/debug/lib/debug_v2_ops_test.py", "tensorflow/python/data/experimental/ops/get_single_element.py", "tensorflow/python/data/experimental/kernel_tests/service/multi_process_cluster.py", "tensorflow/python/kernel_tests/sparse_to_dense_op_py_test.py", "tensorflow/compiler/tests/matrix_triangular_solve_op_test.py", "tensorflow/python/keras/layers/preprocessing/index_lookup.py", "tensorflow/python/data/kernel_tests/padded_batch_test.py", "tensorflow/compiler/tf2xla/python/xla.py", "tensorflow/python/keras/benchmarks/layer_benchmarks/layer_benchmarks_test.py", "tensorflow/python/kernel_tests/linalg/linear_operator_block_diag_test.py", "tensorflow/python/keras/distribute/keras_embedding_model_correctness_test.py", "tensorflow/python/ops/bitwise_ops_test.py", "tensorflow/python/keras/applications/vgg19.py", "tensorflow/python/distribute/multi_worker_test_base.py" ]
[ "# Copyright 2016 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\"\"\"Generic source code transformation infrastructure.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport inspect\nimport threading\nimport types\n\nimport gast\n\nfrom tensorflow.python.autograph.pyct import cache\nfrom tensorflow.python.autograph.pyct import inspect_utils\nfrom tensorflow.python.autograph.pyct import loader\nfrom tensorflow.python.autograph.pyct import naming\nfrom tensorflow.python.autograph.pyct import origin_info\nfrom tensorflow.python.autograph.pyct import parser\nfrom tensorflow.python.autograph.pyct import templates\nfrom tensorflow.python.autograph.pyct import transformer\nfrom tensorflow.python.autograph.utils import ag_logging as logging\n\n\ndef _wrap_into_factory(nodes, entity_name, inner_factory_name,\n outer_factory_name, closure_vars, factory_args,\n future_features):\n \"\"\"Wraps an AST into the body of a factory with consistent lexical context.\n\n The AST is expected to define some symbol with a name given by `entity_name`.\n\n This mechanism ensures that the resulting transformed entity has lexical\n scoping identical to that of the source entity, while allowing extra\n parametrization.\n\n Two nested factories achieve the following:\n\n 1. The inner factory dynamically creates the entity represented by `nodes`.\n 2. The inner factory is parametrized by a custom set of arguments.\n 3. The inner factory has a closure identical to that of the transformed\n entity.\n 4. The inner factory has local variables named like `args`, which `nodes` may\n use as additional parameters.\n 5. The inner factory returns the variables given by `entity_name`.\n 6. The outer factory is niladic.\n 7. The outer factory has no closure.\n 8. The outer factory creates the necessary lexical scope for the inner\n factory, so that the loaded code has the given configuration for\n closure/globals.\n 9. The outer factory returns the inner factory.\n\n Roughly speaking, the following code is generated:\n\n from __future__ import future_feature_1\n from __future__ import future_feature_2\n ...\n\n def outer_factory():\n closure_var_1 = None\n closure_var_2 = None\n ...\n\n def inner_factory(arg_1, arg_2, ...):\n <<nodes>>\n return entity\n\n return inner_factory\n\n The lexical scoping is created using dummy symbol declarations which create\n local variables in the body of the outer factory, so that the Python parser\n correctly marks them as free non-global variables upon load (that is, it\n creates cell slots for each symbol. These symbols are initialized with None,\n but their values are not expected to be used; instead, the caller is expected\n to replace them with the cells of the source entity. For more details, see:\n https://docs.python.org/3/reference/executionmodel.html#binding-of-names\n\n Args:\n nodes: Tuple[ast.AST], the source code to wrap.\n entity_name: Union[Text, ast.AST], the name of the principal entity that\n `nodes` define.\n inner_factory_name: Text, the name of the inner factory.\n outer_factory_name: Text, the name of the outer factory.\n closure_vars: Iterable[Text], names of the closure variables for the inner\n factory.\n factory_args: Iterable[Text], names of additional arguments for the\n inner factory. Useful to configure variables that the converted code can\n use. Typically, these are modules.\n future_features: Iterable[Text], names of future statements to associate the\n code with.\n\n Returns:\n ast.AST\n \"\"\"\n dummy_closure_defs = []\n for var_name in closure_vars:\n template = \"\"\"\n var_name = None\n \"\"\"\n dummy_closure_defs.extend(templates.replace(template, var_name=var_name))\n\n if future_features:\n future_imports = gast.ImportFrom(\n module='__future__',\n names=[gast.alias(name=name, asname=None) for name in future_features],\n level=0)\n else:\n future_imports = []\n\n factory_args = [\n gast.Name(name, ctx=gast.Param(), annotation=None, type_comment=None)\n for name in factory_args\n ]\n\n template = \"\"\"\n future_imports\n def outer_factory_name():\n dummy_closure_defs\n def inner_factory_name(factory_args):\n entity_defs\n return entity_name\n return inner_factory_name\n \"\"\"\n return templates.replace(\n template,\n dummy_closure_defs=dummy_closure_defs,\n entity_defs=nodes,\n entity_name=entity_name,\n factory_args=factory_args,\n future_imports=future_imports,\n inner_factory_name=inner_factory_name,\n outer_factory_name=outer_factory_name)\n\n\nclass _PythonFnFactory(object):\n \"\"\"Helper object that wraps a Python function factory.\"\"\"\n\n def __init__(self, name, freevars, extra_locals):\n \"\"\"Creates a new factory for a Python function.\n\n Args:\n name: The function name.\n freevars: The list of non-global free variables for the function.\n extra_locals: Dict[Text, Any], names and values for custom variables that\n are accessible to the generated code as local variables.\n \"\"\"\n self._name = name\n self._freevars = freevars\n self._extra_locals = extra_locals\n\n self._unbound_factory = None\n self.module = None\n self.source_map = None\n\n def create(self,\n nodes,\n namer,\n inner_factory_name='inner_factory',\n outer_factory_name='outer_factory',\n future_features=()):\n \"\"\"Initializes a function.\"\"\"\n if self._unbound_factory is not None:\n raise ValueError('double initialization; create a new object instead')\n\n inner_factory_name = namer.new_symbol(inner_factory_name, ())\n outer_factory_name = namer.new_symbol(outer_factory_name, ())\n nodes = _wrap_into_factory(nodes, self._name, inner_factory_name,\n outer_factory_name, self._freevars,\n self._extra_locals.keys(), future_features)\n\n module, _, source_map = loader.load_ast(\n nodes, include_source_map=True)\n outer_factory = getattr(module, outer_factory_name)\n self._unbound_factory = outer_factory()\n self.module = module\n self.source_map = source_map\n\n def instantiate(self,\n globals_,\n closure,\n defaults=None,\n kwdefaults=None):\n \"\"\"Creates a new function instance.\"\"\"\n if self._unbound_factory is None:\n raise ValueError('call create first')\n\n factory_code = self._unbound_factory.__code__\n factory_freevars = factory_code.co_freevars\n closure_map = dict(zip(self._freevars, closure))\n factory_closure = tuple(\n closure_map[name] for name in factory_code.co_freevars)\n if len(factory_closure) != len(closure):\n raise ValueError(\n 'closure mismatch, requested {}, but source function had {}'.format(\n self._freevars, factory_freevars))\n\n bound_factory = types.FunctionType(\n code=factory_code,\n globals=globals_,\n name=self._name,\n argdefs=(),\n closure=factory_closure)\n\n # The lint override is a false positive.\n new_fn = bound_factory(**self._extra_locals) # pylint:disable=not-callable\n\n if defaults:\n new_fn.__defaults__ = defaults\n if kwdefaults:\n new_fn.__kwdefaults__ = kwdefaults\n\n return new_fn\n\n\nclass GenericTranspiler(object):\n \"\"\"A generic transpiler for Python functions.\n\n Its interface is the `transform` API, which can process Python function\n objects. Internally, it handles parsing.\n\n Users typically subclass this, customizing the `transform_ast` method. The\n output of transformed_ast is returned directly by `transform`. Existing\n methods like `transform_function` may also be overloaded.\n\n Example:\n\n class MyTransformer(GenericTranspiler):\n\n def transform_ast(self, node, ctx):\n result = <<transform node>>\n return result\n\n transformer = MyTransfomer()\n\n result = transformer.transform(f, ...)\n # result is the output\n \"\"\"\n\n def get_transformed_name(self, node):\n \"\"\"Returns a name for the output function. Subclasses may override this.\"\"\"\n if isinstance(node, gast.Lambda):\n return 'lam'\n elif isinstance(node, gast.FunctionDef):\n return node.name\n raise ValueError('Unknown node type {}'.format(node))\n\n def transform_ast(self, node, ctx):\n \"\"\"Performs an actual transformation of a function's AST.\n\n Subclasses must implement this method, and do not usually call it.\n\n Args:\n node: One or more ast.AST nodes representing the AST to be transformed.\n ctx: transformer.Context.\n \"\"\"\n raise NotImplementedError('subclasses must override this')\n\n def transform(self, obj, user_context):\n \"\"\"Transforms a Python object.\n\n Users typically call this method.\n\n Args:\n obj: A Python object, function, type, etc.\n user_context: An opaque object (may be None) that is forwarded to\n transform_ast, through the ctx.user_context argument.\n Returns:\n The result of calling transform_function.\n\n Raises:\n NotImplementedError: if the type of obj is not handled.\n \"\"\"\n if inspect.isfunction(obj) or inspect.ismethod(obj):\n return self.transform_function(obj, user_context)\n\n raise NotImplementedError('Non-function: {}'.format(type(obj)))\n\n def _erase_arg_defaults(self, node):\n \"\"\"Erase arg default expressions, which would otherwise be unbound.\"\"\"\n args = node.args\n for i in range(len(args.defaults)):\n args.defaults[i] = parser.parse_expression('None')\n for i, d in enumerate(args.kw_defaults):\n if d is not None:\n args.kw_defaults[i] = parser.parse_expression('None')\n return node\n\n def transform_module(self, mod, user_context):\n \"\"\"Transforms a module.\n\n Subclasses may override this method. The return value is opaque.\n\n The method receives the original AST. The result is passed as-is to the\n output of `transform`.\n\n Args:\n mod: A Python module.\n user_context: An opaque object (may be None) that is forwarded to\n transform_ast, through the ctx.user_context argument.\n Returns:\n List[Tuple[Any, Any]]. By default it returns the output of transform_ast,\n evaluated on each supported member, other than modules, together with a\n `transformer.Context` containing information about the transformation\n process.\n \"\"\"\n result = []\n for member in mod.__dict__.values():\n if inspect.ismodule(member):\n continue # Not transforming modules recursively.\n try:\n result.append(self.transform(member, user_context))\n except NotImplementedError:\n pass # Skip unsupported elements.\n return result\n\n def transform_function(self, fn, user_context):\n \"\"\"Transforms a function.\n\n Subclasses may override this method. The return value is opaque.\n\n The method receives the original AST. The result is passed as-is to the\n output of `transform`.\n\n Args:\n fn: A function or lambda.\n user_context: An opaque object (may be None) that is forwarded to\n transform_ast, through the ctx.user_context argument.\n Returns:\n Tuple[Any, Any]. By default it returns the output of transform_ast,\n together with a `transformer.Context` containing information about the\n transformation process.\n \"\"\"\n future_features = inspect_utils.getfutureimports(fn)\n node, source = parser.parse_entity(fn, future_features=future_features)\n logging.log(3, 'Source code of %s:\\n\\n%s\\n', fn, source)\n\n origin_info.resolve_entity(node, source, fn)\n\n namespace = inspect_utils.getnamespace(fn)\n namer = naming.Namer(namespace)\n new_name = namer.new_symbol(self.get_transformed_name(node), ())\n entity_info = transformer.EntityInfo(\n name=new_name,\n source_code=source,\n source_file='<fragment>',\n future_features=future_features,\n namespace=namespace)\n context = transformer.Context(entity_info, namer, user_context)\n\n node = self._erase_arg_defaults(node)\n result = self.transform_ast(node, context)\n\n return result, context\n\n\nclass PyToPy(GenericTranspiler):\n \"\"\"A generic Python-to-Python transpiler.\n\n Its `transform` method offers a function-in, function-out interface.\n Internally, it takes care of parsing, caching and loading of the translated\n code.\n\n Users typically subclass this, overriding `transform_ast`.\n\n Usually, instances of this class are singletons, since each instance manages\n its own cache. The caching can be controlled by overriding `get_caching_key`.\n\n Example:\n\n class MyTransformer(PyToPy):\n\n def transform_ast(self, node, ctx):\n node = <<transform node, usually using ast.NodeTransformer classes>>\n return node\n\n transformer = MyTransfomer()\n\n new_f, module, source_map = transformer.transform_function(f, ...)\n # new_f is a function with signature identical to f\n\n The transformed function has access to the same namespace as the original\n function. To allow access to internal APIs, users may inject additional\n symbols by overriding `get_extra_locals`.\n \"\"\"\n\n def __init__(self):\n self._cache_lock = threading.RLock()\n self._cache = cache.CodeObjectCache()\n\n def get_extra_locals(self):\n \"\"\"Returns extra static local variables to be made to transformed code.\n\n Subclasses must override this.\n\n Returns:\n extra_locals: A Dict[Text, Any] containing additional variables to make\n available to the transformed code.\n \"\"\"\n raise NotImplementedError('subclasses must override this')\n\n def get_caching_key(self, user_context):\n \"\"\"Returns a unique key to use for caching.\n\n Subclasses must override this.\n\n Calls made to `transform_function` with functions that have the same code\n object and caching key will return a cached instance on subsequent\n invocations.\n\n Args:\n user_context: The context object which was passed to `transform`.\n\n Returns:\n extra_locals: A hashable.\n \"\"\"\n raise NotImplementedError('subclasses must override this')\n\n def _cached_factory(self, fn, cache_subkey):\n cached_factory = self._cache[fn][cache_subkey]\n logging.log(3, 'Cache hit for %s subkey %s: %s', fn, cache_subkey,\n cached_factory)\n return cached_factory\n\n def transform_function(self, fn, user_context):\n \"\"\"Transforms a function. See GenericTranspiler.trasnform_function.\n\n This overload wraps the parent's `transform_function`, adding caching and\n facilities to instantiate the output as a Python object. It also\n adds facilities to make new symbols available to the generated Python code,\n visible as local variables - see `get_extra_locals`.\n\n Args:\n fn: A function or lambda.\n user_context: An opaque object (may be None) that is forwarded to\n transform_ast, through the ctx.user_context argument.\n Returns:\n A tuple:\n * A function or lambda with the same signature and closure as `fn`\n * The temporary module into which the transformed function was loaded\n * The source map as a\n Dict[origin_info.LineLocation, origin_info.OriginInfo]\n \"\"\"\n cache_subkey = self.get_caching_key(user_context)\n\n if self._cache.has(fn, cache_subkey):\n # Fast path: use a lock-free check.\n factory = self._cached_factory(fn, cache_subkey)\n\n else:\n with self._cache_lock:\n # Check again under lock.\n if self._cache.has(fn, cache_subkey):\n factory = self._cached_factory(fn, cache_subkey)\n\n else:\n logging.log(1, '%s is not cached for subkey %s', fn, cache_subkey)\n # TODO(mdan): Confusing overloading pattern. Fix.\n nodes, ctx = super(PyToPy, self).transform_function(fn, user_context)\n\n if isinstance(nodes, gast.Lambda):\n nodes = gast.Assign(\n targets=[\n gast.Name(\n ctx.info.name,\n ctx=gast.Store(),\n annotation=None,\n type_comment=None)\n ],\n value=nodes)\n else:\n nodes.name = ctx.info.name\n\n if logging.has_verbosity(2):\n logging.log(2, 'Transformed %s:\\n\\n%s\\n', fn, parser.unparse(nodes))\n\n factory = _PythonFnFactory(\n ctx.info.name, fn.__code__.co_freevars, self.get_extra_locals())\n factory.create(\n nodes, ctx.namer, future_features=ctx.info.future_features)\n self._cache[fn][cache_subkey] = factory\n\n transformed_fn = factory.instantiate(\n globals_=fn.__globals__,\n closure=fn.__closure__ or (),\n defaults=fn.__defaults__,\n kwdefaults=getattr(fn, '__kwdefaults__', None))\n return transformed_fn, factory.module, factory.source_map\n", "# Copyright 2018 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\"\"\"Keras SavedModel deserialization.\"\"\"\n\nimport os\nimport re\nimport types\n\nfrom google.protobuf import message\n\nfrom tensorflow.python.eager import context\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.keras import backend\nfrom tensorflow.python.keras import regularizers\nfrom tensorflow.python.keras.engine import input_spec\nfrom tensorflow.python.keras.optimizer_v2 import optimizer_v2\nfrom tensorflow.python.keras.protobuf import saved_metadata_pb2\nfrom tensorflow.python.keras.protobuf import versions_pb2\nfrom tensorflow.python.keras.saving import saving_utils\nfrom tensorflow.python.keras.saving.saved_model import constants\nfrom tensorflow.python.keras.saving.saved_model import json_utils\nfrom tensorflow.python.keras.saving.saved_model import utils\nfrom tensorflow.python.keras.saving.saved_model.serialized_attributes import CommonEndpoints\nfrom tensorflow.python.keras.utils import generic_utils\nfrom tensorflow.python.keras.utils import metrics_utils\nfrom tensorflow.python.keras.utils.generic_utils import LazyLoader\nfrom tensorflow.python.ops.ragged import ragged_tensor\nfrom tensorflow.python.platform import gfile\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.saved_model import load as tf_load\nfrom tensorflow.python.saved_model import loader_impl\nfrom tensorflow.python.saved_model import nested_structure_coder\nfrom tensorflow.python.saved_model import revived_types\nfrom tensorflow.python.training.tracking import base as trackable\nfrom tensorflow.python.training.tracking import data_structures\nfrom tensorflow.python.util import compat\nfrom tensorflow.python.util import nest\n\n# To avoid circular dependencies between keras/engine and keras/saving,\n# code in keras/saving must delay imports.\n\n# TODO(b/134426265): Switch back to single-quotes to match the rest of the file\n# once the issue with copybara is fixed.\n# pylint:disable=g-inconsistent-quotes\nmodels_lib = LazyLoader(\"models_lib\", globals(),\n \"tensorflow.python.keras.models\")\nbase_layer = LazyLoader(\n \"base_layer\", globals(),\n \"tensorflow.python.keras.engine.base_layer\")\nlayers_module = LazyLoader(\n \"layers_module\", globals(),\n \"tensorflow.python.keras.layers\")\ninput_layer = LazyLoader(\n \"input_layer\", globals(),\n \"tensorflow.python.keras.engine.input_layer\")\nfunctional_lib = LazyLoader(\n \"functional_lib\", globals(),\n \"tensorflow.python.keras.engine.functional\")\ntraining_lib = LazyLoader(\n \"training_lib\", globals(),\n \"tensorflow.python.keras.engine.training\")\ntraining_lib_v1 = LazyLoader(\n \"training_lib_v1\", globals(),\n \"tensorflow.python.keras.engine.training_v1\")\nmetrics = LazyLoader(\"metrics\", globals(),\n \"tensorflow.python.keras.metrics\")\nrecurrent = LazyLoader(\n \"recurrent\", globals(),\n \"tensorflow.python.keras.layers.recurrent\")\n# pylint:enable=g-inconsistent-quotes\n\n\nPUBLIC_ATTRIBUTES = CommonEndpoints.all_functions.union(\n CommonEndpoints.all_checkpointable_objects)\nPUBLIC_ATTRIBUTES.add(constants.KERAS_ATTR)\n\n\ndef load(path, compile=True, options=None): # pylint: disable=redefined-builtin\n \"\"\"Loads Keras objects from a SavedModel.\n\n Any Keras layer or model saved to the SavedModel will be loaded back\n as Keras objects. Other objects are loaded as regular trackable objects (same\n as `tf.saved_model.load`).\n\n Currently, Keras saving/loading only retains the Keras object's weights,\n losses, and call function.\n\n The loaded model can be re-compiled, but the original optimizer, compiled loss\n functions, and metrics are not retained. This is temporary, and `model.save`\n will soon be able to serialize compiled models.\n\n Args:\n path: Path to SavedModel.\n compile: If true, compile the model after loading it.\n options: Optional `tf.saved_model.LoadOptions` object that specifies\n options for loading from SavedModel.\n\n\n Returns:\n Object loaded from SavedModel.\n \"\"\"\n # TODO(kathywu): Add saving/loading of optimizer, compiled losses and metrics.\n # TODO(kathywu): Add code to load from objects that contain all endpoints\n\n # Look for metadata file or parse the SavedModel\n metadata = saved_metadata_pb2.SavedMetadata()\n meta_graph_def = loader_impl.parse_saved_model(path).meta_graphs[0]\n object_graph_def = meta_graph_def.object_graph_def\n path_to_metadata_pb = os.path.join(path, constants.SAVED_METADATA_PATH)\n if gfile.Exists(path_to_metadata_pb):\n try:\n with gfile.GFile(path_to_metadata_pb, 'rb') as f:\n file_content = f.read()\n metadata.ParseFromString(file_content)\n except message.DecodeError as e:\n raise IOError('Cannot parse keras metadata {}: {}.'\n .format(path_to_metadata_pb, str(e)))\n else:\n logging.warning('SavedModel saved prior to TF 2.5 detected when loading '\n 'Keras model. Please ensure that you are saving the model '\n 'with model.save() or tf.keras.models.save_model(), *NOT* '\n 'tf.saved_model.save(). To confirm, there should be a file '\n 'named \"keras_metadata.pb\" in the SavedModel directory.')\n _read_legacy_metadata(object_graph_def, metadata)\n\n if not metadata.nodes:\n # When there are no Keras objects, return the results from the core loader\n return tf_load.load(path, options=options)\n\n # Recreate layers and metrics using the info stored in the metadata.\n keras_loader = KerasObjectLoader(metadata, object_graph_def)\n keras_loader.load_layers(compile=compile)\n\n # Generate a dictionary of all loaded nodes.\n nodes_to_load = {'root': None}\n for node_id, loaded_node in keras_loader.loaded_nodes.items():\n nodes_to_load[keras_loader.get_path(node_id)] = loaded_node\n loaded = tf_load.load_partial(path, nodes_to_load, options=options)\n\n # Finalize the loaded layers and remove the extra tracked dependencies.\n keras_loader.finalize_objects()\n keras_loader.del_tracking()\n\n model = loaded['root']\n\n # pylint: disable=protected-access\n if isinstance(model, training_lib.Model) and compile:\n # TODO(kathywu): Use compiled objects from SavedModel, instead of\n # creating new objects from the training config.\n training_config = model._serialized_attributes['metadata'].get(\n 'training_config', None)\n if training_config is not None:\n model.compile(**saving_utils.compile_args_from_training_config(\n training_config), from_serialized=True)\n saving_utils.try_build_compiled_arguments(model)\n if isinstance(model.optimizer, optimizer_v2.OptimizerV2):\n if (model.optimizer.get_slot_names()):\n logging.warning('Your optimizer uses slots. '\n 'Slots cannot be restored from saved_model, '\n 'as a result, your model is starting with '\n 'a new initialized optimizer.')\n else:\n logging.warning('No training configuration found in save file, so the '\n 'model was *not* compiled. Compile it manually.')\n # pylint: enable=protected-access\n\n # Force variables and resources to initialize.\n if not context.executing_eagerly():\n sess = backend.get_session() # Variables are initialized by this call.\n sess.run(ops.get_collection(ops.GraphKeys.TABLE_INITIALIZERS))\n\n return model\n\n\ndef _read_legacy_metadata(object_graph_def, metadata):\n \"\"\"Builds a KerasMetadata proto from the SavedModel ObjectGraphDef.\"\"\"\n # Older SavedModels store the metadata directly in the proto instead of the\n # separate pb file.\n node_paths = _generate_object_paths(object_graph_def)\n for node_id, proto in enumerate(object_graph_def.nodes):\n if (proto.WhichOneof('kind') == 'user_object' and\n proto.user_object.identifier in constants.KERAS_OBJECT_IDENTIFIERS):\n if not proto.user_object.metadata:\n raise ValueError('Unable to create a Keras model from this SavedModel. '\n 'This SavedModel was created with '\n '`tf.saved_model.save`, and lacks the Keras metadata.'\n 'Please save your Keras model by calling `model.save`'\n 'or `tf.keras.models.save_model`.')\n metadata.nodes.add(\n node_id=node_id,\n node_path=node_paths[node_id],\n version=versions_pb2.VersionDef(\n producer=1, min_consumer=1, bad_consumers=[]),\n identifier=proto.user_object.identifier,\n metadata=proto.user_object.metadata)\n\n\ndef _generate_object_paths(object_graph_def):\n \"\"\"Traverses through an ObjectGraphDef and builds a map of all node paths.\"\"\"\n paths = {0: 'root'}\n nodes_to_visit = [0]\n\n while nodes_to_visit:\n current_node = nodes_to_visit.pop()\n current_path = paths[current_node]\n for reference in object_graph_def.nodes[current_node].children:\n if reference.node_id in paths:\n continue\n paths[reference.node_id] = '{}.{}'.format(current_path,\n reference.local_name)\n nodes_to_visit.append(reference.node_id)\n\n return paths\n\n\ndef _is_graph_network(layer):\n \"\"\"Determines whether the layer is a graph network.\"\"\"\n # pylint: disable=protected-access\n if isinstance(layer, RevivedNetwork):\n return False\n elif isinstance(layer, functional_lib.Functional):\n return (layer._is_graph_network or\n isinstance(layer, models_lib.Sequential))\n return False\n\n\nclass KerasObjectLoader(object):\n \"\"\"Loader that recreates Keras objects (e.g. layers, models).\n\n Layers and models are revived from either the config or SavedModel following\n these rules:\n 1. If object is a graph network (i.e. Sequential or Functional) then it will\n be initialized using the structure from the config only after the children\n layers have been created. Graph networks must be initialized with inputs\n and outputs, so all child layers must be created beforehand.\n 2. If object's config exists and the class can be found, then revive from\n config.\n 3. Object may have already been created if its parent was revived from config.\n In this case, do nothing.\n 4. If nothing of the above applies, compose the various artifacts from the\n SavedModel to create a subclassed layer or model. At this time, custom\n metrics are not supported.\n\n \"\"\"\n\n def __init__(self, metadata, object_graph_def):\n self._metadata = {x.node_id: x for x in metadata.nodes}\n self._proto = object_graph_def\n\n self._node_paths = {node_data.node_id: node_data.node_path\n for node_data in metadata.nodes}\n self.loaded_nodes = {} # Maps node path -> loaded node\n\n # Store all node ids that have already been traversed when tracking nodes\n # that were recreated from the config.\n self._traversed_nodes_from_config = set()\n\n # Maps model id -> (blank model obj, list of child layer or their node ids)\n # This tracks all layers in functional and sequential models. These models\n # are only reconstructed after all of their child layers have been created.\n self.model_layer_dependencies = {}\n self._models_to_reconstruct = []\n\n def del_tracking(self):\n \"\"\"Removes tracked references that are only used when loading the model.\"\"\"\n # Now that the node object has been fully loaded, and the checkpoint has\n # been restored, the object no longer needs to track objects added from\n # SerializedAttributes. (Note that saving a training checkpoint still\n # functions correctly, because layers and variables are tracked separately\n # by the Layer object.)\n # TODO(kathywu): Instead of outright deleting these nodes (which would\n # make restoring from a different checkpoint tricky), mark them as extra\n # dependencies that are OK to overwrite.\n for node in self.loaded_nodes.values():\n node = node[0]\n if not isinstance(node, base_layer.Layer):\n # Loaded nodes can contain other trackable objects created when\n # loading layers from the config, such as variables.\n continue\n for name in PUBLIC_ATTRIBUTES:\n node._delete_tracking(name) # pylint: disable=protected-access\n\n if isinstance(node, functional_lib.Functional):\n # Delete the temporary layer dependencies, which were used to restore\n # the checkpointed values. When the model is live, the user can delete\n # or add layers to the model at any time, so these layer dependencies\n # may be obsolete.\n dependencies = list(node._self_unconditional_dependency_names) # pylint: disable=protected-access\n for name in dependencies:\n if re.match(r'^layer(_with_weights)?-[\\d+]', name) is not None:\n node._delete_tracking(name) # pylint: disable=protected-access\n\n def _add_children_recreated_from_config(self, obj, proto, node_id):\n \"\"\"Recursively records objects recreated from config.\"\"\"\n # pylint: disable=protected-access\n if node_id in self._traversed_nodes_from_config:\n return\n\n parent_path = self._node_paths[node_id]\n self._traversed_nodes_from_config.add(node_id)\n obj._maybe_initialize_trackable()\n if isinstance(obj, base_layer.Layer) and not obj.built:\n metadata = json_utils.decode(self._metadata[node_id].metadata)\n self._try_build_layer(obj, node_id, metadata.get('build_input_shape'))\n\n # Create list of all possible children\n children = []\n # Look for direct children\n for reference in proto.children:\n obj_child = obj._lookup_dependency(reference.local_name)\n children.append((obj_child, reference.node_id, reference.local_name))\n\n # Add metrics that may have been added to the layer._metrics list.\n # This is stored in the SavedModel as layer.keras_api.layer_metrics in\n # SavedModels created after Tf 2.2.\n metric_list_node_id = self._search_for_child_node(\n node_id, [constants.KERAS_ATTR, 'layer_metrics'])\n if metric_list_node_id is not None and hasattr(obj, '_metrics'):\n obj_metrics = {m.name: m for m in obj._metrics}\n for reference in self._proto.nodes[metric_list_node_id].children:\n metric = obj_metrics.get(reference.local_name)\n if metric is not None:\n metric_path = '{}.layer_metrics.{}'.format(constants.KERAS_ATTR,\n reference.local_name)\n children.append((metric, reference.node_id, metric_path))\n\n for (obj_child, child_id, child_name) in children:\n child_proto = self._proto.nodes[child_id]\n\n if not isinstance(obj_child, trackable.Trackable):\n continue\n if (child_proto.user_object.identifier in\n revived_types.registered_identifiers()):\n setter = revived_types.get_setter(child_proto.user_object)\n elif obj_child._object_identifier in constants.KERAS_OBJECT_IDENTIFIERS:\n setter = _revive_setter\n else:\n setter = setattr\n # pylint: enable=protected-access\n\n if child_id in self.loaded_nodes:\n if self.loaded_nodes[child_id][0] is not obj_child:\n # This means that the same trackable object is referenced by two\n # different objects that were recreated from the config.\n logging.warning(\n 'Looks like there is an object (perhaps variable or '\n 'layer) that is shared between different layers/models. '\n 'This may cause issues when restoring the variable '\n 'values. Object: {}'.format(obj_child))\n continue\n\n # Overwrite variable names with the ones saved in the SavedModel.\n if (child_proto.WhichOneof('kind') == 'variable' and\n child_proto.variable.name):\n obj_child._handle_name = child_proto.variable.name + ':0' # pylint: disable=protected-access\n\n if isinstance(obj_child, data_structures.TrackableDataStructure):\n setter = lambda *args: None\n\n child_path = '{}.{}'.format(parent_path, child_name)\n self._node_paths[child_id] = child_path\n self._add_children_recreated_from_config(\n obj_child, child_proto, child_id)\n self.loaded_nodes[child_id] = obj_child, setter\n\n def load_layers(self, compile=True): # pylint: disable=redefined-builtin\n \"\"\"Load all layer nodes from the metadata.\"\"\"\n # Load metrics after models and layers, since it's likely that models\n # and layers will create the metric when initialized (this avoids wasting\n # time by creating objects multiple times).\n metric_list = []\n for node_metadata in self._metadata.values():\n if node_metadata.identifier == constants.METRIC_IDENTIFIER:\n metric_list.append(node_metadata)\n continue\n\n self.loaded_nodes[node_metadata.node_id] = self._load_layer(\n node_metadata.node_id, node_metadata.identifier,\n node_metadata.metadata)\n\n for node_metadata in metric_list:\n try:\n self.loaded_nodes[node_metadata.node_id] = self._load_layer(\n node_metadata.node_id, node_metadata.identifier,\n node_metadata.metadata)\n except ValueError:\n # Metrics are only needed when the model is compiled later. We ignore\n # errors when trying to load custom metrics when `compile=False` until\n # custom metrics are serialized properly (b/135550038).\n if compile:\n raise\n logging.warning('Unable to restore custom metric. Please ensure that '\n 'the layer implements `get_config` and `from_config` '\n 'when saving. In addition, please use the '\n '`custom_objects` arg when calling `load_model()`.')\n\n def _load_layer(self, node_id, identifier, metadata):\n \"\"\"Load a single layer from a SavedUserObject proto.\"\"\"\n metadata = json_utils.decode(metadata)\n\n # If node was already created\n if node_id in self.loaded_nodes:\n node, setter = self.loaded_nodes[node_id]\n\n # Revive setter requires the object to have a `_serialized_attributes`\n # property. Add it here.\n _maybe_add_serialized_attributes(node, metadata)\n\n config = metadata.get('config')\n if _is_graph_network(node) and generic_utils.validate_config(config):\n child_nodes = self._get_child_layer_node_ids(node_id)\n self.model_layer_dependencies[node_id] = (node, child_nodes)\n if not child_nodes:\n self._models_to_reconstruct.append(node_id)\n return node, setter\n\n # Detect whether this object can be revived from the config. If not, then\n # revive from the SavedModel instead.\n obj, setter = self._revive_from_config(identifier, metadata, node_id)\n if obj is None:\n obj, setter = revive_custom_object(identifier, metadata)\n\n # Add an attribute that stores the extra functions/objects saved in the\n # SavedModel. Most of these functions/objects are ignored, but some are\n # used later in the loading process (e.g. the list of regularization\n # losses, or the training config of compiled models).\n _maybe_add_serialized_attributes(obj, metadata)\n return obj, setter\n\n def _revive_from_config(self, identifier, metadata, node_id):\n \"\"\"Revives a layer/model from config, or returns None.\"\"\"\n if identifier == constants.METRIC_IDENTIFIER:\n obj = self._revive_metric_from_config(metadata)\n else:\n obj = (\n self._revive_graph_network(identifier, metadata, node_id) or\n self._revive_layer_or_model_from_config(metadata, node_id))\n\n if obj is None:\n return None, None\n\n setter = self._config_node_setter(_revive_setter)\n self._add_children_recreated_from_config(\n obj, self._proto.nodes[node_id], node_id)\n return obj, setter\n\n def _revive_graph_network(self, identifier, metadata, node_id):\n \"\"\"Revives a graph network from config.\"\"\"\n # Determine whether the metadata contains information for reviving a\n # functional or Sequential model.\n config = metadata.get('config')\n if not generic_utils.validate_config(config):\n return None\n\n class_name = compat.as_str(metadata['class_name'])\n if generic_utils.get_registered_object(class_name) is not None:\n return None\n model_is_functional_or_sequential = (\n metadata.get('is_graph_network', False) or\n class_name == 'Sequential' or\n class_name == 'Functional')\n if not model_is_functional_or_sequential:\n return None\n\n # Revive functional and sequential models as blank model objects for now (\n # must be initialized to enable setattr tracking and attribute caching).\n # Reconstruction of the network is deferred until all of the model's layers\n # have been revived.\n if class_name == 'Sequential':\n model = models_lib.Sequential(name=config['name'])\n # The model is a custom Sequential model.\n elif identifier == constants.SEQUENTIAL_IDENTIFIER:\n # Uses the custom class name, since the config does not have one.\n model = models_lib.Sequential(name=class_name)\n else:\n model = models_lib.Functional(\n inputs=[], outputs=[], name=config['name'])\n\n # Record this model and its layers. This will later be used to reconstruct\n # the model.\n layers = self._get_child_layer_node_ids(node_id)\n self.model_layer_dependencies[node_id] = (model, layers)\n if not layers:\n self._models_to_reconstruct.append(node_id)\n return model\n\n def _revive_layer_or_model_from_config(self, metadata, node_id):\n \"\"\"Revives a layer/custom model from config; returns None if infeasible.\"\"\"\n # Check that the following requirements are met for reviving from config:\n # 1. Object can be deserialized from config.\n # 2. If the object needs to be built, then the build input shape can be\n # found.\n class_name = metadata.get('class_name')\n config = metadata.get('config')\n shared_object_id = metadata.get('shared_object_id')\n must_restore_from_config = metadata.get('must_restore_from_config')\n if not generic_utils.validate_config(config):\n return None\n\n try:\n obj = layers_module.deserialize(\n generic_utils.serialize_keras_class_and_config(\n class_name, config, shared_object_id=shared_object_id))\n except ValueError:\n if must_restore_from_config:\n raise RuntimeError(\n 'Unable to restore a layer of class {cls}. Layers of '\n 'class {cls} require that the class be provided to '\n 'the model loading code, either by registering the '\n 'class using @keras.utils.register_keras_serializable '\n 'on the class def and including that file in your '\n 'program, or by passing the class in a '\n 'keras.utils.CustomObjectScope that wraps this load '\n 'call.'.format(cls=class_name))\n else:\n return None\n\n # Use the dtype, name, and trainable status. Often times these are not\n # specified in custom configs, so retrieve their values from the metadata.\n # pylint: disable=protected-access\n obj._name = metadata['name']\n if metadata.get('trainable') is not None:\n obj.trainable = metadata['trainable']\n if metadata.get('dtype') is not None:\n obj._set_dtype_policy(metadata['dtype'])\n if metadata.get('stateful') is not None:\n obj.stateful = metadata['stateful']\n # Restore model save spec for subclassed models. (layers do not store a\n # SaveSpec)\n if isinstance(obj, training_lib.Model):\n save_spec = metadata.get('save_spec')\n if save_spec is not None:\n obj._set_save_spec(save_spec)\n # pylint: enable=protected-access\n\n build_input_shape = metadata.get('build_input_shape')\n built = self._try_build_layer(obj, node_id, build_input_shape)\n\n if not built:\n # If the layer cannot be built, revive a custom layer instead.\n return None\n return obj\n\n def _revive_metric_from_config(self, metadata):\n \"\"\"Revives a metric object using the config saved in the metadata.\"\"\"\n class_name = compat.as_str(metadata['class_name'])\n config = metadata.get('config')\n\n if not generic_utils.validate_config(config):\n return None\n\n try:\n obj = metrics.deserialize(\n generic_utils.serialize_keras_class_and_config(class_name, config))\n except ValueError:\n return None\n\n build_input_shape = metadata.get('build_input_shape')\n if build_input_shape is not None and hasattr(obj, '_build'):\n obj._build(build_input_shape) # pylint: disable=protected-access\n\n return obj\n\n def _try_build_layer(self, obj, node_id, build_input_shape):\n \"\"\"Attempts to build the layer.\"\"\"\n if obj.built or hasattr(obj.build, '_is_default'):\n obj.built = True\n return True\n\n if build_input_shape is None:\n build_input_shape = self._infer_inputs(node_id, convert_to_shapes=True)\n\n if build_input_shape is not None:\n obj.build(build_input_shape)\n base_layer.Layer.build(obj, build_input_shape)\n return True\n\n return False\n\n def _load_edges(self):\n \"\"\"Add edges for all nodes that are not waiting on initialization.\"\"\"\n for node_id, proto in enumerate(self._proto.nodes):\n if node_id not in self.model_layer_dependencies:\n self._add_object_graph_edges(proto, node_id)\n\n def get_path(self, node_id):\n return self._node_paths[node_id]\n\n def finalize_objects(self):\n \"\"\"Finish setting up Keras objects.\n\n This function is executed after all objects and functions have been created.\n Call functions and losses are attached to each layer, and once all layers\n have been fully set up, graph networks are initialized.\n\n Subclassed models that are revived from the SavedModel are treated like\n layers, and have their call/loss functions attached here.\n \"\"\"\n # Finish setting up layers and subclassed models. This step attaches call\n # functions and losses to each object, and sets model inputs/outputs.\n layers_revived_from_config = []\n layers_revived_from_saved_model = []\n for node_id, (node, _) in self.loaded_nodes.items():\n if (not isinstance(node, base_layer.Layer) or\n # Don't finalize models until all layers have finished loading.\n node_id in self.model_layer_dependencies):\n continue\n\n self._unblock_model_reconstruction(node_id, node)\n\n if isinstance(node, input_layer.InputLayer):\n continue\n elif isinstance(node, metrics.Metric):\n continue\n\n if isinstance(node, (RevivedLayer, RevivedInputLayer)):\n layers_revived_from_saved_model.append(node)\n else:\n layers_revived_from_config.append(node)\n\n _finalize_saved_model_layers(layers_revived_from_saved_model)\n _finalize_config_layers(layers_revived_from_config)\n\n # Initialize graph networks, now that layer dependencies have been resolved.\n self._reconstruct_all_models()\n\n def _unblock_model_reconstruction(self, layer_id, layer):\n \"\"\"Removes layer from blocking model reconstruction.\"\"\"\n for model_id, v in self.model_layer_dependencies.items():\n _, layers = v\n if layer_id not in layers:\n continue\n layers[layers.index(layer_id)] = layer\n if all(isinstance(x, base_layer.Layer) for x in layers):\n self._models_to_reconstruct.append(model_id)\n\n def _reconstruct_all_models(self):\n \"\"\"Reconstructs the network structure of all models.\"\"\"\n all_initialized_models = set()\n while self._models_to_reconstruct:\n model_id = self._models_to_reconstruct.pop(0)\n all_initialized_models.add(model_id)\n model, layers = self.model_layer_dependencies[model_id]\n self._reconstruct_model(model_id, model, layers)\n _finalize_config_layers([model])\n\n if all_initialized_models != set(self.model_layer_dependencies.keys()):\n # This should not happen.\n uninitialized_model_ids = (\n set(self.model_layer_dependencies.keys()) - all_initialized_models)\n uninitialized_model_names = [\n self.model_layer_dependencies[model_id][0].name\n for model_id in uninitialized_model_ids]\n raise ValueError('Error when loading from SavedModel -- the following '\n 'models could not be initialized: {}'\n .format(uninitialized_model_names))\n\n def _reconstruct_model(self, model_id, model, layers):\n \"\"\"Reconstructs the network structure.\"\"\"\n config = json_utils.decode(self._metadata[model_id].metadata)['config']\n\n # Set up model inputs\n if model.inputs:\n # Inputs may already be created if the model is instantiated in another\n # object's __init__.\n pass\n elif isinstance(model, models_lib.Sequential):\n if not layers or not isinstance(layers[0], input_layer.InputLayer):\n if config['layers'][0]['class_name'] == 'InputLayer':\n layers.insert(0, input_layer.InputLayer.from_config(\n config['layers'][0]['config']))\n elif 'batch_input_shape' in config['layers'][0]['config']:\n batch_input_shape = config['layers'][0]['config']['batch_input_shape']\n layers.insert(0, input_layer.InputLayer(\n input_shape=batch_input_shape[1:],\n batch_size=batch_input_shape[0],\n dtype=layers[0].dtype,\n name=layers[0].name + '_input'))\n model.__init__(layers, name=config['name'])\n if not model.inputs:\n first_layer = self._get_child_layer_node_ids(model_id)[0]\n input_specs = self._infer_inputs(first_layer)\n input_shapes = self._infer_inputs(first_layer, convert_to_shapes=True)\n model._set_inputs(input_specs) # pylint: disable=protected-access\n if not model.built and not isinstance(input_specs, dict):\n model.build(input_shapes)\n else: # Reconstruct functional model\n (inputs, outputs,\n created_layers) = functional_lib.reconstruct_from_config(\n config, created_layers={layer.name: layer for layer in layers})\n model.__init__(inputs, outputs, name=config['name'])\n functional_lib.connect_ancillary_layers(model, created_layers)\n\n # Set model dtype.\n _set_network_attributes_from_metadata(model)\n\n # Unblock models that are dependent on this model.\n self._unblock_model_reconstruction(model_id, model)\n\n def _get_child_layer_node_ids(self, node_id):\n \"\"\"Returns the node ids of each layer in a Sequential/Functional model.\"\"\"\n # Sequential and Functional track layers with names following the format\n # \"layer-N\". Use this to generate the list of layers.\n num_layers = 0\n child_layers = {}\n pattern = re.compile('layer-(\\\\d+)')\n\n for child in self._proto.nodes[node_id].children:\n m = pattern.match(child.local_name)\n if m is None:\n continue\n layer_n = int(m.group(1))\n num_layers = max(layer_n + 1, num_layers)\n child_layers[layer_n] = child.node_id\n\n ordered = []\n for n in range(num_layers):\n child = child_layers.get(n)\n if child is None:\n break\n ordered.append(child)\n return ordered\n\n def _search_for_child_node(self, parent_id, path_to_child):\n \"\"\"Returns node id of child node.\n\n A helper method for traversing the object graph proto.\n\n As an example, say that the object graph proto in the SavedModel contains an\n object with the following child and grandchild attributes:\n\n `parent.child_a.child_b`\n\n This method can be used to retrieve the node id of `child_b` using the\n parent's node id by calling:\n\n `_search_for_child_node(parent_id, ['child_a', 'child_b'])`.\n\n Args:\n parent_id: node id of parent node\n path_to_child: list of children names.\n\n Returns:\n node_id of child, or None if child isn't found.\n \"\"\"\n if not path_to_child:\n return parent_id\n\n for child in self._proto.nodes[parent_id].children:\n if child.local_name == path_to_child[0]:\n return self._search_for_child_node(child.node_id, path_to_child[1:])\n return None\n\n def _infer_inputs(self, layer_node_id, convert_to_shapes=False):\n \"\"\"Infers input shape of layer from SavedModel functions.\"\"\"\n coder = nested_structure_coder.StructureCoder()\n call_fn_id = self._search_for_child_node(\n layer_node_id, ['call_and_return_all_conditional_losses'])\n if call_fn_id is None:\n return None\n\n concrete_functions = (\n self._proto.nodes[call_fn_id].function.concrete_functions)\n if not concrete_functions:\n return None\n call_fn_name = concrete_functions[0]\n call_fn_proto = self._proto.concrete_functions[call_fn_name]\n structured_input_signature = coder.decode_proto(\n call_fn_proto.canonicalized_input_signature)\n inputs = structured_input_signature[0][0]\n if convert_to_shapes:\n return nest.map_structure(lambda spec: spec.shape, inputs)\n else:\n return inputs\n\n def _config_node_setter(self, setter):\n \"\"\"Creates edges for nodes that are recreated from config.\"\"\"\n def setattr_wrapper(obj, name, value):\n # Avoid overwriting attributes of objects recreated from the config.\n if obj._lookup_dependency(name) is None: # pylint: disable=protected-access\n setter(obj, name, value)\n return setattr_wrapper\n\n\ndef _finalize_saved_model_layers(layers):\n \"\"\"Runs the final steps of loading Keras Layers from SavedModel.\"\"\"\n # pylint: disable=protected-access\n # 1. Set up call functions for all layers initialized from the SavedModel (\n # and not the config)\n for layer in layers:\n layer.built = True\n layer_call = getattr(_get_keras_attr(layer),\n 'call_and_return_conditional_losses', None)\n if layer_call and layer_call.concrete_functions:\n layer.call = utils.use_wrapped_call(\n layer, layer_call, return_method=True)\n expects_training_arg = layer._serialized_attributes['metadata'][\n 'expects_training_arg']\n if 'training' in layer_call.function_spec.arg_names:\n # This could change the value of `expects_training_arg` if this layer\n # doesn't expect a training arg, but has a child layer that does.\n expects_training_arg = True\n layer._init_call_fn_args(expects_training_arg)\n else:\n layer.call = types.MethodType(\n _unable_to_call_layer_due_to_serialization_issue, layer)\n\n for layer in layers:\n # 2. Set model inputs and outputs.\n if isinstance(layer, RevivedNetwork):\n _set_network_attributes_from_metadata(layer)\n\n if hasattr(_get_keras_attr(layer), 'call_and_return_conditional_losses'):\n call_fn = _get_keras_attr(layer).call_and_return_conditional_losses\n if not call_fn.concrete_functions:\n continue\n if call_fn.input_signature is None:\n inputs = infer_inputs_from_restored_call_function(call_fn)\n else:\n inputs = call_fn.input_signature[0]\n layer._set_inputs(inputs) # pylint: disable=protected-access\n\n # 3. Add losses that aren't generated by the layer.call function.\n _restore_layer_unconditional_losses(layer)\n _restore_layer_activation_loss(layer)\n\n # 4. Restore metrics list\n _restore_layer_metrics(layer)\n\n # pylint: enable=protected-access\n\n\ndef _unable_to_call_layer_due_to_serialization_issue(\n layer, *unused_args, **unused_kwargs):\n \"\"\"Replaces the `layer.call` if the layer was not fully serialized.\n\n Keras Model/Layer serialization is relatively relaxed because SavedModels\n are not always loaded back as keras models. Thus, when there is an issue\n tracing a non-signature function, a warning is logged instead of raising an\n error. This results in a SavedModel where the model's call function is saved,\n but the internal layer call functions are not.\n\n When deserialized with `tf.keras.models.load_model`, the internal layers\n which do not have serialized call functions should raise an error when called.\n\n Args:\n layer: Layer without the serialized call function.\n\n Raises:\n ValueError\n \"\"\"\n\n raise ValueError(\n 'Cannot call custom layer {} of type {}, because the call function was '\n 'not serialized to the SavedModel.'\n 'Please try one of the following methods to fix this issue:'\n '\\n\\n(1) Implement `get_config` and `from_config` in the layer/model '\n 'class, and pass the object to the `custom_objects` argument when '\n 'loading the model. For more details, see: '\n 'https://www.tensorflow.org/guide/keras/save_and_serialize'\n '\\n\\n(2) Ensure that the subclassed model or layer overwrites `call` '\n 'and not `__call__`. The input shape and dtype will be automatically '\n 'recorded when the object is called, and used when saving. To manually '\n 'specify the input shape/dtype, decorate the call function with '\n '`@tf.function(input_signature=...)`.'.format(layer.name, type(layer)))\n\n\ndef _finalize_config_layers(layers):\n \"\"\"Runs the final steps of loading Keras Layers from config.\"\"\"\n for layer in layers:\n # It is assumed that layers define their unconditional losses after being\n # recreated from the config and built. The exceptions to this\n # are Functional and Sequential models, which only store conditional losses\n # (losses dependent on the inputs) in the config. Unconditional losses like\n # weight regularization must be revived from the SavedModel.\n if _is_graph_network(layer):\n _restore_layer_unconditional_losses(layer)\n\n # Some layers, like Dense, record their activation loss function in the\n # config. However, not all layers do this, so the activation loss may be\n # missing when restored from the config/hdf5.\n # TODO(kathywu): Investigate ways to improve the config to ensure consistent\n # loading behavior between HDF5 and SavedModel.\n _restore_layer_activation_loss(layer)\n\n # Restore metrics list.\n _restore_layer_metrics(layer)\n\n # Restore RNN layer states.\n if (isinstance(layer, recurrent.RNN) and\n layer.stateful and\n hasattr(_get_keras_attr(layer), 'states')):\n layer.states = getattr(_get_keras_attr(layer), 'states', None)\n for variable in nest.flatten(layer.states):\n backend.track_variable(variable)\n\n # Perform any layer defined finalization of the layer state.\n layer.finalize_state()\n\n\ndef _finalize_metric(metric):\n metric.update_state = types.MethodType(metrics_utils.update_state_wrapper(\n metric.keras_api.update_state), metric)\n metric.result = metric.keras_api.result\n\n\ndef _restore_layer_unconditional_losses(layer):\n \"\"\"Restore unconditional losses from SavedModel.\"\"\"\n if hasattr(_get_keras_attr(layer), 'layer_regularization_losses'):\n losses = getattr(_get_keras_attr(layer), 'layer_regularization_losses', [])\n else:\n # Some earlier SavedModels may not have layer_regularization_losses\n # serialized separately. Fall back to using the regularization_losses\n # list if it does not exist.\n losses = layer._serialized_attributes.get('regularization_losses', []) # pylint: disable=protected-access\n for loss in losses:\n layer.add_loss(loss)\n\n\ndef _restore_layer_activation_loss(layer):\n \"\"\"Restore actiation loss from SavedModel.\"\"\"\n # Use wrapped activity regularizer function if the layer's activity\n # regularizer wasn't created during initialization.\n activity_regularizer = getattr(_get_keras_attr(layer),\n 'activity_regularizer_fn', None)\n if activity_regularizer and not layer.activity_regularizer:\n try:\n layer.activity_regularizer = activity_regularizer\n except AttributeError:\n # This may happen if a layer wrapper is saved with an activity\n # regularizer. The wrapper object's activity regularizer is unsettable.\n pass\n\n\ndef revive_custom_object(identifier, metadata):\n \"\"\"Revives object from SavedModel.\"\"\"\n if ops.executing_eagerly_outside_functions():\n model_class = training_lib.Model\n else:\n model_class = training_lib_v1.Model\n\n revived_classes = {\n constants.INPUT_LAYER_IDENTIFIER: (\n RevivedInputLayer, input_layer.InputLayer),\n constants.LAYER_IDENTIFIER: (RevivedLayer, base_layer.Layer),\n constants.MODEL_IDENTIFIER: (RevivedNetwork, model_class),\n constants.NETWORK_IDENTIFIER: (RevivedNetwork, functional_lib.Functional),\n constants.SEQUENTIAL_IDENTIFIER: (RevivedNetwork, models_lib.Sequential),\n }\n parent_classes = revived_classes.get(identifier, None)\n\n if parent_classes is not None:\n parent_classes = revived_classes[identifier]\n revived_cls = type(\n compat.as_str(metadata['class_name']), parent_classes, {})\n return revived_cls._init_from_metadata(metadata) # pylint: disable=protected-access\n else:\n raise ValueError('Unable to restore custom object of type {} currently. '\n 'Please make sure that the layer implements `get_config`'\n 'and `from_config` when saving. In addition, please use '\n 'the `custom_objects` arg when calling `load_model()`.'\n .format(identifier))\n\n\ndef _restore_layer_metrics(layer):\n metrics_list = getattr(_get_keras_attr(layer), 'layer_metrics', {})\n layer_metrics = {m.name: m for m in layer._metrics} # pylint: disable=protected-access\n for name, metric in metrics_list.items():\n if name not in layer_metrics:\n # Metrics may be added during initialization/building of custom layers.\n layer._metrics.append(metric) # pylint: disable=protected-access\n\n\n# TODO(kathywu): Centrally define keys and functions for both serialization and\n# deserialization.\nclass RevivedLayer(object):\n \"\"\"Keras layer loaded from a SavedModel.\"\"\"\n\n @classmethod\n def _init_from_metadata(cls, metadata):\n \"\"\"Create revived layer from metadata stored in the SavedModel proto.\"\"\"\n init_args = dict(\n name=metadata['name'],\n trainable=metadata['trainable'])\n if metadata.get('dtype') is not None:\n init_args['dtype'] = metadata['dtype']\n if metadata.get('batch_input_shape') is not None:\n init_args['batch_input_shape'] = metadata['batch_input_shape']\n\n revived_obj = cls(**init_args)\n\n with utils.no_automatic_dependency_tracking_scope(revived_obj):\n # pylint:disable=protected-access\n revived_obj._expects_training_arg = metadata['expects_training_arg']\n config = metadata.get('config')\n if generic_utils.validate_config(config):\n revived_obj._config = config\n if metadata.get('input_spec') is not None:\n revived_obj.input_spec = recursively_deserialize_keras_object(\n metadata['input_spec'],\n module_objects={'InputSpec': input_spec.InputSpec})\n if metadata.get('activity_regularizer') is not None:\n revived_obj.activity_regularizer = regularizers.deserialize(\n metadata['activity_regularizer'])\n if metadata.get('_is_feature_layer') is not None:\n revived_obj._is_feature_layer = metadata['_is_feature_layer']\n if metadata.get('stateful') is not None:\n revived_obj.stateful = metadata['stateful']\n # pylint:enable=protected-access\n\n return revived_obj, _revive_setter\n\n @property\n def keras_api(self):\n return self._serialized_attributes.get(constants.KERAS_ATTR, None)\n\n def get_config(self):\n if hasattr(self, '_config'):\n return self._config\n else:\n raise NotImplementedError\n\n\ndef _revive_setter(layer, name, value):\n \"\"\"Setter function that saves some attributes to separate dictionary.\"\"\"\n # Many attributes in the SavedModel conflict with properties defined in\n # Layer and Model. Save these attributes to a separate dictionary.\n if name in PUBLIC_ATTRIBUTES:\n # pylint: disable=protected-access\n if isinstance(value, trackable.Trackable):\n layer._track_trackable(value, name=name)\n layer._serialized_attributes[name] = value\n # pylint: enable=protected-access\n elif (isinstance(layer, functional_lib.Functional) and\n re.match(r'^layer(_with_weights)?-[\\d+]', name) is not None):\n # Edges named \"layer-n\" or \"layer_with_weights-n\", which are tracked in\n # network._track_layers, should not be added as an attribute. They should\n # be temporarily added as a dependency so that checkpointed values can be\n # restored. These dependencies are manually deleted in\n # KerasObjectLoader.del_tracking.\n\n # Set `overwrite=True` in the case that `layer` already tracks a different\n # layer-n. This may cause variable values to not be loaded properly in the\n # original layer-n, but we already warn the users about this\n # (ctrl-f \"shared between different layers/models\").\n layer._track_trackable(value, name, overwrite=True) # pylint: disable=protected-access\n elif getattr(layer, name, None) is not None:\n # Don't overwrite already defined attributes.\n pass\n else:\n setattr(layer, name, value)\n\n\nclass RevivedInputLayer(object):\n \"\"\"InputLayer loaded from a SavedModel.\"\"\"\n\n @classmethod\n def _init_from_metadata(cls, metadata):\n \"\"\"Revives the saved InputLayer from the Metadata.\"\"\"\n init_args = dict(\n name=metadata['name'],\n dtype=metadata['dtype'],\n sparse=metadata['sparse'],\n ragged=metadata['ragged'],\n batch_input_shape=metadata['batch_input_shape'])\n revived_obj = cls(**init_args)\n with utils.no_automatic_dependency_tracking_scope(revived_obj):\n revived_obj._config = metadata['config'] # pylint:disable=protected-access\n\n return revived_obj, setattr\n\n def get_config(self):\n return self._config\n\n\ndef recursively_deserialize_keras_object(config, module_objects=None):\n \"\"\"Deserialize Keras object from a nested structure.\"\"\"\n if isinstance(config, dict):\n if 'class_name' in config:\n return generic_utils.deserialize_keras_object(\n config, module_objects=module_objects)\n else:\n return {key: recursively_deserialize_keras_object(config[key],\n module_objects)\n for key in config}\n if isinstance(config, (tuple, list)):\n return [recursively_deserialize_keras_object(x, module_objects)\n for x in config]\n else:\n raise ValueError('Unable to decode config: {}'.format(config))\n\n\ndef get_common_shape(x, y):\n \"\"\"Find a `TensorShape` that is compatible with both `x` and `y`.\"\"\"\n if x is None != y is None:\n raise RuntimeError(\n 'Cannot find a common shape when LHS shape is None but RHS shape '\n 'is not (or vice versa): %s vs. %s' % (x, y))\n if x is None:\n return None # The associated input was not a Tensor, no shape generated.\n if not isinstance(x, tensor_shape.TensorShape):\n raise TypeError('Expected x to be a TensorShape but saw %s' % (x,))\n if not isinstance(y, tensor_shape.TensorShape):\n raise TypeError('Expected y to be a TensorShape but saw %s' % (y,))\n if x.rank != y.rank or x.rank is None:\n return tensor_shape.TensorShape(None)\n dims = []\n for dim_x, dim_y in zip(x.dims, y.dims):\n if (dim_x != dim_y\n or tensor_shape.dimension_value(dim_x) is None\n or tensor_shape.dimension_value(dim_y) is None):\n dims.append(None)\n else:\n dims.append(tensor_shape.dimension_value(dim_x))\n return tensor_shape.TensorShape(dims)\n\n\ndef infer_inputs_from_restored_call_function(fn):\n \"\"\"Returns TensorSpec of inputs from a restored call function.\n\n Args:\n fn: Restored layer call function. It is assumed that `fn` has at least\n one concrete function and that the inputs are in the first argument.\n\n Returns:\n TensorSpec of call function inputs.\n \"\"\"\n def common_spec(x, y):\n common_shape = get_common_shape(x.shape, y.shape)\n if isinstance(x, sparse_tensor.SparseTensorSpec):\n return sparse_tensor.SparseTensorSpec(common_shape, x.dtype)\n elif isinstance(x, ragged_tensor.RaggedTensorSpec):\n return ragged_tensor.RaggedTensorSpec(common_shape, x.dtype)\n return tensor_spec.TensorSpec(common_shape, x.dtype, x.name)\n\n spec = fn.concrete_functions[0].structured_input_signature[0][0]\n for concrete in fn.concrete_functions[1:]:\n spec2 = concrete.structured_input_signature[0][0]\n spec = nest.map_structure(common_spec, spec, spec2)\n return spec\n\n\nclass RevivedNetwork(RevivedLayer):\n \"\"\"Keras network of layers loaded from a SavedModel.\"\"\"\n\n @classmethod\n def _init_from_metadata(cls, metadata):\n \"\"\"Create revived network from metadata stored in the SavedModel proto.\"\"\"\n revived_obj = cls(name=metadata['name'])\n\n # Store attributes revived from SerializedAttributes in a un-tracked\n # dictionary. The attributes are the ones listed in CommonEndpoints or\n # \"keras_api\" for keras-specific attributes.\n with utils.no_automatic_dependency_tracking_scope(revived_obj):\n # pylint:disable=protected-access\n revived_obj._expects_training_arg = metadata['expects_training_arg']\n config = metadata.get('config')\n if generic_utils.validate_config(config):\n revived_obj._config = config\n\n if metadata.get('activity_regularizer') is not None:\n revived_obj.activity_regularizer = regularizers.deserialize(\n metadata['activity_regularizer'])\n # pylint:enable=protected-access\n\n return revived_obj, _revive_setter # pylint:disable=protected-access\n\n\ndef _set_network_attributes_from_metadata(revived_obj):\n \"\"\"Sets attributes recorded in the metadata.\"\"\"\n with utils.no_automatic_dependency_tracking_scope(revived_obj):\n # pylint:disable=protected-access\n metadata = revived_obj._serialized_attributes['metadata']\n if metadata.get('dtype') is not None:\n revived_obj._set_dtype_policy(metadata['dtype'])\n revived_obj._trainable = metadata['trainable']\n # pylint:enable=protected-access\n\n\ndef _maybe_add_serialized_attributes(layer, metadata):\n # Store attributes revived from SerializedAttributes in a un-tracked\n # dictionary. The attributes are the ones listed in CommonEndpoints or\n # \"keras_api\" for keras-specific attributes.\n if not hasattr(layer, '_serialized_attributes'):\n with utils.no_automatic_dependency_tracking_scope(layer):\n layer._serialized_attributes = {'metadata': metadata} # pylint: disable=protected-access\n\n\ndef _get_keras_attr(layer):\n return getattr(layer, '_serialized_attributes', {}).get(constants.KERAS_ATTR,\n None)\n", "# 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\n\"\"\"Tests for tensorflow.python.framework.device.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl.testing import parameterized\n\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import device\nfrom tensorflow.python.framework import device_spec\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import googletest\n\n\nTEST_V1_AND_V2 = ((\"v1\", device_spec.DeviceSpecV1),\n (\"v2\", device_spec.DeviceSpecV2))\n\n\nclass DeviceTest(test_util.TensorFlowTestCase, parameterized.TestCase):\n\n @parameterized.named_parameters(*TEST_V1_AND_V2)\n def testMerge(self, DeviceSpec): # pylint: disable=invalid-name\n d = DeviceSpec.from_string(\"/job:muu/task:1/device:MyFunnyDevice:2\")\n self.assertEqual(\"/job:muu/task:1/device:MyFunnyDevice:2\", d.to_string())\n\n if not context.executing_eagerly():\n with ops.device(device.merge_device(\"/device:GPU:0\")):\n var1 = variables.Variable(1.0)\n self.assertEqual(\"/device:GPU:0\", var1.device)\n with ops.device(device.merge_device(\"/job:worker\")):\n var2 = variables.Variable(1.0)\n self.assertEqual(\"/job:worker/device:GPU:0\", var2.device)\n with ops.device(device.merge_device(\"/device:CPU:0\")):\n var3 = variables.Variable(1.0)\n self.assertEqual(\"/job:worker/device:CPU:0\", var3.device)\n with ops.device(device.merge_device(\"/job:ps\")):\n var4 = variables.Variable(1.0)\n self.assertEqual(\"/job:ps/device:CPU:0\", var4.device)\n\n def testCanonicalName(self):\n self.assertEqual(\"/job:foo/replica:0\",\n device.canonical_name(\"/job:foo/replica:0\"))\n self.assertEqual(\"/job:foo/replica:0\",\n device.canonical_name(\"/replica:0/job:foo\"))\n\n self.assertEqual(\"/job:foo/replica:0/task:0\",\n device.canonical_name(\"/job:foo/replica:0/task:0\"))\n self.assertEqual(\"/job:foo/replica:0/task:0\",\n device.canonical_name(\"/job:foo/task:0/replica:0\"))\n\n self.assertEqual(\"/device:CPU:0\",\n device.canonical_name(\"/device:CPU:0\"))\n self.assertEqual(\"/device:GPU:2\",\n device.canonical_name(\"/device:GPU:2\"))\n\n self.assertEqual(\"/job:foo/replica:0/task:0/device:GPU:0\",\n device.canonical_name(\n \"/job:foo/replica:0/task:0/device:GPU:0\"))\n self.assertEqual(\"/job:foo/replica:0/task:0/device:GPU:0\",\n device.canonical_name(\n \"/device:GPU:0/task:0/replica:0/job:foo\"))\n\n def testCheckValid(self):\n device.check_valid(\"/job:foo/replica:0\")\n\n with self.assertRaisesRegex(ValueError, \"invalid literal for int\"):\n device.check_valid(\"/job:j/replica:foo\")\n\n with self.assertRaisesRegex(ValueError, \"invalid literal for int\"):\n device.check_valid(\"/job:j/task:bar\")\n\n # Assume no one will register a device type named \"barcpugpu\"\n with self.assertRaisesRegex(ValueError, \"Unknown attribute: 'barcpugpu'\"):\n device.check_valid(\"/barcpugpu:muu/baz:2\")\n\n with self.assertRaisesRegex(ValueError, \"Cannot specify multiple device\"):\n device.check_valid(\"/cpu:0/device:GPU:2\")\n\n\nif __name__ == \"__main__\":\n googletest.main()\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\"\"\"Library of Cloud TPU helper functions for data loading.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom typing import Callable, Optional, Text, Union\n\nfrom tensorflow.python.data.experimental.ops import interleave_ops\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.data.ops import iterator_ops\nfrom tensorflow.python.data.ops import readers\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import function\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import functional_ops\n\n\ndef _TextLineDataset(filename: Text) -> dataset_ops.Dataset:\n buffer_size = 8 * 1024 * 1024 # 8 MiB per file\n dataset = readers.TextLineDataset(filename, buffer_size=buffer_size)\n return dataset\n\n\ndef _TFRecordDataset(filename: Text) -> dataset_ops.Dataset:\n buffer_size = 8 * 1024 * 1024 # 8 MiB per file\n dataset = readers.TFRecordDataset(filename, buffer_size=buffer_size)\n return dataset\n\n\n_FILETYPE_MAP = {\n 'tfrecord': _TFRecordDataset,\n 'textline': _TextLineDataset,\n 'text': _TextLineDataset,\n}\n\n\ndef StreamingFilesDataset(\n files: Union[Text, dataset_ops.Dataset],\n filetype: Optional[Union[Text, Callable[[Text],\n dataset_ops.Dataset]]] = None,\n file_reader_job: Optional[Text] = None,\n worker_job: Optional[Text] = None,\n num_epochs: Optional[int] = None,\n filename_shuffle_buffer_size: Optional[Union[int, bool]] = None,\n num_parallel_reads: Optional[int] = None,\n batch_transfer_size: Optional[Union[int, bool]] = None,\n sloppy: bool = True) -> dataset_ops.Dataset:\n \"\"\"StreamingFilesDataset constructs a dataset to stream from workers (GCE VM).\n\n Because Cloud TPUs are allocated over the network, a Cloud TPU cannot read\n files local to your GCE VM. In order to train using files stored on your local\n VM (e.g. on local SSD for extreme performance), use the StreamingFilesDataset\n helper to generate a dataset to feed your Cloud TPU with files from your GCE\n VM.\n\n The resulting dataset may return an OutOfRangeError if there are no files\n found as a result of the fileglob expansion.\n\n Note: StreamingFilesDataset assumes that the session is using a\n TPUClusterResolver and has therefore a worker and a coordinator job. File\n loading will be done on the coordinator job.\n\n Args:\n files: A string glob to match files, or a `tf.data.Dataset` generating file\n names.\n filetype: A string (one of 'tfrecord', or 'textline') or a single-argument\n TensorFlow function that when given a filename returns a dataset.\n file_reader_job: An optional string that corresponds to the job that should\n perform the file reads.\n worker_job: An optional string that corresponds to the job that should\n process the tensors (i.e. your GPU or TPU worker).\n num_epochs: The number of epochs through the training set that should be\n generated. By default, it will repeat infinitely.\n filename_shuffle_buffer_size: An optional integer whose value controls the\n shuffling of the file names. If you would like to read from the files in\n the same order, set to 0 or False.\n num_parallel_reads: An optional integer controlling the number of files to\n read from concurrently. (Set to 1 for no parallelism.)\n batch_transfer_size: An optional integer controlling the batching used to\n amortize the remote function invocation overhead. Set to a very large\n number to increase throughput. Set to a very small number to reduce memory\n consumption. Set to False to skip batching.\n sloppy: (Optional.) If `False`, read input data while maintaining a\n deterministic order. (This may have significant performance impacts.)\n sloppy defaults to: True.\n Returns:\n A `tf.data.Dataset` with an infinite stream of elements generated by a\n parallel interleaving of the set of files matched (or generated) by `files`\n with a type is the output of the dataset specified by `filetype`.\n\n Raises:\n ValueError: if any argument is not of the expected type.\n \"\"\"\n if filetype is None:\n filetype = 'tfrecord'\n\n if isinstance(filetype, str):\n if filetype not in _FILETYPE_MAP:\n raise ValueError('Unexpected filetype: %s' % filetype)\n reader_fn = _FILETYPE_MAP[filetype]\n elif callable(filetype):\n reader_fn = filetype\n else:\n raise ValueError('filetype should be a string or a callable')\n\n file_reader_job = file_reader_job or 'coordinator'\n\n worker_job = worker_job or 'worker'\n\n if filename_shuffle_buffer_size is None:\n filename_shuffle_buffer_size = 4096\n\n num_parallel_reads = num_parallel_reads or 8\n\n if batch_transfer_size is None:\n batch_transfer_size = 256\n\n if file_reader_job == 'coordinator':\n file_reader_device = '/job:coordinator/task:0'\n else:\n file_reader_device = '/job:%s' % file_reader_job\n\n with ops.device(file_reader_device):\n if isinstance(files, str):\n source_dataset = dataset_ops.Dataset.list_files(files)\n elif isinstance(files, dataset_ops.DatasetV2):\n source_dataset = files\n else:\n raise ValueError('files was not a string or a dataset: %s' % files)\n\n if filename_shuffle_buffer_size:\n source_dataset = source_dataset.shuffle(\n buffer_size=filename_shuffle_buffer_size)\n\n source_dataset = source_dataset.apply(\n interleave_ops.parallel_interleave(\n reader_fn, cycle_length=num_parallel_reads, sloppy=sloppy))\n\n source_dataset = source_dataset.repeat(num_epochs)\n\n if batch_transfer_size:\n source_dataset = source_dataset.batch(batch_transfer_size)\n\n source_dataset = source_dataset.prefetch(1)\n\n source_iterator = dataset_ops.make_one_shot_iterator(source_dataset)\n source_handle = source_iterator.string_handle()\n\n @function.Defun(dtypes.string)\n def LoadingFunc(h):\n remote_iterator = iterator_ops.Iterator.from_string_handle(\n h, dataset_ops.get_legacy_output_types(source_dataset),\n dataset_ops.get_legacy_output_shapes(source_dataset))\n return remote_iterator.get_next()\n\n def MapFn(unused_input):\n source_dataset_output_types = dataset_ops.get_legacy_output_types(\n source_dataset)\n if isinstance(source_dataset_output_types, dtypes.DType):\n output_types = [source_dataset_output_types]\n elif isinstance(source_dataset_output_types, (list, tuple)):\n output_types = source_dataset_output_types\n else:\n raise ValueError('source dataset has invalid output types')\n remote_calls = functional_ops.remote_call(\n args=[source_handle],\n Tout=output_types,\n f=LoadingFunc,\n target='/job:%s/replica:0/task:0/cpu:0' % file_reader_job)\n if len(remote_calls) == 1:\n return remote_calls[0]\n else:\n return remote_calls\n\n with ops.device('/job:%s' % worker_job):\n output_dataset = dataset_ops.Dataset.range(2).repeat().map(\n MapFn, num_parallel_calls=4 if sloppy else None)\n output_dataset = output_dataset.prefetch(1)\n\n if batch_transfer_size:\n # Undo the batching used during the transfer.\n output_dataset = output_dataset.unbatch().prefetch(1)\n\n return output_dataset\n", "# Copyright 2018 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 TPUStrategy.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\n\nfrom absl.testing import parameterized\n\nfrom tensorflow.core.protobuf import config_pb2\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.distribute import distribute_lib\nfrom tensorflow.python.distribute import distribution_strategy_context\nfrom tensorflow.python.distribute import reduce_util\nfrom tensorflow.python.distribute import strategy_test_lib\nfrom tensorflow.python.distribute import tpu_strategy as tpu_lib\nfrom tensorflow.python.distribute import tpu_values\nfrom tensorflow.python.distribute.cluster_resolver import tpu_cluster_resolver\nfrom tensorflow.python.eager import def_function\nfrom tensorflow.python.eager import function\nfrom tensorflow.python.eager import remote\nfrom tensorflow.python.eager import test\nfrom tensorflow.python.framework import composite_tensor\nfrom tensorflow.python.framework import config\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import device as tf_device\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import sparse_tensor\nfrom tensorflow.python.framework import tensor_spec\nfrom tensorflow.python.framework import type_spec\nfrom tensorflow.python.module import module\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import embedding_ops\nfrom tensorflow.python.ops import lookup_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import random_ops\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.ops.ragged import ragged_tensor\nfrom tensorflow.python.platform import flags\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.tpu import device_assignment as device_assignment_lib\nfrom tensorflow.python.tpu import tpu\nfrom tensorflow.python.tpu import tpu_strategy_util\nfrom tensorflow.python.training import checkpoint_management\nfrom tensorflow.python.training import server_lib\nfrom tensorflow.python.training.tracking import util\nfrom tensorflow.python.util import nest\n\n\nFLAGS = flags.FLAGS\nflags.DEFINE_string(\"tpu\", \"\", \"Name of TPU to connect to.\")\nflags.DEFINE_string(\"project\", None, \"Name of GCP project with TPU.\")\nflags.DEFINE_string(\"zone\", None, \"Name of GCP zone with TPU.\")\n\n\ndef get_tpu_cluster_resolver():\n resolver = tpu_cluster_resolver.TPUClusterResolver(\n tpu=FLAGS.tpu,\n zone=FLAGS.zone,\n project=FLAGS.project,\n )\n return resolver\n\n\ndef get_tpu_strategy(enable_packed_var=False):\n resolver = get_tpu_cluster_resolver()\n remote.connect_to_cluster(resolver)\n tpu_strategy_util.initialize_tpu_system(resolver)\n strategy = tpu_lib.TPUStrategyV2(resolver)\n strategy._enable_packed_variable_in_eager_mode = enable_packed_var\n return strategy\n\n\n# TPU tests which don't use TPUStrategy.\nclass TPUTest(test.TestCase):\n\n def test_multiple_initialize_system(self):\n resolver = get_tpu_cluster_resolver()\n remote.connect_to_cluster(resolver)\n tpu_strategy_util.initialize_tpu_system(resolver)\n\n with test.mock.patch.object(logging, \"warning\") as mock_log:\n tpu_strategy_util.initialize_tpu_system(resolver)\n self.assertRegex(str(mock_log.call_args), \"already been initialized\")\n\n def test_tpu_tf_function_same_device(self):\n with ops.device(\"/device:TPU:0\"):\n a = variables.Variable(1)\n\n @function.defun_with_attributes(attributes={\"_noinline\": True})\n def get_a_plus_one():\n return a + 1\n\n @def_function.function(\n input_signature=[tensor_spec.TensorSpec([], dtypes.int32)])\n def foo(x):\n with ops.device(\"/device:TPU:0\"):\n b = x + get_a_plus_one()\n return b + 1\n\n result = foo(a)\n self.assertAllEqual(4, result)\n\n def test_tpu_return_int32(self):\n with ops.device(\"/device:TPU:0\"):\n a = variables.Variable(0)\n\n @def_function.function\n def foo():\n return a + 1\n\n @def_function.function\n def bar():\n with ops.device(\"/device:TPU:1\"):\n return foo()\n\n with ops.device(\"/device:CPU:0\"):\n result = bar() + 1\n self.assertAllEqual(result, 2)\n\n def test_tpu_output_device(self):\n\n def foo():\n return 1 + 1\n\n func1 = function.defun_with_attributes(\n foo, attributes={\"_XlaMustCompile\": False})\n func2 = function.defun_with_attributes(\n foo, attributes={\n \"_OutputsOnOpDevice\": True,\n \"_XlaMustCompile\": False\n })\n\n with ops.device(\"/device:TPU:0\"):\n ret1 = func1()\n ret2 = func2()\n\n self.assertAllEqual(ret1.backing_device,\n \"/job:localhost/replica:0/task:0/device:CPU:0\")\n self.assertAllEqual(ret2.backing_device,\n \"/job:localhost/replica:0/task:0/device:TPU:0\")\n\n def test_on_demand_op_with_dynamic_output(self):\n if FLAGS.tpu_use_tfrt:\n self.skipTest(\"Support dynamic output in TFRT, see b/192576400\")\n with ops.device(\"/device:TPU:0\"):\n where_output = array_ops.where([True, False, True])\n self.assertAllEqual(where_output, [[0], [2]])\n\n with ops.device(\"/device:TPU:0\"):\n repeat_output = array_ops.repeat(math_ops.range(2), [1, 4])\n self.assertAllEqual(repeat_output, [0, 1, 1, 1, 1])\n\n\[email protected]_parameters([(\"PackedVar\", True), (\"\", False)])\nclass TPUStrategyTest(test.TestCase, parameterized.TestCase):\n\n def test_handle_in_cross_replica_context(self, enable_packed_var):\n strategy = get_tpu_strategy(enable_packed_var)\n with strategy.scope():\n v = variables.Variable(1.0)\n\n @def_function.function\n def func():\n self.assertEndsWith(v.handle.device, \"device:TPU:0\")\n return v + 1.0\n\n ret = func()\n self.assertAllEqual(ret, 2.0)\n\n def testStaticHashTableDatasetFnHostTrainingLoop(self, enable_packed_var):\n self._dataset_fn_tracing_count = 0\n strategy = get_tpu_strategy(enable_packed_var)\n\n with strategy.scope():\n vals = [0, 1, 2]\n keys_tensor = constant_op.constant(\n list(range(len(vals))), dtype=dtypes.int64)\n vals_tensor = constant_op.constant(vals)\n initializer = lookup_ops.KeyValueTensorInitializer(\n keys_tensor, vals_tensor)\n per_worker_table = lookup_ops.StaticHashTable(\n initializer, default_value=-1)\n\n @def_function.function\n def dataset_fn(input_context):\n tensor = constant_op.constant([0, 1, 3], dtype=dtypes.int64)\n global_batch_size = 2\n batch_size = input_context.get_per_replica_batch_size(global_batch_size)\n dataset = dataset_ops.Dataset.from_tensors(tensor).repeat().batch(\n batch_size, drop_remainder=True)\n dataset = dataset.shard(input_context.num_input_pipelines,\n input_context.input_pipeline_id)\n dataset = dataset.prefetch(2) # This prefetches 2 batches per device.\n dataset = dataset.map(per_worker_table.lookup)\n self._dataset_fn_tracing_count += 1\n return dataset\n\n dist_iterator = iter(\n strategy.experimental_distribute_datasets_from_function(dataset_fn))\n\n @def_function.function\n def step_fn(inputs):\n # inputs should be [0, 1, -1]\n return math_ops.reduce_sum(inputs)\n\n def train_steps(iterator, steps):\n\n for _ in math_ops.range(steps):\n strategy.run(step_fn, args=(next(iterator),))\n\n train_steps(dist_iterator, steps=5)\n self.assertEqual(self._dataset_fn_tracing_count, 1)\n\n def test_function_compile_with_xla(self, enable_packed_var):\n if FLAGS.tpu_use_tfrt:\n self.skipTest(\n \"This test triggers _XlaCompile and XlaLaunch which are not \"\n \"supported in tfrt yet. We should avoid using these kernels on TPU. \"\n \"However, it is a workaround to support b/129842431. We need more \"\n \"discussion about how to support it in the long term.\")\n strategy = get_tpu_strategy(enable_packed_var)\n with strategy.scope():\n v = variables.Variable(1.0)\n\n @def_function.function\n def func():\n return v.read_value() + 1.0\n\n with ops.device(\"/device:TPU:0\"):\n self.assertAllEqual(func(), 2.0)\n\n def test_sequential_runs(self, enable_packed_var):\n resolver = get_tpu_cluster_resolver()\n remote.connect_to_cluster(resolver)\n topology = tpu_strategy_util.initialize_tpu_system(resolver)\n # Computation replicated to all cores.\n device_assignment = device_assignment_lib.DeviceAssignment.build(\n topology, num_replicas=2)\n strategy = tpu_lib.TPUStrategyV2(\n resolver, experimental_device_assignment=device_assignment)\n strategy._enable_packed_variable_in_eager_mode = enable_packed_var\n\n # Computation on the 1st core.\n device_assignment2 = device_assignment_lib.DeviceAssignment.build(\n topology, num_replicas=1)\n strategy2 = tpu_lib.TPUStrategyV2(\n resolver, experimental_device_assignment=device_assignment2)\n\n def computation(x):\n return math_ops.square(x)\n\n @def_function.function\n def train_step():\n outputs = strategy.experimental_local_results(\n strategy.run(computation, args=([2., 2.],)))\n outputs2 = strategy2.run(\n computation, args=([outputs[0]],))\n return outputs2\n\n self.assertAllEqual([[16., 16.]], train_step())\n\n def test_device_switch_case(self, enable_packed_var):\n strategy = get_tpu_strategy(enable_packed_var)\n with strategy.scope():\n a = variables.Variable(1)\n\n inference_iteration = variables.Variable(-1)\n\n def inference_fn(x, i):\n return a + x + i\n\n @def_function.function\n def run_inference(x):\n\n def do_inference(device, inference_fn, i):\n with ops.device(device):\n return inference_fn(x, i)\n\n branch_fns = {\n 0: (lambda: do_inference(\"/device:TPU:0\", inference_fn, 0)),\n 1: (lambda: do_inference(\"/device:TPU:1\", inference_fn, 1)),\n }\n branch_index = inference_iteration.assign_add(1, use_locking=True) % 2\n return control_flow_ops.switch_case(branch_index, branch_fns)\n\n self.assertAllEqual(2., run_inference(1)) # Use TPU core 0.\n self.assertAllEqual(3., run_inference(1)) # Use TPU core 1.\n\n def test_recover_from_compilation_failures(self, enable_packed_var):\n # TODO(b/148150981): Stop skipping this test once recovery works\n # for non-local TPU.\n if FLAGS.tpu:\n self.skipTest(\"Recovery fails for non-local TPU, see b/148150981\")\n\n # Disable automatic outside compilation.\n config.set_soft_device_placement(False)\n strategy = get_tpu_strategy(enable_packed_var)\n\n @def_function.function\n def compilation_failure_run():\n\n def computation():\n return random_ops.random_gamma([10], [0.5, 1.5])\n\n return strategy.run(computation)\n\n with self.assertRaises(errors.OpError):\n compilation_failure_run()\n\n @def_function.function\n def good_run():\n\n def computation():\n return random_ops.random_normal([10])\n\n return strategy.run(computation)\n\n good_run()\n\n def test_dynamic_shape_with_outside_compilation_failure(\n self, enable_packed_var):\n # Enable automatic outside compilation.\n config.set_soft_device_placement(True)\n strategy = get_tpu_strategy(enable_packed_var)\n dataset = dataset_ops.Dataset.from_tensors((\"string\", 1.0)).repeat().batch(\n 2, drop_remainder=False)\n dataset = strategy.experimental_distribute_dataset(dataset)\n iterator = iter(dataset)\n\n @def_function.function\n def train_fn(iterator):\n\n def step_fn(inputs):\n input0, input1 = inputs\n return array_ops.size(input0), math_ops.reduce_sum(input1)\n\n return strategy.experimental_local_results(\n strategy.run(step_fn, args=(next(iterator),)))\n\n with self.assertRaises(errors.InvalidArgumentError):\n logging.info(train_fn(iterator))\n\n def test_computation_on_subset_cores(self, enable_packed_var):\n resolver = get_tpu_cluster_resolver()\n remote.connect_to_cluster(resolver)\n topology = tpu_strategy_util.initialize_tpu_system(resolver)\n all_core_strategy = tpu_lib.TPUStrategyV2(resolver)\n all_core_strategy._enable_packed_variable_in_eager_mode = enable_packed_var\n\n with all_core_strategy.scope():\n v = variables.Variable(0.0,\n aggregation=variables.VariableAggregation.MEAN)\n\n # Computation on the 1st core.\n device_assignment = device_assignment_lib.DeviceAssignment.build(\n topology, num_replicas=1)\n first_core_strategy = tpu_lib.TPUStrategyV2(\n resolver, experimental_device_assignment=device_assignment)\n first_core_strategy._enable_packed_variable_in_eager_mode = (\n enable_packed_var)\n\n # Computation on the 2nd core.\n device_assignment2 = device_assignment_lib.DeviceAssignment(\n topology, [[[0, 0, 0, 1]]])\n second_core_strategy = tpu_lib.TPUStrategyV2(\n resolver, experimental_device_assignment=device_assignment2)\n second_core_strategy._enable_packed_variable_in_eager_mode = (\n enable_packed_var)\n\n @def_function.function\n def train_step():\n\n def step_fn():\n return v + 1.0\n\n all_core_strategy.run(step_fn)\n r1 = first_core_strategy.run(step_fn)\n r2 = second_core_strategy.run(step_fn)\n return r1 + r2\n\n train_step()\n self.assertAllEqual(2., train_step())\n\n def test_worker_devices_on_subset_cores(self, enable_packed_var):\n resolver = get_tpu_cluster_resolver()\n remote.connect_to_cluster(resolver)\n topology = tpu_strategy_util.initialize_tpu_system(resolver)\n\n # Strategy for the 1st core.\n device_assignment = device_assignment_lib.DeviceAssignment.build(\n topology, num_replicas=1)\n first_core_strategy = tpu_lib.TPUStrategyV2(\n resolver, experimental_device_assignment=device_assignment)\n first_core_strategy._enable_packed_variable_in_eager_mode = (\n enable_packed_var)\n\n # Strategy for the 2nd core.\n device_assignment2 = device_assignment_lib.DeviceAssignment(\n topology, [[[0, 0, 0, 1]]])\n second_core_strategy = tpu_lib.TPUStrategyV2(\n resolver, experimental_device_assignment=device_assignment2)\n second_core_strategy._enable_packed_variable_in_eager_mode = (\n enable_packed_var)\n\n self.assertLen(first_core_strategy.extended.worker_devices, 1)\n self.assertEndsWith(first_core_strategy.extended.worker_devices[0],\n \"device:TPU:0\")\n\n self.assertLen(second_core_strategy.extended.worker_devices, 1)\n self.assertEndsWith(second_core_strategy.extended.worker_devices[0],\n \"device:TPU:1\")\n\n def test_control_output_in_while_body_fn(self, enable_packed_var):\n strategy = get_tpu_strategy(enable_packed_var)\n\n with strategy.scope():\n v = variables.Variable(\n 0.0, aggregation=variables.VariableAggregation.MEAN)\n\n @def_function.function\n def train_step():\n\n def step_fn():\n v.assign_add(1)\n\n for _ in math_ops.range(2):\n strategy.run(step_fn)\n\n train_step()\n self.assertEqual(2.0, v.numpy())\n\n def test_cluster_conditional_with_dynamic_shape(self, enable_packed_var):\n if FLAGS.tpu_use_tfrt:\n self.skipTest(\"Support dynamic output in TFRT, see b/192576400\")\n strategy = get_tpu_strategy(enable_packed_var)\n\n @def_function.function\n def train_step():\n\n def shape_list(tensor):\n shape = tensor.shape.as_list()\n\n non_static_indexes = []\n for (index, dim) in enumerate(shape):\n if dim is None:\n non_static_indexes.append(index)\n\n if not non_static_indexes:\n return shape\n\n dynamic_shape = array_ops.shape(input=tensor)\n for index in non_static_indexes:\n shape[index] = dynamic_shape[index]\n\n return shape\n\n def step_fn(condition):\n where = array_ops.where(condition)\n if array_ops.shape(where)[0] > 0:\n tensor_shape = shape_list(where)\n d1 = tensor_shape[0]\n d2 = tensor_shape[1]\n where = array_ops.reshape(where, [d1, d2])\n return where\n\n return strategy.run(step_fn, args=([True, False, True],))\n\n outputs = strategy.experimental_local_results(train_step())\n self.assertAllEqual(outputs[0].numpy(), [[0], [2]])\n\n def test_cluster_in_graph_and_while_body_fn(self, enable_packed_var):\n strategy = get_tpu_strategy(enable_packed_var)\n\n @def_function.function\n def train_step():\n\n def step_fn(prev):\n s = prev + 1\n return s\n\n def init_fn():\n return array_ops.zeros(shape=())\n\n prev = strategy.run(init_fn)\n for _ in math_ops.range(10):\n prev = strategy.run(step_fn, args=(prev,))\n return strategy.reduce(reduce_util.ReduceOp.SUM, prev, axis=None)\n\n sum_val = train_step().numpy().astype(float)\n self.assertEqual(sum_val, strategy.num_replicas_in_sync * 10)\n\n def test_two_clusters_with_same_fn(self, enable_packed_var):\n strategy = get_tpu_strategy(enable_packed_var)\n\n @def_function.function\n def foo(x):\n return strategy.run(lambda x: x + 1, (x,))\n\n @def_function.function\n def bar(x):\n foo(x)\n return foo(x)\n\n bar(1)\n\n def test_tpu_variable_run_argument(self, enable_packed_var):\n # TPUStrategy.run() casts inputs to Tensor, but has logic to preserve\n # variables to avoid unintuitive errors.\n # Here we test that a TPUDistributedVariable passed to TPUStrategy.run()\n # remains a variable.\n\n strategy = get_tpu_strategy(enable_packed_var)\n\n with strategy.scope():\n tpu_variable = variables.Variable(1)\n\n def replica_step(first_arg, variable):\n del first_arg # Just here to make sure we're not relying on arg position.\n\n if variable is not None:\n self.assertIsInstance(variable, tpu_values.TPUDistributedVariable)\n\n @def_function.function\n def step():\n strategy.run(\n replica_step, args=(\n 2,\n tpu_variable,\n ))\n\n step()\n\n def test_tpu_run_arg_parsing(self, enable_packed_var):\n strategy = get_tpu_strategy(enable_packed_var)\n\n with strategy.scope():\n tpu_vars = [variables.Variable(1)]\n\n def only_star_args(*args):\n del args\n\n def pos_and_star_args(first_arg, *args):\n del first_arg\n del args\n\n def named_args(first_arg, second_arg):\n del first_arg\n del second_arg\n\n def star_args_and_kw_only(*args, kw):\n del args\n del kw\n\n # pylint:disable=function-redefined\n @def_function.function\n def step():\n strategy.run(only_star_args, args=(2,))\n\n step()\n\n @def_function.function\n def step():\n strategy.run(named_args, kwargs={\"first_arg\": 2, \"second_arg\": 3})\n\n step()\n\n with self.assertRaisesRegex(TypeError, r\"got multiple values for argument\"):\n\n @def_function.function\n def step():\n strategy.run(\n named_args, args=(1,), kwargs={\n \"first_arg\": 2,\n \"second_arg\": 3\n })\n\n step()\n\n with self.assertRaisesRegex(ValueError,\n r\"cannot handle Variables passed to \\*args\"):\n\n @def_function.function\n def step():\n strategy.run(\n only_star_args, args=(\n 2,\n tpu_vars,\n ))\n\n step()\n\n @def_function.function\n def step():\n strategy.run(pos_and_star_args, args=(2, 3, 4))\n\n step()\n\n @def_function.function\n def step():\n strategy.run(star_args_and_kw_only, args=(2, 3), kwargs={\"kw\": tpu_vars})\n\n step()\n\n with self.assertRaisesRegex(ValueError,\n r\"mix of positional args and \\*args\"):\n\n @def_function.function\n def step():\n strategy.run(pos_and_star_args, args=(tpu_vars, 3, 4))\n\n step()\n\n with self.assertRaisesRegex(ValueError, r\"Too many positional arguments\"):\n\n @def_function.function\n def step():\n strategy.run(named_args, args=(2, 3, 4))\n\n step()\n\n class DummyClass:\n\n @def_function.function\n def method(self, arg_1):\n del arg_1\n\n def step(self):\n strategy.run(self.method, args=(tpu_vars,))\n\n DummyClass().step()\n # pylint:enable=function-redefined\n\n def test_using_external_variable_inside_tf_function(self, enable_packed_var):\n strategy = get_tpu_strategy(enable_packed_var)\n dataset = dataset_ops.Dataset.range(\n strategy.num_replicas_in_sync * 2,\n output_type=dtypes.float32).batch(strategy.num_replicas_in_sync)\n input_iterator = iter(strategy.experimental_distribute_dataset(dataset))\n\n v = variables.Variable(2.0)\n\n @def_function.function\n def train_step(data):\n def computation(inputs):\n return inputs + v\n return strategy.run(computation, args=(data,))\n\n expected_result = [[x + 2.] for x in range(0, strategy.num_replicas_in_sync)\n ]\n self.assertAllEqual(\n expected_result,\n strategy.experimental_local_results(train_step(next(input_iterator))))\n\n # TODO(b/145574622): Remove this test once it is re-enabled in values_test.py.\n def test_all_reduce_on_sync_on_read_variable(self, enable_packed_var):\n strategy = get_tpu_strategy(enable_packed_var)\n dataset = dataset_ops.Dataset.range(\n strategy.num_replicas_in_sync, output_type=dtypes.float32).batch(\n strategy.num_replicas_in_sync, drop_remainder=True)\n input_iterator = iter(strategy.experimental_distribute_dataset(dataset))\n\n with strategy.scope():\n w = variables.Variable(\n (0.,),\n shape=(1,),\n trainable=False,\n synchronization=variables.VariableSynchronization.ON_READ,\n aggregation=variables.VariableAggregation.ONLY_FIRST_REPLICA)\n\n @def_function.function\n def run(iterator):\n\n def computation(x):\n w.assign(x + w)\n return w\n\n def all_reduce(x):\n ctx = distribution_strategy_context.get_replica_context()\n return ctx.all_reduce(\"SUM\", w) + x\n\n outputs = strategy.run(computation, args=(next(iterator),))\n outputs2 = strategy.experimental_local_results(\n strategy.run(all_reduce, args=(outputs,)))\n return outputs2\n\n data = range(0, strategy.num_replicas_in_sync)\n data_sum = sum(data)\n expected_result = [\n [x + data_sum] for x in range(0, strategy.num_replicas_in_sync)\n ]\n self.assertAllEqual(expected_result, run(input_iterator))\n self.assertAllEqual((0.,), w.read_value())\n\n def test_run_output_on_device(self, enable_packed_var):\n strategy = get_tpu_strategy(enable_packed_var)\n\n def computation(x):\n return math_ops.square(x)\n\n @def_function.function\n def train_step():\n outputs = strategy.experimental_local_results(\n strategy.run(computation, args=(2,)))\n return outputs\n\n results = train_step()\n self.assertAllEqual([4., 4.], results)\n self.assertAllEqual(\"/job:localhost/replica:0/task:0/device:TPU:0\",\n results[0].backing_device)\n self.assertAllEqual(\"/job:localhost/replica:0/task:0/device:TPU:1\",\n results[1].backing_device)\n\n def test_run_passing_and_returning_nones(self, enable_packed_var):\n strategy = get_tpu_strategy(enable_packed_var)\n\n @def_function.function\n def train_step():\n\n def computation(x):\n return x\n\n # Note that this input None is nested.\n outputs = strategy.experimental_local_results(\n strategy.run(computation, args=([1, [2, None]],)))\n return outputs\n\n results = train_step()\n\n self.assertAllEqual(1, results[0][0])\n self.assertAllEqual(2, results[0][1][0])\n self.assertIsNone(results[0][1][1])\n\n def test_run_passing_and_returning_empty_list(self, enable_packed_var):\n strategy = get_tpu_strategy(enable_packed_var)\n\n @def_function.function\n def train_step():\n\n def computation(x):\n return x\n\n outputs = strategy.experimental_local_results(\n strategy.run(computation, args=([],)))\n return outputs\n\n self.assertEqual([], train_step()[0])\n\n def test_run_passing_and_returning_empty_dict(self, enable_packed_var):\n strategy = get_tpu_strategy(enable_packed_var)\n\n @def_function.function\n def train_step():\n\n def computation(x):\n return x\n\n outputs = strategy.experimental_local_results(\n strategy.run(computation, args=({},)))\n return outputs\n\n self.assertEqual({}, train_step()[0])\n\n def test_composite_input_output(self, enable_packed_var):\n strategy = get_tpu_strategy(enable_packed_var)\n if strategy.num_replicas_in_sync != 2:\n self.skipTest(\"Test assumes two replicas.\")\n\n with strategy.scope():\n table = variables.Variable(\n initial_value=[[0.0, 1.0], [3.0, 7.0]], dtype=dtypes.float32)\n\n @def_function.function\n def sparse_lookup(iterator):\n\n def tpu_function(sparse):\n # Assumes dense_shape is (2, *)\n looked_up = array_ops.gather(table, sparse.values)\n segment_sum = math_ops.unsorted_segment_sum(\n looked_up, sparse.indices[:, 0], 2)\n return sparse, segment_sum\n\n return nest.map_structure(\n strategy.experimental_local_results,\n strategy.run(tpu_function, args=(next(iterator),)))\n\n def dataset_fn(_):\n dataset = dataset_ops.Dataset.range(2)\n\n def make_sparse(_):\n return sparse_tensor.SparseTensor(\n indices=array_ops.constant([[0, 0], [1, 0], [1, 1]],\n dtype=dtypes.int64),\n values=array_ops.constant([0, 0, 1], dtype=dtypes.int32),\n dense_shape=array_ops.constant([2, 2], dtype=dtypes.int64))\n\n return dataset.map(make_sparse)\n\n dataset = iter(\n strategy.distribute_datasets_from_function(\n dataset_fn,\n distribute_lib.InputOptions(experimental_fetch_to_device=False)))\n\n sparse, result = sparse_lookup(dataset)\n\n # All replicas return identical reults.\n for replica in range(strategy.num_replicas_in_sync):\n self.assertIsInstance(sparse[replica], sparse_tensor.SparseTensor)\n self.assertAllEqual(sparse[replica].indices, [[0, 0], [1, 0], [1, 1]])\n self.assertAllEqual(sparse[replica].values, [0, 0, 1])\n self.assertAllEqual(sparse[replica].dense_shape, [2, 2])\n self.assertAllEqual(result[replica], [[0.0, 1.0], [3.0, 8.0]])\n\n def test_composite_input_non_flat_output(self, enable_packed_var):\n strategy = get_tpu_strategy(enable_packed_var)\n if strategy.num_replicas_in_sync != 2:\n self.skipTest(\"Test assumes two replicas.\")\n\n with strategy.scope():\n table = variables.Variable(\n initial_value=[[0.0, 1.0], [3.0, 7.0]], dtype=dtypes.float32)\n\n @def_function.function\n def sparse_lookup(iterator):\n\n def tpu_function(sparse):\n # Assumes dense_shape is (2, *)\n looked_up = array_ops.gather(table, sparse.values)\n segment_sum = math_ops.unsorted_segment_sum(\n looked_up, sparse.indices[:, 0], 2)\n return {\"sparse\": sparse, \"segment_sum\": segment_sum}\n\n return nest.map_structure(\n strategy.experimental_local_results,\n strategy.run(tpu_function, args=(next(iterator),)))\n\n def dataset_fn(_):\n dataset = dataset_ops.Dataset.range(2)\n\n def make_sparse(_):\n return sparse_tensor.SparseTensor(\n indices=array_ops.constant([[0, 0], [1, 0], [1, 1]],\n dtype=dtypes.int64),\n values=array_ops.constant([0, 0, 1], dtype=dtypes.int32),\n dense_shape=array_ops.constant([2, 2], dtype=dtypes.int64))\n\n return dataset.map(make_sparse)\n\n dataset = iter(\n strategy.distribute_datasets_from_function(\n dataset_fn,\n distribute_lib.InputOptions(experimental_fetch_to_device=False)))\n\n output = sparse_lookup(dataset)\n\n # All replicas return identical reults.\n for replica in range(strategy.num_replicas_in_sync):\n self.assertIsInstance(output[\"sparse\"][replica],\n sparse_tensor.SparseTensor)\n self.assertAllEqual(output[\"sparse\"][replica].indices,\n [[0, 0], [1, 0], [1, 1]])\n self.assertAllEqual(output[\"sparse\"][replica].values, [0, 0, 1])\n self.assertAllEqual(output[\"sparse\"][replica].dense_shape, [2, 2])\n self.assertAllEqual(output[\"segment_sum\"][replica],\n [[0.0, 1.0], [3.0, 8.0]])\n\n def test_composite_input_dynamic_shapes_outside_compilation(\n self, enable_packed_var):\n strategy = get_tpu_strategy(enable_packed_var)\n if strategy.num_replicas_in_sync != 2:\n self.skipTest(\"Test assumes two replicas.\")\n\n table = variables.Variable(\n initial_value=[[0.0, 1.0], [3.0, 7.0]], dtype=dtypes.float32)\n\n @def_function.function\n def sparse_lookup(iterator):\n\n def tpu_function(sparse):\n lookup = tpu.outside_compilation(\n embedding_ops.safe_embedding_lookup_sparse, table, sparse)\n return math_ops.reduce_sum(lookup, axis=0)\n\n return strategy.experimental_local_results(\n strategy.run(tpu_function, args=(next(iterator),)))\n\n def dataset_fn(_):\n dataset = dataset_ops.Dataset.range(2)\n\n def make_sparse(i):\n indices = array_ops.constant([[0, 0], [1, 0], [1, 1]],\n dtype=dtypes.int64)[0:2 + i]\n values = array_ops.constant([0, 0, 1], dtype=dtypes.int32)[0:2 + i]\n shape = [\n array_ops.constant([2], dtype=dtypes.int64),\n array_ops.expand_dims(1 + i, axis=0)\n ]\n dense_shape = array_ops.concat(shape, axis=0)\n return sparse_tensor.SparseTensor(\n indices=indices, values=values, dense_shape=dense_shape)\n\n return dataset.map(make_sparse)\n\n dataset = iter(\n strategy.distribute_datasets_from_function(\n dataset_fn,\n options=distribute_lib.InputOptions(\n experimental_fetch_to_device=False)))\n\n result = sparse_lookup(dataset)\n self.assertAllEqual(result, [[0.0, 2.0], [1.5, 5.0]])\n\n def test_composite_input_with_non_flat_components(self, enable_packed_var):\n strategy = get_tpu_strategy(enable_packed_var)\n\n class TestCompositeTypeSpec(type_spec.TypeSpec):\n\n def __init__(self, component_type_spec):\n self._component_type_spec = component_type_spec\n\n @property\n def value_type(self):\n return TestComposite\n\n def _to_components(self, value):\n return value.values\n\n def _from_components(self, components):\n return TestComposite(components[0], components[1][0], components[1][1])\n\n @property\n def _component_specs(self):\n return [self._component_type_spec,\n [self._component_type_spec, self._component_type_spec]]\n\n def _serialize(self):\n return (self._component_type_spec,)\n\n class TestComposite(composite_tensor.CompositeTensor):\n\n def __init__(self, value1, value2, value3):\n self.values = [value1, [value2, value3]]\n\n @property\n def _type_spec(self):\n return TestCompositeTypeSpec(\n tensor_spec.TensorSpec.from_tensor(self.values[0]))\n\n def _shape_invariant_to_type_spec(self, shape):\n return [shape, [shape, shape]]\n\n @def_function.function\n def test_fn(test_composite):\n\n def tpu_function(composite):\n return (composite,\n composite.values[0] + (\n composite.values[1][0] + composite.values[1][1])/2)\n\n return nest.map_structure(\n strategy.experimental_local_results,\n strategy.run(tpu_function, args=(test_composite,)))\n\n a = array_ops.constant([0.1])\n b = array_ops.constant([1.2])\n c = array_ops.constant([-0.4])\n test_composite = TestComposite(a, b, c)\n\n composite, result = test_fn(test_composite)\n\n # All replicas return identical reults.\n for replica in range(strategy.num_replicas_in_sync):\n self.assertIsInstance(composite[replica], TestComposite)\n self.assertAllEqual(composite[replica].values[0], a)\n self.assertAllEqual(composite[replica].values[1][0], b)\n self.assertAllEqual(composite[replica].values[1][1], c)\n self.assertAllEqual(result[replica], array_ops.constant([0.50000006]))\n\n def test_per_device_tracing_of_mirrored_variables(self, enable_packed_var):\n # Define trace_count as a list to avoid python scoping error\n trace_count = [0]\n\n strategy = get_tpu_strategy(enable_packed_var)\n with strategy.scope():\n variable = variables.Variable(0.0)\n\n @def_function.function\n def add_one():\n trace_count[0] = trace_count[0] + 1\n return math_ops.add(variable, constant_op.constant(1.0))\n\n @def_function.function\n def update_variable():\n for device in set(strategy.extended.worker_devices):\n with ops.device(device):\n add_one()\n\n with strategy.scope():\n update_variable.get_concrete_function()\n self.assertLen(strategy.extended.worker_devices, trace_count[0])\n\n\nclass TPUStrategyDataPrefetchTest(test.TestCase):\n\n def test_prefetch_to_device_default(self):\n strategy = get_tpu_strategy()\n dataset = dataset_ops.Dataset.range(\n strategy.num_replicas_in_sync * 2,\n output_type=dtypes.float32).batch(strategy.num_replicas_in_sync)\n\n # Check default, should prefetch to TPU.\n dataset_item = next(iter(strategy.experimental_distribute_dataset(dataset)))\n dataset_location = tf_device.DeviceSpec.from_string(\n dataset_item.values[0].device)\n self.assertEqual(dataset_location.device_type, \"TPU\")\n\n def test_prefetch_to_device_tpu(self):\n strategy = get_tpu_strategy()\n dataset = dataset_ops.Dataset.range(\n strategy.num_replicas_in_sync * 2,\n output_type=dtypes.float32).batch(strategy.num_replicas_in_sync)\n\n input_options = distribute_lib.InputOptions(\n experimental_fetch_to_device=True)\n dataset_item = next(iter(strategy.experimental_distribute_dataset(\n dataset, options=input_options)))\n dataset_location = tf_device.DeviceSpec.from_string(\n dataset_item.values[0].device)\n self.assertEqual(dataset_location.device_type, \"TPU\")\n\n def test_prefetch_to_device_cpu(self):\n strategy = get_tpu_strategy()\n dataset = dataset_ops.Dataset.range(\n strategy.num_replicas_in_sync * 2,\n output_type=dtypes.float32).batch(strategy.num_replicas_in_sync)\n\n # Should be CPU when prefetch_to_device is False.\n input_options = distribute_lib.InputOptions(\n experimental_fetch_to_device=False)\n dataset_item = next(iter(strategy.experimental_distribute_dataset(\n dataset, options=input_options)))\n dataset_location = tf_device.DeviceSpec.from_string(\n dataset_item.values[0].device)\n self.assertEqual(dataset_location.device_type, \"CPU\")\n\n def test_prefetch_to_device_sparse_dataset(self):\n strategy = get_tpu_strategy()\n # Values here aren't important.\n dataset = dataset_ops.Dataset.from_tensors(\n sparse_tensor.SparseTensor(indices=[[0, 0], [0, 1], [1, 0]],\n values=[1, 2, 3],\n dense_shape=[2, 2]))\n dataset = dataset.repeat()\n dataset = dataset.batch(strategy.num_replicas_in_sync)\n\n with self.assertRaisesRegex(ValueError, \"TPUStrategy does not support\"):\n iter(strategy.experimental_distribute_dataset(dataset))\n\n def test_prefetch_to_device_ragged_dataset(self):\n strategy = get_tpu_strategy()\n # Values here aren't important.\n dataset = dataset_ops.Dataset.from_tensors(\n ragged_tensor.RaggedTensor.from_row_splits(\n values=[1, 2, 3],\n row_splits=[0, 2, 3]))\n dataset = dataset.repeat()\n dataset = dataset.batch(strategy.num_replicas_in_sync)\n\n with self.assertRaisesRegex(ValueError, \"TPUStrategy does not support\"):\n iter(strategy.experimental_distribute_dataset(dataset))\n\n def test_prefetch_to_device_sparse_dataset_fn(self):\n strategy = get_tpu_strategy()\n def dataset_fn(ctx):\n del ctx\n # Values here aren't important.\n dataset = dataset_ops.Dataset.from_tensors(\n sparse_tensor.SparseTensor(indices=[[0, 0], [0, 1], [1, 0]],\n values=[1, 2, 3],\n dense_shape=[2, 2]))\n dataset = dataset.repeat()\n return dataset.batch(strategy.num_replicas_in_sync)\n\n with self.assertRaisesRegex(ValueError, \"TPUStrategy does not support\"):\n iter(strategy.distribute_datasets_from_function(dataset_fn))\n\n def test_prefetch_to_device_ragged_dataset_fn(self):\n strategy = get_tpu_strategy()\n def dataset_fn(ctx):\n del ctx\n # Values here aren't important.\n dataset = dataset_ops.Dataset.from_tensors(\n ragged_tensor.RaggedTensor.from_row_splits(\n values=[1, 2, 3],\n row_splits=[0, 2, 3]))\n dataset = dataset.repeat()\n return dataset.batch(strategy.num_replicas_in_sync)\n\n with self.assertRaisesRegex(ValueError, \"TPUStrategy does not support\"):\n iter(strategy.distribute_datasets_from_function(dataset_fn))\n\n\nclass TPUStrategyDistributionTest(\n strategy_test_lib.DistributionTestBase,\n strategy_test_lib.TwoDeviceDistributionTestBase):\n\n def test_update_config_proto(self):\n resolver = get_tpu_cluster_resolver()\n remote.connect_to_cluster(resolver)\n tpu_strategy_util.initialize_tpu_system(resolver)\n strategy = tpu_lib.TPUStrategyV2(resolver)\n\n config_proto = config_pb2.ConfigProto()\n cluster_spec = server_lib.ClusterSpec({\"worker\": [\"fake1\", \"fake2\"]})\n with test.mock.patch.object(\n resolver, \"cluster_spec\", return_value=cluster_spec):\n new_config = strategy.update_config_proto(config_proto)\n\n # Verify cluster_def.\n self.assertProtoEquals(cluster_spec.as_cluster_def(),\n new_config.cluster_def)\n\n # Verify isolate_session_state\n self.assertTrue(new_config.isolate_session_state)\n\n def test_make_input_fn_iterable(self):\n dataset_fn = lambda: dataset_ops.Dataset.range(10)\n expected_values = [[i, i+1] for i in range(0, 10, 2)]\n distribution = get_tpu_strategy()\n input_fn = self._input_fn_to_test_input_context(\n dataset_fn,\n expected_num_replicas_in_sync=2,\n expected_num_input_pipelines=1,\n expected_input_pipeline_id=0)\n self._test_input_fn_iterable(distribution, input_fn, expected_values)\n\n def test_make_input_fn_iterator(self):\n dataset_fn = lambda: dataset_ops.Dataset.range(10)\n expected_values = [[i, i+1] for i in range(0, 10, 2)]\n distribution = get_tpu_strategy()\n input_fn = self._input_fn_to_test_input_context(\n dataset_fn,\n expected_num_replicas_in_sync=2,\n expected_num_input_pipelines=1,\n expected_input_pipeline_id=0)\n iterator = distribution.make_input_fn_iterator(input_fn)\n self._test_input_fn_iterator(\n iterator,\n distribution.extended.worker_devices,\n expected_values)\n\n def test_num_replicas_in_sync(self):\n strategy = get_tpu_strategy()\n self.assertEqual(2, strategy.num_replicas_in_sync)\n\n def test_call_and_merge_exceptions(self):\n strategy = get_tpu_strategy()\n self._test_call_and_merge_exceptions(strategy)\n\n def test_numpy_dataset(self):\n strategy = get_tpu_strategy()\n self._test_numpy_dataset(strategy, run_in_function=True)\n\n def test_global_step_update(self):\n strategy = get_tpu_strategy()\n self._test_global_step_update(strategy)\n\n def test_run(self):\n strategy = get_tpu_strategy()\n self._test_run(strategy, run_in_function=True)\n\n def test_summary_for_replica_zero_only(self):\n strategy = get_tpu_strategy()\n self._test_summary_for_replica_zero_only(strategy)\n\n def test_all_reduce_sum(self):\n strategy = get_tpu_strategy()\n self._test_all_reduce_sum(strategy, run_in_function=True)\n\n def test_all_reduce_sum_gradients(self):\n strategy = get_tpu_strategy()\n self._test_all_reduce_sum_gradients(strategy, run_in_function=True)\n\n def test_all_reduce_sum_gradient_tape(self):\n strategy = get_tpu_strategy()\n self._test_all_reduce_sum_gradient_tape(strategy, run_in_function=True)\n\n def test_all_reduce_mean(self):\n strategy = get_tpu_strategy()\n self._test_all_reduce_mean(strategy, run_in_function=True)\n\n def test_all_reduce_mean_gradients(self):\n strategy = get_tpu_strategy()\n self._test_all_reduce_mean_gradients(strategy, run_in_function=True)\n\n def test_all_reduce_mean_gradient_tape(self):\n strategy = get_tpu_strategy()\n self._test_all_reduce_mean_gradient_tape(strategy, run_in_function=True)\n\n def test_reduce(self):\n strategy = get_tpu_strategy()\n\n inputs = strategy.make_input_fn_iterator(\n lambda _: dataset_ops.Dataset.from_tensor_slices([2., 3.]))\n\n self.evaluate(inputs.initialize())\n per_replica_outputs = strategy.run(\n def_function.function(math_ops.square), args=(next(inputs),))\n\n with strategy.scope():\n mean = strategy.reduce(reduce_util.ReduceOp.MEAN, per_replica_outputs,\n axis=None)\n self.assertEqual(6.5, self.evaluate(mean))\n\n def test_constraint(self):\n strategy = get_tpu_strategy()\n\n with strategy.scope():\n variable = variables.Variable(initial_value=2.,\n constraint=lambda x: 0. * x + 1.)\n self.assertEqual(variable.value().numpy(), 2)\n\n @def_function.function\n def update_variable():\n variable.assign_add(1)\n variable.assign(variable.constraint(variable))\n\n update_variable()\n self.assertEqual(variable.value().numpy(), 1)\n\n def test_trainable_variables(self):\n strategy = get_tpu_strategy()\n self._test_trainable_variable(strategy)\n\n def test_model_parallelism(self):\n resolver = get_tpu_cluster_resolver()\n remote.connect_to_cluster(resolver)\n topology = tpu_strategy_util.initialize_tpu_system(resolver)\n device_assignment = device_assignment_lib.DeviceAssignment(\n topology, core_assignment=[[[0, 0, 0, 0], [0, 0, 0, 1]]])\n strategy = tpu_lib.TPUStrategyV2(\n resolver,\n experimental_device_assignment=device_assignment)\n\n with strategy.scope():\n v = variables.Variable(2.)\n with strategy.extended.experimental_logical_device(1):\n w = variables.Variable(3.)\n\n self.assertLen(strategy.experimental_local_results(v), 1)\n self.assertLen(strategy.experimental_local_results(w), 1)\n self.assertEqual(\"/job:localhost/replica:0/task:0/device:TPU:0\",\n strategy.experimental_local_results(v)[0].device)\n self.assertEqual(\"/job:localhost/replica:0/task:0/device:TPU:1\",\n strategy.experimental_local_results(w)[0].device)\n\n logical_devices = []\n @def_function.function\n def f(x):\n replica_ctx = distribution_strategy_context.get_replica_context()\n with replica_ctx.experimental_logical_device(0):\n y = v * x\n with replica_ctx.experimental_logical_device(1):\n z = w * y\n logical_devices.append((y.device, z.device))\n return z\n\n result = strategy.run(f, args=(5.,))\n\n self.assertEqual(\n [(\"/device:TPU_REPLICATED_CORE:0\", \"/device:TPU_REPLICATED_CORE:1\")],\n logical_devices)\n\n with self.cached_session():\n self.evaluate(variables.global_variables_initializer())\n self.assertEqual(30., self.evaluate(result))\n\n def test_model_parallelism_checkpointing(self):\n\n class PartitionedModel(module.Module):\n\n def __init__(self, v, w):\n super(PartitionedModel, self).__init__()\n\n assert distribution_strategy_context.has_strategy()\n strategy = distribution_strategy_context.get_strategy()\n\n with strategy.extended.experimental_logical_device(0):\n self.v = variables.Variable(v)\n with strategy.extended.experimental_logical_device(1):\n self.w = variables.Variable(w)\n\n def __call__(self, x):\n replica_ctx = distribution_strategy_context.get_replica_context()\n with replica_ctx.experimental_logical_device(0):\n y = self.v * x\n with replica_ctx.experimental_logical_device(1):\n z = self.w * y\n return z\n\n def change_weights_op(self, v_new, w_new):\n return control_flow_ops.group([self.v.assign(v_new),\n self.w.assign(w_new)])\n\n resolver = get_tpu_cluster_resolver()\n remote.connect_to_cluster(resolver)\n topology = tpu_strategy_util.initialize_tpu_system(resolver)\n device_assignment = device_assignment_lib.DeviceAssignment(\n topology, core_assignment=[[[0, 0, 0, 0], [0, 0, 0, 1]]])\n strategy = tpu_lib.TPUStrategyV2(\n resolver,\n experimental_device_assignment=device_assignment)\n\n with strategy.scope():\n model = PartitionedModel(2., 3.)\n\n checkpoint_dir = self.get_temp_dir()\n checkpoint_prefix = os.path.join(checkpoint_dir, \"ckpt\")\n checkpoint = util.Checkpoint(model=model)\n\n with self.cached_session() as sess:\n self.evaluate(variables.global_variables_initializer())\n checkpoint.save(file_prefix=checkpoint_prefix)\n\n self.evaluate(model.change_weights_op(1., 4.))\n result = strategy.run(def_function.function(model), args=(5.0,))\n self.assertEqual(20., self.evaluate(result))\n\n status = checkpoint.restore(\n checkpoint_management.latest_checkpoint(checkpoint_dir))\n status.run_restore_ops(sess) # must run restore op in non-eager mode.\n status.assert_consumed()\n status.assert_existing_objects_matched()\n result = strategy.run(def_function.function(model), args=(5.0,))\n self.assertEqual(30., self.evaluate(result))\n\n\nclass DeviceAssignmentTest(test.TestCase):\n\n def test_core_assignment(self):\n resolver = get_tpu_cluster_resolver()\n remote.connect_to_cluster(resolver)\n topology = tpu_strategy_util.initialize_tpu_system(resolver)\n device_assignment = device_assignment_lib.DeviceAssignment(\n topology, core_assignment=[[[0, 0, 0, 0]]])\n self.assertAllEqual([[[0, 0, 0, 0]]], device_assignment.core_assignment)\n self.assertEqual(1, device_assignment.num_cores_per_replica)\n self.assertEqual(1, device_assignment.num_replicas)\n self.assertEqual(\"/task:0/device:TPU:0\", device_assignment.tpu_device())\n self.assertEqual(\"/task:0/device:CPU:0\", device_assignment.host_device())\n\n def test_device_assignment_strategy_properties(self):\n resolver = get_tpu_cluster_resolver()\n remote.connect_to_cluster(resolver)\n topology = tpu_strategy_util.initialize_tpu_system(resolver)\n device_assignment = device_assignment_lib.DeviceAssignment(\n topology, core_assignment=[[[0, 0, 0, 0]]])\n strategy = tpu_lib.TPUStrategyV2(\n resolver,\n experimental_device_assignment=device_assignment)\n self.assertEqual(strategy.extended.num_hosts, 1)\n self.assertEqual(strategy.num_replicas_in_sync, 1)\n self.assertEqual(strategy.extended.num_replicas_per_host, 1) # pylint: disable=protected-access\n\n def test_device_assignment_constants(self):\n resolver = get_tpu_cluster_resolver()\n remote.connect_to_cluster(resolver)\n topology = tpu_strategy_util.initialize_tpu_system(resolver)\n device_assignment = device_assignment_lib.DeviceAssignment(\n topology,\n core_assignment=device_assignment_lib.SINGLE_CORE_ASSIGNMENT)\n self.assertAllEqual([[[0, 0, 0, 0]]], device_assignment.core_assignment)\n self.assertEqual(1, device_assignment.num_cores_per_replica)\n self.assertEqual(1, device_assignment.num_replicas)\n self.assertEqual(\"/task:0/device:TPU:0\", device_assignment.tpu_device())\n self.assertEqual(\"/task:0/device:CPU:0\", device_assignment.host_device())\n\n def test_variables_mismatched_device_assignment(self):\n resolver = get_tpu_cluster_resolver()\n remote.connect_to_cluster(resolver)\n topology = tpu_strategy_util.initialize_tpu_system(resolver)\n\n strategy0 = tpu_lib.TPUStrategyV2(resolver)\n self.assertEqual(\n (\"/job:localhost/replica:0/task:0/device:TPU:0\",\n \"/job:localhost/replica:0/task:0/device:TPU:1\"),\n strategy0.extended.worker_devices)\n\n with strategy0.scope():\n v = variables.Variable(1.)\n\n v1_assign_op = strategy0.experimental_local_results(v)[1].assign(42.)\n\n with self.cached_session():\n self.evaluate(variables.global_variables_initializer())\n self.evaluate(v1_assign_op)\n self.assertAllEqual([1., 42.],\n self.evaluate(\n strategy0.experimental_local_results(v)))\n\n # Second strategy has devices reversed relative to the first.\n device_assignment = device_assignment_lib.DeviceAssignment(\n topology, core_assignment=[[[0, 0, 0, 1]], [[0, 0, 0, 0]]])\n strategy1 = tpu_lib.TPUStrategyV2(\n resolver,\n experimental_device_assignment=device_assignment)\n self.assertEqual(\n (\"/job:localhost/replica:0/task:0/device:TPU:1\",\n \"/job:localhost/replica:0/task:0/device:TPU:0\"),\n strategy1.extended.worker_devices)\n\n v_read = strategy1.run(def_function.function(v.read_value))\n\n with self.cached_session():\n self.assertAllEqual([42., 1.],\n self.evaluate(\n strategy0.experimental_local_results(v_read)))\n\n\nif __name__ == \"__main__\":\n test.main()\n", "# Copyright 2020 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\"\"\"Common utils for benchmarks.\"\"\"\n\nimport timeit\nimport numpy as np\n\nimport tensorflow as tf\n\nfrom tensorflow.python.keras.benchmarks import distribution_util\n\n\ndef get_benchmark_name(name):\n \"\"\"Split the suffix of the benchmark name.\n\n For example, for the name = 'benchmark_layer_call__Conv2D_small_shape',\n the return value is ['Conv2D', 'small', 'shape'].\n\n This is to generate the metadata of the benchmark test.\n\n Args:\n name: A string, the benchmark name.\n\n Returns:\n A list of strings of the suffix in the benchmark name.\n \"\"\"\n if '__' not in name or '_' not in name:\n raise ValueError('The format of the benchmark name is wrong.')\n return name.split('__')[-1].split('_')\n\n\ndef generate_benchmark_params_cpu_gpu(*params_list):\n \"\"\"Extend the benchmark names with CPU and GPU suffix.\n\n Args:\n *params_list: A list of tuples represents the benchmark parameters.\n\n Returns:\n A list of strings with the benchmark name extended with CPU and GPU suffix.\n \"\"\"\n benchmark_params = []\n for params in params_list:\n benchmark_params.extend([\n ((param[0] + '_CPU',) + param[1:]) for param in params\n ])\n benchmark_params.extend([\n ((param[0] + '_GPU',) + param[1:]) for param in params\n ])\n return benchmark_params\n\n\ndef get_keras_examples_metadata(keras_model,\n batch_size,\n impl='.keras.cfit_graph'):\n return {\n 'model_name': 'keras_examples',\n 'implementation': keras_model + impl,\n 'parameters': 'bs_' + str(batch_size),\n }\n\n\nclass TimerCallBack(tf.keras.callbacks.Callback):\n \"\"\"Callback for logging time in each epoch or batch.\"\"\"\n\n def __init__(self):\n self.times = []\n self.timer = timeit.default_timer\n self.startup_time = timeit.default_timer()\n self.recorded_startup = False\n\n def on_epoch_begin(self, e, logs):\n self.epoch_start_time = self.timer()\n\n def on_epoch_end(self, e, logs):\n self.times.append(self.timer() - self.epoch_start_time)\n\n def on_batch_end(self, e, logs):\n if not self.recorded_startup:\n self.startup_time = self.timer() - self.startup_time\n self.recorded_startup = True\n\n\ndef measure_performance(model_fn,\n x=None,\n y=None,\n epochs=2,\n batch_size=32,\n run_iters=4,\n optimizer=None,\n loss=None,\n metrics=None,\n verbose=0,\n num_gpus=0,\n distribution_strategy='off'):\n \"\"\"Run models and measure the performance.\n\n Args:\n model_fn: Model function to be benchmarked.\n x: Input data. See `x` in the `fit()` method of `keras.Model`.\n y: Target data. See `y` in the `fit()` method of `keras.Model`.\n epochs: Integer. Number of epochs to train the model.\n If unspecified, `epochs` will default to 2.\n batch_size: Integer. Number of samples per gradient update. If unspecified,\n `batch_size` will default to 32.\n run_iters: Integer. Number of iterations to run the performance measurement.\n If unspecified, `run_iters` will default to 4.\n optimizer: String (name of optimizer) or optimizer instance. See\n `tf.keras.optimizers`.\n loss: String (name of objective function), objective function or\n `tf.keras.losses.Loss` instance. See `tf.keras.losses`.\n metrics: Lists of metrics to be evaluated by the model during training. See\n `metrics` in the `compile()` method of `keras.Model`.\n verbose: 0, 1, 2. Verbosity mode. See `verbose` in the `fit()` method of\n `keras.Model`. If unspecified, `verbose` will default to 0.\n num_gpus: Number of GPUs to run the model.\n distribution_strategy: Distribution strategies. It could be\n `multi_worker_mirrored`, `one_device`, `mirrored`. If unspecified,\n `distribution_strategy` will default to 'off'. Note that, `TPU`\n and `parameter_server` are not supported yet.\n\n Returns:\n Performance summary, which contains build_time, compile_time,\n startup_time, avg_epoch_time, wall_time, exp_per_sec, epochs,\n distribution_strategy.\n\n Raise:\n ValueError: If `x` is none or if `optimizer` is not provided or\n if `loss` is not provided or if `num_gpus` is negative.\n \"\"\"\n if 'x' is None:\n raise ValueError('Input data is required.')\n if 'optimizer' is None:\n raise ValueError('Optimizer is required.')\n if 'loss' is None:\n raise ValueError('Loss function is required.')\n if num_gpus < 0:\n raise ValueError('`num_gpus` cannot be negative')\n\n # TODO(xingyulong): we will add tfds support later and\n # get the `num_examples` from info.\n num_examples = x.shape[0]\n\n build_time_list, compile_time_list, startup_time_list = [], [], []\n avg_epoch_time_list, wall_time_list, exp_per_sec_list = [], [], []\n total_num_examples = epochs * num_examples\n\n strategy = distribution_util.get_distribution_strategy(\n distribution_strategy=distribution_strategy, num_gpus=num_gpus)\n\n for _ in range(run_iters):\n timer = timeit.default_timer\n start_time = timer()\n # Init the distribution strategy scope for each iteration.\n strategy_scope = distribution_util.get_strategy_scope(strategy)\n with strategy_scope:\n t0 = timer()\n model = model_fn()\n build_time = timer() - t0\n\n t1 = timer()\n model.compile(\n optimizer=optimizer,\n loss=loss,\n metrics=metrics,\n )\n compile_time = timer() - t1\n # Run one warm up epoch.\n model.fit(x=x, y=y, batch_size=batch_size, epochs=1)\n cbk = TimerCallBack()\n t2 = timer()\n model.fit(\n x=x,\n y=y,\n batch_size=batch_size,\n epochs=epochs,\n callbacks=[cbk],\n verbose=verbose)\n end_time = timer()\n\n build_time_list.append(build_time)\n compile_time_list.append(compile_time)\n startup_time_list.append(cbk.startup_time)\n avg_epoch_time_list.append(np.mean(cbk.times))\n wall_time_list.append(end_time - start_time)\n exp_per_sec_list.append(total_num_examples / (end_time - t2))\n\n metrics = []\n metrics.append({'name': 'build_time', 'value': np.mean(build_time_list)})\n metrics.append({'name': 'compile_time', 'value': np.mean(compile_time_list)})\n metrics.append({'name': 'startup_time', 'value': np.mean(startup_time_list)})\n metrics.append({\n 'name': 'avg_epoch_time',\n 'value': np.mean(avg_epoch_time_list)\n })\n metrics.append({'name': 'exp_per_sec', 'value': np.mean(exp_per_sec_list)})\n metrics.append({'name': 'epochs', 'value': epochs})\n\n wall_time = np.mean(wall_time_list)\n extras = {\n 'distribution_strategy': distribution_strategy,\n 'num_gpus': num_gpus\n }\n\n return metrics, wall_time, extras\n", "# Copyright 2018 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 Model subclassing.\"\"\"\n\nimport copy\nimport os\n\nfrom absl.testing import parameterized\nimport numpy as np\n\nfrom tensorflow.python import keras\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.keras import combinations\nfrom tensorflow.python.keras import keras_parameterized\nfrom tensorflow.python.keras import testing_utils\nfrom tensorflow.python.keras.tests import model_subclassing_test_util as model_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import embedding_ops\nfrom tensorflow.python.ops import init_ops\nfrom tensorflow.python.ops import variables as variables_lib\nfrom tensorflow.python.platform import test\nfrom tensorflow.python.training.tracking import data_structures\n\ntry:\n import h5py # pylint:disable=g-import-not-at-top\nexcept ImportError:\n h5py = None\n\n\n@keras_parameterized.run_all_keras_modes\nclass ModelSubclassingTest(keras_parameterized.TestCase):\n\n def test_custom_build(self):\n class DummyModel(keras.Model):\n\n def __init__(self):\n super(DummyModel, self).__init__()\n self.dense1 = keras.layers.Dense(32, activation='relu')\n self.uses_custom_build = False\n\n def call(self, inputs):\n return self.dense1(inputs)\n\n def build(self, input_shape):\n self.uses_custom_build = True\n\n test_model = DummyModel()\n dummy_data = array_ops.ones((32, 50))\n test_model(dummy_data)\n self.assertTrue(test_model.uses_custom_build, 'Model should use user '\n 'defined build when called.')\n\n def test_attribute_conflict_error(self):\n\n class ModelWithProperty(keras.Model):\n\n @property\n def read_only(self):\n return 1.\n\n m = ModelWithProperty()\n with self.assertRaisesRegex(AttributeError, 'read_only'):\n m.read_only = 2.\n\n def test_custom_build_with_fit(self):\n\n class DummyModel(keras.Model):\n\n def __init__(self):\n super(DummyModel, self).__init__()\n self.layer1 = keras.layers.Dense(10, activation='relu')\n\n def build(self, input_shape):\n self.layer2 = keras.layers.Dense(1, activation='relu')\n\n def call(self, inputs):\n return self.layer2(self.layer1(inputs))\n\n model = DummyModel()\n model.compile(\n 'sgd',\n 'mse',\n run_eagerly=testing_utils.should_run_eagerly())\n model.fit(np.ones((10, 10)), np.ones((10, 1)), batch_size=2, epochs=2)\n self.assertLen(model.layers, 2)\n self.assertLen(model.trainable_variables, 4)\n\n def test_dataset_dict_with_fit(self):\n\n class MyModel(keras.Model):\n\n def __init__(self):\n super(MyModel, self).__init__()\n self.dense1 = keras.layers.Dense(1)\n self.dense2 = keras.layers.Dense(1)\n self.add = keras.layers.Add()\n\n def call(self, x):\n return self.add([self.dense1(x['a']), self.dense2(x['b'])])\n\n model = MyModel()\n model.compile(\n 'sgd',\n 'mse',\n run_eagerly=testing_utils.should_run_eagerly())\n\n data = dataset_ops.DatasetV2.from_tensor_slices(({\n 'a': np.ones((32, 10)),\n 'b': np.ones((32, 20))\n }, np.ones((32, 1)))).batch(2)\n model.fit(data, epochs=2)\n\n def test_invalid_input_shape_build(self):\n num_classes = 2\n input_dim = 50\n\n model = testing_utils.SmallSubclassMLP(\n num_hidden=32, num_classes=num_classes, use_dp=True, use_bn=True)\n\n self.assertFalse(model.built, 'Model should not have been built')\n self.assertFalse(model.weights, ('Model should have no weights since it '\n 'has not been built.'))\n with self.assertRaisesRegex(ValueError,\n 'input shape is not one of the valid types'):\n model.build(input_shape=tensor_shape.Dimension(input_dim))\n\n def test_embed_dtype_with_subclass_build(self):\n class Embedding(keras.layers.Layer):\n \"\"\"An Embedding layer.\"\"\"\n\n def __init__(self, vocab_size, embedding_dim, **kwargs):\n super(Embedding, self).__init__(**kwargs)\n self.vocab_size = vocab_size\n self.embedding_dim = embedding_dim\n\n def build(self, _):\n self.embedding = self.add_variable(\n 'embedding_kernel',\n shape=[self.vocab_size, self.embedding_dim],\n dtype=np.float32,\n initializer=init_ops.random_uniform_initializer(-0.1, 0.1),\n trainable=True)\n\n def call(self, x):\n return embedding_ops.embedding_lookup(self.embedding, x)\n\n class EmbedModel(keras.Model):\n\n def __init__(self, vocab_size, embed_size):\n super(EmbedModel, self).__init__()\n self.embed1 = Embedding(vocab_size, embed_size)\n\n def call(self, inputs):\n return self.embed1(inputs)\n\n model = EmbedModel(100, 20)\n self.assertFalse(model.built, 'Model should not have been built')\n self.assertFalse(model.weights, ('Model should have no weights since it '\n 'has not been built.'))\n with self.assertRaisesRegex(\n ValueError, 'if your layers do not support float type inputs'):\n model.build(input_shape=(35, 20))\n\n def test_single_time_step_rnn_build(self):\n dim = 4\n timesteps = 1\n batch_input_shape = (None, timesteps, dim)\n units = 3\n\n class SimpleRNNModel(keras.Model):\n\n def __init__(self):\n super(SimpleRNNModel, self).__init__()\n self.lstm = keras.layers.LSTM(units)\n\n def call(self, inputs):\n return self.lstm(inputs)\n\n model = SimpleRNNModel()\n self.assertFalse(model.built, 'Model should not have been built')\n self.assertFalse(model.weights, ('Model should have no weights since it '\n 'has not been built.'))\n model.build(batch_input_shape)\n self.assertTrue(model.weights, ('Model should have weights now that it '\n 'has been properly built.'))\n self.assertTrue(model.built, 'Model should be built after calling `build`.')\n model(array_ops.ones((32, timesteps, dim)))\n\n def test_single_io_subclass_build(self):\n num_classes = 2\n input_dim = 50\n batch_size = None\n\n model = testing_utils.SmallSubclassMLP(\n num_hidden=32, num_classes=num_classes, use_dp=True, use_bn=True)\n\n self.assertFalse(model.built, 'Model should not have been built')\n self.assertFalse(model.weights, ('Model should have no weights since it '\n 'has not been built.'))\n model.build(input_shape=(batch_size, input_dim))\n self.assertTrue(model.weights, ('Model should have weights now that it '\n 'has been properly built.'))\n self.assertTrue(model.built, 'Model should be built after calling `build`.')\n model(array_ops.ones((32, input_dim)))\n\n def test_single_io_dimension_subclass_build(self):\n num_classes = 2\n input_dim = tensor_shape.Dimension(50)\n batch_size = tensor_shape.Dimension(None)\n\n model = testing_utils.SmallSubclassMLP(\n num_hidden=32, num_classes=num_classes, use_dp=True, use_bn=True)\n\n self.assertFalse(model.built, 'Model should not have been built')\n self.assertFalse(model.weights, ('Model should have no weights since it '\n 'has not been built.'))\n model.build(input_shape=(batch_size, input_dim))\n self.assertTrue(model.weights, ('Model should have weights now that it '\n 'has been properly built.'))\n self.assertTrue(model.built, 'Model should be built after calling `build`.')\n model(array_ops.ones((32, input_dim)))\n\n def test_multidim_io_subclass_build(self):\n num_classes = 10\n # Input size, e.g. image\n batch_size = 32\n input_shape = (32, 32, 3)\n\n model = model_util.SimpleConvTestModel(num_classes)\n self.assertFalse(model.built, 'Model should not have been built')\n self.assertFalse(model.weights, ('Model should have no weights since it '\n 'has not been built.'))\n batch_input_shape = (batch_size,) + input_shape\n model.build(input_shape=batch_input_shape)\n self.assertTrue(model.weights, ('Model should have weights now that it '\n 'has been properly built.'))\n self.assertTrue(model.built, 'Model should be built after calling `build`.')\n\n model(array_ops.ones(batch_input_shape))\n\n def test_tensorshape_io_subclass_build(self):\n num_classes = 10\n # Input size, e.g. image\n batch_size = None\n input_shape = (32, 32, 3)\n\n model = model_util.SimpleConvTestModel(num_classes)\n self.assertFalse(model.built, 'Model should not have been built')\n self.assertFalse(model.weights, ('Model should have no weights since it '\n 'has not been built.'))\n model.build(\n input_shape=tensor_shape.TensorShape((batch_size,) + input_shape))\n self.assertTrue(model.weights, ('Model should have weights now that it '\n 'has been properly built.'))\n self.assertTrue(model.built, 'Model should be built after calling `build`.')\n\n model(array_ops.ones((32,) + input_shape))\n\n def test_subclass_save_model(self):\n num_classes = 10\n # Input size, e.g. image\n batch_size = None\n input_shape = (32, 32, 3)\n\n model = model_util.SimpleConvTestModel(num_classes)\n self.assertFalse(model.built, 'Model should not have been built')\n self.assertFalse(model.weights, ('Model should have no weights since it '\n 'has not been built.'))\n model.build(\n input_shape=tensor_shape.TensorShape((batch_size,) + input_shape))\n self.assertTrue(model.weights, ('Model should have weights now that it '\n 'has been properly built.'))\n self.assertTrue(model.built, 'Model should be built after calling `build`.')\n weights = model.get_weights()\n\n tf_format_name = os.path.join(self.get_temp_dir(), 'ckpt')\n model.save_weights(tf_format_name)\n if h5py is not None:\n hdf5_format_name = os.path.join(self.get_temp_dir(), 'weights.h5')\n model.save_weights(hdf5_format_name)\n\n model = model_util.SimpleConvTestModel(num_classes)\n model.build(\n input_shape=tensor_shape.TensorShape((batch_size,) + input_shape))\n if h5py is not None:\n model.load_weights(hdf5_format_name)\n self.assertAllClose(weights, model.get_weights())\n model.load_weights(tf_format_name)\n self.assertAllClose(weights, model.get_weights())\n\n def test_multi_io_subclass_build(self):\n batch_size = None\n num_samples = 1000\n input_dim = 50\n model = model_util.get_multi_io_subclass_model()\n self.assertFalse(model.built, 'Model should not have been built')\n self.assertFalse(model.weights, ('Model should have no weights since it '\n 'has not been built.'))\n batch_input_shape = tensor_shape.TensorShape((batch_size, input_dim))\n model.build(\n input_shape=[batch_input_shape, batch_input_shape])\n self.assertTrue(model.weights, ('Model should have weights now that it '\n 'has been properly built.'))\n self.assertTrue(model.built, 'Model should be built after calling `build`.')\n x1 = array_ops.ones((num_samples, input_dim))\n x2 = array_ops.ones((num_samples, input_dim))\n model([x1, x2])\n\n def test_summary(self):\n\n class ToString(object):\n\n def __init__(self):\n self.contents = ''\n\n def __call__(self, msg):\n self.contents += msg + '\\n'\n\n # Single-io\n model = testing_utils.SmallSubclassMLP(\n num_hidden=32, num_classes=4, use_bn=True, use_dp=True)\n model(np.ones((3, 4))) # need to build model first\n print_fn = ToString()\n model.summary(print_fn=print_fn)\n self.assertIn('Trainable params: 356', print_fn.contents)\n\n # Multi-io\n model = model_util.get_multi_io_subclass_model(\n num_classes=(5, 6), use_bn=True, use_dp=True)\n model([np.ones((3, 4)), np.ones((3, 4))]) # need to build model first\n print_fn = ToString()\n model.summary(print_fn=print_fn)\n self.assertIn('Trainable params: 587', print_fn.contents)\n\n # Single-io with unused layer\n model = testing_utils.SmallSubclassMLP(\n num_hidden=32, num_classes=4, use_bn=True, use_dp=True)\n model.unused_layer = keras.layers.Dense(10)\n model(np.ones((3, 4))) # need to build model first\n print_fn = ToString()\n model.summary(print_fn=print_fn)\n self.assertIn('Trainable params: 356', print_fn.contents)\n self.assertIn('0 (unused)', print_fn.contents)\n\n def test_no_dependency(self):\n class Foo(keras.Model):\n\n def __init__(self):\n super(Foo, self).__init__()\n self.isdep = keras.layers.Dense(1)\n self.notdep = data_structures.NoDependency(keras.layers.Dense(2))\n self.notdep_var = data_structures.NoDependency(\n variables_lib.Variable(1., name='notdep_var'))\n\n m = Foo()\n self.assertEqual([m.isdep, m.notdep], m.layers)\n self.assertEqual(1, len(m._checkpoint_dependencies))\n self.assertIs(m.isdep, m._checkpoint_dependencies[0].ref)\n self.assertEqual('notdep_var:0', m.notdep_var.name)\n\n def test_extra_variable(self):\n\n class ExtraVar(keras.Model):\n\n def __init__(self):\n super(ExtraVar, self).__init__()\n self.dense = keras.layers.Dense(1)\n self.var = variables_lib.Variable(1.)\n self.not_trainable_var = variables_lib.Variable(2., trainable=False)\n\n def call(self, inputs):\n return self.dense(inputs + self.var)\n\n m = ExtraVar()\n self.assertTrue(m.trainable)\n self.assertEqual([m.dense], m.layers)\n self.assertEqual([m.var, m.not_trainable_var], m.variables)\n self.assertEqual([m.var], m.trainable_variables)\n self.assertEqual([m.not_trainable_var], m.non_trainable_variables)\n self.assertLen(m.get_weights(), 2)\n m.trainable = False\n self.assertEqual([m.var, m.not_trainable_var], m.variables)\n self.assertEqual([], m.trainable_variables)\n self.assertEqual([m.var, m.not_trainable_var], m.non_trainable_variables)\n self.assertLen(m.get_weights(), 2)\n m.trainable = True\n\n m(array_ops.ones([1, 1]))\n\n self.assertEqual([m.dense.kernel, m.dense.bias], m.dense.variables)\n self.assertEqual([m.dense.kernel, m.dense.bias], m.dense.weights)\n\n self.assertLen(m.get_weights(), 4)\n self.assertEqual([m.dense.kernel, m.dense.bias, m.var, m.not_trainable_var],\n m.variables)\n self.assertEqual([m.dense.kernel, m.dense.bias, m.var],\n m.trainable_variables)\n self.assertEqual([m.not_trainable_var], m.non_trainable_variables)\n\n m.dense.trainable = False\n self.assertEqual(\n [m.dense.kernel, m.dense.bias, m.var, m.not_trainable_var],\n m.variables)\n self.assertEqual([m.var], m.trainable_variables)\n self.assertEqual([m.dense.kernel, m.dense.bias, m.not_trainable_var],\n m.non_trainable_variables)\n self.assertLen(m.get_weights(), 4)\n\n def test_add_weight_in_model(self):\n\n class MyModel(keras.Model):\n\n def __init__(self):\n super(MyModel, self).__init__()\n self.b = self.add_weight('bias', (10,))\n self.c = self.add_weight('bias2', (10,), trainable=False)\n\n def call(self, inputs):\n return inputs + self.b + self.c\n\n x = ops.convert_to_tensor_v2_with_dispatch(np.ones((10, 10), 'float32'))\n model = MyModel()\n model(x)\n self.assertEqual(1, len(model.trainable_weights))\n self.assertEqual(1, len(model.non_trainable_weights))\n self.assertEqual(2, len(model.weights))\n\n class MyModelCustomBuild(keras.Model):\n\n def build(self, input_shape):\n self.b = self.add_weight('bias', (10,))\n self.c = self.add_weight('bias2', (10,), trainable=False)\n\n def call(self, inputs):\n return inputs + self.b + self.c\n\n x = ops.convert_to_tensor_v2_with_dispatch(np.ones((10, 10), 'float32'))\n model = MyModelCustomBuild()\n model(x)\n self.assertEqual(1, len(model.trainable_weights))\n self.assertEqual(1, len(model.non_trainable_weights))\n self.assertEqual(2, len(model.weights))\n\n def test_add_update_in_model(self):\n\n class MyModel(keras.Model):\n\n def __init__(self):\n super(MyModel, self).__init__()\n self.b = self.add_weight('bias', (10,))\n self.c = self.add_weight('bias2', (10,))\n\n def call(self, inputs):\n # Unconditional\n self.add_update(self.b.assign(self.b * 2))\n # Conditional\n self.add_update(self.c.assign(inputs[1, :]))\n return inputs + self.b + self.c\n\n x = ops.convert_to_tensor_v2_with_dispatch(np.ones((10, 10), 'float32'))\n model = MyModel()\n model(x)\n\n if context.executing_eagerly():\n self.assertEqual(0, len(model.updates))\n else:\n self.assertEqual(2, len(model.updates))\n\n\nclass GraphSpecificModelSubclassingTests(test.TestCase):\n\n def test_single_io_workflow_with_tensors(self):\n num_classes = 2\n num_samples = 10\n input_dim = 50\n\n with ops.Graph().as_default(), self.cached_session():\n model = testing_utils.SmallSubclassMLP(\n num_hidden=32, num_classes=num_classes, use_dp=True, use_bn=True)\n model.compile(loss='mse', optimizer='rmsprop')\n\n x = array_ops.ones((num_samples, input_dim))\n y = array_ops.zeros((num_samples, num_classes))\n\n model.fit(x, y, epochs=2, steps_per_epoch=10, verbose=0)\n _ = model.evaluate(steps=10, verbose=0)\n\n def test_multi_io_workflow_with_tensors(self):\n num_classes = (2, 3)\n num_samples = 10\n input_dim = 50\n\n with ops.Graph().as_default(), self.cached_session():\n model = model_util.get_multi_io_subclass_model(\n num_classes=num_classes, use_dp=True, use_bn=True)\n model.compile(loss='mse', optimizer='rmsprop')\n\n x1 = array_ops.ones((num_samples, input_dim))\n x2 = array_ops.ones((num_samples, input_dim))\n y1 = array_ops.zeros((num_samples, num_classes[0]))\n y2 = array_ops.zeros((num_samples, num_classes[1]))\n\n model.fit([x1, x2], [y1, y2], epochs=2, steps_per_epoch=10, verbose=0)\n _ = model.evaluate(steps=10, verbose=0)\n\n def test_updates_and_losses_for_nested_models_in_subclassed_model(self):\n\n # Case 1: deferred-build sequential nested in subclass.\n class TestModel1(keras.Model):\n\n def __init__(self):\n super(TestModel1, self).__init__()\n self.fc = keras.layers.Dense(10, input_shape=(784,),\n activity_regularizer='l1')\n self.bn = keras.Sequential([keras.layers.BatchNormalization(axis=1)])\n\n def call(self, x):\n return self.bn(self.fc(x))\n\n with ops.get_default_graph().as_default(), self.cached_session():\n model = TestModel1()\n\n x = array_ops.ones(shape=[100, 784], dtype='float32')\n model(x)\n self.assertLen(model.updates, 2)\n self.assertLen(model.losses, 1)\n\n # Case 2: placeholder-sequential nested in subclass.\n class TestModel2(keras.Model):\n\n def __init__(self):\n super(TestModel2, self).__init__()\n self.fc = keras.layers.Dense(10, input_shape=(784,),\n activity_regularizer='l1')\n self.bn = keras.Sequential(\n [keras.layers.BatchNormalization(axis=1, input_shape=(10,))])\n\n def call(self, x):\n return self.bn(self.fc(x))\n\n with ops.get_default_graph().as_default(), self.cached_session():\n model = TestModel2()\n\n x = array_ops.ones(shape=[100, 784], dtype='float32')\n model(x)\n self.assertEqual(len(model.get_updates_for(x)), 2)\n self.assertEqual(len(model.get_losses_for(x)), 1)\n\n # Case 3: functional-API model nested in subclass.\n with ops.get_default_graph().as_default():\n inputs = keras.Input((10,))\n outputs = keras.layers.BatchNormalization(axis=1)(inputs)\n bn = keras.Model(inputs, outputs)\n\n class TestModel3(keras.Model):\n\n def __init__(self):\n super(TestModel3, self).__init__()\n self.fc = keras.layers.Dense(10, input_shape=(784,),\n activity_regularizer='l1')\n self.bn = bn\n\n def call(self, x):\n return self.bn(self.fc(x))\n\n with self.cached_session():\n model = TestModel3()\n\n x = array_ops.ones(shape=[100, 784], dtype='float32')\n model(x)\n self.assertEqual(len(model.get_updates_for(x)), 2)\n self.assertEqual(len(model.get_losses_for(x)), 1)\n\n def test_multi_io_workflow_with_numpy_arrays_and_custom_placeholders(self):\n num_classes = (2, 3)\n num_samples = 1000\n input_dim = 50\n\n with ops.Graph().as_default(), self.cached_session():\n model = model_util.get_multi_io_subclass_model(\n num_classes=num_classes, use_dp=True, use_bn=True)\n model.compile(loss='mse', optimizer='rmsprop')\n\n x1 = np.ones((num_samples, input_dim))\n x2 = np.ones((num_samples, input_dim))\n y1 = np.zeros((num_samples, num_classes[0]))\n y2 = np.zeros((num_samples, num_classes[1]))\n\n x2_placeholder = array_ops.placeholder(\n dtype='float32', shape=(None, input_dim))\n model._set_inputs([x1, x2_placeholder])\n\n model.fit([x1, x2], [y1, y2], epochs=2, batch_size=32, verbose=0)\n _ = model.evaluate([x1, x2], [y1, y2], verbose=0)\n\n\[email protected](combinations.combine(mode=['graph', 'eager']))\nclass CustomCallSignatureTests(test.TestCase, parameterized.TestCase):\n\n def test_no_inputs_in_signature(self):\n model = model_util.CustomCallModel()\n first = array_ops.ones([2, 3])\n second = array_ops.ones([2, 5])\n output = model(first, second)\n self.evaluate([v.initializer for v in model.variables])\n expected_output = self.evaluate(model.dense1(first) + model.dense2(second))\n self.assertAllClose(expected_output, self.evaluate(output))\n output = model(first, second, fiddle_with_output='yes')\n self.assertAllClose(10. * expected_output, self.evaluate(output))\n output = model(first, second=second, training=False)\n self.assertAllClose(expected_output, self.evaluate(output))\n\n def test_training_args_call_build(self):\n input_dim = 2\n\n model = model_util.TrainingNoDefaultModel()\n self.assertFalse(model.built, 'Model should not have been built')\n self.assertFalse(model.weights, ('Model should have no weights since it '\n 'has not been built.'))\n model.build((None, input_dim))\n self.assertTrue(model.weights, ('Model should have weights now that it '\n 'has been properly built.'))\n self.assertTrue(model.built, 'Model should be built after calling `build`.')\n\n def test_training_and_mask_args_call_build(self):\n input_dim = 2\n\n model = model_util.TrainingMaskingModel()\n self.assertFalse(model.built, 'Model should not have been built')\n self.assertFalse(model.weights, ('Model should have no weights since it '\n 'has not been built.'))\n model.build((None, input_dim))\n self.assertTrue(model.weights, ('Model should have weights now that it '\n 'has been properly built.'))\n self.assertTrue(model.built, 'Model should be built after calling `build`.')\n\n def test_custom_call_kwargs_and_build(self):\n first_input_shape = (2, 3)\n second_input_shape = (2, 5)\n\n model = model_util.CustomCallModel()\n self.assertFalse(model.built, 'Model should not have been built')\n self.assertFalse(model.weights, ('Model should have no weights since it '\n 'has not been built.'))\n with self.assertRaisesRegex(ValueError,\n 'cannot build your model if it has positional'):\n model.build(input_shape=[first_input_shape, second_input_shape])\n\n def test_kwargs_in_signature(self):\n\n class HasKwargs(keras.Model):\n\n def call(self, x, y=3, **kwargs):\n return x\n\n model = HasKwargs()\n arg = array_ops.ones([1])\n model(arg, a=3)\n if not context.executing_eagerly():\n self.assertLen(model.inputs, 1)\n\n @test_util.assert_no_new_tensors\n @test_util.assert_no_garbage_created\n def test_training_no_default(self):\n if not context.executing_eagerly():\n return\n model = model_util.TrainingNoDefaultModel()\n arg = array_ops.ones([1, 1])\n model(arg, True)\n\n def test_positional_arg_in_call(self):\n\n class ModelWithPositionalArgs(keras.Model):\n\n def call(self, x, x2, x3=None):\n return x + x2\n\n x = np.ones((10, 1))\n y = np.ones((10, 1))\n m = ModelWithPositionalArgs()\n m.compile('sgd', 'mse')\n with self.assertRaisesRegex(ValueError, r'Models passed to `fit`'):\n m.fit(x, y, batch_size=2)\n with self.assertRaisesRegex(ValueError, r'Models passed to `evaluate`'):\n m.evaluate(x, y, batch_size=2)\n with self.assertRaisesRegex(ValueError, r'Models passed to `predict`'):\n m.predict(x, batch_size=2)\n with self.assertRaisesRegex(ValueError,\n r'Models passed to `train_on_batch`'):\n m.train_on_batch(x, y)\n with self.assertRaisesRegex(ValueError,\n r'Models passed to `test_on_batch`'):\n m.test_on_batch(x, y)\n with self.assertRaisesRegex(ValueError,\n r'Models passed to `predict_on_batch`'):\n m.predict_on_batch(x)\n\n def test_deepcopy(self):\n if not context.executing_eagerly():\n self.skipTest('Run in eager mode only.')\n\n class MyModel(keras.Model):\n\n def __init__(self):\n super(MyModel, self).__init__()\n self.my_variable = variables_lib.Variable(0.0, trainable=False)\n self.layer = keras.layers.Dense(4)\n\n def call(self, obs):\n return self.layer(obs)\n\n model = MyModel()\n model.my_variable.assign_add(1.0)\n\n new_model = copy.deepcopy(model)\n self.assertEqual(model.my_variable.numpy(), 1.0)\n self.assertEqual(new_model.my_variable.numpy(), 1.0)\n\n model.my_variable.assign_add(1.0)\n self.assertEqual(model.my_variable.numpy(), 2.0)\n self.assertEqual(new_model.my_variable.numpy(), 1.0)\n\n # Check that Trackable logic still works.\n self.assertLen(new_model.variables, 1)\n self.assertLen(new_model.layers, 1)\n\n def test_batch_counters_not_in_variables(self):\n\n class MyModel(keras.Model):\n\n def __init__(self):\n super(MyModel, self).__init__()\n self.layer = keras.layers.Dense(4)\n\n def call(self, obs):\n return self.layer(obs)\n\n model = MyModel()\n model(np.ones((10, 10)))\n self.assertLen(model.variables, 2)\n\n\nif __name__ == '__main__':\n test.main()\n", "# 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\"\"\"Tests for tensorflow.ops.linalg_grad.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import gradient_checker_v2\nfrom tensorflow.python.ops import gradients_impl\nfrom tensorflow.python.ops import linalg_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops.linalg import linalg_impl\nfrom tensorflow.python.platform import test as test_lib\n\n\ndef _AddTest(test, op_name, testcase_name, fn):\n test_name = '_'.join(['test', op_name, testcase_name])\n if hasattr(test, test_name):\n raise RuntimeError('Test %s defined more than once' % test_name)\n setattr(test, test_name, fn)\n\n\nclass ShapeTest(test_lib.TestCase):\n\n @test_util.run_deprecated_v1\n def testBatchGradientUnknownSize(self):\n with self.cached_session():\n batch_size = constant_op.constant(3)\n matrix_size = constant_op.constant(4)\n batch_identity = array_ops.tile(\n array_ops.expand_dims(\n array_ops.diag(array_ops.ones([matrix_size])), 0),\n [batch_size, 1, 1])\n determinants = linalg_ops.matrix_determinant(batch_identity)\n reduced = math_ops.reduce_sum(determinants)\n sum_grad = gradients_impl.gradients(reduced, batch_identity)[0]\n self.assertAllClose(batch_identity, self.evaluate(sum_grad))\n\n\nclass MatrixUnaryFunctorGradientTest(test_lib.TestCase):\n pass # Filled in below\n\n\ndef _GetMatrixUnaryFunctorGradientTest(functor_, dtype_, shape_, **kwargs_):\n\n @test_util.enable_control_flow_v2\n @test_util.run_in_graph_and_eager_modes(use_gpu=True)\n @test_util.run_without_tensor_float_32(\n 'Tests `tf.linalg.expm`, which call matmul. Additionally, calls ops '\n 'which do matmul in their gradient, such as MatrixSolve.')\n def Test(self):\n\n def RandomInput():\n np.random.seed(1)\n return np.random.uniform(\n low=-1.0, high=1.0,\n size=np.prod(shape_)).reshape(shape_).astype(dtype_)\n\n if functor_.__name__ == 'matrix_square_root':\n # Square the input matrix to ensure that its matrix square root exists\n f = lambda x: functor_(math_ops.matmul(x, x), **kwargs_)\n else:\n f = functor_\n\n # Optimal stepsize for central difference is O(epsilon^{1/3}).\n epsilon = np.finfo(dtype_).eps\n delta = epsilon**(1.0 / 3.0)\n # tolerance obtained by looking at actual differences using\n # np.linalg.norm(theoretical-numerical, np.inf) on -mavx build\n tol = 1e-6 if dtype_ == np.float64 else 0.05\n\n theoretical, numerical = gradient_checker_v2.compute_gradient(\n f, [RandomInput()], delta=delta)\n self.assertAllClose(theoretical, numerical, atol=tol, rtol=tol)\n\n return Test\n\n\nclass MatrixBinaryFunctorGradientTest(test_lib.TestCase):\n pass # Filled in below\n\n\ndef _GetMatrixBinaryFunctorGradientTest(functor_,\n dtype_,\n shape_,\n float32_tol_fudge=1.0,\n **kwargs_):\n\n @test_util.run_in_graph_and_eager_modes(use_gpu=True)\n @test_util.run_without_tensor_float_32(\n 'Tests `tf.linalg.lstsq`, which call matmul. Additionally, calls ops '\n 'which do matmul in their gradient, such as MatrixSolveLs.')\n # TODO(b/164254522): With TensorFloat-32, some tests fails with extremely high\n # absolute and relative differences when calling assertAllClose. For example,\n # the test test_MatrixSolveLsGradient_float32_10_10_1e-06 of class\n # MatrixBinaryFunctorGradientTest fails with a max absolute difference of\n # 0.883 and a max relative difference of 736892. We should consider disabling\n # TensorFloat-32 within `tf.linalg.lstsq and perhaps other linear algebra\n # functions, even if TensorFloat-32 is allowed globally.\n def Test(self):\n\n def RandomInput():\n np.random.seed(1)\n return np.random.uniform(\n low=-1.0, high=1.0,\n size=np.prod(shape_)).reshape(shape_).astype(dtype_)\n\n fixed = RandomInput()\n\n # Optimal stepsize for central difference is O(epsilon^{1/3}).\n epsilon = np.finfo(dtype_).eps\n delta = epsilon**(1.0 / 3.0)\n # tolerance obtained by looking at actual differences using\n # np.linalg.norm(theoretical-numerical, np.inf) on -mavx build\n tol = 1e-6 if dtype_ == np.float64 else float32_tol_fudge * 0.05\n\n # check gradient w.r.t. left argument.\n theoretical, numerical = gradient_checker_v2.compute_gradient(\n lambda x: functor_(x, fixed, **kwargs_), [RandomInput()], delta=delta)\n self.assertAllClose(theoretical, numerical, atol=tol, rtol=tol)\n\n # check gradient w.r.t. right argument.\n theoretical, numerical = gradient_checker_v2.compute_gradient(\n lambda y: functor_(fixed, y, **kwargs_), [RandomInput()], delta=delta)\n self.assertAllClose(theoretical, numerical, atol=tol, rtol=tol)\n\n return Test\n\n\ndef _GetBandedTriangularSolveGradientTest(\n functor_,\n dtype_,\n shape_,\n float32_tol_fudge=1.0, # pylint: disable=redefined-outer-name\n **kwargs_):\n\n @test_util.run_in_graph_and_eager_modes(use_gpu=True)\n def Test(self):\n n = shape_[-1]\n\n np.random.seed(1)\n # Make sure invertible.\n a_np = np.random.uniform(low=1.0, high=2.0, size=shape_).astype(dtype_)\n a = constant_op.constant(a_np)\n\n b_np = np.random.uniform(low=-1.0, high=1.0, size=[n, n]).astype(dtype_)\n b = constant_op.constant(b_np)\n\n epsilon = np.finfo(dtype_).eps\n delta = epsilon**(1.0 / 3.0)\n # tolerance obtained by looking at actual differences using\n # np.linalg.norm(theoretical-numerical, np.inf) on -mavx build\n tol = 1e-6 if dtype_ == np.float64 else float32_tol_fudge * 0.05\n\n # check gradient w.r.t. left argument.\n theoretical, numerical = gradient_checker_v2.compute_gradient(\n lambda x: functor_(x, b, **kwargs_), [a], delta=delta)\n self.assertAllClose(theoretical, numerical, atol=tol, rtol=tol)\n\n # check gradient w.r.t. right argument.\n theoretical, numerical = gradient_checker_v2.compute_gradient(\n lambda y: functor_(a, y, **kwargs_), [b], delta=delta)\n self.assertAllClose(theoretical, numerical, atol=tol, rtol=tol)\n\n return Test\n\n\nif __name__ == '__main__':\n # Tests for gradients of binary matrix operations.\n for dtype in np.float32, np.float64:\n for size in 2, 5, 10:\n # We skip the rank 4, size 10 case: it is slow and conceptually covered\n # by the other cases.\n for extra in [(), (2,), (3,)] + [(3, 2)] * (size < 10):\n for adjoint in False, True:\n shape = extra + (size, size)\n name = '%s_%s_adj_%s' % (dtype.__name__, '_'.join(map(\n str, shape)), str(adjoint))\n _AddTest(\n MatrixBinaryFunctorGradientTest, 'MatrixSolveGradient', name,\n _GetMatrixBinaryFunctorGradientTest(\n linalg_ops.matrix_solve, dtype, shape, adjoint=adjoint))\n\n for lower in True, False:\n name = '%s_low_%s' % (name, lower)\n _AddTest(\n MatrixBinaryFunctorGradientTest,\n 'MatrixTriangularSolveGradient', name,\n _GetMatrixBinaryFunctorGradientTest(\n linalg_ops.matrix_triangular_solve,\n dtype,\n shape,\n float32_tol_fudge=4.0,\n adjoint=adjoint,\n lower=lower))\n\n band_shape = extra + (size // 2 + 1, size)\n name = '%s_%s_adj_%s_low_%s' % (dtype.__name__, '_'.join(\n map(str, band_shape)), str(adjoint), lower)\n _AddTest(\n MatrixBinaryFunctorGradientTest,\n 'BandedTriangularSolveGradient', name,\n _GetBandedTriangularSolveGradientTest(\n linalg_ops.banded_triangular_solve,\n dtype,\n band_shape,\n float32_tol_fudge=4.0,\n adjoint=adjoint,\n lower=lower))\n\n # Tests for gradients of unary matrix operations.\n for dtype in np.float32, np.float64:\n for size in 2, 5, 10:\n # We skip the rank 4, size 10 case: it is slow and conceptually covered\n # by the other cases.\n for extra in [(), (2,), (3,)] + [(3, 2)] * (size < 10):\n shape = extra + (size, size)\n name = '%s_%s' % (dtype.__name__, '_'.join(map(str, shape)))\n _AddTest(\n MatrixUnaryFunctorGradientTest, 'MatrixInverseGradient', name,\n _GetMatrixUnaryFunctorGradientTest(linalg_ops.matrix_inverse, dtype,\n shape))\n if not test_lib.is_built_with_rocm():\n # TODO(rocm) :\n # re-enable this test when upstream issues are resolved\n # see commit msg for details\n _AddTest(\n MatrixUnaryFunctorGradientTest, 'MatrixExponentialGradient', name,\n _GetMatrixUnaryFunctorGradientTest(linalg_impl.matrix_exponential,\n dtype, shape))\n _AddTest(\n MatrixUnaryFunctorGradientTest, 'MatrixDeterminantGradient', name,\n _GetMatrixUnaryFunctorGradientTest(linalg_ops.matrix_determinant,\n dtype, shape))\n _AddTest(\n MatrixUnaryFunctorGradientTest, 'LogMatrixDeterminantGradient',\n name,\n _GetMatrixUnaryFunctorGradientTest(\n lambda x: linalg_ops.log_matrix_determinant(x)[1], dtype,\n shape))\n\n # The numerical Jacobian is consistently invalid for these four shapes\n # because the matrix square root of the perturbed input doesn't exist\n if shape in {(2, 5, 5), (3, 5, 5), (3, 10, 10), (3, 2, 5, 5)}:\n # Alternative shape that consistently produces a valid numerical Jacobian\n shape = extra + (size + 1, size + 1)\n name = '%s_%s' % (dtype.__name__, '_'.join(map(str, shape)))\n _AddTest(\n MatrixUnaryFunctorGradientTest, 'MatrixSquareRootGradient', name,\n _GetMatrixUnaryFunctorGradientTest(linalg_ops.matrix_square_root,\n dtype, shape))\n\n # Tests for gradients of matrix_solve_ls\n for dtype in np.float32, np.float64:\n for rows in 2, 5, 10:\n for cols in 2, 5, 10:\n for l2_regularization in 1e-6, 0.001, 1.0:\n shape = (rows, cols)\n name = '%s_%s_%s' % (dtype.__name__, '_'.join(map(\n str, shape)), l2_regularization)\n float32_tol_fudge = 5.1 if l2_regularization == 1e-6 else 4.0\n _AddTest(\n MatrixBinaryFunctorGradientTest,\n 'MatrixSolveLsGradient',\n name,\n # pylint: disable=long-lambda,g-long-lambda\n _GetMatrixBinaryFunctorGradientTest(\n (lambda a, b, l=l2_regularization: linalg_ops.matrix_solve_ls(\n a, b, l)), dtype, shape, float32_tol_fudge))\n\n test_lib.main()\n", "# Copyright 2019 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\"\"\"CSR sparse matrix tests.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import gradients_impl\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops.linalg.sparse import sparse_csr_matrix_grad # pylint: disable=unused-import\nfrom tensorflow.python.ops.linalg.sparse import sparse_csr_matrix_ops\nfrom tensorflow.python.platform import test\nfrom tensorflow.python.platform import tf_logging\n\n\ndef dense_to_csr_sparse_matrix(dense):\n dense_t = ops.convert_to_tensor(dense)\n locs = array_ops.where(math_ops.abs(dense_t) > 0)\n return sparse_csr_matrix_ops.dense_to_csr_sparse_matrix(dense_t, locs)\n\n\ndef _add_test(test, op_name, testcase_name, fn): # pylint: disable=redefined-outer-name\n if fn is None:\n return\n test_name = \"_\".join([\"test\", op_name, testcase_name])\n if hasattr(test, test_name):\n raise RuntimeError(\"Test %s defined more than once\" % test_name)\n setattr(test, test_name, fn)\n\n\nclass CSRSparseMatrixGradTest(test.TestCase):\n\n @classmethod\n def setUpClass(cls):\n super(CSRSparseMatrixGradTest, cls).setUpClass()\n cls._gpu_available = test_util.is_gpu_available()\n\n # TODO(penporn): Make these tests runnable on eager mode.\n # (tf.gradients and gradient_checker only run in graph mode.)\n @test_util.run_deprecated_v1\n def testLargeBatchConversionGrad(self):\n if not self._gpu_available:\n return\n\n sparsify = lambda m: m * (m > 0)\n for dense_shape in ([53, 65, 127], [127, 65]):\n mats_val = sparsify(np.random.randn(*dense_shape))\n with self.test_session() as sess:\n mats = math_ops.cast(mats_val, dtype=dtypes.float32)\n sparse_mats = dense_to_csr_sparse_matrix(mats)\n dense_mats = sparse_csr_matrix_ops.csr_sparse_matrix_to_dense(\n sparse_mats, dtypes.float32)\n grad_vals = np.random.randn(*dense_shape).astype(np.float32)\n grad_out = gradients_impl.gradients([dense_mats], [mats],\n [grad_vals])[0]\n self.assertEqual(grad_out.dtype, dtypes.float32)\n self.assertEqual(grad_out.shape, dense_shape)\n grad_out_value = sess.run(grad_out)\n tf_logging.info(\"testLargeBatchConversionGrad: Testing shape %s\" %\n dense_shape)\n nonzero_indices = abs(mats_val) > 0.0\n self.assertAllEqual(grad_out_value[nonzero_indices],\n grad_vals[nonzero_indices])\n self.assertTrue(\n np.all(grad_out_value[np.logical_not(nonzero_indices)] == 0.0))\n\n @test_util.run_deprecated_v1\n def testLargeBatchSparseConversionGrad(self):\n sparsify = lambda m: m * (m > 0)\n for dense_shape in ([53, 65, 127], [127, 65]):\n mats_val = sparsify(np.random.randn(*dense_shape))\n\n with self.session(use_gpu=True) as sess:\n indices = array_ops.where_v2(\n math_ops.not_equal(mats_val, array_ops.zeros_like(mats_val)))\n values = math_ops.cast(\n array_ops.gather_nd(mats_val, indices), dtype=dtypes.float32)\n\n grad_vals = np.random.randn(*sess.run(values).shape).astype(np.float32)\n csr_matrix = sparse_csr_matrix_ops.sparse_tensor_to_csr_sparse_matrix(\n indices, values, dense_shape)\n new_coo_tensor = (\n sparse_csr_matrix_ops.csr_sparse_matrix_to_sparse_tensor(\n csr_matrix, type=dtypes.float32))\n grad_out = gradients_impl.gradients([new_coo_tensor.values], [values],\n [grad_vals])[0]\n self.assertEqual(grad_out.dtype, dtypes.float32)\n grad_out_vals = sess.run(grad_out)\n self.assertAllClose(grad_vals, grad_out_vals)\n\n @test_util.run_deprecated_v1\n def testLargeBatchSparseMatrixAddGrad(self):\n if not self._gpu_available:\n return\n\n sparsify = lambda m: m * (m > 0)\n for dense_shape in ([53, 65, 127], [127, 65]):\n a_mats_val = sparsify(np.random.randn(*dense_shape))\n b_mats_val = sparsify(np.random.randn(*dense_shape))\n alpha = np.float32(0.5)\n beta = np.float32(-1.5)\n grad_vals = np.random.randn(*dense_shape).astype(np.float32)\n expected_a_grad = alpha * grad_vals\n expected_b_grad = beta * grad_vals\n expected_a_grad[abs(a_mats_val) == 0.0] = 0.0\n expected_b_grad[abs(b_mats_val) == 0.0] = 0.0\n with self.test_session() as sess:\n a_mats = math_ops.cast(a_mats_val, dtype=dtypes.float32)\n b_mats = math_ops.cast(b_mats_val, dtype=dtypes.float32)\n a_sm = dense_to_csr_sparse_matrix(a_mats)\n b_sm = dense_to_csr_sparse_matrix(b_mats)\n c_sm = sparse_csr_matrix_ops.sparse_matrix_add(\n a_sm, b_sm, alpha=alpha, beta=beta)\n c_dense = sparse_csr_matrix_ops.csr_sparse_matrix_to_dense(\n c_sm, dtypes.float32)\n a_grad, b_grad = gradients_impl.gradients([c_dense], [a_mats, b_mats],\n [grad_vals])\n self.assertEqual(a_grad.dtype, dtypes.float32)\n self.assertEqual(b_grad.dtype, dtypes.float32)\n self.assertEqual(a_grad.shape, dense_shape)\n self.assertEqual(b_grad.shape, dense_shape)\n a_grad_value, b_grad_value = sess.run((a_grad, b_grad))\n tf_logging.info(\"testLargeBatchConversionGrad: Testing shape %s\" %\n dense_shape)\n self.assertAllEqual(expected_a_grad, a_grad_value)\n self.assertAllEqual(expected_b_grad, b_grad_value)\n\n\nif __name__ == \"__main__\":\n test.main()\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\"\"\"Generates and prints out imports and constants for new TensorFlow python api.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport collections\nimport importlib\nimport os\nimport sys\n\nfrom tensorflow.python.tools.api.generator import doc_srcs\nfrom tensorflow.python.util import tf_decorator\nfrom tensorflow.python.util import tf_export\n\nAPI_ATTRS = tf_export.API_ATTRS\nAPI_ATTRS_V1 = tf_export.API_ATTRS_V1\n\n_LAZY_LOADING = False\n_API_VERSIONS = [1, 2]\n_COMPAT_MODULE_TEMPLATE = 'compat.v%d'\n_SUBCOMPAT_MODULE_TEMPLATE = 'compat.v%d.compat.v%d'\n_COMPAT_MODULE_PREFIX = 'compat.v'\n_DEFAULT_PACKAGE = 'tensorflow.python'\n_GENFILES_DIR_SUFFIX = 'genfiles/'\n_SYMBOLS_TO_SKIP_EXPLICITLY = {\n # Overrides __getattr__, so that unwrapping tf_decorator\n # would have side effects.\n 'tensorflow.python.platform.flags.FLAGS'\n}\n_GENERATED_FILE_HEADER = \"\"\"# This file is MACHINE GENERATED! Do not edit.\n# Generated by: tensorflow/python/tools/api/generator/create_python_api.py script.\n\\\"\\\"\\\"%s\n\\\"\\\"\\\"\n\nfrom __future__ import print_function as _print_function\n\nimport sys as _sys\n\n\"\"\"\n_GENERATED_FILE_FOOTER = '\\n\\ndel _print_function\\n'\n_DEPRECATION_FOOTER = \"\"\"\nfrom tensorflow.python.util import module_wrapper as _module_wrapper\n\nif not isinstance(_sys.modules[__name__], _module_wrapper.TFModuleWrapper):\n _sys.modules[__name__] = _module_wrapper.TFModuleWrapper(\n _sys.modules[__name__], \"%s\", public_apis=%s, deprecation=%s,\n has_lite=%s)\n\"\"\"\n_LAZY_LOADING_MODULE_TEXT_TEMPLATE = \"\"\"\n# Inform pytype that this module is dynamically populated (b/111239204).\n_HAS_DYNAMIC_ATTRIBUTES = True\n_PUBLIC_APIS = {\n%s\n}\n\"\"\"\n\n\nclass SymbolExposedTwiceError(Exception):\n \"\"\"Raised when different symbols are exported with the same name.\"\"\"\n pass\n\n\ndef get_canonical_import(import_set):\n \"\"\"Obtain one single import from a set of possible sources of a symbol.\n\n One symbol might come from multiple places as it is being imported and\n reexported. To simplify API changes, we always use the same import for the\n same module, and give preference based on higher priority and alphabetical\n ordering.\n\n Args:\n import_set: (set) Imports providing the same symbol. This is a set of tuples\n in the form (import, priority). We want to pick an import with highest\n priority.\n\n Returns:\n A module name to import\n \"\"\"\n # We use the fact that list sorting is stable, so first we convert the set to\n # a sorted list of the names and then we resort this list to move elements\n # not in core tensorflow to the end.\n # Here we sort by priority (higher preferred) and then alphabetically by\n # import string.\n import_list = sorted(\n import_set,\n key=lambda imp_and_priority: (-imp_and_priority[1], imp_and_priority[0]))\n return import_list[0][0]\n\n\nclass _ModuleInitCodeBuilder(object):\n \"\"\"Builds a map from module name to imports included in that module.\"\"\"\n\n def __init__(self,\n output_package,\n api_version,\n lazy_loading=_LAZY_LOADING,\n use_relative_imports=False):\n self._output_package = output_package\n # Maps API module to API symbol name to set of tuples of the form\n # (module name, priority).\n # The same symbol can be imported from multiple locations. Higher\n # \"priority\" indicates that import location is preferred over others.\n self._module_imports = collections.defaultdict(\n lambda: collections.defaultdict(set))\n self._dest_import_to_id = collections.defaultdict(int)\n # Names that start with underscore in the root module.\n self._underscore_names_in_root = set()\n self._api_version = api_version\n # Controls whether or not exported symbols are lazily loaded or statically\n # imported.\n self._lazy_loading = lazy_loading\n self._use_relative_imports = use_relative_imports\n\n def _check_already_imported(self, symbol_id, api_name):\n if (api_name in self._dest_import_to_id and\n symbol_id != self._dest_import_to_id[api_name] and symbol_id != -1):\n raise SymbolExposedTwiceError(\n 'Trying to export multiple symbols with same name: %s.' % api_name)\n self._dest_import_to_id[api_name] = symbol_id\n\n def add_import(self, symbol, source_module_name, source_name,\n dest_module_name, dest_name):\n \"\"\"Adds this import to module_imports.\n\n Args:\n symbol: TensorFlow Python symbol.\n source_module_name: (string) Module to import from.\n source_name: (string) Name of the symbol to import.\n dest_module_name: (string) Module name to add import to.\n dest_name: (string) Import the symbol using this name.\n\n Raises:\n SymbolExposedTwiceError: Raised when an import with the same\n dest_name has already been added to dest_module_name.\n \"\"\"\n # modules_with_exports.py is only used during API generation and\n # won't be available when actually importing tensorflow.\n if source_module_name.endswith('python.modules_with_exports'):\n source_module_name = symbol.__module__\n import_str = self.format_import(source_module_name, source_name, dest_name)\n\n # Check if we are trying to expose two different symbols with same name.\n full_api_name = dest_name\n if dest_module_name:\n full_api_name = dest_module_name + '.' + full_api_name\n symbol_id = -1 if not symbol else id(symbol)\n self._check_already_imported(symbol_id, full_api_name)\n\n if not dest_module_name and dest_name.startswith('_'):\n self._underscore_names_in_root.add(dest_name)\n\n # The same symbol can be available in multiple modules.\n # We store all possible ways of importing this symbol and later pick just\n # one.\n priority = 0\n if symbol:\n # Give higher priority to source module if it matches\n # symbol's original module.\n if hasattr(symbol, '__module__'):\n priority = int(source_module_name == symbol.__module__)\n # Give higher priority if symbol name matches its __name__.\n if hasattr(symbol, '__name__'):\n priority += int(source_name == symbol.__name__)\n self._module_imports[dest_module_name][full_api_name].add(\n (import_str, priority))\n\n def _import_submodules(self):\n \"\"\"Add imports for all destination modules in self._module_imports.\"\"\"\n # Import all required modules in their parent modules.\n # For e.g. if we import 'foo.bar.Value'. Then, we also\n # import 'bar' in 'foo'.\n imported_modules = set(self._module_imports.keys())\n for module in imported_modules:\n if not module:\n continue\n module_split = module.split('.')\n parent_module = '' # we import submodules in their parent_module\n\n for submodule_index in range(len(module_split)):\n if submodule_index > 0:\n submodule = module_split[submodule_index - 1]\n parent_module += '.' + submodule if parent_module else submodule\n import_from = self._output_package\n if self._lazy_loading:\n import_from += '.' + '.'.join(module_split[:submodule_index + 1])\n self.add_import(\n symbol=None,\n source_module_name='',\n source_name=import_from,\n dest_module_name=parent_module,\n dest_name=module_split[submodule_index])\n else:\n if self._use_relative_imports:\n import_from = '.'\n elif submodule_index > 0:\n import_from += '.' + '.'.join(module_split[:submodule_index])\n self.add_import(\n symbol=None,\n source_module_name=import_from,\n source_name=module_split[submodule_index],\n dest_module_name=parent_module,\n dest_name=module_split[submodule_index])\n\n def build(self):\n \"\"\"Get a map from destination module to __init__.py code for that module.\n\n Returns:\n A dictionary where\n key: (string) destination module (for e.g. tf or tf.consts).\n value: (string) text that should be in __init__.py files for\n corresponding modules.\n \"\"\"\n self._import_submodules()\n module_text_map = {}\n footer_text_map = {}\n for dest_module, dest_name_to_imports in self._module_imports.items():\n # Sort all possible imports for a symbol and pick the first one.\n imports_list = [\n get_canonical_import(imports)\n for _, imports in dest_name_to_imports.items()\n ]\n if self._lazy_loading:\n module_text_map[\n dest_module] = _LAZY_LOADING_MODULE_TEXT_TEMPLATE % '\\n'.join(\n sorted(imports_list))\n else:\n module_text_map[dest_module] = '\\n'.join(sorted(imports_list))\n\n # Expose exported symbols with underscores in root module since we import\n # from it using * import. Don't need this for lazy_loading because the\n # underscore symbols are already included in __all__ when passed in and\n # handled by TFModuleWrapper.\n root_module_footer = ''\n if not self._lazy_loading:\n underscore_names_str = ', '.join(\n '\\'%s\\'' % name for name in sorted(self._underscore_names_in_root))\n\n root_module_footer = \"\"\"\n_names_with_underscore = [%s]\n__all__ = [_s for _s in dir() if not _s.startswith('_')]\n__all__.extend([_s for _s in _names_with_underscore])\n\"\"\" % underscore_names_str\n\n # Add module wrapper if we need to print deprecation messages\n # or if we use lazy loading.\n if self._api_version == 1 or self._lazy_loading:\n for dest_module, _ in self._module_imports.items():\n deprecation = 'False'\n has_lite = 'False'\n if self._api_version == 1: # Add 1.* deprecations.\n if not dest_module.startswith(_COMPAT_MODULE_PREFIX):\n deprecation = 'True'\n # Workaround to make sure not load lite from lite/__init__.py\n if (not dest_module and 'lite' in self._module_imports and\n self._lazy_loading):\n has_lite = 'True'\n if self._lazy_loading:\n public_apis_name = '_PUBLIC_APIS'\n else:\n public_apis_name = 'None'\n footer_text_map[dest_module] = _DEPRECATION_FOOTER % (\n dest_module, public_apis_name, deprecation, has_lite)\n\n return module_text_map, footer_text_map, root_module_footer\n\n def format_import(self, source_module_name, source_name, dest_name):\n \"\"\"Formats import statement.\n\n Args:\n source_module_name: (string) Source module to import from.\n source_name: (string) Source symbol name to import.\n dest_name: (string) Destination alias name.\n\n Returns:\n An import statement string.\n \"\"\"\n if self._lazy_loading:\n return \" '%s': ('%s', '%s'),\" % (dest_name, source_module_name,\n source_name)\n else:\n if source_module_name:\n if source_name == dest_name:\n return 'from %s import %s' % (source_module_name, source_name)\n else:\n return 'from %s import %s as %s' % (source_module_name, source_name,\n dest_name)\n else:\n if source_name == dest_name:\n return 'import %s' % source_name\n else:\n return 'import %s as %s' % (source_name, dest_name)\n\n def get_destination_modules(self):\n return set(self._module_imports.keys())\n\n def copy_imports(self, from_dest_module, to_dest_module):\n self._module_imports[to_dest_module] = (\n self._module_imports[from_dest_module].copy())\n\n\ndef add_nested_compat_imports(module_builder, compat_api_versions,\n output_package):\n \"\"\"Adds compat.vN.compat.vK modules to module builder.\n\n To avoid circular imports, we want to add __init__.py files under\n compat.vN.compat.vK and under compat.vN.compat.vK.compat. For all other\n imports, we point to corresponding modules under compat.vK.\n\n Args:\n module_builder: `_ModuleInitCodeBuilder` instance.\n compat_api_versions: Supported compatibility versions.\n output_package: Base output python package where generated API will be\n added.\n \"\"\"\n imported_modules = module_builder.get_destination_modules()\n\n # Copy over all imports in compat.vK to compat.vN.compat.vK and\n # all imports in compat.vK.compat to compat.vN.compat.vK.compat.\n for v in compat_api_versions:\n for sv in compat_api_versions:\n subcompat_module = _SUBCOMPAT_MODULE_TEMPLATE % (v, sv)\n compat_module = _COMPAT_MODULE_TEMPLATE % sv\n module_builder.copy_imports(compat_module, subcompat_module)\n module_builder.copy_imports('%s.compat' % compat_module,\n '%s.compat' % subcompat_module)\n\n # Prefixes of modules under compatibility packages, for e.g. \"compat.v1.\".\n compat_prefixes = tuple(\n _COMPAT_MODULE_TEMPLATE % v + '.' for v in compat_api_versions)\n\n # Above, we only copied function, class and constant imports. Here\n # we also add imports for child modules.\n for imported_module in imported_modules:\n if not imported_module.startswith(compat_prefixes):\n continue\n module_split = imported_module.split('.')\n\n # Handle compat.vN.compat.vK.compat.foo case. That is,\n # import compat.vK.compat.foo in compat.vN.compat.vK.compat.\n if len(module_split) > 3 and module_split[2] == 'compat':\n src_module = '.'.join(module_split[:3])\n src_name = module_split[3]\n assert src_name != 'v1' and src_name != 'v2', imported_module\n else: # Handle compat.vN.compat.vK.foo case.\n src_module = '.'.join(module_split[:2])\n src_name = module_split[2]\n if src_name == 'compat':\n continue # compat.vN.compat.vK.compat is handled separately\n\n for compat_api_version in compat_api_versions:\n module_builder.add_import(\n symbol=None,\n source_module_name='%s.%s' % (output_package, src_module),\n source_name=src_name,\n dest_module_name='compat.v%d.%s' % (compat_api_version, src_module),\n dest_name=src_name)\n\n\ndef _get_name_and_module(full_name):\n \"\"\"Split full_name into module and short name.\n\n Args:\n full_name: Full name of symbol that includes module.\n\n Returns:\n Full module name and short symbol name.\n \"\"\"\n name_segments = full_name.split('.')\n return '.'.join(name_segments[:-1]), name_segments[-1]\n\n\ndef _join_modules(module1, module2):\n \"\"\"Concatenate 2 module components.\n\n Args:\n module1: First module to join.\n module2: Second module to join.\n\n Returns:\n Given two modules aaa.bbb and ccc.ddd, returns a joined\n module aaa.bbb.ccc.ddd.\n \"\"\"\n if not module1:\n return module2\n if not module2:\n return module1\n return '%s.%s' % (module1, module2)\n\n\ndef add_imports_for_symbol(module_code_builder,\n symbol,\n source_module_name,\n source_name,\n api_name,\n api_version,\n output_module_prefix=''):\n \"\"\"Add imports for the given symbol to `module_code_builder`.\n\n Args:\n module_code_builder: `_ModuleInitCodeBuilder` instance.\n symbol: A symbol.\n source_module_name: Module that we can import the symbol from.\n source_name: Name we can import the symbol with.\n api_name: API name. Currently, must be either `tensorflow` or `estimator`.\n api_version: API version.\n output_module_prefix: Prefix to prepend to destination module.\n \"\"\"\n if api_version == 1:\n names_attr = API_ATTRS_V1[api_name].names\n constants_attr = API_ATTRS_V1[api_name].constants\n else:\n names_attr = API_ATTRS[api_name].names\n constants_attr = API_ATTRS[api_name].constants\n\n # If symbol is _tf_api_constants attribute, then add the constants.\n if source_name == constants_attr:\n for exports, name in symbol:\n for export in exports:\n dest_module, dest_name = _get_name_and_module(export)\n dest_module = _join_modules(output_module_prefix, dest_module)\n module_code_builder.add_import(None, source_module_name, name,\n dest_module, dest_name)\n\n # If symbol has _tf_api_names attribute, then add import for it.\n if (hasattr(symbol, '__dict__') and names_attr in symbol.__dict__):\n\n # Generate import statements for symbols.\n for export in getattr(symbol, names_attr): # pylint: disable=protected-access\n dest_module, dest_name = _get_name_and_module(export)\n dest_module = _join_modules(output_module_prefix, dest_module)\n module_code_builder.add_import(symbol, source_module_name, source_name,\n dest_module, dest_name)\n\n\ndef get_api_init_text(packages,\n packages_to_ignore,\n output_package,\n api_name,\n api_version,\n compat_api_versions=None,\n lazy_loading=_LAZY_LOADING,\n use_relative_imports=False):\n \"\"\"Get a map from destination module to __init__.py code for that module.\n\n Args:\n packages: Base python packages containing python with target tf_export\n decorators.\n packages_to_ignore: python packages to be ignored when checking for\n tf_export decorators.\n output_package: Base output python package where generated API will be\n added.\n api_name: API you want to generate (e.g. `tensorflow` or `estimator`).\n api_version: API version you want to generate (1 or 2).\n compat_api_versions: Additional API versions to generate under compat/\n directory.\n lazy_loading: Boolean flag. If True, a lazy loading `__init__.py` file is\n produced and if `False`, static imports are used.\n use_relative_imports: True if we should use relative imports when importing\n submodules.\n\n Returns:\n A dictionary where\n key: (string) destination module (for e.g. tf or tf.consts).\n value: (string) text that should be in __init__.py files for\n corresponding modules.\n \"\"\"\n if compat_api_versions is None:\n compat_api_versions = []\n module_code_builder = _ModuleInitCodeBuilder(output_package, api_version,\n lazy_loading,\n use_relative_imports)\n\n # Traverse over everything imported above. Specifically,\n # we want to traverse over TensorFlow Python modules.\n\n def in_packages(m):\n return any(package in m for package in packages)\n\n for module in list(sys.modules.values()):\n # Only look at tensorflow modules.\n if (not module or not hasattr(module, '__name__') or\n module.__name__ is None or not in_packages(module.__name__)):\n continue\n if packages_to_ignore and any([p for p in packages_to_ignore\n if p in module.__name__]):\n continue\n\n # Do not generate __init__.py files for contrib modules for now.\n if (('.contrib.' in module.__name__ or module.__name__.endswith('.contrib'))\n and '.lite' not in module.__name__):\n continue\n\n for module_contents_name in dir(module):\n if (module.__name__ + '.' +\n module_contents_name in _SYMBOLS_TO_SKIP_EXPLICITLY):\n continue\n attr = getattr(module, module_contents_name)\n _, attr = tf_decorator.unwrap(attr)\n\n add_imports_for_symbol(module_code_builder, attr, module.__name__,\n module_contents_name, api_name, api_version)\n for compat_api_version in compat_api_versions:\n add_imports_for_symbol(module_code_builder, attr, module.__name__,\n module_contents_name, api_name,\n compat_api_version,\n _COMPAT_MODULE_TEMPLATE % compat_api_version)\n\n if compat_api_versions:\n add_nested_compat_imports(module_code_builder, compat_api_versions,\n output_package)\n return module_code_builder.build()\n\n\ndef get_module(dir_path, relative_to_dir):\n \"\"\"Get module that corresponds to path relative to relative_to_dir.\n\n Args:\n dir_path: Path to directory.\n relative_to_dir: Get module relative to this directory.\n\n Returns:\n Name of module that corresponds to the given directory.\n \"\"\"\n dir_path = dir_path[len(relative_to_dir):]\n # Convert path separators to '/' for easier parsing below.\n dir_path = dir_path.replace(os.sep, '/')\n return dir_path.replace('/', '.').strip('.')\n\n\ndef get_module_docstring(module_name, package, api_name):\n \"\"\"Get docstring for the given module.\n\n This method looks for docstring in the following order:\n 1. Checks if module has a docstring specified in doc_srcs.\n 2. Checks if module has a docstring source module specified\n in doc_srcs. If it does, gets docstring from that module.\n 3. Checks if module with module_name exists under base package.\n If it does, gets docstring from that module.\n 4. Returns a default docstring.\n\n Args:\n module_name: module name relative to tensorflow (excluding 'tensorflow.'\n prefix) to get a docstring for.\n package: Base python package containing python with target tf_export\n decorators.\n api_name: API you want to generate (e.g. `tensorflow` or `estimator`).\n\n Returns:\n One-line docstring to describe the module.\n \"\"\"\n # Get the same module doc strings for any version. That is, for module\n # 'compat.v1.foo' we can get docstring from module 'foo'.\n for version in _API_VERSIONS:\n compat_prefix = _COMPAT_MODULE_TEMPLATE % version\n if module_name.startswith(compat_prefix):\n module_name = module_name[len(compat_prefix):].strip('.')\n\n # Module under base package to get a docstring from.\n docstring_module_name = module_name\n\n doc_sources = doc_srcs.get_doc_sources(api_name)\n\n if module_name in doc_sources:\n docsrc = doc_sources[module_name]\n if docsrc.docstring:\n return docsrc.docstring\n if docsrc.docstring_module_name:\n docstring_module_name = docsrc.docstring_module_name\n\n docstring_module_name = package + '.' + docstring_module_name\n if (docstring_module_name in sys.modules and\n sys.modules[docstring_module_name].__doc__):\n return sys.modules[docstring_module_name].__doc__\n\n return 'Public API for tf.%s namespace.' % module_name\n\n\ndef create_api_files(output_files,\n packages,\n packages_to_ignore,\n root_init_template,\n output_dir,\n output_package,\n api_name,\n api_version,\n compat_api_versions,\n compat_init_templates,\n lazy_loading=_LAZY_LOADING,\n use_relative_imports=False):\n \"\"\"Creates __init__.py files for the Python API.\n\n Args:\n output_files: List of __init__.py file paths to create.\n packages: Base python packages containing python with target tf_export\n decorators.\n packages_to_ignore: python packages to be ignored when checking for\n tf_export decorators.\n root_init_template: Template for top-level __init__.py file. \"# API IMPORTS\n PLACEHOLDER\" comment in the template file will be replaced with imports.\n output_dir: output API root directory.\n output_package: Base output package where generated API will be added.\n api_name: API you want to generate (e.g. `tensorflow` or `estimator`).\n api_version: API version to generate (`v1` or `v2`).\n compat_api_versions: Additional API versions to generate in compat/\n subdirectory.\n compat_init_templates: List of templates for top level compat init files in\n the same order as compat_api_versions.\n lazy_loading: Boolean flag. If True, a lazy loading `__init__.py` file is\n produced and if `False`, static imports are used.\n use_relative_imports: True if we should use relative imports when import\n submodules.\n\n Raises:\n ValueError: if output_files list is missing a required file.\n \"\"\"\n module_name_to_file_path = {}\n for output_file in output_files:\n module_name = get_module(os.path.dirname(output_file), output_dir)\n module_name_to_file_path[module_name] = os.path.normpath(output_file)\n\n # Create file for each expected output in genrule.\n for module, file_path in module_name_to_file_path.items():\n if not os.path.isdir(os.path.dirname(file_path)):\n os.makedirs(os.path.dirname(file_path))\n open(file_path, 'a').close()\n\n (\n module_text_map,\n deprecation_footer_map,\n root_module_footer,\n ) = get_api_init_text(packages, packages_to_ignore, output_package, api_name,\n api_version, compat_api_versions, lazy_loading,\n use_relative_imports)\n\n # Add imports to output files.\n missing_output_files = []\n # Root modules are \"\" and \"compat.v*\".\n root_module = ''\n compat_module_to_template = {\n _COMPAT_MODULE_TEMPLATE % v: t\n for v, t in zip(compat_api_versions, compat_init_templates)\n }\n for v in compat_api_versions:\n compat_module_to_template.update({\n _SUBCOMPAT_MODULE_TEMPLATE % (v, vs): t\n for vs, t in zip(compat_api_versions, compat_init_templates)\n })\n\n for module, text in module_text_map.items():\n # Make sure genrule output file list is in sync with API exports.\n if module not in module_name_to_file_path:\n module_file_path = '\"%s/__init__.py\"' % (module.replace('.', '/'))\n missing_output_files.append(module_file_path)\n continue\n\n contents = ''\n if module == root_module and root_init_template:\n # Read base init file for root module\n with open(root_init_template, 'r') as root_init_template_file:\n contents = root_init_template_file.read()\n contents = contents.replace('# API IMPORTS PLACEHOLDER', text)\n contents = contents.replace('# __all__ PLACEHOLDER', root_module_footer)\n elif module in compat_module_to_template:\n # Read base init file for compat module\n with open(compat_module_to_template[module], 'r') as init_template_file:\n contents = init_template_file.read()\n contents = contents.replace('# API IMPORTS PLACEHOLDER', text)\n else:\n contents = (\n _GENERATED_FILE_HEADER %\n get_module_docstring(module, packages[0], api_name) + text +\n _GENERATED_FILE_FOOTER)\n if module in deprecation_footer_map:\n if '# WRAPPER_PLACEHOLDER' in contents:\n contents = contents.replace('# WRAPPER_PLACEHOLDER',\n deprecation_footer_map[module])\n else:\n contents += deprecation_footer_map[module]\n with open(module_name_to_file_path[module], 'w') as fp:\n fp.write(contents)\n\n if missing_output_files:\n raise ValueError(\n \"\"\"Missing outputs for genrule:\\n%s. Be sure to add these targets to\ntensorflow/python/tools/api/generator/api_init_files_v1.bzl and\ntensorflow/python/tools/api/generator/api_init_files.bzl (tensorflow repo), or\ntensorflow_estimator/python/estimator/api/api_gen.bzl (estimator repo)\"\"\" %\n ',\\n'.join(sorted(missing_output_files)))\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n 'outputs',\n metavar='O',\n type=str,\n nargs='+',\n help='If a single file is passed in, then we assume it contains a '\n 'semicolon-separated list of Python files that we expect this script to '\n 'output. If multiple files are passed in, then we assume output files '\n 'are listed directly as arguments.')\n parser.add_argument(\n '--packages',\n default=_DEFAULT_PACKAGE,\n type=str,\n help='Base packages that import modules containing the target tf_export '\n 'decorators.')\n parser.add_argument(\n '--packages_to_ignore',\n default='',\n type=str,\n help='Packages to exclude from the api generation. This is used to hide '\n 'certain packages from this script when multiple copy of code exists, '\n 'eg Keras. It is useful to avoid the SymbolExposedTwiceError.'\n )\n parser.add_argument(\n '--root_init_template',\n default='',\n type=str,\n help='Template for top level __init__.py file. '\n '\"#API IMPORTS PLACEHOLDER\" comment will be replaced with imports.')\n parser.add_argument(\n '--apidir',\n type=str,\n required=True,\n help='Directory where generated output files are placed. '\n 'gendir should be a prefix of apidir. Also, apidir '\n 'should be a prefix of every directory in outputs.')\n parser.add_argument(\n '--apiname',\n required=True,\n type=str,\n choices=API_ATTRS.keys(),\n help='The API you want to generate.')\n parser.add_argument(\n '--apiversion',\n default=2,\n type=int,\n choices=_API_VERSIONS,\n help='The API version you want to generate.')\n parser.add_argument(\n '--compat_apiversions',\n default=[],\n type=int,\n action='append',\n help='Additional versions to generate in compat/ subdirectory. '\n 'If set to 0, then no additional version would be generated.')\n parser.add_argument(\n '--compat_init_templates',\n default=[],\n type=str,\n action='append',\n help='Templates for top-level __init__ files under compat modules. '\n 'The list of init file templates must be in the same order as '\n 'list of versions passed with compat_apiversions.')\n parser.add_argument(\n '--output_package',\n default='tensorflow',\n type=str,\n help='Root output package.')\n parser.add_argument(\n '--loading',\n default='default',\n type=str,\n choices=['lazy', 'static', 'default'],\n help='Controls how the generated __init__.py file loads the exported '\n 'symbols. \\'lazy\\' means the symbols are loaded when first used. '\n '\\'static\\' means all exported symbols are loaded in the '\n '__init__.py file. \\'default\\' uses the value of the '\n '_LAZY_LOADING constant in create_python_api.py.')\n parser.add_argument(\n '--use_relative_imports',\n default=False,\n type=bool,\n help='Whether to import submodules using relative imports or absolute '\n 'imports')\n args = parser.parse_args()\n\n if len(args.outputs) == 1:\n # If we only get a single argument, then it must be a file containing\n # list of outputs.\n with open(args.outputs[0]) as output_list_file:\n outputs = [line.strip() for line in output_list_file.read().split(';')]\n else:\n outputs = args.outputs\n\n # Populate `sys.modules` with modules containing tf_export().\n packages = args.packages.split(',')\n for package in packages:\n importlib.import_module(package)\n packages_to_ignore = args.packages_to_ignore.split(',')\n\n # Determine if the modules shall be loaded lazily or statically.\n if args.loading == 'default':\n lazy_loading = _LAZY_LOADING\n elif args.loading == 'lazy':\n lazy_loading = True\n elif args.loading == 'static':\n lazy_loading = False\n else:\n # This should never happen (tm).\n raise ValueError('Invalid value for --loading flag: %s. Must be one of '\n 'lazy, static, default.' % args.loading)\n\n create_api_files(outputs, packages, packages_to_ignore,\n args.root_init_template, args.apidir,\n args.output_package, args.apiname, args.apiversion,\n args.compat_apiversions, args.compat_init_templates,\n lazy_loading, args.use_relative_imports)\n\n\nif __name__ == '__main__':\n main()\n", "# 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\"\"\"Tests for DecodeRaw op from parsing_ops.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import parsing_ops\nfrom tensorflow.python.platform import test\n\n\nclass DecodeRawOpTest(test.TestCase):\n\n def testShapeInference(self):\n # Shape function requires placeholders and a graph.\n with ops.Graph().as_default():\n for dtype in [dtypes.bool, dtypes.int8, dtypes.uint8, dtypes.int16,\n dtypes.uint16, dtypes.int32, dtypes.int64, dtypes.float16,\n dtypes.float32, dtypes.float64, dtypes.complex64,\n dtypes.complex128]:\n in_bytes = array_ops.placeholder(dtypes.string, shape=[None])\n decode = parsing_ops.decode_raw(in_bytes, dtype)\n self.assertEqual([None, None], decode.get_shape().as_list())\n\n def testToUint8(self):\n self.assertAllEqual(\n [[ord(\"A\")], [ord(\"a\")]],\n parsing_ops.decode_raw([\"A\", \"a\"], dtypes.uint8))\n\n self.assertAllEqual(\n [[ord(\"w\"), ord(\"e\"), ord(\"r\")], [ord(\"X\"), ord(\"Y\"), ord(\"Z\")]],\n parsing_ops.decode_raw([\"wer\", \"XYZ\"], dtypes.uint8))\n\n with self.assertRaisesOpError(\n \"DecodeRaw requires input strings to all be the same size, but \"\n \"element 1 has size 5 != 6\"):\n self.evaluate(parsing_ops.decode_raw([\"short\", \"longer\"], dtypes.uint8))\n\n def testToInt16(self):\n self.assertAllEqual(\n [[ord(\"A\") + ord(\"a\") * 256, ord(\"B\") + ord(\"C\") * 256]],\n parsing_ops.decode_raw([\"AaBC\"], dtypes.uint16))\n\n with self.assertRaisesOpError(\n \"Input to DecodeRaw has length 3 that is not a multiple of 2, the \"\n \"size of int16\"):\n self.evaluate(parsing_ops.decode_raw([\"123\", \"456\"], dtypes.int16))\n\n def testEndianness(self):\n self.assertAllEqual(\n [[0x04030201]],\n parsing_ops.decode_raw(\n [\"\\x01\\x02\\x03\\x04\"], dtypes.int32, little_endian=True))\n self.assertAllEqual(\n [[0x01020304]],\n parsing_ops.decode_raw(\n [\"\\x01\\x02\\x03\\x04\"], dtypes.int32, little_endian=False))\n self.assertAllEqual([[1 + 2j]],\n parsing_ops.decode_raw([b\"\\x00\\x00\\x80?\\x00\\x00\\x00@\"],\n dtypes.complex64,\n little_endian=True))\n self.assertAllEqual([[1 + 2j]],\n parsing_ops.decode_raw([b\"?\\x80\\x00\\x00@\\x00\\x00\\x00\"],\n dtypes.complex64,\n little_endian=False))\n\n def testToFloat16(self):\n result = np.matrix([[1, -2, -3, 4]], dtype=\"<f2\")\n self.assertAllEqual(\n result, parsing_ops.decode_raw([result.tobytes()], dtypes.float16))\n\n def testToBool(self):\n result = np.matrix([[True, False, False, True]], dtype=\"<b1\")\n self.assertAllEqual(result,\n parsing_ops.decode_raw([result.tobytes()], dtypes.bool))\n\n def testToComplex64(self):\n result = np.matrix([[1 + 1j, 2 - 2j, -3 + 3j, -4 - 4j]], dtype=\"<c8\")\n self.assertAllEqual(\n result, parsing_ops.decode_raw([result.tobytes()], dtypes.complex64))\n\n def testToComplex128(self):\n result = np.matrix([[1 + 1j, 2 - 2j, -3 + 3j, -4 - 4j]], dtype=\"<c16\")\n self.assertAllEqual(\n result, parsing_ops.decode_raw([result.tobytes()], dtypes.complex128))\n\n def testEmptyStringInput(self):\n for num_inputs in range(3):\n result = parsing_ops.decode_raw([\"\"] * num_inputs, dtypes.float16)\n self.assertEqual((num_inputs, 0), self.evaluate(result).shape)\n\n def testToUInt16(self):\n # Use FF/EE/DD/CC so that decoded value is higher than 32768 for uint16\n self.assertAllEqual(\n [[0xFF + 0xEE * 256, 0xDD + 0xCC * 256]],\n parsing_ops.decode_raw([b\"\\xFF\\xEE\\xDD\\xCC\"], dtypes.uint16))\n\n with self.assertRaisesOpError(\n \"Input to DecodeRaw has length 3 that is not a multiple of 2, the \"\n \"size of uint16\"):\n self.evaluate(parsing_ops.decode_raw([\"123\", \"456\"], dtypes.uint16))\n\n\nif __name__ == \"__main__\":\n test.main()\n", "# Copyright 2018 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\"\"\"Utilities related to distribute coordinator.\n\nThe module is used only for utils to support legacy TF1 code path involving\ndistribute coordinator, and is not expected to change in any way. This is\nsubject to cleanup once TF1 is no longer supported.\n\nTODO(rchao): Remove this module once TF1 is not supported.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport copy\nimport json\nimport os\nimport threading\nimport time\nfrom tensorflow.core.protobuf import cluster_pb2\nfrom tensorflow.core.protobuf import config_pb2\nfrom tensorflow.python.client import session\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.training import monitored_session\nfrom tensorflow.python.training import server_lib\n\n_worker_context = threading.local()\n_thread_local = threading.local()\n\n\ndef get_current_worker_context():\n \"\"\"Returns the current task context.\"\"\"\n try:\n return _worker_context.current\n except AttributeError:\n return None\n\n\nclass _TaskType(object):\n PS = \"ps\"\n WORKER = \"worker\"\n CHIEF = \"chief\"\n EVALUATOR = \"evaluator\"\n CLIENT = \"client\"\n\n\ndef _get_num_workers(cluster_spec):\n \"\"\"Gets number of workers including chief.\"\"\"\n if not cluster_spec:\n return 0\n return len(cluster_spec.as_dict().get(_TaskType.WORKER, [])) + len(\n cluster_spec.as_dict().get(_TaskType.CHIEF, []))\n\n\nclass _WorkerContext(object):\n \"\"\"The worker context class.\n\n This context object provides configuration information for each task. One\n context manager with a worker context object will be created per\n invocation to the `worker_fn` where `get_current_worker_context` can be called\n to access the worker context object.\n \"\"\"\n\n def __init__(self,\n strategy,\n cluster_spec,\n task_type,\n task_id,\n session_config=None,\n rpc_layer=\"grpc\",\n worker_barrier=None):\n \"\"\"Initialize the worker context object.\n\n Args:\n strategy: a `DistributionStrategy` object.\n cluster_spec: a ClusterSpec object. It can be empty or None in the local\n training case.\n task_type: a string indicating the role of the corresponding task, such as\n \"worker\" or \"ps\". It can be None if it is local training or in-graph\n replicated training.\n task_id: an integer indicating id of the corresponding task. It can be\n None if it is local training or in-graph replicated training.\n session_config: an optional `tf.compat.v1.ConfigProto` object.\n rpc_layer: optional string specifying the RPC protocol for communication\n with worker masters. If None or empty, hosts in the `cluster_spec` will\n be used directly.\n worker_barrier: optional, the barrier object for worker synchronization.\n \"\"\"\n self._strategy = strategy\n self._cluster_spec = cluster_spec\n self._task_type = task_type\n self._task_id = task_id\n self._session_config = session_config\n self._worker_barrier = worker_barrier\n self._rpc_layer = rpc_layer\n self._master_target = self._get_master_target()\n self._num_workers = _get_num_workers(cluster_spec)\n self._is_chief_node = self._is_chief()\n\n def _debug_message(self):\n if self._cluster_spec:\n return \"[cluster_spec: %r, task_type: %r, task_id: %r]\" % (\n self._cluster_spec, self.task_type, self.task_id)\n else:\n return \"[local]\"\n\n def __enter__(self):\n old_context = get_current_worker_context()\n if old_context:\n raise ValueError(\n \"You cannot run distribute coordinator in a `worker_fn`.\\t\" +\n self._debug_message())\n # pylint: disable=protected-access\n _worker_context.current = self\n\n def __exit__(self, unused_exception_type, unused_exception_value,\n unused_traceback):\n # pylint: disable=protected-access\n _worker_context.current = None\n\n def _get_master_target(self):\n \"\"\"Return the master target for a task.\"\"\"\n # If cluster_spec is None or empty, we use local master.\n if not self._cluster_spec or self._task_type == _TaskType.EVALUATOR:\n return \"\"\n\n # If task_type is None, then it is in-graph replicated training. In this\n # case we use the chief or first worker's master target.\n if not self._task_type:\n if _TaskType.CHIEF in self._cluster_spec.jobs:\n task_type = _TaskType.CHIEF\n task_id = 0\n else:\n assert _TaskType.WORKER in self._cluster_spec.jobs\n task_type = _TaskType.WORKER\n task_id = 0\n else:\n task_type = self._task_type\n task_id = self._task_id\n\n prefix = \"\"\n if self._rpc_layer:\n prefix = self._rpc_layer + \"://\"\n return prefix + self._cluster_spec.job_tasks(task_type)[task_id or 0]\n\n def _is_chief(self):\n \"\"\"Return whether the task is the chief worker.\"\"\"\n if (not self._cluster_spec or\n self._task_type in [_TaskType.CHIEF, _TaskType.EVALUATOR, None]):\n return True\n\n # If not local and chief not in the cluster_spec, use the first worker as\n # chief.\n if (_TaskType.CHIEF not in self._cluster_spec.jobs and\n self._task_type == _TaskType.WORKER and self._task_id == 0):\n return True\n return False\n\n def wait_for_other_workers(self):\n \"\"\"Waits for other workers to reach the same call to this method.\n\n Raises:\n ValueError: if `worker_barrier` is not passed to the __init__ method.\n \"\"\"\n if not self._worker_barrier:\n # TODO(yuefengz): we should throw an error in independent worker mode.\n return\n self._worker_barrier.wait()\n\n def session_creator(self,\n scaffold=None,\n config=None,\n checkpoint_dir=None,\n checkpoint_filename_with_path=None,\n max_wait_secs=7200):\n \"\"\"Returns a session creator.\n\n The returned session creator will be configured with the correct master\n target and session configs. It will also run either init ops or ready ops\n by querying the `strategy` object when `create_session` is called on it.\n\n Args:\n scaffold: A `Scaffold` used for gathering or building supportive ops. If\n not specified a default one is created. It's used to finalize the graph.\n config: `ConfigProto` proto used to configure the session.\n checkpoint_dir: A string. Optional path to a directory where to restore\n variables.\n checkpoint_filename_with_path: Full file name path to the checkpoint file.\n Only one of `checkpoint_dir` or `checkpoint_filename_with_path` can be\n specified.\n max_wait_secs: Maximum time to wait for the session to become available.\n\n Returns:\n a descendant of SessionCreator.\n \"\"\"\n if config:\n session_config = copy.deepcopy(config)\n session_config.MergeFrom(self._session_config)\n else:\n session_config = self._session_config\n\n if not self._strategy or self._strategy.extended.experimental_should_init:\n logging.info(\"Creating chief session creator with config: %r\", config)\n return monitored_session.ChiefSessionCreator(\n scaffold,\n master=self.master_target,\n config=session_config,\n checkpoint_dir=checkpoint_dir,\n checkpoint_filename_with_path=checkpoint_filename_with_path)\n else:\n logging.info(\"Creating worker session creator with config: %r\", config)\n return monitored_session.WorkerSessionCreator(\n scaffold,\n master=self.master_target,\n config=session_config,\n max_wait_secs=max_wait_secs)\n\n @property\n def session_config(self):\n return copy.deepcopy(self._session_config)\n\n @property\n def has_barrier(self):\n \"\"\"Whether the barrier is set or not.\"\"\"\n return self._worker_barrier is not None\n\n @property\n def distributed_mode(self):\n \"\"\"Whether it is distributed training or not.\"\"\"\n return bool(self._cluster_spec) and self._task_type != _TaskType.EVALUATOR\n\n @property\n def cluster_spec(self):\n \"\"\"Returns a copy of the cluster_spec object.\"\"\"\n return copy.deepcopy(self._cluster_spec)\n\n @property\n def task_type(self):\n \"\"\"Returns the role of the corresponding task.\"\"\"\n return self._task_type\n\n @property\n def task_id(self):\n \"\"\"Returns the id or index of the corresponding task.\"\"\"\n return self._task_id\n\n @property\n def master_target(self):\n \"\"\"Returns the session master for the corresponding task to connect to.\"\"\"\n return self._master_target\n\n @property\n def is_chief(self):\n \"\"\"Returns whether the task is a chief node.\"\"\"\n return self._is_chief_node\n\n @property\n def num_workers(self):\n \"\"\"Returns number of workers in the cluster, including chief.\"\"\"\n return self._num_workers\n\n @property\n def experimental_should_init(self):\n \"\"\"Whether to run init ops.\"\"\"\n return self._strategy.extended.experimental_should_init\n\n @property\n def should_checkpoint(self):\n \"\"\"Whether to save checkpoint.\"\"\"\n return self._strategy.extended.should_checkpoint\n\n @property\n def should_save_summary(self):\n \"\"\"Whether to save summaries.\"\"\"\n return self._strategy.extended.should_save_summary\n\n\ndef _run_single_worker(worker_fn,\n strategy,\n cluster_spec,\n task_type,\n task_id,\n session_config,\n rpc_layer=\"\",\n worker_barrier=None,\n coord=None):\n \"\"\"Runs a single worker by calling `worker_fn` under context.\"\"\"\n session_config = copy.deepcopy(session_config)\n strategy = copy.deepcopy(strategy)\n # If there is an EVALUATOR task, we run single-machine eval on that task.\n if task_type == _TaskType.EVALUATOR:\n # It is possible to not have a strategy object for EVALUATOR task.\n if strategy:\n strategy.configure(session_config)\n else:\n assert strategy\n strategy.configure(session_config, cluster_spec, task_type, task_id)\n\n context = _WorkerContext(\n strategy,\n cluster_spec,\n task_type,\n task_id,\n session_config=session_config,\n rpc_layer=rpc_layer,\n worker_barrier=worker_barrier)\n with context:\n if coord:\n with coord.stop_on_exception():\n return worker_fn(strategy)\n else:\n return worker_fn(strategy)\n\n\ndef _split_cluster_for_evaluator(cluster_spec, task_type):\n \"\"\"Split the cluster for evaluator since it needn't talk to other tasks.\"\"\"\n # Splitting the cluster is important to prevent the evaluator from talking to\n # other tasks in the cluster. Since we allow evaluator not to use\n # distribution strategies and as a result ops in the evaluator task may have\n # unspecified devices. Those ops may end up on other tasks if we don't split\n # the cluster.\n # Note: if you bypass distribute coordinator and bring the cluster yourself,\n # you can equivalently set device filters to split clusters. This is already\n # done by distribution strategy's `update_config_proto` method.\n new_cluster_spec = normalize_cluster_spec(cluster_spec).as_dict()\n if task_type == _TaskType.EVALUATOR:\n assert _TaskType.EVALUATOR in new_cluster_spec\n new_cluster_spec = {\n _TaskType.EVALUATOR: new_cluster_spec[_TaskType.EVALUATOR]\n }\n else:\n new_cluster_spec.pop(_TaskType.EVALUATOR, None)\n return normalize_cluster_spec(new_cluster_spec)\n\n\ndef _run_std_server(cluster_spec=None,\n task_type=None,\n task_id=None,\n session_config=None,\n rpc_layer=None,\n environment=None):\n \"\"\"Runs a standard server.\"\"\"\n # Check if the Server is already running. If so, assert that no configuration\n # options have changed, and return the existing Server. This allows us to\n # call `run_distribute_coordinator` multiple times.\n if getattr(_thread_local, \"server\", None) is not None:\n assert _thread_local.cluster_spec == cluster_spec\n assert _thread_local.task_type == task_type\n assert _thread_local.task_id == task_id\n assert _thread_local.session_config_str == repr(session_config)\n assert _thread_local.rpc_layer == rpc_layer\n assert _thread_local.environment == environment\n return _thread_local.server\n else:\n # This method is not thread-safe.\n _thread_local.server_started = True\n _thread_local.cluster_spec = cluster_spec\n _thread_local.task_type = task_type\n _thread_local.task_id = task_id\n _thread_local.session_config_str = repr(session_config)\n _thread_local.rpc_layer = rpc_layer\n _thread_local.environment = environment\n\n assert cluster_spec\n target = cluster_spec.task_address(task_type, task_id)\n if rpc_layer:\n target = rpc_layer + \"://\" + target\n\n class _FakeServer(object):\n \"\"\"A fake server that runs a master session.\"\"\"\n\n def start(self):\n # A tensorflow server starts when a remote session is created.\n logging.info(\n \"Creating a remote session to start a TensorFlow server, \"\n \"target = %r, session_config=%r\", target, session_config)\n session.Session(target=target, config=session_config)\n\n def join(self):\n while True:\n time.sleep(5)\n\n if environment == \"google\":\n server = _FakeServer()\n else:\n if session_config:\n logging.info(\n \"Starting standard TensorFlow server, target = %r, session_config= \"\n \"%r\", target, session_config)\n else:\n logging.info(\"Starting standard TensorFlow server, target = %r\", target)\n cluster_spec = _split_cluster_for_evaluator(cluster_spec, task_type)\n server = server_lib.Server(\n cluster_spec,\n job_name=task_type,\n task_index=task_id,\n config=session_config,\n protocol=rpc_layer)\n\n server.start()\n _thread_local.server = server\n return server\n\n\ndef _configure_session_config_for_std_servers(strategy, eval_strategy,\n session_config, cluster_spec,\n task_type, task_id):\n # pylint: disable=g-doc-args\n \"\"\"Call strategy's `configure` to mutate the session_config.\n\n The session_config is currently needed as default config for a TensorFlow\n server. In the future, we should be able to remove this method and only pass\n the session config to a client session.\n \"\"\"\n if task_type == _TaskType.EVALUATOR:\n if eval_strategy:\n eval_strategy.configure(session_config=session_config)\n else:\n # The strategy may be shared in standalone client mode.\n strategy = copy.deepcopy(strategy)\n strategy.configure(\n session_config=session_config,\n cluster_spec=cluster_spec,\n task_type=task_type,\n task_id=task_id)\n # Remove the device filters specific to the strategy, so that the\n # TensorFlow server brought up with one strategy can be used by other\n # strategies. The device filters can be set in the client side as well.\n del session_config.device_filters[:]\n\n\n# TODO(yuefengz): propagate cluster_spec in the STANDALONE_CLIENT mode.\n# TODO(yuefengz): we may need a smart way to figure out whether the current task\n# is the special task when we support cluster_spec propagation.\ndef run_distribute_coordinator(worker_fn,\n strategy,\n eval_fn=None,\n eval_strategy=None,\n cluster_spec=None,\n task_type=None,\n task_id=None,\n session_config=None,\n rpc_layer=\"grpc\"):\n \"\"\"Runs the coordinator for distributed TensorFlow.\n\n This function runs a split coordinator for distributed TensorFlow in its\n default mode, i.e the STANDALONE_CLIENT mode. Given a `cluster_spec`\n specifying server addresses and their roles in a cluster, this coordinator\n will figure out how to set them up, give the underlying function the right\n targets for master sessions via a scope object and coordinate their training.\n The cluster consisting of standard servers needs to be brought up either with\n the standard server binary or with a binary running distribute coordinator\n with `task_type` set to non-client type which will then turn into standard\n servers.\n\n In addition to be the distribute coordinator, this is also the source of\n configurations for each job in the distributed training. As there are multiple\n ways to configure a distributed TensorFlow cluster, its context object\n provides these configurations so that users or higher-level APIs don't have to\n figure out the configuration for each job by themselves.\n\n In the between-graph replicated training, this coordinator will create\n multiple threads and each calls the `worker_fn` which is supposed to create\n its own graph and connect to one worker master given by its context object. In\n the in-graph replicated training, it has only one thread calling this\n `worker_fn`.\n\n Another mode is the INDEPENDENT_WORKER mode where each server runs a\n distribute coordinator which will start a standard server and optionally runs\n `worker_fn` depending whether it is between-graph training or in-graph\n replicated training.\n\n The `strategy` object is expected to be a DistributionStrategy object which\n has implemented methods needed by distributed coordinator such as\n `configure(session_config, cluster_spec, task_type, task_id)` which configures\n the strategy object for a specific task and `experimental_should_init`\n property which instructs the distribute coordinator whether to run init ops\n for a task. The distribute coordinator will make a copy of the `strategy`\n object, call its `configure` method and pass it to `worker_fn` as an argument.\n\n The `worker_fn` defines the training logic and is called under its own\n worker context which can be accessed to via `get_current_worker_context`. A\n worker context provides access to configurations for each task, e.g. the\n task_type, task_id, master target and so on. Since `worker_fn` will be called\n in a thread and possibly multiple times, caller should be careful when it\n accesses global data. For example, it is unsafe to define flags in a\n `worker_fn` or to define different environment variables for different\n `worker_fn`s.\n\n The `worker_fn` for the between-graph replication is defined as if there is\n only one worker corresponding to the `worker_fn` and possibly ps jobs. For\n example, when training with parameter servers, it assigns variables to\n parameter servers and all other operations to that worker. In the in-graph\n replication case, the `worker_fn` has to define operations for all worker\n jobs. Using a distribution strategy can simplify the `worker_fn` by not having\n to worry about the replication and device assignment of variables and\n operations.\n\n This method is intended to be invoked by high-level APIs so that users don't\n have to explicitly call it to run this coordinator. For those who don't use\n high-level APIs, to change a program to use this coordinator, wrap everything\n in a the program after global data definitions such as commandline flag\n definition into the `worker_fn` and get task-specific configurations from\n the worker context.\n\n The `cluster_spec` can be either passed by the argument or parsed from the\n \"TF_CONFIG\" environment variable. Example of a TF_CONFIG:\n ```\n cluster = {'chief': ['host0:2222'],\n 'ps': ['host1:2222', 'host2:2222'],\n 'worker': ['host3:2222', 'host4:2222', 'host5:2222']}\n os.environ['TF_CONFIG'] = json.dumps({'cluster': cluster})\n ```\n\n If `cluster_spec` is not given in any format, it becomes local training and\n this coordinator will connect to a local session.\n\n For evaluation, if \"evaluator\" exists in the cluster_spec, a separate thread\n will be created to call `eval_fn` with its `task_type` set to \"evaluator\". If\n `eval_fn` is not defined, fall back to `worker_fn`. This implies that\n evaluation will be done on a single machine if there is an \"evaluator\" task.\n If \"evaluator\" doesn't exist in the cluster_spec, it entirely depends on the\n `worker_fn` for how to do evaluation.\n\n Args:\n worker_fn: the function to be called. The function should accept a\n `strategy` object and will be given access to a context object via a\n context manager scope.\n strategy: a DistributionStrategy object specifying whether it should run\n between-graph replicated training or not, whether to run init ops, etc.\n This object will also be configured given `session_config`,\n `cluster_spec`, `task_type` and `task_id`.\n eval_fn: optional function for \"evaluator\" task. If `eval_fn` is not passed\n in but a \"evaluator\" task is found in the `cluster_spec`, the `worker_fn`\n will be used for this task.\n eval_strategy: optional DistributionStrategy object for \"evaluator\" task.\n cluster_spec: a dict, ClusterDef or ClusterSpec specifying servers and roles\n in a cluster. If not set or empty, fall back to local training.\n task_type: the current task type, optional if this is a client.\n task_id: the current task id, optional if this is a client.\n session_config: an optional `tf.compat.v1.ConfigProto` object which will be\n passed to `strategy`'s `configure` method and used to create a session.\n rpc_layer: optional string, the protocol for RPC, e.g. \"grpc\".\n\n Raises:\n ValueError: if `cluster_spec` is supplied but not a dict or a ClusterDef or\n a ClusterSpec.\n\n Returns:\n In the client job, return the value returned by `worker_fn` if\n it is in-graph replication or INDEPENDENT_WORKER mode; return None\n otherwise.\n \"\"\"\n tf_config = json.loads(os.environ.get(\"TF_CONFIG\", \"{}\"))\n rpc_layer = tf_config.get(\"rpc_layer\", rpc_layer)\n environment = tf_config.get(\"environment\", None)\n\n if not cluster_spec:\n cluster_spec = tf_config.get(\"cluster\", {})\n task_env = tf_config.get(\"task\", {})\n if task_env:\n task_type = task_env.get(\"type\", task_type)\n task_id = int(task_env.get(\"index\", task_id))\n\n if cluster_spec:\n # TODO(yuefengz): validate cluster_spec.\n cluster_spec = normalize_cluster_spec(cluster_spec)\n elif hasattr(strategy.extended, \"_cluster_resolver\"):\n cluster_resolver = strategy.extended._cluster_resolver # pylint: disable=protected-access\n task_type = cluster_resolver.task_type\n task_id = cluster_resolver.task_id\n rpc_layer = cluster_resolver.rpc_layer or rpc_layer\n environment = cluster_resolver.environment\n cluster_spec = cluster_resolver.cluster_spec()\n\n # Setting the session config is necessary for some strategies such as\n # CollectiveAllReduceStrategy.\n session_config = session_config or config_pb2.ConfigProto(\n allow_soft_placement=True)\n\n if cluster_spec:\n logging.info(\n \"Running Distribute Coordinator with cluster_spec = %r, \"\n \"task_type = %r, task_id = %r, environment = %r, rpc_layer = %r\",\n cluster_spec.as_dict(), task_type, task_id, environment, rpc_layer)\n\n if not cluster_spec:\n # `mode` is ignored in the local case.\n logging.info(\"Running local Distribute Coordinator.\")\n _run_single_worker(worker_fn, strategy, None, None, None, session_config,\n rpc_layer)\n if eval_fn:\n _run_single_worker(eval_fn, eval_strategy, None, None, None,\n session_config, rpc_layer)\n else:\n logging.warning(\"Skipped evaluation since `eval_fn` is not passed in.\")\n else:\n if not eval_fn:\n logging.warning(\"`eval_fn` is not passed in. The `worker_fn` will be \"\n \"used if an \\\"evaluator\\\" task exists in the cluster.\")\n eval_fn = eval_fn or worker_fn\n if not eval_strategy:\n logging.warning(\"`eval_strategy` is not passed in. No distribution \"\n \"strategy will be used for evaluation.\")\n\n # Every one starts a standard server, get session config from `configure`\n # method.\n _configure_session_config_for_std_servers(strategy, eval_strategy,\n session_config, cluster_spec,\n task_type, task_id)\n\n if (task_type != _TaskType.EVALUATOR and\n not getattr(strategy.extended, \"_std_server_started\", False)):\n # Right now, with eager mode, context is configured with a std server at\n # the very beginning while with graph mode the std server is started when\n # distribute coordinator is called. We should consolidate these two paths.\n server = _run_std_server(\n cluster_spec=cluster_spec,\n task_type=task_type,\n task_id=task_id,\n session_config=session_config,\n rpc_layer=rpc_layer,\n environment=environment)\n if task_type in [_TaskType.CHIEF, _TaskType.WORKER]:\n if strategy.extended.experimental_between_graph:\n # All jobs run `worker_fn` if between-graph.\n return _run_single_worker(worker_fn, strategy, cluster_spec, task_type,\n task_id, session_config, rpc_layer)\n else:\n # Only one node runs `worker_fn` if in-graph.\n context = _WorkerContext(strategy, cluster_spec, task_type, task_id)\n if context.is_chief:\n return _run_single_worker(worker_fn, strategy, cluster_spec, None,\n None, session_config, rpc_layer)\n else:\n server.join()\n elif task_type == _TaskType.EVALUATOR:\n return _run_single_worker(eval_fn, eval_strategy, cluster_spec, task_type,\n task_id, session_config, rpc_layer)\n else:\n if task_type != _TaskType.PS:\n raise ValueError(\"Unexpected task_type: %r\" % task_type)\n server.join()\n\n\ndef normalize_cluster_spec(cluster_spec):\n \"\"\"Makes `cluster_spec` into a `ClusterSpec` object.\n\n Args:\n cluster_spec: a dict, ClusterDef or ClusterSpec object specifying the\n cluster configurations.\n\n Returns:\n a `ClusterSpec` object.\n\n Raises:\n ValueError: if `cluster_spec` is not a dict or a `ClusterSpec` or a\n `ClusterDef`.\n \"\"\"\n if isinstance(cluster_spec, (dict, cluster_pb2.ClusterDef)):\n return server_lib.ClusterSpec(cluster_spec)\n elif not isinstance(cluster_spec, server_lib.ClusterSpec):\n raise ValueError(\n \"`cluster_spec' should be dict or a `tf.train.ClusterSpec` or a \"\n \"`tf.train.ClusterDef` object\")\n return cluster_spec\n", "# Copyright 2016 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\n\"\"\"Synchronize replicas for training.\"\"\"\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.framework import ops\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import data_flow_ops\nfrom tensorflow.python.ops import state_ops\nfrom tensorflow.python.ops import variable_scope\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.training import optimizer\nfrom tensorflow.python.training import queue_runner\nfrom tensorflow.python.training import session_manager\nfrom tensorflow.python.training import session_run_hook\nfrom tensorflow.python.util import deprecation\nfrom tensorflow.python.util.tf_export import tf_export\n\n\n# Please note that the gradients from replicas are averaged instead of summed\n# (as in the old sync_replicas_optimizer) so you need to increase the learning\n# rate according to the number of replicas. This change is introduced to be\n# consistent with how gradients are aggregated (averaged) within a batch in a\n# replica.\n@tf_export(v1=[\"train.SyncReplicasOptimizer\"])\nclass SyncReplicasOptimizer(optimizer.Optimizer):\n \"\"\"Class to synchronize, aggregate gradients and pass them to the optimizer.\n\n This class is deprecated. For synchronous training, please use [Distribution\n Strategies](https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/distribute).\n\n In a typical asynchronous training environment, it's common to have some\n stale gradients. For example, with a N-replica asynchronous training,\n gradients will be applied to the variables N times independently. Depending\n on each replica's training speed, some gradients might be calculated from\n copies of the variable from several steps back (N-1 steps on average). This\n optimizer avoids stale gradients by collecting gradients from all replicas,\n averaging them, then applying them to the variables in one shot, after\n which replicas can fetch the new variables and continue.\n\n The following accumulators/queue are created:\n\n * N `gradient accumulators`, one per variable to train. Gradients are pushed\n to them and the chief worker will wait until enough gradients are collected\n and then average them before applying to variables. The accumulator will\n drop all stale gradients (more details in the accumulator op).\n * 1 `token` queue where the optimizer pushes the new global_step value after\n all variables are updated.\n\n The following local variable is created:\n * `sync_rep_local_step`, one per replica. Compared against the global_step in\n each accumulator to check for staleness of the gradients.\n\n The optimizer adds nodes to the graph to collect gradients and pause the\n trainers until variables are updated.\n For the Parameter Server job:\n\n 1. An accumulator is created for each variable, and each replica pushes the\n gradients into the accumulators instead of directly applying them to the\n variables.\n 2. Each accumulator averages once enough gradients (replicas_to_aggregate)\n have been accumulated.\n 3. Apply the averaged gradients to the variables.\n 4. Only after all variables have been updated, increment the global step.\n 5. Only after step 4, pushes `global_step` in the `token_queue`, once for\n each worker replica. The workers can now fetch the global step, use it to\n update its local_step variable and start the next batch. Please note that\n some workers can consume multiple minibatches, while some may not consume\n even one. This is because each worker fetches minibatches as long as\n a token exists. If one worker is stuck for some reason and does not\n consume a token, another worker can use it.\n\n For the replicas:\n\n 1. Start a step: fetch variables and compute gradients.\n 2. Once the gradients have been computed, push them into gradient\n accumulators. Each accumulator will check the staleness and drop the stale.\n 3. After pushing all the gradients, dequeue an updated value of global_step\n from the token queue and record that step to its local_step variable. Note\n that this is effectively a barrier.\n 4. Start the next batch.\n\n ### Usage\n\n ```python\n # Create any optimizer to update the variables, say a simple SGD:\n opt = GradientDescentOptimizer(learning_rate=0.1)\n\n # Wrap the optimizer with sync_replicas_optimizer with 50 replicas: at each\n # step the optimizer collects 50 gradients before applying to variables.\n # Note that if you want to have 2 backup replicas, you can change\n # total_num_replicas=52 and make sure this number matches how many physical\n # replicas you started in your job.\n opt = tf.compat.v1.train.SyncReplicasOptimizer(opt, replicas_to_aggregate=50,\n total_num_replicas=50)\n\n # Some models have startup_delays to help stabilize the model but when using\n # sync_replicas training, set it to 0.\n\n # Now you can call `minimize()` or `compute_gradients()` and\n # `apply_gradients()` normally\n training_op = opt.minimize(total_loss, global_step=self.global_step)\n\n\n # You can create the hook which handles initialization and queues.\n sync_replicas_hook = opt.make_session_run_hook(is_chief)\n ```\n\n In the training program, every worker will run the train_op as if not\n synchronized.\n\n ```python\n with training.MonitoredTrainingSession(\n master=workers[worker_id].target, is_chief=is_chief,\n hooks=[sync_replicas_hook]) as mon_sess:\n while not mon_sess.should_stop():\n mon_sess.run(training_op)\n ```\n\n To use SyncReplicasOptimizer with an `Estimator`, you need to send\n sync_replicas_hook while calling the fit.\n ```python\n my_estimator = DNNClassifier(..., optimizer=opt)\n my_estimator.fit(..., hooks=[sync_replicas_hook])\n ```\n \"\"\"\n\n @deprecation.deprecated(\n None, \"The `SyncReplicaOptimizer` class is deprecated. For synchronous \"\n \"training, please use [Distribution Strategies](https://github.com/\"\n \"tensorflow/tensorflow/tree/master/tensorflow/contrib/distribute).\",\n warn_once=True)\n def __init__(self,\n opt,\n replicas_to_aggregate,\n total_num_replicas=None,\n variable_averages=None,\n variables_to_average=None,\n use_locking=False,\n name=\"sync_replicas\"):\n \"\"\"Construct a sync_replicas optimizer.\n\n Args:\n opt: The actual optimizer that will be used to compute and apply the\n gradients. Must be one of the Optimizer classes.\n replicas_to_aggregate: number of replicas to aggregate for each variable\n update.\n total_num_replicas: Total number of tasks/workers/replicas, could be\n different from replicas_to_aggregate.\n If total_num_replicas > replicas_to_aggregate: it is backup_replicas +\n replicas_to_aggregate.\n If total_num_replicas < replicas_to_aggregate: Replicas compute\n multiple batches per update to variables.\n variable_averages: Optional `ExponentialMovingAverage` object, used to\n maintain moving averages for the variables passed in\n `variables_to_average`.\n variables_to_average: a list of variables that need to be averaged. Only\n needed if variable_averages is passed in.\n use_locking: If True use locks for update operation.\n name: string. Optional name of the returned operation.\n \"\"\"\n if total_num_replicas is None:\n total_num_replicas = replicas_to_aggregate\n\n super(SyncReplicasOptimizer, self).__init__(use_locking, name)\n logging.info(\n \"SyncReplicasV2: replicas_to_aggregate=%s; total_num_replicas=%s\",\n replicas_to_aggregate, total_num_replicas)\n self._opt = opt\n self._replicas_to_aggregate = replicas_to_aggregate\n self._gradients_applied = False\n self._variable_averages = variable_averages\n self._variables_to_average = variables_to_average\n self._total_num_replicas = total_num_replicas\n self._tokens_per_step = max(total_num_replicas, replicas_to_aggregate)\n self._global_step = None\n self._sync_token_queue = None\n\n # The synchronization op will be executed in a queue runner which should\n # only be executed by one of the replicas (usually the chief).\n self._chief_queue_runner = None\n\n # Remember which accumulator is on which device to set the initial step in\n # the accumulator to be global step. This list contains list of the\n # following format: (accumulator, device).\n self._accumulator_list = []\n\n def compute_gradients(self, *args, **kwargs):\n \"\"\"Compute gradients of \"loss\" for the variables in \"var_list\".\n\n This simply wraps the compute_gradients() from the real optimizer. The\n gradients will be aggregated in the apply_gradients() so that user can\n modify the gradients like clipping with per replica global norm if needed.\n The global norm with aggregated gradients can be bad as one replica's huge\n gradients can hurt the gradients from other replicas.\n\n Args:\n *args: Arguments for compute_gradients().\n **kwargs: Keyword arguments for compute_gradients().\n\n Returns:\n A list of (gradient, variable) pairs.\n \"\"\"\n return self._opt.compute_gradients(*args, **kwargs)\n\n def apply_gradients(self, grads_and_vars, global_step=None, name=None):\n \"\"\"Apply gradients to variables.\n\n This contains most of the synchronization implementation and also wraps the\n apply_gradients() from the real optimizer.\n\n Args:\n grads_and_vars: List of (gradient, variable) pairs as returned by\n compute_gradients().\n global_step: Optional Variable to increment by one after the\n variables have been updated.\n name: Optional name for the returned operation. Default to the\n name passed to the Optimizer constructor.\n\n Returns:\n train_op: The op to dequeue a token so the replicas can exit this batch\n and start the next one. This is executed by each replica.\n\n Raises:\n ValueError: If the grads_and_vars is empty.\n ValueError: If global step is not provided, the staleness cannot be\n checked.\n \"\"\"\n if not grads_and_vars:\n raise ValueError(\"Must supply at least one variable\")\n\n if global_step is None:\n raise ValueError(\"Global step is required to check staleness\")\n\n self._global_step = global_step\n train_ops = []\n aggregated_grad = []\n var_list = []\n\n # local_anchor op will be placed on this worker task by default.\n local_anchor = control_flow_ops.no_op()\n # Colocating local_step variable prevents it being placed on the PS.\n distribution_strategy = distribution_strategy_context.get_strategy()\n with distribution_strategy.extended.colocate_vars_with(local_anchor):\n self._local_step = variable_scope.variable(\n initial_value=0,\n trainable=False,\n collections=[ops.GraphKeys.LOCAL_VARIABLES],\n dtype=global_step.dtype.base_dtype,\n name=\"sync_rep_local_step\")\n\n self.local_step_init_op = state_ops.assign(self._local_step, global_step)\n chief_init_ops = [self.local_step_init_op]\n self.ready_for_local_init_op = variables.report_uninitialized_variables(\n variables.global_variables())\n\n with ops.name_scope(None, self._name):\n for grad, var in grads_and_vars:\n var_list.append(var)\n with ops.device(var.device):\n # Dense gradients.\n if grad is None:\n aggregated_grad.append(None) # pass-through.\n continue\n elif isinstance(grad, ops.Tensor):\n grad_accum = data_flow_ops.ConditionalAccumulator(\n grad.dtype,\n shape=var.get_shape(),\n shared_name=var.name + \"/grad_accum\")\n train_ops.append(grad_accum.apply_grad(\n grad, local_step=self._local_step))\n aggregated_grad.append(grad_accum.take_grad(\n self._replicas_to_aggregate))\n else:\n if not isinstance(grad, ops.IndexedSlices):\n raise ValueError(\"Unknown grad type!\")\n grad_accum = data_flow_ops.SparseConditionalAccumulator(\n grad.dtype, shape=(), shared_name=var.name + \"/grad_accum\")\n train_ops.append(grad_accum.apply_indexed_slices_grad(\n grad, local_step=self._local_step))\n aggregated_grad.append(grad_accum.take_indexed_slices_grad(\n self._replicas_to_aggregate))\n\n self._accumulator_list.append((grad_accum, var.device))\n\n aggregated_grads_and_vars = zip(aggregated_grad, var_list)\n\n # sync_op will be assigned to the same device as the global step.\n with ops.device(global_step.device), ops.name_scope(\"\"):\n update_op = self._opt.apply_gradients(aggregated_grads_and_vars,\n global_step)\n\n # Create token queue.\n with ops.device(global_step.device), ops.name_scope(\"\"):\n sync_token_queue = (\n data_flow_ops.FIFOQueue(-1,\n global_step.dtype.base_dtype,\n shapes=(),\n name=\"sync_token_q\",\n shared_name=\"sync_token_q\"))\n self._sync_token_queue = sync_token_queue\n\n with ops.device(global_step.device), ops.name_scope(\"\"):\n # Replicas have to wait until they can get a token from the token queue.\n with ops.control_dependencies(train_ops):\n token = sync_token_queue.dequeue()\n train_op = state_ops.assign(self._local_step, token)\n\n with ops.control_dependencies([update_op]):\n # Sync_op needs to insert tokens to the token queue at the end of the\n # step so the replicas can fetch them to start the next step.\n tokens = array_ops.fill([self._tokens_per_step], global_step)\n sync_op = sync_token_queue.enqueue_many((tokens,))\n\n if self._variable_averages is not None:\n with ops.control_dependencies([sync_op]), ops.name_scope(\"\"):\n sync_op = self._variable_averages.apply(\n self._variables_to_average)\n\n self._chief_queue_runner = queue_runner.QueueRunner(\n sync_token_queue, [sync_op])\n for accum, dev in self._accumulator_list:\n with ops.device(dev):\n chief_init_ops.append(\n accum.set_global_step(\n global_step, name=\"SetGlobalStep\"))\n self.chief_init_op = control_flow_ops.group(*(chief_init_ops))\n self._gradients_applied = True\n return train_op\n\n def get_chief_queue_runner(self):\n \"\"\"Returns the QueueRunner for the chief to execute.\n\n This includes the operations to synchronize replicas: aggregate gradients,\n apply to variables, increment global step, insert tokens to token queue.\n\n Note that this can only be called after calling apply_gradients() which\n actually generates this queuerunner.\n\n Returns:\n A `QueueRunner` for chief to execute.\n\n Raises:\n ValueError: If this is called before apply_gradients().\n \"\"\"\n if self._gradients_applied is False:\n raise ValueError(\"Should be called after apply_gradients().\")\n\n return self._chief_queue_runner\n\n def get_slot(self, *args, **kwargs):\n \"\"\"Return a slot named \"name\" created for \"var\" by the Optimizer.\n\n This simply wraps the get_slot() from the actual optimizer.\n\n Args:\n *args: Arguments for get_slot().\n **kwargs: Keyword arguments for get_slot().\n\n Returns:\n The `Variable` for the slot if it was created, `None` otherwise.\n \"\"\"\n return self._opt.get_slot(*args, **kwargs)\n\n def variables(self):\n \"\"\"Fetches a list of optimizer variables in the default graph.\n\n This wraps `variables()` from the actual optimizer. It does not include\n the `SyncReplicasOptimizer`'s local step.\n\n Returns:\n A list of variables.\n \"\"\"\n return self._opt.variables()\n\n def get_slot_names(self, *args, **kwargs):\n \"\"\"Return a list of the names of slots created by the `Optimizer`.\n\n This simply wraps the get_slot_names() from the actual optimizer.\n\n Args:\n *args: Arguments for get_slot().\n **kwargs: Keyword arguments for get_slot().\n\n Returns:\n A list of strings.\n \"\"\"\n return self._opt.get_slot_names(*args, **kwargs)\n\n def get_init_tokens_op(self, num_tokens=-1):\n \"\"\"Returns the op to fill the sync_token_queue with the tokens.\n\n This is supposed to be executed in the beginning of the chief/sync thread\n so that even if the total_num_replicas is less than replicas_to_aggregate,\n the model can still proceed as the replicas can compute multiple steps per\n variable update. Make sure:\n `num_tokens >= replicas_to_aggregate - total_num_replicas`.\n\n Args:\n num_tokens: Number of tokens to add to the queue.\n\n Returns:\n An op for the chief/sync replica to fill the token queue.\n\n Raises:\n ValueError: If this is called before apply_gradients().\n ValueError: If num_tokens are smaller than replicas_to_aggregate -\n total_num_replicas.\n \"\"\"\n if self._gradients_applied is False:\n raise ValueError(\n \"get_init_tokens_op() should be called after apply_gradients().\")\n\n tokens_needed = self._replicas_to_aggregate - self._total_num_replicas\n if num_tokens == -1:\n num_tokens = self._replicas_to_aggregate\n elif num_tokens < tokens_needed:\n raise ValueError(\n \"Too few tokens to finish the first step: %d (given) vs %d (needed)\" %\n (num_tokens, tokens_needed))\n\n if num_tokens > 0:\n with ops.device(self._global_step.device), ops.name_scope(\"\"):\n tokens = array_ops.fill([num_tokens], self._global_step)\n init_tokens = self._sync_token_queue.enqueue_many((tokens,))\n else:\n init_tokens = control_flow_ops.no_op(name=\"no_init_tokens\")\n\n return init_tokens\n\n def make_session_run_hook(self, is_chief, num_tokens=-1):\n \"\"\"Creates a hook to handle SyncReplicasHook ops such as initialization.\"\"\"\n return _SyncReplicasOptimizerHook(self, is_chief, num_tokens)\n\n\nclass _SyncReplicasOptimizerHook(session_run_hook.SessionRunHook):\n \"\"\"A SessionRunHook handles ops related to SyncReplicasOptimizer.\"\"\"\n\n def __init__(self, sync_optimizer, is_chief, num_tokens):\n \"\"\"Creates hook to handle SyncReplicasOptimizer initialization ops.\n\n Args:\n sync_optimizer: `SyncReplicasOptimizer` which this hook will initialize.\n is_chief: `Bool`, whether is this a chief replica or not.\n num_tokens: Number of tokens to add to the queue.\n \"\"\"\n self._sync_optimizer = sync_optimizer\n self._is_chief = is_chief\n self._num_tokens = num_tokens\n\n def begin(self):\n if self._sync_optimizer._gradients_applied is False: # pylint: disable=protected-access\n raise ValueError(\n \"SyncReplicasOptimizer.apply_gradient should be called before using \"\n \"the hook.\")\n if self._is_chief:\n self._local_init_op = self._sync_optimizer.chief_init_op\n self._ready_for_local_init_op = (\n self._sync_optimizer.ready_for_local_init_op)\n self._q_runner = self._sync_optimizer.get_chief_queue_runner()\n self._init_tokens_op = self._sync_optimizer.get_init_tokens_op(\n self._num_tokens)\n else:\n self._local_init_op = self._sync_optimizer.local_step_init_op\n self._ready_for_local_init_op = (\n self._sync_optimizer.ready_for_local_init_op)\n self._q_runner = None\n self._init_tokens_op = None\n\n def after_create_session(self, session, coord):\n \"\"\"Runs SyncReplicasOptimizer initialization ops.\"\"\"\n local_init_success, msg = session_manager._ready( # pylint: disable=protected-access\n self._ready_for_local_init_op, session,\n \"Model is not ready for SyncReplicasOptimizer local init.\")\n if not local_init_success:\n raise RuntimeError(\n \"Init operations did not make model ready for SyncReplicasOptimizer \"\n \"local_init. Init op: %s, error: %s\" %\n (self._local_init_op.name, msg))\n session.run(self._local_init_op)\n if self._init_tokens_op is not None:\n session.run(self._init_tokens_op)\n if self._q_runner is not None:\n self._q_runner.create_threads(\n session, coord=coord, daemon=True, start=True)\n", "# Copyright 2021 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# pylint: disable=g-classes-have-attributes\n\"\"\"Contains a shim to allow using TF1 get_variable code in TF2.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport functools\n\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.engine import base_layer\nfrom tensorflow.python.keras.utils import tf_contextlib\nfrom tensorflow.python.keras.utils import tf_inspect\nfrom tensorflow.python.module import module\nfrom tensorflow.python.ops import init_ops\nfrom tensorflow.python.ops import variable_scope as vs\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.util import tf_decorator\n\n\ndef as_shape(shape):\n \"\"\"Converts the given object to a TensorShape.\"\"\"\n if isinstance(shape, tensor_shape.TensorShape):\n return shape\n else:\n return tensor_shape.TensorShape(shape)\n\n\ndef _is_callable_object(obj):\n return hasattr(obj, \"__call__\") and tf_inspect.ismethod(obj.__call__)\n\n\ndef _has_kwargs(fn):\n \"\"\"Returns whether the passed callable has **kwargs in its signature.\n\n Args:\n fn: Function, or function-like object (e.g., result of `functools.partial`).\n\n Returns:\n `bool`: if `fn` has **kwargs in its signature.\n\n Raises:\n `TypeError`: If fn is not a Function, or function-like object.\n \"\"\"\n if isinstance(fn, functools.partial):\n fn = fn.func\n elif _is_callable_object(fn):\n fn = fn.__call__\n elif not callable(fn):\n raise TypeError(\n \"fn should be a function-like object, but is of type {}.\".format(\n type(fn)))\n return tf_inspect.getfullargspec(fn).varkw is not None\n\n\ndef fn_args(fn):\n \"\"\"Get argument names for function-like object.\n\n Args:\n fn: Function, or function-like object (e.g., result of `functools.partial`).\n\n Returns:\n `tuple` of string argument names.\n\n Raises:\n ValueError: if partial function has positionally bound arguments\n \"\"\"\n if isinstance(fn, functools.partial):\n args = fn_args(fn.func)\n args = [a for a in args[len(fn.args):] if a not in (fn.keywords or [])]\n else:\n if hasattr(fn, \"__call__\") and tf_inspect.ismethod(fn.__call__):\n fn = fn.__call__\n args = tf_inspect.getfullargspec(fn).args\n if _is_bound_method(fn) and args:\n # If it's a bound method, it may or may not have a self/cls first\n # argument; for example, self could be captured in *args.\n # If it does have a positional argument, it is self/cls.\n args.pop(0)\n return tuple(args)\n\n\ndef _is_bound_method(fn):\n _, fn = tf_decorator.unwrap(fn)\n return tf_inspect.ismethod(fn) and (fn.__self__ is not None)\n\n\ndef validate_synchronization_aggregation_trainable(\n synchronization, aggregation, trainable, name):\n \"\"\"Given user-provided variable properties, sets defaults and validates.\"\"\"\n if aggregation is None:\n aggregation = variables.VariableAggregation.NONE\n else:\n if not isinstance(aggregation,\n (variables.VariableAggregation,\n variables.VariableAggregationV2)):\n try:\n aggregation = variables.VariableAggregationV2(aggregation)\n except ValueError:\n raise ValueError(\n \"Invalid variable aggregation mode: {} for variable: {}\".format(\n aggregation, name))\n if synchronization is None:\n synchronization = variables.VariableSynchronization.AUTO\n else:\n try:\n synchronization = variables.VariableSynchronization(synchronization)\n except ValueError:\n raise ValueError(\n \"Invalid variable synchronization mode: {} for variable: {}\".format(\n synchronization, name))\n if trainable is None:\n trainable = synchronization != variables.VariableSynchronization.ON_READ\n return synchronization, aggregation, trainable\n\n\nclass _EagerVariableStore(object):\n \"\"\"TF2-compatible VariableStore that avoids collections & tracks regularizers.\n\n New variable names and new variables can be created; all stored\n variables are initialized with the initializer passed to __init__.\n\n All variables get created in `tf.init_scope.` to avoid a bad\n interaction between `tf.function` `FuncGraph` internals, Keras\n Functional Models, and TPUStrategy variable initialization.\n\n Attributes:\n vars: a dictionary with string names (same as passed in GetVar) as keys and\n the corresponding TensorFlow Variables as values.\n \"\"\"\n\n __slots__ = [\"_vars\", \"_regularizers\", \"_store_eager_variables\"]\n\n def __init__(self):\n \"\"\"Create a variable store.\"\"\"\n self._vars = {} # A dictionary of the stored TensorFlow variables.\n self._regularizers = {} # A dict mapping var names to their regularizers.\n self._store_eager_variables = True\n\n def get_variable(\n self,\n name,\n shape=None,\n dtype=dtypes.float32,\n initializer=None,\n regularizer=None,\n reuse=None,\n trainable=None,\n collections=None,\n caching_device=None,\n partitioner=None,\n validate_shape=True,\n use_resource=None,\n custom_getter=None,\n constraint=None,\n synchronization=vs.VariableSynchronization.AUTO,\n aggregation=vs.VariableAggregation.NONE):\n \"\"\"Gets an existing variable with these parameters or create a new one.\n\n If a variable with the given name is already stored, we return the stored\n variable. Otherwise, we create a new one.\n\n Set `reuse` to `True` when you only want to reuse existing Variables.\n Set `reuse` to `False` when you only want to create new Variables.\n Set `reuse` to None (the default) or tf.compat.v1.AUTO_REUSE when you want\n variables to be created if they don't exist or returned if they do.\n\n If initializer is `None` (the default), the default initializer passed in\n the constructor is used. If that one is `None` too, we use a new\n `glorot_uniform_initializer`. If initializer is a Tensor, we use\n it as a value and derive the shape from the initializer.\n\n If a partitioner is provided, a `PartitionedVariable` is returned.\n Accessing this object as a `Tensor` returns the shards concatenated along\n the partition axis.\n\n Some useful partitioners are available. See, e.g.,\n `variable_axis_size_partitioner` and `min_max_variable_partitioner`.\n\n Args:\n name: The name of the new or existing variable.\n shape: Shape of the new or existing variable.\n dtype: Type of the new or existing variable (defaults to `DT_FLOAT`).\n initializer: Initializer for the variable.\n regularizer: A (Tensor -> Tensor or None) function; the result of applying\n it on a newly created variable will be added to the collection\n GraphKeys.REGULARIZATION_LOSSES and can be used for regularization.\n reuse: a Boolean, None, or tf.AUTO_REUSE. Controls reuse or creation of\n variables. When eager execution is enabled this argument is always\n forced to be False.\n trainable: If `True` also add the variable to the graph collection\n `GraphKeys.TRAINABLE_VARIABLES` (see `tf.Variable`). `trainable`\n defaults to `True`, unless `synchronization` is set to `ON_READ`, in\n which case it defaults to `False`.\n collections: List of graph collections keys to add the `Variable` to.\n Defaults to `[GraphKeys.GLOBAL_VARIABLES]` (see `tf.Variable`).\n caching_device: Optional device string or function describing where the\n Variable should be cached for reading. Defaults to the Variable's\n device. If not `None`, caches on another device. Typical use is to\n cache on the device where the Ops using the `Variable` reside, to\n deduplicate copying through `Switch` and other conditional statements.\n partitioner: Optional callable that accepts a fully defined `TensorShape`\n and dtype of the `Variable` to be created, and returns a list of\n partitions for each axis (currently only one axis can be partitioned).\n validate_shape: If False, allows the variable to be initialized with a\n value of unknown shape. If True, the default, the shape of initial_value\n must be known.\n use_resource: If False, creates a regular Variable. If True, creates\n instead an experimental ResourceVariable which has well-defined\n semantics. Defaults to False (will later change to True). When eager\n execution is enabled this argument is always forced to be true.\n custom_getter: Callable that takes as a first argument the true getter,\n and allows overwriting the internal get_variable method. The signature\n of `custom_getter` should match that of this method,\n but the most future-proof version will allow for changes: `def\n custom_getter(getter, *args, **kwargs)`. Direct access to\n all `get_variable` parameters is also allowed: `def\n custom_getter(getter, name, *args, **kwargs)`. A simple identity\n custom getter that simply creates variables with modified names is:\n ```python\n def custom_getter(getter, name, *args, **kwargs): return getter(name +\n '_suffix', *args, **kwargs) ```\n constraint: An optional projection function to be applied to the variable\n after being updated by an `Optimizer` (e.g. used to implement norm\n constraints or value constraints for layer weights). The function must\n take as input the unprojected Tensor representing the value of the\n variable and return the Tensor for the projected value (which must have\n the same shape). Constraints are not safe to use when doing asynchronous\n distributed training.\n synchronization: Indicates when a distributed a variable will be\n aggregated. Accepted values are constants defined in the class\n `tf.VariableSynchronization`. By default the synchronization is set to\n `AUTO` and the current `DistributionStrategy` chooses when to\n synchronize.\n aggregation: Indicates how a distributed variable will be aggregated.\n Accepted values are constants defined in the class\n `tf.VariableAggregation`.\n\n Returns:\n The created or existing `Variable` (or `PartitionedVariable`, if a\n partitioner was used).\n\n Raises:\n ValueError: when creating a new variable and shape is not declared,\n when reusing a variable and specifying a conflicting shape,\n or when violating reuse during variable creation.\n RuntimeError: when eager execution is enabled and not called from an\n EagerVariableStore.\n \"\"\"\n if custom_getter is not None and not callable(custom_getter):\n raise ValueError(\"Passed a custom_getter which is not callable: %s\" %\n custom_getter)\n\n with ops.init_scope():\n if context.executing_eagerly():\n # Variable creation and initialization takes place in `init_scope`s;\n # as such, if an `init_scope` lifts us into the eager context, then we\n # need to use `ResourceVariable`s.\n use_resource = True\n\n # Note that it's fine to reuse eager variables whose initialization was\n # lifted from a function-building graph into the eager context (that's why\n # the following clause is not wrapped in an `init_scope`); lifted variables\n # are tracked by the graph's `VariableStore`.\n if context.executing_eagerly():\n reuse = vs.AUTO_REUSE\n\n # If a *_ref type is passed in an error would be triggered further down the\n # stack. We prevent this using base_dtype to get a non-ref version of the\n # type, before doing anything else. When _ref types are removed in favor of\n # resources, this line can be removed.\n try:\n dtype = dtype.base_dtype\n except AttributeError:\n # .base_dtype not existing means that we will try and use the raw dtype\n # which was passed in - this might be a NumPy type which is valid.\n pass\n\n # This is the main logic of get_variable. However, custom_getter\n # may override this logic. So we save it as a callable and pass\n # it to custom_getter.\n # Note: the parameters of _true_getter, and their documentation, match\n # *exactly* item-for-item with the docstring of this method.\n def _true_getter( # pylint: disable=missing-docstring\n name,\n shape=None,\n dtype=dtypes.float32,\n initializer=None,\n regularizer=None,\n reuse=None,\n trainable=None,\n collections=None, # pylint: disable=unused-argument\n caching_device=None,\n partitioner=None,\n validate_shape=True,\n use_resource=None, # pylint: disable=unused-argument\n constraint=None,\n synchronization=vs.VariableSynchronization.AUTO,\n aggregation=vs.VariableAggregation.NONE):\n # Partitioned variable currently unsupported w/ the shim\n if partitioner is not None:\n raise ValueError(\n \"`partitioner` arg for `get_variable` is unsupported in TF2.\"\n \"File a bug if you need help. You passed %s\" % partitioner)\n\n # Single variable case\n if \"%s/part_0\" % name in self._vars:\n raise ValueError(\n \"No partitioner was provided, but a partitioned version of the \"\n \"variable was found: %s/part_0. Perhaps a variable of the same \"\n \"name was already created with partitioning?\" % name)\n\n return self._get_single_variable(\n name=name,\n shape=shape,\n dtype=dtype,\n initializer=initializer,\n regularizer=regularizer,\n reuse=reuse,\n trainable=trainable,\n caching_device=caching_device,\n validate_shape=validate_shape,\n constraint=constraint,\n synchronization=synchronization,\n aggregation=aggregation)\n\n synchronization, aggregation, trainable = (\n validate_synchronization_aggregation_trainable(\n synchronization, aggregation, trainable, name))\n\n if custom_getter is not None:\n # Handle backwards compatibility with getter arguments that were added\n # to the API after users started writing custom getters.\n custom_getter_kwargs = {\n \"getter\": _true_getter,\n \"name\": name,\n \"shape\": shape,\n \"dtype\": dtype,\n \"initializer\": initializer,\n \"regularizer\": regularizer,\n \"reuse\": reuse,\n \"trainable\": trainable,\n \"collections\": collections,\n \"caching_device\": caching_device,\n \"partitioner\": partitioner,\n \"validate_shape\": validate_shape,\n \"use_resource\": use_resource,\n \"synchronization\": synchronization,\n \"aggregation\": aggregation,\n }\n # `fn_args` and `has_kwargs` can handle functions, `functools.partial`,\n # `lambda`.\n if (\"constraint\" in fn_args(custom_getter) or\n _has_kwargs(custom_getter)):\n custom_getter_kwargs[\"constraint\"] = constraint\n return custom_getter(**custom_getter_kwargs)\n else:\n return _true_getter(\n name,\n shape=shape,\n dtype=dtype,\n initializer=initializer,\n regularizer=regularizer,\n reuse=reuse,\n trainable=trainable,\n collections=collections,\n caching_device=caching_device,\n partitioner=partitioner,\n validate_shape=validate_shape,\n use_resource=use_resource,\n constraint=constraint,\n synchronization=synchronization,\n aggregation=aggregation)\n\n def _get_single_variable(\n self,\n name,\n shape=None,\n dtype=dtypes.float32,\n initializer=None,\n regularizer=None,\n partition_info=None,\n reuse=None,\n trainable=None,\n caching_device=None,\n validate_shape=True,\n constraint=None,\n synchronization=vs.VariableSynchronization.AUTO,\n aggregation=vs.VariableAggregation.NONE):\n \"\"\"Get or create a single Variable (e.g.\n\n a shard or entire variable).\n\n See the documentation of get_variable above (ignore partitioning components)\n for details.\n\n Args:\n name: see get_variable.\n shape: see get_variable.\n dtype: see get_variable.\n initializer: see get_variable.\n regularizer: see get_variable.\n partition_info: _PartitionInfo object.\n reuse: see get_variable.\n trainable: see get_variable.\n caching_device: see get_variable.\n validate_shape: see get_variable.\n constraint: see get_variable.\n synchronization: see get_variable.\n aggregation: see get_variable.\n\n Returns:\n A Variable. See documentation of get_variable above.\n\n Raises:\n ValueError: See documentation of get_variable above.\n \"\"\"\n # Set to true if initializer is a constant.\n initializing_from_value = False\n if initializer is not None and not callable(initializer):\n initializing_from_value = True\n if shape is not None and initializing_from_value:\n raise ValueError(\"If initializer is a constant, do not specify shape.\")\n\n dtype = dtypes.as_dtype(dtype)\n shape = as_shape(shape)\n\n if name in self._vars:\n # Here we handle the case when returning an existing variable.\n if reuse is False: # pylint: disable=g-bool-id-comparison\n err_msg = (\"Variable %s already exists, disallowed.\"\n \" Did you mean to set reuse=True or \"\n \"reuse=tf.AUTO_REUSE in VarScope?\" % name)\n # ResourceVariables don't have an op associated with so no traceback\n raise ValueError(err_msg)\n found_var = self._vars[name]\n if not shape.is_compatible_with(found_var.get_shape()):\n raise ValueError(\"Trying to share variable %s, but specified shape %s\"\n \" and found shape %s.\" %\n (name, shape, found_var.get_shape()))\n if not dtype.is_compatible_with(found_var.dtype):\n dtype_str = dtype.name\n found_type_str = found_var.dtype.name\n raise ValueError(\"Trying to share variable %s, but specified dtype %s\"\n \" and found dtype %s.\" %\n (name, dtype_str, found_type_str))\n return found_var\n\n # The code below handles only the case of creating a new variable.\n if reuse is True: # pylint: disable=g-bool-id-comparison\n raise ValueError(\"Variable %s does not exist, or was not created with \"\n \"tf.get_variable(). Did you mean to set \"\n \"reuse=tf.AUTO_REUSE in VarScope?\" % name)\n\n # Create the tensor to initialize the variable with default value.\n if initializer is None:\n initializer, initializing_from_value = self._get_default_initializer(\n name=name, shape=shape, dtype=dtype)\n # Enter an init scope when creating the initializer.\n with ops.init_scope():\n if initializing_from_value:\n init_val = initializer\n variable_dtype = None\n else:\n # Instantiate initializer if provided initializer is a type object.\n if tf_inspect.isclass(initializer):\n initializer = initializer()\n if shape.is_fully_defined():\n if \"partition_info\" in tf_inspect.getargspec(initializer).args:\n init_val = functools.partial(initializer,\n shape.as_list(),\n dtype=dtype,\n partition_info=partition_info)\n else:\n init_val = functools.partial(initializer,\n shape.as_list(), dtype=dtype)\n variable_dtype = dtype.base_dtype\n else:\n init_val = initializer\n variable_dtype = None\n\n # Create the variable (Always eagerly as a workaround for a strange\n # tpu / funcgraph / keras functional model interaction )\n with ops.init_scope():\n v = variables.Variable(\n initial_value=init_val,\n name=name,\n trainable=trainable,\n caching_device=caching_device,\n dtype=variable_dtype,\n validate_shape=validate_shape,\n constraint=constraint,\n synchronization=synchronization,\n aggregation=aggregation)\n\n self._vars[name] = v\n logging.vlog(1, \"Created variable %s with shape %s and init %s\", v.name,\n format(shape), initializer)\n\n # Run the regularizer if requested and save the resulting loss.\n if regularizer:\n self.add_regularizer(v, regularizer)\n\n return v\n\n def add_regularizer(self, var, regularizer):\n self._regularizers[var.name] = functools.partial(regularizer, var)\n\n # Initialize variable when no initializer provided\n def _get_default_initializer(self, name, shape=None, dtype=dtypes.float32):\n \"\"\"Provide a default initializer and a corresponding value.\n\n Args:\n name: see get_variable.\n shape: see get_variable.\n dtype: see get_variable.\n\n Returns:\n initializer and initializing_from_value. See get_variable above.\n\n Raises:\n ValueError: When giving unsupported dtype.\n \"\"\"\n del shape\n # If dtype is DT_FLOAT, provide a uniform unit scaling initializer\n if dtype.is_floating:\n initializer = init_ops.glorot_uniform_initializer()\n initializing_from_value = False\n # If dtype is DT_INT/DT_UINT, provide a default value `zero`\n # If dtype is DT_BOOL, provide a default value `FALSE`\n elif (dtype.is_integer or dtype.is_unsigned or dtype.is_bool or\n dtype == dtypes.string):\n initializer = init_ops.zeros_initializer()\n initializing_from_value = False\n # NOTES:Do we need to support for handling DT_STRING and DT_COMPLEX here?\n else:\n raise ValueError(\"An initializer for variable %s of %s is required\" %\n (name, dtype.base_dtype))\n\n return initializer, initializing_from_value\n\n\nclass VariableAndLossTracker(module.Module):\n \"\"\"Module that has a scope to capture vars/losses made by `get_variable`.\"\"\"\n\n def __init__(self):\n self._var_store = _EagerVariableStore() # pylint: disable=protected-access\n self._variables = {}\n\n def _variable_creator(self, next_creator, **kwargs):\n var = next_creator(**kwargs)\n self._variables[var.name] = var\n\n return var\n\n @tf_contextlib.contextmanager\n def scope(self):\n with vs.variable_creator_scope(\n self._variable_creator), vs.with_variable_store(self._var_store):\n yield\n\n def get_regularization_losses(self):\n # TODO(kaftan): Consider adding a regex scope like the collection access.\n # But, < 40-50 usages of get_regularization_loss(es) with `scope`\n # & possible to do manually?\n losses = {}\n for var_name, regularizer in self._var_store._regularizers.items(): # pylint: disable=protected-access\n losses[var_name] = regularizer()\n return losses\n\n\nclass VariableScopeWrapperLayer(base_layer.Layer):\n \"\"\"Wrapper Layer to capture `compat.v1.get_variable` and `compat.v1.layers`.\n\n See go/tf2-migration-model-bookkeeping for background.\n\n This shim layer allows using large sets of TF1 model-forward-pass code as a\n Keras layer that works in TF2 with TF2 behaviors enabled. To use it,\n override this class and put your TF1 model's forward pass inside your\n implementation for `forward_pass`.\n\n Below are some examples, and then more details on the functionality of this\n shhim layer to wrap TF1 model forward passes.\n\n Example of capturing tf.compat.v1.layer-based modeling code as a Keras layer:\n\n ```python\n class WrappedDoubleDenseLayer(variable_scope_shim.VariableScopeWrapperLayer):\n\n def __init__(self, units, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.units = units\n\n def forward_pass(self, inputs, training=None):\n out = tf.compat.v1.layers.dense(\n inputs, self.units, name=\"dense_one\",\n kernel_initializer=init_ops.ones_initializer(),\n kernel_regularizer=\"l2\")\n with variable_scope.variable_scope(\"nested_scope\"):\n out = tf.compat.v1.layers.dense(\n out, self.units, name=\"dense_two\",\n kernel_initializer=init_ops.ones_initializer(),\n kernel_regularizer=\"l2\")\n return out\n\n # Create a layer that can be used as a standard keras layer\n layer = WrappedDoubleDenseLayer(10)\n\n # call the layer on inputs\n layer(...)\n\n # Variables created/used within the scope will be tracked by the layer\n layer.weights\n layer.trainable_variables\n\n # Regularization losses will be captured in layer.losses after a call,\n # just like any other Keras layer\n reg_losses = layer.losses\n ```\n\n The solution is to wrap the model construction and execution in a keras-style\n scope:\n\n ```python\n class WrappedDoubleDenseLayer(variable_scope_shim.VariableScopeWrapperLayer):\n\n def __init__(self, units, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.units = units\n\n def forward_pass(self, inputs, training=None):\n out = inputs\n with tf.compat.v1.variable_scope(\"dense_one\"):\n # The weights are created with a `regularizer`,\n # so the layer should track their regularization losses\n kernel = tf.compat.v1.get_variable(\n shape=[out.shape[-1], self.units],\n regularizer=regularizers.L2(),\n initializer=init_ops.ones_initializer(),\n name=\"kernel\")\n bias = tf.compat.v1.get_variable(\n shape=[self.units,],\n initializer=init_ops.zeros_initializer(),\n name=\"bias\")\n out = tf.compat.v1.math.matmul(out, kernel)\n out = tf.compat.v1.nn.bias_add(out, bias)\n with tf.compat.v1.variable_scope(\"nested_scope\"):\n with tf.compat.v1.variable_scope(\"dense_two\"):\n kernel = tf.compat.v1.get_variable(\n shape=[out.shape[-1], self.units],\n regularizer=regularizers.L2(),\n initializer=init_ops.ones_initializer(),\n name=\"kernel\")\n bias = tf.compat.v1.get_variable(\n shape=[self.units,],\n initializer=init_ops.zeros_initializer(),\n name=\"bias\")\n out = tf.compat.v1.math.matmul(out, kernel)\n out = tf.compat.v1.nn.bias_add(out, bias)\n return out\n\n # Create a layer that can be used as a standard keras layer\n layer = WrappedDoubleDenseLayer(10)\n\n # call the layer on inputs\n layer(...)\n\n # Variables created/used within the scope will be tracked by the layer\n layer.weights\n layer.trainable_variables\n\n # Regularization losses will be captured in layer.losses after a call,\n # just like any other Keras layer\n reg_losses = layer.losses\n ```\n\n Regularization losses:\n Any regularizers specified in the `get_variable` calls or `compat.v1.layer`\n creations will get captured by this wrapper layer. Regularization losses\n are accessible in `layer.losses` after a call just like in a standard\n Keras layer, and will be captured by any model that includes this layer.\n\n Variable scope / variable reuse:\n variable-scope based reuse in the `forward_pass` will be respected,\n and work like variable-scope based reuse in TF1.\n\n Variable Names/Pre-trained checkpoint loading:\n variable naming from get_variable and `compat.v1.layer` layers will match\n the TF1 names, so you should be able to re-use your old name-based\n checkpoints.\n\n Training Arg in `forward_pass`:\n Keras will pass a `training` arg to this layer similarly to how it\n passes `training` to other layers in TF2. See more details in the docs\n on `tf.keras.layers.Layer` to understand what will be passed and when.\n Note: tf.compat.v1.layers are usually not called with `training=None`,\n so the training arg to `forward_pass` might not feed through to them\n unless you pass it to their calls explicitly.\n\n Call signature of the forward pass:\n The semantics of the forward pass signature roughly match the standard\n Keras layer `call` signature, except that a `training` arg will *always*\n be passed, so your `forward_pass` must accept either.\n\n Limitations:\n * TF2 will not prune unused variable updates (or unused outputs). You may\n need to adjust your forward pass code to avoid computations or variable\n updates that you don't intend to use. (E.g. by adding a flag to the\n `forward_pass` call signature and branching on it).\n * Avoid Nesting variable creation in tf.function inside of `forward_pass`\n While the layer may safetely be used from inside a `tf.function`, using\n a function inside of `forward_pass` will break the variable scoping.\n * TBD: Nesting keras layers/models or other `VariableScopeWrapperLayer`s\n directly in `forward_pass` may not work correctly just yet.\n Support for this/instructions for how to do this is sill being worked on.\n\n Coming soon: A better guide, testing/verification guide.\n \"\"\"\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n # Relies on keras layers tracking Modules\n self.tracker = VariableAndLossTracker()\n # May need to inspect func to see if it should pass a `training` arg or not\n\n def forward_pass(self, *args, **kwargs):\n raise NotImplementedError\n\n def call(self, *args, **kwargs):\n with self.tracker.scope():\n out = self.forward_pass(*args, **kwargs)\n if not self._eager_losses:\n # We have to record regularization losses in the call as if they\n # are activity losses.\n # So, don't double-count regularization losses if the layer is used\n # multiple times in a model\n for loss in self.tracker.get_regularization_losses().values():\n self.add_loss(loss)\n return out\n", "# 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\"\"\"Extending CheckpointReader for TensorFlow.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors_impl\nfrom tensorflow.python.util import compat\nfrom tensorflow.python.util._pywrap_checkpoint_reader import CheckpointReader\nfrom tensorflow.python.util.tf_export import tf_export\n\n\ndef error_translator(e):\n \"\"\"Translate the tensor_slice_reader.cc errors.\"\"\"\n # TODO(b/143319754): Remove the RuntimeError casting logic once we resolve the\n # issue with throwing python exceptions from C++.\n error_message = str(e)\n if 'not found in checkpoint' in error_message or (\n 'Failed to find any '\n 'matching files for') in error_message:\n raise errors_impl.NotFoundError(None, None, error_message)\n elif 'Sliced checkpoints are not supported' in error_message or (\n 'Data type '\n 'not '\n 'supported') in error_message:\n raise errors_impl.UnimplementedError(None, None, error_message)\n elif 'Failed to get matching files on' in error_message:\n raise errors_impl.InvalidArgumentError(None, None, error_message)\n elif 'Unable to open table file' in error_message:\n raise errors_impl.DataLossError(None, None, error_message)\n elif 'Failed to find the saved tensor slices' in error_message or (\n 'not convertible to numpy dtype' in error_message):\n raise errors_impl.InternalError(None, None, error_message)\n else:\n raise errors_impl.OpError(None, None, error_message, errors_impl.UNKNOWN)\n\n\ndef get_variable_to_dtype_map(self):\n return {\n name: dtypes.DType(type_enum)\n for name, type_enum in self._GetVariableToDataTypeMap().items() # pylint: disable=protected-access\n }\n\nCheckpointReader.get_variable_to_dtype_map = get_variable_to_dtype_map\n\n\ndef has_tensor(self, tensor_str):\n return self._HasTensor(compat.as_bytes(tensor_str)) # pylint: disable=protected-access\n\nCheckpointReader.has_tensor = has_tensor\n\n\ndef get_tensor(self, tensor_str):\n \"\"\"Get the tensor from the Checkpoint object.\"\"\"\n try:\n return CheckpointReader.CheckpointReader_GetTensor(\n self, compat.as_bytes(tensor_str))\n # TODO(b/143319754): Remove the RuntimeError casting logic once we resolve the\n # issue with throwing python exceptions from C++.\n except RuntimeError as e:\n error_translator(e)\n\n\nCheckpointReader.get_tensor = get_tensor\n\n\n# Disable invalid name to keep backwards compatibility with that function.\n# It was previously exported from py_checkpoint_reader.i which did not conform\n# to pylint checks.\n# pylint: disable=invalid-name\n@tf_export(v1=['train.NewCheckpointReader'])\ndef NewCheckpointReader(filepattern):\n \"\"\"A function that returns a CheckPointReader.\n\n Args:\n filepattern: The filename.\n\n Returns:\n A CheckpointReader object.\n \"\"\"\n try:\n return CheckpointReader(compat.as_bytes(filepattern))\n # TODO(b/143319754): Remove the RuntimeError casting logic once we resolve the\n # issue with throwing python exceptions from C++.\n except RuntimeError as e:\n error_translator(e)\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\"\"\"A python interface for Grappler clusters.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport contextlib\n\nfrom tensorflow.core.framework import step_stats_pb2\nfrom tensorflow.core.grappler.costs import op_performance_data_pb2\nfrom tensorflow.core.protobuf import device_properties_pb2\nfrom tensorflow.python.grappler import _pywrap_tf_cluster as tf_cluster\n\n\nclass Cluster(object):\n \"\"\"Grappler Clusters.\"\"\"\n\n def __init__(self,\n allow_soft_placement=True,\n disable_detailed_stats=True,\n disable_timeline=True,\n devices=None):\n \"\"\"Creates a Cluster.\n\n Args:\n allow_soft_placement: If True, TF will automatically fix illegal\n placements instead of erroring out if the placement isn't legal.\n disable_detailed_stats: If True, detailed statistics will not be\n available.\n disable_timeline: If True, the timeline information will not be reported.\n devices: A list of devices of type device_properties_pb2.NamedDevice.\n If None, a device list will be created based on the spec of\n the local machine.\n \"\"\"\n self._tf_cluster = None\n self._generate_timeline = not disable_timeline\n\n if devices is None:\n self._tf_cluster = tf_cluster.TF_NewCluster(allow_soft_placement,\n disable_detailed_stats)\n else:\n devices_serialized = [device.SerializeToString() for device in devices]\n self._tf_cluster = tf_cluster.TF_NewVirtualCluster(devices_serialized)\n\n def Shutdown(self):\n if self._tf_cluster is not None:\n tf_cluster.TF_ShutdownCluster(self._tf_cluster)\n self._tf_cluster = None\n\n def __del__(self):\n self.Shutdown()\n\n @property\n def tf_cluster(self):\n return self._tf_cluster\n\n def ListDevices(self):\n \"\"\"Returns a list of available hardware devices.\"\"\"\n if self._tf_cluster is None:\n return []\n return [device_properties_pb2.NamedDevice.FromString(device)\n for device in tf_cluster.TF_ListDevices(self._tf_cluster)]\n\n def ListAvailableOps(self):\n \"\"\"Returns a list of all available operations (sorted alphabetically).\"\"\"\n return tf_cluster.TF_ListAvailableOps()\n\n def GetSupportedDevices(self, item):\n return tf_cluster.TF_GetSupportedDevices(self._tf_cluster, item.tf_item)\n\n def EstimatePerformance(self, device):\n return tf_cluster.TF_EstimatePerformance(device.SerializeToString())\n\n def MeasureCosts(self, item):\n \"\"\"Returns the cost of running the specified item.\n\n Args:\n item: The item for which to measure the costs.\n Returns: The triplet op_perfs, runtime, step_stats.\n \"\"\"\n op_perf_bytes_list, run_time, step_stats_bytes = tf_cluster.TF_MeasureCosts(\n item.tf_item, self._tf_cluster, self._generate_timeline)\n\n op_perfs = [op_performance_data_pb2.OpPerformance.FromString(op_perf_bytes)\n for op_perf_bytes in op_perf_bytes_list]\n return (op_perfs, run_time,\n step_stats_pb2.StepStats.FromString(step_stats_bytes))\n\n def DeterminePeakMemoryUsage(self, item):\n \"\"\"Returns a snapshot of the peak memory usage.\n\n Args:\n item: The item for which to measure the costs.\n Returns: A hashtable indexed by device name.\n \"\"\"\n return tf_cluster.TF_DeterminePeakMemoryUsage(item.tf_item,\n self._tf_cluster)\n\n\[email protected]\ndef Provision(allow_soft_placement=True,\n disable_detailed_stats=True,\n disable_timeline=True,\n devices=None):\n cluster = Cluster(allow_soft_placement, disable_detailed_stats,\n disable_timeline, devices)\n yield cluster\n cluster.Shutdown()\n", "# 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\"\"\"Tests for tf.layers.normalization.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\n\nimport numpy as np\n\nfrom tensorflow.core.protobuf import saver_pb2\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.keras.legacy_tf_layers import convolutional as conv_layers\nfrom tensorflow.python.keras.legacy_tf_layers import normalization as normalization_layers\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 random_ops\nfrom tensorflow.python.ops import variable_scope\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import test\nfrom tensorflow.python.training import gradient_descent\nfrom tensorflow.python.training import saver as saver_lib\n\n\n@test_util.run_v1_only('b/120545219')\nclass BNTest(test.TestCase):\n\n def _simple_model(self, image, fused, freeze_mode):\n output_channels, kernel_size = 2, 3\n conv = conv_layers.conv2d(\n image,\n output_channels,\n kernel_size,\n use_bias=False,\n kernel_initializer=init_ops.ones_initializer())\n bn_layer = normalization_layers.BatchNormalization(fused=fused)\n bn_layer._bessels_correction_test_only = False\n training = not freeze_mode\n bn = bn_layer.apply(conv, training=training)\n loss = math_ops.reduce_sum(math_ops.abs(bn))\n optimizer = gradient_descent.GradientDescentOptimizer(0.01)\n if not freeze_mode:\n update_ops = ops.get_collection(ops.GraphKeys.UPDATE_OPS)\n with ops.control_dependencies(update_ops):\n train_op = optimizer.minimize(loss)\n else:\n train_op = optimizer.minimize(loss)\n saver = saver_lib.Saver(write_version=saver_pb2.SaverDef.V2)\n return loss, train_op, saver\n\n def _train(self,\n checkpoint_path,\n shape,\n use_gpu,\n is_fused,\n restore=False,\n freeze_mode=False,\n dtype=dtypes.float32):\n ops.reset_default_graph()\n graph = ops.get_default_graph()\n with self.session(graph=graph, use_gpu=use_gpu) as sess:\n image = array_ops.placeholder(dtype=dtype, shape=shape)\n loss, train_op, saver = self._simple_model(image, is_fused, freeze_mode)\n if restore:\n saver.restore(sess, checkpoint_path)\n else:\n self.evaluate(variables.global_variables_initializer())\n np.random.seed(0)\n for _ in range(2):\n image_val = np.random.rand(*shape).astype(dtype.as_numpy_dtype)\n sess.run([loss, train_op], feed_dict={image: image_val})\n if restore:\n all_vars = ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES)\n all_vars_values = [var.eval() for var in all_vars]\n return all_vars_values\n else:\n saver.save(sess, checkpoint_path)\n\n def _infer(self, checkpoint_path, image_val, shape, use_gpu, is_fused):\n dtype = image_val.dtype\n ops.reset_default_graph()\n graph = ops.get_default_graph()\n with self.session(graph=graph, use_gpu=use_gpu) as sess:\n image = array_ops.placeholder(dtype=dtype, shape=shape)\n loss, _, saver = self._simple_model(image, is_fused, True)\n saver.restore(sess, checkpoint_path)\n loss_val = sess.run(loss, feed_dict={image: image_val})\n return loss_val\n\n def _trainEvalSequence(self, dtype, train1_use_gpu, train2_use_gpu,\n infer_use_gpu):\n batch, height, width, input_channels = 2, 4, 5, 3\n shape = [batch, height, width, input_channels]\n\n # Not all characters in a dtype string representation are allowed in\n # filenames in all operating systems. This map will sanitize these.\n dtype_to_valid_fn = {\n dtypes.float16: 'float16',\n dtypes.float32: 'float32',\n }\n checkpoint = os.path.join(\n self.get_temp_dir(), 'cp_%s_%s_%s_%s' % (\n dtype_to_valid_fn[dtype], train1_use_gpu, train2_use_gpu,\n infer_use_gpu))\n\n self._train(\n checkpoint,\n shape,\n use_gpu=train1_use_gpu,\n is_fused=True,\n restore=False,\n freeze_mode=False,\n dtype=dtype)\n\n train_vars = self._train(\n checkpoint,\n shape,\n use_gpu=train2_use_gpu,\n is_fused=True,\n restore=True,\n freeze_mode=False,\n dtype=dtype)\n\n np.random.seed(0)\n image_val = np.random.rand(batch, height, width, input_channels).astype(\n dtype.as_numpy_dtype)\n loss_val = self._infer(\n checkpoint, image_val, shape, use_gpu=infer_use_gpu, is_fused=True)\n\n return train_vars, loss_val\n\n def testHalfPrecision(self):\n ref_vars, ref_loss = self._trainEvalSequence(\n dtype=dtypes.float32,\n train1_use_gpu=True,\n train2_use_gpu=True,\n infer_use_gpu=True)\n\n self.assertEqual(len(ref_vars), 5)\n\n for train1_use_gpu in [True, False]:\n for train2_use_gpu in [True, False]:\n for infer_use_gpu in [True, False]:\n test_vars, test_loss = self._trainEvalSequence(\n dtypes.float16, train1_use_gpu, train2_use_gpu, infer_use_gpu)\n self.assertEqual(len(test_vars), 5)\n for test_var, ref_var in zip(test_vars, ref_vars):\n self.assertAllClose(test_var, ref_var, rtol=1.e-3, atol=1.e-3)\n self.assertAllClose(test_loss, ref_loss, rtol=1.e-3, atol=1.e-3)\n\n def _testCheckpoint(self, is_fused_checkpoint_a, is_fused_checkpoint_b,\n use_gpu_checkpoint_a, use_gpu_checkpoint_b,\n use_gpu_test_a, use_gpu_test_b, freeze_mode):\n batch, height, width, input_channels = 2, 4, 5, 3\n shape = [batch, height, width, input_channels]\n base_path = '%s_%s_%s_%s_%s_%s' % (is_fused_checkpoint_a,\n is_fused_checkpoint_b,\n use_gpu_checkpoint_a,\n use_gpu_checkpoint_b, use_gpu_test_a,\n use_gpu_test_b)\n\n checkpoint_path_a = os.path.join(self.get_temp_dir(),\n 'checkpoint_a_%s' % base_path)\n self._train(\n checkpoint_path_a,\n shape,\n use_gpu_checkpoint_a,\n is_fused_checkpoint_a,\n restore=False,\n freeze_mode=freeze_mode)\n checkpoint_path_b = os.path.join(self.get_temp_dir(),\n 'checkpoint_b_%s' % base_path)\n self._train(\n checkpoint_path_b,\n shape,\n use_gpu_checkpoint_b,\n is_fused_checkpoint_b,\n restore=False,\n freeze_mode=freeze_mode)\n\n vars_fused = self._train(\n checkpoint_path_a,\n shape,\n use_gpu_test_a,\n True,\n restore=True,\n freeze_mode=freeze_mode)\n vars_nonfused = self._train(\n checkpoint_path_b,\n shape,\n use_gpu_test_b,\n False,\n restore=True,\n freeze_mode=freeze_mode)\n self.assertEqual(len(vars_fused), 5)\n self.assertEqual(len(vars_nonfused), 5)\n for var_fused, var_nonfused in zip(vars_fused, vars_nonfused):\n self.assertAllClose(var_fused, var_nonfused, atol=1e-5)\n\n image_val = np.random.rand(batch, height, width,\n input_channels).astype(np.float32)\n loss_fused_val = self._infer(checkpoint_path_a, image_val, shape,\n use_gpu_test_a, True)\n loss_nonfused_val = self._infer(checkpoint_path_b, image_val, shape,\n use_gpu_test_b, False)\n self.assertAllClose(loss_fused_val, loss_nonfused_val, atol=1e-6, rtol=3e-4)\n\n def _testCheckpointCrossDevice(self, ckpt_a_fused, ckpt_a_use_gpu,\n ckpt_b_fused, ckpt_b_use_gpu):\n for use_gpu_test_a in [True, False]:\n for use_gpu_test_b in [True, False]:\n for freeze_mode in [True, False]:\n self._testCheckpoint(ckpt_a_fused, ckpt_a_use_gpu, ckpt_b_fused,\n ckpt_b_use_gpu, use_gpu_test_a, use_gpu_test_b,\n freeze_mode)\n\n def testCheckpointFusedCPUAndFusedGPU(self):\n self._testCheckpointCrossDevice(True, False, True, True)\n\n def testCheckpointFusedCPUAndFusedCPU(self):\n self._testCheckpointCrossDevice(True, False, True, False)\n\n def testCheckpointFusedGPUAndFusedGPU(self):\n self._testCheckpointCrossDevice(True, True, True, True)\n\n def testCheckpointNonFusedCPUAndNonFusedGPU(self):\n self._testCheckpointCrossDevice(False, False, False, True)\n\n def testCheckpointNonFusedCPUAndNonFusedCPU(self):\n self._testCheckpointCrossDevice(False, False, False, False)\n\n def testCheckpointNonFusedGPUAndNonFusedGPU(self):\n self._testCheckpointCrossDevice(False, True, False, True)\n\n def testCheckpointNonFusedGPUAndFusedGPU(self):\n self._testCheckpointCrossDevice(False, True, True, True)\n\n def testCheckpointNonFusedGPUAndFusedCPU(self):\n self._testCheckpointCrossDevice(False, True, True, False)\n\n def testCheckpointNonFusedCPUAndFusedCPU(self):\n self._testCheckpointCrossDevice(False, False, True, False)\n\n def testCreateBN(self):\n # Call layer.\n bn = normalization_layers.BatchNormalization(axis=1)\n inputs = random_ops.random_uniform((5, 4, 3), seed=1)\n training = array_ops.placeholder(dtype='bool')\n outputs = bn.apply(inputs, training=training)\n\n # Verify shape.\n self.assertListEqual(outputs.get_shape().as_list(), [5, 4, 3])\n\n # Verify layer attributes.\n self.assertEqual(len(bn.updates), 2)\n self.assertEqual(len(bn.variables), 4)\n self.assertEqual(len(bn.trainable_variables), 2)\n self.assertEqual(len(bn.non_trainable_variables), 2)\n\n # Test that updates were created and added to UPDATE_OPS.\n self.assertEqual(len(bn.updates), 2)\n self.assertListEqual(\n ops.get_collection(ops.GraphKeys.UPDATE_OPS), bn.updates)\n\n # Test that weights were created and added to TRAINABLE_VARIABLES.\n self.assertListEqual(\n ops.get_collection(ops.GraphKeys.TRAINABLE_VARIABLES),\n bn.trainable_variables)\n\n def testCreateFusedBNFloat16(self):\n # Call layer.\n bn = normalization_layers.BatchNormalization(axis=1, fused=True)\n inputs = random_ops.random_uniform(\n (5, 4, 3, 3), seed=1, dtype=dtypes.float16)\n training = array_ops.placeholder(dtype='bool')\n outputs = bn.apply(inputs, training=training)\n\n # Verify shape.\n self.assertListEqual(outputs.get_shape().as_list(), [5, 4, 3, 3])\n\n # Verify layer attributes.\n self.assertEqual(len(bn.updates), 2)\n self.assertEqual(len(bn.variables), 4)\n self.assertEqual(len(bn.trainable_variables), 2)\n self.assertEqual(len(bn.non_trainable_variables), 2)\n for var in bn.variables:\n self.assertTrue(var.dtype._is_ref_dtype)\n\n # Test that updates were created and added to UPDATE_OPS.\n self.assertEqual(len(bn.updates), 2)\n self.assertListEqual(\n ops.get_collection(ops.GraphKeys.UPDATE_OPS), bn.updates)\n\n # Test that weights were created and added to TRAINABLE_VARIABLES.\n self.assertListEqual(\n ops.get_collection(ops.GraphKeys.TRAINABLE_VARIABLES),\n bn.trainable_variables)\n\n def test3DInputAxis1(self):\n epsilon = 1e-3\n bn = normalization_layers.BatchNormalization(\n axis=1, epsilon=epsilon, momentum=0.9)\n inputs = variables.Variable(\n np.random.random((5, 4, 3)) + 100, dtype=dtypes.float32)\n training = array_ops.placeholder(dtype='bool')\n outputs = bn.apply(inputs, training=training)\n\n with self.cached_session() as sess:\n # Test training with placeholder learning phase.\n self.evaluate(variables.global_variables_initializer())\n\n np_gamma, np_beta = self.evaluate([bn.gamma, bn.beta])\n np_gamma = np.reshape(np_gamma, (1, 4, 1))\n np_beta = np.reshape(np_beta, (1, 4, 1))\n\n for _ in range(100):\n np_output, _, _ = sess.run([outputs] + bn.updates,\n feed_dict={training: True})\n # Verify that the axis is normalized during training.\n normed_np_output = ((np_output - epsilon) * np_gamma) + np_beta\n self.assertAlmostEqual(np.mean(normed_np_output), 0., places=1)\n self.assertAlmostEqual(np.std(normed_np_output), 1., places=1)\n\n # Verify that the statistics are updated during training.\n moving_mean, moving_var = self.evaluate(\n [bn.moving_mean, bn.moving_variance])\n np_inputs = self.evaluate(inputs)\n mean = np.mean(np_inputs, axis=(0, 2))\n std = np.std(np_inputs, axis=(0, 2))\n variance = np.square(std)\n self.assertAllClose(mean, moving_mean, atol=1e-2)\n self.assertAllClose(variance, moving_var, atol=1e-2)\n\n # Test inference with placeholder learning phase.\n np_output = sess.run(outputs, feed_dict={training: False})\n\n # Verify that the axis is normalized during inference.\n normed_np_output = ((np_output - epsilon) * np_gamma) + np_beta\n self.assertAlmostEqual(np.mean(normed_np_output), 0., places=1)\n self.assertAlmostEqual(np.std(normed_np_output), 1., places=1)\n\n def test3DInputAxis2(self):\n epsilon = 1e-3\n bn = normalization_layers.BatchNormalization(\n axis=2, epsilon=epsilon, momentum=0.9)\n inputs = variables.Variable(\n np.random.random((5, 4, 3)) + 100, dtype=dtypes.float32)\n training = array_ops.placeholder(dtype='bool')\n outputs = bn.apply(inputs, training=training)\n\n with self.cached_session() as sess:\n # Test training with placeholder learning phase.\n self.evaluate(variables.global_variables_initializer())\n np_gamma, np_beta = self.evaluate([bn.gamma, bn.beta])\n np_gamma = np.reshape(np_gamma, (1, 1, 3))\n np_beta = np.reshape(np_beta, (1, 1, 3))\n for _ in range(100):\n np_output, _, _ = sess.run([outputs] + bn.updates,\n feed_dict={training: True})\n # Verify that the axis is normalized during training.\n normed_np_output = ((np_output - epsilon) * np_gamma) + np_beta\n self.assertAlmostEqual(np.mean(normed_np_output), 0., places=1)\n self.assertAlmostEqual(np.std(normed_np_output), 1., places=1)\n\n # Verify that the statistics are updated during training.\n moving_mean, moving_var = self.evaluate(\n [bn.moving_mean, bn.moving_variance])\n np_inputs = self.evaluate(inputs)\n mean = np.mean(np_inputs, axis=(0, 1))\n std = np.std(np_inputs, axis=(0, 1))\n variance = np.square(std)\n self.assertAllClose(mean, moving_mean, atol=1e-2)\n self.assertAllClose(variance, moving_var, atol=1e-2)\n\n # Test inference with placeholder learning phase.\n np_output = sess.run(outputs, feed_dict={training: False})\n\n # Verify that the axis is normalized during inference.\n normed_np_output = ((np_output - epsilon) * np_gamma) + np_beta\n self.assertAlmostEqual(np.mean(normed_np_output), 0., places=1)\n self.assertAlmostEqual(np.std(normed_np_output), 1., places=1)\n\n def test4DInputAxis1(self):\n if test.is_gpu_available(cuda_only=True):\n epsilon = 1e-3\n bn = normalization_layers.BatchNormalization(\n axis=1, epsilon=epsilon, momentum=0.9)\n inputs = variables.Variable(\n np.random.random((5, 4, 3, 6)) + 100, dtype=dtypes.float32)\n training = array_ops.placeholder(dtype='bool')\n outputs = bn.apply(inputs, training=training)\n\n with self.session() as sess:\n # Test training with placeholder learning phase.\n self.evaluate(variables.global_variables_initializer())\n np_gamma, np_beta = self.evaluate([bn.gamma, bn.beta])\n np_gamma = np.reshape(np_gamma, (1, 4, 1, 1))\n np_beta = np.reshape(np_beta, (1, 4, 1, 1))\n for _ in range(100):\n np_output, _, _ = sess.run(\n [outputs] + bn.updates, feed_dict={training: True})\n # Verify that the axis is normalized during training.\n normed_np_output = ((np_output - epsilon) * np_gamma) + np_beta\n self.assertAlmostEqual(np.mean(normed_np_output), 0., places=1)\n self.assertAlmostEqual(np.std(normed_np_output), 1., places=1)\n\n # Verify that the statistics are updated during training.\n moving_mean, moving_var = self.evaluate(\n [bn.moving_mean, bn.moving_variance])\n np_inputs = self.evaluate(inputs)\n mean = np.mean(np_inputs, axis=(0, 2, 3))\n std = np.std(np_inputs, axis=(0, 2, 3))\n variance = np.square(std)\n self.assertAllClose(mean, moving_mean, atol=1e-2)\n self.assertAllClose(variance, moving_var, atol=1e-2)\n\n # Test inference with placeholder learning phase.\n np_output = sess.run(outputs, feed_dict={training: False})\n\n # Verify that the axis is normalized during inference.\n normed_np_output = ((np_output - epsilon) * np_gamma) + np_beta\n self.assertAlmostEqual(np.mean(normed_np_output), 0., places=1)\n self.assertAlmostEqual(np.std(normed_np_output), 1., places=1)\n\n def test4DInputAxis2(self):\n epsilon = 1e-3\n bn = normalization_layers.BatchNormalization(\n axis=2, epsilon=epsilon, momentum=0.9)\n inputs = variables.Variable(\n np.random.random((5, 4, 3, 6)) + 100, dtype=dtypes.float32)\n training = array_ops.placeholder(dtype='bool')\n outputs = bn.apply(inputs, training=training)\n\n with self.cached_session() as sess:\n # Test training with placeholder learning phase.\n self.evaluate(variables.global_variables_initializer())\n np_gamma, np_beta = self.evaluate([bn.gamma, bn.beta])\n np_gamma = np.reshape(np_gamma, (1, 1, 3, 1))\n np_beta = np.reshape(np_beta, (1, 1, 3, 1))\n for _ in range(100):\n np_output, _, _ = sess.run([outputs] + bn.updates,\n feed_dict={training: True})\n # Verify that the axis is normalized during training.\n normed_np_output = ((np_output - epsilon) * np_gamma) + np_beta\n self.assertAlmostEqual(np.mean(normed_np_output), 0., places=1)\n self.assertAlmostEqual(np.std(normed_np_output), 1., places=1)\n\n # Verify that the statistics are updated during training.\n moving_mean, moving_var = self.evaluate(\n [bn.moving_mean, bn.moving_variance])\n np_inputs = self.evaluate(inputs)\n mean = np.mean(np_inputs, axis=(0, 1, 3))\n std = np.std(np_inputs, axis=(0, 1, 3))\n variance = np.square(std)\n self.assertAllClose(mean, moving_mean, atol=1e-2)\n self.assertAllClose(variance, moving_var, atol=1e-2)\n\n # Test inference with placeholder learning phase.\n np_output = sess.run(outputs, feed_dict={training: False})\n\n # Verify that the axis is normalized during inference.\n normed_np_output = ((np_output - epsilon) * np_gamma) + np_beta\n self.assertAlmostEqual(np.mean(normed_np_output), 0., places=1)\n self.assertAlmostEqual(np.std(normed_np_output), 1., places=1)\n\n def test4DInputAxis3(self):\n epsilon = 1e-3\n bn = normalization_layers.BatchNormalization(\n axis=3, epsilon=epsilon, momentum=0.9)\n inputs = variables.Variable(\n np.random.random((5, 4, 3, 6)) + 100, dtype=dtypes.float32)\n training = array_ops.placeholder(dtype='bool')\n outputs = bn.apply(inputs, training=training)\n\n with self.cached_session() as sess:\n # Test training with placeholder learning phase.\n self.evaluate(variables.global_variables_initializer())\n np_gamma, np_beta = self.evaluate([bn.gamma, bn.beta])\n np_gamma = np.reshape(np_gamma, (1, 1, 1, 6))\n np_beta = np.reshape(np_beta, (1, 1, 1, 6))\n for _ in range(100):\n np_output, _, _ = sess.run([outputs] + bn.updates,\n feed_dict={training: True})\n # Verify that the axis is normalized during training.\n normed_np_output = ((np_output - epsilon) * np_gamma) + np_beta\n self.assertAlmostEqual(np.mean(normed_np_output), 0., places=1)\n self.assertAlmostEqual(np.std(normed_np_output), 1., places=1)\n\n # Verify that the statistics are updated during training.\n moving_mean, moving_var = self.evaluate(\n [bn.moving_mean, bn.moving_variance])\n np_inputs = self.evaluate(inputs)\n mean = np.mean(np_inputs, axis=(0, 1, 2))\n std = np.std(np_inputs, axis=(0, 1, 2))\n variance = np.square(std)\n self.assertAllClose(mean, moving_mean, atol=1e-2)\n self.assertAllClose(variance, moving_var, atol=1e-2)\n\n # Test inference with placeholder learning phase.\n np_output = sess.run(outputs, feed_dict={training: False})\n\n # Verify that the axis is normalized during inference.\n normed_np_output = ((np_output - epsilon) * np_gamma) + np_beta\n self.assertAlmostEqual(np.mean(normed_np_output), 0., places=1)\n self.assertAlmostEqual(np.std(normed_np_output), 1., places=1)\n\n def test4DInputAxis3Fused(self):\n epsilon = 1e-3\n bn = normalization_layers.BatchNormalization(\n axis=3, epsilon=epsilon, momentum=0.9, fused=True)\n inputs = variables.Variable(\n np.random.random((5, 4, 3, 6)) + 100, dtype=dtypes.float32)\n training = array_ops.placeholder(dtype='bool')\n outputs = bn.apply(inputs, training=training)\n\n with self.cached_session() as sess:\n # Test training with placeholder learning phase.\n self.evaluate(variables.global_variables_initializer())\n np_gamma, np_beta = self.evaluate([bn.gamma, bn.beta])\n np_gamma = np.reshape(np_gamma, (1, 1, 1, 6))\n np_beta = np.reshape(np_beta, (1, 1, 1, 6))\n for _ in range(100):\n np_output, _, _ = sess.run(\n [outputs] + bn.updates, feed_dict={training: True})\n # Verify that the axis is normalized during training.\n normed_np_output = ((np_output - epsilon) * np_gamma) + np_beta\n self.assertAlmostEqual(np.mean(normed_np_output), 0., places=1)\n self.assertAlmostEqual(np.std(normed_np_output), 1., places=1)\n\n # Verify that the statistics are updated during training.\n moving_mean, moving_var = self.evaluate(\n [bn.moving_mean, bn.moving_variance])\n np_inputs = self.evaluate(inputs)\n mean = np.mean(np_inputs, axis=(0, 1, 2))\n std = np.std(np_inputs, axis=(0, 1, 2))\n variance = np.square(std)\n self.assertAllClose(mean, moving_mean, atol=1e-2)\n self.assertAllClose(variance, moving_var, atol=1e-2)\n\n # Test inference with placeholder learning phase.\n np_output = sess.run(outputs, feed_dict={training: False})\n\n # Verify that the axis is normalized during inference.\n normed_np_output = ((np_output - epsilon) * np_gamma) + np_beta\n self.assertAlmostEqual(np.mean(normed_np_output), 0., places=1)\n self.assertAlmostEqual(np.std(normed_np_output), 1., places=1)\n\n def test4DInputAxis1Fused(self):\n if test.is_gpu_available(cuda_only=True):\n epsilon = 1e-3\n bn = normalization_layers.BatchNormalization(\n axis=1, epsilon=epsilon, momentum=0.9, fused=True)\n inputs = variables.Variable(\n np.random.random((5, 4, 3, 6)) + 100, dtype=dtypes.float32)\n training = array_ops.placeholder(dtype='bool')\n outputs = bn.apply(inputs, training=training)\n\n with self.cached_session() as sess:\n # Test training with placeholder learning phase.\n self.evaluate(variables.global_variables_initializer())\n np_gamma, np_beta = self.evaluate([bn.gamma, bn.beta])\n np_gamma = np.reshape(np_gamma, (1, 4, 1, 1))\n np_beta = np.reshape(np_beta, (1, 4, 1, 1))\n for _ in range(100):\n np_output, _, _ = sess.run(\n [outputs] + bn.updates, feed_dict={training: True})\n # Verify that the axis is normalized during training.\n normed_np_output = ((np_output - epsilon) * np_gamma) + np_beta\n self.assertAlmostEqual(np.mean(normed_np_output), 0., places=1)\n self.assertAlmostEqual(np.std(normed_np_output), 1., places=1)\n\n # Verify that the statistics are updated during training.\n moving_mean, moving_var = self.evaluate(\n [bn.moving_mean, bn.moving_variance])\n np_inputs = self.evaluate(inputs)\n mean = np.mean(np_inputs, axis=(0, 2, 3))\n std = np.std(np_inputs, axis=(0, 2, 3))\n variance = np.square(std)\n self.assertAllClose(mean, moving_mean, atol=1e-2)\n self.assertAllClose(variance, moving_var, atol=1e-2)\n\n # Test inference with placeholder learning phase.\n np_output = sess.run(outputs, feed_dict={training: False})\n\n # Verify that the axis is normalized during inference.\n normed_np_output = ((np_output - epsilon) * np_gamma) + np_beta\n self.assertAlmostEqual(np.mean(normed_np_output), 0., places=1)\n self.assertAlmostEqual(np.std(normed_np_output), 1., places=1)\n\n def testNegativeAxis(self):\n epsilon = 1e-3\n bn = normalization_layers.BatchNormalization(\n axis=-1, epsilon=epsilon, momentum=0.9)\n inputs = variables.Variable(\n np.random.random((5, 4, 3, 6)) + 100, dtype=dtypes.float32)\n training = array_ops.placeholder(dtype='bool')\n outputs = bn.apply(inputs, training=training)\n\n with self.cached_session() as sess:\n # Test training with placeholder learning phase.\n self.evaluate(variables.global_variables_initializer())\n np_gamma, np_beta = self.evaluate([bn.gamma, bn.beta])\n np_gamma = np.reshape(np_gamma, (1, 1, 1, 6))\n np_beta = np.reshape(np_beta, (1, 1, 1, 6))\n for _ in range(100):\n np_output, _, _ = sess.run([outputs] + bn.updates,\n feed_dict={training: True})\n\n # Verify that the axis is normalized during training.\n normed_np_output = ((np_output - epsilon) * np_gamma) + np_beta\n self.assertAlmostEqual(np.mean(normed_np_output), 0., places=1)\n self.assertAlmostEqual(np.std(normed_np_output), 1., places=1)\n\n # Verify that the statistics are updated during training.\n moving_mean, moving_var = self.evaluate(\n [bn.moving_mean, bn.moving_variance])\n np_inputs = self.evaluate(inputs)\n mean = np.mean(np_inputs, axis=(0, 1, 2))\n std = np.std(np_inputs, axis=(0, 1, 2))\n variance = np.square(std)\n self.assertAllClose(mean, moving_mean, atol=1e-2)\n self.assertAllClose(variance, moving_var, atol=1e-2)\n\n # Test inference with placeholder learning phase.\n np_output = sess.run(outputs, feed_dict={training: False})\n\n # Verify that the axis is normalized during inference.\n normed_np_output = ((np_output - epsilon) * np_gamma) + np_beta\n self.assertAlmostEqual(np.mean(normed_np_output), 0., places=1)\n self.assertAlmostEqual(np.std(normed_np_output), 1., places=1)\n\n def testBooleanLearningPhase(self):\n epsilon = 1e-3\n bn = normalization_layers.BatchNormalization(\n axis=-1, epsilon=epsilon, momentum=0.9)\n inputs = variables.Variable(\n np.random.random((5, 4, 3, 6)) + 100, dtype=dtypes.float32)\n outputs_training = bn.apply(inputs, training=True)\n outputs_infer = bn.apply(inputs, training=False)\n\n with self.cached_session() as sess:\n # Test training with placeholder learning phase.\n self.evaluate(variables.global_variables_initializer())\n np_gamma, np_beta = self.evaluate([bn.gamma, bn.beta])\n np_gamma = np.reshape(np_gamma, (1, 1, 1, 6))\n np_beta = np.reshape(np_beta, (1, 1, 1, 6))\n for _ in range(100):\n np_output, _, _ = sess.run([outputs_training] + bn.updates)\n # Verify that the axis is normalized during training.\n normed_np_output = ((np_output - epsilon) * np_gamma) + np_beta\n self.assertAlmostEqual(np.mean(normed_np_output), 0., places=2)\n self.assertAlmostEqual(np.std(normed_np_output), 1., places=1)\n\n # Verify that the statistics are updated during training.\n moving_mean, moving_var = self.evaluate(\n [bn.moving_mean, bn.moving_variance])\n np_inputs = self.evaluate(inputs)\n mean = np.mean(np_inputs, axis=(0, 1, 2))\n std = np.std(np_inputs, axis=(0, 1, 2))\n variance = np.square(std)\n self.assertAllClose(mean, moving_mean, atol=1e-2)\n self.assertAllClose(variance, moving_var, atol=1e-2)\n\n # Test inference with placeholder learning phase.\n np_output = self.evaluate(outputs_infer)\n\n # Verify that the axis is normalized during inference.\n normed_np_output = ((np_output - epsilon) * np_gamma) + np_beta\n self.assertAlmostEqual(np.mean(normed_np_output), 0., places=1)\n self.assertAlmostEqual(np.std(normed_np_output), 1., places=1)\n\n def testFunctionalNoReuse(self):\n inputs = variables.Variable(\n np.random.random((5, 4, 3, 6)), dtype=dtypes.float32)\n epsilon = 1e-3\n training = array_ops.placeholder(dtype='bool')\n outputs = normalization_layers.batch_norm(\n inputs,\n axis=-1,\n momentum=0.9,\n epsilon=epsilon,\n training=training,\n name='bn')\n\n updates = ops.get_collection(ops.GraphKeys.UPDATE_OPS)\n all_vars = dict([(v.name, v) for v in variables.global_variables()])\n moving_mean = all_vars['bn/moving_mean:0']\n moving_variance = all_vars['bn/moving_variance:0']\n beta = all_vars['bn/beta:0']\n gamma = all_vars['bn/gamma:0']\n\n with self.cached_session() as sess:\n # Test training with placeholder learning phase.\n self.evaluate(variables.global_variables_initializer())\n np_gamma, np_beta = self.evaluate([gamma, beta])\n np_gamma = np.reshape(np_gamma, (1, 1, 1, 6))\n np_beta = np.reshape(np_beta, (1, 1, 1, 6))\n for _ in range(100):\n np_output, _, _ = sess.run([outputs] + updates,\n feed_dict={training: True})\n # Verify that the axis is normalized during training.\n normed_np_output = ((np_output - epsilon) * np_gamma) + np_beta\n self.assertAlmostEqual(np.mean(normed_np_output), 0., places=1)\n self.assertAlmostEqual(np.std(normed_np_output), 1., places=1)\n\n # Verify that the statistics are updated during training.\n np_moving_mean, np_moving_var = self.evaluate(\n [moving_mean, moving_variance])\n np_inputs = self.evaluate(inputs)\n np_mean = np.mean(np_inputs, axis=(0, 1, 2))\n np_std = np.std(np_inputs, axis=(0, 1, 2))\n np_variance = np.square(np_std)\n self.assertAllClose(np_mean, np_moving_mean, atol=1e-2)\n self.assertAllClose(np_variance, np_moving_var, atol=1e-2)\n\n # Test inference with placeholder learning phase.\n np_output = sess.run(outputs, feed_dict={training: False})\n\n # Verify that the axis is normalized during inference.\n normed_np_output = ((np_output - epsilon) * np_gamma) + np_beta\n self.assertAlmostEqual(np.mean(normed_np_output), 0., places=1)\n self.assertAlmostEqual(np.std(normed_np_output), 1., places=1)\n\n def testFunctionalReuse(self):\n inputs1 = variables.Variable(\n np.random.random((5, 4, 3, 6)), dtype=dtypes.float32)\n inputs2 = variables.Variable(\n np.random.random((5, 4, 3, 6)), dtype=dtypes.float32)\n epsilon = 1e-3\n training = array_ops.placeholder(dtype='bool')\n _ = normalization_layers.batch_norm(\n inputs1,\n axis=-1,\n momentum=0.9,\n epsilon=epsilon,\n training=training,\n name='bn')\n outputs2 = normalization_layers.batch_norm(\n inputs2,\n axis=-1,\n momentum=0.9,\n epsilon=epsilon,\n training=training,\n name='bn',\n reuse=True)\n\n # Last 2 update ops\n updates = ops.get_collection(ops.GraphKeys.UPDATE_OPS)[-2:]\n all_vars = dict([(v.name, v) for v in variables.global_variables()])\n moving_mean = all_vars['bn/moving_mean:0']\n moving_variance = all_vars['bn/moving_variance:0']\n beta = all_vars['bn/beta:0']\n gamma = all_vars['bn/gamma:0']\n\n with self.cached_session() as sess:\n # Test training with placeholder learning phase.\n self.evaluate(variables.global_variables_initializer())\n for _ in range(100):\n np_output, _, _ = sess.run([outputs2] + updates,\n feed_dict={training: True})\n\n # Verify that the statistics are updated during training.\n np_moving_mean, np_moving_var = self.evaluate(\n [moving_mean, moving_variance])\n np_inputs = self.evaluate(inputs2)\n np_mean = np.mean(np_inputs, axis=(0, 1, 2))\n np_std = np.std(np_inputs, axis=(0, 1, 2))\n np_variance = np.square(np_std)\n self.assertAllClose(np_mean, np_moving_mean, atol=1e-2)\n self.assertAllClose(np_variance, np_moving_var, atol=1e-2)\n\n # Verify that the axis is normalized during training.\n np_gamma, np_beta = self.evaluate([gamma, beta])\n np_gamma = np.reshape(np_gamma, (1, 1, 1, 6))\n np_beta = np.reshape(np_beta, (1, 1, 1, 6))\n normed_np_output = ((np_output - epsilon) * np_gamma) + np_beta\n self.assertAlmostEqual(np.mean(normed_np_output), 0., places=2)\n self.assertAlmostEqual(np.std(normed_np_output), 1., places=1)\n\n # Test inference with placeholder learning phase.\n np_output = sess.run(outputs2, feed_dict={training: False})\n\n # Verify that the axis is normalized during inference.\n normed_np_output = ((np_output - epsilon) * np_gamma) + np_beta\n self.assertAlmostEqual(np.mean(normed_np_output), 0., places=2)\n self.assertAlmostEqual(np.std(normed_np_output), 1., places=1)\n\n def testFunctionalReuseFromScope(self):\n inputs = variables.Variable(\n np.random.random((5, 4, 3, 6)), dtype=dtypes.float32)\n epsilon = 1e-3\n training = array_ops.placeholder(dtype='bool')\n with variable_scope.variable_scope('scope'):\n _ = normalization_layers.batch_norm(\n inputs, axis=-1, momentum=0.9, epsilon=epsilon, training=training)\n self.assertEqual(len(variables.global_variables()), 5)\n with variable_scope.variable_scope('scope', reuse=True):\n _ = normalization_layers.batch_norm(\n inputs, axis=-1, momentum=0.9, epsilon=epsilon, training=training)\n self.assertEqual(len(variables.global_variables()), 5)\n\n def testNoCenter(self):\n bn = normalization_layers.BatchNormalization(axis=1, center=False)\n inputs = random_ops.random_uniform((5, 4, 3), seed=1)\n training = array_ops.placeholder(dtype='bool')\n outputs = bn.apply(inputs, training=training)\n\n # Verify shape.\n self.assertListEqual(outputs.get_shape().as_list(), [5, 4, 3])\n\n # Verify layer attributes.\n self.assertEqual(len(bn.updates), 2)\n self.assertEqual(len(bn.variables), 3)\n self.assertEqual(len(bn.trainable_variables), 1)\n self.assertEqual(len(bn.non_trainable_variables), 2)\n\n def testNoScale(self):\n bn = normalization_layers.BatchNormalization(axis=1, scale=False)\n inputs = random_ops.random_uniform((5, 4, 3), seed=1)\n training = array_ops.placeholder(dtype='bool')\n outputs = bn.apply(inputs, training=training)\n\n # Verify shape.\n self.assertListEqual(outputs.get_shape().as_list(), [5, 4, 3])\n\n # Verify layer attributes.\n self.assertEqual(len(bn.updates), 2)\n self.assertEqual(len(bn.variables), 3)\n self.assertEqual(len(bn.trainable_variables), 1)\n self.assertEqual(len(bn.non_trainable_variables), 2)\n\n def testRegularizers(self):\n reg = lambda x: 0.1 * math_ops.reduce_sum(x)\n bn = normalization_layers.BatchNormalization(axis=1, beta_regularizer=reg)\n inputs = random_ops.random_uniform((5, 4, 3), seed=1)\n training = array_ops.placeholder(dtype='bool')\n _ = bn.apply(inputs, training=training)\n self.assertEqual(len(bn.losses), 1)\n\n bn = normalization_layers.BatchNormalization(axis=1, gamma_regularizer=reg)\n inputs = random_ops.random_uniform((5, 4, 3), seed=1)\n training = array_ops.placeholder(dtype='bool')\n _ = bn.apply(inputs, training=training)\n self.assertEqual(len(bn.losses), 1)\n\n def testConstraints(self):\n g_constraint = lambda x: x / math_ops.reduce_sum(x)\n b_constraint = lambda x: x / math_ops.reduce_max(x)\n bn = normalization_layers.BatchNormalization(axis=1,\n gamma_constraint=g_constraint,\n beta_constraint=b_constraint)\n inputs = random_ops.random_uniform((5, 4, 3), seed=1)\n bn(inputs)\n self.assertEqual(bn.gamma_constraint, g_constraint)\n self.assertEqual(bn.beta_constraint, b_constraint)\n\n def testRenorm(self):\n shape = (4, 3)\n xt = array_ops.placeholder(dtypes.float32, shape)\n momentum = 0.99\n renorm_momentum = 0.8\n rmax = 1.1\n rmin = 0.9\n dmax = 0.1\n gamma = 2.\n beta = 3.\n epsilon = 0.001\n bn = normalization_layers.BatchNormalization(\n axis=1,\n gamma_initializer=init_ops.constant_initializer(gamma),\n beta_initializer=init_ops.constant_initializer(beta),\n epsilon=epsilon,\n momentum=momentum,\n renorm=True,\n renorm_clipping={'rmax': rmax, 'rmin': rmin, 'dmax': dmax},\n renorm_momentum=renorm_momentum)\n training = array_ops.placeholder(dtypes.bool)\n yt = bn.apply(xt, training=training)\n\n moving_mean = 0.\n moving_stddev = 1.\n renorm_mean = 0.\n renorm_stddev = 1.\n with self.session() as sess:\n self.evaluate(variables.global_variables_initializer())\n for _ in range(5):\n x = np.random.random(shape)\n\n mean = x.mean(0)\n variance = x.var(0)\n stddev = np.sqrt(variance + epsilon)\n r = (stddev / renorm_stddev).clip(rmin, rmax)\n d = ((mean - renorm_mean) / renorm_stddev).clip(-dmax, dmax)\n y_train = ((x - mean) / stddev * r + d) * gamma + beta\n renorm_mean += (mean - renorm_mean) * (1. - renorm_momentum)\n renorm_stddev += (stddev - renorm_stddev) * (1. - renorm_momentum)\n moving_mean += (mean - moving_mean) * (1. - momentum)\n moving_stddev += (stddev - moving_stddev) * (1. - momentum)\n\n y_test = ((x - moving_mean) /\n (moving_stddev * moving_stddev)**0.5 * gamma) + beta\n\n yt_val_train, _, _ = sess.run([yt] + bn.updates,\n feed_dict={xt: x, training: True})\n yt_val_test, _, _ = sess.run([yt] + bn.updates,\n feed_dict={xt: x, training: False})\n\n self.assertAllClose(y_train, yt_val_train, atol=1e-5)\n self.assertAllClose(y_test, yt_val_test, atol=1e-5)\n\n def testRenormNoClippingSameMomentumGivesSameTestTrain(self):\n shape = (4, 3)\n xt = array_ops.placeholder(dtypes.float32, shape)\n momentum = 0.9\n renorm_momentum = 0.9\n gamma = 2.\n beta = 3.\n epsilon = 0.001\n bn = normalization_layers.BatchNormalization(\n axis=1,\n gamma_initializer=init_ops.constant_initializer(gamma),\n beta_initializer=init_ops.constant_initializer(beta),\n epsilon=epsilon,\n momentum=momentum,\n renorm=True,\n renorm_clipping=None,\n renorm_momentum=momentum)\n training = array_ops.placeholder(dtypes.bool)\n yt = bn.apply(xt, training=training)\n moving_mean = 0.\n moving_stddev = 1.\n renorm_mean = 0.\n renorm_stddev = 1.\n with self.session() as sess:\n self.evaluate(variables.global_variables_initializer())\n for step in range(6):\n x = np.random.random(shape)\n\n mean = x.mean(0)\n variance = x.var(0)\n stddev = np.sqrt(variance + epsilon)\n r = (stddev / renorm_stddev)\n d = ((mean - renorm_mean) / renorm_stddev)\n y_test = ((x - moving_mean) /\n (moving_stddev * moving_stddev)**0.5 * gamma) + beta\n y_train = ((x - mean) / stddev * r + d) * gamma + beta\n renorm_mean += (mean - renorm_mean) * (1. - renorm_momentum)\n renorm_stddev += (stddev - renorm_stddev) * (1. - renorm_momentum)\n moving_mean += (mean - moving_mean) * (1. - momentum)\n moving_stddev += (stddev - moving_stddev) * (1. - momentum)\n\n # Compute test values first, before the train mode updates the moving\n # averages.\n yt_val_test, _, _ = sess.run([yt] + bn.updates,\n feed_dict={xt: x, training: False})\n yt_val_train, _, _ = sess.run([yt] + bn.updates,\n feed_dict={xt: x, training: True})\n\n # Due to initialization inconsistencies, values may not be identical\n # on the first iteration (but shouldn't be different by much more than\n # epsilon). After the first iteration they should be identical.\n atol = epsilon * 1.5 if step == 0 else 1e-5\n self.assertAllClose(y_train, yt_val_train, atol=atol)\n self.assertAllClose(y_test, yt_val_test, atol=atol)\n self.assertAllClose(yt_val_train, yt_val_test, atol=atol)\n\n def testAdjustment(self):\n shape = (4, 3)\n xt = array_ops.placeholder(dtypes.float32, shape)\n momentum = 0.99\n gamma = 2.\n beta = 3.\n epsilon = 0.001\n adjust_scale = random_ops.random_uniform(shape[-1:], 0.5, 1.5)\n adjust_bias = random_ops.random_uniform(shape[-1:], -.2, .2)\n bn = normalization_layers.BatchNormalization(\n axis=1,\n gamma_initializer=init_ops.constant_initializer(gamma),\n beta_initializer=init_ops.constant_initializer(beta),\n epsilon=epsilon,\n momentum=momentum,\n adjustment=lambda _: (adjust_scale, adjust_bias))\n training = array_ops.placeholder(dtypes.bool)\n yt = bn.apply(xt, training=training)\n\n moving_mean = 0.\n moving_variance = 1.\n with self.session() as sess:\n self.evaluate(variables.global_variables_initializer())\n for _ in range(5):\n x = np.random.random(shape)\n yt_val_train, adj_scale_val, adj_bias_val = sess.run(\n [yt, adjust_scale, adjust_bias] + bn.updates,\n feed_dict={xt: x, training: True})[:3]\n yt_val_test = sess.run([yt] + bn.updates,\n feed_dict={xt: x, training: False})[0]\n\n mean = x.mean(0)\n variance = x.var(0)\n y_train = (((x - mean) / (variance + epsilon) ** 0.5) * adj_scale_val +\n adj_bias_val) * gamma + beta\n moving_mean += (mean - moving_mean) * (1. - momentum)\n moving_variance += (variance - moving_variance) * (1. - momentum)\n\n y_test = ((x - moving_mean) / (moving_variance + epsilon) ** 0.5 *\n gamma) + beta\n\n self.assertAllClose(y_train, yt_val_train, atol=1e-5)\n self.assertAllClose(y_test, yt_val_test, atol=1e-5)\n\n def testRenormWithAdjustment(self):\n shape = (4, 3)\n xt = array_ops.placeholder(dtypes.float32, shape)\n momentum = 0.99\n renorm_momentum = 0.8\n rmax = 1.1\n rmin = 0.9\n dmax = 0.1\n gamma = 2.\n beta = 3.\n epsilon = 0.001\n adjust_scale = random_ops.random_uniform(shape[-1:], 0.5, 1.5)\n adjust_bias = random_ops.random_uniform(shape[-1:], -.2, .2)\n bn = normalization_layers.BatchNormalization(\n axis=1,\n gamma_initializer=init_ops.constant_initializer(gamma),\n beta_initializer=init_ops.constant_initializer(beta),\n epsilon=epsilon,\n momentum=momentum,\n renorm=True,\n renorm_clipping={'rmax': rmax, 'rmin': rmin, 'dmax': dmax},\n renorm_momentum=renorm_momentum,\n adjustment=lambda _: (adjust_scale, adjust_bias))\n training = array_ops.placeholder(dtypes.bool)\n yt = bn.apply(xt, training=training)\n\n moving_mean = 0.\n moving_stddev = 1.\n renorm_mean = 0.\n renorm_stddev = 1.\n with self.session() as sess:\n self.evaluate(variables.global_variables_initializer())\n for _ in range(5):\n x = np.random.random(shape)\n yt_val_train, adj_scale_val, adj_bias_val = sess.run(\n [yt, adjust_scale, adjust_bias] + bn.updates,\n feed_dict={xt: x, training: True})[:3]\n yt_val_test = sess.run([yt] + bn.updates,\n feed_dict={xt: x, training: False})[0]\n\n mean = x.mean(0)\n variance = x.var(0)\n stddev = np.sqrt(variance + epsilon)\n r = (stddev / renorm_stddev).clip(rmin, rmax)\n d = ((mean - renorm_mean) / renorm_stddev).clip(-dmax, dmax)\n y_train = (((x - mean) / stddev * r + d) * adj_scale_val +\n adj_bias_val) * gamma + beta\n renorm_mean += (mean - renorm_mean) * (1. - renorm_momentum)\n renorm_stddev += (stddev - renorm_stddev) * (1. - renorm_momentum)\n moving_mean += (mean - moving_mean) * (1. - momentum)\n moving_stddev += (stddev - moving_stddev) * (1. - momentum)\n\n y_test = ((x - moving_mean) /\n (moving_stddev * moving_stddev)**0.5 * gamma) + beta\n\n self.assertAllClose(y_train, yt_val_train, atol=1e-5)\n self.assertAllClose(y_test, yt_val_test, atol=1e-5)\n\n def testGhostBNNegativeVirtualBatch(self):\n shape = [6, 5, 4, 3]\n inp = random_ops.random_uniform(shape, seed=1)\n\n with self.assertRaises(ValueError):\n normalization_layers.batch_normalization(\n inp, virtual_batch_size=-1)\n\n def testGhostBNVirtualBatchFull(self):\n shape = [6, 5, 4, 3]\n inp = random_ops.random_uniform(shape, seed=1)\n out1 = normalization_layers.batch_normalization(inp)\n out2 = normalization_layers.batch_normalization(\n inp, virtual_batch_size=6)\n\n self.assertListEqual(\n out1.shape.as_list(), out2.shape.as_list())\n\n with self.session() as sess:\n self.evaluate(variables.global_variables_initializer())\n\n x = np.random.random(shape)\n y1, y2 = sess.run([out1, out2], feed_dict={inp: x})\n\n self.assertAllClose(y1, y2, atol=1e-5)\n\n def testGhostBNInputOutputShapesMatch(self):\n shape = [6, 4, 3]\n inp = random_ops.random_uniform(shape, seed=1)\n out = normalization_layers.batch_normalization(\n inp, virtual_batch_size=3)\n self.assertListEqual(out.shape.as_list(), shape)\n\n def testGhostBNUnknownBatchSize(self):\n np_shape = [10, 5, 4]\n tf_shape = [None, 5, 4]\n inp = array_ops.placeholder(dtypes.float32, tf_shape)\n out = normalization_layers.batch_normalization(\n inp, virtual_batch_size=2)\n\n with self.session() as sess:\n self.evaluate(variables.global_variables_initializer())\n\n x = np.random.random(np_shape)\n y = sess.run(out, feed_dict={inp: x})\n\n self.assertListEqual(list(y.shape), np_shape)\n\n def testGhostBN2Dims(self):\n shape = [6, 2]\n virtual_batch_size = 3\n beta = 2.\n gamma = 3.\n momentum = 0.8\n epsilon = 1e-3\n moving_means = np.zeros([2, 2], dtype=np.float32)\n moving_vars = np.ones([2, 2], dtype=np.float32)\n\n inp = array_ops.placeholder(dtypes.float32, shape)\n is_training = array_ops.placeholder(dtypes.bool)\n bn = normalization_layers.BatchNormalization(\n momentum=momentum,\n epsilon=epsilon,\n beta_initializer=init_ops.constant_initializer(beta),\n gamma_initializer=init_ops.constant_initializer(gamma),\n virtual_batch_size=virtual_batch_size)\n out = bn.apply(inp, training=is_training)\n ghost_shape = ([virtual_batch_size,\n shape[0] // virtual_batch_size,\n shape[1]])\n\n with self.session() as sess:\n self.evaluate(variables.global_variables_initializer())\n for _ in range(5):\n x = np.random.random(shape)\n\n sub_batched = np.reshape(x, ghost_shape)\n means = np.mean(sub_batched, axis=0, keepdims=True)\n variances = np.var(sub_batched, axis=0, keepdims=True)\n\n avg_means = np.mean(means, axis=1, keepdims=True)\n avg_variances = np.mean(variances, axis=1, keepdims=True)\n\n moving_means = moving_means * momentum + avg_means * (1. - momentum)\n moving_vars = moving_vars * momentum + avg_variances * (1. - momentum)\n\n y_train = ((sub_batched - means) /\n (variances + epsilon) ** 0.5 * gamma) + beta\n y_test = ((sub_batched - moving_means) /\n (moving_vars + epsilon) ** 0.5 * gamma) + beta\n\n y_train = np.reshape(y_train, shape)\n y_test = np.reshape(y_test, shape)\n\n y_val_train, _, _ = sess.run([out] + bn.updates,\n feed_dict={inp: x, is_training: True})\n y_val_test = sess.run(out, feed_dict={inp: x, is_training: False})\n\n self.assertAllClose(y_train, y_val_train, atol=1e-5)\n self.assertAllClose(y_test, y_val_test, atol=1e-5)\n\n def testGhostBN4DimsAxis3(self):\n shape = [6, 10, 10, 3]\n virtual_batch_size = 2\n beta = 2.\n gamma = 3.\n momentum = 0.8\n epsilon = 1e-3\n moving_means = np.zeros([1, 1, 1, 1, 3], dtype=np.float32)\n moving_vars = np.ones([1, 1, 1, 1, 3], dtype=np.float32)\n\n inp = array_ops.placeholder(dtypes.float32, shape)\n is_training = array_ops.placeholder(dtypes.bool)\n bn = normalization_layers.BatchNormalization(\n axis=3,\n momentum=momentum,\n epsilon=epsilon,\n beta_initializer=init_ops.constant_initializer(beta),\n gamma_initializer=init_ops.constant_initializer(gamma),\n virtual_batch_size=virtual_batch_size)\n out = bn.apply(inp, training=is_training)\n ghost_shape = ([virtual_batch_size, shape[0] // virtual_batch_size] +\n shape[1:])\n\n with self.session() as sess:\n self.evaluate(variables.global_variables_initializer())\n for _ in range(5):\n x = np.random.random(shape)\n\n sub_batched = np.reshape(x, ghost_shape)\n means = np.mean(sub_batched, axis=(0, 2, 3), keepdims=True)\n variances = np.var(sub_batched, axis=(0, 2, 3), keepdims=True)\n\n avg_means = np.mean(means, axis=1, keepdims=True)\n avg_variances = np.mean(variances, axis=1, keepdims=True)\n\n moving_means = moving_means * momentum + avg_means * (1. - momentum)\n moving_vars = moving_vars * momentum + avg_variances * (1. - momentum)\n\n y_train = ((sub_batched - means) /\n (variances + epsilon) ** 0.5 * gamma) + beta\n y_test = ((sub_batched - moving_means) /\n (moving_vars + epsilon) ** 0.5 * gamma) + beta\n\n y_train = np.reshape(y_train, shape)\n y_test = np.reshape(y_test, shape)\n\n y_val_train, _, _ = sess.run([out] + bn.updates,\n feed_dict={inp: x, is_training: True})\n y_val_test = sess.run(out, feed_dict={inp: x, is_training: False})\n\n self.assertAllClose(y_train, y_val_train, atol=1e-2)\n self.assertAllClose(y_test, y_val_test, atol=1e-2)\n\n def testGhostBN4DimsAxis1(self):\n shape = [6, 3, 10, 10]\n virtual_batch_size = 2\n beta = 2.\n gamma = 3.\n momentum = 0.8\n epsilon = 1e-3\n moving_means = np.zeros([1, 1, 3, 1, 1], dtype=np.float32)\n moving_vars = np.ones([1, 1, 3, 1, 1], dtype=np.float32)\n\n inp = array_ops.placeholder(dtypes.float32, shape)\n is_training = array_ops.placeholder(dtypes.bool)\n bn = normalization_layers.BatchNormalization(\n axis=1,\n momentum=momentum,\n epsilon=epsilon,\n beta_initializer=init_ops.constant_initializer(beta),\n gamma_initializer=init_ops.constant_initializer(gamma),\n virtual_batch_size=virtual_batch_size,\n fused=False) # NCHW is unsupported by CPU fused batch norm\n out = bn.apply(inp, training=is_training)\n ghost_shape = ([virtual_batch_size, shape[0] // virtual_batch_size] +\n shape[1:])\n\n with self.session() as sess:\n self.evaluate(variables.global_variables_initializer())\n for _ in range(5):\n x = np.random.random(shape)\n\n sub_batched = np.reshape(x, ghost_shape)\n means = np.mean(sub_batched, axis=(0, 3, 4), keepdims=True)\n variances = np.var(sub_batched, axis=(0, 3, 4), keepdims=True)\n\n avg_means = np.mean(means, axis=1, keepdims=True)\n avg_variances = np.mean(variances, axis=1, keepdims=True)\n\n moving_means = moving_means * momentum + avg_means * (1. - momentum)\n moving_vars = moving_vars * momentum + avg_variances * (1. - momentum)\n\n y_train = ((sub_batched - means) /\n (variances + epsilon) ** 0.5 * gamma) + beta\n y_test = ((sub_batched - moving_means) /\n (moving_vars + epsilon) ** 0.5 * gamma) + beta\n\n y_train = np.reshape(y_train, shape)\n y_test = np.reshape(y_test, shape)\n\n y_val_train, _, _ = sess.run([out] + bn.updates,\n feed_dict={inp: x, is_training: True})\n y_val_test = sess.run(out, feed_dict={inp: x, is_training: False})\n\n self.assertAllClose(y_train, y_val_train, atol=1e-2)\n self.assertAllClose(y_test, y_val_test, atol=1e-2)\n\n def testMultiAxisInvalid(self):\n shape = [6, 5, 4, 3]\n inp = random_ops.random_uniform(shape, seed=1)\n\n with self.assertRaises(ValueError):\n normalization_layers.batch_normalization(\n inp, axis=[1, 4]) # out of bounds\n\n with self.assertRaises(ValueError):\n normalization_layers.batch_normalization(\n inp, axis=[-5, 1]) # out of bounds\n\n with self.assertRaises(ValueError):\n normalization_layers.batch_normalization(\n inp, axis=[1, 2, 1]) # duplicate\n\n def test3DInputMultiAxis12(self):\n epsilon = 1e-3\n bn = normalization_layers.BatchNormalization(\n axis=[1, 2], epsilon=epsilon, momentum=0.9)\n inputs = variables.Variable(\n np.random.random((5, 4, 3)) + 100, dtype=dtypes.float32)\n training = array_ops.placeholder(dtype='bool')\n outputs = bn.apply(inputs, training=training)\n\n with self.cached_session() as sess:\n # Test training with placeholder learning phase.\n self.evaluate(variables.global_variables_initializer())\n\n np_gamma, np_beta = self.evaluate([bn.gamma, bn.beta])\n\n for _ in range(100):\n np_output, _, _ = sess.run([outputs] + bn.updates,\n feed_dict={training: True})\n # Verify that the axis is normalized during training.\n normed_np_output = ((np_output - epsilon) * np_gamma) + np_beta\n self.assertAlmostEqual(np.mean(normed_np_output), 0., places=1)\n self.assertAlmostEqual(np.std(normed_np_output), 1., places=1)\n\n # Verify that the statistics are updated during training.\n moving_mean, moving_var = self.evaluate(\n [bn.moving_mean, bn.moving_variance])\n np_inputs = self.evaluate(inputs)\n mean = np.mean(np_inputs, axis=0, keepdims=True)\n std = np.std(np_inputs, axis=0, keepdims=True)\n variance = np.square(std)\n self.assertAllClose(mean, moving_mean, atol=1e-2)\n self.assertAllClose(variance, moving_var, atol=1e-2)\n\n # Test inference with placeholder learning phase.\n np_output = sess.run(outputs, feed_dict={training: False})\n\n # Verify that the axis is normalized during inference.\n normed_np_output = ((np_output - epsilon) * np_gamma) + np_beta\n self.assertAlmostEqual(np.mean(normed_np_output), 0., places=1)\n self.assertAlmostEqual(np.std(normed_np_output), 1., places=1)\n\n def test5DInputMultiAxis123(self):\n epsilon = 1e-3\n bn = normalization_layers.BatchNormalization(\n axis=[1, 2, 3], epsilon=epsilon, momentum=0.9)\n inputs = variables.Variable(\n np.random.random((5, 3, 4, 4, 3)) + 100, dtype=dtypes.float32)\n training = array_ops.placeholder(dtype='bool')\n outputs = bn.apply(inputs, training=training)\n\n with self.cached_session() as sess:\n # Test training with placeholder learning phase.\n self.evaluate(variables.global_variables_initializer())\n\n np_gamma, np_beta = self.evaluate([bn.gamma, bn.beta])\n\n for _ in range(100):\n np_output, _, _ = sess.run([outputs] + bn.updates,\n feed_dict={training: True})\n # Verify that the axis is normalized during training.\n normed_np_output = ((np_output - epsilon) * np_gamma) + np_beta\n self.assertAlmostEqual(np.mean(normed_np_output), 0., places=1)\n self.assertAlmostEqual(np.std(normed_np_output), 1., places=1)\n\n # Verify that the statistics are updated during training.\n moving_mean, moving_var = self.evaluate(\n [bn.moving_mean, bn.moving_variance])\n np_inputs = self.evaluate(inputs)\n mean = np.mean(np_inputs, axis=(0, 4), keepdims=True)\n std = np.std(np_inputs, axis=(0, 4), keepdims=True)\n variance = np.square(std)\n self.assertAllClose(mean, moving_mean, atol=1e-2)\n self.assertAllClose(variance, moving_var, atol=1e-2)\n\n # Test inference with placeholder learning phase.\n np_output = sess.run(outputs, feed_dict={training: False})\n\n # Verify that the axis is normalized during inference.\n normed_np_output = ((np_output - epsilon) * np_gamma) + np_beta\n self.assertAlmostEqual(np.mean(normed_np_output), 0., places=1)\n self.assertAlmostEqual(np.std(normed_np_output), 1., places=1)\n\n def testGhostBN5DimsMultiAxis14(self):\n shape = [6, 3, 10, 10, 4]\n virtual_batch_size = 3\n beta = 2.\n gamma = 3.\n momentum = 0.8\n epsilon = 1e-3\n moving_means = np.zeros([1, 1, 3, 1, 1, 4], dtype=np.float32)\n moving_vars = np.ones([1, 1, 3, 1, 1, 4], dtype=np.float32)\n\n inp = array_ops.placeholder(dtypes.float32, shape)\n is_training = array_ops.placeholder(dtypes.bool)\n bn = normalization_layers.BatchNormalization(\n axis=[1, 4],\n momentum=momentum,\n epsilon=epsilon,\n beta_initializer=init_ops.constant_initializer(beta),\n gamma_initializer=init_ops.constant_initializer(gamma),\n virtual_batch_size=virtual_batch_size,\n fused=False)\n out = bn.apply(inp, training=is_training)\n ghost_shape = ([virtual_batch_size, shape[0] // virtual_batch_size] +\n shape[1:])\n\n with self.session() as sess:\n self.evaluate(variables.global_variables_initializer())\n for _ in range(5):\n x = np.random.random(shape)\n\n sub_batched = np.reshape(x, ghost_shape)\n means = np.mean(sub_batched, axis=(0, 3, 4), keepdims=True)\n variances = np.var(sub_batched, axis=(0, 3, 4), keepdims=True)\n\n avg_means = np.mean(means, axis=1, keepdims=True)\n avg_variances = np.mean(variances, axis=1, keepdims=True)\n\n moving_means = moving_means * momentum + avg_means * (1. - momentum)\n moving_vars = moving_vars * momentum + avg_variances * (1. - momentum)\n\n y_train = ((sub_batched - means) /\n (variances + epsilon) ** 0.5 * gamma) + beta\n y_test = ((sub_batched - moving_means) /\n (moving_vars + epsilon) ** 0.5 * gamma) + beta\n\n y_train = np.reshape(y_train, shape)\n y_test = np.reshape(y_test, shape)\n\n y_val_train, _, _ = sess.run([out] + bn.updates,\n feed_dict={inp: x, is_training: True})\n y_val_test = sess.run(out, feed_dict={inp: x, is_training: False})\n\n self.assertAllClose(y_train, y_val_train, atol=1e-2)\n self.assertAllClose(y_test, y_val_test, atol=1e-2)\n\n\nif __name__ == '__main__':\n test.main()\n", "# lint as: python3\n# Copyright 2018 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\"\"\"A tool to generate api_docs for TensorFlow2.\n\n```\npython generate2.py --output_dir=/tmp/out\n```\n\nRequires a local installation of `tensorflow_docs`:\n\n```\npip install git+https://github.com/tensorflow/docs\n```\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport pathlib\nimport textwrap\n\nfrom absl import app\nfrom absl import flags\n\nimport tensorflow as tf\n\nfrom tensorflow_docs.api_generator import doc_controls\nfrom tensorflow_docs.api_generator import doc_generator_visitor\nfrom tensorflow_docs.api_generator import generate_lib\n\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.util import tf_export\nfrom tensorflow.python.util import tf_inspect\n\n# Caution: the google and oss versions of this import are different.\nimport base_dir\n\n# pylint: disable=g-import-not-at-top\ntry:\n from tensorflow.python.types import doc_typealias\n _EXTRA_DOCS = getattr(doc_typealias, \"_EXTRA_DOCS\", {})\n del doc_typealias\nexcept ImportError:\n _EXTRA_DOCS = {}\n# pylint: enable=g-import-not-at-top\n\n# `tf` has an `__all__` that doesn't list important things like `keras`.\n# The doc generator recognizes `__all__` as the list of public symbols.\n# So patch `tf.__all__` to list everything.\ntf.__all__ = [item_name for item_name, value in tf_inspect.getmembers(tf)]\n\n# tf_export generated two copies of the module objects.\n# This will just list compat.v2 as an alias for tf. Close enough, let's not\n# duplicate all the module skeleton files.\ntf.compat.v2 = tf\n\nFLAGS = flags.FLAGS\n\nflags.DEFINE_string(\n \"code_url_prefix\",\n \"/code/stable/tensorflow\",\n \"A url to prepend to code paths when creating links to defining code\")\n\nflags.DEFINE_string(\"output_dir\", \"/tmp/out\",\n \"A directory, where the docs will be output to.\")\n\nflags.DEFINE_bool(\"search_hints\", True,\n \"Include meta-data search hints at the top of each file.\")\n\nflags.DEFINE_string(\n \"site_path\", \"\",\n \"The path prefix (up to `.../api_docs/python`) used in the \"\n \"`_toc.yaml` and `_redirects.yaml` files\")\n\nflags.DEFINE_bool(\"gen_report\", False,\n (\"Generate an API report containing the health of the\"\n \"docstrings of the public API.\"))\n\n_PRIVATE_MAP = {\n \"tf\": [\"python\", \"core\", \"compiler\", \"examples\", \"tools\", \"contrib\"],\n # There's some aliasing between the compats and v1/2s, so it's easier to\n # block by name and location than by deleting, or hiding objects.\n \"tf.compat.v1.compat\": [\"v1\", \"v2\"],\n \"tf.compat.v2.compat\": [\"v1\", \"v2\"]\n}\n\ntf.__doc__ = \"\"\"\n ## TensorFlow\n\n ```\n pip install tensorflow\n ```\n \"\"\"\n\n\ndef generate_raw_ops_doc():\n \"\"\"Generates docs for `tf.raw_ops`.\"\"\"\n\n warning = textwrap.dedent(\"\"\"\\n\n Note: `tf.raw_ops` provides direct/low level access to all TensorFlow ops.\n See [the RFC](https://github.com/tensorflow/community/blob/master/rfcs/20181225-tf-raw-ops.md)\n for details. Unless you are library writer, you likely do not need to use\n these ops directly.\"\"\")\n\n table_header = textwrap.dedent(\"\"\"\n\n | Op Name | Has Gradient |\n |---------|:------------:|\"\"\")\n\n parts = [warning, table_header]\n\n for op_name in sorted(dir(tf.raw_ops)):\n try:\n ops._gradient_registry.lookup(op_name) # pylint: disable=protected-access\n has_gradient = \"\\N{HEAVY CHECK MARK}\\N{VARIATION SELECTOR-16}\"\n except LookupError:\n has_gradient = \"\\N{CROSS MARK}\"\n\n if not op_name.startswith(\"_\"):\n path = pathlib.Path(\"/\") / FLAGS.site_path / \"tf/raw_ops\" / op_name\n path = path.with_suffix(\".md\")\n link = ('<a id={op_name} href=\"{path}\">{op_name}</a>').format(\n op_name=op_name, path=str(path))\n parts.append(\"| {link} | {has_gradient} |\".format(\n link=link, has_gradient=has_gradient))\n\n return \"\\n\".join(parts)\n\n\n# The doc generator isn't aware of tf_export.\n# So prefix the score tuples with -1 when this is the canonical name, +1\n# otherwise. The generator chooses the name with the lowest score.\nclass TfExportAwareVisitor(doc_generator_visitor.DocGeneratorVisitor):\n \"\"\"A `tf_export`, `keras_export` and `estimator_export` aware doc_visitor.\"\"\"\n\n def _score_name(self, name):\n all_exports = [tf_export.TENSORFLOW_API_NAME,\n tf_export.KERAS_API_NAME,\n tf_export.ESTIMATOR_API_NAME]\n\n for api_name in all_exports:\n canonical = tf_export.get_canonical_name_for_symbol(\n self._index[name], api_name=api_name)\n if canonical is not None:\n break\n\n canonical_score = 1\n if canonical is not None and name == \"tf.\" + canonical:\n canonical_score = -1\n\n scores = super()._score_name(name)\n return (canonical_score,) + scores\n\n\ndef build_docs(output_dir, code_url_prefix, search_hints, gen_report):\n \"\"\"Build api docs for tensorflow v2.\n\n Args:\n output_dir: A string path, where to put the files.\n code_url_prefix: prefix for \"Defined in\" links.\n search_hints: Bool. Include meta-data search hints at the top of each file.\n gen_report: Bool. Generates an API report containing the health of the\n docstrings of the public API.\n \"\"\"\n # The custom page will be used for raw_ops.md not the one generated above.\n doc_controls.set_custom_page_content(tf.raw_ops, generate_raw_ops_doc())\n\n # Hide raw_ops from search.\n for name, obj in tf_inspect.getmembers(tf.raw_ops):\n if not name.startswith(\"_\"):\n doc_controls.hide_from_search(obj)\n\n for cls in [tf.Module, tf.keras.layers.Layer, tf.keras.optimizers.Optimizer]:\n doc_controls.decorate_all_class_attributes(\n decorator=doc_controls.do_not_doc_in_subclasses,\n cls=cls,\n skip=[\"__init__\"])\n\n try:\n doc_controls.do_not_generate_docs(tf.__internal__)\n except AttributeError:\n pass\n\n try:\n doc_controls.do_not_generate_docs(tf.keras.__internal__)\n except AttributeError:\n pass\n\n try:\n doc_controls.do_not_generate_docs(tf.__operators__)\n except AttributeError:\n pass\n\n try:\n doc_controls.do_not_generate_docs(tf.tools)\n except AttributeError:\n pass\n\n try:\n doc_controls.do_not_generate_docs(tf.compat.v1.pywrap_tensorflow)\n except AttributeError:\n pass\n\n try:\n doc_controls.do_not_generate_docs(tf.pywrap_tensorflow)\n except AttributeError:\n pass\n\n try:\n doc_controls.do_not_generate_docs(tf.flags)\n except AttributeError:\n pass\n\n base_dirs, code_url_prefixes = base_dir.get_base_dirs_and_prefixes(\n code_url_prefix)\n doc_generator = generate_lib.DocGenerator(\n root_title=\"TensorFlow 2\",\n py_modules=[(\"tf\", tf)],\n base_dir=base_dirs,\n search_hints=search_hints,\n code_url_prefix=code_url_prefixes,\n site_path=FLAGS.site_path,\n visitor_cls=TfExportAwareVisitor,\n private_map=_PRIVATE_MAP,\n gen_report=gen_report,\n extra_docs=_EXTRA_DOCS\n )\n\n doc_generator.build(output_dir)\n\n if gen_report:\n return\n\n out_path = pathlib.Path(output_dir)\n\n expected_path_contents = {\n \"tf/summary/audio.md\":\n \"tensorboard/plugins/audio/summary_v2.py\",\n \"tf/estimator/DNNClassifier.md\":\n \"tensorflow_estimator/python/estimator/canned/dnn.py\",\n \"tf/nn/sigmoid_cross_entropy_with_logits.md\":\n \"python/ops/nn_impl.py\",\n \"tf/keras/Model.md\":\n \"keras/engine/training.py\",\n \"tf/keras/preprocessing/image/random_brightness.md\":\n \"keras_preprocessing/image/affine_transformations.py\"\n }\n\n all_passed = True\n error_msg_parts = [\n 'Some \"view source\" links seem to be broken, please check:'\n ]\n\n for (rel_path, contents) in expected_path_contents.items():\n path = out_path / rel_path\n if contents not in path.read_text():\n all_passed = False\n error_msg_parts.append(\" \" + str(path))\n\n if not all_passed:\n raise ValueError(\"\\n\".join(error_msg_parts))\n\n rejected_path_contents = {\n \"tf/keras/optimizers.md\": \"keras/optimizers/__init__.py\",\n }\n\n all_passed = True\n error_msg_parts = [\n 'Bad \"view source\" links in generated files, please check:'\n ]\n for rel_path, content in rejected_path_contents.items():\n path = out_path / rel_path\n if content in path.read_text():\n all_passed = False\n error_msg_parts.append(\" \" + str(path))\n\n if not all_passed:\n raise ValueError(\"\\n\".join(error_msg_parts))\n\n num_files = len(list(out_path.rglob(\"*\")))\n if num_files < 2000:\n raise ValueError(\"The TensorFlow api should be more than 2000 files\"\n \"(found {}).\".format(num_files))\n\n\ndef main(argv):\n del argv\n build_docs(\n output_dir=FLAGS.output_dir,\n code_url_prefix=FLAGS.code_url_prefix,\n search_hints=FLAGS.search_hints,\n gen_report=FLAGS.gen_report,)\n\n\nif __name__ == \"__main__\":\n app.run(main)\n", "# Copyright 2020 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# maxlengthations under the License.\n# ==============================================================================\n\"\"\"Tests for bincount ops.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl.testing import parameterized\nimport numpy as np\n\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import sparse_tensor\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import bincount_ops\nfrom tensorflow.python.ops import gen_count_ops\nfrom tensorflow.python.ops import sparse_ops\nfrom tensorflow.python.ops.ragged import ragged_factory_ops\nfrom tensorflow.python.ops.ragged import ragged_tensor\nfrom tensorflow.python.platform import test\n\n\nclass TestSparseCount(test.TestCase, parameterized.TestCase):\n\n @parameterized.named_parameters(\n {\n \"testcase_name\": \"_no_maxlength\",\n \"x\": np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32),\n \"expected_indices\": [[0, 1], [0, 2], [0, 3], [1, 4], [1, 5]],\n \"expected_values\": [1, 1, 1, 2, 1],\n \"expected_shape\": [2, 6]\n }, {\n \"testcase_name\": \"_maxlength\",\n \"x\": np.array([[3, 2, 1, 7], [7, 0, 4, 4]], dtype=np.int32),\n \"maxlength\": 7,\n \"expected_indices\": [[0, 1], [0, 2], [0, 3], [1, 0], [1, 4]],\n \"expected_values\": [1, 1, 1, 1, 2],\n \"expected_shape\": [2, 7]\n }, {\n \"testcase_name\": \"_minlength\",\n \"x\": np.array([[3, 2, 1, 7], [7, 0, 4, 4]], dtype=np.int32),\n \"minlength\": 9,\n \"expected_indices\": [[0, 1], [0, 2], [0, 3], [0, 7], [1, 0], [1, 4],\n [1, 7]],\n \"expected_values\": [1, 1, 1, 1, 1, 2, 1],\n \"expected_shape\": [2, 9]\n }, {\n \"testcase_name\": \"_minlength_larger_values\",\n \"x\": np.array([[3, 2, 1, 7], [7, 0, 4, 4]], dtype=np.int32),\n \"minlength\": 3,\n \"expected_indices\": [[0, 1], [0, 2], [0, 3], [0, 7], [1, 0], [1, 4],\n [1, 7]],\n \"expected_values\": [1, 1, 1, 1, 1, 2, 1],\n \"expected_shape\": [2, 8]\n }, {\n \"testcase_name\": \"_no_maxlength_binary\",\n \"x\": np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32),\n \"expected_indices\": [[0, 1], [0, 2], [0, 3], [1, 4], [1, 5]],\n \"expected_values\": [1, 1, 1, 1, 1],\n \"expected_shape\": [2, 6],\n \"binary_output\": True,\n }, {\n \"testcase_name\": \"_maxlength_binary\",\n \"x\": np.array([[3, 2, 1, 7], [7, 0, 4, 4]], dtype=np.int32),\n \"maxlength\": 7,\n \"expected_indices\": [[0, 1], [0, 2], [0, 3], [1, 0], [1, 4]],\n \"expected_values\": [1, 1, 1, 1, 1],\n \"expected_shape\": [2, 7],\n \"binary_output\": True,\n }, {\n \"testcase_name\": \"_minlength_binary\",\n \"x\": np.array([[3, 2, 1, 7], [7, 0, 4, 4]], dtype=np.int32),\n \"minlength\": 9,\n \"expected_indices\": [[0, 1], [0, 2], [0, 3], [0, 7], [1, 0], [1, 4],\n [1, 7]],\n \"expected_values\": [1, 1, 1, 1, 1, 1, 1],\n \"expected_shape\": [2, 9],\n \"binary_output\": True,\n }, {\n \"testcase_name\": \"_minlength_larger_values_binary\",\n \"x\": np.array([[3, 2, 1, 7], [7, 0, 4, 4]], dtype=np.int32),\n \"minlength\": 3,\n \"expected_indices\": [[0, 1], [0, 2], [0, 3], [0, 7], [1, 0], [1, 4],\n [1, 7]],\n \"expected_values\": [1, 1, 1, 1, 1, 1, 1],\n \"expected_shape\": [2, 8],\n \"binary_output\": True,\n }, {\n \"testcase_name\": \"_no_maxlength_weights\",\n \"x\": np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32),\n \"expected_indices\": [[0, 1], [0, 2], [0, 3], [1, 4], [1, 5]],\n \"expected_values\": [2, 1, 0.5, 9, 3],\n \"expected_shape\": [2, 6],\n \"weights\": [[0.5, 1, 2], [3, 4, 5]]\n }, {\n \"testcase_name\": \"_maxlength_weights\",\n \"x\": np.array([[3, 2, 1, 7], [7, 0, 4, 4]], dtype=np.int32),\n \"maxlength\": 7,\n \"expected_indices\": [[0, 1], [0, 2], [0, 3], [1, 0], [1, 4]],\n \"expected_values\": [2, 1, 0.5, 3, 9],\n \"expected_shape\": [2, 7],\n \"weights\": [[0.5, 1, 2, 11], [7, 3, 4, 5]]\n }, {\n \"testcase_name\": \"_minlength_weights\",\n \"x\": np.array([[3, 2, 1, 7], [7, 0, 4, 4]], dtype=np.int32),\n \"minlength\": 9,\n \"expected_indices\": [[0, 1], [0, 2], [0, 3], [0, 7], [1, 0], [1, 4],\n [1, 7]],\n \"expected_values\": [2, 1, 0.5, 3, 5, 13, 4],\n \"expected_shape\": [2, 9],\n \"weights\": [[0.5, 1, 2, 3], [4, 5, 6, 7]]\n }, {\n \"testcase_name\": \"_minlength_larger_values_weights\",\n \"x\": np.array([[3, 2, 1, 7], [7, 0, 4, 4]], dtype=np.int32),\n \"minlength\": 3,\n \"expected_indices\": [[0, 1], [0, 2], [0, 3], [0, 7], [1, 0], [1, 4],\n [1, 7]],\n \"expected_values\": [2, 1, 0.5, 3, 5, 13, 4],\n \"expected_shape\": [2, 8],\n \"weights\": [[0.5, 1, 2, 3], [4, 5, 6, 7]]\n }, {\n \"testcase_name\": \"_1d\",\n \"x\": np.array([3, 2, 1, 1], dtype=np.int32),\n \"expected_indices\": [[1], [2], [3]],\n \"expected_values\": [2, 1, 1],\n \"expected_shape\": [4]\n }, {\n \"testcase_name\": \"_all_axes\",\n \"x\": np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32),\n \"expected_indices\": [[1], [2], [3], [4], [5]],\n \"expected_values\": [1, 1, 1, 2, 1],\n \"expected_shape\": [6],\n \"axis\": None\n })\n def test_dense_input(self,\n x,\n expected_indices,\n expected_values,\n expected_shape,\n minlength=None,\n maxlength=None,\n binary_output=False,\n weights=None,\n axis=-1):\n y = bincount_ops.sparse_bincount(\n x,\n weights=weights,\n minlength=minlength,\n maxlength=maxlength,\n binary_output=binary_output,\n axis=axis)\n self.assertAllEqual(expected_indices, y.indices)\n self.assertAllEqual(expected_values, y.values)\n self.assertAllEqual(expected_shape, y.dense_shape)\n\n @parameterized.named_parameters(\n {\n \"testcase_name\":\n \"_no_maxlength\",\n \"x\":\n np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]],\n dtype=np.int32),\n \"expected_indices\": [[0, 1], [0, 3], [2, 4], [2, 5]],\n \"expected_values\": [1, 1, 2, 1],\n \"expected_shape\": [3, 6],\n },\n {\n \"testcase_name\":\n \"_maxlength\",\n \"x\":\n np.array([[3, 0, 1, 0], [7, 0, 0, 0], [5, 0, 4, 4]],\n dtype=np.int32),\n \"expected_indices\": [[0, 1], [0, 3], [2, 4], [2, 5]],\n \"expected_values\": [1, 1, 2, 1],\n \"expected_shape\": [3, 7],\n \"maxlength\":\n 7,\n },\n {\n \"testcase_name\":\n \"_minlength\",\n \"x\":\n np.array([[3, 0, 1, 0], [7, 0, 0, 0], [5, 0, 4, 4]],\n dtype=np.int32),\n \"expected_indices\": [[0, 1], [0, 3], [1, 7], [2, 4], [2, 5]],\n \"expected_values\": [1, 1, 1, 2, 1],\n \"expected_shape\": [3, 9],\n \"minlength\":\n 9,\n },\n {\n \"testcase_name\":\n \"_minlength_larger_values\",\n \"x\":\n np.array([[3, 0, 1, 0], [7, 0, 0, 0], [5, 0, 4, 4]],\n dtype=np.int32),\n \"expected_indices\": [[0, 1], [0, 3], [1, 7], [2, 4], [2, 5]],\n \"expected_values\": [1, 1, 1, 2, 1],\n \"expected_shape\": [3, 8],\n \"minlength\":\n 3,\n },\n {\n \"testcase_name\":\n \"_no_maxlength_binary\",\n \"x\":\n np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]],\n dtype=np.int32),\n \"expected_indices\": [[0, 1], [0, 3], [2, 4], [2, 5]],\n \"expected_values\": [1, 1, 1, 1],\n \"expected_shape\": [3, 6],\n \"binary_output\":\n True,\n },\n {\n \"testcase_name\":\n \"_maxlength_binary\",\n \"x\":\n np.array([[3, 0, 1, 0], [0, 0, 7, 0], [5, 0, 4, 4]],\n dtype=np.int32),\n \"expected_indices\": [[0, 1], [0, 3], [2, 4], [2, 5]],\n \"expected_values\": [1, 1, 1, 1],\n \"expected_shape\": [3, 7],\n \"maxlength\":\n 7,\n \"binary_output\":\n True,\n },\n {\n \"testcase_name\":\n \"_minlength_binary\",\n \"x\":\n np.array([[3, 0, 1, 0], [7, 0, 0, 0], [5, 0, 4, 4]],\n dtype=np.int32),\n \"expected_indices\": [[0, 1], [0, 3], [1, 7], [2, 4], [2, 5]],\n \"expected_values\": [1, 1, 1, 1, 1],\n \"expected_shape\": [3, 9],\n \"minlength\":\n 9,\n \"binary_output\":\n True,\n },\n {\n \"testcase_name\":\n \"_minlength_larger_values_binary\",\n \"x\":\n np.array([[3, 0, 1, 0], [7, 0, 0, 0], [5, 0, 4, 4]],\n dtype=np.int32),\n \"expected_indices\": [[0, 1], [0, 3], [1, 7], [2, 4], [2, 5]],\n \"expected_values\": [1, 1, 1, 1, 1],\n \"expected_shape\": [3, 8],\n \"minlength\":\n 3,\n \"binary_output\":\n True,\n },\n {\n \"testcase_name\":\n \"_no_maxlength_weights\",\n \"x\":\n np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]],\n dtype=np.int32),\n \"expected_indices\": [[0, 1], [0, 3], [2, 4], [2, 5]],\n \"expected_values\": [2, 6, 7, 10],\n \"expected_shape\": [3, 6],\n \"weights\":\n np.array([[6, 0, 2, 0], [0, 0, 0, 0], [10, 0, 3.5, 3.5]]),\n },\n {\n \"testcase_name\":\n \"_maxlength_weights\",\n \"x\":\n np.array([[3, 0, 1, 0], [0, 0, 7, 0], [5, 0, 4, 4]],\n dtype=np.int32),\n \"expected_indices\": [[0, 1], [0, 3], [2, 4], [2, 5]],\n \"expected_values\": [2, 6, 7, 10],\n \"expected_shape\": [3, 7],\n \"maxlength\":\n 7,\n \"weights\":\n np.array([[6, 0, 2, 0], [0, 0, 14, 0], [10, 0, 3.5, 3.5]]),\n },\n {\n \"testcase_name\":\n \"_minlength_weights\",\n \"x\":\n np.array([[3, 0, 1, 0], [7, 0, 0, 0], [5, 0, 4, 4]],\n dtype=np.int32),\n \"expected_indices\": [[0, 1], [0, 3], [1, 7], [2, 4], [2, 5]],\n \"expected_values\": [2, 6, 14, 6.5, 10],\n \"expected_shape\": [3, 9],\n \"minlength\":\n 9,\n \"weights\":\n np.array([[6, 0, 2, 0], [14, 0, 0, 0], [10, 0, 3, 3.5]]),\n },\n {\n \"testcase_name\":\n \"_minlength_larger_values_weights\",\n \"x\":\n np.array([[3, 0, 1, 0], [7, 0, 0, 0], [5, 0, 4, 4]],\n dtype=np.int32),\n \"expected_indices\": [[0, 1], [0, 3], [1, 7], [2, 4], [2, 5]],\n \"expected_values\": [2, 6, 14, 6.5, 10],\n \"expected_shape\": [3, 8],\n \"minlength\":\n 3,\n \"weights\":\n np.array([[6, 0, 2, 0], [14, 0, 0, 0], [10, 0, 3, 3.5]]),\n },\n {\n \"testcase_name\": \"_1d\",\n \"x\": np.array([3, 0, 1, 1], dtype=np.int32),\n \"expected_indices\": [[1], [3]],\n \"expected_values\": [2, 1],\n \"expected_shape\": [4],\n },\n {\n \"testcase_name\":\n \"_all_axes\",\n \"x\":\n np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]],\n dtype=np.int32),\n \"expected_indices\": [[1], [3], [4], [5]],\n \"expected_values\": [1, 1, 2, 1],\n \"expected_shape\": [6],\n \"axis\":\n None,\n },\n )\n def test_sparse_input(self,\n x,\n expected_indices,\n expected_values,\n expected_shape,\n maxlength=None,\n minlength=None,\n binary_output=False,\n weights=None,\n axis=-1):\n x_sparse = sparse_ops.from_dense(x)\n w_sparse = sparse_ops.from_dense(weights) if weights is not None else None\n y = bincount_ops.sparse_bincount(\n x_sparse,\n weights=w_sparse,\n minlength=minlength,\n maxlength=maxlength,\n binary_output=binary_output,\n axis=axis)\n self.assertAllEqual(expected_indices, y.indices)\n self.assertAllEqual(expected_values, y.values)\n self.assertAllEqual(expected_shape, y.dense_shape)\n\n @parameterized.named_parameters(\n {\n \"testcase_name\": \"_no_maxlength\",\n \"x\": [[], [], [3, 0, 1], [], [5, 0, 4, 4]],\n \"expected_indices\": [[2, 0], [2, 1], [2, 3], [4, 0], [4, 4], [4, 5]],\n \"expected_values\": [1, 1, 1, 1, 2, 1],\n \"expected_shape\": [5, 6],\n },\n {\n \"testcase_name\": \"_maxlength\",\n \"x\": [[], [], [3, 0, 1], [7], [5, 0, 4, 4]],\n \"maxlength\": 7,\n \"expected_indices\": [[2, 0], [2, 1], [2, 3], [4, 0], [4, 4], [4, 5]],\n \"expected_values\": [1, 1, 1, 1, 2, 1],\n \"expected_shape\": [5, 7],\n },\n {\n \"testcase_name\": \"_minlength\",\n \"x\": [[], [], [3, 0, 1], [7], [5, 0, 4, 4]],\n \"minlength\": 9,\n \"expected_indices\": [[2, 0], [2, 1], [2, 3], [3, 7], [4, 0], [4, 4],\n [4, 5]],\n \"expected_values\": [1, 1, 1, 1, 1, 2, 1],\n \"expected_shape\": [5, 9],\n },\n {\n \"testcase_name\": \"_minlength_larger_values\",\n \"x\": [[], [], [3, 0, 1], [7], [5, 0, 4, 4]],\n \"minlength\": 3,\n \"expected_indices\": [[2, 0], [2, 1], [2, 3], [3, 7], [4, 0], [4, 4],\n [4, 5]],\n \"expected_values\": [1, 1, 1, 1, 1, 2, 1],\n \"expected_shape\": [5, 8],\n },\n {\n \"testcase_name\": \"_no_maxlength_binary\",\n \"x\": [[], [], [3, 0, 1], [], [5, 0, 4, 4]],\n \"expected_indices\": [[2, 0], [2, 1], [2, 3], [4, 0], [4, 4], [4, 5]],\n \"expected_values\": [1, 1, 1, 1, 1, 1],\n \"expected_shape\": [5, 6],\n \"binary_output\": True,\n },\n {\n \"testcase_name\": \"_maxlength_binary\",\n \"x\": [[], [], [3, 0, 1], [7], [5, 0, 4, 4]],\n \"maxlength\": 7,\n \"expected_indices\": [[2, 0], [2, 1], [2, 3], [4, 0], [4, 4], [4, 5]],\n \"expected_values\": [1, 1, 1, 1, 1, 1],\n \"expected_shape\": [5, 7],\n \"binary_output\": True,\n },\n {\n \"testcase_name\": \"_minlength_binary\",\n \"x\": [[], [], [3, 0, 1], [7], [5, 0, 4, 4]],\n \"minlength\": 9,\n \"expected_indices\": [[2, 0], [2, 1], [2, 3], [3, 7], [4, 0], [4, 4],\n [4, 5]],\n \"expected_values\": [1, 1, 1, 1, 1, 1, 1],\n \"expected_shape\": [5, 9],\n \"binary_output\": True,\n },\n {\n \"testcase_name\": \"_minlength_larger_values_binary\",\n \"x\": [[], [], [3, 0, 1], [7], [5, 0, 4, 4]],\n \"minlength\": 3,\n \"binary_output\": True,\n \"expected_indices\": [[2, 0], [2, 1], [2, 3], [3, 7], [4, 0], [4, 4],\n [4, 5]],\n \"expected_values\": [1, 1, 1, 1, 1, 1, 1],\n \"expected_shape\": [5, 8],\n },\n {\n \"testcase_name\": \"_no_maxlength_weights\",\n \"x\": [[], [], [3, 0, 1], [], [5, 0, 4, 4]],\n \"expected_indices\": [[2, 0], [2, 1], [2, 3], [4, 0], [4, 4], [4, 5]],\n \"expected_values\": [0.5, 2, 6, 0.25, 8, 10],\n \"expected_shape\": [5, 6],\n \"weights\": [[], [], [6, 0.5, 2], [], [10, 0.25, 5, 3]],\n },\n {\n \"testcase_name\": \"_maxlength_weights\",\n \"x\": [[], [], [3, 0, 1], [7], [5, 0, 4, 4]],\n \"maxlength\": 7,\n \"expected_indices\": [[2, 0], [2, 1], [2, 3], [4, 0], [4, 4], [4, 5]],\n \"expected_values\": [0.5, 2, 6, 0.25, 8, 10],\n \"expected_shape\": [5, 7],\n \"weights\": [[], [], [6, 0.5, 2], [14], [10, 0.25, 5, 3]],\n },\n {\n \"testcase_name\": \"_minlength_weights\",\n \"x\": [[], [], [3, 0, 1], [7], [5, 0, 4, 4]],\n \"minlength\": 9,\n \"expected_indices\": [[2, 0], [2, 1], [2, 3], [3, 7], [4, 0], [4, 4],\n [4, 5]],\n \"expected_values\": [0.5, 2, 6, 14, 0.25, 8, 10],\n \"expected_shape\": [5, 9],\n \"weights\": [[], [], [6, 0.5, 2], [14], [10, 0.25, 5, 3]],\n },\n {\n \"testcase_name\": \"_minlength_larger_values_weights\",\n \"x\": [[], [], [3, 0, 1], [7], [5, 0, 4, 4]],\n \"minlength\": 3,\n \"expected_indices\": [[2, 0], [2, 1], [2, 3], [3, 7], [4, 0], [4, 4],\n [4, 5]],\n \"expected_values\": [0.5, 2, 6, 14, 0.25, 8, 10],\n \"expected_shape\": [5, 8],\n \"weights\": [[], [], [6, 0.5, 2], [14], [10, 0.25, 5, 3]],\n },\n {\n \"testcase_name\": \"_1d\",\n \"x\": [3, 0, 1, 1],\n \"expected_indices\": [[0], [1], [3]],\n \"expected_values\": [1, 2, 1],\n \"expected_shape\": [4],\n },\n {\n \"testcase_name\": \"_all_axes\",\n \"x\": [[], [], [3, 0, 1], [], [5, 0, 4, 4]],\n \"expected_indices\": [[0], [1], [3], [4], [5]],\n \"expected_values\": [2, 1, 1, 2, 1],\n \"expected_shape\": [6],\n \"axis\": None,\n },\n )\n def test_ragged_input(self,\n x,\n expected_indices,\n expected_values,\n expected_shape,\n maxlength=None,\n minlength=None,\n binary_output=False,\n weights=None,\n axis=-1):\n x_ragged = ragged_factory_ops.constant(x)\n w = ragged_factory_ops.constant(weights) if weights is not None else None\n y = bincount_ops.sparse_bincount(\n x_ragged,\n weights=w,\n minlength=minlength,\n maxlength=maxlength,\n binary_output=binary_output,\n axis=axis)\n self.assertAllEqual(expected_indices, y.indices)\n self.assertAllEqual(expected_values, y.values)\n self.assertAllEqual(expected_shape, y.dense_shape)\n\n\nclass TestDenseBincount(test.TestCase, parameterized.TestCase):\n\n @parameterized.parameters([{\n \"dtype\": np.int32,\n }, {\n \"dtype\": np.int64,\n }])\n def test_sparse_input_all_count(self, dtype):\n np.random.seed(42)\n num_rows = 128\n size = 1000\n n_elems = 4096\n inp_indices = np.random.randint(0, num_rows, (n_elems, 1))\n inp_indices = np.concatenate([inp_indices, np.zeros((n_elems, 1))], axis=1)\n inp_vals = np.random.randint(0, size, (n_elems,), dtype=dtype)\n sparse_inp = sparse_tensor.SparseTensor(inp_indices, inp_vals,\n [num_rows, 1])\n\n np_out = np.bincount(inp_vals, minlength=size)\n self.assertAllEqual(\n np_out, self.evaluate(bincount_ops.bincount(sparse_inp, axis=0)))\n\n @parameterized.parameters([{\n \"dtype\": np.int32,\n }, {\n \"dtype\": np.int64,\n }])\n def test_sparse_input_all_count_with_weights(self, dtype):\n np.random.seed(42)\n num_rows = 128\n size = 1000\n n_elems = 4096\n inp_indices = np.random.randint(0, num_rows, (n_elems, 1))\n inp_indices = np.concatenate([inp_indices, np.zeros((n_elems, 1))], axis=1)\n inp_vals = np.random.randint(0, size, (n_elems,), dtype=dtype)\n sparse_inp = sparse_tensor.SparseTensor(inp_indices, inp_vals,\n [num_rows, 1])\n weight_vals = np.random.random((n_elems,))\n sparse_weights = sparse_tensor.SparseTensor(inp_indices, weight_vals,\n [num_rows, 1])\n\n np_out = np.bincount(inp_vals, minlength=size, weights=weight_vals)\n self.assertAllEqual(\n np_out,\n self.evaluate(bincount_ops.bincount(\n sparse_inp, sparse_weights, axis=0)))\n\n @parameterized.parameters([{\n \"dtype\": np.int32,\n }, {\n \"dtype\": np.int64,\n }])\n def test_sparse_input_all_binary(self, dtype):\n np.random.seed(42)\n num_rows = 128\n size = 10\n n_elems = 4096\n inp_indices = np.random.randint(0, num_rows, (n_elems, 1))\n inp_indices = np.concatenate([inp_indices, np.zeros((n_elems, 1))], axis=1)\n inp_vals = np.random.randint(0, size, (n_elems,), dtype=dtype)\n sparse_inp = sparse_tensor.SparseTensor(inp_indices, inp_vals,\n [num_rows, 1])\n\n np_out = np.ones((size,))\n self.assertAllEqual(\n np_out,\n self.evaluate(bincount_ops.bincount(sparse_inp, binary_output=True)))\n\n @parameterized.parameters([{\n \"dtype\": np.int32,\n }, {\n \"dtype\": np.int64,\n }])\n def test_sparse_input_col_reduce_count(self, dtype):\n num_rows = 128\n num_cols = 27\n size = 100\n np.random.seed(42)\n inp = np.random.randint(0, size, (num_rows, num_cols), dtype=dtype)\n np_out = np.reshape(\n np.concatenate(\n [np.bincount(inp[j, :], minlength=size) for j in range(num_rows)],\n axis=0), (num_rows, size))\n # from_dense will filter out 0s.\n inp = inp + 1\n # from_dense will cause OOM in GPU.\n with ops.device(\"/CPU:0\"):\n inp_sparse = sparse_ops.from_dense(inp)\n inp_sparse = sparse_tensor.SparseTensor(inp_sparse.indices,\n inp_sparse.values - 1,\n inp_sparse.dense_shape)\n self.assertAllEqual(\n np_out, self.evaluate(bincount_ops.bincount(arr=inp_sparse, axis=-1)))\n\n @parameterized.parameters([{\n \"dtype\": np.int32,\n }, {\n \"dtype\": np.int64,\n }])\n def test_sparse_input_col_reduce_binary(self, dtype):\n num_rows = 128\n num_cols = 27\n size = 100\n np.random.seed(42)\n inp = np.random.randint(0, size, (num_rows, num_cols), dtype=dtype)\n np_out = np.reshape(\n np.concatenate([\n np.where(np.bincount(inp[j, :], minlength=size) > 0, 1, 0)\n for j in range(num_rows)\n ],\n axis=0), (num_rows, size))\n # from_dense will filter out 0s.\n inp = inp + 1\n # from_dense will cause OOM in GPU.\n with ops.device(\"/CPU:0\"):\n inp_sparse = sparse_ops.from_dense(inp)\n inp_sparse = sparse_tensor.SparseTensor(inp_sparse.indices,\n inp_sparse.values - 1,\n inp_sparse.dense_shape)\n self.assertAllEqual(\n np_out,\n self.evaluate(\n bincount_ops.bincount(arr=inp_sparse, axis=-1, binary_output=True)))\n\n @parameterized.parameters([{\n \"dtype\": np.int32,\n }, {\n \"dtype\": np.int64,\n }])\n def test_ragged_input_count(self, dtype):\n x = ragged_factory_ops.constant([[], [], [3, 0, 1], [], [5, 0, 4, 4]],\n dtype)\n # pyformat: disable\n expected_output = [\n [0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0],\n [1, 1, 0, 1, 0, 0],\n [0, 0, 0, 0, 0, 0],\n [1, 0, 0, 0, 2, 1]]\n # pyformat: enable\n self.assertAllEqual(expected_output,\n self.evaluate(bincount_ops.bincount(arr=x, axis=-1)))\n\n @parameterized.parameters([{\n \"dtype\": np.int32,\n }, {\n \"dtype\": np.int64,\n }])\n def test_ragged_input_binary(self, dtype):\n x = ragged_factory_ops.constant([[], [], [3, 0, 1], [], [5, 0, 4, 4]])\n # pyformat: disable\n expected_output = [\n [0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0],\n [1, 1, 0, 1, 0, 0],\n [0, 0, 0, 0, 0, 0],\n [1, 0, 0, 0, 1, 1]]\n # pyformat: enable\n self.assertAllEqual(\n expected_output,\n self.evaluate(\n bincount_ops.bincount(arr=x, axis=-1, binary_output=True)))\n\n @parameterized.parameters([{\n \"dtype\": np.int32,\n }, {\n \"dtype\": np.int64,\n }])\n def test_ragged_input_count_with_weights(self, dtype):\n x = ragged_factory_ops.constant([[], [], [3, 0, 1], [], [5, 0, 4, 4]])\n weights = ragged_factory_ops.constant([[], [], [.1, .2, .3], [],\n [.2, .5, .6, .3]])\n # pyformat: disable\n expected_output = [\n [0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0],\n [.2, .3, 0, .1, 0, 0],\n [0, 0, 0, 0, 0, 0],\n [.5, 0, 0, 0, .9, .2]]\n # pyformat: enable\n self.assertAllClose(\n expected_output,\n self.evaluate(bincount_ops.bincount(arr=x, weights=weights, axis=-1)))\n\n @parameterized.parameters([{\n \"dtype\": np.int32,\n }, {\n \"dtype\": np.int64,\n }])\n def test_ragged_input_count_np(self, dtype):\n np.random.seed(42)\n num_rows = 128\n num_cols = 27\n size = 1000\n inp = np.random.randint(0, size, (num_rows, num_cols), dtype=dtype)\n np_out = np.reshape(\n np.concatenate(\n [np.bincount(inp[j, :], minlength=size) for j in range(num_rows)],\n axis=0), (num_rows, size))\n x = ragged_tensor.RaggedTensor.from_tensor(inp)\n self.assertAllEqual(\n np_out,\n self.evaluate(bincount_ops.bincount(arr=x, minlength=size, axis=-1)))\n\n @parameterized.parameters([{\n \"dtype\": np.int32,\n }, {\n \"dtype\": np.int64,\n }])\n def test_ragged_input_count_np_with_weights(self, dtype):\n np.random.seed(42)\n num_rows = 128\n num_cols = 27\n size = 1000\n inp = np.random.randint(0, size, (num_rows, num_cols), dtype=dtype)\n np_weight = np.random.random((num_rows, num_cols))\n np_out = np.reshape(\n np.concatenate([\n np.bincount(inp[j, :], weights=np_weight[j, :], minlength=size)\n for j in range(num_rows)\n ],\n axis=0), (num_rows, size))\n x = ragged_tensor.RaggedTensor.from_tensor(inp)\n weights = ragged_tensor.RaggedTensor.from_tensor(np_weight)\n self.assertAllEqual(\n np_out,\n self.evaluate(\n bincount_ops.bincount(\n arr=x, weights=weights, minlength=size, axis=-1)))\n\n\nclass TestSparseCountFailureModes(test.TestCase):\n\n def test_dense_input_sparse_weights_fails(self):\n x = np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32)\n weights = sparse_ops.from_dense(\n np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32))\n with self.assertRaisesRegex(ValueError, \"must be a tf.Tensor\"):\n self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1))\n\n def test_dense_input_ragged_weights_fails(self):\n x = np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32)\n weights = ragged_factory_ops.constant([[6, 0.5, 2], [14], [10, 0.25, 5, 3]])\n with self.assertRaisesRegex(ValueError, \"must be a tf.Tensor\"):\n self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1))\n\n def test_dense_input_wrong_shape_fails(self):\n x = np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32)\n weights = np.array([[3, 2], [5, 4], [4, 3]])\n # Note: Eager mode and graph mode throw different errors here. Graph mode\n # will fail with a ValueError from the shape checking logic, while Eager\n # will fail with an InvalidArgumentError from the kernel itself.\n if context.executing_eagerly():\n with self.assertRaisesRegex(errors.InvalidArgumentError,\n \"must have the same shape\"):\n self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1))\n else:\n with self.assertRaisesRegex(ValueError, \"both shapes must be equal\"):\n self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1))\n\n def test_sparse_input_dense_weights_fails(self):\n x = sparse_ops.from_dense(\n np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32))\n weights = np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32)\n with self.assertRaisesRegex(ValueError, \"must be a SparseTensor\"):\n self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1))\n\n def test_sparse_input_ragged_weights_fails(self):\n x = sparse_ops.from_dense(\n np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32))\n weights = ragged_factory_ops.constant([[6, 0.5, 2], [14], [10, 0.25, 5, 3]])\n with self.assertRaisesRegex(ValueError, \"must be a SparseTensor\"):\n self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1))\n\n def test_sparse_input_wrong_indices_fails(self):\n x = sparse_ops.from_dense(\n np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32))\n weights = sparse_ops.from_dense(\n np.array([[3, 1, 0, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32))\n with self.assertRaisesRegex(errors.InvalidArgumentError,\n \"must have the same indices\"):\n self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1))\n\n def test_sparse_input_too_many_indices_fails(self):\n x = sparse_ops.from_dense(\n np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32))\n weights = sparse_ops.from_dense(\n np.array([[3, 1, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32))\n with self.assertRaisesIncompatibleShapesError():\n self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1))\n\n def test_sparse_input_wrong_shape_fails(self):\n x = sparse_ops.from_dense(\n np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32))\n weights = sparse_ops.from_dense(\n np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4], [0, 0, 0, 0]],\n dtype=np.int32))\n with self.assertRaisesRegex(errors.InvalidArgumentError,\n \"must have the same dense shape\"):\n self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1))\n\n def test_ragged_input_dense_weights_fails(self):\n x = ragged_factory_ops.constant([[6, 1, 2], [14], [10, 1, 5, 3]])\n weights = np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32)\n with self.assertRaisesRegex(ValueError, \"must be a RaggedTensor\"):\n self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1))\n\n def test_ragged_input_sparse_weights_fails(self):\n x = ragged_factory_ops.constant([[6, 1, 2], [14], [10, 1, 5, 3]])\n weights = sparse_ops.from_dense(\n np.array([[3, 0, 1, 0], [0, 0, 0, 0], [5, 0, 4, 4]], dtype=np.int32))\n with self.assertRaisesRegex(ValueError, \"must be a RaggedTensor\"):\n self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1))\n\n def test_ragged_input_different_shape_fails(self):\n x = ragged_factory_ops.constant([[6, 1, 2], [14], [10, 1, 5, 3]])\n weights = ragged_factory_ops.constant([[6, 0.5, 2], [], [10, 0.25, 5, 3]])\n with self.assertRaisesRegex(errors.InvalidArgumentError,\n \"must have the same row splits\"):\n self.evaluate(bincount_ops.sparse_bincount(x, weights=weights, axis=-1))\n\n\n@test_util.run_all_in_graph_and_eager_modes\n@test_util.disable_tfrt\nclass RawOpsTest(test.TestCase, parameterized.TestCase):\n\n def testSparseCountSparseOutputBadIndicesShape(self):\n indices = [[[0], [0]], [[0], [1]], [[1], [0]], [[1], [2]]]\n values = [1, 1, 1, 10]\n weights = [1, 2, 4, 6]\n dense_shape = [2, 3]\n with self.assertRaisesRegex(errors.InvalidArgumentError,\n \"Input indices must be a 2-dimensional tensor\"):\n self.evaluate(\n gen_count_ops.SparseCountSparseOutput(\n indices=indices,\n values=values,\n dense_shape=dense_shape,\n weights=weights,\n binary_output=False))\n\n def testSparseCountSparseOutputBadWeightsShape(self):\n indices = [[0, 0], [0, 1], [1, 0], [1, 2]]\n values = [1, 1, 1, 10]\n weights = [1, 2, 4]\n dense_shape = [2, 3]\n with self.assertRaisesRegex(errors.InvalidArgumentError,\n \"Weights and values must have the same shape\"):\n self.evaluate(\n gen_count_ops.SparseCountSparseOutput(\n indices=indices,\n values=values,\n dense_shape=dense_shape,\n weights=weights,\n binary_output=False))\n\n def testSparseCountSparseOutputBadNumberOfValues(self):\n indices = [[0, 0], [0, 1], [1, 0]]\n values = [1, 1, 1, 10]\n weights = [1, 2, 4, 6]\n dense_shape = [2, 3]\n with self.assertRaisesRegex(\n errors.InvalidArgumentError,\n \"Number of values must match first dimension of indices\"):\n self.evaluate(\n gen_count_ops.SparseCountSparseOutput(\n indices=indices,\n values=values,\n dense_shape=dense_shape,\n weights=weights,\n binary_output=False))\n\n def testRaggedCountSparseOutput(self):\n splits = [0, 4, 7]\n values = [1, 1, 2, 1, 2, 10, 5]\n weights = [1, 2, 3, 4, 5, 6, 7]\n output_indices, output_values, output_shape = self.evaluate(\n gen_count_ops.RaggedCountSparseOutput(\n splits=splits, values=values, weights=weights, binary_output=False))\n self.assertAllEqual([[0, 1], [0, 2], [1, 2], [1, 5], [1, 10]],\n output_indices)\n self.assertAllEqual([7, 3, 5, 7, 6], output_values)\n self.assertAllEqual([2, 11], output_shape)\n\n def testRaggedCountSparseOutputBadWeightsShape(self):\n splits = [0, 4, 7]\n values = [1, 1, 2, 1, 2, 10, 5]\n weights = [1, 2, 3, 4, 5, 6]\n with self.assertRaisesRegex(errors.InvalidArgumentError,\n \"Weights and values must have the same shape\"):\n self.evaluate(\n gen_count_ops.RaggedCountSparseOutput(\n splits=splits,\n values=values,\n weights=weights,\n binary_output=False))\n\n def testRaggedCountSparseOutputEmptySplits(self):\n splits = []\n values = [1, 1, 2, 1, 2, 10, 5]\n weights = [1, 2, 3, 4, 5, 6, 7]\n with self.assertRaisesRegex(\n errors.InvalidArgumentError,\n \"Must provide at least 2 elements for the splits argument\"):\n self.evaluate(\n gen_count_ops.RaggedCountSparseOutput(\n splits=splits,\n values=values,\n weights=weights,\n binary_output=False))\n\n def testRaggedCountSparseOutputBadSplitsStart(self):\n splits = [1, 7]\n values = [1, 1, 2, 1, 2, 10, 5]\n weights = [1, 2, 3, 4, 5, 6, 7]\n with self.assertRaisesRegex(errors.InvalidArgumentError,\n \"Splits must start with 0\"):\n self.evaluate(\n gen_count_ops.RaggedCountSparseOutput(\n splits=splits,\n values=values,\n weights=weights,\n binary_output=False))\n\n def testRaggedCountSparseOutputBadSplitsEnd(self):\n splits = [0, 5]\n values = [1, 1, 2, 1, 2, 10, 5]\n weights = [1, 2, 3, 4, 5, 6, 7]\n with self.assertRaisesRegex(errors.InvalidArgumentError,\n \"Splits must end with the number of values\"):\n self.evaluate(\n gen_count_ops.RaggedCountSparseOutput(\n splits=splits,\n values=values,\n weights=weights,\n binary_output=False))\n\n\nif __name__ == \"__main__\":\n test.main()\n", "# 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\"\"\"Tests for tensorflow.ops.tf.norm.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import linalg_ops\nfrom tensorflow.python.platform import test as test_lib\n\n\ndef _AddTest(test, test_name, fn):\n test_name = \"_\".join([\"test\", test_name])\n if hasattr(test, test_name):\n raise RuntimeError(\"Test %s defined more than once\" % test_name)\n setattr(test, test_name, fn)\n\n\nclass NormOpTest(test_lib.TestCase):\n\n @test_util.run_v1_only(\"b/120545219\")\n def testBadOrder(self):\n matrix = [[0., 1.], [2., 3.]]\n for ord_ in \"fro\", -7, -1.1, 0:\n with self.assertRaisesRegex(ValueError,\n \"'ord' must be a supported vector norm\"):\n linalg_ops.norm(matrix, ord=ord_)\n\n for ord_ in \"fro\", -7, -1.1, 0:\n with self.assertRaisesRegex(ValueError,\n \"'ord' must be a supported vector norm\"):\n linalg_ops.norm(matrix, ord=ord_, axis=-1)\n\n for ord_ in \"foo\", -7, -1.1, 1.1:\n with self.assertRaisesRegex(ValueError,\n \"'ord' must be a supported matrix norm\"):\n linalg_ops.norm(matrix, ord=ord_, axis=[-2, -1])\n\n @test_util.run_v1_only(\"b/120545219\")\n def testInvalidAxis(self):\n matrix = [[0., 1.], [2., 3.]]\n for axis_ in [], [1, 2, 3], [[1]], [[1], [2]], [3.1415], [1, 1]:\n error_prefix = (\"'axis' must be None, an integer, or a tuple of 2 unique \"\n \"integers\")\n with self.assertRaisesRegex(ValueError, error_prefix):\n linalg_ops.norm(matrix, axis=axis_)\n\n\ndef _GetNormOpTest(dtype_, shape_, ord_, axis_, keep_dims_, use_static_shape_):\n\n def _CompareNorm(self, matrix):\n np_norm = np.linalg.norm(matrix, ord=ord_, axis=axis_, keepdims=keep_dims_)\n with self.cached_session() as sess:\n if use_static_shape_:\n tf_matrix = constant_op.constant(matrix)\n tf_norm = linalg_ops.norm(\n tf_matrix, ord=ord_, axis=axis_, keepdims=keep_dims_)\n tf_norm_val = self.evaluate(tf_norm)\n else:\n tf_matrix = array_ops.placeholder(dtype_)\n tf_norm = linalg_ops.norm(\n tf_matrix, ord=ord_, axis=axis_, keepdims=keep_dims_)\n tf_norm_val = sess.run(tf_norm, feed_dict={tf_matrix: matrix})\n self.assertAllClose(np_norm, tf_norm_val, rtol=1e-5, atol=1e-5)\n\n @test_util.run_v1_only(\"b/120545219\")\n def Test(self):\n is_matrix_norm = (isinstance(axis_, tuple) or\n isinstance(axis_, list)) and len(axis_) == 2\n is_fancy_p_norm = np.isreal(ord_) and np.floor(ord_) != ord_\n if ((not is_matrix_norm and ord_ == \"fro\") or\n (is_matrix_norm and is_fancy_p_norm)):\n self.skipTest(\"Not supported by neither numpy.linalg.norm nor tf.norm\")\n if ord_ == \"euclidean\" or (axis_ is None and len(shape) > 2):\n self.skipTest(\"Not supported by numpy.linalg.norm\")\n matrix = np.random.randn(*shape_).astype(dtype_)\n if dtype_ in (np.complex64, np.complex128):\n matrix += 1j * np.random.randn(*shape_).astype(dtype_)\n _CompareNorm(self, matrix)\n\n return Test\n\n# pylint: disable=redefined-builtin\nif __name__ == \"__main__\":\n for use_static_shape in False, True:\n for dtype in np.float32, np.float64, np.complex64, np.complex128:\n for rows in 2, 5:\n for cols in 2, 5:\n for batch in [], [2], [2, 3]:\n shape = batch + [rows, cols]\n for ord in \"euclidean\", \"fro\", 0.5, 1, 2, np.inf:\n for axis in [\n None, (-2, -1), (-1, -2), -len(shape), 0, len(shape) - 1\n ]:\n for keep_dims in False, True:\n name = \"%s_%s_ord_%s_axis_%s_%s_%s\" % (\n dtype.__name__, \"_\".join(map(str, shape)), ord, axis,\n keep_dims, use_static_shape)\n _AddTest(NormOpTest, \"Norm_\" + name,\n _GetNormOpTest(dtype, shape, ord, axis, keep_dims,\n use_static_shape))\n\n test_lib.main()\n", "# Copyright 2020 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\"\"\"Common array methods.\"\"\"\n# pylint: disable=g-direct-tensorflow-import\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport enum\nimport functools\nimport math\nimport numbers\nimport numpy as np\nimport six\n\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import clip_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import linalg_ops\nfrom tensorflow.python.ops import manip_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import sort_ops\nfrom tensorflow.python.ops.numpy_ops import np_arrays\nfrom tensorflow.python.ops.numpy_ops import np_dtypes\nfrom tensorflow.python.ops.numpy_ops import np_export\nfrom tensorflow.python.ops.numpy_ops import np_utils\nfrom tensorflow.python.util import nest\n\n\nnewaxis = np_export.np_export_constant(__name__, 'newaxis', np.newaxis)\n\n\n@np_utils.np_doc('empty')\ndef empty(shape, dtype=float): # pylint: disable=redefined-outer-name\n return zeros(shape, dtype)\n\n\n@np_utils.np_doc('empty_like')\ndef empty_like(a, dtype=None):\n return zeros_like(a, dtype)\n\n\n@np_utils.np_doc('zeros')\ndef zeros(shape, dtype=float): # pylint: disable=redefined-outer-name\n dtype = (\n np_utils.result_type(dtype) if dtype else np_dtypes.default_float_type())\n return array_ops.zeros(shape, dtype=dtype)\n\n\n@np_utils.np_doc('zeros_like')\ndef zeros_like(a, dtype=None): # pylint: disable=missing-docstring\n if dtype is None:\n # We need to let np_utils.result_type decide the dtype, not tf.zeros_like\n dtype = np_utils.result_type(a)\n else:\n # TF and numpy has different interpretations of Python types such as\n # `float`, so we let `np_utils.result_type` decide.\n dtype = np_utils.result_type(dtype)\n dtype = dtypes.as_dtype(dtype) # Work around b/149877262\n return array_ops.zeros_like(a, dtype)\n\n\n@np_utils.np_doc('ones')\ndef ones(shape, dtype=float): # pylint: disable=redefined-outer-name\n if dtype:\n dtype = np_utils.result_type(dtype)\n return array_ops.ones(shape, dtype=dtype)\n\n\n@np_utils.np_doc('ones_like')\ndef ones_like(a, dtype=None):\n if dtype is None:\n dtype = np_utils.result_type(a)\n else:\n dtype = np_utils.result_type(dtype)\n return array_ops.ones_like(a, dtype)\n\n\n@np_utils.np_doc('eye')\ndef eye(N, M=None, k=0, dtype=float): # pylint: disable=invalid-name,missing-docstring\n if dtype:\n dtype = np_utils.result_type(dtype)\n if not M:\n M = N\n # Making sure N, M and k are `int`\n N = int(N)\n M = int(M)\n k = int(k)\n if k >= M or -k >= N:\n # tf.linalg.diag will raise an error in this case\n return zeros([N, M], dtype=dtype)\n if k == 0:\n return linalg_ops.eye(N, M, dtype=dtype)\n # We need the precise length, otherwise tf.linalg.diag will raise an error\n diag_len = min(N, M)\n if k > 0:\n if N >= M:\n diag_len -= k\n elif N + k > M:\n diag_len = M - k\n elif k <= 0:\n if M >= N:\n diag_len += k\n elif M - k > N:\n diag_len = N + k\n diagonal_ = array_ops.ones([diag_len], dtype=dtype)\n return array_ops.matrix_diag(diagonal=diagonal_, num_rows=N, num_cols=M, k=k)\n\n\n@np_utils.np_doc('identity')\ndef identity(n, dtype=float):\n return eye(N=n, M=n, dtype=dtype)\n\n\n@np_utils.np_doc('full')\ndef full(shape, fill_value, dtype=None): # pylint: disable=redefined-outer-name\n if not isinstance(shape, np_arrays.ndarray):\n shape = asarray(np_arrays.convert_to_tensor(shape, dtype_hint=np.int32))\n shape = atleast_1d(shape)\n fill_value = asarray(fill_value, dtype=dtype)\n return array_ops.broadcast_to(fill_value, shape)\n\n\n# Using doc only here since np full_like signature doesn't seem to have the\n# shape argument (even though it exists in the documentation online).\n@np_utils.np_doc_only('full_like')\ndef full_like(a, fill_value, dtype=None, order='K', subok=True, shape=None): # pylint: disable=missing-docstring,redefined-outer-name\n \"\"\"order, subok and shape arguments mustn't be changed.\"\"\"\n if order != 'K':\n raise ValueError('Non-standard orders are not supported.')\n if not subok:\n raise ValueError('subok being False is not supported.')\n if shape:\n raise ValueError('Overriding the shape is not supported.')\n\n a = asarray(a)\n dtype = dtype or np_utils.result_type(a)\n fill_value = asarray(fill_value, dtype=dtype)\n return array_ops.broadcast_to(fill_value, array_ops.shape(a))\n\n\ndef _array_internal(val, dtype=None, copy=True, ndmin=0): # pylint: disable=redefined-outer-name\n \"\"\"Main implementation of np.array().\"\"\"\n result_t = val\n\n if not isinstance(result_t, ops.Tensor):\n if not dtype:\n dtype = np_utils.result_type(result_t)\n # We can't call `convert_to_tensor(result_t, dtype=dtype)` here because\n # convert_to_tensor doesn't allow incompatible arguments such as (5.5, int)\n # while np.array allows them. We need to convert-then-cast.\n\n # EagerTensor conversion complains about \"mixed types\" when converting\n # tensors with no dtype information. This is because it infers types based\n # on one selected item in the list. So e.g. when converting [2., 2j]\n # to a tensor, it will select float32 as the inferred type and not be able\n # to convert the list to a float 32 tensor.\n # Since we have some information about the final dtype we care about, we\n # supply that information so that convert_to_tensor will do best-effort\n # conversion to that dtype first.\n result_t = np_arrays.convert_to_tensor(result_t, dtype_hint=dtype)\n result_t = math_ops.cast(result_t, dtype=dtype)\n elif dtype:\n result_t = math_ops.cast(result_t, dtype)\n\n if copy:\n result_t = array_ops.identity(result_t)\n\n if ndmin == 0:\n return result_t\n\n ndims = array_ops.rank(result_t)\n\n def true_fn():\n old_shape = array_ops.shape(result_t)\n new_shape = array_ops.concat(\n [array_ops.ones(ndmin - ndims, dtypes.int32), old_shape], axis=0)\n return array_ops.reshape(result_t, new_shape)\n\n result_t = np_utils.cond(\n np_utils.greater(ndmin, ndims), true_fn, lambda: result_t)\n return result_t\n\n\n# TODO(wangpeng): investigate whether we can make `copy` default to False.\n# pylint: disable=g-short-docstring-punctuation,g-no-space-after-docstring-summary,g-doc-return-or-yield,g-doc-args\n@np_utils.np_doc_only('array')\ndef array(val, dtype=None, copy=True, ndmin=0): # pylint: disable=redefined-outer-name\n \"\"\"Since Tensors are immutable, a copy is made only if val is placed on a\n\n different device than the current one. Even if `copy` is False, a new Tensor\n may need to be built to satisfy `dtype` and `ndim`. This is used only if `val`\n is an ndarray or a Tensor.\n \"\"\" # pylint:disable=g-docstring-missing-newline\n if dtype:\n dtype = np_utils.result_type(dtype)\n return _array_internal(val, dtype, copy, ndmin)\n\n\n# pylint: enable=g-short-docstring-punctuation,g-no-space-after-docstring-summary,g-doc-return-or-yield,g-doc-args\n\n\n@np_utils.np_doc('asarray')\ndef asarray(a, dtype=None):\n if dtype:\n dtype = np_utils.result_type(dtype)\n if isinstance(a, np_arrays.ndarray) and (\n not dtype or dtype == a.dtype.as_numpy_dtype):\n return a\n return array(a, dtype, copy=False)\n\n\n@np_utils.np_doc('asanyarray')\ndef asanyarray(a, dtype=None):\n return asarray(a, dtype)\n\n\n@np_utils.np_doc('ascontiguousarray')\ndef ascontiguousarray(a, dtype=None):\n return array(a, dtype, ndmin=1)\n\n\n# Numerical ranges.\n@np_utils.np_doc('arange')\ndef arange(start, stop=None, step=1, dtype=None):\n \"\"\"Returns `step`-separated values in the range [start, stop).\n\n Args:\n start: Start of the interval. Included in the range.\n stop: End of the interval. If not specified, `start` is treated as 0 and\n `start` value is used as `stop`. If specified, it is not included in the\n range if `step` is integer. When `step` is floating point, it may or may\n not be included.\n step: The difference between 2 consecutive values in the output range. It is\n recommended to use `linspace` instead of using non-integer values for\n `step`.\n dtype: Optional. Type of the resulting ndarray. Could be a python type, a\n NumPy type or a TensorFlow `DType`. If not provided, the largest type of\n `start`, `stop`, `step` is used.\n\n Raises:\n ValueError: If step is zero.\n \"\"\"\n if not step:\n raise ValueError('step must be non-zero.')\n if dtype:\n dtype = np_utils.result_type(dtype)\n else:\n if stop is None:\n dtype = np_utils.result_type(start, step)\n else:\n dtype = np_utils.result_type(start, step, stop)\n if step > 0 and ((stop is not None and start > stop) or\n (stop is None and start < 0)):\n return array([], dtype=dtype)\n if step < 0 and ((stop is not None and start < stop) or\n (stop is None and start > 0)):\n return array([], dtype=dtype)\n # TODO(srbs): There are some bugs when start or stop is float type and dtype\n # is integer type.\n return math_ops.cast(\n math_ops.range(start, limit=stop, delta=step), dtype=dtype)\n\n\n# Building matrices.\n@np_utils.np_doc('diag')\ndef diag(v, k=0): # pylint: disable=missing-docstring\n \"\"\"Raises an error if input is not 1- or 2-d.\"\"\"\n v = asarray(v)\n v_rank = array_ops.rank(v)\n\n v.shape.with_rank_at_most(2)\n\n # TODO(nareshmodi): Consider a np_utils.Assert version that will fail during\n # tracing time if the shape is known.\n control_flow_ops.Assert(\n np_utils.logical_or(math_ops.equal(v_rank, 1), math_ops.equal(v_rank, 2)),\n [v_rank])\n\n def _diag(v, k):\n return np_utils.cond(\n math_ops.equal(array_ops.size(v), 0),\n lambda: array_ops.zeros([abs(k), abs(k)], dtype=v.dtype),\n lambda: array_ops.matrix_diag(v, k=k))\n\n def _diag_part(v, k):\n v_shape = array_ops.shape(v)\n v, k = np_utils.cond(\n np_utils.logical_or(\n np_utils.less_equal(k, -1 * np_utils.getitem(v_shape, 0)),\n np_utils.greater_equal(k, np_utils.getitem(v_shape, 1)),\n ), lambda: (array_ops.zeros([0, 0], dtype=v.dtype), 0), lambda: (v, k))\n result = array_ops.matrix_diag_part(v, k=k)\n return result\n\n result = np_utils.cond(\n math_ops.equal(v_rank, 1), lambda: _diag(v, k), lambda: _diag_part(v, k))\n return result\n\n\n@np_utils.np_doc('diagonal')\ndef diagonal(a, offset=0, axis1=0, axis2=1): # pylint: disable=missing-docstring\n a = asarray(a)\n\n maybe_rank = a.shape.rank\n if maybe_rank is not None and offset == 0 and (\n axis1 == maybe_rank - 2 or axis1 == -2) and (axis2 == maybe_rank - 1 or\n axis2 == -1):\n return array_ops.matrix_diag_part(a)\n\n a = moveaxis(a, (axis1, axis2), (-2, -1))\n\n a_shape = array_ops.shape(a)\n\n def _zeros(): # pylint: disable=missing-docstring\n return (array_ops.zeros(\n array_ops.concat([a_shape[:-1], [0]], 0), dtype=a.dtype), 0)\n\n # All zeros since diag_part doesn't handle all possible k (aka offset).\n # Written this way since cond will run shape inference on both branches,\n # and diag_part shape inference will fail when offset is out of bounds.\n a, offset = np_utils.cond(\n np_utils.logical_or(\n np_utils.less_equal(offset, -1 * np_utils.getitem(a_shape, -2)),\n np_utils.greater_equal(offset, np_utils.getitem(a_shape, -1)),\n ), _zeros, lambda: (a, offset))\n\n a = array_ops.matrix_diag_part(a, k=offset)\n return a\n\n\n@np_utils.np_doc('diagflat')\ndef diagflat(v, k=0):\n v = asarray(v)\n return diag(array_ops.reshape(v, [-1]), k)\n\n\ndef _promote_dtype(*arrays):\n dtype = np_utils.result_type(*arrays)\n def _fast_asarray(a):\n if isinstance(a, np_arrays.ndarray) and dtype == a.dtype.as_numpy_dtype:\n return a\n return _array_internal(a, dtype=dtype, copy=False)\n return [_fast_asarray(a) for a in arrays]\n\n\ndef _promote_dtype_binary(t1, t2):\n dtype = np_utils._result_type_binary(t1, t2) # pylint: disable=protected-access\n if not(\n isinstance(t1, np_arrays.ndarray) and dtype == t1.dtype.as_numpy_dtype):\n t1 = _array_internal(t1, dtype=dtype, copy=False)\n if not(\n isinstance(t2, np_arrays.ndarray) and dtype == t2.dtype.as_numpy_dtype):\n t2 = _array_internal(t2, dtype=dtype, copy=False)\n return t1, t2\n\n\n@np_utils.np_doc('all')\ndef all(a, axis=None, keepdims=None): # pylint: disable=redefined-builtin\n a = asarray(a, dtype=bool)\n return math_ops.reduce_all(input_tensor=a, axis=axis, keepdims=keepdims)\n\n\n@np_utils.np_doc('any')\ndef any(a, axis=None, keepdims=None): # pylint: disable=redefined-builtin\n a = asarray(a, dtype=bool)\n return math_ops.reduce_any(input_tensor=a, axis=axis, keepdims=keepdims)\n\n\n@np_utils.np_doc('compress')\ndef compress(condition, a, axis=None): # pylint: disable=redefined-outer-name,missing-function-docstring\n condition = asarray(condition, dtype=bool)\n a = asarray(a)\n\n if condition.ndim != 1:\n raise ValueError('condition must be a 1-d array.')\n # `np.compress` treats scalars as 1-d arrays.\n if a.ndim == 0:\n a = ravel(a)\n\n if axis is None:\n a = ravel(a)\n axis = 0\n\n if axis < 0:\n axis += a.ndim\n\n assert axis >= 0 and axis < a.ndim\n\n # `tf.boolean_mask` requires the first dimensions of array and condition to\n # match. `np.compress` pads condition with False when it is shorter.\n condition_t = condition\n a_t = a\n if condition.shape[0] < a.shape[axis]:\n padding = array_ops.fill([a.shape[axis] - condition.shape[0]], False)\n condition_t = array_ops.concat([condition_t, padding], axis=0)\n return array_ops.boolean_mask(tensor=a_t, mask=condition_t, axis=axis)\n\n\n@np_utils.np_doc('copy')\ndef copy(a):\n return array(a, copy=True)\n\n\ndef _maybe_promote_to_int(a):\n if dtypes.as_dtype(a.dtype).is_integer:\n # If a is an integer type and its precision is less than that of `int`,\n # the output type will be `int`.\n a_numpy_dtype = a.dtype.as_numpy_dtype\n output_type = np.promote_types(a_numpy_dtype, int)\n if output_type != a_numpy_dtype:\n a = asarray(a, dtype=output_type)\n\n return a\n\n\n@np_utils.np_doc('cumprod')\ndef cumprod(a, axis=None, dtype=None): # pylint: disable=missing-docstring\n a = asarray(a, dtype=dtype)\n\n if dtype is None:\n a = _maybe_promote_to_int(a)\n\n # If axis is None, the input is flattened.\n if axis is None:\n a = ravel(a)\n axis = 0\n elif axis < 0:\n axis += array_ops.rank(a)\n return math_ops.cumprod(a, axis)\n\n\n@np_utils.np_doc('cumsum')\ndef cumsum(a, axis=None, dtype=None): # pylint: disable=missing-docstring\n a = asarray(a, dtype=dtype)\n\n if dtype is None:\n a = _maybe_promote_to_int(a)\n\n # If axis is None, the input is flattened.\n if axis is None:\n a = ravel(a)\n axis = 0\n elif axis < 0:\n axis += array_ops.rank(a)\n return math_ops.cumsum(a, axis)\n\n\n@np_utils.np_doc('imag')\ndef imag(val):\n val = asarray(val)\n # TODO(srbs): np.imag returns a scalar if `val` is a scalar, whereas we always\n # return an ndarray.\n return math_ops.imag(val)\n\n\n_TO_INT_ = 0\n_TO_FLOAT = 1\n\n\ndef _reduce(tf_fn,\n a,\n axis=None,\n dtype=None,\n keepdims=None,\n promote_int=_TO_INT_,\n tf_bool_fn=None,\n preserve_bool=False):\n \"\"\"A general reduction function.\n\n Args:\n tf_fn: the TF reduction function.\n a: the array to be reduced.\n axis: (optional) the axis along which to do the reduction. If None, all\n dimensions are reduced.\n dtype: (optional) the dtype of the result.\n keepdims: (optional) whether to keep the reduced dimension(s).\n promote_int: how to promote integer and bool inputs. There are three\n choices. (1) `_TO_INT_` always promotes them to np.int_ or np.uint; (2)\n `_TO_FLOAT` always promotes them to a float type (determined by\n dtypes.default_float_type); (3) None: don't promote.\n tf_bool_fn: (optional) the TF reduction function for bool inputs. It will\n only be used if `dtype` is explicitly set to `np.bool_` or if `a`'s dtype\n is `np.bool_` and `preserve_bool` is True.\n preserve_bool: a flag to control whether to use `tf_bool_fn` if `a`'s dtype\n is `np.bool_` (some reductions such as np.sum convert bools to integers,\n while others such as np.max preserve bools.\n\n Returns:\n An ndarray.\n \"\"\"\n if dtype:\n dtype = np_utils.result_type(dtype)\n if keepdims is None:\n keepdims = False\n a = asarray(a, dtype=dtype)\n if ((dtype == np.bool_ or preserve_bool and a.dtype == np.bool_) and\n tf_bool_fn is not None):\n return tf_bool_fn(input_tensor=a, axis=axis, keepdims=keepdims)\n if dtype is None:\n dtype = a.dtype.as_numpy_dtype\n if np.issubdtype(dtype, np.integer) or dtype == np.bool_:\n if promote_int == _TO_INT_:\n # If a is an integer/bool type and whose bit width is less than np.int_,\n # numpy up-casts it to np.int_ based on the documentation at\n # https://numpy.org/doc/1.18/reference/generated/numpy.sum.html\n if dtype == np.bool_:\n is_signed = True\n width = 8 # We can use any number here that is less than 64\n else:\n is_signed = np.issubdtype(dtype, np.signedinteger)\n width = np.iinfo(dtype).bits\n # Numpy int_ and uint are defined as 'long' and 'unsigned long', so\n # should have the same bit width.\n if width < np.iinfo(np.int_).bits:\n if is_signed:\n dtype = np.int_\n else:\n dtype = np.uint\n a = math_ops.cast(a, dtype)\n elif promote_int == _TO_FLOAT:\n a = math_ops.cast(a, np_dtypes.default_float_type())\n\n if isinstance(axis, ops.Tensor) and axis.dtype not in (\n dtypes.int32, dtypes.int64):\n axis = math_ops.cast(axis, dtypes.int64)\n\n return tf_fn(input_tensor=a, axis=axis, keepdims=keepdims)\n\n\n# TODO (DarrenZhang01): Add `axis` support to the `size` API.\n@np_utils.np_doc('size')\ndef size(x, axis=None): # pylint: disable=missing-docstring\n if axis is not None:\n raise NotImplementedError('axis argument is not supported in the current '\n '`np.size` implementation')\n if isinstance(x, (int, float, np.int32, np.int64, np.float32, np.float64)):\n return 1\n x = asarray(x)\n if x.shape.is_fully_defined():\n return np.prod(x.shape.as_list(), dtype=int)\n else:\n return array_ops.size_v2(x)\n\n\n@np_utils.np_doc('sum')\ndef sum(a, axis=None, dtype=None, keepdims=None): # pylint: disable=redefined-builtin\n return _reduce(\n math_ops.reduce_sum,\n a,\n axis=axis,\n dtype=dtype,\n keepdims=keepdims,\n tf_bool_fn=math_ops.reduce_any)\n\n\n@np_utils.np_doc('prod')\ndef prod(a, axis=None, dtype=None, keepdims=None):\n return _reduce(\n math_ops.reduce_prod,\n a,\n axis=axis,\n dtype=dtype,\n keepdims=keepdims,\n tf_bool_fn=math_ops.reduce_all)\n\n\n@np_utils.np_doc('mean', unsupported_params=['out'])\ndef mean(a, axis=None, dtype=None, out=None, keepdims=None):\n if out is not None:\n raise ValueError('Setting out is not supported.')\n return _reduce(\n math_ops.reduce_mean,\n a,\n axis=axis,\n dtype=dtype,\n keepdims=keepdims,\n promote_int=_TO_FLOAT)\n\n\n@np_utils.np_doc('amax', unsupported_params=['out'])\ndef amax(a, axis=None, out=None, keepdims=None):\n if out is not None:\n raise ValueError('Setting out is not supported.')\n return _reduce(\n math_ops.reduce_max,\n a,\n axis=axis,\n dtype=None,\n keepdims=keepdims,\n promote_int=None,\n tf_bool_fn=math_ops.reduce_any,\n preserve_bool=True)\n\n\n@np_utils.np_doc('amin', unsupported_params=['out'])\ndef amin(a, axis=None, out=None, keepdims=None):\n if out is not None:\n raise ValueError('Setting out is not supported.')\n return _reduce(\n math_ops.reduce_min,\n a,\n axis=axis,\n dtype=None,\n keepdims=keepdims,\n promote_int=None,\n tf_bool_fn=math_ops.reduce_all,\n preserve_bool=True)\n\n\n@np_utils.np_doc('var')\ndef var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=None): # pylint: disable=missing-docstring\n if dtype:\n working_dtype = np_utils.result_type(a, dtype)\n else:\n working_dtype = None\n if out is not None:\n raise ValueError('Setting out is not supported.')\n if ddof != 0:\n # TF reduce_variance doesn't support ddof, so calculate it using raw ops.\n def reduce_fn(input_tensor, axis, keepdims):\n means = math_ops.reduce_mean(input_tensor, axis=axis, keepdims=True)\n centered = input_tensor - means\n if input_tensor.dtype in (dtypes.complex64, dtypes.complex128):\n centered = math_ops.cast(\n math_ops.real(centered * math_ops.conj(centered)),\n input_tensor.dtype)\n else:\n centered = math_ops.square(centered)\n squared_deviations = math_ops.reduce_sum(\n centered, axis=axis, keepdims=keepdims)\n\n if axis is None:\n n = array_ops.size(input_tensor)\n else:\n if axis < 0:\n axis += array_ops.rank(input_tensor)\n n = math_ops.reduce_prod(\n array_ops.gather(array_ops.shape(input_tensor), axis))\n n = math_ops.cast(n - ddof, input_tensor.dtype)\n\n return math_ops.cast(math_ops.divide(squared_deviations, n), dtype)\n else:\n reduce_fn = math_ops.reduce_variance\n\n result = _reduce(\n reduce_fn,\n a,\n axis=axis,\n dtype=working_dtype,\n keepdims=keepdims,\n promote_int=_TO_FLOAT)\n if dtype:\n result = math_ops.cast(result, dtype)\n return result\n\n\n@np_utils.np_doc('std')\ndef std(a, axis=None, keepdims=None): # pylint: disable=missing-function-docstring\n return _reduce(\n math_ops.reduce_std,\n a,\n axis=axis,\n dtype=None,\n keepdims=keepdims,\n promote_int=_TO_FLOAT)\n\n\n@np_utils.np_doc('ravel')\ndef ravel(a): # pylint: disable=missing-docstring\n a = asarray(a)\n return array_ops.reshape(a, [-1])\n\n\n@np_utils.np_doc('real')\ndef real(val):\n val = asarray(val)\n # TODO(srbs): np.real returns a scalar if val is a scalar, whereas we always\n # return an ndarray.\n return math_ops.real(val)\n\n\n@np_utils.np_doc('repeat')\ndef repeat(a, repeats, axis=None): # pylint: disable=missing-docstring\n a = asarray(a)\n original_shape = a._shape_as_list() # pylint: disable=protected-access\n # Best effort recovery of the shape.\n known_shape = original_shape is not None and None not in original_shape\n if known_shape:\n if not original_shape:\n original_shape = (repeats,)\n else:\n repeats_np = np.ravel(np.array(repeats))\n if repeats_np.size == 1:\n repeats_np = repeats_np.item()\n if axis is None:\n original_shape = (repeats_np * np.prod(original_shape),)\n else:\n original_shape[axis] = repeats_np * original_shape[axis]\n else:\n if axis is None:\n original_shape = (repeats_np.sum(),)\n else:\n original_shape[axis] = repeats_np.sum()\n\n repeats = asarray(repeats)\n result = array_ops.repeat(a, repeats, axis)\n if known_shape:\n result.set_shape(original_shape)\n\n return result\n\n\n@np_utils.np_doc('around')\ndef around(a, decimals=0): # pylint: disable=missing-docstring\n a = asarray(a)\n dtype = a.dtype.as_numpy_dtype\n factor = math.pow(10, decimals)\n if np.issubdtype(dtype, np.inexact):\n factor = math_ops.cast(factor, dtype)\n else:\n # Use float as the working dtype when a.dtype is exact (e.g. integer),\n # because `decimals` can be negative.\n float_dtype = np_dtypes.default_float_type()\n a = a.astype(float_dtype)\n factor = math_ops.cast(factor, float_dtype)\n a = math_ops.multiply(a, factor)\n a = math_ops.round(a)\n a = math_ops.divide(a, factor)\n return a.astype(dtype)\n\n\nsetattr(np_arrays.ndarray, '__round__', around)\n\n\n@np_utils.np_doc('reshape')\ndef reshape(a, newshape, order='C'):\n \"\"\"order argument can only b 'C' or 'F'.\"\"\"\n if order not in {'C', 'F'}:\n raise ValueError('Unsupported order argument {}'.format(order))\n\n a = asarray(a)\n if isinstance(newshape, int):\n newshape = [newshape]\n\n if order == 'F':\n r = array_ops.transpose(\n array_ops.reshape(array_ops.transpose(a), newshape[::-1]))\n else:\n r = array_ops.reshape(a, newshape)\n\n return r\n\n\ndef _reshape_method_wrapper(a, *newshape, **kwargs):\n order = kwargs.pop('order', 'C')\n if kwargs:\n raise ValueError('Unsupported arguments: {}'.format(kwargs.keys()))\n\n if len(newshape) == 1 and not isinstance(newshape[0], int):\n newshape = newshape[0]\n\n return reshape(a, newshape, order=order)\n\n\n@np_utils.np_doc('expand_dims')\ndef expand_dims(a, axis):\n a = asarray(a)\n return array_ops.expand_dims(a, axis=axis)\n\n\n@np_utils.np_doc('squeeze')\ndef squeeze(a, axis=None):\n a = asarray(a)\n return array_ops.squeeze(a, axis)\n\n\n@np_utils.np_doc('transpose')\ndef transpose(a, axes=None):\n a = asarray(a)\n if axes is not None:\n axes = asarray(axes)\n return array_ops.transpose(a=a, perm=axes)\n\n\n@np_utils.np_doc('swapaxes')\ndef swapaxes(a, axis1, axis2): # pylint: disable=missing-docstring\n a = asarray(a)\n def adjust_axes(axes, rank):\n def f(x):\n if isinstance(x, int):\n if x < 0:\n x = x + rank\n else:\n x = array_ops.where_v2(x < 0, np_utils.add(x, a_rank), x)\n return x\n return nest.map_structure(f, axes)\n\n if (a.shape.rank is not None and\n isinstance(axis1, int) and isinstance(axis2, int)):\n # This branch makes sure `perm` is statically known, to avoid a\n # not-compile-time-constant XLA error.\n a_rank = a.shape.rank\n axis1, axis2 = adjust_axes((axis1, axis2), a_rank)\n perm = list(range(a_rank))\n perm[axis1] = axis2\n perm[axis2] = axis1\n else:\n a_rank = array_ops.rank(a)\n axis1, axis2 = adjust_axes((axis1, axis2), a_rank)\n perm = math_ops.range(a_rank)\n perm = array_ops.tensor_scatter_update(perm, [[axis1], [axis2]],\n [axis2, axis1])\n a = array_ops.transpose(a, perm)\n return a\n\n\n@np_utils.np_doc('moveaxis')\ndef moveaxis(a, source, destination): # pylint: disable=missing-docstring\n \"\"\"Raises ValueError if source, destination not in (-ndim(a), ndim(a)).\"\"\"\n if not source and not destination:\n return a\n\n a = asarray(a)\n\n if isinstance(source, int):\n source = (source,)\n if isinstance(destination, int):\n destination = (destination,)\n if len(source) != len(destination):\n raise ValueError('The lengths of source and destination must equal')\n\n a_rank = np_utils._maybe_static(array_ops.rank(a)) # pylint: disable=protected-access\n\n def _correct_axis(axis, rank):\n if axis < 0:\n return axis + rank\n return axis\n\n source = tuple(_correct_axis(axis, a_rank) for axis in source)\n destination = tuple(_correct_axis(axis, a_rank) for axis in destination)\n\n if a.shape.rank is not None:\n perm = [i for i in range(a_rank) if i not in source]\n for dest, src in sorted(zip(destination, source)):\n assert dest <= len(perm)\n perm.insert(dest, src)\n else:\n r = math_ops.range(a_rank)\n\n def _remove_indices(a, b):\n \"\"\"Remove indices (`b`) from `a`.\"\"\"\n items = array_ops.unstack(sort_ops.sort(array_ops.stack(b)), num=len(b))\n\n i = 0\n result = []\n\n for item in items:\n result.append(a[i:item])\n i = item + 1\n\n result.append(a[i:])\n\n return array_ops.concat(result, 0)\n\n minus_sources = _remove_indices(r, source)\n minus_dest = _remove_indices(r, destination)\n\n perm = array_ops.scatter_nd(\n array_ops.expand_dims(minus_dest, 1), minus_sources, [a_rank])\n perm = array_ops.tensor_scatter_update(\n perm, array_ops.expand_dims(destination, 1), source)\n a = array_ops.transpose(a, perm)\n\n return a\n\n\n@np_utils.np_doc('pad')\ndef pad(array, pad_width, mode, **kwargs): # pylint: disable=redefined-outer-name\n \"\"\"Only supports modes 'constant', 'reflect' and 'symmetric' currently.\"\"\"\n constant_values = kwargs.get('constant_values', 0)\n if not (mode == 'constant' or mode == 'reflect' or mode == 'symmetric'):\n raise ValueError('Unsupported padding mode: ' + mode)\n mode = mode.upper()\n array = asarray(array)\n pad_width = asarray(pad_width, dtype=dtypes.int32)\n return array_ops.pad(\n tensor=array,\n paddings=pad_width,\n mode=mode,\n constant_values=constant_values)\n\n\n@np_utils.np_doc('take')\ndef take(a, indices, axis=None, out=None, mode='clip'):\n \"\"\"out argument is not supported, and default mode is clip.\"\"\"\n if out is not None:\n raise ValueError('out argument is not supported in take.')\n\n if mode not in {'raise', 'clip', 'wrap'}:\n raise ValueError(\"Invalid mode '{}' for take\".format(mode))\n\n a = asarray(a)\n indices = asarray(indices)\n\n if axis is None:\n a = array_ops.reshape(a, [-1])\n axis = 0\n\n axis_size = array_ops.shape(a, out_type=indices.dtype)[axis]\n if mode == 'clip':\n indices = clip_ops.clip_by_value(indices, 0, axis_size - 1)\n elif mode == 'wrap':\n indices = math_ops.floormod(indices, axis_size)\n else:\n raise ValueError(\"The 'raise' mode to take is not supported.\")\n\n return array_ops.gather(a, indices, axis=axis)\n\n\n@np_utils.np_doc_only('where')\ndef where(condition, x=None, y=None):\n \"\"\"Raises ValueError if exactly one of x or y is not None.\"\"\"\n condition = asarray(condition, dtype=np.bool_)\n if x is None and y is None:\n return nonzero(condition)\n elif x is not None and y is not None:\n x, y = _promote_dtype(x, y)\n return array_ops.where_v2(condition, x, y)\n raise ValueError('Both x and y must be ndarrays, or both must be None.')\n\n\n@np_utils.np_doc('select')\ndef select(condlist, choicelist, default=0): # pylint: disable=missing-docstring\n if len(condlist) != len(choicelist):\n msg = 'condlist must have length equal to choicelist ({} vs {})'\n raise ValueError(msg.format(len(condlist), len(choicelist)))\n if not condlist:\n raise ValueError('condlist must be non-empty')\n choices = _promote_dtype(default, *choicelist)\n choicelist = choices[1:]\n output = choices[0]\n # The traversal is in reverse order so we can return the first value in\n # choicelist where condlist is True.\n for cond, choice in zip(condlist[::-1], choicelist[::-1]):\n output = where(cond, choice, output)\n return output\n\n\n@np_utils.np_doc('shape', link=np_utils.Link(\n 'https://numpy.org/doc/1.18/reference/generated/numpy.shape.html'))\ndef shape(a):\n a = asarray(a)\n return a.shape\n\n\n@np_utils.np_doc('ndim', link=np_utils.NoLink())\ndef ndim(a):\n a = asarray(a)\n return a.ndim\n\n\n@np_utils.np_doc('isscalar')\ndef isscalar(num):\n return ndim(num) == 0\n\n\ndef _boundaries_to_sizes(a, boundaries, axis):\n \"\"\"Converting boundaries of splits to sizes of splits.\n\n Args:\n a: the array to be split.\n boundaries: the boundaries, as in np.split.\n axis: the axis along which to split.\n\n Returns:\n A list of sizes of the splits, as in tf.split.\n \"\"\"\n if axis >= len(a.shape):\n raise ValueError('axis %s is out of bound for shape %s' % (axis, a.shape))\n total_size = a.shape[axis]\n sizes = []\n sizes_sum = 0\n prev = 0\n for i, b in enumerate(boundaries):\n size = b - prev\n if size < 0:\n raise ValueError('The %s-th boundary %s is smaller than the previous '\n 'boundary %s' % (i, b, prev))\n size = min(size, max(0, total_size - sizes_sum))\n sizes.append(size)\n sizes_sum += size\n prev = b\n sizes.append(max(0, total_size - sizes_sum))\n return sizes\n\n\n@np_utils.np_doc('split')\ndef split(ary, indices_or_sections, axis=0):\n ary = asarray(ary)\n if not isinstance(indices_or_sections, six.integer_types):\n indices_or_sections = _boundaries_to_sizes(ary, indices_or_sections, axis)\n return array_ops.split(ary, indices_or_sections, axis=axis)\n\n\ndef _split_on_axis(np_fun_name, axis):\n\n @np_utils.np_doc(np_fun_name)\n def f(ary, indices_or_sections):\n return split(ary, indices_or_sections, axis=axis)\n\n return f\n\n\nvsplit = _split_on_axis('vsplit', axis=0)\nhsplit = _split_on_axis('hsplit', axis=1)\ndsplit = _split_on_axis('dsplit', axis=2)\n\n\n@np_utils.np_doc('broadcast_to')\ndef broadcast_to(array, shape): # pylint: disable=redefined-outer-name\n return full(shape, array)\n\n\n@np_utils.np_doc('stack')\ndef stack(arrays, axis=0): # pylint: disable=missing-function-docstring\n if isinstance(arrays, (np_arrays.ndarray, ops.Tensor)):\n arrays = asarray(arrays)\n if axis == 0:\n return arrays\n else:\n return swapaxes(arrays, 0, axis)\n arrays = _promote_dtype(*arrays) # pylint: disable=protected-access\n unwrapped_arrays = [\n a if isinstance(a, np_arrays.ndarray) else a for a in arrays\n ]\n return asarray(array_ops.stack(unwrapped_arrays, axis))\n\n\n@np_utils.np_doc('hstack')\ndef hstack(tup):\n arrays = [atleast_1d(a) for a in tup]\n arrays = _promote_dtype(*arrays) # pylint: disable=protected-access\n unwrapped_arrays = [\n a if isinstance(a, np_arrays.ndarray) else a for a in arrays\n ]\n rank = array_ops.rank(unwrapped_arrays[0])\n return np_utils.cond(\n math_ops.equal(rank,\n 1), lambda: array_ops.concat(unwrapped_arrays, axis=0),\n lambda: array_ops.concat(unwrapped_arrays, axis=1))\n\n\n@np_utils.np_doc('vstack')\ndef vstack(tup):\n arrays = [atleast_2d(a) for a in tup]\n arrays = _promote_dtype(*arrays) # pylint: disable=protected-access\n unwrapped_arrays = [\n a if isinstance(a, np_arrays.ndarray) else a for a in arrays\n ]\n return array_ops.concat(unwrapped_arrays, axis=0)\n\n\n@np_utils.np_doc('dstack')\ndef dstack(tup):\n arrays = [atleast_3d(a) for a in tup]\n arrays = _promote_dtype(*arrays) # pylint: disable=protected-access\n unwrapped_arrays = [\n a if isinstance(a, np_arrays.ndarray) else a for a in arrays\n ]\n return array_ops.concat(unwrapped_arrays, axis=2)\n\n\ndef _pad_left_to(n, old_shape):\n old_shape = asarray(old_shape, dtype=np.int32)\n new_shape = array_ops.pad(\n old_shape, [[math_ops.maximum(n - array_ops.size(old_shape), 0), 0]],\n constant_values=1)\n return asarray(new_shape)\n\n\ndef _atleast_nd(n, new_shape, *arys):\n \"\"\"Reshape arrays to be at least `n`-dimensional.\n\n Args:\n n: The minimal rank.\n new_shape: a function that takes `n` and the old shape and returns the\n desired new shape.\n *arys: ndarray(s) to be reshaped.\n\n Returns:\n The reshaped array(s).\n \"\"\"\n\n def f(x):\n # pylint: disable=g-long-lambda\n x = asarray(x)\n return asarray(\n np_utils.cond(\n np_utils.greater(n, array_ops.rank(x)),\n lambda: reshape(x, new_shape(n, array_ops.shape(x))),\n lambda: x))\n\n arys = list(map(f, arys))\n if len(arys) == 1:\n return arys[0]\n else:\n return arys\n\n\n@np_utils.np_doc('atleast_1d')\ndef atleast_1d(*arys):\n return _atleast_nd(1, _pad_left_to, *arys)\n\n\n@np_utils.np_doc('atleast_2d')\ndef atleast_2d(*arys):\n return _atleast_nd(2, _pad_left_to, *arys)\n\n\n@np_utils.np_doc('atleast_3d')\ndef atleast_3d(*arys): # pylint: disable=missing-docstring\n\n def new_shape(_, old_shape):\n # pylint: disable=g-long-lambda\n ndim_ = array_ops.size(old_shape)\n return np_utils.cond(\n math_ops.equal(ndim_, 0),\n lambda: constant_op.constant([1, 1, 1], dtype=dtypes.int32),\n lambda: np_utils.cond(\n math_ops.equal(ndim_, 1), lambda: array_ops.pad(\n old_shape, [[1, 1]], constant_values=1), lambda: array_ops.pad(\n old_shape, [[0, 1]], constant_values=1)))\n\n return _atleast_nd(3, new_shape, *arys)\n\n\n@np_utils.np_doc('nonzero')\ndef nonzero(a):\n a = atleast_1d(a)\n if a.shape.rank is None:\n raise ValueError(\"The rank of `a` is unknown, so we can't decide how many \"\n 'arrays to return.')\n return array_ops.unstack(\n array_ops.where_v2(math_ops.cast(a, dtypes.bool)),\n a.shape.rank,\n axis=1)\n\n\n@np_utils.np_doc('diag_indices')\ndef diag_indices(n, ndim=2): # pylint: disable=missing-docstring,redefined-outer-name\n if n < 0:\n raise ValueError(\n 'n argument to diag_indices must be nonnegative, got {}'.format(n))\n if ndim < 0:\n raise ValueError(\n 'ndim argument to diag_indices must be nonnegative, got {}'.format(\n ndim))\n\n return (math_ops.range(n),) * ndim\n\n\n@np_utils.np_doc('tri')\ndef tri(N, M=None, k=0, dtype=None): # pylint: disable=invalid-name,missing-docstring\n M = M if M is not None else N\n if dtype is not None:\n dtype = np_utils.result_type(dtype)\n else:\n dtype = np_dtypes.default_float_type()\n\n if k < 0:\n lower = -k - 1\n if lower > N:\n r = array_ops.zeros([N, M], dtype)\n else:\n # Keep as tf bool, since we create an upper triangular matrix and invert\n # it.\n o = array_ops.ones([N, M], dtype=dtypes.bool)\n r = math_ops.cast(\n math_ops.logical_not(array_ops.matrix_band_part(o, lower, -1)), dtype)\n else:\n o = array_ops.ones([N, M], dtype)\n if k > M:\n r = o\n else:\n r = array_ops.matrix_band_part(o, -1, k)\n return r\n\n\n@np_utils.np_doc('tril')\ndef tril(m, k=0): # pylint: disable=missing-docstring\n m = asarray(m)\n if m.shape.ndims is None:\n raise ValueError('Argument to tril should have known rank')\n m_shape = m.shape.as_list()\n\n if len(m_shape) < 2:\n raise ValueError('Argument to tril must have rank at least 2')\n\n if m_shape[-1] is None or m_shape[-2] is None:\n raise ValueError('Currently, the last two dimensions of the input array '\n 'need to be known.')\n\n z = constant_op.constant(0, m.dtype)\n\n mask = tri(*m_shape[-2:], k=k, dtype=bool)\n return array_ops.where_v2(\n array_ops.broadcast_to(mask, array_ops.shape(m)), m, z)\n\n\n@np_utils.np_doc('triu')\ndef triu(m, k=0): # pylint: disable=missing-docstring\n m = asarray(m)\n if m.shape.ndims is None:\n raise ValueError('Argument to triu should have known rank')\n m_shape = m.shape.as_list()\n\n if len(m_shape) < 2:\n raise ValueError('Argument to triu must have rank at least 2')\n\n if m_shape[-1] is None or m_shape[-2] is None:\n raise ValueError('Currently, the last two dimensions of the input array '\n 'need to be known.')\n\n z = constant_op.constant(0, m.dtype)\n\n mask = tri(*m_shape[-2:], k=k - 1, dtype=bool)\n return array_ops.where_v2(\n array_ops.broadcast_to(mask, array_ops.shape(m)), z, m)\n\n\n@np_utils.np_doc('flip')\ndef flip(m, axis=None): # pylint: disable=missing-docstring\n m = asarray(m)\n\n if axis is None:\n return array_ops.reverse(m, math_ops.range(array_ops.rank(m)))\n\n axis = np_utils._canonicalize_axis(axis, array_ops.rank(m)) # pylint: disable=protected-access\n\n return array_ops.reverse(m, [axis])\n\n\n@np_utils.np_doc('flipud')\ndef flipud(m): # pylint: disable=missing-docstring\n return flip(m, 0)\n\n\n@np_utils.np_doc('fliplr')\ndef fliplr(m): # pylint: disable=missing-docstring\n return flip(m, 1)\n\n\n@np_utils.np_doc('roll')\ndef roll(a, shift, axis=None): # pylint: disable=missing-docstring\n a = asarray(a)\n\n if axis is not None:\n return manip_ops.roll(a, shift, axis)\n\n # If axis is None, the roll happens as a 1-d tensor.\n original_shape = array_ops.shape(a)\n a = manip_ops.roll(array_ops.reshape(a, [-1]), shift, 0)\n return array_ops.reshape(a, original_shape)\n\n\n@np_utils.np_doc('rot90')\ndef rot90(m, k=1, axes=(0, 1)): # pylint: disable=missing-docstring\n m_rank = array_ops.rank(m)\n ax1, ax2 = np_utils._canonicalize_axes(axes, m_rank) # pylint: disable=protected-access\n\n k = k % 4\n if k == 0:\n return m\n elif k == 2:\n return flip(flip(m, ax1), ax2)\n else:\n perm = math_ops.range(m_rank)\n perm = array_ops.tensor_scatter_update(perm, [[ax1], [ax2]], [ax2, ax1])\n\n if k == 1:\n return transpose(flip(m, ax2), perm)\n else:\n return flip(transpose(m, perm), ax2)\n\n\n@np_utils.np_doc('vander')\ndef vander(x, N=None, increasing=False): # pylint: disable=missing-docstring,invalid-name\n x = asarray(x)\n\n x_shape = array_ops.shape(x)\n N = N or x_shape[0]\n\n N_temp = np_utils.get_static_value(N) # pylint: disable=invalid-name\n if N_temp is not None:\n N = N_temp\n if N < 0:\n raise ValueError('N must be nonnegative')\n else:\n control_flow_ops.Assert(N >= 0, [N])\n\n rank = array_ops.rank(x)\n rank_temp = np_utils.get_static_value(rank)\n if rank_temp is not None:\n rank = rank_temp\n if rank != 1:\n raise ValueError('x must be a one-dimensional array')\n else:\n control_flow_ops.Assert(math_ops.equal(rank, 1), [rank])\n\n if increasing:\n start = 0\n limit = N\n delta = 1\n else:\n start = N - 1\n limit = -1\n delta = -1\n\n x = array_ops.expand_dims(x, -1)\n return math_ops.pow(\n x, math_ops.cast(math_ops.range(start, limit, delta), dtype=x.dtype))\n\n\n@np_utils.np_doc('ix_')\ndef ix_(*args): # pylint: disable=missing-docstring\n n = len(args)\n output = []\n for i, a in enumerate(args):\n a = asarray(a)\n a_rank = array_ops.rank(a)\n a_rank_temp = np_utils.get_static_value(a_rank)\n if a_rank_temp is not None:\n a_rank = a_rank_temp\n if a_rank != 1:\n raise ValueError('Arguments must be 1-d, got arg {} of rank {}'.format(\n i, a_rank))\n else:\n control_flow_ops.Assert(math_ops.equal(a_rank, 1), [a_rank])\n\n new_shape = [1] * n\n new_shape[i] = -1\n dtype = a.dtype\n if dtype == dtypes.bool:\n output.append(array_ops.reshape(nonzero(a)[0], new_shape))\n elif dtype.is_integer:\n output.append(array_ops.reshape(a, new_shape))\n else:\n raise ValueError(\n 'Only integer and bool dtypes are supported, got {}'.format(dtype))\n\n return output\n\n\n@np_utils.np_doc('broadcast_arrays')\ndef broadcast_arrays(*args, **kwargs): # pylint: disable=missing-docstring\n subok = kwargs.pop('subok', False)\n if subok:\n raise ValueError('subok=True is not supported.')\n if kwargs:\n raise ValueError('Received unsupported arguments {}'.format(kwargs.keys()))\n\n args = [asarray(arg) for arg in args]\n return np_utils.tf_broadcast(*args)\n\n\n@np_utils.np_doc_only('sign')\ndef sign(x, out=None, where=None, **kwargs): # pylint: disable=missing-docstring,redefined-outer-name\n if out:\n raise ValueError('tf.numpy doesnt support setting out.')\n if where:\n raise ValueError('tf.numpy doesnt support setting where.')\n if kwargs:\n raise ValueError('tf.numpy doesnt support setting {}'.format(kwargs.keys()))\n\n x = asarray(x)\n dtype = x.dtype.as_numpy_dtype\n if np.issubdtype(dtype, np.complexfloating):\n result = math_ops.cast(math_ops.sign(math_ops.real(x)), dtype)\n else:\n result = math_ops.sign(x)\n\n return result\n\n\n# Note that np.take_along_axis may not be present in some supported versions of\n# numpy.\n@np_utils.np_doc('take_along_axis')\ndef take_along_axis(arr, indices, axis): # pylint: disable=missing-docstring\n arr = asarray(arr)\n indices = asarray(indices)\n\n if axis is None:\n return take_along_axis(arr.ravel(), indices, 0)\n\n rank = array_ops.rank(arr)\n axis = axis + rank if axis < 0 else axis\n\n # Broadcast shapes to match, ensure that the axis of interest is not\n # broadcast.\n arr_shape_original = array_ops.shape(arr)\n indices_shape_original = array_ops.shape(indices)\n arr_shape = array_ops.tensor_scatter_update(arr_shape_original, [[axis]], [1])\n indices_shape = array_ops.tensor_scatter_update(indices_shape_original,\n [[axis]], [1])\n broadcasted_shape = array_ops.broadcast_dynamic_shape(arr_shape,\n indices_shape)\n arr_shape = array_ops.tensor_scatter_update(broadcasted_shape, [[axis]],\n [arr_shape_original[axis]])\n indices_shape = array_ops.tensor_scatter_update(\n broadcasted_shape, [[axis]], [indices_shape_original[axis]])\n arr = array_ops.broadcast_to(arr, arr_shape)\n indices = array_ops.broadcast_to(indices, indices_shape)\n\n # Save indices shape so we can restore it later.\n possible_result_shape = indices.shape\n\n # Correct indices since gather doesn't correctly handle negative indices.\n indices = array_ops.where_v2(indices < 0, indices + arr_shape[axis], indices)\n\n swapaxes_ = lambda t: swapaxes(t, axis, -1)\n\n dont_move_axis_to_end = math_ops.equal(axis, np_utils.subtract(rank, 1))\n arr = np_utils.cond(dont_move_axis_to_end, lambda: arr,\n lambda: swapaxes_(arr))\n indices = np_utils.cond(dont_move_axis_to_end, lambda: indices,\n lambda: swapaxes_(indices))\n\n arr_shape = array_ops.shape(arr)\n arr = array_ops.reshape(arr, [-1, arr_shape[-1]])\n\n indices_shape = array_ops.shape(indices)\n indices = array_ops.reshape(indices, [-1, indices_shape[-1]])\n\n result = array_ops.gather(arr, indices, batch_dims=1)\n result = array_ops.reshape(result, indices_shape)\n result = np_utils.cond(dont_move_axis_to_end, lambda: result,\n lambda: swapaxes_(result))\n result.set_shape(possible_result_shape)\n\n return result\n\n\n_SLICE_ERORR = (\n 'only integers, slices (`:`), ellipsis (`...`), '\n 'numpy.newaxis (`None`) and integer or boolean arrays are valid indices')\n\n\ndef _as_index(idx, need_scalar=True):\n \"\"\"Helper function to parse idx as an index.\n\n Args:\n idx: index\n need_scalar: If idx needs to be a scalar value.\n\n Returns:\n A pair, (indx, bool). First one is the parsed index and can be a tensor,\n or scalar integer / Dimension. Second one is True if rank is known to be 0.\n\n Raises:\n IndexError: For incorrect indices.\n \"\"\"\n if isinstance(idx, (numbers.Integral, tensor_shape.Dimension)):\n return idx, True\n data = asarray(idx)\n if data.dtype == dtypes.bool:\n if data.shape.ndims != 1:\n # TODO(agarwal): handle higher rank boolean masks.\n raise NotImplementedError('Need rank 1 for bool index %s' % idx)\n data = array_ops.where_v2(data)\n data = array_ops.reshape(data, [-1])\n if need_scalar and data.shape.rank not in (None, 0):\n raise IndexError(_SLICE_ERORR + ', got {!r}'.format(idx))\n np_dtype = data.dtype.as_numpy_dtype\n if not np.issubdtype(np_dtype, np.integer):\n raise IndexError(_SLICE_ERORR + ', got {!r}'.format(idx))\n if data.dtype not in (dtypes.int64, dtypes.int32):\n # TF slicing can only handle int32/int64. So we need to cast.\n promoted_dtype = np.promote_types(np.int32, np_dtype)\n if promoted_dtype == np.int32:\n data = math_ops.cast(data, dtypes.int32)\n elif promoted_dtype == np.int64:\n data = math_ops.cast(data, dtypes.int64)\n else:\n raise IndexError(_SLICE_ERORR + ', got {!r}'.format(idx))\n return data, data.shape.rank == 0\n\n\nclass _UpdateMethod(enum.Enum):\n UPDATE = 0\n ADD = 1\n MIN = 2\n MAX = 3\n\n\ndef _slice_helper(tensor, slice_spec, update_method=None, updates=None):\n \"\"\"Helper function for __getitem__ and _with_index_update_helper.\n\n This function collects the indices in `slice_spec` into two buckets, which we\n can call \"idx1\" and \"idx2\" here. idx1 is intended for `strided_slice`, idx2\n `gather`. They also correspond to \"basic indices\" and \"advanced indices\" in\n numpy. This function supports both reading and writing at the indices. The\n reading path can be summarized as `gather(stride_slice(tensor, idx1),\n idx2)`. The writing path can be summarized as `strided_slice_update(tensor,\n idx1, scatter(strided_slice(tensor, idx1), idx2, updates))`. (`gather` here\n means `tf.gather` or `tf.gather_nd`; `scatter` here means\n `tf.tensor_scatter_update`.) The writing path is inefficient because it needs\n to first read out a portion (probably much larger than `updates`) of `tensor`\n using `strided_slice`, update it, and then write the portion back. An\n alternative approach is to only use `scatter`, which amounts to using the\n indexing mechanism of gather/scatter to implement\n strided_slice/strided_slice_update. This is feasible for XLA Gather/Scatter\n because they support spans (e.g. `2:5`) in indices (as begin/end pairs), but\n not TF gather/scatter because they don't support spans (except those that\n cover entire dimensions, i.e. `:`). If we materialize spans into individual\n indices, the size of the index tensor would explode. (Note that XLA\n Gather/Scatter have a similar problem for stride > 1 because they don't\n support strides. Indices such as `1:2:8` will need to be materialized into\n individual indices such as [1, 3, 5, 7].)\n\n Args:\n tensor: the tensor to be read from or write into.\n slice_spec: the indices.\n update_method: (optional) a member of `_UpdateMethod`, indicating how to\n update the values (replacement, add, etc.). `None` indicates just reading.\n updates: (optional) the new values to write into `tensor`. It must have the\n same dtype as `tensor`.\n\n Returns:\n The result of reading (if `update_method` is `None`) or the updated `tensor`\n after writing.\n \"\"\"\n begin, end, strides = [], [], []\n new_axis_mask, shrink_axis_mask = 0, 0\n begin_mask, end_mask = 0, 0\n ellipsis_mask = 0\n advanced_indices = []\n shrink_indices = []\n for index, s in enumerate(slice_spec):\n if isinstance(s, slice):\n if s.start is not None:\n begin.append(_as_index(s.start)[0])\n else:\n begin.append(0)\n begin_mask |= (1 << index)\n if s.stop is not None:\n end.append(_as_index(s.stop)[0])\n else:\n end.append(0)\n end_mask |= (1 << index)\n if s.step is not None:\n strides.append(_as_index(s.step)[0])\n else:\n strides.append(1)\n elif s is Ellipsis:\n begin.append(0)\n end.append(0)\n strides.append(1)\n ellipsis_mask |= (1 << index)\n elif s is array_ops.newaxis:\n begin.append(0)\n end.append(0)\n strides.append(1)\n new_axis_mask |= (1 << index)\n else:\n s, is_scalar = _as_index(s, False)\n if is_scalar:\n begin.append(s)\n end.append(s + 1)\n strides.append(1)\n shrink_axis_mask |= (1 << index)\n shrink_indices.append(index)\n else:\n begin.append(0)\n end.append(0)\n strides.append(1)\n begin_mask |= (1 << index)\n end_mask |= (1 << index)\n advanced_indices.append((index, s, ellipsis_mask != 0))\n\n # stack possibly involves no tensors, so we must use op_scope correct graph.\n with ops.name_scope(\n None,\n 'strided_slice', [tensor] + begin + end + strides,\n skip_on_eager=False) as name:\n if begin:\n packed_begin, packed_end, packed_strides = (array_ops.stack(begin),\n array_ops.stack(end),\n array_ops.stack(strides))\n if (packed_begin.dtype == dtypes.int64 or\n packed_end.dtype == dtypes.int64 or\n packed_strides.dtype == dtypes.int64):\n if packed_begin.dtype != dtypes.int64:\n packed_begin = math_ops.cast(packed_begin, dtypes.int64)\n if packed_end.dtype != dtypes.int64:\n packed_end = math_ops.cast(packed_end, dtypes.int64)\n if packed_strides.dtype != dtypes.int64:\n packed_strides = math_ops.cast(packed_strides, dtypes.int64)\n else:\n var_empty = constant_op.constant([], dtype=dtypes.int32)\n packed_begin = packed_end = packed_strides = var_empty\n if update_method == _UpdateMethod.UPDATE and not advanced_indices:\n return array_ops.tensor_strided_slice_update(\n tensor,\n packed_begin,\n packed_end,\n packed_strides,\n updates,\n begin_mask=begin_mask,\n end_mask=end_mask,\n shrink_axis_mask=shrink_axis_mask,\n new_axis_mask=new_axis_mask,\n ellipsis_mask=ellipsis_mask,\n name=name)\n else:\n # TODO(b/164251540): Find a better way to support update that does not\n # involve one read + two writes.\n if updates is not None:\n original_tensor = tensor\n # TODO(agarwal): set_shape on tensor to set rank.\n tensor = array_ops.strided_slice(\n tensor,\n packed_begin,\n packed_end,\n packed_strides,\n begin_mask=begin_mask,\n end_mask=end_mask,\n shrink_axis_mask=shrink_axis_mask,\n new_axis_mask=new_axis_mask,\n ellipsis_mask=ellipsis_mask,\n name=name)\n if not advanced_indices:\n if update_method is None:\n return tensor\n assert update_method != _UpdateMethod.UPDATE\n # TF lacks TensorStridedSliceAdd and alike, so we need to do\n # read+add+update.\n if update_method == _UpdateMethod.ADD:\n update_op = math_ops.add\n elif update_method == _UpdateMethod.MIN:\n update_op = math_ops.minimum\n elif update_method == _UpdateMethod.MAX:\n update_op = math_ops.maximum\n return array_ops.tensor_strided_slice_update(\n original_tensor,\n packed_begin,\n packed_end,\n packed_strides,\n update_op(tensor, updates),\n begin_mask=begin_mask,\n end_mask=end_mask,\n shrink_axis_mask=shrink_axis_mask,\n new_axis_mask=new_axis_mask,\n ellipsis_mask=ellipsis_mask,\n name=name + '_2')\n advanced_indices_map = {}\n for index, data, had_ellipsis in advanced_indices:\n if had_ellipsis:\n num_shrink = len([x for x in shrink_indices if x > index])\n dim = index - len(slice_spec) + num_shrink\n else:\n num_shrink = len([x for x in shrink_indices if x < index])\n dim = index - num_shrink\n advanced_indices_map[dim] = data\n dims = sorted(advanced_indices_map.keys())\n dims_contiguous = True\n if len(dims) > 1:\n if dims[0] < 0 and dims[-1] >= 0: # not all same sign\n dims_contiguous = False\n else:\n for i in range(len(dims) - 1):\n if dims[i] + 1 != dims[i + 1]:\n dims_contiguous = False\n break\n indices = [advanced_indices_map[x] for x in dims]\n indices = _promote_dtype(*indices)\n indices = np_utils.tf_broadcast(*indices)\n stacked_indices = array_ops.stack(indices, axis=-1)\n # Skip the contiguous-dims optimization for update because there is no\n # tf.*scatter* op that supports the `axis` argument.\n if not dims_contiguous or updates is not None:\n if range(len(dims)) != dims:\n tensor = moveaxis(tensor, dims, range(len(dims)))\n tensor_shape_prefix = array_ops.shape(\n tensor, out_type=stacked_indices.dtype)[:len(dims)]\n stacked_indices = array_ops.where_v2(\n stacked_indices < 0, stacked_indices + tensor_shape_prefix,\n stacked_indices)\n if updates is None:\n return array_ops.gather_nd(tensor, stacked_indices)\n else:\n # We only need to move-axis `updates` in the contiguous case becausce\n # only in this case the result dimensions of advanced indexing are in\n # the middle of `updates`. In the non-contiguous case, those dimensions\n # are always at the front.\n if dims_contiguous:\n # TODO(wangpeng): Support unknown rank (e.g. by partially flattening\n # `updates`)\n if stacked_indices.shape.rank is None:\n raise NotImplementedError(\n 'Rank of the advanced indices must currently be known')\n batch_size = stacked_indices.shape.rank - 1\n batch_start = dims[0]\n if batch_start < 0:\n batch_start += len(dims) - batch_size\n def range_(start, length):\n return range(start, start + length)\n updates = moveaxis(updates, range_(batch_start, batch_size),\n range(batch_size))\n if update_method == _UpdateMethod.UPDATE:\n update_op = array_ops.tensor_scatter_update\n elif update_method == _UpdateMethod.ADD:\n update_op = array_ops.tensor_scatter_add\n elif update_method == _UpdateMethod.MIN:\n update_op = array_ops.tensor_scatter_min\n elif update_method == _UpdateMethod.MAX:\n update_op = array_ops.tensor_scatter_max\n tensor = update_op(\n tensor, stacked_indices, updates)\n if range(len(dims)) != dims:\n tensor = moveaxis(tensor, range(len(dims)), dims)\n return array_ops.tensor_strided_slice_update(\n original_tensor,\n packed_begin,\n packed_end,\n packed_strides,\n tensor,\n begin_mask=begin_mask,\n end_mask=end_mask,\n shrink_axis_mask=shrink_axis_mask,\n new_axis_mask=new_axis_mask,\n ellipsis_mask=ellipsis_mask,\n name=name + '_2')\n # Note that gather_nd does not support gathering from inside the array.\n # To avoid shuffling data back and forth, we transform the indices and\n # do a gather instead.\n rank = np_utils._maybe_static(array_ops.rank(tensor)) # pylint: disable=protected-access\n dims = [(x + rank if x < 0 else x) for x in dims]\n shape_tensor = array_ops.shape(tensor)\n dim_sizes = array_ops.gather(shape_tensor, dims)\n if len(dims) == 1:\n stacked_indices = indices[0]\n stacked_indices = math_ops.cast(stacked_indices, dtypes.int32)\n stacked_indices = array_ops.where_v2(stacked_indices < 0,\n stacked_indices + dim_sizes,\n stacked_indices)\n axis = dims[0]\n if len(dims) > 1:\n index_scaling = math_ops.cumprod(\n dim_sizes, reverse=True, exclusive=True)\n def _tensordot(a, b):\n # TODO(b/168657656): This function should be replaced by\n # tensordot(axis=1) once MatMul has int32 XLA kernel.\n b = array_ops.broadcast_to(b, array_ops.shape(a))\n return math_ops.reduce_sum(a * b, axis=-1)\n stacked_indices = _tensordot(stacked_indices, index_scaling)\n flat_shape = array_ops.concat(\n [shape_tensor[:axis], [-1], shape_tensor[axis + len(dims):]],\n axis=0)\n tensor = array_ops.reshape(tensor, flat_shape)\n\n return array_ops.gather(tensor, stacked_indices, axis=axis)\n\n\ndef _as_spec_tuple(slice_spec):\n \"\"\"Convert slice_spec to tuple.\"\"\"\n if isinstance(slice_spec,\n (list, tuple)) and not isinstance(slice_spec, np.ndarray):\n is_index = True\n for s in slice_spec:\n if s is None or s is Ellipsis or isinstance(s, (list, tuple, slice)):\n is_index = False\n break\n elif isinstance(s, (np_arrays.ndarray, np.ndarray)) and s.ndim != 0:\n is_index = False\n break\n if not is_index:\n return tuple(slice_spec)\n return (slice_spec,)\n\n\ndef _getitem(self, slice_spec):\n \"\"\"Implementation of ndarray.__getitem__.\"\"\"\n if (isinstance(slice_spec, bool) or (isinstance(slice_spec, ops.Tensor) and\n slice_spec.dtype == dtypes.bool) or\n (isinstance(slice_spec, (np.ndarray, np_arrays.ndarray)) and\n slice_spec.dtype == np.bool_)):\n return array_ops.boolean_mask(tensor=self, mask=slice_spec)\n\n if not isinstance(slice_spec, tuple):\n slice_spec = _as_spec_tuple(slice_spec)\n\n result_t = _slice_helper(self, slice_spec)\n return result_t\n\n\ndef _with_index_update_helper(update_method, a, slice_spec, updates):\n \"\"\"Implementation of ndarray._with_index_*.\"\"\"\n if (isinstance(slice_spec, bool) or (isinstance(slice_spec, ops.Tensor) and\n slice_spec.dtype == dtypes.bool) or\n (isinstance(slice_spec, (np.ndarray, np_arrays.ndarray)) and\n slice_spec.dtype == np.bool_)):\n slice_spec = nonzero(slice_spec)\n\n if not isinstance(slice_spec, tuple):\n slice_spec = _as_spec_tuple(slice_spec)\n\n a_dtype = a.dtype\n a, updates = _promote_dtype_binary(a, updates)\n result_t = _slice_helper(a, slice_spec, update_method, updates)\n return result_t.astype(a_dtype)\n\n\nsetattr(np_arrays.ndarray, '_numpy_style_getitem', _getitem)\nsetattr(np_arrays.ndarray, '_with_index_update',\n functools.partial(_with_index_update_helper, _UpdateMethod.UPDATE))\nsetattr(np_arrays.ndarray, '_with_index_add',\n functools.partial(_with_index_update_helper, _UpdateMethod.ADD))\nsetattr(np_arrays.ndarray, '_with_index_min',\n functools.partial(_with_index_update_helper, _UpdateMethod.MIN))\nsetattr(np_arrays.ndarray, '_with_index_max',\n functools.partial(_with_index_update_helper, _UpdateMethod.MAX))\n", "# Copyright 2019 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\"\"\"Operations for generating random numbers.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport six\n\nfrom tensorflow.python.distribute import distribution_strategy_context as ds_context\nfrom tensorflow.python.distribute import values_util\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import gen_stateful_random_ops\nfrom tensorflow.python.ops import gen_stateless_random_ops_v2\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import stateless_random_ops\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.ops.stateless_random_ops import Algorithm\nfrom tensorflow.python.training.tracking import tracking\nfrom tensorflow.python.util import nest\nfrom tensorflow.python.util.tf_export import tf_export\n\n\n# A seed for random ops (stateful and stateless) will always be 1024\n# bits, all of which will be sent to the C++ code. The actual C++\n# implementation of some algorithms may only use a lower part of the bits.\n\nUINT64_HALF_SPAN = 2**63\nMAX_INT64 = UINT64_HALF_SPAN - 1\nMIN_INT64 = -UINT64_HALF_SPAN\nUINT64_SPAN = UINT64_HALF_SPAN * 2\n# 'Variable' doesn't support uint32 or uint64 yet (due to reasons explained in\n# b/111604096 and cl/171681867), so I use signed int here. I choose int64\n# instead of int32 here because `VarHandleOp` doesn't support int32 on GPU.\nSEED_TYPE = \"int64\"\nSEED_MIN = MIN_INT64\nSEED_MAX = MAX_INT64\nSEED_UINT_SPAN = UINT64_SPAN\nSEED_TYPE_BITS = 64\nSEED_BIT_MASK = 0xFFFFFFFFFFFFFFFF\nSEED_SIZE = 16 # in units of SEED_TYPE\n\n\nSTATE_TYPE = SEED_TYPE\nALGORITHM_TYPE = STATE_TYPE\nPHILOX_STATE_SIZE = 3\nTHREEFRY_STATE_SIZE = 2\n\n\nRNG_ALG_PHILOX = Algorithm.PHILOX.value\nRNG_ALG_THREEFRY = Algorithm.THREEFRY.value\nDEFAULT_ALGORITHM = RNG_ALG_PHILOX\n\n\ndef non_deterministic_ints(shape, dtype=dtypes.int64):\n \"\"\"Non-deterministically generates some integers.\n\n This op may use some OS-provided source of non-determinism (e.g. an RNG), so\n each execution will give different results.\n\n Args:\n shape: the shape of the result.\n dtype: (optional) the dtype of the result.\n\n Returns:\n a tensor whose element values are non-deterministically chosen.\n \"\"\"\n return gen_stateful_random_ops.non_deterministic_ints(\n shape=shape, dtype=dtype)\n\n\ndef _uint_to_int(n):\n if isinstance(n, int) and n > SEED_MAX:\n n = n - SEED_UINT_SPAN\n return n\n\n\ndef _make_1d_state(state_size, seed):\n \"\"\"Makes a 1-D RNG state.\n\n Args:\n state_size: an integer.\n seed: an integer or 1-D tensor.\n\n Returns:\n a 1-D tensor of shape [state_size] and dtype STATE_TYPE.\n \"\"\"\n if isinstance(seed, six.integer_types):\n # chop the Python integer (infinite precision) into chunks of SEED_TYPE\n ls = []\n for _ in range(state_size):\n ls.append(seed & SEED_BIT_MASK)\n seed >>= SEED_TYPE_BITS\n seed = ls\n # to avoid overflow error from ops.convert_to_tensor\n seed = nest.map_structure(_uint_to_int, seed)\n seed = math_ops.cast(seed, STATE_TYPE)\n seed = array_ops.reshape(seed, [-1])\n seed = seed[0:state_size]\n # Padding with zeros on the *left* if too short. Padding on the right would\n # cause a small seed to be used as the \"counter\" while the \"key\" is always\n # zero (for counter-based RNG algorithms), because in the current memory\n # layout counter is stored before key. In such a situation two RNGs with\n # two different small seeds may generate overlapping outputs.\n seed_size = seed.shape[0]\n if seed_size is None:\n seed_size = array_ops.shape(seed)[0]\n padding_size = math_ops.maximum(state_size - seed_size, 0)\n padding = array_ops.zeros([padding_size], seed.dtype)\n # can't use `pad` because it doesn't support integer dtypes on GPU\n seed = array_ops.concat([padding, seed], axis=0)\n seed.set_shape([state_size])\n return seed\n\n\ndef _get_counter_size(alg):\n if alg == RNG_ALG_PHILOX:\n return 2\n elif alg == RNG_ALG_THREEFRY:\n return 1\n else:\n raise ValueError(\"Unsupported algorithm id: %s\" % alg)\n\n\ndef _get_state_size(alg):\n if alg == RNG_ALG_PHILOX:\n return PHILOX_STATE_SIZE\n elif alg == RNG_ALG_THREEFRY:\n return THREEFRY_STATE_SIZE\n else:\n raise ValueError(\"Unsupported algorithm id: %s\" % alg)\n\n\ndef _check_state_shape(shape, alg):\n if isinstance(alg, ops.Tensor) and not context.executing_eagerly():\n return\n shape.assert_is_compatible_with([_get_state_size(int(alg))])\n\n\ndef _make_state_from_seed(seed, alg):\n return _make_1d_state(_get_state_size(alg), seed)\n\n\n@tf_export(\"random.create_rng_state\", \"random.experimental.create_rng_state\")\ndef create_rng_state(seed, alg):\n \"\"\"Creates a RNG state from an integer or a vector.\n\n Example:\n\n >>> tf.random.create_rng_state(\n ... 1234, \"philox\")\n <tf.Tensor: shape=(3,), dtype=int64, numpy=array([1234, 0, 0])>\n >>> tf.random.create_rng_state(\n ... [12, 34], \"threefry\")\n <tf.Tensor: shape=(2,), dtype=int64, numpy=array([12, 34])>\n\n Args:\n seed: an integer or 1-D numpy array.\n alg: the RNG algorithm. Can be a string, an `Algorithm` or an integer.\n\n Returns:\n a 1-D numpy array whose size depends on the algorithm.\n \"\"\"\n alg = stateless_random_ops.convert_alg_to_int(alg)\n return _make_state_from_seed(seed, alg)\n\n\ndef _shape_tensor(shape):\n \"\"\"Convert to an int32 or int64 tensor, defaulting to int64 if empty.\"\"\"\n if isinstance(shape, (tuple, list)) and not shape:\n dtype = dtypes.int64\n else:\n dtype = None\n return ops.convert_to_tensor(shape, dtype=dtype, name=\"shape\")\n\n\ndef _convert_to_state_tensor(t):\n # to avoid out-of-range error from ops.convert_to_tensor\n t = nest.map_structure(_uint_to_int, t)\n return math_ops.cast(t, STATE_TYPE)\n\n\ndef get_replica_id():\n rctx = ds_context.get_replica_context()\n if rctx is None:\n return None\n return rctx.replica_id_in_sync_group\n\n\n@tf_export(\"random.Generator\", \"random.experimental.Generator\")\nclass Generator(tracking.AutoTrackable):\n \"\"\"Random-number generator.\n\n Example:\n\n Creating a generator from a seed:\n\n >>> g = tf.random.Generator.from_seed(1234)\n >>> g.normal(shape=(2, 3))\n <tf.Tensor: shape=(2, 3), dtype=float32, numpy=\n array([[ 0.9356609 , 1.0854305 , -0.93788373],\n [-0.5061547 , 1.3169702 , 0.7137579 ]], dtype=float32)>\n\n Creating a generator from a non-deterministic state:\n\n >>> g = tf.random.Generator.from_non_deterministic_state()\n >>> g.normal(shape=(2, 3))\n <tf.Tensor: shape=(2, 3), dtype=float32, numpy=...>\n\n All the constructors allow explicitly choosing an Random-Number-Generation\n (RNG) algorithm. Supported algorithms are `\"philox\"` and `\"threefry\"`. For\n example:\n\n >>> g = tf.random.Generator.from_seed(123, alg=\"philox\")\n >>> g.normal(shape=(2, 3))\n <tf.Tensor: shape=(2, 3), dtype=float32, numpy=\n array([[ 0.8673864 , -0.29899067, -0.9310337 ],\n [-1.5828488 , 1.2481191 , -0.6770643 ]], dtype=float32)>\n\n CPU, GPU and TPU with the same algorithm and seed will generate the same\n integer random numbers. Float-point results (such as the output of `normal`)\n may have small numerical discrepancies between different devices.\n\n This class uses a `tf.Variable` to manage its internal state. Every time\n random numbers are generated, the state of the generator will change. For\n example:\n\n >>> g = tf.random.Generator.from_seed(1234)\n >>> g.state\n <tf.Variable ... numpy=array([1234, 0, 0])>\n >>> g.normal(shape=(2, 3))\n <...>\n >>> g.state\n <tf.Variable ... numpy=array([2770, 0, 0])>\n\n The shape of the state is algorithm-specific.\n\n There is also a global generator:\n\n >>> g = tf.random.get_global_generator()\n >>> g.normal(shape=(2, 3))\n <tf.Tensor: shape=(2, 3), dtype=float32, numpy=...>\n\n When creating a generator inside a `tf.distribute.Strategy` scope, each\n replica will get a different stream of random numbers.\n\n Note: `tf.distribute.experimental.CentralStorageStrategy` and\n `tf.distribute.experimental.ParameterServerStrategy` are not supported yet.\n\n For example, in this code:\n\n ```\n strat = tf.distribute.MirroredStrategy(devices=[\"cpu:0\", \"cpu:1\"])\n with strat.scope():\n g = tf.random.Generator.from_seed(1)\n def f():\n return g.normal([])\n results = strat.run(f).values\n ```\n\n `results[0]` and `results[1]` will have different values.\n\n If the generator is seeded (e.g. created via `Generator.from_seed`), the\n random numbers will be determined by the seed, even though different replicas\n get different numbers. One can think of a random number generated on a\n replica as a hash of the replica ID and a \"master\" random number that may be\n common to all replicas. Hence, the whole system is still deterministic.\n\n (Note that the random numbers on different replicas are not correlated, even\n if they are deterministically determined by the same seed. They are not\n correlated in the sense that no matter what statistics one calculates on them,\n there won't be any discernable correlation.)\n\n Generators can be freely saved and restored using `tf.train.Checkpoint`. The\n checkpoint can be restored in a distribution strategy with a different number\n of replicas than the original strategy. If a replica ID is present in both the\n original and the new distribution strategy, its state will be properly\n restored (i.e. the random-number stream from the restored point will be the\n same as that from the saving point) unless the replicas have already diverged\n in their RNG call traces before saving (e.g. one replica has made one RNG call\n while another has made two RNG calls). We don't have such guarantee if the\n generator is saved in a strategy scope and restored outside of any strategy\n scope, or vice versa.\n \"\"\"\n\n @classmethod\n def from_state(cls, state, alg):\n \"\"\"Creates a generator from a state.\n\n See `__init__` for description of `state` and `alg`.\n\n Args:\n state: the new state.\n alg: the RNG algorithm.\n\n Returns:\n The new generator.\n \"\"\"\n return cls(alg=alg, state=state)\n\n @classmethod\n def from_seed(cls, seed, alg=None):\n \"\"\"Creates a generator from a seed.\n\n A seed is a 1024-bit unsigned integer represented either as a Python\n integer or a vector of integers. Seeds shorter than 1024-bit will be\n padded. The padding, the internal structure of a seed and the way a seed\n is converted to a state are all opaque (unspecified). The only semantics\n specification of seeds is that two different seeds are likely to produce\n two independent generators (but no guarantee).\n\n Args:\n seed: the seed for the RNG.\n alg: (optional) the RNG algorithm. If None, it will be auto-selected. See\n `__init__` for its possible values.\n\n Returns:\n The new generator.\n \"\"\"\n if alg is None:\n # TODO(b/170668986): more sophisticated algorithm selection\n alg = DEFAULT_ALGORITHM\n alg = stateless_random_ops.convert_alg_to_int(alg)\n state = create_rng_state(seed, alg)\n return cls(state=state, alg=alg)\n\n @classmethod\n def from_non_deterministic_state(cls, alg=None):\n \"\"\"Creates a generator by non-deterministically initializing its state.\n\n The source of the non-determinism will be platform- and time-dependent.\n\n Args:\n alg: (optional) the RNG algorithm. If None, it will be auto-selected. See\n `__init__` for its possible values.\n\n Returns:\n The new generator.\n \"\"\"\n if alg is None:\n # TODO(b/170668986): more sophisticated algorithm selection\n alg = DEFAULT_ALGORITHM\n alg = stateless_random_ops.convert_alg_to_int(alg)\n state = non_deterministic_ints(shape=[_get_state_size(alg)],\n dtype=SEED_TYPE)\n return cls(state=state, alg=alg)\n\n @classmethod\n def from_key_counter(cls, key, counter, alg):\n \"\"\"Creates a generator from a key and a counter.\n\n This constructor only applies if the algorithm is a counter-based algorithm.\n See method `key` for the meaning of \"key\" and \"counter\".\n\n Args:\n key: the key for the RNG, a scalar of type STATE_TYPE.\n counter: a vector of dtype STATE_TYPE representing the initial counter for\n the RNG, whose length is algorithm-specific.,\n alg: the RNG algorithm. If None, it will be auto-selected. See\n `__init__` for its possible values.\n\n Returns:\n The new generator.\n \"\"\"\n counter = _convert_to_state_tensor(counter)\n key = _convert_to_state_tensor(key)\n alg = stateless_random_ops.convert_alg_to_int(alg)\n counter.shape.assert_is_compatible_with([_get_state_size(alg) - 1])\n key.shape.assert_is_compatible_with([])\n key = array_ops.reshape(key, [1])\n state = array_ops.concat([counter, key], 0)\n return cls(state=state, alg=alg)\n\n def __init__(self, copy_from=None, state=None, alg=None):\n \"\"\"Creates a generator.\n\n The new generator will be initialized by one of the following ways, with\n decreasing precedence:\n (1) If `copy_from` is not None, the new generator is initialized by copying\n information from another generator.\n (2) If `state` and `alg` are not None (they must be set together), the new\n generator is initialized by a state.\n\n Args:\n copy_from: a generator to be copied from.\n state: a vector of dtype STATE_TYPE representing the initial state of the\n RNG, whose length and semantics are algorithm-specific. If it's a\n variable, the generator will reuse it instead of creating a new\n variable.\n alg: the RNG algorithm. Possible values are\n `tf.random.Algorithm.PHILOX` for the Philox algorithm and\n `tf.random.Algorithm.THREEFRY` for the ThreeFry algorithm\n (see paper 'Parallel Random Numbers: As Easy as 1, 2, 3'\n [https://www.thesalmons.org/john/random123/papers/random123sc11.pdf]).\n The string names `\"philox\"` and `\"threefry\"` can also be used.\n Note `PHILOX` guarantees the same numbers are produced (given\n the same random state) across all architectures (CPU, GPU, XLA etc).\n \"\"\"\n # TODO(b/175072242): Remove distribution-strategy dependencies in this file.\n if ds_context.has_strategy():\n self._distribution_strategy = ds_context.get_strategy()\n else:\n self._distribution_strategy = None\n if copy_from is not None:\n # All other arguments should be None\n assert (alg or state) is None\n self._state_var = self._create_variable(copy_from.state, dtype=STATE_TYPE,\n trainable=False)\n self._alg = copy_from.algorithm\n else:\n assert alg is not None and state is not None\n if ds_context.has_strategy():\n strat_name = type(ds_context.get_strategy()).__name__\n # TODO(b/174610856): Support CentralStorageStrategy and\n # ParameterServerStrategy.\n if \"CentralStorage\" in strat_name or \"ParameterServer\" in strat_name:\n raise ValueError(\"%s is not supported yet\" % strat_name)\n alg = stateless_random_ops.convert_alg_to_int(alg)\n if isinstance(state, variables.Variable):\n _check_state_shape(state.shape, alg)\n self._state_var = state\n else:\n state = _convert_to_state_tensor(state)\n _check_state_shape(state.shape, alg)\n self._state_var = self._create_variable(state, dtype=STATE_TYPE,\n trainable=False)\n self._alg = alg\n\n def _create_variable(self, *args, **kwargs):\n \"\"\"Creates a variable.\n\n Args:\n *args: positional arguments passed along to `variables.Variable.\n **kwargs: keyword arguments passed along to `variables.Variable.\n\n Returns:\n The created variable.\n \"\"\"\n return variables.Variable(*args, **kwargs)\n\n def reset(self, state):\n \"\"\"Resets the generator by a new state.\n\n See `__init__` for the meaning of \"state\".\n\n Args:\n state: the new state.\n \"\"\"\n state = _convert_to_state_tensor(state)\n state.shape.assert_is_compatible_with([_get_state_size(self.algorithm)])\n self._state_var.assign(state)\n\n def reset_from_seed(self, seed):\n \"\"\"Resets the generator by a new seed.\n\n See `from_seed` for the meaning of \"seed\".\n\n Args:\n seed: the new seed.\n \"\"\"\n state = create_rng_state(seed, self.algorithm)\n self._state_var.assign(state)\n\n def reset_from_key_counter(self, key, counter):\n \"\"\"Resets the generator by a new key-counter pair.\n\n See `from_key_counter` for the meaning of \"key\" and \"counter\".\n\n Args:\n key: the new key.\n counter: the new counter.\n \"\"\"\n counter = _convert_to_state_tensor(counter)\n key = _convert_to_state_tensor(key)\n counter.shape.assert_is_compatible_with(\n [_get_state_size(self.algorithm) - 1])\n key.shape.assert_is_compatible_with([])\n key = array_ops.reshape(key, [1])\n state = array_ops.concat([counter, key], 0)\n self._state_var.assign(state)\n\n @property\n def state(self):\n \"\"\"The internal state of the RNG.\"\"\"\n return self._state_var\n\n @property\n def algorithm(self):\n \"\"\"The RNG algorithm id (a Python integer or scalar integer Tensor).\"\"\"\n return self._alg\n\n def _standard_normal(self, shape, dtype):\n key, counter = self._prepare_key_counter(shape)\n return gen_stateless_random_ops_v2.stateless_random_normal_v2(\n shape, key=key, counter=counter, dtype=dtype, alg=self.algorithm)\n\n @property\n def key(self):\n \"\"\"The 'key' part of the state of a counter-based RNG.\n\n For a counter-base RNG algorithm such as Philox and ThreeFry (as\n described in paper 'Parallel Random Numbers: As Easy as 1, 2, 3'\n [https://www.thesalmons.org/john/random123/papers/random123sc11.pdf]),\n the RNG state consists of two parts: counter and key. The output is\n generated via the formula: output=hash(key, counter), i.e. a hashing of\n the counter parametrized by the key. Two RNGs with two different keys can\n be thought as generating two independent random-number streams (a stream\n is formed by increasing the counter).\n\n Returns:\n A scalar which is the 'key' part of the state, if the RNG algorithm is\n counter-based; otherwise it raises a ValueError.\n \"\"\"\n alg = self.algorithm\n if alg == RNG_ALG_PHILOX or alg == RNG_ALG_THREEFRY:\n return self._state_var[-1]\n else:\n raise ValueError(\"Unsupported algorithm id: %s\" % alg)\n\n def _skip_single_var(self, var, delta):\n # TODO(wangpeng): Cache the cast algorithm instead of casting everytime.\n return gen_stateful_random_ops.rng_read_and_skip(\n var.handle,\n alg=math_ops.cast(self.algorithm, dtypes.int32),\n delta=math_ops.cast(delta, dtypes.uint64))\n\n def skip(self, delta):\n \"\"\"Advance the counter of a counter-based RNG.\n\n Args:\n delta: the amount of advancement. The state of the RNG after\n `skip(n)` will be the same as that after `normal([n])`\n (or any other distribution). The actual increment added to the\n counter is an unspecified implementation detail.\n\n Returns:\n A `Tensor` of type `int64`.\n \"\"\"\n\n def update_fn(v):\n return self._skip_single_var(v, delta)\n # TODO(b/170515001): Always call strategy.extended.update after calling it\n # from both replica context and cross-replica context is supported.\n if values_util.is_saving_non_distributed():\n # Assumes replica context with replica_id=0, since we only save the first\n # replica.\n return update_fn(self.state)\n if self._distribution_strategy is not None:\n with ds_context.enter_or_assert_strategy(self._distribution_strategy):\n if ds_context.in_cross_replica_context():\n # Code that operates on all replicas of a variable cannot be saved\n # without retracing.\n values_util.mark_as_unsaveable()\n # In cross-replica context we need to use strategy.extended.update.\n return ds_context.get_strategy().extended.update(\n self.state, update_fn)\n return update_fn(self.state)\n\n def _preprocess_key(self, key):\n if self._distribution_strategy is None:\n return key\n with ds_context.enter_or_assert_strategy(self._distribution_strategy):\n replica_id = get_replica_id()\n if replica_id is not None:\n replica_id = array_ops.stack([replica_id, 0], axis=0)\n replica_id = math_ops.cast(replica_id, dtypes.uint64)\n # Conceptually: key = hash(key, replica_id)\n key = gen_stateless_random_ops_v2.stateless_random_uniform_full_int_v2(\n shape=[1], key=key, counter=replica_id, dtype=dtypes.uint64,\n alg=self.algorithm)\n return key\n\n def _prepare_key_counter(self, shape):\n delta = math_ops.reduce_prod(shape)\n counter_key = self.skip(delta)\n counter_size = _get_counter_size(self.algorithm)\n counter = array_ops.bitcast(counter_key[:counter_size], dtypes.uint64)\n key = array_ops.bitcast(counter_key[counter_size:counter_size + 1],\n dtypes.uint64)\n key = self._preprocess_key(key)\n return key, counter\n\n # The following functions return a tensor and as a side effect update\n # self._state_var.\n def normal(self, shape, mean=0.0, stddev=1.0, dtype=dtypes.float32,\n name=None):\n \"\"\"Outputs random values from a normal distribution.\n\n Args:\n shape: A 1-D integer Tensor or Python array. The shape of the output\n tensor.\n mean: A 0-D Tensor or Python value of type `dtype`. The mean of the normal\n distribution.\n stddev: A 0-D Tensor or Python value of type `dtype`. The standard\n deviation of the normal distribution.\n dtype: The type of the output.\n name: A name for the operation (optional).\n\n Returns:\n A tensor of the specified shape filled with random normal values.\n \"\"\"\n with ops.name_scope(name, \"stateful_normal\", [shape, mean, stddev]) as name:\n shape = _shape_tensor(shape)\n mean = ops.convert_to_tensor(mean, dtype=dtype, name=\"mean\")\n stddev = ops.convert_to_tensor(stddev, dtype=dtype, name=\"stddev\")\n rnd = self._standard_normal(shape, dtype=dtype)\n return math_ops.add(rnd * stddev, mean, name=name)\n\n def _truncated_normal(self, shape, dtype):\n key, counter = self._prepare_key_counter(shape)\n return gen_stateless_random_ops_v2.stateless_truncated_normal_v2(\n shape=shape, key=key, counter=counter, dtype=dtype, alg=self.algorithm)\n\n def truncated_normal(self, shape,\n mean=0.0,\n stddev=1.0,\n dtype=dtypes.float32,\n name=None):\n \"\"\"Outputs random values from a truncated normal distribution.\n\n The generated values follow a normal distribution with specified mean and\n standard deviation, except that values whose magnitude is more than\n 2 standard deviations from the mean are dropped and re-picked.\n\n Args:\n shape: A 1-D integer Tensor or Python array. The shape of the output\n tensor.\n mean: A 0-D Tensor or Python value of type `dtype`. The mean of the\n truncated normal distribution.\n stddev: A 0-D Tensor or Python value of type `dtype`. The standard\n deviation of the normal distribution, before truncation.\n dtype: The type of the output.\n name: A name for the operation (optional).\n\n Returns:\n A tensor of the specified shape filled with random truncated normal\n values.\n \"\"\"\n with ops.name_scope(\n name, \"truncated_normal\", [shape, mean, stddev]) as name:\n shape_tensor = _shape_tensor(shape)\n mean_tensor = ops.convert_to_tensor(mean, dtype=dtype, name=\"mean\")\n stddev_tensor = ops.convert_to_tensor(stddev, dtype=dtype, name=\"stddev\")\n rnd = self._truncated_normal(shape_tensor, dtype=dtype)\n mul = rnd * stddev_tensor\n return math_ops.add(mul, mean_tensor, name=name)\n\n def _uniform(self, shape, dtype):\n key, counter = self._prepare_key_counter(shape)\n return gen_stateless_random_ops_v2.stateless_random_uniform_v2(\n shape=shape, key=key, counter=counter, dtype=dtype, alg=self.algorithm)\n\n def _uniform_full_int(self, shape, dtype, name=None):\n key, counter = self._prepare_key_counter(shape)\n return gen_stateless_random_ops_v2.stateless_random_uniform_full_int_v2(\n shape=shape,\n key=key,\n counter=counter,\n dtype=dtype,\n alg=self.algorithm,\n name=name)\n\n def uniform(self, shape, minval=0, maxval=None,\n dtype=dtypes.float32, name=None):\n \"\"\"Outputs random values from a uniform distribution.\n\n The generated values follow a uniform distribution in the range\n `[minval, maxval)`. The lower bound `minval` is included in the range, while\n the upper bound `maxval` is excluded. (For float numbers especially\n low-precision types like bfloat16, because of\n rounding, the result may sometimes include `maxval`.)\n\n For floats, the default range is `[0, 1)`. For ints, at least `maxval` must\n be specified explicitly.\n\n In the integer case, the random integers are slightly biased unless\n `maxval - minval` is an exact power of two. The bias is small for values of\n `maxval - minval` significantly smaller than the range of the output (either\n `2**32` or `2**64`).\n\n For full-range random integers, pass `minval=None` and `maxval=None` with an\n integer `dtype` (for integer dtypes, `minval` and `maxval` must be both\n `None` or both not `None`).\n\n Args:\n shape: A 1-D integer Tensor or Python array. The shape of the output\n tensor.\n minval: A Tensor or Python value of type `dtype`, broadcastable with\n `shape` (for integer types, broadcasting is not supported, so it needs\n to be a scalar). The lower bound (included) on the range of random\n values to generate. Pass `None` for full-range integers. Defaults to 0.\n maxval: A Tensor or Python value of type `dtype`, broadcastable with\n `shape` (for integer types, broadcasting is not supported, so it needs\n to be a scalar). The upper bound (excluded) on the range of random\n values to generate. Pass `None` for full-range integers. Defaults to 1\n if `dtype` is floating point.\n dtype: The type of the output.\n name: A name for the operation (optional).\n\n Returns:\n A tensor of the specified shape filled with random uniform values.\n\n Raises:\n ValueError: If `dtype` is integral and `maxval` is not specified.\n \"\"\"\n dtype = dtypes.as_dtype(dtype)\n if dtype.is_integer:\n if (minval is None) != (maxval is None):\n raise ValueError(\"For integer dtype {}, minval and maxval must be both \"\n \"`None` or both non-`None`; got minval={} and \"\n \"maxval={}\".format(dtype, minval, maxval))\n elif maxval is None:\n maxval = 1\n with ops.name_scope(name, \"stateful_uniform\",\n [shape, minval, maxval]) as name:\n shape = _shape_tensor(shape)\n if dtype.is_integer and minval is None:\n return self._uniform_full_int(shape=shape, dtype=dtype, name=name)\n minval = ops.convert_to_tensor(minval, dtype=dtype, name=\"min\")\n maxval = ops.convert_to_tensor(maxval, dtype=dtype, name=\"max\")\n if dtype.is_integer:\n key, counter = self._prepare_key_counter(shape)\n return gen_stateless_random_ops_v2.stateless_random_uniform_int_v2(\n shape=shape,\n key=key,\n counter=counter,\n minval=minval,\n maxval=maxval,\n alg=self.algorithm,\n name=name)\n else:\n rnd = self._uniform(shape=shape, dtype=dtype)\n return math_ops.add(rnd * (maxval - minval), minval, name=name)\n\n def uniform_full_int(self, shape, dtype=dtypes.uint64, name=None):\n \"\"\"Uniform distribution on an integer type's entire range.\n\n This method is the same as setting `minval` and `maxval` to `None` in the\n `uniform` method.\n\n Args:\n shape: the shape of the output.\n dtype: (optional) the integer type, default to uint64.\n name: (optional) the name of the node.\n\n Returns:\n A tensor of random numbers of the required shape.\n \"\"\"\n dtype = dtypes.as_dtype(dtype)\n with ops.name_scope(name, \"stateful_uniform_full_int\",\n [shape]) as name:\n shape = _shape_tensor(shape)\n return self._uniform_full_int(shape=shape, dtype=dtype, name=name)\n\n def binomial(self, shape, counts, probs, dtype=dtypes.int32, name=None):\n \"\"\"Outputs random values from a binomial distribution.\n\n The generated values follow a binomial distribution with specified count and\n probability of success parameters.\n\n Example:\n\n ```python\n counts = [10., 20.]\n # Probability of success.\n probs = [0.8]\n\n rng = tf.random.Generator.from_seed(seed=234)\n binomial_samples = rng.binomial(shape=[2], counts=counts, probs=probs)\n\n\n counts = ... # Shape [3, 1, 2]\n probs = ... # Shape [1, 4, 2]\n shape = [3, 4, 3, 4, 2]\n rng = tf.random.Generator.from_seed(seed=1717)\n # Sample shape will be [3, 4, 3, 4, 2]\n binomial_samples = rng.binomial(shape=shape, counts=counts, probs=probs)\n ```\n\n\n Args:\n shape: A 1-D integer Tensor or Python array. The shape of the output\n tensor.\n counts: Tensor. The counts of the binomial distribution. Must be\n broadcastable with `probs`, and broadcastable with the rightmost\n dimensions of `shape`.\n probs: Tensor. The probability of success for the\n binomial distribution. Must be broadcastable with `counts` and\n broadcastable with the rightmost dimensions of `shape`.\n dtype: The type of the output. Default: tf.int32\n name: A name for the operation (optional).\n\n Returns:\n samples: A Tensor of the specified shape filled with random binomial\n values. For each i, each samples[i, ...] is an independent draw from\n the binomial distribution on counts[i] trials with probability of\n success probs[i].\n \"\"\"\n dtype = dtypes.as_dtype(dtype)\n with ops.name_scope(name, \"binomial\", [shape, counts, probs]) as name:\n counts = ops.convert_to_tensor(counts, name=\"counts\")\n probs = ops.convert_to_tensor(probs, name=\"probs\")\n shape_tensor = _shape_tensor(shape)\n return gen_stateful_random_ops.stateful_random_binomial(\n self.state.handle,\n self.algorithm,\n shape=shape_tensor,\n counts=counts,\n probs=probs,\n dtype=dtype,\n name=name)\n\n # TODO(wangpeng): implement other distributions\n\n def _make_int64_keys(self, shape=()):\n # New independent keys are generated via\n # `new_key[i] = hash(old_key, counter+i)`, which is exactly what\n # `uniform_full_int(dtype=int64)` does for PhiloxRandom_64_128_128 and\n # ThreeFry_64_64_64.\n return self.uniform_full_int(shape=shape, dtype=dtypes.int64)\n\n def make_seeds(self, count=1):\n \"\"\"Generates seeds for stateless random ops.\n\n For example:\n\n ```python\n seeds = get_global_generator().make_seeds(count=10)\n for i in range(10):\n seed = seeds[:, i]\n numbers = stateless_random_normal(shape=[2, 3], seed=seed)\n ...\n ```\n\n Args:\n count: the number of seed pairs (note that stateless random ops need a\n pair of seeds to invoke).\n\n Returns:\n A tensor of shape [2, count] and dtype int64.\n \"\"\"\n alg = self.algorithm\n if alg == RNG_ALG_PHILOX or alg == RNG_ALG_THREEFRY:\n keys = self._make_int64_keys(shape=[count])\n # The two seeds for stateless random ops don't have individual semantics\n # and are scrambled together, so setting one to zero is fine.\n zeros = array_ops.zeros_like(keys)\n return array_ops.stack([keys, zeros])\n else:\n raise ValueError(\"Unsupported algorithm id: %s\" % alg)\n\n def split(self, count=1):\n \"\"\"Returns a list of independent `Generator` objects.\n\n Two generators are independent of each other in the sense that the\n random-number streams they generate don't have statistically detectable\n correlations. The new generators are also independent of the old one.\n The old generator's state will be changed (like other random-number\n generating methods), so two calls of `split` will return different\n new generators.\n\n For example:\n\n ```python\n gens = get_global_generator().split(count=10)\n for gen in gens:\n numbers = gen.normal(shape=[2, 3])\n # ...\n gens2 = get_global_generator().split(count=10)\n # gens2 will be different from gens\n ```\n\n The new generators will be put on the current device (possible different\n from the old generator's), for example:\n\n ```python\n with tf.device(\"/device:CPU:0\"):\n gen = Generator(seed=1234) # gen is on CPU\n with tf.device(\"/device:GPU:0\"):\n gens = gen.split(count=10) # gens are on GPU\n ```\n\n Args:\n count: the number of generators to return.\n\n Returns:\n A list (length `count`) of `Generator` objects independent of each other.\n The new generators have the same RNG algorithm as the old one.\n \"\"\"\n def _key_to_state(alg, key):\n # Padding with zeros on the left. The zeros will be the counter.\n return [0] * (_get_state_size(alg) - 1) + [key]\n\n alg = self.algorithm\n if alg == RNG_ALG_PHILOX or alg == RNG_ALG_THREEFRY:\n keys = self._make_int64_keys(shape=[count])\n return [Generator(state=_key_to_state(alg, key), alg=alg)\n for key in array_ops.unstack(keys, num=count)]\n else:\n raise ValueError(\"Unsupported algorithm id: %s\" % alg)\n\n\n# It's not safe to create TF ops before `init_google` is called, so this is\n# initialized to None and get a value the first time `get_global_generator` is\n# called.\nglobal_generator = None\n\n\n@tf_export(\"random.get_global_generator\",\n \"random.experimental.get_global_generator\")\ndef get_global_generator():\n \"\"\"Retrieves the global generator.\n\n This function will create the global generator the first time it is called,\n and the generator will be placed at the default device at that time, so one\n needs to be careful when this function is first called. Using a generator\n placed on a less-ideal device will incur performance regression.\n\n Returns:\n The global `tf.random.Generator` object.\n \"\"\"\n global global_generator\n if global_generator is None:\n with ops.init_scope():\n global_generator = Generator.from_non_deterministic_state()\n return global_generator\n\n\n@tf_export(\"random.set_global_generator\",\n \"random.experimental.set_global_generator\")\ndef set_global_generator(generator):\n \"\"\"Replaces the global generator with another `Generator` object.\n\n This function creates a new Generator object (and the Variable object within),\n which does not work well with tf.function because (1) tf.function puts\n restrictions on Variable creation thus reset_global_generator can't be freely\n used inside tf.function; (2) redirecting a global variable to\n a new object is problematic with tf.function because the old object may be\n captured by a 'tf.function'ed function and still be used by it.\n A 'tf.function'ed function only keeps weak references to variables,\n so deleting a variable and then calling that function again may raise an\n error, as demonstrated by\n random_test.py/RandomTest.testResetGlobalGeneratorBadWithDefun .\n\n Args:\n generator: the new `Generator` object.\n \"\"\"\n global global_generator\n global_generator = generator\n", "# Copyright 2019 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\"\"\"Test for the internal ops used by tfdbg v2.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\n\nimport numpy as np\n\nfrom tensorflow.core.protobuf import debug_event_pb2\nfrom tensorflow.python.debug.lib import debug_events_reader\nfrom tensorflow.python.debug.lib import debug_events_writer\nfrom tensorflow.python.debug.lib import dumping_callback_test_lib\nfrom tensorflow.python.eager import def_function\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_util\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import gen_debug_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.platform import googletest\n\n\nclass DebugIdentityV2OpTest(dumping_callback_test_lib.DumpingCallbackTestBase):\n \"\"\"Tests for DebugIdentityV2Op: when DebugEventsWriter is initialized.\n\n DebugEventsWriter being initialized prior to DebugIdentityV2 ops being invoked\n for the first time is the typical case (e.g., tfdbg2 running on a local\n machine with only local devices.)\n \"\"\"\n\n def setUp(self):\n super(DebugIdentityV2OpTest, self).setUp()\n # Testing using a small circular-buffer size.\n self.circular_buffer_size = 4\n self.tfdbg_run_id = \"test_tfdbg_run\"\n self.writer = debug_events_writer.DebugEventsWriter(\n self.dump_root, self.tfdbg_run_id, self.circular_buffer_size)\n\n def tearDown(self):\n self.writer.Close()\n super(DebugIdentityV2OpTest, self).tearDown()\n\n @test_util.run_in_graph_and_eager_modes\n def testSingleTensorFullTensorDebugModeWithCircularBufferBehavior(self):\n\n @def_function.function\n def write_debug_trace(x):\n square = math_ops.square(x)\n gen_debug_ops.debug_identity_v2(\n square,\n tfdbg_context_id=\"deadbeaf\",\n op_name=\"Square\",\n output_slot=0,\n tensor_debug_mode=debug_event_pb2.TensorDebugMode.FULL_TENSOR,\n debug_urls=[\"file://%s\" % self.dump_root])\n\n sqrt = math_ops.sqrt(x)\n gen_debug_ops.debug_identity_v2(\n sqrt,\n tfdbg_context_id=\"beafdead\",\n op_name=\"Sqrt\",\n output_slot=0,\n tensor_debug_mode=debug_event_pb2.TensorDebugMode.FULL_TENSOR,\n debug_urls=[\"file://%s\" % self.dump_root])\n return square + sqrt\n\n x = np.array([3.0, 4.0])\n # Only the graph-execution trace of the last iteration should be written\n # to self.dump_root.\n for _ in range(self.circular_buffer_size // 2 + 1):\n self.assertAllClose(\n write_debug_trace(x), [9.0 + np.sqrt(3.0), 16.0 + 2.0])\n\n with debug_events_reader.DebugEventsReader(self.dump_root) as reader:\n # Check that the .metadata DebugEvents data file has been created, even\n # before FlushExecutionFiles() is called.\n self.assertGreater(reader.starting_wall_time(), 0)\n self.assertTrue(reader.tensorflow_version())\n self.assertTrue(reader.tfdbg_file_version().startswith(\"debug.Event\"))\n\n graph_trace_iter = reader.graph_execution_traces_iterators()[0]\n # Before FlushExecutionFiles() is called, the .graph_execution_traces file\n # ought to be empty.\n with self.assertRaises(StopIteration):\n next(graph_trace_iter)\n\n # Flush the circular buffer.\n self.writer.FlushExecutionFiles()\n graph_trace_iter = reader.graph_execution_traces_iterators()[0]\n\n # The circular buffer has a size of 4. So only the data from the\n # last two iterations should have been written to self.dump_root.\n for _ in range(2):\n debug_event = next(graph_trace_iter).debug_event\n self.assertGreater(debug_event.wall_time, 0)\n trace = debug_event.graph_execution_trace\n self.assertEqual(trace.tfdbg_context_id, \"deadbeaf\")\n self.assertEqual(trace.op_name, \"Square\")\n self.assertEqual(trace.output_slot, 0)\n self.assertEqual(trace.tensor_debug_mode,\n debug_event_pb2.TensorDebugMode.FULL_TENSOR)\n tensor_value = tensor_util.MakeNdarray(trace.tensor_proto)\n self.assertAllClose(tensor_value, [9.0, 16.0])\n\n debug_event = next(graph_trace_iter).debug_event\n self.assertGreater(debug_event.wall_time, 0)\n trace = debug_event.graph_execution_trace\n self.assertEqual(trace.tfdbg_context_id, \"beafdead\")\n self.assertEqual(trace.op_name, \"Sqrt\")\n self.assertEqual(trace.output_slot, 0)\n self.assertEqual(trace.tensor_debug_mode,\n debug_event_pb2.TensorDebugMode.FULL_TENSOR)\n tensor_value = tensor_util.MakeNdarray(trace.tensor_proto)\n self.assertAllClose(tensor_value, [np.sqrt(3.0), 2.0])\n\n # Only the graph-execution trace of the last iteration should be written\n # to self.dump_root.\n with self.assertRaises(StopIteration):\n next(graph_trace_iter)\n\n @test_util.run_in_graph_and_eager_modes\n def testControlFlow(self):\n\n @def_function.function\n def collatz(x):\n counter = constant_op.constant(0, dtype=dtypes.int32)\n while math_ops.greater(x, 1):\n counter = counter + 1\n gen_debug_ops.debug_identity_v2(\n x,\n tfdbg_context_id=\"deadbeaf\",\n op_name=\"x\",\n output_slot=0,\n tensor_debug_mode=debug_event_pb2.TensorDebugMode.FULL_TENSOR,\n debug_urls=[\"file://%s\" % self.dump_root])\n if math_ops.equal(x % 2, 0):\n x = math_ops.div(x, 2)\n else:\n x = x * 3 + 1\n return counter\n\n x = constant_op.constant(10, dtype=dtypes.int32)\n self.evaluate(collatz(x))\n\n self.writer.FlushExecutionFiles()\n with debug_events_reader.DebugEventsReader(self.dump_root) as reader:\n graph_trace_iter = reader.graph_execution_traces_iterators()[0]\n try:\n x_values = []\n timestamp = 0\n while True:\n debug_event = next(graph_trace_iter).debug_event\n self.assertGreater(debug_event.wall_time, timestamp)\n timestamp = debug_event.wall_time\n trace = debug_event.graph_execution_trace\n self.assertEqual(trace.tfdbg_context_id, \"deadbeaf\")\n self.assertEqual(trace.op_name, \"x\")\n self.assertEqual(trace.output_slot, 0)\n self.assertEqual(trace.tensor_debug_mode,\n debug_event_pb2.TensorDebugMode.FULL_TENSOR)\n x_values.append(int(tensor_util.MakeNdarray(trace.tensor_proto)))\n except StopIteration:\n pass\n\n # Due to the circular buffer, only the last 4 iterations of\n # [10, 5, 16, 8, 4, 2] should have been written.\n self.assertAllEqual(x_values, [16, 8, 4, 2])\n\n @test_util.run_in_graph_and_eager_modes\n def testTwoDumpRoots(self):\n another_dump_root = os.path.join(self.dump_root, \"another\")\n another_debug_url = \"file://%s\" % another_dump_root\n another_writer = debug_events_writer.DebugEventsWriter(\n another_dump_root, \"test_tfdbg_run\")\n\n @def_function.function\n def write_debug_trace(x):\n # DebugIdentityV2 is a stateful op. It ought to be included by auto\n # control dependency.\n square = math_ops.square(x)\n gen_debug_ops.debug_identity_v2(\n square,\n tfdbg_context_id=\"deadbeaf\",\n tensor_debug_mode=debug_event_pb2.TensorDebugMode.FULL_TENSOR,\n debug_urls=[\"file://%s\" % self.dump_root, another_debug_url])\n return square + 1.0\n\n x = np.array([3.0, 4.0])\n self.assertAllClose(write_debug_trace(x), np.array([10.0, 17.0]))\n self.writer.FlushExecutionFiles()\n another_writer.FlushExecutionFiles()\n another_writer.Close()\n\n for debug_root in (self.dump_root, another_dump_root):\n with debug_events_reader.DebugEventsReader(debug_root) as reader:\n graph_trace_iter = reader.graph_execution_traces_iterators()[0]\n\n debug_event = next(graph_trace_iter).debug_event\n trace = debug_event.graph_execution_trace\n self.assertEqual(trace.tfdbg_context_id, \"deadbeaf\")\n self.assertEqual(trace.op_name, \"\")\n self.assertEqual(trace.tensor_debug_mode,\n debug_event_pb2.TensorDebugMode.FULL_TENSOR)\n tensor_value = tensor_util.MakeNdarray(trace.tensor_proto)\n self.assertAllClose(tensor_value, [9.0, 16.0])\n\n with self.assertRaises(StopIteration):\n next(graph_trace_iter)\n\n\nclass DebugIdentityV2OpUninitializedWriterTest(\n dumping_callback_test_lib.DumpingCallbackTestBase):\n \"\"\"Tests for DebugIdentityV2Op: when DebugEventsWriter is not initialized.\n\n This case can occur when DebugIdentityV2Ops are running on a remote\n TensorFlow server (e.g., a TPU worker).\n \"\"\"\n\n @test_util.run_in_graph_and_eager_modes\n def testInvokingDebugIdentityV2OpBeforeCreatingDebugEventsWriterWorks(self):\n circular_buffer_size = 3\n\n @def_function.function\n def write_debug_trace(x):\n # DebugIdentityV2 is a stateful op. It ought to be included by auto\n # control dependency.\n square = math_ops.square(x)\n gen_debug_ops.debug_identity_v2(\n square,\n tfdbg_context_id=\"deadbeaf\",\n op_name=\"Square\",\n output_slot=0,\n tensor_debug_mode=debug_event_pb2.TensorDebugMode.FULL_TENSOR,\n debug_urls=[\"file://%s\" % self.dump_root],\n circular_buffer_size=circular_buffer_size)\n return square\n\n # The DebugIdentityV2 ops are invokes *before* a DebugEventsWriter at the\n # same dump root is created.\n for i in range(circular_buffer_size * 2):\n self.assertAllClose(\n write_debug_trace(np.array([i]).astype(np.float32)), [i**2.0])\n writer = debug_events_writer.DebugEventsWriter(self.dump_root,\n \"test_tfdbg_run\",\n circular_buffer_size)\n writer.FlushNonExecutionFiles()\n writer.FlushExecutionFiles()\n\n with debug_events_reader.DebugEventsReader(self.dump_root) as reader:\n graph_trace_iter = reader.graph_execution_traces_iterators()[0]\n graph_execution_traces = []\n while True:\n try:\n graph_execution_traces.append(\n next(graph_trace_iter).debug_event.graph_execution_trace)\n except StopIteration:\n break\n self.assertLen(graph_execution_traces, circular_buffer_size)\n for i in range(circular_buffer_size):\n self.assertAllClose(\n tensor_util.MakeNdarray(graph_execution_traces[i].tensor_proto),\n [(i + circular_buffer_size)**2.0])\n\n\nclass DebugNumericSummaryV2Test(test_util.TensorFlowTestCase):\n\n @test_util.run_in_graph_and_eager_modes\n def testDebugNumericSummaryV2OpReduceInfNanThreeSlots(self):\n\n def debug_summary(x):\n return self.evaluate(\n gen_debug_ops.debug_numeric_summary_v2(\n x,\n tensor_debug_mode=(\n debug_event_pb2.TensorDebugMode.REDUCE_INF_NAN_THREE_SLOTS)))\n\n self.assertAllEqual(\n debug_summary(constant_op.constant([])), [0.0, 0.0, 0.0])\n self.assertAllEqual(\n debug_summary(constant_op.constant(42.0)), [0.0, 0.0, 0.0])\n self.assertAllEqual(\n debug_summary(constant_op.constant([3.0, 4.0])), [0.0, 0.0, 0.0])\n self.assertAllEqual(\n debug_summary(constant_op.constant(np.array([3.0, -np.inf]))),\n [-np.inf, 0.0, 0.0])\n self.assertAllEqual(\n debug_summary(constant_op.constant(np.array([[0, 0], [np.nan, 0]]))),\n [0.0, 0.0, np.nan])\n self.assertAllEqual(\n debug_summary(\n constant_op.constant(np.array([[0, 0], [np.nan, np.inf]]))),\n [0.0, np.inf, np.nan])\n self.assertAllEqual(\n debug_summary(\n constant_op.constant(np.array([[0, np.inf], [np.nan, -np.inf]]))),\n [-np.inf, np.inf, np.nan])\n\n x = np.zeros([100, 100], dtype=np.float16)\n x[32, 47] = np.nan\n self.assertAllEqual(\n debug_summary(constant_op.constant(x)), [0.0, 0.0, np.nan])\n x = np.zeros([97, 97], dtype=np.float32)\n x[50, 83] = -np.inf\n self.assertAllEqual(\n debug_summary(constant_op.constant(x)), [-np.inf, 0.0, 0.0])\n x[1, 41] = np.nan\n self.assertAllEqual(\n debug_summary(constant_op.constant(x)), [-np.inf, 0.0, np.nan])\n x = np.zeros([9701], dtype=np.float64)\n x[9700] = np.nan\n self.assertAllEqual(\n debug_summary(constant_op.constant(x)), [0.0, 0.0, np.nan])\n\n @test_util.run_in_graph_and_eager_modes\n def testDebugNumericSummaryV2OpLargeTensorIDError(self):\n modes = [\n debug_event_pb2.TensorDebugMode.CURT_HEALTH,\n debug_event_pb2.TensorDebugMode.CONCISE_HEALTH,\n debug_event_pb2.TensorDebugMode.SHAPE,\n ]\n # Maximum allowed tensor_id\n tensor_id = np.power(2, 53, dtype=np.int64)\n for mode in modes:\n self.evaluate(\n gen_debug_ops.debug_numeric_summary_v2(\n constant_op.constant(42.0),\n tensor_debug_mode=mode,\n tensor_id=tensor_id,\n output_dtype=dtypes.float64))\n # Incrementing by one should error\n tensor_id += 1\n for mode in modes:\n with self.assertRaises(errors.InvalidArgumentError):\n self.evaluate(\n gen_debug_ops.debug_numeric_summary_v2(\n constant_op.constant(42.0),\n tensor_debug_mode=mode,\n tensor_id=tensor_id,\n output_dtype=dtypes.float64))\n\n @test_util.run_in_graph_and_eager_modes\n def testDebugNumericSummaryV2OpCurtHealthValuesSmall(self):\n\n def debug_summary(x):\n return self.evaluate(\n gen_debug_ops.debug_numeric_summary_v2(\n x,\n tensor_debug_mode=(debug_event_pb2.TensorDebugMode.CURT_HEALTH),\n tensor_id=x._id,\n output_dtype=dtypes.float64)), x._id\n\n tensor, tensor_id = debug_summary(constant_op.constant([]))\n self.assertAllEqual(tensor, [tensor_id, 0.0])\n\n tensor, tensor_id = debug_summary(constant_op.constant(42.0))\n self.assertAllEqual(tensor, [tensor_id, 0.0])\n\n tensor, tensor_id = debug_summary(constant_op.constant([3.0, 4.0]))\n self.assertAllEqual(tensor, [tensor_id, 0.0])\n\n tensor, tensor_id = debug_summary(\n constant_op.constant(np.array([3.0, -np.inf])))\n self.assertAllEqual(tensor, [tensor_id, 1.0])\n\n tensor, tensor_id = debug_summary(\n constant_op.constant(np.array([[0, 0], [np.nan, 0]])))\n self.assertAllEqual(tensor, [tensor_id, 1.0])\n\n tensor, tensor_id = debug_summary(\n constant_op.constant(np.array([[0, 0], [np.nan, np.inf]])))\n self.assertAllEqual(tensor, [tensor_id, 1.0])\n\n tensor, tensor_id = debug_summary(\n constant_op.constant(np.array([[0, np.inf], [np.nan, -np.inf]])))\n self.assertAllEqual(tensor, [tensor_id, 1.0])\n\n @test_util.run_in_graph_and_eager_modes\n def testDebugNumericSummaryV2OpCurtHealthValuesLarge(self):\n\n def debug_summary(x):\n return self.evaluate(\n gen_debug_ops.debug_numeric_summary_v2(\n x,\n tensor_debug_mode=(debug_event_pb2.TensorDebugMode.CURT_HEALTH),\n tensor_id=x._id,\n output_dtype=dtypes.float64)), x._id\n\n x = np.zeros([100, 100], dtype=np.float16)\n x[32, 47] = np.nan\n tensor, tensor_id = debug_summary(constant_op.constant(x))\n self.assertAllEqual(tensor, [tensor_id, 1.0])\n x = np.zeros([97, 97], dtype=np.float32)\n x[50, 83] = -np.inf\n tensor, tensor_id = debug_summary(constant_op.constant(x))\n self.assertAllEqual(tensor, [tensor_id, 1.0])\n x[1, 41] = np.nan\n tensor, tensor_id = debug_summary(constant_op.constant(x))\n self.assertAllEqual(tensor, [tensor_id, 1.0])\n x = np.zeros([9701], dtype=np.float64)\n x[9700] = np.nan\n tensor, tensor_id = debug_summary(constant_op.constant(x))\n self.assertAllEqual(tensor, [tensor_id, 1.0])\n\n @test_util.run_in_graph_and_eager_modes\n def testDebugNumericSummaryV2OpCurtHealthConsistency(self):\n\n def debug_summary(x):\n return self.evaluate(\n gen_debug_ops.debug_numeric_summary_v2(\n x,\n tensor_debug_mode=(debug_event_pb2.TensorDebugMode.CURT_HEALTH),\n tensor_id=x._id,\n output_dtype=dtypes.float64)), x._id\n\n x = np.zeros([100, 100], dtype=np.float16)\n x[43, 99] = np.nan\n c = constant_op.constant(x)\n tensor_1, tensor_id_1 = debug_summary(c)\n tensor_2, tensor_id_2 = debug_summary(c)\n self.assertAllEqual(tensor_1, tensor_2)\n self.assertEqual(tensor_id_1, tensor_id_2)\n\n x = np.zeros([100, 100, 50], dtype=np.float64)\n x[0, 0, 1] = np.inf\n c = constant_op.constant(x)\n tensor_1, tensor_id_1 = debug_summary(c)\n tensor_2, tensor_id_2 = debug_summary(c)\n self.assertAllEqual(tensor_1, tensor_2)\n self.assertEqual(tensor_id_1, tensor_id_2)\n\n c = constant_op.constant(np.ones((100, 200), np.double))\n tensor_1, tensor_id_1 = debug_summary(c)\n tensor_2, tensor_id_2 = debug_summary(c)\n self.assertAllEqual(tensor_1, tensor_2)\n self.assertEqual(tensor_id_1, tensor_id_2)\n\n @test_util.run_in_graph_and_eager_modes\n def testDebugNumericSummaryV2OpConciseHealthSmall(self):\n\n def debug_summary(x):\n return self.evaluate(\n gen_debug_ops.debug_numeric_summary_v2(\n x,\n tensor_debug_mode=(\n debug_event_pb2.TensorDebugMode.CONCISE_HEALTH),\n tensor_id=x._id,\n output_dtype=dtypes.float64)), x._id\n\n tensor, tensor_id = debug_summary(constant_op.constant([]))\n self.assertAllEqual(tensor, [tensor_id, 0.0, 0.0, 0.0, 0.0])\n\n tensor, tensor_id = debug_summary(constant_op.constant(42.0))\n self.assertAllEqual(tensor, [tensor_id, 1.0, 0.0, 0.0, 0.0])\n\n tensor, tensor_id = debug_summary(constant_op.constant([3.0, 4.0]))\n self.assertAllEqual(tensor, [tensor_id, 2.0, 0.0, 0.0, 0.0])\n\n tensor, tensor_id = debug_summary(\n constant_op.constant(np.array([3.0, -np.inf])))\n self.assertAllEqual(tensor, [tensor_id, 2.0, 1.0, 0.0, 0.0])\n\n tensor, tensor_id = debug_summary(\n constant_op.constant(np.array([[0, 0], [np.nan, 0]])))\n self.assertAllEqual(tensor, [tensor_id, 4.0, 0.0, 0.0, 1.0])\n\n tensor, tensor_id = debug_summary(\n constant_op.constant(np.array([[0, 0], [np.nan, np.inf]])))\n self.assertAllEqual(tensor, [tensor_id, 4.0, 0.0, 1.0, 1.0])\n\n tensor, tensor_id = debug_summary(\n constant_op.constant(np.array([[0, np.inf], [np.nan, -np.inf]])))\n self.assertAllEqual(tensor, [tensor_id, 4.0, 1.0, 1.0, 1.0])\n\n @test_util.run_in_graph_and_eager_modes\n def testDebugNumericSummaryV2OpConciseHealthLarge(self):\n\n def debug_summary(x):\n return self.evaluate(\n gen_debug_ops.debug_numeric_summary_v2(\n x,\n tensor_debug_mode=(\n debug_event_pb2.TensorDebugMode.CONCISE_HEALTH),\n tensor_id=x._id,\n output_dtype=dtypes.float64)), x._id\n\n x = np.zeros([100, 100], dtype=np.float16)\n x[32, :] = np.nan\n tensor, tensor_id = debug_summary(constant_op.constant(x))\n self.assertAllEqual(tensor, [tensor_id, 10000.0, 0.0, 0.0, 100.0])\n x = np.zeros([97, 97], dtype=np.float32)\n x[50, 83:85] = -np.inf\n tensor, tensor_id = debug_summary(constant_op.constant(x))\n self.assertAllEqual(tensor, [tensor_id, 97 * 97, 2.0, 0.0, 0.0])\n x[1:9, 41] = np.nan\n tensor, tensor_id = debug_summary(constant_op.constant(x))\n self.assertAllEqual(tensor, [tensor_id, 97 * 97, 2.0, 0.0, 8.0])\n x = np.zeros([9701], dtype=np.float64)\n x[9700] = np.nan\n tensor, tensor_id = debug_summary(constant_op.constant(x))\n self.assertAllEqual(tensor, [tensor_id, 9701, 0.0, 0.0, 1.0])\n\n @test_util.run_in_graph_and_eager_modes\n def testDebugNumericSummaryV2OpConciseHealthConsistency(self):\n\n def debug_summary(x):\n return self.evaluate(\n gen_debug_ops.debug_numeric_summary_v2(\n x,\n tensor_debug_mode=(\n debug_event_pb2.TensorDebugMode.CONCISE_HEALTH),\n tensor_id=x._id,\n output_dtype=dtypes.float64)), x._id\n\n # Assert the same op is returns a consistent value\n x = np.zeros([100, 100], dtype=np.float16)\n x[3, 4] = -np.inf\n c = constant_op.constant(x)\n tensor_1, tensor_id_1 = debug_summary(c)\n tensor_2, tensor_id_2 = debug_summary(c)\n self.assertAllEqual(tensor_1, tensor_2)\n self.assertEqual(tensor_id_1, tensor_id_2)\n\n c = constant_op.constant(np.ones((100, 200), np.double))\n tensor_1, tensor_id_1 = debug_summary(c)\n tensor_2, tensor_id_2 = debug_summary(c)\n self.assertAllEqual(tensor_1, tensor_2)\n self.assertEqual(tensor_id_1, tensor_id_2)\n\n @test_util.run_in_graph_and_eager_modes\n def testDebugNumericSummaryV2OpShapeEmpty(self):\n\n def debug_summary(x):\n return self.evaluate(\n gen_debug_ops.debug_numeric_summary_v2(\n x,\n tensor_debug_mode=(debug_event_pb2.TensorDebugMode.SHAPE),\n tensor_id=x._id,\n output_dtype=dtypes.float64)), x._id\n\n tensor, tensor_id = debug_summary(constant_op.constant(0.0))\n self.assertAllEqual(\n tensor, [tensor_id, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])\n\n @test_util.run_in_graph_and_eager_modes\n def testDebugNumericSummaryV2OpShapeSmall(self):\n\n def debug_summary(x):\n return self.evaluate(\n gen_debug_ops.debug_numeric_summary_v2(\n x,\n tensor_debug_mode=(debug_event_pb2.TensorDebugMode.SHAPE),\n tensor_id=x._id,\n output_dtype=dtypes.float64)), x._id\n\n x = np.zeros([3, 4], dtype=np.float32)\n tensor, tensor_id = debug_summary(constant_op.constant(x))\n self.assertAllEqual(\n tensor, [tensor_id, 1.0, 2.0, 12.0, 3.0, 4.0, 0.0, 0.0, 0.0, 0.0])\n\n x = np.ones([1, 2, 3, 4, 5, 6], dtype=np.float16)\n x[0, 1, 2, 2, 2, 2] = np.nan\n tensor, tensor_id = debug_summary(constant_op.constant(x))\n self.assertAllEqual(\n tensor,\n [tensor_id, 19, 6.0, 2 * 3 * 4 * 5 * 6, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0])\n\n x = np.zeros([2], dtype=np.float32)\n tensor, tensor_id = debug_summary(constant_op.constant(x))\n self.assertAllEqual(\n tensor, [tensor_id, 1.0, 1.0, 2.0, 2.0, 0.0, 0.0, 0.0, 0.0, 0.0])\n\n tensor, tensor_id = debug_summary(constant_op.constant([]))\n self.assertAllEqual(\n tensor, [tensor_id, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])\n\n @test_util.run_in_graph_and_eager_modes\n def testDebugNumericSummaryV2OpShapeLarge(self):\n\n def debug_summary(x):\n return self.evaluate(\n gen_debug_ops.debug_numeric_summary_v2(\n x,\n tensor_debug_mode=(debug_event_pb2.TensorDebugMode.SHAPE),\n tensor_id=x._id,\n output_dtype=dtypes.float64)), x._id\n\n x = np.ones([1, 2, 3, 4, 5, 6, 7], dtype=np.double)\n tensor, tensor_id = debug_summary(constant_op.constant(x))\n self.assertAllEqual(tensor, [\n tensor_id, 2.0, 7.0, 2 * 3 * 4 * 5 * 6 * 7, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0\n ])\n\n @test_util.run_in_graph_and_eager_modes\n def testDebugNumericSummaryV2OpFullHealthSmall(self):\n\n def debug_summary(x):\n return self.evaluate(\n gen_debug_ops.debug_numeric_summary_v2(\n x,\n tensor_debug_mode=(debug_event_pb2.TensorDebugMode.FULL_HEALTH),\n tensor_id=x._id,\n output_dtype=dtypes.float64)), x._id\n\n tensor, tensor_id = debug_summary(constant_op.constant([]))\n expected = [tensor_id, -1, 1, 1, 0, 0, 0, 0, 0, 0, 0]\n self.assertAllEqual(tensor, expected)\n\n tensor, tensor_id = debug_summary(constant_op.constant(42.0))\n expected = [tensor_id, -1, 1, 0, 1, 0, 0, 0, 0, 0, 1]\n self.assertAllEqual(tensor, expected)\n\n tensor, tensor_id = debug_summary(constant_op.constant([3.0, 4.0]))\n expected = [tensor_id, -1, 1, 1, 2, 0, 0, 0, 0, 0, 2]\n self.assertAllEqual(tensor, expected)\n\n tensor, tensor_id = debug_summary(\n constant_op.constant(np.array([3, -np.inf], dtype=np.float32)))\n expected = [tensor_id, -1, 1, 1, 2, 1, 0, 0, 0, 0, 1]\n self.assertAllEqual(tensor, expected)\n\n tensor, tensor_id = debug_summary(\n constant_op.constant(np.array([[0, 0], [np.nan, 0]], dtype=np.float64)))\n expected = [tensor_id, -1, 2, 2, 4, 0, 0, 1, 0, 3, 0]\n self.assertAllEqual(tensor, expected)\n\n tensor, tensor_id = debug_summary(\n constant_op.constant(\n np.array([[0, 0], [np.nan, np.inf]], dtype=np.float16)))\n expected = [tensor_id, -1, 19, 2, 4, 0, 1, 1, 0, 2, 0]\n self.assertAllEqual(tensor, expected)\n\n tensor, tensor_id = debug_summary(\n constant_op.constant(\n np.array([[0, np.inf], [np.nan, -np.inf]], dtype=np.float32)))\n expected = [tensor_id, -1, 1, 2, 4, 1, 1, 1, 0, 1, 0]\n self.assertAllEqual(tensor, expected)\n\n @test_util.run_in_graph_and_eager_modes\n def testDebugNumericSummaryV2OpFullHealthLarge(self):\n\n def debug_summary(x):\n return self.evaluate(\n gen_debug_ops.debug_numeric_summary_v2(\n x,\n tensor_debug_mode=(debug_event_pb2.TensorDebugMode.FULL_HEALTH),\n tensor_id=x._id,\n output_dtype=dtypes.float64)), x._id\n\n def tensor_counts(arr):\n counts = [len(np.shape(arr)), np.size(arr), 0, 0, 0, 0, 0, 0]\n for n in np.ravel(arr):\n if np.isneginf(n):\n counts[2] += 1\n elif np.isposinf(n):\n counts[3] += 1\n elif np.isnan(n):\n counts[4] += 1\n elif n < 0.:\n counts[5] += 1\n elif n == 0.:\n counts[6] += 1\n else:\n counts[7] += 1\n return counts\n\n x = np.zeros([50, 50], dtype=np.float16)\n x[32, 47] = np.nan\n x[0:4, 3] = np.inf\n x[40:50, 40:50] = 10\n x[3, 20] = -10\n tensor, tensor_id = debug_summary(constant_op.constant(x))\n expected = [tensor_id, -1, 19] + tensor_counts(x)\n self.assertAllEqual(tensor, expected)\n\n x = np.ones([25, 25, 50], dtype=np.float32) * np.inf\n x[:, :, 1] = np.nan\n x[:, :, 2] = -np.inf\n x[:, :, 3] = -1\n x[:, :, 4] = 0\n x[:, :, 5] = 1\n tensor, tensor_id = debug_summary(constant_op.constant(x))\n expected = [tensor_id, -1, 1] + tensor_counts(x)\n self.assertAllEqual(tensor, expected)\n x[0, 0, 0] = np.nan\n tensor, tensor_id = debug_summary(constant_op.constant(x))\n expected = [\n tensor_id,\n -1,\n 1,\n ] + tensor_counts(x)\n self.assertAllEqual(tensor, expected)\n x = np.zeros([9701], dtype=np.float64)\n x[9700] = np.nan\n tensor, tensor_id = debug_summary(constant_op.constant(x))\n expected = [tensor_id, -1, 2] + tensor_counts(x)\n self.assertAllEqual(tensor, expected)\n\n @test_util.run_in_graph_and_eager_modes\n def testDebugNumericSummaryV2OpFullHealthConsistency(self):\n\n def debug_summary(x):\n return self.evaluate(\n gen_debug_ops.debug_numeric_summary_v2(\n x,\n tensor_debug_mode=(debug_event_pb2.TensorDebugMode.FULL_HEALTH),\n tensor_id=x._id,\n output_dtype=dtypes.float64)), x._id\n\n # Assert the same op is returns a consistent value\n x = np.zeros([100, 100], dtype=np.float16)\n x[32, 47] = np.nan\n x[0:4, 3] = np.inf\n x[90:100, 90:100] = 10\n x[3, 20] = -10\n c = constant_op.constant(x)\n tensor_1, tensor_id_1 = debug_summary(c)\n tensor_2, tensor_id_2 = debug_summary(c)\n self.assertAllEqual(tensor_1, tensor_2)\n self.assertEqual(tensor_id_1, tensor_id_2)\n\n x = np.ones((100, 200, 3, 10), np.double)\n x[1, 30, 2] = 10\n x[5, :, 0, 1] = np.nan\n x[90:100, 150, :, :] = np.inf\n c = constant_op.constant(x)\n tensor_1, tensor_id_1 = debug_summary(c)\n tensor_2, tensor_id_2 = debug_summary(c)\n self.assertAllEqual(tensor_1, tensor_2)\n self.assertEqual(tensor_id_1, tensor_id_2)\n\n def testCheckNumericsV2OpNegativeAndPositiveInf(self):\n \"\"\"Test that CheckNumericsV2 op distinguishes negative and positive infs.\"\"\"\n with self.session(graph=ops.Graph()):\n t1 = constant_op.constant([-1.0, 1.0])\n t2 = constant_op.constant([0.0, 0.0])\n with self.assertRaisesRegex(\n errors.InvalidArgumentError,\n r\"pass through test.*had -Inf and \\+Inf values\"):\n self.evaluate(\n array_ops.check_numerics_v2(t1 / t2, message=\"pass through test\"))\n\n def testCheckNumericsV2OpNegativeAndPositiveInfAndNaN(self):\n \"\"\"CheckNumericsV2 op distinguishes - & + infs when nan is present.\"\"\"\n with self.session(graph=ops.Graph()):\n t1 = constant_op.constant([-1.0, 1.0, 0.0])\n t2 = constant_op.constant([0.0, 0.0, 0.0])\n with self.assertRaisesRegex(\n errors.InvalidArgumentError,\n r\"pass through test.*had -Inf, \\+Inf, and NaN values\"):\n self.evaluate(\n array_ops.check_numerics_v2(t1 / t2, message=\"pass through test\"))\n\n def testCheckNumericsV2PositiveInfAndNaN(self):\n \"\"\"Test that CheckNumericsV2 op shows sign of inf when nan is present.\"\"\"\n with self.session(graph=ops.Graph()):\n t1 = constant_op.constant([0.0, 1.0])\n t2 = constant_op.constant([0.0, 0.0])\n with self.assertRaisesRegex(\n errors.InvalidArgumentError,\n r\"pass through test.*had \\+Inf and NaN values\"):\n self.evaluate(\n array_ops.check_numerics_v2(t1 / t2, message=\"pass through test\"))\n\n\nif __name__ == \"__main__\":\n ops.enable_eager_execution()\n googletest.main()\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\"\"\"Python wrappers for Datasets and Iterators.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.util import deprecation\nfrom tensorflow.python.util.tf_export import tf_export\n\n\[email protected](None, \"Use `tf.data.Dataset.get_single_element()`.\")\n@tf_export(\"data.experimental.get_single_element\")\ndef get_single_element(dataset):\n \"\"\"Returns the single element of the `dataset` as a nested structure of tensors.\n\n The function enables you to use a `tf.data.Dataset` in a stateless\n \"tensor-in tensor-out\" expression, without creating an iterator.\n This facilitates the ease of data transformation on tensors using the\n optimized `tf.data.Dataset` abstraction on top of them.\n\n For example, lets consider a `preprocessing_fn` which would take as an\n input the raw features and returns the processed feature along with\n it's label.\n\n ```python\n def preprocessing_fn(raw_feature):\n # ... the raw_feature is preprocessed as per the use-case\n return feature\n\n raw_features = ... # input batch of BATCH_SIZE elements.\n dataset = (tf.data.Dataset.from_tensor_slices(raw_features)\n .map(preprocessing_fn, num_parallel_calls=BATCH_SIZE)\n .batch(BATCH_SIZE))\n\n processed_features = tf.data.experimental.get_single_element(dataset)\n ```\n\n In the above example, the `raw_features` tensor of length=BATCH_SIZE\n was converted to a `tf.data.Dataset`. Next, each of the `raw_feature` was\n mapped using the `preprocessing_fn` and the processed features were\n grouped into a single batch. The final `dataset` contains only one element\n which is a batch of all the processed features.\n\n NOTE: The `dataset` should contain only one element.\n\n Now, instead of creating an iterator for the `dataset` and retrieving the\n batch of features, the `tf.data.experimental.get_single_element()` function\n is used to skip the iterator creation process and directly output the batch\n of features.\n\n This can be particularly useful when your tensor transformations are\n expressed as `tf.data.Dataset` operations, and you want to use those\n transformations while serving your model.\n\n # Keras\n\n ```python\n\n model = ... # A pre-built or custom model\n\n class PreprocessingModel(tf.keras.Model):\n def __init__(self, model):\n super().__init__(self)\n self.model = model\n\n @tf.function(input_signature=[...])\n def serving_fn(self, data):\n ds = tf.data.Dataset.from_tensor_slices(data)\n ds = ds.map(preprocessing_fn, num_parallel_calls=BATCH_SIZE)\n ds = ds.batch(batch_size=BATCH_SIZE)\n return tf.argmax(\n self.model(tf.data.experimental.get_single_element(ds)),\n axis=-1\n )\n\n preprocessing_model = PreprocessingModel(model)\n your_exported_model_dir = ... # save the model to this path.\n tf.saved_model.save(preprocessing_model, your_exported_model_dir,\n signatures={'serving_default': preprocessing_model.serving_fn})\n ```\n\n # Estimator\n\n In the case of estimators, you need to generally define a `serving_input_fn`\n which would require the features to be processed by the model while\n inferencing.\n\n ```python\n def serving_input_fn():\n\n raw_feature_spec = ... # Spec for the raw_features\n input_fn = tf.estimator.export.build_parsing_serving_input_receiver_fn(\n raw_feature_spec, default_batch_size=None)\n )\n serving_input_receiver = input_fn()\n raw_features = serving_input_receiver.features\n\n def preprocessing_fn(raw_feature):\n # ... the raw_feature is preprocessed as per the use-case\n return feature\n\n dataset = (tf.data.Dataset.from_tensor_slices(raw_features)\n .map(preprocessing_fn, num_parallel_calls=BATCH_SIZE)\n .batch(BATCH_SIZE))\n\n processed_features = tf.data.experimental.get_single_element(dataset)\n\n # Please note that the value of `BATCH_SIZE` should be equal to\n # the size of the leading dimension of `raw_features`. This ensures\n # that `dataset` has only element, which is a pre-requisite for\n # using `tf.data.experimental.get_single_element(dataset)`.\n\n return tf.estimator.export.ServingInputReceiver(\n processed_features, serving_input_receiver.receiver_tensors)\n\n estimator = ... # A pre-built or custom estimator\n estimator.export_saved_model(your_exported_model_dir, serving_input_fn)\n ```\n\n Args:\n dataset: A `tf.data.Dataset` object containing a single element.\n\n Returns:\n A nested structure of `tf.Tensor` objects, corresponding to the single\n element of `dataset`.\n\n Raises:\n TypeError: if `dataset` is not a `tf.data.Dataset` object.\n InvalidArgumentError: (at runtime) if `dataset` does not contain exactly\n one element.\n \"\"\"\n if not isinstance(dataset, dataset_ops.DatasetV2):\n raise TypeError(\"`dataset` must be a `tf.data.Dataset` object.\")\n\n return dataset.get_single_element()\n", "# Copyright 2021 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\"\"\"tf.data service test-cluster with local and remote workers.\"\"\"\n\nimport tempfile\n\nfrom tensorflow.python.data.experimental.kernel_tests.service import test_base as data_service_test_base\nfrom tensorflow.python.data.experimental.service import server_lib\nfrom tensorflow.python.distribute import multi_process_lib\nfrom tensorflow.python.platform import googletest\n\n_WORKER_SHUTDOWN_QUIET_PERIOD_MS = 100\n\n\n# pylint: disable=protected-access\nclass _RemoteWorkerProcess(multi_process_lib.Process):\n \"\"\"Runs a worker server in a new process to simulate a remote worker.\"\"\"\n\n def __init__(self, dispatcher_address, pipe_writer):\n super(_RemoteWorkerProcess, self).__init__()\n self._dispatcher_address = dispatcher_address\n self._pipe_writer = pipe_writer\n\n # `run` is hidden in multi_process_lib.py. It is assigned with a decorated\n # `run` that runs the process in `absl.app.run`.\n def run(self): # pylint: disable=method-hidden\n self.start_worker()\n\n def start_worker(self):\n self._worker = data_service_test_base.TestWorker(\n self._dispatcher_address, _WORKER_SHUTDOWN_QUIET_PERIOD_MS)\n self._worker.start()\n self._pipe_writer.send(self._worker.worker_address())\n self._worker.join()\n\n\nclass MultiProcessCluster(object):\n \"\"\"tf.data service cluster with local and remote workers.\n\n Represents a cluster with a dispatcher, `num_local_workers` local workers, and\n `num_remote_workers` remote workers. Remote workers run in separate processes.\n This is useful to test reading from local in-process workers. For example:\n\n ```\n cluster = multi_process_cluster.MultiProcessCluster(\n num_local_workers=1, num_remote_workers=3)\n num_elements = 10\n dataset = self.make_distributed_range_dataset(\n num_elements, cluster, target_workers=\"LOCAL\")\n self.assertDatasetProduces(dataset, list(range(num_elements)))\n ```\n \"\"\"\n\n def __init__(self,\n num_local_workers,\n num_remote_workers,\n worker_addresses=None):\n self._start_dispatcher(worker_addresses)\n self._start_local_workers(num_local_workers)\n self._start_remote_workers(num_remote_workers)\n\n def _start_dispatcher(self, worker_addresses):\n work_dir = tempfile.mkdtemp(dir=googletest.GetTempDir())\n self._dispatcher = server_lib.DispatchServer(\n server_lib.DispatcherConfig(\n port=0,\n work_dir=work_dir,\n protocol=\"grpc\",\n worker_addresses=worker_addresses),\n start=True)\n\n def _start_local_workers(self, num_workers):\n self._local_workers = []\n for _ in range(num_workers):\n self.start_local_worker()\n\n def _start_remote_workers(self, num_workers):\n # List of (worker address, remote worker process) tuples.\n self._remote_workers = []\n for _ in range(num_workers):\n self.start_remote_worker()\n\n def start_local_worker(self):\n worker = data_service_test_base.TestWorker(\n self.dispatcher_address(), _WORKER_SHUTDOWN_QUIET_PERIOD_MS)\n worker.start()\n self._local_workers.append(worker)\n\n def start_remote_worker(self):\n pipe_reader, pipe_writer = multi_process_lib.multiprocessing.Pipe(\n duplex=False)\n worker_process = _RemoteWorkerProcess(\n self.dispatcher_address(), pipe_writer)\n worker_process.start()\n worker_address = pipe_reader.recv()\n self._remote_workers.append((worker_address, worker_process))\n\n def dispatcher_address(self):\n return self._dispatcher._address\n\n def local_worker_addresses(self):\n return [worker.worker_address() for worker in self._local_workers]\n\n def remote_worker_addresses(self):\n return [worker[0] for worker in self._remote_workers]\n\n def _stop(self):\n for worker in self._local_workers:\n worker.stop()\n for worker in self._remote_workers:\n worker[1].terminate()\n self._dispatcher._stop()\n\n def __del__(self):\n self._stop()\n\n\ndef test_main():\n \"\"\"Main function to be called within `__main__` of a test file.\"\"\"\n multi_process_lib.test_main()\n", "# 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\"\"\"Tests for tensorflow.kernels.sparse_op.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import sparse_ops\nfrom tensorflow.python.platform import test\n\n\nclass SparseToDenseTest(test.TestCase):\n\n def testInt(self):\n tf_ans = sparse_ops.sparse_to_dense([1, 3], [5], 1, 0)\n np_ans = np.array([0, 1, 0, 1, 0]).astype(np.int32)\n self.assertAllClose(np_ans, tf_ans)\n\n def testFloat(self):\n tf_ans = sparse_ops.sparse_to_dense([1, 3], [5], 1.0, 0.0)\n np_ans = np.array([0, 1, 0, 1, 0]).astype(np.float32)\n self.assertAllClose(np_ans, tf_ans)\n\n def testEmptyNonZeros(self):\n indices = array_ops.constant([], dtype=dtypes.int32)\n values = array_ops.constant([], dtype=dtypes.float32)\n tf_ans = sparse_ops.sparse_to_dense(indices, [5], values, 0.0)\n np_ans = np.array([0, 0, 0, 0, 0]).astype(np.float32)\n self.assertAllClose(np_ans, tf_ans)\n\n def testString(self):\n tf_ans = sparse_ops.sparse_to_dense([1, 3], [5], \"a\", \"b\")\n np_ans = np.array([\"b\", \"a\", \"b\", \"a\", \"b\"]).astype(np.string_)\n self.assertAllEqual(np_ans, tf_ans)\n\n def testSetValue(self):\n tf_ans = sparse_ops.sparse_to_dense([1, 3], [5], [1, 2], -1)\n np_ans = np.array([-1, 1, -1, 2, -1]).astype(np.int32)\n self.assertAllClose(np_ans, tf_ans)\n\n def testSetSingleValue(self):\n tf_ans = sparse_ops.sparse_to_dense([1, 3], [5], 1, -1)\n np_ans = np.array([-1, 1, -1, 1, -1]).astype(np.int32)\n self.assertAllClose(np_ans, tf_ans)\n\n def test2d(self):\n tf_ans = sparse_ops.sparse_to_dense([[1, 3], [2, 0]], [3, 4], 1, -1)\n np_ans = np.array([[-1, -1, -1, -1],\n [-1, -1, -1, 1],\n [1, -1, -1, -1]]).astype(np.int32)\n self.assertAllClose(np_ans, tf_ans)\n\n def testZeroDefault(self):\n x = sparse_ops.sparse_to_dense(2, [4], 7)\n self.assertAllEqual(x, [0, 0, 7, 0])\n\n def test3d(self):\n tf_ans = sparse_ops.sparse_to_dense([[1, 3, 0], [2, 0, 1]], [3, 4, 2], 1,\n -1)\n np_ans = np.ones((3, 4, 2), dtype=np.int32) * -1\n np_ans[1, 3, 0] = 1\n np_ans[2, 0, 1] = 1\n self.assertAllClose(np_ans, tf_ans)\n\n def testBadShape(self):\n with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError),\n \"must be rank 1\"):\n sparse_ops.sparse_to_dense([1, 3], [[5], [3]], 1, -1)\n\n def testBadValue(self):\n with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError),\n r\"sparse_values has incorrect shape \\[2,1\\], \"\n r\"should be \\[\\] or \\[2\\]\"):\n self.evaluate(sparse_ops.sparse_to_dense([1, 3], [5], [[5], [3]], -1))\n\n def testBadNumValues(self):\n with self.assertRaisesRegex(\n (ValueError, errors.InvalidArgumentError),\n r\"sparse_values has incorrect shape \\[3\\], should be \\[\\] or \\[2\\]\"):\n self.evaluate(sparse_ops.sparse_to_dense([1, 3], [5], [1, 2, 3], -1))\n\n def testBadDefault(self):\n with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError),\n \"default_value should be a scalar\"):\n self.evaluate(sparse_ops.sparse_to_dense([1, 3], [5], [1, 2], [0]))\n\n @test_util.disable_xla(\"XLA does not check validity for SparseToDense\")\n def testOutOfBoundsIndicesWithWithoutValidation(self):\n # The GPU implementation doesn't print the contents of the invalid inputs,\n # since the overhead of memory copy between device to host is large.\n # Therefore, the following three tests on invalid inputs will distinguish\n # the reference error messages between GPUs and CPUs.\n error_msg = (r\"out of bounds\" if test_util.is_gpu_available() else\n r\"indices\\[1\\] = \\[10\\] is out of bounds: need 0 <= \"\n \"index < \\[5\\]\")\n with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError),\n error_msg):\n self.evaluate(\n sparse_ops.sparse_to_dense([[1], [10]], [5], [1.0, 1.0], 0.0))\n # When validate_indices=False, the GPU kernel won't check out-of-bound\n # access. Therefore, we skip the following test.\n if not test_util.is_gpu_available():\n # Disable checks, the allocation should still fail.\n with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError),\n \"out of bounds\"):\n self.evaluate(\n sparse_ops.sparse_to_dense([[1], [10]], [5], [-1.0, 1.0],\n 0.0,\n validate_indices=False))\n\n @test_util.disable_xla(\"XLA does not check validity for SparseToDense\")\n def testRepeatingIndicesWithWithoutValidation(self):\n error_msg = (r\"indices\\[1\\] is repeated\" if test_util.is_gpu_available()\n else r\"indices\\[1\\] = \\[1\\] is repeated\")\n with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError),\n error_msg):\n self.evaluate(\n sparse_ops.sparse_to_dense([[1], [1]], [5], [-1.0, 1.0], 0.0))\n # Disable checks\n self.evaluate(\n sparse_ops.sparse_to_dense([[1], [1]], [5], [-1.0, 1.0],\n 0.0,\n validate_indices=False))\n\n @test_util.disable_xla(\"XLA does not check validity for SparseToDense\")\n def testUnsortedIndicesWithWithoutValidation(self):\n error_msg = (r\"indices\\[1\\] is out of order\"\n if test_util.is_gpu_available() else\n r\"indices\\[1\\] = \\[1\\] is out of order\")\n with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError),\n error_msg):\n self.evaluate(\n sparse_ops.sparse_to_dense([[2], [1]], [5], [-1.0, 1.0], 0.0))\n # Disable checks\n self.evaluate(\n sparse_ops.sparse_to_dense([[2], [1]], [5], [-1.0, 1.0],\n 0.0,\n validate_indices=False))\n\n def testShapeInferenceKnownShape(self):\n with ops.Graph().as_default():\n indices = array_ops.placeholder(dtypes.int64)\n\n shape = [4, 5, 6]\n output = sparse_ops.sparse_to_dense(indices, shape, 1, 0)\n self.assertEqual(output.get_shape(), [4, 5, 6])\n\n shape = array_ops.placeholder(dtypes.int64, shape=(3,))\n output = sparse_ops.sparse_to_dense(indices, shape, 1, 0)\n self.assertEqual(output.get_shape().as_list(), [None, None, None])\n\n def testShapeInferenceUnknownShape(self):\n with ops.Graph().as_default():\n indices = array_ops.placeholder(dtypes.int64)\n shape = array_ops.placeholder(dtypes.int64)\n output = sparse_ops.sparse_to_dense(indices, shape, 1, 0)\n self.assertIsNone(output.get_shape().ndims)\n\n\nif __name__ == \"__main__\":\n test.main()\n", "# Copyright 2018 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 tensorflow.ops.tf.MatrixTriangularSolve.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport itertools\n\nimport numpy as np\n\nfrom tensorflow.compiler.tests import xla_test\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import linalg_ops\nfrom tensorflow.python.platform import test\n\n\ndef MakePlaceholder(x):\n return array_ops.placeholder(dtypes.as_dtype(x.dtype), shape=x.shape)\n\n\nclass MatrixTriangularSolveOpTest(xla_test.XLATestCase):\n\n # MatrixTriangularSolve defined for float64, float32, complex64, complex128\n # (https://www.tensorflow.org/api_docs/python/tf/matrix_triangular_solve)\n @property\n def float_types(self):\n return set(super(MatrixTriangularSolveOpTest,\n self).float_types).intersection(\n (np.float64, np.float32, np.complex64, np.complex128))\n\n def _VerifyTriangularSolveBase(self, sess, placeholder_a, placeholder_ca,\n placeholder_b, a, clean_a, b, verification,\n atol):\n feed_dict = {placeholder_a: a, placeholder_ca: clean_a, placeholder_b: b}\n verification_np = sess.run(verification, feed_dict)\n broadcasted_shape = a.shape[:-2] + (b.shape[-2], b.shape[-1])\n broadcasted_b = b + np.zeros(shape=broadcasted_shape, dtype=b.dtype)\n self.assertAllClose(broadcasted_b, verification_np, atol=atol)\n\n def _VerifyTriangularSolve(self, a, b, lower, adjoint, atol):\n clean_a = np.tril(a) if lower else np.triu(a)\n with self.session() as sess:\n placeholder_a = MakePlaceholder(a)\n placeholder_ca = MakePlaceholder(clean_a)\n placeholder_b = MakePlaceholder(b)\n with self.test_scope():\n x = linalg_ops.matrix_triangular_solve(\n placeholder_a, placeholder_b, lower=lower, adjoint=adjoint)\n verification = test_util.matmul_without_tf32(\n placeholder_ca, x, adjoint_a=adjoint)\n self._VerifyTriangularSolveBase(sess, placeholder_a, placeholder_ca,\n placeholder_b, a, clean_a, b,\n verification, atol)\n\n def _VerifyTriangularSolveCombo(self, a, b, atol=1e-4):\n transp = lambda x: np.swapaxes(x, -1, -2)\n for lower, adjoint in itertools.product([True, False], repeat=2):\n self._VerifyTriangularSolve(\n a if lower else transp(a), b, lower, adjoint, atol)\n\n def testBasic(self):\n rng = np.random.RandomState(0)\n a = np.tril(rng.randn(5, 5))\n b = rng.randn(5, 7)\n for dtype in self.float_types:\n self._VerifyTriangularSolveCombo(a.astype(dtype), b.astype(dtype))\n\n def testBasicNotActuallyTriangular(self):\n rng = np.random.RandomState(0)\n a = rng.randn(5, 5) # the `a` matrix is not lower-triangular\n b = rng.randn(5, 7)\n for dtype in self.float_types:\n self._VerifyTriangularSolveCombo(a.astype(dtype), b.astype(dtype))\n\n def testBasicComplexDtypes(self):\n\n if xla_test.test.is_built_with_rocm():\n # The folowing subtest invokes the call to \"BlasTrsm\"\n # That operation is currently not supported on the ROCm platform\n self.skipTest(\"BlasTrsm op for complex types is not supported in ROCm\")\n\n rng = np.random.RandomState(0)\n a = np.tril(rng.randn(5, 5) + rng.randn(5, 5) * 1j)\n b = rng.randn(5, 7) + rng.randn(5, 7) * 1j\n for dtype in self.complex_types:\n self._VerifyTriangularSolveCombo(a.astype(dtype), b.astype(dtype))\n\n def testBatch(self):\n rng = np.random.RandomState(0)\n shapes = [((4, 3, 3), (4, 3, 5)), ((1, 2, 2), (1, 2, 1)),\n ((1, 1, 1), (1, 1, 2)), ((2, 3, 4, 4), (2, 3, 4, 1))]\n tuples = itertools.product(self.float_types, shapes)\n for dtype, (a_shape, b_shape) in tuples:\n n = a_shape[-1]\n a = np.tril(rng.rand(*a_shape) - 0.5) / (2.0 * n) + np.eye(n)\n b = rng.randn(*b_shape)\n self._VerifyTriangularSolveCombo(\n a.astype(dtype), b.astype(dtype), atol=1e-3)\n\n def testBatchBroadcast(self):\n rng = np.random.RandomState(0)\n shapes = [((3, 3), (4, 3, 5)), ((1, 2, 2), (3, 2, 1)), ((1, 1), (1, 1, 2)),\n ((1, 3, 4, 4), (2, 1, 4, 1))]\n tuples = itertools.product(self.float_types, shapes)\n for dtype, (a_shape, b_shape) in tuples:\n n = a_shape[-1]\n a = np.tril(rng.rand(*a_shape) - 0.5) / (2.0 * n) + np.eye(n)\n b = rng.randn(*b_shape)\n self._VerifyTriangularSolveCombo(\n a.astype(dtype), b.astype(dtype), atol=1e-3)\n\n def testLarge(self):\n n = 1024\n rng = np.random.RandomState(0)\n a = np.tril(rng.rand(n, n) - 0.5) / (2.0 * n) + np.eye(n)\n b = rng.randn(n, n)\n self._VerifyTriangularSolve(\n a.astype(np.float32), b.astype(np.float32), True, False, 1e-4)\n\n @test_util.disable_mlir_bridge(\"Error handling\")\n def testNonSquareCoefficientMatrix(self):\n rng = np.random.RandomState(0)\n for dtype in self.float_types:\n a = rng.randn(3, 4).astype(dtype)\n b = rng.randn(4, 4).astype(dtype)\n with self.test_scope():\n with self.assertRaises((ValueError, errors.InvalidArgumentError)):\n linalg_ops.matrix_triangular_solve(a, b)\n\n @test_util.run_v2_only # Different error types\n @test_util.disable_mlir_bridge(\"Error handling\")\n def testWrongDimensionsV2(self):\n randn = np.random.RandomState(0).randn\n for dtype in self.float_types:\n lhs = constant_op.constant(randn(3, 3), dtype=dtype)\n rhs = constant_op.constant(randn(4, 3), dtype=dtype)\n with self.assertRaises(errors.InvalidArgumentError):\n linalg_ops.matrix_triangular_solve(lhs, rhs)\n with self.assertRaises(errors.InvalidArgumentError):\n linalg_ops.matrix_triangular_solve(lhs, rhs)\n\n @test_util.run_v1_only(\"Different error types\")\n @test_util.disable_mlir_bridge(\"Error handling\")\n def testWrongDimensionsV1(self):\n randn = np.random.RandomState(0).randn\n for dtype in self.float_types:\n lhs = constant_op.constant(randn(3, 3), dtype=dtype)\n rhs = constant_op.constant(randn(4, 3), dtype=dtype)\n with self.assertRaises(ValueError):\n linalg_ops.matrix_triangular_solve(lhs, rhs)\n with self.assertRaises(ValueError):\n linalg_ops.matrix_triangular_solve(lhs, rhs)\n\n\nif __name__ == \"__main__\":\n test.main()\n", "# Copyright 2020 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\"\"\"Keras index lookup preprocessing layer.\"\"\"\n# pylint: disable=g-classes-have-attributes\n\nimport collections\nimport json\nimport operator\n\nimport numpy as np\n\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.framework import tensor_spec\nfrom tensorflow.python.framework import tensor_util\nfrom tensorflow.python.keras import backend\nfrom tensorflow.python.keras.engine import base_preprocessing_layer\nfrom tensorflow.python.keras.layers.preprocessing import category_encoding\nfrom tensorflow.python.keras.layers.preprocessing import table_utils\nfrom tensorflow.python.keras.saving.saved_model import layer_serialization\nfrom tensorflow.python.keras.utils import layer_utils\nfrom tensorflow.python.keras.utils import tf_utils\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import init_ops\nfrom tensorflow.python.ops import lookup_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import sparse_ops\nfrom tensorflow.python.ops import string_ops\nfrom tensorflow.python.platform import gfile\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.util import compat\n\nINT = \"int\"\nMULTI_HOT = \"multi_hot\"\nONE_HOT = \"one_hot\"\nCOUNT = \"count\"\nTF_IDF = \"tf_idf\"\n\n_VOCAB_NAME = \"vocab\"\n_IDF_WEIGHTS_NAME = \"idf_weights\"\n\n\nclass _NullInitializer(lookup_ops.TextFileInitializer):\n \"\"\"A placeholder initializer for restoring this layer from a SavedModel.\"\"\"\n\n def __init__(self, key_dtype, value_dtype):\n \"\"\"Construct a table initializer object.\n\n Args:\n key_dtype: Type of the table keys.\n value_dtype: Type of the table values.\n \"\"\"\n self._key_dtype = dtypes.as_dtype(key_dtype)\n self._value_dtype = dtypes.as_dtype(value_dtype)\n\n @property\n def key_dtype(self):\n \"\"\"The expected table key dtype.\"\"\"\n return self._key_dtype\n\n @property\n def value_dtype(self):\n \"\"\"The expected table value dtype.\"\"\"\n return self._value_dtype\n\n def initialize(self, table):\n \"\"\"Returns the table initialization op.\"\"\"\n pass\n\n @property\n def _shared_name(self):\n \"\"\"Returns a shared name to be used by the table.\"\"\"\n shared_name = \"NULL_INITIALIZER_\"\n if context.executing_eagerly():\n # Ensure a unique name when eager execution is enabled to avoid spurious\n # sharing issues..\n shared_name += str(backend.get_uid(shared_name))\n return shared_name\n\n\nclass IndexLookup(base_preprocessing_layer.CombinerPreprocessingLayer):\n \"\"\"Maps values from a vocabulary to integer indices.\n\n This layer translates a set of arbitrary hashables into an integer output via\n a table-based lookup, with optional out-of-vocabulary handling. This is the\n basis layer for both IntegerLookup and StringLookup; it holds the common\n logic but is not intended to be exported as part of the Keras API.\n\n Args:\n max_tokens: The maximum size of the vocabulary for this layer. If None,\n there is no cap on the size of the vocabulary. Note that this size\n includes the OOV and mask tokens.\n num_oov_indices: The number of out-of-vocabulary tokens to use. If this\n value is more than 1, OOV inputs are hashed to determine their OOV value.\n If this value is 0, OOV inputs will cause an error when calling the layer.\n mask_token: A token that represents masked inputs. When `output_mode` is\n `\"int\"`, the token is included in vocabulary and mapped to index 0. In\n other output modes, the token will not appear in the vocabulary and\n instances of the mask token in the input will be dropped. If set to None,\n no mask term will be added.\n oov_token: Only used when `invert` is True. The token to return for OOV\n indices.\n vocabulary: An optional list of vocabulary terms. If the list contains the\n same token multiple times, an error will be thrown.\n invert: Only valid when `output_mode` is `\"int\"`. If True, this layer will\n map indices to vocabulary items instead of mapping vocabulary items to\n indices. Default to False.\n output_mode: Specification for the output of the layer. Defaults to `\"int\"`.\n Values can be `\"int\"`, `\"one_hot\"`, `\"multi_hot\"`, `\"count\"`, or\n `\"tf_idf\"` configuring the layer as follows:\n - `\"int\"`: Return the raw integer indices of the input tokens.\n - `\"one_hot\"`: Encodes each individual element in the input into an\n array the same size as the vocabulary, containing a 1 at the element\n index. If the last dimension is size 1, will encode on that dimension.\n If the last dimension is not size 1, will append a new dimension for\n the encoded output.\n - `\"multi_hot\"`: Encodes each sample in the input into a single array\n the same size as the vocabulary, containing a 1 for each vocabulary\n term present in the sample. Treats the last dimension as the sample\n dimension, if input shape is (..., sample_length), output shape will\n be (..., num_tokens).\n - `\"count\"`: As `\"multi_hot\"`, but the int array contains a count of the\n number of times the token at that index appeared in the sample.\n - `\"tf_idf\"`: As `\"multi_hot\"`, but the TF-IDF algorithm is applied to\n find the value in each token slot.\n pad_to_max_tokens: Only valid when `output_mode` is `\"multi_hot\"`,\n `\"count\"`, or `\"tf_idf\"`. If True, the output will have its feature axis\n padded to `max_tokens` even if the number of unique tokens in the\n vocabulary is less than max_tokens, resulting in a tensor of shape\n [batch_size, max_tokens] regardless of vocabulary size. Defaults to False.\n sparse: Boolean. Only applicable to `\"multi_hot\"` and `\"count\"` output\n modes. If True, returns a `SparseTensor` instead of a dense `Tensor`.\n Defaults to False.\n \"\"\"\n\n def __init__(self,\n max_tokens,\n num_oov_indices,\n mask_token,\n oov_token,\n vocabulary=None,\n invert=False,\n output_mode=INT,\n sparse=False,\n pad_to_max_tokens=False,\n **kwargs):\n # If max_tokens is set, the value must be greater than 1 - otherwise we\n # are creating a 0-element vocab, which doesn't make sense.\n if max_tokens is not None and max_tokens <= 1:\n raise ValueError(\"If set, `max_tokens` must be greater than 1. \"\n \"You passed {}\".format(max_tokens))\n\n if num_oov_indices < 0:\n raise ValueError(\"`num_oov_indices` must be greater than or equal to 0. \"\n \"You passed {}\".format(num_oov_indices))\n\n # Support deprecated names for output_modes.\n if output_mode == \"binary\":\n output_mode = MULTI_HOT\n if output_mode == \"tf-idf\":\n output_mode = TF_IDF\n # 'output_mode' must be one of (INT, ONE_HOT, MULTI_HOT, COUNT, TF_IDF)\n layer_utils.validate_string_arg(\n output_mode,\n allowable_strings=(INT, ONE_HOT, MULTI_HOT, COUNT, TF_IDF),\n layer_name=self.__class__.__name__,\n arg_name=\"output_mode\")\n\n if invert and output_mode != INT:\n raise ValueError(\"`output_mode` must be {} when `invert` is true. You \"\n \"passed {}\".format(INT, output_mode))\n\n self.invert = invert\n self.max_tokens = max_tokens\n self.num_oov_indices = num_oov_indices\n self.output_mode = output_mode\n self.sparse = sparse\n self.pad_to_max_tokens = pad_to_max_tokens\n self._called = False\n\n # A note on vocab_size: we need to always keep a non-Tensor representation\n # of vocab_size around to use in graph building. Because we might be\n # in a tf.function, we can't rely on evaluating the actual tables to\n # find the value either.\n self._vocab_size = None\n # We need to keep track our current vocab size outside of our layer weights\n # to support a static output shape when `output_mode != INT`. The bincount\n # ops do not set shape on their outputs, which means we have to set it\n # ourselves. We persist the current vocab size as a hidden part of the\n # config when serializing our model.\n if \"vocabulary_size\" in kwargs:\n self._vocab_size = kwargs[\"vocabulary_size\"]\n del kwargs[\"vocabulary_size\"]\n\n restore_from_static_table = kwargs.pop(\"has_static_table\", False)\n\n # Make sure the mask token and oov token are truly of the dtype we want. We\n # can ignore strings here, because they have only one dtype.\n dtype = kwargs[\"dtype\"]\n if dtype == dtypes.int32:\n mask_token = None if mask_token is None else np.int32(mask_token)\n oov_token = None if oov_token is None else np.int32(oov_token)\n elif dtype == dtypes.int64:\n mask_token = None if mask_token is None else np.int64(mask_token)\n oov_token = None if oov_token is None else np.int64(oov_token)\n self.mask_token = mask_token\n self.oov_token = oov_token\n\n if max_tokens is not None:\n available_vocab_size = max_tokens - self._token_start_index()\n else:\n available_vocab_size = None\n\n super(IndexLookup, self).__init__(\n combiner=_IndexLookupCombiner(\n vocab_size=available_vocab_size,\n mask_value=mask_token,\n oov_value=oov_token,\n compute_idf=(output_mode == TF_IDF)),\n **kwargs)\n\n # We need to save the key dtype so that we know if we're expecting int64\n # keys. If we are, we will cast int32 inputs to int64 as well.\n if invert:\n self._key_dtype = dtypes.int64\n self._value_dtype = self.dtype\n self._mask_key = 0\n self._mask_value = mask_token\n key_index = lookup_ops.TextFileIndex.LINE_NUMBER\n value_index = lookup_ops.TextFileIndex.WHOLE_LINE\n default_value = self.oov_token\n oov_indices = None\n else:\n self._key_dtype = self.dtype\n self._value_dtype = dtypes.int64\n self._mask_key = mask_token\n key_index = lookup_ops.TextFileIndex.WHOLE_LINE\n value_index = lookup_ops.TextFileIndex.LINE_NUMBER\n # Masks should map to 0 for int output and be dropped otherwise. Max ints\n # will be dropped from the bincount op.\n self._mask_value = 0 if self.output_mode == INT else dtypes.int64.max\n oov_start = self._oov_start_index()\n token_start = self._token_start_index()\n if self.num_oov_indices == 0:\n # If there are no OOV indices, we map OOV tokens to -1 and error out\n # during call if we find a negative index.\n default_value = -1\n oov_indices = None\n elif self.num_oov_indices == 1:\n # If there is only one OOV index, we can set that index as the default\n # value of the index_lookup table.\n default_value = oov_start\n oov_indices = None\n else:\n # If we hav multiple OOV values, we need to do a further hashing step;\n # to make this easier, we set the OOV value to -1. (This lets us do a\n # vectorized add and cast to boolean to determine locations where we\n # need to do extra hashing.)\n default_value = -1\n oov_indices = list(range(oov_start, token_start))\n\n self._static_vocabulary_path = None\n has_vocab_path = (vocabulary is not None and isinstance(vocabulary, str))\n if has_vocab_path or restore_from_static_table:\n self._has_static_table = True\n if vocabulary is None:\n # If we're restoring a layer that was saved with a static table\n # initializer, we create a fake initializer object to let the code\n # progress. The savedmodel restoration code will handle restoring\n # the actual data.\n initializer = _NullInitializer(self._key_dtype, self._value_dtype)\n else:\n if not gfile.Exists(vocabulary):\n raise ValueError(\"Vocabulary file %s does not exist.\" % (vocabulary,))\n self._static_vocabulary_path = vocabulary\n num_tokens = table_utils.num_tokens_in_file(vocabulary)\n self._vocab_size = self._token_start_index() + num_tokens\n\n initializer = lookup_ops.TextFileInitializer(\n filename=vocabulary,\n key_dtype=self._key_dtype,\n key_index=key_index,\n value_dtype=self._value_dtype,\n value_index=value_index,\n value_index_offset=self._token_start_index())\n\n self._table = lookup_ops.StaticHashTable(\n initializer, default_value=default_value)\n self._table_handler = table_utils.TableHandler(\n table=self._table,\n mask_token=self._mask_key if self.mask_token is not None else None,\n mask_value=self._mask_value,\n oov_tokens=oov_indices)\n\n tracked_table = self._add_trackable(self._table, trainable=False)\n\n else:\n self._has_static_table = False\n self._table = lookup_ops.MutableHashTable(\n key_dtype=self._key_dtype,\n value_dtype=self._value_dtype,\n default_value=default_value,\n name=(self._name + \"_index_table\"))\n self._table_handler = table_utils.TableHandler(\n table=self._table,\n oov_tokens=oov_indices)\n if vocabulary is not None:\n self.set_vocabulary(vocabulary)\n tracked_table = self._add_trackable(self._table, trainable=False)\n\n if self.output_mode == TF_IDF:\n # The TF-IDF weight may have a (None,) tensorshape. This creates\n # a 1D variable with arbitrary shape, which we can assign any weight to\n # so long as it has 1 dimension. In order to properly initialize this\n # weight in Keras, we need to provide a custom callable initializer which\n # does not depend on the shape of the weight (as all other initializers\n # do) since the weight is not known. Hence the lambda shape, dtype: [0].\n if not self.pad_to_max_tokens or max_tokens is None:\n initializer = lambda shape, dtype: [0]\n else:\n initializer = init_ops.zeros_initializer\n\n # We are adding these here instead of in build() since they do not depend\n # on the input shape at all.\n idf_shape = (max_tokens,) if self.pad_to_max_tokens else (None,)\n self.tf_idf_weights = self._add_state_variable(\n name=\"idf\",\n shape=tensor_shape.TensorShape(idf_shape),\n dtype=backend.floatx(),\n initializer=initializer)\n\n # This is a workaround for summary() on this layer. Because the table is\n # not mutable during training, the effective number of parameters (and so\n # the weight shape) is 0; we add this as an attr so that the parameter\n # counting code in the Model object doesn't throw an attribute error.\n tracked_table.shape = tensor_shape.TensorShape((0,))\n\n def compute_output_shape(self, input_shape):\n if self.output_mode == INT:\n return input_shape\n if self._vocab_size and not self.pad_to_max_tokens:\n out_depth = self._vocab_size\n else:\n out_depth = self.max_tokens\n return tensor_shape.TensorShape([input_shape[0], out_depth])\n\n def compute_output_signature(self, input_spec):\n output_shape = self.compute_output_shape(input_spec.shape.as_list())\n output_dtype = (self._value_dtype if self.output_mode == INT\n else backend.floatx())\n return tensor_spec.TensorSpec(shape=output_shape, dtype=output_dtype)\n\n def adapt(self, data, reset_state=True):\n \"\"\"Fits the state of the preprocessing layer to the dataset.\n\n Overrides the default adapt method to apply relevant preprocessing to the\n inputs before passing to the combiner.\n\n Args:\n data: The data to train on. It can be passed either as a tf.data Dataset,\n or as a numpy array.\n reset_state: Optional argument specifying whether to clear the state of\n the layer at the start of the call to `adapt`. This must be True for\n this layer, which does not support repeated calls to `adapt`.\n \"\"\"\n if not reset_state:\n raise ValueError(\"IndexLookup does not support streaming adapts.\")\n super(IndexLookup, self).adapt(data, reset_state)\n\n def get_vocabulary(self, include_special_tokens=True):\n \"\"\"Returns the current vocabulary of the layer.\n\n Args:\n include_special_tokens: If True, the returned vocabulary will include mask\n and OOV tokens, and a term's index in the vocabulary will equal the\n term's index when calling the layer. If False, the returned vocabulary\n will not include any mask or OOV tokens.\n \"\"\"\n if self.vocabulary_size() is None:\n return []\n\n # The MutableHashTable data will not be sorted, so we will create a inverted\n # lookup here, and use that to lookup a range of indices [0, vocab_size).\n keys, values = self._table.export()\n vocab, indices = (values, keys) if self.invert else (keys, values)\n lookup = collections.defaultdict(\n lambda: self.oov_token,\n zip(indices.numpy(), self._tensor_vocab_to_numpy(vocab)))\n vocab = [lookup[x] for x in range(self.vocabulary_size())]\n if self.mask_token is not None and self.output_mode == INT:\n vocab[0] = self.mask_token\n if not include_special_tokens:\n vocab = vocab[self._token_start_index():]\n return vocab\n\n def vocabulary_size(self):\n \"\"\"Gets the current size of the layer's vocabulary.\n\n Returns:\n The integer size of the voculary, including optional mask and oov indices.\n \"\"\"\n return self._vocab_size\n\n def vocab_size(self):\n logging.warning(\"vocab_size is deprecated, please use vocabulary_size.\")\n return self.vocabulary_size()\n\n def get_config(self):\n if self._has_static_table:\n vocabulary_path = self._static_vocabulary_path\n else:\n vocabulary_path = None\n\n config = {\n \"invert\": self.invert,\n \"max_tokens\": self.max_tokens,\n \"num_oov_indices\": self.num_oov_indices,\n \"oov_token\": self.oov_token,\n \"mask_token\": self.mask_token,\n \"output_mode\": self.output_mode,\n \"pad_to_max_tokens\": self.pad_to_max_tokens,\n \"vocabulary_size\": self.vocabulary_size(),\n \"vocabulary\": vocabulary_path,\n }\n if self._has_static_table:\n config[\"has_static_table\"] = True\n\n base_config = super(IndexLookup, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n def count_params(self):\n # This method counts the number of scalars in the weights of this layer.\n # Since this layer doesn't have any /actual/ weights (in that there's\n # nothing in this layer that can be trained - we only use the weight\n # abstraction for ease of saving!) we return 0.\n return 0\n\n def set_vocabulary(self, vocabulary, idf_weights=None):\n \"\"\"Sets vocabulary (and optionally document frequency) data for this layer.\n\n This method sets the vocabulary and idf weights for this layer directly,\n instead of analyzing a dataset through `adapt`. It should be used whenever\n the vocab (and optionally document frequency) information is already known.\n If vocabulary data is already present in the layer, this method will replace\n it.\n\n Args:\n vocabulary: An array, numpy array, or tensor of hashable tokens.\n idf_weights: An array, numpy array, or tensor of inverse document\n frequency weights with equal length to vocab. Only necessary if the\n layer output_mode is TF_IDF.\n\n Raises:\n ValueError: If there are too many inputs, the inputs do not match, or\n input data is missing.\n RuntimeError: If the vocabulary cannot be set when this function is\n called. This happens when `\"multi_hot\"`, `\"count\"`, and `\"tfidf\"` modes,\n if `pad_to_max_tokens` is False and the layer itself has already been\n called.\n RuntimeError: If a tensor vocabulary is passed outside of eager execution.\n \"\"\"\n if self._has_static_table:\n raise RuntimeError(\"Layer {} was created with a static file-based table \"\n \"because a file path was passed to the layer \"\n \"init. Layers created with static file-based tables \"\n \"do not support changing the vocabulary after \"\n \"creation.\".format(self.name))\n\n if self.output_mode != TF_IDF and idf_weights is not None:\n raise ValueError(\"`idf_weights` should only be set if output_mode is \"\n \"TF_IDF. output_mode is {}.\".format(self.output_mode))\n\n if (self.output_mode in [MULTI_HOT, COUNT, TF_IDF] and self._called and\n not self.pad_to_max_tokens):\n raise RuntimeError(\"When using {} mode and `pad_to_max_tokens` is \"\n \"False, the vocabulary cannot be changed after the \"\n \"layer is called.\".format(self.output_mode))\n\n if not context.executing_eagerly() and (tensor_util.is_tensor(vocabulary) or\n tensor_util.is_tensor(idf_weights)):\n raise RuntimeError(\n \"Cannot set a tensor vocabulary on {} layer {} when not executing \"\n \"eagerly. Create this layer or call `set_vocabulary` outside of \"\n \"any `tf.function`s and with eager execution enabled.\".format(\n self.__class__.__name__, self.name))\n\n # TODO(mattdangerw): for better performance we should rewrite this entire\n # function to operate on tensors and convert vocabulary to a tensor here.\n if tensor_util.is_tensor(vocabulary):\n vocabulary = self._tensor_vocab_to_numpy(vocabulary)\n if tensor_util.is_tensor(idf_weights):\n idf_weights = idf_weights.numpy()\n\n oov_start = self._oov_start_index()\n token_start = self._token_start_index()\n should_have_mask = (oov_start > 0)\n has_mask = should_have_mask and vocabulary[0] == self.mask_token\n\n should_have_oov = (self.num_oov_indices > 0)\n expected_oov = [self.oov_token] * self.num_oov_indices\n found_oov = vocabulary[oov_start:token_start]\n has_oov = should_have_oov and found_oov == expected_oov\n # If we get a numpy array, then has_oov may end up being a numpy array\n # instead of a bool. Fix this by collapsing the variable if it's not bool.\n if not isinstance(has_oov, bool):\n has_oov = any(has_oov)\n\n if all([should_have_mask, has_mask, should_have_oov]) and not has_oov:\n raise ValueError(\n \"Invalid vocabulary format. The layer was created with \"\n \"`mask_token={mask}` and `oov_token={oov}`. These tokens should be \"\n \"included in the provided vocabulary. The passed vocabulary has the \"\n \"correct mask token `{mask}` at index 0, but does not have the OOV \"\n \"token `{oov}` in indices [{start}:{end}]. Instead, we found \"\n \"`{found}`. Was this vocabulary generated by a layer with \"\n \"incompatible settings?\".format(\n mask=self.mask_token,\n oov=self.oov_token,\n start=oov_start,\n end=token_start,\n found=found_oov))\n\n if all([should_have_oov, has_oov, should_have_mask]) and not has_mask:\n raise ValueError(\n \"Invalid vocabulary format. The layer was created with \"\n \"`mask_token={mask}` and `oov_token={oov}`. These tokens should be \"\n \"included in the provided vocabulary. The passed vocabulary has the \"\n \"correct OOV token `{oov}` at indices [{start}:{end}], but does not \"\n \"have the mask token `{mask}` in index 0. Instead, we found \"\n \"`{found}`. Was this vocabulary generated by a layer with \"\n \"incompatible settings?\".format(\n mask=self.mask_token,\n oov=self.oov_token,\n start=oov_start,\n end=token_start,\n found=vocabulary[0]))\n\n found_special_tokens = has_oov or has_mask\n if found_special_tokens:\n tokens = vocabulary[token_start:]\n else:\n tokens = vocabulary\n\n repeated_tokens = table_utils.find_repeated_tokens(tokens)\n if repeated_tokens:\n raise ValueError(\"The passed vocabulary has at least one repeated \"\n \"term. Please uniquify your dataset. The repeated terms \"\n \"are {}\".format(repeated_tokens))\n\n if self.mask_token in tokens:\n raise ValueError(\"Reserved mask token {} was found in the passed \"\n \"vocabulary at index {}. Please either remove the \"\n \"reserved token from the vocabulary or change the \"\n \"mask token for this layer.\".format(\n self.mask_token, tokens.index(self.mask_token)))\n if self.oov_token in tokens:\n raise ValueError(\"Reserved OOV token {} was found in the passed \"\n \"vocabulary at index {}. Please either remove the \"\n \"reserved token from the vocabulary or change the \"\n \"OOV token for this layer.\".format(\n self.oov_token, tokens.index(self.oov_token)))\n\n self._vocab_size = token_start + len(tokens)\n if self.max_tokens is not None and self._vocab_size > self.max_tokens:\n raise ValueError(\n \"Attempted to set a vocabulary larger than the maximum vocab size. \"\n \"Passed vocab size is {}, max vocab size is {}.\".format(\n self._vocab_size, self.max_tokens))\n\n if self.output_mode == TF_IDF:\n if idf_weights is None:\n raise ValueError(\"`idf_weights` must be set if output_mode is TF_IDF\")\n if len(vocabulary) != len(idf_weights):\n raise ValueError(\"`idf_weights` must be the same length as vocabulary. \"\n \"len(idf_weights) is {}, len(vocabulary) is {}\".format(\n len(vocabulary), len(idf_weights)))\n idf_weights = self._convert_to_ndarray(idf_weights)\n if idf_weights.ndim != 1:\n raise ValueError(\n \"TF-IDF data must be a 1-index array, but received {}\".format(\n type(idf_weights)))\n\n # We add the non-special vocab tokens and optionally the mask_token to our\n # hash table. OOV tokens are handled with the hash table default value and\n # not added directly.\n self._table_handler.clear()\n indices = np.arange(token_start, len(tokens) + token_start, dtype=np.int64)\n if self.invert:\n self._table_handler.insert(indices, tokens)\n else:\n self._table_handler.insert(tokens, indices)\n if self.mask_token is not None:\n self._table_handler.insert([self._mask_key], [self._mask_value])\n\n if self.output_mode == TF_IDF:\n # If the passed vocabulary has no special tokens, we need to pad the front\n # of idf_weights. We don't have real document frequencies for these tokens\n # so we will use an average of all idf_weights passed in as a reasonable\n # default.\n if found_special_tokens:\n front_padding = 0\n front_padding_value = 0\n else:\n front_padding = token_start\n front_padding_value = np.average(idf_weights)\n # If pad_to_max_tokens is true, and max_tokens is greater than our total\n # vocab size, we need to pad the back of idf_weights with zeros as well.\n back_padding_value = 0\n if self.pad_to_max_tokens and self.max_tokens is not None:\n back_padding = self.max_tokens - front_padding - len(idf_weights)\n else:\n back_padding = 0\n idf_weights = np.pad(\n idf_weights, (front_padding, back_padding),\n \"constant\",\n constant_values=(front_padding_value, back_padding_value))\n backend.set_value(self.tf_idf_weights, idf_weights)\n\n def _set_state_variables(self, updates):\n if not self.built:\n raise RuntimeError(\"_set_state_variables() must be called after build().\")\n self.set_vocabulary(\n updates[_VOCAB_NAME], idf_weights=updates[_IDF_WEIGHTS_NAME])\n\n def call(self, inputs):\n if isinstance(inputs, (list, tuple, np.ndarray)):\n inputs = ops.convert_to_tensor_v2_with_dispatch(inputs)\n\n if not self.max_tokens and self._vocab_size is None:\n raise ValueError(\"You must set the layer's vocabulary before calling it. \"\n \"Either pass a `vocabulary` argument to the layer, or \"\n \"call `layer.adapt(dataset)` with some sample data.\")\n self._called = True\n if self._key_dtype == dtypes.int64 and inputs.dtype == dtypes.int32:\n inputs = math_ops.cast(inputs, dtypes.int64)\n lookup_result = self._table_handler.lookup(inputs)\n\n lookup_checks = []\n\n if self.num_oov_indices == 0 and not self.invert:\n if tf_utils.is_sparse(inputs):\n lookup_values = lookup_result.values\n input_values = inputs.values\n elif tf_utils.is_ragged(inputs):\n lookup_values = lookup_result.flat_values\n input_values = inputs.flat_values\n else:\n lookup_values = lookup_result\n input_values = inputs\n oov_indices = array_ops.where_v2(math_ops.equal(lookup_values, -1))\n oov_inputs = array_ops.gather_nd(input_values, oov_indices)\n msg = string_ops.string_format(\n \"When `num_oov_indices=0` all inputs should be in vocabulary, \"\n \"found OOV values {}, consider setting `num_oov_indices=1`.\",\n (oov_inputs,))\n assertion = control_flow_ops.Assert(\n math_ops.equal(array_ops.size(oov_indices), 0), [msg])\n lookup_checks.append(assertion)\n\n with ops.control_dependencies(lookup_checks):\n if self.output_mode == INT:\n return array_ops.identity(lookup_result)\n else:\n return self._encode_output(lookup_result)\n\n def _encode_output(self, lookup_result):\n def expand_dims(inputs, axis):\n if tf_utils.is_sparse(inputs):\n return sparse_ops.sparse_expand_dims(inputs, axis)\n else:\n return array_ops.expand_dims(inputs, axis)\n\n original_shape = lookup_result.shape\n # In all cases, we should uprank scalar input to a single sample.\n if lookup_result.shape.rank == 0:\n lookup_result = expand_dims(lookup_result, -1)\n # One hot will unprank only if the final output dimension is not already 1.\n if self.output_mode == ONE_HOT:\n if lookup_result.shape[-1] != 1:\n lookup_result = expand_dims(lookup_result, -1)\n\n # TODO(b/190445202): remove output rank restriction.\n if lookup_result.shape.rank > 2:\n raise ValueError(\n \"Received input shape {}, which would result in output rank {}. \"\n \"Currently only outputs up to rank 2 are supported for \"\n \"`output_mode={}`.\".format(original_shape, lookup_result.shape.rank,\n self.output_mode))\n\n binary_output = self.output_mode in (MULTI_HOT, ONE_HOT)\n if self._vocab_size and not self.pad_to_max_tokens:\n out_depth = self._vocab_size\n else:\n out_depth = self.max_tokens\n if self.sparse:\n bincounts = category_encoding.sparse_bincount(lookup_result, out_depth,\n binary_output)\n else:\n bincounts = category_encoding.dense_bincount(lookup_result, out_depth,\n binary_output)\n\n if self.output_mode == TF_IDF:\n return math_ops.multiply(bincounts, self.tf_idf_weights)\n\n return bincounts\n\n def _convert_to_ndarray(self, x):\n return np.array(x) if isinstance(x, (list, tuple)) else x\n\n def _oov_start_index(self):\n return 1 if self.mask_token is not None and self.output_mode == INT else 0\n\n def _token_start_index(self):\n return self._oov_start_index() + self.num_oov_indices\n\n @property\n def _trackable_saved_model_saver(self):\n return layer_serialization.IndexLookupLayerSavedModelSaver(self)\n\n # Override points for IntegerLookup and StringLookup.\n def _tensor_vocab_to_numpy(self, vocabulary):\n \"\"\"Converts a tensor vocabulary to a numpy vocabulary.\"\"\"\n return vocabulary.numpy()\n\n\nclass _IndexLookupAccumulator(\n collections.namedtuple(\"Accumulator\",\n [\"data\", \"count_dict\", \"per_doc_count_dict\"])):\n pass\n\n\nclass _IndexLookupCombiner(base_preprocessing_layer.Combiner):\n \"\"\"Combiner for the IndexLookup preprocessing layer.\n\n This class encapsulates the logic for computing a vocabulary based on the\n frequency of each token.\n\n Attributes:\n vocab_size: (Optional) If set, only the top `vocab_size` tokens (based on\n frequency across the dataset) are retained in the vocabulary. If None, or\n set to a value greater than the total number of distinct tokens in the\n dataset, all tokens are retained.\n \"\"\"\n\n def __init__(self,\n vocab_size=None,\n mask_value=None,\n oov_value=None,\n compute_idf=False):\n self._vocab_size = vocab_size\n self._mask_value = mask_value\n self._oov_value = oov_value\n self._compute_idf = compute_idf\n\n def compute(self, values, accumulator=None):\n \"\"\"Compute a step in this computation, returning a new accumulator.\"\"\"\n values = base_preprocessing_layer.convert_to_list(\n values, sparse_default_value=self._mask_value)\n\n if accumulator is None:\n accumulator = self._create_accumulator()\n\n # TODO(momernick): Benchmark improvements to this algorithm.\n if not isinstance(values, list):\n values = [values]\n for document in values:\n if not isinstance(document, list):\n document = [document]\n if self._compute_idf:\n current_doc_id = accumulator.data[\"next_doc_id\"]\n accumulator.data[\"next_doc_id\"] += 1\n for token in document:\n accumulator.count_dict[token] += 1\n if self._compute_idf:\n doc_count = accumulator.per_doc_count_dict[token]\n if doc_count[\"last_doc_id\"] != current_doc_id:\n doc_count[\"count\"] += 1\n doc_count[\"last_doc_id\"] = current_doc_id\n\n return accumulator\n\n def merge(self, accumulators):\n \"\"\"Merge several accumulators to a single accumulator.\"\"\"\n if not accumulators:\n return accumulators\n\n base_accumulator = accumulators[0]\n for accumulator in accumulators[1:]:\n for token, value in accumulator.count_dict.items():\n base_accumulator.count_dict[token] += value\n\n if self._compute_idf:\n base_accumulator.data[\"next_doc_id\"] += accumulator.data[\"next_doc_id\"]\n if self._compute_idf:\n for token, value in accumulator.per_doc_count_dict.items():\n # Any newly created token counts in 'base_accumulator''s\n # per_doc_count_dict will have a last_doc_id of -1. This is always\n # less than the next doc id (which are strictly positive), so any\n # future occurrences are guaranteed to be counted.\n base_accumulator.per_doc_count_dict[token][\"count\"] += value[\n \"count\"]\n\n return base_accumulator\n\n def extract(self, accumulator):\n \"\"\"Convert an accumulator into a dict of output values.\n\n Args:\n accumulator: An accumulator aggregating over the full dataset.\n\n Returns:\n A dict of:\n \"vocab\": A list of the retained items in the vocabulary.\n \"\"\"\n vocab_counts = accumulator.count_dict\n\n # Drop special tokens from our vocab.\n if self._mask_value in vocab_counts:\n del vocab_counts[self._mask_value]\n if self._oov_value in vocab_counts:\n del vocab_counts[self._oov_value]\n # Data processed by the accumulator could be tensors, numpy arrays or lists.\n # For tensor string input, values will have been converted into bytes. We\n # need to check the bytes version of special tokens in this case.\n if isinstance(self._mask_value, str):\n mask_value_bytes = compat.as_bytes(self._mask_value)\n if mask_value_bytes in vocab_counts:\n del vocab_counts[mask_value_bytes]\n if isinstance(self._oov_value, str):\n oov_value_bytes = compat.as_bytes(self._oov_value)\n if oov_value_bytes in vocab_counts:\n del vocab_counts[oov_value_bytes]\n\n sorted_counts = sorted(\n vocab_counts.items(), key=operator.itemgetter(1, 0), reverse=True)\n vocab_data = (\n sorted_counts[:self._vocab_size] if self._vocab_size else sorted_counts)\n vocab = [data[0] for data in vocab_data]\n\n if self._compute_idf:\n num_documents = accumulator.data[\"next_doc_id\"]\n document_counts = accumulator.per_doc_count_dict\n doc_counts = [document_counts[token][\"count\"] for token in vocab]\n idf_weights = self._inverse_document_frequency(doc_counts, num_documents)\n else:\n idf_weights = None\n\n return {_VOCAB_NAME: vocab, _IDF_WEIGHTS_NAME: idf_weights}\n\n def restore(self, output):\n \"\"\"Create an accumulator based on 'output'.\"\"\"\n raise NotImplementedError(\n \"IndexLookup does not restore or support streaming updates.\")\n\n def serialize(self, accumulator):\n \"\"\"Serialize an accumulator for a remote call.\"\"\"\n output_dict = {}\n output_dict[\"vocab\"] = list(accumulator.count_dict.keys())\n output_dict[\"vocab_counts\"] = list(accumulator.count_dict.values())\n\n if self._compute_idf:\n output_dict[\"data\"] = accumulator.data\n output_dict[\"idf_vocab\"] = list(accumulator.per_doc_count_dict.keys())\n output_dict[\"idf_counts\"] = [\n counter[\"count\"]\n for counter in accumulator.per_doc_count_dict.values()\n ]\n return compat.as_bytes(json.dumps(output_dict))\n\n def deserialize(self, encoded_accumulator):\n \"\"\"Deserialize an accumulator received from 'serialize()'.\"\"\"\n accumulator_dict = json.loads(compat.as_text(encoded_accumulator))\n\n accumulator = self._create_accumulator()\n count_dict = dict(\n zip(accumulator_dict[\"vocab\"], accumulator_dict[\"vocab_counts\"]))\n accumulator.count_dict.update(count_dict)\n\n if self._compute_idf:\n accumulator.data = accumulator_dict[\"data\"]\n create_dict = lambda x: {\"count\": x, \"last_doc_id\": -1}\n idf_count_dicts = [\n create_dict(count) for count in accumulator_dict[\"idf_counts\"]\n ]\n idf_dict = dict(zip(accumulator_dict[\"idf_vocab\"], idf_count_dicts))\n accumulator.per_doc_count_dict.update(idf_dict)\n return accumulator\n\n def _create_accumulator(self):\n \"\"\"Accumulate a sorted array of vocab tokens and corresponding counts.\"\"\"\n\n if self._compute_idf:\n create_default_dict = lambda: {\"count\": 0, \"last_doc_id\": -1}\n per_doc_count_dict = collections.defaultdict(create_default_dict)\n data = {\"next_doc_id\": 0}\n else:\n per_doc_count_dict = None\n data = None\n\n count_dict = collections.defaultdict(int)\n return _IndexLookupAccumulator(data, count_dict, per_doc_count_dict)\n\n def _inverse_document_frequency(self, document_counts, num_documents):\n \"\"\"Computes the inverse-document-frequency (IDF) component of TF-IDF.\n\n Uses the default weighting scheme described in\n https://en.wikipedia.org/wiki/Tf%E2%80%93idf.\n\n Args:\n document_counts: An array of the # of documents each token appears in.\n num_documents: An int representing the total number of documents\n\n Returns:\n An array of \"inverse document frequency\" weights.\n \"\"\"\n return np.log(1 + num_documents / (1 + np.array(document_counts)))\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.data.Dataset.padded_batch()`.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl.testing import parameterized\nimport numpy as np\n\nfrom tensorflow.python.data.kernel_tests import checkpoint_test_base\nfrom tensorflow.python.data.kernel_tests import test_base\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.framework import combinations\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import sparse_tensor\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import string_ops\nfrom tensorflow.python.ops.ragged import ragged_tensor_value\nfrom tensorflow.python.platform import test\nfrom tensorflow.python.util import compat\n\n\nclass PaddedBatchTest(test_base.DatasetTestBase, parameterized.TestCase):\n\n @combinations.generate(\n combinations.times(\n test_base.default_test_combinations(),\n combinations.combine(\n count=[32, 34],\n padded_shapes=[[None], [25]],\n drop_remainder=[True, False])))\n def testPaddedBatchDataset(self, count, padded_shapes, drop_remainder):\n seq_lens = np.random.randint(20, size=(count,)).astype(np.int32)\n batch_size = 4\n dataset = dataset_ops.Dataset.from_tensor_slices(seq_lens).map(\n lambda x: array_ops.fill([x], x)).padded_batch(\n batch_size=batch_size,\n drop_remainder=drop_remainder,\n padded_shapes=padded_shapes)\n\n num_full_batches = len(seq_lens) // batch_size\n get_next = self.getNext(dataset)\n for i in range(num_full_batches):\n result = self.evaluate(get_next())\n padded_len = padded_shapes[0]\n if padded_len is None or padded_len == -1:\n padded_len = np.max(result) if result.size > 0 else 0\n self.assertEqual((batch_size, padded_len), result.shape)\n for j in range(batch_size):\n seq_len = seq_lens[(i * batch_size) + j]\n self.assertAllEqual(result[j, :seq_len], [seq_len] * seq_len)\n self.assertAllEqual(result[j, seq_len:], [0] * (padded_len - seq_len))\n\n if not drop_remainder and len(seq_lens) % batch_size > 0:\n result = self.evaluate(get_next())\n padded_len = padded_shapes[0]\n if padded_len is None or padded_len == -1:\n padded_len = np.max(result) if result.size > 0 else 0\n self.assertEqual((len(seq_lens) % batch_size, padded_len), result.shape)\n for j in range(len(seq_lens) % batch_size):\n seq_len = seq_lens[num_full_batches * batch_size + j]\n self.assertAllEqual(result[j, :seq_len], [seq_len] * seq_len)\n self.assertAllEqual(result[j, seq_len:], [0] * (padded_len - seq_len))\n\n with self.assertRaises(errors.OutOfRangeError):\n self.evaluate(get_next())\n with self.assertRaises(errors.OutOfRangeError):\n self.evaluate(get_next())\n\n @combinations.generate(test_base.default_test_combinations())\n def testPaddedBatchShortPadding(self):\n dataset = (\n dataset_ops.Dataset.from_tensor_slices(\n [6, 5, 5, 5, 5]).map(lambda x: array_ops.fill([x], x)).padded_batch(\n batch_size=4, padded_shapes=[5]))\n self.assertDatasetProduces(\n dataset, expected_error=(errors.DataLossError, ''))\n\n @combinations.generate(test_base.default_test_combinations())\n def testPaddedBatchEmptyTensors(self):\n dataset = (\n dataset_ops.Dataset.from_tensor_slices(\n [0, 0, 0, 0]).map(lambda x: array_ops.fill([x], x)).padded_batch(\n batch_size=4, padded_shapes=[-1]))\n self.assertDatasetProduces(dataset, expected_output=[[[], [], [], []]])\n\n @combinations.generate(test_base.default_test_combinations())\n def testDefaultPaddedShapes(self):\n\n def fill(x):\n return array_ops.fill([x], x)\n\n dataset = (\n dataset_ops.Dataset.from_tensor_slices(\n [1, 2, 3, 4]).map(fill).padded_batch(batch_size=2))\n self.assertDatasetProduces(\n dataset,\n expected_output=[[[1, 0], [2, 2]], [[3, 3, 3, 0], [4, 4, 4, 4]]])\n\n @combinations.generate(test_base.default_test_combinations())\n def testNestedDefaultPaddedShapes(self):\n\n def fill_tuple(x):\n return (x, array_ops.fill([x], x))\n\n dataset = (\n dataset_ops.Dataset.from_tensor_slices(\n [1, 2, 3, 4]).map(fill_tuple).padded_batch(batch_size=2))\n self.assertDatasetProduces(\n dataset,\n expected_output=[([1, 2], [[1, 0], [2, 2]]),\n ([3, 4], [[3, 3, 3, 0], [4, 4, 4, 4]])])\n\n @combinations.generate(\n combinations.times(\n test_base.default_test_combinations(),\n combinations.combine(\n padding_values=[(-1, '<end>', {'structure': ''}),\n (-1, '<end>', None)])))\n def testPaddedBatchDatasetNonDefaultPadding(self, padding_values):\n\n def fill_tuple(x):\n filled = array_ops.fill([x], x)\n return (filled, string_ops.as_string(filled), {\n 'structure': string_ops.as_string(filled)\n })\n\n random_seq_lens = np.random.randint(20, size=(32,)).astype(np.int32)\n dataset = (\n dataset_ops.Dataset.from_tensor_slices(random_seq_lens).map(fill_tuple)\n .padded_batch(\n 4, padded_shapes=([-1], [-1], {'structure': [-1]}),\n padding_values=padding_values))\n\n get_next = self.getNext(dataset)\n for i in range(8):\n result = self.evaluate(get_next())\n padded_len = np.max(result[0])\n self.assertEqual((4, padded_len), result[0].shape)\n self.assertEqual((4, padded_len), result[1].shape)\n self.assertEqual((4, padded_len), result[2]['structure'].shape)\n for j in range(4):\n seq_len = random_seq_lens[(i * 4) + j]\n self.assertAllEqual(result[0][j, :seq_len], [seq_len] * seq_len)\n self.assertAllEqual(result[0][j, seq_len:],\n [-1] * (padded_len - seq_len))\n self.assertAllEqual(result[1][j, :seq_len],\n [compat.as_bytes(str(seq_len))] * seq_len)\n self.assertAllEqual(result[1][j, seq_len:],\n [b'<end>'] * (padded_len - seq_len))\n self.assertAllEqual(result[2]['structure'][j, :seq_len],\n [compat.as_bytes(str(seq_len))] * seq_len)\n self.assertAllEqual(result[2]['structure'][j, seq_len:],\n [b''] * (padded_len - seq_len))\n with self.assertRaises(errors.OutOfRangeError):\n self.evaluate(get_next())\n\n @combinations.generate(test_base.default_test_combinations())\n def testPaddedBatchDatasetUnicode(self):\n # See GitHub issue 16149\n def generator():\n data = [[u'Простой', u'тест', u'юникода'],\n [u'никогда', u'не', u'бывает', u'простым']]\n\n for seq in data:\n yield seq, [0, 1, 2, 3]\n\n dataset = dataset_ops.Dataset.from_generator(\n generator, (dtypes.string, dtypes.int32),\n (tensor_shape.TensorShape([None]), tensor_shape.TensorShape([None])))\n padded_dataset = dataset.padded_batch(\n 2, padded_shapes=([None], [None]), padding_values=('', 0))\n next_element = self.getNext(padded_dataset)\n self.evaluate(next_element())\n\n @combinations.generate(test_base.graph_only_combinations())\n def testPaddedBatchDatasetShapeSpecifications(self):\n int_placeholder = array_ops.placeholder(dtypes.int32)\n float_placeholder = array_ops.placeholder(dtypes.float32)\n string_placeholder = array_ops.placeholder(dtypes.string)\n input_dataset = dataset_ops.Dataset.from_tensors(\n (int_placeholder, float_placeholder, string_placeholder))\n\n # Test different ways of specifying the `padded_shapes` argument.\n dynamic_padding_from_tensor_shapes = input_dataset.padded_batch(\n 32,\n padded_shapes=(tensor_shape.TensorShape([None]),\n tensor_shape.TensorShape([None, None]),\n tensor_shape.TensorShape([37])))\n dynamic_padding_from_lists = input_dataset.padded_batch(\n 32, padded_shapes=([None], [None, None], [37]))\n dynamic_padding_from_lists_with_minus_one = input_dataset.padded_batch(\n 32, padded_shapes=([-1], [-1, -1], [37]))\n dynamic_padding_from_tensors = input_dataset.padded_batch(\n 32,\n padded_shapes=(constant_op.constant([-1], dtype=dtypes.int64),\n constant_op.constant([-1, -1], dtype=dtypes.int64),\n constant_op.constant([37], dtype=dtypes.int64)))\n\n for dataset in [\n dynamic_padding_from_tensor_shapes, dynamic_padding_from_lists,\n dynamic_padding_from_lists_with_minus_one, dynamic_padding_from_tensors\n ]:\n dataset_output_shapes = dataset_ops.get_legacy_output_shapes(dataset)\n self.assertEqual([None, None], dataset_output_shapes[0].as_list())\n self.assertEqual([None, None, None], dataset_output_shapes[1].as_list())\n self.assertEqual([None, 37], dataset_output_shapes[2].as_list())\n\n @combinations.generate(test_base.default_test_combinations())\n def testPaddedBatchSparseError(self):\n\n st = sparse_tensor.SparseTensorValue(\n indices=[[0, 0]], values=([42]), dense_shape=[1, 1])\n\n with self.assertRaises(TypeError):\n _ = dataset_ops.Dataset.from_tensors(st).repeat(10).padded_batch(10)\n\n @combinations.generate(test_base.default_test_combinations())\n def testPaddedBatchRaggedError(self):\n\n rt = ragged_tensor_value.RaggedTensorValue(\n np.array([0, 42]), np.array([0, 2], dtype=np.int64))\n\n with self.assertRaises(TypeError):\n _ = dataset_ops.Dataset.from_tensors(rt).repeat(10).padded_batch(10)\n\n @combinations.generate(test_base.default_test_combinations())\n def testPaddedBatchShapeErrorWrongRank(self):\n with self.assertRaisesRegex(\n ValueError, r'The padded shape \\(1,\\) is not compatible with the '\n r'corresponding input component shape \\(\\).'):\n _ = dataset_ops.Dataset.range(10).padded_batch(5, padded_shapes=[1])\n\n @combinations.generate(test_base.default_test_combinations())\n def testPaddedBatchShapeErrorTooSmall(self):\n with self.assertRaisesRegex(\n ValueError, r'The padded shape \\(1,\\) is not compatible with the '\n r'corresponding input component shape \\(3,\\).'):\n _ = dataset_ops.Dataset.from_tensors([1, 2, 3]).padded_batch(\n 5, padded_shapes=[1])\n\n @combinations.generate(test_base.default_test_combinations())\n def testPaddedBatchShapeErrorShapeNotRank1(self):\n with self.assertRaisesRegex(\n ValueError, r'Padded shape .* must be a 1-D tensor '\n r'of tf.int64 values, but its shape was \\(2, 2\\).'):\n _ = dataset_ops.Dataset.from_tensors([1, 2, 3]).padded_batch(\n 5, padded_shapes=[[1, 1], [1, 1]])\n\n @combinations.generate(test_base.default_test_combinations())\n def testPaddedBatchShapeErrorShapeNotInt(self):\n with self.assertRaisesRegex(\n TypeError, r'Padded shape .* must be a 1-D tensor '\n r'of tf.int64 values, but its element type was float32.'):\n _ = dataset_ops.Dataset.from_tensors([1, 2, 3]).padded_batch(\n 5, padded_shapes=constant_op.constant([1.5, 2., 3.]))\n\n @combinations.generate(test_base.default_test_combinations())\n def testPaddedBatchShapeErrorWrongRankFromTensor(self):\n with self.assertRaisesRegex(\n ValueError, r'The padded shape \\(1,\\) is not compatible with the '\n r'corresponding input component shape \\(\\).'):\n shape_as_tensor = constant_op.constant([1], dtype=dtypes.int64)\n _ = dataset_ops.Dataset.range(10).padded_batch(\n 5, padded_shapes=shape_as_tensor)\n\n @combinations.generate(test_base.default_test_combinations())\n def testPaddedBatchShapeErrorDefaultShapeWithUnknownRank(self):\n with self.assertRaisesRegex(ValueError, r'`padded_shapes`.*unknown rank'):\n ds = dataset_ops.Dataset.from_generator(\n lambda: iter([1, 2, 3]), output_types=dtypes.int32)\n ds.padded_batch(2)\n\n @combinations.generate(test_base.graph_only_combinations())\n def testPaddedBatchShapeErrorPlaceholder(self):\n with self.assertRaisesRegex(\n ValueError,\n r'The padded shape \\((\\?|None), (\\?|None)\\) is not compatible with the '\n r'corresponding input component shape \\(\\).'):\n shape_as_tensor = array_ops.placeholder(dtypes.int64, shape=[2])\n _ = dataset_ops.Dataset.range(10).padded_batch(\n 5, padded_shapes=shape_as_tensor)\n\n @combinations.generate(test_base.default_test_combinations())\n def testPaddedBatchBfloat16(self):\n ds = dataset_ops.Dataset.range(5)\n ds = ds.map(lambda x: math_ops.cast(x, dtypes.bfloat16))\n ds = ds.padded_batch(10)\n self.assertDatasetProduces(\n ds, expected_output=[[0.0, 1.0, 2.0, 3.0, 4.0]])\n\n @combinations.generate(test_base.default_test_combinations())\n def testDefaultPaddedValueShapes(self):\n\n def fill(x):\n return array_ops.fill([x], x)\n\n dataset = dataset_ops.Dataset.zip(\n (dataset_ops.Dataset.from_tensor_slices([1, 2, 3, 4]).map(fill),\n dataset_ops.Dataset.from_tensor_slices([1, 2, 3, 4]).map(fill)))\n dataset = dataset.padded_batch(batch_size=2, padding_values=-1)\n self.assertDatasetProduces(\n dataset,\n expected_output=[([[1, -1], [2, 2]], [[1, -1], [2, 2]]),\n ([[3, 3, 3, -1], [4, 4, 4, 4]], [[3, 3, 3, -1],\n [4, 4, 4, 4]])])\n\n\nclass PaddedBatchCheckpointTest(checkpoint_test_base.CheckpointTestBase,\n parameterized.TestCase):\n\n @combinations.generate(\n combinations.times(test_base.default_test_combinations(),\n checkpoint_test_base.default_test_combinations()))\n def test(self, verify_fn):\n\n def build_dataset(seq_lens):\n return dataset_ops.Dataset.from_tensor_slices(seq_lens).map(\n lambda x: array_ops.fill([x], x)).padded_batch(\n batch_size=4, padded_shapes=[-1])\n\n seq_lens = np.random.randint(1, 20, size=(32,)).astype(np.int32)\n verify_fn(self, lambda: build_dataset(seq_lens), num_outputs=8)\n\n @combinations.generate(\n combinations.times(test_base.default_test_combinations(),\n checkpoint_test_base.default_test_combinations()))\n def testNonDefaultPadding(self, verify_fn):\n\n def build_dataset(seq_lens):\n\n def fill_tuple(x):\n filled = array_ops.fill([x], x)\n return (filled, string_ops.as_string(filled))\n\n padded_shape = [-1]\n return dataset_ops.Dataset.from_tensor_slices(seq_lens).map(\n fill_tuple).padded_batch(\n batch_size=4,\n padded_shapes=(padded_shape, padded_shape),\n padding_values=(-1, '<end>'))\n\n seq_lens = np.random.randint(1, 20, size=(32,)).astype(np.int32)\n verify_fn(self, lambda: build_dataset(seq_lens), num_outputs=8)\n\n\nif __name__ == '__main__':\n test.main()\n", "# Copyright 2018 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\"\"\"Experimental library that exposes XLA operations directly in TensorFlow.\n\nIt is sometimes useful to be able to build HLO programs directly from\nTensorFlow. This file provides Tensorflow operators that mirror the semantics of\nHLO operators as closely as possible.\n\nNote: Most of the operators defined in this module are used by the jax2tf\nconverter (see go/jax2tf for details) and are used in SavedModel produced\nby jax2tf. Hence, we need to maintain backwards compatibility for these\noperators. Please reach out to the JAX team if you want to make changes.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.compiler.tf2xla.ops import gen_xla_ops\nfrom tensorflow.core.framework import attr_value_pb2\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import bitwise_ops\nfrom tensorflow.python.ops import gen_math_ops\nfrom tensorflow.python.ops import gen_random_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import random_ops\nfrom tensorflow.python.ops import special_math_ops\nfrom tensorflow.python.ops.numpy_ops import np_utils\n\n# TODO(phawkins): provide wrappers for all XLA operators. Currently the missing\n# ops include:\n# infeed/outfeed (available via tf.contrib.tpu)\n# collectives, e.g., cross-replica-sum (available via tf.contrib.tpu)\n# conditional\n# gather/scatter\n# collapse\n\n# This file reuses builtin names (following XLA's names, so we can call things\n# like xla.max), so we capture the builtin versions here.\n# pylint: disable=redefined-builtin\n_max = max\n_min = min\n_slice = slice # pylint: disable=invalid-name\n\nconstant = constant_op.constant\n\n# Unary operators.\n\n# For most arithmetic operators there is a TensorFlow operator\n# that exactly corresponds to each XLA operator. Rather than defining\n# XLA-specific variants, we reuse the corresponding TensorFlow operator.\n# TODO(phawkins): It would be even better to have TensorFlow operators that 1:1\n# wrap every HLO operator, because that would allow us to be confident that the\n# semantics match.\n\n\ndef _unary_op(fn):\n \"\"\"Wrapper that restricts `fn` to have the correct signature.\"\"\"\n\n def unary_op_wrapper(x, name=None):\n return fn(x, name=name)\n\n return unary_op_wrapper\n\n\nabs = _unary_op(math_ops.abs)\n# TODO(phawkins): implement clz.\nconj = _unary_op(math_ops.conj)\ncos = _unary_op(math_ops.cos)\nceil = _unary_op(math_ops.ceil)\ndigamma = _unary_op(math_ops.digamma)\nerf = _unary_op(math_ops.erf)\nerfc = _unary_op(math_ops.erfc)\nerfinv = _unary_op(math_ops.erfinv)\nndtri = _unary_op(math_ops.ndtri)\nexp = _unary_op(math_ops.exp)\nexpm1 = _unary_op(math_ops.expm1)\nfloor = _unary_op(math_ops.floor)\nimag = _unary_op(math_ops.imag)\nis_finite = _unary_op(math_ops.is_finite)\nlgamma = _unary_op(math_ops.lgamma)\nlog = _unary_op(math_ops.log)\nlog1p = _unary_op(math_ops.log1p)\nlogical_not = _unary_op(math_ops.logical_not)\nneg = _unary_op(math_ops.neg)\nreal = _unary_op(math_ops.real)\n# TODO(phawkins): unlike xla::Round, this rounds to even instead of zero for\n# numbers halfway between two integers.\nround = _unary_op(math_ops.round)\nsin = _unary_op(math_ops.sin)\nsign = _unary_op(math_ops.sign)\ntanh = _unary_op(math_ops.tanh)\n\n# Bessel\nbessel_i0e = _unary_op(special_math_ops.bessel_i0e)\nbessel_i1e = _unary_op(special_math_ops.bessel_i1e)\n\n# Binary operators\n\n# The main difference between TensorFlow and XLA binary ops is the broadcasting\n# semantics. TensorFlow uses Numpy-style broadcasting semantics, whereas XLA\n# requires an explicit specification of which dimensions to broadcast if the\n# arguments have different ranks.\n\n\ndef _broadcasting_binary_op(fn):\n \"\"\"Wraps a binary Tensorflow operator and performs XLA-style broadcasting.\"\"\"\n\n def broadcasting_binary_op_wrapper(x, y, broadcast_dims=None, name=None):\n \"\"\"Inner wrapper function.\"\"\"\n broadcast_dims = broadcast_dims or []\n broadcast_dims = ops.convert_to_tensor(broadcast_dims, dtypes.int64)\n # Rather than relying on having static shape information in the TensorFlow\n # graph, we use an XlaBroadcastHelper op that can compute the correct shapes\n # at JIT compilation time.\n x, y = gen_xla_ops.xla_broadcast_helper(x, y, broadcast_dims)\n return fn(x, y, name=name)\n\n return broadcasting_binary_op_wrapper\n\n\n# Map from TF signed types to TF unsigned types.\n_SIGNED_TO_UNSIGNED_TABLE = {\n dtypes.int8: dtypes.uint8,\n dtypes.int16: dtypes.uint16,\n dtypes.int32: dtypes.uint32,\n dtypes.int64: dtypes.uint64,\n}\n\n# Map from TF unsigned types to TF signed types.\n_UNSIGNED_TO_SIGNED_TABLE = {\n dtypes.uint8: dtypes.int8,\n dtypes.uint16: dtypes.int16,\n dtypes.uint32: dtypes.int32,\n dtypes.uint64: dtypes.int64,\n}\n\n\ndef _shift_right_logical_helper(x, y, name=None):\n \"\"\"Performs an integer right logical shift irrespective of input type.\"\"\"\n assert y.dtype == x.dtype\n dtype = x.dtype\n signed = dtype in _SIGNED_TO_UNSIGNED_TABLE\n if signed:\n unsigned_dtype = _SIGNED_TO_UNSIGNED_TABLE[dtype]\n x = math_ops.cast(x, unsigned_dtype)\n y = math_ops.cast(y, unsigned_dtype)\n output = bitwise_ops.right_shift(x, y, name=name)\n if signed:\n output = math_ops.cast(output, dtype)\n return output\n\n\ndef _shift_right_arithmetic_helper(x, y, name=None):\n \"\"\"Performs an integer right arithmetic shift irrespective of input type.\"\"\"\n assert y.dtype == x.dtype\n dtype = x.dtype\n unsigned = dtype in _UNSIGNED_TO_SIGNED_TABLE\n if unsigned:\n signed_dtype = _UNSIGNED_TO_SIGNED_TABLE[dtype]\n x = math_ops.cast(x, signed_dtype)\n y = math_ops.cast(y, signed_dtype)\n output = bitwise_ops.right_shift(x, y, name=name)\n if unsigned:\n output = math_ops.cast(output, dtype)\n return output\n\n\nadd = _broadcasting_binary_op(math_ops.add)\nsub = _broadcasting_binary_op(math_ops.sub)\nmul = _broadcasting_binary_op(math_ops.mul)\ndiv = _broadcasting_binary_op(math_ops.div)\nrem = _broadcasting_binary_op(gen_math_ops.mod)\nmax = _broadcasting_binary_op(math_ops.maximum)\nmin = _broadcasting_binary_op(math_ops.minimum)\natan2 = _broadcasting_binary_op(math_ops.atan2)\ncomplex = _broadcasting_binary_op(math_ops.complex)\nlogical_and = _broadcasting_binary_op(math_ops.logical_and)\nlogical_or = _broadcasting_binary_op(math_ops.logical_or)\nlogical_xor = _broadcasting_binary_op(math_ops.logical_xor)\neq = _broadcasting_binary_op(math_ops.equal)\nne = _broadcasting_binary_op(math_ops.not_equal)\nge = _broadcasting_binary_op(math_ops.greater_equal)\ngt = _broadcasting_binary_op(math_ops.greater)\nle = _broadcasting_binary_op(math_ops.less_equal)\nlt = _broadcasting_binary_op(math_ops.less)\npow = _broadcasting_binary_op(math_ops.pow)\nshift_left = _broadcasting_binary_op(bitwise_ops.left_shift)\nshift_right_logical = _broadcasting_binary_op(_shift_right_logical_helper)\nshift_right_arithmetic = _broadcasting_binary_op(_shift_right_arithmetic_helper)\n\nigamma = _broadcasting_binary_op(math_ops.igamma)\nigamma_grad_a = _broadcasting_binary_op(gen_math_ops.igamma_grad_a)\nrandom_gamma_grad = _broadcasting_binary_op(gen_random_ops.random_gamma_grad)\nigammac = _broadcasting_binary_op(math_ops.igammac)\npolygamma = _broadcasting_binary_op(math_ops.polygamma)\nzeta = _broadcasting_binary_op(math_ops.zeta)\n\n\ndef _binary_op(fn):\n \"\"\"Wrapper that restricts `fn` to have the correct signature.\"\"\"\n\n def binary_op_wrapper(x, y, name=None):\n return fn(x, y, name=name)\n\n return binary_op_wrapper\n\n\ntranspose = _binary_op(array_ops.transpose)\nrev = _binary_op(array_ops.reverse)\n\nbitcast_convert_type = array_ops.bitcast\n\n\ndef broadcast(x, dims, name=None):\n x = ops.convert_to_tensor(x)\n shape = array_ops.concat([constant_op.constant(dims),\n array_ops.shape(x)],\n axis=0)\n return array_ops.broadcast_to(x, shape, name=name)\n\n\ndef clamp(a, x, b, name=None):\n return min(max(a, x, name=name), b, name=name)\n\n\nconcatenate = array_ops.concat\n\n\ndef conv(lhs,\n rhs,\n window_strides,\n padding,\n lhs_dilation,\n rhs_dilation,\n dimension_numbers,\n feature_group_count=1,\n precision_config=None,\n preferred_element_type=None,\n name=None,\n use_v2=False):\n \"\"\"Wraps the XLA ConvGeneralDilated operator.\n\n ConvGeneralDilated is the most general form of XLA convolution and is\n documented at\n https://www.tensorflow.org/performance/xla/operation_semantics#conv_convolution\n\n Args:\n lhs: the input tensor\n rhs: the kernel tensor\n window_strides: the inter-window strides\n padding: the padding to apply at the start and end of each input dimensions\n lhs_dilation: dilation to apply between input elements\n rhs_dilation: dilation to apply between kernel elements\n dimension_numbers: a `ConvolutionDimensionNumbers` proto.\n feature_group_count: number of feature groups for grouped convolution.\n precision_config: a `xla.PrecisionConfig` proto.\n preferred_element_type: the result `dtype`.\n name: an optional name for the operator.\n use_v2: an optional request to use the XlaConvV2 op even if not necessary.\n\n Returns:\n A tensor representing the output of the convolution.\n \"\"\"\n precision_config_proto = \"\"\n if precision_config:\n precision_config_proto = precision_config.SerializeToString()\n needs_v2 = preferred_element_type or (lhs.dtype != rhs.dtype)\n if preferred_element_type is None:\n preferred_element_type = np_utils.result_type(lhs.dtype, rhs.dtype)\n if needs_v2 or use_v2:\n return gen_xla_ops.xla_conv_v2(\n lhs,\n rhs,\n window_strides=window_strides,\n padding=padding,\n lhs_dilation=lhs_dilation,\n rhs_dilation=rhs_dilation,\n feature_group_count=feature_group_count,\n dimension_numbers=dimension_numbers.SerializeToString(),\n precision_config=precision_config_proto,\n preferred_element_type=preferred_element_type,\n name=name)\n return gen_xla_ops.xla_conv(\n lhs,\n rhs,\n window_strides=window_strides,\n padding=padding,\n lhs_dilation=lhs_dilation,\n rhs_dilation=rhs_dilation,\n feature_group_count=feature_group_count,\n dimension_numbers=dimension_numbers.SerializeToString(),\n precision_config=precision_config_proto,\n name=name)\n\n\nconvert_element_type = math_ops.cast\n\n\ndef dot(lhs, rhs, name=None):\n return math_ops.tensordot(lhs, rhs, axes=1, name=name)\n\n\ndef dot_general(lhs,\n rhs,\n dimension_numbers,\n precision_config=None,\n preferred_element_type=None,\n name=None,\n use_v2=False):\n precision_config_proto = \"\"\n if precision_config:\n precision_config_proto = precision_config.SerializeToString()\n needs_v2 = preferred_element_type or (lhs.dtype != rhs.dtype)\n if preferred_element_type is None:\n preferred_element_type = np_utils.result_type(lhs.dtype, rhs.dtype)\n if needs_v2 or use_v2:\n return gen_xla_ops.xla_dot_v2(\n lhs,\n rhs,\n dimension_numbers=dimension_numbers.SerializeToString(),\n precision_config=precision_config_proto,\n preferred_element_type=preferred_element_type,\n name=name)\n return gen_xla_ops.xla_dot(\n lhs,\n rhs,\n dimension_numbers=dimension_numbers.SerializeToString(),\n precision_config=precision_config_proto,\n name=name)\n\n\ndef self_adjoint_eig(a, lower, max_iter, epsilon):\n return gen_xla_ops.xla_self_adjoint_eig(a, lower, max_iter, epsilon)\n\n\ndef svd(a, max_iter, epsilon, precision_config=None):\n precision_config_proto = \"\"\n if precision_config:\n precision_config_proto = precision_config.SerializeToString()\n return gen_xla_ops.xla_svd(a, max_iter, epsilon, precision_config_proto)\n\n\ndynamic_slice = gen_xla_ops.xla_dynamic_slice\ndynamic_update_slice = gen_xla_ops.xla_dynamic_update_slice\neinsum = gen_xla_ops.xla_einsum\n\n# TODO(phawkins): generalize tf.pad to support interior padding, and then remove\n# the XLA-specific pad operator.\npad = gen_xla_ops.xla_pad\n\n\ndef random_normal(mu, sigma, dims, name=None):\n mu = ops.convert_to_tensor(mu)\n return random_ops.random_normal(\n dims, mean=mu, stddev=sigma, dtype=mu.dtype, name=name)\n\n\ndef random_uniform(minval, maxval, dims, name=None):\n minval = ops.convert_to_tensor(minval)\n return random_ops.random_uniform(\n dims, minval, maxval, dtype=minval.dtype, name=name)\n\n\nrecv = gen_xla_ops.xla_recv\nreduce = gen_xla_ops.xla_reduce\nvariadic_reduce = gen_xla_ops.xla_variadic_reduce_v2\n\nops.no_gradient(\"XlaVariadicReduce\")\n\n\ndef reduce_window(operand,\n init,\n reducer,\n window_dimensions,\n window_strides=None,\n base_dilations=None,\n window_dilations=None,\n padding=None,\n name=None):\n \"\"\"Wraps the XLA ReduceWindow operator.\n\n ReduceWindow is documented at\n https://www.tensorflow.org/performance/xla/operation_semantics#reducewindow .\n\n Args:\n operand: the input tensor\n init: a scalar tensor representing the initial value for the reduction\n reducer: a reduction function that combines a pair of scalars.\n window_dimensions: shape of the window, as a list of integers\n window_strides: inter-window strides, as a list of integers. Optional; if\n omitted, defaults to strides of 1.\n padding: padding to apply to 'operand'. List of (low, high) pairs of\n integers that specify the padding to apply before and after each\n dimension. Optional; if omitted, defaults to no padding.\n name: the operator name, or None.\n\n Returns:\n A tensor that represents the output of the reduce_window operator.\n \"\"\"\n window_strides = window_strides or [1] * len(window_dimensions)\n base_dilations = base_dilations or [1] * len(window_dimensions)\n window_dilations = window_dilations or [1] * len(window_dimensions)\n padding = padding or [(0, 0)] * len(window_dimensions)\n return gen_xla_ops.xla_reduce_window(\n input=operand,\n init_value=init,\n window_dimensions=window_dimensions,\n window_strides=window_strides,\n base_dilations=base_dilations,\n window_dilations=window_dilations,\n padding=padding,\n computation=reducer,\n name=name)\n\n\nreplica_id = gen_xla_ops.xla_replica_id\n\n# Set a static bound for the given input value as a hint to Xla compiler,\n# returns the same value.\n# Usage:\n# def f(t, p):\n# p = xla.set_bound(p, 3) # Tells xla the constraint that p <= 3.\n# return t[:p] # xla knows the bound of the slice is 3.\nset_bound = gen_xla_ops.xla_set_bound\n\n\n# Make a static dimension into a xla bounded dynamic dimension. The current\n# static dimension size will become the bound and the second operand becomes the\n# dynamic size of the dimension.\n#\n# This should mostly be used for testing.\n#\n# def f():\n# array = tf.convert_to_tensor([[1, 2, 3, 4, 5]])\n# # Tells xla the valid size of the array is 3.\n# dim = 0\n# p = xla_set_dynamic_dimension_size(array, dim, 3)\n# assert(reduce_sum(p) == 6) # xla knows only the first 3 elements are valid.\nset_dynamic_dimension_size = gen_xla_ops.xla_set_dynamic_dimension_size\n\n\n# Inverse of xla_set_dynamic_dimension_size. Make an xla bounded dynamic\n# dimension into a static dimension. The bound of the size of dimension\n# `dim_index` becomes the static dimension size.\nremove_dynamic_dimension_size = gen_xla_ops.xla_remove_dynamic_dimension_size\n\n\ndef reshape(x, new_sizes, dimensions=None, name=None):\n if dimensions is not None:\n x = array_ops.transpose(x, dimensions)\n x = array_ops.reshape(x, new_sizes, name=name)\n return x\n\n\ndef select(condition, x, y, name=None):\n return array_ops.where(condition, x, y, name)\n\n\nselect_and_scatter = gen_xla_ops.xla_select_and_scatter\nsend = gen_xla_ops.xla_send\n\n\ndef slice(x, start_dims, limit_dims, strides):\n spec = [\n _slice(start, limit, stride)\n for (start, limit, stride) in zip(start_dims, limit_dims, strides)\n ]\n return x[tuple(spec)]\n\n\nsharding = gen_xla_ops.xla_sharding\n\n\[email protected](\"XlaSharding\")\ndef _sharding_grad(op, grad):\n sharding_attr = op.get_attr(\"sharding\")\n grad_sharding = gen_xla_ops.xla_sharding(grad, sharding=sharding_attr)\n # pylint: disable=protected-access\n grad_sharding.op._set_attr(\"_XlaSharding\",\n attr_value_pb2.AttrValue(s=sharding_attr))\n return [grad_sharding]\n\n\nspmd_full_to_shard_shape = gen_xla_ops.xla_spmd_full_to_shard_shape\nspmd_shard_to_full_shape = gen_xla_ops.xla_spmd_shard_to_full_shape\n\n\[email protected](\"XlaSpmdFullToShardShape\")\ndef _spmd_full_to_shard_shape_grad(op, grad):\n s2f = gen_xla_ops.xla_spmd_shard_to_full_shape(\n grad,\n manual_sharding=op.get_attr(\"manual_sharding\"),\n full_shape=op.inputs[0].shape.as_list())\n return [s2f]\n\n\[email protected](\"XlaSpmdShardToFullShape\")\ndef _spmd_shard_to_full_shape_grad(op, grad):\n f2s = gen_xla_ops.xla_spmd_full_to_shard_shape(\n grad, manual_sharding=op.get_attr(\"manual_sharding\"))\n return [f2s]\n\n\nsort = gen_xla_ops.xla_sort\nkey_value_sort = gen_xla_ops.xla_key_value_sort\nvariadic_sort = gen_xla_ops.xla_variadic_sort\nwhile_loop = gen_xla_ops.xla_while\ndequantize = gen_xla_ops.xla_dequantize\n\n\ndef gather(operand, start_indices, dimension_numbers, slice_sizes,\n indices_are_sorted=False, name=None):\n return gen_xla_ops.xla_gather(\n operand,\n start_indices,\n slice_sizes=slice_sizes,\n dimension_numbers=dimension_numbers.SerializeToString(),\n indices_are_sorted=indices_are_sorted,\n name=name)\n\n\ndef scatter(operand, scatter_indices, updates, update_computation,\n dimension_numbers, indices_are_sorted=False, name=None):\n return gen_xla_ops.xla_scatter(\n operand,\n scatter_indices,\n updates,\n update_computation=update_computation,\n dimension_numbers=dimension_numbers.SerializeToString(),\n indices_are_sorted=indices_are_sorted,\n name=name)\n", "# Copyright 2020 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\"\"\"Benchmarks on Keras layers.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport functools\nimport numpy as np\n\nimport tensorflow as tf\nfrom tensorflow.python.keras.benchmarks import benchmark_util\nfrom tensorflow.python.keras.benchmarks.layer_benchmarks import layer_benchmarks_test_base\nfrom tensorflow.python.platform import benchmark # pylint: disable=unused-import\n\n\ndef _get_metadata(name):\n return {\n \"model_name\": \"ideal_layers\",\n \"parameters\": name[1] + \"_shape\",\n }\n\n\ndef _get_layer_args(layer_cls, layer_args):\n # To make benchmark parameters compatible with GPU platform.\n if layer_cls is tf.keras.layers.Bidirectional:\n return {\"layer\": tf.keras.layers.LSTM(1)}\n return layer_args\n\n\ndef _get_input_data(inputs):\n if \"input_shape\" in inputs:\n return tf.ones(inputs[\"input_shape\"])\n elif \"input\" in inputs:\n return inputs[\"input\"]\n else:\n raise ValueError(\"Please specificy either `input_shape` or `input`\"\n \"for the benchmark test\")\n\n\ndef _layer_call_backward(layer, x):\n with tf.GradientTape() as tape:\n y = layer(x)\n loss = tf.reduce_mean(y**2)\n\n _ = tape.gradient(loss, layer.trainable_variables)\n\nCORE_LAYERS = [\n (\"Dense_small_shape\", tf.keras.layers.Dense,\n {\"units\": 32, \"activation\": \"relu\"},\n {\"input_shape\": (1, 16)}, 100),\n (\"Activation_small_shape\", tf.keras.layers.Activation,\n {\"activation\": \"relu\"},\n {\"input_shape\": (1, 4)}, 100),\n (\"Embedding_small_shape\", tf.keras.layers.Embedding,\n {\"input_dim\": 1, \"output_dim\": 1, \"input_length\": 1},\n {\"input\": np.random.randint(1, size=(1, 1))}, 100),\n (\"Embedding_normal_shape\", tf.keras.layers.Embedding,\n {\"input_dim\": 1000, \"output_dim\": 64, \"input_length\": 10},\n {\"input\": np.random.randint(1000, size=(32, 10))}, 100),\n (\"Masking_small_shape\", tf.keras.layers.Masking,\n {\"mask_value\": 1}, {\"input_shape\": (1, 1)}, 100),\n (\"Lambda_small_shape\", tf.keras.layers.Lambda,\n {\"function\": lambda x: x ** 2}, {\"input_shape\": (1, 1)}, 100),\n (\"Flatten_small_shape\", tf.keras.layers.Flatten,\n {}, {\"input_shape\": (1, 1)}, 100),\n]\n\nCONV_LAYERS = [\n (\"Conv1D_small_shape\", tf.keras.layers.Conv1D,\n {\"filters\": 1, \"kernel_size\": 1, \"activation\": \"relu\"},\n {\"input_shape\": (1, 1, 1)}, 100),\n (\"Conv2D_small_shape\", tf.keras.layers.Conv2D,\n {\"filters\": 1, \"kernel_size\": 1, \"activation\": \"relu\"},\n {\"input_shape\": (1, 1, 1, 1)}, 100),\n (\"Conv2D_normal_shape\", tf.keras.layers.Conv2D,\n {\"filters\": 1, \"kernel_size\": 1, \"activation\": \"relu\"},\n {\"input_shape\": (64, 28, 28, 3)}, 100),\n (\"Conv3D_small_shape\", tf.keras.layers.Conv3D,\n {\"filters\": 1, \"kernel_size\": 1, \"activation\": \"relu\"},\n {\"input_shape\": (1, 1, 1, 1, 1)}, 100),\n (\"Conv1DTranspose_small_shape\", tf.keras.layers.Conv1DTranspose,\n {\"filters\": 1, \"kernel_size\": 1, \"activation\": \"relu\"},\n {\"input_shape\": (1, 1, 1)}, 100),\n (\"Conv2DTranspose_small_shape\", tf.keras.layers.Conv2DTranspose,\n {\"filters\": 1, \"kernel_size\": 1, \"activation\": \"relu\"},\n {\"input_shape\": (1, 1, 1, 1)}, 100),\n (\"Conv3DTranspose_small_shape\", tf.keras.layers.Conv3DTranspose,\n {\"filters\": 1, \"kernel_size\": 1, \"activation\": \"relu\"},\n {\"input_shape\": (1, 1, 1, 1, 1)}, 100),\n (\"SeparableConv1D_small_shape\", tf.keras.layers.SeparableConv1D,\n {\"filters\": 1, \"kernel_size\": 1, \"activation\": \"relu\"},\n {\"input_shape\": (1, 1, 1)}, 100),\n (\"SeparableConv2D_small_shape\", tf.keras.layers.SeparableConv2D,\n {\"filters\": 1, \"kernel_size\": 1, \"activation\": \"relu\"},\n {\"input_shape\": (1, 1, 1, 1)}, 100),\n (\"DepthwiseConv2D_small_shape\", tf.keras.layers.DepthwiseConv2D,\n {\"kernel_size\": 1, \"activation\": \"relu\"},\n {\"input_shape\": (1, 1, 1, 1)}, 100),\n]\n\nRECURRENT_LAYERS = [\n (\"LSTM_small_shape\", tf.keras.layers.LSTM,\n {\"units\": 1}, {\"input_shape\": (1, 1, 1)}, 100),\n (\"LSTM_normal_shape\", tf.keras.layers.LSTM,\n {\"units\": 4}, {\"input_shape\": (32, 10, 8)}, 100),\n (\"GRU_small_shape\", tf.keras.layers.GRU,\n {\"units\": 1}, {\"input_shape\": (1, 1, 1)}, 100),\n (\"SimpleRNN_small_shape\", tf.keras.layers.SimpleRNN,\n {\"units\": 1}, {\"input_shape\": (1, 1, 1)}, 100),\n (\"TimeDistributed_small_shape\", tf.keras.layers.TimeDistributed,\n {\"layer\": tf.keras.layers.Conv2D(1, 1)},\n {\"input_shape\": (1, 1, 1, 1, 1)}, 100),\n (\"Bidirectional_small_shape\", tf.keras.layers.Bidirectional,\n {}, {\"input_shape\": (1, 1, 1)}, 100),\n (\"ConvLSTM2D_small_shape\", tf.keras.layers.ConvLSTM2D,\n {\"filters\": 1, \"kernel_size\": 1, \"activation\": \"relu\"},\n {\"input_shape\": (1, 1, 1, 1, 1)}, 100),\n (\"RNN_small_shape\", tf.keras.layers.RNN,\n {\"cell\": tf.keras.layers.LSTMCell(1)}, {\"input_shape\": (1, 1, 1)}, 100),\n]\n\nNORMALIZATION_LAYERS = [\n (\"BatchNormalization_small_shape\", tf.keras.layers.BatchNormalization,\n {\"axis\": -1}, {\"input_shape\": (1, 1, 1)}, 100),\n (\"LayerNormalization_small_shape\", tf.keras.layers.LayerNormalization,\n {\"axis\": -1}, {\"input_shape\": (1, 1, 1)}, 100),\n]\n\nREGULARIZATION_LAYERS = [\n (\"Dropout_small_shape\", tf.keras.layers.Dropout,\n {\"rate\": 0.2}, {\"input_shape\": (1, 1, 1)}, 100),\n (\"SpatialDropout1D_small_shape\", tf.keras.layers.SpatialDropout1D,\n {\"rate\": 0.2}, {\"input_shape\": (1, 1, 1)}, 100),\n (\"SpatialDropout2D_small_shape\", tf.keras.layers.SpatialDropout2D,\n {\"rate\": 0.2}, {\"input_shape\": (1, 1, 1, 1)}, 100),\n (\"SpatialDropout3D_small_shape\", tf.keras.layers.SpatialDropout3D,\n {\"rate\": 0.2}, {\"input_shape\": (1, 1, 1, 1, 1)}, 100),\n (\"GaussianDropout_small_shape\", tf.keras.layers.GaussianDropout,\n {\"rate\": 0.2}, {\"input_shape\": (1, 1, 1)}, 100),\n (\"GaussianNoise_small_shape\", tf.keras.layers.GaussianNoise,\n {\"stddev\": 0.1}, {\"input_shape\": (1, 1, 1)}, 100),\n (\"ActivityRegularization_small_shape\",\n tf.keras.layers.ActivityRegularization,\n {\"l1\": 0.3}, {\"input_shape\": (1, 1, 1)}, 100),\n (\"AlphaDropout_small_shape\", tf.keras.layers.AlphaDropout,\n {\"rate\": 0.2}, {\"input_shape\": (1, 1, 1)}, 100),\n]\n\n\nATTENSION_LAYERS = [\n (\"Attention_small_shape\", tf.keras.layers.Attention,\n {\"use_scale\": False}, {\"input\": [np.ones((1, 1, 1)), np.ones((1, 1, 1))]},\n 100),\n (\"AdditiveAttention_small_shape\", tf.keras.layers.AdditiveAttention,\n {\"use_scale\": True}, {\"input\": [np.ones((1, 1, 1)), np.ones((1, 1, 1))]},\n 100),\n]\n\nPOOLING_LAYERS = [\n (\"MaxPooling1D_small_shape\", tf.keras.layers.MaxPooling1D,\n {\"pool_size\": 1, \"strides\": 1}, {\"input_shape\": (1, 1, 1)}, 100),\n (\"MaxPooling2D_small_shape\", tf.keras.layers.MaxPooling2D,\n {\"pool_size\": 1, \"strides\": 1}, {\"input_shape\": (1, 1, 1, 1)}, 100),\n (\"MaxPooling3D_small_shape\", tf.keras.layers.MaxPooling3D,\n {\"pool_size\": 1, \"strides\": 1}, {\"input_shape\": (1, 1, 1, 1, 1)}, 100),\n (\"AveragePooling1D_small_shape\", tf.keras.layers.AveragePooling1D,\n {\"pool_size\": 1, \"strides\": 1}, {\"input_shape\": (1, 1, 1)}, 100),\n (\"AveragePooling2D_small_shape\", tf.keras.layers.AveragePooling2D,\n {\"pool_size\": 1, \"strides\": 1}, {\"input_shape\": (1, 1, 1, 1)}, 100),\n (\"AveragePooling3D_small_shape\", tf.keras.layers.AveragePooling3D,\n {\"pool_size\": 1, \"strides\": 1}, {\"input_shape\": (1, 1, 1, 1, 1)}, 100),\n (\"GlobalMaxPooling1D_small_shape\", tf.keras.layers.GlobalMaxPooling1D,\n {}, {\"input_shape\": (1, 1, 1)}, 100),\n (\"GlobalMaxPooling2D_small_shape\", tf.keras.layers.GlobalMaxPooling2D,\n {}, {\"input_shape\": (1, 1, 1, 1)}, 100),\n (\"GlobalMaxPooling3D_small_shape\", tf.keras.layers.GlobalMaxPooling3D,\n {}, {\"input_shape\": (1, 1, 1, 1, 1)}, 100),\n (\"GlobalAveragePooling1D_small_shape\",\n tf.keras.layers.GlobalAveragePooling1D,\n {}, {\"input_shape\": (1, 1, 1)}, 100),\n (\"GlobalAveragePooling2D_small_shape\",\n tf.keras.layers.GlobalAveragePooling2D,\n {}, {\"input_shape\": (1, 1, 1, 1)}, 100),\n (\"GlobalAveragePooling3D_small_shape\",\n tf.keras.layers.GlobalAveragePooling3D,\n {}, {\"input_shape\": (1, 1, 1, 1, 1)}, 100),\n]\n\n\nclass KerasLayerBenchmarks( # pylint: disable=undefined-variable\n layer_benchmarks_test_base.LayerBenchmarksBase,\n metaclass=benchmark.ParameterizedBenchmark):\n\n # The parameter of each layer benchmark is a tuple, and the first one is\n # the benchmark name. It must follow the convention of\n # \"{layer_name}_{small|normal|large}_shape\" to make it compatible with\n # `self.report_benchmark()` method.\n _benchmark_parameters = benchmark_util.generate_benchmark_params_cpu_gpu(\n CORE_LAYERS + CONV_LAYERS + RECURRENT_LAYERS + NORMALIZATION_LAYERS +\n REGULARIZATION_LAYERS + ATTENSION_LAYERS + POOLING_LAYERS)\n\n def benchmark_layer_call(self, layer_cls, layer_args, inputs, num_iters):\n layer = layer_cls(**_get_layer_args(layer_cls, layer_args))\n x = _get_input_data(inputs)\n\n fn = functools.partial(layer, x)\n name = benchmark_util.get_benchmark_name(self._get_name())\n metadata = {\"implementation\": name[0] + \".layer.call\"}\n metadata.update(_get_metadata(name))\n self.run_report(fn, num_iters, metadata)\n\n def benchmark_layer_call_with_function(\n self, layer_cls, layer_args, inputs, num_iters):\n layer = layer_cls(**_get_layer_args(layer_cls, layer_args))\n x = _get_input_data(inputs)\n layer.call = tf.function(layer.call)\n\n fn = functools.partial(layer, x)\n name = benchmark_util.get_benchmark_name(self._get_name())\n metadata = {\"implementation\": name[0] + \".layer.call.function\"}\n metadata.update(_get_metadata(name))\n self.run_report(fn, num_iters, metadata)\n\n def benchmark_layer_call_with_xla(\n self, layer_cls, layer_args, inputs, num_iters):\n name = benchmark_util.get_benchmark_name(self._get_name())\n # TODO(b/173461426)\n if layer_cls is tf.keras.layers.Embedding and name[-1] == \"GPU\":\n return\n layer = layer_cls(**_get_layer_args(layer_cls, layer_args))\n x = _get_input_data(inputs)\n layer.call = tf.function(\n layer.call, jit_compile=True)\n\n fn = functools.partial(layer, x)\n metadata = {\"implementation\": name[0] + \".layer.call.xla\"}\n metadata.update(_get_metadata(name))\n self.run_report(fn, num_iters, metadata)\n\n def benchmark_layer_call_backward(\n self, layer_cls, layer_args, inputs, num_iters):\n layer = layer_cls(**_get_layer_args(layer_cls, layer_args))\n x = _get_input_data(inputs)\n\n fn = functools.partial(_layer_call_backward, layer, x)\n name = benchmark_util.get_benchmark_name(self._get_name())\n metadata = {\"implementation\": name[0] + \".layer.call.backward\"}\n metadata.update(_get_metadata(name))\n self.run_report(fn, num_iters, metadata)\n\n def benchmark_layer_call_backward_with_function(\n self, layer_cls, layer_args, inputs, num_iters):\n layer = layer_cls(**_get_layer_args(layer_cls, layer_args))\n x = _get_input_data(inputs)\n layer.call = tf.function(layer.call)\n\n fn = functools.partial(_layer_call_backward, layer, x)\n name = benchmark_util.get_benchmark_name(self._get_name())\n metadata = {\"implementation\": name[0] + \".layer.call.backward.function\"}\n metadata.update(_get_metadata(name))\n self.run_report(fn, num_iters, metadata)\n\n def benchmark_layer_call_backward_with_xla(\n self, layer_cls, layer_args, inputs, num_iters):\n name = benchmark_util.get_benchmark_name(self._get_name())\n # TODO(b/153480400)\n if layer_cls in [\n tf.keras.layers.LSTM, tf.keras.layers.Bidirectional,\n tf.keras.layers.ConvLSTM2D, tf.keras.layers.GRU, tf.keras.layers.RNN,\n tf.keras.layers.SimpleRNN\n ]:\n return\n # TODO(b/173461426)\n if layer_cls is tf.keras.layers.Embedding and name[-1] == \"GPU\":\n return\n layer = layer_cls(**_get_layer_args(layer_cls, layer_args))\n x = _get_input_data(inputs)\n layer.call = tf.function(\n layer.call, jit_compile=True)\n\n fn = functools.partial(_layer_call_backward, layer, x)\n metadata = {\"implementation\": name[0] + \".layer.call.backward.xla\"}\n metadata.update(_get_metadata(name))\n self.run_report(fn, num_iters, metadata)\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n", "# Copyright 2018 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\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import variables as variables_module\nfrom tensorflow.python.ops.linalg import linalg as linalg_lib\nfrom tensorflow.python.ops.linalg import linear_operator_block_diag as block_diag\nfrom tensorflow.python.ops.linalg import linear_operator_lower_triangular as lower_triangular\nfrom tensorflow.python.ops.linalg import linear_operator_test_util\nfrom tensorflow.python.ops.linalg import linear_operator_util\nfrom tensorflow.python.platform import test\n\nlinalg = linalg_lib\nrng = np.random.RandomState(0)\n\n\ndef _block_diag_dense(expected_shape, blocks):\n \"\"\"Convert a list of blocks, into a dense block diagonal matrix.\"\"\"\n rows = []\n num_cols = 0\n for block in blocks:\n # Get the batch shape for the block.\n batch_row_shape = array_ops.shape(block)[:-1]\n\n zeros_to_pad_before_shape = array_ops.concat(\n [batch_row_shape, [num_cols]], axis=-1)\n zeros_to_pad_before = array_ops.zeros(\n shape=zeros_to_pad_before_shape, dtype=block.dtype)\n num_cols += array_ops.shape(block)[-1]\n zeros_to_pad_after_shape = array_ops.concat(\n [batch_row_shape, [expected_shape[-1] - num_cols]], axis=-1)\n zeros_to_pad_after = array_ops.zeros(\n zeros_to_pad_after_shape, dtype=block.dtype)\n\n rows.append(array_ops.concat(\n [zeros_to_pad_before, block, zeros_to_pad_after], axis=-1))\n\n return array_ops.concat(rows, axis=-2)\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass SquareLinearOperatorBlockDiagTest(\n linear_operator_test_util.SquareLinearOperatorDerivedClassTest):\n \"\"\"Most tests done in the base class LinearOperatorDerivedClassTest.\"\"\"\n\n def setUp(self):\n # Increase from 1e-6 to 1e-4\n self._atol[dtypes.float32] = 1e-4\n self._atol[dtypes.complex64] = 1e-4\n self._rtol[dtypes.float32] = 1e-4\n self._rtol[dtypes.complex64] = 1e-4\n\n @staticmethod\n def operator_shapes_infos():\n shape_info = linear_operator_test_util.OperatorShapesInfo\n return [\n shape_info((0, 0)),\n shape_info((1, 1)),\n shape_info((1, 3, 3)),\n shape_info((5, 5), blocks=[(2, 2), (3, 3)]),\n shape_info((3, 7, 7), blocks=[(1, 2, 2), (3, 2, 2), (1, 3, 3)]),\n shape_info((2, 1, 5, 5), blocks=[(2, 1, 2, 2), (1, 3, 3)]),\n ]\n\n @staticmethod\n def use_blockwise_arg():\n return True\n\n def operator_and_matrix(\n self, shape_info, dtype, use_placeholder,\n ensure_self_adjoint_and_pd=False):\n shape = list(shape_info.shape)\n expected_blocks = (\n shape_info.__dict__[\"blocks\"] if \"blocks\" in shape_info.__dict__\n else [shape])\n matrices = [\n linear_operator_test_util.random_positive_definite_matrix(\n block_shape, dtype, force_well_conditioned=True)\n for block_shape in expected_blocks\n ]\n\n lin_op_matrices = matrices\n\n if use_placeholder:\n lin_op_matrices = [\n array_ops.placeholder_with_default(\n matrix, shape=None) for matrix in matrices]\n\n operator = block_diag.LinearOperatorBlockDiag(\n [linalg.LinearOperatorFullMatrix(\n l,\n is_square=True,\n is_self_adjoint=True if ensure_self_adjoint_and_pd else None,\n is_positive_definite=True if ensure_self_adjoint_and_pd else None)\n for l in lin_op_matrices])\n\n # Should be auto-set.\n self.assertTrue(operator.is_square)\n\n # Broadcast the shapes.\n expected_shape = list(shape_info.shape)\n\n matrices = linear_operator_util.broadcast_matrix_batch_dims(matrices)\n\n block_diag_dense = _block_diag_dense(expected_shape, matrices)\n\n if not use_placeholder:\n block_diag_dense.set_shape(\n expected_shape[:-2] + [expected_shape[-1], expected_shape[-1]])\n\n return operator, block_diag_dense\n\n def test_is_x_flags(self):\n # Matrix with two positive eigenvalues, 1, and 1.\n # The matrix values do not effect auto-setting of the flags.\n matrix = [[1., 0.], [1., 1.]]\n operator = block_diag.LinearOperatorBlockDiag(\n [linalg.LinearOperatorFullMatrix(matrix)],\n is_positive_definite=True,\n is_non_singular=True,\n is_self_adjoint=False)\n self.assertTrue(operator.is_positive_definite)\n self.assertTrue(operator.is_non_singular)\n self.assertFalse(operator.is_self_adjoint)\n\n def test_is_x_parameters(self):\n matrix = [[1., 0.], [1., 1.]]\n sub_operator = linalg.LinearOperatorFullMatrix(matrix)\n operator = block_diag.LinearOperatorBlockDiag(\n [sub_operator],\n is_positive_definite=True,\n is_non_singular=True,\n is_self_adjoint=False)\n self.assertEqual(\n operator.parameters,\n {\n \"name\": None,\n \"is_square\": True,\n \"is_positive_definite\": True,\n \"is_self_adjoint\": False,\n \"is_non_singular\": True,\n \"operators\": [sub_operator],\n })\n self.assertEqual(\n sub_operator.parameters,\n {\n \"is_non_singular\": None,\n \"is_positive_definite\": None,\n \"is_self_adjoint\": None,\n \"is_square\": None,\n \"matrix\": matrix,\n \"name\": \"LinearOperatorFullMatrix\",\n })\n\n def test_block_diag_adjoint_type(self):\n matrix = [[1., 0.], [0., 1.]]\n operator = block_diag.LinearOperatorBlockDiag(\n [\n linalg.LinearOperatorFullMatrix(\n matrix,\n is_non_singular=True,\n ),\n linalg.LinearOperatorFullMatrix(\n matrix,\n is_non_singular=True,\n ),\n ],\n is_non_singular=True,\n )\n adjoint = operator.adjoint()\n self.assertIsInstance(\n adjoint,\n block_diag.LinearOperatorBlockDiag)\n self.assertEqual(2, len(adjoint.operators))\n\n def test_block_diag_cholesky_type(self):\n matrix = [[1., 0.], [0., 1.]]\n operator = block_diag.LinearOperatorBlockDiag(\n [\n linalg.LinearOperatorFullMatrix(\n matrix,\n is_positive_definite=True,\n is_self_adjoint=True,\n ),\n linalg.LinearOperatorFullMatrix(\n matrix,\n is_positive_definite=True,\n is_self_adjoint=True,\n ),\n ],\n is_positive_definite=True,\n is_self_adjoint=True,\n )\n cholesky_factor = operator.cholesky()\n self.assertIsInstance(\n cholesky_factor,\n block_diag.LinearOperatorBlockDiag)\n self.assertEqual(2, len(cholesky_factor.operators))\n self.assertIsInstance(\n cholesky_factor.operators[0],\n lower_triangular.LinearOperatorLowerTriangular)\n self.assertIsInstance(\n cholesky_factor.operators[1],\n lower_triangular.LinearOperatorLowerTriangular\n )\n\n def test_block_diag_inverse_type(self):\n matrix = [[1., 0.], [0., 1.]]\n operator = block_diag.LinearOperatorBlockDiag(\n [\n linalg.LinearOperatorFullMatrix(\n matrix,\n is_non_singular=True,\n ),\n linalg.LinearOperatorFullMatrix(\n matrix,\n is_non_singular=True,\n ),\n ],\n is_non_singular=True,\n )\n inverse = operator.inverse()\n self.assertIsInstance(\n inverse,\n block_diag.LinearOperatorBlockDiag)\n self.assertEqual(2, len(inverse.operators))\n\n def test_block_diag_matmul_type(self):\n matrices1 = []\n matrices2 = []\n for i in range(1, 5):\n matrices1.append(linalg.LinearOperatorFullMatrix(\n linear_operator_test_util.random_normal(\n [2, i], dtype=dtypes.float32)))\n\n matrices2.append(linalg.LinearOperatorFullMatrix(\n linear_operator_test_util.random_normal(\n [i, 3], dtype=dtypes.float32)))\n\n operator1 = block_diag.LinearOperatorBlockDiag(matrices1, is_square=False)\n operator2 = block_diag.LinearOperatorBlockDiag(matrices2, is_square=False)\n\n expected_matrix = math_ops.matmul(\n operator1.to_dense(), operator2.to_dense())\n actual_operator = operator1.matmul(operator2)\n\n self.assertIsInstance(\n actual_operator, block_diag.LinearOperatorBlockDiag)\n actual_, expected_ = self.evaluate([\n actual_operator.to_dense(), expected_matrix])\n self.assertAllClose(actual_, expected_)\n\n def test_block_diag_matmul_raises(self):\n matrices1 = []\n for i in range(1, 5):\n matrices1.append(linalg.LinearOperatorFullMatrix(\n linear_operator_test_util.random_normal(\n [2, i], dtype=dtypes.float32)))\n operator1 = block_diag.LinearOperatorBlockDiag(matrices1, is_square=False)\n operator2 = linalg.LinearOperatorFullMatrix(\n linear_operator_test_util.random_normal(\n [15, 3], dtype=dtypes.float32))\n\n with self.assertRaisesRegex(ValueError, \"Operators are incompatible\"):\n operator1.matmul(operator2)\n\n def test_block_diag_solve_type(self):\n matrices1 = []\n matrices2 = []\n for i in range(1, 5):\n matrices1.append(linalg.LinearOperatorFullMatrix(\n linear_operator_test_util.random_tril_matrix(\n [i, i],\n dtype=dtypes.float32,\n force_well_conditioned=True)))\n\n matrices2.append(linalg.LinearOperatorFullMatrix(\n linear_operator_test_util.random_normal(\n [i, 3], dtype=dtypes.float32)))\n\n operator1 = block_diag.LinearOperatorBlockDiag(matrices1)\n operator2 = block_diag.LinearOperatorBlockDiag(matrices2, is_square=False)\n\n expected_matrix = linalg.solve(\n operator1.to_dense(), operator2.to_dense())\n actual_operator = operator1.solve(operator2)\n\n self.assertIsInstance(\n actual_operator, block_diag.LinearOperatorBlockDiag)\n actual_, expected_ = self.evaluate([\n actual_operator.to_dense(), expected_matrix])\n self.assertAllClose(actual_, expected_)\n\n def test_block_diag_solve_raises(self):\n matrices1 = []\n for i in range(1, 5):\n matrices1.append(linalg.LinearOperatorFullMatrix(\n linear_operator_test_util.random_normal(\n [i, i], dtype=dtypes.float32)))\n operator1 = block_diag.LinearOperatorBlockDiag(matrices1)\n operator2 = linalg.LinearOperatorFullMatrix(\n linear_operator_test_util.random_normal(\n [15, 3], dtype=dtypes.float32))\n\n with self.assertRaisesRegex(ValueError, \"Operators are incompatible\"):\n operator1.solve(operator2)\n\n def test_tape_safe(self):\n matrices = []\n for _ in range(4):\n matrices.append(variables_module.Variable(\n linear_operator_test_util.random_positive_definite_matrix(\n [2, 2], dtype=dtypes.float32, force_well_conditioned=True)))\n\n operator = block_diag.LinearOperatorBlockDiag(\n [linalg.LinearOperatorFullMatrix(\n matrix, is_self_adjoint=True,\n is_positive_definite=True) for matrix in matrices],\n is_self_adjoint=True,\n is_positive_definite=True,\n )\n self.check_tape_safe(operator)\n\n def test_is_non_singular_auto_set(self):\n # Matrix with two positive eigenvalues, 11 and 8.\n # The matrix values do not effect auto-setting of the flags.\n matrix = [[11., 0.], [1., 8.]]\n operator_1 = linalg.LinearOperatorFullMatrix(matrix, is_non_singular=True)\n operator_2 = linalg.LinearOperatorFullMatrix(matrix, is_non_singular=True)\n\n operator = block_diag.LinearOperatorBlockDiag(\n [operator_1, operator_2],\n is_positive_definite=False, # No reason it HAS to be False...\n is_non_singular=None)\n self.assertFalse(operator.is_positive_definite)\n self.assertTrue(operator.is_non_singular)\n\n with self.assertRaisesRegex(ValueError, \"always non-singular\"):\n block_diag.LinearOperatorBlockDiag(\n [operator_1, operator_2], is_non_singular=False)\n\n def test_name(self):\n matrix = [[11., 0.], [1., 8.]]\n operator_1 = linalg.LinearOperatorFullMatrix(matrix, name=\"left\")\n operator_2 = linalg.LinearOperatorFullMatrix(matrix, name=\"right\")\n\n operator = block_diag.LinearOperatorBlockDiag([operator_1, operator_2])\n\n self.assertEqual(\"left_ds_right\", operator.name)\n\n def test_different_dtypes_raises(self):\n operators = [\n linalg.LinearOperatorFullMatrix(rng.rand(2, 3, 3)),\n linalg.LinearOperatorFullMatrix(rng.rand(2, 3, 3).astype(np.float32))\n ]\n with self.assertRaisesRegex(TypeError, \"same dtype\"):\n block_diag.LinearOperatorBlockDiag(operators)\n\n def test_empty_operators_raises(self):\n with self.assertRaisesRegex(ValueError, \"non-empty\"):\n block_diag.LinearOperatorBlockDiag([])\n\n def test_incompatible_input_blocks_raises(self):\n matrix_1 = array_ops.placeholder_with_default(rng.rand(4, 4), shape=None)\n matrix_2 = array_ops.placeholder_with_default(rng.rand(3, 3), shape=None)\n operators = [\n linalg.LinearOperatorFullMatrix(matrix_1, is_square=True),\n linalg.LinearOperatorFullMatrix(matrix_2, is_square=True)\n ]\n operator = block_diag.LinearOperatorBlockDiag(operators)\n x = np.random.rand(2, 4, 5).tolist()\n msg = (\"dimension does not match\" if context.executing_eagerly()\n else \"input structure is ambiguous\")\n with self.assertRaisesRegex(ValueError, msg):\n operator.matmul(x)\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass NonSquareLinearOperatorBlockDiagTest(\n linear_operator_test_util.NonSquareLinearOperatorDerivedClassTest):\n \"\"\"Most tests done in the base class LinearOperatorDerivedClassTest.\"\"\"\n\n def setUp(self):\n # Increase from 1e-6 to 1e-4\n self._atol[dtypes.float32] = 1e-4\n self._atol[dtypes.complex64] = 1e-4\n self._rtol[dtypes.float32] = 1e-4\n self._rtol[dtypes.complex64] = 1e-4\n super(NonSquareLinearOperatorBlockDiagTest, self).setUp()\n\n @staticmethod\n def operator_shapes_infos():\n shape_info = linear_operator_test_util.OperatorShapesInfo\n return [\n shape_info((1, 0)),\n shape_info((1, 2, 3)),\n shape_info((5, 3), blocks=[(2, 1), (3, 2)]),\n shape_info((3, 6, 5), blocks=[(1, 2, 1), (3, 1, 2), (1, 3, 2)]),\n shape_info((2, 1, 5, 2), blocks=[(2, 1, 2, 1), (1, 3, 1)]),\n ]\n\n @staticmethod\n def skip_these_tests():\n return [\n \"cholesky\",\n \"cond\",\n \"det\",\n \"diag_part\",\n \"eigvalsh\",\n \"inverse\",\n \"log_abs_det\",\n \"solve\",\n \"solve_with_broadcast\",\n \"trace\"]\n\n @staticmethod\n def use_blockwise_arg():\n return True\n\n def operator_and_matrix(\n self, shape_info, dtype, use_placeholder,\n ensure_self_adjoint_and_pd=False):\n del ensure_self_adjoint_and_pd\n shape = list(shape_info.shape)\n expected_blocks = (\n shape_info.__dict__[\"blocks\"] if \"blocks\" in shape_info.__dict__\n else [shape])\n matrices = [\n linear_operator_test_util.random_normal(block_shape, dtype=dtype)\n for block_shape in expected_blocks\n ]\n\n lin_op_matrices = matrices\n\n if use_placeholder:\n lin_op_matrices = [\n array_ops.placeholder_with_default(\n matrix, shape=None) for matrix in matrices]\n\n blocks = []\n for l in lin_op_matrices:\n blocks.append(\n linalg.LinearOperatorFullMatrix(\n l,\n is_square=False,\n is_self_adjoint=False,\n is_positive_definite=False))\n operator = block_diag.LinearOperatorBlockDiag(blocks)\n\n # Broadcast the shapes.\n expected_shape = list(shape_info.shape)\n\n matrices = linear_operator_util.broadcast_matrix_batch_dims(matrices)\n\n block_diag_dense = _block_diag_dense(expected_shape, matrices)\n\n if not use_placeholder:\n block_diag_dense.set_shape(expected_shape)\n\n return operator, block_diag_dense\n\n\nif __name__ == \"__main__\":\n linear_operator_test_util.add_tests(SquareLinearOperatorBlockDiagTest)\n linear_operator_test_util.add_tests(NonSquareLinearOperatorBlockDiagTest)\n test.main()\n", "# Copyright 2019 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\"\"\"Correctness test for tf.keras Embedding models using DistributionStrategy.\"\"\"\n\nimport numpy as np\n\nfrom tensorflow.python import keras\nfrom tensorflow.python.distribute import combinations as ds_combinations\nfrom tensorflow.python.distribute import multi_process_runner\nfrom tensorflow.python.keras.distribute import keras_correctness_test_base\nfrom tensorflow.python.keras.optimizer_v2 import gradient_descent as gradient_descent_keras\n\n\nclass DistributionStrategyEmbeddingModelCorrectnessTest(\n keras_correctness_test_base\n .TestDistributionStrategyEmbeddingModelCorrectnessBase):\n\n def get_model(self,\n max_words=10,\n initial_weights=None,\n distribution=None,\n input_shapes=None):\n del input_shapes\n with keras_correctness_test_base.MaybeDistributionScope(distribution):\n word_ids = keras.layers.Input(\n shape=(max_words,), dtype=np.int32, name='words')\n word_embed = keras.layers.Embedding(input_dim=20, output_dim=10)(word_ids)\n if self.use_distributed_dense:\n word_embed = keras.layers.TimeDistributed(keras.layers.Dense(4))(\n word_embed)\n avg = keras.layers.GlobalAveragePooling1D()(word_embed)\n preds = keras.layers.Dense(2, activation='softmax')(avg)\n model = keras.Model(inputs=[word_ids], outputs=[preds])\n\n if initial_weights:\n model.set_weights(initial_weights)\n\n model.compile(\n optimizer=gradient_descent_keras.SGD(learning_rate=0.1),\n loss='sparse_categorical_crossentropy',\n metrics=['sparse_categorical_accuracy'])\n return model\n\n @ds_combinations.generate(\n keras_correctness_test_base.test_combinations_for_embedding_model() +\n keras_correctness_test_base.multi_worker_mirrored_eager())\n def test_embedding_model_correctness(self, distribution, use_numpy,\n use_validation_data):\n\n self.use_distributed_dense = False\n self.run_correctness_test(distribution, use_numpy, use_validation_data)\n\n @ds_combinations.generate(\n keras_correctness_test_base.test_combinations_for_embedding_model() +\n keras_correctness_test_base.multi_worker_mirrored_eager())\n def test_embedding_time_distributed_model_correctness(\n self, distribution, use_numpy, use_validation_data):\n self.use_distributed_dense = True\n self.run_correctness_test(distribution, use_numpy, use_validation_data)\n\n\nclass DistributionStrategySiameseEmbeddingModelCorrectnessTest(\n keras_correctness_test_base\n .TestDistributionStrategyEmbeddingModelCorrectnessBase):\n\n def get_model(self,\n max_words=10,\n initial_weights=None,\n distribution=None,\n input_shapes=None):\n del input_shapes\n with keras_correctness_test_base.MaybeDistributionScope(distribution):\n word_ids_a = keras.layers.Input(\n shape=(max_words,), dtype=np.int32, name='words_a')\n word_ids_b = keras.layers.Input(\n shape=(max_words,), dtype=np.int32, name='words_b')\n\n def submodel(embedding, word_ids):\n word_embed = embedding(word_ids)\n rep = keras.layers.GlobalAveragePooling1D()(word_embed)\n return keras.Model(inputs=[word_ids], outputs=[rep])\n\n word_embed = keras.layers.Embedding(\n input_dim=20,\n output_dim=10,\n input_length=max_words,\n embeddings_initializer=keras.initializers.RandomUniform(0, 1))\n\n a_rep = submodel(word_embed, word_ids_a).outputs[0]\n b_rep = submodel(word_embed, word_ids_b).outputs[0]\n sim = keras.layers.Dot(axes=1, normalize=True)([a_rep, b_rep])\n\n model = keras.Model(inputs=[word_ids_a, word_ids_b], outputs=[sim])\n\n if initial_weights:\n model.set_weights(initial_weights)\n\n # TODO(b/130808953): Switch back to the V1 optimizer after global_step\n # is made mirrored.\n model.compile(\n optimizer=gradient_descent_keras.SGD(learning_rate=0.1),\n loss='mse',\n metrics=['mse'])\n return model\n\n def get_data(self,\n count=(keras_correctness_test_base._GLOBAL_BATCH_SIZE *\n keras_correctness_test_base._EVAL_STEPS),\n min_words=5,\n max_words=10,\n max_word_id=19,\n num_classes=2):\n features_a, labels_a, _ = (\n super(DistributionStrategySiameseEmbeddingModelCorrectnessTest,\n self).get_data(count, min_words, max_words, max_word_id,\n num_classes))\n\n features_b, labels_b, _ = (\n super(DistributionStrategySiameseEmbeddingModelCorrectnessTest,\n self).get_data(count, min_words, max_words, max_word_id,\n num_classes))\n\n y_train = np.zeros((count, 1), dtype=np.float32)\n y_train[labels_a == labels_b] = 1.0\n y_train[labels_a != labels_b] = -1.0\n # TODO(b/123360757): Add tests for using list as inputs for multi-input\n # models.\n x_train = {\n 'words_a': features_a,\n 'words_b': features_b,\n }\n x_predict = x_train\n\n return x_train, y_train, x_predict\n\n @ds_combinations.generate(\n keras_correctness_test_base.test_combinations_for_embedding_model() +\n keras_correctness_test_base.multi_worker_mirrored_eager())\n def test_siamese_embedding_model_correctness(self, distribution, use_numpy,\n use_validation_data):\n self.run_correctness_test(distribution, use_numpy, use_validation_data)\n\n\nif __name__ == '__main__':\n multi_process_runner.test_main()\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 bitwise operations.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport six\n\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import bitwise_ops\nfrom tensorflow.python.ops import gen_bitwise_ops\nfrom tensorflow.python.platform import googletest\n\n\nclass BitwiseOpTest(test_util.TensorFlowTestCase):\n\n def __init__(self, method_name=\"runTest\"):\n super(BitwiseOpTest, self).__init__(method_name)\n\n @test_util.run_deprecated_v1\n def testBinaryOps(self):\n dtype_list = [dtypes.int8, dtypes.int16, dtypes.int32, dtypes.int64,\n dtypes.uint8, dtypes.uint16, dtypes.uint32, dtypes.uint64]\n\n with self.session() as sess:\n for dtype in dtype_list:\n lhs = constant_op.constant([0, 5, 3, 14], dtype=dtype)\n rhs = constant_op.constant([5, 0, 7, 11], dtype=dtype)\n and_result, or_result, xor_result = sess.run(\n [bitwise_ops.bitwise_and(lhs, rhs),\n bitwise_ops.bitwise_or(lhs, rhs),\n bitwise_ops.bitwise_xor(lhs, rhs)])\n self.assertAllEqual(and_result, [0, 0, 3, 10])\n self.assertAllEqual(or_result, [5, 5, 7, 15])\n self.assertAllEqual(xor_result, [5, 5, 4, 5])\n\n def testPopulationCountOp(self):\n dtype_list = [\n dtypes.int8, dtypes.int16, dtypes.int32, dtypes.int64, dtypes.uint8,\n dtypes.uint16, dtypes.uint32, dtypes.uint64\n ]\n raw_inputs = [0, 1, -1, 3, -3, 5, -5, 14, -14,\n 127, 128, 255, 256, 65535, 65536,\n 2**31 - 1, 2**31, 2**32 - 1, 2**32, -2**32 + 1, -2**32,\n -2**63 + 1, 2**63 - 1]\n def count_bits(x):\n return sum(bin(z).count(\"1\") for z in six.iterbytes(x.tobytes()))\n for dtype in dtype_list:\n with self.cached_session():\n print(\"PopulationCount test: \", dtype)\n inputs = np.array(raw_inputs, dtype=dtype.as_numpy_dtype)\n truth = [count_bits(x) for x in inputs]\n input_tensor = constant_op.constant(inputs, dtype=dtype)\n popcnt_result = self.evaluate(\n gen_bitwise_ops.population_count(input_tensor))\n self.assertAllEqual(truth, popcnt_result)\n\n @test_util.run_deprecated_v1\n def testInvertOp(self):\n dtype_list = [dtypes.int8, dtypes.int16, dtypes.int32, dtypes.int64,\n dtypes.uint8, dtypes.uint16, dtypes.uint32, dtypes.uint64]\n inputs = [0, 5, 3, 14]\n with self.session() as sess:\n for dtype in dtype_list:\n # Because of issues with negative numbers, let's test this indirectly.\n # 1. invert(a) and a = 0\n # 2. invert(a) or a = invert(0)\n input_tensor = constant_op.constant(inputs, dtype=dtype)\n not_a_and_a, not_a_or_a, not_0 = sess.run(\n [bitwise_ops.bitwise_and(\n input_tensor, bitwise_ops.invert(input_tensor)),\n bitwise_ops.bitwise_or(\n input_tensor, bitwise_ops.invert(input_tensor)),\n bitwise_ops.invert(constant_op.constant(0, dtype=dtype))])\n self.assertAllEqual(not_a_and_a, [0, 0, 0, 0])\n self.assertAllEqual(not_a_or_a, [not_0] * 4)\n # For unsigned dtypes let's also check the result directly.\n if dtype.is_unsigned:\n inverted = self.evaluate(bitwise_ops.invert(input_tensor))\n expected = [dtype.max - x for x in inputs]\n self.assertAllEqual(inverted, expected)\n\n @test_util.run_deprecated_v1\n def testShiftsWithPositiveLHS(self):\n dtype_list = [np.int8, np.int16, np.int32, np.int64,\n np.uint8, np.uint16, np.uint32, np.uint64]\n\n with self.session() as sess:\n for dtype in dtype_list:\n lhs = np.array([0, 5, 3, 14], dtype=dtype)\n rhs = np.array([5, 0, 7, 3], dtype=dtype)\n left_shift_result, right_shift_result = sess.run(\n [bitwise_ops.left_shift(lhs, rhs),\n bitwise_ops.right_shift(lhs, rhs)])\n self.assertAllEqual(left_shift_result, np.left_shift(lhs, rhs))\n self.assertAllEqual(right_shift_result, np.right_shift(lhs, rhs))\n\n @test_util.run_deprecated_v1\n def testShiftsWithNegativeLHS(self):\n dtype_list = [np.int8, np.int16, np.int32, np.int64]\n\n with self.session() as sess:\n for dtype in dtype_list:\n lhs = np.array([-1, -5, -3, -14], dtype=dtype)\n rhs = np.array([5, 0, 7, 11], dtype=dtype)\n left_shift_result, right_shift_result = sess.run(\n [bitwise_ops.left_shift(lhs, rhs),\n bitwise_ops.right_shift(lhs, rhs)])\n self.assertAllEqual(left_shift_result, np.left_shift(lhs, rhs))\n self.assertAllEqual(right_shift_result, np.right_shift(lhs, rhs))\n\n @test_util.run_deprecated_v1\n def testImplementationDefinedShiftsDoNotCrash(self):\n dtype_list = [np.int8, np.int16, np.int32, np.int64]\n\n with self.session() as sess:\n for dtype in dtype_list:\n lhs = np.array([-1, -5, -3, -14], dtype=dtype)\n rhs = np.array([-2, 64, 101, 32], dtype=dtype)\n # We intentionally do not test for specific values here since the exact\n # outputs are implementation-defined. However, we should not crash or\n # trigger an undefined-behavior error from tools such as\n # AddressSanitizer.\n sess.run([bitwise_ops.left_shift(lhs, rhs),\n bitwise_ops.right_shift(lhs, rhs)])\n\n\n @test_util.run_deprecated_v1\n def testShapeInference(self):\n dtype_list = [dtypes.int8, dtypes.int16, dtypes.int32, dtypes.int64,\n dtypes.uint8, dtypes.uint16]\n\n with self.session() as sess:\n for dtype in dtype_list:\n lhs = constant_op.constant([[0], [3], [5]], dtype=dtype)\n rhs = constant_op.constant([[1, 2, 4]], dtype=dtype)\n\n and_tensor = bitwise_ops.bitwise_and(lhs, rhs)\n or_tensor = bitwise_ops.bitwise_or(lhs, rhs)\n xor_tensor = bitwise_ops.bitwise_xor(lhs, rhs)\n ls_tensor = bitwise_ops.left_shift(lhs, rhs)\n rs_tensor = bitwise_ops.right_shift(lhs, rhs)\n\n and_result, or_result, xor_result, ls_result, rs_result = sess.run(\n [and_tensor, or_tensor, xor_tensor, ls_tensor, rs_tensor])\n\n # Compare shape inference with result\n self.assertAllEqual(and_tensor.get_shape().as_list(), and_result.shape)\n self.assertAllEqual(and_tensor.get_shape().as_list(), [3, 3])\n self.assertAllEqual(or_tensor.get_shape().as_list(), or_result.shape)\n self.assertAllEqual(or_tensor.get_shape().as_list(), [3, 3])\n self.assertAllEqual(xor_tensor.get_shape().as_list(), xor_result.shape)\n self.assertAllEqual(xor_tensor.get_shape().as_list(), [3, 3])\n self.assertAllEqual(ls_tensor.get_shape().as_list(), ls_result.shape)\n self.assertAllEqual(ls_tensor.get_shape().as_list(), [3, 3])\n self.assertAllEqual(rs_tensor.get_shape().as_list(), rs_result.shape)\n self.assertAllEqual(rs_tensor.get_shape().as_list(), [3, 3])\n\n\nif __name__ == \"__main__\":\n googletest.main()\n", "# 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# pylint: disable=invalid-name\n\"\"\"VGG19 model for Keras.\n\nReference:\n - [Very Deep Convolutional Networks for Large-Scale Image Recognition](\n https://arxiv.org/abs/1409.1556) (ICLR 2015)\n\"\"\"\n\nfrom tensorflow.python.keras import backend\nfrom tensorflow.python.keras.applications import imagenet_utils\nfrom tensorflow.python.keras.engine import training\nfrom tensorflow.python.keras.layers import VersionAwareLayers\nfrom tensorflow.python.keras.utils import data_utils\nfrom tensorflow.python.keras.utils import layer_utils\nfrom tensorflow.python.lib.io import file_io\nfrom tensorflow.python.util.tf_export import keras_export\n\n\nWEIGHTS_PATH = ('https://storage.googleapis.com/tensorflow/keras-applications/'\n 'vgg19/vgg19_weights_tf_dim_ordering_tf_kernels.h5')\nWEIGHTS_PATH_NO_TOP = ('https://storage.googleapis.com/tensorflow/'\n 'keras-applications/vgg19/'\n 'vgg19_weights_tf_dim_ordering_tf_kernels_notop.h5')\n\nlayers = VersionAwareLayers()\n\n\n@keras_export('keras.applications.vgg19.VGG19', 'keras.applications.VGG19')\ndef VGG19(\n include_top=True,\n weights='imagenet',\n input_tensor=None,\n input_shape=None,\n pooling=None,\n classes=1000,\n classifier_activation='softmax'):\n \"\"\"Instantiates the VGG19 architecture.\n\n Reference:\n - [Very Deep Convolutional Networks for Large-Scale Image Recognition](\n https://arxiv.org/abs/1409.1556) (ICLR 2015)\n\n For image classification use cases, see\n [this page for detailed examples](\n https://keras.io/api/applications/#usage-examples-for-image-classification-models).\n\n For transfer learning use cases, make sure to read the\n [guide to transfer learning & fine-tuning](\n https://keras.io/guides/transfer_learning/).\n\n The default input size for this model is 224x224.\n\n Note: each Keras Application expects a specific kind of input preprocessing.\n For VGG19, call `tf.keras.applications.vgg19.preprocess_input` on your\n inputs before passing them to the model.\n `vgg19.preprocess_input` will convert the input images from RGB to BGR,\n then will zero-center each color channel with respect to the ImageNet dataset,\n without scaling.\n\n Args:\n include_top: whether to include the 3 fully-connected\n layers at the top of the network.\n weights: one of `None` (random initialization),\n 'imagenet' (pre-training on ImageNet),\n or the path to the weights file to be loaded.\n input_tensor: optional Keras tensor\n (i.e. output of `layers.Input()`)\n to use as image input for the model.\n input_shape: optional shape tuple, only to be specified\n if `include_top` is False (otherwise the input shape\n has to be `(224, 224, 3)`\n (with `channels_last` data format)\n or `(3, 224, 224)` (with `channels_first` data format).\n It should have exactly 3 inputs channels,\n and width and height should be no smaller than 32.\n E.g. `(200, 200, 3)` would be one valid value.\n pooling: Optional pooling mode for feature extraction\n when `include_top` is `False`.\n - `None` means that the output of the model will be\n the 4D tensor output of the\n last convolutional block.\n - `avg` means that global average pooling\n will be applied to the output of the\n last convolutional block, and thus\n the output of the model will be a 2D tensor.\n - `max` means that global max pooling will\n be applied.\n classes: optional number of classes to classify images\n into, only to be specified if `include_top` is True, and\n if no `weights` argument is specified.\n classifier_activation: A `str` or callable. The activation function to use\n on the \"top\" layer. Ignored unless `include_top=True`. Set\n `classifier_activation=None` to return the logits of the \"top\" layer.\n When loading pretrained weights, `classifier_activation` can only\n be `None` or `\"softmax\"`.\n\n Returns:\n A `keras.Model` instance.\n \"\"\"\n if not (weights in {'imagenet', None} or file_io.file_exists_v2(weights)):\n raise ValueError('The `weights` argument should be either '\n '`None` (random initialization), `imagenet` '\n '(pre-training on ImageNet), '\n 'or the path to the weights file to be loaded.')\n\n if weights == 'imagenet' and include_top and classes != 1000:\n raise ValueError('If using `weights` as `\"imagenet\"` with `include_top`'\n ' as true, `classes` should be 1000')\n # Determine proper input shape\n input_shape = imagenet_utils.obtain_input_shape(\n input_shape,\n default_size=224,\n min_size=32,\n data_format=backend.image_data_format(),\n require_flatten=include_top,\n weights=weights)\n\n if input_tensor is None:\n img_input = layers.Input(shape=input_shape)\n else:\n if not backend.is_keras_tensor(input_tensor):\n img_input = layers.Input(tensor=input_tensor, shape=input_shape)\n else:\n img_input = input_tensor\n # Block 1\n x = layers.Conv2D(\n 64, (3, 3), activation='relu', padding='same', name='block1_conv1')(\n img_input)\n x = layers.Conv2D(\n 64, (3, 3), activation='relu', padding='same', name='block1_conv2')(x)\n x = layers.MaxPooling2D((2, 2), strides=(2, 2), name='block1_pool')(x)\n\n # Block 2\n x = layers.Conv2D(\n 128, (3, 3), activation='relu', padding='same', name='block2_conv1')(x)\n x = layers.Conv2D(\n 128, (3, 3), activation='relu', padding='same', name='block2_conv2')(x)\n x = layers.MaxPooling2D((2, 2), strides=(2, 2), name='block2_pool')(x)\n\n # Block 3\n x = layers.Conv2D(\n 256, (3, 3), activation='relu', padding='same', name='block3_conv1')(x)\n x = layers.Conv2D(\n 256, (3, 3), activation='relu', padding='same', name='block3_conv2')(x)\n x = layers.Conv2D(\n 256, (3, 3), activation='relu', padding='same', name='block3_conv3')(x)\n x = layers.Conv2D(\n 256, (3, 3), activation='relu', padding='same', name='block3_conv4')(x)\n x = layers.MaxPooling2D((2, 2), strides=(2, 2), name='block3_pool')(x)\n\n # Block 4\n x = layers.Conv2D(\n 512, (3, 3), activation='relu', padding='same', name='block4_conv1')(x)\n x = layers.Conv2D(\n 512, (3, 3), activation='relu', padding='same', name='block4_conv2')(x)\n x = layers.Conv2D(\n 512, (3, 3), activation='relu', padding='same', name='block4_conv3')(x)\n x = layers.Conv2D(\n 512, (3, 3), activation='relu', padding='same', name='block4_conv4')(x)\n x = layers.MaxPooling2D((2, 2), strides=(2, 2), name='block4_pool')(x)\n\n # Block 5\n x = layers.Conv2D(\n 512, (3, 3), activation='relu', padding='same', name='block5_conv1')(x)\n x = layers.Conv2D(\n 512, (3, 3), activation='relu', padding='same', name='block5_conv2')(x)\n x = layers.Conv2D(\n 512, (3, 3), activation='relu', padding='same', name='block5_conv3')(x)\n x = layers.Conv2D(\n 512, (3, 3), activation='relu', padding='same', name='block5_conv4')(x)\n x = layers.MaxPooling2D((2, 2), strides=(2, 2), name='block5_pool')(x)\n\n if include_top:\n # Classification block\n x = layers.Flatten(name='flatten')(x)\n x = layers.Dense(4096, activation='relu', name='fc1')(x)\n x = layers.Dense(4096, activation='relu', name='fc2')(x)\n imagenet_utils.validate_activation(classifier_activation, weights)\n x = layers.Dense(classes, activation=classifier_activation,\n name='predictions')(x)\n else:\n if pooling == 'avg':\n x = layers.GlobalAveragePooling2D()(x)\n elif pooling == 'max':\n x = layers.GlobalMaxPooling2D()(x)\n\n # Ensure that the model takes into account\n # any potential predecessors of `input_tensor`.\n if input_tensor is not None:\n inputs = layer_utils.get_source_inputs(input_tensor)\n else:\n inputs = img_input\n # Create model.\n model = training.Model(inputs, x, name='vgg19')\n\n # Load weights.\n if weights == 'imagenet':\n if include_top:\n weights_path = data_utils.get_file(\n 'vgg19_weights_tf_dim_ordering_tf_kernels.h5',\n WEIGHTS_PATH,\n cache_subdir='models',\n file_hash='cbe5617147190e668d6c5d5026f83318')\n else:\n weights_path = data_utils.get_file(\n 'vgg19_weights_tf_dim_ordering_tf_kernels_notop.h5',\n WEIGHTS_PATH_NO_TOP,\n cache_subdir='models',\n file_hash='253f8cb515780f3b799900260a226db6')\n model.load_weights(weights_path)\n elif weights is not None:\n model.load_weights(weights)\n\n return model\n\n\n@keras_export('keras.applications.vgg19.preprocess_input')\ndef preprocess_input(x, data_format=None):\n return imagenet_utils.preprocess_input(\n x, data_format=data_format, mode='caffe')\n\n\n@keras_export('keras.applications.vgg19.decode_predictions')\ndef decode_predictions(preds, top=5):\n return imagenet_utils.decode_predictions(preds, top=top)\n\n\npreprocess_input.__doc__ = imagenet_utils.PREPROCESS_INPUT_DOC.format(\n mode='',\n ret=imagenet_utils.PREPROCESS_INPUT_RET_DOC_CAFFE,\n error=imagenet_utils.PREPROCESS_INPUT_ERROR_DOC)\ndecode_predictions.__doc__ = imagenet_utils.decode_predictions.__doc__\n", "# Copyright 2018 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\"\"\"Base testing class for strategies that require multiple nodes.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport contextlib\nimport copy\nimport json\nimport os\nimport subprocess\nimport sys\nimport threading\nimport unittest\n\nimport six\n\n_portpicker_import_error = None\ntry:\n import portpicker # pylint: disable=g-import-not-at-top\nexcept (ImportError, ModuleNotFoundError) as _error: # pylint: disable=invalid-name\n _portpicker_import_error = _error\n portpicker = None\n\n# pylint: disable=g-import-not-at-top\nfrom tensorflow.core.protobuf import config_pb2\nfrom tensorflow.core.protobuf import rewriter_config_pb2\nfrom tensorflow.python.client import session\nfrom tensorflow.python.distribute import distribute_coordinator as dc\nfrom tensorflow.python.distribute import multi_process_runner\nfrom tensorflow.python.distribute.cluster_resolver import SimpleClusterResolver\nfrom tensorflow.python.distribute.cluster_resolver import TFConfigClusterResolver\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.eager import remote\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.platform import test\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.training import coordinator\nfrom tensorflow.python.training import server_lib\nfrom tensorflow.python.util import deprecation\nfrom tensorflow.python.util import nest\nfrom tensorflow.python.util.compat import collections_abc\nfrom tensorflow.python.util.tf_export import tf_export\n\n\noriginal_run_std_server = dc._run_std_server # pylint: disable=protected-access\n\nASSIGNED_PORTS = set()\nlock = threading.Lock()\n\n\ndef pick_unused_port():\n \"\"\"Returns an unused and unassigned local port.\"\"\"\n if _portpicker_import_error:\n raise _portpicker_import_error # pylint: disable=raising-bad-type\n\n global ASSIGNED_PORTS\n with lock:\n while True:\n try:\n port = portpicker.pick_unused_port()\n except portpicker.NoFreePortFoundError:\n raise unittest.SkipTest('Flakes in portpicker library do not represent '\n 'TensorFlow errors.')\n if port > 10000 and port not in ASSIGNED_PORTS:\n ASSIGNED_PORTS.add(port)\n logging.info('Using local port %r', port)\n return port\n\n\ndef _create_cluster(num_workers,\n num_ps,\n has_chief=False,\n has_eval=False,\n protocol='grpc',\n worker_config=None,\n ps_config=None,\n eval_config=None,\n worker_name='worker',\n ps_name='ps',\n chief_name='chief'):\n \"\"\"Creates and starts local servers and returns the cluster_spec dict.\"\"\"\n if _portpicker_import_error:\n raise _portpicker_import_error # pylint: disable=raising-bad-type\n worker_ports = [pick_unused_port() for _ in range(num_workers)]\n ps_ports = [pick_unused_port() for _ in range(num_ps)]\n\n cluster_dict = {}\n if num_workers > 0:\n cluster_dict[worker_name] = ['localhost:%s' % port for port in worker_ports]\n if num_ps > 0:\n cluster_dict[ps_name] = ['localhost:%s' % port for port in ps_ports]\n if has_eval:\n cluster_dict['evaluator'] = ['localhost:%s' % pick_unused_port()]\n if has_chief:\n cluster_dict[chief_name] = ['localhost:%s' % pick_unused_port()]\n\n cs = server_lib.ClusterSpec(cluster_dict)\n\n for i in range(num_workers):\n server_lib.Server(\n cs,\n job_name=worker_name,\n protocol=protocol,\n task_index=i,\n config=worker_config,\n start=True)\n\n for i in range(num_ps):\n server_lib.Server(\n cs,\n job_name=ps_name,\n protocol=protocol,\n task_index=i,\n config=ps_config,\n start=True)\n\n if has_chief:\n server_lib.Server(\n cs,\n job_name=chief_name,\n protocol=protocol,\n task_index=0,\n config=worker_config,\n start=True)\n\n if has_eval:\n server_lib.Server(\n cs,\n job_name='evaluator',\n protocol=protocol,\n task_index=0,\n config=eval_config,\n start=True)\n\n return cluster_dict\n\n\ndef create_in_process_cluster(num_workers,\n num_ps,\n has_chief=False,\n has_eval=False,\n rpc_layer='grpc'):\n \"\"\"Create an in-process cluster that consists of only standard server.\"\"\"\n # Leave some memory for cuda runtime.\n gpu_mem_frac = 0.7 / (num_workers + int(has_chief) + int(has_eval))\n worker_config = config_pb2.ConfigProto()\n worker_config.gpu_options.per_process_gpu_memory_fraction = gpu_mem_frac\n\n # The cluster may hang if workers don't have enough inter_op threads. See\n # b/172296720 for more details.\n if worker_config.inter_op_parallelism_threads < num_workers + 1:\n worker_config.inter_op_parallelism_threads = num_workers + 1\n\n # Enable collective ops which has no impact on non-collective ops.\n # TODO(yuefengz, tucker): removing this after we move the initialization of\n # collective mgr to the session level.\n if has_chief:\n worker_config.experimental.collective_group_leader = (\n '/job:chief/replica:0/task:0')\n else:\n worker_config.experimental.collective_group_leader = (\n '/job:worker/replica:0/task:0')\n\n ps_config = config_pb2.ConfigProto()\n ps_config.device_count['GPU'] = 0\n\n eval_config = config_pb2.ConfigProto()\n eval_config.experimental.collective_group_leader = ''\n\n # Create in-process servers. Once an in-process tensorflow server is created,\n # there is no way to terminate it. So we create one cluster per test process.\n # We could've started the server in another process, we could then kill that\n # process to terminate the server. The reasons why we don't want multiple\n # processes are\n # 1) it is more difficult to manage these processes;\n # 2) there is something global in CUDA such that if we initialize CUDA in the\n # parent process, the child process cannot initialize it again and thus cannot\n # use GPUs (https://stackoverflow.com/questions/22950047).\n cluster = None\n try:\n cluster = _create_cluster(\n num_workers,\n num_ps=num_ps,\n has_chief=has_chief,\n has_eval=has_eval,\n worker_config=worker_config,\n ps_config=ps_config,\n eval_config=eval_config,\n protocol=rpc_layer)\n except errors.UnknownError as e:\n if 'Could not start gRPC server' in e.message:\n raise unittest.SkipTest('Cannot start std servers.')\n else:\n raise\n return cluster\n\n\nclass MultiProcessCluster(object):\n \"\"\"A cluster of TensorFlow servers in separate processes.\n\n This class is not thread-safe.\n \"\"\"\n\n def __init__(self,\n cluster_resolver,\n stream_output=False,\n collective_leader=None):\n self._cluster_resolver = cluster_resolver\n self._cluster_spec = cluster_resolver.cluster_spec().as_dict()\n self._rpc_layer = cluster_resolver.rpc_layer\n self._stream_output = stream_output\n self._start_events = {}\n self._finish_events = {}\n self._mpr_manager = multi_process_runner.manager()\n\n def task_function(start_events, finish_events):\n cluster_resolver = TFConfigClusterResolver()\n cluster_spec = cluster_resolver.cluster_spec()\n task_type = cluster_resolver.task_type\n task_id = cluster_resolver.task_id\n rpc_layer = cluster_resolver.rpc_layer\n\n # TODO(yuefengz): support GPU clusters.\n server_config = config_pb2.ConfigProto()\n server_config.device_count['GPU'] = 0\n\n if collective_leader:\n server_config.experimental.collective_group_leader = collective_leader\n server_config.experimental.collective_nccl = False\n\n logging.info(\n 'Enabling collective ops with cluster_spec = %r, task_type = %r, '\n 'task_id = %r, rpc_layer = %r, collective_leader = %s',\n cluster_spec, task_type, task_id, rpc_layer, collective_leader)\n else:\n logging.info(\n 'Starting server with cluster_spec = %r, task_type = %r, '\n 'task_id = %r, rpc_layer = %r', cluster_spec, task_type, task_id,\n rpc_layer)\n\n server_lib.Server(\n cluster_spec,\n job_name=task_type,\n protocol=rpc_layer,\n task_index=task_id,\n config=server_config,\n start=True)\n\n start_event = start_events[task_type][task_id]\n start_event.set()\n\n finish_event = finish_events[task_type][task_id]\n finish_event.wait()\n\n os._exit(0) # pylint: disable=protected-access\n\n self._task_function = task_function\n self._mpr = None\n\n def start(self):\n \"\"\"Starts one TensorFlow server for each task in the cluster_resolver.\n\n It will wait until all the servers are up before returns.\n \"\"\"\n if self._mpr:\n raise ValueError('The cluster has already been started.')\n for task_type, task_addresses in self._cluster_spec.items():\n self._start_events[task_type] = []\n self._finish_events[task_type] = []\n for _ in task_addresses:\n self._start_events[task_type].append(self._mpr_manager.Event())\n self._finish_events[task_type].append(self._mpr_manager.Event())\n\n self._mpr = multi_process_runner.MultiProcessRunner(\n self._task_function,\n self._cluster_spec,\n args=(self._start_events, self._finish_events),\n rpc_layer=self._rpc_layer,\n stream_output=self._stream_output,\n return_output=False,\n use_dill_for_args=False)\n self._mpr.start()\n for task_type, task_addresses in self._cluster_spec.items():\n for i in range(len(task_addresses)):\n self._start_events[task_type][i].wait()\n\n def stop(self):\n \"\"\"Stops all the servers.\"\"\"\n for task_type, task_addresses in self._cluster_spec.items():\n for i in range(len(task_addresses)):\n self._finish_events[task_type][i].set()\n try:\n self._mpr.join()\n except multi_process_runner.UnexpectedSubprocessExitError:\n # TODO(yuefengz): investigate why processes exit with 255.\n pass\n self._mpr = None\n self._start_events = {}\n self._finish_events = {}\n\n def kill_task(self, task_type, task_id):\n \"\"\"Kill a server given task_type and task_id.\n\n Args:\n task_type: the type of the task such as \"worker\".\n task_id: the id the task such as 1.\n \"\"\"\n assert self._mpr\n if (not self._start_events[task_type][task_id].is_set() or\n self._finish_events[task_type][task_id].is_set()):\n raise ValueError(\"The task %s:%d doesn't exist.\" % (task_type, task_id))\n\n self._finish_events[task_type][task_id].set()\n self._mpr._processes[(task_type, task_id)].join()\n\n def start_task(self, task_type, task_id):\n \"\"\"Starts a server given task_type and task_id.\n\n Args:\n task_type: the type of the task such as \"worker\".\n task_id: the id the task such as 1.\n\n Raises:\n ValueError: if the server alreay exists.\n \"\"\"\n assert self._mpr\n\n if (not self._start_events[task_type][task_id].is_set() or\n not self._finish_events[task_type][task_id].is_set()):\n raise ValueError(\n 'The task %s:%d is still alive. You cannot start another one.' %\n (task_type, task_id))\n self._start_events[task_type][task_id] = self._mpr_manager.Event()\n self._finish_events[task_type][task_id] = self._mpr_manager.Event()\n self._mpr.start_single_process(task_type=task_type, task_id=task_id)\n self._start_events[task_type][task_id].wait()\n\n @property\n def cluster_resolver(self):\n return copy.deepcopy(self._cluster_resolver)\n\n\ndef create_multi_process_cluster(num_workers,\n num_ps,\n has_chief=False,\n has_eval=False,\n rpc_layer='grpc',\n stream_output=False,\n collective_leader=None):\n cluster_spec = create_cluster_spec(\n has_chief=has_chief,\n num_workers=num_workers,\n num_ps=num_ps,\n has_eval=has_eval)\n\n cluster = MultiProcessCluster(\n SimpleClusterResolver(\n server_lib.ClusterSpec(cluster_spec), rpc_layer=rpc_layer),\n stream_output=stream_output,\n collective_leader=collective_leader)\n cluster.start()\n return cluster\n\n\n@tf_export(\n '__internal__.distribute.multi_process_runner.create_cluster_spec', v1=[])\ndef create_cluster_spec(has_chief=False,\n num_workers=1,\n num_ps=0,\n has_eval=False):\n \"\"\"Create a cluster spec with tasks with unused local ports.\n\n This utility finds available ports at localhost, and returns a dict that\n represents the cluster spec that utilizes those ports, according to the\n arguments. The dict representing the cluster spec contains task types, and\n their instances' addresses. Note that this is usually only for testing purpose\n using multiple processes in the local machine, and should not be used for real\n multi-worker TensorFlow programs, where the addresses need to point to the\n processes at separate machines.\n\n This util is useful when creating the `cluster_spec` arg for\n `tf.__internal__.distribute.multi_process_runner.run`.\n\n Args:\n has_chief: Whether the generated cluster spec should contain \"chief\" task\n type.\n num_workers: Number of workers to use in the cluster spec.\n num_ps: Number of parameter servers to use in the cluster spec.\n has_eval: Whether this cluster spec has evaluator.\n\n Returns:\n A dict that represents the cluster spec using localhost ports for the tasks.\n\n Example:\n\n ```python\n cluster_spec =\n tf.__internal__.distribute.multi_process_runner.create_cluster_spec(\n has_chief=True, num_workers=2, num_ps=2)\n # An example of cluster_spec is\n # {'chief': ['localhost:23381'],\n # 'worker': ['localhost:19197', 'localhost:22903'],\n # 'ps': ['localhost:16912', 'localhost:21535']}\n\n cluster_spec =\n tf.__internal__.distribute.multi_process_runner.create_cluster_spec(\n has_chief=False, num_workers=0, num_ps=0, has_eval=True)\n # An example of cluster_spec is\n # {'evaluator': ['localhost:23381']}\n ```\n \"\"\"\n if _portpicker_import_error:\n raise _portpicker_import_error # pylint: disable=raising-bad-type\n\n cluster_spec = {}\n if has_chief:\n cluster_spec['chief'] = ['localhost:%s' % pick_unused_port()]\n if num_workers:\n cluster_spec['worker'] = [\n 'localhost:%s' % pick_unused_port() for _ in range(num_workers)\n ]\n if num_ps:\n cluster_spec['ps'] = [\n 'localhost:%s' % pick_unused_port() for _ in range(num_ps)\n ]\n if has_eval:\n cluster_spec['evaluator'] = ['localhost:%s' % pick_unused_port()]\n return cluster_spec\n\n\[email protected]\ndef skip_if_grpc_server_cant_be_started(test_obj):\n try:\n yield\n except errors.UnknownError as e:\n if 'Could not start gRPC server' in e.message:\n reason = 'Cannot start std servers.'\n test_obj.test_skipped_reason = reason\n test_obj.skipTest(reason)\n else:\n raise\n\n\nclass MultiWorkerTestBase(test.TestCase):\n \"\"\"Base class for testing multi node strategy and dataset.\"\"\"\n\n @classmethod\n def setUpClass(cls, num_workers=2, num_ps=1): # pylint: disable=g-missing-super-call\n \"\"\"Create a local cluster with 2 workers.\"\"\"\n cls._cluster_spec = create_in_process_cluster(num_workers=num_workers,\n num_ps=num_ps)\n cls._default_target = 'grpc://' + cls._cluster_spec['worker'][0]\n\n def setUp(self):\n # We only cache the session in one test because another test may have a\n # different session config or master target.\n self._thread_local = threading.local()\n self._thread_local.cached_session = None\n self._coord = coordinator.Coordinator()\n\n @contextlib.contextmanager\n def session(self, graph=None, config=None, target=None):\n \"\"\"Create a test session with master target set to the testing cluster.\n\n Creates a test session that connects to the local testing cluster.\n\n Args:\n graph: Optional graph to use during the returned session.\n config: An optional config_pb2.ConfigProto to use to configure the\n session.\n target: the target of session to connect to.\n\n Yields:\n A Session object that should be used as a context manager to surround\n the graph building and execution code in a test case.\n \"\"\"\n config = self._create_config(config)\n\n if target is None:\n target = self._default_target\n with session.Session(graph=graph, config=config, target=target) as sess:\n yield sess\n\n @contextlib.contextmanager\n # TODO(b/117573461): Overwrite self.evaluate() to use this function.\n def cached_session(self, graph=None, config=None, target=None):\n \"\"\"Create a test session with master target set to the testing cluster.\n\n Creates a test session that connects to the local testing cluster.\n The session is only created once per test and then reused.\n\n Args:\n graph: Optional graph to use during the returned session.\n config: An optional config_pb2.ConfigProto to use to configure the\n session.\n target: the target of session to connect to.\n\n Yields:\n A Session object that should be used as a context manager to surround\n the graph building and execution code in a test case. Note that the\n session will live until the end of the test.\n \"\"\"\n config = self._create_config(config)\n\n if target is None:\n target = self._default_target\n if getattr(self._thread_local, 'cached_session', None) is None:\n self._thread_local.cached_session = session.Session(\n graph=None, config=config, target=target)\n sess = self._thread_local.cached_session\n with sess.graph.as_default(), sess.as_default():\n yield sess\n\n def _create_config(self, config):\n if config is None:\n config = config_pb2.ConfigProto(allow_soft_placement=True)\n else:\n config = copy.deepcopy(config)\n # Don't perform optimizations for tests so we don't inadvertently run\n # gpu ops on cpu\n config.graph_options.optimizer_options.opt_level = -1\n config.graph_options.rewrite_options.constant_folding = (\n rewriter_config_pb2.RewriterConfig.OFF)\n\n return config\n\n def _run_client(self, client_fn, task_type, task_id, num_gpus, eager_mode,\n *args, **kwargs):\n\n def wrapped_client_fn():\n with self._coord.stop_on_exception():\n client_fn(task_type, task_id, num_gpus, *args, **kwargs)\n\n if eager_mode:\n with context.eager_mode():\n wrapped_client_fn()\n else:\n with context.graph_mode():\n wrapped_client_fn()\n\n def _run_between_graph_clients(self, client_fn, cluster_spec, num_gpus, *args,\n **kwargs):\n \"\"\"Runs several clients for between-graph replication.\n\n Args:\n client_fn: a function that needs to accept `task_type`, `task_id`,\n `num_gpus`.\n cluster_spec: a dict specifying jobs in a cluster.\n num_gpus: number of GPUs per worker.\n *args: will be passed to `client_fn`.\n **kwargs: will be passed to `client_fn`.\n \"\"\"\n threads = []\n for task_type in ['chief', 'worker']:\n for task_id in range(len(cluster_spec.get(task_type, []))):\n t = threading.Thread(\n target=self._run_client,\n args=(client_fn, task_type, task_id, num_gpus,\n context.executing_eagerly()) + args,\n kwargs=kwargs)\n t.start()\n threads.append(t)\n self._coord.join(threads)\n\n\nclass SingleWorkerTestBaseGraph(MultiWorkerTestBase):\n \"\"\"Base class for testing remote single worker strategy graph and dataset.\"\"\"\n\n @classmethod\n def setUpClass(cls):\n super(SingleWorkerTestBaseGraph, cls).setUpClass(num_workers=1)\n\n\nclass SingleWorkerTestBaseEager(test.TestCase):\n \"\"\"Base class for testing remote single worker strategy eager and dataset.\"\"\"\n\n def setUp(self):\n super(SingleWorkerTestBaseEager, self).setUp()\n workers, _ = test_util.create_local_cluster(num_workers=1, num_ps=0)\n remote.connect_to_remote_host(workers[0].target)\n\n def cached_session(self):\n return DummySession()\n\n\nclass DummySession(object):\n\n def __enter__(self):\n return\n\n def __exit__(self, exception_type, exception_value, traceback):\n pass\n\n\nclass MockOsEnv(collections_abc.Mapping):\n \"\"\"A class that allows per-thread TF_CONFIG.\"\"\"\n\n def __init__(self, *args):\n self._dict = dict()\n self._thread_local = threading.local()\n super(MockOsEnv, self).__init__(*args)\n\n def get(self, key, default=None):\n if not hasattr(self._thread_local, 'dict'):\n self._thread_local.dict = dict()\n if key == 'TF_CONFIG':\n return dict.get(self._thread_local.dict, key, default)\n else:\n return dict.get(self._dict, key, default)\n\n def __getitem__(self, key):\n if not hasattr(self._thread_local, 'dict'):\n self._thread_local.dict = dict()\n if key == 'TF_CONFIG':\n return dict.__getitem__(self._thread_local.dict, key)\n else:\n return dict.__getitem__(self._dict, key)\n\n def __setitem__(self, key, val):\n if not hasattr(self._thread_local, 'dict'):\n self._thread_local.dict = dict()\n if key == 'TF_CONFIG':\n return dict.__setitem__(self._thread_local.dict, key, val)\n else:\n return dict.__setitem__(self._dict, key, val)\n\n def __iter__(self):\n if not hasattr(self._thread_local, 'dict'):\n self._thread_local.dict = dict()\n for x in self._thread_local.dict:\n yield x\n for x in self._dict:\n yield x\n\n def __len__(self):\n if not hasattr(self._thread_local, 'dict'):\n self._thread_local.dict = dict()\n return self._thread_local.dict.__len__() + self._dict.__len__()\n\n\nclass IndependentWorkerTestBase(test.TestCase):\n \"\"\"Testing infra for independent workers.\"\"\"\n\n def _make_mock_run_std_server(self):\n\n def _mock_run_std_server(*args, **kwargs):\n \"\"\"Returns the std server once all threads have started it.\"\"\"\n with skip_if_grpc_server_cant_be_started(self):\n ret = original_run_std_server(*args, **kwargs)\n # Wait for all std servers to be brought up in order to reduce the chance\n # of remote sessions taking local ports that have been assigned to std\n # servers. Only call this barrier the first time this function is run for\n # each thread.\n if not getattr(self._thread_local, 'server_started', False):\n self._barrier.wait()\n self._thread_local.server_started = True\n return ret\n\n return _mock_run_std_server\n\n def setUp(self):\n self._mock_os_env = MockOsEnv()\n self._mock_context = test.mock.patch.object(os, 'environ',\n self._mock_os_env)\n self._coord = coordinator.Coordinator()\n super(IndependentWorkerTestBase, self).setUp()\n self._mock_context.__enter__()\n # threading local object to be shared by all threads\n self._thread_local = threading.local()\n\n def tearDown(self):\n self._mock_context.__exit__(None, None, None)\n super(IndependentWorkerTestBase, self).tearDown()\n\n def _task_thread(self, task_fn, tf_config, executing_eagerly, *args,\n **kwargs):\n with self._coord.stop_on_exception():\n os.environ['TF_CONFIG'] = json.dumps(tf_config)\n # Force the new thread simulating a worker to run in the same context\n # mode as the parent thread does.\n if executing_eagerly:\n with context.eager_mode():\n task_fn(*args, **kwargs)\n else:\n with ops.Graph().as_default(), context.graph_mode():\n task_fn(*args, **kwargs)\n\n def _run_task_in_thread(self, task_fn, cluster_spec, task_type, task_id,\n *args, **kwargs):\n \"\"\"Run tasks in a thread.\n\n If `tf_config` is provided, use it for the new thread; if not, construct one\n from `cluster_spec`, `task_type`, and `task_id`, and provide it to the new\n thread to be set as `TF_CONFIG` environment.\n\n Args:\n task_fn: The function to run in the new thread.\n cluster_spec: The cluster spec.\n task_type: The task type.\n task_id: The task id.\n *args: Additional positional arguments to provide to the thread's task_fn.\n **kwargs: Additional keyword arguments to provide to the thread's task_fn.\n If `tf_config` is provided, that dict will be used for the TF_CONFIG for\n the new thread.\n\n Returns:\n The thread that has started.\n \"\"\"\n tf_config = kwargs.pop('tf_config', None)\n if tf_config is None:\n if task_type:\n tf_config = {\n 'cluster': cluster_spec,\n 'task': {\n 'type': task_type,\n 'index': task_id\n }\n }\n else:\n tf_config = {\n 'cluster': cluster_spec,\n }\n t = threading.Thread(\n target=self._task_thread,\n args=(task_fn, tf_config, context.executing_eagerly()) + args,\n kwargs=kwargs)\n t.start()\n return t\n\n def run_multiple_tasks_in_threads(self, task_fn, cluster_spec, *args,\n **kwargs):\n # The task_fn should create std_server by itself.\n threads = {}\n for task_type in cluster_spec.keys():\n threads[task_type] = []\n for task_id in range(len(cluster_spec[task_type])):\n t = self._run_task_in_thread(task_fn, cluster_spec, task_type, task_id,\n *args, **kwargs)\n threads[task_type].append(t)\n return threads\n\n def join_independent_workers(self, worker_threads):\n with skip_if_grpc_server_cant_be_started(self):\n self._coord.join(worker_threads)\n\n\nclass MultiWorkerMultiProcessTest(test.TestCase):\n \"\"\"Testing infra for independent workers using multiple processes.\"\"\"\n\n def _run_task_in_process(self, cmd_args, cluster_spec, task_type, task_id):\n env = os.environ.copy()\n env['TF_CONFIG'] = json.dumps({\n 'cluster': cluster_spec,\n 'task': {\n 'type': task_type,\n 'index': task_id\n }\n })\n return subprocess.Popen(\n cmd_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)\n\n @deprecation.deprecated(\n None, '`run_multiple_tasks_in_processes` is deprecated; any new test '\n 'requiring multiple processes should use `multi_process_runner` for '\n 'better support of log printing, streaming, and more functionality.')\n def run_multiple_tasks_in_processes(self, cmd_args, cluster_spec):\n \"\"\"Run `cmd_args` in a process for each task in `cluster_spec`.\"\"\"\n processes = {}\n for task_type in cluster_spec.keys():\n processes[task_type] = []\n for task_id in range(len(cluster_spec[task_type])):\n p = self._run_task_in_process(cmd_args, cluster_spec, task_type,\n task_id)\n processes[task_type].append(p)\n return processes\n\n @deprecation.deprecated(\n None, '`join_independent_workers` is deprecated; any new test '\n 'requiring multiple processes should use `multi_process_runner` for '\n 'better support of log printing, streaming, and more functionality.')\n def join_independent_workers(self, worker_processes):\n return_codes = []\n for p in nest.flatten(worker_processes):\n try:\n # Calling p.wait() will hang if we don't consume its output.\n p.communicate()\n except ValueError:\n # The output of the process may have been consumed, in which case\n # calling `p.communicate()` will raise a ValueError.\n pass\n finally:\n return_codes.append(p.returncode)\n for return_code in return_codes:\n self.assertEqual(return_code, 0)\n\n @deprecation.deprecated(\n None, '`stream_stderr` is deprecated; any new test '\n 'requiring multiple processes should use `multi_process_runner` for '\n 'better support of log printing, streaming, and more functionality.')\n def stream_stderr(self, processes, print_only_first=False):\n \"\"\"Consume stderr of all processes and print to stdout.\n\n To reduce the amount of logging, caller can set print_only_first to True.\n In that case, this function only prints stderr from the first process of\n each type.\n\n Args:\n processes: A dictionary from process type string -> list of processes.\n print_only_first: If true, only print output from first process of each\n type.\n \"\"\"\n\n def _stream_stderr_single_process(process, type_string, index,\n print_to_stdout):\n \"\"\"Consume a single process's stderr and optionally print to stdout.\"\"\"\n while True:\n output = process.stderr.readline()\n if not output and process.poll() is not None:\n break\n if output and print_to_stdout:\n print('{}{} {}'.format(type_string, index, output.strip()))\n sys.stdout.flush()\n\n stream_threads = []\n for process_type, process_list in six.iteritems(processes):\n for i in range(len(process_list)):\n print_to_stdout = (not print_only_first) or (i == 0)\n thread = threading.Thread(\n target=_stream_stderr_single_process,\n args=(process_list[i], process_type, i, print_to_stdout))\n thread.start()\n stream_threads.append(thread)\n for thread in stream_threads:\n thread.join()\n\n\ndef get_tf_config_task():\n return json.loads(os.environ['TF_CONFIG'])['task']\n\n\ndef get_tf_config_cluster_spec():\n return json.loads(os.environ['TF_CONFIG'])['cluster']\n\n\ndef get_task_type():\n return get_tf_config_task()['type']\n\n\ndef get_task_index():\n return get_tf_config_task()['index']\n\n\ndef is_chief():\n return ('chief' not in get_tf_config_cluster_spec()\n and get_task_type() == 'worker'\n and get_task_index() == 0)\n" ]
[ [ "tensorflow.python.autograph.pyct.templates.replace", "tensorflow.python.autograph.pyct.origin_info.resolve_entity", "tensorflow.python.autograph.pyct.parser.parse_entity", "tensorflow.python.autograph.pyct.transformer.EntityInfo", "tensorflow.python.autograph.pyct.naming.Namer", "tensorflow.python.autograph.pyct.transformer.Context", "tensorflow.python.autograph.pyct.cache.CodeObjectCache", "tensorflow.python.autograph.pyct.inspect_utils.getfutureimports", "tensorflow.python.autograph.pyct.parser.parse_expression", "tensorflow.python.autograph.utils.ag_logging.log", "tensorflow.python.autograph.utils.ag_logging.has_verbosity", "tensorflow.python.autograph.pyct.parser.unparse", "tensorflow.python.autograph.pyct.loader.load_ast", "tensorflow.python.autograph.pyct.inspect_utils.getnamespace" ], [ "tensorflow.python.framework.tensor_shape.TensorShape", "tensorflow.python.platform.gfile.GFile", "tensorflow.python.keras.utils.generic_utils.serialize_keras_class_and_config", "tensorflow.python.framework.ops.executing_eagerly_outside_functions", "tensorflow.python.platform.gfile.Exists", "tensorflow.python.keras.saving.saving_utils.try_build_compiled_arguments", "tensorflow.python.ops.ragged.ragged_tensor.RaggedTensorSpec", "tensorflow.python.eager.context.executing_eagerly", "tensorflow.python.keras.utils.metrics_utils.update_state_wrapper", "tensorflow.python.saved_model.load.load_partial", "tensorflow.python.keras.utils.generic_utils.get_registered_object", "tensorflow.python.keras.backend.track_variable", "tensorflow.python.keras.saving.saved_model.json_utils.decode", "tensorflow.python.framework.ops.get_collection", "tensorflow.python.saved_model.loader_impl.parse_saved_model", "tensorflow.python.saved_model.revived_types.get_setter", "tensorflow.python.util.compat.as_str", "tensorflow.python.framework.tensor_shape.dimension_value", "tensorflow.python.keras.backend.get_session", "tensorflow.python.util.nest.map_structure", "tensorflow.python.platform.tf_logging.warning", "tensorflow.python.keras.saving.saved_model.serialized_attributes.CommonEndpoints.all_functions.union", "tensorflow.python.keras.saving.saving_utils.compile_args_from_training_config", "tensorflow.python.framework.sparse_tensor.SparseTensorSpec", "tensorflow.python.saved_model.nested_structure_coder.StructureCoder", "tensorflow.python.keras.utils.generic_utils.deserialize_keras_object", "tensorflow.python.keras.regularizers.deserialize", "tensorflow.python.saved_model.load.load", "tensorflow.python.framework.tensor_spec.TensorSpec", "tensorflow.python.saved_model.revived_types.registered_identifiers", "tensorflow.python.keras.saving.saved_model.utils.use_wrapped_call", "tensorflow.python.keras.utils.generic_utils.validate_config", "tensorflow.python.keras.protobuf.saved_metadata_pb2.SavedMetadata", "tensorflow.python.keras.protobuf.versions_pb2.VersionDef", "tensorflow.python.keras.saving.saved_model.utils.no_automatic_dependency_tracking_scope", "tensorflow.python.util.nest.flatten" ], [ "tensorflow.python.framework.device.check_valid", "tensorflow.python.framework.device.merge_device", "tensorflow.python.ops.variables.Variable", "tensorflow.python.framework.device.canonical_name", "tensorflow.python.platform.googletest.main", "tensorflow.python.eager.context.executing_eagerly" ], [ "tensorflow.python.data.ops.readers.TextLineDataset", "tensorflow.python.data.experimental.ops.interleave_ops.parallel_interleave", "tensorflow.python.framework.function.Defun", "tensorflow.python.data.ops.readers.TFRecordDataset", "tensorflow.python.ops.functional_ops.remote_call", "tensorflow.python.data.ops.dataset_ops.make_one_shot_iterator", "tensorflow.python.data.ops.dataset_ops.Dataset.range", "tensorflow.python.framework.ops.device", "tensorflow.python.data.ops.dataset_ops.get_legacy_output_shapes", "tensorflow.python.data.ops.dataset_ops.get_legacy_output_types", "tensorflow.python.data.ops.dataset_ops.Dataset.list_files" ], [ "tensorflow.python.tpu.device_assignment.DeviceAssignment.build", "tensorflow.python.data.ops.dataset_ops.Dataset.from_tensors", "tensorflow.python.ops.array_ops.constant", "tensorflow.python.ops.array_ops.shape", "tensorflow.python.framework.config.set_soft_device_placement", "tensorflow.python.distribute.cluster_resolver.tpu_cluster_resolver.TPUClusterResolver", "tensorflow.python.tpu.tpu.outside_compilation", "tensorflow.python.tpu.device_assignment.DeviceAssignment", "tensorflow.python.ops.variables.Variable", "tensorflow.python.distribute.distribution_strategy_context.has_strategy", "tensorflow.python.ops.array_ops.zeros", "tensorflow.python.framework.device.DeviceSpec.from_string", "tensorflow.python.training.checkpoint_management.latest_checkpoint", "tensorflow.python.eager.remote.connect_to_cluster", "tensorflow.python.framework.ops.device", "tensorflow.python.data.ops.dataset_ops.Dataset.range", "tensorflow.python.platform.flags.DEFINE_string", "tensorflow.python.distribute.distribute_lib.InputOptions", "tensorflow.python.distribute.tpu_strategy.TPUStrategyV2", "tensorflow.python.ops.array_ops.where", "tensorflow.python.tpu.tpu_strategy_util.initialize_tpu_system", "tensorflow.python.ops.array_ops.gather", "tensorflow.python.framework.sparse_tensor.SparseTensor", "tensorflow.python.ops.array_ops.size", "tensorflow.python.ops.lookup_ops.KeyValueTensorInitializer", "tensorflow.python.ops.array_ops.expand_dims", "tensorflow.python.ops.control_flow_ops.switch_case", "tensorflow.python.eager.function.defun_with_attributes", "tensorflow.python.ops.math_ops.reduce_sum", "tensorflow.python.eager.test.main", "tensorflow.python.data.ops.dataset_ops.Dataset.from_tensor_slices", "tensorflow.python.ops.math_ops.square", "tensorflow.python.eager.def_function.function", "tensorflow.python.ops.random_ops.random_gamma", "tensorflow.python.training.server_lib.ClusterSpec", "tensorflow.python.distribute.distribution_strategy_context.get_strategy", "tensorflow.python.ops.math_ops.unsorted_segment_sum", "tensorflow.python.ops.lookup_ops.StaticHashTable", "tensorflow.python.distribute.distribution_strategy_context.get_replica_context", "tensorflow.python.ops.ragged.ragged_tensor.RaggedTensor.from_row_splits", "tensorflow.python.ops.math_ops.range", "tensorflow.python.ops.array_ops.concat", "tensorflow.python.framework.tensor_spec.TensorSpec", "tensorflow.python.framework.tensor_spec.TensorSpec.from_tensor", "tensorflow.python.ops.array_ops.reshape", "tensorflow.python.eager.test.mock.patch.object", "tensorflow.python.ops.random_ops.random_normal", "tensorflow.python.ops.variables.global_variables_initializer", "tensorflow.python.training.tracking.util.Checkpoint", "tensorflow.core.protobuf.config_pb2.ConfigProto", "tensorflow.python.framework.constant_op.constant" ], [ "tensorflow.python.keras.benchmarks.distribution_util.get_strategy_scope", "numpy.mean", "tensorflow.python.keras.benchmarks.distribution_util.get_distribution_strategy" ], [ "tensorflow.python.framework.tensor_shape.TensorShape", "tensorflow.python.keras.layers.Dense", "tensorflow.python.ops.array_ops.placeholder", "tensorflow.python.ops.variables.Variable", "tensorflow.python.ops.init_ops.random_uniform_initializer", "tensorflow.python.ops.array_ops.zeros", "tensorflow.python.eager.context.executing_eagerly", "tensorflow.python.keras.layers.BatchNormalization", "tensorflow.python.keras.tests.model_subclassing_test_util.CustomCallModel", "tensorflow.python.keras.layers.LSTM", "tensorflow.python.platform.test.main", "tensorflow.python.ops.array_ops.ones", "tensorflow.python.ops.embedding_ops.embedding_lookup", "tensorflow.python.keras.tests.model_subclassing_test_util.SimpleConvTestModel", "numpy.zeros", "tensorflow.python.keras.tests.model_subclassing_test_util.TrainingNoDefaultModel", "tensorflow.python.keras.layers.Add", "tensorflow.python.keras.Model", "tensorflow.python.keras.testing_utils.SmallSubclassMLP", "tensorflow.python.keras.combinations.combine", "tensorflow.python.keras.tests.model_subclassing_test_util.get_multi_io_subclass_model", "tensorflow.python.keras.testing_utils.should_run_eagerly", "tensorflow.python.keras.Input", "tensorflow.python.framework.tensor_shape.Dimension", "tensorflow.python.framework.ops.Graph", "tensorflow.python.keras.tests.model_subclassing_test_util.TrainingMaskingModel", "numpy.ones", "tensorflow.python.framework.ops.get_default_graph" ], [ "tensorflow.python.ops.linalg_ops.matrix_solve_ls", "tensorflow.python.framework.test_util.run_in_graph_and_eager_modes", "numpy.random.seed", "tensorflow.python.framework.test_util.run_without_tensor_float_32", "tensorflow.python.ops.linalg_ops.matrix_determinant", "numpy.finfo", "tensorflow.python.platform.test.main", "tensorflow.python.ops.math_ops.matmul", "tensorflow.python.platform.test.is_built_with_rocm", "tensorflow.python.ops.array_ops.ones", "tensorflow.python.ops.linalg_ops.log_matrix_determinant", "numpy.random.uniform", "numpy.prod", "tensorflow.python.ops.gradients_impl.gradients", "tensorflow.python.ops.math_ops.reduce_sum", "tensorflow.python.framework.constant_op.constant" ], [ "tensorflow.python.ops.linalg.sparse.sparse_csr_matrix_ops.dense_to_csr_sparse_matrix", "numpy.logical_not", "tensorflow.python.ops.math_ops.abs", "tensorflow.python.ops.linalg.sparse.sparse_csr_matrix_ops.csr_sparse_matrix_to_sparse_tensor", "tensorflow.python.ops.gradients_impl.gradients", "tensorflow.python.ops.array_ops.zeros_like", "tensorflow.python.platform.tf_logging.info", "tensorflow.python.ops.linalg.sparse.sparse_csr_matrix_ops.csr_sparse_matrix_to_dense", "tensorflow.python.ops.array_ops.gather_nd", "tensorflow.python.platform.test.main", "numpy.random.randn", "tensorflow.python.framework.ops.convert_to_tensor", "numpy.float32", "tensorflow.python.ops.math_ops.cast", "tensorflow.python.ops.linalg.sparse.sparse_csr_matrix_ops.sparse_tensor_to_csr_sparse_matrix", "tensorflow.python.ops.linalg.sparse.sparse_csr_matrix_ops.sparse_matrix_add", "tensorflow.python.framework.test_util.is_gpu_available" ], [ "tensorflow.python.util.tf_decorator.unwrap", "tensorflow.python.tools.api.generator.doc_srcs.get_doc_sources" ], [ "numpy.matrix", "tensorflow.python.ops.parsing_ops.decode_raw", "tensorflow.python.framework.ops.Graph", "tensorflow.python.ops.array_ops.placeholder", "tensorflow.python.platform.test.main" ], [ "tensorflow.python.training.monitored_session.WorkerSessionCreator", "tensorflow.python.platform.tf_logging.warning", "tensorflow.python.training.monitored_session.ChiefSessionCreator", "tensorflow.python.platform.tf_logging.info", "tensorflow.python.training.server_lib.ClusterSpec", "tensorflow.python.client.session.Session", "tensorflow.python.training.server_lib.Server", "tensorflow.core.protobuf.config_pb2.ConfigProto" ], [ "tensorflow.python.framework.ops.device", "tensorflow.python.ops.data_flow_ops.SparseConditionalAccumulator", "tensorflow.python.training.session_manager._ready", "tensorflow.python.ops.variable_scope.variable", "tensorflow.python.ops.array_ops.fill", "tensorflow.python.ops.variables.global_variables", "tensorflow.python.ops.control_flow_ops.group", "tensorflow.python.training.queue_runner.QueueRunner", "tensorflow.python.platform.tf_logging.info", "tensorflow.python.util.tf_export.tf_export", "tensorflow.python.distribute.distribution_strategy_context.get_strategy", "tensorflow.python.framework.ops.name_scope", "tensorflow.python.ops.state_ops.assign", "tensorflow.python.ops.control_flow_ops.no_op", "tensorflow.python.framework.ops.control_dependencies", "tensorflow.python.ops.data_flow_ops.FIFOQueue", "tensorflow.python.util.deprecation.deprecated" ], [ "tensorflow.python.framework.tensor_shape.TensorShape", "tensorflow.python.ops.variable_scope.variable_creator_scope", "tensorflow.python.framework.ops.init_scope", "tensorflow.python.ops.init_ops.glorot_uniform_initializer", "tensorflow.python.ops.variables.VariableAggregationV2", "tensorflow.python.ops.init_ops.zeros_initializer", "tensorflow.python.keras.utils.tf_inspect.ismethod", "tensorflow.python.framework.dtypes.as_dtype", "tensorflow.python.ops.variables.VariableSynchronization", "tensorflow.python.ops.variables.Variable", "tensorflow.python.ops.variable_scope.with_variable_store", "tensorflow.python.keras.utils.tf_inspect.getargspec", "tensorflow.python.keras.utils.tf_inspect.isclass", "tensorflow.python.util.tf_decorator.unwrap", "tensorflow.python.eager.context.executing_eagerly", "tensorflow.python.keras.utils.tf_inspect.getfullargspec" ], [ "tensorflow.python.framework.errors_impl.DataLossError", "tensorflow.python.framework.errors_impl.InternalError", "tensorflow.python.util.compat.as_bytes", "tensorflow.python.util.tf_export.tf_export", "tensorflow.python.framework.errors_impl.UnimplementedError", "tensorflow.python.framework.errors_impl.NotFoundError", "tensorflow.python.framework.errors_impl.InvalidArgumentError", "tensorflow.python.framework.dtypes.DType", "tensorflow.python.framework.errors_impl.OpError" ], [ "tensorflow.python.grappler._pywrap_tf_cluster.TF_NewVirtualCluster", "tensorflow.core.grappler.costs.op_performance_data_pb2.OpPerformance.FromString", "tensorflow.python.grappler._pywrap_tf_cluster.TF_NewCluster", "tensorflow.python.grappler._pywrap_tf_cluster.TF_MeasureCosts", "tensorflow.python.grappler._pywrap_tf_cluster.TF_DeterminePeakMemoryUsage", "tensorflow.core.protobuf.device_properties_pb2.NamedDevice.FromString", "tensorflow.python.grappler._pywrap_tf_cluster.TF_GetSupportedDevices", "tensorflow.core.framework.step_stats_pb2.StepStats.FromString", "tensorflow.python.grappler._pywrap_tf_cluster.TF_ListAvailableOps", "tensorflow.python.grappler._pywrap_tf_cluster.TF_ListDevices", "tensorflow.python.grappler._pywrap_tf_cluster.TF_ShutdownCluster" ], [ "numpy.sqrt", "tensorflow.python.ops.math_ops.reduce_max", "tensorflow.python.ops.array_ops.placeholder", "numpy.mean", "numpy.var", "tensorflow.python.keras.legacy_tf_layers.normalization.batch_normalization", "tensorflow.python.ops.init_ops.constant_initializer", "numpy.square", "tensorflow.python.ops.math_ops.abs", "tensorflow.python.framework.test_util.run_v1_only", "tensorflow.python.framework.ops.get_collection", "numpy.reshape", "numpy.std", "tensorflow.python.ops.init_ops.ones_initializer", "tensorflow.python.platform.test.main", "tensorflow.python.ops.variable_scope.variable_scope", "tensorflow.python.framework.ops.control_dependencies", "numpy.zeros", "tensorflow.python.framework.ops.reset_default_graph", "tensorflow.python.ops.math_ops.reduce_sum", "tensorflow.python.ops.variables.global_variables", "tensorflow.python.platform.test.is_gpu_available", "numpy.random.rand", "tensorflow.python.keras.legacy_tf_layers.normalization.batch_norm", "tensorflow.python.training.gradient_descent.GradientDescentOptimizer", "numpy.random.random", "numpy.random.seed", "numpy.ones", "tensorflow.python.framework.ops.get_default_graph", "tensorflow.python.keras.legacy_tf_layers.normalization.BatchNormalization", "tensorflow.python.ops.variables.global_variables_initializer", "tensorflow.python.ops.random_ops.random_uniform", "tensorflow.python.training.saver.Saver" ], [ "tensorflow.python.util.tf_inspect.getmembers", "tensorflow.python.framework.ops._gradient_registry.lookup", "tensorflow.python.util.tf_export.get_canonical_name_for_symbol" ], [ "tensorflow.python.eager.context.executing_eagerly", "tensorflow.python.ops.bincount_ops.sparse_bincount", "numpy.random.random", "numpy.random.seed", "tensorflow.python.ops.ragged.ragged_factory_ops.constant", "numpy.ones", "tensorflow.python.ops.bincount_ops.bincount", "tensorflow.python.ops.gen_count_ops.RaggedCountSparseOutput", "tensorflow.python.framework.sparse_tensor.SparseTensor", "tensorflow.python.platform.test.main", "numpy.bincount", "tensorflow.python.ops.ragged.ragged_tensor.RaggedTensor.from_tensor", "tensorflow.python.framework.ops.device", "tensorflow.python.ops.gen_count_ops.SparseCountSparseOutput", "numpy.array", "numpy.zeros", "tensorflow.python.ops.sparse_ops.from_dense", "numpy.random.randint" ], [ "tensorflow.python.framework.test_util.run_v1_only", "tensorflow.python.ops.linalg_ops.norm", "numpy.linalg.norm", "tensorflow.python.ops.array_ops.placeholder", "tensorflow.python.platform.test.main", "numpy.random.randn", "numpy.floor", "numpy.isreal", "tensorflow.python.framework.constant_op.constant" ], [ "tensorflow.python.ops.math_ops.imag", "tensorflow.python.ops.array_ops.split", "tensorflow.python.ops.numpy_ops.np_utils.getitem", "tensorflow.python.ops.math_ops.reduce_any", "tensorflow.python.ops.math_ops.real", "tensorflow.python.ops.array_ops.fill", "tensorflow.python.ops.math_ops.divide", "tensorflow.python.ops.clip_ops.clip_by_value", "tensorflow.python.ops.array_ops.matrix_diag_part", "tensorflow.python.ops.numpy_ops.np_dtypes.default_float_type", "tensorflow.python.ops.math_ops.cumprod", "tensorflow.python.ops.numpy_ops.np_utils.np_doc", "tensorflow.python.ops.math_ops.equal", "tensorflow.python.ops.numpy_ops.np_utils.result_type", "numpy.array", "tensorflow.python.ops.math_ops.range", "tensorflow.python.ops.array_ops.reverse", "tensorflow.python.ops.array_ops.pad", "tensorflow.python.ops.linalg_ops.eye", "numpy.promote_types", "tensorflow.python.ops.array_ops.gather_nd", "tensorflow.python.ops.array_ops.size_v2", "numpy.iinfo", "tensorflow.python.ops.numpy_ops.np_utils.Link", "tensorflow.python.ops.array_ops.transpose", "tensorflow.python.ops.array_ops.tensor_strided_slice_update", "tensorflow.python.ops.numpy_ops.np_utils.greater", "tensorflow.python.ops.numpy_ops.np_utils.NoLink", "tensorflow.python.ops.math_ops.square", "tensorflow.python.framework.dtypes.as_dtype", "tensorflow.python.ops.numpy_ops.np_utils.get_static_value", "tensorflow.python.ops.array_ops.stack", "tensorflow.python.ops.numpy_ops.np_utils._result_type_binary", "tensorflow.python.ops.math_ops.floormod", "tensorflow.python.ops.array_ops.concat", "tensorflow.python.ops.numpy_ops.np_utils.subtract", "tensorflow.python.ops.array_ops.shape", "tensorflow.python.ops.array_ops.strided_slice", "tensorflow.python.ops.array_ops.tensor_scatter_update", "numpy.issubdtype", "tensorflow.python.ops.array_ops.broadcast_dynamic_shape", "tensorflow.python.ops.manip_ops.roll", "tensorflow.python.ops.array_ops.squeeze", "tensorflow.python.ops.math_ops.round", "tensorflow.python.ops.array_ops.identity", "tensorflow.python.ops.array_ops.gather", "tensorflow.python.ops.array_ops.size", "tensorflow.python.ops.array_ops.ones", "tensorflow.python.ops.array_ops.zeros_like", "tensorflow.python.ops.array_ops.repeat", "tensorflow.python.ops.math_ops.reduce_mean", "tensorflow.python.ops.array_ops.matrix_band_part", "tensorflow.python.ops.math_ops.conj", "tensorflow.python.ops.array_ops.broadcast_to", "tensorflow.python.ops.math_ops.cumsum", "tensorflow.python.ops.numpy_ops.np_export.np_export_constant", "tensorflow.python.ops.numpy_ops.np_utils.tf_broadcast", "tensorflow.python.ops.array_ops.reshape", "tensorflow.python.ops.array_ops.matrix_diag", "tensorflow.python.framework.ops.name_scope", "tensorflow.python.ops.math_ops.multiply", "tensorflow.python.ops.array_ops.where_v2", "tensorflow.python.ops.numpy_ops.np_arrays.convert_to_tensor", "tensorflow.python.ops.array_ops.zeros", "tensorflow.python.ops.numpy_ops.np_utils._canonicalize_axes", "tensorflow.python.ops.control_flow_ops.Assert", "tensorflow.python.ops.array_ops.rank", "tensorflow.python.ops.math_ops.reduce_all", "tensorflow.python.util.nest.map_structure", "tensorflow.python.ops.math_ops.cast", "tensorflow.python.ops.numpy_ops.np_utils.add", "tensorflow.python.ops.array_ops.ones_like", "tensorflow.python.ops.math_ops.sign", "numpy.prod", "tensorflow.python.ops.numpy_ops.np_utils.np_doc_only", "tensorflow.python.ops.array_ops.boolean_mask", "tensorflow.python.ops.array_ops.expand_dims", "tensorflow.python.ops.math_ops.reduce_sum", "tensorflow.python.framework.constant_op.constant" ], [ "tensorflow.python.ops.array_ops.shape", "tensorflow.python.ops.gen_stateless_random_ops_v2.stateless_truncated_normal_v2", "tensorflow.python.ops.variables.Variable", "tensorflow.python.distribute.distribution_strategy_context.has_strategy", "tensorflow.python.ops.array_ops.zeros", "tensorflow.python.eager.context.executing_eagerly", "tensorflow.python.distribute.values_util.mark_as_unsaveable", "tensorflow.python.distribute.values_util.is_saving_non_distributed", "tensorflow.python.distribute.distribution_strategy_context.enter_or_assert_strategy", "tensorflow.python.ops.array_ops.unstack", "tensorflow.python.util.tf_export.tf_export", "tensorflow.python.ops.math_ops.reduce_prod", "tensorflow.python.ops.array_ops.bitcast", "tensorflow.python.ops.math_ops.add", "tensorflow.python.util.nest.map_structure", "tensorflow.python.ops.gen_stateless_random_ops_v2.stateless_random_uniform_full_int_v2", "tensorflow.python.ops.stateless_random_ops.convert_alg_to_int", "tensorflow.python.ops.gen_stateless_random_ops_v2.stateless_random_uniform_int_v2", "tensorflow.python.ops.math_ops.cast", "tensorflow.python.distribute.distribution_strategy_context.in_cross_replica_context", "tensorflow.python.ops.gen_stateful_random_ops.non_deterministic_ints", "tensorflow.python.framework.ops.init_scope", "tensorflow.python.ops.array_ops.zeros_like", "tensorflow.python.ops.gen_stateful_random_ops.stateful_random_binomial", "tensorflow.python.framework.dtypes.as_dtype", "tensorflow.python.distribute.distribution_strategy_context.get_strategy", "tensorflow.python.framework.ops.convert_to_tensor", "tensorflow.python.distribute.distribution_strategy_context.get_replica_context", "tensorflow.python.ops.gen_stateless_random_ops_v2.stateless_random_normal_v2", "tensorflow.python.ops.array_ops.stack", "tensorflow.python.ops.array_ops.concat", "tensorflow.python.ops.gen_stateless_random_ops_v2.stateless_random_uniform_v2", "tensorflow.python.ops.array_ops.reshape", "tensorflow.python.framework.ops.name_scope", "tensorflow.python.ops.math_ops.maximum" ], [ "tensorflow.python.framework.tensor_util.MakeNdarray", "numpy.sqrt", "tensorflow.python.ops.array_ops.check_numerics_v2", "tensorflow.python.debug.lib.debug_events_reader.DebugEventsReader", "tensorflow.python.ops.math_ops.greater", "numpy.isneginf", "tensorflow.python.ops.math_ops.sqrt", "tensorflow.python.framework.ops.enable_eager_execution", "numpy.size", "tensorflow.python.ops.gen_debug_ops.debug_numeric_summary_v2", "tensorflow.python.platform.googletest.main", "numpy.ravel", "numpy.zeros", "numpy.power", "numpy.isnan", "tensorflow.python.ops.math_ops.square", "tensorflow.python.ops.math_ops.equal", "tensorflow.python.ops.gen_debug_ops.debug_identity_v2", "tensorflow.python.ops.math_ops.div", "tensorflow.python.debug.lib.debug_events_writer.DebugEventsWriter", "numpy.array", "tensorflow.python.framework.ops.Graph", "numpy.isposinf", "numpy.ones", "numpy.shape", "tensorflow.python.framework.constant_op.constant" ], [ "tensorflow.python.util.tf_export.tf_export", "tensorflow.python.util.deprecation.deprecated" ], [ "tensorflow.python.distribute.multi_process_lib.multiprocessing.Pipe", "tensorflow.python.distribute.multi_process_lib.test_main", "tensorflow.python.data.experimental.kernel_tests.service.test_base.TestWorker", "tensorflow.python.data.experimental.service.server_lib.DispatcherConfig", "tensorflow.python.platform.googletest.GetTempDir" ], [ "tensorflow.python.framework.test_util.disable_xla", "tensorflow.python.ops.array_ops.constant", "tensorflow.python.framework.ops.Graph", "numpy.ones", "tensorflow.python.ops.array_ops.placeholder", "tensorflow.python.platform.test.main", "tensorflow.python.ops.sparse_ops.sparse_to_dense", "numpy.array", "tensorflow.python.framework.test_util.is_gpu_available" ], [ "numpy.swapaxes", "tensorflow.python.framework.test_util.run_v1_only", "tensorflow.compiler.tests.xla_test.test.is_built_with_rocm", "numpy.eye", "tensorflow.python.framework.dtypes.as_dtype", "tensorflow.python.framework.test_util.disable_mlir_bridge", "tensorflow.python.platform.test.main", "tensorflow.python.ops.linalg_ops.matrix_triangular_solve", "tensorflow.python.framework.test_util.matmul_without_tf32", "numpy.triu", "numpy.random.RandomState", "numpy.zeros", "numpy.tril" ], [ "tensorflow.python.framework.tensor_shape.TensorShape", "tensorflow.python.util.compat.as_text", "tensorflow.python.keras.layers.preprocessing.table_utils.TableHandler", "tensorflow.python.keras.utils.tf_utils.is_ragged", "tensorflow.python.keras.backend.get_uid", "tensorflow.python.ops.array_ops.gather_nd", "tensorflow.python.platform.gfile.Exists", "tensorflow.python.ops.sparse_ops.sparse_expand_dims", "tensorflow.python.eager.context.executing_eagerly", "tensorflow.python.ops.array_ops.identity", "numpy.pad", "tensorflow.python.keras.backend.floatx", "tensorflow.python.ops.array_ops.size", "tensorflow.python.keras.layers.preprocessing.table_utils.find_repeated_tokens", "tensorflow.python.framework.ops.control_dependencies", "tensorflow.python.keras.layers.preprocessing.category_encoding.dense_bincount", "tensorflow.python.ops.math_ops.cast", "tensorflow.python.keras.engine.base_preprocessing_layer.convert_to_list", "tensorflow.python.platform.tf_logging.warning", "tensorflow.python.framework.tensor_util.is_tensor", "tensorflow.python.ops.lookup_ops.MutableHashTable", "tensorflow.python.ops.math_ops.equal", "tensorflow.python.keras.layers.preprocessing.category_encoding.sparse_bincount", "tensorflow.python.framework.dtypes.as_dtype", "numpy.int64", "tensorflow.python.ops.lookup_ops.StaticHashTable", "tensorflow.python.keras.utils.layer_utils.validate_string_arg", "numpy.array", "tensorflow.python.framework.tensor_spec.TensorSpec", "tensorflow.python.ops.string_ops.string_format", "numpy.int32", "tensorflow.python.util.compat.as_bytes", "tensorflow.python.ops.math_ops.multiply", "tensorflow.python.keras.saving.saved_model.layer_serialization.IndexLookupLayerSavedModelSaver", "tensorflow.python.keras.backend.set_value", "tensorflow.python.framework.ops.convert_to_tensor_v2_with_dispatch", "tensorflow.python.keras.layers.preprocessing.table_utils.num_tokens_in_file", "numpy.average", "tensorflow.python.ops.array_ops.expand_dims", "tensorflow.python.keras.utils.tf_utils.is_sparse" ], [ "tensorflow.python.data.ops.dataset_ops.Dataset.from_tensors", "tensorflow.python.framework.tensor_shape.TensorShape", "tensorflow.python.data.kernel_tests.test_base.default_test_combinations", "tensorflow.python.ops.array_ops.placeholder", "numpy.max", "tensorflow.python.data.kernel_tests.test_base.graph_only_combinations", "tensorflow.python.data.ops.dataset_ops.Dataset.range", "tensorflow.python.data.ops.dataset_ops.get_legacy_output_shapes", "numpy.random.randint", "tensorflow.python.framework.sparse_tensor.SparseTensorValue", "tensorflow.python.ops.array_ops.fill", "tensorflow.python.platform.test.main", "tensorflow.python.data.kernel_tests.checkpoint_test_base.default_test_combinations", "tensorflow.python.ops.math_ops.cast", "tensorflow.python.data.ops.dataset_ops.Dataset.from_tensor_slices", "numpy.array", "tensorflow.python.framework.combinations.combine", "tensorflow.python.ops.string_ops.as_string", "tensorflow.python.framework.constant_op.constant" ], [ "tensorflow.python.ops.array_ops.shape", "tensorflow.python.ops.bitwise_ops.right_shift", "tensorflow.compiler.tf2xla.ops.gen_xla_ops.xla_broadcast_helper", "tensorflow.python.ops.math_ops.tensordot", "tensorflow.python.ops.array_ops.transpose", "tensorflow.python.framework.ops.RegisterGradient", "tensorflow.compiler.tf2xla.ops.gen_xla_ops.xla_svd", "tensorflow.python.ops.array_ops.where", "tensorflow.python.framework.ops.no_gradient", "tensorflow.python.ops.math_ops.cast", "tensorflow.compiler.tf2xla.ops.gen_xla_ops.xla_sharding", "tensorflow.python.framework.ops.convert_to_tensor", "tensorflow.core.framework.attr_value_pb2.AttrValue", "tensorflow.python.ops.numpy_ops.np_utils.result_type", "tensorflow.python.ops.array_ops.broadcast_to", "tensorflow.compiler.tf2xla.ops.gen_xla_ops.xla_self_adjoint_eig", "tensorflow.compiler.tf2xla.ops.gen_xla_ops.xla_reduce_window", "tensorflow.python.ops.array_ops.reshape", "tensorflow.python.ops.random_ops.random_normal", "tensorflow.python.ops.random_ops.random_uniform", "tensorflow.python.framework.constant_op.constant" ], [ "tensorflow.python.keras.benchmarks.benchmark_util.generate_benchmark_params_cpu_gpu", "tensorflow.reduce_mean", "tensorflow.keras.layers.Conv2D", "tensorflow.ones", "tensorflow.test.main", "numpy.ones", "tensorflow.function", "tensorflow.keras.layers.LSTM", "numpy.random.randint", "tensorflow.keras.layers.LSTMCell", "tensorflow.GradientTape" ], [ "tensorflow.python.eager.context.executing_eagerly", "tensorflow.python.ops.linalg.linear_operator_test_util.add_tests", "tensorflow.python.ops.array_ops.concat", "tensorflow.python.ops.array_ops.shape", "tensorflow.python.ops.linalg.linear_operator_test_util.random_positive_definite_matrix", "tensorflow.python.ops.linalg.linear_operator_test_util.random_normal", "tensorflow.python.ops.linalg.linear_operator_util.broadcast_matrix_batch_dims", "tensorflow.python.ops.array_ops.zeros", "tensorflow.python.platform.test.main", "tensorflow.python.ops.array_ops.placeholder_with_default", "numpy.random.rand", "tensorflow.python.ops.linalg.linear_operator_test_util.random_tril_matrix", "tensorflow.python.ops.linalg.linear_operator_block_diag.LinearOperatorBlockDiag", "numpy.random.RandomState" ], [ "tensorflow.python.keras.initializers.RandomUniform", "tensorflow.python.keras.layers.Embedding", "tensorflow.python.keras.optimizer_v2.gradient_descent.SGD", "tensorflow.python.keras.layers.Dense", "tensorflow.python.keras.distribute.keras_correctness_test_base.multi_worker_mirrored_eager", "tensorflow.python.keras.Model", "tensorflow.python.keras.distribute.keras_correctness_test_base.test_combinations_for_embedding_model", "tensorflow.python.distribute.multi_process_runner.test_main", "tensorflow.python.keras.distribute.keras_correctness_test_base.MaybeDistributionScope", "tensorflow.python.keras.layers.Input", "numpy.zeros", "tensorflow.python.keras.layers.GlobalAveragePooling1D", "tensorflow.python.keras.layers.Dot" ], [ "numpy.right_shift", "tensorflow.python.ops.bitwise_ops.bitwise_or", "tensorflow.python.ops.bitwise_ops.bitwise_xor", "tensorflow.python.ops.bitwise_ops.right_shift", "tensorflow.python.platform.googletest.main", "tensorflow.python.ops.gen_bitwise_ops.population_count", "numpy.left_shift", "tensorflow.python.ops.bitwise_ops.bitwise_and", "tensorflow.python.ops.bitwise_ops.invert", "numpy.array", "tensorflow.python.ops.bitwise_ops.left_shift", "tensorflow.python.framework.constant_op.constant" ], [ "tensorflow.python.keras.applications.imagenet_utils.decode_predictions", "tensorflow.python.keras.backend.image_data_format", "tensorflow.python.keras.utils.data_utils.get_file", "tensorflow.python.keras.layers.VersionAwareLayers", "tensorflow.python.util.tf_export.keras_export", "tensorflow.python.keras.utils.layer_utils.get_source_inputs", "tensorflow.python.keras.backend.is_keras_tensor", "tensorflow.python.lib.io.file_io.file_exists_v2", "tensorflow.python.keras.applications.imagenet_utils.PREPROCESS_INPUT_DOC.format", "tensorflow.python.keras.applications.imagenet_utils.preprocess_input", "tensorflow.python.keras.applications.imagenet_utils.validate_activation", "tensorflow.python.keras.engine.training.Model" ], [ "tensorflow.python.framework.test_util.create_local_cluster", "tensorflow.python.eager.context.executing_eagerly", "tensorflow.python.util.tf_export.tf_export", "tensorflow.python.training.server_lib.Server", "tensorflow.python.eager.context.graph_mode", "tensorflow.python.util.deprecation.deprecated", "tensorflow.python.eager.context.eager_mode", "tensorflow.python.distribute.multi_process_runner.MultiProcessRunner", "tensorflow.python.training.coordinator.Coordinator", "tensorflow.python.training.server_lib.ClusterSpec", "tensorflow.python.client.session.Session", "tensorflow.python.distribute.multi_process_runner.manager", "tensorflow.python.framework.ops.Graph", "tensorflow.python.platform.tf_logging.info", "tensorflow.python.distribute.cluster_resolver.TFConfigClusterResolver", "tensorflow.python.eager.remote.connect_to_remote_host", "tensorflow.python.platform.test.mock.patch.object", "tensorflow.core.protobuf.config_pb2.ConfigProto", "tensorflow.python.util.nest.flatten" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "2.6", "2.3", "2.4", "2.9", "2.5", "2.8", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "2.7", "2.9", "2.5", "2.6", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "1.10", "1.12", "2.7", "2.6", "1.13", "2.3", "2.4", "2.9", "1.7", "2.5", "2.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "2.6", "2.2", "2.3", "2.4", "2.9", "2.5", "2.8", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "1.12", "2.6", "2.2", "1.13", "2.3", "2.4", "1.4", "2.9", "1.5", "1.7", "2.5", "0.12", "1.0", "2.8", "1.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.4", "2.5", "2.6", "2.7" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "1.12", "2.6", "2.2", "1.13", "2.3", "2.4", "1.4", "2.9", "1.5", "1.7", "2.5", "0.12", "1.0", "2.8", "1.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "2.7", "2.4", "2.9", "2.5", "2.6", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "2.6", "2.2", "2.3", "2.4", "2.9", "2.5", "2.8", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "1.10", "1.12", "2.7", "2.6", "1.13", "2.3", "2.4", "2.9", "2.5", "2.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "1.10", "1.12", "2.7", "2.6", "1.4", "1.13", "2.3", "2.4", "2.9", "1.5", "1.7", "2.5", "0.12", "1.0", "2.2", "1.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "1.10", "1.12", "2.7", "2.6", "1.4", "1.13", "2.3", "2.4", "2.9", "1.5", "1.7", "2.5", "0.12", "1.0", "2.2", "1.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "2.6", "2.4", "2.9", "2.5", "2.8", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.5", "1.7", "1.4" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "2.3", "2.4", "2.5", "2.6" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "1.12", "2.6", "2.2", "1.13", "2.3", "2.4", "2.9", "2.5", "2.8", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "2.6", "2.2", "2.3", "2.4", "2.9", "2.5", "2.8", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "2.6", "2.2", "1.13", "2.3", "2.4", "2.9", "2.5", "2.8", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "2.7", "2.4", "2.3", "2.9", "2.5", "2.6", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.9", "2.8", "2.7", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "2.7", "2.6", "2.4", "2.3", "2.9", "2.5", "2.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.5", "1.7", "1.4" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "2.7", "2.9", "2.6", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "2.6", "2.2", "2.3", "2.4", "2.9", "2.5", "2.8", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "2.6", "2.4", "2.9", "2.5", "2.8", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.6", "2.7" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "1.10", "1.12", "2.7", "2.6", "1.4", "1.13", "2.3", "2.4", "2.9", "1.5", "1.7", "2.5", "0.12", "1.0", "2.2", "1.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "2.7", "2.4", "2.3", "2.9", "2.5", "2.6", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "2.6", "2.4", "2.3", "2.5", "2.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "2.7", "2.6", "2.4", "2.3", "2.9", "2.5", "2.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.6", "2.3", "2.4", "2.5", "2.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "1.12", "2.6", "2.2", "1.13", "2.3", "2.4", "2.9", "1.5", "1.7", "2.5", "2.8", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "2.2", "2.3", "2.4", "2.5", "2.6" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "2.6", "1.4", "2.2", "2.3", "2.4", "2.9", "1.5", "1.7", "2.5", "0.12", "1.0", "2.8", "1.2", "2.10" ] } ]
datability-io/incubator-superset
[ "ebb799140a20964802c0b427d8687ee1b45679b3" ]
[ "superset/views/core.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# pylint: disable=C,R,W\nfrom datetime import datetime, timedelta\nimport inspect\nimport logging\nimport os\nimport re\nimport time\nimport traceback\nfrom urllib import parse\n\nfrom flask import (\n abort, flash, g, Markup, redirect, render_template, request, Response, url_for,\n)\nfrom flask_appbuilder import expose, SimpleFormView\nfrom flask_appbuilder.actions import action\nfrom flask_appbuilder.models.sqla.interface import SQLAInterface\nfrom flask_appbuilder.security.decorators import has_access, has_access_api\nfrom flask_babel import gettext as __\nfrom flask_babel import lazy_gettext as _\nimport pandas as pd\nimport simplejson as json\nimport sqlalchemy as sqla\nfrom sqlalchemy import and_, create_engine, MetaData, or_, update\nfrom sqlalchemy.engine.url import make_url\nfrom sqlalchemy.exc import IntegrityError\nfrom werkzeug.routing import BaseConverter\nfrom werkzeug.utils import secure_filename\n\nfrom superset import (\n app, appbuilder, cache, db, results_backend,\n security_manager, sql_lab, viz)\nfrom superset.connectors.connector_registry import ConnectorRegistry\nfrom superset.connectors.sqla.models import AnnotationDatasource, SqlaTable\nfrom superset.exceptions import SupersetException\nfrom superset.forms import CsvToDatabaseForm\nfrom superset.jinja_context import get_template_processor\nfrom superset.legacy import cast_form_data, update_time_range\nimport superset.models.core as models\nfrom superset.models.sql_lab import Query\nfrom superset.models.user_attributes import UserAttribute\nfrom superset.sql_parse import ParsedQuery\nfrom superset.utils import core as utils\nfrom superset.utils import dashboard_import_export\nfrom superset.utils.dates import now_as_float\nfrom .base import (\n api, BaseSupersetView,\n check_ownership,\n CsvResponse, data_payload_response, DeleteMixin, generate_download_headers,\n get_error_msg, handle_api_exception, json_error_response, json_success,\n SupersetFilter, SupersetModelView, YamlExportMixin,\n)\nfrom .utils import bootstrap_user_data\n\nconfig = app.config\nstats_logger = config.get('STATS_LOGGER')\nlog_this = models.Log.log_this\nDAR = models.DatasourceAccessRequest\nQueryStatus = utils.QueryStatus\n\n\nALL_DATASOURCE_ACCESS_ERR = __(\n 'This endpoint requires the `all_datasource_access` permission')\nDATASOURCE_MISSING_ERR = __('The data source seems to have been deleted')\nACCESS_REQUEST_MISSING_ERR = __(\n 'The access requests seem to have been deleted')\nUSER_MISSING_ERR = __('The user seems to have been deleted')\n\nFORM_DATA_KEY_BLACKLIST = []\nif not config.get('ENABLE_JAVASCRIPT_CONTROLS'):\n FORM_DATA_KEY_BLACKLIST = [\n 'js_tooltip',\n 'js_onclick_href',\n 'js_data_mutator',\n ]\n\n\ndef get_database_access_error_msg(database_name):\n return __('This view requires the database %(name)s or '\n '`all_datasource_access` permission', name=database_name)\n\n\ndef is_owner(obj, user):\n \"\"\" Check if user is owner of the slice \"\"\"\n return obj and user in obj.owners\n\n\nclass SliceFilter(SupersetFilter):\n def apply(self, query, func): # noqa\n if security_manager.all_datasource_access():\n return query\n perms = self.get_view_menus('datasource_access')\n # TODO(bogdan): add `schema_access` support here\n return query.filter(self.model.perm.in_(perms))\n\n\nclass DashboardFilter(SupersetFilter):\n\n \"\"\"List dashboards for which users have access to at least one slice or are owners\"\"\"\n\n def apply(self, query, func): # noqa\n if security_manager.all_datasource_access():\n return query\n Slice = models.Slice # noqa\n Dash = models.Dashboard # noqa\n User = security_manager.user_model\n # TODO(bogdan): add `schema_access` support here\n datasource_perms = self.get_view_menus('datasource_access')\n slice_ids_qry = (\n db.session\n .query(Slice.id)\n .filter(Slice.perm.in_(datasource_perms))\n )\n owner_ids_qry = (\n db.session\n .query(Dash.id)\n .join(Dash.owners)\n .filter(User.id == User.get_user_id())\n )\n query = query.filter(\n or_(Dash.id.in_(\n db.session.query(Dash.id)\n .distinct()\n .join(Dash.slices)\n .filter(Slice.id.in_(slice_ids_qry)),\n ), Dash.id.in_(owner_ids_qry)),\n )\n return query\n\n\nclass DatabaseView(SupersetModelView, DeleteMixin, YamlExportMixin): # noqa\n datamodel = SQLAInterface(models.Database)\n\n list_title = _('List Databases')\n show_title = _('Show Database')\n add_title = _('Add Database')\n edit_title = _('Edit Database')\n\n list_columns = [\n 'database_name', 'backend', 'allow_run_async',\n 'allow_dml', 'allow_csv_upload', 'expose_in_sqllab', 'creator', 'modified']\n order_columns = [\n 'database_name', 'allow_run_async', 'allow_dml',\n 'modified', 'allow_csv_upload', 'expose_in_sqllab',\n ]\n add_columns = [\n 'database_name', 'sqlalchemy_uri', 'cache_timeout', 'expose_in_sqllab',\n 'allow_run_async', 'allow_csv_upload',\n 'allow_ctas', 'allow_dml', 'force_ctas_schema', 'impersonate_user',\n 'allow_multi_schema_metadata_fetch', 'extra',\n ]\n search_exclude_columns = (\n 'password', 'tables', 'created_by', 'changed_by', 'queries',\n 'saved_queries')\n edit_columns = add_columns\n show_columns = [\n 'tables',\n 'cache_timeout',\n 'extra',\n 'database_name',\n 'sqlalchemy_uri',\n 'perm',\n 'created_by',\n 'created_on',\n 'changed_by',\n 'changed_on',\n ]\n add_template = 'superset/models/database/add.html'\n edit_template = 'superset/models/database/edit.html'\n base_order = ('changed_on', 'desc')\n description_columns = {\n 'sqlalchemy_uri': utils.markdown(\n 'Refer to the '\n '[SqlAlchemy docs]'\n '(http://docs.sqlalchemy.org/en/rel_1_2/core/engines.html#'\n 'database-urls) '\n 'for more information on how to structure your URI.', True),\n 'expose_in_sqllab': _('Expose this DB in SQL Lab'),\n 'allow_run_async': _(\n 'Operate the database in asynchronous mode, meaning '\n 'that the queries are executed on remote workers as opposed '\n 'to on the web server itself. '\n 'This assumes that you have a Celery worker setup as well '\n 'as a results backend. Refer to the installation docs '\n 'for more information.'),\n 'allow_ctas': _('Allow CREATE TABLE AS option in SQL Lab'),\n 'allow_dml': _(\n 'Allow users to run non-SELECT statements '\n '(UPDATE, DELETE, CREATE, ...) '\n 'in SQL Lab'),\n 'force_ctas_schema': _(\n 'When allowing CREATE TABLE AS option in SQL Lab, '\n 'this option forces the table to be created in this schema'),\n 'extra': utils.markdown(\n 'JSON string containing extra configuration elements.<br/>'\n '1. The ``engine_params`` object gets unpacked into the '\n '[sqlalchemy.create_engine]'\n '(http://docs.sqlalchemy.org/en/latest/core/engines.html#'\n 'sqlalchemy.create_engine) call, while the ``metadata_params`` '\n 'gets unpacked into the [sqlalchemy.MetaData]'\n '(http://docs.sqlalchemy.org/en/rel_1_0/core/metadata.html'\n '#sqlalchemy.schema.MetaData) call.<br/>'\n '2. The ``metadata_cache_timeout`` is a cache timeout setting '\n 'in seconds for metadata fetch of this database. Specify it as '\n '**\"metadata_cache_timeout\": {\"schema_cache_timeout\": 600, '\n '\"table_cache_timeout\": 600}**. '\n 'If unset, cache will not be enabled for the functionality. '\n 'A timeout of 0 indicates that the cache never expires.<br/>'\n '3. The ``schemas_allowed_for_csv_upload`` is a comma separated list '\n 'of schemas that CSVs are allowed to upload to. '\n 'Specify it as **\"schemas_allowed_for_csv_upload\": '\n '[\"public\", \"csv_upload\"]**. '\n 'If database flavor does not support schema or any schema is allowed '\n 'to be accessed, just leave the list empty', True),\n 'impersonate_user': _(\n 'If Presto, all the queries in SQL Lab are going to be executed as the '\n 'currently logged on user who must have permission to run them.<br/>'\n 'If Hive and hive.server2.enable.doAs is enabled, will run the queries as '\n 'service account, but impersonate the currently logged on user '\n 'via hive.server2.proxy.user property.'),\n 'allow_multi_schema_metadata_fetch': _(\n 'Allow SQL Lab to fetch a list of all tables and all views across '\n 'all database schemas. For large data warehouse with thousands of '\n 'tables, this can be expensive and put strain on the system.'),\n 'cache_timeout': _(\n 'Duration (in seconds) of the caching timeout for charts of this database. '\n 'A timeout of 0 indicates that the cache never expires. '\n 'Note this defaults to the global timeout if undefined.'),\n 'allow_csv_upload': _(\n 'If selected, please set the schemas allowed for csv upload in Extra.'),\n }\n label_columns = {\n 'expose_in_sqllab': _('Expose in SQL Lab'),\n 'allow_ctas': _('Allow CREATE TABLE AS'),\n 'allow_dml': _('Allow DML'),\n 'force_ctas_schema': _('CTAS Schema'),\n 'database_name': _('Database'),\n 'creator': _('Creator'),\n 'changed_on_': _('Last Changed'),\n 'sqlalchemy_uri': _('SQLAlchemy URI'),\n 'cache_timeout': _('Chart Cache Timeout'),\n 'extra': _('Extra'),\n 'allow_run_async': _('Asynchronous Query Execution'),\n 'impersonate_user': _('Impersonate the logged on user'),\n 'allow_csv_upload': _('Allow Csv Upload'),\n 'modified': _('Modified'),\n 'allow_multi_schema_metadata_fetch': _('Allow Multi Schema Metadata Fetch'),\n 'backend': _('Backend'),\n }\n\n def pre_add(self, db):\n self.check_extra(db)\n db.set_sqlalchemy_uri(db.sqlalchemy_uri)\n security_manager.merge_perm('database_access', db.perm)\n # adding a new database we always want to force refresh schema list\n for schema in db.all_schema_names():\n security_manager.merge_perm(\n 'schema_access', security_manager.get_schema_perm(db, schema))\n\n def pre_update(self, db):\n self.pre_add(db)\n\n def pre_delete(self, obj):\n if obj.tables:\n raise SupersetException(Markup(\n 'Cannot delete a database that has tables attached. '\n \"Here's the list of associated tables: \" +\n ', '.join('{}'.format(o) for o in obj.tables)))\n\n def _delete(self, pk):\n DeleteMixin._delete(self, pk)\n\n def check_extra(self, db):\n # this will check whether json.loads(extra) can succeed\n try:\n extra = db.get_extra()\n except Exception as e:\n raise Exception('Extra field cannot be decoded by JSON. {}'.format(str(e)))\n\n # this will check whether 'metadata_params' is configured correctly\n metadata_signature = inspect.signature(MetaData)\n for key in extra.get('metadata_params', {}):\n if key not in metadata_signature.parameters:\n raise Exception('The metadata_params in Extra field '\n 'is not configured correctly. The key '\n '{} is invalid.'.format(key))\n\n\nappbuilder.add_link(\n 'Import Dashboards',\n label=__('Import Dashboards'),\n href='/superset/import_dashboards',\n icon='fa-cloud-upload',\n category='Manage',\n category_label=__('Manage'),\n category_icon='fa-wrench')\n\n\nappbuilder.add_view(\n DatabaseView,\n 'Databases',\n label=__('Databases'),\n icon='fa-database',\n category='Sources',\n category_label=__('Sources'),\n category_icon='fa-database')\n\n\nclass DatabaseAsync(DatabaseView):\n list_columns = [\n 'id', 'database_name',\n 'expose_in_sqllab', 'allow_ctas', 'force_ctas_schema',\n 'allow_run_async', 'allow_dml',\n 'allow_multi_schema_metadata_fetch', 'allow_csv_upload',\n 'allows_subquery', 'backend',\n ]\n\n\nappbuilder.add_view_no_menu(DatabaseAsync)\n\n\nclass CsvToDatabaseView(SimpleFormView):\n form = CsvToDatabaseForm\n form_template = 'superset/form_view/csv_to_database_view/edit.html'\n form_title = _('CSV to Database configuration')\n add_columns = ['database', 'schema', 'table_name']\n\n def form_get(self, form):\n form.sep.data = ','\n form.header.data = 0\n form.mangle_dupe_cols.data = True\n form.skipinitialspace.data = False\n form.skip_blank_lines.data = True\n form.infer_datetime_format.data = True\n form.decimal.data = '.'\n form.if_exists.data = 'fail'\n\n def form_post(self, form):\n database = form.con.data\n schema_name = form.schema.data or ''\n\n if not self.is_schema_allowed(database, schema_name):\n message = _('Database \"{0}\" Schema \"{1}\" is not allowed for csv uploads. '\n 'Please contact Superset Admin'.format(database.database_name,\n schema_name))\n flash(message, 'danger')\n return redirect('/csvtodatabaseview/form')\n\n csv_file = form.csv_file.data\n form.csv_file.data.filename = secure_filename(form.csv_file.data.filename)\n csv_filename = form.csv_file.data.filename\n path = os.path.join(config['UPLOAD_FOLDER'], csv_filename)\n try:\n utils.ensure_path_exists(config['UPLOAD_FOLDER'])\n csv_file.save(path)\n table = SqlaTable(table_name=form.name.data)\n table.database = form.data.get('con')\n table.database_id = table.database.id\n table.database.db_engine_spec.create_table_from_csv(form, table)\n except Exception as e:\n try:\n os.remove(path)\n except OSError:\n pass\n message = 'Table name {} already exists. Please pick another'.format(\n form.name.data) if isinstance(e, IntegrityError) else e\n flash(\n message,\n 'danger')\n stats_logger.incr('failed_csv_upload')\n return redirect('/csvtodatabaseview/form')\n\n os.remove(path)\n # Go back to welcome page / splash screen\n db_name = table.database.database_name\n message = _('CSV file \"{0}\" uploaded to table \"{1}\" in '\n 'database \"{2}\"'.format(csv_filename,\n form.name.data,\n db_name))\n flash(message, 'info')\n stats_logger.incr('successful_csv_upload')\n return redirect('/tablemodelview/list/')\n\n def is_schema_allowed(self, database, schema):\n if not database.allow_csv_upload:\n return False\n schemas = database.get_schema_access_for_csv_upload()\n if schemas:\n return schema in schemas\n return (security_manager.database_access(database) or\n security_manager.all_datasource_access())\n\n\nappbuilder.add_view_no_menu(CsvToDatabaseView)\n\n\nclass DatabaseTablesAsync(DatabaseView):\n list_columns = ['id', 'all_table_names_in_database', 'all_schema_names']\n\n\nappbuilder.add_view_no_menu(DatabaseTablesAsync)\n\n\nif config.get('ENABLE_ACCESS_REQUEST'):\n class AccessRequestsModelView(SupersetModelView, DeleteMixin):\n datamodel = SQLAInterface(DAR)\n list_columns = [\n 'username', 'user_roles', 'datasource_link',\n 'roles_with_datasource', 'created_on']\n order_columns = ['created_on']\n base_order = ('changed_on', 'desc')\n label_columns = {\n 'username': _('User'),\n 'user_roles': _('User Roles'),\n 'database': _('Database URL'),\n 'datasource_link': _('Datasource'),\n 'roles_with_datasource': _('Roles to grant'),\n 'created_on': _('Created On'),\n }\n\n appbuilder.add_view(\n AccessRequestsModelView,\n 'Access requests',\n label=__('Access requests'),\n category='Security',\n category_label=__('Security'),\n icon='fa-table')\n\n\nclass SliceModelView(SupersetModelView, DeleteMixin): # noqa\n route_base = '/chart'\n datamodel = SQLAInterface(models.Slice)\n\n list_title = _('List Charts')\n show_title = _('Show Chart')\n add_title = _('Add Chart')\n edit_title = _('Edit Chart')\n\n can_add = False\n label_columns = {\n 'datasource_link': _('Datasource'),\n }\n search_columns = (\n 'slice_name', 'description', 'viz_type', 'datasource_name', 'owners',\n )\n list_columns = [\n 'slice_link', 'viz_type', 'datasource_link', 'creator', 'modified']\n order_columns = ['viz_type', 'datasource_link', 'modified']\n edit_columns = [\n 'slice_name', 'description', 'viz_type', 'owners', 'dashboards',\n 'params', 'cache_timeout']\n base_order = ('changed_on', 'desc')\n description_columns = {\n 'description': Markup(\n 'The content here can be displayed as widget headers in the '\n 'dashboard view. Supports '\n '<a href=\"https://daringfireball.net/projects/markdown/\"\">'\n 'markdown</a>'),\n 'params': _(\n 'These parameters are generated dynamically when clicking '\n 'the save or overwrite button in the explore view. This JSON '\n 'object is exposed here for reference and for power users who may '\n 'want to alter specific parameters.',\n ),\n 'cache_timeout': _(\n 'Duration (in seconds) of the caching timeout for this chart. '\n 'Note this defaults to the datasource/table timeout if undefined.'),\n }\n base_filters = [['id', SliceFilter, lambda: []]]\n label_columns = {\n 'cache_timeout': _('Cache Timeout'),\n 'creator': _('Creator'),\n 'dashboards': _('Dashboards'),\n 'datasource_link': _('Datasource'),\n 'description': _('Description'),\n 'modified': _('Last Modified'),\n 'owners': _('Owners'),\n 'params': _('Parameters'),\n 'slice_link': _('Chart'),\n 'slice_name': _('Name'),\n 'table': _('Table'),\n 'viz_type': _('Visualization Type'),\n }\n\n def pre_add(self, obj):\n utils.validate_json(obj.params)\n\n def pre_update(self, obj):\n utils.validate_json(obj.params)\n check_ownership(obj)\n\n def pre_delete(self, obj):\n check_ownership(obj)\n\n @expose('/add', methods=['GET', 'POST'])\n @has_access\n def add(self):\n datasources = ConnectorRegistry.get_all_datasources(db.session)\n datasources = [\n {'value': str(d.id) + '__' + d.type, 'label': repr(d)}\n for d in datasources\n ]\n return self.render_template(\n 'superset/add_slice.html',\n bootstrap_data=json.dumps({\n 'datasources': sorted(datasources, key=lambda d: d['label']),\n }),\n )\n\n\nappbuilder.add_view(\n SliceModelView,\n 'Charts',\n label=__('Charts'),\n icon='fa-bar-chart',\n category='',\n category_icon='')\n\n\nclass SliceAsync(SliceModelView): # noqa\n route_base = '/sliceasync'\n list_columns = [\n 'id', 'slice_link', 'viz_type', 'slice_name',\n 'creator', 'modified', 'icons']\n label_columns = {\n 'icons': ' ',\n 'slice_link': _('Chart'),\n }\n\n\nappbuilder.add_view_no_menu(SliceAsync)\n\n\nclass SliceAddView(SliceModelView): # noqa\n route_base = '/sliceaddview'\n list_columns = [\n 'id', 'slice_name', 'slice_url', 'edit_url', 'viz_type', 'params',\n 'description', 'description_markeddown', 'datasource_id', 'datasource_type',\n 'datasource_name_text', 'datasource_link',\n 'owners', 'modified', 'changed_on']\n\n\nappbuilder.add_view_no_menu(SliceAddView)\n\n\nclass DashboardModelView(SupersetModelView, DeleteMixin): # noqa\n route_base = '/dashboard'\n datamodel = SQLAInterface(models.Dashboard)\n\n list_title = _('List Dashboards')\n show_title = _('Show Dashboard')\n add_title = _('Add Dashboard')\n edit_title = _('Edit Dashboard')\n\n list_columns = ['dashboard_link', 'creator', 'modified']\n order_columns = ['modified']\n edit_columns = [\n 'dashboard_title', 'slug', 'owners', 'position_json', 'css',\n 'json_metadata']\n show_columns = edit_columns + ['table_names', 'slices']\n search_columns = ('dashboard_title', 'slug', 'owners')\n add_columns = edit_columns\n base_order = ('changed_on', 'desc')\n description_columns = {\n 'position_json': _(\n 'This json object describes the positioning of the widgets in '\n 'the dashboard. It is dynamically generated when adjusting '\n 'the widgets size and positions by using drag & drop in '\n 'the dashboard view'),\n 'css': _(\n 'The CSS for individual dashboards can be altered here, or '\n 'in the dashboard view where changes are immediately '\n 'visible'),\n 'slug': _('To get a readable URL for your dashboard'),\n 'json_metadata': _(\n 'This JSON object is generated dynamically when clicking '\n 'the save or overwrite button in the dashboard view. It '\n 'is exposed here for reference and for power users who may '\n 'want to alter specific parameters.'),\n 'owners': _('Owners is a list of users who can alter the dashboard.'),\n }\n base_filters = [['slice', DashboardFilter, lambda: []]]\n label_columns = {\n 'dashboard_link': _('Dashboard'),\n 'dashboard_title': _('Title'),\n 'slug': _('Slug'),\n 'slices': _('Charts'),\n 'owners': _('Owners'),\n 'creator': _('Creator'),\n 'modified': _('Modified'),\n 'position_json': _('Position JSON'),\n 'css': _('CSS'),\n 'json_metadata': _('JSON Metadata'),\n 'table_names': _('Underlying Tables'),\n }\n\n def pre_add(self, obj):\n obj.slug = obj.slug.strip() or None\n if obj.slug:\n obj.slug = obj.slug.replace(' ', '-')\n obj.slug = re.sub(r'[^\\w\\-]+', '', obj.slug)\n if g.user not in obj.owners:\n obj.owners.append(g.user)\n utils.validate_json(obj.json_metadata)\n utils.validate_json(obj.position_json)\n owners = [o for o in obj.owners]\n for slc in obj.slices:\n slc.owners = list(set(owners) | set(slc.owners))\n\n def pre_update(self, obj):\n check_ownership(obj)\n self.pre_add(obj)\n\n def pre_delete(self, obj):\n check_ownership(obj)\n\n @action('mulexport', __('Export'), __('Export dashboards?'), 'fa-database')\n def mulexport(self, items):\n if not isinstance(items, list):\n items = [items]\n ids = ''.join('&id={}'.format(d.id) for d in items)\n return redirect(\n '/dashboard/export_dashboards_form?{}'.format(ids[1:]))\n\n @log_this\n @has_access\n @expose('/export_dashboards_form')\n def download_dashboards(self):\n if request.args.get('action') == 'go':\n ids = request.args.getlist('id')\n return Response(\n models.Dashboard.export_dashboards(ids),\n headers=generate_download_headers('json'),\n mimetype='application/text')\n return self.render_template(\n 'superset/export_dashboards.html',\n dashboards_url='/dashboard/list',\n )\n\n\nappbuilder.add_view(\n DashboardModelView,\n 'Dashboards',\n label=__('Dashboards'),\n icon='fa-dashboard',\n category='',\n category_icon='')\n\n\nclass DashboardModelViewAsync(DashboardModelView): # noqa\n route_base = '/dashboardasync'\n list_columns = [\n 'id', 'dashboard_link', 'creator', 'modified', 'dashboard_title',\n 'changed_on', 'url', 'changed_by_name',\n ]\n label_columns = {\n 'dashboard_link': _('Dashboard'),\n 'dashboard_title': _('Title'),\n 'creator': _('Creator'),\n 'modified': _('Modified'),\n }\n\n\nappbuilder.add_view_no_menu(DashboardModelViewAsync)\n\n\nclass DashboardAddView(DashboardModelView): # noqa\n route_base = '/dashboardaddview'\n list_columns = [\n 'id', 'dashboard_link', 'creator', 'modified', 'dashboard_title',\n 'changed_on', 'url', 'changed_by_name',\n ]\n show_columns = list(set(DashboardModelView.edit_columns + list_columns))\n\n\nappbuilder.add_view_no_menu(DashboardAddView)\n\n\nclass LogModelView(SupersetModelView):\n datamodel = SQLAInterface(models.Log)\n\n list_title = _('List Log')\n show_title = _('Show Log')\n add_title = _('Add Log')\n edit_title = _('Edit Log')\n\n list_columns = ('user', 'action', 'dttm')\n edit_columns = ('user', 'action', 'dttm', 'json')\n base_order = ('dttm', 'desc')\n label_columns = {\n 'user': _('User'),\n 'action': _('Action'),\n 'dttm': _('dttm'),\n 'json': _('JSON'),\n }\n\n\nappbuilder.add_view(\n LogModelView,\n 'Action Log',\n label=__('Action Log'),\n category='Security',\n category_label=__('Security'),\n icon='fa-list-ol')\n\n\[email protected]('/health')\ndef health():\n return 'OK'\n\n\[email protected]('/healthcheck')\ndef healthcheck():\n return 'OK'\n\n\[email protected]('/ping')\ndef ping():\n return 'OK'\n\n\nclass KV(BaseSupersetView):\n\n \"\"\"Used for storing and retrieving key value pairs\"\"\"\n\n @log_this\n @has_access_api\n @expose('/store/', methods=['POST'])\n def store(self):\n try:\n value = request.form.get('data')\n obj = models.KeyValue(value=value)\n db.session.add(obj)\n db.session.commit()\n except Exception as e:\n return json_error_response(e)\n return Response(\n json.dumps({'id': obj.id}),\n status=200)\n\n @log_this\n @has_access_api\n @expose('/<key_id>/', methods=['GET'])\n def get_value(self, key_id):\n kv = None\n try:\n kv = db.session.query(models.KeyValue).filter_by(id=key_id).one()\n except Exception as e:\n return json_error_response(e)\n return Response(kv.value, status=200)\n\n\nappbuilder.add_view_no_menu(KV)\n\n\nclass R(BaseSupersetView):\n\n \"\"\"used for short urls\"\"\"\n\n @log_this\n @expose('/<url_id>')\n def index(self, url_id):\n url = db.session.query(models.Url).filter_by(id=url_id).first()\n if url and url.url:\n explore_url = '//superset/explore/?'\n if url.url.startswith(explore_url):\n explore_url += f'r={url_id}'\n return redirect(explore_url[1:])\n else:\n return redirect(url.url[1:])\n else:\n flash('URL to nowhere...', 'danger')\n return redirect('/')\n\n @log_this\n @has_access_api\n @expose('/shortner/', methods=['POST'])\n def shortner(self):\n url = request.form.get('data')\n obj = models.Url(url=url)\n db.session.add(obj)\n db.session.commit()\n return Response(\n '{scheme}://{request.headers[Host]}/r/{obj.id}'.format(\n scheme=request.scheme, request=request, obj=obj),\n mimetype='text/plain')\n\n\nappbuilder.add_view_no_menu(R)\n\n\nclass Superset(BaseSupersetView):\n \"\"\"The base views for Superset!\"\"\"\n @has_access_api\n @expose('/datasources/')\n def datasources(self):\n datasources = ConnectorRegistry.get_all_datasources(db.session)\n datasources = [o.short_data for o in datasources]\n datasources = sorted(datasources, key=lambda o: o['name'])\n return self.json_response(datasources)\n\n @has_access_api\n @expose('/override_role_permissions/', methods=['POST'])\n def override_role_permissions(self):\n \"\"\"Updates the role with the give datasource permissions.\n\n Permissions not in the request will be revoked. This endpoint should\n be available to admins only. Expects JSON in the format:\n {\n 'role_name': '{role_name}',\n 'database': [{\n 'datasource_type': '{table|druid}',\n 'name': '{database_name}',\n 'schema': [{\n 'name': '{schema_name}',\n 'datasources': ['{datasource name}, {datasource name}']\n }]\n }]\n }\n \"\"\"\n data = request.get_json(force=True)\n role_name = data['role_name']\n databases = data['database']\n\n db_ds_names = set()\n for dbs in databases:\n for schema in dbs['schema']:\n for ds_name in schema['datasources']:\n fullname = utils.get_datasource_full_name(\n dbs['name'], ds_name, schema=schema['name'])\n db_ds_names.add(fullname)\n\n existing_datasources = ConnectorRegistry.get_all_datasources(db.session)\n datasources = [\n d for d in existing_datasources if d.full_name in db_ds_names]\n role = security_manager.find_role(role_name)\n # remove all permissions\n role.permissions = []\n # grant permissions to the list of datasources\n granted_perms = []\n for datasource in datasources:\n view_menu_perm = security_manager.find_permission_view_menu(\n view_menu_name=datasource.perm,\n permission_name='datasource_access')\n # prevent creating empty permissions\n if view_menu_perm and view_menu_perm.view_menu:\n role.permissions.append(view_menu_perm)\n granted_perms.append(view_menu_perm.view_menu.name)\n db.session.commit()\n return self.json_response({\n 'granted': granted_perms,\n 'requested': list(db_ds_names),\n }, status=201)\n\n @log_this\n @has_access\n @expose('/request_access/')\n def request_access(self):\n datasources = set()\n dashboard_id = request.args.get('dashboard_id')\n if dashboard_id:\n dash = (\n db.session.query(models.Dashboard)\n .filter_by(id=int(dashboard_id))\n .one()\n )\n datasources |= dash.datasources\n datasource_id = request.args.get('datasource_id')\n datasource_type = request.args.get('datasource_type')\n if datasource_id:\n ds_class = ConnectorRegistry.sources.get(datasource_type)\n datasource = (\n db.session.query(ds_class)\n .filter_by(id=int(datasource_id))\n .one()\n )\n datasources.add(datasource)\n\n has_access = all(\n (\n datasource and security_manager.datasource_access(datasource)\n for datasource in datasources\n ))\n if has_access:\n return redirect('/superset/dashboard/{}'.format(dashboard_id))\n\n if request.args.get('action') == 'go':\n for datasource in datasources:\n access_request = DAR(\n datasource_id=datasource.id,\n datasource_type=datasource.type)\n db.session.add(access_request)\n db.session.commit()\n flash(__('Access was requested'), 'info')\n return redirect('/')\n\n return self.render_template(\n 'superset/request_access.html',\n datasources=datasources,\n datasource_names=', '.join([o.name for o in datasources]),\n )\n\n @log_this\n @has_access\n @expose('/approve')\n def approve(self):\n def clean_fulfilled_requests(session):\n for r in session.query(DAR).all():\n datasource = ConnectorRegistry.get_datasource(\n r.datasource_type, r.datasource_id, session)\n if not datasource or \\\n security_manager.datasource_access(datasource):\n # datasource does not exist anymore\n session.delete(r)\n session.commit()\n datasource_type = request.args.get('datasource_type')\n datasource_id = request.args.get('datasource_id')\n created_by_username = request.args.get('created_by')\n role_to_grant = request.args.get('role_to_grant')\n role_to_extend = request.args.get('role_to_extend')\n\n session = db.session\n datasource = ConnectorRegistry.get_datasource(\n datasource_type, datasource_id, session)\n\n if not datasource:\n flash(DATASOURCE_MISSING_ERR, 'alert')\n return json_error_response(DATASOURCE_MISSING_ERR)\n\n requested_by = security_manager.find_user(username=created_by_username)\n if not requested_by:\n flash(USER_MISSING_ERR, 'alert')\n return json_error_response(USER_MISSING_ERR)\n\n requests = (\n session.query(DAR)\n .filter(\n DAR.datasource_id == datasource_id,\n DAR.datasource_type == datasource_type,\n DAR.created_by_fk == requested_by.id)\n .all()\n )\n\n if not requests:\n flash(ACCESS_REQUEST_MISSING_ERR, 'alert')\n return json_error_response(ACCESS_REQUEST_MISSING_ERR)\n\n # check if you can approve\n if (\n security_manager.all_datasource_access() or\n check_ownership(datasource, raise_if_false=False)\n ):\n # can by done by admin only\n if role_to_grant:\n role = security_manager.find_role(role_to_grant)\n requested_by.roles.append(role)\n msg = __(\n '%(user)s was granted the role %(role)s that gives access '\n 'to the %(datasource)s',\n user=requested_by.username,\n role=role_to_grant,\n datasource=datasource.full_name)\n utils.notify_user_about_perm_udate(\n g.user, requested_by, role, datasource,\n 'email/role_granted.txt', app.config)\n flash(msg, 'info')\n\n if role_to_extend:\n perm_view = security_manager.find_permission_view_menu(\n 'email/datasource_access', datasource.perm)\n role = security_manager.find_role(role_to_extend)\n security_manager.add_permission_role(role, perm_view)\n msg = __('Role %(r)s was extended to provide the access to '\n 'the datasource %(ds)s', r=role_to_extend,\n ds=datasource.full_name)\n utils.notify_user_about_perm_udate(\n g.user, requested_by, role, datasource,\n 'email/role_extended.txt', app.config)\n flash(msg, 'info')\n clean_fulfilled_requests(session)\n else:\n flash(__('You have no permission to approve this request'),\n 'danger')\n return redirect('/accessrequestsmodelview/list/')\n for r in requests:\n session.delete(r)\n session.commit()\n return redirect('/accessrequestsmodelview/list/')\n\n def get_form_data(self, slice_id=None, use_slice_data=False):\n form_data = {}\n post_data = request.form.get('form_data')\n request_args_data = request.args.get('form_data')\n # Supporting POST\n if post_data:\n form_data.update(json.loads(post_data))\n # request params can overwrite post body\n if request_args_data:\n form_data.update(json.loads(request_args_data))\n\n url_id = request.args.get('r')\n if url_id:\n saved_url = db.session.query(models.Url).filter_by(id=url_id).first()\n if saved_url:\n url_str = parse.unquote_plus(\n saved_url.url.split('?')[1][10:], encoding='utf-8', errors=None)\n url_form_data = json.loads(url_str)\n # allow form_date in request override saved url\n url_form_data.update(form_data)\n form_data = url_form_data\n\n if request.args.get('viz_type'):\n # Converting old URLs\n form_data = cast_form_data(form_data)\n\n form_data = {\n k: v\n for k, v in form_data.items()\n if k not in FORM_DATA_KEY_BLACKLIST\n }\n\n # When a slice_id is present, load from DB and override\n # the form_data from the DB with the other form_data provided\n slice_id = form_data.get('slice_id') or slice_id\n slc = None\n\n # Check if form data only contains slice_id\n contains_only_slc_id = not any(key != 'slice_id' for key in form_data)\n\n # Include the slice_form_data if request from explore or slice calls\n # or if form_data only contains slice_id\n if slice_id and (use_slice_data or contains_only_slc_id):\n slc = db.session.query(models.Slice).filter_by(id=slice_id).one_or_none()\n if slc:\n slice_form_data = slc.form_data.copy()\n slice_form_data.update(form_data)\n form_data = slice_form_data\n\n update_time_range(form_data)\n\n return form_data, slc\n\n def get_viz(\n self,\n slice_id=None,\n form_data=None,\n datasource_type=None,\n datasource_id=None,\n force=False,\n ):\n if slice_id:\n slc = (\n db.session.query(models.Slice)\n .filter_by(id=slice_id)\n .one()\n )\n return slc.get_viz()\n else:\n viz_type = form_data.get('viz_type', 'table')\n datasource = ConnectorRegistry.get_datasource(\n datasource_type, datasource_id, db.session)\n viz_obj = viz.viz_types[viz_type](\n datasource,\n form_data=form_data,\n force=force,\n )\n return viz_obj\n\n @has_access\n @expose('/slice/<slice_id>/')\n def slice(self, slice_id):\n form_data, slc = self.get_form_data(slice_id, use_slice_data=True)\n if not slc:\n abort(404)\n endpoint = '/superset/explore/?form_data={}'.format(\n parse.quote(json.dumps(form_data)),\n )\n if request.args.get('standalone') == 'true':\n endpoint += '&standalone=true'\n return redirect(endpoint)\n\n def get_query_string_response(self, viz_obj):\n query = None\n try:\n query_obj = viz_obj.query_obj()\n if query_obj:\n query = viz_obj.datasource.get_query_str(query_obj)\n except Exception as e:\n logging.exception(e)\n return json_error_response(e)\n\n if query_obj and query_obj['prequeries']:\n query_obj['prequeries'].append(query)\n query = ';\\n\\n'.join(query_obj['prequeries'])\n if query:\n query += ';'\n else:\n query = 'No query.'\n\n return self.json_response({\n 'query': query,\n 'language': viz_obj.datasource.query_language,\n })\n\n def get_raw_results(self, viz_obj):\n return self.json_response({\n 'data': viz_obj.get_df().to_dict('records'),\n })\n\n def get_samples(self, viz_obj):\n return self.json_response({\n 'data': viz_obj.get_samples(),\n })\n\n def generate_json(\n self, datasource_type, datasource_id, form_data,\n csv=False, query=False, force=False, results=False,\n samples=False,\n ):\n viz_obj = self.get_viz(\n datasource_type=datasource_type,\n datasource_id=datasource_id,\n form_data=form_data,\n force=force,\n )\n security_manager.assert_datasource_permission(viz_obj.datasource)\n\n if csv:\n return CsvResponse(\n viz_obj.get_csv(),\n status=200,\n headers=generate_download_headers('csv'),\n mimetype='application/csv')\n\n if query:\n return self.get_query_string_response(viz_obj)\n\n if results:\n return self.get_raw_results(viz_obj)\n\n if samples:\n return self.get_samples(viz_obj)\n\n payload = viz_obj.get_payload()\n return data_payload_response(*viz_obj.payload_json_and_has_error(payload))\n\n @log_this\n @api\n @has_access_api\n @expose('/slice_json/<slice_id>')\n def slice_json(self, slice_id):\n form_data, slc = self.get_form_data(slice_id, use_slice_data=True)\n datasource_type = slc.datasource.type\n datasource_id = slc.datasource.id\n\n return self.generate_json(datasource_type=datasource_type,\n datasource_id=datasource_id,\n form_data=form_data)\n\n @log_this\n @api\n @has_access_api\n @expose('/annotation_json/<layer_id>')\n def annotation_json(self, layer_id):\n form_data = self.get_form_data()[0]\n form_data['layer_id'] = layer_id\n form_data['filters'] = [{'col': 'layer_id',\n 'op': '==',\n 'val': layer_id}]\n datasource = AnnotationDatasource()\n viz_obj = viz.viz_types['table'](\n datasource,\n form_data=form_data,\n force=False,\n )\n payload = viz_obj.get_payload()\n return data_payload_response(*viz_obj.payload_json_and_has_error(payload))\n\n @log_this\n @api\n @has_access_api\n @handle_api_exception\n @expose('/explore_json/<datasource_type>/<datasource_id>/', methods=['GET', 'POST'])\n @expose('/explore_json/', methods=['GET', 'POST'])\n def explore_json(self, datasource_type=None, datasource_id=None):\n \"\"\"Serves all request that GET or POST form_data\n\n This endpoint evolved to be the entry point of many different\n requests that GETs or POSTs a form_data.\n\n `self.generate_json` receives this input and returns different\n payloads based on the request args in the first block\n\n TODO: break into one endpoint for each return shape\"\"\"\n csv = request.args.get('csv') == 'true'\n query = request.args.get('query') == 'true'\n results = request.args.get('results') == 'true'\n samples = request.args.get('samples') == 'true'\n force = request.args.get('force') == 'true'\n\n form_data = self.get_form_data()[0]\n datasource_id, datasource_type = self.datasource_info(\n datasource_id, datasource_type, form_data)\n\n return self.generate_json(\n datasource_type=datasource_type,\n datasource_id=datasource_id,\n form_data=form_data,\n csv=csv,\n query=query,\n results=results,\n force=force,\n samples=samples,\n )\n\n @log_this\n @has_access\n @expose('/import_dashboards', methods=['GET', 'POST'])\n def import_dashboards(self):\n \"\"\"Overrides the dashboards using json instances from the file.\"\"\"\n f = request.files.get('file')\n if request.method == 'POST' and f:\n dashboard_import_export.import_dashboards(db.session, f.stream)\n return redirect('/dashboard/list/')\n return self.render_template('superset/import_dashboards.html')\n\n @log_this\n @has_access\n @expose('/explorev2/<datasource_type>/<datasource_id>/')\n def explorev2(self, datasource_type, datasource_id):\n \"\"\"Deprecated endpoint, here for backward compatibility of urls\"\"\"\n return redirect(url_for(\n 'Superset.explore',\n datasource_type=datasource_type,\n datasource_id=datasource_id,\n **request.args))\n\n @staticmethod\n def datasource_info(datasource_id, datasource_type, form_data):\n \"\"\"Compatibility layer for handling of datasource info\n\n datasource_id & datasource_type used to be passed in the URL\n directory, now they should come as part of the form_data,\n This function allows supporting both without duplicating code\"\"\"\n datasource = form_data.get('datasource', '')\n if '__' in datasource:\n datasource_id, datasource_type = datasource.split('__')\n # The case where the datasource has been deleted\n datasource_id = None if datasource_id == 'None' else datasource_id\n\n if not datasource_id:\n raise Exception(\n 'The datasource associated with this chart no longer exists')\n datasource_id = int(datasource_id)\n return datasource_id, datasource_type\n\n @log_this\n @has_access\n @expose('/explore/<datasource_type>/<datasource_id>/', methods=['GET', 'POST'])\n @expose('/explore/', methods=['GET', 'POST'])\n def explore(self, datasource_type=None, datasource_id=None):\n user_id = g.user.get_id() if g.user else None\n form_data, slc = self.get_form_data(use_slice_data=True)\n\n datasource_id, datasource_type = self.datasource_info(\n datasource_id, datasource_type, form_data)\n\n error_redirect = '/chart/list/'\n datasource = ConnectorRegistry.get_datasource(\n datasource_type, datasource_id, db.session)\n if not datasource:\n flash(DATASOURCE_MISSING_ERR, 'danger')\n return redirect(error_redirect)\n\n if config.get('ENABLE_ACCESS_REQUEST') and (\n not security_manager.datasource_access(datasource)\n ):\n flash(\n __(security_manager.get_datasource_access_error_msg(datasource)),\n 'danger')\n return redirect(\n 'superset/request_access/?'\n f'datasource_type={datasource_type}&'\n f'datasource_id={datasource_id}&')\n\n viz_type = form_data.get('viz_type')\n if not viz_type and datasource.default_endpoint:\n return redirect(datasource.default_endpoint)\n\n # slc perms\n slice_add_perm = security_manager.can_access('can_add', 'SliceModelView')\n slice_overwrite_perm = is_owner(slc, g.user)\n slice_download_perm = security_manager.can_access(\n 'can_download', 'SliceModelView')\n\n form_data['datasource'] = str(datasource_id) + '__' + datasource_type\n\n # On explore, merge legacy and extra filters into the form data\n utils.convert_legacy_filters_into_adhoc(form_data)\n utils.merge_extra_filters(form_data)\n\n # merge request url params\n if request.method == 'GET':\n utils.merge_request_params(form_data, request.args)\n\n # handle save or overwrite\n action = request.args.get('action')\n\n if action == 'overwrite' and not slice_overwrite_perm:\n return json_error_response(\n _('You don\\'t have the rights to ') + _('alter this ') + _('chart'),\n status=400)\n\n if action == 'saveas' and not slice_add_perm:\n return json_error_response(\n _('You don\\'t have the rights to ') + _('create a ') + _('chart'),\n status=400)\n\n if action in ('saveas', 'overwrite'):\n return self.save_or_overwrite_slice(\n request.args,\n slc, slice_add_perm,\n slice_overwrite_perm,\n slice_download_perm,\n datasource_id,\n datasource_type,\n datasource.name)\n\n standalone = request.args.get('standalone') == 'true'\n bootstrap_data = {\n 'can_add': slice_add_perm,\n 'can_download': slice_download_perm,\n 'can_overwrite': slice_overwrite_perm,\n 'datasource': datasource.data,\n 'form_data': form_data,\n 'datasource_id': datasource_id,\n 'datasource_type': datasource_type,\n 'slice': slc.data if slc else None,\n 'standalone': standalone,\n 'user_id': user_id,\n 'forced_height': request.args.get('height'),\n 'common': self.common_bootsrap_payload(),\n }\n table_name = datasource.table_name \\\n if datasource_type == 'table' \\\n else datasource.datasource_name\n if slc:\n title = slc.slice_name\n else:\n title = _('Explore - %(table)s', table=table_name)\n return self.render_template(\n 'superset/basic.html',\n bootstrap_data=json.dumps(bootstrap_data),\n entry='explore',\n title=title,\n standalone_mode=standalone)\n\n @api\n @handle_api_exception\n @has_access_api\n @expose('/filter/<datasource_type>/<datasource_id>/<column>/')\n def filter(self, datasource_type, datasource_id, column):\n \"\"\"\n Endpoint to retrieve values for specified column.\n\n :param datasource_type: Type of datasource e.g. table\n :param datasource_id: Datasource id\n :param column: Column name to retrieve values for\n :return:\n \"\"\"\n # TODO: Cache endpoint by user, datasource and column\n datasource = ConnectorRegistry.get_datasource(\n datasource_type, datasource_id, db.session)\n if not datasource:\n return json_error_response(DATASOURCE_MISSING_ERR)\n security_manager.assert_datasource_permission(datasource)\n payload = json.dumps(\n datasource.values_for_column(\n column,\n config.get('FILTER_SELECT_ROW_LIMIT', 10000),\n ),\n default=utils.json_int_dttm_ser)\n return json_success(payload)\n\n def save_or_overwrite_slice(\n self, args, slc, slice_add_perm, slice_overwrite_perm, slice_download_perm,\n datasource_id, datasource_type, datasource_name):\n \"\"\"Save or overwrite a slice\"\"\"\n slice_name = args.get('slice_name')\n action = args.get('action')\n form_data, _ = self.get_form_data()\n\n if action in ('saveas'):\n if 'slice_id' in form_data:\n form_data.pop('slice_id') # don't save old slice_id\n slc = models.Slice(owners=[g.user] if g.user else [])\n\n slc.params = json.dumps(form_data, indent=2, sort_keys=True)\n slc.datasource_name = datasource_name\n slc.viz_type = form_data['viz_type']\n slc.datasource_type = datasource_type\n slc.datasource_id = datasource_id\n slc.slice_name = slice_name\n\n if action in ('saveas') and slice_add_perm:\n self.save_slice(slc)\n elif action == 'overwrite' and slice_overwrite_perm:\n self.overwrite_slice(slc)\n\n # Adding slice to a dashboard if requested\n dash = None\n if request.args.get('add_to_dash') == 'existing':\n dash = (\n db.session.query(models.Dashboard)\n .filter_by(id=int(request.args.get('save_to_dashboard_id')))\n .one()\n )\n\n # check edit dashboard permissions\n dash_overwrite_perm = check_ownership(dash, raise_if_false=False)\n if not dash_overwrite_perm:\n return json_error_response(\n _('You don\\'t have the rights to ') + _('alter this ') +\n _('dashboard'),\n status=400)\n\n flash(\n 'Slice [{}] was added to dashboard [{}]'.format(\n slc.slice_name,\n dash.dashboard_title),\n 'info')\n elif request.args.get('add_to_dash') == 'new':\n # check create dashboard permissions\n dash_add_perm = security_manager.can_access('can_add', 'DashboardModelView')\n if not dash_add_perm:\n return json_error_response(\n _('You don\\'t have the rights to ') + _('create a ') + _('dashboard'),\n status=400)\n\n dash = models.Dashboard(\n dashboard_title=request.args.get('new_dashboard_name'),\n owners=[g.user] if g.user else [])\n flash(\n 'Dashboard [{}] just got created and slice [{}] was added '\n 'to it'.format(\n dash.dashboard_title,\n slc.slice_name),\n 'info')\n\n if dash and slc not in dash.slices:\n dash.slices.append(slc)\n db.session.commit()\n\n response = {\n 'can_add': slice_add_perm,\n 'can_download': slice_download_perm,\n 'can_overwrite': is_owner(slc, g.user),\n 'form_data': slc.form_data,\n 'slice': slc.data,\n }\n\n if request.args.get('goto_dash') == 'true':\n response.update({'dashboard': dash.url})\n\n return json_success(json.dumps(response))\n\n def save_slice(self, slc):\n session = db.session()\n msg = _('Chart [{}] has been saved').format(slc.slice_name)\n session.add(slc)\n session.commit()\n flash(msg, 'info')\n\n def overwrite_slice(self, slc):\n session = db.session()\n session.merge(slc)\n session.commit()\n msg = _('Chart [{}] has been overwritten').format(slc.slice_name)\n flash(msg, 'info')\n\n @api\n @has_access_api\n @expose('/checkbox/<model_view>/<id_>/<attr>/<value>', methods=['GET'])\n def checkbox(self, model_view, id_, attr, value):\n \"\"\"endpoint for checking/unchecking any boolean in a sqla model\"\"\"\n modelview_to_model = {\n '{}ColumnInlineView'.format(name.capitalize()): source.column_class\n for name, source in ConnectorRegistry.sources.items()\n }\n model = modelview_to_model[model_view]\n col = db.session.query(model).filter_by(id=id_).first()\n checked = value == 'true'\n if col:\n setattr(col, attr, checked)\n if checked:\n metrics = col.get_metrics().values()\n col.datasource.add_missing_metrics(metrics)\n db.session.commit()\n return json_success('OK')\n\n @api\n @has_access_api\n @expose('/schemas/<db_id>/')\n @expose('/schemas/<db_id>/<force_refresh>/')\n def schemas(self, db_id, force_refresh='false'):\n db_id = int(db_id)\n force_refresh = force_refresh.lower() == 'true'\n database = (\n db.session\n .query(models.Database)\n .filter_by(id=db_id)\n .one()\n )\n schemas = database.all_schema_names(cache=database.schema_cache_enabled,\n cache_timeout=database.schema_cache_timeout,\n force=force_refresh)\n schemas = security_manager.schemas_accessible_by_user(database, schemas)\n return Response(\n json.dumps({'schemas': schemas}),\n mimetype='application/json')\n\n @api\n @has_access_api\n @expose('/tables/<db_id>/<schema>/<substr>/')\n @expose('/tables/<db_id>/<schema>/<substr>/<force_refresh>/')\n def tables(self, db_id, schema, substr, force_refresh='false'):\n \"\"\"Endpoint to fetch the list of tables for given database\"\"\"\n db_id = int(db_id)\n force_refresh = force_refresh.lower() == 'true'\n schema = utils.js_string_to_python(schema)\n substr = utils.js_string_to_python(substr)\n database = db.session.query(models.Database).filter_by(id=db_id).one()\n\n if schema:\n table_names = database.all_table_names_in_schema(\n schema=schema, force=force_refresh,\n cache=database.table_cache_enabled,\n cache_timeout=database.table_cache_timeout)\n view_names = database.all_view_names_in_schema(\n schema=schema, force=force_refresh,\n cache=database.table_cache_enabled,\n cache_timeout=database.table_cache_timeout)\n else:\n table_names = database.all_table_names_in_database(\n cache=True, force=False, cache_timeout=24 * 60 * 60)\n view_names = database.all_view_names_in_database(\n cache=True, force=False, cache_timeout=24 * 60 * 60)\n table_names = security_manager.accessible_by_user(database, table_names, schema)\n view_names = security_manager.accessible_by_user(database, view_names, schema)\n\n if substr:\n table_names = [tn for tn in table_names if substr in tn]\n view_names = [vn for vn in view_names if substr in vn]\n\n max_items = config.get('MAX_TABLE_NAMES') or len(table_names)\n total_items = len(table_names) + len(view_names)\n max_tables = len(table_names)\n max_views = len(view_names)\n if total_items and substr:\n max_tables = max_items * len(table_names) // total_items\n max_views = max_items * len(view_names) // total_items\n\n table_options = [{'value': tn, 'label': tn}\n for tn in table_names[:max_tables]]\n table_options.extend([{'value': vn, 'label': '[view] {}'.format(vn)}\n for vn in view_names[:max_views]])\n payload = {\n 'tableLength': len(table_names) + len(view_names),\n 'options': table_options,\n }\n return json_success(json.dumps(payload))\n\n @api\n @has_access_api\n @expose('/copy_dash/<dashboard_id>/', methods=['GET', 'POST'])\n def copy_dash(self, dashboard_id):\n \"\"\"Copy dashboard\"\"\"\n session = db.session()\n data = json.loads(request.form.get('data'))\n dash = models.Dashboard()\n original_dash = (\n session\n .query(models.Dashboard)\n .filter_by(id=dashboard_id).first())\n\n dash.owners = [g.user] if g.user else []\n dash.dashboard_title = data['dashboard_title']\n\n if data['duplicate_slices']:\n # Duplicating slices as well, mapping old ids to new ones\n old_to_new_sliceids = {}\n for slc in original_dash.slices:\n new_slice = slc.clone()\n new_slice.owners = [g.user] if g.user else []\n session.add(new_slice)\n session.flush()\n new_slice.dashboards.append(dash)\n old_to_new_sliceids['{}'.format(slc.id)] = \\\n '{}'.format(new_slice.id)\n\n # update chartId of layout entities\n # in v2_dash positions json data, chartId should be integer,\n # while in older version slice_id is string type\n for value in data['positions'].values():\n if (\n isinstance(value, dict) and value.get('meta') and\n value.get('meta').get('chartId')\n ):\n old_id = '{}'.format(value.get('meta').get('chartId'))\n new_id = int(old_to_new_sliceids[old_id])\n value['meta']['chartId'] = new_id\n else:\n dash.slices = original_dash.slices\n dash.params = original_dash.params\n\n self._set_dash_metadata(dash, data)\n session.add(dash)\n session.commit()\n dash_json = json.dumps(dash.data)\n session.close()\n return json_success(dash_json)\n\n @api\n @has_access_api\n @expose('/save_dash/<dashboard_id>/', methods=['GET', 'POST'])\n def save_dash(self, dashboard_id):\n \"\"\"Save a dashboard's metadata\"\"\"\n session = db.session()\n dash = (session\n .query(models.Dashboard)\n .filter_by(id=dashboard_id).first())\n check_ownership(dash, raise_if_false=True)\n data = json.loads(request.form.get('data'))\n self._set_dash_metadata(dash, data)\n session.merge(dash)\n session.commit()\n session.close()\n return json_success(json.dumps({'status': 'SUCCESS'}))\n\n @staticmethod\n def _set_dash_metadata(dashboard, data):\n positions = data['positions']\n # find slices in the position data\n slice_ids = []\n slice_id_to_name = {}\n for value in positions.values():\n if (\n isinstance(value, dict) and value.get('meta') and\n value.get('meta').get('chartId')\n ):\n slice_id = value.get('meta').get('chartId')\n slice_ids.append(slice_id)\n slice_id_to_name[slice_id] = value.get('meta').get('sliceName')\n\n session = db.session()\n Slice = models.Slice # noqa\n current_slices = session.query(Slice).filter(\n Slice.id.in_(slice_ids)).all()\n\n dashboard.slices = current_slices\n\n # update slice names. this assumes user has permissions to update the slice\n for slc in dashboard.slices:\n new_name = slice_id_to_name[slc.id]\n if slc.slice_name != new_name:\n slc.slice_name = new_name\n session.merge(slc)\n session.flush()\n\n # remove leading and trailing white spaces in the dumped json\n dashboard.position_json = json.dumps(\n positions, indent=None, separators=(',', ':'), sort_keys=True)\n md = dashboard.params_dict\n dashboard.css = data.get('css')\n dashboard.dashboard_title = data['dashboard_title']\n\n if 'filter_immune_slices' not in md:\n md['filter_immune_slices'] = []\n if 'timed_refresh_immune_slices' not in md:\n md['timed_refresh_immune_slices'] = []\n if 'filter_immune_slice_fields' not in md:\n md['filter_immune_slice_fields'] = {}\n md['expanded_slices'] = data['expanded_slices']\n default_filters_data = json.loads(data.get('default_filters', '{}'))\n applicable_filters = \\\n {key: v for key, v in default_filters_data.items()\n if int(key) in slice_ids}\n md['default_filters'] = json.dumps(applicable_filters)\n dashboard.json_metadata = json.dumps(md)\n\n @api\n @has_access_api\n @expose('/add_slices/<dashboard_id>/', methods=['POST'])\n def add_slices(self, dashboard_id):\n \"\"\"Add and save slices to a dashboard\"\"\"\n data = json.loads(request.form.get('data'))\n session = db.session()\n Slice = models.Slice # noqa\n dash = (\n session.query(models.Dashboard).filter_by(id=dashboard_id).first())\n check_ownership(dash, raise_if_false=True)\n new_slices = session.query(Slice).filter(\n Slice.id.in_(data['slice_ids']))\n dash.slices += new_slices\n session.merge(dash)\n session.commit()\n session.close()\n return 'SLICES ADDED'\n\n @api\n @has_access_api\n @expose('/testconn', methods=['POST', 'GET'])\n def testconn(self):\n \"\"\"Tests a sqla connection\"\"\"\n try:\n username = g.user.username if g.user is not None else None\n uri = request.json.get('uri')\n db_name = request.json.get('name')\n impersonate_user = request.json.get('impersonate_user')\n database = None\n if db_name:\n database = (\n db.session\n .query(models.Database)\n .filter_by(database_name=db_name)\n .first()\n )\n if database and uri == database.safe_sqlalchemy_uri():\n # the password-masked uri was passed\n # use the URI associated with this database\n uri = database.sqlalchemy_uri_decrypted\n\n configuration = {}\n\n if database and uri:\n url = make_url(uri)\n db_engine = models.Database.get_db_engine_spec_for_backend(\n url.get_backend_name())\n db_engine.patch()\n\n masked_url = database.get_password_masked_url_from_uri(uri)\n logging.info('Superset.testconn(). Masked URL: {0}'.format(masked_url))\n\n configuration.update(\n db_engine.get_configuration_for_impersonation(uri,\n impersonate_user,\n username),\n )\n\n engine_params = (\n request.json\n .get('extras', {})\n .get('engine_params', {}))\n connect_args = engine_params.get('connect_args')\n\n if configuration:\n connect_args['configuration'] = configuration\n\n engine = create_engine(uri, **engine_params)\n engine.connect()\n return json_success(json.dumps(engine.table_names(), indent=4))\n except Exception as e:\n logging.exception(e)\n return json_error_response((\n 'Connection failed!\\n\\n'\n 'The error message returned was:\\n{}').format(e))\n\n @api\n @has_access_api\n @expose('/recent_activity/<user_id>/', methods=['GET'])\n def recent_activity(self, user_id):\n \"\"\"Recent activity (actions) for a given user\"\"\"\n M = models # noqa\n\n if request.args.get('limit'):\n limit = int(request.args.get('limit'))\n else:\n limit = 1000\n\n qry = (\n db.session.query(M.Log, M.Dashboard, M.Slice)\n .outerjoin(\n M.Dashboard,\n M.Dashboard.id == M.Log.dashboard_id,\n )\n .outerjoin(\n M.Slice,\n M.Slice.id == M.Log.slice_id,\n )\n .filter(\n sqla.and_(\n ~M.Log.action.in_(('queries', 'shortner', 'sql_json')),\n M.Log.user_id == user_id,\n ),\n )\n .order_by(M.Log.dttm.desc())\n .limit(limit)\n )\n payload = []\n for log in qry.all():\n item_url = None\n item_title = None\n if log.Dashboard:\n item_url = log.Dashboard.url\n item_title = log.Dashboard.dashboard_title\n elif log.Slice:\n item_url = log.Slice.slice_url\n item_title = log.Slice.slice_name\n\n payload.append({\n 'action': log.Log.action,\n 'item_url': item_url,\n 'item_title': item_title,\n 'time': log.Log.dttm,\n })\n return json_success(\n json.dumps(payload, default=utils.json_int_dttm_ser))\n\n @api\n @has_access_api\n @expose('/csrf_token/', methods=['GET'])\n def csrf_token(self):\n return Response(\n self.render_template('superset/csrf_token.json'),\n mimetype='text/json',\n )\n\n @api\n @has_access_api\n @expose('/fave_dashboards_by_username/<username>/', methods=['GET'])\n def fave_dashboards_by_username(self, username):\n \"\"\"This lets us use a user's username to pull favourite dashboards\"\"\"\n user = security_manager.find_user(username=username)\n return self.fave_dashboards(user.get_id())\n\n @api\n @has_access_api\n @expose('/fave_dashboards/<user_id>/', methods=['GET'])\n def fave_dashboards(self, user_id):\n qry = (\n db.session.query(\n models.Dashboard,\n models.FavStar.dttm,\n )\n .join(\n models.FavStar,\n sqla.and_(\n models.FavStar.user_id == int(user_id),\n models.FavStar.class_name == 'Dashboard',\n models.Dashboard.id == models.FavStar.obj_id,\n ),\n )\n .order_by(\n models.FavStar.dttm.desc(),\n )\n )\n payload = []\n for o in qry.all():\n d = {\n 'id': o.Dashboard.id,\n 'dashboard': o.Dashboard.dashboard_link(),\n 'title': o.Dashboard.dashboard_title,\n 'url': o.Dashboard.url,\n 'dttm': o.dttm,\n }\n if o.Dashboard.created_by:\n user = o.Dashboard.created_by\n d['creator'] = str(user)\n d['creator_url'] = '/superset/profile/{}/'.format(\n user.username)\n payload.append(d)\n return json_success(\n json.dumps(payload, default=utils.json_int_dttm_ser))\n\n @api\n @has_access_api\n @expose('/created_dashboards/<user_id>/', methods=['GET'])\n def created_dashboards(self, user_id):\n Dash = models.Dashboard # noqa\n qry = (\n db.session.query(\n Dash,\n )\n .filter(\n sqla.or_(\n Dash.created_by_fk == user_id,\n Dash.changed_by_fk == user_id,\n ),\n )\n .order_by(\n Dash.changed_on.desc(),\n )\n )\n payload = [{\n 'id': o.id,\n 'dashboard': o.dashboard_link(),\n 'title': o.dashboard_title,\n 'url': o.url,\n 'dttm': o.changed_on,\n } for o in qry.all()]\n return json_success(\n json.dumps(payload, default=utils.json_int_dttm_ser))\n\n @api\n @has_access_api\n @expose('/user_slices', methods=['GET'])\n @expose('/user_slices/<user_id>/', methods=['GET'])\n def user_slices(self, user_id=None):\n \"\"\"List of slices a user created, or faved\"\"\"\n if not user_id:\n user_id = g.user.id\n Slice = models.Slice # noqa\n FavStar = models.FavStar # noqa\n qry = (\n db.session.query(Slice,\n FavStar.dttm).join(\n models.FavStar,\n sqla.and_(\n models.FavStar.user_id == int(user_id),\n models.FavStar.class_name == 'slice',\n models.Slice.id == models.FavStar.obj_id,\n ),\n isouter=True).filter(\n sqla.or_(\n Slice.created_by_fk == user_id,\n Slice.changed_by_fk == user_id,\n FavStar.user_id == user_id,\n ),\n )\n .order_by(Slice.slice_name.asc())\n )\n payload = [{\n 'id': o.Slice.id,\n 'title': o.Slice.slice_name,\n 'url': o.Slice.slice_url,\n 'data': o.Slice.form_data,\n 'dttm': o.dttm if o.dttm else o.Slice.changed_on,\n 'viz_type': o.Slice.viz_type,\n } for o in qry.all()]\n return json_success(\n json.dumps(payload, default=utils.json_int_dttm_ser))\n\n @api\n @has_access_api\n @expose('/created_slices', methods=['GET'])\n @expose('/created_slices/<user_id>/', methods=['GET'])\n def created_slices(self, user_id=None):\n \"\"\"List of slices created by this user\"\"\"\n if not user_id:\n user_id = g.user.id\n Slice = models.Slice # noqa\n qry = (\n db.session.query(Slice)\n .filter(\n sqla.or_(\n Slice.created_by_fk == user_id,\n Slice.changed_by_fk == user_id,\n ),\n )\n .order_by(Slice.changed_on.desc())\n )\n payload = [{\n 'id': o.id,\n 'title': o.slice_name,\n 'url': o.slice_url,\n 'dttm': o.changed_on,\n 'viz_type': o.viz_type,\n } for o in qry.all()]\n return json_success(\n json.dumps(payload, default=utils.json_int_dttm_ser))\n\n @api\n @has_access_api\n @expose('/fave_slices', methods=['GET'])\n @expose('/fave_slices/<user_id>/', methods=['GET'])\n def fave_slices(self, user_id=None):\n \"\"\"Favorite slices for a user\"\"\"\n if not user_id:\n user_id = g.user.id\n qry = (\n db.session.query(\n models.Slice,\n models.FavStar.dttm,\n )\n .join(\n models.FavStar,\n sqla.and_(\n models.FavStar.user_id == int(user_id),\n models.FavStar.class_name == 'slice',\n models.Slice.id == models.FavStar.obj_id,\n ),\n )\n .order_by(\n models.FavStar.dttm.desc(),\n )\n )\n payload = []\n for o in qry.all():\n d = {\n 'id': o.Slice.id,\n 'title': o.Slice.slice_name,\n 'url': o.Slice.slice_url,\n 'dttm': o.dttm,\n 'viz_type': o.Slice.viz_type,\n }\n if o.Slice.created_by:\n user = o.Slice.created_by\n d['creator'] = str(user)\n d['creator_url'] = '/superset/profile/{}/'.format(\n user.username)\n payload.append(d)\n return json_success(\n json.dumps(payload, default=utils.json_int_dttm_ser))\n\n @api\n @has_access_api\n @expose('/warm_up_cache/', methods=['GET'])\n def warm_up_cache(self):\n \"\"\"Warms up the cache for the slice or table.\n\n Note for slices a force refresh occurs.\n \"\"\"\n slices = None\n session = db.session()\n slice_id = request.args.get('slice_id')\n table_name = request.args.get('table_name')\n db_name = request.args.get('db_name')\n\n if not slice_id and not (table_name and db_name):\n return json_error_response(__(\n 'Malformed request. slice_id or table_name and db_name '\n 'arguments are expected'), status=400)\n if slice_id:\n slices = session.query(models.Slice).filter_by(id=slice_id).all()\n if not slices:\n return json_error_response(__(\n 'Chart %(id)s not found', id=slice_id), status=404)\n elif table_name and db_name:\n SqlaTable = ConnectorRegistry.sources['table']\n table = (\n session.query(SqlaTable)\n .join(models.Database)\n .filter(\n models.Database.database_name == db_name or\n SqlaTable.table_name == table_name)\n ).first()\n if not table:\n return json_error_response(__(\n \"Table %(t)s wasn't found in the database %(d)s\",\n t=table_name, s=db_name), status=404)\n slices = session.query(models.Slice).filter_by(\n datasource_id=table.id,\n datasource_type=table.type).all()\n\n for slc in slices:\n try:\n form_data = self.get_form_data(slc.id, use_slice_data=True)[0]\n obj = self.get_viz(\n datasource_type=slc.datasource.type,\n datasource_id=slc.datasource.id,\n form_data=form_data,\n force=True,\n )\n obj.get_json()\n except Exception as e:\n return json_error_response(utils.error_msg_from_exception(e))\n return json_success(json.dumps(\n [{'slice_id': slc.id, 'slice_name': slc.slice_name}\n for slc in slices]))\n\n @has_access_api\n @expose('/favstar/<class_name>/<obj_id>/<action>/')\n def favstar(self, class_name, obj_id, action):\n \"\"\"Toggle favorite stars on Slices and Dashboard\"\"\"\n session = db.session()\n FavStar = models.FavStar # noqa\n count = 0\n favs = session.query(FavStar).filter_by(\n class_name=class_name, obj_id=obj_id,\n user_id=g.user.get_id()).all()\n if action == 'select':\n if not favs:\n session.add(\n FavStar(\n class_name=class_name,\n obj_id=obj_id,\n user_id=g.user.get_id(),\n dttm=datetime.now(),\n ),\n )\n count = 1\n elif action == 'unselect':\n for fav in favs:\n session.delete(fav)\n else:\n count = len(favs)\n session.commit()\n return json_success(json.dumps({'count': count}))\n\n @has_access\n @expose('/dashboard/<dashboard_id>/')\n def dashboard(self, dashboard_id):\n \"\"\"Server side rendering for a dashboard\"\"\"\n session = db.session()\n qry = session.query(models.Dashboard)\n if dashboard_id.isdigit():\n qry = qry.filter_by(id=int(dashboard_id))\n else:\n qry = qry.filter_by(slug=dashboard_id)\n\n dash = qry.one_or_none()\n if not dash:\n abort(404)\n datasources = set()\n for slc in dash.slices:\n datasource = slc.datasource\n if datasource:\n datasources.add(datasource)\n\n if config.get('ENABLE_ACCESS_REQUEST'):\n for datasource in datasources:\n if datasource and not security_manager.datasource_access(datasource):\n flash(\n __(security_manager.get_datasource_access_error_msg(datasource)),\n 'danger')\n return redirect(\n 'superset/request_access/?'\n f'dashboard_id={dash.id}&')\n\n dash_edit_perm = check_ownership(dash, raise_if_false=False) and \\\n security_manager.can_access('can_save_dash', 'Superset')\n dash_save_perm = security_manager.can_access('can_save_dash', 'Superset')\n superset_can_explore = security_manager.can_access('can_explore', 'Superset')\n slice_can_edit = security_manager.can_access('can_edit', 'SliceModelView')\n\n standalone_mode = request.args.get('standalone') == 'true'\n edit_mode = request.args.get('edit') == 'true'\n\n # Hack to log the dashboard_id properly, even when getting a slug\n @log_this\n def dashboard(**kwargs): # noqa\n pass\n dashboard(\n dashboard_id=dash.id,\n dashboard_version='v2',\n dash_edit_perm=dash_edit_perm,\n edit_mode=edit_mode)\n\n dashboard_data = dash.data\n dashboard_data.update({\n 'standalone_mode': standalone_mode,\n 'dash_save_perm': dash_save_perm,\n 'dash_edit_perm': dash_edit_perm,\n 'superset_can_explore': superset_can_explore,\n 'slice_can_edit': slice_can_edit,\n })\n\n bootstrap_data = {\n 'user_id': g.user.get_id(),\n 'dashboard_data': dashboard_data,\n 'datasources': {ds.uid: ds.data for ds in datasources},\n 'common': self.common_bootsrap_payload(),\n 'editMode': edit_mode,\n }\n\n if request.args.get('json') == 'true':\n return json_success(json.dumps(bootstrap_data))\n\n return self.render_template(\n 'superset/dashboard.html',\n entry='dashboard',\n standalone_mode=standalone_mode,\n title=dash.dashboard_title,\n bootstrap_data=json.dumps(bootstrap_data),\n )\n\n @api\n @log_this\n @expose('/log/', methods=['POST'])\n def log(self):\n return Response(status=200)\n\n @has_access\n @expose('/sync_druid/', methods=['POST'])\n @log_this\n def sync_druid_source(self):\n \"\"\"Syncs the druid datasource in main db with the provided config.\n\n The endpoint takes 3 arguments:\n user - user name to perform the operation as\n cluster - name of the druid cluster\n config - configuration stored in json that contains:\n name: druid datasource name\n dimensions: list of the dimensions, they become druid columns\n with the type STRING\n metrics_spec: list of metrics (dictionary). Metric consists of\n 2 attributes: type and name. Type can be count,\n etc. `count` type is stored internally as longSum\n other fields will be ignored.\n\n Example: {\n 'name': 'test_click',\n 'metrics_spec': [{'type': 'count', 'name': 'count'}],\n 'dimensions': ['affiliate_id', 'campaign', 'first_seen']\n }\n \"\"\"\n payload = request.get_json(force=True)\n druid_config = payload['config']\n user_name = payload['user']\n cluster_name = payload['cluster']\n\n user = security_manager.find_user(username=user_name)\n DruidDatasource = ConnectorRegistry.sources['druid']\n DruidCluster = DruidDatasource.cluster_class\n if not user:\n err_msg = __(\"Can't find User '%(name)s', please ask your admin \"\n 'to create one.', name=user_name)\n logging.error(err_msg)\n return json_error_response(err_msg)\n cluster = db.session.query(DruidCluster).filter_by(\n cluster_name=cluster_name).first()\n if not cluster:\n err_msg = __(\"Can't find DruidCluster with cluster_name = \"\n \"'%(name)s'\", name=cluster_name)\n logging.error(err_msg)\n return json_error_response(err_msg)\n try:\n DruidDatasource.sync_to_db_from_config(\n druid_config, user, cluster)\n except Exception as e:\n logging.exception(utils.error_msg_from_exception(e))\n return json_error_response(utils.error_msg_from_exception(e))\n return Response(status=201)\n\n @has_access\n @expose('/sqllab_viz/', methods=['POST'])\n @log_this\n def sqllab_viz(self):\n SqlaTable = ConnectorRegistry.sources['table']\n data = json.loads(request.form.get('data'))\n table_name = data.get('datasourceName')\n table = (\n db.session.query(SqlaTable)\n .filter_by(table_name=table_name)\n .first()\n )\n if not table:\n table = SqlaTable(table_name=table_name)\n table.database_id = data.get('dbId')\n table.schema = data.get('schema')\n table.template_params = data.get('templateParams')\n table.is_sqllab_view = True\n q = ParsedQuery(data.get('sql'))\n table.sql = q.stripped()\n db.session.add(table)\n cols = []\n for config in data.get('columns'):\n column_name = config.get('name')\n SqlaTable = ConnectorRegistry.sources['table']\n TableColumn = SqlaTable.column_class\n SqlMetric = SqlaTable.metric_class\n col = TableColumn(\n column_name=column_name,\n filterable=True,\n groupby=True,\n is_dttm=config.get('is_date', False),\n type=config.get('type', False),\n )\n cols.append(col)\n\n table.columns = cols\n table.metrics = [\n SqlMetric(metric_name='count', expression='count(*)'),\n ]\n db.session.commit()\n return self.json_response(json.dumps({\n 'table_id': table.id,\n }))\n\n @has_access\n @expose('/table/<database_id>/<path:table_name>/<schema>/')\n @log_this\n def table(self, database_id, table_name, schema):\n schema = utils.js_string_to_python(schema)\n table_name = parse.unquote_plus(table_name)\n mydb = db.session.query(models.Database).filter_by(id=database_id).one()\n payload_columns = []\n indexes = []\n primary_key = []\n foreign_keys = []\n try:\n columns = mydb.get_columns(table_name, schema)\n indexes = mydb.get_indexes(table_name, schema)\n primary_key = mydb.get_pk_constraint(table_name, schema)\n foreign_keys = mydb.get_foreign_keys(table_name, schema)\n except Exception as e:\n return json_error_response(utils.error_msg_from_exception(e))\n keys = []\n if primary_key and primary_key.get('constrained_columns'):\n primary_key['column_names'] = primary_key.pop('constrained_columns')\n primary_key['type'] = 'pk'\n keys += [primary_key]\n for fk in foreign_keys:\n fk['column_names'] = fk.pop('constrained_columns')\n fk['type'] = 'fk'\n keys += foreign_keys\n for idx in indexes:\n idx['type'] = 'index'\n keys += indexes\n\n for col in columns:\n dtype = ''\n try:\n dtype = '{}'.format(col['type'])\n except Exception:\n # sqla.types.JSON __str__ has a bug, so using __class__.\n dtype = col['type'].__class__.__name__\n pass\n payload_columns.append({\n 'name': col['name'],\n 'type': dtype.split('(')[0] if '(' in dtype else dtype,\n 'longType': dtype,\n 'keys': [\n k for k in keys\n if col['name'] in k.get('column_names')\n ],\n })\n tbl = {\n 'name': table_name,\n 'columns': payload_columns,\n 'selectStar': mydb.select_star(\n table_name, schema=schema, show_cols=True, indent=True,\n cols=columns, latest_partition=True),\n 'primaryKey': primary_key,\n 'foreignKeys': foreign_keys,\n 'indexes': keys,\n }\n return json_success(json.dumps(tbl))\n\n @has_access\n @expose('/extra_table_metadata/<database_id>/<path:table_name>/<schema>/')\n @log_this\n def extra_table_metadata(self, database_id, table_name, schema):\n schema = utils.js_string_to_python(schema)\n table_name = parse.unquote_plus(table_name)\n mydb = db.session.query(models.Database).filter_by(id=database_id).one()\n payload = mydb.db_engine_spec.extra_table_metadata(\n mydb, table_name, schema)\n return json_success(json.dumps(payload))\n\n @has_access\n @expose('/select_star/<database_id>/<table_name>')\n @expose('/select_star/<database_id>/<table_name>/<schema>')\n @log_this\n def select_star(self, database_id, table_name, schema=None):\n mydb = db.session.query(\n models.Database).filter_by(id=database_id).first()\n return json_success(\n mydb.select_star(\n table_name,\n schema,\n latest_partition=True,\n show_cols=True,\n ),\n )\n\n @expose('/theme/')\n def theme(self):\n return self.render_template('superset/theme.html')\n\n @has_access_api\n @expose('/cached_key/<key>/')\n @log_this\n def cached_key(self, key):\n \"\"\"Returns a key from the cache\"\"\"\n resp = cache.get(key)\n if resp:\n return resp\n return 'nope'\n\n @has_access_api\n @expose('/cache_key_exist/<key>/')\n @log_this\n def cache_key_exist(self, key):\n \"\"\"Returns if a key from cache exist\"\"\"\n key_exist = True if cache.get(key) else False\n status = 200 if key_exist else 404\n return json_success(json.dumps({'key_exist': key_exist}),\n status=status)\n\n @has_access_api\n @expose('/results/<key>/')\n @log_this\n def results(self, key):\n \"\"\"Serves a key off of the results backend\"\"\"\n if not results_backend:\n return json_error_response(\"Results backend isn't configured\")\n\n read_from_results_backend_start = now_as_float()\n blob = results_backend.get(key)\n stats_logger.timing(\n 'sqllab.query.results_backend_read',\n now_as_float() - read_from_results_backend_start,\n )\n if not blob:\n return json_error_response(\n 'Data could not be retrieved. '\n 'You may want to re-run the query.',\n status=410,\n )\n\n query = db.session.query(Query).filter_by(results_key=key).one()\n rejected_tables = security_manager.rejected_datasources(\n query.sql, query.database, query.schema)\n if rejected_tables:\n return json_error_response(security_manager.get_table_access_error_msg(\n '{}'.format(rejected_tables)), status=403)\n\n payload = utils.zlib_decompress_to_string(blob)\n display_limit = app.config.get('DEFAULT_SQLLAB_LIMIT', None)\n if display_limit:\n payload_json = json.loads(payload)\n payload_json['data'] = payload_json['data'][:display_limit]\n return json_success(\n json.dumps(\n payload_json,\n default=utils.json_iso_dttm_ser,\n ignore_nan=True,\n ),\n )\n\n @has_access_api\n @expose('/stop_query/', methods=['POST'])\n @log_this\n def stop_query(self):\n client_id = request.form.get('client_id')\n try:\n query = (\n db.session.query(Query)\n .filter_by(client_id=client_id).one()\n )\n query.status = QueryStatus.STOPPED\n db.session.commit()\n except Exception:\n pass\n return self.json_response('OK')\n\n @has_access_api\n @expose('/sql_json/', methods=['POST', 'GET'])\n @log_this\n def sql_json(self):\n \"\"\"Runs arbitrary sql and returns and json\"\"\"\n async_ = request.form.get('runAsync') == 'true'\n sql = request.form.get('sql')\n database_id = request.form.get('database_id')\n schema = request.form.get('schema') or None\n template_params = json.loads(\n request.form.get('templateParams') or '{}')\n limit = int(request.form.get('queryLimit', 0))\n if limit < 0:\n logging.warning(\n 'Invalid limit of {} specified. Defaulting to max limit.'.format(limit))\n limit = 0\n limit = limit or app.config.get('SQL_MAX_ROW')\n\n session = db.session()\n mydb = session.query(models.Database).filter_by(id=database_id).first()\n\n if not mydb:\n json_error_response(\n 'Database with id {} is missing.'.format(database_id))\n\n rejected_tables = security_manager.rejected_datasources(sql, mydb, schema)\n if rejected_tables:\n return json_error_response(\n security_manager.get_table_access_error_msg(rejected_tables),\n link=security_manager.get_table_access_link(rejected_tables),\n status=403)\n session.commit()\n\n select_as_cta = request.form.get('select_as_cta') == 'true'\n tmp_table_name = request.form.get('tmp_table_name')\n if select_as_cta and mydb.force_ctas_schema:\n tmp_table_name = '{}.{}'.format(\n mydb.force_ctas_schema,\n tmp_table_name,\n )\n\n client_id = request.form.get('client_id') or utils.shortid()[:10]\n limits = [mydb.db_engine_spec.get_limit_from_sql(sql), limit]\n query = Query(\n database_id=int(database_id),\n limit=min(lim for lim in limits if lim is not None),\n sql=sql,\n schema=schema,\n select_as_cta=request.form.get('select_as_cta') == 'true',\n start_time=now_as_float(),\n tab_name=request.form.get('tab'),\n status=QueryStatus.PENDING if async_ else QueryStatus.RUNNING,\n sql_editor_id=request.form.get('sql_editor_id'),\n tmp_table_name=tmp_table_name,\n user_id=g.user.get_id() if g.user else None,\n client_id=client_id,\n )\n session.add(query)\n session.flush()\n query_id = query.id\n session.commit() # shouldn't be necessary\n if not query_id:\n raise Exception(_('Query record was not created as expected.'))\n logging.info('Triggering query_id: {}'.format(query_id))\n\n try:\n template_processor = get_template_processor(\n database=query.database, query=query)\n rendered_query = template_processor.process_template(\n query.sql,\n **template_params)\n except Exception as e:\n return json_error_response(\n 'Template rendering failed: {}'.format(utils.error_msg_from_exception(e)))\n\n # Async request.\n if async_:\n logging.info('Running query on a Celery worker')\n # Ignore the celery future object and the request may time out.\n try:\n sql_lab.get_sql_results.delay(\n query_id,\n rendered_query,\n return_results=False,\n store_results=not query.select_as_cta,\n user_name=g.user.username if g.user else None,\n start_time=now_as_float())\n except Exception as e:\n logging.exception(e)\n msg = _(\n 'Failed to start remote query on a worker. '\n 'Tell your administrator to verify the availability of '\n 'the message queue.')\n query.status = QueryStatus.FAILED\n query.error_message = msg\n session.commit()\n return json_error_response('{}'.format(msg))\n\n resp = json_success(json.dumps(\n {'query': query.to_dict()}, default=utils.json_int_dttm_ser,\n ignore_nan=True), status=202)\n session.commit()\n return resp\n\n # Sync request.\n try:\n timeout = config.get('SQLLAB_TIMEOUT')\n timeout_msg = (\n f'The query exceeded the {timeout} seconds timeout.')\n with utils.timeout(seconds=timeout,\n error_message=timeout_msg):\n # pylint: disable=no-value-for-parameter\n data = sql_lab.get_sql_results(\n query_id,\n rendered_query,\n return_results=True,\n user_name=g.user.username if g.user else None)\n payload = json.dumps(\n data,\n default=utils.pessimistic_json_iso_dttm_ser,\n ignore_nan=True,\n encoding=None,\n )\n except Exception as e:\n logging.exception(e)\n return json_error_response('{}'.format(e))\n if data.get('status') == QueryStatus.FAILED:\n return json_error_response(payload=data)\n return json_success(payload)\n\n @has_access\n @expose('/csv/<client_id>')\n @log_this\n def csv(self, client_id):\n \"\"\"Download the query results as csv.\"\"\"\n logging.info('Exporting CSV file [{}]'.format(client_id))\n query = (\n db.session.query(Query)\n .filter_by(client_id=client_id)\n .one()\n )\n\n rejected_tables = security_manager.rejected_datasources(\n query.sql, query.database, query.schema)\n if rejected_tables:\n flash(\n security_manager.get_table_access_error_msg('{}'.format(rejected_tables)))\n return redirect('/')\n blob = None\n if results_backend and query.results_key:\n logging.info(\n 'Fetching CSV from results backend '\n '[{}]'.format(query.results_key))\n blob = results_backend.get(query.results_key)\n if blob:\n logging.info('Decompressing')\n json_payload = utils.zlib_decompress_to_string(blob)\n obj = json.loads(json_payload)\n columns = [c['name'] for c in obj['columns']]\n df = pd.DataFrame.from_records(obj['data'], columns=columns)\n logging.info('Using pandas to convert to CSV')\n csv = df.to_csv(index=False, **config.get('CSV_EXPORT'))\n else:\n logging.info('Running a query to turn into CSV')\n sql = query.select_sql or query.executed_sql\n df = query.database.get_df(sql, query.schema)\n # TODO(bkyryliuk): add compression=gzip for big files.\n csv = df.to_csv(index=False, **config.get('CSV_EXPORT'))\n response = Response(csv, mimetype='text/csv')\n response.headers['Content-Disposition'] = f'attachment; filename={query.name}.csv'\n logging.info('Ready to return response')\n return response\n\n @api\n @handle_api_exception\n @has_access\n @expose('/fetch_datasource_metadata')\n @log_this\n def fetch_datasource_metadata(self):\n datasource_id, datasource_type = (\n request.args.get('datasourceKey').split('__'))\n datasource = ConnectorRegistry.get_datasource(\n datasource_type, datasource_id, db.session)\n # Check if datasource exists\n if not datasource:\n return json_error_response(DATASOURCE_MISSING_ERR)\n\n # Check permission for datasource\n security_manager.assert_datasource_permission(datasource)\n return json_success(json.dumps(datasource.data))\n\n @has_access_api\n @expose('/queries/<last_updated_ms>')\n def queries(self, last_updated_ms):\n \"\"\"Get the updated queries.\"\"\"\n stats_logger.incr('queries')\n if not g.user.get_id():\n return json_error_response(\n 'Please login to access the queries.', status=403)\n\n # Unix time, milliseconds.\n last_updated_ms_int = int(float(last_updated_ms)) if last_updated_ms else 0\n\n # UTC date time, same that is stored in the DB.\n last_updated_dt = utils.EPOCH + timedelta(seconds=last_updated_ms_int / 1000)\n\n sql_queries = (\n db.session.query(Query)\n .filter(\n Query.user_id == g.user.get_id(),\n Query.changed_on >= last_updated_dt,\n )\n .all()\n )\n dict_queries = {q.client_id: q.to_dict() for q in sql_queries}\n\n now = int(round(time.time() * 1000))\n\n unfinished_states = [\n QueryStatus.PENDING,\n QueryStatus.RUNNING,\n ]\n\n queries_to_timeout = [\n client_id for client_id, query_dict in dict_queries.items()\n if (\n query_dict['state'] in unfinished_states and (\n now - query_dict['startDttm'] >\n config.get('SQLLAB_ASYNC_TIME_LIMIT_SEC') * 1000\n )\n )\n ]\n\n if queries_to_timeout:\n update(Query).where(\n and_(\n Query.user_id == g.user.get_id(),\n Query.client_id in queries_to_timeout,\n ),\n ).values(state=QueryStatus.TIMED_OUT)\n\n for client_id in queries_to_timeout:\n dict_queries[client_id]['status'] = QueryStatus.TIMED_OUT\n\n return json_success(\n json.dumps(dict_queries, default=utils.json_int_dttm_ser))\n\n @has_access\n @expose('/search_queries')\n @log_this\n def search_queries(self):\n \"\"\"Search for queries.\"\"\"\n query = db.session.query(Query)\n search_user_id = request.args.get('user_id')\n database_id = request.args.get('database_id')\n search_text = request.args.get('search_text')\n status = request.args.get('status')\n # From and To time stamp should be Epoch timestamp in seconds\n from_time = request.args.get('from')\n to_time = request.args.get('to')\n\n if search_user_id:\n # Filter on db Id\n query = query.filter(Query.user_id == search_user_id)\n\n if database_id:\n # Filter on db Id\n query = query.filter(Query.database_id == database_id)\n\n if status:\n # Filter on status\n query = query.filter(Query.status == status)\n\n if search_text:\n # Filter on search text\n query = query \\\n .filter(Query.sql.like('%{}%'.format(search_text)))\n\n if from_time:\n query = query.filter(Query.start_time > int(from_time))\n\n if to_time:\n query = query.filter(Query.start_time < int(to_time))\n\n query_limit = config.get('QUERY_SEARCH_LIMIT', 1000)\n sql_queries = (\n query.order_by(Query.start_time.asc())\n .limit(query_limit)\n .all()\n )\n\n dict_queries = [q.to_dict() for q in sql_queries]\n\n return Response(\n json.dumps(dict_queries, default=utils.json_int_dttm_ser),\n status=200,\n mimetype='application/json')\n\n @app.errorhandler(500)\n def show_traceback(self):\n return render_template(\n 'superset/traceback.html',\n error_msg=get_error_msg(),\n ), 500\n\n @expose('/welcome')\n def welcome(self):\n \"\"\"Personalized welcome page\"\"\"\n if not g.user or not g.user.get_id():\n return redirect(appbuilder.get_url_for_login)\n\n welcome_dashboard_id = (\n db.session\n .query(UserAttribute.welcome_dashboard_id)\n .filter_by(user_id=g.user.get_id())\n .scalar()\n )\n if welcome_dashboard_id:\n return self.dashboard(str(welcome_dashboard_id))\n\n payload = {\n 'user': bootstrap_user_data(),\n 'common': self.common_bootsrap_payload(),\n }\n\n return self.render_template(\n 'superset/basic.html',\n entry='welcome',\n title='Superset',\n bootstrap_data=json.dumps(payload, default=utils.json_iso_dttm_ser),\n )\n\n @has_access\n @expose('/profile/<username>/')\n def profile(self, username):\n \"\"\"User profile page\"\"\"\n if not username and g.user:\n username = g.user.username\n\n payload = {\n 'user': bootstrap_user_data(username, include_perms=True),\n 'common': self.common_bootsrap_payload(),\n }\n\n return self.render_template(\n 'superset/basic.html',\n title=_(\"%(user)s's profile\", user=username),\n entry='profile',\n bootstrap_data=json.dumps(payload, default=utils.json_iso_dttm_ser),\n )\n\n @has_access\n @expose('/sqllab')\n def sqllab(self):\n \"\"\"SQL Editor\"\"\"\n d = {\n 'defaultDbId': config.get('SQLLAB_DEFAULT_DBID'),\n 'common': self.common_bootsrap_payload(),\n }\n return self.render_template(\n 'superset/basic.html',\n entry='sqllab',\n bootstrap_data=json.dumps(d, default=utils.json_iso_dttm_ser),\n )\n\n @api\n @handle_api_exception\n @has_access_api\n @expose('/slice_query/<slice_id>/')\n def slice_query(self, slice_id):\n \"\"\"\n This method exposes an API endpoint to\n get the database query string for this slice\n \"\"\"\n viz_obj = self.get_viz(slice_id)\n security_manager.assert_datasource_permission(viz_obj.datasource)\n return self.get_query_string_response(viz_obj)\n\n @api\n @has_access_api\n @expose('/schemas_access_for_csv_upload')\n def schemas_access_for_csv_upload(self):\n \"\"\"\n This method exposes an API endpoint to\n get the schema access control settings for csv upload in this database\n \"\"\"\n if not request.args.get('db_id'):\n return json_error_response(\n 'No database is allowed for your csv upload')\n\n db_id = int(request.args.get('db_id'))\n database = (\n db.session\n .query(models.Database)\n .filter_by(id=db_id)\n .one()\n )\n try:\n schemas_allowed = database.get_schema_access_for_csv_upload()\n if (security_manager.database_access(database) or\n security_manager.all_datasource_access()):\n return self.json_response(schemas_allowed)\n # the list schemas_allowed should not be empty here\n # and the list schemas_allowed_processed returned from security_manager\n # should not be empty either,\n # otherwise the database should have been filtered out\n # in CsvToDatabaseForm\n schemas_allowed_processed = security_manager.schemas_accessible_by_user(\n database, schemas_allowed, False)\n return self.json_response(schemas_allowed_processed)\n except Exception:\n return json_error_response((\n 'Failed to fetch schemas allowed for csv upload in this database! '\n 'Please contact Superset Admin!\\n\\n'\n 'The error message returned was:\\n{}').format(traceback.format_exc()))\n\n\nappbuilder.add_view_no_menu(Superset)\n\n\nclass CssTemplateModelView(SupersetModelView, DeleteMixin):\n datamodel = SQLAInterface(models.CssTemplate)\n\n list_title = _('List Css Template')\n show_title = _('Show Css Template')\n add_title = _('Add Css Template')\n edit_title = _('Edit Css Template')\n\n list_columns = ['template_name']\n edit_columns = ['template_name', 'css']\n add_columns = edit_columns\n label_columns = {\n 'template_name': _('Template Name'),\n }\n\n\nclass CssTemplateAsyncModelView(CssTemplateModelView):\n list_columns = ['template_name', 'css']\n\n\nappbuilder.add_separator('Sources')\nappbuilder.add_view(\n CssTemplateModelView,\n 'CSS Templates',\n label=__('CSS Templates'),\n icon='fa-css3',\n category='Manage',\n category_label=__('Manage'),\n category_icon='')\n\n\nappbuilder.add_view_no_menu(CssTemplateAsyncModelView)\n\nappbuilder.add_link(\n 'SQL Editor',\n label=_('SQL Editor'),\n href='/superset/sqllab',\n category_icon='fa-flask',\n icon='fa-flask',\n category='SQL Lab',\n category_label=__('SQL Lab'),\n)\n\nappbuilder.add_link(\n 'Query Search',\n label=_('Query Search'),\n href='/superset/sqllab#search',\n icon='fa-search',\n category_icon='fa-flask',\n category='SQL Lab',\n category_label=__('SQL Lab'),\n)\n\nappbuilder.add_link(\n 'Upload a CSV',\n label=__('Upload a CSV'),\n href='/csvtodatabaseview/form',\n icon='fa-upload',\n category='Sources',\n category_label=__('Sources'),\n category_icon='fa-wrench')\nappbuilder.add_separator('Sources')\n\n\[email protected]_request\ndef apply_caching(response):\n \"\"\"Applies the configuration's http headers to all responses\"\"\"\n for k, v in config.get('HTTP_HEADERS').items():\n response.headers[k] = v\n return response\n\n\n# ---------------------------------------------------------------------\n# Redirecting URL from previous names\nclass RegexConverter(BaseConverter):\n def __init__(self, url_map, *items):\n super(RegexConverter, self).__init__(url_map)\n self.regex = items[0]\n\n\napp.url_map.converters['regex'] = RegexConverter\n\n\[email protected]('/<regex(\"panoramix\\/.*\"):url>')\ndef panoramix(url): # noqa\n return redirect(request.full_path.replace('panoramix', 'superset'))\n\n\[email protected]('/<regex(\"caravel\\/.*\"):url>')\ndef caravel(url): # noqa\n return redirect(request.full_path.replace('caravel', 'superset'))\n\n\n# ---------------------------------------------------------------------\n" ]
[ [ "pandas.DataFrame.from_records" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
rucmlcv/IEPT_FSL
[ "54b0a58b5928771ef8dcc6dcd6f4314739ffe14a" ]
[ "SSL/dataloader/samplers.py" ]
[ "import torch\nimport numpy as np\n\n\nclass CategoriesSamplerBak():\n\n def __init__(self, label, n_batch, n_cls, n_per): #n_batch 为 一个epoch的episode数亩\n \n self.n_batch = n_batch\n self.n_cls = n_cls\n self.n_per = n_per\n self.n_step = 0\n self.mark = {}\n self.r_clses = None\n\n label = np.array(label)\n self.m_ind = []\n for i in range(max(label) + 1):\n ind = np.argwhere(label == i).reshape(-1)\n ind = torch.from_numpy(ind)\n self.m_ind.append(ind)\n\n def __len__(self):\n return self.n_batch\n \n def __iter__(self):\n for i_batch in range(self.n_batch):\n batch = []\n if self.r_clses is None:\n classes = torch.randperm(len(self.m_ind))[:self.n_cls]\n self.r_clses = classes\n else:\n classes = self.r_clses\n self.r_clses = None\n\n for c in classes:\n l = self.m_ind[c]\n self.mark[l] = True\n\n pos = torch.randperm(len(l))[:self.n_per]\n batch.append(l[pos])\n batch = torch.stack(batch).t().reshape(-1)\n yield batch\n\n def getmark(self):\n count = 0\n for c in self.m_ind:\n if c not in self.mark:\n count += 1\n print(count)\n\n\nclass CategoriesSampler():\n\n def __init__(self, label, n_batch, n_cls, n_per): #n_batch 为 一个epoch的episode数亩\n \n self.n_batch = n_batch\n self.n_cls = n_cls\n self.n_per = n_per\n self.n_step = 0\n\n label = np.array(label)\n self.m_ind = []\n for i in range(max(label) + 1):\n ind = np.argwhere(label == i).reshape(-1)\n ind = torch.from_numpy(ind)\n self.m_ind.append(ind)\n\n def __len__(self):\n return self.n_batch\n \n def __iter__(self):\n for i_batch in range(self.n_batch):\n batch = []\n\n classes = torch.randperm(len(self.m_ind))[:self.n_cls]\n\n for c in classes:\n l = self.m_ind[c]\n pos = torch.randperm(len(l))[:self.n_per]\n batch.append(l[pos])\n batch = torch.stack(batch).t().reshape(-1)\n yield batch\n\n\n" ]
[ [ "torch.stack", "numpy.array", "torch.from_numpy", "numpy.argwhere" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jianwang-ntu/deeplift_tf2.0
[ "957511e3e307fdb93f65bf54cc2b5214e5374f49" ]
[ "tests/conversion/sequential/test_conv2d_model_same_padding.py" ]
[ "from __future__ import division\nfrom __future__ import print_function\nfrom __future__ import absolute_import\nimport unittest\nfrom unittest import skip\nimport sys\nimport os\nimport numpy as np\nnp.random.seed(1234)\nfrom deeplift.conversion import kerasapi_conversion as kc\nimport deeplift.layers as layers\nfrom deeplift.layers import NonlinearMxtsMode\nfrom deeplift.util import compile_func\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import models\nfrom tensorflow.keras import backend as K\n\n\nclass TestConvolutionalModel(unittest.TestCase):\n\n\n def setUp(self):\n self.inp = (np.random.randn(10*10*51*51)\n .reshape(10,10,51,51)).transpose(0,2,3,1)\n self.keras_model = keras.models.Sequential()\n conv_layer1 = keras.layers.convolutional.Convolution2D(\n nb_filter=20, nb_row=4, nb_col=4, subsample=(2,2),\n activation=\"relu\",\n padding='same',\n input_shape=(51,51,10))\n self.keras_model.add(conv_layer1)\n conv_layer2 = keras.layers.convolutional.Convolution2D(\n nb_filter=10, nb_row=4, nb_col=4, subsample=(2,2),\n activation=\"relu\",\n padding='same')\n self.keras_model.add(conv_layer2)\n self.keras_model.add(keras.layers.pooling.MaxPooling2D(\n pool_size=(4,4), strides=(2,2),\n padding='same')) \n self.keras_model.add(keras.layers.pooling.AveragePooling2D(\n pool_size=(4,4), strides=(2,2),\n padding='same')) \n self.keras_model.add(keras.layers.Flatten())\n self.keras_model.add(keras.layers.Dense(output_dim=1))\n self.keras_model.add(keras.layers.core.Activation(\"sigmoid\"))\n self.keras_model.compile(loss=\"mse\", optimizer=\"sgd\")\n self.keras_output_fprop_func = compile_func(\n [self.keras_model.layers[0].input,\n K.learning_phase()],\n self.keras_model.layers[-1].output)\n\n grad = tf.gradients(ys=tf.reduce_sum(\n input_tensor=self.keras_model.layers[-2].output[:,0]),\n xs=[self.keras_model.layers[0].input])[0]\n self.grad_func = compile_func(\n [self.keras_model.layers[0].input,\n K.learning_phase()], grad)\n\n self.saved_file_path = \"conv2model_samepadding.h5\"\n if (os.path.isfile(self.saved_file_path)):\n os.remove(self.saved_file_path)\n self.keras_model.save(self.saved_file_path)\n \n def test_convert_conv2d_model_forward_prop(self): \n deeplift_model =\\\n kc.convert_model_from_saved_files(\n self.saved_file_path,\n nonlinear_mxts_mode=NonlinearMxtsMode.Rescale) \n deeplift_fprop_func = compile_func(\n [deeplift_model.get_layers()[0].get_activation_vars()],\n deeplift_model.get_layers()[-1].get_activation_vars())\n np.testing.assert_almost_equal(\n deeplift_fprop_func(self.inp),\n self.keras_output_fprop_func([self.inp, 0]),\n decimal=6)\n \n def test_convert_conv2d_model_compute_scores(self): \n deeplift_model =\\\n kc.convert_model_from_saved_files(\n self.saved_file_path,\n nonlinear_mxts_mode=NonlinearMxtsMode.Rescale) \n deeplift_contribs_func = deeplift_model.\\\n get_target_contribs_func(\n find_scores_layer_idx=0,\n target_layer_idx=-2)\n np.testing.assert_almost_equal(\n deeplift_contribs_func(task_idx=0,\n input_data_list=[self.inp],\n batch_size=10,\n progress_update=None),\n #when biases are 0 and ref is 0, deeplift is the same as grad*inp \n self.grad_func([self.inp, 0])*self.inp, decimal=6)\n\n def tearDown(self):\n if (os.path.isfile(self.saved_file_path)):\n os.remove(self.saved_file_path)\n" ]
[ [ "tensorflow.keras.layers.core.Activation", "tensorflow.keras.layers.pooling.MaxPooling2D", "numpy.random.seed", "tensorflow.keras.layers.Dense", "tensorflow.keras.backend.learning_phase", "tensorflow.reduce_sum", "tensorflow.keras.layers.convolutional.Convolution2D", "tensorflow.keras.layers.pooling.AveragePooling2D", "numpy.random.randn", "tensorflow.keras.models.Sequential", "tensorflow.keras.layers.Flatten" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "2.6", "2.4", "2.3", "2.5", "2.2" ] } ]
Rhcsky/KoSpeech
[ "dbff78140d150dcc71d14d65f81c011847e9574d", "dbff78140d150dcc71d14d65f81c011847e9574d" ]
[ "kospeech/optim/adamp.py", "kospeech/models/model.py" ]
[ "# AdamP\r\n# Copyright (c) 2020-present NAVER Corp.\r\n# MIT license\r\n\r\nimport torch\r\nfrom torch.optim.optimizer import Optimizer\r\nimport math\r\n\r\n\r\nclass AdamP(Optimizer):\r\n \"\"\"\r\n Paper: \"AdamP: Slowing Down the Slowdown for Momentum Optimizers on Scale-invariant Weights\"\r\n\r\n Copied from https://github.com/clovaai/AdamP/\r\n Copyright (c) 2020 Naver Corp.\r\n MIT License\r\n \"\"\"\r\n def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8,\r\n weight_decay=0, delta=0.1, wd_ratio=0.1, nesterov=False):\r\n defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay,\r\n delta=delta, wd_ratio=wd_ratio, nesterov=nesterov)\r\n super(AdamP, self).__init__(params, defaults)\r\n\r\n def _channel_view(self, x):\r\n return x.view(x.size(0), -1)\r\n\r\n def _layer_view(self, x):\r\n return x.view(1, -1)\r\n\r\n def _cosine_similarity(self, x, y, eps, view_func):\r\n x = view_func(x)\r\n y = view_func(y)\r\n\r\n x_norm = x.norm(dim=1).add_(eps)\r\n y_norm = y.norm(dim=1).add_(eps)\r\n dot = (x * y).sum(dim=1)\r\n\r\n return dot.abs() / x_norm / y_norm\r\n\r\n def _projection(self, p, grad, perturb, delta, wd_ratio, eps):\r\n wd = 1\r\n expand_size = [-1] + [1] * (len(p.shape) - 1)\r\n for view_func in [self._channel_view, self._layer_view]:\r\n\r\n cosine_sim = self._cosine_similarity(grad, p.data, eps, view_func)\r\n\r\n if cosine_sim.max() < delta / math.sqrt(view_func(p.data).size(1)):\r\n p_n = p.data / view_func(p.data).norm(dim=1).view(expand_size).add_(eps)\r\n perturb -= p_n * view_func(p_n * perturb).sum(dim=1).view(expand_size)\r\n wd = wd_ratio\r\n\r\n return perturb, wd\r\n\r\n return perturb, wd\r\n\r\n def step(self, closure=None):\r\n loss = None\r\n if closure is not None:\r\n loss = closure()\r\n\r\n for group in self.param_groups:\r\n for p in group['params']:\r\n if p.grad is None:\r\n continue\r\n\r\n grad = p.grad.data\r\n beta1, beta2 = group['betas']\r\n nesterov = group['nesterov']\r\n\r\n state = self.state[p]\r\n\r\n # State initialization\r\n if len(state) == 0:\r\n state['step'] = 0\r\n state['exp_avg'] = torch.zeros_like(p.data)\r\n state['exp_avg_sq'] = torch.zeros_like(p.data)\r\n\r\n # Adam\r\n exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']\r\n\r\n state['step'] += 1\r\n bias_correction1 = 1 - beta1 ** state['step']\r\n bias_correction2 = 1 - beta2 ** state['step']\r\n\r\n exp_avg.mul_(beta1).add_(1 - beta1, grad)\r\n exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad)\r\n\r\n denom = (exp_avg_sq.sqrt() / math.sqrt(bias_correction2)).add_(group['eps'])\r\n step_size = group['lr'] / bias_correction1\r\n\r\n if nesterov:\r\n perturb = (beta1 * exp_avg + (1 - beta1) * grad) / denom\r\n else:\r\n perturb = exp_avg / denom\r\n\r\n # Projection\r\n wd_ratio = 1\r\n if len(p.shape) > 1:\r\n perturb, wd_ratio = self._projection(p, grad, perturb, group['delta'], group['wd_ratio'],\r\n group['eps'])\r\n\r\n # Weight decay\r\n if group['weight_decay'] > 0:\r\n p.data.mul_(1 - group['lr'] * group['weight_decay'] * wd_ratio)\r\n\r\n # Step\r\n p.data.add_(-step_size, perturb)\r\n\r\n return loss\r\n", "# Copyright (c) 2021, Soohwan Kim. All rights reserved.\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n\r\nimport torch\r\nimport torch.nn as nn\r\nfrom torch import Tensor\r\nfrom typing import Tuple\r\n\r\nfrom kospeech.models.modules import Linear\r\nfrom kospeech.models.encoder import (\r\n BaseEncoder,\r\n TransducerEncoder,\r\n)\r\nfrom kospeech.models.decoder import (\r\n BaseDecoder,\r\n TransducerDecoder,\r\n)\r\n\r\n\r\nclass BaseModel(nn.Module):\r\n def __init__(self):\r\n super(BaseModel, self).__init__()\r\n\r\n def count_parameters(self) -> int:\r\n \"\"\" Count parameters of encoder \"\"\"\r\n return sum([p.numel for p in self.parameters()])\r\n\r\n def update_dropout(self, dropout_p: float) -> None:\r\n \"\"\" Update dropout probability of encoder \"\"\"\r\n for name, child in self.named_children():\r\n if isinstance(child, nn.Dropout):\r\n child.p = dropout_p\r\n\r\n @torch.no_grad()\r\n def recognize(self, inputs: Tensor, input_lengths: Tensor):\r\n raise NotImplementedError\r\n\r\n\r\nclass EncoderModel(BaseModel):\r\n \"\"\" Super class of KoSpeech's Encoder only Models \"\"\"\r\n def __init__(self):\r\n super(EncoderModel, self).__init__()\r\n self.decoder = None\r\n\r\n def set_decoder(self, decoder):\r\n \"\"\" Setter for decoder \"\"\"\r\n self.decoder = decoder\r\n\r\n def forward(self, inputs: Tensor, input_lengths: Tensor) -> Tuple[Tensor, Tensor]:\r\n \"\"\"\r\n Forward propagate a `inputs` for ctc training.\r\n\r\n Args:\r\n inputs (torch.FloatTensor): A input sequence passed to encoder. Typically for inputs this will be a padded\r\n `FloatTensor` of size ``(batch, seq_length, dimension)``.\r\n input_lengths (torch.LongTensor): The length of input tensor. ``(batch)``\r\n\r\n Returns:\r\n (Tensor, Tensor):\r\n\r\n * predicted_log_prob (torch.FloatTensor)s: Log probability of model predictions.\r\n * output_lengths (torch.LongTensor): The length of output tensor ``(batch)``\r\n \"\"\"\r\n raise NotImplementedError\r\n\r\n @torch.no_grad()\r\n def decode(self, predicted_log_probs: Tensor) -> Tensor:\r\n \"\"\"\r\n Decode encoder_outputs.\r\n\r\n Args:\r\n predicted_log_probs (torch.FloatTensor):Log probability of model predictions. `FloatTensor` of size\r\n ``(batch, seq_length, dimension)``\r\n\r\n Returns:\r\n * predictions (torch.FloatTensor): Result of model predictions.\r\n \"\"\"\r\n return predicted_log_probs.max(-1)[1]\r\n\r\n @torch.no_grad()\r\n def recognize(self, inputs: Tensor, input_lengths: Tensor) -> Tensor:\r\n \"\"\"\r\n Recognize input speech.\r\n\r\n Args:\r\n inputs (torch.FloatTensor): A input sequence passed to encoder. Typically for inputs this will be a padded\r\n `FloatTensor` of size ``(batch, seq_length, dimension)``.\r\n input_lengths (torch.LongTensor): The length of input tensor. ``(batch)``\r\n\r\n Returns:\r\n * predictions (torch.FloatTensor): Result of model predictions.\r\n \"\"\"\r\n predicted_log_probs, _ = self.forward(inputs, input_lengths)\r\n if self.decoder is not None:\r\n return self.decoder.decode(predicted_log_probs)\r\n return self.decode(predicted_log_probs)\r\n\r\n\r\nclass EncoderDecoderModel(BaseModel):\r\n \"\"\" Super class of KoSpeech's Encoder-Decoder Models \"\"\"\r\n def __init__(self, encoder: BaseEncoder, decoder: BaseDecoder) -> None:\r\n super(EncoderDecoderModel, self).__init__()\r\n self.encoder = encoder\r\n self.decoder = decoder\r\n\r\n def set_encoder(self, encoder):\r\n \"\"\" Setter for encoder \"\"\"\r\n self.encoder = encoder\r\n\r\n def set_decoder(self, decoder):\r\n \"\"\" Setter for decoder \"\"\"\r\n self.decoder = decoder\r\n\r\n def count_parameters(self) -> int:\r\n \"\"\" Count parameters of encoder \"\"\"\r\n num_encoder_parameters = self.encoder.count_parameters()\r\n num_decoder_parameters = self.decoder.count_parameters()\r\n return num_encoder_parameters + num_decoder_parameters\r\n\r\n def update_dropout(self, dropout_p) -> None:\r\n \"\"\" Update dropout probability of model \"\"\"\r\n self.encoder.update_dropout(dropout_p)\r\n self.decoder.update_dropout(dropout_p)\r\n\r\n def forward(\r\n self,\r\n inputs: Tensor,\r\n input_lengths: Tensor,\r\n targets: Tensor,\r\n *args,\r\n ) -> Tuple[Tensor, Tensor, Tensor]:\r\n \"\"\"\r\n Forward propagate a `inputs` and `targets` pair for training.\r\n\r\n Args:\r\n inputs (torch.FloatTensor): A input sequence passed to encoder. Typically for inputs this will be a padded\r\n `FloatTensor` of size ``(batch, seq_length, dimension)``.\r\n input_lengths (torch.LongTensor): The length of input tensor. ``(batch)``\r\n targets (torch.LongTensr): A target sequence passed to decoder. `IntTensor` of size ``(batch, seq_length)``\r\n\r\n Returns:\r\n (Tensor, Tensor, Tensor)\r\n\r\n * predicted_log_probs (torch.FloatTensor): Log probability of model predictions.\r\n * encoder_output_lengths: The length of encoder outputs. ``(batch)``\r\n * encoder_log_probs: Log probability of encoder outputs will be passed to CTC Loss.\r\n If joint_ctc_attention is False, return None.\r\n \"\"\"\r\n raise NotImplementedError\r\n\r\n @torch.no_grad()\r\n def recognize(self, inputs: Tensor, input_lengths: Tensor) -> Tensor:\r\n \"\"\"\r\n Recognize input speech. This method consists of the forward of the encoder and the decode() of the decoder.\r\n\r\n Args:\r\n inputs (torch.FloatTensor): A input sequence passed to encoder. Typically for inputs this will be a padded\r\n `FloatTensor` of size ``(batch, seq_length, dimension)``.\r\n input_lengths (torch.LongTensor): The length of input tensor. ``(batch)``\r\n\r\n Returns:\r\n * predictions (torch.FloatTensor): Result of model predictions.\r\n \"\"\"\r\n encoder_outputs, encoder_output_lengths, _ = self.encoder(inputs, input_lengths)\r\n return self.decoder.decode(encoder_outputs, encoder_output_lengths)\r\n\r\n\r\nclass TransducerModel(BaseModel):\r\n \"\"\" Super class of KoSpeech's Transducer Models \"\"\"\r\n def __init__(\r\n self,\r\n encoder: TransducerEncoder,\r\n decoder: TransducerDecoder,\r\n d_model: int,\r\n num_classes: int,\r\n ) -> None:\r\n super(TransducerModel, self).__init__()\r\n self.encoder = encoder\r\n self.decoder = decoder\r\n self.fc = Linear(d_model << 1, num_classes, bias=False)\r\n\r\n def set_encoder(self, encoder):\r\n \"\"\" Setter for encoder \"\"\"\r\n self.encoder = encoder\r\n\r\n def set_decoder(self, decoder):\r\n \"\"\" Setter for decoder \"\"\"\r\n self.decoder = decoder\r\n\r\n def count_parameters(self) -> int:\r\n \"\"\" Count parameters of encoder \"\"\"\r\n num_encoder_parameters = self.encoder.count_parameters()\r\n num_decoder_parameters = self.decoder.count_parameters()\r\n return num_encoder_parameters + num_decoder_parameters\r\n\r\n def update_dropout(self, dropout_p) -> None:\r\n \"\"\" Update dropout probability of model \"\"\"\r\n self.encoder.update_dropout(dropout_p)\r\n self.decoder.update_dropout(dropout_p)\r\n\r\n def joint(self, encoder_outputs: Tensor, decoder_outputs: Tensor) -> Tensor:\r\n \"\"\"\r\n Joint `encoder_outputs` and `decoder_outputs`.\r\n\r\n Args:\r\n encoder_outputs (torch.FloatTensor): A output sequence of encoder. `FloatTensor` of size\r\n ``(batch, seq_length, dimension)``\r\n decoder_outputs (torch.FloatTensor): A output sequence of decoder. `FloatTensor` of size\r\n ``(batch, seq_length, dimension)``\r\n\r\n Returns:\r\n * outputs (torch.FloatTensor): outputs of joint `encoder_outputs` and `decoder_outputs`..\r\n \"\"\"\r\n if encoder_outputs.dim() == 3 and decoder_outputs.dim() == 3:\r\n input_length = encoder_outputs.size(1)\r\n target_length = decoder_outputs.size(1)\r\n\r\n encoder_outputs = encoder_outputs.unsqueeze(2)\r\n decoder_outputs = decoder_outputs.unsqueeze(1)\r\n\r\n encoder_outputs = encoder_outputs.repeat([1, 1, target_length, 1])\r\n decoder_outputs = decoder_outputs.repeat([1, input_length, 1, 1])\r\n\r\n outputs = torch.cat((encoder_outputs, decoder_outputs), dim=-1)\r\n outputs = self.fc(outputs).log_softmax(dim=-1)\r\n\r\n return outputs\r\n\r\n def forward(\r\n self,\r\n inputs: Tensor,\r\n input_lengths: Tensor,\r\n targets: Tensor,\r\n target_lengths: Tensor,\r\n ) -> Tensor:\r\n \"\"\"\r\n Forward propagate a `inputs` and `targets` pair for training.\r\n\r\n Args:\r\n inputs (torch.FloatTensor): A input sequence passed to encoder. Typically for inputs this will be a padded\r\n `FloatTensor` of size ``(batch, seq_length, dimension)``.\r\n input_lengths (torch.LongTensor): The length of input tensor. ``(batch)``\r\n targets (torch.LongTensr): A target sequence passed to decoder. `IntTensor` of size ``(batch, seq_length)``\r\n target_lengths (torch.LongTensor): The length of target tensor. ``(batch)``\r\n\r\n Returns:\r\n * predictions (torch.FloatTensor): Result of model predictions.\r\n \"\"\"\r\n encoder_outputs, _ = self.encoder(inputs, input_lengths)\r\n decoder_outputs, _ = self.decoder(targets, target_lengths)\r\n return self.joint(encoder_outputs, decoder_outputs)\r\n\r\n @torch.no_grad()\r\n def decode(self, encoder_output: Tensor, max_length: int) -> Tensor:\r\n \"\"\"\r\n Decode `encoder_outputs`.\r\n\r\n Args:\r\n encoder_output (torch.FloatTensor): A output sequence of encoder. `FloatTensor` of size\r\n ``(seq_length, dimension)``\r\n max_length (int): max decoding time step\r\n\r\n Returns:\r\n * predicted_log_probs (torch.FloatTensor): Log probability of model predictions.\r\n \"\"\"\r\n pred_tokens, hidden_state = list(), None\r\n decoder_input = encoder_output.new_tensor([[self.decoder.sos_id]], dtype=torch.long)\r\n\r\n for t in range(max_length):\r\n decoder_output, hidden_state = self.decoder(decoder_input, hidden_states=hidden_state)\r\n step_output = self.joint(encoder_output[t].view(-1), decoder_output.view(-1))\r\n step_output = step_output.softmax(dim=0)\r\n pred_token = step_output.argmax(dim=0)\r\n pred_token = int(pred_token.item())\r\n pred_tokens.append(pred_token)\r\n decoder_input = step_output.new_tensor([[pred_token]], dtype=torch.long)\r\n\r\n return torch.LongTensor(pred_tokens)\r\n\r\n @torch.no_grad()\r\n def recognize(self, inputs: Tensor, input_lengths: Tensor) -> Tensor:\r\n \"\"\"\r\n Recognize input speech. This method consists of the forward of the encoder and the decode() of the decoder.\r\n\r\n Args:\r\n inputs (torch.FloatTensor): A input sequence passed to encoder. Typically for inputs this will be a padded\r\n `FloatTensor` of size ``(batch, seq_length, dimension)``.\r\n input_lengths (torch.LongTensor): The length of input tensor. ``(batch)``\r\n\r\n Returns:\r\n * outputs (torch.FloatTensor): Result of model predictions.\r\n \"\"\"\r\n outputs = list()\r\n\r\n encoder_outputs, output_lengths = self.encoder(inputs, input_lengths)\r\n max_length = encoder_outputs.size(1)\r\n\r\n for encoder_output in encoder_outputs:\r\n decoded_seq = self.decode(encoder_output, max_length)\r\n outputs.append(decoded_seq)\r\n\r\n outputs = torch.stack(outputs, dim=1).transpose(0, 1)\r\n\r\n return outputs\r\n" ]
[ [ "torch.zeros_like" ], [ "torch.stack", "torch.LongTensor", "torch.no_grad", "torch.cat" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jlmaurer/PyRate
[ "bf1a3d916f1c83e7a0dda3ecc15858f8f1e4ee84" ]
[ "tests/test_mst.py" ]
[ "# This Python module is part of the PyRate software package.\n#\n# Copyright 2017 Geoscience Australia\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'''\nThis module contains tests for the mst.py PyRate module.\n'''\n\nimport glob\nimport os\nimport shutil\nimport subprocess\nimport tempfile\nimport unittest\nfrom itertools import product\nfrom numpy import empty, array, nan, isnan, sum as nsum\n\nimport numpy as np\nfrom tests.common import MockIfg, small5_mock_ifgs, small_data_setup\n\nfrom pyrate import algorithm\nfrom pyrate import config as cf\nfrom pyrate import mst\nfrom pyrate.scripts import run_pyrate, run_prepifg\nfrom pyrate.shared import IfgPart, Tile, create_tiles\nfrom tests import common\n\n\nclass MSTTests(unittest.TestCase):\n '''Basic verification of minimum spanning tree (MST) functionality.'''\n\n def setUp(self):\n self.ifgs = small_data_setup()\n\n def test_mst_matrix_as_array(self):\n # Verifies MST matrix func returns array with dict/trees in each cell\n for i in self.ifgs[3:]:\n i.phase_data[0, 1] = 0 # partial stack of NODATA to one cell\n\n for i in self.ifgs:\n i.convert_to_nans() # zeros to NaN/NODATA\n\n epochs = algorithm.get_epochs(self.ifgs)[0]\n res = mst._mst_matrix_as_array(self.ifgs)\n ys, xs = res.shape\n\n for y, x in product(range(ys), range(xs)):\n r = res[y, x]\n num_nodes = len(r)\n self.assertTrue(num_nodes < len(epochs.dates))\n\n stack = array([i.phase_data[y, x] for i in self.ifgs]) # 17 ifg stack\n self.assertTrue(0 == nsum(stack == 0)) # all 0s should be converted\n nc = nsum(isnan(stack))\n exp_count = len(epochs.dates) - 1\n\n if nc == 0:\n self.assertEqual(num_nodes, exp_count)\n elif nc > 5:\n # rough test: too many nans must reduce the total tree size\n self.assertTrue(num_nodes <= (17-nc))\n\n def test_mst_matrix_as_ifgs(self):\n # ensure only ifgs are returned, not individual MST graphs\n ifgs = small5_mock_ifgs()\n nifgs = len(ifgs)\n ys, xs = ifgs[0].shape\n result = mst._mst_matrix_ifgs_only(ifgs)\n\n for coord in product(range(ys), range(xs)):\n stack = (i.phase_data[coord] for i in self.ifgs)\n nc = nsum([isnan(n) for n in stack])\n self.assertTrue(len(result[coord]) <= (nifgs - nc))\n\n # HACK: type testing here is a bit grubby\n self.assertTrue(all([isinstance(i, MockIfg) for i in ifgs]))\n\n def test_partial_nan_pixel_stack(self):\n # Ensure a limited # of coherent cells results in a smaller MST tree\n num_coherent = 3\n\n def assert_equal():\n res = mst._mst_matrix_as_array(mock_ifgs)\n self.assertEqual(len(res[0,0]), num_coherent)\n\n mock_ifgs = [MockIfg(i, 1, 1) for i in self.ifgs]\n for m in mock_ifgs[num_coherent:]:\n m.phase_data[:] = nan\n assert_equal()\n\n # fill in more nans leaving only one ifg\n for m in mock_ifgs[1:num_coherent]:\n m.phase_data[:] = nan\n num_coherent = 1\n assert_equal()\n\n def test_all_nan_pixel_stack(self):\n # ensure full stack of NaNs in an MST pixel classifies to NaN\n mock_ifgs = [MockIfg(i, 1, 1) for i in self.ifgs]\n for m in mock_ifgs:\n m.phase_data[:] = nan\n\n res = mst._mst_matrix_as_array(mock_ifgs)\n exp = empty((1,1), dtype=object)\n exp[:] = nan\n\n shape = (mock_ifgs[0].nrows, mock_ifgs[0].ncols)\n self.assertTrue(res.shape == shape)\n self.assertEqual(exp, res)\n\n\nclass DefaultMSTTests(unittest.TestCase):\n\n def test_default_mst(self):\n # default MST from full set of Ifgs shouldn't drop any nodes\n ifgs = small5_mock_ifgs()\n dates = [(i.master, i.slave) for i in ifgs]\n\n res = mst.mst_from_ifgs(ifgs)[0]\n num_edges = len(res)\n self.assertEqual(num_edges, len(ifgs))\n\n # test edges, note node order can be reversed\n for edge in res:\n self.assertTrue(edge in dates or (edge[1], edge[0]) in dates)\n\n # check all nodes exist in this default tree\n mst_dates = set(res)\n mst_dates = list(sum(mst_dates, ()))\n for i in ifgs:\n for node in (i.master, i.slave):\n self.assertIn(node, mst_dates)\n\n\nclass NetworkxMSTTreeCheck(unittest.TestCase):\n def setUp(self):\n self.ifgs = small_data_setup()\n\n def test_assert_is_not_tree(self):\n non_overlapping = [1, 2, 5, 6, 12, 13, 14, 15, 16, 17]\n ifgs_non_overlapping = [ifg for i, ifg in enumerate(self.ifgs)\n if i+1 in non_overlapping]\n edges, is_tree, ntrees, _ = mst.mst_from_ifgs(ifgs_non_overlapping)\n self.assertFalse(is_tree)\n self.assertEqual(4, ntrees)\n\n def test_small_data_tree(self):\n self.assertTrue(mst.mst_from_ifgs(self.ifgs)[1])\n\n def test_assert_is_tree(self):\n overlapping = [1, 2, 3, 4, 6, 7, 10, 11, 16, 17]\n\n ifgs_overlapping = [ifg for i, ifg in enumerate(self.ifgs)\n if (i+1 in overlapping)]\n edges, is_tree, ntrees, _ = mst.mst_from_ifgs(ifgs_overlapping)\n self.assertFalse(is_tree)\n self.assertEqual(4, ntrees)\n\n def test_assert_two_trees_overlapping(self):\n overlapping = [3, 4, 5, 6, 7, 8, 9, 10, 11, 16, 17]\n\n ifgs_overlapping = [ifg for i, ifg in enumerate(self.ifgs)\n if (i+1 in overlapping)]\n edges, is_tree, ntrees, _ = mst.mst_from_ifgs(ifgs_overlapping)\n self.assertFalse(is_tree)\n self.assertEqual(2, ntrees)\n\n def test_assert_two_trees_non_overlapping(self):\n non_overlapping = [2, 5, 6, 12, 13, 15]\n ifgs_non_overlapping = [ifg for i, ifg in enumerate(self.ifgs)\n if i+1 in non_overlapping]\n edges, is_tree, ntrees, _ = mst.mst_from_ifgs(ifgs_non_overlapping)\n self.assertFalse(is_tree)\n self.assertEqual(2, ntrees)\n\n\nclass IfgPartTest(unittest.TestCase):\n\n def setUp(self):\n self.ifgs = small_data_setup()\n self.params = cf.get_config_params(common.TEST_CONF_ROIPAC)\n\n def test_ifg_part_shape_and_slice(self):\n r_start = 0\n r_end = 10\n for i in self.ifgs:\n tile = Tile(0, top_left=(r_start, 0), bottom_right=(r_end, i.ncols))\n ifg_part = IfgPart(i.data_path, tile)\n self.assertEqual(ifg_part.phase_data.shape,\n (r_end-r_start, i.phase_data.shape[1]))\n np.testing.assert_array_equal(ifg_part.phase_data,\n i.phase_data[r_start:r_end, :])\n\n def test_mst_multiprocessing_serial(self):\n self.params[cf.PARALLEL] = False\n original_mst = mst.mst_boolean_array(self.ifgs)\n parallel_mst = mst.mst_parallel(self.ifgs, params=self.params)\n np.testing.assert_array_equal(original_mst, parallel_mst)\n\n def test_mst_multiprocessing(self):\n self.params[cf.PARALLEL] = True\n original_mst = mst.mst_boolean_array(self.ifgs)\n parallel_mst = mst.mst_parallel(self.ifgs, params=self.params)\n np.testing.assert_array_equal(original_mst, parallel_mst)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n" ]
[ [ "numpy.isnan", "numpy.testing.assert_array_equal", "numpy.array", "numpy.sum", "numpy.empty" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ohad83/pandas
[ "c5576293859f4351e508471811948e9a1dac4a30", "c5576293859f4351e508471811948e9a1dac4a30", "4071dde86e33434e1bee8304fa62074949f813cc" ]
[ "pandas/core/window/expanding.py", "pandas/compat/numpy/function.py", "pandas/tests/tools/test_numeric.py" ]
[ "from textwrap import dedent\n\nfrom pandas.compat.numpy import function as nv\nfrom pandas.util._decorators import Appender, Substitution\n\nfrom pandas.core.window.common import WindowGroupByMixin, _doc_template, _shared_docs\nfrom pandas.core.window.rolling import _Rolling_and_Expanding\n\n\nclass Expanding(_Rolling_and_Expanding):\n \"\"\"\n Provide expanding transformations.\n\n Parameters\n ----------\n min_periods : int, default 1\n Minimum number of observations in window required to have a value\n (otherwise result is NA).\n center : bool, default False\n Set the labels at the center of the window.\n axis : int or str, default 0\n\n Returns\n -------\n a Window sub-classed for the particular operation\n\n See Also\n --------\n rolling : Provides rolling window calculations.\n ewm : Provides exponential weighted functions.\n\n Notes\n -----\n By default, the result is set to the right edge of the window. This can be\n changed to the center of the window by setting ``center=True``.\n\n Examples\n --------\n\n >>> df = pd.DataFrame({'B': [0, 1, 2, np.nan, 4]})\n B\n 0 0.0\n 1 1.0\n 2 2.0\n 3 NaN\n 4 4.0\n\n >>> df.expanding(2).sum()\n B\n 0 NaN\n 1 1.0\n 2 3.0\n 3 3.0\n 4 7.0\n \"\"\"\n\n _attributes = [\"min_periods\", \"center\", \"axis\"]\n\n def __init__(self, obj, min_periods=1, center=False, axis=0, **kwargs):\n super().__init__(obj=obj, min_periods=min_periods, center=center, axis=axis)\n\n @property\n def _constructor(self):\n return Expanding\n\n def _get_window(self, other=None, **kwargs):\n \"\"\"\n Get the window length over which to perform some operation.\n\n Parameters\n ----------\n other : object, default None\n The other object that is involved in the operation.\n Such an object is involved for operations like covariance.\n\n Returns\n -------\n window : int\n The window length.\n \"\"\"\n axis = self.obj._get_axis(self.axis)\n length = len(axis) + (other is not None) * len(axis)\n\n other = self.min_periods or -1\n return max(length, other)\n\n _agg_see_also_doc = dedent(\n \"\"\"\n See Also\n --------\n DataFrame.expanding.aggregate\n DataFrame.rolling.aggregate\n DataFrame.aggregate\n \"\"\"\n )\n\n _agg_examples_doc = dedent(\n \"\"\"\n Examples\n --------\n\n >>> df = pd.DataFrame(np.random.randn(10, 3), columns=['A', 'B', 'C'])\n >>> df\n A B C\n 0 -2.385977 -0.102758 0.438822\n 1 -1.004295 0.905829 -0.954544\n 2 0.735167 -0.165272 -1.619346\n 3 -0.702657 -1.340923 -0.706334\n 4 -0.246845 0.211596 -0.901819\n 5 2.463718 3.157577 -1.380906\n 6 -1.142255 2.340594 -0.039875\n 7 1.396598 -1.647453 1.677227\n 8 -0.543425 1.761277 -0.220481\n 9 -0.640505 0.289374 -1.550670\n\n >>> df.ewm(alpha=0.5).mean()\n A B C\n 0 -2.385977 -0.102758 0.438822\n 1 -1.464856 0.569633 -0.490089\n 2 -0.207700 0.149687 -1.135379\n 3 -0.471677 -0.645305 -0.906555\n 4 -0.355635 -0.203033 -0.904111\n 5 1.076417 1.503943 -1.146293\n 6 -0.041654 1.925562 -0.588728\n 7 0.680292 0.132049 0.548693\n 8 0.067236 0.948257 0.163353\n 9 -0.286980 0.618493 -0.694496\n \"\"\"\n )\n\n @Substitution(\n see_also=_agg_see_also_doc,\n examples=_agg_examples_doc,\n versionadded=\"\",\n klass=\"Series/Dataframe\",\n axis=\"\",\n )\n @Appender(_shared_docs[\"aggregate\"])\n def aggregate(self, func, *args, **kwargs):\n return super().aggregate(func, *args, **kwargs)\n\n agg = aggregate\n\n @Substitution(name=\"expanding\")\n @Appender(_shared_docs[\"count\"])\n def count(self, **kwargs):\n return super().count(**kwargs)\n\n @Substitution(name=\"expanding\")\n @Appender(_shared_docs[\"apply\"])\n def apply(self, func, raw=None, args=(), kwargs={}):\n return super().apply(func, raw=raw, args=args, kwargs=kwargs)\n\n @Substitution(name=\"expanding\")\n @Appender(_shared_docs[\"sum\"])\n def sum(self, *args, **kwargs):\n nv.validate_expanding_func(\"sum\", args, kwargs)\n return super().sum(*args, **kwargs)\n\n @Substitution(name=\"expanding\")\n @Appender(_doc_template)\n @Appender(_shared_docs[\"max\"])\n def max(self, *args, **kwargs):\n nv.validate_expanding_func(\"max\", args, kwargs)\n return super().max(*args, **kwargs)\n\n @Substitution(name=\"expanding\")\n @Appender(_shared_docs[\"min\"])\n def min(self, *args, **kwargs):\n nv.validate_expanding_func(\"min\", args, kwargs)\n return super().min(*args, **kwargs)\n\n @Substitution(name=\"expanding\")\n @Appender(_shared_docs[\"mean\"])\n def mean(self, *args, **kwargs):\n nv.validate_expanding_func(\"mean\", args, kwargs)\n return super().mean(*args, **kwargs)\n\n @Substitution(name=\"expanding\")\n @Appender(_shared_docs[\"median\"])\n def median(self, **kwargs):\n return super().median(**kwargs)\n\n @Substitution(name=\"expanding\", versionadded=\"\")\n @Appender(_shared_docs[\"std\"])\n def std(self, ddof=1, *args, **kwargs):\n nv.validate_expanding_func(\"std\", args, kwargs)\n return super().std(ddof=ddof, **kwargs)\n\n @Substitution(name=\"expanding\", versionadded=\"\")\n @Appender(_shared_docs[\"var\"])\n def var(self, ddof=1, *args, **kwargs):\n nv.validate_expanding_func(\"var\", args, kwargs)\n return super().var(ddof=ddof, **kwargs)\n\n @Substitution(name=\"expanding\")\n @Appender(_doc_template)\n @Appender(_shared_docs[\"skew\"])\n def skew(self, **kwargs):\n return super().skew(**kwargs)\n\n _agg_doc = dedent(\n \"\"\"\n Examples\n --------\n\n The example below will show an expanding calculation with a window size of\n four matching the equivalent function call using `scipy.stats`.\n\n >>> arr = [1, 2, 3, 4, 999]\n >>> import scipy.stats\n >>> fmt = \"{0:.6f}\" # limit the printed precision to 6 digits\n >>> print(fmt.format(scipy.stats.kurtosis(arr[:-1], bias=False)))\n -1.200000\n >>> print(fmt.format(scipy.stats.kurtosis(arr, bias=False)))\n 4.999874\n >>> s = pd.Series(arr)\n >>> s.expanding(4).kurt()\n 0 NaN\n 1 NaN\n 2 NaN\n 3 -1.200000\n 4 4.999874\n dtype: float64\n \"\"\"\n )\n\n @Appender(_agg_doc)\n @Substitution(name=\"expanding\")\n @Appender(_shared_docs[\"kurt\"])\n def kurt(self, **kwargs):\n return super().kurt(**kwargs)\n\n @Substitution(name=\"expanding\")\n @Appender(_shared_docs[\"quantile\"])\n def quantile(self, quantile, interpolation=\"linear\", **kwargs):\n return super().quantile(\n quantile=quantile, interpolation=interpolation, **kwargs\n )\n\n @Substitution(name=\"expanding\")\n @Appender(_doc_template)\n @Appender(_shared_docs[\"cov\"])\n def cov(self, other=None, pairwise=None, ddof=1, **kwargs):\n return super().cov(other=other, pairwise=pairwise, ddof=ddof, **kwargs)\n\n @Substitution(name=\"expanding\")\n @Appender(_shared_docs[\"corr\"])\n def corr(self, other=None, pairwise=None, **kwargs):\n return super().corr(other=other, pairwise=pairwise, **kwargs)\n\n\nclass ExpandingGroupby(WindowGroupByMixin, Expanding):\n \"\"\"\n Provide a expanding groupby implementation.\n \"\"\"\n\n @property\n def _constructor(self):\n return Expanding\n", "\"\"\"\nFor compatibility with numpy libraries, pandas functions or\nmethods have to accept '*args' and '**kwargs' parameters to\naccommodate numpy arguments that are not actually used or\nrespected in the pandas implementation.\n\nTo ensure that users do not abuse these parameters, validation\nis performed in 'validators.py' to make sure that any extra\nparameters passed correspond ONLY to those in the numpy signature.\nPart of that validation includes whether or not the user attempted\nto pass in non-default values for these extraneous parameters. As we\nwant to discourage users from relying on these parameters when calling\nthe pandas implementation, we want them only to pass in the default values\nfor these parameters.\n\nThis module provides a set of commonly used default arguments for functions\nand methods that are spread throughout the codebase. This module will make it\neasier to adjust to future upstream changes in the analogous numpy signatures.\n\"\"\"\nfrom collections import OrderedDict\nfrom distutils.version import LooseVersion\nfrom typing import Any, Dict, Optional, Union\n\nfrom numpy import __version__ as _np_version, ndarray\n\nfrom pandas._libs.lib import is_bool, is_integer\nfrom pandas.errors import UnsupportedFunctionCall\nfrom pandas.util._validators import (\n validate_args,\n validate_args_and_kwargs,\n validate_kwargs,\n)\n\n\nclass CompatValidator:\n def __init__(self, defaults, fname=None, method=None, max_fname_arg_count=None):\n self.fname = fname\n self.method = method\n self.defaults = defaults\n self.max_fname_arg_count = max_fname_arg_count\n\n def __call__(self, args, kwargs, fname=None, max_fname_arg_count=None, method=None):\n if args or kwargs:\n fname = self.fname if fname is None else fname\n max_fname_arg_count = (\n self.max_fname_arg_count\n if max_fname_arg_count is None\n else max_fname_arg_count\n )\n method = self.method if method is None else method\n\n if method == \"args\":\n validate_args(fname, args, max_fname_arg_count, self.defaults)\n elif method == \"kwargs\":\n validate_kwargs(fname, kwargs, self.defaults)\n elif method == \"both\":\n validate_args_and_kwargs(\n fname, args, kwargs, max_fname_arg_count, self.defaults\n )\n else:\n raise ValueError(f\"invalid validation method '{method}'\")\n\n\nARGMINMAX_DEFAULTS = dict(out=None)\nvalidate_argmin = CompatValidator(\n ARGMINMAX_DEFAULTS, fname=\"argmin\", method=\"both\", max_fname_arg_count=1\n)\nvalidate_argmax = CompatValidator(\n ARGMINMAX_DEFAULTS, fname=\"argmax\", method=\"both\", max_fname_arg_count=1\n)\n\n\ndef process_skipna(skipna, args):\n if isinstance(skipna, ndarray) or skipna is None:\n args = (skipna,) + args\n skipna = True\n\n return skipna, args\n\n\ndef validate_argmin_with_skipna(skipna, args, kwargs):\n \"\"\"\n If 'Series.argmin' is called via the 'numpy' library,\n the third parameter in its signature is 'out', which\n takes either an ndarray or 'None', so check if the\n 'skipna' parameter is either an instance of ndarray or\n is None, since 'skipna' itself should be a boolean\n \"\"\"\n\n skipna, args = process_skipna(skipna, args)\n validate_argmin(args, kwargs)\n return skipna\n\n\ndef validate_argmax_with_skipna(skipna, args, kwargs):\n \"\"\"\n If 'Series.argmax' is called via the 'numpy' library,\n the third parameter in its signature is 'out', which\n takes either an ndarray or 'None', so check if the\n 'skipna' parameter is either an instance of ndarray or\n is None, since 'skipna' itself should be a boolean\n \"\"\"\n\n skipna, args = process_skipna(skipna, args)\n validate_argmax(args, kwargs)\n return skipna\n\n\nARGSORT_DEFAULTS: \"OrderedDict[str, Optional[Union[int, str]]]\" = OrderedDict()\nARGSORT_DEFAULTS[\"axis\"] = -1\nARGSORT_DEFAULTS[\"kind\"] = \"quicksort\"\nARGSORT_DEFAULTS[\"order\"] = None\n\nif LooseVersion(_np_version) >= LooseVersion(\"1.17.0\"):\n # GH-26361. NumPy added radix sort and changed default to None.\n ARGSORT_DEFAULTS[\"kind\"] = None\n\n\nvalidate_argsort = CompatValidator(\n ARGSORT_DEFAULTS, fname=\"argsort\", max_fname_arg_count=0, method=\"both\"\n)\n\n# two different signatures of argsort, this second validation\n# for when the `kind` param is supported\nARGSORT_DEFAULTS_KIND: \"OrderedDict[str, Optional[int]]\" = OrderedDict()\nARGSORT_DEFAULTS_KIND[\"axis\"] = -1\nARGSORT_DEFAULTS_KIND[\"order\"] = None\nvalidate_argsort_kind = CompatValidator(\n ARGSORT_DEFAULTS_KIND, fname=\"argsort\", max_fname_arg_count=0, method=\"both\"\n)\n\n\ndef validate_argsort_with_ascending(ascending, args, kwargs):\n \"\"\"\n If 'Categorical.argsort' is called via the 'numpy' library, the\n first parameter in its signature is 'axis', which takes either\n an integer or 'None', so check if the 'ascending' parameter has\n either integer type or is None, since 'ascending' itself should\n be a boolean\n \"\"\"\n\n if is_integer(ascending) or ascending is None:\n args = (ascending,) + args\n ascending = True\n\n validate_argsort_kind(args, kwargs, max_fname_arg_count=3)\n return ascending\n\n\nCLIP_DEFAULTS = dict(out=None) # type Dict[str, Any]\nvalidate_clip = CompatValidator(\n CLIP_DEFAULTS, fname=\"clip\", method=\"both\", max_fname_arg_count=3\n)\n\n\ndef validate_clip_with_axis(axis, args, kwargs):\n \"\"\"\n If 'NDFrame.clip' is called via the numpy library, the third\n parameter in its signature is 'out', which can takes an ndarray,\n so check if the 'axis' parameter is an instance of ndarray, since\n 'axis' itself should either be an integer or None\n \"\"\"\n\n if isinstance(axis, ndarray):\n args = (axis,) + args\n axis = None\n\n validate_clip(args, kwargs)\n return axis\n\n\nCOMPRESS_DEFAULTS: \"OrderedDict[str, Any]\" = OrderedDict()\nCOMPRESS_DEFAULTS[\"axis\"] = None\nCOMPRESS_DEFAULTS[\"out\"] = None\nvalidate_compress = CompatValidator(\n COMPRESS_DEFAULTS, fname=\"compress\", method=\"both\", max_fname_arg_count=1\n)\n\nCUM_FUNC_DEFAULTS: \"OrderedDict[str, Any]\" = OrderedDict()\nCUM_FUNC_DEFAULTS[\"dtype\"] = None\nCUM_FUNC_DEFAULTS[\"out\"] = None\nvalidate_cum_func = CompatValidator(\n CUM_FUNC_DEFAULTS, method=\"both\", max_fname_arg_count=1\n)\nvalidate_cumsum = CompatValidator(\n CUM_FUNC_DEFAULTS, fname=\"cumsum\", method=\"both\", max_fname_arg_count=1\n)\n\n\ndef validate_cum_func_with_skipna(skipna, args, kwargs, name):\n \"\"\"\n If this function is called via the 'numpy' library, the third\n parameter in its signature is 'dtype', which takes either a\n 'numpy' dtype or 'None', so check if the 'skipna' parameter is\n a boolean or not\n \"\"\"\n if not is_bool(skipna):\n args = (skipna,) + args\n skipna = True\n\n validate_cum_func(args, kwargs, fname=name)\n return skipna\n\n\nALLANY_DEFAULTS: \"OrderedDict[str, Optional[bool]]\" = OrderedDict()\nALLANY_DEFAULTS[\"dtype\"] = None\nALLANY_DEFAULTS[\"out\"] = None\nALLANY_DEFAULTS[\"keepdims\"] = False\nvalidate_all = CompatValidator(\n ALLANY_DEFAULTS, fname=\"all\", method=\"both\", max_fname_arg_count=1\n)\nvalidate_any = CompatValidator(\n ALLANY_DEFAULTS, fname=\"any\", method=\"both\", max_fname_arg_count=1\n)\n\nLOGICAL_FUNC_DEFAULTS = dict(out=None, keepdims=False)\nvalidate_logical_func = CompatValidator(LOGICAL_FUNC_DEFAULTS, method=\"kwargs\")\n\nMINMAX_DEFAULTS = dict(out=None, keepdims=False)\nvalidate_min = CompatValidator(\n MINMAX_DEFAULTS, fname=\"min\", method=\"both\", max_fname_arg_count=1\n)\nvalidate_max = CompatValidator(\n MINMAX_DEFAULTS, fname=\"max\", method=\"both\", max_fname_arg_count=1\n)\n\nRESHAPE_DEFAULTS: Dict[str, str] = dict(order=\"C\")\nvalidate_reshape = CompatValidator(\n RESHAPE_DEFAULTS, fname=\"reshape\", method=\"both\", max_fname_arg_count=1\n)\n\nREPEAT_DEFAULTS: Dict[str, Any] = dict(axis=None)\nvalidate_repeat = CompatValidator(\n REPEAT_DEFAULTS, fname=\"repeat\", method=\"both\", max_fname_arg_count=1\n)\n\nROUND_DEFAULTS: Dict[str, Any] = dict(out=None)\nvalidate_round = CompatValidator(\n ROUND_DEFAULTS, fname=\"round\", method=\"both\", max_fname_arg_count=1\n)\n\nSORT_DEFAULTS: \"OrderedDict[str, Optional[Union[int, str]]]\" = OrderedDict()\nSORT_DEFAULTS[\"axis\"] = -1\nSORT_DEFAULTS[\"kind\"] = \"quicksort\"\nSORT_DEFAULTS[\"order\"] = None\nvalidate_sort = CompatValidator(SORT_DEFAULTS, fname=\"sort\", method=\"kwargs\")\n\nSTAT_FUNC_DEFAULTS: \"OrderedDict[str, Optional[Any]]\" = OrderedDict()\nSTAT_FUNC_DEFAULTS[\"dtype\"] = None\nSTAT_FUNC_DEFAULTS[\"out\"] = None\n\nPROD_DEFAULTS = SUM_DEFAULTS = STAT_FUNC_DEFAULTS.copy()\nSUM_DEFAULTS[\"keepdims\"] = False\nSUM_DEFAULTS[\"initial\"] = None\n\nMEDIAN_DEFAULTS = STAT_FUNC_DEFAULTS.copy()\nMEDIAN_DEFAULTS[\"overwrite_input\"] = False\nMEDIAN_DEFAULTS[\"keepdims\"] = False\n\nSTAT_FUNC_DEFAULTS[\"keepdims\"] = False\n\nvalidate_stat_func = CompatValidator(STAT_FUNC_DEFAULTS, method=\"kwargs\")\nvalidate_sum = CompatValidator(\n SUM_DEFAULTS, fname=\"sum\", method=\"both\", max_fname_arg_count=1\n)\nvalidate_prod = CompatValidator(\n PROD_DEFAULTS, fname=\"prod\", method=\"both\", max_fname_arg_count=1\n)\nvalidate_mean = CompatValidator(\n STAT_FUNC_DEFAULTS, fname=\"mean\", method=\"both\", max_fname_arg_count=1\n)\nvalidate_median = CompatValidator(\n MEDIAN_DEFAULTS, fname=\"median\", method=\"both\", max_fname_arg_count=1\n)\n\nSTAT_DDOF_FUNC_DEFAULTS: \"OrderedDict[str, Optional[bool]]\" = OrderedDict()\nSTAT_DDOF_FUNC_DEFAULTS[\"dtype\"] = None\nSTAT_DDOF_FUNC_DEFAULTS[\"out\"] = None\nSTAT_DDOF_FUNC_DEFAULTS[\"keepdims\"] = False\nvalidate_stat_ddof_func = CompatValidator(STAT_DDOF_FUNC_DEFAULTS, method=\"kwargs\")\n\nTAKE_DEFAULTS: \"OrderedDict[str, Optional[str]]\" = OrderedDict()\nTAKE_DEFAULTS[\"out\"] = None\nTAKE_DEFAULTS[\"mode\"] = \"raise\"\nvalidate_take = CompatValidator(TAKE_DEFAULTS, fname=\"take\", method=\"kwargs\")\n\n\ndef validate_take_with_convert(convert, args, kwargs):\n \"\"\"\n If this function is called via the 'numpy' library, the third\n parameter in its signature is 'axis', which takes either an\n ndarray or 'None', so check if the 'convert' parameter is either\n an instance of ndarray or is None\n \"\"\"\n\n if isinstance(convert, ndarray) or convert is None:\n args = (convert,) + args\n convert = True\n\n validate_take(args, kwargs, max_fname_arg_count=3, method=\"both\")\n return convert\n\n\nTRANSPOSE_DEFAULTS = dict(axes=None)\nvalidate_transpose = CompatValidator(\n TRANSPOSE_DEFAULTS, fname=\"transpose\", method=\"both\", max_fname_arg_count=0\n)\n\n\ndef validate_window_func(name, args, kwargs):\n numpy_args = (\"axis\", \"dtype\", \"out\")\n msg = (\n f\"numpy operations are not valid with window objects. \"\n f\"Use .{name}() directly instead \"\n )\n\n if len(args) > 0:\n raise UnsupportedFunctionCall(msg)\n\n for arg in numpy_args:\n if arg in kwargs:\n raise UnsupportedFunctionCall(msg)\n\n\ndef validate_rolling_func(name, args, kwargs):\n numpy_args = (\"axis\", \"dtype\", \"out\")\n msg = (\n f\"numpy operations are not valid with window objects. \"\n f\"Use .rolling(...).{name}() instead \"\n )\n\n if len(args) > 0:\n raise UnsupportedFunctionCall(msg)\n\n for arg in numpy_args:\n if arg in kwargs:\n raise UnsupportedFunctionCall(msg)\n\n\ndef validate_expanding_func(name, args, kwargs):\n numpy_args = (\"axis\", \"dtype\", \"out\")\n msg = (\n f\"numpy operations are not valid with window objects. \"\n f\"Use .expanding(...).{name}() instead \"\n )\n\n if len(args) > 0:\n raise UnsupportedFunctionCall(msg)\n\n for arg in numpy_args:\n if arg in kwargs:\n raise UnsupportedFunctionCall(msg)\n\n\ndef validate_groupby_func(name, args, kwargs, allowed=None):\n \"\"\"\n 'args' and 'kwargs' should be empty, except for allowed\n kwargs because all of\n their necessary parameters are explicitly listed in\n the function signature\n \"\"\"\n if allowed is None:\n allowed = []\n\n kwargs = set(kwargs) - set(allowed)\n\n if len(args) + len(kwargs) > 0:\n raise UnsupportedFunctionCall(\n f\"numpy operations are not valid with \"\n f\"groupby. Use .groupby(...).{name}() \"\n f\"instead\"\n )\n\n\nRESAMPLER_NUMPY_OPS = (\"min\", \"max\", \"sum\", \"prod\", \"mean\", \"std\", \"var\")\n\n\ndef validate_resampler_func(method, args, kwargs):\n \"\"\"\n 'args' and 'kwargs' should be empty because all of\n their necessary parameters are explicitly listed in\n the function signature\n \"\"\"\n if len(args) + len(kwargs) > 0:\n if method in RESAMPLER_NUMPY_OPS:\n raise UnsupportedFunctionCall(\n f\"numpy operations are not \"\n f\"valid with resample. Use \"\n f\".resample(...).{method}() instead\"\n )\n else:\n raise TypeError(\"too many arguments passed in\")\n\n\ndef validate_minmax_axis(axis):\n \"\"\"\n Ensure that the axis argument passed to min, max, argmin, or argmax is\n zero or None, as otherwise it will be incorrectly ignored.\n\n Parameters\n ----------\n axis : int or None\n\n Raises\n ------\n ValueError\n \"\"\"\n ndim = 1 # hard-coded for Index\n if axis is None:\n return\n if axis >= ndim or (axis < 0 and ndim + axis < 0):\n raise ValueError(f\"`axis` must be fewer than the number of dimensions ({ndim})\")\n", "import decimal\n\nimport numpy as np\nfrom numpy import iinfo\nimport pytest\n\nimport pandas as pd\nfrom pandas import DataFrame, Index, Series, to_numeric\nimport pandas.util.testing as tm\n\n\[email protected](params=[None, \"ignore\", \"raise\", \"coerce\"])\ndef errors(request):\n return request.param\n\n\[email protected](params=[True, False])\ndef signed(request):\n return request.param\n\n\[email protected](params=[lambda x: x, str], ids=[\"identity\", \"str\"])\ndef transform(request):\n return request.param\n\n\[email protected](params=[47393996303418497800, 100000000000000000000])\ndef large_val(request):\n return request.param\n\n\[email protected](params=[True, False])\ndef multiple_elts(request):\n return request.param\n\n\[email protected](\n params=[\n (lambda x: Index(x, name=\"idx\"), tm.assert_index_equal),\n (lambda x: Series(x, name=\"ser\"), tm.assert_series_equal),\n (lambda x: np.array(Index(x).values), tm.assert_numpy_array_equal),\n ]\n)\ndef transform_assert_equal(request):\n return request.param\n\n\[email protected](\n \"input_kwargs,result_kwargs\",\n [\n (dict(), dict(dtype=np.int64)),\n (dict(errors=\"coerce\", downcast=\"integer\"), dict(dtype=np.int8)),\n ],\n)\ndef test_empty(input_kwargs, result_kwargs):\n # see gh-16302\n ser = Series([], dtype=object)\n result = to_numeric(ser, **input_kwargs)\n\n expected = Series([], **result_kwargs)\n tm.assert_series_equal(result, expected)\n\n\[email protected](\"last_val\", [\"7\", 7])\ndef test_series(last_val):\n ser = Series([\"1\", \"-3.14\", last_val])\n result = to_numeric(ser)\n\n expected = Series([1, -3.14, 7])\n tm.assert_series_equal(result, expected)\n\n\[email protected](\n \"data\",\n [\n [1, 3, 4, 5],\n [1.0, 3.0, 4.0, 5.0],\n # Bool is regarded as numeric.\n [True, False, True, True],\n ],\n)\ndef test_series_numeric(data):\n ser = Series(data, index=list(\"ABCD\"), name=\"EFG\")\n\n result = to_numeric(ser)\n tm.assert_series_equal(result, ser)\n\n\[email protected](\n \"data,msg\",\n [\n ([1, -3.14, \"apple\"], 'Unable to parse string \"apple\" at position 2'),\n (\n [\"orange\", 1, -3.14, \"apple\"],\n 'Unable to parse string \"orange\" at position 0',\n ),\n ],\n)\ndef test_error(data, msg):\n ser = Series(data)\n\n with pytest.raises(ValueError, match=msg):\n to_numeric(ser, errors=\"raise\")\n\n\[email protected](\n \"errors,exp_data\", [(\"ignore\", [1, -3.14, \"apple\"]), (\"coerce\", [1, -3.14, np.nan])]\n)\ndef test_ignore_error(errors, exp_data):\n ser = Series([1, -3.14, \"apple\"])\n result = to_numeric(ser, errors=errors)\n\n expected = Series(exp_data)\n tm.assert_series_equal(result, expected)\n\n\[email protected](\n \"errors,exp\",\n [\n (\"raise\", 'Unable to parse string \"apple\" at position 2'),\n (\"ignore\", [True, False, \"apple\"]),\n # Coerces to float.\n (\"coerce\", [1.0, 0.0, np.nan]),\n ],\n)\ndef test_bool_handling(errors, exp):\n ser = Series([True, False, \"apple\"])\n\n if isinstance(exp, str):\n with pytest.raises(ValueError, match=exp):\n to_numeric(ser, errors=errors)\n else:\n result = to_numeric(ser, errors=errors)\n expected = Series(exp)\n\n tm.assert_series_equal(result, expected)\n\n\ndef test_list():\n ser = [\"1\", \"-3.14\", \"7\"]\n res = to_numeric(ser)\n\n expected = np.array([1, -3.14, 7])\n tm.assert_numpy_array_equal(res, expected)\n\n\[email protected](\n \"data,arr_kwargs\",\n [\n ([1, 3, 4, 5], dict(dtype=np.int64)),\n ([1.0, 3.0, 4.0, 5.0], dict()),\n # Boolean is regarded as numeric.\n ([True, False, True, True], dict()),\n ],\n)\ndef test_list_numeric(data, arr_kwargs):\n result = to_numeric(data)\n expected = np.array(data, **arr_kwargs)\n tm.assert_numpy_array_equal(result, expected)\n\n\[email protected](\"kwargs\", [dict(dtype=\"O\"), dict()])\ndef test_numeric(kwargs):\n data = [1, -3.14, 7]\n\n ser = Series(data, **kwargs)\n result = to_numeric(ser)\n\n expected = Series(data)\n tm.assert_series_equal(result, expected)\n\n\[email protected](\n \"columns\",\n [\n # One column.\n \"a\",\n # Multiple columns.\n [\"a\", \"b\"],\n ],\n)\ndef test_numeric_df_columns(columns):\n # see gh-14827\n df = DataFrame(\n dict(\n a=[1.2, decimal.Decimal(3.14), decimal.Decimal(\"infinity\"), \"0.1\"],\n b=[1.0, 2.0, 3.0, 4.0],\n )\n )\n\n expected = DataFrame(dict(a=[1.2, 3.14, np.inf, 0.1], b=[1.0, 2.0, 3.0, 4.0]))\n\n df_copy = df.copy()\n df_copy[columns] = df_copy[columns].apply(to_numeric)\n\n tm.assert_frame_equal(df_copy, expected)\n\n\[email protected](\n \"data,exp_data\",\n [\n (\n [[decimal.Decimal(3.14), 1.0], decimal.Decimal(1.6), 0.1],\n [[3.14, 1.0], 1.6, 0.1],\n ),\n ([np.array([decimal.Decimal(3.14), 1.0]), 0.1], [[3.14, 1.0], 0.1]),\n ],\n)\ndef test_numeric_embedded_arr_likes(data, exp_data):\n # Test to_numeric with embedded lists and arrays\n df = DataFrame(dict(a=data))\n df[\"a\"] = df[\"a\"].apply(to_numeric)\n\n expected = DataFrame(dict(a=exp_data))\n tm.assert_frame_equal(df, expected)\n\n\ndef test_all_nan():\n ser = Series([\"a\", \"b\", \"c\"])\n result = to_numeric(ser, errors=\"coerce\")\n\n expected = Series([np.nan, np.nan, np.nan])\n tm.assert_series_equal(result, expected)\n\n\ndef test_type_check(errors):\n # see gh-11776\n df = DataFrame({\"a\": [1, -3.14, 7], \"b\": [\"4\", \"5\", \"6\"]})\n kwargs = dict(errors=errors) if errors is not None else dict()\n error_ctx = pytest.raises(TypeError, match=\"1-d array\")\n\n with error_ctx:\n to_numeric(df, **kwargs)\n\n\[email protected](\"val\", [1, 1.1, 20001])\ndef test_scalar(val, signed, transform):\n val = -val if signed else val\n assert to_numeric(transform(val)) == float(val)\n\n\ndef test_really_large_scalar(large_val, signed, transform, errors):\n # see gh-24910\n kwargs = dict(errors=errors) if errors is not None else dict()\n val = -large_val if signed else large_val\n\n val = transform(val)\n val_is_string = isinstance(val, str)\n\n if val_is_string and errors in (None, \"raise\"):\n msg = \"Integer out of range. at position 0\"\n with pytest.raises(ValueError, match=msg):\n to_numeric(val, **kwargs)\n else:\n expected = float(val) if (errors == \"coerce\" and val_is_string) else val\n tm.assert_almost_equal(to_numeric(val, **kwargs), expected)\n\n\ndef test_really_large_in_arr(large_val, signed, transform, multiple_elts, errors):\n # see gh-24910\n kwargs = dict(errors=errors) if errors is not None else dict()\n val = -large_val if signed else large_val\n val = transform(val)\n\n extra_elt = \"string\"\n arr = [val] + multiple_elts * [extra_elt]\n\n val_is_string = isinstance(val, str)\n coercing = errors == \"coerce\"\n\n if errors in (None, \"raise\") and (val_is_string or multiple_elts):\n if val_is_string:\n msg = \"Integer out of range. at position 0\"\n else:\n msg = 'Unable to parse string \"string\" at position 1'\n\n with pytest.raises(ValueError, match=msg):\n to_numeric(arr, **kwargs)\n else:\n result = to_numeric(arr, **kwargs)\n\n exp_val = float(val) if (coercing and val_is_string) else val\n expected = [exp_val]\n\n if multiple_elts:\n if coercing:\n expected.append(np.nan)\n exp_dtype = float\n else:\n expected.append(extra_elt)\n exp_dtype = object\n else:\n exp_dtype = float if isinstance(exp_val, (int, float)) else object\n\n tm.assert_almost_equal(result, np.array(expected, dtype=exp_dtype))\n\n\ndef test_really_large_in_arr_consistent(large_val, signed, multiple_elts, errors):\n # see gh-24910\n #\n # Even if we discover that we have to hold float, does not mean\n # we should be lenient on subsequent elements that fail to be integer.\n kwargs = dict(errors=errors) if errors is not None else dict()\n arr = [str(-large_val if signed else large_val)]\n\n if multiple_elts:\n arr.insert(0, large_val)\n\n if errors in (None, \"raise\"):\n index = int(multiple_elts)\n msg = \"Integer out of range. at position {index}\".format(index=index)\n\n with pytest.raises(ValueError, match=msg):\n to_numeric(arr, **kwargs)\n else:\n result = to_numeric(arr, **kwargs)\n\n if errors == \"coerce\":\n expected = [float(i) for i in arr]\n exp_dtype = float\n else:\n expected = arr\n exp_dtype = object\n\n tm.assert_almost_equal(result, np.array(expected, dtype=exp_dtype))\n\n\[email protected](\n \"errors,checker\",\n [\n (\"raise\", 'Unable to parse string \"fail\" at position 0'),\n (\"ignore\", lambda x: x == \"fail\"),\n (\"coerce\", lambda x: np.isnan(x)),\n ],\n)\ndef test_scalar_fail(errors, checker):\n scalar = \"fail\"\n\n if isinstance(checker, str):\n with pytest.raises(ValueError, match=checker):\n to_numeric(scalar, errors=errors)\n else:\n assert checker(to_numeric(scalar, errors=errors))\n\n\[email protected](\"data\", [[1, 2, 3], [1.0, np.nan, 3, np.nan]])\ndef test_numeric_dtypes(data, transform_assert_equal):\n transform, assert_equal = transform_assert_equal\n data = transform(data)\n\n result = to_numeric(data)\n assert_equal(result, data)\n\n\[email protected](\n \"data,exp\",\n [\n ([\"1\", \"2\", \"3\"], np.array([1, 2, 3], dtype=\"int64\")),\n ([\"1.5\", \"2.7\", \"3.4\"], np.array([1.5, 2.7, 3.4])),\n ],\n)\ndef test_str(data, exp, transform_assert_equal):\n transform, assert_equal = transform_assert_equal\n result = to_numeric(transform(data))\n\n expected = transform(exp)\n assert_equal(result, expected)\n\n\ndef test_datetime_like(tz_naive_fixture, transform_assert_equal):\n transform, assert_equal = transform_assert_equal\n idx = pd.date_range(\"20130101\", periods=3, tz=tz_naive_fixture)\n\n result = to_numeric(transform(idx))\n expected = transform(idx.asi8)\n assert_equal(result, expected)\n\n\ndef test_timedelta(transform_assert_equal):\n transform, assert_equal = transform_assert_equal\n idx = pd.timedelta_range(\"1 days\", periods=3, freq=\"D\")\n\n result = to_numeric(transform(idx))\n expected = transform(idx.asi8)\n assert_equal(result, expected)\n\n\ndef test_period(transform_assert_equal):\n transform, assert_equal = transform_assert_equal\n\n idx = pd.period_range(\"2011-01\", periods=3, freq=\"M\", name=\"\")\n inp = transform(idx)\n\n if isinstance(inp, Index):\n result = to_numeric(inp)\n expected = transform(idx.asi8)\n assert_equal(result, expected)\n else:\n # TODO: PeriodDtype, so support it in to_numeric.\n pytest.skip(\"Missing PeriodDtype support in to_numeric\")\n\n\[email protected](\n \"errors,expected\",\n [\n (\"raise\", \"Invalid object type at position 0\"),\n (\"ignore\", Series([[10.0, 2], 1.0, \"apple\"])),\n (\"coerce\", Series([np.nan, 1.0, np.nan])),\n ],\n)\ndef test_non_hashable(errors, expected):\n # see gh-13324\n ser = Series([[10.0, 2], 1.0, \"apple\"])\n\n if isinstance(expected, str):\n with pytest.raises(TypeError, match=expected):\n to_numeric(ser, errors=errors)\n else:\n result = to_numeric(ser, errors=errors)\n tm.assert_series_equal(result, expected)\n\n\ndef test_downcast_invalid_cast():\n # see gh-13352\n data = [\"1\", 2, 3]\n invalid_downcast = \"unsigned-integer\"\n msg = \"invalid downcasting method provided\"\n\n with pytest.raises(ValueError, match=msg):\n to_numeric(data, downcast=invalid_downcast)\n\n\ndef test_errors_invalid_value():\n # see gh-26466\n data = [\"1\", 2, 3]\n invalid_error_value = \"invalid\"\n msg = \"invalid error value specified\"\n\n with pytest.raises(ValueError, match=msg):\n to_numeric(data, errors=invalid_error_value)\n\n\[email protected](\n \"data\",\n [\n [\"1\", 2, 3],\n [1, 2, 3],\n np.array([\"1970-01-02\", \"1970-01-03\", \"1970-01-04\"], dtype=\"datetime64[D]\"),\n ],\n)\[email protected](\n \"kwargs,exp_dtype\",\n [\n # Basic function tests.\n (dict(), np.int64),\n (dict(downcast=None), np.int64),\n # Support below np.float32 is rare and far between.\n (dict(downcast=\"float\"), np.dtype(np.float32).char),\n # Basic dtype support.\n (dict(downcast=\"unsigned\"), np.dtype(np.typecodes[\"UnsignedInteger\"][0])),\n ],\n)\ndef test_downcast_basic(data, kwargs, exp_dtype):\n # see gh-13352\n result = to_numeric(data, **kwargs)\n expected = np.array([1, 2, 3], dtype=exp_dtype)\n tm.assert_numpy_array_equal(result, expected)\n\n\[email protected](\"signed_downcast\", [\"integer\", \"signed\"])\[email protected](\n \"data\",\n [\n [\"1\", 2, 3],\n [1, 2, 3],\n np.array([\"1970-01-02\", \"1970-01-03\", \"1970-01-04\"], dtype=\"datetime64[D]\"),\n ],\n)\ndef test_signed_downcast(data, signed_downcast):\n # see gh-13352\n smallest_int_dtype = np.dtype(np.typecodes[\"Integer\"][0])\n expected = np.array([1, 2, 3], dtype=smallest_int_dtype)\n\n res = to_numeric(data, downcast=signed_downcast)\n tm.assert_numpy_array_equal(res, expected)\n\n\ndef test_ignore_downcast_invalid_data():\n # If we can't successfully cast the given\n # data to a numeric dtype, do not bother\n # with the downcast parameter.\n data = [\"foo\", 2, 3]\n expected = np.array(data, dtype=object)\n\n res = to_numeric(data, errors=\"ignore\", downcast=\"unsigned\")\n tm.assert_numpy_array_equal(res, expected)\n\n\ndef test_ignore_downcast_neg_to_unsigned():\n # Cannot cast to an unsigned integer\n # because we have a negative number.\n data = [\"-1\", 2, 3]\n expected = np.array([-1, 2, 3], dtype=np.int64)\n\n res = to_numeric(data, downcast=\"unsigned\")\n tm.assert_numpy_array_equal(res, expected)\n\n\[email protected](\"downcast\", [\"integer\", \"signed\", \"unsigned\"])\[email protected](\n \"data,expected\",\n [\n ([\"1.1\", 2, 3], np.array([1.1, 2, 3], dtype=np.float64)),\n (\n [10000.0, 20000, 3000, 40000.36, 50000, 50000.00],\n np.array(\n [10000.0, 20000, 3000, 40000.36, 50000, 50000.00], dtype=np.float64\n ),\n ),\n ],\n)\ndef test_ignore_downcast_cannot_convert_float(data, expected, downcast):\n # Cannot cast to an integer (signed or unsigned)\n # because we have a float number.\n res = to_numeric(data, downcast=downcast)\n tm.assert_numpy_array_equal(res, expected)\n\n\[email protected](\n \"downcast,expected_dtype\",\n [(\"integer\", np.int16), (\"signed\", np.int16), (\"unsigned\", np.uint16)],\n)\ndef test_downcast_not8bit(downcast, expected_dtype):\n # the smallest integer dtype need not be np.(u)int8\n data = [\"256\", 257, 258]\n\n expected = np.array([256, 257, 258], dtype=expected_dtype)\n res = to_numeric(data, downcast=downcast)\n tm.assert_numpy_array_equal(res, expected)\n\n\[email protected](\n \"dtype,downcast,min_max\",\n [\n (\"int8\", \"integer\", [iinfo(np.int8).min, iinfo(np.int8).max]),\n (\"int16\", \"integer\", [iinfo(np.int16).min, iinfo(np.int16).max]),\n (\"int32\", \"integer\", [iinfo(np.int32).min, iinfo(np.int32).max]),\n (\"int64\", \"integer\", [iinfo(np.int64).min, iinfo(np.int64).max]),\n (\"uint8\", \"unsigned\", [iinfo(np.uint8).min, iinfo(np.uint8).max]),\n (\"uint16\", \"unsigned\", [iinfo(np.uint16).min, iinfo(np.uint16).max]),\n (\"uint32\", \"unsigned\", [iinfo(np.uint32).min, iinfo(np.uint32).max]),\n (\"uint64\", \"unsigned\", [iinfo(np.uint64).min, iinfo(np.uint64).max]),\n (\"int16\", \"integer\", [iinfo(np.int8).min, iinfo(np.int8).max + 1]),\n (\"int32\", \"integer\", [iinfo(np.int16).min, iinfo(np.int16).max + 1]),\n (\"int64\", \"integer\", [iinfo(np.int32).min, iinfo(np.int32).max + 1]),\n (\"int16\", \"integer\", [iinfo(np.int8).min - 1, iinfo(np.int16).max]),\n (\"int32\", \"integer\", [iinfo(np.int16).min - 1, iinfo(np.int32).max]),\n (\"int64\", \"integer\", [iinfo(np.int32).min - 1, iinfo(np.int64).max]),\n (\"uint16\", \"unsigned\", [iinfo(np.uint8).min, iinfo(np.uint8).max + 1]),\n (\"uint32\", \"unsigned\", [iinfo(np.uint16).min, iinfo(np.uint16).max + 1]),\n (\"uint64\", \"unsigned\", [iinfo(np.uint32).min, iinfo(np.uint32).max + 1]),\n ],\n)\ndef test_downcast_limits(dtype, downcast, min_max):\n # see gh-14404: test the limits of each downcast.\n series = to_numeric(Series(min_max), downcast=downcast)\n assert series.dtype == dtype\n\n\[email protected](\n \"ser,expected\",\n [\n (\n pd.Series([0, 9223372036854775808]),\n pd.Series([0, 9223372036854775808], dtype=np.uint64),\n )\n ],\n)\ndef test_downcast_uint64(ser, expected):\n # see gh-14422:\n # BUG: to_numeric doesn't work uint64 numbers\n\n result = pd.to_numeric(ser, downcast=\"unsigned\")\n\n tm.assert_series_equal(result, expected)\n\n\[email protected](\n \"data,exp_data\",\n [\n (\n [200, 300, \"\", \"NaN\", 30000000000000000000],\n [200, 300, np.nan, np.nan, 30000000000000000000],\n ),\n (\n [\"12345678901234567890\", \"1234567890\", \"ITEM\"],\n [12345678901234567890, 1234567890, np.nan],\n ),\n ],\n)\ndef test_coerce_uint64_conflict(data, exp_data):\n # see gh-17007 and gh-17125\n #\n # Still returns float despite the uint64-nan conflict,\n # which would normally force the casting to object.\n result = to_numeric(Series(data), errors=\"coerce\")\n expected = Series(exp_data, dtype=float)\n tm.assert_series_equal(result, expected)\n\n\[email protected](\n \"errors,exp\",\n [\n (\"ignore\", Series([\"12345678901234567890\", \"1234567890\", \"ITEM\"])),\n (\"raise\", \"Unable to parse string\"),\n ],\n)\ndef test_non_coerce_uint64_conflict(errors, exp):\n # see gh-17007 and gh-17125\n #\n # For completeness.\n ser = Series([\"12345678901234567890\", \"1234567890\", \"ITEM\"])\n\n if isinstance(exp, str):\n with pytest.raises(ValueError, match=exp):\n to_numeric(ser, errors=errors)\n else:\n result = to_numeric(ser, errors=errors)\n tm.assert_series_equal(result, ser)\n" ]
[ [ "pandas.util._decorators.Substitution", "pandas.util._decorators.Appender", "pandas.compat.numpy.function.validate_expanding_func" ], [ "pandas.util._validators.validate_args_and_kwargs", "pandas.errors.UnsupportedFunctionCall", "pandas._libs.lib.is_integer", "pandas.util._validators.validate_args", "pandas.util._validators.validate_kwargs", "pandas._libs.lib.is_bool" ], [ "pandas.timedelta_range", "pandas.util.testing.assert_numpy_array_equal", "pandas.Series", "pandas.period_range", "numpy.isnan", "pandas.util.testing.assert_series_equal", "pandas.DataFrame", "numpy.dtype", "pandas.util.testing.assert_frame_equal", "pandas.Index", "numpy.iinfo", "pandas.date_range", "numpy.array", "pandas.to_numeric" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
myelintek/tensorpack
[ "8d5ae5cc2cfcf2e4e53b4d1064ac9e727f736d09", "8d5ae5cc2cfcf2e4e53b4d1064ac9e727f736d09", "8d5ae5cc2cfcf2e4e53b4d1064ac9e727f736d09" ]
[ "examples/ConvolutionalPoseMachines/load-cpm.py", "examples/GAN/CycleGAN.py", "tensorpack/models/layer_norm.py" ]
[ "#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n# File: load-cpm.py\n# Author: Yuxin Wu <[email protected]>\n\nimport cv2\nimport tensorflow as tf\nimport numpy as np\nimport argparse\n\nfrom tensorpack import *\nfrom tensorpack.utils import viz\nfrom tensorpack.utils.argtools import memoized\n\n\"\"\"\n15 channels:\n0-1 head, neck\n2-4 right shoulder, right elbow, right wrist\n5-7 left shoulder, left elbow, left wrist\n8-10 right hip, right knee, right ankle\n11-13 left hip, left knee, left ankle\n14: background\n\"\"\"\n\n\ndef colorize(img, heatmap):\n \"\"\" img: bgr, [0,255]\n heatmap: [0,1]\n \"\"\"\n heatmap = viz.intensity_to_rgb(heatmap, cmap='jet')[:, :, ::-1]\n return img * 0.5 + heatmap * 0.5\n\n\n@memoized\ndef get_gaussian_map():\n gaussian_map = np.zeros((368, 368), dtype='float32')\n for x_p in range(368):\n for y_p in range(368):\n dist_sq = (x_p - 368 / 2) * (x_p - 368 / 2) + \\\n (y_p - 368 / 2) * (y_p - 368 / 2)\n exponent = dist_sq / 2.0 / (21**2)\n gaussian_map[y_p, x_p] = np.exp(-exponent)\n return gaussian_map.reshape((1, 368, 368, 1))\n\n\ndef CPM(image):\n image = image / 256.0 - 0.5\n\n gmap = tf.constant(get_gaussian_map())\n gmap = tf.pad(gmap, [[0, 0], [0, 1], [0, 1], [0, 0]])\n pool_center = AvgPooling('mappool', gmap, 9, stride=8, padding='VALID')\n with argscope(Conv2D, kernel_shape=3, nl=tf.nn.relu,\n W_init=tf.random_normal_initializer(stddev=0.01)):\n shared = (LinearWrap(image)\n .Conv2D('conv1_1', 64)\n .Conv2D('conv1_2', 64)\n .MaxPooling('pool1', 2)\n # 184\n .Conv2D('conv2_1', 128)\n .Conv2D('conv2_2', 128)\n .MaxPooling('pool2', 2)\n # 92\n .Conv2D('conv3_1', 256)\n .Conv2D('conv3_2', 256)\n .Conv2D('conv3_3', 256)\n .Conv2D('conv3_4', 256)\n .MaxPooling('pool3', 2)\n # 46\n .Conv2D('conv4_1', 512)\n .Conv2D('conv4_2', 512)\n .Conv2D('conv4_3_CPM', 256)\n .Conv2D('conv4_4_CPM', 256)\n .Conv2D('conv4_5_CPM', 256)\n .Conv2D('conv4_6_CPM', 256)\n .Conv2D('conv4_7_CPM', 128)())\n\n def add_stage(stage, l):\n l = tf.concat([l, shared, pool_center], 3,\n name='concat_stage{}'.format(stage))\n for i in range(1, 6):\n l = Conv2D('Mconv{}_stage{}'.format(i, stage), l, 128)\n l = Conv2D('Mconv6_stage{}'.format(stage), l, 128, kernel_shape=1)\n l = Conv2D('Mconv7_stage{}'.format(stage),\n l, 15, kernel_shape=1, nl=tf.identity)\n return l\n\n with argscope(Conv2D, kernel_shape=7, nl=tf.nn.relu):\n out1 = (LinearWrap(shared)\n .Conv2D('conv5_1_CPM', 512, kernel_shape=1)\n .Conv2D('conv5_2_CPM', 15, kernel_shape=1, nl=tf.identity)())\n out2 = add_stage(2, out1)\n out3 = add_stage(3, out2)\n out4 = add_stage(4, out3)\n out5 = add_stage(5, out4)\n out6 = add_stage(6, out5)\n tf.image.resize_bilinear(out6, [368, 368], name='resized_map')\n\n\ndef run_test(model_path, img_file):\n param_dict = np.load(model_path, encoding='latin1').item()\n predict_func = OfflinePredictor(PredictConfig(\n inputs_desc=[InputDesc(tf.float32, (None, 368, 368, 3), 'input')],\n tower_func=CPM,\n session_init=DictRestore(param_dict),\n input_names=['input'],\n output_names=['resized_map']\n ))\n\n im = cv2.imread(img_file, cv2.IMREAD_COLOR).astype('float32')\n im = cv2.resize(im, (368, 368))\n out = predict_func(im[None, :, :, :])[0][0]\n hm = out[:, :, :14].sum(axis=2)\n viz = colorize(im, hm)\n cv2.imwrite(\"output.jpg\", viz)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--load', required=True, help='.npy model file')\n parser.add_argument('--input', required=True, help='input image')\n args = parser.parse_args()\n run_test(args.load, args.input)\n", "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# File: CycleGAN.py\n# Author: Yuxin Wu <[email protected]>\n\nimport os\nimport argparse\nimport glob\nfrom six.moves import range\n\n\nfrom tensorpack import *\nfrom tensorpack.tfutils.summary import add_moving_summary\nfrom tensorpack.tfutils.scope_utils import auto_reuse_variable_scope\nimport tensorflow as tf\nfrom GAN import GANTrainer, GANModelDesc\n\n\"\"\"\n1. Download the dataset following the original project: https://github.com/junyanz/CycleGAN#train\n2. ./CycleGAN.py --data /path/to/datasets/horse2zebra\nTraining and testing visualizations will be in tensorboard.\n\nThis implementation doesn't use fake sample buffer.\nIt's not hard to add but I didn't observe any difference with it.\n\"\"\"\n\nSHAPE = 256\nBATCH = 1\nTEST_BATCH = 32\nNF = 64 # channel size\n\n\ndef INReLU(x, name=None):\n x = InstanceNorm('inorm', x)\n return tf.nn.relu(x, name=name)\n\n\ndef INLReLU(x, name=None):\n x = InstanceNorm('inorm', x)\n return LeakyReLU(x, name=name)\n\n\nclass Model(GANModelDesc):\n def _get_inputs(self):\n return [InputDesc(tf.float32, (None, SHAPE, SHAPE, 3), 'inputA'),\n InputDesc(tf.float32, (None, SHAPE, SHAPE, 3), 'inputB')]\n\n @staticmethod\n def build_res_block(x, name, chan, first=False):\n with tf.variable_scope(name):\n input = x\n return (LinearWrap(x)\n .tf.pad([[0, 0], [0, 0], [1, 1], [1, 1]], mode='SYMMETRIC')\n .Conv2D('conv0', chan, padding='VALID')\n .tf.pad([[0, 0], [0, 0], [1, 1], [1, 1]], mode='SYMMETRIC')\n .Conv2D('conv1', chan, padding='VALID', nl=tf.identity)\n .InstanceNorm('inorm')()) + input\n\n @auto_reuse_variable_scope\n def generator(self, img):\n assert img is not None\n with argscope([Conv2D, Deconv2D], nl=INReLU, kernel_shape=3):\n l = (LinearWrap(img)\n .tf.pad([[0, 0], [0, 0], [3, 3], [3, 3]], mode='SYMMETRIC')\n .Conv2D('conv0', NF, kernel_shape=7, padding='VALID')\n .Conv2D('conv1', NF * 2, stride=2)\n .Conv2D('conv2', NF * 4, stride=2)())\n for k in range(9):\n l = Model.build_res_block(l, 'res{}'.format(k), NF * 4, first=(k == 0))\n l = (LinearWrap(l)\n .Deconv2D('deconv0', NF * 2, stride=2)\n .Deconv2D('deconv1', NF * 1, stride=2)\n .tf.pad([[0, 0], [0, 0], [3, 3], [3, 3]], mode='SYMMETRIC')\n .Conv2D('convlast', 3, kernel_shape=7, padding='VALID', nl=tf.tanh, use_bias=True)())\n return l\n\n @auto_reuse_variable_scope\n def discriminator(self, img):\n with argscope(Conv2D, nl=INLReLU, kernel_shape=4, stride=2):\n l = (LinearWrap(img)\n .Conv2D('conv0', NF, nl=LeakyReLU)\n .Conv2D('conv1', NF * 2)\n .Conv2D('conv2', NF * 4)\n .Conv2D('conv3', NF * 8, stride=1)\n .Conv2D('conv4', 1, stride=1, nl=tf.identity, use_bias=True)())\n return l\n\n def _build_graph(self, inputs):\n A, B = inputs\n with tf.name_scope('preprocess'):\n A = tf.transpose(A / 128.0 - 1.0, [0, 3, 1, 2])\n B = tf.transpose(B / 128.0 - 1.0, [0, 3, 1, 2])\n\n def viz3(name, a, b, c):\n with tf.name_scope(name):\n im = tf.concat([a, b, c], axis=3)\n im = tf.transpose(im, [0, 2, 3, 1])\n im = (im + 1.0) * 128\n im = tf.clip_by_value(im, 0, 255)\n im = tf.cast(im, tf.uint8, name='viz')\n tf.summary.image(name, im, max_outputs=50)\n\n # use the initializers from torch\n with argscope([Conv2D, Deconv2D], use_bias=False,\n W_init=tf.random_normal_initializer(stddev=0.02)), \\\n argscope([Conv2D, Deconv2D, InstanceNorm], data_format='NCHW'), \\\n argscope(LeakyReLU, alpha=0.2):\n with tf.variable_scope('gen'):\n with tf.variable_scope('B'):\n AB = self.generator(A)\n with tf.variable_scope('A'):\n BA = self.generator(B)\n ABA = self.generator(AB)\n with tf.variable_scope('B'):\n BAB = self.generator(BA)\n\n viz3('A_recon', A, AB, ABA)\n viz3('B_recon', B, BA, BAB)\n\n with tf.variable_scope('discrim'):\n with tf.variable_scope('A'):\n A_dis_real = self.discriminator(A)\n A_dis_fake = self.discriminator(BA)\n\n with tf.variable_scope('B'):\n B_dis_real = self.discriminator(B)\n B_dis_fake = self.discriminator(AB)\n\n def LSGAN_losses(real, fake):\n d_real = tf.reduce_mean(tf.squared_difference(real, 1), name='d_real')\n d_fake = tf.reduce_mean(tf.square(fake), name='d_fake')\n d_loss = tf.multiply(d_real + d_fake, 0.5, name='d_loss')\n\n g_loss = tf.reduce_mean(tf.squared_difference(fake, 1), name='g_loss')\n add_moving_summary(g_loss, d_loss)\n return g_loss, d_loss\n\n with tf.name_scope('losses'):\n with tf.name_scope('LossA'):\n # reconstruction loss\n recon_loss_A = tf.reduce_mean(tf.abs(A - ABA), name='recon_loss')\n # gan loss\n G_loss_A, D_loss_A = LSGAN_losses(A_dis_real, A_dis_fake)\n\n with tf.name_scope('LossB'):\n recon_loss_B = tf.reduce_mean(tf.abs(B - BAB), name='recon_loss')\n G_loss_B, D_loss_B = LSGAN_losses(B_dis_real, B_dis_fake)\n\n LAMBDA = 10.0\n self.g_loss = tf.add((G_loss_A + G_loss_B),\n (recon_loss_A + recon_loss_B) * LAMBDA, name='G_loss_total')\n self.d_loss = tf.add(D_loss_A, D_loss_B, name='D_loss_total')\n self.collect_variables('gen', 'discrim')\n\n add_moving_summary(recon_loss_A, recon_loss_B, self.g_loss, self.d_loss)\n\n def _get_optimizer(self):\n lr = tf.get_variable('learning_rate', initializer=2e-4, trainable=False)\n return tf.train.AdamOptimizer(lr, beta1=0.5, epsilon=1e-3)\n\n\ndef get_data(datadir, isTrain=True):\n if isTrain:\n augs = [\n imgaug.Resize(int(SHAPE * 1.12)),\n imgaug.RandomCrop(SHAPE),\n imgaug.Flip(horiz=True),\n ]\n else:\n augs = [imgaug.Resize(SHAPE)]\n\n def get_image_pairs(dir1, dir2):\n def get_df(dir):\n files = sorted(glob.glob(os.path.join(dir, '*.jpg')))\n df = ImageFromFile(files, channel=3, shuffle=isTrain)\n return AugmentImageComponent(df, augs)\n return JoinData([get_df(dir1), get_df(dir2)])\n\n names = ['trainA', 'trainB'] if isTrain else ['testA', 'testB']\n df = get_image_pairs(*[os.path.join(datadir, n) for n in names])\n df = BatchData(df, BATCH if isTrain else TEST_BATCH)\n df = PrefetchDataZMQ(df, 2 if isTrain else 1)\n return df\n\n\nclass VisualizeTestSet(Callback):\n def _setup_graph(self):\n self.pred = self.trainer.get_predictor(\n ['inputA', 'inputB'], ['A_recon/viz', 'B_recon/viz'])\n\n def _before_train(self):\n global args\n self.val_ds = get_data(args.data, isTrain=False)\n self.val_ds.reset_state()\n\n def _trigger(self):\n idx = 0\n for iA, iB in self.val_ds.get_data():\n vizA, vizB = self.pred(iA, iB)\n self.trainer.monitors.put_image('testA-{}'.format(idx), vizA)\n self.trainer.monitors.put_image('testB-{}'.format(idx), vizB)\n idx += 1\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '--data', required=True,\n help='the image directory. should contain trainA/trainB/testA/testB')\n parser.add_argument('--load', help='load model')\n args = parser.parse_args()\n\n logger.auto_set_dir()\n\n data = get_data(args.data)\n data = PrintData(data)\n\n GANTrainer(QueueInput(data), Model()).train_with_defaults(\n callbacks=[\n ModelSaver(),\n ScheduledHyperParamSetter(\n 'learning_rate',\n [(100, 2e-4), (200, 0)], interp='linear'),\n PeriodicTrigger(VisualizeTestSet(), every_k_epochs=3),\n ],\n max_epoch=195,\n steps_per_epoch=data.size(),\n session_init=SaverRestore(args.load) if args.load else None\n )\n", "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# File: layer_norm.py\n# Author: Yuxin Wu <[email protected]>\n\nimport tensorflow as tf\nfrom .common import layer_register\n\n__all__ = ['LayerNorm', 'InstanceNorm']\n\n\n@layer_register()\ndef LayerNorm(x, epsilon=1e-5, use_bias=True, use_scale=True, data_format='NHWC'):\n \"\"\"\n Layer Normalization layer, as described in the paper:\n `Layer Normalization <https://arxiv.org/abs/1607.06450>`_.\n\n Args:\n x (tf.Tensor): a 4D or 2D tensor. When 4D, the layout should match data_format.\n epsilon (float): epsilon to avoid divide-by-zero.\n use_scale, use_bias (bool): whether to use the extra affine transformation or not.\n \"\"\"\n shape = x.get_shape().as_list()\n ndims = len(shape)\n assert ndims in [2, 4]\n\n mean, var = tf.nn.moments(x, list(range(1, len(shape))), keep_dims=True)\n\n if data_format == 'NCHW':\n chan = shape[1]\n new_shape = [1, chan, 1, 1]\n else:\n chan = shape[-1]\n new_shape = [1, 1, 1, chan]\n if ndims == 2:\n new_shape = [1, chan]\n\n if use_bias:\n beta = tf.get_variable('beta', [chan], initializer=tf.constant_initializer())\n beta = tf.reshape(beta, new_shape)\n else:\n beta = tf.zeros([1] * ndims, name='beta')\n if use_scale:\n gamma = tf.get_variable('gamma', [chan], initializer=tf.constant_initializer(1.0))\n gamma = tf.reshape(gamma, new_shape)\n else:\n gamma = tf.ones([1] * ndims, name='gamma')\n\n return tf.nn.batch_normalization(x, mean, var, beta, gamma, epsilon, name='output')\n\n\n@layer_register()\ndef InstanceNorm(x, epsilon=1e-5, data_format='NHWC', use_affine=True):\n \"\"\"\n Instance Normalization, as in the paper:\n `Instance Normalization: The Missing Ingredient for Fast Stylization\n <https://arxiv.org/abs/1607.08022>`_.\n\n Args:\n x (tf.Tensor): a 4D tensor.\n epsilon (float): avoid divide-by-zero\n use_affine (bool): whether to apply learnable affine transformation\n \"\"\"\n shape = x.get_shape().as_list()\n assert len(shape) == 4, \"Input of InstanceNorm has to be 4D!\"\n\n if data_format == 'NHWC':\n axis = [1, 2]\n ch = shape[3]\n new_shape = [1, 1, 1, ch]\n else:\n axis = [2, 3]\n ch = shape[1]\n new_shape = [1, ch, 1, 1]\n assert ch is not None, \"Input of InstanceNorm require known channel!\"\n\n mean, var = tf.nn.moments(x, axis, keep_dims=True)\n\n if not use_affine:\n return tf.divide(x - mean, tf.sqrt(var + epsilon), name='output')\n\n beta = tf.get_variable('beta', [ch], initializer=tf.constant_initializer())\n beta = tf.reshape(beta, new_shape)\n gamma = tf.get_variable('gamma', [ch], initializer=tf.constant_initializer(1.0))\n gamma = tf.reshape(gamma, new_shape)\n return tf.nn.batch_normalization(x, mean, var, beta, gamma, epsilon, name='output')\n" ]
[ [ "tensorflow.image.resize_bilinear", "tensorflow.random_normal_initializer", "tensorflow.pad", "numpy.load", "numpy.exp", "numpy.zeros" ], [ "tensorflow.clip_by_value", "tensorflow.nn.relu", "tensorflow.get_variable", "tensorflow.multiply", "tensorflow.transpose", "tensorflow.concat", "tensorflow.summary.image", "tensorflow.cast", "tensorflow.add", "tensorflow.name_scope", "tensorflow.train.AdamOptimizer", "tensorflow.square", "tensorflow.variable_scope", "tensorflow.random_normal_initializer", "tensorflow.squared_difference", "tensorflow.abs" ], [ "tensorflow.nn.batch_normalization", "tensorflow.zeros", "tensorflow.nn.moments", "tensorflow.reshape", "tensorflow.ones", "tensorflow.constant_initializer", "tensorflow.sqrt" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "1.12", "2.6", "2.2", "1.13", "2.3", "2.4", "1.4", "2.9", "1.5", "1.7", "2.5", "0.12", "1.0", "2.8", "1.2", "2.10" ] } ]