repo_name
stringlengths 6
130
| hexsha
sequence | file_path
sequence | code
sequence | apis
sequence | possible_versions
list |
---|---|---|---|---|---|
openvinotoolkit/nncf_pytorch | [
"13a483eac6ed891720ba90d7902142c4b3bfa599",
"13a483eac6ed891720ba90d7902142c4b3bfa599"
] | [
"tests/torch/nas/test_state.py",
"examples/experimental/onnx/run_ptq.py"
] | [
"\"\"\"\n Copyright (c) 2022 Intel Corporation\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 http://www.apache.org/licenses/LICENSE-2.0\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\"\"\"\nimport logging\nfrom copy import deepcopy\nfrom functools import partial\n\nimport pytest\nimport torch\n\nfrom nncf.common.utils.logger import logger as nncf_logger\nfrom nncf.experimental.torch.nas.bootstrapNAS.elasticity.base_handler import SEHBuilderStateNames\nfrom nncf.experimental.torch.nas.bootstrapNAS.elasticity.elastic_depth import EDBuilderStateNames\nfrom nncf.experimental.torch.nas.bootstrapNAS.elasticity.elastic_kernel import EKBuilderStateNames\nfrom nncf.experimental.torch.nas.bootstrapNAS.elasticity.elastic_width import EWBuilderStateNames\nfrom nncf.experimental.torch.nas.bootstrapNAS.elasticity.elasticity_dim import ElasticityDim\nfrom nncf.torch.model_creation import create_nncf_network\nfrom tests.torch.helpers import BasicConvTestModel\nfrom tests.torch.helpers import get_empty_config\nfrom tests.torch.nas.creators import build_elastic_model_from_handler\nfrom tests.torch.nas.descriptors import ElasticityDesc\nfrom tests.torch.nas.helpers import do_conv2d\nfrom tests.torch.nas.helpers import move_model_to_cuda_if_available\nfrom tests.torch.nas.test_elastic_depth import BASIC_ELASTIC_DEPTH_PARAMS\nfrom tests.torch.nas.test_elastic_depth import BasicTestSuperNet\nfrom tests.torch.nas.test_elastic_depth import DepthBasicConvTestModel\nfrom tests.torch.nas.test_elastic_kernel import BASIC_ELASTIC_KERNEL_PARAMS\nfrom tests.torch.nas.test_elastic_width import BASIC_ELASTIC_WIDTH_PARAMS\nfrom tests.torch.nas.test_elastic_width import TwoConvAddConvTestModel\nfrom tests.torch.nas.test_elastic_width import TwoSequentialConvBNTestModel\n\n\[email protected]_fixture()\ndef _nncf_caplog(caplog):\n nncf_logger.propagate = True\n yield caplog\n nncf_logger.propagate = False\n\n\ndef ref_width_output_fn(model, x):\n return model.get_minimal_subnet_output_without_reorg(x)\n\n\nCOMMON_WIDTH_STATE_DESCS = [\n ElasticityDesc(\n ElasticityDim.WIDTH,\n model_cls=TwoConvAddConvTestModel,\n params=BASIC_ELASTIC_WIDTH_PARAMS,\n ref_state={\n 'elasticity_params': BASIC_ELASTIC_WIDTH_PARAMS,\n 'grouped_node_names_to_prune': [\n ['TwoConvAddConvTestModel/NNCFConv2d[conv1]/conv2d_0',\n 'TwoConvAddConvTestModel/NNCFConv2d[conv2]/conv2d_0']\n ]\n },\n ref_output_fn=ref_width_output_fn\n ),\n ElasticityDesc(\n ElasticityDim.WIDTH,\n model_cls=TwoSequentialConvBNTestModel,\n params=BASIC_ELASTIC_WIDTH_PARAMS,\n ref_state={\n 'elasticity_params': BASIC_ELASTIC_WIDTH_PARAMS,\n 'grouped_node_names_to_prune': [\n ['TwoSequentialConvBNTestModel/Sequential[all_layers]/NNCFConv2d[0]/conv2d_0'],\n ['TwoSequentialConvBNTestModel/Sequential[all_layers]/NNCFConv2d[3]/conv2d_0']\n ]\n },\n ref_output_fn=ref_width_output_fn\n ),\n]\n\n\ndef ref_kernel_output_fn(model, x):\n conv = model.conv\n ref_padding = 1\n ref_weights = conv.weight[:, :, 1:4, 1:4]\n return do_conv2d(conv, x, weight=ref_weights, padding=ref_padding)\n\n\nCOMMON_KERNEL_DESC = ElasticityDesc(\n ElasticityDim.KERNEL,\n model_cls=partial(BasicConvTestModel, 1, out_channels=1, kernel_size=5),\n params=BASIC_ELASTIC_KERNEL_PARAMS,\n ref_output_fn=ref_kernel_output_fn,\n ref_state={\n SEHBuilderStateNames.ELASTICITY_PARAMS: BASIC_ELASTIC_KERNEL_PARAMS,\n EKBuilderStateNames.NODE_NAMES_TO_MAKE_ELASTIC: ['BasicConvTestModel/NNCFConv2d[conv]/conv2d_0']\n },\n input_size=[1, 1, 5, 5]\n)\n\nCOMMON_DEPTH_SUPERNET_DESC = ElasticityDesc(\n ElasticityDim.DEPTH,\n model_cls=BasicTestSuperNet,\n params={\n 'mode': 'auto',\n 'min_block_size': 2\n },\n ref_state={\n 'elasticity_params': {\n 'allow_linear_combination': False,\n 'allow_nested_blocks': False,\n 'max_block_size': 50,\n 'min_block_size': 2,\n 'skipped_blocks': None\n },\n EDBuilderStateNames.SKIPPED_BLOCKS: [\n {\n 'start_node_name': 'BasicTestSuperNet/NNCFConv2d[conv1]/conv2d_0',\n 'end_node_name': 'BasicTestSuperNet/__add___0'\n }\n ],\n EDBuilderStateNames.SKIPPED_BLOCKS_DEPENDENCIES: {0: [0]},\n EDBuilderStateNames.OrdinalIds: [[1, 3]],\n },\n ref_search_space=[[0], []]\n)\n\n\ndef ref_depth_output_fn(model, x):\n model.set_skipped_layers(['conv1'])\n return model(x)\n\n\nCOMMON_DEPTH_BASIC_DESC = ElasticityDesc(\n ElasticityDim.DEPTH,\n model_cls=DepthBasicConvTestModel,\n params=BASIC_ELASTIC_DEPTH_PARAMS,\n ref_output_fn=ref_depth_output_fn,\n ref_search_space=[[0], []],\n ref_state={\n 'elasticity_params': {\n 'allow_linear_combination': False,\n 'allow_nested_blocks': False,\n 'max_block_size': 50,\n 'min_block_size': 6,\n 'skipped_blocks': [['DepthBasicConvTestModel/Sequential[branch_with_blocks]/NNCFConv2d[conv0]/conv2d_0',\n 'DepthBasicConvTestModel/Sequential[branch_with_blocks]/NNCFConv2d[conv1]/conv2d_0']]\n },\n EDBuilderStateNames.SKIPPED_BLOCKS: BASIC_ELASTIC_DEPTH_PARAMS['skipped_blocks_state'],\n EDBuilderStateNames.SKIPPED_BLOCKS_DEPENDENCIES: BASIC_ELASTIC_DEPTH_PARAMS['skipped_blocks_dependencies'],\n EDBuilderStateNames.OrdinalIds: None,\n }\n)\n\nLIST_STATE_AFTER_BUILD_DESCS = [\n *COMMON_WIDTH_STATE_DESCS,\n COMMON_DEPTH_SUPERNET_DESC,\n COMMON_KERNEL_DESC\n]\n\n\[email protected]('desc', LIST_STATE_AFTER_BUILD_DESCS, ids=map(str, LIST_STATE_AFTER_BUILD_DESCS))\ndef test_can_get_builder_state_after_build(desc):\n _, builder = desc.build_handler()\n actual_state = builder.get_state()\n assert actual_state == desc.ref_state\n\n\nELASTIC_WIDTH_PARAMS_BB = {'filter_importance': 'L2', **BASIC_ELASTIC_WIDTH_PARAMS}\nLIST_STATE_BEFORE_BUILD_DESCS = [\n ElasticityDesc(\n ElasticityDim.WIDTH,\n params=ELASTIC_WIDTH_PARAMS_BB,\n ref_state={\n SEHBuilderStateNames.ELASTICITY_PARAMS: ELASTIC_WIDTH_PARAMS_BB,\n EWBuilderStateNames.GROUPED_NODE_NAMES_TO_PRUNE: []\n }\n ),\n ElasticityDesc(\n ElasticityDim.KERNEL,\n params=BASIC_ELASTIC_KERNEL_PARAMS,\n ref_state={\n SEHBuilderStateNames.ELASTICITY_PARAMS: BASIC_ELASTIC_KERNEL_PARAMS,\n EKBuilderStateNames.NODE_NAMES_TO_MAKE_ELASTIC: []\n }\n ),\n COMMON_DEPTH_BASIC_DESC\n]\n\n\[email protected]('desc', LIST_STATE_BEFORE_BUILD_DESCS, ids=map(str, LIST_STATE_BEFORE_BUILD_DESCS))\nclass TestBeforeBuild:\n def test_can_get_builder_state_before_build(self, desc: ElasticityDesc):\n builder = desc.create_builder()\n actual_state = builder.get_state()\n assert actual_state == desc.ref_state\n\n def test_output_warning_when_state_overrides_params(self, desc: ElasticityDesc, _nncf_caplog):\n old_builder = desc.create_builder_with_config({})\n old_state = old_builder.get_state()\n\n new_params = desc.params\n new_builder = desc.create_builder_with_config(new_params)\n new_builder.load_state(old_state)\n\n record = next(iter(_nncf_caplog.records))\n assert record.levelno == logging.WARNING\n\n def test_no_warning_when_state_and_params_are_the_same(self, desc: ElasticityDesc, _nncf_caplog):\n old_builder = desc.create_builder()\n old_state = old_builder.get_state()\n\n new_params = desc.params.copy()\n new_builder = desc.create_builder_with_config(new_params)\n new_builder.load_state(old_state)\n\n assert not _nncf_caplog.records\n\n\nLIST_LOAD_STATE_DESCS = [\n COMMON_DEPTH_BASIC_DESC,\n *COMMON_WIDTH_STATE_DESCS,\n COMMON_KERNEL_DESC\n]\n\n\[email protected]('desc', LIST_LOAD_STATE_DESCS, ids=map(str, LIST_LOAD_STATE_DESCS))\ndef test_can_load_handler_state(desc: ElasticityDesc):\n model = desc.model_cls()\n move_model_to_cuda_if_available(model)\n model_copy = deepcopy(model)\n device = next(iter(model.parameters())).device\n dummy_input = torch.ones(model.INPUT_SIZE).to(device)\n\n input_size = desc.input_size\n if not input_size:\n input_size = model.INPUT_SIZE\n config = get_empty_config(input_sample_sizes=input_size)\n old_nncf_network = create_nncf_network(model, config)\n old_builder = desc.create_builder()\n old_handler = old_builder.build(old_nncf_network)\n elastic_model = build_elastic_model_from_handler(old_nncf_network, old_handler)\n old_handler.activate_minimum_subnet()\n old_output = elastic_model(dummy_input)\n ref_output = desc.ref_output_fn(model, dummy_input)\n assert torch.allclose(old_output, ref_output)\n\n new_nncf_network = create_nncf_network(model_copy, config)\n builder_state = old_builder.get_state()\n # no need in config to restore builder state\n new_builder = desc.create_builder_with_config({})\n\n new_builder.load_state(builder_state)\n new_handler = new_builder.build(new_nncf_network)\n elastic_model = build_elastic_model_from_handler(new_nncf_network, new_handler)\n new_handler.activate_minimum_subnet()\n new_output = elastic_model(dummy_input)\n assert torch.allclose(old_output, new_output)\n",
"\"\"\"\n Copyright (c) 2022 Intel Corporation\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 http://www.apache.org/licenses/LICENSE-2.0\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 os\nfrom typing import List\nfrom typing import Optional\n\nimport numpy as np\nimport onnx\n\nfrom nncf.experimental.post_training.compression_builder import CompressionBuilder\nfrom nncf.experimental.post_training.algorithms.quantization import PostTrainingQuantization\nfrom nncf.experimental.post_training.algorithms.quantization import PostTrainingQuantizationParameters\nfrom nncf.common.utils.logger import logger as nncf_logger\n\nfrom openvino.tools.accuracy_checker.config import ConfigReader\nfrom openvino.tools.accuracy_checker.argparser import build_arguments_parser\nfrom openvino.tools.accuracy_checker.dataset import Dataset\nfrom openvino.tools.accuracy_checker.evaluators import ModelEvaluator\n\nfrom nncf.experimental.post_training.api import dataset as ptq_api_dataset\n\n\n#pylint: disable=redefined-outer-name\nclass OpenVINOAccuracyCheckerDataset(ptq_api_dataset.Dataset):\n def __init__(self, model_evaluator: ModelEvaluator, batch_size, shuffle):\n super().__init__(batch_size, shuffle)\n self.model_evaluator = model_evaluator\n\n def __getitem__(self, item):\n _, batch_annotation, batch_input, _ = self.model_evaluator.dataset[item]\n filled_inputs, _, _ = self.model_evaluator._get_batch_input(\n batch_annotation, batch_input)\n\n assert len(filled_inputs) == 1\n dummy_target = 0\n\n for _, v in filled_inputs[0].items():\n return np.squeeze(v, axis=0), dummy_target\n\n raise RuntimeError(\"filled_inputs has no value.\")\n\n def __len__(self):\n return len(self.model_evaluator.dataset)\n\n\ndef run(onnx_model_path: str, output_model_path: str, dataset: Dataset,\n ignored_scopes: Optional[List[str]] = None, evaluate: Optional[bool] = False):\n\n num_init_samples = len(dataset)\n\n nncf_logger.info(\"Post-Training Quantization Parameters:\")\n nncf_logger.info(f\" number of samples: {num_init_samples}\")\n nncf_logger.info(f\" ignored_scopes: {ignored_scopes}\")\n onnx.checker.check_model(onnx_model_path)\n original_model = onnx.load(onnx_model_path)\n nncf_logger.info(f\"The model is loaded from {onnx_model_path}\")\n\n # Step 1: Create a pipeline of compression algorithms.\n builder = CompressionBuilder()\n\n # Step 2: Create the quantization algorithm and add to the builder.\n quantization_parameters = PostTrainingQuantizationParameters(\n number_samples=num_init_samples,\n ignored_scopes=ignored_scopes\n )\n quantization = PostTrainingQuantization(quantization_parameters)\n builder.add_algorithm(quantization)\n\n # Step 4: Execute the pipeline.\n nncf_logger.info(\"Post-Training Quantization has just started!\")\n quantized_model = builder.apply(original_model, dataset)\n\n # Step 5: Save the quantized model.\n onnx.save(quantized_model, output_model_path)\n nncf_logger.info(\n \"The quantized model is saved on {}\".format(output_model_path))\n\n onnx.checker.check_model(output_model_path)\n\n\nif __name__ == '__main__':\n parser = build_arguments_parser()\n parser.add_argument(\"--output-model-dir\", \"-o\",\n help=\"Directory path to save output quantized ONNX model\", type=str)\n args = parser.parse_args()\n config, mode = ConfigReader.merge(args)\n\n assert mode == \"models\"\n for config_entry in config[mode]:\n model_evaluator = ModelEvaluator.from_configs(config_entry)\n assert \"datasets\" in config_entry\n assert len(config_entry[\"datasets\"]\n ) == 1, \"Config should have one dataset.\"\n\n dataset_config = config_entry[\"datasets\"][0]\n dataset = OpenVINOAccuracyCheckerDataset(\n model_evaluator, batch_size=1, shuffle=True)\n\n assert \"launchers\" in config_entry\n assert len(config_entry[\"launchers\"]) == 1\n\n onnx_model_path = config_entry[\"launchers\"][0][\"model\"]\n\n fname = onnx_model_path.stem\n output_model_path = os.path.join(\n args.output_model_dir, fname + \"-quantized.onnx\")\n\n onnx_model_path = str(onnx_model_path)\n run(onnx_model_path,\n output_model_path,\n dataset\n )\n"
] | [
[
"torch.allclose",
"torch.ones"
],
[
"numpy.squeeze"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
baba1587/jax | [
"cb77f2a22de49e85da93f43b7dc448aa238d5207"
] | [
"jax/lax/lax.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 builtins\nimport collections\nimport enum\nimport functools\nimport itertools\nimport operator\nimport string\nfrom typing import (Any, Callable, List, NamedTuple, Optional, Sequence, Union,\n Tuple, Type)\nimport warnings\n\nimport numpy as onp\n\nfrom ..util import partial, prod\n\nfrom .. import core\nfrom .. import ad_util\nfrom .. import api\nfrom .. import linear_util as lu\nfrom .. import dtypes\nfrom .. import lazy\nfrom .. import lib\nfrom ..config import flags\nfrom ..core import Primitive\nfrom ..abstract_arrays import (UnshapedArray, ShapedArray, ConcreteArray,\n AbstractToken, array_types, make_shaped_array,\n raise_to_shaped, abstract_token, canonicalize_shape)\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 ..util import curry, cache, safe_zip, unzip2, prod\nfrom ..tree_util import build_tree, tree_unflatten, tree_map\nfrom ..lib import pytree\nfrom ..lib import xla_bridge\nfrom ..lib import xla_client\n\nxb = xla_bridge\nxc = xla_client\nxops = xla_client.ops\n\nFLAGS = flags.FLAGS\n\n_max = builtins.max\n_min = builtins.max\n_reduce = functools.reduce\n\nArray = Any\nDType = Any\nShape = Sequence[int]\n\n@cache()\ndef broadcast_shapes(*shapes):\n \"\"\"Returns the shape that results from NumPy broadcasting of `shapes`.\"\"\"\n if len(shapes) == 1:\n return shapes[0]\n ndim = _max(len(shape) for shape in shapes)\n shapes = onp.array([(1,) * (ndim - len(shape)) + shape for shape in shapes])\n is_zero = onp.any(shapes == 0, axis=0)\n max_shape = onp.max(shapes, axis=0)\n result_shape = onp.where(is_zero, 0, max_shape)\n if not onp.all((shapes == result_shape) | (shapes == 1)):\n raise ValueError(\"Incompatible shapes for broadcasting: {}\"\n .format(tuple(map(tuple, shapes))))\n return canonicalize_shape(result_shape)\n\ndef _identity(x): return x\n\n### traceables\n\ndef neg(x: Array) -> Array:\n r\"\"\"Elementwise negation: :math:`-x`.\"\"\"\n return neg_p.bind(x)\n\ndef sign(x: Array) -> Array:\n r\"\"\"Elementwise sign.\n\n For floating-point inputs, returns\n :math:`\\mathrm{sign}(x) = \\begin{cases}\n -1 & x < 0\\\\\n -0 & x = -0\\\\\n \\mathit{NaN} & x = \\mathit{NaN}\\\\\n +0 & x = +0\\\\\n 1 & x > 0\n \\end{cases}`\n\n For signed integer inputs, returns\n :math:`\\mathrm{sign}(x) = \\begin{cases}\n -1 & x < 0\\\\\n 0 & x = 0\\\\\n 1 & x > 0\n \\end{cases}`\n\n For complex inputs, returns the complex phase, i.e.\n :math:`\\mathrm{sign}(x) = \\frac{x}{|x|}`.\n \"\"\"\n return sign_p.bind(x)\n\ndef nextafter(x1: Array, x2: Array) -> Array:\n r\"\"\"Returns the next representable value after `x1` in the direction of `x2`.\"\"\"\n return nextafter_p.bind(_brcast(x1, x2), _brcast(x2, x1))\n\ndef floor(x: Array) -> Array:\n r\"\"\"Elementwise floor: :math:`\\left\\lfloor x \\right\\rfloor`.\"\"\"\n return floor_p.bind(x)\n\ndef ceil(x: Array) -> Array:\n r\"\"\"Elementwise ceiling: :math:`\\left\\lceil x \\right\\rceil`.\"\"\"\n return ceil_p.bind(x)\n\ndef round(x: Array) -> Array:\n r\"\"\"Elementwise round.\n\n Rounds values to the nearest integer. Halfway values (e.g., `0.5`) are rounded\n away from zero.\"\"\"\n return round_p.bind(x)\n\ndef is_finite(x: Array) -> Array:\n r\"\"\"Elementwise :math:`\\mathrm{isfinite}`.\n\n For each element x returns `True` if and only if x is not :math:`\\pm\\infty` or\n :math:`\\mathit{NaN}`.\n \"\"\"\n return is_finite_p.bind(x)\n\ndef exp(x: Array) -> Array:\n r\"\"\"Elementwise exponential: :math:`e^x`.\"\"\"\n return exp_p.bind(x)\n\ndef expm1(x: Array) -> Array:\n r\"\"\"Elementwise :math:`e^{x} - 1`.\"\"\"\n return expm1_p.bind(x)\n\ndef log(x: Array) -> Array:\n r\"\"\"Elementwise natural logarithm: :math:`\\mathrm{log}(x)`.\"\"\"\n return log_p.bind(x)\n\ndef log1p(x: Array) -> Array:\n r\"\"\"Elementwise :math:`\\mathrm{log}(1 + x)`.\"\"\"\n return log1p_p.bind(x)\n\ndef tanh(x: Array) -> Array:\n r\"\"\"Elementwise hyperbolic tangent: :math:`\\mathrm{tanh}(x)`.\"\"\"\n return tanh_p.bind(x)\n\ndef sin(x: Array) -> Array:\n r\"\"\"Elementwise sine: :math:`\\mathrm{sin}(x)`.\"\"\"\n return sin_p.bind(x)\n\ndef cos(x: Array) -> Array:\n r\"\"\"Elementwise cosine: :math:`\\mathrm{cos}(x)`.\"\"\"\n return cos_p.bind(x)\n\ndef atan2(x: Array, y: Array) -> Array:\n r\"\"\"Elementwise arc tangent of two variables:\n :math:`\\mathrm{atan}({x \\over y})`.\"\"\"\n return atan2_p.bind(x, y)\n\ndef betainc(a: Array, b: Array, x: Array) -> Array:\n r\"\"\"Elementwise regularized incomplete beta integral.\"\"\"\n return regularized_incomplete_beta_p.bind(a, b, x)\n\ndef lgamma(x: Array) -> Array:\n r\"\"\"Elementwise log gamma: :math:`\\mathrm{log}(\\Gamma(x))`.\"\"\"\n return lgamma_p.bind(x)\n\ndef digamma(x: Array) -> Array:\n r\"\"\"Elementwise digamma: :math:`\\psi(x)`.\"\"\"\n return digamma_p.bind(x)\n\ndef igamma(a: Array, x: Array) -> Array:\n r\"\"\"Elementwise regularized incomplete gamma function.\"\"\"\n return igamma_p.bind(a, x)\n\ndef igammac(a: Array, x: Array) -> Array:\n r\"\"\"Elementwise complementary regularized incomplete gamma function.\"\"\"\n return igammac_p.bind(a, x)\n\ndef igamma_grad_a(a: Array, x: Array) -> Array:\n r\"\"\"Elementwise derivative of the regularized incomplete gamma function.\"\"\"\n return igamma_grad_a_p.bind(a, x)\n\ndef bessel_i0e(x: Array) -> Array:\n r\"\"\"Exponentially scaled modified Bessel function of order 0:\n :math:`\\mathrm{i0e}(x) = e^{-|x|} \\mathrm{i0}(x)`\n \"\"\"\n return bessel_i0e_p.bind(x)\n\ndef bessel_i1e(x: Array) -> Array:\n r\"\"\"Exponentially scaled modified Bessel function of order 1:\n :math:`\\mathrm{i1e}(x) = e^{-|x|} \\mathrm{i1}(x)`\n \"\"\"\n return bessel_i1e_p.bind(x)\n\ndef erf(x: Array) -> Array:\n r\"\"\"Elementwise error function: :math:`\\mathrm{erf}(x)`.\"\"\"\n return erf_p.bind(x)\n\ndef erfc(x: Array) -> Array:\n r\"\"\"Elementwise complementary error function:\n :math:`\\mathrm{erfc}(x) = 1 - \\mathrm{erf}(x)`.\"\"\"\n return erfc_p.bind(x)\n\ndef erf_inv(x: Array) -> Array:\n r\"\"\"Elementwise inverse error function: :math:`\\mathrm{erf}^{-1}(x)`.\"\"\"\n return erf_inv_p.bind(x)\n\ndef real(x: Array) -> Array:\n r\"\"\"Elementwise extract real part: :math:`\\mathrm{Re}(x)`.\n\n Returns the real part of a complex number.\n \"\"\"\n return real_p.bind(x)\n\ndef imag(x: Array) -> Array:\n r\"\"\"Elementwise extract imaginary part: :math:`\\mathrm{Im}(x)`.\n\n Returns the imaginary part of a complex number.\n \"\"\"\n return imag_p.bind(x)\n\ndef complex(x: Array, y: Array) -> Array:\n r\"\"\"Elementwise make complex number: :math:`x + jy`.\n\n Builds a complex number from real and imaginary parts.\n \"\"\"\n return complex_p.bind(_brcast(x, y), _brcast(y, x))\n\ndef conj(x: Array) -> Array:\n r\"\"\"Elementwise complex conjugate function: :math:`\\overline{x}`.\"\"\"\n return conj_p.bind(x, input_dtype=_dtype(x))\n\ndef abs(x: Array) -> Array:\n r\"\"\"Elementwise absolute value: :math:`|x|`.\"\"\"\n return abs_p.bind(x)\n\ndef pow(x: Array, y: Array) -> Array:\n r\"\"\"Elementwise power: :math:`x^y`.\"\"\"\n return pow_p.bind(x, y)\n\ndef integer_pow(x: Array, y: int) -> Array:\n r\"\"\"Elementwise power: :math:`x^y`, where :math:`y` is a fixed integer.\"\"\"\n if y == 0:\n return _ones(x)\n elif y == 1:\n return x\n else:\n return integer_pow_p.bind(x, y=y)\n\ndef sqrt(x: Array) -> Array:\n r\"\"\"Elementwise square root: :math:`\\sqrt{x}`.\"\"\"\n return sqrt_p.bind(x)\n\ndef rsqrt(x: Array) -> Array:\n r\"\"\"Elementwise reciprocal square root: :math:`1 \\over \\sqrt{x}.\"\"\"\n return rsqrt_p.bind(x)\n\ndef bitwise_not(x: Array) -> Array:\n r\"\"\"Elementwise NOT: :math:`\\neg x`.\"\"\"\n return not_p.bind(x)\n\ndef bitwise_and(x: Array, y: Array) -> Array:\n r\"\"\"Elementwise AND: :math:`x \\wedge y`.\"\"\"\n return and_p.bind(x, y)\n\ndef bitwise_or(x: Array, y: Array) -> Array:\n r\"\"\"Elementwise OR: :math:`x \\vee y`.\"\"\"\n return or_p.bind(x, y)\n\ndef bitwise_xor(x: Array, y: Array) -> Array:\n r\"\"\"Elementwise exclusive OR: :math:`x \\oplus y`.\"\"\"\n return xor_p.bind(x, y)\n\ndef population_count(x: Array) -> Array:\n r\"\"\"Elementwise popcount, count the number of set bits in each element.\"\"\"\n return population_count_p.bind(x)\n\ndef add(x: Array, y: Array) -> Array:\n r\"\"\"Elementwise addition: :math:`x + y`.\"\"\"\n return add_p.bind(x, y)\n\ndef sub(x: Array, y: Array) -> Array:\n r\"\"\"Elementwise subtraction: :math:`x - y`.\"\"\"\n return sub_p.bind(x, y)\n\ndef mul(x: Array, y: Array) -> Array:\n r\"\"\"Elementwise multiplication: :math:`x \\times y`.\"\"\"\n return mul_p.bind(x, y)\n\ndef div(x: Array, y: Array) -> Array:\n r\"\"\"Elementwise division: :math:`x \\over y`.\"\"\"\n return div_p.bind(x, y)\n\ndef rem(x: Array, y: Array) -> Array:\n r\"\"\"Elementwise remainder: :math:`x \\bmod y`.\"\"\"\n return rem_p.bind(x, y)\n\ndef max(x: Array, y: Array) -> Array:\n r\"\"\"Elementwise maximum: :math:`\\mathrm{max}(x, y)`\n\n For complex numbers, uses a lexicographic comparison on the\n `(real, imaginary)` pairs.\"\"\"\n return max_p.bind(x, y)\n\ndef min(x: Array, y: Array) -> Array:\n r\"\"\"Elementwise minimum: :math:`\\mathrm{min}(x, y)`\n\n For complex numbers, uses a lexicographic comparison on the\n `(real, imaginary)` pairs.\"\"\"\n return min_p.bind(x, y)\n\ndef shift_left(x: Array, y: Array) -> Array:\n r\"\"\"Elementwise left shift: :math:`x \\ll y`.\"\"\"\n return shift_left_p.bind(x, y)\n\ndef shift_right_arithmetic(x: Array, y: Array) -> Array:\n r\"\"\"Elementwise arithmetic right shift: :math:`x \\gg y`.\"\"\"\n return shift_right_arithmetic_p.bind(x, y)\n\ndef shift_right_logical(x: Array, y: Array) -> Array:\n r\"\"\"Elementwise logical right shift: :math:`x \\gg y`.\"\"\"\n return shift_right_logical_p.bind(x, y)\n\ndef eq(x: Array, y: Array) -> Array:\n r\"\"\"Elementwise equals: :math:`x = y`.\"\"\"\n return eq_p.bind(x, y)\n\ndef ne(x: Array, y: Array) -> Array:\n r\"\"\"Elementwise not-equals: :math:`x \\neq y`.\"\"\"\n return ne_p.bind(x, y)\n\ndef ge(x: Array, y: Array) -> Array:\n r\"\"\"Elementwise greater-than-or-equals: :math:`x \\geq y`.\"\"\"\n return ge_p.bind(x, y)\n\ndef gt(x: Array, y: Array) -> Array:\n r\"\"\"Elementwise greater-than: :math:`x > y`.\"\"\"\n return gt_p.bind(x, y)\n\ndef le(x: Array, y: Array) -> Array:\n r\"\"\"Elementwise less-than-or-equals: :math:`x \\leq y`.\"\"\"\n return le_p.bind(x, y)\n\ndef lt(x: Array, y: Array) -> Array:\n r\"\"\"Elementwise less-than: :math:`x < y`.\"\"\"\n return lt_p.bind(x, y)\n\ndef convert_element_type(operand: Array, new_dtype: DType) -> Array:\n \"\"\"Elementwise cast.\n\n Wraps XLA's `ConvertElementType\n <https://www.tensorflow.org/xla/operation_semantics#convertelementtype>`_\n operator, which performs an elementwise conversion from one type to another.\n Similar to a C++ `static_cast`.\n\n Args:\n operand: an array or scalar value to be cast\n new_dtype: the new type. Should be a NumPy type.\n\n Returns:\n An array with the same shape as `operand`, cast elementwise to `new_dtype`.\n \"\"\"\n new_dtype = dtypes.canonicalize_dtype(new_dtype)\n # Avoids dropping precision by casting Python scalars to the default Jax\n # type. If we passed a Python scalar directly to the bind call below, it is\n # cast to the default type as part of the calling convention.\n if type(operand) in dtypes.python_scalar_dtypes:\n operand = onp.asarray(operand, new_dtype)\n old_dtype = dtypes.canonicalize_dtype(_dtype(operand))\n if old_dtype == new_dtype:\n return operand\n if (dtypes.issubdtype(old_dtype, onp.complexfloating) and\n not dtypes.issubdtype(new_dtype, onp.complexfloating)):\n msg = \"Casting complex values to real discards the imaginary part\"\n warnings.warn(msg, onp.ComplexWarning, stacklevel=2)\n return convert_element_type_p.bind(\n operand, new_dtype=new_dtype, old_dtype=old_dtype)\n\ndef bitcast_convert_type(operand: Array, new_dtype: DType) -> Array:\n \"\"\"Elementwise bitcast.\n\n Wraps XLA's `BitcastConvertType\n <https://www.tensorflow.org/xla/operation_semantics#bitcastconverttype>`_\n operator, which performs a bit cast from one type to another. The bitwidth\n of the source and destination types must match.\n\n Args:\n operand: an array or scalar value to be cast\n new_dtype: the new type. Should be a NumPy type.\n\n Returns:\n An array with the same shape as `operand`, bitcast elementwise to\n `new_dtype`.\n \"\"\"\n new_dtype = dtypes.canonicalize_dtype(new_dtype)\n old_dtype = _dtype(operand)\n if old_dtype != new_dtype:\n return bitcast_convert_type_p.bind(operand, new_dtype=new_dtype)\n else:\n return operand\n\ndef clamp(min: Array, x: Array, max: Array) -> Array:\n r\"\"\"Elementwise clamp.\n\n Returns :math:`\\mathrm{clamp}(x) = \\begin{cases}\n \\mathit{min} & \\text{if } x < \\mathit{min},\\\\\n \\mathit{max} & \\text{if } x > \\mathit{max},\\\\\n x & \\text{otherwise}\n \\end{cases}`.\n \"\"\"\n return clamp_p.bind(min, x, max)\n\ndef concatenate(operands: Sequence[Array], dimension: int) -> Array:\n \"\"\"Concatenates a sequence of arrays along `dimension`.\n\n Wraps XLA's `Concatenate\n <https://www.tensorflow.org/xla/operation_semantics#concatenate>`_\n operator.\n\n Args:\n operands: a sequence of arrays to concatenate. The arrays must have equal\n shapes, except in the `dimension` axis.\n dimension: the dimension along which to concatenate the arrays.\n\n Returns:\n An array containing the concatenation.\n \"\"\"\n return concatenate_p.bind(*operands, dimension=dimension)\n\nPrecision = xla_client.PrecisionConfig.Precision\nPrecision.__str__ = lambda precision: precision.name\nPrecisionType = Any\n\nclass ConvDimensionNumbers(NamedTuple):\n \"\"\"Describes batch, spatial, and feature dimensions of a convolution.\n\n Args:\n lhs_spec: a tuple of nonnegative integer dimension numbers containing\n `(batch dimension, feature dimension, spatial dimensions...)`.\n rhs_spec: a tuple of nonnegative integer dimension numbers containing\n `(out feature dimension, in feature dimension, spatial dimensions...)`.\n out_spec: a tuple of nonnegative integer dimension numbers containing\n `(batch dimension, feature dimension, spatial dimensions...)`.\n \"\"\"\n lhs_spec: Sequence[int]\n rhs_spec: Sequence[int]\n out_spec: Sequence[int]\n\nConvGeneralDilatedDimensionNumbers = Union[\n None, ConvDimensionNumbers, Tuple[str, str, str]]\n\ndef conv_general_dilated(\n lhs: Array, rhs: Array, window_strides: Sequence[int],\n padding: Union[str, Sequence[Tuple[int, int]]],\n lhs_dilation: Optional[Sequence[int]] = None,\n rhs_dilation: Optional[Sequence[int]] = None,\n dimension_numbers: ConvGeneralDilatedDimensionNumbers = None,\n feature_group_count: int = 1, batch_group_count: int = 1,\n precision: Optional[PrecisionType] = None) -> Array:\n \"\"\"General n-dimensional convolution operator, with optional dilation.\n\n Wraps XLA's `Conv\n <https://www.tensorflow.org/xla/operation_semantics#conv_convolution>`_\n operator.\n\n Args:\n lhs: a rank `n+2` dimensional input array.\n rhs: a rank `n+2` dimensional array of kernel weights.\n window_strides: a sequence of `n` integers, representing the inter-window\n strides.\n padding: either the string `'SAME'`, the string `'VALID'`, or a sequence of\n `n` `(low, high)` integer pairs that give the padding to apply before and\n after each spatial dimension.\n lhs_dilation: `None`, or a sequence of `n` integers, giving the\n dilation factor to apply in each spatial dimension of `lhs`. LHS dilation\n is also known as transposed convolution.\n rhs_dilation: `None`, or a sequence of `n` integers, giving the\n dilation factor to apply in each spatial dimension of `rhs`. RHS dilation\n is also known as atrous convolution.\n dimension_numbers: either `None`, a `ConvDimensionNumbers` object, or\n a 3-tuple `(lhs_spec, rhs_spec, out_spec)`, where each element is a string\n of length `n+2`.\n feature_group_count: integer, default 1. See XLA HLO docs.\n batch_group_count: integer, default 1. See XLA HLO docs.\n precision: Optional. Either `None`, which means the default precision for\n the backend, or a `Precision` enum value.\n\n Returns:\n An array containing the convolution result.\n\n In the string case of `dimension_numbers`, each character identifies by\n position:\n\n - the batch dimensions in `lhs`, `rhs`, and the output with the character\n 'N',\n - the feature dimensions in `lhs` and the output with the character 'C',\n - the input and output feature dimensions in rhs with the characters 'I'\n and 'O' respectively, and\n - spatial dimension correspondences between lhs, rhs, and the output using\n any distinct characters.\n\n For example, to indicate dimension numbers consistent with the `conv` function\n with two spatial dimensions, one could use `('NCHW', 'OIHW', 'NCHW')`. As\n another example, to indicate dimension numbers consistent with the TensorFlow\n Conv2D operation, one could use `('NHWC', 'HWIO', 'NHWC')`. When using the\n latter form of convolution dimension specification, window strides are\n associated with spatial dimension character labels according to the order in\n which the labels appear in the `rhs_spec` string, so that `window_strides[0]`\n is matched with the dimension corresponding to the first character\n appearing in rhs_spec that is not `'I'` or `'O'`.\n\n If `dimension_numbers` is `None`, the default is `('NCHW', 'OIHW', 'NCHW')`\n (for a 2D convolution).\n \"\"\"\n dnums: ConvDimensionNumbers\n dnums = conv_dimension_numbers(lhs.shape, rhs.shape, dimension_numbers)\n if lhs_dilation is None:\n lhs_dilation = (1,) * (lhs.ndim - 2)\n elif isinstance(padding, str) and not len(lhs_dilation) == lhs_dilation.count(1):\n raise ValueError(\n \"String padding is not implemented for transposed convolution \"\n \"using this op. Please either exactly specify the required padding or \"\n \"use conv_transpose.\")\n if rhs_dilation is None:\n rhs_dilation = (1,) * (rhs.ndim - 2)\n if isinstance(padding, str):\n lhs_perm, rhs_perm, _ = dnums\n rhs_shape = onp.take(rhs.shape, rhs_perm)[2:]\n effective_rhs_shape = [(k-1) * r + 1 for k, r in zip(rhs_shape, rhs_dilation)]\n padding = padtype_to_pads(\n onp.take(lhs.shape, lhs_perm)[2:], effective_rhs_shape,\n window_strides, padding)\n return conv_general_dilated_p.bind(\n lhs, rhs, window_strides=tuple(window_strides), padding=tuple(padding),\n lhs_dilation=tuple(lhs_dilation), rhs_dilation=tuple(rhs_dilation),\n dimension_numbers=dnums,\n feature_group_count=feature_group_count,\n batch_group_count=batch_group_count,\n lhs_shape=lhs.shape, rhs_shape=rhs.shape,\n precision=_canonicalize_precision(precision))\n\ndef dot(lhs: Array, rhs: Array, precision: Optional[PrecisionType] = None) -> Array:\n \"\"\"Vector/vector, matrix/vector, and matrix/matrix multiplication.\n\n Wraps XLA's `Dot\n <https://www.tensorflow.org/xla/operation_semantics#dot>`_\n operator.\n\n For more general contraction, see the `dot_general` operator.\n\n Args:\n lhs: an array of rank 1 or 2.\n rhs: an array of rank 1 or 2.\n precision: Optional. Either `None`, which means the default precision for\n the backend, or a `Precision` enum value.\n\n Returns:\n An array containing the product.\n \"\"\"\n if 1 <= lhs.ndim <= 2 and 1 <= rhs.ndim <= 2 and lhs.shape[-1] == rhs.shape[0]:\n return dot_general(lhs, rhs, (((lhs.ndim - 1,), (0,)), ((), ())),\n precision=precision)\n else:\n raise TypeError(\"Incompatible shapes for dot: got {} and {}.\".format(\n lhs.shape, rhs.shape))\n\n\nDotDimensionNumbers = Tuple[Tuple[Sequence[int], Sequence[int]],\n Tuple[Sequence[int], Sequence[int]]]\n\ndef dot_general(lhs: Array, rhs: Array, dimension_numbers: DotDimensionNumbers,\n precision: Optional[PrecisionType] = None) -> Array:\n \"\"\"More general contraction operator.\n\n Wraps XLA's `DotGeneral\n <https://www.tensorflow.org/xla/operation_semantics#dotgeneral>`_\n operator.\n\n Args:\n lhs: an array\n rhs: an array\n dimension_numbers: a tuple of tuples of the form\n `((lhs_contracting_dims, rhs_contracting_dims),\n (lhs_batch_dims, rhs_batch_dims))`\n precision: Optional. Either `None`, which means the default precision for\n the backend, or a `Precision` enum value.\n\n Returns:\n An array containing the result.\n \"\"\"\n contract_dims_seq, batch_dims_seq = dimension_numbers\n contract_dims = tuple(map(lambda x: tuple(x), contract_dims_seq))\n batch_dims = tuple(map(lambda x: tuple(x), batch_dims_seq))\n if not dtypes.issubdtype(lhs.dtype, onp.inexact):\n # TODO(b/134526360): XLA doesn't support bool or integer dots, so we emit a\n # sum of products instead.\n lhs_contract_dims, rhs_contract_dims = contract_dims\n lhs_batch_dims, rhs_batch_dims = batch_dims\n lhs_noncontract_dims = tuple(sorted(\n set(range(onp.ndim(lhs))) - set(lhs_batch_dims) - set(lhs_contract_dims)))\n rhs_noncontract_dims = tuple(sorted(\n set(range(onp.ndim(rhs))) - set(rhs_batch_dims) - set(rhs_contract_dims)))\n lhs = transpose(lhs,\n lhs_batch_dims + lhs_noncontract_dims + lhs_contract_dims)\n rhs = transpose(rhs,\n rhs_batch_dims + rhs_noncontract_dims + rhs_contract_dims)\n new_lhs_shape = onp.insert(onp.array(onp.shape(lhs), dtype=onp.int64),\n len(lhs_batch_dims) + len(lhs_noncontract_dims),\n (1,) * len(rhs_noncontract_dims))\n new_rhs_shape = onp.insert(onp.array(onp.shape(rhs), dtype=onp.int64),\n len(lhs_batch_dims),\n (1,) * len(lhs_noncontract_dims))\n lhs = reshape(lhs, new_lhs_shape)\n rhs = reshape(rhs, new_rhs_shape)\n out_ndim = (len(lhs_batch_dims) + len(lhs_noncontract_dims) +\n len(rhs_noncontract_dims))\n op_product = bitwise_and if lhs.dtype == onp.bool_ else mul\n op_sum = bitwise_or if lhs.dtype == onp.bool_ else add\n return reduce(op_product(lhs, rhs), _zero(lhs), op_sum,\n tuple(range(out_ndim, out_ndim + len(lhs_contract_dims))))\n\n return dot_general_p.bind(lhs, rhs,\n dimension_numbers=(contract_dims, batch_dims),\n precision=_canonicalize_precision(precision))\n\ndef broadcast(operand: Array, sizes: Sequence[int]) -> Array:\n \"\"\"Broadcasts an array, adding new major dimensions.\n\n Wraps XLA's `Broadcast\n <https://www.tensorflow.org/xla/operation_semantics#broadcast>`_\n operator.\n\n Args:\n operand: an array\n sizes: a sequence of integers, giving the sizes of new major dimensions\n to add.\n\n Returns:\n An array containing the result.\n \"\"\"\n dims = tuple(range(len(sizes), len(sizes) + onp.ndim(operand)))\n return broadcast_in_dim(operand, tuple(sizes) + onp.shape(operand), dims)\n\ndef broadcast_in_dim(operand: Array, shape: Shape,\n broadcast_dimensions: Sequence[int]) -> Array:\n \"\"\"Wraps XLA's `BroadcastInDim\n <https://www.tensorflow.org/xla/operation_semantics#broadcastindim>`_\n operator.\n \"\"\"\n shape = _broadcast_in_dim_shape_rule(\n operand, shape=shape, broadcast_dimensions=broadcast_dimensions)\n if onp.ndim(operand) == len(shape) and not len(broadcast_dimensions):\n return operand\n return broadcast_in_dim_p.bind(\n operand, shape=tuple(shape),\n broadcast_dimensions=tuple(broadcast_dimensions))\n\ndef broadcast_to_rank(x: Array, rank: int) -> Array:\n \"\"\"Adds leading dimensions of ``1`` to give ``x`` rank ``rank``.\"\"\"\n return broadcast(x, (1,) * (rank - x.ndim))\n\ndef reshape(operand: Array, new_sizes: Shape,\n dimensions: Optional[Sequence[int]] = None) -> Array:\n \"\"\"Wraps XLA's `Reshape\n <https://www.tensorflow.org/xla/operation_semantics#reshape>`_\n operator.\n \"\"\"\n new_sizes = canonicalize_shape(new_sizes) # TODO\n new_sizes = tuple(new_sizes)\n same_shape = onp.shape(operand) == new_sizes\n same_dims = dimensions is None or tuple(dimensions) == tuple(range(onp.ndim(operand)))\n if onp.shape(operand) and same_shape and same_dims:\n return operand\n else:\n return reshape_p.bind(\n operand, new_sizes=new_sizes,\n dimensions=None if dimensions is None or same_dims else tuple(dimensions))\n\ndef pad(operand: Array, padding_value: Array,\n padding_config: Sequence[Tuple[int, int, int]]) -> Array:\n \"\"\"Wraps XLA's `Pad\n <https://www.tensorflow.org/xla/operation_semantics#pad>`_\n operator.\n \"\"\"\n return pad_p.bind(operand, padding_value, padding_config=tuple(padding_config))\n\ndef rev(operand: Array, dimensions: Sequence[int]) -> Array:\n \"\"\"Wraps XLA's `Rev\n <https://www.tensorflow.org/xla/operation_semantics#rev_reverse>`_\n operator.\n \"\"\"\n return rev_p.bind(operand, dimensions=tuple(dimensions))\n\ndef select(pred: Array, on_true: Array, on_false: Array) -> Array:\n \"\"\"Wraps XLA's `Select\n <https://www.tensorflow.org/xla/operation_semantics#select>`_\n operator.\n \"\"\"\n return select_p.bind(pred, on_true, on_false)\n\ndef slice(operand: Array, start_indices: Sequence[int],\n limit_indices: Sequence[int],\n strides: Optional[Sequence[int]] = None) -> Array:\n \"\"\"Wraps XLA's `Slice\n <https://www.tensorflow.org/xla/operation_semantics#slice>`_\n operator.\n \"\"\"\n if (onp.all(onp.equal(start_indices, 0))\n and onp.all(onp.equal(limit_indices, operand.shape))\n and strides is None):\n return operand\n else:\n return slice_p.bind(operand, start_indices=tuple(start_indices),\n limit_indices=tuple(limit_indices),\n strides=None if strides is None else tuple(strides))\n\ndef dynamic_slice(operand: Array, start_indices: Sequence[Array],\n slice_sizes: Shape) -> Array:\n \"\"\"Wraps XLA's `DynamicSlice\n <https://www.tensorflow.org/xla/operation_semantics#dynamicslice>`_\n operator.\n\n Args:\n operand: an array to slice.\n start_indices: a list of scalar indices, one per dimension.\n slice_sizes: the size of the slice. Must be a sequence of non-negative\n integers with length equal to `ndim(operand)`.\n\n Returns:\n An array containing the slice.\n \"\"\"\n start_indices = _dynamic_slice_indices(operand, start_indices)\n return dynamic_slice_p.bind(operand, *start_indices,\n slice_sizes=tuple(slice_sizes))\n\ndef dynamic_update_slice(operand: Array, update: Array,\n start_indices: Array) -> Array:\n \"\"\"Wraps XLA's `DynamicUpdateSlice\n <https://www.tensorflow.org/xla/operation_semantics#dynamicupdateslice>`_\n operator.\n\n Args:\n operand: an array to slice.\n update: an array containing the new values to write onto `operand`.\n start_indices: a list of scalar indices, one per dimension.\n\n Returns:\n An array containing the slice.\n \"\"\"\n start_indices = _dynamic_slice_indices(operand, start_indices)\n return dynamic_update_slice_p.bind(operand, update, *start_indices)\n\n\nclass GatherDimensionNumbers(NamedTuple):\n \"\"\"\n Describes the dimension number arguments to an `XLA's Gather operator\n <https://www.tensorflow.org/xla/operation_semantics#gather>`_. See the XLA\n documentation for more details of what the dimension numbers mean.\n\n Args:\n offset_dims: the set of dimensions in the `gather` output that offset into\n an array sliced from `operand`. Must be a tuple of integers in ascending\n order, each representing a dimension number of the output.\n collapsed_slice_dims: the set of dimensions `i` in `operand` that have\n `slice_sizes[i] == 1` and that should not have a corresponding dimension\n in the output of the gather. Must be a tuple of integers in ascending\n order.\n start_index_map: for each dimension in `start_indices`, gives the\n corresponding dimension in `operand` that is to be sliced. Must be a\n tuple of integers with size equal to `start_indices.shape[-1]`.\n\n Unlike XLA's `GatherDimensionNumbers` structure, `index_vector_dim` is\n implicit; there is always an index vector dimension and it must always be the\n last dimension. To gather scalar indices, add a trailing dimension of size 1.\n \"\"\"\n offset_dims: Sequence[int]\n collapsed_slice_dims: Sequence[int]\n start_index_map: Sequence[int]\n\n\ndef gather(operand: Array, start_indices: Array,\n dimension_numbers: GatherDimensionNumbers,\n slice_sizes: Shape) -> Array:\n \"\"\"Gather operator.\n\n Wraps `XLA's Gather operator\n <https://www.tensorflow.org/xla/operation_semantics#gather>`_.\n\n The semantics of gather are complicated, and its API might change in the\n future. For most use cases, you should prefer `Numpy-style indexing\n <https://docs.scipy.org/doc/numpy-1.16.0/reference/arrays.indexing.html>`_\n (e.g., `x[:, (1,4,7), ...]`), rather than using `gather` directly.\n\n Args:\n operand: an array from which slices should be taken\n start_indices: the indices at which slices should be taken\n dimension_numbers: a `lax.GatherDimensionNumbers` object that describes\n how dimensions of `operand`, `start_indices` and the output relate.\n slice_sizes: the size of each slice. Must be a sequence of non-negative\n integers with length equal to `ndim(operand)`.\n\n Returns:\n An array containing the gather output.\n \"\"\"\n return gather_p.bind(\n operand, start_indices, dimension_numbers=dimension_numbers,\n slice_sizes=canonicalize_shape(slice_sizes))\n\n\nclass ScatterDimensionNumbers(NamedTuple):\n \"\"\"\n Describes the dimension number arguments to an `XLA's Scatter operator\n <https://www.tensorflow.org/xla/operation_semantics#scatter>`_. See the XLA\n documentation for more details of what the dimension numbers mean.\n\n Args:\n update_window_dims: the set of dimensions in the `updates` that are window\n dimensions. Must be a tuple of integers in ascending\n order, each representing a dimension number.\n inserted_window_dims: the set of size 1 window dimensions that must be inserted\n into the shape of `updates`. Must be a tuple of integers in ascending\n order, each representing a dimension number of the output. These are the\n mirror image of `collapsed_slice_dims` in the case of `gather`.\n scatter_dims_to_operand_dims: for each dimension in `scatter_indices`, gives\n the corresponding dimension in `operand`. Must be a sequence of integers\n with size equal to indices.shape[-1].\n\n Unlike XLA's `ScatterDimensionNumbers` structure, `index_vector_dim` is\n implicit; there is always an index vector dimension and it must always be the\n last dimension. To scatter scalar indices, add a trailing dimension of size 1.\n \"\"\"\n update_window_dims: Sequence[int]\n inserted_window_dims: Sequence[int]\n scatter_dims_to_operand_dims: Sequence[int]\n\ndef scatter_add(operand: Array, scatter_indices: Array, updates: Array,\n dimension_numbers: ScatterDimensionNumbers) -> Array:\n \"\"\"Scatter-add operator.\n\n Wraps `XLA's Scatter operator\n <https://www.tensorflow.org/xla/operation_semantics#scatter>`_, where\n addition is used to combine updates and values from `operand`.\n\n The semantics of scatter are complicated and its API is subject to change.\n\n Args:\n operand: an array to which the scatter should be applied\n scatter_indices: an array that gives the indices in `operand` to which each\n update in `updates` should be applied.\n updates: the updates that should be scattered onto `operand`.\n dimension_numbers: a `lax.ScatterDimensionNumbers` object that describes\n how dimensions of `operand`, `start_indices`, `updates` and the output\n relate.\n\n Returns:\n An array containing the sum of `operand` and the scattered updates.\n \"\"\"\n jaxpr, consts = _reduction_jaxpr(add, _abstractify(_const(operand, 0)))\n return scatter_add_p.bind(\n operand, scatter_indices, updates, update_jaxpr=jaxpr,\n update_consts=consts, dimension_numbers=dimension_numbers)\n\ndef scatter_mul(operand: Array, scatter_indices: Array, updates: Array,\n dimension_numbers: ScatterDimensionNumbers) -> Array:\n \"\"\"Scatter-multiply operator.\n\n Wraps `XLA's Scatter operator\n <https://www.tensorflow.org/xla/operation_semantics#scatter>`_, where\n multiplication is used to combine updates and values from `operand`.\n\n The semantics of scatter are complicated and its API is subject to change.\n\n Args:\n operand: an array to which the scatter should be applied\n scatter_indices: an array that gives the indices in `operand` to which each\n update in `updates` should be applied.\n updates: the updates that should be scattered onto `operand`.\n dimension_numbers: a `lax.ScatterDimensionNumbers` object that describes\n how dimensions of `operand`, `start_indices`, `updates` and the output\n relate.\n\n Returns:\n An array containing the sum of `operand` and the scattered updates.\n \"\"\"\n jaxpr, consts = _reduction_jaxpr(mul, _abstractify(_const(operand, 1)))\n return scatter_mul_p.bind(\n operand, scatter_indices, updates, update_jaxpr=jaxpr,\n update_consts=consts, dimension_numbers=dimension_numbers)\n\ndef scatter_min(operand: Array, scatter_indices: Array, updates: Array,\n dimension_numbers: ScatterDimensionNumbers) -> Array:\n \"\"\"Scatter-min operator.\n\n Wraps `XLA's Scatter operator\n <https://www.tensorflow.org/xla/operation_semantics#scatter>`_, where\n the `min` function is used to combine updates and values from `operand`.\n\n The semantics of scatter are complicated and its API is subject to change.\n\n Args:\n operand: an array to which the scatter should be applied\n scatter_indices: an array that gives the indices in `operand` to which each\n update in `updates` should be applied.\n updates: the updates that should be scattered onto `operand`.\n dimension_numbers: a `lax.ScatterDimensionNumbers` object that describes\n how dimensions of `operand`, `start_indices`, `updates` and the output\n relate.\n\n Returns:\n An array containing the sum of `operand` and the scattered updates.\n \"\"\"\n jaxpr, consts = _reduction_jaxpr(min, _abstractify(_const(operand, 0)))\n return scatter_min_p.bind(\n operand, scatter_indices, updates, update_jaxpr=jaxpr,\n update_consts=consts, dimension_numbers=dimension_numbers)\n\ndef scatter_max(operand: Array, scatter_indices: Array, updates: Array,\n dimension_numbers: ScatterDimensionNumbers) -> Array:\n \"\"\"Scatter-max operator.\n\n Wraps `XLA's Scatter operator\n <https://www.tensorflow.org/xla/operation_semantics#scatter>`_, where\n the `max` function is used to combine updates and values from `operand`.\n\n The semantics of scatter are complicated and its API is subject to change.\n\n Args:\n operand: an array to which the scatter should be applied\n scatter_indices: an array that gives the indices in `operand` to which each\n update in `updates` should be applied.\n updates: the updates that should be scattered onto `operand`.\n dimension_numbers: a `lax.ScatterDimensionNumbers` object that describes\n how dimensions of `operand`, `start_indices`, `updates` and the output\n relate.\n\n Returns:\n An array containing the sum of `operand` and the scattered updates.\n \"\"\"\n jaxpr, consts = _reduction_jaxpr(max, _abstractify(_const(operand, 0)))\n return scatter_max_p.bind(\n operand, scatter_indices, updates, update_jaxpr=jaxpr,\n update_consts=consts, dimension_numbers=dimension_numbers)\n\n# Define this outside of scatter to ensure cache hits.\n_scatter_reduction_computation = lambda x, y: y\n\ndef scatter(operand: Array, scatter_indices:Array, updates: Array,\n dimension_numbers: ScatterDimensionNumbers) -> Array:\n \"\"\"Scatter-update operator.\n\n Wraps `XLA's Scatter operator\n <https://www.tensorflow.org/xla/operation_semantics#scatter>`_, where updates\n replace values from `operand`.\n\n If multiple updates are performed to the same index of operand, they may be\n applied in any order.\n\n The semantics of scatter are complicated and its API is subject to change.\n\n Args:\n operand: an array to which the scatter should be applied\n scatter_indices: an array that gives the indices in `operand` to which each\n update in `updates` should be applied.\n updates: the updates that should be scattered onto `operand`.\n dimension_numbers: a `lax.ScatterDimensionNumbers` object that describes\n how dimensions of `operand`, `start_indices`, `updates` and the output\n relate.\n\n Returns:\n An array containing the sum of `operand` and the scattered updates.\n \"\"\"\n jaxpr, consts = _reduction_jaxpr(_scatter_reduction_computation,\n _abstractify(_const(operand, 0)))\n return scatter_p.bind(\n operand, scatter_indices, updates, update_jaxpr=jaxpr,\n update_consts=consts, dimension_numbers=dimension_numbers)\n\ndef index_take(src: Array, idxs: Array, axes: Sequence[int]) -> Array:\n indices = concatenate([reshape(i, [i.shape[0], 1]) for i in idxs], 1)\n indices = indices % onp.array([src.shape[ax] for ax in axes])\n slice_sizes = list(src.shape)\n for ax in axes:\n slice_sizes[ax] = 1\n offset_dims = tuple(range(1, src.ndim - indices.shape[1] + 1))\n dnums = GatherDimensionNumbers(\n offset_dims=offset_dims,\n collapsed_slice_dims=axes,\n start_index_map=axes)\n return gather(src, indices, dimension_numbers=dnums,\n slice_sizes=tuple(slice_sizes))\n\ndef transpose(operand: Array, permutation: Sequence[int]) -> Array:\n \"\"\"Wraps XLA's `Transpose\n <https://www.tensorflow.org/xla/operation_semantics#transpose>`_\n operator.\n \"\"\"\n permutation = tuple(permutation)\n if permutation == tuple(range(len(permutation))):\n return operand\n else:\n return transpose_p.bind(operand, permutation=permutation)\n\ndef reduce(operand: Array, init_value: Array, computation: Callable,\n dimensions: Sequence[int]) -> Array:\n \"\"\"Wraps XLA's `Reduce\n <https://www.tensorflow.org/xla/operation_semantics#reduce>`_\n operator.\n \"\"\"\n monoid_reducer = _get_monoid_reducer(computation, init_value)\n if monoid_reducer:\n return monoid_reducer(operand, dimensions)\n else:\n jaxpr, consts = _reduction_jaxpr(computation, _abstractify(init_value))\n return reduce_p.bind(operand, init_value, computation=computation,\n jaxpr=jaxpr, consts=consts, dimensions=tuple(dimensions))\n\n@cache()\ndef _reduction_jaxpr(computation, aval):\n pval = pe.PartialVal.unknown(aval)\n comp = lu.wrap_init(lambda x, y: (computation(x, y),))\n jaxpr, _, consts = pe.trace_to_jaxpr(comp, (pval, pval), instantiate=False)\n return jaxpr, consts\n\ndef _get_monoid_reducer(monoid_op: Callable, x: Array) -> Optional[Callable]:\n aval = core.get_aval(x)\n dtype = _dtype(x)\n if (type(aval) is ConcreteArray) and aval.shape == ():\n if monoid_op is add:\n return aval.val == 0 and _reduce_sum\n if monoid_op is mul:\n return aval.val == 1 and _reduce_prod\n elif monoid_op is bitwise_or and dtype == onp.bool_:\n return aval.val == _get_max_identity(dtype) and _reduce_or\n elif monoid_op is bitwise_and and dtype == onp.bool_:\n return aval.val == _get_min_identity(dtype) and _reduce_and\n elif monoid_op is max:\n return aval.val == _get_max_identity(dtype) and _reduce_max\n elif monoid_op is min:\n return aval.val == _get_min_identity(dtype) and _reduce_min\n return None\n\ndef _get_max_identity(dtype: DType) -> Array:\n if dtypes.issubdtype(dtype, onp.inexact):\n return onp.array(-onp.inf, dtype)\n elif dtypes.issubdtype(dtype, onp.integer):\n return onp.array(dtypes.iinfo(dtype).min, dtype)\n elif dtypes.issubdtype(dtype, onp.bool_):\n return onp.array(False, onp.bool_)\n\ndef _get_min_identity(dtype: DType) -> Array:\n if dtypes.issubdtype(dtype, onp.inexact):\n return onp.array(onp.inf, dtype)\n elif dtypes.issubdtype(dtype, onp.integer):\n return onp.array(dtypes.iinfo(dtype).max, dtype)\n elif dtypes.issubdtype(dtype, onp.bool_):\n return onp.array(True, onp.bool_)\n\ndef _reduce_sum(operand: Array, axes: Sequence[int]) -> Array:\n return reduce_sum_p.bind(operand, axes=tuple(axes))\n\ndef _reduce_prod(operand: Array, axes: Sequence[int]) -> Array:\n return reduce_prod_p.bind(operand, axes=tuple(axes))\n\ndef _reduce_max(operand: Array, axes: Sequence[int]) -> Array:\n return reduce_max_p.bind(operand, axes=tuple(axes))\n\ndef _reduce_min(operand: Array, axes: Sequence[int]) -> Array:\n return reduce_min_p.bind(operand, axes=tuple(axes))\n\ndef _reduce_or(operand: Array, axes: Sequence[int]) -> Array:\n return reduce_or_p.bind(operand, axes=tuple(axes))\n\ndef _reduce_and(operand: Array, axes: Sequence[int]) -> Array:\n return reduce_and_p.bind(operand, axes=tuple(axes))\n\ndef reduce_window(operand: Array, init_value: Array, computation: Callable,\n window_dimensions: Shape, window_strides: Sequence[int],\n padding: str) -> Array:\n \"\"\"Wraps XLA's `ReduceWindow\n <https://www.tensorflow.org/xla/operation_semantics#reducewindow>`_\n operator.\n \"\"\"\n monoid_reducer = _get_monoid_window_reducer(computation, init_value)\n if monoid_reducer:\n return monoid_reducer(operand, window_dimensions, window_strides, padding)\n else:\n jaxpr, consts = _reduction_jaxpr(computation, _abstractify(init_value))\n return reduce_window_p.bind(\n operand, init_value, jaxpr=jaxpr, consts=consts,\n window_dimensions=tuple(window_dimensions),\n window_strides=tuple(window_strides), padding=padding)\n\ndef _get_monoid_window_reducer(monoid_op: Callable, x: Array) -> Optional[Callable]:\n aval = core.get_aval(x)\n if (type(aval) is ConcreteArray) and aval.shape == ():\n if monoid_op is add:\n return aval.val == 0 and _reduce_window_sum\n elif monoid_op is max:\n return aval.val == _get_max_identity(aval.dtype) and _reduce_window_max\n elif monoid_op is min:\n return aval.val == _get_min_identity(aval.dtype) and _reduce_window_min\n return None\n\ndef _reduce_window_sum(operand: Array, window_dimensions: Shape,\n window_strides: Sequence[int], padding: str) -> Array:\n return reduce_window_sum_p.bind(\n operand, window_dimensions=tuple(window_dimensions),\n window_strides=tuple(window_strides), padding=padding)\n\ndef _reduce_window_prod(operand: Array, window_dimensions: Shape,\n window_strides: Sequence[int], padding: str) -> Array:\n init_value = _const(operand, 1)\n jaxpr, consts = _reduction_jaxpr(mul, _abstractify(init_value))\n return reduce_window_p.bind(\n operand, init_value, jaxpr=jaxpr, consts=consts,\n window_dimensions=tuple(window_dimensions),\n window_strides=tuple(window_strides), padding=padding)\n\ndef _reduce_window_max(operand: Array, window_dimensions: Shape,\n window_strides: Sequence[int], padding: str) -> Array:\n return reduce_window_max_p.bind(\n operand, window_dimensions=tuple(window_dimensions),\n window_strides=tuple(window_strides), padding=padding)\n\ndef _reduce_window_min(operand: Array, window_dimensions: Shape,\n window_strides: Sequence[int], padding: str) -> Array:\n return reduce_window_min_p.bind(\n operand, window_dimensions=tuple(window_dimensions),\n window_strides=tuple(window_strides), padding=padding)\n\ndef _select_and_scatter(operand: Array, select: Callable,\n window_dimensions: Shape, window_strides: Sequence[int],\n padding: str, source: Array, init_value: Array,\n scatter: Callable) -> Array:\n select_jaxpr, select_consts = _reduction_jaxpr(select, _abstractify(init_value))\n scatter_jaxpr, scatter_consts = _reduction_jaxpr(scatter, _abstractify(init_value))\n return select_and_scatter_p.bind(\n operand, source, init_value, select_jaxpr=select_jaxpr,\n select_consts=select_consts, scatter_jaxpr=scatter_jaxpr,\n scatter_consts=scatter_consts, window_dimensions=tuple(window_dimensions),\n window_strides=tuple(window_strides), padding=padding)\n\ndef _select_and_scatter_add(source: Array, operand: Array,\n select_prim: core.Primitive,\n window_dimensions: Shape,\n window_strides: Sequence[int],\n padding: str) -> Array:\n return select_and_scatter_add_p.bind(\n source, operand, select_prim=select_prim,\n window_dimensions=tuple(window_dimensions),\n window_strides=tuple(window_strides), padding=padding)\n\ndef _select_and_gather_add(tangents: Array, operand: Array,\n select_prim: core.Primitive,\n window_dimensions: Shape,\n window_strides: Sequence[int],\n padding: str) -> Array:\n return select_and_gather_add_p.bind(\n tangents, operand, select_prim=select_prim,\n window_dimensions=tuple(window_dimensions),\n window_strides=tuple(window_strides), padding=padding)\n\ndef cumsum(operand: Array, axis: int) -> Array:\n \"\"\"Computes a cumulative sum along `axis`.\"\"\"\n return cumsum_p.bind(operand, axis=int(axis))\n\ndef cumprod(operand: Array, axis: int) -> Array:\n \"\"\"Computes a cumulative product along `axis`.\"\"\"\n return cumprod_p.bind(operand, axis=int(axis))\n\ndef sort(operand: Union[Array, Tuple[Array, ...]], dimension: int = -1\n ) -> Union[Array, Tuple[Array, ...]]:\n \"\"\"Wraps XLA's `Sort\n <https://www.tensorflow.org/xla/operation_semantics#sort>`_\n operator.\n \"\"\"\n if isinstance(operand, tuple):\n if len(operand) == 0:\n raise TypeError(\"Sort requires at least one operand\")\n dimension = _canonicalize_axis(dimension, len(operand[0].shape))\n return tuple(sort_p.bind(*operand, dimension=dimension))\n else:\n dimension = _canonicalize_axis(dimension, len(operand.shape))\n return sort_p.bind(operand, dimension=dimension)[0]\n\ndef sort_key_val(keys: Array, values: Array,\n dimension: int = -1) -> Tuple[Array, Array]:\n \"\"\"Sorts ``keys`` along ``dimension`` and applies same permutation to ``values``.\"\"\"\n dimension = _canonicalize_axis(dimension, len(keys.shape))\n k, v = sort_p.bind(keys, values, dimension=dimension)\n return k, v\n\ndef top_k(operand: Array, k: int) -> Tuple[Array, Array]:\n \"\"\"Returns top ``k`` values and their indices along the last axis of ``operand``.\"\"\"\n k = int(k)\n if k < 0:\n raise ValueError(\"k argument to top_k must be nonnegative, got {}\".format(k))\n return top_k_p.bind(operand, k=k)\n\ndef tie_in(x: Array, y: Array) -> Array:\n \"\"\"Gives ``y`` a fake data dependence on ``x``.\n\n When staging to XLA (e.g. running under jit or pmap), values that don't depend\n on computation inputs are computed op-by-op, and folded into the XLA\n computation as constants.\n\n ``tie_in`` provides a way to explicitly stage values into the computation.\n When staging to XLA and ``x`` is already staged, then the result of ``tie_in``\n is ``y``, but staged to XLA. Downstream use of the result will also be staged\n to XLA.\n \"\"\"\n return tie_in_p.bind(x, y)\n\n\ndef full(shape: Shape, fill_value: Array, dtype: Optional[DType] = None) -> Array:\n \"\"\"Returns an array of `shape` filled with `fill_value`.\n\n Arguments:\n shape: sequence of integers, describing the shape of the output array.\n fill_value: the value to fill the new array with.\n dtype: the type of the output array, or `None`. If not `None`, `fill_value`\n will be cast to `dtype`.\n \"\"\"\n shape = canonicalize_shape(shape)\n if onp.shape(fill_value):\n msg = \"full must be called with scalar fill_value, got fill_value.shape {}.\"\n raise TypeError(msg.format(onp.shape(fill_value)))\n dtype = dtypes.canonicalize_dtype(dtype or _dtype(fill_value))\n # TODO(mattjj): remove device_put when dtype conversion produces DeviceArray\n fill_value = xla.device_put_p.bind(convert_element_type(fill_value, dtype))\n return broadcast(fill_value, shape)\n\ndef iota(dtype: DType, size: int) -> Array:\n \"\"\"Wraps XLA's `Iota\n <https://www.tensorflow.org/xla/operation_semantics#iota>`_\n operator.\n \"\"\"\n size = size if type(size) is masking.Poly else int(size)\n shape = canonicalize_shape((size,))\n dtype = dtypes.canonicalize_dtype(dtype)\n lazy_expr = lazy.iota(dtype, shape[0])\n aval = ShapedArray(shape, dtype)\n return xla.DeviceArray(aval, None, lazy_expr, xla.DeviceConstant())\n\ndef broadcasted_iota(dtype: DType, shape: Shape, dimension: int) -> Array:\n \"\"\"Convenience wrapper around ``iota``.\"\"\"\n dtype = dtypes.canonicalize_dtype(dtype)\n shape = canonicalize_shape(shape)\n dimension = int(dimension)\n return broadcast_in_dim(iota(dtype, shape[dimension]), shape, [dimension])\n\ndef _eye(dtype: DType, shape: Shape, offset: int) -> Array:\n \"\"\"Like numpy.eye, create a 2D array with ones on a diagonal.\n\n This function exists for creating lazy identity matrices; that is,\n materialization of the array is delayed and it may be fused into consumers to\n avoid materialization at all.\"\"\"\n N, M = tuple(map(int, shape))\n offset = int(offset)\n dtype = dtypes.canonicalize_dtype(dtype)\n lazy_expr = lazy.eye(dtype, (N, M), offset)\n aval = ShapedArray((N, M), dtype)\n return xla.DeviceArray(aval, None, lazy_expr, xla.DeviceConstant())\n\ndef _delta(dtype: DType, shape: Shape, axes: Sequence[int]) -> Array:\n \"\"\"This function exists for creating lazy Kronecker delta arrays, particularly\n for use in jax.numpy.einsum to express traces. It differs from ``eye`` in that\n it can create arrays of any rank, but doesn't allow offsets.\"\"\"\n shape = tuple(map(int, shape))\n axes = tuple(map(int, axes))\n dtype = dtypes.canonicalize_dtype(dtype)\n base_shape = tuple(onp.take(shape, axes))\n lazy_expr = lazy.broadcast(lazy.delta(dtype, base_shape), shape, axes)\n aval = ShapedArray(shape, dtype)\n return xla.DeviceArray(aval, None, lazy_expr, xla.DeviceConstant())\n\ndef _tri(dtype: DType, shape: Shape, offset: int) -> Array:\n \"\"\"Like numpy.tri, create a 2D array with ones below a diagonal.\n This function exists for creating lazy triangular matrices, particularly for\n use in jax.numpy.tri.\"\"\"\n N, M = tuple(map(int, shape))\n offset = int(offset)\n dtype = dtypes.canonicalize_dtype(dtype)\n lazy_expr = lazy.tri(dtype, (N, M), offset)\n aval = ShapedArray((N, M), dtype)\n return xla.DeviceArray(aval, None, lazy_expr, xla.DeviceConstant())\n\ndef stop_gradient(x):\n \"\"\"Stops gradient computation.\n\n Operationally `stop_gradient` is the identity function, that is, it returns\n argument `x` unchanged. However, `stop_gradient` prevents the flow of\n gradients during forward or reverse-mode automatic differentiation. If there\n are multiple nested gradient computations, `stop_gradient` stops gradients\n for all of them.\n\n For example:\n\n >>> jax.grad(lambda x: x**2)(3.)\n array(6., dtype=float32)\n >>> jax.grad(lambda x: jax.lax.stop_gradient(x)**2)(3.)\n array(0., dtype=float32)\n >>> jax.grad(jax.grad(lambda x: x**2))(3.)\n array(2., dtype=float32)\n >>> jax.grad(jax.grad(lambda x: jax.lax.stop_gradient(x)**2))(3.)\n array(0., dtype=float32)\n \"\"\"\n return tree_map(ad_util.stop_gradient_p.bind, x)\n\n\n### convenience wrappers around traceables\n\n\ndef conv(lhs: Array, rhs: Array, window_strides: Sequence[int],\n padding: str, precision: Optional[PrecisionType] = None) -> Array:\n \"\"\"Convenience wrapper around `conv_general_dilated`.\n\n Args:\n lhs: a rank `n+2` dimensional input array.\n rhs: a rank `n+2` dimensional array of kernel weights.\n window_strides: a sequence of `n` integers, representing the inter-window\n strides.\n padding: either the string `'SAME'`, the string `'VALID'`.\n precision: Optional. Either `None`, which means the default precision for\n the backend, or a `Precision` enum value.\n\n Returns:\n An array containing the convolution result.\n \"\"\"\n pads = padtype_to_pads(lhs.shape[2:], rhs.shape[2:], window_strides, padding)\n return conv_general_dilated(lhs, rhs, window_strides, padding,\n precision=precision)\n\ndef conv_with_general_padding(lhs: Array, rhs: Array,\n window_strides: Sequence[int],\n padding: Union[str, Sequence[Tuple[int, int]]],\n lhs_dilation: Optional[Sequence[int]],\n rhs_dilation: Optional[Sequence[int]],\n precision: Optional[PrecisionType] = None) -> Array:\n \"\"\"Convenience wrapper around `conv_general_dilated`.\n\n Args:\n lhs: a rank `n+2` dimensional input array.\n rhs: a rank `n+2` dimensional array of kernel weights.\n window_strides: a sequence of `n` integers, representing the inter-window\n strides.\n padding: either the string `'SAME'`, the string `'VALID'`, or a sequence of\n `n` `(low, high)` integer pairs that give the padding to apply before and\n after each spatial dimension.\n lhs_dilation: `None`, or a sequence of `n` integers, giving the\n dilation factor to apply in each spatial dimension of `lhs`. LHS dilation\n is also known as transposed convolution.\n rhs_dilation: `None`, or a sequence of `n` integers, giving the\n dilation factor to apply in each spatial dimension of `rhs`. RHS dilation\n is also known as atrous convolution.\n precision: Optional. Either `None`, which means the default precision for\n the backend, or a `Precision` enum value.\n\n Returns:\n An array containing the convolution result.\n \"\"\"\n return conv_general_dilated(\n lhs, rhs, window_strides, padding, lhs_dilation=lhs_dilation,\n rhs_dilation=rhs_dilation, precision=precision)\n\n\ndef _conv_transpose_padding(k, s, padding):\n \"\"\"Calculate before and after padding for a dim of transposed convolution.\n\n Args:\n k: int: kernel dimension.\n s: int: dimension stride value.\n padding: 'same' or 'valid' padding mode for original forward conv.\n\n Returns:\n 2-tuple: ints: before and after padding for transposed convolution.\n \"\"\"\n if padding == 'SAME':\n pad_len = k + s - 2\n if s > k - 1:\n pad_a = k - 1\n else:\n pad_a = int(onp.ceil(pad_len / 2))\n elif padding == 'VALID':\n pad_len = k + s - 2 + _max(k - s, 0)\n pad_a = k - 1\n else:\n raise ValueError('Padding mode must be `SAME` or `VALID`.')\n pad_b = pad_len - pad_a\n return pad_a, pad_b\n\n\ndef _flip_axes(x, axes):\n \"\"\"Flip ndarray 'x' along each axis specified in axes tuple.\"\"\"\n for axis in axes:\n x = onp.flip(x, axis)\n return x\n\n\ndef conv_transpose(lhs: Array, rhs: Array, strides: Sequence[int],\n padding: Union[str, Sequence[Tuple[int, int]]],\n rhs_dilation: Optional[Sequence[int]] = None,\n dimension_numbers: ConvGeneralDilatedDimensionNumbers = None,\n transpose_kernel: bool = False,\n precision: Optional[PrecisionType] = None) -> Array:\n \"\"\"Convenience wrapper for calculating the N-d convolution \"transpose\".\n\n This function directly calculates a fractionally strided conv rather than\n indirectly calculating the gradient (transpose) of a forward convolution.\n\n Args:\n lhs: a rank `n+2` dimensional input array.\n rhs: a rank `n+2` dimensional array of kernel weights.\n strides: sequence of `n` integers, sets fractional stride.\n padding: 'SAME', 'VALID' will set as transpose of corresponding forward\n conv, or a sequence of `n` integer 2-tuples describing before-and-after\n padding for each `n` spatial dimension.\n rhs_dilation: `None`, or a sequence of `n` integers, giving the\n dilation factor to apply in each spatial dimension of `rhs`. RHS dilation\n is also known as atrous convolution.\n dimension_numbers: tuple of dimension descriptors as in\n lax.conv_general_dilated. Defaults to tensorflow convention.\n transpose_kernel: if True flips spatial axes and swaps the input/output\n channel axes of the kernel. This makes the output of this function identical\n to the gradient-derived functions like keras.layers.Conv2DTranspose\n applied to the same kernel. For typical use in neural nets this is completely\n pointless and just makes input/output channel specification confusing.\n precision: Optional. Either `None`, which means the default precision for\n the backend, or a `Precision` enum value.\n\n Returns:\n Transposed N-d convolution, with output padding following the conventions of\n keras.layers.Conv2DTranspose.\n \"\"\"\n assert len(lhs.shape) == len(rhs.shape) and len(lhs.shape) > 2\n ndims = len(lhs.shape)\n one = (1,) * (ndims - 2)\n # Set dimensional layout defaults if not specified.\n if dimension_numbers is None:\n if ndims == 3:\n dimension_numbers = ('NHC', 'HIO', 'NHC')\n elif ndims == 4:\n dimension_numbers = ('NHWC', 'HWIO', 'NHWC')\n elif ndims == 5:\n dimension_numbers = ('NHWDC', 'HWDIO', 'NHWDC')\n else:\n raise ValueError('No 4+ dimensional dimension_number defaults.')\n dn = conv_dimension_numbers(lhs.shape, rhs.shape, dimension_numbers)\n k_shape = onp.take(rhs.shape, dn.rhs_spec)\n k_sdims = k_shape[2:]\n # Calculate correct output shape given padding and strides.\n pads: Union[str, Sequence[Tuple[int, int]]]\n if padding in {'SAME', 'VALID'}:\n if rhs_dilation is None:\n rhs_dilation = (1,) * (rhs.ndim - 2)\n effective_k_size = map(lambda k, r: (k-1) * r + 1, k_sdims, rhs_dilation)\n pads = [_conv_transpose_padding(k, s, padding)\n for k,s in zip(effective_k_size, strides)]\n else:\n pads = padding\n if transpose_kernel:\n # flip spatial dims and swap input / output channel axes\n rhs = _flip_axes(rhs, onp.array(dn.rhs_spec)[2:])\n rhs = onp.swapaxes(rhs, dn.rhs_spec[0], dn.rhs_spec[1])\n return conv_general_dilated(lhs, rhs, one, pads, strides, rhs_dilation, dn,\n precision=precision)\n\n\ndef full_like(x: Array, fill_value: Array, dtype: Optional[DType] = None,\n shape: Optional[Shape] = None) -> Array:\n \"\"\"Create a full array like np.full based on the example array `x`.\n\n Args:\n x: example array-like, used for shape and dtype information.\n fill_value: a scalar value to fill the entries of the output array.\n dtype: optional, a dtype parameter for the output ndarray.\n shape: optional, a shape parameter for the output ndarray.\n\n Returns:\n An ndarray with the same shape as `x` with its entries set equal to\n `fill_value`, similar to the output of np.full.\n \"\"\"\n fill_shape = onp.shape(x) if shape is None else canonicalize_shape(shape)\n fill_value = tie_in(x, fill_value)\n return full(fill_shape, fill_value, dtype or _dtype(x))\n\n\ndef collapse(operand: Array, start_dimension: int, stop_dimension: int) -> Array:\n lo, hi = start_dimension, stop_dimension\n size = prod(operand.shape[lo:hi])\n new_shape = operand.shape[:lo] + (size,) + operand.shape[hi:]\n return reshape(operand, new_shape)\n\n\ndef slice_in_dim(operand: Array, start_index: Optional[int],\n limit_index: Optional[int],\n stride: int = 1, axis: int = 0)-> Array:\n \"\"\"Convenience wrapper around slice applying to only one dimension.\"\"\"\n start_indices = [0] * operand.ndim\n limit_indices = list(operand.shape)\n strides = [1] * operand.ndim\n\n # translate `None`\n len_axis = operand.shape[axis]\n start_index_int = int(start_index) if start_index is not None else 0\n limit_index_int = int(limit_index) if limit_index is not None else len_axis\n\n # translate negative indices\n if start_index_int < 0:\n start_index_int = start_index_int + len_axis\n if limit_index_int < 0:\n limit_index_int = limit_index_int + len_axis\n\n axis = int(axis)\n start_indices[axis] = start_index_int\n limit_indices[axis] = limit_index_int\n strides[axis] = int(stride)\n\n return slice(operand, start_indices, limit_indices, strides)\n\n\ndef index_in_dim(operand: Array, index: int, axis: int = 0,\n keepdims: bool = True) -> Array:\n \"\"\"Convenience wrapper around slice to perform int indexing.\"\"\"\n index, axis = int(index), int(axis)\n axis_size = operand.shape[axis]\n wrapped_index = index + axis_size if index < 0 else index\n if not 0 <= wrapped_index < axis_size:\n msg = 'index {} is out of bounds for axis {} with size {}'\n raise IndexError(msg.format(index, axis, axis_size))\n result = slice_in_dim(operand, wrapped_index, wrapped_index + 1, 1, axis)\n if keepdims:\n return result\n else:\n return reshape(result, onp.delete(operand.shape, axis))\n\n\ndef dynamic_slice_in_dim(operand: Array, start_index: Array,\n slice_size: int, axis: int = 0) -> Array:\n \"\"\"Convenience wrapper around dynamic_slice applying to one dimension.\"\"\"\n start_indices = [_zero(start_index)] * operand.ndim\n slice_sizes = list(operand.shape)\n\n axis = int(axis)\n start_indices[axis] = start_index\n slice_sizes[axis] = int(slice_size)\n return dynamic_slice(operand, start_indices, slice_sizes)\n\n\ndef dynamic_index_in_dim(operand: Array, index: Array, axis: int = 0,\n keepdims: bool = True) -> Array:\n \"\"\"Convenience wrapper around dynamic_slice to perform int indexing.\"\"\"\n result = dynamic_slice_in_dim(operand, index, 1, axis)\n if keepdims:\n return result\n else:\n return reshape(result, onp.delete(operand.shape, axis))\n\n\ndef dynamic_update_slice_in_dim(operand: Array, update: Array,\n start_index: Array, axis: int) -> Array:\n axis = int(axis)\n start_indices = [_zero(start_index)] * _ndim(operand)\n start_indices[axis] = start_index\n return dynamic_update_slice(operand, update, start_indices)\n\n\ndef dynamic_update_index_in_dim(operand: Array, update: Array, index: Array,\n axis: int) -> Array:\n axis = int(axis)\n if _ndim(update) != _ndim(operand):\n assert _ndim(update) + 1 == _ndim(operand)\n ax = axis % _ndim(operand)\n update = reshape(update, operand.shape[:ax] + (1,) + operand.shape[ax+1:])\n return dynamic_update_slice_in_dim(operand, update, index, axis)\n\n\ndef batch_matmul(lhs: Array, rhs: Array,\n precision: Optional[PrecisionType] = None) -> Array:\n \"\"\"Batch matrix multiplication.\"\"\"\n if _min(lhs.ndim, rhs.ndim) < 2:\n raise ValueError('Arguments to batch_matmul must be at least 2D, got {}, {}'\n .format(lhs.ndim, rhs.ndim))\n if lhs.ndim != rhs.ndim:\n raise ValueError('Arguments to batch_matmul must have same ndim, got {}, {}'\n .format(lhs.ndim, rhs.ndim))\n lhs_contract = (lhs.ndim - 1,)\n rhs_contract = (rhs.ndim - 2,)\n batch = tuple(range(lhs.ndim - 2))\n return dot_general(lhs, rhs, ((lhs_contract, rhs_contract), (batch, batch)),\n precision=precision)\n\n\n# These functions also exist in the XLA client library, but we treat them\n# as non-primitive to maintain a smaller set of autodiff primitives.\n\ndef square(x: Array) -> Array:\n r\"\"\"Elementwise square: :math:`x^2`.\"\"\"\n return integer_pow(x, 2)\n\ndef reciprocal(x: Array) -> Array:\n r\"\"\"Elementwise reciprocal: :math:`1 \\over x`.\"\"\"\n return integer_pow(x, -1)\n\ndef _upcast_fp16_for_computation(f):\n @functools.wraps(f)\n def f_wrapped(x):\n dtype = _dtype(x)\n if dtype == onp.float16 or dtype == dtypes.bfloat16:\n return convert_element_type(\n f(convert_element_type(x, onp.float32)), dtype)\n return f(x)\n\n return f_wrapped\n\[email protected]\n@_upcast_fp16_for_computation\ndef tan(x: Array) -> Array:\n r\"\"\"Elementwise tangent: :math:`\\mathrm{tan}(x)`.\"\"\"\n return div(sin(x), cos(x))\n\[email protected]\ndef asin(x: Array) -> Array:\n r\"\"\"Elementwise arc sine: :math:`\\mathrm{asin}(x)`.\"\"\"\n return mul(_const(x, 2),\n atan2(x, add(_const(x, 1), sqrt(sub(_const(x, 1), square(x))))))\n\[email protected]\ndef acos(x: Array) -> Array:\n r\"\"\"Elementwise arc cosine: :math:`\\mathrm{acos}(x)`.\"\"\"\n return select(\n ne(x, _const(x, -1.0)),\n mul(_const(x, 2),\n atan2(sqrt(sub(_const(x, 1), square(x))), add(_const(x, 1), x))),\n full_like(x, onp.pi))\n\ndef atan(x: Array) -> Array:\n r\"\"\"Elementwise arc tangent: :math:`\\mathrm{atan}(x)`.\"\"\"\n return atan2(x, _const(x, 1))\n\ndef sinh(x: Array) -> Array:\n r\"\"\"Elementwise hyperbolic sine: :math:`\\mathrm{sinh}(x)`.\"\"\"\n return sinh_p.bind(x)\n\ndef cosh(x: Array) -> Array:\n r\"\"\"Elementwise hyperbolic cosine: :math:`\\mathrm{cosh}(x)`.\"\"\"\n return cosh_p.bind(x)\n\ndef asinh(x: Array) -> Array:\n r\"\"\"Elementwise inverse hyperbolic sine: :math:`\\mathrm{asinh}(x)`.\"\"\"\n return asinh_p.bind(x)\n\ndef acosh(x: Array) -> Array:\n r\"\"\"Elementwise inverse hyperbolic cosine: :math:`\\mathrm{acosh}(x)`.\"\"\"\n return acosh_p.bind(x)\n\ndef atanh(x: Array) -> Array:\n r\"\"\"Elementwise inverse hyperbolic tangent: :math:`\\mathrm{atanh}(x)`.\"\"\"\n return atanh_p.bind(x)\n\n\n# Add some methods to ShapedArray that rely on lax primitives\n\nShapedArray.broadcast = core.aval_method(broadcast)\nShapedArray.transpose = core.aval_method(transpose) # clobbered by lax_numpy\nShapedArray.reshape = core.aval_method(reshape) # clobbered by lax_numpy\n\ndef _iter(tracer):\n if tracer.ndim == 0:\n raise TypeError(\"iteration over a 0-d array\") # same as numpy error\n else:\n n = tracer.shape[0]\n # return (index_in_dim(tracer, i, keepdims=False) for i in range(n))\n return iter([index_in_dim(tracer, i, keepdims=False) for i in range(n)])\nShapedArray._iter = staticmethod(_iter)\n\n# Add some ad handlers that use (or could use) lax primitives\n\ndef zeros_like_array(x):\n return full_like(x, 0)\n\nfor t in itertools.chain(dtypes.python_scalar_dtypes.keys(), array_types,\n [xla.DeviceArray, pxla.ShardedDeviceArray]):\n ad_util.jaxval_adders[t] = add\nad_util.jaxval_zeros_likers[xla.DeviceArray] = zeros_like_array\nad_util.jaxval_zeros_likers[pxla.ShardedDeviceArray] = zeros_like_array\n\n\n### primitives\n\n\n_input_dtype = lambda *args, **_: dtypes.canonicalize_dtype(args[0].dtype)\n_fixed_dtype = lambda dtype: lambda *args, **kwargs: dtypes.canonicalize_dtype(dtype)\n_complex_basetype = lambda dtype: onp.abs(onp.zeros((), dtype)).dtype\n\ndef standard_primitive(shape_rule, dtype_rule, name, translation_rule=None):\n prim = Primitive(name)\n prim.def_impl(partial(xla.apply_primitive, prim))\n prim.def_abstract_eval(partial(standard_abstract_eval, prim, shape_rule, dtype_rule))\n xla.translations[prim] = translation_rule or partial(standard_translate, name)\n return prim\n\n\ndef standard_abstract_eval(prim, shape_rule, dtype_rule, *args, **kwargs):\n assert all(isinstance(arg, UnshapedArray) for arg in args), args\n least_specialized = _max(\n map(type, args), key=operator.attrgetter('array_abstraction_level'))\n if least_specialized is ConcreteArray:\n return ConcreteArray(prim.impl(*[x.val for x in args], **kwargs))\n elif least_specialized is ShapedArray:\n return ShapedArray(shape_rule(*args, **kwargs), dtype_rule(*args, **kwargs))\n elif least_specialized is UnshapedArray:\n return UnshapedArray(dtype_rule(*args, **kwargs))\n else:\n raise TypeError(args, least_specialized)\n\n\ndef standard_translate(name, c, *args, **kwargs):\n xla_opname = ''.join(term.capitalize() for term in name.split('_'))\n return getattr(xops, xla_opname)(*args, **kwargs)\n\n\ndef unop_dtype_rule(result_dtype, accepted_dtypes, name, aval, **kwargs):\n if not any(dtypes.issubdtype(aval.dtype, t) for t in accepted_dtypes):\n msg = '{} does not accept dtype {}. Accepted dtypes are subtypes of {}.'\n typename = str(onp.dtype(aval.dtype).name)\n accepted_typenames = (t.__name__ for t in accepted_dtypes)\n raise TypeError(msg.format(name, typename, ', '.join(accepted_typenames)))\n return result_dtype(aval.dtype)\n\n\ndef unop(result_dtype, accepted_dtypes, name, translation_rule=None):\n dtype_rule = partial(unop_dtype_rule, result_dtype, accepted_dtypes, name)\n prim = standard_primitive(_attrgetter('shape'), dtype_rule, name,\n translation_rule=translation_rule)\n batching.defvectorized(prim)\n masking.defvectorized(prim)\n return prim\nstandard_unop = partial(unop, _identity)\n_attrgetter = lambda name: lambda x, **kwargs: getattr(x, name)\n\n\ndef naryop_dtype_rule(result_dtype, accepted_dtypes, name, *avals, **kwargs):\n aval_dtypes = [aval.dtype for aval in avals]\n for i, (aval_dtype, types) in enumerate(zip(aval_dtypes, accepted_dtypes)):\n if not any(dtypes.issubdtype(aval_dtype, t) for t in types):\n msg = ('{} does not accept dtype {} at position {}. '\n 'Accepted dtypes at position {} are subtypes of {}.')\n typename = str(onp.dtype(aval_dtype).name)\n typenames = ', '.join(t.__name__ for t in types)\n raise TypeError(msg.format(name, typename, i, i, typenames))\n _check_same_dtypes(name, False, *aval_dtypes)\n return result_dtype(*avals)\n\n\ndef _broadcasting_shape_rule(name, *avals):\n shapes = onp.array([aval.shape for aval in avals if aval.shape])\n if not shapes.size:\n return ()\n if len({len(shape) for shape in shapes}) != 1:\n msg = '{} got arrays of different rank: {}.'\n raise TypeError(msg.format(name, ', '.join(map(str, map(tuple, shapes)))))\n is_zero = onp.any(shapes == 0, axis=0)\n max_shape = onp.max(shapes, axis=0)\n result_shape = onp.where(is_zero, 0, max_shape)\n if not onp.all((shapes == result_shape) | (shapes == 1)):\n msg = '{} got incompatible shapes for broadcasting: {}.'\n raise TypeError(msg.format(name, ', '.join(map(str, map(tuple, shapes)))))\n return tuple(result_shape)\n\n\ndef naryop(result_dtype, accepted_dtypes, name, translation_rule=None):\n dtype_rule = partial(naryop_dtype_rule, result_dtype, accepted_dtypes, name)\n shape_rule = partial(_broadcasting_shape_rule, name)\n prim = standard_primitive(shape_rule, dtype_rule, name,\n translation_rule=translation_rule)\n batching.defbroadcasting(prim)\n masking.defnaryop(prim)\n return prim\nstandard_naryop = partial(naryop, _input_dtype)\n\n\ndef _broadcast_translate(translate: Callable):\n # Decorator for translation rules which adds explicit broadcasting of\n # positional arguments. This is necessary only for a handful of primitives\n # whose XLA implementations do not support broadcasting.\n def _broadcast_array(array, array_shape, result_shape):\n if array_shape == result_shape:\n return array\n bcast_dims = tuple(range(len(result_shape) - len(array_shape),\n len(result_shape)))\n result = xops.BroadcastInDim(array, result_shape, bcast_dims)\n return result\n\n def _broadcasted_translation_rule(c, *args, **kwargs):\n shapes = [c.get_shape(arg).dimensions() for arg in args]\n result_shape = broadcast_shapes(*shapes)\n args = [_broadcast_array(arg, arg_shape, result_shape)\n for arg, arg_shape in zip(args, shapes)]\n return translate(c, *args, **kwargs)\n return _broadcasted_translation_rule\n\n# NOTE(mattjj): this isn't great for orchestrate fwd mode because it means JVPs\n# get two extra ops in them: a reshape and a broadcast_in_dim (or sometimes just\n# a broadcast). but saving the shape info with the primitives isn't great either\n# because then we can't trace these ops without shape data.\ndef _brcast(x, *others):\n # Used in jvprules to make naryop broadcasting explicit for transposability.\n # Requires shape info during jvp tracing, which isn't strictly necessary.\n # We don't need full numpy broadcasting, but otherwise the logic is the same\n # so we reuse the broadcast_shapes function after filtering out scalars.\n shapes = tuple(filter(None, map(onp.shape, (x,) + others)))\n shape = shapes and broadcast_shapes(*shapes)\n if onp.shape(x) != shape:\n return _brcast_to(x, shape)\n else:\n return x\n\n\ndef _brcast_to(x, shape):\n x_shape = onp.shape(x)\n assert x_shape != shape\n if x_shape:\n assert len(x_shape) == len(shape)\n broadcast_dimensions, = onp.where(onp.equal(x_shape, shape))\n squeezed_dimensions, = onp.where(onp.not_equal(x_shape, shape))\n inshape = onp.delete(x_shape, squeezed_dimensions)\n return broadcast_in_dim(reshape(x, inshape), shape, broadcast_dimensions)\n else:\n return broadcast(x, shape)\n\n\n_float = {onp.floating}\n_complex = {onp.complexfloating}\n_complex_elem_types = {onp.float32, onp.float64}\n_int = {onp.integer}\n_bool = {onp.bool_}\n\n_num = _int | _float | _complex\n_any = _int | _float | _complex | _bool\n_bool_or_int = _int | _bool\n\nneg_p = standard_unop(_num, 'neg')\nad.deflinear(neg_p, lambda t: [neg(t)])\n\ndef _sign_translation_rule(c, x):\n shape = c.get_shape(x)\n dtype = shape.numpy_dtype()\n if dtypes.issubdtype(dtype, onp.unsignedinteger):\n zero = xb.constant(c, onp.array(0, dtype=dtype))\n dims = c.get_shape(x).dimensions()\n return xops.Select(xops.Eq(x, zero), xops.Broadcast(zero, dims),\n xops.Broadcast(xb.constant(c, onp.array(1, dtype=dtype)),\n dims))\n return xops.Sign(x)\n\nsign_p = standard_unop(_num, 'sign', translation_rule=_sign_translation_rule)\nad.defjvp_zero(sign_p)\n\nnextafter_p = standard_naryop(\n [_float, _float], 'nextafter',\n translation_rule=lambda c, x1, x2: xops.NextAfter(x1, x2))\n\nfloor_p = standard_unop(_float, 'floor')\nad.defjvp_zero(floor_p)\n\nceil_p = standard_unop(_float, 'ceil')\nad.defjvp_zero(ceil_p)\n\nround_p = standard_unop(_float, 'round')\nad.defjvp_zero(round_p)\n\nis_finite_p = unop(_fixed_dtype(onp.bool_), _float, 'is_finite')\nad.defjvp_zero(is_finite_p)\n\nexp_p = standard_unop(_float | _complex, 'exp')\nad.defjvp2(exp_p, lambda g, ans, x: mul(g, ans))\n\nlog_p = standard_unop(_float | _complex, 'log')\nad.defjvp(log_p, lambda g, x: div(g, x))\n\nexpm1_p = standard_unop(_float | _complex, 'expm1')\nad.defjvp2(expm1_p, lambda g, ans, x: mul(g, add(ans, _one(ans))))\n\nlog1p_p = standard_unop(_float | _complex, 'log1p')\nad.defjvp(log1p_p, lambda g, x: div(g, add(x, _one(x))))\n\ntanh_p = standard_unop(_float | _complex, 'tanh')\nad.defjvp2(tanh_p, lambda g, ans, x: mul(g, sub(_one(x), mul(ans, ans))))\n\nsin_p = standard_unop(_float | _complex, 'sin')\nad.defjvp(sin_p, lambda g, x: mul(g, cos(x)))\n\ncos_p = standard_unop(_float | _complex, 'cos')\nad.defjvp(cos_p, lambda g, x: neg(mul(g, sin(x))))\n\natan2_p = standard_naryop([_float, _float], 'atan2')\nad.defjvp(atan2_p,\n lambda g, x, y: _brcast(g, y) * (y / (square(x) + square(y))),\n lambda g, x, y: _brcast(g, x) * -x / (square(x) + square(y)))\n\nsinh_p = standard_unop(_float | _complex, 'sinh')\nad.defjvp(sinh_p, lambda g, x: mul(g, cosh(x)))\n\ncosh_p = standard_unop(_float | _complex, 'cosh')\nad.defjvp(cosh_p, lambda g, x: mul(g, sinh(x)))\n\nasinh_p = standard_unop(_float | _complex, 'asinh')\nad.defjvp(asinh_p, lambda g, x: mul(g, rsqrt(square(x) + _one(x))))\n\nacosh_p = standard_unop(_float | _complex, 'acosh')\nad.defjvp(acosh_p,\n lambda g, x: mul(g, rsqrt((x - _one(x)) * (x + _one(x)))))\n\natanh_p = standard_unop(_float | _complex, 'atanh')\nad.defjvp(atanh_p,\n lambda g, x: mul(g, reciprocal((_one(x) - x) * (_one(x) + x))))\n\nregularized_incomplete_beta_p = standard_naryop(\n [_float, _float, _float], 'regularized_incomplete_beta',\n translation_rule=_broadcast_translate(\n partial(standard_translate, 'regularized_incomplete_beta')))\n\ndef betainc_gradx(g, a, b, x):\n lbeta = lgamma(a) + lgamma(b) - lgamma(a + b)\n partial_x = exp((b - 1) * log1p(-x) +\n (a - 1) * log(x) - lbeta)\n return partial_x * g\n\ndef betainc_grad_not_implemented(g, a, b, x):\n raise ValueError(\"Betainc gradient with respect to a and b not supported.\")\n\nad.defjvp(regularized_incomplete_beta_p,\n betainc_grad_not_implemented,\n betainc_grad_not_implemented,\n betainc_gradx)\n\nlgamma_p = standard_unop(_float, 'lgamma')\nad.defjvp(lgamma_p, lambda g, x: mul(g, digamma(x)))\n\ndigamma_p = standard_unop(_float, 'digamma')\n\nigamma_p = standard_naryop(\n [_float, _float], 'igamma',\n translation_rule=_broadcast_translate(partial(standard_translate, 'igamma')))\nigamma_grad_a_p = standard_naryop([_float, _float], 'igamma_grad_a',\n translation_rule=_broadcast_translate(partial(standard_translate,\n 'igamma_grad_a')))\n\ndef igamma_gradx(g, a, x):\n return _brcast(g, a, x) * exp(-x + (a - _ones(a)) * log(x) - lgamma(a))\n\ndef igamma_grada(g, a, x):\n return _brcast(g, a, x) * igamma_grad_a(a, x)\n\nad.defjvp(igamma_p, igamma_grada, igamma_gradx)\n\nigammac_p = standard_naryop(\n [_float, _float], 'igammac',\n translation_rule=_broadcast_translate(partial(standard_translate, 'igammac')))\n\ndef igammac_gradx(g, a, x):\n return -igamma_gradx(g, a, x)\n\ndef igammac_grada(g, a, x):\n return -igamma_grada(g, a, x)\n\nad.defjvp(igammac_p, igammac_grada, igammac_gradx)\n\nbessel_i0e_p = standard_unop(_float, 'bessel_i0e')\nad.defjvp2(bessel_i0e_p, lambda g, y, x: g * (bessel_i1e(x) - sign(x) * y))\n\nbessel_i1e_p = standard_unop(_float, 'bessel_i1e')\ndef _bessel_i1e_jvp(g, y, x):\n eps = dtypes.finfo(_dtype(x)).eps\n x_is_not_tiny = abs(x) > eps\n safe_x = select(x_is_not_tiny, x, full_like(x, eps))\n dy_dx = bessel_i0e(safe_x) - y * (sign(safe_x) + reciprocal(safe_x))\n dy_dx = select(x_is_not_tiny, dy_dx, full_like(x, 0.5))\n return g * dy_dx\nad.defjvp2(bessel_i1e_p, _bessel_i1e_jvp)\n\nerf_p = standard_unop(_float, 'erf')\nad.defjvp(erf_p, lambda g, x: mul(_const(x, 2. / onp.sqrt(onp.pi)),\n mul(g, exp(neg(square(x))))))\n\nerfc_p = standard_unop(_float, 'erfc')\nad.defjvp(erfc_p, lambda g, x: mul(_const(x, 2. / onp.sqrt(onp.pi)),\n mul(neg(g), exp(neg(square(x))))))\n\nerf_inv_p = standard_unop(_float, 'erf_inv')\nad.defjvp2(erf_inv_p, lambda g, ans, x: mul(_const(x, onp.sqrt(onp.pi) / 2.),\n mul(g, exp(square(ans)))))\n\nreal_p = unop(_complex_basetype, _complex, 'real')\nad.deflinear(real_p, lambda t: [complex(t, onp.zeros((), _dtype(t)))])\n\nimag_p = unop(_complex_basetype, _complex, 'imag')\nad.defjvp(imag_p, lambda g, _: real(mul(_const(g, -1j), g)))\n\n_complex_dtype = lambda dtype, *args: (onp.zeros((), dtype) + onp.zeros((), onp.complex64)).dtype\ncomplex_p = naryop(_complex_dtype, [_complex_elem_types, _complex_elem_types],\n 'complex')\nad.deflinear(complex_p, lambda t: [real(t), imag(neg(t))])\n\nconj_p = unop(_complex_dtype, _complex_elem_types | _complex, 'conj')\n\ndef _conj_transpose_rule(t, x, *, input_dtype):\n assert ad.is_undefined_primal(x)\n if dtypes.issubdtype(input_dtype, onp.complexfloating):\n return [conj(t)]\n else:\n return [real(t)]\n\nxla.translations[conj_p] = lambda c, x, **kwargs: xops.Conj(x)\nad.primitive_jvps[conj_p] = partial(ad.linear_jvp, conj_p)\nad.primitive_transposes[conj_p] = _conj_transpose_rule\n\nabs_p = unop(_complex_basetype, _num, 'abs')\n\ndef _abs_jvp_rule(g, ans, x):\n if _iscomplex(x):\n return _maybe_real(mul(g, div(_maybe_conj(x),\n _replace_zero(convert_element_type(ans, _dtype(x))))))\n else:\n return select(ge(x, _zero(x)), g, neg(g))\nad.defjvp2(abs_p, _abs_jvp_rule)\n_maybe_conj = lambda x: conj(x) if _iscomplex(x) else x\n_maybe_real = lambda x: real(x) if _iscomplex(x) else x\n\nsqrt_p = standard_unop(_float | _complex, 'sqrt')\nad.defjvp2(sqrt_p, lambda g, ans, x: mul(g, div(_const(x, 0.5), ans)))\n\nrsqrt_p = standard_unop(_float | _complex, 'rsqrt')\nad.defjvp2(rsqrt_p,\n lambda g, ans, x:\n mul(g, mul(_const(x, -0.5), pow(x, _const(x, -1.5)))))\n\npow_p = standard_naryop([_float | _complex, _float | _complex], 'pow')\n\ndef _pow_jvp_lhs(g, ans, x, y):\n jac = mul(y, pow(x, select(eq(y, _zeros(y)), _ones(y), sub(y, _ones(y)))))\n return mul(_brcast(g, y), jac)\n\ndef _pow_jvp_rhs(g, ans, x, y):\n return mul(_brcast(g, x), mul(log(_replace_zero(x)), ans))\n\nad.defjvp2(pow_p, _pow_jvp_lhs, _pow_jvp_rhs)\n\n\ndef _integer_pow_dtype_rule(x, *, y):\n dtype = unop_dtype_rule(_identity, _int | _float | _complex, 'integer_pow', x)\n if y < 0 and dtypes.issubdtype(dtype, onp.integer):\n raise TypeError(\"Integers cannot be raised to negative powers, got \"\n f\"integer_pow({x}, {y})\")\n return dtype\n\ndef _integer_pow_translation_rule(c, x, *, y):\n if y == 0:\n shape = c.get_shape(x)\n return xb.constant(c, onp.array(1, dtype=shape.numpy_dtype()))\n is_reciprocal = y < 0\n if is_reciprocal:\n y = -y\n acc = None\n while y > 0:\n if y & 1:\n acc = x if acc is None else xops.Mul(acc, x)\n y >>= 1\n if y > 0:\n x = xops.Mul(x, x)\n return xops.Reciprocal(acc) if is_reciprocal else acc\n\ndef _integer_pow_jvp(g, x, *, y):\n return g if y == 0 else mul(g, mul(_const(x, y), integer_pow(x, y - 1)))\n\ninteger_pow_p = standard_primitive(\n _attrgetter('shape'), _integer_pow_dtype_rule, 'integer_pow',\n translation_rule=_integer_pow_translation_rule)\nbatching.defvectorized(integer_pow_p)\nmasking.defvectorized(integer_pow_p)\nad.defjvp(integer_pow_p, _integer_pow_jvp)\n\n_replace_zero = lambda x: select(eq(x, _const(x, 0)), _ones(x), x)\n\nnot_p = standard_unop(_bool_or_int, 'not')\n\nand_p = standard_naryop([_bool_or_int, _bool_or_int], 'and')\nad.defjvp_zero(and_p)\n\nor_p = standard_naryop([_bool_or_int, _bool_or_int], 'or')\nad.defjvp_zero(or_p)\n\nxor_p = standard_naryop([_bool_or_int, _bool_or_int], 'xor')\nad.defjvp_zero(xor_p)\n\npopulation_count_p = standard_unop(_bool_or_int, 'population_count')\n\ndef _add_transpose(t, x, y):\n # The following linearity assertion is morally true, but because in some cases we\n # instantiate zeros for convenience, it doesn't always hold.\n # assert ad.is_undefined_primal(x) and ad.is_undefined_primal(y)\n return [t, t]\n\nadd_p = standard_naryop([_num, _num], 'add')\nad.defjvp(add_p, lambda g, x, y: _brcast(g, y), lambda g, x, y: _brcast(g, x))\nad.primitive_transposes[add_p] = _add_transpose\n\n\ndef _sub_transpose(t, x, y):\n # The following linearity assertion is morally true, but because in some cases\n # we instantiate zeros for convenience, it doesn't always hold.\n # assert ad.is_undefined_primal(x) and ad.is_undefined_primal(y)\n return [t, neg(t) if t is not ad_util.zero else ad_util.zero]\n\nsub_p = standard_naryop([_num, _num], 'sub')\nad.defjvp(sub_p,\n lambda g, x, y: _brcast(g, y),\n lambda g, x, y: _brcast(neg(g), x))\nad.primitive_transposes[sub_p] = _sub_transpose\n\nmul_p = standard_naryop([_num, _num], 'mul')\nad.defbilinear_broadcasting(_brcast, mul_p, mul, mul)\n\n\ndef _div_transpose_rule(cotangent, x, y):\n assert ad.is_undefined_primal(x) and not ad.is_undefined_primal(y)\n res = ad_util.zero if cotangent is ad_util.zero else div(cotangent, y)\n return res, None\ndiv_p = standard_naryop([_num, _num], 'div')\nad.defjvp(div_p,\n lambda g, x, y: div(_brcast(g, y), y),\n lambda g, x, y: mul(mul(neg(_brcast(g, x)), x), integer_pow(y, -2)))\nad.primitive_transposes[div_p] = _div_transpose_rule\n\nrem_p = standard_naryop([_num, _num], 'rem')\nad.defjvp(rem_p,\n lambda g, x, y: _brcast(g, y),\n lambda g, x, y: mul(_brcast(neg(g), x), floor(div(x, y))))\n\n\ndef _broadcasting_select(c, which, x, y):\n \"\"\"Wrapper around XLA `Select` that broadcasts its arguments.\"\"\"\n which_shape, x_shape, y_shape = (\n c.get_shape(t).dimensions() for t in (which, x, y))\n out_shape = broadcast_shapes(which_shape, x_shape, y_shape)\n bcast_dims = lambda shape: tuple(range(len(out_shape) - len(shape),\n len(out_shape)))\n which = xops.BroadcastInDim(which, out_shape, bcast_dims(which_shape))\n x = xops.BroadcastInDim(x, out_shape, bcast_dims(x_shape))\n y = xops.BroadcastInDim(y, out_shape, bcast_dims(y_shape))\n return xops.Select(which, x, y)\n\n\ndef _minmax_translation_rule(c, x, y, *, minmax=None, cmp=None):\n dtype = c.get_shape(x).numpy_dtype()\n if dtypes.issubdtype(dtype, onp.complexfloating):\n rx = xops.Real(x)\n ry = xops.Real(y)\n return _broadcasting_select(\n c, xops.Select(xops.Eq(rx, ry), cmp(xops.Imag(x), xops.Imag(y)),\n cmp(rx, ry)),\n x, y)\n return minmax(x, y)\n\nmax_p = standard_naryop([_any, _any], 'max', translation_rule=partial(\n _minmax_translation_rule, minmax=xops.Max, cmp=xops.Gt))\nad.defjvp2(max_p,\n lambda g, ans, x, y: mul(_brcast(g, y), _balanced_eq(x, ans, y)),\n lambda g, ans, x, y: mul(_brcast(g, x), _balanced_eq(y, ans, x)))\n\nmin_p = standard_naryop([_any, _any], 'min', translation_rule=partial(\n _minmax_translation_rule, minmax=xops.Min, cmp=xops.Lt))\nad.defjvp2(min_p,\n lambda g, ans, x, y: mul(_brcast(g, y), _balanced_eq(x, ans, y)),\n lambda g, ans, x, y: mul(_brcast(g, x), _balanced_eq(y, ans, x)))\n\n\nshift_left_p = standard_naryop([_int, _int], 'shift_left')\nad.defjvp_zero(shift_left_p)\n\nshift_right_arithmetic_p = standard_naryop([_int, _int], 'shift_right_arithmetic')\nad.defjvp_zero(shift_right_arithmetic_p)\n\nshift_right_logical_p = standard_naryop([_int, _int], 'shift_right_logical')\nad.defjvp_zero(shift_right_logical_p)\n\neq_p = naryop(_fixed_dtype(onp.bool_), [_any, _any], 'eq')\nad.defjvp_zero(eq_p)\n\nne_p = naryop(_fixed_dtype(onp.bool_), [_any, _any], 'ne')\nad.defjvp_zero(ne_p)\n\nge_p = naryop(_fixed_dtype(onp.bool_), [_any, _any], 'ge')\nad.defjvp_zero(ge_p)\n\ngt_p = naryop(_fixed_dtype(onp.bool_), [_any, _any], 'gt')\nad.defjvp_zero(gt_p)\n\nle_p = naryop(_fixed_dtype(onp.bool_), [_any, _any], 'le')\nad.defjvp_zero(le_p)\n\nlt_p = naryop(_fixed_dtype(onp.bool_), [_any, _any], 'lt')\nad.defjvp_zero(lt_p)\n\n\ndef _convert_element_type_shape_rule(operand, *, new_dtype, old_dtype):\n return operand.shape\n\ndef _convert_element_type_dtype_rule(operand, *, new_dtype, old_dtype):\n return new_dtype\n\ndef _convert_element_type_translation_rule(c, operand, *, new_dtype, old_dtype):\n if (dtypes.issubdtype(old_dtype, onp.complexfloating) and\n not dtypes.issubdtype(new_dtype, onp.complexfloating)):\n operand = xops.Real(operand)\n new_etype = xla_client.dtype_to_etype(new_dtype)\n return xops.ConvertElementType(operand, new_element_type=new_etype)\n\ndef _convert_element_type_transpose_rule(t, *, new_dtype, old_dtype):\n assert t.dtype == new_dtype, (t.dtype, new_dtype)\n return [convert_element_type_p.bind(t, new_dtype=old_dtype,\n old_dtype=new_dtype)]\n\nconvert_element_type_p = standard_primitive(\n _convert_element_type_shape_rule, _convert_element_type_dtype_rule,\n 'convert_element_type', _convert_element_type_translation_rule)\nad.deflinear(convert_element_type_p, _convert_element_type_transpose_rule)\nbatching.defvectorized(convert_element_type_p)\nmasking.defvectorized(convert_element_type_p)\n\n\ndef _bitcast_convert_type_shape_rule(operand, *, new_dtype):\n return operand.shape\n\ndef _bitcast_convert_type_dtype_rule(operand, *, new_dtype):\n return new_dtype\n\ndef _bitcast_convert_type_translation_rule(c, operand, *, new_dtype):\n new_etype = xla_bridge.dtype_to_etype(new_dtype)\n return xops.BitcastConvertType(operand, new_element_type=new_etype)\n\nbitcast_convert_type_p = standard_primitive(\n _bitcast_convert_type_shape_rule, _bitcast_convert_type_dtype_rule,\n 'bitcast_convert_type', _bitcast_convert_type_translation_rule)\nad.defjvp_zero(bitcast_convert_type_p)\nbatching.defvectorized(bitcast_convert_type_p)\nmasking.defvectorized(bitcast_convert_type_p)\n\n\ndef _conv_general_dilated_shape_rule(\n lhs, rhs, *, window_strides, padding, lhs_dilation, rhs_dilation,\n dimension_numbers, feature_group_count, batch_group_count,\n **unused_kwargs):\n assert type(dimension_numbers) is ConvDimensionNumbers\n if not feature_group_count > 0:\n msg = (\"conv_general_dilated feature_group_count \"\n \"must be a positive integer, got {}.\")\n raise ValueError(msg.format(feature_group_count))\n lhs_feature_count = lhs.shape[dimension_numbers.lhs_spec[1]]\n quot, rem = divmod(lhs_feature_count, feature_group_count)\n if rem:\n msg = (\"conv_general_dilated feature_group_count must divide lhs feature \"\n \"dimension size, but {} does not divide {}.\")\n raise ValueError(msg.format(feature_group_count, lhs_feature_count))\n if quot != rhs.shape[dimension_numbers.rhs_spec[1]]:\n msg = (\"conv_general_dilated lhs feature dimension size divided by \"\n \"feature_group_count must equal the rhs input feature dimension \"\n \"size, but {} // {} != {}.\")\n raise ValueError(msg.format(lhs_feature_count, feature_group_count,\n rhs.shape[dimension_numbers.rhs_spec[1]]))\n if rhs.shape[dimension_numbers.rhs_spec[0]] % feature_group_count:\n msg = (\"conv_general_dilated rhs output feature dimension size must be a \"\n \"multiple of feature_group_count, but {} is not a multiple of {}.\")\n raise ValueError(msg.format(rhs.shape[dimension_numbers.rhs_spec[0]],\n feature_group_count))\n\n if not batch_group_count > 0:\n msg = (\"conv_general_dilated batch_group_count \"\n \"must be a positive integer, got {}.\")\n raise ValueError(msg.format(batch_group_count))\n lhs_batch_count = lhs.shape[dimension_numbers.lhs_spec[0]]\n if lhs_batch_count % batch_group_count != 0:\n msg = (\"conv_general_dilated batch_group_count must divide lhs batch \"\n \"dimension size, but {} does not divide {}.\")\n raise ValueError(msg.format(batch_group_count, lhs_batch_count))\n if rhs.shape[dimension_numbers.rhs_spec[0]] % feature_group_count:\n msg = (\"conv_general_dilated rhs output feature dimension size must be a \"\n \"multiple of batch_group_count, but {} is not a multiple of {}.\")\n raise ValueError(msg.format(rhs.shape[dimension_numbers.rhs_spec[0]],\n batch_ground_count))\n\n if not batch_group_count > 0 and feature_group_count > 0:\n msg = (\"At most one of batch_group_count and feature_group_count may be > \"\n \"1, got batch_group_count={} and feature_group_count={}\")\n raise ValueError(msg.format(batch_group_count, feature_group_count))\n\n lhs_perm, rhs_perm, out_perm = dimension_numbers\n lhs_trans = _dilate_shape(onp.take(lhs.shape, lhs_perm), lhs_dilation)\n rhs_trans = _dilate_shape(onp.take(rhs.shape, rhs_perm), rhs_dilation)\n out_trans = conv_shape_tuple(lhs_trans, rhs_trans, window_strides, padding,\n batch_group_count)\n return tuple(onp.take(out_trans, onp.argsort(out_perm)))\n\ndef _conv_general_dilated_dtype_rule(\n lhs, rhs, *, window_strides, padding, lhs_dilation, rhs_dilation,\n dimension_numbers, **unused_kwargs):\n return naryop_dtype_rule(_input_dtype, [_float, _float],\n 'conv_general_dilated', lhs, rhs)\n\n_conv_spec_transpose = lambda spec: (spec[1], spec[0]) + spec[2:]\n_conv_sdims = lambda spec: spec[2:]\n\n# Understanding the convolution transpose rules:\n# Ignoring the spatial dimensions, let m = batch, j = input feature,\n# k = output feature.\n#\n# Convolution computes the following contraction:\n# Forward: [m, j] [j, k] -> [m, k]\n#\n# The transposes are similar to the rules for transposing a matmul:\n# LHS transpose: [m, k] [k, j] -> [m, j]\n# RHS transpose: [j, m] [m, k] -> [j, k]\n#\n# With feature grouping, we have the following signatures:\n# Forward: [m, gj] [j, gk] -> [m, gk]\n# LHS transpose: [m, gk] [k, gj] -> [m, gj]\n# --> implemented as feature grouping after transposing the group from the\n# kernel input features to the kernel output features.\n# RHS transpose: [gj, m] [m, gk] -> [j, gk]\n# --> which is batch grouping.\n#\n# With batch grouping, we have the following signatures:\n# Forward: [gm,j] [j,gk]->[m,gk]\n# LHS transpose: [m, gk][gk, j] -> [gm, j]\n# --> implemented as feature grouping with transposing the group on the kernel\n# and the output.\n# RHS transpose: [j, gm][m, gk] -> [j, gk]\n# --> which is feature grouping.\n\ndef _conv_general_dilated_transpose_lhs(\n g, rhs, *, window_strides, padding, lhs_dilation, rhs_dilation,\n dimension_numbers, feature_group_count, batch_group_count,\n lhs_shape, rhs_shape, precision):\n assert type(dimension_numbers) is ConvDimensionNumbers\n assert batch_group_count == 1 or feature_group_count == 1\n lhs_sdims, rhs_sdims, out_sdims = map(_conv_sdims, dimension_numbers)\n lhs_spec, rhs_spec, out_spec = dimension_numbers\n t_rhs_spec = _conv_spec_transpose(rhs_spec)\n if feature_group_count > 1:\n # in addition to switching the dims in the spec, need to move the feature\n # group axis into the transposed rhs's output feature dim\n rhs = _reshape_axis_out_of(rhs_spec[0], feature_group_count, rhs)\n rhs = _reshape_axis_into(rhs_spec[0], rhs_spec[1], rhs)\n elif batch_group_count > 1:\n rhs = _reshape_axis_out_of(rhs_spec[0], batch_group_count, rhs)\n rhs = _reshape_axis_into(rhs_spec[0], rhs_spec[1], rhs)\n feature_group_count = batch_group_count\n trans_dimension_numbers = ConvDimensionNumbers(out_spec, t_rhs_spec, lhs_spec)\n padding = _conv_general_vjp_lhs_padding(\n onp.take(lhs_shape, lhs_sdims), onp.take(rhs_shape, rhs_sdims),\n window_strides, onp.take(g.shape, out_sdims), padding, lhs_dilation,\n rhs_dilation)\n revd_weights = rev(rhs, rhs_sdims)\n out = conv_general_dilated(\n g, revd_weights, window_strides=lhs_dilation, padding=padding,\n lhs_dilation=window_strides, rhs_dilation=rhs_dilation,\n dimension_numbers=trans_dimension_numbers,\n feature_group_count=feature_group_count,\n batch_group_count=1, precision=precision)\n if batch_group_count > 1:\n out = _reshape_axis_out_of(lhs_spec[1], batch_group_count, out)\n out = _reshape_axis_into(lhs_spec[1], lhs_spec[0], out)\n return out\n\ndef _conv_general_dilated_transpose_rhs(\n g, lhs, *, window_strides, padding, lhs_dilation, rhs_dilation,\n dimension_numbers: ConvDimensionNumbers, feature_group_count: int,\n batch_group_count: int, lhs_shape, rhs_shape, precision):\n assert type(dimension_numbers) is ConvDimensionNumbers\n if onp.size(g) == 0:\n # Avoids forming degenerate convolutions where the RHS has spatial size 0.\n return ad_util.zero\n lhs_sdims, rhs_sdims, out_sdims = map(_conv_sdims, dimension_numbers)\n lhs_trans, rhs_trans, out_trans = map(_conv_spec_transpose, dimension_numbers)\n assert batch_group_count == 1 or feature_group_count == 1\n if batch_group_count > 1:\n feature_group_count = batch_group_count\n batch_group_count = 1\n elif feature_group_count > 1:\n batch_group_count = feature_group_count\n feature_group_count = 1\n trans_dimension_numbers = ConvDimensionNumbers(lhs_trans, out_trans, rhs_trans)\n padding = _conv_general_vjp_rhs_padding(\n onp.take(lhs_shape, lhs_sdims), onp.take(rhs_shape, rhs_sdims),\n window_strides, onp.take(g.shape, out_sdims), padding, lhs_dilation,\n rhs_dilation)\n return conv_general_dilated(\n lhs, g, window_strides=rhs_dilation, padding=padding,\n lhs_dilation=lhs_dilation, rhs_dilation=window_strides,\n dimension_numbers=trans_dimension_numbers,\n feature_group_count=feature_group_count,\n batch_group_count=batch_group_count, precision=precision)\n\ndef _conv_general_dilated_translation_rule(\n c, lhs, rhs, *, window_strides, padding, lhs_dilation, rhs_dilation,\n dimension_numbers, feature_group_count, batch_group_count, precision,\n **unused_kwargs):\n assert type(dimension_numbers) is ConvDimensionNumbers\n dimension_numbers = _conv_general_proto(dimension_numbers)\n return xops.ConvGeneralDilated(lhs, rhs, window_strides, padding, lhs_dilation,\n rhs_dilation, dimension_numbers,\n feature_group_count, batch_group_count,\n precision_config=_precision_config(precision))\n\ndef _conv_general_dilated_batch_rule(\n batched_args, batch_dims, *, window_strides, padding,\n lhs_dilation, rhs_dilation, dimension_numbers,\n feature_group_count, batch_group_count, precision, **unused_kwargs):\n assert batch_group_count == 1 or feature_group_count == 1\n lhs, rhs = batched_args\n lhs_bdim, rhs_bdim = batch_dims\n lhs_spec, rhs_spec, out_spec = dimension_numbers\n\n if lhs_bdim is not None and rhs_bdim is not None:\n assert lhs.shape[lhs_bdim] == rhs.shape[rhs_bdim]\n if batch_group_count > 1:\n new_lhs = _reshape_axis_into(lhs_bdim, lhs_spec[0], lhs)\n batch_group_count *= lhs.shape[lhs_bdim]\n else:\n new_lhs = _reshape_axis_into(lhs_bdim, lhs_spec[1], lhs)\n feature_group_count *= lhs.shape[lhs_bdim]\n new_rhs = _reshape_axis_into(rhs_bdim, rhs_spec[0], rhs)\n out = conv_general_dilated(\n new_lhs, new_rhs, window_strides, padding, lhs_dilation, rhs_dilation,\n dimension_numbers, feature_group_count=feature_group_count,\n batch_group_count=batch_group_count,\n precision=precision)\n out = _reshape_axis_out_of(out_spec[1], lhs.shape[lhs_bdim], out)\n return out, out_spec[1]\n\n elif lhs_bdim is not None:\n if batch_group_count == 1:\n new_lhs = _reshape_axis_into(lhs_bdim, lhs_spec[0], lhs)\n out = conv_general_dilated(new_lhs, rhs, window_strides, padding,\n lhs_dilation, rhs_dilation, dimension_numbers,\n feature_group_count, precision=precision)\n out = _reshape_axis_out_of(out_spec[0], lhs.shape[lhs_bdim], out)\n return out, out_spec[0]\n else:\n new_lhs = _reshape_axis_out_of(lhs_spec[0] + int(lhs_bdim <= lhs_spec[0]),\n batch_group_count, lhs)\n new_lhs = _reshape_axis_into(lhs_bdim + int(lhs_spec[0] < lhs_bdim),\n lhs_spec[0] + 1,\n new_lhs)\n new_lhs = _reshape_axis_into(lhs_spec[0], lhs_spec[0], new_lhs)\n out = conv_general_dilated(new_lhs, rhs, window_strides, padding,\n lhs_dilation, rhs_dilation, dimension_numbers,\n feature_group_count, batch_group_count,\n precision=precision)\n out = _reshape_axis_out_of(out_spec[0], lhs.shape[lhs_bdim], out)\n return out, out_spec[0]\n\n elif rhs_bdim is not None:\n if feature_group_count == 1 and batch_group_count == 1:\n new_rhs = _reshape_axis_into(rhs_bdim, rhs_spec[0], rhs)\n out = conv_general_dilated(lhs, new_rhs, window_strides, padding,\n lhs_dilation, rhs_dilation, dimension_numbers,\n feature_group_count, batch_group_count,\n precision=precision)\n out = _reshape_axis_out_of(out_spec[1], rhs.shape[rhs_bdim], out)\n return out, out_spec[1]\n else:\n # groups need to be outermost, so we need to factor them out of the\n # rhs output feature dim, then factor the batch dim into the remaining rhs\n # output feature dim, then put groups back in. We do something\n # similar on the output. An alternative which would require more FLOPs but\n # fewer reshapes would be to broadcast lhs.\n group_count = (feature_group_count if feature_group_count > 1\n else batch_group_count)\n new_rhs = _reshape_axis_out_of(rhs_spec[0] + int(rhs_bdim <= rhs_spec[0]),\n group_count, rhs)\n new_rhs = _reshape_axis_into(rhs_bdim + int(rhs_spec[0] < rhs_bdim),\n rhs_spec[0] + 1,\n new_rhs)\n new_rhs = _reshape_axis_into(rhs_spec[0], rhs_spec[0], new_rhs)\n out = conv_general_dilated(lhs, new_rhs, window_strides, padding,\n lhs_dilation, rhs_dilation, dimension_numbers,\n feature_group_count, batch_group_count,\n precision=precision)\n out = _reshape_axis_out_of(out_spec[1], group_count, out)\n out = _reshape_axis_out_of(out_spec[1] + 1, rhs.shape[rhs_bdim], out)\n out = _reshape_axis_into(out_spec[1], out_spec[1] + 1, out)\n return out, out_spec[1]\n\nconv_general_dilated_p = standard_primitive(\n _conv_general_dilated_shape_rule, _conv_general_dilated_dtype_rule,\n 'conv_general_dilated', _conv_general_dilated_translation_rule)\nad.defbilinear(conv_general_dilated_p,\n _conv_general_dilated_transpose_lhs,\n _conv_general_dilated_transpose_rhs)\nbatching.primitive_batchers[conv_general_dilated_p] = \\\n _conv_general_dilated_batch_rule\n\n\ndef _reshape_axis_into(src, dst, x):\n perm = [i for i in range(x.ndim) if i != src]\n perm.insert(dst, src)\n new_shape = list(onp.delete(x.shape, src))\n new_shape[dst] *= x.shape[src]\n return reshape(x, new_shape, perm)\n\ndef _reshape_axis_out_of(src, size1, x):\n shape = list(x.shape)\n size2, ragged = divmod(shape[src], size1)\n assert not ragged\n shape[src:src+1] = [size1, size2]\n return reshape(x, shape)\n\ndef _precision_config(precision):\n if precision is not None:\n config = xla_client.PrecisionConfig()\n config.operand_precision.extend((precision, precision))\n return config\n return None\n\n\ndef _dot_general_shape_rule(lhs, rhs, *, dimension_numbers, precision):\n (lhs_contracting, rhs_contracting), (lhs_batch, rhs_batch) = dimension_numbers\n if len(lhs_batch) != len(rhs_batch):\n msg = (\"dot_general requires equal numbers of lhs_batch and rhs_batch \"\n \"dimensions, got lhs_batch {} and rhs_batch {}.\")\n raise TypeError(msg.format(lhs_batch, rhs_batch))\n if not onp.all(onp.equal(lhs_batch, rhs_batch)):\n msg = (\"dot_general requires same lhs and rhs batch dimension numbers, \"\n \"got {} and {}.\")\n raise TypeError(msg.format(lhs_batch, rhs_batch))\n lhs_batch_shape = onp.take(lhs.shape, lhs_batch)\n rhs_batch_shape = onp.take(rhs.shape, rhs_batch)\n if not onp.all(onp.equal(lhs_batch_shape, rhs_batch_shape)):\n msg = (\"dot_general requires lhs batch dimensions and rhs batch dimensions \"\n \"to have the same shape, got {} and {}.\")\n raise TypeError(msg.format(lhs_batch_shape, rhs_batch_shape))\n if tuple(sorted(lhs_batch)) != tuple(range(len(lhs_batch))):\n msg = (\"dot_general requires lhs batch dimensions to precede contracting \"\n \"and non-contracting dimensions, got lhs_batch {}.\")\n raise TypeError(msg.format(lhs_batch))\n if tuple(sorted(rhs_batch)) != tuple(range(len(rhs_batch))):\n msg = (\"dot_general requires rhs batch dimensions to precede contracting \"\n \"and non-contracting dimensions, got rhs_batch {}.\")\n raise TypeError(msg.format(rhs_batch))\n lhs_contracting_shape = onp.take(lhs.shape, lhs_contracting)\n rhs_contracting_shape = onp.take(rhs.shape, rhs_contracting)\n if not onp.all(onp.equal(lhs_contracting_shape, rhs_contracting_shape)):\n msg = (\"dot_general requires contracting dimensions to have the same \"\n \"shape, got {} and {}.\")\n raise TypeError(msg.format(lhs_contracting_shape, rhs_contracting_shape))\n\n batch_shape = tuple(onp.take(lhs.shape, lhs_batch))\n lhs_contract_or_batch = tuple(lhs_contracting) + tuple(lhs_batch)\n lhs_tensored_shape = tuple(onp.delete(lhs.shape, lhs_contract_or_batch))\n rhs_contract_or_batch = tuple(rhs_contracting) + tuple(rhs_batch)\n rhs_tensored_shape = tuple(onp.delete(rhs.shape, rhs_contract_or_batch))\n return batch_shape + lhs_tensored_shape + rhs_tensored_shape\n\n\ndef _dot_general_dtype_rule(lhs, rhs, *, dimension_numbers, precision):\n return naryop_dtype_rule(_input_dtype, [_num, _num], 'dot_general', lhs, rhs)\n\n\ndef _dot_general_transpose_lhs(g, y, *, dimension_numbers, precision,\n swap_ans=False):\n (x_contract, y_contract), (x_batch, y_batch) = dimension_numbers\n x_ndim = g.ndim - y.ndim + len(x_batch) + 2 * len(x_contract)\n x_kept = remaining(range(x_ndim), x_contract, x_batch)\n y_kept = remaining(range(y.ndim), y_contract, y_batch)\n if swap_ans:\n ans_batch, ans_y, _ = ranges_like(x_batch, y_kept, x_kept)\n else:\n ans_batch, _, ans_y = ranges_like(x_batch, x_kept, y_kept)\n dims = ((ans_y, y_kept), (ans_batch, y_batch))\n x_contract_sorted_by_y = list(onp.take(x_contract, onp.argsort(y_contract)))\n out_axes = onp.argsort(list(x_batch) + x_kept + x_contract_sorted_by_y)\n return transpose(dot_general(g, y, dims, precision=precision),\n tuple(out_axes))\n\ndef _dot_general_transpose_rhs(g, x, *, dimension_numbers, precision):\n (x_contract, y_contract), (x_batch, y_batch) = dimension_numbers\n swapped_dimension_numbers = ((y_contract, x_contract), (y_batch, x_batch))\n return _dot_general_transpose_lhs(\n g, x, dimension_numbers=swapped_dimension_numbers, precision=precision,\n swap_ans=True)\n\n\ndef _dot_general_batch_rule(batched_args, batch_dims, *, dimension_numbers,\n precision):\n # there are three kinds of dimensions in a dot_general:\n # - contraction dimensions appear in lhs and rhs but not the result\n # - batch dimensions appear in lhs, rhs, and result\n # - tensor product dimensions appear in the result and one of lhs or rhs\n (lhs_contract, rhs_contract), (lhs_batch, rhs_batch) = dimension_numbers\n lhs, rhs = batched_args\n lbd, rbd = batch_dims\n assert lbd is not None or rbd is not None\n if lbd is not None and rbd is not None:\n # adding a batch dimension\n if lbd != 0:\n lhs = batching.moveaxis(lhs, lbd, 0)\n if rbd != 0:\n rhs = batching.moveaxis(rhs, rbd, 0)\n lhs_batch = (0,) + tuple(onp.add(1, lhs_batch))\n rhs_batch = (0,) + tuple(onp.add(1, rhs_batch))\n lhs_contract = tuple(onp.add(1, lhs_contract))\n rhs_contract = tuple(onp.add(1, rhs_contract))\n result_batch_dim = 0\n else:\n # adding a tensor product dimension\n if lbd is not None:\n if lhs_batch == () or lbd > onp.max(lhs_batch):\n # can avoid transposes\n bump_lhs_contract = onp.greater_equal(lhs_contract, lbd)\n lhs_contract = tuple(onp.add(lhs_contract, bump_lhs_contract))\n result_batch_dim = lbd - len(lhs_contract) + sum(bump_lhs_contract)\n else:\n # move the new dimension to the end of lhs to avoid changing batch dims\n lhs = batching.moveaxis(lhs, lbd, lhs.ndim - 1)\n # lhs tensor product dims in result come after batch dims\n result_batch_dim = lhs.ndim - len(lhs_contract) - 1\n else:\n if rhs_batch == () or rbd > onp.max(rhs_batch):\n # can avoid transposes\n bump_rhs_contract = onp.greater_equal(rhs_contract, rbd)\n rhs_contract = tuple(onp.add(rhs_contract, bump_rhs_contract))\n result_batch_dim = (rbd + (lhs.ndim - len(lhs_contract) - len(lhs_batch))\n - (len(rhs_contract) - sum(bump_rhs_contract)))\n else:\n # move the new dimension to the end of rhs to avoid changing batch dims\n rhs = batching.moveaxis(rhs, rbd, rhs.ndim - 1)\n # rhs tensor product dims in result come after batch dims + lhs tensor\n # product dims\n result_batch_dim = (lhs.ndim - len(lhs_contract) - len(lhs_batch) +\n rhs.ndim - len(rhs_contract) - 1)\n new_dimension_numbers = [(lhs_contract, rhs_contract), (lhs_batch, rhs_batch)]\n batched_out = dot_general(lhs, rhs, new_dimension_numbers,\n precision=precision)\n return batched_out, int(result_batch_dim)\n\ndef _dot_general_translation_rule(c, lhs, rhs, *, dimension_numbers, precision):\n return xops.DotGeneral(lhs, rhs,\n xc.make_dot_dimension_numbers(dimension_numbers),\n precision_config=_precision_config(precision))\n\ndef _dot_general_masking_rule(padded_vals, logical_shapes, *, dimension_numbers,\n precision):\n lhs, rhs = padded_vals\n lhs_shape, rhs_shape = logical_shapes\n lhs_ndim, rhs_ndim = len(lhs_shape), len(rhs_shape)\n (lhs_contract, rhs_contract), (lhs_batch, rhs_batch) = dimension_numbers\n\n # we need only mask the lhs contraction dimensions\n if len(lhs_contract) == 0:\n return dot_general(lhs, rhs, dimension_numbers, precision=precision)\n else:\n masks = [broadcasted_iota(onp.int32, lhs.shape, d) < lhs_shape[d]\n for d in lhs_contract]\n mask_intersection = masks[0]\n for mask in masks[1:]:\n mask_intersection &= mask\n masked_lhs = select(mask_intersection, lhs, zeros_like_array(lhs))\n return dot_general(masked_lhs, rhs, dimension_numbers, precision=precision)\n\ndot_general_p = standard_primitive(_dot_general_shape_rule,\n _dot_general_dtype_rule, 'dot_general',\n _dot_general_translation_rule)\nad.defbilinear(dot_general_p,\n _dot_general_transpose_lhs, _dot_general_transpose_rhs)\nbatching.primitive_batchers[dot_general_p] = _dot_general_batch_rule\nmasking.masking_rules[dot_general_p] = _dot_general_masking_rule\n\n\ndef _broadcast_shape_rule(operand, sizes):\n _check_shapelike('broadcast', 'sizes', sizes)\n return tuple(sizes) + operand.shape\n\ndef _broadcast_batch_rule(batched_args, batch_dims, *, sizes):\n operand, = batched_args\n bdim, = batch_dims\n new_bdim = None if bdim is None else bdim + len(sizes)\n return broadcast(operand, sizes), new_bdim\n\nbroadcast_p = standard_primitive(\n _broadcast_shape_rule, _input_dtype, 'broadcast')\nad.deflinear(broadcast_p, lambda t, sizes: [_reduce_sum(t, range(len(sizes)))])\nbatching.primitive_batchers[broadcast_p] = _broadcast_batch_rule\n\ndef _broadcast_in_dim_impl(operand, *, shape, broadcast_dimensions):\n if type(operand) is xla.DeviceArray:\n shape = _broadcast_in_dim_shape_rule(\n operand, shape=shape, broadcast_dimensions=broadcast_dimensions)\n aval = ShapedArray(shape, _dtype(operand))\n lazy_expr = lazy.broadcast(operand._lazy_expr, shape, broadcast_dimensions)\n return xla.DeviceArray(aval, operand._device, lazy_expr, operand.device_buffer)\n else:\n return xla.apply_primitive(broadcast_in_dim_p, operand, shape=shape,\n broadcast_dimensions=broadcast_dimensions)\n\ndef _broadcast_in_dim_shape_rule(operand, *, shape, broadcast_dimensions):\n _check_shapelike('broadcast_in_dim', 'shape', shape)\n _check_shapelike('broadcast_in_dim', 'broadcast_dimensions',\n broadcast_dimensions)\n operand_ndim = onp.ndim(operand)\n if operand_ndim != len(broadcast_dimensions):\n msg = ('broadcast_in_dim broadcast_dimensions must have length equal to '\n 'operand ndim; got broadcast_dimensions {} for operand ndim {}.')\n raise TypeError(msg.format(broadcast_dimensions, operand_ndim))\n if len(shape) < operand_ndim:\n msg = ('broadcast_in_dim target broadcast shape must have equal or higher rank '\n 'to the operand shape; got operand ndim {} and target broadcast ndim {}.')\n raise TypeError(msg.format(operand_ndim, len(shape)))\n if not set(broadcast_dimensions).issubset(set(range(len(shape)))):\n msg = ('broadcast_in_dim broadcast_dimensions must be a subset of output '\n 'dimensions, got {} for operand ndim {} and shape {}.')\n raise TypeError(msg.format(broadcast_dimensions, operand_ndim, shape))\n if any(operand.shape[i] != 1 and operand.shape[i] != shape[broadcast_dimensions[i]]\n for i in range(operand_ndim)):\n msg = ('broadcast_in_dim operand dimension sizes must either be 1, or be '\n 'equal to their corresponding dimensions in the target broadcast shape; '\n 'got operand of shape {}, target broadcast shape {}, '\n 'broadcast_dimensions {} ')\n raise TypeError(msg.format(operand.shape, shape, broadcast_dimensions))\n if (len(broadcast_dimensions) != len(set(broadcast_dimensions)) or\n tuple(broadcast_dimensions) != tuple(sorted(broadcast_dimensions))):\n msg = ('broadcast_in_dim broadcast_dimensions must be strictly increasing; '\n 'got broadcast_dimensions {}')\n raise TypeError(msg.format(broadcast_dimensions))\n\n return shape\n\ndef _broadcast_in_dim_transpose_rule(t, *, shape, broadcast_dimensions):\n axes = tuple(onp.delete(range(len(shape)), broadcast_dimensions))\n return [_reduce_sum(t, axes)]\n\ndef _broadcast_in_dim_batch_rule(batched_args, batch_dims, *, shape,\n broadcast_dimensions):\n operand, = batched_args\n bdim, = batch_dims\n new_operand = batching.moveaxis(operand, bdim, 0)\n new_shape = (operand.shape[bdim],) + shape\n new_broadcast_dimensions = (0,) + tuple(onp.add(1, broadcast_dimensions))\n return broadcast_in_dim(new_operand, new_shape, new_broadcast_dimensions), 0\n\n\nbroadcast_in_dim_p = standard_primitive(\n _broadcast_in_dim_shape_rule, _input_dtype, 'broadcast_in_dim')\nbroadcast_in_dim_p.def_impl(_broadcast_in_dim_impl)\nad.deflinear(broadcast_in_dim_p, _broadcast_in_dim_transpose_rule)\nbatching.primitive_batchers[broadcast_in_dim_p] = _broadcast_in_dim_batch_rule\n\n\ndef _clamp_shape_rule(min, operand, max):\n if min.shape and min.shape != operand.shape:\n m = \"clamp requires min.shape == operand.shape or min.shape == (), got {}.\"\n raise TypeError(m.format(min.shape))\n if max.shape and max.shape != operand.shape:\n m = \"clamp requires max.shape == operand.shape or max.shape == (), got {}.\"\n raise TypeError(m.format(max.shape))\n return operand.shape\n\n_clamp_dtype_rule = partial(naryop_dtype_rule, _input_dtype, [_any, _any, _any],\n 'clamp')\n\nclamp_p = standard_primitive(_clamp_shape_rule, _clamp_dtype_rule, 'clamp')\nad.defjvp(clamp_p,\n lambda g, min, operand, max:\n select(bitwise_and(gt(min, operand), lt(min, max)),\n _brcast(g, operand), _zeros(operand)),\n lambda g, min, operand, max:\n select(bitwise_and(gt(operand, min), lt(operand, max)),\n g, _zeros(operand)),\n lambda g, min, operand, max:\n select(lt(max, operand), _brcast(g, operand), _zeros(operand)))\n\n\ndef _concatenate_shape_rule(*operands, **kwargs):\n dimension = kwargs.pop('dimension')\n if not operands:\n msg = \"concatenate expects at least one operand, got 0.\"\n raise TypeError(msg)\n if not all(isinstance(operand, UnshapedArray) for operand in operands):\n msg = \"All objects to concatenate must be arrays, got {}.\"\n op = next(op for op in operands if not isinstance(op, UnshapedArray))\n raise TypeError(msg.format(type(op)))\n if len(set(operand.ndim for operand in operands)) != 1:\n msg = \"Cannot concatenate arrays with different ranks, got {}.\"\n raise TypeError(msg.format(\", \".join(str(o.ndim) for o in operands)))\n shapes = onp.array([operand.shape for operand in operands])\n if not 0 <= dimension < shapes.shape[1]:\n msg = \"concatenate dimension out of bounds: dimension {} for shapes {}.\"\n raise TypeError(msg.format(dimension, \", \".join(map(str, shapes))))\n if not onp.all(onp.delete(shapes[0] == shapes, dimension, axis=1)):\n msg = (\"Cannot concatenate arrays with shapes that differ in dimensions \"\n \"other than the one being concatenated: dimension {} for shapes {}.\")\n raise TypeError(msg.format(dimension, \", \".join(map(str, shapes))))\n\n concat_size = sum(o.shape[dimension] for o in operands)\n ex_shape = operands[0].shape\n return ex_shape[:dimension] + (concat_size,) + ex_shape[dimension+1:]\n\ndef _concatenate_dtype_rule(*operands, **kwargs):\n _check_same_dtypes('concatenate', False, *(o.dtype for o in operands))\n return operands[0].dtype\n\ndef _concatenate_translation_rule(c, *operands, **kwargs):\n dimension = kwargs.pop('dimension')\n return xops.ConcatInDim(c, operands, dimension)\n\ndef _concatenate_transpose_rule(t, *operands, dimension):\n operand_shapes = [o.aval.shape if ad.is_undefined_primal(o) else o.shape\n for o in operands]\n if t is ad_util.zero:\n return [ad_util.zero if ad.is_undefined_primal(o) else None for o in operands]\n else:\n limit_points = onp.cumsum([shape[dimension] for shape in operand_shapes])\n starts = onp.zeros((len(operands), t.ndim), dtype=int)\n starts[1:, dimension] = limit_points[:-1]\n limits = onp.tile(t.shape, (len(operands), 1))\n limits[:, dimension] = limit_points\n\n return [slice(t, start, limit) if ad.is_undefined_primal(o) else None\n for o, start, limit in zip(operands, starts, limits)]\n\ndef _concatenate_batch_rule(batched_args, batch_dims, *, dimension):\n size = next(op.shape[bdim] for op, bdim in zip(batched_args, batch_dims)\n if bdim is not None)\n operands = [batching.moveaxis(op, bdim, 0) if bdim is not None\n else broadcast(op, (size,))\n for op, bdim in zip(batched_args, batch_dims)]\n return concatenate(operands, dimension + 1), 0\n\n# The concatenate_p masking rule requires use of a while-loop construct and so\n# is defined in lax_control_flow.py\n\nconcatenate_p = standard_primitive(\n _concatenate_shape_rule, _concatenate_dtype_rule, 'concatenate',\n _concatenate_translation_rule)\nad.deflinear(concatenate_p, _concatenate_transpose_rule)\nad.primitive_transposes[concatenate_p] = _concatenate_transpose_rule\nbatching.primitive_batchers[concatenate_p] = _concatenate_batch_rule\n\n\ndef _pad_dtype_rule(operand, padding_value, *, padding_config):\n if operand.dtype != padding_value.dtype:\n msg = \"pad operand and padding_value must be same dtype: got {} and {}.\"\n raise TypeError(msg.format(operand.dtype, padding_value.dtype))\n\n return _input_dtype(operand, padding_value)\n\ndef _pad_shape_rule(operand, padding_value, *, padding_config):\n lo, hi, interior = zip(*padding_config)\n out_shape = onp.add(onp.add(onp.add(lo, hi), operand.shape),\n onp.multiply(interior, onp.subtract(operand.shape, 1)))\n return tuple(out_shape)\n\ndef _pad_transpose(t, operand, padding_value, *, padding_config):\n if t is ad_util.zero:\n return [ad_util.zero if ad.is_undefined_primal(operand) else None,\n ad_util.zero if ad.is_undefined_primal(padding_value) else None]\n\n lo, hi, interior = zip(*padding_config)\n total = lambda x: _reduce_sum(x, list(range(t.ndim)))\n\n def t_op():\n unpad_config = zip(onp.negative(lo), onp.negative(hi), onp.zeros_like(interior))\n unpadded = pad(t, onp.array(0., t.dtype), unpad_config)\n return slice(unpadded, onp.zeros_like(lo), unpadded.shape, onp.add(interior, 1))\n\n t_operand = t_op() if ad.is_undefined_primal(operand) else None\n t_padv = sub(total(t), total(t_operand)) if ad.is_undefined_primal(padding_value) else None\n\n return [t_operand, t_padv]\n\ndef _pad_batch_rule(batched_args, batch_dims, *, padding_config):\n operand, padding_value = batched_args\n operand_bdim, padding_value_bdim = batch_dims\n if padding_value_bdim is None:\n assert operand_bdim is not None\n padding_config = list(padding_config)\n padding_config.insert(operand_bdim, (0, 0, 0))\n return pad(operand, padding_value, padding_config), operand_bdim\n else:\n raise NotImplementedError # loop and stack\n\ndef _pad_translation_rule(c, operand, padding_value, *, padding_config):\n return xops.Pad(operand, padding_value,\n xc.make_padding_config(padding_config))\n\npad_p = standard_primitive(_pad_shape_rule, _pad_dtype_rule, 'pad',\n translation_rule=_pad_translation_rule)\nad.deflinear(pad_p, _pad_transpose)\nad.primitive_transposes[pad_p] = _pad_transpose\nbatching.primitive_batchers[pad_p] = _pad_batch_rule\n\n\n# We have a nonstandard reshape impl so that we can be lazy about data movement.\ndef _reshape_impl(operand, *, new_sizes, dimensions):\n old_sizes = onp.shape(operand)\n if type(operand) is xla.DeviceArray and dimensions is None:\n bcast_dims = _is_singleton_reshape(old_sizes, new_sizes)\n if bcast_dims is not None:\n aval = ShapedArray(new_sizes, operand.dtype)\n lazy_expr = lazy.broadcast(operand._lazy_expr, new_sizes, bcast_dims)\n return xla.DeviceArray(aval, operand._device, lazy_expr, operand.device_buffer)\n\n if type(operand) is pxla.ShardedDeviceArray and dimensions is None:\n array = _reshape_sharded_device_array(operand, new_sizes, old_sizes)\n if array is not None:\n return array\n\n return xla.apply_primitive(reshape_p, operand, new_sizes=new_sizes,\n dimensions=dimensions)\n\ndef _is_singleton_reshape(old, new):\n # A singleton reshape is one where only singleton dimensions are added. We\n # want to detect them because they can be expressed as (lazy) broadcasts.\n old, new = iter(old), iter(new)\n d1, d2 = next(old, None), next(new, None)\n bcast_dims = []\n i = 0\n while True:\n if d1 is d2 is None:\n return bcast_dims\n elif d1 == d2:\n bcast_dims.append(i)\n i += 1\n d1, d2 = next(old, None), next(new, None)\n elif d2 == 1:\n i += 1\n d2 = next(new, None)\n else:\n return None\n\ndef _reshape_sharded_device_array(array, new_sizes, old_sizes):\n \"\"\"Returns None if `array` could not be efficiently reshaped.\n\n This function is primarily to support soft_pmap, although these optimizations\n could be useful when directly calling reshape as well.\n \"\"\"\n # TODO(jekbradbury): the axis split/merge logic below assumes that\n # ShardedDevicesArrays are always sharded across their leading axes. Remove\n # this constraint, especially if/when we add APIs that produce sharding across\n # interior axes.\n if any(num_shards != 1 for num_shards\n in array.sharding_spec.shards_per_axis[1:]):\n return None\n\n # TODO(skye): handle replicated buffers\n if array.sharding_spec.replication_factor != 1:\n return None\n\n # ShardedDevicesArrays require all buffers to have the same shape\n chunk_shape = array.device_buffers[0].shape().dimensions()\n chunk_size = chunk_shape[0] if len(chunk_shape) > 0 else 1\n\n if _is_axis_merge(old_sizes, new_sizes):\n num_chunks, ragged = divmod(new_sizes[0], chunk_size)\n if ragged: return None\n aval = ShapedArray(new_sizes, array.dtype)\n sharding_spec = pxla.ShardingSpec(\n shards_per_axis=(num_chunks,) + (1,) * (len(new_sizes) - 1),\n is_axis_materialized=(True,) * len(new_sizes),\n replication_factor=1)\n return pxla.ShardedDeviceArray(aval, sharding_spec, array.device_buffers)\n\n if _is_axis_split(old_sizes, new_sizes):\n split_axis_size, ragged = divmod(old_sizes[0], chunk_size)\n if ragged: return None\n if new_sizes[0] != split_axis_size: return None\n aval = ShapedArray(new_sizes, array.dtype)\n sharding_spec = pxla._pmap_sharding_spec(\n new_sizes[0], new_sizes[0], ShapedArray(new_sizes[1:], array.dtype), True)\n return pxla.ShardedDeviceArray(aval, sharding_spec, array.device_buffers)\n\n return None\n\ndef _is_axis_merge(s1, s2):\n # TODO(skye): we might still be able to handle these cases as merges, I\n # haven't thought about it much.\n if len(s1) < 2 or len(s2) < 1: return False\n return s1[2:] == s2[1:] and s1[0] * s1[1] == s2[0]\n\ndef _is_axis_split(s1, s2):\n return _is_axis_merge(s2, s1)\n\ndef _reshape_shape_rule(operand, *, new_sizes, dimensions):\n if not onp.all(onp.greater_equal(new_sizes, 0)):\n msg = 'reshape new_sizes must all be positive, got {}.'\n raise TypeError(msg.format(new_sizes))\n if prod(onp.shape(operand)) != prod(new_sizes):\n msg = 'reshape total size must be unchanged, got new_sizes {} for shape {}.'\n raise TypeError(msg.format(new_sizes, onp.shape(operand)))\n if dimensions is not None:\n if set(dimensions) != set(range(onp.ndim(operand))):\n msg = ('reshape dimensions must be a permutation of operand dimensions, '\n 'got dimensions {} for shape {}.')\n raise TypeError(msg.format(dimensions, onp.shape(operand)))\n return tuple(new_sizes)\n\ndef _reshape_dtype_rule(operand, *, new_sizes, dimensions):\n return operand.dtype\n\ndef _reshape_translation_rule(c, operand, *, new_sizes, dimensions):\n if dimensions is None:\n return xops.Reshape(operand, new_sizes)\n else:\n return xops.Reshape(operand, dimensions, new_sizes)\n\ndef _reshape_transpose_rule(t, operand, *, new_sizes, dimensions):\n assert ad.is_undefined_primal(operand)\n if dimensions is None:\n return [reshape(t, operand.aval.shape)]\n else:\n return [transpose(reshape(t, onp.take(operand.aval.shape, dimensions)),\n onp.argsort(dimensions))]\n\ndef _reshape_batch_rule(batched_args, batch_dims, *, new_sizes, dimensions):\n operand, = batched_args\n bdim, = batch_dims\n operand = batching.moveaxis(operand, bdim, 0)\n if dimensions is not None:\n dimensions = (0,) + tuple(onp.add(1, dimensions))\n return reshape(operand, operand.shape[:1] + new_sizes, dimensions), 0\n\nreshape_p = standard_primitive(_reshape_shape_rule, _reshape_dtype_rule,\n 'reshape', _reshape_translation_rule)\nreshape_p.def_impl(_reshape_impl)\nad.deflinear2(reshape_p, _reshape_transpose_rule)\nbatching.primitive_batchers[reshape_p] = _reshape_batch_rule\n\n\ndef _rev_shape_rule(operand, *, dimensions):\n _check_shapelike('rev', 'dimensions', dimensions)\n if len(set(dimensions)) != len(dimensions):\n msg = 'rev dimensions must be unique, got {}.'\n raise TypeError(msg.format(dimensions))\n if dimensions and not _max(dimensions) < operand.ndim:\n msg = ('rev dimensions must all be less than operand ndim, got dimensions '\n '{} for operand ndim {}.')\n raise TypeError(msg.format(dimensions, operand.ndim))\n return operand.shape\n\ndef _rev_batch_rule(batched_args, batch_dims, *, dimensions):\n operand, = batched_args\n bdim, = batch_dims\n new_dimensions = [i + 1 if i >= bdim else i for i in dimensions]\n return rev(operand, new_dimensions), bdim\n\nrev_p = standard_primitive(_rev_shape_rule, _input_dtype, 'rev')\nad.deflinear(rev_p, lambda t, dimensions: [rev(t, dimensions)])\nbatching.primitive_batchers[rev_p] = _rev_batch_rule\n\n\ndef _transpose_impl(operand, *, permutation):\n if type(operand) is xla.DeviceArray:\n lazy_expr = lazy.transpose(operand._lazy_expr, permutation)\n aval = ShapedArray(lazy_expr.shape, operand.dtype)\n return xla.DeviceArray(aval, operand._device, lazy_expr, operand.device_buffer)\n else:\n return xla.apply_primitive(transpose_p, operand, permutation=permutation)\n\ndef _transpose_shape_rule(operand, *, permutation):\n if not isinstance(permutation, (tuple, list, onp.ndarray)):\n msg = \"transpose permutation must be a tuple/list/ndarray, got {}.\"\n raise TypeError(msg.format(type(permutation)))\n if tuple(sorted(permutation)) != tuple(range(operand.ndim)):\n msg = (\"transpose permutation isn't a permutation of operand dimensions, \"\n \"got permutation {} for operand shape {}.\")\n raise TypeError(msg.format(permutation, operand.shape))\n return tuple(onp.take(operand.shape, permutation))\n\ndef _transpose_batch_rule(batched_args, batch_dims, *, permutation):\n operand, = batched_args\n bdim, = batch_dims\n perm = (bdim,) + tuple(i if i < bdim else i+1 for i in permutation)\n return transpose(operand, perm), 0\n\ntranspose_p = standard_primitive(_transpose_shape_rule, _input_dtype,\n 'transpose')\ntranspose_p.def_impl(_transpose_impl)\nad.deflinear(transpose_p,\n lambda t, permutation: [transpose(t, onp.argsort(permutation))])\nbatching.primitive_batchers[transpose_p] = _transpose_batch_rule\n\n\ndef _select_shape_rule(pred, on_true, on_false):\n if on_true.shape != on_false.shape:\n msg = \"select on_true and on_false must have the same shape, got {} and {}.\"\n raise TypeError(msg.format(on_true.shape, on_false.shape))\n if pred.shape and pred.shape != on_true.shape:\n msg = (\"select pred must be scalar or have the same shape as on_true and \"\n \"on_false, got pred shape {} for on_true and on_false of shape {}.\")\n raise TypeError(msg.format(pred.shape, on_true.shape))\n return on_true.shape\n\ndef _select_dtype_rule(pred, on_true, on_false):\n _check_same_dtypes(\"select\", False, on_true.dtype, on_false.dtype)\n if not dtypes.issubdtype(pred.dtype, onp.bool_):\n msg = \"select pred must be boolean type, got {}.\"\n raise TypeError(msg.format(pred.dtype))\n return on_true.dtype\n\ndef _select_transpose_rule(t, pred, on_true, on_false):\n assert not ad.is_undefined_primal(pred)\n if t is ad_util.zero:\n return [None,\n ad_util.zero if ad.is_undefined_primal(on_true) else None,\n ad_util.zero if ad.is_undefined_primal(on_false) else None]\n else:\n zeros = full_like(t, 0)\n return [None,\n select(pred, t, zeros) if ad.is_undefined_primal(on_true) else None,\n select(pred, zeros, t) if ad.is_undefined_primal(on_false) else None]\n\ndef _select_batch_rule(batched_args, batch_dims, **unused_kwargs):\n pred, on_true, on_false, = batched_args\n pred_bdim, ot_bdim, of_bdim = batch_dims\n size = next(x.shape[i] for x, i in zip(batched_args, batch_dims)\n if i is not None)\n\n # avoid transposes and some broadcasts in special cases\n if pred_bdim == ot_bdim == of_bdim:\n if onp.shape(pred) == onp.shape(on_true):\n return select(pred, on_true, on_false), pred_bdim\n else:\n # vmapped function had a scalar pred with nonscalar args\n assert onp.ndim(pred) == 1\n pred = broadcast_in_dim(pred, on_true.shape, [pred_bdim])\n return select(pred, on_true, on_false), pred_bdim\n elif onp.ndim(pred) == 0 and ot_bdim is not None and of_bdim is not None:\n if ot_bdim == of_bdim:\n return select(pred, on_true, on_false), ot_bdim\n elif onp.shape(on_true) == onp.shape(on_false):\n on_false = batching.moveaxis(on_false, of_bdim, ot_bdim)\n return select(pred, on_true, on_false), ot_bdim\n\n pred = batching.bdim_at_front(pred, pred_bdim, size) if onp.shape(pred) else pred\n if not onp.shape(on_true) == onp.shape(on_false) == ():\n on_true = batching.bdim_at_front(on_true, ot_bdim, size)\n on_false = batching.bdim_at_front(on_false, of_bdim, size)\n assert onp.shape(on_true) == onp.shape(on_false)\n if 0 < onp.ndim(pred) < onp.ndim(on_true):\n # vmapped function had a scalar pred with nonscalar args\n assert onp.ndim(pred) == 1\n pred = broadcast_in_dim(pred, on_true.shape, [0])\n if onp.ndim(pred) > onp.ndim(on_true):\n assert onp.ndim(on_true) == 0\n on_true = broadcast(on_true, pred.shape)\n on_false = broadcast(on_false, pred.shape)\n return select(pred, on_true, on_false), 0\n\nselect_p = standard_primitive(_select_shape_rule, _select_dtype_rule, 'select')\nad.defjvp(select_p,\n None,\n lambda g, b, x, y: select(b, g, _zeros(g)),\n lambda g, b, x, y: select(b, _zeros(g), g))\nad.primitive_transposes[select_p] = _select_transpose_rule\nbatching.primitive_batchers[select_p] = _select_batch_rule\n\n\ndef _slice_shape_rule(operand, *, start_indices, limit_indices, strides):\n _check_shapelike(\"slice\", \"start_indices\", start_indices)\n _check_shapelike(\"slice\", \"limit_indices\", limit_indices)\n if operand.ndim != len(start_indices):\n msg = (\"slice start_indices must have length equal to the number of \"\n \"dimensions of the operand, got indices {} for operand shape {}.\")\n raise TypeError(msg.format(start_indices, operand.shape))\n if len(start_indices) != len(limit_indices):\n msg = (\"slice limit_indices must have the same length as start_indices, \"\n \"got start_inidices {} and limit_indices {}.\")\n raise TypeError(msg.format(start_indices, limit_indices))\n if not onp.all(onp.less_equal(limit_indices, operand.shape)):\n msg = (\"slice limit_indices must be less than or equal to operand shape, \"\n \"got limit_indices {} for operand shape {}.\")\n raise TypeError(msg.format(limit_indices, operand.shape))\n if not onp.all(onp.greater_equal(start_indices, 0)):\n msg = (\"slice start_indices must be greater than or equal to zero, \"\n \"got start_indices of {}.\")\n raise TypeError(msg.format(start_indices))\n if not onp.all(onp.greater_equal(limit_indices, start_indices)):\n msg = (\"slice limit_indices must be greater than or equal to start_indices,\"\n \" got start_indices {} and limit_indices {}.\")\n raise TypeError(msg.format(start_indices, limit_indices))\n if strides is None:\n strides = onp.ones(operand.ndim, onp.int32)\n else:\n _check_shapelike(\"slice\", \"strides\", strides)\n if len(strides) != operand.ndim:\n msg = (\"slice strides must have length equal to the number of dimensions \"\n \"of the operand, got strides {} for operand shape {}.\")\n raise TypeError(msg.format(strides, operand.shape))\n if not onp.all(onp.greater(strides, 0)):\n msg = \"slice strides must be positive, got {}\"\n raise TypeError(msg.format(strides))\n\n result_shape = onp.floor_divide(\n onp.add(onp.subtract(limit_indices, start_indices), strides) - 1, strides)\n return tuple(result_shape)\n\ndef _slice_translation_rule(c, operand, *, start_indices, limit_indices,\n strides):\n return xops.Slice(operand, start_indices, limit_indices,\n strides or [1] * len(start_indices))\n\ndef _slice_transpose_rule(t, operand, *, start_indices, limit_indices, strides):\n assert ad.is_undefined_primal(operand)\n operand_shape = operand.aval.shape\n if strides is None or onp.all(onp.equal(strides, 1)):\n pads = zip(start_indices, onp.subtract(operand_shape, limit_indices),\n (0,) * len(start_indices))\n else:\n real_limits = onp.add(onp.add(start_indices, 1),\n onp.multiply(onp.subtract(t.shape, 1), strides))\n pads = zip(start_indices, onp.subtract(operand_shape, real_limits),\n onp.subtract(strides, 1))\n result = pad(t, _const(t, 0), pads)\n assert result.shape == operand_shape\n return [result]\n\ndef _slice_batching_rule(batched_args, batch_dims, *, start_indices,\n limit_indices, strides):\n operand, = batched_args\n bdim, = batch_dims\n\n new_start_indices = list(start_indices)\n new_start_indices.insert(bdim, 0)\n\n new_limit_indices = list(limit_indices)\n new_limit_indices.insert(bdim, operand.shape[bdim])\n\n if strides is None:\n new_strides = None\n else:\n new_strides = list(strides)\n new_strides.insert(bdim, 1)\n\n out = slice(operand, new_start_indices, new_limit_indices, new_strides)\n return out, bdim\n\nslice_p = standard_primitive(_slice_shape_rule, _input_dtype, 'slice',\n _slice_translation_rule)\nad.deflinear2(slice_p, _slice_transpose_rule)\nbatching.primitive_batchers[slice_p] = _slice_batching_rule\n\n\ndef _dynamic_slice_shape_rule(operand, *start_indices, slice_sizes):\n if operand.ndim != len(start_indices):\n msg = (\"dynamic_slice start_indices must have length equal to the number \"\n \"of dimensions of the operand, got indices {} for operand shape {}.\")\n raise TypeError(msg.format(start_indices, operand.shape))\n if len(start_indices) != len(slice_sizes):\n msg = (\"dynamic_slice slice_sizes must have the same length as \"\n \"start_indices, got start_inidices length {} and slice_sizes {}.\")\n raise TypeError(msg.format(len(start_indices), slice_sizes))\n if not onp.all(onp.less_equal(slice_sizes, operand.shape)):\n msg = (\"slice slice_sizes must be less than or equal to operand shape, \"\n \"got slice_sizes {} for operand shape {}.\")\n raise TypeError(msg.format(slice_sizes, operand.shape))\n if not onp.all(onp.greater_equal(slice_sizes, 0)):\n msg = (\"slice slice_sizes must be greater than or equal to zero, \"\n \"got slice_sizes of {}.\")\n raise TypeError(msg.format(slice_sizes))\n return tuple(slice_sizes)\n\ndef _dynamic_slice_dtype_rule(operand, *start_indices, slice_sizes):\n if any(i.dtype != start_indices[0].dtype or\n not dtypes.issubdtype(i.dtype, onp.integer) for i in start_indices):\n msg = (\"index arguments to dynamic_slice must be integers of the same \"\n \"type, got: {}\")\n raise TypeError(msg.format(\", \".join(i.dtype.name for i in start_indices)))\n return operand.dtype\n\ndef _dynamic_slice_translation_rule(c, operand, *start_indices, slice_sizes):\n return xops.DynamicSlice(operand, start_indices, slice_sizes)\n\ndef _dynamic_slice_jvp(primals, tangents, *, slice_sizes):\n tangent_out = ad_util.zero\n if tangents[0] is not ad_util.zero:\n tangent_out = dynamic_slice(tangents[0], primals[1:], slice_sizes)\n return dynamic_slice(primals[0], primals[1:], slice_sizes), tangent_out\n\ndef _dynamic_slice_transpose_rule(t, operand, *start_indices, slice_sizes):\n assert ad.is_undefined_primal(operand)\n assert all(not ad.is_undefined_primal(s) for s in start_indices)\n operand_shape = operand.aval.shape\n zeros = full(operand_shape, tie_in(t, _zero(t)))\n return ([dynamic_update_slice(zeros, t, start_indices)] +\n [None] * len(start_indices))\n\ndef _batch_dynamic_slice_indices(indices, bdims):\n size = next((x.shape[i] for x, i in zip(indices, bdims) if i is not None), -1)\n if size < 0:\n return concatenate([reshape(i, [1]) for i in indices], 0), None\n indices = concatenate(\n [broadcast_in_dim(x, (size, 1),\n broadcast_dimensions=((0,) if i is not None else ()))\n for x, i in zip(indices, bdims)],\n dimension=1)\n return indices, 0\n\ndef _dynamic_slice_batching_rule(batched_args, batch_dims, *, slice_sizes):\n # A dynamic slice is a special case of gather; we can delegate to the gather\n # batching rule.\n # TODO(phawkins): consider removing dynamic_slice entirely and using gather\n # always.\n operand, *start_indices = batched_args\n operand_bd, *start_idx_bds = batch_dims\n operand_shape = (operand.shape if operand_bd is batching.not_mapped\n else tuple(onp.delete(operand.shape, operand_bd)))\n dims = tuple(range(len(operand_shape)))\n dnums = GatherDimensionNumbers(offset_dims=dims, collapsed_slice_dims=(),\n start_index_map=dims)\n index, index_bdim = _batch_dynamic_slice_indices(start_indices, start_idx_bds)\n return _gather_batching_rule(\n [operand, index], [operand_bd, index_bdim], dimension_numbers=dnums,\n slice_sizes=slice_sizes)\n\n\ndynamic_slice_p = standard_primitive(\n _dynamic_slice_shape_rule, _dynamic_slice_dtype_rule, 'dynamic_slice',\n _dynamic_slice_translation_rule)\nad.primitive_jvps[dynamic_slice_p] = _dynamic_slice_jvp # TODO\nad.primitive_transposes[dynamic_slice_p] = _dynamic_slice_transpose_rule\nbatching.primitive_batchers[dynamic_slice_p] = _dynamic_slice_batching_rule\n\n\ndef _dynamic_update_slice_shape_rule(operand, update, *start_indices):\n if operand.ndim != update.ndim:\n msg = (\"dynamic_update_slice update must have the same rank as operand, \"\n \"got update shape {} for operand shape {}.\")\n raise TypeError(msg.format(update.shape, operand.shape))\n if operand.ndim != len(start_indices):\n msg = (\"dynamic_update_slice start_indices must have length equal to the \"\n \"rank of operand, got indices {} for operand shape {}.\")\n raise TypeError(msg.format(start_indices, operand.shape))\n if not onp.all(onp.less_equal(update.shape, operand.shape)):\n msg = (\"dynamic_update_slice update shape must be smaller than operand \"\n \"shape, got update shape {} for operand shape {}.\")\n raise TypeError(msg.format(update.shape, operand.shape))\n return operand.shape\n\ndef _dynamic_update_slice_dtype_rule(operand, update, *start_indices):\n _check_same_dtypes(\"dynamic_update_slice\", False, operand.dtype, update.dtype)\n if any(i.dtype != start_indices[0].dtype or\n not dtypes.issubdtype(i.dtype, onp.integer) for i in start_indices):\n msg = (\"index arguments to dynamic_update_slice must be integers of the \"\n \"same type, got {}\")\n raise TypeError(msg.format(\", \".join(i.dtype.name for i in start_indices)))\n return operand.dtype\n\ndef _dynamic_update_slice_jvp(primals, tangents):\n operand, update = primals[:2]\n start_indices = primals[2:]\n g_operand, g_update = tangents[:2]\n val_out = dynamic_update_slice(operand, update, start_indices)\n if g_operand is ad_util.zero and g_update is ad_util.zero:\n tangent_out = ad_util.zero\n else:\n g_operand = ad.instantiate_zeros(operand, g_operand)\n g_update = ad.instantiate_zeros(update, g_update)\n tangent_out = dynamic_update_slice(g_operand, g_update, start_indices)\n return val_out, tangent_out\n\ndef _dynamic_update_slice_transpose_rule(t, operand, update, *start_indices):\n assert all(not ad.is_undefined_primal(x) for x in start_indices)\n if ad.is_undefined_primal(update):\n update_shape = update.aval.shape\n else:\n update_shape = update.shape\n dus = dynamic_update_slice\n ds = dynamic_slice\n zeros = _zeros(t, shape=update_shape)\n operand_t = dus(t, zeros, start_indices) if ad.is_undefined_primal(operand) else None\n update_t = ds(t, start_indices, update_shape) if ad.is_undefined_primal(update) else None\n return [operand_t, update_t] + [None] * len(start_indices)\n\ndef _dynamic_update_slice_translation_rule(c, operand, update, *start_indices):\n return xops.DynamicUpdateSlice(operand, update, start_indices)\n\ndef _dynamic_update_slice_batching_rule(batched_args, batch_dims):\n # A dynamic update slice is a special case of scatter; we can delegate to the\n # scatter batching rule.\n # TODO(phawkins): consider removing dynamic_update_slice entirely and using\n # scatter always.\n operand, update, *start_idx = batched_args\n operand_bd, update_bd, *start_idx_bd = batch_dims\n update_shape = (update.shape if update_bd is batching.not_mapped\n else tuple(onp.delete(update.shape, update_bd)))\n dims = tuple(range(len(update_shape)))\n dnums = ScatterDimensionNumbers(update_window_dims=dims,\n inserted_window_dims=(),\n scatter_dims_to_operand_dims=dims)\n index, index_bdim = _batch_dynamic_slice_indices(start_idx, start_idx_bd)\n return _scatter_batching_rule(\n scatter, (operand, index, update), (operand_bd, index_bdim, update_bd),\n update_jaxpr=None, update_consts=None, dimension_numbers=dnums)\n\n\ndynamic_update_slice_p = standard_primitive(\n _dynamic_update_slice_shape_rule, _dynamic_update_slice_dtype_rule,\n 'dynamic_update_slice', _dynamic_update_slice_translation_rule)\nad.primitive_jvps[dynamic_update_slice_p] = _dynamic_update_slice_jvp\nad.primitive_transposes[dynamic_update_slice_p] = \\\n _dynamic_update_slice_transpose_rule\nbatching.primitive_batchers[dynamic_update_slice_p] = \\\n _dynamic_update_slice_batching_rule\n\n\ndef _gather_dimensions_proto(indices_shape, dimension_numbers):\n assert type(dimension_numbers) is GatherDimensionNumbers\n proto = xla_client.GatherDimensionNumbers()\n proto.offset_dims.extend(dimension_numbers.offset_dims)\n proto.collapsed_slice_dims.extend(dimension_numbers.collapsed_slice_dims)\n proto.start_index_map.extend(dimension_numbers.start_index_map)\n assert indices_shape.rank() > 0\n proto.index_vector_dim = indices_shape.rank() - 1\n return proto\n\ndef _gather_dtype_rule(operand, start_indices, **kwargs):\n if not dtypes.issubdtype(start_indices.dtype, onp.integer):\n raise ValueError(\"start_indices must have an integer type\")\n return dtypes.canonicalize_dtype(operand.dtype)\n\ndef _gather_shape_rule(operand, start_indices, *, dimension_numbers,\n slice_sizes):\n if len(operand.shape) != len(slice_sizes):\n msg = (\"slice_sizes must have rank equal to the gather operand; \"\n \"operand.shape={}, slice_sizes={}\".format(operand.shape, slice_sizes))\n raise ValueError(msg)\n result_rank = len(dimension_numbers.offset_dims) + start_indices.ndim - 1\n start_indices_shape = iter(start_indices.shape[:-1])\n slice_sizes = iter(onp.delete(slice_sizes, dimension_numbers.collapsed_slice_dims))\n return tuple(next(slice_sizes) if i in dimension_numbers.offset_dims\n else next(start_indices_shape) for i in range(result_rank))\n\ndef _gather_translation_rule(c, operand, start_indices, *, dimension_numbers,\n slice_sizes):\n indices_shape = c.get_shape(start_indices)\n return xops.Gather(\n operand, start_indices,\n _gather_dimensions_proto(indices_shape, dimension_numbers), slice_sizes,\n indices_are_sorted=False)\n\ndef _gather_jvp_rule(g, operand, start_indices, *, dimension_numbers,\n slice_sizes):\n return gather(g, start_indices, dimension_numbers, slice_sizes)\n\ndef _gather_transpose_rule(t, operand, start_indices, *, dimension_numbers,\n slice_sizes):\n assert ad.is_undefined_primal(operand)\n operand_shape = operand.aval.shape\n if t is ad_util.zero:\n return [ad_util.zero, ad_util.zero]\n zeros = full(operand_shape, tie_in(t, _zero(t)))\n scatter_dnums = ScatterDimensionNumbers(\n update_window_dims=dimension_numbers.offset_dims,\n inserted_window_dims=dimension_numbers.collapsed_slice_dims,\n scatter_dims_to_operand_dims=dimension_numbers.start_index_map)\n return [scatter_add(zeros, start_indices, t, scatter_dnums), ad_util.zero]\n\ndef _gather_batching_rule(batched_args, batch_dims, *, dimension_numbers,\n slice_sizes):\n operand, start_indices = batched_args\n operand_bdim, start_indices_bdim = batch_dims\n\n if operand_bdim is not None and start_indices_bdim is None:\n operand = batching.moveaxis(operand, operand_bdim, 0)\n slice_sizes = (operand.shape[0],) + slice_sizes\n offset_dims = (0,) + tuple(onp.add(1, dimension_numbers.offset_dims))\n collapsed_slice_dims = tuple(onp.add(1, dimension_numbers.collapsed_slice_dims))\n start_index_map = tuple(onp.add(1, dimension_numbers.start_index_map))\n dnums = GatherDimensionNumbers(\n offset_dims=offset_dims,\n collapsed_slice_dims=collapsed_slice_dims,\n start_index_map=start_index_map)\n return gather(operand, start_indices, dimension_numbers=dnums,\n slice_sizes=slice_sizes), 0\n\n elif operand_bdim is None and start_indices_bdim is not None:\n start_indices = batching.moveaxis(start_indices, start_indices_bdim, 0)\n offset_dims = tuple(onp.add(1, dimension_numbers.offset_dims))\n dnums = GatherDimensionNumbers(\n offset_dims=offset_dims,\n collapsed_slice_dims=dimension_numbers.collapsed_slice_dims,\n start_index_map=dimension_numbers.start_index_map)\n return gather(operand, start_indices, dimension_numbers=dnums,\n slice_sizes=slice_sizes), 0\n\n else:\n # move our batch dimensions to the front to preserve sanity\n operand = batching.moveaxis(operand, operand_bdim, 0)\n start_indices = batching.moveaxis(start_indices, start_indices_bdim, 0)\n\n # Example: user code had start_indices shape (3, 4, 5), and we have to deal\n # with start_indices shape (7, 3, 4, 5). We transform that to a\n # start_indices of shape (7, 3, 4, 6) where we concatenated an iota that\n # counts along our batch dimension to the front of the ndindex.\n count_shape = list(start_indices.shape)\n count_shape[-1] = 1\n counts = broadcasted_iota(start_indices.dtype, tuple(count_shape), 0)\n start_indices = concatenate([counts, start_indices], len(count_shape) - 1)\n\n slice_sizes = (1,) + slice_sizes\n collapsed_slice_dims = (0,) + tuple(onp.add(1, dimension_numbers.collapsed_slice_dims))\n offset_dims = tuple(onp.add(1, dimension_numbers.offset_dims))\n start_index_map = (0,) + tuple(onp.add(1, dimension_numbers.start_index_map))\n\n dnums = GatherDimensionNumbers(\n offset_dims=offset_dims,\n collapsed_slice_dims=collapsed_slice_dims,\n start_index_map=start_index_map)\n return gather(operand, start_indices, dimension_numbers=dnums,\n slice_sizes=slice_sizes), 0\n\ngather_p = standard_primitive(\n _gather_shape_rule, _gather_dtype_rule, 'gather',\n _gather_translation_rule)\nad.defjvp(gather_p, _gather_jvp_rule, None)\n\nad.primitive_transposes[gather_p] = _gather_transpose_rule\nbatching.primitive_batchers[gather_p] = _gather_batching_rule\n\n\ndef _scatter_dimensions_proto(indices_shape, dimension_numbers):\n assert type(dimension_numbers) is ScatterDimensionNumbers\n proto = xla_client.ScatterDimensionNumbers()\n proto.update_window_dims.extend(dimension_numbers.update_window_dims)\n proto.inserted_window_dims.extend(dimension_numbers.inserted_window_dims)\n proto.scatter_dims_to_operand_dims.extend(\n dimension_numbers.scatter_dims_to_operand_dims)\n assert indices_shape.rank() > 0\n proto.index_vector_dim = indices_shape.rank() - 1\n return proto\n\ndef _scatter_dtype_rule(operand, scatter_indices, updates, **kwargs):\n if not dtypes.issubdtype(scatter_indices.dtype, onp.integer):\n raise ValueError(\"scatter_indices must have an integer type\")\n _check_same_dtypes(\"scatter\", False, operand.dtype, updates.dtype)\n return dtypes.canonicalize_dtype(operand.dtype)\n\ndef _scatter_shape_rule(operand, scatter_indices, updates, **kwargs):\n return operand.shape\n\ndef _scatter_translation_rule(c, operand, scatter_indices, updates,\n update_jaxpr, update_consts, dimension_numbers):\n dtype = c.get_shape(operand).numpy_dtype()\n init_value = xb.constant(c, onp.array(0, dtype))\n update_computation = _reduction_computation(\n c, update_jaxpr, update_consts, init_value)\n indices_shape = c.get_shape(scatter_indices)\n return xops.Scatter(operand, scatter_indices, updates, update_computation,\n _scatter_dimensions_proto(indices_shape, dimension_numbers),\n False, False)\n\ndef _scatter_add_jvp(primals, tangents, *, update_jaxpr, update_consts,\n dimension_numbers):\n operand, scatter_indices, updates = primals\n g_operand, g_scatter_indices, g_updates = tangents\n val_out = scatter_add_p.bind(\n operand, scatter_indices, updates, update_jaxpr=update_jaxpr,\n update_consts=update_consts, dimension_numbers=dimension_numbers)\n if g_operand is ad_util.zero and g_updates is ad_util.zero:\n tangent_out = ad_util.zero\n else:\n g_operand = ad.instantiate_zeros(operand, g_operand)\n g_updates = ad.instantiate_zeros(updates, g_updates)\n tangent_out = scatter_add_p.bind(\n g_operand, scatter_indices, g_updates, update_jaxpr=update_jaxpr,\n update_consts=update_consts, dimension_numbers=dimension_numbers)\n return val_out, tangent_out\n\ndef _scatter_add_transpose_rule(t, operand, scatter_indices, updates, *,\n update_jaxpr, update_consts, dimension_numbers):\n assert not ad.is_undefined_primal(scatter_indices)\n if ad.is_undefined_primal(updates):\n updates_shape = updates.aval.shape\n else:\n updates_shape = updates.shape\n if t is ad_util.zero:\n return [ad_util.zero, None, ad_util.zero]\n\n operand_t = update_t = None\n if ad.is_undefined_primal(operand):\n operand_t = t\n\n if ad.is_undefined_primal(updates):\n gather_dnums = GatherDimensionNumbers(\n offset_dims=dimension_numbers.update_window_dims,\n collapsed_slice_dims=dimension_numbers.inserted_window_dims,\n start_index_map=dimension_numbers.scatter_dims_to_operand_dims)\n slice_sizes = []\n pos = 0\n for i in range(len(t.shape)):\n if i in dimension_numbers.inserted_window_dims:\n slice_sizes.append(1)\n else:\n slice_sizes.append(updates_shape[dimension_numbers.update_window_dims[pos]])\n pos += 1\n update_t = gather(t, scatter_indices, dimension_numbers=gather_dnums,\n slice_sizes=slice_sizes)\n return [operand_t, None, update_t]\n\ndef _scatter_mul_transpose_rule(t, operand, scatter_indices, updates, *,\n update_jaxpr, update_consts, dimension_numbers):\n assert not ad.is_undefined_primal(scatter_indices)\n if ad.is_undefined_primal(updates):\n updates_shape = updates.aval.shape\n else:\n updates_shape = updates.shape\n if t is ad_util.zero:\n return [ad_util.zero, None, ad_util.zero]\n\n operand_t = update_t = None\n if ad.is_undefined_primal(operand):\n operand_t = scatter_mul(t, scatter_indices, updates,\n dimension_numbers=dimension_numbers)\n\n if ad.is_undefined_primal(updates):\n gather_dnums = GatherDimensionNumbers(\n offset_dims=dimension_numbers.update_window_dims,\n collapsed_slice_dims=dimension_numbers.inserted_window_dims,\n start_index_map=dimension_numbers.scatter_dims_to_operand_dims)\n slice_sizes = []\n pos = 0\n for i in range(len(t.shape)):\n if i in dimension_numbers.inserted_window_dims:\n slice_sizes.append(1)\n else:\n slice_sizes.append(updates_shape[dimension_numbers.update_window_dims[pos]])\n pos += 1\n update_t = gather(mul(t, operand), scatter_indices,\n dimension_numbers=gather_dnums, slice_sizes=slice_sizes)\n return [operand_t, None, update_t]\n\n\ndef _scatter_batching_rule(scatter_op, batched_args, batch_dims, *,\n update_jaxpr, update_consts, dimension_numbers):\n operand, scatter_indices, updates = batched_args\n operand_bdim, scatter_indices_bdim, updates_bdim = batch_dims\n del update_jaxpr, update_consts # Unused.\n\n # move the operand batch dim to the front if it is not None, otherwise create\n # it at the front (so that we can scatter into it)\n size = next(x.shape[ax] for x, ax in zip(batched_args, batch_dims)\n if ax is not None)\n operand = batching.bdim_at_front(operand, operand_bdim, size)\n operand_bdim = 0\n\n updates = batching.bdim_at_front(updates, updates_bdim, size)\n\n if scatter_indices_bdim is None:\n inserted_window_dims = tuple(onp.add(1, dimension_numbers.inserted_window_dims))\n update_window_dims = (0,) + tuple(onp.add(1, dimension_numbers.update_window_dims))\n scatter_dims_to_operand_dims = tuple(onp.add(1, dimension_numbers.scatter_dims_to_operand_dims))\n dnums = ScatterDimensionNumbers(\n update_window_dims=update_window_dims,\n inserted_window_dims=inserted_window_dims,\n scatter_dims_to_operand_dims=scatter_dims_to_operand_dims)\n return scatter_op(operand, scatter_indices, updates, dnums), 0\n\n\n # see the third case in _gather_batching_rule for comparison and comments\n scatter_indices = batching.bdim_at_front(\n scatter_indices, scatter_indices_bdim, size)\n\n count_shape = list(scatter_indices.shape)\n count_shape[-1] = 1\n counts = broadcasted_iota(scatter_indices.dtype, tuple(count_shape), 0)\n scatter_indices = concatenate([counts, scatter_indices],\n len(count_shape) - 1)\n\n update_window_dims = tuple(onp.add(1, dimension_numbers.update_window_dims))\n inserted_window_dims = (0,) + tuple(onp.add(1, dimension_numbers.inserted_window_dims))\n scatter_dims_to_operand_dims = (0,) + tuple(onp.add(1, dimension_numbers.scatter_dims_to_operand_dims))\n\n dnums = ScatterDimensionNumbers(\n update_window_dims=update_window_dims,\n inserted_window_dims=inserted_window_dims,\n scatter_dims_to_operand_dims=scatter_dims_to_operand_dims)\n return scatter_op(operand, scatter_indices, updates, dnums), 0\n\nscatter_add_p = standard_primitive(\n _scatter_shape_rule, _scatter_dtype_rule, 'scatter-add',\n _scatter_translation_rule)\nad.primitive_jvps[scatter_add_p] = _scatter_add_jvp\nad.primitive_transposes[scatter_add_p] = _scatter_add_transpose_rule\nbatching.primitive_batchers[scatter_add_p] = (\n partial(_scatter_batching_rule, scatter_add))\n\n\nscatter_mul_p = standard_primitive(\n _scatter_shape_rule, _scatter_dtype_rule, 'scatter-mul',\n _scatter_translation_rule)\n\ndef _scatter_mul_jvp_rhs(g, x, i, y, *, dimension_numbers, **kw):\n return mul(x, scatter_add(zeros_like_array(x), i, g,\n dimension_numbers=dimension_numbers))\n\nad.defjvp(scatter_mul_p,\n lambda g, x, i, y, **kw: scatter_mul_p.bind(g, i, y, **kw),\n None,\n _scatter_mul_jvp_rhs)\nad.primitive_transposes[scatter_mul_p] = _scatter_mul_transpose_rule\nbatching.primitive_batchers[scatter_mul_p] = (\n partial(_scatter_batching_rule, scatter_mul))\n\n# TODO(jlebar): Add derivatives.\nscatter_min_p = standard_primitive(\n _scatter_shape_rule, _scatter_dtype_rule, 'scatter-min',\n _scatter_translation_rule)\nbatching.primitive_batchers[scatter_min_p] = (\n partial(_scatter_batching_rule, scatter_min))\n\n# TODO(jlebar): Add derivatives.\nscatter_max_p = standard_primitive(\n _scatter_shape_rule, _scatter_dtype_rule, 'scatter-max',\n _scatter_translation_rule)\nbatching.primitive_batchers[scatter_max_p] = (\n partial(_scatter_batching_rule, scatter_max))\n\n\ndef _scatter_jvp(primals, tangents, *, update_jaxpr, update_consts,\n dimension_numbers):\n operand, scatter_indices, updates = primals\n g_operand, g_scatter_indices, g_updates = tangents\n dnums = dimension_numbers\n\n if g_operand is ad_util.zero and g_updates is ad_util.zero:\n val_out = scatter_p.bind(\n operand, scatter_indices, updates, update_jaxpr=update_jaxpr,\n update_consts=update_consts, dimension_numbers=dnums)\n tangent_out = ad_util.zero\n return val_out, tangent_out\n\n g_operand = ad.instantiate_zeros(operand, g_operand)\n g_updates = ad.instantiate_zeros(updates, g_updates)\n\n # If there are overlapping indices in the scatter, it is unspecified which\n # update \"wins\". So we use the following perhaps surprising scheme:\n # a) attach a positive ID to each update in updates, forming (value, id) pairs\n # (using a new array dimension because scatter doesn't actually support\n # pairs).\n # b) perform the scatter, yielding (value, id) updates, which we split apart.\n # c) perform the inverse gather on the ids (similar to\n # _scatter_add_transpose), and use it to build a mask for the tangent of\n # `updates`.\n # d) perform a scatter-add on the masked JVP values. A benefit of using\n # scatter-add here is that we don't need a `scatter` transpose rule.\n\n # a) add unique positive IDs (iotas) to the updates, and zeros to the operand.\n operand_shape = operand.shape\n updates_shape = updates.shape\n updates_dtype = _dtype(updates)\n\n new_operand = reshape(operand, (1,) + operand_shape)\n new_operand = pad(new_operand, _zero(operand),\n ((0, 1, 0),) + tuple((0, 0, 0) for _ in operand_shape))\n\n # We specify the dtype here in case `updates_shape` is an empty tuple, in\n # which case numpy defaults to float64.\n ids_shape = onp.array(updates_shape, dtype=onp.int32)\n ids_shape[dnums.update_window_dims,] = 1\n num_ids = onp.prod(ids_shape)\n update_ids = add(reshape(iota(updates_dtype, num_ids), ids_shape),\n _ones(updates))\n\n # TODO(phawkins): there is a potential bug here if the number of updates\n # is large enough to overflow the number of mantissa bits in a float so IDs\n # end up colliding. We could also utilize the exponent and sign bits, with a\n # little more work.\n assert num_ids < (2 ** dtypes.finfo(updates_dtype).nmant)\n\n updates = reshape(updates, (1,) + updates_shape)\n reshaped_update_ids = reshape(update_ids, (1,) + updates_shape)\n updates_and_ids = concatenate((updates, reshaped_update_ids), 0)\n\n new_dnums = ScatterDimensionNumbers(\n update_window_dims=(0,) + tuple(d + 1 for d in dnums.update_window_dims),\n inserted_window_dims=tuple(d + 1 for d in dnums.inserted_window_dims),\n scatter_dims_to_operand_dims=tuple(d + 1 for d in dnums.scatter_dims_to_operand_dims))\n outputs = scatter_p.bind(\n new_operand, scatter_indices, updates_and_ids, update_jaxpr=update_jaxpr,\n update_consts=update_consts, dimension_numbers=new_dnums)\n val_out = index_in_dim(outputs, 0, keepdims=False)\n scattered_ids = index_in_dim(outputs, 1, keepdims=False)\n\n # b) compute the inverse gather that \"undoes\" the scatter on the id values.\n gather_dnums = GatherDimensionNumbers(\n offset_dims=dnums.update_window_dims,\n collapsed_slice_dims=dnums.inserted_window_dims,\n start_index_map=dnums.scatter_dims_to_operand_dims)\n slice_sizes = []\n pos = 0\n for i in range(len(scattered_ids.shape)):\n if i in dnums.inserted_window_dims:\n slice_sizes.append(1)\n else:\n slice_sizes.append(updates_shape[dnums.update_window_dims[pos]])\n pos += 1\n gathered_update_ids = gather(scattered_ids, scatter_indices,\n dimension_numbers=gather_dnums,\n slice_sizes=slice_sizes)\n\n # c) mask off input JVP elements that do not correspond to a primal output.\n masked_g_operand = select(eq(scattered_ids, _zeros(scattered_ids)),\n g_operand, _zeros(g_operand))\n masked_g_updates = select(eq(update_ids, gathered_update_ids),\n g_updates, _zeros(g_updates))\n\n # d) perform a scatter-add to compute the tangent output.\n tangent_out = scatter_add(masked_g_operand, scatter_indices, masked_g_updates,\n dimension_numbers=dnums)\n return val_out, tangent_out\n\n\nscatter_p = standard_primitive(\n _scatter_shape_rule, _scatter_dtype_rule, 'scatter',\n _scatter_translation_rule)\nad.primitive_jvps[scatter_p] = _scatter_jvp\nbatching.primitive_batchers[scatter_p] = (\n partial(_scatter_batching_rule, scatter))\n\n\ndef _reduce_shape_rule(operand, init_value, *, computation, jaxpr, consts,\n dimensions):\n return tuple(onp.delete(operand.shape, dimensions))\n\ndef _reduce_translation_rule(c, operand, init_value, *, computation, jaxpr,\n consts, dimensions):\n xla_computation = _reduction_computation(c, jaxpr, consts, init_value)\n return xops.Reduce(c, [operand], [init_value], xla_computation, dimensions)\n\ndef _reduce_batch_rule(batched_args, batch_dims, *, computation, jaxpr, consts,\n dimensions):\n operand, init_value = batched_args\n operand_bdim, init_value_bdim = batch_dims\n if init_value_bdim is None:\n assert operand_bdim is not None\n new_dimensions = [d + bool(d >= operand_bdim) for d in dimensions]\n new_operand_bdim = operand_bdim - int(onp.sum(onp.less(dimensions, operand_bdim)))\n return reduce(operand, init_value, computation, new_dimensions), new_operand_bdim\n else:\n raise NotImplementedError # loop and stack\n\ndef _reduction_computation(c, jaxpr, consts, init_value):\n shape = c.get_shape(init_value)\n axis_env = xla.AxisEnv(1) # no parallel primitives inside reductions\n subc = xla_bridge.make_computation_builder(\"reduction_computation\")\n assert len(consts) == 0, \"Reduction computations cannot have constants\"\n args = [xb.parameter(subc, 0, shape), xb.parameter(subc, 1, shape)]\n out, = xla.jaxpr_subcomp(subc, jaxpr, None, axis_env, consts, '', *args)\n return subc.build(out)\n\ndef _masking_defreducer(prim, identity):\n masking.masking_rules[prim] = partial(_reducer_masking_rule, prim, identity)\n\ndef _reducer_masking_rule(prim, identity, padded_vals, logical_shapes,\n axes):\n (padded_val,), (logical_shape,) = padded_vals, logical_shapes\n padded_shape = masking.padded_shape_as_value(padded_val.shape)\n masks = [broadcasted_iota(onp.int32, padded_shape, i) < d\n for i, d in enumerate(logical_shape) if i in axes]\n mask = _reduce(operator.and_, masks)\n masked_val = select(mask, padded_val, identity(padded_shape, padded_val.dtype))\n return prim.bind(masked_val, axes=axes)\n\nreduce_p = standard_primitive(_reduce_shape_rule, _input_dtype, 'reduce',\n _reduce_translation_rule)\nbatching.primitive_batchers[reduce_p] = _reduce_batch_rule\n\n\ndef _reduce_number_dtype_rule(name, operand, *args, **kw):\n if not dtypes.issubdtype(operand.dtype, onp.number):\n raise TypeError(\"{} does not accept dtype {}. Accepted dtypes are subtypes \"\n \"of number.\".format(name, onp.dtype(operand.dtype).name))\n return dtypes.canonicalize_dtype(operand.dtype)\n\ndef _reduce_sum_shape_rule(operand, *, axes):\n return _reduce_op_shape_rule(operand, axes=axes)\n\ndef _reduce_sum_translation_rule(c, operand, *, axes):\n dtype = c.get_shape(operand).numpy_dtype()\n scalar = ShapedArray((), dtype)\n return xops.Reduce(c, [operand], [xb.constant(c, onp.array(0, dtype))],\n xla.primitive_subcomputation(add_p, scalar, scalar),\n axes)\n\ndef _reduce_sum_transpose_rule(cotangent, operand, *, axes):\n assert ad.is_undefined_primal(operand)\n input_shape = operand.aval.shape\n broadcast_dimensions = tuple(onp.delete(onp.arange(len(input_shape)), axes))\n result = broadcast_in_dim(cotangent, input_shape, broadcast_dimensions)\n assert result.shape == input_shape\n return [result]\n\nreduce_sum_p = standard_primitive(\n _reduce_sum_shape_rule, partial(_reduce_number_dtype_rule, 'reduce_sum'),\n 'reduce_sum', _reduce_sum_translation_rule)\nad.deflinear2(reduce_sum_p, _reduce_sum_transpose_rule)\nbatching.defreducer(reduce_sum_p)\n_masking_defreducer(reduce_sum_p,\n lambda shape, dtype: onp.broadcast_to(onp.array(0, dtype), shape))\n\n\ndef _reduce_op_shape_rule(operand, *, axes):\n return tuple(onp.delete(operand.shape, axes))\n\ndef _reduce_prod_translation_rule(c, operand, *, axes):\n dtype = c.get_shape(operand).numpy_dtype()\n scalar = ShapedArray((), dtype)\n return xops.Reduce(c, [operand], [xb.constant(c, onp.array(1, dtype))],\n xla.primitive_subcomputation(mul_p, scalar, scalar), axes)\n\ndef _reduce_prod_jvp_rule(primals, tangents, *, axes):\n operand, = primals\n tangent, = tangents\n input_shape = onp.array(operand.shape)\n\n n = onp.prod(input_shape[list(axes)])\n non_axes = onp.delete(onp.arange(len(input_shape)), axes)\n\n # Move the reduced axes to the front, and flatten them to 1D.\n permutation = axes + tuple(non_axes)\n new_shape = (n,) + tuple(input_shape[non_axes])\n operand = reshape(operand, new_shape, permutation)\n tangent = reshape(tangent, new_shape, permutation)\n\n def _reduce_prod_tree(x, axis=0):\n \"\"\"Reduce by repeatedly splitting the array and multiplying.\"\"\"\n while x.shape[axis] > 1:\n n = x.shape[axis]\n n1 = (n + 1) // 2\n n2 = n - n1\n x1 = slice_in_dim(x, 0, n1)\n x2 = slice_in_dim(x, n1, None)\n if n2 != n1:\n paddings = [(0, 0, 0)] * len(x.shape)\n paddings[axis] = (0, 1, 0)\n x2 = pad(x2, _const(x, 1), paddings)\n x = x1 * x2\n shape = list(x.shape)\n del shape[axis]\n return reshape(x, shape)\n\n return api.jvp(_reduce_prod_tree, (operand,), (tangent,))\n\n\nreduce_prod_p = standard_primitive(\n _reduce_op_shape_rule, partial(_reduce_number_dtype_rule, 'reduce_prod'),\n 'reduce_prod', _reduce_prod_translation_rule)\nad.primitive_jvps[reduce_prod_p] = _reduce_prod_jvp_rule\nbatching.defreducer(reduce_prod_p)\n\n\ndef _reduce_chooser_shape_rule(operand, *, axes):\n return tuple(onp.delete(operand.shape, axes))\n\ndef _reduce_chooser_translation_rule(prim, identity, c, operand, *, axes):\n dtype = c.get_shape(operand).numpy_dtype()\n scalar = ShapedArray((), dtype)\n return xops.Reduce(c, [operand], [xb.constant(c, identity(dtype))],\n xla.primitive_subcomputation(prim, scalar, scalar), axes)\n\ndef _reduce_chooser_jvp_rule(g, ans, operand, *, axes):\n # TODO(mattjj): an alternative is to use variadic reduce to compute the chosen\n # locations in a single pass (rather than comparing equality) and use a\n # gather, and/or even push along the chosen elements of g (b/112040122)\n shape = [1 if i in axes else d for i, d in enumerate(operand.shape)]\n location_indicators = convert_element_type(\n _eq_meet(operand, reshape(ans, shape)), g.dtype)\n counts = _reduce_sum(location_indicators, axes)\n return div(_reduce_sum(mul(g, location_indicators), axes), counts)\n\n_reduce_max_translation_rule = partial(_reduce_chooser_translation_rule, max_p,\n _get_max_identity)\nreduce_max_p = standard_primitive(_reduce_op_shape_rule, _input_dtype,\n 'reduce_max', _reduce_max_translation_rule)\nad.defjvp2(reduce_max_p, _reduce_chooser_jvp_rule)\nbatching.defreducer(reduce_max_p)\n\n\n_reduce_min_translation_rule = partial(\n _reduce_chooser_translation_rule, min_p, _get_min_identity)\nreduce_min_p = standard_primitive(_reduce_op_shape_rule, _input_dtype,\n 'reduce_min', _reduce_min_translation_rule)\nad.defjvp2(reduce_min_p, _reduce_chooser_jvp_rule)\nbatching.defreducer(reduce_min_p)\n\n\ndef _reduce_logical_shape_rule(operand, *, axes):\n if operand.dtype != onp.bool_:\n msg = \"logical reduction requires operand dtype bool, got {}.\"\n raise TypeError(msg.format(operand.dtype))\n return tuple(onp.delete(operand.shape, axes))\n\ndef _reduce_logical_translation_rule(prim, identity, c, operand, *, axes):\n scalar = ShapedArray((), onp.bool_)\n return xops.Reduce(c, [operand], [xb.constant(c, identity(onp.bool_))],\n xla.primitive_subcomputation(prim, scalar, scalar), axes)\n\n_reduce_or_translation_rule = partial(_reduce_logical_translation_rule,\n or_p, _get_max_identity)\nreduce_or_p = standard_primitive(_reduce_logical_shape_rule, _fixed_dtype(onp.bool_),\n 'reduce_or', _reduce_or_translation_rule)\nbatching.defreducer(reduce_or_p)\n\n\n_reduce_and_translation_rule = partial(_reduce_logical_translation_rule,\n and_p, _get_min_identity)\nreduce_and_p = standard_primitive(_reduce_logical_shape_rule, _fixed_dtype(onp.bool_),\n 'reduce_and', _reduce_and_translation_rule)\nbatching.defreducer(reduce_and_p)\n\ndef _reduce_window_shape_rule(operand, init_value, *, jaxpr, consts,\n window_dimensions, window_strides, padding):\n if operand.dtype != init_value.dtype:\n msg = (\"reduce_window got inconsistent dtypes for operand and init_value: \"\n \" got operand dtype {} and init_value dtype {}.\")\n raise TypeError(msg.format(operand.dtype, init_value.dtype))\n return _common_reduce_window_shape_rule(operand, window_dimensions,\n window_strides, padding)\n\ndef _reduce_window_translation_rule(c, operand, init_value, *, jaxpr, consts,\n window_dimensions, window_strides, padding):\n xla_computation = _reduction_computation(c, jaxpr, consts, init_value)\n pads = xc.window_padding_type_to_pad_values(\n padding, c.get_shape(operand).dimensions(), window_dimensions,\n window_strides)\n return xops.ReduceWindowWithGeneralPadding(\n operand, init_value, xla_computation, window_dimensions,\n window_strides, (), (), pads)\n\ndef _generic_reduce_window_batch_rule(\n batched_args, batch_dims, *, jaxpr, consts, window_dimensions,\n window_strides, padding):\n operand, init = batched_args\n bdim, init_bdim = batch_dims\n if init_bdim is not None:\n raise NotImplementedError(\"reduce_window batching is not implemented for \"\n \"initial values\")\n\n def reduce_window(x, window_dimensions, window_strides, padding):\n return reduce_window_p.bind(\n x, init, jaxpr=jaxpr, consts=consts, window_dimensions=window_dimensions,\n window_strides=window_strides, padding=padding)\n return _reduce_window_batch_rule(reduce_window, (operand,), (bdim,),\n window_dimensions, window_strides, padding)\n\n\nreduce_window_p = standard_primitive(\n _reduce_window_shape_rule, _input_dtype, 'reduce_window',\n _reduce_window_translation_rule)\nbatching.primitive_batchers[reduce_window_p] = _generic_reduce_window_batch_rule\n\n\ndef _reduce_window_sum_shape_rule(operand, *, window_dimensions, window_strides,\n padding):\n if not dtypes.issubdtype(operand.dtype, onp.number):\n msg = \"operand to reduce_window_sum must have a number dtype, got {}\"\n raise TypeError(msg.format(onp.dtype(operand.dtype).name))\n return _common_reduce_window_shape_rule(operand, window_dimensions,\n window_strides, padding)\n\ndef _reduce_window_sum_translation_rule(c, operand, *, window_dimensions,\n window_strides, padding):\n dtype = c.get_shape(operand).numpy_dtype()\n scalar = ShapedArray((), dtype)\n pads = xc.window_padding_type_to_pad_values(\n padding, c.get_shape(operand).dimensions(), window_dimensions,\n window_strides)\n return xops.ReduceWindowWithGeneralPadding(\n operand, xb.constant(c, onp.array(0, dtype)),\n xla.primitive_subcomputation(add_p, scalar, scalar), window_dimensions,\n window_strides, (), (), pads)\n\ndef _reduce_window_sum_transpose_rule(cotangent, operand, *, window_dimensions,\n window_strides, padding):\n assert ad.is_undefined_primal(operand)\n input_shape = operand.aval.shape\n in_pads = padtype_to_pads(input_shape, window_dimensions, window_strides,\n padding)\n ones = [1] * len(input_shape)\n pads = _conv_general_vjp_lhs_padding(\n input_shape, window_dimensions, window_strides, cotangent.shape, in_pads,\n ones, ones)\n padding_config = [(lo, hi, stride - 1)\n for (lo, hi), stride in zip(pads, window_strides)]\n pad_cotangent = pad(cotangent, _zero(cotangent), padding_config)\n result = _reduce_window_sum(pad_cotangent, window_dimensions, ones,\n xla_client.PaddingType.VALID)\n assert result.shape == input_shape\n return [result]\n\ndef _reduce_window_batch_rule(reduce_window, batched_args, bdims, *,\n window_dimensions, window_strides, padding):\n operand, = batched_args\n bdim, = bdims\n\n if bdim is not None:\n window_dimensions = \\\n window_dimensions[:bdim] + (1,) + window_dimensions[bdim:]\n window_strides = window_strides[:bdim] + (1,) + window_strides[bdim:]\n\n operand = reduce_window(\n operand, window_dimensions, window_strides, padding)\n\n return operand, bdim\n\nreduce_window_sum_p = standard_primitive(\n _reduce_window_sum_shape_rule, _input_dtype, 'reduce_window_sum',\n _reduce_window_sum_translation_rule)\nad.deflinear2(reduce_window_sum_p, _reduce_window_sum_transpose_rule)\nbatching.primitive_batchers[reduce_window_sum_p] = partial(\n _reduce_window_batch_rule, _reduce_window_sum)\n\ndef _reduce_window_chooser_translation_rule(\n prim, identity, c, operand, *, window_dimensions, window_strides, padding):\n dtype = c.get_shape(operand).numpy_dtype()\n scalar = ShapedArray((), dtype)\n pads = xc.window_padding_type_to_pad_values(\n padding, c.get_shape(operand).dimensions(), window_dimensions,\n window_strides)\n return xops.ReduceWindowWithGeneralPadding(\n operand, xb.constant(c, identity(dtype)),\n xla.primitive_subcomputation(prim, scalar, scalar), window_dimensions,\n window_strides, (), (), pads)\n\ndef _reduce_window_chooser_jvp_rule(prim, g, operand, *, window_dimensions,\n window_strides, padding):\n assert prim is max_p or prim is min_p\n select_prim = ge_p if prim is max_p else le_p\n return _select_and_gather_add(g, operand, select_prim, window_dimensions,\n window_strides, padding)\n\n\ndef _common_reduce_window_shape_rule(operand, window_dimensions,\n window_strides, padding):\n _check_shapelike(\"reduce_window\", \"window_dimensions\", window_dimensions)\n _check_shapelike(\"reduce_window\", \"window_strides\", window_strides)\n if operand.ndim != len(window_dimensions):\n msg = (\"reduce_window got the wrong number of window_dimensions for \"\n \"operand: got operand shape {} with window_dimensions {}.\")\n raise TypeError(msg.format(operand.shape, window_dimensions))\n if len(window_strides) != len(window_dimensions):\n msg = (\"reduce_window got inconsistent window_strides and \"\n \"window_dimensions: got window_strides {} and window_dimensions {}.\")\n raise TypeError(msg.format(window_strides, window_dimensions))\n\n return reduce_window_shape_tuple(operand.shape, window_dimensions,\n window_strides, padding)\n\ndef reduce_window_shape_tuple(operand_shape, window_dimensions, window_strides,\n padding):\n pads = padtype_to_pads(operand_shape, window_dimensions, window_strides, padding)\n operand_padded = onp.add(operand_shape, onp.add(*zip(*pads)))\n t = onp.floor_divide(\n onp.subtract(operand_padded, window_dimensions), window_strides) + 1\n return tuple(t)\n\n_reduce_window_max_translation_rule = partial(\n _reduce_window_chooser_translation_rule, max_p, _get_max_identity)\nreduce_window_max_p = standard_primitive(\n _common_reduce_window_shape_rule, _input_dtype, 'reduce_window_max',\n _reduce_window_max_translation_rule)\nad.defjvp(reduce_window_max_p, partial(_reduce_window_chooser_jvp_rule, max_p))\nbatching.primitive_batchers[reduce_window_max_p] = partial(\n _reduce_window_batch_rule, _reduce_window_max)\n\n_reduce_window_min_translation_rule = partial(\n _reduce_window_chooser_translation_rule, min_p, _get_min_identity)\nreduce_window_min_p = standard_primitive(\n _common_reduce_window_shape_rule, _input_dtype, 'reduce_window_min',\n _reduce_window_min_translation_rule)\nad.defjvp(reduce_window_min_p, partial(_reduce_window_chooser_jvp_rule, min_p))\n\n_reduce_window_min_batch_rule = partial(_reduce_window_batch_rule,\n _reduce_window_min)\nbatching.primitive_batchers[reduce_window_min_p] = partial(\n _reduce_window_batch_rule, _reduce_window_min)\n\n\ndef _select_and_scatter_shape_rule(\n operand, source, init_value, *, select_jaxpr, select_consts, scatter_jaxpr,\n scatter_consts, window_dimensions, window_strides, padding):\n _check_shapelike(\"select_and_scatter\", \"window_dimensions\", window_dimensions)\n _check_shapelike(\"select_and_scatter\", \"window_strides\", window_strides)\n if len(window_dimensions) != len(window_strides):\n msg = (\"select_and_scatter got inconsistent window_strides and \"\n \"window_dimensions: got window_strides {} and window_dimensions {}.\")\n raise TypeError(msg.format(window_strides, window_dimensions))\n return operand.shape\n\ndef _select_and_scatter_translation(\n c, operand, source, init_value, *, select_jaxpr, select_consts, scatter_jaxpr,\n scatter_consts, window_dimensions, window_strides, padding):\n select = _reduction_computation(c, select_jaxpr, select_consts, init_value)\n scatter = _reduction_computation(c, scatter_jaxpr, scatter_consts, init_value)\n pads = xc.window_padding_type_to_pad_values(\n padding, c.get_shape(operand).dimensions(), window_dimensions,\n window_strides)\n return xops.SelectAndScatterWithGeneralPadding(\n operand, select, window_dimensions, window_strides, pads, source,\n init_value, scatter)\n\nselect_and_scatter_p = standard_primitive(\n _select_and_scatter_shape_rule, _input_dtype, 'select_and_scatter',\n _select_and_scatter_translation)\n\n\ndef _select_and_scatter_add_shape_rule(\n source, operand, *, select_prim, window_dimensions, window_strides,\n padding):\n return operand.shape\n\ndef _select_and_scatter_add_translation(\n c, source, operand, *, select_prim, window_dimensions, window_strides,\n padding):\n dtype = c.get_shape(operand).numpy_dtype()\n scalar = ShapedArray((), dtype)\n select = xla.primitive_subcomputation(select_prim, scalar, scalar)\n scatter = xla.primitive_subcomputation(add_p, scalar, scalar)\n zero = xb.constant(c, onp.array(0, dtype))\n pads = xc.window_padding_type_to_pad_values(\n padding, c.get_shape(operand).dimensions(), window_dimensions,\n window_strides)\n return xops.SelectAndScatterWithGeneralPadding(\n operand, select, window_dimensions, window_strides, pads, source, zero,\n scatter)\n\ndef _select_and_scatter_add_jvp(\n primals, tangents, *, select_prim, window_dimensions, window_strides,\n padding):\n source, operand = primals\n g_source, g_operand = tangents\n val_out = _select_and_scatter_add(\n source, operand, select_prim, window_dimensions, window_strides,\n padding)\n del g_operand\n if g_source is ad_util.zero:\n tangent_out = ad_util.zero\n else:\n tangent_out = _select_and_scatter_add(\n g_source, operand, select_prim, window_dimensions,\n window_strides, padding)\n return val_out, tangent_out\n\ndef _select_and_scatter_add_transpose(\n t, source, operand, *, select_prim, window_dimensions, window_strides,\n padding):\n assert ad.is_undefined_primal(source) and not ad.is_undefined_primal(operand)\n source_t = _select_and_gather_add(t, operand, select_prim, window_dimensions,\n window_strides, padding)\n return [source_t, None]\n\ndef _select_and_scatter_add_batch_rule(batched_args, batch_dims, **kwargs):\n source, operand = batched_args\n s_bdims, o_bdims = batch_dims\n\n if s_bdims is not None and o_bdims is not None:\n #TODO(#212): use a map construct instead of unrolling.\n source = batching.moveaxis(source, s_bdims, 0)\n operand = batching.moveaxis(operand, o_bdims, 0)\n outputs = [\n _select_and_scatter_add(s, o, **kwargs) for s, o in zip(source, operand)]\n outputs = [reshape(out, (1,) + out.shape) for out in outputs]\n outputs = concatenate(outputs, 0)\n return outputs, 0\n elif s_bdims is not None:\n #TODO(#212): use a map construct instead of unrolling.\n source = batching.moveaxis(source, s_bdims, 0)\n outputs = [\n _select_and_scatter_add(s, operand, **kwargs) for s in source]\n outputs = [reshape(out, (1,) + out.shape) for out in outputs]\n outputs = concatenate(outputs, 0)\n return outputs, 0\n elif o_bdims is not None:\n #TODO(#212): use a map construct instead of unrolling.\n operand = batching.moveaxis(operand, o_bdims, 0)\n outputs = [\n _select_and_scatter_add(source, o, **kwargs) for o in operand]\n outputs = [reshape(out, (1,) + out.shape) for out in outputs]\n outputs = concatenate(outputs, 0)\n return outputs, 0\n\nselect_and_scatter_add_p = standard_primitive(\n _select_and_scatter_add_shape_rule, _input_dtype, 'select_and_scatter_add',\n _select_and_scatter_add_translation)\nad.primitive_transposes[select_and_scatter_add_p] = \\\n _select_and_scatter_add_transpose\nad.primitive_jvps[select_and_scatter_add_p] = _select_and_scatter_add_jvp\nbatching.primitive_batchers[select_and_scatter_add_p] = \\\n _select_and_scatter_add_batch_rule\n\ndef _select_and_gather_add_shape_rule(\n tangents, operand, *, select_prim, window_dimensions, window_strides,\n padding):\n if tangents.shape != operand.shape:\n msg = (\"select_and_gather_add tangents and operand shapes must match, \"\n \"got {} and {}.\")\n raise TypeError(msg.format(tangents.shape, operand.shape))\n return _common_reduce_window_shape_rule(operand, window_dimensions,\n window_strides, padding)\n\n\n_UINT_DTYPES = {\n 16: onp.uint16,\n 32: onp.uint32,\n 64: onp.uint64,\n}\n\n_INT_DTYPES = {\n 16: onp.int16,\n 32: onp.int32,\n 64: onp.int64,\n}\n\ndef _select_and_gather_add_translation(\n c, tangents, operand, *, select_prim, window_dimensions, window_strides,\n padding, max_bits=64):\n shape = c.get_shape(operand)\n dtype = shape.numpy_dtype()\n etype = shape.xla_element_type()\n nbits = dtypes.finfo(dtype).bits\n\n assert nbits <= max_bits\n double_word_reduction = nbits * 2 <= max_bits\n\n const = lambda c, dtype, x: xb.constant(c, onp.array(x, dtype=dtype),\n canonicalize_types=False)\n\n if double_word_reduction:\n # TODO(b/73062247): XLA doesn't yet implement ReduceWindow on tuples, so\n # we implement a pair-wise ReduceWindow by packing two k-bit values into\n # 2k-bit unsigned integer using bit tricks.\n word_dtype = _UINT_DTYPES[nbits]\n double_word_dtype = _UINT_DTYPES[nbits * 2]\n word_type = xla_client.dtype_to_etype(word_dtype)\n double_word_type = xla_client.dtype_to_etype(double_word_dtype)\n\n # Packs two values into a tuple.\n def pack(a, b):\n a = xops.BitcastConvertType(a, word_type)\n b = xops.BitcastConvertType(b, word_type)\n a = xops.ConvertElementType(a, double_word_type)\n b = xops.ConvertElementType(b, double_word_type)\n a = xops.ShiftLeft(a, const(c, double_word_dtype, nbits))\n return xops.Or(a, b)\n\n # Unpacks the first element of a tuple.\n def fst(c, t):\n st = xops.ShiftRightLogical(t, const(c, double_word_dtype, nbits))\n return xops.BitcastConvertType(xops.ConvertElementType(st, word_type), etype)\n\n # Unpacks the second element of a tuple.\n def snd(t):\n return xops.BitcastConvertType(xops.ConvertElementType(t, word_type), etype)\n\n else:\n # The double-word trick above only works if we have a sufficiently large\n # type. As an alternative, we can pack two half words into a single word,\n # at the cost of precision.\n # TODO(b/73062247): add support for tuple reductions and remove this case.\n warnings.warn(\"Using reduced precision for gradient of reduce-window \"\n \"min/max operator to work around missing XLA support for \"\n \"pair-reductions. This is likely from a second or \"\n \"higher derivative of a max-pooling operation.\")\n r_nbits = nbits // 2\n # Drop/round the bottom mantissa bits.\n nexp = dtypes.finfo(dtype).nexp\n nmant = r_nbits - nexp - 1\n\n double_word_dtype = word_dtype = _UINT_DTYPES[nbits]\n word_type = xla_client.dtype_to_etype(word_dtype)\n\n # Packs two values into a tuple.\n def pack(a, b):\n a = xops.ReducePrecision(a, exponent_bits=nexp, mantissa_bits=nmant)\n b = xops.ReducePrecision(b, exponent_bits=nexp, mantissa_bits=nmant)\n a = xops.BitcastConvertType(a, word_type)\n b = xops.BitcastConvertType(b, word_type)\n b = xops.ShiftRightLogical(b, const(c, word_dtype, r_nbits))\n return xops.Or(a, b)\n\n # Unpacks the first element of a tuple.\n def fst(c, t):\n st = xops.And(t, const(c, word_dtype, ((1 << r_nbits) - 1) << r_nbits))\n return xops.BitcastConvertType(st, etype)\n\n # Unpacks the second element of a tuple.\n def snd(t):\n return xops.BitcastConvertType(xops.ShiftLeft(t, const(c, word_dtype, r_nbits)),\n etype)\n\n def reducer():\n c = xla_bridge.make_computation_builder(\"select_and_gather_pair_reducer\")\n x = xb.parameter(c, 0,\n xla_client.Shape.array_shape(onp.dtype(double_word_dtype), ()))\n y = xb.parameter(c, 1,\n xla_client.Shape.array_shape(onp.dtype(double_word_dtype), ()))\n assert select_prim is ge_p or select_prim is le_p\n which = xops.Ge if select_prim is ge_p else xops.Le\n xops.Select(which(fst(c, x), fst(c, y)), x, y)\n return c.build()\n\n\n assert select_prim is ge_p or select_prim is le_p, select_prim\n init = -onp.inf if select_prim is ge_p else onp.inf\n pads = xc.window_padding_type_to_pad_values(\n padding, c.get_shape(operand).dimensions(), window_dimensions,\n window_strides)\n out = xops.ReduceWindowWithGeneralPadding(\n pack(operand, tangents), pack(const(c, dtype, init), const(c, dtype, 0)),\n reducer(), window_dimensions, window_strides, (), (), pads)\n return snd(out)\n\ndef _select_and_gather_add_jvp(\n primals, tangents, *, select_prim, window_dimensions, window_strides,\n padding):\n source, operand = primals\n g_source, g_operand = tangents\n val_out = _select_and_gather_add(\n source, operand, select_prim, window_dimensions, window_strides,\n padding)\n del g_operand\n if g_source is ad_util.zero:\n tangent_out = ad_util.zero\n else:\n tangent_out = _select_and_gather_add(\n g_source, operand, select_prim, window_dimensions,\n window_strides, padding)\n return val_out, tangent_out\n\ndef _select_and_gather_add_transpose(\n t, tangents, operand, *, select_prim, window_dimensions, window_strides,\n padding):\n assert ad.is_undefined_primal(tangents) and not ad.is_undefined_primal(operand)\n result = _select_and_scatter_add(t, operand, select_prim, window_dimensions,\n window_strides, padding)\n return [result, None]\n\ndef _select_and_gather_add_batching_rule(\n batched_args, batch_dims, *, select_prim, window_dimensions, window_strides,\n padding):\n t, x = batched_args\n t_bdim, x_bdim = batch_dims\n size = next(a.shape[bdim] for a, bdim in zip(batched_args, batch_dims)\n if bdim is not None)\n t = batching.bdim_at_front(t, t_bdim, size)\n x = batching.bdim_at_front(x, x_bdim, size)\n window_dimensions = (1,) + window_dimensions\n window_strides = (1,) + window_strides\n out = _select_and_gather_add(t, x, select_prim, window_dimensions,\n window_strides, padding)\n return (out, 0)\n\n\nselect_and_gather_add_p = standard_primitive(\n _select_and_gather_add_shape_rule, _input_dtype, 'select_and_gather_add',\n _select_and_gather_add_translation)\nad.primitive_jvps[select_and_gather_add_p] = _select_and_gather_add_jvp\nad.primitive_transposes[select_and_gather_add_p] = \\\n _select_and_gather_add_transpose\nbatching.primitive_batchers[select_and_gather_add_p] = \\\n _select_and_gather_add_batching_rule\nxla.backend_specific_translations['tpu'][select_and_gather_add_p] = partial(\n _select_and_gather_add_translation,\n max_bits=32)\n\n\n# Parallel prefix-scan. See:\n# https://developer.nvidia.com/gpugems/gpugems3/part-vi-gpu-computing/chapter-39-parallel-prefix-sum-scan-cuda\n# and\n# Blelloch, Guy E. 1990. \"Prefix Sums and Their Applications.\", Technical Report\n# CMU-CS-90-190, School of Computer Science, Carnegie Mellon University.\n#\n# Unlike the Blelloch algorithm, we use an out-of-place algorithm that uses 2n\n# space. This is somewhat wasteful if we are interested only in the output of\n# the forward pass, but more memory-efficient if we intend to differentiate\n# through the implementation of the scan.\ndef _prescan_power_of_two(x, axis: int, op: Callable, unit):\n n = x.shape[axis]\n assert n != 0 and n & (n - 1) == 0, \"n must be a power of 2\"\n\n # Upsweep\n xs = []\n for d in range(0, n.bit_length() - 1):\n x1 = slice_in_dim(x, 0, None, stride=2, axis=axis)\n xs.append(x1)\n x2 = slice_in_dim(x, 1, None, stride=2, axis=axis)\n x = op(x1, x2)\n total = x\n\n # Downsweep\n x = full_like(total, unit)\n pad_left = [(0, 0, 0)] * len(x.shape)\n pad_left[axis] = (1, 0, 1)\n pad_right = [(0, 0, 0)] * len(x.shape)\n pad_right[axis] = (0, 1, 1)\n for w in reversed(xs):\n x1 = pad(x, _const(x, 0), pad_right)\n x2 = pad(x, _const(x, 0), pad_left)\n w = pad(w, _const(x, 0), pad_left)\n x = x1 + op(x2, w)\n\n return x, total\n\n\ndef _parallel_prefix_scan(x, axis: int, op: Callable, unit):\n n = x.shape[axis]\n if n == 0:\n return x\n # Pads to the next largest power of two\n nbits = n.bit_length()\n if n == (1 << (nbits - 1)):\n nbits -= 1\n padding = [(0, 0, 0)] * len(x.shape)\n padding[axis] = (0, (1 << nbits) - n, 0)\n x = pad(x, _const(x, unit), padding)\n x, total = _prescan_power_of_two(x, axis, op, unit)\n return concatenate((slice_in_dim(x, 1, n, axis=axis), total), dimension=axis)\n\n_cumsum_prefix_scan = partial(_parallel_prefix_scan, op=add, unit=0)\n_cumprod_prefix_scan = partial(_parallel_prefix_scan, op=mul, unit=1)\n\ndef _cumred_shape_rule(x, *, axis: int):\n if axis < 0 or axis >= x.ndim:\n raise ValueError(\n \"axis {} is out of bounds for array of shape {}\".format(axis, x.shape))\n return x.shape\n\ndef _cumsum_transpose_rule(t, *, axis: int):\n return [rev(cumsum(rev(t, (axis,)), axis=axis), (axis,))]\n\ndef _cumprod_jvp_rule(primals, tangents, *, axis: int):\n # Irrespective of backend, we always use the parallel prefix scan\n # implementation when differentiating because reduce_window is not\n # arbitrarily differentiable.\n return api.jvp(partial(_cumprod_prefix_scan, axis=axis), primals, tangents)\n\n\ndef _cumred_tpu_translation_rule(window_reduce: Callable, unit, x, *,\n axis: int):\n # On TPU, an implementation using reduce_window is handled specially by the\n # compiler and is efficient. On other backends, it is O(n^2).\n n = x.shape[axis]\n if n == 0:\n return x\n padding = [(0, 0, 0)] * x.ndim\n padding[axis] = (n - 1, 0, 0)\n x = pad(x, _const(x, unit), padding)\n strides = [1] * x.ndim\n window_dims = [1] * x.ndim\n window_dims[axis] = n\n return window_reduce(x, window_dims, strides, xla_client.PaddingType.VALID)\n\ndef _cumred_batch_rule(prim, batched_args, batch_dims, *, axis: int):\n operand, = batched_args\n bdim, = batch_dims\n axis = axis if axis < bdim else axis + 1\n return prim.bind(operand, axis=axis), bdim\n\n\ncumsum_p = standard_primitive(\n _cumred_shape_rule, partial(_reduce_number_dtype_rule, \"cumsum\"),\n 'cumsum', xla.lower_fun(_cumsum_prefix_scan, multiple_results=False))\nad.deflinear(cumsum_p, _cumsum_transpose_rule)\nxla.backend_specific_translations['tpu'][cumsum_p] = xla.lower_fun(\n partial(_cumred_tpu_translation_rule, _reduce_window_sum, 0),\n multiple_results=False)\nbatching.primitive_batchers[cumsum_p] = partial(_cumred_batch_rule, cumsum_p)\n\n\ncumprod_p = standard_primitive(\n _cumred_shape_rule, partial(_reduce_number_dtype_rule, \"cumprod\"),\n 'cumprod', xla.lower_fun(_cumprod_prefix_scan, multiple_results=False))\nad.primitive_jvps[cumprod_p] = _cumprod_jvp_rule\nxla.backend_specific_translations['tpu'][cumprod_p] = xla.lower_fun(\n partial(_cumred_tpu_translation_rule, _reduce_window_prod, 1),\n multiple_results=False)\nbatching.primitive_batchers[cumprod_p] = partial(_cumred_batch_rule, cumprod_p)\n\n\ndef _sort_abstract_eval(*args, **kwargs):\n args = tuple(raise_to_shaped(arg) for arg in args)\n if any(arg.shape != args[0].shape for arg in args[1:]):\n shapes = \" \".join(str(a.shape) for a in args)\n raise TypeError(f\"Arguments to sort must have equal shapes, got: {shapes}\")\n return args\n\n\ndef _float_to_int_for_sort(x):\n # Switch from a floating point value to a integer value in such a way that\n # when using the integer value to compare, we get the same result for normal\n # values, and -nan is treated as the smallest value, and nan is treated as\n # the largest value.\n # If f is a float, and\n # x = bit_cast<int32>(f);\n # y = x < 0 ? int32_max - x : x;\n # then y is ordered as an int32 such that finite values have the obvious\n # order, -0 is ordered before 0, and -NaN and NaN appear at the beginning\n # and end of the ordering.\n # Note that in order to avoid -x to overflow, we calculate\n # int32_max - x as unsigned, and then convert back to signed.\n if x.dtype == dtypes.bfloat16:\n x = convert_element_type(x, onp.float32)\n nbits = onp.finfo(x).bits\n signed_dtype = _INT_DTYPES[nbits]\n unsigned_dtype = _UINT_DTYPES[nbits]\n\n signed = bitcast_convert_type(x, signed_dtype)\n unsigned = bitcast_convert_type(x, unsigned_dtype)\n flipped = bitcast_convert_type(\n sub(unsigned_dtype(onp.iinfo(signed_dtype).max), unsigned), signed_dtype)\n return select(lt(signed, _zero(signed)), flipped, signed)\n\n# Default comparator that sorts the operands only on their first arguments.\n# For floating point types, a total order is created where\n# -NaN < -infinity < ... < -0 < 0 < ... < infinity < NaN.\n# For complex types, the (real, imag) pairs are sorted lexicographically\n# (following NumPy's semantics).\n# This code adds complex-number support to the algorithm from:\n# https://github.com/tensorflow/tensorflow/blob/ba43780830f09da72081fe5061c436f1c6203a92/tensorflow/compiler/xla/client/lib/comparators.h#L33\ndef _sort_lt_comparator(*operands):\n assert len(operands) >= 2 and len(operands) % 2 == 0, operands\n x, y = operands[:2]\n assert x.dtype == y.dtype, (x.dtype, y.dtype)\n if onp.issubdtype(x.dtype, onp.complexfloating):\n x_keys = [_float_to_int_for_sort(real(x)), _float_to_int_for_sort(imag(x))]\n y_keys = [_float_to_int_for_sort(real(y)), _float_to_int_for_sort(imag(y))]\n elif onp.issubdtype(x.dtype, onp.floating):\n x_keys = [_float_to_int_for_sort(x)]\n y_keys = [_float_to_int_for_sort(y)]\n else:\n x_keys = [x]\n y_keys = [y]\n\n p = None\n for xk, yk in zip(x_keys[::-1], y_keys[::-1]):\n p = (bitwise_or(lt(xk, yk), bitwise_and(eq(xk, yk), p)) if p is not None\n else lt(xk, yk))\n return p\n\ndef _sort_translation_rule(c, *operands, dimension):\n types = [c.get_shape(x).xla_element_type() for x in operands]\n subc = xla_bridge.make_computation_builder(\"sort_lt_comparator\")\n params = [xb.parameter(subc, 2 * i + j, xc.Shape.array_shape(typ, ()))\n for i, typ in enumerate(types) for j in range(2)]\n result = xla.lower_fun(_sort_lt_comparator,\n multiple_results=False)(subc, *params)\n comparator = subc.build(result)\n out = xops.Sort(c, operands, dimension=dimension, is_stable=True,\n comparator=comparator)\n return out if len(operands) != 1 else xops.Tuple(c, [out])\n\ndef _sort_jvp(primals, tangents, *, dimension):\n shape = primals[0].shape\n iotas = []\n for dim, size in enumerate(shape):\n dtype = onp.int32 if size < onp.iinfo(onp.int32).max else onp.int64\n iotas.append(broadcasted_iota(dtype, shape, dim))\n primals = sort_p.bind(*(primals + (iotas[dimension],)), dimension=dimension)\n idx = tuple(primals[-1] if i == dimension else iotas[i]\n for i in range(len(shape)))\n tangents_out = tuple(ad_util.zero if t is ad_util.zero else t[idx]\n for t in tangents)\n return tuple(primals[:-1]), tangents_out\n\ndef _sort_batch_rule(batched_args, batch_dims, *, dimension):\n prototype_arg, new_bdim = next(\n (a, b) for a, b in zip(batched_args, batch_dims) if b is not None)\n new_args = []\n for arg, bdim in zip(batched_args, batch_dims):\n if bdim is None:\n dims = onp.delete(onp.arange(prototype_arg.ndim), new_bdim)\n new_args.append(broadcast_in_dim(arg, prototype_arg.shape, dims))\n else:\n new_args.append(batching.moveaxis(arg, bdim, new_bdim))\n new_dimension = dimension + (new_bdim <= dimension)\n bdims = (new_bdim,) * len(new_args)\n return sort_p.bind(*new_args, dimension=new_dimension), bdims\n\n\nsort_p = Primitive('sort')\nsort_p.multiple_results = True\nsort_p.def_impl(partial(xla.apply_primitive, sort_p))\nsort_p.def_abstract_eval(_sort_abstract_eval)\nxla.translations[sort_p] = _sort_translation_rule\nad.primitive_jvps[sort_p] = _sort_jvp\nbatching.primitive_batchers[sort_p] = _sort_batch_rule\n\n\ndef _top_k_abstract_eval(operand, *, k):\n if k < 0:\n raise ValueError(\"k argument to top_k must be nonnegative, got {}\".format(k))\n if len(operand.shape) == 0:\n raise TypeError(\"top_k operand must have >= 1 dimension, got {}\"\n .format(operand.shape))\n shape = list(operand.shape)\n if shape[-1] < k:\n msg = \"k argument to top_k must be no larger than minor dimension; {} vs {}\"\n raise ValueError(msg.format(k, shape))\n shape[-1] = k\n return (ShapedArray(shape, operand.dtype),\n ShapedArray(shape, onp.dtype(onp.int32)))\n\ndef _top_k_jvp(primals, tangents, *, k):\n operand, = primals\n tangent, = tangents\n primals_out = top_k(operand, k)\n if tangent is ad_util.zero:\n tangents_out = (ad_util.zero, ad_util.zero)\n else:\n _, k_idxs = primals_out\n idx_shape = k_idxs.shape\n rank = len(idx_shape)\n gather_index_shape = idx_shape + (1,)\n gather_indices = []\n for i in range(rank-1):\n _iota = iota(k_idxs.dtype, idx_shape[i])\n _iota = tie_in(operand, _iota)\n _iota = broadcast_in_dim(_iota, gather_index_shape, (i,))\n gather_indices.append(_iota)\n gather_indices.append(reshape(k_idxs, gather_index_shape))\n gather_indices = concatenate(gather_indices, dimension=rank)\n slice_sizes = (1,) * rank\n dnums = GatherDimensionNumbers(\n offset_dims=(),\n collapsed_slice_dims=tuple(range(rank)),\n start_index_map=tuple(range(rank)))\n tangents_out = (gather(tangent, gather_indices, dnums, slice_sizes),\n ad_util.zero)\n return primals_out, tangents_out\n\ndef _top_k_batch_rule(batched_args, batch_dims, *, k):\n operand, = batched_args\n bdim, = batch_dims\n if bdim == operand.ndim-1:\n perm = onp.arange(operand.ndim)\n perm[bdim-1], perm[bdim] = perm[bdim], perm[bdim-1]\n top_k_v, top_k_i = top_k(transpose(operand, perm), k=k)\n return (transpose(top_k_v, perm),\n transpose(top_k_i, perm)), (bdim, bdim)\n else:\n return top_k(operand, k=k), (bdim, bdim)\n\ntop_k_p = Primitive('top_k')\ntop_k_p.multiple_results = True\ntop_k_p.def_impl(partial(xla.apply_primitive, top_k_p))\ntop_k_p.def_abstract_eval(_top_k_abstract_eval)\nxla.translations[top_k_p] = partial(standard_translate, 'top_k')\nad.primitive_jvps[top_k_p] = _top_k_jvp\nbatching.primitive_batchers[top_k_p] = _top_k_batch_rule\n\ndef _tie_in_transpose_rule(t):\n return [ad_util.zero, t]\n\ndef _tie_in_batch_rule(batched_args, batch_dims):\n y = tie_in(*batched_args)\n _, bdim_y = batch_dims\n return y, bdim_y\n\ntie_in_p = Primitive('tie_in')\ntie_in_p.def_impl(lambda x, y: y)\ntie_in_p.def_abstract_eval(lambda x, y: raise_to_shaped(y))\nxla.translations[tie_in_p] = lambda c, x, y: y\nad.deflinear(tie_in_p, _tie_in_transpose_rule)\nbatching.primitive_batchers[tie_in_p] = _tie_in_batch_rule\nmasking.masking_rules[tie_in_p] = lambda vals, logical_shapes: vals[1]\n\n\ndef _stop_gradient_jvp_rule(primals, tangents):\n # if we don't call stop_gradient here, we'd only peel off one autodiff tracer\n x, = primals\n return stop_gradient(x), ad_util.zero\n\ndef _stop_gradient_batch_rule(batched_args, batch_dims):\n x, = batched_args\n dim, = batch_dims\n return stop_gradient(x), dim\n\nxla.translations[ad_util.stop_gradient_p] = lambda c, x: x\nad.primitive_jvps[ad_util.stop_gradient_p] = _stop_gradient_jvp_rule\nbatching.primitive_batchers[ad_util.stop_gradient_p] = _stop_gradient_batch_rule\n\n\ndef create_token(x):\n \"\"\"Creates an XLA token value with no preconditions for sequencing effects.\n\n Experimental.\n\n Args:\n x: a dummy argument used to tie the CreateToken operator into a trace. The\n value of `x` is ignored.\n \"\"\"\n # x is a dummy argument used to tie the operator into a trace.\n return create_token_p.bind(x)\n\ncreate_token_p = Primitive(\"create_token\")\ncreate_token_p.def_impl(partial(xla.apply_primitive, create_token_p))\ncreate_token_p.def_abstract_eval(lambda _: abstract_token)\nxla.translations[create_token_p] = lambda c, _: xops.CreateToken(c)\n\ndef after_all(*operands):\n \"\"\"Merges one or more XLA token values. Experimental.\n\n Wraps the XLA AfterAll operator.\"\"\"\n return after_all_p.bind(*operands)\n\ndef _after_all_abstract_eval(*operands):\n if any(x is not abstract_token for x in operands):\n raise TypeError(\"Arguments to after_all must be tokens\")\n return abstract_token\n\n\ndef _after_all_translation_rule(c, *operands):\n return xops.AfterAll(c, operands)\n\nafter_all_p = Primitive(\"after_all\")\nafter_all_p.def_impl(partial(xla.apply_primitive, after_all_p))\nafter_all_p.def_abstract_eval(_after_all_abstract_eval)\nxla.translations[after_all_p] = _after_all_translation_rule\n\n\ndef infeed(token, shape=None):\n \"\"\"Consumes an infeed value of `shape` from the host. Experimental.\n\n `token` is used to sequence infeed and outfeed effects.\n \"\"\"\n flat_shapes, treedef = pytree.flatten(shape)\n for shape in flat_shapes:\n if not isinstance(shape, ShapedArray):\n raise TypeError(\"shape argument to infeed must be a pytree of \"\n \"ShapedArray values, got {}\".format(shape))\n xs_and_token = infeed_p.bind(token, shapes=tuple(flat_shapes))\n return (treedef.unflatten(xs_and_token[:-1]), xs_and_token[-1])\n\ndef _infeed_abstract_eval(token, *, shapes):\n if token is not abstract_token:\n raise TypeError(\"First argument to infeed must be a token\")\n return shapes + (abstract_token,)\n\n\ndef _infeed_translation_rule(c, token, *, shapes):\n shape = tuple(xla.aval_to_xla_shape(x).with_major_to_minor_layout_if_absent()\n for x in shapes)\n xs_and_token = xops.InfeedWithToken(token,\n xla_client.Shape.tuple_shape(shape))\n xs = xops.GetTupleElement(xs_and_token, 0)\n token = xops.GetTupleElement(xs_and_token, 1)\n outs = [xops.GetTupleElement(xs, i) for i in range(len(shapes))] + [token]\n return xops.Tuple(c, outs)\n\ninfeed_p = Primitive(\"infeed\")\ninfeed_p.multiple_results = True\ninfeed_p.def_impl(partial(xla.apply_primitive, infeed_p))\ninfeed_p.def_abstract_eval(_infeed_abstract_eval)\nxla.translations[infeed_p] = _infeed_translation_rule\n\ndef outfeed(token, xs):\n \"\"\"Outfeeds value `xs` to the host. Experimental.\n\n `token` is used to sequence infeed and outfeed effects.\n \"\"\"\n flat_xs, _ = pytree.flatten(xs)\n return outfeed_p.bind(token, *flat_xs)\n\ndef _outfeed_abstract_eval(token, *xs):\n if token is not abstract_token:\n raise TypeError(\"First argument to outfeed must be a token\")\n return abstract_token\n\n\ndef _outfeed_translation_rule(c, token, *xs):\n t = xops.Tuple(c, xs)\n return xops.OutfeedWithToken(t, token, c.get_shape(t))\n\noutfeed_p = Primitive(\"outfeed\")\noutfeed_p.def_impl(partial(xla.apply_primitive, outfeed_p))\noutfeed_p.def_abstract_eval(_outfeed_abstract_eval)\nxla.translations[outfeed_p] = _outfeed_translation_rule\n\ndef rng_uniform(a, b, shape):\n \"\"\"Stateful PRNG generator. Experimental and its use is discouraged.\n\n Returns uniformly distributed random numbers in the range [a, b)\n\n You should use jax.random for most purposes; this function exists only for\n niche use cases with special performance requirements.\n\n This API may be removed at any time.\n \"\"\"\n return rng_uniform_p.bind(a, b, shape=tuple(shape))\n\ndef _rng_uniform_abstract_eval(a, b, *, shape):\n if a.dtype != b.dtype:\n raise ValueError(\n \"Arguments to rng_uniform must have identical dtypes, got {} \"\n \"and {}.\".format(a.dtype, b.dtype))\n if a.shape != () or b.shape != ():\n raise ValueError(\n \"Arguments to rng_uniform must be scalars; got shapes {} and {}.\"\n .format(a.shape, b.shape))\n return ShapedArray(shape, a.dtype)\n\ndef _rng_uniform_translation_rule(c, a, b, *, shape):\n xla_shape = xc.Shape.array_shape(c.get_shape(a).xla_element_type(), shape)\n return xops.RngUniform(a, b, xla_shape)\n\nrng_uniform_p = Primitive(\"rng_uniform\")\nrng_uniform_p.def_impl(partial(xla.apply_primitive, rng_uniform_p))\nrng_uniform_p.def_abstract_eval(_rng_uniform_abstract_eval)\nxla.translations[rng_uniform_p] = _rng_uniform_translation_rule\n\n### util\n\n_ndim = onp.ndim\n\n\ndef _dilate_shape(shape, dilation):\n \"\"\"Utility function for computing the shape resulting from a dilation.\"\"\"\n if not onp.all(onp.greater(dilation, 0)):\n msg = \"All dilations must be positive, got {}.\"\n raise TypeError(msg.format(dilation))\n dilation = (1,) * (len(shape) - len(dilation)) + tuple(dilation)\n return onp.where(shape == 0, 0,\n onp.multiply(dilation, onp.subtract(shape, 1)) + 1)\n\ndef _ceil_divide(x1, x2):\n return -onp.floor_divide(onp.negative(x1), x2)\n\ndef padtype_to_pads(in_shape, window_shape, window_strides, padding):\n \"\"\"Convert padding string to list of pairs of pad values.\"\"\"\n PaddingType = xla_client.PaddingType\n\n if isinstance(padding, str):\n mapping = {'VALID': PaddingType.VALID, 'SAME': PaddingType.SAME}\n try:\n padding = mapping[padding.upper()]\n except KeyError as err:\n msg = \"Unrecognized padding type: expected 'VALID' or 'SAME', got {}.\"\n raise RuntimeError(msg.format(padding)) from err\n\n if padding == PaddingType.SAME:\n out_shape = _ceil_divide(in_shape, window_strides)\n pad_sizes = onp.maximum(0, (out_shape - 1) * window_strides +\n window_shape - in_shape)\n return [(pad_size // 2, pad_size - pad_size // 2) for pad_size in pad_sizes]\n elif padding == PaddingType.VALID:\n return [(0, 0)] * len(in_shape)\n else:\n msg = \"Unknown padding type: {}.\"\n raise TypeError(msg.format(padding))\n\n\ndef _check_same_dtypes(name, ignore_fp_precision, *ttypes):\n \"\"\"Check that dtypes agree, possibly ignoring float precision.\"\"\"\n # the `ignore_fp_precision` flag exists because the XLA shape inference logic\n # allows mixed floating point precision, but the HLO verifier often rejects it\n types = list(map(onp.dtype, ttypes)) # canonicalize\n if ignore_fp_precision:\n types = [\n onp.floating if dtypes.issubdtype(dtype, onp.floating)\n else onp.complexfloating if dtypes.issubdtype(dtype, onp.complexfloating)\n else dtype for dtype in types]\n if len({dtypes.canonicalize_dtype(t) for t in types}) != 1:\n if ignore_fp_precision:\n msg = (\"{} requires arguments to have same dtypes up to floating point \"\n \"precision, got {}.\")\n else:\n msg = \"{} requires arguments to have the same dtypes, got {}.\"\n raise TypeError(msg.format(name, \", \".join(map(str, types))))\n\n\ndef _check_conv_shapes(name, lhs_shape, rhs_shape, window_strides):\n \"\"\"Check that conv shapes are valid and are consistent with window_strides.\"\"\"\n if len(lhs_shape) != len(rhs_shape):\n msg = \"Arguments to {} must have same rank, got {} and {}.\"\n raise TypeError(msg.format(name, len(lhs_shape), len(rhs_shape)))\n if len(lhs_shape) < 2:\n msg = \"Arguments to {} must have rank at least 2, got {} and {}.\"\n raise TypeError(msg.format(name, len(lhs_shape), len(rhs_shape)))\n if lhs_shape[1] != rhs_shape[1]:\n msg = \"Arguments to {} must agree on input feature size, got {} and {}.\"\n raise TypeError(msg.format(name, lhs_shape[1], rhs_shape[1]))\n _check_shapelike(name, \"window_strides\", window_strides)\n if not onp.all(onp.greater(window_strides, 0)):\n msg = \"All elements of window_strides must be positive, got {}.\"\n raise TypeError(msg.format(window_strides))\n if len(window_strides) != len(lhs_shape) - 2:\n msg = \"{} window_strides has wrong length: expected {}, got {}.\"\n expected_length = len(lhs_shape) - 2\n raise TypeError(msg.format(name, expected_length, len(window_strides)))\n\n\ndef conv_shape_tuple(lhs_shape, rhs_shape, strides, pads, batch_group_count=1):\n \"\"\"Compute the shape tuple of a conv given input shapes in canonical order.\"\"\"\n if isinstance(pads, str):\n pads = padtype_to_pads(lhs_shape[2:], rhs_shape[2:], strides, pads)\n if len(pads) != len(lhs_shape) - 2:\n msg = \"Wrong number of explicit pads for convolution: expected {}, got {}.\"\n raise TypeError(msg.format(len(lhs_shape) - 2, len(pads)))\n\n lhs_padded = onp.add(lhs_shape[2:], onp.sum(onp.array(pads).reshape(-1, 2),\n axis=1))\n out_space = onp.floor_divide(\n onp.subtract(lhs_padded, rhs_shape[2:]), strides) + 1\n out_space = onp.maximum(0, out_space)\n assert lhs_shape[0] % batch_group_count == 0\n out_shape = (lhs_shape[0] // batch_group_count, rhs_shape[0])\n return tuple(out_shape + tuple(out_space))\n\n\ndef conv_general_shape_tuple(lhs_shape, rhs_shape, window_strides, padding,\n dimension_numbers):\n lhs_perm, rhs_perm, out_perm = conv_general_permutations(dimension_numbers)\n lhs_trans = onp.take(lhs_shape, lhs_perm)\n rhs_trans = onp.take(rhs_shape, rhs_perm)\n out_trans = conv_shape_tuple(lhs_trans, rhs_trans, window_strides, padding)\n return tuple(onp.take(out_trans, onp.argsort(out_perm)))\n\n\ndef conv_transpose_shape_tuple(lhs_shape, rhs_shape, window_strides, padding,\n dimension_numbers):\n lhs_perm, rhs_perm, out_perm = conv_general_permutations(dimension_numbers)\n lhs_trans = onp.take(lhs_shape, lhs_perm)\n rhs_trans = onp.take(rhs_shape, rhs_perm)\n if isinstance(padding, str):\n padding = [_conv_transpose_padding(k, s, padding)\n for k,s in zip(rhs_trans[2:], window_strides)]\n padding = list(map(onp.sum, padding))\n unpad_out_space = [(i-1) * s - k + 2\n for i, k, s in zip(lhs_trans[2:],\n rhs_trans[2:],\n window_strides)]\n out_space = onp.sum([unpad_out_space, padding], axis=0).tolist()\n out_trans = tuple((lhs_trans[0], rhs_trans[0]) + tuple(out_space))\n return tuple(onp.take(out_trans, onp.argsort(out_perm)))\n\n\ndef _check_shapelike(fun_name, arg_name, obj):\n \"\"\"Check that `obj` is a shape-like value (e.g. tuple of nonnegative ints).\"\"\"\n if not isinstance(obj, (tuple, list, onp.ndarray)):\n msg = \"{} {} must be of type tuple/list/ndarray, got {}.\"\n raise TypeError(msg.format(fun_name, arg_name, type(obj)))\n # bool(obj) for an ndarray raises an error, so we check len\n if not len(obj): # pylint: disable=g-explicit-length-test\n return\n obj_arr = onp.array(obj)\n if obj_arr.ndim != 1:\n msg = \"{} {} must be rank 1, got {}.\"\n raise TypeError(msg.format(obj_arr.ndim))\n try:\n canonicalize_shape(obj_arr)\n except TypeError:\n msg = \"{} {} must have every element be an integer type, got {}.\"\n raise TypeError(msg.format(fun_name, arg_name, tuple(map(type, obj))))\n if not (obj_arr >= 0).all():\n msg = \"{} {} must have every element be nonnegative, got {}.\"\n raise TypeError(msg.format(fun_name, arg_name, obj))\n\n\ndef _dynamic_slice_indices(operand, start_indices):\n if not isinstance(start_indices, (tuple, list)):\n if start_indices.ndim != 1:\n raise ValueError(\"Slice indices must be a 1D sequence, got {}\"\n .format(start_indices.shape))\n start_indices = [reshape(slice(start_indices, [i], [i+1]), ())\n for i in range(operand.ndim)]\n else:\n start_indices = [onp.asarray(i, dtype=dtypes.int_) if isinstance(i, int)\n else i for i in start_indices]\n if len(start_indices) != operand.ndim:\n msg = (\"Length of slice indices must match number of operand dimensions ({} \"\n \"vs {})\")\n raise ValueError(msg.format(len(start_indices), operand.shape))\n # map int over operand.shape to raise any dynamic-shape errors\n return [select(lt(i, _const(i, 0)), add(i, _const(i, int(d))), i)\n for i, d in zip(start_indices, operand.shape)]\n\n\n\ndef _const(example, val):\n if dtypes.is_python_scalar(example):\n return dtypes.scalar_type_of(example)(val)\n return onp.array(val, _dtype(example))\n\n_zeros: Callable = partial(full_like, fill_value=0)\n_zero: Callable = partial(full_like, shape=(), fill_value=0)\n_ones: Callable = partial(full_like, fill_value=1)\n_one: Callable = partial(full_like, shape=(), fill_value=1)\n_twos: Callable = partial(full_like, fill_value=2)\n_two: Callable = partial(full_like, shape=(), fill_value=2)\n\ndtype: Callable = dtypes.result_type\n_dtype: Callable = dtypes.result_type\n\ndef _iscomplex(x) -> bool:\n return dtypes.issubdtype(_dtype(x), onp.complexfloating)\n\n\ndef ranges_like(*xs):\n start = 0\n for x in xs:\n x_len = len(x)\n yield range(start, start + x_len)\n start += x_len\n\n\ndef remaining(original, *removed_lists):\n blacklist = set(itertools.chain(*removed_lists))\n return [i for i in original if i not in blacklist]\n\n\ndef _canonicalize_precision(precision):\n if precision is None:\n return None\n if isinstance(precision, Precision):\n return precision\n else:\n msg = \"Precision argument must be None or a lax.Precision value; got {}\"\n raise ValueError(msg.format(precision))\n\n\ndef conv_dimension_numbers(lhs_shape, rhs_shape, dimension_numbers):\n \"\"\"Converts convolution `dimension_numbers` to a `ConvDimensionNumbers`.\n\n Args:\n lhs_shape: tuple of nonnegative integers, shape of the convolution input.\n rhs_shape: tuple of nonnegative integers, shape of the convolution kernel.\n dimension_numbers: None or a tuple/list of strings or a ConvDimensionNumbers\n object following the convolution dimension number specification format in\n xla_client.py.\n\n Returns:\n A `ConvDimensionNumbers` object that represents `dimension_numbers` in the\n canonical form used by lax functions.\n \"\"\"\n if isinstance(dimension_numbers, ConvDimensionNumbers):\n return dimension_numbers\n if len(lhs_shape) != len(rhs_shape):\n msg = \"convolution requires lhs and rhs ndim to be equal, got {} and {}.\"\n raise TypeError(msg.format(len(lhs_shape), len(rhs_shape)))\n\n if dimension_numbers is None:\n iota = tuple(range(len(lhs_shape)))\n return ConvDimensionNumbers(iota, iota, iota)\n elif isinstance(dimension_numbers, (list, tuple)):\n if len(dimension_numbers) != 3:\n msg = \"convolution dimension_numbers list/tuple must be length 3, got {}.\"\n raise TypeError(msg.format(len(dimension_numbers)))\n if not all(isinstance(elt, str) for elt in dimension_numbers):\n msg = \"convolution dimension_numbers elements must be strings, got {}.\"\n raise TypeError(msg.format(tuple(map(type, dimension_numbers))))\n msg = (\"convolution dimension_numbers[{}] must have len equal to the ndim \"\n \"of lhs and rhs, got {} for lhs and rhs shapes {} and {}.\")\n for i, elt in enumerate(dimension_numbers):\n if len(elt) != len(lhs_shape):\n raise TypeError(msg.format(i, len(elt), lhs_shape, rhs_shape))\n\n lhs_spec, rhs_spec, out_spec = conv_general_permutations(dimension_numbers)\n return ConvDimensionNumbers(lhs_spec, rhs_spec, out_spec)\n else:\n msg = \"convolution dimension_numbers must be tuple/list or None, got {}.\"\n raise TypeError(msg.format(type(dimension_numbers)))\n\n\ndef conv_general_permutations(dimension_numbers):\n \"\"\"Utility for convolution dimension permutations relative to Conv HLO.\"\"\"\n lhs_spec, rhs_spec, out_spec = dimension_numbers\n lhs_char, rhs_char, out_char = charpairs = (\"N\", \"C\"), (\"O\", \"I\"), (\"N\", \"C\")\n for i, (a, b) in enumerate(charpairs):\n if not dimension_numbers[i].count(a) == dimension_numbers[i].count(b) == 1:\n msg = (\"convolution dimension_numbers[{}] must contain the characters \"\n \"'{}' and '{}' exactly once, got {}.\")\n raise TypeError(msg.format(i, a, b, dimension_numbers[i]))\n if len(dimension_numbers[i]) != len(set(dimension_numbers[i])):\n msg = (\"convolution dimension_numbers[{}] cannot have duplicate \"\n \"characters, got {}.\")\n raise TypeError(msg.format(i, dimension_numbers[i]))\n if not (set(lhs_spec) - set(lhs_char) == set(rhs_spec) - set(rhs_char) ==\n set(out_spec) - set(out_char)):\n msg = (\"convolution dimension_numbers elements must each have the same \"\n \"set of spatial characters, got {}.\")\n raise TypeError(msg.format(dimension_numbers))\n\n def getperm(spec, charpair):\n spatial = (i for i, c in enumerate(spec) if c not in charpair)\n if spec is not rhs_spec:\n spatial = sorted(spatial, key=lambda i: rhs_spec.index(spec[i]))\n return (spec.index(charpair[0]), spec.index(charpair[1])) + tuple(spatial)\n\n lhs_perm, rhs_perm, out_perm = map(getperm, dimension_numbers, charpairs)\n return lhs_perm, rhs_perm, out_perm\n\n\ndef _conv_general_proto(dimension_numbers):\n assert type(dimension_numbers) is ConvDimensionNumbers\n lhs_spec, rhs_spec, out_spec = dimension_numbers\n proto = xla_client.ConvolutionDimensionNumbers()\n proto.input_batch_dimension = lhs_spec[0]\n proto.input_feature_dimension = lhs_spec[1]\n proto.output_batch_dimension = out_spec[0]\n proto.output_feature_dimension = out_spec[1]\n proto.kernel_output_feature_dimension = rhs_spec[0]\n proto.kernel_input_feature_dimension = rhs_spec[1]\n proto.input_spatial_dimensions.extend(lhs_spec[2:])\n proto.kernel_spatial_dimensions.extend(rhs_spec[2:])\n proto.output_spatial_dimensions.extend(out_spec[2:])\n return proto\n\n\ndef _conv_general_vjp_lhs_padding(\n in_shape, window_dimensions, window_strides, out_shape, padding,\n lhs_dilation, rhs_dilation):\n lhs_dilated_shape = _dilate_shape(in_shape, lhs_dilation)\n rhs_dilated_shape = _dilate_shape(window_dimensions, rhs_dilation)\n out_dilated_shape = _dilate_shape(out_shape, window_strides)\n pad_before = onp.subtract(rhs_dilated_shape, [lo for lo, _ in padding]) - 1\n pad_after = (onp.add(lhs_dilated_shape, rhs_dilated_shape) - 1\n - out_dilated_shape - pad_before)\n return zip(pad_before, pad_after)\n\n\ndef _conv_general_vjp_rhs_padding(\n in_shape, window_dimensions, window_strides, out_shape, padding,\n lhs_dilation, rhs_dilation):\n lhs_dilated_shape = _dilate_shape(in_shape, lhs_dilation)\n rhs_dilated_shape = _dilate_shape(window_dimensions, rhs_dilation)\n out_dilated_shape = _dilate_shape(out_shape, window_strides)\n total_in_pad = out_dilated_shape + rhs_dilated_shape - lhs_dilated_shape - 1\n return [(pad[0], tot - pad[0]) for pad, tot in zip(padding, total_in_pad)]\n\n\ndef _balanced_eq(x, z, y):\n return div(select(_eq_meet(x, z), _ones(z), _zeros(z)),\n select(_eq_meet(y, z), _twos(z), _ones(z)))\n\n\ndef _eq_meet(a, b):\n a_dtype, b_dtype = _dtype(a), _dtype(b)\n if a_dtype != b_dtype:\n higher_dtype = dtypes.promote_types(a_dtype, b_dtype)\n if higher_dtype == a_dtype:\n a = convert_element_type(a, b_dtype)\n else:\n b = convert_element_type(b, a_dtype)\n return eq(a, b)\n\n\ndef _abstractify(x):\n return raise_to_shaped(core.get_aval(x))\n\n\ndef _check_user_dtype_supported(dtype, fun_name=None):\n onp_dtype = onp.dtype(dtype)\n if onp_dtype.kind not in \"biufc\" and onp_dtype.type != dtypes.bfloat16:\n msg = f\"JAX only supports number and bool dtypes, got dtype {dtype}\"\n raise TypeError(msg)\n if dtype is not None and onp_dtype != dtypes.canonicalize_dtype(dtype):\n msg = (\"Explicitly requested dtype {} {} is not available, \"\n \"and will be truncated to dtype {}. To enable more dtypes, set the \"\n \"jax_enable_x64 configuration option or the JAX_ENABLE_X64 shell \"\n \"environment variable. \"\n \"See https://github.com/google/jax#current-gotchas for more.\")\n fun_name = \"requested in {}\".format(fun_name) if fun_name else \"\"\n truncated_dtype = dtypes.canonicalize_dtype(dtype).name\n warnings.warn(msg.format(dtype, fun_name , truncated_dtype))\n\n\ndef _canonicalize_axis(axis, num_dims):\n \"\"\"Canonicalize an axis in (-num_dims, num_dims) to [0, num_dims).\"\"\"\n axis = int(axis)\n if axis < 0:\n axis = axis + num_dims\n if axis < 0 or axis >= num_dims:\n raise ValueError(\n \"axis {} is out of bounds for array of dimension {}\".format(\n axis, num_dims))\n return axis\n"
] | [
[
"numpy.take",
"numpy.sqrt",
"numpy.asarray",
"numpy.issubdtype",
"numpy.cumsum",
"numpy.dtype",
"numpy.all",
"numpy.max",
"numpy.zeros_like",
"numpy.any",
"numpy.iinfo",
"numpy.negative",
"numpy.where",
"numpy.swapaxes",
"numpy.greater",
"numpy.arange",
"numpy.less",
"numpy.subtract",
"numpy.finfo",
"numpy.greater_equal",
"numpy.ceil",
"numpy.size",
"numpy.less_equal",
"numpy.zeros",
"numpy.ndim",
"numpy.delete",
"numpy.equal",
"numpy.not_equal",
"numpy.argsort",
"numpy.array",
"numpy.flip",
"numpy.sum",
"numpy.maximum",
"numpy.ones",
"numpy.shape",
"numpy.prod",
"numpy.add"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
mak213k/Servidor_automatizado_python | [
"75a111b9d3b2c50c6f2a9a36d21432053f02284d",
"34cfac4a889e2c973651c1c07740ea0908542d68",
"4403ef8027a2f814220baacc95856cf5fbf01d21",
"75a111b9d3b2c50c6f2a9a36d21432053f02284d",
"34cfac4a889e2c973651c1c07740ea0908542d68",
"4403ef8027a2f814220baacc95856cf5fbf01d21"
] | [
"ServidorPython/python32_web/Lib/site-packages/numpy/lib/tests/test_recfunctions.py",
"ServidorPython/python32_web/Lib/site-packages/sklearn/utils/estimator_checks.py",
"ServidorPython/python32_web/Lib/site-packages/sklearn/ensemble/_hist_gradient_boosting/tests/test_gradient_boosting.py",
"ServidorPython/python32_web/Lib/site-packages/numpy/lib/npyio.py",
"ServidorPython/python32_web/Lib/site-packages/scipy/signal/tests/test_fir_filter_design.py",
"ServidorPython/python32_web/Lib/site-packages/sklearn/metrics/scorer.py"
] | [
"from __future__ import division, absolute_import, print_function\n\nimport pytest\n\nimport numpy as np\nimport numpy.ma as ma\nfrom numpy.ma.mrecords import MaskedRecords\nfrom numpy.ma.testutils import assert_equal\nfrom numpy.testing import assert_, assert_raises\nfrom numpy.lib.recfunctions import (\n drop_fields, rename_fields, get_fieldstructure, recursive_fill_fields,\n find_duplicates, merge_arrays, append_fields, stack_arrays, join_by,\n repack_fields, unstructured_to_structured, structured_to_unstructured,\n apply_along_fields, require_fields, assign_fields_by_name)\nget_names = np.lib.recfunctions.get_names\nget_names_flat = np.lib.recfunctions.get_names_flat\nzip_descr = np.lib.recfunctions.zip_descr\n\n\nclass TestRecFunctions(object):\n # Misc tests\n\n def setup(self):\n x = np.array([1, 2, ])\n y = np.array([10, 20, 30])\n z = np.array([('A', 1.), ('B', 2.)],\n dtype=[('A', '|S3'), ('B', float)])\n w = np.array([(1, (2, 3.0)), (4, (5, 6.0))],\n dtype=[('a', int), ('b', [('ba', float), ('bb', int)])])\n self.data = (w, x, y, z)\n\n def test_zip_descr(self):\n # Test zip_descr\n (w, x, y, z) = self.data\n\n # Std array\n test = zip_descr((x, x), flatten=True)\n assert_equal(test,\n np.dtype([('', int), ('', int)]))\n test = zip_descr((x, x), flatten=False)\n assert_equal(test,\n np.dtype([('', int), ('', int)]))\n\n # Std & flexible-dtype\n test = zip_descr((x, z), flatten=True)\n assert_equal(test,\n np.dtype([('', int), ('A', '|S3'), ('B', float)]))\n test = zip_descr((x, z), flatten=False)\n assert_equal(test,\n np.dtype([('', int),\n ('', [('A', '|S3'), ('B', float)])]))\n\n # Standard & nested dtype\n test = zip_descr((x, w), flatten=True)\n assert_equal(test,\n np.dtype([('', int),\n ('a', int),\n ('ba', float), ('bb', int)]))\n test = zip_descr((x, w), flatten=False)\n assert_equal(test,\n np.dtype([('', int),\n ('', [('a', int),\n ('b', [('ba', float), ('bb', int)])])]))\n\n def test_drop_fields(self):\n # Test drop_fields\n a = np.array([(1, (2, 3.0)), (4, (5, 6.0))],\n dtype=[('a', int), ('b', [('ba', float), ('bb', int)])])\n\n # A basic field\n test = drop_fields(a, 'a')\n control = np.array([((2, 3.0),), ((5, 6.0),)],\n dtype=[('b', [('ba', float), ('bb', int)])])\n assert_equal(test, control)\n\n # Another basic field (but nesting two fields)\n test = drop_fields(a, 'b')\n control = np.array([(1,), (4,)], dtype=[('a', int)])\n assert_equal(test, control)\n\n # A nested sub-field\n test = drop_fields(a, ['ba', ])\n control = np.array([(1, (3.0,)), (4, (6.0,))],\n dtype=[('a', int), ('b', [('bb', int)])])\n assert_equal(test, control)\n\n # All the nested sub-field from a field: zap that field\n test = drop_fields(a, ['ba', 'bb'])\n control = np.array([(1,), (4,)], dtype=[('a', int)])\n assert_equal(test, control)\n\n test = drop_fields(a, ['a', 'b'])\n assert_(test is None)\n\n def test_rename_fields(self):\n # Test rename fields\n a = np.array([(1, (2, [3.0, 30.])), (4, (5, [6.0, 60.]))],\n dtype=[('a', int),\n ('b', [('ba', float), ('bb', (float, 2))])])\n test = rename_fields(a, {'a': 'A', 'bb': 'BB'})\n newdtype = [('A', int), ('b', [('ba', float), ('BB', (float, 2))])]\n control = a.view(newdtype)\n assert_equal(test.dtype, newdtype)\n assert_equal(test, control)\n\n def test_get_names(self):\n # Test get_names\n ndtype = np.dtype([('A', '|S3'), ('B', float)])\n test = get_names(ndtype)\n assert_equal(test, ('A', 'B'))\n\n ndtype = np.dtype([('a', int), ('b', [('ba', float), ('bb', int)])])\n test = get_names(ndtype)\n assert_equal(test, ('a', ('b', ('ba', 'bb'))))\n\n def test_get_names_flat(self):\n # Test get_names_flat\n ndtype = np.dtype([('A', '|S3'), ('B', float)])\n test = get_names_flat(ndtype)\n assert_equal(test, ('A', 'B'))\n\n ndtype = np.dtype([('a', int), ('b', [('ba', float), ('bb', int)])])\n test = get_names_flat(ndtype)\n assert_equal(test, ('a', 'b', 'ba', 'bb'))\n\n def test_get_fieldstructure(self):\n # Test get_fieldstructure\n\n # No nested fields\n ndtype = np.dtype([('A', '|S3'), ('B', float)])\n test = get_fieldstructure(ndtype)\n assert_equal(test, {'A': [], 'B': []})\n\n # One 1-nested field\n ndtype = np.dtype([('A', int), ('B', [('BA', float), ('BB', '|S1')])])\n test = get_fieldstructure(ndtype)\n assert_equal(test, {'A': [], 'B': [], 'BA': ['B', ], 'BB': ['B']})\n\n # One 2-nested fields\n ndtype = np.dtype([('A', int),\n ('B', [('BA', int),\n ('BB', [('BBA', int), ('BBB', int)])])])\n test = get_fieldstructure(ndtype)\n control = {'A': [], 'B': [], 'BA': ['B'], 'BB': ['B'],\n 'BBA': ['B', 'BB'], 'BBB': ['B', 'BB']}\n assert_equal(test, control)\n\n def test_find_duplicates(self):\n # Test find_duplicates\n a = ma.array([(2, (2., 'B')), (1, (2., 'B')), (2, (2., 'B')),\n (1, (1., 'B')), (2, (2., 'B')), (2, (2., 'C'))],\n mask=[(0, (0, 0)), (0, (0, 0)), (0, (0, 0)),\n (0, (0, 0)), (1, (0, 0)), (0, (1, 0))],\n dtype=[('A', int), ('B', [('BA', float), ('BB', '|S1')])])\n\n test = find_duplicates(a, ignoremask=False, return_index=True)\n control = [0, 2]\n assert_equal(sorted(test[-1]), control)\n assert_equal(test[0], a[test[-1]])\n\n test = find_duplicates(a, key='A', return_index=True)\n control = [0, 1, 2, 3, 5]\n assert_equal(sorted(test[-1]), control)\n assert_equal(test[0], a[test[-1]])\n\n test = find_duplicates(a, key='B', return_index=True)\n control = [0, 1, 2, 4]\n assert_equal(sorted(test[-1]), control)\n assert_equal(test[0], a[test[-1]])\n\n test = find_duplicates(a, key='BA', return_index=True)\n control = [0, 1, 2, 4]\n assert_equal(sorted(test[-1]), control)\n assert_equal(test[0], a[test[-1]])\n\n test = find_duplicates(a, key='BB', return_index=True)\n control = [0, 1, 2, 3, 4]\n assert_equal(sorted(test[-1]), control)\n assert_equal(test[0], a[test[-1]])\n\n def test_find_duplicates_ignoremask(self):\n # Test the ignoremask option of find_duplicates\n ndtype = [('a', int)]\n a = ma.array([1, 1, 1, 2, 2, 3, 3],\n mask=[0, 0, 1, 0, 0, 0, 1]).view(ndtype)\n test = find_duplicates(a, ignoremask=True, return_index=True)\n control = [0, 1, 3, 4]\n assert_equal(sorted(test[-1]), control)\n assert_equal(test[0], a[test[-1]])\n\n test = find_duplicates(a, ignoremask=False, return_index=True)\n control = [0, 1, 2, 3, 4, 6]\n assert_equal(sorted(test[-1]), control)\n assert_equal(test[0], a[test[-1]])\n\n def test_repack_fields(self):\n dt = np.dtype('u1,f4,i8', align=True)\n a = np.zeros(2, dtype=dt)\n\n assert_equal(repack_fields(dt), np.dtype('u1,f4,i8'))\n assert_equal(repack_fields(a).itemsize, 13)\n assert_equal(repack_fields(repack_fields(dt), align=True), dt)\n\n # make sure type is preserved\n dt = np.dtype((np.record, dt))\n assert_(repack_fields(dt).type is np.record)\n\n def test_structured_to_unstructured(self):\n a = np.zeros(4, dtype=[('a', 'i4'), ('b', 'f4,u2'), ('c', 'f4', 2)])\n out = structured_to_unstructured(a)\n assert_equal(out, np.zeros((4,5), dtype='f8'))\n\n b = np.array([(1, 2, 5), (4, 5, 7), (7, 8 ,11), (10, 11, 12)],\n dtype=[('x', 'i4'), ('y', 'f4'), ('z', 'f8')])\n out = np.mean(structured_to_unstructured(b[['x', 'z']]), axis=-1)\n assert_equal(out, np.array([ 3. , 5.5, 9. , 11. ]))\n out = np.mean(structured_to_unstructured(b[['x']]), axis=-1)\n assert_equal(out, np.array([ 1. , 4. , 7. , 10. ]))\n\n c = np.arange(20).reshape((4,5))\n out = unstructured_to_structured(c, a.dtype)\n want = np.array([( 0, ( 1., 2), [ 3., 4.]),\n ( 5, ( 6., 7), [ 8., 9.]),\n (10, (11., 12), [13., 14.]),\n (15, (16., 17), [18., 19.])],\n dtype=[('a', 'i4'),\n ('b', [('f0', 'f4'), ('f1', 'u2')]),\n ('c', 'f4', (2,))])\n assert_equal(out, want)\n\n d = np.array([(1, 2, 5), (4, 5, 7), (7, 8 ,11), (10, 11, 12)],\n dtype=[('x', 'i4'), ('y', 'f4'), ('z', 'f8')])\n assert_equal(apply_along_fields(np.mean, d),\n np.array([ 8.0/3, 16.0/3, 26.0/3, 11. ]))\n assert_equal(apply_along_fields(np.mean, d[['x', 'z']]),\n np.array([ 3. , 5.5, 9. , 11. ]))\n\n # check that for uniform field dtypes we get a view, not a copy:\n d = np.array([(1, 2, 5), (4, 5, 7), (7, 8 ,11), (10, 11, 12)],\n dtype=[('x', 'i4'), ('y', 'i4'), ('z', 'i4')])\n dd = structured_to_unstructured(d)\n ddd = unstructured_to_structured(dd, d.dtype)\n assert_(dd.base is d)\n assert_(ddd.base is d)\n\n # including uniform fields with subarrays unpacked\n d = np.array([(1, [2, 3], [[ 4, 5], [ 6, 7]]),\n (8, [9, 10], [[11, 12], [13, 14]])],\n dtype=[('x0', 'i4'), ('x1', ('i4', 2)), ('x2', ('i4', (2, 2)))])\n dd = structured_to_unstructured(d)\n ddd = unstructured_to_structured(dd, d.dtype)\n assert_(dd.base is d)\n assert_(ddd.base is d)\n\n # test that nested fields with identical names don't break anything\n point = np.dtype([('x', int), ('y', int)])\n triangle = np.dtype([('a', point), ('b', point), ('c', point)])\n arr = np.zeros(10, triangle)\n res = structured_to_unstructured(arr, dtype=int)\n assert_equal(res, np.zeros((10, 6), dtype=int))\n\n\n def test_field_assignment_by_name(self):\n a = np.ones(2, dtype=[('a', 'i4'), ('b', 'f8'), ('c', 'u1')])\n newdt = [('b', 'f4'), ('c', 'u1')]\n\n assert_equal(require_fields(a, newdt), np.ones(2, newdt))\n\n b = np.array([(1,2), (3,4)], dtype=newdt)\n assign_fields_by_name(a, b, zero_unassigned=False)\n assert_equal(a, np.array([(1,1,2),(1,3,4)], dtype=a.dtype))\n assign_fields_by_name(a, b)\n assert_equal(a, np.array([(0,1,2),(0,3,4)], dtype=a.dtype))\n\n # test nested fields\n a = np.ones(2, dtype=[('a', [('b', 'f8'), ('c', 'u1')])])\n newdt = [('a', [('c', 'u1')])]\n assert_equal(require_fields(a, newdt), np.ones(2, newdt))\n b = np.array([((2,),), ((3,),)], dtype=newdt)\n assign_fields_by_name(a, b, zero_unassigned=False)\n assert_equal(a, np.array([((1,2),), ((1,3),)], dtype=a.dtype))\n assign_fields_by_name(a, b)\n assert_equal(a, np.array([((0,2),), ((0,3),)], dtype=a.dtype))\n\n # test unstructured code path for 0d arrays\n a, b = np.array(3), np.array(0)\n assign_fields_by_name(b, a)\n assert_equal(b[()], 3)\n\n\nclass TestRecursiveFillFields(object):\n # Test recursive_fill_fields.\n def test_simple_flexible(self):\n # Test recursive_fill_fields on flexible-array\n a = np.array([(1, 10.), (2, 20.)], dtype=[('A', int), ('B', float)])\n b = np.zeros((3,), dtype=a.dtype)\n test = recursive_fill_fields(a, b)\n control = np.array([(1, 10.), (2, 20.), (0, 0.)],\n dtype=[('A', int), ('B', float)])\n assert_equal(test, control)\n\n def test_masked_flexible(self):\n # Test recursive_fill_fields on masked flexible-array\n a = ma.array([(1, 10.), (2, 20.)], mask=[(0, 1), (1, 0)],\n dtype=[('A', int), ('B', float)])\n b = ma.zeros((3,), dtype=a.dtype)\n test = recursive_fill_fields(a, b)\n control = ma.array([(1, 10.), (2, 20.), (0, 0.)],\n mask=[(0, 1), (1, 0), (0, 0)],\n dtype=[('A', int), ('B', float)])\n assert_equal(test, control)\n\n\nclass TestMergeArrays(object):\n # Test merge_arrays\n\n def setup(self):\n x = np.array([1, 2, ])\n y = np.array([10, 20, 30])\n z = np.array(\n [('A', 1.), ('B', 2.)], dtype=[('A', '|S3'), ('B', float)])\n w = np.array(\n [(1, (2, 3.0)), (4, (5, 6.0))],\n dtype=[('a', int), ('b', [('ba', float), ('bb', int)])])\n self.data = (w, x, y, z)\n\n def test_solo(self):\n # Test merge_arrays on a single array.\n (_, x, _, z) = self.data\n\n test = merge_arrays(x)\n control = np.array([(1,), (2,)], dtype=[('f0', int)])\n assert_equal(test, control)\n test = merge_arrays((x,))\n assert_equal(test, control)\n\n test = merge_arrays(z, flatten=False)\n assert_equal(test, z)\n test = merge_arrays(z, flatten=True)\n assert_equal(test, z)\n\n def test_solo_w_flatten(self):\n # Test merge_arrays on a single array w & w/o flattening\n w = self.data[0]\n test = merge_arrays(w, flatten=False)\n assert_equal(test, w)\n\n test = merge_arrays(w, flatten=True)\n control = np.array([(1, 2, 3.0), (4, 5, 6.0)],\n dtype=[('a', int), ('ba', float), ('bb', int)])\n assert_equal(test, control)\n\n def test_standard(self):\n # Test standard & standard\n # Test merge arrays\n (_, x, y, _) = self.data\n test = merge_arrays((x, y), usemask=False)\n control = np.array([(1, 10), (2, 20), (-1, 30)],\n dtype=[('f0', int), ('f1', int)])\n assert_equal(test, control)\n\n test = merge_arrays((x, y), usemask=True)\n control = ma.array([(1, 10), (2, 20), (-1, 30)],\n mask=[(0, 0), (0, 0), (1, 0)],\n dtype=[('f0', int), ('f1', int)])\n assert_equal(test, control)\n assert_equal(test.mask, control.mask)\n\n def test_flatten(self):\n # Test standard & flexible\n (_, x, _, z) = self.data\n test = merge_arrays((x, z), flatten=True)\n control = np.array([(1, 'A', 1.), (2, 'B', 2.)],\n dtype=[('f0', int), ('A', '|S3'), ('B', float)])\n assert_equal(test, control)\n\n test = merge_arrays((x, z), flatten=False)\n control = np.array([(1, ('A', 1.)), (2, ('B', 2.))],\n dtype=[('f0', int),\n ('f1', [('A', '|S3'), ('B', float)])])\n assert_equal(test, control)\n\n def test_flatten_wflexible(self):\n # Test flatten standard & nested\n (w, x, _, _) = self.data\n test = merge_arrays((x, w), flatten=True)\n control = np.array([(1, 1, 2, 3.0), (2, 4, 5, 6.0)],\n dtype=[('f0', int),\n ('a', int), ('ba', float), ('bb', int)])\n assert_equal(test, control)\n\n test = merge_arrays((x, w), flatten=False)\n controldtype = [('f0', int),\n ('f1', [('a', int),\n ('b', [('ba', float), ('bb', int)])])]\n control = np.array([(1., (1, (2, 3.0))), (2, (4, (5, 6.0)))],\n dtype=controldtype)\n assert_equal(test, control)\n\n def test_wmasked_arrays(self):\n # Test merge_arrays masked arrays\n (_, x, _, _) = self.data\n mx = ma.array([1, 2, 3], mask=[1, 0, 0])\n test = merge_arrays((x, mx), usemask=True)\n control = ma.array([(1, 1), (2, 2), (-1, 3)],\n mask=[(0, 1), (0, 0), (1, 0)],\n dtype=[('f0', int), ('f1', int)])\n assert_equal(test, control)\n test = merge_arrays((x, mx), usemask=True, asrecarray=True)\n assert_equal(test, control)\n assert_(isinstance(test, MaskedRecords))\n\n def test_w_singlefield(self):\n # Test single field\n test = merge_arrays((np.array([1, 2]).view([('a', int)]),\n np.array([10., 20., 30.])),)\n control = ma.array([(1, 10.), (2, 20.), (-1, 30.)],\n mask=[(0, 0), (0, 0), (1, 0)],\n dtype=[('a', int), ('f1', float)])\n assert_equal(test, control)\n\n def test_w_shorter_flex(self):\n # Test merge_arrays w/ a shorter flexndarray.\n z = self.data[-1]\n\n # Fixme, this test looks incomplete and broken\n #test = merge_arrays((z, np.array([10, 20, 30]).view([('C', int)])))\n #control = np.array([('A', 1., 10), ('B', 2., 20), ('-1', -1, 20)],\n # dtype=[('A', '|S3'), ('B', float), ('C', int)])\n #assert_equal(test, control)\n\n # Hack to avoid pyflakes warnings about unused variables\n merge_arrays((z, np.array([10, 20, 30]).view([('C', int)])))\n np.array([('A', 1., 10), ('B', 2., 20), ('-1', -1, 20)],\n dtype=[('A', '|S3'), ('B', float), ('C', int)])\n\n def test_singlerecord(self):\n (_, x, y, z) = self.data\n test = merge_arrays((x[0], y[0], z[0]), usemask=False)\n control = np.array([(1, 10, ('A', 1))],\n dtype=[('f0', int),\n ('f1', int),\n ('f2', [('A', '|S3'), ('B', float)])])\n assert_equal(test, control)\n\n\nclass TestAppendFields(object):\n # Test append_fields\n\n def setup(self):\n x = np.array([1, 2, ])\n y = np.array([10, 20, 30])\n z = np.array(\n [('A', 1.), ('B', 2.)], dtype=[('A', '|S3'), ('B', float)])\n w = np.array([(1, (2, 3.0)), (4, (5, 6.0))],\n dtype=[('a', int), ('b', [('ba', float), ('bb', int)])])\n self.data = (w, x, y, z)\n\n def test_append_single(self):\n # Test simple case\n (_, x, _, _) = self.data\n test = append_fields(x, 'A', data=[10, 20, 30])\n control = ma.array([(1, 10), (2, 20), (-1, 30)],\n mask=[(0, 0), (0, 0), (1, 0)],\n dtype=[('f0', int), ('A', int)],)\n assert_equal(test, control)\n\n def test_append_double(self):\n # Test simple case\n (_, x, _, _) = self.data\n test = append_fields(x, ('A', 'B'), data=[[10, 20, 30], [100, 200]])\n control = ma.array([(1, 10, 100), (2, 20, 200), (-1, 30, -1)],\n mask=[(0, 0, 0), (0, 0, 0), (1, 0, 1)],\n dtype=[('f0', int), ('A', int), ('B', int)],)\n assert_equal(test, control)\n\n def test_append_on_flex(self):\n # Test append_fields on flexible type arrays\n z = self.data[-1]\n test = append_fields(z, 'C', data=[10, 20, 30])\n control = ma.array([('A', 1., 10), ('B', 2., 20), (-1, -1., 30)],\n mask=[(0, 0, 0), (0, 0, 0), (1, 1, 0)],\n dtype=[('A', '|S3'), ('B', float), ('C', int)],)\n assert_equal(test, control)\n\n def test_append_on_nested(self):\n # Test append_fields on nested fields\n w = self.data[0]\n test = append_fields(w, 'C', data=[10, 20, 30])\n control = ma.array([(1, (2, 3.0), 10),\n (4, (5, 6.0), 20),\n (-1, (-1, -1.), 30)],\n mask=[(\n 0, (0, 0), 0), (0, (0, 0), 0), (1, (1, 1), 0)],\n dtype=[('a', int),\n ('b', [('ba', float), ('bb', int)]),\n ('C', int)],)\n assert_equal(test, control)\n\n\nclass TestStackArrays(object):\n # Test stack_arrays\n def setup(self):\n x = np.array([1, 2, ])\n y = np.array([10, 20, 30])\n z = np.array(\n [('A', 1.), ('B', 2.)], dtype=[('A', '|S3'), ('B', float)])\n w = np.array([(1, (2, 3.0)), (4, (5, 6.0))],\n dtype=[('a', int), ('b', [('ba', float), ('bb', int)])])\n self.data = (w, x, y, z)\n\n def test_solo(self):\n # Test stack_arrays on single arrays\n (_, x, _, _) = self.data\n test = stack_arrays((x,))\n assert_equal(test, x)\n assert_(test is x)\n\n test = stack_arrays(x)\n assert_equal(test, x)\n assert_(test is x)\n\n def test_unnamed_fields(self):\n # Tests combinations of arrays w/o named fields\n (_, x, y, _) = self.data\n\n test = stack_arrays((x, x), usemask=False)\n control = np.array([1, 2, 1, 2])\n assert_equal(test, control)\n\n test = stack_arrays((x, y), usemask=False)\n control = np.array([1, 2, 10, 20, 30])\n assert_equal(test, control)\n\n test = stack_arrays((y, x), usemask=False)\n control = np.array([10, 20, 30, 1, 2])\n assert_equal(test, control)\n\n def test_unnamed_and_named_fields(self):\n # Test combination of arrays w/ & w/o named fields\n (_, x, _, z) = self.data\n\n test = stack_arrays((x, z))\n control = ma.array([(1, -1, -1), (2, -1, -1),\n (-1, 'A', 1), (-1, 'B', 2)],\n mask=[(0, 1, 1), (0, 1, 1),\n (1, 0, 0), (1, 0, 0)],\n dtype=[('f0', int), ('A', '|S3'), ('B', float)])\n assert_equal(test, control)\n assert_equal(test.mask, control.mask)\n\n test = stack_arrays((z, x))\n control = ma.array([('A', 1, -1), ('B', 2, -1),\n (-1, -1, 1), (-1, -1, 2), ],\n mask=[(0, 0, 1), (0, 0, 1),\n (1, 1, 0), (1, 1, 0)],\n dtype=[('A', '|S3'), ('B', float), ('f2', int)])\n assert_equal(test, control)\n assert_equal(test.mask, control.mask)\n\n test = stack_arrays((z, z, x))\n control = ma.array([('A', 1, -1), ('B', 2, -1),\n ('A', 1, -1), ('B', 2, -1),\n (-1, -1, 1), (-1, -1, 2), ],\n mask=[(0, 0, 1), (0, 0, 1),\n (0, 0, 1), (0, 0, 1),\n (1, 1, 0), (1, 1, 0)],\n dtype=[('A', '|S3'), ('B', float), ('f2', int)])\n assert_equal(test, control)\n\n def test_matching_named_fields(self):\n # Test combination of arrays w/ matching field names\n (_, x, _, z) = self.data\n zz = np.array([('a', 10., 100.), ('b', 20., 200.), ('c', 30., 300.)],\n dtype=[('A', '|S3'), ('B', float), ('C', float)])\n test = stack_arrays((z, zz))\n control = ma.array([('A', 1, -1), ('B', 2, -1),\n (\n 'a', 10., 100.), ('b', 20., 200.), ('c', 30., 300.)],\n dtype=[('A', '|S3'), ('B', float), ('C', float)],\n mask=[(0, 0, 1), (0, 0, 1),\n (0, 0, 0), (0, 0, 0), (0, 0, 0)])\n assert_equal(test, control)\n assert_equal(test.mask, control.mask)\n\n test = stack_arrays((z, zz, x))\n ndtype = [('A', '|S3'), ('B', float), ('C', float), ('f3', int)]\n control = ma.array([('A', 1, -1, -1), ('B', 2, -1, -1),\n ('a', 10., 100., -1), ('b', 20., 200., -1),\n ('c', 30., 300., -1),\n (-1, -1, -1, 1), (-1, -1, -1, 2)],\n dtype=ndtype,\n mask=[(0, 0, 1, 1), (0, 0, 1, 1),\n (0, 0, 0, 1), (0, 0, 0, 1), (0, 0, 0, 1),\n (1, 1, 1, 0), (1, 1, 1, 0)])\n assert_equal(test, control)\n assert_equal(test.mask, control.mask)\n\n def test_defaults(self):\n # Test defaults: no exception raised if keys of defaults are not fields.\n (_, _, _, z) = self.data\n zz = np.array([('a', 10., 100.), ('b', 20., 200.), ('c', 30., 300.)],\n dtype=[('A', '|S3'), ('B', float), ('C', float)])\n defaults = {'A': '???', 'B': -999., 'C': -9999., 'D': -99999.}\n test = stack_arrays((z, zz), defaults=defaults)\n control = ma.array([('A', 1, -9999.), ('B', 2, -9999.),\n (\n 'a', 10., 100.), ('b', 20., 200.), ('c', 30., 300.)],\n dtype=[('A', '|S3'), ('B', float), ('C', float)],\n mask=[(0, 0, 1), (0, 0, 1),\n (0, 0, 0), (0, 0, 0), (0, 0, 0)])\n assert_equal(test, control)\n assert_equal(test.data, control.data)\n assert_equal(test.mask, control.mask)\n\n def test_autoconversion(self):\n # Tests autoconversion\n adtype = [('A', int), ('B', bool), ('C', float)]\n a = ma.array([(1, 2, 3)], mask=[(0, 1, 0)], dtype=adtype)\n bdtype = [('A', int), ('B', float), ('C', float)]\n b = ma.array([(4, 5, 6)], dtype=bdtype)\n control = ma.array([(1, 2, 3), (4, 5, 6)], mask=[(0, 1, 0), (0, 0, 0)],\n dtype=bdtype)\n test = stack_arrays((a, b), autoconvert=True)\n assert_equal(test, control)\n assert_equal(test.mask, control.mask)\n with assert_raises(TypeError):\n stack_arrays((a, b), autoconvert=False)\n\n def test_checktitles(self):\n # Test using titles in the field names\n adtype = [(('a', 'A'), int), (('b', 'B'), bool), (('c', 'C'), float)]\n a = ma.array([(1, 2, 3)], mask=[(0, 1, 0)], dtype=adtype)\n bdtype = [(('a', 'A'), int), (('b', 'B'), bool), (('c', 'C'), float)]\n b = ma.array([(4, 5, 6)], dtype=bdtype)\n test = stack_arrays((a, b))\n control = ma.array([(1, 2, 3), (4, 5, 6)], mask=[(0, 1, 0), (0, 0, 0)],\n dtype=bdtype)\n assert_equal(test, control)\n assert_equal(test.mask, control.mask)\n\n def test_subdtype(self):\n z = np.array([\n ('A', 1), ('B', 2)\n ], dtype=[('A', '|S3'), ('B', float, (1,))])\n zz = np.array([\n ('a', [10.], 100.), ('b', [20.], 200.), ('c', [30.], 300.)\n ], dtype=[('A', '|S3'), ('B', float, (1,)), ('C', float)])\n\n res = stack_arrays((z, zz))\n expected = ma.array(\n data=[\n (b'A', [1.0], 0),\n (b'B', [2.0], 0),\n (b'a', [10.0], 100.0),\n (b'b', [20.0], 200.0),\n (b'c', [30.0], 300.0)],\n mask=[\n (False, [False], True),\n (False, [False], True),\n (False, [False], False),\n (False, [False], False),\n (False, [False], False)\n ],\n dtype=zz.dtype\n )\n assert_equal(res.dtype, expected.dtype)\n assert_equal(res, expected)\n assert_equal(res.mask, expected.mask)\n\n\nclass TestJoinBy(object):\n def setup(self):\n self.a = np.array(list(zip(np.arange(10), np.arange(50, 60),\n np.arange(100, 110))),\n dtype=[('a', int), ('b', int), ('c', int)])\n self.b = np.array(list(zip(np.arange(5, 15), np.arange(65, 75),\n np.arange(100, 110))),\n dtype=[('a', int), ('b', int), ('d', int)])\n\n def test_inner_join(self):\n # Basic test of join_by\n a, b = self.a, self.b\n\n test = join_by('a', a, b, jointype='inner')\n control = np.array([(5, 55, 65, 105, 100), (6, 56, 66, 106, 101),\n (7, 57, 67, 107, 102), (8, 58, 68, 108, 103),\n (9, 59, 69, 109, 104)],\n dtype=[('a', int), ('b1', int), ('b2', int),\n ('c', int), ('d', int)])\n assert_equal(test, control)\n\n def test_join(self):\n a, b = self.a, self.b\n\n # Fixme, this test is broken\n #test = join_by(('a', 'b'), a, b)\n #control = np.array([(5, 55, 105, 100), (6, 56, 106, 101),\n # (7, 57, 107, 102), (8, 58, 108, 103),\n # (9, 59, 109, 104)],\n # dtype=[('a', int), ('b', int),\n # ('c', int), ('d', int)])\n #assert_equal(test, control)\n\n # Hack to avoid pyflakes unused variable warnings\n join_by(('a', 'b'), a, b)\n np.array([(5, 55, 105, 100), (6, 56, 106, 101),\n (7, 57, 107, 102), (8, 58, 108, 103),\n (9, 59, 109, 104)],\n dtype=[('a', int), ('b', int),\n ('c', int), ('d', int)])\n\n def test_join_subdtype(self):\n # tests the bug in https://stackoverflow.com/q/44769632/102441\n from numpy.lib import recfunctions as rfn\n foo = np.array([(1,)],\n dtype=[('key', int)])\n bar = np.array([(1, np.array([1,2,3]))],\n dtype=[('key', int), ('value', 'uint16', 3)])\n res = join_by('key', foo, bar)\n assert_equal(res, bar.view(ma.MaskedArray))\n\n def test_outer_join(self):\n a, b = self.a, self.b\n\n test = join_by(('a', 'b'), a, b, 'outer')\n control = ma.array([(0, 50, 100, -1), (1, 51, 101, -1),\n (2, 52, 102, -1), (3, 53, 103, -1),\n (4, 54, 104, -1), (5, 55, 105, -1),\n (5, 65, -1, 100), (6, 56, 106, -1),\n (6, 66, -1, 101), (7, 57, 107, -1),\n (7, 67, -1, 102), (8, 58, 108, -1),\n (8, 68, -1, 103), (9, 59, 109, -1),\n (9, 69, -1, 104), (10, 70, -1, 105),\n (11, 71, -1, 106), (12, 72, -1, 107),\n (13, 73, -1, 108), (14, 74, -1, 109)],\n mask=[(0, 0, 0, 1), (0, 0, 0, 1),\n (0, 0, 0, 1), (0, 0, 0, 1),\n (0, 0, 0, 1), (0, 0, 0, 1),\n (0, 0, 1, 0), (0, 0, 0, 1),\n (0, 0, 1, 0), (0, 0, 0, 1),\n (0, 0, 1, 0), (0, 0, 0, 1),\n (0, 0, 1, 0), (0, 0, 0, 1),\n (0, 0, 1, 0), (0, 0, 1, 0),\n (0, 0, 1, 0), (0, 0, 1, 0),\n (0, 0, 1, 0), (0, 0, 1, 0)],\n dtype=[('a', int), ('b', int),\n ('c', int), ('d', int)])\n assert_equal(test, control)\n\n def test_leftouter_join(self):\n a, b = self.a, self.b\n\n test = join_by(('a', 'b'), a, b, 'leftouter')\n control = ma.array([(0, 50, 100, -1), (1, 51, 101, -1),\n (2, 52, 102, -1), (3, 53, 103, -1),\n (4, 54, 104, -1), (5, 55, 105, -1),\n (6, 56, 106, -1), (7, 57, 107, -1),\n (8, 58, 108, -1), (9, 59, 109, -1)],\n mask=[(0, 0, 0, 1), (0, 0, 0, 1),\n (0, 0, 0, 1), (0, 0, 0, 1),\n (0, 0, 0, 1), (0, 0, 0, 1),\n (0, 0, 0, 1), (0, 0, 0, 1),\n (0, 0, 0, 1), (0, 0, 0, 1)],\n dtype=[('a', int), ('b', int), ('c', int), ('d', int)])\n assert_equal(test, control)\n\n def test_different_field_order(self):\n # gh-8940\n a = np.zeros(3, dtype=[('a', 'i4'), ('b', 'f4'), ('c', 'u1')])\n b = np.ones(3, dtype=[('c', 'u1'), ('b', 'f4'), ('a', 'i4')])\n # this should not give a FutureWarning:\n j = join_by(['c', 'b'], a, b, jointype='inner', usemask=False)\n assert_equal(j.dtype.names, ['b', 'c', 'a1', 'a2'])\n\n def test_duplicate_keys(self):\n a = np.zeros(3, dtype=[('a', 'i4'), ('b', 'f4'), ('c', 'u1')])\n b = np.ones(3, dtype=[('c', 'u1'), ('b', 'f4'), ('a', 'i4')])\n assert_raises(ValueError, join_by, ['a', 'b', 'b'], a, b)\n\n @pytest.mark.xfail(reason=\"See comment at gh-9343\")\n def test_same_name_different_dtypes_key(self):\n a_dtype = np.dtype([('key', 'S5'), ('value', '<f4')])\n b_dtype = np.dtype([('key', 'S10'), ('value', '<f4')])\n expected_dtype = np.dtype([\n ('key', 'S10'), ('value1', '<f4'), ('value2', '<f4')])\n\n a = np.array([('Sarah', 8.0), ('John', 6.0)], dtype=a_dtype)\n b = np.array([('Sarah', 10.0), ('John', 7.0)], dtype=b_dtype)\n res = join_by('key', a, b)\n\n assert_equal(res.dtype, expected_dtype)\n\n def test_same_name_different_dtypes(self):\n # gh-9338\n a_dtype = np.dtype([('key', 'S10'), ('value', '<f4')])\n b_dtype = np.dtype([('key', 'S10'), ('value', '<f8')])\n expected_dtype = np.dtype([\n ('key', '|S10'), ('value1', '<f4'), ('value2', '<f8')])\n\n a = np.array([('Sarah', 8.0), ('John', 6.0)], dtype=a_dtype)\n b = np.array([('Sarah', 10.0), ('John', 7.0)], dtype=b_dtype)\n res = join_by('key', a, b)\n\n assert_equal(res.dtype, expected_dtype)\n\n def test_subarray_key(self):\n a_dtype = np.dtype([('pos', int, 3), ('f', '<f4')])\n a = np.array([([1, 1, 1], np.pi), ([1, 2, 3], 0.0)], dtype=a_dtype)\n\n b_dtype = np.dtype([('pos', int, 3), ('g', '<f4')])\n b = np.array([([1, 1, 1], 3), ([3, 2, 1], 0.0)], dtype=b_dtype)\n\n expected_dtype = np.dtype([('pos', int, 3), ('f', '<f4'), ('g', '<f4')])\n expected = np.array([([1, 1, 1], np.pi, 3)], dtype=expected_dtype)\n\n res = join_by('pos', a, b)\n assert_equal(res.dtype, expected_dtype)\n assert_equal(res, expected)\n\n def test_padded_dtype(self):\n dt = np.dtype('i1,f4', align=True)\n dt.names = ('k', 'v')\n assert_(len(dt.descr), 3) # padding field is inserted\n\n a = np.array([(1, 3), (3, 2)], dt)\n b = np.array([(1, 1), (2, 2)], dt)\n res = join_by('k', a, b)\n\n # no padding fields remain\n expected_dtype = np.dtype([\n ('k', 'i1'), ('v1', 'f4'), ('v2', 'f4')\n ])\n\n assert_equal(res.dtype, expected_dtype)\n\n\nclass TestJoinBy2(object):\n @classmethod\n def setup(cls):\n cls.a = np.array(list(zip(np.arange(10), np.arange(50, 60),\n np.arange(100, 110))),\n dtype=[('a', int), ('b', int), ('c', int)])\n cls.b = np.array(list(zip(np.arange(10), np.arange(65, 75),\n np.arange(100, 110))),\n dtype=[('a', int), ('b', int), ('d', int)])\n\n def test_no_r1postfix(self):\n # Basic test of join_by no_r1postfix\n a, b = self.a, self.b\n\n test = join_by(\n 'a', a, b, r1postfix='', r2postfix='2', jointype='inner')\n control = np.array([(0, 50, 65, 100, 100), (1, 51, 66, 101, 101),\n (2, 52, 67, 102, 102), (3, 53, 68, 103, 103),\n (4, 54, 69, 104, 104), (5, 55, 70, 105, 105),\n (6, 56, 71, 106, 106), (7, 57, 72, 107, 107),\n (8, 58, 73, 108, 108), (9, 59, 74, 109, 109)],\n dtype=[('a', int), ('b', int), ('b2', int),\n ('c', int), ('d', int)])\n assert_equal(test, control)\n\n def test_no_postfix(self):\n assert_raises(ValueError, join_by, 'a', self.a, self.b,\n r1postfix='', r2postfix='')\n\n def test_no_r2postfix(self):\n # Basic test of join_by no_r2postfix\n a, b = self.a, self.b\n\n test = join_by(\n 'a', a, b, r1postfix='1', r2postfix='', jointype='inner')\n control = np.array([(0, 50, 65, 100, 100), (1, 51, 66, 101, 101),\n (2, 52, 67, 102, 102), (3, 53, 68, 103, 103),\n (4, 54, 69, 104, 104), (5, 55, 70, 105, 105),\n (6, 56, 71, 106, 106), (7, 57, 72, 107, 107),\n (8, 58, 73, 108, 108), (9, 59, 74, 109, 109)],\n dtype=[('a', int), ('b1', int), ('b', int),\n ('c', int), ('d', int)])\n assert_equal(test, control)\n\n def test_two_keys_two_vars(self):\n a = np.array(list(zip(np.tile([10, 11], 5), np.repeat(np.arange(5), 2),\n np.arange(50, 60), np.arange(10, 20))),\n dtype=[('k', int), ('a', int), ('b', int), ('c', int)])\n\n b = np.array(list(zip(np.tile([10, 11], 5), np.repeat(np.arange(5), 2),\n np.arange(65, 75), np.arange(0, 10))),\n dtype=[('k', int), ('a', int), ('b', int), ('c', int)])\n\n control = np.array([(10, 0, 50, 65, 10, 0), (11, 0, 51, 66, 11, 1),\n (10, 1, 52, 67, 12, 2), (11, 1, 53, 68, 13, 3),\n (10, 2, 54, 69, 14, 4), (11, 2, 55, 70, 15, 5),\n (10, 3, 56, 71, 16, 6), (11, 3, 57, 72, 17, 7),\n (10, 4, 58, 73, 18, 8), (11, 4, 59, 74, 19, 9)],\n dtype=[('k', int), ('a', int), ('b1', int),\n ('b2', int), ('c1', int), ('c2', int)])\n test = join_by(\n ['a', 'k'], a, b, r1postfix='1', r2postfix='2', jointype='inner')\n assert_equal(test.dtype, control.dtype)\n assert_equal(test, control)\n\nclass TestAppendFieldsObj(object):\n \"\"\"\n Test append_fields with arrays containing objects\n \"\"\"\n # https://github.com/numpy/numpy/issues/2346\n\n def setup(self):\n from datetime import date\n self.data = dict(obj=date(2000, 1, 1))\n\n def test_append_to_objects(self):\n \"Test append_fields when the base array contains objects\"\n obj = self.data['obj']\n x = np.array([(obj, 1.), (obj, 2.)],\n dtype=[('A', object), ('B', float)])\n y = np.array([10, 20], dtype=int)\n test = append_fields(x, 'C', data=y, usemask=False)\n control = np.array([(obj, 1.0, 10), (obj, 2.0, 20)],\n dtype=[('A', object), ('B', float), ('C', int)])\n assert_equal(test, control)\n",
"import types\nimport warnings\nimport sys\nimport traceback\nimport pickle\nfrom copy import deepcopy\nfrom functools import partial\nfrom inspect import signature\n\nimport numpy as np\nfrom scipy import sparse\nfrom scipy.stats import rankdata\n\nfrom . import IS_PYPY\nfrom . import _joblib\nfrom .testing import assert_raises, _get_args\nfrom .testing import assert_raises_regex\nfrom .testing import assert_raise_message\nfrom .testing import assert_equal\nfrom .testing import assert_not_equal\nfrom .testing import assert_in\nfrom .testing import assert_array_equal\nfrom .testing import assert_array_almost_equal\nfrom .testing import assert_allclose\nfrom .testing import assert_allclose_dense_sparse\nfrom .testing import assert_warns_message\nfrom .testing import set_random_state\nfrom .testing import assert_greater\nfrom .testing import assert_greater_equal\nfrom .testing import SkipTest\nfrom .testing import ignore_warnings\nfrom .testing import assert_dict_equal\nfrom .testing import create_memmap_backed_data\nfrom . import is_scalar_nan\nfrom ..discriminant_analysis import LinearDiscriminantAnalysis\nfrom ..linear_model import Ridge\n\n\nfrom ..base import (clone, ClusterMixin, is_classifier, is_regressor,\n _DEFAULT_TAGS, RegressorMixin, is_outlier_detector)\n\nfrom ..metrics import accuracy_score, adjusted_rand_score, f1_score\n\nfrom ..random_projection import BaseRandomProjection\nfrom ..feature_selection import SelectKBest\nfrom ..pipeline import make_pipeline\nfrom ..exceptions import DataConversionWarning\nfrom ..exceptions import SkipTestWarning\nfrom ..model_selection import train_test_split\nfrom ..model_selection import ShuffleSplit\nfrom ..model_selection._validation import _safe_split\nfrom ..metrics.pairwise import (rbf_kernel, linear_kernel,\n pairwise_distances)\n\nfrom .import shuffle\nfrom .validation import has_fit_parameter, _num_samples\nfrom ..preprocessing import StandardScaler\nfrom ..datasets import load_iris, load_boston, make_blobs\n\n\nBOSTON = None\nCROSS_DECOMPOSITION = ['PLSCanonical', 'PLSRegression', 'CCA', 'PLSSVD']\n\n\ndef _safe_tags(estimator, key=None):\n # if estimator doesn't have _get_tags, use _DEFAULT_TAGS\n # if estimator has tags but not key, use _DEFAULT_TAGS[key]\n if hasattr(estimator, \"_get_tags\"):\n if key is not None:\n return estimator._get_tags().get(key, _DEFAULT_TAGS[key])\n tags = estimator._get_tags()\n return {key: tags.get(key, _DEFAULT_TAGS[key])\n for key in _DEFAULT_TAGS.keys()}\n if key is not None:\n return _DEFAULT_TAGS[key]\n return _DEFAULT_TAGS\n\n\ndef _yield_checks(name, estimator):\n tags = _safe_tags(estimator)\n yield check_estimators_dtypes\n yield check_fit_score_takes_y\n yield check_sample_weights_pandas_series\n yield check_sample_weights_list\n yield check_sample_weights_invariance\n yield check_estimators_fit_returns_self\n yield partial(check_estimators_fit_returns_self, readonly_memmap=True)\n\n # Check that all estimator yield informative messages when\n # trained on empty datasets\n if not tags[\"no_validation\"]:\n yield check_complex_data\n yield check_dtype_object\n yield check_estimators_empty_data_messages\n\n if name not in CROSS_DECOMPOSITION:\n # cross-decomposition's \"transform\" returns X and Y\n yield check_pipeline_consistency\n\n if not tags[\"allow_nan\"] and not tags[\"no_validation\"]:\n # Test that all estimators check their input for NaN's and infs\n yield check_estimators_nan_inf\n\n yield check_estimators_overwrite_params\n if hasattr(estimator, 'sparsify'):\n yield check_sparsify_coefficients\n\n yield check_estimator_sparse_data\n\n # Test that estimators can be pickled, and once pickled\n # give the same answer as before.\n yield check_estimators_pickle\n\n\ndef _yield_classifier_checks(name, classifier):\n tags = _safe_tags(classifier)\n\n # test classifiers can handle non-array data\n yield check_classifier_data_not_an_array\n # test classifiers trained on a single label always return this label\n yield check_classifiers_one_label\n yield check_classifiers_classes\n yield check_estimators_partial_fit_n_features\n # basic consistency testing\n yield check_classifiers_train\n yield partial(check_classifiers_train, readonly_memmap=True)\n yield check_classifiers_regression_target\n if not tags[\"no_validation\"]:\n yield check_supervised_y_no_nan\n yield check_supervised_y_2d\n yield check_estimators_unfitted\n if 'class_weight' in classifier.get_params().keys():\n yield check_class_weight_classifiers\n\n yield check_non_transformer_estimators_n_iter\n # test if predict_proba is a monotonic transformation of decision_function\n yield check_decision_proba_consistency\n\n\n@ignore_warnings(category=(DeprecationWarning, FutureWarning))\ndef check_supervised_y_no_nan(name, estimator_orig):\n # Checks that the Estimator targets are not NaN.\n estimator = clone(estimator_orig)\n rng = np.random.RandomState(888)\n X = rng.randn(10, 5)\n y = np.full(10, np.inf)\n y = multioutput_estimator_convert_y_2d(estimator, y)\n\n errmsg = \"Input contains NaN, infinity or a value too large for \" \\\n \"dtype('float64').\"\n try:\n estimator.fit(X, y)\n except ValueError as e:\n if str(e) != errmsg:\n raise ValueError(\"Estimator {0} raised error as expected, but \"\n \"does not match expected error message\"\n .format(name))\n else:\n raise ValueError(\"Estimator {0} should have raised error on fitting \"\n \"array y with NaN value.\".format(name))\n\n\ndef _yield_regressor_checks(name, regressor):\n tags = _safe_tags(regressor)\n # TODO: test with intercept\n # TODO: test with multiple responses\n # basic testing\n yield check_regressors_train\n yield partial(check_regressors_train, readonly_memmap=True)\n yield check_regressor_data_not_an_array\n yield check_estimators_partial_fit_n_features\n yield check_regressors_no_decision_function\n if not tags[\"no_validation\"]:\n yield check_supervised_y_2d\n yield check_supervised_y_no_nan\n if name != 'CCA':\n # check that the regressor handles int input\n yield check_regressors_int\n yield check_estimators_unfitted\n yield check_non_transformer_estimators_n_iter\n\n\ndef _yield_transformer_checks(name, transformer):\n # All transformers should either deal with sparse data or raise an\n # exception with type TypeError and an intelligible error message\n yield check_transformer_data_not_an_array\n # these don't actually fit the data, so don't raise errors\n yield check_transformer_general\n yield partial(check_transformer_general, readonly_memmap=True)\n\n if not _safe_tags(transformer, \"stateless\"):\n yield check_transformers_unfitted\n # Dependent on external solvers and hence accessing the iter\n # param is non-trivial.\n external_solver = ['Isomap', 'KernelPCA', 'LocallyLinearEmbedding',\n 'RandomizedLasso', 'LogisticRegressionCV']\n if name not in external_solver:\n yield check_transformer_n_iter\n\n\ndef _yield_clustering_checks(name, clusterer):\n yield check_clusterer_compute_labels_predict\n if name not in ('WardAgglomeration', \"FeatureAgglomeration\"):\n # this is clustering on the features\n # let's not test that here.\n yield check_clustering\n yield partial(check_clustering, readonly_memmap=True)\n yield check_estimators_partial_fit_n_features\n yield check_non_transformer_estimators_n_iter\n\n\ndef _yield_outliers_checks(name, estimator):\n\n # checks for outlier detectors that have a fit_predict method\n if hasattr(estimator, 'fit_predict'):\n yield check_outliers_fit_predict\n\n # checks for estimators that can be used on a test set\n if hasattr(estimator, 'predict'):\n yield check_outliers_train\n yield partial(check_outliers_train, readonly_memmap=True)\n # test outlier detectors can handle non-array data\n yield check_classifier_data_not_an_array\n # test if NotFittedError is raised\n yield check_estimators_unfitted\n\n\ndef _yield_all_checks(name, estimator):\n tags = _safe_tags(estimator)\n if \"2darray\" not in tags[\"X_types\"]:\n warnings.warn(\"Can't test estimator {} which requires input \"\n \" of type {}\".format(name, tags[\"X_types\"]),\n SkipTestWarning)\n return\n if tags[\"_skip_test\"]:\n warnings.warn(\"Explicit SKIP via _skip_test tag for estimator \"\n \"{}.\".format(name),\n SkipTestWarning)\n return\n\n for check in _yield_checks(name, estimator):\n yield check\n if is_classifier(estimator):\n for check in _yield_classifier_checks(name, estimator):\n yield check\n if is_regressor(estimator):\n for check in _yield_regressor_checks(name, estimator):\n yield check\n if hasattr(estimator, 'transform'):\n for check in _yield_transformer_checks(name, estimator):\n yield check\n if isinstance(estimator, ClusterMixin):\n for check in _yield_clustering_checks(name, estimator):\n yield check\n if is_outlier_detector(estimator):\n for check in _yield_outliers_checks(name, estimator):\n yield check\n yield check_fit2d_predict1d\n yield check_methods_subset_invariance\n yield check_fit2d_1sample\n yield check_fit2d_1feature\n yield check_fit1d\n yield check_get_params_invariance\n yield check_set_params\n yield check_dict_unchanged\n yield check_dont_overwrite_parameters\n yield check_fit_idempotent\n\n\ndef check_estimator(Estimator):\n \"\"\"Check if estimator adheres to scikit-learn conventions.\n\n This estimator will run an extensive test-suite for input validation,\n shapes, etc.\n Additional tests for classifiers, regressors, clustering or transformers\n will be run if the Estimator class inherits from the corresponding mixin\n from sklearn.base.\n\n This test can be applied to classes or instances.\n Classes currently have some additional tests that related to construction,\n while passing instances allows the testing of multiple options.\n\n Parameters\n ----------\n estimator : estimator object or class\n Estimator to check. Estimator is a class object or instance.\n\n \"\"\"\n if isinstance(Estimator, type):\n # got a class\n name = Estimator.__name__\n estimator = Estimator()\n check_parameters_default_constructible(name, Estimator)\n check_no_attributes_set_in_init(name, estimator)\n else:\n # got an instance\n estimator = Estimator\n name = type(estimator).__name__\n\n for check in _yield_all_checks(name, estimator):\n try:\n check(name, estimator)\n except SkipTest as exception:\n # the only SkipTest thrown currently results from not\n # being able to import pandas.\n warnings.warn(str(exception), SkipTestWarning)\n\n\ndef _boston_subset(n_samples=200):\n global BOSTON\n if BOSTON is None:\n boston = load_boston()\n X, y = boston.data, boston.target\n X, y = shuffle(X, y, random_state=0)\n X, y = X[:n_samples], y[:n_samples]\n X = StandardScaler().fit_transform(X)\n BOSTON = X, y\n return BOSTON\n\n\ndef set_checking_parameters(estimator):\n # set parameters to speed up some estimators and\n # avoid deprecated behaviour\n params = estimator.get_params()\n name = estimator.__class__.__name__\n if (\"n_iter\" in params and name != \"TSNE\"):\n estimator.set_params(n_iter=5)\n if \"max_iter\" in params:\n if estimator.max_iter is not None:\n estimator.set_params(max_iter=min(5, estimator.max_iter))\n # LinearSVR, LinearSVC\n if estimator.__class__.__name__ in ['LinearSVR', 'LinearSVC']:\n estimator.set_params(max_iter=20)\n # NMF\n if estimator.__class__.__name__ == 'NMF':\n estimator.set_params(max_iter=100)\n # MLP\n if estimator.__class__.__name__ in ['MLPClassifier', 'MLPRegressor']:\n estimator.set_params(max_iter=100)\n if \"n_resampling\" in params:\n # randomized lasso\n estimator.set_params(n_resampling=5)\n if \"n_estimators\" in params:\n # especially gradient boosting with default 100\n # FIXME: The default number of trees was changed and is set to 'warn'\n # for some of the ensemble methods. We need to catch this case to avoid\n # an error during the comparison. To be reverted in 0.22.\n if estimator.n_estimators == 'warn':\n estimator.set_params(n_estimators=5)\n else:\n estimator.set_params(n_estimators=min(5, estimator.n_estimators))\n if \"max_trials\" in params:\n # RANSAC\n estimator.set_params(max_trials=10)\n if \"n_init\" in params:\n # K-Means\n estimator.set_params(n_init=2)\n\n if hasattr(estimator, \"n_components\"):\n estimator.n_components = 2\n\n if name == 'TruncatedSVD':\n # TruncatedSVD doesn't run with n_components = n_features\n # This is ugly :-/\n estimator.n_components = 1\n\n if hasattr(estimator, \"n_clusters\"):\n estimator.n_clusters = min(estimator.n_clusters, 2)\n\n if hasattr(estimator, \"n_best\"):\n estimator.n_best = 1\n\n if name == \"SelectFdr\":\n # be tolerant of noisy datasets (not actually speed)\n estimator.set_params(alpha=.5)\n\n if name == \"TheilSenRegressor\":\n estimator.max_subpopulation = 100\n\n if estimator.__class__.__name__ == \"IsolationForest\":\n # XXX to be removed in 0.22.\n # this is used because the old IsolationForest does not\n # respect the outlier detection API and thus and does not\n # pass the outlier detection common tests.\n estimator.set_params(behaviour='new')\n\n if isinstance(estimator, BaseRandomProjection):\n # Due to the jl lemma and often very few samples, the number\n # of components of the random matrix projection will be probably\n # greater than the number of features.\n # So we impose a smaller number (avoid \"auto\" mode)\n estimator.set_params(n_components=2)\n\n if isinstance(estimator, SelectKBest):\n # SelectKBest has a default of k=10\n # which is more feature than we have in most case.\n estimator.set_params(k=1)\n\n if name in ('HistGradientBoostingClassifier',\n 'HistGradientBoostingRegressor'):\n # The default min_samples_leaf (20) isn't appropriate for small\n # datasets (only very shallow trees are built) that the checks use.\n estimator.set_params(min_samples_leaf=5)\n\n\nclass NotAnArray:\n \"\"\"An object that is convertible to an array\n\n Parameters\n ----------\n data : array_like\n The data.\n \"\"\"\n\n def __init__(self, data):\n self.data = data\n\n def __array__(self, dtype=None):\n return self.data\n\n\ndef _is_pairwise(estimator):\n \"\"\"Returns True if estimator has a _pairwise attribute set to True.\n\n Parameters\n ----------\n estimator : object\n Estimator object to test.\n\n Returns\n -------\n out : bool\n True if _pairwise is set to True and False otherwise.\n \"\"\"\n return bool(getattr(estimator, \"_pairwise\", False))\n\n\ndef _is_pairwise_metric(estimator):\n \"\"\"Returns True if estimator accepts pairwise metric.\n\n Parameters\n ----------\n estimator : object\n Estimator object to test.\n\n Returns\n -------\n out : bool\n True if _pairwise is set to True and False otherwise.\n \"\"\"\n metric = getattr(estimator, \"metric\", None)\n\n return bool(metric == 'precomputed')\n\n\ndef pairwise_estimator_convert_X(X, estimator, kernel=linear_kernel):\n\n if _is_pairwise_metric(estimator):\n return pairwise_distances(X, metric='euclidean')\n if _is_pairwise(estimator):\n return kernel(X, X)\n\n return X\n\n\ndef _generate_sparse_matrix(X_csr):\n \"\"\"Generate sparse matrices with {32,64}bit indices of diverse format\n\n Parameters\n ----------\n X_csr: CSR Matrix\n Input matrix in CSR format\n\n Returns\n -------\n out: iter(Matrices)\n In format['dok', 'lil', 'dia', 'bsr', 'csr', 'csc', 'coo',\n 'coo_64', 'csc_64', 'csr_64']\n \"\"\"\n\n assert X_csr.format == 'csr'\n yield 'csr', X_csr.copy()\n for sparse_format in ['dok', 'lil', 'dia', 'bsr', 'csc', 'coo']:\n yield sparse_format, X_csr.asformat(sparse_format)\n\n # Generate large indices matrix only if its supported by scipy\n X_coo = X_csr.asformat('coo')\n X_coo.row = X_coo.row.astype('int64')\n X_coo.col = X_coo.col.astype('int64')\n yield \"coo_64\", X_coo\n\n for sparse_format in ['csc', 'csr']:\n X = X_csr.asformat(sparse_format)\n X.indices = X.indices.astype('int64')\n X.indptr = X.indptr.astype('int64')\n yield sparse_format + \"_64\", X\n\n\ndef check_estimator_sparse_data(name, estimator_orig):\n\n rng = np.random.RandomState(0)\n X = rng.rand(40, 10)\n X[X < .8] = 0\n X = pairwise_estimator_convert_X(X, estimator_orig)\n X_csr = sparse.csr_matrix(X)\n y = (4 * rng.rand(40)).astype(np.int)\n # catch deprecation warnings\n with ignore_warnings(category=DeprecationWarning):\n estimator = clone(estimator_orig)\n y = multioutput_estimator_convert_y_2d(estimator, y)\n for matrix_format, X in _generate_sparse_matrix(X_csr):\n # catch deprecation warnings\n with ignore_warnings(category=(DeprecationWarning, FutureWarning)):\n estimator = clone(estimator_orig)\n if name in ['Scaler', 'StandardScaler']:\n estimator.set_params(with_mean=False)\n # fit and predict\n try:\n with ignore_warnings(category=(DeprecationWarning, FutureWarning)):\n estimator.fit(X, y)\n if hasattr(estimator, \"predict\"):\n pred = estimator.predict(X)\n if _safe_tags(estimator, \"multioutput_only\"):\n assert_equal(pred.shape, (X.shape[0], 1))\n else:\n assert_equal(pred.shape, (X.shape[0],))\n if hasattr(estimator, 'predict_proba'):\n probs = estimator.predict_proba(X)\n assert_equal(probs.shape, (X.shape[0], 4))\n except (TypeError, ValueError) as e:\n if 'sparse' not in repr(e).lower():\n if \"64\" in matrix_format:\n msg = (\"Estimator %s doesn't seem to support %s matrix, \"\n \"and is not failing gracefully, e.g. by using \"\n \"check_array(X, accept_large_sparse=False)\")\n raise AssertionError(msg % (name, matrix_format))\n else:\n print(\"Estimator %s doesn't seem to fail gracefully on \"\n \"sparse data: error message state explicitly that \"\n \"sparse input is not supported if this is not\"\n \" the case.\" % name)\n raise\n except Exception:\n print(\"Estimator %s doesn't seem to fail gracefully on \"\n \"sparse data: it should raise a TypeError if sparse input \"\n \"is explicitly not supported.\" % name)\n raise\n\n\n@ignore_warnings(category=(DeprecationWarning, FutureWarning))\ndef check_sample_weights_pandas_series(name, estimator_orig):\n # check that estimators will accept a 'sample_weight' parameter of\n # type pandas.Series in the 'fit' function.\n estimator = clone(estimator_orig)\n if has_fit_parameter(estimator, \"sample_weight\"):\n try:\n import pandas as pd\n X = np.array([[1, 1], [1, 2], [1, 3], [1, 4],\n [2, 1], [2, 2], [2, 3], [2, 4]])\n X = pd.DataFrame(pairwise_estimator_convert_X(X, estimator_orig))\n y = pd.Series([1, 1, 1, 1, 2, 2, 2, 2])\n weights = pd.Series([1] * 8)\n if _safe_tags(estimator, \"multioutput_only\"):\n y = pd.DataFrame(y)\n try:\n estimator.fit(X, y, sample_weight=weights)\n except ValueError:\n raise ValueError(\"Estimator {0} raises error if \"\n \"'sample_weight' parameter is of \"\n \"type pandas.Series\".format(name))\n except ImportError:\n raise SkipTest(\"pandas is not installed: not testing for \"\n \"input of type pandas.Series to class weight.\")\n\n\n@ignore_warnings(category=(DeprecationWarning, FutureWarning))\ndef check_sample_weights_list(name, estimator_orig):\n # check that estimators will accept a 'sample_weight' parameter of\n # type list in the 'fit' function.\n if has_fit_parameter(estimator_orig, \"sample_weight\"):\n estimator = clone(estimator_orig)\n rnd = np.random.RandomState(0)\n X = pairwise_estimator_convert_X(rnd.uniform(size=(10, 3)),\n estimator_orig)\n y = np.arange(10) % 3\n y = multioutput_estimator_convert_y_2d(estimator, y)\n sample_weight = [3] * 10\n # Test that estimators don't raise any exception\n estimator.fit(X, y, sample_weight=sample_weight)\n\n\n@ignore_warnings(category=(DeprecationWarning, FutureWarning))\ndef check_sample_weights_invariance(name, estimator_orig):\n # check that the estimators yield same results for\n # unit weights and no weights\n if (has_fit_parameter(estimator_orig, \"sample_weight\") and\n not (hasattr(estimator_orig, \"_pairwise\")\n and estimator_orig._pairwise)):\n # We skip pairwise because the data is not pairwise\n\n estimator1 = clone(estimator_orig)\n estimator2 = clone(estimator_orig)\n set_random_state(estimator1, random_state=0)\n set_random_state(estimator2, random_state=0)\n\n X = np.array([[1, 3], [1, 3], [1, 3], [1, 3],\n [2, 1], [2, 1], [2, 1], [2, 1],\n [3, 3], [3, 3], [3, 3], [3, 3],\n [4, 1], [4, 1], [4, 1], [4, 1]], dtype=np.dtype('float'))\n y = np.array([1, 1, 1, 1, 2, 2, 2, 2,\n 1, 1, 1, 1, 2, 2, 2, 2], dtype=np.dtype('int'))\n y = multioutput_estimator_convert_y_2d(estimator1, y)\n\n estimator1.fit(X, y=y, sample_weight=np.ones(shape=len(y)))\n estimator2.fit(X, y=y, sample_weight=None)\n\n for method in [\"predict\", \"transform\"]:\n if hasattr(estimator_orig, method):\n X_pred1 = getattr(estimator1, method)(X)\n X_pred2 = getattr(estimator2, method)(X)\n if sparse.issparse(X_pred1):\n X_pred1 = X_pred1.toarray()\n X_pred2 = X_pred2.toarray()\n assert_allclose(X_pred1, X_pred2,\n err_msg=\"For %s sample_weight=None is not\"\n \" equivalent to sample_weight=ones\"\n % name)\n\n\n@ignore_warnings(category=(DeprecationWarning, FutureWarning, UserWarning))\ndef check_dtype_object(name, estimator_orig):\n # check that estimators treat dtype object as numeric if possible\n rng = np.random.RandomState(0)\n X = pairwise_estimator_convert_X(rng.rand(40, 10), estimator_orig)\n X = X.astype(object)\n y = (X[:, 0] * 4).astype(np.int)\n estimator = clone(estimator_orig)\n y = multioutput_estimator_convert_y_2d(estimator, y)\n\n estimator.fit(X, y)\n if hasattr(estimator, \"predict\"):\n estimator.predict(X)\n\n if hasattr(estimator, \"transform\"):\n estimator.transform(X)\n\n try:\n estimator.fit(X, y.astype(object))\n except Exception as e:\n if \"Unknown label type\" not in str(e):\n raise\n\n tags = _safe_tags(estimator)\n if 'str' not in tags['X_types']:\n X[0, 0] = {'foo': 'bar'}\n msg = \"argument must be a string.* number\"\n assert_raises_regex(TypeError, msg, estimator.fit, X, y)\n else:\n # Estimators supporting string will not call np.asarray to convert the\n # data to numeric and therefore, the error will not be raised.\n # Checking for each element dtype in the input array will be costly.\n # Refer to #11401 for full discussion.\n estimator.fit(X, y)\n\n\ndef check_complex_data(name, estimator_orig):\n # check that estimators raise an exception on providing complex data\n X = np.random.sample(10) + 1j * np.random.sample(10)\n X = X.reshape(-1, 1)\n y = np.random.sample(10) + 1j * np.random.sample(10)\n estimator = clone(estimator_orig)\n assert_raises_regex(ValueError, \"Complex data not supported\",\n estimator.fit, X, y)\n\n\n@ignore_warnings\ndef check_dict_unchanged(name, estimator_orig):\n # this estimator raises\n # ValueError: Found array with 0 feature(s) (shape=(23, 0))\n # while a minimum of 1 is required.\n # error\n if name in ['SpectralCoclustering']:\n return\n rnd = np.random.RandomState(0)\n if name in ['RANSACRegressor']:\n X = 3 * rnd.uniform(size=(20, 3))\n else:\n X = 2 * rnd.uniform(size=(20, 3))\n\n X = pairwise_estimator_convert_X(X, estimator_orig)\n\n y = X[:, 0].astype(np.int)\n estimator = clone(estimator_orig)\n y = multioutput_estimator_convert_y_2d(estimator, y)\n if hasattr(estimator, \"n_components\"):\n estimator.n_components = 1\n\n if hasattr(estimator, \"n_clusters\"):\n estimator.n_clusters = 1\n\n if hasattr(estimator, \"n_best\"):\n estimator.n_best = 1\n\n set_random_state(estimator, 1)\n\n estimator.fit(X, y)\n for method in [\"predict\", \"transform\", \"decision_function\",\n \"predict_proba\"]:\n if hasattr(estimator, method):\n dict_before = estimator.__dict__.copy()\n getattr(estimator, method)(X)\n assert_dict_equal(estimator.__dict__, dict_before,\n 'Estimator changes __dict__ during %s' % method)\n\n\ndef is_public_parameter(attr):\n return not (attr.startswith('_') or attr.endswith('_'))\n\n\n@ignore_warnings(category=(DeprecationWarning, FutureWarning))\ndef check_dont_overwrite_parameters(name, estimator_orig):\n # check that fit method only changes or sets private attributes\n if hasattr(estimator_orig.__init__, \"deprecated_original\"):\n # to not check deprecated classes\n return\n estimator = clone(estimator_orig)\n rnd = np.random.RandomState(0)\n X = 3 * rnd.uniform(size=(20, 3))\n X = pairwise_estimator_convert_X(X, estimator_orig)\n y = X[:, 0].astype(np.int)\n y = multioutput_estimator_convert_y_2d(estimator, y)\n\n if hasattr(estimator, \"n_components\"):\n estimator.n_components = 1\n if hasattr(estimator, \"n_clusters\"):\n estimator.n_clusters = 1\n\n set_random_state(estimator, 1)\n dict_before_fit = estimator.__dict__.copy()\n estimator.fit(X, y)\n\n dict_after_fit = estimator.__dict__\n\n public_keys_after_fit = [key for key in dict_after_fit.keys()\n if is_public_parameter(key)]\n\n attrs_added_by_fit = [key for key in public_keys_after_fit\n if key not in dict_before_fit.keys()]\n\n # check that fit doesn't add any public attribute\n assert not attrs_added_by_fit, (\n 'Estimator adds public attribute(s) during'\n ' the fit method.'\n ' Estimators are only allowed to add private attributes'\n ' either started with _ or ended'\n ' with _ but %s added'\n % ', '.join(attrs_added_by_fit))\n\n # check that fit doesn't change any public attribute\n attrs_changed_by_fit = [key for key in public_keys_after_fit\n if (dict_before_fit[key]\n is not dict_after_fit[key])]\n\n assert not attrs_changed_by_fit, (\n 'Estimator changes public attribute(s) during'\n ' the fit method. Estimators are only allowed'\n ' to change attributes started'\n ' or ended with _, but'\n ' %s changed'\n % ', '.join(attrs_changed_by_fit))\n\n\n@ignore_warnings(category=(DeprecationWarning, FutureWarning))\ndef check_fit2d_predict1d(name, estimator_orig):\n # check by fitting a 2d array and predicting with a 1d array\n rnd = np.random.RandomState(0)\n X = 3 * rnd.uniform(size=(20, 3))\n X = pairwise_estimator_convert_X(X, estimator_orig)\n y = X[:, 0].astype(np.int)\n estimator = clone(estimator_orig)\n y = multioutput_estimator_convert_y_2d(estimator, y)\n\n if hasattr(estimator, \"n_components\"):\n estimator.n_components = 1\n if hasattr(estimator, \"n_clusters\"):\n estimator.n_clusters = 1\n\n set_random_state(estimator, 1)\n estimator.fit(X, y)\n tags = _safe_tags(estimator)\n if tags[\"no_validation\"]:\n # FIXME this is a bit loose\n return\n\n for method in [\"predict\", \"transform\", \"decision_function\",\n \"predict_proba\"]:\n if hasattr(estimator, method):\n assert_raise_message(ValueError, \"Reshape your data\",\n getattr(estimator, method), X[0])\n\n\ndef _apply_on_subsets(func, X):\n # apply function on the whole set and on mini batches\n result_full = func(X)\n n_features = X.shape[1]\n result_by_batch = [func(batch.reshape(1, n_features))\n for batch in X]\n # func can output tuple (e.g. score_samples)\n if type(result_full) == tuple:\n result_full = result_full[0]\n result_by_batch = list(map(lambda x: x[0], result_by_batch))\n\n if sparse.issparse(result_full):\n result_full = result_full.A\n result_by_batch = [x.A for x in result_by_batch]\n return np.ravel(result_full), np.ravel(result_by_batch)\n\n\n@ignore_warnings(category=(DeprecationWarning, FutureWarning))\ndef check_methods_subset_invariance(name, estimator_orig):\n # check that method gives invariant results if applied\n # on mini bathes or the whole set\n rnd = np.random.RandomState(0)\n X = 3 * rnd.uniform(size=(20, 3))\n X = pairwise_estimator_convert_X(X, estimator_orig)\n y = X[:, 0].astype(np.int)\n estimator = clone(estimator_orig)\n y = multioutput_estimator_convert_y_2d(estimator, y)\n\n if hasattr(estimator, \"n_components\"):\n estimator.n_components = 1\n if hasattr(estimator, \"n_clusters\"):\n estimator.n_clusters = 1\n\n set_random_state(estimator, 1)\n estimator.fit(X, y)\n\n for method in [\"predict\", \"transform\", \"decision_function\",\n \"score_samples\", \"predict_proba\"]:\n\n msg = (\"{method} of {name} is not invariant when applied \"\n \"to a subset.\").format(method=method, name=name)\n # TODO remove cases when corrected\n if (name, method) in [('NuSVC', 'decision_function'),\n ('SparsePCA', 'transform'),\n ('MiniBatchSparsePCA', 'transform'),\n ('DummyClassifier', 'predict'),\n ('BernoulliRBM', 'score_samples')]:\n raise SkipTest(msg)\n\n if hasattr(estimator, method):\n result_full, result_by_batch = _apply_on_subsets(\n getattr(estimator, method), X)\n assert_allclose(result_full, result_by_batch,\n atol=1e-7, err_msg=msg)\n\n\n@ignore_warnings\ndef check_fit2d_1sample(name, estimator_orig):\n # Check that fitting a 2d array with only one sample either works or\n # returns an informative message. The error message should either mention\n # the number of samples or the number of classes.\n rnd = np.random.RandomState(0)\n X = 3 * rnd.uniform(size=(1, 10))\n y = X[:, 0].astype(np.int)\n estimator = clone(estimator_orig)\n y = multioutput_estimator_convert_y_2d(estimator, y)\n\n if hasattr(estimator, \"n_components\"):\n estimator.n_components = 1\n if hasattr(estimator, \"n_clusters\"):\n estimator.n_clusters = 1\n\n set_random_state(estimator, 1)\n\n # min_cluster_size cannot be less than the data size for OPTICS.\n if name == 'OPTICS':\n estimator.set_params(min_samples=1)\n\n msgs = [\"1 sample\", \"n_samples = 1\", \"n_samples=1\", \"one sample\",\n \"1 class\", \"one class\"]\n\n try:\n estimator.fit(X, y)\n except ValueError as e:\n if all(msg not in repr(e) for msg in msgs):\n raise e\n\n\n@ignore_warnings\ndef check_fit2d_1feature(name, estimator_orig):\n # check fitting a 2d array with only 1 feature either works or returns\n # informative message\n rnd = np.random.RandomState(0)\n X = 3 * rnd.uniform(size=(10, 1))\n X = pairwise_estimator_convert_X(X, estimator_orig)\n y = X[:, 0].astype(np.int)\n estimator = clone(estimator_orig)\n y = multioutput_estimator_convert_y_2d(estimator, y)\n\n if hasattr(estimator, \"n_components\"):\n estimator.n_components = 1\n if hasattr(estimator, \"n_clusters\"):\n estimator.n_clusters = 1\n # ensure two labels in subsample for RandomizedLogisticRegression\n if name == 'RandomizedLogisticRegression':\n estimator.sample_fraction = 1\n # ensure non skipped trials for RANSACRegressor\n if name == 'RANSACRegressor':\n estimator.residual_threshold = 0.5\n\n y = multioutput_estimator_convert_y_2d(estimator, y)\n set_random_state(estimator, 1)\n\n msgs = [\"1 feature(s)\", \"n_features = 1\", \"n_features=1\"]\n\n try:\n estimator.fit(X, y)\n except ValueError as e:\n if all(msg not in repr(e) for msg in msgs):\n raise e\n\n\n@ignore_warnings\ndef check_fit1d(name, estimator_orig):\n # check fitting 1d X array raises a ValueError\n rnd = np.random.RandomState(0)\n X = 3 * rnd.uniform(size=(20))\n y = X.astype(np.int)\n estimator = clone(estimator_orig)\n tags = _safe_tags(estimator)\n if tags[\"no_validation\"]:\n # FIXME this is a bit loose\n return\n y = multioutput_estimator_convert_y_2d(estimator, y)\n\n if hasattr(estimator, \"n_components\"):\n estimator.n_components = 1\n if hasattr(estimator, \"n_clusters\"):\n estimator.n_clusters = 1\n\n set_random_state(estimator, 1)\n assert_raises(ValueError, estimator.fit, X, y)\n\n\n@ignore_warnings(category=(DeprecationWarning, FutureWarning))\ndef check_transformer_general(name, transformer, readonly_memmap=False):\n X, y = make_blobs(n_samples=30, centers=[[0, 0, 0], [1, 1, 1]],\n random_state=0, n_features=2, cluster_std=0.1)\n X = StandardScaler().fit_transform(X)\n X -= X.min()\n\n if readonly_memmap:\n X, y = create_memmap_backed_data([X, y])\n\n _check_transformer(name, transformer, X, y)\n _check_transformer(name, transformer, X.tolist(), y.tolist())\n\n\n@ignore_warnings(category=(DeprecationWarning, FutureWarning))\ndef check_transformer_data_not_an_array(name, transformer):\n X, y = make_blobs(n_samples=30, centers=[[0, 0, 0], [1, 1, 1]],\n random_state=0, n_features=2, cluster_std=0.1)\n X = StandardScaler().fit_transform(X)\n # We need to make sure that we have non negative data, for things\n # like NMF\n X -= X.min() - .1\n this_X = NotAnArray(X)\n this_y = NotAnArray(np.asarray(y))\n _check_transformer(name, transformer, this_X, this_y)\n\n\n@ignore_warnings(category=(DeprecationWarning, FutureWarning))\ndef check_transformers_unfitted(name, transformer):\n X, y = _boston_subset()\n\n transformer = clone(transformer)\n with assert_raises((AttributeError, ValueError), msg=\"The unfitted \"\n \"transformer {} does not raise an error when \"\n \"transform is called. Perhaps use \"\n \"check_is_fitted in transform.\".format(name)):\n transformer.transform(X)\n\n\ndef _check_transformer(name, transformer_orig, X, y):\n n_samples, n_features = np.asarray(X).shape\n transformer = clone(transformer_orig)\n set_random_state(transformer)\n\n # fit\n\n if name in CROSS_DECOMPOSITION:\n y_ = np.c_[y, y]\n y_[::2, 1] *= 2\n else:\n y_ = y\n\n transformer.fit(X, y_)\n # fit_transform method should work on non fitted estimator\n transformer_clone = clone(transformer)\n X_pred = transformer_clone.fit_transform(X, y=y_)\n\n if isinstance(X_pred, tuple):\n for x_pred in X_pred:\n assert_equal(x_pred.shape[0], n_samples)\n else:\n # check for consistent n_samples\n assert_equal(X_pred.shape[0], n_samples)\n\n if hasattr(transformer, 'transform'):\n if name in CROSS_DECOMPOSITION:\n X_pred2 = transformer.transform(X, y_)\n X_pred3 = transformer.fit_transform(X, y=y_)\n else:\n X_pred2 = transformer.transform(X)\n X_pred3 = transformer.fit_transform(X, y=y_)\n\n if _safe_tags(transformer_orig, 'non_deterministic'):\n msg = name + ' is non deterministic'\n raise SkipTest(msg)\n if isinstance(X_pred, tuple) and isinstance(X_pred2, tuple):\n for x_pred, x_pred2, x_pred3 in zip(X_pred, X_pred2, X_pred3):\n assert_allclose_dense_sparse(\n x_pred, x_pred2, atol=1e-2,\n err_msg=\"fit_transform and transform outcomes \"\n \"not consistent in %s\"\n % transformer)\n assert_allclose_dense_sparse(\n x_pred, x_pred3, atol=1e-2,\n err_msg=\"consecutive fit_transform outcomes \"\n \"not consistent in %s\"\n % transformer)\n else:\n assert_allclose_dense_sparse(\n X_pred, X_pred2,\n err_msg=\"fit_transform and transform outcomes \"\n \"not consistent in %s\"\n % transformer, atol=1e-2)\n assert_allclose_dense_sparse(\n X_pred, X_pred3, atol=1e-2,\n err_msg=\"consecutive fit_transform outcomes \"\n \"not consistent in %s\"\n % transformer)\n assert_equal(_num_samples(X_pred2), n_samples)\n assert_equal(_num_samples(X_pred3), n_samples)\n\n # raises error on malformed input for transform\n if hasattr(X, 'T') and not _safe_tags(transformer, \"stateless\"):\n # If it's not an array, it does not have a 'T' property\n with assert_raises(ValueError, msg=\"The transformer {} does \"\n \"not raise an error when the number of \"\n \"features in transform is different from\"\n \" the number of features in \"\n \"fit.\".format(name)):\n transformer.transform(X.T)\n\n\n@ignore_warnings\ndef check_pipeline_consistency(name, estimator_orig):\n if _safe_tags(estimator_orig, 'non_deterministic'):\n msg = name + ' is non deterministic'\n raise SkipTest(msg)\n\n # check that make_pipeline(est) gives same score as est\n X, y = make_blobs(n_samples=30, centers=[[0, 0, 0], [1, 1, 1]],\n random_state=0, n_features=2, cluster_std=0.1)\n X -= X.min()\n X = pairwise_estimator_convert_X(X, estimator_orig, kernel=rbf_kernel)\n estimator = clone(estimator_orig)\n y = multioutput_estimator_convert_y_2d(estimator, y)\n set_random_state(estimator)\n pipeline = make_pipeline(estimator)\n estimator.fit(X, y)\n pipeline.fit(X, y)\n\n funcs = [\"score\", \"fit_transform\"]\n\n for func_name in funcs:\n func = getattr(estimator, func_name, None)\n if func is not None:\n func_pipeline = getattr(pipeline, func_name)\n result = func(X, y)\n result_pipe = func_pipeline(X, y)\n assert_allclose_dense_sparse(result, result_pipe)\n\n\n@ignore_warnings\ndef check_fit_score_takes_y(name, estimator_orig):\n # check that all estimators accept an optional y\n # in fit and score so they can be used in pipelines\n rnd = np.random.RandomState(0)\n X = rnd.uniform(size=(10, 3))\n X = pairwise_estimator_convert_X(X, estimator_orig)\n y = np.arange(10) % 3\n estimator = clone(estimator_orig)\n y = multioutput_estimator_convert_y_2d(estimator, y)\n set_random_state(estimator)\n\n funcs = [\"fit\", \"score\", \"partial_fit\", \"fit_predict\", \"fit_transform\"]\n for func_name in funcs:\n func = getattr(estimator, func_name, None)\n if func is not None:\n func(X, y)\n args = [p.name for p in signature(func).parameters.values()]\n if args[0] == \"self\":\n # if_delegate_has_method makes methods into functions\n # with an explicit \"self\", so need to shift arguments\n args = args[1:]\n assert args[1] in [\"y\", \"Y\"], (\n \"Expected y or Y as second argument for method \"\n \"%s of %s. Got arguments: %r.\"\n % (func_name, type(estimator).__name__, args))\n\n\n@ignore_warnings\ndef check_estimators_dtypes(name, estimator_orig):\n rnd = np.random.RandomState(0)\n X_train_32 = 3 * rnd.uniform(size=(20, 5)).astype(np.float32)\n X_train_32 = pairwise_estimator_convert_X(X_train_32, estimator_orig)\n X_train_64 = X_train_32.astype(np.float64)\n X_train_int_64 = X_train_32.astype(np.int64)\n X_train_int_32 = X_train_32.astype(np.int32)\n y = X_train_int_64[:, 0]\n y = multioutput_estimator_convert_y_2d(estimator_orig, y)\n\n methods = [\"predict\", \"transform\", \"decision_function\", \"predict_proba\"]\n\n for X_train in [X_train_32, X_train_64, X_train_int_64, X_train_int_32]:\n estimator = clone(estimator_orig)\n set_random_state(estimator, 1)\n estimator.fit(X_train, y)\n\n for method in methods:\n if hasattr(estimator, method):\n getattr(estimator, method)(X_train)\n\n\n@ignore_warnings(category=(DeprecationWarning, FutureWarning))\ndef check_estimators_empty_data_messages(name, estimator_orig):\n e = clone(estimator_orig)\n set_random_state(e, 1)\n\n X_zero_samples = np.empty(0).reshape(0, 3)\n # The precise message can change depending on whether X or y is\n # validated first. Let us test the type of exception only:\n with assert_raises(ValueError, msg=\"The estimator {} does not\"\n \" raise an error when an empty data is used \"\n \"to train. Perhaps use \"\n \"check_array in train.\".format(name)):\n e.fit(X_zero_samples, [])\n\n X_zero_features = np.empty(0).reshape(3, 0)\n # the following y should be accepted by both classifiers and regressors\n # and ignored by unsupervised models\n y = multioutput_estimator_convert_y_2d(e, np.array([1, 0, 1]))\n msg = (r\"0 feature\\(s\\) \\(shape=\\(3, 0\\)\\) while a minimum of \\d* \"\n \"is required.\")\n assert_raises_regex(ValueError, msg, e.fit, X_zero_features, y)\n\n\n@ignore_warnings(category=DeprecationWarning)\ndef check_estimators_nan_inf(name, estimator_orig):\n # Checks that Estimator X's do not contain NaN or inf.\n rnd = np.random.RandomState(0)\n X_train_finite = pairwise_estimator_convert_X(rnd.uniform(size=(10, 3)),\n estimator_orig)\n X_train_nan = rnd.uniform(size=(10, 3))\n X_train_nan[0, 0] = np.nan\n X_train_inf = rnd.uniform(size=(10, 3))\n X_train_inf[0, 0] = np.inf\n y = np.ones(10)\n y[:5] = 0\n y = multioutput_estimator_convert_y_2d(estimator_orig, y)\n error_string_fit = \"Estimator doesn't check for NaN and inf in fit.\"\n error_string_predict = (\"Estimator doesn't check for NaN and inf in\"\n \" predict.\")\n error_string_transform = (\"Estimator doesn't check for NaN and inf in\"\n \" transform.\")\n for X_train in [X_train_nan, X_train_inf]:\n # catch deprecation warnings\n with ignore_warnings(category=(DeprecationWarning, FutureWarning)):\n estimator = clone(estimator_orig)\n set_random_state(estimator, 1)\n # try to fit\n try:\n estimator.fit(X_train, y)\n except ValueError as e:\n if 'inf' not in repr(e) and 'NaN' not in repr(e):\n print(error_string_fit, estimator, e)\n traceback.print_exc(file=sys.stdout)\n raise e\n except Exception as exc:\n print(error_string_fit, estimator, exc)\n traceback.print_exc(file=sys.stdout)\n raise exc\n else:\n raise AssertionError(error_string_fit, estimator)\n # actually fit\n estimator.fit(X_train_finite, y)\n\n # predict\n if hasattr(estimator, \"predict\"):\n try:\n estimator.predict(X_train)\n except ValueError as e:\n if 'inf' not in repr(e) and 'NaN' not in repr(e):\n print(error_string_predict, estimator, e)\n traceback.print_exc(file=sys.stdout)\n raise e\n except Exception as exc:\n print(error_string_predict, estimator, exc)\n traceback.print_exc(file=sys.stdout)\n else:\n raise AssertionError(error_string_predict, estimator)\n\n # transform\n if hasattr(estimator, \"transform\"):\n try:\n estimator.transform(X_train)\n except ValueError as e:\n if 'inf' not in repr(e) and 'NaN' not in repr(e):\n print(error_string_transform, estimator, e)\n traceback.print_exc(file=sys.stdout)\n raise e\n except Exception as exc:\n print(error_string_transform, estimator, exc)\n traceback.print_exc(file=sys.stdout)\n else:\n raise AssertionError(error_string_transform, estimator)\n\n\n@ignore_warnings\ndef check_estimators_pickle(name, estimator_orig):\n \"\"\"Test that we can pickle all estimators\"\"\"\n check_methods = [\"predict\", \"transform\", \"decision_function\",\n \"predict_proba\"]\n\n X, y = make_blobs(n_samples=30, centers=[[0, 0, 0], [1, 1, 1]],\n random_state=0, n_features=2, cluster_std=0.1)\n\n # some estimators can't do features less than 0\n X -= X.min()\n X = pairwise_estimator_convert_X(X, estimator_orig, kernel=rbf_kernel)\n\n tags = _safe_tags(estimator_orig)\n # include NaN values when the estimator should deal with them\n if tags['allow_nan']:\n # set randomly 10 elements to np.nan\n rng = np.random.RandomState(42)\n mask = rng.choice(X.size, 10, replace=False)\n X.reshape(-1)[mask] = np.nan\n\n estimator = clone(estimator_orig)\n\n # some estimators only take multioutputs\n y = multioutput_estimator_convert_y_2d(estimator, y)\n\n set_random_state(estimator)\n estimator.fit(X, y)\n\n result = dict()\n for method in check_methods:\n if hasattr(estimator, method):\n result[method] = getattr(estimator, method)(X)\n\n # pickle and unpickle!\n pickled_estimator = pickle.dumps(estimator)\n if estimator.__module__.startswith('sklearn.'):\n assert b\"version\" in pickled_estimator\n unpickled_estimator = pickle.loads(pickled_estimator)\n\n result = dict()\n for method in check_methods:\n if hasattr(estimator, method):\n result[method] = getattr(estimator, method)(X)\n\n for method in result:\n unpickled_result = getattr(unpickled_estimator, method)(X)\n assert_allclose_dense_sparse(result[method], unpickled_result)\n\n\n@ignore_warnings(category=(DeprecationWarning, FutureWarning))\ndef check_estimators_partial_fit_n_features(name, estimator_orig):\n # check if number of features changes between calls to partial_fit.\n if not hasattr(estimator_orig, 'partial_fit'):\n return\n estimator = clone(estimator_orig)\n X, y = make_blobs(n_samples=50, random_state=1)\n X -= X.min()\n\n try:\n if is_classifier(estimator):\n classes = np.unique(y)\n estimator.partial_fit(X, y, classes=classes)\n else:\n estimator.partial_fit(X, y)\n except NotImplementedError:\n return\n\n with assert_raises(ValueError,\n msg=\"The estimator {} does not raise an\"\n \" error when the number of features\"\n \" changes between calls to \"\n \"partial_fit.\".format(name)):\n estimator.partial_fit(X[:, :-1], y)\n\n\n@ignore_warnings(category=(DeprecationWarning, FutureWarning))\ndef check_clustering(name, clusterer_orig, readonly_memmap=False):\n clusterer = clone(clusterer_orig)\n X, y = make_blobs(n_samples=50, random_state=1)\n X, y = shuffle(X, y, random_state=7)\n X = StandardScaler().fit_transform(X)\n rng = np.random.RandomState(7)\n X_noise = np.concatenate([X, rng.uniform(low=-3, high=3, size=(5, 2))])\n\n if readonly_memmap:\n X, y, X_noise = create_memmap_backed_data([X, y, X_noise])\n\n n_samples, n_features = X.shape\n # catch deprecation and neighbors warnings\n if hasattr(clusterer, \"n_clusters\"):\n clusterer.set_params(n_clusters=3)\n set_random_state(clusterer)\n if name == 'AffinityPropagation':\n clusterer.set_params(preference=-100)\n clusterer.set_params(max_iter=100)\n\n # fit\n clusterer.fit(X)\n # with lists\n clusterer.fit(X.tolist())\n\n pred = clusterer.labels_\n assert_equal(pred.shape, (n_samples,))\n assert_greater(adjusted_rand_score(pred, y), 0.4)\n if _safe_tags(clusterer, 'non_deterministic'):\n return\n set_random_state(clusterer)\n with warnings.catch_warnings(record=True):\n pred2 = clusterer.fit_predict(X)\n assert_array_equal(pred, pred2)\n\n # fit_predict(X) and labels_ should be of type int\n assert_in(pred.dtype, [np.dtype('int32'), np.dtype('int64')])\n assert_in(pred2.dtype, [np.dtype('int32'), np.dtype('int64')])\n\n # Add noise to X to test the possible values of the labels\n labels = clusterer.fit_predict(X_noise)\n\n # There should be at least one sample in every cluster. Equivalently\n # labels_ should contain all the consecutive values between its\n # min and its max.\n labels_sorted = np.unique(labels)\n assert_array_equal(labels_sorted, np.arange(labels_sorted[0],\n labels_sorted[-1] + 1))\n\n # Labels are expected to start at 0 (no noise) or -1 (if noise)\n assert labels_sorted[0] in [0, -1]\n # Labels should be less than n_clusters - 1\n if hasattr(clusterer, 'n_clusters'):\n n_clusters = getattr(clusterer, 'n_clusters')\n assert_greater_equal(n_clusters - 1, labels_sorted[-1])\n # else labels should be less than max(labels_) which is necessarily true\n\n\n@ignore_warnings(category=DeprecationWarning)\ndef check_clusterer_compute_labels_predict(name, clusterer_orig):\n \"\"\"Check that predict is invariant of compute_labels\"\"\"\n X, y = make_blobs(n_samples=20, random_state=0)\n clusterer = clone(clusterer_orig)\n set_random_state(clusterer)\n\n if hasattr(clusterer, \"compute_labels\"):\n # MiniBatchKMeans\n X_pred1 = clusterer.fit(X).predict(X)\n clusterer.set_params(compute_labels=False)\n X_pred2 = clusterer.fit(X).predict(X)\n assert_array_equal(X_pred1, X_pred2)\n\n\n@ignore_warnings(category=DeprecationWarning)\ndef check_classifiers_one_label(name, classifier_orig):\n error_string_fit = \"Classifier can't train when only one class is present.\"\n error_string_predict = (\"Classifier can't predict when only one class is \"\n \"present.\")\n rnd = np.random.RandomState(0)\n X_train = rnd.uniform(size=(10, 3))\n X_test = rnd.uniform(size=(10, 3))\n y = np.ones(10)\n # catch deprecation warnings\n with ignore_warnings(category=(DeprecationWarning, FutureWarning)):\n classifier = clone(classifier_orig)\n # try to fit\n try:\n classifier.fit(X_train, y)\n except ValueError as e:\n if 'class' not in repr(e):\n print(error_string_fit, classifier, e)\n traceback.print_exc(file=sys.stdout)\n raise e\n else:\n return\n except Exception as exc:\n print(error_string_fit, classifier, exc)\n traceback.print_exc(file=sys.stdout)\n raise exc\n # predict\n try:\n assert_array_equal(classifier.predict(X_test), y)\n except Exception as exc:\n print(error_string_predict, classifier, exc)\n raise exc\n\n\n@ignore_warnings # Warnings are raised by decision function\ndef check_classifiers_train(name, classifier_orig, readonly_memmap=False):\n X_m, y_m = make_blobs(n_samples=300, random_state=0)\n X_m, y_m = shuffle(X_m, y_m, random_state=7)\n X_m = StandardScaler().fit_transform(X_m)\n # generate binary problem from multi-class one\n y_b = y_m[y_m != 2]\n X_b = X_m[y_m != 2]\n tags = _safe_tags(classifier_orig)\n\n if name in ['BernoulliNB', 'MultinomialNB', 'ComplementNB']:\n X_m -= X_m.min()\n X_b -= X_b.min()\n\n if readonly_memmap:\n X_m, y_m, X_b, y_b = create_memmap_backed_data([X_m, y_m, X_b, y_b])\n\n for (X, y) in [(X_m, y_m), (X_b, y_b)]:\n classes = np.unique(y)\n n_classes = len(classes)\n n_samples, n_features = X.shape\n classifier = clone(classifier_orig)\n X = pairwise_estimator_convert_X(X, classifier)\n y = multioutput_estimator_convert_y_2d(classifier, y)\n\n set_random_state(classifier)\n # raises error on malformed input for fit\n if not tags[\"no_validation\"]:\n with assert_raises(\n ValueError,\n msg=\"The classifier {} does not \"\n \"raise an error when incorrect/malformed input \"\n \"data for fit is passed. The number of training \"\n \"examples is not the same as the number of labels. \"\n \"Perhaps use check_X_y in fit.\".format(name)):\n classifier.fit(X, y[:-1])\n\n # fit\n classifier.fit(X, y)\n # with lists\n classifier.fit(X.tolist(), y.tolist())\n assert hasattr(classifier, \"classes_\")\n y_pred = classifier.predict(X)\n\n assert_equal(y_pred.shape, (n_samples,))\n # training set performance\n if not tags['poor_score']:\n assert_greater(accuracy_score(y, y_pred), 0.83)\n\n # raises error on malformed input for predict\n msg_pairwise = (\n \"The classifier {} does not raise an error when shape of X in \"\n \" {} is not equal to (n_test_samples, n_training_samples)\")\n msg = (\"The classifier {} does not raise an error when the number of \"\n \"features in {} is different from the number of features in \"\n \"fit.\")\n\n if not tags[\"no_validation\"]:\n if _is_pairwise(classifier):\n with assert_raises(ValueError,\n msg=msg_pairwise.format(name, \"predict\")):\n classifier.predict(X.reshape(-1, 1))\n else:\n with assert_raises(ValueError,\n msg=msg.format(name, \"predict\")):\n classifier.predict(X.T)\n if hasattr(classifier, \"decision_function\"):\n try:\n # decision_function agrees with predict\n decision = classifier.decision_function(X)\n if n_classes == 2:\n if not tags[\"multioutput_only\"]:\n assert_equal(decision.shape, (n_samples,))\n else:\n assert_equal(decision.shape, (n_samples, 1))\n dec_pred = (decision.ravel() > 0).astype(np.int)\n assert_array_equal(dec_pred, y_pred)\n else:\n assert_equal(decision.shape, (n_samples, n_classes))\n assert_array_equal(np.argmax(decision, axis=1), y_pred)\n\n # raises error on malformed input for decision_function\n if not tags[\"no_validation\"]:\n if _is_pairwise(classifier):\n with assert_raises(ValueError, msg=msg_pairwise.format(\n name, \"decision_function\")):\n classifier.decision_function(X.reshape(-1, 1))\n else:\n with assert_raises(ValueError, msg=msg.format(\n name, \"decision_function\")):\n classifier.decision_function(X.T)\n except NotImplementedError:\n pass\n\n if hasattr(classifier, \"predict_proba\"):\n # predict_proba agrees with predict\n y_prob = classifier.predict_proba(X)\n assert_equal(y_prob.shape, (n_samples, n_classes))\n assert_array_equal(np.argmax(y_prob, axis=1), y_pred)\n # check that probas for all classes sum to one\n assert_array_almost_equal(np.sum(y_prob, axis=1),\n np.ones(n_samples))\n if not tags[\"no_validation\"]:\n # raises error on malformed input for predict_proba\n if _is_pairwise(classifier_orig):\n with assert_raises(ValueError, msg=msg_pairwise.format(\n name, \"predict_proba\")):\n classifier.predict_proba(X.reshape(-1, 1))\n else:\n with assert_raises(ValueError, msg=msg.format(\n name, \"predict_proba\")):\n classifier.predict_proba(X.T)\n if hasattr(classifier, \"predict_log_proba\"):\n # predict_log_proba is a transformation of predict_proba\n y_log_prob = classifier.predict_log_proba(X)\n assert_allclose(y_log_prob, np.log(y_prob), 8, atol=1e-9)\n assert_array_equal(np.argsort(y_log_prob), np.argsort(y_prob))\n\n\ndef check_outlier_corruption(num_outliers, expected_outliers, decision):\n # Check for deviation from the precise given contamination level that may\n # be due to ties in the anomaly scores.\n if num_outliers < expected_outliers:\n start = num_outliers\n end = expected_outliers + 1\n else:\n start = expected_outliers\n end = num_outliers + 1\n\n # ensure that all values in the 'critical area' are tied,\n # leading to the observed discrepancy between provided\n # and actual contamination levels.\n sorted_decision = np.sort(decision)\n msg = ('The number of predicted outliers is not equal to the expected '\n 'number of outliers and this difference is not explained by the '\n 'number of ties in the decision_function values')\n assert len(np.unique(sorted_decision[start:end])) == 1, msg\n\n\ndef check_outliers_train(name, estimator_orig, readonly_memmap=True):\n n_samples = 300\n X, _ = make_blobs(n_samples=n_samples, random_state=0)\n X = shuffle(X, random_state=7)\n\n if readonly_memmap:\n X = create_memmap_backed_data(X)\n\n n_samples, n_features = X.shape\n estimator = clone(estimator_orig)\n set_random_state(estimator)\n\n # fit\n estimator.fit(X)\n # with lists\n estimator.fit(X.tolist())\n\n y_pred = estimator.predict(X)\n assert y_pred.shape == (n_samples,)\n assert y_pred.dtype.kind == 'i'\n assert_array_equal(np.unique(y_pred), np.array([-1, 1]))\n\n decision = estimator.decision_function(X)\n scores = estimator.score_samples(X)\n for output in [decision, scores]:\n assert output.dtype == np.dtype('float')\n assert output.shape == (n_samples,)\n\n # raises error on malformed input for predict\n assert_raises(ValueError, estimator.predict, X.T)\n\n # decision_function agrees with predict\n dec_pred = (decision >= 0).astype(np.int)\n dec_pred[dec_pred == 0] = -1\n assert_array_equal(dec_pred, y_pred)\n\n # raises error on malformed input for decision_function\n assert_raises(ValueError, estimator.decision_function, X.T)\n\n # decision_function is a translation of score_samples\n y_dec = scores - estimator.offset_\n assert_allclose(y_dec, decision)\n\n # raises error on malformed input for score_samples\n assert_raises(ValueError, estimator.score_samples, X.T)\n\n # contamination parameter (not for OneClassSVM which has the nu parameter)\n if (hasattr(estimator, 'contamination')\n and not hasattr(estimator, 'novelty')):\n # proportion of outliers equal to contamination parameter when not\n # set to 'auto'. This is true for the training set and cannot thus be\n # checked as follows for estimators with a novelty parameter such as\n # LocalOutlierFactor (tested in check_outliers_fit_predict)\n expected_outliers = 30\n contamination = expected_outliers / n_samples\n estimator.set_params(contamination=contamination)\n estimator.fit(X)\n y_pred = estimator.predict(X)\n\n num_outliers = np.sum(y_pred != 1)\n # num_outliers should be equal to expected_outliers unless\n # there are ties in the decision_function values. this can\n # only be tested for estimators with a decision_function\n # method, i.e. all estimators except LOF which is already\n # excluded from this if branch.\n if num_outliers != expected_outliers:\n decision = estimator.decision_function(X)\n check_outlier_corruption(num_outliers, expected_outliers, decision)\n\n # raises error when contamination is a scalar and not in [0,1]\n for contamination in [-0.5, 2.3]:\n estimator.set_params(contamination=contamination)\n assert_raises(ValueError, estimator.fit, X)\n\n\n@ignore_warnings(category=(DeprecationWarning, FutureWarning))\ndef check_estimators_fit_returns_self(name, estimator_orig,\n readonly_memmap=False):\n \"\"\"Check if self is returned when calling fit\"\"\"\n X, y = make_blobs(random_state=0, n_samples=9, n_features=4)\n # some want non-negative input\n X -= X.min()\n X = pairwise_estimator_convert_X(X, estimator_orig)\n\n estimator = clone(estimator_orig)\n y = multioutput_estimator_convert_y_2d(estimator, y)\n\n if readonly_memmap:\n X, y = create_memmap_backed_data([X, y])\n\n set_random_state(estimator)\n assert estimator.fit(X, y) is estimator\n\n\n@ignore_warnings\ndef check_estimators_unfitted(name, estimator_orig):\n \"\"\"Check that predict raises an exception in an unfitted estimator.\n\n Unfitted estimators should raise either AttributeError or ValueError.\n The specific exception type NotFittedError inherits from both and can\n therefore be adequately raised for that purpose.\n \"\"\"\n\n # Common test for Regressors, Classifiers and Outlier detection estimators\n X, y = _boston_subset()\n\n estimator = clone(estimator_orig)\n\n msg = \"fit\"\n if hasattr(estimator, 'predict'):\n can_predict = False\n try:\n # some models can predict without fitting\n # like GaussianProcess regressors\n # in this case, we skip this test\n pred = estimator.predict(X)\n assert pred.shape[0] == X.shape[0]\n can_predict = True\n except ValueError:\n pass\n if can_predict:\n raise SkipTest(\n \"{} can predict without fitting, skipping \"\n \"check_estimator_unfitted.\".format(name))\n\n assert_raise_message((AttributeError, ValueError), msg,\n estimator.predict, X)\n\n if hasattr(estimator, 'decision_function'):\n assert_raise_message((AttributeError, ValueError), msg,\n estimator.decision_function, X)\n\n if hasattr(estimator, 'predict_proba'):\n assert_raise_message((AttributeError, ValueError), msg,\n estimator.predict_proba, X)\n\n if hasattr(estimator, 'predict_log_proba'):\n assert_raise_message((AttributeError, ValueError), msg,\n estimator.predict_log_proba, X)\n\n\n@ignore_warnings(category=(DeprecationWarning, FutureWarning))\ndef check_supervised_y_2d(name, estimator_orig):\n if _safe_tags(estimator_orig, \"multioutput_only\"):\n # These only work on 2d, so this test makes no sense\n return\n rnd = np.random.RandomState(0)\n X = pairwise_estimator_convert_X(rnd.uniform(size=(10, 3)), estimator_orig)\n y = np.arange(10) % 3\n estimator = clone(estimator_orig)\n set_random_state(estimator)\n # fit\n estimator.fit(X, y)\n y_pred = estimator.predict(X)\n\n set_random_state(estimator)\n # Check that when a 2D y is given, a DataConversionWarning is\n # raised\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter(\"always\", DataConversionWarning)\n warnings.simplefilter(\"ignore\", RuntimeWarning)\n estimator.fit(X, y[:, np.newaxis])\n y_pred_2d = estimator.predict(X)\n msg = \"expected 1 DataConversionWarning, got: %s\" % (\n \", \".join([str(w_x) for w_x in w]))\n if not _safe_tags(estimator, \"multioutput\"):\n # check that we warned if we don't support multi-output\n assert_greater(len(w), 0, msg)\n assert \"DataConversionWarning('A column-vector y\" \\\n \" was passed when a 1d array was expected\" in msg\n assert_allclose(y_pred.ravel(), y_pred_2d.ravel())\n\n\n@ignore_warnings\ndef check_classifiers_predictions(X, y, name, classifier_orig):\n classes = np.unique(y)\n classifier = clone(classifier_orig)\n if name == 'BernoulliNB':\n X = X > X.mean()\n set_random_state(classifier)\n\n classifier.fit(X, y)\n y_pred = classifier.predict(X)\n\n if hasattr(classifier, \"decision_function\"):\n decision = classifier.decision_function(X)\n assert isinstance(decision, np.ndarray)\n if len(classes) == 2:\n dec_pred = (decision.ravel() > 0).astype(np.int)\n dec_exp = classifier.classes_[dec_pred]\n assert_array_equal(dec_exp, y_pred,\n err_msg=\"decision_function does not match \"\n \"classifier for %r: expected '%s', got '%s'\" %\n (classifier, \", \".join(map(str, dec_exp)),\n \", \".join(map(str, y_pred))))\n elif getattr(classifier, 'decision_function_shape', 'ovr') == 'ovr':\n decision_y = np.argmax(decision, axis=1).astype(int)\n y_exp = classifier.classes_[decision_y]\n assert_array_equal(y_exp, y_pred,\n err_msg=\"decision_function does not match \"\n \"classifier for %r: expected '%s', got '%s'\" %\n (classifier, \", \".join(map(str, y_exp)),\n \", \".join(map(str, y_pred))))\n\n # training set performance\n if name != \"ComplementNB\":\n # This is a pathological data set for ComplementNB.\n # For some specific cases 'ComplementNB' predicts less classes\n # than expected\n assert_array_equal(np.unique(y), np.unique(y_pred))\n assert_array_equal(classes, classifier.classes_,\n err_msg=\"Unexpected classes_ attribute for %r: \"\n \"expected '%s', got '%s'\" %\n (classifier, \", \".join(map(str, classes)),\n \", \".join(map(str, classifier.classes_))))\n\n\ndef choose_check_classifiers_labels(name, y, y_names):\n return y if name in [\"LabelPropagation\", \"LabelSpreading\"] else y_names\n\n\ndef check_classifiers_classes(name, classifier_orig):\n X_multiclass, y_multiclass = make_blobs(n_samples=30, random_state=0,\n cluster_std=0.1)\n X_multiclass, y_multiclass = shuffle(X_multiclass, y_multiclass,\n random_state=7)\n X_multiclass = StandardScaler().fit_transform(X_multiclass)\n # We need to make sure that we have non negative data, for things\n # like NMF\n X_multiclass -= X_multiclass.min() - .1\n\n X_binary = X_multiclass[y_multiclass != 2]\n y_binary = y_multiclass[y_multiclass != 2]\n\n X_multiclass = pairwise_estimator_convert_X(X_multiclass, classifier_orig)\n X_binary = pairwise_estimator_convert_X(X_binary, classifier_orig)\n\n labels_multiclass = [\"one\", \"two\", \"three\"]\n labels_binary = [\"one\", \"two\"]\n\n y_names_multiclass = np.take(labels_multiclass, y_multiclass)\n y_names_binary = np.take(labels_binary, y_binary)\n\n for X, y, y_names in [(X_multiclass, y_multiclass, y_names_multiclass),\n (X_binary, y_binary, y_names_binary)]:\n for y_names_i in [y_names, y_names.astype('O')]:\n y_ = choose_check_classifiers_labels(name, y, y_names_i)\n check_classifiers_predictions(X, y_, name, classifier_orig)\n\n labels_binary = [-1, 1]\n y_names_binary = np.take(labels_binary, y_binary)\n y_binary = choose_check_classifiers_labels(name, y_binary, y_names_binary)\n check_classifiers_predictions(X_binary, y_binary, name, classifier_orig)\n\n\n@ignore_warnings(category=(DeprecationWarning, FutureWarning))\ndef check_regressors_int(name, regressor_orig):\n X, _ = _boston_subset()\n X = pairwise_estimator_convert_X(X[:50], regressor_orig)\n rnd = np.random.RandomState(0)\n y = rnd.randint(3, size=X.shape[0])\n y = multioutput_estimator_convert_y_2d(regressor_orig, y)\n rnd = np.random.RandomState(0)\n # separate estimators to control random seeds\n regressor_1 = clone(regressor_orig)\n regressor_2 = clone(regressor_orig)\n set_random_state(regressor_1)\n set_random_state(regressor_2)\n\n if name in CROSS_DECOMPOSITION:\n y_ = np.vstack([y, 2 * y + rnd.randint(2, size=len(y))])\n y_ = y_.T\n else:\n y_ = y\n\n # fit\n regressor_1.fit(X, y_)\n pred1 = regressor_1.predict(X)\n regressor_2.fit(X, y_.astype(np.float))\n pred2 = regressor_2.predict(X)\n assert_allclose(pred1, pred2, atol=1e-2, err_msg=name)\n\n\n@ignore_warnings(category=(DeprecationWarning, FutureWarning))\ndef check_regressors_train(name, regressor_orig, readonly_memmap=False):\n X, y = _boston_subset()\n X = pairwise_estimator_convert_X(X, regressor_orig)\n y = StandardScaler().fit_transform(y.reshape(-1, 1)) # X is already scaled\n y = y.ravel()\n regressor = clone(regressor_orig)\n y = multioutput_estimator_convert_y_2d(regressor, y)\n if name in CROSS_DECOMPOSITION:\n rnd = np.random.RandomState(0)\n y_ = np.vstack([y, 2 * y + rnd.randint(2, size=len(y))])\n y_ = y_.T\n else:\n y_ = y\n\n if readonly_memmap:\n X, y, y_ = create_memmap_backed_data([X, y, y_])\n\n if not hasattr(regressor, 'alphas') and hasattr(regressor, 'alpha'):\n # linear regressors need to set alpha, but not generalized CV ones\n regressor.alpha = 0.01\n if name == 'PassiveAggressiveRegressor':\n regressor.C = 0.01\n\n # raises error on malformed input for fit\n with assert_raises(ValueError, msg=\"The classifier {} does not\"\n \" raise an error when incorrect/malformed input \"\n \"data for fit is passed. The number of training \"\n \"examples is not the same as the number of \"\n \"labels. Perhaps use check_X_y in fit.\".format(name)):\n regressor.fit(X, y[:-1])\n # fit\n set_random_state(regressor)\n regressor.fit(X, y_)\n regressor.fit(X.tolist(), y_.tolist())\n y_pred = regressor.predict(X)\n assert_equal(y_pred.shape, y_.shape)\n\n # TODO: find out why PLS and CCA fail. RANSAC is random\n # and furthermore assumes the presence of outliers, hence\n # skipped\n if not _safe_tags(regressor, \"poor_score\"):\n assert_greater(regressor.score(X, y_), 0.5)\n\n\n@ignore_warnings\ndef check_regressors_no_decision_function(name, regressor_orig):\n # checks whether regressors have decision_function or predict_proba\n rng = np.random.RandomState(0)\n X = rng.normal(size=(10, 4))\n regressor = clone(regressor_orig)\n y = multioutput_estimator_convert_y_2d(regressor, X[:, 0])\n\n if hasattr(regressor, \"n_components\"):\n # FIXME CCA, PLS is not robust to rank 1 effects\n regressor.n_components = 1\n\n regressor.fit(X, y)\n funcs = [\"decision_function\", \"predict_proba\", \"predict_log_proba\"]\n for func_name in funcs:\n func = getattr(regressor, func_name, None)\n if func is None:\n # doesn't have function\n continue\n # has function. Should raise deprecation warning\n msg = func_name\n assert_warns_message(DeprecationWarning, msg, func, X)\n\n\n@ignore_warnings(category=(DeprecationWarning, FutureWarning))\ndef check_class_weight_classifiers(name, classifier_orig):\n if name == \"NuSVC\":\n # the sparse version has a parameter that doesn't do anything\n raise SkipTest(\"Not testing NuSVC class weight as it is ignored.\")\n if name.endswith(\"NB\"):\n # NaiveBayes classifiers have a somewhat different interface.\n # FIXME SOON!\n raise SkipTest\n\n for n_centers in [2, 3]:\n # create a very noisy dataset\n X, y = make_blobs(centers=n_centers, random_state=0, cluster_std=20)\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.5,\n random_state=0)\n\n # can't use gram_if_pairwise() here, setting up gram matrix manually\n if _is_pairwise(classifier_orig):\n X_test = rbf_kernel(X_test, X_train)\n X_train = rbf_kernel(X_train, X_train)\n\n n_centers = len(np.unique(y_train))\n\n if n_centers == 2:\n class_weight = {0: 1000, 1: 0.0001}\n else:\n class_weight = {0: 1000, 1: 0.0001, 2: 0.0001}\n\n classifier = clone(classifier_orig).set_params(\n class_weight=class_weight)\n if hasattr(classifier, \"n_iter\"):\n classifier.set_params(n_iter=100)\n if hasattr(classifier, \"max_iter\"):\n classifier.set_params(max_iter=1000)\n if hasattr(classifier, \"min_weight_fraction_leaf\"):\n classifier.set_params(min_weight_fraction_leaf=0.01)\n if hasattr(classifier, \"n_iter_no_change\"):\n classifier.set_params(n_iter_no_change=20)\n\n set_random_state(classifier)\n classifier.fit(X_train, y_train)\n y_pred = classifier.predict(X_test)\n # XXX: Generally can use 0.89 here. On Windows, LinearSVC gets\n # 0.88 (Issue #9111)\n assert_greater(np.mean(y_pred == 0), 0.87)\n\n\n@ignore_warnings(category=(DeprecationWarning, FutureWarning))\ndef check_class_weight_balanced_classifiers(name, classifier_orig, X_train,\n y_train, X_test, y_test, weights):\n classifier = clone(classifier_orig)\n if hasattr(classifier, \"n_iter\"):\n classifier.set_params(n_iter=100)\n if hasattr(classifier, \"max_iter\"):\n classifier.set_params(max_iter=1000)\n\n set_random_state(classifier)\n classifier.fit(X_train, y_train)\n y_pred = classifier.predict(X_test)\n\n classifier.set_params(class_weight='balanced')\n classifier.fit(X_train, y_train)\n y_pred_balanced = classifier.predict(X_test)\n assert_greater(f1_score(y_test, y_pred_balanced, average='weighted'),\n f1_score(y_test, y_pred, average='weighted'))\n\n\n@ignore_warnings(category=(DeprecationWarning, FutureWarning))\ndef check_class_weight_balanced_linear_classifier(name, Classifier):\n \"\"\"Test class weights with non-contiguous class labels.\"\"\"\n # this is run on classes, not instances, though this should be changed\n X = np.array([[-1.0, -1.0], [-1.0, 0], [-.8, -1.0],\n [1.0, 1.0], [1.0, 0.0]])\n y = np.array([1, 1, 1, -1, -1])\n\n classifier = Classifier()\n\n if hasattr(classifier, \"n_iter\"):\n # This is a very small dataset, default n_iter are likely to prevent\n # convergence\n classifier.set_params(n_iter=1000)\n if hasattr(classifier, \"max_iter\"):\n classifier.set_params(max_iter=1000)\n set_random_state(classifier)\n\n # Let the model compute the class frequencies\n classifier.set_params(class_weight='balanced')\n coef_balanced = classifier.fit(X, y).coef_.copy()\n\n # Count each label occurrence to reweight manually\n n_samples = len(y)\n n_classes = float(len(np.unique(y)))\n\n class_weight = {1: n_samples / (np.sum(y == 1) * n_classes),\n -1: n_samples / (np.sum(y == -1) * n_classes)}\n classifier.set_params(class_weight=class_weight)\n coef_manual = classifier.fit(X, y).coef_.copy()\n\n assert_allclose(coef_balanced, coef_manual,\n err_msg=\"Classifier %s is not computing\"\n \" class_weight=balanced properly.\"\n % name)\n\n\n@ignore_warnings(category=(DeprecationWarning, FutureWarning))\ndef check_estimators_overwrite_params(name, estimator_orig):\n X, y = make_blobs(random_state=0, n_samples=9)\n # some want non-negative input\n X -= X.min()\n X = pairwise_estimator_convert_X(X, estimator_orig, kernel=rbf_kernel)\n estimator = clone(estimator_orig)\n y = multioutput_estimator_convert_y_2d(estimator, y)\n\n set_random_state(estimator)\n\n # Make a physical copy of the original estimator parameters before fitting.\n params = estimator.get_params()\n original_params = deepcopy(params)\n\n # Fit the model\n estimator.fit(X, y)\n\n # Compare the state of the model parameters with the original parameters\n new_params = estimator.get_params()\n for param_name, original_value in original_params.items():\n new_value = new_params[param_name]\n\n # We should never change or mutate the internal state of input\n # parameters by default. To check this we use the joblib.hash function\n # that introspects recursively any subobjects to compute a checksum.\n # The only exception to this rule of immutable constructor parameters\n # is possible RandomState instance but in this check we explicitly\n # fixed the random_state params recursively to be integer seeds.\n assert_equal(_joblib.hash(new_value), _joblib.hash(original_value),\n \"Estimator %s should not change or mutate \"\n \" the parameter %s from %s to %s during fit.\"\n % (name, param_name, original_value, new_value))\n\n\ndef check_no_attributes_set_in_init(name, estimator):\n \"\"\"Check setting during init. \"\"\"\n\n if hasattr(type(estimator).__init__, \"deprecated_original\"):\n return\n\n init_params = _get_args(type(estimator).__init__)\n if IS_PYPY:\n # __init__ signature has additional objects in PyPy\n for key in ['obj']:\n if key in init_params:\n init_params.remove(key)\n parents_init_params = [param for params_parent in\n (_get_args(parent) for parent in\n type(estimator).__mro__)\n for param in params_parent]\n\n # Test for no setting apart from parameters during init\n invalid_attr = (set(vars(estimator)) - set(init_params)\n - set(parents_init_params))\n assert not invalid_attr, (\n \"Estimator %s should not set any attribute apart\"\n \" from parameters during init. Found attributes %s.\"\n % (name, sorted(invalid_attr)))\n # Ensure that each parameter is set in init\n invalid_attr = set(init_params) - set(vars(estimator)) - {\"self\"}\n assert not invalid_attr, (\n \"Estimator %s should store all parameters\"\n \" as an attribute during init. Did not find \"\n \"attributes %s.\"\n % (name, sorted(invalid_attr)))\n\n\n@ignore_warnings(category=(DeprecationWarning, FutureWarning))\ndef check_sparsify_coefficients(name, estimator_orig):\n X = np.array([[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1],\n [-1, -2], [2, 2], [-2, -2]])\n y = [1, 1, 1, 2, 2, 2, 3, 3, 3]\n est = clone(estimator_orig)\n\n est.fit(X, y)\n pred_orig = est.predict(X)\n\n # test sparsify with dense inputs\n est.sparsify()\n assert sparse.issparse(est.coef_)\n pred = est.predict(X)\n assert_array_equal(pred, pred_orig)\n\n # pickle and unpickle with sparse coef_\n est = pickle.loads(pickle.dumps(est))\n assert sparse.issparse(est.coef_)\n pred = est.predict(X)\n assert_array_equal(pred, pred_orig)\n\n\n@ignore_warnings(category=DeprecationWarning)\ndef check_classifier_data_not_an_array(name, estimator_orig):\n X = np.array([[3, 0], [0, 1], [0, 2], [1, 1], [1, 2], [2, 1]])\n X = pairwise_estimator_convert_X(X, estimator_orig)\n y = [1, 1, 1, 2, 2, 2]\n y = multioutput_estimator_convert_y_2d(estimator_orig, y)\n check_estimators_data_not_an_array(name, estimator_orig, X, y)\n\n\n@ignore_warnings(category=DeprecationWarning)\ndef check_regressor_data_not_an_array(name, estimator_orig):\n X, y = _boston_subset(n_samples=50)\n X = pairwise_estimator_convert_X(X, estimator_orig)\n y = multioutput_estimator_convert_y_2d(estimator_orig, y)\n check_estimators_data_not_an_array(name, estimator_orig, X, y)\n\n\n@ignore_warnings(category=(DeprecationWarning, FutureWarning))\ndef check_estimators_data_not_an_array(name, estimator_orig, X, y):\n if name in CROSS_DECOMPOSITION:\n raise SkipTest(\"Skipping check_estimators_data_not_an_array \"\n \"for cross decomposition module as estimators \"\n \"are not deterministic.\")\n # separate estimators to control random seeds\n estimator_1 = clone(estimator_orig)\n estimator_2 = clone(estimator_orig)\n set_random_state(estimator_1)\n set_random_state(estimator_2)\n\n y_ = NotAnArray(np.asarray(y))\n X_ = NotAnArray(np.asarray(X))\n\n # fit\n estimator_1.fit(X_, y_)\n pred1 = estimator_1.predict(X_)\n estimator_2.fit(X, y)\n pred2 = estimator_2.predict(X)\n assert_allclose(pred1, pred2, atol=1e-2, err_msg=name)\n\n\ndef check_parameters_default_constructible(name, Estimator):\n # this check works on classes, not instances\n # test default-constructibility\n # get rid of deprecation warnings\n with ignore_warnings(category=(DeprecationWarning, FutureWarning)):\n required_parameters = getattr(Estimator, \"_required_parameters\", [])\n if required_parameters:\n if required_parameters in ([\"base_estimator\"], [\"estimator\"]):\n if issubclass(Estimator, RegressorMixin):\n estimator = Estimator(Ridge())\n else:\n estimator = Estimator(LinearDiscriminantAnalysis())\n else:\n raise SkipTest(\"Can't instantiate estimator {} which\"\n \" requires parameters {}\".format(\n name, required_parameters))\n else:\n estimator = Estimator()\n # test cloning\n clone(estimator)\n # test __repr__\n repr(estimator)\n # test that set_params returns self\n assert estimator.set_params() is estimator\n\n # test if init does nothing but set parameters\n # this is important for grid_search etc.\n # We get the default parameters from init and then\n # compare these against the actual values of the attributes.\n\n # this comes from getattr. Gets rid of deprecation decorator.\n init = getattr(estimator.__init__, 'deprecated_original',\n estimator.__init__)\n\n try:\n def param_filter(p):\n \"\"\"Identify hyper parameters of an estimator\"\"\"\n return (p.name != 'self' and\n p.kind != p.VAR_KEYWORD and\n p.kind != p.VAR_POSITIONAL)\n\n init_params = [p for p in signature(init).parameters.values()\n if param_filter(p)]\n\n except (TypeError, ValueError):\n # init is not a python function.\n # true for mixins\n return\n params = estimator.get_params()\n if required_parameters == [\"estimator\"]:\n # they can need a non-default argument\n init_params = init_params[1:]\n\n for init_param in init_params:\n assert_not_equal(init_param.default, init_param.empty,\n \"parameter %s for %s has no default value\"\n % (init_param.name, type(estimator).__name__))\n if type(init_param.default) is type:\n assert_in(init_param.default, [np.float64, np.int64])\n else:\n assert_in(type(init_param.default),\n [str, int, float, bool, tuple, type(None),\n np.float64, types.FunctionType, _joblib.Memory])\n if init_param.name not in params.keys():\n # deprecated parameter, not in get_params\n assert init_param.default is None\n continue\n\n param_value = params[init_param.name]\n if isinstance(param_value, np.ndarray):\n assert_array_equal(param_value, init_param.default)\n else:\n if is_scalar_nan(param_value):\n # Allows to set default parameters to np.nan\n assert param_value is init_param.default, init_param.name\n else:\n assert param_value == init_param.default, init_param.name\n\n\ndef multioutput_estimator_convert_y_2d(estimator, y):\n # Estimators in mono_output_task_error raise ValueError if y is of 1-D\n # Convert into a 2-D y for those estimators.\n if _safe_tags(estimator, \"multioutput_only\"):\n return np.reshape(y, (-1, 1))\n return y\n\n\n@ignore_warnings(category=(DeprecationWarning, FutureWarning))\ndef check_non_transformer_estimators_n_iter(name, estimator_orig):\n # Test that estimators that are not transformers with a parameter\n # max_iter, return the attribute of n_iter_ at least 1.\n\n # These models are dependent on external solvers like\n # libsvm and accessing the iter parameter is non-trivial.\n not_run_check_n_iter = ['Ridge', 'SVR', 'NuSVR', 'NuSVC',\n 'RidgeClassifier', 'SVC', 'RandomizedLasso',\n 'LogisticRegressionCV', 'LinearSVC',\n 'LogisticRegression']\n\n # Tested in test_transformer_n_iter\n not_run_check_n_iter += CROSS_DECOMPOSITION\n if name in not_run_check_n_iter:\n return\n\n # LassoLars stops early for the default alpha=1.0 the iris dataset.\n if name == 'LassoLars':\n estimator = clone(estimator_orig).set_params(alpha=0.)\n else:\n estimator = clone(estimator_orig)\n if hasattr(estimator, 'max_iter'):\n iris = load_iris()\n X, y_ = iris.data, iris.target\n y_ = multioutput_estimator_convert_y_2d(estimator, y_)\n\n set_random_state(estimator, 0)\n if name == 'AffinityPropagation':\n estimator.fit(X)\n else:\n estimator.fit(X, y_)\n\n assert estimator.n_iter_ >= 1\n\n\n@ignore_warnings(category=(DeprecationWarning, FutureWarning))\ndef check_transformer_n_iter(name, estimator_orig):\n # Test that transformers with a parameter max_iter, return the\n # attribute of n_iter_ at least 1.\n estimator = clone(estimator_orig)\n if hasattr(estimator, \"max_iter\"):\n if name in CROSS_DECOMPOSITION:\n # Check using default data\n X = [[0., 0., 1.], [1., 0., 0.], [2., 2., 2.], [2., 5., 4.]]\n y_ = [[0.1, -0.2], [0.9, 1.1], [0.1, -0.5], [0.3, -0.2]]\n\n else:\n X, y_ = make_blobs(n_samples=30, centers=[[0, 0, 0], [1, 1, 1]],\n random_state=0, n_features=2, cluster_std=0.1)\n X -= X.min() - 0.1\n set_random_state(estimator, 0)\n estimator.fit(X, y_)\n\n # These return a n_iter per component.\n if name in CROSS_DECOMPOSITION:\n for iter_ in estimator.n_iter_:\n assert_greater_equal(iter_, 1)\n else:\n assert_greater_equal(estimator.n_iter_, 1)\n\n\n@ignore_warnings(category=(DeprecationWarning, FutureWarning))\ndef check_get_params_invariance(name, estimator_orig):\n # Checks if get_params(deep=False) is a subset of get_params(deep=True)\n e = clone(estimator_orig)\n\n shallow_params = e.get_params(deep=False)\n deep_params = e.get_params(deep=True)\n\n assert all(item in deep_params.items() for item in\n shallow_params.items())\n\n\n@ignore_warnings(category=(DeprecationWarning, FutureWarning))\ndef check_set_params(name, estimator_orig):\n # Check that get_params() returns the same thing\n # before and after set_params() with some fuzz\n estimator = clone(estimator_orig)\n\n orig_params = estimator.get_params(deep=False)\n msg = (\"get_params result does not match what was passed to set_params\")\n\n estimator.set_params(**orig_params)\n curr_params = estimator.get_params(deep=False)\n assert_equal(set(orig_params.keys()), set(curr_params.keys()), msg)\n for k, v in curr_params.items():\n assert orig_params[k] is v, msg\n\n # some fuzz values\n test_values = [-np.inf, np.inf, None]\n\n test_params = deepcopy(orig_params)\n for param_name in orig_params.keys():\n default_value = orig_params[param_name]\n for value in test_values:\n test_params[param_name] = value\n try:\n estimator.set_params(**test_params)\n except (TypeError, ValueError) as e:\n e_type = e.__class__.__name__\n # Exception occurred, possibly parameter validation\n warnings.warn(\"{0} occurred during set_params of param {1} on \"\n \"{2}. It is recommended to delay parameter \"\n \"validation until fit.\".format(e_type,\n param_name,\n name))\n\n change_warning_msg = \"Estimator's parameters changed after \" \\\n \"set_params raised {}\".format(e_type)\n params_before_exception = curr_params\n curr_params = estimator.get_params(deep=False)\n try:\n assert_equal(set(params_before_exception.keys()),\n set(curr_params.keys()))\n for k, v in curr_params.items():\n assert params_before_exception[k] is v\n except AssertionError:\n warnings.warn(change_warning_msg)\n else:\n curr_params = estimator.get_params(deep=False)\n assert_equal(set(test_params.keys()),\n set(curr_params.keys()),\n msg)\n for k, v in curr_params.items():\n assert test_params[k] is v, msg\n test_params[param_name] = default_value\n\n\n@ignore_warnings(category=(DeprecationWarning, FutureWarning))\ndef check_classifiers_regression_target(name, estimator_orig):\n # Check if classifier throws an exception when fed regression targets\n\n boston = load_boston()\n X, y = boston.data, boston.target\n e = clone(estimator_orig)\n msg = 'Unknown label type: '\n if not _safe_tags(e, \"no_validation\"):\n assert_raises_regex(ValueError, msg, e.fit, X, y)\n\n\n@ignore_warnings(category=(DeprecationWarning, FutureWarning))\ndef check_decision_proba_consistency(name, estimator_orig):\n # Check whether an estimator having both decision_function and\n # predict_proba methods has outputs with perfect rank correlation.\n\n centers = [(2, 2), (4, 4)]\n X, y = make_blobs(n_samples=100, random_state=0, n_features=4,\n centers=centers, cluster_std=1.0, shuffle=True)\n X_test = np.random.randn(20, 2) + 4\n estimator = clone(estimator_orig)\n\n if (hasattr(estimator, \"decision_function\") and\n hasattr(estimator, \"predict_proba\")):\n\n estimator.fit(X, y)\n a = estimator.predict_proba(X_test)[:, 1]\n b = estimator.decision_function(X_test)\n assert_array_equal(rankdata(a), rankdata(b))\n\n\ndef check_outliers_fit_predict(name, estimator_orig):\n # Check fit_predict for outlier detectors.\n\n n_samples = 300\n X, _ = make_blobs(n_samples=n_samples, random_state=0)\n X = shuffle(X, random_state=7)\n n_samples, n_features = X.shape\n estimator = clone(estimator_orig)\n\n set_random_state(estimator)\n\n y_pred = estimator.fit_predict(X)\n assert y_pred.shape == (n_samples,)\n assert y_pred.dtype.kind == 'i'\n assert_array_equal(np.unique(y_pred), np.array([-1, 1]))\n\n # check fit_predict = fit.predict when the estimator has both a predict and\n # a fit_predict method. recall that it is already assumed here that the\n # estimator has a fit_predict method\n if hasattr(estimator, 'predict'):\n y_pred_2 = estimator.fit(X).predict(X)\n assert_array_equal(y_pred, y_pred_2)\n\n if hasattr(estimator, \"contamination\"):\n # proportion of outliers equal to contamination parameter when not\n # set to 'auto'\n expected_outliers = 30\n contamination = float(expected_outliers)/n_samples\n estimator.set_params(contamination=contamination)\n y_pred = estimator.fit_predict(X)\n\n num_outliers = np.sum(y_pred != 1)\n # num_outliers should be equal to expected_outliers unless\n # there are ties in the decision_function values. this can\n # only be tested for estimators with a decision_function\n # method\n if (num_outliers != expected_outliers and\n hasattr(estimator, 'decision_function')):\n decision = estimator.decision_function(X)\n check_outlier_corruption(num_outliers, expected_outliers, decision)\n\n # raises error when contamination is a scalar and not in [0,1]\n for contamination in [-0.5, 2.3]:\n estimator.set_params(contamination=contamination)\n assert_raises(ValueError, estimator.fit_predict, X)\n\n\ndef check_fit_idempotent(name, estimator_orig):\n # Check that est.fit(X) is the same as est.fit(X).fit(X). Ideally we would\n # check that the estimated parameters during training (e.g. coefs_) are\n # the same, but having a universal comparison function for those\n # attributes is difficult and full of edge cases. So instead we check that\n # predict(), predict_proba(), decision_function() and transform() return\n # the same results.\n\n check_methods = [\"predict\", \"transform\", \"decision_function\",\n \"predict_proba\"]\n rng = np.random.RandomState(0)\n\n estimator = clone(estimator_orig)\n set_random_state(estimator)\n if 'warm_start' in estimator.get_params().keys():\n estimator.set_params(warm_start=False)\n\n n_samples = 100\n X = rng.normal(loc=100, size=(n_samples, 2))\n X = pairwise_estimator_convert_X(X, estimator)\n if is_regressor(estimator_orig):\n y = rng.normal(size=n_samples)\n else:\n y = rng.randint(low=0, high=2, size=n_samples)\n y = multioutput_estimator_convert_y_2d(estimator, y)\n\n train, test = next(ShuffleSplit(test_size=.2, random_state=rng).split(X))\n X_train, y_train = _safe_split(estimator, X, y, train)\n X_test, y_test = _safe_split(estimator, X, y, test, train)\n\n # Fit for the first time\n estimator.fit(X_train, y_train)\n\n result = {method: getattr(estimator, method)(X_test)\n for method in check_methods\n if hasattr(estimator, method)}\n\n # Fit again\n set_random_state(estimator)\n estimator.fit(X_train, y_train)\n\n for method in check_methods:\n if hasattr(estimator, method):\n new_result = getattr(estimator, method)(X_test)\n assert_allclose_dense_sparse(result[method], new_result)\n",
"import numpy as np\nimport pytest\nfrom sklearn.datasets import make_classification, make_regression\n\n# To use this experimental feature, we need to explicitly ask for it:\nfrom sklearn.experimental import enable_hist_gradient_boosting # noqa\nfrom sklearn.ensemble import HistGradientBoostingRegressor\nfrom sklearn.ensemble import HistGradientBoostingClassifier\n\n\nX_classification, y_classification = make_classification(random_state=0)\nX_regression, y_regression = make_regression(random_state=0)\n\n\[email protected]('GradientBoosting, X, y', [\n (HistGradientBoostingClassifier, X_classification, y_classification),\n (HistGradientBoostingRegressor, X_regression, y_regression)\n])\[email protected](\n 'params, err_msg',\n [({'loss': 'blah'}, 'Loss blah is not supported for'),\n ({'learning_rate': 0}, 'learning_rate=0 must be strictly positive'),\n ({'learning_rate': -1}, 'learning_rate=-1 must be strictly positive'),\n ({'max_iter': 0}, 'max_iter=0 must not be smaller than 1'),\n ({'max_leaf_nodes': 0}, 'max_leaf_nodes=0 should not be smaller than 2'),\n ({'max_leaf_nodes': 1}, 'max_leaf_nodes=1 should not be smaller than 2'),\n ({'max_depth': 0}, 'max_depth=0 should not be smaller than 2'),\n ({'max_depth': 1}, 'max_depth=1 should not be smaller than 2'),\n ({'min_samples_leaf': 0}, 'min_samples_leaf=0 should not be smaller'),\n ({'l2_regularization': -1}, 'l2_regularization=-1 must be positive'),\n ({'max_bins': 1}, 'max_bins=1 should be no smaller than 2 and no larger'),\n ({'max_bins': 257}, 'max_bins=257 should be no smaller than 2 and no'),\n ({'n_iter_no_change': -1}, 'n_iter_no_change=-1 must be positive'),\n ({'validation_fraction': -1}, 'validation_fraction=-1 must be strictly'),\n ({'validation_fraction': 0}, 'validation_fraction=0 must be strictly'),\n ({'tol': -1}, 'tol=-1 must not be smaller than 0')]\n)\ndef test_init_parameters_validation(GradientBoosting, X, y, params, err_msg):\n\n with pytest.raises(ValueError, match=err_msg):\n GradientBoosting(**params).fit(X, y)\n\n\ndef test_invalid_classification_loss():\n binary_clf = HistGradientBoostingClassifier(loss=\"binary_crossentropy\")\n err_msg = (\"loss='binary_crossentropy' is not defined for multiclass \"\n \"classification with n_classes=3, use \"\n \"loss='categorical_crossentropy' instead\")\n with pytest.raises(ValueError, match=err_msg):\n binary_clf.fit(np.zeros(shape=(3, 2)), np.arange(3))\n\n\[email protected](\n 'scoring, validation_fraction, n_iter_no_change, tol', [\n ('neg_mean_squared_error', .1, 5, 1e-7), # use scorer\n ('neg_mean_squared_error', None, 5, 1e-1), # use scorer on train data\n (None, .1, 5, 1e-7), # same with default scorer\n (None, None, 5, 1e-1),\n ('loss', .1, 5, 1e-7), # use loss\n ('loss', None, 5, 1e-1), # use loss on training data\n (None, None, None, None), # no early stopping\n ])\ndef test_early_stopping_regression(scoring, validation_fraction,\n n_iter_no_change, tol):\n\n max_iter = 200\n\n X, y = make_regression(random_state=0)\n\n gb = HistGradientBoostingRegressor(\n verbose=1, # just for coverage\n min_samples_leaf=5, # easier to overfit fast\n scoring=scoring,\n tol=tol,\n validation_fraction=validation_fraction,\n max_iter=max_iter,\n n_iter_no_change=n_iter_no_change,\n random_state=0\n )\n gb.fit(X, y)\n\n if n_iter_no_change is not None:\n assert n_iter_no_change <= gb.n_iter_ < max_iter\n else:\n assert gb.n_iter_ == max_iter\n\n\[email protected]('data', (\n make_classification(random_state=0),\n make_classification(n_classes=3, n_clusters_per_class=1, random_state=0)\n))\[email protected](\n 'scoring, validation_fraction, n_iter_no_change, tol', [\n ('accuracy', .1, 5, 1e-7), # use scorer\n ('accuracy', None, 5, 1e-1), # use scorer on training data\n (None, .1, 5, 1e-7), # same with default scorerscor\n (None, None, 5, 1e-1),\n ('loss', .1, 5, 1e-7), # use loss\n ('loss', None, 5, 1e-1), # use loss on training data\n (None, None, None, None), # no early stopping\n ])\ndef test_early_stopping_classification(data, scoring, validation_fraction,\n n_iter_no_change, tol):\n\n max_iter = 50\n\n X, y = data\n\n gb = HistGradientBoostingClassifier(\n verbose=1, # just for coverage\n min_samples_leaf=5, # easier to overfit fast\n scoring=scoring,\n tol=tol,\n validation_fraction=validation_fraction,\n max_iter=max_iter,\n n_iter_no_change=n_iter_no_change,\n random_state=0\n )\n gb.fit(X, y)\n\n if n_iter_no_change is not None:\n assert n_iter_no_change <= gb.n_iter_ < max_iter\n else:\n assert gb.n_iter_ == max_iter\n\n\[email protected](\n 'scores, n_iter_no_change, tol, stopping',\n [\n ([], 1, 0.001, False), # not enough iterations\n ([1, 1, 1], 5, 0.001, False), # not enough iterations\n ([1, 1, 1, 1, 1], 5, 0.001, False), # not enough iterations\n ([1, 2, 3, 4, 5, 6], 5, 0.001, False), # significant improvement\n ([1, 2, 3, 4, 5, 6], 5, 0., False), # significant improvement\n ([1, 2, 3, 4, 5, 6], 5, 0.999, False), # significant improvement\n ([1, 2, 3, 4, 5, 6], 5, 5 - 1e-5, False), # significant improvement\n ([1] * 6, 5, 0., True), # no significant improvement\n ([1] * 6, 5, 0.001, True), # no significant improvement\n ([1] * 6, 5, 5, True), # no significant improvement\n ]\n)\ndef test_should_stop(scores, n_iter_no_change, tol, stopping):\n\n gbdt = HistGradientBoostingClassifier(\n n_iter_no_change=n_iter_no_change, tol=tol\n )\n assert gbdt._should_stop(scores) == stopping\n",
"from __future__ import division, absolute_import, print_function\n\nimport sys\nimport os\nimport re\nimport functools\nimport itertools\nimport warnings\nimport weakref\nfrom operator import itemgetter, index as opindex\n\nimport numpy as np\nfrom . import format\nfrom ._datasource import DataSource\nfrom numpy.core import overrides\nfrom numpy.core.multiarray import packbits, unpackbits\nfrom numpy.core.overrides import set_module\nfrom numpy.core._internal import recursive\nfrom ._iotools import (\n LineSplitter, NameValidator, StringConverter, ConverterError,\n ConverterLockError, ConversionWarning, _is_string_like,\n has_nested_fields, flatten_dtype, easy_dtype, _decode_line\n )\n\nfrom numpy.compat import (\n asbytes, asstr, asunicode, asbytes_nested, bytes, basestring, unicode,\n os_fspath, os_PathLike\n )\nfrom numpy.core.numeric import pickle\n\nif sys.version_info[0] >= 3:\n from collections.abc import Mapping\nelse:\n from future_builtins import map\n from collections import Mapping\n\n\n@set_module('numpy')\ndef loads(*args, **kwargs):\n # NumPy 1.15.0, 2017-12-10\n warnings.warn(\n \"np.loads is deprecated, use pickle.loads instead\",\n DeprecationWarning, stacklevel=2)\n return pickle.loads(*args, **kwargs)\n\n\n__all__ = [\n 'savetxt', 'loadtxt', 'genfromtxt', 'ndfromtxt', 'mafromtxt',\n 'recfromtxt', 'recfromcsv', 'load', 'loads', 'save', 'savez',\n 'savez_compressed', 'packbits', 'unpackbits', 'fromregex', 'DataSource'\n ]\n\n\narray_function_dispatch = functools.partial(\n overrides.array_function_dispatch, module='numpy')\n\n\nclass BagObj(object):\n \"\"\"\n BagObj(obj)\n\n Convert attribute look-ups to getitems on the object passed in.\n\n Parameters\n ----------\n obj : class instance\n Object on which attribute look-up is performed.\n\n Examples\n --------\n >>> from numpy.lib.npyio import BagObj as BO\n >>> class BagDemo(object):\n ... def __getitem__(self, key): # An instance of BagObj(BagDemo)\n ... # will call this method when any\n ... # attribute look-up is required\n ... result = \"Doesn't matter what you want, \"\n ... return result + \"you're gonna get this\"\n ...\n >>> demo_obj = BagDemo()\n >>> bagobj = BO(demo_obj)\n >>> bagobj.hello_there\n \"Doesn't matter what you want, you're gonna get this\"\n >>> bagobj.I_can_be_anything\n \"Doesn't matter what you want, you're gonna get this\"\n\n \"\"\"\n\n def __init__(self, obj):\n # Use weakref to make NpzFile objects collectable by refcount\n self._obj = weakref.proxy(obj)\n\n def __getattribute__(self, key):\n try:\n return object.__getattribute__(self, '_obj')[key]\n except KeyError:\n raise AttributeError(key)\n\n def __dir__(self):\n \"\"\"\n Enables dir(bagobj) to list the files in an NpzFile.\n\n This also enables tab-completion in an interpreter or IPython.\n \"\"\"\n return list(object.__getattribute__(self, '_obj').keys())\n\n\ndef zipfile_factory(file, *args, **kwargs):\n \"\"\"\n Create a ZipFile.\n\n Allows for Zip64, and the `file` argument can accept file, str, or\n pathlib.Path objects. `args` and `kwargs` are passed to the zipfile.ZipFile\n constructor.\n \"\"\"\n if not hasattr(file, 'read'):\n file = os_fspath(file)\n import zipfile\n kwargs['allowZip64'] = True\n return zipfile.ZipFile(file, *args, **kwargs)\n\n\nclass NpzFile(Mapping):\n \"\"\"\n NpzFile(fid)\n\n A dictionary-like object with lazy-loading of files in the zipped\n archive provided on construction.\n\n `NpzFile` is used to load files in the NumPy ``.npz`` data archive\n format. It assumes that files in the archive have a ``.npy`` extension,\n other files are ignored.\n\n The arrays and file strings are lazily loaded on either\n getitem access using ``obj['key']`` or attribute lookup using\n ``obj.f.key``. A list of all files (without ``.npy`` extensions) can\n be obtained with ``obj.files`` and the ZipFile object itself using\n ``obj.zip``.\n\n Attributes\n ----------\n files : list of str\n List of all files in the archive with a ``.npy`` extension.\n zip : ZipFile instance\n The ZipFile object initialized with the zipped archive.\n f : BagObj instance\n An object on which attribute can be performed as an alternative\n to getitem access on the `NpzFile` instance itself.\n allow_pickle : bool, optional\n Allow loading pickled data. Default: False\n\n .. versionchanged:: 1.16.3\n Made default False in response to CVE-2019-6446.\n\n pickle_kwargs : dict, optional\n Additional keyword arguments to pass on to pickle.load.\n These are only useful when loading object arrays saved on\n Python 2 when using Python 3.\n\n Parameters\n ----------\n fid : file or str\n The zipped archive to open. This is either a file-like object\n or a string containing the path to the archive.\n own_fid : bool, optional\n Whether NpzFile should close the file handle.\n Requires that `fid` is a file-like object.\n\n Examples\n --------\n >>> from tempfile import TemporaryFile\n >>> outfile = TemporaryFile()\n >>> x = np.arange(10)\n >>> y = np.sin(x)\n >>> np.savez(outfile, x=x, y=y)\n >>> outfile.seek(0)\n\n >>> npz = np.load(outfile)\n >>> isinstance(npz, np.lib.io.NpzFile)\n True\n >>> npz.files\n ['y', 'x']\n >>> npz['x'] # getitem access\n array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\n >>> npz.f.x # attribute lookup\n array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\n\n \"\"\"\n\n def __init__(self, fid, own_fid=False, allow_pickle=False,\n pickle_kwargs=None):\n # Import is postponed to here since zipfile depends on gzip, an\n # optional component of the so-called standard library.\n _zip = zipfile_factory(fid)\n self._files = _zip.namelist()\n self.files = []\n self.allow_pickle = allow_pickle\n self.pickle_kwargs = pickle_kwargs\n for x in self._files:\n if x.endswith('.npy'):\n self.files.append(x[:-4])\n else:\n self.files.append(x)\n self.zip = _zip\n self.f = BagObj(self)\n if own_fid:\n self.fid = fid\n else:\n self.fid = None\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n self.close()\n\n def close(self):\n \"\"\"\n Close the file.\n\n \"\"\"\n if self.zip is not None:\n self.zip.close()\n self.zip = None\n if self.fid is not None:\n self.fid.close()\n self.fid = None\n self.f = None # break reference cycle\n\n def __del__(self):\n self.close()\n\n # Implement the Mapping ABC\n def __iter__(self):\n return iter(self.files)\n\n def __len__(self):\n return len(self.files)\n\n def __getitem__(self, key):\n # FIXME: This seems like it will copy strings around\n # more than is strictly necessary. The zipfile\n # will read the string and then\n # the format.read_array will copy the string\n # to another place in memory.\n # It would be better if the zipfile could read\n # (or at least uncompress) the data\n # directly into the array memory.\n member = False\n if key in self._files:\n member = True\n elif key in self.files:\n member = True\n key += '.npy'\n if member:\n bytes = self.zip.open(key)\n magic = bytes.read(len(format.MAGIC_PREFIX))\n bytes.close()\n if magic == format.MAGIC_PREFIX:\n bytes = self.zip.open(key)\n return format.read_array(bytes,\n allow_pickle=self.allow_pickle,\n pickle_kwargs=self.pickle_kwargs)\n else:\n return self.zip.read(key)\n else:\n raise KeyError(\"%s is not a file in the archive\" % key)\n\n\n if sys.version_info.major == 3:\n # deprecate the python 2 dict apis that we supported by accident in\n # python 3. We forgot to implement itervalues() at all in earlier\n # versions of numpy, so no need to deprecated it here.\n\n def iteritems(self):\n # Numpy 1.15, 2018-02-20\n warnings.warn(\n \"NpzFile.iteritems is deprecated in python 3, to match the \"\n \"removal of dict.itertems. Use .items() instead.\",\n DeprecationWarning, stacklevel=2)\n return self.items()\n\n def iterkeys(self):\n # Numpy 1.15, 2018-02-20\n warnings.warn(\n \"NpzFile.iterkeys is deprecated in python 3, to match the \"\n \"removal of dict.iterkeys. Use .keys() instead.\",\n DeprecationWarning, stacklevel=2)\n return self.keys()\n\n\n@set_module('numpy')\ndef load(file, mmap_mode=None, allow_pickle=False, fix_imports=True,\n encoding='ASCII'):\n \"\"\"\n Load arrays or pickled objects from ``.npy``, ``.npz`` or pickled files.\n\n Parameters\n ----------\n file : file-like object, string, or pathlib.Path\n The file to read. File-like objects must support the\n ``seek()`` and ``read()`` methods. Pickled files require that the\n file-like object support the ``readline()`` method as well.\n mmap_mode : {None, 'r+', 'r', 'w+', 'c'}, optional\n If not None, then memory-map the file, using the given mode (see\n `numpy.memmap` for a detailed description of the modes). A\n memory-mapped array is kept on disk. However, it can be accessed\n and sliced like any ndarray. Memory mapping is especially useful\n for accessing small fragments of large files without reading the\n entire file into memory.\n allow_pickle : bool, optional\n Allow loading pickled object arrays stored in npy files. Reasons for\n disallowing pickles include security, as loading pickled data can\n execute arbitrary code. If pickles are disallowed, loading object\n arrays will fail. Default: False\n\n .. versionchanged:: 1.16.3\n Made default False in response to CVE-2019-6446.\n\n fix_imports : bool, optional\n Only useful when loading Python 2 generated pickled files on Python 3,\n which includes npy/npz files containing object arrays. If `fix_imports`\n is True, pickle will try to map the old Python 2 names to the new names\n used in Python 3.\n encoding : str, optional\n What encoding to use when reading Python 2 strings. Only useful when\n loading Python 2 generated pickled files in Python 3, which includes\n npy/npz files containing object arrays. Values other than 'latin1',\n 'ASCII', and 'bytes' are not allowed, as they can corrupt numerical\n data. Default: 'ASCII'\n\n Returns\n -------\n result : array, tuple, dict, etc.\n Data stored in the file. For ``.npz`` files, the returned instance\n of NpzFile class must be closed to avoid leaking file descriptors.\n\n Raises\n ------\n IOError\n If the input file does not exist or cannot be read.\n ValueError\n The file contains an object array, but allow_pickle=False given.\n\n See Also\n --------\n save, savez, savez_compressed, loadtxt\n memmap : Create a memory-map to an array stored in a file on disk.\n lib.format.open_memmap : Create or load a memory-mapped ``.npy`` file.\n\n Notes\n -----\n - If the file contains pickle data, then whatever object is stored\n in the pickle is returned.\n - If the file is a ``.npy`` file, then a single array is returned.\n - If the file is a ``.npz`` file, then a dictionary-like object is\n returned, containing ``{filename: array}`` key-value pairs, one for\n each file in the archive.\n - If the file is a ``.npz`` file, the returned value supports the\n context manager protocol in a similar fashion to the open function::\n\n with load('foo.npz') as data:\n a = data['a']\n\n The underlying file descriptor is closed when exiting the 'with'\n block.\n\n Examples\n --------\n Store data to disk, and load it again:\n\n >>> np.save('/tmp/123', np.array([[1, 2, 3], [4, 5, 6]]))\n >>> np.load('/tmp/123.npy')\n array([[1, 2, 3],\n [4, 5, 6]])\n\n Store compressed data to disk, and load it again:\n\n >>> a=np.array([[1, 2, 3], [4, 5, 6]])\n >>> b=np.array([1, 2])\n >>> np.savez('/tmp/123.npz', a=a, b=b)\n >>> data = np.load('/tmp/123.npz')\n >>> data['a']\n array([[1, 2, 3],\n [4, 5, 6]])\n >>> data['b']\n array([1, 2])\n >>> data.close()\n\n Mem-map the stored array, and then access the second row\n directly from disk:\n\n >>> X = np.load('/tmp/123.npy', mmap_mode='r')\n >>> X[1, :]\n memmap([4, 5, 6])\n\n \"\"\"\n if encoding not in ('ASCII', 'latin1', 'bytes'):\n # The 'encoding' value for pickle also affects what encoding\n # the serialized binary data of NumPy arrays is loaded\n # in. Pickle does not pass on the encoding information to\n # NumPy. The unpickling code in numpy.core.multiarray is\n # written to assume that unicode data appearing where binary\n # should be is in 'latin1'. 'bytes' is also safe, as is 'ASCII'.\n #\n # Other encoding values can corrupt binary data, and we\n # purposefully disallow them. For the same reason, the errors=\n # argument is not exposed, as values other than 'strict'\n # result can similarly silently corrupt numerical data.\n raise ValueError(\"encoding must be 'ASCII', 'latin1', or 'bytes'\")\n\n if sys.version_info[0] >= 3:\n pickle_kwargs = dict(encoding=encoding, fix_imports=fix_imports)\n else:\n # Nothing to do on Python 2\n pickle_kwargs = {}\n\n # TODO: Use contextlib.ExitStack once we drop Python 2\n if hasattr(file, 'read'):\n fid = file\n own_fid = False\n else:\n fid = open(os_fspath(file), \"rb\")\n own_fid = True\n\n try:\n # Code to distinguish from NumPy binary files and pickles.\n _ZIP_PREFIX = b'PK\\x03\\x04'\n _ZIP_SUFFIX = b'PK\\x05\\x06' # empty zip files start with this\n N = len(format.MAGIC_PREFIX)\n magic = fid.read(N)\n # If the file size is less than N, we need to make sure not\n # to seek past the beginning of the file\n fid.seek(-min(N, len(magic)), 1) # back-up\n if magic.startswith(_ZIP_PREFIX) or magic.startswith(_ZIP_SUFFIX):\n # zip-file (assume .npz)\n # Transfer file ownership to NpzFile\n ret = NpzFile(fid, own_fid=own_fid, allow_pickle=allow_pickle,\n pickle_kwargs=pickle_kwargs)\n own_fid = False\n return ret\n elif magic == format.MAGIC_PREFIX:\n # .npy file\n if mmap_mode:\n return format.open_memmap(file, mode=mmap_mode)\n else:\n return format.read_array(fid, allow_pickle=allow_pickle,\n pickle_kwargs=pickle_kwargs)\n else:\n # Try a pickle\n if not allow_pickle:\n raise ValueError(\"Cannot load file containing pickled data \"\n \"when allow_pickle=False\")\n try:\n return pickle.load(fid, **pickle_kwargs)\n except Exception:\n raise IOError(\n \"Failed to interpret file %s as a pickle\" % repr(file))\n finally:\n if own_fid:\n fid.close()\n\n\ndef _save_dispatcher(file, arr, allow_pickle=None, fix_imports=None):\n return (arr,)\n\n\n@array_function_dispatch(_save_dispatcher)\ndef save(file, arr, allow_pickle=True, fix_imports=True):\n \"\"\"\n Save an array to a binary file in NumPy ``.npy`` format.\n\n Parameters\n ----------\n file : file, str, or pathlib.Path\n File or filename to which the data is saved. If file is a file-object,\n then the filename is unchanged. If file is a string or Path, a ``.npy``\n extension will be appended to the file name if it does not already\n have one.\n arr : array_like\n Array data to be saved.\n allow_pickle : bool, optional\n Allow saving object arrays using Python pickles. Reasons for disallowing\n pickles include security (loading pickled data can execute arbitrary\n code) and portability (pickled objects may not be loadable on different\n Python installations, for example if the stored objects require libraries\n that are not available, and not all pickled data is compatible between\n Python 2 and Python 3).\n Default: True\n fix_imports : bool, optional\n Only useful in forcing objects in object arrays on Python 3 to be\n pickled in a Python 2 compatible way. If `fix_imports` is True, pickle\n will try to map the new Python 3 names to the old module names used in\n Python 2, so that the pickle data stream is readable with Python 2.\n\n See Also\n --------\n savez : Save several arrays into a ``.npz`` archive\n savetxt, load\n\n Notes\n -----\n For a description of the ``.npy`` format, see :py:mod:`numpy.lib.format`.\n\n Examples\n --------\n >>> from tempfile import TemporaryFile\n >>> outfile = TemporaryFile()\n\n >>> x = np.arange(10)\n >>> np.save(outfile, x)\n\n >>> outfile.seek(0) # Only needed here to simulate closing & reopening file\n >>> np.load(outfile)\n array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\n\n \"\"\"\n own_fid = False\n if hasattr(file, 'read'):\n fid = file\n else:\n file = os_fspath(file)\n if not file.endswith('.npy'):\n file = file + '.npy'\n fid = open(file, \"wb\")\n own_fid = True\n\n if sys.version_info[0] >= 3:\n pickle_kwargs = dict(fix_imports=fix_imports)\n else:\n # Nothing to do on Python 2\n pickle_kwargs = None\n\n try:\n arr = np.asanyarray(arr)\n format.write_array(fid, arr, allow_pickle=allow_pickle,\n pickle_kwargs=pickle_kwargs)\n finally:\n if own_fid:\n fid.close()\n\n\ndef _savez_dispatcher(file, *args, **kwds):\n for a in args:\n yield a\n for v in kwds.values():\n yield v\n\n\n@array_function_dispatch(_savez_dispatcher)\ndef savez(file, *args, **kwds):\n \"\"\"\n Save several arrays into a single file in uncompressed ``.npz`` format.\n\n If arguments are passed in with no keywords, the corresponding variable\n names, in the ``.npz`` file, are 'arr_0', 'arr_1', etc. If keyword\n arguments are given, the corresponding variable names, in the ``.npz``\n file will match the keyword names.\n\n Parameters\n ----------\n file : str or file\n Either the file name (string) or an open file (file-like object)\n where the data will be saved. If file is a string or a Path, the\n ``.npz`` extension will be appended to the file name if it is not\n already there.\n args : Arguments, optional\n Arrays to save to the file. Since it is not possible for Python to\n know the names of the arrays outside `savez`, the arrays will be saved\n with names \"arr_0\", \"arr_1\", and so on. These arguments can be any\n expression.\n kwds : Keyword arguments, optional\n Arrays to save to the file. Arrays will be saved in the file with the\n keyword names.\n\n Returns\n -------\n None\n\n See Also\n --------\n save : Save a single array to a binary file in NumPy format.\n savetxt : Save an array to a file as plain text.\n savez_compressed : Save several arrays into a compressed ``.npz`` archive\n\n Notes\n -----\n The ``.npz`` file format is a zipped archive of files named after the\n variables they contain. The archive is not compressed and each file\n in the archive contains one variable in ``.npy`` format. For a\n description of the ``.npy`` format, see :py:mod:`numpy.lib.format`.\n\n When opening the saved ``.npz`` file with `load` a `NpzFile` object is\n returned. This is a dictionary-like object which can be queried for\n its list of arrays (with the ``.files`` attribute), and for the arrays\n themselves.\n\n Examples\n --------\n >>> from tempfile import TemporaryFile\n >>> outfile = TemporaryFile()\n >>> x = np.arange(10)\n >>> y = np.sin(x)\n\n Using `savez` with \\\\*args, the arrays are saved with default names.\n\n >>> np.savez(outfile, x, y)\n >>> outfile.seek(0) # Only needed here to simulate closing & reopening file\n >>> npzfile = np.load(outfile)\n >>> npzfile.files\n ['arr_1', 'arr_0']\n >>> npzfile['arr_0']\n array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\n\n Using `savez` with \\\\**kwds, the arrays are saved with the keyword names.\n\n >>> outfile = TemporaryFile()\n >>> np.savez(outfile, x=x, y=y)\n >>> outfile.seek(0)\n >>> npzfile = np.load(outfile)\n >>> npzfile.files\n ['y', 'x']\n >>> npzfile['x']\n array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\n\n \"\"\"\n _savez(file, args, kwds, False)\n\n\ndef _savez_compressed_dispatcher(file, *args, **kwds):\n for a in args:\n yield a\n for v in kwds.values():\n yield v\n\n\n@array_function_dispatch(_savez_compressed_dispatcher)\ndef savez_compressed(file, *args, **kwds):\n \"\"\"\n Save several arrays into a single file in compressed ``.npz`` format.\n\n If keyword arguments are given, then filenames are taken from the keywords.\n If arguments are passed in with no keywords, then stored file names are\n arr_0, arr_1, etc.\n\n Parameters\n ----------\n file : str or file\n Either the file name (string) or an open file (file-like object)\n where the data will be saved. If file is a string or a Path, the\n ``.npz`` extension will be appended to the file name if it is not\n already there.\n args : Arguments, optional\n Arrays to save to the file. Since it is not possible for Python to\n know the names of the arrays outside `savez`, the arrays will be saved\n with names \"arr_0\", \"arr_1\", and so on. These arguments can be any\n expression.\n kwds : Keyword arguments, optional\n Arrays to save to the file. Arrays will be saved in the file with the\n keyword names.\n\n Returns\n -------\n None\n\n See Also\n --------\n numpy.save : Save a single array to a binary file in NumPy format.\n numpy.savetxt : Save an array to a file as plain text.\n numpy.savez : Save several arrays into an uncompressed ``.npz`` file format\n numpy.load : Load the files created by savez_compressed.\n\n Notes\n -----\n The ``.npz`` file format is a zipped archive of files named after the\n variables they contain. The archive is compressed with\n ``zipfile.ZIP_DEFLATED`` and each file in the archive contains one variable\n in ``.npy`` format. For a description of the ``.npy`` format, see \n :py:mod:`numpy.lib.format`.\n\n\n When opening the saved ``.npz`` file with `load` a `NpzFile` object is\n returned. This is a dictionary-like object which can be queried for\n its list of arrays (with the ``.files`` attribute), and for the arrays\n themselves.\n\n Examples\n --------\n >>> test_array = np.random.rand(3, 2)\n >>> test_vector = np.random.rand(4)\n >>> np.savez_compressed('/tmp/123', a=test_array, b=test_vector)\n >>> loaded = np.load('/tmp/123.npz')\n >>> print(np.array_equal(test_array, loaded['a']))\n True\n >>> print(np.array_equal(test_vector, loaded['b']))\n True\n\n \"\"\"\n _savez(file, args, kwds, True)\n\n\ndef _savez(file, args, kwds, compress, allow_pickle=True, pickle_kwargs=None):\n # Import is postponed to here since zipfile depends on gzip, an optional\n # component of the so-called standard library.\n import zipfile\n\n if not hasattr(file, 'read'):\n file = os_fspath(file)\n if not file.endswith('.npz'):\n file = file + '.npz'\n\n namedict = kwds\n for i, val in enumerate(args):\n key = 'arr_%d' % i\n if key in namedict.keys():\n raise ValueError(\n \"Cannot use un-named variables and keyword %s\" % key)\n namedict[key] = val\n\n if compress:\n compression = zipfile.ZIP_DEFLATED\n else:\n compression = zipfile.ZIP_STORED\n\n zipf = zipfile_factory(file, mode=\"w\", compression=compression)\n\n if sys.version_info >= (3, 6):\n # Since Python 3.6 it is possible to write directly to a ZIP file.\n for key, val in namedict.items():\n fname = key + '.npy'\n val = np.asanyarray(val)\n force_zip64 = val.nbytes >= 2**30\n with zipf.open(fname, 'w', force_zip64=force_zip64) as fid:\n format.write_array(fid, val,\n allow_pickle=allow_pickle,\n pickle_kwargs=pickle_kwargs)\n else:\n # Stage arrays in a temporary file on disk, before writing to zip.\n\n # Import deferred for startup time improvement\n import tempfile\n # Since target file might be big enough to exceed capacity of a global\n # temporary directory, create temp file side-by-side with the target file.\n file_dir, file_prefix = os.path.split(file) if _is_string_like(file) else (None, 'tmp')\n fd, tmpfile = tempfile.mkstemp(prefix=file_prefix, dir=file_dir, suffix='-numpy.npy')\n os.close(fd)\n try:\n for key, val in namedict.items():\n fname = key + '.npy'\n fid = open(tmpfile, 'wb')\n try:\n format.write_array(fid, np.asanyarray(val),\n allow_pickle=allow_pickle,\n pickle_kwargs=pickle_kwargs)\n fid.close()\n fid = None\n zipf.write(tmpfile, arcname=fname)\n except IOError as exc:\n raise IOError(\"Failed to write to %s: %s\" % (tmpfile, exc))\n finally:\n if fid:\n fid.close()\n finally:\n os.remove(tmpfile)\n\n zipf.close()\n\n\ndef _getconv(dtype):\n \"\"\" Find the correct dtype converter. Adapted from matplotlib \"\"\"\n\n def floatconv(x):\n x.lower()\n if '0x' in x:\n return float.fromhex(x)\n return float(x)\n\n typ = dtype.type\n if issubclass(typ, np.bool_):\n return lambda x: bool(int(x))\n if issubclass(typ, np.uint64):\n return np.uint64\n if issubclass(typ, np.int64):\n return np.int64\n if issubclass(typ, np.integer):\n return lambda x: int(float(x))\n elif issubclass(typ, np.longdouble):\n return np.longdouble\n elif issubclass(typ, np.floating):\n return floatconv\n elif issubclass(typ, complex):\n return lambda x: complex(asstr(x).replace('+-', '-'))\n elif issubclass(typ, np.bytes_):\n return asbytes\n elif issubclass(typ, np.unicode_):\n return asunicode\n else:\n return asstr\n\n# amount of lines loadtxt reads in one chunk, can be overridden for testing\n_loadtxt_chunksize = 50000\n\n\n@set_module('numpy')\ndef loadtxt(fname, dtype=float, comments='#', delimiter=None,\n converters=None, skiprows=0, usecols=None, unpack=False,\n ndmin=0, encoding='bytes', max_rows=None):\n \"\"\"\n Load data from a text file.\n\n Each row in the text file must have the same number of values.\n\n Parameters\n ----------\n fname : file, str, or pathlib.Path\n File, filename, or generator to read. If the filename extension is\n ``.gz`` or ``.bz2``, the file is first decompressed. Note that\n generators should return byte strings for Python 3k.\n dtype : data-type, optional\n Data-type of the resulting array; default: float. If this is a\n structured data-type, the resulting array will be 1-dimensional, and\n each row will be interpreted as an element of the array. In this\n case, the number of columns used must match the number of fields in\n the data-type.\n comments : str or sequence of str, optional\n The characters or list of characters used to indicate the start of a\n comment. None implies no comments. For backwards compatibility, byte\n strings will be decoded as 'latin1'. The default is '#'.\n delimiter : str, optional\n The string used to separate values. For backwards compatibility, byte\n strings will be decoded as 'latin1'. The default is whitespace.\n converters : dict, optional\n A dictionary mapping column number to a function that will parse the\n column string into the desired value. E.g., if column 0 is a date\n string: ``converters = {0: datestr2num}``. Converters can also be\n used to provide a default value for missing data (but see also\n `genfromtxt`): ``converters = {3: lambda s: float(s.strip() or 0)}``.\n Default: None.\n skiprows : int, optional\n Skip the first `skiprows` lines; default: 0.\n usecols : int or sequence, optional\n Which columns to read, with 0 being the first. For example,\n ``usecols = (1,4,5)`` will extract the 2nd, 5th and 6th columns.\n The default, None, results in all columns being read.\n\n .. versionchanged:: 1.11.0\n When a single column has to be read it is possible to use\n an integer instead of a tuple. E.g ``usecols = 3`` reads the\n fourth column the same way as ``usecols = (3,)`` would.\n unpack : bool, optional\n If True, the returned array is transposed, so that arguments may be\n unpacked using ``x, y, z = loadtxt(...)``. When used with a structured\n data-type, arrays are returned for each field. Default is False.\n ndmin : int, optional\n The returned array will have at least `ndmin` dimensions.\n Otherwise mono-dimensional axes will be squeezed.\n Legal values: 0 (default), 1 or 2.\n\n .. versionadded:: 1.6.0\n encoding : str, optional\n Encoding used to decode the inputfile. Does not apply to input streams.\n The special value 'bytes' enables backward compatibility workarounds\n that ensures you receive byte arrays as results if possible and passes\n 'latin1' encoded strings to converters. Override this value to receive\n unicode arrays and pass strings as input to converters. If set to None\n the system default is used. The default value is 'bytes'.\n\n .. versionadded:: 1.14.0\n max_rows : int, optional\n Read `max_rows` lines of content after `skiprows` lines. The default\n is to read all the lines.\n\n .. versionadded:: 1.16.0\n\n Returns\n -------\n out : ndarray\n Data read from the text file.\n\n See Also\n --------\n load, fromstring, fromregex\n genfromtxt : Load data with missing values handled as specified.\n scipy.io.loadmat : reads MATLAB data files\n\n Notes\n -----\n This function aims to be a fast reader for simply formatted files. The\n `genfromtxt` function provides more sophisticated handling of, e.g.,\n lines with missing values.\n\n .. versionadded:: 1.10.0\n\n The strings produced by the Python float.hex method can be used as\n input for floats.\n\n Examples\n --------\n >>> from io import StringIO # StringIO behaves like a file object\n >>> c = StringIO(u\"0 1\\\\n2 3\")\n >>> np.loadtxt(c)\n array([[ 0., 1.],\n [ 2., 3.]])\n\n >>> d = StringIO(u\"M 21 72\\\\nF 35 58\")\n >>> np.loadtxt(d, dtype={'names': ('gender', 'age', 'weight'),\n ... 'formats': ('S1', 'i4', 'f4')})\n array([('M', 21, 72.0), ('F', 35, 58.0)],\n dtype=[('gender', '|S1'), ('age', '<i4'), ('weight', '<f4')])\n\n >>> c = StringIO(u\"1,0,2\\\\n3,0,4\")\n >>> x, y = np.loadtxt(c, delimiter=',', usecols=(0, 2), unpack=True)\n >>> x\n array([ 1., 3.])\n >>> y\n array([ 2., 4.])\n\n \"\"\"\n # Type conversions for Py3 convenience\n if comments is not None:\n if isinstance(comments, (basestring, bytes)):\n comments = [comments]\n comments = [_decode_line(x) for x in comments]\n # Compile regex for comments beforehand\n comments = (re.escape(comment) for comment in comments)\n regex_comments = re.compile('|'.join(comments))\n\n if delimiter is not None:\n delimiter = _decode_line(delimiter)\n\n user_converters = converters\n\n if encoding == 'bytes':\n encoding = None\n byte_converters = True\n else:\n byte_converters = False\n\n if usecols is not None:\n # Allow usecols to be a single int or a sequence of ints\n try:\n usecols_as_list = list(usecols)\n except TypeError:\n usecols_as_list = [usecols]\n for col_idx in usecols_as_list:\n try:\n opindex(col_idx)\n except TypeError as e:\n e.args = (\n \"usecols must be an int or a sequence of ints but \"\n \"it contains at least one element of type %s\" %\n type(col_idx),\n )\n raise\n # Fall back to existing code\n usecols = usecols_as_list\n\n fown = False\n try:\n if isinstance(fname, os_PathLike):\n fname = os_fspath(fname)\n if _is_string_like(fname):\n fh = np.lib._datasource.open(fname, 'rt', encoding=encoding)\n fencoding = getattr(fh, 'encoding', 'latin1')\n fh = iter(fh)\n fown = True\n else:\n fh = iter(fname)\n fencoding = getattr(fname, 'encoding', 'latin1')\n except TypeError:\n raise ValueError('fname must be a string, file handle, or generator')\n\n # input may be a python2 io stream\n if encoding is not None:\n fencoding = encoding\n # we must assume local encoding\n # TODO emit portability warning?\n elif fencoding is None:\n import locale\n fencoding = locale.getpreferredencoding()\n\n # not to be confused with the flatten_dtype we import...\n @recursive\n def flatten_dtype_internal(self, dt):\n \"\"\"Unpack a structured data-type, and produce re-packing info.\"\"\"\n if dt.names is None:\n # If the dtype is flattened, return.\n # If the dtype has a shape, the dtype occurs\n # in the list more than once.\n shape = dt.shape\n if len(shape) == 0:\n return ([dt.base], None)\n else:\n packing = [(shape[-1], list)]\n if len(shape) > 1:\n for dim in dt.shape[-2::-1]:\n packing = [(dim*packing[0][0], packing*dim)]\n return ([dt.base] * int(np.prod(dt.shape)), packing)\n else:\n types = []\n packing = []\n for field in dt.names:\n tp, bytes = dt.fields[field]\n flat_dt, flat_packing = self(tp)\n types.extend(flat_dt)\n # Avoid extra nesting for subarrays\n if tp.ndim > 0:\n packing.extend(flat_packing)\n else:\n packing.append((len(flat_dt), flat_packing))\n return (types, packing)\n\n @recursive\n def pack_items(self, items, packing):\n \"\"\"Pack items into nested lists based on re-packing info.\"\"\"\n if packing is None:\n return items[0]\n elif packing is tuple:\n return tuple(items)\n elif packing is list:\n return list(items)\n else:\n start = 0\n ret = []\n for length, subpacking in packing:\n ret.append(self(items[start:start+length], subpacking))\n start += length\n return tuple(ret)\n\n def split_line(line):\n \"\"\"Chop off comments, strip, and split at delimiter. \"\"\"\n line = _decode_line(line, encoding=encoding)\n\n if comments is not None:\n line = regex_comments.split(line, maxsplit=1)[0]\n line = line.strip('\\r\\n')\n if line:\n return line.split(delimiter)\n else:\n return []\n\n def read_data(chunk_size):\n \"\"\"Parse each line, including the first.\n\n The file read, `fh`, is a global defined above.\n\n Parameters\n ----------\n chunk_size : int\n At most `chunk_size` lines are read at a time, with iteration\n until all lines are read.\n\n \"\"\"\n X = []\n line_iter = itertools.chain([first_line], fh)\n line_iter = itertools.islice(line_iter, max_rows)\n for i, line in enumerate(line_iter):\n vals = split_line(line)\n if len(vals) == 0:\n continue\n if usecols:\n vals = [vals[j] for j in usecols]\n if len(vals) != N:\n line_num = i + skiprows + 1\n raise ValueError(\"Wrong number of columns at line %d\"\n % line_num)\n\n # Convert each value according to its column and store\n items = [conv(val) for (conv, val) in zip(converters, vals)]\n\n # Then pack it according to the dtype's nesting\n items = pack_items(items, packing)\n X.append(items)\n if len(X) > chunk_size:\n yield X\n X = []\n if X:\n yield X\n\n try:\n # Make sure we're dealing with a proper dtype\n dtype = np.dtype(dtype)\n defconv = _getconv(dtype)\n\n # Skip the first `skiprows` lines\n for i in range(skiprows):\n next(fh)\n\n # Read until we find a line with some values, and use\n # it to estimate the number of columns, N.\n first_vals = None\n try:\n while not first_vals:\n first_line = next(fh)\n first_vals = split_line(first_line)\n except StopIteration:\n # End of lines reached\n first_line = ''\n first_vals = []\n warnings.warn('loadtxt: Empty input file: \"%s\"' % fname, stacklevel=2)\n N = len(usecols or first_vals)\n\n dtype_types, packing = flatten_dtype_internal(dtype)\n if len(dtype_types) > 1:\n # We're dealing with a structured array, each field of\n # the dtype matches a column\n converters = [_getconv(dt) for dt in dtype_types]\n else:\n # All fields have the same dtype\n converters = [defconv for i in range(N)]\n if N > 1:\n packing = [(N, tuple)]\n\n # By preference, use the converters specified by the user\n for i, conv in (user_converters or {}).items():\n if usecols:\n try:\n i = usecols.index(i)\n except ValueError:\n # Unused converter specified\n continue\n if byte_converters:\n # converters may use decode to workaround numpy's old behaviour,\n # so encode the string again before passing to the user converter\n def tobytes_first(x, conv):\n if type(x) is bytes:\n return conv(x)\n return conv(x.encode(\"latin1\"))\n import functools\n converters[i] = functools.partial(tobytes_first, conv=conv)\n else:\n converters[i] = conv\n\n converters = [conv if conv is not bytes else\n lambda x: x.encode(fencoding) for conv in converters]\n\n # read data in chunks and fill it into an array via resize\n # over-allocating and shrinking the array later may be faster but is\n # probably not relevant compared to the cost of actually reading and\n # converting the data\n X = None\n for x in read_data(_loadtxt_chunksize):\n if X is None:\n X = np.array(x, dtype)\n else:\n nshape = list(X.shape)\n pos = nshape[0]\n nshape[0] += len(x)\n X.resize(nshape, refcheck=False)\n X[pos:, ...] = x\n finally:\n if fown:\n fh.close()\n\n if X is None:\n X = np.array([], dtype)\n\n # Multicolumn data are returned with shape (1, N, M), i.e.\n # (1, 1, M) for a single row - remove the singleton dimension there\n if X.ndim == 3 and X.shape[:2] == (1, 1):\n X.shape = (1, -1)\n\n # Verify that the array has at least dimensions `ndmin`.\n # Check correctness of the values of `ndmin`\n if ndmin not in [0, 1, 2]:\n raise ValueError('Illegal value of ndmin keyword: %s' % ndmin)\n # Tweak the size and shape of the arrays - remove extraneous dimensions\n if X.ndim > ndmin:\n X = np.squeeze(X)\n # and ensure we have the minimum number of dimensions asked for\n # - has to be in this order for the odd case ndmin=1, X.squeeze().ndim=0\n if X.ndim < ndmin:\n if ndmin == 1:\n X = np.atleast_1d(X)\n elif ndmin == 2:\n X = np.atleast_2d(X).T\n\n if unpack:\n if len(dtype_types) > 1:\n # For structured arrays, return an array for each field.\n return [X[field] for field in dtype.names]\n else:\n return X.T\n else:\n return X\n\n\ndef _savetxt_dispatcher(fname, X, fmt=None, delimiter=None, newline=None,\n header=None, footer=None, comments=None,\n encoding=None):\n return (X,)\n\n\n@array_function_dispatch(_savetxt_dispatcher)\ndef savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\\n', header='',\n footer='', comments='# ', encoding=None):\n \"\"\"\n Save an array to a text file.\n\n Parameters\n ----------\n fname : filename or file handle\n If the filename ends in ``.gz``, the file is automatically saved in\n compressed gzip format. `loadtxt` understands gzipped files\n transparently.\n X : 1D or 2D array_like\n Data to be saved to a text file.\n fmt : str or sequence of strs, optional\n A single format (%10.5f), a sequence of formats, or a\n multi-format string, e.g. 'Iteration %d -- %10.5f', in which\n case `delimiter` is ignored. For complex `X`, the legal options\n for `fmt` are:\n\n * a single specifier, `fmt='%.4e'`, resulting in numbers formatted\n like `' (%s+%sj)' % (fmt, fmt)`\n * a full string specifying every real and imaginary part, e.g.\n `' %.4e %+.4ej %.4e %+.4ej %.4e %+.4ej'` for 3 columns\n * a list of specifiers, one per column - in this case, the real\n and imaginary part must have separate specifiers,\n e.g. `['%.3e + %.3ej', '(%.15e%+.15ej)']` for 2 columns\n delimiter : str, optional\n String or character separating columns.\n newline : str, optional\n String or character separating lines.\n\n .. versionadded:: 1.5.0\n header : str, optional\n String that will be written at the beginning of the file.\n\n .. versionadded:: 1.7.0\n footer : str, optional\n String that will be written at the end of the file.\n\n .. versionadded:: 1.7.0\n comments : str, optional\n String that will be prepended to the ``header`` and ``footer`` strings,\n to mark them as comments. Default: '# ', as expected by e.g.\n ``numpy.loadtxt``.\n\n .. versionadded:: 1.7.0\n encoding : {None, str}, optional\n Encoding used to encode the outputfile. Does not apply to output\n streams. If the encoding is something other than 'bytes' or 'latin1'\n you will not be able to load the file in NumPy versions < 1.14. Default\n is 'latin1'.\n\n .. versionadded:: 1.14.0\n\n\n See Also\n --------\n save : Save an array to a binary file in NumPy ``.npy`` format\n savez : Save several arrays into an uncompressed ``.npz`` archive\n savez_compressed : Save several arrays into a compressed ``.npz`` archive\n\n Notes\n -----\n Further explanation of the `fmt` parameter\n (``%[flag]width[.precision]specifier``):\n\n flags:\n ``-`` : left justify\n\n ``+`` : Forces to precede result with + or -.\n\n ``0`` : Left pad the number with zeros instead of space (see width).\n\n width:\n Minimum number of characters to be printed. The value is not truncated\n if it has more characters.\n\n precision:\n - For integer specifiers (eg. ``d,i,o,x``), the minimum number of\n digits.\n - For ``e, E`` and ``f`` specifiers, the number of digits to print\n after the decimal point.\n - For ``g`` and ``G``, the maximum number of significant digits.\n - For ``s``, the maximum number of characters.\n\n specifiers:\n ``c`` : character\n\n ``d`` or ``i`` : signed decimal integer\n\n ``e`` or ``E`` : scientific notation with ``e`` or ``E``.\n\n ``f`` : decimal floating point\n\n ``g,G`` : use the shorter of ``e,E`` or ``f``\n\n ``o`` : signed octal\n\n ``s`` : string of characters\n\n ``u`` : unsigned decimal integer\n\n ``x,X`` : unsigned hexadecimal integer\n\n This explanation of ``fmt`` is not complete, for an exhaustive\n specification see [1]_.\n\n References\n ----------\n .. [1] `Format Specification Mini-Language\n <https://docs.python.org/library/string.html#format-specification-mini-language>`_,\n Python Documentation.\n\n Examples\n --------\n >>> x = y = z = np.arange(0.0,5.0,1.0)\n >>> np.savetxt('test.out', x, delimiter=',') # X is an array\n >>> np.savetxt('test.out', (x,y,z)) # x,y,z equal sized 1D arrays\n >>> np.savetxt('test.out', x, fmt='%1.4e') # use exponential notation\n\n \"\"\"\n\n # Py3 conversions first\n if isinstance(fmt, bytes):\n fmt = asstr(fmt)\n delimiter = asstr(delimiter)\n\n class WriteWrap(object):\n \"\"\"Convert to unicode in py2 or to bytes on bytestream inputs.\n\n \"\"\"\n def __init__(self, fh, encoding):\n self.fh = fh\n self.encoding = encoding\n self.do_write = self.first_write\n\n def close(self):\n self.fh.close()\n\n def write(self, v):\n self.do_write(v)\n\n def write_bytes(self, v):\n if isinstance(v, bytes):\n self.fh.write(v)\n else:\n self.fh.write(v.encode(self.encoding))\n\n def write_normal(self, v):\n self.fh.write(asunicode(v))\n\n def first_write(self, v):\n try:\n self.write_normal(v)\n self.write = self.write_normal\n except TypeError:\n # input is probably a bytestream\n self.write_bytes(v)\n self.write = self.write_bytes\n\n own_fh = False\n if isinstance(fname, os_PathLike):\n fname = os_fspath(fname)\n if _is_string_like(fname):\n # datasource doesn't support creating a new file ...\n open(fname, 'wt').close()\n fh = np.lib._datasource.open(fname, 'wt', encoding=encoding)\n own_fh = True\n # need to convert str to unicode for text io output\n if sys.version_info[0] == 2:\n fh = WriteWrap(fh, encoding or 'latin1')\n elif hasattr(fname, 'write'):\n # wrap to handle byte output streams\n fh = WriteWrap(fname, encoding or 'latin1')\n else:\n raise ValueError('fname must be a string or file handle')\n\n try:\n X = np.asarray(X)\n\n # Handle 1-dimensional arrays\n if X.ndim == 0 or X.ndim > 2:\n raise ValueError(\n \"Expected 1D or 2D array, got %dD array instead\" % X.ndim)\n elif X.ndim == 1:\n # Common case -- 1d array of numbers\n if X.dtype.names is None:\n X = np.atleast_2d(X).T\n ncol = 1\n\n # Complex dtype -- each field indicates a separate column\n else:\n ncol = len(X.dtype.names)\n else:\n ncol = X.shape[1]\n\n iscomplex_X = np.iscomplexobj(X)\n # `fmt` can be a string with multiple insertion points or a\n # list of formats. E.g. '%10.5f\\t%10d' or ('%10.5f', '$10d')\n if type(fmt) in (list, tuple):\n if len(fmt) != ncol:\n raise AttributeError('fmt has wrong shape. %s' % str(fmt))\n format = asstr(delimiter).join(map(asstr, fmt))\n elif isinstance(fmt, str):\n n_fmt_chars = fmt.count('%')\n error = ValueError('fmt has wrong number of %% formats: %s' % fmt)\n if n_fmt_chars == 1:\n if iscomplex_X:\n fmt = [' (%s+%sj)' % (fmt, fmt), ] * ncol\n else:\n fmt = [fmt, ] * ncol\n format = delimiter.join(fmt)\n elif iscomplex_X and n_fmt_chars != (2 * ncol):\n raise error\n elif ((not iscomplex_X) and n_fmt_chars != ncol):\n raise error\n else:\n format = fmt\n else:\n raise ValueError('invalid fmt: %r' % (fmt,))\n\n if len(header) > 0:\n header = header.replace('\\n', '\\n' + comments)\n fh.write(comments + header + newline)\n if iscomplex_X:\n for row in X:\n row2 = []\n for number in row:\n row2.append(number.real)\n row2.append(number.imag)\n s = format % tuple(row2) + newline\n fh.write(s.replace('+-', '-'))\n else:\n for row in X:\n try:\n v = format % tuple(row) + newline\n except TypeError:\n raise TypeError(\"Mismatch between array dtype ('%s') and \"\n \"format specifier ('%s')\"\n % (str(X.dtype), format))\n fh.write(v)\n\n if len(footer) > 0:\n footer = footer.replace('\\n', '\\n' + comments)\n fh.write(comments + footer + newline)\n finally:\n if own_fh:\n fh.close()\n\n\n@set_module('numpy')\ndef fromregex(file, regexp, dtype, encoding=None):\n \"\"\"\n Construct an array from a text file, using regular expression parsing.\n\n The returned array is always a structured array, and is constructed from\n all matches of the regular expression in the file. Groups in the regular\n expression are converted to fields of the structured array.\n\n Parameters\n ----------\n file : str or file\n File name or file object to read.\n regexp : str or regexp\n Regular expression used to parse the file.\n Groups in the regular expression correspond to fields in the dtype.\n dtype : dtype or list of dtypes\n Dtype for the structured array.\n encoding : str, optional\n Encoding used to decode the inputfile. Does not apply to input streams.\n\n .. versionadded:: 1.14.0\n\n Returns\n -------\n output : ndarray\n The output array, containing the part of the content of `file` that\n was matched by `regexp`. `output` is always a structured array.\n\n Raises\n ------\n TypeError\n When `dtype` is not a valid dtype for a structured array.\n\n See Also\n --------\n fromstring, loadtxt\n\n Notes\n -----\n Dtypes for structured arrays can be specified in several forms, but all\n forms specify at least the data type and field name. For details see\n `doc.structured_arrays`.\n\n Examples\n --------\n >>> f = open('test.dat', 'w')\n >>> f.write(\"1312 foo\\\\n1534 bar\\\\n444 qux\")\n >>> f.close()\n\n >>> regexp = r\"(\\\\d+)\\\\s+(...)\" # match [digits, whitespace, anything]\n >>> output = np.fromregex('test.dat', regexp,\n ... [('num', np.int64), ('key', 'S3')])\n >>> output\n array([(1312L, 'foo'), (1534L, 'bar'), (444L, 'qux')],\n dtype=[('num', '<i8'), ('key', '|S3')])\n >>> output['num']\n array([1312, 1534, 444], dtype=int64)\n\n \"\"\"\n own_fh = False\n if not hasattr(file, \"read\"):\n file = np.lib._datasource.open(file, 'rt', encoding=encoding)\n own_fh = True\n\n try:\n if not isinstance(dtype, np.dtype):\n dtype = np.dtype(dtype)\n\n content = file.read()\n if isinstance(content, bytes) and isinstance(regexp, np.unicode):\n regexp = asbytes(regexp)\n elif isinstance(content, np.unicode) and isinstance(regexp, bytes):\n regexp = asstr(regexp)\n\n if not hasattr(regexp, 'match'):\n regexp = re.compile(regexp)\n seq = regexp.findall(content)\n if seq and not isinstance(seq[0], tuple):\n # Only one group is in the regexp.\n # Create the new array as a single data-type and then\n # re-interpret as a single-field structured array.\n newdtype = np.dtype(dtype[dtype.names[0]])\n output = np.array(seq, dtype=newdtype)\n output.dtype = dtype\n else:\n output = np.array(seq, dtype=dtype)\n\n return output\n finally:\n if own_fh:\n file.close()\n\n\n#####--------------------------------------------------------------------------\n#---- --- ASCII functions ---\n#####--------------------------------------------------------------------------\n\n\n@set_module('numpy')\ndef genfromtxt(fname, dtype=float, comments='#', delimiter=None,\n skip_header=0, skip_footer=0, converters=None,\n missing_values=None, filling_values=None, usecols=None,\n names=None, excludelist=None, deletechars=None,\n replace_space='_', autostrip=False, case_sensitive=True,\n defaultfmt=\"f%i\", unpack=None, usemask=False, loose=True,\n invalid_raise=True, max_rows=None, encoding='bytes'):\n \"\"\"\n Load data from a text file, with missing values handled as specified.\n\n Each line past the first `skip_header` lines is split at the `delimiter`\n character, and characters following the `comments` character are discarded.\n\n Parameters\n ----------\n fname : file, str, pathlib.Path, list of str, generator\n File, filename, list, or generator to read. If the filename\n extension is `.gz` or `.bz2`, the file is first decompressed. Note\n that generators must return byte strings in Python 3k. The strings\n in a list or produced by a generator are treated as lines.\n dtype : dtype, optional\n Data type of the resulting array.\n If None, the dtypes will be determined by the contents of each\n column, individually.\n comments : str, optional\n The character used to indicate the start of a comment.\n All the characters occurring on a line after a comment are discarded\n delimiter : str, int, or sequence, optional\n The string used to separate values. By default, any consecutive\n whitespaces act as delimiter. An integer or sequence of integers\n can also be provided as width(s) of each field.\n skiprows : int, optional\n `skiprows` was removed in numpy 1.10. Please use `skip_header` instead.\n skip_header : int, optional\n The number of lines to skip at the beginning of the file.\n skip_footer : int, optional\n The number of lines to skip at the end of the file.\n converters : variable, optional\n The set of functions that convert the data of a column to a value.\n The converters can also be used to provide a default value\n for missing data: ``converters = {3: lambda s: float(s or 0)}``.\n missing : variable, optional\n `missing` was removed in numpy 1.10. Please use `missing_values`\n instead.\n missing_values : variable, optional\n The set of strings corresponding to missing data.\n filling_values : variable, optional\n The set of values to be used as default when the data are missing.\n usecols : sequence, optional\n Which columns to read, with 0 being the first. For example,\n ``usecols = (1, 4, 5)`` will extract the 2nd, 5th and 6th columns.\n names : {None, True, str, sequence}, optional\n If `names` is True, the field names are read from the first line after\n the first `skip_header` lines. This line can optionally be proceeded\n by a comment delimiter. If `names` is a sequence or a single-string of\n comma-separated names, the names will be used to define the field names\n in a structured dtype. If `names` is None, the names of the dtype\n fields will be used, if any.\n excludelist : sequence, optional\n A list of names to exclude. This list is appended to the default list\n ['return','file','print']. Excluded names are appended an underscore:\n for example, `file` would become `file_`.\n deletechars : str, optional\n A string combining invalid characters that must be deleted from the\n names.\n defaultfmt : str, optional\n A format used to define default field names, such as \"f%i\" or \"f_%02i\".\n autostrip : bool, optional\n Whether to automatically strip white spaces from the variables.\n replace_space : char, optional\n Character(s) used in replacement of white spaces in the variables\n names. By default, use a '_'.\n case_sensitive : {True, False, 'upper', 'lower'}, optional\n If True, field names are case sensitive.\n If False or 'upper', field names are converted to upper case.\n If 'lower', field names are converted to lower case.\n unpack : bool, optional\n If True, the returned array is transposed, so that arguments may be\n unpacked using ``x, y, z = loadtxt(...)``\n usemask : bool, optional\n If True, return a masked array.\n If False, return a regular array.\n loose : bool, optional\n If True, do not raise errors for invalid values.\n invalid_raise : bool, optional\n If True, an exception is raised if an inconsistency is detected in the\n number of columns.\n If False, a warning is emitted and the offending lines are skipped.\n max_rows : int, optional\n The maximum number of rows to read. Must not be used with skip_footer\n at the same time. If given, the value must be at least 1. Default is\n to read the entire file.\n\n .. versionadded:: 1.10.0\n encoding : str, optional\n Encoding used to decode the inputfile. Does not apply when `fname` is\n a file object. The special value 'bytes' enables backward compatibility\n workarounds that ensure that you receive byte arrays when possible\n and passes latin1 encoded strings to converters. Override this value to\n receive unicode arrays and pass strings as input to converters. If set\n to None the system default is used. The default value is 'bytes'.\n\n .. versionadded:: 1.14.0\n\n Returns\n -------\n out : ndarray\n Data read from the text file. If `usemask` is True, this is a\n masked array.\n\n See Also\n --------\n numpy.loadtxt : equivalent function when no data is missing.\n\n Notes\n -----\n * When spaces are used as delimiters, or when no delimiter has been given\n as input, there should not be any missing data between two fields.\n * When the variables are named (either by a flexible dtype or with `names`,\n there must not be any header in the file (else a ValueError\n exception is raised).\n * Individual values are not stripped of spaces by default.\n When using a custom converter, make sure the function does remove spaces.\n\n References\n ----------\n .. [1] NumPy User Guide, section `I/O with NumPy\n <https://docs.scipy.org/doc/numpy/user/basics.io.genfromtxt.html>`_.\n\n Examples\n ---------\n >>> from io import StringIO\n >>> import numpy as np\n\n Comma delimited file with mixed dtype\n\n >>> s = StringIO(u\"1,1.3,abcde\")\n >>> data = np.genfromtxt(s, dtype=[('myint','i8'),('myfloat','f8'),\n ... ('mystring','S5')], delimiter=\",\")\n >>> data\n array((1, 1.3, 'abcde'),\n dtype=[('myint', '<i8'), ('myfloat', '<f8'), ('mystring', '|S5')])\n\n Using dtype = None\n\n >>> s.seek(0) # needed for StringIO example only\n >>> data = np.genfromtxt(s, dtype=None,\n ... names = ['myint','myfloat','mystring'], delimiter=\",\")\n >>> data\n array((1, 1.3, 'abcde'),\n dtype=[('myint', '<i8'), ('myfloat', '<f8'), ('mystring', '|S5')])\n\n Specifying dtype and names\n\n >>> s.seek(0)\n >>> data = np.genfromtxt(s, dtype=\"i8,f8,S5\",\n ... names=['myint','myfloat','mystring'], delimiter=\",\")\n >>> data\n array((1, 1.3, 'abcde'),\n dtype=[('myint', '<i8'), ('myfloat', '<f8'), ('mystring', '|S5')])\n\n An example with fixed-width columns\n\n >>> s = StringIO(u\"11.3abcde\")\n >>> data = np.genfromtxt(s, dtype=None, names=['intvar','fltvar','strvar'],\n ... delimiter=[1,3,5])\n >>> data\n array((1, 1.3, 'abcde'),\n dtype=[('intvar', '<i8'), ('fltvar', '<f8'), ('strvar', '|S5')])\n\n \"\"\"\n if max_rows is not None:\n if skip_footer:\n raise ValueError(\n \"The keywords 'skip_footer' and 'max_rows' can not be \"\n \"specified at the same time.\")\n if max_rows < 1:\n raise ValueError(\"'max_rows' must be at least 1.\")\n\n if usemask:\n from numpy.ma import MaskedArray, make_mask_descr\n # Check the input dictionary of converters\n user_converters = converters or {}\n if not isinstance(user_converters, dict):\n raise TypeError(\n \"The input argument 'converter' should be a valid dictionary \"\n \"(got '%s' instead)\" % type(user_converters))\n\n if encoding == 'bytes':\n encoding = None\n byte_converters = True\n else:\n byte_converters = False\n\n # Initialize the filehandle, the LineSplitter and the NameValidator\n own_fhd = False\n try:\n if isinstance(fname, os_PathLike):\n fname = os_fspath(fname)\n if isinstance(fname, basestring):\n fhd = iter(np.lib._datasource.open(fname, 'rt', encoding=encoding))\n own_fhd = True\n else:\n fhd = iter(fname)\n except TypeError:\n raise TypeError(\n \"fname must be a string, filehandle, list of strings, \"\n \"or generator. Got %s instead.\" % type(fname))\n\n split_line = LineSplitter(delimiter=delimiter, comments=comments,\n autostrip=autostrip, encoding=encoding)\n validate_names = NameValidator(excludelist=excludelist,\n deletechars=deletechars,\n case_sensitive=case_sensitive,\n replace_space=replace_space)\n\n # Skip the first `skip_header` rows\n for i in range(skip_header):\n next(fhd)\n\n # Keep on until we find the first valid values\n first_values = None\n try:\n while not first_values:\n first_line = _decode_line(next(fhd), encoding)\n if (names is True) and (comments is not None):\n if comments in first_line:\n first_line = (\n ''.join(first_line.split(comments)[1:]))\n first_values = split_line(first_line)\n except StopIteration:\n # return an empty array if the datafile is empty\n first_line = ''\n first_values = []\n warnings.warn('genfromtxt: Empty input file: \"%s\"' % fname, stacklevel=2)\n\n # Should we take the first values as names ?\n if names is True:\n fval = first_values[0].strip()\n if comments is not None:\n if fval in comments:\n del first_values[0]\n\n # Check the columns to use: make sure `usecols` is a list\n if usecols is not None:\n try:\n usecols = [_.strip() for _ in usecols.split(\",\")]\n except AttributeError:\n try:\n usecols = list(usecols)\n except TypeError:\n usecols = [usecols, ]\n nbcols = len(usecols or first_values)\n\n # Check the names and overwrite the dtype.names if needed\n if names is True:\n names = validate_names([str(_.strip()) for _ in first_values])\n first_line = ''\n elif _is_string_like(names):\n names = validate_names([_.strip() for _ in names.split(',')])\n elif names:\n names = validate_names(names)\n # Get the dtype\n if dtype is not None:\n dtype = easy_dtype(dtype, defaultfmt=defaultfmt, names=names,\n excludelist=excludelist,\n deletechars=deletechars,\n case_sensitive=case_sensitive,\n replace_space=replace_space)\n # Make sure the names is a list (for 2.5)\n if names is not None:\n names = list(names)\n\n if usecols:\n for (i, current) in enumerate(usecols):\n # if usecols is a list of names, convert to a list of indices\n if _is_string_like(current):\n usecols[i] = names.index(current)\n elif current < 0:\n usecols[i] = current + len(first_values)\n # If the dtype is not None, make sure we update it\n if (dtype is not None) and (len(dtype) > nbcols):\n descr = dtype.descr\n dtype = np.dtype([descr[_] for _ in usecols])\n names = list(dtype.names)\n # If `names` is not None, update the names\n elif (names is not None) and (len(names) > nbcols):\n names = [names[_] for _ in usecols]\n elif (names is not None) and (dtype is not None):\n names = list(dtype.names)\n\n # Process the missing values ...............................\n # Rename missing_values for convenience\n user_missing_values = missing_values or ()\n if isinstance(user_missing_values, bytes):\n user_missing_values = user_missing_values.decode('latin1')\n\n # Define the list of missing_values (one column: one list)\n missing_values = [list(['']) for _ in range(nbcols)]\n\n # We have a dictionary: process it field by field\n if isinstance(user_missing_values, dict):\n # Loop on the items\n for (key, val) in user_missing_values.items():\n # Is the key a string ?\n if _is_string_like(key):\n try:\n # Transform it into an integer\n key = names.index(key)\n except ValueError:\n # We couldn't find it: the name must have been dropped\n continue\n # Redefine the key as needed if it's a column number\n if usecols:\n try:\n key = usecols.index(key)\n except ValueError:\n pass\n # Transform the value as a list of string\n if isinstance(val, (list, tuple)):\n val = [str(_) for _ in val]\n else:\n val = [str(val), ]\n # Add the value(s) to the current list of missing\n if key is None:\n # None acts as default\n for miss in missing_values:\n miss.extend(val)\n else:\n missing_values[key].extend(val)\n # We have a sequence : each item matches a column\n elif isinstance(user_missing_values, (list, tuple)):\n for (value, entry) in zip(user_missing_values, missing_values):\n value = str(value)\n if value not in entry:\n entry.append(value)\n # We have a string : apply it to all entries\n elif isinstance(user_missing_values, basestring):\n user_value = user_missing_values.split(\",\")\n for entry in missing_values:\n entry.extend(user_value)\n # We have something else: apply it to all entries\n else:\n for entry in missing_values:\n entry.extend([str(user_missing_values)])\n\n # Process the filling_values ...............................\n # Rename the input for convenience\n user_filling_values = filling_values\n if user_filling_values is None:\n user_filling_values = []\n # Define the default\n filling_values = [None] * nbcols\n # We have a dictionary : update each entry individually\n if isinstance(user_filling_values, dict):\n for (key, val) in user_filling_values.items():\n if _is_string_like(key):\n try:\n # Transform it into an integer\n key = names.index(key)\n except ValueError:\n # We couldn't find it: the name must have been dropped,\n continue\n # Redefine the key if it's a column number and usecols is defined\n if usecols:\n try:\n key = usecols.index(key)\n except ValueError:\n pass\n # Add the value to the list\n filling_values[key] = val\n # We have a sequence : update on a one-to-one basis\n elif isinstance(user_filling_values, (list, tuple)):\n n = len(user_filling_values)\n if (n <= nbcols):\n filling_values[:n] = user_filling_values\n else:\n filling_values = user_filling_values[:nbcols]\n # We have something else : use it for all entries\n else:\n filling_values = [user_filling_values] * nbcols\n\n # Initialize the converters ................................\n if dtype is None:\n # Note: we can't use a [...]*nbcols, as we would have 3 times the same\n # ... converter, instead of 3 different converters.\n converters = [StringConverter(None, missing_values=miss, default=fill)\n for (miss, fill) in zip(missing_values, filling_values)]\n else:\n dtype_flat = flatten_dtype(dtype, flatten_base=True)\n # Initialize the converters\n if len(dtype_flat) > 1:\n # Flexible type : get a converter from each dtype\n zipit = zip(dtype_flat, missing_values, filling_values)\n converters = [StringConverter(dt, locked=True,\n missing_values=miss, default=fill)\n for (dt, miss, fill) in zipit]\n else:\n # Set to a default converter (but w/ different missing values)\n zipit = zip(missing_values, filling_values)\n converters = [StringConverter(dtype, locked=True,\n missing_values=miss, default=fill)\n for (miss, fill) in zipit]\n # Update the converters to use the user-defined ones\n uc_update = []\n for (j, conv) in user_converters.items():\n # If the converter is specified by column names, use the index instead\n if _is_string_like(j):\n try:\n j = names.index(j)\n i = j\n except ValueError:\n continue\n elif usecols:\n try:\n i = usecols.index(j)\n except ValueError:\n # Unused converter specified\n continue\n else:\n i = j\n # Find the value to test - first_line is not filtered by usecols:\n if len(first_line):\n testing_value = first_values[j]\n else:\n testing_value = None\n if conv is bytes:\n user_conv = asbytes\n elif byte_converters:\n # converters may use decode to workaround numpy's old behaviour,\n # so encode the string again before passing to the user converter\n def tobytes_first(x, conv):\n if type(x) is bytes:\n return conv(x)\n return conv(x.encode(\"latin1\"))\n import functools\n user_conv = functools.partial(tobytes_first, conv=conv)\n else:\n user_conv = conv\n converters[i].update(user_conv, locked=True,\n testing_value=testing_value,\n default=filling_values[i],\n missing_values=missing_values[i],)\n uc_update.append((i, user_conv))\n # Make sure we have the corrected keys in user_converters...\n user_converters.update(uc_update)\n\n # Fixme: possible error as following variable never used.\n # miss_chars = [_.missing_values for _ in converters]\n\n # Initialize the output lists ...\n # ... rows\n rows = []\n append_to_rows = rows.append\n # ... masks\n if usemask:\n masks = []\n append_to_masks = masks.append\n # ... invalid\n invalid = []\n append_to_invalid = invalid.append\n\n # Parse each line\n for (i, line) in enumerate(itertools.chain([first_line, ], fhd)):\n values = split_line(line)\n nbvalues = len(values)\n # Skip an empty line\n if nbvalues == 0:\n continue\n if usecols:\n # Select only the columns we need\n try:\n values = [values[_] for _ in usecols]\n except IndexError:\n append_to_invalid((i + skip_header + 1, nbvalues))\n continue\n elif nbvalues != nbcols:\n append_to_invalid((i + skip_header + 1, nbvalues))\n continue\n # Store the values\n append_to_rows(tuple(values))\n if usemask:\n append_to_masks(tuple([v.strip() in m\n for (v, m) in zip(values,\n missing_values)]))\n if len(rows) == max_rows:\n break\n\n if own_fhd:\n fhd.close()\n\n # Upgrade the converters (if needed)\n if dtype is None:\n for (i, converter) in enumerate(converters):\n current_column = [itemgetter(i)(_m) for _m in rows]\n try:\n converter.iterupgrade(current_column)\n except ConverterLockError:\n errmsg = \"Converter #%i is locked and cannot be upgraded: \" % i\n current_column = map(itemgetter(i), rows)\n for (j, value) in enumerate(current_column):\n try:\n converter.upgrade(value)\n except (ConverterError, ValueError):\n errmsg += \"(occurred line #%i for value '%s')\"\n errmsg %= (j + 1 + skip_header, value)\n raise ConverterError(errmsg)\n\n # Check that we don't have invalid values\n nbinvalid = len(invalid)\n if nbinvalid > 0:\n nbrows = len(rows) + nbinvalid - skip_footer\n # Construct the error message\n template = \" Line #%%i (got %%i columns instead of %i)\" % nbcols\n if skip_footer > 0:\n nbinvalid_skipped = len([_ for _ in invalid\n if _[0] > nbrows + skip_header])\n invalid = invalid[:nbinvalid - nbinvalid_skipped]\n skip_footer -= nbinvalid_skipped\n#\n# nbrows -= skip_footer\n# errmsg = [template % (i, nb)\n# for (i, nb) in invalid if i < nbrows]\n# else:\n errmsg = [template % (i, nb)\n for (i, nb) in invalid]\n if len(errmsg):\n errmsg.insert(0, \"Some errors were detected !\")\n errmsg = \"\\n\".join(errmsg)\n # Raise an exception ?\n if invalid_raise:\n raise ValueError(errmsg)\n # Issue a warning ?\n else:\n warnings.warn(errmsg, ConversionWarning, stacklevel=2)\n\n # Strip the last skip_footer data\n if skip_footer > 0:\n rows = rows[:-skip_footer]\n if usemask:\n masks = masks[:-skip_footer]\n\n # Convert each value according to the converter:\n # We want to modify the list in place to avoid creating a new one...\n if loose:\n rows = list(\n zip(*[[conv._loose_call(_r) for _r in map(itemgetter(i), rows)]\n for (i, conv) in enumerate(converters)]))\n else:\n rows = list(\n zip(*[[conv._strict_call(_r) for _r in map(itemgetter(i), rows)]\n for (i, conv) in enumerate(converters)]))\n\n # Reset the dtype\n data = rows\n if dtype is None:\n # Get the dtypes from the types of the converters\n column_types = [conv.type for conv in converters]\n # Find the columns with strings...\n strcolidx = [i for (i, v) in enumerate(column_types)\n if v == np.unicode_]\n\n if byte_converters and strcolidx:\n # convert strings back to bytes for backward compatibility\n warnings.warn(\n \"Reading unicode strings without specifying the encoding \"\n \"argument is deprecated. Set the encoding, use None for the \"\n \"system default.\",\n np.VisibleDeprecationWarning, stacklevel=2)\n def encode_unicode_cols(row_tup):\n row = list(row_tup)\n for i in strcolidx:\n row[i] = row[i].encode('latin1')\n return tuple(row)\n\n try:\n data = [encode_unicode_cols(r) for r in data]\n except UnicodeEncodeError:\n pass\n else:\n for i in strcolidx:\n column_types[i] = np.bytes_\n\n # Update string types to be the right length\n sized_column_types = column_types[:]\n for i, col_type in enumerate(column_types):\n if np.issubdtype(col_type, np.character):\n n_chars = max(len(row[i]) for row in data)\n sized_column_types[i] = (col_type, n_chars)\n\n if names is None:\n # If the dtype is uniform (before sizing strings)\n base = {\n c_type\n for c, c_type in zip(converters, column_types)\n if c._checked}\n if len(base) == 1:\n uniform_type, = base\n (ddtype, mdtype) = (uniform_type, bool)\n else:\n ddtype = [(defaultfmt % i, dt)\n for (i, dt) in enumerate(sized_column_types)]\n if usemask:\n mdtype = [(defaultfmt % i, bool)\n for (i, dt) in enumerate(sized_column_types)]\n else:\n ddtype = list(zip(names, sized_column_types))\n mdtype = list(zip(names, [bool] * len(sized_column_types)))\n output = np.array(data, dtype=ddtype)\n if usemask:\n outputmask = np.array(masks, dtype=mdtype)\n else:\n # Overwrite the initial dtype names if needed\n if names and dtype.names:\n dtype.names = names\n # Case 1. We have a structured type\n if len(dtype_flat) > 1:\n # Nested dtype, eg [('a', int), ('b', [('b0', int), ('b1', 'f4')])]\n # First, create the array using a flattened dtype:\n # [('a', int), ('b1', int), ('b2', float)]\n # Then, view the array using the specified dtype.\n if 'O' in (_.char for _ in dtype_flat):\n if has_nested_fields(dtype):\n raise NotImplementedError(\n \"Nested fields involving objects are not supported...\")\n else:\n output = np.array(data, dtype=dtype)\n else:\n rows = np.array(data, dtype=[('', _) for _ in dtype_flat])\n output = rows.view(dtype)\n # Now, process the rowmasks the same way\n if usemask:\n rowmasks = np.array(\n masks, dtype=np.dtype([('', bool) for t in dtype_flat]))\n # Construct the new dtype\n mdtype = make_mask_descr(dtype)\n outputmask = rowmasks.view(mdtype)\n # Case #2. We have a basic dtype\n else:\n # We used some user-defined converters\n if user_converters:\n ishomogeneous = True\n descr = []\n for i, ttype in enumerate([conv.type for conv in converters]):\n # Keep the dtype of the current converter\n if i in user_converters:\n ishomogeneous &= (ttype == dtype.type)\n if np.issubdtype(ttype, np.character):\n ttype = (ttype, max(len(row[i]) for row in data))\n descr.append(('', ttype))\n else:\n descr.append(('', dtype))\n # So we changed the dtype ?\n if not ishomogeneous:\n # We have more than one field\n if len(descr) > 1:\n dtype = np.dtype(descr)\n # We have only one field: drop the name if not needed.\n else:\n dtype = np.dtype(ttype)\n #\n output = np.array(data, dtype)\n if usemask:\n if dtype.names:\n mdtype = [(_, bool) for _ in dtype.names]\n else:\n mdtype = bool\n outputmask = np.array(masks, dtype=mdtype)\n # Try to take care of the missing data we missed\n names = output.dtype.names\n if usemask and names:\n for (name, conv) in zip(names, converters):\n missing_values = [conv(_) for _ in conv.missing_values\n if _ != '']\n for mval in missing_values:\n outputmask[name] |= (output[name] == mval)\n # Construct the final array\n if usemask:\n output = output.view(MaskedArray)\n output._mask = outputmask\n if unpack:\n return output.squeeze().T\n return output.squeeze()\n\n\ndef ndfromtxt(fname, **kwargs):\n \"\"\"\n Load ASCII data stored in a file and return it as a single array.\n\n Parameters\n ----------\n fname, kwargs : For a description of input parameters, see `genfromtxt`.\n\n See Also\n --------\n numpy.genfromtxt : generic function.\n\n \"\"\"\n kwargs['usemask'] = False\n return genfromtxt(fname, **kwargs)\n\n\ndef mafromtxt(fname, **kwargs):\n \"\"\"\n Load ASCII data stored in a text file and return a masked array.\n\n Parameters\n ----------\n fname, kwargs : For a description of input parameters, see `genfromtxt`.\n\n See Also\n --------\n numpy.genfromtxt : generic function to load ASCII data.\n\n \"\"\"\n kwargs['usemask'] = True\n return genfromtxt(fname, **kwargs)\n\n\ndef recfromtxt(fname, **kwargs):\n \"\"\"\n Load ASCII data from a file and return it in a record array.\n\n If ``usemask=False`` a standard `recarray` is returned,\n if ``usemask=True`` a MaskedRecords array is returned.\n\n Parameters\n ----------\n fname, kwargs : For a description of input parameters, see `genfromtxt`.\n\n See Also\n --------\n numpy.genfromtxt : generic function\n\n Notes\n -----\n By default, `dtype` is None, which means that the data-type of the output\n array will be determined from the data.\n\n \"\"\"\n kwargs.setdefault(\"dtype\", None)\n usemask = kwargs.get('usemask', False)\n output = genfromtxt(fname, **kwargs)\n if usemask:\n from numpy.ma.mrecords import MaskedRecords\n output = output.view(MaskedRecords)\n else:\n output = output.view(np.recarray)\n return output\n\n\ndef recfromcsv(fname, **kwargs):\n \"\"\"\n Load ASCII data stored in a comma-separated file.\n\n The returned array is a record array (if ``usemask=False``, see\n `recarray`) or a masked record array (if ``usemask=True``,\n see `ma.mrecords.MaskedRecords`).\n\n Parameters\n ----------\n fname, kwargs : For a description of input parameters, see `genfromtxt`.\n\n See Also\n --------\n numpy.genfromtxt : generic function to load ASCII data.\n\n Notes\n -----\n By default, `dtype` is None, which means that the data-type of the output\n array will be determined from the data.\n\n \"\"\"\n # Set default kwargs for genfromtxt as relevant to csv import.\n kwargs.setdefault(\"case_sensitive\", \"lower\")\n kwargs.setdefault(\"names\", True)\n kwargs.setdefault(\"delimiter\", \",\")\n kwargs.setdefault(\"dtype\", None)\n output = genfromtxt(fname, **kwargs)\n\n usemask = kwargs.get(\"usemask\", False)\n if usemask:\n from numpy.ma.mrecords import MaskedRecords\n output = output.view(MaskedRecords)\n else:\n output = output.view(np.recarray)\n return output\n",
"from __future__ import division, print_function, absolute_import\n\nimport numpy as np\nfrom numpy.testing import (assert_almost_equal, assert_array_almost_equal,\n assert_equal, assert_,\n assert_allclose, assert_warns)\nfrom pytest import raises as assert_raises\nimport pytest\n\nfrom scipy.linalg import LinAlgWarning\nfrom scipy.special import sinc\nfrom scipy.signal import kaiser_beta, kaiser_atten, kaiserord, \\\n firwin, firwin2, freqz, remez, firls, minimum_phase\n\n\ndef test_kaiser_beta():\n b = kaiser_beta(58.7)\n assert_almost_equal(b, 0.1102 * 50.0)\n b = kaiser_beta(22.0)\n assert_almost_equal(b, 0.5842 + 0.07886)\n b = kaiser_beta(21.0)\n assert_equal(b, 0.0)\n b = kaiser_beta(10.0)\n assert_equal(b, 0.0)\n\n\ndef test_kaiser_atten():\n a = kaiser_atten(1, 1.0)\n assert_equal(a, 7.95)\n a = kaiser_atten(2, 1/np.pi)\n assert_equal(a, 2.285 + 7.95)\n\n\ndef test_kaiserord():\n assert_raises(ValueError, kaiserord, 1.0, 1.0)\n numtaps, beta = kaiserord(2.285 + 7.95 - 0.001, 1/np.pi)\n assert_equal((numtaps, beta), (2, 0.0))\n\n\nclass TestFirwin(object):\n\n def check_response(self, h, expected_response, tol=.05):\n N = len(h)\n alpha = 0.5 * (N-1)\n m = np.arange(0,N) - alpha # time indices of taps\n for freq, expected in expected_response:\n actual = abs(np.sum(h*np.exp(-1.j*np.pi*m*freq)))\n mse = abs(actual-expected)**2\n assert_(mse < tol, 'response not as expected, mse=%g > %g'\n % (mse, tol))\n\n def test_response(self):\n N = 51\n f = .5\n # increase length just to try even/odd\n h = firwin(N, f) # low-pass from 0 to f\n self.check_response(h, [(.25,1), (.75,0)])\n\n h = firwin(N+1, f, window='nuttall') # specific window\n self.check_response(h, [(.25,1), (.75,0)])\n\n h = firwin(N+2, f, pass_zero=False) # stop from 0 to f --> high-pass\n self.check_response(h, [(.25,0), (.75,1)])\n\n f1, f2, f3, f4 = .2, .4, .6, .8\n h = firwin(N+3, [f1, f2], pass_zero=False) # band-pass filter\n self.check_response(h, [(.1,0), (.3,1), (.5,0)])\n\n h = firwin(N+4, [f1, f2]) # band-stop filter\n self.check_response(h, [(.1,1), (.3,0), (.5,1)])\n\n h = firwin(N+5, [f1, f2, f3, f4], pass_zero=False, scale=False)\n self.check_response(h, [(.1,0), (.3,1), (.5,0), (.7,1), (.9,0)])\n\n h = firwin(N+6, [f1, f2, f3, f4]) # multiband filter\n self.check_response(h, [(.1,1), (.3,0), (.5,1), (.7,0), (.9,1)])\n\n h = firwin(N+7, 0.1, width=.03) # low-pass\n self.check_response(h, [(.05,1), (.75,0)])\n\n h = firwin(N+8, 0.1, pass_zero=False) # high-pass\n self.check_response(h, [(.05,0), (.75,1)])\n\n def mse(self, h, bands):\n \"\"\"Compute mean squared error versus ideal response across frequency\n band.\n h -- coefficients\n bands -- list of (left, right) tuples relative to 1==Nyquist of\n passbands\n \"\"\"\n w, H = freqz(h, worN=1024)\n f = w/np.pi\n passIndicator = np.zeros(len(w), bool)\n for left, right in bands:\n passIndicator |= (f >= left) & (f < right)\n Hideal = np.where(passIndicator, 1, 0)\n mse = np.mean(abs(abs(H)-Hideal)**2)\n return mse\n\n def test_scaling(self):\n \"\"\"\n For one lowpass, bandpass, and highpass example filter, this test\n checks two things:\n - the mean squared error over the frequency domain of the unscaled\n filter is smaller than the scaled filter (true for rectangular\n window)\n - the response of the scaled filter is exactly unity at the center\n of the first passband\n \"\"\"\n N = 11\n cases = [\n ([.5], True, (0, 1)),\n ([0.2, .6], False, (.4, 1)),\n ([.5], False, (1, 1)),\n ]\n for cutoff, pass_zero, expected_response in cases:\n h = firwin(N, cutoff, scale=False, pass_zero=pass_zero, window='ones')\n hs = firwin(N, cutoff, scale=True, pass_zero=pass_zero, window='ones')\n if len(cutoff) == 1:\n if pass_zero:\n cutoff = [0] + cutoff\n else:\n cutoff = cutoff + [1]\n assert_(self.mse(h, [cutoff]) < self.mse(hs, [cutoff]),\n 'least squares violation')\n self.check_response(hs, [expected_response], 1e-12)\n\n\nclass TestFirWinMore(object):\n \"\"\"Different author, different style, different tests...\"\"\"\n\n def test_lowpass(self):\n width = 0.04\n ntaps, beta = kaiserord(120, width)\n kwargs = dict(cutoff=0.5, window=('kaiser', beta), scale=False)\n taps = firwin(ntaps, **kwargs)\n\n # Check the symmetry of taps.\n assert_array_almost_equal(taps[:ntaps//2], taps[ntaps:ntaps-ntaps//2-1:-1])\n\n # Check the gain at a few samples where we know it should be approximately 0 or 1.\n freq_samples = np.array([0.0, 0.25, 0.5-width/2, 0.5+width/2, 0.75, 1.0])\n freqs, response = freqz(taps, worN=np.pi*freq_samples)\n assert_array_almost_equal(np.abs(response),\n [1.0, 1.0, 1.0, 0.0, 0.0, 0.0], decimal=5)\n\n taps_str = firwin(ntaps, pass_zero='lowpass', **kwargs)\n assert_allclose(taps, taps_str)\n\n def test_highpass(self):\n width = 0.04\n ntaps, beta = kaiserord(120, width)\n\n # Ensure that ntaps is odd.\n ntaps |= 1\n\n kwargs = dict(cutoff=0.5, window=('kaiser', beta), scale=False)\n taps = firwin(ntaps, pass_zero=False, **kwargs)\n\n # Check the symmetry of taps.\n assert_array_almost_equal(taps[:ntaps//2], taps[ntaps:ntaps-ntaps//2-1:-1])\n\n # Check the gain at a few samples where we know it should be approximately 0 or 1.\n freq_samples = np.array([0.0, 0.25, 0.5-width/2, 0.5+width/2, 0.75, 1.0])\n freqs, response = freqz(taps, worN=np.pi*freq_samples)\n assert_array_almost_equal(np.abs(response),\n [0.0, 0.0, 0.0, 1.0, 1.0, 1.0], decimal=5)\n\n taps_str = firwin(ntaps, pass_zero='highpass', **kwargs)\n assert_allclose(taps, taps_str)\n\n def test_bandpass(self):\n width = 0.04\n ntaps, beta = kaiserord(120, width)\n kwargs = dict(cutoff=[0.3, 0.7], window=('kaiser', beta), scale=False)\n taps = firwin(ntaps, pass_zero=False, **kwargs)\n\n # Check the symmetry of taps.\n assert_array_almost_equal(taps[:ntaps//2], taps[ntaps:ntaps-ntaps//2-1:-1])\n\n # Check the gain at a few samples where we know it should be approximately 0 or 1.\n freq_samples = np.array([0.0, 0.2, 0.3-width/2, 0.3+width/2, 0.5,\n 0.7-width/2, 0.7+width/2, 0.8, 1.0])\n freqs, response = freqz(taps, worN=np.pi*freq_samples)\n assert_array_almost_equal(np.abs(response),\n [0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0], decimal=5)\n\n taps_str = firwin(ntaps, pass_zero='bandpass', **kwargs)\n assert_allclose(taps, taps_str)\n\n def test_bandstop_multi(self):\n width = 0.04\n ntaps, beta = kaiserord(120, width)\n kwargs = dict(cutoff=[0.2, 0.5, 0.8], window=('kaiser', beta),\n scale=False)\n taps = firwin(ntaps, **kwargs)\n\n # Check the symmetry of taps.\n assert_array_almost_equal(taps[:ntaps//2], taps[ntaps:ntaps-ntaps//2-1:-1])\n\n # Check the gain at a few samples where we know it should be approximately 0 or 1.\n freq_samples = np.array([0.0, 0.1, 0.2-width/2, 0.2+width/2, 0.35,\n 0.5-width/2, 0.5+width/2, 0.65,\n 0.8-width/2, 0.8+width/2, 0.9, 1.0])\n freqs, response = freqz(taps, worN=np.pi*freq_samples)\n assert_array_almost_equal(np.abs(response),\n [1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0],\n decimal=5)\n\n taps_str = firwin(ntaps, pass_zero='bandstop', **kwargs)\n assert_allclose(taps, taps_str)\n\n def test_fs_nyq(self):\n \"\"\"Test the fs and nyq keywords.\"\"\"\n nyquist = 1000\n width = 40.0\n relative_width = width/nyquist\n ntaps, beta = kaiserord(120, relative_width)\n taps = firwin(ntaps, cutoff=[300, 700], window=('kaiser', beta),\n pass_zero=False, scale=False, fs=2*nyquist)\n\n # Check the symmetry of taps.\n assert_array_almost_equal(taps[:ntaps//2], taps[ntaps:ntaps-ntaps//2-1:-1])\n\n # Check the gain at a few samples where we know it should be approximately 0 or 1.\n freq_samples = np.array([0.0, 200, 300-width/2, 300+width/2, 500,\n 700-width/2, 700+width/2, 800, 1000])\n freqs, response = freqz(taps, worN=np.pi*freq_samples/nyquist)\n assert_array_almost_equal(np.abs(response),\n [0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0], decimal=5)\n\n taps2 = firwin(ntaps, cutoff=[300, 700], window=('kaiser', beta),\n pass_zero=False, scale=False, nyq=nyquist)\n assert_allclose(taps2, taps)\n\n def test_bad_cutoff(self):\n \"\"\"Test that invalid cutoff argument raises ValueError.\"\"\"\n # cutoff values must be greater than 0 and less than 1.\n assert_raises(ValueError, firwin, 99, -0.5)\n assert_raises(ValueError, firwin, 99, 1.5)\n # Don't allow 0 or 1 in cutoff.\n assert_raises(ValueError, firwin, 99, [0, 0.5])\n assert_raises(ValueError, firwin, 99, [0.5, 1])\n # cutoff values must be strictly increasing.\n assert_raises(ValueError, firwin, 99, [0.1, 0.5, 0.2])\n assert_raises(ValueError, firwin, 99, [0.1, 0.5, 0.5])\n # Must have at least one cutoff value.\n assert_raises(ValueError, firwin, 99, [])\n # 2D array not allowed.\n assert_raises(ValueError, firwin, 99, [[0.1, 0.2],[0.3, 0.4]])\n # cutoff values must be less than nyq.\n assert_raises(ValueError, firwin, 99, 50.0, nyq=40)\n assert_raises(ValueError, firwin, 99, [10, 20, 30], nyq=25)\n assert_raises(ValueError, firwin, 99, 50.0, fs=80)\n assert_raises(ValueError, firwin, 99, [10, 20, 30], fs=50)\n\n def test_even_highpass_raises_value_error(self):\n \"\"\"Test that attempt to create a highpass filter with an even number\n of taps raises a ValueError exception.\"\"\"\n assert_raises(ValueError, firwin, 40, 0.5, pass_zero=False)\n assert_raises(ValueError, firwin, 40, [.25, 0.5])\n\n def test_bad_pass_zero(self):\n \"\"\"Test degenerate pass_zero cases.\"\"\"\n with assert_raises(ValueError, match='pass_zero must be'):\n firwin(41, 0.5, pass_zero='foo')\n with assert_raises(TypeError, match='cannot be interpreted'):\n firwin(41, 0.5, pass_zero=1.)\n for pass_zero in ('lowpass', 'highpass'):\n with assert_raises(ValueError, match='cutoff must have one'):\n firwin(41, [0.5, 0.6], pass_zero=pass_zero)\n for pass_zero in ('bandpass', 'bandstop'):\n with assert_raises(ValueError, match='must have at least two'):\n firwin(41, [0.5], pass_zero=pass_zero)\n\n\nclass TestFirwin2(object):\n\n def test_invalid_args(self):\n # `freq` and `gain` have different lengths.\n assert_raises(ValueError, firwin2, 50, [0, 0.5, 1], [0.0, 1.0])\n # `nfreqs` is less than `ntaps`.\n assert_raises(ValueError, firwin2, 50, [0, 0.5, 1], [0.0, 1.0, 1.0], nfreqs=33)\n # Decreasing value in `freq`\n assert_raises(ValueError, firwin2, 50, [0, 0.5, 0.4, 1.0], [0, .25, .5, 1.0])\n # Value in `freq` repeated more than once.\n assert_raises(ValueError, firwin2, 50, [0, .1, .1, .1, 1.0],\n [0.0, 0.5, 0.75, 1.0, 1.0])\n # `freq` does not start at 0.0.\n assert_raises(ValueError, firwin2, 50, [0.5, 1.0], [0.0, 1.0])\n\n # Type II filter, but the gain at nyquist frequency is not zero.\n assert_raises(ValueError, firwin2, 16, [0.0, 0.5, 1.0], [0.0, 1.0, 1.0])\n\n # Type III filter, but the gains at nyquist and zero rate are not zero.\n assert_raises(ValueError, firwin2, 17, [0.0, 0.5, 1.0], [0.0, 1.0, 1.0],\n antisymmetric=True)\n assert_raises(ValueError, firwin2, 17, [0.0, 0.5, 1.0], [1.0, 1.0, 0.0],\n antisymmetric=True)\n assert_raises(ValueError, firwin2, 17, [0.0, 0.5, 1.0], [1.0, 1.0, 1.0],\n antisymmetric=True)\n\n # Type VI filter, but the gain at zero rate is not zero.\n assert_raises(ValueError, firwin2, 16, [0.0, 0.5, 1.0], [1.0, 1.0, 0.0],\n antisymmetric=True)\n\n def test01(self):\n width = 0.04\n beta = 12.0\n ntaps = 400\n # Filter is 1 from w=0 to w=0.5, then decreases linearly from 1 to 0 as w\n # increases from w=0.5 to w=1 (w=1 is the Nyquist frequency).\n freq = [0.0, 0.5, 1.0]\n gain = [1.0, 1.0, 0.0]\n taps = firwin2(ntaps, freq, gain, window=('kaiser', beta))\n freq_samples = np.array([0.0, 0.25, 0.5-width/2, 0.5+width/2,\n 0.75, 1.0-width/2])\n freqs, response = freqz(taps, worN=np.pi*freq_samples)\n assert_array_almost_equal(np.abs(response),\n [1.0, 1.0, 1.0, 1.0-width, 0.5, width], decimal=5)\n\n def test02(self):\n width = 0.04\n beta = 12.0\n # ntaps must be odd for positive gain at Nyquist.\n ntaps = 401\n # An ideal highpass filter.\n freq = [0.0, 0.5, 0.5, 1.0]\n gain = [0.0, 0.0, 1.0, 1.0]\n taps = firwin2(ntaps, freq, gain, window=('kaiser', beta))\n freq_samples = np.array([0.0, 0.25, 0.5-width, 0.5+width, 0.75, 1.0])\n freqs, response = freqz(taps, worN=np.pi*freq_samples)\n assert_array_almost_equal(np.abs(response),\n [0.0, 0.0, 0.0, 1.0, 1.0, 1.0], decimal=5)\n\n def test03(self):\n width = 0.02\n ntaps, beta = kaiserord(120, width)\n # ntaps must be odd for positive gain at Nyquist.\n ntaps = int(ntaps) | 1\n freq = [0.0, 0.4, 0.4, 0.5, 0.5, 1.0]\n gain = [1.0, 1.0, 0.0, 0.0, 1.0, 1.0]\n taps = firwin2(ntaps, freq, gain, window=('kaiser', beta))\n freq_samples = np.array([0.0, 0.4-width, 0.4+width, 0.45,\n 0.5-width, 0.5+width, 0.75, 1.0])\n freqs, response = freqz(taps, worN=np.pi*freq_samples)\n assert_array_almost_equal(np.abs(response),\n [1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0], decimal=5)\n\n def test04(self):\n \"\"\"Test firwin2 when window=None.\"\"\"\n ntaps = 5\n # Ideal lowpass: gain is 1 on [0,0.5], and 0 on [0.5, 1.0]\n freq = [0.0, 0.5, 0.5, 1.0]\n gain = [1.0, 1.0, 0.0, 0.0]\n taps = firwin2(ntaps, freq, gain, window=None, nfreqs=8193)\n alpha = 0.5 * (ntaps - 1)\n m = np.arange(0, ntaps) - alpha\n h = 0.5 * sinc(0.5 * m)\n assert_array_almost_equal(h, taps)\n\n def test05(self):\n \"\"\"Test firwin2 for calculating Type IV filters\"\"\"\n ntaps = 1500\n\n freq = [0.0, 1.0]\n gain = [0.0, 1.0]\n taps = firwin2(ntaps, freq, gain, window=None, antisymmetric=True)\n assert_array_almost_equal(taps[: ntaps // 2], -taps[ntaps // 2:][::-1])\n\n freqs, response = freqz(taps, worN=2048)\n assert_array_almost_equal(abs(response), freqs / np.pi, decimal=4)\n\n def test06(self):\n \"\"\"Test firwin2 for calculating Type III filters\"\"\"\n ntaps = 1501\n\n freq = [0.0, 0.5, 0.55, 1.0]\n gain = [0.0, 0.5, 0.0, 0.0]\n taps = firwin2(ntaps, freq, gain, window=None, antisymmetric=True)\n assert_equal(taps[ntaps // 2], 0.0)\n assert_array_almost_equal(taps[: ntaps // 2], -taps[ntaps // 2 + 1:][::-1])\n\n freqs, response1 = freqz(taps, worN=2048)\n response2 = np.interp(freqs / np.pi, freq, gain)\n assert_array_almost_equal(abs(response1), response2, decimal=3)\n\n def test_fs_nyq(self):\n taps1 = firwin2(80, [0.0, 0.5, 1.0], [1.0, 1.0, 0.0])\n taps2 = firwin2(80, [0.0, 30.0, 60.0], [1.0, 1.0, 0.0], fs=120.0)\n assert_array_almost_equal(taps1, taps2)\n taps2 = firwin2(80, [0.0, 30.0, 60.0], [1.0, 1.0, 0.0], nyq=60.0)\n assert_array_almost_equal(taps1, taps2)\n\nclass TestRemez(object):\n\n def test_bad_args(self):\n assert_raises(ValueError, remez, 11, [0.1, 0.4], [1], type='pooka')\n\n def test_hilbert(self):\n N = 11 # number of taps in the filter\n a = 0.1 # width of the transition band\n\n # design an unity gain hilbert bandpass filter from w to 0.5-w\n h = remez(11, [a, 0.5-a], [1], type='hilbert')\n\n # make sure the filter has correct # of taps\n assert_(len(h) == N, \"Number of Taps\")\n\n # make sure it is type III (anti-symmetric tap coefficients)\n assert_array_almost_equal(h[:(N-1)//2], -h[:-(N-1)//2-1:-1])\n\n # Since the requested response is symmetric, all even coefficients\n # should be zero (or in this case really small)\n assert_((abs(h[1::2]) < 1e-15).all(), \"Even Coefficients Equal Zero\")\n\n # now check the frequency response\n w, H = freqz(h, 1)\n f = w/2/np.pi\n Hmag = abs(H)\n\n # should have a zero at 0 and pi (in this case close to zero)\n assert_((Hmag[[0, -1]] < 0.02).all(), \"Zero at zero and pi\")\n\n # check that the pass band is close to unity\n idx = np.logical_and(f > a, f < 0.5-a)\n assert_((abs(Hmag[idx] - 1) < 0.015).all(), \"Pass Band Close To Unity\")\n\n def test_compare(self):\n # test comparison to MATLAB\n k = [0.024590270518440, -0.041314581814658, -0.075943803756711,\n -0.003530911231040, 0.193140296954975, 0.373400753484939,\n 0.373400753484939, 0.193140296954975, -0.003530911231040,\n -0.075943803756711, -0.041314581814658, 0.024590270518440]\n h = remez(12, [0, 0.3, 0.5, 1], [1, 0], Hz=2.)\n assert_allclose(h, k)\n h = remez(12, [0, 0.3, 0.5, 1], [1, 0], fs=2.)\n assert_allclose(h, k)\n\n h = [-0.038976016082299, 0.018704846485491, -0.014644062687875,\n 0.002879152556419, 0.016849978528150, -0.043276706138248,\n 0.073641298245579, -0.103908158578635, 0.129770906801075,\n -0.147163447297124, 0.153302248456347, -0.147163447297124,\n 0.129770906801075, -0.103908158578635, 0.073641298245579,\n -0.043276706138248, 0.016849978528150, 0.002879152556419,\n -0.014644062687875, 0.018704846485491, -0.038976016082299]\n assert_allclose(remez(21, [0, 0.8, 0.9, 1], [0, 1], Hz=2.), h)\n assert_allclose(remez(21, [0, 0.8, 0.9, 1], [0, 1], fs=2.), h)\n\n\nclass TestFirls(object):\n\n def test_bad_args(self):\n # even numtaps\n assert_raises(ValueError, firls, 10, [0.1, 0.2], [0, 0])\n # odd bands\n assert_raises(ValueError, firls, 11, [0.1, 0.2, 0.4], [0, 0, 0])\n # len(bands) != len(desired)\n assert_raises(ValueError, firls, 11, [0.1, 0.2, 0.3, 0.4], [0, 0, 0])\n # non-monotonic bands\n assert_raises(ValueError, firls, 11, [0.2, 0.1], [0, 0])\n assert_raises(ValueError, firls, 11, [0.1, 0.2, 0.3, 0.3], [0] * 4)\n assert_raises(ValueError, firls, 11, [0.3, 0.4, 0.1, 0.2], [0] * 4)\n assert_raises(ValueError, firls, 11, [0.1, 0.3, 0.2, 0.4], [0] * 4)\n # negative desired\n assert_raises(ValueError, firls, 11, [0.1, 0.2], [-1, 1])\n # len(weight) != len(pairs)\n assert_raises(ValueError, firls, 11, [0.1, 0.2], [0, 0], [1, 2])\n # negative weight\n assert_raises(ValueError, firls, 11, [0.1, 0.2], [0, 0], [-1])\n\n def test_firls(self):\n N = 11 # number of taps in the filter\n a = 0.1 # width of the transition band\n\n # design a halfband symmetric low-pass filter\n h = firls(11, [0, a, 0.5-a, 0.5], [1, 1, 0, 0], fs=1.0)\n\n # make sure the filter has correct # of taps\n assert_equal(len(h), N)\n\n # make sure it is symmetric\n midx = (N-1) // 2\n assert_array_almost_equal(h[:midx], h[:-midx-1:-1])\n\n # make sure the center tap is 0.5\n assert_almost_equal(h[midx], 0.5)\n\n # For halfband symmetric, odd coefficients (except the center)\n # should be zero (really small)\n hodd = np.hstack((h[1:midx:2], h[-midx+1::2]))\n assert_array_almost_equal(hodd, 0)\n\n # now check the frequency response\n w, H = freqz(h, 1)\n f = w/2/np.pi\n Hmag = np.abs(H)\n\n # check that the pass band is close to unity\n idx = np.logical_and(f > 0, f < a)\n assert_array_almost_equal(Hmag[idx], 1, decimal=3)\n\n # check that the stop band is close to zero\n idx = np.logical_and(f > 0.5-a, f < 0.5)\n assert_array_almost_equal(Hmag[idx], 0, decimal=3)\n\n def test_compare(self):\n # compare to OCTAVE output\n taps = firls(9, [0, 0.5, 0.55, 1], [1, 1, 0, 0], [1, 2])\n # >> taps = firls(8, [0 0.5 0.55 1], [1 1 0 0], [1, 2]);\n known_taps = [-6.26930101730182e-04, -1.03354450635036e-01,\n -9.81576747564301e-03, 3.17271686090449e-01,\n 5.11409425599933e-01, 3.17271686090449e-01,\n -9.81576747564301e-03, -1.03354450635036e-01,\n -6.26930101730182e-04]\n assert_allclose(taps, known_taps)\n\n # compare to MATLAB output\n taps = firls(11, [0, 0.5, 0.5, 1], [1, 1, 0, 0], [1, 2])\n # >> taps = firls(10, [0 0.5 0.5 1], [1 1 0 0], [1, 2]);\n known_taps = [\n 0.058545300496815, -0.014233383714318, -0.104688258464392,\n 0.012403323025279, 0.317930861136062, 0.488047220029700,\n 0.317930861136062, 0.012403323025279, -0.104688258464392,\n -0.014233383714318, 0.058545300496815]\n assert_allclose(taps, known_taps)\n\n # With linear changes:\n taps = firls(7, (0, 1, 2, 3, 4, 5), [1, 0, 0, 1, 1, 0], fs=20)\n # >> taps = firls(6, [0, 0.1, 0.2, 0.3, 0.4, 0.5], [1, 0, 0, 1, 1, 0])\n known_taps = [\n 1.156090832768218, -4.1385894727395849, 7.5288619164321826,\n -8.5530572592947856, 7.5288619164321826, -4.1385894727395849,\n 1.156090832768218]\n assert_allclose(taps, known_taps)\n\n taps = firls(7, (0, 1, 2, 3, 4, 5), [1, 0, 0, 1, 1, 0], nyq=10)\n assert_allclose(taps, known_taps)\n\n with pytest.raises(ValueError, match='between 0 and 1'):\n firls(7, [0, 1], [0, 1], nyq=0.5)\n\n def test_rank_deficient(self):\n # solve() runs but warns (only sometimes, so here we don't use match)\n x = firls(21, [0, 0.1, 0.9, 1], [1, 1, 0, 0])\n w, h = freqz(x, fs=2.)\n assert_allclose(np.abs(h[:2]), 1., atol=1e-5)\n assert_allclose(np.abs(h[-2:]), 0., atol=1e-6)\n # switch to pinvh (tolerances could be higher with longer\n # filters, but using shorter ones is faster computationally and\n # the idea is the same)\n x = firls(101, [0, 0.01, 0.99, 1], [1, 1, 0, 0])\n w, h = freqz(x, fs=2.)\n mask = w < 0.01\n assert mask.sum() > 3\n assert_allclose(np.abs(h[mask]), 1., atol=1e-4)\n mask = w > 0.99\n assert mask.sum() > 3\n assert_allclose(np.abs(h[mask]), 0., atol=1e-4)\n\n\nclass TestMinimumPhase(object):\n\n def test_bad_args(self):\n # not enough taps\n assert_raises(ValueError, minimum_phase, [1.])\n assert_raises(ValueError, minimum_phase, [1., 1.])\n assert_raises(ValueError, minimum_phase, np.ones(10) * 1j)\n assert_raises(ValueError, minimum_phase, 'foo')\n assert_raises(ValueError, minimum_phase, np.ones(10), n_fft=8)\n assert_raises(ValueError, minimum_phase, np.ones(10), method='foo')\n assert_warns(RuntimeWarning, minimum_phase, np.arange(3))\n\n def test_homomorphic(self):\n # check that it can recover frequency responses of arbitrary\n # linear-phase filters\n\n # for some cases we can get the actual filter back\n h = [1, -1]\n h_new = minimum_phase(np.convolve(h, h[::-1]))\n assert_allclose(h_new, h, rtol=0.05)\n\n # but in general we only guarantee we get the magnitude back\n rng = np.random.RandomState(0)\n for n in (2, 3, 10, 11, 15, 16, 17, 20, 21, 100, 101):\n h = rng.randn(n)\n h_new = minimum_phase(np.convolve(h, h[::-1]))\n assert_allclose(np.abs(np.fft.fft(h_new)),\n np.abs(np.fft.fft(h)), rtol=1e-4)\n\n def test_hilbert(self):\n # compare to MATLAB output of reference implementation\n\n # f=[0 0.3 0.5 1];\n # a=[1 1 0 0];\n # h=remez(11,f,a);\n h = remez(12, [0, 0.3, 0.5, 1], [1, 0], fs=2.)\n k = [0.349585548646686, 0.373552164395447, 0.326082685363438,\n 0.077152207480935, -0.129943946349364, -0.059355880509749]\n m = minimum_phase(h, 'hilbert')\n assert_allclose(m, k, rtol=2e-3)\n\n # f=[0 0.8 0.9 1];\n # a=[0 0 1 1];\n # h=remez(20,f,a);\n h = remez(21, [0, 0.8, 0.9, 1], [0, 1], fs=2.)\n k = [0.232486803906329, -0.133551833687071, 0.151871456867244,\n -0.157957283165866, 0.151739294892963, -0.129293146705090,\n 0.100787844523204, -0.065832656741252, 0.035361328741024,\n -0.014977068692269, -0.158416139047557]\n m = minimum_phase(h, 'hilbert', n_fft=2**19)\n assert_allclose(m, k, rtol=2e-3)\n",
"\"\"\"\nThe :mod:`sklearn.metrics.scorer` submodule implements a flexible\ninterface for model selection and evaluation using\narbitrary score functions.\n\nA scorer object is a callable that can be passed to\n:class:`sklearn.model_selection.GridSearchCV` or\n:func:`sklearn.model_selection.cross_val_score` as the ``scoring``\nparameter, to specify how a model should be evaluated.\n\nThe signature of the call is ``(estimator, X, y)`` where ``estimator``\nis the model to be evaluated, ``X`` is the test data and ``y`` is the\nground truth labeling (or ``None`` in the case of unsupervised models).\n\"\"\"\n\n# Authors: Andreas Mueller <[email protected]>\n# Lars Buitinck\n# Arnaud Joly <[email protected]>\n# License: Simplified BSD\n\nfrom abc import ABCMeta\nfrom collections.abc import Iterable\n\nimport numpy as np\n\nfrom . import (r2_score, median_absolute_error, max_error, mean_absolute_error,\n mean_squared_error, mean_squared_log_error, accuracy_score,\n f1_score, roc_auc_score, average_precision_score,\n precision_score, recall_score, log_loss,\n balanced_accuracy_score, explained_variance_score,\n brier_score_loss, jaccard_score)\n\nfrom .cluster import adjusted_rand_score\nfrom .cluster import homogeneity_score\nfrom .cluster import completeness_score\nfrom .cluster import v_measure_score\nfrom .cluster import mutual_info_score\nfrom .cluster import adjusted_mutual_info_score\nfrom .cluster import normalized_mutual_info_score\nfrom .cluster import fowlkes_mallows_score\n\nfrom ..utils.multiclass import type_of_target\nfrom ..base import is_regressor\n\n\nclass _BaseScorer(metaclass=ABCMeta):\n def __init__(self, score_func, sign, kwargs):\n self._kwargs = kwargs\n self._score_func = score_func\n self._sign = sign\n\n def __repr__(self):\n kwargs_string = \"\".join([\", %s=%s\" % (str(k), str(v))\n for k, v in self._kwargs.items()])\n return (\"make_scorer(%s%s%s%s)\"\n % (self._score_func.__name__,\n \"\" if self._sign > 0 else \", greater_is_better=False\",\n self._factory_args(), kwargs_string))\n\n def _factory_args(self):\n \"\"\"Return non-default make_scorer arguments for repr.\"\"\"\n return \"\"\n\n\nclass _PredictScorer(_BaseScorer):\n def __call__(self, estimator, X, y_true, sample_weight=None):\n \"\"\"Evaluate predicted target values for X relative to y_true.\n\n Parameters\n ----------\n estimator : object\n Trained estimator to use for scoring. Must have a predict_proba\n method; the output of that is used to compute the score.\n\n X : array-like or sparse matrix\n Test data that will be fed to estimator.predict.\n\n y_true : array-like\n Gold standard target values for X.\n\n sample_weight : array-like, optional (default=None)\n Sample weights.\n\n Returns\n -------\n score : float\n Score function applied to prediction of estimator on X.\n \"\"\"\n\n y_pred = estimator.predict(X)\n if sample_weight is not None:\n return self._sign * self._score_func(y_true, y_pred,\n sample_weight=sample_weight,\n **self._kwargs)\n else:\n return self._sign * self._score_func(y_true, y_pred,\n **self._kwargs)\n\n\nclass _ProbaScorer(_BaseScorer):\n def __call__(self, clf, X, y, sample_weight=None):\n \"\"\"Evaluate predicted probabilities for X relative to y_true.\n\n Parameters\n ----------\n clf : object\n Trained classifier to use for scoring. Must have a predict_proba\n method; the output of that is used to compute the score.\n\n X : array-like or sparse matrix\n Test data that will be fed to clf.predict_proba.\n\n y : array-like\n Gold standard target values for X. These must be class labels,\n not probabilities.\n\n sample_weight : array-like, optional (default=None)\n Sample weights.\n\n Returns\n -------\n score : float\n Score function applied to prediction of estimator on X.\n \"\"\"\n y_type = type_of_target(y)\n y_pred = clf.predict_proba(X)\n if y_type == \"binary\":\n if y_pred.shape[1] == 2:\n y_pred = y_pred[:, 1]\n else:\n raise ValueError('got predict_proba of shape {},'\n ' but need classifier with two'\n ' classes for {} scoring'.format(\n y_pred.shape, self._score_func.__name__))\n if sample_weight is not None:\n return self._sign * self._score_func(y, y_pred,\n sample_weight=sample_weight,\n **self._kwargs)\n else:\n return self._sign * self._score_func(y, y_pred, **self._kwargs)\n\n def _factory_args(self):\n return \", needs_proba=True\"\n\n\nclass _ThresholdScorer(_BaseScorer):\n def __call__(self, clf, X, y, sample_weight=None):\n \"\"\"Evaluate decision function output for X relative to y_true.\n\n Parameters\n ----------\n clf : object\n Trained classifier to use for scoring. Must have either a\n decision_function method or a predict_proba method; the output of\n that is used to compute the score.\n\n X : array-like or sparse matrix\n Test data that will be fed to clf.decision_function or\n clf.predict_proba.\n\n y : array-like\n Gold standard target values for X. These must be class labels,\n not decision function values.\n\n sample_weight : array-like, optional (default=None)\n Sample weights.\n\n Returns\n -------\n score : float\n Score function applied to prediction of estimator on X.\n \"\"\"\n y_type = type_of_target(y)\n if y_type not in (\"binary\", \"multilabel-indicator\"):\n raise ValueError(\"{0} format is not supported\".format(y_type))\n\n if is_regressor(clf):\n y_pred = clf.predict(X)\n else:\n try:\n y_pred = clf.decision_function(X)\n\n # For multi-output multi-class estimator\n if isinstance(y_pred, list):\n y_pred = np.vstack([p for p in y_pred]).T\n\n except (NotImplementedError, AttributeError):\n y_pred = clf.predict_proba(X)\n\n if y_type == \"binary\":\n if y_pred.shape[1] == 2:\n y_pred = y_pred[:, 1]\n else:\n raise ValueError('got predict_proba of shape {},'\n ' but need classifier with two'\n ' classes for {} scoring'.format(\n y_pred.shape,\n self._score_func.__name__))\n elif isinstance(y_pred, list):\n y_pred = np.vstack([p[:, -1] for p in y_pred]).T\n\n if sample_weight is not None:\n return self._sign * self._score_func(y, y_pred,\n sample_weight=sample_weight,\n **self._kwargs)\n else:\n return self._sign * self._score_func(y, y_pred, **self._kwargs)\n\n def _factory_args(self):\n return \", needs_threshold=True\"\n\n\ndef get_scorer(scoring):\n \"\"\"Get a scorer from string\n\n Parameters\n ----------\n scoring : str | callable\n scoring method as string. If callable it is returned as is.\n\n Returns\n -------\n scorer : callable\n The scorer.\n \"\"\"\n if isinstance(scoring, str):\n try:\n scorer = SCORERS[scoring]\n except KeyError:\n raise ValueError('%r is not a valid scoring value. '\n 'Use sorted(sklearn.metrics.SCORERS.keys()) '\n 'to get valid options.' % (scoring))\n else:\n scorer = scoring\n return scorer\n\n\ndef _passthrough_scorer(estimator, *args, **kwargs):\n \"\"\"Function that wraps estimator.score\"\"\"\n return estimator.score(*args, **kwargs)\n\n\ndef check_scoring(estimator, scoring=None, allow_none=False):\n \"\"\"Determine scorer from user options.\n\n A TypeError will be thrown if the estimator cannot be scored.\n\n Parameters\n ----------\n estimator : estimator object implementing 'fit'\n The object to use to fit the data.\n\n scoring : string, callable or None, optional, default: None\n A string (see model evaluation documentation) or\n a scorer callable object / function with signature\n ``scorer(estimator, X, y)``.\n\n allow_none : boolean, optional, default: False\n If no scoring is specified and the estimator has no score function, we\n can either return None or raise an exception.\n\n Returns\n -------\n scoring : callable\n A scorer callable object / function with signature\n ``scorer(estimator, X, y)``.\n \"\"\"\n if not hasattr(estimator, 'fit'):\n raise TypeError(\"estimator should be an estimator implementing \"\n \"'fit' method, %r was passed\" % estimator)\n if isinstance(scoring, str):\n return get_scorer(scoring)\n elif callable(scoring):\n # Heuristic to ensure user has not passed a metric\n module = getattr(scoring, '__module__', None)\n if hasattr(module, 'startswith') and \\\n module.startswith('sklearn.metrics.') and \\\n not module.startswith('sklearn.metrics.scorer') and \\\n not module.startswith('sklearn.metrics.tests.'):\n raise ValueError('scoring value %r looks like it is a metric '\n 'function rather than a scorer. A scorer should '\n 'require an estimator as its first parameter. '\n 'Please use `make_scorer` to convert a metric '\n 'to a scorer.' % scoring)\n return get_scorer(scoring)\n elif scoring is None:\n if hasattr(estimator, 'score'):\n return _passthrough_scorer\n elif allow_none:\n return None\n else:\n raise TypeError(\n \"If no scoring is specified, the estimator passed should \"\n \"have a 'score' method. The estimator %r does not.\"\n % estimator)\n elif isinstance(scoring, Iterable):\n raise ValueError(\"For evaluating multiple scores, use \"\n \"sklearn.model_selection.cross_validate instead. \"\n \"{0} was passed.\".format(scoring))\n else:\n raise ValueError(\"scoring value should either be a callable, string or\"\n \" None. %r was passed\" % scoring)\n\n\ndef _check_multimetric_scoring(estimator, scoring=None):\n \"\"\"Check the scoring parameter in cases when multiple metrics are allowed\n\n Parameters\n ----------\n estimator : sklearn estimator instance\n The estimator for which the scoring will be applied.\n\n scoring : string, callable, list/tuple, dict or None, default: None\n A single string (see :ref:`scoring_parameter`) or a callable\n (see :ref:`scoring`) to evaluate the predictions on the test set.\n\n For evaluating multiple metrics, either give a list of (unique) strings\n or a dict with names as keys and callables as values.\n\n NOTE that when using custom scorers, each scorer should return a single\n value. Metric functions returning a list/array of values can be wrapped\n into multiple scorers that return one value each.\n\n See :ref:`multimetric_grid_search` for an example.\n\n If None the estimator's score method is used.\n The return value in that case will be ``{'score': <default_scorer>}``.\n If the estimator's score method is not available, a ``TypeError``\n is raised.\n\n Returns\n -------\n scorers_dict : dict\n A dict mapping each scorer name to its validated scorer.\n\n is_multimetric : bool\n True if scorer is a list/tuple or dict of callables\n False if scorer is None/str/callable\n \"\"\"\n if callable(scoring) or scoring is None or isinstance(scoring,\n str):\n scorers = {\"score\": check_scoring(estimator, scoring=scoring)}\n return scorers, False\n else:\n err_msg_generic = (\"scoring should either be a single string or \"\n \"callable for single metric evaluation or a \"\n \"list/tuple of strings or a dict of scorer name \"\n \"mapped to the callable for multiple metric \"\n \"evaluation. Got %s of type %s\"\n % (repr(scoring), type(scoring)))\n\n if isinstance(scoring, (list, tuple, set)):\n err_msg = (\"The list/tuple elements must be unique \"\n \"strings of predefined scorers. \")\n invalid = False\n try:\n keys = set(scoring)\n except TypeError:\n invalid = True\n if invalid:\n raise ValueError(err_msg)\n\n if len(keys) != len(scoring):\n raise ValueError(err_msg + \"Duplicate elements were found in\"\n \" the given list. %r\" % repr(scoring))\n elif len(keys) > 0:\n if not all(isinstance(k, str) for k in keys):\n if any(callable(k) for k in keys):\n raise ValueError(err_msg +\n \"One or more of the elements were \"\n \"callables. Use a dict of score name \"\n \"mapped to the scorer callable. \"\n \"Got %r\" % repr(scoring))\n else:\n raise ValueError(err_msg +\n \"Non-string types were found in \"\n \"the given list. Got %r\"\n % repr(scoring))\n scorers = {scorer: check_scoring(estimator, scoring=scorer)\n for scorer in scoring}\n else:\n raise ValueError(err_msg +\n \"Empty list was given. %r\" % repr(scoring))\n\n elif isinstance(scoring, dict):\n keys = set(scoring)\n if not all(isinstance(k, str) for k in keys):\n raise ValueError(\"Non-string types were found in the keys of \"\n \"the given dict. scoring=%r\" % repr(scoring))\n if len(keys) == 0:\n raise ValueError(\"An empty dict was passed. %r\"\n % repr(scoring))\n scorers = {key: check_scoring(estimator, scoring=scorer)\n for key, scorer in scoring.items()}\n else:\n raise ValueError(err_msg_generic)\n return scorers, True\n\n\ndef make_scorer(score_func, greater_is_better=True, needs_proba=False,\n needs_threshold=False, **kwargs):\n \"\"\"Make a scorer from a performance metric or loss function.\n\n This factory function wraps scoring functions for use in GridSearchCV\n and cross_val_score. It takes a score function, such as ``accuracy_score``,\n ``mean_squared_error``, ``adjusted_rand_index`` or ``average_precision``\n and returns a callable that scores an estimator's output.\n\n Read more in the :ref:`User Guide <scoring>`.\n\n Parameters\n ----------\n score_func : callable,\n Score function (or loss function) with signature\n ``score_func(y, y_pred, **kwargs)``.\n\n greater_is_better : boolean, default=True\n Whether score_func is a score function (default), meaning high is good,\n or a loss function, meaning low is good. In the latter case, the\n scorer object will sign-flip the outcome of the score_func.\n\n needs_proba : boolean, default=False\n Whether score_func requires predict_proba to get probability estimates\n out of a classifier.\n\n needs_threshold : boolean, default=False\n Whether score_func takes a continuous decision certainty.\n This only works for binary classification using estimators that\n have either a decision_function or predict_proba method.\n\n For example ``average_precision`` or the area under the roc curve\n can not be computed using discrete predictions alone.\n\n **kwargs : additional arguments\n Additional parameters to be passed to score_func.\n\n Returns\n -------\n scorer : callable\n Callable object that returns a scalar score; greater is better.\n\n Examples\n --------\n >>> from sklearn.metrics import fbeta_score, make_scorer\n >>> ftwo_scorer = make_scorer(fbeta_score, beta=2)\n >>> ftwo_scorer\n make_scorer(fbeta_score, beta=2)\n >>> from sklearn.model_selection import GridSearchCV\n >>> from sklearn.svm import LinearSVC\n >>> grid = GridSearchCV(LinearSVC(), param_grid={'C': [1, 10]},\n ... scoring=ftwo_scorer)\n \"\"\"\n sign = 1 if greater_is_better else -1\n if needs_proba and needs_threshold:\n raise ValueError(\"Set either needs_proba or needs_threshold to True,\"\n \" but not both.\")\n if needs_proba:\n cls = _ProbaScorer\n elif needs_threshold:\n cls = _ThresholdScorer\n else:\n cls = _PredictScorer\n return cls(score_func, sign, kwargs)\n\n\n# Standard regression scores\nexplained_variance_scorer = make_scorer(explained_variance_score)\nr2_scorer = make_scorer(r2_score)\nmax_error_scorer = make_scorer(max_error,\n greater_is_better=False)\nneg_mean_squared_error_scorer = make_scorer(mean_squared_error,\n greater_is_better=False)\nneg_mean_squared_log_error_scorer = make_scorer(mean_squared_log_error,\n greater_is_better=False)\nneg_mean_absolute_error_scorer = make_scorer(mean_absolute_error,\n greater_is_better=False)\n\nneg_median_absolute_error_scorer = make_scorer(median_absolute_error,\n greater_is_better=False)\n\n# Standard Classification Scores\naccuracy_scorer = make_scorer(accuracy_score)\nbalanced_accuracy_scorer = make_scorer(balanced_accuracy_score)\n\n# Score functions that need decision values\nroc_auc_scorer = make_scorer(roc_auc_score, greater_is_better=True,\n needs_threshold=True)\naverage_precision_scorer = make_scorer(average_precision_score,\n needs_threshold=True)\n\n# Score function for probabilistic classification\nneg_log_loss_scorer = make_scorer(log_loss, greater_is_better=False,\n needs_proba=True)\nbrier_score_loss_scorer = make_scorer(brier_score_loss,\n greater_is_better=False,\n needs_proba=True)\n\n\n# Clustering scores\nadjusted_rand_scorer = make_scorer(adjusted_rand_score)\nhomogeneity_scorer = make_scorer(homogeneity_score)\ncompleteness_scorer = make_scorer(completeness_score)\nv_measure_scorer = make_scorer(v_measure_score)\nmutual_info_scorer = make_scorer(mutual_info_score)\nadjusted_mutual_info_scorer = make_scorer(adjusted_mutual_info_score)\nnormalized_mutual_info_scorer = make_scorer(normalized_mutual_info_score)\nfowlkes_mallows_scorer = make_scorer(fowlkes_mallows_score)\n\n\nSCORERS = dict(explained_variance=explained_variance_scorer,\n r2=r2_scorer,\n max_error=max_error_scorer,\n neg_median_absolute_error=neg_median_absolute_error_scorer,\n neg_mean_absolute_error=neg_mean_absolute_error_scorer,\n neg_mean_squared_error=neg_mean_squared_error_scorer,\n neg_mean_squared_log_error=neg_mean_squared_log_error_scorer,\n accuracy=accuracy_scorer, roc_auc=roc_auc_scorer,\n balanced_accuracy=balanced_accuracy_scorer,\n average_precision=average_precision_scorer,\n neg_log_loss=neg_log_loss_scorer,\n brier_score_loss=brier_score_loss_scorer,\n # Cluster metrics that use supervised evaluation\n adjusted_rand_score=adjusted_rand_scorer,\n homogeneity_score=homogeneity_scorer,\n completeness_score=completeness_scorer,\n v_measure_score=v_measure_scorer,\n mutual_info_score=mutual_info_scorer,\n adjusted_mutual_info_score=adjusted_mutual_info_scorer,\n normalized_mutual_info_score=normalized_mutual_info_scorer,\n fowlkes_mallows_score=fowlkes_mallows_scorer)\n\n\nfor name, metric in [('precision', precision_score),\n ('recall', recall_score), ('f1', f1_score),\n ('jaccard', jaccard_score)]:\n SCORERS[name] = make_scorer(metric, average='binary')\n for average in ['macro', 'micro', 'samples', 'weighted']:\n qualified_name = '{0}_{1}'.format(name, average)\n SCORERS[qualified_name] = make_scorer(metric, pos_label=None,\n average=average)\n"
] | [
[
"numpy.lib.recfunctions.rename_fields",
"numpy.lib.recfunctions.merge_arrays",
"numpy.dtype",
"numpy.lib.recfunctions.require_fields",
"numpy.lib.recfunctions.recursive_fill_fields",
"numpy.ma.array",
"numpy.lib.recfunctions.structured_to_unstructured",
"numpy.arange",
"numpy.lib.recfunctions.repack_fields",
"numpy.lib.recfunctions.drop_fields",
"numpy.lib.recfunctions.append_fields",
"numpy.ma.zeros",
"numpy.zeros",
"numpy.lib.recfunctions.assign_fields_by_name",
"numpy.lib.recfunctions.apply_along_fields",
"numpy.lib.recfunctions.unstructured_to_structured",
"numpy.testing.assert_raises",
"numpy.testing.assert_",
"numpy.array",
"numpy.lib.recfunctions.join_by",
"numpy.lib.recfunctions.get_fieldstructure",
"numpy.lib.recfunctions.stack_arrays",
"numpy.lib.recfunctions.find_duplicates",
"numpy.tile",
"numpy.ones",
"numpy.ma.testutils.assert_equal"
],
[
"numpy.take",
"pandas.Series",
"numpy.asarray",
"numpy.dtype",
"pandas.DataFrame",
"numpy.random.randn",
"numpy.mean",
"numpy.random.sample",
"scipy.sparse.issparse",
"numpy.unique",
"numpy.reshape",
"numpy.arange",
"numpy.full",
"numpy.argmax",
"numpy.ravel",
"numpy.log",
"scipy.sparse.csr_matrix",
"numpy.argsort",
"numpy.array",
"numpy.random.RandomState",
"numpy.sum",
"scipy.stats.rankdata",
"numpy.sort",
"numpy.ones",
"numpy.empty"
],
[
"sklearn.datasets.make_classification",
"sklearn.ensemble.HistGradientBoostingClassifier",
"numpy.arange",
"sklearn.datasets.make_regression",
"numpy.zeros",
"sklearn.ensemble.HistGradientBoostingRegressor"
],
[
"numpy.asarray",
"numpy.squeeze",
"numpy.issubdtype",
"numpy.dtype",
"numpy.ma.make_mask_descr",
"numpy.iscomplexobj",
"numpy.compat.os_fspath",
"numpy.compat.asunicode",
"numpy.compat.asstr",
"numpy.atleast_1d",
"numpy.asanyarray",
"numpy.core.numeric.pickle.load",
"numpy.core.numeric.pickle.loads",
"numpy.core.overrides.set_module",
"numpy.atleast_2d",
"numpy.lib._datasource.open",
"numpy.array",
"numpy.compat.asbytes",
"numpy.prod"
],
[
"scipy.signal.freqz",
"scipy.signal.kaiser_atten",
"numpy.exp",
"numpy.where",
"scipy.signal.remez",
"scipy.signal.firwin",
"numpy.testing.assert_equal",
"numpy.hstack",
"numpy.arange",
"scipy.signal.firwin2",
"numpy.testing.assert_almost_equal",
"numpy.interp",
"numpy.testing.assert_array_almost_equal",
"scipy.signal.firls",
"scipy.signal.kaiserord",
"numpy.testing.assert_",
"numpy.testing.assert_allclose",
"numpy.logical_and",
"numpy.random.RandomState",
"numpy.array",
"scipy.signal.kaiser_beta",
"scipy.special.sinc",
"numpy.convolve",
"numpy.abs",
"numpy.fft.fft",
"scipy.signal.minimum_phase",
"numpy.ones"
],
[
"numpy.vstack"
]
] | [
{
"matplotlib": [],
"numpy": [
"1.11",
"1.19",
"1.24",
"1.16",
"1.23",
"1.20",
"1.7",
"1.12",
"1.21",
"1.22",
"1.14",
"1.6",
"1.13",
"1.9",
"1.17",
"1.10",
"1.18",
"1.15",
"1.8"
],
"pandas": [],
"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": [
"1.6",
"1.10",
"1.4",
"1.3",
"1.9",
"0.19",
"1.5",
"0.18",
"1.7",
"1.0",
"0.17",
"1.2",
"1.8"
],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"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": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
sainjusajan/django-oscar | [
"466e8edc807be689b0a28c9e525c8323cc48b8e1"
] | [
"oscar/lib/python2.7/site-packages/IPython/core/pylabtools.py"
] | [
"# -*- coding: utf-8 -*-\r\n\"\"\"Pylab (matplotlib) support utilities.\"\"\"\r\nfrom __future__ import print_function\r\n\r\n# Copyright (c) IPython Development Team.\r\n# Distributed under the terms of the Modified BSD License.\r\n\r\nfrom io import BytesIO\r\n\r\nfrom IPython.core.display import _pngxy\r\nfrom IPython.utils.decorators import flag_calls\r\nfrom IPython.utils import py3compat\r\n\r\n# If user specifies a GUI, that dictates the backend, otherwise we read the\r\n# user's mpl default from the mpl rc structure\r\nbackends = {'tk': 'TkAgg',\r\n 'gtk': 'GTKAgg',\r\n 'gtk3': 'GTK3Agg',\r\n 'wx': 'WXAgg',\r\n 'qt': 'Qt4Agg', # qt3 not supported\r\n 'qt4': 'Qt4Agg',\r\n 'qt5': 'Qt5Agg',\r\n 'osx': 'MacOSX',\r\n 'nbagg': 'nbAgg',\r\n 'notebook': 'nbAgg',\r\n 'agg': 'agg',\r\n 'inline': 'module://ipykernel.pylab.backend_inline',\r\n 'ipympl': 'module://ipympl.backend_nbagg',\r\n}\r\n\r\n# We also need a reverse backends2guis mapping that will properly choose which\r\n# GUI support to activate based on the desired matplotlib backend. For the\r\n# most part it's just a reverse of the above dict, but we also need to add a\r\n# few others that map to the same GUI manually:\r\nbackend2gui = dict(zip(backends.values(), backends.keys()))\r\n# Our tests expect backend2gui to just return 'qt'\r\nbackend2gui['Qt4Agg'] = 'qt'\r\n# In the reverse mapping, there are a few extra valid matplotlib backends that\r\n# map to the same GUI support\r\nbackend2gui['GTK'] = backend2gui['GTKCairo'] = 'gtk'\r\nbackend2gui['GTK3Cairo'] = 'gtk3'\r\nbackend2gui['WX'] = 'wx'\r\nbackend2gui['CocoaAgg'] = 'osx'\r\n# And some backends that don't need GUI integration\r\ndel backend2gui['nbAgg']\r\ndel backend2gui['agg']\r\ndel backend2gui['module://ipykernel.pylab.backend_inline']\r\n\r\n#-----------------------------------------------------------------------------\r\n# Matplotlib utilities\r\n#-----------------------------------------------------------------------------\r\n\r\n\r\ndef getfigs(*fig_nums):\r\n \"\"\"Get a list of matplotlib figures by figure numbers.\r\n\r\n If no arguments are given, all available figures are returned. If the\r\n argument list contains references to invalid figures, a warning is printed\r\n but the function continues pasting further figures.\r\n\r\n Parameters\r\n ----------\r\n figs : tuple\r\n A tuple of ints giving the figure numbers of the figures to return.\r\n \"\"\"\r\n from matplotlib._pylab_helpers import Gcf\r\n if not fig_nums:\r\n fig_managers = Gcf.get_all_fig_managers()\r\n return [fm.canvas.figure for fm in fig_managers]\r\n else:\r\n figs = []\r\n for num in fig_nums:\r\n f = Gcf.figs.get(num)\r\n if f is None:\r\n print('Warning: figure %s not available.' % num)\r\n else:\r\n figs.append(f.canvas.figure)\r\n return figs\r\n\r\n\r\ndef figsize(sizex, sizey):\r\n \"\"\"Set the default figure size to be [sizex, sizey].\r\n\r\n This is just an easy to remember, convenience wrapper that sets::\r\n\r\n matplotlib.rcParams['figure.figsize'] = [sizex, sizey]\r\n \"\"\"\r\n import matplotlib\r\n matplotlib.rcParams['figure.figsize'] = [sizex, sizey]\r\n\r\n\r\ndef print_figure(fig, fmt='png', bbox_inches='tight', **kwargs):\r\n \"\"\"Print a figure to an image, and return the resulting file data\r\n \r\n Returned data will be bytes unless ``fmt='svg'``,\r\n in which case it will be unicode.\r\n \r\n Any keyword args are passed to fig.canvas.print_figure,\r\n such as ``quality`` or ``bbox_inches``.\r\n \"\"\"\r\n from matplotlib import rcParams\r\n # When there's an empty figure, we shouldn't return anything, otherwise we\r\n # get big blank areas in the qt console.\r\n if not fig.axes and not fig.lines:\r\n return\r\n\r\n dpi = fig.dpi\r\n if fmt == 'retina':\r\n dpi = dpi * 2\r\n fmt = 'png'\r\n \r\n # build keyword args\r\n kw = dict(\r\n format=fmt,\r\n facecolor=fig.get_facecolor(),\r\n edgecolor=fig.get_edgecolor(),\r\n dpi=dpi,\r\n bbox_inches=bbox_inches,\r\n )\r\n # **kwargs get higher priority\r\n kw.update(kwargs)\r\n \r\n bytes_io = BytesIO()\r\n fig.canvas.print_figure(bytes_io, **kw)\r\n data = bytes_io.getvalue()\r\n if fmt == 'svg':\r\n data = data.decode('utf-8')\r\n return data\r\n \r\ndef retina_figure(fig, **kwargs):\r\n \"\"\"format a figure as a pixel-doubled (retina) PNG\"\"\"\r\n pngdata = print_figure(fig, fmt='retina', **kwargs)\r\n # Make sure that retina_figure acts just like print_figure and returns\r\n # None when the figure is empty.\r\n if pngdata is None:\r\n return\r\n w, h = _pngxy(pngdata)\r\n metadata = dict(width=w//2, height=h//2)\r\n return pngdata, metadata\r\n\r\n# We need a little factory function here to create the closure where\r\n# safe_execfile can live.\r\ndef mpl_runner(safe_execfile):\r\n \"\"\"Factory to return a matplotlib-enabled runner for %run.\r\n\r\n Parameters\r\n ----------\r\n safe_execfile : function\r\n This must be a function with the same interface as the\r\n :meth:`safe_execfile` method of IPython.\r\n\r\n Returns\r\n -------\r\n A function suitable for use as the ``runner`` argument of the %run magic\r\n function.\r\n \"\"\"\r\n \r\n def mpl_execfile(fname,*where,**kw):\r\n \"\"\"matplotlib-aware wrapper around safe_execfile.\r\n\r\n Its interface is identical to that of the :func:`execfile` builtin.\r\n\r\n This is ultimately a call to execfile(), but wrapped in safeties to\r\n properly handle interactive rendering.\"\"\"\r\n\r\n import matplotlib\r\n import matplotlib.pyplot as plt\r\n\r\n #print '*** Matplotlib runner ***' # dbg\r\n # turn off rendering until end of script\r\n is_interactive = matplotlib.rcParams['interactive']\r\n matplotlib.interactive(False)\r\n safe_execfile(fname,*where,**kw)\r\n matplotlib.interactive(is_interactive)\r\n # make rendering call now, if the user tried to do it\r\n if plt.draw_if_interactive.called:\r\n plt.draw()\r\n plt.draw_if_interactive.called = False\r\n\r\n # re-draw everything that is stale\r\n try:\r\n da = plt.draw_all\r\n except AttributeError:\r\n pass\r\n else:\r\n da()\r\n\r\n return mpl_execfile\r\n\r\n\r\ndef _reshow_nbagg_figure(fig):\r\n \"\"\"reshow an nbagg figure\"\"\"\r\n try:\r\n reshow = fig.canvas.manager.reshow\r\n except AttributeError:\r\n raise NotImplementedError()\r\n else:\r\n reshow()\r\n\r\n\r\ndef select_figure_formats(shell, formats, **kwargs):\r\n \"\"\"Select figure formats for the inline backend.\r\n\r\n Parameters\r\n ==========\r\n shell : InteractiveShell\r\n The main IPython instance.\r\n formats : str or set\r\n One or a set of figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'.\r\n **kwargs : any\r\n Extra keyword arguments to be passed to fig.canvas.print_figure.\r\n \"\"\"\r\n import matplotlib\r\n from matplotlib.figure import Figure\r\n\r\n svg_formatter = shell.display_formatter.formatters['image/svg+xml']\r\n png_formatter = shell.display_formatter.formatters['image/png']\r\n jpg_formatter = shell.display_formatter.formatters['image/jpeg']\r\n pdf_formatter = shell.display_formatter.formatters['application/pdf']\r\n\r\n if isinstance(formats, py3compat.string_types):\r\n formats = {formats}\r\n # cast in case of list / tuple\r\n formats = set(formats)\r\n\r\n [ f.pop(Figure, None) for f in shell.display_formatter.formatters.values() ]\r\n mplbackend = matplotlib.get_backend().lower()\r\n if mplbackend == 'nbagg' or mplbackend == 'module://ipympl.backend_nbagg':\r\n formatter = shell.display_formatter.ipython_display_formatter\r\n formatter.for_type(Figure, _reshow_nbagg_figure)\r\n\r\n supported = {'png', 'png2x', 'retina', 'jpg', 'jpeg', 'svg', 'pdf'}\r\n bad = formats.difference(supported)\r\n if bad:\r\n bs = \"%s\" % ','.join([repr(f) for f in bad])\r\n gs = \"%s\" % ','.join([repr(f) for f in supported])\r\n raise ValueError(\"supported formats are: %s not %s\" % (gs, bs))\r\n \r\n if 'png' in formats:\r\n png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))\r\n if 'retina' in formats or 'png2x' in formats:\r\n png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs))\r\n if 'jpg' in formats or 'jpeg' in formats:\r\n jpg_formatter.for_type(Figure, lambda fig: print_figure(fig, 'jpg', **kwargs))\r\n if 'svg' in formats:\r\n svg_formatter.for_type(Figure, lambda fig: print_figure(fig, 'svg', **kwargs))\r\n if 'pdf' in formats:\r\n pdf_formatter.for_type(Figure, lambda fig: print_figure(fig, 'pdf', **kwargs))\r\n\r\n#-----------------------------------------------------------------------------\r\n# Code for initializing matplotlib and importing pylab\r\n#-----------------------------------------------------------------------------\r\n\r\n\r\ndef find_gui_and_backend(gui=None, gui_select=None):\r\n \"\"\"Given a gui string return the gui and mpl backend.\r\n\r\n Parameters\r\n ----------\r\n gui : str\r\n Can be one of ('tk','gtk','wx','qt','qt4','inline').\r\n gui_select : str\r\n Can be one of ('tk','gtk','wx','qt','qt4','inline').\r\n This is any gui already selected by the shell.\r\n\r\n Returns\r\n -------\r\n A tuple of (gui, backend) where backend is one of ('TkAgg','GTKAgg',\r\n 'WXAgg','Qt4Agg','module://ipykernel.pylab.backend_inline').\r\n \"\"\"\r\n\r\n import matplotlib\r\n\r\n if gui and gui != 'auto':\r\n # select backend based on requested gui\r\n backend = backends[gui]\r\n else:\r\n # We need to read the backend from the original data structure, *not*\r\n # from mpl.rcParams, since a prior invocation of %matplotlib may have\r\n # overwritten that.\r\n # WARNING: this assumes matplotlib 1.1 or newer!!\r\n backend = matplotlib.rcParamsOrig['backend']\r\n # In this case, we need to find what the appropriate gui selection call\r\n # should be for IPython, so we can activate inputhook accordingly\r\n gui = backend2gui.get(backend, None)\r\n\r\n # If we have already had a gui active, we need it and inline are the\r\n # ones allowed.\r\n if gui_select and gui != gui_select:\r\n gui = gui_select\r\n backend = backends[gui]\r\n\r\n return gui, backend\r\n\r\n\r\ndef activate_matplotlib(backend):\r\n \"\"\"Activate the given backend and set interactive to True.\"\"\"\r\n\r\n import matplotlib\r\n matplotlib.interactive(True)\r\n \r\n # Matplotlib had a bug where even switch_backend could not force\r\n # the rcParam to update. This needs to be set *before* the module\r\n # magic of switch_backend().\r\n matplotlib.rcParams['backend'] = backend\r\n\r\n import matplotlib.pyplot\r\n matplotlib.pyplot.switch_backend(backend)\r\n\r\n # This must be imported last in the matplotlib series, after\r\n # backend/interactivity choices have been made\r\n import matplotlib.pyplot as plt\r\n\r\n plt.show._needmain = False\r\n # We need to detect at runtime whether show() is called by the user.\r\n # For this, we wrap it into a decorator which adds a 'called' flag.\r\n plt.draw_if_interactive = flag_calls(plt.draw_if_interactive)\r\n\r\n\r\ndef import_pylab(user_ns, import_all=True):\r\n \"\"\"Populate the namespace with pylab-related values.\r\n \r\n Imports matplotlib, pylab, numpy, and everything from pylab and numpy.\r\n \r\n Also imports a few names from IPython (figsize, display, getfigs)\r\n \r\n \"\"\"\r\n\r\n # Import numpy as np/pyplot as plt are conventions we're trying to\r\n # somewhat standardize on. Making them available to users by default\r\n # will greatly help this.\r\n s = (\"import numpy\\n\"\r\n \"import matplotlib\\n\"\r\n \"from matplotlib import pylab, mlab, pyplot\\n\"\r\n \"np = numpy\\n\"\r\n \"plt = pyplot\\n\"\r\n )\r\n exec(s, user_ns)\r\n \r\n if import_all:\r\n s = (\"from matplotlib.pylab import *\\n\"\r\n \"from numpy import *\\n\")\r\n exec(s, user_ns)\r\n \r\n # IPython symbols to add\r\n user_ns['figsize'] = figsize\r\n from IPython.core.display import display\r\n # Add display and getfigs to the user's namespace\r\n user_ns['display'] = display\r\n user_ns['getfigs'] = getfigs\r\n\r\n\r\ndef configure_inline_support(shell, backend):\r\n \"\"\"Configure an IPython shell object for matplotlib use.\r\n\r\n Parameters\r\n ----------\r\n shell : InteractiveShell instance\r\n\r\n backend : matplotlib backend\r\n \"\"\"\r\n # If using our svg payload backend, register the post-execution\r\n # function that will pick up the results for display. This can only be\r\n # done with access to the real shell object.\r\n\r\n # Note: if we can't load the inline backend, then there's no point\r\n # continuing (such as in terminal-only shells in environments without\r\n # zeromq available).\r\n try:\r\n from ipykernel.pylab.backend_inline import InlineBackend\r\n except ImportError:\r\n return\r\n import matplotlib\r\n\r\n cfg = InlineBackend.instance(parent=shell)\r\n cfg.shell = shell\r\n if cfg not in shell.configurables:\r\n shell.configurables.append(cfg)\r\n\r\n if backend == backends['inline']:\r\n from ipykernel.pylab.backend_inline import flush_figures\r\n shell.events.register('post_execute', flush_figures)\r\n\r\n # Save rcParams that will be overwrittern\r\n shell._saved_rcParams = dict()\r\n for k in cfg.rc:\r\n shell._saved_rcParams[k] = matplotlib.rcParams[k]\r\n # load inline_rc\r\n matplotlib.rcParams.update(cfg.rc)\r\n new_backend_name = \"inline\"\r\n else:\r\n from ipykernel.pylab.backend_inline import flush_figures\r\n try:\r\n shell.events.unregister('post_execute', flush_figures)\r\n except ValueError:\r\n pass\r\n if hasattr(shell, '_saved_rcParams'):\r\n matplotlib.rcParams.update(shell._saved_rcParams)\r\n del shell._saved_rcParams\r\n new_backend_name = \"other\"\r\n\r\n # only enable the formats once -> don't change the enabled formats (which the user may\r\n # has changed) when getting another \"%matplotlib inline\" call.\r\n # See https://github.com/ipython/ipykernel/issues/29\r\n cur_backend = getattr(configure_inline_support, \"current_backend\", \"unset\")\r\n if new_backend_name != cur_backend:\r\n # Setup the default figure format\r\n select_figure_formats(shell, cfg.figure_formats, **cfg.print_figure_kwargs)\r\n configure_inline_support.current_backend = new_backend_name\r\n"
] | [
[
"matplotlib._pylab_helpers.Gcf.get_all_fig_managers",
"matplotlib.pyplot.switch_backend",
"matplotlib.pyplot.draw",
"matplotlib.get_backend",
"matplotlib.rcParams.update",
"matplotlib.interactive",
"matplotlib._pylab_helpers.Gcf.figs.get"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
sherrytp/TradingEvolved | [
"4bc9cc18244954bff37a80f67cce658bd0802b5d",
"4bc9cc18244954bff37a80f67cce658bd0802b5d",
"4bc9cc18244954bff37a80f67cce658bd0802b5d"
] | [
"examples/old/zipline_alpaca2.py",
"examples/old/zipline_model5.py",
"examples/quantinsti/svm_momentum.py"
] | [
"# https://github.com/RomanMichaelPaolucci/AI_Stock_Trading/blob/master/IBM.csv\nimport abc\nimport threading\nimport time\nimport pandas as pd\nimport numpy as np\nfrom keras.layers import Dense\nfrom keras.models import Sequential, model_from_json\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report\nfrom alpaca_trade_api import REST\n\n\nclass AlpacaPaperSocket(REST):\n def __init__(self):\n super().__init__(\n key_id='PKPO0ZH3XTVB336B7TEO',\n secret_key='gcs4U2Hp/ACI4A5UwYjYugrPqB2odD/m40Zuz5qw',\n base_url='https://paper-api.alpaca.markets'\n )\n\n\nclass TradingSystem(abc.ABC):\n\n def __init__(self, api, symbol, time_frame, system_id, system_label):\n # Connect to api\n # Connect to BrokenPipeError\n # Save fields to class\n self.api = api\n self.symbol = symbol\n self.time_frame = time_frame\n self.system_id = system_id\n self.system_label = system_label\n thread = threading.Thread(target=self.system_loop)\n thread.start()\n\n @abc.abstractmethod\n def place_buy_order(self):\n pass\n\n @abc.abstractmethod\n def place_sell_order(self):\n pass\n\n @abc.abstractmethod\n def system_loop(self):\n pass\n\n\n# Class to develop your AI portfolio manager\nclass PMModelDevelopment:\n\n def __init__(self):\n # Read your data in and split the dependent and independent\n data = pd.read_csv('IBM.csv')\n X = data['Delta Close']\n y = data.drop(['Delta Close'], axis=1)\n\n # Train test spit\n X_train, X_test, y_train, y_test = train_test_split(X, y)\n\n # Create the sequential\n network = Sequential()\n\n # Create the structure of the neural network\n network.add(Dense(1, input_shape=(1,), activation='tanh'))\n network.add(Dense(3, activation='tanh'))\n network.add(Dense(3, activation='tanh'))\n network.add(Dense(3, activation='tanh'))\n network.add(Dense(1, activation='tanh'))\n\n # Compile the model\n network.compile(\n optimizer='rmsprop',\n loss='hinge',\n metrics=['accuracy']\n )\n # Train the model\n network.fit(X_train.values, y_train.values, epochs=100)\n\n # Evaluate the predictions of the model\n y_pred = network.predict(X_test.values)\n y_pred = np.around(y_pred, 0)\n print(classification_report(y_test, y_pred))\n\n # Save structure to json\n model = network.to_json()\n with open(\"model.json\", \"w\") as json_file:\n json_file.write(model)\n\n # Save weights to HDF5\n network.save_weights(\"weights.h5\")\n\n\n# AI Portfolio Manager\nclass PortfolioManagementModel:\n\n def __init__(self):\n # Data in to test that the saving of weights worked\n data = pd.read_csv('IBM.csv')\n X = data['Delta Close']\n y = data.drop(['Delta Close'], axis=1)\n\n # Read structure from json\n json_file = open('model.json', 'r')\n json = json_file.read()\n json_file.close()\n self.network = model_from_json(json)\n\n # Read weights from HDF5\n self.network.load_weights(\"weights.h5\")\n\n # Verify weights and structure are loaded\n y_pred = self.network.predict(X.values)\n y_pred = np.around(y_pred, 0)\n print(classification_report(y, y_pred))\n\nPortfolioManagementModel()\n\n\n# in implemenation create a vector to store data...\nclass PortfolioManagementSystem(TradingSystem):\n\n def __init__(self):\n super().__init__(AlpacaPaperSocket(), 'IBM', 86400, 1, 'AI_PM')\n self.AI = PortfolioManagementModel()\n\n def place_buy_order(self):\n self.api.submit_order(\n symbol='IBM',\n qty=1,\n side='buy',\n type='market',\n time_in_force='day',\n )\n\n def place_sell_order(self):\n self.api.submit_order(\n symbol='IBM',\n qty=1,\n side='sell',\n type='market',\n time_in_force='day',\n )\n\n def system_loop(self):\n # Variables for weekly close\n this_weeks_close = 0\n last_weeks_close = 0\n delta = 0\n day_count = 0\n while(True):\n # Wait a day to request more data\n time.sleep(1440)\n # Request EoD data for IBM\n data_req = self.api.get_barset('IBM', timeframe='1D', limit=1).df\n # Construct dataframe to predict\n x = pd.DataFrame(\n data=[[\n data_req['IBM']['close'][0]]], columns='Close'.split()\n )\n if(day_count == 7):\n day_count = 0\n last_weeks_close = this_weeks_close\n this_weeks_close = x['Close']\n delta = this_weeks_close - last_weeks_close\n\n # AI choosing to buy, sell, or hold\n if np.around(self.AI.network.predict([delta])) <= -.5:\n self.place_sell_order()\n\n elif np.around(self.AI.network.predict([delta]) >= .5):\n self.place_buy_order()\n\n\nPortfolioManagementSystem()\n",
"from zipline.api import order_target_percent, order_target, symbol, record\nfrom pandas_datareader import data as pdr\nimport matplotlib.pyplot as plt\nfrom datetime import datetime\nimport numpy as np\nimport pandas as pd\n\naapl = pdr.get_data_yahoo('AAPL', start=datetime(2006, 10, 1), end=datetime(2012, 1, 1))\n# Initialize the short and long windows\nshort_window = 40\nlong_window = 100\n\n# Initialize the `signals` DataFrame with the `signal` column\nsignals = pd.DataFrame(index=aapl.index)\nsignals['signal'] = 0.0\n\n# Create short simple moving average over the short window\nsignals['short_mavg'] = aapl['Close'].rolling(window=short_window, min_periods=1, center=False).mean()\n\n# Create long simple moving average over the long window\nsignals['long_mavg'] = aapl['Close'].rolling(window=long_window, min_periods=1, center=False).mean()\n\n# Create signals\nsignals['signal'][short_window:] = np.where(signals['short_mavg'][short_window:] > signals['long_mavg'][short_window:], 1.0, 0.0)\n\n# Generate trading orders\nsignals['positions'] = signals['signal'].diff()\nprint(signals)\n# Initialize the plot figure\nfig = plt.figure()\n\n# Add a subplot and label for y-axis\nax1 = fig.add_subplot(111, ylabel='Price in $')\n\n# Plot the closing price\naapl['Close'].plot(ax=ax1, color='r', lw=2.)\n\n# Plot the short and long moving averages\nsignals[['short_mavg', 'long_mavg']].plot(ax=ax1, lw=2.)\n\n# Plot the buy signals\nax1.plot(signals.loc[signals.positions == 1.0].index,\n signals.short_mavg[signals.positions == 1.0],\n '^', markersize=10, color='m')\n\n# Plot the sell signals\nax1.plot(signals.loc[signals.positions == -1.0].index,\n signals.short_mavg[signals.positions == -1.0],\n 'v', markersize=10, color='k')\n\n# Show the plot\nplt.show()\n# Set the initial capital\ninitial_capital = float(100000.0)\n\n# Create a DataFrame `positions`\npositions = pd.DataFrame(index=signals.index).fillna(0.0)\n\n# Buy a 100 shares\npositions['AAPL'] = 100 * signals['signal']\n\n# Initialize the portfolio with value owned\nportfolio = positions.multiply(aapl['Adj Close'], axis=0)\n\n# Store the difference in shares owned\npos_diff = positions.diff()\n\n# Add `holdings` to portfolio\nportfolio['holdings'] = (positions.multiply(aapl['Adj Close'], axis=0)).sum(axis=1)\n\n# Add `cash` to portfolio\nportfolio['cash'] = initial_capital - (pos_diff.multiply(aapl['Adj Close'], axis=0)).sum(axis=1).cumsum()\n\n# Add `total` to portfolio\nportfolio['total'] = portfolio['cash'] + portfolio['holdings']\n\n# Add `returns` to portfolio\nportfolio['returns'] = portfolio['total'].pct_change()\n\nfig = plt.figure()\n\nax1 = fig.add_subplot(111, ylabel='Portfolio value in $')\n\n# Plot the equity curve in dollars\nportfolio['total'].plot(ax=ax1, lw=2.)\n\n# Plot the \"buy\" trades against the equity curve\nax1.plot(portfolio.loc[signals.positions == 1.0].index,\n portfolio.total[signals.positions == 1.0],\n '^', markersize=10, color='m')\n\n# Plot the \"sell\" trades against the equity curve\nax1.plot(portfolio.loc[signals.positions == -1.0].index,\n portfolio.total[signals.positions == -1.0],\n 'v', markersize=10, color='k')\n\n# Show the plot\nplt.show()\n\ndef initialize(context):\n context.sym = symbol('AAPL')\n context.i = 0\n\ndef handle_data(context, data):\n # skip first 300 days to get full windows\n context.i += 1\n if context.i < 300:\n return\n\n short_mavg = data.history(context.sym, 'price', 100, '1d').mean()\n long_mavg = data.history(context.sym, 'price', 300, '1d').mean()\n if short_mavg > long_mavg:\n order_target(context.sym, 100)\n elif short_mavg < long_mavg:\n order_target(context.sym, 0)\n\n record(AAPL=data.current(context.sym, 'price'),\n short_mavg=short_mavg, long_mavg=long_mavg)",
"\"\"\"\nsvm_momentum.py\n===========================\n author: erichamer\n\"\"\"\nimport numpy as np\nfrom sklearn import svm\n\n\ndef myTradingSystem(DATE, OPEN, HIGH, LOW, CLOSE, VOL, OI, P, R, RINFO, exposure, equity, settings):\n\n def predict(momentum, CLOSE, lookback, gap, dimension):\n '''\n y = 1 if the price is up and y = -1 if the price is down\n '''\n X = np.concatenate([momentum[i:i + dimension] for i in range(lookback - gap - dimension)], axis=1).T\n y = np.sign((CLOSE[dimension+gap:] - CLOSE[dimension+gap-1:-1]).T[0])\n y[y==0] = 1\n\n # fit the classifier with the lookback data\n clf = svm.SVC()\n clf.fit(X, y)\n\n # now predict on the live data\n return clf.predict(momentum[-dimension:].T)\n\n n_markets = len(settings['markets'])\n lookback = settings['lookback']\n dimension = settings['dimension']\n gap = settings['gap']\n\n pos = np.zeros((1, n_markets), dtype=np.float)\n\n momentum = (CLOSE[gap:, :] - CLOSE[:-gap, :]) / CLOSE[:-gap, :]\n\n for market in range(n_markets):\n try:\n pos[0, market] = predict(momentum[:, market].reshape(-1, 1), CLOSE[:, market].reshape(-1, 1), lookback,\n gap, dimension)\n except ValueError as e:\n pos[0, market] = 0\n return pos, settings\n\n\ndef mySettings():\n \"\"\" Define your trading system settings here \"\"\"\n\n settings = {}\n settings['markets'] = ['CASH', 'F_AD', 'F_AE', 'F_AH', 'F_AX', 'F_BC', 'F_BG', 'F_BO', 'F_BP', 'F_C', 'F_CA',\n 'F_CC', 'F_CD', 'F_CF', 'F_CL', 'F_CT', 'F_DL', 'F_DM', 'F_DT', 'F_DX', 'F_DZ', 'F_EB',\n 'F_EC', 'F_ED', 'F_ES', 'F_F', 'F_FB', 'F_FC', 'F_FL', 'F_FM', 'F_FP', 'F_FV', 'F_FY',\n 'F_GC', 'F_GD', 'F_GS', 'F_GX', 'F_HG', 'F_HO', 'F_HP', 'F_JY', 'F_KC', 'F_LB', 'F_LC',\n 'F_LN', 'F_LQ', 'F_LR', 'F_LU', 'F_LX', 'F_MD', 'F_MP', 'F_ND', 'F_NG', 'F_NQ', 'F_NR',\n 'F_NY', 'F_O', 'F_OJ', 'F_PA', 'F_PL', 'F_PQ', 'F_RB', 'F_RF', 'F_RP', 'F_RR', 'F_RU',\n 'F_RY', 'F_S', 'F_SB', 'F_SF', 'F_SH', 'F_SI', 'F_SM', 'F_SS', 'F_SX', 'F_TR', 'F_TU',\n 'F_TY', 'F_UB', 'F_US', 'F_UZ', 'F_VF', 'F_VT', 'F_VW', 'F_VX', 'F_W', 'F_XX', 'F_YM',\n 'F_ZQ']\n\n settings['lookback'] = 252\n settings['budget'] = 10 ** 6\n settings['slippage'] = 0.05\n\n settings['gap'] = 20\n settings['dimension'] = 5\n\n return settings\n\n\nif __name__ == '__main__':\n from quantiacsToolbox.quantiacsToolbox import runts\n runts(__file__)\n"
] | [
[
"numpy.around",
"pandas.read_csv",
"sklearn.metrics.classification_report",
"sklearn.model_selection.train_test_split"
],
[
"matplotlib.pyplot.show",
"numpy.where",
"pandas.DataFrame",
"matplotlib.pyplot.figure"
],
[
"numpy.sign",
"numpy.zeros",
"sklearn.svm.SVC"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"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": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
amelieEmily/RobustDARTS | [
"b26e127c6e9c330258786f5eb77b17d367f546ff",
"b26e127c6e9c330258786f5eb77b17d367f546ff"
] | [
"src/utils.py",
"src/evaluation/eval_imagenet.py"
] | [
"import os\nimport yaml\nimport numpy as np\nimport torch\nimport shutil\nimport torchvision.transforms as transforms\nfrom torch.autograd import Variable\nfrom collections import namedtuple\n\nclass MyDumper(yaml.Dumper):\n\n def increase_indent(self, flow=False, indentless=False):\n return super(MyDumper, self).increase_indent(flow, False)\n\n\nGenotype = namedtuple('Genotype', 'normal normal_concat reduce reduce_concat')\n\nPRIMITIVES = [\n 'none',\n 'noise',\n 'max_pool_3x3',\n 'avg_pool_3x3',\n 'skip_connect',\n 'sep_conv_3x3',\n 'sep_conv_5x5',\n 'dil_conv_3x3',\n 'dil_conv_5x5'\n]\n\n\nclass EVLocalAvg(object):\n def __init__(self, window=5, ev_freq=2, total_epochs=50):\n \"\"\" Keep track of the eigenvalues local average.\n\n Args:\n window (int): number of elements used to compute local average.\n Default: 5\n ev_freq (int): frequency used to compute eigenvalues. Default:\n every 2 epochs\n total_epochs (int): total number of epochs that DARTS runs.\n Default: 50\n\n \"\"\"\n self.window = window\n self.ev_freq = ev_freq\n self.epochs = total_epochs\n\n self.stop_search = False\n self.stop_epoch = total_epochs - 1\n self.stop_genotype = None\n\n self.ev = []\n self.ev_local_avg = []\n self.genotypes = {}\n self.la_epochs = {}\n\n # start and end index of the local average window\n self.la_start_idx = 0\n self.la_end_idx = self.window\n\n def reset(self):\n self.ev = []\n self.ev_local_avg = []\n self.genotypes = {}\n self.la_epochs = {}\n\n def update(self, epoch, ev, genotype):\n \"\"\" Method to update the local average list.\n\n Args:\n epoch (int): current epoch\n ev (float): current dominant eigenvalue\n genotype (namedtuple): current genotype\n\n \"\"\"\n self.ev.append(ev)\n self.genotypes.update({epoch: genotype})\n # set the stop_genotype to the current genotype in case the early stop\n # procedure decides not to early stop\n self.stop_genotype = genotype\n\n # since the local average computation starts after the dominant\n # eigenvalue in the first epoch is already computed we have to wait\n # at least until we have 3 eigenvalues in the list.\n if (len(self.ev) >= int(np.ceil(self.window/2))) and (epoch <\n self.epochs - 1):\n # start sliding the window as soon as the number of eigenvalues in\n # the list becomes equal to the window size\n if len(self.ev) < self.window:\n self.ev_local_avg.append(np.mean(self.ev))\n else:\n assert len(self.ev[self.la_start_idx: self.la_end_idx]) == self.window\n self.ev_local_avg.append(np.mean(self.ev[self.la_start_idx:\n self.la_end_idx]))\n self.la_start_idx += 1\n self.la_end_idx += 1\n\n # keep track of the offset between the current epoch and the epoch\n # corresponding to the local average. NOTE: in the end the size of\n # self.ev and self.ev_local_avg should be equal\n self.la_epochs.update({epoch: int(epoch -\n int(self.ev_freq*np.floor(self.window/2)))})\n\n elif len(self.ev) < int(np.ceil(self.window/2)):\n self.la_epochs.update({epoch: -1})\n\n # since there is an offset between the current epoch and the local\n # average epoch, loop in the last epoch to compute the local average of\n # these number of elements: window, window - 1, window - 2, ..., ceil(window/2)\n elif epoch == self.epochs - 1:\n for i in range(int(np.ceil(self.window/2))):\n assert len(self.ev[self.la_start_idx: self.la_end_idx]) == self.window - i\n self.ev_local_avg.append(np.mean(self.ev[self.la_start_idx:\n self.la_end_idx + 1]))\n self.la_start_idx += 1\n\n def early_stop(self, epoch, factor=1.3, es_start_epoch=10, delta=4):\n \"\"\" Early stopping criterion\n\n Args:\n epoch (int): current epoch\n factor (float): threshold factor for the ration between the current\n and prefious eigenvalue. Default: 1.3\n es_start_epoch (int): until this epoch do not consider early\n stopping. Default: 20\n delta (int): factor influencing which previous local average we\n consider for early stopping. Default: 2\n \"\"\"\n if int(self.la_epochs[epoch] - self.ev_freq*delta) >= es_start_epoch:\n # the current local average corresponds to\n # epoch - int(self.ev_freq*np.floor(self.window/2))\n current_la = self.ev_local_avg[-1]\n # by default take the local average corresponding to epoch\n # delta*self.ev_freq\n previous_la = self.ev_local_avg[-1 - delta]\n\n self.stop_search = current_la / previous_la > factor\n if self.stop_search:\n self.stop_epoch = int(self.la_epochs[epoch] - self.ev_freq*delta)\n self.stop_genotype = self.genotypes[self.stop_epoch]\n\n\nclass AvgrageMeter(object):\n\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.avg = 0\n self.sum = 0\n self.cnt = 0\n\n def update(self, val, n=1):\n self.sum += val * n\n self.cnt += n\n self.avg = self.sum / self.cnt\n\n\ndef accuracy(output, target, topk=(1,)):\n maxk = max(topk)\n batch_size = target.size(0)\n\n _, pred = output.topk(maxk, 1, True, True)\n pred = pred.t()\n correct = pred.eq(target.view(1, -1).expand_as(pred))\n\n res = []\n for k in topk:\n correct_k = correct[:k].view(-1).float().sum(0)\n res.append(correct_k.mul_(100.0/batch_size))\n return res\n\ndef write_yaml_results_eval(args, results_file, result_to_log):\n setting = '_'.join([args.space, args.dataset])\n regularization = '_'.join(\n [str(args.search_dp), str(args.search_wd)]\n )\n results_file = os.path.join(args._save, results_file+'.yaml')\n\n try:\n with open(results_file, 'r') as f:\n result = yaml.load(f, Loader=yaml.Loader)\n if setting in result.keys():\n if regularization in result[setting].keys():\n if args.search_task_id in result[setting][regularization]:\n result[setting][regularization][args.search_task_id].append(result_to_log)\n else:\n result[setting][regularization].update({args.search_task_id:\n [result_to_log]})\n else:\n result[setting].update({regularization: {args.search_task_id:\n [result_to_log]}})\n else:\n result.update({setting: {regularization: {args.search_task_id:\n [result_to_log]}}})\n with open(results_file, 'w') as f:\n yaml.dump(result, f, Dumper=MyDumper, default_flow_style=False)\n except (AttributeError, FileNotFoundError) as e:\n result = {\n setting: {\n regularization: {\n args.search_task_id: [result_to_log]\n }\n }\n }\n with open(results_file, 'w') as f:\n yaml.dump(result, f, Dumper=MyDumper, default_flow_style=False)\n\ndef write_yaml_results(args, results_file, result_to_log):\n setting = '_'.join([args.space, args.dataset])\n regularization = '_'.join(\n [str(args.drop_path_prob), str(args.weight_decay)]\n )\n results_file = os.path.join(args._save, results_file+'.yaml')\n\n try:\n with open(results_file, 'r') as f:\n result = yaml.load(f, Loader=yaml.Loader)\n if setting in result.keys():\n if regularization in result[setting].keys():\n result[setting][regularization].update({args.task_id: result_to_log})\n else:\n result[setting].update({regularization: {args.task_id: result_to_log}})\n else:\n result.update({setting: {regularization: {args.task_id: result_to_log}}})\n with open(results_file, 'w') as f:\n yaml.dump(result, f, Dumper=MyDumper, default_flow_style=False)\n except (AttributeError, FileNotFoundError) as e:\n result = {\n setting: {\n regularization: {\n args.task_id: result_to_log\n }\n }\n }\n with open(results_file, 'w') as f:\n yaml.dump(result, f, Dumper=MyDumper, default_flow_style=False)\n\n\nclass Cutout(object):\n def __init__(self, length, prob=1.0):\n self.length = length\n self.prob = prob\n\n def __call__(self, img):\n if np.random.binomial(1, self.prob):\n h, w = img.size(1), img.size(2)\n mask = np.ones((h, w), np.float32)\n y = np.random.randint(h)\n x = np.random.randint(w)\n\n y1 = np.clip(y - self.length // 2, 0, h)\n y2 = np.clip(y + self.length // 2, 0, h)\n x1 = np.clip(x - self.length // 2, 0, w)\n x2 = np.clip(x + self.length // 2, 0, w)\n\n mask[y1: y2, x1: x2] = 0.\n mask = torch.from_numpy(mask)\n mask = mask.expand_as(img)\n img *= mask\n return img\n\ndef _data_transforms_svhn(args):\n SVHN_MEAN = [0.4377, 0.4438, 0.4728]\n SVHN_STD = [0.1980, 0.2010, 0.1970]\n\n train_transform = transforms.Compose([\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize(SVHN_MEAN, SVHN_STD),\n ])\n if args.cutout:\n train_transform.transforms.append(Cutout(args.cutout_length,\n args.cutout_prob))\n\n valid_transform = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(SVHN_MEAN, SVHN_STD),\n ])\n return train_transform, valid_transform\n\ndef _data_transforms_dr_detection(args):\n\n DR_DETECTION_MEAN = [0.42, 0.22, 0.075]\n DR_DETECTION_STD = [0.27, 0.15, 0.081]\n if args.is_eval:\n\n train_transform = transforms.Compose([\n transforms.Resize(540), # 256\n transforms.RandomRotation((-45.0, +45.0)),\n transforms.RandomResizedCrop(512, scale=(0.9, 1.1), ratio=(0.9, 1.1)), # 224\n transforms.RandomHorizontalFlip(),\n transforms.RandomVerticalFlip(),\n transforms.ColorJitter(brightness=0.1, contrast=[0.75,1.5],\n saturation=[0.75,1.5], hue=0.15),\n transforms.ToTensor(),\n transforms.Normalize(mean=DR_DETECTION_MEAN, std=DR_DETECTION_STD)\n ])\n if args.cutout:\n train_transform.transforms.append(Cutout(args.cutout_length,\n args.cutout_prob))\n\n valid_transform = transforms.Compose([\n transforms.Resize(540),\n transforms.CenterCrop(512),\n transforms.ToTensor(),\n transforms.Normalize(mean=DR_DETECTION_MEAN, std=DR_DETECTION_STD),\n ])\n\n else:\n train_transform = transforms.Compose([\n transforms.Resize(256), # 256\n transforms.RandomRotation((-45.0, +45.0)),\n transforms.RandomResizedCrop(224, scale=(0.9, 1.1), ratio=(0.9, 1.1)), # 224\n transforms.RandomHorizontalFlip(),\n transforms.RandomVerticalFlip(),\n transforms.ColorJitter(brightness=0.1, contrast=[0.75, 1.5],\n saturation=[0.75, 1.5], hue=0.15),\n transforms.ToTensor(),\n transforms.Normalize(mean=DR_DETECTION_MEAN, std=DR_DETECTION_STD),\n # transforms.RandomErasing(),\n ])\n if args.cutout:\n train_transform.transforms.append(Cutout(args.cutout_length,\n args.cutout_prob))\n\n valid_transform = transforms.Compose([\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize(mean=DR_DETECTION_MEAN, std=DR_DETECTION_STD),\n ])\n return train_transform, valid_transform\n\ndef _data_transforms_malaria(args):\n\n train_transform = transforms.Compose([\n transforms.Resize(100),\n transforms.RandomCrop(64), # 224\n transforms.RandomHorizontalFlip(),\n transforms.RandomVerticalFlip(),\n transforms.ToTensor(),\n ])\n if args.cutout:\n train_transform.transforms.append(Cutout(args.cutout_length,\n args.cutout_prob))\n\n valid_transform = transforms.Compose([\n transforms.Resize(100),\n transforms.RandomCrop(64), # 224\n transforms.RandomHorizontalFlip(),\n transforms.RandomVerticalFlip(),\n transforms.ToTensor(),\n ])\n return train_transform, valid_transform\n\ndef _data_transforms_mnist(args):\n MNIST_MEAN = [0.5, 0.5, 0.5]\n MNIST_STD = [0.5, 0.5, 0.5]\n\n train_transform = transforms.Compose([\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize(MNIST_MEAN, MNIST_STD),\n ])\n if args.cutout:\n train_transform.transforms.append(Cutout(args.cutout_length,\n args.cutout_prob))\n\n valid_transform = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(MNIST_MEAN, MNIST_STD),\n ])\n return train_transform, valid_transform\n\ndef _data_transforms_cifar100(args):\n CIFAR_MEAN = [0.5071, 0.4865, 0.4409]\n CIFAR_STD = [0.2673, 0.2564, 0.2762]\n\n train_transform = transforms.Compose([\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize(CIFAR_MEAN, CIFAR_STD),\n ])\n if args.cutout:\n train_transform.transforms.append(Cutout(args.cutout_length,\n args.cutout_prob))\n\n valid_transform = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(CIFAR_MEAN, CIFAR_STD),\n ])\n return train_transform, valid_transform\n\n\ndef _data_transforms_cifar10(args):\n CIFAR_MEAN = [0.49139968, 0.48215827, 0.44653124]\n CIFAR_STD = [0.24703233, 0.24348505, 0.26158768]\n\n train_transform = transforms.Compose([\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize(CIFAR_MEAN, CIFAR_STD),\n ])\n if args.cutout:\n train_transform.transforms.append(Cutout(args.cutout_length,\n args.cutout_prob))\n\n valid_transform = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(CIFAR_MEAN, CIFAR_STD),\n ])\n return train_transform, valid_transform\n\n\ndef count_parameters_in_MB(model):\n return np.sum(np.prod(v.size()) for v in model.parameters())/1e6\n\n\ndef save(model, model_path):\n torch.save(model.state_dict(), model_path)\n\ndef load(model, model_path):\n model.load_state_dict(torch.load(model_path))\n\ndef save_checkpoint(state, is_best, save, epoch, task_id):\n filename = \"checkpoint_{}_{}.pth.tar\".format(task_id, epoch)\n filename = os.path.join(save, filename)\n\n torch.save(state, filename)\n if is_best:\n best_filename = os.path.join(save, 'model_best.pth.tar')\n shutil.copyfile(filename, best_filename)\n\ndef load_checkpoint(model, optimizer, scheduler, architect, save, la_tracker,\n epoch, task_id):\n filename = \"checkpoint_{}_{}.pth.tar\".format(task_id, epoch)\n filename = os.path.join(save, filename)\n\n checkpoint = torch.load(filename)\n\n model.load_state_dict(checkpoint['state_dict'])\n model.alphas_normal.data = checkpoint['alphas_normal']\n model.alphas_reduce.data = checkpoint['alphas_reduce']\n optimizer.load_state_dict(checkpoint['optimizer'])\n architect.optimizer.load_state_dict(checkpoint['arch_optimizer'])\n la_tracker.ev = checkpoint['ev']\n la_tracker.ev_local_avg = checkpoint['ev_local_avg']\n la_tracker.genotypes = checkpoint['genotypes']\n la_tracker.la_epochs = checkpoint['la_epochs']\n la_tracker.la_start_idx = checkpoint['la_start_idx']\n la_tracker.la_end_idx = checkpoint['la_end_idx']\n lr = checkpoint['lr']\n return lr\n\n\ndef drop_path(x, drop_prob):\n if drop_prob > 0.:\n keep_prob = 1.-drop_prob\n mask = Variable(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\ndef create_exp_dir(path, scripts_to_save=None):\n if not os.path.exists(path):\n os.makedirs(path, exist_ok=True)\n print('Experiment dir : {}'.format(path))\n\n if scripts_to_save is not None:\n os.mkdir(os.path.join(path, 'scripts'))\n for script in scripts_to_save:\n dst_file = os.path.join(path, 'scripts', os.path.basename(script))\n shutil.copyfile(script, dst_file)\n\n\ndef print_args(args):\n for arg, val in args.__dict__.items():\n print(arg + '.' * (50 - len(arg) - len(str(val))) + str(val))\n print()\n",
"import os\nimport sys\nimport numpy as np\nimport torch\nsys.path.insert(0, '../RobustDARTS')\n\nfrom src import utils\nimport glob\nimport random\nimport logging\nimport argparse\nimport torch.nn as nn\nimport torch.utils\nimport torchvision.datasets as dset\nimport torchvision.transforms as transforms\nimport torch.backends.cudnn as cudnn\nfrom src.utils import Genotype\n\nfrom torch.autograd import Variable\nfrom model import NetworkImageNet as Network\n\n\nparser = argparse.ArgumentParser(\"imagenet\")\nparser.add_argument('--data', type=str, default='../data', help='location of the data corpus')\nparser.add_argument('--batch_size', type=int, default=128, help='batch size')\nparser.add_argument('--report_freq', type=float, default=100, help='report frequency')\nparser.add_argument('--gpu', type=int, default=0, help='gpu device id')\nparser.add_argument('--init_channels', type=int, default=48, help='num of init channels')\nparser.add_argument('--layers', type=int, default=14, help='total number of layers')\nparser.add_argument('--model_path', type=str, default='EXP/model.pt', help='path of pretrained model')\nparser.add_argument('--auxiliary', action='store_true', default=False, help='use auxiliary tower')\nparser.add_argument('--drop_path_prob', type=float, default=0, help='drop path probability')\nparser.add_argument('--seed', type=int, default=0, help='random seed')\nparser.add_argument('--arch', type=str, default='DARTS', help='which architecture to use')\nargs = parser.parse_args()\n\nlog_format = '%(asctime)s %(message)s'\nlogging.basicConfig(stream=sys.stdout, level=logging.INFO,\n format=log_format, datefmt='%m/%d %I:%M:%S %p')\n\nCLASSES = 1000\n\n\ndef main():\n if not torch.cuda.is_available():\n logging.info('no gpu device available')\n sys.exit(1)\n\n np.random.seed(args.seed)\n torch.cuda.set_device(args.gpu)\n cudnn.benchmark = True\n torch.manual_seed(args.seed)\n cudnn.enabled=True\n torch.cuda.manual_seed(args.seed)\n logging.info('gpu device = %d' % args.gpu)\n logging.info(\"args = %s\", args)\n\n genotype = Genotype(normal=[('skip_connect', 1), ('skip_connect', 0), ('skip_connect', 1), ('skip_connect', 2), ('skip_connect', 3), ('skip_connect', 2), ('skip_connect', 2), ('dil_conv_3x3', 3)], normal_concat=range(2, 6), reduce=[('max_pool_3x3', 1), ('max_pool_3x3', 0), ('skip_connect', 2), ('max_pool_3x3', 0), ('skip_connect', 2), ('skip_connect', 3), ('skip_connect', 3), ('max_pool_3x3', 0)], reduce_concat=range(2, 6))\n\n model = Network(args.init_channels, CLASSES, args.layers, args.auxiliary, genotype)\n model = model.cuda()\n model.load_state_dict(torch.load(args.model_path)['state_dict'])\n\n logging.info(\"param size = %fMB\", utils.count_parameters_in_MB(model))\n\n criterion = nn.CrossEntropyLoss()\n criterion = criterion.cuda()\n\n validdir = os.path.join(args.data, 'val')\n normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n valid_data = dset.ImageFolder(\n validdir,\n transforms.Compose([\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n normalize,\n ]))\n\n valid_queue = torch.utils.data.DataLoader(\n valid_data, batch_size=args.batch_size, shuffle=False, pin_memory=True, num_workers=4)\n\n model.drop_path_prob = args.drop_path_prob\n valid_acc_top1, valid_acc_top5, valid_obj = infer(valid_queue, model, criterion)\n logging.info('valid_acc_top1 %f', valid_acc_top1)\n logging.info('valid_acc_top5 %f', valid_acc_top5)\n\n\ndef infer(valid_queue, model, criterion):\n objs = utils.AvgrageMeter()\n top1 = utils.AvgrageMeter()\n top5 = utils.AvgrageMeter()\n model.eval()\n\n for step, (input, target) in enumerate(valid_queue):\n with torch.no_grad():\n input = Variable(input).cuda()\n target = Variable(target).cuda()\n\n logits, _ = model(input)\n loss = criterion(logits, target)\n\n prec1, prec5 = utils.accuracy(logits, target, topk=(1, 5))\n n = input.size(0)\n objs.update(loss.data[0], n)\n top1.update(prec1.data[0], n)\n top5.update(prec5.data[0], n)\n\n if step % args.report_freq == 0:\n logging.info('valid %03d %e %f %f', step, objs.avg, top1.avg, top5.avg)\n\n return top1.avg, top5.avg, objs.avg\n\n\nif __name__ == '__main__':\n main()"
] | [
[
"torch.load",
"numpy.clip",
"torch.from_numpy",
"numpy.ones",
"numpy.ceil",
"torch.save",
"numpy.mean",
"numpy.floor",
"numpy.random.binomial",
"numpy.random.randint"
],
[
"torch.nn.CrossEntropyLoss",
"torch.cuda.set_device",
"torch.cuda.manual_seed",
"numpy.random.seed",
"torch.manual_seed",
"torch.load",
"torch.utils.data.DataLoader",
"torch.no_grad",
"torch.cuda.is_available",
"torch.autograd.Variable"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
gertjanvanzwieten/nutils | [
"ec04d66e4797398496453181f96b14ad2edae228"
] | [
"tests/test_types.py"
] | [
"from nutils.testing import *\nimport nutils.types\nimport inspect, pickle, itertools, ctypes, stringly, tempfile, io, os\nimport numpy\n\nclass apply_annotations(TestCase):\n\n def test_without_annotations(self):\n @nutils.types.apply_annotations\n def f(a, b):\n return a, b\n a, b = f(1, 2)\n self.assertEqual(a, 1)\n self.assertEqual(b, 2)\n\n def test_pos_or_kw(self):\n @nutils.types.apply_annotations\n def f(a:int, b, c:str):\n return a, b, c\n a, b, c = f(1, 2, 3)\n self.assertEqual(a, 1)\n self.assertEqual(b, 2)\n self.assertEqual(c, '3')\n\n def test_with_signature(self):\n def f(a):\n return a\n f.__signature__ = inspect.Signature([inspect.Parameter('a', inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=str)])\n f = nutils.types.apply_annotations(f)\n self.assertEqual(f(1), '1')\n\n def test_posonly(self):\n def f(a):\n return a\n f.__signature__ = inspect.Signature([inspect.Parameter('a', inspect.Parameter.POSITIONAL_ONLY, annotation=str)])\n f = nutils.types.apply_annotations(f)\n self.assertEqual(f(1), '1')\n\n def test_kwonly(self):\n @nutils.types.apply_annotations\n def f(a:str, *, b:int, c:bool):\n return a, b, c\n self.assertEqual(f(1, b='2', c=3), ('1', 2, True))\n\n def test_varpos(self):\n @nutils.types.apply_annotations\n def f(a:str, *args):\n return a, args\n self.assertEqual(f(1, 2, 3), ('1', (2, 3)))\n\n def test_varpos_annotated(self):\n map_str = lambda args: map(str, args)\n @nutils.types.apply_annotations\n def f(a:str, *args:map_str):\n return a, args\n self.assertEqual(f(1, 2, 3), ('1', ('2', '3')))\n\n def test_varkw(self):\n @nutils.types.apply_annotations\n def f(a:str, **kwargs):\n return a, kwargs\n self.assertEqual(f(1, b=2, c=3), ('1', dict(b=2, c=3)))\n\n def test_varkw_annotated(self):\n map_str = lambda kwargs: {k: str(v) for k, v in kwargs.items()}\n @nutils.types.apply_annotations\n def f(a:str, **kwargs:map_str):\n return a, kwargs\n self.assertEqual(f(1, b=2, c=3), ('1', dict(b='2', c='3')))\n\n def test_posonly_varkw(self):\n def f(a, b, **c):\n return a, b, c\n f.__signature__ = inspect.Signature([inspect.Parameter('a', inspect.Parameter.POSITIONAL_ONLY, annotation=str),\n inspect.Parameter('b', inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=str, default=None),\n inspect.Parameter('c', inspect.Parameter.VAR_KEYWORD)])\n f = nutils.types.apply_annotations(f)\n self.assertEqual(f(1, c=2, d=3), ('1', None, dict(c=2, d=3)))\n self.assertEqual(f(1, None, c=2, d=3), ('1', None, dict(c=2, d=3)))\n self.assertEqual(f(1, b=None, c=2, d=3), ('1', None, dict(c=2, d=3)))\n self.assertEqual(f(1, b=4, c=2, d=3), ('1', '4', dict(c=2, d=3)))\n\n def test_default_none(self):\n @nutils.types.apply_annotations\n def f(a:str=None):\n return a\n self.assertEqual(f(), None)\n self.assertEqual(f(None), None)\n self.assertEqual(f(1), '1')\n\nclass nutils_hash(TestCase):\n\n class custom:\n @property\n def __nutils_hash__(self):\n return b'01234567890123456789'\n def f(self):\n pass\n\n def test_ellipsis(self):\n self.assertEqual(nutils.types.nutils_hash(...).hex(), '0c8bce06e451e4d5c49f60da0abf2ccbadf80600')\n\n def test_None(self):\n self.assertEqual(nutils.types.nutils_hash(None).hex(), 'bdfcbd663476b2db5b2b2e59a6d93882a908dc76')\n\n def test_bool(self):\n self.assertEqual(nutils.types.nutils_hash(False).hex(), '04a5e8f73dcea55dcd7482a476cf2e7b53d6dc50')\n self.assertEqual(nutils.types.nutils_hash(True).hex(), '3fe990437e1624c831729f2866979254437bb7e9')\n\n def test_int(self):\n self.assertEqual(nutils.types.nutils_hash(1).hex(), '00ec7dea895ebd921e56bbc554688d8b3a1e4dfc')\n self.assertEqual(nutils.types.nutils_hash(2).hex(), '8ae88fa39407cf75e46f9e0aba8c971de2256b14')\n\n def test_float(self):\n self.assertEqual(nutils.types.nutils_hash(1.).hex(), 'def4bae4f2a3e29f6ddac537d3fa7c72195e5d8b')\n self.assertEqual(nutils.types.nutils_hash(2.5).hex(), '5216c2bf3c16d8b8ff4d9b79f482e5cea0a4cb95')\n\n def test_complex(self):\n self.assertEqual(nutils.types.nutils_hash(1+0j).hex(), 'cf7a0d933b7bb8d3ca252683b137534a1ecae073')\n self.assertEqual(nutils.types.nutils_hash(2+1j).hex(), 'ee088890528f941a80aa842dad36591b05253e55')\n\n def test_inequality_numbers(self):\n self.assertNotEqual(nutils.types.nutils_hash(1).hex(), nutils.types.nutils_hash(1.).hex())\n self.assertNotEqual(nutils.types.nutils_hash(1).hex(), nutils.types.nutils_hash(1+0j).hex())\n self.assertNotEqual(nutils.types.nutils_hash(1).hex(), nutils.types.nutils_hash(True).hex())\n\n def test_str(self):\n self.assertEqual(nutils.types.nutils_hash('spam').hex(), '3ca1023ab75a68dc7b0f83b43ec624704a7aef61')\n self.assertEqual(nutils.types.nutils_hash('eggs').hex(), '124b0a7b3984e08125c380f7454896c1cad22e2c')\n\n def test_bytes(self):\n self.assertEqual(nutils.types.nutils_hash(b'spam').hex(), '5e717ec15aace7c25610c1dea340f2173f2df014')\n self.assertEqual(nutils.types.nutils_hash(b'eggs').hex(), '98f2061978497751cac94f982fd96d9b015b74c3')\n\n def test_tuple(self):\n self.assertEqual(nutils.types.nutils_hash(()).hex(), '15d44755bf0731b2a3e9a5c5c8e0807b61881a1f')\n self.assertEqual(nutils.types.nutils_hash((1,)).hex(), '328b16ebbc1815cf579ae038a35c4d68ebb022af')\n self.assertNotEqual(nutils.types.nutils_hash((1,'spam')).hex(), nutils.types.nutils_hash(('spam',1)).hex())\n\n def test_frozenset(self):\n self.assertEqual(nutils.types.nutils_hash(frozenset([1,2])).hex(), '3862dc7e5321bc8a576c385ed2c12c71b96a375a')\n self.assertEqual(nutils.types.nutils_hash(frozenset(['spam','eggs'])).hex(), '2c75fd3db57f5e505e1425ae9ff6dcbbc77fd123')\n\n @unittest.skipIf(sys.version_info < (3,7), \"not supported in this Python version\")\n def test_dataclass(self):\n import dataclasses\n A = dataclasses.make_dataclass('A', [('n', int), ('f', float)])\n self.assertEqual(nutils.types.nutils_hash(A(n=1, f=2.5)).hex(), 'daf4235240e897beb9586db3c91663b24e229c52')\n\n def test_type_bool(self):\n self.assertEqual(nutils.types.nutils_hash(bool).hex(), 'feb912889d52d45fcd1e778c427b093a19a1ea78')\n\n def test_type_int(self):\n self.assertEqual(nutils.types.nutils_hash(int).hex(), 'aa8cb9975f7161b1f7ceb88b4b8585b49946b31e')\n\n def test_type_float(self):\n self.assertEqual(nutils.types.nutils_hash(float).hex(), '6d5079a53075f4b6f7710377838d8183730f1388')\n\n def test_type_complex(self):\n self.assertEqual(nutils.types.nutils_hash(complex).hex(), '6b00f6b9c6522742fd3f8054af6f10a24a671fff')\n\n def test_type_str(self):\n self.assertEqual(nutils.types.nutils_hash(str).hex(), '2349e11586163208d2581fe736630f4e4b680a7b')\n\n def test_type_bytes(self):\n self.assertEqual(nutils.types.nutils_hash(bytes).hex(), 'b0826ca666a48739e6f8b968d191adcefaa39670')\n\n def test_type_tuple(self):\n self.assertEqual(nutils.types.nutils_hash(tuple).hex(), '07cb4a24ca8ac53c820f20721432b4726e2ad1af')\n\n def test_type_frozenset(self):\n self.assertEqual(nutils.types.nutils_hash(frozenset).hex(), '48dc7cd0fbd54924498deb7c68dd363b4049f5e2')\n\n def test_type_bufferedreader(self):\n try:\n fid, path = tempfile.mkstemp()\n os.write(fid, b'test')\n os.close(fid)\n with open(path, 'rb') as f:\n f.seek(2)\n self.assertEqual(nutils.types.nutils_hash(f).hex(), '4edef1af3aa845b9e8bbde2d8265be5f30be4c2a')\n self.assertEqual(f.tell(), 2)\n with open(path, 'rb+') as f, self.assertRaises(TypeError):\n nutils.types.nutils_hash(f).hex()\n finally:\n os.unlink(path)\n\n def test_type_boundmethod(self):\n self.assertEqual(nutils.types.nutils_hash(self.custom().f).hex(), 'ebf7084bb2504922235ab035a9197b9cb4cf47af')\n\n def test_custom(self):\n self.assertEqual(nutils.types.nutils_hash(self.custom()).hex(), b'01234567890123456789'.hex())\n\n def test_unhashable(self):\n with self.assertRaises(TypeError):\n nutils.types.nutils_hash([])\n\nclass CacheMeta(TestCase):\n\n def test_property(self):\n\n for withslots in False, True:\n with self.subTest(withslots=withslots):\n\n class T(metaclass=nutils.types.CacheMeta):\n if withslots:\n __slots__ = ()\n __cache__ = 'x',\n @property\n def x(self):\n nonlocal ncalls\n ncalls += 1\n return 1\n\n ncalls = 0\n t = T()\n self.assertEqual(ncalls, 0)\n self.assertEqual(t.x, 1)\n self.assertEqual(ncalls, 1)\n self.assertEqual(t.x, 1)\n self.assertEqual(ncalls, 1)\n\n def test_set_property(self):\n\n class T(metaclass=nutils.types.CacheMeta):\n __cache__ = 'x',\n @property\n def x(self):\n return 1\n\n t = T()\n with self.assertRaises(AttributeError):\n t.x = 1\n\n def test_del_property(self):\n\n class T(metaclass=nutils.types.CacheMeta):\n __cache__ = 'x',\n @property\n def x(self):\n return 1\n\n t = T()\n with self.assertRaises(AttributeError):\n del t.x\n\n def test_method_without_args(self):\n\n for withslots in False, True:\n with self.subTest(withslots=withslots):\n\n class T(metaclass=nutils.types.CacheMeta):\n if withslots:\n __slots__ = ()\n __cache__ = 'x',\n def x(self):\n nonlocal ncalls\n ncalls += 1\n return 1\n\n ncalls = 0\n t = T()\n self.assertEqual(ncalls, 0)\n self.assertEqual(t.x(), 1)\n self.assertEqual(ncalls, 1)\n self.assertEqual(t.x(), 1)\n self.assertEqual(ncalls, 1)\n\n def test_method_with_args(self):\n\n for withslots in False, True:\n with self.subTest(withslots=withslots):\n\n class T(metaclass=nutils.types.CacheMeta):\n if withslots:\n __slots__ = ()\n __cache__ = 'x',\n def x(self, a, b):\n nonlocal ncalls\n ncalls += 1\n return a + b\n\n ncalls = 0\n t = T()\n self.assertEqual(ncalls, 0)\n self.assertEqual(t.x(1, 2), 3)\n self.assertEqual(ncalls, 1)\n self.assertEqual(t.x(a=1, b=2), 3)\n self.assertEqual(ncalls, 1)\n self.assertEqual(t.x(2, 2), 4)\n self.assertEqual(ncalls, 2)\n self.assertEqual(t.x(a=2, b=2), 4)\n self.assertEqual(ncalls, 2)\n self.assertEqual(t.x(1, 2), 3)\n self.assertEqual(ncalls, 3)\n\n def test_method_with_args_and_preprocessors(self):\n\n for withslots in False, True:\n with self.subTest(withslots=withslots):\n\n class T(metaclass=nutils.types.CacheMeta):\n if withslots:\n __slots__ = ()\n __cache__ = 'x',\n @nutils.types.apply_annotations\n def x(self, a:int, b:int):\n nonlocal ncalls\n ncalls += 1\n return a + b\n\n ncalls = 0\n t = T()\n self.assertEqual(ncalls, 0)\n self.assertEqual(t.x(1, 2), 3)\n self.assertEqual(ncalls, 1)\n self.assertEqual(t.x(a='1', b='2'), 3)\n self.assertEqual(ncalls, 1)\n self.assertEqual(t.x('2', '2'), 4)\n self.assertEqual(ncalls, 2)\n self.assertEqual(t.x(a=2, b=2), 4)\n self.assertEqual(ncalls, 2)\n self.assertEqual(t.x('1', 2), 3)\n self.assertEqual(ncalls, 3)\n\n def test_method_with_kwargs(self):\n\n for withslots in False, True:\n with self.subTest(withslots=withslots):\n\n class T(metaclass=nutils.types.CacheMeta):\n if withslots:\n __slots__ = ()\n __cache__ = 'x',\n def x(self, a, **kwargs):\n nonlocal ncalls\n ncalls += 1\n return a + sum(kwargs.values())\n\n ncalls = 0\n t = T()\n self.assertEqual(ncalls, 0)\n self.assertEqual(t.x(1, b=2), 3)\n self.assertEqual(ncalls, 1)\n self.assertEqual(t.x(a=1, b=2), 3)\n self.assertEqual(ncalls, 1)\n self.assertEqual(t.x(1, b=2, c=3), 6)\n self.assertEqual(ncalls, 2)\n self.assertEqual(t.x(a=1, b=2, c=3), 6)\n self.assertEqual(ncalls, 2)\n\n def test_subclass_redefined_property(self):\n\n class T(metaclass=nutils.types.CacheMeta):\n __cache__ = 'x',\n @property\n def x(self):\n return 1\n\n class U(T):\n __cache__ = 'x',\n @property\n def x(self):\n return super().x + 1\n @property\n def y(self):\n return super().x\n\n u1 = U()\n self.assertEqual(u1.x, 2)\n self.assertEqual(u1.y, 1)\n\n u2 = U()\n self.assertEqual(u2.y, 1)\n self.assertEqual(u2.x, 2)\n\n def test_missing_attribute(self):\n\n with self.assertRaisesRegex(TypeError, 'Attribute listed in __cache__ is undefined: x'):\n class T(metaclass=nutils.types.CacheMeta):\n __cache__ = 'x',\n\n def test_invalid_attribute(self):\n\n with self.assertRaisesRegex(TypeError, \"Don't know how to cache attribute x: None\"):\n class T(metaclass=nutils.types.CacheMeta):\n __cache__ = 'x',\n x = None\n\n def test_name_mangling(self):\n\n for withslots in False, True:\n with self.subTest(withslots=withslots):\n\n class T(metaclass=nutils.types.CacheMeta):\n if withslots:\n __slots__ = ()\n __cache__ = '__x',\n @property\n def __x(self):\n nonlocal ncalls\n ncalls += 1\n return 1\n @property\n def y(self):\n return self.__x\n\n ncalls = 0\n t = T()\n self.assertEqual(ncalls, 0)\n self.assertEqual(t.y, 1)\n self.assertEqual(ncalls, 1)\n self.assertEqual(t.y, 1)\n self.assertEqual(ncalls, 1)\n\nclass strictint(TestCase):\n\n def test_int(self):\n value = nutils.types.strictint(1)\n self.assertEqual(value, 1)\n self.assertEqual(type(value), int)\n\n def test_numpy_int(self):\n value = nutils.types.strictint(numpy.int64(1))\n self.assertEqual(value, 1)\n self.assertEqual(type(value), int)\n\n def test_float(self):\n with self.assertRaises(ValueError):\n nutils.types.strictint(1.)\n\n def test_numpy_float(self):\n with self.assertRaises(ValueError):\n nutils.types.strictint(numpy.float64(1.))\n\n def test_complex(self):\n with self.assertRaises(ValueError):\n nutils.types.strictint(1+0j)\n\n def test_str(self):\n with self.assertRaises(ValueError):\n nutils.types.strictint('1')\n\nclass strictfloat(TestCase):\n\n def test_int(self):\n value = nutils.types.strictfloat(1)\n self.assertEqual(value, 1.)\n self.assertEqual(type(value), float)\n\n def test_numpy_int(self):\n value = nutils.types.strictfloat(numpy.int64(1))\n self.assertEqual(value, 1.)\n self.assertEqual(type(value), float)\n\n def test_float(self):\n value = nutils.types.strictfloat(1.)\n self.assertEqual(value, 1.)\n self.assertEqual(type(value), float)\n\n def test_numpy_float(self):\n value = nutils.types.strictfloat(numpy.float64(1.))\n self.assertEqual(value, 1.)\n self.assertEqual(type(value), float)\n\n def test_complex(self):\n with self.assertRaises(ValueError):\n nutils.types.strictint(1+0j)\n\n def test_str(self):\n with self.assertRaises(ValueError):\n nutils.types.strictfloat('1.')\n\nclass strictstr(TestCase):\n\n def test_str(self):\n value = nutils.types.strictstr('spam')\n self.assertEqual(value, 'spam')\n self.assertEqual(type(value), str)\n\n def test_int(self):\n with self.assertRaises(ValueError):\n nutils.types.strictstr(1)\n\nclass strict(TestCase):\n\n def test_valid(self):\n self.assertEqual(nutils.types.strict[int](1), 1)\n\n def test_invalid(self):\n with self.assertRaises(ValueError):\n nutils.types.strict[int]('1')\n\n def test_call(self):\n with self.assertRaises(TypeError):\n nutils.types.strict()\n\nclass tupletype(TestCase):\n\n def test_valid1(self):\n value = nutils.types.tuple[nutils.types.strictint]([])\n self.assertEqual(value, ())\n self.assertEqual(type(value), tuple)\n\n def test_valid2(self):\n value = nutils.types.tuple[nutils.types.strictint]([1,2,3])\n self.assertEqual(value, (1,2,3))\n self.assertEqual(type(value), tuple)\n\n def test_invalid(self):\n with self.assertRaises(ValueError):\n nutils.types.tuple[nutils.types.strictint]([1, 'spam','eggs'])\n\n def test_without_item_constructor(self):\n src = 1,2,3\n self.assertEqual(nutils.types.tuple(src), tuple(src))\n\n def test_name(self):\n self.assertEqual(nutils.types.tuple[nutils.types.strictint].__name__, 'tuple[nutils.types.strictint]')\n\nclass frozendict(TestCase):\n\n def test_constructor(self):\n src = {'spam': 1, 'eggs': 2.3}\n for name, value in [('mapping', src), ('mapping_view', src.items()), ('iterable', (item for item in src.items())), ('frozendict', nutils.types.frozendict(src))]:\n with self.subTest(name):\n frozen = nutils.types.frozendict(value)\n self.assertIsInstance(frozen, nutils.types.frozendict)\n self.assertEqual(dict(frozen), src)\n\n def test_constructor_invalid(self):\n with self.assertRaises(ValueError):\n nutils.types.frozendict(['spam', 'eggs', 1])\n\n def test_clsgetitem(self):\n T = nutils.types.frozendict[str, float]\n src = {1: 2, 'spam': '2.3'}\n for name, value in [('mapping', src), ('mapping_view', src.items()), ('iterable', (item for item in src.items()))]:\n with self.subTest(name):\n frozen = T(value)\n self.assertIsInstance(frozen, nutils.types.frozendict)\n self.assertEqual(dict(frozen), {'1': 2., 'spam': 2.3})\n\n def test_clsgetitem_invalid_types(self):\n with self.assertRaises(RuntimeError):\n nutils.types.frozendict[str, float, bool]\n\n def test_clsgetitem_invalid_value(self):\n T = nutils.types.frozendict[str, float]\n with self.assertRaises(ValueError):\n T(1)\n\n def test_setitem(self):\n frozen = nutils.types.frozendict({'spam': 1, 'eggs': 2.3})\n with self.assertRaises(TypeError):\n frozen['eggs'] = 3\n\n def test_delitem(self):\n frozen = nutils.types.frozendict({'spam': 1, 'eggs': 2.3})\n with self.assertRaises(TypeError):\n del frozen['eggs']\n\n def test_getitem_existing(self):\n frozen = nutils.types.frozendict({'spam': 1, 'eggs': 2.3})\n self.assertEqual(frozen['spam'], 1)\n\n def test_getitem_nonexisting(self):\n frozen = nutils.types.frozendict({'spam': 1, 'eggs': 2.3})\n with self.assertRaises(KeyError):\n frozen['foo']\n\n def test_contains(self):\n frozen = nutils.types.frozendict({'spam': 1, 'eggs': 2.3})\n self.assertIn('spam', frozen)\n self.assertNotIn('foo', frozen)\n\n def test_iter(self):\n src = {'spam': 1, 'eggs': 2.3}\n frozen = nutils.types.frozendict(src)\n self.assertEqual(frozenset(frozen), frozenset(src))\n\n def test_len(self):\n src = {'spam': 1, 'eggs': 2.3}\n frozen = nutils.types.frozendict(src)\n self.assertEqual(len(frozen), len(src))\n\n def test_hash(self):\n src = {'spam': 1, 'eggs': 2.3}\n self.assertEqual(hash(nutils.types.frozendict(src)), hash(nutils.types.frozendict(src)))\n\n def test_copy(self):\n src = {'spam': 1, 'eggs': 2.3}\n copy = nutils.types.frozendict(src).copy()\n self.assertIsInstance(copy, dict)\n self.assertEqual(copy, src)\n\n def test_pickle(self):\n src = {'spam': 1, 'eggs': 2.3}\n frozen = pickle.loads(pickle.dumps(nutils.types.frozendict(src)))\n self.assertIsInstance(frozen, nutils.types.frozendict)\n self.assertEqual(dict(frozen), src)\n\n def test_eq_same_id(self):\n src = {'spam': 1, 'eggs': 2.3}\n a = nutils.types.frozendict(src)\n self.assertEqual(a, a)\n\n def test_eq_other_id(self):\n src = {'spam': 1, 'eggs': 2.3}\n a = nutils.types.frozendict(src)\n b = nutils.types.frozendict(src)\n self.assertEqual(a, b)\n\n def test_eq_deduplicated(self):\n src = {'spam': 1, 'eggs': 2.3}\n a = nutils.types.frozendict(src)\n b = nutils.types.frozendict(src)\n a == b # this replaces `a.__base` with `b.__base`\n self.assertEqual(a, b)\n\n def test_ineq_frozendict(self):\n src = {'spam': 1, 'eggs': 2.3}\n self.assertNotEqual(nutils.types.frozendict(src), nutils.types.frozendict({'spam': 1}))\n\n def test_ineq_dict(self):\n src = {'spam': 1, 'eggs': 2.3}\n self.assertNotEqual(nutils.types.frozendict(src), src)\n\n def test_nutils_hash(self):\n frozen = nutils.types.frozendict({'spam': 1, 'eggs': 2.3})\n self.assertEqual(nutils.types.nutils_hash(frozen).hex(), '8cf14f109e54707af9c2e66d7d3cdb755cce8243')\n\nclass frozenmultiset(TestCase):\n\n def test_constructor(self):\n src = 'spam', 'bacon', 'sausage', 'spam'\n for name, value in [('tuple', src), ('frozenmultiset', nutils.types.frozenmultiset(src))]:\n with self.subTest(name=name):\n frozen = nutils.types.frozenmultiset(value)\n for item in 'spam', 'bacon', 'sausage':\n self.assertEqual({k: tuple(frozen).count(k) for k in set(src)}, {'spam':2, 'bacon':1, 'sausage':1})\n\n def test_clsgetitem(self):\n src = False, 1, numpy.int64(2)\n frozen = nutils.types.frozenmultiset[nutils.types.strictint](src)\n self.assertEqual(set(frozen), {0, 1, 2})\n\n def test_preserve_order(self):\n for src in [('spam', 'bacon', 'sausage', 'spam'), ('spam', 'egg', 'spam', 'spam', 'bacon', 'spam')]:\n with self.subTest(src=src):\n self.assertEqual(tuple(nutils.types.frozenmultiset(src)), src)\n\n def test_and(self):\n for l, r, lar in [[['spam', 'eggs'], ['spam', 'spam', 'eggs'], ['spam', 'eggs']],\n [['spam'], ['eggs'], []],\n [['spam','spam']]*3]:\n with self.subTest(l=l, r=r, lar=lar):\n self.assertEqual(nutils.types.frozenmultiset(l)&nutils.types.frozenmultiset(r), nutils.types.frozenmultiset(lar))\n with self.subTest(l=r, r=l, lar=lar):\n self.assertEqual(nutils.types.frozenmultiset(r)&nutils.types.frozenmultiset(l), nutils.types.frozenmultiset(lar))\n\n def test_sub(self):\n for l, r, lmr, rml in [[['spam', 'eggs'], ['spam', 'spam', 'eggs'], [], ['spam']],\n [['spam'], ['eggs'], ['spam'], ['eggs']],\n [['spam'], ['spam'], [], []]]:\n with self.subTest(l=l, r=r, lmr=lmr):\n self.assertEqual(nutils.types.frozenmultiset(l)-nutils.types.frozenmultiset(r), nutils.types.frozenmultiset(lmr))\n with self.subTest(l=r, r=l, lmr=rml):\n self.assertEqual(nutils.types.frozenmultiset(r)-nutils.types.frozenmultiset(l), nutils.types.frozenmultiset(rml))\n\n def test_pickle(self):\n src = 'spam', 'bacon', 'sausage', 'spam'\n frozen = pickle.loads(pickle.dumps(nutils.types.frozenmultiset(src)))\n self.assertIsInstance(frozen, nutils.types.frozenmultiset)\n self.assertEqual(frozen, nutils.types.frozenmultiset(src))\n\n def test_hash(self):\n src = 'spam', 'bacon', 'sausage', 'spam'\n ref = nutils.types.frozenmultiset(src)\n for perm in itertools.permutations(src):\n with self.subTest(perm=perm):\n self.assertEqual(hash(nutils.types.frozenmultiset(src)), hash(ref))\n\n def test_nutils_hash(self):\n for perm in itertools.permutations(('spam', 'bacon', 'sausage', 'spam')):\n with self.subTest(perm=perm):\n frozen = nutils.types.frozenmultiset(perm)\n self.assertEqual(nutils.types.nutils_hash(frozen).hex(), 'f3fd9c6d4741af2e67973457ee6308deddcb714c')\n\n def test_eq(self):\n src = 'spam', 'bacon', 'sausage', 'spam'\n ref = nutils.types.frozenmultiset(src)\n for perm in itertools.permutations(src):\n with self.subTest(perm=perm):\n self.assertEqual(nutils.types.frozenmultiset(src), ref)\n\n def test_contains(self):\n src = 'spam', 'bacon', 'sausage', 'spam'\n frozen = nutils.types.frozenmultiset(src)\n for item in 'spam', 'bacon', 'eggs':\n with self.subTest(item=item):\n if item in src:\n self.assertIn(item, frozen)\n else:\n self.assertNotIn(item, frozen)\n\n def test_len(self):\n src = 'spam', 'bacon', 'sausage', 'spam'\n frozen = nutils.types.frozenmultiset(src)\n self.assertEqual(len(frozen), len(src))\n\n def test_nonzero(self):\n self.assertTrue(nutils.types.frozenmultiset(['spam', 'eggs']))\n self.assertFalse(nutils.types.frozenmultiset([]))\n\n def test_add(self):\n l = nutils.types.frozenmultiset(['spam', 'bacon'])\n r = nutils.types.frozenmultiset(['sausage', 'spam'])\n lpr = nutils.types.frozenmultiset(['spam', 'bacon', 'sausage', 'spam'])\n self.assertEqual(l+r, lpr)\n\n def test_isdisjoint(self):\n for l, r, disjoint in [[['spam', 'eggs'], ['spam', 'spam', 'eggs'], False],\n [['spam'], ['eggs'], True],\n [['spam'], ['spam'], False]]:\n with self.subTest(l=l, r=r, disjoint=disjoint):\n self.assertEqual(nutils.types.frozenmultiset(l).isdisjoint(nutils.types.frozenmultiset(r)), disjoint)\n\nclass frozenarray(TestCase):\n\n def _test_constructor(self, src, frozen_dtype, src_types=(list,numpy.array,nutils.types.frozenarray)):\n src = list(src)\n for copy in True, False:\n for src_type in src_types:\n with self.subTest(copy=copy, src_type=src_type):\n frozen = nutils.types.frozenarray(src_type(src), copy=copy, dtype=frozen_dtype)\n self.assertIsInstance(frozen, nutils.types.frozenarray)\n self.assertEqual(frozen.tolist(), src)\n def _test_constructor_raises(self, src, frozen_dtype, exc_type, exc_regex):\n src = list(src)\n for copy in True, False:\n for src_type in list, numpy.array, nutils.types.frozenarray:\n with self.subTest(copy=copy, src_type=src_type), self.assertRaisesRegex(exc_type, exc_regex):\n nutils.types.frozenarray(src_type(src), copy=copy, dtype=frozen_dtype)\n def test_constructor_bool(self):\n self._test_constructor((False, True), bool)\n def test_constructor_bool_emptyarray(self):\n self._test_constructor((), bool, src_types=[list])\n def test_constructor_int(self):\n self._test_constructor((0,1), int)\n def test_constructor_int_upcast(self):\n self._test_constructor((False,True), int)\n def test_constructor_int_downcast(self):\n self._test_constructor((0.,1.), int)\n def test_constructor_int_emptyarray(self):\n self._test_constructor((), int, src_types=[list])\n def test_constructor_float(self):\n self._test_constructor((0.,1.), float)\n def test_constructor_float_upcast(self):\n self._test_constructor((0,1), float)\n def test_constructor_float_downcast(self):\n src = [0.+0j,1.+0j]\n for copy in True, False:\n with self.subTest(copy=copy, src_type=list), self.assertRaises(TypeError):\n nutils.types.frozenarray(src, copy=copy, dtype=float)\n for src_type in numpy.array, nutils.types.frozenarray:\n with self.subTest(copy=copy, src_type=src_type), self.assertWarns(numpy.ComplexWarning):\n nutils.types.frozenarray(src_type(src), copy=copy, dtype=float)\n def test_constructor_complex(self):\n self._test_constructor((0+0j,1+1j), complex)\n def test_constructor_strictint(self):\n self._test_constructor((0,1), nutils.types.strictint)\n def test_constructor_strictint_upcast(self):\n self._test_constructor((False,True), nutils.types.strictint)\n def test_constructor_strictint_downcast(self):\n self._test_constructor_raises((0.,1.), nutils.types.strictint, ValueError, '^downcasting .* is forbidden$')\n def test_constructor_strictint_emptyarray(self):\n self._test_constructor((), nutils.types.strictint, src_types=[list])\n def test_constructor_strictfloat(self):\n self._test_constructor((0.,1.), nutils.types.strictfloat)\n def test_constructor_strictfloat_upcast(self):\n self._test_constructor((0,1), nutils.types.strictfloat)\n def test_constructor_strictfloat_downcast(self):\n self._test_constructor_raises((0.+0j,1.+0j), nutils.types.strictfloat, ValueError, '^downcasting .* is forbidden$')\n def test_constructor_invalid_dtype(self):\n self._test_constructor_raises((0,1), list, ValueError, '^unsupported dtype:')\n\n def test_clsgetitem(self):\n src = [0.,1.]\n frozen = nutils.types.frozenarray[nutils.types.strictfloat](src)\n self.assertIsInstance(frozen, nutils.types.frozenarray)\n self.assertEqual(frozen.tolist(), src)\n\n def test_clsgetitem_invalid(self):\n src = [0.,1.]\n with self.assertRaises(ValueError):\n nutils.types.frozenarray[nutils.types.strictint](src)\n\n def test_nutils_hash(self):\n a = nutils.types.frozenarray(numpy.array([[1,2],[3,4]], numpy.int64))\n b = nutils.types.frozenarray(numpy.array([[1,3],[2,4]], numpy.int64))\n self.assertNotEqual(nutils.types.nutils_hash(a).hex(), nutils.types.nutils_hash(b).hex())\n self.assertEqual(nutils.types.nutils_hash(a).hex(), nutils.types.nutils_hash(b.T).hex())\n self.assertEqual(nutils.types.nutils_hash(a).hex(), '42cc3a5e1216c1f0a9921a61a3a2c67025c98d69')\n self.assertEqual(nutils.types.nutils_hash(b).hex(), '8f0c9f9a118c42c258f1e69e374aadda99b4be97')\n\n def test_pickle(self):\n src = [[1,2],[3,4]]\n value = pickle.loads(pickle.dumps(nutils.types.frozenarray(src)))\n self.assertIsInstance(value, nutils.types.frozenarray)\n self.assertEqual(value, nutils.types.frozenarray(src))\n\n def test_eq_same_instance(self):\n a = nutils.types.frozenarray([[1,2],[3,4]], int)\n self.assertEqual(a, a)\n\n def test_eq_not_frozenarray(self):\n a = nutils.types.frozenarray([[1,2],[3,4]], int)\n self.assertNotEqual(a, [[1,2],[3,4]])\n\n def test_eq_same_base(self):\n base = numpy.array([[1,2],[3,4]], int)\n a = nutils.types.frozenarray(base, copy=False)\n b = nutils.types.frozenarray(base, copy=False)\n self.assertEqual(a, b)\n\n def test_eq_different_array(self):\n a = nutils.types.frozenarray([[1,2],[3,4]], int)\n b = nutils.types.frozenarray([[1,3],[2,4]], int)\n self.assertNotEqual(a, b)\n\n def test_eq_different_dtype(self):\n a = nutils.types.frozenarray([[1,2],[3,4]], int)\n b = nutils.types.frozenarray([[1,2],[3,4]], float)\n self.assertNotEqual(a, b)\n\n def test_eq_different_base(self):\n a = nutils.types.frozenarray([[1,2],[3,4]], int)\n b = nutils.types.frozenarray([[1,2],[3,4]], int)\n self.assertEqual(a, b)\n\n def test_ineq_equal(self):\n l = nutils.types.frozenarray([1,2], int)\n r = nutils.types.frozenarray([1,2], int)\n self.assertFalse(l < r)\n self.assertTrue(l <= r)\n self.assertFalse(l > r)\n self.assertTrue(l >= r)\n\n def test_ineq_smaller(self):\n l = nutils.types.frozenarray([1,2], int)\n r = nutils.types.frozenarray([2,1], int)\n self.assertTrue(l < r)\n self.assertTrue(l <= r)\n self.assertFalse(l > r)\n self.assertFalse(l >= r)\n\n def test_ineq_larger(self):\n l = nutils.types.frozenarray([2,1], int)\n r = nutils.types.frozenarray([1,2], int)\n self.assertFalse(l < r)\n self.assertFalse(l <= r)\n self.assertTrue(l > r)\n self.assertTrue(l >= r)\n\n def test_ineq_incomparable(self):\n array = nutils.types.frozenarray([1,2], int)\n for op in operator.lt, operator.le, operator.gt, operator.ge:\n with self.subTest(op=op), self.assertRaises(TypeError):\n op(array, 1)\n\n def test_full(self):\n self.assertEqual(nutils.types.frozenarray.full([2,3], 1.5), nutils.types.frozenarray([[1.5]*3]*2, float))\n\n def test_as_numpy_array(self):\n\n a = numpy.array(nutils.types.frozenarray([1,2]))\n self.assertIsInstance(a, numpy.ndarray)\n\nclass c_array(TestCase):\n\n def test_idempotence(self):\n a = numpy.array([1,2,3], dtype=numpy.int64)\n P = nutils.types.c_array[numpy.int64]\n a_ct = P(a)\n self.assertEqual(P(a_ct), a_ct)\n\n def test_list(self):\n a = [1,2,3]\n a_ct = nutils.types.c_array[numpy.int64](a)\n self.assertEqual(a_ct.data_as(ctypes.POINTER(ctypes.c_int64)).contents.value, 1)\n\n def test_array(self):\n a = numpy.array([1,2,3], dtype=numpy.int64)\n a_ct = nutils.types.c_array[numpy.int64](a)\n self.assertEqual(a_ct.data_as(ctypes.POINTER(ctypes.c_int64)).contents.value, 1)\n\n def test_array_invalid_dtype(self):\n a = numpy.array([1,2,3], dtype=numpy.int32)\n with self.assertRaisesRegex(ValueError, '^Expected dtype .* but array has dtype .*\\\\.$'):\n a_ct = nutils.types.c_array[numpy.int64](a)\n\n def test_array_noncontinguous(self):\n a = numpy.array([[1,2],[3,4]], dtype=numpy.int32).T\n with self.assertRaisesRegex(ValueError, '^Array is not contiguous\\\\.$'):\n a_ct = nutils.types.c_array[numpy.int64](a)\n\n def test_wo_getitem(self):\n with self.assertRaises(TypeError):\n nutils.types.c_array()\n\nclass T_Immutable(nutils.types.Immutable):\n def __init__(self, x, y, *, z):\n pass\n\nclass T_Singleton(nutils.types.Singleton):\n def __init__(self, x, y, *, z):\n pass\n\n@parametrize\nclass ImmutableFamily(TestCase):\n\n def test_pickle(self):\n T = {nutils.types.Immutable: T_Immutable, nutils.types.Singleton: T_Singleton}[self.cls]\n a = T(1, 2, z=3)\n b = pickle.loads(pickle.dumps(a))\n self.assertEqual(a, b)\n\n def test_eq(self):\n class T(self.cls):\n def __init__(self, x, y):\n pass\n class U(self.cls):\n def __init__(self, x, y):\n pass\n\n self.assertEqual(T(1, 2), T(1, 2))\n self.assertNotEqual(T(1, 2), T(2, 1))\n self.assertNotEqual(T(1, 2), U(1, 2))\n\n def test_canonical_args(self):\n class T(self.cls):\n def __init__(self, x, y, z=3):\n pass\n\n self.assertEqual(T(x=1, y=2), T(1, 2, 3))\n\n def test_keyword_args(self):\n class T(self.cls):\n def __init__(self, x, y, **kwargs):\n pass\n\n a = T(x=1, y=2, z=3)\n b = T(1, 2, z=3)\n self.assertEqual(a, b)\n\n def test_preprocessors(self):\n class T(self.cls):\n @nutils.types.apply_annotations\n def __init__(self, x: int):\n pass\n\n self.assertEqual(T(1), T('1'))\n self.assertEqual(T(1), T(x='1'))\n\n def test_nutils_hash(self):\n class T(self.cls):\n def __init__(self, x, y):\n pass\n class T1(self.cls, version=1):\n def __init__(self, x, y):\n pass\n class U(self.cls):\n def __init__(self, x, y):\n pass\n\n self.assertEqual(nutils.types.nutils_hash(T(1, 2)).hex(), nutils.types.nutils_hash(T(1, 2)).hex())\n self.assertNotEqual(nutils.types.nutils_hash(T(1, 2)).hex(), nutils.types.nutils_hash(T(2, 1)).hex())\n self.assertNotEqual(nutils.types.nutils_hash(T(1, 2)).hex(), nutils.types.nutils_hash(U(1, 2)).hex())\n # Since the hash does not include base classes, the hashes of Immutable and Singleton are the same.\n self.assertEqual(nutils.types.nutils_hash(T(1, 2)).hex(), '8c3ba8f0d9eb054ab192f4e4e2ba7442564bdf85')\n self.assertEqual(nutils.types.nutils_hash(T1(1, 2)).hex(), 'bab4ee65b5189f544a4242f0e386af76cfa6e31d')\n\n @parametrize.enable_if(lambda cls: cls is nutils.types.Singleton)\n def test_deduplication(self):\n class T(self.cls):\n def __init__(self, x, y):\n pass\n class U(self.cls):\n def __init__(self, x, y):\n pass\n\n a = T(1, 2)\n b = T(1, 2)\n c = T(2, 1)\n d = U(1, 2)\n self.assertIs(a, b)\n self.assertEqual(a, b)\n self.assertIsNot(a, c)\n self.assertNotEqual(a, c)\n self.assertIsNot(a, d)\n self.assertNotEqual(a, d)\n\nImmutableFamily(cls=nutils.types.Immutable)\nImmutableFamily(cls=nutils.types.Singleton)\n\n# vim:sw=2:sts=2:et\n"
] | [
[
"numpy.int64",
"numpy.array",
"numpy.float64"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
islasimpson/snowpaper_2022 | [
"d6ee677f696d7fd6e7cadef8168ce4fd8b184cac",
"d6ee677f696d7fd6e7cadef8168ce4fd8b184cac",
"d6ee677f696d7fd6e7cadef8168ce4fd8b184cac",
"d6ee677f696d7fd6e7cadef8168ce4fd8b184cac",
"d6ee677f696d7fd6e7cadef8168ce4fd8b184cac",
"d6ee677f696d7fd6e7cadef8168ce4fd8b184cac",
"d6ee677f696d7fd6e7cadef8168ce4fd8b184cac",
"d6ee677f696d7fd6e7cadef8168ce4fd8b184cac",
"d6ee677f696d7fd6e7cadef8168ce4fd8b184cac",
"d6ee677f696d7fd6e7cadef8168ce4fd8b184cac"
] | [
"DATA_SORT/3cities/SCAM/outputcesmscam_TREFHT_CLM5_CLM5F_001.py",
"DATA_SORT/3cities/SCAM_CLMINIT_60days_withclearsky/outputcesmscam_FLNSC_CLM5_CLM5F_001.py",
"DATA_SORT/3cities/SCAM/weakerrelaxation/outputcesmscam_TREFHT_SNOWDa_CLM5F_002.py",
"DATA_SORT/3cities/SCAM/weakerrelaxation/outputcesmscam_TBOT_CLM5_CLM5F_002.py",
"DATA_SORT/3cities/SCAM_CLMINIT/outputcesmscam_TREFHT_SNOWD_CLM5F_001.py",
"DATA_SORT/3cities/SCAM_CLMINIT/outputcesmscam_SNODP_CLM5_CLM5F_001.py",
"DATA_SORT/3cities/SCAM_CLMINIT_60days/outputcesmscam_FSNS_SNOWD_SNOWDF_002.py",
"DATA_SORT/3cities/SCAM/outputcesmscam_TS_CLM5_CLM5F_002.py",
"DATA_SORT/3cities/SCAM_CLMINIT_60days/outputcesmscam_T850_SNOWD_CLM5F_001.py",
"DATA_SORT/3cities/SCAM/weakerrelaxation/outputcesmscam_TSNO_SNOWD_SNOWDF_001.py"
] | [
"import importlib\nimport xarray as xr\nimport numpy as np\nimport pandas as pd\nimport sys\n\nfrom CASutils import filter_utils as filt\nfrom CASutils import readdata_utils as read\nfrom CASutils import calendar_utils as cal\n\nimportlib.reload(filt)\nimportlib.reload(read)\nimportlib.reload(cal)\n\n\nexpname=['SASK_CLM5_CLM5F_01.001.FSCAM.sask_1979_2014',\n 'TOR_CLM5_CLM5F_01.001.FSCAM.tor_1979_2014',\n 'SID_SNOWD_SNOWDF_01.001.FSCAM.sidsnowd1']\n\noutname='SCAM_CLM5_CLM5F_001'\n\ncityname=['Saskatoon','Toronto','Siderovsk']\ncitylon=[253.330, 280.617, 82.3139]\ncitylat=[52.1579, 43.6532, 66.5973]\n\nfor icity in np.arange(0,3,1):\n\n basedir=\"/project/cas02/islas/CLM5_CLM4/raw/SCAM_new_lowrelax/\"\n pathout=\"/project/cas/islas/python_savs/snowpaper/DATA_SORT/3cities/\"\n \n fpath=basedir+expname[icity]+\"/atm/hist/h0concat.nc\"\n print(fpath)\n dat = read.read_sfc_cesm(fpath,\"1979-01-01T12:00:00\",\"2014-12-31T12:00:00\")\n \n if (icity == 0): \n trefht = xr.DataArray(np.zeros([dat.time.size, 3]), coords=[dat.time, cityname],\n dims=['time','city'], name='trefht')\n \n trefht[:,icity] = dat.TREFHT.isel(lon=0,lat=0)\n \n trefht.to_netcdf(path=pathout+\"TREFHT_\"+outname+\".nc\")\n",
"import importlib\nimport xarray as xr\nimport numpy as np\nimport pandas as pd\nimport sys\n\nfrom CASutils import filter_utils as filt\nfrom CASutils import readdata_utils as read\nfrom CASutils import calendar_utils as cal\n\nimportlib.reload(filt)\nimportlib.reload(read)\nimportlib.reload(cal)\n\n\nexpname=['SASK_CLM5_CLM5F_01.001.FSCAM.sask_1979_2014',\n 'TOR_CLM5_CLM5F_01.001.FSCAM.tor_1979_2014',\n 'SID_CLM5_CLM5F_01.001.FSCAM.sid_1979_2014']\n\noutname='SCAM_CLM5_CLM5F_01'\n\ncityname=['Saskatoon','Toronto','Siderovsk']\ncitylon=[253.330, 280.617, 82.3139]\ncitylat=[52.1579, 43.6532, 66.5973]\n\nfor icity in np.arange(0,3,1):\n\n basedir=\"/project/cas02/islas/CLM5_CLM4/raw/SCAM_CLM_INIT_60days_withclearsky/\"\n pathout=\"/project/cas/islas/python_savs/snowpaper/DATA_SORT/3cities/SCAM_CLMINIT_60days_withclearsky/\"\n \n fpath=basedir+expname[icity]+\"/atm/hist/h0concat.nc\"\n print(fpath)\n dat = read.read_sfc_cesm(fpath,\"1979-01-01T12:00:00\",\"2014-12-31T12:00:00\")\n \n if (icity == 0): \n flnsc = xr.DataArray(np.zeros([dat.time.size, 3]), coords=[dat.time, cityname],\n dims=['time','city'], name='flnsc')\n \n flnsc[:,icity] = dat.FLNSC.isel(lon=0,lat=0)\n \n flnsc.to_netcdf(path=pathout+\"FLNSC_\"+outname+\".nc\")\n",
"import importlib\nimport xarray as xr\nimport numpy as np\nimport pandas as pd\nimport sys\n\nfrom CASutils import filter_utils as filt\nfrom CASutils import readdata_utils as read\nfrom CASutils import calendar_utils as cal\n\nimportlib.reload(filt)\nimportlib.reload(read)\nimportlib.reload(cal)\n\n\nexpname=['SASK_SNOWDa_CLM5F_02.001.FSCAM.sask2_1979_2014',\n 'TOR_SNOWDa_CLM5F_02.001.FSCAM.tor2_1979_2014',\n 'SID_SNOWDa_CLM5F_02.001.FSCAM.sid2_1979_2014']\n\noutname='SCAM_SNOWDa_CLM5F_02'\n\ncityname=['Saskatoon','Toronto','Siderovsk']\ncitylon=[253.330, 280.617, 82.3139]\ncitylat=[52.1579, 43.6532, 66.5973]\n\nfor icity in np.arange(0,3,1):\n\n basedir=\"/project/cas02/islas/CLM5_CLM4/raw/SCAM_new_lowrelax/\"\n pathout=\"/project/cas/islas/python_savs/snowpaper/DATA_SORT/3cities/SCAM/new_lowrelax/\"\n \n fpath=basedir+expname[icity]+\"/atm/hist/h0concat.nc\"\n print(fpath)\n dat = read.read_sfc_cesm(fpath,\"1979-01-01T12:00:00\",\"2014-12-31T12:00:00\")\n \n if (icity == 0): \n trefht = xr.DataArray(np.zeros([dat.time.size, 3]), coords=[dat.time, cityname],\n dims=['time','city'], name='trefht')\n \n trefht[:,icity] = dat.TREFHT.isel(lon=0,lat=0)\n \n trefht.to_netcdf(path=pathout+\"TREFHT_\"+outname+\".nc\")\n",
"import importlib\nimport xarray as xr\nimport numpy as np\nimport pandas as pd\nimport sys\n\nfrom CASutils import filter_utils as filt\nfrom CASutils import readdata_utils as read\nfrom CASutils import calendar_utils as cal\n\nimportlib.reload(filt)\nimportlib.reload(read)\nimportlib.reload(cal)\n\n\nexpname=['SASK_CLM5_CLM5F_02.001.FSCAM.sask2_1979_2014',\n 'TOR_CLM5_CLM5F_02.001.FSCAM.tor2_1979_2014',\n 'SID_CLM5_CLM5F_02.001.FSCAM.sid2_1979_2014']\n\noutname='SCAM_CLM5_CLM5F_02'\n\ncityname=['Saskatoon','Toronto','Siderovsk']\ncitylon=[253.330, 280.617, 82.3139]\ncitylat=[52.1579, 43.6532, 66.5973]\n\nfor icity in np.arange(0,3,1):\n\n basedir=\"/project/cas02/islas/CLM5_CLM4/raw/SCAM_new_lowrelax/\"\n pathout=\"/project/cas/islas/python_savs/snowpaper/DATA_SORT/3cities/SCAM/new_lowrelax/\"\n \n fpath=basedir+expname[icity]+\"/atm/hist/h0concat.nc\"\n print(fpath)\n dat = read.read_sfc_cesm(fpath,\"1979-01-01T12:00:00\",\"2014-12-31T12:00:00\")\n \n if (icity == 0): \n tbot = xr.DataArray(np.zeros([dat.time.size, 3]), coords=[dat.time, cityname],\n dims=['time','city'], name='tbot')\n \n tbot[:,icity] = dat.TBOT.isel(lon=0,lat=0)\n \n tbot.to_netcdf(path=pathout+\"TBOT_\"+outname+\".nc\")\n",
"import importlib\nimport xarray as xr\nimport numpy as np\nimport pandas as pd\nimport sys\n\nfrom CASutils import filter_utils as filt\nfrom CASutils import readdata_utils as read\nfrom CASutils import calendar_utils as cal\n\nimportlib.reload(filt)\nimportlib.reload(read)\nimportlib.reload(cal)\n\n\nexpname=['SASK_SNOWD_CLM5F_01.001.FSCAM.sask_1979_2014',\n 'TOR_SNOWD_CLM5F_01.001.FSCAM.tor_1979_2014',\n 'SID_SNOWD_CLM5F_01.001.FSCAM.sid_1979_2014']\n\noutname='SCAM_SNOWD_CLM5F_01'\n\ncityname=['Saskatoon','Toronto','Siderovsk']\ncitylon=[253.330, 280.617, 82.3139]\ncitylat=[52.1579, 43.6532, 66.5973]\n\nfor icity in np.arange(0,3,1):\n\n basedir=\"/project/cas02/islas/CLM5_CLM4/raw/SCAM_CLM_INIT/\"\n pathout=\"/project/cas/islas/python_savs/snowpaper/DATA_SORT/3cities/SCAM_CLM_INIT/\"\n \n fpath=basedir+expname[icity]+\"/atm/hist/h0concat.nc\"\n print(fpath)\n dat = read.read_sfc_cesm(fpath,\"1979-01-01T12:00:00\",\"2014-12-31T12:00:00\")\n \n if (icity == 0): \n trefht = xr.DataArray(np.zeros([dat.time.size, 3]), coords=[dat.time, cityname],\n dims=['time','city'], name='trefht')\n \n trefht[:,icity] = dat.TREFHT.isel(lon=0,lat=0)\n \n trefht.to_netcdf(path=pathout+\"TREFHT_\"+outname+\".nc\")\n",
"import importlib\nimport xarray as xr\nimport numpy as np\nimport pandas as pd\nimport sys\n\nfrom CASutils import filter_utils as filt\nfrom CASutils import readdata_utils as read\nfrom CASutils import calendar_utils as cal\n\nimportlib.reload(filt)\nimportlib.reload(read)\nimportlib.reload(cal)\n\n\nexpname=['SASK_CLM5_CLM5F_01.001.FSCAM.sask_1979_2014',\n 'TOR_CLM5_CLM5F_01.001.FSCAM.tor_1979_2014',\n 'SID_CLM5_CLM5F_01.001.FSCAM.sid_1979_2014']\n\noutname='SCAM_CLM5_CLM5F_01'\n\ncityname=['Saskatoon','Toronto','Siderovsk']\ncitylon=[253.330, 280.617, 82.3139]\ncitylat=[52.1579, 43.6532, 66.5973]\n\nfor icity in np.arange(0,3,1):\n\n basedir=\"/project/cas02/islas/CLM5_CLM4/raw/SCAM_CLM_INIT/\"\n pathout=\"/project/cas/islas/python_savs/snowpaper/DATA_SORT/3cities/SCAM_CLM_INIT/\"\n \n fpath=basedir+expname[icity]+\"/lnd/hist/h2concat.nc\"\n dat = xr.open_mfdataset(fpath, coords='minimal', join='override', decode_times=True)\n dat = dat.sel(time=slice(\"1979-01-01T00:00:00\", \"2014-12-31T23:50:00\"))\n daystr = xr.DataArray(dat.indexes['time'].strftime('%Y-%m-%d'), coords = dat.time.coords, name='daystr')\n snoliq = dat.SNO_LIQ\n snoliqdaily = snoliq.groupby(daystr).mean('time', skipna=True)\n time = dat.time.groupby(daystr).mean('time')\n snoliqdaily['daystr'] = time\n snoliqdaily = snoliqdaily.rename({'daystr':'time'})\n\n if (icity == 0): \n snoliqout = xr.DataArray(np.zeros([snoliqdaily.time.size, snoliqdaily.levsno.size, 3]), \n coords=[snoliqdaily.time, snoliqdaily.levsno, cityname],\n dims=['time','levsno','city'], name='snoliq')\n \n snoliqout[:,:,icity] = snoliqdaily.isel(lon=0,lat=0)\n \n snoliqout.to_netcdf(path=pathout+\"SNO_LIQ_\"+outname+\".nc\")\n",
"import importlib\nimport xarray as xr\nimport numpy as np\nimport pandas as pd\nimport sys\n\nfrom CASutils import filter_utils as filt\nfrom CASutils import readdata_utils as read\nfrom CASutils import calendar_utils as cal\n\nimportlib.reload(filt)\nimportlib.reload(read)\nimportlib.reload(cal)\n\n\nexpname=['SASK_SNOWD_SNOWDF_02.001.FSCAM.sasksnowd2',\n 'TOR_SNOWD_SNOWDF_02.001.FSCAM.torsnowd2',\n 'SID_SNOWD_SNOWDF_02.001.FSCAM.sidsnowd2']\n\noutname='SCAM_SNOWD_SNOWDF_02'\n\ncityname=['Saskatoon','Toronto','Siderovsk']\ncitylon=[253.330, 280.617, 82.3139]\ncitylat=[52.1579, 43.6532, 66.5973]\n\nfor icity in np.arange(0,3,1):\n\n basedir=\"/project/cas02/islas/CLM5_CLM4/raw/SCAM_CLM_INIT_60days/\"\n pathout=\"/project/cas/islas/python_savs/snowpaper/DATA_SORT/3cities/SCAM_CLMINIT_60days/\"\n \n fpath=basedir+expname[icity]+\"/atm/hist/h0concat.nc\"\n print(fpath)\n dat = read.read_sfc_cesm(fpath,\"1979-01-01T12:00:00\",\"2014-12-31T12:00:00\")\n \n if (icity == 0): \n fsns = xr.DataArray(np.zeros([dat.time.size, 3]), coords=[dat.time, cityname],\n dims=['time','city'], name='fsns')\n \n fsns[:,icity] = dat.FSNS.isel(lon=0,lat=0)\n \n fsns.to_netcdf(path=pathout+\"FSNS_\"+outname+\".nc\")\n",
"import importlib\nimport xarray as xr\nimport numpy as np\nimport pandas as pd\n\nfrom CASutils import filter_utils as filt\nfrom CASutils import readdata_utils as read\nfrom CASutils import calendar_utils as cal\n\nimportlib.reload(filt)\nimportlib.reload(read)\nimportlib.reload(cal)\n\n\nexpname=['SASK_CLM5_CLM5F_02.001.FSCAM.sask2_1979_2014',\n 'TOR_CLM5_CLM5F_02.001.FSCAM.tor2_1979_2014',\n 'SID_CLM5_CLM5F_02.001.FSCAM.sid2_1979_2014']\n\noutname='SCAM_CLM5_CLM5F_002'\n\ncityname=['Saskatoon','Toronto','Siderovsk']\ncitylon=[253.330, 280.617, 82.3139]\ncitylat=[52.1579, 43.6532, 66.5973]\n\nfor icity in np.arange(0,3,1):\n\n basedir=\"/project/cas02/islas/CLM5_CLM4/raw/SCAM_new_lowrelax/\"\n pathout=\"/project/cas/islas/python_savs/snowpaper/DATA_SORT/3cities/\"\n \n fpath=basedir+expname[icity]+\"/atm/hist/h0concat.nc\"\n print(fpath)\n dat = read.read_sfc_cesm(fpath,\"1979-01-01T12:00:00\",\"2014-12-31T12:00:00\")\n \n if (icity == 0): \n ts = xr.DataArray(np.zeros([dat.time.size, 3]), coords=[dat.time, cityname],\n dims=['time','city'], name='ts')\n \n ts[:,icity] = dat.TS.isel(lon=0,lat=0)\n \n ts.to_netcdf(path=pathout+\"TS_\"+outname+\".nc\")\n",
"import importlib\nimport xarray as xr\nimport numpy as np\nimport pandas as pd\nimport sys\n\nfrom CASutils import filter_utils as filt\nfrom CASutils import readdata_utils as read\nfrom CASutils import calendar_utils as cal\n\nimportlib.reload(filt)\nimportlib.reload(read)\nimportlib.reload(cal)\n\n\nexpname=['SASK_SNOWD_CLM5F_01.001.FSCAM.sask_1979_2014',\n 'TOR_SNOWD_CLM5F_01.001.FSCAM.tor_1979_2014',\n 'SID_SNOWD_CLM5F_01.001.FSCAM.sid_1979_2014']\n\noutname='SCAM_SNOWD_CLM5F_01'\n\ncityname=['Saskatoon','Toronto','Siderovsk']\ncitylon=[253.330, 280.617, 82.3139]\ncitylat=[52.1579, 43.6532, 66.5973]\n\nfor icity in np.arange(0,3,1):\n\n basedir=\"/project/cas02/islas/CLM5_CLM4/raw/SCAM_CLM_INIT_60days/\"\n pathout=\"/project/cas/islas/python_savs/snowpaper/DATA_SORT/3cities/SCAM_CLMINIT_60days/\"\n \n fpath=basedir+expname[icity]+\"/atm/hist/h0concat.nc\"\n print(fpath)\n dat = read.read_sfc_cesm(fpath,\"1979-01-01T12:00:00\",\"2014-12-31T12:00:00\")\n \n if (icity == 0): \n t850 = xr.DataArray(np.zeros([dat.time.size, 3]), coords=[dat.time, cityname],\n dims=['time','city'], name='t850')\n \n t850[:,icity] = dat.T850.isel(lon=0,lat=0)\n \n t850.to_netcdf(path=pathout+\"T850_\"+outname+\".nc\")\n",
"import importlib\nimport xarray as xr\nimport numpy as np\nimport pandas as pd\nimport sys\n\nfrom CASutils import filter_utils as filt\nfrom CASutils import readdata_utils as read\nfrom CASutils import calendar_utils as cal\n\nimportlib.reload(filt)\nimportlib.reload(read)\nimportlib.reload(cal)\n\n\nexpname=['SASK_SNOWD_SNOWDF_01.001.FSCAM.sasksnowd1',\n 'TOR_SNOWD_SNOWDF_01.001.FSCAM.torsnowd1',\n 'SID_SNOWD_SNOWDF_01.001.FSCAM.sidsnowd1']\n\noutname='SCAM_SNOWD_SNOWDF_01'\n\ncityname=['Saskatoon','Toronto','Siderovsk']\ncitylon=[253.330, 280.617, 82.3139]\ncitylat=[52.1579, 43.6532, 66.5973]\n\nfor icity in np.arange(0,3,1):\n\n basedir=\"/project/cas02/islas/CLM5_CLM4/raw/SCAM_new_lowrelax/\"\n pathout=\"/project/cas/islas/python_savs/snowpaper/DATA_SORT/3cities/SCAM/new_lowrelax/\"\n \n fpath=basedir+expname[icity]+\"/lnd/hist/h2concat.nc\"\n dat = xr.open_mfdataset(fpath, coords='minimal', join='override', decode_times=True)\n dat = dat.sel(time=slice(\"1979-01-01T00:00:00\", \"2014-12-31T23:50:00\"))\n daystr = xr.DataArray(dat.indexes['time'].strftime('%Y-%m-%d'), coords = dat.time.coords, name='daystr')\n snot = dat.SNO_T\n snotdaily = snot.groupby(daystr).mean('time', skipna=True)\n time = dat.time.groupby(daystr).mean('time')\n snotdaily['daystr'] = time\n snotdaily = snotdaily.rename({'daystr':'time'})\n\n if (icity == 0): \n snotout = xr.DataArray(np.zeros([snotdaily.time.size, snotdaily.levsno.size, 3]), \n coords=[snotdaily.time, snotdaily.levsno, cityname],\n dims=['time','levsno','city'], name='snot')\n \n snotout[:,:,icity] = snotdaily.isel(lon=0,lat=0)\n \n snotout.to_netcdf(path=pathout+\"SNO_T_\"+outname+\".nc\")\n"
] | [
[
"numpy.arange",
"numpy.zeros"
],
[
"numpy.arange",
"numpy.zeros"
],
[
"numpy.arange",
"numpy.zeros"
],
[
"numpy.arange",
"numpy.zeros"
],
[
"numpy.arange",
"numpy.zeros"
],
[
"numpy.arange",
"numpy.zeros"
],
[
"numpy.arange",
"numpy.zeros"
],
[
"numpy.arange",
"numpy.zeros"
],
[
"numpy.arange",
"numpy.zeros"
],
[
"numpy.arange",
"numpy.zeros"
]
] | [
{
"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": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
GuillaumeRochette/HumanViewSynthesis | [
"358d9cb55486ad0f81a31df8ab4159153765e7e5",
"d65ea8744e284ec956bbc04f294f05e47731360f",
"d65ea8744e284ec956bbc04f294f05e47731360f",
"d65ea8744e284ec956bbc04f294f05e47731360f"
] | [
"geometry/matrix.py",
"nn/blur.py",
"data/Panoptic/transform.py",
"operations/metrics/pose.py"
] | [
"from typing import Tuple\nimport torch\nfrom torch import Tensor\n\n\ndef homogeneous(A: Tensor, b: Tensor) -> Tensor:\n \"\"\"\n Converts heterogeneous matrix into homogeneous matrix.\n\n :param A: Heterogeneous matrix of shape [*, N, N].\n :param b: Heterogeneous vector of shape [*, N, 1].\n :return: Homogeneous matrix of shape [*, N + 1, N + 1].\n \"\"\"\n assert A.shape[:-2] == b.shape[:-2]\n assert A.shape[-2] == A.shape[-1] == b.shape[-2]\n assert b.shape[-1] == 1\n\n s, n = A.shape[:-2], A.shape[-2]\n\n c = torch.zeros(s + (1, n), dtype=A.dtype, device=A.device)\n d = torch.ones(s + (1, 1), dtype=A.dtype, device=A.device)\n\n M = torch.cat(\n [\n torch.cat([A, b], dim=-1),\n torch.cat([c, d], dim=-1),\n ],\n dim=-2,\n )\n\n return M\n\n\ndef heterogeneous(M: Tensor) -> Tuple[Tensor, Tensor]:\n \"\"\"\n Converts homogeneous matrix into heterogeneous matrix.\n\n :param M: Homogeneous matrix of shape [*, N + 1, N + 1].\n :return: Heterogeneous matrix and vector of shapes [*, N, N] and [*, N, 1] respectively.\n \"\"\"\n assert M.shape[-2] == M.shape[-1]\n\n n = M.shape[-2] - 1\n\n Ab, cd = M.split([n, 1], dim=-2)\n A, b = Ab.split([n, 1], dim=-1)\n c, d = cd.split([n, 1], dim=-1)\n A, b = A / d, b / d\n\n return A, b\n\n\ndef affine(x: Tensor, A: Tensor, b: Tensor) -> Tensor:\n \"\"\"\n Applies an affine transformation to x given A and b.\n\n :param x: Vector of shape [*, N, 1].\n :param A: Matrix of shape [*, N, N].\n :param b: Vector of shape [*, N, 1].\n :return: Vector of shape [*, N, 1].\n \"\"\"\n assert x.ndim == A.ndim == b.ndim\n assert x.shape[-2] == A.shape[-2] == A.shape[-1] == b.shape[-2]\n assert x.shape[-1] == b.shape[-1] == 1\n\n y = A @ x + b\n\n return y\n\n\ndef eye_like(x: Tensor) -> Tensor:\n \"\"\"\n Return an identity matrix of the same shape as x.\n\n :param x: Matrix of shape [*, M, N].\n :return: Identity matrix of shape [*, M, N].\n \"\"\"\n m, n = x.shape[-2], x.shape[-1]\n\n return torch.eye(m, n, dtype=x.dtype, device=x.device).expand_as(x)\n\n\ndef diag(x: Tensor):\n \"\"\"\n Returns a diagonal matrix given a vector.\n\n :param x: Vector of shape [*, M, 1].\n :return: Diagonal matrix of shape [*, M, M].\n \"\"\"\n assert x.shape[-1] == 1\n m = x.shape[-2]\n\n return torch.eye(m, dtype=x.dtype, device=x.device) * x\n",
"from typing import Union\nfrom math import floor, ceil\n\nimport torch\nfrom torch import Tensor\nfrom torch.nn import Module\nfrom torch.nn import functional as F\n\n\ndef _box_kernel_1d(n: int) -> Tensor:\n assert n > 0\n x = [1.0 for k in range(n)]\n x = torch.tensor(x)\n x = x / x.sum()\n return x\n\n\ndef _binomial_kernel_1d(n: int) -> Tensor:\n assert n > 0\n x = [1.0]\n for k in range(n - 1):\n y = x[k] * (n - 1 - k) / (k + 1)\n x.append(y)\n x = torch.tensor(x)\n x = x / x.sum()\n return x\n\n\ndef _box_kernel_2d(h: int, w: int) -> Tensor:\n a, b = _box_kernel_1d(n=h), _box_kernel_1d(n=w)\n x = a[:, None] * b[None, :]\n return x\n\n\ndef _binomial_kernel_2d(h: int, w: int) -> Tensor:\n a, b = _binomial_kernel_1d(n=h), _binomial_kernel_1d(n=w)\n x = a[:, None] * b[None, :]\n return x\n\n\nclass Blur2d(Module):\n def __init__(\n self,\n kernel_size: int,\n kernel_type: str = \"binomial\",\n stride: int = 1,\n padding: Union[int, float] = 0,\n ):\n super(Blur2d, self).__init__()\n\n self.kernel_size = kernel_size\n\n if kernel_type == \"box\":\n kernel_func = _box_kernel_2d\n elif kernel_type == \"binomial\":\n kernel_func = _binomial_kernel_2d\n else:\n raise ValueError(f\"Unknown kernel type: {kernel_type}.\")\n self.kernel_type = kernel_type\n\n kernel = kernel_func(h=kernel_size, w=kernel_size)\n self.register_buffer(\"kernel\", kernel, persistent=False)\n\n self.stride = stride\n\n if isinstance(padding, float):\n p1, p2 = floor(padding), ceil(padding)\n else:\n p1 = p2 = padding\n\n self.padding = (p1, p2, p1, p2)\n\n def forward(self, input: Tensor) -> Tensor:\n n, c, h, w = input.shape\n kernel = self.kernel.expand((c, 1) + self.kernel.shape)\n\n return F.conv2d(\n input=F.pad(input, self.padding),\n weight=kernel,\n stride=self.stride,\n groups=c,\n )\n\n def extra_repr(self):\n s = (\n f\"kernel_size={self.kernel_size}\"\n f\", kernel_type={self.kernel_type}\"\n f\", stride={self.stride}\"\n f\", padding={self.padding}\"\n )\n return s\n",
"from typing import Tuple, Union\n\nimport torch\nfrom torchvision.transforms import ToTensor as ImageToTensor\n\nfrom data.transforms import (\n MaskToTensor,\n Threshold,\n StaticBoxCrop,\n Resize,\n stabilized_padding,\n)\nfrom data.Panoptic.skeleton import JOINTS\nfrom data.Panoptic.convert import BODY_135_to_BODY_117_2d, BODY_135_to_BODY_117_3d\nfrom data.Panoptic.statistics import MEDIAN_PIXEL\n\nfrom geometry.extrinsic import world_to_camera\n\n\nclass PanopticImageTransform(object):\n def __init__(\n self,\n cr_size: Union[int, Tuple[int, int]] = None,\n re_size: Union[int, Tuple[int, int]] = None,\n ):\n self.i2t = ImageToTensor()\n self.m2t = MaskToTensor()\n self.threshold = Threshold(min_value=0.25, max_value=1.0)\n\n self.crop = None\n if cr_size is not None:\n self.crop = StaticBoxCrop(size=cr_size)\n\n self.resize = None\n if re_size is not None:\n self.resize = Resize(size=re_size)\n\n def __call__(self, input: dict) -> dict:\n p, c = input[\"pose_2d\"].split([2, 1], dim=-2)\n p, c = BODY_135_to_BODY_117_2d(p=p, c=c)\n c = self.threshold(c)\n input[\"pose_2d\"] = {\n \"p\": p,\n \"c\": c,\n }\n\n p, c = input[\"pose_3d\"].split([3, 1], dim=-2)\n p, c = BODY_135_to_BODY_117_3d(p=p, c=c)\n p = world_to_camera(\n xyz=p,\n R=input[\"R\"][None, :, :],\n t=input[\"t\"][None, :, :],\n )\n c = self.threshold(c)\n input[\"pose_3d\"] = {\n \"root\": {\n \"p\": p[JOINTS[\"Sternum\"] : JOINTS[\"Sternum\"] + 1, :, :],\n \"c\": c[JOINTS[\"Sternum\"] : JOINTS[\"Sternum\"] + 1, :, :],\n },\n \"relative\": {\n \"p\": p - p[JOINTS[\"Sternum\"] : JOINTS[\"Sternum\"] + 1, :, :],\n \"c\": c & c[JOINTS[\"Sternum\"] : JOINTS[\"Sternum\"] + 1, :, :],\n },\n }\n\n x_off, y_off = 0.0, 0.0\n if self.crop:\n p, c = input[\"pose_2d\"][\"p\"], input[\"pose_2d\"][\"c\"]\n points = p[c.expand_as(p)].reshape(-1, 2, 1)\n points = points if len(points) > 0 else p\n (m, _), (M, _) = points.min(dim=-3), points.max(dim=-3)\n x_m, y_m = m.squeeze(dim=-1).tolist()\n x_M, y_M = M.squeeze(dim=-1).tolist()\n input[\"image\"], (x_off, y_off) = self.crop(\n image=input[\"image\"],\n bounds=(x_m, y_m, x_M, y_M),\n )\n input[\"mask\"], (_, _) = self.crop(\n image=input[\"mask\"],\n bounds=(x_m, y_m, x_M, y_M),\n )\n input[\"K\"] = input[\"K\"] - torch.tensor(\n [\n [0.0, 0.0, x_off],\n [0.0, 0.0, y_off],\n [0.0, 0.0, 0.0],\n ]\n )\n # input[\"pose_2d\"][\"p\"] = input[\"pose_2d\"][\"p\"] - torch.tensor([[x_off], [y_off]])\n input[\"crop_offset\"] = torch.tensor([x_off, y_off])\n input[\"cropped_resolution\"] = torch.tensor(input[\"image\"].size)\n\n if self.resize:\n input[\"image\"], (w_r, h_r) = self.resize(image=input[\"image\"])\n input[\"mask\"], (_, _) = self.resize(image=input[\"mask\"])\n input[\"K\"] = input[\"K\"] * torch.tensor(\n [\n [w_r, 1.0, w_r],\n [1.0, h_r, h_r],\n [1.0, 1.0, 1.0],\n ]\n )\n # input[\"pose_2d\"][\"p\"] = input[\"pose_2d\"][\"p\"] * torch.tensor([[w_r], [h_r]])\n input[\"resized_resolution\"] = torch.tensor(input[\"image\"].size)\n\n input[\"stabilized_padding\"] = stabilized_padding(\n crop_offset=input[\"crop_offset\"],\n original_resolution=input[\"resolution\"],\n cropped_resolution=input[\"cropped_resolution\"],\n resized_resolution=input[\"resized_resolution\"],\n )\n\n input[\"image\"] = self.i2t(input[\"image\"])\n input[\"mask\"] = self.m2t(input[\"mask\"])\n # input[\"masked_image\"] = input[\"mask\"] * input[\"image\"]\n input[\"masked_image\"] = (\n input[\"mask\"] * input[\"image\"]\n + ~input[\"mask\"] * MEDIAN_PIXEL[..., None, None]\n )\n\n return input\n\n\nclass PanopticImagePairTransform(object):\n def __init__(\n self,\n cr_size_A: Union[int, Tuple[int, int]] = None,\n cr_size_B: Union[int, Tuple[int, int]] = None,\n re_size_A: Union[int, Tuple[int, int]] = None,\n re_size_B: Union[int, Tuple[int, int]] = None,\n ):\n self.i2t = ImageToTensor()\n self.m2t = MaskToTensor()\n self.threshold = Threshold(min_value=0.25, max_value=1.0)\n\n self.views = [\"A\", \"B\"]\n self.crop = {\n \"A\": None,\n \"B\": None,\n }\n if cr_size_A is not None:\n self.crop[\"A\"] = StaticBoxCrop(size=cr_size_A)\n if cr_size_B is not None:\n self.crop[\"B\"] = StaticBoxCrop(size=cr_size_B)\n\n self.resize = {\n \"A\": None,\n \"B\": None,\n }\n if re_size_A is not None:\n self.resize[\"A\"] = Resize(size=re_size_A)\n if re_size_B is not None:\n self.resize[\"B\"] = Resize(size=re_size_B)\n\n def __call__(self, input: dict) -> dict:\n for v in self.views:\n p, c = input[v][\"pose_2d\"].split([2, 1], dim=-2)\n p, c = BODY_135_to_BODY_117_2d(p=p, c=c)\n c = self.threshold(c)\n input[v][\"pose_2d\"] = {\n \"p\": p,\n \"c\": c,\n }\n\n p, c = input[\"W\"][\"pose_3d\"].split([3, 1], dim=-2)\n p, c = BODY_135_to_BODY_117_3d(p=p, c=c)\n p = world_to_camera(\n xyz=p,\n R=input[v][\"R\"][None, :, :],\n t=input[v][\"t\"][None, :, :],\n )\n c = self.threshold(c)\n input[v][\"pose_3d\"] = {\n \"root\": {\n \"p\": p[JOINTS[\"Sternum\"] : JOINTS[\"Sternum\"] + 1, :, :],\n \"c\": c[JOINTS[\"Sternum\"] : JOINTS[\"Sternum\"] + 1, :, :],\n },\n \"relative\": {\n \"p\": p - p[JOINTS[\"Sternum\"] : JOINTS[\"Sternum\"] + 1, :, :],\n \"c\": c & c[JOINTS[\"Sternum\"] : JOINTS[\"Sternum\"] + 1, :, :],\n },\n }\n\n x_off, y_off = 0.0, 0.0\n if self.crop[v]:\n p, c = input[v][\"pose_2d\"][\"p\"], input[v][\"pose_2d\"][\"c\"]\n points = p[c.expand_as(p)].reshape(-1, 2, 1)\n points = points if len(points) > 0 else p\n (m, _), (M, _) = points.min(dim=-3), points.max(dim=-3)\n x_m, y_m = m.squeeze(dim=-1).tolist()\n x_M, y_M = M.squeeze(dim=-1).tolist()\n input[v][\"image\"], (x_off, y_off) = self.crop[v](\n image=input[v][\"image\"],\n bounds=(x_m, y_m, x_M, y_M),\n )\n input[v][\"mask\"], (_, _) = self.crop[v](\n image=input[v][\"mask\"],\n bounds=(x_m, y_m, x_M, y_M),\n )\n input[v][\"K\"] = input[v][\"K\"] - torch.tensor(\n [\n [0.0, 0.0, x_off],\n [0.0, 0.0, y_off],\n [0.0, 0.0, 0.0],\n ]\n )\n # input[v][\"pose_2d\"][\"p\"] = input[v][\"pose_2d\"][\"p\"] - torch.tensor([[x_off], [y_off]])\n input[v][\"crop_offset\"] = torch.tensor([x_off, y_off])\n input[v][\"cropped_resolution\"] = torch.tensor(input[v][\"image\"].size)\n\n if self.resize[v]:\n input[v][\"image\"], (w_r, h_r) = self.resize[v](image=input[v][\"image\"])\n input[v][\"mask\"], (_, _) = self.resize[v](image=input[v][\"mask\"])\n input[v][\"K\"] = input[v][\"K\"] * torch.tensor(\n [\n [w_r, 1.0, w_r],\n [1.0, h_r, h_r],\n [1.0, 1.0, 1.0],\n ]\n )\n # input[v][\"pose_2d\"][\"p\"] = input[v][\"pose_2d\"][\"p\"] * torch.tensor([[w_r], [h_r]])\n input[v][\"resized_resolution\"] = torch.tensor(input[v][\"image\"].size)\n\n input[v][\"stabilized_padding\"] = stabilized_padding(\n crop_offset=input[v][\"crop_offset\"],\n original_resolution=input[v][\"resolution\"],\n cropped_resolution=input[v][\"cropped_resolution\"],\n resized_resolution=input[v][\"resized_resolution\"],\n )\n\n input[v][\"image\"] = self.i2t(input[v][\"image\"])\n input[v][\"mask\"] = self.m2t(input[v][\"mask\"])\n # input[v][\"masked_image\"] = input[v][\"mask\"] * input[v][\"image\"]\n input[v][\"masked_image\"] = (\n input[v][\"mask\"] * input[v][\"image\"]\n + ~input[v][\"mask\"] * MEDIAN_PIXEL[..., None, None]\n )\n\n return input\n",
"import torch\nfrom torch import Tensor\nfrom torchmetrics import Metric\n\nfrom operations.reduce import weighted_mean\n\n\ndef mpjpe(input: Tensor, target: Tensor) -> Tensor:\n \"\"\"\n Computes the Mean Per Joint Position Error between a prediction and a target.\n\n :param input: [*, J, 3, 1].\n :param target: [*, J, 3, 1].\n :return: [*].\n \"\"\"\n assert input.shape[:-2] == target.shape[:-2]\n assert input.shape[-1] == target.shape[-1] == 1\n\n error = (input - target).norm(p=2, dim=[-2, -1]).mean(dim=-1)\n return error\n\n\nclass MPJPEMetric(Metric):\n def __init__(self, dist_sync_on_step=False):\n super(MPJPEMetric, self).__init__(dist_sync_on_step=dist_sync_on_step)\n\n self.add_state(\n \"num\",\n default=torch.tensor(0, dtype=torch.double),\n dist_reduce_fx=\"sum\",\n )\n self.add_state(\n \"den\",\n default=torch.tensor(0, dtype=torch.long),\n dist_reduce_fx=\"sum\",\n )\n\n def update(self, input: Tensor, target: Tensor):\n error = mpjpe(input=input, target=target)\n\n self.num += torch.sum(error)\n self.den += error.numel()\n\n def compute(self) -> Tensor:\n return self.num / self.den\n\n\ndef nmpjpe(input: Tensor, target: Tensor) -> Tensor:\n \"\"\"\n Computes the Normalised Mean Per Joint Position Error between a prediction and a target.\n\n :param input: [*, J, 3, 1].\n :param target: [*, J, 3, 1].\n :return: [*].\n \"\"\"\n assert input.shape[:-2] == target.shape[:-2]\n assert input.shape[-1] == target.shape[-1] == 1\n\n num = (input * target).sum(dim=[-3, -2, -1], keepdim=True)\n den = (input * input).sum(dim=[-3, -2, -1], keepdim=True)\n alpha = num / den\n input_ = alpha * input\n error = (input_ - target).norm(p=2, dim=[-2, -1]).mean(dim=-1)\n\n return error\n\n\nclass NMPJPEMetric(Metric):\n def __init__(self, dist_sync_on_step=False):\n super(NMPJPEMetric, self).__init__(dist_sync_on_step=dist_sync_on_step)\n\n self.add_state(\n \"num\",\n default=torch.tensor(0, dtype=torch.double),\n dist_reduce_fx=\"sum\",\n )\n self.add_state(\n \"den\",\n default=torch.tensor(0, dtype=torch.long),\n dist_reduce_fx=\"sum\",\n )\n\n def update(self, input: Tensor, target: Tensor):\n error = nmpjpe(input=input, target=target)\n\n self.num += torch.sum(error)\n self.den += error.numel()\n\n def compute(self) -> Tensor:\n return self.num / self.den\n\n\ndef procrustes(input: Tensor, target: Tensor):\n \"\"\"\n Computes the Procrustes transformation between a prediction and a target.\n\n :param input: Tensor of shape [*, J, 3, 1].\n :param target: Tensor of shape [*, J, 3, 1].\n :return:\n \"\"\"\n input_ = input.squeeze(dim=-1)\n target_ = target.squeeze(dim=-1)\n\n input_mean = input_.mean(dim=-2)\n target_mean = target_.mean(dim=-2)\n\n input_ = input_ - input_mean[..., None, :]\n target_ = target_ - target_mean[..., None, :]\n\n input_norm = input_.norm(dim=[-2, -1])\n target_norm = target_.norm(dim=[-2, -1])\n\n input_ = input_ / input_norm[..., None, None]\n target_ = target_ / target_norm[..., None, None]\n\n A = target_.transpose(-1, -2) @ input_\n U, S, V = A.svd()\n\n tr = S.sum(dim=-1)\n a = tr * (target_norm / input_norm)\n\n R = U @ V.transpose(-1, -2)\n\n t = target_mean[..., None] - a[..., None, None] * (R @ input_mean[..., None])\n return a, R, t\n\n\ndef pmpjpe(input: Tensor, target: Tensor) -> Tensor:\n \"\"\"\n Computes the Procrustes Mean Per Joint Position Error between a prediction and a target.\n\n :param input: [*, J, 3, 1].\n :param target: [*, J, 3, 1].\n :return:\n \"\"\"\n assert input.shape[:-2] == target.shape[:-2]\n assert input.shape[-1] == target.shape[-1] == 1\n\n a, R, t = procrustes(input=input, target=target)\n a = a[..., None, None, None]\n R = R[..., None, :, :]\n t = t[..., None, :, :]\n input_ = a * (R @ input) + t\n error = (input_ - target).norm(p=2, dim=[-2, -1]).mean(dim=-1)\n\n return error\n\n\nclass PMPJPEMetric(Metric):\n def __init__(self, dist_sync_on_step=False):\n super(PMPJPEMetric, self).__init__(dist_sync_on_step=dist_sync_on_step)\n\n self.add_state(\n \"num\",\n default=torch.tensor(0, dtype=torch.double),\n dist_reduce_fx=\"sum\",\n )\n self.add_state(\n \"den\",\n default=torch.tensor(0, dtype=torch.long),\n dist_reduce_fx=\"sum\",\n )\n\n def update(self, input: Tensor, target: Tensor):\n error = pmpjpe(input=input, target=target)\n\n self.num += torch.sum(error)\n self.den += error.numel()\n\n def compute(self) -> Tensor:\n return self.num / self.den\n\n\ndef mpvjpe(input: Tensor, target: Tensor, weight: Tensor) -> Tensor:\n \"\"\"\n Computes the Mean Per Valid Joint Position Error between a prediction and a target.\n\n :param input: [*, J, 3, 1].\n :param target: [*, J, 3, 1].\n :param weight: [*, J, 1, 1].\n :return:\n \"\"\"\n assert input.shape[:-2] == target.shape[:-2] == weight.shape[:-2]\n assert input.shape[-1] == target.shape[-1] == 1\n assert weight.shape[-2] == weight.shape[-1] == 1\n\n error = weighted_mean(\n input=(input - target).norm(p=2, dim=[-2, -1], keepdim=True),\n weight=weight,\n dim=[-3, -2, -1],\n )\n\n return error\n\n\nclass MPVJPEMetric(Metric):\n def __init__(self, dist_sync_on_step=False):\n super(MPVJPEMetric, self).__init__(dist_sync_on_step=dist_sync_on_step)\n\n self.add_state(\n \"num\",\n default=torch.tensor(0, dtype=torch.double),\n dist_reduce_fx=\"sum\",\n )\n self.add_state(\n \"den\",\n default=torch.tensor(0, dtype=torch.long),\n dist_reduce_fx=\"sum\",\n )\n\n def update(self, input: Tensor, target: Tensor, weight: Tensor):\n error = mpvjpe(input=input, target=target, weight=weight)\n\n self.num += torch.sum(error)\n self.den += error.numel()\n\n def compute(self) -> Tensor:\n return self.num / self.den\n"
] | [
[
"torch.eye",
"torch.ones",
"torch.cat",
"torch.zeros"
],
[
"torch.nn.functional.pad",
"torch.tensor"
],
[
"torch.tensor"
],
[
"torch.sum",
"torch.tensor"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
tomcattigerkkk/traj_gen | [
"d01882c17d8e979860fb1f09defa968a86adb494"
] | [
"python/scripts/traj_gen/chomp_trajectory.py"
] | [
"#!/usr/bin/env python\n# coding=utf-8\n\nfrom .traj_gen_base import TrajGen\nimport numpy as np\nimport casadi as ca\nfrom scipy.interpolate import interp1d\nclass CHOMPTrajGen(TrajGen):\n def __init__(self, knots_, dim_, pntDensity_):\n super().__init__(knots_, dim_)\n self.pntDensity = pntDensity_\n assert knots_.shape[0]==2, 'For optimalTraj, knots = [t0, tf]'\n self.num_variables = int(np.floor((knots_[-1]-knots_[0])*pntDensity_))\n self.dt = (knots_[-1]-knots_[0])/(self.num_variables-1)\n self.ts = np.linspace(knots_[0], knots_[-1], self.num_variables) # different from Ts\n self.Xs = np.zeros((self.dim, self.num_variables))\n\n def findStepIndex(self, t):\n \"\"\"\n find the closest index of the segment\n \"\"\"\n time_diff = (self.ts-t)**2\n return np.where(time_diff==np.min(time_diff))[0][0]\n\n def setDerivativeObj(self, weight_mask):\n self.weight_mask = weight_mask\n\n def addPin(self, pin_):\n if pin_['d'] >= self.num_variables:\n print(\"Warning: The degree of the pin exceed the total number of variables. This pin ignored\\n\")\n super().addPin(pin_)\n X_ = pin_['X']\n m = 0\n if len(X_.shape) == 2: # 2 dimension ==> loose pin\n if m in self.loosePinSet.keys():\n self.loosePinSet[m].append(pin_)\n else:\n self.loosePinSet[m] = [pin_]\n elif len(X_.shape) == 1: # vector ==> fix pin\n if m in self.fixPinSet.keys():\n self.fixPinSet[m].append(pin_)\n else:\n self.fixPinSet[m] = [pin_]\n else:\n print(\"Warning: Dim of pin value is invalid\\n\")\n\n def getDiffMat(self, d_):\n if d_ == 0:\n mat_ = np.diag(np.ones(self.num_variables))\n else:\n mat_ = np.diag(np.ones(self.num_variables))\n for j in range(1, d_+1):\n D_ = np.zeros((self.num_variables-j, self.num_variables-j+1))\n for i in range(self.num_variables-j):\n D_[i, i:i+2] = np.array([-1, 1])\n D_ = D_/self.dt\n mat_ = np.dot(D_, mat_)\n return mat_\n\n def loosePin2InequalityMat(self,):\n ASet = None\n BSet = None\n if len(self.loosePinSet.keys()) == 0:\n return ASet, BSet\n for pin in self.loosePinSet[0]:\n a_set_ = []\n b_set_ = []\n for dd in range(self.dim):\n\n n_ = np.min([self.findStepIndex(pin['t']), self.num_variables-pin['d']-1])\n a_ = np.zeros((2, self.num_variables-pin['d']))\n a_[:, n_] = np.array([1, -1])\n a_ = np.dot(a_, self.getDiffMat(pin['d']))\n a_set_.append(a_)\n b_ = np.array([pin['X'][dd, 1], -pin['X'][dd, 0]]).reshape(-1, 1)\n b_set_.append(b_)\n\n if ASet is None:\n ASet = np.array(a_set_)\n BSet = np.array(b_set_).reshape(self.dim, -1, 1)\n else:\n ASet = np.concatenate((ASet, np.array(a_set_)), axis=1)\n BSet = np.concatenate((BSet, np.array(b_set_).reshape(self.dim, -1, 1)), axis=1)\n print('Bset final in {}'.format(BSet.shape))\n return ASet, BSet\n\n def fixPin2EqualityMat(self,):\n AeqSet = None\n BeqSet = None\n if len(self.fixPinSet.keys())==0:\n return AeqSet, BeqSet\n for pin in self.fixPinSet[0]:\n aeq_set_ = []\n beq_set_ = []\n for dd in range(self.dim):\n n_ = np.min([self.findStepIndex(pin['t']), self.num_variables-pin['d']-1])\n a_ = np.zeros(self.num_variables-pin['d'])\n a_[n_] = 1.0\n a_ = np.dot(a_, self.getDiffMat(pin['d']))\n aeq_set_.append(a_)\n # print(aeq_set_)\n b_ = pin['X'][dd]\n beq_set_.append(b_)\n if AeqSet is None:\n AeqSet = np.array(aeq_set_).reshape(self.dim, 1, -1)\n BeqSet = np.array(beq_set_).reshape(self.dim, 1, -1)\n # print(AeqSet.shape)\n # print(BeqSet.shape)\n else:\n AeqSet = np.concatenate((AeqSet, np.array(aeq_set_).reshape(self.dim, 1, -1)), axis=1)\n BeqSet = np.concatenate((BeqSet, np.array(beq_set_).reshape(self.dim, 1, -1)), axis=1)\n # print(BeqSet.shape)\n return AeqSet, BeqSet\n\n def getQPset(self,):\n # 1. objective\n QSet = np.zeros((self.dim, self.num_variables, self.num_variables))\n for dd in range(self.dim):\n Q_ = np.zeros((self.num_variables, self.num_variables))\n for d in range(1, self.weight_mask.shape[0]+1):\n if self.weight_mask[d-1]>0:\n temp_ = self.getDiffMat(d)\n Qd_ = np.dot(temp_.T, temp_)\n Q_ = Q_ + self.weight_mask[d-1]*Qd_\n QSet[dd] = Q_\n\n # 2. constraints\n ASet, BSet = self.loosePin2InequalityMat()\n AeqSet, BeqSet = self.fixPin2EqualityMat()\n\n return QSet, ASet, BSet, AeqSet, BeqSet\n\n def solve(self,):\n self.isSolved = True\n # prepare QP\n QSet, ASet, BSet, AeqSet, BeqSet = self.getQPset()\n\n if ASet is None:\n print(\"Please define the beginning and also the end pins\")\n return False\n\n for dd in range(self.dim):\n print('solving {}-th dimension.. \\n'.format(dd))\n x_sym = ca.SX.sym('x', QSet[0].shape[0])\n opts_setting = {'ipopt.max_iter':100, 'ipopt.print_level':0, 'print_time':0, 'ipopt.acceptable_tol':1e-8, 'ipopt.acceptable_obj_change_tol':1e-6}\n obj = ca.mtimes([x_sym.T, QSet[dd], x_sym])\n if ASet is None:\n a_set = AeqSet[dd].copy()\n else:\n a_set = np.concatenate((ASet[dd], AeqSet[dd]))\n Ax_sym = ca.mtimes([a_set, x_sym])\n if BSet is None:\n b_set_u = BeqSet[dd]\n b_set_l = BeqSet[dd]\n else:\n b_set_u = np.concatenate((BSet[dd], BeqSet[dd]), axis=0) # Ax <= b_set_u\n b_set_l = np.concatenate((-np.inf*np.ones(BSet[dd].shape), BeqSet[dd]), axis=0) # Ax >= b_set_l\n nlp_prob = {'f': obj, 'x': x_sym, 'g':Ax_sym}\n solver = ca.nlpsol('solver', 'ipopt', nlp_prob, opts_setting)\n try:\n result = solver(lbg=b_set_l, ubg=b_set_u,)\n Phat_ = result['x']\n # print(Phat_)\n flag_ = True\n except:\n Phat_ = None\n flag_ = False\n if flag_:\n self.Xs[dd] = Phat_.full().flatten()\n else:\n self.isSolved = False\n print(\"Failure ..\")\n return False\n return True\n\n def eval(self, t_, d_):\n val_ = np.zeros((self.dim, t_.shape[0]))\n for dd in range(self.dim):\n for idx in range(t_.shape[0]):\n t_i = t_[idx]\n if t_i < self.Ts[0] or t_i > self.Ts[-1]:\n print(\"WARNING: Eval of t: out of bound. Extrapolation\\n\")\n Xsd_ = np.dot(self.getDiffMat(d_), self.Xs[dd].T)\n if d_ >0:\n t_v_ = self.ts[:-d_]\n else:\n t_v_ = self.ts\n # print(t_v_.shape)\n # print(Xsd_.shape)\n set_interp = interp1d(t_v_, Xsd_, kind='linear')\n # print(t_v_[-1])\n # print(t_[idx])\n if t_[idx] <= t_v_[-1]:\n val_[dd, idx] = set_interp(t_[idx])\n else:\n val_[dd, idx] = set_interp(t_v_[-1])\n return val_\n"
] | [
[
"numpy.dot",
"numpy.linspace",
"numpy.min",
"numpy.ones",
"numpy.concatenate",
"scipy.interpolate.interp1d",
"numpy.floor",
"numpy.array",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"1.6",
"0.14",
"1.10",
"0.15",
"1.4",
"0.16",
"1.9",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"1.0",
"0.17",
"1.3",
"1.8"
],
"tensorflow": []
}
] |
SmirnovKol/recurrent-visual-attention | [
"a38ac8958ebf1c61a10c4d5320f1e31d3d0b73dd"
] | [
"data_loader.py"
] | [
"import numpy as np\nfrom utils import plot_images\n\nimport torch\nfrom torchvision import datasets\nfrom torchvision import transforms\nfrom torch.utils.data.sampler import SubsetRandomSampler\n\n\ndef get_train_valid_loader(\n data_dir,\n batch_size,\n random_seed,\n valid_size=0.1,\n shuffle=True,\n show_sample=False,\n num_workers=4,\n pin_memory=False,\n):\n \"\"\"Train and validation data loaders.\n\n If using CUDA, num_workers should be set to 1 and pin_memory to True.\n\n Args:\n data_dir: path directory to the dataset.\n batch_size: how many samples per batch to load.\n random_seed: fix seed for reproducibility.\n valid_size: percentage split of the training set used for\n the validation set. Should be a float in the range [0, 1].\n In the paper, this number is set to 0.1.\n shuffle: whether to shuffle the train/validation indices.\n show_sample: plot 9x9 sample grid of the dataset.\n num_workers: number of subprocesses to use when loading the dataset.\n pin_memory: whether to copy tensors into CUDA pinned memory. Set it to\n True if using GPU.\n \"\"\"\n error_msg = \"[!] valid_size should be in the range [0, 1].\"\n assert (valid_size >= 0) and (valid_size <= 1), error_msg\n\n # define transforms\n normalize = transforms.Normalize((0.1307,), (0.3081,))\n trans = transforms.Compose([transforms.ToTensor(), normalize])\n\n # load dataset\n dataset = datasets.MNIST(data_dir, train=True, download=True, transform=trans)\n\n num_train = len(dataset)\n indices = list(range(num_train))\n split = int(np.floor(valid_size * num_train))\n\n if shuffle:\n np.random.seed(random_seed)\n np.random.shuffle(indices)\n\n train_idx, valid_idx = indices[split:], indices[:split]\n\n train_sampler = SubsetRandomSampler(train_idx)\n valid_sampler = SubsetRandomSampler(valid_idx)\n\n train_loader = torch.utils.data.DataLoader(\n dataset,\n batch_size=batch_size,\n sampler=train_sampler,\n num_workers=num_workers,\n pin_memory=pin_memory,\n )\n\n valid_loader = torch.utils.data.DataLoader(\n dataset,\n batch_size=batch_size,\n sampler=valid_sampler,\n num_workers=num_workers,\n pin_memory=pin_memory,\n )\n\n # visualize some images\n if show_sample:\n sample_loader = torch.utils.data.DataLoader(\n dataset,\n batch_size=9,\n shuffle=shuffle,\n num_workers=num_workers,\n pin_memory=pin_memory,\n )\n data_iter = iter(sample_loader)\n images, labels = data_iter.next()\n X = images.numpy()\n X = np.transpose(X, [0, 2, 3, 1])\n plot_images(X, labels)\n\n return (train_loader, valid_loader)\n\n\ndef get_test_loader(data_dir, batch_size, num_workers=4, pin_memory=False):\n \"\"\"Test datalaoder.\n\n If using CUDA, num_workers should be set to 1 and pin_memory to True.\n\n Args:\n data_dir: path directory to the dataset.\n batch_size: how many samples per batch to load.\n num_workers: number of subprocesses to use when loading the dataset.\n pin_memory: whether to copy tensors into CUDA pinned memory. Set it to\n True if using GPU.\n \"\"\"\n # define transforms\n normalize = transforms.Normalize((0.1307,), (0.3081,))\n trans = transforms.Compose([transforms.ToTensor(), normalize])\n\n # load dataset\n dataset = datasets.MNIST(data_dir, train=False, download=True, transform=trans)\n\n data_loader = torch.utils.data.DataLoader(\n dataset,\n batch_size=batch_size,\n shuffle=False,\n num_workers=num_workers,\n pin_memory=pin_memory,\n )\n\n return data_loader\n"
] | [
[
"numpy.random.seed",
"torch.utils.data.DataLoader",
"torch.utils.data.sampler.SubsetRandomSampler",
"numpy.random.shuffle",
"numpy.floor",
"numpy.transpose"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
badrutdinovrr/darts | [
"434708e63cbda8f710d3c1810d06ad31c11db923"
] | [
"cnn/model_search.py"
] | [
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom operations import *\nfrom torch.autograd import Variable\nfrom genotypes import PRIMITIVES\nfrom genotypes import Genotype\n\n\nclass MixedOp(nn.Module):\n\n def __init__(self, C, stride):\n super(MixedOp, self).__init__()\n self._ops = nn.ModuleList()\n for primitive in PRIMITIVES:\n op = OPS[primitive](C, stride, False)\n if 'pool' in primitive:\n op = nn.Sequential(op, nn.BatchNorm2d(C, affine=False))\n self._ops.append(op)\n\n def forward(self, x, weights):\n return sum(w * op(x) for w, op in zip(weights, self._ops))\n\n\nclass Cell(nn.Module):\n\n def __init__(self, steps, multiplier, C_prev_prev, C_prev, C, reduction, reduction_prev):\n super(Cell, self).__init__()\n self.reduction = reduction\n\n if reduction_prev:\n self.preprocess0 = FactorizedReduce(C_prev_prev, C, affine=False)\n else:\n self.preprocess0 = ReLUConvBN(C_prev_prev, C, 1, 1, 0, affine=False)\n self.preprocess1 = ReLUConvBN(C_prev, C, 1, 1, 0, affine=False)\n self._steps = steps\n self._multiplier = multiplier\n\n self._ops = nn.ModuleList()\n self._bns = nn.ModuleList()\n for i in range(self._steps):\n for j in range(2+i):\n stride = 2 if reduction and j < 2 else 1\n op = MixedOp(C, stride)\n self._ops.append(op)\n\n def forward(self, s0, s1, weights):\n s0 = self.preprocess0(s0)\n s1 = self.preprocess1(s1)\n\n states = [s0, s1]\n offset = 0\n for i in range(self._steps):\n s = sum(self._ops[offset+j](h, weights[offset+j]) for j, h in enumerate(states))\n offset += len(states)\n states.append(s)\n\n return torch.cat(states[-self._multiplier:], dim=1)\n\n\nclass Network(nn.Module):\n\n def __init__(self, C, num_classes, layers, criterion, steps=4, multiplier=4, stem_multiplier=3):\n super(Network, self).__init__()\n self._C = C\n self._num_classes = num_classes\n self._layers = layers\n self._criterion = criterion\n self._steps = steps\n self._multiplier = multiplier\n\n C_curr = stem_multiplier*C\n self.stem = nn.Sequential(\n nn.Conv2d(1, C_curr, 3, padding=1, bias=False),\n nn.BatchNorm2d(C_curr)\n )\n \n C_prev_prev, C_prev, C_curr = C_curr, C_curr, C\n self.cells = nn.ModuleList()\n reduction_prev = False\n for i in range(layers):\n if i in [layers//3, 2*layers//3]:\n C_curr *= 2\n reduction = True\n else:\n reduction = False\n cell = Cell(steps, multiplier, C_prev_prev, C_prev, C_curr, reduction, reduction_prev)\n reduction_prev = reduction\n self.cells += [cell]\n C_prev_prev, C_prev = C_prev, multiplier*C_curr\n\n self.global_pooling = nn.AdaptiveAvgPool2d(1)\n self.classifier = nn.Linear(C_prev, num_classes)\n\n self._initialize_alphas()\n\n def new(self):\n model_new = Network(self._C, self._num_classes, self._layers, self._criterion).cuda()\n for x, y in zip(model_new.arch_parameters(), self.arch_parameters()):\n x.data.copy_(y.data)\n return model_new\n\n def forward(self, input):\n s0 = s1 = self.stem(input)\n for i, cell in enumerate(self.cells):\n if cell.reduction:\n weights = F.softmax(self.alphas_reduce, dim=-1)\n else:\n weights = F.softmax(self.alphas_normal, dim=-1)\n s0, s1 = s1, cell(s0, s1, weights)\n out = self.global_pooling(s1)\n logits = self.classifier(out.view(out.size(0),-1))\n return logits\n\n def _loss(self, input, target):\n logits = self(input)\n return self._criterion(logits, target) \n\n def _initialize_alphas(self):\n k = sum(1 for i in range(self._steps) for n in range(2+i))\n num_ops = len(PRIMITIVES)\n\n self.alphas_normal = Variable(1e-3*torch.randn(k, num_ops).cuda(), requires_grad=True)\n self.alphas_reduce = Variable(1e-3*torch.randn(k, num_ops).cuda(), requires_grad=True)\n self._arch_parameters = [\n self.alphas_normal,\n self.alphas_reduce,\n ]\n\n def arch_parameters(self):\n return self._arch_parameters\n\n def genotype(self):\n\n def _parse(weights):\n gene = []\n n = 2\n start = 0\n for i in range(self._steps):\n end = start + n\n W = weights[start:end].copy()\n edges = sorted(range(i + 2), key=lambda x: -max(W[x][k] for k in range(len(W[x])) if k != PRIMITIVES.index('none')))[:2]\n for j in edges:\n k_best = None\n for k in range(len(W[j])):\n if k != PRIMITIVES.index('none'):\n if k_best is None or W[j][k] > W[j][k_best]:\n k_best = k\n gene.append((PRIMITIVES[k_best], j))\n start = end\n n += 1\n return gene\n\n gene_normal = _parse(F.softmax(self.alphas_normal, dim=-1).data.cpu().numpy())\n gene_reduce = _parse(F.softmax(self.alphas_reduce, dim=-1).data.cpu().numpy())\n\n concat = range(2+self._steps-self._multiplier, self._steps+2)\n genotype = Genotype(\n normal=gene_normal, normal_concat=concat,\n reduce=gene_reduce, reduce_concat=concat\n )\n return genotype\n\n"
] | [
[
"torch.nn.functional.softmax",
"torch.cat",
"torch.randn",
"torch.nn.ModuleList",
"torch.nn.Conv2d",
"torch.nn.Linear",
"torch.nn.AdaptiveAvgPool2d",
"torch.nn.BatchNorm2d"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
915288938lx/Personae-master-01 | [
"0885c37956bd3f9157c66109e09755a51ad5d3a1"
] | [
"algorithm/RL/DDPG.py"
] | [
"# coding=utf-8\n\nimport tensorflow as tf\nimport numpy as np\n\nimport os\n\nfrom algorithm import config\nfrom base.env.market import Market\nfrom checkpoints import CHECKPOINTS_DIR\nfrom base.algorithm.model import BaseRLTFModel\nfrom helper.args_parser import model_launcher_parser\nfrom helper.data_logger import generate_algorithm_logger, generate_market_logger\n\n\nclass Algorithm(BaseRLTFModel):\n\n def __init__(self, session, env, a_space, s_space, **options):\n super(Algorithm, self).__init__(session, env, a_space, s_space, **options)\n\n self.actor_loss, self.critic_loss = .0, .0\n\n # Initialize buffer.\n self.buffer = np.zeros((self.buffer_size, self.s_space * 2 + 1 + 1))\n self.buffer_length = 0\n\n self._init_input()\n self._init_nn()\n self._init_op()\n self._init_saver()\n self._init_summary_writer()\n\n def _init_input(self):\n self.s = tf.placeholder(tf.float32, [None, self.s_space], 'state')\n self.r = tf.placeholder(tf.float32, [None, 1], 'reward')\n self.s_next = tf.placeholder(tf.float32, [None, self.s_space], 'state_next')\n\n def _init_nn(self):\n # Initialize predict actor and critic.\n self.a_predict = self.__build_actor_nn(self.s, \"predict/actor\", trainable=True)\n self.q_predict = self.__build_critic(self.s, self.a_predict, \"predict/critic\", trainable=True)\n # Initialize target actor and critic.\n self.a_next = self.__build_actor_nn(self.s_next, \"target/actor\", trainable=False)\n self.q_next = self.__build_critic(self.s_next, self.a_next, \"target/critic\", trainable=False)\n # Save scopes\n self.scopes = [\"predict/actor\", \"target/actor\", \"predict/critic\", \"target/critic\"]\n\n def _init_op(self):\n # Get actor and critic parameters.\n params = [tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope) for scope in self.scopes]\n zipped_a_params, zipped_c_params = zip(params[0], params[1]), zip(params[2], params[3])\n # Initialize update actor and critic op.\n self.update_a = [tf.assign(t_a, (1 - self.tau) * t_a + self.tau * p_a) for p_a, t_a in zipped_a_params]\n self.update_c = [tf.assign(t_c, (1 - self.tau) * t_c + self.tau * p_c) for p_c, t_c in zipped_c_params]\n # Initialize actor loss and train op.\n with tf.variable_scope('actor_loss'):\n self.a_loss = -tf.reduce_mean(self.q_predict)\n with tf.variable_scope('actor_train'):\n self.a_train_op = tf.train.RMSPropOptimizer(self.learning_rate).minimize(self.a_loss, var_list=params[0])\n # Initialize critic loss and train op.\n self.q_target = self.r + self.gamma * self.q_next\n with tf.variable_scope('critic_loss'):\n self.c_loss = tf.losses.mean_squared_error(self.q_target, self.q_predict)\n with tf.variable_scope('critic_train'):\n self.c_train_op = tf.train.RMSPropOptimizer(self.learning_rate * 2).minimize(self.c_loss, var_list=params[2])\n # Initialize variables.\n self.session.run(tf.global_variables_initializer())\n\n def run(self):\n if self.mode != 'train':\n self.restore()\n else:\n for episode in range(self.episodes):\n self.log_loss(episode)\n s = self.env.reset(self.mode)\n while True:\n c, a, a_index = self.predict(s)\n s_next, r, status, info = self.env.forward(c, a)\n self.save_transition(s, a_index, r, s_next)\n self.train()\n s = s_next\n if status == self.env.Done:\n self.env.trader.log_asset(episode)\n break\n if self.enable_saver and episode % 10 == 0:\n self.save(episode)\n\n def train(self):\n if self.buffer_length < self.buffer_size:\n return\n self.session.run([self.update_a, self.update_c])\n s, a, r, s_next = self.get_transition_batch()\n self.critic_loss, _ = self.session.run([self.c_loss, self.c_train_op], {self.s: s, self.a_predict: a, self.r: r, self.s_next: s_next})\n self.actor_loss, _ = self.session.run([self.a_loss, self.a_train_op], {self.s: s})\n\n def predict(self, s):\n a = self.session.run(self.a_predict, {self.s: s})[0][0]\n return self.get_stock_code_and_action(a, use_greedy=True, use_prob=True if self.mode == 'train' else False)\n\n def save_transition(self, s, a, r, s_next):\n transition = np.hstack((s, [[a]], [[r]], s_next))\n self.buffer[self.buffer_length % self.buffer_size, :] = transition\n self.buffer_length += 1\n\n def get_transition_batch(self):\n indices = np.random.choice(self.buffer_size, size=self.batch_size)\n batch = self.buffer[indices, :]\n s = batch[:, :self.s_space]\n a = batch[:, self.s_space: self.s_space + 1]\n r = batch[:, -self.s_space - 1: -self.s_space]\n s_next = batch[:, -self.s_space:]\n return s, a, r, s_next\n\n def log_loss(self, episode):\n self.logger.warning(\"Episode: {0} | Actor Loss: {1:.2f} | Critic Loss: {2:.2f}\".format(episode,\n self.actor_loss,\n self.critic_loss))\n\n def __build_actor_nn(self, state, scope, trainable=True):\n\n w_init, b_init = tf.random_normal_initializer(.0, .001), tf.constant_initializer(.1)\n\n with tf.variable_scope(scope):\n # state is ? * code_count * data_dim.\n first_dense = tf.layers.dense(state,\n 64,\n tf.nn.relu,\n kernel_initializer=w_init,\n bias_initializer=b_init,\n trainable=trainable)\n\n action = tf.layers.dense(first_dense,\n 1,\n tf.nn.sigmoid,\n kernel_initializer=w_init,\n bias_initializer=b_init,\n trainable=trainable)\n\n return tf.multiply(action, self.a_space - 1)\n\n @staticmethod\n def __build_critic(state, action, scope, trainable=True):\n\n w_init, b_init = tf.random_normal_initializer(.0, .3), tf.constant_initializer(.1)\n\n with tf.variable_scope(scope):\n\n s_first_dense = tf.layers.dense(state,\n 32,\n tf.nn.relu,\n kernel_initializer=w_init,\n bias_initializer=b_init,\n trainable=trainable)\n\n a_first_dense = tf.layers.dense(action,\n 32,\n tf.nn.relu,\n kernel_initializer=w_init,\n bias_initializer=b_init,\n trainable=trainable)\n\n q_value = tf.layers.dense(tf.nn.relu(s_first_dense + a_first_dense),\n 1,\n kernel_initializer=w_init,\n bias_initializer=b_init,\n trainable=trainable)\n\n return q_value\n\n\ndef main(args):\n mode = args.mode\n # mode = 'test'\n codes = args.codes\n # codes = [\"AU88\", \"RB88\", \"CU88\", \"AL88\"]\n # codes = [\"T9999\"]\n market = args.market\n # market = 'future'\n episode = args.episode\n # episode = 2000\n # training_data_ratio = 0.5\n training_data_ratio = args.training_data_ratio\n\n model_name = os.path.basename(__file__).split('.')[0]\n\n env = Market(codes, start_date=\"2012-01-01\", end_date=\"2019-07-19\", **{\n \"market\": market,\n # \"use_sequence\": True,\n \"logger\": generate_market_logger(model_name),\n \"training_data_ratio\": training_data_ratio,\n })\n\n algorithm = Algorithm(tf.Session(config=config), env, env.trader.action_space, env.data_dim, **{\n \"mode\": mode,\n \"episodes\": episode,\n \"enable_saver\": True,\n \"learning_rate\": 0.003,\n \"enable_summary_writer\": True,\n \"logger\": generate_algorithm_logger(model_name),\n \"save_path\": os.path.join(CHECKPOINTS_DIR, \"RL\", model_name, market, \"model\"),\n \"summary_path\": os.path.join(CHECKPOINTS_DIR, \"RL\", model_name, market, \"summary\"),\n })\n\n algorithm.run()\n algorithm.eval()\n algorithm.plot()\n\n\nif __name__ == '__main__':\n main(model_launcher_parser.parse_args())\n\n\n"
] | [
[
"numpy.hstack",
"tensorflow.losses.mean_squared_error",
"tensorflow.multiply",
"tensorflow.nn.relu",
"tensorflow.train.RMSPropOptimizer",
"numpy.random.choice",
"tensorflow.get_collection",
"tensorflow.reduce_mean",
"tensorflow.assign",
"tensorflow.placeholder",
"tensorflow.layers.dense",
"tensorflow.constant_initializer",
"tensorflow.global_variables_initializer",
"tensorflow.Session",
"tensorflow.variable_scope",
"tensorflow.random_normal_initializer",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.4",
"1.5",
"1.7",
"0.12",
"1.0",
"1.2"
]
}
] |
fragrussu/qMRINet | [
"418cbe22cefa2974d8a97b359324ff4c35865d22"
] | [
"tools/trainpar_deepqmri.py"
] | [
"# Author: Francesco Grussu, University College London\n#\t\t <[email protected]> <[email protected]>\n#\n# Code released under BSD Two-Clause license\n#\n# Copyright (c) 2020 University College London. \n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n# \n# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n# \n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n# \n# The views and conclusions contained in the software and documentation are those\n# of the authors and should not be interpreted as representing official policies,\n# either expressed or implied, of the FreeBSD Project.\n\n### Load libraries\nimport argparse, os, sys\nfrom numpy import matlib\nimport numpy as np\nimport torch\nfrom torch import nn\nfrom torch import Tensor\nfrom torch.utils.data import DataLoader\nfrom torch import autograd\nimport pickle as pk\nfrom pathlib import Path as pt\nsys.path.insert(0, os.path.dirname(pt(__file__).absolute()) )\nimport deepqmri\n\n\nif __name__ == \"__main__\":\n\n\t\n\t### Print help and parse arguments\n\tparser = argparse.ArgumentParser(description='This program trains a qMRI-net for quantitative MRI parameter estimation. A qMRI-Nnet enables voxel-by-voxel estimation of microstructural properties from sets of MRI images aacquired by varying the MRI sequence parameters. Author: Francesco Grussu, University College London (<[email protected]><[email protected]>). Code released under BSD Two-Clause license. Copyright (c) 2020 University College London. All rights reserved.')\n\tparser.add_argument('sig_train', help='path to a pickle binary file storing the input training MRI signals as a numpy matrix (rows: voxels; columns: measurements)')\n\tparser.add_argument('param_train', help='path to a pickle binary file storing the training tissue parameter data as a numpy matrix (rows: voxels; columns: parameters)')\n\tparser.add_argument('sig_val', help='path to a pickle binary file storing the input validation MRI signals as a numpy matrix (rows: voxels; columns: measurements)')\n\tparser.add_argument('param_val', help='path to a pickle binary file storing the validation tissue parameters as a numpy matrix (rows: voxels; columns: parameters)')\n\tparser.add_argument('mri_model', help='string indicating the MRI model to fit (choose among: \"pr_hybriddwi\" for prostate hybrid diffusion-relaxometry imaging; \"br_sirsmdt\" for brain saturation recovery diffusion tensor on spherical mean signals; \"twocompdwite\" for a two-compartment diffusion-t2 relaxation model without anisotropy). Tissue parameters will be: model \"pr_hybriddwi\", parameters vl, v s.t. ve=(1-vl)*v, Dl, De, Ds, t2l, t2e, t2s, s0, where l/e/stroma stands for lumen/epithelium/stroma; model \"br_sirsmdt\", parameters dpar, kperp s.t. dperp=kperp*dpar, t1, s0; model \"twocompdwite\", parameters v, Da, t2a, Db, Kb, t2b, s0')\n\tparser.add_argument('mri_prot', help='path to text file storing the MRI protocol. For model \"pr_hybriddwi\" and \"twocompdwite\" it must contain a matrix where the 1st row stores b-values in s/mm^2, while 2nd row echo times in ms; for model \"br_sirsmdt\" it must contain a matrix where the 1st row stores preparation times (saturation-inversion delay) in ms, the 2nd row inversion times (inversion-excitation delay) in ms, the 3rd row b-values in s/mm^2. For a pure inversion recovery (i.e. no saturation pulse), use a very large number for the saturation-inversion delay (at least 5 times the maximum expected T1). Different entries should be separated by spaces')\n\tparser.add_argument('out_base', help='base name of output directory (a string built with the network parameters will be added to the base). The output directory will contain the following output files: ** losstrain.bin, pickle binary storing the training loss as a numpy matrix (shape: epoch x batch); ** lossval.bin, pickle binary storing the validation loss as a numpy matrix (shape: epoch x 1); ** nnet_epoch0.bin, pickle binary storing the qMRI-net at initialisation; ** nnet_epoch0.pth, Pytorch binary storing the qMRI-net at initialisation; ** nnet_epoch<FINAL_EPOCH>.bin, pickle binary storing the qMRI-net at the final epoch; ** nnet_lossvalmin.bin, pickle binary storing the trained qMRI-net at the best epoch (epoch with lowest validation loss, check nnet_lossvalmin.info file for more information); * nnet_lossvalmin.pth, Pytorch binary storing the trained qMRI-net at the best epoch (epoch with lowest validation loss, check nnet_lossvalmin.info file for more information); ** nnet_lossvalmin_sigval.bin, prediction of the validation signals (shape: voxels x measurements) at the best epoch (epoch with lowest validation loss, check nnet_lossvalmin.info file for more information); ** nnet_lossvalmin_tissueval.bin, prediction of tissue parameters from validation signals (shape: voxels x number_of_tissue_parameters) at the best epoch (epoch with lowest validation loss, check nnet_lossvalmin.info file for more information); ** nnet_lossvalmin.info, text file reporting information regarding the epoch with the lowest validation loss; ** lossval_min.txt, miniimum validation loss; ** nnet_lossvalmin_sigtest.bin, prediction of the test signals (shape: voxels x measurements) at the best epoch (epoch with lowest validation loss, check nnet_lossvalmin.info file for more information), if those signals are provided; ** nnet_lossvalmin_tissuetest.bin, prediction of tissue parameters from test signals (shape: voxels x number_of_tissue_parameters) at the best epoch (epoch with lowest validation loss, check nnet_lossvalmin.info file for more information) if test signals are provided')\n\tparser.add_argument('--nn', metavar='<list>', help='array storing the number of hidden neurons, separated by hyphens (example: 30-15-8). The first number (input neurons) must equal the number of measurements in the protocol (Nmeas); the last number (output neurons) must equal the number of parameters in the model (Npar, 9 for model \"pr_hybriddwi\", 4 for model \"br_sirsmdt\", 7 for model \"twocompdwite\"). Default: Nmeas-(Npar + (Nmeas minus Npar))/2-Npar, where Nmeas is the number of MRI measurements and Npar is the number of tissue parameters for the signal model to fit')\n\tparser.add_argument('--pdrop', metavar='<value>', default='0.0', help='dropout probability in each layer of the neural network. Default: 0.0')\n\tparser.add_argument('--noepoch', metavar='<value>', default='500', help='number of epochs used for training. Default: 500')\n\tparser.add_argument('--lrate', metavar='<value>', default='0.001', help='learning rate. Default: 0.001')\n\tparser.add_argument('--mbatch', metavar='<value>', help='number of voxels in each training mini-batch. Default: 1/80 of the total number of training voxels (minimum: 2 voxels)')\n\tparser.add_argument('--seed', metavar='<value>', default='19102018', help='integer used as a seed for Numpy and PyTorch random number generators. Default: 19102018')\n\tparser.add_argument('--nwork', metavar='<value>', default='0', help='number of workers for data loader. Default: 0')\n\tparser.add_argument('--dtest', metavar='<file>', help='path to an option input pickle binary file storing test MRI signals as a numpy matrix (rows: voxels; columns: measurements)')\n\tparser.add_argument('--parmin', metavar='<value>', help='list of lower bounds of tissue parameters. Entries corresponding to different parameters should be separated by a comma (for example: 0.5,0.2,250,0.5 for model br_sirsmdt). Tissue parameters are: model \"pr_hybriddwi\", parameters vl, v s.t. ve=(1-vl)*v, Dl, De, Ds, t2l, t2e, t2s, s0, where l/e/stroma stands for lumen/epithelium/stroma; model \"br_sirsmdt\", parameters dpar, kperp s.t. dperp=kperp*dpar, t1, s0; model \"twocompdwite\", parameters v, Da, t2a, Db, Kb, t2b, s0, where a and b indicate compartments a and b. If not specified, default tissue parameter ranges are used.')\n\tparser.add_argument('--parmax', metavar='<value>', help='list of upper bounds of tissue parameters. Entries corresponding to different parameters should be separated by a comma (for example: 2.4,0.9,3000,5.0 for model br_sirsmdt). Tissue parameters are: model \"pr_hybriddwi\", parameters vl, v s.t. ve=(1-vl)*v, Dl, De, Ds, t2l, t2e, t2s, s0, where l/e/stroma stands for lumen/epithelium/stroma; model \"br_sirsmdt\", parameters dpar, kperp s.t. dperp=kperp*dpar, t1, s0; model \"twocompdwite\", parameters v, Da, t2a, Db, Kb, t2b, s0, where a and b indicate compartments a and b. If not specified, default tissue parameter ranges are used.')\n\targs = parser.parse_args()\n\n\t### Get some of the inputs\n\tpdrop = float(args.pdrop)\n\tnoepoch = int(args.noepoch)\n\tlrate = float(args.lrate)\n\tseed = int(args.seed)\n\tnwork = int(args.nwork)\n\tmrimodel = args.mri_model\n\n\t### Print some information\n\tprint('')\n\tprint('')\n\tprint('********************************************************************')\n\tprint(' TRAIN A qMRI-NET (qmripar CLASS) ')\n\tprint('********************************************************************')\n\tprint('')\n\tprint('** Input training MRI signals: {}'.format(args.sig_train))\n\tprint('** Input training tissue parameters: {}'.format(args.param_train))\n\tprint('** Input validation MRI signals: {}'.format(args.sig_val))\n\tprint('** Input validation tissue parameters: {}'.format(args.param_val))\n\tif args.dtest is not None:\n\t\tprint('** Input test MRI signals: {}'.format(args.dtest))\n\n\t### Load training MRI signals\n\tfh = open(args.sig_train,'rb')\n\tdatatrain = pk.load(fh)\n\tfh.close()\n\tnvox_train = datatrain.shape[0]\n\tnmeas_train = datatrain.shape[1]\n\n\t### Load validation MRI signals\n\tfh = open(args.sig_val,'rb')\n\tdataval = pk.load(fh)\n\tfh.close()\n\tnvox_val = dataval.shape[0]\n\tif dataval.shape[1]!=datatrain.shape[1]:\n\t\traise RuntimeError('the number of MRI measurements in the validation set differs from the training set!')\t\t\n\n\t### Load test MRI signals\n\tif args.dtest is not None:\n\t\tfh = open(args.dtest,'rb')\n\t\tdatatest = np.float32(pk.load(fh))\n\t\tfh.close()\n\t\tif datatest.shape[1]!=datatrain.shape[1]:\n\t\t\traise RuntimeError('the number of MRI measurements in the test set differs from the training set!')\t\t\n\n\t### Load training tissue parameters\n\tfh = open(args.param_train,'rb')\n\tprmtrain = pk.load(fh)\n\tnpar_train = prmtrain.shape[1]\n\tfh.close()\n\tif prmtrain.shape[0]!=datatrain.shape[0]:\n\t\traise RuntimeError('the number of voxels in the training parameters differs from the training MRI signals!')\t\t\n\n\t### Load validation tissue parameters\n\tfh = open(args.param_val,'rb')\n\tprmval = pk.load(fh)\n\tfh.close()\n\tif prmval.shape[0]!=dataval.shape[0]:\n\t\traise RuntimeError('the number of voxels in the validation parameters differs from the validation MRI signals!')\n\tif prmval.shape[1]!=prmtrain.shape[1]:\n\t\traise RuntimeError('the number of validation parameters differs from the number of training parameters!')\t\t\n\n\t### Get number of mini-batches\n\tif args.mbatch is None:\n\t\tmbatch = int(float(datatrain.shape[0]) / 80.0) # Default: 1/80 of the total number of training voxels\n\telse:\n\t\tmbatch = int(args.mbatch)\n\t\tif (mbatch>datatrain.shape[0]):\n\t\t\tmbatch = datatrain.shape[0]\n\t\tif(mbatch<2):\n\t\t\tmbatch = int(2)\n\n\t### Load MRI protocol\n\ttry:\n\t\tmriprot = np.loadtxt(args.mri_prot)\n\texcept:\n\t\traise RuntimeError('the format of the MRI protocol is not understood!')\n\t\t\n\t### Check that MRI model exists\n\tif ( (mrimodel!='pr_hybriddwi') and (mrimodel!='br_sirsmdt') and (mrimodel!='twocompdwite') ):\n\t\traise RuntimeError('the chosen MRI model is not implemented. Sorry!')\n\tif (mrimodel=='pr_hybriddwi'):\n\t\ts0idx = 8\n\telif (mrimodel=='br_sirsmdt'):\n\t\ts0idx = 3\n\telif (mrimodel=='twocompdwite'):\n\t\ts0idx = 6\n\n\t### Get specifics for hidden layers\n\tif args.nn is None:\n\n\t\tif (mrimodel=='pr_hybriddwi'): \n\t\t\tnpars = 9\n\t\telif (mrimodel=='br_sirsmdt'):\n\t\t\tnpars = 4\n\t\telif (mrimodel=='twocompdwite'):\n\t\t\tnpars = 7\n\t\telse:\n\t\t\traise RuntimeError('the chosen MRI model is not implemented. Sorry!')\n\n\n\t\tnhidden = np.array([int(nmeas_train) , int(float(npars)+0.5*( float(nmeas_train) - float(npars))) , int(npars)])\n\t\tnhidden_str = '{}-{}-{}'.format( int(nmeas_train) , int(float(npars)+0.5*( float(nmeas_train) - float(npars))) , int(npars) )\n\n\telse:\n\t\tnhidden = (args.nn).split('-')\n\t\tnhidden = np.array( list(map( int,nhidden )) )\n\t\tnhidden_str = args.nn\n\n\t### Get optional user-defined bounds for tissue parameters\n\tif (args.parmin is not None) or (args.parmax is not None):\n\t\t\n\t\tif (args.parmin is not None) and (args.parmax is None):\n\t\t\traise RuntimeError('you need to set both parmin and parmax options simultaneously')\n\t\t\n\t\tif (args.parmax is not None) and (args.parmin is None):\n\t\t\traise RuntimeError('you need to set both parmin and parmax options simultaneously')\n\t\t\t\t\t\n\t\t# Lower bound\n\t\tpminbound = (args.parmin).split(',')\n\t\tpminbound = np.array( list(map( float, pminbound )) )\n\t\t\n\t\t# Upper bound\n\t\tpmaxbound = (args.parmax).split(',')\n\t\tpmaxbound = np.array( list(map( float, pmaxbound )) )\n\n\n\t### Create output base name\n\tout_base_dir = '{}_nhidden{}_pdrop{}_noepoch{}_lr{}_mbatch{}_seed{}'.format(args.out_base,nhidden_str,pdrop,noepoch,lrate,mbatch,seed)\n\tif(os.path.isdir(out_base_dir)==False):\t\n\t\tos.mkdir(out_base_dir)\n\n\t### Print some more information\n\tprint('** Output directory: {}'.format(out_base_dir))\n\tprint('')\n\tprint('')\n\tprint('PARAMETERS')\n\tprint('')\n\tprint('** Hidden neurons: {}'.format(nhidden))\n\tprint('** Dropout probability: {}'.format(pdrop))\n\tprint('** Number of epochs: {}'.format(noepoch))\n\tprint('** Learning rate: {}'.format(lrate))\n\tprint('** Number of voxels in a mini-batch: {}'.format(mbatch))\n\tprint('** Seed: {}'.format(seed))\n\tprint('** Number of workers for data loader: {}'.format(nwork))\n\n\n\t### Set random seeds\n\tnp.random.seed(seed) # Random seed for reproducibility: NumPy\n\ttorch.manual_seed(seed) # Random seed for reproducibility: PyTorch\n\n\t### Normalise MRI signals and convert to single precision\n\tmax_val_train = np.transpose( matlib.repmat(np.max(datatrain,axis=1),nmeas_train,1) )\n\tdatatrain = np.float32( datatrain / max_val_train )\n\n\tmax_val_val = np.transpose( matlib.repmat(np.max(dataval,axis=1),nmeas_train,1) )\n\tdataval = np.float32( dataval / max_val_val )\n\n\tif args.dtest is not None:\n\t\tmax_val_test = np.transpose( matlib.repmat(np.max(datatest,axis=1),nmeas_train,1) )\n\t\tdatatest = np.float32( datatest / max_val_test )\n\n\tprmtrain = np.float32(prmtrain)\n\tprmval = np.float32(prmval)\n\t\n\t### Create mini-batches on training data with data loader\n\tloadertrain = DataLoader(np.concatenate((datatrain,prmtrain),axis=1), batch_size=mbatch, shuffle=True, num_workers=nwork)\n\n\t### Allocate memory for losses\n\tnobatch=0 # Count how many mini-batches of size mbatch we created\n\tfor signals in loadertrain:\n\t\tnobatch = nobatch+1\n\tlosstrain = np.zeros((noepoch,nobatch)) + np.nan\n\tlossval = np.zeros((noepoch,1)) + np.nan\n\n\t### Instantiate the network and training objects, and save the intantiated network\n\tnnet = deepqmri.qmripar(nhidden,pdrop,mrimodel,mriprot).cpu() # Instantiate neural network\n\tif (args.parmin is not None) or (args.parmax is not None):\n\t\tnnet.changelim(pminbound,pmaxbound) # Change tissue parameter ranges\n\tprint('** Tissue parameter names: {}'.format(nnet.param_name))\t\n\tprint('** Tissue parameter lower bounds: {}'.format(nnet.param_min))\t\n\tprint('** Tissue parameter upper bounds: {}'.format(nnet.param_max))\t\n\tprint('')\n\tprint('')\n\tnnetloss = nn.MSELoss() # Loss: L2 norm (mean squared error, Gaussian noise)\n\tnnetopt = torch.optim.Adam(nnet.parameters(), lr=lrate) # Network trained with ADAM optimiser\n\ttorch.save( nnet.state_dict(), os.path.join(out_base_dir,'epoch0_net.pth') ) # Save network at epoch 0 (i.e. at initialisation)\n\tnnet_file = open(os.path.join(out_base_dir,'epoch0_net.bin'),'wb')\n\tpk.dump(nnet,nnet_file,pk.HIGHEST_PROTOCOL) \n\tnnet_file.close()\n\n\t### Create normalisation tensors for model parameters\n\tslope_norm_tr = np.ones((mbatch , npar_train))\n\toffset_norm_tr = np.ones((mbatch , npar_train))\n\n\tfor pp in range(0,npar_train):\n\t\tslope_norm_tr[:,pp] = 1.0 / (nnet.param_max[pp] - nnet.param_min[pp])\n\t\toffset_norm_tr[:,pp] = (-1.0*nnet.param_min[pp]) / (nnet.param_max[pp] - nnet.param_min[pp])\n\n\tslope_norm_tr = Tensor(np.float32(slope_norm_tr))\n\toffset_norm_tr = Tensor(np.float32(offset_norm_tr))\n\n\n\tslope_norm_val = np.ones((nvox_val , npar_train))\n\toffset_norm_val = np.ones((nvox_val , npar_train))\n\n\tfor pp in range(0,npar_train):\n\t\tslope_norm_val[:,pp] = 1.0 / (nnet.param_max[pp] - nnet.param_min[pp])\n\t\toffset_norm_val[:,pp] = (-1.0*nnet.param_min[pp]) / (nnet.param_max[pp] - nnet.param_min[pp])\n\n\tslope_norm_val = Tensor(np.float32(slope_norm_val))\n\toffset_norm_val = Tensor(np.float32(offset_norm_val))\n\n\t### Run training\n\t# Loop over epochs\n\tloss_val_prev = np.inf\n\tfor epoch in range(noepoch):\n\t \n\t\tprint(' EPOCH {}/{}'.format(epoch+1,noepoch))\n\t\tprint('')\n\n\t\t# Loop over mini-batches for at a fixed epoch\n\t\tminibatch_id = 0\n\t\tfor signals in loadertrain:\n\n\n\t\t\t# Pass the mini-batch through the network and store the training loss\n\t\t\toutput = nnet( Tensor(signals[:,0:nmeas_train]) ) # Pass MRI measurements and estimate tissue parmaters\n\t\t\ttry:\n\t\t\t\tlossmeas_train = nnetloss(Tensor(output)*slope_norm_tr + offset_norm_tr, Tensor(signals[:,nmeas_train:nmeas_train+npar_train])*slope_norm_tr + offset_norm_tr) # Training loss \n\t\t\texcept:\n\t\t\t\traise RuntimeError('The number of training voxels must be a multiple of the size of the mini-batch!')\n\n\t\t\t# Back propagation\n\t\t\tnnetopt.zero_grad() # Evaluate loss gradient with respect to network parameters at the output layer\n\t\t\tlossmeas_train.backward() # Backpropage the loss gradient through previous layers\n\t\t\tnnetopt.step() # Update network parameters\n\t\t\n\t\t\t# Store loss for the current mini-batch of training\n\t\t\tlosstrain[epoch,minibatch_id] = Tensor.numpy(lossmeas_train.data)\n\n\t\t\t# Update mini-batch counter\n\t\t\tminibatch_id = minibatch_id + 1\n\t\t\n\t\t\n\t\t# Run validation\n\t\tnnet.eval() # Set network to evaluation mode (deactivates dropout)\n\t\ttissueval_nnet = nnet( Tensor(dataval) ) # Output of full network (predicted tissue parameters)\n\t\tdataval_nnet = nnet.getsignals( Tensor(tissueval_nnet) ) # Estimate MRI signals\n\t\tdataval_nnet = dataval_nnet.detach().numpy()\n\t\tmax_val_val_out = np.transpose( matlib.repmat(np.max(dataval_nnet,axis=1),nmeas_train,1) )\n\t\tlossmeas_val = nnetloss( Tensor(tissueval_nnet)*slope_norm_val + offset_norm_val , Tensor(prmval)*slope_norm_val + offset_norm_val ) # Validation loss\n\t\t# Store validation loss\n\t\tlossval[epoch,0] = Tensor.numpy(lossmeas_val.data)\n\n\t\t# Save trained network at current epoch if validation loss has decreased\n\t\tif(Tensor.numpy(lossmeas_val.data)<=loss_val_prev):\n\t\t\tprint(' ... validation loss has decreased. Saving net...')\n\t\t\t# Save network\n\t\t\ttorch.save( nnet.state_dict(), os.path.join(out_base_dir,'lossvalmin_net.pth') )\n\t\t\tnnet_file = open(os.path.join(out_base_dir,'lossvalmin_net.bin'),'wb')\n\t\t\tpk.dump(nnet,nnet_file,pk.HIGHEST_PROTOCOL) \n\t\t\tnnet_file.close()\n\t\t\t# Save information on the epoch\n\t\t\tnnet_text = open(os.path.join(out_base_dir,'lossvalmin.info'),'w')\n\t\t\tnnet_text.write('Epoch {} (indices starting from 0)'.format(epoch));\n\t\t\tnnet_text.close();\n\t\t\t# Update value of best validation loss so far\n\t\t\tloss_val_prev = Tensor.numpy(lossmeas_val.data)\n\t\t\t# Save predicted validation tissue parameters \n\t\t\ttissueval_nnet = tissueval_nnet.detach().numpy()\n\t\t\ttissueval_nnet[:,s0idx] = (max_val_val[:,0]/max_val_val_out[:,0])*tissueval_nnet[:,s0idx] # Rescale s0 (any column of would work)\n\t\t\ttissueval_nnet_file = open(os.path.join(out_base_dir,'lossvalmin_tissueval.bin'),'wb')\n\t\t\tpk.dump(tissueval_nnet,tissueval_nnet_file,pk.HIGHEST_PROTOCOL) \n\t\t\ttissueval_nnet_file.close()\n\t\t\t# Save predicted validation signals\n\t\t\tdataval_nnet = (max_val_val/max_val_val_out)*dataval_nnet\t\t\t\t\n\t\t\tdataval_nnet_file = open(os.path.join(out_base_dir,'lossvalmin_sigval.bin'),'wb')\n\t\t\tpk.dump(dataval_nnet,dataval_nnet_file,pk.HIGHEST_PROTOCOL) \n\t\t\tdataval_nnet_file.close()\n\n\t\t\t# Analyse test data if provided\n\t\t\tif args.dtest is not None:\n\t\t\t\t# Get neuronal activations as well as predicted test tissue parameters and test MRI signals \n\t\t\t\ttissuetest_nnet = nnet( Tensor(datatest) ) # Output of network (estimated tissue parameters)\n\t\t\t\tdatatest_nnet = nnet.getsignals( Tensor(tissuetest_nnet) ) # Predicted MRI signals\n\t\t\t\tdatatest_nnet = datatest_nnet.detach().numpy()\n\t\t\t\tmax_val_test_out = np.transpose( matlib.repmat(np.max(datatest_nnet,axis=1),nmeas_train,1) )\n\t\t\t\t# Save predicted test tissue parameters \n\t\t\t\ttissuetest_nnet = tissuetest_nnet.detach().numpy()\n\t\t\t\ttissuetest_nnet[:,s0idx] = (max_val_test[:,0]/max_val_test_out[:,0])*tissuetest_nnet[:,s0idx] # Rescale s0 (any column of max_val_test works)\n\t\t\t\ttissuetest_nnet_file = open(os.path.join(out_base_dir,'lossvalmin_tissuetest.bin'),'wb')\n\t\t\t\tpk.dump(tissuetest_nnet,tissuetest_nnet_file,pk.HIGHEST_PROTOCOL) \n\t\t\t\ttissuetest_nnet_file.close()\n\t\t\t\t# Save predicted test signals\n\t\t\t\tdatatest_nnet = (max_val_test/max_val_test_out)*datatest_nnet # Rescale signal\t\n\t\t\t\tdatatest_nnet_file = open(os.path.join(out_base_dir,'lossvalmin_sigtest.bin'),'wb')\n\t\t\t\tpk.dump(datatest_nnet,datatest_nnet_file,pk.HIGHEST_PROTOCOL) \n\t\t\t\tdatatest_nnet_file.close()\n\n\n\t\t# Set network back to training mode\n\t\tnnet.train()\n\n\t\t# Print some information\n\t\tprint('')\n\t\tprint(' TRAINING INFO:')\n\t\tprint(' Trainig loss: {:.12f}; validation loss: {:.12f}'.format(Tensor.numpy(lossmeas_train.data), Tensor.numpy(lossmeas_val.data)) )\n\t\tprint('')\n\n\t# Save the final network\n\tnnet.eval()\n\ttorch.save( nnet.state_dict(), os.path.join(out_base_dir,'epoch{}_net.pth'.format(noepoch)) )\n\tnnet_file = open(os.path.join(out_base_dir,'epoch{}_net.bin'.format(noepoch)),'wb')\n\tpk.dump(nnet,nnet_file,pk.HIGHEST_PROTOCOL) \n\tnnet_file.close()\n\n\t# Save the training and validation loss\n\tlosstrain_file = open(os.path.join(out_base_dir,'losstrain.bin'),'wb')\n\tpk.dump(losstrain,losstrain_file,pk.HIGHEST_PROTOCOL) \n\tlosstrain_file.close()\n\n\tlossval_file = open(os.path.join(out_base_dir,'lossval.bin'),'wb')\n\tpk.dump(lossval,lossval_file,pk.HIGHEST_PROTOCOL) \n\tlossval_file.close()\n\tnp.savetxt(os.path.join(out_base_dir,'lossval_min.txt'), [np.nanmin(lossval)], fmt='%.12f', delimiter=' ')\n\n\n"
] | [
[
"numpy.random.seed",
"torch.Tensor",
"torch.manual_seed",
"numpy.nanmin",
"torch.Tensor.numpy",
"numpy.ones",
"numpy.concatenate",
"numpy.max",
"numpy.float32",
"numpy.zeros",
"torch.nn.MSELoss",
"numpy.loadtxt"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Morisset/Mexico-datos | [
"29d5ed1079732d5d809bc14eb5d3438662508728"
] | [
"codigo/process_datos_abiertos.py"
] | [
"import os\nimport csv\nimport pandas as pd\nimport geopandas as gpd\nfrom datetime import datetime, timedelta\n\n\n## PROCESSING FUNCTIONS ##\n\ndef confirmados_diarios_por_estado(datos, entidades):\n \"\"\"\n Calcula el número total de casos confirmados por fecha y por estado.\n\n Input:\n - datos: datos abiertos de COVID-19 en México disponibles en [1].\n\n Output:\n - serie: Serie de tiempo de nuevos casos confirmados por dia para cada\n entidad federativa en México.\n\n [1]: https://www.gob.mx/salud/documentos/datos-abiertos-152127\n \"\"\"\n series = (datos[datos['RESULTADO'] == 1]\n .groupby(['ENTIDAD_UM', 'FECHA_INGRESO'])\n .count()['ORIGEN'])\n return get_formato_series(series, entidades)\n\n\ndef negativos_diarios_por_estado(datos, entidades):\n \"\"\"\n Calcula el número total de casos negativos por fecha y por estado.\n\n Input:\n - datos: datos abiertos de COVID-19 en México disponibles en [1].\n\n Output:\n - series: Serie de tiempo de nuevas pruebas negativas por dia para cada\n entidad federativa en México.\n\n [1]: https://www.gob.mx/salud/documentos/datos-abiertos-152127\n\n \"\"\"\n series = (datos[datos['RESULTADO'] == 2]\n .groupby(['ENTIDAD_UM', 'FECHA_INGRESO'])\n .count()['ORIGEN'])\n return get_formato_series(series, entidades)\n\n\ndef pruebas_pendientes_diarias_por_estado(datos, entidades):\n \"\"\"\n Calcula el número de pruebas pendientes por fecha y por estado.\n\n Input:\n - datos: datos abiertos de COVID-19 en México disponibles en [1].\n\n Output:\n - series: Serie de tiempo de nuevas pruebas pendientes por dia para cada\n entidad federativa en México.\n\n [1]: https://www.gob.mx/salud/documentos/datos-abiertos-152127\n\n \"\"\"\n series = (datos[datos['RESULTADO'] == 3]\n .groupby(['ENTIDAD_UM', 'FECHA_INGRESO'])\n .count()['ORIGEN'])\n return get_formato_series(series, entidades)\n\n\ndef pruebas_totales_diarias_por_estado(datos, entidades):\n \"\"\"\n Calcula el número total de pruebas realizadas por fecha y por estado.\n\n Input:\n - datos: datos abiertos de COVID-19 en México disponibles en [1].\n\n Output:\n - series: Serie de tiempo de nuevas pruebas totales por dia para cada\n entidad federativa en México.\n\n [1]: https://www.gob.mx/salud/documentos/datos-abiertos-152127\n\n \"\"\"\n series = (datos\n .groupby(['ENTIDAD_UM', 'FECHA_INGRESO'])\n .count()['ORIGEN'])\n return get_formato_series(series, entidades)\n\n\ndef defunciones_diarias_por_estado(datos, entidades):\n \"\"\"\n Calcula el número de defunciones por fecha y por estado.\n\n Input:\n - datos: datos abiertos de COVID-19 en México disponibles en [1].\n\n Output:\n - series: Serie de tiempo de nuevas muertes por dia para cada entidad\n federativa en México.\n\n [1]: https://www.gob.mx/salud/documentos/datos-abiertos-152127\n\n \"\"\"\n idx = (datos['RESULTADO'] == 1) & (datos['FECHA_DEF'] != '9999-99-99')\n series = (datos[idx]\n .groupby(['ENTIDAD_UM', 'FECHA_DEF'])\n .count()['ORIGEN'])\n return get_formato_series(series, entidades)\n\n\ndef hospitalizados_diarios_por_estado(datos, entidades):\n \"\"\"\n Calcula el número de pacientes hopitalizados por fecha y por estado.\n\n Input:\n - datos: datos abiertos de COVID-19 en México disponibles en [1].\n\n Output:\n - series: Serie de tiempo de nuevos hospitalizados por dia para cada entidad\n federativa en México.\n\n [1]: https://www.gob.mx/salud/documentos/datos-abiertos-152127\n\n \"\"\"\n # esta serie incluye UCI + noUCI\n idx = (datos['RESULTADO'] == 1) & (datos['TIPO_PACIENTE'] == 2)\n series = (datos[idx]\n .groupby(['ENTIDAD_UM', 'FECHA_INGRESO'])\n .count()['ORIGEN'])\n return get_formato_series(series, entidades)\n\n\ndef ambulatorios_diarios_por_estado(datos, entidades):\n \"\"\"\n Calcula el número de pacientes ambulatorios por fecha y por estado.\n\n Input:\n - datos: datos abiertos de COVID-19 en México disponibles en [1].\n\n Output:\n - series: Serie de tiempo de nuevos pacientes infectados ambulatorios por\n dia para cada entidad federativa en México.\n\n [1]: https://www.gob.mx/salud/documentos/datos-abiertos-152127\n\n \"\"\"\n idx = (datos['RESULTADO'] == 1) & (datos['TIPO_PACIENTE'] == 1)\n series = (datos[idx]\n .groupby(['ENTIDAD_UM', 'FECHA_INGRESO'])\n .count()['ORIGEN'])\n return get_formato_series(series, entidades)\n\n\ndef uci_diarios_por_estado(datos, entidades):\n \"\"\"\n Calcula el número de pacientes ingresados a una UCI por fecha y por estado.\n\n Input:\n - datos: datos abiertos de COVID-19 en México disponibles en [1].\n\n Output:\n - series: Serie de tiempo de nuevos pacientes en UCI por dia para cada\n entidad federativa en México.\n\n [1]: https://www.gob.mx/salud/documentos/datos-abiertos-152127\n\n \"\"\"\n idx = (datos['RESULTADO'] == 1) & (datos['UCI'] == 1)\n series = (datos[idx]\n .groupby(['ENTIDAD_UM', 'FECHA_INGRESO'])\n .count()['ORIGEN'])\n return get_formato_series(series, entidades)\n\n\n## HELPER FUNCTIONS ##\n\ndef get_formato_series(series, entidades):\n \"\"\"\n Convierte groupby a formato tidy (columnas son estados e indice es la fecha).\n\n Input:\n - series:\n DataFrame en formato groupby agrupada for una columna que corresponde a\n entidades federativas y otra columna que corresponde a una fecha.\n - entidades:\n diccionario de clave_de_entidad => nombre_de_entidad.\n\n Output:\n - series:\n DataFrame en formato tidy, con los nombres de los estados como columnas\n (la primer columna es el total nacional) y con la fecha como indice.\n\n \"\"\"\n diccionario_cambio_edos = {'Ciudad De México': 'Ciudad de México',\n 'Coahuila De Zaragoza': 'Coahuila',\n 'Michoacán De Ocampo': 'Michoacán',\n 'Veracruz De Ignacio De La Llave': 'Veracruz'}\n\n series = series.unstack(level=0).fillna(0).astype('int')\n\n # Formato para mexicovid19/Mexico-datos\n series.index.name = 'Fecha'\n series.index = pd.to_datetime(series.index)\n # Formato oficial de DGE\n series = series.rename(columns=entidades)\n # Formato específico de nuestro repositorio\n series = series.rename(columns=diccionario_cambio_edos)\n series = series.reindex(sorted(series.columns), axis=1)\n # Formato de agregado nacional\n series.loc[:, 'Nacional'] = series.sum(axis=1)\n # Reordenar columnas para que los casos nacionales queden primero\n cols = list(series.columns)\n cols = cols[-1:] + cols[:-1]\n series = series[cols]\n\n # Llenamos ceros para fechas sin informacion\n idx = pd.date_range(series.index.min(), series.index.max())\n series = series.reindex(idx, fill_value=0)\n series.index.name = 'Fecha'\n\n return series\n\n\nif __name__ == '__main__':\n\n update_time = datetime.now() - timedelta(hours=6)\n date = datetime.now() - timedelta(days=1)\n date_filename = date.strftime('%Y%m%d')\n date_iso = date.strftime('%Y-%m-%d')\n\n repo = '..'\n dir_datos_abiertos = os.path.join(repo, 'datos_abiertos', '')\n dir_datos = os.path.join(repo, 'datos', '')\n dir_geo = os.path.join(dir_datos, 'geograficos', '')\n dir_demograficos = os.path.join(dir_datos, 'demograficos_variables', '')\n\n dir_series_dge = os.path.join(dir_datos_abiertos, 'series_de_tiempo', '')\n dir_series = os.path.join(dir_datos, 'series_de_tiempo', '')\n\n dir_input = os.path.join(dir_datos_abiertos, 'raw', '')\n input_filename = dir_input + f'datos_abiertos_{date_filename}.zip'\n\n ## READING ##\n\n # Lee los datos abiertos\n datos_abiertos_df = pd.read_csv(input_filename, compression='zip')\n\n # Lee catalogo de entidades (hoja de calculo 'Catálogo de ENTIDADES' en\n # el archivo 'diccionario_datos/Catalogos_0412.xlsx''; ha sido convertido a csv)\n cat = (pd.read_csv(dir_input + 'diccionario_datos/catalogo_entidades.csv')\n .set_index('CLAVE_ENTIDAD')['ENTIDAD_FEDERATIVA']\n .to_dict())\n # cambia mayúsculas de estados por formato título\n entidades = {key: val.title() for (key, val) in cat.items()}\n\n # Datos abiertos\n files = ['covid19_mex_confirmados.csv',\n 'covid19_mex_negativos.csv',\n 'covid19_mex_pendientes.csv',\n 'covid19_mex_pruebas-totales.csv',\n 'covid19_mex_muertes.csv',\n 'covid19_mex_hospitalizados.csv',\n 'covid19_mex_uci.csv',\n 'covid19_mex_ambulatorios.csv']\n\n funciones = [confirmados_diarios_por_estado,\n negativos_diarios_por_estado,\n pruebas_pendientes_diarias_por_estado,\n pruebas_totales_diarias_por_estado,\n defunciones_diarias_por_estado,\n hospitalizados_diarios_por_estado,\n uci_diarios_por_estado,\n ambulatorios_diarios_por_estado]\n\n dfs = [func(datos_abiertos_df, entidades) for func in funciones]\n\n for f, df in zip(files, dfs):\n df.to_csv(f'{dir_series_dge}/nuevos/{f}')\n df.cumsum().to_csv(f'{dir_series_dge}/acumulados/{f}')\n\n ## Series de tiempo estaticas (solo actualiza ultima fila) ##\n\n # Formato unix sin quotes\n csv.register_dialect('unixnq', delimiter=',', lineterminator='\\n',\n quoting=csv.QUOTE_NONE)\n\n # Totales por estado\n totales_file = dir_series + 'covid19_mex_casos_totales.csv'\n fila_totales = dfs[0].cumsum().tail(1) # confirmados_diarios_por_estado\n with open(totales_file, 'a') as f:\n writer = csv.writer(f, 'unixnq')\n writer.writerow([date_iso] + fila_totales.values[0].tolist())\n\n # Casos ultimas 24h\n nuevos_file = dir_series + 'covid19_mex_casos_nuevos.csv'\n totales_df = pd.read_csv(totales_file)\n fila_nuevos = (totales_df.iloc[-1, 1:] - totales_df.iloc[-2, 1:]).astype(int)\n with open(nuevos_file, 'a') as f:\n writer = csv.writer(f, 'unixnq')\n writer.writerow([date_iso] + fila_nuevos.values.tolist()) # a series\n\n # Muertes por estado\n muertes_file = dir_series + 'covid19_mex_muertes.csv'\n fila_muertes = dfs[4].cumsum().tail(1) # defunciones_diarias_por_estado\n with open(muertes_file, 'a') as f:\n writer = csv.writer(f, 'unixnq')\n writer.writerow([date_iso] + fila_muertes.values[0].tolist())\n\n # Muertes nuevas por estado\n muertes_nuevas_file = dir_series + 'covid19_mex_muertes_nuevas.csv'\n muertes_df = pd.read_csv(muertes_file)\n fila_nuevas = (muertes_df.iloc[-1, 1:] - muertes_df.iloc[-2, 1:]).astype(int)\n with open(muertes_nuevas_file, 'a') as f:\n writer = csv.writer(f, 'unixnq')\n writer.writerow([date_iso] + fila_nuevas.values.tolist()) # a series\n\n # Sospechosos por estado\n sospechosos_file = dir_series + 'covid19_mex_sospechosos.csv'\n # pruebas_pendientes_diarias_por_estado\n fila_sospechosos = dfs[2].cumsum().tail(1)\n with open(sospechosos_file, 'a') as f:\n writer = csv.writer(f, 'unixnq')\n writer.writerow([date_iso] + fila_sospechosos.values[0].tolist())\n\n # Sospechosos por estado\n negativos_file = dir_series + 'covid19_mex_negativos.csv'\n fila_negativos = dfs[1].cumsum().tail(1) # negativos_diarios_por_estado\n with open(negativos_file, 'a') as f:\n writer = csv.writer(f, 'unixnq')\n writer.writerow([date_iso] + fila_negativos.values[0].tolist())\n\n ## Totales por estado en el archivo geojson ##\n geojson_file = dir_geo + 'mexico.geojson'\n edos_hoy_file = dir_datos + 'estados_hoy.csv'\n updated_file = dir_datos + 'last_updated.csv'\n\n gdf = gpd.read_file(geojson_file).set_index('name')\n gdf.totales = fila_totales.drop('Nacional', axis=1).squeeze()\n gdf.nuevos = fila_nuevos.drop('Nacional').squeeze() # series\n gdf.muertes = fila_muertes.drop('Nacional', axis=1).squeeze()\n gdf.muertes_nuevas = fila_nuevas.drop('Nacional').squeeze() # series\n gdf.sospechosos = fila_sospechosos.drop('Nacional', axis=1).squeeze()\n gdf.negativos = fila_negativos.drop('Nacional', axis=1).squeeze()\n gdf.totales_100k = gdf.totales * 100000 / gdf.population\n gdf.muertes_100k = gdf.muertes * 100000 / gdf.population\n\n gdf.updated_at = str(update_time).replace(' ', 'T')\n\n gdf = gdf.reset_index()\n assert gdf.shape[1] == 14\n\n gdf.to_file(geojson_file, driver='GeoJSON')\n gdf.loc[0:0, ['updated_at']].to_csv(updated_file, index=False)\n\n ### Estados hoy ###\n cols_edos_hoy = ['name', 'totales', 'nuevos',\n 'muertes', 'muertes_nuevas', 'sospechosos', 'negativos']\n\n map_cols = {'name': 'Estado',\n 'totales': 'Confirmados totales',\n 'nuevos': 'Confirmados nuevos',\n 'muertes': 'Defunciones',\n 'muertes_nuevas': 'Defunciones nuevas',\n 'sospechosos': 'Sospechosos totales',\n 'negativos': 'Negativos totales'}\n\n edos_hoy_df = gdf[cols_edos_hoy].rename(columns=map_cols)\n edos_hoy_df.to_csv(edos_hoy_file, index=False)\n\n print(f'Se procesaron exitosamente los datos abiertos de {input_filename}')\n"
] | [
[
"pandas.to_datetime",
"pandas.read_csv"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
mariolpantunes/ml-deti | [
"a47fdb5df70e3f6fda5768be14f97462dfe057fb"
] | [
"code/Ex02.py"
] | [
"import matplotlib.pyplot as plt\nimport arff\nimport numpy as np\nfrom sklearn import linear_model\n\n# Load dataset\ndataset = arff.load(open('dataset/dataset01.arff', 'r'))\ndata = np.array(dataset['data'])\n\n# Reshape vector\nX1 = data[:, 0].reshape(-1, 1)\nX2 = np.multiply(X1, X1)\nX = np.concatenate((X1, X2), axis=1)\nY = data[:, 1].reshape(-1, 1)\n\n# Plot points\nplt.scatter(X1, Y, color='black')\nplt.xticks(())\nplt.yticks(())\nplt.show()\n\n# Create linear regression object\nmodel = linear_model.LinearRegression()\n\n# Train the model using X and Y\nmodel.fit(X, Y)\n\n# The coefficients\nprint(\"Y = %.2fX^2 + %.2fX + %.2f\" % (model.coef_[0][0], model.coef_[0][1], model.intercept_))\n\n# The mean square error\nprint(\"Residual sum of squares: %.2f\" % np.mean((model.predict(X) - Y) ** 2))\n\n# Explained variance score: 1 is perfect prediction\nprint('Variance score: %.2f' % model.score(X, Y))\n\n# Plot outputs\nplt.scatter(X1, Y, color='black')\nplt.plot(X1, model.predict(X), color='blue', linewidth=3)\nplt.xticks(())\nplt.yticks(())\n\nplt.show()\n"
] | [
[
"matplotlib.pyplot.yticks",
"matplotlib.pyplot.scatter",
"numpy.multiply",
"numpy.concatenate",
"sklearn.linear_model.LinearRegression",
"matplotlib.pyplot.xticks",
"numpy.array",
"matplotlib.pyplot.show"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
JacobEkedahl/detect-intros-from-video | [
"9b2bac1c7209558711072f967a3359d2ca698cd4"
] | [
"src/stats/intro_stats.py"
] | [
"import matplotlib.pyplot as plt\n\nimport utils.extractor as extractor\nimport utils.file_handler as file_handler\nimport utils.time_handler as time_handler\n\n\ndef plot_intros():\n intros = extractor.get_intros_from_data()\n only_valid_intros = [x for x in intros if not x[\"end\"] == \"00:00:00\"]\n x_data = map(get_start_time_seconds, only_valid_intros) \n y_data = map(get_size_from_intro, only_valid_intros) \n # naming the x axis\n plt.xlabel('Start time of intro (Seconds)') \n # naming the y axis \n plt.ylabel('Length of intro (Seconds)')\n plt.grid(True)\n plt.scatter(list(x_data), list(y_data)) \n plt.show()\n\ndef plot_hist_sizes():\n intros = extractor.get_intros_from_data()\n only_valid_intros = [x for x in intros if not x[\"end\"] == \"00:00:00\"]\n x_data = list(map(get_size_from_intro, only_valid_intros))\n plt.xlabel('Length of intro (Seconds)') \n plt.ylabel('Frequency')\n plt.grid(True)\n plt.hist(x_data, bins=40)\n plt.show()\n\ndef plot_hist_frequency():\n intros = extractor.get_intros_from_data()\n only_valid_intros = [x for x in intros if not x[\"end\"] == \"00:00:00\"]\n x_data = list(map(get_start_time_seconds, only_valid_intros))\n plt.xlabel('Start time of intro (Seconds)') \n plt.ylabel('Frequency')\n plt.grid(True)\n plt.hist(x_data, bins=60)\n plt.show()\n\ndef plot_all_intros():\n x_titles = ['Start time of intro (Seconds)', 'Length of intro (Seconds)']\n y_title = 'Frequency'\n titles = ['Start times of intros','Lengths of intros']\n colors = ['blue', 'blue']\n bins = [60, 40]\n intros = extractor.get_intros_from_data()\n only_valid_intros = [x for x in intros if not x[\"end\"] == \"00:00:00\"]\n x_size = list(map(get_size_from_intro, only_valid_intros))\n x_start = list(map(get_start_time_seconds, only_valid_intros))\n x_data = [x_start, x_size]\n fig, axs = plt.subplots(1, 2)\n axs = axs.ravel()\n\n for idx, ax in enumerate(axs):\n ax.hist(x_data[idx], bins=bins[idx], fc=colors[idx])\n # ax.set_title(titles[idx])\n ax.set_xlabel(x_titles[idx])\n ax.set_ylabel(y_title)\n ax.grid()\n plt.tight_layout()\n plt.show()\n\n\ndef get_size_from_intro(intro):\n start = time_handler.timestamp(intro[\"start\"]) / 1000\n end = time_handler.timestamp(intro[\"end\"]) / 1000\n return abs(start - end)\n\ndef get_start_time_seconds(intro):\n return time_handler.timestamp(intro[\"start\"]) / 1000\n"
] | [
[
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"matplotlib.pyplot.hist",
"matplotlib.pyplot.ylabel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
idanmoradarthas/DataScienceUtils | [
"be4806ebcb9ab0e2cdd189842227bd242f0c8910"
] | [
"tests/test_strings.py"
] | [
"import pandas\n\nfrom ds_utils.strings import append_tags_to_frame, extract_significant_terms_from_subset\n\n\ndef test_append_tags_to_frame():\n x_train = pandas.DataFrame([{\"article_name\": \"1\", \"article_tags\": \"ds,ml,dl\"},\n {\"article_name\": \"2\", \"article_tags\": \"ds,ml\"}])\n x_test = pandas.DataFrame([{\"article_name\": \"3\", \"article_tags\": \"ds,ml,py\"}])\n\n x_train_expected = pandas.DataFrame([{\"article_name\": \"1\", \"tag_ds\": 1, \"tag_ml\": 1, \"tag_dl\": 1},\n {\"article_name\": \"2\", \"tag_ds\": 1, \"tag_ml\": 1, \"tag_dl\": 0}],\n columns=[\"article_name\", \"tag_dl\", \"tag_ds\", \"tag_ml\"])\n x_test_expected = pandas.DataFrame([{\"article_name\": \"3\", \"tag_ds\": 1, \"tag_ml\": 1, \"tag_dl\": 0}],\n columns=[\"article_name\", \"tag_dl\", \"tag_ds\", \"tag_ml\"])\n\n x_train_with_tags, x_test_with_tags = append_tags_to_frame(x_train, x_test, \"article_tags\", \"tag_\")\n pandas.testing.assert_frame_equal(x_train_expected, x_train_with_tags, check_like=True)\n pandas.testing.assert_frame_equal(x_test_expected, x_test_with_tags, check_like=True)\n\n\ndef test_significant_terms():\n corpus = ['This is the first document.', 'This document is the second document.', 'And this is the third one.',\n 'Is this the first document?']\n data_frame = pandas.DataFrame(corpus, columns=[\"content\"])\n subset_data_frame = data_frame[data_frame.index > 1]\n terms = extract_significant_terms_from_subset(data_frame, subset_data_frame, \"content\")\n\n expected = pandas.Series(\n [1.0, 1.0, 1.0, 0.6666666666666666, 0.6666666666666666, 0.6666666666666666, 0.5, 0.25, 0.0],\n index=['third', 'one', 'and', 'this', 'the', 'is', 'first', 'document', 'second'])\n\n pandas.testing.assert_series_equal(expected, terms)\n"
] | [
[
"pandas.testing.assert_series_equal",
"pandas.testing.assert_frame_equal",
"pandas.Series",
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
slomrafgrav/models | [
"91a59c78e8c48e8a1b2fec37143e52dae3f066c1",
"e498d28503fd4a12d1fa9ade41891f2f9601c674",
"e498d28503fd4a12d1fa9ade41891f2f9601c674",
"e498d28503fd4a12d1fa9ade41891f2f9601c674",
"e498d28503fd4a12d1fa9ade41891f2f9601c674",
"e498d28503fd4a12d1fa9ade41891f2f9601c674",
"91a59c78e8c48e8a1b2fec37143e52dae3f066c1"
] | [
"research/object_detection/eval_util.py",
"research/object_detection/builders/image_resizer_builder_test.py",
"research/object_detection/models/ssd_inception_v2_feature_extractor.py",
"research/object_detection/core/region_similarity_calculator.py",
"official/mnist/mnist_eager.py",
"official/utils/misc/model_helpers_test.py",
"research/object_detection/builders/box_predictor_builder_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\"\"\"Common utility functions for evaluation.\"\"\"\nimport collections\nimport os\nimport time\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom object_detection.core import box_list\nfrom object_detection.core import box_list_ops\nfrom object_detection.core import keypoint_ops\nfrom object_detection.core import standard_fields as fields\nfrom object_detection.metrics import coco_evaluation\nfrom object_detection.utils import label_map_util\nfrom object_detection.utils import object_detection_evaluation\nfrom object_detection.utils import ops\nfrom object_detection.utils import shape_utils\nfrom object_detection.utils import visualization_utils as vis_utils\n\nslim = tf.contrib.slim\n\n# A dictionary of metric names to classes that implement the metric. The classes\n# in the dictionary must implement\n# utils.object_detection_evaluation.DetectionEvaluator interface.\nEVAL_METRICS_CLASS_DICT = {\n 'coco_detection_metrics':\n coco_evaluation.CocoDetectionEvaluator,\n 'coco_mask_metrics':\n coco_evaluation.CocoMaskEvaluator,\n 'oid_challenge_detection_metrics':\n object_detection_evaluation.OpenImagesDetectionChallengeEvaluator,\n 'pascal_voc_detection_metrics':\n object_detection_evaluation.PascalDetectionEvaluator,\n 'weighted_pascal_voc_detection_metrics':\n object_detection_evaluation.WeightedPascalDetectionEvaluator,\n 'pascal_voc_instance_segmentation_metrics':\n object_detection_evaluation.PascalInstanceSegmentationEvaluator,\n 'weighted_pascal_voc_instance_segmentation_metrics':\n object_detection_evaluation.WeightedPascalInstanceSegmentationEvaluator,\n 'oid_V2_detection_metrics':\n object_detection_evaluation.OpenImagesDetectionEvaluator,\n}\n\nEVAL_DEFAULT_METRIC = 'coco_detection_metrics'\n\n\ndef write_metrics(metrics, global_step, summary_dir):\n \"\"\"Write metrics to a summary directory.\n\n Args:\n metrics: A dictionary containing metric names and values.\n global_step: Global step at which the metrics are computed.\n summary_dir: Directory to write tensorflow summaries to.\n \"\"\"\n tf.logging.info('Writing metrics to tf summary.')\n summary_writer = tf.summary.FileWriterCache.get(summary_dir)\n for key in sorted(metrics):\n summary = tf.Summary(value=[\n tf.Summary.Value(tag=key, simple_value=metrics[key]),\n ])\n summary_writer.add_summary(summary, global_step)\n tf.logging.info('%s: %f', key, metrics[key])\n tf.logging.info('Metrics written to tf summary.')\n\n\n# TODO(rathodv): Add tests.\ndef visualize_detection_results(result_dict,\n tag,\n global_step,\n categories,\n summary_dir='',\n export_dir='',\n agnostic_mode=False,\n show_groundtruth=False,\n groundtruth_box_visualization_color='black',\n min_score_thresh=.5,\n max_num_predictions=20,\n skip_scores=False,\n skip_labels=False,\n keep_image_id_for_visualization_export=False):\n \"\"\"Visualizes detection results and writes visualizations to image summaries.\n\n This function visualizes an image with its detected bounding boxes and writes\n to image summaries which can be viewed on tensorboard. It optionally also\n writes images to a directory. In the case of missing entry in the label map,\n unknown class name in the visualization is shown as \"N/A\".\n\n Args:\n result_dict: a dictionary holding groundtruth and detection\n data corresponding to each image being evaluated. The following keys\n are required:\n 'original_image': a numpy array representing the image with shape\n [1, height, width, 3] or [1, height, width, 1]\n 'detection_boxes': a numpy array of shape [N, 4]\n 'detection_scores': a numpy array of shape [N]\n 'detection_classes': a numpy array of shape [N]\n The following keys are optional:\n 'groundtruth_boxes': a numpy array of shape [N, 4]\n 'groundtruth_keypoints': a numpy array of shape [N, num_keypoints, 2]\n Detections are assumed to be provided in decreasing order of score and for\n display, and we assume that scores are probabilities between 0 and 1.\n tag: tensorboard tag (string) to associate with image.\n global_step: global step at which the visualization are generated.\n categories: a list of dictionaries representing all possible categories.\n Each dict in this list has the following keys:\n 'id': (required) an integer id uniquely identifying this category\n 'name': (required) string representing category name\n e.g., 'cat', 'dog', 'pizza'\n 'supercategory': (optional) string representing the supercategory\n e.g., 'animal', 'vehicle', 'food', etc\n summary_dir: the output directory to which the image summaries are written.\n export_dir: the output directory to which images are written. If this is\n empty (default), then images are not exported.\n agnostic_mode: boolean (default: False) controlling whether to evaluate in\n class-agnostic mode or not.\n show_groundtruth: boolean (default: False) controlling whether to show\n groundtruth boxes in addition to detected boxes\n groundtruth_box_visualization_color: box color for visualizing groundtruth\n boxes\n min_score_thresh: minimum score threshold for a box to be visualized\n max_num_predictions: maximum number of detections to visualize\n skip_scores: whether to skip score when drawing a single detection\n skip_labels: whether to skip label when drawing a single detection\n keep_image_id_for_visualization_export: whether to keep image identifier in\n filename when exported to export_dir\n Raises:\n ValueError: if result_dict does not contain the expected keys (i.e.,\n 'original_image', 'detection_boxes', 'detection_scores',\n 'detection_classes')\n \"\"\"\n detection_fields = fields.DetectionResultFields\n input_fields = fields.InputDataFields\n if not set([\n input_fields.original_image,\n detection_fields.detection_boxes,\n detection_fields.detection_scores,\n detection_fields.detection_classes,\n ]).issubset(set(result_dict.keys())):\n raise ValueError('result_dict does not contain all expected keys.')\n if show_groundtruth and input_fields.groundtruth_boxes not in result_dict:\n raise ValueError('If show_groundtruth is enabled, result_dict must contain '\n 'groundtruth_boxes.')\n tf.logging.info('Creating detection visualizations.')\n category_index = label_map_util.create_category_index(categories)\n\n image = np.squeeze(result_dict[input_fields.original_image], axis=0)\n if image.shape[2] == 1: # If one channel image, repeat in RGB.\n image = np.tile(image, [1, 1, 3])\n detection_boxes = result_dict[detection_fields.detection_boxes]\n detection_scores = result_dict[detection_fields.detection_scores]\n detection_classes = np.int32((result_dict[\n detection_fields.detection_classes]))\n detection_keypoints = result_dict.get(detection_fields.detection_keypoints)\n detection_masks = result_dict.get(detection_fields.detection_masks)\n detection_boundaries = result_dict.get(detection_fields.detection_boundaries)\n\n # Plot groundtruth underneath detections\n if show_groundtruth:\n groundtruth_boxes = result_dict[input_fields.groundtruth_boxes]\n groundtruth_keypoints = result_dict.get(input_fields.groundtruth_keypoints)\n vis_utils.visualize_boxes_and_labels_on_image_array(\n image=image,\n boxes=groundtruth_boxes,\n classes=None,\n scores=None,\n category_index=category_index,\n keypoints=groundtruth_keypoints,\n use_normalized_coordinates=False,\n max_boxes_to_draw=None,\n groundtruth_box_visualization_color=groundtruth_box_visualization_color)\n vis_utils.visualize_boxes_and_labels_on_image_array(\n image,\n detection_boxes,\n detection_classes,\n detection_scores,\n category_index,\n instance_masks=detection_masks,\n instance_boundaries=detection_boundaries,\n keypoints=detection_keypoints,\n use_normalized_coordinates=False,\n max_boxes_to_draw=max_num_predictions,\n min_score_thresh=min_score_thresh,\n agnostic_mode=agnostic_mode,\n skip_scores=skip_scores,\n skip_labels=skip_labels)\n\n if export_dir:\n if keep_image_id_for_visualization_export and result_dict[fields.\n InputDataFields()\n .key]:\n export_path = os.path.join(export_dir, 'export-{}-{}.png'.format(\n tag, result_dict[fields.InputDataFields().key]))\n else:\n export_path = os.path.join(export_dir, 'export-{}.png'.format(tag))\n vis_utils.save_image_array_as_png(image, export_path)\n\n summary = tf.Summary(value=[\n tf.Summary.Value(\n tag=tag,\n image=tf.Summary.Image(\n encoded_image_string=vis_utils.encode_image_array_as_png_str(\n image)))\n ])\n summary_writer = tf.summary.FileWriterCache.get(summary_dir)\n summary_writer.add_summary(summary, global_step)\n\n tf.logging.info('Detection visualizations written to summary with tag %s.',\n tag)\n\n\ndef _run_checkpoint_once(tensor_dict,\n evaluators=None,\n batch_processor=None,\n checkpoint_dirs=None,\n variables_to_restore=None,\n restore_fn=None,\n num_batches=1,\n master='',\n save_graph=False,\n save_graph_dir='',\n losses_dict=None,\n eval_export_path=None):\n \"\"\"Evaluates metrics defined in evaluators and returns summaries.\n\n This function loads the latest checkpoint in checkpoint_dirs and evaluates\n all metrics defined in evaluators. The metrics are processed in batch by the\n batch_processor.\n\n Args:\n tensor_dict: a dictionary holding tensors representing a batch of detections\n and corresponding groundtruth annotations.\n evaluators: a list of object of type DetectionEvaluator to be used for\n evaluation. Note that the metric names produced by different evaluators\n must be unique.\n batch_processor: a function taking four arguments:\n 1. tensor_dict: the same tensor_dict that is passed in as the first\n argument to this function.\n 2. sess: a tensorflow session\n 3. batch_index: an integer representing the index of the batch amongst\n all batches\n By default, batch_processor is None, which defaults to running:\n return sess.run(tensor_dict)\n To skip an image, it suffices to return an empty dictionary in place of\n result_dict.\n checkpoint_dirs: list of directories to load into an EnsembleModel. If it\n has only one directory, EnsembleModel will not be used --\n a DetectionModel\n will be instantiated directly. Not used if restore_fn is set.\n variables_to_restore: None, or a dictionary mapping variable names found in\n a checkpoint to model variables. The dictionary would normally be\n generated by creating a tf.train.ExponentialMovingAverage object and\n calling its variables_to_restore() method. Not used if restore_fn is set.\n restore_fn: None, or a function that takes a tf.Session object and correctly\n restores all necessary variables from the correct checkpoint file. If\n None, attempts to restore from the first directory in checkpoint_dirs.\n num_batches: the number of batches to use for evaluation.\n master: the location of the Tensorflow session.\n save_graph: whether or not the Tensorflow graph is stored as a pbtxt file.\n save_graph_dir: where to store the Tensorflow graph on disk. If save_graph\n is True this must be non-empty.\n losses_dict: optional dictionary of scalar detection losses.\n eval_export_path: Path for saving a json file that contains the detection\n results in json format.\n\n Returns:\n global_step: the count of global steps.\n all_evaluator_metrics: A dictionary containing metric names and values.\n\n Raises:\n ValueError: if restore_fn is None and checkpoint_dirs doesn't have at least\n one element.\n ValueError: if save_graph is True and save_graph_dir is not defined.\n \"\"\"\n if save_graph and not save_graph_dir:\n raise ValueError('`save_graph_dir` must be defined.')\n sess = tf.Session(master, graph=tf.get_default_graph())\n sess.run(tf.global_variables_initializer())\n sess.run(tf.local_variables_initializer())\n sess.run(tf.tables_initializer())\n if restore_fn:\n restore_fn(sess)\n else:\n if not checkpoint_dirs:\n raise ValueError('`checkpoint_dirs` must have at least one entry.')\n checkpoint_file = tf.train.latest_checkpoint(checkpoint_dirs[0])\n saver = tf.train.Saver(variables_to_restore)\n saver.restore(sess, checkpoint_file)\n\n if save_graph:\n tf.train.write_graph(sess.graph_def, save_graph_dir, 'eval.pbtxt')\n\n counters = {'skipped': 0, 'success': 0}\n aggregate_result_losses_dict = collections.defaultdict(list)\n with tf.contrib.slim.queues.QueueRunners(sess):\n try:\n for batch in range(int(num_batches)):\n if (batch + 1) % 100 == 0:\n tf.logging.info('Running eval ops batch %d/%d', batch + 1,\n num_batches)\n if not batch_processor:\n try:\n if not losses_dict:\n losses_dict = {}\n result_dict, result_losses_dict = sess.run([tensor_dict,\n losses_dict])\n counters['success'] += 1\n except tf.errors.InvalidArgumentError:\n tf.logging.info('Skipping image')\n counters['skipped'] += 1\n result_dict = {}\n else:\n result_dict, result_losses_dict = batch_processor(\n tensor_dict, sess, batch, counters, losses_dict=losses_dict)\n if not result_dict:\n continue\n for key, value in iter(result_losses_dict.items()):\n aggregate_result_losses_dict[key].append(value)\n for evaluator in evaluators:\n # TODO(b/65130867): Use image_id tensor once we fix the input data\n # decoders to return correct image_id.\n # TODO(akuznetsa): result_dict contains batches of images, while\n # add_single_ground_truth_image_info expects a single image. Fix\n if (isinstance(result_dict, dict) and\n fields.InputDataFields.key in result_dict and\n result_dict[fields.InputDataFields.key]):\n image_id = result_dict[fields.InputDataFields.key]\n else:\n image_id = batch\n evaluator.add_single_ground_truth_image_info(\n image_id=image_id, groundtruth_dict=result_dict)\n evaluator.add_single_detected_image_info(\n image_id=image_id, detections_dict=result_dict)\n tf.logging.info('Running eval batches done.')\n except tf.errors.OutOfRangeError:\n tf.logging.info('Done evaluating -- epoch limit reached')\n finally:\n # When done, ask the threads to stop.\n tf.logging.info('# success: %d', counters['success'])\n tf.logging.info('# skipped: %d', counters['skipped'])\n all_evaluator_metrics = {}\n if eval_export_path and eval_export_path is not None:\n for evaluator in evaluators:\n if (isinstance(evaluator, coco_evaluation.CocoDetectionEvaluator) or\n isinstance(evaluator, coco_evaluation.CocoMaskEvaluator)):\n tf.logging.info('Started dumping to json file.')\n evaluator.dump_detections_to_json_file(\n json_output_path=eval_export_path)\n tf.logging.info('Finished dumping to json file.')\n for evaluator in evaluators:\n metrics = evaluator.evaluate()\n evaluator.clear()\n if any(key in all_evaluator_metrics for key in metrics):\n raise ValueError('Metric names between evaluators must not collide.')\n all_evaluator_metrics.update(metrics)\n global_step = tf.train.global_step(sess, tf.train.get_global_step())\n\n for key, value in iter(aggregate_result_losses_dict.items()):\n all_evaluator_metrics['Losses/' + key] = np.mean(value)\n sess.close()\n return (global_step, all_evaluator_metrics)\n\n\n# TODO(rathodv): Add tests.\ndef repeated_checkpoint_run(tensor_dict,\n summary_dir,\n evaluators,\n batch_processor=None,\n checkpoint_dirs=None,\n variables_to_restore=None,\n restore_fn=None,\n num_batches=1,\n eval_interval_secs=120,\n max_number_of_evaluations=None,\n master='',\n save_graph=False,\n save_graph_dir='',\n losses_dict=None,\n eval_export_path=None):\n \"\"\"Periodically evaluates desired tensors using checkpoint_dirs or restore_fn.\n\n This function repeatedly loads a checkpoint and evaluates a desired\n set of tensors (provided by tensor_dict) and hands the resulting numpy\n arrays to a function result_processor which can be used to further\n process/save/visualize the results.\n\n Args:\n tensor_dict: a dictionary holding tensors representing a batch of detections\n and corresponding groundtruth annotations.\n summary_dir: a directory to write metrics summaries.\n evaluators: a list of object of type DetectionEvaluator to be used for\n evaluation. Note that the metric names produced by different evaluators\n must be unique.\n batch_processor: a function taking three arguments:\n 1. tensor_dict: the same tensor_dict that is passed in as the first\n argument to this function.\n 2. sess: a tensorflow session\n 3. batch_index: an integer representing the index of the batch amongst\n all batches\n By default, batch_processor is None, which defaults to running:\n return sess.run(tensor_dict)\n checkpoint_dirs: list of directories to load into a DetectionModel or an\n EnsembleModel if restore_fn isn't set. Also used to determine when to run\n next evaluation. Must have at least one element.\n variables_to_restore: None, or a dictionary mapping variable names found in\n a checkpoint to model variables. The dictionary would normally be\n generated by creating a tf.train.ExponentialMovingAverage object and\n calling its variables_to_restore() method. Not used if restore_fn is set.\n restore_fn: a function that takes a tf.Session object and correctly restores\n all necessary variables from the correct checkpoint file.\n num_batches: the number of batches to use for evaluation.\n eval_interval_secs: the number of seconds between each evaluation run.\n max_number_of_evaluations: the max number of iterations of the evaluation.\n If the value is left as None the evaluation continues indefinitely.\n master: the location of the Tensorflow session.\n save_graph: whether or not the Tensorflow graph is saved as a pbtxt file.\n save_graph_dir: where to save on disk the Tensorflow graph. If store_graph\n is True this must be non-empty.\n losses_dict: optional dictionary of scalar detection losses.\n eval_export_path: Path for saving a json file that contains the detection\n results in json format.\n\n Returns:\n metrics: A dictionary containing metric names and values in the latest\n evaluation.\n\n Raises:\n ValueError: if max_num_of_evaluations is not None or a positive number.\n ValueError: if checkpoint_dirs doesn't have at least one element.\n \"\"\"\n if max_number_of_evaluations and max_number_of_evaluations <= 0:\n raise ValueError(\n '`number_of_steps` must be either None or a positive number.')\n\n if not checkpoint_dirs:\n raise ValueError('`checkpoint_dirs` must have at least one entry.')\n\n last_evaluated_model_path = None\n number_of_evaluations = 0\n while True:\n start = time.time()\n tf.logging.info('Starting evaluation at ' + time.strftime(\n '%Y-%m-%d-%H:%M:%S', time.gmtime()))\n model_path = tf.train.latest_checkpoint(checkpoint_dirs[0])\n if not model_path:\n tf.logging.info('No model found in %s. Will try again in %d seconds',\n checkpoint_dirs[0], eval_interval_secs)\n elif model_path == last_evaluated_model_path:\n tf.logging.info('Found already evaluated checkpoint. Will try again in '\n '%d seconds', eval_interval_secs)\n else:\n last_evaluated_model_path = model_path\n global_step, metrics = _run_checkpoint_once(\n tensor_dict,\n evaluators,\n batch_processor,\n checkpoint_dirs,\n variables_to_restore,\n restore_fn,\n num_batches,\n master,\n save_graph,\n save_graph_dir,\n losses_dict=losses_dict,\n eval_export_path=eval_export_path)\n write_metrics(metrics, global_step, summary_dir)\n number_of_evaluations += 1\n\n if (max_number_of_evaluations and\n number_of_evaluations >= max_number_of_evaluations):\n tf.logging.info('Finished evaluation!')\n break\n time_to_next_eval = start + eval_interval_secs - time.time()\n if time_to_next_eval > 0:\n time.sleep(time_to_next_eval)\n\n return metrics\n\n\ndef _scale_box_to_absolute(args):\n boxes, image_shape = args\n return box_list_ops.to_absolute_coordinates(\n box_list.BoxList(boxes), image_shape[0], image_shape[1]).get()\n\n\ndef _resize_detection_masks(args):\n detection_boxes, detection_masks, image_shape = args\n detection_masks_reframed = ops.reframe_box_masks_to_image_masks(\n detection_masks, detection_boxes, image_shape[0], image_shape[1])\n return tf.cast(tf.greater(detection_masks_reframed, 0.5), tf.uint8)\n\n\ndef _resize_groundtruth_masks(args):\n mask, image_shape = args\n mask = tf.expand_dims(mask, 3)\n mask = tf.image.resize_images(\n mask,\n image_shape,\n method=tf.image.ResizeMethod.NEAREST_NEIGHBOR,\n align_corners=True)\n return tf.cast(tf.squeeze(mask, 3), tf.uint8)\n\n\ndef _scale_keypoint_to_absolute(args):\n keypoints, image_shape = args\n return keypoint_ops.scale(keypoints, image_shape[0], image_shape[1])\n\n\ndef result_dict_for_single_example(image,\n key,\n detections,\n groundtruth=None,\n class_agnostic=False,\n scale_to_absolute=False):\n \"\"\"Merges all detection and groundtruth information for a single example.\n\n Note that evaluation tools require classes that are 1-indexed, and so this\n function performs the offset. If `class_agnostic` is True, all output classes\n have label 1.\n\n Args:\n image: A single 4D uint8 image tensor of shape [1, H, W, C].\n key: A single string tensor identifying the image.\n detections: A dictionary of detections, returned from\n DetectionModel.postprocess().\n groundtruth: (Optional) Dictionary of groundtruth items, with fields:\n 'groundtruth_boxes': [num_boxes, 4] float32 tensor of boxes, in\n normalized coordinates.\n 'groundtruth_classes': [num_boxes] int64 tensor of 1-indexed classes.\n 'groundtruth_area': [num_boxes] float32 tensor of bbox area. (Optional)\n 'groundtruth_is_crowd': [num_boxes] int64 tensor. (Optional)\n 'groundtruth_difficult': [num_boxes] int64 tensor. (Optional)\n 'groundtruth_group_of': [num_boxes] int64 tensor. (Optional)\n 'groundtruth_instance_masks': 3D int64 tensor of instance masks\n (Optional).\n class_agnostic: Boolean indicating whether the detections are class-agnostic\n (i.e. binary). Default False.\n scale_to_absolute: Boolean indicating whether boxes and keypoints should be\n scaled to absolute coordinates. Note that for IoU based evaluations, it\n does not matter whether boxes are expressed in absolute or relative\n coordinates. Default False.\n\n Returns:\n A dictionary with:\n 'original_image': A [1, H, W, C] uint8 image tensor.\n 'key': A string tensor with image identifier.\n 'detection_boxes': [max_detections, 4] float32 tensor of boxes, in\n normalized or absolute coordinates, depending on the value of\n `scale_to_absolute`.\n 'detection_scores': [max_detections] float32 tensor of scores.\n 'detection_classes': [max_detections] int64 tensor of 1-indexed classes.\n 'detection_masks': [max_detections, H, W] float32 tensor of binarized\n masks, reframed to full image masks.\n 'groundtruth_boxes': [num_boxes, 4] float32 tensor of boxes, in\n normalized or absolute coordinates, depending on the value of\n `scale_to_absolute`. (Optional)\n 'groundtruth_classes': [num_boxes] int64 tensor of 1-indexed classes.\n (Optional)\n 'groundtruth_area': [num_boxes] float32 tensor of bbox area. (Optional)\n 'groundtruth_is_crowd': [num_boxes] int64 tensor. (Optional)\n 'groundtruth_difficult': [num_boxes] int64 tensor. (Optional)\n 'groundtruth_group_of': [num_boxes] int64 tensor. (Optional)\n 'groundtruth_instance_masks': 3D int64 tensor of instance masks\n (Optional).\n\n \"\"\"\n\n if groundtruth:\n max_gt_boxes = tf.shape(\n groundtruth[fields.InputDataFields.groundtruth_boxes])[0]\n for gt_key in groundtruth:\n # expand groundtruth dict along the batch dimension.\n groundtruth[gt_key] = tf.expand_dims(groundtruth[gt_key], 0)\n\n for detection_key in detections:\n detections[detection_key] = tf.expand_dims(\n detections[detection_key][0], axis=0)\n\n batched_output_dict = result_dict_for_batched_example(\n image,\n tf.expand_dims(key, 0),\n detections,\n groundtruth,\n class_agnostic,\n scale_to_absolute,\n max_gt_boxes=max_gt_boxes)\n\n exclude_keys = [\n fields.InputDataFields.original_image,\n fields.DetectionResultFields.num_detections,\n fields.InputDataFields.num_groundtruth_boxes\n ]\n\n output_dict = {\n fields.InputDataFields.original_image:\n batched_output_dict[fields.InputDataFields.original_image]\n }\n\n for key in batched_output_dict:\n # remove the batch dimension.\n if key not in exclude_keys:\n output_dict[key] = tf.squeeze(batched_output_dict[key], 0)\n return output_dict\n\n\ndef result_dict_for_batched_example(images,\n keys,\n detections,\n groundtruth=None,\n class_agnostic=False,\n scale_to_absolute=False,\n original_image_spatial_shapes=None,\n true_image_shapes=None,\n max_gt_boxes=None):\n \"\"\"Merges all detection and groundtruth information for a single example.\n\n Note that evaluation tools require classes that are 1-indexed, and so this\n function performs the offset. If `class_agnostic` is True, all output classes\n have label 1.\n\n Args:\n images: A single 4D uint8 image tensor of shape [batch_size, H, W, C].\n keys: A [batch_size] string tensor with image identifier.\n detections: A dictionary of detections, returned from\n DetectionModel.postprocess().\n groundtruth: (Optional) Dictionary of groundtruth items, with fields:\n 'groundtruth_boxes': [batch_size, max_number_of_boxes, 4] float32 tensor\n of boxes, in normalized coordinates.\n 'groundtruth_classes': [batch_size, max_number_of_boxes] int64 tensor of\n 1-indexed classes.\n 'groundtruth_area': [batch_size, max_number_of_boxes] float32 tensor of\n bbox area. (Optional)\n 'groundtruth_is_crowd':[batch_size, max_number_of_boxes] int64\n tensor. (Optional)\n 'groundtruth_difficult': [batch_size, max_number_of_boxes] int64\n tensor. (Optional)\n 'groundtruth_group_of': [batch_size, max_number_of_boxes] int64\n tensor. (Optional)\n 'groundtruth_instance_masks': 4D int64 tensor of instance\n masks (Optional).\n class_agnostic: Boolean indicating whether the detections are class-agnostic\n (i.e. binary). Default False.\n scale_to_absolute: Boolean indicating whether boxes and keypoints should be\n scaled to absolute coordinates. Note that for IoU based evaluations, it\n does not matter whether boxes are expressed in absolute or relative\n coordinates. Default False.\n original_image_spatial_shapes: A 2D int32 tensor of shape [batch_size, 2]\n used to resize the image. When set to None, the image size is retained.\n true_image_shapes: A 2D int32 tensor of shape [batch_size, 3]\n containing the size of the unpadded original_image.\n max_gt_boxes: [batch_size] tensor representing the maximum number of\n groundtruth boxes to pad.\n\n Returns:\n A dictionary with:\n 'original_image': A [batch_size, H, W, C] uint8 image tensor.\n 'original_image_spatial_shape': A [batch_size, 2] tensor containing the\n original image sizes.\n 'true_image_shape': A [batch_size, 3] tensor containing the size of\n the unpadded original_image.\n 'key': A [batch_size] string tensor with image identifier.\n 'detection_boxes': [batch_size, max_detections, 4] float32 tensor of boxes,\n in normalized or absolute coordinates, depending on the value of\n `scale_to_absolute`.\n 'detection_scores': [batch_size, max_detections] float32 tensor of scores.\n 'detection_classes': [batch_size, max_detections] int64 tensor of 1-indexed\n classes.\n 'detection_masks': [batch_size, max_detections, H, W] float32 tensor of\n binarized masks, reframed to full image masks.\n 'num_detections': [batch_size] int64 tensor containing number of valid\n detections.\n 'groundtruth_boxes': [batch_size, num_boxes, 4] float32 tensor of boxes, in\n normalized or absolute coordinates, depending on the value of\n `scale_to_absolute`. (Optional)\n 'groundtruth_classes': [batch_size, num_boxes] int64 tensor of 1-indexed\n classes. (Optional)\n 'groundtruth_area': [batch_size, num_boxes] float32 tensor of bbox\n area. (Optional)\n 'groundtruth_is_crowd': [batch_size, num_boxes] int64 tensor. (Optional)\n 'groundtruth_difficult': [batch_size, num_boxes] int64 tensor. (Optional)\n 'groundtruth_group_of': [batch_size, num_boxes] int64 tensor. (Optional)\n 'groundtruth_instance_masks': 4D int64 tensor of instance masks\n (Optional).\n 'num_groundtruth_boxes': [batch_size] tensor containing the maximum number\n of groundtruth boxes per image.\n\n Raises:\n ValueError: if original_image_spatial_shape is not 2D int32 tensor of shape\n [2].\n ValueError: if true_image_shapes is not 2D int32 tensor of shape\n [3].\n \"\"\"\n label_id_offset = 1 # Applying label id offset (b/63711816)\n\n input_data_fields = fields.InputDataFields\n if original_image_spatial_shapes is None:\n original_image_spatial_shapes = tf.tile(\n tf.expand_dims(tf.shape(images)[1:3], axis=0),\n multiples=[tf.shape(images)[0], 1])\n else:\n if (len(original_image_spatial_shapes.shape) != 2 and\n original_image_spatial_shapes.shape[1] != 2):\n raise ValueError(\n '`original_image_spatial_shape` should be a 2D tensor of shape '\n '[batch_size, 2].')\n\n if true_image_shapes is None:\n true_image_shapes = tf.tile(\n tf.expand_dims(tf.shape(images)[1:4], axis=0),\n multiples=[tf.shape(images)[0], 1])\n else:\n if (len(true_image_shapes.shape) != 2\n and true_image_shapes.shape[1] != 3):\n raise ValueError('`true_image_shapes` should be a 2D tensor of '\n 'shape [batch_size, 3].')\n\n output_dict = {\n input_data_fields.original_image:\n images,\n input_data_fields.key:\n keys,\n input_data_fields.original_image_spatial_shape: (\n original_image_spatial_shapes),\n input_data_fields.true_image_shape:\n true_image_shapes\n }\n\n detection_fields = fields.DetectionResultFields\n detection_boxes = detections[detection_fields.detection_boxes]\n detection_scores = detections[detection_fields.detection_scores]\n num_detections = tf.to_int32(detections[detection_fields.num_detections])\n\n if class_agnostic:\n detection_classes = tf.ones_like(detection_scores, dtype=tf.int64)\n else:\n detection_classes = (\n tf.to_int64(detections[detection_fields.detection_classes]) +\n label_id_offset)\n\n if scale_to_absolute:\n output_dict[detection_fields.detection_boxes] = (\n shape_utils.static_or_dynamic_map_fn(\n _scale_box_to_absolute,\n elems=[detection_boxes, original_image_spatial_shapes],\n dtype=tf.float32))\n else:\n output_dict[detection_fields.detection_boxes] = detection_boxes\n output_dict[detection_fields.detection_classes] = detection_classes\n output_dict[detection_fields.detection_scores] = detection_scores\n output_dict[detection_fields.num_detections] = num_detections\n\n if detection_fields.detection_masks in detections:\n detection_masks = detections[detection_fields.detection_masks]\n # TODO(rathodv): This should be done in model's postprocess\n # function ideally.\n output_dict[detection_fields.detection_masks] = (\n shape_utils.static_or_dynamic_map_fn(\n _resize_detection_masks,\n elems=[detection_boxes, detection_masks,\n original_image_spatial_shapes],\n dtype=tf.uint8))\n\n if detection_fields.detection_keypoints in detections:\n detection_keypoints = detections[detection_fields.detection_keypoints]\n output_dict[detection_fields.detection_keypoints] = detection_keypoints\n if scale_to_absolute:\n output_dict[detection_fields.detection_keypoints] = (\n shape_utils.static_or_dynamic_map_fn(\n _scale_keypoint_to_absolute,\n elems=[detection_keypoints, original_image_spatial_shapes],\n dtype=tf.float32))\n\n if groundtruth:\n if max_gt_boxes is None:\n if input_data_fields.num_groundtruth_boxes in groundtruth:\n max_gt_boxes = groundtruth[input_data_fields.num_groundtruth_boxes]\n else:\n raise ValueError(\n 'max_gt_boxes must be provided when processing batched examples.')\n\n if input_data_fields.groundtruth_instance_masks in groundtruth:\n masks = groundtruth[input_data_fields.groundtruth_instance_masks]\n groundtruth[input_data_fields.groundtruth_instance_masks] = (\n shape_utils.static_or_dynamic_map_fn(\n _resize_groundtruth_masks,\n elems=[masks, original_image_spatial_shapes],\n dtype=tf.uint8))\n\n output_dict.update(groundtruth)\n if scale_to_absolute:\n groundtruth_boxes = groundtruth[input_data_fields.groundtruth_boxes]\n output_dict[input_data_fields.groundtruth_boxes] = (\n shape_utils.static_or_dynamic_map_fn(\n _scale_box_to_absolute,\n elems=[groundtruth_boxes, original_image_spatial_shapes],\n dtype=tf.float32))\n\n # For class-agnostic models, groundtruth classes all become 1.\n if class_agnostic:\n groundtruth_classes = groundtruth[input_data_fields.groundtruth_classes]\n groundtruth_classes = tf.ones_like(groundtruth_classes, dtype=tf.int64)\n output_dict[input_data_fields.groundtruth_classes] = groundtruth_classes\n\n output_dict[input_data_fields.num_groundtruth_boxes] = max_gt_boxes\n\n return output_dict\n\n\ndef get_evaluators(eval_config, categories, evaluator_options=None):\n \"\"\"Returns the evaluator class according to eval_config, valid for categories.\n\n Args:\n eval_config: An `eval_pb2.EvalConfig`.\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 evaluator_options: A dictionary of metric names (see\n EVAL_METRICS_CLASS_DICT) to `DetectionEvaluator` initialization\n keyword arguments. For example:\n evalator_options = {\n 'coco_detection_metrics': {'include_metrics_per_category': True}\n }\n\n Returns:\n An list of instances of DetectionEvaluator.\n\n Raises:\n ValueError: if metric is not in the metric class dictionary.\n \"\"\"\n evaluator_options = evaluator_options or {}\n eval_metric_fn_keys = eval_config.metrics_set\n if not eval_metric_fn_keys:\n eval_metric_fn_keys = [EVAL_DEFAULT_METRIC]\n evaluators_list = []\n for eval_metric_fn_key in eval_metric_fn_keys:\n if eval_metric_fn_key not in EVAL_METRICS_CLASS_DICT:\n raise ValueError('Metric not found: {}'.format(eval_metric_fn_key))\n kwargs_dict = (evaluator_options[eval_metric_fn_key] if eval_metric_fn_key\n in evaluator_options else {})\n evaluators_list.append(EVAL_METRICS_CLASS_DICT[eval_metric_fn_key](\n categories,\n **kwargs_dict))\n return evaluators_list\n\n\ndef get_eval_metric_ops_for_evaluators(eval_config,\n categories,\n eval_dict):\n \"\"\"Returns eval metrics ops to use with `tf.estimator.EstimatorSpec`.\n\n Args:\n eval_config: An `eval_pb2.EvalConfig`.\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 eval_dict: An evaluation dictionary, returned from\n result_dict_for_single_example().\n\n Returns:\n A dictionary of metric names to tuple of value_op and update_op that can be\n used as eval metric ops in tf.EstimatorSpec.\n \"\"\"\n eval_metric_ops = {}\n evaluator_options = evaluator_options_from_eval_config(eval_config)\n evaluators_list = get_evaluators(eval_config, categories, evaluator_options)\n for evaluator in evaluators_list:\n eval_metric_ops.update(evaluator.get_estimator_eval_metric_ops(\n eval_dict))\n return eval_metric_ops\n\n\ndef evaluator_options_from_eval_config(eval_config):\n \"\"\"Produces a dictionary of evaluation options for each eval metric.\n\n Args:\n eval_config: An `eval_pb2.EvalConfig`.\n\n Returns:\n evaluator_options: A dictionary of metric names (see\n EVAL_METRICS_CLASS_DICT) to `DetectionEvaluator` initialization\n keyword arguments. For example:\n evalator_options = {\n 'coco_detection_metrics': {'include_metrics_per_category': True}\n }\n \"\"\"\n eval_metric_fn_keys = eval_config.metrics_set\n evaluator_options = {}\n for eval_metric_fn_key in eval_metric_fn_keys:\n if eval_metric_fn_key in ('coco_detection_metrics', 'coco_mask_metrics'):\n evaluator_options[eval_metric_fn_key] = {\n 'include_metrics_per_category': (\n eval_config.include_metrics_per_category)\n }\n return evaluator_options\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 object_detection.builders.image_resizer_builder.\"\"\"\nimport numpy as np\nimport tensorflow as tf\nfrom google.protobuf import text_format\nfrom object_detection.builders import image_resizer_builder\nfrom object_detection.protos import image_resizer_pb2\n\n\nclass ImageResizerBuilderTest(tf.test.TestCase):\n\n def _shape_of_resized_random_image_given_text_proto(self, input_shape,\n text_proto):\n image_resizer_config = image_resizer_pb2.ImageResizer()\n text_format.Merge(text_proto, image_resizer_config)\n image_resizer_fn = image_resizer_builder.build(image_resizer_config)\n images = tf.to_float(\n tf.random_uniform(input_shape, minval=0, maxval=255, dtype=tf.int32))\n resized_images, _ = image_resizer_fn(images)\n with self.test_session() as sess:\n return sess.run(resized_images).shape\n\n def test_build_keep_aspect_ratio_resizer_returns_expected_shape(self):\n image_resizer_text_proto = \"\"\"\n keep_aspect_ratio_resizer {\n min_dimension: 10\n max_dimension: 20\n }\n \"\"\"\n input_shape = (50, 25, 3)\n expected_output_shape = (20, 10, 3)\n output_shape = self._shape_of_resized_random_image_given_text_proto(\n input_shape, image_resizer_text_proto)\n self.assertEqual(output_shape, expected_output_shape)\n\n def test_build_keep_aspect_ratio_resizer_grayscale(self):\n image_resizer_text_proto = \"\"\"\n keep_aspect_ratio_resizer {\n min_dimension: 10\n max_dimension: 20\n convert_to_grayscale: true\n }\n \"\"\"\n input_shape = (50, 25, 3)\n expected_output_shape = (20, 10, 1)\n output_shape = self._shape_of_resized_random_image_given_text_proto(\n input_shape, image_resizer_text_proto)\n self.assertEqual(output_shape, expected_output_shape)\n\n def test_build_keep_aspect_ratio_resizer_with_padding(self):\n image_resizer_text_proto = \"\"\"\n keep_aspect_ratio_resizer {\n min_dimension: 10\n max_dimension: 20\n pad_to_max_dimension: true\n per_channel_pad_value: 3\n per_channel_pad_value: 4\n per_channel_pad_value: 5\n }\n \"\"\"\n input_shape = (50, 25, 3)\n expected_output_shape = (20, 20, 3)\n output_shape = self._shape_of_resized_random_image_given_text_proto(\n input_shape, image_resizer_text_proto)\n self.assertEqual(output_shape, expected_output_shape)\n\n def test_built_fixed_shape_resizer_returns_expected_shape(self):\n image_resizer_text_proto = \"\"\"\n fixed_shape_resizer {\n height: 10\n width: 20\n }\n \"\"\"\n input_shape = (50, 25, 3)\n expected_output_shape = (10, 20, 3)\n output_shape = self._shape_of_resized_random_image_given_text_proto(\n input_shape, image_resizer_text_proto)\n self.assertEqual(output_shape, expected_output_shape)\n\n def test_built_fixed_shape_resizer_grayscale(self):\n image_resizer_text_proto = \"\"\"\n fixed_shape_resizer {\n height: 10\n width: 20\n convert_to_grayscale: true\n }\n \"\"\"\n input_shape = (50, 25, 3)\n expected_output_shape = (10, 20, 1)\n output_shape = self._shape_of_resized_random_image_given_text_proto(\n input_shape, image_resizer_text_proto)\n self.assertEqual(output_shape, expected_output_shape)\n\n def test_raises_error_on_invalid_input(self):\n invalid_input = 'invalid_input'\n with self.assertRaises(ValueError):\n image_resizer_builder.build(invalid_input)\n\n def _resized_image_given_text_proto(self, image, text_proto):\n image_resizer_config = image_resizer_pb2.ImageResizer()\n text_format.Merge(text_proto, image_resizer_config)\n image_resizer_fn = image_resizer_builder.build(image_resizer_config)\n image_placeholder = tf.placeholder(tf.uint8, [1, None, None, 3])\n resized_image, _ = image_resizer_fn(image_placeholder)\n with self.test_session() as sess:\n return sess.run(resized_image, feed_dict={image_placeholder: image})\n\n def test_fixed_shape_resizer_nearest_neighbor_method(self):\n image_resizer_text_proto = \"\"\"\n fixed_shape_resizer {\n height: 1\n width: 1\n resize_method: NEAREST_NEIGHBOR\n }\n \"\"\"\n image = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n image = np.expand_dims(image, axis=2)\n image = np.tile(image, (1, 1, 3))\n image = np.expand_dims(image, axis=0)\n resized_image = self._resized_image_given_text_proto(\n image, image_resizer_text_proto)\n vals = np.unique(resized_image).tolist()\n self.assertEqual(len(vals), 1)\n self.assertEqual(vals[0], 1)\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\"\"\"SSDFeatureExtractor for InceptionV2 features.\"\"\"\nimport tensorflow as tf\n\nfrom object_detection.meta_architectures import ssd_meta_arch\nfrom object_detection.models import feature_map_generators\nfrom object_detection.utils import ops\nfrom object_detection.utils import shape_utils\nfrom nets import inception_v2\n\nslim = tf.contrib.slim\n\n\nclass SSDInceptionV2FeatureExtractor(ssd_meta_arch.SSDFeatureExtractor):\n \"\"\"SSD Feature Extractor using InceptionV2 features.\"\"\"\n\n def __init__(self,\n is_training,\n depth_multiplier,\n min_depth,\n pad_to_multiple,\n conv_hyperparams_fn,\n reuse_weights=None,\n use_explicit_padding=False,\n use_depthwise=False,\n override_base_feature_extractor_hyperparams=False):\n \"\"\"InceptionV2 Feature Extractor for SSD Models.\n\n Args:\n is_training: whether the network is in training mode.\n depth_multiplier: float depth multiplier for feature extractor.\n min_depth: minimum feature extractor depth.\n pad_to_multiple: the nearest multiple to zero pad the input height and\n width dimensions to.\n conv_hyperparams_fn: A function to construct tf slim arg_scope for conv2d\n and separable_conv2d ops in the layers that are added on top of the\n base feature extractor.\n reuse_weights: Whether to reuse variables. Default is None.\n use_explicit_padding: Whether to use explicit padding when extracting\n features. Default is False.\n use_depthwise: Whether to use depthwise convolutions. Default is False.\n override_base_feature_extractor_hyperparams: Whether to override\n hyperparameters of the base feature extractor with the one from\n `conv_hyperparams_fn`.\n\n Raises:\n ValueError: If `override_base_feature_extractor_hyperparams` is False.\n \"\"\"\n super(SSDInceptionV2FeatureExtractor, self).__init__(\n is_training=is_training,\n depth_multiplier=depth_multiplier,\n min_depth=min_depth,\n pad_to_multiple=pad_to_multiple,\n conv_hyperparams_fn=conv_hyperparams_fn,\n reuse_weights=reuse_weights,\n use_explicit_padding=use_explicit_padding,\n use_depthwise=use_depthwise,\n override_base_feature_extractor_hyperparams=\n override_base_feature_extractor_hyperparams)\n if not self._override_base_feature_extractor_hyperparams:\n raise ValueError('SSD Inception V2 feature extractor always uses'\n 'scope returned by `conv_hyperparams_fn` for both the '\n 'base feature extractor and the additional layers '\n 'added since there is no arg_scope defined for the base '\n 'feature extractor.')\n\n def preprocess(self, resized_inputs):\n \"\"\"SSD preprocessing.\n\n Maps pixel values to the range [-1, 1].\n\n Args:\n resized_inputs: a [batch, height, width, channels] float tensor\n representing a batch of images.\n\n Returns:\n preprocessed_inputs: a [batch, height, width, channels] float tensor\n representing a batch of images.\n \"\"\"\n return (2.0 / 255.0) * resized_inputs - 1.0\n\n def extract_features(self, preprocessed_inputs):\n \"\"\"Extract features from preprocessed inputs.\n\n Args:\n preprocessed_inputs: a [batch, height, width, channels] float tensor\n representing a batch of images.\n\n Returns:\n feature_maps: a list of tensors where the ith tensor has shape\n [batch, height_i, width_i, depth_i]\n \"\"\"\n preprocessed_inputs = shape_utils.check_min_image_dim(\n 33, preprocessed_inputs)\n\n feature_map_layout = {\n 'from_layer': ['Mixed_4c', 'Mixed_5c', '', '', '', ''],\n 'layer_depth': [-1, -1, 512, 256, 256, 128],\n 'use_explicit_padding': self._use_explicit_padding,\n 'use_depthwise': self._use_depthwise,\n }\n\n with slim.arg_scope(self._conv_hyperparams_fn()):\n with tf.variable_scope('InceptionV2',\n reuse=self._reuse_weights) as scope:\n _, image_features = inception_v2.inception_v2_base(\n ops.pad_to_multiple(preprocessed_inputs, self._pad_to_multiple),\n final_endpoint='Mixed_5c',\n min_depth=self._min_depth,\n depth_multiplier=self._depth_multiplier,\n scope=scope)\n feature_maps = feature_map_generators.multi_resolution_feature_maps(\n feature_map_layout=feature_map_layout,\n depth_multiplier=self._depth_multiplier,\n min_depth=self._min_depth,\n insert_1x1_conv=True,\n image_features=image_features)\n\n return feature_maps.values()\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\"\"\"Region Similarity Calculators for BoxLists.\n\nRegion Similarity Calculators compare a pairwise measure of similarity\nbetween the boxes in two BoxLists.\n\"\"\"\nfrom abc import ABCMeta\nfrom abc import abstractmethod\n\nimport tensorflow as tf\n\nfrom object_detection.core import box_list_ops\nfrom object_detection.core import standard_fields as fields\n\n\nclass RegionSimilarityCalculator(object):\n \"\"\"Abstract base class for region similarity calculator.\"\"\"\n __metaclass__ = ABCMeta\n\n def compare(self, boxlist1, boxlist2, scope=None):\n \"\"\"Computes matrix of pairwise similarity between BoxLists.\n\n This op (to be overridden) computes a measure of pairwise similarity between\n the boxes in the given BoxLists. Higher values indicate more similarity.\n\n Note that this method simply measures similarity and does not explicitly\n perform a matching.\n\n Args:\n boxlist1: BoxList holding N boxes.\n boxlist2: BoxList holding M boxes.\n scope: Op scope name. Defaults to 'Compare' if None.\n\n Returns:\n a (float32) tensor of shape [N, M] with pairwise similarity score.\n \"\"\"\n with tf.name_scope(scope, 'Compare', [boxlist1, boxlist2]) as scope:\n return self._compare(boxlist1, boxlist2)\n\n @abstractmethod\n def _compare(self, boxlist1, boxlist2):\n pass\n\n\nclass IouSimilarity(RegionSimilarityCalculator):\n \"\"\"Class to compute similarity based on Intersection over Union (IOU) metric.\n\n This class computes pairwise similarity between two BoxLists based on IOU.\n \"\"\"\n\n def _compare(self, boxlist1, boxlist2):\n \"\"\"Compute pairwise IOU similarity between the two BoxLists.\n\n Args:\n boxlist1: BoxList holding N boxes.\n boxlist2: BoxList holding M boxes.\n\n Returns:\n A tensor with shape [N, M] representing pairwise iou scores.\n \"\"\"\n return box_list_ops.iou(boxlist1, boxlist2)\n\n\nclass NegSqDistSimilarity(RegionSimilarityCalculator):\n \"\"\"Class to compute similarity based on the squared distance metric.\n\n This class computes pairwise similarity between two BoxLists based on the\n negative squared distance metric.\n \"\"\"\n\n def _compare(self, boxlist1, boxlist2):\n \"\"\"Compute matrix of (negated) sq distances.\n\n Args:\n boxlist1: BoxList holding N boxes.\n boxlist2: BoxList holding M boxes.\n\n Returns:\n A tensor with shape [N, M] representing negated pairwise squared distance.\n \"\"\"\n return -1 * box_list_ops.sq_dist(boxlist1, boxlist2)\n\n\nclass IoaSimilarity(RegionSimilarityCalculator):\n \"\"\"Class to compute similarity based on Intersection over Area (IOA) metric.\n\n This class computes pairwise similarity between two BoxLists based on their\n pairwise intersections divided by the areas of second BoxLists.\n \"\"\"\n\n def _compare(self, boxlist1, boxlist2):\n \"\"\"Compute pairwise IOA similarity between the two BoxLists.\n\n Args:\n boxlist1: BoxList holding N boxes.\n boxlist2: BoxList holding M boxes.\n\n Returns:\n A tensor with shape [N, M] representing pairwise IOA scores.\n \"\"\"\n return box_list_ops.ioa(boxlist1, boxlist2)\n\n\nclass ThresholdedIouSimilarity(RegionSimilarityCalculator):\n \"\"\"Class to compute similarity based on thresholded IOU and score.\n\n This class computes pairwise similarity between two BoxLists based on IOU and\n a 'score' present in boxlist1. If IOU > threshold, then the entry in the\n output pairwise tensor will contain `score`, otherwise 0.\n \"\"\"\n\n def __init__(self, iou_threshold=0):\n \"\"\"Initialize the ThresholdedIouSimilarity.\n\n Args:\n iou_threshold: For a given pair of boxes, if the IOU is > iou_threshold,\n then the comparison result will be the foreground probability of\n the first box, otherwise it will be zero.\n \"\"\"\n self._iou_threshold = iou_threshold\n\n def _compare(self, boxlist1, boxlist2):\n \"\"\"Compute pairwise IOU similarity between the two BoxLists and score.\n\n Args:\n boxlist1: BoxList holding N boxes. Must have a score field.\n boxlist2: BoxList holding M boxes.\n\n Returns:\n A tensor with shape [N, M] representing scores threholded by pairwise\n iou scores.\n \"\"\"\n ious = box_list_ops.iou(boxlist1, boxlist2)\n scores = boxlist1.get_field(fields.BoxListFields.scores)\n scores = tf.expand_dims(scores, axis=1)\n row_replicated_scores = tf.tile(scores, [1, tf.shape(ious)[-1]])\n thresholded_ious = tf.where(ious > self._iou_threshold,\n row_replicated_scores, tf.zeros_like(ious))\n\n return thresholded_ious\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\"\"\"MNIST model training with TensorFlow eager execution.\n\nSee:\nhttps://research.googleblog.com/2017/10/eager-execution-imperative-define-by.html\n\nThis program demonstrates training of the convolutional neural network model\ndefined in mnist.py with eager execution enabled.\n\nIf you are not interested in eager execution, you should ignore this file.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport time\n\n# pylint: disable=g-bad-import-order\nfrom absl import app as absl_app\nfrom absl import flags\nimport tensorflow as tf\n# pylint: enable=g-bad-import-order\n\nfrom official.mnist import dataset as mnist_dataset\nfrom official.mnist import mnist\nfrom official.utils.flags import core as flags_core\nfrom official.utils.misc import model_helpers\n\n\ntfe = tf.contrib.eager\n\ndef loss(logits, labels):\n return tf.reduce_mean(\n tf.nn.sparse_softmax_cross_entropy_with_logits(\n logits=logits, labels=labels))\n\n\ndef compute_accuracy(logits, labels):\n predictions = tf.argmax(logits, axis=1, output_type=tf.int64)\n labels = tf.cast(labels, tf.int64)\n batch_size = int(logits.shape[0])\n return tf.reduce_sum(\n tf.cast(tf.equal(predictions, labels), dtype=tf.float32)) / batch_size\n\n\ndef train(model, optimizer, dataset, step_counter, log_interval=None):\n \"\"\"Trains model on `dataset` using `optimizer`.\"\"\"\n\n start = time.time()\n for (batch, (images, labels)) in enumerate(dataset):\n with tf.contrib.summary.record_summaries_every_n_global_steps(\n 10, global_step=step_counter):\n # Record the operations used to compute the loss given the input,\n # so that the gradient of the loss with respect to the variables\n # can be computed.\n with tf.GradientTape() as tape:\n logits = model(images, training=True)\n loss_value = loss(logits, labels)\n tf.contrib.summary.scalar('loss', loss_value)\n tf.contrib.summary.scalar('accuracy', compute_accuracy(logits, labels))\n grads = tape.gradient(loss_value, model.variables)\n optimizer.apply_gradients(\n zip(grads, model.variables), global_step=step_counter)\n if log_interval and batch % log_interval == 0:\n rate = log_interval / (time.time() - start)\n print('Step #%d\\tLoss: %.6f (%d steps/sec)' % (batch, loss_value, rate))\n start = time.time()\n\n\ndef test(model, dataset):\n \"\"\"Perform an evaluation of `model` on the examples from `dataset`.\"\"\"\n avg_loss = tfe.metrics.Mean('loss', dtype=tf.float32)\n accuracy = tfe.metrics.Accuracy('accuracy', dtype=tf.float32)\n\n for (images, labels) in dataset:\n logits = model(images, training=False)\n avg_loss(loss(logits, labels))\n accuracy(\n tf.argmax(logits, axis=1, output_type=tf.int64),\n tf.cast(labels, tf.int64))\n print('Test set: Average loss: %.4f, Accuracy: %4f%%\\n' %\n (avg_loss.result(), 100 * accuracy.result()))\n with tf.contrib.summary.always_record_summaries():\n tf.contrib.summary.scalar('loss', avg_loss.result())\n tf.contrib.summary.scalar('accuracy', accuracy.result())\n\n\ndef run_mnist_eager(flags_obj):\n \"\"\"Run MNIST training and eval loop in eager mode.\n\n Args:\n flags_obj: An object containing parsed flag values.\n \"\"\"\n tf.enable_eager_execution()\n model_helpers.apply_clean(flags.FLAGS)\n\n # Automatically determine device and data_format\n (device, data_format) = ('/gpu:0', 'channels_first')\n if flags_obj.no_gpu or not tf.test.is_gpu_available():\n (device, data_format) = ('/cpu:0', 'channels_last')\n # If data_format is defined in FLAGS, overwrite automatically set value.\n if flags_obj.data_format is not None:\n data_format = flags_obj.data_format\n print('Using device %s, and data format %s.' % (device, data_format))\n\n # Load the datasets\n train_ds = mnist_dataset.train(flags_obj.data_dir).shuffle(60000).batch(\n flags_obj.batch_size)\n test_ds = mnist_dataset.test(flags_obj.data_dir).batch(\n flags_obj.batch_size)\n\n # Create the model and optimizer\n model = mnist.create_model(data_format)\n optimizer = tf.train.MomentumOptimizer(flags_obj.lr, flags_obj.momentum)\n\n # Create file writers for writing TensorBoard summaries.\n if flags_obj.output_dir:\n # Create directories to which summaries will be written\n # tensorboard --logdir=<output_dir>\n # can then be used to see the recorded summaries.\n train_dir = os.path.join(flags_obj.output_dir, 'train')\n test_dir = os.path.join(flags_obj.output_dir, 'eval')\n tf.gfile.MakeDirs(flags_obj.output_dir)\n else:\n train_dir = None\n test_dir = None\n summary_writer = tf.contrib.summary.create_file_writer(\n train_dir, flush_millis=10000)\n test_summary_writer = tf.contrib.summary.create_file_writer(\n test_dir, flush_millis=10000, name='test')\n\n # Create and restore checkpoint (if one exists on the path)\n checkpoint_prefix = os.path.join(flags_obj.model_dir, 'ckpt')\n step_counter = tf.train.get_or_create_global_step()\n checkpoint = tf.train.Checkpoint(\n model=model, optimizer=optimizer, step_counter=step_counter)\n # Restore variables on creation if a checkpoint exists.\n checkpoint.restore(tf.train.latest_checkpoint(flags_obj.model_dir))\n\n # Train and evaluate for a set number of epochs.\n with tf.device(device):\n for _ in range(flags_obj.train_epochs):\n start = time.time()\n with summary_writer.as_default():\n train(model, optimizer, train_ds, step_counter,\n flags_obj.log_interval)\n end = time.time()\n print('\\nTrain time for epoch #%d (%d total steps): %f' %\n (checkpoint.save_counter.numpy() + 1,\n step_counter.numpy(),\n end - start))\n with test_summary_writer.as_default():\n test(model, test_ds)\n checkpoint.save(checkpoint_prefix)\n\n\ndef define_mnist_eager_flags():\n \"\"\"Defined flags and defaults for MNIST in eager mode.\"\"\"\n flags_core.define_base_eager()\n flags_core.define_image()\n flags.adopt_module_key_flags(flags_core)\n\n flags.DEFINE_integer(\n name='log_interval', short_name='li', default=10,\n help=flags_core.help_wrap('batches between logging training status'))\n\n flags.DEFINE_string(\n name='output_dir', short_name='od', default=None,\n help=flags_core.help_wrap('Directory to write TensorBoard summaries'))\n\n flags.DEFINE_float(name='learning_rate', short_name='lr', default=0.01,\n help=flags_core.help_wrap('Learning rate.'))\n\n flags.DEFINE_float(name='momentum', short_name='m', default=0.5,\n help=flags_core.help_wrap('SGD momentum.'))\n\n flags.DEFINE_bool(name='no_gpu', short_name='nogpu', default=False,\n help=flags_core.help_wrap(\n 'disables GPU usage even if a GPU is available'))\n\n flags_core.set_defaults(\n data_dir='/tmp/tensorflow/mnist/input_data',\n model_dir='/tmp/tensorflow/mnist/checkpoints/',\n batch_size=100,\n train_epochs=10,\n )\n\n\ndef main(_):\n run_mnist_eager(flags.FLAGS)\n\n\nif __name__ == '__main__':\n define_mnist_eager_flags()\n absl_app.run(main=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 Model Helper functions.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf # pylint: disable=g-bad-import-order\n\nfrom official.utils.misc import model_helpers\n\n\nclass PastStopThresholdTest(tf.test.TestCase):\n \"\"\"Tests for past_stop_threshold.\"\"\"\n\n def test_past_stop_threshold(self):\n \"\"\"Tests for normal operating conditions.\"\"\"\n self.assertTrue(model_helpers.past_stop_threshold(0.54, 1))\n self.assertTrue(model_helpers.past_stop_threshold(54, 100))\n self.assertFalse(model_helpers.past_stop_threshold(0.54, 0.1))\n self.assertFalse(model_helpers.past_stop_threshold(-0.54, -1.5))\n self.assertTrue(model_helpers.past_stop_threshold(-0.54, 0))\n self.assertTrue(model_helpers.past_stop_threshold(0, 0))\n self.assertTrue(model_helpers.past_stop_threshold(0.54, 0.54))\n\n def test_past_stop_threshold_none_false(self):\n \"\"\"Tests that check None returns false.\"\"\"\n self.assertFalse(model_helpers.past_stop_threshold(None, -1.5))\n self.assertFalse(model_helpers.past_stop_threshold(None, None))\n self.assertFalse(model_helpers.past_stop_threshold(None, 1.5))\n # Zero should be okay, though.\n self.assertTrue(model_helpers.past_stop_threshold(0, 1.5))\n\n def test_past_stop_threshold_not_number(self):\n \"\"\"Tests for error conditions.\"\"\"\n with self.assertRaises(ValueError):\n model_helpers.past_stop_threshold(\"str\", 1)\n\n with self.assertRaises(ValueError):\n model_helpers.past_stop_threshold(\"str\", tf.constant(5))\n\n with self.assertRaises(ValueError):\n model_helpers.past_stop_threshold(\"str\", \"another\")\n\n with self.assertRaises(ValueError):\n model_helpers.past_stop_threshold(0, None)\n\n with self.assertRaises(ValueError):\n model_helpers.past_stop_threshold(0.7, \"str\")\n\n with self.assertRaises(ValueError):\n model_helpers.past_stop_threshold(tf.constant(4), None)\n\n\nclass SyntheticDataTest(tf.test.TestCase):\n \"\"\"Tests for generate_synthetic_data.\"\"\"\n\n def test_generate_synethetic_data(self):\n input_element, label_element = model_helpers.generate_synthetic_data(\n input_shape=tf.TensorShape([5]),\n input_value=123,\n input_dtype=tf.float32,\n label_shape=tf.TensorShape([]),\n label_value=456,\n label_dtype=tf.int32).make_one_shot_iterator().get_next()\n\n with self.test_session() as sess:\n for n in range(5):\n inp, lab = sess.run((input_element, label_element))\n self.assertAllClose(inp, [123., 123., 123., 123., 123.])\n self.assertEquals(lab, 456)\n\n def test_generate_only_input_data(self):\n d = model_helpers.generate_synthetic_data(\n input_shape=tf.TensorShape([4]),\n input_value=43.5,\n input_dtype=tf.float32)\n\n element = d.make_one_shot_iterator().get_next()\n self.assertFalse(isinstance(element, tuple))\n\n with self.test_session() as sess:\n inp = sess.run(element)\n self.assertAllClose(inp, [43.5, 43.5, 43.5, 43.5])\n\n def test_generate_nested_data(self):\n d = model_helpers.generate_synthetic_data(\n input_shape={'a': tf.TensorShape([2]),\n 'b': {'c': tf.TensorShape([3]), 'd': tf.TensorShape([])}},\n input_value=1.1)\n\n element = d.make_one_shot_iterator().get_next()\n self.assertIn('a', element)\n self.assertIn('b', element)\n self.assertEquals(len(element['b']), 2)\n self.assertIn('c', element['b'])\n self.assertIn('d', element['b'])\n self.assertNotIn('c', element)\n\n with self.test_session() as sess:\n inp = sess.run(element)\n self.assertAllClose(inp['a'], [1.1, 1.1])\n self.assertAllClose(inp['b']['c'], [1.1, 1.1, 1.1])\n self.assertAllClose(inp['b']['d'], 1.1)\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\"\"\"Tests for box_predictor_builder.\"\"\"\n\nimport mock\nimport tensorflow as tf\n\nfrom google.protobuf import text_format\nfrom object_detection.builders import box_predictor_builder\nfrom object_detection.builders import hyperparams_builder\nfrom object_detection.predictors import mask_rcnn_box_predictor\nfrom object_detection.protos import box_predictor_pb2\nfrom object_detection.protos import hyperparams_pb2\n\n\nclass ConvolutionalBoxPredictorBuilderTest(tf.test.TestCase):\n\n def test_box_predictor_calls_conv_argscope_fn(self):\n conv_hyperparams_text_proto = \"\"\"\n regularizer {\n l1_regularizer {\n weight: 0.0003\n }\n }\n initializer {\n truncated_normal_initializer {\n mean: 0.0\n stddev: 0.3\n }\n }\n activation: RELU_6\n \"\"\"\n hyperparams_proto = hyperparams_pb2.Hyperparams()\n text_format.Merge(conv_hyperparams_text_proto, hyperparams_proto)\n def mock_conv_argscope_builder(conv_hyperparams_arg, is_training):\n return (conv_hyperparams_arg, is_training)\n\n box_predictor_proto = box_predictor_pb2.BoxPredictor()\n box_predictor_proto.convolutional_box_predictor.conv_hyperparams.CopyFrom(\n hyperparams_proto)\n box_predictor = box_predictor_builder.build(\n argscope_fn=mock_conv_argscope_builder,\n box_predictor_config=box_predictor_proto,\n is_training=False,\n num_classes=10)\n (conv_hyperparams_actual, is_training) = box_predictor._conv_hyperparams_fn\n self.assertAlmostEqual((hyperparams_proto.regularizer.\n l1_regularizer.weight),\n (conv_hyperparams_actual.regularizer.l1_regularizer.\n weight))\n self.assertAlmostEqual((hyperparams_proto.initializer.\n truncated_normal_initializer.stddev),\n (conv_hyperparams_actual.initializer.\n truncated_normal_initializer.stddev))\n self.assertAlmostEqual((hyperparams_proto.initializer.\n truncated_normal_initializer.mean),\n (conv_hyperparams_actual.initializer.\n truncated_normal_initializer.mean))\n self.assertEqual(hyperparams_proto.activation,\n conv_hyperparams_actual.activation)\n self.assertFalse(is_training)\n\n def test_construct_non_default_conv_box_predictor(self):\n box_predictor_text_proto = \"\"\"\n convolutional_box_predictor {\n min_depth: 2\n max_depth: 16\n num_layers_before_predictor: 2\n use_dropout: false\n dropout_keep_probability: 0.4\n kernel_size: 3\n box_code_size: 3\n apply_sigmoid_to_scores: true\n class_prediction_bias_init: 4.0\n use_depthwise: true\n }\n \"\"\"\n conv_hyperparams_text_proto = \"\"\"\n regularizer {\n l1_regularizer {\n }\n }\n initializer {\n truncated_normal_initializer {\n }\n }\n \"\"\"\n hyperparams_proto = hyperparams_pb2.Hyperparams()\n text_format.Merge(conv_hyperparams_text_proto, hyperparams_proto)\n def mock_conv_argscope_builder(conv_hyperparams_arg, is_training):\n return (conv_hyperparams_arg, is_training)\n\n box_predictor_proto = box_predictor_pb2.BoxPredictor()\n text_format.Merge(box_predictor_text_proto, box_predictor_proto)\n box_predictor_proto.convolutional_box_predictor.conv_hyperparams.CopyFrom(\n hyperparams_proto)\n box_predictor = box_predictor_builder.build(\n argscope_fn=mock_conv_argscope_builder,\n box_predictor_config=box_predictor_proto,\n is_training=False,\n num_classes=10,\n add_background_class=False)\n class_head = box_predictor._class_prediction_head\n self.assertEqual(box_predictor._min_depth, 2)\n self.assertEqual(box_predictor._max_depth, 16)\n self.assertEqual(box_predictor._num_layers_before_predictor, 2)\n self.assertFalse(class_head._use_dropout)\n self.assertAlmostEqual(class_head._dropout_keep_prob, 0.4)\n self.assertTrue(class_head._apply_sigmoid_to_scores)\n self.assertAlmostEqual(class_head._class_prediction_bias_init, 4.0)\n self.assertEqual(class_head._num_class_slots, 10)\n self.assertEqual(box_predictor.num_classes, 10)\n self.assertFalse(box_predictor._is_training)\n self.assertTrue(class_head._use_depthwise)\n\n def test_construct_default_conv_box_predictor(self):\n box_predictor_text_proto = \"\"\"\n convolutional_box_predictor {\n conv_hyperparams {\n regularizer {\n l1_regularizer {\n }\n }\n initializer {\n truncated_normal_initializer {\n }\n }\n }\n }\"\"\"\n box_predictor_proto = box_predictor_pb2.BoxPredictor()\n text_format.Merge(box_predictor_text_proto, box_predictor_proto)\n box_predictor = box_predictor_builder.build(\n argscope_fn=hyperparams_builder.build,\n box_predictor_config=box_predictor_proto,\n is_training=True,\n num_classes=90)\n class_head = box_predictor._class_prediction_head\n self.assertEqual(box_predictor._min_depth, 0)\n self.assertEqual(box_predictor._max_depth, 0)\n self.assertEqual(box_predictor._num_layers_before_predictor, 0)\n self.assertTrue(class_head._use_dropout)\n self.assertAlmostEqual(class_head._dropout_keep_prob, 0.8)\n self.assertFalse(class_head._apply_sigmoid_to_scores)\n self.assertEqual(class_head._num_class_slots, 91)\n self.assertEqual(box_predictor.num_classes, 90)\n self.assertTrue(box_predictor._is_training)\n self.assertFalse(class_head._use_depthwise)\n\n\nclass WeightSharedConvolutionalBoxPredictorBuilderTest(tf.test.TestCase):\n\n def test_box_predictor_calls_conv_argscope_fn(self):\n conv_hyperparams_text_proto = \"\"\"\n regularizer {\n l1_regularizer {\n weight: 0.0003\n }\n }\n initializer {\n truncated_normal_initializer {\n mean: 0.0\n stddev: 0.3\n }\n }\n activation: RELU_6\n \"\"\"\n hyperparams_proto = hyperparams_pb2.Hyperparams()\n text_format.Merge(conv_hyperparams_text_proto, hyperparams_proto)\n def mock_conv_argscope_builder(conv_hyperparams_arg, is_training):\n return (conv_hyperparams_arg, is_training)\n\n box_predictor_proto = box_predictor_pb2.BoxPredictor()\n (box_predictor_proto.weight_shared_convolutional_box_predictor\n .conv_hyperparams.CopyFrom(hyperparams_proto))\n box_predictor = box_predictor_builder.build(\n argscope_fn=mock_conv_argscope_builder,\n box_predictor_config=box_predictor_proto,\n is_training=False,\n num_classes=10)\n (conv_hyperparams_actual, is_training) = box_predictor._conv_hyperparams_fn\n self.assertAlmostEqual((hyperparams_proto.regularizer.\n l1_regularizer.weight),\n (conv_hyperparams_actual.regularizer.l1_regularizer.\n weight))\n self.assertAlmostEqual((hyperparams_proto.initializer.\n truncated_normal_initializer.stddev),\n (conv_hyperparams_actual.initializer.\n truncated_normal_initializer.stddev))\n self.assertAlmostEqual((hyperparams_proto.initializer.\n truncated_normal_initializer.mean),\n (conv_hyperparams_actual.initializer.\n truncated_normal_initializer.mean))\n self.assertEqual(hyperparams_proto.activation,\n conv_hyperparams_actual.activation)\n self.assertFalse(is_training)\n\n def test_construct_non_default_conv_box_predictor(self):\n box_predictor_text_proto = \"\"\"\n weight_shared_convolutional_box_predictor {\n depth: 2\n num_layers_before_predictor: 2\n kernel_size: 7\n box_code_size: 3\n class_prediction_bias_init: 4.0\n }\n \"\"\"\n conv_hyperparams_text_proto = \"\"\"\n regularizer {\n l1_regularizer {\n }\n }\n initializer {\n truncated_normal_initializer {\n }\n }\n \"\"\"\n hyperparams_proto = hyperparams_pb2.Hyperparams()\n text_format.Merge(conv_hyperparams_text_proto, hyperparams_proto)\n def mock_conv_argscope_builder(conv_hyperparams_arg, is_training):\n return (conv_hyperparams_arg, is_training)\n\n box_predictor_proto = box_predictor_pb2.BoxPredictor()\n text_format.Merge(box_predictor_text_proto, box_predictor_proto)\n (box_predictor_proto.weight_shared_convolutional_box_predictor.\n conv_hyperparams.CopyFrom(hyperparams_proto))\n box_predictor = box_predictor_builder.build(\n argscope_fn=mock_conv_argscope_builder,\n box_predictor_config=box_predictor_proto,\n is_training=False,\n num_classes=10,\n add_background_class=False)\n class_head = box_predictor._class_prediction_head\n self.assertEqual(box_predictor._depth, 2)\n self.assertEqual(box_predictor._num_layers_before_predictor, 2)\n self.assertAlmostEqual(class_head._class_prediction_bias_init, 4.0)\n self.assertEqual(box_predictor.num_classes, 10)\n self.assertFalse(box_predictor._is_training)\n self.assertEqual(box_predictor._apply_batch_norm, False)\n\n def test_construct_non_default_depthwise_conv_box_predictor(self):\n box_predictor_text_proto = \"\"\"\n weight_shared_convolutional_box_predictor {\n depth: 2\n num_layers_before_predictor: 2\n kernel_size: 7\n box_code_size: 3\n class_prediction_bias_init: 4.0\n use_depthwise: true\n }\n \"\"\"\n conv_hyperparams_text_proto = \"\"\"\n regularizer {\n l1_regularizer {\n }\n }\n initializer {\n truncated_normal_initializer {\n }\n }\n \"\"\"\n hyperparams_proto = hyperparams_pb2.Hyperparams()\n text_format.Merge(conv_hyperparams_text_proto, hyperparams_proto)\n def mock_conv_argscope_builder(conv_hyperparams_arg, is_training):\n return (conv_hyperparams_arg, is_training)\n\n box_predictor_proto = box_predictor_pb2.BoxPredictor()\n text_format.Merge(box_predictor_text_proto, box_predictor_proto)\n (box_predictor_proto.weight_shared_convolutional_box_predictor.\n conv_hyperparams.CopyFrom(hyperparams_proto))\n box_predictor = box_predictor_builder.build(\n argscope_fn=mock_conv_argscope_builder,\n box_predictor_config=box_predictor_proto,\n is_training=False,\n num_classes=10,\n add_background_class=False)\n class_head = box_predictor._class_prediction_head\n self.assertEqual(box_predictor._depth, 2)\n self.assertEqual(box_predictor._num_layers_before_predictor, 2)\n self.assertEqual(box_predictor._apply_batch_norm, False)\n self.assertEqual(box_predictor._use_depthwise, True)\n self.assertAlmostEqual(class_head._class_prediction_bias_init, 4.0)\n self.assertEqual(box_predictor.num_classes, 10)\n self.assertFalse(box_predictor._is_training)\n\n def test_construct_default_conv_box_predictor(self):\n box_predictor_text_proto = \"\"\"\n weight_shared_convolutional_box_predictor {\n conv_hyperparams {\n regularizer {\n l1_regularizer {\n }\n }\n initializer {\n truncated_normal_initializer {\n }\n }\n }\n }\"\"\"\n box_predictor_proto = box_predictor_pb2.BoxPredictor()\n text_format.Merge(box_predictor_text_proto, box_predictor_proto)\n box_predictor = box_predictor_builder.build(\n argscope_fn=hyperparams_builder.build,\n box_predictor_config=box_predictor_proto,\n is_training=True,\n num_classes=90)\n self.assertEqual(box_predictor._depth, 0)\n self.assertEqual(box_predictor._num_layers_before_predictor, 0)\n self.assertEqual(box_predictor.num_classes, 90)\n self.assertTrue(box_predictor._is_training)\n self.assertEqual(box_predictor._apply_batch_norm, False)\n\n def test_construct_default_conv_box_predictor_with_batch_norm(self):\n box_predictor_text_proto = \"\"\"\n weight_shared_convolutional_box_predictor {\n conv_hyperparams {\n regularizer {\n l1_regularizer {\n }\n }\n batch_norm {\n train: true\n }\n initializer {\n truncated_normal_initializer {\n }\n }\n }\n }\"\"\"\n box_predictor_proto = box_predictor_pb2.BoxPredictor()\n text_format.Merge(box_predictor_text_proto, box_predictor_proto)\n box_predictor = box_predictor_builder.build(\n argscope_fn=hyperparams_builder.build,\n box_predictor_config=box_predictor_proto,\n is_training=True,\n num_classes=90)\n self.assertEqual(box_predictor._depth, 0)\n self.assertEqual(box_predictor._num_layers_before_predictor, 0)\n self.assertEqual(box_predictor.num_classes, 90)\n self.assertTrue(box_predictor._is_training)\n self.assertEqual(box_predictor._apply_batch_norm, True)\n\n\nclass MaskRCNNBoxPredictorBuilderTest(tf.test.TestCase):\n\n def test_box_predictor_builder_calls_fc_argscope_fn(self):\n fc_hyperparams_text_proto = \"\"\"\n regularizer {\n l1_regularizer {\n weight: 0.0003\n }\n }\n initializer {\n truncated_normal_initializer {\n mean: 0.0\n stddev: 0.3\n }\n }\n activation: RELU_6\n op: FC\n \"\"\"\n hyperparams_proto = hyperparams_pb2.Hyperparams()\n text_format.Merge(fc_hyperparams_text_proto, hyperparams_proto)\n box_predictor_proto = box_predictor_pb2.BoxPredictor()\n box_predictor_proto.mask_rcnn_box_predictor.fc_hyperparams.CopyFrom(\n hyperparams_proto)\n mock_argscope_fn = mock.Mock(return_value='arg_scope')\n box_predictor = box_predictor_builder.build(\n argscope_fn=mock_argscope_fn,\n box_predictor_config=box_predictor_proto,\n is_training=False,\n num_classes=10)\n mock_argscope_fn.assert_called_with(hyperparams_proto, False)\n self.assertEqual(box_predictor._box_prediction_head._fc_hyperparams_fn,\n 'arg_scope')\n self.assertEqual(box_predictor._class_prediction_head._fc_hyperparams_fn,\n 'arg_scope')\n\n def test_non_default_mask_rcnn_box_predictor(self):\n fc_hyperparams_text_proto = \"\"\"\n regularizer {\n l1_regularizer {\n }\n }\n initializer {\n truncated_normal_initializer {\n }\n }\n activation: RELU_6\n op: FC\n \"\"\"\n box_predictor_text_proto = \"\"\"\n mask_rcnn_box_predictor {\n use_dropout: true\n dropout_keep_probability: 0.8\n box_code_size: 3\n share_box_across_classes: true\n }\n \"\"\"\n hyperparams_proto = hyperparams_pb2.Hyperparams()\n text_format.Merge(fc_hyperparams_text_proto, hyperparams_proto)\n def mock_fc_argscope_builder(fc_hyperparams_arg, is_training):\n return (fc_hyperparams_arg, is_training)\n\n box_predictor_proto = box_predictor_pb2.BoxPredictor()\n text_format.Merge(box_predictor_text_proto, box_predictor_proto)\n box_predictor_proto.mask_rcnn_box_predictor.fc_hyperparams.CopyFrom(\n hyperparams_proto)\n box_predictor = box_predictor_builder.build(\n argscope_fn=mock_fc_argscope_builder,\n box_predictor_config=box_predictor_proto,\n is_training=True,\n num_classes=90)\n box_head = box_predictor._box_prediction_head\n class_head = box_predictor._class_prediction_head\n self.assertTrue(box_head._use_dropout)\n self.assertTrue(class_head._use_dropout)\n self.assertAlmostEqual(box_head._dropout_keep_prob, 0.8)\n self.assertAlmostEqual(class_head._dropout_keep_prob, 0.8)\n self.assertEqual(box_predictor.num_classes, 90)\n self.assertTrue(box_predictor._is_training)\n self.assertEqual(box_head._box_code_size, 3)\n self.assertEqual(box_head._share_box_across_classes, True)\n\n def test_build_default_mask_rcnn_box_predictor(self):\n box_predictor_proto = box_predictor_pb2.BoxPredictor()\n box_predictor_proto.mask_rcnn_box_predictor.fc_hyperparams.op = (\n hyperparams_pb2.Hyperparams.FC)\n box_predictor = box_predictor_builder.build(\n argscope_fn=mock.Mock(return_value='arg_scope'),\n box_predictor_config=box_predictor_proto,\n is_training=True,\n num_classes=90)\n box_head = box_predictor._box_prediction_head\n class_head = box_predictor._class_prediction_head\n self.assertFalse(box_head._use_dropout)\n self.assertFalse(class_head._use_dropout)\n self.assertAlmostEqual(box_head._dropout_keep_prob, 0.5)\n self.assertEqual(box_predictor.num_classes, 90)\n self.assertTrue(box_predictor._is_training)\n self.assertEqual(box_head._box_code_size, 4)\n self.assertEqual(len(box_predictor._third_stage_heads.keys()), 0)\n\n def test_build_box_predictor_with_mask_branch(self):\n box_predictor_proto = box_predictor_pb2.BoxPredictor()\n box_predictor_proto.mask_rcnn_box_predictor.fc_hyperparams.op = (\n hyperparams_pb2.Hyperparams.FC)\n box_predictor_proto.mask_rcnn_box_predictor.conv_hyperparams.op = (\n hyperparams_pb2.Hyperparams.CONV)\n box_predictor_proto.mask_rcnn_box_predictor.predict_instance_masks = True\n box_predictor_proto.mask_rcnn_box_predictor.mask_prediction_conv_depth = 512\n box_predictor_proto.mask_rcnn_box_predictor.mask_height = 16\n box_predictor_proto.mask_rcnn_box_predictor.mask_width = 16\n mock_argscope_fn = mock.Mock(return_value='arg_scope')\n box_predictor = box_predictor_builder.build(\n argscope_fn=mock_argscope_fn,\n box_predictor_config=box_predictor_proto,\n is_training=True,\n num_classes=90)\n mock_argscope_fn.assert_has_calls(\n [mock.call(box_predictor_proto.mask_rcnn_box_predictor.fc_hyperparams,\n True),\n mock.call(box_predictor_proto.mask_rcnn_box_predictor.conv_hyperparams,\n True)], any_order=True)\n box_head = box_predictor._box_prediction_head\n class_head = box_predictor._class_prediction_head\n third_stage_heads = box_predictor._third_stage_heads\n self.assertFalse(box_head._use_dropout)\n self.assertFalse(class_head._use_dropout)\n self.assertAlmostEqual(box_head._dropout_keep_prob, 0.5)\n self.assertAlmostEqual(class_head._dropout_keep_prob, 0.5)\n self.assertEqual(box_predictor.num_classes, 90)\n self.assertTrue(box_predictor._is_training)\n self.assertEqual(box_head._box_code_size, 4)\n self.assertTrue(\n mask_rcnn_box_predictor.MASK_PREDICTIONS in third_stage_heads)\n self.assertEqual(\n third_stage_heads[mask_rcnn_box_predictor.MASK_PREDICTIONS]\n ._mask_prediction_conv_depth, 512)\n\n def test_build_box_predictor_with_convlve_then_upsample_masks(self):\n box_predictor_proto = box_predictor_pb2.BoxPredictor()\n box_predictor_proto.mask_rcnn_box_predictor.fc_hyperparams.op = (\n hyperparams_pb2.Hyperparams.FC)\n box_predictor_proto.mask_rcnn_box_predictor.conv_hyperparams.op = (\n hyperparams_pb2.Hyperparams.CONV)\n box_predictor_proto.mask_rcnn_box_predictor.predict_instance_masks = True\n box_predictor_proto.mask_rcnn_box_predictor.mask_prediction_conv_depth = 512\n box_predictor_proto.mask_rcnn_box_predictor.mask_height = 24\n box_predictor_proto.mask_rcnn_box_predictor.mask_width = 24\n box_predictor_proto.mask_rcnn_box_predictor.convolve_then_upsample_masks = (\n True)\n\n mock_argscope_fn = mock.Mock(return_value='arg_scope')\n box_predictor = box_predictor_builder.build(\n argscope_fn=mock_argscope_fn,\n box_predictor_config=box_predictor_proto,\n is_training=True,\n num_classes=90)\n mock_argscope_fn.assert_has_calls(\n [mock.call(box_predictor_proto.mask_rcnn_box_predictor.fc_hyperparams,\n True),\n mock.call(box_predictor_proto.mask_rcnn_box_predictor.conv_hyperparams,\n True)], any_order=True)\n box_head = box_predictor._box_prediction_head\n class_head = box_predictor._class_prediction_head\n third_stage_heads = box_predictor._third_stage_heads\n self.assertFalse(box_head._use_dropout)\n self.assertFalse(class_head._use_dropout)\n self.assertAlmostEqual(box_head._dropout_keep_prob, 0.5)\n self.assertAlmostEqual(class_head._dropout_keep_prob, 0.5)\n self.assertEqual(box_predictor.num_classes, 90)\n self.assertTrue(box_predictor._is_training)\n self.assertEqual(box_head._box_code_size, 4)\n self.assertTrue(\n mask_rcnn_box_predictor.MASK_PREDICTIONS in third_stage_heads)\n self.assertEqual(\n third_stage_heads[mask_rcnn_box_predictor.MASK_PREDICTIONS]\n ._mask_prediction_conv_depth, 512)\n self.assertTrue(third_stage_heads[mask_rcnn_box_predictor.MASK_PREDICTIONS]\n ._convolve_then_upsample)\n\n\nclass RfcnBoxPredictorBuilderTest(tf.test.TestCase):\n\n def test_box_predictor_calls_fc_argscope_fn(self):\n conv_hyperparams_text_proto = \"\"\"\n regularizer {\n l1_regularizer {\n weight: 0.0003\n }\n }\n initializer {\n truncated_normal_initializer {\n mean: 0.0\n stddev: 0.3\n }\n }\n activation: RELU_6\n \"\"\"\n hyperparams_proto = hyperparams_pb2.Hyperparams()\n text_format.Merge(conv_hyperparams_text_proto, hyperparams_proto)\n def mock_conv_argscope_builder(conv_hyperparams_arg, is_training):\n return (conv_hyperparams_arg, is_training)\n\n box_predictor_proto = box_predictor_pb2.BoxPredictor()\n box_predictor_proto.rfcn_box_predictor.conv_hyperparams.CopyFrom(\n hyperparams_proto)\n box_predictor = box_predictor_builder.build(\n argscope_fn=mock_conv_argscope_builder,\n box_predictor_config=box_predictor_proto,\n is_training=False,\n num_classes=10)\n (conv_hyperparams_actual, is_training) = box_predictor._conv_hyperparams_fn\n self.assertAlmostEqual((hyperparams_proto.regularizer.\n l1_regularizer.weight),\n (conv_hyperparams_actual.regularizer.l1_regularizer.\n weight))\n self.assertAlmostEqual((hyperparams_proto.initializer.\n truncated_normal_initializer.stddev),\n (conv_hyperparams_actual.initializer.\n truncated_normal_initializer.stddev))\n self.assertAlmostEqual((hyperparams_proto.initializer.\n truncated_normal_initializer.mean),\n (conv_hyperparams_actual.initializer.\n truncated_normal_initializer.mean))\n self.assertEqual(hyperparams_proto.activation,\n conv_hyperparams_actual.activation)\n self.assertFalse(is_training)\n\n def test_non_default_rfcn_box_predictor(self):\n conv_hyperparams_text_proto = \"\"\"\n regularizer {\n l1_regularizer {\n }\n }\n initializer {\n truncated_normal_initializer {\n }\n }\n activation: RELU_6\n \"\"\"\n box_predictor_text_proto = \"\"\"\n rfcn_box_predictor {\n num_spatial_bins_height: 4\n num_spatial_bins_width: 4\n depth: 4\n box_code_size: 3\n crop_height: 16\n crop_width: 16\n }\n \"\"\"\n hyperparams_proto = hyperparams_pb2.Hyperparams()\n text_format.Merge(conv_hyperparams_text_proto, hyperparams_proto)\n def mock_conv_argscope_builder(conv_hyperparams_arg, is_training):\n return (conv_hyperparams_arg, is_training)\n\n box_predictor_proto = box_predictor_pb2.BoxPredictor()\n text_format.Merge(box_predictor_text_proto, box_predictor_proto)\n box_predictor_proto.rfcn_box_predictor.conv_hyperparams.CopyFrom(\n hyperparams_proto)\n box_predictor = box_predictor_builder.build(\n argscope_fn=mock_conv_argscope_builder,\n box_predictor_config=box_predictor_proto,\n is_training=True,\n num_classes=90)\n self.assertEqual(box_predictor.num_classes, 90)\n self.assertTrue(box_predictor._is_training)\n self.assertEqual(box_predictor._box_code_size, 3)\n self.assertEqual(box_predictor._num_spatial_bins, [4, 4])\n self.assertEqual(box_predictor._crop_size, [16, 16])\n\n def test_default_rfcn_box_predictor(self):\n conv_hyperparams_text_proto = \"\"\"\n regularizer {\n l1_regularizer {\n }\n }\n initializer {\n truncated_normal_initializer {\n }\n }\n activation: RELU_6\n \"\"\"\n hyperparams_proto = hyperparams_pb2.Hyperparams()\n text_format.Merge(conv_hyperparams_text_proto, hyperparams_proto)\n def mock_conv_argscope_builder(conv_hyperparams_arg, is_training):\n return (conv_hyperparams_arg, is_training)\n\n box_predictor_proto = box_predictor_pb2.BoxPredictor()\n box_predictor_proto.rfcn_box_predictor.conv_hyperparams.CopyFrom(\n hyperparams_proto)\n box_predictor = box_predictor_builder.build(\n argscope_fn=mock_conv_argscope_builder,\n box_predictor_config=box_predictor_proto,\n is_training=True,\n num_classes=90)\n self.assertEqual(box_predictor.num_classes, 90)\n self.assertTrue(box_predictor._is_training)\n self.assertEqual(box_predictor._box_code_size, 4)\n self.assertEqual(box_predictor._num_spatial_bins, [3, 3])\n self.assertEqual(box_predictor._crop_size, [12, 12])\n\n\nif __name__ == '__main__':\n tf.test.main()\n"
] | [
[
"numpy.squeeze",
"numpy.mean",
"tensorflow.get_default_graph",
"tensorflow.to_int32",
"tensorflow.to_int64",
"tensorflow.greater",
"tensorflow.squeeze",
"tensorflow.train.get_global_step",
"tensorflow.train.Saver",
"tensorflow.train.write_graph",
"tensorflow.shape",
"tensorflow.image.resize_images",
"tensorflow.global_variables_initializer",
"tensorflow.logging.info",
"tensorflow.contrib.slim.queues.QueueRunners",
"tensorflow.local_variables_initializer",
"tensorflow.train.latest_checkpoint",
"numpy.int32",
"tensorflow.ones_like",
"tensorflow.expand_dims",
"numpy.tile",
"tensorflow.Summary.Value",
"tensorflow.tables_initializer",
"tensorflow.summary.FileWriterCache.get"
],
[
"numpy.expand_dims",
"numpy.unique",
"numpy.tile",
"tensorflow.placeholder",
"tensorflow.test.main",
"numpy.array",
"tensorflow.random_uniform"
],
[
"tensorflow.variable_scope"
],
[
"tensorflow.zeros_like",
"tensorflow.expand_dims",
"tensorflow.shape",
"tensorflow.name_scope"
],
[
"tensorflow.device",
"tensorflow.enable_eager_execution",
"tensorflow.train.latest_checkpoint",
"tensorflow.contrib.summary.create_file_writer",
"tensorflow.train.Checkpoint",
"tensorflow.cast",
"tensorflow.contrib.summary.record_summaries_every_n_global_steps",
"tensorflow.equal",
"tensorflow.train.get_or_create_global_step",
"tensorflow.train.MomentumOptimizer",
"tensorflow.nn.sparse_softmax_cross_entropy_with_logits",
"tensorflow.contrib.summary.always_record_summaries",
"tensorflow.gfile.MakeDirs",
"tensorflow.contrib.summary.scalar",
"tensorflow.test.is_gpu_available",
"tensorflow.argmax",
"tensorflow.GradientTape"
],
[
"tensorflow.TensorShape",
"tensorflow.constant",
"tensorflow.test.main"
],
[
"tensorflow.test.main"
]
] | [
{
"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",
"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.13",
"1.10",
"1.12"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
DrAuxin/WestpaTools | [
"4e236e0a3d65504d1937260316a4a5c6f39aa610",
"4e236e0a3d65504d1937260316a4a5c6f39aa610"
] | [
"wtools/plotting.py",
"wtools/extrema.py"
] | [
"import h5py\nimport numpy\nimport matplotlib.pyplot as plt\n\ndef plotflux(h5file, state=1):\n \"\"\"\n A function that plots the dataset target_flux_evolution from a direct.h5 file.\n\n Parameters\n ----------\n h5file: dictionary\n The user's HDF5 file loaded with loadh5.\n state: integer\n The target state; the state for which you want to know the entering flux for.\n\n Returns\n -------\n Nothing\n The plot of the flux evolution will be shown in a separate window.\n\n Examples\n --------\n >>> h5file = loadh5(\"west.h5\")\n >>> plotflux(h5file, 1)\n --------\n | __/ |\n | / |\n -------- \n \"\"\"\n fluxes = h5file['target_flux_evolution']['expected',:,state-1]\n iterations = numpy.arange(1,len(fluxes)+1,1)\n fig, ax = plt.subplots()\n ax.plot(iterations,fluxes, linewidth=3)\n ax.set_xlabel('WE Iteration', fontsize=24)\n ax.set_ylabel('Mean Flux', fontsize=24)\n ax.ticklabel_format(style='sci', axis='y', scilimits=(0,0))\n ax.tick_params(labelsize=22)\n fig.tight_layout()\n plt.show()\n",
"import numpy\nimport h5py\n\ndef findmax(h5file, pcoord_dim, fi, li):\n \"\"\"\n A function that locates the segment with the maximum pcoord value.\n\n Parameters\n ----------\n h5file: dictionary\n The user's HDF5 file loaded with loadh5.\n pcoord_dim: integer\n The progress coordinate dimension you want to know the max for.\n fi: integer\n The starting iteration for consideration.\n li: integer\n The ending iteration for consideration.\n\n Returns\n -------\n Nothing\n The maximum value and its corresponding iter and seg numbers are printed to the terminal.\n\n Examples\n --------\n >>> h5file = loadh5(\"west.h5\")\n >>> findmax(h5file, 1, 1, 10)\n Maximum pcoord value for dimension 1 is: 22.9468\n It is segment: 78 of iteration: 10 \n \"\"\"\n max_values = []\n for i in range(fi,li+1):\n i = str(i)\n iteration = \"iter_\" + str(numpy.char.zfill(i,8))\n pc = h5file['iterations'][iteration]['pcoord']\n maxv = numpy.max(pc[:,-1,pcoord_dim-1])\n max_values.append(maxv)\n maxmax = numpy.max(max_values)\n nw = numpy.where(max_values>(maxmax-maxmax*0.0001))\n iter_num = str((nw[0]+1)[0])\n \n wheretolook = \"iter_\" + str(numpy.char.zfill(iter_num,8))\n max_iter = h5file['iterations'][wheretolook]['pcoord'][:,-1,pcoord_dim-1]\n segmax = numpy.max(max_iter)\n nw2 = numpy.where(max_iter>(segmax-segmax*0.0001))\n seg_num = (nw2[0]+1)[0]\n print (\"Maximum pcoord value for dimension\",pcoord_dim,\"is:\",segmax) \n print (\"It is segment:\",seg_num,\"of iteration:\",iter_num)\n\ndef findmin(h5file, pcoord_dim, fi, li):\n \"\"\"\n A function that locates the segment with the minimum pcoord value.\n\n Parameters\n ----------\n h5file: dictionary\n The user's HDF5 file loaded with loadh5.\n pcoord_dim: integer\n The progress coordinate dimension you want to know the min for.\n fi: integer\n The starting iteration for consideration.\n li: integer\n The ending iteration for consideration.\n\n Returns\n -------\n Nothing\n The minimum value and its corresponding iter and seg numbers are printed to the terminal.\n\n Examples\n --------\n >>> h5file = loadh5(\"west.h5\")\n >>> findmin(h5file, 1, 1, 10)\n Minimum pcoord value for dimension 1 is: 2.4968\n It is segment: 1 of iteration: 9 \n \"\"\"\n min_values = []\n for i in range(fi,li+1):\n i = str(i)\n iteration = \"iter_\" + str(numpy.char.zfill(i,8))\n pc = h5file['iterations'][iteration]['pcoord']\n minv = numpy.min(pc[:,-1,pcoord_dim-1])\n min_values.append(minv)\n minmin = numpy.min(min_values)\n print(min_values)\n print(minmin)\n nw = numpy.where(min_values<(minmin+minmin*0.0001))\n print(nw)\n iter_num = str((nw[0]+1)[0])\n \n wheretolook = \"iter_\" + str(numpy.char.zfill(iter_num,8))\n min_iter = h5file['iterations'][wheretolook]['pcoord'][:,-1,pcoord_dim-1]\n segmin = numpy.min(min_iter)\n nw2 = numpy.where(min_iter<(segmin+segmin*0.0001))\n seg_num = (nw2[0]+1)[0]\n print (\"Minimum pcoord value for dimension\",pcoord_dim,\"is:\",segmin) \n print (\"It is segment:\",seg_num,\"of iteration:\",iter_num)\n"
] | [
[
"matplotlib.pyplot.show",
"matplotlib.pyplot.subplots"
],
[
"numpy.max",
"numpy.where",
"numpy.char.zfill",
"numpy.min"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
anonips/-MDP-Playground | [
"74431f98c210830a93a1bc83fcdcb95bf1644696",
"74431f98c210830a93a1bc83fcdcb95bf1644696"
] | [
"experiments/custom_agents_opt.py",
"experiments/custom_agents_rainbow_noises.py"
] | [
"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom ray.rllib.agents.trainer import Trainer, with_common_config\nfrom ray.rllib.utils.annotations import override\n\n# yapf: disable\n# __sphinx_doc_begin__\nclass RandomAgent(Trainer):\n \"\"\"Policy that takes random actions and never learns.\"\"\"\n\n _name = \"RandomAgent\"\n _default_config = with_common_config({\n \"rollouts_per_iteration\": 10,\n })\n\n @override(Trainer)\n def _init(self, config, env_creator):\n self.env = env_creator(config[\"env_config\"])\n\n @override(Trainer)\n def _train(self):\n rewards = []\n steps = 0\n for _ in range(self.config[\"rollouts_per_iteration\"]):\n obs = self.env.reset()\n done = False\n reward = 0.0\n while not done:\n action = self.env.action_space.sample()\n obs, r, done, info = self.env.step(action)\n\n reward += r\n steps += 1\n rewards.append(reward)\n return {\n \"episode_reward_mean\": np.mean(rewards),\n \"timesteps_this_iter\": steps,\n }\n\nclass VIAgent(Trainer):\n \"\"\"Value Iteration.\n #TODO Make it Generalized PI.\n \"\"\"\n\n _name = \"VIAgent\"\n _default_config = with_common_config({\n \"tolerance\": 0.01,\n \"discount_factor\": 0.5,\n \"rollouts_per_iteration\": 10,\n \"episode_length\": 200,\n # \"lr\": 0.5\n })\n\n @override(Trainer)\n def _init(self, config, env_creator):\n self.env = env_creator(config[\"env_config\"])\n self.V = np.zeros(self.env.observation_space.n)\n self.policy = np.zeros(self.env.observation_space.n, dtype=int)\n self.policy[:] = -1 #IMP # To avoid initing it to a value within action_space range\n\n @override(Trainer)\n def _train(self):\n max_diff = np.inf # Maybe keep a state variable so that we don't need to update every train iteration??\n state_space_size = self.env.observation_space.n\n gamma = self.config[\"discount_factor\"]\n total_iterations = 0\n while max_diff > self.config[\"tolerance\"]:\n total_iterations += 1\n for s in range(state_space_size):\n # print(\"self.V[:]\", s, max_diff, self.V, [self.env.R(s, a) for a in range(self.env.action_space.n)], self.policy[s])\n self.V_old = self.V.copy() # Is this asynchronous? V_old should be held constant for all states in the for loop?\n # print([self.env.R(s, a) for a in range(self.env.action_space.n)], [gamma * self.V[self.env.P(s, a)] for a in range(self.env.action_space.n)], [self.env.R(s, a) + gamma * self.V[self.env.P(s, a)] for a in range(self.env.action_space.n)])\n self.policy[s] = np.argmax([self.env.R(s, a) + gamma * self.V[self.env.P(s, a)] for a in range(self.env.action_space.n)])\n self.V[s] = np.max([self.env.R(s, a) + gamma * self.V[self.env.P(s, a)] for a in range(self.env.action_space.n)]) # We want R to be a callable function, so I guess we have to keep a for loop here??\n # print(\"self.V, self.V_old, self.policy[s]\", self.V, self.V_old, self.policy[s], self.env.P(s, self.policy[s]))\n\n max_diff = np.max(np.absolute(self.V_old - self.V))\n # import time\n # time.sleep(2)\n# for s in range(state_space_size):\n# print(\"FINAL self.V[:]\", s, max_diff, self.V[:], [self.env.R(s, a) for a in range(self.env.action_space.n)])\n\n print(\"Total iterations:\", total_iterations)\n rewards = []\n steps = 0\n for _ in range(self.config[\"rollouts_per_iteration\"]):\n obs = self.env.reset()\n done = False\n reward = 0.0\n for _ in range(self.config[\"episode_length\"]):\n action = self.policy[obs]\n obs, r, done, info = self.env.step(action)\n\n reward += r\n steps += 1\n rewards.append(reward)\n return {\n \"episode_reward_mean\": np.mean(rewards),\n \"timesteps_this_iter\": steps,\n }\n\n\n\n\nimport ray\nfrom ray import tune\nfrom ray.rllib.utils.seed import seed as rllib_seed\nimport rl_toy\nfrom rl_toy.envs import RLToyEnv\nfrom ray.tune.registry import register_env\nregister_env(\"RLToy-v0\", lambda config: RLToyEnv(config))\n\n\n\nfrom ray.rllib.models.preprocessors import OneHotPreprocessor\nfrom ray.rllib.models import ModelCatalog\nModelCatalog.register_custom_preprocessor(\"ohe\", OneHotPreprocessor)\n\n\n\n#rllib_seed(0, 0, 0) ####IMP Doesn't work due to multi-process I think; so use config[\"seed\"]\nray.init()\n\n\n# Old config space\n# algorithms = [\"DQN\"]\n# state_space_sizes = [2**i for i in range(4,6)]\n# action_space_sizes = [2**i for i in range(1,6)]\n# delays = [0] + [2**i for i in range(5)]\n# sequence_lengths = [i for i in range(1,6)]\n# reward_densities = [0.25] # np.linspace(0.0, 1.0, num=5)\n# # make_reward_dense = [True, False]\n# terminal_state_densities = [0.25] # np.linspace(0.1, 1.0, num=5)\n\n\n#test basic case\n# algorithms = [\"DQN\"]\n# state_space_sizes = [10]\n# action_space_sizes = [10]\n# delays = [4]\n# sequence_lengths = [2]\n# reward_densities = [0.25] # np.linspace(0.0, 1.0, num=5)\n# # make_reward_dense = [True, False]\n# terminal_state_densities = [0.25] # np.linspace(0.1, 1.0, num=5)\n\nstate_space_sizes = [8]#, 10, 12, 14] # [2**i for i in range(1,6)]\naction_space_sizes = [8]#2, 4, 8, 16] # [2**i for i in range(1,6)]\ndelays = [0] # + [2**i for i in range(4)]\nsequence_lengths = [1]#, 2]#i for i in range(1,4)]\nreward_densities = [0.25] # np.linspace(0.0, 1.0, num=5)\n# make_reward_dense = [True, False]\nterminal_state_densities = [0.25] # np.linspace(0.1, 1.0, num=5)\nalgorithms = [\"DQN\"]\n#seeds = []\n# Others, keep the rest fixed for these: learning_starts, target_network_update_freq, double_dqn, fcnet_hiddens, fcnet_activation, use_lstm, lstm_seq_len, sample_batch_size/train_batch_size\n# More others: adam_epsilon, exploration_final_eps/exploration_fraction, buffer_size\nnum_layerss = [1, 2, 3, 4]\nlayer_widths = [128, 256, 512]\nfcnet_activations = [\"tanh\", \"relu\", \"sigmoid\"]\nlearning_startss = [500, 1000, 2000, 4000, 8000]\ntarget_network_update_freqs = [8, 80, 800]\ndouble_dqn = [False, True]\nlearning_rates = [1e-2, 1e-3, 1e-4, 1e-5, 1e-6]\nadam_epsilons = [1e-3, 1e-4, 1e-5, 1e-6] # [1e-1, 1e-4, 1e-7, 1e-10]\n# lstm with sequence lengths\n\nprint('# Algorithm, state_space_size, action_space_size, delay, sequence_length, reward_density,'\n 'terminal_state_density ')\nprint(algorithms, state_space_sizes, action_space_sizes, delays, sequence_lengths, reward_densities, terminal_state_densities)\n\n\n\n# stats = {}\n# aaaa = 3\n\n#TODO Write addnl. line at beginning of file for column names\n# fout = open('rl_stats_temp.csv', 'a') #hardcoded\n# fout.write('# basename, n_points, n_features, n_trees ')\n\nimport time\nstart = time.time()\nprint(algorithms, state_space_sizes, action_space_sizes, delays,\n sequence_lengths, reward_densities, terminal_state_densities)\n\n\ndef on_train_result(info):\n# print(\"#############trainer.train() result: {} -> {} episodes\".format(\n# info[\"trainer\"], info[\"result\"][\"episodes_this_iter\"]), info)\n # you can mutate the result dict to add new fields to return\n# stats['episode_len_mean'] = info['result']['episode_len_mean']\n# print(\"++++++++\", aaaa, stats)\n algorithm = info[\"trainer\"]._name\n state_space_size = info[\"result\"][\"config\"][\"env_config\"][\"state_space_size\"]\n action_space_size = info[\"result\"][\"config\"][\"env_config\"][\"action_space_size\"]\n delay = info[\"result\"][\"config\"][\"env_config\"][\"delay\"]\n sequence_length = info[\"result\"][\"config\"][\"env_config\"][\"sequence_length\"]\n reward_density = info[\"result\"][\"config\"][\"env_config\"][\"reward_density\"]\n terminal_state_density = info[\"result\"][\"config\"][\"env_config\"][\"terminal_state_density\"]\n fcnet_hiddens = info[\"result\"][\"config\"][\"model\"][\"fcnet_hiddens\"]\n num_layers = len(fcnet_hiddens)\n layer_width = fcnet_hiddens[0] #hack\n lr = info[\"result\"][\"config\"][\"lr\"]\n adam_epsilon = info[\"result\"][\"config\"][\"adam_epsilon\"]\n\n timesteps_total = info[\"result\"][\"timesteps_total\"] # also has episodes_total and training_iteration\n episode_reward_mean = info[\"result\"][\"episode_reward_mean\"] # also has max and min\n episode_len_mean = info[\"result\"][\"episode_len_mean\"]\n\n fout = open('./rl_stats_temp_opt.csv', 'a') #hardcoded\n fout.write('# Algorithm, state_space_size, action_space_size, delay, sequence_length, reward_density, '\n 'terminal_state_density, num_layers, layer_width, lr, adam_epsilon,\\n' + str(algorithm) + ' ' + str(state_space_size) +\n ' ' + str(action_space_size) + ' ' + str(delay) + ' ' + str(sequence_length)\n + ' ' + str(reward_density) + ' ' + str(terminal_state_density) + ' ')\n # Writes every iteration, would slow things down. #hack\n fout.write(str(num_layers) + ' ' + str(layer_width) + ' ' + str(lr) + ' ' + str(adam_epsilon) + ' ' + str(timesteps_total) + ' ' + str(episode_reward_mean) +\n ' ' + str(episode_len_mean) + '\\n')\n fout.close()\n\n info[\"result\"][\"callback_ok\"] = True\n\n\n\n# tune.run(\n# RandomAgent,\n# stop={\n# \"timesteps_total\": 20000,\n# },\n# config={\n# \"rollouts_per_iteration\": 10,\n# \"env\": \"RLToy-v0\",\n# \"env_config\": {\n# 'state_space_type': 'discrete',\n# 'action_space_type': 'discrete',\n# 'state_space_size': 16,\n# 'action_space_size': 16,\n# 'generate_random_mdp': True,\n# 'delay': 6,\n# 'sequence_length': 1,\n# 'reward_density': 0.25,\n# 'terminal_state_density': 0.25\n# },\n# },\n# )\n\n# tune.run(\n# VIAgent,\n# stop={\n# \"timesteps_total\": 20000,\n# },\n# config={\n# \"tolerance\": 0.01,\n# \"discount_factor\": 0.99,\n# \"rollouts_per_iteration\": 10,\n# \"env\": \"RLToy-v0\",\n# \"env_config\": {\n# 'state_space_type': 'discrete',\n# 'action_space_type': 'discrete',\n# 'state_space_size': 10,\n# 'action_space_size': 10,\n# 'generate_random_mdp': True,\n# 'delay': 0,\n# 'sequence_length': 1,\n# 'reward_density': 0.25,\n# 'terminal_state_density': 0.25\n# },\n# },\n# )\n\nfor algorithm in algorithms: #TODO each one has different config_spaces\n for state_space_size in state_space_sizes:\n for action_space_size in action_space_sizes:\n for delay in delays:\n for sequence_length in sequence_lengths:\n for reward_density in reward_densities:\n for terminal_state_density in terminal_state_densities:\n for lr in learning_rates:\n for adam_epsilon in adam_epsilons:\n tune.run(\n algorithm,\n stop={\n \"timesteps_total\": 20000,\n },\n config={\n# 'seed': 0, #seed\n \"adam_epsilon\": adam_epsilon,\n \"lr\": lr, # \"lr\": grid_search([1e-2, 1e-4, 1e-6]),\n \"beta_annealing_fraction\": 1.0,\n \"buffer_size\": 1000000,\n \"double_q\": False,\n \"dueling\": False,\n \"env\": \"RLToy-v0\",\n \"env_config\": {\n 'seed': 0, #seed\n 'state_space_type': 'discrete',\n 'action_space_type': 'discrete',\n 'state_space_size': state_space_size,\n 'action_space_size': action_space_size,\n 'generate_random_mdp': True,\n 'delay': delay,\n 'sequence_length': sequence_length,\n 'reward_density': reward_density,\n 'terminal_state_density': terminal_state_density,\n 'repeats_in_sequences': False,\n 'reward_unit': 1.0,\n 'make_denser': False,\n 'completely_connected': True\n },\n \"model\": {\n \"fcnet_hiddens\": [256, 256],\n \"custom_preprocessor\": \"ohe\",\n \"custom_options\": {}, # extra options to pass to your preprocessor\n \"fcnet_activation\": \"tanh\",\n \"use_lstm\": False,\n \"max_seq_len\": 20,\n \"lstm_cell_size\": 256,\n \"lstm_use_prev_action_reward\": False,\n },\n \"exploration_final_eps\": 0.01,\n \"exploration_fraction\": 0.1,\n \"final_prioritized_replay_beta\": 1.0,\n \"hiddens\": None,\n \"learning_starts\": 1000,\n \"n_step\": 1,\n \"noisy\": False,\n \"num_atoms\": 1,\n \"prioritized_replay\": False,\n \"prioritized_replay_alpha\": 0.5,\n \"sample_batch_size\": 4,\n \"schedule_max_timesteps\": 20000,\n \"target_network_update_freq\": 800,\n \"timesteps_per_iteration\": 100,\n \"train_batch_size\": 32,\n\n \"callbacks\": {\n # \"on_episode_start\": tune.function(on_episode_start),\n # \"on_episode_step\": tune.function(on_episode_step),\n # \"on_episode_end\": tune.function(on_episode_end),\n # \"on_sample_end\": tune.function(on_sample_end),\n \"on_train_result\": tune.function(on_train_result),\n # \"on_postprocess_traj\": tune.function(on_postprocess_traj),\n },\n },\n #return_trials=True # add tirals = tune.run( above\n )\n\nend = time.time()\nprint(\"No. of seconds to run:\", end - start)\n",
"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom ray.rllib.agents.trainer import Trainer, with_common_config\nfrom ray.rllib.utils.annotations import override\nfrom ray.rllib.agents.dqn import DQNTrainer\nfrom ray.rllib.offline import OutputWriter\nimport sys, os\nprint(\"Arguments\", sys.argv)\nSLURM_ARRAY_TASK_ID = sys.argv[1]\n\nclass HackWriter(OutputWriter):\n def write(self, sample_batch):\n print(sample_batch.data)\n fout = open('./rl_stats_temp_hack_writer.csv', 'a') #hack\n fout.write(str(sample_batch.data))\n fout.close()\n\ndef return_hack_writer(io_context):\n hw = HackWriter()\n# print(\"##############sample_batch\", io_context)#.rows(), sample_batch.data)\n return hw\n# hw.write(sample_batch)\n\n# yapf: disable\n# __sphinx_doc_begin__\nclass RandomAgent(Trainer):\n \"\"\"Policy that takes random actions and never learns.\"\"\"\n\n _name = \"RandomAgent\"\n _default_config = with_common_config({\n \"rollouts_per_iteration\": 10,\n })\n\n @override(Trainer)\n def _init(self, config, env_creator):\n self.env = env_creator(config[\"env_config\"])\n\n @override(Trainer)\n def _train(self):\n rewards = []\n steps = 0\n for _ in range(self.config[\"rollouts_per_iteration\"]):\n obs = self.env.reset()\n done = False\n reward = 0.0\n while not done:\n action = self.env.action_space.sample()\n obs, r, done, info = self.env.step(action)\n\n reward += r\n steps += 1\n rewards.append(reward)\n return {\n \"episode_reward_mean\": np.mean(rewards),\n \"timesteps_this_iter\": steps,\n }\n\nclass VIAgent(Trainer):\n \"\"\"Value Iteration.\n #TODO Make it Generalized PI.\n \"\"\"\n\n _name = \"VIAgent\"\n _default_config = with_common_config({\n \"tolerance\": 0.01,\n \"discount_factor\": 0.5,\n \"rollouts_per_iteration\": 10,\n \"episode_length\": 200,\n # \"lr\": 0.5\n })\n\n @override(Trainer)\n def _init(self, config, env_creator):\n self.env = env_creator(config[\"env_config\"])\n self.V = np.zeros(self.env.observation_space.n)\n self.policy = np.zeros(self.env.observation_space.n, dtype=int)\n self.policy[:] = -1 #IMP # To avoid initing it to a value within action_space range\n\n @override(Trainer)\n def _train(self):\n max_diff = np.inf # Maybe keep a state variable so that we don't need to update every train iteration??\n state_space_size = self.env.observation_space.n\n gamma = self.config[\"discount_factor\"]\n total_iterations = 0\n while max_diff > self.config[\"tolerance\"]:\n total_iterations += 1\n for s in range(state_space_size):\n # print(\"self.V[:]\", s, max_diff, self.V, [self.env.R(s, a) for a in range(self.env.action_space.n)], self.policy[s])\n self.V_old = self.V.copy() # Is this asynchronous? V_old should be held constant for all states in the for loop?\n # print([self.env.R(s, a) for a in range(self.env.action_space.n)], [gamma * self.V[self.env.P(s, a)] for a in range(self.env.action_space.n)], [self.env.R(s, a) + gamma * self.V[self.env.P(s, a)] for a in range(self.env.action_space.n)])\n self.policy[s] = np.argmax([self.env.R(s, a) + gamma * self.V[self.env.P(s, a)] for a in range(self.env.action_space.n)])\n self.V[s] = np.max([self.env.R(s, a) + gamma * self.V[self.env.P(s, a)] for a in range(self.env.action_space.n)]) # We want R to be a callable function, so I guess we have to keep a for loop here??\n # print(\"self.V, self.V_old, self.policy[s]\", self.V, self.V_old, self.policy[s], self.env.P(s, self.policy[s]))\n\n max_diff = np.max(np.absolute(self.V_old - self.V))\n # import time\n # time.sleep(2)\n# for s in range(state_space_size):\n# print(\"FINAL self.V[:]\", s, max_diff, self.V[:], [self.env.R(s, a) for a in range(self.env.action_space.n)])\n\n print(\"Total iterations:\", total_iterations)\n rewards = []\n steps = 0\n for _ in range(self.config[\"rollouts_per_iteration\"]):\n obs = self.env.reset()\n done = False\n reward = 0.0\n for _ in range(self.config[\"episode_length\"]):\n action = self.policy[obs]\n obs, r, done, info = self.env.step(action)\n\n reward += r\n steps += 1\n rewards.append(reward)\n return {\n \"episode_reward_mean\": np.mean(rewards),\n \"timesteps_this_iter\": steps,\n }\n\n\n\n\nimport ray\nfrom ray import tune\nfrom ray.rllib.utils.seed import seed as rllib_seed\nimport rl_toy\nfrom rl_toy.envs import RLToyEnv\nfrom ray.tune.registry import register_env\nregister_env(\"RLToy-v0\", lambda config: RLToyEnv(config))\n\n\n\nfrom ray.rllib.models.preprocessors import OneHotPreprocessor\nfrom ray.rllib.models import ModelCatalog\nModelCatalog.register_custom_preprocessor(\"ohe\", OneHotPreprocessor)\n\n\n\n#rllib_seed(0, 0, 0) ####IMP Doesn't work due to multi-process I think; so use config[\"seed\"]\n# np.random.seed(0)\n# import random\n# random.seed(0)\n# import tensorflow as tf\n# tf.set_random_seed(0)\nray.init(local_mode=True)#, object_id_seed=0)\n\n\n# Old config space\n# algorithms = [\"DQN\"]\n# state_space_sizes = [2**i for i in range(4,6)]\n# action_space_sizes = [2**i for i in range(1,6)]\n# delays = [0] + [2**i for i in range(5)]\n# sequence_lengths = [i for i in range(1,6)]\n# reward_densities = [0.25] # np.linspace(0.0, 1.0, num=5)\n# # make_reward_dense = [True, False]\n# terminal_state_densities = [0.25] # np.linspace(0.1, 1.0, num=5)\n\n\n#test basic case\n# algorithms = [\"DQN\"]\n# state_space_sizes = [10]\n# action_space_sizes = [10]\n# delays = [4]\n# sequence_lengths = [2]\n# reward_densities = [0.25] # np.linspace(0.0, 1.0, num=5)\n# # make_reward_dense = [True, False]\n# terminal_state_densities = [0.25] # np.linspace(0.1, 1.0, num=5)\n\nnum_seeds = 10\nstate_space_sizes = [8]#, 10, 12, 14] # [2**i for i in range(1,6)]\naction_space_sizes = [8]#2, 4, 8, 16] # [2**i for i in range(1,6)]\ndelays = [0]# + [2**i for i in range(4)]\nsequence_lengths = [1]#, 2, 3, 4]#i for i in range(1,4)]\nreward_densities = [0.25] # np.linspace(0.0, 1.0, num=5)\ntransition_noises = [0]#, 0.01, 0.02, 0.10, 0.25]\nreward_noises = [0, 1, 5, 10, 25] # Std dev. of normal dist. #, lambda a: a.normal(0, 0.1), lambda a: a.normal(0, 0.25), lambda a: a.normal(0, 0.5),]\n# make_reward_dense = [True, False]\nterminal_state_densities = [0.25] # np.linspace(0.1, 1.0, num=5)\nalgorithms = [\"DQN\"]\nseeds = [i for i in range(num_seeds)]\n# Others, keep the rest fixed for these: learning_starts, target_network_update_freq, double_dqn, fcnet_hiddens, fcnet_activation, use_lstm, lstm_seq_len, sample_batch_size/train_batch_size, learning rate\n# More others: adam_epsilon, exploration_final_eps/exploration_fraction, buffer_size\nnum_layerss = [1, 2, 3, 4]\nlayer_widths = [8, 32, 128]\nfcnet_activations = [\"tanh\", \"relu\", \"sigmoid\"]\nlearning_startss = [500, 1000, 2000, 4000, 8000]\ntarget_network_update_freqs = [8, 80, 800]\ndouble_dqn = [False, True]\nlearning_rates = []\n\n# lstm with sequence lengths\n\nprint('# Algorithm, state_space_size, action_space_size, delay, sequence_length, reward_density,'\n 'terminal_state_density ')\nprint(algorithms, state_space_sizes, action_space_sizes, delays, sequence_lengths, reward_densities, terminal_state_densities)\n\n\n\n#TODO Write addnl. line at beginning of file for column names\n# fout = open('rl_stats_temp.csv', 'a') #hardcoded\n# fout.write('# basename, n_points, n_features, n_trees ')\n\nhack_filename = './' + SLURM_ARRAY_TASK_ID + '.csv'\nfout = open(hack_filename, 'a') #hardcoded\nfout.write('# Algorithm, state_space_size, action_space_size, delay, sequence_length, reward_density, '\n 'terminal_state_density, transition_noise, reward_noise, dummy_seed,\\n')\nfout.close()\n\nimport time\nstart = time.time()\n\n\ndef on_train_result(info):\n# print(\"#############trainer.train() result: {} -> {} episodes\".format(\n# info[\"trainer\"], info[\"result\"][\"episodes_this_iter\"]), info)\n # you can mutate the result dict to add new fields to return\n# stats['episode_len_mean'] = info['result']['episode_len_mean']\n# print(\"++++++++\", aaaa, stats)\n training_iteration = info[\"result\"][\"training_iteration\"]\n algorithm = info[\"trainer\"]._name\n state_space_size = info[\"result\"][\"config\"][\"env_config\"][\"state_space_size\"]\n action_space_size = info[\"result\"][\"config\"][\"env_config\"][\"action_space_size\"]\n delay = info[\"result\"][\"config\"][\"env_config\"][\"delay\"]\n sequence_length = info[\"result\"][\"config\"][\"env_config\"][\"sequence_length\"]\n reward_density = info[\"result\"][\"config\"][\"env_config\"][\"reward_density\"]\n terminal_state_density = info[\"result\"][\"config\"][\"env_config\"][\"terminal_state_density\"]\n dummy_seed = info[\"result\"][\"config\"][\"env_config\"][\"dummy_seed\"]\n transition_noise = info[\"result\"][\"config\"][\"env_config\"][\"transition_noise\"]\n reward_noise = info[\"result\"][\"config\"][\"env_config\"][\"reward_noise_std\"]\n\n timesteps_total = info[\"result\"][\"timesteps_total\"] # also has episodes_total and training_iteration\n episode_reward_mean = info[\"result\"][\"episode_reward_mean\"] # also has max and min\n episode_len_mean = info[\"result\"][\"episode_len_mean\"]\n\n fout = open(hack_filename, 'a') #hardcoded\n fout.write(str(training_iteration) + ' ')\n fout.write(str(algorithm) + ' ' + str(state_space_size) +\n ' ' + str(action_space_size) + ' ' + str(delay) + ' ' + str(sequence_length)\n + ' ' + str(reward_density) + ' ' + str(terminal_state_density) + ' ')\n # Writes every iteration, would slow things down. #hack\n fout.write(str(transition_noise) + ' ' + str(reward_noise) + ' ' + str(dummy_seed) + ' ' + str(timesteps_total) + ' ' + str(episode_reward_mean) +\n ' ' + str(episode_len_mean) + '\\n')\n fout.close()\n\n # print(\"###HACK info object:\", info)\n hack_filename_eval = './' + SLURM_ARRAY_TASK_ID + '_eval.csv'\n fout = open(hack_filename_eval, 'a') #hardcoded\n fout.write('#HACK STRING EVAL' + \"\\n\")\n fout.close()\n\n info[\"result\"][\"callback_ok\"] = True\n\n\ndef on_episode_end(info):\n # if not info[\"env\"].config[\"make_denser\"]:\n# print(\"###on_episode_end\", info[\"episode\"].agent_rewards)\n\n #info has env, policy, Episode objects\n if \"dummy_eval\" in info[\"env\"].get_unwrapped()[0].config:\n print(\"###on_episode_end info\", info[\"env\"].get_unwrapped()[0].config[\"make_denser\"], info[\"episode\"].total_reward, info[\"episode\"].length) #, info[\"episode\"]._agent_reward_history)\n reward_this_episode = info[\"episode\"].total_reward\n length_this_episode = info[\"episode\"].length\n hack_filename_eval = './' + SLURM_ARRAY_TASK_ID + '_eval.csv'\n fout = open(hack_filename_eval, 'a') #hardcoded\n fout.write(str(reward_this_episode) + ' ' + str(length_this_episode) + \"\\n\")\n fout.close()\n\n\n\n# tune.run(\n# RandomAgent,\n# stop={\n# \"timesteps_total\": 20000,\n# },\n# config={\n# \"rollouts_per_iteration\": 10,\n# \"env\": \"RLToy-v0\",\n# \"env_config\": {\n# 'state_space_type': 'discrete',\n# 'action_space_type': 'discrete',\n# 'state_space_size': 16,\n# 'action_space_size': 16,\n# 'generate_random_mdp': True,\n# 'delay': 6,\n# 'sequence_length': 1,\n# 'reward_density': 0.25,\n# 'terminal_state_density': 0.25\n# },\n# },\n# )\n\n# tune.run(\n# VIAgent,\n# stop={\n# \"timesteps_total\": 20000,\n# },\n# config={\n# \"tolerance\": 0.01,\n# \"discount_factor\": 0.99,\n# \"rollouts_per_iteration\": 10,\n# \"env\": \"RLToy-v0\",\n# \"env_config\": {\n# 'state_space_type': 'discrete',\n# 'action_space_type': 'discrete',\n# 'state_space_size': 10,\n# 'action_space_size': 10,\n# 'generate_random_mdp': True,\n# 'delay': 0,\n# 'sequence_length': 1,\n# 'reward_density': 0.25,\n# 'terminal_state_density': 0.25\n# },\n# },\n# )\n\nfor algorithm in algorithms: #TODO each one has different config_spaces\n for state_space_size in state_space_sizes:\n for action_space_size in action_space_sizes:\n for delay in delays:\n for sequence_length in sequence_lengths:\n for reward_density in reward_densities:\n for terminal_state_density in terminal_state_densities:\n for transition_noise in transition_noises:\n for reward_noise in reward_noises:\n for dummy_seed in seeds: #TODO Different seeds for Ray Trainer (TF, numpy, Python; Torch, Env), Environment (it has multiple sources of randomness too), Ray Evaluator\n tune.run(\n algorithm,\n #hack\n # ag = DQNTrainer(\n stop={\n \"timesteps_total\": 20000,\n },\n config={ # Addnl. for rainbow: n_step (sample_batch_size will be at least this much!!), prioritized_replay, num_atoms, dueling, double_q, noisy\n #'seed': 0, #seed\n \"adam_epsilon\": 1e-4,\n \"buffer_size\": 1000000,\n \"double_q\": True,\n \"dueling\": True,\n \"lr\": 1e-3,\n \"exploration_final_eps\": 0.01,\n \"exploration_fraction\": 0.1,\n \"schedule_max_timesteps\": 20000,\n # \"hiddens\": None,\n \"learning_starts\": 500,\n \"target_network_update_freq\": 80,\n \"n_step\": 4, # delay + sequence_length [1, 2, 4, 8]\n \"noisy\": True,\n \"num_atoms\": 10, # [5, 10, 20]\n \"prioritized_replay\": True,\n \"prioritized_replay_alpha\": 0.75, #\n \"prioritized_replay_beta\": 0.4,\n \"final_prioritized_replay_beta\": 1.0, #\n \"beta_annealing_fraction\": 1.0, #\n\n \"sample_batch_size\": 4,\n \"timesteps_per_iteration\": 1000,\n \"train_batch_size\": 32,\n \"min_iter_time_s\": 1,\n\n \"env\": \"RLToy-v0\",\n \"env_config\": {\n 'dummy_seed': dummy_seed,\n 'seed': 0, #seed\n 'state_space_type': 'discrete',\n 'action_space_type': 'discrete',\n 'state_space_size': state_space_size,\n 'action_space_size': action_space_size,\n 'generate_random_mdp': True,\n 'delay': delay,\n 'sequence_length': sequence_length,\n 'reward_density': reward_density,\n 'terminal_state_density': terminal_state_density,\n 'repeats_in_sequences': False,\n 'reward_unit': 1.0,\n 'make_denser': False,\n 'completely_connected': True,\n 'transition_noise': transition_noise,\n 'reward_noise': tune.function(lambda a: a.normal(0, reward_noise)),\n 'reward_noise_std': reward_noise,\n },\n \"model\": {\n \"fcnet_hiddens\": [256, 256],\n \"custom_preprocessor\": \"ohe\",\n \"custom_options\": {}, # extra options to pass to your preprocessor\n \"fcnet_activation\": \"tanh\",\n \"use_lstm\": False,\n \"max_seq_len\": 20,\n \"lstm_cell_size\": 256,\n \"lstm_use_prev_action_reward\": False,\n },\n\n \"callbacks\": {\n # \"on_episode_start\": tune.function(on_episode_start),\n # \"on_episode_step\": tune.function(on_episode_step),\n \"on_episode_end\": tune.function(on_episode_end),\n # \"on_sample_end\": tune.function(on_sample_end),\n \"on_train_result\": tune.function(on_train_result),\n # \"on_postprocess_traj\": tune.function(on_postprocess_traj),\n },\n \"evaluation_interval\": 1, # I think this every x training_iterations\n \"evaluation_config\": {\n #'seed': 0, #seed\n \"exploration_fraction\": 0,\n \"exploration_final_eps\": 0,\n \"batch_mode\": \"complete_episodes\",\n 'horizon': 100,\n \"env_config\": {\n \"dummy_eval\": True, #hack\n 'transition_noise': 0,\n 'reward_noise': tune.function(lambda a: a.normal(0, 0))\n }\n },\n # \"output\": return_hack_writer,\n # \"output_compress_columns\": [],\n },\n #return_trials=True # add trials = tune.run( above\n )\n # ag.train()\n\nend = time.time()\nprint(\"No. of seconds to run:\", end - start)\n"
] | [
[
"numpy.absolute",
"numpy.zeros",
"numpy.mean"
],
[
"numpy.absolute",
"numpy.zeros",
"numpy.mean"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
zhengzangw/RODNet | [
"eca5f2bd1f3051c2b823d279532ddafa71b009c1"
] | [
"rodnet/models/backbones/hgwi.py"
] | [
"import torch\nimport torch.nn as nn\n\n\nclass RadarStackedHourglass(nn.Module):\n def __init__(self, n_class, stacked_num=1):\n super(RadarStackedHourglass, self).__init__()\n self.stacked_num = stacked_num\n self.conv1a = nn.Conv3d(\n in_channels=2,\n out_channels=32,\n kernel_size=(9, 5, 5),\n stride=(1, 1, 1),\n padding=(4, 2, 2),\n )\n self.conv1b = nn.Conv3d(\n in_channels=32,\n out_channels=64,\n kernel_size=(9, 5, 5),\n stride=(1, 1, 1),\n padding=(4, 2, 2),\n )\n self.conv1c = nn.Conv3d(\n in_channels=64,\n out_channels=160,\n kernel_size=(9, 5, 5),\n stride=(1, 1, 1),\n padding=(4, 2, 2),\n )\n\n self.hourglass = []\n for i in range(stacked_num):\n self.hourglass.append(\n nn.ModuleList(\n [\n RODEncode(),\n RODDecode(),\n nn.Conv3d(\n in_channels=160,\n out_channels=n_class,\n kernel_size=(9, 5, 5),\n stride=(1, 1, 1),\n padding=(4, 2, 2),\n ),\n nn.Conv3d(\n in_channels=n_class,\n out_channels=160,\n kernel_size=(9, 5, 5),\n stride=(1, 1, 1),\n padding=(4, 2, 2),\n ),\n ]\n )\n )\n self.hourglass = nn.ModuleList(self.hourglass)\n self.relu = nn.ReLU()\n self.bn1a = nn.BatchNorm3d(num_features=32)\n self.bn1b = nn.BatchNorm3d(num_features=64)\n self.bn1c = nn.BatchNorm3d(num_features=160)\n self.sigmoid = nn.Sigmoid()\n\n def forward(self, x):\n x = self.relu(self.bn1a(self.conv1a(x)))\n x = self.relu(self.bn1b(self.conv1b(x)))\n x = self.relu(self.bn1c(self.conv1c(x)))\n\n out = []\n for i in range(self.stacked_num):\n x, x1, x2, x3 = self.hourglass[i][0](x)\n x = self.hourglass[i][1](x, x1, x2, x3)\n confmap = self.hourglass[i][2](x)\n out.append(self.sigmoid(confmap))\n if i < self.stacked_num - 1:\n confmap_ = self.hourglass[i][3](confmap)\n x = x + confmap_\n\n return out\n\n\nclass InceptionLayerConcat(nn.Module):\n \"\"\"\n Kernal size: for 2d kernal size, since the kernal size in temporal domain will be fixed\n \"\"\"\n\n def __init__(self, kernal_size, in_channel, stride):\n super(InceptionLayerConcat, self).__init__()\n\n paddingX = kernal_size[0] // 2\n paddingY = kernal_size[1] // 2\n\n self.branch1 = nn.Conv3d(\n in_channels=in_channel,\n out_channels=32,\n kernel_size=(5, kernal_size[0], kernal_size[1]),\n stride=stride,\n padding=(2, paddingX, paddingY),\n )\n self.branch2a = nn.Conv3d(\n in_channels=in_channel,\n out_channels=64,\n kernel_size=(5, kernal_size[0], kernal_size[1]),\n stride=(1, 1, 1),\n padding=(2, paddingX, paddingY),\n )\n self.branch2b = nn.Conv3d(\n in_channels=64,\n out_channels=64,\n kernel_size=(9, kernal_size[0], kernal_size[1]),\n stride=stride,\n padding=(4, paddingX, paddingY),\n )\n self.branch3a = nn.Conv3d(\n in_channels=in_channel,\n out_channels=64,\n kernel_size=(5, kernal_size[0], kernal_size[1]),\n stride=(1, 1, 1),\n padding=(2, paddingX, paddingY),\n )\n self.branch3b = nn.Conv3d(\n in_channels=64,\n out_channels=64,\n kernel_size=(13, kernal_size[0], kernal_size[1]),\n stride=stride,\n padding=(6, paddingX, paddingY),\n )\n\n def forward(self, x):\n branch1 = self.branch1(x)\n\n branch2 = self.branch2a(x)\n branch2 = self.branch2b(branch2)\n\n branch3 = self.branch3a(x)\n branch3 = self.branch3b(branch3)\n\n return torch.cat((branch1, branch2, branch3), 1)\n\n\nclass RODEncode(nn.Module):\n def __init__(self):\n super(RODEncode, self).__init__()\n self.inception1 = InceptionLayerConcat(\n kernal_size=(5, 5), in_channel=160, stride=(1, 2, 2)\n )\n self.inception2 = InceptionLayerConcat(\n kernal_size=(5, 5), in_channel=160, stride=(1, 2, 2)\n )\n self.inception3 = InceptionLayerConcat(\n kernal_size=(5, 5), in_channel=160, stride=(1, 2, 2)\n )\n\n self.skip_inception1 = InceptionLayerConcat(\n kernal_size=(5, 5), in_channel=160, stride=(1, 2, 2)\n )\n self.skip_inception2 = InceptionLayerConcat(\n kernal_size=(5, 5), in_channel=160, stride=(1, 2, 2)\n )\n self.skip_inception3 = InceptionLayerConcat(\n kernal_size=(5, 5), in_channel=160, stride=(1, 2, 2)\n )\n # self.conv4a = nn.Conv3d(in_channels=64, out_channels=64,\n # kernel_size=(9, 5, 5), stride=(1, 1, 1), padding=(4, 2, 2))\n # self.conv4b = nn.Conv3d(in_channels=64, out_channels=64,\n # kernel_size=(9, 5, 5), stride=(1, 2, 2), padding=(4, 2, 2))\n # self.conv5a = nn.Conv3d(in_channels=64, out_channels=64,\n # kernel_size=(9, 5, 5), stride=(1, 1, 1), padding=(4, 2, 2))\n # self.conv5b = nn.Conv3d(in_channels=64, out_channels=64,\n # kernel_size=(9, 5, 5), stride=(1, 2, 2), padding=(4, 2, 2))\n self.bn1 = nn.BatchNorm3d(num_features=160)\n self.bn2 = nn.BatchNorm3d(num_features=160)\n self.bn3 = nn.BatchNorm3d(num_features=160)\n\n self.skip_bn1 = nn.BatchNorm3d(num_features=160)\n self.skip_bn2 = nn.BatchNorm3d(num_features=160)\n self.skip_bn3 = nn.BatchNorm3d(num_features=160)\n # self.bn4a = nn.BatchNorm3d(num_features=64)\n # self.bn4b = nn.BatchNorm3d(num_features=64)\n # self.bn5a = nn.BatchNorm3d(num_features=64)\n # self.bn5b = nn.BatchNorm3d(num_features=64)\n self.relu = nn.ReLU()\n\n def forward(self, x):\n x1 = self.relu(self.skip_bn1(self.skip_inception1(x)))\n x = self.relu(\n self.bn1(self.inception1(x))\n ) # (B, 2, W, 128, 128) -> (B, 64, W, 128, 128)\n\n x2 = self.relu(self.skip_bn2(self.skip_inception2(x)))\n x = self.relu(\n self.bn2(self.inception2(x))\n ) # (B, 2, W, 128, 128) -> (B, 64, W, 128, 128)\n\n x3 = self.relu(self.skip_bn3(self.skip_inception3(x)))\n x = self.relu(\n self.bn3(self.inception3(x))\n ) # (B, 2, W, 128, 128) -> (B, 64, W, 128, 128)\n\n return x, x1, x2, x3\n\n\nclass RODDecode(nn.Module):\n def __init__(self):\n super(RODDecode, self).__init__()\n self.convt1 = nn.ConvTranspose3d(\n in_channels=160,\n out_channels=160,\n kernel_size=(3, 6, 6),\n stride=(1, 2, 2),\n padding=(1, 2, 2),\n )\n self.convt2 = nn.ConvTranspose3d(\n in_channels=160,\n out_channels=160,\n kernel_size=(3, 6, 6),\n stride=(1, 2, 2),\n padding=(1, 2, 2),\n )\n self.convt3 = nn.ConvTranspose3d(\n in_channels=160,\n out_channels=160,\n kernel_size=(3, 6, 6),\n stride=(1, 2, 2),\n padding=(1, 2, 2),\n )\n self.conv1 = nn.Conv3d(\n in_channels=160,\n out_channels=160,\n kernel_size=(9, 5, 5),\n stride=(1, 1, 1),\n padding=(4, 2, 2),\n )\n self.conv2 = nn.Conv3d(\n in_channels=160,\n out_channels=160,\n kernel_size=(9, 5, 5),\n stride=(1, 1, 1),\n padding=(4, 2, 2),\n )\n self.conv3 = nn.Conv3d(\n in_channels=160,\n out_channels=160,\n kernel_size=(9, 5, 5),\n stride=(1, 1, 1),\n padding=(4, 2, 2),\n )\n self.prelu = nn.PReLU()\n self.sigmoid = nn.Sigmoid()\n # self.upsample = nn.Upsample(size=(rodnet_configs['win_size'], radar_configs['ramap_rsize'],\n # radar_configs['ramap_asize']), mode='nearest')\n\n def forward(self, x, x1, x2, x3):\n x = self.prelu(\n self.convt1(x + x3)\n ) # (B, 256, W/4, 16, 16) -> (B, 128, W/2, 32, 32)\n x = self.prelu(self.conv1(x))\n x = self.prelu(\n self.convt2(x + x2)\n ) # (B, 128, W/2, 32, 32) -> (B, 64, W, 64, 64)\n x = self.prelu(self.conv2(x))\n x = self.prelu(self.convt3(x + x1)) # (B, 64, W, 64, 64) -> (B, 3, W, 128, 128)\n x = self.prelu(self.conv3(x))\n return x\n"
] | [
[
"torch.cat",
"torch.nn.ConvTranspose3d",
"torch.nn.PReLU",
"torch.nn.ModuleList",
"torch.nn.Sigmoid",
"torch.nn.Conv3d",
"torch.nn.ReLU",
"torch.nn.BatchNorm3d"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
bopopescu/fbserver | [
"e812dbc4dc0cbf2fda19473015a3d7e253718a19",
"e812dbc4dc0cbf2fda19473015a3d7e253718a19",
"e812dbc4dc0cbf2fda19473015a3d7e253718a19",
"e812dbc4dc0cbf2fda19473015a3d7e253718a19"
] | [
"venv/lib/python2.7/site-packages/sklearn/base.py",
"venv/lib/python2.7/site-packages/sklearn/utils/random.py",
"venv/lib/python2.7/site-packages/sklearn/neighbors/base.py",
"venv/lib/python2.7/site-packages/sklearn/ensemble/tests/test_weight_boosting.py"
] | [
"\"\"\"Base classes for all estimators.\"\"\"\n# Author: Gael Varoquaux <[email protected]>\n# License: BSD 3 clause\n\nimport copy\nimport inspect\nimport warnings\n\nimport numpy as np\nfrom scipy import sparse\nfrom .externals import six\n\n\n###############################################################################\ndef clone(estimator, safe=True):\n \"\"\"Constructs a new estimator with the same parameters.\n\n Clone does a deep copy of the model in an estimator\n without actually copying attached data. It yields a new estimator\n with the same parameters that has not been fit on any data.\n\n Parameters\n ----------\n estimator: estimator object, or list, tuple or set of objects\n The estimator or group of estimators to be cloned\n\n safe: boolean, optional\n If safe is false, clone will fall back to a deepcopy on objects\n that are not estimators.\n\n \"\"\"\n estimator_type = type(estimator)\n # XXX: not handling dictionaries\n if estimator_type in (list, tuple, set, frozenset):\n return estimator_type([clone(e, safe=safe) for e in estimator])\n elif not hasattr(estimator, 'get_params'):\n if not safe:\n return copy.deepcopy(estimator)\n else:\n raise TypeError(\"Cannot clone object '%s' (type %s): \"\n \"it does not seem to be a scikit-learn estimator \"\n \"it does not implement a 'get_params' methods.\"\n % (repr(estimator), type(estimator)))\n klass = estimator.__class__\n new_object_params = estimator.get_params(deep=False)\n for name, param in six.iteritems(new_object_params):\n new_object_params[name] = clone(param, safe=False)\n new_object = klass(**new_object_params)\n params_set = new_object.get_params(deep=False)\n\n # quick sanity check of the parameters of the clone\n for name in new_object_params:\n param1 = new_object_params[name]\n param2 = params_set[name]\n if isinstance(param1, np.ndarray):\n # For most ndarrays, we do not test for complete equality\n if not isinstance(param2, type(param1)):\n equality_test = False\n elif (param1.ndim > 0\n and param1.shape[0] > 0\n and isinstance(param2, np.ndarray)\n and param2.ndim > 0\n and param2.shape[0] > 0):\n equality_test = (\n param1.shape == param2.shape\n and param1.dtype == param2.dtype\n # We have to use '.flat' for 2D arrays\n and param1.flat[0] == param2.flat[0]\n and param1.flat[-1] == param2.flat[-1]\n )\n else:\n equality_test = np.all(param1 == param2)\n elif sparse.issparse(param1):\n # For sparse matrices equality doesn't work\n if not sparse.issparse(param2):\n equality_test = False\n elif param1.size == 0 or param2.size == 0:\n equality_test = (\n param1.__class__ == param2.__class__\n and param1.size == 0\n and param2.size == 0\n )\n else:\n equality_test = (\n param1.__class__ == param2.__class__\n and param1.data[0] == param2.data[0]\n and param1.data[-1] == param2.data[-1]\n and param1.nnz == param2.nnz\n and param1.shape == param2.shape\n )\n else:\n equality_test = new_object_params[name] == params_set[name]\n if not equality_test:\n raise RuntimeError('Cannot clone object %s, as the constructor '\n 'does not seem to set parameter %s' %\n (estimator, name))\n\n return new_object\n\n\n###############################################################################\ndef _pprint(params, offset=0, printer=repr):\n \"\"\"Pretty print the dictionary 'params'\n\n Parameters\n ----------\n params: dict\n The dictionary to pretty print\n\n offset: int\n The offset in characters to add at the begin of each line.\n\n printer:\n The function to convert entries to strings, typically\n the builtin str or repr\n\n \"\"\"\n # Do a multi-line justified repr:\n options = np.get_printoptions()\n np.set_printoptions(precision=5, threshold=64, edgeitems=2)\n params_list = list()\n this_line_length = offset\n line_sep = ',\\n' + (1 + offset // 2) * ' '\n for i, (k, v) in enumerate(sorted(six.iteritems(params))):\n if type(v) is float:\n # use str for representing floating point numbers\n # this way we get consistent representation across\n # architectures and versions.\n this_repr = '%s=%s' % (k, str(v))\n else:\n # use repr of the rest\n this_repr = '%s=%s' % (k, printer(v))\n if len(this_repr) > 500:\n this_repr = this_repr[:300] + '...' + this_repr[-100:]\n if i > 0:\n if (this_line_length + len(this_repr) >= 75 or '\\n' in this_repr):\n params_list.append(line_sep)\n this_line_length = len(line_sep)\n else:\n params_list.append(', ')\n this_line_length += 2\n params_list.append(this_repr)\n this_line_length += len(this_repr)\n\n np.set_printoptions(**options)\n lines = ''.join(params_list)\n # Strip trailing space to avoid nightmare in doctests\n lines = '\\n'.join(l.rstrip(' ') for l in lines.split('\\n'))\n return lines\n\n\n###############################################################################\nclass BaseEstimator(object):\n \"\"\"Base class for all estimators in scikit-learn\n\n Notes\n -----\n All estimators should specify all the parameters that can be set\n at the class level in their ``__init__`` as explicit keyword\n arguments (no ``*args`` or ``**kwargs``).\n \"\"\"\n\n @classmethod\n def _get_param_names(cls):\n \"\"\"Get parameter names for the estimator\"\"\"\n # fetch the constructor or the original constructor before\n # deprecation wrapping if any\n init = getattr(cls.__init__, 'deprecated_original', cls.__init__)\n if init is object.__init__:\n # No explicit constructor to introspect\n return []\n\n # introspect the constructor arguments to find the model parameters\n # to represent\n args, varargs, kw, default = inspect.getargspec(init)\n if varargs is not None:\n raise RuntimeError(\"scikit-learn estimators should always \"\n \"specify their parameters in the signature\"\n \" of their __init__ (no varargs).\"\n \" %s doesn't follow this convention.\"\n % (cls, ))\n # Remove 'self'\n # XXX: This is going to fail if the init is a staticmethod, but\n # who would do this?\n args.pop(0)\n args.sort()\n return args\n\n def get_params(self, deep=True):\n \"\"\"Get parameters for this estimator.\n\n Parameters\n ----------\n deep: boolean, optional\n If True, will return the parameters for this estimator and\n contained subobjects that are estimators.\n\n Returns\n -------\n params : mapping of string to any\n Parameter names mapped to their values.\n \"\"\"\n out = dict()\n for key in self._get_param_names():\n # We need deprecation warnings to always be on in order to\n # catch deprecated param values.\n # This is set in utils/__init__.py but it gets overwritten\n # when running under python3 somehow.\n warnings.simplefilter(\"always\", DeprecationWarning)\n try:\n with warnings.catch_warnings(record=True) as w:\n value = getattr(self, key, None)\n if len(w) and w[0].category == DeprecationWarning:\n # if the parameter is deprecated, don't show it\n continue\n finally:\n warnings.filters.pop(0)\n\n # XXX: should we rather test if instance of estimator?\n if deep and hasattr(value, 'get_params'):\n deep_items = value.get_params().items()\n out.update((key + '__' + k, val) for k, val in deep_items)\n out[key] = value\n return out\n\n def set_params(self, **params):\n \"\"\"Set the parameters of this estimator.\n\n The method works on simple estimators as well as on nested objects\n (such as pipelines). The former have parameters of the form\n ``<component>__<parameter>`` so that it's possible to update each\n component of a nested object.\n\n Returns\n -------\n self\n \"\"\"\n if not params:\n # Simple optimisation to gain speed (inspect is slow)\n return self\n valid_params = self.get_params(deep=True)\n for key, value in six.iteritems(params):\n split = key.split('__', 1)\n if len(split) > 1:\n # nested objects case\n name, sub_name = split\n if not name in valid_params:\n raise ValueError('Invalid parameter %s for estimator %s' %\n (name, self))\n sub_object = valid_params[name]\n sub_object.set_params(**{sub_name: value})\n else:\n # simple objects case\n if not key in valid_params:\n raise ValueError('Invalid parameter %s ' 'for estimator %s'\n % (key, self.__class__.__name__))\n setattr(self, key, value)\n return self\n\n def __repr__(self):\n class_name = self.__class__.__name__\n return '%s(%s)' % (class_name, _pprint(self.get_params(deep=False),\n offset=len(class_name),),)\n\n\n###############################################################################\nclass ClassifierMixin(object):\n \"\"\"Mixin class for all classifiers in scikit-learn.\"\"\"\n\n def score(self, X, y, sample_weight=None):\n \"\"\"Returns the mean accuracy on the given test data and labels.\n\n Parameters\n ----------\n X : array-like, shape = (n_samples, n_features)\n Test samples.\n\n y : array-like, shape = (n_samples,)\n True labels for X.\n\n sample_weight : array-like, shape = [n_samples], optional\n Sample weights.\n\n Returns\n -------\n score : float\n Mean accuracy of self.predict(X) wrt. y.\n\n \"\"\"\n from .metrics import accuracy_score\n return accuracy_score(y, self.predict(X), sample_weight=sample_weight)\n\n\n###############################################################################\nclass RegressorMixin(object):\n \"\"\"Mixin class for all regression estimators in scikit-learn.\"\"\"\n\n def score(self, X, y, sample_weight=None):\n \"\"\"Returns the coefficient of determination R^2 of the prediction.\n\n The coefficient R^2 is defined as (1 - u/v), where u is the regression\n sum of squares ((y_true - y_pred) ** 2).sum() and v is the residual\n sum of squares ((y_true - y_true.mean()) ** 2).sum().\n Best possible score is 1.0, lower values are worse.\n\n Parameters\n ----------\n X : array-like, shape = (n_samples, n_features)\n Test samples.\n\n y : array-like, shape = (n_samples,)\n True values for X.\n\n sample_weight : array-like, shape = [n_samples], optional\n Sample weights.\n\n Returns\n -------\n score : float\n R^2 of self.predict(X) wrt. y.\n \"\"\"\n\n from .metrics import r2_score\n return r2_score(y, self.predict(X), sample_weight=sample_weight)\n\n\n###############################################################################\nclass ClusterMixin(object):\n \"\"\"Mixin class for all cluster estimators in scikit-learn.\"\"\"\n def fit_predict(self, X, y=None):\n \"\"\"Performs clustering on X and returns cluster labels.\n\n Parameters\n ----------\n X : ndarray, shape (n_samples, n_features)\n Input data.\n\n Returns\n -------\n y : ndarray, shape (n_samples,)\n cluster labels\n \"\"\"\n # non-optimized default implementation; override when a better\n # method is possible for a given clustering algorithm\n self.fit(X)\n return self.labels_\n\n\nclass BiclusterMixin(object):\n \"\"\"Mixin class for all bicluster estimators in scikit-learn\"\"\"\n\n @property\n def biclusters_(self):\n \"\"\"Convenient way to get row and column indicators together.\n\n Returns the ``rows_`` and ``columns_`` members.\n \"\"\"\n return self.rows_, self.columns_\n\n def get_indices(self, i):\n \"\"\"Row and column indices of the i'th bicluster.\n\n Only works if ``rows_`` and ``columns_`` attributes exist.\n\n Returns\n -------\n row_ind : np.array, dtype=np.intp\n Indices of rows in the dataset that belong to the bicluster.\n col_ind : np.array, dtype=np.intp\n Indices of columns in the dataset that belong to the bicluster.\n\n \"\"\"\n from .cluster.bicluster.utils import get_indices\n return get_indices(self.rows_[i], self.columns_[i])\n\n def get_shape(self, i):\n \"\"\"Shape of the i'th bicluster.\n\n Returns\n -------\n shape : (int, int)\n Number of rows and columns (resp.) in the bicluster.\n \"\"\"\n from .cluster.bicluster.utils import get_shape\n return get_shape(self.rows_[i], self.columns_[i])\n\n def get_submatrix(self, i, data):\n \"\"\"Returns the submatrix corresponding to bicluster `i`.\n\n Works with sparse matrices. Only works if ``rows_`` and\n ``columns_`` attributes exist.\n\n \"\"\"\n from .cluster.bicluster.utils import get_submatrix\n return get_submatrix(self.rows_[i], self.columns_[i], data)\n\n\n###############################################################################\nclass TransformerMixin(object):\n \"\"\"Mixin class for all transformers in scikit-learn.\"\"\"\n\n def fit_transform(self, X, y=None, **fit_params):\n \"\"\"Fit to data, then transform it.\n\n Fits transformer to X and y with optional parameters fit_params\n and returns a transformed version of X.\n\n Parameters\n ----------\n X : numpy array of shape [n_samples, n_features]\n Training set.\n\n y : numpy array of shape [n_samples]\n Target values.\n\n Returns\n -------\n X_new : numpy array of shape [n_samples, n_features_new]\n Transformed array.\n\n \"\"\"\n # non-optimized default implementation; override when a better\n # method is possible for a given clustering algorithm\n if y is None:\n # fit method of arity 1 (unsupervised transformation)\n return self.fit(X, **fit_params).transform(X)\n else:\n # fit method of arity 2 (supervised transformation)\n return self.fit(X, y, **fit_params).transform(X)\n\n\n###############################################################################\nclass MetaEstimatorMixin(object):\n \"\"\"Mixin class for all meta estimators in scikit-learn.\"\"\"\n # this is just a tag for the moment\n\n\n###############################################################################\n# XXX: Temporary solution to figure out if an estimator is a classifier\n\ndef _get_sub_estimator(estimator):\n \"\"\"Returns the final estimator if there is any.\"\"\"\n if hasattr(estimator, 'estimator'):\n # GridSearchCV and other CV-tuned estimators\n return _get_sub_estimator(estimator.estimator)\n if hasattr(estimator, 'steps'):\n # Pipeline\n return _get_sub_estimator(estimator.steps[-1][1])\n return estimator\n\n\ndef is_classifier(estimator):\n \"\"\"Returns True if the given estimator is (probably) a classifier.\"\"\"\n estimator = _get_sub_estimator(estimator)\n return isinstance(estimator, ClassifierMixin)\n",
"# This file contains a backport of np.random.choice from numpy 1.7\n# The function can be removed when we bump the requirements to >=1.7\n\nimport numpy as np\nimport operator\n\nfrom sklearn.utils import check_random_state\n\nfrom ._random import sample_without_replacement\n\n__all__ = ['sample_without_replacement', 'choice']\n\n\ndef choice(a, size=None, replace=True, p=None, random_state=None):\n \"\"\"\n choice(a, size=None, replace=True, p=None)\n\n Generates a random sample from a given 1-D array\n\n .. versionadded:: 1.7.0\n\n Parameters\n -----------\n a : 1-D array-like or int\n If an ndarray, a random sample is generated from its elements.\n If an int, the random sample is generated as if a was np.arange(n)\n\n size : int or tuple of ints, optional\n Output shape. Default is None, in which case a single value is\n returned.\n\n replace : boolean, optional\n Whether the sample is with or without replacement.\n\n p : 1-D array-like, optional\n The probabilities associated with each entry in a.\n If not given the sample assumes a uniform distribtion over all\n entries in a.\n\n random_state : int, RandomState instance or None, optional (default=None)\n If int, random_state is the seed used by the random number generator;\n If RandomState instance, random_state is the random number generator;\n If None, the random number generator is the RandomState instance used\n by `np.random`.\n\n\n Returns\n --------\n samples : 1-D ndarray, shape (size,)\n The generated random samples\n\n Raises\n -------\n ValueError\n If a is an int and less than zero, if a or p are not 1-dimensional,\n if a is an array-like of size 0, if p is not a vector of\n probabilities, if a and p have different lengths, or if\n replace=False and the sample size is greater than the population\n size\n\n See Also\n ---------\n randint, shuffle, permutation\n\n Examples\n ---------\n Generate a uniform random sample from np.arange(5) of size 3:\n\n >>> np.random.choice(5, 3) # doctest: +SKIP\n array([0, 3, 4])\n >>> #This is equivalent to np.random.randint(0,5,3)\n\n Generate a non-uniform random sample from np.arange(5) of size 3:\n\n >>> np.random.choice(5, 3, p=[0.1, 0, 0.3, 0.6, 0]) # doctest: +SKIP\n array([3, 3, 0])\n\n Generate a uniform random sample from np.arange(5) of size 3 without\n replacement:\n\n >>> np.random.choice(5, 3, replace=False) # doctest: +SKIP\n array([3,1,0])\n >>> #This is equivalent to np.random.shuffle(np.arange(5))[:3]\n\n Generate a non-uniform random sample from np.arange(5) of size\n 3 without replacement:\n\n >>> np.random.choice(5, 3, replace=False, p=[0.1, 0, 0.3, 0.6, 0])\n ... # doctest: +SKIP\n array([2, 3, 0])\n\n Any of the above can be repeated with an arbitrary array-like\n instead of just integers. For instance:\n\n >>> aa_milne_arr = ['pooh', 'rabbit', 'piglet', 'Christopher']\n >>> np.random.choice(aa_milne_arr, 5, p=[0.5, 0.1, 0.1, 0.3])\n ... # doctest: +SKIP\n array(['pooh', 'pooh', 'pooh', 'Christopher', 'piglet'],\n dtype='|S11')\n\n \"\"\"\n random_state = check_random_state(random_state)\n\n # Format and Verify input\n a = np.array(a, copy=False)\n if a.ndim == 0:\n try:\n # __index__ must return an integer by python rules.\n pop_size = operator.index(a.item())\n except TypeError:\n raise ValueError(\"a must be 1-dimensional or an integer\")\n if pop_size <= 0:\n raise ValueError(\"a must be greater than 0\")\n elif a.ndim != 1:\n raise ValueError(\"a must be 1-dimensional\")\n else:\n pop_size = a.shape[0]\n if pop_size is 0:\n raise ValueError(\"a must be non-empty\")\n\n if None != p:\n p = np.array(p, dtype=np.double, ndmin=1, copy=False)\n if p.ndim != 1:\n raise ValueError(\"p must be 1-dimensional\")\n if p.size != pop_size:\n raise ValueError(\"a and p must have same size\")\n if np.any(p < 0):\n raise ValueError(\"probabilities are not non-negative\")\n if not np.allclose(p.sum(), 1):\n raise ValueError(\"probabilities do not sum to 1\")\n\n shape = size\n if shape is not None:\n size = np.prod(shape, dtype=np.intp)\n else:\n size = 1\n\n # Actual sampling\n if replace:\n if None != p:\n cdf = p.cumsum()\n cdf /= cdf[-1]\n uniform_samples = random_state.random_sample(shape)\n idx = cdf.searchsorted(uniform_samples, side='right')\n # searchsorted returns a scalar\n idx = np.array(idx, copy=False)\n else:\n idx = random_state.randint(0, pop_size, size=shape)\n else:\n if size > pop_size:\n raise ValueError(\"Cannot take a larger sample than \"\n \"population when 'replace=False'\")\n\n if None != p:\n if np.sum(p > 0) < size:\n raise ValueError(\"Fewer non-zero entries in p than size\")\n n_uniq = 0\n p = p.copy()\n found = np.zeros(shape, dtype=np.int)\n flat_found = found.ravel()\n while n_uniq < size:\n x = random_state.rand(size - n_uniq)\n if n_uniq > 0:\n p[flat_found[0:n_uniq]] = 0\n cdf = np.cumsum(p)\n cdf /= cdf[-1]\n new = cdf.searchsorted(x, side='right')\n _, unique_indices = np.unique(new, return_index=True)\n unique_indices.sort()\n new = new.take(unique_indices)\n flat_found[n_uniq:n_uniq + new.size] = new\n n_uniq += new.size\n idx = found\n else:\n idx = random_state.permutation(pop_size)[:size]\n if shape is not None:\n idx.shape = shape\n\n if shape is None and isinstance(idx, np.ndarray):\n # In most cases a scalar will have been made an array\n idx = idx.item(0)\n\n #Use samples as indices for a if a is array-like\n if a.ndim == 0:\n return idx\n\n if shape is not None and idx.ndim == 0:\n # If size == () then the user requested a 0-d array as opposed to\n # a scalar object when size is None. However a[idx] is always a\n # scalar and not an array. So this makes sure the result is an\n # array, taking into account that np.array(item) may not work\n # for object arrays.\n res = np.empty((), dtype=a.dtype)\n res[()] = a[idx]\n return res\n\n return a[idx]\n",
"\"\"\"Base and mixin classes for nearest neighbors\"\"\"\n# Authors: Jake Vanderplas <[email protected]>\n# Fabian Pedregosa <[email protected]>\n# Alexandre Gramfort <[email protected]>\n# Sparseness support by Lars Buitinck <[email protected]>\n# Multi-output support by Arnaud Joly <[email protected]>\n#\n# License: BSD 3 clause (C) INRIA, University of Amsterdam\nimport warnings\nfrom abc import ABCMeta, abstractmethod\n\nimport numpy as np\nfrom scipy.sparse import csr_matrix, issparse\n\nfrom .ball_tree import BallTree\nfrom .kd_tree import KDTree\nfrom ..base import BaseEstimator\nfrom ..metrics import pairwise_distances\nfrom ..metrics.pairwise import PAIRWISE_DISTANCE_FUNCTIONS\nfrom ..utils import safe_asarray, atleast2d_or_csr, check_arrays\nfrom ..utils.fixes import argpartition\nfrom ..utils.validation import DataConversionWarning\nfrom ..externals import six\n\n\nVALID_METRICS = dict(ball_tree=BallTree.valid_metrics,\n kd_tree=KDTree.valid_metrics,\n # The following list comes from the\n # sklearn.metrics.pairwise doc string\n brute=(list(PAIRWISE_DISTANCE_FUNCTIONS.keys()) +\n ['braycurtis', 'canberra', 'chebyshev',\n 'correlation', 'cosine', 'dice', 'hamming',\n 'jaccard', 'kulsinski', 'mahalanobis',\n 'matching', 'minkowski', 'rogerstanimoto',\n 'russellrao', 'seuclidean', 'sokalmichener',\n 'sokalsneath', 'sqeuclidean',\n 'yule', 'wminkowski']))\n\n\nVALID_METRICS_SPARSE = dict(ball_tree=[],\n kd_tree=[],\n brute=PAIRWISE_DISTANCE_FUNCTIONS.keys())\n\n\nclass NeighborsWarning(UserWarning):\n pass\n\n\n# Make sure that NeighborsWarning are displayed more than once\nwarnings.simplefilter(\"always\", NeighborsWarning)\n\n\ndef _check_weights(weights):\n \"\"\"Check to make sure weights are valid\"\"\"\n if weights in (None, 'uniform', 'distance'):\n return weights\n elif callable(weights):\n return weights\n else:\n raise ValueError(\"weights not recognized: should be 'uniform', \"\n \"'distance', or a callable function\")\n\n\ndef _get_weights(dist, weights):\n \"\"\"Get the weights from an array of distances and a parameter ``weights``\n\n Parameters\n ===========\n dist: ndarray\n The input distances\n weights: {'uniform', 'distance' or a callable}\n The kind of weighting used\n\n Returns\n ========\n weights_arr: array of the same shape as ``dist``\n if ``weights == 'uniform'``, then returns None\n \"\"\"\n if weights in (None, 'uniform'):\n return None\n elif weights == 'distance':\n with np.errstate(divide='ignore'):\n dist = 1. / dist\n return dist\n elif callable(weights):\n return weights(dist)\n else:\n raise ValueError(\"weights not recognized: should be 'uniform', \"\n \"'distance', or a callable function\")\n\n\nclass NeighborsBase(six.with_metaclass(ABCMeta, BaseEstimator)):\n \"\"\"Base class for nearest neighbors estimators.\"\"\"\n\n @abstractmethod\n def __init__(self):\n pass\n\n def _init_params(self, n_neighbors=None, radius=None,\n algorithm='auto', leaf_size=30, metric='minkowski',\n p=2, metric_params=None, **kwargs):\n if kwargs:\n warnings.warn(\"Passing additional arguments to the metric \"\n \"function as **kwargs is deprecated \"\n \"and will no longer be supported in 0.18. \"\n \"Use metric_params instead.\",\n DeprecationWarning, stacklevel=3)\n if metric_params is None:\n metric_params = {}\n metric_params.update(kwargs)\n\n self.n_neighbors = n_neighbors\n self.radius = radius\n self.algorithm = algorithm\n self.leaf_size = leaf_size\n self.metric = metric\n self.metric_params = metric_params\n self.p = p\n\n if algorithm not in ['auto', 'brute',\n 'kd_tree', 'ball_tree']:\n raise ValueError(\"unrecognized algorithm: '%s'\" % algorithm)\n\n if algorithm == 'auto':\n alg_check = 'ball_tree'\n else:\n alg_check = algorithm\n\n if callable(metric):\n if algorithm == 'kd_tree':\n # callable metric is only valid for brute force and ball_tree\n raise ValueError(\n \"kd_tree algorithm does not support callable metric '%s'\"\n % metric)\n elif metric not in VALID_METRICS[alg_check]:\n raise ValueError(\"Metric '%s' not valid for algorithm '%s'\"\n % (metric, algorithm))\n\n if self.metric_params is not None and 'p' in self.metric_params:\n warnings.warn(\"Parameter p is found in metric_params. \"\n \"The corresponding parameter from __init__ \"\n \"is ignored.\", SyntaxWarning, stacklevel=3)\n effective_p = metric_params['p']\n else:\n effective_p = self.p\n\n if self.metric in ['wminkowski', 'minkowski'] and effective_p < 1:\n raise ValueError(\"p must be greater than one for minkowski metric\")\n\n self._fit_X = None\n self._tree = None\n self._fit_method = None\n\n def _fit(self, X):\n if self.metric_params is None:\n self.effective_metric_params_ = {}\n else:\n self.effective_metric_params_ = self.metric_params.copy()\n\n effective_p = self.effective_metric_params_.get('p', self.p)\n if self.metric in ['wminkowski', 'minkowski']:\n self.effective_metric_params_['p'] = effective_p\n\n self.effective_metric_ = self.metric\n # For minkowski distance, use more efficient methods where available\n if self.metric == 'minkowski':\n p = self.effective_metric_params_.pop('p', 2)\n if p < 1:\n raise ValueError(\"p must be greater than one \"\n \"for minkowski metric\")\n elif p == 1:\n self.effective_metric_ = 'manhattan'\n elif p == 2:\n self.effective_metric_ = 'euclidean'\n elif p == np.inf:\n self.effective_metric_ = 'chebyshev'\n else:\n self.effective_metric_params_['p'] = p\n\n if isinstance(X, NeighborsBase):\n self._fit_X = X._fit_X\n self._tree = X._tree\n self._fit_method = X._fit_method\n return self\n\n elif isinstance(X, BallTree):\n self._fit_X = X.data\n self._tree = X\n self._fit_method = 'ball_tree'\n return self\n\n elif isinstance(X, KDTree):\n self._fit_X = X.data\n self._tree = X\n self._fit_method = 'kd_tree'\n return self\n\n X = atleast2d_or_csr(X, copy=False)\n\n n_samples = X.shape[0]\n if n_samples == 0:\n raise ValueError(\"n_samples must be greater than 0\")\n\n if issparse(X):\n if self.algorithm not in ('auto', 'brute'):\n warnings.warn(\"cannot use tree with sparse input: \"\n \"using brute force\")\n if self.effective_metric_ not in VALID_METRICS_SPARSE['brute']:\n raise ValueError(\"metric '%s' not valid for sparse input\"\n % self.effective_metric_)\n self._fit_X = X.copy()\n self._tree = None\n self._fit_method = 'brute'\n return self\n\n self._fit_method = self.algorithm\n self._fit_X = X\n\n if self._fit_method == 'auto':\n # A tree approach is better for small number of neighbors,\n # and KDTree is generally faster when available\n if (self.n_neighbors is None\n or self.n_neighbors < self._fit_X.shape[0] // 2):\n if self.effective_metric_ in VALID_METRICS['kd_tree']:\n self._fit_method = 'kd_tree'\n else:\n self._fit_method = 'ball_tree'\n else:\n self._fit_method = 'brute'\n\n if self._fit_method == 'ball_tree':\n self._tree = BallTree(X, self.leaf_size,\n metric=self.effective_metric_,\n **self.effective_metric_params_)\n elif self._fit_method == 'kd_tree':\n self._tree = KDTree(X, self.leaf_size,\n metric=self.effective_metric_,\n **self.effective_metric_params_)\n elif self._fit_method == 'brute':\n self._tree = None\n else:\n raise ValueError(\"algorithm = '%s' not recognized\"\n % self.algorithm)\n return self\n\n\nclass KNeighborsMixin(object):\n \"\"\"Mixin for k-neighbors searches\"\"\"\n\n def kneighbors(self, X, n_neighbors=None, return_distance=True):\n \"\"\"Finds the K-neighbors of a point.\n\n Returns distance\n\n Parameters\n ----------\n X : array-like, last dimension same as that of fit data\n The new point.\n\n n_neighbors : int\n Number of neighbors to get (default is the value\n passed to the constructor).\n\n return_distance : boolean, optional. Defaults to True.\n If False, distances will not be returned\n\n Returns\n -------\n dist : array\n Array representing the lengths to point, only present if\n return_distance=True\n\n ind : array\n Indices of the nearest points in the population matrix.\n\n Examples\n --------\n In the following example, we construct a NeighborsClassifier\n class from an array representing our data set and ask who's\n the closest point to [1,1,1]\n\n >>> samples = [[0., 0., 0.], [0., .5, 0.], [1., 1., .5]]\n >>> from sklearn.neighbors import NearestNeighbors\n >>> neigh = NearestNeighbors(n_neighbors=1)\n >>> neigh.fit(samples) # doctest: +ELLIPSIS\n NearestNeighbors(algorithm='auto', leaf_size=30, ...)\n >>> print(neigh.kneighbors([1., 1., 1.])) # doctest: +ELLIPSIS\n (array([[ 0.5]]), array([[2]]...))\n\n As you can see, it returns [[0.5]], and [[2]], which means that the\n element is at distance 0.5 and is the third element of samples\n (indexes start at 0). You can also query for multiple points:\n\n >>> X = [[0., 1., 0.], [1., 0., 1.]]\n >>> neigh.kneighbors(X, return_distance=False) # doctest: +ELLIPSIS\n array([[1],\n [2]]...)\n\n \"\"\"\n if self._fit_method is None:\n raise ValueError(\"must fit neighbors before querying\")\n\n X = atleast2d_or_csr(X)\n\n if n_neighbors is None:\n n_neighbors = self.n_neighbors\n\n if self._fit_method == 'brute':\n # for efficiency, use squared euclidean distances\n if self.effective_metric_ == 'euclidean':\n dist = pairwise_distances(X, self._fit_X, 'euclidean',\n squared=True)\n else:\n dist = pairwise_distances(X, self._fit_X,\n self.effective_metric_,\n **self.effective_metric_params_)\n\n neigh_ind = argpartition(dist, n_neighbors - 1, axis=1)\n neigh_ind = neigh_ind[:, :n_neighbors]\n # argpartition doesn't guarantee sorted order, so we sort again\n j = np.arange(neigh_ind.shape[0])[:, None]\n neigh_ind = neigh_ind[j, np.argsort(dist[j, neigh_ind])]\n if return_distance:\n if self.effective_metric_ == 'euclidean':\n return np.sqrt(dist[j, neigh_ind]), neigh_ind\n else:\n return dist[j, neigh_ind], neigh_ind\n else:\n return neigh_ind\n elif self._fit_method in ['ball_tree', 'kd_tree']:\n result = self._tree.query(X, n_neighbors,\n return_distance=return_distance)\n return result\n else:\n raise ValueError(\"internal: _fit_method not recognized\")\n\n def kneighbors_graph(self, X, n_neighbors=None,\n mode='connectivity'):\n \"\"\"Computes the (weighted) graph of k-Neighbors for points in X\n\n Parameters\n ----------\n X : array-like, shape = [n_samples, n_features]\n Sample data\n\n n_neighbors : int\n Number of neighbors for each sample.\n (default is value passed to the constructor).\n\n mode : {'connectivity', 'distance'}, optional\n Type of returned matrix: 'connectivity' will return the\n connectivity matrix with ones and zeros, in 'distance' the\n edges are Euclidean distance between points.\n\n Returns\n -------\n A : sparse matrix in CSR format, shape = [n_samples, n_samples_fit]\n n_samples_fit is the number of samples in the fitted data\n A[i, j] is assigned the weight of edge that connects i to j.\n\n Examples\n --------\n >>> X = [[0], [3], [1]]\n >>> from sklearn.neighbors import NearestNeighbors\n >>> neigh = NearestNeighbors(n_neighbors=2)\n >>> neigh.fit(X) # doctest: +ELLIPSIS\n NearestNeighbors(algorithm='auto', leaf_size=30, ...)\n >>> A = neigh.kneighbors_graph(X)\n >>> A.toarray()\n array([[ 1., 0., 1.],\n [ 0., 1., 1.],\n [ 1., 0., 1.]])\n\n See also\n --------\n NearestNeighbors.radius_neighbors_graph\n \"\"\"\n X = safe_asarray(X)\n\n if n_neighbors is None:\n n_neighbors = self.n_neighbors\n\n n_samples1 = X.shape[0]\n n_samples2 = self._fit_X.shape[0]\n n_nonzero = n_samples1 * n_neighbors\n A_indptr = np.arange(0, n_nonzero + 1, n_neighbors)\n\n # construct CSR matrix representation of the k-NN graph\n if mode == 'connectivity':\n A_data = np.ones((n_samples1, n_neighbors))\n A_ind = self.kneighbors(X, n_neighbors, return_distance=False)\n\n elif mode == 'distance':\n data, ind = self.kneighbors(X, n_neighbors + 1,\n return_distance=True)\n A_data, A_ind = data[:, 1:], ind[:, 1:]\n\n else:\n raise ValueError(\n 'Unsupported mode, must be one of \"connectivity\" '\n 'or \"distance\" but got \"%s\" instead' % mode)\n\n return csr_matrix((A_data.ravel(), A_ind.ravel(), A_indptr),\n shape=(n_samples1, n_samples2))\n\n\nclass RadiusNeighborsMixin(object):\n \"\"\"Mixin for radius-based neighbors searches\"\"\"\n\n def radius_neighbors(self, X, radius=None, return_distance=True):\n \"\"\"Finds the neighbors within a given radius of a point or points.\n\n Returns indices of and distances to the neighbors of each point.\n\n Parameters\n ----------\n X : array-like, last dimension same as that of fit data\n The new point or points\n\n radius : float\n Limiting distance of neighbors to return.\n (default is the value passed to the constructor).\n\n return_distance : boolean, optional. Defaults to True.\n If False, distances will not be returned\n\n Returns\n -------\n dist : array\n Array representing the euclidean distances to each point,\n only present if return_distance=True.\n\n ind : array\n Indices of the nearest points in the population matrix.\n\n Examples\n --------\n In the following example, we construct a NeighborsClassifier\n class from an array representing our data set and ask who's\n the closest point to [1,1,1]\n\n >>> samples = [[0., 0., 0.], [0., .5, 0.], [1., 1., .5]]\n >>> from sklearn.neighbors import NearestNeighbors\n >>> neigh = NearestNeighbors(radius=1.6)\n >>> neigh.fit(samples) # doctest: +ELLIPSIS\n NearestNeighbors(algorithm='auto', leaf_size=30, ...)\n >>> print(neigh.radius_neighbors([1., 1., 1.])) # doctest: +ELLIPSIS\n (array([[ 1.5, 0.5]]...), array([[1, 2]]...)\n\n The first array returned contains the distances to all points which\n are closer than 1.6, while the second array returned contains their\n indices. In general, multiple points can be queried at the same time.\n\n Notes\n -----\n Because the number of neighbors of each point is not necessarily\n equal, the results for multiple query points cannot be fit in a\n standard data array.\n For efficiency, `radius_neighbors` returns arrays of objects, where\n each object is a 1D array of indices or distances.\n \"\"\"\n\n if self._fit_method is None:\n raise ValueError(\"must fit neighbors before querying\")\n\n X = atleast2d_or_csr(X)\n\n if radius is None:\n radius = self.radius\n\n if self._fit_method == 'brute':\n # for efficiency, use squared euclidean distances\n if self.effective_metric_ == 'euclidean':\n dist = pairwise_distances(X, self._fit_X, 'euclidean',\n squared=True)\n radius *= radius\n else:\n dist = pairwise_distances(X, self._fit_X,\n self.effective_metric_,\n **self.effective_metric_params_)\n neigh_ind = [np.where(d < radius)[0] for d in dist]\n\n # if there are the same number of neighbors for each point,\n # we can do a normal array. Otherwise, we return an object\n # array with elements that are numpy arrays\n try:\n neigh_ind = np.asarray(neigh_ind, dtype=int)\n dtype_F = float\n except ValueError:\n neigh_ind = np.asarray(neigh_ind, dtype='object')\n dtype_F = object\n\n if return_distance:\n if self.effective_metric_ == 'euclidean':\n dist = np.array([np.sqrt(d[neigh_ind[i]])\n for i, d in enumerate(dist)],\n dtype=dtype_F)\n else:\n dist = np.array([d[neigh_ind[i]]\n for i, d in enumerate(dist)],\n dtype=dtype_F)\n return dist, neigh_ind\n else:\n return neigh_ind\n elif self._fit_method in ['ball_tree', 'kd_tree']:\n results = self._tree.query_radius(X, radius,\n return_distance=return_distance)\n if return_distance:\n ind, dist = results\n return dist, ind\n else:\n return results\n else:\n raise ValueError(\"internal: _fit_method not recognized\")\n\n def radius_neighbors_graph(self, X, radius=None, mode='connectivity'):\n \"\"\"Computes the (weighted) graph of Neighbors for points in X\n\n Neighborhoods are restricted the points at a distance lower than\n radius.\n\n Parameters\n ----------\n X : array-like, shape = [n_samples, n_features]\n Sample data\n\n radius : float\n Radius of neighborhoods.\n (default is the value passed to the constructor).\n\n mode : {'connectivity', 'distance'}, optional\n Type of returned matrix: 'connectivity' will return the\n connectivity matrix with ones and zeros, in 'distance' the\n edges are Euclidean distance between points.\n\n Returns\n -------\n A : sparse matrix in CSR format, shape = [n_samples, n_samples]\n A[i, j] is assigned the weight of edge that connects i to j.\n\n Examples\n --------\n >>> X = [[0], [3], [1]]\n >>> from sklearn.neighbors import NearestNeighbors\n >>> neigh = NearestNeighbors(radius=1.5)\n >>> neigh.fit(X) # doctest: +ELLIPSIS\n NearestNeighbors(algorithm='auto', leaf_size=30, ...)\n >>> A = neigh.radius_neighbors_graph(X)\n >>> A.toarray()\n array([[ 1., 0., 1.],\n [ 0., 1., 0.],\n [ 1., 0., 1.]])\n\n See also\n --------\n kneighbors_graph\n \"\"\"\n X = safe_asarray(X)\n\n if radius is None:\n radius = self.radius\n\n n_samples1 = X.shape[0]\n n_samples2 = self._fit_X.shape[0]\n\n # construct CSR matrix representation of the NN graph\n if mode == 'connectivity':\n A_ind = self.radius_neighbors(X, radius,\n return_distance=False)\n A_data = None\n elif mode == 'distance':\n dist, A_ind = self.radius_neighbors(X, radius,\n return_distance=True)\n A_data = np.concatenate(list(dist))\n else:\n raise ValueError(\n 'Unsupported mode, must be one of \"connectivity\", '\n 'or \"distance\" but got %s instead' % mode)\n\n n_neighbors = np.array([len(a) for a in A_ind])\n n_nonzero = np.sum(n_neighbors)\n if A_data is None:\n A_data = np.ones(n_nonzero)\n A_ind = np.concatenate(list(A_ind))\n A_indptr = np.concatenate((np.zeros(1, dtype=int),\n np.cumsum(n_neighbors)))\n\n return csr_matrix((A_data, A_ind, A_indptr),\n shape=(n_samples1, n_samples2))\n\n\nclass SupervisedFloatMixin(object):\n def fit(self, X, y):\n \"\"\"Fit the model using X as training data and y as target values\n\n Parameters\n ----------\n X : {array-like, sparse matrix, BallTree, KDTree}\n Training data. If array or matrix, shape = [n_samples, n_features]\n\n y : {array-like, sparse matrix}\n Target values, array of float values, shape = [n_samples]\n or [n_samples, n_outputs]\n \"\"\"\n if not isinstance(X, (KDTree, BallTree)):\n X, y = check_arrays(X, y, sparse_format=\"csr\")\n self._y = y\n return self._fit(X)\n\n\nclass SupervisedIntegerMixin(object):\n def fit(self, X, y):\n \"\"\"Fit the model using X as training data and y as target values\n\n Parameters\n ----------\n X : {array-like, sparse matrix, BallTree, KDTree}\n Training data. If array or matrix, shape = [n_samples, n_features]\n\n y : {array-like, sparse matrix}\n Target values of shape = [n_samples] or [n_samples, n_outputs]\n\n \"\"\"\n if not isinstance(X, (KDTree, BallTree)):\n X, y = check_arrays(X, y, sparse_format=\"csr\")\n\n if y.ndim == 1 or y.ndim == 2 and y.shape[1] == 1:\n if y.ndim != 1:\n warnings.warn(\"A column-vector y was passed when a 1d array \"\n \"was expected. Please change the shape of y to \"\n \"(n_samples, ), for example using ravel().\",\n DataConversionWarning, stacklevel=2)\n\n self.outputs_2d_ = False\n y = y.reshape((-1, 1))\n else:\n self.outputs_2d_ = True\n\n self.classes_ = []\n self._y = np.empty(y.shape, dtype=np.int)\n for k in range(self._y.shape[1]):\n classes, self._y[:, k] = np.unique(y[:, k], return_inverse=True)\n self.classes_.append(classes)\n\n if not self.outputs_2d_:\n self.classes_ = self.classes_[0]\n self._y = self._y.ravel()\n\n return self._fit(X)\n\n\nclass UnsupervisedMixin(object):\n def fit(self, X, y=None):\n \"\"\"Fit the model using X as training data\n\n Parameters\n ----------\n X : {array-like, sparse matrix, BallTree, KDTree}\n Training data. If array or matrix, shape = [n_samples, n_features]\n \"\"\"\n return self._fit(X)\n",
"\"\"\"Testing for the boost module (sklearn.ensemble.boost).\"\"\"\n\nimport numpy as np\nfrom numpy.testing import assert_array_equal, assert_array_less\nfrom numpy.testing import assert_array_almost_equal\nfrom numpy.testing import assert_equal\nfrom nose.tools import assert_raises\n\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn.grid_search import GridSearchCV\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.ensemble import AdaBoostRegressor\nfrom scipy.sparse import csc_matrix\nfrom scipy.sparse import csr_matrix\nfrom scipy.sparse import coo_matrix\nfrom scipy.sparse import dok_matrix\nfrom scipy.sparse import lil_matrix\nfrom sklearn.svm import SVC, SVR\nfrom sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor\nfrom sklearn.utils import shuffle\nfrom sklearn import datasets\nimport time\n\n\n# Common random state\nrng = np.random.RandomState(0)\n\n# Toy sample\nX = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]]\ny_class = [\"foo\", \"foo\", \"foo\", 1, 1, 1] # test string class labels\ny_regr = [-1, -1, -1, 1, 1, 1]\nT = [[-1, -1], [2, 2], [3, 2]]\ny_t_class = [\"foo\", 1, 1]\ny_t_regr = [-1, 1, 1]\n\n# Load the iris dataset and randomly permute it\niris = datasets.load_iris()\nperm = rng.permutation(iris.target.size)\niris.data, iris.target = shuffle(iris.data, iris.target, random_state=rng)\n\n# Load the boston dataset and randomly permute it\nboston = datasets.load_boston()\nboston.data, boston.target = shuffle(boston.data, boston.target,\n random_state=rng)\n\n\ndef test_classification_toy():\n \"\"\"Check classification on a toy dataset.\"\"\"\n for alg in ['SAMME', 'SAMME.R']:\n clf = AdaBoostClassifier(algorithm=alg, random_state=0)\n clf.fit(X, y_class)\n assert_array_equal(clf.predict(T), y_t_class)\n assert_array_equal(np.unique(np.asarray(y_t_class)), clf.classes_)\n assert_equal(clf.predict_proba(T).shape, (len(T), 2))\n assert_equal(clf.decision_function(T).shape, (len(T),))\n\n\ndef test_regression_toy():\n \"\"\"Check classification on a toy dataset.\"\"\"\n clf = AdaBoostRegressor(random_state=0)\n clf.fit(X, y_regr)\n assert_array_equal(clf.predict(T), y_t_regr)\n\n\ndef test_iris():\n \"\"\"Check consistency on dataset iris.\"\"\"\n classes = np.unique(iris.target)\n clf_samme = prob_samme = None\n\n for alg in ['SAMME', 'SAMME.R']:\n clf = AdaBoostClassifier(algorithm=alg)\n clf.fit(iris.data, iris.target)\n\n assert_array_equal(classes, clf.classes_)\n proba = clf.predict_proba(iris.data)\n if alg == \"SAMME\":\n clf_samme = clf\n prob_samme = proba\n assert_equal(proba.shape[1], len(classes))\n assert_equal(clf.decision_function(iris.data).shape[1], len(classes))\n\n score = clf.score(iris.data, iris.target)\n assert score > 0.9, \"Failed with algorithm %s and score = %f\" % \\\n (alg, score)\n\n # Somewhat hacky regression test: prior to\n # ae7adc880d624615a34bafdb1d75ef67051b8200,\n # predict_proba returned SAMME.R values for SAMME.\n clf_samme.algorithm = \"SAMME.R\"\n assert_array_less(0,\n np.abs(clf_samme.predict_proba(iris.data) - prob_samme))\n\n\ndef test_boston():\n \"\"\"Check consistency on dataset boston house prices.\"\"\"\n clf = AdaBoostRegressor(random_state=0)\n clf.fit(boston.data, boston.target)\n score = clf.score(boston.data, boston.target)\n assert score > 0.85\n\n\ndef test_staged_predict():\n \"\"\"Check staged predictions.\"\"\"\n rng = np.random.RandomState(0)\n iris_weights = rng.randint(10, size=iris.target.shape)\n boston_weights = rng.randint(10, size=boston.target.shape)\n\n # AdaBoost classification\n for alg in ['SAMME', 'SAMME.R']:\n clf = AdaBoostClassifier(algorithm=alg, n_estimators=10)\n clf.fit(iris.data, iris.target, sample_weight=iris_weights)\n\n predictions = clf.predict(iris.data)\n staged_predictions = [p for p in clf.staged_predict(iris.data)]\n proba = clf.predict_proba(iris.data)\n staged_probas = [p for p in clf.staged_predict_proba(iris.data)]\n score = clf.score(iris.data, iris.target, sample_weight=iris_weights)\n staged_scores = [\n s for s in clf.staged_score(\n iris.data, iris.target, sample_weight=iris_weights)]\n\n assert_equal(len(staged_predictions), 10)\n assert_array_almost_equal(predictions, staged_predictions[-1])\n assert_equal(len(staged_probas), 10)\n assert_array_almost_equal(proba, staged_probas[-1])\n assert_equal(len(staged_scores), 10)\n assert_array_almost_equal(score, staged_scores[-1])\n\n # AdaBoost regression\n clf = AdaBoostRegressor(n_estimators=10, random_state=0)\n clf.fit(boston.data, boston.target, sample_weight=boston_weights)\n\n predictions = clf.predict(boston.data)\n staged_predictions = [p for p in clf.staged_predict(boston.data)]\n score = clf.score(boston.data, boston.target, sample_weight=boston_weights)\n staged_scores = [\n s for s in clf.staged_score(\n boston.data, boston.target, sample_weight=boston_weights)]\n\n assert_equal(len(staged_predictions), 10)\n assert_array_almost_equal(predictions, staged_predictions[-1])\n assert_equal(len(staged_scores), 10)\n assert_array_almost_equal(score, staged_scores[-1])\n\n\ndef test_gridsearch():\n \"\"\"Check that base trees can be grid-searched.\"\"\"\n # AdaBoost classification\n boost = AdaBoostClassifier(base_estimator=DecisionTreeClassifier())\n parameters = {'n_estimators': (1, 2),\n 'base_estimator__max_depth': (1, 2),\n 'algorithm': ('SAMME', 'SAMME.R')}\n clf = GridSearchCV(boost, parameters)\n clf.fit(iris.data, iris.target)\n\n # AdaBoost regression\n boost = AdaBoostRegressor(base_estimator=DecisionTreeRegressor(),\n random_state=0)\n parameters = {'n_estimators': (1, 2),\n 'base_estimator__max_depth': (1, 2)}\n clf = GridSearchCV(boost, parameters)\n clf.fit(boston.data, boston.target)\n\n\ndef test_pickle():\n \"\"\"Check pickability.\"\"\"\n import pickle\n\n # Adaboost classifier\n for alg in ['SAMME', 'SAMME.R']:\n obj = AdaBoostClassifier(algorithm=alg)\n obj.fit(iris.data, iris.target)\n score = obj.score(iris.data, iris.target)\n s = pickle.dumps(obj)\n\n obj2 = pickle.loads(s)\n assert_equal(type(obj2), obj.__class__)\n score2 = obj2.score(iris.data, iris.target)\n assert_equal(score, score2)\n\n # Adaboost regressor\n obj = AdaBoostRegressor(random_state=0)\n obj.fit(boston.data, boston.target)\n score = obj.score(boston.data, boston.target)\n s = pickle.dumps(obj)\n\n obj2 = pickle.loads(s)\n assert_equal(type(obj2), obj.__class__)\n score2 = obj2.score(boston.data, boston.target)\n assert_equal(score, score2)\n\n\ndef test_importances():\n \"\"\"Check variable importances.\"\"\"\n X, y = datasets.make_classification(n_samples=2000,\n n_features=10,\n n_informative=3,\n n_redundant=0,\n n_repeated=0,\n shuffle=False,\n random_state=1)\n\n for alg in ['SAMME', 'SAMME.R']:\n clf = AdaBoostClassifier(algorithm=alg)\n\n clf.fit(X, y)\n importances = clf.feature_importances_\n\n assert_equal(importances.shape[0], 10)\n assert_equal((importances[:3, np.newaxis] >= importances[3:]).all(),\n True)\n\n\ndef test_error():\n \"\"\"Test that it gives proper exception on deficient input.\"\"\"\n assert_raises(ValueError,\n AdaBoostClassifier(learning_rate=-1).fit,\n X, y_class)\n\n assert_raises(ValueError,\n AdaBoostClassifier(algorithm=\"foo\").fit,\n X, y_class)\n\n assert_raises(ValueError,\n AdaBoostClassifier().fit,\n X, y_class, sample_weight=np.asarray([-1]))\n\n\ndef test_base_estimator():\n \"\"\"Test different base estimators.\"\"\"\n from sklearn.ensemble import RandomForestClassifier\n from sklearn.svm import SVC\n\n # XXX doesn't work with y_class because RF doesn't support classes_\n # Shouldn't AdaBoost run a LabelBinarizer?\n clf = AdaBoostClassifier(RandomForestClassifier())\n clf.fit(X, y_regr)\n\n clf = AdaBoostClassifier(SVC(), algorithm=\"SAMME\")\n clf.fit(X, y_class)\n\n from sklearn.ensemble import RandomForestRegressor\n from sklearn.svm import SVR\n\n clf = AdaBoostRegressor(RandomForestRegressor(), random_state=0)\n clf.fit(X, y_regr)\n\n clf = AdaBoostRegressor(SVR(), random_state=0)\n clf.fit(X, y_regr)\n\n\ndef test_sparse_classification():\n \"\"\"Check classification with sparse input.\"\"\"\n\n class CustomSVC(SVC):\n \"\"\"SVC variant that records the nature of the training set.\"\"\"\n\n def fit(self, X, y, sample_weight=None):\n \"\"\"Modification on fit caries data type for later verification.\"\"\"\n super(CustomSVC, self).fit(X, y, sample_weight=sample_weight)\n self.data_type_ = type(X)\n return self\n\n X, y = datasets.make_multilabel_classification(n_classes=1, n_samples=100,\n n_features=50,\n return_indicator=True,\n random_state=42)\n # Flatten y to a 1d array\n y = np.ravel(y)\n\n X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)\n\n for sparse_format in [csc_matrix, csr_matrix, lil_matrix, coo_matrix,\n dok_matrix]:\n X_train_sparse = sparse_format(X_train)\n X_test_sparse = sparse_format(X_test)\n\n # Trained on sparse format\n sparse_classifier = AdaBoostClassifier(\n base_estimator=CustomSVC(probability=True),\n random_state=1,\n algorithm=\"SAMME\"\n ).fit(X_train_sparse, y_train)\n\n # Trained on dense format\n dense_classifier = AdaBoostClassifier(\n base_estimator=CustomSVC(probability=True),\n random_state=1,\n algorithm=\"SAMME\"\n ).fit(X_train, y_train)\n\n # predict\n sparse_results = sparse_classifier.predict(X_test_sparse)\n dense_results = dense_classifier.predict(X_test)\n assert_array_equal(sparse_results, dense_results)\n sparse_y_pred, dense_y_pred = sparse_results, dense_results\n\n # decision_function\n sparse_results = sparse_classifier.decision_function(X_test_sparse)\n dense_results = dense_classifier.decision_function(X_test)\n assert_array_equal(sparse_results, dense_results)\n\n # predict_log_proba\n sparse_results = sparse_classifier.predict_log_proba(X_test_sparse)\n dense_results = dense_classifier.predict_log_proba(X_test)\n assert_array_equal(sparse_results, dense_results)\n\n # predict_proba\n sparse_results = sparse_classifier.predict_proba(X_test_sparse)\n dense_results = dense_classifier.predict_proba(X_test)\n assert_array_equal(sparse_results, dense_results)\n\n # score\n sparse_results = sparse_classifier.score(X_test_sparse, y_test)\n dense_results = dense_classifier.score(X_test, y_test)\n assert_array_equal(sparse_results, dense_results)\n\n # staged_decision_function\n sparse_results = sparse_classifier.staged_decision_function(\n X_test_sparse)\n dense_results = dense_classifier.staged_decision_function(X_test)\n for sprase_res, dense_res in zip(sparse_results, dense_results):\n assert_array_equal(sprase_res, dense_res)\n\n # staged_predict\n sparse_results = sparse_classifier.staged_predict(X_test_sparse)\n dense_results = dense_classifier.staged_predict(X_test)\n for sprase_res, dense_res in zip(sparse_results, dense_results):\n assert_array_equal(sprase_res, dense_res)\n\n # staged_predict_proba\n sparse_results = sparse_classifier.staged_predict_proba(X_test_sparse)\n dense_results = dense_classifier.staged_predict_proba(X_test)\n for sprase_res, dense_res in zip(sparse_results, dense_results):\n assert_array_equal(sprase_res, dense_res)\n\n # staged_score\n sparse_results = sparse_classifier.staged_score(X_test_sparse,\n y_test)\n dense_results = dense_classifier.staged_score(X_test, y_test)\n for sprase_res, dense_res in zip(sparse_results, dense_results):\n assert_array_equal(sprase_res, dense_res)\n\n # Verify sparsity of data is maintained during training\n sparse_type = type(X_train_sparse)\n types = [i.data_type_ for i in sparse_classifier.estimators_]\n\n assert all([(t == csc_matrix or t == csr_matrix)\n for t in types])\n\n\ndef test_sparse_regression():\n \"\"\"Check regression with sparse input.\"\"\"\n\n class CustomSVR(SVR):\n \"\"\"SVR variant that records the nature of the training set.\"\"\"\n\n def fit(self, X, y, sample_weight=None):\n \"\"\"Modification on fit caries data type for later verification.\"\"\"\n super(CustomSVR, self).fit(X, y, sample_weight=sample_weight)\n self.data_type_ = type(X)\n return self\n\n X, y = datasets.make_regression(n_samples=100, n_features=50, n_targets=1,\n random_state=42)\n\n X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)\n\n for sparse_format in [csc_matrix, csr_matrix, lil_matrix, coo_matrix,\n dok_matrix]:\n X_train_sparse = sparse_format(X_train)\n X_test_sparse = sparse_format(X_test)\n\n # Trained on sparse format\n sparse_classifier = AdaBoostRegressor(\n base_estimator=CustomSVR(probability=True),\n random_state=1\n ).fit(X_train_sparse, y_train)\n\n # Trained on dense format\n dense_classifier = dense_results = AdaBoostRegressor(\n base_estimator=CustomSVR(probability=True),\n random_state=1\n ).fit(X_train, y_train)\n\n # predict\n sparse_results = sparse_classifier.predict(X_test_sparse)\n dense_results = dense_classifier.predict(X_test)\n assert_array_equal(sparse_results, dense_results)\n\n # staged_predict\n sparse_results = sparse_classifier.staged_predict(X_test_sparse)\n dense_results = dense_classifier.staged_predict(X_test)\n for sprase_res, dense_res in zip(sparse_results, dense_results):\n assert_array_equal(sprase_res, dense_res)\n\n sparse_type = type(X_train_sparse)\n types = [i.data_type_ for i in sparse_classifier.estimators_]\n\n assert all([(t == csc_matrix or t == csr_matrix)\n for t in types])\n\n\nif __name__ == \"__main__\":\n import nose\n nose.runmodule()\n"
] | [
[
"numpy.all",
"numpy.set_printoptions",
"scipy.sparse.issparse",
"numpy.get_printoptions"
],
[
"numpy.sum",
"numpy.unique",
"numpy.cumsum",
"numpy.any",
"numpy.prod",
"numpy.array",
"numpy.zeros",
"sklearn.utils.check_random_state",
"numpy.empty"
],
[
"scipy.sparse.issparse",
"numpy.sqrt",
"numpy.unique",
"numpy.asarray",
"numpy.arange",
"numpy.cumsum",
"scipy.sparse.csr_matrix",
"numpy.ones",
"numpy.where",
"numpy.errstate",
"numpy.argsort",
"numpy.zeros",
"numpy.sum",
"numpy.empty"
],
[
"sklearn.ensemble.RandomForestRegressor",
"sklearn.cross_validation.train_test_split",
"sklearn.datasets.make_classification",
"numpy.asarray",
"sklearn.tree.DecisionTreeClassifier",
"sklearn.datasets.load_boston",
"numpy.testing.assert_equal",
"sklearn.ensemble.RandomForestClassifier",
"numpy.unique",
"numpy.ravel",
"numpy.testing.assert_array_almost_equal",
"sklearn.datasets.load_iris",
"sklearn.grid_search.GridSearchCV",
"sklearn.svm.SVR",
"sklearn.ensemble.AdaBoostClassifier",
"sklearn.datasets.make_multilabel_classification",
"sklearn.svm.SVC",
"numpy.random.RandomState",
"sklearn.tree.DecisionTreeRegressor",
"sklearn.utils.shuffle",
"numpy.testing.assert_array_equal",
"sklearn.datasets.make_regression",
"sklearn.ensemble.AdaBoostRegressor"
]
] | [
{
"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": [],
"tensorflow": []
},
{
"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": [],
"tensorflow": []
}
] |
jupiterman/Data-Transfer-Neural-Way | [
"d900a5552c78f81450c3918640aa3e9210a57488"
] | [
"script_helper/Script/Network.py"
] | [
"from __future__ import print_function\nfrom __future__ import division\nfrom __future__ import absolute_import\n\nfrom scipy.misc import imread, imresize, imsave, fromimage, toimage\nfrom scipy.optimize import fmin_l_bfgs_b\nimport numpy as np\nimport time\nimport argparse\nimport warnings\n\nfrom keras.models import Model\nfrom keras.layers import Input\nfrom keras.layers.convolutional import Convolution2D, AveragePooling2D, MaxPooling2D\nfrom keras import backend as K\nfrom keras.utils.data_utils import get_file\nfrom keras.utils.layer_utils import convert_all_kernels_in_model\n\n\"\"\"\nNeural Style Transfer with Keras 2.0.5\n\nBased on:\nhttps://github.com/fchollet/keras/blob/master/examples/neural_style_transfer.py\n\n-----------------------------------------------------------------------------------------------------------------------\n\"\"\"\n\nTHEANO_WEIGHTS_PATH_NO_TOP = 'https://github.com/fchollet/deep-learning-models/releases/download/v0.1/vgg16_weights_th_dim_ordering_th_kernels_notop.h5'\nTF_WEIGHTS_PATH_NO_TOP = 'https://github.com/fchollet/deep-learning-models/releases/download/v0.1/vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5'\n\nTH_19_WEIGHTS_PATH_NO_TOP = 'https://github.com/fchollet/deep-learning-models/releases/download/v0.1/vgg19_weights_th_dim_ordering_th_kernels_notop.h5'\nTF_19_WEIGHTS_PATH_NO_TOP = 'https://github.com/fchollet/deep-learning-models/releases/download/v0.1/vgg19_weights_tf_dim_ordering_tf_kernels_notop.h5'\n\n\nparser = argparse.ArgumentParser(description='Neural style transfer with Keras.')\nparser.add_argument('base_image_path', metavar='base', type=str,\n help='Path to the image to transform.')\n\nparser.add_argument('syle_image_paths', metavar='ref', nargs='+', type=str,\n help='Path to the style reference image.')\n\nparser.add_argument('result_prefix', metavar='res_prefix', type=str,\n help='Prefix for the saved results.')\n\nparser.add_argument(\"--style_masks\", type=str, default=None, nargs='+',\n help='Masks for style images')\n\nparser.add_argument(\"--content_mask\", type=str, default=None,\n help='Masks for the content image')\n\nparser.add_argument(\"--color_mask\", type=str, default=None,\n help='Mask for color preservation')\n\nparser.add_argument(\"--image_size\", dest=\"img_size\", default=400, type=int,\n help='Minimum image size')\n\nparser.add_argument(\"--content_weight\", dest=\"content_weight\", default=0.025, type=float,\n help=\"Weight of content\")\n\nparser.add_argument(\"--style_weight\", dest=\"style_weight\", nargs='+', default=[1], type=float,\n help=\"Weight of style, can be multiple for multiple styles\")\n\nparser.add_argument(\"--style_scale\", dest=\"style_scale\", default=1.0, type=float,\n help=\"Scale the weighing of the style\")\n\nparser.add_argument(\"--total_variation_weight\", dest=\"tv_weight\", default=8.5e-5, type=float,\n help=\"Total Variation weight\")\n\nparser.add_argument(\"--num_iter\", dest=\"num_iter\", default=10, type=int,\n help=\"Number of iterations\")\n\nparser.add_argument(\"--model\", default=\"vgg16\", type=str,\n help=\"Choices are 'vgg16' and 'vgg19'\")\n\nparser.add_argument(\"--content_loss_type\", default=0, type=int,\n help='Can be one of 0, 1 or 2. Readme contains the required information of each mode.')\n\nparser.add_argument(\"--rescale_image\", dest=\"rescale_image\", default=\"False\", type=str,\n help=\"Rescale image after execution to original dimentions\")\n\nparser.add_argument(\"--rescale_method\", dest=\"rescale_method\", default=\"bilinear\", type=str,\n help=\"Rescale image algorithm\")\n\nparser.add_argument(\"--maintain_aspect_ratio\", dest=\"maintain_aspect_ratio\", default=\"True\", type=str,\n help=\"Maintain aspect ratio of loaded images\")\n\nparser.add_argument(\"--content_layer\", dest=\"content_layer\", default=\"conv5_2\", type=str,\n help=\"Content layer used for content loss.\")\n\nparser.add_argument(\"--init_image\", dest=\"init_image\", default=\"content\", type=str,\n help=\"Initial image used to generate the final image. Options are 'content', 'noise', or 'gray'\")\n\nparser.add_argument(\"--pool_type\", dest=\"pool\", default=\"max\", type=str,\n help='Pooling type. Can be \"ave\" for average pooling or \"max\" for max pooling')\n\nparser.add_argument('--preserve_color', dest='color', default=\"False\", type=str,\n help='Preserve original color in image')\n\nparser.add_argument('--min_improvement', default=0.0, type=float,\n help='Defines minimum improvement required to continue script')\n\n\ndef str_to_bool(v):\n return v.lower() in (\"true\", \"yes\", \"t\", \"1\")\n\n''' Arguments '''\n\nargs = parser.parse_args()\nbase_image_path = args.base_image_path\nstyle_reference_image_paths = args.syle_image_paths\nresult_prefix = args.result_prefix\n\nstyle_image_paths = []\nfor style_image_path in style_reference_image_paths:\n style_image_paths.append(style_image_path)\n\nstyle_masks_present = args.style_masks is not None\nmask_paths = []\n\nif style_masks_present:\n for mask_path in args.style_masks:\n mask_paths.append(mask_path)\n\nif style_masks_present:\n assert len(style_image_paths) == len(mask_paths), \"Wrong number of style masks provided.\\n\" \\\n \"Number of style images = %d, \\n\" \\\n \"Number of style mask paths = %d.\" % \\\n (len(style_image_paths), len(style_masks_present))\n\ncontent_mask_present = args.content_mask is not None\ncontent_mask_path = args.content_mask\n\n\ncolor_mask_present = args.color_mask is not None\n\nrescale_image = str_to_bool(args.rescale_image)\nmaintain_aspect_ratio = str_to_bool(args.maintain_aspect_ratio)\npreserve_color = str_to_bool(args.color)\n\n# these are the weights of the different loss components\ncontent_weight = args.content_weight\ntotal_variation_weight = args.tv_weight\n\nstyle_weights = []\n\nif len(style_image_paths) != len(args.style_weight):\n print(\"Mismatch in number of style images provided and number of style weights provided. \\n\"\n \"Found %d style images and %d style weights. \\n\"\n \"Equally distributing weights to all other styles.\" % (len(style_image_paths), len(args.style_weight)))\n\n weight_sum = sum(args.style_weight) * args.style_scale\n count = len(style_image_paths)\n\n for i in range(len(style_image_paths)):\n style_weights.append(weight_sum / count)\nelse:\n for style_weight in args.style_weight:\n style_weights.append(style_weight * args.style_scale)\n\n# Decide pooling function\npooltype = str(args.pool).lower()\nassert pooltype in [\"ave\", \"max\"], 'Pooling argument is wrong. Needs to be either \"ave\" or \"max\".'\n\npooltype = 1 if pooltype == \"ave\" else 0\n\nread_mode = \"gray\" if args.init_image == \"gray\" else \"color\"\n\n# dimensions of the generated picture.\nimg_width = img_height = 0\n\nimg_WIDTH = img_HEIGHT = 0\naspect_ratio = 0\n\nassert args.content_loss_type in [0, 1, 2], \"Content Loss Type must be one of 0, 1 or 2\"\n\n\n# util function to open, resize and format pictures into appropriate tensors\ndef preprocess_image(image_path, load_dims=False, read_mode=\"color\"):\n global img_width, img_height, img_WIDTH, img_HEIGHT, aspect_ratio\n\n mode = \"RGB\" if read_mode == \"color\" else \"L\"\n img = imread(image_path, mode=mode) # Prevents crashes due to PNG images (ARGB)\n\n if mode == \"L\":\n # Expand the 1 channel grayscale to 3 channel grayscale image\n temp = np.zeros(img.shape + (3,), dtype=np.uint8)\n temp[:, :, 0] = img\n temp[:, :, 1] = img.copy()\n temp[:, :, 2] = img.copy()\n\n img = temp\n\n if load_dims:\n img_WIDTH = img.shape[0]\n img_HEIGHT = img.shape[1]\n aspect_ratio = float(img_HEIGHT) / img_WIDTH\n\n img_width = args.img_size\n if maintain_aspect_ratio:\n img_height = int(img_width * aspect_ratio)\n else:\n img_height = args.img_size\n\n img = imresize(img, (img_width, img_height)).astype('float32')\n\n # RGB -> BGR\n img = img[:, :, ::-1]\n\n img[:, :, 0] -= 103.939\n img[:, :, 1] -= 116.779\n img[:, :, 2] -= 123.68\n\n if K.image_dim_ordering() == \"th\":\n img = img.transpose((2, 0, 1)).astype('float32')\n\n img = np.expand_dims(img, axis=0)\n return img\n\n\n# util function to convert a tensor into a valid image\ndef deprocess_image(x):\n if K.image_dim_ordering() == \"th\":\n x = x.reshape((3, img_width, img_height))\n x = x.transpose((1, 2, 0))\n else:\n x = x.reshape((img_width, img_height, 3))\n\n x[:, :, 0] += 103.939\n x[:, :, 1] += 116.779\n x[:, :, 2] += 123.68\n\n # BGR -> RGB\n x = x[:, :, ::-1]\n\n x = np.clip(x, 0, 255).astype('uint8')\n return x\n\n\n# util function to preserve image color\ndef original_color_transform(content, generated, mask=None):\n generated = fromimage(toimage(generated, mode='RGB'), mode='YCbCr') # Convert to YCbCr color space\n\n if mask is None:\n generated[:, :, 1:] = content[:, :, 1:] # Generated CbCr = Content CbCr\n else:\n width, height, channels = generated.shape\n\n for i in range(width):\n for j in range(height):\n if mask[i, j] == 1:\n generated[i, j, 1:] = content[i, j, 1:]\n\n generated = fromimage(toimage(generated, mode='YCbCr'), mode='RGB') # Convert to RGB color space\n return generated\n\n\ndef load_mask(mask_path, shape, return_mask_img=False):\n if K.image_dim_ordering() == \"th\":\n _, channels, width, height = shape\n else:\n _, width, height, channels = shape\n\n mask = imread(mask_path, mode=\"L\") # Grayscale mask load\n mask = imresize(mask, (width, height)).astype('float32')\n\n # Perform binarization of mask\n mask[mask <= 127] = 0\n mask[mask > 128] = 255\n\n max = np.amax(mask)\n mask /= max\n\n if return_mask_img: return mask\n\n mask_shape = shape[1:]\n\n mask_tensor = np.empty(mask_shape)\n\n for i in range(channels):\n if K.image_dim_ordering() == \"th\":\n mask_tensor[i, :, :] = mask\n else:\n mask_tensor[:, :, i] = mask\n\n return mask_tensor\n\n\ndef pooling_func(x):\n if pooltype == 1:\n return AveragePooling2D((2, 2), strides=(2, 2))(x)\n else:\n return MaxPooling2D((2, 2), strides=(2, 2))(x)\n\n\n# get tensor representations of our images\nbase_image = K.variable(preprocess_image(base_image_path, True, read_mode=read_mode))\n\nstyle_reference_images = []\nfor style_path in style_image_paths:\n style_reference_images.append(K.variable(preprocess_image(style_path)))\n\n# this will contain our generated image\nif K.image_dim_ordering() == 'th':\n combination_image = K.placeholder((1, 3, img_width, img_height))\nelse:\n combination_image = K.placeholder((1, img_width, img_height, 3))\n\nimage_tensors = [base_image]\nfor style_image_tensor in style_reference_images:\n image_tensors.append(style_image_tensor)\nimage_tensors.append(combination_image)\n\nnb_tensors = len(image_tensors)\nnb_style_images = nb_tensors - 2 # Content and Output image not considered\n\n# combine the various images into a single Keras tensor\ninput_tensor = K.concatenate(image_tensors, axis=0)\n\nif K.image_dim_ordering() == \"th\":\n shape = (nb_tensors, 3, img_width, img_height)\nelse:\n shape = (nb_tensors, img_width, img_height, 3)\n\nip = Input(tensor=input_tensor, batch_shape=shape)\n\n# build the VGG16 network with our 3 images as input\nx = Convolution2D(64, (3, 3), activation='relu', name='conv1_1', padding='same')(ip)\nx = Convolution2D(64, (3, 3), activation='relu', name='conv1_2', padding='same')(x)\nx = pooling_func(x)\n\nx = Convolution2D(128, (3, 3), activation='relu', name='conv2_1', padding='same')(x)\nx = Convolution2D(128, (3, 3), activation='relu', name='conv2_2', padding='same')(x)\nx = pooling_func(x)\n\nx = Convolution2D(256, (3, 3), activation='relu', name='conv3_1', padding='same')(x)\nx = Convolution2D(256, (3, 3), activation='relu', name='conv3_2', padding='same')(x)\nx = Convolution2D(256, (3, 3), activation='relu', name='conv3_3', padding='same')(x)\nif args.model == \"vgg19\":\n x = Convolution2D(256, (3, 3), activation='relu', name='conv3_4', padding='same')(x)\nx = pooling_func(x)\n\nx = Convolution2D(512, (3, 3), activation='relu', name='conv4_1', padding='same')(x)\nx = Convolution2D(512, (3, 3), activation='relu', name='conv4_2', padding='same')(x)\nx = Convolution2D(512, (3, 3), activation='relu', name='conv4_3', padding='same')(x)\nif args.model == \"vgg19\":\n x = Convolution2D(512, (3, 3), activation='relu', name='conv4_4', padding='same')(x)\nx = pooling_func(x)\n\nx = Convolution2D(512, (3, 3), activation='relu', name='conv5_1', padding='same')(x)\nx = Convolution2D(512, (3, 3), activation='relu', name='conv5_2', padding='same')(x)\nx = Convolution2D(512, (3, 3), activation='relu', name='conv5_3', padding='same')(x)\nif args.model == \"vgg19\":\n x = Convolution2D(512, (3, 3), activation='relu', name='conv5_4', padding='same')(x)\nx = pooling_func(x)\n\nmodel = Model(ip, x)\n\nif K.image_dim_ordering() == \"th\":\n if args.model == \"vgg19\":\n weights = get_file('vgg19_weights_th_dim_ordering_th_kernels_notop.h5', TH_19_WEIGHTS_PATH_NO_TOP, cache_subdir='models')\n else:\n weights = get_file('vgg16_weights_th_dim_ordering_th_kernels_notop.h5', THEANO_WEIGHTS_PATH_NO_TOP, cache_subdir='models')\nelse:\n if args.model == \"vgg19\":\n weights = get_file('vgg19_weights_tf_dim_ordering_tf_kernels_notop.h5', TF_19_WEIGHTS_PATH_NO_TOP, cache_subdir='models')\n else:\n weights = get_file('vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5', TF_WEIGHTS_PATH_NO_TOP, cache_subdir='models')\n\nmodel.load_weights(weights)\n\nif K.backend() == 'tensorflow' and K.image_dim_ordering() == \"th\":\n warnings.warn('You are using the TensorFlow backend, yet you '\n 'are using the Theano '\n 'image dimension ordering convention '\n '(`image_dim_ordering=\"th\"`). '\n 'For best performance, set '\n '`image_dim_ordering=\"tf\"` in '\n 'your Keras config '\n 'at ~/.keras/keras.json.')\n convert_all_kernels_in_model(model)\n\nprint('Model loaded.')\n\n# get the symbolic outputs of each \"key\" layer (we gave them unique names).\noutputs_dict = dict([(layer.name, layer.output) for layer in model.layers])\nshape_dict = dict([(layer.name, layer.output_shape) for layer in model.layers])\n\n# compute the neural style loss\n# first we need to define 4 util functions\n\n# the gram matrix of an image tensor (feature-wise outer product)\ndef gram_matrix(x):\n assert K.ndim(x) == 3\n if K.image_dim_ordering() == \"th\":\n features = K.batch_flatten(x)\n else:\n features = K.batch_flatten(K.permute_dimensions(x, (2, 0, 1)))\n gram = K.dot(features, K.transpose(features))\n return gram\n\n\n# the \"style loss\" is designed to maintain\n# the style of the reference image in the generated image.\n# It is based on the gram matrices (which capture style) of\n# feature maps from the style reference image\n# and from the generated image\ndef style_loss(style, combination, mask_path=None, nb_channels=None):\n assert K.ndim(style) == 3\n assert K.ndim(combination) == 3\n\n if content_mask_path is not None:\n content_mask = K.variable(load_mask(content_mask_path, nb_channels))\n combination = combination * K.stop_gradient(content_mask)\n del content_mask\n\n if mask_path is not None:\n style_mask = K.variable(load_mask(mask_path, nb_channels))\n style = style * K.stop_gradient(style_mask)\n if content_mask_path is None:\n combination = combination * K.stop_gradient(style_mask)\n del style_mask\n\n S = gram_matrix(style)\n C = gram_matrix(combination)\n channels = 3\n size = img_width * img_height\n return K.sum(K.square(S - C)) / (4. * (channels ** 2) * (size ** 2))\n\n\n# an auxiliary loss function\n# designed to maintain the \"content\" of the\n# base image in the generated image\ndef content_loss(base, combination):\n channel_dim = 0 if K.image_dim_ordering() == \"th\" else -1\n\n try:\n channels = K.int_shape(base)[channel_dim]\n except TypeError:\n channels = K.shape(base)[channel_dim]\n size = img_width * img_height\n\n if args.content_loss_type == 1:\n multiplier = 1. / (2. * (channels ** 0.5) * (size ** 0.5))\n elif args.content_loss_type == 2:\n multiplier = 1. / (channels * size)\n else:\n multiplier = 1.\n\n return multiplier * K.sum(K.square(combination - base))\n\n\n# the 3rd loss function, total variation loss,\n# designed to keep the generated image locally coherent\ndef total_variation_loss(x):\n assert K.ndim(x) == 4\n if K.image_dim_ordering() == 'th':\n a = K.square(x[:, :, :img_width - 1, :img_height - 1] - x[:, :, 1:, :img_height - 1])\n b = K.square(x[:, :, :img_width - 1, :img_height - 1] - x[:, :, :img_width - 1, 1:])\n else:\n a = K.square(x[:, :img_width - 1, :img_height - 1, :] - x[:, 1:, :img_height - 1, :])\n b = K.square(x[:, :img_width - 1, :img_height - 1, :] - x[:, :img_width - 1, 1:, :])\n return K.sum(K.pow(a + b, 1.25))\n\n\n# combine these loss functions into a single scalar\nloss = K.variable(0.)\nlayer_features = outputs_dict[args.content_layer] # 'conv5_2' or 'conv4_2'\nbase_image_features = layer_features[0, :, :, :]\ncombination_features = layer_features[nb_tensors - 1, :, :, :]\nloss += content_weight * content_loss(base_image_features,\n combination_features)\nstyle_masks = []\nif style_masks_present:\n style_masks = mask_paths # If mask present, pass dictionary of masks to style loss\nelse:\n style_masks = [None for _ in range(nb_style_images)] # If masks not present, pass None to the style loss\n\nchannel_index = 1 if K.image_dim_ordering() == \"th\" else -1\n\nfeature_layers = ['conv1_1', 'conv2_1', 'conv3_1', 'conv4_1', 'conv5_1']\nfor layer_name in feature_layers:\n layer_features = outputs_dict[layer_name]\n shape = shape_dict[layer_name]\n combination_features = layer_features[nb_tensors - 1, :, :, :]\n\n style_reference_features = layer_features[1:nb_tensors - 1, :, :, :]\n sl = []\n for j in range(nb_style_images):\n sl.append(style_loss(style_reference_features[j], combination_features, style_masks[j], shape))\n\n for j in range(nb_style_images):\n loss += (style_weights[j] / len(feature_layers)) * sl[j]\n\nloss += total_variation_weight * total_variation_loss(combination_image)\n\n# get the gradients of the generated image wrt the loss\ngrads = K.gradients(loss, combination_image)\n\noutputs = [loss]\nif type(grads) in {list, tuple}:\n outputs += grads\nelse:\n outputs.append(grads)\n\nf_outputs = K.function([combination_image], outputs)\n\n\ndef eval_loss_and_grads(x):\n if K.image_dim_ordering() == 'th':\n x = x.reshape((1, 3, img_width, img_height))\n else:\n x = x.reshape((1, img_width, img_height, 3))\n outs = f_outputs([x])\n loss_value = outs[0]\n if len(outs[1:]) == 1:\n grad_values = outs[1].flatten().astype('float64')\n else:\n grad_values = np.array(outs[1:]).flatten().astype('float64')\n return loss_value, grad_values\n\n\n# this Evaluator class makes it possible\n# to compute loss and gradients in one pass\n# while retrieving them via two separate functions,\n# \"loss\" and \"grads\". This is done because scipy.optimize\n# requires separate functions for loss and gradients,\n# but computing them separately would be inefficient.\nclass Evaluator(object):\n def __init__(self):\n self.loss_value = None\n self.grads_values = None\n\n def loss(self, x):\n assert self.loss_value is None\n loss_value, grad_values = eval_loss_and_grads(x)\n self.loss_value = loss_value\n self.grad_values = grad_values\n return self.loss_value\n\n def grads(self, x):\n assert self.loss_value is not None\n grad_values = np.copy(self.grad_values)\n self.loss_value = None\n self.grad_values = None\n return grad_values\n\n\nevaluator = Evaluator()\n\n# run scipy-based optimization (L-BFGS) over the pixels of the generated image\n# so as to minimize the neural style loss\n\n\nif \"content\" in args.init_image or \"gray\" in args.init_image:\n x = preprocess_image(base_image_path, True, read_mode=read_mode)\nelif \"noise\" in args.init_image:\n x = np.random.uniform(0, 255, (1, img_width, img_height, 3)) - 128.\n\n if K.image_dim_ordering() == \"th\":\n x = x.transpose((0, 3, 1, 2))\nelse:\n print(\"Using initial image : \", args.init_image)\n x = preprocess_image(args.init_image, read_mode=read_mode)\n\n# We require original image if we are to preserve color in YCbCr mode\nif preserve_color:\n content = imread(base_image_path, mode=\"YCbCr\")\n content = imresize(content, (img_width, img_height))\n\n if color_mask_present:\n if K.image_dim_ordering() == \"th\":\n color_mask_shape = (None, None, img_width, img_height)\n else:\n color_mask_shape = (None, img_width, img_height, None)\n\n color_mask = load_mask(args.color_mask, color_mask_shape, return_mask_img=True)\n else:\n color_mask = None\nelse:\n color_mask = None\n\nnum_iter = args.num_iter\nprev_min_val = -1\n\nimprovement_threshold = float(args.min_improvement)\n\nfor i in range(num_iter):\n print(\"Starting iteration %d of %d\" % ((i + 1), num_iter))\n start_time = time.time()\n\n x, min_val, info = fmin_l_bfgs_b(evaluator.loss, x.flatten(), fprime=evaluator.grads, maxfun=20)\n\n if prev_min_val == -1:\n prev_min_val = min_val\n\n improvement = (prev_min_val - min_val) / prev_min_val * 100\n\n print('Current loss value:', min_val, \" Improvement : %0.3f\" % improvement, \"%\")\n prev_min_val = min_val\n # save current generated image\n img = deprocess_image(x.copy())\n\n if preserve_color and content is not None:\n img = original_color_transform(content, img, mask=color_mask)\n\n if not rescale_image:\n img_ht = int(img_width * aspect_ratio)\n print(\"Rescaling Image to (%d, %d)\" % (img_width, img_ht))\n img = imresize(img, (img_width, img_ht), interp=args.rescale_method)\n\n if rescale_image:\n print(\"Rescaling Image to (%d, %d)\" % (img_WIDTH, img_HEIGHT))\n img = imresize(img, (img_WIDTH, img_HEIGHT), interp=args.rescale_method)\n\n fname = result_prefix + '_at_iteration_%d.png' % (i + 1)\n imsave(fname, img)\n end_time = time.time()\n print('Image saved as', fname)\n print('Iteration %d completed in %ds' % (i + 1, end_time - start_time))\n\n if improvement_threshold is not 0.0:\n if improvement < improvement_threshold and improvement is not 0.0:\n print(\"Improvement (%f) is less than improvement threshold (%f). Early stopping script.\" % (\n improvement, improvement_threshold))\n exit()\n"
] | [
[
"numpy.amax",
"numpy.expand_dims",
"scipy.misc.imresize",
"scipy.misc.toimage",
"numpy.clip",
"scipy.misc.imsave",
"numpy.copy",
"scipy.misc.imread",
"numpy.random.uniform",
"numpy.array",
"numpy.zeros",
"numpy.empty"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"0.14",
"0.15",
"0.10",
"0.16",
"0.19",
"0.18",
"0.12",
"1.0",
"0.17",
"1.2"
],
"tensorflow": []
}
] |
Hazboun6/pta_sim | [
"cf8676e23056586ecb35a030dbaad45a1f985764",
"cf8676e23056586ecb35a030dbaad45a1f985764"
] | [
"pta_sim/pint_sim.py",
"pta_sim/scripts/ng12p5yr_nm_b1937_r4a.py"
] | [
"#!/usr/bin/env python\n# coding: utf-8\nimport numpy as np\nimport astropy.units as u\nfrom astropy.time import Time, TimeDelta\n\nfrom pint.residuals import resids\nimport pint.toa as toa\nfrom pint import models\n\n__all__ = ['make_ideal',\n 'createfourierdesignmatrix_red',\n 'add_rednoise',\n 'add_dm_rednoise',\n 'add_efac',\n 'add_equad',\n 'add_ecorr']\n\ndef make_ideal(toas, model, iterations=2):\n '''\n Takes a pint.toas and pint.model object and effectively zeros out the residuals.\n '''\n for ii in range(iterations):\n rs=resids(toas, model)\n toas.adjust_TOAs(TimeDelta(-1.0*rs.time_resids))\n\ndef createfourierdesignmatrix_red(toas, nmodes=30, Tspan=None,\n logf=False, fmin=None, fmax=None,\n pshift=False, modes=None):\n \"\"\"\n Construct fourier design matrix from eq 11 of Lentati et al, 2013\n\n Parameters\n ----------\n\n toas : array\n Vector of time series in seconds.\n\n nmodes : int\n Number of fourier coefficients to use.\n\n Tspan : float\n Option to us some other Tspan [s]\n\n logf : bool\n Use log frequency spacing.\n\n fmin : float\n Lower sampling frequency.\n\n fmax : float\n Upper sampling frequency.\n\n pshift : bool\n Option to add random phase shift.\n\n modes : array\n Option to provide explicit list or array of sampling frequencies.\n\n Returns\n -------\n F : array\n fourier design matrix, [NTOAs x 2 nfreqs].\n f : arraty\n Sampling frequencies, [2 nfreqs].\n \"\"\"\n\n T = Tspan if Tspan is not None else toas.max() - toas.min()\n\n # define sampling frequencies\n if modes is not None:\n nmodes = len(modes)\n f = modes\n elif fmin is None and fmax is None and not logf:\n # make sure partially overlapping sets of modes\n # have identical frequencies\n f = 1.0 * np.arange(1, nmodes + 1) / T\n else:\n # more general case\n\n if fmin is None:\n fmin = 1 / T\n\n if fmax is None:\n fmax = nmodes / T\n\n if logf:\n f = np.logspace(np.log10(fmin), np.log10(fmax), nmodes)\n else:\n f = np.linspace(fmin, fmax, nmodes)\n\n # add random phase shift to basis functions\n ranphase = (np.random.uniform(0.0, 2 * np.pi, nmodes)\n if pshift else np.zeros(nmodes))\n\n Ffreqs = np.repeat(f, 2)\n\n N = len(toas)\n F = np.zeros((N, 2 * nmodes))\n\n # The sine/cosine modes\n F[:,::2] = np.sin(2*np.pi*toas[:,None]*f[None,:] +\n ranphase[None,:])\n F[:,1::2] = np.cos(2*np.pi*toas[:,None]*f[None,:] +\n ranphase[None,:])\n\n return F, Ffreqs\n\ndef add_rednoise(TOAs, A, gamma, components=30,\n seed=None, modes=None, Tspan=None):\n \"\"\"Add red noise with P(f) = A^2 / (12 pi^2) (f * year)^-gamma,\n using `components` Fourier bases.\n Optionally take a pseudorandom-number-generator seed.\"\"\"\n\n # nobs=len(psr.toas)\n nobs = len(TOAs.table)\n\n day_in_sec = 86400\n year_in_sec = 365.25*day_in_sec\n fyr = 1 / year_in_sec\n\n if seed is not None:\n np.random.seed(seed)\n if modes is not None:\n print('Must use linear spacing.')\n\n toas = np.array(TOAs.table['tdbld'], dtype='float64') * day_in_sec #to sec\n Tspan = toas.max() - toas.min()\n F, freqs = createfourierdesignmatrix_red(toas,Tspan=Tspan,modes=modes)\n prior = A**2 * (freqs/fyr)**(-gamma) / (12 * np.pi**2 * Tspan) * year_in_sec**3\n y = np.sqrt(prior) * np.random.randn(freqs.size)\n dt = np.dot(F,y) * u.s\n TOAs.adjust_TOAs(TimeDelta(dt.to('day')))\n\ndef add_dm_rednoise(TOAs, A, gamma, components=30, rf_ref=1400,\n seed=None, modes=None, Tspan=None, useDM=False):\n \"\"\"Add red noise with P(f) = A^2 / (12 pi^2) (f year)^-gamma,\n using `components` Fourier bases.\n Optionally take a pseudorandom-number-generator seed.\"\"\"\n\n # nobs=len(psr.toas)\n nobs = len(TOAs.table)\n radio_freqs = TOAs.table['freq']\n if useDM:\n rf_ref = 4.15e3\n chrom = rf_ref**2 / radio_freqs**2\n day_in_sec = 86400\n year_in_sec = 365.25*day_in_sec\n fyr = 1 / year_in_sec\n\n if seed is not None:\n np.random.seed(seed)\n\n toas = np.array(TOAs.table['tdbld'], dtype='float64') * day_in_sec #to sec\n\n Tspan = toas.max() - toas.min()\n\n F, freqs = createfourierdesignmatrix_red(toas,Tspan=Tspan,modes=modes)\n prior = A**2 * (freqs/fyr)**(-gamma) / (12 * np.pi**2 * Tspan) * year_in_sec**3\n\n y = np.sqrt(prior) * np.random.randn(freqs.size)\n dt = chrom.quantity.value * np.dot(F,y) * u.s\n TOAs.adjust_TOAs(TimeDelta(dt.to('day')))\n\ndef add_equad(TOAs, equad, flagid=None, flags=None, seed=None):\n \"\"\"Add quadrature noise of rms `equad` [s].\n Optionally take a pseudorandom-number-generator seed.\"\"\"\n\n if seed is not None:\n np.random.seed(seed)\n\n # default equadvec\n equadvec = np.zeros(TOAs.ntoas)\n\n # check that equad is scalar if flags is None\n if flags is None:\n if not np.isscalar(equad):\n raise ValueError('ERROR: If flags is None, equad must be a scalar')\n else:\n equadvec = np.ones(TOAs.ntoas) * equad\n\n if flags is not None and flagid is not None and not np.isscalar(equad):\n if len(equad) == len(flags):\n for ct, flag in enumerate(flags):\n ind = flag == np.array([f['f'] for f\n in TOAs.table['flags'].data])\n equadvec[ind] = equad[ct]\n\n equadvec = equadvec * u.s * np.random.randn(TOAs.ntoas)\n TOAs.adjust_TOAs(TimeDelta(equadvec.to('day')))\n\n\ndef add_efac(TOAs, efac, flagid=None, flags=None, seed=None):\n \"\"\"Add quadrature noise of rms `equad` [s].\n Optionally take a pseudorandom-number-generator seed.\"\"\"\n\n if seed is not None:\n np.random.seed(seed)\n\n # default equadvec\n efacvec = np.zeros(TOAs.ntoas)\n\n # check that equad is scalar if flags is None\n if flags is None:\n if not np.isscalar(efac):\n raise ValueError('ERROR: If flags is None, efac must be a scalar')\n else:\n efacvec = np.ones(TOAs.ntoas) * efac\n\n if flags is not None and flagid is not None and not np.isscalar(efac):\n if len(efac) == len(flags):\n for ct, flag in enumerate(flags):\n ind = flag == np.array([f['f'] for f\n in TOAs.table['flags'].data])\n efacvec[ind] = efac[ct]\n\n dt = efacvec * TOAs.get_errors().to('s') * np.random.randn(TOAs.ntoas)\n TOAs.adjust_TOAs(TimeDelta(dt.to('day')))\n\ndef quantize(times, flags=None, dt=1.0):\n isort = np.argsort(times)\n\n bucket_ref = [times[isort[0]]]\n bucket_ind = [[isort[0]]]\n\n for i in isort[1:]:\n if times[i] - bucket_ref[-1] < dt:\n bucket_ind[-1].append(i)\n else:\n bucket_ref.append(times[i])\n bucket_ind.append([i])\n\n avetoas = np.array([np.mean(times[l]) for l in bucket_ind],'d')\n if flags is not None:\n aveflags = np.array([flags[l[0]] for l in bucket_ind])\n\n U = np.zeros((len(times),len(bucket_ind)),'d')\n for i,l in enumerate(bucket_ind):\n U[l,i] = 1\n\n if flags is not None:\n return avetoas, aveflags, U\n else:\n return avetoas, U\n\n\ndef add_ecorr(TOAs, ecorr, flagid=None, flags=None, coarsegrain=1*u.s, seed=None):\n \"\"\"Add correlated quadrature noise of rms `ecorr` [s],\n with coarse-graining time `coarsegrain` [days].\n Optionally take a pseudorandom-number-generator seed.\"\"\"\n\n if seed is not None:\n np.random.seed(seed)\n\n times = np.array(TOAs.table['tdbld'], dtype='float64')\n if flags is None:\n t, U = quantize(times, dt=coarsegrain.to('day').value)\n elif flags is not None and flagid is not None:\n flagvals = np.array([f[flagid] for f in TOAs.table['flags'].data])\n t, f, U = quantize(times, flagvals, dt=coarsegrain.to('day').value)\n\n # default ecorr value\n ecorrvec = np.zeros(len(t))\n\n # check that ecorr is scalar if flags is None\n if flags is None:\n if not np.isscalar(ecorr):\n raise ValueError('ERROR: If flags is None, ecorr must be a scalar')\n else:\n ecorrvec = np.ones(len(t)) * ecorr\n\n if flags is not None and flagid is not None and not np.isscalar(ecorr):\n if len(ecorr) == len(flags):\n for ct, flag in enumerate(flags):\n ind = flag == np.array(f)\n ecorrvec[ind] = ecorr[ct]\n\n ecorrvec = np.dot(U * ecorrvec, np.random.randn(U.shape[1])) * u.s\n TOAs.adjust_TOAs(TimeDelta(ecorrvec.to('day')))\n",
"#!/usr/bin/env python\n# coding: utf-8\n\n# Noise model selection on NANOGrav pulsars\n\nimport json, pickle, copy\nimport logging\nimport numpy as np\nfrom enterprise_extensions.models import model_singlepsr_noise\nfrom enterprise_extensions.hypermodel import HyperModel\nfrom enterprise.signals import parameter, gp_signals, deterministic_signals\nfrom enterprise.signals import signal_base\nfrom enterprise_extensions import gp_kernels as gpk\nfrom enterprise_extensions.blocks import chromatic_noise_block\n\nimport pta_sim.parse_sim as parse_sim\nargs = parse_sim.arguments()\nlogging.basicConfig(level=logging.WARNING)\n\nwith open(args.pickle, 'rb') as fin:\n psr = pickle.load(fin)\n\nwith open(args.model_kwargs_path, 'r') as fin:\n model_kwargs = json.load(fin)\n\n# Add to exponential dips for J1713+0747\n #Model, kernel, extra DMGP, Chrom Kernel, Chrom Quad, Index\nmodel_labels = [['A', 'periodic', True, True, 'sq_exp', False, 4]\n ]\n\nptas = {}\nall_kwargs = {}\n\n# Periodic GP kernel for DM\nlog10_sigma = parameter.Uniform(-10, -4.8)\nlog10_ell = parameter.Uniform(1, 2.4)\nlog10_p = parameter.Uniform(-2, -1)\nlog10_gam_p = parameter.Uniform(-2, 2)\n\ndm_basis = gpk.linear_interp_basis_dm(dt=14*86400)\ndm_prior = gpk.periodic_kernel(log10_sigma=log10_sigma,\n log10_ell=log10_ell,\n log10_gam_p=log10_gam_p,\n log10_p=log10_p)\n\ndmgp = gp_signals.BasisGP(dm_prior, dm_basis, name='dm_gp1')\n\n# Periodic GP kernel for DM\nlog10_sigma2 = parameter.Uniform(-4.8, -3)\nlog10_ell2 = parameter.Uniform(2.4, 5)\nlog10_p2 = parameter.Uniform(-2, 2)\nlog10_gam_p2 = parameter.Uniform(-2, 2)\n\ndm_basis2 = gpk.linear_interp_basis_dm(dt=14*86400)\ndm_prior2 = gpk.periodic_kernel(log10_sigma=log10_sigma2,\n log10_ell=log10_ell2,\n log10_gam_p=log10_gam_p2,\n log10_p=log10_p2)\n\ndmgp2 = gp_signals.BasisGP(dm_prior2, dm_basis2, name='dm_gp2')\n\nch_log10_sigma = parameter.Uniform(-10, -3.5)\nch_log10_ell = parameter.Uniform(1, 6)\n\nchm_basis = gpk.linear_interp_basis_chromatic(dt=14*86400, idx=4)\nchm_prior = gpk.se_dm_kernel(log10_sigma=ch_log10_sigma, log10_ell=ch_log10_ell)\n\nchromgp = gp_signals.BasisGP(chm_prior, chm_basis, name='chrom_gp')\n#\n# chromgp = chromatic_noise_block(nondiag_kernel='sq_exp')\n\n@signal_base.function\ndef chromatic_quad(toas, freqs, quad_coeff=np.ones(3)*1e-10, idx=4):\n \"\"\"\n Basis for chromatic quadratic function.\n\n :param idx: index of chromatic dependence\n\n :return ret: normalized quadratic basis matrix [Ntoa, 3]\n \"\"\"\n t0 = (toas.max() + toas.min()) / 2\n a, b, c = 10**quad_coeff[0], 10**quad_coeff[1], 10**quad_coeff[2]\n quad = (a*(toas-t0)**2 + b*(toas-t0) + c)* (1400/freqs) ** idx\n\n return quad\n\nquad_coeff = parameter.Uniform(-10, -4, size=3)\ndeter_chrom = chromatic_quad(quad_coeff=quad_coeff)\nchrom_quad = deterministic_signals.Deterministic(deter_chrom,\n name='deter_chrom_quad')\n\nfor ii, ent in enumerate(model_labels):\n if ent[2] and ent[5]:\n extra = dmgp + dmgp2 + chromgp + chrom_quad\n elif ent[2]:\n extra = dmgp + dmgp2 + chromgp\n elif ent[5]:\n extra = dmgp + chromgp + chrom_quad\n else:\n extra = dmgp + chromgp\n\n new_kwargs = {'dm_nondiag_kernel':ent[1],\n 'dm_var':False,\n 'chrom_gp': ent[3],\n 'chrom_gp_kernel':'nondiag',\n 'chrom_idx':ent[6],\n 'chrom_kernel':ent[4],\n 'chrom_dt':14,\n 'dm_expdip':False,\n 'extra_sigs':extra,\n 'psd':'spectrum',\n }\n\n kwargs = copy.deepcopy(model_kwargs['5'])\n kwargs.update(new_kwargs)\n ptas[ii] = model_singlepsr_noise(psr, **kwargs)\n all_kwargs[ii] = kwargs\n\nsuper_model = HyperModel(ptas)\n\nsampler = super_model.setup_sampler(resume=True, outdir=args.outdir,\n empirical_distr=args.emp_distr)\n\nmodel_params = {}\nfor ky, pta in ptas.items():\n model_params.update({str(ky): pta.param_names})\n\nwith open(args.outdir + '/model_params.json', 'w') as fout:\n json.dump(model_params, fout, sort_keys=True,\n indent=4, separators=(',', ': '))\n\nkwargs_out = copy.deepcopy(all_kwargs)\nkys = list(kwargs_out.keys())\nkwargs_out[kys[0]]['extra_sigs'] = str('dm_gp + chrom_gp + dm_gp2 + chrom_quad')\n# kwargs_out[kys[2]]['extra_sigs'] = str('chrom_quad')\n# kwargs_out[kys[3]]['extra_sigs'] = str('dm_gp2 + chrom_quad')\n\nwith open(args.outdir + '/model_kwargs.json', 'w') as fout:\n json.dump(kwargs_out, fout, sort_keys=True,\n indent=4, separators=(',', ': '))\n\nwith open(args.outdir + '/model_labels.json', 'w') as fout:\n json.dump(model_labels, fout, sort_keys=True,\n indent=4, separators=(',', ': '))\n\n# sampler for N steps\nN = args.niter\nx0 = super_model.initial_sample()\n\nsampler.sample(x0, N, SCAMweight=30, AMweight=15, DEweight=50, burn=500000,\n writeHotChains=args.writeHotChains,\n hotChain=args.hot_chain)\n"
] | [
[
"numpy.dot",
"numpy.sqrt",
"numpy.random.seed",
"numpy.linspace",
"numpy.arange",
"numpy.cos",
"numpy.sin",
"numpy.ones",
"numpy.random.uniform",
"numpy.log10",
"numpy.random.randn",
"numpy.mean",
"numpy.isscalar",
"numpy.argsort",
"numpy.repeat",
"numpy.array",
"numpy.zeros"
],
[
"numpy.ones"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Keesiu/meta-kaggle | [
"87de739aba2399fd31072ee81b391f9b7a63f540",
"87de739aba2399fd31072ee81b391f9b7a63f540",
"87de739aba2399fd31072ee81b391f9b7a63f540",
"87de739aba2399fd31072ee81b391f9b7a63f540",
"87de739aba2399fd31072ee81b391f9b7a63f540",
"87de739aba2399fd31072ee81b391f9b7a63f540",
"87de739aba2399fd31072ee81b391f9b7a63f540",
"87de739aba2399fd31072ee81b391f9b7a63f540",
"87de739aba2399fd31072ee81b391f9b7a63f540",
"87de739aba2399fd31072ee81b391f9b7a63f540",
"87de739aba2399fd31072ee81b391f9b7a63f540",
"87de739aba2399fd31072ee81b391f9b7a63f540",
"87de739aba2399fd31072ee81b391f9b7a63f540",
"87de739aba2399fd31072ee81b391f9b7a63f540",
"87de739aba2399fd31072ee81b391f9b7a63f540",
"87de739aba2399fd31072ee81b391f9b7a63f540",
"87de739aba2399fd31072ee81b391f9b7a63f540",
"87de739aba2399fd31072ee81b391f9b7a63f540",
"87de739aba2399fd31072ee81b391f9b7a63f540",
"87de739aba2399fd31072ee81b391f9b7a63f540",
"87de739aba2399fd31072ee81b391f9b7a63f540",
"87de739aba2399fd31072ee81b391f9b7a63f540",
"87de739aba2399fd31072ee81b391f9b7a63f540",
"87de739aba2399fd31072ee81b391f9b7a63f540",
"87de739aba2399fd31072ee81b391f9b7a63f540",
"87de739aba2399fd31072ee81b391f9b7a63f540",
"87de739aba2399fd31072ee81b391f9b7a63f540",
"87de739aba2399fd31072ee81b391f9b7a63f540",
"87de739aba2399fd31072ee81b391f9b7a63f540",
"87de739aba2399fd31072ee81b391f9b7a63f540",
"87de739aba2399fd31072ee81b391f9b7a63f540",
"87de739aba2399fd31072ee81b391f9b7a63f540",
"87de739aba2399fd31072ee81b391f9b7a63f540",
"87de739aba2399fd31072ee81b391f9b7a63f540",
"87de739aba2399fd31072ee81b391f9b7a63f540",
"87de739aba2399fd31072ee81b391f9b7a63f540",
"87de739aba2399fd31072ee81b391f9b7a63f540",
"87de739aba2399fd31072ee81b391f9b7a63f540",
"87de739aba2399fd31072ee81b391f9b7a63f540"
] | [
"data/external/repositories_2to3/137656/blundercheck-master/combine/data_prep/prepare_pgmodel.py",
"data/external/repositories_2to3/132160/kaggle-ndsb-master/average_predictions.py",
"data/external/repositories_2to3/197978/Grasp-and-lift-EEG-challenge-master/lvl3/genYOLO.py",
"data/external/repositories_2to3/236942/homesite-master/python/build_meta_keras.py",
"data/external/repositories_2to3/36064/kaggle-bulldozer-master/model2.py",
"data/external/repositories_2to3/136714/kaggle-plankton-master/scripts/predict_avg_transformed.py",
"data/external/repositories/136714/kaggle-plankton-master/scripts/train_model.py",
"data/external/repositories_2to3/137656/blundercheck-master/combine/contest_20150303a/modeling/compute_moveaggs.py",
"data/external/repositories_2to3/132160/kaggle-ndsb-master/ensemble_predictions.py",
"data/external/repositories_2to3/164369/kaggle-public-master/instacart/compute_weights_2.py",
"data/external/repositories_2to3/166417/Restaurant-Revenue-Prediction-master/Ari/needs_work/GridSearch.py",
"data/external/repositories_2to3/132160/kaggle-ndsb-master/configurations/triplescale_fs2_fs5.py",
"data/external/repositories_2to3/136714/kaggle-plankton-master/scripts/train_base.py",
"data/external/repositories_2to3/137656/blundercheck-master/combine/contest_20150219a/data_prep/show_pgdata.py",
"data/external/repositories_2to3/253384/national_data_science_bowl_2-master/theano/utils.py",
"data/external/repositories_2to3/139781/ndsb-master/caffe-dev/python/caffe/test/test_net.py",
"data/external/repositories_2to3/236942/homesite-master/python/build_meta_3layer_keras.py",
"data/external/repositories/204509/kaggle-liberty-mutual-group-master/code/combine_data.py",
"data/external/repositories/248568/cuisinier-master/lemma.py",
"data/external/repositories/109477/gatsby-hackathon-seizure-master/code/python/seizures/evaluation/ToyXValidationData.py",
"data/external/repositories_2to3/202553/Grasp-and-Lift-master/carl/bag/blendxgbcv.py",
"data/external/repositories_2to3/137656/blundercheck-master/combine/contest_20150223a/data_prep/prepare_vw_movemodel.py",
"data/external/repositories_2to3/237806/Kaggle_HomesiteQuoteConversion-master/Python/xgb_stop_to_python.py",
"src/features/aggregate.py",
"data/external/repositories_2to3/119820/kaggle-seizure-prediction-master/layers/hidden_layer.py",
"data/external/repositories_2to3/160523/kaggle_Otto-master/new/src/0_level/tfidf.py",
"data/external/repositories_2to3/267667/kaggle-heart-master/dihedral.py",
"data/external/repositories_2to3/113677/KaggleBillionWordImputation-master/scripts/predict_sentences.py",
"data/external/repositories/74978/Kaggle_Galaxy_Zoo-master/layer_factory.py",
"data/external/repositories_2to3/155255/KaggleMalware-master/Learning/svm_experiments.py",
"data/external/repositories_2to3/190816/MasterThesisDiabeticRetinopathy-master/scripts/old/extract_features.py",
"data/external/repositories_2to3/141822/AXA_Telematics-master/Trip_Matching/Jitter_Solution/vector_math.py",
"data/external/repositories_2to3/109477/gatsby-hackathon-seizure-master/code/python/seizures/features/FFTFeatures.py",
"data/external/repositories_2to3/161279/otto_2015-master/otto-py/model.nnc.stack.py",
"data/external/repositories_2to3/137656/blundercheck-master/combine/contest_20150210a/data_prep/make_scatterplots.py",
"data/external/repositories_2to3/137656/blundercheck-master/combine/contest_20150303a/modeling/fit_errorchunk_models.py",
"data/external/repositories_2to3/172220/kaggle_diabetic-master/nn.py",
"data/external/repositories_2to3/132160/kaggle-ndsb-master/configurations/bagging_04_convroll4_doublescale_fs5.py",
"data/external/repositories_2to3/70362/kaggle-galaxies-master/predict_augmented_npy_pysex.py"
] | [
"#!/usr/bin/env python\r\n\r\nfrom pandas import *\r\nfrom numpy import *\r\nfrom djeval import *\r\nimport csv, code\r\nimport pickle as pickle\r\nfrom sklearn.externals import joblib\r\n\r\nNUM_GAMES=50000\r\n\r\n\r\ndef shell():\r\n vars = globals()\r\n vars.update(locals())\r\n shell = code.InteractiveConsole(vars)\r\n shell.interact()\r\n\r\nmsg(\"Hi! Reading eheaders\")\r\neheaders_filename = '/data/eheaders.p'\r\neheaders_file = open(eheaders_filename, 'r')\r\neheaders = pickle.load(eheaders_file)\r\nelos = eheaders['elos']\r\nresult = eheaders['result']\r\ncheckmate = eheaders['checkmate']\r\nopenings = eheaders['openings']\r\nocount = eheaders['opening_count']\r\n\r\nmsg(\"Hi! Reading crunched movescores from %s\" % sys.argv[1])\r\ncrunched_path = sys.argv[1]\r\ncrunched_df = read_csv(crunched_path, sep=',', engine='c', index_col=['gamenum', 'side'])\r\n\r\ndo_gb = False\r\nif do_gb:\r\n msg(\"Hi! Reading GB scores from %s\" % sys.argv[2])\r\n gb_path = sys.argv[2]\r\n gb_df = read_csv(gb_path, sep=',', engine='c', index_col=['gamenum'])\r\n\r\nmsg(\"Hi! Reading depthstats\")\r\ndepthstats_path = '/data/depthstats.csv'\r\ncolumns = [\r\n'gamenum',\r\n'side',\r\n'mean_depth',\r\n'mean_seldepth',\r\n'mean_depths_agreeing_ratio',\r\n'mean_deepest_agree_ratio',\r\n'pct_sanemoves',\r\n'gamelength',\r\n'mean_num_bestmoves',\r\n'mean_num_bestmove_changes',\r\n'mean_bestmove_depths_agreeing',\r\n'mean_deepest_change',\r\n'mean_deepest_change_ratio',\r\n]\r\ndepthstats_df = read_csv(depthstats_path, sep=' ', engine='c', header=None, names=columns, index_col=False)\r\ndepthstats_df = depthstats_df.set_index(['gamenum', 'side'])\r\n# we have the gamelength column in another df, drop it here to avoid conflicts\r\ndepthstats_df.drop('gamelength', axis=1, inplace=True)\r\n\r\ndo_material = True\r\nif do_material:\r\n msg(\"Hi! Reading material\")\r\n material_path = '/data/material.csv'\r\n columns = [\r\n 'gamenum',\r\n 'material_break_0',\r\n 'material_break_1',\r\n 'material_break_2',\r\n 'material_break_3',\r\n 'material_break_4',\r\n 'opening_length',\r\n 'midgame_length',\r\n 'endgame_length',\r\n 'mean_acwsa',\r\n 'mean_acwsa_0',\r\n 'mean_acwsa_1',\r\n 'mean_acwsa_2',\r\n 'mean_acwsa_3',\r\n 'mean_acwsa_4',\r\n 'mean_acwsa_5',\r\n 'mean_acwsa_6',\r\n 'mean_acwsa_7',\r\n 'mean_acwsa_8',\r\n 'mean_acwsa_9',\r\n ]\r\n material_df = read_csv(material_path, sep=' ', engine='c', header=None, names=columns, index_col=False)\r\n material_df = material_df.set_index(['gamenum'])\r\n material_df = material_df.reindex(list(range(1, NUM_GAMES+1)))\r\n material_df = material_df.fillna(material_df.mean())\r\n\r\nmsg(\"Reading ELOscored data\")\r\neloscored_cols = [\r\n 'gamenum',\r\n 'final_elo',\r\n 'final_ply',\r\n 'final_num_games',\r\n 'final_elo_stdev',\r\n 'elopath_min',\r\n 'elopath_max',\r\n]\r\neloscored_df = read_csv('/data/data.pgn.eloscored21', sep=',', engine='c', header=None, names=eloscored_cols, index_col=False)\r\neloscored_df = eloscored_df.set_index(['gamenum'])\r\n\r\nmsg(\"Reading ELOscored data 4\")\r\neloscored4_cols = [\r\n 'gamenum',\r\n 'final_elo',\r\n 'final_ply',\r\n 'final_num_games',\r\n 'final_elo_stdev',\r\n]\r\neloscored4_cols[1:] = [x + '_elo4' for x in eloscored4_cols[1:]]\r\neloscored4_df = read_csv('/data/data.pgn.eloscored4', sep=',', engine='c', header=None, names=eloscored4_cols, index_col=False)\r\neloscored4_df = eloscored4_df.set_index(['gamenum'])\r\n\r\nmsg(\"Reading ELOscored data 10\")\r\neloscored10_cols = [\r\n 'gamenum',\r\n 'final_elo',\r\n 'final_ply',\r\n 'final_num_games',\r\n 'final_elo_stdev',\r\n]\r\neloscored10_cols[1:] = [x + '_elo10' for x in eloscored10_cols[1:]]\r\neloscored10_df = read_csv('/data/data.pgn.eloscored10', sep=',', engine='c', header=None, names=eloscored10_cols, index_col=False)\r\neloscored10_df = eloscored10_df.set_index(['gamenum'])\r\n\r\ndo_movemodel=True\r\nif do_movemodel:\r\n msg(\"Hi! Reading moveaggs\")\r\n move_aggs = joblib.load('/data/move_aggs.p')\r\n move_aggs.fillna(move_aggs.mean(), inplace=True)\r\n move_aggs = move_aggs[['mean', 'median', '25', '10', 'min', 'max', 'stdev']]\r\n msg(\"Hi! Reading wmoveaggs\")\r\n wmove_aggs = joblib.load('/data/wmove_aggs.p')\r\n wmove_aggs.fillna(wmove_aggs.mean(), inplace=True)\r\n wmove_aggs.rename(columns={'elo_pred': 'moveelo_weighted'}, inplace=True)\r\n wmove_aggs = wmove_aggs['moveelo_weighted']\r\n\r\ndo_elochunk = False\r\nif do_elochunk:\r\n ch_agg_df = joblib.load('/data/chunk_aggs.p')\r\n ch_agg_df.index = ch_agg_df.index.droplevel('elo')\r\n ch_agg_df.columns = ['elochunk_' + x for x in ch_agg_df.columns]\r\n\r\n\r\nmsg(\"Hi! Setting up playergame rows\")\r\n\r\nif do_elochunk:\r\n elorange_cols = list(ch_agg_df.columns.values)\r\n msg(\"elorange cols are %s\" % elorange_cols)\r\n\r\nmsg('Preparing ELO df')\r\nelo_rows = [[x[0][0], x[0][1], x[1]] for x in list(elos.items())]\r\nelo_df = DataFrame(elo_rows, columns=['gamenum','side','elo'])\r\nelo_df.set_index(['gamenum','side'], inplace=True)\r\n\r\nmsg('Joining DFs')\r\nsupplemental_dfs = [depthstats_df, elo_df, crunched_df]\r\nif do_movemodel:\r\n supplemental_dfs.extend([move_aggs, wmove_aggs])\r\nif do_elochunk:\r\n supplemental_dfs.append(ch_agg_df)\r\nmega_df = concat(supplemental_dfs, axis=1)\r\nif do_material:\r\n mega_df = mega_df.join(material_df, how='outer')\r\nmega_df = mega_df.join(eloscored_df, how='outer')\r\nmega_df = mega_df.join(eloscored4_df, how='outer')\r\nmega_df = mega_df.join(eloscored10_df, how='outer')\r\nif do_gb:\r\n mega_df = mega_df.join(gb_df, how='outer')\r\n\r\nyy_df = mega_df\r\nmsg(\"hi, columns are %s\" % yy_df.columns)\r\n\r\n# TODO confirm that all columns are there\r\n\r\n\r\ndef opening_feature(opening):\r\n if ocount[opening] < 20:\r\n return 'rare'\r\n if ocount[opening] < 200:\r\n return 'uncommon'\r\n return opening\r\n\r\nmsg(\"Hi! Computing additional features\")\r\nyy_df['opening_feature'] = [opening_feature(openings[x]) for x in yy_df.index.get_level_values('gamenum')]\r\nyy_df['opening_count'] = [ocount[openings[x]] for x in yy_df.index.get_level_values('gamenum')]\r\nyy_df['any_grit'] = (yy_df['grit'] > 0)\r\nyy_df['major_grit'] = (yy_df['grit'] > 5)\r\nyy_df['nmerror'] = log((-1 * yy_df['meanerror']).clip(1,60)).clip(1,4) - 2.53\r\nyy_df['premature_quit'] = (yy_df['gameoutcome'] == -1) & (yy_df['my_final_equity'] > -100)\r\nyy_df['drawn_game'] = (yy_df['gameoutcome'] == 0)\r\nyy_df['ended_by_checkmate'] = yy_df['won_by_checkmate'] | yy_df['lost_by_checkmate']\r\nyy_df['noblunders'] = (yy_df['blunderrate'] == 0)\r\nyy_df['final_equity'] = yy_df['my_final_equity'].abs().clip(0,300)\r\nyy_df['early_lead'] = yy_df['early_lead'].clip(0,100)\r\nyy_df['mean_depth_clipped'] = yy_df['mean_depth'].clip(0,25)\r\nyy_df['gamelength_clipped'] = yy_df['gamelength'].clip(20,200)\r\n\r\n\r\n# prepare opponent_df with selected info about opponent\r\nopponent_columns = ['meanerror', 'blunderrate', 'perfectrate', 'grit', 'meanecho', 'mate_created', 'mate_destroyed', 'q_error_one', 'q_error_two', 'stdeverror', 'elo', 'any_grit', 'noblunders', 'nmerror', 'mean_depths_agreeing_ratio', 'mean_deepest_agree_ratio', 'pct_sanemoves']\r\nif do_elochunk:\r\n opponent_columns.extend(elorange_cols)\r\nopponent_df = yy_df[opponent_columns]\r\nopponent_df = opponent_df.reset_index()\r\nopponent_df['side'] = opponent_df['side'] * -1\r\nopponent_df.set_index(['gamenum', 'side'], inplace=True)\r\nopponent_df.columns = ['opponent_' + x for x in opponent_df.columns]\r\nyy_df = concat([yy_df, opponent_df], axis=1)\r\n\r\n# more derived columns that use opponent comparisons\r\nyy_df['elo_advantage'] = (yy_df['elo'] - yy_df['opponent_elo']).clip(-500, 500)\r\nyy_df['max_nmerror'] = yy_df[['nmerror', 'opponent_nmerror']].max(axis=1)\r\nyy_df['min_nmerror'] = yy_df[['nmerror', 'opponent_nmerror']].min(axis=1)\r\nyy_df['max_meanecho'] = yy_df[['meanecho', 'opponent_meanecho']].max(axis=1)\r\nyy_df['elo_avg'] = (yy_df['elo'] + yy_df['opponent_elo'])/2.0\r\nyy_df['elo_advantage'] = (yy_df['elo'] - yy_df['opponent_elo'])\r\nyy_df['winner_elo_advantage'] = yy_df['elo_advantage'] * yy_df['gameoutcome']\r\n\r\n\r\nmsg(\"Hi! Computing dummy variables\")\r\ncategorical_features = ['opening_feature']\r\ndummies = get_dummies(yy_df[categorical_features]).astype(np.int8)\r\nyy_df = yy_df.join(dummies)\r\n\r\n# fill in missing values\r\nmsg(\"Hi! Filling in missing values\")\r\nfull_index = pandas.MultiIndex.from_product([list(range(1,NUM_GAMES + 1)), [1,-1]], names=['gamenum', 'side'])\r\nyy_df = yy_df.reindex(full_index)\r\nyy_elo = yy_df['elo'].copy(True)\r\nyy_df.fillna(yy_df.mean(numeric_only=True), inplace=True)\r\nyy_df.fillna(False, inplace=True)\r\nyy_df['elo'] = yy_elo\r\n\r\n# stupid patch for some stupid opening feature that got assigned to False by fillna ?!!?!?!?\r\nyy_df.loc[yy_df['opening_feature'] == False,'opening_feature'] = 'rare'\r\n\r\nmsg(\"Hi! Writing yy_df to disk\")\r\nyy_df.to_pickle(sys.argv[3])\r\n\r\nmsg(\"Column counts are:\")\r\ncounts = yy_df.count(axis=0)\r\nprint(counts)\r\n\r\n",
"import numpy as np\r\nimport sys\r\n\r\nif len(sys.argv) < 3:\r\n sys.exit(\"Usage: python average_predictions.py <predictions_file1> [predictions_file_2] [...] <output_file>\")\r\n\r\npredictions_paths = sys.argv[1:-1]\r\ntarget_path = sys.argv[-1]\r\npredictions = [np.load(path) for path in predictions_paths]\r\navg_predictions = np.mean(predictions, axis=0)\r\nnp.save(target_path, avg_predictions)\r\n",
"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Aug 31 16:01:25 2015.\r\n\r\n@author: rc,alex\r\n\"\"\"\r\nimport os\r\nimport sys\r\nif __name__ == '__main__' and __package__ is None:\r\n filePath = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\r\n sys.path.append(filePath)\r\n\r\nfrom glob import glob\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom sklearn.metrics import roc_auc_score\r\n\r\nfrom preprocessing.aux import getEventNames\r\n\r\ncols = getEventNames()\r\nids = np.load('../infos_test.npy')\r\nsubject_test = ids[:, 1]\r\nseries_test = ids[:, 2]\r\nids = ids[:, 0]\r\n\r\nlabels = np.load('../infos_val.npy')\r\nsubjects = labels[:, -2]\r\nseries = labels[:, -1]\r\nlabels = labels[:, :-2]\r\n\r\nsubs_val = []\r\nsubs_test = []\r\n\r\n# get all submissions\r\nsubs = glob('models/*.yml')\r\n# remove folder and extension\r\nsubs = [sub[7:-4] for sub in subs]\r\n\r\n# load subs\r\nprint('Computing an average of %d submissions:' % len(subs))\r\nfor sub in subs:\r\n print(sub)\r\n subs_val.append(np.load('val/val_%s.npy' % sub)[0])\r\n subs_test.append(pd.read_csv('submissions/%s.csv' % sub,\r\n index_col=0).values)\r\n\r\n# average all models\r\nens_val = np.mean(subs_val, axis=0)\r\nens_test = np.mean(subs_test, axis=0)\r\n\r\n# stats of the average\r\naucs_val = [np.mean(roc_auc_score(labels[series == s], ens_val[series == s]))\r\n for s in [7, 8]]\r\nprint('AUC: %.5f (SD: %.5f), s7: %.5f ; s8: %.5f' % (np.mean(aucs_val),\r\n np.std(aucs_val),\r\n aucs_val[0], aucs_val[1]))\r\n\r\n# save\r\nnp.save('val/val_YOLO.npy', [ens_val])\r\nsub = pd.DataFrame(data=ens_test, index=ids, columns=cols)\r\nsub.to_csv('submissions/YOLO.csv', index_label='id', float_format='%.8f')\r\n",
"\"\"\"\r\nCreated on Thu Dec 10 10:44:27 2015\r\n\r\n@author: konrad\r\n\"\"\"\r\nfrom keras.regularizers import l2, activity_l2\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom keras.models import Sequential\r\nfrom keras.layers.core import Dense, Dropout, Activation\r\nfrom keras.layers.normalization import BatchNormalization\r\nfrom keras.optimizers import Adadelta\r\nfrom itertools import product\r\nimport datetime\r\n\r\nif __name__ == '__main__':\r\n\r\n ## settings\r\n projPath = './'\r\n dataset_version = \"kb9\"\r\n model_type = \"keras\"\r\n seed_value = 123\r\n todate = datetime.datetime.now().strftime(\"%Y%m%d\")\r\n np.random.seed(seed_value)\r\n\r\n # data\r\n # read the training and test sets\r\n xtrain = pd.read_csv(projPath + 'input/xtrain_'+ dataset_version + '.csv')\r\n id_train = xtrain.QuoteNumber\r\n ytrain = xtrain.QuoteConversion_Flag\r\n xtrain.drop('QuoteNumber', axis = 1, inplace = True)\r\n xtrain.drop('QuoteConversion_Flag', axis = 1, inplace = True)\r\n\r\n xtest = pd.read_csv(projPath + 'input/xtest_'+ dataset_version + '.csv')\r\n id_test = xtest.QuoteNumber\r\n xtest.drop('QuoteNumber', axis = 1, inplace = True)\r\n\r\n # folds\r\n xfolds = pd.read_csv(projPath + 'input/xfolds.csv')\r\n # work with 5-fold split\r\n fold_index = xfolds.fold5\r\n fold_index = np.array(fold_index) - 1\r\n n_folds = len(np.unique(fold_index))\r\n\r\n ## model\r\n nb_classes = 2\r\n dims = xtrain.shape[1]\r\n epochs = 30\r\n\r\n # parameter grids\r\n drop_vals = [0.01, 0.2]\r\n dec_vals = [0.995, 0.8]\r\n lr_vals = [1, 0.5, 0.1]\r\n reg_vals = [1e-5,1e-3]\r\n lay_vals = [1,2]\r\n param_grid = tuple([drop_vals, dec_vals, lr_vals, reg_vals, lay_vals])\r\n param_grid = list(product(*param_grid))\r\n\r\n # storage structure for forecasts\r\n mvalid = np.zeros((xtrain.shape[0],len(param_grid)))\r\n mfull = np.zeros((xtest.shape[0],len(param_grid)))\r\n\r\n ## build 2nd level forecasts\r\n for i in range(len(param_grid)):\r\n print(\"processing parameter combo:\", param_grid[i])\r\n print(\"Combo:\", i, \"of\", len(param_grid))\r\n # loop over folds\r\n # Recompile model on each fold\r\n for j in range(0,n_folds):\r\n # configure model with j-th combo of parameters\r\n x = param_grid[i]\r\n model = Sequential()\r\n model.add(Dense(dims * x[4], input_shape=(dims,),W_regularizer=l2(x[3])))\r\n model.add(BatchNormalization())\r\n model.add(Dropout(x[0]))\r\n model.add(Dense(nb_classes))\r\n model.add(Activation('softmax'))\r\n opt=Adadelta(lr=x[2],decay=x[1],epsilon=1e-5)\r\n model.compile(loss='binary_crossentropy', optimizer=opt)\r\n\r\n idx0 = np.where(fold_index != j)\r\n idx1 = np.where(fold_index == j)\r\n x0 = np.array(xtrain)[idx0,:][0]\r\n x1 = np.array(xtrain)[idx1,:][0]\r\n y0 = np.array(ytrain)[idx0]\r\n y1 = np.array(ytrain)[idx1]\r\n y00 = np.zeros((x0.shape[0],2))\r\n y00[:,0] = y0; y00[:,1] = 1-y0\r\n # fit the model on observations associated with subject whichSubject in this fold\r\n model.fit(x0, y00, nb_epoch=epochs, batch_size=1000)\r\n mvalid[idx1,i] = model.predict_proba(x1)[:,0]\r\n del model\r\n print(\"finished fold:\", j)\r\n\r\n print(\"Building full prediction model for test set.\")\r\n # configure model with j-th combo of parameters\r\n x = param_grid[i]\r\n model = Sequential()\r\n model.add(Dense(dims * x[4], input_shape=(dims,),W_regularizer=l2(x[3])))\r\n #model.add(PReLU())\r\n model.add(BatchNormalization())\r\n model.add(Dropout(x[0]))\r\n model.add(Dense(nb_classes))\r\n model.add(Activation('softmax'))\r\n opt=Adadelta(lr=x[2],decay=x[1],epsilon=1e-5)\r\n model.compile(loss='binary_crossentropy', optimizer=opt)\r\n\r\n # fit on complete dataset\r\n ytrain0 = np.zeros((xtrain.shape[0],2))\r\n ytrain0[:,0] = ytrain\r\n ytrain0[:,1] = 1- ytrain\r\n model.fit(np.array(xtrain), ytrain0,nb_epoch=epochs, batch_size=1000)\r\n mfull[:,i] = model.predict_proba(np.array(xtest))[:,0]\r\n del model\r\n print(\"finished full prediction\")\r\n\r\n ## store the results\r\n # add indices etc\r\n mvalid = pd.DataFrame(mvalid)\r\n mvalid.columns = [model_type + str(i) for i in range(0, mvalid.shape[1])]\r\n mvalid['QuoteNumber'] = id_train\r\n mvalid['QuoteConversion_Flag'] = ytrain\r\n\r\n mfull = pd.DataFrame(mfull)\r\n mfull.columns = [model_type + str(i) for i in range(0, mfull.shape[1])]\r\n mfull['QuoteNumber'] = id_test\r\n\r\n\r\n # save the files\r\n mvalid.to_csv(projPath + 'metafeatures/prval_' + model_type + todate + '_data' + dataset_version + '_seed' + str(seed_value) + '.csv', index = False, header = True)\r\n mfull.to_csv(projPath + 'metafeatures/prfull_' + model_type + todate + '_data' + dataset_version + '_seed' + str(seed_value) + '.csv', index = False, header = True)\r\n",
"import time\r\n\r\nimport numpy as np\r\nfrom sklearn.preprocessing import OneHotEncoder, MinMaxScaler\r\nfrom sklearn.gaussian_process import GaussianProcess\r\nfrom sklearn.linear_model import Ridge, Lasso\r\nfrom sklearn.svm import NuSVR, SVR\r\nimport scipy\r\n\r\nfrom util import Logger, get_rmse\r\n\r\nclass Linear():\r\n def __init__(self, type='Ridge', alpha=3, C=1.0, nu=0.2, limit=None, \\\r\n epsilon=0.1):\r\n self.limit = limit\r\n if type == 'Ridge':\r\n self.model = Ridge(alpha=alpha)\r\n elif type == 'SVR':\r\n self.model = SVR(kernel='linear', C=C, epsilon=epsilon)\r\n elif type == 'NuSVR':\r\n self.model = NuSVR(C=C, nu=nu, kernel='linear')\r\n elif type == 'Lasso':\r\n self.model = Lasso(alpha=alpha)\r\n \r\n @staticmethod\r\n def get_cal(m):\r\n # get calitative features\r\n # watch out as indices depend on feature vector!\r\n return np.hstack((m[:,:23], m[:,24:37], m[:,38:52])) + 1\r\n \r\n @staticmethod\r\n def get_cant(m):\r\n # get cantitative features\r\n # watch out as indices depend on feature vector!\r\n return np.hstack((m[:,23:24], m[:,37:38], m[:,52:]))\r\n \r\n def fit(self, train_X, train_Y):\r\n # no fitting done here, just saving data\r\n if self.limit:\r\n if len(train_X) > self.limit:\r\n train_X = train_X[-self.limit:]\r\n train_Y = train_Y[-self.limit:]\r\n self.train_X = np.array(train_X)\r\n self.train_Y = np.array(train_Y)\r\n \r\n \r\n def predict(self, test_X):\r\n # fitting done here\r\n # not efficient on the long term\r\n test_X = np.array(test_X)\r\n enc = OneHotEncoder()\r\n scal = MinMaxScaler()\r\n data = np.vstack((self.train_X, test_X))\r\n enc.fit(self.get_cal(data))\r\n scal.fit(self.get_cant(data))\r\n \r\n new_train_X1 = enc.transform(self.get_cal(self.train_X))\r\n new_train_X2 = scal.transform(self.get_cant(self.train_X))\r\n new_train_X = scipy.sparse.hstack((new_train_X1, new_train_X2))\r\n new_test_X1 = enc.transform(self.get_cal(test_X))\r\n new_test_X2 = scal.transform(self.get_cant(test_X))\r\n new_test_X = scipy.sparse.hstack((new_test_X1, new_test_X2))\r\n \r\n self.model.fit(new_train_X, self.train_Y)\r\n R = self.model.predict(new_test_X)\r\n return R\r\n\r\ndef tt(args):\r\n from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor, \\\r\n ExtraTreesRegressor\r\n \r\n task_id, model_type, model_params, Xtrain, Ytrain, Xtest, model_key, key = args\r\n \r\n if len(Xtest) == 0:\r\n return (task_id, [])\r\n \r\n model_options = {\r\n 'GBR': GradientBoostingRegressor,\r\n 'RFR': RandomForestRegressor,\r\n 'Linear': Linear,\r\n 'ETR': ExtraTreesRegressor,\r\n \r\n }\r\n map_params = {\r\n 'ne': 'n_estimators',\r\n 'md': 'max_depth',\r\n 'mss': 'min_samples_split',\r\n 'msl': 'min_samples_leaf',\r\n 'ss': 'subsample',\r\n 'lr': 'learning_rate',\r\n 'n': 'n_jobs',\r\n 'rs': 'random_state',\r\n 'a': 'alpha',\r\n 't': 'type',\r\n 'c': 'C',\r\n 'nu': 'nu',\r\n 'l': 'limit',\r\n 'e': 'epsilon',\r\n }\r\n \r\n mp = {}\r\n for k, v in list(model_params.items()):\r\n mp[map_params[k]] = v\r\n m = model_options[model_type](**mp)\r\n m.fit(Xtrain, Ytrain)\r\n r = m.predict(Xtest)\r\n del m\r\n del model_options\r\n return (task_id, r)\r\n\r\nclass SplitModel():\r\n '''\r\n build a series of models by spliting the dataset on a given feature\r\n '''\r\n def __init__(self, split_keys, index, n_est=5, models=None, \\\r\n weights=None, bias=None, seed=1):\r\n self.bias = None\r\n \r\n model_params = []\r\n for md in [3, 6, 12, 16, 30]:\r\n for lr in [0.1, 0.3, 0.6, 0.9]:\r\n for mss in [5, 10, 16, 32, 64]:\r\n msl = mss / 2\r\n for ss in [0.3, 0.5, 0.7, 1]:\r\n model_params.append(\r\n ('GBR', dict(ne=n_est, md=md, lr=lr, mss=mss, msl=msl, ss=ss))\r\n )\r\n for md in [3, 6, 12, 16, 30]:\r\n for mss in [5, 10, 16, 32, 64]:\r\n msl = mss / 2\r\n model_params.append(\r\n ('RFR', dict(ne=n_est, md=md, mss=mss, msl=msl, n=4, rs=seed+md+mss))\r\n )\r\n model_params.append(('Linear', dict(t='NuSVR', c=0.1, nu=0.2, l=25000)))\r\n model_params.append(('Linear', dict(t='SVR', c=0.1, e=0.05, l=10000))) # ajuta pe index1 (0.22013316780439385, 0.52, 0.2, 0.14, 0.08, 0.06)\r\n model_params.append(('Linear', dict(t='Lasso', a=0.0001, l=20000)))\r\n model_params.append(('Linear', dict(t='Lasso', a=0.00001, l=20000)))\r\n \r\n self.bias = bias\r\n if weights:\r\n self.weights = weights\r\n else:\r\n self.weights = [1.0/len(models)] * len(models)\r\n self.model_params = []\r\n for i in range(len(models)):\r\n self.model_params.append((i,) + model_params[models[i]])\r\n for m in self.model_params:\r\n print(m)\r\n \r\n self.index = index\r\n self.split_keys = split_keys\r\n \r\n def train_test(self, Xtrain, Ytrain, Xtest):\r\n Xtrain = np.array(Xtrain)\r\n Ytrain = np.array(Ytrain)\r\n Xtest = np.array(Xtest)\r\n tasks = []\r\n task_id = 0\r\n results = []\r\n l = Logger(len(self.split_keys) * len(self.model_params), \\\r\n len(self.split_keys), tag='SplitModel')\r\n for key in self.split_keys:\r\n mask_train = Xtrain[:,self.index] == key\r\n mask_test = Xtest[:,self.index] == key\r\n for model_key, model_type, model_params in self.model_params:\r\n task = (\r\n task_id,\r\n model_type, \r\n model_params, \r\n Xtrain[mask_train],\r\n Ytrain[mask_train],\r\n Xtest[mask_test],\r\n model_key,\r\n key,\r\n )\r\n results.append(tt(task))\r\n print((task_id, model_key, key))\r\n tasks.append((task_id, model_key, key))\r\n l.step()\r\n \r\n task_id += 1\r\n \r\n tasks = {t[0]: t[1:] for t in tasks}\r\n result_batches = [np.array([0.0] * len(Xtest))\\\r\n for i in range(len(self.model_params))]\r\n for result_set in results:\r\n task_id, Ytask = result_set\r\n task = tasks[task_id]\r\n model_key = task[-2]\r\n mask_test = Xtest[:,self.index] == task[-1]\r\n result_batches[model_key][mask_test] += Ytask\r\n \r\n Ytest = np.array([0.0] * len(Xtest))\r\n for (i, batch) in enumerate(result_batches):\r\n Ytest += batch * self.weights[i]\r\n if self.bias:\r\n Ytest += self.bias\r\n \r\n return (Ytest, result_batches)\r\n \r\n \r\nclass BigModel():\r\n def __init__(self, columns, n_est=5, seed=1):\r\n split_keys1 = sorted(list(range(1,7)))\r\n index1 = columns.index('ProductGroup')\r\n split_keys2 = [0, 1, 2, 3, 4, 5, 30, 31, 32, 33, 34, 35, 36, 37, 38, 60, 61, 62, 63, 64, 65, 65.5, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 120, 121, 122, 123, 124, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159]\r\n index2 = columns.index('type2')\r\n \r\n model_weights1 = [0.03131793, 0.02611096, 0.04683615, 0.04510745, 0.05901089, 0.05310125, 0.03905133, 0.06681227, 0.02479392, 0.04527772, 0.04649242, 0.03905532, 0.05324603, 0.02950949, 0.02942703, 0.04844027, 0.01096952, 0.04392747, 0.02677431, 0.00101947, 0.01306091, 0.00294178, 0.03421554, 0.05725074, 0.01947722, 0.01850144, -0.00323456, 0.03188587, 0.01445867, 0.01919743, 0.03913423, 0.02684197, -0.01231671, -0.01055348]\r\n model_indices1 = [20, 22, 26, 28, 30, 33, 36, 46, 57, 96, 97, 123, 131, 143, 160, 175, 185, 187, 197, 209, 215, 236, 255, 257, 276, 279, 298, 322, 330, 335, 354, 357, 414, 424]\r\n bias1 = -0.12037114510366997\r\n \r\n model_weights2 = [0.114999546, 0.0642159312, 0.0763160215, 0.0749201568, 0.0722169352, 0.0403322002, 0.105175222, 0.0257017482, 0.00992976551, -0.0198667402, 0.0836062323, 0.0618304965, -0.00770000674, -0.00243349526, 0.106124237, 0.0228227453, -1.57590333e-05, 0.0449772596, 0.0141671971, -0.0480243632, 0.049008765, 0.0389751147, 0.087701499]\r\n model_indices2 = [22, 24, 29, 47, 88, 94, 98, 110, 130, 139, 162, 172, 192, 214, 256, 291, 297, 322, 329, 371, 413, 414, 415]\r\n bias2 = -0.099892980166821133\r\n \r\n self.weights = [0.53, 0.2, 0.09, 0.1, 0.08]\r\n self.models = [\r\n SplitModel(split_keys1, index1, n_est=n_est, \\\r\n seed=seed+1, models=model_indices1, weights=model_weights1,\\\r\n bias=bias1),\r\n SplitModel(split_keys2, index2, n_est=n_est, \\\r\n seed=seed+2, models=model_indices2, weights=model_weights2,\\\r\n bias=bias2),\r\n SplitModel(split_keys1, index1, seed=seed+3, models=[425]),\r\n SplitModel(split_keys2, index2, seed=seed+4, models=[427]),\r\n SplitModel(split_keys2, index2, seed=seed+5, models=[428]),\r\n ]\r\n \r\n def train_test(self, train_X, train_Y, test_X):\r\n self.results = []\r\n rez = np.array([0.0] * len(test_X))\r\n l = Logger(len(self.models), 1, tag='BigModel')\r\n \r\n for i, m in enumerate(self.models):\r\n m_rez, m_batches = m.train_test(train_X, train_Y, test_X)\r\n rez += self.weights[i] * m_rez\r\n self.results.append((m_rez, m_batches))\r\n l.step()\r\n return rez\r\n\r\n'''\r\nclass TimeModel():\r\n @staticmethod\r\n def train_test(train_X, train_Y, test_X):\r\n test_X_np = np.array(test_X)\r\n year1 = np.min(np.array(test_X_np)[:,37])\r\n month1 = np.min(np.array(test_X_np)[:,36])\r\n \r\n year2 = np.max(np.array(test_X_np)[:,37])\r\n month2 = np.max(np.array(test_X_np)[:,36])\r\n n_predict = int((year2 - year1) * 12 + month2 - month1 + 1)\r\n \r\n ppm = {} # price per month\r\n apm = [[] for i in range(13)] # average per month\r\n for i, row in enumerate(train_X):\r\n m = row[36]\r\n y = row[37]\r\n p = train_Y[i]\r\n \r\n if y * 12 + m < year1 * 12 + month1 - 72:\r\n continue\r\n \r\n if y not in ppm:\r\n ppm[y] = {}\r\n if m not in ppm[y]:\r\n ppm[y][m] = []\r\n ppm[y][m].append(p)\r\n apm[m].append(p)\r\n \r\n apm = [np.mean(l) for l in apm[1:]]\r\n average = np.mean(train_Y)\r\n \r\n plot = []\r\n for y in sorted(ppm.keys()):\r\n for m in sorted(ppm[y].keys()):\r\n plot.append(np.mean(ppm[y][m]))\r\n \r\n X = np.reshape(range(len(plot) + n_predict), (len(plot) + n_predict, 1))\r\n \r\n nuggets = [0.000003,0.00001,0.00003,0.0001,0.0003,0.001,0.003, 0.01]\r\n total_dev = np.array([0.0] * n_predict)\r\n preds = np.array([0.0] * len(X))\r\n for nugget in nuggets:\r\n g = GaussianProcess(regr='linear', \\\r\n corr='squared_exponential', nugget=nugget)\r\n g.fit(X[:-n_predict], plot)\r\n preds += g.predict(X)\r\n deviations = g.predict(X[-n_predict:]) - average\r\n total_dev = total_dev + deviations\r\n \r\n \r\n total_dev /= len(nuggets)\r\n preds /= len(nuggets)\r\n \r\n R = []\r\n for row in test_X:\r\n m = row[36] # month\r\n y = row[37] # year\r\n i = (y - year1) * 12 + m - month1\r\n R.append(total_dev[i])\r\n \r\n return R\r\n'''\r\n",
"# Script to convert and resize training and test images into npy\r\n\r\n\r\n\r\nimport os\r\nimport argparse\r\nimport itertools\r\nfrom time import time\r\nfrom time import strftime\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\nfrom sklearn.metrics import accuracy_score\r\n\r\nfrom plankton import utils\r\nfrom plankton.augment_iterators import im_affine_transform\r\n\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument('model')\r\n\r\nparser.add_argument('--X_test_npy', default='data/X_test_48.npy')\r\nparser.add_argument('--X_train_npy', default='data/X_train_48.npy')\r\nparser.add_argument('--y_train_npy', default='data/X_train_48.npy')\r\nparser.add_argument('--hw', default=48, type=int)\r\nparser.add_argument('--eval_on_train', action='store_true')\r\n\r\nparser.add_argument('--X_test_fname_npy', default='data/X_test_fname_48.npy')\r\nparser.add_argument('--enc', default='data/y_train_encoder-2015-02-21-21-04-01.pickle')\r\nparser.add_argument('--submission_sample', default='data/sampleSubmission.csv')\r\nparser.add_argument('--out_dir', default='submissions/')\r\n\r\nparser.add_argument('--scale_lower', default=0.85, type=float)\r\nparser.add_argument('--scale_upper', default=1.15, type=float)\r\nparser.add_argument('--scale_step', default=3, type=float)\r\n\r\nparser.add_argument('--rotation_lower', default=0, type=int)\r\nparser.add_argument('--rotation_upper', default=360, type=int)\r\nparser.add_argument('--rotation_step', default=36, type=int)\r\n\r\nparser.add_argument('--translate_y_lower', default=-2, type=int)\r\nparser.add_argument('--translate_y_upper', default=3, type=int)\r\nparser.add_argument('--translate_y_step', default=2, type=int)\r\n\r\nparser.add_argument('--translate_x_lower', default=-2, type=int)\r\nparser.add_argument('--translate_x_upper', default=3, type=int)\r\nparser.add_argument('--translate_x_step', default=2, type=int)\r\n\r\nargs = parser.parse_args()\r\n\r\n\r\ndef generate_predictions_with_augmented_images(net, X, combinations):\r\n t0 = time()\r\n n = X.shape[0]\r\n num_features = 121\r\n num_combination = len(combinations)\r\n predictions = np.empty((n, num_features))\r\n # TODO optimize by vectorizing the for loop\r\n # (although X_aug will be very very big and probably won't fit in memory?)\r\n for i, x in enumerate(X):\r\n if i % 1000 == 0:\r\n print('Finished predicting %i images. Took %i seconds so far' % (i, time() - t0))\r\n\r\n # Image only has one channel (grayscale)\r\n # im_affine_transform only works for images with shape of (height, width)\r\n x = x[0]\r\n x_aug = np.array([\r\n im_affine_transform(x, scale=scale, rotation=rotation, translate_y=translate_y, translate_x=translate_x)\r\n for scale, rotation, translate_y, translate_x in combinations\r\n ])\r\n\r\n x_aug = x_aug.reshape(num_combination, 1, args.hw, args.hw).astype(np.float32)\r\n # TODO do we need to normalize this back to 0?\r\n pred = net.predict_proba(x_aug).mean(axis=0)\r\n predictions[i] = pred\r\n return predictions\r\n\r\nif __name__ == '__main__':\r\n scale_choices = np.linspace(args.scale_lower, args.scale_upper, args.scale_step)\r\n rotation_choices = list(range(args.rotation_lower, args.rotation_upper, args.rotation_step))\r\n translate_y_choices = list(range(args.translate_y_lower, args.translate_y_upper, args.translate_y_step))\r\n translate_x_choices = list(range(args.translate_x_lower, args.translate_x_upper, args.translate_x_step))\r\n\r\n combinations = list(itertools.product(scale_choices, rotation_choices, translate_y_choices, translate_x_choices))\r\n num_combination = len(combinations)\r\n print('scale_choices = ', scale_choices)\r\n print('rotation_choices = ', rotation_choices)\r\n print('translate_y_choices = ', translate_y_choices)\r\n print('translate_x_choices = ', translate_x_choices)\r\n print('Number of augmented images per test image is %i' % num_combination)\r\n\r\n print('Loading test images from %s and %s' % (args.X_test_npy, args.X_test_fname_npy))\r\n X = np.load(args.X_test_npy)\r\n X_train = np.load(args.X_train_npy)\r\n fname = np.load(args.X_test_fname_npy)\r\n hw = args.hw\r\n\r\n print('Loading model from %s' % args.model)\r\n net = utils.load_from_pickle(args.model)\r\n enc = utils.load_from_pickle(args.enc)\r\n # TODO change batchsize to the num_combinaions and see if faster?\r\n\r\n if args.eval_on_train:\r\n print('Evaluating on training set')\r\n X_train = np.load(args.X_train_npy)\r\n y_train = np.load(args.y_train_npy)\r\n pred_proba_aug = generate_predictions_with_augmented_images(net, X_train, combinations)\r\n pred_aug = pred_proba_aug.argmax(axis=0)\r\n pred_prob = net.predict_proba(X_train)\r\n pred = net.predict(X_train)\r\n\r\n ascore = accuracy_score(y_train, pred)\r\n lscore = utils.multiclass_log_loss(y_train, pred_prob)\r\n print('Non-augmented score on training set: ascore=%.4f, lscore=%.4f' % (ascore, lscore))\r\n\r\n ascore_aug = accuracy_score(y_train, pred_aug)\r\n lscore_aug = utils.multiclass_log_loss(y_train, pred_proba_aug)\r\n print('Augmented score of training set: ascore=%.4f, lscore=%.4f' % (ascore_aug, lscore_aug))\r\n\r\n print('Predicting...')\r\n t0 = time()\r\n predictions = generate_predictions_with_augmented_images(net, X, combinations)\r\n column_name = np.hstack([['image'], enc.classes_])\r\n submmission = pd.DataFrame(np.c_[fname, predictions], columns=column_name)\r\n print('Finished predicting all %i images. Took %i seconds in total' % (len(submmission), time() - t0))\r\n\r\n t0 = time()\r\n suffix = strftime('%Y-%m-%d-%H-%M-%S')\r\n csv_fname = '%s%s.csv' % (args.out_dir, suffix)\r\n print('Saving prediction to %s' % csv_fname)\r\n submmission.to_csv(csv_fname, index=False, header=True)\r\n print('Done. Took %i seconds' % (time() - t0))\r\n\r\n print('Ziping up submission...')\r\n t0 = time()\r\n zip_fname = '%s%s.zip' % (args.out_dir, suffix)\r\n zip_cmd = 'zip %s %s' % (zip_fname, csv_fname)\r\n os.system(zip_cmd)\r\n print('Zip file created at %s. Took %i seconds' % (zip_fname, time() - t0))\r\n",
"# Script to train model\nfrom __future__ import division, print_function\n\nimport argparse\nfrom time import time\n\nimport numpy as np\n\nfrom plankton import utils\nfrom plankton import get_net\n\nparser = argparse.ArgumentParser()\nparser.add_argument('net_name')\nparser.add_argument('--X_train_train_npy', default='data/X_train_train')\nparser.add_argument('--X_train_test_npy', default='data/X_train_test')\nparser.add_argument('--y_train_train_npy', default='data/y_train_train')\nparser.add_argument('--y_train_test_npy', default='data/y_train_test')\nparser.add_argument('--hw', default=48, type=int)\nparser.add_argument('--out_dir', default='models/')\nargs = parser.parse_args()\n\nif __name__ == '__main__':\n print('Loading training images')\n X_train, X_test = np.load('%s_%i.npy' % (args.X_train_train_npy, args.hw)), np.load('%s_%i.npy' % (args.X_train_test_npy, args.hw))\n y_train, y_test = np.load('%s_%i.npy' % (args.y_train_train_npy, args.hw)), np.load('%s_%i.npy' % (args.y_train_test_npy, args.hw))\n print(X_train.shape, X_test.shape, y_train.shape, y_test.shape)\n\n print('Loading model definition from %s' % args.net_name)\n net = get_net(args.net_name)\n\n # Pass mean value of training data to the batch iterator\n X_train_mean = np.mean(X_train, axis=0)\n net.batch_iterator_train.mean = X_train_mean\n net.batch_iterator_test.mean = X_train_mean\n\n t0 = time()\n print('Started training at %s' % t0)\n net.fit(X_train, y_train)\n print('Finished training. Took %i seconds' % (time() - t0))\n\n y_test_pred = net.predict(X_test)\n y_test_pred_proba = net.predict_proba(X_test)\n lscore = utils.multiclass_log_loss(y_test, y_test_pred_proba)\n ascore = net.score(X_test, y_test)\n\n print('Accuracy test score is %.4f' % ascore)\n print('Multiclass log loss test score is %.4f' % lscore)\n\n model_fname = utils.save_to_pickle(net, '%snet-%s-%s' % (args.out_dir, args.net_name, lscore))\n print('Model saved to %s' % model_fname)\n",
"#!/usr/bin/env python\r\n\r\nimport sys, time\r\nimport numpy as np\r\nfrom io import StringIO\r\nimport pickle as pickle\r\nfrom pandas import DataFrame\r\nfrom pandas import concat\r\nfrom pandas import read_pickle\r\nfrom pandas import cut\r\nfrom pandas import concat\r\nfrom pandas import set_option\r\nfrom sklearn.externals import joblib\r\nfrom sklearn.cross_validation import cross_val_score\r\nfrom sklearn.ensemble import RandomForestRegressor\r\nfrom sklearn.metrics import mean_absolute_error\r\nfrom djeval import *\r\n\r\nmsg(\"Hi, reading moves.\")\r\nmoves_df = read_pickle(sys.argv[1])\r\n\r\n\r\nprint('SHAPE', moves_df.shape)\r\nset_option('display.max_rows', None)\r\nprint(moves_df.memory_usage(index=True).sum())\r\nprint(moves_df.memory_usage(index=True))\r\n\r\ngrp = moves_df.groupby(['gamenum', 'side'])\r\nmove_aggs = grp['elo_predicted'].agg({'mean': np.mean, 'median' : np.median, 'stdev': np.std,\r\n '25': lambda x: np.percentile(x, 25),\r\n '10': lambda x: np.percentile(x, 10),\r\n 'min': lambda x: np.min(x),\r\n 'max': lambda x: np.max(x),\r\n })\r\n\r\n\r\njoblib.dump(move_aggs, '/data/move_aggs.p')\r\n\r\nexd = moves_df[['gamenum','side','elo_weighted_pred','elo_pred_weight']]\r\ngrp = exd.groupby(['gamenum', 'side'])\r\nwmove_aggs = grp.aggregate(np.sum)\r\nwmove_aggs['elo_pred'] = wmove_aggs['elo_weighted_pred'] / wmove_aggs['elo_pred_weight']\r\njoblib.dump(wmove_aggs, '/data/wmove_aggs.p')\r\nprint(wmove_aggs.head())\r\n",
"\"\"\"\r\nGiven a set of validation predictions, this script computes the optimal linear weights on the validation set.\r\nIt computes the weighted blend of test predictions, where some models are replaced by their bagged versions.\r\n\"\"\"\r\n\r\nimport os\r\nimport numpy as np\r\nimport sys\r\n\r\nimport theano\r\nimport theano.tensor as T\r\nimport scipy\r\n\r\nimport data\r\nimport utils\r\nimport nn_plankton\r\n\r\n\r\nCONFIGS = ['convroll4_doublescale_fs5', 'cp8', 'convroll4_big_wd_maxout512',\r\n 'triplescale_fs2_fs5', 'cr4_ds', 'convroll5_preinit_resume_drop@420',\r\n 'doublescale_fs5_latemerge_2233', 'convroll_all_broaden_7x7_weightdecay', 'convroll4_1024_lesswd',\r\n 'convroll4_big_weightdecay']\r\n\r\nBAGGED_CONFIGS = ['convroll4_doublescale_fs5', 'cp8', 'convroll4_big_wd_maxout512',\r\n 'cr4_ds', 'convroll5_preinit_resume_drop@420',\r\n 'convroll_all_broaden_7x7_weightdecay', 'convroll4_big_weightdecay']\r\n\r\n# creating and checking the paths\r\nn_models = len(CONFIGS)\r\nvalid_predictions_paths = []\r\nfor config in CONFIGS:\r\n p = 'predictions/valid--blend_featblend_%s--featblend_%s--avg-prob.npy' % (config, config)\r\n valid_predictions_paths.append(p)\r\n\r\ntest_predictions_paths = [p.replace('valid--', 'test--', 1) for p in valid_predictions_paths]\r\ntest_bagged_prediction_paths = []\r\nfor bagged_config in BAGGED_CONFIGS:\r\n bagged_p = 'predictions/bagged--test--blend_featblend_bagged_%s--avg-prob.npy' % bagged_config\r\n test_bagged_prediction_paths.append(bagged_p)\r\n for i in range(n_models):\r\n if bagged_config in test_predictions_paths[i]:\r\n test_predictions_paths[i] = bagged_p\r\n\r\ntest_unbagged_prediction_paths = [p for p in test_predictions_paths if 'bagged' not in p]\r\n\r\nmissing_predictions = []\r\nfor path in valid_predictions_paths + test_bagged_prediction_paths + test_unbagged_prediction_paths:\r\n if not os.path.isfile(path):\r\n missing_predictions.append(path)\r\n\r\nif missing_predictions:\r\n print('\\tPlease generate the following predictions:\\n\\t%s' % '\\n\\t'.join(missing_predictions))\r\n sys.exit(0)\r\n\r\n# loading validation predictions\r\ns = np.load(\"validation_split_v1.pkl\")\r\nt_valid = data.labels_train[s['indices_valid']]\r\n\r\npredictions_list = [np.load(path) for path in valid_predictions_paths]\r\npredictions_stack = np.array(predictions_list).astype(theano.config.floatX) # num_sources x num_datapoints x 121\r\n\r\nprint(\"Individual prediction errors\")\r\nindividual_prediction_errors = [utils.log_loss(p, t_valid) for p in predictions_list]\r\ndel predictions_list\r\nfor i in range(n_models):\r\n print(individual_prediction_errors[i], os.path.basename(valid_predictions_paths[i]))\r\nprint()\r\n\r\n# optimizing weights\r\nX = theano.shared(predictions_stack) # source predictions\r\nt = theano.shared(utils.one_hot(t_valid)) # targets\r\nW = T.vector('W')\r\n\r\ns = T.nnet.softmax(W).reshape((W.shape[0], 1, 1))\r\nweighted_avg_predictions = T.sum(X * s, axis=0) # T.tensordot(X, s, [[0], [0]])\r\nerror = nn_plankton.log_loss(weighted_avg_predictions, t)\r\ngrad = T.grad(error, W)\r\n\r\nf = theano.function([W], error)\r\ng = theano.function([W], grad)\r\n\r\nw_init = np.zeros(n_models, dtype=theano.config.floatX)\r\nout, loss, _ = scipy.optimize.fmin_l_bfgs_b(f, w_init, fprime=g, pgtol=1e-09, epsilon=1e-08, maxfun=10000)\r\n\r\nweights = np.exp(out)\r\nweights /= weights.sum()\r\n\r\nprint('Optimal weights')\r\nfor i in range(n_models):\r\n print(weights[i], os.path.basename(valid_predictions_paths[i]))\r\nprint()\r\n\r\nprint('Generating test set predictions')\r\npredictions_list = [np.load(path) for path in test_predictions_paths]\r\npredictions_stack = np.array(predictions_list) # num_sources x num_datapoints x 121\r\ndel predictions_list\r\n\r\ntarget_path = 'predictions/weighted_blend.npy'\r\nweighted_predictions = np.sum(predictions_stack * weights.reshape((weights.shape[0], 1, 1)), axis=0)\r\nnp.save(target_path, weighted_predictions)\r\nprint(' stored in %s' % target_path)\r\n",
"import sqlite3\r\nimport pandas as pd\r\nimport numpy as np\r\nimport csv\r\nimport gzip\r\nfrom collections import defaultdict\r\n\r\nif __name__ == '__main__':\r\n conn = sqlite3.connect('data/instacart.db')\r\n c = conn.cursor()\r\n\r\n # Get the orders properly sorted, so we can directly\r\n # group by user_id, order_id and then compute the weights.\r\n q = \"\"\"\r\n SELECT user_id, order_id, days_since_prior_order \r\n FROM orders\r\n ORDER BY order_number\r\n \"\"\"\r\n\r\n orders = pd.read_sql(q, conn)\r\n\r\n # First day is 0\r\n orders.ix[orders.days_since_prior_order == '', 'days_since_prior_order'] = 0\r\n\r\n # Cumsum to obtain total days since *first* order\r\n orders_g = orders.groupby(['user_id'])['days_since_prior_order'].cumsum()\r\n orders['cumulative_days'] = orders_g.astype(int)\r\n # But I need to subtract cumulative_days from the actual day of the \r\n # order we want to compute... which will be the maximum\r\n max_cum_days = orders.groupby(['user_id'])['cumulative_days'].max()\r\n max_cum_days = max_cum_days.reset_index()\r\n max_cum_days.columns = ['user_id', 'max_order_day']\r\n orders = pd.merge(orders, max_cum_days, on = \"user_id\", how = 'left')\r\n\r\n # Compute weights\r\n orders['w_periodic'] = (np.cos(2 * (orders['max_order_day'] - orders['cumulative_days']) / 365.0 * 3.14) + 1) / 2\r\n orders['w_decay'] = 1.0 / ((365 - orders['cumulative_days']) / 365.0 + 1.0)\r\n\r\n # Remove unwanted columns (for DB storage, let's try not do duplicate)\r\n res = orders\r\n res = res.drop(['days_since_prior_order', 'cumulative_days', 'max_order_day'],\r\n axis = 1)\r\n\r\n # Insert weights into the DB\r\n res.to_sql('order_weights', conn, if_exists = 'replace')\r\n c.execute(\"CREATE INDEX IF NOT EXISTS idx_tmp1 ON order_weights(user_id)\")\r\n c.execute(\"CREATE INDEX IF NOT EXISTS idx_tmp2 ON order_weights(order_id)\")\r\n\r\n\r\n",
"\t\r\n# Grid Search for Algorithm Tuning\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom sklearn import datasets\r\nfrom sklearn.linear_model import Ridge\r\nfrom sklearn.grid_search import GridSearchCV\r\n\r\n\r\n### Plotting function ###\r\n\r\nfrom matplotlib import pyplot as plt\r\nfrom sklearn.metrics import r2_score\r\n\r\ndef plot_r2(y, y_pred, title):\r\n plt.figure(figsize=(10, 6))\r\n plt.grid()\r\n plt.scatter(y, y_pred, marker='.')\r\n plt.xlabel(\"Actual Target\"); plt.ylabel(\"Predicted Target\")\r\n plt.title(title)\r\n xmn, xmx = plt.xlim()\r\n ymn, ymx = plt.ylim()\r\n mx = max(xmx, ymx) \r\n buff = mx * .1\r\n plt.text(xmn + buff, mx - buff, \"R2 Score: %f\" % (r2_score(y, y_pred), ), size=15)\r\n plt.plot([0., mx], [0., mx])\r\n plt.xlim(xmn, mx)\r\n plt.ylim(ymn, mx)\r\n\r\n\r\n\r\n### Preprocessing ### \r\n\r\ndataset = pd.read_csv(\"train.csv\")\r\ndataset.head()\r\nfeats = dataset.drop(\"revenue\", axis=1) \r\nX = feats.values #features\r\ny = dataset[\"revenue\"].values #target\r\n\r\n\r\n\r\n# prepare a range of alpha values to test\r\nalphas = np.array([1,0.1,0.01,0.001,0.0001,0])\r\n# 100000 works best.\r\n\r\n# create and fit a ridge regression model, testing each alpha\r\nmodel = Ridge()\r\ngrid = GridSearchCV(estimator=model, param_grid=dict(alpha=alphas))\r\ny_pred = grid.fit(X, y)\r\n\r\nr2_score(y, y_pred)\r\nrmse = sqrt(mean_squared_error(y, y_pred))\r\nprint(rmse)",
"import numpy as np\r\n\r\nimport theano \r\nimport theano.tensor as T\r\n\r\nimport lasagne as nn\r\n\r\nimport data\r\nimport load\r\nimport nn_plankton\r\nimport dihedral\r\nimport tmp_dnn\r\nimport tta\r\n\r\n\r\n\r\npatch_sizes = [(95, 95), (47, 47), (47, 47)]\r\naugmentation_params = {\r\n 'zoom_range': (1 / 1.6, 1.6),\r\n 'rotation_range': (0, 360),\r\n 'shear_range': (-20, 20),\r\n 'translation_range': (-10, 10),\r\n 'do_flip': True,\r\n 'allow_stretch': 1.3,\r\n}\r\n\r\nbatch_size = 128 // 4\r\nchunk_size = 32768 // 4\r\nnum_chunks_train = 840\r\n\r\nmomentum = 0.9\r\nlearning_rate_schedule = {\r\n 0: 0.003,\r\n 700: 0.0003,\r\n 800: 0.00003,\r\n}\r\n\r\nvalidate_every = 20\r\nsave_every = 20\r\n\r\n\r\ndef estimate_scale(img):\r\n return np.maximum(img.shape[0], img.shape[1]) / 85.0\r\n\r\nscale_factors = [estimate_scale, 2.0, 5.0] # combine size-based rescaling + fixed rescaling\r\n \r\n\r\n# augmentation_transforms_test = []\r\n# for flip in [True, False]:\r\n# for zoom in [1/1.3, 1/1.2, 1/1.1, 1.0, 1.1, 1.2, 1.3]:\r\n# for rot in np.linspace(0.0, 360.0, 5, endpoint=False):\r\n# tf = data.build_augmentation_transform(zoom=(zoom, zoom), rotation=rot, flip=flip)\r\n# augmentation_transforms_test.append(tf)\r\naugmentation_transforms_test = tta.build_quasirandom_transforms(70, **{\r\n 'zoom_range': (1 / 1.4, 1.4),\r\n 'rotation_range': (0, 360),\r\n 'shear_range': (-10, 10),\r\n 'translation_range': (-8, 8),\r\n 'do_flip': True,\r\n 'allow_stretch': 1.2,\r\n})\r\n\r\n\r\ndata_loader = load.ZmuvMultiscaleDataLoader(scale_factors=scale_factors, num_chunks_train=num_chunks_train,\r\n patch_sizes=patch_sizes, chunk_size=chunk_size, augmentation_params=augmentation_params,\r\n augmentation_transforms_test=augmentation_transforms_test)\r\n\r\n\r\n# Conv2DLayer = nn.layers.cuda_convnet.Conv2DCCLayer\r\n# MaxPool2DLayer = nn.layers.cuda_convnet.MaxPool2DCCLayer\r\n\r\nConv2DLayer = tmp_dnn.Conv2DDNNLayer\r\nMaxPool2DLayer = tmp_dnn.MaxPool2DDNNLayer\r\n\r\n\r\ndef build_model():\r\n # variable scale part\r\n l0_variable = nn.layers.InputLayer((batch_size, 1, patch_sizes[0][0], patch_sizes[0][1]))\r\n l0c = dihedral.CyclicSliceLayer(l0_variable)\r\n\r\n l1a = Conv2DLayer(l0c, num_filters=32, filter_size=(3, 3), border_mode=\"same\", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1))\r\n l1b = Conv2DLayer(l1a, num_filters=32, filter_size=(3, 3), border_mode=\"same\", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1))\r\n l1 = MaxPool2DLayer(l1b, ds=(3, 3), strides=(2, 2))\r\n\r\n l2a = Conv2DLayer(l1, num_filters=64, filter_size=(3, 3), border_mode=\"same\", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1))\r\n l2b = Conv2DLayer(l2a, num_filters=64, filter_size=(3, 3), border_mode=\"same\", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1))\r\n l2 = MaxPool2DLayer(l2b, ds=(3, 3), strides=(2, 2))\r\n\r\n l3a = Conv2DLayer(l2, num_filters=128, filter_size=(3, 3), border_mode=\"same\", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1))\r\n l3b = Conv2DLayer(l3a, num_filters=128, filter_size=(3, 3), border_mode=\"same\", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1))\r\n l3c = Conv2DLayer(l3b, num_filters=128, filter_size=(3, 3), border_mode=\"same\", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1))\r\n l3 = MaxPool2DLayer(l3c, ds=(3, 3), strides=(2, 2))\r\n\r\n l4a = Conv2DLayer(l3, num_filters=256, filter_size=(3, 3), border_mode=\"same\", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1))\r\n l4b = Conv2DLayer(l4a, num_filters=256, filter_size=(3, 3), border_mode=\"same\", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1))\r\n l4c = Conv2DLayer(l4b, num_filters=256, filter_size=(3, 3), border_mode=\"same\", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1))\r\n l4 = MaxPool2DLayer(l4c, ds=(3, 3), strides=(2, 2))\r\n l4f = nn.layers.flatten(l4)\r\n\r\n l5 = nn.layers.DenseLayer(nn.layers.dropout(l4f, p=0.5), num_units=256, W=nn_plankton.Orthogonal(1.0), b=nn.init.Constant(0.1))\r\n l5r = dihedral.CyclicRollLayer(l5)\r\n\r\n l6 = nn.layers.DenseLayer(nn.layers.dropout(l5r, p=0.5), num_units=256, W=nn_plankton.Orthogonal(1.0), b=nn.init.Constant(0.1))\r\n l_variable = dihedral.CyclicPoolLayer(l6, pool_function=nn_plankton.rms)\r\n\r\n\r\n # fixed scale part 1\r\n l0_fixed1 = nn.layers.InputLayer((batch_size, 1, patch_sizes[1][0], patch_sizes[1][1]))\r\n l0c = dihedral.CyclicSliceLayer(l0_fixed1)\r\n\r\n l1a = Conv2DLayer(l0c, num_filters=16, filter_size=(3, 3), border_mode=\"same\", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1))\r\n l1b = Conv2DLayer(l1a, num_filters=16, filter_size=(3, 3), border_mode=\"same\", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1))\r\n l1 = MaxPool2DLayer(l1b, ds=(3, 3), strides=(2, 2))\r\n\r\n l2a = Conv2DLayer(l1, num_filters=32, filter_size=(3, 3), border_mode=\"same\", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1))\r\n l2b = Conv2DLayer(l2a, num_filters=32, filter_size=(3, 3), border_mode=\"same\", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1))\r\n l2 = MaxPool2DLayer(l2b, ds=(3, 3), strides=(2, 2))\r\n\r\n l3a = Conv2DLayer(l2, num_filters=64, filter_size=(3, 3), border_mode=\"same\", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1))\r\n l3b = Conv2DLayer(l3a, num_filters=64, filter_size=(3, 3), border_mode=\"same\", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1))\r\n l3c = Conv2DLayer(l3b, num_filters=64, filter_size=(3, 3), border_mode=\"same\", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1))\r\n l3 = MaxPool2DLayer(l3c, ds=(3, 3), strides=(2, 2))\r\n l3f = nn.layers.flatten(l3)\r\n\r\n l4 = nn.layers.DenseLayer(nn.layers.dropout(l3f, p=0.5), num_units=128, W=nn_plankton.Orthogonal(1.0), b=nn.init.Constant(0.1))\r\n l4r = dihedral.CyclicRollLayer(l4)\r\n\r\n l5 = nn.layers.DenseLayer(nn.layers.dropout(l4r, p=0.5), num_units=128, W=nn_plankton.Orthogonal(1.0), b=nn.init.Constant(0.1))\r\n l_fixed1 = dihedral.CyclicPoolLayer(l5, pool_function=nn_plankton.rms) \r\n\r\n\r\n # fixed scale part 2\r\n l0_fixed2 = nn.layers.InputLayer((batch_size, 1, patch_sizes[2][0], patch_sizes[2][1]))\r\n l0c = dihedral.CyclicSliceLayer(l0_fixed2)\r\n\r\n l1a = Conv2DLayer(l0c, num_filters=16, filter_size=(3, 3), border_mode=\"same\", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1))\r\n l1b = Conv2DLayer(l1a, num_filters=16, filter_size=(3, 3), border_mode=\"same\", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1))\r\n l1 = MaxPool2DLayer(l1b, ds=(3, 3), strides=(2, 2))\r\n\r\n l2a = Conv2DLayer(l1, num_filters=32, filter_size=(3, 3), border_mode=\"same\", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1))\r\n l2b = Conv2DLayer(l2a, num_filters=32, filter_size=(3, 3), border_mode=\"same\", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1))\r\n l2 = MaxPool2DLayer(l2b, ds=(3, 3), strides=(2, 2))\r\n\r\n l3a = Conv2DLayer(l2, num_filters=64, filter_size=(3, 3), border_mode=\"same\", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1))\r\n l3b = Conv2DLayer(l3a, num_filters=64, filter_size=(3, 3), border_mode=\"same\", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1))\r\n l3c = Conv2DLayer(l3b, num_filters=64, filter_size=(3, 3), border_mode=\"same\", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1))\r\n l3 = MaxPool2DLayer(l3c, ds=(3, 3), strides=(2, 2))\r\n l3f = nn.layers.flatten(l3)\r\n\r\n l4 = nn.layers.DenseLayer(nn.layers.dropout(l3f, p=0.5), num_units=128, W=nn_plankton.Orthogonal(1.0), b=nn.init.Constant(0.1))\r\n l4r = dihedral.CyclicRollLayer(l4)\r\n\r\n l5 = nn.layers.DenseLayer(nn.layers.dropout(l4r, p=0.5), num_units=128, W=nn_plankton.Orthogonal(1.0), b=nn.init.Constant(0.1))\r\n l_fixed2 = dihedral.CyclicPoolLayer(l5, pool_function=nn_plankton.rms) \r\n\r\n\r\n # merge the parts\r\n l_merged = nn.layers.concat([l_variable, l_fixed1, l_fixed2])\r\n\r\n l7 = nn.layers.DenseLayer(nn.layers.dropout(l_merged, p=0.5), num_units=data.num_classes, nonlinearity=T.nnet.softmax, W=nn_plankton.Orthogonal(1.0))\r\n\r\n return [l0_variable, l0_fixed1, l0_fixed2], l7\r\n",
"# Script to train base model\r\n\r\n\r\nimport argparse\r\nfrom time import time\r\n\r\nimport numpy as np\r\n\r\nfrom plankton import utils\r\nfrom plankton import get_net\r\n\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument('net_name')\r\nparser.add_argument('--X_train_train_npy', default='data/X_train_train')\r\nparser.add_argument('--X_train_test_npy', default='data/X_train_test')\r\nparser.add_argument('--y_train_train_superclass', default='data/y_train_train_superclass')\r\nparser.add_argument('--y_train_test_superclass', default='data/y_train_test_superclass')\r\nparser.add_argument('--hw', default=48, type=int)\r\nparser.add_argument('--out_dir', default='models/')\r\nargs = parser.parse_args()\r\n\r\nif __name__ == '__main__':\r\n print('Loading training images')\r\n X_train, X_test = np.load('%s_%i.npy' % (args.X_train_train_npy, args.hw)), np.load('%s_%i.npy' % (args.X_train_test_npy, args.hw))\r\n y_train, y_test = np.load('%s_%i.npy' % (args.y_train_train_superclass, args.hw)), np.load('%s_%i.npy' % (args.y_train_test_superclass, args.hw))\r\n print(X_train.shape, X_test.shape, y_train.shape, y_test.shape)\r\n\r\n print('Loading model definition from %s' % args.net_name)\r\n net = get_net(args.net_name)\r\n\r\n # Pass mean value of training data to the batch iterator\r\n X_train_mean = np.mean(X_train, axis=0)\r\n net.batch_iterator_train.mean = X_train_mean\r\n net.batch_iterator_test.mean = X_train_mean\r\n\r\n t0 = time()\r\n print('Started training at %s' % t0)\r\n net.fit(X_train, y_train)\r\n print('Finished training. Took %i seconds' % (time() - t0))\r\n\r\n y_test_pred = net.predict(X_test)\r\n y_test_pred_proba = net.predict_proba(X_test)\r\n lscore = utils.multiclass_log_loss(y_test, y_test_pred_proba)\r\n ascore = net.score(X_test, y_test)\r\n\r\n print('Accuracy test score is %.4f' % ascore)\r\n print('Multiclass log loss test score is %.4f' % lscore)\r\n\r\n model_fname = utils.save_to_pickle(net, '%snet-%s-%s' % (args.out_dir, args.net_name, lscore))\r\n print('Model saved to %s' % model_fname)\r\n",
"#!/usr/bin/env python\r\n\r\nfrom pandas import *\r\nimport numpy as np\r\nfrom djeval import *\r\n\r\nmsg(\"Hi, reading yy_df.\")\r\nyy_df = read_pickle(sys.argv[1])\r\n\r\n# warn about bad data counts\r\n\r\ncounts = yy_df.count(axis=0)\r\ncols_bad = (counts % 50000 != 0)\r\nnum_bad_columns = len(counts[cols_bad])\r\nif num_bad_columns > 0:\r\n msg(\"WARNING there are %i bad columns.\" % num_bad_columns)\r\n msg(\"They are:\")\r\n msg(counts[cols_bad])\r\n\r\nfor colname in yy_df.columns.values:\r\n if np.sum(notnull(yy_df[colname])) % 50000 != 0:\r\n print('%s has only %i notnull values' % (colname, np.sum(notnull(yy_df[colname]))))\r\n# msg('Looking at %s' % colname)\r\n if yy_df[colname].dtype != 'float32':\r\n if np.sum(np.isfinite(yy_df['meanecho'])) % 50000 != 0:\r\n print('%s has only %i finite values' % (colname, np.sum(np.isfinite(yy_df['meanecho']))))\r\n else:\r\n X = np.asanyarray(yy_df[colname])\r\n if (X.dtype.char in np.typecodes['AllFloat'] and not np.isfinite(X.sum())\r\n and not np.isfinite(X).all()):\r\n msg('OOOPPPS Problem with %s' % colname)\r\n raise ValueError('PROBLEM VAR')\r\n",
"__author__ = 'dudevil'\r\n\r\nimport pickle\r\nimport functools\r\nimport operator\r\nimport numpy as np\r\nimport pandas as pd\r\nimport theano\r\nimport theano.tensor as T\r\nfrom importlib import import_module\r\nfrom theano.tensor.nnet import conv\r\nfrom sklearn.metrics import confusion_matrix\r\nimport lasagne\r\n\r\ndef load_config(file):\r\n model = import_module('models.%s' % file)\r\n assert hasattr(model, 'build_model')\r\n assert hasattr(model, 'train_params')\r\n return model.build_model(), model.train_params\r\n\r\n\r\ndef save_network(net, filename='data/tidy/net.pickle'):\r\n with open(filename, 'wb') as f:\r\n pickle.dump(lasagne.layers.get_all_param_values(net['output']), f, -1)\r\n\r\n\r\ndef load_network(filename='data/tidy/net.pickle'):\r\n with open(filename, 'r') as f:\r\n net = pickle.load(f)\r\n return net\r\n\r\n\r\ndef print_network(net, logger=None):\r\n for layer in list(net.values()):\r\n output_shape = layer.output_shape\r\n msg = \" {:<18}\\t{:<20}\\tproduces {:>7} outputs\".format(\r\n getattr(layer, 'name') if getattr(layer, 'name') is not None else layer.__class__.__name__,\r\n str(output_shape),\r\n str(functools.reduce(operator.mul, output_shape[1:])),\r\n )\r\n if logger is not None:\r\n logger.info(msg)\r\n else:\r\n print(msg)\r\n\r\n\r\ndef images_byerror(y_pred, y_true, images):\r\n # this is a cunfusing code and should not be used\r\n diff = np.abs(y_true - y_pred)\r\n order = diff.argsort()[::-1]\r\n return pd.Series(index=images[order], data=diff[order])\r\n\r\n\r\ndef make_predictions_series(y_pred, images):\r\n return pd.Series(index=images, data=y_pred)\r\n\r\n\r\ndef kappa(y_true, y_pred):\r\n \"\"\"\r\n Quadratic kappa score: http://www.kaggle.com/c/diabetic-retinopathy-detection/details/evaluation\r\n Implementaion mostly taken from: http://scikit-learn-laboratory.readthedocs.org/en/latest/_modules/skll/metrics.html\r\n\r\n :param y_true:\r\n :param y_pred:\r\n :return:\r\n \"\"\"\r\n # Ensure that the lists are both the same length\r\n assert(len(y_true) == len(y_pred))\r\n\r\n # This rather crazy looking typecast is intended to work as follows:\r\n # If an input is an int, the operations will have no effect.\r\n # If it is a float, it will be rounded and then converted to an int\r\n # because the ml_metrics package requires ints.\r\n # If it is a str like \"1\", then it will be converted to a (rounded) int.\r\n # If it is a str that can't be typecast, then the user is\r\n # given a hopefully useful error message.\r\n # Note: numpy and python 3.3 use bankers' rounding.\r\n try:\r\n y_true = [int(np.round(float(y))) for y in y_true]\r\n y_pred = [int(np.round(float(y))) for y in y_pred]\r\n except ValueError as e:\r\n print(\"Kappa values must be integers or strings\")\r\n raise e\r\n\r\n # Figure out normalized expected values\r\n min_rating = min(min(y_true), min(y_pred))\r\n max_rating = max(max(y_true), max(y_pred))\r\n\r\n # shift the values so that the lowest value is 0\r\n # (to support scales that include negative values)\r\n y_true = [y - min_rating for y in y_true]\r\n y_pred = [y - min_rating for y in y_pred]\r\n\r\n # Build the observed/confusion matrix\r\n num_ratings = max_rating - min_rating + 1\r\n observed = confusion_matrix(y_true, y_pred,\r\n labels=list(range(num_ratings)))\r\n num_scored_items = float(len(y_true))\r\n\r\n # Build weight array if weren't passed one\r\n weights = np.empty((num_ratings, num_ratings))\r\n for i in range(num_ratings):\r\n for j in range(num_ratings):\r\n weights[i, j] = abs(i - j) ** 2\r\n\r\n hist_true = np.bincount(y_true, minlength=num_ratings)\r\n hist_true = hist_true[: num_ratings] / num_scored_items\r\n hist_pred = np.bincount(y_pred, minlength=num_ratings)\r\n hist_pred = hist_pred[: num_ratings] / num_scored_items\r\n expected = np.outer(hist_true, hist_pred)\r\n\r\n # Normalize observed array\r\n observed = observed / num_scored_items\r\n\r\n # If all weights are zero, that means no disagreements matter.\r\n k = 1.0\r\n if np.count_nonzero(weights):\r\n k -= (sum(sum(weights * observed)) / sum(sum(weights * expected)))\r\n\r\n return k\r\n\r\n\r\ndef get_predictions(output, batch_size=64):\r\n \"\"\"\r\n This function decodes the neural net output to predictions as described in\r\n this paper: https://web.missouri.edu/~zwyw6/files/rank.pdf\r\n :param minibatch:\r\n :return:\r\n \"\"\"\r\n assert len(output.shape) == 2\r\n last = np.ones(output.shape[0], dtype=np.bool)\r\n preds = np.zeros(output.shape[0], dtype=np.int8)\r\n\r\n for col in output.T:\r\n last = last & col\r\n preds += last\r\n return preds\r\n\r\n\r\ndef to_ordinal(y, n_classes=4):\r\n res = np.zeros((len(y), n_classes), dtype=theano.config.floatX)\r\n for i, cls in enumerate(y):\r\n res[i, :cls] = 1.\r\n return res\r\n\r\n\r\ndef gaussian_filter(kernel_shape):\r\n x = np.zeros((kernel_shape, kernel_shape), dtype=theano.config.floatX)\r\n\r\n def gauss(x, y, sigma=2.0):\r\n Z = 2 * np.pi * sigma**2\r\n return 1./Z * np.exp(-(x**2 + y**2) / (2. * sigma**2))\r\n\r\n for i in range(kernel_shape):\r\n for j in range(kernel_shape):\r\n x[i,j] = gauss(i-4., j-4.)\r\n\r\n return x / np.sum(x)\r\n\r\n\r\ndef lecun_lcn(input, img_shape, kernel_shape, threshold=1e-4):\r\n \"\"\"\r\n Yann LeCun's local contrast normalization\r\n This is performed per-colorchannel!!!\r\n\r\n http://yann.lecun.com/exdb/publis/pdf/jarrett-iccv-09.pdf\r\n \"\"\"\r\n input = input.reshape((input.shape[0], 1, input.shape[1], input.shape[2]))\r\n X = T.matrix(dtype=input.dtype)\r\n X = X.reshape((len(input), 1, img_shape[0], img_shape[1]))\r\n\r\n filter_shape = (1, 1, kernel_shape, kernel_shape)\r\n filters = theano.shared(gaussian_filter(kernel_shape).reshape(filter_shape))\r\n\r\n convout = conv.conv2d(input=X,\r\n filters=filters,\r\n image_shape=(input.shape[0], 1, img_shape[0], img_shape[1]),\r\n filter_shape=filter_shape,\r\n border_mode='full')\r\n\r\n # For each pixel, remove mean of 9x9 neighborhood\r\n mid = int(np.floor(kernel_shape / 2.))\r\n centered_X = X - convout[:, :, mid:-mid, mid:-mid]\r\n\r\n # Scale down norm of 9x9 patch if norm is bigger than 1\r\n sum_sqr_XX = conv.conv2d(input=T.sqr(X),\r\n filters=filters,\r\n image_shape=(input.shape[0], 1, img_shape[0], img_shape[1]),\r\n filter_shape=filter_shape,\r\n border_mode='full')\r\n\r\n denom = T.sqrt(sum_sqr_XX[:, :, mid:-mid, mid:-mid])\r\n per_img_mean = T.mean(denom, axis=(1, 2))\r\n divisor = T.largest(per_img_mean.dimshuffle(0, 1, 'x', 'x'), denom)\r\n divisor = T.maximum(divisor, threshold)\r\n\r\n new_X = centered_X / divisor\r\n #new_X = theano.tensor.flatten(new_X, outdim=3)\r\n\r\n f = theano.function([X], new_X)\r\n return f(input)\r\n\r\n\r\ndef lcn_image(images, kernel_size=9):\r\n \"\"\"\r\n This assumes image is 01c and the output will be c01 (compatible with conv2d)\r\n\r\n :param image:\r\n :param inplace:\r\n :return:\r\n \"\"\"\r\n image_shape = (images.shape[1], images.shape[2])\r\n if len(images.shape) == 3:\r\n # this is greyscale images\r\n output = lecun_lcn(images, image_shape, kernel_size)\r\n else:\r\n # color image, assume RGB\r\n r = images[:, :, :, 0]\r\n g = images[:, :, :, 1]\r\n b = images[:, :, :, 2]\r\n\r\n output = np.concatenate((\r\n lecun_lcn(r, image_shape, kernel_size),\r\n lecun_lcn(g, image_shape, kernel_size),\r\n lecun_lcn(b, image_shape, kernel_size)),\r\n axis=1\r\n )\r\n return output\r\n\r\n\r\ndef global_contrast_normalize(X, scale=1., subtract_mean=True, use_std=False,\r\n sqrt_bias=0., min_divisor=1e-8):\r\n \"\"\" Code adopted from here: https://github.com/lisa-lab/pylearn2/blob/master/pylearn2/expr/preprocessing.py\r\n but can work with b01c and bc01 orderings\r\n\r\n An Analysis of Single-Layer\r\n Networks in Unsupervised Feature Learning\". AISTATS 14, 2011.\r\n http://www.stanford.edu/~acoates/papers/coatesleeng_aistats_2011.pdf\r\n \"\"\"\r\n assert X.ndim > 2, \"X.ndim must be more than 2\"\r\n scale = float(scale)\r\n assert scale >= min_divisor\r\n\r\n # Note: this is per-example mean across pixels, not the\r\n # per-pixel mean across examples. So it is perfectly fine\r\n # to subtract this without worrying about whether the current\r\n # object is the train, valid, or test set.\r\n aggr_axis = tuple(np.arange(len(X.shape) - 1) + 1)\r\n mean = np.mean(X, axis=aggr_axis, keepdims=True)\r\n if subtract_mean:\r\n X = X - mean[:, np.newaxis] # Makes a copy.\r\n else:\r\n X = X.copy()\r\n\r\n if use_std:\r\n # ddof=1 simulates MATLAB's var() behaviour, which is what Adam\r\n # Coates' code does.\r\n ddof = 1\r\n\r\n # If we don't do this, X.var will return nan.\r\n if X.shape[1] == 1:\r\n ddof = 0\r\n\r\n normalizers = np.sqrt(sqrt_bias + np.var(X, axis=aggr_axis, ddof=ddof, keepdims=True)) / scale\r\n else:\r\n normalizers = np.sqrt(sqrt_bias + np.sum((X ** 2), axis=aggr_axis, keepdims=True)) / scale\r\n\r\n # Don't normalize by anything too small.\r\n normalizers[normalizers < min_divisor] = 1.\r\n X /= normalizers[:, np.newaxis] # Does not make a copy.\r\n return X",
"import unittest\r\nimport tempfile\r\nimport os\r\nimport numpy as np\r\n\r\nimport caffe\r\n\r\ndef simple_net_file(num_output):\r\n \"\"\"Make a simple net prototxt, based on test_net.cpp, returning the name\r\n of the (temporary) file.\"\"\"\r\n\r\n f = tempfile.NamedTemporaryFile(delete=False)\r\n f.write(\"\"\"name: 'testnet' force_backward: true\r\n layers { type: DUMMY_DATA name: 'data' top: 'data' top: 'label'\r\n dummy_data_param { num: 5 channels: 2 height: 3 width: 4\r\n num: 5 channels: 1 height: 1 width: 1\r\n data_filler { type: 'gaussian' std: 1 }\r\n data_filler { type: 'constant' } } }\r\n layers { type: CONVOLUTION name: 'conv' bottom: 'data' top: 'conv'\r\n convolution_param { num_output: 11 kernel_size: 2 pad: 3\r\n weight_filler { type: 'gaussian' std: 1 }\r\n bias_filler { type: 'constant' value: 2 } }\r\n weight_decay: 1 weight_decay: 0 }\r\n layers { type: INNER_PRODUCT name: 'ip' bottom: 'conv' top: 'ip'\r\n inner_product_param { num_output: \"\"\" + str(num_output) + \"\"\"\r\n weight_filler { type: 'gaussian' std: 2.5 }\r\n bias_filler { type: 'constant' value: -3 } } }\r\n layers { type: SOFTMAX_LOSS name: 'loss' bottom: 'ip' bottom: 'label'\r\n top: 'loss' }\"\"\")\r\n f.close()\r\n return f.name\r\n\r\nclass TestNet(unittest.TestCase):\r\n def setUp(self):\r\n self.num_output = 13\r\n net_file = simple_net_file(self.num_output)\r\n self.net = caffe.Net(net_file)\r\n # fill in valid labels\r\n self.net.blobs['label'].data[...] = \\\r\n np.random.randint(self.num_output,\r\n size=self.net.blobs['label'].data.shape)\r\n os.remove(net_file)\r\n\r\n def test_memory(self):\r\n \"\"\"Check that holding onto blob data beyond the life of a Net is OK\"\"\"\r\n\r\n params = sum(list(map(list, iter(self.net.params.values()))), [])\r\n blobs = list(self.net.blobs.values())\r\n del self.net\r\n\r\n # now sum everything (forcing all memory to be read)\r\n total = 0\r\n for p in params:\r\n total += p.data.sum() + p.diff.sum()\r\n for bl in blobs:\r\n total += bl.data.sum() + bl.diff.sum()\r\n\r\n def test_forward_backward(self):\r\n self.net.forward()\r\n self.net.backward()\r\n\r\n def test_inputs_outputs(self):\r\n self.assertEqual(self.net.inputs, [])\r\n self.assertEqual(self.net.outputs, ['loss'])\r\n\r\n def test_save_and_read(self):\r\n f = tempfile.NamedTemporaryFile(delete=False)\r\n f.close()\r\n self.net.save(f.name)\r\n net_file = simple_net_file(self.num_output)\r\n net2 = caffe.Net(net_file, f.name)\r\n os.remove(net_file)\r\n os.remove(f.name)\r\n for name in self.net.params:\r\n for i in range(len(self.net.params[name])):\r\n self.assertEqual(abs(self.net.params[name][i].data\r\n - net2.params[name][i].data).sum(), 0)\r\n",
"import numpy as np\r\nimport pandas as pd\r\nfrom keras.models import Sequential\r\nfrom keras.layers.core import Dropout, Activation\r\nfrom keras.layers.normalization import BatchNormalization\r\nfrom keras.layers.advanced_activations import PReLU\r\nfrom keras.utils import np_utils\r\nfrom sklearn.metrics import roc_auc_score\r\nfrom sklearn.preprocessing import LabelEncoder\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom keras.layers.core import Dense\r\nimport datetime\r\n\r\n## settings\r\nprojPath = './'\r\ndataset_version = \"mp4\"\r\nmodel_type = \"keras\"\r\nseed_value = 578943\r\ntodate = datetime.datetime.now().strftime(\"%Y%m%d\")\r\nnp.random.seed(seed_value)\r\nnp.random.seed(1778) # for reproducibility\r\nneed_normalise=True\r\nneed_categorical=False\r\n\r\ndef getDummy(df,col):\r\n category_values=df[col].unique()\r\n data=[[0 for i in range(len(category_values))] for i in range(len(df))]\r\n dic_category=dict()\r\n for i,val in enumerate(list(category_values)):\r\n dic_category[str(val)]=i\r\n # print dic_category\r\n for i in range(len(df)):\r\n data[i][dic_category[str(df[col][i])]]=1\r\n\r\n data=np.array(data)\r\n for i,val in enumerate(list(category_values)):\r\n df.loc[:,\"_\".join([col,str(val)])]=data[:,i]\r\n\r\n return df\r\n\r\ntrain = pd.read_csv(projPath + 'input/xtrain_'+ dataset_version + '.csv')\r\nid_train = train.QuoteNumber\r\ny_train_quote_flag = train.QuoteConversion_Flag\r\ny_train = train.QuoteConversion_Flag\r\ntrain.drop('QuoteNumber', axis = 1, inplace = True)\r\ntrain.drop('QuoteConversion_Flag', axis = 1, inplace = True)\r\ntrain.drop(['PropertyField6', 'GeographicField10A'], axis=1, inplace = True)\r\n\r\ntest = pd.read_csv(projPath + 'input/xtest_'+ dataset_version + '.csv')\r\nid_test = test.QuoteNumber\r\ntest.drop('QuoteNumber', axis = 1, inplace = True)\r\ntest.drop(['PropertyField6', 'GeographicField10A'], axis=1, inplace = True)\r\n\r\nfor f in test.columns:#\r\n if train[f].dtype=='object':\r\n lbl = LabelEncoder()\r\n lbl.fit(list(train[f])+list(test[f]))\r\n train[f] = lbl.transform(list(train[f].values))\r\n test[f] = lbl.transform(list(test[f].values))\r\n\r\n#try to encode all params less than 100 to be category\r\nif need_categorical:\r\n #row bind train and test\r\n x = train.append(test, ignore_index=True)\r\n del train\r\n del test\r\n for f in x.columns:#\r\n category_values= set(list(x[f].unique()))\r\n if len(category_values) < 4:\r\n print (f)\r\n x = getDummy(x, f)\r\n test = x.iloc[260753:, ]\r\n train = x.iloc[:260753:, ]\r\n\r\nencoder = LabelEncoder()\r\ny_train = encoder.fit_transform(y_train).astype(np.int32)\r\ny_train = np_utils.to_categorical(y_train)\r\n\r\nprint (\"processsing finished\")\r\ntrain = np.array(train)\r\ntrain = train.astype(np.float32)\r\ntest = np.array(test)\r\ntest = test.astype(np.float32)\r\nif need_normalise:\r\n scaler = StandardScaler().fit(train)\r\n train = scaler.transform(train)\r\n test = scaler.transform(test)\r\n\r\n# folds\r\nxfolds = pd.read_csv(projPath + 'input/xfolds.csv')\r\n# work with 5-fold split\r\nfold_index = xfolds.fold5\r\nfold_index = np.array(fold_index) - 1\r\nn_folds = len(np.unique(fold_index))\r\n\r\nnb_classes = 2\r\nprint(nb_classes, 'classes')\r\n\r\ndims = train.shape[1]\r\nprint(dims, 'dims')\r\n\r\nauc_scores=[]\r\nbest_score=-1\r\n\r\nparam_grid = [[1024, 0.1, 0.6, 1024, 0.6, 420, 0.6, 400],\r\n [1324, 0.15, 0.6, 712, 0.8, 520, 0.7, 400],\r\n [96, 0.05, 0.4, 1512, 0.4, 330, 0.6, 400]]\r\n\r\n# storage structure for forecasts\r\nmvalid = np.zeros((train.shape[0],len(param_grid)))\r\nmfull = np.zeros((test.shape[0],len(param_grid)))\r\n\r\n## build 2nd level forecasts\r\nfor i in range(len(param_grid)):\r\n print(\"processing parameter combo:\", param_grid[i])\r\n print(\"Combo:\", i+1, \"of\", len(param_grid))\r\n # loop over folds\r\n # Recompile model on each fold\r\n for j in range(0,n_folds):\r\n # configure model with j-th combo of parameters\r\n x = param_grid[i]\r\n model = Sequential()\r\n model.add(Dense(x[0], input_shape=(dims,)))\r\n model.add(Dropout(x[1]))# input dropout\r\n model.add(PReLU())\r\n model.add(BatchNormalization())\r\n model.add(Dropout(x[2]))\r\n model.add(Dense(x[3]))\r\n model.add(PReLU())\r\n model.add(BatchNormalization())\r\n model.add(Dropout(x[4]))\r\n model.add(Dense(x[5]))\r\n model.add(PReLU())\r\n model.add(BatchNormalization())\r\n model.add(Dropout(x[6]))\r\n model.add(Dense(nb_classes))\r\n model.add(Activation('softmax'))\r\n model.compile(loss='binary_crossentropy', optimizer=\"sgd\")\r\n\r\n idx0 = np.where(fold_index != j)\r\n idx1 = np.where(fold_index == j)\r\n x0 = np.array(train)[idx0,:][0]\r\n x1 = np.array(train)[idx1,:][0]\r\n y0 = np.array(y_train)[idx0]\r\n y1 = np.array(y_train)[idx1]\r\n\r\n # fit the model on observations associated with subject whichSubject in this fold\r\n model.fit(x0, y0, nb_epoch=x[7], batch_size=1256)\r\n mvalid[idx1,i] = model.predict_proba(x1)[:,1]\r\n y_pre = model.predict_proba(x1)[:,1]\r\n scores = roc_auc_score(y1[:,1],y_pre)\r\n print('AUC score', scores)\r\n del model\r\n print(\"finished fold:\", j)\r\n\r\n print(\"Building full prediction model for test set.\")\r\n # configure model with j-th combo of parameters\r\n x = param_grid[i]\r\n model = Sequential()\r\n model.add(Dense(x[0], input_shape=(dims,)))\r\n model.add(Dropout(x[1]))# input dropout\r\n model.add(PReLU())\r\n model.add(BatchNormalization())\r\n model.add(Dropout(x[2]))\r\n model.add(Dense(x[3]))\r\n model.add(PReLU())\r\n model.add(BatchNormalization())\r\n model.add(Dropout(x[4]))\r\n model.add(Dense(x[5]))\r\n model.add(PReLU())\r\n model.add(BatchNormalization())\r\n model.add(Dropout(x[6]))\r\n model.add(Dense(nb_classes))\r\n model.add(Activation('softmax'))\r\n model.compile(loss='binary_crossentropy', optimizer=\"sgd\")\r\n # fit on complete dataset\r\n\r\n model.fit(np.array(train), y_train, nb_epoch=x[7], batch_size=1256)\r\n mfull[:,i] = model.predict_proba(np.array(test))[:,1]\r\n\r\n del model\r\n print(\"finished full prediction\")\r\n\r\n## store the results\r\n# add indices etc\r\nmvalid = pd.DataFrame(mvalid)\r\nmvalid.columns = [model_type + str(i) for i in range(0, mvalid.shape[1])]\r\nmvalid['QuoteNumber'] = id_train\r\nmvalid['QuoteConversion_Flag'] = y_train_quote_flag\r\n\r\nmfull = pd.DataFrame(mfull)\r\nmfull.columns = [model_type + str(i) for i in range(0, mfull.shape[1])]\r\nmfull['QuoteNumber'] = id_test\r\n\r\n\r\n# save the files\r\nmvalid.to_csv(projPath + 'metafeatures/prval_' + model_type + todate + '_data' + dataset_version + '_seed' + str(seed_value) + '.csv', index = False, header = True)\r\nmfull.to_csv(projPath + 'metafeatures/prfull_' + model_type + todate + '_data' + dataset_version + '_seed' + str(seed_value) + '.csv', index = False, header = True)\r\n",
"# -*- coding: utf-8 -*-\n\n\"\"\"\ncode to combine data from different algorithms with different degrees and\ncoefficient\n\"\"\"\n\nimport pandas as pd\n\nprint('Reading data...')\nxgb1 = pd.read_csv(\"../output/xgboost_1.csv\")\nxgb2 = pd.read_csv(\"../output/xgboost_2.csv\")\nrf = pd.read_csv(\"../output/rf.csv\")\ngbm = pd.read_csv(\"../output/gbm.csv\")\n\nprint('Combining...')\nind = rf.Id\n\nd_xgb1 = 1.5\nd_xgb2 = 0.4\nd_rf = 0.006\nd_gbm = 0.006\n\nc_xgb1 = 0.765\nc_xgb2 = 0.035\nc_rf = 0.15\nc_gbm = 0.15\n\nxgb1 = xgb1.Hazard ** d_xgb1 * c_xgb1\nxgb2 = xgb2.Hazard ** d_xgb2 * c_xgb2\nrf = rf.Hazard ** d_rf * c_rf\ngbm = gbm.Hazard ** d_gbm * c_gbm\n\nyp = xgb1 + xgb2 + rf + gbm\n\nprint('Saving...')\npreds = pd.DataFrame({\"Id\": ind, \"Hazard\": yp})\npreds = preds.set_index('Id')\npreds.to_csv('../output/combined_predictions.csv')",
"# -*- coding: utf-8 -*-\n\n\"\"\"\nNot compatible with Python 3\nCreated on Fri Dec 4 18:11:16 2015\n\n@author: Sravani Kamisetty\n\"\"\"\n\nfrom pandas import Series, DataFrame\n\n\nfrom sklearn import tree\nimport pandas as pd\nimport numpy as np\nimport nltk\nimport re\nfrom nltk.stem import WordNetLemmatizer\nfrom sklearn.svm import LinearSVC\nfrom sklearn.metrics import classification_report\nimport sklearn.metrics\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn import grid_search\nfrom sklearn.linear_model import LogisticRegression\n\ndef computeAccuracy(Y,YPredicted):\n count = 0\n for i in range(0,len(Y)):\n if Y[i] == YPredicted[i]:\n count = count + 1\n\n return (count/len(Y) * 100)\n\n# A combination of Word lemmatization + LinearSVC model finally pushes the accuracy score past 80%\n\ntraindf = pd.read_json(\"resources/train.json\")\ntraindf['ingredients_clean_string'] = [' , '.join(z).strip() for z in traindf['ingredients']]\ntraindf['ingredients_string'] = [' '.join([WordNetLemmatizer().lemmatize(re.sub('[^A-Za-z]', ' ', line)) for line in lists]).strip() for lists in traindf['ingredients']]\n\n\ntestdf = pd.read_json(\"resources/test.json\")\ntestdf['ingredients_clean_string'] = [' , '.join(z).strip() for z in testdf['ingredients']]\ntestdf['ingredients_string'] = [' '.join([WordNetLemmatizer().lemmatize(re.sub('[^A-Za-z]', ' ', line)) for line in lists]).strip() for lists in testdf['ingredients']]\n\n\n\ncorpustr = traindf['ingredients_string']\nvectorizertr = TfidfVectorizer(stop_words='english',\n ngram_range = ( 1 , 1 ),analyzer=\"word\",\n max_df = .57 , binary=False , token_pattern=r'\\w+' , sublinear_tf=False)\ntfidftr=vectorizertr.fit_transform(corpustr).todense()\ncorpusts = testdf['ingredients_string']\nvectorizerts = TfidfVectorizer(stop_words='english')\ntfidfts=vectorizertr.transform(corpusts)\n\npredictors_tr = tfidftr\n\ntargets_tr = traindf['cuisine']\n\npredictors_ts = tfidfts\n\n# LR, SCV\nclassifier = LinearSVC(C=0.80, penalty=\"l2\", dual=False)\nparameters = {'C':[1, 10]}\nclf = LinearSVC()\nclf = LogisticRegression()\nclassifier = grid_search.GridSearchCV(clf, parameters)\nclassifier=classifier.fit(predictors_tr,targets_tr)\n\n#decision trees\n#clf = tree.DecisionTreeClassifier()\n#parameters = {'max_depth':[100]}\n#classifier=clf.fit(predictors_tr,targets_tr)\n\npredictions_train = classifier.predict(predictors_tr)\n\npredictions=classifier.predict(predictors_ts)\nfor i in range(0,predictions.size):\n predictions[i] = str(predictions[i])\nfor i in range(0,predictions_train.size):\n predictions_train[i] = str(predictions_train[i])\n\n#print predictions_train\ntestdf['cuisine'] = predictions\ntestdf = testdf.sort('id' , ascending=True)\n\n#print computeAccuracy(predictors_tr,predictions_train)\n#print predictions_train\n#print computeAccuracy(predictions,targets_ts)\n\n#print testdf\n\ntestdf[['id' , 'cuisine' ]].to_csv(\"subTree.csv\");\n",
"from numpy.matlib import repmat\n\nimport numpy as np\n\n\nclass ToyXValidationData():\n \"\"\"\n Class that generates easy data for XValidation (list of matrices/lists)\n to test the pipeline\n \n @author Heiko\n \"\"\"\n @staticmethod\n def get():\n X_list = []\n y_list = []\n dim = 10\n for _ in range(10):\n n = np.random.randint(10, 100)\n y = (np.random.rand(n) > .5).astype(np.int64)\n X = np.random.randn(n, dim) + repmat(y, dim, 1).T\n X_list += [X]\n y_list += [y]\n \n return X_list, y_list\n",
"import numpy as np\r\nimport pandas as pd\r\nfrom sklearn import metrics\r\nfrom glob import glob\r\nimport sys\r\nfrom xgb_classifier import xgb_classifier\r\ndef myauc(y,pred):\r\n fpr, tpr, thresholds = metrics.roc_curve(y, pred, pos_label=1)\r\n return metrics.auc(fpr, tpr)\r\ndef train_predict(X,y,Xt,yt=[],c=1):\r\n if c==1:\r\n #clf=xgb_classifier(num_round=45,eta=0.1,min_child_weight=5,depth=10, subsample=0.5,col=1) \r\n clf=xgb_classifier(num_round=45,eta=0.1,min_child_weight=20,depth=20, subsample=0.1,col=0.7)\r\n return clf.train_predict(X,y,Xt,yt)\r\nnames=['HandStart','FirstDigitTouch','BothStartLoadPhase','LiftOff','Replace','BothReleased']\r\n\r\nsubjects = list(range(1,13))\r\nreal=[]\r\nfor subject in subjects:\r\n fnames = ['../../data/train/subj%d_series%d_events.csv' % (subject,i) for i in range(7,9)]\r\n for fname in fnames:\r\n labels= pd.read_csv(fname)\r\n real.append(labels)\r\n print(fname,labels.shape)\r\nreal=pd.concat(real)\r\nprint('combined', real.shape)\r\nreal['subject']=real['id'].apply(lambda x:x.split('_')[0][4:])\r\nreal.drop('id',inplace=True,axis=1)\r\nxx=[]\r\nbestweight=[]\r\nbestscore=[]\r\nstart={}\r\nfor i in range(1,13):\r\n start[i]=0\r\n\r\npbest=pd.read_csv('../vali-stack_srk1/vali1_3_new_cv.csv')\r\nfor name in names:\r\n pbest[name]=0.0\r\nimport os\r\nX=None\r\nfor subk in range(1,13):\r\n X= None\r\n for fname in os.listdir('cv'):\r\n if 'sub%d.csv'%subk not in fname:\r\n continue\r\n \r\n sub2=pd.read_csv('cv/'+fname)\r\n if X is None:\r\n X=np.array(sub2[names])\r\n else:\r\n X=np.hstack((X,np.array(sub2[names])))\r\n # column stack all the models, X.shape[1]=num_electrode * num_classifier * num_events\r\n\r\n print('predict sub%d'%subk, X.shape)\r\n mask=np.array(real['subject']==str(subk)) \r\n X1=X[:X.shape[0]/2]\r\n X2=X[X.shape[0]/2:] \r\n for name in names:\r\n \r\n y=np.array(real[name])\r\n y=y[mask]\r\n \r\n y1=y[:X.shape[0]/2]\r\n y2=y[X.shape[0]/2:]\r\n yr2=train_predict(X1,y1,X2,yt=y2,c=1)\r\n \r\n xx.append(myauc(y2,yr2))\r\n print(name, xx[-1])\r\n yr1=train_predict(X2,y2,X1,yt=y1,c=1)\r\n xx.append(myauc(y1,yr1))\r\n print(name, xx[-1])\r\n tmp=np.array(pbest[name])\r\n tmp[mask]=np.concatenate((yr1,yr2))\r\n pbest[name]=tmp\r\n \r\n print('%d average'%subk,np.mean(xx))\r\npbest.to_csv('xgball.csv',index=False) \r\n",
"#!/usr/bin/env python\r\n\r\nimport sys, time\r\nimport numpy as np\r\nfrom io import StringIO\r\nimport pickle as pickle\r\nfrom pandas import DataFrame\r\nfrom pandas import concat\r\nfrom pandas import read_pickle\r\nfrom pandas import cut\r\nfrom pandas import concat\r\nfrom sklearn.externals import joblib\r\nfrom sklearn.cross_validation import cross_val_score\r\nfrom sklearn.ensemble import RandomForestRegressor\r\nfrom sklearn.metrics import mean_absolute_error\r\nfrom djeval import *\r\n\r\nmsg(\"Hi, reading moves.\")\r\nmoves_df = read_pickle(sys.argv[1])\r\n\r\ntrain_df = moves_df[moves_df['elo'].notnull()]\r\nthe_iter = train_df.iterrows()\r\nfor ix, row in the_iter:\r\n print('%f | halfply:%f moverscore:%f side:%i depth:%f seldepth:%f num_bestmoves:%f num_bestmove_changes:%f bestmove_depths_agreeing:%f deepest_change:%f elo:%f' % (row['movergain'], row['halfply'], row['moverscore'], row['side'], row['depth'], row['seldepth'], row['num_bestmoves'], row['num_bestmove_changes'], row['bestmove_depths_agreeing'], row['deepest_change'], row['elo']))\r\n# print '%f | garbage:%f' % (row['movergain'], np.random.rand())\r\n",
"#based on \r\n# https://www.kaggle.com/sushize/homesite-quote-conversion/xgb-stop/log\r\n# abd\r\n#https://www.kaggle.com/mpearmain/homesite-quote-conversion/xgboost-benchmark/code\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport xgboost as xgb\r\nfrom sklearn import preprocessing\r\nfrom sklearn.cross_validation import train_test_split\r\n\r\nseed = 1718\r\n\r\ntrain = pd.read_csv(\"./input/train.csv\")\r\ntest = pd.read_csv(\"./input/test.csv\")\r\n\r\n\r\ntrain = train.drop('QuoteNumber', axis=1) \r\ntest = test.drop('QuoteNumber', axis=1)\r\n\r\n# Lets play with some dates\r\ntrain['Date'] = pd.to_datetime(pd.Series(train['Original_Quote_Date']))\r\ntrain = train.drop('Original_Quote_Date', axis=1)\r\n\r\ntest['Date'] = pd.to_datetime(pd.Series(test['Original_Quote_Date']))\r\ntest = test.drop('Original_Quote_Date', axis=1)\r\n\r\ntrain['Year'] = train['Date'].apply(lambda x: int(str(x)[:4]))\r\ntrain['Month'] = train['Date'].apply(lambda x: int(str(x)[5:7]))\r\ntrain['weekday'] = train['Date'].dt.dayofweek\r\n\r\ntest['Year'] = test['Date'].apply(lambda x: int(str(x)[:4]))\r\ntest['Month'] = test['Date'].apply(lambda x: int(str(x)[5:7]))\r\ntest['weekday'] = test['Date'].dt.dayofweek\r\n\r\ntrain = train.drop('Date', axis=1) \r\ntest = test.drop('Date', axis=1)\r\n\r\ntrain = train.fillna(0)\r\ntest = test.fillna(0) \r\n\r\nfeatures = list(train.columns[1:]) #la colonne 0 est le quote_conversionflag \r\nprint(features)\r\n\r\n\r\nfor f in train.columns:\r\n if train[f].dtype=='object':\r\n print(f)\r\n lbl = preprocessing.LabelEncoder()\r\n lbl.fit(list(train[f].values) + list(test[f].values))\r\n train[f] = lbl.transform(list(train[f].values))\r\n test[f] = lbl.transform(list(test[f].values))\r\n\r\ndtrain = xgb.DMatrix(train[features], train['QuoteConversion_Flag']) \r\ndtest = xgb.DMatrix(test[features])\r\n\r\n\r\nparam = {\r\n #1- General Parameters \r\n 'booster' : \"gbtree\", #booster [default=gbtree]\r\n 'silent': 0 , #silent [default=0]\r\n #'nthread' : -1 , #nthread [default to maximum number of threads available if not set]\r\n\r\n #2A-Parameters for Tree Booster \r\n 'eta' :0.023, # eta [default=0.3] range: [0,1]\r\n #'gamma':0 ,#gamma [default=0] range: [0,∞]\r\n 'max_depth' :6, #max_depth [default=6] range: [1,∞]\r\n #'min_child_weight':1, #default=1]range: [0,∞]\r\n #'max_delta_step':0, #max_delta_step [default=0] range: [0,∞]\r\n 'subsample' :0.83, #subsample [default=1]range: (0,1]\r\n 'colsample_bytree' :0.77, #colsample_bytree [default=1]range: (0,1]\r\n #'lambda': 1, #lambda [default=1]\r\n #'alpha':0.0001, #alpha [default=0]\r\n \r\n \r\n #2B- Parameters for Linear Booster\r\n #'lambda': 0, #lambda [default=0]\r\n #'alpha':0, #alpha [default=0]\r\n #'lambda_bias':0, #default 0\r\n \r\n #3- earning Task Parameters\r\n 'objective': 'binary:logistic', #objective [ default=reg:linear ]\r\n #'base_score'=0.5, #base_score [ default=0.5 ]\r\n 'eval_metric' : 'auc', #eval_metric [ default according to objective ]\r\n 'seed':seed #seed [ default=0 ]\r\n \r\n }\r\n\r\nnum_boost_round = 1800\r\n\r\nbst = xgb.train(\r\n params=param, \r\n dtrain=dtrain,\r\n num_boost_round=num_boost_round\r\n #watchlist\r\n )\r\n\r\n \r\n#prediction\r\npreds= bst.predict(dtest)\r\nprint (preds)\r\n\r\n#print to CSV\r\nsample = pd.read_csv('./input/sample_submission.csv')\r\nsample.QuoteConversion_Flag = preds\r\nsample.to_csv('xgb_shizepython.csv', index=False)\r\n",
"# -*- coding: utf-8 -*-\r\n\r\nimport os, logging, argparse\r\nimport pandas as pd\r\nimport collections\r\nfrom time import time\r\nimport itertools\r\n\r\n\r\ndef main(metadata_path = \"data/raw/meta-kaggle-2016\",\r\n interim_path = \"data/interim\"):\r\n \r\n \"\"\"Aggregates extracted features from script to repository level.\r\n \r\n Builds teams_df from Teams.csv by dropping all repos without python files,\r\n aggregates all source code metrics by repository ID and compute basic\r\n statistical metrics per repository, like mean and sum. Finally, combines\r\n these statistics with teams_df and save it to <interim_path>.\"\"\"\r\n \r\n # logging\r\n logger = logging.getLogger(__name__)\r\n \r\n # normalize paths\r\n metadata_path = os.path.normpath(metadata_path)\r\n logger.debug(\"Path to meta-kaggle-2016 normalized: {}\"\r\n .format(metadata_path))\r\n interim_path = os.path.normpath(interim_path)\r\n logger.debug(\"Path to iterim data normalized: {}\"\r\n .format(interim_path))\r\n \r\n # load Teams.csv\r\n teams_df = pd.read_csv(os.path.join(metadata_path, 'Teams.csv'),\r\n low_memory=False)\r\n logger.info(\"Loaded Team.csv with {} repositories.\"\r\n .format(len(teams_df)))\r\n \r\n # load extracted_df\r\n extracted_df = pd.read_pickle(os.path.join(interim_path,\r\n 'extracted_df.pkl'))\r\n logger.info(\"Loaded extracted_df.pkl with {} files.\"\r\n .format(len(extracted_df)))\r\n \r\n # start aggregation\r\n start = time()\r\n \r\n # reduces teams_df by filtering for repos with python scripts\r\n ids_counter = collections.Counter(extracted_df['repo_id'])\r\n ids_set = set(ids_counter)\r\n in_features = [repo_id in ids_set for repo_id in teams_df['Id'].tolist()]\r\n teams_df = teams_df[in_features].set_index('Id')\r\n logger.info(\"Reduced teams_df to {} entries with python scripts.\"\r\n .format(len(teams_df)))\r\n \r\n # add column 'n_scripts' which counts the number of scripts\r\n teams_df['n_scripts'] = [ids_counter[key] for key in teams_df.index]\r\n logger.info(\"Added column 'n_scripts' which is the number of scripts.\")\r\n \r\n # transform boolean columns (like _is_error flags) to integer\r\n n_bool = len(extracted_df.select_dtypes('bool').columns)\r\n for col in extracted_df.select_dtypes('bool').columns:\r\n extracted_df[col] = extracted_df[col].astype(int)\r\n logger.info(\"Turned {} boolean columns of extracted_df to integer.\"\r\n .format(n_bool))\r\n \r\n # splits extracted_df along 'repo_id'\r\n grouped = extracted_df.groupby('repo_id')\r\n logger.info(\"Splitted extracted_df into groups along repo_id.\")\r\n \r\n # aggregate features\r\n repos = {}\r\n for repo_id, group in grouped:\r\n stats = []\r\n # remove first column 'repo_id'\r\n for col_name in group.drop('repo_id', axis=1):\r\n # calculate relevant statistics\r\n stats.extend([group[col_name].sum(), group[col_name].mean()])\r\n repos[repo_id] = stats\r\n columns = list(itertools.product(extracted_df.columns[1:], ['sum','mean']))\r\n # build aggregated_df from dict repos\r\n aggregated_df = pd.DataFrame.from_dict(repos,\r\n orient='index',\r\n columns=columns)\r\n logger.info(\"{} features on script-level aggregated to {} on repo-level.\"\r\n .format(extracted_df.shape[1]-1, aggregated_df.shape[1]))\r\n \r\n # concatenates teams_df with aggregated_df\r\n aggregated_df = pd.concat([teams_df, aggregated_df], axis=1)\r\n logger.info(\"Combined aggregated features with teams_df.\")\r\n \r\n # export aggregated_df as pickle file to interim folder\r\n aggregated_df.to_pickle(os.path.join(interim_path, 'aggregated_df.pkl'))\r\n logger.info(\"Saved aggregated_df to {}.\"\r\n .format(os.path.join(interim_path, 'aggregated_df.pkl')))\r\n \r\n # logging time passed\r\n end = time()\r\n time_passed = pd.Timedelta(seconds=end-start).round(freq='s')\r\n logger.info(\"Time needed to extract the features: {}\".format(time_passed))\r\n\r\n\r\nif __name__ == '__main__':\r\n \r\n # configure logging\r\n logging.basicConfig(\r\n level = logging.DEBUG,\r\n format = \"%(asctime)s %(name)-20s %(levelname)-8s %(message)s\",\r\n filename = \"logs/aggregate.log\",\r\n datefmt = \"%a, %d %b %Y %H:%M:%S\")\r\n \r\n # parse arguments\r\n parser = argparse.ArgumentParser(\r\n description = \"Aggregates extracted features.\")\r\n parser.add_argument(\r\n '--metadata_path',\r\n default = \"data/raw/meta-kaggle-2016\",\r\n help = \"path to Kaggle Meta Dataset 2016, where Teams.csv is \\\r\n (default: data/raw/meta-kaggle-2016)\")\r\n parser.add_argument(\r\n '--interim_path',\r\n default = \"data/interim\",\r\n help = \"path to to load extracted_df and store aggregated_df \\\r\n (default: data/interim)\")\r\n args = parser.parse_args()\r\n \r\n # run main\r\n main(args.metadata_path, args.interim_path)",
"import numpy as np\r\nimport theano\r\nimport theano.tensor as T\r\nfrom theano.ifelse import ifelse\r\n\r\n\r\nclass HiddenLayer(object):\r\n def __init__(self, rng, input, n_in, n_out, training_mode, dropout_prob, activation, weights_variance):\r\n self.input = input\r\n if activation == 'tanh':\r\n activation_function = lambda x: T.tanh(x)\r\n W_values = np.asarray(rng.uniform(\r\n low=-np.sqrt(6. / (n_in + n_out)),\r\n high=np.sqrt(6. / (n_in + n_out)),\r\n size=(n_in, n_out)), dtype='float32')\r\n b_values = np.zeros((n_out,), dtype='float32')\r\n\r\n elif activation == 'relu':\r\n activation_function = lambda x: T.maximum(0.0, x)\r\n W_values = np.asarray(rng.normal(0.0, weights_variance, size=(n_in, n_out)), dtype='float32')\r\n b_values = np.ones((n_out,), dtype='float32') / 10.0\r\n else:\r\n raise ValueError('unknown activation function')\r\n\r\n self.W = theano.shared(value=W_values, name='W', borrow=True)\r\n self.b = theano.shared(value=b_values, name='b', borrow=True)\r\n\r\n inv_dropout_prob = np.float32(1.0 - dropout_prob)\r\n lin_output = ifelse(T.eq(training_mode, 1),\r\n T.dot(self._dropout(rng, input, dropout_prob), self.W) + self.b,\r\n T.dot(input, inv_dropout_prob * self.W) + self.b)\r\n\r\n self.output = activation_function(lin_output)\r\n self.weights = [self.W, self.b]\r\n\r\n def _dropout(self, rng, layer, p):\r\n srng = T.shared_randomstreams.RandomStreams(rng.randint(777777))\r\n mask = srng.binomial(n=1, p=1 - p, size=layer.shape)\r\n output = layer * T.cast(mask, 'float32')\r\n return output\r\n",
"import pandas as pd\r\nimport numpy as np\r\nimport ml_metrics as metrics\r\nfrom sklearn.feature_extraction.text import TfidfTransformer\r\n\r\nprint(\"read training data\")\r\ntrain = pd.read_csv(\"../Data/train.csv\")\r\ntarget = train['target']\r\nNAME=train.columns[0:]\r\nid=train['id']\r\ndel train['id'] \r\ndel train['target']\r\n\r\ntransformer = TfidfTransformer()\r\ntrain = transformer.fit_transform(train)\r\n\r\ntrain=pd.DataFrame(train.toarray())\r\ntrain.columns=NAME[1:-1]\r\ntrain=pd.concat([id,train,target],axis=1)\r\ntrain.to_csv(\"../Data/train_tfidf.csv\",index=False)\r\n\r\ntest = pd.read_csv(\"../Data/test.csv\")\r\nid = test['id']\r\ndel test['id']\r\ntest = transformer.transform(test)\r\ntest=pd.DataFrame(test.toarray())\r\ntest.columns=NAME[1:-1]\r\ntest=pd.concat([id,test],axis=1)\r\ntest.to_csv(\"C:/Users/kawa/Desktop/kaggle/otto/test_tfidf.csv\",index=False)\r\n\r\n\r\n\r\n",
"import numpy as np\r\nimport theano\r\nimport theano.tensor as T\r\n\r\nimport lasagne as nn\r\n\r\n\r\ndef array_tf_0(arr):\r\n return arr\r\n\r\ndef array_tf_90(arr):\r\n axes_order = list(range(arr.ndim - 2)) + [arr.ndim - 1, arr.ndim - 2]\r\n slices = [slice(None) for _ in range(arr.ndim - 2)] + [slice(None), slice(None, None, -1)]\r\n return arr[tuple(slices)].transpose(axes_order)\r\n\r\ndef array_tf_180(arr):\r\n slices = [slice(None) for _ in range(arr.ndim - 2)] + [slice(None, None, -1), slice(None, None, -1)]\r\n return arr[tuple(slices)]\r\n\r\ndef array_tf_270(arr):\r\n axes_order = list(range(arr.ndim - 2)) + [arr.ndim - 1, arr.ndim - 2]\r\n slices = [slice(None) for _ in range(arr.ndim - 2)] + [slice(None, None, -1), slice(None)]\r\n return arr[tuple(slices)].transpose(axes_order)\r\n\r\n\r\ndef array_tf_0f(arr): # horizontal flip\r\n slices = [slice(None) for _ in range(arr.ndim - 2)] + [slice(None), slice(None, None, -1)]\r\n return arr[tuple(slices)]\r\n\r\ndef array_tf_90f(arr):\r\n axes_order = list(range(arr.ndim - 2)) + [arr.ndim - 1, arr.ndim - 2]\r\n slices = [slice(None) for _ in range(arr.ndim - 2)] + [slice(None), slice(None)]\r\n # slicing does nothing here, technically I could get rid of it.\r\n return arr[tuple(slices)].transpose(axes_order)\r\n\r\ndef array_tf_180f(arr):\r\n slices = [slice(None) for _ in range(arr.ndim - 2)] + [slice(None, None, -1), slice(None)]\r\n return arr[tuple(slices)]\r\n\r\ndef array_tf_270f(arr):\r\n axes_order = list(range(arr.ndim - 2)) + [arr.ndim - 1, arr.ndim - 2]\r\n slices = [slice(None) for _ in range(arr.ndim - 2)] + [slice(None, None, -1), slice(None, None, -1)]\r\n return arr[tuple(slices)].transpose(axes_order)\r\n\r\n\r\n# c01b versions of the helper functions\r\n\r\ndef array_tf_0_c01b(arr):\r\n return arr\r\n\r\ndef array_tf_90_c01b(arr):\r\n axes_order = [0, 2, 1, 3]\r\n slices = [slice(None), slice(None), slice(None, None, -1), slice(None)]\r\n return arr[tuple(slices)].transpose(axes_order)\r\n\r\ndef array_tf_180_c01b(arr):\r\n slices = [slice(None), slice(None, None, -1), slice(None, None, -1), slice(None)]\r\n return arr[tuple(slices)]\r\n\r\ndef array_tf_270_c01b(arr):\r\n axes_order = [0, 2, 1, 3]\r\n slices = [slice(None), slice(None, None, -1), slice(None), slice(None)]\r\n return arr[tuple(slices)].transpose(axes_order)\r\n\r\n\r\ndef array_tf_0f_c01b(arr): # horizontal flip\r\n slices = [slice(None), slice(None), slice(None, None, -1), slice(None)]\r\n return arr[tuple(slices)]\r\n\r\ndef array_tf_90f_c01b(arr):\r\n axes_order = [0, 2, 1, 3]\r\n slices = [slice(None), slice(None), slice(None), slice(None)]\r\n # slicing does nothing here, technically I could get rid of it.\r\n return arr[tuple(slices)].transpose(axes_order)\r\n\r\ndef array_tf_180f_c01b(arr):\r\n slices = [slice(None), slice(None, None, -1), slice(None), slice(None)]\r\n return arr[tuple(slices)]\r\n\r\ndef array_tf_270f_c01b(arr):\r\n axes_order = [0, 2, 1, 3]\r\n slices = [slice(None), slice(None, None, -1), slice(None, None, -1), slice(None)]\r\n return arr[tuple(slices)].transpose(axes_order)\r\n\r\n\r\n\r\n\r\nclass CyclicSliceLayer(nn.layers.Layer):\r\n \"\"\"\r\n This layer stacks rotations of 0, 90, 180, and 270 degrees of the input\r\n along the batch dimension.\r\n If the input has shape (batch_size, num_channels, r, c),\r\n then the output will have shape (4 * batch_size, num_channels, r, c).\r\n Note that the stacking happens on axis 0, so a reshape to\r\n (4, batch_size, num_channels, r, c) will separate the slice axis.\r\n \"\"\"\r\n def __init__(self, input_layer):\r\n super(CyclicSliceLayer, self).__init__(input_layer)\r\n\r\n def get_output_shape_for(self, input_shape):\r\n return (4 * input_shape[0],) + input_shape[1:]\r\n\r\n def get_output_for(self, input, *args, **kwargs):\r\n return T.concatenate([\r\n array_tf_0(input),\r\n array_tf_90(input),\r\n array_tf_180(input),\r\n array_tf_270(input),\r\n ], axis=0)\r\n\r\n\r\nclass DihedralSliceLayer(nn.layers.Layer):\r\n \"\"\"\r\n This layer stacks rotations of 0, 90, 180, and 270 degrees of the input,\r\n as well as their horizontal flips, along the batch dimension.\r\n If the input has shape (batch_size, num_channels, r, c),\r\n then the output will have shape (8 * batch_size, num_channels, r, c).\r\n Note that the stacking happens on axis 0, so a reshape to\r\n (8, batch_size, num_channels, r, c) will separate the slice axis.\r\n \"\"\"\r\n def __init__(self, input_layer):\r\n super(DihedralSliceLayer, self).__init__(input_layer)\r\n\r\n def get_output_shape_for(self, input_shape):\r\n return (8 * input_shape[0],) + input_shape[1:]\r\n\r\n def get_output_for(self, input, *args, **kwargs):\r\n return T.concatenate([\r\n array_tf_0(input),\r\n array_tf_90(input),\r\n array_tf_180(input),\r\n array_tf_270(input),\r\n array_tf_0f(input),\r\n array_tf_90f(input),\r\n array_tf_180f(input),\r\n array_tf_270f(input),\r\n ], axis=0)\r\n\r\n\r\nclass CyclicRollLayer(nn.layers.Layer):\r\n \"\"\"\r\n This layer turns (n_views * batch_size, num_features) into\r\n (n_views * batch_size, n_views * num_features) by rolling\r\n and concatenating feature maps.\r\n \"\"\"\r\n def __init__(self, input_layer):\r\n super(CyclicRollLayer, self).__init__(input_layer)\r\n self.compute_permutation_matrix()\r\n\r\n def compute_permutation_matrix(self):\r\n map_identity = np.arange(4)\r\n map_rot90 = np.array([1, 2, 3, 0])\r\n\r\n valid_maps = []\r\n current_map = map_identity\r\n for k in range(4):\r\n valid_maps.append(current_map)\r\n current_map = current_map[map_rot90]\r\n\r\n self.perm_matrix = np.array(valid_maps)\r\n\r\n def get_output_shape_for(self, input_shape):\r\n return (input_shape[0], 4*input_shape[1])\r\n\r\n def get_output_for(self, input, *args, **kwargs):\r\n s = input.shape\r\n input_unfolded = input.reshape((4, s[0] // 4, s[1]))\r\n\r\n permuted_inputs = []\r\n for p in self.perm_matrix:\r\n input_permuted = input_unfolded[p].reshape(s)\r\n permuted_inputs.append(input_permuted)\r\n\r\n return T.concatenate(permuted_inputs, axis=1) # concatenate long the channel axis\r\n\r\n\r\nclass DihedralRollLayer(nn.layers.Layer):\r\n \"\"\"\r\n This layer turns (n_views * batch_size, num_features) into\r\n (n_views * batch_size, n_views * num_features) by rolling\r\n and concatenating feature maps.\r\n \"\"\"\r\n def __init__(self, input_layer):\r\n super(DihedralRollLayer, self).__init__(input_layer)\r\n self.compute_permutation_matrix()\r\n\r\n def compute_permutation_matrix(self):\r\n map_identity = np.arange(8)\r\n map_rot90 = np.array([1, 2, 3, 0, 5, 6, 7, 4]) # 7, 4, 5, 6]) # CORRECTED\r\n map_flip = np.array([4, 5, 6, 7, 0, 1, 2, 3])\r\n\r\n valid_maps = []\r\n current_map = map_identity\r\n for k in range(4):\r\n valid_maps.append(current_map)\r\n current_map = current_map[map_rot90]\r\n\r\n for k in range(4):\r\n valid_maps.append(current_map[map_flip])\r\n current_map = current_map[map_rot90]\r\n\r\n self.perm_matrix = np.array(valid_maps)\r\n\r\n def get_output_shape_for(self, input_shape):\r\n return (input_shape[0], 8*input_shape[1])\r\n\r\n def get_output_for(self, input, *args, **kwargs):\r\n s = input.shape\r\n input_unfolded = input.reshape((8, s[0] // 8, s[1]))\r\n\r\n permuted_inputs = []\r\n for p in self.perm_matrix:\r\n input_permuted = input_unfolded[p].reshape(s)\r\n permuted_inputs.append(input_permuted)\r\n\r\n return T.concatenate(permuted_inputs, axis=1) # concatenate long the channel axis\r\n\r\n\r\nclass CyclicConvRollLayer(CyclicRollLayer):\r\n \"\"\"\r\n This layer turns (n_views * batch_size, num_channels, r, c) into\r\n (n_views * batch_size, n_views * num_channels, r, c) by rolling\r\n and concatenating feature maps.\r\n It also applies the correct inverse transforms to the r and c\r\n dimensions to align the feature maps.\r\n \"\"\"\r\n def __init__(self, input_layer):\r\n super(CyclicConvRollLayer, self).__init__(input_layer)\r\n self.inv_tf_funcs = [array_tf_0, array_tf_270, array_tf_180, array_tf_90]\r\n\r\n def get_output_shape_for(self, input_shape):\r\n return (input_shape[0], 4*input_shape[1]) + input_shape[2:]\r\n\r\n def get_output_for(self, input, *args, **kwargs):\r\n s = input.shape\r\n input_unfolded = input.reshape((4, s[0] // 4, s[1], s[2], s[3]))\r\n\r\n permuted_inputs = []\r\n for p, inv_tf in zip(self.perm_matrix, self.inv_tf_funcs):\r\n input_permuted = inv_tf(input_unfolded[p].reshape(s))\r\n permuted_inputs.append(input_permuted)\r\n\r\n return T.concatenate(permuted_inputs, axis=1) # concatenate long the channel axis\r\n\r\n\r\nclass DihedralConvRollLayer(DihedralRollLayer):\r\n \"\"\"\r\n This layer turns (n_views * batch_size, num_channels, r, c) into\r\n (n_views * batch_size, n_views * num_channels, r, c) by rolling\r\n and concatenating feature maps.\r\n It also applies the correct inverse transforms to the r and c\r\n dimensions to align the feature maps.\r\n \"\"\"\r\n def __init__(self, input_layer):\r\n super(DihedralConvRollLayer, self).__init__(input_layer)\r\n self.inv_tf_funcs = [array_tf_0, array_tf_270, array_tf_180, array_tf_90,\r\n array_tf_0f, array_tf_90f, array_tf_180f, array_tf_270f]\r\n\r\n raise RuntimeError(\"The implementation of this class is not correct.\")\r\n\r\n def get_output_shape_for(self, input_shape):\r\n return (input_shape[0], 8*input_shape[1]) + input_shape[2:]\r\n\r\n def get_output_for(self, input, *args, **kwargs):\r\n s = input.shape\r\n input_unfolded = input.reshape((8, s[0] // 8, s[1], s[2], s[3]))\r\n\r\n permuted_inputs = []\r\n for p, inv_tf in zip(self.perm_matrix, self.inv_tf_funcs):\r\n input_permuted = inv_tf(input_unfolded[p].reshape(s))\r\n permuted_inputs.append(input_permuted)\r\n\r\n return T.concatenate(permuted_inputs, axis=1) # concatenate along the channel axis\r\n\r\n\r\n\r\nclass CyclicConvRollLayer_c01b(CyclicConvRollLayer):\r\n \"\"\"\r\n This layer turns (n_views * batch_size, num_channels, r, c) into\r\n (n_views * batch_size, n_views * num_channels, r, c) by rolling\r\n and concatenating feature maps.\r\n It also applies the correct inverse transforms to the r and c\r\n dimensions to align the feature maps.\r\n \"\"\"\r\n def __init__(self, input_layer):\r\n super(CyclicConvRollLayer, self).__init__(input_layer)\r\n self.inv_tf_funcs = [array_tf_0_c01b, array_tf_270_c01b, array_tf_180_c01b, array_tf_90_c01b]\r\n\r\n def get_output_shape_for(self, input_shape):\r\n return (4 * input_shape[0],) + input_shape[1:]\r\n\r\n def get_output_for(self, input, *args, **kwargs):\r\n s = input.shape\r\n input_unfolded = input.reshape((s[0], s[1], s[2], 4, s[3] // 4))\r\n\r\n permuted_inputs = []\r\n for p, inv_tf in zip(self.perm_matrix, self.inv_tf_funcs):\r\n input_permuted = inv_tf(input_unfolded[:, :, :, p, :].reshape(s))\r\n permuted_inputs.append(input_permuted)\r\n\r\n return T.concatenate(permuted_inputs, axis=0) # concatenate long the channel axis\r\n\r\n\r\nclass CyclicPoolLayer(nn.layers.Layer):\r\n \"\"\"\r\n Utility layer that unfolds the viewpoints dimension and pools over it.\r\n Note that this only makes sense for dense representations, not for\r\n feature maps (because no inverse transforms are applied to align them).\r\n \"\"\"\r\n def __init__(self, input_layer, pool_function=T.mean):\r\n super(CyclicPoolLayer, self).__init__(input_layer)\r\n self.pool_function = pool_function\r\n\r\n def get_output_shape_for(self, input_shape):\r\n return (input_shape[0] // 4, input_shape[1])\r\n\r\n def get_output_for(self, input, *args, **kwargs):\r\n unfolded_input = input.reshape((4, input.shape[0] // 4, input.shape[1]))\r\n return self.pool_function(unfolded_input, axis=0)\r\n\r\n\r\nclass DihedralPoolLayer(nn.layers.Layer):\r\n \"\"\"\r\n Utility layer that unfolds the viewpoints dimension and pools over it.\r\n Note that this only makes sense for dense representations, not for\r\n feature maps (because no inverse transforms are applied to align them).\r\n \"\"\"\r\n def __init__(self, input_layer, pool_function=T.mean):\r\n super(DihedralPoolLayer, self).__init__(input_layer)\r\n self.pool_function = pool_function\r\n\r\n def get_output_shape_for(self, input_shape):\r\n return (input_shape[0] // 8, input_shape[1])\r\n\r\n def get_output_for(self, input, *args, **kwargs):\r\n unfolded_input = input.reshape((8, input.shape[0] // 8, input.shape[1]))\r\n return self.pool_function(unfolded_input, axis=0)\r\n\r\n\r\nclass NINCyclicPoolLayer(nn.layers.Layer):\r\n \"\"\"\r\n Like CyclicPoolLayer, but broadcasting along all axes beyond the first two.\r\n \"\"\"\r\n def __init__(self, input_layer, pool_function=T.mean):\r\n super(NINCyclicPoolLayer, self).__init__(input_layer)\r\n self.pool_function = pool_function\r\n\r\n def get_output_shape_for(self, input_shape):\r\n return (input_shape[0] // 4,) + input_shape[1:]\r\n\r\n def get_output_for(self, input, *args, **kwargs):\r\n unfolded_input = input.reshape((4, self.input_shape[0] // 4) + self.input_shape[1:])\r\n return self.pool_function(unfolded_input, axis=0)\r\n\r\n\r\nclass FlipSliceLayer(nn.layers.Layer):\r\n \"\"\"\r\n This layer stacks the input images along with their flips along the batch\r\n dimension.\r\n If the input has shape (batch_size, num_channels, r, c),\r\n then the output will have shape (2 * batch_size, num_channels, r, c).\r\n Note that the stacking happens on axis 0, so a reshape to\r\n (2, batch_size, num_channels, r, c) will separate the slice axis.\r\n \"\"\"\r\n def __init__(self, input_layer):\r\n super(FlipSliceLayer, self).__init__(input_layer)\r\n\r\n def get_output_shape_for(self, input_shape):\r\n return (2 * input_shape[0],) + input_shape[1:]\r\n\r\n def get_output_for(self, input, *args, **kwargs):\r\n return T.concatenate([\r\n array_tf_0(input),\r\n array_tf_0f(input),\r\n ], axis=0)",
"#!/usr/bin/env python\r\n\r\nimport argparse, itertools, sys\r\nimport pickle as pickle\r\n\r\nimport numpy as np\r\nfrom util import Prediction, tokenize_words\r\nfrom sklearn.ensemble import RandomForestClassifier\r\n \r\ndef load(fd):\r\n d = np.load(fd)\r\n return d['X']\r\n\r\ndef load_classifier(fd):\r\n results = pickle.load(fd)\r\n return results['rf']\r\n\r\ndef opts():\r\n parser = argparse.ArgumentParser(\r\n description='Find optimal threshold for inserting words')\r\n parser.add_argument('data', type=argparse.FileType('r'),\r\n help='npz file with training data')\r\n parser.add_argument('classifier', type=argparse.FileType('r'),\r\n help='Input pickle file with classifier to re-use')\r\n parser.add_argument('predictions', type=argparse.FileType('r'),\r\n help='Input file with predicted words and locations')\r\n return parser\r\n\r\nif __name__ == \"__main__\":\r\n args = opts().parse_args()\r\n \r\n print(\"Loading test data\", file=sys.stderr)\r\n X = load(args.data)\r\n X = np.asarray(X, dtype=np.float32)\r\n X = np.nan_to_num(X) \r\n \r\n print(\"Loading classifer\", file=sys.stderr)\r\n clf = load_classifier(args.classifier)\r\n \r\n print(\"Predicting decisions\", file=sys.stderr)\r\n d = clf.predict(X)\r\n \r\n print(\"Performing decisions on stdin\", file=sys.stderr)\r\n for di, line, pred in zip(d, sys.stdin, args.predictions):\r\n pred = Prediction.parse(pred)\r\n words = tokenize_words(line)\r\n if di == 0: # do nothing\r\n pass\r\n elif di == 1: # insert space\r\n words.insert(pred.location, ' ')\r\n else: # insert word\r\n words.insert(pred.location, pred.word)\r\n print(' '.join(words))",
"import numpy as np\n\n\nimport theano\nimport theano.tensor as T\nimport theano.sandbox\nimport theano.tensor.shared_randomstreams\nfrom theano.tensor.signal import downsample\nfrom theano.tensor.nnet import conv\n\n##################################\n## Various activation functions ##\n##################################\n#### rectified linear unit\ndef ReLU(x):\n y = T.maximum(0.0, x)\n return(y)\n#### sigmoid\ndef Sigmoid(x):\n y = T.nnet.sigmoid(x)\n return(y)\n#### tanh\ndef Tanh(x):\n y = T.tanh(x)\n return(y)\n#### softmax\ndef SoftMax(x):\n y = T.nnet.softmax(x)\n return(y)\n \n \n############################################\n## Definition of LogisticRegression class ##\n############################################\nclass LogisticRegression(object):\n \"\"\"Logistic Regression Class\n\n The logistic regression is fully described by a weight matrix :math:`W`\n and bias vector :math:`b`. \n \n Instead of classification, we here use LR for the purpose of regression,\n since the targets in this case are continous and in the range [0,1].\n Secondly, they have some kind of probability interpration, especially for \n class 1 and class 6, with the following facts hold\n class 1.1 + class 1.2 + class 1.3 = 1\n class 6.1 + class 6.2 = 1\n \"\"\"\n\n #### initialization\n def __init__(self, input, n_in, n_out,\n W=None, b=None, prob_constraint_on=None):\n \"\"\" Initialize the parameters of the logistic regression\n\n :type input: theano.tensor.TensorType\n :param input: symbolic variable that describes the input of the\n architecture (one minibatch)\n\n :type n_in: int\n :param n_in: number of input units, the dimension of the space in\n which the datapoints lie\n\n :type n_out: int\n :param n_out: number of output units, the dimension of the space in\n which the labels lie\n \n :type prob_constraint_on: boolean\n :param prob_constraint_on: whether we use the probability constraints or not\n\n \"\"\"\n\n # initialize weight matrix W\n if W is None:\n self.W = theano.shared(\n value=np.zeros((n_in, n_out), dtype=theano.config.floatX),\n name='W')\n else:\n self.W = W\n\n # initialize bias b\n if b is None:\n self.b = theano.shared(\n value=np.zeros((n_out,), dtype=theano.config.floatX),\n name='b')\n else:\n self.b = b\n\n # compute prediction\n # the linear output\n lin_output = T.dot(input, self.W) + self.b\n \n if prob_constraint_on == None:\n #### we do not use those probability constraints\n self.y_pred = Sigmoid(lin_output)\n\n elif prob_constraint_on == \"top\":\n #### We first predict the probability of each class using softmax.\n # We then weight those probabilities by multiplying them by the\n # probability of their parent in the Galaxy Zoo Decision Tree.\n \n # class 1\n prob_Class1 = SoftMax(lin_output[:,0:3])\n \n # class 2\n prob_Class2 = SoftMax(lin_output[:,3:5])\n # weight these probabilities using the probability of class 1.2\n prob_Class2 *= T.shape_padright(prob_Class1[:,1])\n \n # class 3\n prob_Class3 = SoftMax(lin_output[:,5:7])\n # weight these probabilities using the probability of class 2.2\n prob_Class3 *= T.shape_padright(prob_Class2[:,1])\n \n # class 4\n prob_Class4 = SoftMax(lin_output[:,7:9])\n # weight these probabilities using the probability of class 2.2\n prob_Class4 *= T.shape_padright(prob_Class2[:,1])\n \n # class 5\n prob_Class5 = SoftMax(lin_output[:,9:13])\n # weight these probabilities using the probability of class 2.2\n prob_Class5 *= T.shape_padright(prob_Class2[:,1])\n \n # class 6\n prob_Class6 = SoftMax(lin_output[:,13:15])\n \n # class 7\n prob_Class7 = SoftMax(lin_output[:,15:18])\n # weight these probabilities using the probability of class 1.1\n prob_Class7 *= T.shape_padright(prob_Class1[:,0])\n \n # class 8\n prob_Class8 = SoftMax(lin_output[:,18:25])\n # weight these probabilities using the probability of class 6.1\n prob_Class8 *= T.shape_padright(prob_Class6[:,0])\n \n # class 9\n prob_Class9 = SoftMax(lin_output[:,25:28])\n # weight these probabilities using the probability of class 2.1\n prob_Class9 *= T.shape_padright(prob_Class2[:,0])\n \n # class 10\n prob_Class10 = SoftMax(lin_output[:,28:31])\n # weight these probabilities using the probability of class 4.1\n prob_Class10 *= T.shape_padright(prob_Class4[:,0])\n \n # class 11\n prob_Class11 = SoftMax(lin_output[:,31:37])\n # weight these probabilities using the probability of class 4.1\n prob_Class11 *= T.shape_padright(prob_Class4[:,0])\n \n # concatenate all the probabilities into a single tensor variable\n self.y_pred = T.concatenate(\n [prob_Class1, prob_Class2, prob_Class3, prob_Class4,\n prob_Class5, prob_Class6, prob_Class7, prob_Class8,\n prob_Class9, prob_Class10, prob_Class11], axis=1)\n elif prob_constraint_on == \"down\":\n #### we use those probability constraints\n \n # the following probabilities should sum up to 1, so we use SoftMax\n # to predict all of them\n ind1 = [2, 8, 15, 16, 17, 25, 26, 27, 31, 32, 33, 34, 35, 36]\n p1 = SoftMax(lin_output[:,ind1])\n prob_Class1_3 = p1[:,0]\n prob_Class4_2 = p1[:,1]\n prob_Class7 = p1[:,2:5]\n prob_Class9 = p1[:,5:8]\n prob_Class11 = p1[:,8:14]\n \n prob_Class4_1 = T.sum(prob_Class11, axis=1)\n prob_Class2_1 = T.sum(prob_Class9, axis=1)\n prob_Class2_2 = prob_Class4_1 + prob_Class4_2\n prob_Class1_1 = T.sum(prob_Class7, axis=1)\n prob_Class1_2 = prob_Class2_1 + prob_Class2_2\n prob_Class1 = T.concatenate(\n [T.shape_padright(prob_Class1_1),\n T.shape_padright(prob_Class1_2),\n T.shape_padright(prob_Class1_3)], axis=1)\n prob_Class2 = T.concatenate(\n [T.shape_padright(prob_Class2_1),\n T.shape_padright(prob_Class2_2)], axis=1)\n prob_Class4 = T.concatenate(\n [T.shape_padright(prob_Class4_1),\n T.shape_padright(prob_Class4_2)], axis=1)\n \n # the following probabilities should sum up to 1, so we use SoftMax\n # to predict all of them\n ind2 = [14, 18, 19, 20, 21, 24, 23, 24] \n p2 = SoftMax(lin_output[:,ind2])\n prob_Class6_2 = p2[:,0]\n prob_Class8 = p2[:,1:8]\n prob_Class6_1 = T.sum(prob_Class8, axis=1)\n prob_Class6 = T.concatenate(\n [T.shape_padright(prob_Class6_1),\n T.shape_padright(prob_Class6_2)], axis=1)\n \n # for the following probabilities, we resort to the same strategy in\n # the \"top\" option\n # class 3\n prob_Class3 = SoftMax(lin_output[:,5:7])\n # weight these probabilities using the probability of class 2.2\n prob_Class3 *= T.shape_padright(prob_Class2[:,1])\n \n # class 5\n prob_Class5 = SoftMax(lin_output[:,9:13])\n # weight these probabilities using the probability of class 2.2\n prob_Class5 *= T.shape_padright(prob_Class2[:,1])\n \n # class 10\n prob_Class10 = SoftMax(lin_output[:,28:31])\n # weight these probabilities using the probability of class 4.1\n prob_Class10 *= T.shape_padright(prob_Class4[:,0])\n \n # concatenate all the probabilities into a single tensor variable\n self.y_pred = T.concatenate(\n [prob_Class1, prob_Class2, prob_Class3, prob_Class4,\n prob_Class5, prob_Class6, prob_Class7, prob_Class8,\n prob_Class9, prob_Class10, prob_Class11], axis=1)\n \n \n # parameters of the model\n self.params = [self.W, self.b]\n\n #### the loss function in this case is (R)MSE\n def MSE(self, y):\n return T.mean((self.y_pred - y)**2)\n \n #### the cross-entropy\n def CrossEntropy(self, y):\n return -T.mean(y*T.log(self.y_pred))\n \n #### KL divergence\n def KL(self, y):\n return T.mean(y*T.log(y/self.y_pred) + (1-y)*T.log((1-y)/(1-self.y_pred)))\n \n\n\n#####################################\n## Definition of HiddenLayer class ##\n#####################################\nclass HiddenLayer(object):\n def __init__(self, rng, input, n_in, n_out,\n activation=Tanh, use_bias=True,\n W=None, b=None):\n \"\"\"\n Typical hidden layer of a MLP: units are fully-connected and have\n sigmoidal activation function. Weight matrix W is of shape (n_in,n_out)\n and the bias vector b is of shape (n_out,).\n\n NOTE : The nonlinearity used here is tanh\n\n Hidden unit activation is given by: tanh(dot(input,W) + b)\n\n :type rng: np.random.RandomState\n :param rng: a random number generator used to initialize weights\n\n :type input: theano.tensor.dmatrix\n :param input: a symbolic tensor of shape (n_examples, n_in)\n\n :type n_in: int\n :param n_in: dimensionality of input\n\n :type n_out: int\n :param n_out: number of hidden units\n\n :type activation: theano.Op or function\n :param activation: Non linearity to be applied in the hidden\n layer\n \"\"\"\n self.input = input\n self.activation = activation\n\n if W is None:\n W_values = np.asarray(0.01 * rng.standard_normal(\n size=(n_in, n_out)), dtype=theano.config.floatX)\n self.W = theano.shared(value=W_values, name='W', borrow=True)\n else:\n self.W = W\n \n if b is None:\n if activation == ReLU:\n # for ReLU, we initialize bias as constant 1 as suggested in\n # the dropout and ImageNet paper\n b_values = np.ones((n_out,), dtype=theano.config.floatX)\n else:\n b_values = np.zeros((n_out,), dtype=theano.config.floatX)\n self.b = theano.shared(value=b_values, name='b', borrow=True)\n else:\n self.b = b\n\n if use_bias:\n lin_output = T.dot(input, self.W) + self.b\n else:\n lin_output = T.dot(input, self.W)\n\n self.output = (lin_output if activation is None else activation(lin_output))\n \n # parameters of the model\n if use_bias:\n self.params = [self.W, self.b]\n else:\n self.params = [self.W]\n\n\n###############################################\n## Helper function to compute dropout output ##\n###############################################\n#### Credit to Misha Denil\ndef _dropout_from_layer(rng, layer, p):\n \"\"\"p is the probablity of dropping a unit\n \"\"\"\n srng = theano.tensor.shared_randomstreams.RandomStreams(\n rng.randint(999999))\n \n # p=1-p because 1's indicate keep and p is prob of dropping\n mask = srng.binomial(n=1, p=1-p, size=layer.shape)\n # The cast is important because\n # int * float32 = float64 which pulls things off the gpu\n output = layer * T.cast(mask, theano.config.floatX)\n return output\n\n\n############################################\n## Definition of DropoutHiddenLayer class ##\n############################################\n#### Credit to Misha Denil\nclass DropoutHiddenLayer(HiddenLayer):\n def __init__(self, rng, input, n_in, n_out,\n activation, use_bias, dropout_rate, W=None, b=None):\n super(DropoutHiddenLayer, self).__init__(\n rng=rng, input=input, n_in=n_in, n_out=n_out, W=W, b=b,\n activation=activation, use_bias=use_bias)\n self.output = _dropout_from_layer(rng, self.output, p=dropout_rate)\n\n\n#############################\n## Definition of MLP class ##\n#############################\n#### Credit to Misha Denil\nclass MLP(object):\n \"\"\"A multilayer perceptron with all the trappings required to do dropout\n training.\n\n \"\"\"\n def __init__(self, rng, input, layer_sizes, dropout_rates,\n activations=None, use_bias=True, prob_constraint_on=True):\n \"\"\"For training without dropout, you should set dropout_rates to all\n zeros. Otherwise, with non-zero dropout_rate, dropout is included in\n the training, with dropout probability for each hidden layer in the MLP\n specified by dropout_rate.\n \"\"\"\n # Set up all the hidden layers\n weight_matrix_sizes = zip(layer_sizes, layer_sizes[1:])\n # we build two parallel layers\n # - training_layers for training with/without dropout\n # - testing_layers for testing the performance\n self.training_layers = []\n self.testing_layers = []\n \n # dropout the input\n next_training_layer_input = _dropout_from_layer(rng, input, p=dropout_rates[0])\n next_testing_layer_input = input\n \n layer_counter = 0\n for n_in, n_out in weight_matrix_sizes[:-1]:\n \n # setup the training layer\n next_training_layer = DropoutHiddenLayer(rng=rng,\n input=next_training_layer_input,\n n_in=n_in, n_out=n_out,\n activation=activations[layer_counter],\n use_bias=use_bias,\n dropout_rate=dropout_rates[layer_counter])\n self.training_layers.append(next_training_layer)\n next_training_layer_input = next_training_layer.output\n\n # setup the testing layer\n # Reuse the paramters from the dropout layer here, in a different\n # path through the graph.\n next_testing_layer = HiddenLayer(rng=rng,\n input=next_testing_layer_input,\n n_in=n_in, n_out=n_out,\n activation=activations[layer_counter],\n use_bias=use_bias,\n # for testing, we SHOULD scale the weight matrix W with (1-p)\n W=next_training_layer.W * (1 - dropout_rates[layer_counter]),\n b=next_training_layer.b)\n self.testing_layers.append(next_testing_layer)\n next_testing_layer_input = next_testing_layer.output\n \n layer_counter += 1\n \n # Set up the output layer for training layers\n n_in, n_out = weight_matrix_sizes[-1]\n training_output_layer = LogisticRegression(\n input=next_training_layer_input,\n n_in=n_in, n_out=n_out,\n prob_constraint_on=prob_constraint_on)\n self.training_layers.append(training_output_layer)\n\n # Set up the output layer for testing layers\n # Again, reuse paramters in the dropout output.\n testing_output_layer = LogisticRegression(\n input=next_testing_layer_input,\n n_in=n_in, n_out=n_out,\n # for testing, we SHOULD scale the weight matrix W with (1-p)\n W=training_output_layer.W * (1 - dropout_rates[-1]),\n b=training_output_layer.b,\n prob_constraint_on=prob_constraint_on)\n self.testing_layers.append(testing_output_layer)\n\n # Use the MSE of the logistic regression layer as the objective\n # In training phase, we use the MSE of the logistic regression layer\n # which is on top of the dropout_layers\n self.training_MSE = self.training_layers[-1].MSE\n # In validation/testing phase, we use the MSE of the logistic regression layer\n # which is on top of the normal_layers\n self.testing_MSE = self.testing_layers[-1].MSE\n \n # NOTE: for prediction, we use all the weights, thus we should use\n # the normal layers instead of the dropout layers\n self.y_pred = self.testing_layers[-1].y_pred\n \n # Grab all the parameters together.\n self.params = [ param for layer in self.training_layers for param in layer.params ]\n # The above is Double Iteration in List Comprehension\n # See the discussion in\n # http://stackoverflow.com/questions/17657720/python-list-comprehension-double-for\n # In regular for-loop format, we have\n # for layer in self.dropout_layers:\n # for param in layer.params:\n # put param in the resulting list\n \n \n#######################################\n## Definition of ConvPoolLayer class ##\n#######################################\nclass ConvPoolLayer(object):\n \"\"\" A convolutional followed by pooling layer \"\"\"\n\n def __init__(self, rng, input, filter_shape, image_shape,\n pooltype=\"max\", poolsize=(2, 2), activation=Tanh):\n\n\n assert image_shape[1] == filter_shape[1]\n self.input = input\n\n W_values = np.asarray(0.01 * rng.standard_normal(\n size=filter_shape), dtype=theano.config.floatX)\n self.W = theano.shared(value=W_values, name='W', borrow=True)\n\n # the bias is a 1D tensor -- one bias per output feature map\n if activation == ReLU:\n # for ReLU, we initialize bias as constant 1 as suggested in\n # the dropout and ImageNet paper\n b_values = np.ones((filter_shape[0],), dtype=theano.config.floatX)\n else:\n b_values = np.zeros((filter_shape[0],), dtype=theano.config.floatX)\n self.b = theano.shared(value=b_values, name='b', borrow=True)\n\n # convolve input feature maps with filters\n conv_out = conv.conv2d(input=input, filters=self.W,\n filter_shape=filter_shape, image_shape=image_shape)\n if pooltype == \"max\":\n # downsample each feature map individually, using maxpooling\n pooled_out = downsample.max_pool_2d(input=conv_out,\n ds=poolsize,\n ignore_border=True)\n elif pooltype == \"mean\":\n # For mean/average pooling, see\n # https://groups.google.com/forum/#!msg/theano-users/MiyDStm1W0c/L1dcRAz1Y9kJ\n # and for images2neibs, see\n # http://deeplearning.net/software/theano/library/sandbox/neighbours.html\n \n # no module theano.sandbox.neighbours found? will look into this in the future\n pooled_out = theano.sandbox.neighbours.images2neibs(ten4=conv_out,\n neib_shape=poolsize,\n ignore_border=True)\n pooled_out = pooled_out.mean(axis=-1)\n elif pooltype == \"none\":\n pooled_out = conv_out\n\n # add the bias term. Since the bias is a vector (1D array), we first\n # reshape it to a tensor of shape (1,n_filters,1,1). Each bias will\n # thus be broadcasted across mini-batches and feature map\n # width & height\n self.output = activation(pooled_out + self.b.dimshuffle('x', 0, 'x', 'x'))\n\n # store parameters of this layer\n self.params = [self.W, self.b]\n\n\n#############################\n## Definition of CNN class ##\n#############################\nclass CNN(object):\n \"\"\"A CNN architecture\n\n \"\"\"\n def __init__(self, rng, input, batch_size, channel, image_size, kernels, poolings, activations=None):\n \n self.layers = []\n #next_CNN_n_in = channel\n next_CNN_layer_input = input\n #batch_size = input.shape[0]\n next_CNN_input_size = channel\n #image_size = input.shape[2]\n for i in xrange(len(kernels)):\n image_shape = (batch_size, next_CNN_input_size, image_size, image_size)\n filter_shape = (kernels[i][\"num\"], next_CNN_input_size,\n kernels[i][\"size\"], kernels[i][\"size\"])\n poolsize = (poolings[i][\"size\"], poolings[i][\"size\"])\n next_CNN_layer = ConvPoolLayer(rng,\n input=next_CNN_layer_input,\n image_shape=image_shape,\n filter_shape=filter_shape,\n pooltype=poolings[i][\"type\"],\n poolsize=poolsize,\n activation=activations[i])\n self.layers.append(next_CNN_layer)\n \n next_CNN_layer_input = next_CNN_layer.output\n image_size = (image_size - kernels[i][\"size\"] + 1)/poolings[i][\"size\"]\n assert image_size % 1 == 0\n next_CNN_input_size = kernels[i][\"num\"]\n \n self.output = self.layers[-1].output\n self.params = [ param for layer in self.layers for param in layer.params ]\n # The above is Double Iteration in List Comprehension as used in MLP class",
"from SupervisedLearning import SKSupervisedLearning\r\nfrom train_files import TrainFiles\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn.svm import SVC\r\nfrom sklearn.metrics import log_loss, confusion_matrix\r\nfrom sklearn.calibration import CalibratedClassifierCV\r\nfrom tr_utils import vote\r\nimport matplotlib.pylab as plt\r\nfrom train_nn import createDataSets, train\r\n\r\ntrain_path_mix = \"/kaggle/malware/mix_lbp.csv\"\r\nlabels_file = \"/kaggle/malware/trainLabels.csv\"\r\n\r\nX, Y_train, Xt, Y_test = TrainFiles.from_csv(train_path_mix)\r\n\r\ndef plot_confusion(sl):\r\n conf_mat = confusion_matrix(sl.Y_test, sl.clf.predict(sl.X_test_scaled)).astype(dtype='float')\r\n norm_conf_mat = conf_mat / conf_mat.sum(axis = 1)[:, None]\r\n\r\n fig = plt.figure()\r\n plt.clf()\r\n ax = fig.add_subplot(111)\r\n ax.set_aspect(1)\r\n res = ax.imshow(norm_conf_mat, cmap=plt.cm.jet, \r\n interpolation='nearest')\r\n cb = fig.colorbar(res)\r\n labs = np.unique(Y_test)\r\n x = labs - 1\r\n\r\n plt.xticks(x, labs)\r\n plt.yticks(x, labs)\r\n\r\n for i in x:\r\n for j in x:\r\n ax.text(i - 0.2, j + 0.2, \"{:3.0f}\".format(norm_conf_mat[j, i] * 100.))\r\n return conf_mat\r\n\r\nsl = SKSupervisedLearning(SVC, X, Y_train, Xt, Y_test)\r\nsl.fit_standard_scaler()\r\nsl.train_params = {'C': 100, 'gamma': 0.01, 'probability' : True}\r\nll_trn, ll_tst = sl.fit_and_validate()\r\n\r\nprint(\"SVC log loss: \", ll_tst)\r\n\r\nconf_svm = plot_confusion(sl)\r\n\r\n#Neural net\r\ntrndata, tstdata = createDataSets(sl.X_train_scaled, Y_train, sl.X_test_scaled, Y_test)\r\nfnn = train(trndata, tstdata, epochs = 1000, test_error = 0.025, momentum = 0.15, weight_decay = 0.0001)\r\n\r\nsl_ccrf = SKSupervisedLearning(CalibratedClassifierCV, X, Y_train, Xt, Y_test)\r\nsl_ccrf.train_params = \\\r\n {'base_estimator': RandomForestClassifier(**{'n_estimators' : 7500, 'max_depth' : 200}), 'cv': 10}\r\nsl_ccrf.fit_standard_scaler()\r\nll_ccrf_trn, ll_ccrf_tst = sl_ccrf.fit_and_validate()\r\n\r\nprint(\"Calibrated log loss: \", ll_ccrf_tst)\r\nconf_ccrf = plot_confusion(sl_ccrf)\r\n\r\n#predicted = cross_val_predict(SVC(**sl.train_params), sl.X_train_scaled, n_jobs = -1, y = Y_train, cv=10)\r\n\r\n#fig,ax = plt.subplots()\r\n#ax.scatter(Y_train, predicted)\r\n#ax.plot([y.min(), y.max()], [y.min(), y.max()], 'k--', lw=4)\r\n#ax.set_xlabel('Measured')\r\n#ax.set_ylabel('Predicted')\r\n#ax.xticks(np.unique(Y_test))\r\n#ax.yticks(np.unique(Y_test))\r\n\r\n#fig.show()\r\n\r\nx = 1. / np.arange(1., 6)\r\ny = 1 - x\r\n\r\nxx, yy = np.meshgrid(x, y)\r\nlls1 = np.zeros(xx.shape[0] * yy.shape[0]).reshape(xx.shape[0], yy.shape[0])\r\nlls2 = np.zeros(xx.shape[0] * yy.shape[0]).reshape(xx.shape[0], yy.shape[0])\r\n\r\nfor i, x_ in enumerate(x):\r\n for j, y_ in enumerate(y):\r\n proba = vote([sl.proba_test, sl_ccrf.proba_test], [x_, y_])\r\n lls1[i, j] = log_loss(Y_test, proba)\r\n\r\n proba = vote([sl.proba_test, sl_ccrf.proba_test], [y_, x_])\r\n lls2[i, j] = log_loss(Y_test, proba)\r\n\r\nfig = plt.figure()\r\nplt.clf()\r\nax = fig.add_subplot(121)\r\nax1 = fig.add_subplot(122)\r\n\r\nax.set_aspect(1)\r\nax1.set_aspect(1)\r\n\r\nres = ax.imshow(np.array(lls1), cmap=plt.cm.jet, \r\n interpolation='nearest')\r\nres = ax1.imshow(np.array(lls2), cmap=plt.cm.jet, \r\n interpolation='nearest')\r\n\r\ncb = fig.colorbar(res)\r\n\r\n",
"from caffe.io import load_image\r\nimport os\r\nimport sys\r\nimport numpy as np\r\nimport multiprocessing as mp\r\nimport scipy\r\nimport time\r\nfrom distance.distance import cdist as native_cdist\r\nfrom .lmdbWriter import open_csv\r\nfrom skimage.util import view_as_windows\r\n\r\ndef main(argv):\r\n import argparse\r\n parser = argparse.ArgumentParser(description='Extracts features from every image')\r\n parser.add_argument('-path', help='Path to directory where lmdb database is stored')\r\n parser.add_argument('-size', help='Patch size')\r\n parser.add_argument('-stride', help='Stride')\r\n args = parser.parse_args()\r\n return args\r\n\r\n\r\ndef im2col(Im, block, stride, style='sliding'):\r\n \"\"\"block = (patchsize, patchsize)\r\n first do sliding\r\n \"\"\"\r\n bx, by = block\r\n Imx, Imy = Im.shape\r\n Imcol = []\r\n for j in range(0, Imy, stride):\r\n for i in range(0, Imx, stride):\r\n if (i+bx <= Imx) and (j+by <= Imy):\r\n Imcol.append(Im[i:i+bx, j:j+by].T.reshape(bx*by))\r\n else:\r\n break\r\n return np.asarray(Imcol).T\r\n\r\n\r\ndef stack(labelDataPair, i, numEntries):\r\n\r\n flattened = np.transpose(labelDataPair[1]).flatten()\r\n if i % 5000 == 0:\r\n print(\"{0}/{1} images flattened\".format(i, numEntries))\r\n\r\n return flattened\r\n\r\n\r\ndef extract_features(path, keys, centroids, rfSize, ImageDim, whitening, M, P, stride):\r\n #assert(nargin == 4 || nargin == 6)\r\n numCentroids = centroids.shape[0]\r\n numSamples = len(keys)\r\n numFeats = ImageDim[0]*ImageDim[1]*ImageDim[2]\r\n # compute features for all training images\r\n XC = np.zeros((numSamples, numCentroids*4))\r\n labels = np.zeros((numSamples, 1))\r\n j = 0\r\n for i in range(numSamples):\r\n\r\n total_start = time.time()\r\n print(\"Sample {0}\".format(i))\r\n if (np.mod(i,2000) == 0):\r\n np.save('test_features_windowsize_{0}_iteration_{1}'.format(rfSize,i), XC)\r\n print('Extracting features: ' + str(i) + '/' + str(numSamples))\r\n \r\n img = load_image(path + keys[i])\r\n# X = np.transpose(reader.next()[1]).flatten()\r\n X = img.flatten()\r\n\r\n # extract overlapping sub-patches into rows of 'patches'\r\n start = time.time()\r\n patches = np.vstack(\r\n (im2col(np.reshape(X[0:numFeats/3],ImageDim[0:2],'F'), (rfSize, rfSize), stride),\r\n im2col(np.reshape(X[numFeats/3:numFeats*2/3],ImageDim[0:2],'F'), (rfSize, rfSize), stride), im2col(np.reshape(X[numFeats*2/3:numFeats],ImageDim[0:2],'F'), (rfSize, rfSize), stride))).T\r\n end = time.time()\r\n \r\n w = view_as_windows(img, (rfSize,rfsize, 3), stride)\r\n w = w.reshape((w.shape[0]*w.shape[1],w.shape[3]*w.shape[4]*w.shape[5]))\r\n print(np.array_equal(patches, w))\r\n from time import sleep\r\n for i in range(w.shape[0]):\r\n print(w[i,0:20])\r\n print(patches[i,500:520])\r\n sleep(1)\r\n\r\n print(\"Extract overlapping sub-patches time:{0}\".format(end - start))\r\n\r\n # do preprocessing for each patch\r\n\r\n \r\n # normalize for contrast\r\n start = time.time()\r\n patchesMean = np.mean(patches, axis=1, dtype=np.float32, keepdims=True)\r\n patchesVar = np.var(patches, axis=1, dtype=np.float32, ddof=1, keepdims=True)\r\n offsetMatrix = 10.0 * np.ones(patchesVar.shape) \r\n patches = (patches - patchesMean) / np.sqrt(patchesVar + offsetMatrix)\r\n end = time.time()\r\n print(\"Preprocessing time:{0}\".format(end - start))\r\n # whiten\r\n if (whitening):\r\n patches = np.dot((patches - M), P)\r\n # compute 'triangle' activation function\r\n start = time.time()\r\n z = native_cdist(patches, centroids)\r\n end = time.time()\r\n print(\"Triangle time:{0}\".format(end - start))\r\n\r\n start = time.time()\r\n mu = np.tile(np.array([np.mean(z, axis = 1)]).T, (1, centroids.shape[0])) # average distance to centroids for each patch\r\n patches = np.maximum(mu - z, np.zeros(mu.shape))\r\n end = time.time()\r\n print(\"Distance calculation time:{0}\".format(end - start))\r\n # patches is now the data matrix of activations for each patch\r\n\r\n # reshape to numCentroids-channel image\r\n start = time.time()\r\n prows = (ImageDim[0]-rfSize + 1*stride)/stride\r\n pcols = (ImageDim[1]-rfSize + 1*stride)/stride\r\n patches = np.reshape(patches, (prows, pcols, numCentroids),'F')\r\n end = time.time()\r\n print(\"Reshaping time:{0}\".format(end - start))\r\n start = time.time()\r\n # pool over quadrants\r\n halfr = np.round(float(prows)/2)\r\n halfc = np.round(float(pcols)/2)\r\n q1 = np.array([np.sum(np.sum(patches[0:halfc, 0:halfr, :], axis = 1),axis = 0)])\r\n q2 = np.array([np.sum(np.sum(patches[halfc:patches.shape[0], 0:halfr, :], axis = 1),axis = 0)])\r\n q3 = np.array([np.sum(np.sum(patches[0:halfc, halfr:patches.shape[1], :], axis = 1),axis = 0)])\r\n q4 = np.array([np.sum(np.sum(patches[halfc:patches.shape[0], halfr:patches.shape[1], :], axis = 1),axis = 0)])\r\n end = time.time()\r\n print(\"Pooling time:{0}\".format(end - start))\r\n\r\n # concatenate into feature vector\r\n XC[j,:] = np.vstack((q1,q2,q3,q4)).flatten()\r\n j += 1\r\n total_end = time.time()\r\n print(\"Iteration time:{0}\".format(total_end - total_start))\r\n\r\n return XC\r\n\r\n\r\nif __name__ == '__main__':\r\n \r\n arguments = main(sys.argv[1:])\r\n path = arguments.path\r\n rfsize = int(arguments.size)\r\n if arguments.stride:\r\n stride =int( arguments.stride)\r\n else:\r\n stride = 1\r\n\r\n #reader = LmdbReader(path)\r\n #numEntries = reader.info()['entries']\r\n ImageDim = (512,512,3)\r\n centroids = np.load('npy_data/train_centroids_windowsize_{0}.npy'.format(rfsize))\r\n M = np.load('npy_data/train_mean_windowsize_{0}.npy'.format(rfsize))\r\n P = np.load('npy_data/train_eigenvectors_windowsize_{0}.npy'.format(rfsize))\r\n \r\n\r\n# trainX = np.zeros((numEntries,ImageDim[0]*ImageDim[1]*ImageDim[2]))\r\n# trainY = np.zeros((numEntries,))\r\n# i = 0\r\n\r\n# while(1):\r\n\r\n# labelDataPair = reader.next()\r\n# if labelDataPair is False:\r\n# break\r\n# else:\r\n# trainY[i,] = labelDataPair[0]\r\n# trainX[i,:] = np.transpose(labelDataPair[1]).flatten()\r\n# i += 1\r\n# if i % 100 == 0:\r\n# print i\r\n import json \r\n keys = os.listdir(path)\r\n with open('keys.txt', 'w') as f:\r\n json.dump(keys, f)\r\n features = extract_features(path, keys, centroids, rfsize, ImageDim, True, M, P, stride)\r\n np.save('train_features_windowsize_{0}'.format(rfsize), features)\r\n \r\n# print trainY\r\n \r\n# reader = LmdbReader(path)\r\n# print trainX.shape, trainY.shape\r\n \r\n# pool = mp.Pool()\r\n# results = [pool.apply(stack, args=(reader.next(), i, numEntries - 1)) for i in range(0, numEntries)]\r\n# print \"Finished\"\r\n \r\n",
"import numpy as np\r\nfrom math import sqrt\r\n\r\n\r\n#********************\r\n#**** this function finds a point which is greater than the min distance\r\n#********************\r\ndef find_closest_point_at_minimum_distance(path_array,starting_location,distance_required,pos_or_neg):\r\n\r\n x1 = path_array[starting_location,0]\r\n y1 = path_array[starting_location,1]\r\n\r\n if (pos_or_neg > 0):\r\n for loc1 in range(starting_location, len(path_array) ):\r\n min_loc = loc1\r\n x2 = path_array[loc1,0]\r\n y2 = path_array[loc1,1]\r\n \r\n distance1 = get_distance(x1,y1,x2,y2)\r\n if (distance1 > distance_required): # see if the distance is close enough\r\n break\r\n\r\n else:\r\n for loc1 in range(starting_location, 0, -1 ):\r\n min_loc = loc1\r\n x2 = path_array[loc1,0]\r\n y2 = path_array[loc1,1]\r\n \r\n distance1 = get_distance(x1,y1,x2,y2)\r\n if (distance1 > distance_required): # see if the distance is close enough\r\n break\r\n\r\n return min_loc\r\n#********************\r\n#**** this function finds a point which is greater than the min distance\r\n#********************\r\n\r\n\r\n#********************\r\n#**** this function finds a point which is greater than the min distance\r\n#********************\r\ndef get_distance( x1, y1, x2, y2):\r\n distance1 = ((x1 - x2)**2 + (y1 - y2)**2 ) ** (.5)\r\n return distance1\r\n\r\n\r\ndef unit_vector(vector):\r\n \"\"\" Returns the unit vector of the vector. \"\"\"\r\n #return vector / np.linalg.norm(vector)\r\n return vector / ( vector[0]**2 + vector[1]**2) ** (.5) \r\n\r\n#@profile\r\ndef angle_between(v1, v2):\r\n \"\"\" Returns the angle in radians between vectors 'v1' and 'v2'::\r\n\r\n >>> angle_between((1, 0, 0), (0, 1, 0))\r\n 1.5707963267948966\r\n >>> angle_between((1, 0, 0), (1, 0, 0))\r\n 0.0\r\n >>> angle_between((1, 0, 0), (-1, 0, 0))\r\n 3.141592653589793\r\n \"\"\"\r\n v1_u = unit_vector(v1)\r\n v2_u = unit_vector(v2)\r\n angle = np.arccos(np.dot(v1_u, v2_u))\r\n if np.isnan(angle):\r\n if (v1_u == v2_u).all():\r\n return 0.0\r\n else:\r\n return np.pi\r\n return angle\r\n\r\n\r\n\r\n#**************\r\n#*** Get the angle between 3 points\r\n#***************\r\ndef get_angle_between_3_points(x1,y1,x2,y2,x3,y3):\r\n\r\n # get the vector\r\n v1 = [ x2-x1, y2-y1]\r\n v2 = [ x2-x3, y2-y3] \r\n angle1 = angle_between(v1, v2) * 57.2957795130823 # the angle of the angle in degrees\r\n\r\n distance1 = get_distance( x1, y1, x2, y2)\r\n distance2 = get_distance( x2, y2, x3, y3)\r\n\r\n return angle1, distance1, distance2\r\n \r\n\r\n\r\n\r\n\r\n\r\n#********************\r\n#**** this function rotates the N x 2 path by a 2x2 rotation matrix\r\n#********************\r\ndef rotate_path( matrix1, angle_to_rotate):\r\n\r\n rotation_matrix = [ [ np.cos(angle_to_rotate), -1 * np.sin(angle_to_rotate) ], \r\n [ np.sin(angle_to_rotate), np.cos(angle_to_rotate) ] ]\r\n \r\n matrix1 = np.dot( matrix1, rotation_matrix)\r\n return matrix1 \r\n#********************\r\n#**** end function rotates the N x 2 path by a 2x2 rotation matrix\r\n#********************\r\n\r\n\r\n\r\n\r\n#********************\r\n#**** this function flips the y coordinates\r\n#********************\r\ndef flip_y_coords(matrix1):\r\n flip_y = [1, -1]\r\n matrix1 = np.multiply( matrix1, flip_y)\r\n return matrix1\r\n#********************\r\n#**** end function flips the y coordinates\r\n#********************\r\n\r\n#********************\r\n#**** this function flips the x coordinates\r\n#********************\r\ndef flip_x_coords(matrix1):\r\n flip_x = [-1, 1]\r\n matrix1 = np.multiply( matrix1, flip_x)\r\n return matrix1\r\n#********************\r\n#**** end function flips the y coordinates\r\n#********************\r\n\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \r\n \r\n \r\n#**************\r\n#*** RDP Calculation for simplifying a series of points\r\n#***************\r\n\"\"\"\r\nThe Ramer-Douglas-Peucker algorithm roughly ported from the pseudo-code provided\r\nby http://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm\r\n\"\"\"\r\ndef distance(a, b):\r\n return sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2)\r\n\r\ndef point_line_distance(point, start, end):\r\n if (start == end):\r\n return distance(point, start)\r\n else:\r\n n = abs(\r\n (end[0] - start[0]) * (start[1] - point[1]) - (start[0] - point[0]) * (end[1] - start[1])\r\n )\r\n d = sqrt(\r\n (end[0] - start[0]) ** 2 + (end[1] - start[1]) ** 2\r\n )\r\n return n / d\r\n\r\ndef rdp(points, epsilon):\r\n \"\"\"\r\n Reduces a series of points to a simplified version that loses detail, but\r\n maintains the general shape of the series.\r\n \"\"\"\r\n dmax = 0.0\r\n index = 0\r\n for i in range(1, len(points) - 1):\r\n d = point_line_distance(points[i], points[0], points[-1])\r\n if d > dmax:\r\n index = i\r\n dmax = d\r\n if dmax >= epsilon:\r\n results = rdp(points[:index+1], epsilon)[:-1] + rdp(points[index:], epsilon)\r\n else:\r\n results = [points[0], points[-1]]\r\n return results\r\n\r\n\r\n\r\ndef rdp_recursion(points, epsilon,route):\r\n # as long as there are more than 4 RDP points, step inward 1 point at a time and call it recursively to \r\n # try to get the RDP points to line up closer\r\n \r\n results = rdp(points, epsilon)\r\n results_array = np.array(results)\r\n RDP_index = match_RDP_to_route( results_array, route)\r\n \r\n\r\n results_hold = []\r\n point_segment = points\r\n route_segment = route\r\n cnt = 0\r\n \r\n while(len(results) >= 4): # while we have at least 4 RDP points in this segment then iterate\r\n results_hold.insert(cnt, results[0]) # save the first and last RDP points\r\n results_hold.insert(cnt+1, results[-1])\r\n cnt+=1\r\n \r\n # generate a route segment starting at the second RDP point and ending at the second to last one\r\n point_segment = point_segment[ RDP_index[1]: RDP_index[-2]+1] \r\n route_segment = route_segment[ RDP_index[1]: RDP_index[-2]+1, :]\r\n \r\n results = rdp(point_segment, epsilon)\r\n results_array = np.array(results)\r\n RDP_index = match_RDP_to_route( results_array, route_segment) \r\n \r\n \r\n if (len(results) == 2):\r\n results_hold.insert(cnt, results[0]) # save the first and last RDP points\r\n results_hold.insert(cnt+1, results[-1])\r\n cnt+=1\r\n elif (len(results) ==3): # save all the RDP Points \r\n results_hold.insert(cnt, results[0]) # save the first and last RDP points\r\n results_hold.insert(cnt+1, results[1]) # save the first and last RDP points\r\n results_hold.insert(cnt+2, results[-1])\r\n cnt+=1\r\n\r\n return results_hold\r\n\r\n\r\n\r\n\r\n\r\ndef match_RDP_to_route(RDP_points, route):\r\n\r\n match_loc = []\r\n cnt = 0\r\n for point_cnt in range(0, len(RDP_points) ):\r\n\r\n #print (RDP_points[point_cnt,0], RDP_points[point_cnt,1] )\r\n\r\n match_found = 0\r\n while( match_found ==0):\r\n if( RDP_points[point_cnt,0] == route[cnt,0] and RDP_points[point_cnt,1] == route[cnt,1] ): # see if the simp\r\n match_loc.append(cnt)\r\n match_found = 1\r\n cnt=cnt+1\r\n\r\n return match_loc\r\n\r\n\r\n\r\n\r\n#**************\r\n#***End RDP Calculation for simplifying a series of points\r\n#*************** ",
"from scipy.fftpack import fft, fftshift\r\n\r\nimport numpy as np\r\nimport math\r\nfrom seizures.features.FeatureExtractBase import FeatureExtractBase\r\n\r\n\r\ndef nextpow2(i):\r\n #n = 1\r\n #while n < i: n *= 2\r\n #return n\r\n return int(2**math.ceil(math.log(i)/math.log(2)))\r\n\r\nclass FFTFeatures(FeatureExtractBase):\r\n \"\"\"\r\n Class to extracts spectral powers based on FFT features.\r\n @author Julian\r\n \"\"\"\r\n\r\n def __init__(self, band_means, band_width):\r\n self.band_means = band_means\r\n self.band_width = band_width\r\n\r\n def extract(self, instance):\r\n data = instance.eeg_data\r\n L = data.shape[1]\r\n\r\n nfft = nextpow2(L)\r\n Y = fft(data, nfft)\r\n psd = 2 * abs(Y[:,:(Y.shape[1] / 2)]) ** 2\r\n f = instance.sample_rate / 2 * np.linspace(0, 1, nfft / 2)\r\n\r\n feats = np.zeros((instance.number_of_channels, len(self.band_means)))\r\n for i in range(len(self.band_means)):\r\n inds = abs(self.band_means[i] - f) < self.band_width\r\n feats[:, i] += np.sum(psd[:,inds], 1)\r\n\r\n return feats.reshape((feats.shape[0]*feats.shape[1],))\r\n\r\n def extract_julian_old(self, instance):\r\n subsampled_instance = instance.subsample_data(self.sampling_rate)\r\n features = np.empty((subsampled_instance.number_of_channels, self.bins))\r\n\r\n for channel_index in range(0, subsampled_instance.number_of_channels):\r\n frequencies = abs(fftshift(fft(subsampled_instance.eeg_data[channel_index, :])))\r\n frequencies_to_sum = len(frequencies) / (self.bins * 2)\r\n\r\n for i in range(1, self.bins):\r\n features[channel_index, i] = np.mean(np.square(frequencies[(i - 1) * frequencies_to_sum:i * frequencies_to_sum]))\r\n\r\n return features.reshape((features.shape[0] * features.shape[1], 1))\r\n",
"import numpy as np\r\nimport pandas as pd\r\nfrom sklearn.preprocessing import LabelEncoder\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn import feature_extraction\r\nfrom sklearn.cross_validation import StratifiedKFold\r\nfrom lasagne.layers import DenseLayer\r\nfrom lasagne.layers import InputLayer\r\nfrom lasagne.layers import DropoutLayer\r\nfrom lasagne.nonlinearities import softmax, sigmoid, tanh, linear\r\nfrom lasagne.updates import momentum, nesterov_momentum, sgd, rmsprop\r\nfrom nolearn.lasagne import NeuralNet\r\nfrom joblib import Parallel, delayed\r\n#from multiprocessing import Pool\r\nimport sys\r\nimport getopt\r\nimport theano\r\nimport random\r\nimport os\r\nfrom sklearn.metrics import log_loss\r\n\r\ndef float32(k):\r\n return np.cast['float32'](k)\r\n\r\nclass AdjustVariable(object):\r\n def __init__(self, name, start=0.03, stop=0.001):\r\n self.name = name\r\n self.start, self.stop = start, stop\r\n self.ls = None\r\n\r\n def __call__(self, nn, train_history):\r\n if self.ls is None:\r\n self.ls = np.linspace(self.start, self.stop, nn.max_epochs)\r\n\r\n epoch = train_history[-1]['epoch']\r\n new_value = float32(self.ls[epoch - 1])\r\n setattr(nn, self.name, new_value)\r\n #getattr(nn, self.name).set_value(new_value)\r\n \r\ndef load_train_data(path):\r\n df = pd.read_csv(path)\r\n X = df.values.copy()\r\n np.random.seed(seed=2015)\r\n np.random.shuffle(X)\r\n X, labels, ids = X[:, 1:-1].astype(np.float32), X[:, -1], X[:, 0].astype(str)\r\n X_row_sums = X.sum(axis=1, keepdims=True)\r\n ix = [ix for ix, i in enumerate(X_row_sums==0.) if i]\r\n X_row_sums[ix] = [1.0]\r\n X = X/X_row_sums\r\n encoder = LabelEncoder()\r\n y = encoder.fit_transform(labels).astype(np.int32)\r\n scaler = StandardScaler()\r\n X = scaler.fit_transform(X)\r\n return X, y, ids, encoder, scaler\r\n \r\ndef load_test_data(path, scaler):\r\n df = pd.read_csv(path)\r\n X = df.values.copy()\r\n X, ids = X[:, 1:].astype(np.float32), X[:, 0].astype(str)\r\n X_row_sums = X.sum(axis=1, keepdims=True)\r\n ix = [ix for ix, i in enumerate(X_row_sums==0.) if i]\r\n X_row_sums[ix] = [1.0]\r\n X = X/X_row_sums\r\n X = scaler.fit_transform(X)\r\n return X, ids\r\n \r\ndef make_submission(clf, X_test, ids, encoder, name='predictions/nn2.cv.csv'):\r\n y_prob = clf.predict_proba(X_test)\r\n with open(name, 'w') as f:\r\n f.write('id,')\r\n f.write(','.join(encoder.classes_))\r\n f.write('\\n')\r\n for id, probs in zip(ids, y_prob):\r\n probas = ','.join([id] + list(map(str, probs.tolist())))\r\n f.write(probas)\r\n f.write('\\n')\r\n print((\"Wrote submission to file {}.\".format(name)))\r\n\r\ndef NeuralNetConstructor():\r\n layers0 = [('input', InputLayer),\r\n ('dense0', DenseLayer),\r\n ('dropout1', DropoutLayer),\r\n ('dense1', DenseLayer),\r\n ('dropout2', DropoutLayer),\r\n ('dense2', DenseLayer),\r\n ('dropout3', DropoutLayer), \r\n ('output', DenseLayer)]\r\n\r\n\r\n net0 = NeuralNet(layers=layers0,\r\n \r\n input_shape=(None, num_features),\r\n #dense100_num_units=50,\r\n #dense100_nonlinearity=linear,\r\n dense0_num_units=500,\r\n dropout1_p=0.5,\r\n dense1_num_units=300,\r\n dropout2_p=0.1,\r\n dense2_num_units=100,\r\n dropout3_p=0.1, \r\n output_num_units=num_classes,\r\n output_nonlinearity=softmax,\r\n\r\n update=nesterov_momentum,\r\n update_learning_rate=0.01,\r\n update_momentum=0.9,\r\n #on_epoch_finished=[\r\n # AdjustVariable('update_learning_rate', start=0.01, stop=0.0001),\r\n # AdjustVariable('update_momentum', start=0.9, stop=0.999),\r\n # ],\r\n \r\n eval_size=0.01,\r\n verbose=0,\r\n max_epochs=70)\r\n return net0\r\n\r\ndef compute_fold(train_index, valid_index, X, y, X_test, ids_train, ids_test):\r\n net0 = NeuralNetConstructor()\r\n X_train, X_valid = X[train_index], X[valid_index]\r\n y_train, y_valid = y[train_index], y[valid_index]\r\n\r\n index_shuffle = [i for i in range(X_train.shape[0])]\r\n random.shuffle(index_shuffle)\r\n net0.fit(X_train[index_shuffle,:], y_train[index_shuffle])\r\n \r\n # prediction on valid\r\n y_pred = net0.predict_proba(X_valid)\r\n preds_train = pd.DataFrame(y_pred, columns=['Class_'+str(i+1) for i in range(num_classes)])\r\n preds_train['id'] = ids_train[valid_index]\r\n preds_train['set'] = 1\r\n\r\n y_pred = net0.predict_proba(X_test)\r\n preds_test = pd.DataFrame(y_pred, columns=['Class_'+str(i+1) for i in range(num_classes)])\r\n preds_test['id'] = ids_test\r\n preds_test['set'] = 0\r\n \r\n preds = preds_train.append(preds_test, ignore_index=True)\r\n return preds\r\n \r\n\r\nopts, args = getopt.getopt(sys.argv[1:], \"t:v:p:e:c:f:\", [\"train=\", \"test=\", \"pred=\", \"epoch=\", \"cv=\", \"folds=\"])\r\nopts = {x[0]:x[1] for x in opts}\r\ntrain_file = opts['--train']\r\ntest_file = opts['--test']\r\npred_file = opts['--pred']\r\nepoch = int(opts['--epoch'])\r\ncv = int(opts['--cv'])\r\nnfolds = int(opts['--folds'])\r\n\r\nif cv == 0: \r\n nfolds = 2\r\n\r\nX, y, ids_train, encoder, scaler = load_train_data(train_file)\r\nX_test, ids_test = load_test_data(test_file, scaler)\r\nnum_classes = len(encoder.classes_)\r\nnum_features = X.shape[1]\r\nskf = StratifiedKFold(y, nfolds, random_state=2015)\r\nids_train_folds = np.empty(0)\r\nfor train_index, valid_index in skf:\r\n ids_train_folds = np.append(ids_train_folds, ids_train[valid_index])\r\n#pool = Pool()\r\n\r\nfor e in range(epoch):\r\n print(\"processing iteration\", e)\r\n\r\n if cv == 0:\r\n net0 = NeuralNetConstructor()\r\n index_shuffle = [i for i in range(X.shape[0])]\r\n random.shuffle(index_shuffle)\r\n net0.fit(X[index_shuffle,:], y[index_shuffle])\r\n preds = pd.DataFrame(net0.predict_proba(X_test), columns=['Class_'+str(i+1) for i in range(num_classes)])\r\n preds['id'] = ids_test\r\n preds.to_csv('../data/output-py/test_raw/' + os.path.splitext(pred_file)[0] + '.epoch' + str(e) + '.csv', index=False)\r\n else:\r\n count = 0\r\n preds_epoch = pd.DataFrame()\r\n actual = np.empty(0)\r\n list_result = Parallel(n_jobs=6)(delayed(compute_fold)(train_index, valid_index, X, y, X_test, ids_train, ids_test) for train_index, valid_index in skf)\r\n preds = pd.concat(list_result, axis = 0)\r\n preds.to_csv('../data/output-py/train_raw/' + os.path.splitext(pred_file)[0] + '.epoch' + str(e) + '.csv', index=False)\r\n #list_result = [pool.apply_async(compute_fold, args = (train_index, valid_index, X, y, ids_train)) for train_index, valid_index in skf]\r\n",
"#!/usr/bin/env python\r\n\r\nimport matplotlib\r\nmatplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab!\r\n\r\nimport sys\r\nimport seaborn as sns\r\nfrom pandas import read_pickle, qcut\r\nfrom itertools import combinations\r\nimport matplotlib.pyplot as plt\r\nfrom djeval import *\r\n\r\nsns.set_palette(\"deep\", desat=.6)\r\nsns.set_context(rc={\"figure.figsize\": (8, 4)})\r\n\r\nmsg(\"Hello there, reading yy_df.\")\r\nyy_df = read_pickle(sys.argv[1])\r\n\r\nx = yy_df['nmerror']\r\ny = yy_df['elo']\r\nwith sns.axes_style(\"white\"):\r\n sns.jointplot(x, y, kind=\"hex\")\r\nplt.savefig('/data/seaborn.png')\r\nplt.close()\r\n\r\nwith_elo = yy_df[yy_df['elo'].notnull()]\r\n\r\nfeatures = ['nmerror',\r\n 'blunderrate', 'noblunders', \r\n 'perfectrate',\r\n 'gameoutcome',\r\n 'won_by_checkmate', 'lost_by_checkmate', 'ended_by_checkmate',\r\n 'my_final_equity', 'final_equity',\r\n 'grit', 'any_grit', 'opponent_any_grit', 'major_grit',\r\n 'mate_created', 'mate_destroyed', 'premature_quit',\r\n 'side',\r\n 'drawn_game',\r\n 'gamelength',\r\n 'meanecho',\r\n 'opponent_nmerror', 'opponent_noblunders',\r\n 'mean_depth_clipped',\r\n 'mean_seldepth',\r\n 'min_nmerror', 'max_nmerror', 'max_meanecho',\r\n 'early_lead',\r\n 'q_error_one', 'q_error_two',\r\n 'opponent_q_error_one', 'opponent_q_error_two',\r\n 'pct_sanemoves',\r\n 'opponent_blunderrate', 'opponent_perfectrate',\r\n 'opponent_grit', 'opponent_meanecho',\r\n 'opponent_mate_created', 'opponent_mate_destroyed',\r\n 'mean_seldepth',\r\n 'mean_depths_ar', 'mean_deepest_ar',\r\n 'opponent_mean_depths_ar', 'opponent_mean_deepest_ar',\r\n 'pct_sanemoves',\r\n 'moveelo_weighted'\r\n ]\r\n\r\nplottables = ['elo', 'gbr_prediction', 'gbr_error']\r\nplottables.extend(['gamelength', 'mean_depth_clipped', 'mean_deepest_ar', 'opponent_mean_deepest_ar'])\r\n\r\ndo_indivs = False\r\nif do_indivs:\r\n for a, b in combinations(plottables, 2):\r\n for first, second in [(a,b), (b,a)]:\r\n try:\r\n groupings, bins = qcut(with_elo[first], 10, labels=False, retbins=True)\r\n sns.violinplot(with_elo[second], groupings)\r\n plt.savefig('/data/' + first + '_' + second + '.png')\r\n plt.close()\r\n except:\r\n print((\"Couldnt manage for %s %s\" % (first, second)))\r\n\r\n # f, ax = plt.subplots(figsize=(11, 6))\r\n # sns.violinplot(with_elo[second], groupings, names=[str(b) + str(b+1) for b in bins[:-1]])\r\n # ax.set(ylim=(-.7, 1.05))\r\n # sns.despine(left=True, bottom=True)\r\n print('.', end=' ')\r\n sys.stdout.flush()\r\n\r\n\r\ng = sns.pairplot(with_elo[plottables], size=2.5)\r\nplt.savefig('/data/pairplot.png')\r\nplt.close()\r\n",
"#!/usr/bin/env python\r\n\r\nimport os, code\r\nimport pickle as pickle\r\nfrom djeval import *\r\nimport numpy as np\r\nfrom pandas import read_pickle, cut, concat, Series, get_dummies\r\nfrom sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier, ExtraTreesClassifier\r\nfrom sklearn.cross_validation import StratifiedKFold, cross_val_score\r\nfrom sklearn.metrics import average_precision_score\r\nfrom sklearn.externals import joblib\r\nfrom sklearn.linear_model import LogisticRegression\r\n\r\nNUM_ELO_GROUPS = int(sys.argv[1])\r\nNUM_ERRORCHUNKS = int(sys.argv[2])\r\nNUM_ESTIMATORS = int(sys.argv[3])\r\nLOW_BOUND = float(sys.argv[4])\r\nHIGH_BOUND = float(sys.argv[5])\r\n\r\nn_cv_groups = 2\r\n\r\ndef shell():\r\n vars = globals()\r\n vars.update(locals())\r\n shell = code.InteractiveConsole(vars)\r\n shell.interact()\r\n\r\nchunk_spacing_factor = (HIGH_BOUND / LOW_BOUND) ** (1/(float(NUM_ERRORCHUNKS)-1.))\r\nchunk_bounds = [-1. * LOW_BOUND * (chunk_spacing_factor ** i) for i in range(0,NUM_ERRORCHUNKS)]\r\nchunk_bounds.insert(0, 0.)\r\nmsg('errorchunk bounds are %s' % chunk_bounds)\r\n\r\n\r\nmsg('splitting ELOs')\r\neheaders_filename = '/data/eheaders.p'\r\neheaders_file = open(eheaders_filename, 'r')\r\neheaders = pickle.load(eheaders_file)\r\nelos = list(eheaders['elos'].values())\r\nelo_bins = np.percentile(elos, np.arange(0, 100. + 1e-9, 100./float(NUM_ELO_GROUPS)))\r\nmsg('ELO bins are %s' % str(elo_bins))\r\n\r\nmsg('reading movedata')\r\nmoves_df = read_pickle('/data/movedata.p')\r\nmoves_df['clipped_movergain'] = moves_df['movergain'].clip(-1e9,0)\r\ntrain_df = moves_df[moves_df['elo'].notnull()]\r\n\r\nchain_validating = True\r\nif chain_validating:\r\n train_df = train_df[train_df['gamenum'] % 3 == 0]\r\n\r\nmsg('Looking at %i moves' % train_df.shape[0])\r\ntrain_df['elo_groups'] = cut(train_df['elo'], elo_bins, include_lowest=True)\r\n\r\nblundermodel_dir = sys.argv[6]\r\nif not os.path.exists(blundermodel_dir):\r\n os.makedirs(blundermodel_dir)\r\n\r\ncategorical_features = ['bestmove_piece', 'bestmove_dir']\r\ndummy_features = []\r\nfor index, cf in enumerate(categorical_features):\r\n dummies = get_dummies(train_df[cf], prefix=cf)\r\n dummy_features.extend(dummies.columns.values)\r\n\r\nfeatures = ['side', 'halfply', 'moverscore', 'bestmove_is_capture', 'bestmove_is_check', 'depth', 'seldepth', 'num_bestmoves', 'num_bestmove_changes', 'bestmove_depths_agreeing', 'deepest_change', 'bestmove_dist', 'prevgain']\r\nfeatures.extend(dummy_features)\r\n\r\njoblib.dump([elo_bins, chunk_bounds, features], blundermodel_dir + 'groups.p')\r\n\r\n# more features you could have:\r\n# * loss for the 2nd, 3rd, 4th, 5th best move, etc (perfect move is\r\n# less likely if there are several very close alternatives)\r\n\r\nmodelnum = 0\r\nfor elo_name, elo_df in train_df.groupby(train_df['elo_groups']):\r\n subset_df = elo_df\r\n for cb in chunk_bounds:\r\n msg('working on elo group %s, of size %i. fitting model for error >= %f' % (elo_name, subset_df.shape[0], cb))\r\n X = subset_df[features]\r\n y = (subset_df['clipped_movergain'] >= cb)\r\n\r\n rfc = True\r\n if rfc:\r\n extra = True\r\n if extra:\r\n clf = ExtraTreesClassifier(min_samples_split=200, min_samples_leaf=50, n_jobs=-1, n_estimators=NUM_ESTIMATORS, verbose=1)\r\n else:\r\n clf = RandomForestClassifier(min_samples_split=200, min_samples_leaf=50, n_jobs=-1, n_estimators=NUM_ESTIMATORS, verbose=1, oob_score=True)\r\n else:\r\n clf = GradientBoostingClassifier(min_samples_split=500, min_samples_leaf=300, n_estimators=NUM_ESTIMATORS, verbose=1, subsample=0.5, learning_rate=0.2)\r\n\r\n msg('CROSS VALIDATING')\r\n skf = StratifiedKFold(y, n_folds=2, shuffle=True)\r\n ins = []\r\n outs = []\r\n for train_index, test_index in skf:\r\n foo = clf.fit(X.iloc[train_index], y.iloc[train_index])\r\n ins.append(average_precision_score(clf.predict(X.iloc[train_index]), y.iloc[train_index]))\r\n outs.append(average_precision_score(clf.predict(X.iloc[test_index]), y.iloc[test_index]))\r\n msg(\"insample average precision score: %s = %f\" % (ins, np.mean(ins)))\r\n msg(\"outsample average precision score: %s = %f\" % (outs, np.mean(outs)))\r\n # cvs = cross_val_score(clf, X, y, cv=n_cv_groups, n_jobs=-1, scoring='roc_auc')\r\n # msg('CV scores: %s = %f' % (cvs, np.mean(cvs)))\r\n\r\n msg('FITTING')\r\n if chain_validating:\r\n fit_df = subset_df[subset_df['gamenum'] % 3 == 0]\r\n fit_X = fit_df[features]\r\n fit_y = (fit_df['clipped_movergain'] >= cb)\r\n clf.fit(fit_X, fit_y)\r\n else:\r\n clf.fit(X, y)\r\n\r\n # measure in-sample score\r\n # measure extent of over-fitting\r\n # measure model quality in-sample and out-of-sample\r\n\r\n pred_y = clf.predict_proba(X)\r\n pred_y = [x[1] for x in pred_y]\r\n combo = concat([Series(y.values), Series(pred_y)], axis=1)\r\n combo.columns = ['actual', 'predicted']\r\n combo_groups = cut(combo['predicted'], 10)\r\n msg(\"PREDICTION DISTRIBUTION AND SUCCESS:\\n%s\" % combo.groupby(combo_groups)['actual'].agg({'mean actual': np.mean, 'count': len}))\r\n\r\n msg(\"FULL INSAMPLE AVERAGE PRECISION SCORE: %f\" % average_precision_score(y, pred_y))\r\n\r\n joblib.dump([elo_name, cb, clf], '%s%i.p' % (blundermodel_dir, modelnum))\r\n modelnum = modelnum + 1\r\n subset_df = subset_df[~y]\r\n",
"\r\nfrom time import time\r\n\r\nimport lasagne\r\nimport lasagne.layers\r\nfrom lasagne.updates import nesterov_momentum\r\nfrom lasagne.objectives import Objective\r\nfrom lasagne.layers import get_all_layers, get_output, InputLayer\r\nfrom nolearn.lasagne import NeuralNet\r\nfrom nolearn.lasagne.handlers import SaveWeights\r\nimport numpy as np\r\nimport theano\r\nfrom theano import tensor as T\r\n\r\nimport data\r\nimport util\r\nimport iterator\r\n\r\n\r\ndef create_net(config, **kwargs):\r\n args = {\r\n 'layers': config.layers,\r\n 'batch_iterator_train': iterator.ResampleIterator(\r\n config, batch_size=config.get('batch_size_train')),\r\n 'batch_iterator_test': iterator.SharedIterator(\r\n config, deterministic=True, \r\n batch_size=config.get('batch_size_test')),\r\n 'on_epoch_finished': [\r\n Schedule('update_learning_rate', config.get('schedule'),\r\n weights_file=config.final_weights_file),\r\n SaveBestWeights(weights_file=config.weights_file, \r\n loss='kappa', greater_is_better=True,),\r\n SaveWeights(config.weights_epoch, every_n_epochs=5),\r\n SaveWeights(config.weights_best, every_n_epochs=1, only_best=True),\r\n ],\r\n 'objective': get_objective(),\r\n 'use_label_encoder': False,\r\n 'eval_size': 0.1,\r\n 'regression': True,\r\n 'max_epochs': 1000,\r\n 'verbose': 2,\r\n 'update_learning_rate': theano.shared(\r\n util.float32(config.get('schedule')[0])),\r\n 'update': nesterov_momentum,\r\n 'update_momentum': 0.9,\r\n 'custom_score': ('kappa', util.kappa),\r\n\r\n }\r\n args.update(kwargs)\r\n net = Net(**args)\r\n return net\r\n\r\n\r\ndef get_objective(l1=0.0, l2=0.0005):\r\n class RegularizedObjective(Objective):\r\n\r\n def get_loss(self, input=None, target=None, aggregation=None,\r\n deterministic=False, **kwargs):\r\n\r\n l1_layer = get_all_layers(self.input_layer)[1]\r\n\r\n loss = super(RegularizedObjective, self).get_loss(\r\n input=input, target=target, aggregation=aggregation,\r\n deterministic=deterministic, **kwargs)\r\n if not deterministic:\r\n return loss \\\r\n + l1 * lasagne.regularization.regularize_layer_params(\r\n l1_layer, lasagne.regularization.l1) \\\r\n + l2 * lasagne.regularization.regularize_network_params(\r\n self.input_layer, lasagne.regularization.l2)\r\n else:\r\n return loss\r\n return RegularizedObjective\r\n\r\n\r\nclass Schedule(object):\r\n def __init__(self, name, schedule, weights_file=None):\r\n self.name = name\r\n self.schedule = schedule\r\n self.weights_file = weights_file\r\n\r\n def __call__(self, nn, train_history):\r\n epoch = train_history[-1]['epoch']\r\n if epoch in self.schedule:\r\n new_value = self.schedule[epoch]\r\n if new_value == 'stop':\r\n if self.weights_file is not None:\r\n nn.save_params_to(self.weights_file)\r\n raise StopIteration\r\n getattr(nn, self.name).set_value(util.float32(new_value))\r\n\r\n\r\nclass SaveBestWeights(object):\r\n def __init__(self, weights_file, loss='kappa', greater_is_better=True):\r\n self.weights_file = weights_file\r\n self.best_valid = np.inf\r\n self.best_valid_epoch = 0\r\n self.best_weights = None\r\n self.loss = loss\r\n self.greater_is_better = greater_is_better\r\n\r\n def __call__(self, nn, train_history):\r\n current_valid = train_history[-1][self.loss] \\\r\n * (-1.0 if self.greater_is_better else 1.0)\r\n current_epoch = train_history[-1]['epoch']\r\n if current_valid < self.best_valid:\r\n self.best_valid = current_valid\r\n self.best_valid_epoch = current_epoch\r\n self.best_weights = [w.get_value() for w in nn.get_all_params()]\r\n nn.save_params_to(self.weights_file)\r\n\r\n\r\nclass Net(NeuralNet):\r\n\r\n def train_test_split(self, X, y, eval_size):\r\n if eval_size:\r\n X_train, X_valid, y_train, y_valid = data.split(\r\n X, y, test_size=eval_size)\r\n else:\r\n X_train, y_train = X, y\r\n X_valid, y_valid = X[len(X):], y[len(y):]\r\n\r\n return X_train, X_valid, y_train, y_valid\r\n\r\n def initialize(self):\r\n if getattr(self, '_initialized', False):\r\n return\r\n\r\n out = getattr(self, '_output_layer', None)\r\n if out is None:\r\n out = self._output_layer = self.initialize_layers()\r\n self._check_for_unused_kwargs()\r\n\r\n iter_funcs = self._create_iter_funcs(\r\n self.layers_, self.objective, self.update,\r\n self.y_tensor_type,\r\n )\r\n self.train_iter_, self.eval_iter_, self.predict_iter_, self.transform_iter_ = iter_funcs\r\n self._initialized = True\r\n\r\n def _create_iter_funcs(self, layers, objective, update, output_type):\r\n y_batch = output_type('y_batch')\r\n\r\n output_layer = list(layers.values())[-1]\r\n objective_params = self._get_params_for('objective')\r\n obj = objective(output_layer, **objective_params)\r\n if not hasattr(obj, 'layers'):\r\n # XXX breaking the Lasagne interface a little:\r\n obj.layers = layers\r\n\r\n loss_train = obj.get_loss(None, y_batch)\r\n loss_eval = obj.get_loss(None, y_batch, deterministic=True)\r\n predict_proba = get_output(output_layer, None, deterministic=True)\r\n\r\n try:\r\n transform = get_output([v for k, v in list(layers.items()) \r\n if 'rmspool' in k or 'maxpool' in k][-1],\r\n None, deterministic=True)\r\n except IndexError:\r\n transform = get_output(list(layers.values())[-2], None,\r\n deterministic=True)\r\n\r\n if not self.regression:\r\n predict = predict_proba.argmax(axis=1)\r\n accuracy = T.mean(T.eq(predict, y_batch))\r\n else:\r\n accuracy = loss_eval\r\n\r\n all_params = self.get_all_params(trainable=True)\r\n update_params = self._get_params_for('update')\r\n updates = update(loss_train, all_params, **update_params)\r\n\r\n input_layers = [layer for layer in list(layers.values())\r\n if isinstance(layer, InputLayer)]\r\n\r\n X_inputs = [theano.Param(input_layer.input_var, name=input_layer.name)\r\n for input_layer in input_layers]\r\n inputs = X_inputs + [theano.Param(y_batch, name=\"y\")]\r\n\r\n train_iter = theano.function(\r\n inputs=inputs,\r\n outputs=[loss_train],\r\n updates=updates,\r\n )\r\n eval_iter = theano.function(\r\n inputs=inputs,\r\n outputs=[loss_eval, accuracy],\r\n )\r\n predict_iter = theano.function(\r\n inputs=X_inputs,\r\n outputs=predict_proba,\r\n )\r\n transform_iter = theano.function(\r\n inputs=X_inputs,\r\n outputs=transform,\r\n )\r\n return train_iter, eval_iter, predict_iter, transform_iter\r\n\r\n def transform(self, X, transform=None, color_vec=None):\r\n features = []\r\n for Xb, yb in self.batch_iterator_test(X, transform=transform,\r\n color_vec=color_vec):\r\n features.append(self.transform_iter_(Xb))\r\n return np.vstack(features)\r\n \r\n def train_loop(self, X, y):\r\n X_train, X_valid, y_train, y_valid = self.train_test_split(\r\n X, y, self.eval_size)\r\n\r\n on_epoch_finished = self.on_epoch_finished\r\n if not isinstance(on_epoch_finished, (list, tuple)):\r\n on_epoch_finished = [on_epoch_finished]\r\n\r\n on_training_started = self.on_training_started\r\n if not isinstance(on_training_started, (list, tuple)):\r\n on_training_started = [on_training_started]\r\n\r\n on_training_finished = self.on_training_finished\r\n if not isinstance(on_training_finished, (list, tuple)):\r\n on_training_finished = [on_training_finished]\r\n\r\n epoch = 0\r\n best_valid_loss = (\r\n min([row['valid_loss'] for row in self.train_history_]) if\r\n self.train_history_ else np.inf\r\n )\r\n best_train_loss = (\r\n min([row['train_loss'] for row in self.train_history_]) if\r\n self.train_history_ else np.inf\r\n )\r\n for func in on_training_started:\r\n func(self, self.train_history_)\r\n\r\n num_epochs_past = len(self.train_history_)\r\n\r\n while epoch < self.max_epochs:\r\n epoch += 1\r\n\r\n train_losses = []\r\n valid_losses = []\r\n valid_accuracies = []\r\n y_pred, y_true = [], []\r\n\r\n t0 = time()\r\n\r\n for Xb, yb in self.batch_iterator_train(X_train, y_train):\r\n batch_train_loss = self.train_iter_(Xb, yb)\r\n if not np.isfinite(batch_train_loss[0]):\r\n raise ValueError(\"non finite loss\")\r\n train_losses.append(batch_train_loss)\r\n\r\n for Xb, yb in self.batch_iterator_test(X_valid, y_valid):\r\n\r\n batch_valid_loss, accuracy = self.eval_iter_(Xb, yb)\r\n\r\n valid_losses.append(batch_valid_loss)\r\n valid_accuracies.append(accuracy)\r\n y_true.append(yb)\r\n if self.custom_score:\r\n y_prob = self.predict_iter_(Xb)\r\n y_pred.append(y_prob)\r\n\r\n avg_train_loss = np.mean(train_losses)\r\n avg_valid_loss = np.mean(valid_losses)\r\n avg_valid_accuracy = np.mean(valid_accuracies)\r\n if self.custom_score and self.eval_size:\r\n\r\n y_true = np.concatenate(y_true)\r\n y_pred = np.concatenate(y_pred)\r\n y_pred = np.clip(y_pred, np.min(y_true), np.max(y_true))\r\n avg_custom_score = self.custom_score[1](y_true, y_pred)\r\n\r\n if avg_train_loss < best_train_loss:\r\n best_train_loss = avg_train_loss\r\n if avg_valid_loss < best_valid_loss:\r\n best_valid_loss = avg_valid_loss\r\n\r\n info = {\r\n 'epoch': num_epochs_past + epoch,\r\n 'train_loss': avg_train_loss,\r\n 'train_loss_best': best_train_loss == avg_train_loss,\r\n 'valid_loss': avg_valid_loss,\r\n 'valid_loss_best': best_valid_loss == avg_valid_loss,\r\n 'valid_accuracy': avg_valid_accuracy,\r\n 'dur': time() - t0,\r\n }\r\n if self.custom_score and self.eval_size:\r\n info[self.custom_score[0]] = avg_custom_score\r\n self.train_history_.append(info)\r\n\r\n try:\r\n for func in on_epoch_finished:\r\n func(self, self.train_history_)\r\n except StopIteration:\r\n break\r\n\r\n for func in on_training_finished:\r\n func(self, self.train_history_)\r\n\r\n",
"import numpy as np\r\n\r\nimport theano \r\nimport theano.tensor as T\r\n\r\nimport lasagne as nn\r\n\r\nimport data\r\nimport load\r\nimport nn_plankton\r\nimport dihedral\r\nimport dihedral_fast\r\nimport tmp_dnn\r\nimport tta\r\n\r\n\r\nvalidation_split_path = \"splits/bagging_split_4.pkl\"\r\n\r\n\r\npatch_sizes = [(95, 95), (47, 47)]\r\naugmentation_params = {\r\n 'zoom_range': (1 / 1.6, 1.6),\r\n 'rotation_range': (0, 360),\r\n 'shear_range': (-20, 20),\r\n 'translation_range': (-10, 10),\r\n 'do_flip': True,\r\n 'allow_stretch': 1.3,\r\n}\r\n\r\nbatch_size = 128 // 4\r\nchunk_size = 32768 // 4\r\nnum_chunks_train = 840\r\n\r\nmomentum = 0.9\r\nlearning_rate_schedule = {\r\n 0: 0.0015,\r\n 700: 0.00015,\r\n 800: 0.000015,\r\n}\r\n\r\nvalidate_every = 20\r\nsave_every = 20\r\n\r\n\r\ndef estimate_scale(img):\r\n return np.maximum(img.shape[0], img.shape[1]) / 85.0\r\n\r\nscale_factors = [estimate_scale, 5.0] # combine size-based rescaling + fixed rescaling\r\n \r\n\r\n# augmentation_transforms_test = []\r\n# for flip in [True, False]:\r\n# for zoom in [1/1.3, 1/1.2, 1/1.1, 1.0, 1.1, 1.2, 1.3]:\r\n# for rot in np.linspace(0.0, 360.0, 5, endpoint=False):\r\n# tf = data.build_augmentation_transform(zoom=(zoom, zoom), rotation=rot, flip=flip)\r\n# augmentation_transforms_test.append(tf)\r\naugmentation_transforms_test = tta.build_quasirandom_transforms(70, **{\r\n 'zoom_range': (1 / 1.4, 1.4),\r\n 'rotation_range': (0, 360),\r\n 'shear_range': (-10, 10),\r\n 'translation_range': (-8, 8),\r\n 'do_flip': True,\r\n 'allow_stretch': 1.2,\r\n})\r\n\r\n\r\n\r\ndata_loader = load.ZmuvMultiscaleDataLoader(scale_factors=scale_factors, num_chunks_train=num_chunks_train,\r\n patch_sizes=patch_sizes, chunk_size=chunk_size, augmentation_params=augmentation_params,\r\n augmentation_transforms_test=augmentation_transforms_test, validation_split_path=validation_split_path)\r\n\r\n\r\n# Conv2DLayer = nn.layers.cuda_convnet.Conv2DCCLayer\r\n# MaxPool2DLayer = nn.layers.cuda_convnet.MaxPool2DCCLayer\r\n\r\nConv2DLayer = tmp_dnn.Conv2DDNNLayer\r\nMaxPool2DLayer = tmp_dnn.MaxPool2DDNNLayer\r\n\r\n\r\ndef build_model():\r\n l0_variable = nn.layers.InputLayer((batch_size, 1, patch_sizes[0][0], patch_sizes[0][1]))\r\n l0c = dihedral.CyclicSliceLayer(l0_variable)\r\n\r\n l1a = Conv2DLayer(l0c, num_filters=32, filter_size=(3, 3), border_mode=\"same\", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1), nonlinearity=nn_plankton.leaky_relu)\r\n l1b = Conv2DLayer(l1a, num_filters=16, filter_size=(3, 3), border_mode=\"same\", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1), nonlinearity=nn_plankton.leaky_relu)\r\n l1 = MaxPool2DLayer(l1b, ds=(3, 3), strides=(2, 2))\r\n l1r = dihedral_fast.CyclicConvRollLayer(l1)\r\n\r\n l2a = Conv2DLayer(l1r, num_filters=64, filter_size=(3, 3), border_mode=\"same\", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1), nonlinearity=nn_plankton.leaky_relu)\r\n l2b = Conv2DLayer(l2a, num_filters=32, filter_size=(3, 3), border_mode=\"same\", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1), nonlinearity=nn_plankton.leaky_relu)\r\n l2 = MaxPool2DLayer(l2b, ds=(3, 3), strides=(2, 2))\r\n l2r = dihedral_fast.CyclicConvRollLayer(l2)\r\n\r\n l3a = Conv2DLayer(l2r, num_filters=128, filter_size=(3, 3), border_mode=\"same\", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1), nonlinearity=nn_plankton.leaky_relu)\r\n l3b = Conv2DLayer(l3a, num_filters=128, filter_size=(3, 3), border_mode=\"same\", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1), nonlinearity=nn_plankton.leaky_relu)\r\n l3c = Conv2DLayer(l3b, num_filters=64, filter_size=(3, 3), border_mode=\"same\", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1), nonlinearity=nn_plankton.leaky_relu)\r\n l3 = MaxPool2DLayer(l3c, ds=(3, 3), strides=(2, 2))\r\n l3r = dihedral_fast.CyclicConvRollLayer(l3)\r\n\r\n l4a = Conv2DLayer(l3r, num_filters=256, filter_size=(3, 3), border_mode=\"same\", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1), nonlinearity=nn_plankton.leaky_relu)\r\n l4b = Conv2DLayer(l4a, num_filters=256, filter_size=(3, 3), border_mode=\"same\", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1), nonlinearity=nn_plankton.leaky_relu)\r\n l4c = Conv2DLayer(l4b, num_filters=128, filter_size=(3, 3), border_mode=\"same\", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1), nonlinearity=nn_plankton.leaky_relu) \r\n l4 = MaxPool2DLayer(l4c, ds=(3, 3), strides=(2, 2))\r\n l4r = dihedral_fast.CyclicConvRollLayer(l4)\r\n l4f = nn.layers.flatten(l4r)\r\n\r\n l5 = nn.layers.DenseLayer(nn.layers.dropout(l4f, p=0.5), num_units=256, W=nn_plankton.Orthogonal(1.0), b=nn.init.Constant(0.1), nonlinearity=nn_plankton.leaky_relu)\r\n l5r = dihedral_fast.CyclicRollLayer(l5)\r\n\r\n l6 = nn.layers.DenseLayer(nn.layers.dropout(l5r, p=0.5), num_units=256, W=nn_plankton.Orthogonal(1.0), b=nn.init.Constant(0.1), nonlinearity=nn_plankton.leaky_relu)\r\n l_variable = dihedral.CyclicPoolLayer(l6, pool_function=nn_plankton.rms)\r\n\r\n\r\n # fixed scale part\r\n l0_fixed = nn.layers.InputLayer((batch_size, 1, patch_sizes[1][0], patch_sizes[1][1]))\r\n l0c = dihedral.CyclicSliceLayer(l0_fixed)\r\n\r\n l1a = Conv2DLayer(l0c, num_filters=16, filter_size=(3, 3), border_mode=\"same\", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1))\r\n l1b = Conv2DLayer(l1a, num_filters=8, filter_size=(3, 3), border_mode=\"same\", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1))\r\n l1 = MaxPool2DLayer(l1b, ds=(3, 3), strides=(2, 2))\r\n l1r = dihedral_fast.CyclicConvRollLayer(l1)\r\n\r\n l2a = Conv2DLayer(l1r, num_filters=32, filter_size=(3, 3), border_mode=\"same\", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1))\r\n l2b = Conv2DLayer(l2a, num_filters=16, filter_size=(3, 3), border_mode=\"same\", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1))\r\n l2 = MaxPool2DLayer(l2b, ds=(3, 3), strides=(2, 2))\r\n l2r = dihedral_fast.CyclicConvRollLayer(l2)\r\n\r\n l3a = Conv2DLayer(l2r, num_filters=64, filter_size=(3, 3), border_mode=\"same\", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1))\r\n l3b = Conv2DLayer(l3a, num_filters=64, filter_size=(3, 3), border_mode=\"same\", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1))\r\n l3c = Conv2DLayer(l3b, num_filters=32, filter_size=(3, 3), border_mode=\"same\", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1))\r\n l3 = MaxPool2DLayer(l3c, ds=(3, 3), strides=(2, 2))\r\n l3r = dihedral_fast.CyclicConvRollLayer(l3)\r\n l3f = nn.layers.flatten(l3r)\r\n\r\n l4 = nn.layers.DenseLayer(nn.layers.dropout(l3f, p=0.5), num_units=128, W=nn_plankton.Orthogonal(1.0), b=nn.init.Constant(0.1))\r\n l4r = dihedral_fast.CyclicRollLayer(l4)\r\n\r\n l5 = nn.layers.DenseLayer(nn.layers.dropout(l4r, p=0.5), num_units=128, W=nn_plankton.Orthogonal(1.0), b=nn.init.Constant(0.1))\r\n l_fixed = dihedral.CyclicPoolLayer(l5, pool_function=nn_plankton.rms) \r\n\r\n\r\n # merge the parts\r\n l_merged = nn.layers.concat([l_variable, l_fixed])\r\n\r\n l7 = nn.layers.DenseLayer(nn.layers.dropout(l_merged, p=0.5), num_units=data.num_classes, nonlinearity=T.nnet.softmax, W=nn_plankton.Orthogonal(1.0))\r\n\r\n return [l0_variable, l0_fixed], l7\r\n",
"\"\"\"\r\nLoad an analysis file and redo the predictions on the validation set / test set,\r\nthis time with augmented data and averaging. Store them as numpy files.\r\n\"\"\"\r\n\r\nimport numpy as np\r\n# import pandas as pd\r\nimport theano\r\nimport theano.tensor as T\r\nimport layers\r\nimport cc_layers\r\nimport custom\r\nimport load_data\r\nimport realtime_augmentation as ra\r\nimport time\r\nimport csv\r\nimport os\r\nimport pickle as pickle\r\n\r\n\r\nBATCH_SIZE = 32 # 16\r\nNUM_INPUT_FEATURES = 3\r\n\r\nCHUNK_SIZE = 8000 # 10000 # this should be a multiple of the batch size\r\n\r\n# ANALYSIS_PATH = \"analysis/try_convnet_cc_multirot_3x69r45_untied_bias.pkl\"\r\nANALYSIS_PATH = \"analysis/final/try_convnet_cc_multirotflip_3x69r45_pysex.pkl\"\r\n\r\nDO_VALID = True # disable this to not bother with the validation set evaluation\r\nDO_TEST = True # disable this to not generate predictions on the testset\r\n\r\n\r\n\r\ntarget_filename = os.path.basename(ANALYSIS_PATH).replace(\".pkl\", \".npy.gz\")\r\ntarget_path_valid = os.path.join(\"predictions/final/augmented/valid\", target_filename)\r\ntarget_path_test = os.path.join(\"predictions/final/augmented/test\", target_filename)\r\n\r\n\r\nprint(\"Loading model data etc.\")\r\nanalysis = np.load(ANALYSIS_PATH)\r\n\r\ninput_sizes = [(69, 69), (69, 69)]\r\n\r\nds_transforms = [\r\n ra.build_ds_transform(3.0, target_size=input_sizes[0]),\r\n ra.build_ds_transform(3.0, target_size=input_sizes[1]) + ra.build_augmentation_transform(rotation=45)]\r\n\r\nnum_input_representations = len(ds_transforms)\r\n\r\n# split training data into training + a small validation set\r\nnum_train = load_data.num_train\r\nnum_valid = num_train // 10 # integer division\r\nnum_train -= num_valid\r\nnum_test = load_data.num_test\r\n\r\nvalid_ids = load_data.train_ids[num_train:]\r\ntrain_ids = load_data.train_ids[:num_train]\r\ntest_ids = load_data.test_ids\r\n\r\ntrain_indices = np.arange(num_train)\r\nvalid_indices = np.arange(num_train, num_train+num_valid)\r\ntest_indices = np.arange(num_test)\r\n\r\ny_valid = np.load(\"data/solutions_train.npy\")[num_train:]\r\n\r\n\r\nprint(\"Build model\")\r\nl0 = layers.Input2DLayer(BATCH_SIZE, NUM_INPUT_FEATURES, input_sizes[0][0], input_sizes[0][1])\r\nl0_45 = layers.Input2DLayer(BATCH_SIZE, NUM_INPUT_FEATURES, input_sizes[1][0], input_sizes[1][1])\r\n\r\nl0r = layers.MultiRotSliceLayer([l0, l0_45], part_size=45, include_flip=True)\r\n\r\nl0s = cc_layers.ShuffleBC01ToC01BLayer(l0r) \r\n\r\nl1a = cc_layers.CudaConvnetConv2DLayer(l0s, n_filters=32, filter_size=6, weights_std=0.01, init_bias_value=0.1, dropout=0.0, partial_sum=1, untie_biases=True)\r\nl1 = cc_layers.CudaConvnetPooling2DLayer(l1a, pool_size=2)\r\n\r\nl2a = cc_layers.CudaConvnetConv2DLayer(l1, n_filters=64, filter_size=5, weights_std=0.01, init_bias_value=0.1, dropout=0.0, partial_sum=1, untie_biases=True)\r\nl2 = cc_layers.CudaConvnetPooling2DLayer(l2a, pool_size=2)\r\n\r\nl3a = cc_layers.CudaConvnetConv2DLayer(l2, n_filters=128, filter_size=3, weights_std=0.01, init_bias_value=0.1, dropout=0.0, partial_sum=1, untie_biases=True)\r\nl3b = cc_layers.CudaConvnetConv2DLayer(l3a, n_filters=128, filter_size=3, pad=0, weights_std=0.1, init_bias_value=0.1, dropout=0.0, partial_sum=1, untie_biases=True)\r\nl3 = cc_layers.CudaConvnetPooling2DLayer(l3b, pool_size=2)\r\n\r\nl3s = cc_layers.ShuffleC01BToBC01Layer(l3)\r\n\r\nj3 = layers.MultiRotMergeLayer(l3s, num_views=4) # 2) # merge convolutional parts\r\n\r\nl4 = layers.DenseLayer(j3, n_outputs=4096, weights_std=0.001, init_bias_value=0.01, dropout=0.5)\r\n\r\n# l4a = layers.DenseLayer(j3, n_outputs=4096, weights_std=0.001, init_bias_value=0.01, dropout=0.5, nonlinearity=layers.identity)\r\n# l4 = layers.FeatureMaxPoolingLayer(l4a, pool_size=2, feature_dim=1, implementation='reshape')\r\n\r\n# l5 = layers.DenseLayer(l4, n_outputs=37, weights_std=0.01, init_bias_value=0.0, dropout=0.5, nonlinearity=custom.clip_01) # nonlinearity=layers.identity)\r\nl5 = layers.DenseLayer(l4, n_outputs=37, weights_std=0.01, init_bias_value=0.1, dropout=0.5, nonlinearity=layers.identity)\r\n\r\n# l6 = layers.OutputLayer(l5, error_measure='mse')\r\nl6 = custom.OptimisedDivGalaxyOutputLayer(l5) # this incorporates the constraints on the output (probabilities sum to one, weighting, etc.)\r\n\r\n\r\n\r\nxs_shared = [theano.shared(np.zeros((1,1,1,1), dtype=theano.config.floatX)) for _ in range(num_input_representations)]\r\n\r\nidx = T.lscalar('idx')\r\n\r\ngivens = {\r\n l0.input_var: xs_shared[0][idx*BATCH_SIZE:(idx+1)*BATCH_SIZE],\r\n l0_45.input_var: xs_shared[1][idx*BATCH_SIZE:(idx+1)*BATCH_SIZE],\r\n}\r\n\r\ncompute_output = theano.function([idx], l6.predictions(dropout_active=False), givens=givens)\r\n\r\n\r\nprint(\"Load model parameters\")\r\nlayers.set_param_values(l6, analysis['param_values'])\r\n\r\nprint(\"Create generators\")\r\n# set here which transforms to use to make predictions\r\naugmentation_transforms = []\r\nfor zoom in [1 / 1.2, 1.0, 1.2]:\r\n for angle in np.linspace(0, 360, 10, endpoint=False):\r\n augmentation_transforms.append(ra.build_augmentation_transform(rotation=angle, zoom=zoom))\r\n augmentation_transforms.append(ra.build_augmentation_transform(rotation=(angle + 180), zoom=zoom, shear=180)) # flipped\r\n\r\nprint(\" %d augmentation transforms.\" % len(augmentation_transforms))\r\n\r\n\r\naugmented_data_gen_valid = ra.realtime_fixed_augmented_data_gen(valid_indices, 'train', augmentation_transforms=augmentation_transforms, chunk_size=CHUNK_SIZE, target_sizes=input_sizes, ds_transforms=ds_transforms, processor_class=ra.LoadAndProcessFixedPysexCenteringRescaling)\r\nvalid_gen = load_data.buffered_gen_mp(augmented_data_gen_valid, buffer_size=1)\r\n\r\n\r\naugmented_data_gen_test = ra.realtime_fixed_augmented_data_gen(test_indices, 'test', augmentation_transforms=augmentation_transforms, chunk_size=CHUNK_SIZE, target_sizes=input_sizes, ds_transforms=ds_transforms, processor_class=ra.LoadAndProcessFixedPysexCenteringRescaling)\r\ntest_gen = load_data.buffered_gen_mp(augmented_data_gen_test, buffer_size=1)\r\n\r\n\r\napprox_num_chunks_valid = int(np.ceil(num_valid * len(augmentation_transforms) / float(CHUNK_SIZE)))\r\napprox_num_chunks_test = int(np.ceil(num_test * len(augmentation_transforms) / float(CHUNK_SIZE)))\r\n\r\nprint(\"Approximately %d chunks for the validation set\" % approx_num_chunks_valid)\r\nprint(\"Approximately %d chunks for the test set\" % approx_num_chunks_test)\r\n\r\n\r\nif DO_VALID:\r\n print()\r\n print(\"VALIDATION SET\")\r\n print(\"Compute predictions\")\r\n predictions_list = []\r\n start_time = time.time()\r\n\r\n for e, (chunk_data, chunk_length) in enumerate(valid_gen):\r\n print(\"Chunk %d\" % (e + 1))\r\n xs_chunk = chunk_data\r\n\r\n # need to transpose the chunks to move the 'channels' dimension up\r\n xs_chunk = [x_chunk.transpose(0, 3, 1, 2) for x_chunk in xs_chunk]\r\n\r\n print(\" load data onto GPU\")\r\n for x_shared, x_chunk in zip(xs_shared, xs_chunk):\r\n x_shared.set_value(x_chunk)\r\n num_batches_chunk = int(np.ceil(chunk_length / float(BATCH_SIZE)))\r\n\r\n # make predictions, don't forget to cute off the zeros at the end\r\n predictions_chunk_list = []\r\n for b in range(num_batches_chunk):\r\n if b % 1000 == 0:\r\n print(\" batch %d/%d\" % (b + 1, num_batches_chunk))\r\n\r\n predictions = compute_output(b)\r\n predictions_chunk_list.append(predictions)\r\n\r\n predictions_chunk = np.vstack(predictions_chunk_list)\r\n predictions_chunk = predictions_chunk[:chunk_length] # cut off zeros / padding\r\n\r\n print(\" compute average over transforms\")\r\n predictions_chunk_avg = predictions_chunk.reshape(-1, len(augmentation_transforms), 37).mean(1)\r\n\r\n predictions_list.append(predictions_chunk_avg)\r\n\r\n time_since_start = time.time() - start_time\r\n print(\" %s since start\" % load_data.hms(time_since_start))\r\n\r\n\r\n all_predictions = np.vstack(predictions_list)\r\n\r\n print(\"Write predictions to %s\" % target_path_valid)\r\n load_data.save_gz(target_path_valid, all_predictions)\r\n\r\n print(\"Evaluate\")\r\n rmse_valid = analysis['losses_valid'][-1]\r\n rmse_augmented = np.sqrt(np.mean((y_valid - all_predictions)**2))\r\n print(\" MSE (last iteration):\\t%.6f\" % rmse_valid)\r\n print(\" MSE (augmented):\\t%.6f\" % rmse_augmented)\r\n\r\n\r\n\r\nif DO_TEST:\r\n print()\r\n print(\"TEST SET\")\r\n print(\"Compute predictions\")\r\n predictions_list = []\r\n start_time = time.time()\r\n\r\n for e, (chunk_data, chunk_length) in enumerate(test_gen):\r\n print(\"Chunk %d\" % (e + 1))\r\n xs_chunk = chunk_data\r\n\r\n # need to transpose the chunks to move the 'channels' dimension up\r\n xs_chunk = [x_chunk.transpose(0, 3, 1, 2) for x_chunk in xs_chunk]\r\n\r\n print(\" load data onto GPU\")\r\n for x_shared, x_chunk in zip(xs_shared, xs_chunk):\r\n x_shared.set_value(x_chunk)\r\n num_batches_chunk = int(np.ceil(chunk_length / float(BATCH_SIZE)))\r\n\r\n # make predictions, don't forget to cute off the zeros at the end\r\n predictions_chunk_list = []\r\n for b in range(num_batches_chunk):\r\n if b % 1000 == 0:\r\n print(\" batch %d/%d\" % (b + 1, num_batches_chunk))\r\n\r\n predictions = compute_output(b)\r\n predictions_chunk_list.append(predictions)\r\n\r\n predictions_chunk = np.vstack(predictions_chunk_list)\r\n predictions_chunk = predictions_chunk[:chunk_length] # cut off zeros / padding\r\n\r\n print(\" compute average over transforms\")\r\n predictions_chunk_avg = predictions_chunk.reshape(-1, len(augmentation_transforms), 37).mean(1)\r\n\r\n predictions_list.append(predictions_chunk_avg)\r\n\r\n time_since_start = time.time() - start_time\r\n print(\" %s since start\" % load_data.hms(time_since_start))\r\n\r\n all_predictions = np.vstack(predictions_list)\r\n\r\n\r\n print(\"Write predictions to %s\" % target_path_test)\r\n load_data.save_gz(target_path_test, all_predictions)\r\n\r\n print(\"Done!\")\r\n"
] | [
[
"sklearn.externals.joblib.load"
],
[
"numpy.load",
"numpy.mean",
"numpy.save"
],
[
"sklearn.metrics.roc_auc_score",
"pandas.read_csv",
"numpy.save",
"pandas.DataFrame",
"numpy.std",
"numpy.mean",
"numpy.load"
],
[
"pandas.read_csv",
"numpy.random.seed",
"numpy.unique",
"pandas.DataFrame",
"numpy.array",
"numpy.zeros",
"numpy.where"
],
[
"numpy.hstack",
"sklearn.preprocessing.OneHotEncoder",
"sklearn.svm.NuSVR",
"sklearn.svm.SVR",
"sklearn.linear_model.Lasso",
"sklearn.linear_model.Ridge",
"sklearn.preprocessing.MinMaxScaler",
"scipy.sparse.hstack",
"numpy.array",
"numpy.vstack"
],
[
"numpy.hstack",
"numpy.linspace",
"pandas.DataFrame",
"numpy.load",
"numpy.empty",
"sklearn.metrics.accuracy_score"
],
[
"numpy.load",
"numpy.mean"
],
[
"sklearn.externals.joblib.dump",
"numpy.min",
"numpy.percentile",
"numpy.max",
"pandas.set_option",
"pandas.read_pickle"
],
[
"scipy.optimize.fmin_l_bfgs_b",
"numpy.save",
"numpy.exp",
"numpy.load",
"numpy.array",
"numpy.zeros"
],
[
"pandas.merge",
"numpy.cos",
"pandas.read_sql"
],
[
"pandas.read_csv",
"sklearn.metrics.r2_score",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.title",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.plot",
"sklearn.linear_model.Ridge",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.xlabel",
"numpy.array",
"matplotlib.pyplot.figure"
],
[
"numpy.maximum"
],
[
"numpy.load",
"numpy.mean"
],
[
"numpy.asanyarray",
"numpy.isfinite"
],
[
"numpy.abs",
"pandas.Series",
"numpy.ones",
"numpy.mean",
"numpy.bincount",
"numpy.count_nonzero",
"numpy.floor",
"numpy.var",
"numpy.outer",
"numpy.exp",
"numpy.zeros",
"numpy.sum",
"numpy.empty"
],
[
"numpy.random.randint"
],
[
"sklearn.metrics.roc_auc_score",
"pandas.read_csv",
"numpy.random.seed",
"numpy.unique",
"pandas.DataFrame",
"sklearn.preprocessing.StandardScaler",
"numpy.array",
"sklearn.preprocessing.LabelEncoder",
"numpy.where"
],
[
"pandas.read_csv",
"pandas.DataFrame"
],
[
"sklearn.linear_model.LogisticRegression",
"sklearn.grid_search.GridSearchCV",
"pandas.read_json",
"sklearn.svm.LinearSVC",
"sklearn.feature_extraction.text.TfidfVectorizer"
],
[
"numpy.matlib.repmat",
"numpy.random.randn",
"numpy.random.rand",
"numpy.random.randint"
],
[
"pandas.concat",
"pandas.read_csv",
"sklearn.metrics.roc_curve",
"numpy.concatenate",
"numpy.mean",
"sklearn.metrics.auc",
"numpy.array"
],
[
"pandas.read_pickle"
],
[
"sklearn.preprocessing.LabelEncoder",
"pandas.read_csv",
"pandas.Series"
],
[
"pandas.concat",
"pandas.Timedelta",
"pandas.DataFrame.from_dict"
],
[
"numpy.zeros",
"numpy.sqrt",
"numpy.float32",
"numpy.ones"
],
[
"sklearn.feature_extraction.text.TfidfTransformer",
"pandas.concat",
"pandas.read_csv"
],
[
"numpy.arange",
"numpy.array"
],
[
"numpy.asarray",
"numpy.load",
"numpy.nan_to_num"
],
[
"numpy.zeros",
"numpy.ones"
],
[
"matplotlib.pylab.yticks",
"sklearn.ensemble.RandomForestClassifier",
"sklearn.metrics.log_loss",
"matplotlib.pylab.xticks",
"matplotlib.pylab.figure",
"matplotlib.pylab.clf"
],
[
"numpy.dot",
"numpy.sqrt",
"numpy.array_equal",
"numpy.asarray",
"numpy.reshape",
"numpy.mod",
"numpy.ones",
"numpy.mean",
"numpy.transpose",
"numpy.var",
"numpy.zeros",
"numpy.sum",
"numpy.vstack"
],
[
"numpy.dot",
"numpy.multiply",
"numpy.isnan",
"numpy.cos",
"numpy.sin",
"numpy.array"
],
[
"numpy.square",
"numpy.linspace",
"scipy.fftpack.fft",
"numpy.sum",
"numpy.empty"
],
[
"pandas.concat",
"pandas.read_csv",
"sklearn.cross_validation.StratifiedKFold",
"numpy.random.seed",
"numpy.linspace",
"numpy.random.shuffle",
"pandas.DataFrame",
"numpy.append",
"sklearn.preprocessing.StandardScaler",
"sklearn.preprocessing.LabelEncoder",
"numpy.empty"
],
[
"matplotlib.use",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.close",
"pandas.read_pickle",
"pandas.qcut"
],
[
"sklearn.externals.joblib.dump",
"sklearn.cross_validation.StratifiedKFold",
"sklearn.ensemble.RandomForestClassifier",
"pandas.Series",
"sklearn.ensemble.ExtraTreesClassifier",
"numpy.mean",
"pandas.cut",
"sklearn.metrics.average_precision_score",
"sklearn.ensemble.GradientBoostingClassifier",
"pandas.read_pickle",
"pandas.get_dummies"
],
[
"numpy.isfinite",
"numpy.min",
"numpy.concatenate",
"numpy.max",
"numpy.mean",
"numpy.vstack"
],
[
"numpy.maximum"
],
[
"numpy.linspace",
"numpy.arange",
"numpy.mean",
"numpy.load",
"numpy.zeros",
"numpy.vstack"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"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.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
},
{
"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": [
"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": [],
"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": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"1.6",
"0.14",
"1.10",
"0.15",
"1.4",
"0.16",
"1.9",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"0.17",
"1.3",
"1.8"
],
"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": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"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": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"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.3",
"1.1",
"1.5",
"1.2"
],
"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": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"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": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"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": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"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": [
"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": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"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": []
},
{
"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": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
tacox5/elastic_pendulum | [
"c2058444ca161a420466b531b008fe247a87db60"
] | [
"pyelastic/pendulum.py"
] | [
"import os\nimport glob\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\nfrom scipy.interpolate import interp1d\nfrom .settings import *\n\n\nclass ElasticPendulum:\n \"\"\"Class that handles the simulation of springy, double pendulums. This class\n handles a number of initial conditions from starting angle to pendulum mass\"\"\"\n\n def __init__(self, **kwargs):\n \"\"\"Animate\n\n Args:\n alpha_0 : float\n Inital angle of the top pendulum in radians\n beta_0 : float\n Inital angle of the bottom pendulum in radians\n alpha_1 : float, default=True\n Inital angular velocity of the top pendulum in radians\n beta_1 : float, default=True\n Inital angular velocity of the top pendulum in radians\n k1 : boolean, default=True\n Spring constant of the top pendulum in arbitrary units\n k2 : boolean, default=True\n Spring constant of the top pendulum in arbitrary units\n l1 : boolean, default=True\n Length of the top pendulum in arbitrary units\n l2 : boolean, default=True\n Length of the bottom pendulum in arbitrary units\n m1 : float, default=1.0\n Mass of the top pendulum in arbitrary units\n m2 : float, default=1.0\n Mass of the bottom pendulum in arbitrary units\n a0 : boolean, default=True\n b0 : boolean, default=True\n a1 : boolean, default=True\n b1 : boolean, default=True\n t_end : float, default=2\n Length of the simulation in seconds\n fps : int, default=24\n Frame rate of the video simulation. Sets the resolution of the integrator\n and helps to visualize the results later\n \"\"\"\n prop_defaults = {\n \"alpha_0\": np.random.uniform(-np.pi, np.pi),\n \"beta_0\": np.random.uniform(-np.pi, np.pi),\n \"alpha_1\": 0.0,\n \"beta_1\": 0.0,\n \"k1\": np.random.uniform(35, 55),\n \"k2\": np.random.uniform(35, 55),\n \"l1\": 1.0,\n \"l2\": 1.0,\n \"m1\": 1.0,\n \"m2\": 1.0,\n \"a0\": 1.0,\n \"b0\": 1.0,\n \"a1\": 1.0,\n \"b1\": 1.0,\n \"t_end\": 2,\n \"fps\": 24,\n \"g\": GRAVITY,\n }\n\n for (prop, default) in prop_defaults.items():\n setattr(self, prop, kwargs.get(prop, default))\n\n self.dt = 1.0 / self.fps\n self.t_eval = np.arange(0, self.t_end, self.dt)\n\n def _spherical_to_cartesian(self, array, interpolate=True):\n \"\"\"Transforms from 2D spherical coordinate system to a cartesian coordinate system\n\n Args:\n array : np.ndarray\n Output array from integration function in spherical coordinates\n\n interpolate : boolean, default=True\n\n\n Returns:\n None\n \"\"\"\n x1 = array[:, 2] * np.sin(array[:, 0])\n x2 = x1 + array[:, 3] * np.sin(array[:, 1])\n y1 = -array[:, 2] * np.cos(array[:, 0])\n y2 = y1 - array[:, 3] * np.cos(array[:, 1])\n\n if interpolate:\n self.fx1 = interp1d(np.arange(0, x1.shape[0]), x1)\n self.fy1 = interp1d(np.arange(0, x1.shape[0]), y1)\n self.fx2 = interp1d(np.arange(0, x1.shape[0]), x2)\n self.fy2 = interp1d(np.arange(0, x1.shape[0]), y2)\n\n return x1, x2, y1, y2\n\n def _alpha_pp(self, t, Y):\n \"\"\" \"\"\"\n alpha_0, alpha_1, beta_0, beta_1, a0, a1, b0, _ = Y\n return -(\n self.g * self.m1 * np.sin(alpha_0)\n - self.k2 * self.l2 * np.sin(alpha_0 - beta_0)\n + self.k2 * b0 * np.sin(alpha_0 - beta_0)\n + 2 * self.m1 * a1 * alpha_1\n ) / (self.m1 * a0)\n\n def _beta_pp(self, t, Y):\n \"\"\" \"\"\"\n alpha_0, alpha_1, beta_0, beta_1, a0, a1, b0, b1 = Y\n return (\n -self.k1 * self.l1 * np.sin(alpha_0 - beta_0)\n + self.k1 * a0 * np.sin(alpha_0 - beta_0)\n - 2.0 * self.m1 * b1 * beta_1\n ) / (self.m1 * b0)\n\n def _a_pp(self, t, Y):\n \"\"\" \"\"\"\n alpha_0, alpha_1, beta_0, beta_1, a0, a1, b0, b1 = Y\n return (\n self.k1 * self.l1\n + self.g * self.m1 * np.cos(alpha_0)\n - self.k2 * self.l2 * np.cos(alpha_0 - beta_0)\n + self.k2 * b0 * np.cos(alpha_0 - beta_0)\n + a0 * (-self.k1 + self.m1 * alpha_1 ** 2)\n ) / self.m1\n\n def _b_pp(self, t, Y):\n \"\"\" \"\"\"\n alpha_0, alpha_1, beta_0, beta_1, a0, a1, b0, b1 = Y\n return (\n self.k2 * self.l2 * self.m1\n + self.k2 * self.l2 * self.m2 * np.cos(alpha_0 - beta_0)\n + self.k1 * self.m2 * a0 * np.cos(alpha_0 - beta_0)\n - b0 * (self.k2 * (self.m1 + self.m2) - self.m1 * self.m2 * beta_1 ** 2)\n ) / (self.m1 * self.m2)\n\n def _lagrangian(self, t, Y):\n \"\"\"Set of differential equations to integrate to solve the equations of motion\n for the pendulum masses. Incorporates\n\n Args:\n t : np.ndarray\n Evaluation time array\n Y : np.ndarray\n Initial conditions of the pendulum masses\n Returns:\n list :\n Evaluation of the differential equations\n \"\"\"\n return [\n Y[1],\n self._alpha_pp(t, Y),\n Y[3],\n self._beta_pp(t, Y),\n Y[5],\n self._a_pp(t, Y),\n Y[7],\n self._b_pp(t, Y),\n ]\n\n def integrate(self, method=\"LSODA\", interpolate=True):\n \"\"\"Main\n\n Args:\n method : str, default=LSODA\n Integrator type to integrate the set of differential equations. Options\n are: RK45, RK23, DOP853, Radu, BDF, and LSODA. For more information, see\n scipy.integrate.solve_ivp documentation\n interpolate : boolean, default=True\n Whether to interpolate the final results. Useful for animation\n\n Returns:\n None\n \"\"\"\n Y0 = [\n self.alpha_0,\n self.alpha_1,\n self.beta_0,\n self.beta_1,\n self.a0,\n self.a1,\n self.b0,\n self.b1,\n ]\n self.solution = solve_ivp(\n self._lagrangian, [0, self.t_end], Y0, t_eval=self.t_eval, method=method\n )\n self.x1, self.x2, self.y1, self.y2 = self._spherical_to_cartesian(\n self.solution.y[[0, 2, 4, 6]].T, interpolate=interpolate\n )\n"
] | [
[
"numpy.arange",
"scipy.integrate.solve_ivp",
"numpy.cos",
"numpy.sin",
"numpy.random.uniform"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.6",
"1.10",
"1.4",
"1.9",
"1.5",
"1.2",
"1.7",
"1.0",
"1.3",
"1.8"
],
"tensorflow": []
}
] |
Mark-Kinyua/python_public | [
"25c4eff3a6f93c35a949f94a2f9c3df3202a3113",
"25c4eff3a6f93c35a949f94a2f9c3df3202a3113"
] | [
"motion_detector/main.py",
"ai_class_work/nairobi_roadNetwork/NairobiRoadNetwork.py"
] | [
"import numpy as np\nimport cv2\n\n# A motion detecetor, yup... lol.\n# Remember to use an old python version < 3.6\n\n\nimage_path = 'room_people.jpg' # Photo\n\n# The model was already formulated, just need to loaad it into the system.\n\nprototxt_path = 'models/MobileNetSSD_deploy.prototxt' # Load Model\nmodel_path = 'models/MobileNetSSD_deploy.caffemodel'\nmin_confidence = 0.2\n\n# Things it can identify\nclasses = [\"background\",\"aeroplane\",\"bicycle\",\"bird\",\"boat\",\"bottle\",\"bus\",\"car\",\"cat\",\"chair\",\"cow\",\"diningtable\",\"dog\",\"horse\",\n \"motorbike\",\"person\",\"pottedplant\",\"sheep\",\"sofa\",\"train\",\"tvmonitor\"]\n\nnp.random.seed(543210) # Same Colors\ncolors = np.random.uniform(0, 255, size=(len(classes), 3))\n\nnet = cv2.dnn.readNetFromCaffe(prototxt_path, model_path)\n\n# img = cv2.imread(image_path)\n\ncap = cv2.VideoCapture(0)\n\nwhile True:\n\n _, img = cap.read()\n\n height, width = img.shape[0], img.shape[1]\n\n blob = cv2.dnn.blobFromImage(cv2.resize(img, (300, 300)), 0.007, (300,300), 130)\n\n net.setInput(blob)\n\n detected_objects = net.forward()\n\n for i in range(detected_objects.shape[2]):\n\n confidence = detected_objects[0][0][i][2]\n\n if confidence > min_confidence:\n class_index = int(detected_objects[0,0,i,1])\n\n upper_left_x = int(detected_objects[0, 0, i, 3] * width)\n upper_left_y = int(detected_objects[0, 0, i, 3] * height)\n lower_right_x = int(detected_objects[0, 0, i, 5] * width)\n lower_right_y = int(detected_objects[0, 0, i, 6] * height)\n\n prediction_text = f\"{classes[class_index]}: {confidence:.2f}%\"\n cv2.rectangle(img, (upper_left_x, upper_left_y), (lower_right_x, lower_right_y), colors[class_index], 3)\n cv2.putText(img, prediction_text, (upper_left_x,\n upper_left_y- 15 if upper_left_y > 30 else upper_left_y + 15),\n cv2.FONT_HERSHEY_SIMPLEX, 0.6, colors[class_index], 2)\n\n cv2.imshow(\"Detected Objects\", img)\n cv2.waitKey(5)\n\ncv2.destroyAllWindows()\ncap.release()\n",
"import networkx as nx\r\nimport matplotlib.pyplot as plt\r\nfrom classes.bfs import BfsTraverser\r\n\r\nG = nx.Graph()\r\nnodes = [\"Karen\", \"J6\", \"Gitaru\", \"J1\", \"J4\", \"J7\"]\r\nG.add_nodes_from(nodes)\r\nG.nodes() # confirm nodes\r\n\r\n# Add Edges and their weights\r\nG.add_edge(\"Karen\", \"J1\", weight=\"2.8\")\r\nG.add_edge(\"Karen\", \"J6\", weight=\"4\")\r\nG.add_edge(\"J1\", \"J4\", weight=\"2.6\")\r\nG.add_edge(\"J6\", \"Gitaru\", weight=\"10\")\r\nG.add_edge(\"J6\", \"J7\", weight=\"6\")\r\nG.add_edge(\"J6\", \"J4\", weight=\"6\")\r\nG.add_edge(\"Gitaru\", \"J7\", weight=\"6\")\r\n\r\n# position the nodes to resemble Nairobis map\r\nG.nodes[\"Karen\"]['pos'] = (0, 0)\r\nG.nodes[\"J6\"]['pos'] = (0, 2)\r\nG.nodes[\"J1\"]['pos'] = (2, -2)\r\nG.nodes[\"J4\"]['pos'] = (4, -2)\r\nG.nodes[\"J7\"]['pos'] = (0, 4)\r\nG.nodes[\"Gitaru\"]['pos'] = (-1, 3)\r\n\r\n# store all positions in a variable\r\nnode_pos = nx.get_node_attributes(G, 'pos')\r\n\r\n# call BFS to return set of all possible routes to the goal\r\nroute_bfs = BfsTraverser()\r\nroutes = route_bfs.BFS(G, \"Karen\", \"Gitaru\")\r\nprint(route_bfs.visited)\r\nroute_list = route_bfs.visited\r\n\r\n# color the nodes in the route_bfs\r\nnode_col = ['darkturquoise' if not node in route_list else 'peru' for node in G.nodes()]\r\nperu_colored_edges = list(zip(route_list, route_list[1:]))\r\n# color the edges as well\r\n\r\n# print(peru_colored_edges)\r\nedge_col = ['darkturquoise' if not edge in peru_colored_edges else 'peru' for edge in G.edges()]\r\narc_weight = nx.get_edge_attributes(G, 'weight')\r\nnx.draw_networkx(G, node_pos, node_color=node_col, node_size=450)\r\nnx.draw_networkx_edges(G, node_pos, width=2, edge_color=edge_col)\r\n# nx.draw_networkx_edge_labels(G, node_pos,edge_color= edge_col, edge_labels=arc_weight)\r\nnx.draw_networkx_edge_labels(G, node_pos, edge_labels=arc_weight)\r\nplt.axis('off')\r\nplt.show()\r\n"
] | [
[
"numpy.random.seed"
],
[
"matplotlib.pyplot.show",
"matplotlib.pyplot.axis"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
demetoir/MLtools | [
"8c42fcd4cc71728333d9c116ade639fe57d50d37",
"8c42fcd4cc71728333d9c116ade639fe57d50d37",
"8c42fcd4cc71728333d9c116ade639fe57d50d37",
"8c42fcd4cc71728333d9c116ade639fe57d50d37"
] | [
"script/sklearn_like_toolkit/warpper/skClf_wrapper/skMultinomial_NBClf.py",
"script/sklearn_like_toolkit/warpper/skReg_wrapper/skARDReg.py",
"script/workbench/experiment_code.py",
"script/sklearn_like_toolkit/warpper/skReg_wrapper/skTheilSenReg.py"
] | [
"from hyperopt import hp\r\nfrom sklearn.naive_bayes import MultinomialNB as _skMultinomialNB\r\n\r\nfrom script.sklearn_like_toolkit.warpper.base.BaseWrapperClf import BaseWrapperClf\r\nfrom script.sklearn_like_toolkit.warpper.base.MixIn import MetaBaseWrapperClfWithABC\r\n\r\n\r\nclass skMultinomial_NBClf(BaseWrapperClf, _skMultinomialNB, metaclass=MetaBaseWrapperClfWithABC):\r\n def __init__(self, alpha=1.0, fit_prior=True, class_prior=None):\r\n _skMultinomialNB.__init__(self, alpha, fit_prior, class_prior)\r\n BaseWrapperClf.__init__(self)\r\n\r\n HyperOpt_space = {\r\n 'alpha': hp.loguniform('alpha', -8, 1),\r\n }\r\n\r\n tuning_grid = {\r\n 'alpha': [0.00001, 0.0001, 0.001, 0.01, 0.1, 1.0, 10.0],\r\n # 'class_prior': None,\r\n # 'fit_prior': True\r\n }\r\n",
"from hyperopt import hp\r\nfrom sklearn.linear_model import ARDRegression as _ARDRegression\r\n\r\nfrom script.sklearn_like_toolkit.warpper.base.BaseWrapperReg import BaseWrapperReg\r\nfrom script.sklearn_like_toolkit.warpper.base.MixIn import MetaBaseWrapperRegWithABC\r\n\r\n\r\nclass skARDReg(_ARDRegression, BaseWrapperReg, metaclass=MetaBaseWrapperRegWithABC):\r\n\r\n def __init__(self, n_iter=300, tol=1.e-3, alpha_1=1.e-6, alpha_2=1.e-6, lambda_1=1.e-6, lambda_2=1.e-6,\r\n compute_score=False, threshold_lambda=1.e+4, fit_intercept=True, normalize=False, copy_X=True,\r\n verbose=False):\r\n _ARDRegression.__init__(\r\n self, n_iter, tol, alpha_1, alpha_2, lambda_1, lambda_2, compute_score, threshold_lambda,\r\n fit_intercept, normalize, copy_X, verbose)\r\n BaseWrapperReg.__init__(self)\r\n\r\n HyperOpt_space = {\r\n 'n_iter': 10 + hp.randint('n_iter', 500),\r\n 'tol': hp.loguniform('tol', -8, 0),\r\n 'alpha_1': hp.loguniform('alpha_1', -8, 0),\r\n 'alpha_2': hp.loguniform('alpha_2', -8, 0),\r\n 'lambda_1': hp.loguniform('lambda_1', -8, 0),\r\n 'lambda_2': hp.loguniform('lambda_2', -8, 0),\r\n 'threshold_lambda': hp.loguniform('threshold_lambda', 1, 7),\r\n }\r\n\r\n tuning_grid = {\r\n 'n_iter': 300,\r\n 'tol': 1.e-3,\r\n 'alpha_1': 1.e-6,\r\n 'alpha_2': 1.e-6,\r\n 'lambda_1': 1.e-6,\r\n 'lambda_2': 1.e-6,\r\n 'compute_score': False,\r\n 'threshold_lambda': 1.e+4,\r\n 'fit_intercept': True,\r\n 'normalize': False,\r\n 'copy_X': True,\r\n 'verbose': False,\r\n }\r\n",
"# -*- coding:utf-8 -*-\r\n\r\n\r\nimport os\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom catboost import CatBoostRegressor\r\nfrom lightgbm import LGBMRegressor\r\nfrom sklearn.decomposition import PCA\r\nfrom sklearn.neural_network.multilayer_perceptron import MLPRegressor\r\nfrom script.data_handler.DatasetPackLoader import DatasetPackLoader\r\nfrom script.data_handler.DummyDataset import DummyDataset\r\nfrom script.data_handler.HousePrices import HousePricesHelper\r\nfrom script.data_handler.wine_quality import wine_qualityPack\r\nfrom script.model.sklearn_like_model.AE.CVAE import CVAE, CVAE_MixIn\r\nfrom script.model.sklearn_like_model.GAN.C_GAN import C_GAN\r\nfrom script.sklearn_like_toolkit.ClassifierPack import ClassifierPack\r\nfrom script.sklearn_like_toolkit.EnsembleClfPack import EnsembleClfPack\r\nfrom script.sklearn_like_toolkit.FoldingHardVoteClf import FoldingHardVoteClf\r\nfrom script.sklearn_like_toolkit.warpper.mlxtend_wrapper import mlxStackingCVClf, mlxStackingClf\r\nfrom script.util.Logger import StdoutOnlyLogger, pprint_logger\r\nfrom script.util.PlotTools import PlotTools\r\nfrom script.util.deco import deco_timeit, deco_save_log\r\nfrom script.util.misc_util import path_join\r\nfrom script.util.numpy_utils import np_stat_dict, np_minmax_normalize\r\n########################################################################################################################\r\n# print(built-in function) is not good for logging\r\nfrom script.util.pandas_util import df_to_onehot_embedding, df_to_np_onehot_embedding\r\nfrom unit_test.data_handler.test_wine_quality import load_wine_quality_dataset\r\nfrom unit_test.model.sklearn_like_model.GAN.test_GAN import to_zero_one_encoding\r\nfrom script.model.sklearn_like_model.BaseModel import BaseModel\r\nfrom script.util.Stacker import Stacker\r\nfrom script.util.tensor_ops import *\r\nfrom tqdm import trange\r\nimport tensorflow as tf\r\n\r\nNpArr = np.array\r\n\r\nbprint = print\r\nlogger = StdoutOnlyLogger()\r\n# noinspection PyShadowingBuiltins\r\nprint = logger.get_log()\r\npprint = pprint_logger(print)\r\n\r\n\r\n#######################################################################################################################\r\n@deco_timeit\r\n@deco_save_log\r\ndef exp_stacking_metaclf(print, pprint):\r\n dataset = DatasetPackLoader().load_dataset(\"titanic\")\r\n train_set, valid_set = dataset.split('train', 'train', 'valid', (7, 3))\r\n train_Xs, train_Ys = train_set.full_batch(['Xs', 'Ys'])\r\n valid_Xs, valid_Ys = valid_set.full_batch(['Xs', 'Ys'])\r\n\r\n clf = ClassifierPack()\r\n clf.drop('mlxMLP')\r\n clf.drop('mlxAdaline')\r\n clf.drop('mlxSoftmaxRegressionClf')\r\n clf.drop('skGaussian_NB')\r\n clf.drop('skQDA')\r\n\r\n pack = clf.pack\r\n for key, meta_clf in pack.items():\r\n if 'mlx' in key:\r\n continue\r\n\r\n pprint(f'meta clf = {key}')\r\n stacking = clf.to_stackingClf(meta_clf)\r\n stacking.fit(train_Xs, train_Ys)\r\n score = stacking.score(valid_Xs, valid_Ys)\r\n pprint(f'score {score}')\r\n # break\r\n\r\n\r\n@deco_timeit\r\n@deco_save_log\r\ndef exp_stackingCV_metaclf(pprint):\r\n dataset = DatasetPackLoader().load_dataset(\"titanic\")\r\n train_set, valid_set = dataset.split('train', 'train', 'valid', (7, 3))\r\n train_Xs, train_Ys = train_set.full_batch(['Xs', 'Ys'])\r\n valid_Xs, valid_Ys = valid_set.full_batch(['Xs', 'Ys'])\r\n\r\n clf = ClassifierPack()\r\n clf.drop('mlxMLP')\r\n clf.drop('mlxAdaline')\r\n clf.drop('mlxSoftmaxRegressionClf')\r\n clf.drop('skGaussian_NB')\r\n clf.drop('skQDA')\r\n\r\n pack = clf.pack\r\n for key, meta_clf in pack.items():\r\n if 'mlx' in key:\r\n continue\r\n\r\n pprint(f'meta clf = {key}')\r\n stacking = clf.to_stackingCVClf(meta_clf)\r\n stacking.fit(train_Xs, train_Ys)\r\n score = stacking.score_pack(valid_Xs, valid_Ys)\r\n pprint(f'score {score}')\r\n # break\r\n\r\n\r\n@deco_timeit\r\n@deco_save_log\r\ndef exp_titanic_statistic(print, pprint):\r\n dataset = DatasetPackLoader().load_dataset(\"titanic\")\r\n train_set, valid_set = dataset.split('train', 'train', 'valid', (7, 3))\r\n train_Xs, train_Ys = train_set.full_batch(['Xs', 'Ys'])\r\n valid_Xs, valid_Ys = valid_set.full_batch(['Xs', 'Ys'])\r\n\r\n clf_pack = ClassifierPack()\r\n clf_pack.drop('mlxMLP')\r\n clf_pack.drop('mlxAdaline')\r\n clf_pack.drop('mlxSoftmaxRegressionClf')\r\n clf_pack.drop('skGaussian_NB')\r\n clf_pack.drop('skQDA')\r\n\r\n pack = clf_pack.pack\r\n pprint(f'pack list {pack}')\r\n meta_clf = pack['skBernoulli_NB']\r\n pprint(f'metaclf = {meta_clf}')\r\n\r\n clf_pack.fit(train_Xs, train_Ys)\r\n score_pack = clf_pack.score_pack(valid_Xs, valid_Ys)\r\n pprint('default param clf pack')\r\n pprint(score_pack)\r\n\r\n clf_pack.param_search(train_Xs, train_Ys)\r\n score_pack = clf_pack.score_pack(valid_Xs, valid_Ys)\r\n pprint('optimize param clf pack top1')\r\n pprint(score_pack)\r\n\r\n pack = [clf for k, clf in clf_pack.pack.items() if hasattr(clf, 'get_params')]\r\n pack1_default = pack\r\n pack10_default = pack * 10\r\n pack100_default_ = pack * 100\r\n\r\n pack1_top1 = clf_pack.clone_top_k_tuned(k=1)\r\n pack1_top1 = [clf for k, clf in pack1_top1.items() if hasattr(clf, 'get_params')]\r\n pack10_top1 = pack1_top1 * 10\r\n pack100_top1 = pack1_top1 * 100\r\n\r\n pack1_top5 = clf_pack.clone_top_k_tuned(k=5)\r\n pack1_top5 = [clf for k, clf in pack1_top5.items() if hasattr(clf, 'get_params')]\r\n pack10_top5 = pack1_top5 * 10\r\n pack100_top5 = pack1_top5 * 100\r\n\r\n def voting_stacking_stackingCV(pack, param_type, pack_n, top):\r\n pprint(f'param_type={param_type}, pack_n={pack_n}, top={top}')\r\n\r\n voting = FoldingHardVoteClf(pack)\r\n voting.fit(train_Xs, train_Ys)\r\n score_pack = voting.score_pack(valid_Xs, valid_Ys)\r\n pprint(f'{param_type} param clf pack * {pack_n}, {top} to hard voting')\r\n pprint(score_pack)\r\n\r\n stacking = mlxStackingClf(pack, meta_clf)\r\n stacking.fit(train_Xs, train_Ys)\r\n score_pack = stacking.score_pack(valid_Xs, valid_Ys)\r\n pprint(f'{param_type} param clf pack * {pack_n}, {top} to stacking')\r\n pprint(score_pack)\r\n\r\n stackingCV = mlxStackingCVClf(pack, meta_clf)\r\n stackingCV.fit(train_Xs, train_Xs)\r\n score_pack = stackingCV.score_pack(valid_Xs, valid_Ys)\r\n pprint(f'{param_type} param clf pack * {pack_n}, {top} to stackingCV')\r\n pprint(score_pack)\r\n\r\n voting_stacking_stackingCV(pack1_default, 'default', 1, None)\r\n voting_stacking_stackingCV(pack10_default, 'default', 10, None)\r\n voting_stacking_stackingCV(pack100_default_, 'default', 100, None)\r\n voting_stacking_stackingCV(pack1_top1, 'optimize', 1, 'top1')\r\n voting_stacking_stackingCV(pack10_top1, 'optimize', 10, 'top1')\r\n voting_stacking_stackingCV(pack100_top1, 'optimize', 100, 'top1')\r\n voting_stacking_stackingCV(pack1_top5, 'optimize', 1, 'top5')\r\n voting_stacking_stackingCV(pack10_top5, 'optimize', 10, 'top5')\r\n voting_stacking_stackingCV(pack100_top5, 'optimize', 100, 'top5')\r\n\r\n\r\n@deco_timeit\r\n@deco_save_log\r\ndef exp_titanic_id_static(print, pprint):\r\n dataset = DatasetPackLoader().load_dataset(\"titanic\")\r\n dataset = dataset.set['train']\r\n\r\n ret_dict = {}\r\n n = 100\r\n for i in range(n):\r\n clf_pack = ClassifierPack()\r\n dataset.shuffle()\r\n train_set, valid_set = dataset.split((7, 3))\r\n train_Xs, train_Ys = train_set.full_batch(['Xs', 'Ys'])\r\n clf_pack.fit(train_Xs, train_Ys)\r\n\r\n dataset.sort()\r\n full_Xs, full_Ys = dataset.full_batch(['Xs', 'Ys'])\r\n predict = clf_pack.predict(full_Xs)\r\n\r\n for key in predict:\r\n if key in ret_dict:\r\n ret_dict[key] += predict[key] / float(n)\r\n else:\r\n ret_dict[key] = predict[key] / float(n)\r\n\r\n import pandas as pd\r\n\r\n df = pd.DataFrame()\r\n for key in ret_dict:\r\n df[key] = ret_dict[key]\r\n for key in dataset.BATCH_KEYS:\r\n if key in ['Xs', 'Ys']:\r\n continue\r\n print(key, type(key))\r\n df[key] = dataset.full_batch([key])\r\n\r\n df.to_csv('./exp_titianic_id_result.csv', )\r\n\r\n\r\ndef print_score_statistic(clf, scores):\r\n stat = np_stat_dict(scores)\r\n pprint(f\"\"\"{clf}, {stat}\"\"\")\r\n\r\n\r\ndef exp_model_confidence():\r\n data_pack = DatasetPackLoader().load_dataset(\"titanic\")\r\n # data_pack.shuffle()\r\n train_dataset = data_pack.set['train']\r\n train_dataset.sort()\r\n full_Xs, full_Ys = train_dataset.full_batch(['Xs', 'Ys'])\r\n\r\n train_set, valid_set = train_dataset.split((7, 3))\r\n train_Xs, train_Ys = train_set.full_batch(['Xs', 'Ys'])\r\n valid_Xs, valid_Ys = valid_set.full_batch(['Xs', 'Ys'])\r\n\r\n dump_path = path_join('.', 'sklearn_pkl_dump')\r\n clf_pack_path = path_join(dump_path, ClassifierPack.__name__ + '.pkl')\r\n esm_pack_path = path_join(dump_path, EnsembleClfPack.__name__ + '.pkl')\r\n\r\n if not os.path.exists(clf_pack_path):\r\n clf_pack = ClassifierPack()\r\n clf_pack.param_search(train_Xs, train_Ys)\r\n clf_pack.dump(clf_pack_path)\r\n\r\n clf_pack = ClassifierPack().load(clf_pack_path)\r\n clf_pack.drop('mlxAdaline')\r\n clf_pack.drop('mlxLogisticRegression')\r\n clf_pack.drop('skGaussian_NB')\r\n clf_pack.drop('mlxMLP')\r\n clf_pack.drop('skQDA')\r\n\r\n esm_pack = clf_pack.to_ensembleClfpack()\r\n esm_pack.fit(train_Xs, train_Ys)\r\n\r\n train_dataset.sort()\r\n full_Xs, full_Ys = train_dataset.full_batch(['Xs', 'Ys'])\r\n\r\n confidence_result_path = 'confidence_result.csv'\r\n df = pd.DataFrame()\r\n\r\n for key, val in esm_pack.predict_confidence(full_Xs).items():\r\n df[key] = val\r\n pprint(df.head(5))\r\n\r\n difficulty_path = './titanic_difficulty_stat.csv'\r\n difficulty_stat_df = pd.DataFrame().from_csv(difficulty_path)\r\n survived = difficulty_stat_df[['Survived']]\r\n difficulty_df = difficulty_stat_df[['total_difficulty']]\r\n df = pd.concat([df, difficulty_df, survived], axis=1)\r\n\r\n for key, predict in esm_pack.predict(full_Xs).items():\r\n if 'Vote' in key:\r\n df[key + '_score'] = np.equal(predict, survived['Survived']).astype(int)\r\n\r\n score = esm_pack.score_pack(full_Xs, full_Ys)\r\n pprint(score)\r\n\r\n # pprint(df.head(5))\r\n\r\n df.to_csv(confidence_result_path)\r\n\r\n\r\ndef exp_titanic_data_difficulty():\r\n data_pack = DatasetPackLoader().load_dataset(\"titanic\")\r\n train_dataset = data_pack.set['train']\r\n train_dataset.shuffle()\r\n train_set, valid_set = train_dataset.split((7, 3))\r\n train_Xs, train_Ys = train_set.full_batch(['Xs', 'Ys'])\r\n\r\n dump_path = path_join('.', 'sklearn_pkl_dump')\r\n clf_pack_path = path_join(dump_path, ClassifierPack.__name__ + '.pkl')\r\n if not os.path.exists(clf_pack_path):\r\n train_dataset.shuffle()\r\n train_set, valid_set = train_dataset.split((7, 3))\r\n train_Xs, train_Ys = train_set.full_batch(['Xs', 'Ys'])\r\n\r\n clf_pack = ClassifierPack()\r\n clf_pack.param_search(train_Xs, train_Ys)\r\n clf_pack.dump(clf_pack_path)\r\n\r\n clf_pack = ClassifierPack().load(clf_pack_path)\r\n clf_pack.drop('mlxAdaline')\r\n clf_pack.drop('mlxLogisticRegression')\r\n clf_pack.drop('skGaussian_NB')\r\n clf_pack.drop('mlxMLP')\r\n clf_pack.drop('skQDA')\r\n\r\n def difficulty_stat(pack, dataset, n=100):\r\n dataset.sort()\r\n full_Xs, full_Ys = dataset.full_batch(['Xs', 'Ys'])\r\n\r\n ret = {}\r\n for clf_key, clf in pack.pack.items():\r\n print(clf_key)\r\n predicts = []\r\n for _ in trange(n):\r\n dataset.shuffle()\r\n train_set, valid_set = dataset.split((7, 3))\r\n train_Xs, train_Ys = train_set.full_batch(['Xs', 'Ys'])\r\n\r\n clf.fit(train_Xs, train_Ys)\r\n predict = clf.predict(full_Xs)\r\n predicts += [predict]\r\n\r\n predicts = np.array(predicts)\r\n predicts = predicts.transpose()\r\n\r\n stat_dicts = {\r\n 'mean': [],\r\n 'std': []\r\n }\r\n for idx, predict in enumerate(predicts):\r\n row_stat = np_stat_dict(predict)\r\n for key in stat_dicts:\r\n stat_dicts[key] += [row_stat[key]]\r\n\r\n for key in stat_dicts:\r\n ret[f'{clf_key}_{key}'] = stat_dicts[key]\r\n\r\n # pprint(ret.keys())\r\n # for key in ret:\r\n # pprint(key, ret[key][:3], len(ret[key]))\r\n\r\n return ret\r\n\r\n result_path = './titanic_difficulty_stat.csv'\r\n if not os.path.exists(result_path):\r\n esm_pack = clf_pack.to_ensembleClfpack()\r\n esm_pack.fit(train_Xs, train_Ys)\r\n\r\n pack_dict = difficulty_stat(clf_pack, train_dataset, n=100)\r\n clf_pack_result_df = pd.DataFrame(pack_dict)\r\n esm_pack_dict = difficulty_stat(esm_pack, train_dataset, n=100)\r\n esm_pack_dict_df = pd.DataFrame(esm_pack_dict)\r\n\r\n train_dataset.sort()\r\n ground_true_df = train_dataset.to_DataFrame(['Survived'])\r\n\r\n result_df = pd.concat([ground_true_df, clf_pack_result_df, esm_pack_dict_df], axis=1)\r\n result_df.to_csv('./titanic_difficulty_stat.csv')\r\n\r\n df = pd.DataFrame.from_csv(result_path)\r\n\r\n # pprint(list(df.keys()))\r\n pprint(df.head(5))\r\n for key in df:\r\n if 'min' in key or 'max' in key:\r\n df = df.drop(columns=[key])\r\n df.to_csv(result_path)\r\n\r\n keys = [\r\n 'skMLP_mean',\r\n 'skMLP_std',\r\n 'skSGD_mean',\r\n 'skSGD_std',\r\n 'skBernoulli_NB_mean',\r\n 'skBernoulli_NB_std',\r\n 'skMultinomial_NB_mean',\r\n 'skMultinomial_NB_std',\r\n 'skDecisionTree_mean',\r\n 'skDecisionTree_std',\r\n 'skRandomForest_mean',\r\n 'skRandomForest_std',\r\n 'skExtraTrees_mean',\r\n 'skExtraTrees_std',\r\n 'skAdaBoost_mean',\r\n 'skAdaBoost_std',\r\n 'skGradientBoosting_mean',\r\n 'skGradientBoosting_std',\r\n 'skKNeighbors_mean',\r\n 'skKNeighbors_std',\r\n 'skLinear_SVC_mean',\r\n 'skLinear_SVC_std',\r\n 'skRBF_SVM_mean',\r\n 'skRBF_SVM_std',\r\n 'skGaussianProcess_mean',\r\n 'skGaussianProcess_std',\r\n 'skBagging_mean',\r\n 'skBagging_std',\r\n 'XGBoost_mean',\r\n 'XGBoost_std',\r\n 'LightGBM_mean',\r\n 'LightGBM_std',\r\n 'CatBoost_mean',\r\n 'CatBoost_std',\r\n 'mlxPerceptronClf_mean',\r\n 'mlxPerceptronClf_std',\r\n 'FoldingHardVote_mean',\r\n 'FoldingHardVote_std',\r\n 'mlxStackingCVClf_mean',\r\n 'mlxStackingCVClf_std',\r\n 'mlxStackingClf_mean',\r\n 'mlxStackingClf_std']\r\n for key in keys:\r\n if 'mean' in key:\r\n df[key] = abs(df['Survived'] - df[key])\r\n pprint(df.head(5))\r\n df.to_csv(result_path)\r\n\r\n df['total_difficulty'] = [0] * len(df)\r\n\r\n count = 0.0\r\n for key in keys:\r\n if 'mean' in key:\r\n count += 1\r\n df['total_difficulty'] += df[key]\r\n df['total_difficulty'] = df['total_difficulty'] / count\r\n pprint(df.head(5))\r\n df.to_csv(result_path)\r\n\r\n # col = clf_name_mean,clf_name_std ..., feature,\r\n # sort by difficulty\r\n # use best...\r\n\r\n\r\ndef titanic_load_merge_set():\r\n path = os.getcwd()\r\n merge_set_path = os.path.join(path, \"data\", \"titanic\", \"merge_set.csv\")\r\n if not os.path.exists(merge_set_path):\r\n path = os.getcwd()\r\n train_path = os.path.join(path, \"data\", \"titanic\", \"train.csv\")\r\n test_path = os.path.join(path, \"data\", \"titanic\", \"test.csv\")\r\n\r\n train_df = pd.read_csv(train_path)\r\n test_df = pd.read_csv(test_path)\r\n\r\n merged_df = pd.concat([train_df, test_df])\r\n merged_df = merged_df.reset_index(drop=True)\r\n\r\n merged_df.to_csv(merge_set_path)\r\n else:\r\n merged_df = pd.read_csv(merge_set_path)\r\n\r\n return merged_df\r\n\r\n\r\ndef exp_age_predict_regr():\r\n def trans_build_predict_age_dataset():\r\n path = os.getcwd()\r\n trans_merge_path = os.path.join(path, \"data\", \"titanic\", \"trans_merge.csv\")\r\n trans_df = pd.read_csv(trans_merge_path)\r\n\r\n merge_set_path = os.path.join(path, 'data', 'titanic', 'merge_set.csv')\r\n merge_set = pd.read_csv(merge_set_path)\r\n age = merge_set[['Age']]\r\n\r\n for col in trans_df.columns:\r\n if 'Unnamed' in col:\r\n del trans_df[col]\r\n # trans_df = trans_df.drop(columns=['Survived'])\r\n trans_df = trans_df.drop(columns=['Age_bucket'])\r\n\r\n trans_df = pd.concat([trans_df, age], axis=1)\r\n\r\n trans_df_with_age = trans_df.query(\"\"\"not Age.isna()\"\"\")\r\n # pprint(trans_df_with_age.head(1))\r\n # pprint(trans_df_with_age.info())\r\n\r\n keys = list(trans_df_with_age.keys().values)\r\n\r\n keys.remove('Age')\r\n # pprint(keys)\r\n\r\n Xs_df = trans_df_with_age[keys]\r\n Ys_df = trans_df_with_age[['Age']]\r\n # pprint(list(Ys_df['Age'].unique()))\r\n # pprint(Xs_df.info())\r\n # pprint(Xs_df.head(5))\r\n #\r\n # pprint(Ys_df.info())\r\n # pprint(Ys_df.head(5))\r\n\r\n Xs = df_to_np_onehot_embedding(Xs_df)\r\n # Ys = df_to_np_onehot_embedding(Ys_df)\r\n Ys = np.array(Ys_df['Age'])\r\n # pprint(Xs.shape)\r\n # pprint(Ys.shape)\r\n dataset = DummyDataset()\r\n dataset.add_data('Xs', Xs)\r\n dataset.add_data('Ys', Ys)\r\n\r\n # pprint(dataset.to_DataFrame().info())\r\n\r\n return dataset\r\n\r\n def build_predict_age_dataset():\r\n path = os.getcwd()\r\n trans_merge_path = os.path.join(path, \"data\", \"titanic\", \"trans_merge.csv\")\r\n trans_df = pd.read_csv(trans_merge_path)\r\n\r\n for col in trans_df.columns:\r\n if 'Unnamed' in col:\r\n del trans_df[col]\r\n trans_df = trans_df.drop(columns=['Survived'])\r\n\r\n trans_df_with_age = trans_df.query(\"\"\"Age_bucket != 'None' \"\"\")\r\n pprint(trans_df_with_age.head(1))\r\n pprint(trans_df_with_age.info())\r\n\r\n keys = list(trans_df_with_age.keys().values)\r\n\r\n keys.remove('Age_bucket')\r\n pprint(keys)\r\n\r\n Xs_df = trans_df_with_age[keys]\r\n Ys_df = trans_df_with_age[['Age_bucket']]\r\n pprint(list(Ys_df['Age_bucket'].unique()))\r\n # pprint(Xs_df.info())\r\n # pprint(Xs_df.head(5))\r\n\r\n pprint(Ys_df.info())\r\n pprint(Ys_df.head())\r\n\r\n Xs = df_to_np_onehot_embedding(Xs_df)\r\n Ys = df_to_np_onehot_embedding(Ys_df)\r\n # pprint(Xs.shape)\r\n # pprint(Ys.shape)\r\n dataset = DummyDataset()\r\n dataset.add_data('Xs', Xs)\r\n dataset.add_data('Ys', Ys)\r\n\r\n pprint(dataset.to_DataFrame().info())\r\n\r\n return dataset\r\n\r\n dataset = trans_build_predict_age_dataset()\r\n dataset.shuffle()\r\n train, test = dataset.split((20, 3))\r\n train_Xs, train_Ys = train.full_batch(['Xs', 'Ys'])\r\n test_Xs, test_Ys = test.full_batch(['Xs', 'Ys'])\r\n\r\n from xgboost import XGBRegressor\r\n reg = MLPRegressor(hidden_layer_sizes=(500,))\r\n reg = LGBMRegressor()\r\n reg = CatBoostRegressor()\r\n reg = XGBRegressor()\r\n reg.fit(train_Xs, train_Ys)\r\n pprint(reg.score(train_Xs, train_Ys))\r\n pprint(reg.score(test_Xs, test_Ys))\r\n n_sample = 5\r\n pprint(reg.predict(train_Xs[:n_sample]), train_Ys[:n_sample])\r\n pprint(reg.predict(test_Xs[:n_sample]), test_Ys[:n_sample])\r\n\r\n stat = abs(reg.predict(train_Xs) - train_Ys)\r\n stat = np_stat_dict(stat)\r\n pprint(stat)\r\n\r\n stat = abs(reg.predict(test_Xs) - test_Ys)\r\n stat = np_stat_dict(stat)\r\n pprint(stat)\r\n\r\n # clf_pack = ClassifierPack(['skMLP'])\r\n # clf_pack.pack['skMLP'].n_classes_ = test_Ys.shape[1]\r\n # # clf_pack.fit(train_Xs, train_Ys)\r\n # clf_pack.param_search(train_Xs, train_Ys)\r\n # pprint('train', clf_pack.score_pack(train_Xs, train_Ys))\r\n # pprint('test', clf_pack.score_pack(test_Xs, test_Ys))\r\n # pprint(['19~30',\r\n # '30~40',\r\n # '50~60',\r\n # '1~3',\r\n # '12~15',\r\n # '3~6',\r\n # '15~19',\r\n # '6~12',\r\n # '40~50',\r\n # '60~81',\r\n # '0~1'])\r\n\r\n\r\ndef main():\r\n print(exp_titanic_statistic.__name__)\r\n # exp_stacking_metaclf()\r\n # exp_voting()\r\n pass\r\n\r\n\r\n# def exp_titanic_corr_heatmap():\r\n# import matplotlib.pyplot as plt\r\n# import seaborn as sns\r\n#\r\n# def plot_corr_matrix(data, attr, fig_no):\r\n# corr = data.corr()\r\n# # f, ax = plt.subplots(figsize=(11, 9))\r\n#\r\n# # Generate a custom diverging colormap\r\n# cmap = sns.diverging_palette(220, 10, as_cmap=True)\r\n#\r\n# # Draw the heatmap with the mask and correct aspect ratio\r\n# sns.heatmap(corr, cmap=cmap, vmax=1.0, vmin=-1.0, center=0,\r\n# square=True, linewidths=.5, cbar_kws={\"shrink\": .5})\r\n# plt.show()\r\n#\r\n# path = 'temp.csv'\r\n# if not os.path.exists(path):\r\n# df = build_transform(titanic_load_merge_set())\r\n# df.to_csv(path, index=False)\r\n# pprint(df.info())\r\n#\r\n# df = pd.read_csv(path, index_col=False)\r\n# df = df.query('not Survived.isna()')\r\n# pprint(df.info())\r\n#\r\n# df = df_to_onehot_embedding(df)\r\n# pprint(df.info())\r\n#\r\n# corr = df.corr()\r\n# # pprint(corr)\r\n# pprint(list(corr['Survived_0.0'].items()))\r\n# pprint(list(corr['Survived_1.0'].items()))\r\n# # plot_corr_matrix(df, df.keys(), 3)\r\n\r\n\r\ndef exp_C_GAN_with_titanic():\r\n def show(data):\r\n pass\r\n\r\n pass\r\n #\r\n data_size = 4000\r\n zero_one_rate = 0.5\r\n datapack = DatasetPackLoader().load_dataset('titanic')\r\n train_set = datapack['train']\r\n test_set = datapack['test']\r\n train_set.shuffle()\r\n train, valid = train_set.split()\r\n\r\n train_Xs, train_Ys = train.full_batch(['Xs', 'Ys'])\r\n valid_Xs, valid_Ys = valid.full_batch(['Xs', 'Ys'])\r\n #\r\n print(train_Xs.shape, train_Ys.shape)\r\n # path = 'C:\\\\Users\\\\demetoir_desktop\\\\PycharmProjects\\\\MLtools\\\\instance\\\\demetoir_C_GAN_2018-06-29_02-33-02'\r\n # if not os.path.exists(path):\r\n gan = C_GAN(learning_rate=0.001, n_noise=32, loss_type='GAN', with_clipping=True, clipping=.15)\r\n gan.train(train_Xs, train_Ys, epoch=1000)\r\n # path = gan.save()\r\n # print(path)\r\n\r\n # path = \"C:\\\\Users\\\\demetoir_desktop\\\\PycharmProjects\\\\MLtools\\\\instance\\\\demetoir_C_GAN_2018-06-29_03-06-38\"\r\n # gan = C_GAN().load(path)\r\n\r\n metric = gan.metric(train_Xs, train_Ys)\r\n pprint(metric)\r\n\r\n Ys_gen = [[1, 0] for _ in range(int(data_size * zero_one_rate))] \\\r\n + [[0, 1] for _ in range(int(data_size * (1 - zero_one_rate)))]\r\n Ys_gen = np.array(Ys_gen)\r\n\r\n Xs_gen = gan.generate(1)\r\n Xs_gen = to_zero_one_encoding(Xs_gen)\r\n pprint(Xs_gen)\r\n pprint(Xs_gen.shape)\r\n\r\n # plot_1d(train_Xs[:1])\r\n # plot_1d(Xs_gen)\r\n # plt.plot(train_Xs[:1])\r\n # plt.show()\r\n\r\n # Xs_merge = np.concatenate([Xs_gen, train_Xs], axis=0)\r\n # Ys_merge = np.concatenate([Ys_gen, train_Ys], axis=0)\r\n # clf_pack = ClassifierPack()\r\n # # clf_pack.drop_clf('skQDA')\r\n # clf_pack.drop_clf('skGaussian_NB')\r\n # clf_pack.drop_clf('mlxSoftmaxRegressionClf')\r\n # clf_pack.drop_clf('mlxPerceptronClf')\r\n # clf_pack.drop_clf('mlxMLP')\r\n # clf_pack.drop_clf('mlxLogisticRegression')\r\n # clf_pack.drop_clf('mlxAdaline')\r\n # clf_pack.drop_clf('skLinear_SVC')\r\n # clf_pack.drop_clf('skSGD')\r\n # clf_pack.drop_clf('skRBF_SVM')\r\n # clf_pack.drop_clf('skMultinomial_NB')\r\n # clf_pack.fit(Xs_merge, Ys_merge)\r\n #\r\n # score = clf_pack.score(Xs_merge, Ys_merge)\r\n # pprint(score)\r\n #\r\n # score = clf_pack.score(Xs_gen, Ys_gen)\r\n # pprint(score)\r\n #\r\n # score = clf_pack.score(train_Xs, train_Ys)\r\n # pprint(score)\r\n #\r\n # score = clf_pack.score(valid_Xs, valid_Ys)\r\n # pprint(score)\r\n\r\n # esm_pack = clf_pack.to_ensembleClfpack()\r\n # esm_pack.fit(Xs_merge, Ys_merge)\r\n #\r\n # score = esm_pack.score_pack(Xs_gen, Ys_gen)\r\n # pprint(score)\r\n #\r\n # score = esm_pack.score_pack(train_Xs, train_Ys)\r\n # pprint(score)\r\n #\r\n # score = esm_pack.score_pack(valid_Xs, valid_Ys)\r\n # pprint(score)\r\n\r\n\r\ndef exp_CVAE_with_titanic():\r\n data_size = 4000\r\n zero_one_rate = 0.5\r\n datapack = DatasetPackLoader().load_dataset('titanic')\r\n train_set = datapack['train']\r\n test_set = datapack['test']\r\n train_set.shuffle()\r\n train, valid = train_set.split()\r\n\r\n train_Xs, train_Ys = train.full_batch(['Xs', 'Ys'])\r\n valid_Xs, valid_Ys = valid.full_batch(['Xs', 'Ys'])\r\n\r\n # path = 'C:\\\\Users\\\\demetoir_desktop\\\\PycharmProjects\\\\MLtools\\\\instance\\\\demetoir_C_GAN_2018-06-29_02-33-02'\r\n # if not os.path.exists(path):\r\n cvae = CVAE(learning_rate=0.1, latent_code_size=32, verbose=20, KL_D_rate=.05)\r\n cvae.train(train_Xs, train_Ys, epoch=1)\r\n # path = gan.save()\r\n # print(path)\r\n\r\n # path = \"C:\\\\Users\\\\demetoir_desktop\\\\PycharmProjects\\\\MLtools\\\\instance\\\\demetoir_C_GAN_2018-06-29_03-06-38\"\r\n # gan = C_GAN().load(path)\r\n\r\n metric = cvae.metric(train_Xs, train_Ys)\r\n pprint(metric)\r\n\r\n Xs_gen = cvae.recon(train_Xs, train_Ys)\r\n\r\n # plot_1d(Xs_gen[:1])\r\n # plot_1d(train_Xs[:1])\r\n\r\n #\r\n # Xs_gen = np.concatenate([Xs_gen, cvae.recon(train_Xs, train_Ys)], axis=0)\r\n # Xs_gen = np.concatenate([Xs_gen, cvae.recon(train_Xs, train_Ys)], axis=0)\r\n # Xs_gen = np.concatenate([Xs_gen, cvae.recon(train_Xs, train_Ys)], axis=0)\r\n # Xs_gen = np.concatenate([Xs_gen, cvae.recon(train_Xs, train_Ys)], axis=0)\r\n # Xs_gen = to_zero_one_encoding(Xs_gen)\r\n # pprint(Xs_gen)\r\n # pprint(Xs_gen.shape)\r\n # Ys_gen = np.concatenate([train_Ys, train_Ys, train_Ys, train_Ys, train_Ys], axis=0)\r\n\r\n # Xs_merge = np.concatenate([Xs_gen, train_Xs], axis=0)\r\n # Ys_merge = np.concatenate([Ys_gen, train_Ys], axis=0)\r\n # clf_pack = ClassifierPack()\r\n # # clf_pack.drop_clf('skQDA')\r\n # clf_pack.drop_clf('skGaussian_NB')\r\n # clf_pack.drop_clf('mlxSoftmaxRegressionClf')\r\n # clf_pack.drop_clf('mlxPerceptronClf')\r\n # clf_pack.drop_clf('mlxMLP')\r\n # clf_pack.drop_clf('mlxLogisticRegression')\r\n # clf_pack.drop_clf('mlxAdaline')\r\n # clf_pack.drop_clf('skLinear_SVC')\r\n # clf_pack.drop_clf('skSGD')\r\n # clf_pack.drop_clf('skRBF_SVM')\r\n # clf_pack.drop_clf('skMultinomial_NB')\r\n # clf_pack.fit(Xs_gen, Ys_gen)\r\n #\r\n # score = clf_pack.score(Xs_gen, Ys_gen)\r\n # pprint(score)\r\n #\r\n # score = clf_pack.score(Xs_gen, Ys_gen)\r\n # pprint(score)\r\n #\r\n # score = clf_pack.score(train_Xs, train_Ys)\r\n # pprint(score)\r\n #\r\n # score = clf_pack.score(valid_Xs, valid_Ys)\r\n # pprint(score)\r\n #\r\n # esm_pack = clf_pack.to_ensembleClfpack()\r\n # esm_pack.fit(Xs_gen, Ys_gen)\r\n #\r\n # score = esm_pack.score(Xs_gen, Ys_gen)\r\n # pprint(score)\r\n #\r\n # score = esm_pack.score(train_Xs, train_Ys)\r\n # pprint(score)\r\n #\r\n # score = esm_pack.score(valid_Xs, valid_Ys)\r\n # pprint(score)\r\n #\r\n # test_Xs = test_set.full_batch('Xs')\r\n # predict = esm_pack.predict(test_Xs)['FoldingHardVote']\r\n # # predict = clf_pack.predict(test_Xs)['skBagging']\r\n # pprint(predict)\r\n # pprint(predict.shape)\r\n # submit_path = './submit.csv'\r\n # datapack.to_kaggle_submit_csv(submit_path, predict)\r\n\r\n\r\ndef titanic_submit():\r\n datapack = DatasetPackLoader().load_dataset('titanic')\r\n # datapack = DatasetPackLoader().load_dataset('titanic')\r\n train_set = datapack['train']\r\n test_set = datapack['test']\r\n train_set.shuffle()\r\n train, valid = train_set.split()\r\n\r\n train_Xs, train_Ys = train.full_batch(['Xs', 'Ys'])\r\n valid_Xs, valid_Ys = valid.full_batch(['Xs', 'Ys'])\r\n\r\n path = './clf_pack.clf'\r\n if not os.path.exists(path):\r\n train_Xs, train_Ys = train_set.full_batch(['Xs', 'Ys'])\r\n clf_pack = ClassifierPack()\r\n clf_pack.gridSearchCV(train_Xs, train_Ys, cv=10)\r\n clf_pack.dump(path)\r\n\r\n clf_pack = ClassifierPack().load(path)\r\n # pprint(clf_pack.optimize_result)\r\n clf_pack.drop('skQDA')\r\n clf_pack.drop('skGaussian_NB')\r\n clf_pack.drop('mlxSoftmaxRegressionClf')\r\n clf_pack.drop('mlxPerceptronClf')\r\n clf_pack.drop('mlxMLP')\r\n clf_pack.drop('mlxLogisticRegression')\r\n clf_pack.drop('mlxAdaline')\r\n clf_pack.drop('skLinear_SVC')\r\n\r\n train_Xs, train_Ys = train.full_batch(['Xs', 'Ys'])\r\n valid_Xs, valid_Ys = valid.full_batch(['Xs', 'Ys'])\r\n score = clf_pack.score(train_Xs, train_Ys)\r\n pprint(score)\r\n\r\n score = clf_pack.score(valid_Xs, valid_Ys)\r\n pprint(score)\r\n #\r\n esm_pack = clf_pack.to_ensembleClfpack()\r\n train, valid = train_set.split((2, 7))\r\n train_Xs, train_Ys = train.full_batch(['Xs', 'Ys'])\r\n valid_Xs, valid_Ys = valid.full_batch(['Xs', 'Ys'])\r\n\r\n esm_pack.fit(train_Xs, train_Ys)\r\n pprint(esm_pack.score_pack(train_Xs, train_Ys))\r\n pprint(esm_pack.score_pack(valid_Xs, valid_Ys))\r\n\r\n test_Xs = test_set.full_batch(['Xs'])\r\n\r\n predict = esm_pack.predict(test_Xs)['FoldingHardVote']\r\n # predict = clf_pack.predict(test_Xs)['skBagging']\r\n pprint(predict)\r\n pprint(predict.shape)\r\n submit_path = './submit.csv'\r\n datapack.to_kaggle_submit_csv(submit_path, predict)\r\n\r\n # clf_pack.dump(path)\r\n\r\n\r\nclass autoOnehot(BaseModel, CVAE_MixIn):\r\n _params_keys = [\r\n 'batch_size',\r\n 'learning_rate',\r\n 'beta1',\r\n 'L1_norm_lambda',\r\n 'K_average_top_k_loss',\r\n 'code_size',\r\n 'z_size',\r\n 'encoder_net_shapes',\r\n 'decoder_net_shapes',\r\n 'with_noise',\r\n 'noise_intensity',\r\n 'loss_type',\r\n 'KL_D_rate'\r\n ]\r\n\r\n def __init__(self, batch_size=100, learning_rate=0.01, beta1=0.9, L1_norm_lambda=0.001, cate_code_size=32,\r\n gauss_code_size=10,\r\n z_size=32, encoder_net_shapes=(512,), decoder_net_shapes=(512,), with_noise=False, noise_intensity=1.,\r\n loss_type='VAE', KL_D_rate=1.0, verbose=10):\r\n BaseModel.__init__(self, verbose)\r\n CVAE_MixIn.__init__(self)\r\n\r\n self.batch_size = batch_size\r\n self.learning_rate = learning_rate\r\n self.beta1 = beta1\r\n self.L1_norm_lambda = L1_norm_lambda\r\n self.cate_code_size = cate_code_size\r\n self.gauss_code_size = gauss_code_size\r\n self.latent_code_size = cate_code_size + gauss_code_size\r\n\r\n self.z_size = self.latent_code_size\r\n\r\n self.loss_type = loss_type\r\n self.encoder_net_shapes = encoder_net_shapes\r\n self.decoder_net_shapes = decoder_net_shapes\r\n self.with_noise = with_noise\r\n self.noise_intensity = noise_intensity\r\n self.KL_D_rate = KL_D_rate\r\n\r\n def _build_input_shapes(self, shapes):\r\n ret = {}\r\n ret.update(self._build_Xs_input_shape(shapes))\r\n\r\n ret.update(self._build_Ys_input_shape(shapes))\r\n\r\n shapes['zs'] = [None, self.z_size]\r\n ret.update(self._build_zs_input_shape(shapes))\r\n\r\n shapes['noise'] = [None] + list(ret['X_shape'])\r\n ret.update(self._build_noise_input_shape(shapes))\r\n\r\n return ret\r\n\r\n def encoder(self, Xs, net_shapes, reuse=False, name='encoder'):\r\n with tf.variable_scope(name, reuse=reuse):\r\n stack = Stacker(flatten(Xs))\r\n\r\n for shape in net_shapes:\r\n stack.linear_block(shape, relu)\r\n\r\n stack.linear_block(self.cate_code_size + self.gauss_code_size * 2, relu)\r\n\r\n return stack.last_layer\r\n\r\n def decoder(self, zs, net_shapes, reuse=False, name='decoder'):\r\n with tf.variable_scope(name, reuse=reuse):\r\n stack = Stacker(zs)\r\n\r\n for shape in net_shapes:\r\n stack.linear_block(shape, relu)\r\n\r\n stack.linear_block(self.X_flatten_size, relu)\r\n # stack.linear(self.X_flatten_size)\r\n # stack.relu()\r\n # stack.reshape(self.Xs_shape)\r\n\r\n return stack.last_layer\r\n\r\n def aux_reg(self, Xs_onehot, net_shapes, reuse=False, name='aux_reg'):\r\n with tf.variable_scope(name, reuse=reuse):\r\n stack = Stacker(Xs_onehot)\r\n\r\n for shape in net_shapes:\r\n stack.linear_block(shape, sigmoid)\r\n\r\n stack.linear_block(1, sigmoid)\r\n\r\n return stack.last_layer\r\n\r\n def _build_main_graph(self):\r\n self.Xs = placeholder(tf.float32, self.Xs_shape, name='Xs')\r\n self.Ys = placeholder(tf.float32, self.Ys_shape, name='Ys')\r\n self.zs = placeholder(tf.float32, self.zs_shape, name='zs')\r\n self.noises = placeholder(tf.float32, self.noises_shape, name='noises')\r\n\r\n self.Xs_noised = tf.add(self.Xs, self.noises, name='Xs_noised')\r\n if self.with_noise:\r\n Xs = self.Xs_noised\r\n else:\r\n Xs = self.Xs\r\n\r\n self.h = self.encoder(Xs, self.encoder_net_shapes)\r\n\r\n self.h_cate = self.h[:, :self.cate_code_size]\r\n self.h_softmax = tf.nn.softmax(self.h_cate)\r\n self.h_cate_index = tf.argmax(self.h_softmax, 1)\r\n self.cate_code = tf.one_hot(self.h_cate_index, self.cate_code_size)\r\n\r\n self.h_gauss = self.h[:, self.cate_code_size:]\r\n self.h_gauss_mean = self.h_gauss[:, : self.gauss_code_size]\r\n\r\n self.h_gauss_std = self.h_gauss[:, self.gauss_code_size:]\r\n self.h_gauss_std = tf.nn.softplus(self.h_gauss_std)\r\n self.gauss_code = self.h_gauss_mean + self.h_gauss_std * tf.random_normal(tf.shape(self.h_gauss_mean), 0, 1,\r\n dtype=tf.float32)\r\n\r\n # self.latent_code = tf.one_hot(tf.arg_max(self.h, 1), self.latent_code_size)\r\n self.latent_code = concat([self.cate_code, self.gauss_code], axis=1)\r\n\r\n # self.latent_code = self.h\r\n\r\n self.Xs_recon = self.decoder(self.latent_code, self.decoder_net_shapes)\r\n self.Xs_gen = self.decoder(self.zs, self.decoder_net_shapes, reuse=True)\r\n\r\n net_shapes = (512, 512)\r\n self.h_aux_reg = self.aux_reg(self.latent_code, net_shapes)\r\n\r\n head = get_scope()\r\n self.vars_encoder = collect_vars(join_scope(head, 'encoder'))\r\n self.vars_decoder = collect_vars(join_scope(head, 'decoder'))\r\n self.vars_aux_reg = collect_vars(join_scope(head, 'aux_reg'))\r\n\r\n self.vars = self.vars_encoder + self.vars_decoder\r\n\r\n def _build_loss_ops(self):\r\n X = flatten(self.Xs)\r\n X_out = flatten(self.Xs_recon)\r\n\r\n self.MSE = tf.reduce_sum(tf.squared_difference(X, X_out), axis=1)\r\n if self.loss_type == 'MSE_only':\r\n self.loss = self.MSE\r\n\r\n self.step_func = tf.cast(X * self.cate_code_size, tf.int32)\r\n onehot_label = tf.one_hot(self.step_func, self.cate_code_size)\r\n self.loss_index = tf.nn.softmax_cross_entropy_with_logits_v2(logits=self.h_softmax, labels=onehot_label)\r\n self.loss_index *= 0.001\r\n # self.loss += self.loss_index\r\n\r\n self.loss_mean = tf.reduce_mean(self.loss, name='loss_mean')\r\n\r\n self.aux_reg_loss = tf.sqrt(tf.squared_difference(self.h_aux_reg, self.Ys))\r\n\r\n self.__metric_ops = [self.loss, self.aux_reg_loss, self.loss_index]\r\n\r\n def _build_train_ops(self):\r\n var = self.vars_encoder + self.vars_decoder\r\n self.train_op = tf.train.AdamOptimizer(self.learning_rate, self.beta1).minimize(loss=self.loss,\r\n var_list=var)\r\n\r\n var = self.vars_aux_reg + self.vars_encoder\r\n self.train_aux = tf.train.AdamOptimizer(self.learning_rate, self.beta1).minimize(loss=self.aux_reg_loss,\r\n var_list=var)\r\n\r\n var = self.vars_encoder\r\n self.train_index = tf.train.AdamOptimizer(self.learning_rate, self.beta1).minimize(loss=self.loss_index,\r\n var_list=var)\r\n self.__train_ops = [self.train_op, self.train_aux, self.train_index, ]\r\n # self.__train_ops = [self.train_op]\r\n\r\n def train(self, Xs, Ys, epoch=1, save_interval=None, batch_size=None):\r\n self._prepare_train(Xs=Xs, Ys=Ys)\r\n dataset = self.to_dummyDataset(Xs=Xs, Ys=Ys)\r\n\r\n if batch_size is None:\r\n batch_size = self.batch_size\r\n\r\n iter_num = 0\r\n iter_per_epoch = dataset.size // batch_size\r\n self.log.info(\"train epoch {}, iter/epoch {}\".format(epoch, iter_per_epoch))\r\n\r\n for e in trange(epoch):\r\n dataset.shuffle()\r\n\r\n for i in range(iter_per_epoch):\r\n iter_num += 1\r\n\r\n Xs, Ys = dataset.next_batch(batch_size, batch_keys=['Xs', 'Ys'])\r\n noise = self.get_noises(Xs.shape, self.noise_intensity)\r\n\r\n # train_ops = [self.train_op, self.train_aux]\r\n train_ops = self.__train_ops\r\n self.sess.run(train_ops, feed_dict={\r\n self._Xs: Xs,\r\n self._Ys: Ys,\r\n self._noises: noise\r\n })\r\n\r\n recon = self.sess.run(self.Xs_recon, feed_dict={\r\n self._Xs: Xs,\r\n self._Ys: Ys,\r\n self._noises: noise\r\n })\r\n self.sess.run(train_ops, feed_dict={\r\n self._Xs: recon,\r\n self._Ys: Ys,\r\n self._noises: noise\r\n })\r\n\r\n # metric = self.metric(Xs, Ys)\r\n # self.log.info(f\"e:{e} {metric}\")\r\n\r\n if save_interval is not None and e % save_interval == 0:\r\n self.save()\r\n\r\n def code(self, Xs):\r\n noise = self.get_noises(Xs.shape)\r\n return self.get_tf_values(self._code_ops, {\r\n self._Xs: Xs,\r\n self._noises: noise\r\n })\r\n\r\n def recon(self, Xs):\r\n noise = self.get_noises(Xs.shape)\r\n return self.get_tf_values(self._recon_ops, {\r\n self._Xs: Xs,\r\n self._noises: noise\r\n })\r\n\r\n def metric(self, Xs, Ys):\r\n noise = self.get_noises(Xs.shape)\r\n metric_ops = self.__metric_ops\r\n ae_loss, aux_reg_loss, index_loss = self.get_tf_values(metric_ops,\r\n {\r\n self._Xs: Xs,\r\n self.Ys: Ys,\r\n self._noises: noise\r\n })\r\n return {\r\n 'ae_loss': np.mean(ae_loss),\r\n 'aux_reg_loss': np.mean(aux_reg_loss),\r\n 'index_loss': np.mean(index_loss)\r\n }\r\n\r\n def generate(self, zs, Ys):\r\n return self.get_tf_values(self._recon_ops, {\r\n self._Ys: Ys,\r\n self._zs: zs\r\n })\r\n\r\n def predict(self, Xs, Ys):\r\n noise = self.get_noises(Xs.shape)\r\n return self.get_tf_values(self.h_aux_reg, {\r\n self._Xs: Xs,\r\n self.Ys: Ys,\r\n self._noises: noise\r\n })\r\n pass\r\n\r\n def score(self, Xs, Ys):\r\n predict = self.predict(Xs, Ys)\r\n return np.sqrt((predict - Ys) * (predict - Ys))\r\n\r\n\r\ndef test_auto_onehot_encoder():\r\n dataset_path = \"\"\"C:\\\\Users\\\\demetoir_desktop\\\\PycharmProjects\\\\MLtools\\\\data\\\\HousePrices\"\"\"\r\n merge_df = HousePricesHelper.load_merge_set(dataset_path)\r\n\r\n merge_null_clean = HousePricesHelper.null_cleaning(merge_df)\r\n\r\n Xs = merge_null_clean['col_00_1stFlrSF'][:1400]\r\n Ys = merge_null_clean['col_70_SalePrice'][:1400]\r\n\r\n Xs = NpArr(Xs)\r\n Ys = NpArr(Ys)\r\n Xs = np_minmax_normalize(Xs)\r\n Ys = np_minmax_normalize(Ys)\r\n\r\n Xs = Xs.reshape(-1, 1)\r\n Ys = Ys.reshape(-1, 1)\r\n\r\n cate_code_size = 10\r\n aoe = autoOnehot(gauss_code_size=1, cate_code_size=cate_code_size, loss_type='MSE_only', batch_size=128,\r\n learning_rate=0.01,\r\n encoder_net_shapes=(512, 256),\r\n decoder_net_shapes=(256, 512),\r\n # with_noise=True,\r\n # noise_intensity=0.00001\r\n )\r\n aoe.train(Xs, Ys, epoch=100)\r\n metric = aoe.metric(Xs, Ys)\r\n pprint('metric')\r\n pprint(metric)\r\n\r\n aoe.batch_size = 128\r\n aoe.train(Xs, Ys, epoch=200)\r\n metric = aoe.metric(Xs, Ys)\r\n pprint('metric')\r\n pprint(metric)\r\n\r\n aoe.batch_size = 256\r\n aoe.train(Xs, Ys, epoch=400)\r\n metric = aoe.metric(Xs, Ys)\r\n pprint('metric')\r\n pprint(metric)\r\n\r\n # aoe.batch_size = 512\r\n # aoe.train(Xs, Ys, epoch=1600)\r\n # metric = aoe.metric(Xs, Ys)\r\n # pprint('metric')\r\n # pprint(metric)\r\n\r\n score = aoe.score(Xs, Ys)\r\n pprint('score')\r\n pprint(np.mean(score))\r\n pprint()\r\n\r\n predict = aoe.predict(Xs, Ys)\r\n pprint('predict')\r\n pprint(Ys[10:15])\r\n pprint(predict[10:15])\r\n\r\n latent = aoe.code(Xs)\r\n pprint('latent')\r\n pprint(latent[10:15])\r\n\r\n x_walk = np.arange(0, 1, 0.05).reshape(-1, 1)\r\n y = np.zeros_like(x_walk)\r\n latent = aoe.code(x_walk)\r\n recon = aoe.recon(x_walk)\r\n pprint('latent walk')\r\n pprint(x_walk)\r\n pprint(latent)\r\n pprint(recon)\r\n\r\n recon = aoe.recon(Xs)\r\n pprint('recon')\r\n pprint(Xs[10:15])\r\n pprint(recon[10:15])\r\n\r\n latent = aoe.code(Xs)[:, :cate_code_size]\r\n print(latent.shape)\r\n print(np.bincount(np.argmax(latent, axis=1)))\r\n\r\n pprint(aoe.get_tf_values(aoe.h_cate_index, {\r\n aoe.Xs: Xs[10:15]\r\n }))\r\n pprint(aoe.get_tf_values(aoe.step_func,\r\n {\r\n aoe.Xs: np.arange(0, 1, 0.05).reshape(-1, 1)\r\n }))\r\n\r\n\r\ndef exp_wine_quality_predict():\r\n dataset_path = \"\"\"C:\\\\Users\\\\demetoir_desktop\\\\PycharmProjects\\\\MLtools\\\\data\\\\winequality\"\"\"\r\n dataset_pack = wine_qualityPack().load(dataset_path)\r\n dataset_pack.shuffle()\r\n dataset_pack.split('data', 'train', 'test', rate=(7, 3))\r\n train_set = dataset_pack['train']\r\n test_set = dataset_pack['test']\r\n print(train_set.to_DataFrame().info())\r\n\r\n train_Xs, train_Ys = train_set.full_batch(['Xs', 'Ys'])\r\n test_Xs, test_Ys = test_set.full_batch(['Xs', 'Ys'])\r\n\r\n import os\r\n\r\n clf_pack_path = './clf_pack.pkl'\r\n if not os.path.exists(clf_pack_path):\r\n clf_pack = ClassifierPack(['XGBoostClf'])\r\n # clf_pack.drop('CatBoostClf')\r\n # clf_pack.drop('skQDAClf')\r\n # clf_pack.drop('skNearestCentroidClf')\r\n # clf_pack.drop('skGaussianProcessClf')\r\n # clf_pack.drop('skGaussian_NBClf')\r\n # clf_pack.drop('skGradientBoostingClf')\r\n # clf_pack.drop('skMultinomial_NBClf')\r\n # clf_pack.drop('skPassiveAggressiveClf')\r\n\r\n # clf_pack.fit(train_Xs, train_Ys)\r\n clf_pack.HyperOptSearch(train_Xs, train_Ys, 200, parallel=False)\r\n\r\n clf_pack.dump(clf_pack_path)\r\n else:\r\n clf_pack = ClassifierPack().load(clf_pack_path)\r\n\r\n clf_pack = ClassifierPack(['XGBoostClf'])\r\n clf_pack.fit(train_Xs, train_Ys)\r\n\r\n score = clf_pack.score(train_Xs, train_Ys)\r\n pprint(score)\r\n\r\n score = clf_pack.score(test_Xs, test_Ys)\r\n pprint(score)\r\n\r\n # proba = clf_pack.predict_proba(train_Xs[:5])\r\n # print(proba)\r\n\r\n smaple_X = test_Xs[10:15]\r\n sample_y = test_Ys[10:15]\r\n\r\n proba = clf_pack.predict_proba(smaple_X)\r\n print(proba)\r\n predict = clf_pack.predict(smaple_X)\r\n print(predict)\r\n print(sample_y)\r\n\r\n # score = clf_pack.score_pack(train_Xs, train_Ys)\r\n # pprint(score)\r\n #\r\n score = clf_pack.score_pack(test_Xs, test_Ys)\r\n pprint(score)\r\n matrix = score['XGBoostClf']['confusion_matrix']\r\n pprint(matrix / len(test_Xs))\r\n\r\n\r\ndef exp_data_aug_VAE_wine_quality():\r\n rets = load_wine_quality_dataset()\r\n Xs, Ys, test_Xs, test_Ys, sample_xs, sample_Ys = rets\r\n\r\n CVAE_path = './CVAE.pkl'\r\n if not os.path.exists(CVAE_path):\r\n cvae = CVAE(loss_type='MSE_only', learning_rate=0.01, latent_code_size=5,\r\n decoder_net_shapes=(128, 128), encoder_net_shapes=(128, 128), batch_size=512)\r\n cvae.train(Xs, Ys, epoch=1600)\r\n cvae.save(CVAE_path)\r\n else:\r\n cvae = CVAE().load_meta(CVAE_path)\r\n\r\n metric = cvae.metric(Xs, Ys)\r\n metric = np.mean(metric)\r\n print(metric)\r\n\r\n def train_doubling_batch_size(tf_model, Xs, Ys, epoch=100, iter_=3):\r\n for _ in range(iter_):\r\n tf_model.train(Xs, Ys, epoch=epoch)\r\n metric = tf_model.metric(Xs, Ys)\r\n metric = np.mean(metric)\r\n print(metric)\r\n tf_model.batch_size *= 2\r\n epoch *= 2\r\n\r\n recon = cvae.recon(sample_xs, sample_Ys)\r\n print(sample_xs)\r\n pprint(recon)\r\n\r\n gen_labels_1 = np.array([[0, 1] for _ in range(2000)])\r\n gen_x_1 = cvae.generate(gen_labels_1)\r\n merged_Xs = np.concatenate([Xs, gen_x_1])\r\n merged_Ys = np.concatenate([Ys, gen_labels_1])\r\n\r\n gen_labels_0 = np.array([[1, 0] for _ in range(2000)])\r\n gen_x_0 = cvae.generate(gen_labels_1)\r\n gen_only_x = np.concatenate([gen_x_0, gen_x_1])\r\n gen_only_labels = np.concatenate([gen_labels_0, gen_labels_1])\r\n\r\n high = 0.02\r\n low = -0.02\r\n noised_Xs = np.concatenate([\r\n Xs,\r\n Xs + np.random.uniform(low, high, size=Xs.shape),\r\n Xs + np.random.uniform(low, high, size=Xs.shape),\r\n Xs + np.random.uniform(low, high, size=Xs.shape),\r\n ])\r\n noised_Ys = np.concatenate([Ys, Ys, Ys, Ys])\r\n\r\n def print_score_info(clf_pack):\r\n merge_score = clf_pack.score(gen_only_x, gen_only_labels)\r\n train_score = clf_pack.score(Xs, Ys)\r\n test_score = clf_pack.score(test_Xs, test_Ys)\r\n noised_score = clf_pack.score(noised_Xs, noised_Ys)\r\n print('aug score')\r\n pprint(f' train_score : {train_score}')\r\n pprint(f'merge_score : {merge_score}')\r\n pprint(f'test_score : {test_score}')\r\n pprint(f'noised_score : {noised_score}')\r\n\r\n clf_pack = ClassifierPack(['XGBoostClf'])\r\n clf_pack.fit(merged_Xs, merged_Ys)\r\n print('fit merge')\r\n print_score_info(clf_pack)\r\n\r\n clf_pack = ClassifierPack(['XGBoostClf'])\r\n clf_pack.fit(Xs, Ys)\r\n print('fit origin')\r\n print_score_info(clf_pack)\r\n\r\n clf_pack = ClassifierPack(['XGBoostClf'])\r\n clf_pack.fit(gen_only_x, gen_only_labels)\r\n print('fit gen_only')\r\n print_score_info(clf_pack)\r\n\r\n clf_pack = ClassifierPack(['XGBoostClf'])\r\n clf_pack.fit(noised_Xs, noised_Ys)\r\n print('fit noised')\r\n print_score_info(clf_pack)\r\n\r\n\r\ndef exp_data_aug_GAN_wine_quality():\r\n rets = load_wine_quality_dataset()\r\n train_Xs, train_Ys, test_Xs, test_Ys, sample_xs, sample_Ys = rets\r\n\r\n model = C_GAN\r\n GAN_path = f'./{model.__name__}.pkl'\r\n if not os.path.exists(GAN_path):\r\n c_GAN = model(loss_type='WGAN', learning_rate=0.001, batch_size=256, G_net_shape=(256, 256),\r\n D_net_shape=(64, 64))\r\n c_GAN.train(train_Xs, train_Ys, epoch=200)\r\n c_GAN.save(GAN_path)\r\n else:\r\n c_GAN = model().load_meta(GAN_path)\r\n\r\n metric = c_GAN.metric(train_Xs, train_Ys)\r\n print(metric)\r\n\r\n recon = c_GAN.recon(sample_xs, sample_Ys)\r\n print(sample_xs)\r\n pprint(recon)\r\n\r\n gen_labels_1 = np.array([[0, 1] for _ in range(2000)])\r\n gen_x_1 = c_GAN.generate(gen_labels_1)\r\n merged_Xs = np.concatenate([train_Xs, gen_x_1])\r\n merged_Ys = np.concatenate([train_Ys, gen_labels_1])\r\n\r\n gen_labels_0 = np.array([[1, 0] for _ in range(2000)])\r\n gen_x_0 = c_GAN.generate(gen_labels_1)\r\n gen_only_x = np.concatenate([gen_x_0, gen_x_1])\r\n gen_only_labels = np.concatenate([gen_labels_0, gen_labels_1])\r\n\r\n high = 0.02\r\n low = -0.02\r\n noised_Xs = np.concatenate([\r\n train_Xs,\r\n train_Xs + np.random.uniform(low, high, size=train_Xs.shape),\r\n train_Xs + np.random.uniform(low, high, size=train_Xs.shape),\r\n train_Xs + np.random.uniform(low, high, size=train_Xs.shape),\r\n ])\r\n noised_Ys = np.concatenate([train_Ys, train_Ys, train_Ys, train_Ys])\r\n\r\n def print_score_info(clf_pack):\r\n merge_score = clf_pack.score(gen_only_x, gen_only_labels)\r\n train_score = clf_pack.score(train_Xs, train_Ys)\r\n test_score = clf_pack.score(test_Xs, test_Ys)\r\n noised_score = clf_pack.score(noised_Xs, noised_Ys)\r\n print('aug score')\r\n pprint(f' train_score : {train_score}')\r\n pprint(f'merge_score : {merge_score}')\r\n pprint(f'test_score : {test_score}')\r\n pprint(f'noised_score : {noised_score}')\r\n\r\n clf_pack = ClassifierPack(['XGBoostClf'])\r\n clf_pack.fit(merged_Xs, merged_Ys)\r\n print('fit merge')\r\n print_score_info(clf_pack)\r\n\r\n clf_pack = ClassifierPack(['XGBoostClf'])\r\n clf_pack.fit(train_Xs, train_Ys)\r\n print('fit origin')\r\n print_score_info(clf_pack)\r\n\r\n clf_pack = ClassifierPack(['XGBoostClf'])\r\n clf_pack.fit(gen_only_x, gen_only_labels)\r\n print('fit gen_only')\r\n print_score_info(clf_pack)\r\n\r\n clf_pack = ClassifierPack(['XGBoostClf'])\r\n clf_pack.fit(noised_Xs, noised_Ys)\r\n print('fit noised')\r\n print_score_info(clf_pack)\r\n\r\n\r\ndef groupby_label(dataset):\r\n # x = dataset_pack['data'].Ys_onehot_label\r\n x = dataset.Ys_index_label\r\n\r\n print(np.bincount(x))\r\n print(np.unique(x))\r\n\r\n label_partials = []\r\n for key in np.unique(x):\r\n idxs = np.where(x == key)\r\n partial = dataset.x[idxs]\r\n label_partials += [partial]\r\n\r\n return label_partials\r\n\r\n\r\ndef exp_wine_quality_pca():\r\n df_Xs_keys = [\r\n 'col_0_fixed_acidity', 'col_1_volatile_acidity', 'col_2_citric_acid',\r\n 'col_3_residual_sugar', 'col_4_chlorides', 'col_5_free_sulfur_dioxide',\r\n 'col_6_total_sulfur_dioxide', 'col_7_density', 'col_8_pH',\r\n 'col_9_sulphates', 'col_10_alcohol', 'col_12_color'\r\n ]\r\n df_Ys_key = 'col_11_quality'\r\n\r\n dataset_path = \"\"\"C:\\\\Users\\\\demetoir_desktop\\\\PycharmProjects\\\\MLtools\\\\data\\\\winequality\"\"\"\r\n dataset_pack = wine_qualityPack().load(dataset_path)\r\n dataset_pack.shuffle()\r\n full_Xs, full_Ys = dataset_pack['data'].full_batch(['Xs', 'Ys'])\r\n\r\n dataset_pack.split('data', 'train', 'test', rate=(7, 3))\r\n train_set = dataset_pack['train']\r\n test_set = dataset_pack['test']\r\n\r\n Xs, Ys = train_set.full_batch(['Xs', 'Ys'])\r\n test_Xs, test_Ys = test_set.full_batch(['Xs', 'Ys'])\r\n sample_xs = Xs[:5]\r\n sample_Ys = Ys[:5]\r\n\r\n label_partials = groupby_label(dataset_pack['data'])\r\n\r\n model = PCA(n_components=2)\r\n transformed = model.fit(full_Xs)\r\n print(transformed)\r\n\r\n transformed = []\r\n for partial in label_partials:\r\n pca_partial = model.transform(partial)\r\n transformed += [pca_partial]\r\n\r\n pprint(transformed)\r\n plot = PlotTools(show=True, save=False)\r\n plot.scatter_2d(*transformed)\r\n",
"from hyperopt import hp\r\nfrom sklearn.linear_model import TheilSenRegressor as _TheilSenRegressor\r\n\r\nfrom script.sklearn_like_toolkit.warpper.base.BaseWrapperReg import BaseWrapperReg\r\nfrom script.sklearn_like_toolkit.warpper.base.MixIn import MetaBaseWrapperRegWithABC\r\n\r\n\r\nclass skTheilSenReg(_TheilSenRegressor, BaseWrapperReg, metaclass=MetaBaseWrapperRegWithABC):\r\n\r\n def __init__(self, fit_intercept=True, copy_X=True, max_subpopulation=1e4, n_subsamples=None, max_iter=300,\r\n tol=1.e-3, random_state=None, n_jobs=1, verbose=False):\r\n max_iter = int(max_iter)\r\n _TheilSenRegressor.__init__(\r\n self, fit_intercept, copy_X, max_subpopulation, n_subsamples, max_iter, tol, random_state, n_jobs,\r\n verbose)\r\n BaseWrapperReg.__init__(self)\r\n\r\n HyperOpt_space = {\r\n 'max_subpopulation': 1e4,\r\n 'n_subsamples': None,\r\n 'max_iter': hp.qloguniform('max_iter', 4, 8, 1),\r\n 'tol': hp.loguniform('tol', -8, 0),\r\n }\r\n\r\n tuning_grid = {\r\n 'fit_intercept': True,\r\n 'copy_X': True,\r\n 'max_subpopulation': 1e4,\r\n 'n_subsamples': None,\r\n 'max_iter': 300,\r\n 'tol': 1.e-3,\r\n 'random_state': None,\r\n 'n_jobs': 1,\r\n 'verbose': False,\r\n }\r\n"
] | [
[
"sklearn.naive_bayes.MultinomialNB.__init__"
],
[
"sklearn.linear_model.ARDRegression.__init__"
],
[
"pandas.DataFrame.from_csv",
"numpy.sqrt",
"tensorflow.cast",
"pandas.DataFrame",
"numpy.concatenate",
"sklearn.neural_network.multilayer_perceptron.MLPRegressor",
"numpy.zeros_like",
"numpy.mean",
"tensorflow.train.AdamOptimizer",
"numpy.where",
"pandas.read_csv",
"numpy.unique",
"numpy.arange",
"numpy.argmax",
"tensorflow.add",
"tensorflow.argmax",
"pandas.concat",
"tensorflow.shape",
"tensorflow.one_hot",
"numpy.equal",
"numpy.array",
"sklearn.decomposition.PCA",
"tensorflow.nn.softmax",
"tensorflow.reduce_mean",
"numpy.bincount",
"tensorflow.nn.softmax_cross_entropy_with_logits_v2",
"tensorflow.variable_scope",
"numpy.random.uniform",
"tensorflow.squared_difference",
"tensorflow.nn.softplus"
],
[
"sklearn.linear_model.TheilSenRegressor.__init__"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"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": [
"1.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
umangino/pandas | [
"c492672699110fe711b7f76ded5828ff24bce5ab",
"c492672699110fe711b7f76ded5828ff24bce5ab",
"c492672699110fe711b7f76ded5828ff24bce5ab",
"c492672699110fe711b7f76ded5828ff24bce5ab",
"c492672699110fe711b7f76ded5828ff24bce5ab",
"c492672699110fe711b7f76ded5828ff24bce5ab",
"c492672699110fe711b7f76ded5828ff24bce5ab"
] | [
"pandas/tests/indexes/multi/test_formats.py",
"pandas/io/parsers/base_parser.py",
"pandas/core/util/hashing.py",
"pandas/tests/window/test_win_type.py",
"pandas/tests/indexes/datetimelike_/test_is_monotonic.py",
"pandas/tests/io/formats/test_to_excel.py",
"pandas/tests/indexes/numeric/test_indexing.py"
] | [
"import warnings\n\nimport numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import (\n Index,\n MultiIndex,\n)\n\n\ndef test_format(idx):\n idx.format()\n idx[:0].format()\n\n\ndef test_format_integer_names():\n index = MultiIndex(\n levels=[[0, 1], [0, 1]], codes=[[0, 0, 1, 1], [0, 1, 0, 1]], names=[0, 1]\n )\n index.format(names=True)\n\n\ndef test_format_sparse_config(idx):\n warn_filters = warnings.filters\n warnings.filterwarnings(\"ignore\", category=FutureWarning, module=\".*format\")\n # GH1538\n with pd.option_context(\"display.multi_sparse\", False):\n result = idx.format()\n assert result[1] == \"foo two\"\n\n warnings.filters = warn_filters\n\n\ndef test_format_sparse_display():\n index = MultiIndex(\n levels=[[0, 1], [0, 1], [0, 1], [0]],\n codes=[\n [0, 0, 0, 1, 1, 1],\n [0, 0, 1, 0, 0, 1],\n [0, 1, 0, 0, 1, 0],\n [0, 0, 0, 0, 0, 0],\n ],\n )\n\n result = index.format()\n assert result[3] == \"1 0 0 0\"\n\n\ndef test_repr_with_unicode_data():\n with pd.option_context(\"display.encoding\", \"UTF-8\"):\n d = {\"a\": [\"\\u05d0\", 2, 3], \"b\": [4, 5, 6], \"c\": [7, 8, 9]}\n index = pd.DataFrame(d).set_index([\"a\", \"b\"]).index\n assert \"\\\\\" not in repr(index) # we don't want unicode-escaped\n\n\ndef test_repr_roundtrip_raises():\n mi = MultiIndex.from_product([list(\"ab\"), range(3)], names=[\"first\", \"second\"])\n msg = \"Must pass both levels and codes\"\n with pytest.raises(TypeError, match=msg):\n eval(repr(mi))\n\n\ndef test_unicode_string_with_unicode():\n d = {\"a\": [\"\\u05d0\", 2, 3], \"b\": [4, 5, 6], \"c\": [7, 8, 9]}\n idx = pd.DataFrame(d).set_index([\"a\", \"b\"]).index\n str(idx)\n\n\ndef test_repr_max_seq_item_setting(idx):\n # GH10182\n idx = idx.repeat(50)\n with pd.option_context(\"display.max_seq_items\", None):\n repr(idx)\n assert \"...\" not in str(idx)\n\n\nclass TestRepr:\n def test_unicode_repr_issues(self):\n levels = [Index([\"a/\\u03c3\", \"b/\\u03c3\", \"c/\\u03c3\"]), Index([0, 1])]\n codes = [np.arange(3).repeat(2), np.tile(np.arange(2), 3)]\n index = MultiIndex(levels=levels, codes=codes)\n\n repr(index.levels)\n repr(index.get_level_values(1))\n\n def test_repr_max_seq_items_equal_to_n(self, idx):\n # display.max_seq_items == n\n with pd.option_context(\"display.max_seq_items\", 6):\n result = idx.__repr__()\n expected = \"\"\"\\\nMultiIndex([('foo', 'one'),\n ('foo', 'two'),\n ('bar', 'one'),\n ('baz', 'two'),\n ('qux', 'one'),\n ('qux', 'two')],\n names=['first', 'second'])\"\"\"\n assert result == expected\n\n def test_repr(self, idx):\n result = idx[:1].__repr__()\n expected = \"\"\"\\\nMultiIndex([('foo', 'one')],\n names=['first', 'second'])\"\"\"\n assert result == expected\n\n result = idx.__repr__()\n expected = \"\"\"\\\nMultiIndex([('foo', 'one'),\n ('foo', 'two'),\n ('bar', 'one'),\n ('baz', 'two'),\n ('qux', 'one'),\n ('qux', 'two')],\n names=['first', 'second'])\"\"\"\n assert result == expected\n\n with pd.option_context(\"display.max_seq_items\", 5):\n result = idx.__repr__()\n expected = \"\"\"\\\nMultiIndex([('foo', 'one'),\n ('foo', 'two'),\n ...\n ('qux', 'one'),\n ('qux', 'two')],\n names=['first', 'second'], length=6)\"\"\"\n assert result == expected\n\n # display.max_seq_items == 1\n with pd.option_context(\"display.max_seq_items\", 1):\n result = idx.__repr__()\n expected = \"\"\"\\\nMultiIndex([...\n ('qux', 'two')],\n names=['first', ...], length=6)\"\"\"\n assert result == expected\n\n def test_rjust(self, narrow_multi_index):\n mi = narrow_multi_index\n result = mi[:1].__repr__()\n expected = \"\"\"\\\nMultiIndex([('a', 9, '2000-01-01 00:00:00')],\n names=['a', 'b', 'dti'])\"\"\"\n assert result == expected\n\n result = mi[::500].__repr__()\n expected = \"\"\"\\\nMultiIndex([( 'a', 9, '2000-01-01 00:00:00'),\n ( 'a', 9, '2000-01-01 00:08:20'),\n ('abc', 10, '2000-01-01 00:16:40'),\n ('abc', 10, '2000-01-01 00:25:00')],\n names=['a', 'b', 'dti'])\"\"\"\n assert result == expected\n\n result = mi.__repr__()\n expected = \"\"\"\\\nMultiIndex([( 'a', 9, '2000-01-01 00:00:00'),\n ( 'a', 9, '2000-01-01 00:00:01'),\n ( 'a', 9, '2000-01-01 00:00:02'),\n ( 'a', 9, '2000-01-01 00:00:03'),\n ( 'a', 9, '2000-01-01 00:00:04'),\n ( 'a', 9, '2000-01-01 00:00:05'),\n ( 'a', 9, '2000-01-01 00:00:06'),\n ( 'a', 9, '2000-01-01 00:00:07'),\n ( 'a', 9, '2000-01-01 00:00:08'),\n ( 'a', 9, '2000-01-01 00:00:09'),\n ...\n ('abc', 10, '2000-01-01 00:33:10'),\n ('abc', 10, '2000-01-01 00:33:11'),\n ('abc', 10, '2000-01-01 00:33:12'),\n ('abc', 10, '2000-01-01 00:33:13'),\n ('abc', 10, '2000-01-01 00:33:14'),\n ('abc', 10, '2000-01-01 00:33:15'),\n ('abc', 10, '2000-01-01 00:33:16'),\n ('abc', 10, '2000-01-01 00:33:17'),\n ('abc', 10, '2000-01-01 00:33:18'),\n ('abc', 10, '2000-01-01 00:33:19')],\n names=['a', 'b', 'dti'], length=2000)\"\"\"\n assert result == expected\n\n def test_tuple_width(self, wide_multi_index):\n mi = wide_multi_index\n result = mi[:1].__repr__()\n expected = \"\"\"MultiIndex([('a', 9, '2000-01-01 00:00:00', '2000-01-01 00:00:00', ...)],\n names=['a', 'b', 'dti_1', 'dti_2', 'dti_3'])\"\"\"\n assert result == expected\n\n result = mi[:10].__repr__()\n expected = \"\"\"\\\nMultiIndex([('a', 9, '2000-01-01 00:00:00', '2000-01-01 00:00:00', ...),\n ('a', 9, '2000-01-01 00:00:01', '2000-01-01 00:00:01', ...),\n ('a', 9, '2000-01-01 00:00:02', '2000-01-01 00:00:02', ...),\n ('a', 9, '2000-01-01 00:00:03', '2000-01-01 00:00:03', ...),\n ('a', 9, '2000-01-01 00:00:04', '2000-01-01 00:00:04', ...),\n ('a', 9, '2000-01-01 00:00:05', '2000-01-01 00:00:05', ...),\n ('a', 9, '2000-01-01 00:00:06', '2000-01-01 00:00:06', ...),\n ('a', 9, '2000-01-01 00:00:07', '2000-01-01 00:00:07', ...),\n ('a', 9, '2000-01-01 00:00:08', '2000-01-01 00:00:08', ...),\n ('a', 9, '2000-01-01 00:00:09', '2000-01-01 00:00:09', ...)],\n names=['a', 'b', 'dti_1', 'dti_2', 'dti_3'])\"\"\"\n assert result == expected\n\n result = mi.__repr__()\n expected = \"\"\"\\\nMultiIndex([( 'a', 9, '2000-01-01 00:00:00', '2000-01-01 00:00:00', ...),\n ( 'a', 9, '2000-01-01 00:00:01', '2000-01-01 00:00:01', ...),\n ( 'a', 9, '2000-01-01 00:00:02', '2000-01-01 00:00:02', ...),\n ( 'a', 9, '2000-01-01 00:00:03', '2000-01-01 00:00:03', ...),\n ( 'a', 9, '2000-01-01 00:00:04', '2000-01-01 00:00:04', ...),\n ( 'a', 9, '2000-01-01 00:00:05', '2000-01-01 00:00:05', ...),\n ( 'a', 9, '2000-01-01 00:00:06', '2000-01-01 00:00:06', ...),\n ( 'a', 9, '2000-01-01 00:00:07', '2000-01-01 00:00:07', ...),\n ( 'a', 9, '2000-01-01 00:00:08', '2000-01-01 00:00:08', ...),\n ( 'a', 9, '2000-01-01 00:00:09', '2000-01-01 00:00:09', ...),\n ...\n ('abc', 10, '2000-01-01 00:33:10', '2000-01-01 00:33:10', ...),\n ('abc', 10, '2000-01-01 00:33:11', '2000-01-01 00:33:11', ...),\n ('abc', 10, '2000-01-01 00:33:12', '2000-01-01 00:33:12', ...),\n ('abc', 10, '2000-01-01 00:33:13', '2000-01-01 00:33:13', ...),\n ('abc', 10, '2000-01-01 00:33:14', '2000-01-01 00:33:14', ...),\n ('abc', 10, '2000-01-01 00:33:15', '2000-01-01 00:33:15', ...),\n ('abc', 10, '2000-01-01 00:33:16', '2000-01-01 00:33:16', ...),\n ('abc', 10, '2000-01-01 00:33:17', '2000-01-01 00:33:17', ...),\n ('abc', 10, '2000-01-01 00:33:18', '2000-01-01 00:33:18', ...),\n ('abc', 10, '2000-01-01 00:33:19', '2000-01-01 00:33:19', ...)],\n names=['a', 'b', 'dti_1', 'dti_2', 'dti_3'], length=2000)\"\"\"\n assert result == expected\n",
"from __future__ import annotations\n\nfrom collections import defaultdict\nfrom copy import copy\nimport csv\nimport datetime\nfrom enum import Enum\nimport itertools\nfrom typing import (\n Callable,\n DefaultDict,\n Hashable,\n Iterable,\n List,\n Mapping,\n Sequence,\n Tuple,\n cast,\n final,\n overload,\n)\nimport warnings\n\nimport numpy as np\n\nimport pandas._libs.lib as lib\nimport pandas._libs.ops as libops\nimport pandas._libs.parsers as parsers\nfrom pandas._libs.parsers import STR_NA_VALUES\nfrom pandas._libs.tslibs import parsing\nfrom pandas._typing import (\n ArrayLike,\n DtypeArg,\n)\nfrom pandas.errors import (\n ParserError,\n ParserWarning,\n)\nfrom pandas.util._exceptions import find_stack_level\n\nfrom pandas.core.dtypes.astype import astype_nansafe\nfrom pandas.core.dtypes.common import (\n ensure_object,\n is_bool_dtype,\n is_categorical_dtype,\n is_dict_like,\n is_dtype_equal,\n is_extension_array_dtype,\n is_integer,\n is_integer_dtype,\n is_list_like,\n is_object_dtype,\n is_scalar,\n is_string_dtype,\n pandas_dtype,\n)\nfrom pandas.core.dtypes.dtypes import CategoricalDtype\nfrom pandas.core.dtypes.missing import isna\n\nfrom pandas import DataFrame\nfrom pandas.core import algorithms\nfrom pandas.core.arrays import Categorical\nfrom pandas.core.indexes.api import (\n Index,\n MultiIndex,\n ensure_index_from_sequences,\n)\nfrom pandas.core.series import Series\nfrom pandas.core.tools import datetimes as tools\n\nfrom pandas.io.date_converters import generic_parser\n\n\nclass ParserBase:\n class BadLineHandleMethod(Enum):\n ERROR = 0\n WARN = 1\n SKIP = 2\n\n _implicit_index: bool = False\n _first_chunk: bool\n\n def __init__(self, kwds):\n\n self.names = kwds.get(\"names\")\n self.orig_names: list | None = None\n self.prefix = kwds.pop(\"prefix\", None)\n\n self.index_col = kwds.get(\"index_col\", None)\n self.unnamed_cols: set = set()\n self.index_names: list | None = None\n self.col_names = None\n\n self.parse_dates = _validate_parse_dates_arg(kwds.pop(\"parse_dates\", False))\n self._parse_date_cols: Iterable = []\n self.date_parser = kwds.pop(\"date_parser\", None)\n self.dayfirst = kwds.pop(\"dayfirst\", False)\n self.keep_date_col = kwds.pop(\"keep_date_col\", False)\n\n self.na_values = kwds.get(\"na_values\")\n self.na_fvalues = kwds.get(\"na_fvalues\")\n self.na_filter = kwds.get(\"na_filter\", False)\n self.keep_default_na = kwds.get(\"keep_default_na\", True)\n\n self.dtype = copy(kwds.get(\"dtype\", None))\n\n self.true_values = kwds.get(\"true_values\")\n self.false_values = kwds.get(\"false_values\")\n self.mangle_dupe_cols = kwds.get(\"mangle_dupe_cols\", True)\n self.infer_datetime_format = kwds.pop(\"infer_datetime_format\", False)\n self.cache_dates = kwds.pop(\"cache_dates\", True)\n\n self._date_conv = _make_date_converter(\n date_parser=self.date_parser,\n dayfirst=self.dayfirst,\n infer_datetime_format=self.infer_datetime_format,\n cache_dates=self.cache_dates,\n )\n\n # validate header options for mi\n self.header = kwds.get(\"header\")\n if isinstance(self.header, (list, tuple, np.ndarray)):\n if not all(map(is_integer, self.header)):\n raise ValueError(\"header must be integer or list of integers\")\n if any(i < 0 for i in self.header):\n raise ValueError(\n \"cannot specify multi-index header with negative integers\"\n )\n if kwds.get(\"usecols\"):\n raise ValueError(\n \"cannot specify usecols when specifying a multi-index header\"\n )\n if kwds.get(\"names\"):\n raise ValueError(\n \"cannot specify names when specifying a multi-index header\"\n )\n\n # validate index_col that only contains integers\n if self.index_col is not None:\n is_sequence = isinstance(self.index_col, (list, tuple, np.ndarray))\n if not (\n is_sequence\n and all(map(is_integer, self.index_col))\n or is_integer(self.index_col)\n ):\n raise ValueError(\n \"index_col must only contain row numbers \"\n \"when specifying a multi-index header\"\n )\n elif self.header is not None:\n # GH 27394\n if self.prefix is not None:\n raise ValueError(\n \"Argument prefix must be None if argument header is not None\"\n )\n # GH 16338\n elif not is_integer(self.header):\n raise ValueError(\"header must be integer or list of integers\")\n # GH 27779\n elif self.header < 0:\n raise ValueError(\n \"Passing negative integer to header is invalid. \"\n \"For no header, use header=None instead\"\n )\n\n self._name_processed = False\n\n self._first_chunk = True\n\n self.usecols, self.usecols_dtype = self._validate_usecols_arg(kwds[\"usecols\"])\n\n # Fallback to error to pass a sketchy test(test_override_set_noconvert_columns)\n # Normally, this arg would get pre-processed earlier on\n self.on_bad_lines = kwds.get(\"on_bad_lines\", self.BadLineHandleMethod.ERROR)\n\n def _validate_parse_dates_presence(self, columns: Sequence[Hashable]) -> Iterable:\n \"\"\"\n Check if parse_dates are in columns.\n\n If user has provided names for parse_dates, check if those columns\n are available.\n\n Parameters\n ----------\n columns : list\n List of names of the dataframe.\n\n Returns\n -------\n The names of the columns which will get parsed later if a dict or list\n is given as specification.\n\n Raises\n ------\n ValueError\n If column to parse_date is not in dataframe.\n\n \"\"\"\n cols_needed: Iterable\n if is_dict_like(self.parse_dates):\n cols_needed = itertools.chain(*self.parse_dates.values())\n elif is_list_like(self.parse_dates):\n # a column in parse_dates could be represented\n # ColReference = Union[int, str]\n # DateGroups = List[ColReference]\n # ParseDates = Union[DateGroups, List[DateGroups],\n # Dict[ColReference, DateGroups]]\n cols_needed = itertools.chain.from_iterable(\n col if is_list_like(col) and not isinstance(col, tuple) else [col]\n for col in self.parse_dates\n )\n else:\n cols_needed = []\n\n cols_needed = list(cols_needed)\n\n # get only columns that are references using names (str), not by index\n missing_cols = \", \".join(\n sorted(\n {\n col\n for col in cols_needed\n if isinstance(col, str) and col not in columns\n }\n )\n )\n if missing_cols:\n raise ValueError(\n f\"Missing column provided to 'parse_dates': '{missing_cols}'\"\n )\n # Convert positions to actual column names\n return [\n col if (isinstance(col, str) or col in columns) else columns[col]\n for col in cols_needed\n ]\n\n def close(self):\n pass\n\n @final\n @property\n def _has_complex_date_col(self) -> bool:\n return isinstance(self.parse_dates, dict) or (\n isinstance(self.parse_dates, list)\n and len(self.parse_dates) > 0\n and isinstance(self.parse_dates[0], list)\n )\n\n @final\n def _should_parse_dates(self, i: int) -> bool:\n if isinstance(self.parse_dates, bool):\n return self.parse_dates\n else:\n if self.index_names is not None:\n name = self.index_names[i]\n else:\n name = None\n j = i if self.index_col is None else self.index_col[i]\n\n if is_scalar(self.parse_dates):\n return (j == self.parse_dates) or (\n name is not None and name == self.parse_dates\n )\n else:\n return (j in self.parse_dates) or (\n name is not None and name in self.parse_dates\n )\n\n @final\n def _extract_multi_indexer_columns(\n self,\n header,\n index_names: list | None,\n passed_names: bool = False,\n ):\n \"\"\"\n Extract and return the names, index_names, col_names if the column\n names are a MultiIndex.\n\n Parameters\n ----------\n header: list of lists\n The header rows\n index_names: list, optional\n The names of the future index\n passed_names: bool, default False\n A flag specifying if names where passed\n\n \"\"\"\n if len(header) < 2:\n return header[0], index_names, None, passed_names\n\n # the names are the tuples of the header that are not the index cols\n # 0 is the name of the index, assuming index_col is a list of column\n # numbers\n ic = self.index_col\n if ic is None:\n ic = []\n\n if not isinstance(ic, (list, tuple, np.ndarray)):\n ic = [ic]\n sic = set(ic)\n\n # clean the index_names\n index_names = header.pop(-1)\n index_names, _, _ = self._clean_index_names(index_names, self.index_col)\n\n # extract the columns\n field_count = len(header[0])\n\n # check if header lengths are equal\n if not all(len(header_iter) == field_count for header_iter in header[1:]):\n raise ParserError(\"Header rows must have an equal number of columns.\")\n\n def extract(r):\n return tuple(r[i] for i in range(field_count) if i not in sic)\n\n columns = list(zip(*(extract(r) for r in header)))\n names = columns.copy()\n for single_ic in sorted(ic):\n names.insert(single_ic, single_ic)\n\n # Clean the column names (if we have an index_col).\n if len(ic):\n col_names = [\n r[ic[0]]\n if ((r[ic[0]] is not None) and r[ic[0]] not in self.unnamed_cols)\n else None\n for r in header\n ]\n else:\n col_names = [None] * len(header)\n\n passed_names = True\n\n return names, index_names, col_names, passed_names\n\n @final\n def _maybe_dedup_names(self, names: Sequence[Hashable]) -> Sequence[Hashable]:\n # see gh-7160 and gh-9424: this helps to provide\n # immediate alleviation of the duplicate names\n # issue and appears to be satisfactory to users,\n # but ultimately, not needing to butcher the names\n # would be nice!\n if self.mangle_dupe_cols:\n names = list(names) # so we can index\n counts: DefaultDict[Hashable, int] = defaultdict(int)\n is_potential_mi = _is_potential_multi_index(names, self.index_col)\n\n for i, col in enumerate(names):\n cur_count = counts[col]\n\n while cur_count > 0:\n counts[col] = cur_count + 1\n\n if is_potential_mi:\n # for mypy\n assert isinstance(col, tuple)\n col = col[:-1] + (f\"{col[-1]}.{cur_count}\",)\n else:\n col = f\"{col}.{cur_count}\"\n cur_count = counts[col]\n\n names[i] = col\n counts[col] = cur_count + 1\n\n return names\n\n @final\n def _maybe_make_multi_index_columns(\n self,\n columns: Sequence[Hashable],\n col_names: Sequence[Hashable] | None = None,\n ) -> Sequence[Hashable] | MultiIndex:\n # possibly create a column mi here\n if _is_potential_multi_index(columns):\n list_columns = cast(List[Tuple], columns)\n return MultiIndex.from_tuples(list_columns, names=col_names)\n return columns\n\n @final\n def _make_index(\n self, data, alldata, columns, indexnamerow=False\n ) -> tuple[Index | None, Sequence[Hashable] | MultiIndex]:\n index: Index | None\n if not is_index_col(self.index_col) or not self.index_col:\n index = None\n\n elif not self._has_complex_date_col:\n simple_index = self._get_simple_index(alldata, columns)\n index = self._agg_index(simple_index)\n elif self._has_complex_date_col:\n if not self._name_processed:\n (self.index_names, _, self.index_col) = self._clean_index_names(\n list(columns), self.index_col\n )\n self._name_processed = True\n date_index = self._get_complex_date_index(data, columns)\n index = self._agg_index(date_index, try_parse_dates=False)\n\n # add names for the index\n if indexnamerow:\n coffset = len(indexnamerow) - len(columns)\n assert index is not None\n index = index.set_names(indexnamerow[:coffset])\n\n # maybe create a mi on the columns\n columns = self._maybe_make_multi_index_columns(columns, self.col_names)\n\n return index, columns\n\n @final\n def _get_simple_index(self, data, columns):\n def ix(col):\n if not isinstance(col, str):\n return col\n raise ValueError(f\"Index {col} invalid\")\n\n to_remove = []\n index = []\n for idx in self.index_col:\n i = ix(idx)\n to_remove.append(i)\n index.append(data[i])\n\n # remove index items from content and columns, don't pop in\n # loop\n for i in sorted(to_remove, reverse=True):\n data.pop(i)\n if not self._implicit_index:\n columns.pop(i)\n\n return index\n\n @final\n def _get_complex_date_index(self, data, col_names):\n def _get_name(icol):\n if isinstance(icol, str):\n return icol\n\n if col_names is None:\n raise ValueError(f\"Must supply column order to use {icol!s} as index\")\n\n for i, c in enumerate(col_names):\n if i == icol:\n return c\n\n to_remove = []\n index = []\n for idx in self.index_col:\n name = _get_name(idx)\n to_remove.append(name)\n index.append(data[name])\n\n # remove index items from content and columns, don't pop in\n # loop\n for c in sorted(to_remove, reverse=True):\n data.pop(c)\n col_names.remove(c)\n\n return index\n\n def _clean_mapping(self, mapping):\n \"\"\"converts col numbers to names\"\"\"\n if not isinstance(mapping, dict):\n return mapping\n clean = {}\n for col, v in mapping.items():\n # for mypy\n assert self.orig_names is not None\n if isinstance(col, int) and col not in self.orig_names:\n col = self.orig_names[col]\n clean[col] = v\n return clean\n\n @final\n def _agg_index(self, index, try_parse_dates: bool = True) -> Index:\n arrays = []\n\n for i, arr in enumerate(index):\n\n if try_parse_dates and self._should_parse_dates(i):\n arr = self._date_conv(arr)\n\n if self.na_filter:\n col_na_values = self.na_values\n col_na_fvalues = self.na_fvalues\n else:\n col_na_values = set()\n col_na_fvalues = set()\n\n if isinstance(self.na_values, dict):\n assert self.index_names is not None\n col_name = self.index_names[i]\n if col_name is not None:\n col_na_values, col_na_fvalues = _get_na_values(\n col_name, self.na_values, self.na_fvalues, self.keep_default_na\n )\n\n clean_dtypes = self._clean_mapping(self.dtype)\n\n cast_type = None\n if isinstance(clean_dtypes, dict) and self.index_names is not None:\n cast_type = clean_dtypes.get(self.index_names[i], None)\n\n try_num_bool = not (cast_type and is_string_dtype(cast_type))\n\n arr, _ = self._infer_types(\n arr, col_na_values | col_na_fvalues, try_num_bool\n )\n arrays.append(arr)\n\n names = self.index_names\n index = ensure_index_from_sequences(arrays, names)\n\n return index\n\n @final\n def _convert_to_ndarrays(\n self,\n dct: Mapping,\n na_values,\n na_fvalues,\n verbose: bool = False,\n converters=None,\n dtypes=None,\n ):\n result = {}\n for c, values in dct.items():\n conv_f = None if converters is None else converters.get(c, None)\n if isinstance(dtypes, dict):\n cast_type = dtypes.get(c, None)\n else:\n # single dtype or None\n cast_type = dtypes\n\n if self.na_filter:\n col_na_values, col_na_fvalues = _get_na_values(\n c, na_values, na_fvalues, self.keep_default_na\n )\n else:\n col_na_values, col_na_fvalues = set(), set()\n\n if c in self._parse_date_cols:\n # GH#26203 Do not convert columns which get converted to dates\n # but replace nans to ensure to_datetime works\n mask = algorithms.isin(values, set(col_na_values) | col_na_fvalues)\n np.putmask(values, mask, np.nan)\n result[c] = values\n continue\n\n if conv_f is not None:\n # conv_f applied to data before inference\n if cast_type is not None:\n warnings.warn(\n (\n \"Both a converter and dtype were specified \"\n f\"for column {c} - only the converter will be used.\"\n ),\n ParserWarning,\n stacklevel=find_stack_level(),\n )\n\n try:\n values = lib.map_infer(values, conv_f)\n except ValueError:\n # error: Argument 2 to \"isin\" has incompatible type \"List[Any]\";\n # expected \"Union[Union[ExtensionArray, ndarray], Index, Series]\"\n mask = algorithms.isin(\n values, list(na_values) # type: ignore[arg-type]\n ).view(np.uint8)\n values = lib.map_infer_mask(values, conv_f, mask)\n\n cvals, na_count = self._infer_types(\n values, set(col_na_values) | col_na_fvalues, try_num_bool=False\n )\n else:\n is_ea = is_extension_array_dtype(cast_type)\n is_str_or_ea_dtype = is_ea or is_string_dtype(cast_type)\n # skip inference if specified dtype is object\n # or casting to an EA\n try_num_bool = not (cast_type and is_str_or_ea_dtype)\n\n # general type inference and conversion\n cvals, na_count = self._infer_types(\n values, set(col_na_values) | col_na_fvalues, try_num_bool\n )\n\n # type specified in dtype param or cast_type is an EA\n if cast_type and (\n not is_dtype_equal(cvals, cast_type)\n or is_extension_array_dtype(cast_type)\n ):\n if not is_ea and na_count > 0:\n try:\n if is_bool_dtype(cast_type):\n raise ValueError(\n f\"Bool column has NA values in column {c}\"\n )\n except (AttributeError, TypeError):\n # invalid input to is_bool_dtype\n pass\n cast_type = pandas_dtype(cast_type)\n cvals = self._cast_types(cvals, cast_type, c)\n\n result[c] = cvals\n if verbose and na_count:\n print(f\"Filled {na_count} NA values in column {c!s}\")\n return result\n\n @final\n def _set_noconvert_dtype_columns(\n self, col_indices: list[int], names: Sequence[Hashable]\n ) -> set[int]:\n \"\"\"\n Set the columns that should not undergo dtype conversions.\n\n Currently, any column that is involved with date parsing will not\n undergo such conversions. If usecols is specified, the positions of the columns\n not to cast is relative to the usecols not to all columns.\n\n Parameters\n ----------\n col_indices: The indices specifying order and positions of the columns\n names: The column names which order is corresponding with the order\n of col_indices\n\n Returns\n -------\n A set of integers containing the positions of the columns not to convert.\n \"\"\"\n usecols: list[int] | list[str] | None\n noconvert_columns = set()\n if self.usecols_dtype == \"integer\":\n # A set of integers will be converted to a list in\n # the correct order every single time.\n usecols = sorted(self.usecols)\n elif callable(self.usecols) or self.usecols_dtype not in (\"empty\", None):\n # The names attribute should have the correct columns\n # in the proper order for indexing with parse_dates.\n usecols = col_indices\n else:\n # Usecols is empty.\n usecols = None\n\n def _set(x) -> int:\n if usecols is not None and is_integer(x):\n x = usecols[x]\n\n if not is_integer(x):\n x = col_indices[names.index(x)]\n\n return x\n\n if isinstance(self.parse_dates, list):\n for val in self.parse_dates:\n if isinstance(val, list):\n for k in val:\n noconvert_columns.add(_set(k))\n else:\n noconvert_columns.add(_set(val))\n\n elif isinstance(self.parse_dates, dict):\n for val in self.parse_dates.values():\n if isinstance(val, list):\n for k in val:\n noconvert_columns.add(_set(k))\n else:\n noconvert_columns.add(_set(val))\n\n elif self.parse_dates:\n if isinstance(self.index_col, list):\n for k in self.index_col:\n noconvert_columns.add(_set(k))\n elif self.index_col is not None:\n noconvert_columns.add(_set(self.index_col))\n\n return noconvert_columns\n\n def _infer_types(self, values, na_values, try_num_bool=True):\n \"\"\"\n Infer types of values, possibly casting\n\n Parameters\n ----------\n values : ndarray\n na_values : set\n try_num_bool : bool, default try\n try to cast values to numeric (first preference) or boolean\n\n Returns\n -------\n converted : ndarray\n na_count : int\n \"\"\"\n na_count = 0\n if issubclass(values.dtype.type, (np.number, np.bool_)):\n # If our array has numeric dtype, we don't have to check for strings in isin\n na_values = np.array([val for val in na_values if not isinstance(val, str)])\n mask = algorithms.isin(values, na_values)\n na_count = mask.astype(\"uint8\", copy=False).sum()\n if na_count > 0:\n if is_integer_dtype(values):\n values = values.astype(np.float64)\n np.putmask(values, mask, np.nan)\n return values, na_count\n\n if try_num_bool and is_object_dtype(values.dtype):\n # exclude e.g DatetimeIndex here\n try:\n result, _ = lib.maybe_convert_numeric(values, na_values, False)\n except (ValueError, TypeError):\n # e.g. encountering datetime string gets ValueError\n # TypeError can be raised in floatify\n result = values\n na_count = parsers.sanitize_objects(result, na_values)\n else:\n na_count = isna(result).sum()\n else:\n result = values\n if values.dtype == np.object_:\n na_count = parsers.sanitize_objects(values, na_values)\n\n if result.dtype == np.object_ and try_num_bool:\n result, _ = libops.maybe_convert_bool(\n np.asarray(values),\n true_values=self.true_values,\n false_values=self.false_values,\n )\n\n return result, na_count\n\n def _cast_types(self, values, cast_type, column):\n \"\"\"\n Cast values to specified type\n\n Parameters\n ----------\n values : ndarray\n cast_type : string or np.dtype\n dtype to cast values to\n column : string\n column name - used only for error reporting\n\n Returns\n -------\n converted : ndarray\n \"\"\"\n if is_categorical_dtype(cast_type):\n known_cats = (\n isinstance(cast_type, CategoricalDtype)\n and cast_type.categories is not None\n )\n\n if not is_object_dtype(values) and not known_cats:\n # TODO: this is for consistency with\n # c-parser which parses all categories\n # as strings\n\n values = astype_nansafe(values, np.dtype(str))\n\n cats = Index(values).unique().dropna()\n values = Categorical._from_inferred_categories(\n cats, cats.get_indexer(values), cast_type, true_values=self.true_values\n )\n\n # use the EA's implementation of casting\n elif is_extension_array_dtype(cast_type):\n # ensure cast_type is an actual dtype and not a string\n cast_type = pandas_dtype(cast_type)\n array_type = cast_type.construct_array_type()\n try:\n if is_bool_dtype(cast_type):\n return array_type._from_sequence_of_strings(\n values,\n dtype=cast_type,\n true_values=self.true_values,\n false_values=self.false_values,\n )\n else:\n return array_type._from_sequence_of_strings(values, dtype=cast_type)\n except NotImplementedError as err:\n raise NotImplementedError(\n f\"Extension Array: {array_type} must implement \"\n \"_from_sequence_of_strings in order to be used in parser methods\"\n ) from err\n\n else:\n try:\n values = astype_nansafe(values, cast_type, copy=True, skipna=True)\n except ValueError as err:\n raise ValueError(\n f\"Unable to convert column {column} to type {cast_type}\"\n ) from err\n return values\n\n @overload\n def _do_date_conversions(\n self,\n names: Index,\n data: DataFrame,\n ) -> tuple[Sequence[Hashable] | Index, DataFrame]:\n ...\n\n @overload\n def _do_date_conversions(\n self,\n names: Sequence[Hashable],\n data: Mapping[Hashable, ArrayLike],\n ) -> tuple[Sequence[Hashable], Mapping[Hashable, ArrayLike]]:\n ...\n\n def _do_date_conversions(\n self,\n names: Sequence[Hashable] | Index,\n data: Mapping[Hashable, ArrayLike] | DataFrame,\n ) -> tuple[Sequence[Hashable] | Index, Mapping[Hashable, ArrayLike] | DataFrame]:\n # returns data, columns\n\n if self.parse_dates is not None:\n data, names = _process_date_conversion(\n data,\n self._date_conv,\n self.parse_dates,\n self.index_col,\n self.index_names,\n names,\n keep_date_col=self.keep_date_col,\n )\n\n return names, data\n\n def _check_data_length(\n self,\n columns: Sequence[Hashable],\n data: Sequence[ArrayLike],\n ) -> None:\n \"\"\"Checks if length of data is equal to length of column names.\n\n One set of trailing commas is allowed. self.index_col not False\n results in a ParserError previously when lengths do not match.\n\n Parameters\n ----------\n columns: list of column names\n data: list of array-likes containing the data column-wise.\n \"\"\"\n if not self.index_col and len(columns) != len(data) and columns:\n if len(columns) == len(data) - 1 and np.all(\n (is_object_dtype(data[-1]) and data[-1] == \"\") | isna(data[-1])\n ):\n return\n warnings.warn(\n \"Length of header or names does not match length of data. This leads \"\n \"to a loss of data with index_col=False.\",\n ParserWarning,\n stacklevel=find_stack_level(),\n )\n\n @overload\n def _evaluate_usecols(\n self,\n usecols: set[int] | Callable[[Hashable], object],\n names: Sequence[Hashable],\n ) -> set[int]:\n ...\n\n @overload\n def _evaluate_usecols(\n self, usecols: set[str], names: Sequence[Hashable]\n ) -> set[str]:\n ...\n\n def _evaluate_usecols(\n self,\n usecols: Callable[[Hashable], object] | set[str] | set[int],\n names: Sequence[Hashable],\n ) -> set[str] | set[int]:\n \"\"\"\n Check whether or not the 'usecols' parameter\n is a callable. If so, enumerates the 'names'\n parameter and returns a set of indices for\n each entry in 'names' that evaluates to True.\n If not a callable, returns 'usecols'.\n \"\"\"\n if callable(usecols):\n return {i for i, name in enumerate(names) if usecols(name)}\n return usecols\n\n def _validate_usecols_names(self, usecols, names):\n \"\"\"\n Validates that all usecols are present in a given\n list of names. If not, raise a ValueError that\n shows what usecols are missing.\n\n Parameters\n ----------\n usecols : iterable of usecols\n The columns to validate are present in names.\n names : iterable of names\n The column names to check against.\n\n Returns\n -------\n usecols : iterable of usecols\n The `usecols` parameter if the validation succeeds.\n\n Raises\n ------\n ValueError : Columns were missing. Error message will list them.\n \"\"\"\n missing = [c for c in usecols if c not in names]\n if len(missing) > 0:\n raise ValueError(\n f\"Usecols do not match columns, columns expected but not found: \"\n f\"{missing}\"\n )\n\n return usecols\n\n def _validate_usecols_arg(self, usecols):\n \"\"\"\n Validate the 'usecols' parameter.\n\n Checks whether or not the 'usecols' parameter contains all integers\n (column selection by index), strings (column by name) or is a callable.\n Raises a ValueError if that is not the case.\n\n Parameters\n ----------\n usecols : list-like, callable, or None\n List of columns to use when parsing or a callable that can be used\n to filter a list of table columns.\n\n Returns\n -------\n usecols_tuple : tuple\n A tuple of (verified_usecols, usecols_dtype).\n\n 'verified_usecols' is either a set if an array-like is passed in or\n 'usecols' if a callable or None is passed in.\n\n 'usecols_dtype` is the inferred dtype of 'usecols' if an array-like\n is passed in or None if a callable or None is passed in.\n \"\"\"\n msg = (\n \"'usecols' must either be list-like of all strings, all unicode, \"\n \"all integers or a callable.\"\n )\n if usecols is not None:\n if callable(usecols):\n return usecols, None\n\n if not is_list_like(usecols):\n # see gh-20529\n #\n # Ensure it is iterable container but not string.\n raise ValueError(msg)\n\n usecols_dtype = lib.infer_dtype(usecols, skipna=False)\n\n if usecols_dtype not in (\"empty\", \"integer\", \"string\"):\n raise ValueError(msg)\n\n usecols = set(usecols)\n\n return usecols, usecols_dtype\n return usecols, None\n\n def _clean_index_names(self, columns, index_col):\n if not is_index_col(index_col):\n return None, columns, index_col\n\n columns = list(columns)\n\n # In case of no rows and multiindex columns we have to set index_names to\n # list of Nones GH#38292\n if not columns:\n return [None] * len(index_col), columns, index_col\n\n cp_cols = list(columns)\n index_names: list[str | int | None] = []\n\n # don't mutate\n index_col = list(index_col)\n\n for i, c in enumerate(index_col):\n if isinstance(c, str):\n index_names.append(c)\n for j, name in enumerate(cp_cols):\n if name == c:\n index_col[i] = j\n columns.remove(name)\n break\n else:\n name = cp_cols[c]\n columns.remove(name)\n index_names.append(name)\n\n # Only clean index names that were placeholders.\n for i, name in enumerate(index_names):\n if isinstance(name, str) and name in self.unnamed_cols:\n index_names[i] = None\n\n return index_names, columns, index_col\n\n def _get_empty_meta(\n self, columns, index_col, index_names, dtype: DtypeArg | None = None\n ):\n columns = list(columns)\n\n # Convert `dtype` to a defaultdict of some kind.\n # This will enable us to write `dtype[col_name]`\n # without worrying about KeyError issues later on.\n if not is_dict_like(dtype):\n # if dtype == None, default will be object.\n default_dtype = dtype or object\n # error: Argument 1 to \"defaultdict\" has incompatible type \"Callable[[],\n # Union[ExtensionDtype, str, dtype[Any], Type[object], Dict[Hashable,\n # Union[ExtensionDtype, Union[str, dtype[Any]], Type[str], Type[float],\n # Type[int], Type[complex], Type[bool], Type[object]]]]]\"; expected\n # \"Optional[Callable[[], Union[ExtensionDtype, str, dtype[Any],\n # Type[object]]]]\"\n # error: Incompatible return value type (got \"Union[ExtensionDtype, str,\n # dtype[Any], Type[object], Dict[Hashable, Union[ExtensionDtype, Union[str,\n # dtype[Any]], Type[str], Type[float], Type[int], Type[complex], Type[bool],\n # Type[object]]]]\", expected \"Union[ExtensionDtype, str, dtype[Any],\n # Type[object]]\")\n dtype = defaultdict(\n lambda: default_dtype # type: ignore[arg-type, return-value]\n )\n else:\n dtype = cast(dict, dtype)\n dtype = defaultdict(\n lambda: object,\n {columns[k] if is_integer(k) else k: v for k, v in dtype.items()},\n )\n\n # Even though we have no data, the \"index\" of the empty DataFrame\n # could for example still be an empty MultiIndex. Thus, we need to\n # check whether we have any index columns specified, via either:\n #\n # 1) index_col (column indices)\n # 2) index_names (column names)\n #\n # Both must be non-null to ensure a successful construction. Otherwise,\n # we have to create a generic empty Index.\n if (index_col is None or index_col is False) or index_names is None:\n index = Index([])\n else:\n data = [Series([], dtype=dtype[name]) for name in index_names]\n index = ensure_index_from_sequences(data, names=index_names)\n index_col.sort()\n\n for i, n in enumerate(index_col):\n columns.pop(n - i)\n\n col_dict = {col_name: Series([], dtype=dtype[col_name]) for col_name in columns}\n\n return index, columns, col_dict\n\n\ndef _make_date_converter(\n date_parser=None, dayfirst=False, infer_datetime_format=False, cache_dates=True\n):\n def converter(*date_cols):\n if date_parser is None:\n strs = parsing.concat_date_cols(date_cols)\n\n try:\n return tools.to_datetime(\n ensure_object(strs),\n utc=None,\n dayfirst=dayfirst,\n errors=\"ignore\",\n infer_datetime_format=infer_datetime_format,\n cache=cache_dates,\n ).to_numpy()\n\n except ValueError:\n return tools.to_datetime(\n parsing.try_parse_dates(strs, dayfirst=dayfirst), cache=cache_dates\n )\n else:\n try:\n result = tools.to_datetime(\n date_parser(*date_cols), errors=\"ignore\", cache=cache_dates\n )\n if isinstance(result, datetime.datetime):\n raise Exception(\"scalar parser\")\n return result\n except Exception:\n try:\n return tools.to_datetime(\n parsing.try_parse_dates(\n parsing.concat_date_cols(date_cols),\n parser=date_parser,\n dayfirst=dayfirst,\n ),\n errors=\"ignore\",\n )\n except Exception:\n return generic_parser(date_parser, *date_cols)\n\n return converter\n\n\nparser_defaults = {\n \"delimiter\": None,\n \"escapechar\": None,\n \"quotechar\": '\"',\n \"quoting\": csv.QUOTE_MINIMAL,\n \"doublequote\": True,\n \"skipinitialspace\": False,\n \"lineterminator\": None,\n \"header\": \"infer\",\n \"index_col\": None,\n \"names\": None,\n \"prefix\": None,\n \"skiprows\": None,\n \"skipfooter\": 0,\n \"nrows\": None,\n \"na_values\": None,\n \"keep_default_na\": True,\n \"true_values\": None,\n \"false_values\": None,\n \"converters\": None,\n \"dtype\": None,\n \"cache_dates\": True,\n \"thousands\": None,\n \"comment\": None,\n \"decimal\": \".\",\n # 'engine': 'c',\n \"parse_dates\": False,\n \"keep_date_col\": False,\n \"dayfirst\": False,\n \"date_parser\": None,\n \"usecols\": None,\n # 'iterator': False,\n \"chunksize\": None,\n \"verbose\": False,\n \"encoding\": None,\n \"squeeze\": None,\n \"compression\": None,\n \"mangle_dupe_cols\": True,\n \"infer_datetime_format\": False,\n \"skip_blank_lines\": True,\n \"encoding_errors\": \"strict\",\n \"on_bad_lines\": ParserBase.BadLineHandleMethod.ERROR,\n \"error_bad_lines\": None,\n \"warn_bad_lines\": None,\n}\n\n\ndef _process_date_conversion(\n data_dict,\n converter: Callable,\n parse_spec,\n index_col,\n index_names,\n columns,\n keep_date_col: bool = False,\n):\n def _isindex(colspec):\n return (isinstance(index_col, list) and colspec in index_col) or (\n isinstance(index_names, list) and colspec in index_names\n )\n\n new_cols = []\n new_data = {}\n\n orig_names = columns\n columns = list(columns)\n\n date_cols = set()\n\n if parse_spec is None or isinstance(parse_spec, bool):\n return data_dict, columns\n\n if isinstance(parse_spec, list):\n # list of column lists\n for colspec in parse_spec:\n if is_scalar(colspec) or isinstance(colspec, tuple):\n if isinstance(colspec, int) and colspec not in data_dict:\n colspec = orig_names[colspec]\n if _isindex(colspec):\n continue\n # Pyarrow engine returns Series which we need to convert to\n # numpy array before converter, its a no-op for other parsers\n data_dict[colspec] = converter(np.asarray(data_dict[colspec]))\n else:\n new_name, col, old_names = _try_convert_dates(\n converter, colspec, data_dict, orig_names\n )\n if new_name in data_dict:\n raise ValueError(f\"New date column already in dict {new_name}\")\n new_data[new_name] = col\n new_cols.append(new_name)\n date_cols.update(old_names)\n\n elif isinstance(parse_spec, dict):\n # dict of new name to column list\n for new_name, colspec in parse_spec.items():\n if new_name in data_dict:\n raise ValueError(f\"Date column {new_name} already in dict\")\n\n _, col, old_names = _try_convert_dates(\n converter, colspec, data_dict, orig_names\n )\n\n new_data[new_name] = col\n\n # If original column can be converted to date we keep the converted values\n # This can only happen if values are from single column\n if len(colspec) == 1:\n new_data[colspec[0]] = col\n\n new_cols.append(new_name)\n date_cols.update(old_names)\n\n data_dict.update(new_data)\n new_cols.extend(columns)\n\n if not keep_date_col:\n for c in list(date_cols):\n data_dict.pop(c)\n new_cols.remove(c)\n\n return data_dict, new_cols\n\n\ndef _try_convert_dates(parser: Callable, colspec, data_dict, columns):\n colset = set(columns)\n colnames = []\n\n for c in colspec:\n if c in colset:\n colnames.append(c)\n elif isinstance(c, int) and c not in columns:\n colnames.append(columns[c])\n else:\n colnames.append(c)\n\n new_name: tuple | str\n if all(isinstance(x, tuple) for x in colnames):\n new_name = tuple(map(\"_\".join, zip(*colnames)))\n else:\n new_name = \"_\".join([str(x) for x in colnames])\n to_parse = [np.asarray(data_dict[c]) for c in colnames if c in data_dict]\n\n new_col = parser(*to_parse)\n return new_name, new_col, colnames\n\n\ndef _get_na_values(col, na_values, na_fvalues, keep_default_na):\n \"\"\"\n Get the NaN values for a given column.\n\n Parameters\n ----------\n col : str\n The name of the column.\n na_values : array-like, dict\n The object listing the NaN values as strings.\n na_fvalues : array-like, dict\n The object listing the NaN values as floats.\n keep_default_na : bool\n If `na_values` is a dict, and the column is not mapped in the\n dictionary, whether to return the default NaN values or the empty set.\n\n Returns\n -------\n nan_tuple : A length-two tuple composed of\n\n 1) na_values : the string NaN values for that column.\n 2) na_fvalues : the float NaN values for that column.\n \"\"\"\n if isinstance(na_values, dict):\n if col in na_values:\n return na_values[col], na_fvalues[col]\n else:\n if keep_default_na:\n return STR_NA_VALUES, set()\n\n return set(), set()\n else:\n return na_values, na_fvalues\n\n\ndef _is_potential_multi_index(\n columns: Sequence[Hashable] | MultiIndex,\n index_col: bool | Sequence[int] | None = None,\n) -> bool:\n \"\"\"\n Check whether or not the `columns` parameter\n could be converted into a MultiIndex.\n\n Parameters\n ----------\n columns : array-like\n Object which may or may not be convertible into a MultiIndex\n index_col : None, bool or list, optional\n Column or columns to use as the (possibly hierarchical) index\n\n Returns\n -------\n bool : Whether or not columns could become a MultiIndex\n \"\"\"\n if index_col is None or isinstance(index_col, bool):\n index_col = []\n\n return bool(\n len(columns)\n and not isinstance(columns, MultiIndex)\n and all(isinstance(c, tuple) for c in columns if c not in list(index_col))\n )\n\n\ndef _validate_parse_dates_arg(parse_dates):\n \"\"\"\n Check whether or not the 'parse_dates' parameter\n is a non-boolean scalar. Raises a ValueError if\n that is the case.\n \"\"\"\n msg = (\n \"Only booleans, lists, and dictionaries are accepted \"\n \"for the 'parse_dates' parameter\"\n )\n\n if parse_dates is not None:\n if is_scalar(parse_dates):\n if not lib.is_bool(parse_dates):\n raise TypeError(msg)\n\n elif not isinstance(parse_dates, (list, dict)):\n raise TypeError(msg)\n\n return parse_dates\n\n\ndef is_index_col(col) -> bool:\n return col is not None and col is not False\n",
"\"\"\"\ndata hash pandas / numpy objects\n\"\"\"\nfrom __future__ import annotations\n\nimport itertools\nfrom typing import (\n TYPE_CHECKING,\n Hashable,\n Iterable,\n Iterator,\n cast,\n)\n\nimport numpy as np\n\nfrom pandas._libs import lib\nfrom pandas._libs.hashing import hash_object_array\nfrom pandas._typing import ArrayLike\n\nfrom pandas.core.dtypes.common import (\n is_categorical_dtype,\n is_list_like,\n)\nfrom pandas.core.dtypes.generic import (\n ABCDataFrame,\n ABCExtensionArray,\n ABCIndex,\n ABCMultiIndex,\n ABCSeries,\n)\n\nif TYPE_CHECKING:\n from pandas import (\n Categorical,\n DataFrame,\n Index,\n MultiIndex,\n Series,\n )\n\n\n# 16 byte long hashing key\n_default_hash_key = \"0123456789123456\"\n\n\ndef combine_hash_arrays(arrays: Iterator[np.ndarray], num_items: int) -> np.ndarray:\n \"\"\"\n Parameters\n ----------\n arrays : Iterator[np.ndarray]\n num_items : int\n\n Returns\n -------\n np.ndarray[uint64]\n\n Should be the same as CPython's tupleobject.c\n \"\"\"\n try:\n first = next(arrays)\n except StopIteration:\n return np.array([], dtype=np.uint64)\n\n arrays = itertools.chain([first], arrays)\n\n mult = np.uint64(1000003)\n out = np.zeros_like(first) + np.uint64(0x345678)\n for i, a in enumerate(arrays):\n inverse_i = num_items - i\n out ^= a\n out *= mult\n mult += np.uint64(82520 + inverse_i + inverse_i)\n assert i + 1 == num_items, \"Fed in wrong num_items\"\n out += np.uint64(97531)\n return out\n\n\ndef hash_pandas_object(\n obj: Index | DataFrame | Series,\n index: bool = True,\n encoding: str = \"utf8\",\n hash_key: str | None = _default_hash_key,\n categorize: bool = True,\n) -> Series:\n \"\"\"\n Return a data hash of the Index/Series/DataFrame.\n\n Parameters\n ----------\n obj : Index, Series, or DataFrame\n index : bool, default True\n Include the index in the hash (if Series/DataFrame).\n encoding : str, default 'utf8'\n Encoding for data & key when strings.\n hash_key : str, default _default_hash_key\n Hash_key for string key to encode.\n categorize : bool, default True\n Whether to first categorize object arrays before hashing. This is more\n efficient when the array contains duplicate values.\n\n Returns\n -------\n Series of uint64, same length as the object\n \"\"\"\n from pandas import Series\n\n if hash_key is None:\n hash_key = _default_hash_key\n\n if isinstance(obj, ABCMultiIndex):\n return Series(hash_tuples(obj, encoding, hash_key), dtype=\"uint64\", copy=False)\n\n elif isinstance(obj, ABCIndex):\n h = hash_array(obj._values, encoding, hash_key, categorize).astype(\n \"uint64\", copy=False\n )\n ser = Series(h, index=obj, dtype=\"uint64\", copy=False)\n\n elif isinstance(obj, ABCSeries):\n h = hash_array(obj._values, encoding, hash_key, categorize).astype(\n \"uint64\", copy=False\n )\n if index:\n index_iter = (\n hash_pandas_object(\n obj.index,\n index=False,\n encoding=encoding,\n hash_key=hash_key,\n categorize=categorize,\n )._values\n for _ in [None]\n )\n arrays = itertools.chain([h], index_iter)\n h = combine_hash_arrays(arrays, 2)\n\n ser = Series(h, index=obj.index, dtype=\"uint64\", copy=False)\n\n elif isinstance(obj, ABCDataFrame):\n hashes = (\n hash_array(series._values, encoding, hash_key, categorize)\n for _, series in obj.items()\n )\n num_items = len(obj.columns)\n if index:\n index_hash_generator = (\n hash_pandas_object(\n obj.index,\n index=False,\n encoding=encoding,\n hash_key=hash_key,\n categorize=categorize,\n )._values\n for _ in [None]\n )\n num_items += 1\n\n # keep `hashes` specifically a generator to keep mypy happy\n _hashes = itertools.chain(hashes, index_hash_generator)\n hashes = (x for x in _hashes)\n h = combine_hash_arrays(hashes, num_items)\n\n ser = Series(h, index=obj.index, dtype=\"uint64\", copy=False)\n else:\n raise TypeError(f\"Unexpected type for hashing {type(obj)}\")\n\n return ser\n\n\ndef hash_tuples(\n vals: MultiIndex | Iterable[tuple[Hashable, ...]],\n encoding: str = \"utf8\",\n hash_key: str = _default_hash_key,\n) -> np.ndarray:\n \"\"\"\n Hash an MultiIndex / listlike-of-tuples efficiently.\n\n Parameters\n ----------\n vals : MultiIndex or listlike-of-tuples\n encoding : str, default 'utf8'\n hash_key : str, default _default_hash_key\n\n Returns\n -------\n ndarray[np.uint64] of hashed values\n \"\"\"\n if not is_list_like(vals):\n raise TypeError(\"must be convertible to a list-of-tuples\")\n\n from pandas import (\n Categorical,\n MultiIndex,\n )\n\n if not isinstance(vals, ABCMultiIndex):\n mi = MultiIndex.from_tuples(vals)\n else:\n mi = vals\n\n # create a list-of-Categoricals\n cat_vals = [\n Categorical(mi.codes[level], mi.levels[level], ordered=False, fastpath=True)\n for level in range(mi.nlevels)\n ]\n\n # hash the list-of-ndarrays\n hashes = (\n _hash_categorical(cat, encoding=encoding, hash_key=hash_key) for cat in cat_vals\n )\n h = combine_hash_arrays(hashes, len(cat_vals))\n\n return h\n\n\ndef _hash_categorical(cat: Categorical, encoding: str, hash_key: str) -> np.ndarray:\n \"\"\"\n Hash a Categorical by hashing its categories, and then mapping the codes\n to the hashes\n\n Parameters\n ----------\n cat : Categorical\n encoding : str\n hash_key : str\n\n Returns\n -------\n ndarray[np.uint64] of hashed values, same size as len(c)\n \"\"\"\n # Convert ExtensionArrays to ndarrays\n values = np.asarray(cat.categories._values)\n hashed = hash_array(values, encoding, hash_key, categorize=False)\n\n # we have uint64, as we don't directly support missing values\n # we don't want to use take_nd which will coerce to float\n # instead, directly construct the result with a\n # max(np.uint64) as the missing value indicator\n #\n # TODO: GH 15362\n\n mask = cat.isna()\n if len(hashed):\n result = hashed.take(cat.codes)\n else:\n result = np.zeros(len(mask), dtype=\"uint64\")\n\n if mask.any():\n result[mask] = lib.u8max\n\n return result\n\n\ndef hash_array(\n vals: ArrayLike,\n encoding: str = \"utf8\",\n hash_key: str = _default_hash_key,\n categorize: bool = True,\n) -> np.ndarray:\n \"\"\"\n Given a 1d array, return an array of deterministic integers.\n\n Parameters\n ----------\n vals : ndarray or ExtensionArray\n encoding : str, default 'utf8'\n Encoding for data & key when strings.\n hash_key : str, default _default_hash_key\n Hash_key for string key to encode.\n categorize : bool, default True\n Whether to first categorize object arrays before hashing. This is more\n efficient when the array contains duplicate values.\n\n Returns\n -------\n ndarray[np.uint64, ndim=1]\n Hashed values, same length as the vals.\n \"\"\"\n if not hasattr(vals, \"dtype\"):\n raise TypeError(\"must pass a ndarray-like\")\n dtype = vals.dtype\n\n # For categoricals, we hash the categories, then remap the codes to the\n # hash values. (This check is above the complex check so that we don't ask\n # numpy if categorical is a subdtype of complex, as it will choke).\n if is_categorical_dtype(dtype):\n vals = cast(\"Categorical\", vals)\n return _hash_categorical(vals, encoding, hash_key)\n\n elif isinstance(vals, ABCExtensionArray):\n vals, _ = vals._values_for_factorize()\n\n elif not isinstance(vals, np.ndarray):\n # GH#42003\n raise TypeError(\n \"hash_array requires np.ndarray or ExtensionArray, not \"\n f\"{type(vals).__name__}. Use hash_pandas_object instead.\"\n )\n\n return _hash_ndarray(vals, encoding, hash_key, categorize)\n\n\ndef _hash_ndarray(\n vals: np.ndarray,\n encoding: str = \"utf8\",\n hash_key: str = _default_hash_key,\n categorize: bool = True,\n) -> np.ndarray:\n \"\"\"\n See hash_array.__doc__.\n \"\"\"\n dtype = vals.dtype\n\n # we'll be working with everything as 64-bit values, so handle this\n # 128-bit value early\n if np.issubdtype(dtype, np.complex128):\n return hash_array(np.real(vals)) + 23 * hash_array(np.imag(vals))\n\n # First, turn whatever array this is into unsigned 64-bit ints, if we can\n # manage it.\n elif dtype == bool:\n vals = vals.astype(\"u8\")\n elif issubclass(dtype.type, (np.datetime64, np.timedelta64)):\n vals = vals.view(\"i8\").astype(\"u8\", copy=False)\n elif issubclass(dtype.type, np.number) and dtype.itemsize <= 8:\n vals = vals.view(f\"u{vals.dtype.itemsize}\").astype(\"u8\")\n else:\n # With repeated values, its MUCH faster to categorize object dtypes,\n # then hash and rename categories. We allow skipping the categorization\n # when the values are known/likely to be unique.\n if categorize:\n from pandas import (\n Categorical,\n Index,\n factorize,\n )\n\n codes, categories = factorize(vals, sort=False)\n cat = Categorical(\n codes, Index._with_infer(categories), ordered=False, fastpath=True\n )\n return _hash_categorical(cat, encoding, hash_key)\n\n try:\n vals = hash_object_array(vals, hash_key, encoding)\n except TypeError:\n # we have mixed types\n vals = hash_object_array(\n vals.astype(str).astype(object), hash_key, encoding\n )\n\n # Then, redistribute these 64-bit ints within the space of 64-bit ints\n vals ^= vals >> 30\n vals *= np.uint64(0xBF58476D1CE4E5B9)\n vals ^= vals >> 27\n vals *= np.uint64(0x94D049BB133111EB)\n vals ^= vals >> 31\n return vals\n",
"import numpy as np\nimport pytest\n\nfrom pandas.errors import UnsupportedFunctionCall\nimport pandas.util._test_decorators as td\n\nfrom pandas import (\n DataFrame,\n Series,\n Timedelta,\n concat,\n date_range,\n)\nimport pandas._testing as tm\nfrom pandas.api.indexers import BaseIndexer\n\n\[email protected](\n params=[\n \"triang\",\n \"blackman\",\n \"hamming\",\n \"bartlett\",\n \"bohman\",\n \"blackmanharris\",\n \"nuttall\",\n \"barthann\",\n ]\n)\ndef win_types(request):\n return request.param\n\n\[email protected](params=[\"kaiser\", \"gaussian\", \"general_gaussian\", \"exponential\"])\ndef win_types_special(request):\n return request.param\n\n\[email protected]_if_no_scipy\ndef test_constructor(frame_or_series):\n # GH 12669\n c = frame_or_series(range(5)).rolling\n\n # valid\n c(win_type=\"boxcar\", window=2, min_periods=1)\n c(win_type=\"boxcar\", window=2, min_periods=1, center=True)\n c(win_type=\"boxcar\", window=2, min_periods=1, center=False)\n\n\[email protected](\"w\", [2.0, \"foo\", np.array([2])])\[email protected]_if_no_scipy\ndef test_invalid_constructor(frame_or_series, w):\n # not valid\n\n c = frame_or_series(range(5)).rolling\n with pytest.raises(ValueError, match=\"min_periods must be an integer\"):\n c(win_type=\"boxcar\", window=2, min_periods=w)\n with pytest.raises(ValueError, match=\"center must be a boolean\"):\n c(win_type=\"boxcar\", window=2, min_periods=1, center=w)\n\n\[email protected](\"wt\", [\"foobar\", 1])\[email protected]_if_no_scipy\ndef test_invalid_constructor_wintype(frame_or_series, wt):\n c = frame_or_series(range(5)).rolling\n with pytest.raises(ValueError, match=\"Invalid win_type\"):\n c(win_type=wt, window=2)\n\n\[email protected]_if_no_scipy\ndef test_constructor_with_win_type(frame_or_series, win_types):\n # GH 12669\n c = frame_or_series(range(5)).rolling\n c(win_type=win_types, window=2)\n\n\[email protected](\"method\", [\"sum\", \"mean\"])\ndef test_numpy_compat(method):\n # see gh-12811\n w = Series([2, 4, 6]).rolling(window=2)\n\n msg = \"numpy operations are not valid with window objects\"\n\n with pytest.raises(UnsupportedFunctionCall, match=msg):\n getattr(w, method)(1, 2, 3)\n with pytest.raises(UnsupportedFunctionCall, match=msg):\n getattr(w, method)(dtype=np.float64)\n\n\[email protected]_if_no_scipy\[email protected](\"arg\", [\"median\", \"kurt\", \"skew\"])\ndef test_agg_function_support(arg):\n df = DataFrame({\"A\": np.arange(5)})\n roll = df.rolling(2, win_type=\"triang\")\n\n msg = f\"'{arg}' is not a valid function for 'Window' object\"\n with pytest.raises(AttributeError, match=msg):\n roll.agg(arg)\n\n with pytest.raises(AttributeError, match=msg):\n roll.agg([arg])\n\n with pytest.raises(AttributeError, match=msg):\n roll.agg({\"A\": arg})\n\n\[email protected]_if_no_scipy\ndef test_invalid_scipy_arg():\n # This error is raised by scipy\n msg = r\"boxcar\\(\\) got an unexpected\"\n with pytest.raises(TypeError, match=msg):\n Series(range(3)).rolling(1, win_type=\"boxcar\").mean(foo=\"bar\")\n\n\[email protected]_if_no_scipy\ndef test_constructor_with_win_type_invalid(frame_or_series):\n # GH 13383\n c = frame_or_series(range(5)).rolling\n\n msg = \"window must be an integer 0 or greater\"\n\n with pytest.raises(ValueError, match=msg):\n c(-1, win_type=\"boxcar\")\n\n\[email protected]_if_no_scipy\[email protected](\"ignore:can't resolve:ImportWarning\")\ndef test_window_with_args():\n # make sure that we are aggregating window functions correctly with arg\n r = Series(np.random.randn(100)).rolling(\n window=10, min_periods=1, win_type=\"gaussian\"\n )\n expected = concat([r.mean(std=10), r.mean(std=0.01)], axis=1)\n expected.columns = [\"<lambda>\", \"<lambda>\"]\n result = r.aggregate([lambda x: x.mean(std=10), lambda x: x.mean(std=0.01)])\n tm.assert_frame_equal(result, expected)\n\n def a(x):\n return x.mean(std=10)\n\n def b(x):\n return x.mean(std=0.01)\n\n expected = concat([r.mean(std=10), r.mean(std=0.01)], axis=1)\n expected.columns = [\"a\", \"b\"]\n result = r.aggregate([a, b])\n tm.assert_frame_equal(result, expected)\n\n\[email protected]_if_no_scipy\ndef test_win_type_with_method_invalid():\n with pytest.raises(\n NotImplementedError, match=\"'single' is the only supported method type.\"\n ):\n Series(range(1)).rolling(1, win_type=\"triang\", method=\"table\")\n\n\[email protected]_if_no_scipy\[email protected](\"arg\", [2000000000, \"2s\", Timedelta(\"2s\")])\ndef test_consistent_win_type_freq(arg):\n # GH 15969\n s = Series(range(1))\n with pytest.raises(ValueError, match=\"Invalid win_type freq\"):\n s.rolling(arg, win_type=\"freq\")\n\n\ndef test_win_type_freq_return_deprecation():\n freq_roll = Series(range(2), index=date_range(\"2020\", periods=2)).rolling(\"2s\")\n with tm.assert_produces_warning(FutureWarning):\n assert freq_roll.win_type == \"freq\"\n\n\[email protected]_if_no_scipy\ndef test_win_type_not_implemented():\n class CustomIndexer(BaseIndexer):\n def get_window_bounds(self, num_values, min_periods, center, closed):\n return np.array([0, 1]), np.array([1, 2])\n\n df = DataFrame({\"values\": range(2)})\n indexer = CustomIndexer()\n with pytest.raises(NotImplementedError, match=\"BaseIndexer subclasses not\"):\n df.rolling(indexer, win_type=\"boxcar\")\n\n\[email protected]_if_no_scipy\ndef test_cmov_mean():\n # GH 8238\n vals = np.array([6.95, 15.21, 4.72, 9.12, 13.81, 13.49, 16.68, 9.48, 10.63, 14.48])\n result = Series(vals).rolling(5, center=True).mean()\n expected_values = [\n np.nan,\n np.nan,\n 9.962,\n 11.27,\n 11.564,\n 12.516,\n 12.818,\n 12.952,\n np.nan,\n np.nan,\n ]\n expected = Series(expected_values)\n tm.assert_series_equal(expected, result)\n\n\[email protected]_if_no_scipy\ndef test_cmov_window():\n # GH 8238\n vals = np.array([6.95, 15.21, 4.72, 9.12, 13.81, 13.49, 16.68, 9.48, 10.63, 14.48])\n result = Series(vals).rolling(5, win_type=\"boxcar\", center=True).mean()\n expected_values = [\n np.nan,\n np.nan,\n 9.962,\n 11.27,\n 11.564,\n 12.516,\n 12.818,\n 12.952,\n np.nan,\n np.nan,\n ]\n expected = Series(expected_values)\n tm.assert_series_equal(expected, result)\n\n\[email protected]_if_no_scipy\ndef test_cmov_window_corner():\n # GH 8238\n # all nan\n vals = Series([np.nan] * 10)\n result = vals.rolling(5, center=True, win_type=\"boxcar\").mean()\n assert np.isnan(result).all()\n\n # empty\n vals = Series([], dtype=object)\n result = vals.rolling(5, center=True, win_type=\"boxcar\").mean()\n assert len(result) == 0\n\n # shorter than window\n vals = Series(np.random.randn(5))\n result = vals.rolling(10, win_type=\"boxcar\").mean()\n assert np.isnan(result).all()\n assert len(result) == 5\n\n\[email protected]_if_no_scipy\[email protected](\n \"f,xp\",\n [\n (\n \"mean\",\n [\n [np.nan, np.nan],\n [np.nan, np.nan],\n [9.252, 9.392],\n [8.644, 9.906],\n [8.87, 10.208],\n [6.81, 8.588],\n [7.792, 8.644],\n [9.05, 7.824],\n [np.nan, np.nan],\n [np.nan, np.nan],\n ],\n ),\n (\n \"std\",\n [\n [np.nan, np.nan],\n [np.nan, np.nan],\n [3.789706, 4.068313],\n [3.429232, 3.237411],\n [3.589269, 3.220810],\n [3.405195, 2.380655],\n [3.281839, 2.369869],\n [3.676846, 1.801799],\n [np.nan, np.nan],\n [np.nan, np.nan],\n ],\n ),\n (\n \"var\",\n [\n [np.nan, np.nan],\n [np.nan, np.nan],\n [14.36187, 16.55117],\n [11.75963, 10.48083],\n [12.88285, 10.37362],\n [11.59535, 5.66752],\n [10.77047, 5.61628],\n [13.51920, 3.24648],\n [np.nan, np.nan],\n [np.nan, np.nan],\n ],\n ),\n (\n \"sum\",\n [\n [np.nan, np.nan],\n [np.nan, np.nan],\n [46.26, 46.96],\n [43.22, 49.53],\n [44.35, 51.04],\n [34.05, 42.94],\n [38.96, 43.22],\n [45.25, 39.12],\n [np.nan, np.nan],\n [np.nan, np.nan],\n ],\n ),\n ],\n)\ndef test_cmov_window_frame(f, xp):\n # Gh 8238\n df = DataFrame(\n np.array(\n [\n [12.18, 3.64],\n [10.18, 9.16],\n [13.24, 14.61],\n [4.51, 8.11],\n [6.15, 11.44],\n [9.14, 6.21],\n [11.31, 10.67],\n [2.94, 6.51],\n [9.42, 8.39],\n [12.44, 7.34],\n ]\n )\n )\n xp = DataFrame(np.array(xp))\n\n roll = df.rolling(5, win_type=\"boxcar\", center=True)\n rs = getattr(roll, f)()\n\n tm.assert_frame_equal(xp, rs)\n\n\[email protected]_if_no_scipy\ndef test_cmov_window_na_min_periods():\n # min_periods\n vals = Series(np.random.randn(10))\n vals[4] = np.nan\n vals[8] = np.nan\n\n xp = vals.rolling(5, min_periods=4, center=True).mean()\n rs = vals.rolling(5, win_type=\"boxcar\", min_periods=4, center=True).mean()\n tm.assert_series_equal(xp, rs)\n\n\[email protected]_if_no_scipy\ndef test_cmov_window_regular(win_types):\n # GH 8238\n vals = np.array([6.95, 15.21, 4.72, 9.12, 13.81, 13.49, 16.68, 9.48, 10.63, 14.48])\n xps = {\n \"hamming\": [\n np.nan,\n np.nan,\n 8.71384,\n 9.56348,\n 12.38009,\n 14.03687,\n 13.8567,\n 11.81473,\n np.nan,\n np.nan,\n ],\n \"triang\": [\n np.nan,\n np.nan,\n 9.28667,\n 10.34667,\n 12.00556,\n 13.33889,\n 13.38,\n 12.33667,\n np.nan,\n np.nan,\n ],\n \"barthann\": [\n np.nan,\n np.nan,\n 8.4425,\n 9.1925,\n 12.5575,\n 14.3675,\n 14.0825,\n 11.5675,\n np.nan,\n np.nan,\n ],\n \"bohman\": [\n np.nan,\n np.nan,\n 7.61599,\n 9.1764,\n 12.83559,\n 14.17267,\n 14.65923,\n 11.10401,\n np.nan,\n np.nan,\n ],\n \"blackmanharris\": [\n np.nan,\n np.nan,\n 6.97691,\n 9.16438,\n 13.05052,\n 14.02156,\n 15.10512,\n 10.74574,\n np.nan,\n np.nan,\n ],\n \"nuttall\": [\n np.nan,\n np.nan,\n 7.04618,\n 9.16786,\n 13.02671,\n 14.03559,\n 15.05657,\n 10.78514,\n np.nan,\n np.nan,\n ],\n \"blackman\": [\n np.nan,\n np.nan,\n 7.73345,\n 9.17869,\n 12.79607,\n 14.20036,\n 14.57726,\n 11.16988,\n np.nan,\n np.nan,\n ],\n \"bartlett\": [\n np.nan,\n np.nan,\n 8.4425,\n 9.1925,\n 12.5575,\n 14.3675,\n 14.0825,\n 11.5675,\n np.nan,\n np.nan,\n ],\n }\n\n xp = Series(xps[win_types])\n rs = Series(vals).rolling(5, win_type=win_types, center=True).mean()\n tm.assert_series_equal(xp, rs)\n\n\[email protected]_if_no_scipy\ndef test_cmov_window_regular_linear_range(win_types):\n # GH 8238\n vals = np.array(range(10), dtype=float)\n xp = vals.copy()\n xp[:2] = np.nan\n xp[-2:] = np.nan\n xp = Series(xp)\n\n rs = Series(vals).rolling(5, win_type=win_types, center=True).mean()\n tm.assert_series_equal(xp, rs)\n\n\[email protected]_if_no_scipy\ndef test_cmov_window_regular_missing_data(win_types):\n # GH 8238\n vals = np.array(\n [6.95, 15.21, 4.72, 9.12, 13.81, 13.49, 16.68, np.nan, 10.63, 14.48]\n )\n xps = {\n \"bartlett\": [\n np.nan,\n np.nan,\n 9.70333,\n 10.5225,\n 8.4425,\n 9.1925,\n 12.5575,\n 14.3675,\n 15.61667,\n 13.655,\n ],\n \"blackman\": [\n np.nan,\n np.nan,\n 9.04582,\n 11.41536,\n 7.73345,\n 9.17869,\n 12.79607,\n 14.20036,\n 15.8706,\n 13.655,\n ],\n \"barthann\": [\n np.nan,\n np.nan,\n 9.70333,\n 10.5225,\n 8.4425,\n 9.1925,\n 12.5575,\n 14.3675,\n 15.61667,\n 13.655,\n ],\n \"bohman\": [\n np.nan,\n np.nan,\n 8.9444,\n 11.56327,\n 7.61599,\n 9.1764,\n 12.83559,\n 14.17267,\n 15.90976,\n 13.655,\n ],\n \"hamming\": [\n np.nan,\n np.nan,\n 9.59321,\n 10.29694,\n 8.71384,\n 9.56348,\n 12.38009,\n 14.20565,\n 15.24694,\n 13.69758,\n ],\n \"nuttall\": [\n np.nan,\n np.nan,\n 8.47693,\n 12.2821,\n 7.04618,\n 9.16786,\n 13.02671,\n 14.03673,\n 16.08759,\n 13.65553,\n ],\n \"triang\": [\n np.nan,\n np.nan,\n 9.33167,\n 9.76125,\n 9.28667,\n 10.34667,\n 12.00556,\n 13.82125,\n 14.49429,\n 13.765,\n ],\n \"blackmanharris\": [\n np.nan,\n np.nan,\n 8.42526,\n 12.36824,\n 6.97691,\n 9.16438,\n 13.05052,\n 14.02175,\n 16.1098,\n 13.65509,\n ],\n }\n\n xp = Series(xps[win_types])\n rs = Series(vals).rolling(5, win_type=win_types, min_periods=3).mean()\n tm.assert_series_equal(xp, rs)\n\n\[email protected]_if_no_scipy\ndef test_cmov_window_special(win_types_special):\n # GH 8238\n kwds = {\n \"kaiser\": {\"beta\": 1.0},\n \"gaussian\": {\"std\": 1.0},\n \"general_gaussian\": {\"p\": 2.0, \"sig\": 2.0},\n \"exponential\": {\"tau\": 10},\n }\n\n vals = np.array([6.95, 15.21, 4.72, 9.12, 13.81, 13.49, 16.68, 9.48, 10.63, 14.48])\n\n xps = {\n \"gaussian\": [\n np.nan,\n np.nan,\n 8.97297,\n 9.76077,\n 12.24763,\n 13.89053,\n 13.65671,\n 12.01002,\n np.nan,\n np.nan,\n ],\n \"general_gaussian\": [\n np.nan,\n np.nan,\n 9.85011,\n 10.71589,\n 11.73161,\n 13.08516,\n 12.95111,\n 12.74577,\n np.nan,\n np.nan,\n ],\n \"kaiser\": [\n np.nan,\n np.nan,\n 9.86851,\n 11.02969,\n 11.65161,\n 12.75129,\n 12.90702,\n 12.83757,\n np.nan,\n np.nan,\n ],\n \"exponential\": [\n np.nan,\n np.nan,\n 9.83364,\n 11.10472,\n 11.64551,\n 12.66138,\n 12.92379,\n 12.83770,\n np.nan,\n np.nan,\n ],\n }\n\n xp = Series(xps[win_types_special])\n rs = (\n Series(vals)\n .rolling(5, win_type=win_types_special, center=True)\n .mean(**kwds[win_types_special])\n )\n tm.assert_series_equal(xp, rs)\n\n\[email protected]_if_no_scipy\ndef test_cmov_window_special_linear_range(win_types_special):\n # GH 8238\n kwds = {\n \"kaiser\": {\"beta\": 1.0},\n \"gaussian\": {\"std\": 1.0},\n \"general_gaussian\": {\"p\": 2.0, \"sig\": 2.0},\n \"slepian\": {\"width\": 0.5},\n \"exponential\": {\"tau\": 10},\n }\n\n vals = np.array(range(10), dtype=float)\n xp = vals.copy()\n xp[:2] = np.nan\n xp[-2:] = np.nan\n xp = Series(xp)\n\n rs = (\n Series(vals)\n .rolling(5, win_type=win_types_special, center=True)\n .mean(**kwds[win_types_special])\n )\n tm.assert_series_equal(xp, rs)\n",
"from pandas import (\n Index,\n NaT,\n date_range,\n)\n\n\ndef test_is_monotonic_with_nat():\n # GH#31437\n # PeriodIndex.is_monotonic_increasing should behave analogously to DatetimeIndex,\n # in particular never be monotonic when we have NaT\n dti = date_range(\"2016-01-01\", periods=3)\n pi = dti.to_period(\"D\")\n tdi = Index(dti.view(\"timedelta64[ns]\"))\n\n for obj in [pi, pi._engine, dti, dti._engine, tdi, tdi._engine]:\n if isinstance(obj, Index):\n # i.e. not Engines\n assert obj.is_monotonic_increasing\n assert obj.is_monotonic_increasing\n assert not obj.is_monotonic_decreasing\n assert obj.is_unique\n\n dti1 = dti.insert(0, NaT)\n pi1 = dti1.to_period(\"D\")\n tdi1 = Index(dti1.view(\"timedelta64[ns]\"))\n\n for obj in [pi1, pi1._engine, dti1, dti1._engine, tdi1, tdi1._engine]:\n if isinstance(obj, Index):\n # i.e. not Engines\n assert not obj.is_monotonic_increasing\n assert not obj.is_monotonic_increasing\n assert not obj.is_monotonic_decreasing\n assert obj.is_unique\n\n dti2 = dti.insert(3, NaT)\n pi2 = dti2.to_period(\"H\")\n tdi2 = Index(dti2.view(\"timedelta64[ns]\"))\n\n for obj in [pi2, pi2._engine, dti2, dti2._engine, tdi2, tdi2._engine]:\n if isinstance(obj, Index):\n # i.e. not Engines\n assert not obj.is_monotonic_increasing\n assert not obj.is_monotonic_increasing\n assert not obj.is_monotonic_decreasing\n assert obj.is_unique\n",
"\"\"\"Tests formatting as writer-agnostic ExcelCells\n\nExcelFormatter is tested implicitly in pandas/tests/io/excel\n\"\"\"\nimport string\n\nimport pytest\n\nimport pandas.util._test_decorators as td\n\nimport pandas._testing as tm\n\nfrom pandas.io.formats.css import CSSWarning\nfrom pandas.io.formats.excel import CSSToExcelConverter\n\n\[email protected](\n \"css,expected\",\n [\n # FONT\n # - name\n (\"font-family: foo,bar\", {\"font\": {\"name\": \"foo\"}}),\n ('font-family: \"foo bar\",baz', {\"font\": {\"name\": \"foo bar\"}}),\n (\"font-family: foo,\\nbar\", {\"font\": {\"name\": \"foo\"}}),\n (\"font-family: foo, bar, baz\", {\"font\": {\"name\": \"foo\"}}),\n (\"font-family: bar, foo\", {\"font\": {\"name\": \"bar\"}}),\n (\"font-family: 'foo bar', baz\", {\"font\": {\"name\": \"foo bar\"}}),\n (\"font-family: 'foo \\\\'bar', baz\", {\"font\": {\"name\": \"foo 'bar\"}}),\n ('font-family: \"foo \\\\\"bar\", baz', {\"font\": {\"name\": 'foo \"bar'}}),\n ('font-family: \"foo ,bar\", baz', {\"font\": {\"name\": \"foo ,bar\"}}),\n # - family\n (\"font-family: serif\", {\"font\": {\"name\": \"serif\", \"family\": 1}}),\n (\"font-family: Serif\", {\"font\": {\"name\": \"serif\", \"family\": 1}}),\n (\"font-family: roman, serif\", {\"font\": {\"name\": \"roman\", \"family\": 1}}),\n (\"font-family: roman, sans-serif\", {\"font\": {\"name\": \"roman\", \"family\": 2}}),\n (\"font-family: roman, sans serif\", {\"font\": {\"name\": \"roman\"}}),\n (\"font-family: roman, sansserif\", {\"font\": {\"name\": \"roman\"}}),\n (\"font-family: roman, cursive\", {\"font\": {\"name\": \"roman\", \"family\": 4}}),\n (\"font-family: roman, fantasy\", {\"font\": {\"name\": \"roman\", \"family\": 5}}),\n # - size\n (\"font-size: 1em\", {\"font\": {\"size\": 12}}),\n (\"font-size: xx-small\", {\"font\": {\"size\": 6}}),\n (\"font-size: x-small\", {\"font\": {\"size\": 7.5}}),\n (\"font-size: small\", {\"font\": {\"size\": 9.6}}),\n (\"font-size: medium\", {\"font\": {\"size\": 12}}),\n (\"font-size: large\", {\"font\": {\"size\": 13.5}}),\n (\"font-size: x-large\", {\"font\": {\"size\": 18}}),\n (\"font-size: xx-large\", {\"font\": {\"size\": 24}}),\n (\"font-size: 50%\", {\"font\": {\"size\": 6}}),\n # - bold\n (\"font-weight: 100\", {\"font\": {\"bold\": False}}),\n (\"font-weight: 200\", {\"font\": {\"bold\": False}}),\n (\"font-weight: 300\", {\"font\": {\"bold\": False}}),\n (\"font-weight: 400\", {\"font\": {\"bold\": False}}),\n (\"font-weight: normal\", {\"font\": {\"bold\": False}}),\n (\"font-weight: lighter\", {\"font\": {\"bold\": False}}),\n (\"font-weight: bold\", {\"font\": {\"bold\": True}}),\n (\"font-weight: bolder\", {\"font\": {\"bold\": True}}),\n (\"font-weight: 700\", {\"font\": {\"bold\": True}}),\n (\"font-weight: 800\", {\"font\": {\"bold\": True}}),\n (\"font-weight: 900\", {\"font\": {\"bold\": True}}),\n # - italic\n (\"font-style: italic\", {\"font\": {\"italic\": True}}),\n (\"font-style: oblique\", {\"font\": {\"italic\": True}}),\n # - underline\n (\"text-decoration: underline\", {\"font\": {\"underline\": \"single\"}}),\n (\"text-decoration: overline\", {}),\n (\"text-decoration: none\", {}),\n # - strike\n (\"text-decoration: line-through\", {\"font\": {\"strike\": True}}),\n (\n \"text-decoration: underline line-through\",\n {\"font\": {\"strike\": True, \"underline\": \"single\"}},\n ),\n (\n \"text-decoration: underline; text-decoration: line-through\",\n {\"font\": {\"strike\": True}},\n ),\n # - color\n (\"color: red\", {\"font\": {\"color\": \"FF0000\"}}),\n (\"color: #ff0000\", {\"font\": {\"color\": \"FF0000\"}}),\n (\"color: #f0a\", {\"font\": {\"color\": \"FF00AA\"}}),\n # - shadow\n (\"text-shadow: none\", {\"font\": {\"shadow\": False}}),\n (\"text-shadow: 0px -0em 0px #CCC\", {\"font\": {\"shadow\": False}}),\n (\"text-shadow: 0px -0em 0px #999\", {\"font\": {\"shadow\": False}}),\n (\"text-shadow: 0px -0em 0px\", {\"font\": {\"shadow\": False}}),\n (\"text-shadow: 2px -0em 0px #CCC\", {\"font\": {\"shadow\": True}}),\n (\"text-shadow: 0px -2em 0px #CCC\", {\"font\": {\"shadow\": True}}),\n (\"text-shadow: 0px -0em 2px #CCC\", {\"font\": {\"shadow\": True}}),\n (\"text-shadow: 0px -0em 2px\", {\"font\": {\"shadow\": True}}),\n (\"text-shadow: 0px -2em\", {\"font\": {\"shadow\": True}}),\n # FILL\n # - color, fillType\n (\n \"background-color: red\",\n {\"fill\": {\"fgColor\": \"FF0000\", \"patternType\": \"solid\"}},\n ),\n (\n \"background-color: #ff0000\",\n {\"fill\": {\"fgColor\": \"FF0000\", \"patternType\": \"solid\"}},\n ),\n (\n \"background-color: #f0a\",\n {\"fill\": {\"fgColor\": \"FF00AA\", \"patternType\": \"solid\"}},\n ),\n # BORDER\n # - style\n (\n \"border-style: solid\",\n {\n \"border\": {\n \"top\": {\"style\": \"medium\"},\n \"bottom\": {\"style\": \"medium\"},\n \"left\": {\"style\": \"medium\"},\n \"right\": {\"style\": \"medium\"},\n }\n },\n ),\n (\n \"border-style: solid; border-width: thin\",\n {\n \"border\": {\n \"top\": {\"style\": \"thin\"},\n \"bottom\": {\"style\": \"thin\"},\n \"left\": {\"style\": \"thin\"},\n \"right\": {\"style\": \"thin\"},\n }\n },\n ),\n (\n \"border-top-style: solid; border-top-width: thin\",\n {\"border\": {\"top\": {\"style\": \"thin\"}}},\n ),\n (\n \"border-top-style: solid; border-top-width: 1pt\",\n {\"border\": {\"top\": {\"style\": \"thin\"}}},\n ),\n (\"border-top-style: solid\", {\"border\": {\"top\": {\"style\": \"medium\"}}}),\n (\n \"border-top-style: solid; border-top-width: medium\",\n {\"border\": {\"top\": {\"style\": \"medium\"}}},\n ),\n (\n \"border-top-style: solid; border-top-width: 2pt\",\n {\"border\": {\"top\": {\"style\": \"medium\"}}},\n ),\n (\n \"border-top-style: solid; border-top-width: thick\",\n {\"border\": {\"top\": {\"style\": \"thick\"}}},\n ),\n (\n \"border-top-style: solid; border-top-width: 4pt\",\n {\"border\": {\"top\": {\"style\": \"thick\"}}},\n ),\n (\n \"border-top-style: dotted\",\n {\"border\": {\"top\": {\"style\": \"mediumDashDotDot\"}}},\n ),\n (\n \"border-top-style: dotted; border-top-width: thin\",\n {\"border\": {\"top\": {\"style\": \"dotted\"}}},\n ),\n (\"border-top-style: dashed\", {\"border\": {\"top\": {\"style\": \"mediumDashed\"}}}),\n (\n \"border-top-style: dashed; border-top-width: thin\",\n {\"border\": {\"top\": {\"style\": \"dashed\"}}},\n ),\n (\"border-top-style: double\", {\"border\": {\"top\": {\"style\": \"double\"}}}),\n # - color\n (\n \"border-style: solid; border-color: #0000ff\",\n {\n \"border\": {\n \"top\": {\"style\": \"medium\", \"color\": \"0000FF\"},\n \"right\": {\"style\": \"medium\", \"color\": \"0000FF\"},\n \"bottom\": {\"style\": \"medium\", \"color\": \"0000FF\"},\n \"left\": {\"style\": \"medium\", \"color\": \"0000FF\"},\n }\n },\n ),\n (\n \"border-top-style: double; border-top-color: blue\",\n {\"border\": {\"top\": {\"style\": \"double\", \"color\": \"0000FF\"}}},\n ),\n (\n \"border-top-style: solid; border-top-color: #06c\",\n {\"border\": {\"top\": {\"style\": \"medium\", \"color\": \"0066CC\"}}},\n ),\n (\n \"border-top-color: blue\",\n {\"border\": {\"top\": {\"color\": \"0000FF\", \"style\": \"none\"}}},\n ),\n # ALIGNMENT\n # - horizontal\n (\"text-align: center\", {\"alignment\": {\"horizontal\": \"center\"}}),\n (\"text-align: left\", {\"alignment\": {\"horizontal\": \"left\"}}),\n (\"text-align: right\", {\"alignment\": {\"horizontal\": \"right\"}}),\n (\"text-align: justify\", {\"alignment\": {\"horizontal\": \"justify\"}}),\n # - vertical\n (\"vertical-align: top\", {\"alignment\": {\"vertical\": \"top\"}}),\n (\"vertical-align: text-top\", {\"alignment\": {\"vertical\": \"top\"}}),\n (\"vertical-align: middle\", {\"alignment\": {\"vertical\": \"center\"}}),\n (\"vertical-align: bottom\", {\"alignment\": {\"vertical\": \"bottom\"}}),\n (\"vertical-align: text-bottom\", {\"alignment\": {\"vertical\": \"bottom\"}}),\n # - wrap_text\n (\"white-space: nowrap\", {\"alignment\": {\"wrap_text\": False}}),\n (\"white-space: pre\", {\"alignment\": {\"wrap_text\": False}}),\n (\"white-space: pre-line\", {\"alignment\": {\"wrap_text\": False}}),\n (\"white-space: normal\", {\"alignment\": {\"wrap_text\": True}}),\n # NUMBER FORMAT\n (\"number-format: 0%\", {\"number_format\": {\"format_code\": \"0%\"}}),\n ],\n)\ndef test_css_to_excel(css, expected):\n convert = CSSToExcelConverter()\n assert expected == convert(css)\n\n\ndef test_css_to_excel_multiple():\n convert = CSSToExcelConverter()\n actual = convert(\n \"\"\"\n font-weight: bold;\n text-decoration: underline;\n color: red;\n border-width: thin;\n text-align: center;\n vertical-align: top;\n unused: something;\n \"\"\"\n )\n assert {\n \"font\": {\"bold\": True, \"underline\": \"single\", \"color\": \"FF0000\"},\n \"border\": {\n \"top\": {\"style\": \"thin\"},\n \"right\": {\"style\": \"thin\"},\n \"bottom\": {\"style\": \"thin\"},\n \"left\": {\"style\": \"thin\"},\n },\n \"alignment\": {\"horizontal\": \"center\", \"vertical\": \"top\"},\n } == actual\n\n\[email protected](\n \"css,inherited,expected\",\n [\n (\"font-weight: bold\", \"\", {\"font\": {\"bold\": True}}),\n (\"\", \"font-weight: bold\", {\"font\": {\"bold\": True}}),\n (\n \"font-weight: bold\",\n \"font-style: italic\",\n {\"font\": {\"bold\": True, \"italic\": True}},\n ),\n (\"font-style: normal\", \"font-style: italic\", {\"font\": {\"italic\": False}}),\n (\"font-style: inherit\", \"\", {}),\n (\n \"font-style: normal; font-style: inherit\",\n \"font-style: italic\",\n {\"font\": {\"italic\": True}},\n ),\n ],\n)\ndef test_css_to_excel_inherited(css, inherited, expected):\n convert = CSSToExcelConverter(inherited)\n assert expected == convert(css)\n\n\[email protected](\n \"input_color,output_color\",\n (\n list(CSSToExcelConverter.NAMED_COLORS.items())\n + [(\"#\" + rgb, rgb) for rgb in CSSToExcelConverter.NAMED_COLORS.values()]\n + [(\"#F0F\", \"FF00FF\"), (\"#ABC\", \"AABBCC\")]\n ),\n)\ndef test_css_to_excel_good_colors(input_color, output_color):\n # see gh-18392\n css = (\n f\"border-top-color: {input_color}; \"\n f\"border-right-color: {input_color}; \"\n f\"border-bottom-color: {input_color}; \"\n f\"border-left-color: {input_color}; \"\n f\"background-color: {input_color}; \"\n f\"color: {input_color}\"\n )\n\n expected = {}\n\n expected[\"fill\"] = {\"patternType\": \"solid\", \"fgColor\": output_color}\n\n expected[\"font\"] = {\"color\": output_color}\n\n expected[\"border\"] = {\n k: {\"color\": output_color, \"style\": \"none\"}\n for k in (\"top\", \"right\", \"bottom\", \"left\")\n }\n\n with tm.assert_produces_warning(None):\n convert = CSSToExcelConverter()\n assert expected == convert(css)\n\n\[email protected](\"input_color\", [None, \"not-a-color\"])\ndef test_css_to_excel_bad_colors(input_color):\n # see gh-18392\n css = (\n f\"border-top-color: {input_color}; \"\n f\"border-right-color: {input_color}; \"\n f\"border-bottom-color: {input_color}; \"\n f\"border-left-color: {input_color}; \"\n f\"background-color: {input_color}; \"\n f\"color: {input_color}\"\n )\n\n expected = {}\n\n if input_color is not None:\n expected[\"fill\"] = {\"patternType\": \"solid\"}\n\n with tm.assert_produces_warning(CSSWarning):\n convert = CSSToExcelConverter()\n assert expected == convert(css)\n\n\ndef tests_css_named_colors_valid():\n upper_hexs = set(map(str.upper, string.hexdigits))\n for color in CSSToExcelConverter.NAMED_COLORS.values():\n assert len(color) == 6 and all(c in upper_hexs for c in color)\n\n\[email protected]_if_no_mpl\ndef test_css_named_colors_from_mpl_present():\n from matplotlib.colors import CSS4_COLORS as mpl_colors\n\n pd_colors = CSSToExcelConverter.NAMED_COLORS\n for name, color in mpl_colors.items():\n assert name in pd_colors and pd_colors[name] == color[1:]\n",
"import numpy as np\nimport pytest\n\nfrom pandas.errors import InvalidIndexError\n\nfrom pandas import (\n Index,\n RangeIndex,\n Series,\n Timestamp,\n)\nimport pandas._testing as tm\nfrom pandas.core.indexes.api import (\n Float64Index,\n Int64Index,\n UInt64Index,\n)\n\n\[email protected]\ndef index_large():\n # large values used in UInt64Index tests where no compat needed with Int64/Float64\n large = [2**63, 2**63 + 10, 2**63 + 15, 2**63 + 20, 2**63 + 25]\n return UInt64Index(large)\n\n\nclass TestGetLoc:\n @pytest.mark.parametrize(\"method\", [None, \"pad\", \"backfill\", \"nearest\"])\n def test_get_loc(self, method):\n index = Index([0, 1, 2])\n warn = None if method is None else FutureWarning\n\n with tm.assert_produces_warning(warn, match=\"deprecated\"):\n assert index.get_loc(1, method=method) == 1\n\n if method:\n with tm.assert_produces_warning(warn, match=\"deprecated\"):\n assert index.get_loc(1, method=method, tolerance=0) == 1\n\n @pytest.mark.parametrize(\"method\", [None, \"pad\", \"backfill\", \"nearest\"])\n @pytest.mark.filterwarnings(\"ignore:Passing method:FutureWarning\")\n def test_get_loc_raises_bad_label(self, method):\n index = Index([0, 1, 2])\n if method:\n msg = \"not supported between\"\n err = TypeError\n else:\n msg = r\"\\[1, 2\\]\"\n err = InvalidIndexError\n\n with pytest.raises(err, match=msg):\n index.get_loc([1, 2], method=method)\n\n @pytest.mark.parametrize(\n \"method,loc\", [(\"pad\", 1), (\"backfill\", 2), (\"nearest\", 1)]\n )\n @pytest.mark.filterwarnings(\"ignore:Passing method:FutureWarning\")\n def test_get_loc_tolerance(self, method, loc):\n index = Index([0, 1, 2])\n assert index.get_loc(1.1, method) == loc\n assert index.get_loc(1.1, method, tolerance=1) == loc\n\n @pytest.mark.parametrize(\"method\", [\"pad\", \"backfill\", \"nearest\"])\n def test_get_loc_outside_tolerance_raises(self, method):\n index = Index([0, 1, 2])\n with pytest.raises(KeyError, match=\"1.1\"):\n with tm.assert_produces_warning(FutureWarning, match=\"deprecated\"):\n index.get_loc(1.1, method, tolerance=0.05)\n\n def test_get_loc_bad_tolerance_raises(self):\n index = Index([0, 1, 2])\n with pytest.raises(ValueError, match=\"must be numeric\"):\n with tm.assert_produces_warning(FutureWarning, match=\"deprecated\"):\n index.get_loc(1.1, \"nearest\", tolerance=\"invalid\")\n\n def test_get_loc_tolerance_no_method_raises(self):\n index = Index([0, 1, 2])\n with pytest.raises(ValueError, match=\"tolerance .* valid if\"):\n index.get_loc(1.1, tolerance=1)\n\n def test_get_loc_raises_missized_tolerance(self):\n index = Index([0, 1, 2])\n with pytest.raises(ValueError, match=\"tolerance size must match\"):\n with tm.assert_produces_warning(FutureWarning, match=\"deprecated\"):\n index.get_loc(1.1, \"nearest\", tolerance=[1, 1])\n\n @pytest.mark.filterwarnings(\"ignore:Passing method:FutureWarning\")\n def test_get_loc_float64(self):\n idx = Float64Index([0.0, 1.0, 2.0])\n for method in [None, \"pad\", \"backfill\", \"nearest\"]:\n assert idx.get_loc(1, method) == 1\n if method is not None:\n assert idx.get_loc(1, method, tolerance=0) == 1\n\n for method, loc in [(\"pad\", 1), (\"backfill\", 2), (\"nearest\", 1)]:\n assert idx.get_loc(1.1, method) == loc\n assert idx.get_loc(1.1, method, tolerance=0.9) == loc\n\n with pytest.raises(KeyError, match=\"^'foo'$\"):\n idx.get_loc(\"foo\")\n with pytest.raises(KeyError, match=r\"^1\\.5$\"):\n idx.get_loc(1.5)\n with pytest.raises(KeyError, match=r\"^1\\.5$\"):\n idx.get_loc(1.5, method=\"pad\", tolerance=0.1)\n with pytest.raises(KeyError, match=\"^True$\"):\n idx.get_loc(True)\n with pytest.raises(KeyError, match=\"^False$\"):\n idx.get_loc(False)\n\n with pytest.raises(ValueError, match=\"must be numeric\"):\n idx.get_loc(1.4, method=\"nearest\", tolerance=\"foo\")\n\n with pytest.raises(ValueError, match=\"must contain numeric elements\"):\n idx.get_loc(1.4, method=\"nearest\", tolerance=np.array([\"foo\"]))\n\n with pytest.raises(\n ValueError, match=\"tolerance size must match target index size\"\n ):\n idx.get_loc(1.4, method=\"nearest\", tolerance=np.array([1, 2]))\n\n def test_get_loc_na(self):\n idx = Float64Index([np.nan, 1, 2])\n assert idx.get_loc(1) == 1\n assert idx.get_loc(np.nan) == 0\n\n idx = Float64Index([np.nan, 1, np.nan])\n assert idx.get_loc(1) == 1\n\n # representable by slice [0:2:2]\n msg = \"'Cannot get left slice bound for non-unique label: nan'\"\n with pytest.raises(KeyError, match=msg):\n idx.slice_locs(np.nan)\n # not representable by slice\n idx = Float64Index([np.nan, 1, np.nan, np.nan])\n assert idx.get_loc(1) == 1\n msg = \"'Cannot get left slice bound for non-unique label: nan\"\n with pytest.raises(KeyError, match=msg):\n idx.slice_locs(np.nan)\n\n def test_get_loc_missing_nan(self):\n # GH#8569\n idx = Float64Index([1, 2])\n assert idx.get_loc(1) == 0\n with pytest.raises(KeyError, match=r\"^3$\"):\n idx.get_loc(3)\n with pytest.raises(KeyError, match=\"^nan$\"):\n idx.get_loc(np.nan)\n with pytest.raises(InvalidIndexError, match=r\"\\[nan\\]\"):\n # listlike/non-hashable raises TypeError\n idx.get_loc([np.nan])\n\n @pytest.mark.parametrize(\"vals\", [[1], [1.0], [Timestamp(\"2019-12-31\")], [\"test\"]])\n @pytest.mark.parametrize(\"method\", [\"nearest\", \"pad\", \"backfill\"])\n def test_get_loc_float_index_nan_with_method(self, vals, method):\n # GH#39382\n idx = Index(vals)\n with pytest.raises(KeyError, match=\"nan\"):\n with tm.assert_produces_warning(FutureWarning, match=\"deprecated\"):\n idx.get_loc(np.nan, method=method)\n\n @pytest.mark.parametrize(\"dtype\", [\"f8\", \"i8\", \"u8\"])\n def test_get_loc_numericindex_none_raises(self, dtype):\n # case that goes through searchsorted and key is non-comparable to values\n arr = np.arange(10**7, dtype=dtype)\n idx = Index(arr)\n with pytest.raises(KeyError, match=\"None\"):\n idx.get_loc(None)\n\n def test_get_loc_overflows(self):\n # unique but non-monotonic goes through IndexEngine.mapping.get_item\n idx = Index([0, 2, 1])\n\n val = np.iinfo(np.int64).max + 1\n\n with pytest.raises(KeyError, match=str(val)):\n idx.get_loc(val)\n with pytest.raises(KeyError, match=str(val)):\n idx._engine.get_loc(val)\n\n\nclass TestGetIndexer:\n def test_get_indexer(self):\n index1 = Index([1, 2, 3, 4, 5])\n index2 = Index([2, 4, 6])\n\n r1 = index1.get_indexer(index2)\n e1 = np.array([1, 3, -1], dtype=np.intp)\n tm.assert_almost_equal(r1, e1)\n\n @pytest.mark.parametrize(\"reverse\", [True, False])\n @pytest.mark.parametrize(\n \"expected,method\",\n [\n (np.array([-1, 0, 0, 1, 1], dtype=np.intp), \"pad\"),\n (np.array([-1, 0, 0, 1, 1], dtype=np.intp), \"ffill\"),\n (np.array([0, 0, 1, 1, 2], dtype=np.intp), \"backfill\"),\n (np.array([0, 0, 1, 1, 2], dtype=np.intp), \"bfill\"),\n ],\n )\n def test_get_indexer_methods(self, reverse, expected, method):\n index1 = Index([1, 2, 3, 4, 5])\n index2 = Index([2, 4, 6])\n\n if reverse:\n index1 = index1[::-1]\n expected = expected[::-1]\n\n result = index2.get_indexer(index1, method=method)\n tm.assert_almost_equal(result, expected)\n\n def test_get_indexer_invalid(self):\n # GH10411\n index = Index(np.arange(10))\n\n with pytest.raises(ValueError, match=\"tolerance argument\"):\n index.get_indexer([1, 0], tolerance=1)\n\n with pytest.raises(ValueError, match=\"limit argument\"):\n index.get_indexer([1, 0], limit=1)\n\n @pytest.mark.parametrize(\n \"method, tolerance, indexer, expected\",\n [\n (\"pad\", None, [0, 5, 9], [0, 5, 9]),\n (\"backfill\", None, [0, 5, 9], [0, 5, 9]),\n (\"nearest\", None, [0, 5, 9], [0, 5, 9]),\n (\"pad\", 0, [0, 5, 9], [0, 5, 9]),\n (\"backfill\", 0, [0, 5, 9], [0, 5, 9]),\n (\"nearest\", 0, [0, 5, 9], [0, 5, 9]),\n (\"pad\", None, [0.2, 1.8, 8.5], [0, 1, 8]),\n (\"backfill\", None, [0.2, 1.8, 8.5], [1, 2, 9]),\n (\"nearest\", None, [0.2, 1.8, 8.5], [0, 2, 9]),\n (\"pad\", 1, [0.2, 1.8, 8.5], [0, 1, 8]),\n (\"backfill\", 1, [0.2, 1.8, 8.5], [1, 2, 9]),\n (\"nearest\", 1, [0.2, 1.8, 8.5], [0, 2, 9]),\n (\"pad\", 0.2, [0.2, 1.8, 8.5], [0, -1, -1]),\n (\"backfill\", 0.2, [0.2, 1.8, 8.5], [-1, 2, -1]),\n (\"nearest\", 0.2, [0.2, 1.8, 8.5], [0, 2, -1]),\n ],\n )\n def test_get_indexer_nearest(self, method, tolerance, indexer, expected):\n index = Index(np.arange(10))\n\n actual = index.get_indexer(indexer, method=method, tolerance=tolerance)\n tm.assert_numpy_array_equal(actual, np.array(expected, dtype=np.intp))\n\n @pytest.mark.parametrize(\"listtype\", [list, tuple, Series, np.array])\n @pytest.mark.parametrize(\n \"tolerance, expected\",\n list(\n zip(\n [[0.3, 0.3, 0.1], [0.2, 0.1, 0.1], [0.1, 0.5, 0.5]],\n [[0, 2, -1], [0, -1, -1], [-1, 2, 9]],\n )\n ),\n )\n def test_get_indexer_nearest_listlike_tolerance(\n self, tolerance, expected, listtype\n ):\n index = Index(np.arange(10))\n\n actual = index.get_indexer(\n [0.2, 1.8, 8.5], method=\"nearest\", tolerance=listtype(tolerance)\n )\n tm.assert_numpy_array_equal(actual, np.array(expected, dtype=np.intp))\n\n def test_get_indexer_nearest_error(self):\n index = Index(np.arange(10))\n with pytest.raises(ValueError, match=\"limit argument\"):\n index.get_indexer([1, 0], method=\"nearest\", limit=1)\n\n with pytest.raises(ValueError, match=\"tolerance size must match\"):\n index.get_indexer([1, 0], method=\"nearest\", tolerance=[1, 2, 3])\n\n @pytest.mark.parametrize(\n \"method,expected\",\n [(\"pad\", [8, 7, 0]), (\"backfill\", [9, 8, 1]), (\"nearest\", [9, 7, 0])],\n )\n def test_get_indexer_nearest_decreasing(self, method, expected):\n index = Index(np.arange(10))[::-1]\n\n actual = index.get_indexer([0, 5, 9], method=method)\n tm.assert_numpy_array_equal(actual, np.array([9, 4, 0], dtype=np.intp))\n\n actual = index.get_indexer([0.2, 1.8, 8.5], method=method)\n tm.assert_numpy_array_equal(actual, np.array(expected, dtype=np.intp))\n\n @pytest.mark.parametrize(\n \"idx_class\", [Int64Index, RangeIndex, Float64Index, UInt64Index]\n )\n @pytest.mark.parametrize(\"method\", [\"get_indexer\", \"get_indexer_non_unique\"])\n def test_get_indexer_numeric_index_boolean_target(self, method, idx_class):\n # GH 16877\n\n numeric_index = idx_class(RangeIndex(4))\n other = Index([True, False, True])\n\n result = getattr(numeric_index, method)(other)\n expected = np.array([-1, -1, -1], dtype=np.intp)\n if method == \"get_indexer\":\n tm.assert_numpy_array_equal(result, expected)\n else:\n missing = np.arange(3, dtype=np.intp)\n tm.assert_numpy_array_equal(result[0], expected)\n tm.assert_numpy_array_equal(result[1], missing)\n\n @pytest.mark.parametrize(\"method\", [\"pad\", \"backfill\", \"nearest\"])\n def test_get_indexer_with_method_numeric_vs_bool(self, method):\n left = Index([1, 2, 3])\n right = Index([True, False])\n\n with pytest.raises(TypeError, match=\"Cannot compare\"):\n left.get_indexer(right, method=method)\n\n with pytest.raises(TypeError, match=\"Cannot compare\"):\n right.get_indexer(left, method=method)\n\n def test_get_indexer_numeric_vs_bool(self):\n left = Index([1, 2, 3])\n right = Index([True, False])\n\n res = left.get_indexer(right)\n expected = -1 * np.ones(len(right), dtype=np.intp)\n tm.assert_numpy_array_equal(res, expected)\n\n res = right.get_indexer(left)\n expected = -1 * np.ones(len(left), dtype=np.intp)\n tm.assert_numpy_array_equal(res, expected)\n\n res = left.get_indexer_non_unique(right)[0]\n expected = -1 * np.ones(len(right), dtype=np.intp)\n tm.assert_numpy_array_equal(res, expected)\n\n res = right.get_indexer_non_unique(left)[0]\n expected = -1 * np.ones(len(left), dtype=np.intp)\n tm.assert_numpy_array_equal(res, expected)\n\n def test_get_indexer_float64(self):\n idx = Float64Index([0.0, 1.0, 2.0])\n tm.assert_numpy_array_equal(\n idx.get_indexer(idx), np.array([0, 1, 2], dtype=np.intp)\n )\n\n target = [-0.1, 0.5, 1.1]\n tm.assert_numpy_array_equal(\n idx.get_indexer(target, \"pad\"), np.array([-1, 0, 1], dtype=np.intp)\n )\n tm.assert_numpy_array_equal(\n idx.get_indexer(target, \"backfill\"), np.array([0, 1, 2], dtype=np.intp)\n )\n tm.assert_numpy_array_equal(\n idx.get_indexer(target, \"nearest\"), np.array([0, 1, 1], dtype=np.intp)\n )\n\n def test_get_indexer_nan(self):\n # GH#7820\n result = Float64Index([1, 2, np.nan]).get_indexer([np.nan])\n expected = np.array([2], dtype=np.intp)\n tm.assert_numpy_array_equal(result, expected)\n\n def test_get_indexer_int64(self):\n index = Int64Index(range(0, 20, 2))\n target = Int64Index(np.arange(10))\n indexer = index.get_indexer(target)\n expected = np.array([0, -1, 1, -1, 2, -1, 3, -1, 4, -1], dtype=np.intp)\n tm.assert_numpy_array_equal(indexer, expected)\n\n target = Int64Index(np.arange(10))\n indexer = index.get_indexer(target, method=\"pad\")\n expected = np.array([0, 0, 1, 1, 2, 2, 3, 3, 4, 4], dtype=np.intp)\n tm.assert_numpy_array_equal(indexer, expected)\n\n target = Int64Index(np.arange(10))\n indexer = index.get_indexer(target, method=\"backfill\")\n expected = np.array([0, 1, 1, 2, 2, 3, 3, 4, 4, 5], dtype=np.intp)\n tm.assert_numpy_array_equal(indexer, expected)\n\n def test_get_indexer_uint64(self, index_large):\n target = UInt64Index(np.arange(10).astype(\"uint64\") * 5 + 2**63)\n indexer = index_large.get_indexer(target)\n expected = np.array([0, -1, 1, 2, 3, 4, -1, -1, -1, -1], dtype=np.intp)\n tm.assert_numpy_array_equal(indexer, expected)\n\n target = UInt64Index(np.arange(10).astype(\"uint64\") * 5 + 2**63)\n indexer = index_large.get_indexer(target, method=\"pad\")\n expected = np.array([0, 0, 1, 2, 3, 4, 4, 4, 4, 4], dtype=np.intp)\n tm.assert_numpy_array_equal(indexer, expected)\n\n target = UInt64Index(np.arange(10).astype(\"uint64\") * 5 + 2**63)\n indexer = index_large.get_indexer(target, method=\"backfill\")\n expected = np.array([0, 1, 1, 2, 3, 4, -1, -1, -1, -1], dtype=np.intp)\n tm.assert_numpy_array_equal(indexer, expected)\n\n\nclass TestWhere:\n @pytest.mark.parametrize(\n \"index\",\n [\n Float64Index(np.arange(5, dtype=\"float64\")),\n Int64Index(range(0, 20, 2)),\n UInt64Index(np.arange(5, dtype=\"uint64\")),\n ],\n )\n def test_where(self, listlike_box, index):\n cond = [True] * len(index)\n expected = index\n result = index.where(listlike_box(cond))\n\n cond = [False] + [True] * (len(index) - 1)\n expected = Float64Index([index._na_value] + index[1:].tolist())\n result = index.where(listlike_box(cond))\n tm.assert_index_equal(result, expected)\n\n def test_where_uint64(self):\n idx = UInt64Index([0, 6, 2])\n mask = np.array([False, True, False])\n other = np.array([1], dtype=np.int64)\n\n expected = UInt64Index([1, 6, 1])\n\n result = idx.where(mask, other)\n tm.assert_index_equal(result, expected)\n\n result = idx.putmask(~mask, other)\n tm.assert_index_equal(result, expected)\n\n def test_where_infers_type_instead_of_trying_to_convert_string_to_float(self):\n # GH 32413\n index = Index([1, np.nan])\n cond = index.notna()\n other = Index([\"a\", \"b\"], dtype=\"string\")\n\n expected = Index([1.0, \"b\"])\n result = index.where(cond, other)\n\n tm.assert_index_equal(result, expected)\n\n\nclass TestTake:\n @pytest.mark.parametrize(\"klass\", [Float64Index, Int64Index, UInt64Index])\n def test_take_preserve_name(self, klass):\n index = klass([1, 2, 3, 4], name=\"foo\")\n taken = index.take([3, 0, 1])\n assert index.name == taken.name\n\n def test_take_fill_value_float64(self):\n # GH 12631\n idx = Float64Index([1.0, 2.0, 3.0], name=\"xxx\")\n result = idx.take(np.array([1, 0, -1]))\n expected = Float64Index([2.0, 1.0, 3.0], name=\"xxx\")\n tm.assert_index_equal(result, expected)\n\n # fill_value\n result = idx.take(np.array([1, 0, -1]), fill_value=True)\n expected = Float64Index([2.0, 1.0, np.nan], name=\"xxx\")\n tm.assert_index_equal(result, expected)\n\n # allow_fill=False\n result = idx.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True)\n expected = Float64Index([2.0, 1.0, 3.0], name=\"xxx\")\n tm.assert_index_equal(result, expected)\n\n msg = (\n \"When allow_fill=True and fill_value is not None, \"\n \"all indices must be >= -1\"\n )\n with pytest.raises(ValueError, match=msg):\n idx.take(np.array([1, 0, -2]), fill_value=True)\n with pytest.raises(ValueError, match=msg):\n idx.take(np.array([1, 0, -5]), fill_value=True)\n\n msg = \"index -5 is out of bounds for (axis 0 with )?size 3\"\n with pytest.raises(IndexError, match=msg):\n idx.take(np.array([1, -5]))\n\n @pytest.mark.parametrize(\"klass\", [Int64Index, UInt64Index])\n def test_take_fill_value_ints(self, klass):\n # see gh-12631\n idx = klass([1, 2, 3], name=\"xxx\")\n result = idx.take(np.array([1, 0, -1]))\n expected = klass([2, 1, 3], name=\"xxx\")\n tm.assert_index_equal(result, expected)\n\n name = klass.__name__\n msg = f\"Unable to fill values because {name} cannot contain NA\"\n\n # fill_value=True\n with pytest.raises(ValueError, match=msg):\n idx.take(np.array([1, 0, -1]), fill_value=True)\n\n # allow_fill=False\n result = idx.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True)\n expected = klass([2, 1, 3], name=\"xxx\")\n tm.assert_index_equal(result, expected)\n\n with pytest.raises(ValueError, match=msg):\n idx.take(np.array([1, 0, -2]), fill_value=True)\n with pytest.raises(ValueError, match=msg):\n idx.take(np.array([1, 0, -5]), fill_value=True)\n\n msg = \"index -5 is out of bounds for (axis 0 with )?size 3\"\n with pytest.raises(IndexError, match=msg):\n idx.take(np.array([1, -5]))\n\n\nclass TestContains:\n @pytest.mark.parametrize(\"klass\", [Float64Index, Int64Index, UInt64Index])\n def test_contains_none(self, klass):\n # GH#35788 should return False, not raise TypeError\n index = klass([0, 1, 2, 3, 4])\n assert None not in index\n\n def test_contains_float64_nans(self):\n index = Float64Index([1.0, 2.0, np.nan])\n assert np.nan in index\n\n def test_contains_float64_not_nans(self):\n index = Float64Index([1.0, 2.0, np.nan])\n assert 1.0 in index\n\n\nclass TestSliceLocs:\n @pytest.mark.parametrize(\"dtype\", [int, float])\n def test_slice_locs(self, dtype):\n index = Index(np.array([0, 1, 2, 5, 6, 7, 9, 10], dtype=dtype))\n n = len(index)\n\n assert index.slice_locs(start=2) == (2, n)\n assert index.slice_locs(start=3) == (3, n)\n assert index.slice_locs(3, 8) == (3, 6)\n assert index.slice_locs(5, 10) == (3, n)\n assert index.slice_locs(end=8) == (0, 6)\n assert index.slice_locs(end=9) == (0, 7)\n\n # reversed\n index2 = index[::-1]\n assert index2.slice_locs(8, 2) == (2, 6)\n assert index2.slice_locs(7, 3) == (2, 5)\n\n @pytest.mark.parametrize(\"dtype\", [int, float])\n def test_slice_locs_float_locs(self, dtype):\n index = Index(np.array([0, 1, 2, 5, 6, 7, 9, 10], dtype=dtype))\n n = len(index)\n assert index.slice_locs(5.0, 10.0) == (3, n)\n assert index.slice_locs(4.5, 10.5) == (3, 8)\n\n index2 = index[::-1]\n assert index2.slice_locs(8.5, 1.5) == (2, 6)\n assert index2.slice_locs(10.5, -1) == (0, n)\n\n @pytest.mark.parametrize(\"dtype\", [int, float])\n def test_slice_locs_dup_numeric(self, dtype):\n index = Index(np.array([10, 12, 12, 14], dtype=dtype))\n assert index.slice_locs(12, 12) == (1, 3)\n assert index.slice_locs(11, 13) == (1, 3)\n\n index2 = index[::-1]\n assert index2.slice_locs(12, 12) == (1, 3)\n assert index2.slice_locs(13, 11) == (1, 3)\n\n def test_slice_locs_na(self):\n index = Index([np.nan, 1, 2])\n assert index.slice_locs(1) == (1, 3)\n assert index.slice_locs(np.nan) == (0, 3)\n\n index = Index([0, np.nan, np.nan, 1, 2])\n assert index.slice_locs(np.nan) == (1, 5)\n\n def test_slice_locs_na_raises(self):\n index = Index([np.nan, 1, 2])\n with pytest.raises(KeyError, match=\"\"):\n index.slice_locs(start=1.5)\n\n with pytest.raises(KeyError, match=\"\"):\n index.slice_locs(end=1.5)\n\n\nclass TestGetSliceBounds:\n @pytest.mark.parametrize(\"kind\", [\"getitem\", \"loc\", None])\n @pytest.mark.parametrize(\"side, expected\", [(\"left\", 4), (\"right\", 5)])\n def test_get_slice_bounds_within(self, kind, side, expected):\n index = Index(range(6))\n with tm.assert_produces_warning(FutureWarning, match=\"'kind' argument\"):\n\n result = index.get_slice_bound(4, kind=kind, side=side)\n assert result == expected\n\n @pytest.mark.parametrize(\"kind\", [\"getitem\", \"loc\", None])\n @pytest.mark.parametrize(\"side\", [\"left\", \"right\"])\n @pytest.mark.parametrize(\"bound, expected\", [(-1, 0), (10, 6)])\n def test_get_slice_bounds_outside(self, kind, side, expected, bound):\n index = Index(range(6))\n with tm.assert_produces_warning(FutureWarning, match=\"'kind' argument\"):\n result = index.get_slice_bound(bound, kind=kind, side=side)\n assert result == expected\n"
] | [
[
"pandas.MultiIndex",
"numpy.arange",
"pandas.Index",
"pandas.option_context",
"pandas.DataFrame"
],
[
"pandas._libs.parsers.sanitize_objects",
"numpy.asarray",
"pandas.core.dtypes.common.is_extension_array_dtype",
"pandas._libs.lib.maybe_convert_numeric",
"pandas.core.dtypes.common.is_dtype_equal",
"pandas.errors.ParserError",
"numpy.dtype",
"pandas.core.dtypes.common.ensure_object",
"pandas.core.series.Series",
"pandas._libs.lib.map_infer_mask",
"pandas.core.dtypes.astype.astype_nansafe",
"pandas._libs.lib.map_infer",
"pandas.core.dtypes.common.is_dict_like",
"pandas.core.dtypes.common.is_string_dtype",
"pandas.core.dtypes.common.is_categorical_dtype",
"pandas.core.dtypes.common.is_list_like",
"numpy.putmask",
"pandas.core.dtypes.common.is_integer_dtype",
"pandas._libs.tslibs.parsing.try_parse_dates",
"pandas.core.indexes.api.ensure_index_from_sequences",
"pandas.core.dtypes.common.pandas_dtype",
"pandas.io.date_converters.generic_parser",
"pandas.core.indexes.api.Index",
"pandas.util._exceptions.find_stack_level",
"pandas.core.dtypes.common.is_bool_dtype",
"pandas.core.algorithms.isin",
"pandas.core.dtypes.common.is_scalar",
"pandas._libs.tslibs.parsing.concat_date_cols",
"pandas.core.dtypes.common.is_integer",
"pandas.core.dtypes.common.is_object_dtype",
"pandas._libs.lib.is_bool",
"pandas.core.dtypes.missing.isna",
"pandas._libs.lib.infer_dtype",
"pandas.core.indexes.api.MultiIndex.from_tuples"
],
[
"pandas.core.dtypes.common.is_list_like",
"numpy.imag",
"pandas.Series",
"numpy.asarray",
"pandas.Categorical",
"numpy.issubdtype",
"pandas.factorize",
"pandas.MultiIndex.from_tuples",
"numpy.real",
"numpy.uint64",
"numpy.zeros_like",
"pandas._libs.hashing.hash_object_array",
"numpy.array",
"pandas.Index._with_infer",
"pandas.core.dtypes.common.is_categorical_dtype"
],
[
"pandas._testing.assert_produces_warning",
"pandas.Series",
"numpy.isnan",
"numpy.arange",
"pandas.Timedelta",
"pandas._testing.assert_frame_equal",
"numpy.random.randn",
"pandas.date_range",
"pandas._testing.assert_series_equal",
"numpy.array"
],
[
"pandas.date_range"
],
[
"pandas._testing.assert_produces_warning",
"matplotlib.colors.CSS4_COLORS.items",
"pandas.io.formats.excel.CSSToExcelConverter.NAMED_COLORS.values",
"pandas.io.formats.excel.CSSToExcelConverter",
"pandas.io.formats.excel.CSSToExcelConverter.NAMED_COLORS.items"
],
[
"pandas._testing.assert_almost_equal",
"pandas._testing.assert_produces_warning",
"pandas._testing.assert_numpy_array_equal",
"pandas.Timestamp",
"pandas.RangeIndex",
"pandas.core.indexes.api.UInt64Index",
"numpy.arange",
"pandas.Index",
"pandas.core.indexes.api.Float64Index",
"numpy.iinfo",
"numpy.array",
"pandas._testing.assert_index_equal"
]
] | [
{
"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",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"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",
"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": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jackd/graphics | [
"736b99a3306e302674a9b7599e3e2857b85fdb74",
"736b99a3306e302674a9b7599e3e2857b85fdb74",
"736b99a3306e302674a9b7599e3e2857b85fdb74"
] | [
"tensorflow_graphics/nn/metric/tests/fscore_test.py",
"tensorflow_graphics/notebooks/mesh_viewer.py",
"tensorflow_graphics/nn/layer/tests/graph_convolution_test.py"
] | [
"# Copyright 2020 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Tests for the fscore metric.\"\"\"\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_graphics.nn.metric import fscore\nfrom tensorflow_graphics.nn.metric import precision\nfrom tensorflow_graphics.nn.metric import recall\nfrom tensorflow_graphics.util import test_case\n\n\ndef random_tensor(tensor_shape):\n return np.random.uniform(low=0.0, high=1.0, size=tensor_shape)\n\n\ndef random_tensor_shape():\n tensor_size = np.random.randint(5) + 1\n return np.random.randint(1, 10, size=(tensor_size)).tolist()\n\n\ndef binary_precision_function(ground_truth, predictions):\n return precision.evaluate(ground_truth, predictions, classes=[1])\n\n\ndef binary_recall_function(ground_truth, predictions):\n return recall.evaluate(ground_truth, predictions, classes=[1])\n\n\nclass FscoreTest(test_case.TestCase):\n\n @parameterized.parameters(\n # Precision = 0.5, Recall = 0.25.\n ((0, 1, 1, 1, 1), (1, 1, 0, 0, 0), 2 * (0.5 * 0.25) / (0.5 + 0.25)),\n # Precision = 1, Recall = 1.\n ((0, 0, 0, 1, 1, 1, 0, 1), (0, 0, 0, 1, 1, 1, 0, 1), 1),\n # Precision = 0, Recall = 0.\n ((0, 1, 0, 0, 0, 0), (0, 0, 0, 0, 0, 0), 0))\n def test_evaluate_preset(self, ground_truth, predictions, expected_fscore):\n tensor_shape = random_tensor_shape()\n\n ground_truth_labels = np.tile(ground_truth, tensor_shape + [1])\n predicted_labels = np.tile(predictions, tensor_shape + [1])\n expected = np.tile(expected_fscore, tensor_shape)\n\n result = fscore.evaluate(\n ground_truth_labels,\n predicted_labels,\n precision_function=binary_precision_function,\n recall_function=binary_recall_function)\n\n self.assertAllClose(expected, result)\n\n @parameterized.parameters(\n (\"Not all batch dimensions are broadcast-compatible.\", (1, 5, 3), (4, 3)),\n (\"Not all batch dimensions are broadcast-compatible.\", (3, 4), (2, 4, 5)),\n )\n def test_evaluate_shape_exception_raised(self, error_msg, *shape):\n \"\"\"Tests that the shape exception is raised.\"\"\"\n self.assert_exception_is_raised(fscore.evaluate, error_msg, shape)\n\n @parameterized.parameters(\n ((1, 5, 3), (2, 5, 1)),\n ((None, 2, 6), (4, 2, None)),\n ((3, 1, 1, 2), (3, 5, 8, 2)),\n )\n def test_evaluate_shape_exception_not_raised(self, *shapes):\n \"\"\"Tests that the shape exceptions are not raised.\"\"\"\n self.assert_exception_is_not_raised(fscore.evaluate, shapes)\n\n\nif __name__ == \"__main__\":\n test_case.main()\n",
"# Copyright 2020 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Helper class for viewing 3D meshes in Colab demos.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nfrom tensorflow_graphics.notebooks import threejs_visualization\n\nSEGMENTATION_COLORMAP = np.array(\n ((165, 242, 12), (89, 12, 89), (165, 89, 165), (242, 242, 165),\n (242, 165, 12), (89, 12, 12), (165, 12, 12), (165, 89, 242), (12, 12, 165),\n (165, 12, 89), (12, 89, 89), (165, 165, 89), (89, 242, 12), (12, 89, 165),\n (242, 242, 89), (165, 165, 165)),\n dtype=np.float32) / 255.0\n\n\nclass Viewer(object):\n \"\"\"A ThreeJS based viewer class for viewing 3D meshes.\"\"\"\n\n def _mesh_from_data(self, data):\n \"\"\"Creates a dictionary of ThreeJS mesh objects from numpy data.\"\"\"\n if 'vertices' not in data or 'faces' not in data:\n raise ValueError('Mesh Data must contain vertices and faces')\n vertices = np.asarray(data['vertices'])\n faces = np.asarray(data['faces'])\n material = self.context.THREE.MeshLambertMaterial.new_object({\n 'color': 0xfffacd,\n 'vertexColors': self.context.THREE.NoColors,\n 'side': self.context.THREE.DoubleSide,\n })\n mesh = {'vertices': vertices, 'faces': faces}\n if 'vertex_colors' in data:\n mesh['vertex_colors'] = np.asarray(data['vertex_colors'])\n material = self.context.THREE.MeshLambertMaterial.new_object({\n 'color': 0xfffacd,\n 'vertexColors': self.context.THREE.VertexColors,\n 'side': self.context.THREE.DoubleSide,\n })\n mesh['material'] = material\n return mesh\n\n def __init__(self, source_mesh_data):\n context = threejs_visualization.build_context()\n self.context = context\n light1 = context.THREE.PointLight.new_object(0x808080)\n light1.position.set(10., 10., 10.)\n light2 = context.THREE.AmbientLight.new_object(0x808080)\n lights = (light1, light2)\n\n camera = threejs_visualization.build_perspective_camera(\n field_of_view=30, position=(0.0, 0.0, 4.0))\n\n mesh = self._mesh_from_data(source_mesh_data)\n geometries = threejs_visualization.triangular_mesh_renderer([mesh],\n lights=lights,\n camera=camera,\n width=400,\n height=400)\n\n self.geometries = geometries\n",
"# Copyright 2020 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Tests for the graph convolution layers.\"\"\"\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\nimport tensorflow as tf\n\nimport tensorflow_graphics.nn.layer.graph_convolution as gc_layer\nfrom tensorflow_graphics.util import test_case\n\n\ndef _dense_to_sparse(data):\n \"\"\"Convert a numpy array to a tf.SparseTensor.\"\"\"\n indices = np.where(data)\n return tf.SparseTensor(\n np.stack(indices, axis=-1), data[indices], dense_shape=data.shape)\n\n\ndef _dummy_data(batch_size, num_vertices, num_channels):\n \"\"\"Create inputs for feature_steered_convolution.\"\"\"\n if batch_size > 0:\n data = np.zeros(\n shape=(batch_size, num_vertices, num_channels), dtype=np.float32)\n neighbors = _dense_to_sparse(\n np.tile(np.eye(num_vertices, dtype=np.float32), (batch_size, 1, 1)))\n else:\n data = np.zeros(shape=(num_vertices, num_channels), dtype=np.float32)\n neighbors = _dense_to_sparse(np.eye(num_vertices, dtype=np.float32))\n return data, neighbors\n\n\nclass GraphConvolutionTestFeatureSteeredConvolutionLayerTests(\n test_case.TestCase):\n\n @parameterized.parameters(\n (1, 1, 1, 1, 1, False),\n (4, 2, 3, None, 5, False),\n (1, 2, 3, 4, 5, True),\n )\n def test_feature_steered_convolution_layer_exception_not_raised_shapes(\n self, batch_size, num_vertices, in_channels, out_channels,\n num_weight_matrices, translation_invariant):\n \"\"\"Check if the convolution parameters and output have correct shapes.\"\"\"\n data, neighbors = _dummy_data(batch_size, num_vertices, in_channels)\n name_scope = \"test\"\n if tf.executing_eagerly():\n layer = gc_layer.FeatureSteeredConvolutionKerasLayer(\n translation_invariant=translation_invariant,\n num_weight_matrices=num_weight_matrices,\n num_output_channels=out_channels,\n name=name_scope)\n\n def _run_convolution():\n \"\"\"Run the appropriate feature steered convolution layer.\"\"\"\n if tf.executing_eagerly():\n try:\n output = layer(inputs=[data, neighbors], sizes=None)\n except Exception as e: # pylint: disable=broad-except\n self.fail(\"Exception raised: %s\" % str(e))\n else:\n try:\n output = gc_layer.feature_steered_convolution_layer(\n data=data,\n neighbors=neighbors,\n sizes=None,\n translation_invariant=translation_invariant,\n num_weight_matrices=num_weight_matrices,\n num_output_channels=out_channels,\n name=None,\n var_name=name_scope)\n except Exception as e: # pylint: disable=broad-except\n self.fail(\"Exception raised: %s\" % str(e))\n return output\n\n output = _run_convolution()\n output_shape = output.shape.as_list()\n out_channels = in_channels if out_channels is None else out_channels\n\n self.assertEqual(output_shape[-1], out_channels)\n self.assertAllEqual(output_shape[:-1], data.shape[:-1])\n\n def _get_var_shape(var_name):\n \"\"\"Get the shape of a variable by name.\"\"\"\n if tf.executing_eagerly():\n trainable_variables = layer.trainable_variables\n for tv in trainable_variables:\n if tv.name == name_scope + \"/\" + var_name + \":0\":\n return tv.shape.as_list()\n raise ValueError(\"Variable not found.\")\n else:\n with tf.compat.v1.variable_scope(name_scope, reuse=True):\n variable = tf.compat.v1.get_variable(\n var_name, initializer=tf.constant(0))\n return variable.shape.as_list()\n\n self.assertAllEqual(_get_var_shape(\"u\"), [in_channels, num_weight_matrices])\n self.assertAllEqual(_get_var_shape(\"c\"), [num_weight_matrices])\n self.assertAllEqual(_get_var_shape(\"b\"), [out_channels])\n self.assertAllEqual(\n _get_var_shape(\"w\"), [num_weight_matrices, in_channels, out_channels])\n if not translation_invariant:\n self.assertAllEqual(\n _get_var_shape(\"v\"), [in_channels, num_weight_matrices])\n\n def test_feature_steered_convolution_layer_initializer(self):\n \"\"\"Tests a custom variable initializer.\"\"\"\n data = np.array(((1.0, 1.0), (-1.0, 1.0), (-1.0, -1.0), (1.0, -1.0)))\n neighbors_indices = np.array(((0, 0), (0, 1), (0, 3),\n (1, 0), (1, 1), (1, 2),\n (2, 1), (2, 2), (2, 3),\n (3, 0), (3, 2), (3, 3)))\n neighbors = tf.SparseTensor(\n neighbors_indices, np.ones(shape=(12,)) / 3.0, dense_shape=(4, 4))\n initializer = tf.compat.v1.keras.initializers.zeros()\n\n if tf.executing_eagerly():\n layer = gc_layer.FeatureSteeredConvolutionKerasLayer(\n translation_invariant=False,\n initializer=initializer)\n output = layer(inputs=[data, neighbors], sizes=None)\n else:\n out = gc_layer.feature_steered_convolution_layer(\n data=data,\n neighbors=neighbors,\n sizes=None,\n translation_invariant=False,\n initializer=initializer)\n self.evaluate(tf.compat.v1.global_variables_initializer())\n output = self.evaluate(out)\n\n # All zeros initializer should result in all zeros output.\n self.assertAllEqual(output, np.zeros_like(data))\n\n def test_feature_steered_convolution_layer_training(self):\n \"\"\"Test a simple training loop.\"\"\"\n # Generate a small valid input for a simple training task.\n # Four corners of a square.\n data = np.array(((1.0, 1.0), (-1.0, 1.0), (-1.0, -1.0), (1.0, -1.0)))\n neighbors_indices = np.array(((0, 0), (0, 1), (0, 3),\n (1, 0), (1, 1), (1, 2),\n (2, 1), (2, 2), (2, 3),\n (3, 0), (3, 2), (3, 3)))\n neighbors = tf.SparseTensor(\n neighbors_indices, np.ones(shape=(12,)) / 3.0, dense_shape=(4, 4))\n # Desired output is arbitrary.\n labels = np.reshape([-1.0, -0.5, 0.5, 1.0], (-1, 1))\n num_training_iterations = 5\n\n if tf.executing_eagerly():\n with tf.GradientTape(persistent=True) as tape:\n layer = gc_layer.FeatureSteeredConvolutionKerasLayer(\n translation_invariant=False,\n num_weight_matrices=1,\n num_output_channels=1)\n output = layer(inputs=[data, neighbors], sizes=None)\n loss = tf.nn.l2_loss(output - labels)\n\n trainable_variables = layer.trainable_variables\n for _ in range(num_training_iterations):\n grads = tape.gradient(loss, trainable_variables)\n tf.compat.v1.train.GradientDescentOptimizer(1e-4).apply_gradients(\n zip(grads, trainable_variables))\n else:\n output = gc_layer.feature_steered_convolution_layer(\n data=data,\n neighbors=neighbors,\n sizes=None,\n translation_invariant=False,\n num_weight_matrices=1,\n num_output_channels=1)\n train_op = tf.compat.v1.train.GradientDescentOptimizer(1e-4).minimize(\n tf.nn.l2_loss(output - labels))\n with tf.compat.v1.Session() as sess:\n sess.run(tf.compat.v1.initialize_all_variables())\n for _ in range(num_training_iterations):\n sess.run(train_op)\n\n\nclass GraphConvolutionTestDynamicGraphConvolutionKerasLayerTests(\n test_case.TestCase):\n\n @parameterized.parameters(\n (1, 1, 1, 1, \"weighted\"),\n (4, 2, 3, 12, \"max\"),\n (1, 2, 3, 4, \"max\"),\n )\n def test_dynamic_graph_convolution_keras_layer_exception_not_raised_shapes(\n self, batch_size, num_vertices, in_channels, out_channels, reduction):\n \"\"\"Check if the convolution parameters and output have correct shapes.\"\"\"\n if not tf.executing_eagerly():\n return\n data, neighbors = _dummy_data(batch_size, num_vertices, in_channels)\n layer = gc_layer.DynamicGraphConvolutionKerasLayer(\n num_output_channels=out_channels,\n reduction=reduction)\n\n try:\n output = layer(inputs=[data, neighbors], sizes=None)\n except Exception as e: # pylint: disable=broad-except\n self.fail(\"Exception raised: %s\" % str(e))\n\n self.assertAllEqual((batch_size, num_vertices, out_channels), output.shape)\n\n @parameterized.parameters(\n (1, 1, 1, 1, \"weighted\"),\n (4, 2, 3, 12, \"max\"),\n (1, 2, 3, 4, \"max\"),\n )\n def test_dynamic_graph_convolution_keras_layer_zero_kernel(\n self, batch_size, num_vertices, in_channels, out_channels, reduction):\n \"\"\"Tests convolution with an all-zeros kernel.\"\"\"\n if not tf.executing_eagerly():\n return\n data, neighbors = _dummy_data(batch_size, num_vertices, in_channels)\n data = np.random.uniform(size=data.shape).astype(np.float32)\n layer = gc_layer.DynamicGraphConvolutionKerasLayer(\n num_output_channels=out_channels,\n reduction=reduction,\n use_bias=False,\n kernel_initializer=tf.compat.v1.keras.initializers.zeros())\n\n output = layer(inputs=[data, neighbors], sizes=None)\n\n self.assertAllEqual(\n output,\n np.zeros(shape=(batch_size, num_vertices, out_channels),\n dtype=np.float32))\n\n @parameterized.parameters((1, 1, 1), (2, 3, 12), (2, 3, 4))\n def test_dynamic_graph_convolution_keras_layer_duplicate_features(\n self, num_vertices, in_channels, out_channels):\n \"\"\"Tests convolution when all vertex features are identical.\"\"\"\n if not tf.executing_eagerly():\n return\n data = np.random.uniform(size=(1, in_channels))\n data = np.tile(data, (num_vertices, 1))\n # Results should be independent of 'neighbors'.\n neighbors = np.maximum(np.random.randint(\n 0, 2, size=(num_vertices, num_vertices)), np.eye(num_vertices))\n neighbors = _dense_to_sparse(neighbors)\n layer = gc_layer.DynamicGraphConvolutionKerasLayer(\n num_output_channels=out_channels,\n reduction=\"max\")\n\n output = layer(inputs=[data, neighbors], sizes=None)\n\n output_tile = tf.tile(output[:1, :], (num_vertices, 1))\n\n self.assertAllEqual(output, output_tile)\n\n @parameterized.parameters(\"weighted\", \"max\")\n def test_dynamic_graph_convolution_keras_layer_training(self, reduction):\n \"\"\"Test a simple training loop.\"\"\"\n if not tf.executing_eagerly():\n return\n # Generate a small valid input for a simple training task.\n # Four corners of a square.\n data = np.array(((1.0, 1.0), (-1.0, 1.0), (-1.0, -1.0), (1.0, -1.0)))\n neighbors_indices = np.array(((0, 0), (0, 1), (0, 3),\n (1, 0), (1, 1), (1, 2),\n (2, 1), (2, 2), (2, 3),\n (3, 0), (3, 2), (3, 3)))\n neighbors = tf.SparseTensor(\n neighbors_indices, np.ones(shape=(12,)) / 3.0, dense_shape=(4, 4))\n # Desired output is arbitrary.\n labels = np.reshape([-1.0, -0.5, 0.5, 1.0], (-1, 1))\n num_training_iterations = 5\n\n with tf.GradientTape(persistent=True) as tape:\n layer = gc_layer.DynamicGraphConvolutionKerasLayer(\n num_output_channels=2,\n reduction=reduction)\n output = layer(inputs=[data, neighbors], sizes=None)\n loss = tf.nn.l2_loss(output - labels)\n\n trainable_variables = layer.trainable_variables\n for _ in range(num_training_iterations):\n grads = tape.gradient(loss, trainable_variables)\n tf.compat.v1.train.GradientDescentOptimizer(1e-4).apply_gradients(\n zip(grads, trainable_variables))\n\nif __name__ == \"__main__\":\n test_case.main()\n"
] | [
[
"numpy.random.uniform",
"numpy.tile",
"numpy.random.randint"
],
[
"numpy.asarray",
"numpy.array"
],
[
"tensorflow.compat.v1.initialize_all_variables",
"tensorflow.nn.l2_loss",
"numpy.zeros_like",
"numpy.where",
"numpy.random.randint",
"numpy.reshape",
"numpy.eye",
"numpy.stack",
"tensorflow.compat.v1.variable_scope",
"tensorflow.tile",
"numpy.zeros",
"tensorflow.compat.v1.train.GradientDescentOptimizer",
"tensorflow.executing_eagerly",
"numpy.array",
"tensorflow.GradientTape",
"tensorflow.compat.v1.keras.initializers.zeros",
"tensorflow.constant",
"numpy.tile",
"numpy.ones",
"tensorflow.compat.v1.global_variables_initializer",
"tensorflow.compat.v1.Session",
"numpy.random.uniform"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
zhaodi-Wen/Child_skin_disease_detect | [
"e95045341e8c27161eebb2c9c3b68026a4ea247b",
"e95045341e8c27161eebb2c9c3b68026a4ea247b"
] | [
"src/src/create_tf_record.py",
"src/src/slim/train_image_classifier.py"
] | [
"# -*-coding: utf-8 -*-\n\"\"\"\n @Project: create_tfrecord\n @File : create_tfrecord.py\n @Author : panjq\n @E-mail : [email protected]\n @Date : 2018-07-27 17:19:54\n @desc : 将图片数据保存为单个tfrecord文件\n\"\"\"\n\n##########################################################################\n\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport cv2\nimport matplotlib.pyplot as plt\nimport random\nfrom PIL import Image\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\"\n\ntrain_path = './train_new/img'\ntest_path = './test_new/img'\nlist = set(os.listdir(test_path))\nclasses=sorted(list,key=str.lower)\nprint(classes)\n##########################################################################\ndef _int64_feature(value):\n return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))\n# 生成字符串型的属性\ndef _bytes_feature(value):\n return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))\n# 生成实数型的属性\ndef float_list_feature(value):\n return tf.train.Feature(float_list=tf.train.FloatList(value=value))\n\ndef get_example_nums(tf_records_filenames):\n '''\n 统计tf_records图像的个数(example)个数\n :param tf_records_filenames: tf_records文件路径\n :return:\n '''\n nums= 0\n for record in tf.python_io.tf_record_iterator(tf_records_filenames):\n nums += 1\n return nums\n\ndef show_image(title,image):\n '''\n 显示图片\n :param title: 图像标题\n :param image: 图像的数据\n :return:\n '''\n # plt.figure(\"show_image\")\n # print(image.dtype)\n plt.imshow(image)\n plt.axis('on') # 关掉坐标轴为 off\n plt.title(title) # 图像题目\n plt.show()\n\n# def load_labels_file(filename,labels_num=1,shuffle=False):\n# '''\n# 载图txt文件,文件中每行为一个图片信息,且以空格隔开:图像路径 标签1 标签2,如:test_image/1.jpg 0 2\n# :param filename:\n# :param labels_num :labels个数\n# :param shuffle :是否打乱顺序\n# :return:images type->list\n# :return:labels type->list\n# '''\n# images=[]\n# labels=[]\n# with open(filename) as f:\n# lines_list=f.readlines()\n# if shuffle:\n# random.shuffle(lines_list)\n#\n# for lines in lines_list:\n# line=lines.rstrip().split(' ')\n# label=[]\n# for i in range(labels_num):\n# label.append(int(line[i+1]))\n# images.append(line[0])\n# labels.append(label)\n# return images,labels\n\ndef load_labels_file(filename,num=1,shuffle=False):\n '''\n 载图txt文件,文件中每行为一个图片信息,且以空格隔开:图像路径 标签1 标签2,如:test_image/1.jpg 0 2\n :param filename:\n :param labels_num :labels个数\n :param shuffle :是否打乱顺序\n :return:images type->list\n :return:labels type->list\n '''\n images=[]\n labels=[]\n # with open(filename) as f:\n # lines_list=f.readlines()\n # if shuffle:\n # random.shuffle(lines_list)\n #\n # for lines in lines_list:\n # line=lines.rstrip().split(' ')\n # label=[]\n # for i in range(labels_num):\n # label.append(int(line[i+1]))\n # images.append(line[0])\n # labels.append(label)\n # return images,labels\n for index,name in enumerate(classes):\n # print(index,name)\n class_path = filename+'/'+name+'/'\n # print(class_path)\n for img_name in os.listdir(class_path):\n img_path = class_path+img_name\n # print(img_path)\n images.append(img_path)\n labels.append(index)\n # img = Image.open(img_path)\n\n # img = img.resize((224,224))\n # img_raw = img.tobytes()\n # with open(train_label,'a') as f:\n # f.write(str(index)+'\\n')\n randnum = random.randint(0, 100)\n random.seed(randnum)\n random.shuffle(images)\n random.seed(randnum)\n random.shuffle(labels)\n return images,labels\n\ndef read_image(filename, resize_height, resize_width,normalization=False):\n '''\n 读取图片数据,默认返回的是uint8,[0,255]\n :param filename:\n :param resize_height:\n :param resize_width:\n :param normalization:是否归一化到[0.,1.0]\n :return: 返回的图片数据\n '''\n\n bgr_image = cv2.imread(filename)\n if len(bgr_image.shape)==2:#若是灰度图则转为三通道\n print(\"Warning:gray image\",filename)\n bgr_image = cv2.cvtColor(bgr_image, cv2.COLOR_GRAY2BGR)\n\n rgb_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2RGB)#将BGR转为RGB\n # show_image(filename,rgb_image)\n # rgb_image=Image.open(filename)\n if resize_height>0 and resize_width>0:\n rgb_image=cv2.resize(rgb_image,(resize_width,resize_height))\n rgb_image=np.asanyarray(rgb_image)\n if normalization:\n # 不能写成:rgb_image=rgb_image/255\n rgb_image=rgb_image/255.0\n # show_image(\"src resize image\",image)\n return rgb_image\n\n\ndef get_batch_images(images,labels,batch_size,labels_nums,one_hot=False,shuffle=False,num_threads=64):\n '''\n :param images:图像\n :param labels:标签\n :param batch_size:\n :param labels_nums:标签个数\n :param one_hot:是否将labels转为one_hot的形式\n :param shuffle:是否打乱顺序,一般train时shuffle=True,验证时shuffle=False\n :return:返回batch的images和labels\n '''\n min_after_dequeue = 200\n capacity = min_after_dequeue + 3 * batch_size # 保证capacity必须大于min_after_dequeue参数值\n if shuffle:\n images_batch, labels_batch = tf.train.shuffle_batch([images,labels],\n batch_size=batch_size,\n capacity=capacity,\n min_after_dequeue=min_after_dequeue,\n num_threads=num_threads)\n else:\n images_batch, labels_batch = tf.train.batch([images,labels],\n batch_size=batch_size,\n capacity=capacity,\n num_threads=num_threads)\n if one_hot:\n labels_batch = tf.one_hot(labels_batch, labels_nums, 1, 0)\n return images_batch,labels_batch\n\ndef read_records(filename,resize_height, resize_width,type=None):\n '''\n 解析record文件:源文件的图像数据是RGB,uint8,[0,255],一般作为训练数据时,需要归一化到[0,1]\n :param filename:\n :param resize_height:\n :param resize_width:\n :param type:选择图像数据的返回类型\n None:默认将uint8-[0,255]转为float32-[0,255]\n normalization:归一化float32-[0,1]\n centralization:归一化float32-[0,1],再减均值中心化\n :return:\n '''\n # 创建文件队列,不限读取的数量\n filename_queue = tf.train.string_input_producer([filename])\n # create a reader from file queue\n reader = tf.TFRecordReader()\n # reader从文件队列中读入一个序列化的样本\n _, serialized_example = reader.read(filename_queue)\n # get feature from serialized example\n # 解析符号化的样本\n features = tf.parse_single_example(\n serialized_example,\n features={\n 'image_raw': tf.FixedLenFeature([], tf.string),\n 'height': tf.FixedLenFeature([], tf.int64),\n 'width': tf.FixedLenFeature([], tf.int64),\n 'depth': tf.FixedLenFeature([], tf.int64),\n 'label': tf.FixedLenFeature([], tf.int64)\n }\n )\n tf_image = tf.decode_raw(features['image_raw'], tf.uint8)#获得图像原始的数据\n\n tf_height = features['height']\n tf_width = features['width']\n tf_depth = features['depth']\n tf_label = tf.cast(features['label'], tf.int32)\n # PS:恢复原始图像数据,reshape的大小必须与保存之前的图像shape一致,否则出错\n # tf_image=tf.reshape(tf_image, [-1]) # 转换为行向量\n tf_image=tf.reshape(tf_image, [resize_height, resize_width, 3]) # 设置图像的维度\n\n # 恢复数据后,才可以对图像进行resize_images:输入uint->输出float32\n # tf_image=tf.image.resize_images(tf_image,[224, 224])\n\n # 存储的图像类型为uint8,tensorflow训练时数据必须是tf.float32\n if type is None:\n tf_image = tf.cast(tf_image, tf.float32)\n elif type=='normalization':# [1]若需要归一化请使用:\n # 仅当输入数据是uint8,才会归一化[0,255]\n # tf_image = tf.image.convert_image_dtype(tf_image, tf.float32)\n tf_image = tf.cast(tf_image, tf.float32) * (1. / 255.0) # 归一化\n elif type=='centralization':\n # 若需要归一化,且中心化,假设均值为0.5,请使用:\n tf_image = tf.cast(tf_image, tf.float32) * (1. / 255) - 0.5 #中心化\n\n # 这里仅仅返回图像和标签\n # return tf_image, tf_height,tf_width,tf_depth,tf_label\n return tf_image,tf_label\n\n\ndef create_records(image_dir, output_record_dir, resize_height, resize_width,shuffle,log=5):\n '''\n 实现将图像原始数据,label,长,宽等信息保存为record文件\n 注意:读取的图像数据默认是uint8,再转为tf的字符串型BytesList保存,解析请需要根据需要转换类型\n :param image_dir:原始图像的目录\n :param file:输入保存图片信息的txt文件(image_dir+file构成图片的路径)\n :param output_record_dir:保存record文件的路径\n :param resize_height:\n :param resize_width:\n PS:当resize_height或者resize_width=0是,不执行resize\n :param shuffle:是否打乱顺序\n :param log:log信息打印间隔\n '''\n # 加载文件,仅获取一个label\n images_list, labels_list=load_labels_file(image_dir,1,shuffle)\n\n writer = tf.python_io.TFRecordWriter(output_record_dir)\n for i, [image_name, labels] in enumerate(zip(images_list, labels_list)):\n image_path=image_name\n # print(image_path)\n # print(labels)\n if not os.path.exists(image_path):\n print('Err:no image',image_path)\n continue\n image = read_image(image_path, resize_height, resize_width)\n image_raw = image.tostring()\n if i%log==0 or i==len(images_list)-1:\n print('------------processing:%d-th------------' % (i))\n print('current image_path=%s' % (image_path),'shape:{}'.format(image.shape),'labels:{}'.format(labels))\n # 这里仅保存一个label,多label适当增加\"'label': _int64_feature(label)\"项\n label=labels\n example = tf.train.Example(features=tf.train.Features(feature={\n 'image_raw': _bytes_feature(image_raw),\n 'height': _int64_feature(image.shape[0]),\n 'width': _int64_feature(image.shape[1]),\n 'depth': _int64_feature(image.shape[2]),\n 'labels': _int64_feature(label)\n }))\n writer.write(example.SerializeToString())\n writer.close()\n\ndef disp_records(record_file,resize_height, resize_width,show_nums=4):\n '''\n 解析record文件,并显示show_nums张图片,主要用于验证生成record文件是否成功\n :param tfrecord_file: record文件路径\n :return:\n '''\n # 读取record函数\n tf_image, tf_label = read_records(record_file,resize_height,resize_width,type='normalization')\n # 显示前4个图片\n init_op = tf.initialize_all_variables()\n with tf.Session() as sess:\n sess.run(init_op)\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(sess=sess, coord=coord)\n for i in range(show_nums):\n image,label = sess.run([tf_image,tf_label]) # 在会话中取出image和label\n # image = tf_image.eval()\n # 直接从record解析的image是一个向量,需要reshape显示\n # image = image.reshape([height,width,depth])\n #print('shape:{},tpye:{},labels:{}'.format(image.shape,image.dtype,label))\n # pilimg = Image.fromarray(np.asarray(image_eval_reshape))\n # pilimg.show()\n show_image(\"image:%d\"%(label),image)\n coord.request_stop()\n coord.join(threads)\n\n\ndef batch_test(record_file,resize_height, resize_width):\n '''\n :param record_file: record文件路径\n :param resize_height:\n :param resize_width:\n :return:\n :PS:image_batch, label_batch一般作为网络的输入\n '''\n # 读取record函数\n tf_image,tf_label = read_records(record_file,resize_height,resize_width,type='normalization')\n image_batch, label_batch= get_batch_images(tf_image,tf_label,batch_size=4,labels_nums=5,one_hot=False,shuffle=False)\n\n init = tf.global_variables_initializer()\n with tf.Session() as sess: # 开始一个会话\n sess.run(init)\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(coord=coord)\n for i in range(4):\n # 在会话中取出images和labels\n images, labels = sess.run([image_batch, label_batch])\n # 这里仅显示每个batch里第一张图片\n show_image(\"image\", images[0, :, :, :])\n print('shape:{},tpye:{},labels:{}'.format(images.shape,images.dtype,labels))\n\n # 停止所有线程\n coord.request_stop()\n coord.join(threads)\n\n\n# if __name__ == '__main__':\n# # 参数设置\n#\n# resize_height = 224 # 指定存储图片高度\n# resize_width = 224 # 指定存储图片宽度\n# shuffle=True\n# log=5\n# # 产生train.record文件\n# image_dir='dataset/train'\n# train_labels = 'dataset/train.txt' # 图片路径\n# train_record_output = 'dataset/record/train.tfrecords'\n# create_records(image_dir,train_labels, train_record_output, resize_height, resize_width,shuffle,log)\n# train_nums=get_example_nums(train_record_output)\n# print(\"save train example nums={}\".format(train_nums))\n#\n# # 产生val.record文件\n# image_dir='dataset/val'\n# val_labels = 'dataset/val.txt' # 图片路径\n# val_record_output = 'dataset/record/val.tfrecords'\n# create_records(image_dir,val_labels, val_record_output, resize_height, resize_width,shuffle,log)\n# val_nums=get_example_nums(val_record_output)\n# print(\"save val example nums={}\".format(val_nums))\n#\n# # 测试显示函数\n# # disp_records(train_record_output,resize_height, resize_width)\n# batch_test(train_record_output,resize_height, resize_width)\n\nif __name__ == '__main__':\n # 参数设置\n\n resize_height = 224 # 指定存储图片高度\n resize_width = 224 # 指定存储图片宽度\n shuffle=True\n log=5\n # 产生train.record文件\n image_dir='./train_new/img'\n # train_labels = './onsets/train.txt' # 图片路径\n train_record_output = 'train.tfrecord'\n create_records(image_dir, train_record_output, resize_height, resize_width,shuffle,log)\n train_nums=get_example_nums(train_record_output)\n print(\"save train example nums={}\".format(train_nums))\n\n # 产生val.record文件\n image_dir='./test_new/img'\n # val_labels = './onsets/val.txt' # 图片路径\n val_record_output = 'val.tfrecord'\n create_records(image_dir, val_record_output, resize_height, resize_width,shuffle,log)\n val_nums=get_example_nums(val_record_output)\n print(\"save val example nums={}\".format(val_nums))\n\n # 测试显示函数\n # disp_records(train_record_output,resize_height, resize_width)\n # batch_test(train_record_output,resize_height, resize_width)",
"# 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 training script that trains a model using a given dataset.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\n\nfrom datasets import dataset_factory\nfrom deployment import model_deploy\nfrom nets import nets_factory\nfrom preprocessing import preprocessing_factory\nimport os\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\"\nslim = tf.contrib.slim\n\ntf.app.flags.DEFINE_string(\n 'master', '', 'The address of the TensorFlow master to use.')\n\ntf.app.flags.DEFINE_string(\n 'train_dir', '/tmp/tfmodel/',\n 'Directory where checkpoints and event logs are written to.')\n\ntf.app.flags.DEFINE_integer('num_clones', 1,\n 'Number of model clones to deploy. Note For '\n 'historical reasons loss from all clones averaged '\n 'out and learning rate decay happen per clone '\n 'epochs')\n\ntf.app.flags.DEFINE_boolean('clone_on_cpu', False,\n 'Use CPUs to deploy clones.')\n\ntf.app.flags.DEFINE_integer('worker_replicas', 1, 'Number of worker replicas.')\n\ntf.app.flags.DEFINE_integer(\n 'num_ps_tasks', 0,\n 'The number of parameter servers. If the value is 0, then the parameters '\n 'are handled locally by the worker.')\n\ntf.app.flags.DEFINE_integer(\n 'num_readers', 4,\n 'The number of parallel readers that read data from the dataset.')\n\ntf.app.flags.DEFINE_integer(\n 'num_preprocessing_threads', 4,\n 'The number of threads used to create the batches.')\n\ntf.app.flags.DEFINE_integer(\n 'log_every_n_steps', 50,\n 'The frequency with which logs are print.')\n\ntf.app.flags.DEFINE_integer(\n 'save_summaries_secs', 600,\n 'The frequency with which summaries are saved, in seconds.')\n\ntf.app.flags.DEFINE_integer(\n 'save_interval_secs', 600,\n 'The frequency with which the model is saved, in seconds.')\n\ntf.app.flags.DEFINE_integer(\n 'task', 0, 'Task id of the replica running the training.')\n\n######################\n# Optimization Flags #\n######################\n\ntf.app.flags.DEFINE_float(\n 'weight_decay', 0.00004, 'The weight decay on the model weights.')\n\ntf.app.flags.DEFINE_string(\n 'optimizer', 'rmsprop',\n 'The name of the optimizer, one of \"adadelta\", \"adagrad\", \"adam\",'\n '\"ftrl\", \"momentum\", \"sgd\" or \"rmsprop\".')\n\ntf.app.flags.DEFINE_float(\n 'adadelta_rho', 0.95,\n 'The decay rate for adadelta.')\n\ntf.app.flags.DEFINE_float(\n 'adagrad_initial_accumulator_value', 0.1,\n 'Starting value for the AdaGrad accumulators.')\n\ntf.app.flags.DEFINE_float(\n 'adam_beta1', 0.9,\n 'The exponential decay rate for the 1st moment estimates.')\n\ntf.app.flags.DEFINE_float(\n 'adam_beta2', 0.999,\n 'The exponential decay rate for the 2nd moment estimates.')\n\ntf.app.flags.DEFINE_float('opt_epsilon', 1.0, 'Epsilon term for the optimizer.')\n\ntf.app.flags.DEFINE_float('ftrl_learning_rate_power', -0.5,\n 'The learning rate power.')\n\ntf.app.flags.DEFINE_float(\n 'ftrl_initial_accumulator_value', 0.1,\n 'Starting value for the FTRL accumulators.')\n\ntf.app.flags.DEFINE_float(\n 'ftrl_l1', 0.0, 'The FTRL l1 regularization strength.')\n\ntf.app.flags.DEFINE_float(\n 'ftrl_l2', 0.0, 'The FTRL l2 regularization strength.')\n\ntf.app.flags.DEFINE_float(\n 'momentum', 0.9,\n 'The momentum for the MomentumOptimizer and RMSPropOptimizer.')\n\ntf.app.flags.DEFINE_float('rmsprop_momentum', 0.9, 'Momentum.')\n\ntf.app.flags.DEFINE_float('rmsprop_decay', 0.9, 'Decay term for RMSProp.')\n\ntf.app.flags.DEFINE_integer(\n 'quantize_delay', -1,\n 'Number of steps to start quantized training. Set to -1 would disable '\n 'quantized training.')\n\n#######################\n# Learning Rate Flags #\n#######################\n\ntf.app.flags.DEFINE_string(\n 'learning_rate_decay_type',\n 'exponential',\n 'Specifies how the learning rate is decayed. One of \"fixed\", \"exponential\",'\n ' or \"polynomial\"')\n\ntf.app.flags.DEFINE_float('learning_rate', 0.01, 'Initial learning rate.')\n\ntf.app.flags.DEFINE_float(\n 'end_learning_rate', 0.0001,\n 'The minimal end learning rate used by a polynomial decay learning rate.')\n\ntf.app.flags.DEFINE_float(\n 'label_smoothing', 0.0, 'The amount of label smoothing.')\n\ntf.app.flags.DEFINE_float(\n 'learning_rate_decay_factor', 0.94, 'Learning rate decay factor.')\n\ntf.app.flags.DEFINE_float(\n 'num_epochs_per_decay', 2.0,\n 'Number of epochs after which learning rate decays. Note: this flag counts '\n 'epochs per clone but aggregates per sync replicas. So 1.0 means that '\n 'each clone will go over full epoch individually, but replicas will go '\n 'once across all replicas.')\n\ntf.app.flags.DEFINE_bool(\n 'sync_replicas', False,\n 'Whether or not to synchronize the replicas during training.')\n\ntf.app.flags.DEFINE_integer(\n 'replicas_to_aggregate', 1,\n 'The Number of gradients to collect before updating params.')\n\ntf.app.flags.DEFINE_float(\n 'moving_average_decay', None,\n 'The decay to use for the moving average.'\n 'If left as None, then moving averages are not used.')\n\n#######################\n# Dataset Flags #\n#######################\n\ntf.app.flags.DEFINE_string(\n 'dataset_name', 'imagenet', 'The name of the dataset to load.')\n\ntf.app.flags.DEFINE_string(\n 'dataset_split_name', 'train', 'The name of the train/test split.')\n\ntf.app.flags.DEFINE_string(\n 'dataset_dir', None, 'The directory where the dataset files are stored.')\n\ntf.app.flags.DEFINE_integer(\n 'labels_offset', 0,\n 'An offset for the labels in the dataset. This flag is primarily used to '\n 'evaluate the VGG and ResNet architectures which do not use a background '\n 'class for the ImageNet dataset.')\n\ntf.app.flags.DEFINE_string(\n 'model_name', 'inception_v3', 'The name of the architecture to train.')\n\ntf.app.flags.DEFINE_string(\n 'preprocessing_name', None, 'The name of the preprocessing to use. If left '\n 'as `None`, then the model_name flag is used.')\n\ntf.app.flags.DEFINE_integer(\n 'batch_size', 32, 'The number of samples in each batch.')\n\ntf.app.flags.DEFINE_integer(\n 'train_image_size', None, 'Train image size')\n\ntf.app.flags.DEFINE_integer('max_number_of_steps', None,\n 'The maximum number of training steps.')\n\n#####################\n# Fine-Tuning Flags #\n#####################\n\ntf.app.flags.DEFINE_string(\n 'checkpoint_path', None,\n 'The path to a checkpoint from which to fine-tune.')\n\ntf.app.flags.DEFINE_string(\n 'checkpoint_exclude_scopes', None,\n 'Comma-separated list of scopes of variables to exclude when restoring '\n 'from a checkpoint.')\n\ntf.app.flags.DEFINE_string(\n 'trainable_scopes', None,\n 'Comma-separated list of scopes to filter the set of variables to train.'\n 'By default, None would train all the variables.')\n\ntf.app.flags.DEFINE_boolean(\n 'ignore_missing_vars', False,\n 'When restoring a checkpoint would ignore missing variables.')\n\nFLAGS = tf.app.flags.FLAGS\n\n\ndef _configure_learning_rate(num_samples_per_epoch, global_step):\n \"\"\"Configures the learning rate.\n\n Args:\n num_samples_per_epoch: The number of samples in each epoch of training.\n global_step: The global_step tensor.\n\n Returns:\n A `Tensor` representing the learning rate.\n\n Raises:\n ValueError: if\n \"\"\"\n # Note: when num_clones is > 1, this will actually have each clone to go\n # over each epoch FLAGS.num_epochs_per_decay times. This is different\n # behavior from sync replicas and is expected to produce different results.\n decay_steps = int(num_samples_per_epoch * FLAGS.num_epochs_per_decay /\n FLAGS.batch_size)\n\n if FLAGS.sync_replicas:\n decay_steps /= FLAGS.replicas_to_aggregate\n\n if FLAGS.learning_rate_decay_type == 'exponential':\n return tf.train.exponential_decay(FLAGS.learning_rate,\n global_step,\n decay_steps,\n FLAGS.learning_rate_decay_factor,\n staircase=True,\n name='exponential_decay_learning_rate')\n elif FLAGS.learning_rate_decay_type == 'fixed':\n return tf.constant(FLAGS.learning_rate, name='fixed_learning_rate')\n elif FLAGS.learning_rate_decay_type == 'polynomial':\n return tf.train.polynomial_decay(FLAGS.learning_rate,\n global_step,\n decay_steps,\n FLAGS.end_learning_rate,\n power=1.0,\n cycle=False,\n name='polynomial_decay_learning_rate')\n else:\n raise ValueError('learning_rate_decay_type [%s] was not recognized' %\n FLAGS.learning_rate_decay_type)\n\n\ndef _configure_optimizer(learning_rate):\n \"\"\"Configures the optimizer used for training.\n\n Args:\n learning_rate: A scalar or `Tensor` learning rate.\n\n Returns:\n An instance of an optimizer.\n\n Raises:\n ValueError: if FLAGS.optimizer is not recognized.\n \"\"\"\n if FLAGS.optimizer == 'adadelta':\n optimizer = tf.train.AdadeltaOptimizer(\n learning_rate,\n rho=FLAGS.adadelta_rho,\n epsilon=FLAGS.opt_epsilon)\n elif FLAGS.optimizer == 'adagrad':\n optimizer = tf.train.AdagradOptimizer(\n learning_rate,\n initial_accumulator_value=FLAGS.adagrad_initial_accumulator_value)\n elif FLAGS.optimizer == 'adam':\n optimizer = tf.train.AdamOptimizer(\n learning_rate,\n beta1=FLAGS.adam_beta1,\n beta2=FLAGS.adam_beta2,\n epsilon=FLAGS.opt_epsilon)\n elif FLAGS.optimizer == 'ftrl':\n optimizer = tf.train.FtrlOptimizer(\n learning_rate,\n learning_rate_power=FLAGS.ftrl_learning_rate_power,\n initial_accumulator_value=FLAGS.ftrl_initial_accumulator_value,\n l1_regularization_strength=FLAGS.ftrl_l1,\n l2_regularization_strength=FLAGS.ftrl_l2)\n elif FLAGS.optimizer == 'momentum':\n optimizer = tf.train.MomentumOptimizer(\n learning_rate,\n momentum=FLAGS.momentum,\n name='Momentum')\n elif FLAGS.optimizer == 'rmsprop':\n optimizer = tf.train.RMSPropOptimizer(\n learning_rate,\n decay=FLAGS.rmsprop_decay,\n momentum=FLAGS.rmsprop_momentum,\n epsilon=FLAGS.opt_epsilon)\n elif FLAGS.optimizer == 'sgd':\n optimizer = tf.train.GradientDescentOptimizer(learning_rate)\n else:\n raise ValueError('Optimizer [%s] was not recognized' % FLAGS.optimizer)\n return optimizer\n\n\ndef _get_init_fn():\n \"\"\"Returns a function run by the chief worker to warm-start the training.\n\n Note that the init_fn is only run when initializing the model during the very\n first global step.\n\n Returns:\n An init function run by the supervisor.\n \"\"\"\n if FLAGS.checkpoint_path is None:\n return None\n\n # Warn the user if a checkpoint exists in the train_dir. Then we'll be\n # ignoring the checkpoint anyway.\n if tf.train.latest_checkpoint(FLAGS.train_dir):\n tf.logging.info(\n 'Ignoring --checkpoint_path because a checkpoint already exists in %s'\n % FLAGS.train_dir)\n return None\n\n exclusions = []\n if FLAGS.checkpoint_exclude_scopes:\n exclusions = [scope.strip()\n for scope in FLAGS.checkpoint_exclude_scopes.split(',')]\n\n # TODO(sguada) variables.filter_variables()\n variables_to_restore = []\n for var in slim.get_model_variables():\n for exclusion in exclusions:\n if var.op.name.startswith(exclusion):\n break\n else:\n variables_to_restore.append(var)\n\n if tf.gfile.IsDirectory(FLAGS.checkpoint_path):\n checkpoint_path = tf.train.latest_checkpoint(FLAGS.checkpoint_path)\n else:\n checkpoint_path = FLAGS.checkpoint_path\n\n tf.logging.info('Fine-tuning from %s' % checkpoint_path)\n\n return slim.assign_from_checkpoint_fn(\n checkpoint_path,\n variables_to_restore,\n ignore_missing_vars=FLAGS.ignore_missing_vars)\n\n\ndef _get_variables_to_train():\n \"\"\"Returns a list of variables to train.\n\n Returns:\n A list of variables to train by the optimizer.\n \"\"\"\n if FLAGS.trainable_scopes is None:\n return tf.trainable_variables()\n else:\n scopes = [scope.strip() for scope in FLAGS.trainable_scopes.split(',')]\n\n variables_to_train = []\n for scope in scopes:\n variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope)\n variables_to_train.extend(variables)\n return variables_to_train\n\n\ndef main(_):\n if not FLAGS.dataset_dir:\n raise ValueError('You must supply the dataset directory with --dataset_dir')\n\n tf.logging.set_verbosity(tf.logging.INFO)\n with tf.Graph().as_default():\n #######################\n # Config model_deploy #\n #######################\n deploy_config = model_deploy.DeploymentConfig(\n num_clones=FLAGS.num_clones,\n clone_on_cpu=FLAGS.clone_on_cpu,\n replica_id=FLAGS.task,\n num_replicas=FLAGS.worker_replicas,\n num_ps_tasks=FLAGS.num_ps_tasks)\n\n # Create global_step\n with tf.device(deploy_config.variables_device()):\n global_step = slim.create_global_step()\n\n ######################\n # Select the dataset #\n ######################\n dataset = dataset_factory.get_dataset(\n FLAGS.dataset_name, FLAGS.dataset_split_name, FLAGS.dataset_dir)\n\n ######################\n # Select the network #\n ######################\n network_fn = nets_factory.get_network_fn(\n FLAGS.model_name,\n num_classes=(dataset.num_classes - FLAGS.labels_offset),\n weight_decay=FLAGS.weight_decay,\n is_training=True)\n\n #####################################\n # Select the preprocessing function #\n #####################################\n preprocessing_name = FLAGS.preprocessing_name or FLAGS.model_name\n image_preprocessing_fn = preprocessing_factory.get_preprocessing(\n preprocessing_name,\n is_training=True)\n\n ##############################################################\n # Create a dataset provider that loads data from the dataset #\n ##############################################################\n with tf.device(deploy_config.inputs_device()):\n provider = slim.dataset_data_provider.DatasetDataProvider(\n dataset,\n num_readers=FLAGS.num_readers,\n common_queue_capacity=20 * FLAGS.batch_size,\n common_queue_min=10 * FLAGS.batch_size)\n [image, label] = provider.get(['image', 'label'])\n label -= FLAGS.labels_offset\n\n train_image_size = FLAGS.train_image_size or network_fn.default_image_size\n\n image = image_preprocessing_fn(image, train_image_size, train_image_size)\n\n images, labels = tf.train.batch(\n [image, label],\n batch_size=FLAGS.batch_size,\n num_threads=FLAGS.num_preprocessing_threads,\n capacity=5 * FLAGS.batch_size)\n labels = slim.one_hot_encoding(\n labels, dataset.num_classes - FLAGS.labels_offset)\n batch_queue = slim.prefetch_queue.prefetch_queue(\n [images, labels], capacity=2 * deploy_config.num_clones)\n\n ####################\n # Define the model #\n ####################\n def clone_fn(batch_queue):\n \"\"\"Allows data parallelism by creating multiple clones of network_fn.\"\"\"\n images, labels = batch_queue.dequeue()\n logits, end_points = network_fn(images)\n\n #############################\n # Specify the loss function #\n #############################\n if 'AuxLogits' in end_points:\n slim.losses.softmax_cross_entropy(\n end_points['AuxLogits'], labels,\n label_smoothing=FLAGS.label_smoothing, weights=0.4,\n scope='aux_loss')\n slim.losses.softmax_cross_entropy(\n logits, labels, label_smoothing=FLAGS.label_smoothing, weights=1.0)\n return end_points\n\n # Gather initial summaries.\n summaries = set(tf.get_collection(tf.GraphKeys.SUMMARIES))\n\n clones = model_deploy.create_clones(deploy_config, clone_fn, [batch_queue])\n first_clone_scope = deploy_config.clone_scope(0)\n # Gather update_ops from the first clone. These contain, for example,\n # the updates for the batch_norm variables created by network_fn.\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS, first_clone_scope)\n\n # Add summaries for end_points.\n end_points = clones[0].outputs\n for end_point in end_points:\n x = end_points[end_point]\n summaries.add(tf.summary.histogram('activations/' + end_point, x))\n summaries.add(tf.summary.scalar('sparsity/' + end_point,\n tf.nn.zero_fraction(x)))\n\n # Add summaries for losses.\n for loss in tf.get_collection(tf.GraphKeys.LOSSES, first_clone_scope):\n summaries.add(tf.summary.scalar('losses/%s' % loss.op.name, loss))\n\n # Add summaries for variables.\n for variable in slim.get_model_variables():\n summaries.add(tf.summary.histogram(variable.op.name, variable))\n\n #################################\n # Configure the moving averages #\n #################################\n if FLAGS.moving_average_decay:\n moving_average_variables = slim.get_model_variables()\n variable_averages = tf.train.ExponentialMovingAverage(\n FLAGS.moving_average_decay, global_step)\n else:\n moving_average_variables, variable_averages = None, None\n\n if FLAGS.quantize_delay >= 0:\n tf.contrib.quantize.create_training_graph(\n quant_delay=FLAGS.quantize_delay)\n\n #########################################\n # Configure the optimization procedure. #\n #########################################\n with tf.device(deploy_config.optimizer_device()):\n learning_rate = _configure_learning_rate(dataset.num_samples, global_step)\n optimizer = _configure_optimizer(learning_rate)\n summaries.add(tf.summary.scalar('learning_rate', learning_rate))\n\n if FLAGS.sync_replicas:\n # If sync_replicas is enabled, the averaging will be done in the chief\n # queue runner.\n optimizer = tf.train.SyncReplicasOptimizer(\n opt=optimizer,\n replicas_to_aggregate=FLAGS.replicas_to_aggregate,\n total_num_replicas=FLAGS.worker_replicas,\n variable_averages=variable_averages,\n variables_to_average=moving_average_variables)\n elif FLAGS.moving_average_decay:\n # Update ops executed locally by trainer.\n update_ops.append(variable_averages.apply(moving_average_variables))\n\n # Variables to train.\n variables_to_train = _get_variables_to_train()\n\n # and returns a train_tensor and summary_op\n total_loss, clones_gradients = model_deploy.optimize_clones(\n clones,\n optimizer,\n var_list=variables_to_train)\n # Add total_loss to summary.\n summaries.add(tf.summary.scalar('total_loss', total_loss))\n\n # Create gradient updates.\n grad_updates = optimizer.apply_gradients(clones_gradients,\n global_step=global_step)\n update_ops.append(grad_updates)\n\n update_op = tf.group(*update_ops)\n with tf.control_dependencies([update_op]):\n train_tensor = tf.identity(total_loss, name='train_op')\n\n # Add the summaries from the first clone. These contain the summaries\n # created by model_fn and either optimize_clones() or _gather_clone_loss().\n summaries |= set(tf.get_collection(tf.GraphKeys.SUMMARIES,\n first_clone_scope))\n\n # Merge all summaries together.\n summary_op = tf.summary.merge(list(summaries), name='summary_op')\n\n ###########################\n # Kicks off the training. #\n ###########################\n slim.learning.train(\n train_tensor,\n logdir=FLAGS.train_dir,\n master=FLAGS.master,\n is_chief=(FLAGS.task == 0),\n init_fn=_get_init_fn(),\n summary_op=summary_op,\n number_of_steps=FLAGS.max_number_of_steps,\n log_every_n_steps=FLAGS.log_every_n_steps,\n save_summaries_secs=FLAGS.save_summaries_secs,\n save_interval_secs=FLAGS.save_interval_secs,\n sync_optimizer=optimizer if FLAGS.sync_replicas else None)\n\n\nif __name__ == '__main__':\n tf.app.run()\n"
] | [
[
"matplotlib.pyplot.imshow",
"tensorflow.FixedLenFeature",
"tensorflow.cast",
"tensorflow.TFRecordReader",
"tensorflow.train.batch",
"tensorflow.train.Int64List",
"tensorflow.decode_raw",
"tensorflow.python_io.TFRecordWriter",
"tensorflow.initialize_all_variables",
"numpy.asanyarray",
"tensorflow.Session",
"matplotlib.pyplot.axis",
"tensorflow.train.shuffle_batch",
"matplotlib.pyplot.title",
"tensorflow.train.Coordinator",
"tensorflow.global_variables_initializer",
"tensorflow.train.string_input_producer",
"tensorflow.one_hot",
"tensorflow.train.BytesList",
"tensorflow.train.FloatList",
"tensorflow.python_io.tf_record_iterator",
"matplotlib.pyplot.show",
"tensorflow.train.start_queue_runners",
"tensorflow.reshape"
],
[
"tensorflow.control_dependencies",
"tensorflow.train.ExponentialMovingAverage",
"tensorflow.app.flags.DEFINE_string",
"tensorflow.train.AdamOptimizer",
"tensorflow.app.flags.DEFINE_boolean",
"tensorflow.gfile.IsDirectory",
"tensorflow.group",
"tensorflow.train.batch",
"tensorflow.summary.scalar",
"tensorflow.Graph",
"tensorflow.get_collection",
"tensorflow.app.flags.DEFINE_integer",
"tensorflow.train.exponential_decay",
"tensorflow.train.MomentumOptimizer",
"tensorflow.logging.set_verbosity",
"tensorflow.trainable_variables",
"tensorflow.train.FtrlOptimizer",
"tensorflow.app.run",
"tensorflow.train.AdagradOptimizer",
"tensorflow.app.flags.DEFINE_bool",
"tensorflow.train.RMSPropOptimizer",
"tensorflow.identity",
"tensorflow.train.AdadeltaOptimizer",
"tensorflow.contrib.quantize.create_training_graph",
"tensorflow.train.GradientDescentOptimizer",
"tensorflow.logging.info",
"tensorflow.summary.histogram",
"tensorflow.train.polynomial_decay",
"tensorflow.train.latest_checkpoint",
"tensorflow.constant",
"tensorflow.nn.zero_fraction",
"tensorflow.train.SyncReplicasOptimizer",
"tensorflow.app.flags.DEFINE_float"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
CoAxLab/infomercial | [
"fa5d1c1e5c1351735dda2961a2a94f71cd17e270"
] | [
"infomercial/exp/softmeta_bandit.py"
] | [
"import os\nimport fire\nimport gym\n\nimport numpy as np\nfrom scipy.special import softmax\n\nfrom noboard.csv import SummaryWriter\n\nfrom copy import deepcopy\nfrom scipy.stats import entropy\nfrom collections import OrderedDict\n\nfrom infomercial.distance import kl\nfrom infomercial.memory import DiscreteDistribution\nfrom infomercial.models import Critic\nfrom infomercial.models import SoftmaxActor\n\nfrom infomercial.utils import estimate_regret\nfrom infomercial.utils import load_checkpoint\nfrom infomercial.utils import save_checkpoint\n\n\ndef R_update(state, reward, critic, lr):\n \"\"\"Really simple TD learning\"\"\"\n\n update = lr * (reward - critic(state))\n critic.update(state, update)\n\n return critic\n\n\ndef E_update(state, value, critic, lr):\n \"\"\"Bellman update\"\"\"\n update = lr * value\n critic.replace(state, update)\n\n return critic\n\n\ndef R_homeostasis(reward, total_reward, set_point):\n \"\"\"Update reward value assuming homeostatic value.\n \n Value based on Keramati and Gutkin, 2014.\n https://elifesciences.org/articles/04811\n \"\"\"\n deviance_last = np.abs(set_point - total_reward)\n deviance = np.abs(set_point - (total_reward + reward))\n reward_value = deviance_last - deviance\n return reward_value\n\n\ndef run(env_name='BanditOneHot10-v0',\n num_episodes=1000,\n temp=1.0,\n tie_threshold=0.0,\n tie_break=None,\n lr_R=.1,\n master_seed=42,\n write_to_disk=True,\n log_dir=None):\n \"\"\"Bandit agent - softmax (E, R)\"\"\"\n\n # --- Init ---\n writer = SummaryWriter(log_dir=log_dir, write_to_disk=write_to_disk)\n\n # -\n env = gym.make(env_name)\n env.seed(master_seed)\n num_actions = env.action_space.n\n all_actions = list(range(num_actions))\n best_action = env.best\n\n default_reward_value = 0\n default_info_value = entropy(np.ones(num_actions) / num_actions)\n E_t = default_info_value\n R_t = default_reward_value\n\n # --- Agents and memories ---\n critic_R = Critic(num_actions, default_value=default_reward_value)\n critic_E = Critic(num_actions, default_value=default_info_value)\n actor_R = SoftmaxActor(num_actions, temp=temp, seed_value=master_seed)\n actor_E = SoftmaxActor(num_actions, temp=temp, seed_value=master_seed)\n memories = [DiscreteDistribution() for _ in range(num_actions)]\n\n # -\n num_best = 0\n total_R = 0.0\n total_E = 0.0\n total_regret = 0.0\n\n # ------------------------------------------------------------------------\n for n in range(num_episodes):\n env.reset()\n\n # Meta-greed policy selection\n if (E_t - tie_threshold) > R_t:\n critic = critic_E\n actor = actor_E\n policy = 0\n else:\n critic = critic_R\n actor = actor_R\n policy = 1\n\n # Choose an action; Choose a bandit\n action = actor(list(critic.model.values()))\n if action in best_action:\n num_best += 1\n\n # Est. regret and save it\n regret = estimate_regret(all_actions, action, critic)\n\n # Pull a lever.\n state, R_t, _, _ = env.step(action)\n R_t = R_homeostasis(R_t, total_R, num_episodes)\n\n # Estimate E\n old = deepcopy(memories[action])\n memories[action].update((int(state), int(R_t)))\n new = deepcopy(memories[action])\n E_t = kl(new, old, default_info_value)\n\n # Learning, both policies.\n critic_R = R_update(action, R_t, critic_R, lr_R)\n critic_E = E_update(action, E_t, critic_E, lr=1)\n\n # Log data\n writer.add_scalar(\"policy\", policy, n)\n writer.add_scalar(\"state\", int(state), n)\n writer.add_scalar(\"action\", action, n)\n writer.add_scalar(\"regret\", regret, n)\n writer.add_scalar(\"score_E\", E_t, n)\n writer.add_scalar(\"score_R\", R_t, n)\n writer.add_scalar(\"value_E\", critic_E(action), n)\n writer.add_scalar(\"value_R\", critic_R(action), n)\n\n total_E += E_t\n total_R += R_t\n total_regret += regret\n writer.add_scalar(\"total_regret\", total_regret, n)\n writer.add_scalar(\"total_E\", total_E, n)\n writer.add_scalar(\"total_R\", total_R, n)\n writer.add_scalar(\"p_bests\", num_best / (n + 1), n)\n\n # -- Build the final result, and save or return it ---\n writer.close()\n\n result = dict(best=env.best,\n num_episodes=num_episodes,\n temp=temp,\n tie_threshold=tie_threshold,\n critic_E=critic_E.state_dict(),\n critic_R=critic_R.state_dict(),\n total_E=total_E,\n total_R=total_R,\n total_regret=total_regret,\n env_name=env_name,\n lr_R=lr_R,\n master_seed=master_seed)\n\n if write_to_disk:\n save_checkpoint(result,\n filename=os.path.join(writer.log_dir, \"result.pkl\"))\n\n return result\n\n\nif __name__ == \"__main__\":\n fire.Fire(run)"
] | [
[
"numpy.abs",
"numpy.ones"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
dnicholson/gasex-python | [
"53b8c3ff4e64e724d8883bdef299d465621b124f"
] | [
"gasex/diff.py"
] | [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n% Diffusion coeff and Schmidt number for gases in fresh/sea water\n%=========================================================================\n% Modified by D. Nicholson from MATLAB gas_diffusion Version 2.0 16 July 2013\n% Author: Roberta C. Hamme (University of Victoria)\n% Diffusion values for 'He','Ne','Ar','Kr','Xe','N2','O2','CH4','N2' and 'CO2' are calculated from\n% gas_diffusion Version 2.0 functions \n% salinity correction is of the form: D = D0 * (1 - 0.049 * SP / 35.5)\n% \n%\n% Support for additional gases ('CO2','N2O','CH4','RN','SF6','DMS','CFC12','CFC11','CH3BR','CCL4')\n% has been added based on Wanninkhof 2014 \n%\n% Table 1:\n% Sc = A + Bt + Ct2+ dt3+ Et4(t in °C). The last column is the calculated Schmidt number for 20°C. \n% The Schmidt number is the kinematic viscosity of waterdivided by the molecular diffusion \n% coefficient of the gas. The kinematic viscosity for fresh water and seawater are from \n% Sharqawy et al. (2010). The dif-fusion coefficients of gases are from the following: \n% 3He, He, Ne, Kr, Xe, CH4, CO2, and Rn measured by Jähne et al. (1987); Ar, O2, N2, N2O, \n% and CCl4fitusing Wilke and Chang (1955) as adapted by Hayduk and Laudie (1974); SF6 \n% measured by King and Saltzman (1995); DMS measured by Saltzman etal. (1993); CFC-11 and \n% CFC-12 measured by Zheng et al. (1998); CH3Br measured by De Bruyn and Saltzman (1997a).\n%\n%\n% REFERENCE:\n% He, Ne, Kr, Xe, CH4, CO2, H2 freshwater values from Jahne et al., 1987.\n% \"Measurement of Diffusion Coeffients of Sparingly Soluble Gases in Water\"\n% J. Geophys. Res., 92(C10), 10767-10776.\n% Ar freshwaters values are extrapolated from Jahne et al. 1987\n% He, Ne, Kr, Xe values at each temperature were fitted to D vs. mass^-0.5\n% relationship to predict Ar at those temperatures, then Ar was fit to a\n% ln(D_Ar) vs. 1/T(K) relationship to obtain Eyring equation coefficients\n% O2 and N2 freshwater values from Ferrell and Himmelblau, 1967.\n% \"Diffusion coefficients of nitrogen and oxygen in water\"\n% J. Chem. Eng. Data, 12(1), 111-115, doi: 10.1021/je60032a036.\n% Correction for salinity is based on Jahne's observed average 4.9% decrease in\n% diffusivity for H2 and He in 35.5 ppt NaCl solution\n%\n% for Ne, the Jahne values compare well with and fall between those of\n% Wise and Houghton 1968 and Holz et al. 1994\n% for Ar, the extrapolated Jahne values compare well with Wise and Houghton 1968,\n% O'Brien and Hyslop 1977, and a numerical simulation by Bourg et al. 2008\n% but are higher than other reported values\n% for Kr, the Jahne values compare well with Wise and Houghton 1968,\n% and a numerical simulation by Bourg et al. 2008\n% for Xe, the Jahne values compare well with Pollack 1981, and a numerical\n% simulation by Bourg et al. 2008, but fall significantly above Wise and Houghton 1968\n% and below Weingartner et al. 1992\n% for O2, there is general agreement among measurements. The Ferrel and Himmelblau values\n% agree reasonably well with Baird and Davidson 1962, Wise and Houghton 1966,\n% Duda and Vrentas 1968, O'Brien and Hyslop 1977, and the Wilke and Change (1955) theory\n% as tabulated by Wanninkhof 1992, but lie below Krieger et al 1967\n% for N2, there is less agreement. The Ferrel and Himmelblau values\n% agree reasonably well with Baird and Davidson 1962, O'Brien and Hyslop 1977,\n% and the Wilke and Change (1955) theory as tabulated by Wanninkhof 1992,\n% but lie significantly below the values of Wise and Houghton 1966 and Krieger et al 1967\n% for He, I did not investigate comparisons of data, but chose Jahne\n% since their work for other gases appears to be the best\n% for CO2, CH4 and H2: Jahne 1987 \n%\n% \n%\n% DISCLAIMER:\n% This software is provided \"as is\" without warranty of any kind.\n%=========================================================================\n\"\"\"\nfrom __future__ import division\nimport numpy as np\nfrom numpy.polynomial.polynomial import polyval\nfrom ._utilities import match_args_return\nfrom gasex.phys import R as R \nfrom gasex.phys import visc as visc\n\n\n# Currently supported gases\n# TODO: find N2O, CO diffusivities\nGAS_LIST = ('HE','NE','AR','KR','XE','N2','O2','CH4','N2','CO2')\n\n@match_args_return\ndef diff(SP,pt,*,gas=None):\n \n \"\"\"\n DESCRIPTION\n -----------\n Diffusion coefficients of various gases in fresh/sea water\n \n PARAMETERS\n -----------\n SP = practical salinity [PSS-78]\n pt = potential temperature [degree C]\n gas = 'He','Ne','Ar','Kr','Xe','N2','O2','CH4','N2' or 'CO2'\n \n OUTPUT:\n D = diffusion coefficient [m^2 s-1]\n\n \"\"\"\n g_up = gas.upper()\n if g_up not in GAS_LIST:\n raise ValueError(\"gas: must be one of \", GAS_LIST)\n \n AEa_dict = {'O2': (4.286e-6, 18700),\\\n 'HE': (0.8180e-6, 11700),\\\n 'NE': (1.6080e-6, 14840),\\\n 'AR': (2.227e-6, 16680),\\\n 'KR': (6.3930e-6, 20200),\\\n 'XE': (9.0070e-6, 21610),\\\n 'N2': (3.4120e-6, 18500),\\\n 'CH4':(3.0470e-6, 18360),\\\n 'CO2':(5.0190e-6, 19510),\\\n 'H2': (3.3380e-6, 16060)}\n \n if g_up in AEa_dict.keys():\n #freshwater diffusivity\n AEa = AEa_dict[g_up]\n D0 = AEa[0] * np.exp(-AEa[1] / (R * (pt+273.15)))\n #salinity correction\n D = D0 * (1 - 0.049 * SP / 35.5)\n else:\n raise ValueError(\"gas: must be one of \", AEa_dict.keys())\n return D\n\n\n@match_args_return\ndef schmidt(SP,pt,*,gas=None):\n\n g_up = gas.upper()\n if g_up not in GAS_LIST:\n raise ValueError(\"gas\", g_up, \" does not match one of \", GAS_LIST)\n \n Sc = visc(SP,pt) / diff(SP,pt,gas=gas) \n return Sc\n\n@match_args_return\ndef schmidt_W14(pt,*,gas=None,sw=True):\n \"\"\"Schmidt number @ 35 psu based on Wanninkhof 2014 Table 1\n\n Args:\n pt ([array like]): potential temperature [degree C]\n gas ([string]): abbreviation for gas. Defaults to None.\n sw (bool, optional): if True, then calculates for SP = 35, of false, \n calculates for fresh water. Defaults to True.\n\n Raises:\n ValueError: [description]\n\n Returns:\n [type]: Schmidt number [dimensionless]\n \"\"\"\n W14_LIST = ('CO2','N2O','CH4','RN','SF6','DMS','CFC12','CFC11','CH3BR','CCL4')\n g_up = gas.upper()\n if sw:\n A_dict = {'CO2': (2116.8,-136.25,4.7353,-0.092307,0.0007555 ),\\\n 'N2O': (2356.2,-166.38,6.3952,-0.13422,0.0011506 ),\\\n 'CH4':(2101.2,-131.54,4.4931,-0.08676,0.00070663),\n 'RN': (3489.6,-244.56,8.9713,-0.18022,0.0014985 ),\n 'SF6':(3177.5,-200.57,6.8865,-0.13335,0.0010877 ),\n 'DMS':(2855.7,-177.63,6.0438,-0.11645,0.00094743),\n 'CFC12':(3828.1,-249.86, 8.7603, -0.1716, 0.001408 ),\n 'CFC11':(3579.2, -222.63, 7.5749, -0.14595, 0.0011874 ),\n 'CH3BR':(2181.8, -138.4, 4.7663, -0.092448, 0.0007547 ),\n 'CCL4': (4398.7, -308.25, 11.798, -0.24709, 0.0021159) }\n else:\n A_dict = {'CO2': (1923.6, -125.06, 4.3773, -0.085681, 0.00070284 ),\\\n 'N2O': (2141.2, -152.56, 5.8963, -0.12411, 0.0010655 ),\\\n 'CH4':(1909.4, -120.78, 4.1555, -0.080578, 0.00065777),\n 'RN': (3171, -224.28, 8.2809, -0.16699, 0.0013915 ),\n 'SF6':(3035, -196.35, 6.851, -0.13387, 0.0010972 ),\n 'DMS':(2595, -163.12, 5.5902, -0.10817, 0.00088204),\n 'CFC12':(3478.6, -229.32, 8.0961, -0.15923, 0.0013095 ),\n 'CFC11':(3460, -217.49, 7.4537, -0.14423, 0.0011761 ),\n 'CH3BR':(2109.2, -135.17, 4.6884, -0.091317, 0.00074715 ),\n 'CCL4': (3997.2, -282.69, 10.88, -0.22855, 0.0019605) }\n\n if g_up in A_dict.keys():\n A = A_dict[g_up]\n else:\n raise ValueError(\"gas\", g_up, \" does not match one of \", A_dict.keys())\n\n Sc = polyval(pt,A)\n return Sc\n"
] | [
[
"numpy.polynomial.polynomial.polyval",
"numpy.exp"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
alixhami/training-data-analyst | [
"3eb60cb6c8b55fd7f38414c1082da36b8e62558e"
] | [
"courses/machine_learning/deepdive/05_artandscience/simplernn/trainer/model.py"
] | [
"#!/usr/bin/env python3\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\nimport tensorflow as tf\nimport tensorflow.contrib.metrics as metrics\nimport tensorflow.contrib.rnn as rnn\n\ntf.logging.set_verbosity(tf.logging.INFO)\n\nSEQ_LEN = 10\nDEFAULTS = [[0.0] for x in range(0, SEQ_LEN)]\nBATCH_SIZE = 20\nTIMESERIES_INPUT_LAYER = 'rawdata'\nTIMESERIES_COL = '{}_input'.format(TIMESERIES_INPUT_LAYER)\n# In each sequence, column index 0 to N_INPUTS - 1 are features, and column index N_INPUTS to SEQ_LEN are labels\nN_OUTPUTS = 1\nN_INPUTS = SEQ_LEN - N_OUTPUTS\nLSTM_SIZE = 3 # number of hidden layers in each of the LSTM cells\n\n# Read data and convert to needed format\ndef read_dataset(filename, mode, batch_size):\n def _input_fn():\n # Provide the ability to decode a CSV\n def decode_csv(line):\n # all_data is a list of scalar tensors\n all_data = tf.decode_csv(line, record_defaults = DEFAULTS)\n inputs = all_data[:len(all_data) - N_OUTPUTS] # first N_INPUTS values\n labels = all_data[len(all_data) - N_OUTPUTS:] # last N_OUTPUTS values\n\n # Convert each list of rank R tensors to one rank R+1 tensor\n inputs = tf.stack(inputs, axis = 0)\n labels = tf.stack(labels, axis = 0)\n\n # Convert input R+1 tensor into a feature dictionary of one R+1 tensor\n features = {TIMESERIES_COL: inputs}\n\n return features, labels\n\n # Create list of files that match pattern\n file_list = tf.gfile.Glob(filename)\n\n # Create dataset from file list\n dataset = tf.data.TextLineDataset(file_list).map(decode_csv)\n\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 dataset = dataset.repeat(num_epochs).batch(batch_size)\n\n iterator = dataset.make_one_shot_iterator()\n batch_features, batch_labels = iterator.get_next()\n return batch_features, batch_labels\n return _input_fn\n\n# Create inference model using Keras\n# The model here is a dnn regressor\ndef make_keras_estimator(output_dir):\n from tensorflow import keras\n model = keras.models.Sequential()\n model.add(keras.layers.Dense(32, input_shape=(N_INPUTS,), name=TIMESERIES_INPUT_LAYER))\n model.add(keras.layers.Activation('relu'))\n model.add(keras.layers.Dense(1))\n model.compile(loss = 'mean_squared_error',\n optimizer = 'adam', \n metrics = ['mae', 'mape']) # mean absolute [percentage] error\n return keras.estimator.model_to_estimator(model, model_dir=output_dir)\n\n# Create the inference model\ndef simple_rnn(features, labels, mode):\n # 0. Reformat input shape to become a sequence\n x = tf.split(features[TIMESERIES_COL], N_INPUTS, 1)\n\n # 1. Configure the RNN\n lstm_cell = rnn.BasicLSTMCell(LSTM_SIZE, forget_bias = 1.0)\n outputs, _ = rnn.static_rnn(lstm_cell, x, dtype = tf.float32)\n\n # Slice to keep only the last cell of the RNN\n outputs = outputs[-1]\n #print('last outputs={}'.format(outputs))\n\n # Output is result of linear activation of last layer of RNN\n weight = tf.Variable(tf.random_normal([LSTM_SIZE, N_OUTPUTS]))\n bias = tf.Variable(tf.random_normal([N_OUTPUTS]))\n predictions = tf.matmul(outputs, weight) + bias\n \n # 2. Loss function, training/eval ops\n if mode == tf.estimator.ModeKeys.TRAIN or mode == tf.estimator.ModeKeys.EVAL:\n loss = tf.losses.mean_squared_error(labels, predictions)\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 = \"SGD\")\n eval_metric_ops = {\n \"rmse\": tf.metrics.root_mean_squared_error(labels, predictions)\n }\n else:\n loss = None\n train_op = None\n eval_metric_ops = None\n \n # 3. Create predictions\n predictions_dict = {\"predicted\": predictions}\n \n # 4. Create export outputs\n export_outputs = {\"predict_export_outputs\": tf.estimator.export.PredictOutput(outputs = predictions)}\n\n # 4. Return EstimatorSpec\n return tf.estimator.EstimatorSpec(\n 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# Create serving input function\ndef serving_input_fn():\n feature_placeholders = {\n TIMESERIES_COL: tf.placeholder(tf.float32, [None, N_INPUTS])\n }\n\n features = {\n key: tf.expand_dims(tensor, -1)\n for key, tensor in feature_placeholders.items()\n }\n features[TIMESERIES_COL] = tf.squeeze(features[TIMESERIES_COL], axis = [2])\n\n return tf.estimator.export.ServingInputReceiver(features, feature_placeholders)\n\n# Create custom estimator's train and evaluate function\ndef train_and_evaluate(output_dir, use_keras):\n if use_keras:\n estimator = make_keras_estimator(output_dir)\n else:\n estimator = tf.estimator.Estimator(model_fn = simple_rnn, \n model_dir = output_dir)\n train_spec = tf.estimator.TrainSpec(read_dataset('train.csv',\n tf.estimator.ModeKeys.TRAIN,\n 512),\n max_steps = 1000)\n exporter = tf.estimator.LatestExporter('exporter', serving_input_fn)\n eval_spec = tf.estimator.EvalSpec(read_dataset('valid.csv',\n tf.estimator.ModeKeys.EVAL,\n 512),\n steps = None, \n exporters = exporter)\n tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec)\n"
] | [
[
"tensorflow.stack",
"tensorflow.data.TextLineDataset",
"tensorflow.keras.estimator.model_to_estimator",
"tensorflow.estimator.train_and_evaluate",
"tensorflow.decode_csv",
"tensorflow.estimator.export.PredictOutput",
"tensorflow.squeeze",
"tensorflow.train.get_global_step",
"tensorflow.logging.set_verbosity",
"tensorflow.estimator.export.ServingInputReceiver",
"tensorflow.keras.models.Sequential",
"tensorflow.estimator.LatestExporter",
"tensorflow.matmul",
"tensorflow.estimator.Estimator",
"tensorflow.keras.layers.Dense",
"tensorflow.metrics.root_mean_squared_error",
"tensorflow.placeholder",
"tensorflow.gfile.Glob",
"tensorflow.contrib.rnn.static_rnn",
"tensorflow.split",
"tensorflow.losses.mean_squared_error",
"tensorflow.keras.layers.Activation",
"tensorflow.contrib.rnn.BasicLSTMCell",
"tensorflow.expand_dims",
"tensorflow.estimator.EstimatorSpec",
"tensorflow.random_normal"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.13",
"1.5",
"1.7",
"0.12",
"1.0",
"1.2"
]
}
] |
NiccoloSacchi/rlcard | [
"046129e8616b12e25652957869a94ab5fd838ae1"
] | [
"rlcard/games/leducholdem/game.py"
] | [
"import numpy as np\nfrom copy import copy\n\nfrom rlcard.games.leducholdem.dealer import LeducholdemDealer as Dealer\nfrom rlcard.games.leducholdem.player import LeducholdemPlayer as Player\nfrom rlcard.games.leducholdem.judger import LeducholdemJudger as Judger\nfrom rlcard.games.leducholdem.round import LeducholdemRound as Round\n\nfrom rlcard.games.limitholdem.game import LimitholdemGame\n\nclass LeducholdemGame(LimitholdemGame):\n\n def __init__(self, allow_step_back=False):\n ''' Initialize the class leducholdem Game\n '''\n self.allow_step_back = allow_step_back\n ''' No big/small blind\n # Some configarations of the game\n # These arguments are fixed in Leduc Hold'em Game\n\n # Raise amount and allowed times\n self.raise_amount = 2\n self.allowed_raise_num = 2\n\n self.num_players = 2\n '''\n # Some configarations of the game\n # These arguments can be specified for creating new games\n\n # Small blind and big blind\n self.small_blind = 1\n self.big_blind = 2 * self.small_blind\n\n # Raise amount and allowed times\n self.raise_amount = self.big_blind\n self.allowed_raise_num = 2\n\n self.num_players = 2\n\n def init_game(self):\n ''' Initialilze the game of Limit Texas Hold'em\n\n This version supports two-player limit texas hold'em\n\n Returns:\n (tuple): Tuple containing:\n\n (dict): The first state of the game\n (int): Current player's id\n '''\n # Initilize a dealer that can deal cards\n self.dealer = Dealer()\n\n # Initilize two players to play the game\n self.players = [Player(i) for i in range(self.num_players)]\n\n # Initialize a judger class which will decide who wins in the end\n self.judger = Judger()\n\n # Prepare for the first round\n for i in range(self.num_players):\n self.players[i].hand = self.dealer.deal_card()\n # Randomly choose a small blind and a big blind\n s = np.random.randint(0, self.num_players)\n b = (s + 1) % self.num_players\n self.players[b].in_chips = self.big_blind\n self.players[s].in_chips = self.small_blind\n self.public_card = None\n # The player with small blind plays the first\n self.game_pointer = s\n\n # Initilize a bidding round, in the first round, the big blind and the small blind needs to\n # be passed to the round for processing.\n self.round = Round(raise_amount=self.raise_amount,\n allowed_raise_num=self.allowed_raise_num,\n num_players=self.num_players)\n\n self.round.start_new_round(game_pointer=self.game_pointer, raised=[p.in_chips for p in self.players])\n\n # Count the round. There are 2 rounds in each game.\n self.round_counter = 0\n\n # Save the hisory for stepping back to the last state.\n self.history = []\n\n state = self.get_state(self.game_pointer)\n\n return state, self.game_pointer\n\n def step(self, action):\n ''' Get the next state\n\n Args:\n action (str): a specific action. (call, raise, fold, or check)\n\n Returns:\n (tuple): Tuple containing:\n\n (dict): next player's state\n (int): next plater's id\n '''\n if self.allow_step_back:\n # First snapshot the current state\n r = copy(self.round)\n r_raised = copy(self.round.raised)\n gp = self.game_pointer\n r_c = self.round_counter\n d_deck = copy(self.dealer.deck)\n p = copy(self.public_card)\n ps = [copy(self.players[i]) for i in range(self.num_players)]\n ps_hand = [copy(self.players[i].hand) for i in range(self.num_players)]\n self.history.append((r, r_raised, gp, r_c, d_deck, p, ps, ps_hand))\n\n # Then we proceed to the next round\n self.game_pointer = self.round.proceed_round(self.players, action)\n\n # If a round is over, we deal more public cards\n if self.round.is_over():\n # For the first round, we deal 1 card as public card. Double the raise amount for the second round\n if self.round_counter == 0:\n self.public_card = self.dealer.deal_card()\n self.round.raise_amount = 2 * self.raise_amount\n\n self.round_counter += 1\n self.round.start_new_round(self.game_pointer)\n\n state = self.get_state(self.game_pointer)\n\n return state, self.game_pointer\n\n def get_state(self, player):\n ''' Return player's state\n\n Args:\n player_id (int): player id\n\n Returns:\n (dict): The state of the player\n '''\n chips = [self.players[i].in_chips for i in range(self.num_players)]\n legal_actions = self.get_legal_actions()\n state = self.players[player].get_state(self.public_card, chips, legal_actions)\n state['current_player'] = self.game_pointer\n\n return state\n\n def is_over(self):\n ''' Check if the game is over\n\n Returns:\n (boolean): True if the game is over\n '''\n alive_players = [1 if p.status=='alive' else 0 for p in self.players]\n # If only one player is alive, the game is over.\n if sum(alive_players) == 1:\n return True\n\n # If all rounds are finshed\n if self.round_counter >= 2:\n return True\n return False\n\n def get_payoffs(self):\n ''' Return the payoffs of the game\n\n Returns:\n (list): Each entry corresponds to the payoff of one player\n '''\n chips_payoffs = self.judger.judge_game(self.players, self.public_card)\n payoffs = np.array(chips_payoffs) / (self.big_blind)\n return payoffs\n\n def step_back(self):\n ''' Return to the previous state of the game\n\n Returns:\n (bool): True if the game steps back successfully\n '''\n if len(self.history) > 0:\n self.round, r_raised, self.game_pointer, self.round_counter, d_deck, self.public_card, self.players, ps_hand = self.history.pop()\n self.round.raised = r_raised\n self.dealer.deck = d_deck\n for i, hand in enumerate(ps_hand):\n self.players[i].hand = hand\n return True\n return False\n\n\n# Test the game\n\n#if __name__ == \"__main__\":\n# game = LeducholdemGame(allow_step_back=True)\n# while True:\n# print('New Game')\n# state, game_pointer = game.init_game()\n# print(game_pointer, state)\n# i = 1\n# while not game.is_over():\n# i += 1\n# legal_actions = game.get_legal_actions()\n# if i == 4:\n# print('Step back')\n# print(game.step_back())\n# game_pointer = game.get_player_id()\n# print(game_pointer)\n# state = game.get_state(game_pointer)\n# legal_actions = game.get_legal_actions()\n# # action = input()\n# action = np.random.choice(legal_actions)\n# print(game_pointer, action, legal_actions, state)\n# state, game_pointer = game.step(action)\n# print(game_pointer, state)\n#\n# print(game.get_payoffs())\n"
] | [
[
"numpy.array",
"numpy.random.randint"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
DanielHuji-RB/RB-article | [
"e5a9ba30edfb030db1cd3bcf562c6abff3f9d48e",
"e5a9ba30edfb030db1cd3bcf562c6abff3f9d48e"
] | [
"Python/Functions_base/Functions/replace_ElecNaming.py",
"Python/Functions_base/Functions/DL_functions.py"
] | [
"#Daniel Sand\n\nimport pandas as pd\nimport numpy as np\n\n\nfileName='/Tscores.csv'\n\nnewFileName='/Tscores_v3.csv'\ndf=pd.read_csv(fileName, sep=',')\n\n#6 differnt electordes\noldFormat=['0-1','0-2','0-3','2-Jan','3-Jan','3-Feb']\nnewFormat=['0_1','0_2','0_3','2_1','3_1','3_2']\n\nfor iCont in range(0, len(oldFormat)):\n currElec_old = oldFormat[iCont]\n currElec_new = newFormat[iCont]\n df.loc[df.Elec==currElec_old,'Elec']=currElec_new\ndf.to_csv(path_or_buf=newFileName)\n",
"#daniel sand\n\n\nimport numpy as np\nimport pandas as pd\nimport os\n# import matlab.engine\n# Feature Extraction with Univariate Statistical Tests (Chi-squared for classification)\nfrom Functions import arrangeData as AD\nfrom Functions import FeaturesSelection_script as FSS\nfrom sklearn.model_selection import StratifiedKFold\nfrom keras.models import Model\nfrom keras.layers import Input, Dense, Dropout\nfrom keras.callbacks import EarlyStopping\nfrom keras.utils.vis_utils import plot_model\nfrom keras.callbacks import ModelCheckpoint\n\nfrom Functions import arrangeData as AD\nfrom Functions import mrmr as M\n\n\ndef DL_v1(x_train,y_train,df_xTrain, x_val,y_val, x_test,y_test, feature_scope, df_results_new, line, name, iter):\n strName_forWeigths = (', '.join(str(x) for x in [name]))\n\n #inltizion\n x_train_orginal = x_train.copy()\n y_train_orginal= y_train.copy()\n x_val_orginal = x_val.copy()\n y_val_orginal = y_val.copy()\n x_test_orginal = x_test.copy()\n y_test_orginal = y_test.copy()\n modelCounter=0\n # eng = matlab.engine.start_matlab()\n valAcc=0\n\n for iFeature in range(0, len(feature_scope)):\n #Feature Selection\n featureNum = feature_scope[iFeature]\n FSmodel = M.mRMR(nFeats=featureNum)\n modelFit = FSmodel.fit(x_train_orginal, y_train_orginal)\n x_train=modelFit._transform(x_train_orginal)\n x_val = modelFit._transform(x_val_orginal)\n x_test = modelFit._transform(x_test_orginal)\n\n\n #not sure this is important\n y_train= y_train_orginal.copy()\n y_val = y_val_orginal.copy()\n y_test = y_test_orginal.copy()\n\n '#_model paramters'\n\n loss_scope=['mean_squared_error','hinge','categorical_crossentropy']\n activation_scope=['tanh','relu','sigmoid']\n\n for iLoss in range(0,len(loss_scope)):\n lossName=loss_scope[iLoss]\n for iActivation in range(0,len(activation_scope)):\n activationName=activation_scope[iActivation]\n # optimzer_scope=[ 'Adam', 'Adamax','SGD','Adagrad' ,'Adadelta','RMSprop' ,'Nadam']# all optimzers beside 'TFOptimizer',\n optimzer_scope=[ 'Adam','Adamax','SGD']# all optimzers beside 'TFOptimizer',\n for iOptimzer in range(0, len(optimzer_scope)):\n optimzerName=optimzer_scope[iOptimzer]\n dropoutV_scope=[0.2,0.4,0.6,0.8]\n for iDropOut in range (0, len(dropoutV_scope)):\n dropoutV=dropoutV_scope[iDropOut]\n\n batch_size_n_scope = [32]\n for iBatch in range(0, len(batch_size_n_scope)):\n batch_size_n = batch_size_n_scope[iBatch]\n modelCounter=modelCounter+1\n\n epochs=500\n '''Train model:'''\n N_nodes=50\n # first sub_nn\n input_data_1 = Input(shape=(featureNum,))\n x1 = Dense(N_nodes, activation=activationName)(input_data_1) # relu sigmoid\n for iInputData in range(0, 4):\n x1 = Dropout(dropoutV)(x1)\n x1 = Dense(50, activation=activationName)(x1)\n x1 = Dropout(dropoutV)(x1)\n top_nn_output = Dense(15, activation=activationName)(x1)\n output_layer = Dense(1)(top_nn_output)\n\n model = Model(input=[input_data_1], outputs=[output_layer])\n model.compile(optimizer=optimzerName, loss=lossName, metrics=['accuracy'])# loss='binary_crossentropy'\n\n\n # checkpoint\n filepath = \"weights.best\"+strName_forWeigths+str(iter)+\".hdf5\"\n checkpoint = ModelCheckpoint(filepath, monitor='val_acc', verbose=1, save_best_only=True, mode='max')\n # early stop\n earlystop = EarlyStopping(monitor='val_acc', min_delta=0.001, patience=100, verbose=1, mode='auto')\n callbacks_list = [earlystop,checkpoint]\n history = model.fit([x_train],[y_train.ravel()], epochs=epochs, batch_size=batch_size_n ,callbacks=callbacks_list, validation_data=([x_val], [y_val.ravel()]))#need to drop off the second label\n valScore_temp, valAcc_temp = model.evaluate([x_val], [y_val.ravel()], batch_size=batch_size_n).copy()\n\n if np.array(model.history.history['val_acc']).argmax() >20:\n model.load_weights(filepath)\n\n valScore_temp, valAcc_temp = model.evaluate([x_val], [y_val.ravel()], batch_size=batch_size_n).copy()\n trainScore_temp, trainAcc_temp = model.evaluate([x_train], [y_train.ravel()], batch_size=batch_size_n).copy()\n\n if (valAcc_temp > valAcc) and (trainAcc_temp>0.6):\n\n modelH_Params = type('', (), {})()\n\n valAcc = valAcc_temp\n modelH_Params.Val_score=valScore_temp.copy()\n modelH_Params.Val_accuracy=valAcc_temp.copy()\n\n modelH_Params.Train_score, modelH_Params.Train_accuracy = model.evaluate([x_train], [y_train.ravel()],batch_size=batch_size_n).copy()\n modelH_Params.Test_score, modelH_Params.Test_accuracy = model.evaluate([x_test], [y_test.ravel()],batch_size=batch_size_n).copy()\n print('Test_acc :' + str(modelH_Params.Test_accuracy))\n\n\n #hyperParams\n modelH_Params.Model=model\n modelH_Params.Modelhistory=history\n modelH_Params.Modelname='Complex_NN_Model'\n modelH_Params.featureSelection_N= featureNum\n modelH_Params.optimzerName = optimzerName\n modelH_Params.epochs = epochs\n modelH_Params.Reg = 'nan'#reg\n modelH_Params.batch_size_n = batch_size_n\n modelH_Params.activationName = activationName\n modelH_Params.lossfunction=lossName\n modelH_Params.dropoutV=dropoutV\n\n\n line, df_results_new = AD.add2Excel_v2_DL(modelH_Params, line, df_results_new, name, str(iter))\n\n return modelH_Params,df_results_new,line"
] | [
[
"pandas.read_csv"
],
[
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ThinkBigAnalytics/ludwig | [
"0a3159af4cc91f57251f3dec0cdb863c7003cf00"
] | [
"ludwig/features/image_feature.py"
] | [
"#! /usr/bin/env python\n# coding=utf-8\n# Copyright (c) 2019 Uber Technologies, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\nimport logging\nimport os\n\nimport h5py\nimport numpy as np\nimport tensorflow as tf\nfrom skimage.io import imread\n\nfrom ludwig.constants import *\nfrom ludwig.features.base_feature import BaseFeature\nfrom ludwig.features.base_feature import InputFeature\nfrom ludwig.models.modules.image_encoders import ResNetEncoder\nfrom ludwig.models.modules.image_encoders import Stacked2DCNN\nfrom ludwig.utils.image_utils import resize_image\nfrom ludwig.utils.misc import get_from_registry\nfrom ludwig.utils.misc import set_default_value\n\n\nclass ImageBaseFeature(BaseFeature):\n def __init__(self, feature):\n super().__init__(feature)\n self.type = IMAGE\n\n preprocessing_defaults = {\n 'missing_value_strategy': BACKFILL,\n 'in_memory': True,\n 'resize_method': 'crop_or_pad'\n }\n\n @staticmethod\n def get_feature_meta(column, preprocessing_parameters):\n return {\n 'preprocessing': preprocessing_parameters\n }\n\n @staticmethod\n def add_feature_data(\n feature,\n dataset_df,\n data,\n metadata,\n preprocessing_parameters\n ):\n set_default_value(\n feature,\n 'in_memory',\n preprocessing_parameters['in_memory']\n )\n\n if ('height' in preprocessing_parameters or\n 'width' in preprocessing_parameters):\n should_resize = True\n try:\n provided_height = int(preprocessing_parameters[HEIGHT])\n provided_width = int(preprocessing_parameters[WIDTH])\n except ValueError as e:\n raise ValueError(\n 'Image height and width must be set and have '\n 'positive integer values: ' + str(e)\n )\n if (provided_height <= 0 or provided_width <= 0):\n raise ValueError(\n 'Image height and width must be positive integers'\n )\n else:\n should_resize = False\n\n csv_path = os.path.dirname(os.path.abspath(dataset_df.csv))\n\n num_images = len(dataset_df)\n\n height = 0\n width = 0\n num_channels = 1\n\n if num_images > 0:\n # here if a width and height have not been specified\n # we assume that all images have the same wifth and im_height\n # thus the width and height of the first one are the same\n # of all the other ones\n first_image = imread(\n os.path.join(csv_path, dataset_df[feature['name']][0])\n )\n height = first_image.shape[0]\n width = first_image.shape[1]\n\n if first_image.ndim == 2:\n num_channels = 1\n else:\n num_channels = first_image.shape[2]\n\n if should_resize:\n height = provided_height\n width = provided_width\n\n metadata[feature['name']]['preprocessing']['height'] = height\n metadata[feature['name']]['preprocessing']['width'] = width\n metadata[feature['name']]['preprocessing'][\n 'num_channels'] = num_channels\n\n if feature['in_memory']:\n data[feature['name']] = np.empty(\n (num_images, height, width, num_channels),\n dtype=np.int8\n )\n for i in range(len(dataset_df)):\n filename = os.path.join(\n csv_path,\n dataset_df[feature['name']][i]\n )\n img = imread(filename)\n if img.ndim == 2:\n img = img.reshape((img.shape[0], img.shape[1], 1))\n if should_resize:\n img = resize_image(\n img,\n (height, width),\n preprocessing_parameters['resize_method']\n )\n data[feature['name']][i, :, :, :] = img\n else:\n data_fp = os.path.splitext(dataset_df.csv)[0] + '.hdf5'\n mode = 'w'\n if os.path.isfile(data_fp):\n mode = 'r+'\n with h5py.File(data_fp, mode) as h5_file:\n image_dataset = h5_file.create_dataset(\n feature['name'] + '_data',\n (num_images, height, width, num_channels),\n dtype=np.uint8\n )\n for i in range(len(dataset_df)):\n filename = os.path.join(\n csv_path,\n dataset_df[feature['name']][i]\n )\n img = imread(filename)\n if img.ndim == 2:\n img = img.reshape((img.shape[0], img.shape[1], 1))\n if should_resize:\n img = resize_image(\n img,\n (height, width),\n preprocessing_parameters['resize_method'],\n )\n\n image_dataset[i, :height, :width, :] = img\n\n data[feature['name']] = np.arange(num_images)\n\n\nclass ImageInputFeature(ImageBaseFeature, InputFeature):\n def __init__(self, feature):\n super().__init__(feature)\n\n self.height = 0\n self.width = 0\n self.num_channels = 0\n\n self.in_memory = True\n self.data_hdf5_fp = ''\n\n self.encoder = 'stacked_cnn'\n\n encoder_parameters = self.overwrite_defaults(feature)\n\n self.encoder_obj = self.get_image_encoder(encoder_parameters)\n\n def get_image_encoder(self, encoder_parameters):\n return get_from_registry(\n self.encoder, image_encoder_registry)(\n **encoder_parameters\n )\n\n def _get_input_placeholder(self):\n # None dimension is for dealing with variable batch size\n return tf.placeholder(\n tf.float32,\n shape=[None, self.height, self.width, self.num_channels],\n name=self.name,\n )\n\n def build_input(\n self,\n regularizer,\n dropout_rate,\n is_training=False,\n **kwargs\n ):\n placeholder = self._get_input_placeholder()\n logging.debug(' targets_placeholder: {0}'.format(placeholder))\n\n feature_representation, feature_representation_size = self.encoder_obj(\n placeholder,\n regularizer,\n dropout_rate,\n is_training,\n )\n logging.debug(\n ' feature_representation: {0}'.format(feature_representation)\n )\n\n feature_representation = {\n 'name': self.name,\n 'type': self.type,\n 'representation': feature_representation,\n 'size': feature_representation_size,\n 'placeholder': placeholder\n }\n return feature_representation\n\n @staticmethod\n def update_model_definition_with_metadata(\n input_feature,\n feature_metadata,\n *args,\n **kwargs\n ):\n for dim in ['height', 'width', 'num_channels']:\n input_feature[dim] = feature_metadata['preprocessing'][dim]\n input_feature['data_hdf5_fp'] = (\n kwargs['model_definition']['data_hdf5_fp']\n )\n\n @staticmethod\n def populate_defaults(input_feature):\n set_default_value(input_feature, 'tied_weights', None)\n\n\nimage_encoder_registry = {\n 'stacked_cnn': Stacked2DCNN,\n 'resnet': ResNetEncoder\n}\n"
] | [
[
"numpy.arange",
"tensorflow.placeholder",
"numpy.empty"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.13",
"1.5",
"1.7",
"0.12",
"1.0",
"1.2"
]
}
] |
devinlife/tensorflow | [
"1445444c15a396410f25ae91b7d1c19d724e2afc",
"1445444c15a396410f25ae91b7d1c19d724e2afc",
"1445444c15a396410f25ae91b7d1c19d724e2afc",
"1445444c15a396410f25ae91b7d1c19d724e2afc",
"1445444c15a396410f25ae91b7d1c19d724e2afc"
] | [
"tensorflow/python/keras/layers/convolutional.py",
"tensorflow/python/kernel_tests/lu_op_test.py",
"tensorflow/python/ops/nn_impl.py",
"tensorflow/compiler/tests/ternary_ops_test.py",
"tensorflow/python/keras/layers/pooling.py"
] | [
"# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Keras convolution layers and image transformation layers.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.keras import activations\nfrom tensorflow.python.keras import backend\nfrom tensorflow.python.keras import constraints\nfrom tensorflow.python.keras import initializers\nfrom tensorflow.python.keras import regularizers\nfrom tensorflow.python.keras.engine.base_layer import Layer\nfrom tensorflow.python.keras.engine.input_spec import InputSpec\n# imports for backwards namespace compatibility\n# pylint: disable=unused-import\nfrom tensorflow.python.keras.layers.pooling import AveragePooling1D\nfrom tensorflow.python.keras.layers.pooling import AveragePooling2D\nfrom tensorflow.python.keras.layers.pooling import AveragePooling3D\nfrom tensorflow.python.keras.layers.pooling import MaxPooling1D\nfrom tensorflow.python.keras.layers.pooling import MaxPooling2D\nfrom tensorflow.python.keras.layers.pooling import MaxPooling3D\n# pylint: enable=unused-import\nfrom tensorflow.python.keras.utils import conv_utils\nfrom tensorflow.python.keras.utils import tf_utils\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import nn\nfrom tensorflow.python.ops import nn_ops\nfrom tensorflow.python.util.tf_export import keras_export\n# pylint: disable=g-classes-have-attributes\n\n\nclass Conv(Layer):\n \"\"\"Abstract N-D convolution layer (private, used as implementation base).\n\n This layer creates a convolution kernel that is convolved\n (actually cross-correlated) with the layer input to produce a tensor of\n outputs. If `use_bias` is True (and a `bias_initializer` is provided),\n a bias vector is created and added to the outputs. Finally, if\n `activation` is not `None`, it is applied to the outputs as well.\n\n Note: layer attributes cannot be modified after the layer has been called\n once (except the `trainable` attribute).\n\n Arguments:\n rank: An integer, the rank of the convolution, e.g. \"2\" for 2D convolution.\n filters: Integer, the dimensionality of the output space (i.e. the number\n of filters in the convolution).\n kernel_size: An integer or tuple/list of n integers, specifying the\n length of the convolution window.\n strides: An integer or tuple/list of n integers,\n specifying the stride length of the convolution.\n Specifying any stride value != 1 is incompatible with specifying\n any `dilation_rate` value != 1.\n padding: One of `\"valid\"`, `\"same\"`, or `\"causal\"` (case-insensitive).\n data_format: A string, one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch_size, ..., channels)` while `channels_first` corresponds to\n inputs with shape `(batch_size, channels, ...)`.\n dilation_rate: An integer or tuple/list of n integers, specifying\n the dilation rate to use for dilated convolution.\n Currently, specifying any `dilation_rate` value != 1 is\n incompatible with specifying any `strides` value != 1.\n activation: Activation function to use.\n If you don't specify anything, no activation is applied.\n use_bias: Boolean, whether the layer uses a bias.\n kernel_initializer: An initializer for the convolution kernel.\n bias_initializer: An initializer for the bias vector. If None, the default\n initializer will be used.\n kernel_regularizer: Optional regularizer for the convolution kernel.\n bias_regularizer: Optional regularizer for the bias vector.\n activity_regularizer: Optional regularizer function for the output.\n kernel_constraint: Optional projection function to be applied to the\n kernel after being updated by an `Optimizer` (e.g. used to implement\n norm constraints or value constraints for layer weights). The function\n must take as input the unprojected variable and must return the\n projected variable (which must have the same shape). Constraints are\n not safe to use when doing asynchronous distributed training.\n bias_constraint: Optional projection function to be applied to the\n bias after being updated by an `Optimizer`.\n trainable: Boolean, if `True` the weights of this layer will be marked as\n trainable (and listed in `layer.trainable_weights`).\n name: A string, the name of the layer.\n \"\"\"\n\n def __init__(self, rank,\n filters,\n kernel_size,\n strides=1,\n padding='valid',\n data_format=None,\n dilation_rate=1,\n activation=None,\n use_bias=True,\n kernel_initializer='glorot_uniform',\n bias_initializer='zeros',\n kernel_regularizer=None,\n bias_regularizer=None,\n activity_regularizer=None,\n kernel_constraint=None,\n bias_constraint=None,\n trainable=True,\n name=None,\n **kwargs):\n super(Conv, self).__init__(\n trainable=trainable,\n name=name,\n activity_regularizer=regularizers.get(activity_regularizer),\n **kwargs)\n self.rank = rank\n if filters is not None and not isinstance(filters, int):\n filters = int(filters)\n self.filters = filters\n self.kernel_size = conv_utils.normalize_tuple(\n kernel_size, rank, 'kernel_size')\n if not all(self.kernel_size):\n raise ValueError('The argument `kernel_size` cannot contain 0(s). '\n 'Received: %s' % (kernel_size,))\n self.strides = conv_utils.normalize_tuple(strides, rank, 'strides')\n self.padding = conv_utils.normalize_padding(padding)\n if (self.padding == 'causal' and not isinstance(self,\n (Conv1D, SeparableConv1D))):\n raise ValueError('Causal padding is only supported for `Conv1D`'\n 'and ``SeparableConv1D`.')\n self.data_format = conv_utils.normalize_data_format(data_format)\n self.dilation_rate = conv_utils.normalize_tuple(\n dilation_rate, rank, 'dilation_rate')\n self.activation = activations.get(activation)\n self.use_bias = use_bias\n self.kernel_initializer = initializers.get(kernel_initializer)\n self.bias_initializer = initializers.get(bias_initializer)\n self.kernel_regularizer = regularizers.get(kernel_regularizer)\n self.bias_regularizer = regularizers.get(bias_regularizer)\n self.kernel_constraint = constraints.get(kernel_constraint)\n self.bias_constraint = constraints.get(bias_constraint)\n self.input_spec = InputSpec(ndim=self.rank + 2)\n\n def build(self, input_shape):\n input_shape = tensor_shape.TensorShape(input_shape)\n input_channel = self._get_input_channel(input_shape)\n kernel_shape = self.kernel_size + (input_channel, self.filters)\n\n self.kernel = self.add_weight(\n name='kernel',\n shape=kernel_shape,\n initializer=self.kernel_initializer,\n regularizer=self.kernel_regularizer,\n constraint=self.kernel_constraint,\n trainable=True,\n dtype=self.dtype)\n if self.use_bias:\n self.bias = self.add_weight(\n name='bias',\n shape=(self.filters,),\n initializer=self.bias_initializer,\n regularizer=self.bias_regularizer,\n constraint=self.bias_constraint,\n trainable=True,\n dtype=self.dtype)\n else:\n self.bias = None\n channel_axis = self._get_channel_axis()\n self.input_spec = InputSpec(ndim=self.rank + 2,\n axes={channel_axis: input_channel})\n\n self._build_conv_op_input_shape = input_shape\n self._build_input_channel = input_channel\n self._padding_op = self._get_padding_op()\n self._conv_op_data_format = conv_utils.convert_data_format(\n self.data_format, self.rank + 2)\n self._convolution_op = nn_ops.Convolution(\n input_shape,\n filter_shape=self.kernel.shape,\n dilation_rate=self.dilation_rate,\n strides=self.strides,\n padding=self._padding_op,\n data_format=self._conv_op_data_format)\n self.built = True\n\n def call(self, inputs):\n if self._recreate_conv_op(inputs):\n self._convolution_op = nn_ops.Convolution(\n inputs.get_shape(),\n filter_shape=self.kernel.shape,\n dilation_rate=self.dilation_rate,\n strides=self.strides,\n padding=self._padding_op,\n data_format=self._conv_op_data_format)\n self._build_conv_op_input_shape = inputs.get_shape()\n\n # Apply causal padding to inputs for Conv1D.\n if self.padding == 'causal' and self.__class__.__name__ == 'Conv1D':\n inputs = array_ops.pad(inputs, self._compute_causal_padding())\n\n outputs = self._convolution_op(inputs, self.kernel)\n\n if self.use_bias:\n if self.data_format == 'channels_first':\n if self.rank == 1:\n # nn.bias_add does not accept a 1D input tensor.\n bias = array_ops.reshape(self.bias, (1, self.filters, 1))\n outputs += bias\n else:\n outputs = nn.bias_add(outputs, self.bias, data_format='NCHW')\n else:\n outputs = nn.bias_add(outputs, self.bias, data_format='NHWC')\n\n if self.activation is not None:\n return self.activation(outputs)\n return outputs\n\n def _spatial_output_shape(self, spatial_input_shape):\n return [\n conv_utils.conv_output_length(\n length,\n self.kernel_size[i],\n padding=self.padding,\n stride=self.strides[i],\n dilation=self.dilation_rate[i])\n for i, length in enumerate(spatial_input_shape)\n ]\n\n def compute_output_shape(self, input_shape):\n input_shape = tensor_shape.TensorShape(input_shape).as_list()\n if self.data_format == 'channels_last':\n return tensor_shape.TensorShape(\n [input_shape[0]] + self._spatial_output_shape(input_shape[1:-1]) +\n [self.filters])\n else:\n return tensor_shape.TensorShape(\n [input_shape[0], self.filters] +\n self._spatial_output_shape(input_shape[2:]))\n\n def get_config(self):\n config = {\n 'filters': self.filters,\n 'kernel_size': self.kernel_size,\n 'strides': self.strides,\n 'padding': self.padding,\n 'data_format': self.data_format,\n 'dilation_rate': self.dilation_rate,\n 'activation': activations.serialize(self.activation),\n 'use_bias': self.use_bias,\n 'kernel_initializer': initializers.serialize(self.kernel_initializer),\n 'bias_initializer': initializers.serialize(self.bias_initializer),\n 'kernel_regularizer': regularizers.serialize(self.kernel_regularizer),\n 'bias_regularizer': regularizers.serialize(self.bias_regularizer),\n 'activity_regularizer':\n regularizers.serialize(self.activity_regularizer),\n 'kernel_constraint': constraints.serialize(self.kernel_constraint),\n 'bias_constraint': constraints.serialize(self.bias_constraint)\n }\n base_config = super(Conv, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n def _compute_causal_padding(self):\n \"\"\"Calculates padding for 'causal' option for 1-d conv layers.\"\"\"\n left_pad = self.dilation_rate[0] * (self.kernel_size[0] - 1)\n if self.data_format == 'channels_last':\n causal_padding = [[0, 0], [left_pad, 0], [0, 0]]\n else:\n causal_padding = [[0, 0], [0, 0], [left_pad, 0]]\n return causal_padding\n\n def _get_channel_axis(self):\n if self.data_format == 'channels_first':\n return 1\n else:\n return -1\n\n def _get_input_channel(self, input_shape):\n channel_axis = self._get_channel_axis()\n if input_shape.dims[channel_axis].value is None:\n raise ValueError('The channel dimension of the inputs '\n 'should be defined. Found `None`.')\n return int(input_shape[channel_axis])\n\n def _get_padding_op(self):\n if self.padding == 'causal':\n op_padding = 'valid'\n else:\n op_padding = self.padding\n if not isinstance(op_padding, (list, tuple)):\n op_padding = op_padding.upper()\n return op_padding\n\n def _recreate_conv_op(self, inputs):\n \"\"\"Recreate conv_op if necessary.\n\n Check if the input_shape in call() is different from that in build().\n If the most-specific input shape describing the build and call shapes is not\n equal to the shape we currently built with, then we need to rebuild the\n _convolution_op to avoid incorrect behavior.\n\n Args:\n inputs: The input data to call() method.\n\n Returns:\n `True` or `False` to indicate whether to recreate the conv_op.\n \"\"\"\n call_input_shape = inputs.get_shape()\n # If the most specific compatible shape between _build_input_shape and\n # call_input_shape is not _build_input_shape then we must re-build.\n return self._build_conv_op_input_shape.most_specific_compatible_shape(\n call_input_shape) != self._build_conv_op_input_shape\n\n\n@keras_export('keras.layers.Conv1D', 'keras.layers.Convolution1D')\nclass Conv1D(Conv):\n \"\"\"1D convolution layer (e.g. temporal convolution).\n\n This layer creates a convolution kernel that is convolved\n with the layer input over a single spatial (or temporal) dimension\n to produce a tensor of outputs.\n If `use_bias` is True, a bias vector is created and added to the outputs.\n Finally, if `activation` is not `None`,\n it is applied to the outputs as well.\n\n When using this layer as the first layer in a model,\n provide an `input_shape` argument\n (tuple of integers or `None`, e.g.\n `(10, 128)` for sequences of 10 vectors of 128-dimensional vectors,\n or `(None, 128)` for variable-length sequences of 128-dimensional vectors.\n\n Examples:\n\n >>> # The inputs are 128-length vectors with 10 timesteps, and the batch size\n >>> # is 4.\n >>> input_shape = (4, 10, 128)\n >>> x = tf.random.normal(input_shape)\n >>> y = tf.keras.layers.Conv1D(\n ... 32, 3, activation='relu',input_shape=input_shape)(x)\n >>> print(y.shape)\n (4, 8, 32)\n\n Arguments:\n filters: Integer, the dimensionality of the output space\n (i.e. the number of output filters in the convolution).\n kernel_size: An integer or tuple/list of a single integer,\n specifying the length of the 1D convolution window.\n strides: An integer or tuple/list of a single integer,\n specifying the stride length of the convolution.\n Specifying any stride value != 1 is incompatible with specifying\n any `dilation_rate` value != 1.\n padding: One of `\"valid\"`, `\"causal\"` or `\"same\"` (case-insensitive).\n `\"causal\"` results in causal (dilated) convolutions, e.g. `output[t]`\n does not depend on `input[t+1:]`. Useful when modeling temporal data\n where the model should not violate the temporal order.\n See [WaveNet: A Generative Model for Raw Audio, section\n 2.1](https://arxiv.org/abs/1609.03499).\n data_format: A string,\n one of `channels_last` (default) or `channels_first`.\n dilation_rate: an integer or tuple/list of a single integer, specifying\n the dilation rate to use for dilated convolution.\n Currently, specifying any `dilation_rate` value != 1 is\n incompatible with specifying any `strides` value != 1.\n activation: Activation function to use.\n If you don't specify anything, no activation is applied (\n see `keras.activations`).\n use_bias: Boolean, whether the layer uses a bias vector.\n kernel_initializer: Initializer for the `kernel` weights matrix (\n see `keras.initializers`).\n bias_initializer: Initializer for the bias vector (\n see `keras.initializers`).\n kernel_regularizer: Regularizer function applied to\n the `kernel` weights matrix (see `keras.regularizers`).\n bias_regularizer: Regularizer function applied to the bias vector (\n see `keras.regularizers`).\n activity_regularizer: Regularizer function applied to\n the output of the layer (its \"activation\") (\n see `keras.regularizers`).\n kernel_constraint: Constraint function applied to the kernel matrix (\n see `keras.constraints`).\n bias_constraint: Constraint function applied to the bias vector (\n see `keras.constraints`).\n\n Input shape:\n 3D tensor with shape: `(batch_size, steps, input_dim)`\n\n Output shape:\n 3D tensor with shape: `(batch_size, new_steps, filters)`\n `steps` value might have changed due to padding or strides.\n\n Returns:\n A tensor of rank 3 representing\n `activation(conv1d(inputs, kernel) + bias)`.\n\n Raises:\n ValueError: when both `strides` > 1 and `dilation_rate` > 1.\n \"\"\"\n\n def __init__(self,\n filters,\n kernel_size,\n strides=1,\n padding='valid',\n data_format='channels_last',\n dilation_rate=1,\n activation=None,\n use_bias=True,\n kernel_initializer='glorot_uniform',\n bias_initializer='zeros',\n kernel_regularizer=None,\n bias_regularizer=None,\n activity_regularizer=None,\n kernel_constraint=None,\n bias_constraint=None,\n **kwargs):\n super(Conv1D, self).__init__(\n rank=1,\n filters=filters,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n data_format=data_format,\n dilation_rate=dilation_rate,\n activation=activations.get(activation),\n use_bias=use_bias,\n kernel_initializer=initializers.get(kernel_initializer),\n bias_initializer=initializers.get(bias_initializer),\n kernel_regularizer=regularizers.get(kernel_regularizer),\n bias_regularizer=regularizers.get(bias_regularizer),\n activity_regularizer=regularizers.get(activity_regularizer),\n kernel_constraint=constraints.get(kernel_constraint),\n bias_constraint=constraints.get(bias_constraint),\n **kwargs)\n\n\n@keras_export('keras.layers.Conv2D', 'keras.layers.Convolution2D')\nclass Conv2D(Conv):\n \"\"\"2D convolution layer (e.g. spatial convolution over images).\n\n This layer creates a convolution kernel that is convolved\n with the layer input to produce a tensor of\n outputs. If `use_bias` is True,\n a bias vector is created and added to the outputs. Finally, if\n `activation` is not `None`, it is applied to the outputs as well.\n\n When using this layer as the first layer in a model,\n provide the keyword argument `input_shape`\n (tuple of integers, does not include the sample axis),\n e.g. `input_shape=(128, 128, 3)` for 128x128 RGB pictures\n in `data_format=\"channels_last\"`.\n\n Examples:\n\n >>> # The inputs are 28x28 RGB images with `channels_last` and the batch\n >>> # size is 4.\n >>> input_shape = (4, 28, 28, 3)\n >>> x = tf.random.normal(input_shape)\n >>> y = tf.keras.layers.Conv2D(\n ... 2, 3, activation='relu', input_shape=input_shape)(x)\n >>> print(y.shape)\n (4, 26, 26, 2)\n\n >>> # With `dilation_rate` as 2.\n >>> input_shape = (4, 28, 28, 3)\n >>> x = tf.random.normal(input_shape)\n >>> y = tf.keras.layers.Conv2D(\n ... 2, 3, activation='relu', dilation_rate=2, input_shape=input_shape)(x)\n >>> print(y.shape)\n (4, 24, 24, 2)\n\n >>> # With `padding` as \"same\".\n >>> input_shape = (4, 28, 28, 3)\n >>> x = tf.random.normal(input_shape)\n >>> y = tf.keras.layers.Conv2D(\n ... 2, 3, activation='relu', padding=\"same\", input_shape=input_shape)(x)\n >>> print(y.shape)\n (4, 28, 28, 2)\n\n\n Arguments:\n filters: Integer, the dimensionality of the output space\n (i.e. the number of output filters in the convolution).\n kernel_size: An integer or tuple/list of 2 integers, specifying the\n height and width of the 2D convolution window.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n strides: An integer or tuple/list of 2 integers,\n specifying the strides of the convolution along the height and width.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n Specifying any stride value != 1 is incompatible with specifying\n any `dilation_rate` value != 1.\n padding: one of `\"valid\"` or `\"same\"` (case-insensitive).\n data_format: A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch_size, height, width, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch_size, channels, height, width)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".\n dilation_rate: an integer or tuple/list of 2 integers, specifying\n the dilation rate to use for dilated convolution.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n Currently, specifying any `dilation_rate` value != 1 is\n incompatible with specifying any stride value != 1.\n activation: Activation function to use.\n If you don't specify anything, no activation is applied (\n see `keras.activations`).\n use_bias: Boolean, whether the layer uses a bias vector.\n kernel_initializer: Initializer for the `kernel` weights matrix (\n see `keras.initializers`).\n bias_initializer: Initializer for the bias vector (\n see `keras.initializers`).\n kernel_regularizer: Regularizer function applied to\n the `kernel` weights matrix (see `keras.regularizers`).\n bias_regularizer: Regularizer function applied to the bias vector (\n see `keras.regularizers`).\n activity_regularizer: Regularizer function applied to\n the output of the layer (its \"activation\") (\n see `keras.regularizers`).\n kernel_constraint: Constraint function applied to the kernel matrix (\n see `keras.constraints`).\n bias_constraint: Constraint function applied to the bias vector (\n see `keras.constraints`).\n\n Input shape:\n 4D tensor with shape:\n `(batch_size, channels, rows, cols)` if data_format='channels_first'\n or 4D tensor with shape:\n `(batch_size, rows, cols, channels)` if data_format='channels_last'.\n\n Output shape:\n 4D tensor with shape:\n `(batch_size, filters, new_rows, new_cols)` if data_format='channels_first'\n or 4D tensor with shape:\n `(batch_size, new_rows, new_cols, filters)` if data_format='channels_last'.\n `rows` and `cols` values might have changed due to padding.\n\n Returns:\n A tensor of rank 4 representing\n `activation(conv2d(inputs, kernel) + bias)`.\n\n Raises:\n ValueError: if `padding` is \"causal\".\n ValueError: when both `strides` > 1 and `dilation_rate` > 1.\n \"\"\"\n\n def __init__(self,\n filters,\n kernel_size,\n strides=(1, 1),\n padding='valid',\n data_format=None,\n dilation_rate=(1, 1),\n activation=None,\n use_bias=True,\n kernel_initializer='glorot_uniform',\n bias_initializer='zeros',\n kernel_regularizer=None,\n bias_regularizer=None,\n activity_regularizer=None,\n kernel_constraint=None,\n bias_constraint=None,\n **kwargs):\n super(Conv2D, self).__init__(\n rank=2,\n filters=filters,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n data_format=data_format,\n dilation_rate=dilation_rate,\n activation=activations.get(activation),\n use_bias=use_bias,\n kernel_initializer=initializers.get(kernel_initializer),\n bias_initializer=initializers.get(bias_initializer),\n kernel_regularizer=regularizers.get(kernel_regularizer),\n bias_regularizer=regularizers.get(bias_regularizer),\n activity_regularizer=regularizers.get(activity_regularizer),\n kernel_constraint=constraints.get(kernel_constraint),\n bias_constraint=constraints.get(bias_constraint),\n **kwargs)\n\n\n@keras_export('keras.layers.Conv3D', 'keras.layers.Convolution3D')\nclass Conv3D(Conv):\n \"\"\"3D convolution layer (e.g. spatial convolution over volumes).\n\n This layer creates a convolution kernel that is convolved\n with the layer input to produce a tensor of\n outputs. If `use_bias` is True,\n a bias vector is created and added to the outputs. Finally, if\n `activation` is not `None`, it is applied to the outputs as well.\n\n When using this layer as the first layer in a model,\n provide the keyword argument `input_shape`\n (tuple of integers, does not include the sample axis),\n e.g. `input_shape=(128, 128, 128, 1)` for 128x128x128 volumes\n with a single channel,\n in `data_format=\"channels_last\"`.\n\n Examples:\n\n >>> # The inputs are 28x28x28 volumes with a single channel, and the\n >>> # batch size is 4\n >>> input_shape =(4, 28, 28, 28, 1)\n >>> x = tf.random.normal(input_shape)\n >>> y = tf.keras.layers.Conv3D(\n ... 2, 3, activation='relu', input_shape=input_shape)(x)\n >>> print(y.shape)\n (4, 26, 26, 26, 2)\n\n Arguments:\n filters: Integer, the dimensionality of the output space\n (i.e. the number of output filters in the convolution).\n kernel_size: An integer or tuple/list of 3 integers, specifying the\n depth, height and width of the 3D convolution window.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n strides: An integer or tuple/list of 3 integers,\n specifying the strides of the convolution along each spatial\n dimension.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n Specifying any stride value != 1 is incompatible with specifying\n any `dilation_rate` value != 1.\n padding: one of `\"valid\"` or `\"same\"` (case-insensitive).\n data_format: A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch_size, spatial_dim1, spatial_dim2, spatial_dim3, channels)`\n while `channels_first` corresponds to inputs with shape\n `(batch_size, channels, spatial_dim1, spatial_dim2, spatial_dim3)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".\n dilation_rate: an integer or tuple/list of 3 integers, specifying\n the dilation rate to use for dilated convolution.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n Currently, specifying any `dilation_rate` value != 1 is\n incompatible with specifying any stride value != 1.\n activation: Activation function to use.\n If you don't specify anything, no activation is applied (\n see `keras.activations`).\n use_bias: Boolean, whether the layer uses a bias vector.\n kernel_initializer: Initializer for the `kernel` weights matrix (\n see `keras.initializers`).\n bias_initializer: Initializer for the bias vector (\n see `keras.initializers`).\n kernel_regularizer: Regularizer function applied to\n the `kernel` weights matrix (\n see `keras.regularizers`).\n bias_regularizer: Regularizer function applied to the bias vector (\n see `keras.regularizers`).\n activity_regularizer: Regularizer function applied to\n the output of the layer (its \"activation\") (\n see `keras.regularizers`).\n kernel_constraint: Constraint function applied to the kernel matrix (\n see `keras.constraints`).\n bias_constraint: Constraint function applied to the bias vector (\n see `keras.constraints`).\n\n Input shape:\n 5D tensor with shape:\n `(batch_size, channels, conv_dim1, conv_dim2, conv_dim3)` if\n data_format='channels_first'\n or 5D tensor with shape:\n `(batch_size, conv_dim1, conv_dim2, conv_dim3, channels)` if\n data_format='channels_last'.\n\n Output shape:\n 5D tensor with shape:\n `(batch_size, filters, new_conv_dim1, new_conv_dim2, new_conv_dim3)` if\n data_format='channels_first'\n or 5D tensor with shape:\n `(batch_size, new_conv_dim1, new_conv_dim2, new_conv_dim3, filters)` if\n data_format='channels_last'.\n `new_conv_dim1`, `new_conv_dim2` and `new_conv_dim3` values might have\n changed due to padding.\n\n Returns:\n A tensor of rank 5 representing\n `activation(conv3d(inputs, kernel) + bias)`.\n\n Raises:\n ValueError: if `padding` is \"causal\".\n ValueError: when both `strides` > 1 and `dilation_rate` > 1.\n \"\"\"\n\n def __init__(self,\n filters,\n kernel_size,\n strides=(1, 1, 1),\n padding='valid',\n data_format=None,\n dilation_rate=(1, 1, 1),\n activation=None,\n use_bias=True,\n kernel_initializer='glorot_uniform',\n bias_initializer='zeros',\n kernel_regularizer=None,\n bias_regularizer=None,\n activity_regularizer=None,\n kernel_constraint=None,\n bias_constraint=None,\n **kwargs):\n super(Conv3D, self).__init__(\n rank=3,\n filters=filters,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n data_format=data_format,\n dilation_rate=dilation_rate,\n activation=activations.get(activation),\n use_bias=use_bias,\n kernel_initializer=initializers.get(kernel_initializer),\n bias_initializer=initializers.get(bias_initializer),\n kernel_regularizer=regularizers.get(kernel_regularizer),\n bias_regularizer=regularizers.get(bias_regularizer),\n activity_regularizer=regularizers.get(activity_regularizer),\n kernel_constraint=constraints.get(kernel_constraint),\n bias_constraint=constraints.get(bias_constraint),\n **kwargs)\n\n\n@keras_export('keras.layers.Conv1DTranspose',\n 'keras.layers.Convolution1DTranspose')\nclass Conv1DTranspose(Conv1D):\n \"\"\"Transposed convolution layer (sometimes called Deconvolution).\n\n The need for transposed convolutions generally arises\n from the desire to use a transformation going in the opposite direction\n of a normal convolution, i.e., from something that has the shape of the\n output of some convolution to something that has the shape of its input\n while maintaining a connectivity pattern that is compatible with\n said convolution.\n\n When using this layer as the first layer in a model,\n provide the keyword argument `input_shape`\n (tuple of integers, does not include the sample axis),\n e.g. `input_shape=(128, 3)` for data with 128 time steps and 3 channels.\n\n Arguments:\n filters: Integer, the dimensionality of the output space\n (i.e. the number of output filters in the convolution).\n kernel_size: An integer length of the 1D convolution window.\n strides: An integer specifying the stride of the convolution along the\n time dimension. Specifying a stride value != 1 is incompatible with\n specifying a `dilation_rate` value != 1. Defaults to 1.\n padding: one of `\"valid\"` or `\"same\"` (case-insensitive).\n output_padding: An integer specifying the amount of padding along\n the time dimension of the output tensor.\n The amount of output padding must be lower than the stride.\n If set to `None` (default), the output shape is inferred.\n data_format: A string, one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch_size, length, channels)` while `channels_first` corresponds to\n inputs with shape `(batch_size, channels, length)`.\n dilation_rate: an integer, specifying\n the dilation rate to use for dilated convolution.\n Currently, specifying a `dilation_rate` value != 1 is\n incompatible with specifying a stride value != 1.\n activation: Activation function to use.\n If you don't specify anything, no activation is applied (\n see `keras.activations`).\n use_bias: Boolean, whether the layer uses a bias vector.\n kernel_initializer: Initializer for the `kernel` weights matrix (\n see `keras.initializers`).\n bias_initializer: Initializer for the bias vector (\n see `keras.initializers`).\n kernel_regularizer: Regularizer function applied to\n the `kernel` weights matrix (see `keras.regularizers`).\n bias_regularizer: Regularizer function applied to the bias vector (\n see `keras.regularizers`).\n activity_regularizer: Regularizer function applied to\n the output of the layer (its \"activation\") (see `keras.regularizers`).\n kernel_constraint: Constraint function applied to the kernel matrix (\n see `keras.constraints`).\n bias_constraint: Constraint function applied to the bias vector (\n see `keras.constraints`).\n\n Input shape:\n 3D tensor with shape:\n `(batch_size, steps, channels)`\n\n Output shape:\n 3D tensor with shape:\n `(batch_size, new_steps, filters)`\n If `output_padding` is specified:\n ```\n new_timesteps = ((timesteps - 1) * strides + kernel_size -\n 2 * padding + output_padding)\n ```\n\n Returns:\n A tensor of rank 3 representing\n `activation(conv1dtranspose(inputs, kernel) + bias)`.\n\n Raises:\n ValueError: if `padding` is \"causal\".\n ValueError: when both `strides` > 1 and `dilation_rate` > 1.\n\n References:\n - [A guide to convolution arithmetic for deep learning](\n https://arxiv.org/abs/1603.07285v1)\n - [Deconvolutional Networks](\n https://www.matthewzeiler.com/mattzeiler/deconvolutionalnetworks.pdf)\n \"\"\"\n\n def __init__(self,\n filters,\n kernel_size,\n strides=1,\n padding='valid',\n output_padding=None,\n data_format=None,\n dilation_rate=1,\n activation=None,\n use_bias=True,\n kernel_initializer='glorot_uniform',\n bias_initializer='zeros',\n kernel_regularizer=None,\n bias_regularizer=None,\n activity_regularizer=None,\n kernel_constraint=None,\n bias_constraint=None,\n **kwargs):\n super(Conv1DTranspose, self).__init__(\n filters=filters,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n data_format=data_format,\n dilation_rate=dilation_rate,\n activation=activations.get(activation),\n use_bias=use_bias,\n kernel_initializer=initializers.get(kernel_initializer),\n bias_initializer=initializers.get(bias_initializer),\n kernel_regularizer=regularizers.get(kernel_regularizer),\n bias_regularizer=regularizers.get(bias_regularizer),\n activity_regularizer=regularizers.get(activity_regularizer),\n kernel_constraint=constraints.get(kernel_constraint),\n bias_constraint=constraints.get(bias_constraint),\n **kwargs)\n\n self.output_padding = output_padding\n if self.output_padding is not None:\n self.output_padding = conv_utils.normalize_tuple(\n self.output_padding, 1, 'output_padding')\n for stride, out_pad in zip(self.strides, self.output_padding):\n if out_pad >= stride:\n raise ValueError('Stride ' + str(self.strides) + ' must be '\n 'greater than output padding ' +\n str(self.output_padding))\n\n def build(self, input_shape):\n input_shape = tensor_shape.TensorShape(input_shape)\n if len(input_shape) != 3:\n raise ValueError('Inputs should have rank 3. Received input shape: ' +\n str(input_shape))\n channel_axis = self._get_channel_axis()\n if input_shape.dims[channel_axis].value is None:\n raise ValueError('The channel dimension of the inputs '\n 'should be defined. Found `None`.')\n input_dim = int(input_shape[channel_axis])\n self.input_spec = InputSpec(ndim=3, axes={channel_axis: input_dim})\n kernel_shape = self.kernel_size + (self.filters, input_dim)\n\n self.kernel = self.add_weight(\n name='kernel',\n shape=kernel_shape,\n initializer=self.kernel_initializer,\n regularizer=self.kernel_regularizer,\n constraint=self.kernel_constraint,\n trainable=True,\n dtype=self.dtype)\n if self.use_bias:\n self.bias = self.add_weight(\n name='bias',\n shape=(self.filters,),\n initializer=self.bias_initializer,\n regularizer=self.bias_regularizer,\n constraint=self.bias_constraint,\n trainable=True,\n dtype=self.dtype)\n else:\n self.bias = None\n self.built = True\n\n def call(self, inputs):\n inputs_shape = array_ops.shape(inputs)\n batch_size = inputs_shape[0]\n if self.data_format == 'channels_first':\n t_axis = 2\n else:\n t_axis = 1\n\n length = inputs_shape[t_axis]\n if self.output_padding is None:\n output_padding = None\n else:\n output_padding = self.output_padding[0]\n\n # Infer the dynamic output shape:\n out_length = conv_utils.deconv_output_length(\n length, self.kernel_size[0], padding=self.padding,\n output_padding=output_padding, stride=self.strides[0],\n dilation=self.dilation_rate[0])\n if self.data_format == 'channels_first':\n output_shape = (batch_size, self.filters, out_length)\n else:\n output_shape = (batch_size, out_length, self.filters)\n data_format = conv_utils.convert_data_format(self.data_format, ndim=3)\n\n output_shape_tensor = array_ops.stack(output_shape)\n outputs = nn_ops.conv1d_transpose(\n inputs,\n self.kernel,\n output_shape_tensor,\n strides=self.strides,\n padding=self.padding.upper(),\n data_format=data_format,\n dilations=self.dilation_rate)\n\n if not context.executing_eagerly():\n # Infer the static output shape:\n out_shape = self.compute_output_shape(inputs.shape)\n outputs.set_shape(out_shape)\n\n if self.use_bias:\n outputs = nn.bias_add(\n outputs,\n self.bias,\n data_format=data_format)\n\n if self.activation is not None:\n return self.activation(outputs)\n return outputs\n\n def compute_output_shape(self, input_shape):\n input_shape = tensor_shape.TensorShape(input_shape).as_list()\n output_shape = list(input_shape)\n if self.data_format == 'channels_first':\n c_axis, t_axis = 1, 2\n else:\n c_axis, t_axis = 2, 1\n\n if self.output_padding is None:\n output_padding = None\n else:\n output_padding = self.output_padding[0]\n output_shape[c_axis] = self.filters\n output_shape[t_axis] = conv_utils.deconv_output_length(\n output_shape[t_axis],\n self.kernel_size[0],\n padding=self.padding,\n output_padding=output_padding,\n stride=self.strides[0],\n dilation=self.dilation_rate[0])\n return tensor_shape.TensorShape(output_shape)\n\n def get_config(self):\n config = super(Conv1DTranspose, self).get_config()\n config['output_padding'] = self.output_padding\n return config\n\n\n@keras_export('keras.layers.Conv2DTranspose',\n 'keras.layers.Convolution2DTranspose')\nclass Conv2DTranspose(Conv2D):\n \"\"\"Transposed convolution layer (sometimes called Deconvolution).\n\n The need for transposed convolutions generally arises\n from the desire to use a transformation going in the opposite direction\n of a normal convolution, i.e., from something that has the shape of the\n output of some convolution to something that has the shape of its input\n while maintaining a connectivity pattern that is compatible with\n said convolution.\n\n When using this layer as the first layer in a model,\n provide the keyword argument `input_shape`\n (tuple of integers, does not include the sample axis),\n e.g. `input_shape=(128, 128, 3)` for 128x128 RGB pictures\n in `data_format=\"channels_last\"`.\n\n Arguments:\n filters: Integer, the dimensionality of the output space\n (i.e. the number of output filters in the convolution).\n kernel_size: An integer or tuple/list of 2 integers, specifying the\n height and width of the 2D convolution window.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n strides: An integer or tuple/list of 2 integers,\n specifying the strides of the convolution along the height and width.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n Specifying any stride value != 1 is incompatible with specifying\n any `dilation_rate` value != 1.\n padding: one of `\"valid\"` or `\"same\"` (case-insensitive).\n output_padding: An integer or tuple/list of 2 integers,\n specifying the amount of padding along the height and width\n of the output tensor.\n Can be a single integer to specify the same value for all\n spatial dimensions.\n The amount of output padding along a given dimension must be\n lower than the stride along that same dimension.\n If set to `None` (default), the output shape is inferred.\n data_format: A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch_size, height, width, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch_size, channels, height, width)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".\n dilation_rate: an integer or tuple/list of 2 integers, specifying\n the dilation rate to use for dilated convolution.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n Currently, specifying any `dilation_rate` value != 1 is\n incompatible with specifying any stride value != 1.\n activation: Activation function to use.\n If you don't specify anything, no activation is applied (\n see `keras.activations`).\n use_bias: Boolean, whether the layer uses a bias vector.\n kernel_initializer: Initializer for the `kernel` weights matrix (\n see `keras.initializers`).\n bias_initializer: Initializer for the bias vector (\n see `keras.initializers`).\n kernel_regularizer: Regularizer function applied to\n the `kernel` weights matrix (see `keras.regularizers`).\n bias_regularizer: Regularizer function applied to the bias vector (\n see `keras.regularizers`).\n activity_regularizer: Regularizer function applied to\n the output of the layer (its \"activation\") (see `keras.regularizers`).\n kernel_constraint: Constraint function applied to the kernel matrix (\n see `keras.constraints`).\n bias_constraint: Constraint function applied to the bias vector (\n see `keras.constraints`).\n\n Input shape:\n 4D tensor with shape:\n `(batch_size, channels, rows, cols)` if data_format='channels_first'\n or 4D tensor with shape:\n `(batch_size, rows, cols, channels)` if data_format='channels_last'.\n\n Output shape:\n 4D tensor with shape:\n `(batch_size, filters, new_rows, new_cols)` if data_format='channels_first'\n or 4D tensor with shape:\n `(batch_size, new_rows, new_cols, filters)` if data_format='channels_last'.\n `rows` and `cols` values might have changed due to padding.\n If `output_padding` is specified:\n ```\n new_rows = ((rows - 1) * strides[0] + kernel_size[0] - 2 * padding[0] +\n output_padding[0])\n new_cols = ((cols - 1) * strides[1] + kernel_size[1] - 2 * padding[1] +\n output_padding[1])\n ```\n\n Returns:\n A tensor of rank 4 representing\n `activation(conv2dtranspose(inputs, kernel) + bias)`.\n\n Raises:\n ValueError: if `padding` is \"causal\".\n ValueError: when both `strides` > 1 and `dilation_rate` > 1.\n\n References:\n - [A guide to convolution arithmetic for deep\n learning](https://arxiv.org/abs/1603.07285v1)\n - [Deconvolutional\n Networks](https://www.matthewzeiler.com/mattzeiler/deconvolutionalnetworks.pdf)\n \"\"\"\n\n def __init__(self,\n filters,\n kernel_size,\n strides=(1, 1),\n padding='valid',\n output_padding=None,\n data_format=None,\n dilation_rate=(1, 1),\n activation=None,\n use_bias=True,\n kernel_initializer='glorot_uniform',\n bias_initializer='zeros',\n kernel_regularizer=None,\n bias_regularizer=None,\n activity_regularizer=None,\n kernel_constraint=None,\n bias_constraint=None,\n **kwargs):\n super(Conv2DTranspose, self).__init__(\n filters=filters,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n data_format=data_format,\n dilation_rate=dilation_rate,\n activation=activations.get(activation),\n use_bias=use_bias,\n kernel_initializer=initializers.get(kernel_initializer),\n bias_initializer=initializers.get(bias_initializer),\n kernel_regularizer=regularizers.get(kernel_regularizer),\n bias_regularizer=regularizers.get(bias_regularizer),\n activity_regularizer=regularizers.get(activity_regularizer),\n kernel_constraint=constraints.get(kernel_constraint),\n bias_constraint=constraints.get(bias_constraint),\n **kwargs)\n\n self.output_padding = output_padding\n if self.output_padding is not None:\n self.output_padding = conv_utils.normalize_tuple(\n self.output_padding, 2, 'output_padding')\n for stride, out_pad in zip(self.strides, self.output_padding):\n if out_pad >= stride:\n raise ValueError('Stride ' + str(self.strides) + ' must be '\n 'greater than output padding ' +\n str(self.output_padding))\n\n def build(self, input_shape):\n input_shape = tensor_shape.TensorShape(input_shape)\n if len(input_shape) != 4:\n raise ValueError('Inputs should have rank 4. Received input shape: ' +\n str(input_shape))\n channel_axis = self._get_channel_axis()\n if input_shape.dims[channel_axis].value is None:\n raise ValueError('The channel dimension of the inputs '\n 'should be defined. Found `None`.')\n input_dim = int(input_shape[channel_axis])\n self.input_spec = InputSpec(ndim=4, axes={channel_axis: input_dim})\n kernel_shape = self.kernel_size + (self.filters, input_dim)\n\n self.kernel = self.add_weight(\n name='kernel',\n shape=kernel_shape,\n initializer=self.kernel_initializer,\n regularizer=self.kernel_regularizer,\n constraint=self.kernel_constraint,\n trainable=True,\n dtype=self.dtype)\n if self.use_bias:\n self.bias = self.add_weight(\n name='bias',\n shape=(self.filters,),\n initializer=self.bias_initializer,\n regularizer=self.bias_regularizer,\n constraint=self.bias_constraint,\n trainable=True,\n dtype=self.dtype)\n else:\n self.bias = None\n self.built = True\n\n def call(self, inputs):\n inputs_shape = array_ops.shape(inputs)\n batch_size = inputs_shape[0]\n if self.data_format == 'channels_first':\n h_axis, w_axis = 2, 3\n else:\n h_axis, w_axis = 1, 2\n\n # Use the constant height and weight when possible.\n # TODO(scottzhu): Extract this into a utility function that can be applied\n # to all convolutional layers, which currently lost the static shape\n # information due to tf.shape().\n height, width = None, None\n if inputs.shape.rank is not None:\n dims = inputs.shape.as_list()\n height = dims[h_axis]\n width = dims[w_axis]\n height = height if height is not None else inputs_shape[h_axis]\n width = width if width is not None else inputs_shape[w_axis]\n\n kernel_h, kernel_w = self.kernel_size\n stride_h, stride_w = self.strides\n\n if self.output_padding is None:\n out_pad_h = out_pad_w = None\n else:\n out_pad_h, out_pad_w = self.output_padding\n\n # Infer the dynamic output shape:\n out_height = conv_utils.deconv_output_length(height,\n kernel_h,\n padding=self.padding,\n output_padding=out_pad_h,\n stride=stride_h,\n dilation=self.dilation_rate[0])\n out_width = conv_utils.deconv_output_length(width,\n kernel_w,\n padding=self.padding,\n output_padding=out_pad_w,\n stride=stride_w,\n dilation=self.dilation_rate[1])\n if self.data_format == 'channels_first':\n output_shape = (batch_size, self.filters, out_height, out_width)\n else:\n output_shape = (batch_size, out_height, out_width, self.filters)\n\n output_shape_tensor = array_ops.stack(output_shape)\n outputs = backend.conv2d_transpose(\n inputs,\n self.kernel,\n output_shape_tensor,\n strides=self.strides,\n padding=self.padding,\n data_format=self.data_format,\n dilation_rate=self.dilation_rate)\n\n if not context.executing_eagerly():\n # Infer the static output shape:\n out_shape = self.compute_output_shape(inputs.shape)\n outputs.set_shape(out_shape)\n\n if self.use_bias:\n outputs = nn.bias_add(\n outputs,\n self.bias,\n data_format=conv_utils.convert_data_format(self.data_format, ndim=4))\n\n if self.activation is not None:\n return self.activation(outputs)\n return outputs\n\n def compute_output_shape(self, input_shape):\n input_shape = tensor_shape.TensorShape(input_shape).as_list()\n output_shape = list(input_shape)\n if self.data_format == 'channels_first':\n c_axis, h_axis, w_axis = 1, 2, 3\n else:\n c_axis, h_axis, w_axis = 3, 1, 2\n\n kernel_h, kernel_w = self.kernel_size\n stride_h, stride_w = self.strides\n\n if self.output_padding is None:\n out_pad_h = out_pad_w = None\n else:\n out_pad_h, out_pad_w = self.output_padding\n\n output_shape[c_axis] = self.filters\n output_shape[h_axis] = conv_utils.deconv_output_length(\n output_shape[h_axis],\n kernel_h,\n padding=self.padding,\n output_padding=out_pad_h,\n stride=stride_h,\n dilation=self.dilation_rate[0])\n output_shape[w_axis] = conv_utils.deconv_output_length(\n output_shape[w_axis],\n kernel_w,\n padding=self.padding,\n output_padding=out_pad_w,\n stride=stride_w,\n dilation=self.dilation_rate[1])\n return tensor_shape.TensorShape(output_shape)\n\n def get_config(self):\n config = super(Conv2DTranspose, self).get_config()\n config['output_padding'] = self.output_padding\n return config\n\n\n@keras_export('keras.layers.Conv3DTranspose',\n 'keras.layers.Convolution3DTranspose')\nclass Conv3DTranspose(Conv3D):\n \"\"\"Transposed convolution layer (sometimes called Deconvolution).\n\n The need for transposed convolutions generally arises\n from the desire to use a transformation going in the opposite direction\n of a normal convolution, i.e., from something that has the shape of the\n output of some convolution to something that has the shape of its input\n while maintaining a connectivity pattern that is compatible with\n said convolution.\n\n When using this layer as the first layer in a model,\n provide the keyword argument `input_shape`\n (tuple of integers, does not include the sample axis),\n e.g. `input_shape=(128, 128, 128, 3)` for a 128x128x128 volume with 3 channels\n if `data_format=\"channels_last\"`.\n\n Arguments:\n filters: Integer, the dimensionality of the output space\n (i.e. the number of output filters in the convolution).\n kernel_size: An integer or tuple/list of 3 integers, specifying the\n depth, height and width of the 3D convolution window.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n strides: An integer or tuple/list of 3 integers,\n specifying the strides of the convolution along the depth, height\n and width.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n Specifying any stride value != 1 is incompatible with specifying\n any `dilation_rate` value != 1.\n padding: one of `\"valid\"` or `\"same\"` (case-insensitive).\n output_padding: An integer or tuple/list of 3 integers,\n specifying the amount of padding along the depth, height, and\n width.\n Can be a single integer to specify the same value for all\n spatial dimensions.\n The amount of output padding along a given dimension must be\n lower than the stride along that same dimension.\n If set to `None` (default), the output shape is inferred.\n data_format: A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch_size, depth, height, width, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch_size, channels, depth, height, width)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".\n dilation_rate: an integer or tuple/list of 3 integers, specifying\n the dilation rate to use for dilated convolution.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n Currently, specifying any `dilation_rate` value != 1 is\n incompatible with specifying any stride value != 1.\n activation: Activation function to use.\n If you don't specify anything, no activation is applied (\n see `keras.activations`).\n use_bias: Boolean, whether the layer uses a bias vector.\n kernel_initializer: Initializer for the `kernel` weights matrix.\n bias_initializer: Initializer for the bias vector.\n kernel_regularizer: Regularizer function applied to\n the `kernel` weights matrix (\n see `keras.regularizers`).\n bias_regularizer: Regularizer function applied to the bias vector (\n see `keras.regularizers`).\n activity_regularizer: Regularizer function applied to\n the output of the layer (its \"activation\") (\n see `keras.regularizers`).\n kernel_constraint: Constraint function applied to the kernel matrix (\n see `keras.constraints`).\n bias_constraint: Constraint function applied to the bias vector (\n see `keras.constraints`).\n\n Input shape:\n 5D tensor with shape:\n `(batch_size, channels, depth, rows, cols)` if data_format='channels_first'\n or 5D tensor with shape:\n `(batch_size, depth, rows, cols, channels)` if data_format='channels_last'.\n\n Output shape:\n 5D tensor with shape:\n `(batch_size, filters, new_depth, new_rows, new_cols)` if\n data_format='channels_first'\n or 5D tensor with shape:\n `(batch_size, new_depth, new_rows, new_cols, filters)` if\n data_format='channels_last'.\n `depth` and `rows` and `cols` values might have changed due to padding.\n If `output_padding` is specified::\n ```\n new_depth = ((depth - 1) * strides[0] + kernel_size[0] - 2 * padding[0] +\n output_padding[0])\n new_rows = ((rows - 1) * strides[1] + kernel_size[1] - 2 * padding[1] +\n output_padding[1])\n new_cols = ((cols - 1) * strides[2] + kernel_size[2] - 2 * padding[2] +\n output_padding[2])\n ```\n\n Returns:\n A tensor of rank 5 representing\n `activation(conv3dtranspose(inputs, kernel) + bias)`.\n\n Raises:\n ValueError: if `padding` is \"causal\".\n ValueError: when both `strides` > 1 and `dilation_rate` > 1.\n\n References:\n - [A guide to convolution arithmetic for deep\n learning](https://arxiv.org/abs/1603.07285v1)\n - [Deconvolutional\n Networks](https://www.matthewzeiler.com/mattzeiler/deconvolutionalnetworks.pdf)\n \"\"\"\n\n def __init__(self,\n filters,\n kernel_size,\n strides=(1, 1, 1),\n padding='valid',\n output_padding=None,\n data_format=None,\n dilation_rate=(1, 1, 1),\n activation=None,\n use_bias=True,\n kernel_initializer='glorot_uniform',\n bias_initializer='zeros',\n kernel_regularizer=None,\n bias_regularizer=None,\n activity_regularizer=None,\n kernel_constraint=None,\n bias_constraint=None,\n **kwargs):\n super(Conv3DTranspose, self).__init__(\n filters=filters,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n data_format=data_format,\n dilation_rate=dilation_rate,\n activation=activations.get(activation),\n use_bias=use_bias,\n kernel_initializer=initializers.get(kernel_initializer),\n bias_initializer=initializers.get(bias_initializer),\n kernel_regularizer=regularizers.get(kernel_regularizer),\n bias_regularizer=regularizers.get(bias_regularizer),\n activity_regularizer=regularizers.get(activity_regularizer),\n kernel_constraint=constraints.get(kernel_constraint),\n bias_constraint=constraints.get(bias_constraint),\n **kwargs)\n\n self.output_padding = output_padding\n if self.output_padding is not None:\n self.output_padding = conv_utils.normalize_tuple(\n self.output_padding, 3, 'output_padding')\n for stride, out_pad in zip(self.strides, self.output_padding):\n if out_pad >= stride:\n raise ValueError('Stride ' + str(self.strides) + ' must be '\n 'greater than output padding ' +\n str(self.output_padding))\n\n def build(self, input_shape):\n input_shape = tensor_shape.TensorShape(input_shape)\n if len(input_shape) != 5:\n raise ValueError('Inputs should have rank 5, received input shape:',\n str(input_shape))\n channel_axis = self._get_channel_axis()\n if input_shape.dims[channel_axis].value is None:\n raise ValueError('The channel dimension of the inputs '\n 'should be defined, found None: ' + str(input_shape))\n input_dim = int(input_shape[channel_axis])\n kernel_shape = self.kernel_size + (self.filters, input_dim)\n self.input_spec = InputSpec(ndim=5, axes={channel_axis: input_dim})\n\n self.kernel = self.add_weight(\n 'kernel',\n shape=kernel_shape,\n initializer=self.kernel_initializer,\n regularizer=self.kernel_regularizer,\n constraint=self.kernel_constraint,\n trainable=True,\n dtype=self.dtype)\n if self.use_bias:\n self.bias = self.add_weight(\n 'bias',\n shape=(self.filters,),\n initializer=self.bias_initializer,\n regularizer=self.bias_regularizer,\n constraint=self.bias_constraint,\n trainable=True,\n dtype=self.dtype)\n else:\n self.bias = None\n self.built = True\n\n def call(self, inputs):\n inputs_shape = array_ops.shape(inputs)\n batch_size = inputs_shape[0]\n if self.data_format == 'channels_first':\n d_axis, h_axis, w_axis = 2, 3, 4\n else:\n d_axis, h_axis, w_axis = 1, 2, 3\n\n depth = inputs_shape[d_axis]\n height = inputs_shape[h_axis]\n width = inputs_shape[w_axis]\n\n kernel_d, kernel_h, kernel_w = self.kernel_size\n stride_d, stride_h, stride_w = self.strides\n\n if self.output_padding is None:\n out_pad_d = out_pad_h = out_pad_w = None\n else:\n out_pad_d, out_pad_h, out_pad_w = self.output_padding\n\n # Infer the dynamic output shape:\n out_depth = conv_utils.deconv_output_length(depth,\n kernel_d,\n padding=self.padding,\n output_padding=out_pad_d,\n stride=stride_d)\n out_height = conv_utils.deconv_output_length(height,\n kernel_h,\n padding=self.padding,\n output_padding=out_pad_h,\n stride=stride_h)\n out_width = conv_utils.deconv_output_length(width,\n kernel_w,\n padding=self.padding,\n output_padding=out_pad_w,\n stride=stride_w)\n if self.data_format == 'channels_first':\n output_shape = (batch_size, self.filters, out_depth, out_height,\n out_width)\n strides = (1, 1, stride_d, stride_h, stride_w)\n else:\n output_shape = (batch_size, out_depth, out_height, out_width,\n self.filters)\n strides = (1, stride_d, stride_h, stride_w, 1)\n\n output_shape_tensor = array_ops.stack(output_shape)\n outputs = nn.conv3d_transpose(\n inputs,\n self.kernel,\n output_shape_tensor,\n strides,\n data_format=conv_utils.convert_data_format(self.data_format, ndim=5),\n padding=self.padding.upper())\n\n if not context.executing_eagerly():\n # Infer the static output shape:\n out_shape = self.compute_output_shape(inputs.shape)\n outputs.set_shape(out_shape)\n\n if self.use_bias:\n outputs = nn.bias_add(\n outputs,\n self.bias,\n data_format=conv_utils.convert_data_format(self.data_format, ndim=4))\n\n if self.activation is not None:\n return self.activation(outputs)\n return outputs\n\n def compute_output_shape(self, input_shape):\n input_shape = tensor_shape.TensorShape(input_shape).as_list()\n output_shape = list(input_shape)\n if self.data_format == 'channels_first':\n c_axis, d_axis, h_axis, w_axis = 1, 2, 3, 4\n else:\n c_axis, d_axis, h_axis, w_axis = 4, 1, 2, 3\n\n kernel_d, kernel_h, kernel_w = self.kernel_size\n stride_d, stride_h, stride_w = self.strides\n\n if self.output_padding is None:\n out_pad_d = out_pad_h = out_pad_w = None\n else:\n out_pad_d, out_pad_h, out_pad_w = self.output_padding\n\n output_shape[c_axis] = self.filters\n output_shape[d_axis] = conv_utils.deconv_output_length(\n output_shape[d_axis],\n kernel_d,\n padding=self.padding,\n output_padding=out_pad_d,\n stride=stride_d)\n output_shape[h_axis] = conv_utils.deconv_output_length(\n output_shape[h_axis],\n kernel_h,\n padding=self.padding,\n output_padding=out_pad_h,\n stride=stride_h)\n output_shape[w_axis] = conv_utils.deconv_output_length(\n output_shape[w_axis],\n kernel_w,\n padding=self.padding,\n output_padding=out_pad_w,\n stride=stride_w)\n return tensor_shape.TensorShape(output_shape)\n\n def get_config(self):\n config = super(Conv3DTranspose, self).get_config()\n config.pop('dilation_rate')\n config['output_padding'] = self.output_padding\n return config\n\n\nclass SeparableConv(Conv):\n \"\"\"Abstract base layer for separable nD convolution.\n\n This layer performs a depthwise convolution that acts separately on\n channels, followed by a pointwise convolution that mixes channels.\n If `use_bias` is True and a bias initializer is provided,\n it adds a bias vector to the output.\n It then optionally applies an activation function to produce the final output.\n\n Arguments:\n rank: An integer, the rank of the convolution, e.g. \"2\" for 2D convolution.\n filters: Integer, the dimensionality of the output space (i.e. the number\n of filters in the convolution).\n kernel_size: A tuple or list of integers specifying the spatial\n dimensions of the filters. Can be a single integer to specify the same\n value for all spatial dimensions.\n strides: A tuple or list of integers specifying the strides\n of the convolution. Can be a single integer to specify the same value for\n all spatial dimensions.\n Specifying any `stride` value != 1 is incompatible with specifying\n any `dilation_rate` value != 1.\n padding: One of `\"valid\"` or `\"same\"` (case-insensitive).\n data_format: A string, one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch_size, ..., channels)` while `channels_first` corresponds to\n inputs with shape `(batch_size, channels, ...)`.\n dilation_rate: An integer or tuple/list of 2 integers, specifying\n the dilation rate to use for dilated convolution.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n Currently, specifying any `dilation_rate` value != 1 is\n incompatible with specifying any stride value != 1.\n depth_multiplier: The number of depthwise convolution output channels for\n each input channel. The total number of depthwise convolution output\n channels will be equal to `num_filters_in * depth_multiplier`.\n activation: Activation function to use.\n If you don't specify anything, no activation is applied (\n see `keras.activations`).\n use_bias: Boolean, whether the layer uses a bias.\n depthwise_initializer: An initializer for the depthwise convolution kernel.\n pointwise_initializer: An initializer for the pointwise convolution kernel.\n bias_initializer: An initializer for the bias vector. If None, the default\n initializer will be used.\n depthwise_regularizer: Optional regularizer for the depthwise\n convolution kernel.\n pointwise_regularizer: Optional regularizer for the pointwise\n convolution kernel.\n bias_regularizer: Optional regularizer for the bias vector.\n activity_regularizer: Optional regularizer function for the output.\n depthwise_constraint: Optional projection function to be applied to the\n depthwise kernel after being updated by an `Optimizer` (e.g. used for\n norm constraints or value constraints for layer weights). The function\n must take as input the unprojected variable and must return the\n projected variable (which must have the same shape). Constraints are\n not safe to use when doing asynchronous distributed training.\n pointwise_constraint: Optional projection function to be applied to the\n pointwise kernel after being updated by an `Optimizer`.\n bias_constraint: Optional projection function to be applied to the\n bias after being updated by an `Optimizer`.\n trainable: Boolean, if `True` the weights of this layer will be marked as\n trainable (and listed in `layer.trainable_weights`).\n name: A string, the name of the layer.\n \"\"\"\n\n def __init__(self,\n rank,\n filters,\n kernel_size,\n strides=1,\n padding='valid',\n data_format=None,\n dilation_rate=1,\n depth_multiplier=1,\n activation=None,\n use_bias=True,\n depthwise_initializer='glorot_uniform',\n pointwise_initializer='glorot_uniform',\n bias_initializer='zeros',\n depthwise_regularizer=None,\n pointwise_regularizer=None,\n bias_regularizer=None,\n activity_regularizer=None,\n depthwise_constraint=None,\n pointwise_constraint=None,\n bias_constraint=None,\n trainable=True,\n name=None,\n **kwargs):\n super(SeparableConv, self).__init__(\n rank=rank,\n filters=filters,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n data_format=data_format,\n dilation_rate=dilation_rate,\n activation=activations.get(activation),\n use_bias=use_bias,\n bias_initializer=initializers.get(bias_initializer),\n bias_regularizer=regularizers.get(bias_regularizer),\n activity_regularizer=regularizers.get(activity_regularizer),\n bias_constraint=bias_constraint,\n trainable=trainable,\n name=name,\n **kwargs)\n self.depth_multiplier = depth_multiplier\n self.depthwise_initializer = initializers.get(depthwise_initializer)\n self.pointwise_initializer = initializers.get(pointwise_initializer)\n self.depthwise_regularizer = regularizers.get(depthwise_regularizer)\n self.pointwise_regularizer = regularizers.get(pointwise_regularizer)\n self.depthwise_constraint = constraints.get(depthwise_constraint)\n self.pointwise_constraint = constraints.get(pointwise_constraint)\n\n def build(self, input_shape):\n input_shape = tensor_shape.TensorShape(input_shape)\n channel_axis = self._get_channel_axis()\n if input_shape.dims[channel_axis].value is None:\n raise ValueError('The channel dimension of the inputs '\n 'should be defined. Found `None`.')\n input_dim = int(input_shape[channel_axis])\n self.input_spec = InputSpec(ndim=self.rank + 2,\n axes={channel_axis: input_dim})\n depthwise_kernel_shape = self.kernel_size + (input_dim,\n self.depth_multiplier)\n pointwise_kernel_shape = (\n 1,) * self.rank + (self.depth_multiplier * input_dim, self.filters)\n\n self.depthwise_kernel = self.add_weight(\n name='depthwise_kernel',\n shape=depthwise_kernel_shape,\n initializer=self.depthwise_initializer,\n regularizer=self.depthwise_regularizer,\n constraint=self.depthwise_constraint,\n trainable=True,\n dtype=self.dtype)\n self.pointwise_kernel = self.add_weight(\n name='pointwise_kernel',\n shape=pointwise_kernel_shape,\n initializer=self.pointwise_initializer,\n regularizer=self.pointwise_regularizer,\n constraint=self.pointwise_constraint,\n trainable=True,\n dtype=self.dtype)\n if self.use_bias:\n self.bias = self.add_weight(\n name='bias',\n shape=(self.filters,),\n initializer=self.bias_initializer,\n regularizer=self.bias_regularizer,\n constraint=self.bias_constraint,\n trainable=True,\n dtype=self.dtype)\n else:\n self.bias = None\n self.built = True\n\n def call(self, inputs):\n raise NotImplementedError\n\n def get_config(self):\n config = {\n 'filters':\n self.filters,\n 'kernel_size':\n self.kernel_size,\n 'strides':\n self.strides,\n 'padding':\n self.padding,\n 'data_format':\n self.data_format,\n 'depth_multiplier':\n self.depth_multiplier,\n 'dilation_rate':\n self.dilation_rate,\n 'activation':\n activations.serialize(self.activation),\n 'use_bias':\n self.use_bias,\n 'depthwise_initializer':\n initializers.serialize(self.depthwise_initializer),\n 'pointwise_initializer':\n initializers.serialize(self.pointwise_initializer),\n 'bias_initializer':\n initializers.serialize(self.bias_initializer),\n 'depthwise_regularizer':\n regularizers.serialize(self.depthwise_regularizer),\n 'pointwise_regularizer':\n regularizers.serialize(self.pointwise_regularizer),\n 'bias_regularizer':\n regularizers.serialize(self.bias_regularizer),\n 'activity_regularizer':\n regularizers.serialize(self.activity_regularizer),\n 'depthwise_constraint':\n constraints.serialize(self.depthwise_constraint),\n 'pointwise_constraint':\n constraints.serialize(self.pointwise_constraint),\n 'bias_constraint':\n constraints.serialize(self.bias_constraint)\n }\n base_config = super(SeparableConv, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@keras_export('keras.layers.SeparableConv1D',\n 'keras.layers.SeparableConvolution1D')\nclass SeparableConv1D(SeparableConv):\n \"\"\"Depthwise separable 1D convolution.\n\n This layer performs a depthwise convolution that acts separately on\n channels, followed by a pointwise convolution that mixes channels.\n If `use_bias` is True and a bias initializer is provided,\n it adds a bias vector to the output.\n It then optionally applies an activation function to produce the final output.\n\n Arguments:\n filters: Integer, the dimensionality of the output space (i.e. the number\n of filters in the convolution).\n kernel_size: A single integer specifying the spatial\n dimensions of the filters.\n strides: A single integer specifying the strides\n of the convolution.\n Specifying any `stride` value != 1 is incompatible with specifying\n any `dilation_rate` value != 1.\n padding: One of `\"valid\"`, `\"same\"`, or `\"causal\"` (case-insensitive).\n data_format: A string, one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch_size, length, channels)` while `channels_first` corresponds to\n inputs with shape `(batch_size, channels, length)`.\n dilation_rate: A single integer, specifying\n the dilation rate to use for dilated convolution.\n Currently, specifying any `dilation_rate` value != 1 is\n incompatible with specifying any stride value != 1.\n depth_multiplier: The number of depthwise convolution output channels for\n each input channel. The total number of depthwise convolution output\n channels will be equal to `num_filters_in * depth_multiplier`.\n activation: Activation function to use.\n If you don't specify anything, no activation is applied (\n see `keras.activations`).\n use_bias: Boolean, whether the layer uses a bias.\n depthwise_initializer: An initializer for the depthwise convolution kernel (\n see `keras.initializers`).\n pointwise_initializer: An initializer for the pointwise convolution kernel (\n see `keras.initializers`).\n bias_initializer: An initializer for the bias vector. If None, the default\n initializer will be used (see `keras.initializers`).\n depthwise_regularizer: Optional regularizer for the depthwise\n convolution kernel (see `keras.regularizers`).\n pointwise_regularizer: Optional regularizer for the pointwise\n convolution kernel (see `keras.regularizers`).\n bias_regularizer: Optional regularizer for the bias vector (\n see `keras.regularizers`).\n activity_regularizer: Optional regularizer function for the output (\n see `keras.regularizers`).\n depthwise_constraint: Optional projection function to be applied to the\n depthwise kernel after being updated by an `Optimizer` (e.g. used for\n norm constraints or value constraints for layer weights). The function\n must take as input the unprojected variable and must return the\n projected variable (which must have the same shape). Constraints are\n not safe to use when doing asynchronous distributed training (\n see `keras.constraints`).\n pointwise_constraint: Optional projection function to be applied to the\n pointwise kernel after being updated by an `Optimizer` (\n see `keras.constraints`).\n bias_constraint: Optional projection function to be applied to the\n bias after being updated by an `Optimizer` (\n see `keras.constraints`).\n trainable: Boolean, if `True` the weights of this layer will be marked as\n trainable (and listed in `layer.trainable_weights`).\n name: A string, the name of the layer.\n\n Input shape:\n 3D tensor with shape:\n `(batch_size, channels, steps)` if data_format='channels_first'\n or 5D tensor with shape:\n `(batch_size, steps, channels)` if data_format='channels_last'.\n\n Output shape:\n 3D tensor with shape:\n `(batch_size, filters, new_steps)` if data_format='channels_first'\n or 3D tensor with shape:\n `(batch_size, new_steps, filters)` if data_format='channels_last'.\n `new_steps` value might have changed due to padding or strides.\n\n Returns:\n A tensor of rank 3 representing\n `activation(separableconv1d(inputs, kernel) + bias)`.\n\n Raises:\n ValueError: when both `strides` > 1 and `dilation_rate` > 1.\n \"\"\"\n\n def __init__(self,\n filters,\n kernel_size,\n strides=1,\n padding='valid',\n data_format=None,\n dilation_rate=1,\n depth_multiplier=1,\n activation=None,\n use_bias=True,\n depthwise_initializer='glorot_uniform',\n pointwise_initializer='glorot_uniform',\n bias_initializer='zeros',\n depthwise_regularizer=None,\n pointwise_regularizer=None,\n bias_regularizer=None,\n activity_regularizer=None,\n depthwise_constraint=None,\n pointwise_constraint=None,\n bias_constraint=None,\n **kwargs):\n super(SeparableConv1D, self).__init__(\n rank=1,\n filters=filters,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n data_format=data_format,\n dilation_rate=dilation_rate,\n depth_multiplier=depth_multiplier,\n activation=activations.get(activation),\n use_bias=use_bias,\n depthwise_initializer=initializers.get(depthwise_initializer),\n pointwise_initializer=initializers.get(pointwise_initializer),\n bias_initializer=initializers.get(bias_initializer),\n depthwise_regularizer=regularizers.get(depthwise_regularizer),\n pointwise_regularizer=regularizers.get(pointwise_regularizer),\n bias_regularizer=regularizers.get(bias_regularizer),\n activity_regularizer=regularizers.get(activity_regularizer),\n depthwise_constraint=constraints.get(depthwise_constraint),\n pointwise_constraint=constraints.get(pointwise_constraint),\n bias_constraint=constraints.get(bias_constraint),\n **kwargs)\n\n def call(self, inputs):\n if self.padding == 'causal':\n inputs = array_ops.pad(inputs, self._compute_causal_padding())\n if self.data_format == 'channels_last':\n strides = (1,) + self.strides * 2 + (1,)\n spatial_start_dim = 1\n else:\n strides = (1, 1) + self.strides * 2\n spatial_start_dim = 2\n\n # Explicitly broadcast inputs and kernels to 4D.\n # TODO(fchollet): refactor when a native separable_conv1d op is available.\n inputs = array_ops.expand_dims(inputs, spatial_start_dim)\n depthwise_kernel = array_ops.expand_dims(self.depthwise_kernel, 0)\n pointwise_kernel = array_ops.expand_dims(self.pointwise_kernel, 0)\n dilation_rate = (1,) + self.dilation_rate\n\n if self.padding == 'causal':\n op_padding = 'valid'\n else:\n op_padding = self.padding\n outputs = nn.separable_conv2d(\n inputs,\n depthwise_kernel,\n pointwise_kernel,\n strides=strides,\n padding=op_padding.upper(),\n rate=dilation_rate,\n data_format=conv_utils.convert_data_format(self.data_format, ndim=4))\n\n if self.use_bias:\n outputs = nn.bias_add(\n outputs,\n self.bias,\n data_format=conv_utils.convert_data_format(self.data_format, ndim=4))\n\n outputs = array_ops.squeeze(outputs, [spatial_start_dim])\n\n if self.activation is not None:\n return self.activation(outputs)\n return outputs\n\n\n@keras_export('keras.layers.SeparableConv2D',\n 'keras.layers.SeparableConvolution2D')\nclass SeparableConv2D(SeparableConv):\n \"\"\"Depthwise separable 2D convolution.\n\n Separable convolutions consist of first performing\n a depthwise spatial convolution\n (which acts on each input channel separately)\n followed by a pointwise convolution which mixes the resulting\n output channels. The `depth_multiplier` argument controls how many\n output channels are generated per input channel in the depthwise step.\n\n Intuitively, separable convolutions can be understood as\n a way to factorize a convolution kernel into two smaller kernels,\n or as an extreme version of an Inception block.\n\n Arguments:\n filters: Integer, the dimensionality of the output space\n (i.e. the number of output filters in the convolution).\n kernel_size: An integer or tuple/list of 2 integers, specifying the\n height and width of the 2D convolution window.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n strides: An integer or tuple/list of 2 integers,\n specifying the strides of the convolution along the height and width.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n Specifying any stride value != 1 is incompatible with specifying\n any `dilation_rate` value != 1.\n padding: one of `\"valid\"` or `\"same\"` (case-insensitive).\n data_format: A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch_size, height, width, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch_size, channels, height, width)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".\n dilation_rate: An integer or tuple/list of 2 integers, specifying\n the dilation rate to use for dilated convolution.\n Currently, specifying any `dilation_rate` value != 1 is\n incompatible with specifying any `strides` value != 1.\n depth_multiplier: The number of depthwise convolution output channels\n for each input channel.\n The total number of depthwise convolution output\n channels will be equal to `filters_in * depth_multiplier`.\n activation: Activation function to use.\n If you don't specify anything, no activation is applied (\n see `keras.activations`).\n use_bias: Boolean, whether the layer uses a bias vector.\n depthwise_initializer: Initializer for the depthwise kernel matrix (\n see `keras.initializers`).\n pointwise_initializer: Initializer for the pointwise kernel matrix (\n see `keras.initializers`).\n bias_initializer: Initializer for the bias vector (\n see `keras.initializers`).\n depthwise_regularizer: Regularizer function applied to\n the depthwise kernel matrix (see `keras.regularizers`).\n pointwise_regularizer: Regularizer function applied to\n the pointwise kernel matrix (see `keras.regularizers`).\n bias_regularizer: Regularizer function applied to the bias vector (\n see `keras.regularizers`).\n activity_regularizer: Regularizer function applied to\n the output of the layer (its \"activation\") (\n see `keras.regularizers`).\n depthwise_constraint: Constraint function applied to\n the depthwise kernel matrix (\n see `keras.constraints`).\n pointwise_constraint: Constraint function applied to\n the pointwise kernel matrix (\n see `keras.constraints`).\n bias_constraint: Constraint function applied to the bias vector (\n see `keras.constraints`).\n\n Input shape:\n 4D tensor with shape:\n `(batch_size, channels, rows, cols)` if data_format='channels_first'\n or 4D tensor with shape:\n `(batch_size, rows, cols, channels)` if data_format='channels_last'.\n\n Output shape:\n 4D tensor with shape:\n `(batch_size, filters, new_rows, new_cols)` if data_format='channels_first'\n or 4D tensor with shape:\n `(batch_size, new_rows, new_cols, filters)` if data_format='channels_last'.\n `rows` and `cols` values might have changed due to padding.\n\n Returns:\n A tensor of rank 4 representing\n `activation(separableconv2d(inputs, kernel) + bias)`.\n\n Raises:\n ValueError: if `padding` is \"causal\".\n ValueError: when both `strides` > 1 and `dilation_rate` > 1.\n \"\"\"\n\n def __init__(self,\n filters,\n kernel_size,\n strides=(1, 1),\n padding='valid',\n data_format=None,\n dilation_rate=(1, 1),\n depth_multiplier=1,\n activation=None,\n use_bias=True,\n depthwise_initializer='glorot_uniform',\n pointwise_initializer='glorot_uniform',\n bias_initializer='zeros',\n depthwise_regularizer=None,\n pointwise_regularizer=None,\n bias_regularizer=None,\n activity_regularizer=None,\n depthwise_constraint=None,\n pointwise_constraint=None,\n bias_constraint=None,\n **kwargs):\n super(SeparableConv2D, self).__init__(\n rank=2,\n filters=filters,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n data_format=data_format,\n dilation_rate=dilation_rate,\n depth_multiplier=depth_multiplier,\n activation=activations.get(activation),\n use_bias=use_bias,\n depthwise_initializer=initializers.get(depthwise_initializer),\n pointwise_initializer=initializers.get(pointwise_initializer),\n bias_initializer=initializers.get(bias_initializer),\n depthwise_regularizer=regularizers.get(depthwise_regularizer),\n pointwise_regularizer=regularizers.get(pointwise_regularizer),\n bias_regularizer=regularizers.get(bias_regularizer),\n activity_regularizer=regularizers.get(activity_regularizer),\n depthwise_constraint=constraints.get(depthwise_constraint),\n pointwise_constraint=constraints.get(pointwise_constraint),\n bias_constraint=constraints.get(bias_constraint),\n **kwargs)\n\n def call(self, inputs):\n # Apply the actual ops.\n if self.data_format == 'channels_last':\n strides = (1,) + self.strides + (1,)\n else:\n strides = (1, 1) + self.strides\n outputs = nn.separable_conv2d(\n inputs,\n self.depthwise_kernel,\n self.pointwise_kernel,\n strides=strides,\n padding=self.padding.upper(),\n rate=self.dilation_rate,\n data_format=conv_utils.convert_data_format(self.data_format, ndim=4))\n\n if self.use_bias:\n outputs = nn.bias_add(\n outputs,\n self.bias,\n data_format=conv_utils.convert_data_format(self.data_format, ndim=4))\n\n if self.activation is not None:\n return self.activation(outputs)\n return outputs\n\n\n@keras_export('keras.layers.DepthwiseConv2D')\nclass DepthwiseConv2D(Conv2D):\n \"\"\"Depthwise separable 2D convolution.\n\n Depthwise Separable convolutions consist of performing\n just the first step in a depthwise spatial convolution\n (which acts on each input channel separately).\n The `depth_multiplier` argument controls how many\n output channels are generated per input channel in the depthwise step.\n\n Arguments:\n kernel_size: An integer or tuple/list of 2 integers, specifying the\n height and width of the 2D convolution window.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n strides: An integer or tuple/list of 2 integers,\n specifying the strides of the convolution along the height and width.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n Specifying any stride value != 1 is incompatible with specifying\n any `dilation_rate` value != 1.\n padding: one of `'valid'` or `'same'` (case-insensitive).\n depth_multiplier: The number of depthwise convolution output channels\n for each input channel.\n The total number of depthwise convolution output\n channels will be equal to `filters_in * depth_multiplier`.\n data_format: A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch_size, height, width, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch_size, channels, height, width)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be 'channels_last'.\n dilation_rate: An integer or tuple/list of 2 integers, specifying\n the dilation rate to use for dilated convolution.\n Currently, specifying any `dilation_rate` value != 1 is\n incompatible with specifying any `strides` value != 1.\n activation: Activation function to use.\n If you don't specify anything, no activation is applied (\n see `keras.activations`).\n use_bias: Boolean, whether the layer uses a bias vector.\n depthwise_initializer: Initializer for the depthwise kernel matrix (\n see `keras.initializers`).\n bias_initializer: Initializer for the bias vector (\n see `keras.initializers`).\n depthwise_regularizer: Regularizer function applied to\n the depthwise kernel matrix (see `keras.regularizers`).\n bias_regularizer: Regularizer function applied to the bias vector (\n see `keras.regularizers`).\n activity_regularizer: Regularizer function applied to\n the output of the layer (its 'activation') (\n see `keras.regularizers`).\n depthwise_constraint: Constraint function applied to\n the depthwise kernel matrix (\n see `keras.constraints`).\n bias_constraint: Constraint function applied to the bias vector (\n see `keras.constraints`).\n\n Input shape:\n 4D tensor with shape:\n `[batch_size, channels, rows, cols]` if data_format='channels_first'\n or 4D tensor with shape:\n `[batch_size, rows, cols, channels]` if data_format='channels_last'.\n\n Output shape:\n 4D tensor with shape:\n `[batch_size, filters, new_rows, new_cols]` if data_format='channels_first'\n or 4D tensor with shape:\n `[batch_size, new_rows, new_cols, filters]` if data_format='channels_last'.\n `rows` and `cols` values might have changed due to padding.\n\n Returns:\n A tensor of rank 4 representing\n `activation(depthwiseconv2d(inputs, kernel) + bias)`.\n\n Raises:\n ValueError: if `padding` is \"causal\".\n ValueError: when both `strides` > 1 and `dilation_rate` > 1.\n \"\"\"\n\n def __init__(self,\n kernel_size,\n strides=(1, 1),\n padding='valid',\n depth_multiplier=1,\n data_format=None,\n dilation_rate=(1, 1),\n activation=None,\n use_bias=True,\n depthwise_initializer='glorot_uniform',\n bias_initializer='zeros',\n depthwise_regularizer=None,\n bias_regularizer=None,\n activity_regularizer=None,\n depthwise_constraint=None,\n bias_constraint=None,\n **kwargs):\n super(DepthwiseConv2D, self).__init__(\n filters=None,\n kernel_size=kernel_size,\n strides=strides,\n padding=padding,\n data_format=data_format,\n dilation_rate=dilation_rate,\n activation=activation,\n use_bias=use_bias,\n bias_regularizer=bias_regularizer,\n activity_regularizer=activity_regularizer,\n bias_constraint=bias_constraint,\n **kwargs)\n self.depth_multiplier = depth_multiplier\n self.depthwise_initializer = initializers.get(depthwise_initializer)\n self.depthwise_regularizer = regularizers.get(depthwise_regularizer)\n self.depthwise_constraint = constraints.get(depthwise_constraint)\n self.bias_initializer = initializers.get(bias_initializer)\n\n def build(self, input_shape):\n if len(input_shape) < 4:\n raise ValueError('Inputs to `DepthwiseConv2D` should have rank 4. '\n 'Received input shape:', str(input_shape))\n input_shape = tensor_shape.TensorShape(input_shape)\n channel_axis = self._get_channel_axis()\n if input_shape.dims[channel_axis].value is None:\n raise ValueError('The channel dimension of the inputs to '\n '`DepthwiseConv2D` '\n 'should be defined. Found `None`.')\n input_dim = int(input_shape[channel_axis])\n depthwise_kernel_shape = (self.kernel_size[0],\n self.kernel_size[1],\n input_dim,\n self.depth_multiplier)\n\n self.depthwise_kernel = self.add_weight(\n shape=depthwise_kernel_shape,\n initializer=self.depthwise_initializer,\n name='depthwise_kernel',\n regularizer=self.depthwise_regularizer,\n constraint=self.depthwise_constraint)\n\n if self.use_bias:\n self.bias = self.add_weight(shape=(input_dim * self.depth_multiplier,),\n initializer=self.bias_initializer,\n name='bias',\n regularizer=self.bias_regularizer,\n constraint=self.bias_constraint)\n else:\n self.bias = None\n # Set input spec.\n self.input_spec = InputSpec(ndim=4, axes={channel_axis: input_dim})\n self.built = True\n\n def call(self, inputs):\n outputs = backend.depthwise_conv2d(\n inputs,\n self.depthwise_kernel,\n strides=self.strides,\n padding=self.padding,\n dilation_rate=self.dilation_rate,\n data_format=self.data_format)\n\n if self.use_bias:\n outputs = backend.bias_add(\n outputs,\n self.bias,\n data_format=self.data_format)\n\n if self.activation is not None:\n return self.activation(outputs)\n\n return outputs\n\n @tf_utils.shape_type_conversion\n def compute_output_shape(self, input_shape):\n if self.data_format == 'channels_first':\n rows = input_shape[2]\n cols = input_shape[3]\n out_filters = input_shape[1] * self.depth_multiplier\n elif self.data_format == 'channels_last':\n rows = input_shape[1]\n cols = input_shape[2]\n out_filters = input_shape[3] * self.depth_multiplier\n\n rows = conv_utils.conv_output_length(rows, self.kernel_size[0],\n self.padding,\n self.strides[0],\n self.dilation_rate[0])\n cols = conv_utils.conv_output_length(cols, self.kernel_size[1],\n self.padding,\n self.strides[1],\n self.dilation_rate[1])\n if self.data_format == 'channels_first':\n return (input_shape[0], out_filters, rows, cols)\n elif self.data_format == 'channels_last':\n return (input_shape[0], rows, cols, out_filters)\n\n def get_config(self):\n config = super(DepthwiseConv2D, self).get_config()\n config.pop('filters')\n config.pop('kernel_initializer')\n config.pop('kernel_regularizer')\n config.pop('kernel_constraint')\n config['depth_multiplier'] = self.depth_multiplier\n config['depthwise_initializer'] = initializers.serialize(\n self.depthwise_initializer)\n config['depthwise_regularizer'] = regularizers.serialize(\n self.depthwise_regularizer)\n config['depthwise_constraint'] = constraints.serialize(\n self.depthwise_constraint)\n return config\n\n\n@keras_export('keras.layers.UpSampling1D')\nclass UpSampling1D(Layer):\n \"\"\"Upsampling layer for 1D inputs.\n\n Repeats each temporal step `size` times along the time axis.\n\n Examples:\n\n >>> input_shape = (2, 2, 3)\n >>> x = np.arange(np.prod(input_shape)).reshape(input_shape)\n >>> print(x)\n [[[ 0 1 2]\n [ 3 4 5]]\n [[ 6 7 8]\n [ 9 10 11]]]\n >>> y = tf.keras.layers.UpSampling1D(size=2)(x)\n >>> print(y)\n tf.Tensor(\n [[[ 0 1 2]\n [ 0 1 2]\n [ 3 4 5]\n [ 3 4 5]]\n [[ 6 7 8]\n [ 6 7 8]\n [ 9 10 11]\n [ 9 10 11]]], shape=(2, 4, 3), dtype=int64)\n\n Arguments:\n size: Integer. Upsampling factor.\n\n Input shape:\n 3D tensor with shape: `(batch_size, steps, features)`.\n\n Output shape:\n 3D tensor with shape: `(batch_size, upsampled_steps, features)`.\n \"\"\"\n\n def __init__(self, size=2, **kwargs):\n super(UpSampling1D, self).__init__(**kwargs)\n self.size = int(size)\n self.input_spec = InputSpec(ndim=3)\n\n def compute_output_shape(self, input_shape):\n input_shape = tensor_shape.TensorShape(input_shape).as_list()\n size = self.size * input_shape[1] if input_shape[1] is not None else None\n return tensor_shape.TensorShape([input_shape[0], size, input_shape[2]])\n\n def call(self, inputs):\n output = backend.repeat_elements(inputs, self.size, axis=1)\n return output\n\n def get_config(self):\n config = {'size': self.size}\n base_config = super(UpSampling1D, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@keras_export('keras.layers.UpSampling2D')\nclass UpSampling2D(Layer):\n \"\"\"Upsampling layer for 2D inputs.\n\n Repeats the rows and columns of the data\n by `size[0]` and `size[1]` respectively.\n\n Examples:\n\n >>> input_shape = (2, 2, 1, 3)\n >>> x = np.arange(np.prod(input_shape)).reshape(input_shape)\n >>> print(x)\n [[[[ 0 1 2]]\n [[ 3 4 5]]]\n [[[ 6 7 8]]\n [[ 9 10 11]]]]\n >>> y = tf.keras.layers.UpSampling2D(size=(1, 2))(x)\n >>> print(y)\n tf.Tensor(\n [[[[ 0 1 2]\n [ 0 1 2]]\n [[ 3 4 5]\n [ 3 4 5]]]\n [[[ 6 7 8]\n [ 6 7 8]]\n [[ 9 10 11]\n [ 9 10 11]]]], shape=(2, 2, 2, 3), dtype=int64)\n\n Arguments:\n size: Int, or tuple of 2 integers.\n The upsampling factors for rows and columns.\n data_format: A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch_size, height, width, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch_size, channels, height, width)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".\n interpolation: A string, one of `nearest` or `bilinear`.\n\n Input shape:\n 4D tensor with shape:\n - If `data_format` is `\"channels_last\"`:\n `(batch_size, rows, cols, channels)`\n - If `data_format` is `\"channels_first\"`:\n `(batch_size, channels, rows, cols)`\n\n Output shape:\n 4D tensor with shape:\n - If `data_format` is `\"channels_last\"`:\n `(batch_size, upsampled_rows, upsampled_cols, channels)`\n - If `data_format` is `\"channels_first\"`:\n `(batch_size, channels, upsampled_rows, upsampled_cols)`\n \"\"\"\n\n def __init__(self,\n size=(2, 2),\n data_format=None,\n interpolation='nearest',\n **kwargs):\n super(UpSampling2D, self).__init__(**kwargs)\n self.data_format = conv_utils.normalize_data_format(data_format)\n self.size = conv_utils.normalize_tuple(size, 2, 'size')\n if interpolation not in {'nearest', 'bilinear'}:\n raise ValueError('`interpolation` argument should be one of `\"nearest\"` '\n 'or `\"bilinear\"`.')\n self.interpolation = interpolation\n self.input_spec = InputSpec(ndim=4)\n\n def compute_output_shape(self, input_shape):\n input_shape = tensor_shape.TensorShape(input_shape).as_list()\n if self.data_format == 'channels_first':\n height = self.size[0] * input_shape[\n 2] if input_shape[2] is not None else None\n width = self.size[1] * input_shape[\n 3] if input_shape[3] is not None else None\n return tensor_shape.TensorShape(\n [input_shape[0], input_shape[1], height, width])\n else:\n height = self.size[0] * input_shape[\n 1] if input_shape[1] is not None else None\n width = self.size[1] * input_shape[\n 2] if input_shape[2] is not None else None\n return tensor_shape.TensorShape(\n [input_shape[0], height, width, input_shape[3]])\n\n def call(self, inputs):\n return backend.resize_images(\n inputs, self.size[0], self.size[1], self.data_format,\n interpolation=self.interpolation)\n\n def get_config(self):\n config = {\n 'size': self.size,\n 'data_format': self.data_format,\n 'interpolation': self.interpolation\n }\n base_config = super(UpSampling2D, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@keras_export('keras.layers.UpSampling3D')\nclass UpSampling3D(Layer):\n \"\"\"Upsampling layer for 3D inputs.\n\n Repeats the 1st, 2nd and 3rd dimensions\n of the data by `size[0]`, `size[1]` and `size[2]` respectively.\n\n Examples:\n\n >>> input_shape = (2, 1, 2, 1, 3)\n >>> x = tf.constant(1, shape=input_shape)\n >>> y = tf.keras.layers.UpSampling3D(size=2)(x)\n >>> print(y.shape)\n (2, 2, 4, 2, 3)\n\n Arguments:\n size: Int, or tuple of 3 integers.\n The upsampling factors for dim1, dim2 and dim3.\n data_format: A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch_size, spatial_dim1, spatial_dim2, spatial_dim3, channels)`\n while `channels_first` corresponds to inputs with shape\n `(batch_size, channels, spatial_dim1, spatial_dim2, spatial_dim3)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".\n\n Input shape:\n 5D tensor with shape:\n - If `data_format` is `\"channels_last\"`:\n `(batch_size, dim1, dim2, dim3, channels)`\n - If `data_format` is `\"channels_first\"`:\n `(batch_size, channels, dim1, dim2, dim3)`\n\n Output shape:\n 5D tensor with shape:\n - If `data_format` is `\"channels_last\"`:\n `(batch_size, upsampled_dim1, upsampled_dim2, upsampled_dim3, channels)`\n - If `data_format` is `\"channels_first\"`:\n `(batch_size, channels, upsampled_dim1, upsampled_dim2, upsampled_dim3)`\n \"\"\"\n\n def __init__(self, size=(2, 2, 2), data_format=None, **kwargs):\n self.data_format = conv_utils.normalize_data_format(data_format)\n self.size = conv_utils.normalize_tuple(size, 3, 'size')\n self.input_spec = InputSpec(ndim=5)\n super(UpSampling3D, self).__init__(**kwargs)\n\n def compute_output_shape(self, input_shape):\n input_shape = tensor_shape.TensorShape(input_shape).as_list()\n if self.data_format == 'channels_first':\n dim1 = self.size[0] * input_shape[\n 2] if input_shape[2] is not None else None\n dim2 = self.size[1] * input_shape[\n 3] if input_shape[3] is not None else None\n dim3 = self.size[2] * input_shape[\n 4] if input_shape[4] is not None else None\n return tensor_shape.TensorShape(\n [input_shape[0], input_shape[1], dim1, dim2, dim3])\n else:\n dim1 = self.size[0] * input_shape[\n 1] if input_shape[1] is not None else None\n dim2 = self.size[1] * input_shape[\n 2] if input_shape[2] is not None else None\n dim3 = self.size[2] * input_shape[\n 3] if input_shape[3] is not None else None\n return tensor_shape.TensorShape(\n [input_shape[0], dim1, dim2, dim3, input_shape[4]])\n\n def call(self, inputs):\n return backend.resize_volumes(\n inputs, self.size[0], self.size[1], self.size[2], self.data_format)\n\n def get_config(self):\n config = {'size': self.size, 'data_format': self.data_format}\n base_config = super(UpSampling3D, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@keras_export('keras.layers.ZeroPadding1D')\nclass ZeroPadding1D(Layer):\n \"\"\"Zero-padding layer for 1D input (e.g. temporal sequence).\n\n Examples:\n\n >>> input_shape = (2, 2, 3)\n >>> x = np.arange(np.prod(input_shape)).reshape(input_shape)\n >>> print(x)\n [[[ 0 1 2]\n [ 3 4 5]]\n [[ 6 7 8]\n [ 9 10 11]]]\n >>> y = tf.keras.layers.ZeroPadding1D(padding=2)(x)\n >>> print(y)\n tf.Tensor(\n [[[ 0 0 0]\n [ 0 0 0]\n [ 0 1 2]\n [ 3 4 5]\n [ 0 0 0]\n [ 0 0 0]]\n [[ 0 0 0]\n [ 0 0 0]\n [ 6 7 8]\n [ 9 10 11]\n [ 0 0 0]\n [ 0 0 0]]], shape=(2, 6, 3), dtype=int64)\n\n Arguments:\n padding: Int, or tuple of int (length 2), or dictionary.\n - If int:\n How many zeros to add at the beginning and end of\n the padding dimension (axis 1).\n - If tuple of int (length 2):\n How many zeros to add at the beginning and the end of\n the padding dimension (`(left_pad, right_pad)`).\n\n Input shape:\n 3D tensor with shape `(batch_size, axis_to_pad, features)`\n\n Output shape:\n 3D tensor with shape `(batch_size, padded_axis, features)`\n \"\"\"\n\n def __init__(self, padding=1, **kwargs):\n super(ZeroPadding1D, self).__init__(**kwargs)\n self.padding = conv_utils.normalize_tuple(padding, 2, 'padding')\n self.input_spec = InputSpec(ndim=3)\n\n def compute_output_shape(self, input_shape):\n if input_shape[1] is not None:\n length = input_shape[1] + self.padding[0] + self.padding[1]\n else:\n length = None\n return tensor_shape.TensorShape([input_shape[0], length, input_shape[2]])\n\n def call(self, inputs):\n return backend.temporal_padding(inputs, padding=self.padding)\n\n def get_config(self):\n config = {'padding': self.padding}\n base_config = super(ZeroPadding1D, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@keras_export('keras.layers.ZeroPadding2D')\nclass ZeroPadding2D(Layer):\n \"\"\"Zero-padding layer for 2D input (e.g. picture).\n\n This layer can add rows and columns of zeros\n at the top, bottom, left and right side of an image tensor.\n\n Examples:\n\n >>> input_shape = (1, 1, 2, 2)\n >>> x = np.arange(np.prod(input_shape)).reshape(input_shape)\n >>> print(x)\n [[[[0 1]\n [2 3]]]]\n >>> y = tf.keras.layers.ZeroPadding2D(padding=1)(x)\n >>> print(y)\n tf.Tensor(\n [[[[0 0]\n [0 0]\n [0 0]\n [0 0]]\n [[0 0]\n [0 1]\n [2 3]\n [0 0]]\n [[0 0]\n [0 0]\n [0 0]\n [0 0]]]], shape=(1, 3, 4, 2), dtype=int64)\n\n Arguments:\n padding: Int, or tuple of 2 ints, or tuple of 2 tuples of 2 ints.\n - If int: the same symmetric padding\n is applied to height and width.\n - If tuple of 2 ints:\n interpreted as two different\n symmetric padding values for height and width:\n `(symmetric_height_pad, symmetric_width_pad)`.\n - If tuple of 2 tuples of 2 ints:\n interpreted as\n `((top_pad, bottom_pad), (left_pad, right_pad))`\n data_format: A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch_size, height, width, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch_size, channels, height, width)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".\n\n Input shape:\n 4D tensor with shape:\n - If `data_format` is `\"channels_last\"`:\n `(batch_size, rows, cols, channels)`\n - If `data_format` is `\"channels_first\"`:\n `(batch_size, channels, rows, cols)`\n\n Output shape:\n 4D tensor with shape:\n - If `data_format` is `\"channels_last\"`:\n `(batch_size, padded_rows, padded_cols, channels)`\n - If `data_format` is `\"channels_first\"`:\n `(batch_size, channels, padded_rows, padded_cols)`\n \"\"\"\n\n def __init__(self, padding=(1, 1), data_format=None, **kwargs):\n super(ZeroPadding2D, self).__init__(**kwargs)\n self.data_format = conv_utils.normalize_data_format(data_format)\n if isinstance(padding, int):\n self.padding = ((padding, padding), (padding, padding))\n elif hasattr(padding, '__len__'):\n if len(padding) != 2:\n raise ValueError('`padding` should have two elements. '\n 'Found: ' + str(padding))\n height_padding = conv_utils.normalize_tuple(padding[0], 2,\n '1st entry of padding')\n width_padding = conv_utils.normalize_tuple(padding[1], 2,\n '2nd entry of padding')\n self.padding = (height_padding, width_padding)\n else:\n raise ValueError('`padding` should be either an int, '\n 'a tuple of 2 ints '\n '(symmetric_height_pad, symmetric_width_pad), '\n 'or a tuple of 2 tuples of 2 ints '\n '((top_pad, bottom_pad), (left_pad, right_pad)). '\n 'Found: ' + str(padding))\n self.input_spec = InputSpec(ndim=4)\n\n def compute_output_shape(self, input_shape):\n input_shape = tensor_shape.TensorShape(input_shape).as_list()\n if self.data_format == 'channels_first':\n if input_shape[2] is not None:\n rows = input_shape[2] + self.padding[0][0] + self.padding[0][1]\n else:\n rows = None\n if input_shape[3] is not None:\n cols = input_shape[3] + self.padding[1][0] + self.padding[1][1]\n else:\n cols = None\n return tensor_shape.TensorShape(\n [input_shape[0], input_shape[1], rows, cols])\n elif self.data_format == 'channels_last':\n if input_shape[1] is not None:\n rows = input_shape[1] + self.padding[0][0] + self.padding[0][1]\n else:\n rows = None\n if input_shape[2] is not None:\n cols = input_shape[2] + self.padding[1][0] + self.padding[1][1]\n else:\n cols = None\n return tensor_shape.TensorShape(\n [input_shape[0], rows, cols, input_shape[3]])\n\n def call(self, inputs):\n return backend.spatial_2d_padding(\n inputs, padding=self.padding, data_format=self.data_format)\n\n def get_config(self):\n config = {'padding': self.padding, 'data_format': self.data_format}\n base_config = super(ZeroPadding2D, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@keras_export('keras.layers.ZeroPadding3D')\nclass ZeroPadding3D(Layer):\n \"\"\"Zero-padding layer for 3D data (spatial or spatio-temporal).\n\n Examples:\n\n >>> input_shape = (1, 1, 2, 2, 3)\n >>> x = np.arange(np.prod(input_shape)).reshape(input_shape)\n >>> y = tf.keras.layers.ZeroPadding3D(padding=2)(x)\n >>> print(y.shape)\n (1, 5, 6, 6, 3)\n\n Arguments:\n padding: Int, or tuple of 3 ints, or tuple of 3 tuples of 2 ints.\n - If int: the same symmetric padding\n is applied to height and width.\n - If tuple of 3 ints:\n interpreted as two different\n symmetric padding values for height and width:\n `(symmetric_dim1_pad, symmetric_dim2_pad, symmetric_dim3_pad)`.\n - If tuple of 3 tuples of 2 ints:\n interpreted as\n `((left_dim1_pad, right_dim1_pad), (left_dim2_pad,\n right_dim2_pad), (left_dim3_pad, right_dim3_pad))`\n data_format: A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch_size, spatial_dim1, spatial_dim2, spatial_dim3, channels)`\n while `channels_first` corresponds to inputs with shape\n `(batch_size, channels, spatial_dim1, spatial_dim2, spatial_dim3)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".\n\n Input shape:\n 5D tensor with shape:\n - If `data_format` is `\"channels_last\"`:\n `(batch_size, first_axis_to_pad, second_axis_to_pad, third_axis_to_pad,\n depth)`\n - If `data_format` is `\"channels_first\"`:\n `(batch_size, depth, first_axis_to_pad, second_axis_to_pad,\n third_axis_to_pad)`\n\n Output shape:\n 5D tensor with shape:\n - If `data_format` is `\"channels_last\"`:\n `(batch_size, first_padded_axis, second_padded_axis, third_axis_to_pad,\n depth)`\n - If `data_format` is `\"channels_first\"`:\n `(batch_size, depth, first_padded_axis, second_padded_axis,\n third_axis_to_pad)`\n \"\"\"\n\n def __init__(self, padding=(1, 1, 1), data_format=None, **kwargs):\n super(ZeroPadding3D, self).__init__(**kwargs)\n self.data_format = conv_utils.normalize_data_format(data_format)\n if isinstance(padding, int):\n self.padding = ((padding, padding), (padding, padding), (padding,\n padding))\n elif hasattr(padding, '__len__'):\n if len(padding) != 3:\n raise ValueError('`padding` should have 3 elements. '\n 'Found: ' + str(padding))\n dim1_padding = conv_utils.normalize_tuple(padding[0], 2,\n '1st entry of padding')\n dim2_padding = conv_utils.normalize_tuple(padding[1], 2,\n '2nd entry of padding')\n dim3_padding = conv_utils.normalize_tuple(padding[2], 2,\n '3rd entry of padding')\n self.padding = (dim1_padding, dim2_padding, dim3_padding)\n else:\n raise ValueError(\n '`padding` should be either an int, '\n 'a tuple of 3 ints '\n '(symmetric_dim1_pad, symmetric_dim2_pad, symmetric_dim3_pad), '\n 'or a tuple of 3 tuples of 2 ints '\n '((left_dim1_pad, right_dim1_pad),'\n ' (left_dim2_pad, right_dim2_pad),'\n ' (left_dim3_pad, right_dim2_pad)). '\n 'Found: ' + str(padding))\n self.input_spec = InputSpec(ndim=5)\n\n def compute_output_shape(self, input_shape):\n input_shape = tensor_shape.TensorShape(input_shape).as_list()\n if self.data_format == 'channels_first':\n if input_shape[2] is not None:\n dim1 = input_shape[2] + 2 * self.padding[0][0]\n else:\n dim1 = None\n if input_shape[3] is not None:\n dim2 = input_shape[3] + 2 * self.padding[1][0]\n else:\n dim2 = None\n if input_shape[4] is not None:\n dim3 = input_shape[4] + 2 * self.padding[2][0]\n else:\n dim3 = None\n return tensor_shape.TensorShape(\n [input_shape[0], input_shape[1], dim1, dim2, dim3])\n elif self.data_format == 'channels_last':\n if input_shape[1] is not None:\n dim1 = input_shape[1] + 2 * self.padding[0][1]\n else:\n dim1 = None\n if input_shape[2] is not None:\n dim2 = input_shape[2] + 2 * self.padding[1][1]\n else:\n dim2 = None\n if input_shape[3] is not None:\n dim3 = input_shape[3] + 2 * self.padding[2][1]\n else:\n dim3 = None\n return tensor_shape.TensorShape(\n [input_shape[0], dim1, dim2, dim3, input_shape[4]])\n\n def call(self, inputs):\n return backend.spatial_3d_padding(\n inputs, padding=self.padding, data_format=self.data_format)\n\n def get_config(self):\n config = {'padding': self.padding, 'data_format': self.data_format}\n base_config = super(ZeroPadding3D, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@keras_export('keras.layers.Cropping1D')\nclass Cropping1D(Layer):\n \"\"\"Cropping layer for 1D input (e.g. temporal sequence).\n\n It crops along the time dimension (axis 1).\n\n Examples:\n\n >>> input_shape = (2, 3, 2)\n >>> x = np.arange(np.prod(input_shape)).reshape(input_shape)\n >>> print(x)\n [[[ 0 1]\n [ 2 3]\n [ 4 5]]\n [[ 6 7]\n [ 8 9]\n [10 11]]]\n >>> y = tf.keras.layers.Cropping1D(cropping=1)(x)\n >>> print(y)\n tf.Tensor(\n [[[2 3]]\n [[8 9]]], shape=(2, 1, 2), dtype=int64)\n\n Arguments:\n cropping: Int or tuple of int (length 2)\n How many units should be trimmed off at the beginning and end of\n the cropping dimension (axis 1).\n If a single int is provided, the same value will be used for both.\n\n Input shape:\n 3D tensor with shape `(batch_size, axis_to_crop, features)`\n\n Output shape:\n 3D tensor with shape `(batch_size, cropped_axis, features)`\n \"\"\"\n\n def __init__(self, cropping=(1, 1), **kwargs):\n super(Cropping1D, self).__init__(**kwargs)\n self.cropping = conv_utils.normalize_tuple(cropping, 2, 'cropping')\n self.input_spec = InputSpec(ndim=3)\n\n def compute_output_shape(self, input_shape):\n input_shape = tensor_shape.TensorShape(input_shape).as_list()\n if input_shape[1] is not None:\n length = input_shape[1] - self.cropping[0] - self.cropping[1]\n else:\n length = None\n return tensor_shape.TensorShape([input_shape[0], length, input_shape[2]])\n\n def call(self, inputs):\n if self.cropping[1] == 0:\n return inputs[:, self.cropping[0]:, :]\n else:\n return inputs[:, self.cropping[0]:-self.cropping[1], :]\n\n def get_config(self):\n config = {'cropping': self.cropping}\n base_config = super(Cropping1D, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@keras_export('keras.layers.Cropping2D')\nclass Cropping2D(Layer):\n \"\"\"Cropping layer for 2D input (e.g. picture).\n\n It crops along spatial dimensions, i.e. height and width.\n\n Examples:\n\n >>> input_shape = (2, 28, 28, 3)\n >>> x = np.arange(np.prod(input_shape)).reshape(input_shape)\n >>> y = tf.keras.layers.Cropping2D(cropping=((2, 2), (4, 4)))(x)\n >>> print(y.shape)\n (2, 24, 20, 3)\n\n Arguments:\n cropping: Int, or tuple of 2 ints, or tuple of 2 tuples of 2 ints.\n - If int: the same symmetric cropping\n is applied to height and width.\n - If tuple of 2 ints:\n interpreted as two different\n symmetric cropping values for height and width:\n `(symmetric_height_crop, symmetric_width_crop)`.\n - If tuple of 2 tuples of 2 ints:\n interpreted as\n `((top_crop, bottom_crop), (left_crop, right_crop))`\n data_format: A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch_size, height, width, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch_size, channels, height, width)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".\n\n Input shape:\n 4D tensor with shape:\n - If `data_format` is `\"channels_last\"`:\n `(batch_size, rows, cols, channels)`\n - If `data_format` is `\"channels_first\"`:\n `(batch_size, channels, rows, cols)`\n\n Output shape:\n 4D tensor with shape:\n - If `data_format` is `\"channels_last\"`:\n `(batch_size, cropped_rows, cropped_cols, channels)`\n - If `data_format` is `\"channels_first\"`:\n `(batch_size, channels, cropped_rows, cropped_cols)`\n \"\"\"\n\n def __init__(self, cropping=((0, 0), (0, 0)), data_format=None, **kwargs):\n super(Cropping2D, self).__init__(**kwargs)\n self.data_format = conv_utils.normalize_data_format(data_format)\n if isinstance(cropping, int):\n self.cropping = ((cropping, cropping), (cropping, cropping))\n elif hasattr(cropping, '__len__'):\n if len(cropping) != 2:\n raise ValueError('`cropping` should have two elements. '\n 'Found: ' + str(cropping))\n height_cropping = conv_utils.normalize_tuple(cropping[0], 2,\n '1st entry of cropping')\n width_cropping = conv_utils.normalize_tuple(cropping[1], 2,\n '2nd entry of cropping')\n self.cropping = (height_cropping, width_cropping)\n else:\n raise ValueError('`cropping` should be either an int, '\n 'a tuple of 2 ints '\n '(symmetric_height_crop, symmetric_width_crop), '\n 'or a tuple of 2 tuples of 2 ints '\n '((top_crop, bottom_crop), (left_crop, right_crop)). '\n 'Found: ' + str(cropping))\n self.input_spec = InputSpec(ndim=4)\n\n def compute_output_shape(self, input_shape):\n input_shape = tensor_shape.TensorShape(input_shape).as_list()\n # pylint: disable=invalid-unary-operand-type\n if self.data_format == 'channels_first':\n return tensor_shape.TensorShape([\n input_shape[0], input_shape[1],\n input_shape[2] - self.cropping[0][0] - self.cropping[0][1]\n if input_shape[2] else None,\n input_shape[3] - self.cropping[1][0] - self.cropping[1][1]\n if input_shape[3] else None\n ])\n else:\n return tensor_shape.TensorShape([\n input_shape[0],\n input_shape[1] - self.cropping[0][0] - self.cropping[0][1]\n if input_shape[1] else None,\n input_shape[2] - self.cropping[1][0] - self.cropping[1][1]\n if input_shape[2] else None, input_shape[3]\n ])\n # pylint: enable=invalid-unary-operand-type\n\n def call(self, inputs):\n # pylint: disable=invalid-unary-operand-type\n if self.data_format == 'channels_first':\n if self.cropping[0][1] == self.cropping[1][1] == 0:\n return inputs[:, :, self.cropping[0][0]:, self.cropping[1][0]:]\n elif self.cropping[0][1] == 0:\n return inputs[:, :, self.cropping[0][0]:, self.cropping[1][0]:\n -self.cropping[1][1]]\n elif self.cropping[1][1] == 0:\n return inputs[:, :, self.cropping[0][0]:-self.cropping[0][1],\n self.cropping[1][0]:]\n return inputs[:, :, self.cropping[0][0]:-self.cropping[0][1],\n self.cropping[1][0]:-self.cropping[1][1]]\n else:\n if self.cropping[0][1] == self.cropping[1][1] == 0:\n return inputs[:, self.cropping[0][0]:, self.cropping[1][0]:, :]\n elif self.cropping[0][1] == 0:\n return inputs[:, self.cropping[0][0]:, self.cropping[1][0]:\n -self.cropping[1][1], :]\n elif self.cropping[1][1] == 0:\n return inputs[:, self.cropping[0][0]:-self.cropping[0][1],\n self.cropping[1][0]:, :]\n return inputs[:, self.cropping[0][0]:-self.cropping[0][1], self.cropping[\n 1][0]:-self.cropping[1][1], :] # pylint: disable=invalid-unary-operand-type\n # pylint: enable=invalid-unary-operand-type\n\n def get_config(self):\n config = {'cropping': self.cropping, 'data_format': self.data_format}\n base_config = super(Cropping2D, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@keras_export('keras.layers.Cropping3D')\nclass Cropping3D(Layer):\n \"\"\"Cropping layer for 3D data (e.g. spatial or spatio-temporal).\n\n Examples:\n\n >>> input_shape = (2, 28, 28, 10, 3)\n >>> x = np.arange(np.prod(input_shape)).reshape(input_shape)\n >>> y = tf.keras.layers.Cropping3D(cropping=(2, 4, 2))(x)\n >>> print(y.shape)\n (2, 24, 20, 6, 3)\n\n Arguments:\n cropping: Int, or tuple of 3 ints, or tuple of 3 tuples of 2 ints.\n - If int: the same symmetric cropping\n is applied to depth, height, and width.\n - If tuple of 3 ints: interpreted as two different\n symmetric cropping values for depth, height, and width:\n `(symmetric_dim1_crop, symmetric_dim2_crop, symmetric_dim3_crop)`.\n - If tuple of 3 tuples of 2 ints: interpreted as\n `((left_dim1_crop, right_dim1_crop), (left_dim2_crop,\n right_dim2_crop), (left_dim3_crop, right_dim3_crop))`\n data_format: A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch_size, spatial_dim1, spatial_dim2, spatial_dim3, channels)`\n while `channels_first` corresponds to inputs with shape\n `(batch_size, channels, spatial_dim1, spatial_dim2, spatial_dim3)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".\n\n Input shape:\n 5D tensor with shape:\n - If `data_format` is `\"channels_last\"`:\n `(batch_size, first_axis_to_crop, second_axis_to_crop, third_axis_to_crop,\n depth)`\n - If `data_format` is `\"channels_first\"`:\n `(batch_size, depth, first_axis_to_crop, second_axis_to_crop,\n third_axis_to_crop)`\n\n Output shape:\n 5D tensor with shape:\n - If `data_format` is `\"channels_last\"`:\n `(batch_size, first_cropped_axis, second_cropped_axis, third_cropped_axis,\n depth)`\n - If `data_format` is `\"channels_first\"`:\n `(batch_size, depth, first_cropped_axis, second_cropped_axis,\n third_cropped_axis)`\n \"\"\"\n\n def __init__(self,\n cropping=((1, 1), (1, 1), (1, 1)),\n data_format=None,\n **kwargs):\n super(Cropping3D, self).__init__(**kwargs)\n self.data_format = conv_utils.normalize_data_format(data_format)\n if isinstance(cropping, int):\n self.cropping = ((cropping, cropping), (cropping, cropping), (cropping,\n cropping))\n elif hasattr(cropping, '__len__'):\n if len(cropping) != 3:\n raise ValueError('`cropping` should have 3 elements. '\n 'Found: ' + str(cropping))\n dim1_cropping = conv_utils.normalize_tuple(cropping[0], 2,\n '1st entry of cropping')\n dim2_cropping = conv_utils.normalize_tuple(cropping[1], 2,\n '2nd entry of cropping')\n dim3_cropping = conv_utils.normalize_tuple(cropping[2], 2,\n '3rd entry of cropping')\n self.cropping = (dim1_cropping, dim2_cropping, dim3_cropping)\n else:\n raise ValueError(\n '`cropping` should be either an int, '\n 'a tuple of 3 ints '\n '(symmetric_dim1_crop, symmetric_dim2_crop, symmetric_dim3_crop), '\n 'or a tuple of 3 tuples of 2 ints '\n '((left_dim1_crop, right_dim1_crop),'\n ' (left_dim2_crop, right_dim2_crop),'\n ' (left_dim3_crop, right_dim2_crop)). '\n 'Found: ' + str(cropping))\n self.input_spec = InputSpec(ndim=5)\n\n def compute_output_shape(self, input_shape):\n input_shape = tensor_shape.TensorShape(input_shape).as_list()\n # pylint: disable=invalid-unary-operand-type\n if self.data_format == 'channels_first':\n if input_shape[2] is not None:\n dim1 = input_shape[2] - self.cropping[0][0] - self.cropping[0][1]\n else:\n dim1 = None\n if input_shape[3] is not None:\n dim2 = input_shape[3] - self.cropping[1][0] - self.cropping[1][1]\n else:\n dim2 = None\n if input_shape[4] is not None:\n dim3 = input_shape[4] - self.cropping[2][0] - self.cropping[2][1]\n else:\n dim3 = None\n return tensor_shape.TensorShape(\n [input_shape[0], input_shape[1], dim1, dim2, dim3])\n elif self.data_format == 'channels_last':\n if input_shape[1] is not None:\n dim1 = input_shape[1] - self.cropping[0][0] - self.cropping[0][1]\n else:\n dim1 = None\n if input_shape[2] is not None:\n dim2 = input_shape[2] - self.cropping[1][0] - self.cropping[1][1]\n else:\n dim2 = None\n if input_shape[3] is not None:\n dim3 = input_shape[3] - self.cropping[2][0] - self.cropping[2][1]\n else:\n dim3 = None\n return tensor_shape.TensorShape(\n [input_shape[0], dim1, dim2, dim3, input_shape[4]])\n # pylint: enable=invalid-unary-operand-type\n\n def call(self, inputs):\n # pylint: disable=invalid-unary-operand-type\n if self.data_format == 'channels_first':\n if self.cropping[0][1] == self.cropping[1][1] == self.cropping[2][1] == 0:\n return inputs[:, :, self.cropping[0][0]:, self.cropping[1][0]:,\n self.cropping[2][0]:]\n elif self.cropping[0][1] == self.cropping[1][1] == 0:\n return inputs[:, :, self.cropping[0][0]:, self.cropping[1][0]:,\n self.cropping[2][0]:-self.cropping[2][1]]\n elif self.cropping[1][1] == self.cropping[2][1] == 0:\n return inputs[:, :, self.cropping[0][0]:-self.cropping[0][1],\n self.cropping[1][0]:, self.cropping[2][0]:]\n elif self.cropping[0][1] == self.cropping[2][1] == 0:\n return inputs[:, :, self.cropping[0][0]:, self.cropping[1][0]:\n -self.cropping[1][1], self.cropping[2][0]:]\n elif self.cropping[0][1] == 0:\n return inputs[:, :, self.cropping[0][0]:, self.cropping[1][\n 0]:-self.cropping[1][1], self.cropping[2][0]:-self.cropping[2][1]]\n elif self.cropping[1][1] == 0:\n return inputs[:, :, self.cropping[0][0]:-self.cropping[0][1], self.\n cropping[1][0]:, self.cropping[2][0]:-self.cropping[2][1]]\n elif self.cropping[2][1] == 0:\n return inputs[:, :, self.cropping[0][0]:-self.cropping[0][1], self.\n cropping[1][0]:-self.cropping[1][1], self.cropping[2][0]:]\n return inputs[:, :, self.cropping[0][0]:-self.cropping[0][1],\n self.cropping[1][0]:-self.cropping[1][1], self.cropping[2][\n 0]:-self.cropping[2][1]]\n else:\n if self.cropping[0][1] == self.cropping[1][1] == self.cropping[2][1] == 0:\n return inputs[:, self.cropping[0][0]:, self.cropping[1][0]:,\n self.cropping[2][0]:, :]\n elif self.cropping[0][1] == self.cropping[1][1] == 0:\n return inputs[:, self.cropping[0][0]:, self.cropping[1][0]:,\n self.cropping[2][0]:-self.cropping[2][1], :]\n elif self.cropping[1][1] == self.cropping[2][1] == 0:\n return inputs[:, self.cropping[0][0]:-self.cropping[0][1],\n self.cropping[1][0]:, self.cropping[2][0]:, :]\n elif self.cropping[0][1] == self.cropping[2][1] == 0:\n return inputs[:, self.cropping[0][0]:, self.cropping[1][0]:\n -self.cropping[1][1], self.cropping[2][0]:, :]\n elif self.cropping[0][1] == 0:\n return inputs[:, self.cropping[0][0]:, self.cropping[1][\n 0]:-self.cropping[1][1], self.cropping[2][0]:\n -self.cropping[2][1], :]\n elif self.cropping[1][1] == 0:\n return inputs[:, self.cropping[0][\n 0]:-self.cropping[0][1], self.cropping[1][0]:, self.cropping[2][0]:\n -self.cropping[2][1], :]\n elif self.cropping[2][1] == 0:\n return inputs[:, self.cropping[0][0]:-self.cropping[0][1],\n self.cropping[1][0]:-self.cropping[1][1], self.cropping[\n 2][0]:, :]\n return inputs[:, self.cropping[0][0]:-self.cropping[0][1], self.cropping[\n 1][0]:-self.cropping[1][1], self.cropping[2][0]: # pylint: disable=invalid-unary-operand-type\n -self.cropping[2][1], :] # pylint: disable=invalid-unary-operand-type\n # pylint: enable=invalid-unary-operand-type\n\n def get_config(self):\n config = {'cropping': self.cropping, 'data_format': self.data_format}\n base_config = super(Cropping3D, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n# Aliases\n\nConvolution1D = Conv1D\nConvolution2D = Conv2D\nConvolution3D = Conv3D\nSeparableConvolution1D = SeparableConv1D\nSeparableConvolution2D = SeparableConv2D\nConvolution2DTranspose = Conv2DTranspose\nConvolution3DTranspose = Conv3DTranspose\nDeconvolution2D = Deconv2D = Conv2DTranspose\nDeconvolution3D = Deconv3D = Conv3DTranspose\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.Lu.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.python.client import session\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 control_flow_ops\nfrom tensorflow.python.ops import linalg_ops\nfrom tensorflow.python.ops import map_fn\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import random_ops\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import benchmark\nfrom tensorflow.python.platform import test\n\n\nclass LuOpTest(test.TestCase):\n\n @property\n def float_types(self):\n return set((np.float64, np.float32, np.complex64, np.complex128))\n\n def _verifyLuBase(self, x, lower, upper, perm, verification,\n output_idx_type):\n lower_np, upper_np, perm_np, verification_np = self.evaluate(\n [lower, upper, perm, verification])\n\n self.assertAllClose(x, verification_np)\n self.assertShapeEqual(x, lower)\n self.assertShapeEqual(x, upper)\n\n self.assertAllEqual(x.shape[:-1], perm.shape.as_list())\n\n # Check dtypes are as expected.\n self.assertEqual(x.dtype, lower_np.dtype)\n self.assertEqual(x.dtype, upper_np.dtype)\n self.assertEqual(output_idx_type.as_numpy_dtype, perm_np.dtype)\n\n # Check that the permutation is valid.\n if perm_np.shape[-1] > 0:\n perm_reshaped = np.reshape(perm_np, (-1, perm_np.shape[-1]))\n for perm_vector in perm_reshaped:\n self.assertAllClose(np.arange(len(perm_vector)), np.sort(perm_vector))\n\n def _verifyLu(self, x, output_idx_type=dtypes.int64):\n # Verify that Px = LU.\n lu, perm = linalg_ops.lu(x, output_idx_type=output_idx_type)\n\n # Prepare the lower factor of shape num_rows x num_rows\n lu_shape = np.array(lu.shape.as_list())\n batch_shape = lu_shape[:-2]\n num_rows = lu_shape[-2]\n num_cols = lu_shape[-1]\n\n lower = array_ops.matrix_band_part(lu, -1, 0)\n\n if num_rows > num_cols:\n eye = linalg_ops.eye(\n num_rows, batch_shape=batch_shape, dtype=lower.dtype)\n lower = array_ops.concat([lower, eye[..., num_cols:]], axis=-1)\n elif num_rows < num_cols:\n lower = lower[..., :num_rows]\n\n # Fill the diagonal with ones.\n ones_diag = array_ops.ones(\n np.append(batch_shape, num_rows), dtype=lower.dtype)\n lower = array_ops.matrix_set_diag(lower, ones_diag)\n\n # Prepare the upper factor.\n upper = array_ops.matrix_band_part(lu, 0, -1)\n\n verification = math_ops.matmul(lower, upper)\n\n # Permute the rows of product of the Cholesky factors.\n if num_rows > 0:\n # Reshape the product of the triangular factors and permutation indices\n # to a single batch dimension. This makes it easy to apply\n # invert_permutation and gather_nd ops.\n perm_reshaped = array_ops.reshape(perm, [-1, num_rows])\n verification_reshaped = array_ops.reshape(verification,\n [-1, num_rows, num_cols])\n # Invert the permutation in each batch.\n inv_perm_reshaped = map_fn.map_fn(array_ops.invert_permutation,\n perm_reshaped)\n batch_size = perm_reshaped.shape.as_list()[0]\n # Prepare the batch indices with the same shape as the permutation.\n # The corresponding batch index is paired with each of the `num_rows`\n # permutation indices.\n batch_indices = math_ops.cast(\n array_ops.broadcast_to(\n math_ops.range(batch_size)[:, None], perm_reshaped.shape),\n dtype=output_idx_type)\n permuted_verification_reshaped = array_ops.gather_nd(\n verification_reshaped,\n array_ops.stack([batch_indices, inv_perm_reshaped], axis=-1))\n\n # Reshape the verification matrix back to the original shape.\n verification = array_ops.reshape(permuted_verification_reshaped,\n lu_shape)\n\n self._verifyLuBase(x, lower, upper, perm, verification,\n output_idx_type)\n\n def testBasic(self):\n data = np.array([[4., -1., 2.], [-1., 6., 0], [10., 0., 5.]])\n\n for dtype in (np.float32, np.float64):\n for output_idx_type in (dtypes.int32, dtypes.int64):\n with self.subTest(dtype=dtype, output_idx_type=output_idx_type):\n self._verifyLu(data.astype(dtype), output_idx_type=output_idx_type)\n\n for dtype in (np.complex64, np.complex128):\n for output_idx_type in (dtypes.int32, dtypes.int64):\n with self.subTest(dtype=dtype, output_idx_type=output_idx_type):\n complex_data = np.tril(1j * data, -1).astype(dtype)\n complex_data += np.triu(-1j * data, 1).astype(dtype)\n complex_data += data\n self._verifyLu(complex_data, output_idx_type=output_idx_type)\n\n def testPivoting(self):\n # This matrix triggers partial pivoting because the first diagonal entry\n # is small.\n data = np.array([[1e-9, 1., 0.], [1., 0., 0], [0., 1., 5]])\n self._verifyLu(data.astype(np.float32))\n\n for dtype in (np.float32, np.float64):\n with self.subTest(dtype=dtype):\n self._verifyLu(data.astype(dtype))\n _, p = linalg_ops.lu(data)\n p_val = self.evaluate([p])\n # Make sure p_val is not the identity permutation.\n self.assertNotAllClose(np.arange(3), p_val)\n\n for dtype in (np.complex64, np.complex128):\n with self.subTest(dtype=dtype):\n complex_data = np.tril(1j * data, -1).astype(dtype)\n complex_data += np.triu(-1j * data, 1).astype(dtype)\n complex_data += data\n self._verifyLu(complex_data)\n _, p = linalg_ops.lu(data)\n p_val = self.evaluate([p])\n # Make sure p_val is not the identity permutation.\n self.assertNotAllClose(np.arange(3), p_val)\n\n def testInvalidMatrix(self):\n # LU factorization gives an error when the input is singular.\n # Note: A singular matrix may return without error but it won't be a valid\n # factorization.\n for dtype in self.float_types:\n with self.subTest(dtype=dtype):\n with self.assertRaises(errors.InvalidArgumentError):\n self.evaluate(\n linalg_ops.lu(\n np.array([[1., 2., 3.], [2., 4., 6.], [2., 3., 4.]],\n dtype=dtype)))\n with self.assertRaises(errors.InvalidArgumentError):\n self.evaluate(\n linalg_ops.lu(\n np.array([[[1., 2., 3.], [2., 4., 6.], [1., 2., 3.]],\n [[1., 2., 3.], [3., 4., 5.], [5., 6., 7.]]],\n dtype=dtype)))\n\n def testBatch(self):\n simple_array = np.array([[[1., -1.], [2., 5.]]]) # shape (1, 2, 2)\n self._verifyLu(simple_array)\n self._verifyLu(np.vstack((simple_array, simple_array)))\n odd_sized_array = np.array([[[4., -1., 2.], [-1., 6., 0], [2., 0., 5.]]])\n self._verifyLu(np.vstack((odd_sized_array, odd_sized_array)))\n\n batch_size = 200\n\n # Generate random matrices.\n np.random.seed(42)\n matrices = np.random.rand(batch_size, 5, 5)\n self._verifyLu(matrices)\n\n # Generate random complex valued matrices.\n np.random.seed(52)\n matrices = np.random.rand(batch_size, 5,\n 5) + 1j * np.random.rand(batch_size, 5, 5)\n self._verifyLu(matrices)\n\n def testLargeMatrix(self):\n # Generate random matrices.\n n = 500\n np.random.seed(64)\n data = np.random.rand(n, n)\n self._verifyLu(data)\n\n # Generate random complex valued matrices.\n np.random.seed(129)\n data = np.random.rand(n, n) + 1j * np.random.rand(n, n)\n self._verifyLu(data)\n\n @test_util.run_v1_only(\"b/120545219\")\n def testEmpty(self):\n self._verifyLu(np.empty([0, 2, 2]))\n self._verifyLu(np.empty([2, 0, 0]))\n\n @test_util.run_deprecated_v1\n def testConcurrentExecutesWithoutError(self):\n matrix1 = random_ops.random_normal([5, 5], seed=42)\n matrix2 = random_ops.random_normal([5, 5], seed=42)\n lu1, p1 = linalg_ops.lu(matrix1)\n lu2, p2 = linalg_ops.lu(matrix2)\n lu1_val, p1_val, lu2_val, p2_val = self.evaluate([lu1, p1, lu2, p2])\n self.assertAllEqual(lu1_val, lu2_val)\n self.assertAllEqual(p1_val, p2_val)\n\n\nclass LuBenchmark(test.Benchmark):\n shapes = [\n (4, 4),\n (10, 10),\n (16, 16),\n (101, 101),\n (256, 256),\n (1000, 1000),\n (1024, 1024),\n (2048, 2048),\n (4096, 4096),\n (513, 2, 2),\n (513, 8, 8),\n (513, 256, 256),\n (4, 513, 2, 2),\n ]\n\n def _GenerateMatrix(self, shape):\n batch_shape = shape[:-2]\n shape = shape[-2:]\n assert shape[0] == shape[1]\n n = shape[0]\n matrix = np.ones(shape).astype(np.float32) / (2.0 * n) + np.diag(\n np.ones(n).astype(np.float32))\n return np.tile(matrix, batch_shape + (1, 1))\n\n def benchmarkLuOp(self):\n for shape in self.shapes:\n with ops.Graph().as_default(), \\\n session.Session(config=benchmark.benchmark_config()) as sess, \\\n ops.device(\"/cpu:0\"):\n matrix = variables.Variable(self._GenerateMatrix(shape))\n lu, p = linalg_ops.lu(matrix)\n variables.global_variables_initializer().run()\n self.run_op_benchmark(\n sess,\n control_flow_ops.group(lu, p),\n min_iters=25,\n name=\"lu_cpu_{shape}\".format(shape=shape))\n\n if test.is_gpu_available(True):\n with ops.Graph().as_default(), \\\n session.Session(config=benchmark.benchmark_config()) as sess, \\\n ops.device(\"/device:GPU:0\"):\n matrix = variables.Variable(self._GenerateMatrix(shape))\n lu, p = linalg_ops.lu(matrix)\n variables.global_variables_initializer().run()\n self.run_op_benchmark(\n sess,\n control_flow_ops.group(lu, p),\n min_iters=25,\n name=\"lu_gpu_{shape}\".format(shape=shape))\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\"\"\"Implementation of Neural Net (NN) functions.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport math\n\nfrom tensorflow.python.compat import compat\nfrom tensorflow.python.distribute import distribution_strategy_context as ds\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 candidate_sampling_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import custom_gradient\nfrom tensorflow.python.ops import embedding_ops\nfrom tensorflow.python.ops import gen_array_ops # pylint: disable=unused-import\nfrom tensorflow.python.ops import gen_nn_ops\nfrom tensorflow.python.ops import gen_sparse_ops\nfrom tensorflow.python.ops import linalg_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import nn_ops\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.ops.losses import util as losses_util\nfrom tensorflow.python.platform import device_context\nfrom tensorflow.python.util.deprecation import deprecated_args\nfrom tensorflow.python.util.deprecation import deprecated_argument_lookup\nfrom tensorflow.python.util.tf_export import tf_export\n\n\n@tf_export(\"nn.log_poisson_loss\")\ndef log_poisson_loss(targets, log_input, compute_full_loss=False, name=None):\n \"\"\"Computes log Poisson loss given `log_input`.\n\n Gives the log-likelihood loss between the prediction and the target under the\n assumption that the target has a Poisson distribution.\n Caveat: By default, this is not the exact loss, but the loss minus a\n constant term [log(z!)]. That has no effect for optimization, but\n does not play well with relative loss comparisons. To compute an\n approximation of the log factorial term, specify\n compute_full_loss=True to enable Stirling's Approximation.\n\n For brevity, let `c = log(x) = log_input`, `z = targets`. The log Poisson\n loss is\n\n -log(exp(-x) * (x^z) / z!)\n = -log(exp(-x) * (x^z)) + log(z!)\n ~ -log(exp(-x)) - log(x^z) [+ z * log(z) - z + 0.5 * log(2 * pi * z)]\n [ Note the second term is the Stirling's Approximation for log(z!).\n It is invariant to x and does not affect optimization, though\n important for correct relative loss comparisons. It is only\n computed when compute_full_loss == True. ]\n = x - z * log(x) [+ z * log(z) - z + 0.5 * log(2 * pi * z)]\n = exp(c) - z * c [+ z * log(z) - z + 0.5 * log(2 * pi * z)]\n\n Args:\n targets: A `Tensor` of the same type and shape as `log_input`.\n log_input: A `Tensor` of type `float32` or `float64`.\n compute_full_loss: whether to compute the full loss. If false, a constant\n term is dropped in favor of more efficient optimization.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of the same shape as `log_input` with the componentwise\n logistic losses.\n\n Raises:\n ValueError: If `log_input` and `targets` do not have the same shape.\n \"\"\"\n with ops.name_scope(name, \"log_poisson_loss\", [log_input, targets]) as name:\n log_input = ops.convert_to_tensor(log_input, name=\"log_input\")\n targets = ops.convert_to_tensor(targets, name=\"targets\")\n try:\n targets.get_shape().merge_with(log_input.get_shape())\n except ValueError:\n raise ValueError(\n \"log_input and targets must have the same shape (%s vs %s)\" %\n (log_input.get_shape(), targets.get_shape()))\n\n result = math_ops.exp(log_input) - log_input * targets\n if compute_full_loss:\n # need to create constant tensors here so that their dtypes can be matched\n # to that of the targets.\n point_five = constant_op.constant(0.5, dtype=targets.dtype)\n two_pi = constant_op.constant(2 * math.pi, dtype=targets.dtype)\n\n stirling_approx = (targets * math_ops.log(targets)) - targets + (\n point_five * math_ops.log(two_pi * targets))\n zeros = array_ops.zeros_like(targets, dtype=targets.dtype)\n ones = array_ops.ones_like(targets, dtype=targets.dtype)\n cond = math_ops.logical_and(targets >= zeros, targets <= ones)\n result += array_ops.where(cond, zeros, stirling_approx)\n return result\n\n\n@tf_export(v1=[\"nn.sigmoid_cross_entropy_with_logits\"])\ndef sigmoid_cross_entropy_with_logits( # pylint: disable=invalid-name\n _sentinel=None,\n labels=None,\n logits=None,\n name=None):\n \"\"\"Computes sigmoid cross entropy given `logits`.\n\n Measures the probability error in discrete classification tasks in which each\n class is independent and not mutually exclusive. For instance, one could\n perform multilabel classification where a picture can contain both an elephant\n and a dog at the same time.\n\n For brevity, let `x = logits`, `z = labels`. The logistic loss is\n\n z * -log(sigmoid(x)) + (1 - z) * -log(1 - sigmoid(x))\n = z * -log(1 / (1 + exp(-x))) + (1 - z) * -log(exp(-x) / (1 + exp(-x)))\n = z * log(1 + exp(-x)) + (1 - z) * (-log(exp(-x)) + log(1 + exp(-x)))\n = z * log(1 + exp(-x)) + (1 - z) * (x + log(1 + exp(-x))\n = (1 - z) * x + log(1 + exp(-x))\n = x - x * z + log(1 + exp(-x))\n\n For x < 0, to avoid overflow in exp(-x), we reformulate the above\n\n x - x * z + log(1 + exp(-x))\n = log(exp(x)) - x * z + log(1 + exp(-x))\n = - x * z + log(1 + exp(x))\n\n Hence, to ensure stability and avoid overflow, the implementation uses this\n equivalent formulation\n\n max(x, 0) - x * z + log(1 + exp(-abs(x)))\n\n `logits` and `labels` must have the same type and shape.\n\n Args:\n _sentinel: Used to prevent positional parameters. Internal, do not use.\n labels: A `Tensor` of the same type and shape as `logits`.\n logits: A `Tensor` of type `float32` or `float64`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of the same shape as `logits` with the componentwise\n logistic losses.\n\n Raises:\n ValueError: If `logits` and `labels` do not have the same shape.\n \"\"\"\n # pylint: disable=protected-access\n nn_ops._ensure_xent_args(\"sigmoid_cross_entropy_with_logits\", _sentinel,\n labels, logits)\n # pylint: enable=protected-access\n\n with ops.name_scope(name, \"logistic_loss\", [logits, labels]) as name:\n logits = ops.convert_to_tensor(logits, name=\"logits\")\n labels = ops.convert_to_tensor(labels, name=\"labels\")\n try:\n labels.get_shape().merge_with(logits.get_shape())\n except ValueError:\n raise ValueError(\"logits and labels must have the same shape (%s vs %s)\" %\n (logits.get_shape(), labels.get_shape()))\n\n # The logistic loss formula from above is\n # x - x * z + log(1 + exp(-x))\n # For x < 0, a more numerically stable formula is\n # -x * z + log(1 + exp(x))\n # Note that these two expressions can be combined into the following:\n # max(x, 0) - x * z + log(1 + exp(-abs(x)))\n # To allow computing gradients at zero, we define custom versions of max and\n # abs functions.\n zeros = array_ops.zeros_like(logits, dtype=logits.dtype)\n cond = (logits >= zeros)\n relu_logits = array_ops.where(cond, logits, zeros)\n neg_abs_logits = array_ops.where(cond, -logits, logits)\n return math_ops.add(\n relu_logits - logits * labels,\n math_ops.log1p(math_ops.exp(neg_abs_logits)),\n name=name)\n\n\n# Note: intentionally calling this v2 to not allow existing code with indirect\n# imports to ignore the sentinel behavior.\n@tf_export(\"nn.sigmoid_cross_entropy_with_logits\", v1=[])\ndef sigmoid_cross_entropy_with_logits_v2( # pylint: disable=invalid-name\n labels=None,\n logits=None,\n name=None):\n \"\"\"Computes sigmoid cross entropy given `logits`.\n\n Measures the probability error in discrete classification tasks in which each\n class is independent and not mutually exclusive. For instance, one could\n perform multilabel classification where a picture can contain both an elephant\n and a dog at the same time.\n\n For brevity, let `x = logits`, `z = labels`. The logistic loss is\n\n z * -log(sigmoid(x)) + (1 - z) * -log(1 - sigmoid(x))\n = z * -log(1 / (1 + exp(-x))) + (1 - z) * -log(exp(-x) / (1 + exp(-x)))\n = z * log(1 + exp(-x)) + (1 - z) * (-log(exp(-x)) + log(1 + exp(-x)))\n = z * log(1 + exp(-x)) + (1 - z) * (x + log(1 + exp(-x))\n = (1 - z) * x + log(1 + exp(-x))\n = x - x * z + log(1 + exp(-x))\n\n For x < 0, to avoid overflow in exp(-x), we reformulate the above\n\n x - x * z + log(1 + exp(-x))\n = log(exp(x)) - x * z + log(1 + exp(-x))\n = - x * z + log(1 + exp(x))\n\n Hence, to ensure stability and avoid overflow, the implementation uses this\n equivalent formulation\n\n max(x, 0) - x * z + log(1 + exp(-abs(x)))\n\n `logits` and `labels` must have the same type and shape.\n\n Args:\n labels: A `Tensor` of the same type and shape as `logits`.\n logits: A `Tensor` of type `float32` or `float64`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of the same shape as `logits` with the componentwise\n logistic losses.\n\n Raises:\n ValueError: If `logits` and `labels` do not have the same shape.\n \"\"\"\n return sigmoid_cross_entropy_with_logits(\n logits=logits, labels=labels, name=name)\n\n\n@tf_export(\"nn.weighted_cross_entropy_with_logits\", v1=[])\ndef weighted_cross_entropy_with_logits_v2(labels, logits, pos_weight,\n name=None):\n \"\"\"Computes a weighted cross entropy.\n\n This is like `sigmoid_cross_entropy_with_logits()` except that `pos_weight`,\n allows one to trade off recall and precision by up- or down-weighting the\n cost of a positive error relative to a negative error.\n\n The usual cross-entropy cost is defined as:\n\n labels * -log(sigmoid(logits)) +\n (1 - labels) * -log(1 - sigmoid(logits))\n\n A value `pos_weight > 1` decreases the false negative count, hence increasing\n the recall.\n Conversely setting `pos_weight < 1` decreases the false positive count and\n increases the precision.\n This can be seen from the fact that `pos_weight` is introduced as a\n multiplicative coefficient for the positive labels term\n in the loss expression:\n\n labels * -log(sigmoid(logits)) * pos_weight +\n (1 - labels) * -log(1 - sigmoid(logits))\n\n For brevity, let `x = logits`, `z = labels`, `q = pos_weight`.\n The loss is:\n\n qz * -log(sigmoid(x)) + (1 - z) * -log(1 - sigmoid(x))\n = qz * -log(1 / (1 + exp(-x))) + (1 - z) * -log(exp(-x) / (1 + exp(-x)))\n = qz * log(1 + exp(-x)) + (1 - z) * (-log(exp(-x)) + log(1 + exp(-x)))\n = qz * log(1 + exp(-x)) + (1 - z) * (x + log(1 + exp(-x))\n = (1 - z) * x + (qz + 1 - z) * log(1 + exp(-x))\n = (1 - z) * x + (1 + (q - 1) * z) * log(1 + exp(-x))\n\n Setting `l = (1 + (q - 1) * z)`, to ensure stability and avoid overflow,\n the implementation uses\n\n (1 - z) * x + l * (log(1 + exp(-abs(x))) + max(-x, 0))\n\n `logits` and `labels` must have the same type and shape.\n\n Args:\n labels: A `Tensor` of the same type and shape as `logits`.\n logits: A `Tensor` of type `float32` or `float64`.\n pos_weight: A coefficient to use on the positive examples.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of the same shape as `logits` with the componentwise\n weighted logistic losses.\n\n Raises:\n ValueError: If `logits` and `labels` do not have the same shape.\n \"\"\"\n with ops.name_scope(name, \"logistic_loss\", [logits, labels]) as name:\n logits = ops.convert_to_tensor(logits, name=\"logits\")\n labels = ops.convert_to_tensor(labels, name=\"labels\")\n try:\n labels.get_shape().merge_with(logits.get_shape())\n except ValueError:\n raise ValueError(\"logits and labels must have the same shape (%s vs %s)\" %\n (logits.get_shape(), labels.get_shape()))\n\n # The logistic loss formula from above is\n # (1 - z) * x + (1 + (q - 1) * z) * log(1 + exp(-x))\n # For x < 0, a more numerically stable formula is\n # (1 - z) * x + (1 + (q - 1) * z) * log(1 + exp(x)) - l * x\n # To avoid branching, we use the combined version\n # (1 - z) * x + l * (log(1 + exp(-abs(x))) + max(-x, 0))\n log_weight = 1 + (pos_weight - 1) * labels\n return math_ops.add(\n (1 - labels) * logits,\n log_weight * (math_ops.log1p(math_ops.exp(-math_ops.abs(logits))) +\n nn_ops.relu(-logits)),\n name=name)\n\n\n@tf_export(v1=[\"nn.weighted_cross_entropy_with_logits\"])\n@deprecated_args(None, \"targets is deprecated, use labels instead\", \"targets\")\ndef weighted_cross_entropy_with_logits(labels=None,\n logits=None,\n pos_weight=None,\n name=None,\n targets=None):\n \"\"\"Computes a weighted cross entropy.\n\n This is like `sigmoid_cross_entropy_with_logits()` except that `pos_weight`,\n allows one to trade off recall and precision by up- or down-weighting the\n cost of a positive error relative to a negative error.\n\n The usual cross-entropy cost is defined as:\n\n labels * -log(sigmoid(logits)) +\n (1 - labels) * -log(1 - sigmoid(logits))\n\n A value `pos_weight > 1` decreases the false negative count, hence increasing\n the recall.\n Conversely setting `pos_weight < 1` decreases the false positive count and\n increases the precision.\n This can be seen from the fact that `pos_weight` is introduced as a\n multiplicative coefficient for the positive labels term\n in the loss expression:\n\n labels * -log(sigmoid(logits)) * pos_weight +\n (1 - labels) * -log(1 - sigmoid(logits))\n\n For brevity, let `x = logits`, `z = labels`, `q = pos_weight`.\n The loss is:\n\n qz * -log(sigmoid(x)) + (1 - z) * -log(1 - sigmoid(x))\n = qz * -log(1 / (1 + exp(-x))) + (1 - z) * -log(exp(-x) / (1 + exp(-x)))\n = qz * log(1 + exp(-x)) + (1 - z) * (-log(exp(-x)) + log(1 + exp(-x)))\n = qz * log(1 + exp(-x)) + (1 - z) * (x + log(1 + exp(-x))\n = (1 - z) * x + (qz + 1 - z) * log(1 + exp(-x))\n = (1 - z) * x + (1 + (q - 1) * z) * log(1 + exp(-x))\n\n Setting `l = (1 + (q - 1) * z)`, to ensure stability and avoid overflow,\n the implementation uses\n\n (1 - z) * x + l * (log(1 + exp(-abs(x))) + max(-x, 0))\n\n `logits` and `labels` must have the same type and shape.\n\n Args:\n labels: A `Tensor` of the same type and shape as `logits`.\n logits: A `Tensor` of type `float32` or `float64`.\n pos_weight: A coefficient to use on the positive examples.\n name: A name for the operation (optional).\n targets: Deprecated alias for labels.\n\n Returns:\n A `Tensor` of the same shape as `logits` with the componentwise\n weighted logistic losses.\n\n Raises:\n ValueError: If `logits` and `labels` do not have the same shape.\n \"\"\"\n labels = deprecated_argument_lookup(\"labels\", labels, \"targets\", targets)\n return weighted_cross_entropy_with_logits_v2(labels, logits, pos_weight, name)\n\n\n@tf_export(\"nn.compute_average_loss\")\ndef compute_average_loss(per_example_loss,\n sample_weight=None,\n global_batch_size=None):\n \"\"\"Scales per-example losses with sample_weights and computes their average.\n\n Usage with distribution strategy and custom training loop:\n\n ```python\n with strategy.scope():\n def compute_loss(labels, predictions, sample_weight=None):\n\n # If you are using a `Loss` class instead, set reduction to `NONE` so that\n # we can do the reduction afterwards and divide by global batch size.\n per_example_loss = tf.keras.losses.sparse_categorical_crossentropy(\n labels, predictions)\n\n # Compute loss that is scaled by sample_weight and by global batch size.\n return tf.nn.compute_average_loss(\n per_example_loss,\n sample_weight=sample_weight,\n global_batch_size=GLOBAL_BATCH_SIZE)\n ```\n\n Args:\n per_example_loss: Per-example loss.\n sample_weight: Optional weighting for each example.\n global_batch_size: Optional global batch size value. Defaults to (size of\n first dimension of `losses`) * (number of replicas).\n\n Returns:\n Scalar loss value.\n \"\"\" # pylint: disable=g-doc-exception\n per_example_loss = ops.convert_to_tensor(per_example_loss)\n input_dtype = per_example_loss.dtype\n\n with losses_util.check_per_example_loss_rank(per_example_loss):\n if sample_weight is not None:\n per_example_loss = losses_util.scale_losses_by_sample_weight(\n per_example_loss, sample_weight)\n per_example_loss = math_ops.cast(per_example_loss, input_dtype)\n\n if global_batch_size is None:\n if ds.has_strategy() and ds.in_cross_replica_context():\n raise RuntimeError(\n \"You are calling `compute_average_loss` in cross replica context, \"\n \"while it was expected to be called in replica context.\")\n\n num_replicas = ds.get_strategy().num_replicas_in_sync\n per_replica_batch_size = array_ops.shape_v2(per_example_loss)[0]\n global_batch_size = per_replica_batch_size * num_replicas\n global_batch_size = math_ops.cast(global_batch_size, input_dtype)\n\n return math_ops.reduce_sum(per_example_loss) / global_batch_size\n\n\n@tf_export(\"nn.scale_regularization_loss\")\ndef scale_regularization_loss(regularization_loss):\n \"\"\"Scales the sum of the given regularization losses by number of replicas.\n\n Usage with distribution strategy and custom training loop:\n\n ```python\n with strategy.scope():\n def compute_loss(self, label, predictions):\n per_example_loss = tf.keras.losses.sparse_categorical_crossentropy(\n labels, predictions)\n\n # Compute loss that is scaled by sample_weight and by global batch size.\n loss = tf.nn.compute_average_loss(\n per_example_loss,\n sample_weight=sample_weight,\n global_batch_size=GLOBAL_BATCH_SIZE)\n\n # Add scaled regularization losses.\n loss += tf.nn.scale_regularization_loss(tf.nn.l2_loss(weights))\n return loss\n ```\n\n Args:\n regularization_loss: Regularization loss.\n\n Returns:\n Scalar loss value.\n \"\"\" # pylint: disable=g-doc-exception\n if ds.has_strategy() and ds.in_cross_replica_context():\n raise RuntimeError(\n \"You are calling `scale_regularization_loss` in cross replica context, \"\n \"while it was expected to be called in replica context.\")\n\n num_replicas = ds.get_strategy().num_replicas_in_sync\n return math_ops.reduce_sum(regularization_loss) / num_replicas\n\n\n@tf_export(v1=[\"nn.relu_layer\"])\ndef relu_layer(x, weights, biases, name=None):\n \"\"\"Computes Relu(x * weight + biases).\n\n Args:\n x: a 2D tensor. Dimensions typically: batch, in_units\n weights: a 2D tensor. Dimensions typically: in_units, out_units\n biases: a 1D tensor. Dimensions: out_units\n name: A name for the operation (optional). If not specified\n \"nn_relu_layer\" is used.\n\n Returns:\n A 2-D Tensor computing relu(matmul(x, weights) + biases).\n Dimensions typically: batch, out_units.\n \"\"\"\n with ops.name_scope(name, \"relu_layer\", [x, weights, biases]) as name:\n x = ops.convert_to_tensor(x, name=\"x\")\n weights = ops.convert_to_tensor(weights, name=\"weights\")\n biases = ops.convert_to_tensor(biases, name=\"biases\")\n xw_plus_b = nn_ops.bias_add(math_ops.matmul(x, weights), biases)\n return nn_ops.relu(xw_plus_b, name=name)\n\n\n@tf_export(\"nn.swish\")\n@custom_gradient.custom_gradient\ndef swish(features):\n # pylint: disable=g-doc-args\n \"\"\"Computes the Swish activation function: `x * sigmoid(x)`.\n\n Source: \"Searching for Activation Functions\" (Ramachandran et al. 2017)\n https://arxiv.org/abs/1710.05941\n\n Args:\n features: A `Tensor` representing preactivation values.\n name: A name for the operation (optional).\n\n Returns:\n The activation value.\n \"\"\"\n # pylint: enable=g-doc-args\n features = ops.convert_to_tensor(features, name=\"features\")\n\n def grad(dy):\n \"\"\"Gradient for the Swish activation function\"\"\"\n # Naively, x * tf.nn.sigmoid(x) requires keeping both x and sigmoid(x)\n # around for backprop, effectively doubling the tensor's memory consumption.\n # We use a control dependency here so that sigmoid(features) is re-computed\n # during backprop (the control dep prevents it being de-duped with the\n # forward pass) and we can free the sigmoid(features) expression immediately\n # after use during the forward pass.\n with ops.control_dependencies([dy]):\n sigmoid_features = math_ops.sigmoid(features)\n activation_grad = (\n sigmoid_features * (1.0 + features * (1.0 - sigmoid_features)))\n return dy * activation_grad\n\n return features * math_ops.sigmoid(features), grad\n\n\n# pylint: disable=redefined-builtin\n@tf_export(\"linalg.normalize\")\ndef normalize(tensor, ord=\"euclidean\", axis=None, name=None):\n \"\"\"Normalizes `tensor` along dimension `axis` using specified norm.\n\n This uses `tf.linalg.norm` to compute the norm along `axis`.\n\n This function can compute several different vector norms (the 1-norm, the\n Euclidean or 2-norm, the inf-norm, and in general the p-norm for p > 0) and\n matrix norms (Frobenius, 1-norm, 2-norm and inf-norm).\n\n Args:\n tensor: `Tensor` of types `float32`, `float64`, `complex64`, `complex128`\n ord: Order of the norm. Supported values are `'fro'`, `'euclidean'`, `1`,\n `2`, `np.inf` and any positive real number yielding the corresponding\n p-norm. Default is `'euclidean'` which is equivalent to Frobenius norm if\n `tensor` is a matrix and equivalent to 2-norm for vectors.\n Some restrictions apply: a) The Frobenius norm `'fro'` is not defined for\n vectors, b) If axis is a 2-tuple (matrix norm), only `'euclidean'`,\n '`fro'`, `1`, `2`, `np.inf` are supported. See the description of `axis`\n on how to compute norms for a batch of vectors or matrices stored in a\n tensor.\n axis: If `axis` is `None` (the default), the input is considered a vector\n and a single vector norm is computed over the entire set of values in the\n tensor, i.e. `norm(tensor, ord=ord)` is equivalent to\n `norm(reshape(tensor, [-1]), ord=ord)`. If `axis` is a Python integer, the\n input is considered a batch of vectors, and `axis` determines the axis in\n `tensor` over which to compute vector norms. If `axis` is a 2-tuple of\n Python integers it is considered a batch of matrices and `axis` determines\n the axes in `tensor` over which to compute a matrix norm.\n Negative indices are supported. Example: If you are passing a tensor that\n can be either a matrix or a batch of matrices at runtime, pass\n `axis=[-2,-1]` instead of `axis=None` to make sure that matrix norms are\n computed.\n name: The name of the op.\n\n Returns:\n normalized: A normalized `Tensor` with the same shape as `tensor`.\n norm: The computed norms with the same shape and dtype `tensor` but the\n final axis is 1 instead. Same as running\n `tf.cast(tf.linalg.norm(tensor, ord, axis keepdims=True), tensor.dtype)`.\n\n Raises:\n ValueError: If `ord` or `axis` is invalid.\n \"\"\"\n with ops.name_scope(name, \"normalize\", [tensor]) as name:\n tensor = ops.convert_to_tensor(tensor)\n norm = linalg_ops.norm(tensor, ord, axis, keepdims=True)\n norm = math_ops.cast(norm, tensor.dtype)\n normalized = tensor / norm\n return normalized, norm\n\n\n@tf_export(v1=[\"math.l2_normalize\", \"linalg.l2_normalize\", \"nn.l2_normalize\"])\n@deprecated_args(None, \"dim is deprecated, use axis instead\", \"dim\")\ndef l2_normalize(x, axis=None, epsilon=1e-12, name=None, dim=None):\n \"\"\"Normalizes along dimension `axis` using an L2 norm.\n\n For a 1-D tensor with `axis = 0`, computes\n\n output = x / sqrt(max(sum(x**2), epsilon))\n\n For `x` with more dimensions, independently normalizes each 1-D slice along\n dimension `axis`.\n\n Args:\n x: A `Tensor`.\n axis: Dimension along which to normalize. A scalar or a vector of\n integers.\n epsilon: A lower bound value for the norm. Will use `sqrt(epsilon)` as the\n divisor if `norm < sqrt(epsilon)`.\n name: A name for this operation (optional).\n dim: Deprecated alias for axis.\n\n Returns:\n A `Tensor` with the same shape as `x`.\n \"\"\"\n axis = deprecated_argument_lookup(\"axis\", axis, \"dim\", dim)\n return l2_normalize_v2(x, axis, epsilon, name)\n\n\n@tf_export(\"math.l2_normalize\", \"linalg.l2_normalize\", \"nn.l2_normalize\", v1=[])\ndef l2_normalize_v2(x, axis=None, epsilon=1e-12, name=None):\n \"\"\"Normalizes along dimension `axis` using an L2 norm.\n\n For a 1-D tensor with `axis = 0`, computes\n\n output = x / sqrt(max(sum(x**2), epsilon))\n\n For `x` with more dimensions, independently normalizes each 1-D slice along\n dimension `axis`.\n\n Args:\n x: A `Tensor`.\n axis: Dimension along which to normalize. A scalar or a vector of\n integers.\n epsilon: A lower bound value for the norm. Will use `sqrt(epsilon)` as the\n divisor if `norm < sqrt(epsilon)`.\n name: A name for this operation (optional).\n\n Returns:\n A `Tensor` with the same shape as `x`.\n \"\"\"\n with ops.name_scope(name, \"l2_normalize\", [x]) as name:\n x = ops.convert_to_tensor(x, name=\"x\")\n square_sum = math_ops.reduce_sum(math_ops.square(x), axis, keepdims=True)\n x_inv_norm = math_ops.rsqrt(math_ops.maximum(square_sum, epsilon))\n return math_ops.multiply(x, x_inv_norm, name=name)\n\n\ndef _count_nonzero(input_tensor, dtype=dtypes.int64):\n \"\"\"Same as math_ops.count_nonzero.\n\n The reduction is done in dtype, which can be faster for 32-bit dtypes.\n\n Args:\n input_tensor: numeric tensor\n dtype: reduction dtype\n\n Returns:\n number of nonzero values with type dtype\n \"\"\"\n with ops.name_scope(\"count_nonzero\", values=[input_tensor]):\n zero = array_ops.zeros([], dtype=input_tensor.dtype)\n nonzero_count = math_ops.reduce_sum(\n math_ops.cast(\n math_ops.not_equal(input_tensor, zero),\n dtype=dtype), name=\"nonzero_count\")\n return nonzero_count\n\n\n@tf_export(\"math.zero_fraction\", \"nn.zero_fraction\")\ndef zero_fraction(value, name=None):\n \"\"\"Returns the fraction of zeros in `value`.\n\n If `value` is empty, the result is `nan`.\n\n This is useful in summaries to measure and report sparsity. For example,\n\n ```python\n z = tf.nn.relu(...)\n summ = tf.compat.v1.summary.scalar('sparsity', tf.nn.zero_fraction(z))\n ```\n\n Args:\n value: A tensor of numeric type.\n name: A name for the operation (optional).\n\n Returns:\n The fraction of zeros in `value`, with type `float32`.\n \"\"\"\n with ops.name_scope(name, \"zero_fraction\", [value]):\n value = ops.convert_to_tensor(value, name=\"value\")\n size = array_ops.size(value, out_type=dtypes.int64)\n # If the count is small, we can save memory/CPU with an int32 reduction.\n num_nonzero = control_flow_ops.cond(\n size <= dtypes.int32.max,\n # pylint: disable=g-long-lambda\n true_fn=lambda: math_ops.cast(\n _count_nonzero(value, dtype=dtypes.int32),\n dtype=dtypes.int64),\n false_fn=lambda: _count_nonzero(value, dtype=dtypes.int64))\n\n with ops.name_scope(\"counts_to_fraction\"):\n num_zero = size - num_nonzero\n num_zero_float32 = math_ops.cast(num_zero, dtype=dtypes.float32)\n size_float32 = math_ops.cast(size, dtype=dtypes.float32)\n zero_fraction_float32 = num_zero_float32 / size_float32\n\n return array_ops.identity(zero_fraction_float32, \"fraction\")\n\n\n# pylint: disable=redefined-builtin\n@tf_export(v1=[\"nn.depthwise_conv2d\"])\ndef depthwise_conv2d(input,\n filter,\n strides,\n padding,\n rate=None,\n name=None,\n data_format=None,\n dilations=None):\n \"\"\"Depthwise 2-D convolution.\n\n Given a 4D input tensor ('NHWC' or 'NCHW' data formats)\n and a filter tensor of shape\n `[filter_height, filter_width, in_channels, channel_multiplier]`\n containing `in_channels` convolutional filters of depth 1, `depthwise_conv2d`\n applies a different filter to each input channel (expanding from 1 channel\n to `channel_multiplier` channels for each), then concatenates the results\n together. The output has `in_channels * channel_multiplier` channels.\n\n In detail, with the default NHWC format,\n\n output[b, i, j, k * channel_multiplier + q] = sum_{di, dj}\n filter[di, dj, k, q] * input[b, strides[1] * i + rate[0] * di,\n strides[2] * j + rate[1] * dj, k]\n\n Must have `strides[0] = strides[3] = 1`. For the most common case of the\n same horizontal and vertical strides, `strides = [1, stride, stride, 1]`.\n If any value in `rate` is greater than 1, we perform atrous depthwise\n convolution, in which case all values in the `strides` tensor must be equal\n to 1.\n\n Usage Example:\n\n >>> x = np.array([\n ... [1., 2.],\n ... [3., 4.],\n ... [5., 6.]\n ... ], dtype=np.float32).reshape((1, 3, 2, 1))\n >>> kernel = np.array([\n ... [1., 2.],\n ... [3., 4]\n ... ], dtype=np.float32).reshape((2, 1, 1, 2))\n >>> tf.compat.v1.nn.depthwise_conv2d(x, kernel, strides=[1, 1, 1, 1],\n ... padding='VALID').numpy()\n array([[[[10., 14.],\n [14., 20.]],\n [[18., 26.],\n [22., 32.]]]], dtype=float32)\n\n >>> tf.compat.v1.nn.depthwise_conv2d(x, kernel, strides=[1, 1, 1, 1],\n ... padding=[[0, 0], [1, 0], [1, 0], [0, 0]]\n ... ).numpy()\n array([[[[ 0., 0.],\n [ 3., 4.],\n [ 6., 8.]],\n [[ 0., 0.],\n [10., 14.],\n [14., 20.]],\n [[ 0., 0.],\n [18., 26.],\n [22., 32.]]]], dtype=float32)\n\n Args:\n input: 4-D with shape according to `data_format`.\n filter: 4-D with shape\n `[filter_height, filter_width, in_channels, channel_multiplier]`.\n strides: 1-D of size 4. The stride of the sliding window for each\n dimension of `input`.\n padding: Controls how to pad the image before applying the convolution. Can\n be the string `\"SAME\"` or `\"VALID\"` indicating the type of padding\n algorithm to use, or a list indicating the explicit paddings at the start\n and end of each dimension. When explicit padding is used and data_format\n is `\"NHWC\"`, this should be in the form `[[0, 0], [pad_top, pad_bottom],\n [pad_left, pad_right], [0, 0]]`. When explicit padding used and\n data_format is `\"NCHW\"`, this should be in the form `[[0, 0], [0, 0],\n [pad_top, pad_bottom], [pad_left, pad_right]]`.\n rate: 1-D of size 2. The dilation rate in which we sample input values\n across the `height` and `width` dimensions in atrous convolution. If it is\n greater than 1, then all values of strides must be 1.\n name: A name for this operation (optional).\n data_format: The data format for input. Either \"NHWC\" (default) or \"NCHW\".\n dilations: Alias of rate.\n\n Returns:\n A 4-D `Tensor` with shape according to `data_format`. E.g., for\n \"NHWC\" format, shape is\n `[batch, out_height, out_width, in_channels * channel_multiplier].`\n \"\"\"\n rate = deprecated_argument_lookup(\"dilations\", dilations, \"rate\", rate)\n with ops.name_scope(name, \"depthwise\", [input, filter]) as name:\n input = ops.convert_to_tensor(input, name=\"tensor_in\")\n filter = ops.convert_to_tensor(filter, name=\"filter_in\")\n if rate is None:\n rate = [1, 1]\n\n # Use depthwise_conv2d_native if executing on TPU.\n if device_context.enclosing_tpu_context() is not None:\n if data_format == \"NCHW\":\n dilations = [1, 1, rate[0], rate[1]]\n else:\n dilations = [1, rate[0], rate[1], 1]\n return nn_ops.depthwise_conv2d_native(\n input=input,\n filter=filter,\n strides=strides,\n padding=padding,\n data_format=data_format,\n dilations=dilations,\n name=name)\n\n def op(input_converted, _, padding):\n return nn_ops.depthwise_conv2d_native(\n input=input_converted,\n filter=filter,\n strides=strides,\n padding=padding,\n data_format=data_format,\n name=name)\n\n return nn_ops.with_space_to_batch(\n input=input,\n filter_shape=array_ops.shape(filter),\n dilation_rate=rate,\n padding=padding,\n data_format=data_format,\n op=op)\n\n\n@tf_export(\"nn.depthwise_conv2d\", v1=[])\ndef depthwise_conv2d_v2(input,\n filter,\n strides,\n padding,\n data_format=None,\n dilations=None,\n name=None):\n \"\"\"Depthwise 2-D convolution.\n\n Given a 4D input tensor ('NHWC' or 'NCHW' data formats)\n and a filter tensor of shape\n `[filter_height, filter_width, in_channels, channel_multiplier]`\n containing `in_channels` convolutional filters of depth 1, `depthwise_conv2d`\n applies a different filter to each input channel (expanding from 1 channel\n to `channel_multiplier` channels for each), then concatenates the results\n together. The output has `in_channels * channel_multiplier` channels.\n\n In detail, with the default NHWC format,\n\n output[b, i, j, k * channel_multiplier + q] = sum_{di, dj}\n filter[di, dj, k, q] * input[b, strides[1] * i + rate[0] * di,\n strides[2] * j + rate[1] * dj, k]\n\n Must have `strides[0] = strides[3] = 1`. For the most common case of the\n same horizontal and vertical strides, `strides = [1, stride, stride, 1]`.\n If any value in `rate` is greater than 1, we perform atrous depthwise\n convolution, in which case all values in the `strides` tensor must be equal\n to 1.\n\n Usage Example:\n\n >>> x = np.array([\n ... [1., 2.],\n ... [3., 4.],\n ... [5., 6.]\n ... ], dtype=np.float32).reshape((1, 3, 2, 1))\n >>> kernel = np.array([\n ... [1., 2.],\n ... [3., 4]\n ... ], dtype=np.float32).reshape((2, 1, 1, 2))\n >>> tf.nn.depthwise_conv2d(x, kernel, strides=[1, 1, 1, 1],\n ... padding='VALID').numpy()\n array([[[[10., 14.],\n [14., 20.]],\n [[18., 26.],\n [22., 32.]]]], dtype=float32)\n\n >>> tf.nn.depthwise_conv2d(x, kernel, strides=[1, 1, 1, 1],\n ... padding=[[0, 0], [1, 0], [1, 0], [0, 0]]).numpy()\n array([[[[ 0., 0.],\n [ 3., 4.],\n [ 6., 8.]],\n [[ 0., 0.],\n [10., 14.],\n [14., 20.]],\n [[ 0., 0.],\n [18., 26.],\n [22., 32.]]]], dtype=float32)\n\n Args:\n input: 4-D with shape according to `data_format`.\n filter: 4-D with shape\n `[filter_height, filter_width, in_channels, channel_multiplier]`.\n strides: 1-D of size 4. The stride of the sliding window for each\n dimension of `input`.\n padding: Controls how to pad the image before applying the convolution. Can\n be the string `\"SAME\"` or `\"VALID\"` indicating the type of padding\n algorithm to use, or a list indicating the explicit paddings at the start\n and end of each dimension. When explicit padding is used and data_format\n is `\"NHWC\"`, this should be in the form `[[0, 0], [pad_top, pad_bottom],\n [pad_left, pad_right], [0, 0]]`. When explicit padding used and\n data_format is `\"NCHW\"`, this should be in the form `[[0, 0], [0, 0],\n [pad_top, pad_bottom], [pad_left, pad_right]]`.\n data_format: The data format for input. Either \"NHWC\" (default) or \"NCHW\".\n dilations: 1-D of size 2. The dilation rate in which we sample input values\n across the `height` and `width` dimensions in atrous convolution. If it is\n greater than 1, then all values of strides must be 1.\n name: A name for this operation (optional).\n\n Returns:\n A 4-D `Tensor` with shape according to `data_format`. E.g., for\n \"NHWC\" format, shape is\n `[batch, out_height, out_width, in_channels * channel_multiplier].`\n \"\"\"\n return depthwise_conv2d(input=input,\n filter=filter,\n strides=strides,\n padding=padding,\n rate=dilations,\n name=name,\n data_format=data_format)\n\n# pylint: enable=redefined-builtin\n\n\n# pylint: disable=redefined-builtin,line-too-long\n@tf_export(v1=[\"nn.separable_conv2d\"])\ndef separable_conv2d(input,\n depthwise_filter,\n pointwise_filter,\n strides,\n padding,\n rate=None,\n name=None,\n data_format=None,\n dilations=None):\n \"\"\"2-D convolution with separable filters.\n\n Performs a depthwise convolution that acts separately on channels followed by\n a pointwise convolution that mixes channels. Note that this is separability\n between dimensions `[1, 2]` and `3`, not spatial separability between\n dimensions `1` and `2`.\n\n In detail, with the default NHWC format,\n\n output[b, i, j, k] = sum_{di, dj, q, r}\n input[b, strides[1] * i + di, strides[2] * j + dj, q] *\n depthwise_filter[di, dj, q, r] *\n pointwise_filter[0, 0, q * channel_multiplier + r, k]\n\n `strides` controls the strides for the depthwise convolution only, since\n the pointwise convolution has implicit strides of `[1, 1, 1, 1]`. Must have\n `strides[0] = strides[3] = 1`. For the most common case of the same\n horizontal and vertical strides, `strides = [1, stride, stride, 1]`.\n If any value in `rate` is greater than 1, we perform atrous depthwise\n convolution, in which case all values in the `strides` tensor must be equal\n to 1.\n\n Args:\n input: 4-D `Tensor` with shape according to `data_format`.\n depthwise_filter: 4-D `Tensor` with shape\n `[filter_height, filter_width, in_channels, channel_multiplier]`.\n Contains `in_channels` convolutional filters of depth 1.\n pointwise_filter: 4-D `Tensor` with shape\n `[1, 1, channel_multiplier * in_channels, out_channels]`. Pointwise\n filter to mix channels after `depthwise_filter` has convolved spatially.\n strides: 1-D of size 4. The strides for the depthwise convolution for\n each dimension of `input`.\n padding: Controls how to pad the image before applying the depthwise\n convolution. Can be the string `\"SAME\"` or `\"VALID\"` indicating the type\n of padding algorithm to use, or a Python list indicating the explicit\n paddings at the start and end of each dimension. When explicit padding is\n used and data_format is `\"NHWC\"`, this should be in the form `[[0, 0],\n [pad_top, pad_bottom], [pad_left, pad_right], [0, 0]]`. When explicit\n padding used and data_format is `\"NCHW\"`, this should be in the form\n `[[0, 0], [0, 0], [pad_top, pad_bottom], [pad_left, pad_right]]`.\n rate: 1-D of size 2. The dilation rate in which we sample input values\n across the `height` and `width` dimensions in atrous convolution. If it is\n greater than 1, then all values of strides must be 1.\n name: A name for this operation (optional).\n data_format: The data format for input. Either \"NHWC\" (default) or \"NCHW\".\n dilations: Alias of rate.\n\n Returns:\n A 4-D `Tensor` with shape according to 'data_format'. For\n example, with data_format=\"NHWC\", shape is [batch, out_height,\n out_width, out_channels].\n \"\"\"\n rate = deprecated_argument_lookup(\"dilations\", dilations, \"rate\", rate)\n with ops.name_scope(name, \"separable_conv2d\",\n [input, depthwise_filter, pointwise_filter]) as name:\n input = ops.convert_to_tensor(input, name=\"tensor_in\")\n depthwise_filter = ops.convert_to_tensor(\n depthwise_filter, name=\"depthwise_filter\")\n pointwise_filter = ops.convert_to_tensor(\n pointwise_filter, name=\"pointwise_filter\")\n\n pointwise_filter_shape = pointwise_filter.get_shape().with_rank(4)\n pointwise_filter_shape.dims[0].assert_is_compatible_with(1)\n pointwise_filter_shape.dims[1].assert_is_compatible_with(1)\n\n if rate is None:\n rate = [1, 1]\n\n # The layout of the ops in the graph are expected to be as follows:\n # depthwise_conv2d // Conv2D op corresponding to native depthwise conv.\n # separable_conv2d // Conv2D op corresponding to the pointwise conv.\n\n def op(input_converted, _, padding):\n return nn_ops.depthwise_conv2d_native(\n input=input_converted,\n filter=depthwise_filter,\n strides=strides,\n padding=padding,\n data_format=data_format,\n name=\"depthwise\")\n\n depthwise = nn_ops.with_space_to_batch(\n input=input,\n filter_shape=array_ops.shape(depthwise_filter),\n dilation_rate=rate,\n padding=padding,\n data_format=data_format,\n op=op)\n\n return nn_ops.conv2d(\n depthwise,\n pointwise_filter, [1, 1, 1, 1],\n padding=\"VALID\",\n data_format=data_format,\n name=name)\n\n\n@tf_export(\"nn.separable_conv2d\", v1=[])\ndef separable_conv2d_v2(\n input,\n depthwise_filter,\n pointwise_filter,\n strides,\n padding,\n data_format=None,\n dilations=None,\n name=None,\n):\n \"\"\"2-D convolution with separable filters.\n\n Performs a depthwise convolution that acts separately on channels followed by\n a pointwise convolution that mixes channels. Note that this is separability\n between dimensions `[1, 2]` and `3`, not spatial separability between\n dimensions `1` and `2`.\n\n In detail, with the default NHWC format,\n\n output[b, i, j, k] = sum_{di, dj, q, r}\n input[b, strides[1] * i + di, strides[2] * j + dj, q] *\n depthwise_filter[di, dj, q, r] *\n pointwise_filter[0, 0, q * channel_multiplier + r, k]\n\n `strides` controls the strides for the depthwise convolution only, since\n the pointwise convolution has implicit strides of `[1, 1, 1, 1]`. Must have\n `strides[0] = strides[3] = 1`. For the most common case of the same\n horizontal and vertical strides, `strides = [1, stride, stride, 1]`.\n If any value in `rate` is greater than 1, we perform atrous depthwise\n convolution, in which case all values in the `strides` tensor must be equal\n to 1.\n\n Args:\n input: 4-D `Tensor` with shape according to `data_format`.\n depthwise_filter: 4-D `Tensor` with shape `[filter_height, filter_width,\n in_channels, channel_multiplier]`. Contains `in_channels` convolutional\n filters of depth 1.\n pointwise_filter: 4-D `Tensor` with shape `[1, 1, channel_multiplier *\n in_channels, out_channels]`. Pointwise filter to mix channels after\n `depthwise_filter` has convolved spatially.\n strides: 1-D of size 4. The strides for the depthwise convolution for each\n dimension of `input`.\n padding: Controls how to pad the image before applying the depthwise\n convolution. Can be the string `\"SAME\"` or `\"VALID\"` indicating the type\n of padding algorithm to use, or a Python list indicating the explicit\n paddings at the start and end of each dimension. When explicit padding is\n used and data_format is `\"NHWC\"`, this should be in the form `[[0, 0],\n [pad_top, pad_bottom], [pad_left, pad_right], [0, 0]]`. When explicit\n padding used and data_format is `\"NCHW\"`, this should be in the form\n `[[0, 0], [0, 0], [pad_top, pad_bottom], [pad_left, pad_right]]`.\n data_format: The data format for input. Either \"NHWC\" (default) or \"NCHW\".\n dilations: 1-D of size 2. The dilation rate in which we sample input values\n across the `height` and `width` dimensions in atrous convolution. If it is\n greater than 1, then all values of strides must be 1.\n name: A name for this operation (optional).\n\n Returns:\n A 4-D `Tensor` with shape according to 'data_format'. For\n example, with data_format=\"NHWC\", shape is [batch, out_height,\n out_width, out_channels].\n \"\"\"\n return separable_conv2d(\n input,\n depthwise_filter,\n pointwise_filter,\n strides,\n padding,\n rate=dilations,\n name=name,\n data_format=data_format)\n\n# pylint: enable=redefined-builtin,line-too-long\n\n\n@tf_export(v1=[\"nn.sufficient_statistics\"])\ndef sufficient_statistics(x, axes, shift=None, keep_dims=None, name=None,\n keepdims=None):\n \"\"\"Calculate the sufficient statistics for the mean and variance of `x`.\n\n These sufficient statistics are computed using the one pass algorithm on\n an input that's optionally shifted. See:\n https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Computing_shifted_data\n\n Args:\n x: A `Tensor`.\n axes: Array of ints. Axes along which to compute mean and variance.\n shift: A `Tensor` containing the value by which to shift the data for\n numerical stability, or `None` if no shift is to be performed. A shift\n close to the true mean provides the most numerically stable results.\n keep_dims: produce statistics with the same dimensionality as the input.\n name: Name used to scope the operations that compute the sufficient stats.\n keepdims: Alias for keep_dims.\n\n Returns:\n Four `Tensor` objects of the same type as `x`:\n\n * the count (number of elements to average over).\n * the (possibly shifted) sum of the elements in the array.\n * the (possibly shifted) sum of squares of the elements in the array.\n * the shift by which the mean must be corrected or None if `shift` is None.\n \"\"\"\n axes = list(set(axes))\n keep_dims = deprecated_argument_lookup(\n \"keepdims\", keepdims, \"keep_dims\", keep_dims)\n if keep_dims is None:\n keep_dims = False\n with ops.name_scope(name, \"sufficient_statistics\", [x, shift]):\n x = ops.convert_to_tensor(x, name=\"x\")\n x_shape = x.get_shape()\n if x_shape.rank is not None and all(\n x_shape.dims[d].value is not None for d in axes):\n counts = 1\n for d in axes:\n counts *= x_shape.dims[d].value\n counts = constant_op.constant(counts, dtype=x.dtype)\n else: # shape needs to be inferred at runtime.\n x_dims = array_ops.gather(\n math_ops.cast(array_ops.shape(x), x.dtype), axes)\n counts = math_ops.reduce_prod(x_dims, name=\"count\")\n if shift is not None:\n shift = ops.convert_to_tensor(shift, name=\"shift\")\n m_ss = math_ops.subtract(x, shift)\n v_ss = math_ops.squared_difference(x, shift)\n else: # no shift.\n m_ss = x\n v_ss = math_ops.square(x)\n m_ss = math_ops.reduce_sum(m_ss, axes, keepdims=keep_dims, name=\"mean_ss\")\n v_ss = math_ops.reduce_sum(v_ss, axes, keepdims=keep_dims, name=\"var_ss\")\n return counts, m_ss, v_ss, shift\n\n\n@tf_export(\"nn.sufficient_statistics\", v1=[])\ndef sufficient_statistics_v2(x, axes, shift=None, keepdims=False, name=None):\n \"\"\"Calculate the sufficient statistics for the mean and variance of `x`.\n\n These sufficient statistics are computed using the one pass algorithm on\n an input that's optionally shifted. See:\n https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Computing_shifted_data\n\n Args:\n x: A `Tensor`.\n axes: Array of ints. Axes along which to compute mean and variance.\n shift: A `Tensor` containing the value by which to shift the data for\n numerical stability, or `None` if no shift is to be performed. A shift\n close to the true mean provides the most numerically stable results.\n keepdims: produce statistics with the same dimensionality as the input.\n name: Name used to scope the operations that compute the sufficient stats.\n\n Returns:\n Four `Tensor` objects of the same type as `x`:\n\n * the count (number of elements to average over).\n * the (possibly shifted) sum of the elements in the array.\n * the (possibly shifted) sum of squares of the elements in the array.\n * the shift by which the mean must be corrected or None if `shift` is None.\n \"\"\"\n return sufficient_statistics(\n x=x, axes=axes, shift=shift, keep_dims=keepdims, name=name)\n\n\n@tf_export(\"nn.normalize_moments\")\ndef normalize_moments(counts, mean_ss, variance_ss, shift, name=None):\n \"\"\"Calculate the mean and variance of based on the sufficient statistics.\n\n Args:\n counts: A `Tensor` containing the total count of the data (one value).\n mean_ss: A `Tensor` containing the mean sufficient statistics: the (possibly\n shifted) sum of the elements to average over.\n variance_ss: A `Tensor` containing the variance sufficient statistics: the\n (possibly shifted) squared sum of the data to compute the variance over.\n shift: A `Tensor` containing the value by which the data is shifted for\n numerical stability, or `None` if no shift was performed.\n name: Name used to scope the operations that compute the moments.\n\n Returns:\n Two `Tensor` objects: `mean` and `variance`.\n \"\"\"\n with ops.name_scope(name, \"normalize\", [counts, mean_ss, variance_ss, shift]):\n divisor = math_ops.reciprocal(counts, name=\"divisor\")\n if shift is not None:\n shifted_mean = math_ops.multiply(mean_ss, divisor, name=\"shifted_mean\")\n mean = math_ops.add(shifted_mean, shift, name=\"mean\")\n else: # no shift.\n shifted_mean = math_ops.multiply(mean_ss, divisor, name=\"mean\")\n mean = shifted_mean\n variance = math_ops.subtract(\n math_ops.multiply(variance_ss, divisor),\n math_ops.square(shifted_mean),\n name=\"variance\")\n return (mean, variance)\n\n\n@tf_export(v1=[\"nn.moments\"])\ndef moments(\n x,\n axes,\n shift=None, # pylint: disable=unused-argument\n name=None,\n keep_dims=None,\n keepdims=None):\n \"\"\"Calculate the mean and variance of `x`.\n\n The mean and variance are calculated by aggregating the contents of `x`\n across `axes`. If `x` is 1-D and `axes = [0]` this is just the mean\n and variance of a vector.\n\n Note: shift is currently not used; the true mean is computed and used.\n\n When using these moments for batch normalization (see\n `tf.nn.batch_normalization`):\n\n * for so-called \"global normalization\", used with convolutional filters with\n shape `[batch, height, width, depth]`, pass `axes=[0, 1, 2]`.\n * for simple batch normalization pass `axes=[0]` (batch only).\n\n Args:\n x: A `Tensor`.\n axes: Array of ints. Axes along which to compute mean and\n variance.\n shift: Not used in the current implementation\n name: Name used to scope the operations that compute the moments.\n keep_dims: produce moments with the same dimensionality as the input.\n keepdims: Alias to keep_dims.\n\n Returns:\n Two `Tensor` objects: `mean` and `variance`.\n \"\"\"\n keep_dims = deprecated_argument_lookup(\n \"keepdims\", keepdims, \"keep_dims\", keep_dims)\n if keep_dims is None:\n keep_dims = False\n with ops.name_scope(name, \"moments\", [x, axes]):\n # The dynamic range of fp16 is too limited to support the collection of\n # sufficient statistics. As a workaround we simply perform the operations\n # on 32-bit floats before converting the mean and variance back to fp16\n y = math_ops.cast(x, dtypes.float32) if x.dtype == dtypes.float16 else x\n # Compute true mean while keeping the dims for proper broadcasting.\n mean = math_ops.reduce_mean(y, axes, keepdims=True, name=\"mean\")\n # sample variance, not unbiased variance\n # Note: stop_gradient does not change the gradient that gets\n # backpropagated to the mean from the variance calculation,\n # because that gradient is zero\n variance = math_ops.reduce_mean(\n math_ops.squared_difference(y, array_ops.stop_gradient(mean)),\n axes,\n keepdims=True,\n name=\"variance\")\n if not keep_dims:\n mean = array_ops.squeeze(mean, axes)\n variance = array_ops.squeeze(variance, axes)\n if x.dtype == dtypes.float16:\n return (math_ops.cast(mean, dtypes.float16),\n math_ops.cast(variance, dtypes.float16))\n else:\n return (mean, variance)\n\n\n@tf_export(\"nn.moments\", v1=[])\ndef moments_v2(\n x,\n axes,\n shift=None,\n keepdims=False,\n name=None):\n \"\"\"Calculates the mean and variance of `x`.\n\n The mean and variance are calculated by aggregating the contents of `x`\n across `axes`. If `x` is 1-D and `axes = [0]` this is just the mean\n and variance of a vector.\n\n Note: shift is currently not used; the true mean is computed and used.\n\n When using these moments for batch normalization (see\n `tf.nn.batch_normalization`):\n\n * for so-called \"global normalization\", used with convolutional filters with\n shape `[batch, height, width, depth]`, pass `axes=[0, 1, 2]`.\n * for simple batch normalization pass `axes=[0]` (batch only).\n\n Args:\n x: A `Tensor`.\n axes: Array of ints. Axes along which to compute mean and\n variance.\n shift: Not used in the current implementation.\n keepdims: produce moments with the same dimensionality as the input.\n name: Name used to scope the operations that compute the moments.\n\n Returns:\n Two `Tensor` objects: `mean` and `variance`.\n \"\"\"\n return moments(x=x, axes=axes, shift=shift, name=name, keep_dims=keepdims)\n\n\n@tf_export(v1=[\"nn.weighted_moments\"])\ndef weighted_moments(x, axes, frequency_weights, name=None, keep_dims=None,\n keepdims=None):\n \"\"\"Returns the frequency-weighted mean and variance of `x`.\n\n Args:\n x: A tensor.\n axes: 1-d tensor of int32 values; these are the axes along which\n to compute mean and variance.\n frequency_weights: A tensor of positive weights which can be\n broadcast with x.\n name: Name used to scope the operation.\n keep_dims: Produce moments with the same dimensionality as the input.\n keepdims: Alias of keep_dims.\n\n Returns:\n Two tensors: `weighted_mean` and `weighted_variance`.\n \"\"\"\n keep_dims = deprecated_argument_lookup(\n \"keepdims\", keepdims, \"keep_dims\", keep_dims)\n if keep_dims is None:\n keep_dims = False\n with ops.name_scope(name, \"weighted_moments\", [x, frequency_weights, axes]):\n x = ops.convert_to_tensor(x, name=\"x\")\n frequency_weights = ops.convert_to_tensor(\n frequency_weights, name=\"frequency_weights\")\n\n # Unlike moments(), this just uses a simpler two-pass method.\n\n # See comment in moments() WRT precision; it applies here too.\n needs_cast = x.dtype == dtypes.float16\n if needs_cast:\n x = math_ops.cast(x, dtypes.float32)\n\n if frequency_weights.dtype != x.dtype:\n frequency_weights = math_ops.cast(frequency_weights, x.dtype)\n\n # Note that we use keep_dims=True for our reductions regardless of the arg;\n # this is so that the results remain broadcast-compatible with the inputs.\n weighted_input_sum = math_ops.reduce_sum(\n frequency_weights * x, axes, name=\"weighted_input_sum\", keepdims=True)\n\n # The shape of the weights isn't necessarily the same as x's\n # shape, just broadcast-compatible with it -- so this expression\n # performs broadcasting to give a per-item weight, with the same\n # shape as (frequency_weights * x). This avoids having to reason\n # through all the broadcast logic to compute a correct\n # sum_of_weights.\n broadcasted_weights = frequency_weights + array_ops.zeros_like(x)\n\n sum_of_weights = math_ops.reduce_sum(\n broadcasted_weights, axes, name=\"sum_of_weights\", keepdims=True)\n\n divisor = math_ops.reciprocal(sum_of_weights, name=\"inv_weight_sum\")\n\n weighted_mean = math_ops.multiply(weighted_input_sum, divisor)\n\n # Have the weighted mean; now on to variance:\n weighted_distsq = math_ops.reduce_sum(\n frequency_weights * math_ops.squared_difference(x, weighted_mean),\n axes,\n name=\"weighted_distsq\",\n keepdims=True)\n\n weighted_variance = math_ops.multiply(weighted_distsq, divisor)\n\n if not keep_dims:\n weighted_mean = array_ops.squeeze(weighted_mean, axis=axes)\n weighted_variance = array_ops.squeeze(\n weighted_variance, axis=axes)\n\n if needs_cast:\n weighted_mean = math_ops.cast(weighted_mean, dtypes.float16)\n weighted_variance = math_ops.cast(weighted_variance, dtypes.float16)\n\n return weighted_mean, weighted_variance\n\n\n@tf_export(\"nn.weighted_moments\", v1=[])\ndef weighted_moments_v2(x, axes, frequency_weights, keepdims=False, name=None):\n \"\"\"Returns the frequency-weighted mean and variance of `x`.\n\n Args:\n x: A tensor.\n axes: 1-d tensor of int32 values; these are the axes along which\n to compute mean and variance.\n frequency_weights: A tensor of positive weights which can be\n broadcast with x.\n keepdims: Produce moments with the same dimensionality as the input.\n name: Name used to scope the operation.\n\n Returns:\n Two tensors: `weighted_mean` and `weighted_variance`.\n \"\"\"\n return weighted_moments(\n x=x,\n axes=axes,\n frequency_weights=frequency_weights,\n name=name,\n keep_dims=keepdims)\n\n\n@tf_export(\"nn.batch_normalization\")\ndef batch_normalization(x,\n mean,\n variance,\n offset,\n scale,\n variance_epsilon,\n name=None):\n r\"\"\"Batch normalization.\n\n Normalizes a tensor by `mean` and `variance`, and applies (optionally) a\n `scale` \\\\(\\gamma\\\\) to it, as well as an `offset` \\\\(\\beta\\\\):\n\n \\\\(\\frac{\\gamma(x-\\mu)}{\\sigma}+\\beta\\\\)\n\n `mean`, `variance`, `offset` and `scale` are all expected to be of one of two\n shapes:\n\n * In all generality, they can have the same number of dimensions as the\n input `x`, with identical sizes as `x` for the dimensions that are not\n normalized over (the 'depth' dimension(s)), and dimension 1 for the\n others which are being normalized over.\n `mean` and `variance` in this case would typically be the outputs of\n `tf.nn.moments(..., keepdims=True)` during training, or running averages\n thereof during inference.\n * In the common case where the 'depth' dimension is the last dimension in\n the input tensor `x`, they may be one dimensional tensors of the same\n size as the 'depth' dimension.\n This is the case for example for the common `[batch, depth]` layout of\n fully-connected layers, and `[batch, height, width, depth]` for\n convolutions.\n `mean` and `variance` in this case would typically be the outputs of\n `tf.nn.moments(..., keepdims=False)` during training, or running averages\n thereof during inference.\n\n See equation 11 in Algorithm 2 of source: \n [Batch Normalization: Accelerating Deep Network Training by\n Reducing Internal Covariate Shift; S. Ioffe, C. Szegedy]\n (http://arxiv.org/abs/1502.03167).\n\n Args:\n x: Input `Tensor` of arbitrary dimensionality.\n mean: A mean `Tensor`.\n variance: A variance `Tensor`.\n offset: An offset `Tensor`, often denoted \\\\(\\beta\\\\) in equations, or\n None. If present, will be added to the normalized tensor.\n scale: A scale `Tensor`, often denoted \\\\(\\gamma\\\\) in equations, or\n `None`. If present, the scale is applied to the normalized tensor.\n variance_epsilon: A small float number to avoid dividing by 0.\n name: A name for this operation (optional).\n\n Returns:\n the normalized, scaled, offset tensor.\n\n References:\n Batch Normalization - Accelerating Deep Network Training by Reducing\n Internal Covariate Shift:\n [Ioffe et al., 2015](http://arxiv.org/abs/1502.03167)\n ([pdf](http://proceedings.mlr.press/v37/ioffe15.pdf))\n \"\"\"\n with ops.name_scope(name, \"batchnorm\", [x, mean, variance, scale, offset]):\n inv = math_ops.rsqrt(variance + variance_epsilon)\n if scale is not None:\n inv *= scale\n # Note: tensorflow/contrib/quantize/python/fold_batch_norms.py depends on\n # the precise order of ops that are generated by the expression below.\n return x * math_ops.cast(inv, x.dtype) + math_ops.cast(\n offset - mean * inv if offset is not None else -mean * inv, x.dtype)\n\n\n@tf_export(v1=[\"nn.fused_batch_norm\"])\ndef fused_batch_norm(\n x,\n scale,\n offset, # pylint: disable=invalid-name\n mean=None,\n variance=None,\n epsilon=0.001,\n data_format=\"NHWC\",\n is_training=True,\n name=None,\n exponential_avg_factor=1.0):\n r\"\"\"Batch normalization.\n\n\n See Source: [Batch Normalization: Accelerating Deep Network Training by\n Reducing Internal Covariate Shift; S. Ioffe, C. Szegedy]\n (http://arxiv.org/abs/1502.03167).\n\n Args:\n x: Input `Tensor` of 4 dimensions.\n scale: A `Tensor` of 1 dimension for scaling.\n offset: A `Tensor` of 1 dimension for bias.\n mean: A `Tensor` of 1 dimension for population mean. The shape and meaning\n of this argument depends on the value of is_training and\n exponential_avg_factor as follows:\n is_training==False (inference):\n Mean must be a `Tensor` of the same shape as scale containing the\n estimated population mean computed during training.\n is_training==True and exponential_avg_factor == 1.0:\n Mean must be None.\n is_training==True and exponential_avg_factor != 1.0:\n Mean must be a `Tensor` of the same shape as scale containing the\n exponential running mean.\n variance: A `Tensor` of 1 dimension for population variance. The shape and\n meaning of this argument depends on the value of is_training and\n exponential_avg_factor as follows:\n is_training==False (inference):\n Variance must be a `Tensor` of the same shape as scale containing\n the estimated population variance computed during training.\n is_training==True and exponential_avg_factor == 1.0:\n Variance must be None.\n is_training==True and exponential_avg_factor != 1.0:\n Variance must be a `Tensor` of the same shape as scale containing\n the exponential running variance.\n epsilon: A small float number added to the variance of x.\n data_format: The data format for x. Either \"NHWC\" (default) or \"NCHW\".\n is_training: A bool value to specify if the operation is used for\n training or inference.\n name: A name for this operation (optional).\n exponential_avg_factor: A float number (usually between 0 and 1) used\n for controlling the decay of the running\n population average of mean and variance.\n If set to 1.0, the current batch average is\n returned.\n\n Returns:\n y: A 4D Tensor for the normalized, scaled, offsetted x.\n running_mean: A 1D Tensor for the exponential running mean of x.\n The output value is (1 - exponential_avg_factor) * mean +\n exponential_avg_factor * batch_mean), where batch_mean\n is the mean of the current batch in x.\n running_var: A 1D Tensor for the exponential running variance\n The output value is (1 - exponential_avg_factor) * variance +\n exponential_avg_factor * batch_variance), where batch_variance\n is the variance of the current batch in x.\n\n References:\n Batch Normalization - Accelerating Deep Network Training by Reducing\n Internal Covariate Shift:\n [Ioffe et al., 2015](http://proceedings.mlr.press/v37/ioffe15.html)\n ([pdf](http://proceedings.mlr.press/v37/ioffe15.pdf))\n \"\"\"\n if is_training and exponential_avg_factor == 1.0:\n if (mean is not None) or (variance is not None):\n raise ValueError(\"Both 'mean' and 'variance' must be None when \"\n \"is_training is True and \"\n \"exponential_avg_factor == 1.0.\")\n else:\n if (mean is None) or (variance is None):\n raise ValueError(\"Both 'mean' and 'variance' must be a 1D tensor when \"\n \"is_training is False or \"\n \"exponential_avg_factor != 1.0.\")\n x = ops.convert_to_tensor(x, name=\"input\")\n scale = ops.convert_to_tensor(scale, name=\"scale\")\n offset = ops.convert_to_tensor(offset, name=\"offset\")\n if mean is None:\n mean = constant_op.constant([])\n if variance is None:\n variance = constant_op.constant([])\n\n # Set a minimum epsilon to 1.001e-5, which is a requirement by CUDNN to\n # prevent exception (see cudnn.h).\n min_epsilon = 1.001e-5\n epsilon = epsilon if epsilon > min_epsilon else min_epsilon\n\n if compat.forward_compatible(2020, 3, 6):\n y, running_mean, running_var, _, _, _ = gen_nn_ops.fused_batch_norm_v3(\n x,\n scale,\n offset,\n mean,\n variance,\n epsilon=epsilon,\n exponential_avg_factor=exponential_avg_factor,\n data_format=data_format,\n is_training=is_training,\n name=name)\n return y, running_mean, running_var\n else:\n y, running_mean, running_var, _, _, _ = gen_nn_ops.fused_batch_norm_v3(\n x,\n scale,\n offset,\n mean,\n variance,\n epsilon=epsilon,\n data_format=data_format,\n is_training=is_training,\n name=name)\n return y, running_mean, running_var\n\n\n@tf_export(v1=[\"nn.batch_norm_with_global_normalization\"])\ndef batch_norm_with_global_normalization(t=None,\n m=None,\n v=None,\n beta=None,\n gamma=None,\n variance_epsilon=None,\n scale_after_normalization=None,\n name=None,\n input=None, # pylint: disable=redefined-builtin\n mean=None,\n variance=None):\n \"\"\"Batch normalization.\n\n This op is deprecated. See `tf.nn.batch_normalization`.\n\n Args:\n t: A 4D input Tensor.\n m: A 1D mean Tensor with size matching the last dimension of t.\n This is the first output from tf.nn.moments,\n or a saved moving average thereof.\n v: A 1D variance Tensor with size matching the last dimension of t.\n This is the second output from tf.nn.moments,\n or a saved moving average thereof.\n beta: A 1D beta Tensor with size matching the last dimension of t.\n An offset to be added to the normalized tensor.\n gamma: A 1D gamma Tensor with size matching the last dimension of t.\n If \"scale_after_normalization\" is true, this tensor will be multiplied\n with the normalized tensor.\n variance_epsilon: A small float number to avoid dividing by 0.\n scale_after_normalization: A bool indicating whether the resulted tensor\n needs to be multiplied with gamma.\n name: A name for this operation (optional).\n input: Alias for t.\n mean: Alias for m.\n variance: Alias for v.\n\n Returns:\n A batch-normalized `t`.\n\n References:\n Batch Normalization - Accelerating Deep Network Training by Reducing\n Internal Covariate Shift:\n [Ioffe et al., 2015](http://proceedings.mlr.press/v37/ioffe15.html)\n ([pdf](http://proceedings.mlr.press/v37/ioffe15.pdf))\n \"\"\"\n t = deprecated_argument_lookup(\"input\", input, \"t\", t)\n m = deprecated_argument_lookup(\"mean\", mean, \"m\", m)\n v = deprecated_argument_lookup(\"variance\", variance, \"v\", v)\n return batch_normalization(t, m, v, beta, gamma if scale_after_normalization\n else None, variance_epsilon, name)\n\n\n# pylint: disable=redefined-builtin,line-too-long\n@tf_export(\"nn.batch_norm_with_global_normalization\", v1=[])\ndef batch_norm_with_global_normalization_v2(input,\n mean,\n variance,\n beta,\n gamma,\n variance_epsilon,\n scale_after_normalization,\n name=None):\n \"\"\"Batch normalization.\n\n This op is deprecated. See `tf.nn.batch_normalization`.\n\n Args:\n input: A 4D input Tensor.\n mean: A 1D mean Tensor with size matching the last dimension of t.\n This is the first output from tf.nn.moments,\n or a saved moving average thereof.\n variance: A 1D variance Tensor with size matching the last dimension of t.\n This is the second output from tf.nn.moments,\n or a saved moving average thereof.\n beta: A 1D beta Tensor with size matching the last dimension of t.\n An offset to be added to the normalized tensor.\n gamma: A 1D gamma Tensor with size matching the last dimension of t.\n If \"scale_after_normalization\" is true, this tensor will be multiplied\n with the normalized tensor.\n variance_epsilon: A small float number to avoid dividing by 0.\n scale_after_normalization: A bool indicating whether the resulted tensor\n needs to be multiplied with gamma.\n name: A name for this operation (optional).\n\n Returns:\n A batch-normalized `t`.\n\n References:\n Batch Normalization - Accelerating Deep Network Training by Reducing Internal Covariate Shift:\n [Ioffe et al., 2015](http://proceedings.mlr.press/v37/ioffe15.html)\n ([pdf](http://proceedings.mlr.press/v37/ioffe15.pdf))\n \"\"\"\n return batch_norm_with_global_normalization(t=input,\n m=mean,\n v=variance,\n beta=beta,\n gamma=gamma,\n variance_epsilon=variance_epsilon,\n scale_after_normalization=scale_after_normalization,\n name=name)\n\n# pylint: enable=redefined-builtin,line-too-long\n\n\ndef _sum_rows(x):\n \"\"\"Returns a vector summing up each row of the matrix x.\"\"\"\n # _sum_rows(x) is equivalent to math_ops.reduce_sum(x, 1) when x is\n # a matrix. The gradient of _sum_rows(x) is more efficient than\n # reduce_sum(x, 1)'s gradient in today's implementation. Therefore,\n # we use _sum_rows(x) in the nce_loss() computation since the loss\n # is mostly used for training.\n cols = array_ops.shape(x)[1]\n ones_shape = array_ops.stack([cols, 1])\n ones = array_ops.ones(ones_shape, x.dtype)\n return array_ops.reshape(math_ops.matmul(x, ones), [-1])\n\n\ndef _compute_sampled_logits(weights,\n biases,\n labels,\n inputs,\n num_sampled,\n num_classes,\n num_true=1,\n sampled_values=None,\n subtract_log_q=True,\n remove_accidental_hits=False,\n partition_strategy=\"mod\",\n name=None,\n seed=None):\n \"\"\"Helper function for nce_loss and sampled_softmax_loss functions.\n\n Computes sampled output training logits and labels suitable for implementing\n e.g. noise-contrastive estimation (see nce_loss) or sampled softmax (see\n sampled_softmax_loss).\n\n Note: In the case where num_true > 1, we assign to each target class\n the target probability 1 / num_true so that the target probabilities\n sum to 1 per-example.\n\n Args:\n weights: A `Tensor` of shape `[num_classes, dim]`, or a list of `Tensor`\n objects whose concatenation along dimension 0 has shape\n `[num_classes, dim]`. The (possibly-partitioned) class embeddings.\n biases: A `Tensor` of shape `[num_classes]`. The (possibly-partitioned)\n class biases.\n labels: A `Tensor` of type `int64` and shape `[batch_size,\n num_true]`. The target classes. Note that this format differs from\n the `labels` argument of `nn.softmax_cross_entropy_with_logits`.\n inputs: A `Tensor` of shape `[batch_size, dim]`. The forward\n activations of the input network.\n num_sampled: An `int`. The number of classes to randomly sample per batch.\n num_classes: An `int`. The number of possible classes.\n num_true: An `int`. The number of target classes per training example.\n sampled_values: a tuple of (`sampled_candidates`, `true_expected_count`,\n `sampled_expected_count`) returned by a `*_candidate_sampler` function.\n (if None, we default to `log_uniform_candidate_sampler`)\n subtract_log_q: A `bool`. whether to subtract the log expected count of\n the labels in the sample to get the logits of the true labels.\n Default is True. Turn off for Negative Sampling.\n remove_accidental_hits: A `bool`. whether to remove \"accidental hits\"\n where a sampled class equals one of the target classes. Default is\n False.\n partition_strategy: A string specifying the partitioning strategy, relevant\n if `len(weights) > 1`. Currently `\"div\"` and `\"mod\"` are supported.\n Default is `\"mod\"`. See `tf.nn.embedding_lookup` for more details.\n name: A name for the operation (optional).\n seed: random seed for candidate sampling. Default to None, which doesn't set\n the op-level random seed for candidate sampling.\n Returns:\n out_logits: `Tensor` object with shape\n `[batch_size, num_true + num_sampled]`, for passing to either\n `nn.sigmoid_cross_entropy_with_logits` (NCE) or\n `nn.softmax_cross_entropy_with_logits` (sampled softmax).\n out_labels: A Tensor object with the same shape as `out_logits`.\n \"\"\"\n\n if isinstance(weights, variables.PartitionedVariable):\n weights = list(weights)\n if not isinstance(weights, list):\n weights = [weights]\n\n with ops.name_scope(name, \"compute_sampled_logits\",\n weights + [biases, inputs, labels]):\n if labels.dtype != dtypes.int64:\n labels = math_ops.cast(labels, dtypes.int64)\n labels_flat = array_ops.reshape(labels, [-1])\n\n # Sample the negative labels.\n # sampled shape: [num_sampled] tensor\n # true_expected_count shape = [batch_size, 1] tensor\n # sampled_expected_count shape = [num_sampled] tensor\n if sampled_values is None:\n sampled_values = candidate_sampling_ops.log_uniform_candidate_sampler(\n true_classes=labels,\n num_true=num_true,\n num_sampled=num_sampled,\n unique=True,\n range_max=num_classes,\n seed=seed)\n # NOTE: pylint cannot tell that 'sampled_values' is a sequence\n # pylint: disable=unpacking-non-sequence\n sampled, true_expected_count, sampled_expected_count = (\n array_ops.stop_gradient(s) for s in sampled_values)\n # pylint: enable=unpacking-non-sequence\n sampled = math_ops.cast(sampled, dtypes.int64)\n\n # labels_flat is a [batch_size * num_true] tensor\n # sampled is a [num_sampled] int tensor\n all_ids = array_ops.concat([labels_flat, sampled], 0)\n\n # Retrieve the true weights and the logits of the sampled weights.\n\n # weights shape is [num_classes, dim]\n all_w = embedding_ops.embedding_lookup(\n weights, all_ids, partition_strategy=partition_strategy)\n if all_w.dtype != inputs.dtype:\n all_w = math_ops.cast(all_w, inputs.dtype)\n\n # true_w shape is [batch_size * num_true, dim]\n true_w = array_ops.slice(all_w, [0, 0],\n array_ops.stack(\n [array_ops.shape(labels_flat)[0], -1]))\n\n sampled_w = array_ops.slice(\n all_w, array_ops.stack([array_ops.shape(labels_flat)[0], 0]), [-1, -1])\n # inputs has shape [batch_size, dim]\n # sampled_w has shape [num_sampled, dim]\n # Apply X*W', which yields [batch_size, num_sampled]\n sampled_logits = math_ops.matmul(inputs, sampled_w, transpose_b=True)\n\n # Retrieve the true and sampled biases, compute the true logits, and\n # add the biases to the true and sampled logits.\n all_b = embedding_ops.embedding_lookup(\n biases, all_ids, partition_strategy=partition_strategy)\n if all_b.dtype != inputs.dtype:\n all_b = math_ops.cast(all_b, inputs.dtype)\n # true_b is a [batch_size * num_true] tensor\n # sampled_b is a [num_sampled] float tensor\n true_b = array_ops.slice(all_b, [0], array_ops.shape(labels_flat))\n sampled_b = array_ops.slice(all_b, array_ops.shape(labels_flat), [-1])\n\n # inputs shape is [batch_size, dim]\n # true_w shape is [batch_size * num_true, dim]\n # row_wise_dots is [batch_size, num_true, dim]\n dim = array_ops.shape(true_w)[1:2]\n new_true_w_shape = array_ops.concat([[-1, num_true], dim], 0)\n row_wise_dots = math_ops.multiply(\n array_ops.expand_dims(inputs, 1),\n array_ops.reshape(true_w, new_true_w_shape))\n # We want the row-wise dot plus biases which yields a\n # [batch_size, num_true] tensor of true_logits.\n dots_as_matrix = array_ops.reshape(row_wise_dots,\n array_ops.concat([[-1], dim], 0))\n true_logits = array_ops.reshape(_sum_rows(dots_as_matrix), [-1, num_true])\n true_b = array_ops.reshape(true_b, [-1, num_true])\n true_logits += true_b\n sampled_logits += sampled_b\n\n if remove_accidental_hits:\n acc_hits = candidate_sampling_ops.compute_accidental_hits(\n labels, sampled, num_true=num_true)\n acc_indices, acc_ids, acc_weights = acc_hits\n\n # This is how SparseToDense expects the indices.\n acc_indices_2d = array_ops.reshape(acc_indices, [-1, 1])\n acc_ids_2d_int32 = array_ops.reshape(\n math_ops.cast(acc_ids, dtypes.int32), [-1, 1])\n sparse_indices = array_ops.concat([acc_indices_2d, acc_ids_2d_int32], 1,\n \"sparse_indices\")\n # Create sampled_logits_shape = [batch_size, num_sampled]\n sampled_logits_shape = array_ops.concat(\n [array_ops.shape(labels)[:1],\n array_ops.expand_dims(num_sampled, 0)], 0)\n if sampled_logits.dtype != acc_weights.dtype:\n acc_weights = math_ops.cast(acc_weights, sampled_logits.dtype)\n sampled_logits += gen_sparse_ops.sparse_to_dense(\n sparse_indices,\n sampled_logits_shape,\n acc_weights,\n default_value=0.0,\n validate_indices=False)\n\n if subtract_log_q:\n # Subtract log of Q(l), prior probability that l appears in sampled.\n true_logits -= math_ops.log(true_expected_count)\n sampled_logits -= math_ops.log(sampled_expected_count)\n\n # Construct output logits and labels. The true labels/logits start at col 0.\n out_logits = array_ops.concat([true_logits, sampled_logits], 1)\n\n # true_logits is a float tensor, ones_like(true_logits) is a float\n # tensor of ones. We then divide by num_true to ensure the per-example\n # labels sum to 1.0, i.e. form a proper probability distribution.\n out_labels = array_ops.concat([\n array_ops.ones_like(true_logits) / num_true,\n array_ops.zeros_like(sampled_logits)\n ], 1)\n\n return out_logits, out_labels\n\n\n@tf_export(\"nn.nce_loss\", v1=[])\ndef nce_loss_v2(weights,\n biases,\n labels,\n inputs,\n num_sampled,\n num_classes,\n num_true=1,\n sampled_values=None,\n remove_accidental_hits=False,\n name=\"nce_loss\"):\n \"\"\"Computes and returns the noise-contrastive estimation training loss.\n\n See [Noise-contrastive estimation: A new estimation principle for\n unnormalized statistical\n models](http://www.jmlr.org/proceedings/papers/v9/gutmann10a/gutmann10a.pdf).\n Also see our [Candidate Sampling Algorithms\n Reference](https://www.tensorflow.org/extras/candidate_sampling.pdf)\n\n A common use case is to use this method for training, and calculate the full\n sigmoid loss for evaluation or inference as in the following example:\n\n ```python\n if mode == \"train\":\n loss = tf.nn.nce_loss(\n weights=weights,\n biases=biases,\n labels=labels,\n inputs=inputs,\n ...)\n elif mode == \"eval\":\n logits = tf.matmul(inputs, tf.transpose(weights))\n logits = tf.nn.bias_add(logits, biases)\n labels_one_hot = tf.one_hot(labels, n_classes)\n loss = tf.nn.sigmoid_cross_entropy_with_logits(\n labels=labels_one_hot,\n logits=logits)\n loss = tf.reduce_sum(loss, axis=1)\n ```\n\n Note: when doing embedding lookup on `weights` and `bias`, \"div\" partition\n strategy will be used. Support for other partition strategy will be added\n later.\n\n Note: By default this uses a log-uniform (Zipfian) distribution for sampling,\n so your labels must be sorted in order of decreasing frequency to achieve\n good results. For more details, see\n `tf.random.log_uniform_candidate_sampler`.\n\n Note: In the case where `num_true` > 1, we assign to each target class\n the target probability 1 / `num_true` so that the target probabilities\n sum to 1 per-example.\n\n Note: It would be useful to allow a variable number of target classes per\n example. We hope to provide this functionality in a future release.\n For now, if you have a variable number of target classes, you can pad them\n out to a constant number by either repeating them or by padding\n with an otherwise unused class.\n\n Args:\n weights: A `Tensor` of shape `[num_classes, dim]`, or a list of `Tensor`\n objects whose concatenation along dimension 0 has shape [num_classes,\n dim]. The (possibly-partitioned) class embeddings.\n biases: A `Tensor` of shape `[num_classes]`. The class biases.\n labels: A `Tensor` of type `int64` and shape `[batch_size, num_true]`. The\n target classes.\n inputs: A `Tensor` of shape `[batch_size, dim]`. The forward activations of\n the input network.\n num_sampled: An `int`. The number of negative classes to randomly sample\n per batch. This single sample of negative classes is evaluated for each\n element in the batch.\n num_classes: An `int`. The number of possible classes.\n num_true: An `int`. The number of target classes per training example.\n sampled_values: a tuple of (`sampled_candidates`, `true_expected_count`,\n `sampled_expected_count`) returned by a `*_candidate_sampler` function.\n (if None, we default to `log_uniform_candidate_sampler`)\n remove_accidental_hits: A `bool`. Whether to remove \"accidental hits\"\n where a sampled class equals one of the target classes. If set to `True`,\n this is a \"Sampled Logistic\" loss instead of NCE, and we are learning to\n generate log-odds instead of log probabilities. See our [Candidate\n Sampling Algorithms Reference]\n (https://www.tensorflow.org/extras/candidate_sampling.pdf). Default is\n False.\n name: A name for the operation (optional).\n\n Returns:\n A `batch_size` 1-D tensor of per-example NCE losses.\n \"\"\"\n # TODO(yuefengz): get partition_strategy from either variables or distribution\n # strategies.\n return nce_loss(\n weights,\n biases,\n labels,\n inputs,\n num_sampled,\n num_classes,\n num_true=num_true,\n sampled_values=sampled_values,\n remove_accidental_hits=remove_accidental_hits,\n partition_strategy=\"div\",\n name=name)\n\n\n@tf_export(v1=[\"nn.nce_loss\"])\ndef nce_loss(weights,\n biases,\n labels,\n inputs,\n num_sampled,\n num_classes,\n num_true=1,\n sampled_values=None,\n remove_accidental_hits=False,\n partition_strategy=\"mod\",\n name=\"nce_loss\"):\n \"\"\"Computes and returns the noise-contrastive estimation training loss.\n\n A common use case is to use this method for training, and calculate the full\n sigmoid loss for evaluation or inference. In this case, you must set\n `partition_strategy=\"div\"` for the two losses to be consistent, as in the\n following example:\n\n ```python\n if mode == \"train\":\n loss = tf.nn.nce_loss(\n weights=weights,\n biases=biases,\n labels=labels,\n inputs=inputs,\n ...,\n partition_strategy=\"div\")\n elif mode == \"eval\":\n logits = tf.matmul(inputs, tf.transpose(weights))\n logits = tf.nn.bias_add(logits, biases)\n labels_one_hot = tf.one_hot(labels, n_classes)\n loss = tf.nn.sigmoid_cross_entropy_with_logits(\n labels=labels_one_hot,\n logits=logits)\n loss = tf.reduce_sum(loss, axis=1)\n ```\n\n Note: By default this uses a log-uniform (Zipfian) distribution for sampling,\n so your labels must be sorted in order of decreasing frequency to achieve\n good results. For more details, see\n `tf.random.log_uniform_candidate_sampler`.\n\n Note: In the case where `num_true` > 1, we assign to each target class\n the target probability 1 / `num_true` so that the target probabilities\n sum to 1 per-example.\n\n Note: It would be useful to allow a variable number of target classes per\n example. We hope to provide this functionality in a future release.\n For now, if you have a variable number of target classes, you can pad them\n out to a constant number by either repeating them or by padding\n with an otherwise unused class.\n\n Args:\n weights: A `Tensor` of shape `[num_classes, dim]`, or a list of `Tensor`\n objects whose concatenation along dimension 0 has shape\n [num_classes, dim]. The (possibly-partitioned) class embeddings.\n biases: A `Tensor` of shape `[num_classes]`. The class biases.\n labels: A `Tensor` of type `int64` and shape `[batch_size,\n num_true]`. The target classes.\n inputs: A `Tensor` of shape `[batch_size, dim]`. The forward\n activations of the input network.\n num_sampled: An `int`. The number of negative classes to randomly sample\n per batch. This single sample of negative classes is evaluated for each\n element in the batch.\n num_classes: An `int`. The number of possible classes.\n num_true: An `int`. The number of target classes per training example.\n sampled_values: a tuple of (`sampled_candidates`, `true_expected_count`,\n `sampled_expected_count`) returned by a `*_candidate_sampler` function.\n (if None, we default to `log_uniform_candidate_sampler`)\n remove_accidental_hits: A `bool`. Whether to remove \"accidental hits\"\n where a sampled class equals one of the target classes. If set to\n `True`, this is a \"Sampled Logistic\" loss instead of NCE, and we are\n learning to generate log-odds instead of log probabilities. See\n our Candidate Sampling Algorithms Reference\n ([pdf](https://www.tensorflow.org/extras/candidate_sampling.pdf)).\n Default is False.\n partition_strategy: A string specifying the partitioning strategy, relevant\n if `len(weights) > 1`. Currently `\"div\"` and `\"mod\"` are supported.\n Default is `\"mod\"`. See `tf.nn.embedding_lookup` for more details.\n name: A name for the operation (optional).\n\n Returns:\n A `batch_size` 1-D tensor of per-example NCE losses.\n\n References:\n Noise-contrastive estimation - A new estimation principle for unnormalized\n statistical models:\n [Gutmann et al., 2010](http://proceedings.mlr.press/v9/gutmann10a)\n ([pdf](http://proceedings.mlr.press/v9/gutmann10a/gutmann10a.pdf))\n \"\"\"\n logits, labels = _compute_sampled_logits(\n weights=weights,\n biases=biases,\n labels=labels,\n inputs=inputs,\n num_sampled=num_sampled,\n num_classes=num_classes,\n num_true=num_true,\n sampled_values=sampled_values,\n subtract_log_q=True,\n remove_accidental_hits=remove_accidental_hits,\n partition_strategy=partition_strategy,\n name=name)\n sampled_losses = sigmoid_cross_entropy_with_logits(\n labels=labels, logits=logits, name=\"sampled_losses\")\n # sampled_losses is batch_size x {true_loss, sampled_losses...}\n # We sum out true and sampled losses.\n return _sum_rows(sampled_losses)\n\n\n@tf_export(\"nn.sampled_softmax_loss\", v1=[])\ndef sampled_softmax_loss_v2(weights,\n biases,\n labels,\n inputs,\n num_sampled,\n num_classes,\n num_true=1,\n sampled_values=None,\n remove_accidental_hits=True,\n seed=None,\n name=\"sampled_softmax_loss\"):\n \"\"\"Computes and returns the sampled softmax training loss.\n\n This is a faster way to train a softmax classifier over a huge number of\n classes.\n\n This operation is for training only. It is generally an underestimate of\n the full softmax loss.\n\n A common use case is to use this method for training, and calculate the full\n sigmoid loss for evaluation or inference as in the following example:\n\n ```python\n if mode == \"train\":\n loss = tf.nn.sampled_softmax_loss(\n weights=weights,\n biases=biases,\n labels=labels,\n inputs=inputs,\n ...)\n elif mode == \"eval\":\n logits = tf.matmul(inputs, tf.transpose(weights))\n logits = tf.nn.bias_add(logits, biases)\n labels_one_hot = tf.one_hot(labels, n_classes)\n loss = tf.nn.softmax_cross_entropy_with_logits(\n labels=labels_one_hot,\n logits=logits)\n ```\n\n See our [Candidate Sampling Algorithms Reference]\n (https://www.tensorflow.org/extras/candidate_sampling.pdf)\n\n Also see Section 3 of [Jean et al., 2014](http://arxiv.org/abs/1412.2007)\n ([pdf](http://arxiv.org/pdf/1412.2007.pdf)) for the math.\n\n Note: when doing embedding lookup on `weights` and `bias`, \"div\" partition\n strategy will be used. Support for other partition strategy will be added\n later.\n\n Args:\n weights: A `Tensor` of shape `[num_classes, dim]`, or a list of `Tensor`\n objects whose concatenation along dimension 0 has shape [num_classes,\n dim]. The (possibly-sharded) class embeddings.\n biases: A `Tensor` of shape `[num_classes]`. The class biases.\n labels: A `Tensor` of type `int64` and shape `[batch_size, num_true]`. The\n target classes. Note that this format differs from the `labels` argument\n of `nn.softmax_cross_entropy_with_logits`.\n inputs: A `Tensor` of shape `[batch_size, dim]`. The forward activations of\n the input network.\n num_sampled: An `int`. The number of classes to randomly sample per batch.\n num_classes: An `int`. The number of possible classes.\n num_true: An `int`. The number of target classes per training example.\n sampled_values: a tuple of (`sampled_candidates`, `true_expected_count`,\n `sampled_expected_count`) returned by a `*_candidate_sampler` function.\n (if None, we default to `log_uniform_candidate_sampler`)\n remove_accidental_hits: A `bool`. whether to remove \"accidental hits\"\n where a sampled class equals one of the target classes. Default is True.\n seed: random seed for candidate sampling. Default to None, which doesn't set\n the op-level random seed for candidate sampling.\n name: A name for the operation (optional).\n\n Returns:\n A `batch_size` 1-D tensor of per-example sampled softmax losses.\n\n \"\"\"\n return sampled_softmax_loss(\n weights,\n biases,\n labels,\n inputs,\n num_sampled,\n num_classes,\n num_true=num_true,\n sampled_values=sampled_values,\n remove_accidental_hits=remove_accidental_hits,\n partition_strategy=\"div\",\n name=name,\n seed=seed)\n\n\n@tf_export(v1=[\"nn.sampled_softmax_loss\"])\ndef sampled_softmax_loss(weights,\n biases,\n labels,\n inputs,\n num_sampled,\n num_classes,\n num_true=1,\n sampled_values=None,\n remove_accidental_hits=True,\n partition_strategy=\"mod\",\n name=\"sampled_softmax_loss\",\n seed=None):\n \"\"\"Computes and returns the sampled softmax training loss.\n\n This is a faster way to train a softmax classifier over a huge number of\n classes.\n\n This operation is for training only. It is generally an underestimate of\n the full softmax loss.\n\n A common use case is to use this method for training, and calculate the full\n softmax loss for evaluation or inference. In this case, you must set\n `partition_strategy=\"div\"` for the two losses to be consistent, as in the\n following example:\n\n ```python\n if mode == \"train\":\n loss = tf.nn.sampled_softmax_loss(\n weights=weights,\n biases=biases,\n labels=labels,\n inputs=inputs,\n ...,\n partition_strategy=\"div\")\n elif mode == \"eval\":\n logits = tf.matmul(inputs, tf.transpose(weights))\n logits = tf.nn.bias_add(logits, biases)\n labels_one_hot = tf.one_hot(labels, n_classes)\n loss = tf.nn.softmax_cross_entropy_with_logits(\n labels=labels_one_hot,\n logits=logits)\n ```\n\n See our Candidate Sampling Algorithms Reference\n ([pdf](https://www.tensorflow.org/extras/candidate_sampling.pdf)).\n Also see Section 3 of (Jean et al., 2014) for the math.\n\n Args:\n weights: A `Tensor` of shape `[num_classes, dim]`, or a list of `Tensor`\n objects whose concatenation along dimension 0 has shape\n [num_classes, dim]. The (possibly-sharded) class embeddings.\n biases: A `Tensor` of shape `[num_classes]`. The class biases.\n labels: A `Tensor` of type `int64` and shape `[batch_size,\n num_true]`. The target classes. Note that this format differs from\n the `labels` argument of `nn.softmax_cross_entropy_with_logits`.\n inputs: A `Tensor` of shape `[batch_size, dim]`. The forward\n activations of the input network.\n num_sampled: An `int`. The number of classes to randomly sample per batch.\n num_classes: An `int`. The number of possible classes.\n num_true: An `int`. The number of target classes per training example.\n sampled_values: a tuple of (`sampled_candidates`, `true_expected_count`,\n `sampled_expected_count`) returned by a `*_candidate_sampler` function.\n (if None, we default to `log_uniform_candidate_sampler`)\n remove_accidental_hits: A `bool`. whether to remove \"accidental hits\"\n where a sampled class equals one of the target classes. Default is\n True.\n partition_strategy: A string specifying the partitioning strategy, relevant\n if `len(weights) > 1`. Currently `\"div\"` and `\"mod\"` are supported.\n Default is `\"mod\"`. See `tf.nn.embedding_lookup` for more details.\n name: A name for the operation (optional).\n seed: random seed for candidate sampling. Default to None, which doesn't set\n the op-level random seed for candidate sampling.\n\n Returns:\n A `batch_size` 1-D tensor of per-example sampled softmax losses.\n\n References:\n On Using Very Large Target Vocabulary for Neural Machine Translation:\n [Jean et al., 2014]\n (https://aclanthology.coli.uni-saarland.de/papers/P15-1001/p15-1001)\n ([pdf](http://aclweb.org/anthology/P15-1001))\n \"\"\"\n logits, labels = _compute_sampled_logits(\n weights=weights,\n biases=biases,\n labels=labels,\n inputs=inputs,\n num_sampled=num_sampled,\n num_classes=num_classes,\n num_true=num_true,\n sampled_values=sampled_values,\n subtract_log_q=True,\n remove_accidental_hits=remove_accidental_hits,\n partition_strategy=partition_strategy,\n name=name,\n seed=seed)\n labels = array_ops.stop_gradient(labels, name=\"labels_stop_gradient\")\n sampled_losses = nn_ops.softmax_cross_entropy_with_logits_v2(\n labels=labels, logits=logits)\n # sampled_losses is a [batch_size] tensor.\n return sampled_losses\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\"\"\"Test cases for ternary operators.\"\"\"\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\nimport scipy.special as sps\n\nfrom tensorflow.compiler.tests import xla_test\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 gen_math_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.platform import googletest\n\n\nclass TernaryOpsTest(xla_test.XLATestCase, parameterized.TestCase):\n\n def _testTernary(self, op, a, b, c, expected, rtol=1e-3, atol=1e-6):\n with self.session() as session:\n with self.test_scope():\n pa = array_ops.placeholder(dtypes.as_dtype(a.dtype), a.shape, name=\"a\")\n pb = array_ops.placeholder(dtypes.as_dtype(b.dtype), b.shape, name=\"b\")\n pc = array_ops.placeholder(dtypes.as_dtype(c.dtype), c.shape, name=\"c\")\n output = op(pa, pb, pc)\n result = session.run(output, {pa: a, pb: b, pc: c})\n self.assertAllClose(result, expected, rtol=rtol, atol=atol)\n return result\n\n @parameterized.parameters(\n {'start': 1, 'end': 2, 'num': 1},\n {'start': 1, 'end': 4, 'num': 3},\n {'start': 0, 'end': 41, 'num': 42})\n @test_util.disable_mlir_bridge('Requires dynamic shape handling')\n def testLinspace(self, start, end, num):\n expected = np.linspace(start, end, num, dtype=np.float32)\n result = self._testTernary(\n math_ops.linspace,\n np.float32(start),\n np.float32(end),\n np.int32(num),\n expected)\n # According to linspace spec, start has to be the first element and end has\n # to be last element.\n self.assertEqual(result[-1], expected[-1])\n self.assertEqual(result[0], expected[0])\n\n def testRange(self):\n self._testTernary(\n math_ops.range,\n np.int32(1),\n np.int32(2),\n np.int32(1),\n expected=np.array([1], dtype=np.int32))\n self._testTernary(\n math_ops.range,\n np.int32(1),\n np.int32(7),\n np.int32(2),\n expected=np.array([1, 3, 5], dtype=np.int32))\n\n @test_util.disable_mlir_bridge('TODO(b/155949336)')\n def testSelect(self):\n for dtype in self.numeric_types:\n self._testTernary(\n array_ops.where,\n np.array(False),\n np.array(2, dtype=dtype),\n np.array(7, dtype=dtype),\n expected=np.array(7, dtype=dtype))\n\n self._testTernary(\n array_ops.where,\n np.array(True),\n np.array([1, 2, 3, 4], dtype=dtype),\n np.array([5, 6, 7, 8], dtype=dtype),\n expected=np.array([1, 2, 3, 4], dtype=dtype))\n\n self._testTernary(\n array_ops.where,\n np.array(False),\n np.array([[1, 2], [3, 4], [5, 6]], dtype=dtype),\n np.array([[7, 8], [9, 10], [11, 12]], dtype=dtype),\n expected=np.array([[7, 8], [9, 10], [11, 12]], dtype=dtype))\n\n self._testTernary(\n array_ops.where,\n np.array([0, 1, 1, 0], dtype=np.bool),\n np.array([1, 2, 3, 4], dtype=dtype),\n np.array([5, 6, 7, 8], dtype=dtype),\n expected=np.array([5, 2, 3, 8], dtype=dtype))\n\n self._testTernary(\n array_ops.where,\n np.array([0, 1, 0], dtype=np.bool),\n np.array([[1, 2], [3, 4], [5, 6]], dtype=dtype),\n np.array([[7, 8], [9, 10], [11, 12]], dtype=dtype),\n expected=np.array([[7, 8], [3, 4], [11, 12]], dtype=dtype))\n\n def testSelectV2(self):\n for dtype in self.numeric_types:\n self._testTernary(\n array_ops.where_v2,\n np.array(False),\n np.array(2, dtype=dtype),\n np.array(7, dtype=dtype),\n expected=np.array(7, dtype=dtype))\n\n self._testTernary(\n array_ops.where_v2,\n np.array(True),\n np.array([1, 2, 3, 4], dtype=dtype),\n np.array([5, 6, 7, 8], dtype=dtype),\n expected=np.array([1, 2, 3, 4], dtype=dtype))\n\n self._testTernary(\n array_ops.where_v2,\n np.array(False),\n np.array([[1, 2], [3, 4], [5, 6]], dtype=dtype),\n np.array([[7, 8], [9, 10], [11, 12]], dtype=dtype),\n expected=np.array([[7, 8], [9, 10], [11, 12]], dtype=dtype))\n\n self._testTernary(\n array_ops.where_v2,\n np.array([0, 1, 1, 0], dtype=np.bool),\n np.array([1, 2, 3, 4], dtype=dtype),\n np.array([5, 6, 7, 8], dtype=dtype),\n expected=np.array([5, 2, 3, 8], dtype=dtype))\n\n # Broadcast the condition\n self._testTernary(\n array_ops.where_v2,\n np.array([0, 1], dtype=np.bool),\n np.array([[1, 2], [3, 4], [5, 6]], dtype=dtype),\n np.array([[7, 8], [9, 10], [11, 12]], dtype=dtype),\n expected=np.array([[7, 2], [9, 4], [11, 6]], dtype=dtype))\n\n # Broadcast the then branch to the else\n self._testTernary(\n array_ops.where_v2,\n np.array([[0, 1], [1, 0], [1, 1]], dtype=np.bool),\n np.array([[1, 2]], dtype=dtype),\n np.array([[7, 8], [9, 10], [11, 12]], dtype=dtype),\n expected=np.array([[7, 2], [1, 10], [1, 2]], dtype=dtype))\n\n # Broadcast the else branch to the then\n self._testTernary(\n array_ops.where_v2,\n np.array([[1, 0], [0, 1], [0, 0]], dtype=np.bool),\n np.array([[7, 8], [9, 10], [11, 12]], dtype=dtype),\n np.array([[1, 2]], dtype=dtype),\n expected=np.array([[7, 2], [1, 10], [1, 2]], dtype=dtype))\n\n # Broadcast the then/else branches to the condition\n self._testTernary(\n array_ops.where_v2,\n np.array([[1, 0], [0, 1], [1, 1]], dtype=np.bool),\n np.array(7, dtype=dtype),\n np.array(8, dtype=dtype),\n expected=np.array([[7, 8], [8, 7], [7, 7]], dtype=dtype))\n self._testTernary(\n array_ops.where_v2,\n np.array([[1, 0], [0, 1], [0, 0]], dtype=np.bool),\n np.array(7, dtype=dtype),\n np.array([8, 9], dtype=dtype),\n expected=np.array([[7, 9], [8, 7], [8, 9]], dtype=dtype))\n\n @test_util.disable_mlir_bridge('TODO(b/155097273)')\n def testSlice(self):\n for dtype in self.numeric_types:\n self._testTernary(\n array_ops.slice,\n np.array([[], [], []], dtype=dtype),\n np.array([1, 0], dtype=np.int32),\n np.array([2, 0], dtype=np.int32),\n expected=np.array([[], []], dtype=dtype))\n\n self._testTernary(\n array_ops.slice,\n np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=dtype),\n np.array([0, 1], dtype=np.int32),\n np.array([2, 1], dtype=np.int32),\n expected=np.array([[2], [5]], dtype=dtype))\n\n def testClipByValue(self):\n for dtype in self.numeric_types - self.complex_types:\n test_cases = [\n (np.array([2, 4, 5], dtype=dtype), dtype(7)), #\n (dtype(1), np.array([2, 4, 5], dtype=dtype)), #\n (np.array([-2, 7, 7], dtype=dtype), np.array([-2, 9, 8], dtype=dtype))\n ]\n x = np.array([-2, 10, 6], dtype=dtype)\n for lower, upper in test_cases:\n self._testTernary(\n gen_math_ops._clip_by_value,\n x,\n lower,\n upper,\n expected=np.minimum(np.maximum(x, lower), upper))\n\n @test_util.disable_mlir_bridge('Enable tf.Betainc Compilation')\n def testBetaincSanity(self):\n # This operation is only supported for float32 and float64.\n for dtype in self.numeric_types & {np.float32, np.float64}:\n # Sanity check a few identities:\n # - betainc(a, b, 0) == 0\n # - betainc(a, b, 1) == 1\n # - betainc(a, 1, x) == x ** a\n # Compare against the implementation in SciPy.\n a = np.array([.3, .4, .2, .2], dtype=dtype)\n b = np.array([1., 1., .4, .4], dtype=dtype)\n x = np.array([.3, .4, .0, .1], dtype=dtype)\n expected = sps.betainc(a, b, x)\n self._testTernary(\n math_ops.betainc, a, b, x, expected, rtol=5e-6, atol=6e-6)\n\n @parameterized.parameters(\n {\n 'sigma': 1e15,\n 'rtol': 1e-6,\n 'atol': 1e-4\n },\n {\n 'sigma': 30,\n 'rtol': 1e-6,\n 'atol': 2e-3\n },\n {\n 'sigma': 1e-8,\n 'rtol': 5e-4,\n 'atol': 3e-4\n },\n {\n 'sigma': 1e-16,\n 'rtol': 1e-6,\n 'atol': 2e-4\n },\n )\n @test_util.disable_mlir_bridge('Enable tf.Betainc Compilation')\n def testBetainc(self, sigma, rtol, atol):\n # This operation is only supported for float32 and float64.\n for dtype in self.numeric_types & {np.float32, np.float64}:\n # Randomly generate a, b, x in the numerical domain of betainc.\n # Compare against the implementation in SciPy.\n a = np.abs(np.random.randn(10, 10) * sigma).astype(dtype) # in (0, infty)\n b = np.abs(np.random.randn(10, 10) * sigma).astype(dtype) # in (0, infty)\n x = np.random.rand(10, 10).astype(dtype) # in (0, 1)\n expected = sps.betainc(a, b, x, dtype=dtype)\n self._testTernary(\n math_ops.betainc, a, b, x, expected, rtol=rtol, atol=atol)\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\"\"\"Pooling layers.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport functools\n\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.keras import backend\nfrom tensorflow.python.keras.engine.base_layer import Layer\nfrom tensorflow.python.keras.engine.input_spec import InputSpec\nfrom tensorflow.python.keras.utils import conv_utils\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import nn\nfrom tensorflow.python.util.tf_export import keras_export\n\n\nclass Pooling1D(Layer):\n \"\"\"Pooling layer for arbitrary pooling functions, for 1D inputs.\n\n This class only exists for code reuse. It will never be an exposed API.\n\n Arguments:\n pool_function: The pooling function to apply, e.g. `tf.nn.max_pool2d`.\n pool_size: An integer or tuple/list of a single integer,\n representing the size of the pooling window.\n strides: An integer or tuple/list of a single integer, specifying the\n strides of the pooling operation.\n padding: A string. The padding method, either 'valid' or 'same'.\n Case-insensitive.\n data_format: A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, steps, features)` while `channels_first`\n corresponds to inputs with shape\n `(batch, features, steps)`.\n name: A string, the name of the layer.\n \"\"\"\n\n def __init__(self, pool_function, pool_size, strides,\n padding='valid', data_format='channels_last',\n name=None, **kwargs):\n super(Pooling1D, self).__init__(name=name, **kwargs)\n if data_format is None:\n data_format = backend.image_data_format()\n if strides is None:\n strides = pool_size\n self.pool_function = pool_function\n self.pool_size = conv_utils.normalize_tuple(pool_size, 1, 'pool_size')\n self.strides = conv_utils.normalize_tuple(strides, 1, 'strides')\n self.padding = conv_utils.normalize_padding(padding)\n self.data_format = conv_utils.normalize_data_format(data_format)\n self.input_spec = InputSpec(ndim=3)\n\n def call(self, inputs):\n pad_axis = 2 if self.data_format == 'channels_last' else 3\n inputs = array_ops.expand_dims(inputs, pad_axis)\n outputs = self.pool_function(\n inputs,\n self.pool_size + (1,),\n strides=self.strides + (1,),\n padding=self.padding,\n data_format=self.data_format)\n return array_ops.squeeze(outputs, pad_axis)\n\n def compute_output_shape(self, input_shape):\n input_shape = tensor_shape.TensorShape(input_shape).as_list()\n if self.data_format == 'channels_first':\n steps = input_shape[2]\n features = input_shape[1]\n else:\n steps = input_shape[1]\n features = input_shape[2]\n length = conv_utils.conv_output_length(steps,\n self.pool_size[0],\n self.padding,\n self.strides[0])\n if self.data_format == 'channels_first':\n return tensor_shape.TensorShape([input_shape[0], features, length])\n else:\n return tensor_shape.TensorShape([input_shape[0], length, features])\n\n def get_config(self):\n config = {\n 'strides': self.strides,\n 'pool_size': self.pool_size,\n 'padding': self.padding,\n 'data_format': self.data_format,\n }\n base_config = super(Pooling1D, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@keras_export('keras.layers.MaxPool1D', 'keras.layers.MaxPooling1D')\nclass MaxPooling1D(Pooling1D):\n \"\"\"Max pooling operation for 1D temporal data.\n\n Downsamples the input representation by taking the maximum value over the\n window defined by `pool_size`. The window is shifted by `strides`. The\n resulting output when using \"valid\" padding option has a shape of:\n `output_shape = (input_shape - pool_size + 1) / strides)`\n\n The resulting output shape when using the \"same\" padding option is:\n `output_shape = input_shape / strides`\n\n For example, for strides=1 and padding=\"valid\":\n\n >>> x = tf.constant([1., 2., 3., 4., 5.])\n >>> x = tf.reshape(x, [1, 5, 1])\n >>> max_pool_1d = tf.keras.layers.MaxPooling1D(pool_size=2,\n ... strides=1, padding='valid')\n >>> max_pool_1d(x)\n <tf.Tensor: shape=(1, 4, 1), dtype=float32, numpy=\n array([[[2.],\n [3.],\n [4.],\n [5.]]], dtype=float32)>\n\n For example, for strides=2 and padding=\"valid\":\n\n >>> x = tf.constant([1., 2., 3., 4., 5.])\n >>> x = tf.reshape(x, [1, 5, 1])\n >>> max_pool_1d = tf.keras.layers.MaxPooling1D(pool_size=2,\n ... strides=2, padding='valid')\n >>> max_pool_1d(x)\n <tf.Tensor: shape=(1, 2, 1), dtype=float32, numpy=\n array([[[2.],\n [4.]]], dtype=float32)>\n\n For example, for strides=1 and padding=\"same\":\n\n >>> x = tf.constant([1., 2., 3., 4., 5.])\n >>> x = tf.reshape(x, [1, 5, 1])\n >>> max_pool_1d = tf.keras.layers.MaxPooling1D(pool_size=2,\n ... strides=1, padding='same')\n >>> max_pool_1d(x)\n <tf.Tensor: shape=(1, 5, 1), dtype=float32, numpy=\n array([[[2.],\n [3.],\n [4.],\n [5.],\n [5.]]], dtype=float32)>\n\n Arguments:\n pool_size: Integer, size of the max pooling window.\n strides: Integer, or None. Specifies how much the pooling window moves\n for each pooling step.\n If None, it will default to `pool_size`.\n padding: One of `\"valid\"` or `\"same\"` (case-insensitive).\n \"valid\" adds no padding. \"same\" adds padding such that if the stride\n is 1, the output shape is the same as the input shape.\n data_format: A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, steps, features)` while `channels_first`\n corresponds to inputs with shape\n `(batch, features, steps)`.\n\n Input shape:\n - If `data_format='channels_last'`:\n 3D tensor with shape `(batch_size, steps, features)`.\n - If `data_format='channels_first'`:\n 3D tensor with shape `(batch_size, features, steps)`.\n\n Output shape:\n - If `data_format='channels_last'`:\n 3D tensor with shape `(batch_size, downsampled_steps, features)`.\n - If `data_format='channels_first'`:\n 3D tensor with shape `(batch_size, features, downsampled_steps)`.\n \"\"\"\n\n def __init__(self, pool_size=2, strides=None,\n padding='valid', data_format='channels_last', **kwargs):\n\n super(MaxPooling1D, self).__init__(\n functools.partial(backend.pool2d, pool_mode='max'),\n pool_size=pool_size,\n strides=strides,\n padding=padding,\n data_format=data_format,\n **kwargs)\n\n\n@keras_export('keras.layers.AveragePooling1D', 'keras.layers.AvgPool1D')\nclass AveragePooling1D(Pooling1D):\n \"\"\"Average pooling for temporal data.\n\n Arguments:\n pool_size: Integer, size of the average pooling windows.\n strides: Integer, or None. Factor by which to downscale.\n E.g. 2 will halve the input.\n If None, it will default to `pool_size`.\n padding: One of `\"valid\"` or `\"same\"` (case-insensitive).\n data_format: A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, steps, features)` while `channels_first`\n corresponds to inputs with shape\n `(batch, features, steps)`.\n\n Input shape:\n - If `data_format='channels_last'`:\n 3D tensor with shape `(batch_size, steps, features)`.\n - If `data_format='channels_first'`:\n 3D tensor with shape `(batch_size, features, steps)`.\n\n Output shape:\n - If `data_format='channels_last'`:\n 3D tensor with shape `(batch_size, downsampled_steps, features)`.\n - If `data_format='channels_first'`:\n 3D tensor with shape `(batch_size, features, downsampled_steps)`.\n \"\"\"\n\n def __init__(self, pool_size=2, strides=None,\n padding='valid', data_format='channels_last', **kwargs):\n super(AveragePooling1D, self).__init__(\n functools.partial(backend.pool2d, pool_mode='avg'),\n pool_size=pool_size,\n strides=strides,\n padding=padding,\n data_format=data_format,\n **kwargs)\n\n\nclass Pooling2D(Layer):\n \"\"\"Pooling layer for arbitrary pooling functions, for 2D inputs (e.g. images).\n\n This class only exists for code reuse. It will never be an exposed API.\n\n Arguments:\n pool_function: The pooling function to apply, e.g. `tf.nn.max_pool2d`.\n pool_size: An integer or tuple/list of 2 integers: (pool_height, pool_width)\n specifying the size of the pooling window.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n strides: An integer or tuple/list of 2 integers,\n specifying the strides of the pooling operation.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n padding: A string. The padding method, either 'valid' or 'same'.\n Case-insensitive.\n data_format: A string, one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, height, width, channels)` while `channels_first` corresponds to\n inputs with shape `(batch, channels, height, width)`.\n name: A string, the name of the layer.\n \"\"\"\n\n def __init__(self, pool_function, pool_size, strides,\n padding='valid', data_format=None,\n name=None, **kwargs):\n super(Pooling2D, self).__init__(name=name, **kwargs)\n if data_format is None:\n data_format = backend.image_data_format()\n if strides is None:\n strides = pool_size\n self.pool_function = pool_function\n self.pool_size = conv_utils.normalize_tuple(pool_size, 2, 'pool_size')\n self.strides = conv_utils.normalize_tuple(strides, 2, 'strides')\n self.padding = conv_utils.normalize_padding(padding)\n self.data_format = conv_utils.normalize_data_format(data_format)\n self.input_spec = InputSpec(ndim=4)\n\n def call(self, inputs):\n if self.data_format == 'channels_last':\n pool_shape = (1,) + self.pool_size + (1,)\n strides = (1,) + self.strides + (1,)\n else:\n pool_shape = (1, 1) + self.pool_size\n strides = (1, 1) + self.strides\n outputs = self.pool_function(\n inputs,\n ksize=pool_shape,\n strides=strides,\n padding=self.padding.upper(),\n data_format=conv_utils.convert_data_format(self.data_format, 4))\n return outputs\n\n def compute_output_shape(self, input_shape):\n input_shape = tensor_shape.TensorShape(input_shape).as_list()\n if self.data_format == 'channels_first':\n rows = input_shape[2]\n cols = input_shape[3]\n else:\n rows = input_shape[1]\n cols = input_shape[2]\n rows = conv_utils.conv_output_length(rows, self.pool_size[0], self.padding,\n self.strides[0])\n cols = conv_utils.conv_output_length(cols, self.pool_size[1], self.padding,\n self.strides[1])\n if self.data_format == 'channels_first':\n return tensor_shape.TensorShape(\n [input_shape[0], input_shape[1], rows, cols])\n else:\n return tensor_shape.TensorShape(\n [input_shape[0], rows, cols, input_shape[3]])\n\n def get_config(self):\n config = {\n 'pool_size': self.pool_size,\n 'padding': self.padding,\n 'strides': self.strides,\n 'data_format': self.data_format\n }\n base_config = super(Pooling2D, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@keras_export('keras.layers.MaxPool2D', 'keras.layers.MaxPooling2D')\nclass MaxPooling2D(Pooling2D):\n \"\"\"Max pooling operation for 2D spatial data.\n\n Downsamples the input representation by taking the maximum value over the\n window defined by `pool_size` for each dimension along the features axis.\n The window is shifted by `strides` in each dimension. The resulting output\n when using \"valid\" padding option has a shape(number of rows or columns) of:\n `output_shape = (input_shape - pool_size + 1) / strides)`\n\n The resulting output shape when using the \"same\" padding option is:\n `output_shape = input_shape / strides`\n\n For example, for stride=(1,1) and padding=\"valid\":\n\n >>> x = tf.constant([[1., 2., 3.],\n ... [4., 5., 6.],\n ... [7., 8., 9.]])\n >>> x = tf.reshape(x, [1, 3, 3, 1])\n >>> max_pool_2d = tf.keras.layers.MaxPooling2D(pool_size=(2, 2),\n ... strides=(1, 1), padding='valid')\n >>> max_pool_2d(x)\n <tf.Tensor: shape=(1, 2, 2, 1), dtype=float32, numpy=\n array([[[[5.],\n [6.]],\n [[8.],\n [9.]]]], dtype=float32)>\n\n For example, for stride=(2,2) and padding=\"valid\":\n\n >>> x = tf.constant([[1., 2., 3., 4.],\n ... [5., 6., 7., 8.],\n ... [9., 10., 11., 12.]])\n >>> x = tf.reshape(x, [1, 3, 4, 1])\n >>> max_pool_2d = tf.keras.layers.MaxPooling2D(pool_size=(2, 2),\n ... strides=(1, 1), padding='valid')\n >>> max_pool_2d(x)\n <tf.Tensor: shape=(1, 2, 3, 1), dtype=float32, numpy=\n array([[[[ 6.],\n [ 7.],\n [ 8.]],\n [[10.],\n [11.],\n [12.]]]], dtype=float32)>\n \n Usage Example:\n \n >>> input_image = tf.constant([[[[1.], [1.], [2.], [4.]],\n ... [[2.], [2.], [3.], [2.]],\n ... [[4.], [1.], [1.], [1.]],\n ... [[2.], [2.], [1.], [4.]]]]) \n >>> output = tf.constant([[[[1], [0]],\n ... [[0], [1]]]]) \n >>> model = tf.keras.models.Sequential()\n >>> model.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2), \n ... input_shape=(4,4,1)))\n >>> model.compile('adam', 'mean_squared_error')\n >>> model.predict(input_image, steps=1)\n array([[[[2.],\n [4.]],\n [[4.],\n [4.]]]], dtype=float32)\n\n For example, for stride=(1,1) and padding=\"same\":\n\n >>> x = tf.constant([[1., 2., 3.],\n ... [4., 5., 6.],\n ... [7., 8., 9.]])\n >>> x = tf.reshape(x, [1, 3, 3, 1])\n >>> max_pool_2d = tf.keras.layers.MaxPooling2D(pool_size=(2, 2),\n ... strides=(1, 1), padding='same')\n >>> max_pool_2d(x)\n <tf.Tensor: shape=(1, 3, 3, 1), dtype=float32, numpy=\n array([[[[5.],\n [6.],\n [6.]],\n [[8.],\n [9.],\n [9.]],\n [[8.],\n [9.],\n [9.]]]], dtype=float32)>\n\n Arguments:\n pool_size: integer or tuple of 2 integers,\n window size over which to take the maximum.\n `(2, 2)` will take the max value over a 2x2 pooling window.\n If only one integer is specified, the same window length\n will be used for both dimensions.\n strides: Integer, tuple of 2 integers, or None.\n Strides values. Specifies how far the pooling window moves\n for each pooling step. If None, it will default to `pool_size`.\n padding: One of `\"valid\"` or `\"same\"` (case-insensitive).\n \"valid\" adds no zero padding. \"same\" adds padding such that if the stride\n is 1, the output shape is the same as input shape.\n data_format: A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, height, width, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch, channels, height, width)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".\n\n Input shape:\n - If `data_format='channels_last'`:\n 4D tensor with shape `(batch_size, rows, cols, channels)`.\n - If `data_format='channels_first'`:\n 4D tensor with shape `(batch_size, channels, rows, cols)`.\n\n Output shape:\n - If `data_format='channels_last'`:\n 4D tensor with shape `(batch_size, pooled_rows, pooled_cols, channels)`.\n - If `data_format='channels_first'`:\n 4D tensor with shape `(batch_size, channels, pooled_rows, pooled_cols)`.\n\n Returns:\n A tensor of rank 4 representing the maximum pooled values. See above for\n output shape.\n \"\"\"\n\n def __init__(self,\n pool_size=(2, 2),\n strides=None,\n padding='valid',\n data_format=None,\n **kwargs):\n super(MaxPooling2D, self).__init__(\n nn.max_pool,\n pool_size=pool_size, strides=strides,\n padding=padding, data_format=data_format, **kwargs)\n\n\n@keras_export('keras.layers.AveragePooling2D', 'keras.layers.AvgPool2D')\nclass AveragePooling2D(Pooling2D):\n \"\"\"Average pooling operation for spatial data.\n\n Arguments:\n pool_size: integer or tuple of 2 integers,\n factors by which to downscale (vertical, horizontal).\n `(2, 2)` will halve the input in both spatial dimension.\n If only one integer is specified, the same window length\n will be used for both dimensions.\n strides: Integer, tuple of 2 integers, or None.\n Strides values.\n If None, it will default to `pool_size`.\n padding: One of `\"valid\"` or `\"same\"` (case-insensitive).\n data_format: A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, height, width, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch, channels, height, width)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".\n\n Input shape:\n - If `data_format='channels_last'`:\n 4D tensor with shape `(batch_size, rows, cols, channels)`.\n - If `data_format='channels_first'`:\n 4D tensor with shape `(batch_size, channels, rows, cols)`.\n\n Output shape:\n - If `data_format='channels_last'`:\n 4D tensor with shape `(batch_size, pooled_rows, pooled_cols, channels)`.\n - If `data_format='channels_first'`:\n 4D tensor with shape `(batch_size, channels, pooled_rows, pooled_cols)`.\n \"\"\"\n\n def __init__(self,\n pool_size=(2, 2),\n strides=None,\n padding='valid',\n data_format=None,\n **kwargs):\n super(AveragePooling2D, self).__init__(\n nn.avg_pool,\n pool_size=pool_size, strides=strides,\n padding=padding, data_format=data_format, **kwargs)\n\n\nclass Pooling3D(Layer):\n \"\"\"Pooling layer for arbitrary pooling functions, for 3D inputs.\n\n This class only exists for code reuse. It will never be an exposed API.\n\n Arguments:\n pool_function: The pooling function to apply, e.g. `tf.nn.max_pool2d`.\n pool_size: An integer or tuple/list of 3 integers:\n (pool_depth, pool_height, pool_width)\n specifying the size of the pooling window.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n strides: An integer or tuple/list of 3 integers,\n specifying the strides of the pooling operation.\n Can be a single integer to specify the same value for\n all spatial dimensions.\n padding: A string. The padding method, either 'valid' or 'same'.\n Case-insensitive.\n data_format: A string, one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, depth, height, width, channels)`\n while `channels_first` corresponds to\n inputs with shape `(batch, channels, depth, height, width)`.\n name: A string, the name of the layer.\n \"\"\"\n\n def __init__(self, pool_function, pool_size, strides,\n padding='valid', data_format='channels_last',\n name=None, **kwargs):\n super(Pooling3D, self).__init__(name=name, **kwargs)\n if data_format is None:\n data_format = backend.image_data_format()\n if strides is None:\n strides = pool_size\n self.pool_function = pool_function\n self.pool_size = conv_utils.normalize_tuple(pool_size, 3, 'pool_size')\n self.strides = conv_utils.normalize_tuple(strides, 3, 'strides')\n self.padding = conv_utils.normalize_padding(padding)\n self.data_format = conv_utils.normalize_data_format(data_format)\n self.input_spec = InputSpec(ndim=5)\n\n def call(self, inputs):\n pool_shape = (1,) + self.pool_size + (1,)\n strides = (1,) + self.strides + (1,)\n\n if self.data_format == 'channels_first':\n # TF does not support `channels_first` with 3D pooling operations,\n # so we must handle this case manually.\n # TODO(fchollet): remove this when TF pooling is feature-complete.\n inputs = array_ops.transpose(inputs, (0, 2, 3, 4, 1))\n\n outputs = self.pool_function(\n inputs,\n ksize=pool_shape,\n strides=strides,\n padding=self.padding.upper())\n\n if self.data_format == 'channels_first':\n outputs = array_ops.transpose(outputs, (0, 4, 1, 2, 3))\n return outputs\n\n def compute_output_shape(self, input_shape):\n input_shape = tensor_shape.TensorShape(input_shape).as_list()\n if self.data_format == 'channels_first':\n len_dim1 = input_shape[2]\n len_dim2 = input_shape[3]\n len_dim3 = input_shape[4]\n else:\n len_dim1 = input_shape[1]\n len_dim2 = input_shape[2]\n len_dim3 = input_shape[3]\n len_dim1 = conv_utils.conv_output_length(len_dim1, self.pool_size[0],\n self.padding, self.strides[0])\n len_dim2 = conv_utils.conv_output_length(len_dim2, self.pool_size[1],\n self.padding, self.strides[1])\n len_dim3 = conv_utils.conv_output_length(len_dim3, self.pool_size[2],\n self.padding, self.strides[2])\n if self.data_format == 'channels_first':\n return tensor_shape.TensorShape(\n [input_shape[0], input_shape[1], len_dim1, len_dim2, len_dim3])\n else:\n return tensor_shape.TensorShape(\n [input_shape[0], len_dim1, len_dim2, len_dim3, input_shape[4]])\n\n def get_config(self):\n config = {\n 'pool_size': self.pool_size,\n 'padding': self.padding,\n 'strides': self.strides,\n 'data_format': self.data_format\n }\n base_config = super(Pooling3D, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@keras_export('keras.layers.MaxPool3D', 'keras.layers.MaxPooling3D')\nclass MaxPooling3D(Pooling3D):\n \"\"\"Max pooling operation for 3D data (spatial or spatio-temporal).\n\n Arguments:\n pool_size: Tuple of 3 integers,\n factors by which to downscale (dim1, dim2, dim3).\n `(2, 2, 2)` will halve the size of the 3D input in each dimension.\n strides: tuple of 3 integers, or None. Strides values.\n padding: One of `\"valid\"` or `\"same\"` (case-insensitive).\n data_format: A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, spatial_dim1, spatial_dim2, spatial_dim3, channels)`\n while `channels_first` corresponds to inputs with shape\n `(batch, channels, spatial_dim1, spatial_dim2, spatial_dim3)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".\n\n Input shape:\n - If `data_format='channels_last'`:\n 5D tensor with shape:\n `(batch_size, spatial_dim1, spatial_dim2, spatial_dim3, channels)`\n - If `data_format='channels_first'`:\n 5D tensor with shape:\n `(batch_size, channels, spatial_dim1, spatial_dim2, spatial_dim3)`\n\n Output shape:\n - If `data_format='channels_last'`:\n 5D tensor with shape:\n `(batch_size, pooled_dim1, pooled_dim2, pooled_dim3, channels)`\n - If `data_format='channels_first'`:\n 5D tensor with shape:\n `(batch_size, channels, pooled_dim1, pooled_dim2, pooled_dim3)`\n \"\"\"\n\n def __init__(self,\n pool_size=(2, 2, 2),\n strides=None,\n padding='valid',\n data_format=None,\n **kwargs):\n super(MaxPooling3D, self).__init__(\n nn.max_pool3d,\n pool_size=pool_size, strides=strides,\n padding=padding, data_format=data_format, **kwargs)\n\n\n@keras_export('keras.layers.AveragePooling3D', 'keras.layers.AvgPool3D')\nclass AveragePooling3D(Pooling3D):\n \"\"\"Average pooling operation for 3D data (spatial or spatio-temporal).\n\n Arguments:\n pool_size: tuple of 3 integers,\n factors by which to downscale (dim1, dim2, dim3).\n `(2, 2, 2)` will halve the size of the 3D input in each dimension.\n strides: tuple of 3 integers, or None. Strides values.\n padding: One of `\"valid\"` or `\"same\"` (case-insensitive).\n data_format: A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, spatial_dim1, spatial_dim2, spatial_dim3, channels)`\n while `channels_first` corresponds to inputs with shape\n `(batch, channels, spatial_dim1, spatial_dim2, spatial_dim3)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".\n\n Input shape:\n - If `data_format='channels_last'`:\n 5D tensor with shape:\n `(batch_size, spatial_dim1, spatial_dim2, spatial_dim3, channels)`\n - If `data_format='channels_first'`:\n 5D tensor with shape:\n `(batch_size, channels, spatial_dim1, spatial_dim2, spatial_dim3)`\n\n Output shape:\n - If `data_format='channels_last'`:\n 5D tensor with shape:\n `(batch_size, pooled_dim1, pooled_dim2, pooled_dim3, channels)`\n - If `data_format='channels_first'`:\n 5D tensor with shape:\n `(batch_size, channels, pooled_dim1, pooled_dim2, pooled_dim3)`\n \"\"\"\n\n def __init__(self,\n pool_size=(2, 2, 2),\n strides=None,\n padding='valid',\n data_format=None,\n **kwargs):\n super(AveragePooling3D, self).__init__(\n nn.avg_pool3d,\n pool_size=pool_size, strides=strides,\n padding=padding, data_format=data_format, **kwargs)\n\n\nclass GlobalPooling1D(Layer):\n \"\"\"Abstract class for different global pooling 1D layers.\"\"\"\n\n def __init__(self, data_format='channels_last', **kwargs):\n super(GlobalPooling1D, self).__init__(**kwargs)\n self.input_spec = InputSpec(ndim=3)\n self.data_format = conv_utils.normalize_data_format(data_format)\n\n def compute_output_shape(self, input_shape):\n input_shape = tensor_shape.TensorShape(input_shape).as_list()\n if self.data_format == 'channels_first':\n return tensor_shape.TensorShape([input_shape[0], input_shape[1]])\n else:\n return tensor_shape.TensorShape([input_shape[0], input_shape[2]])\n\n def call(self, inputs):\n raise NotImplementedError\n\n def get_config(self):\n config = {'data_format': self.data_format}\n base_config = super(GlobalPooling1D, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@keras_export('keras.layers.GlobalAveragePooling1D',\n 'keras.layers.GlobalAvgPool1D')\nclass GlobalAveragePooling1D(GlobalPooling1D):\n \"\"\"Global average pooling operation for temporal data.\n\n Examples:\n\n >>> input_shape = (2, 3, 4)\n >>> x = tf.random.normal(input_shape)\n >>> y = tf.keras.layers.GlobalAveragePooling1D()(x)\n >>> print(y.shape)\n (2, 4)\n\n Arguments:\n data_format: A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, steps, features)` while `channels_first`\n corresponds to inputs with shape\n `(batch, features, steps)`.\n\n Call arguments:\n inputs: A 3D tensor.\n mask: Binary tensor of shape `(batch_size, steps)` indicating whether\n a given step should be masked (excluded from the average).\n\n Input shape:\n - If `data_format='channels_last'`:\n 3D tensor with shape:\n `(batch_size, steps, features)`\n - If `data_format='channels_first'`:\n 3D tensor with shape:\n `(batch_size, features, steps)`\n\n Output shape:\n 2D tensor with shape `(batch_size, features)`.\n \"\"\"\n\n def __init__(self, data_format='channels_last', **kwargs):\n super(GlobalAveragePooling1D, self).__init__(data_format=data_format,\n **kwargs)\n self.supports_masking = True\n\n def call(self, inputs, mask=None):\n steps_axis = 1 if self.data_format == 'channels_last' else 2\n if mask is not None:\n mask = math_ops.cast(mask, backend.floatx())\n mask = array_ops.expand_dims(\n mask, 2 if self.data_format == 'channels_last' else 1)\n inputs *= mask\n return backend.sum(inputs, axis=steps_axis) / math_ops.reduce_sum(\n mask, axis=steps_axis)\n else:\n return backend.mean(inputs, axis=steps_axis)\n\n def compute_mask(self, inputs, mask=None):\n return None\n\n\n@keras_export('keras.layers.GlobalMaxPool1D', 'keras.layers.GlobalMaxPooling1D')\nclass GlobalMaxPooling1D(GlobalPooling1D):\n \"\"\"Global max pooling operation for 1D temporal data.\n\n Downsamples the input representation by taking the maximum value over\n the time dimension.\n\n For example:\n\n >>> x = tf.constant([[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]])\n >>> x = tf.reshape(x, [3, 3, 1])\n >>> x\n <tf.Tensor: shape=(3, 3, 1), dtype=float32, numpy=\n array([[[1.], [2.], [3.]],\n [[4.], [5.], [6.]],\n [[7.], [8.], [9.]]], dtype=float32)>\n >>> max_pool_1d = tf.keras.layers.GlobalMaxPooling1D()\n >>> max_pool_1d(x)\n <tf.Tensor: shape=(3, 1), dtype=float32, numpy=\n array([[3.],\n [6.],\n [9.], dtype=float32)>\n\n Arguments:\n data_format: A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, steps, features)` while `channels_first`\n corresponds to inputs with shape\n `(batch, features, steps)`.\n\n Input shape:\n - If `data_format='channels_last'`:\n 3D tensor with shape:\n `(batch_size, steps, features)`\n - If `data_format='channels_first'`:\n 3D tensor with shape:\n `(batch_size, features, steps)`\n\n Output shape:\n 2D tensor with shape `(batch_size, features)`.\n \"\"\"\n\n def call(self, inputs):\n steps_axis = 1 if self.data_format == 'channels_last' else 2\n return backend.max(inputs, axis=steps_axis)\n\n\nclass GlobalPooling2D(Layer):\n \"\"\"Abstract class for different global pooling 2D layers.\n \"\"\"\n\n def __init__(self, data_format=None, **kwargs):\n super(GlobalPooling2D, self).__init__(**kwargs)\n self.data_format = conv_utils.normalize_data_format(data_format)\n self.input_spec = InputSpec(ndim=4)\n\n def compute_output_shape(self, input_shape):\n input_shape = tensor_shape.TensorShape(input_shape).as_list()\n if self.data_format == 'channels_last':\n return tensor_shape.TensorShape([input_shape[0], input_shape[3]])\n else:\n return tensor_shape.TensorShape([input_shape[0], input_shape[1]])\n\n def call(self, inputs):\n raise NotImplementedError\n\n def get_config(self):\n config = {'data_format': self.data_format}\n base_config = super(GlobalPooling2D, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@keras_export('keras.layers.GlobalAveragePooling2D',\n 'keras.layers.GlobalAvgPool2D')\nclass GlobalAveragePooling2D(GlobalPooling2D):\n \"\"\"Global average pooling operation for spatial data.\n\n Examples:\n\n >>> input_shape = (2, 4, 5, 3)\n >>> x = tf.random.normal(input_shape)\n >>> y = tf.keras.layers.GlobalAveragePooling2D()(x)\n >>> print(y.shape)\n (2, 3)\n\n Arguments:\n data_format: A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, height, width, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch, channels, height, width)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".\n\n Input shape:\n - If `data_format='channels_last'`:\n 4D tensor with shape `(batch_size, rows, cols, channels)`.\n - If `data_format='channels_first'`:\n 4D tensor with shape `(batch_size, channels, rows, cols)`.\n\n Output shape:\n 2D tensor with shape `(batch_size, channels)`.\n \"\"\"\n\n def call(self, inputs):\n if self.data_format == 'channels_last':\n return backend.mean(inputs, axis=[1, 2])\n else:\n return backend.mean(inputs, axis=[2, 3])\n\n\n@keras_export('keras.layers.GlobalMaxPool2D', 'keras.layers.GlobalMaxPooling2D')\nclass GlobalMaxPooling2D(GlobalPooling2D):\n \"\"\"Global max pooling operation for spatial data.\n\n Examples:\n\n >>> input_shape = (2, 4, 5, 3)\n >>> x = tf.random.normal(input_shape)\n >>> y = tf.keras.layers.GlobalMaxPool2D()(x)\n >>> print(y.shape)\n (2, 3)\n\n Arguments:\n data_format: A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, height, width, channels)` while `channels_first`\n corresponds to inputs with shape\n `(batch, channels, height, width)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".\n\n Input shape:\n - If `data_format='channels_last'`:\n 4D tensor with shape `(batch_size, rows, cols, channels)`.\n - If `data_format='channels_first'`:\n 4D tensor with shape `(batch_size, channels, rows, cols)`.\n\n Output shape:\n 2D tensor with shape `(batch_size, channels)`.\n \"\"\"\n\n def call(self, inputs):\n if self.data_format == 'channels_last':\n return backend.max(inputs, axis=[1, 2])\n else:\n return backend.max(inputs, axis=[2, 3])\n\n\nclass GlobalPooling3D(Layer):\n \"\"\"Abstract class for different global pooling 3D layers.\"\"\"\n\n def __init__(self, data_format=None, **kwargs):\n super(GlobalPooling3D, self).__init__(**kwargs)\n self.data_format = conv_utils.normalize_data_format(data_format)\n self.input_spec = InputSpec(ndim=5)\n\n def compute_output_shape(self, input_shape):\n input_shape = tensor_shape.TensorShape(input_shape).as_list()\n if self.data_format == 'channels_last':\n return tensor_shape.TensorShape([input_shape[0], input_shape[4]])\n else:\n return tensor_shape.TensorShape([input_shape[0], input_shape[1]])\n\n def call(self, inputs):\n raise NotImplementedError\n\n def get_config(self):\n config = {'data_format': self.data_format}\n base_config = super(GlobalPooling3D, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\n@keras_export('keras.layers.GlobalAveragePooling3D',\n 'keras.layers.GlobalAvgPool3D')\nclass GlobalAveragePooling3D(GlobalPooling3D):\n \"\"\"Global Average pooling operation for 3D data.\n\n Arguments:\n data_format: A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, spatial_dim1, spatial_dim2, spatial_dim3, channels)`\n while `channels_first` corresponds to inputs with shape\n `(batch, channels, spatial_dim1, spatial_dim2, spatial_dim3)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".\n\n Input shape:\n - If `data_format='channels_last'`:\n 5D tensor with shape:\n `(batch_size, spatial_dim1, spatial_dim2, spatial_dim3, channels)`\n - If `data_format='channels_first'`:\n 5D tensor with shape:\n `(batch_size, channels, spatial_dim1, spatial_dim2, spatial_dim3)`\n\n Output shape:\n 2D tensor with shape `(batch_size, channels)`.\n \"\"\"\n\n def call(self, inputs):\n if self.data_format == 'channels_last':\n return backend.mean(inputs, axis=[1, 2, 3])\n else:\n return backend.mean(inputs, axis=[2, 3, 4])\n\n\n@keras_export('keras.layers.GlobalMaxPool3D', 'keras.layers.GlobalMaxPooling3D')\nclass GlobalMaxPooling3D(GlobalPooling3D):\n \"\"\"Global Max pooling operation for 3D data.\n\n Arguments:\n data_format: A string,\n one of `channels_last` (default) or `channels_first`.\n The ordering of the dimensions in the inputs.\n `channels_last` corresponds to inputs with shape\n `(batch, spatial_dim1, spatial_dim2, spatial_dim3, channels)`\n while `channels_first` corresponds to inputs with shape\n `(batch, channels, spatial_dim1, spatial_dim2, spatial_dim3)`.\n It defaults to the `image_data_format` value found in your\n Keras config file at `~/.keras/keras.json`.\n If you never set it, then it will be \"channels_last\".\n\n Input shape:\n - If `data_format='channels_last'`:\n 5D tensor with shape:\n `(batch_size, spatial_dim1, spatial_dim2, spatial_dim3, channels)`\n - If `data_format='channels_first'`:\n 5D tensor with shape:\n `(batch_size, channels, spatial_dim1, spatial_dim2, spatial_dim3)`\n\n Output shape:\n 2D tensor with shape `(batch_size, channels)`.\n \"\"\"\n\n def call(self, inputs):\n if self.data_format == 'channels_last':\n return backend.max(inputs, axis=[1, 2, 3])\n else:\n return backend.max(inputs, axis=[2, 3, 4])\n\n\n# Aliases\n\nAvgPool1D = AveragePooling1D\nMaxPool1D = MaxPooling1D\nAvgPool2D = AveragePooling2D\nMaxPool2D = MaxPooling2D\nAvgPool3D = AveragePooling3D\nMaxPool3D = MaxPooling3D\nGlobalMaxPool1D = GlobalMaxPooling1D\nGlobalMaxPool2D = GlobalMaxPooling2D\nGlobalMaxPool3D = GlobalMaxPooling3D\nGlobalAvgPool1D = GlobalAveragePooling1D\nGlobalAvgPool2D = GlobalAveragePooling2D\nGlobalAvgPool3D = GlobalAveragePooling3D\n"
] | [
[
"tensorflow.python.framework.tensor_shape.TensorShape",
"tensorflow.python.ops.array_ops.shape",
"tensorflow.python.keras.backend.spatial_3d_padding",
"tensorflow.python.keras.utils.conv_utils.convert_data_format",
"tensorflow.python.keras.regularizers.get",
"tensorflow.python.ops.array_ops.squeeze",
"tensorflow.python.keras.utils.conv_utils.deconv_output_length",
"tensorflow.python.keras.backend.spatial_2d_padding",
"tensorflow.python.keras.utils.conv_utils.conv_output_length",
"tensorflow.python.eager.context.executing_eagerly",
"tensorflow.python.keras.backend.repeat_elements",
"tensorflow.python.keras.backend.depthwise_conv2d",
"tensorflow.python.keras.backend.bias_add",
"tensorflow.python.util.tf_export.keras_export",
"tensorflow.python.keras.constraints.get",
"tensorflow.python.keras.backend.resize_images",
"tensorflow.python.ops.nn_ops.Convolution",
"tensorflow.python.keras.activations.get",
"tensorflow.python.ops.nn.bias_add",
"tensorflow.python.keras.utils.conv_utils.normalize_tuple",
"tensorflow.python.keras.regularizers.serialize",
"tensorflow.python.ops.array_ops.stack",
"tensorflow.python.keras.backend.temporal_padding",
"tensorflow.python.keras.activations.serialize",
"tensorflow.python.keras.backend.conv2d_transpose",
"tensorflow.python.keras.backend.resize_volumes",
"tensorflow.python.keras.constraints.serialize",
"tensorflow.python.ops.array_ops.reshape",
"tensorflow.python.keras.engine.input_spec.InputSpec",
"tensorflow.python.keras.utils.conv_utils.normalize_data_format",
"tensorflow.python.keras.initializers.get",
"tensorflow.python.ops.array_ops.expand_dims",
"tensorflow.python.keras.initializers.serialize",
"tensorflow.python.keras.utils.conv_utils.normalize_padding"
],
[
"tensorflow.python.ops.linalg_ops.eye",
"numpy.vstack",
"tensorflow.python.framework.ops.device",
"numpy.tril",
"tensorflow.python.ops.linalg_ops.lu",
"tensorflow.python.framework.test_util.run_v1_only",
"numpy.reshape",
"numpy.arange",
"tensorflow.python.platform.test.main",
"tensorflow.python.platform.benchmark.benchmark_config",
"tensorflow.python.ops.math_ops.matmul",
"numpy.triu",
"tensorflow.python.ops.array_ops.matrix_set_diag",
"tensorflow.python.platform.test.is_gpu_available",
"tensorflow.python.ops.array_ops.matrix_band_part",
"numpy.append",
"numpy.random.rand",
"numpy.array",
"tensorflow.python.ops.array_ops.stack",
"tensorflow.python.ops.math_ops.range",
"tensorflow.python.ops.array_ops.concat",
"numpy.random.seed",
"tensorflow.python.ops.control_flow_ops.group",
"tensorflow.python.framework.ops.Graph",
"tensorflow.python.ops.map_fn.map_fn",
"numpy.tile",
"numpy.sort",
"numpy.ones",
"tensorflow.python.ops.array_ops.reshape",
"tensorflow.python.ops.random_ops.random_normal",
"tensorflow.python.ops.variables.global_variables_initializer",
"numpy.empty"
],
[
"tensorflow.python.ops.math_ops.log",
"tensorflow.python.ops.math_ops.subtract",
"tensorflow.python.ops.array_ops.shape",
"tensorflow.python.platform.device_context.enclosing_tpu_context",
"tensorflow.python.ops.nn_ops._ensure_xent_args",
"tensorflow.python.compat.compat.forward_compatible",
"tensorflow.python.ops.math_ops.rsqrt",
"tensorflow.python.ops.math_ops.exp",
"tensorflow.python.distribute.distribution_strategy_context.has_strategy",
"tensorflow.python.ops.array_ops.zeros",
"tensorflow.python.ops.array_ops.squeeze",
"tensorflow.python.ops.math_ops.not_equal",
"tensorflow.python.ops.nn_ops.softmax_cross_entropy_with_logits_v2",
"tensorflow.python.ops.losses.util.scale_losses_by_sample_weight",
"tensorflow.python.ops.gen_sparse_ops.sparse_to_dense",
"tensorflow.python.ops.array_ops.identity",
"tensorflow.python.ops.array_ops.stop_gradient",
"tensorflow.python.ops.math_ops.logical_and",
"tensorflow.python.ops.candidate_sampling_ops.log_uniform_candidate_sampler",
"tensorflow.python.ops.candidate_sampling_ops.compute_accidental_hits",
"tensorflow.python.ops.math_ops.abs",
"tensorflow.python.ops.array_ops.where",
"tensorflow.python.util.tf_export.tf_export",
"tensorflow.python.ops.math_ops.reduce_prod",
"tensorflow.python.ops.math_ops.add",
"tensorflow.python.ops.array_ops.size",
"tensorflow.python.ops.array_ops.ones",
"tensorflow.python.ops.math_ops.matmul",
"tensorflow.python.ops.embedding_ops.embedding_lookup",
"tensorflow.python.framework.ops.control_dependencies",
"tensorflow.python.ops.gen_nn_ops.fused_batch_norm_v3",
"tensorflow.python.ops.math_ops.cast",
"tensorflow.python.distribute.distribution_strategy_context.in_cross_replica_context",
"tensorflow.python.ops.nn_ops.conv2d",
"tensorflow.python.ops.nn_ops.depthwise_conv2d_native",
"tensorflow.python.framework.constant_op.constant",
"tensorflow.python.ops.math_ops.square",
"tensorflow.python.ops.array_ops.zeros_like",
"tensorflow.python.ops.linalg_ops.norm",
"tensorflow.python.util.deprecation.deprecated_args",
"tensorflow.python.distribute.distribution_strategy_context.get_strategy",
"tensorflow.python.ops.math_ops.reduce_mean",
"tensorflow.python.ops.math_ops.maximum",
"tensorflow.python.ops.math_ops.squared_difference",
"tensorflow.python.ops.array_ops.shape_v2",
"tensorflow.python.framework.ops.convert_to_tensor",
"tensorflow.python.ops.array_ops.stack",
"tensorflow.python.ops.array_ops.ones_like",
"tensorflow.python.ops.math_ops.sigmoid",
"tensorflow.python.ops.array_ops.concat",
"tensorflow.python.framework.ops.name_scope",
"tensorflow.python.ops.math_ops.reciprocal",
"tensorflow.python.ops.array_ops.reshape",
"tensorflow.python.ops.math_ops.multiply",
"tensorflow.python.ops.nn_ops.relu",
"tensorflow.python.ops.losses.util.check_per_example_loss_rank",
"tensorflow.python.ops.array_ops.expand_dims",
"tensorflow.python.ops.math_ops.reduce_sum",
"tensorflow.python.util.deprecation.deprecated_argument_lookup"
],
[
"numpy.maximum",
"numpy.linspace",
"numpy.int32",
"tensorflow.python.framework.dtypes.as_dtype",
"tensorflow.python.framework.test_util.disable_mlir_bridge",
"numpy.random.randn",
"numpy.random.rand",
"numpy.float32",
"tensorflow.python.platform.googletest.main",
"numpy.array",
"scipy.special.betainc"
],
[
"tensorflow.python.ops.array_ops.transpose",
"tensorflow.python.keras.backend.max",
"tensorflow.python.framework.tensor_shape.TensorShape",
"tensorflow.python.keras.backend.image_data_format",
"tensorflow.python.keras.utils.conv_utils.convert_data_format",
"tensorflow.python.util.tf_export.keras_export",
"tensorflow.python.keras.backend.sum",
"tensorflow.python.keras.engine.input_spec.InputSpec",
"tensorflow.python.ops.array_ops.squeeze",
"tensorflow.python.keras.backend.floatx",
"tensorflow.python.keras.utils.conv_utils.normalize_data_format",
"tensorflow.python.keras.backend.mean",
"tensorflow.python.keras.utils.conv_utils.normalize_tuple",
"tensorflow.python.keras.utils.conv_utils.conv_output_length",
"tensorflow.python.ops.array_ops.expand_dims",
"tensorflow.python.ops.math_ops.reduce_sum",
"tensorflow.python.keras.utils.conv_utils.normalize_padding"
]
] | [
{
"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.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",
"2.3",
"2.4",
"2.9",
"2.5",
"2.8",
"2.10"
]
},
{
"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": [
"1.13"
]
}
] |
ChidanandKumarKS/mxnet | [
"1ed8b19849046bce92fd3d4a390b2adc405b584a"
] | [
"python/mxnet/base.py"
] | [
"# coding: utf-8\n# pylint: disable=invalid-name, no-member\n\"\"\"ctypes library of mxnet and helper functions.\"\"\"\nfrom __future__ import absolute_import\n\nimport sys\nimport ctypes\nimport atexit\nimport warnings\nimport inspect\nimport numpy as np\nfrom . import libinfo\nwarnings.filterwarnings('default', category=DeprecationWarning)\n\n__all__ = ['MXNetError']\n#----------------------------\n# library loading\n#----------------------------\nif sys.version_info[0] == 3:\n string_types = str,\n numeric_types = (float, int, np.float32, np.int32)\n integer_types = int\n # this function is needed for python3\n # to convert ctypes.char_p .value back to python str\n py_str = lambda x: x.decode('utf-8')\nelse:\n string_types = basestring,\n numeric_types = (float, int, long, np.float32, np.int32)\n integer_types = (int, long)\n py_str = lambda x: x\n\nclass _NullType(object):\n \"\"\"Placeholder for arguments\"\"\"\n def __repr__(self):\n return '_Null'\n\n_Null = _NullType()\n\nclass MXNetError(Exception):\n \"\"\"Error that will be throwed by all mxnet functions.\"\"\"\n pass\n\nclass NotImplementedForSymbol(MXNetError):\n def __init__(self, function, alias, *args):\n super(NotImplementedForSymbol, self).__init__()\n self.function = function.__name__\n self.alias = alias\n self.args = [str(type(a)) for a in args]\n def __str__(self):\n msg = 'Function {}'.format(self.function)\n if self.alias:\n msg += ' (namely operator \"{}\")'.format(self.alias)\n if self.args:\n msg += ' with arguments ({})'.format(', '.join(self.args))\n msg += ' is not implemented for Symbol and only available in NDArray.'\n return msg\n\ndef _load_lib():\n \"\"\"Load library by searching possible path.\"\"\"\n lib_path = libinfo.find_lib_path()\n lib = ctypes.CDLL(lib_path[0], ctypes.RTLD_LOCAL)\n # DMatrix functions\n lib.MXGetLastError.restype = ctypes.c_char_p\n return lib\n\n# version number\n__version__ = libinfo.__version__\n# library instance of mxnet\n_LIB = _load_lib()\n\n# type definitions\nmx_uint = ctypes.c_uint\nmx_float = ctypes.c_float\nmx_float_p = ctypes.POINTER(mx_float)\nmx_real_t = np.float32\nNDArrayHandle = ctypes.c_void_p\nFunctionHandle = ctypes.c_void_p\nOpHandle = ctypes.c_void_p\nCachedOpHandle = ctypes.c_void_p\nSymbolHandle = ctypes.c_void_p\nExecutorHandle = ctypes.c_void_p\nDataIterCreatorHandle = ctypes.c_void_p\nDataIterHandle = ctypes.c_void_p\nKVStoreHandle = ctypes.c_void_p\nRecordIOHandle = ctypes.c_void_p\nRtcHandle = ctypes.c_void_p\n#----------------------------\n# helper function definition\n#----------------------------\ndef check_call(ret):\n \"\"\"Check the return value of C API call.\n\n This function will raise an exception when an error occurs.\n Wrap every API call with this function.\n\n Parameters\n ----------\n ret : int\n return value from API calls.\n \"\"\"\n if ret != 0:\n raise MXNetError(py_str(_LIB.MXGetLastError()))\n\nif sys.version_info[0] < 3:\n def c_str(string):\n \"\"\"Create ctypes char * from a Python string.\n\n Parameters\n ----------\n string : string type\n Python string.\n\n Returns\n -------\n str : c_char_p\n A char pointer that can be passed to C API.\n\n Examples\n --------\n >>> x = mx.base.c_str(\"Hello, World\")\n >>> print x.value\n Hello, World\n \"\"\"\n return ctypes.c_char_p(string)\nelse:\n def c_str(string):\n \"\"\"Create ctypes char * from a Python string.\n\n Parameters\n ----------\n string : string type\n Python string.\n\n Returns\n -------\n str : c_char_p\n A char pointer that can be passed to C API.\n\n Examples\n --------\n >>> x = mx.base.c_str(\"Hello, World\")\n >>> print x.value\n Hello, World\n \"\"\"\n return ctypes.c_char_p(string.encode('utf-8'))\n\n\ndef c_array(ctype, values):\n \"\"\"Create ctypes array from a Python array.\n\n Parameters\n ----------\n ctype : ctypes data type\n Data type of the array we want to convert to, such as mx_float.\n\n values : tuple or list\n Data content.\n\n Returns\n -------\n out : ctypes array\n Created ctypes array.\n\n Examples\n --------\n >>> x = mx.base.c_array(mx.base.mx_float, [1, 2, 3])\n >>> print len(x)\n 3\n >>> x[1]\n 2.0\n \"\"\"\n return (ctype * len(values))(*values)\n\ndef ctypes2buffer(cptr, length):\n \"\"\"Convert ctypes pointer to buffer type.\n\n Parameters\n ----------\n cptr : ctypes.POINTER(ctypes.c_char)\n Pointer to the raw memory region.\n length : int\n The length of the buffer.\n\n Returns\n -------\n buffer : bytearray\n The raw byte memory buffer.\n \"\"\"\n if not isinstance(cptr, ctypes.POINTER(ctypes.c_char)):\n raise TypeError('expected char pointer')\n res = bytearray(length)\n rptr = (ctypes.c_char * length).from_buffer(res)\n if not ctypes.memmove(rptr, cptr, length):\n raise RuntimeError('memmove failed')\n return res\n\ndef ctypes2numpy_shared(cptr, shape):\n \"\"\"Convert a ctypes pointer to a numpy array.\n\n The resulting NumPy array shares the memory with the pointer.\n\n Parameters\n ----------\n cptr : ctypes.POINTER(mx_float)\n pointer to the memory region\n\n shape : tuple\n Shape of target `NDArray`.\n\n Returns\n -------\n out : numpy_array\n A numpy array : numpy array.\n \"\"\"\n if not isinstance(cptr, ctypes.POINTER(mx_float)):\n raise RuntimeError('expected float pointer')\n size = 1\n for s in shape:\n size *= s\n dbuffer = (mx_float * size).from_address(ctypes.addressof(cptr.contents))\n return np.frombuffer(dbuffer, dtype=np.float32).reshape(shape)\n\n\ndef build_param_doc(arg_names, arg_types, arg_descs, remove_dup=True):\n \"\"\"Build argument docs in python style.\n\n arg_names : list of str\n Argument names.\n\n arg_types : list of str\n Argument type information.\n\n arg_descs : list of str\n Argument description information.\n\n remove_dup : boolean, optional\n Whether remove duplication or not.\n\n Returns\n -------\n docstr : str\n Python docstring of parameter sections.\n \"\"\"\n param_keys = set()\n param_str = []\n for key, type_info, desc in zip(arg_names, arg_types, arg_descs):\n if key in param_keys and remove_dup:\n continue\n if key == 'num_args':\n continue\n param_keys.add(key)\n ret = '%s : %s' % (key, type_info)\n if len(desc) != 0:\n ret += '\\n ' + desc\n param_str.append(ret)\n doc_str = ('Parameters\\n' +\n '----------\\n' +\n '%s\\n')\n doc_str = doc_str % ('\\n'.join(param_str))\n return doc_str\n\n\ndef _notify_shutdown():\n \"\"\"Notify MXNet about a shutdown.\"\"\"\n check_call(_LIB.MXNotifyShutdown())\n\natexit.register(_notify_shutdown)\n\ndef add_fileline_to_docstring(module, incursive=True):\n \"\"\"Append the definition position to each function contained in module.\n\n Examples\n --------\n # Put the following codes at the end of a file\n add_fileline_to_docstring(__name__)\n \"\"\"\n\n def _add_fileline(obj):\n \"\"\"Add fileinto to a object.\n \"\"\"\n if obj.__doc__ is None or 'From:' in obj.__doc__:\n return\n fname = inspect.getsourcefile(obj)\n if fname is None:\n return\n try:\n line = inspect.getsourcelines(obj)[-1]\n except IOError:\n return\n obj.__doc__ += '\\n\\nFrom:%s:%d' % (fname, line)\n\n if isinstance(module, str):\n module = sys.modules[module]\n for _, obj in inspect.getmembers(module):\n if inspect.isbuiltin(obj):\n continue\n if inspect.isfunction(obj):\n _add_fileline(obj)\n if inspect.ismethod(obj):\n _add_fileline(obj.__func__)\n if inspect.isclass(obj) and incursive:\n add_fileline_to_docstring(obj, False)\n"
] | [
[
"numpy.frombuffer"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jpivarski/awkward-1.0 | [
"49a3ff13ef90b8778a80573211d58c544729eaa5",
"49a3ff13ef90b8778a80573211d58c544729eaa5",
"49a3ff13ef90b8778a80573211d58c544729eaa5",
"49a3ff13ef90b8778a80573211d58c544729eaa5",
"49a3ff13ef90b8778a80573211d58c544729eaa5",
"49a3ff13ef90b8778a80573211d58c544729eaa5",
"49a3ff13ef90b8778a80573211d58c544729eaa5",
"49a3ff13ef90b8778a80573211d58c544729eaa5"
] | [
"tests/v2/test_0879-non-primitive-with-field.py",
"tests/v2/test_0224-arrow-to-awkward.py",
"tests/v2/test_0410-fix-argminmax-positions-for-missing-values.py",
"tests/v2/test_0198-tutorial-documentation-1.py",
"tests/v2/test_1999-bug1406.py",
"tests/v2/test_0028-add-dressed-types.py",
"tests/v2/test_1072-sort.py",
"tests/v2/test_0008-slices-and-getitem.py"
] | [
"# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE\n\nimport pytest # noqa: F401\nimport numpy as np # noqa: F401\nimport awkward as ak # noqa: F401\n\n\ndef test_unknown_type():\n array = ak._v2.Array({\"x\": np.arange(10)})\n array = ak._v2.operations.with_field(base=array, what=None, where=\"unknown field1\")\n array = ak._v2.operations.with_field(\n base=array, what=[None], where=\"unknown field2\"\n )\n\n # Try to access the type of a single element\n # This raises a ValueError in #879\n tpe1 = array[\"unknown field1\"].type\n tpe2 = array[\"unknown field2\"].type\n assert str(tpe1) == \"10 * ?unknown\"\n assert str(tpe2) == \"10 * ?unknown\"\n\n\ndef test_in_place_wrapper_broadcasting():\n array = ak._v2.Array({\"x\": np.arange(3)})\n array[\"unknown field\"] = None\n\n assert array[\"unknown field\"].tolist() == [None, None, None]\n assert ak._v2.operations.fields(array) == [\"x\", \"unknown field\"]\n",
"# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE\n\nimport pytest # noqa: F401\nimport numpy as np # noqa: F401\nimport awkward as ak # noqa: F401\n\npyarrow = pytest.importorskip(\"pyarrow\")\npytest.importorskip(\"awkward._v2._connect.pyarrow\")\n\nto_list = ak._v2.operations.to_list\n\n\ndef test_toarrow_BitMaskedArray():\n content = ak._v2.highlevel.Array(\n [\"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\"]\n ).layout\n bitmask = ak._v2.index.IndexU8(np.array([40, 34], dtype=np.uint8))\n array = ak._v2.contents.BitMaskedArray(bitmask, content, False, 9, False)\n assert array.to_arrow().to_pylist() == to_list(array)\n\n\ndef test_toarrow_ByteMaskedArray_1():\n content = ak._v2.highlevel.Array(\n [\"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\"]\n ).layout\n bytemask = ak._v2.index.Index8(np.array([False, True, False], dtype=np.bool_))\n array = ak._v2.contents.ByteMaskedArray(bytemask, content, True)\n assert array.to_arrow().to_pylist() == to_list(array)\n\n\ndef test_toarrow_NumpyArray_1():\n array = ak._v2.contents.NumpyArray(np.array([0.0, 1.1, 2.2, 3.3, 4.4, 5.5]))\n assert isinstance(array.to_arrow(), pyarrow.lib.Array)\n assert array.to_arrow().to_pylist() == [0.0, 1.1, 2.2, 3.3, 4.4, 5.5]\n\n\ndef test_toarrow_NumpyArray_2():\n array = ak._v2.contents.NumpyArray(np.array([[0.0, 1.1], [2.2, 3.3], [4.4, 5.5]]))\n assert isinstance(array.to_arrow(), pyarrow.lib.Array)\n assert array.to_arrow().to_pylist() == [[0.0, 1.1], [2.2, 3.3], [4.4, 5.5]]\n\n\ndef test_toarrow_EmptyArray():\n array = ak._v2.contents.EmptyArray()\n assert isinstance(array.to_arrow(), pyarrow.lib.Array)\n assert array.to_arrow().to_pylist() == []\n\n\ndef test_toarrow_ListOffsetArray64():\n content = ak._v2.contents.NumpyArray(\n np.array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9])\n )\n offsets = ak._v2.index.Index64(np.array([0, 3, 3, 5, 6, 9]))\n array = ak._v2.contents.ListOffsetArray(offsets, content)\n assert isinstance(array.to_arrow().storage, pyarrow.LargeListArray)\n assert array.to_arrow().to_pylist() == [\n [1.1, 2.2, 3.3],\n [],\n [4.4, 5.5],\n [6.6],\n [7.7, 8.8, 9.9],\n ]\n assert array[1:].to_arrow().to_pylist() == [\n [],\n [4.4, 5.5],\n [6.6],\n [7.7, 8.8, 9.9],\n ]\n assert array[2:].to_arrow().to_pylist() == [\n [4.4, 5.5],\n [6.6],\n [7.7, 8.8, 9.9],\n ]\n\n\ndef test_toarrow_ListOffsetArrayU32():\n content = ak._v2.contents.NumpyArray(\n np.array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9])\n )\n offsets = ak._v2.index.IndexU32(np.array([0, 3, 3, 5, 6, 9]))\n array = ak._v2.contents.ListOffsetArray(offsets, content)\n assert isinstance(array.to_arrow().storage, pyarrow.ListArray)\n assert array.to_arrow().to_pylist() == [\n [1.1, 2.2, 3.3],\n [],\n [4.4, 5.5],\n [6.6],\n [7.7, 8.8, 9.9],\n ]\n assert array[1:].to_arrow().to_pylist() == [\n [],\n [4.4, 5.5],\n [6.6],\n [7.7, 8.8, 9.9],\n ]\n assert array[2:].to_arrow().to_pylist() == [\n [4.4, 5.5],\n [6.6],\n [7.7, 8.8, 9.9],\n ]\n\n\ndef test_toarrow_ListArray_RegularArray():\n content = ak._v2.highlevel.Array(\n [\"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\"]\n ).layout\n offsets = ak._v2.index.Index32(np.array([0, 3, 3, 5, 6, 9]))\n array = ak._v2.contents.ListOffsetArray(offsets, content)\n assert array.to_arrow().to_pylist() == [\n [\"one\", \"two\", \"three\"],\n [],\n [\"four\", \"five\"],\n [\"six\"],\n [\"seven\", \"eight\", \"nine\"],\n ]\n\n content = ak._v2.contents.NumpyArray(\n np.array([0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10])\n )\n offsets = ak._v2.index.Index64(np.array([0, 3, 3, 5, 6, 10, 10]))\n listoffsetarray = ak._v2.contents.ListOffsetArray(offsets, content)\n regulararray = ak._v2.contents.RegularArray(listoffsetarray, 2, zeros_length=0)\n starts = ak._v2.index.Index64(np.array([0, 1], dtype=np.int64))\n stops = ak._v2.index.Index64(np.array([2, 3], dtype=np.int64))\n listarray = ak._v2.contents.ListArray(starts, stops, regulararray)\n\n assert isinstance(listarray.to_arrow().storage, pyarrow.LargeListArray)\n assert listarray.to_arrow().to_pylist() == [\n [[[0.0, 1.1, 2.2], []], [[3.3, 4.4], [5.5]]],\n [[[3.3, 4.4], [5.5]], [[6.6, 7.7, 8.8, 9.9], []]],\n ]\n assert listarray[1:].to_arrow().to_pylist() == [\n [[[3.3, 4.4], [5.5]], [[6.6, 7.7, 8.8, 9.9], []]],\n ]\n\n assert isinstance(regulararray.to_arrow().storage, pyarrow.FixedSizeListArray)\n assert regulararray.to_arrow().to_pylist() == [\n [[0.0, 1.1, 2.2], []],\n [[3.3, 4.4], [5.5]],\n [[6.6, 7.7, 8.8, 9.9], []],\n ]\n assert regulararray[1:].to_arrow().to_pylist() == [\n [[3.3, 4.4], [5.5]],\n [[6.6, 7.7, 8.8, 9.9], []],\n ]\n\n\ndef test_toarrow_RecordArray():\n content = ak._v2.contents.NumpyArray(\n np.array([0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10])\n )\n offsets = ak._v2.index.Index64(np.array([0, 3, 3, 5, 6, 10, 10]))\n listoffsetarray = ak._v2.contents.ListOffsetArray(offsets, content)\n content1 = ak._v2.contents.NumpyArray(np.array([1, 2, 3, 4, 5]))\n content2 = ak._v2.contents.NumpyArray(\n np.array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9])\n )\n offsets = ak._v2.index.Index32(np.array([0, 3, 3, 5, 6, 9]))\n\n recordarray = ak._v2.contents.RecordArray(\n [content1, listoffsetarray, content2, content1],\n fields=[\"one\", \"two\", \"2\", \"wonky\"],\n )\n\n assert isinstance(recordarray.to_arrow().storage, pyarrow.StructArray)\n assert recordarray.to_arrow().to_pylist() == [\n {\"one\": 1, \"two\": [0.0, 1.1, 2.2], \"2\": 1.1, \"wonky\": 1},\n {\"one\": 2, \"two\": [], \"2\": 2.2, \"wonky\": 2},\n {\"one\": 3, \"two\": [3.3, 4.4], \"2\": 3.3, \"wonky\": 3},\n {\"one\": 4, \"two\": [5.5], \"2\": 4.4, \"wonky\": 4},\n {\"one\": 5, \"two\": [6.6, 7.7, 8.8, 9.9], \"2\": 5.5, \"wonky\": 5},\n ]\n\n\ndef test_toarrow_UnionArray():\n content0 = ak._v2.highlevel.Array([[1.1, 2.2, 3.3], [], [4.4, 5.5]]).layout\n content1 = ak._v2.contents.NumpyArray(np.array([1, 2, 3, 4, 5]))\n tags = ak._v2.index.Index8(np.array([1, 1, 0, 0, 1, 0, 1, 1], dtype=np.int8))\n index = ak._v2.index.Index32(np.array([0, 1, 0, 1, 2, 2, 4, 3], dtype=np.int32))\n unionarray = ak._v2.contents.UnionArray(tags, index, [content0, content1])\n\n assert isinstance(unionarray.to_arrow().storage, pyarrow.UnionArray)\n assert unionarray.to_arrow().to_pylist() == [\n 1,\n 2,\n [1.1, 2.2, 3.3],\n [],\n 3,\n [4.4, 5.5],\n 5,\n 4,\n ]\n\n\ndef test_toarrow_IndexedArray():\n content = ak._v2.contents.NumpyArray(\n np.array([0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9])\n )\n index = ak._v2.index.Index32(np.array([0, 2, 4, 6, 8, 9, 7, 5], dtype=np.int64))\n indexedarray = ak._v2.contents.IndexedArray(index, content)\n\n assert isinstance(indexedarray.to_arrow().storage, pyarrow.lib.DoubleArray)\n assert indexedarray.to_arrow().to_pylist() == [\n 0.0,\n 2.2,\n 4.4,\n 6.6,\n 8.8,\n 9.9,\n 7.7,\n 5.5,\n ]\n\n\ndef test_toarrow_IndexedOptionArray_2():\n array = ak._v2.highlevel.Array([1.1, 2.2, 3.3, 4.4, 5.5, None]).layout\n\n assert array.to_arrow().to_pylist() == [1.1, 2.2, 3.3, 4.4, 5.5, None]\n assert array[:-1].to_arrow().to_pylist() == [1.1, 2.2, 3.3, 4.4, 5.5]\n assert array[:1].to_arrow().to_pylist() == [1.1]\n assert array[:0].to_arrow().to_pylist() == []\n\n content = ak._v2.contents.NumpyArray(np.array([], dtype=np.float64))\n index = ak._v2.index.Index32(np.array([-1, -1, -1, -1], dtype=np.int32))\n indexedoptionarray = ak._v2.contents.IndexedOptionArray(index, content)\n assert indexedoptionarray.to_arrow().to_pylist() == [None, None, None, None]\n\n\ndef test_toarrow_ByteMaskedArray_2():\n content = ak._v2.contents.NumpyArray(\n np.array([0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10])\n )\n offsets = ak._v2.index.Index64(np.array([0, 3, 3, 5, 6, 10, 10], dtype=np.int64))\n listoffsetarray = ak._v2.contents.ListOffsetArray(offsets, content)\n bytemaskedarray = ak._v2.contents.ByteMaskedArray(\n ak._v2.index.Index8(np.array([True, True, False, False, False], dtype=np.int8)),\n listoffsetarray,\n True,\n )\n\n assert bytemaskedarray.to_arrow().to_pylist() == [\n [0.0, 1.1, 2.2],\n [],\n None,\n None,\n None,\n ]\n\n\ndef test_toarrow_ByteMaskedArray_3():\n content = ak._v2.contents.NumpyArray(\n np.array([0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10])\n )\n offsets = ak._v2.index.Index64(np.array([0, 3, 3, 5, 6, 10, 10], dtype=np.int64))\n listoffsetarray = ak._v2.contents.ListOffsetArray(offsets, content)\n regulararray = ak._v2.contents.RegularArray(listoffsetarray, 2, zeros_length=0)\n starts = ak._v2.index.Index64(np.array([0, 1]))\n stops = ak._v2.index.Index64(np.array([2, 3]))\n listarray = ak._v2.contents.ListArray(starts, stops, regulararray)\n\n bytemaskedarray = ak._v2.contents.ByteMaskedArray(\n ak._v2.index.Index8(np.array([True, False], dtype=np.int8)), listarray, True\n )\n assert bytemaskedarray.to_arrow().to_pylist() == to_list(bytemaskedarray)\n\n\ndef test_toarrow_ByteMaskedArray_4():\n content1 = ak._v2.contents.NumpyArray(np.array([1, 2, 3, 4, 5]))\n content2 = ak._v2.contents.NumpyArray(\n np.array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9])\n )\n content = ak._v2.contents.NumpyArray(\n np.array([0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10])\n )\n offsets = ak._v2.index.Index64(np.array([0, 3, 3, 5, 6, 10, 10], dtype=np.int64))\n listoffsetarray = ak._v2.contents.ListOffsetArray(offsets, content)\n recordarray = ak._v2.contents.RecordArray(\n [content1, listoffsetarray, content2, content1],\n fields=[\"one\", \"two\", \"2\", \"wonky\"],\n )\n\n bytemaskedarray = ak._v2.contents.ByteMaskedArray(\n ak._v2.index.Index8(np.array([True, False], dtype=np.int8)), recordarray, True\n )\n assert bytemaskedarray.to_arrow().to_pylist() == to_list(bytemaskedarray)\n\n\ndef test_toarrow_ByteMaskedArray_5():\n content = ak._v2.contents.NumpyArray(\n np.array([0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9])\n )\n index = ak._v2.index.Index32(np.array([0, 2, 4, 6, 8, 9, 7, 5], dtype=np.int64))\n indexedarray = ak._v2.contents.IndexedArray(index, content)\n\n bytemaskedarray = ak._v2.contents.ByteMaskedArray(\n ak._v2.index.Index8(np.array([True, False, False], dtype=np.int8)),\n indexedarray,\n True,\n )\n assert bytemaskedarray.to_arrow().to_pylist() == to_list(bytemaskedarray)\n\n\ndef test_toarrow_ByteMaskedArray_broken_unions_1():\n content0 = ak._v2.highlevel.Array(\n [[0.0, 1.1, 2.2], [], [3.3, 4.4], [5.5], [6.6, 7.7, 8.8, 9.9]]\n ).layout\n content1 = ak._v2.contents.NumpyArray(np.array([0.0, 1.1, 2.2, 3.3, 4.4]))\n tags = ak._v2.index.Index8(np.array([1, 1, 0, 0, 1, 0, 1, 1, 0, 0], dtype=np.int8))\n index = ak._v2.index.Index32(\n np.array([0, 1, 1, 0, 2, 2, 4, 3, 3, 4], dtype=np.int32)\n )\n unionarray = ak._v2.contents.UnionArray(tags, index, [content0, content1])\n\n bytemaskedarray = ak._v2.contents.ByteMaskedArray(\n ak._v2.index.Index8(\n # tags 1, 1, 0, 0, 1, 0, 1, 1, 0, 0\n # index 0, 1, 1, 0, 2, 2, 4, 3, 3, 4\n np.array(\n [True, False, False, True, False, True, True, False, False, True],\n dtype=np.int8,\n )\n ),\n unionarray,\n valid_when=True,\n )\n assert bytemaskedarray.to_arrow().to_pylist() == to_list(bytemaskedarray)\n\n\ndef test_toarrow_ByteMaskedArray_broken_unions_2():\n content0 = ak._v2.highlevel.Array(\n [[0.0, 1.1, 2.2], [], [3.3, 4.4], [5.5], [6.6, 7.7, 8.8, 9.9]]\n ).layout\n content1 = ak._v2.contents.NumpyArray(np.array([0.0, 1.1, 2.2, 3.3, 4.4]))\n tags = ak._v2.index.Index8(\n np.array([1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0], dtype=np.int8)\n )\n index = ak._v2.index.Index32(\n np.array([0, 1, 1, 0, 2, 2, 4, 3, 3, 4, 3], dtype=np.int32)\n )\n unionarray = ak._v2.contents.UnionArray(tags, index, [content0, content1])\n\n bytemaskedarray = ak._v2.contents.ByteMaskedArray(\n ak._v2.index.Index8(\n # tags 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0\n # index 0, 1, 1, 0, 2, 2, 4, 3, 3, 4, 3\n np.array(\n [True, False, False, True, False, True, True, False, False, True, True],\n dtype=np.int8,\n )\n ),\n unionarray,\n valid_when=True,\n )\n assert bytemaskedarray.to_arrow().to_pylist() == to_list(bytemaskedarray)\n\n\ndef test_toarrow_IndexedOptionArray():\n ioa = ak._v2.contents.IndexedOptionArray(\n ak._v2.index.Index32([-30, 19, 6, 7, -3, 21, 13, 22, 17, 9, -12, 16]),\n ak._v2.contents.NumpyArray(\n np.array(\n [\n 5.2,\n 1.7,\n 6.7,\n -0.4,\n 4.0,\n 7.8,\n 3.8,\n 6.8,\n 4.2,\n 0.3,\n 4.6,\n 6.2,\n 6.9,\n -0.7,\n 3.9,\n 1.6,\n 8.7,\n -0.7,\n 3.2,\n 4.3,\n 4.0,\n 5.8,\n 4.2,\n 7.0,\n 5.6,\n 3.8,\n ]\n )\n ),\n )\n assert ioa.to_arrow().to_pylist() == to_list(ioa)\n\n\ndef test_fromarrow_NumpyArray_1():\n boolarray = ak._v2.contents.NumpyArray(\n np.array([True, True, True, False, False, True, False, True, False, True])\n )\n assert to_list(\n ak._v2._connect.pyarrow.handle_arrow(boolarray.to_arrow())\n ) == to_list(boolarray)\n\n\ndef test_fromarrow_NumpyArray_2():\n content = ak._v2.contents.NumpyArray(\n np.array([0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10])\n )\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(content.to_arrow())) == to_list(\n content\n )\n\n\ndef test_fromarrow_ListOffsetArray():\n content = ak._v2.contents.NumpyArray(\n np.array([0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10])\n )\n offsets = ak._v2.index.Index64(np.array([0, 3, 3, 5, 6, 10, 10]))\n listoffsetarray = ak._v2.contents.ListOffsetArray(offsets, content)\n assert to_list(\n ak._v2._connect.pyarrow.handle_arrow(listoffsetarray.to_arrow())\n ) == to_list(listoffsetarray)\n\n\ndef test_fromarrow_RegularArray():\n content = ak._v2.contents.NumpyArray(\n np.array([0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10])\n )\n offsets = ak._v2.index.Index64(np.array([0, 3, 3, 5, 6, 10, 10], dtype=np.int64))\n listoffsetarray = ak._v2.contents.ListOffsetArray(offsets, content)\n\n regulararray = ak._v2.contents.RegularArray(listoffsetarray, 2, zeros_length=0)\n assert to_list(\n ak._v2._connect.pyarrow.handle_arrow(regulararray.to_arrow())\n ) == to_list(regulararray)\n\n\ndef test_fromarrow_RecordArray():\n content = ak._v2.contents.NumpyArray(\n np.array([0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10])\n )\n offsets = ak._v2.index.Index64(np.array([0, 3, 3, 5, 6, 10, 10], dtype=np.int64))\n listoffsetarray = ak._v2.contents.ListOffsetArray(offsets, content)\n\n content1 = ak._v2.contents.NumpyArray(np.array([1, 2, 3, 4, 5]))\n content2 = ak._v2.contents.NumpyArray(\n np.array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9])\n )\n offsets = ak._v2.index.Index32(np.array([0, 3, 3, 5, 6, 9]))\n recordarray = ak._v2.contents.RecordArray(\n [content1, listoffsetarray, content2, content1],\n fields=[\"one\", \"chonks\", \"2\", \"wonky\"],\n )\n assert to_list(\n ak._v2._connect.pyarrow.handle_arrow(recordarray.to_arrow())\n ) == to_list(recordarray)\n\n\ndef test_fromarrow_UnionArray():\n content0 = ak._v2.highlevel.Array([[1.1, 2.2, 3.3], [], [4.4, 5.5]]).layout\n content = ak._v2.highlevel.Array(\n [\"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\"]\n ).layout\n tags = ak._v2.index.Index8(np.array([1, 1, 0, 0, 1, 0, 1, 1], dtype=np.int8))\n index = ak._v2.index.Index32(np.array([0, 1, 0, 1, 2, 2, 4, 3], dtype=np.int32))\n array = ak._v2.contents.UnionArray(tags, index, [content0, content])\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(array.to_arrow())) == to_list(\n array\n )\n\n\ndef test_chunkedarray():\n a = pyarrow.chunked_array(\n [\n pyarrow.array([1.1, 2.2, 3.3]),\n pyarrow.array([], pyarrow.float64()),\n pyarrow.array([4.4, 5.5]),\n pyarrow.array([6.6]),\n pyarrow.array([], pyarrow.float64()),\n pyarrow.array([], pyarrow.float64()),\n pyarrow.array([7.7, 8.8, 9.9]),\n ]\n )\n assert a.to_pylist() == [1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9]\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n 1.1,\n 2.2,\n 3.3,\n 4.4,\n 5.5,\n 6.6,\n 7.7,\n 8.8,\n 9.9,\n ]\n\n\ndef test_recordbatch():\n a = pyarrow.RecordBatch.from_arrays(\n [\n pyarrow.array([1.1, 2.2, 3.3, 4.4, 5.5]),\n pyarrow.array([[1, 2, 3], [], [], [4, 5], [6]]),\n ],\n [\"a\", \"b\"],\n )\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n {\"a\": 1.1, \"b\": [1, 2, 3]},\n {\"a\": 2.2, \"b\": []},\n {\"a\": 3.3, \"b\": []},\n {\"a\": 4.4, \"b\": [4, 5]},\n {\"a\": 5.5, \"b\": [6]},\n ]\n\n a = pyarrow.RecordBatch.from_arrays(\n [\n pyarrow.array([1.1, 2.2, 3.3, None, 5.5]),\n pyarrow.array([[1, None, 3], [], [], [4, 5], [6]]),\n ],\n [\"a\", \"b\"],\n )\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n {\"a\": 1.1, \"b\": [1, None, 3]},\n {\"a\": 2.2, \"b\": []},\n {\"a\": 3.3, \"b\": []},\n {\"a\": None, \"b\": [4, 5]},\n {\"a\": 5.5, \"b\": [6]},\n ]\n\n a = pyarrow.RecordBatch.from_arrays(\n [\n pyarrow.array([1.1, 2.2, 3.3, None, 5.5]),\n pyarrow.array([[1, 2, 3], [], [4, 5], [None], [6]]),\n pyarrow.array(\n [\n {\"x\": 1, \"y\": 1.1},\n {\"x\": 2, \"y\": 2.2},\n {\"x\": 3, \"y\": 3.3},\n {\"x\": 4, \"y\": None},\n {\"x\": 5, \"y\": 5.5},\n ]\n ),\n pyarrow.array(\n [\n {\"x\": 1, \"y\": 1.1},\n None,\n None,\n {\"x\": 4, \"y\": None},\n {\"x\": 5, \"y\": 5.5},\n ]\n ),\n pyarrow.array(\n [\n [{\"x\": 1, \"y\": 1.1}, {\"x\": 2, \"y\": 2.2}, {\"x\": 3, \"y\": 3.3}],\n [],\n [{\"x\": 4, \"y\": None}, {\"x\": 5, \"y\": 5.5}],\n [None],\n [{\"x\": 6, \"y\": 6.6}],\n ]\n ),\n ],\n [\"a\", \"b\", \"c\", \"d\", \"e\"],\n )\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n {\n \"a\": 1.1,\n \"b\": [1, 2, 3],\n \"c\": {\"x\": 1, \"y\": 1.1},\n \"d\": {\"x\": 1, \"y\": 1.1},\n \"e\": [{\"x\": 1, \"y\": 1.1}, {\"x\": 2, \"y\": 2.2}, {\"x\": 3, \"y\": 3.3}],\n },\n {\"a\": 2.2, \"b\": [], \"c\": {\"x\": 2, \"y\": 2.2}, \"d\": None, \"e\": []},\n {\n \"a\": 3.3,\n \"b\": [4, 5],\n \"c\": {\"x\": 3, \"y\": 3.3},\n \"d\": None,\n \"e\": [{\"x\": 4, \"y\": None}, {\"x\": 5, \"y\": 5.5}],\n },\n {\n \"a\": None,\n \"b\": [None],\n \"c\": {\"x\": 4, \"y\": None},\n \"d\": {\"x\": 4, \"y\": None},\n \"e\": [None],\n },\n {\n \"a\": 5.5,\n \"b\": [6],\n \"c\": {\"x\": 5, \"y\": 5.5},\n \"d\": {\"x\": 5, \"y\": 5.5},\n \"e\": [{\"x\": 6, \"y\": 6.6}],\n },\n ]\n\n\n### All of the following tests were copied (translated) over from Awkward 0.\n\n\ndef test_arrow_toarrow_string():\n a = ak._v2.operations.from_iter([\"one\", \"two\", \"three\"]).layout\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a.to_arrow())) == to_list(a)\n a = ak._v2.operations.from_iter(\n [[\"one\", \"two\", \"three\"], [], [\"four\", \"five\"]]\n ).layout\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a.to_arrow())) == to_list(a)\n if hasattr(pyarrow.BinaryArray, \"from_buffers\"):\n a = ak._v2.operations.from_iter([b\"one\", b\"two\", b\"three\"]).layout\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a.to_arrow())) == [\n b\"one\",\n b\"two\",\n b\"three\",\n ]\n a = ak._v2.operations.from_iter(\n [[b\"one\", b\"two\", b\"three\"], [], [b\"four\", b\"five\"]]\n ).layout\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a.to_arrow())) == [\n [b\"one\", b\"two\", b\"three\"],\n [],\n [b\"four\", b\"five\"],\n ]\n else:\n a = ak._v2.operations.from_iter([b\"one\", b\"two\", b\"three\"]).layout\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a.to_arrow())) == [\n \"one\",\n \"two\",\n \"three\",\n ]\n a = ak._v2.operations.from_iter(\n [[b\"one\", b\"two\", b\"three\"], [], [b\"four\", b\"five\"]]\n ).layout\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a.to_arrow())) == [\n [\"one\", \"two\", \"three\"],\n [],\n [\"four\", \"five\"],\n ]\n\n\ndef test_arrow_array():\n a = pyarrow.array([1.1, 2.2, 3.3, 4.4, 5.5])\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n 1.1,\n 2.2,\n 3.3,\n 4.4,\n 5.5,\n ]\n\n\ndef test_arrow_boolean():\n a = pyarrow.array([True, True, False, False, True])\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n True,\n True,\n False,\n False,\n True,\n ]\n\n\ndef test_arrow_array_null():\n a = pyarrow.array([1.1, 2.2, 3.3, None, 4.4, 5.5])\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n 1.1,\n 2.2,\n 3.3,\n None,\n 4.4,\n 5.5,\n ]\n\n\ndef test_arrow_nested_array():\n a = pyarrow.array([[1.1, 2.2, 3.3], [], [4.4, 5.5]])\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n [1.1, 2.2, 3.3],\n [],\n [4.4, 5.5],\n ]\n\n\ndef test_arrow_nested_nested_array():\n a = pyarrow.array([[[1.1, 2.2], [3.3], []], [], [[4.4, 5.5]]])\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n [[1.1, 2.2], [3.3], []],\n [],\n [[4.4, 5.5]],\n ]\n\n\ndef test_arrow_nested_array_null():\n a = pyarrow.array([[1.1, 2.2, None], [], [4.4, 5.5]])\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n [1.1, 2.2, None],\n [],\n [4.4, 5.5],\n ]\n\n\ndef test_arrow_null_nested_array_null():\n a = pyarrow.array([[1.1, 2.2, None], [], None, [4.4, 5.5]])\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n [1.1, 2.2, None],\n [],\n None,\n [4.4, 5.5],\n ]\n\n\ndef test_arrow_chunked_array():\n a = pyarrow.chunked_array(\n [\n pyarrow.array([1.1, 2.2, 3.3, 4.4, 5.5]),\n pyarrow.array([], pyarrow.float64()),\n pyarrow.array([6.6, 7.7, 8.8]),\n ]\n )\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n 1.1,\n 2.2,\n 3.3,\n 4.4,\n 5.5,\n 6.6,\n 7.7,\n 8.8,\n ]\n\n\ndef test_arrow_struct():\n a = pyarrow.array([{\"x\": 1, \"y\": 1.1}, {\"x\": 2, \"y\": 2.2}, {\"x\": 3, \"y\": 3.3}])\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n {\"x\": 1, \"y\": 1.1},\n {\"x\": 2, \"y\": 2.2},\n {\"x\": 3, \"y\": 3.3},\n ]\n\n\ndef test_arrow_struct_null():\n a = pyarrow.array([{\"x\": 1, \"y\": 1.1}, {\"x\": 2, \"y\": None}, {\"x\": 3, \"y\": 3.3}])\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n {\"x\": 1, \"y\": 1.1},\n {\"x\": 2, \"y\": None},\n {\"x\": 3, \"y\": 3.3},\n ]\n\n\ndef test_arrow_null_struct():\n a = pyarrow.array(\n [{\"x\": 1, \"y\": 1.1}, None, {\"x\": 2, \"y\": 2.2}, {\"x\": 3, \"y\": 3.3}]\n )\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n {\"x\": 1, \"y\": 1.1},\n None,\n {\"x\": 2, \"y\": 2.2},\n {\"x\": 3, \"y\": 3.3},\n ]\n\n\ndef test_arrow_null_struct_null():\n a = pyarrow.array(\n [{\"x\": 1, \"y\": 1.1}, None, {\"x\": 2, \"y\": None}, {\"x\": 3, \"y\": 3.3}]\n )\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n {\"x\": 1, \"y\": 1.1},\n None,\n {\"x\": 2, \"y\": None},\n {\"x\": 3, \"y\": 3.3},\n ]\n\n\ndef test_arrow_chunked_struct():\n t = pyarrow.struct({\"x\": pyarrow.int64(), \"y\": pyarrow.float64()})\n a = pyarrow.chunked_array(\n [\n pyarrow.array(\n [{\"x\": 1, \"y\": 1.1}, {\"x\": 2, \"y\": 2.2}, {\"x\": 3, \"y\": 3.3}], t\n ),\n pyarrow.array([], t),\n pyarrow.array([{\"x\": 4, \"y\": 4.4}, {\"x\": 5, \"y\": 5.5}], t),\n ]\n )\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n {\"x\": 1, \"y\": 1.1},\n {\"x\": 2, \"y\": 2.2},\n {\"x\": 3, \"y\": 3.3},\n {\"x\": 4, \"y\": 4.4},\n {\"x\": 5, \"y\": 5.5},\n ]\n\n\ndef test_arrow_nested_struct():\n a = pyarrow.array(\n [\n [{\"x\": 1, \"y\": 1.1}, {\"x\": 2, \"y\": 2.2}, {\"x\": 3, \"y\": 3.3}],\n [],\n [{\"x\": 4, \"y\": 4.4}, {\"x\": 5, \"y\": 5.5}],\n ]\n )\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n [{\"x\": 1, \"y\": 1.1}, {\"x\": 2, \"y\": 2.2}, {\"x\": 3, \"y\": 3.3}],\n [],\n [{\"x\": 4, \"y\": 4.4}, {\"x\": 5, \"y\": 5.5}],\n ]\n\n\ndef test_arrow_nested_struct_null():\n a = pyarrow.array(\n [\n [{\"x\": 1, \"y\": 1.1}, {\"x\": 2, \"y\": None}, {\"x\": 3, \"y\": 3.3}],\n [],\n [{\"x\": 4, \"y\": 4.4}, {\"x\": 5, \"y\": 5.5}],\n ]\n )\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n [{\"x\": 1, \"y\": 1.1}, {\"x\": 2, \"y\": None}, {\"x\": 3, \"y\": 3.3}],\n [],\n [{\"x\": 4, \"y\": 4.4}, {\"x\": 5, \"y\": 5.5}],\n ]\n\n\ndef test_arrow_null_nested_struct():\n a = pyarrow.array(\n [\n [{\"x\": 1, \"y\": 1.1}, {\"x\": 2, \"y\": 2.2}, {\"x\": 3, \"y\": 3.3}],\n None,\n [],\n [{\"x\": 4, \"y\": 4.4}, {\"x\": 5, \"y\": 5.5}],\n ]\n )\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n [{\"x\": 1, \"y\": 1.1}, {\"x\": 2, \"y\": 2.2}, {\"x\": 3, \"y\": 3.3}],\n None,\n [],\n [{\"x\": 4, \"y\": 4.4}, {\"x\": 5, \"y\": 5.5}],\n ]\n\n\ndef test_arrow_null_nested_struct_null():\n a = pyarrow.array(\n [\n [{\"x\": 1, \"y\": 1.1}, {\"x\": 2, \"y\": None}, {\"x\": 3, \"y\": 3.3}],\n None,\n [],\n [{\"x\": 4, \"y\": 4.4}, {\"x\": 5, \"y\": 5.5}],\n ]\n )\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n [{\"x\": 1, \"y\": 1.1}, {\"x\": 2, \"y\": None}, {\"x\": 3, \"y\": 3.3}],\n None,\n [],\n [{\"x\": 4, \"y\": 4.4}, {\"x\": 5, \"y\": 5.5}],\n ]\n\n\ndef test_arrow_struct_nested():\n a = pyarrow.array(\n [{\"x\": [], \"y\": 1.1}, {\"x\": [2], \"y\": 2.2}, {\"x\": [3, 3], \"y\": 3.3}]\n )\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n {\"x\": [], \"y\": 1.1},\n {\"x\": [2], \"y\": 2.2},\n {\"x\": [3, 3], \"y\": 3.3},\n ]\n\n\ndef test_arrow_struct_nested_null():\n a = pyarrow.array(\n [{\"x\": [], \"y\": 1.1}, {\"x\": [2], \"y\": 2.2}, {\"x\": [None, 3], \"y\": 3.3}]\n )\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n {\"x\": [], \"y\": 1.1},\n {\"x\": [2], \"y\": 2.2},\n {\"x\": [None, 3], \"y\": 3.3},\n ]\n\n\ndef test_arrow_nested_struct_nested():\n a = pyarrow.array(\n [\n [{\"x\": [], \"y\": 1.1}, {\"x\": [2], \"y\": 2.2}, {\"x\": [3, 3], \"y\": 3.3}],\n [],\n [{\"x\": [4, 4, 4], \"y\": 4.4}, {\"x\": [5, 5, 5, 5], \"y\": 5.5}],\n ]\n )\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n [{\"x\": [], \"y\": 1.1}, {\"x\": [2], \"y\": 2.2}, {\"x\": [3, 3], \"y\": 3.3}],\n [],\n [{\"x\": [4, 4, 4], \"y\": 4.4}, {\"x\": [5, 5, 5, 5], \"y\": 5.5}],\n ]\n\n\ndef test_arrow_null_nested_struct_nested_null():\n a = pyarrow.array(\n [\n [{\"x\": [], \"y\": 1.1}, {\"x\": [2], \"y\": 2.2}, {\"x\": [None, 3], \"y\": 3.3}],\n None,\n [],\n [{\"x\": [4, 4, 4], \"y\": 4.4}, {\"x\": [5, 5, 5, 5], \"y\": 5.5}],\n ]\n )\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n [{\"x\": [], \"y\": 1.1}, {\"x\": [2], \"y\": 2.2}, {\"x\": [None, 3], \"y\": 3.3}],\n None,\n [],\n [{\"x\": [4, 4, 4], \"y\": 4.4}, {\"x\": [5, 5, 5, 5], \"y\": 5.5}],\n ]\n\n\ndef test_arrow_strings():\n a = pyarrow.array([\"one\", \"two\", \"three\", \"fo\\u2014ur\", \"five\"])\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n \"one\",\n \"two\",\n \"three\",\n \"fo\\u2014ur\",\n \"five\",\n ]\n\n\ndef test_arrow_strings_null():\n a = pyarrow.array([\"one\", \"two\", None, \"fo\\u2014ur\", \"five\"])\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n \"one\",\n \"two\",\n None,\n \"fo\\u2014ur\",\n \"five\",\n ]\n\n\ndef test_arrow_binary():\n a = pyarrow.array([b\"one\", b\"two\", b\"three\", b\"four\", b\"five\"])\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n b\"one\",\n b\"two\",\n b\"three\",\n b\"four\",\n b\"five\",\n ]\n\n\ndef test_arrow_binary_null():\n a = pyarrow.array([b\"one\", b\"two\", None, b\"four\", b\"five\"])\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n b\"one\",\n b\"two\",\n None,\n b\"four\",\n b\"five\",\n ]\n\n\ndef test_arrow_chunked_strings():\n a = pyarrow.chunked_array(\n [\n pyarrow.array([\"one\", \"two\", \"three\", \"four\", \"five\"]),\n pyarrow.array([\"six\", \"seven\", \"eight\"]),\n ]\n )\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n \"one\",\n \"two\",\n \"three\",\n \"four\",\n \"five\",\n \"six\",\n \"seven\",\n \"eight\",\n ]\n\n\ndef test_arrow_nested_strings():\n a = pyarrow.array([[\"one\", \"two\", \"three\"], [], [\"four\", \"five\"]])\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n [\"one\", \"two\", \"three\"],\n [],\n [\"four\", \"five\"],\n ]\n\n\ndef test_arrow_nested_strings_null():\n a = pyarrow.array([[\"one\", \"two\", None], [], [\"four\", \"five\"]])\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n [\"one\", \"two\", None],\n [],\n [\"four\", \"five\"],\n ]\n\n\ndef test_arrow_null_nested_strings_null():\n a = pyarrow.array([[\"one\", \"two\", None], [], None, [\"four\", \"five\"]])\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n [\"one\", \"two\", None],\n [],\n None,\n [\"four\", \"five\"],\n ]\n\n\ndef test_arrow_union_sparse():\n a = pyarrow.UnionArray.from_sparse(\n pyarrow.array([0, 1, 0, 0, 1], type=pyarrow.int8()),\n [\n pyarrow.array([0.0, 1.1, 2.2, 3.3, 4.4]),\n pyarrow.array([True, True, False, True, False]),\n ],\n )\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n 0.0,\n True,\n 2.2,\n 3.3,\n False,\n ]\n\n\ndef test_arrow_union_sparse_null():\n a = pyarrow.UnionArray.from_sparse(\n pyarrow.array([0, 1, 0, 0, 1], type=pyarrow.int8()),\n [\n pyarrow.array([0.0, 1.1, None, 3.3, 4.4]),\n pyarrow.array([True, True, False, True, False]),\n ],\n )\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n 0.0,\n True,\n None,\n 3.3,\n False,\n ]\n\n\ndef test_arrow_union_sparse_null_null():\n a = pyarrow.UnionArray.from_sparse(\n pyarrow.array([0, 1, 0, 0, 1], type=pyarrow.int8()),\n [\n pyarrow.array([0.0, 1.1, None, 3.3, 4.4]),\n pyarrow.array([True, None, False, True, False]),\n ],\n )\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n 0.0,\n None,\n None,\n 3.3,\n False,\n ]\n\n\ndef test_arrow_union_dense():\n a = pyarrow.UnionArray.from_dense(\n pyarrow.array([0, 1, 0, 0, 0, 1, 1], type=pyarrow.int8()),\n pyarrow.array([0, 0, 1, 2, 3, 1, 2], type=pyarrow.int32()),\n [pyarrow.array([0.0, 1.1, 2.2, 3.3]), pyarrow.array([True, True, False])],\n )\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n 0.0,\n True,\n 1.1,\n 2.2,\n 3.3,\n True,\n False,\n ]\n\n\ndef test_arrow_union_dense_null():\n a = pyarrow.UnionArray.from_dense(\n pyarrow.array([0, 1, 0, 0, 0, 1, 1], type=pyarrow.int8()),\n pyarrow.array([0, 0, 1, 2, 3, 1, 2], type=pyarrow.int32()),\n [pyarrow.array([0.0, 1.1, None, 3.3]), pyarrow.array([True, True, False])],\n )\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n 0.0,\n True,\n 1.1,\n None,\n 3.3,\n True,\n False,\n ]\n\n\ndef test_arrow_union_dense_null_null():\n a = pyarrow.UnionArray.from_dense(\n pyarrow.array([0, 1, 0, 0, 0, 1, 1], type=pyarrow.int8()),\n pyarrow.array([0, 0, 1, 2, 3, 1, 2], type=pyarrow.int32()),\n [pyarrow.array([0.0, 1.1, None, 3.3]), pyarrow.array([True, None, False])],\n )\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n 0.0,\n True,\n 1.1,\n None,\n 3.3,\n None,\n False,\n ]\n\n\ndef test_arrow_dictarray():\n a = pyarrow.DictionaryArray.from_arrays(\n pyarrow.array([0, 0, 2, 2, 1, 0, 2, 1, 1]),\n pyarrow.array([\"one\", \"two\", \"three\"]),\n )\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n \"one\",\n \"one\",\n \"three\",\n \"three\",\n \"two\",\n \"one\",\n \"three\",\n \"two\",\n \"two\",\n ]\n\n\ndef test_arrow_dictarray_null():\n a = pyarrow.DictionaryArray.from_arrays(\n pyarrow.array([0, 0, 2, None, 1, None, 2, 1, 1]),\n pyarrow.array([\"one\", \"two\", \"three\"]),\n )\n print(a)\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n \"one\",\n \"one\",\n \"three\",\n None,\n \"two\",\n None,\n \"three\",\n \"two\",\n \"two\",\n ]\n\n\ndef test_arrow_null_dictarray():\n a = pyarrow.DictionaryArray.from_arrays(\n pyarrow.array([0, 0, 2, 2, 1, 0, 2, 1, 1]),\n pyarrow.array([\"one\", None, \"three\"]),\n )\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n \"one\",\n \"one\",\n \"three\",\n \"three\",\n None,\n \"one\",\n \"three\",\n None,\n None,\n ]\n\n\ndef test_arrow_batch():\n a = pyarrow.RecordBatch.from_arrays(\n [\n pyarrow.array([1.1, 2.2, 3.3, None, 5.5]),\n pyarrow.array([[1, 2, 3], [], [4, 5], [None], [6]]),\n pyarrow.array(\n [\n {\"x\": 1, \"y\": 1.1},\n {\"x\": 2, \"y\": 2.2},\n {\"x\": 3, \"y\": 3.3},\n {\"x\": 4, \"y\": None},\n {\"x\": 5, \"y\": 5.5},\n ]\n ),\n pyarrow.array(\n [\n {\"x\": 1, \"y\": 1.1},\n None,\n None,\n {\"x\": 4, \"y\": None},\n {\"x\": 5, \"y\": 5.5},\n ]\n ),\n pyarrow.array(\n [\n [{\"x\": 1, \"y\": 1.1}, {\"x\": 2, \"y\": 2.2}, {\"x\": 3, \"y\": 3.3}],\n [],\n [{\"x\": 4, \"y\": None}, {\"x\": 5, \"y\": 5.5}],\n [None],\n [{\"x\": 6, \"y\": 6.6}],\n ]\n ),\n ],\n [\"a\", \"b\", \"c\", \"d\", \"e\"],\n )\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n {\n \"a\": 1.1,\n \"b\": [1, 2, 3],\n \"c\": {\"x\": 1, \"y\": 1.1},\n \"d\": {\"x\": 1, \"y\": 1.1},\n \"e\": [{\"x\": 1, \"y\": 1.1}, {\"x\": 2, \"y\": 2.2}, {\"x\": 3, \"y\": 3.3}],\n },\n {\"a\": 2.2, \"b\": [], \"c\": {\"x\": 2, \"y\": 2.2}, \"d\": None, \"e\": []},\n {\n \"a\": 3.3,\n \"b\": [4, 5],\n \"c\": {\"x\": 3, \"y\": 3.3},\n \"d\": None,\n \"e\": [{\"x\": 4, \"y\": None}, {\"x\": 5, \"y\": 5.5}],\n },\n {\n \"a\": None,\n \"b\": [None],\n \"c\": {\"x\": 4, \"y\": None},\n \"d\": {\"x\": 4, \"y\": None},\n \"e\": [None],\n },\n {\n \"a\": 5.5,\n \"b\": [6],\n \"c\": {\"x\": 5, \"y\": 5.5},\n \"d\": {\"x\": 5, \"y\": 5.5},\n \"e\": [{\"x\": 6, \"y\": 6.6}],\n },\n ]\n\n\ndef test_arrow_table():\n a = pyarrow.Table.from_batches(\n [\n pyarrow.RecordBatch.from_arrays(\n [\n pyarrow.array([1.1, 2.2, 3.3, None, 5.5]),\n pyarrow.array([[1, 2, 3], [], [4, 5], [None], [6]]),\n pyarrow.array(\n [\n {\"x\": 1, \"y\": 1.1},\n {\"x\": 2, \"y\": 2.2},\n {\"x\": 3, \"y\": 3.3},\n {\"x\": 4, \"y\": None},\n {\"x\": 5, \"y\": 5.5},\n ]\n ),\n pyarrow.array(\n [\n {\"x\": 1, \"y\": 1.1},\n None,\n None,\n {\"x\": 4, \"y\": None},\n {\"x\": 5, \"y\": 5.5},\n ]\n ),\n pyarrow.array(\n [\n [\n {\"x\": 1, \"y\": 1.1},\n {\"x\": 2, \"y\": 2.2},\n {\"x\": 3, \"y\": 3.3},\n ],\n [],\n [{\"x\": 4, \"y\": None}, {\"x\": 5, \"y\": 5.5}],\n [None],\n [{\"x\": 6, \"y\": 6.6}],\n ]\n ),\n ],\n [\"a\", \"b\", \"c\", \"d\", \"e\"],\n ),\n pyarrow.RecordBatch.from_arrays(\n [\n pyarrow.array([1.1, 2.2, 3.3, None, 5.5]),\n pyarrow.array([[1, 2, 3], [], [4, 5], [None], [6]]),\n pyarrow.array(\n [\n {\"x\": 1, \"y\": 1.1},\n {\"x\": 2, \"y\": 2.2},\n {\"x\": 3, \"y\": 3.3},\n {\"x\": 4, \"y\": None},\n {\"x\": 5, \"y\": 5.5},\n ]\n ),\n pyarrow.array(\n [\n {\"x\": 1, \"y\": 1.1},\n None,\n None,\n {\"x\": 4, \"y\": None},\n {\"x\": 5, \"y\": 5.5},\n ]\n ),\n pyarrow.array(\n [\n [\n {\"x\": 1, \"y\": 1.1},\n {\"x\": 2, \"y\": 2.2},\n {\"x\": 3, \"y\": 3.3},\n ],\n [],\n [{\"x\": 4, \"y\": None}, {\"x\": 5, \"y\": 5.5}],\n [None],\n [{\"x\": 6, \"y\": 6.6}],\n ]\n ),\n ],\n [\"a\", \"b\", \"c\", \"d\", \"e\"],\n ),\n ]\n )\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n {\n \"a\": 1.1,\n \"b\": [1, 2, 3],\n \"c\": {\"x\": 1, \"y\": 1.1},\n \"d\": {\"x\": 1, \"y\": 1.1},\n \"e\": [{\"x\": 1, \"y\": 1.1}, {\"x\": 2, \"y\": 2.2}, {\"x\": 3, \"y\": 3.3}],\n },\n {\"a\": 2.2, \"b\": [], \"c\": {\"x\": 2, \"y\": 2.2}, \"d\": None, \"e\": []},\n {\n \"a\": 3.3,\n \"b\": [4, 5],\n \"c\": {\"x\": 3, \"y\": 3.3},\n \"d\": None,\n \"e\": [{\"x\": 4, \"y\": None}, {\"x\": 5, \"y\": 5.5}],\n },\n {\n \"a\": None,\n \"b\": [None],\n \"c\": {\"x\": 4, \"y\": None},\n \"d\": {\"x\": 4, \"y\": None},\n \"e\": [None],\n },\n {\n \"a\": 5.5,\n \"b\": [6],\n \"c\": {\"x\": 5, \"y\": 5.5},\n \"d\": {\"x\": 5, \"y\": 5.5},\n \"e\": [{\"x\": 6, \"y\": 6.6}],\n },\n {\n \"a\": 1.1,\n \"b\": [1, 2, 3],\n \"c\": {\"x\": 1, \"y\": 1.1},\n \"d\": {\"x\": 1, \"y\": 1.1},\n \"e\": [{\"x\": 1, \"y\": 1.1}, {\"x\": 2, \"y\": 2.2}, {\"x\": 3, \"y\": 3.3}],\n },\n {\"a\": 2.2, \"b\": [], \"c\": {\"x\": 2, \"y\": 2.2}, \"d\": None, \"e\": []},\n {\n \"a\": 3.3,\n \"b\": [4, 5],\n \"c\": {\"x\": 3, \"y\": 3.3},\n \"d\": None,\n \"e\": [{\"x\": 4, \"y\": None}, {\"x\": 5, \"y\": 5.5}],\n },\n {\n \"a\": None,\n \"b\": [None],\n \"c\": {\"x\": 4, \"y\": None},\n \"d\": {\"x\": 4, \"y\": None},\n \"e\": [None],\n },\n {\n \"a\": 5.5,\n \"b\": [6],\n \"c\": {\"x\": 5, \"y\": 5.5},\n \"d\": {\"x\": 5, \"y\": 5.5},\n \"e\": [{\"x\": 6, \"y\": 6.6}],\n },\n ]\n\n\ndef test_arrow_nonnullable_table():\n x = pyarrow.array([1, 2, 3])\n y = pyarrow.array([1.1, 2.2, 3.3])\n table = pyarrow.Table.from_arrays([x], [\"x\"])\n if hasattr(pyarrow, \"column\"):\n table2 = table.add_column(\n 1,\n pyarrow.column(\n pyarrow.field(\"y\", y.type, False), np.array([1.1, 2.2, 3.3])\n ),\n )\n else:\n table2 = table.add_column(1, \"y\", y)\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(table2)) == [\n {\"x\": 1, \"y\": 1.1},\n {\"x\": 2, \"y\": 2.2},\n {\"x\": 3, \"y\": 3.3},\n ]\n\n\ndef test_arrow_coverage100():\n a = ak._v2.operations.from_iter(\n [True, True, False, False, True, False, True, False]\n ).layout\n assert a.to_arrow().to_pylist() == to_list(a)\n\n a = ak._v2.contents.ListOffsetArray(\n ak._v2.index.Index32(np.array([0, 5, 10], \"i4\")),\n ak._v2.contents.NumpyArray(\n np.frombuffer(b\"hellothere\", \"u1\"), parameters={\"__array__\": \"bytes\"}\n ),\n parameters={\"__array__\": \"bytestring\"},\n )\n assert a.to_arrow().to_pylist() == [b\"hello\", b\"there\"]\n\n a = ak._v2.contents.ByteMaskedArray(\n ak._v2.index.Index8(np.array([False, True, False, False, True, True])),\n ak._v2.contents.ListOffsetArray(\n ak._v2.index.Index32(np.array([0, 5, 10, 15, 20, 25, 30], \"i4\")),\n ak._v2.contents.NumpyArray(\n np.frombuffer(b\"hellotherehellotherehellothere\", \"u1\"),\n parameters={\"__array__\": \"bytes\"},\n ),\n parameters={\"__array__\": \"bytestring\"},\n ),\n valid_when=False,\n )\n assert a.to_arrow().to_pylist() == [\n b\"hello\",\n None,\n b\"hello\",\n b\"there\",\n None,\n None,\n ]\n\n a = ak._v2.contents.ByteMaskedArray(\n ak._v2.index.Index8(np.array([False, True])),\n ak._v2.contents.ListOffsetArray(\n ak._v2.index.Index32(np.array([0, 5, 10], \"i4\")),\n ak._v2.contents.NumpyArray(\n np.frombuffer(b\"hellothere\", \"u1\"), parameters={\"__array__\": \"bytes\"}\n ),\n parameters={\"__array__\": \"bytestring\"},\n ),\n valid_when=False,\n )\n assert a.to_arrow().to_pylist() == [b\"hello\", None]\n\n a = ak._v2.contents.IndexedOptionArray(\n ak._v2.index.Index32(np.array([-1, 1, -1, 0, 0, -1], \"i4\")),\n ak._v2.contents.ListOffsetArray(\n ak._v2.index.Index32(np.array([0, 5, 10], \"i4\")),\n ak._v2.contents.NumpyArray(\n np.frombuffer(b\"hellothere\", \"u1\"), parameters={\"__array__\": \"bytes\"}\n ),\n parameters={\"__array__\": \"bytestring\"},\n ),\n )\n assert a.to_arrow().to_pylist() == [\n None,\n b\"there\",\n None,\n b\"hello\",\n b\"hello\",\n None,\n ]\n\n a = ak._v2.contents.ListOffsetArray(\n ak._v2.index.Index32(np.array([0, 5, 10], \"i4\")),\n ak._v2.contents.NumpyArray(\n np.frombuffer(b\"hellothere\", \"u1\"), parameters={\"__array__\": \"chars\"}\n ),\n parameters={\"__array__\": \"string\"},\n )\n assert a.to_arrow().to_pylist() == [\"hello\", \"there\"]\n\n a = ak._v2.contents.ByteMaskedArray(\n ak._v2.index.Index8(np.array([False, True, False, False, True, True])),\n ak._v2.contents.ListOffsetArray(\n ak._v2.index.Index32(np.array([0, 5, 10, 15, 20, 25, 30], \"i4\")),\n ak._v2.contents.NumpyArray(\n np.frombuffer(b\"hellotherehellotherehellothere\", \"u1\"),\n parameters={\"__array__\": \"chars\"},\n ),\n parameters={\"__array__\": \"string\"},\n ),\n valid_when=False,\n )\n assert a.to_arrow().to_pylist() == [\"hello\", None, \"hello\", \"there\", None, None]\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a.to_arrow())) == [\n \"hello\",\n None,\n \"hello\",\n \"there\",\n None,\n None,\n ]\n\n a = ak._v2.contents.ByteMaskedArray(\n ak._v2.index.Index8(np.array([False, True, False, False, True, True])),\n ak._v2.contents.ListOffsetArray(\n ak._v2.index.Index64(np.array([0, 5, 10, 15, 20, 25, 30], \"i8\")),\n ak._v2.contents.NumpyArray(\n np.frombuffer(b\"hellotherehellotherehellothere\", \"u1\"),\n parameters={\"__array__\": \"chars\"},\n ),\n parameters={\"__array__\": \"string\"},\n ),\n valid_when=False,\n )\n assert a.to_arrow().to_pylist() == [\"hello\", None, \"hello\", \"there\", None, None]\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a.to_arrow())) == [\n \"hello\",\n None,\n \"hello\",\n \"there\",\n None,\n None,\n ]\n\n a = ak._v2.contents.ByteMaskedArray(\n ak._v2.index.Index8(np.array([False, True, False, False, True, True])),\n ak._v2.contents.ListOffsetArray(\n ak._v2.index.Index64(np.array([0, 5, 10, 15, 20, 25, 30], \"i8\")),\n ak._v2.contents.NumpyArray(\n np.frombuffer(b\"hellotherehellotherehellothere\", \"u1\"),\n parameters={\"__array__\": \"bytes\"},\n ),\n parameters={\"__array__\": \"bytestring\"},\n ),\n valid_when=False,\n )\n assert a.to_arrow().to_pylist() == [\n b\"hello\",\n None,\n b\"hello\",\n b\"there\",\n None,\n None,\n ]\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a.to_arrow())) == [\n b\"hello\",\n None,\n b\"hello\",\n b\"there\",\n None,\n None,\n ]\n\n a = ak._v2.contents.ByteMaskedArray(\n ak._v2.index.Index8(np.array([False, True])),\n ak._v2.contents.ListOffsetArray(\n ak._v2.index.Index32(np.array([0, 5, 10], \"i4\")),\n ak._v2.contents.NumpyArray(\n np.frombuffer(b\"hellothere\", \"u1\"), parameters={\"__array__\": \"chars\"}\n ),\n parameters={\"__array__\": \"string\"},\n ),\n valid_when=False,\n )\n assert a.to_arrow().to_pylist() == [\"hello\", None]\n\n a = ak._v2.contents.IndexedOptionArray(\n ak._v2.index.Index32(np.array([-1, 1, -1, 0, 0, -1], \"i4\")),\n ak._v2.contents.ListOffsetArray(\n ak._v2.index.Index32(np.array([0, 5, 10], \"i4\")),\n ak._v2.contents.NumpyArray(\n np.frombuffer(b\"hellothere\", \"u1\"), parameters={\"__array__\": \"chars\"}\n ),\n parameters={\"__array__\": \"string\"},\n ),\n )\n assert a.to_arrow().to_pylist() == [None, \"there\", None, \"hello\", \"hello\", None]\n\n a = ak._v2.contents.ListOffsetArray(\n ak._v2.index.Index32(np.array([0, 5, 10], \"i4\")),\n ak._v2.contents.NumpyArray(np.frombuffer(b\"hellothere\", \"u1\")),\n )\n assert a.to_arrow().to_pylist() == [\n [104, 101, 108, 108, 111],\n [116, 104, 101, 114, 101],\n ]\n\n a = ak._v2.contents.ByteMaskedArray(\n ak._v2.index.Index8(np.array([False, True, False, False, True, True])),\n ak._v2.contents.ListOffsetArray(\n ak._v2.index.Index32(np.array([0, 5, 10, 15, 20, 25, 30], \"i4\")),\n ak._v2.contents.NumpyArray(\n np.frombuffer(b\"hellotherehellotherehellothere\", \"u1\")\n ),\n ),\n valid_when=False,\n )\n assert a.to_arrow().to_pylist() == [\n [104, 101, 108, 108, 111],\n None,\n [104, 101, 108, 108, 111],\n [116, 104, 101, 114, 101],\n None,\n None,\n ]\n\n a = ak._v2.contents.ByteMaskedArray(\n ak._v2.index.Index8(np.array([False, True])),\n ak._v2.contents.ListOffsetArray(\n ak._v2.index.Index32(np.array([0, 5, 10], \"i4\")),\n ak._v2.contents.NumpyArray(np.frombuffer(b\"hellothere\", \"u1\")),\n ),\n valid_when=False,\n )\n assert a.to_arrow().to_pylist() == [[104, 101, 108, 108, 111], None]\n\n a = ak._v2.contents.IndexedOptionArray(\n ak._v2.index.Index32(np.array([-1, 1, -1, 0, 0, -1], \"i4\")),\n ak._v2.contents.ListOffsetArray(\n ak._v2.index.Index32(np.array([0, 5, 10], \"i4\")),\n ak._v2.contents.NumpyArray(np.frombuffer(b\"hellothere\", \"u1\")),\n ),\n )\n assert a.to_arrow().to_pylist() == [\n None,\n [116, 104, 101, 114, 101],\n None,\n [104, 101, 108, 108, 111],\n [104, 101, 108, 108, 111],\n None,\n ]\n\n a = ak._v2.contents.IndexedOptionArray(\n ak._v2.index.Index32(np.array([-1, 1, -1, 0, 0, -1], \"i4\")),\n ak._v2.contents.RegularArray(\n ak._v2.contents.NumpyArray(np.array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6])),\n 3,\n zeros_length=0,\n ),\n )\n assert a.to_arrow().to_pylist() == [\n None,\n [4.4, 5.5, 6.6],\n None,\n [1.1, 2.2, 3.3],\n [1.1, 2.2, 3.3],\n None,\n ]\n\n a = ak._v2.contents.IndexedOptionArray(\n ak._v2.index.Index32(np.array([-1, 1, -1, 0, 0, -1, 1, -1], \"i4\")),\n ak._v2.contents.RegularArray(\n ak._v2.contents.NumpyArray(np.array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6])),\n 3,\n zeros_length=0,\n ),\n )\n assert a.to_arrow().to_pylist() == [\n None,\n [4.4, 5.5, 6.6],\n None,\n [1.1, 2.2, 3.3],\n [1.1, 2.2, 3.3],\n None,\n [4.4, 5.5, 6.6],\n None,\n ]\n\n a = ak._v2.contents.IndexedOptionArray(\n ak._v2.index.Index64(np.array([-1, 1, -1, 0, 0, -1, 1, -1], \"i8\")),\n ak._v2.contents.RegularArray(\n ak._v2.contents.NumpyArray(np.array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6])),\n 3,\n zeros_length=0,\n ),\n )\n assert a.to_arrow().to_pylist() == [\n None,\n [4.4, 5.5, 6.6],\n None,\n [1.1, 2.2, 3.3],\n [1.1, 2.2, 3.3],\n None,\n [4.4, 5.5, 6.6],\n None,\n ]\n\n a = ak._v2.contents.ByteMaskedArray(\n ak._v2.index.Index8(np.array([True, True, True, True, False, False])),\n ak._v2.contents.IndexedOptionArray(\n ak._v2.index.Index32(np.array([-1, 1, -1, 0, 0, -1], \"i4\")),\n ak._v2.contents.RegularArray(\n ak._v2.contents.NumpyArray(np.array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6])),\n 3,\n zeros_length=0,\n ),\n ),\n valid_when=True,\n )\n assert a.to_arrow().to_pylist() == [\n None,\n [4.4, 5.5, 6.6],\n None,\n [1.1, 2.2, 3.3],\n None,\n None,\n ]\n\n a = ak._v2.contents.UnmaskedArray(\n ak._v2.contents.ListOffsetArray(\n ak._v2.index.Index32(np.array([0, 5, 10], \"i4\")),\n ak._v2.contents.NumpyArray(np.frombuffer(b\"hellothere\", \"u1\")),\n )\n )\n assert a.to_arrow().to_pylist() == [\n [104, 101, 108, 108, 111],\n [116, 104, 101, 114, 101],\n ]\n\n a = pyarrow.array(\n [\"one\", \"two\", \"three\", \"two\", \"two\", \"one\", \"three\", \"one\"]\n ).dictionary_encode()\n b = ak._v2._connect.pyarrow.handle_arrow(a)\n assert isinstance(b, ak._v2.contents.IndexedOptionArray)\n assert to_list(b) == [\"one\", \"two\", \"three\", \"two\", \"two\", \"one\", \"three\", \"one\"]\n\n a = ak._v2.highlevel.Array([[1.1, 2.2, 3.3], [], None, [4.4, 5.5]]).layout\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a.to_arrow())) == [\n [1.1, 2.2, 3.3],\n [],\n None,\n [4.4, 5.5],\n ]\n\n a = ak._v2.contents.ByteMaskedArray(\n ak._v2.index.Index8(np.array([False, False, False, True, True, False, False])),\n ak._v2.contents.NumpyArray(np.array([1.1, 2.2, 3.3, 999, 314, 4.4, 5.5])),\n valid_when=False,\n )\n assert a.to_arrow().to_pylist() == [1.1, 2.2, 3.3, None, None, 4.4, 5.5]\n\n a = ak._v2.contents.ByteMaskedArray(\n ak._v2.index.Index8(np.array([False, False, False, True, True, False, False])),\n ak._v2.operations.from_iter(\n [b\"hello\", b\"\", b\"there\", b\"yuk\", b\"\", b\"o\", b\"hellothere\"]\n ).layout,\n valid_when=False,\n )\n assert a.to_arrow().to_pylist() == [\n b\"hello\",\n b\"\",\n b\"there\",\n None,\n None,\n b\"o\",\n b\"hellothere\",\n ]\n\n a = ak._v2.contents.ByteMaskedArray(\n ak._v2.index.Index8([True, True, False, True]),\n ak._v2.operations.from_iter([[1.1, 2.2, 3.3], [], [999], [4.4, 5.5]]).layout,\n valid_when=True,\n )\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a.to_arrow())) == [\n [1.1, 2.2, 3.3],\n [],\n None,\n [4.4, 5.5],\n ]\n\n a = ak._v2.operations.from_iter([[1, 2, 3], [], [4, 5], 999, 123]).layout\n assert a.to_arrow().to_pylist() == [[1, 2, 3], [], [4, 5], 999, 123]\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a.to_arrow())) == [\n [1, 2, 3],\n [],\n [4, 5],\n 999,\n 123,\n ]\n\n\ndef test_arrow_coverage100_broken_unions():\n a = ak._v2.operations.from_iter([[1, 2, 3], [], [4, 5], 999, 123]).layout\n b = ak._v2.contents.ByteMaskedArray(\n ak._v2.index.Index8(np.array([True, True, False, False, True])),\n a,\n valid_when=True,\n )\n assert b.to_arrow().to_pylist() == [[1, 2, 3], [], None, None, 123]\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(b.to_arrow())) == [\n [1, 2, 3],\n [],\n None,\n None,\n 123,\n ]\n\n content1 = ak._v2.operations.from_iter([1.1, 2.2, 3.3, 4.4, 5.5]).layout\n content2 = ak._v2.contents.NumpyArray(np.array([], dtype=np.int32))\n a = ak._v2.contents.UnionArray(\n ak._v2.index.Index8(np.array([0, 0, 0, 0, 0], \"i1\")),\n ak._v2.index.Index32(np.array([0, 1, 2, 3, 4], \"i4\")),\n [content1, content2],\n )\n assert to_list(a) == [1.1, 2.2, 3.3, 4.4, 5.5]\n assert a.to_arrow().to_pylist() == [1.1, 2.2, 3.3, 4.4, 5.5]\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a.to_arrow())) == [\n 1.1,\n 2.2,\n 3.3,\n 4.4,\n 5.5,\n ]\n\n a = pyarrow.UnionArray.from_sparse(\n pyarrow.array([0, 0, 0, 0, 0], type=pyarrow.int8()),\n [\n pyarrow.array([0.0, 1.1, None, 3.3, 4.4]),\n pyarrow.array([True, None, False, True, False]),\n ],\n )\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n 0.0,\n 1.1,\n None,\n 3.3,\n 4.4,\n ]\n\n a = pyarrow.UnionArray.from_sparse(\n pyarrow.array([0, 1, 0, 1, 1], \"i1\"),\n [\n pyarrow.array([[0.0, 1.1, 2.2], [], None, [5.5], [6.6, 7.7, 8.8, 9.9]]),\n pyarrow.array([0.0, 1.1, 2.2, None, None]),\n ],\n [\"0\", \"1\"],\n [0, 1],\n )\n assert a.to_pylist() == [[0.0, 1.1, 2.2], 1.1, None, None, None]\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n [0.0, 1.1, 2.2],\n 1.1,\n None,\n None,\n None,\n ]\n\n a = pyarrow.chunked_array([pyarrow.array([1.1, 2.2, 3.3, 4.4, 5.5])])\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a)) == [\n 1.1,\n 2.2,\n 3.3,\n 4.4,\n 5.5,\n ]\n\n\n# NumpyArray in Awkward Arrays translate to their corresponding DataType Arrays in Arrow\ndef test_nonzero_offset_fromarrow_NumpyArray_1():\n boolarray = ak._v2.contents.NumpyArray(\n np.array([True, True, True, False, False, True, False, True, False, True])\n )\n assert to_list(\n ak._v2._connect.pyarrow.handle_arrow(boolarray.to_arrow()[5:])\n ) == pyarrow.Array.to_pylist(boolarray.to_arrow()[5:])\n\n\ndef test_nonzero_offset_fromarrow_NumpyArray_2():\n content = ak._v2.contents.NumpyArray(\n np.array([0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10])\n )\n assert to_list(\n ak._v2._connect.pyarrow.handle_arrow(content.to_arrow()[2:])\n ) == pyarrow.Array.to_pylist(content.to_arrow()[2:])\n\n\ndef test_nonzero_offset_fromarrow_NumpyArray_3():\n content = ak._v2.contents.NumpyArray(\n np.array([0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10])\n )\n assert to_list(\n ak._v2._connect.pyarrow.handle_arrow(content.to_arrow()[2:5])\n ) == pyarrow.Array.to_pylist(content.to_arrow()[2:5])\n\n\ndef test_nonzero_offset_fromarrow_NumpyArray_4():\n content = ak._v2.contents.NumpyArray(\n np.array([0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10])\n )\n assert to_list(\n ak._v2._connect.pyarrow.handle_arrow(content.to_arrow()[0:9:2])\n ) == pyarrow.Array.to_pylist(content.to_arrow()[0:9:2])\n\n\ndef test_nonzero_offset_fromarrow_NumpyArray_5():\n content = ak._v2.contents.NumpyArray(\n np.array([0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10])\n )\n assert to_list(\n ak._v2._connect.pyarrow.handle_arrow(content.to_arrow()[-2:10])\n ) == pyarrow.Array.to_pylist(content.to_arrow()[-2:10])\n\n\ndef test_nonzero_offset_fromarrow_NumpyArray_6():\n content = ak._v2.contents.NumpyArray(\n np.array([0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10])\n )\n assert to_list(\n ak._v2._connect.pyarrow.handle_arrow(content.to_arrow()[-3:3:-1])\n ) == pyarrow.Array.to_pylist(content.to_arrow()[-3:3:-1])\n\n\n# ListOffsetArrays in Awkward Arrays translate to ListArrays in Arrow\ndef test_nonzero_offset_fromarrow_ListOffsetArray_1():\n content = ak._v2.contents.NumpyArray(\n np.array([0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10])\n )\n offsets = ak._v2.index.Index64(np.array([0, 3, 3, 5, 6, 10, 10]))\n listoffsetarray = ak._v2.contents.ListOffsetArray(offsets, content)\n assert to_list(\n ak._v2._connect.pyarrow.handle_arrow(listoffsetarray.to_arrow()[2:])\n ) == pyarrow.Array.to_pylist(listoffsetarray.to_arrow()[2:])\n\n\ndef test_nonzero_offset_fromarrow_ListOffsetArray_2():\n content = ak._v2.contents.NumpyArray(\n np.array([0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10])\n )\n offsets = ak._v2.index.Index64(np.array([0, 3, 3, 5, 6, 10, 10]))\n listoffsetarray = ak._v2.contents.ListOffsetArray(offsets, content)\n assert to_list(\n ak._v2._connect.pyarrow.handle_arrow(listoffsetarray.to_arrow()[2:5])\n ) == pyarrow.Array.to_pylist(listoffsetarray.to_arrow()[2:5])\n\n\ndef test_nonzero_offset_fromarrow_ListOffsetArray_3():\n content = ak._v2.contents.NumpyArray(\n np.array([0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10])\n )\n offsets = ak._v2.index.Index64(np.array([0, 3, 3, 5, 6, 10, 10]))\n listoffsetarray = ak._v2.contents.ListOffsetArray(offsets, content)\n assert to_list(\n ak._v2._connect.pyarrow.handle_arrow(listoffsetarray.to_arrow()[0:5:2])\n ) == pyarrow.Array.to_pylist(listoffsetarray.to_arrow()[0:5:2])\n\n\ndef test_nonzero_offset_fromarrow_ListOffsetArray_4():\n content = ak._v2.contents.NumpyArray(\n np.array([0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10])\n )\n offsets = ak._v2.index.Index64(np.array([0, 3, 3, 5, 6, 10, 10]))\n listoffsetarray = ak._v2.contents.ListOffsetArray(offsets, content)\n assert to_list(\n ak._v2._connect.pyarrow.handle_arrow(listoffsetarray.to_arrow()[-3:3:-1])\n ) == pyarrow.Array.to_pylist(listoffsetarray.to_arrow()[-3:3:-1])\n\n\n# RegularArrays in Awkward Arrays translate to ListArrays in Arrow\ndef test_nonzero_offset_fromarrow_RegularArray_1():\n content = ak._v2.contents.NumpyArray(\n np.array([0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10])\n )\n offsets = ak._v2.index.Index64(np.array([0, 3, 3, 5, 6, 10, 10]))\n listoffsetarray = ak._v2.contents.ListOffsetArray(offsets, content)\n\n regulararray = ak._v2.contents.RegularArray(listoffsetarray, 2, zeros_length=0)\n assert to_list(\n ak._v2._connect.pyarrow.handle_arrow(regulararray.to_arrow()[2:])\n ) == pyarrow.Array.to_pylist(regulararray.to_arrow()[2:])\n\n\ndef test_nonzero_offset_fromarrow_RegularArray_2():\n content = ak._v2.contents.NumpyArray(\n np.array([0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10])\n )\n offsets = ak._v2.index.Index64(np.array([0, 3, 3, 5, 6, 10, 10]))\n listoffsetarray = ak._v2.contents.ListOffsetArray(offsets, content)\n\n regulararray = ak._v2.contents.RegularArray(listoffsetarray, 2, zeros_length=0)\n assert to_list(\n ak._v2._connect.pyarrow.handle_arrow(regulararray.to_arrow()[2:5])\n ) == pyarrow.Array.to_pylist(regulararray.to_arrow()[2:5])\n\n\ndef test_nonzero_offset_fromarrow_RegularArray_3():\n content = ak._v2.contents.NumpyArray(\n np.array([0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10])\n )\n offsets = ak._v2.index.Index64(np.array([0, 3, 3, 5, 6, 10, 10]))\n listoffsetarray = ak._v2.contents.ListOffsetArray(offsets, content)\n\n regulararray = ak._v2.contents.RegularArray(listoffsetarray, 2, zeros_length=0)\n assert to_list(\n ak._v2._connect.pyarrow.handle_arrow(regulararray.to_arrow()[0:5:2])\n ) == pyarrow.Array.to_pylist(regulararray.to_arrow()[0:5:2])\n\n\ndef test_nonzero_offset_fromarrow_RegularArray_4():\n content = ak._v2.contents.NumpyArray(\n np.array([0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10])\n )\n offsets = ak._v2.index.Index64(np.array([0, 3, 3, 5, 6, 10, 10]))\n listoffsetarray = ak._v2.contents.ListOffsetArray(offsets, content)\n\n regulararray = ak._v2.contents.RegularArray(listoffsetarray, 2, zeros_length=0)\n assert to_list(\n ak._v2._connect.pyarrow.handle_arrow(regulararray.to_arrow()[-3:3:-1])\n ) == pyarrow.Array.to_pylist(regulararray.to_arrow()[-3:3:-1])\n\n\n# RecordArrays in Awkward Arrays translate to Struct Arrays in Arrow\ndef test_nonzero_offset_fromarrow_RecordArray_1():\n content = ak._v2.contents.NumpyArray(\n np.array([0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10])\n )\n offsets = ak._v2.index.Index64(np.array([0, 3, 3, 5, 6, 10, 10]))\n listoffsetarray = ak._v2.contents.ListOffsetArray(offsets, content)\n\n content1 = ak._v2.contents.NumpyArray(np.array([1, 2, 3, 4, 5]))\n content2 = ak._v2.contents.NumpyArray(\n np.array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9])\n )\n offsets = ak._v2.index.Index32(np.array([0, 3, 3, 5, 6, 9]))\n recordarray = ak._v2.contents.RecordArray(\n [content1, listoffsetarray, content2, content1],\n fields=[\"one\", \"chonks\", \"2\", \"wonky\"],\n )\n assert to_list(\n ak._v2._connect.pyarrow.handle_arrow(recordarray.to_arrow()[2:])\n ) == pyarrow.Array.to_pylist(recordarray.to_arrow()[2:])\n\n\ndef test_nonzero_offset_fromarrow_RecordArray_2():\n content = ak._v2.contents.NumpyArray(\n np.array([0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10])\n )\n offsets = ak._v2.index.Index64(np.array([0, 3, 3, 5, 6, 10, 10]))\n listoffsetarray = ak._v2.contents.ListOffsetArray(offsets, content)\n\n content1 = ak._v2.contents.NumpyArray(np.array([1, 2, 3, 4, 5]))\n content2 = ak._v2.contents.NumpyArray(\n np.array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9])\n )\n offsets = ak._v2.index.Index32(np.array([0, 3, 3, 5, 6, 9]))\n recordarray = ak._v2.contents.RecordArray(\n [content1, listoffsetarray, content2, content1],\n fields=[\"one\", \"chonks\", \"2\", \"wonky\"],\n )\n assert to_list(\n ak._v2._connect.pyarrow.handle_arrow(recordarray.to_arrow()[2:5])\n ) == pyarrow.Array.to_pylist(recordarray.to_arrow()[2:5])\n\n\ndef test_nonzero_offset_fromarrow_RecordArray_3():\n content = ak._v2.contents.NumpyArray(\n np.array([0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10])\n )\n offsets = ak._v2.index.Index64(np.array([0, 3, 3, 5, 6, 10, 10]))\n listoffsetarray = ak._v2.contents.ListOffsetArray(offsets, content)\n\n content1 = ak._v2.contents.NumpyArray(np.array([1, 2, 3, 4, 5]))\n content2 = ak._v2.contents.NumpyArray(\n np.array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9])\n )\n offsets = ak._v2.index.Index32(np.array([0, 3, 3, 5, 6, 9]))\n recordarray = ak._v2.contents.RecordArray(\n [content1, listoffsetarray, content2, content1],\n fields=[\"one\", \"chonks\", \"2\", \"wonky\"],\n )\n assert to_list(\n ak._v2._connect.pyarrow.handle_arrow(recordarray.to_arrow()[0:5:2])\n ) == pyarrow.Array.to_pylist(recordarray.to_arrow()[0:5:2])\n\n\ndef test_nonzero_offset_fromarrow_RecordArray_4():\n content = ak._v2.contents.NumpyArray(\n np.array([0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10])\n )\n offsets = ak._v2.index.Index64(np.array([0, 3, 3, 5, 6, 10, 10]))\n listoffsetarray = ak._v2.contents.ListOffsetArray(offsets, content)\n\n content1 = ak._v2.contents.NumpyArray(np.array([1, 2, 3, 4, 5]))\n content2 = ak._v2.contents.NumpyArray(\n np.array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9])\n )\n offsets = ak._v2.index.Index32(np.array([0, 3, 3, 5, 6, 9]))\n recordarray = ak._v2.contents.RecordArray(\n [content1, listoffsetarray, content2, content1],\n fields=[\"one\", \"chonks\", \"2\", \"wonky\"],\n )\n assert to_list(\n ak._v2._connect.pyarrow.handle_arrow(recordarray.to_arrow()[-3:3:-1])\n ) == pyarrow.Array.to_pylist(recordarray.to_arrow()[-3:3:-1])\n\n\ndef test_nonzero_offset_fromarrow_RecordArray_4_again():\n content = ak._v2.contents.NumpyArray(\n np.array([0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10])\n )\n offsets = ak._v2.index.Index64(np.array([0, 3, 3, 5, 6, 10, 10]))\n listoffsetarray = ak._v2.contents.ListOffsetArray(offsets, content)\n\n content1 = ak._v2.contents.NumpyArray(np.array([1, 2, 3, 4, 5]))\n content2 = ak._v2.contents.NumpyArray(\n np.array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9])\n )\n offsets = ak._v2.index.Index32(np.array([0, 3, 3, 5, 6, 9]))\n recordarray = ak._v2.contents.RecordArray(\n [content1, listoffsetarray, content2, content1],\n fields=[\"one\", \"chonks\", \"2\", \"wonky\"],\n )\n assert to_list(\n ak._v2._connect.pyarrow.handle_arrow(recordarray.to_arrow()[-3:3:-1])\n ) == pyarrow.Array.to_pylist(recordarray.to_arrow()[-3:3:-1])\n\n\ndef test_nonzero_offset_fromarrow_UnionArray_1():\n content0 = ak._v2.highlevel.Array([[1.1, 2.2, 3.3], [], [4.4, 5.5]]).layout\n content = ak._v2.highlevel.Array(\n [\"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\"]\n ).layout\n tags = ak._v2.index.Index8(np.array([1, 1, 0, 0, 1, 0, 1, 1], dtype=np.int8))\n index = ak._v2.index.Index32(np.array([0, 1, 0, 1, 2, 2, 4, 3], dtype=np.int32))\n array = ak._v2.contents.UnionArray(tags, index, [content0, content])\n assert to_list(\n ak._v2._connect.pyarrow.handle_arrow(array.to_arrow()[2:])\n ) == pyarrow.Array.to_pylist(array.to_arrow()[2:])\n\n\ndef test_nonzero_offset_fromarrow_UnionArray_2():\n content0 = ak._v2.highlevel.Array([[1.1, 2.2, 3.3], [], [4.4, 5.5]]).layout\n content = ak._v2.highlevel.Array(\n [\"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\"]\n ).layout\n tags = ak._v2.index.Index8(np.array([1, 1, 0, 0, 1, 0, 1, 1], dtype=np.int8))\n index = ak._v2.index.Index32(np.array([0, 1, 0, 1, 2, 2, 4, 3], dtype=np.int32))\n array = ak._v2.contents.UnionArray(tags, index, [content0, content])\n assert to_list(\n ak._v2._connect.pyarrow.handle_arrow(array.to_arrow()[2:5])\n ) == pyarrow.Array.to_pylist(array.to_arrow()[2:5])\n\n\ndef test_nonzero_offset_fromarrow_UnionArray_3():\n content0 = ak._v2.highlevel.Array([[1.1, 2.2, 3.3], [], [4.4, 5.5]]).layout\n content = ak._v2.highlevel.Array(\n [\"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\"]\n ).layout\n tags = ak._v2.index.Index8(np.array([1, 1, 0, 0, 1, 0, 1, 1], dtype=np.int8))\n index = ak._v2.index.Index32(np.array([0, 1, 0, 1, 2, 2, 4, 3], dtype=np.int32))\n array = ak._v2.contents.UnionArray(tags, index, [content0, content])\n assert to_list(\n ak._v2._connect.pyarrow.handle_arrow(array.to_arrow()[0:5:1])\n ) == pyarrow.Array.to_pylist(array.to_arrow()[0:5:1])\n\n\ndef test_nonzero_offset_fromarrow_ArrowDictionaryArray_1():\n a = pyarrow.DictionaryArray.from_arrays(\n pyarrow.array([0, 0, 2, 2, 1, 0, 2, 1, 1]),\n pyarrow.array([\"one\", None, \"three\"]),\n )\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a[2:])) == [\n \"three\",\n \"three\",\n None,\n \"one\",\n \"three\",\n None,\n None,\n ]\n\n\ndef test_nonzero_offset_fromarrow_ArrowDictionaryArray_2():\n a = pyarrow.DictionaryArray.from_arrays(\n pyarrow.array([0, 0, 2, 2, 1, 0, 2, 1, 1]),\n pyarrow.array([\"one\", None, \"three\"]),\n )\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a[2:5])) == [\n \"three\",\n \"three\",\n None,\n ]\n\n\ndef test_nonzero_offset_fromarrow_ArrowDictionaryArray_3():\n a = pyarrow.DictionaryArray.from_arrays(\n pyarrow.array([0, 0, 2, 2, 1, 0, 2, 1, 1]),\n pyarrow.array([\"one\", None, \"three\"]),\n )\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a[0:8:2])) == [\n \"one\",\n \"three\",\n None,\n \"three\",\n ]\n\n\ndef test_nonzero_offset_fromarrow_ArrowDictionaryArray_4():\n a = pyarrow.DictionaryArray.from_arrays(\n pyarrow.array([0, 0, 2, 2, 1, 0, 2, 1, 1]),\n pyarrow.array([\"one\", None, \"three\"]),\n )\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a[-3:3:-1])) == [\n \"three\",\n \"one\",\n None,\n ]\n\n\ndef test_nonzero_offset_fromarrow_ArrowRecordBatch_1():\n a = pyarrow.RecordBatch.from_arrays(\n [\n pyarrow.array([1.1, 2.2, 3.3, 4.4, 5.5]),\n pyarrow.array([[1, 2, 3], [], [], [4, 5], [6]]),\n ],\n [\"a\", \"b\"],\n )\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a[0])) == a[0].to_pylist()\n\n\ndef test_nonzero_offset_fromarrow_ArrowRecordBatch_2():\n a = pyarrow.RecordBatch.from_arrays(\n [\n pyarrow.array([1.1, 2.2, 3.3, 4.4, 5.5]),\n pyarrow.array([[1, 2, 3], [], [], [4, 5], [6]]),\n ],\n [\"a\", \"b\"],\n )\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a[2:])) == [\n {\"a\": 3.3, \"b\": []},\n {\"a\": 4.4, \"b\": [4, 5]},\n {\"a\": 5.5, \"b\": [6]},\n ]\n\n\ndef test_nonzero_offset_fromarrow_ArrowRecordBatch_3():\n a = pyarrow.RecordBatch.from_arrays(\n [\n pyarrow.array([1.1, 2.2, 3.3, 4.4, 5.5]),\n pyarrow.array([[1, 2, 3], [], [], [4, 5], [6]]),\n ],\n [\"a\", \"b\"],\n )\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a[2:5])) == [\n {\"a\": 3.3, \"b\": []},\n {\"a\": 4.4, \"b\": [4, 5]},\n {\"a\": 5.5, \"b\": [6]},\n ]\n\n\ndef test_nonzero_offset_fromarrow_ArrowRecordBatch_4():\n a = pyarrow.RecordBatch.from_arrays(\n [\n pyarrow.array([1.1, 2.2, 3.3, 4.4, 5.5]),\n pyarrow.array([[1, 2, 3], [], [], [4, 5], [6]]),\n ],\n [\"a\", \"b\"],\n )\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a[0:5:2])) == [\n {\"a\": 1.1, \"b\": [1, 2, 3]},\n {\"a\": 3.3, \"b\": []},\n {\"a\": 5.5, \"b\": [6]},\n ]\n\n\ndef test_nonzero_offset_fromarrow_ArrowRecordBatch_4_again():\n a = pyarrow.RecordBatch.from_arrays(\n [\n pyarrow.array([1.1, 2.2, 3.3, 4.4, 5.5]),\n pyarrow.array([[1, 2, 3], [], [], [4, 5], [6]]),\n ],\n [\"a\", \"b\"],\n )\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a[-2:0:-1])) == [\n {\"a\": 4.4, \"b\": [4, 5]},\n {\"a\": 3.3, \"b\": []},\n {\"a\": 2.2, \"b\": []},\n ]\n\n\ndef test_nonzero_offset_fromarrow_ArrowTable_1():\n a = pyarrow.Table.from_batches(\n [\n pyarrow.RecordBatch.from_arrays(\n [\n pyarrow.array([1.1, 2.2, 3.3, None, 5.5]),\n pyarrow.array([[1, 2, 3], [], [4, 5], [None], [6]]),\n pyarrow.array(\n [\n {\"x\": 1, \"y\": 1.1},\n {\"x\": 2, \"y\": 2.2},\n {\"x\": 3, \"y\": 3.3},\n {\"x\": 4, \"y\": None},\n {\"x\": 5, \"y\": 5.5},\n ]\n ),\n pyarrow.array(\n [\n {\"x\": 1, \"y\": 1.1},\n None,\n None,\n {\"x\": 4, \"y\": None},\n {\"x\": 5, \"y\": 5.5},\n ]\n ),\n pyarrow.array(\n [\n [\n {\"x\": 1, \"y\": 1.1},\n {\"x\": 2, \"y\": 2.2},\n {\"x\": 3, \"y\": 3.3},\n ],\n [],\n [{\"x\": 4, \"y\": None}, {\"x\": 5, \"y\": 5.5}],\n [None],\n [{\"x\": 6, \"y\": 6.6}],\n ]\n ),\n ],\n [\"a\", \"b\", \"c\", \"d\", \"e\"],\n ),\n pyarrow.RecordBatch.from_arrays(\n [\n pyarrow.array([1.1, 2.2, 3.3, None, 5.5]),\n pyarrow.array([[1, 2, 3], [], [4, 5], [None], [6]]),\n pyarrow.array(\n [\n {\"x\": 1, \"y\": 1.1},\n {\"x\": 2, \"y\": 2.2},\n {\"x\": 3, \"y\": 3.3},\n {\"x\": 4, \"y\": None},\n {\"x\": 5, \"y\": 5.5},\n ]\n ),\n pyarrow.array(\n [\n {\"x\": 1, \"y\": 1.1},\n None,\n None,\n {\"x\": 4, \"y\": None},\n {\"x\": 5, \"y\": 5.5},\n ]\n ),\n pyarrow.array(\n [\n [\n {\"x\": 1, \"y\": 1.1},\n {\"x\": 2, \"y\": 2.2},\n {\"x\": 3, \"y\": 3.3},\n ],\n [],\n [{\"x\": 4, \"y\": None}, {\"x\": 5, \"y\": 5.5}],\n [None],\n [{\"x\": 6, \"y\": 6.6}],\n ]\n ),\n ],\n [\"a\", \"b\", \"c\", \"d\", \"e\"],\n ),\n ]\n )\n assert to_list(ak._v2._connect.pyarrow.handle_arrow(a[0:5:2])) == [\n {\n \"a\": 1.1,\n \"b\": [1, 2, 3],\n \"c\": {\"x\": 1, \"y\": 1.1},\n \"d\": {\"x\": 1, \"y\": 1.1},\n \"e\": [{\"x\": 1, \"y\": 1.1}, {\"x\": 2, \"y\": 2.2}, {\"x\": 3, \"y\": 3.3}],\n },\n {\n \"a\": 3.3,\n \"b\": [4, 5],\n \"c\": {\"x\": 3, \"y\": 3.3},\n \"d\": None,\n \"e\": [{\"x\": 4, \"y\": None}, {\"x\": 5, \"y\": 5.5}],\n },\n {\n \"a\": 5.5,\n \"b\": [6],\n \"c\": {\"x\": 5, \"y\": 5.5},\n \"d\": {\"x\": 5, \"y\": 5.5},\n \"e\": [{\"x\": 6, \"y\": 6.6}],\n },\n ]\n",
"# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE\n\nimport pytest # noqa: F401\nimport numpy as np # noqa: F401\nimport awkward as ak # noqa: F401\n\nto_list = ak._v2.operations.to_list\n\n\ndef test_jagged_axis0():\n assert ak._v2.operations.min(\n ak._v2.highlevel.Array([[1.1, 5.5], [4.4], [2.2, 3.3, 0.0, -10]]), axis=0\n ).tolist() == [1.1, 3.3, 0, -10]\n assert ak._v2.operations.argmin(\n ak._v2.highlevel.Array([[1.1, 5.5], [4.4], [2.2, 3.3, 0.0, -10]]), axis=0\n ).tolist() == [0, 2, 2, 2]\n\n\ndef test_jagged_axis1():\n # first is [[1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [999, 2.0], [1.0]]\n\n array = ak._v2.highlevel.Array(\n [\n [[1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [999, 2.0], [1.0]],\n [[1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [999, 2.0], [1.0]],\n ]\n )\n assert ak._v2.operations.min(array, axis=1).tolist() == [\n [1, 2, 3.3],\n [1, 2, 3.3],\n ]\n assert ak._v2.operations.argmin(array, axis=1).tolist() == [\n [4, 3, 2],\n [4, 3, 2],\n ]\n\n array = ak._v2.highlevel.Array(\n [\n [[1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [999, 2.0], [1.0]],\n [[], [1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [999, 2.0], [1.0]],\n ]\n )\n assert ak._v2.operations.min(array, axis=1).tolist() == [\n [1, 2, 3.3],\n [1, 2, 3.3],\n ]\n assert ak._v2.operations.argmin(array, axis=1).tolist() == [\n [4, 3, 2],\n [5, 4, 3],\n ]\n\n array = ak._v2.highlevel.Array(\n [\n [[1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [999, 2.0], [1.0]],\n [[], [], [1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [999, 2.0], [1.0]],\n ]\n )\n assert ak._v2.operations.min(array, axis=1).tolist() == [\n [1, 2, 3.3],\n [1, 2, 3.3],\n ]\n assert ak._v2.operations.argmin(array, axis=1).tolist() == [\n [4, 3, 2],\n [6, 5, 4],\n ]\n\n array = ak._v2.highlevel.Array(\n [\n [[1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [999, 2.0], [1.0]],\n [[1.1], [1.1, 2.2], [], [1.1, 2.2, 3.3], [999, 2.0], [1.0]],\n ]\n )\n assert ak._v2.operations.min(array, axis=1).tolist() == [\n [1, 2, 3.3],\n [1, 2, 3.3],\n ]\n assert ak._v2.operations.argmin(array, axis=1).tolist() == [\n [4, 3, 2],\n [5, 4, 3],\n ]\n\n array = ak._v2.highlevel.Array(\n [\n [[1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [999, 2.0], [1.0]],\n [[1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [], [999, 2.0], [1.0]],\n ]\n )\n assert ak._v2.operations.min(array, axis=1).tolist() == [\n [1, 2, 3.3],\n [1, 2, 3.3],\n ]\n assert ak._v2.operations.argmin(array, axis=1).tolist() == [\n [4, 3, 2],\n [5, 4, 2],\n ]\n\n array = ak._v2.highlevel.Array(\n [\n [[1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [999, 2.0], [1.0]],\n [[1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [999, 2.0], [], [1.0]],\n ]\n )\n assert ak._v2.operations.min(array, axis=1).tolist() == [\n [1, 2, 3.3],\n [1, 2, 3.3],\n ]\n assert ak._v2.operations.argmin(array, axis=1).tolist() == [\n [4, 3, 2],\n [5, 3, 2],\n ]\n\n array = ak._v2.highlevel.Array(\n [\n [[1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [999, 2.0], [1.0]],\n [[1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [999, 2.0], [1.0], []],\n ]\n )\n assert ak._v2.operations.min(array, axis=1).tolist() == [\n [1, 2, 3.3],\n [1, 2, 3.3],\n ]\n assert ak._v2.operations.argmin(array, axis=1).tolist() == [\n [4, 3, 2],\n [4, 3, 2],\n ]\n\n array = ak._v2.highlevel.Array(\n [\n [[1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [999, 2.0], [1.0]],\n [[1.1, 999, 999], [1.1, 2.2, 999], [1.1, 2.2, 3.3], [999, 2.0], [1.0]],\n ]\n )\n assert ak._v2.operations.min(array, axis=1).tolist() == [\n [1, 2, 3.3],\n [1, 2, 3.3],\n ]\n assert ak._v2.operations.argmin(array, axis=1).tolist() == [\n [4, 3, 2],\n [4, 3, 2],\n ]\n\n array = ak._v2.highlevel.Array(\n [\n [[1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [999, 2.0], [1.0]],\n [[1.1, 999, 999, 999], [1.1, 2.2, 999], [1.1, 2.2, 3.3], [999, 2.0], [1.0]],\n ]\n )\n assert ak._v2.operations.min(array, axis=1).tolist() == [\n [1, 2, 3.3],\n [1, 2, 3.3, 999],\n ]\n assert ak._v2.operations.argmin(array, axis=1).tolist() == [\n [4, 3, 2],\n [4, 3, 2, 0],\n ]\n\n # first is [[], [1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [999, 2.0], [1.0]]\n\n array = ak._v2.highlevel.Array(\n [\n [[], [1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [999, 2.0], [1.0]],\n [[1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [999, 2.0], [1.0]],\n ]\n )\n assert ak._v2.operations.min(array, axis=1).tolist() == [\n [1, 2, 3.3],\n [1, 2, 3.3],\n ]\n assert ak._v2.operations.argmin(array, axis=1).tolist() == [\n [5, 4, 3],\n [4, 3, 2],\n ]\n\n array = ak._v2.highlevel.Array(\n [\n [[], [1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [999, 2.0], [1.0]],\n [[], [1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [999, 2.0], [1.0]],\n ]\n )\n assert ak._v2.operations.min(array, axis=1).tolist() == [\n [1, 2, 3.3],\n [1, 2, 3.3],\n ]\n assert ak._v2.operations.argmin(array, axis=1).tolist() == [\n [5, 4, 3],\n [5, 4, 3],\n ]\n\n array = ak._v2.highlevel.Array(\n [\n [[], [1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [999, 2.0], [1.0]],\n [[], [], [1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [999, 2.0], [1.0]],\n ]\n )\n assert ak._v2.operations.min(array, axis=1).tolist() == [\n [1, 2, 3.3],\n [1, 2, 3.3],\n ]\n assert ak._v2.operations.argmin(array, axis=1).tolist() == [\n [5, 4, 3],\n [6, 5, 4],\n ]\n\n array = ak._v2.highlevel.Array(\n [\n [[], [1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [999, 2.0], [1.0]],\n [[1.1], [1.1, 2.2], [], [1.1, 2.2, 3.3], [999, 2.0], [1.0]],\n ]\n )\n assert ak._v2.operations.min(array, axis=1).tolist() == [\n [1, 2, 3.3],\n [1, 2, 3.3],\n ]\n assert ak._v2.operations.argmin(array, axis=1).tolist() == [\n [5, 4, 3],\n [5, 4, 3],\n ]\n\n array = ak._v2.highlevel.Array(\n [\n [[], [1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [999, 2.0], [1.0]],\n [[1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [], [999, 2.0], [1.0]],\n ]\n )\n assert ak._v2.operations.min(array, axis=1).tolist() == [\n [1, 2, 3.3],\n [1, 2, 3.3],\n ]\n assert ak._v2.operations.argmin(array, axis=1).tolist() == [\n [5, 4, 3],\n [5, 4, 2],\n ]\n\n array = ak._v2.highlevel.Array(\n [\n [[], [1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [999, 2.0], [1.0]],\n [[1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [999, 2.0], [], [1.0]],\n ]\n )\n assert ak._v2.operations.min(array, axis=1).tolist() == [\n [1, 2, 3.3],\n [1, 2, 3.3],\n ]\n assert ak._v2.operations.argmin(array, axis=1).tolist() == [\n [5, 4, 3],\n [5, 3, 2],\n ]\n\n array = ak._v2.highlevel.Array(\n [\n [[], [1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [999, 2.0], [1.0]],\n [[1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [999, 2.0], [1.0], []],\n ]\n )\n assert ak._v2.operations.min(array, axis=1).tolist() == [\n [1, 2, 3.3],\n [1, 2, 3.3],\n ]\n assert ak._v2.operations.argmin(array, axis=1).tolist() == [\n [5, 4, 3],\n [4, 3, 2],\n ]\n\n array = ak._v2.highlevel.Array(\n [\n [[], [1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [999, 2.0], [1.0]],\n [[1.1, 999, 999], [1.1, 2.2, 999], [1.1, 2.2, 3.3], [999, 2.0], [1.0]],\n ]\n )\n assert ak._v2.operations.min(array, axis=1).tolist() == [\n [1, 2, 3.3],\n [1, 2, 3.3],\n ]\n assert ak._v2.operations.argmin(array, axis=1).tolist() == [\n [5, 4, 3],\n [4, 3, 2],\n ]\n\n array = ak._v2.highlevel.Array(\n [\n [[], [1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [999, 2.0], [1.0]],\n [[1.1, 999, 999, 999], [1.1, 2.2, 999], [1.1, 2.2, 3.3], [999, 2.0], [1.0]],\n ]\n )\n assert ak._v2.operations.min(array, axis=1).tolist() == [\n [1, 2, 3.3],\n [1, 2, 3.3, 999],\n ]\n assert ak._v2.operations.argmin(array, axis=1).tolist() == [\n [5, 4, 3],\n [4, 3, 2, 0],\n ]\n\n # first is [[1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [], [999, 2.0], [1.0]]\n\n array = ak._v2.highlevel.Array(\n [\n [[1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [], [999, 2.0], [1.0]],\n [[1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [999, 2.0], [1.0]],\n ]\n )\n assert ak._v2.operations.min(array, axis=1).tolist() == [\n [1, 2, 3.3],\n [1, 2, 3.3],\n ]\n assert ak._v2.operations.argmin(array, axis=1).tolist() == [\n [5, 4, 2],\n [4, 3, 2],\n ]\n\n array = ak._v2.highlevel.Array(\n [\n [[1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [], [999, 2.0], [1.0]],\n [[], [1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [999, 2.0], [1.0]],\n ]\n )\n assert ak._v2.operations.min(array, axis=1).tolist() == [\n [1, 2, 3.3],\n [1, 2, 3.3],\n ]\n assert ak._v2.operations.argmin(array, axis=1).tolist() == [\n [5, 4, 2],\n [5, 4, 3],\n ]\n\n array = ak._v2.highlevel.Array(\n [\n [[1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [], [999, 2.0], [1.0]],\n [[], [], [1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [999, 2.0], [1.0]],\n ]\n )\n assert ak._v2.operations.min(array, axis=1).tolist() == [\n [1, 2, 3.3],\n [1, 2, 3.3],\n ]\n assert ak._v2.operations.argmin(array, axis=1).tolist() == [\n [5, 4, 2],\n [6, 5, 4],\n ]\n\n array = ak._v2.highlevel.Array(\n [\n [[1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [], [999, 2.0], [1.0]],\n [[1.1], [1.1, 2.2], [], [1.1, 2.2, 3.3], [999, 2.0], [1.0]],\n ]\n )\n assert ak._v2.operations.min(array, axis=1).tolist() == [\n [1, 2, 3.3],\n [1, 2, 3.3],\n ]\n assert ak._v2.operations.argmin(array, axis=1).tolist() == [\n [5, 4, 2],\n [5, 4, 3],\n ]\n\n array = ak._v2.highlevel.Array(\n [\n [[1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [], [999, 2.0], [1.0]],\n [[1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [], [999, 2.0], [1.0]],\n ]\n )\n assert ak._v2.operations.min(array, axis=1).tolist() == [\n [1, 2, 3.3],\n [1, 2, 3.3],\n ]\n assert ak._v2.operations.argmin(array, axis=1).tolist() == [\n [5, 4, 2],\n [5, 4, 2],\n ]\n\n array = ak._v2.highlevel.Array(\n [\n [[1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [], [999, 2.0], [1.0]],\n [[1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [999, 2.0], [], [1.0]],\n ]\n )\n assert ak._v2.operations.min(array, axis=1).tolist() == [\n [1, 2, 3.3],\n [1, 2, 3.3],\n ]\n assert ak._v2.operations.argmin(array, axis=1).tolist() == [\n [5, 4, 2],\n [5, 3, 2],\n ]\n\n array = ak._v2.highlevel.Array(\n [\n [[1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [], [999, 2.0], [1.0]],\n [[1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [999, 2.0], [1.0], []],\n ]\n )\n assert ak._v2.operations.min(array, axis=1).tolist() == [\n [1, 2, 3.3],\n [1, 2, 3.3],\n ]\n assert ak._v2.operations.argmin(array, axis=1).tolist() == [\n [5, 4, 2],\n [4, 3, 2],\n ]\n\n array = ak._v2.highlevel.Array(\n [\n [[1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [], [999, 2.0], [1.0]],\n [[1.1, 999, 999], [1.1, 2.2, 999], [1.1, 2.2, 3.3], [999, 2.0], [1.0]],\n ]\n )\n assert ak._v2.operations.min(array, axis=1).tolist() == [\n [1, 2, 3.3],\n [1, 2, 3.3],\n ]\n assert ak._v2.operations.argmin(array, axis=1).tolist() == [\n [5, 4, 2],\n [4, 3, 2],\n ]\n\n array = ak._v2.highlevel.Array(\n [\n [[1.1], [1.1, 2.2], [1.1, 2.2, 3.3], [], [999, 2.0], [1.0]],\n [[1.1, 999, 999, 999], [1.1, 2.2, 999], [1.1, 2.2, 3.3], [999, 2.0], [1.0]],\n ]\n )\n assert ak._v2.operations.min(array, axis=1).tolist() == [\n [1, 2, 3.3],\n [1, 2, 3.3, 999],\n ]\n assert ak._v2.operations.argmin(array, axis=1).tolist() == [\n [5, 4, 2],\n [4, 3, 2, 0],\n ]\n\n\ndef test_IndexedOptionArray():\n content = ak._v2.highlevel.Array([1.1, 2.2, 3.3, 4.4, 5.5]).layout\n index = ak._v2.index.Index64(np.array([4, 2, -1, -1, 1, 0, 1]))\n array = ak._v2.highlevel.Array(ak._v2.contents.IndexedOptionArray(index, content))\n assert array.tolist() == [5.5, 3.3, None, None, 2.2, 1.1, 2.2]\n assert ak._v2.operations.min(array, axis=0) == 1.1\n assert ak._v2.operations.argmin(array, axis=0) == 5\n\n assert ak._v2.operations.argmin(\n ak._v2.highlevel.Array([[2.2, 1.1], [None, 3.3], [2.2, 1.1]]), axis=-1\n ).tolist() == [1, 1, 1]\n assert ak._v2.operations.argmin(\n ak._v2.highlevel.Array([[2.2, 1.1], [None, 3.3], [2.2, None, 1.1]]), axis=-1\n ).tolist() == [1, 1, 2]\n assert ak._v2.operations.argmin(\n ak._v2.highlevel.Array([[2.2, 1.1], [3.3, None], [2.2, None, 1.1]]), axis=-1\n ).tolist() == [1, 0, 2]\n\n assert ak._v2.operations.argmin(\n ak._v2.highlevel.Array([[2.2, 1.1, 0.0], [], [None, 0.5], [2, 1]]), axis=0\n ).tolist() == [3, 2, 0]\n assert ak._v2.operations.argmin(\n ak._v2.highlevel.Array([[2.2, 1.1, 0.0], [], [0.5, None], [2, 1]]), axis=0\n ).tolist() == [2, 3, 0]\n assert ak._v2.operations.argmin(\n ak._v2.highlevel.Array([[2.2, 1.1, 0.0], [0.5, None], [], [2, 1]]), axis=0\n ).tolist() == [1, 3, 0]\n\n\ndef test_ByteMaskedArray():\n content = ak._v2.highlevel.Array([1.1, 2.2, 3.3, 999, 999, 4.4, 5.5]).layout\n mask = ak._v2.index.Index8(\n np.array([False, False, False, True, True, False, False])\n )\n bytemaskedarray = ak._v2.contents.ByteMaskedArray(mask, content, valid_when=False)\n array = ak._v2.highlevel.Array(bytemaskedarray)\n assert array.tolist() == [1.1, 2.2, 3.3, None, None, 4.4, 5.5]\n assert ak._v2.operations.max(array, axis=0) == 5.5\n assert ak._v2.operations.argmax(array, axis=0) == 6\n\n offsets = ak._v2.index.Index64(np.array([0, 2, 4, 7], dtype=np.int64))\n listoffsetarray = ak._v2.contents.ListOffsetArray(offsets, bytemaskedarray)\n array = ak._v2.highlevel.Array(listoffsetarray)\n assert array.tolist() == [[1.1, 2.2], [3.3, None], [None, 4.4, 5.5]]\n assert ak._v2.operations.max(array, axis=1).tolist() == [2.2, 3.3, 5.5]\n assert ak._v2.operations.argmax(array, axis=1).tolist() == [1, 0, 2]\n",
"# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE\n\nimport pytest # noqa: F401\nimport numpy as np # noqa: F401\nimport awkward as ak # noqa: F401\n\nto_list = ak._v2.operations.to_list\n\n\ndef test_singletons():\n array = ak._v2.Array([1.1, 2.2, None, 3.3, None, None, 4.4, 5.5])\n assert to_list(ak._v2.operations.singletons(array)) == [\n [1.1],\n [2.2],\n [],\n [3.3],\n [],\n [],\n [4.4],\n [5.5],\n ]\n\n assert to_list(\n ak._v2.operations.singletons(\n ak._v2.Array([1.1, 2.2, None, 3.3, None, None, 4.4, 5.5])\n )\n ) == [[1.1], [2.2], [], [3.3], [], [], [4.4], [5.5]]\n assert to_list(\n ak._v2.operations.singletons(\n ak._v2.Array([[1.1, 2.2, None], [3.3, None], [None], [4.4, 5.5]])\n )\n ) == [[[1.1], [2.2], []], [[3.3], []], [[]], [[4.4], [5.5]]]\n assert to_list(\n ak._v2.operations.singletons(\n ak._v2.Array([[[1.1, 2.2, None]], [[3.3, None]], [[None]], [[4.4, 5.5]]])\n )\n ) == [[[[1.1], [2.2], []]], [[[3.3], []]], [[[]]], [[[4.4], [5.5]]]]\n\n\ndef test_firsts():\n assert to_list(\n ak._v2.operations.firsts(\n ak._v2.operations.singletons(\n ak._v2.Array([1.1, 2.2, None, 3.3, None, None, 4.4, 5.5])\n ),\n axis=1,\n )\n ) == [1.1, 2.2, None, 3.3, None, None, 4.4, 5.5]\n assert to_list(\n ak._v2.operations.firsts(\n ak._v2.operations.singletons(\n ak._v2.Array([[1.1, 2.2, None], [3.3, None], [None], [4.4, 5.5]])\n ),\n axis=2,\n )\n ) == [[1.1, 2.2, None], [3.3, None], [None], [4.4, 5.5]]\n assert to_list(\n ak._v2.operations.firsts(\n ak._v2.operations.singletons(\n ak._v2.Array(\n [[[1.1, 2.2, None]], [[3.3, None]], [[None]], [[4.4, 5.5]]]\n )\n ),\n axis=3,\n )\n ) == [[[1.1, 2.2, None]], [[3.3, None]], [[None]], [[4.4, 5.5]]]\n\n\ndef test_allow_missing():\n array = ak._v2.Array([1.1, 2.2, None, 3.3, None, None, 4.4, 5.5])\n ak._v2.operations.to_numpy(array)\n with pytest.raises(ValueError):\n ak._v2.operations.to_numpy(array, allow_missing=False)\n\n\ndef test_flatten0():\n array = ak._v2.Array([1.1, 2.2, None, 3.3, None, None, 4.4, 5.5])\n assert to_list(ak._v2.operations.flatten(array, axis=0)) == [\n 1.1,\n 2.2,\n 3.3,\n 4.4,\n 5.5,\n ]\n\n content0 = ak._v2.operations.from_iter(\n [1.1, 2.2, None, 3.3, None, None, 4.4, 5.5], highlevel=False\n )\n content1 = ak._v2.operations.from_iter(\n [\"one\", None, \"two\", None, \"three\"], highlevel=False\n )\n array = ak._v2.Array(\n ak._v2.contents.UnionArray(\n ak._v2.index.Index8(\n np.array([0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0], dtype=np.int8)\n ),\n ak._v2.index.Index64(\n np.array([0, 0, 1, 1, 2, 2, 3, 3, 4, 5, 6, 4, 7], dtype=np.int64)\n ),\n [content0, content1],\n )\n )\n assert to_list(array) == [\n 1.1,\n \"one\",\n 2.2,\n None,\n None,\n \"two\",\n 3.3,\n None,\n None,\n None,\n 4.4,\n \"three\",\n 5.5,\n ]\n assert to_list(ak._v2.operations.flatten(array, axis=0)) == [\n 1.1,\n \"one\",\n 2.2,\n \"two\",\n 3.3,\n 4.4,\n \"three\",\n 5.5,\n ]\n",
"# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE\n\nimport pytest # noqa: F401\nimport awkward as ak # noqa: F401\nimport numpy as np\n\nto_list = ak._v2.operations.to_list\n\n\ndef test_1406issue():\n array = ak._v2.Array(\n ak._v2.contents.ListOffsetArray(\n ak._v2.index.Index64(np.array([1, 3], dtype=np.int64)),\n ak._v2.contents.ListOffsetArray(\n ak._v2.index.Index64(np.array([0, 2, 2, 3], dtype=np.int64)),\n ak._v2.contents.NumpyArray(np.array([0, 1, 2], dtype=np.int64)),\n ),\n ),\n check_valid=True,\n )\n\n index = ak._v2.Array(\n ak._v2.contents.ListOffsetArray(\n ak._v2.index.Index64(np.array([0, 2], dtype=np.int64)),\n ak._v2.contents.IndexedOptionArray(\n ak._v2.index.Index64(np.array([0, 1], dtype=np.int64)),\n ak._v2.contents.ListOffsetArray(\n ak._v2.index.Index64(np.array([0, 0, 1], dtype=np.int64)),\n ak._v2.contents.NumpyArray(np.array([0], dtype=np.int64)),\n ),\n ),\n ),\n check_valid=True,\n )\n assert to_list(array[index]) == [[[], [2]]]\n\n\ndef test_success_remove_option_type():\n array = ak._v2.Array(\n ak._v2.contents.ListOffsetArray(\n ak._v2.index.Index64(np.array([1, 3], dtype=np.int64)),\n ak._v2.contents.ListOffsetArray(\n ak._v2.index.Index64(np.array([0, 2, 2, 3], dtype=np.int64)),\n ak._v2.contents.NumpyArray(np.array([0, 1, 2], dtype=np.int64)),\n ),\n ),\n check_valid=True,\n )\n\n index = ak._v2.Array(\n ak._v2.contents.ListOffsetArray(\n ak._v2.index.Index64(np.array([0, 2], dtype=np.int64)),\n ak._v2.contents.ListOffsetArray(\n ak._v2.index.Index64(np.array([0, 0, 1], dtype=np.int64)),\n ak._v2.contents.NumpyArray(np.array([0], dtype=np.int64)),\n ),\n ),\n check_valid=True,\n )\n\n assert to_list(array[index]) == [[[], [2]]]\n\n\ndef test_success_start_offset0():\n\n array = ak._v2.Array(\n ak._v2.contents.ListOffsetArray(\n ak._v2.index.Index64(np.array([0, 2], dtype=np.int64)),\n ak._v2.contents.ListOffsetArray(\n ak._v2.index.Index64(np.array([2, 2, 3], dtype=np.int64)),\n ak._v2.contents.NumpyArray(np.array([0, 1, 2], dtype=np.int64)),\n ),\n ),\n check_valid=True,\n )\n\n index = ak._v2.Array(\n ak._v2.contents.ListOffsetArray(\n ak._v2.index.Index64(np.array([0, 2], dtype=np.int64)),\n ak._v2.contents.IndexedOptionArray(\n ak._v2.index.Index64(np.array([0, 1], dtype=np.int64)),\n ak._v2.contents.ListOffsetArray(\n ak._v2.index.Index64(np.array([0, 0, 1], dtype=np.int64)),\n ak._v2.contents.NumpyArray(np.array([0], dtype=np.int64)),\n ),\n ),\n ),\n check_valid=True,\n )\n\n assert to_list(array[index]) == [[[], [2]]]\n\n\ndef test_success_nonempty_list():\n array = ak._v2.Array(\n ak._v2.contents.ListOffsetArray(\n ak._v2.index.Index64(np.array([1, 3], dtype=np.int64)),\n ak._v2.contents.ListOffsetArray(\n ak._v2.index.Index64(np.array([0, 1, 2, 3], dtype=np.int64)),\n ak._v2.contents.NumpyArray(np.array([0, 1, 2], dtype=np.int64)),\n ),\n ),\n check_valid=True,\n )\n\n index = ak._v2.Array(\n ak._v2.contents.ListOffsetArray(\n ak._v2.index.Index64(np.array([0, 2], dtype=np.int64)),\n ak._v2.contents.IndexedOptionArray(\n ak._v2.index.Index64(np.array([0, 1], dtype=np.int64)),\n ak._v2.contents.ListOffsetArray(\n ak._v2.index.Index64(np.array([0, 1, 2], dtype=np.int64)),\n ak._v2.contents.NumpyArray(np.array([0, 0], dtype=np.int64)),\n ),\n ),\n ),\n check_valid=True,\n )\n\n assert to_list(array[index]) == [[[0], [1]]]\n",
"# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE\n\nimport pytest # noqa: F401\nimport numpy as np # noqa: F401\nimport awkward as ak # noqa: F401\n\nto_list = ak._v2.operations.to_list\n\n\ndef test_fromnumpy():\n a = np.arange(2 * 3 * 5).reshape((2, 3, 5))\n b = ak._v2.operations.from_numpy(a)\n assert to_list(a) == to_list(b)\n\n\ndef test_highlevel():\n a = ak._v2.highlevel.Array(\n [[1.1, 2.2, 3.3], [], [4.4, 5.5], [6.6], [7.7, 8.8, 9.9]], check_valid=True\n )\n assert (\n repr(a)\n == \"<Array [[1.1, 2.2, 3.3], [], ..., [7.7, 8.8, 9.9]] type='5 * var * float64'>\"\n )\n assert str(a) == \"[[1.1, 2.2, 3.3], [], [4.4, 5.5], [6.6], [7.7, 8.8, 9.9]]\"\n\n b = ak._v2.highlevel.Array(np.arange(100, dtype=np.int32), check_valid=True)\n assert (\n repr(b)\n == \"<Array [0, 1, 2, 3, 4, 5, 6, ..., 94, 95, 96, 97, 98, 99] type='100 * int32'>\"\n )\n assert (\n str(b)\n == \"[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ..., 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]\"\n )\n\n c = ak._v2.highlevel.Array(\n '[{\"one\": 3.14, \"two\": [1.1, 2.2]}, {\"one\": 99.9, \"two\": [-3.1415926]}]',\n check_valid=True,\n )\n assert (\n repr(c)\n == \"<Array [{one: 3.14, two: [...]}, {...}] type='2 * {one: float64, two: var *...'>\"\n )\n assert str(c) == \"[{one: 3.14, two: [1.1, 2.2]}, {one: 99.9, two: [-3.14]}]\"\n\n\nclass Dummy(ak.highlevel.Array):\n pass\n\n\ndef test_string1():\n a = ak._v2.highlevel.Array(\n np.array([ord(x) for x in \"hey there\"], dtype=np.uint8), check_valid=True\n )\n a.__class__ = ak._v2.behaviors.string.ByteBehavior\n assert str(a) == str(b\"hey there\")\n assert str(a) == str(b\"hey there\")\n\n\ndef test_string2():\n content = ak._v2.contents.NumpyArray(\n np.array([ord(x) for x in \"heythere\"], dtype=np.uint8)\n )\n listoffsetarray = ak._v2.contents.ListOffsetArray(\n ak._v2.index.Index64(np.array([0, 3, 3, 8])), content\n )\n a = ak._v2.highlevel.Array(listoffsetarray, check_valid=True)\n\n assert isinstance(a, ak._v2.highlevel.Array)\n assert not isinstance(a, ak._v2.behaviors.string.StringBehavior)\n assert to_list(a) == [[104, 101, 121], [], [116, 104, 101, 114, 101]]\n\n assert str(ak._v2.operations.type(a)) == \"3 * var * uint8\"\n assert str(ak._v2.operations.type(a[0])) == \"3 * uint8\"\n assert str(ak._v2.operations.type(a[1])) == \"0 * uint8\"\n assert str(ak._v2.operations.type(a[2])) == \"5 * uint8\"\n assert (\n repr(a)\n == \"<Array [[104, 101, 121], ..., [116, 104, ..., 114, 101]] type='3 * var * uint8'>\"\n )\n assert str(a) == \"[[104, 101, 121], [], [116, 104, 101, 114, 101]]\"\n assert repr(a[0]) == \"<Array [104, 101, 121] type='3 * uint8'>\"\n assert repr(a[1]) == \"<Array [] type='0 * uint8'>\"\n assert repr(a[2]) == \"<Array [116, 104, 101, 114, 101] type='5 * uint8'>\"\n\n content = ak._v2.contents.NumpyArray(\n np.array([ord(x) for x in \"heythere\"], dtype=np.uint8),\n parameters={\"__array__\": \"char\", \"encoding\": \"utf-8\"},\n )\n listoffsetarray = ak._v2.contents.ListOffsetArray(\n ak._v2.index.Index64(np.array([0, 3, 3, 8])),\n content,\n parameters={\"__array__\": \"string\"},\n )\n a = ak._v2.highlevel.Array(listoffsetarray, check_valid=True)\n\n a = ak._v2.highlevel.Array(listoffsetarray, check_valid=True)\n assert isinstance(a, ak._v2.highlevel.Array)\n assert to_list(a) == [\"hey\", \"\", \"there\"]\n\n assert str(a) == \"['hey', '', 'there']\"\n assert repr(a[0]) == \"'hey'\"\n assert repr(a[1]) == \"''\"\n assert repr(a[2]) == \"'there'\"\n",
"# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE\n\nimport pytest # noqa: F401\nimport numpy as np # noqa: F401\nimport awkward as ak # noqa: F401\n\nto_list = ak._v2.operations.to_list\n\n\ndef test_keep_None_in_place_test():\n v2_array = ak._v2.highlevel.Array([[3, 2, 1], [], None, [4, 5]]).layout\n\n assert to_list(v2_array.argsort(axis=1)) == [\n [2, 1, 0],\n [],\n None,\n [0, 1],\n ]\n\n assert to_list(v2_array.sort(axis=1)) == [\n [1, 2, 3],\n [],\n None,\n [4, 5],\n ]\n\n assert to_list(v2_array.sort(axis=1)) == [[1, 2, 3], [], None, [4, 5]]\n assert v2_array.typetracer.sort(axis=1).form == v2_array.argsort(axis=1).form\n\n assert to_list(v2_array.argsort(axis=1)) == [[2, 1, 0], [], None, [0, 1]]\n\n\ndef test_keep_None_in_place_test_2():\n v2_array = ak._v2.highlevel.Array([[3, 2, 1], [], None, [4, 5]]).layout\n assert v2_array.typetracer.argsort(axis=1).form == v2_array.argsort(axis=1).form\n\n\ndef test_empty_slice():\n electron = ak._v2.highlevel.Array(\n ak._v2.contents.ListOffsetArray(\n ak._v2.index.Index64(np.array([0, 0, 1], np.int64)),\n ak._v2.contents.RecordArray(\n [ak._v2.contents.NumpyArray(np.array([1.0]))],\n [\"pt\"],\n parameters={\"__record__\": \"Electron\"},\n ),\n )\n )\n v2_electron = electron.layout[[[], []]]\n\n assert to_list(v2_electron) == [[], []]\n\n\ndef test_masked():\n v2_array = ak._v2.highlevel.Array([[0, 1, 2, 3], [3, 3, 3, 2, 1]])\n is_valid = v2_array != 3\n\n v2_array_mask = ak._v2.highlevel.Array(\n ak._v2.contents.ListOffsetArray(\n v2_array.layout.offsets,\n ak._v2.contents.ByteMaskedArray(\n ak._v2.index.Index8(is_valid.layout.content.data),\n v2_array.layout.content,\n valid_when=True,\n ),\n )\n )\n\n assert to_list(v2_array_mask) == [\n [0, 1, 2, None],\n [None, None, None, 2, 1],\n ]\n\n assert to_list(v2_array_mask.layout.sort(axis=1)) == [\n [0, 1, 2, None],\n [1, 2, None, None, None],\n ]\n assert (\n v2_array_mask.layout.typetracer.sort(axis=1).form\n == v2_array_mask.layout.sort(axis=1).form\n )\n\n\ndef test_v1_argsort_and_v2_sort():\n v2_array = ak._v2.highlevel.Array([1, 2, None, 3, 0, None]).layout\n assert to_list(v2_array.sort()) == [\n 0,\n 1,\n 2,\n 3,\n None,\n None,\n ]\n assert v2_array.typetracer.sort().form == v2_array.sort().form\n\n\ndef test_v1_argsort_2d_and_v2_sort():\n v2_array = ak._v2.highlevel.Array(\n [[1, 2, None, 3, 0, None], [1, 2, None, 3, 0, None]]\n ).layout\n assert to_list(v2_array.sort()) == [\n [\n 0,\n 1,\n 2,\n 3,\n None,\n None,\n ],\n [\n 0,\n 1,\n 2,\n 3,\n None,\n None,\n ],\n ]\n assert v2_array.typetracer.sort().form == v2_array.sort().form\n\n\ndef test_nan():\n v2_array = ak._v2.highlevel.Array([1, 2, np.nan, 3, 0, np.nan]).layout\n assert str(to_list(v2_array.sort())) == \"[nan, nan, 0.0, 1.0, 2.0, 3.0]\"\n assert v2_array.typetracer.sort().form == v2_array.sort().form\n\n\ndef test_sort_strings():\n v2_array = ak._v2.highlevel.Array(\n [\"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\"]\n ).layout\n assert to_list(v2_array) == [\n \"one\",\n \"two\",\n \"three\",\n \"four\",\n \"five\",\n \"six\",\n \"seven\",\n \"eight\",\n ]\n assert to_list(v2_array.sort()) == [\n \"eight\",\n \"five\",\n \"four\",\n \"one\",\n \"seven\",\n \"six\",\n \"three\",\n \"two\",\n ]\n assert v2_array.typetracer.sort().form == v2_array.sort().form\n\n\ndef test_sort_nested_strings():\n v2_array = ak._v2.highlevel.Array(\n [[\"one\", \"two\"], [\"three\", \"four\", \"five\"], [\"six\"], [\"seven\", \"eight\"]]\n ).layout\n assert to_list(v2_array) == [\n [\"one\", \"two\"],\n [\"three\", \"four\", \"five\"],\n [\"six\"],\n [\"seven\", \"eight\"],\n ]\n assert to_list(v2_array.sort()) == [\n [\"one\", \"two\"],\n [\"five\", \"four\", \"three\"],\n [\"six\"],\n [\"eight\", \"seven\"],\n ]\n\n assert v2_array.typetracer.sort().form == v2_array.sort().form\n\n\ndef test_sort_invalid_axis():\n v2_array = ak._v2.operations.from_numpy(\n np.array([[3.3, 2.2], [1.1, 5.5], [4.4, 6.6]]),\n regulararray=True,\n highlevel=False,\n )\n\n with pytest.raises(ValueError) as err:\n v2_array.sort(axis=3)\n assert str(err.value).startswith(\n \"axis=3 exceeds the depth of the nested list structure (which is 2)\"\n )\n\n\ndef test_numpy_array_iscontiguous():\n matrix = np.arange(64).reshape(8, -1)\n v2_layout = ak._v2.contents.NumpyArray(matrix[:, 0])\n\n assert not v2_layout.is_contiguous\n\n assert to_list(v2_layout) == [0, 8, 16, 24, 32, 40, 48, 56]\n\n matrix2 = np.arange(64).reshape(8, -1)\n v2_array = ak._v2.contents.NumpyArray(matrix2[:, 0])\n assert not v2_array.is_contiguous\n\n assert to_list(v2_array.sort()) == [0, 8, 16, 24, 32, 40, 48, 56]\n assert v2_array.typetracer.sort().form == v2_array.sort().form\n\n\ndef test_numpyarray_sort():\n v2_array = ak._v2.operations.from_numpy(\n np.array([3.3, 2.2, 1.1, 5.5, 4.4]), regulararray=True, highlevel=False\n )\n assert to_list(np.sort(np.asarray(v2_array))) == [\n 1.1,\n 2.2,\n 3.3,\n 4.4,\n 5.5,\n ]\n assert to_list(v2_array.sort()) == [\n 1.1,\n 2.2,\n 3.3,\n 4.4,\n 5.5,\n ]\n assert v2_array.typetracer.sort().form == v2_array.sort().form\n\n\ndef test_3d():\n array = ak._v2.Array(\n np.array(\n [\n # axis 2: 0 1 2 3 4 # axis 1:\n [\n [1.1, 2.2, 3.3, 4.4, 5.5], # 0\n [6.6, 7.7, 8.8, 9.9, 10.10], # 1\n [11.11, 12.12, 13.13, 14.14, 15.15],\n ], # 2\n [\n [-1.1, -2.2, -3.3, -4.4, -5.5], # 3\n [-6.6, -7.7, -8.8, -9.9, -10.1], # 4\n [-11.11, -12.12, -13.13, -14.14, -15.15],\n ],\n ]\n )\n ) # 5\n\n assert to_list(\n ak._v2.operations.argsort(array, axis=2, ascending=True, stable=False)\n ) == to_list(np.argsort(array, 2))\n assert to_list(\n ak._v2.operations.sort(array, axis=2, ascending=True, stable=False)\n ) == to_list(np.sort(np.asarray(array), 2))\n assert to_list(\n ak._v2.operations.argsort(array, axis=1, ascending=True, stable=False)\n ) == to_list(np.argsort(np.asarray(array), 1))\n assert to_list(\n ak._v2.operations.sort(array, axis=1, ascending=True, stable=False)\n ) == to_list(np.sort(np.asarray(array), 1))\n assert to_list(\n ak._v2.operations.sort(np.asarray(array), axis=1, ascending=False, stable=False)\n ) == [\n [\n [11.11, 12.12, 13.13, 14.14, 15.15],\n [6.6, 7.7, 8.8, 9.9, 10.1],\n [1.1, 2.2, 3.3, 4.4, 5.5],\n ],\n [\n [-1.1, -2.2, -3.3, -4.4, -5.5],\n [-6.6, -7.7, -8.8, -9.9, -10.1],\n [-11.11, -12.12, -13.13, -14.14, -15.15],\n ],\n ]\n assert to_list(\n ak._v2.operations.sort(array, axis=0, ascending=True, stable=False)\n ) == to_list(np.sort(np.asarray(array), 0))\n assert to_list(\n ak._v2.operations.argsort(array, axis=0, ascending=True, stable=False)\n ) == to_list(np.argsort(np.asarray(array), 0))\n\n\ndef test_bool_sort():\n v2_array = ak._v2.operations.from_numpy(\n np.array([True, False, True, False, False]), regulararray=True, highlevel=False\n )\n assert to_list(v2_array.sort()) == [\n False,\n False,\n False,\n True,\n True,\n ]\n assert v2_array.typetracer.sort().form == v2_array.sort().form\n\n\ndef test_emptyarray_sort():\n v2_array = ak._v2.contents.emptyarray.EmptyArray()\n assert to_list(v2_array.sort()) == []\n\n v2_array = ak._v2.highlevel.Array([[], [], []]).layout\n assert to_list(v2_array.sort()) == [[], [], []]\n assert v2_array.typetracer.sort().form == v2_array.sort().form\n\n\ndef test_listarray_sort():\n v2_array = ak._v2.contents.listarray.ListArray( # noqa: F841\n ak._v2.index.Index(np.array([4, 100, 1])),\n ak._v2.index.Index(np.array([7, 100, 3, 200])),\n ak._v2.contents.numpyarray.NumpyArray(\n np.array([6.6, 4.4, 5.5, 7.7, 3.3, 2.2, 1.1, 8.8])\n ),\n )\n\n assert to_list(v2_array) == [\n [3.3, 2.2, 1.1],\n [],\n [4.4, 5.5],\n ]\n\n assert to_list(v2_array.sort()) == [\n [1.1, 2.2, 3.3],\n [],\n [4.4, 5.5],\n ]\n assert v2_array.typetracer.sort().form == v2_array.sort().form\n\n\ndef test_listoffsetarray_sort():\n v2_array = ak._v2.operations.from_iter(\n [[3.3, 2.2, 1.1], [], [5.5, 4.4], [6.6], [9.9, 7.7, 8.8, 10.1]], highlevel=False\n )\n assert to_list(v2_array.sort()) == [\n [1.1, 2.2, 3.3],\n [],\n [4.4, 5.5],\n [6.6],\n [7.7, 8.8, 9.9, 10.10],\n ]\n assert v2_array.typetracer.sort().form == v2_array.sort().form\n assert to_list(v2_array.sort(axis=0)) == [\n [3.3, 2.2, 1.1],\n [],\n [5.5, 4.4],\n [6.6],\n [9.9, 7.7, 8.8, 10.1],\n ]\n assert v2_array.typetracer.sort(axis=0).form == v2_array.sort(axis=0).form\n\n v2_array = ak._v2.operations.from_iter(\n [\n [[11.1, 0.0, -2.2], [], [33.33, 4.4]],\n [],\n [[5.5]],\n [[6.6, -9.9, 8.8, 7.7]],\n [[], [12.2, 1.1, 10.0]],\n ],\n highlevel=False,\n )\n assert to_list(v2_array.sort(axis=0)) == [\n [[5.5, -9.9, -2.2], [], [33.33, 4.4]],\n [],\n [[6.6]],\n [[11.1, 0.0, 8.8, 7.7]],\n [[], [12.2, 1.1, 10.0]],\n ]\n assert v2_array.typetracer.sort(axis=0).form == v2_array.sort(axis=0).form\n # [\n # [[5.5, -9.9, -2.2], [], [33.33, 4.4]],\n # [],\n # [[6.6]],\n # [[11.1, 0.0, 8.8, 7.7]],\n # [[], [12.2, 1.1, 10.0]]\n # ]\n assert to_list(v2_array.sort(axis=1)) == [\n [[11.1, 0.0, -2.2], [], [33.33, 4.4]],\n [],\n [[5.5]],\n [[6.6, -9.9, 8.8, 7.7]],\n [[], [12.2, 1.1, 10.0]],\n ]\n assert v2_array.typetracer.sort(axis=1).form == v2_array.sort(axis=1).form\n # [\n # [[11.1, 0.0, -2.2], [], [33.33, 4.4]],\n # [],\n # [[5.5]],\n # [[6.6, -9.9, 8.8, 7.7]],\n # [[], [12.2, 1.1, 10.0]]\n # ]\n assert to_list(v2_array.sort(axis=2)) == [\n [[-2.2, 0.0, 11.1], [], [4.4, 33.33]],\n [],\n [[5.5]],\n [[-9.9, 6.6, 7.7, 8.8]],\n [[], [1.1, 10.0, 12.2]],\n ]\n assert v2_array.typetracer.sort(axis=2).form == v2_array.sort(axis=2).form\n # [\n # [[-2.2, 0.0, 11.1], [], [4.4, 33.33]],\n # [],\n # [[5.5]],\n # [[-9.9, 6.6, 7.7, 8.8]],\n # [[], [1.1, 10.0, 12.2]]\n # ]\n assert to_list(v2_array.sort()) == [\n [[-2.2, 0.0, 11.1], [], [4.4, 33.33]],\n [],\n [[5.5]],\n [[-9.9, 6.6, 7.7, 8.8]],\n [[], [1.1, 10.0, 12.2]],\n ]\n assert v2_array.typetracer.sort().form == v2_array.sort().form\n # [\n # [[-2.2, 0.0, 11.1], [], [4.4, 33.33]],\n # [],\n # [[5.5]],\n # [[-9.9, 6.6, 7.7, 8.8]],\n # [[], [1.1, 10.0, 12.2]]\n # ]\n\n\ndef test_regulararray_sort():\n v2_array = ak._v2.operations.from_numpy(\n np.array(\n [\n [\n [3.3, 1.1, 5.5, 2.2, 4.4],\n [8.8, 6.6, 9.9, 7.7, 10.10],\n [11.11, 14.14, 15.15, 12.12, 13.13],\n ],\n [\n [-1.1, -2.2, -5.5, -3.3, -4.4],\n [-7.7, -8.8, -9.9, -6.6, -10.1],\n [-13.13, -11.11, -12.12, -14.14, -15.15],\n ],\n ]\n ),\n regulararray=True,\n highlevel=False,\n )\n assert to_list(v2_array) == [\n [\n [3.3, 1.1, 5.5, 2.2, 4.4],\n [8.8, 6.6, 9.9, 7.7, 10.1],\n [11.11, 14.14, 15.15, 12.12, 13.13],\n ],\n [\n [-1.1, -2.2, -5.5, -3.3, -4.4],\n [-7.7, -8.8, -9.9, -6.6, -10.1],\n [-13.13, -11.11, -12.12, -14.14, -15.15],\n ],\n ]\n assert to_list(v2_array.sort()) == [\n [\n [1.1, 2.2, 3.3, 4.4, 5.5],\n [6.6, 7.7, 8.8, 9.9, 10.1],\n [11.11, 12.12, 13.13, 14.14, 15.15],\n ],\n [\n [-5.5, -4.4, -3.3, -2.2, -1.1],\n [-10.1, -9.9, -8.8, -7.7, -6.6],\n [-15.15, -14.14, -13.13, -12.12, -11.11],\n ],\n ]\n assert v2_array.typetracer.sort().form == v2_array.sort().form\n\n\ndef test_bytemaskedarray_sort():\n content = ak._v2.operations.from_iter(\n [\n [[1.1, 0.0, 2.2], [], [3.3, 4.4]],\n [],\n [[5.5]],\n [[6.6, 9.9, 8.8, 7.7]],\n [[], [12.2, 11.1, 10.0]],\n ],\n highlevel=False,\n )\n mask = ak._v2.index.Index8(np.array([0, 0, 1, 1, 0], dtype=np.int8))\n v2_array = ak._v2.contents.ByteMaskedArray(mask, content, valid_when=False)\n\n assert to_list(v2_array) == [\n [[1.1, 0.0, 2.2], [], [3.3, 4.4]],\n [],\n None,\n None,\n [[], [12.2, 11.1, 10.0]],\n ]\n assert to_list(v2_array.sort()) == [\n [[0.0, 1.1, 2.2], [], [3.3, 4.4]],\n [],\n None,\n None,\n [[], [10.0, 11.1, 12.2]],\n ]\n assert v2_array.typetracer.sort().form == v2_array.sort().form\n\n\ndef test_bytemaskedarray_sort_2():\n array3 = ak._v2.highlevel.Array(\n [[2.2, 1.1, 3.3], [], [4.4, 5.5], [5.5], [-4.4, -5.5, -6.6]]\n ).layout\n\n assert to_list(\n ak._v2.operations.sort(array3, axis=1, ascending=False, stable=False)\n ) == [\n [3.3, 2.2, 1.1],\n [],\n [5.5, 4.4],\n [5.5],\n [-4.4, -5.5, -6.6],\n ]\n\n assert to_list(\n ak._v2.operations.sort(array3, axis=0, ascending=True, stable=False)\n ) == [\n [-4.4, -5.5, -6.6],\n [],\n [2.2, 1.1],\n [4.4],\n [5.5, 5.5, 3.3],\n ]\n\n content = ak._v2.operations.from_iter(\n [[0.0, 1.1, 2.2], [], [3.3, 4.4], [5.5], [6.6, 7.7, 8.8, 9.9]], highlevel=False\n )\n mask = ak._v2.index.Index8(np.array([0, 0, 1, 1, 0], dtype=np.int8))\n array = ak._v2.contents.ByteMaskedArray(mask, content, valid_when=False)\n assert to_list(\n ak._v2.operations.argsort(array, axis=0, ascending=True, stable=False)\n ) == [\n [0, 0, 0],\n [],\n [2, 2, 2, 2],\n None,\n None,\n ]\n\n assert to_list(\n ak._v2.operations.sort(array, axis=0, ascending=True, stable=False)\n ) == [\n [0.0, 1.1, 2.2],\n [],\n [6.6, 7.7, 8.8, 9.9],\n None,\n None,\n ]\n\n assert to_list(\n ak._v2.operations.sort(array, axis=0, ascending=False, stable=False)\n ) == [\n [6.6, 7.7, 8.8],\n [],\n [0.0, 1.1, 2.2, 9.9],\n None,\n None,\n ]\n\n assert to_list(\n ak._v2.operations.argsort(array, axis=1, ascending=True, stable=False)\n ) == [\n [0, 1, 2],\n [],\n None,\n None,\n [0, 1, 2, 3],\n ]\n\n assert to_list(ak._v2.operations.sort(array, 1, False, False)) == [\n [2.2, 1.1, 0.0],\n [],\n None,\n None,\n [9.9, 8.8, 7.7, 6.6],\n ]\n\n\ndef test_bitmaskedarray_sort():\n v2_array = ak._v2.contents.bitmaskedarray.BitMaskedArray(\n ak._v2.index.Index(\n np.packbits(\n np.array(\n [\n 1,\n 1,\n 1,\n 1,\n 0,\n 0,\n 0,\n 0,\n 1,\n 0,\n 1,\n 0,\n 1,\n ],\n dtype=np.uint8,\n )\n )\n ),\n ak._v2.contents.numpyarray.NumpyArray(\n np.array(\n [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6]\n )\n ),\n valid_when=True,\n length=13,\n lsb_order=False,\n )\n\n assert to_list(v2_array.sort()) == [\n 0.0,\n 1.0,\n 1.1,\n 2.0,\n 3.0,\n 3.3,\n 5.5,\n None,\n None,\n None,\n None,\n None,\n None,\n ]\n assert v2_array.typetracer.sort().form == v2_array.sort().form\n\n\ndef test_unmaskedarray_sort():\n v2_array = ak._v2.contents.unmaskedarray.UnmaskedArray(\n ak._v2.contents.numpyarray.NumpyArray(\n np.array([0.0, 2.2, 1.1, 3.3], dtype=np.float64)\n )\n )\n assert to_list(v2_array.sort()) == [0.0, 1.1, 2.2, 3.3]\n assert v2_array.typetracer.sort().form == v2_array.sort().form\n\n\ndef test_unionarray_sort():\n v2_array = ak._v2.contents.unionarray.UnionArray(\n ak._v2.index.Index(np.array([1, 1, 0, 0, 1, 0, 1], dtype=np.int8)),\n ak._v2.index.Index(np.array([4, 3, 0, 1, 2, 2, 4, 100])),\n [\n ak._v2.contents.numpyarray.NumpyArray(np.array([1, 2, 3])),\n ak._v2.contents.numpyarray.NumpyArray(np.array([1.1, 2.2, 3.3, 4.4, 5.5])),\n ],\n )\n\n assert to_list(v2_array) == [5.5, 4.4, 1, 2, 3.3, 3, 5.5]\n assert to_list(v2_array.sort()) == [1.0, 2.0, 3.0, 3.3, 4.4, 5.5, 5.5]\n\n\ndef test_unionarray_sort_2():\n v2_array = ak._v2.contents.unionarray.UnionArray( # noqa: F841\n ak._v2.index.Index(np.array([1, 1, 0, 0, 1, 0, 1], dtype=np.int8)),\n ak._v2.index.Index(np.array([4, 3, 0, 1, 2, 2, 4, 100])),\n [\n ak._v2.contents.numpyarray.NumpyArray(np.array([1, 2, 3])),\n ak._v2.contents.numpyarray.NumpyArray(np.array([7, 0, 3, 4, 5])),\n ],\n )\n\n assert to_list(v2_array) == [5, 4, 1, 2, 3, 3, 5]\n assert to_list(v2_array.sort()) == [1, 2, 3, 3, 4, 5, 5]\n\n\ndef test_indexedarray_sort():\n v2_array = ak._v2.contents.indexedarray.IndexedArray( # noqa: F841\n ak._v2.index.Index(np.array([2, 2, 0, 1, 4, 5, 4])),\n ak._v2.contents.numpyarray.NumpyArray(np.array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6])),\n )\n assert to_list(v2_array) == [3.3, 3.3, 1.1, 2.2, 5.5, 6.6, 5.5]\n assert to_list(v2_array.sort()) == [1.1, 2.2, 3.3, 3.3, 5.5, 5.5, 6.6]\n assert v2_array.typetracer.sort().form == v2_array.sort().form\n\n\ndef test_indexedoptionarray_sort():\n v2_array = ak._v2.contents.indexedoptionarray.IndexedOptionArray( # noqa: F841\n ak._v2.index.Index(np.array([2, 2, -1, 1, -1, 5, 4])),\n ak._v2.contents.recordarray.RecordArray(\n [\n ak._v2.contents.numpyarray.NumpyArray(\n np.array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6])\n )\n ],\n [\"nest\"],\n ),\n )\n assert to_list(v2_array.sort()) == [\n {\"nest\": 2.2},\n {\"nest\": 3.3},\n {\"nest\": 3.3},\n {\"nest\": 5.5},\n {\"nest\": 6.6},\n None,\n None,\n ]\n assert v2_array.typetracer.sort().form == v2_array.sort().form\n\n v2_array = ak._v2.highlevel.Array(\n [[1, 2, None, 3, 0, None], [1, 2, None, 3, 0, None]]\n ).layout\n assert to_list(v2_array) == [\n [1, 2, None, 3, 0, None],\n [1, 2, None, 3, 0, None],\n ]\n assert to_list(v2_array.sort()) == [\n [0, 1, 2, 3, None, None],\n [0, 1, 2, 3, None, None],\n ]\n assert v2_array.typetracer.sort().form == v2_array.sort().form\n\n v2_array = ak._v2.highlevel.Array(\n [\n [None, None, 2.2, 1.1, 3.3],\n [None, None, None],\n [4.4, None, 5.5],\n [5.5, None, None],\n [-4.4, -5.5, -6.6],\n ]\n ).layout\n\n assert to_list(v2_array.sort()) == [\n [1.1, 2.2, 3.3, None, None],\n [None, None, None],\n [4.4, 5.5, None],\n [5.5, None, None],\n [-6.6, -5.5, -4.4],\n ]\n assert v2_array.typetracer.sort().form == v2_array.sort().form\n\n assert to_list(v2_array.sort(axis=0)) == [\n [-4.4, -5.5, -6.6, 1.1, 3.3],\n [4.4, None, 2.2],\n [5.5, None, 5.5],\n [None, None, None],\n [None, None, None],\n ]\n assert v2_array.typetracer.sort(axis=0).form == v2_array.sort(axis=0).form\n\n assert to_list(v2_array.sort(axis=1, ascending=True, stable=False)) == [\n [1.1, 2.2, 3.3, None, None],\n [None, None, None],\n [4.4, 5.5, None],\n [5.5, None, None],\n [-6.6, -5.5, -4.4],\n ]\n assert (\n v2_array.typetracer.sort(axis=1, ascending=True, stable=False).form\n == v2_array.sort(axis=1, ascending=True, stable=False).form\n )\n\n assert to_list(v2_array.sort(axis=1, ascending=False, stable=True)) == [\n [3.3, 2.2, 1.1, None, None],\n [None, None, None],\n [5.5, 4.4, None],\n [5.5, None, None],\n [-4.4, -5.5, -6.6],\n ]\n assert (\n v2_array.typetracer.sort(axis=1, ascending=False, stable=True).form\n == v2_array.sort(axis=1, ascending=False, stable=True).form\n )\n\n assert to_list(v2_array.sort(axis=1, ascending=False, stable=False)) == [\n [3.3, 2.2, 1.1, None, None],\n [None, None, None],\n [5.5, 4.4, None],\n [5.5, None, None],\n [-4.4, -5.5, -6.6],\n ]\n assert (\n v2_array.typetracer.sort(axis=1, ascending=False, stable=False).form\n == v2_array.sort(axis=1, ascending=False, stable=False).form\n )\n\n\ndef test_sort_zero_length_arrays():\n array = ak._v2.contents.IndexedArray(\n ak._v2.index.Index64([]), ak._v2.contents.NumpyArray([1, 2, 3])\n )\n assert to_list(array) == []\n assert to_list(ak._v2.operations.sort(array)) == []\n assert to_list(ak._v2.operations.argsort(array)) == []\n\n content0 = ak._v2.operations.from_iter(\n [[1.1, 2.2, 3.3], [], [4.4, 5.5]], highlevel=False\n )\n content1 = ak._v2.operations.from_iter(\n [\"one\", \"two\", \"three\", \"four\", \"five\"], highlevel=False\n )\n tags = ak._v2.index.Index8([])\n index = ak._v2.index.Index32([])\n array = ak._v2.contents.UnionArray(tags, index, [content0, content1])\n assert to_list(array) == []\n assert to_list(ak._v2.operations.sort(array)) == []\n assert to_list(ak._v2.operations.argsort(array)) == []\n\n content = ak._v2.operations.from_iter(\n [[0.0, 1.1, 2.2], [], [3.3, 4.4], [5.5], [6.6, 7.7, 8.8, 9.9]], highlevel=False\n )\n mask = ak._v2.index.Index8([])\n array = ak._v2.contents.ByteMaskedArray(mask, content, valid_when=False)\n assert to_list(array) == []\n assert to_list(ak._v2.operations.sort(array)) == []\n assert to_list(ak._v2.operations.argsort(array)) == []\n\n array = ak._v2.contents.NumpyArray([])\n assert to_list(array) == []\n assert to_list(ak._v2.operations.sort(array)) == []\n assert to_list(ak._v2.operations.argsort(array)) == []\n\n array = ak._v2.contents.RecordArray([], None, 0)\n assert to_list(array) == []\n assert to_list(ak._v2.operations.sort(array)) == []\n\n content = ak._v2.contents.NumpyArray(\n np.array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9])\n )\n starts1 = ak._v2.index.Index64([])\n stops1 = ak._v2.index.Index64([])\n offsets1 = ak._v2.index.Index64(np.array([0]))\n array = ak._v2.contents.ListArray(starts1, stops1, content)\n assert to_list(array) == []\n assert to_list(ak._v2.operations.sort(array)) == []\n assert to_list(ak._v2.operations.argsort(array)) == []\n\n array = ak._v2.contents.ListOffsetArray(offsets1, content)\n assert to_list(array) == []\n assert to_list(ak._v2.operations.sort(array)) == []\n assert to_list(ak._v2.operations.argsort(array)) == []\n\n\ndef test_recordarray_sort():\n v2_array = ak._v2.contents.regulararray.RegularArray( # noqa: F841\n ak._v2.contents.recordarray.RecordArray(\n [\n ak._v2.contents.numpyarray.NumpyArray(\n np.array([0.0, 1.1, 2.2, 33.33, 4.4, 5.5, -6.6])\n )\n ],\n [\"nest\"],\n ),\n 3,\n )\n assert to_list(v2_array.sort()) == [\n [{\"nest\": 0.0}, {\"nest\": 1.1}, {\"nest\": 2.2}],\n [{\"nest\": 4.4}, {\"nest\": 5.5}, {\"nest\": 33.33}],\n ]\n assert v2_array.typetracer.sort().form == v2_array.sort().form\n",
"# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE\n\nimport pytest # noqa: F401\nimport numpy as np # noqa: F401\nimport awkward as ak # noqa: F401\n\nto_list = ak._v2.operations.to_list\n\n\ndef test_numpyarray_getitem_bystrides():\n a = np.arange(10)\n b = ak._v2.contents.NumpyArray(a)\n\n assert b[3] == a[3]\n assert b[-3] == a[-3]\n assert to_list(b[()]) == to_list(a[()])\n assert to_list(b[slice(None)]) == to_list(a[slice(None)])\n assert to_list(b[slice(3, 7)]) == to_list(a[slice(3, 7)])\n assert to_list(b[slice(3, 100)]) == to_list(a[slice(3, 100)])\n assert to_list(b[slice(-100, 7)]) == to_list(a[slice(-100, 7)])\n assert to_list(b[slice(3, -3)]) == to_list(a[slice(3, -3)])\n assert to_list(b[slice(1, 7, 2)]) == to_list(a[slice(1, 7, 2)])\n assert to_list(b[slice(-8, 7, 2)]) == to_list(a[slice(-8, 7, 2)])\n assert to_list(b[slice(None, 7, 2)]) == to_list(a[slice(None, 7, 2)])\n assert to_list(b[slice(None, -3, 2)]) == to_list(a[slice(None, -3, 2)])\n assert to_list(b[slice(8, None, -1)]) == to_list(a[slice(8, None, -1)])\n assert to_list(b[slice(8, None, -2)]) == to_list(a[slice(8, None, -2)])\n assert to_list(b[slice(-2, None, -2)]) == to_list(a[slice(-2, None, -2)])\n\n a = np.arange(7 * 5).reshape(7, 5)\n b = ak._v2.contents.NumpyArray(a)\n\n assert to_list(b[()]) == to_list(a[()])\n assert to_list(b[3]) == to_list(a[3])\n assert to_list(b[(3, 2)]) == to_list(a[3, 2])\n assert to_list(b[slice(1, 4)]) == to_list(a[slice(1, 4)])\n assert to_list(b[(3, slice(1, 4))]) == to_list(a[3, slice(1, 4)])\n assert to_list(b[(slice(1, 4), 3)]) == to_list(a[slice(1, 4), 3])\n assert to_list(b[(slice(1, 4), slice(2, None))]) == to_list(\n a[slice(1, 4), slice(2, None)]\n )\n assert to_list(b[(slice(None, None, -1), slice(2, None))]) == to_list(\n a[slice(None, None, -1), slice(2, None)]\n )\n\n assert to_list(b[:, np.newaxis, :]) == to_list(a[:, np.newaxis, :])\n assert to_list(b[np.newaxis, :, np.newaxis, :, np.newaxis]) == to_list(\n a[np.newaxis, :, np.newaxis, :, np.newaxis]\n )\n\n assert to_list(b[Ellipsis, 3]) == to_list(a[Ellipsis, 3])\n assert to_list(b[Ellipsis, 3, 2]) == to_list(a[Ellipsis, 3, 2])\n assert to_list(b[3, Ellipsis]) == to_list(a[3, Ellipsis])\n assert to_list(b[3, 2, Ellipsis]) == to_list(a[3, 2, Ellipsis])\n\n\ndef test_numpyarray_getitem_next():\n a = np.arange(10)\n b = ak._v2.contents.NumpyArray(a)\n c = np.array([7, 3, 3, 5])\n\n assert to_list(b[c]) == to_list(a[c])\n assert b.typetracer[c].form == b[c].form\n c = np.array([0, 0, 0, 1, 1, 1, 0, 1, 0, 1])\n assert to_list(b[c]) == to_list(a[c])\n assert b.typetracer[c].form == b[c].form\n c = np.array([False, False, False, True, True, True, False, True, False, True])\n assert to_list(b[c]) == to_list(a[c])\n assert b.typetracer[c].form == b[c].form\n c = np.array([], dtype=int)\n assert to_list(b[c]) == to_list(a[c])\n assert b.typetracer[c].form == b[c].form\n\n a = np.arange(10 * 3).reshape(10, 3)\n b = ak._v2.contents.NumpyArray(a)\n c = np.array([7, 3, 3, 5])\n\n assert to_list(b[c]) == to_list(a[c])\n assert b.typetracer[c].form == b[c].form\n c = np.array([False, False, False, True, True, True, False, True, False, True])\n assert to_list(b[c]) == to_list(a[c])\n assert b.typetracer[c].form == b[c].form\n c = np.array([], dtype=int)\n assert to_list(b[c]) == to_list(a[c])\n assert b.typetracer[c].form == b[c].form\n\n a = np.arange(7 * 5).reshape(7, 5)\n b = ak._v2.contents.NumpyArray(a)\n\n c1 = np.array([], np.int64)\n c2 = np.array([], np.int64)\n\n assert to_list(b[c1, c2]) == to_list(a[c1, c2])\n assert a[c1, c2].ndim == 1\n assert b.typetracer[c1, c2].form == b[c1, c2].form\n\n a = np.arange(7 * 5).reshape(7, 5)\n b = ak._v2.contents.NumpyArray(a)\n c1 = np.array([4, 1, 1, 3])\n c2 = np.array([2, 2, 0, 1])\n assert to_list(b[c1, c2]) == to_list(a[c1, c2])\n assert b.typetracer[c1, c2].form == b[c1, c2].form\n\n c = np.array([False, False, True, True, False, True, True])\n assert to_list(b[c]) == to_list(a[c])\n assert b.typetracer[c].form == b[c].form\n\n c = np.array([], dtype=int)\n assert to_list(b[c]) == to_list(a[c])\n c1 = np.array([], dtype=int)\n c2 = np.array([], dtype=int)\n assert to_list(b[c1, c2]) == to_list(a[c1, c2])\n assert b.typetracer[c1, c2].form == b[c1, c2].form\n\n a = np.arange(7 * 5).reshape(7, 5)\n b = ak._v2.contents.NumpyArray(a)\n c = np.array([2, 0, 0, 1])\n assert to_list(b[1:4, c]) == to_list(a[1:4, c])\n assert to_list(b[c, 1:4]) == to_list(a[c, 1:4])\n assert to_list(b[1:4, np.newaxis, c]) == to_list(a[1:4, np.newaxis, c])\n assert to_list(b[c, np.newaxis, 1:4]) == to_list(a[c, np.newaxis, 1:4])\n assert to_list(b[1:4, np.newaxis, np.newaxis, c]) == to_list(\n a[1:4, np.newaxis, np.newaxis, c]\n )\n assert to_list(b[c, np.newaxis, np.newaxis, 1:4]) == to_list(\n a[c, np.newaxis, np.newaxis, 1:4]\n )\n assert to_list(b[Ellipsis, c]) == to_list(a[Ellipsis, c])\n assert to_list(b[c, Ellipsis]) == to_list(a[c, Ellipsis])\n\n\ndef test_numpyarray_getitem_next_2():\n a = np.arange(7 * 5).reshape(7, 5)\n b = ak._v2.contents.NumpyArray(a)\n\n c1 = np.array([[4, 1], [1, 3], [0, 4]])\n c2 = np.array([[2, 2], [0, 1], [1, 3]])\n assert to_list(b[c1, c2]) == to_list(a[c1, c2])\n\n c = a % 2 == 0 # two dimensional\n assert to_list(b[c]) == to_list(a[c])\n assert to_list(b[c,]) == to_list( # noqa: E231\n a[\n c,\n ]\n )\n"
] | [
[
"numpy.arange"
],
[
"numpy.frombuffer",
"numpy.array"
],
[
"numpy.array"
],
[
"numpy.array"
],
[
"numpy.array"
],
[
"numpy.arange",
"numpy.array"
],
[
"numpy.argsort",
"numpy.arange",
"numpy.array",
"numpy.asarray"
],
[
"numpy.arange",
"numpy.array"
]
] | [
{
"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": []
}
] |
VACUMM/xoa | [
"c6a0d860528cf33ae15c77fa111f95daab0321c0",
"c6a0d860528cf33ae15c77fa111f95daab0321c0",
"c6a0d860528cf33ae15c77fa111f95daab0321c0",
"c6a0d860528cf33ae15c77fa111f95daab0321c0"
] | [
"xoa/__init__.py",
"xoa/tests/test_coords.py",
"xoa/tests/test_regrid.py",
"xoa/geo.py"
] | [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nxarray-based ocean analysis library\n\nThe successor of Vacumm.\n\"\"\"\n# Copyright 2020-2021 Shom\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 os\nimport re\nimport warnings\nimport platform\n\nimport pkg_resources\nimport appdirs\nimport configobj\nimport validate\n\n\n# Taken from xarray\ntry:\n __version__ = pkg_resources.get_distribution(\"xoa\").version\nexcept Exception:\n # Local copy or not installed with setuptools.\n # Disable minimum version checks on downstream libraries.\n __version__ = \"999\"\n\n_RE_OPTION_MATCH = re.compile(r\"^(\\w+)\\W(\\w+)$\").match\n\n#: Specifications of configuration options\nCONFIG_SPECS = \"\"\"\n[cf] # cf module\ncache=boolean(default=True) # use the :mod:`~xoa.cf` in memory and file caches\n\n[plot] # plot parameters\ncmapdiv = string(default=\"cmo.balance\") # defaut diverging colormap\ncmappos = string(default=\"cmo.amp\") # default positive colormap\ncmapneg = string(default=\"cmo.tempo_r\") # default negative colormap\ncmapcyc = string(default=\"cmo.phase\") # default cyclic colormap\n\n\"\"\"\n\n#: Default xoa user configuration file\nDEFAULT_USER_CONFIG_FILE = os.path.join(\n appdirs.user_config_dir(\"xoa\"), \"xoa.cfg\"\n)\n\n# Directory of sample files\n_SAMPLE_DIR = os.path.join(os.path.dirname(__file__), '_samples')\n\n_PACKAGES = [\n \"appdirs\",\n \"cartopy\",\n \"cmocean\",\n \"configobj\",\n \"matplotlib\",\n \"numpy\",\n \"pandas\",\n \"scipy\",\n \"xarray\",\n \"xesmf\"\n ]\n\n\nclass XoaError(Exception):\n pass\n\n\nclass XoaConfigError(XoaError):\n pass\n\n\nclass XoaWarning(UserWarning):\n pass\n\n\ndef xoa_warn(message, stacklevel=2):\n \"\"\"Issue a :class:`XoaWarning` warning\n\n Example\n -------\n .. ipython:: python\n :okwarning:\n\n @suppress\n from xoa import xoa_warn\n xoa_warn('Be careful!')\n \"\"\"\n warnings.warn(message, XoaWarning, stacklevel=stacklevel)\n\n\ndef _get_cache_():\n from . import __init__\n if not hasattr(__init__, \"_XOA_CACHE\"):\n __init__._XOA_CACHE = {}\n return __init__._XOA_CACHE\n\n\ndef load_options(cfgfile=None):\n \"\"\"Load specified options\n\n Parameters\n ----------\n cfgfile: file, list(str), dict\n\n Example\n -------\n .. ipython:: python\n\n @suppress\n from xoa import load_options\n # Dict\n load_options({'plot': {'cmappos': 'mycmap'}})\n\n # Lines\n optlines = \"[plot]\\\\n cmappos=mycmap\".split('\\\\n')\n load_options(optlines)\n \"\"\"\n _get_cache_()\n xoa_cache = _get_cache_()\n\n if \"cfgspecs\" not in xoa_cache:\n xoa_cache[\"cfgspecs\"] = configobj.ConfigObj(\n CONFIG_SPECS.split(\"\\n\"),\n list_values=False,\n interpolation=False,\n raise_errors=True,\n file_error=True,\n )\n if \"options\" not in xoa_cache:\n xoa_cache[\"options\"] = configobj.ConfigObj(\n (\n DEFAULT_USER_CONFIG_FILE\n if os.path.exists(DEFAULT_USER_CONFIG_FILE)\n else None\n ),\n configspec=xoa_cache[\"cfgspecs\"],\n file_error=False,\n raise_errors=True,\n list_values=True,\n )\n if cfgfile:\n xoa_cache[\"options\"].merge(\n configobj.ConfigObj(\n cfgfile, file_error=True, raise_errors=True, list_values=True\n )\n )\n xoa_cache[\"options\"].validate(validate.Validator(), copy=True)\n\n\ndef _get_options_():\n xoa_cache = _get_cache_()\n if \"options\" not in xoa_cache:\n load_options()\n return xoa_cache[\"options\"]\n\n\ndef get_option(section, option=None):\n \"\"\"Get a config option\n\n Example\n -------\n .. ipython:: python\n\n @suppress\n from xoa import get_option\n print(get_option('plot', 'cmapdiv'))\n print(get_option('plot.cmapdiv'))\n \"\"\"\n options = _get_options_()\n if option is None:\n m = _RE_OPTION_MATCH(section)\n if m:\n section, option = m.groups()\n else:\n raise XoaConfigError(\n \"You must provide an option name to get_option\"\n )\n try:\n value = options[section][option]\n except Exception:\n return XoaConfigError(f\"Invalid section/option: {section}/{option}\")\n return value\n\n\nclass set_options(object):\n \"\"\"Set configuration options\n\n Parameters\n ----------\n section: str, None\n **options: dict\n If a key is in the format \"<section>.<option>\", then the section\n is overwritten.\n\n\n Example\n -------\n .. ipython:: python\n\n @suppress\n from xoa import set_options, get_option\n\n # Classic: for the session\n set_options('plot', cmapdiv='cmo.balance', cmappos='cmo.amp')\n\n # With dict\n opts = {\"plot.cmapdiv\": \"cmo.balance\"}\n set_options(**opts)\n\n # Context: temporary\n with set_options('plot', cmapdiv='cmo.delta'):\n print('within context:', get_option('plot.cmapdiv'))\n print('after context:', get_option('plot.cmapdiv'))\n\n \"\"\"\n\n def __init__(self, section=None, **options):\n # Format before being ingested\n self.xoa_cache = _get_cache_()\n self.old_options = self.xoa_cache.get(\"options\")\n if \"options\" in self.xoa_cache:\n del self.xoa_cache[\"options\"]\n opts = {}\n for option, value in options.items():\n m = _RE_OPTION_MATCH(option)\n if m:\n sec, option = m.groups()\n else:\n if section is None:\n raise XoaConfigError(\n \"You must specify the section explicitly or through the option name\")\n sec = section\n opts.setdefault(sec, {})[option] = value\n\n # Ingest options\n load_options(opts)\n\n def __enter__(self):\n return self.xoa_cache[\"options\"]\n\n def __exit__(self, type, value, traceback):\n if self.old_options:\n self.xoa_cache[\"options\"] = self.old_options\n else:\n del self.xoa_cache[\"options\"]\n\n\ndef set_option(option, value):\n \"\"\"Set a single option using the flat format, i.e ``section.option``\n\n Parameters\n ----------\n option: str\n Option name in the ``section.option`` format\n value:\n Value to set\n\n Example\n -------\n .. ipython:: python\n\n @suppress\n from xoa import set_option\n set_option('plot.cmapdiv', 'cmo.balance');\n \"\"\"\n return set_options(None, **{option: value})\n\n\ndef reset_options():\n \"\"\"Restore options to their default values in the current session\n\n Example\n -------\n .. ipython:: python\n\n @suppress\n from xoa import get_option, set_options, reset_options\n print(get_option('plot.cmapdiv'))\n set_options('plot', cmapdiv='mycmap')\n print(get_option('plot.cmapdiv'))\n reset_options()\n print(get_option('plot.cmapdiv'))\n \"\"\"\n xoa_cache = _get_cache_()\n del xoa_cache['options']\n\n\ndef show_options(specs=False):\n \"\"\"Print current xoa configuration\n\n Parameters\n ----------\n specs: bool\n Print option specifications instead\n\n Example\n -------\n .. ipython:: python\n\n @suppress\n from xoa import show_options\n show_options()\n show_options(specs=True)\n \"\"\"\n if specs:\n print(CONFIG_SPECS.strip(\"\\n\"))\n else:\n print(\"\\n\".join(_get_options_().write())\n .strip(\"\\n\").replace('#', ' #'))\n\n\ndef _parse_requirements_(reqfile):\n re_match_specs_match = re.compile(r\"^(\\w+)(\\W+.+)?$\").match\n reqs = {}\n with open(reqfile) as f:\n for line in f:\n line = line.strip().strip(\"\\n\")\n if line and not line.startswith(\"#\"):\n m = re_match_specs_match(line)\n if m:\n reqs[m.group(1)] = m.group(2)\n return reqs\n\n\ndef show_versions():\n \"\"\"Print the versions of xoa and of some dependencies\n\n Example\n -------\n .. ipython:: python\n :okexcept:\n\n @suppress\n from xoa import show_versions\n show_versions()\n \"\"\"\n print(\"- python:\", platform.python_version())\n print(\"- xoa:\", __version__)\n for package in _PACKAGES:\n try:\n version = pkg_resources.get_distribution(package).version\n except pkg_resources.DistributionNotFound:\n version = \"NOT INSTALLED or UKNOWN\"\n print(f\"- {package}: {version}\")\n\n\ndef show_paths():\n \"\"\"Print some xoa paths\n\n Example\n -------\n .. ipython:: python\n :okexcept:\n\n @suppress\n from xoa import show_paths\n show_paths()\n \"\"\"\n print(\"- xoa library dir:\", os.path.dirname(__file__))\n from . import cf\n asterix = False\n for label, path in [(\"user config file\", DEFAULT_USER_CONFIG_FILE),\n (\"user CF specs file\", cf.USER_CF_FILE),\n (\"user CF cache file\", cf.USER_CF_CACHE_FILE)]:\n if not os.path.exists(path):\n asterix = True\n path = path + \" [*]\"\n print(\"-\", label+\":\", path)\n print(\"- data samples:\", \" \".join(get_data_sample()))\n if asterix:\n print(\"*: file not present\")\n\n\ndef show_info(opt_specs=True):\n \"\"\"Print xoa related info\n\n Example\n -------\n .. ipython:: python\n :okexcept:\n\n @suppress\n from xoa import show_info\n show_info()\n \"\"\"\n print(\"# VERSIONS\")\n show_versions()\n print(\"\\n# FILES AND DIRECTORIES\")\n show_paths()\n print(\"\\n# OPTIONS\")\n show_options(specs=opt_specs)\n\n\ndef get_data_sample(filename=None):\n \"\"\"Get the absolute path to a sample file\n\n Parameters\n ----------\n filename: str, None\n Name of the sample. If ommited, a list of available samples\n name is returned.\n\n Returns\n -------\n str OR list(str)\n\n Example\n -------\n .. .ipython:: python\n\n @suppress\n from xoa import get_data_sample\n get_data_sample(\"croco.south-africa.surf.nc\")\n get_data_sample()\n\n See also\n --------\n show_data_samples\n open_data_sample\n \"\"\"\n if not os.path.exists(_SAMPLE_DIR):\n filenames = []\n else:\n filenames = os.listdir(_SAMPLE_DIR)\n if filename is None:\n return filenames\n if filename not in filenames:\n raise XoaError(\"Invalid data sample: \"+filename)\n return os.path.join(_SAMPLE_DIR, filename)\n\n\ndef open_data_sample(filename, **kwargs):\n \"\"\"Open a data sample with :func:`xarray.open_dataset` or :func:`pandas.read_csv`\n\n A shortcut to::\n\n xr.open_dataset(get_data_sample(filename))\n\n Parameters\n ----------\n filename: str\n File name of the sample\n\n Returns\n -------\n xarray.Dataset, pandas.DataFrame\n\n Example\n -------\n .. .ipython:: python\n\n @suppress\n from xoa import open_data_sample\n open_data_sample(\"croco.south-africa.nc\")\n\n\n See also\n --------\n get_data_sample\n show_data_samples\n \"\"\"\n fname = get_data_sample(filename)\n if fname.endswith(\"nc\"):\n import xarray as xr\n return xr.open_dataset(fname, **kwargs)\n import pandas as pd\n return pd.read_csv(fname, **kwargs)\n\n\ndef show_data_samples():\n \"\"\"Print the list of data samples\n\n Example\n -------\n .. ipython:: python\n\n @suppress\n from xoa import show_data_samples\n show_data_samples()\n\n See also\n --------\n get_data_samples\n open_data_sample\n \"\"\"\n print(' '.join(get_data_sample()))\n\n\ndef register_accessors(xoa=True, xcf=False, decode_sigma=False):\n \"\"\"Register xarray accessors\n\n Parameters\n ----------\n xoa: bool, str\n Register the main accessors with\n :func:`~xoa.cf.register_xoa_accessors`.\n xcf: bool, str\n Register the :mod:`xoa.cf` module accessors with\n :func:`~xoa.cf.register_cf_accessors`.\n decode_sigma: bool, str\n Register the :mod:`xoa.sigma` module accessor with\n :func:`~xoa.cf.register_sigma_accessor`.\n\n See also\n --------\n xoa.accessors\n \"\"\"\n if xoa:\n from .accessors import register_xoa_accessors\n kw = {\"name\": xoa} if isinstance(xoa, str) else {}\n register_xoa_accessors(**kw)\n if xcf:\n from .accessors import register_cf_accessors\n kw = {\"name\": xcf} if isinstance(xcf, str) else {}\n register_cf_accessors(**kw)\n if decode_sigma:\n from .accessors import register_sigma_accessor\n kw = {\"name\": decode_sigma} if isinstance(decode_sigma, str) else {}\n register_sigma_accessor(**kw)\n",
"# -*- coding: utf-8 -*-\n\"\"\"\nTest the :mod:`xoa.coords` module\n\"\"\"\n\nimport pytest\nimport numpy as np\nimport xarray as xr\n\nimport xoa\nfrom xoa import coords\n\n\[email protected](\n \"inshape,indims,tdims,mode,outshape,outdims\",\n [\n ((1, 2), ('y', 'x'), (\"x\", \"y\"), \"classic\",\n (2, 1), (\"x\", \"y\")),\n ((3, 2), ('y', 'x'), (\"t\", \"y\"), \"insert\",\n (2, 1, 3), (\"x\", \"t\", \"y\")),\n ((3, 2), ('y', 'x'), (\"x\", \"t\", \"y\"), \"compat\",\n (2, 3), (\"x\", \"y\")),\n ((3, 4, 2), ('y', 't', 'x'), (Ellipsis, \"x\", \"e\", \"y\"), \"compat\",\n (4, 2, 3), (\"t\", \"x\", \"y\")),\n ]\n)\ndef test_coords_transpose(inshape, indims, tdims, mode, outshape, outdims):\n da = xr.DataArray(np.ones(inshape), dims=indims)\n dao = coords.transpose(da, tdims, mode)\n assert dao.dims == outdims\n assert dao.shape == outshape\n\n\ndef test_coords_is_lon():\n\n x = xr.DataArray([5], dims=\"lon\", name=\"lon\")\n y = xr.DataArray([5], dims=\"lat\")\n temp = xr.DataArray(np.ones((1, 1)), dims=('lat', 'lon'), coords={'lon': x, 'lat': y})\n\n assert coords.is_lon(x)\n assert coords.is_lon(temp.lon)\n assert not coords.is_lon(temp.lat)\n\n\ndef test_coords_get_depth_from_variable():\n\n da = xr.DataArray(\n np.ones((2, 3)),\n dims=(\"depth\", \"lon\"),\n coords={\"depth\": (\"depth\", [0, 1]), \"lon\": [1, 2, 3]})\n depth = coords.get_depth(da)\n assert depth is not None\n np.testing.assert_allclose(depth.values, [0, 1])\n\n\ndef test_coords_get_depth_from_sigma():\n\n ds = xoa.open_data_sample(\"croco.south-africa.meridional.nc\")\n depth = coords.get_depth(ds)\n assert depth is not None\n assert depth.name == \"depth\"\n\n\ndef test_coords_get_depth_from_dz():\n\n ds = xoa.open_data_sample(\"hycom.gdp.h.nc\")\n ds = ds.rename(h=\"dz\")\n depth = coords.get_depth(ds)\n assert depth is not None\n assert depth.name == \"depth\"\n",
"# -*- coding: utf-8 -*-\n\"\"\"\nTest the :mod:`xoa.regrid` module\n\"\"\"\n\nimport numpy as np\nimport xarray as xr\nimport pytest\n\nfrom xoa import regrid\nfrom test_interp import get_grid2locs_coords, vfunc, get_interp1d_data\n\n\ndef test_regrid_regrid1d():\n\n # Get some data\n xxi, yyi, vari, xxo, yyo = get_interp1d_data()\n\n # Some inits\n nz1 = xxo.shape[1]\n nx, nz0 = xxi.shape\n nt = 2\n dep0 = xr.DataArray(yyi[0], dims='nz', name='nz')\n dep1 = xr.DataArray(yyo[0], dims='nk', name='nk')\n lon = xr.DataArray(xxi[:, 0], dims='lon')\n time = xr.DataArray(np.arange(nt, dtype='d'), dims='time')\n\n # data:3d, coord_in:1d, coord_out:1d\n da_in = xr.DataArray(\n np.resize(vari, (nt, nx, nz0)),\n name=\"banana\",\n dims=('time', 'lon', 'nz'),\n coords=(time, lon, dep0),\n attrs={'long_name': 'Big banana'})\n da_out = regrid.regrid1d(da_in, dep1, method=\"linear\")\n assert da_out.dims == (\"time\", \"lon\", \"nk\")\n assert da_out.shape == (nt, nx, nz1)\n assert not np.isnan(da_out).all()\n assert da_out.min() >= da_in.min()\n assert da_out.max() <= da_in.max()\n\n # data: 3d, coord_in: 2d, coord_out: 2d\n depth_in = xr.DataArray(yyi, dims=(\"lon\", \"nz\"),)\n depth_out = xr.DataArray(\n yyo, dims=(\"lon\", \"nk\"),\n attrs={'standard_name': 'ocean_layer_depth'})\n del da_in[\"nz\"]\n da_in = da_in.assign_coords(\n {\"time\": time, \"lon\": lon, \"depth\": depth_in})\n da_out = regrid.regrid1d(da_in, depth_out, method=\"linear\")\n assert da_out.dims == ('time', \"lon\", \"nk\")\n assert \"depth\" in da_out.coords\n assert not np.isnan(da_out).all()\n\n # same but transposed\n da_in = da_in.transpose(\"time\", \"nz\", \"lon\")\n da_out = regrid.regrid1d(da_in, depth_out, method=\"linear\")\n assert da_out.dims == ('time', \"nk\", \"lon\")\n assert not np.isnan(da_out).all()\n\n\[email protected](\n \"mode,expected\", [\n [\"no\", [np.nan, 1, np.nan]],\n [\"bottom\", [1, 1, np.nan]],\n [\"below\", [1, 1, np.nan]],\n [-1, [1, 1, np.nan]],\n ['top', [np.nan, 1, 1]],\n ['both', [1, 1, 1]],\n ]\n )\ndef test_regrid_extrap1d(mode, expected):\n nz, ny, nx = 4, 3, 5\n zi = np.linspace(3, 10, nz)\n zi = xr.DataArray(np.arange(nz), dims=\"z\")\n vi = xr.DataArray(np.ones((nz, ny, nx)), dims=('z', 'y', 'x'), coords={\"z\": zi})\n vi[:, 0] = np.nan\n vi[:, -1] = np.nan\n vi.attrs[\"long_name\"] = \"Long name\"\n vi.name = \"toto\"\n vo = regrid.extrap1d(vi, \"y\", mode)\n np.testing.assert_allclose(vo.values[0, :, 0], expected)\n assert vo.name == vi.name\n assert vo.attrs == vi.attrs\n assert 'z' in vo.coords\n\n\ndef test_regrid_grid2loc():\n\n np.random.seed(0)\n\n # Multi-dimensional generic coordinates\n nex = 4\n nexz = 2\n nxi = 7\n nyi = 6\n nzi = 5\n nti = 4\n no = 10\n xxi, yyi, zzi, tti, xo, yo, to, zo = get_grid2locs_coords(\n nex=nex, nexz=nexz, nxi=nxi, nyi=nyi, nzi=nzi, nti=nti, no=no)\n ttidt = tti.astype(\"m8[us]\") + np.datetime64(\"1950-01-01\")\n todt = to.astype(\"m8[us]\") + np.datetime64(\"1950-01-01\")\n todt = xr.DataArray(todt, dims='time')\n xo = xr.DataArray(xo, dims=\"time\")\n yo = xr.DataArray(yo, dims=\"time\")\n zo = xr.DataArray(zo, dims=\"time\")\n loc = xr.Dataset(\n coords={\"time\": todt, \"depth\": zo, \"lat\": yo, \"lon\": xo})\n\n # Pure 1D axes\n xi = xr.DataArray(xxi[0, 0, 0, :], dims='lon')\n yi = xr.DataArray(yyi[0, 0, :, 0], dims='lat')\n zi = xr.DataArray(zzi[0, 0, :, 0, 0], dims='depth')\n ti = xr.DataArray(ttidt[:, 0, 0, 0], dims='time')\n mi = xr.DataArray(np.arange(nex), dims='member')\n vi = vfunc(tti, zzi, yyi, xxi)\n vi = xr.DataArray(\n np.resize(vi, (nex, )+vi.shape[1:]),\n dims=('member', 'time', 'depth', 'lat', 'lon'),\n coords={\"member\": mi, \"time\": ti, \"depth\": zi, \"lat\": yi, \"lon\": xi},\n attrs={'long_name': \"Long name\"})\n vo_truth = np.array(vfunc(to, zo.values, yo.values, xo.values))\n vo_interp = regrid.grid2loc(vi, loc)\n assert vo_interp.shape == (nex, no)\n assert vo_interp.dims == (\"member\", \"time\")\n assert \"time\" in vo_interp.coords\n assert \"lon\" in vo_interp.coords\n assert \"member\" in vo_interp.coords\n vo_truth[np.isnan(vo_interp[0].values)] = np.nan\n np.testing.assert_almost_equal(vo_interp[0], vo_truth)\n assert \"long_name\" in vo_interp.attrs\n",
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nGeographic utilities\n\"\"\"\n# Copyright 2020-2021 Shom\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\nimport numba\n\nfrom . import coords as xcoords\n\n\n#: Earth radius in meters\nEARTH_RADIUS = 6371e3\n\n\[email protected]\ndef _haversine_(lon0, lat0, lon1, lat1):\n \"\"\"Haversine distance between two points on a **unit sphere**\n\n Parameters\n ----------\n lon0: float, array_like\n Longitude of the first point(s)\n lat0: float, array_like\n Latitude of the first point(s)\n lon1: float, array_like\n Longitude of the second point(s)\n lat1: float, array_like\n Latitude of the second point(s)\n\n Return\n ------\n float, array_like\n Distance(s)\n \"\"\"\n deg2rad = math.pi / 180.\n dist = math.sin(deg2rad*(lat0-lat1)*0.5)**2\n dist += (math.cos(deg2rad*lat0) * math.cos(deg2rad*lat1) *\n math.sin(deg2rad*(lon0-lon1)*0.5)**2)\n dist = 2. * math.asin(math.sqrt(dist))\n return dist\n\n\ndef haversine(lon0, lat0, lon1, lat1, radius=EARTH_RADIUS):\n \"\"\"Haversine distance between two points\n\n Parameters\n ----------\n lon0: float, array_like\n Longitude of the first point(s)\n lat0: float, array_like\n Latitude of the first point(s)\n lon1: float, array_like\n Longitude of the second point(s)\n lat1: float, array_like\n Latitude of the second point(s)\n radius: float\n Radius of the sphere which defaults to the earth radius\n\n Return\n ------\n float, array_like\n Distance(s)\n \"\"\"\n return _haversine_(\n np.double(lon0), np.double(lat0),\n np.double(lon1), np.double(lat1)) * radius\n\n\ndef bearing(lon0, lat0, lon1, lat1):\n \"\"\"Compute the bearing angle (forward azimuth)\n\n Parameters\n ----------\n lon0: float, array_like\n Longitude of the first point(s)\n lat0: float, array_like\n Latitude of the first point(s)\n lon1: float, array_like\n Longitude of the second point(s)\n lat1: float, array_like\n Latitude of the second point(s)\n\n Return\n ------\n float, array_like\n Angle(s)\n \"\"\"\n return _bearing_(\n np.double(lon0), np.double(lat0), np.double(lon1), np.double(lat1))\n\n\[email protected]\ndef _bearing_(lon0, lat0, lon1, lat1):\n deg2rad = math.pi / 180.\n a = math.arctan2(\n math.cos(deg2rad*lat0)*math.sin(deg2rad*lat1) -\n math.sin(deg2rad*lat0)*math.cos(deg2rad*lat1)*math.cos(deg2rad*(lon1-lon0)),\n math.sin(deg2rad*(lon1-lon0))*math.cos(deg2rad*lat1))\n return a * 180 / math.pi\n\n\ndef get_extent(extent, margin=0, square=False):\n \"\"\"Compute the geographic extent in degrees\n\n Parameters\n ----------\n extent: xarray.DataArray, xarray.Dataset, dict, tuple, list\n Either:\n\n - An array or dataset with longitude and latitude coordinates.\n - A dict with ``lon`` and ``lat`` keys: ``dict(lon=..., lat=...)``\n - A two-element tuple of longitudes and latitudes: ``(lon, lat)``\n - A extent list: ``[xmin, xmax, ymin, ymax]``.\n margin: float\n A relative fraction of the width and height that is used to set margins.\n For instance, a value of ``-0.1`` shrinks the box of 10% on each side.\n square: bool\n Force the box to be square in degrees.\n\n Return\n ------\n list\n ``[xmin, xmax, ymin, ymax]``\n\n Example\n -------\n\n .. ipython:: python\n\n @suppress\n from xoa.geo import get_extent\n @suppress\n import numpy as np\n get_extent([10., 20., 10., 20.], margin=0.1)\n get_extent({\"lon\": np.linspace(10, 20, 5), \"lat\": np.linspace(10, 20, 5)}, square=True)\n get_extent((np.linspace(10, 20, 5), np.linspace(10, 20, 5)), margin=-.1, square=True)\n\n \"\"\"\n # Get min and max\n if hasattr(extent, \"coords\"):\n lon = xcoords.get_lon(extent)\n lat = xcoords.get_lat(extent)\n extent = (lon, lat)\n elif isinstance(extent, dict):\n extent = extent['lon'], extent['lat']\n if isinstance(extent, (list, np.ndarray)):\n xmin, xmax, ymin, ymax = extent\n else: # tuple\n lon, lat = extent\n xmin = float(np.min(lon))\n xmax = float(np.max(lon))\n ymin = float(np.min(lat))\n ymax = float(np.max(lat))\n\n # Scale\n if square or margin:\n dx = xmax - xmin\n dy = ymax - ymin\n x0 = 0.5 * (xmin+xmax)\n y0 = 0.5 * (ymin+ymax)\n if square:\n aspect = dx * math.cos(y0*math.pi/180) / dy\n if aspect > 1:\n dy *= aspect\n else:\n dx /= aspect\n xmargin = margin * dx\n ymargin = margin * dy\n xmin = x0 - 0.5 * dx - xmargin\n xmax = x0 + 0.5 * dx + xmargin\n ymin = y0 - 0.5 * dy - ymargin\n ymax = y0 + 0.5 * dy + ymargin\n\n return [xmin, xmax, ymin, ymax]\n"
] | [
[
"pandas.read_csv"
],
[
"numpy.ones",
"numpy.testing.assert_allclose"
],
[
"numpy.resize",
"numpy.random.seed",
"numpy.linspace",
"numpy.isnan",
"numpy.arange",
"numpy.ones",
"numpy.datetime64",
"numpy.testing.assert_almost_equal",
"numpy.testing.assert_allclose"
],
[
"numpy.max",
"numpy.double",
"numpy.min"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
fabianp/nipy | [
"40e89f3ca7f34df05631623807993026134e6de3"
] | [
"nipy/labs/spatial_models/hroi.py"
] | [
"# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-\n# vi: set ft=python sts=4 ts=4 sw=4 et:\n\"\"\"\nThis module contains the specification of 'hierarchical ROI' object,\nWhich is used in spatial models of the library such as structural analysis\n\nThe connection with other classes is not completely satisfactory at the moment:\nthere should be some intermediate classes between 'Fields' and 'hroi'\n\nAuthor : Bertrand Thirion, 2009-2011\n Virgile Fritsch <[email protected]>\n\n\"\"\"\n\nimport numpy as np\n\nfrom nipy.algorithms.graph.graph import WeightedGraph\nfrom nipy.algorithms.graph.forest import Forest\nfrom nipy.algorithms.graph.field import field_from_coo_matrix_and_data\nfrom .mroi import SubDomains\n\nNINF = - np.inf\n\n\ndef hroi_agglomeration(input_hroi, criterion='size', smin=0):\n \"\"\"Performs an agglomeration then a selection of regions\n so that a certain size or volume criterion is satisfied.\n\n Parameters\n ----------\n input_hroi: HierarchicalROI instance\n The input hROI\n criterion: str, optional\n To be chosen among 'size' or 'volume'\n smin: float, optional\n The applied criterion\n\n Returns\n -------\n output_hroi: HierarchicalROI instance\n \"\"\"\n if criterion not in ['size', 'volume']:\n return ValueError('unknown criterion')\n output_hroi = input_hroi.copy()\n k = 2 * output_hroi.k\n if criterion == 'size':\n value = output_hroi.get_size()\n if criterion == 'volume':\n value = output_hroi.get_volume()\n\n # iteratively agglomerate regions that are too small\n while k > output_hroi.k:\n k = output_hroi.k\n # regions agglomeration\n output_hroi.merge_ascending(output_hroi.get_id()[value <= smin])\n # suppress parents nodes having only one child\n output_hroi.merge_descending()\n # early stopping 1\n if output_hroi.k == 0:\n break\n # early stopping 2\n if criterion == 'size':\n value = output_hroi.get_size()\n if criterion == 'volume':\n value = output_hroi.get_volume()\n if value.max() < smin:\n break\n\n # finally remove those regions for which the criterion cannot be matched\n output_hroi.select_roi(output_hroi.get_id()[value > smin])\n return output_hroi\n\n\ndef HROI_as_discrete_domain_blobs(domain, data, threshold=NINF, smin=0,\n criterion='size'):\n \"\"\"Instantiate an HierarchicalROI as the blob decomposition\n of data in a certain domain.\n\n Parameters\n ----------\n domain : discrete_domain.StructuredDomain instance,\n Definition of the spatial context.\n data : array of shape (domain.size)\n The corresponding data field.\n threshold : float, optional\n Thresholding level.\n criterion : string, optional\n To be chosen among 'size' or 'volume'.\n smin: float, optional\n A threshold on the criterion.\n\n Returns\n -------\n nroi: HierachicalROI instance with a `signal` feature.\n\n \"\"\"\n if threshold > data.max():\n # return an empty HROI structure\n label = - np.ones(data.shape)\n parents = np.array([])\n return HierarchicalROI(domain, label, parents)\n\n # check size\n df = field_from_coo_matrix_and_data(domain.topology, data)\n idx, parents, label = df.threshold_bifurcations(th=threshold)\n nroi = HierarchicalROI(domain, label, parents)\n # create a signal feature\n data = np.ravel(data)\n signal = [data[nroi.select_id(id, roi=False)] for id in nroi.get_id()]\n nroi.set_feature('signal', signal)\n # agglomerate regions in order to compact the structure if necessary\n nroi = hroi_agglomeration(nroi, criterion=criterion, smin=smin)\n return nroi\n\n\ndef HROI_from_watershed(domain, data, threshold=NINF):\n \"\"\"Instantiate an HierarchicalROI as the watershed of a certain dataset\n\n Parameters\n ----------\n domain: discrete_domain.StructuredDomain instance\n Definition of the spatial context.\n data: array of shape (domain.size)\n The corresponding data field.\n threshold: float, optional\n Thresholding level.\n\n Returns\n -------\n nroi : ``HierarchichalROI`` instance\n The HierachicalROI instance with a ``seed`` feature.\n \"\"\"\n if threshold > data.max():\n # return an empty HROI structure\n label = - np.ones(data.shape)\n parents = np.array([])\n return HierarchicalROI(domain, label, parents)\n\n df = field_from_coo_matrix_and_data(domain.topology, data)\n idx, label = df.custom_watershed(0, threshold)\n parents = np.arange(idx.size).astype(int)\n nroi = HierarchicalROI(domain, label, parents)\n\n nroi.set_roi_feature('seed', idx)\n return nroi\n\n\n########################################################################\n# Hierarchical ROI\n########################################################################\nclass HierarchicalROI(SubDomains):\n \"\"\"Class that handles hierarchical ROIs\n\n Parameters\n ----------\n k : int\n Number of ROI in the SubDomains object\n label : array of shape (domain.size), dtype=np.int\n An array use to define which voxel belongs to which ROI.\n The label values greater than -1 correspond to subregions\n labelling. The labels are recomputed so as to be consecutive\n integers.\n The labels should not be accessed outside this class. One has to\n use the API mapping methods instead.\n features : dict {str: list of object, length=self.k}\n Describe the voxels features, grouped by ROI\n roi_features : dict {str: array-like, shape=(self.k, roi_feature_dim)\n Describe the ROI features. A special feature, `id`, is read-only and\n is used to give an unique identifier for region, which is persistent\n through the MROI objects manipulations. On should access the different\n ROI's features using ids.\n parents : np.ndarray, shape(self.k)\n self.parents[i] is the index of the parent of the i-th ROI.\n\n TODO: have the parents as a list of id rather than a list of indices.\n \"\"\"\n\n def __init__(self, domain, label, parents, id=None):\n \"\"\"Building the HierarchicalROI\n \"\"\"\n SubDomains.__init__(self, domain, label, id=id)\n self.parents = np.ravel(parents).astype(np.int)\n\n ###\n # Getters for very basic features or roi features\n ###\n def get_volume(self, id=None, ignore_children=True):\n \"\"\"Get ROI volume\n\n Parameters\n ----------\n id: any hashable type, optional\n Id of the ROI from which we want to get the volume.\n Can be None (default) if we want all ROIs's volumes.\n ignore_children : bool, optional\n Specify if the volume of the node should include\n (ignore_children = False) or not the one of its children\n (ignore_children = True).\n\n Returns\n -------\n volume : float\n if an id is provided,\n or list of float\n if no id provided (default)\n \"\"\"\n if ignore_children:\n # volume of the children is not included\n volume = SubDomains.get_volume(self, id)\n else:\n # volume of the children is included\n if id is not None:\n volume = SubDomains.get_volume(self, id)\n desc = self.make_forest().get_descendents(\n self.select_id(id), exclude_self=True)\n # get children volume\n for k in desc:\n volume = volume + SubDomains.get_volume(\n self, self.get_id()[k])\n else:\n volume = []\n for id in self.get_id():\n roi_volume = SubDomains.get_volume(self, id)\n desc = self.make_forest().get_descendents(\n self.select_id(id), exclude_self=True)\n # get children volume\n for k in desc:\n roi_volume = roi_volume + SubDomains.get_volume(\n self, self.get_id()[k])\n volume.append(roi_volume)\n return volume\n\n def get_size(self, id=None, ignore_children=True):\n \"\"\"Get ROI size (counted in terms of voxels)\n\n Parameters\n ----------\n id: any hashable type, optional\n Id of the ROI from which we want to get the size.\n Can be None (default) if we want all ROIs's sizes.\n ignore_children: bool, optional\n Specify if the size of the node should include\n (ignore_children = False) or not the one of its children\n (ignore_children = True).\n\n Returns\n -------\n size: int\n if an id is provided,\n or list of int\n if no id provided (default)\n\n \"\"\"\n if ignore_children:\n # size of the children is not included\n size = SubDomains.get_size(self, id)\n else:\n # size of the children is included\n if id is not None:\n size = SubDomains.get_size(self, id)\n desc = self.make_forest().get_descendents(\n self.select_id(id), exclude_self=True)\n # get children size\n for k in desc:\n size = size + SubDomains.get_size(self, self.get_id()[k])\n else:\n size = []\n for id in self.get_id():\n roi_size = SubDomains.get_size(self, id)\n desc = self.make_forest().get_descendents(\n self.select_id(id), exclude_self=True)\n # get children size\n for k in desc:\n roi_size = roi_size + SubDomains.get_size(\n self, self.get_id()[k])\n size.append(roi_size)\n return size\n\n def select_roi(self, id_list):\n \"\"\"Returns an instance of HROI with only the subset of chosen ROIs.\n\n The hierarchy is set accordingly.\n\n Parameters\n ----------\n id_list: list of id (any hashable type)\n The id of the ROI to be kept in the structure.\n\n \"\"\"\n valid = np.asarray([int(i in id_list) for i in self.get_id()])\n if np.size(id_list) == 0:\n # handle the case of an empty selection\n new_parents = np.array([])\n self = HierarchicalROI(\n self.domain, -np.ones(self.label.size), np.array([]))\n else:\n # get new parents\n new_parents = Forest(self.k, self.parents).subforest(\n valid.astype(np.bool)).parents.astype(np.int)\n SubDomains.select_roi(self, id_list)\n self.parents = new_parents\n self.recompute_labels()\n\n def make_graph(self):\n \"\"\"Output an nipy graph structure to represent the ROI hierarchy.\n\n \"\"\"\n if self.k == 0:\n return None\n weights = np.ones(self.k)\n edges = (np.vstack((np.arange(self.k), self.parents))).T\n return WeightedGraph(self.k, edges, weights)\n\n def make_forest(self):\n \"\"\"Output an nipy forest structure to represent the ROI hierarchy.\n\n \"\"\"\n if self.k == 0:\n return None\n G = Forest(self.k, self.parents)\n return G\n\n def merge_ascending(self, id_list, pull_features=None):\n \"\"\"Remove the non-valid ROIs by including them in\n their parents when it exists.\n\n Parameters\n ----------\n id_list: list of id (any hashable type)\n The id of the ROI to be merged into their parents.\n Nodes that are their own parent are unmodified.\n pull_features: list of str\n List of the ROI features that will be pooled from the children\n when they are merged into their parents. Otherwise, the receiving\n parent would keep its own ROI feature.\n \"\"\"\n if pull_features is None:\n pull_features = []\n if self.k == 0:\n return\n id_list = [k for k in self.get_id() if k in id_list]\n\n # relabel maps old labels to new labels \n relabel = np.arange(self.k)\n\n # merge nodes, one at a time\n for c_id in id_list:\n # define alias for clearer indexing\n c_pos = self.select_id(c_id)\n p_pos = self.parents[c_pos]\n p_id = self.get_id()[p_pos]\n \n if p_pos != c_pos:\n # this will be used in many places\n mask_pos = np.ones(self.k, np.bool)\n mask_pos[c_pos] = False\n \n # set new parents\n self.parents = self.parents[mask_pos]\n self.parents[self.parents == c_pos] = p_pos\n self.parents[self.parents > c_pos] -= 1\n self.k -= 1\n\n # merge labels\n relabel[relabel == c_id] = p_id\n\n # compute new features\n for fid in self.features.keys():\n # replace feature\n # (without the API since self is in an inconsistent state)\n dj = self.get_feature(fid)\n dj[p_pos] = np.hstack((dj[self.select_id(c_id)], \n dj[self.select_id(p_id)]))\n del dj[c_pos]\n self.features[fid] = dj\n\n # compute new roi features\n for fid in self.roi_features.keys():\n dj = self.get_roi_feature(fid)\n if fid in pull_features:\n # modify only if `pull` requested\n dj[p_pos] = dj[c_pos]\n self.roi_features[fid] = dj[mask_pos]\n\n # update the labels \n self.label[self.label > -1] = relabel[self.label[self.label > - 1]]\n self.recompute_labels()\n\n def merge_descending(self, pull_features=None):\n \"\"\" Remove the items with only one son by including them in their son\n\n Parameters\n ----------\n methods indicates the way possible features are dealt with\n (not implemented yet)\n\n Caveat\n ------\n if roi_features have been defined, they will be removed\n \"\"\"\n if pull_features is None:\n pull_features = []\n\n if self.k == 0:\n return\n \n # relabel maps old labels to new labels \n relabel = np.arange(self.k)\n\n # merge nodes, one at a time\n id_list = self.get_id()[:: - 1]\n \n for p_id in id_list:\n p_pos = self.select_id(p_id)\n p_children = np.nonzero(self.parents == p_pos)[0]\n \n if p_pos in p_children:\n # remove current node from its children list\n p_children = p_children[p_children != p_pos]\n\n if p_children.size == 1:\n # merge node if it has only one child\n c_pos = p_children[0]\n c_id = self.get_id()[c_pos]\n mask_pos = np.ones(self.k, np.bool)\n mask_pos[p_pos] = False\n\n # set new parents\n self.parents[c_pos] = self.parents[p_pos]\n if self.parents[c_pos] == p_pos:\n self.parents[c_pos] = c_pos\n self.parents = self.parents[mask_pos]\n self.parents[self.parents > p_pos] -= 1\n # merge labels\n relabel[relabel == p_pos] = relabel[c_pos]\n self.k -= 1\n \n # compute new features\n for fid in self.features.keys():\n # replace feature\n # (without the API since self is in an inconsistent state)\n dj = self.get_feature(fid)\n dj[c_pos] = np.hstack((dj[self.select_id(c_id)], \n dj[self.select_id(p_id)]))\n del dj[p_pos]\n self.features[fid] = dj\n\n # compute new roi features\n for fid in self.roi_features.keys():\n dj = self.get_roi_feature(fid)\n if fid in pull_features:\n # modify only if `pull` requested\n dj[c_pos] = dj[p_pos]\n self.roi_features[fid] = dj[mask_pos]\n \n # update HROI structure\n self.label[self.label > -1] = relabel[self.label[self.label > - 1]]\n self.recompute_labels()\n\n def get_parents(self):\n \"\"\"Return the parent of each node in the hierarchy\n\n The parents are represented by their position in the nodes flat list.\n\n TODO:\n The purpose of this class API is not to rely on this order, so\n we should have self.parents as a list of ids instead of a list of\n positions\n \"\"\"\n return self.parents\n\n def get_leaves_id(self):\n \"\"\"Return the ids of the leaves.\n\n \"\"\"\n if self.k == 0:\n return np.array([])\n # locate the positions of the children of each node\n is_leaf_aux = [np.where(self.parents == k)[0] for k in range(self.k)]\n # select nodes that has no child (different from themselves)\n is_leaf = np.asarray(\n [(len(child) == 0) or (len(child) == 1 and child[0] == i)\n for i, child in enumerate(is_leaf_aux)])\n # finaly return ids\n return self.get_id()[is_leaf]\n\n def reduce_to_leaves(self):\n \"\"\"Create a new set of rois which are only the leaves of self.\n\n Modification of the structure is done in place. One way therefore\n want to work on a copy a of a given HROI oject.\n\n \"\"\"\n if self.k == 0:\n # handle the empy HROI case\n return HierarchicalROI(\n self.domain, -np.ones(self.domain.size), np.array([]))\n leaves_id = self.get_leaves_id()\n self.select_roi(leaves_id)\n\n def copy(self):\n \"\"\" Returns a copy of self.\n\n self.domain is not copied.\n\n \"\"\"\n cp = HierarchicalROI(\n self.domain, self.label.copy(), self.parents.copy(), self.get_id())\n # copy features\n for fid in self.features.keys():\n cp.set_feature(fid, self.get_feature(fid))\n # copy ROI features\n for fid in self.roi_features.keys():\n cp.set_roi_feature(fid, self.get_roi_feature(fid))\n return cp\n\n def representative_feature(self, fid, method='mean', id=None,\n ignore_children=True, assess_quality=True):\n \"\"\"Compute a ROI representative of a given feature.\n\n Parameters\n ----------\n fid: str,\n Feature id\n method: str,\n Method used to compute a representative.\n Chosen among 'mean' (default), 'max', 'median', 'min',\n 'weighted mean'.\n id: any hashable type\n Id of the ROI from which we want to extract a representative feature.\n Can be None (default) if we want to get all ROIs's representatives.\n ignore_children: bool,\n Specify if the volume of the node should include\n (ignore_children = False) or not the one of its children\n (ignore_children = True).\n assess_quality: bool\n If True, a new roi feature is created, which represent the quality\n of the feature representative (the number of non-nan value for the\n feature over the ROI size).\n Default is False.\n\n \"\"\"\n rf = []\n eps = 1.e-15\n feature_quality = np.zeros(self.k)\n for i, k in enumerate(self.get_id()):\n f = self.get_feature(fid, k)\n p_pos = self.select_id(k)\n if not ignore_children:\n # also include the children features\n desc = np.nonzero(self.parents == p_pos)[0]\n if p_pos in desc:\n desc = desc[desc != p_pos]\n for c in desc:\n f = np.concatenate(\n (f, self.get_feature(fid, self.get_id()[c])))\n # NaN-resistant representative\n if f.ndim == 2:\n nan = np.isnan(f.sum(1))\n else:\n nan = np.isnan(f)\n # feature quality\n feature_quality[i] = (~nan).sum() / float(nan.size)\n # compute representative\n if method == \"mean\":\n rf.append(np.mean(f[~nan], 0))\n if method == \"weighted mean\":\n lvk = self.get_local_volume(k)\n if not ignore_children:\n # append weights for children's voxels\n for c in desc:\n lvk = np.concatenate(\n (lvk,\n self.get_local_volume(fid, self.select_id(c))))\n tmp = np.dot(lvk[~nan], f[~nan].reshape((-1, 1))) / \\\n np.maximum(eps, np.sum(lvk[~nan]))\n rf.append(tmp)\n if method == \"min\":\n rf.append(np.min(f[~nan]))\n if method == \"max\":\n rf.append(np.max(f[~nan]))\n if method == \"median\":\n rf.append(np.median(f[~nan], 0))\n if id is not None:\n summary_feature = rf[self.select_id(id)]\n else:\n summary_feature = rf\n\n if assess_quality:\n self.set_roi_feature('%s_quality' % fid, feature_quality)\n return np.array(summary_feature)\n\n\ndef make_hroi_from_subdomain(sub_domain, parents):\n \"\"\"Instantiate an HROi from a SubDomain instance and parents\n\n \"\"\"\n hroi = HierarchicalROI(sub_domain.domain, sub_domain.label, parents)\n # set features\n for fid in sub_domain.features.keys():\n hroi.set_feature(fid, sub_domain.get_feature(fid))\n # set ROI features\n for fid in sub_domain.roi_features.keys():\n hroi.set_roi_feature(fid, sub_domain.get_roi_feature(fid))\n return hroi\n"
] | [
[
"numpy.sum",
"numpy.nonzero",
"numpy.min",
"numpy.isnan",
"numpy.arange",
"numpy.median",
"numpy.ones",
"numpy.max",
"numpy.size",
"numpy.mean",
"numpy.ravel",
"numpy.array",
"numpy.zeros",
"numpy.where"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
lgraesser/MCER | [
"250aa6965064dbc73462eb5edb559bf9ce949b70"
] | [
"utils.py"
] | [
"import json\nimport logging\nimport matplotlib.pyplot as plt\nimport os\nimport tensorflow as tf\nfrom sklearn.utils import shuffle\n\nimport model\nimport train\n\nlogger = logging.getLogger('utils')\nlogger.setLevel(logging.INFO)\n\n\ndef get_data_path():\n '''Returns the path to the image and annotation data.\n Downloads the data if it doesn't exist.\n '''\n # Download caption annotation files\n annotation_folder = '/data/train_data/annotations/'\n if not os.path.exists(os.path.abspath('.') + annotation_folder):\n logger.info('Downloading captions file.')\n annotation_zip = tf.keras.utils.get_file('captions.zip',\n cache_subdir=os.path.abspath('./data/train_data'),\n origin = 'http://images.cocodataset.org/annotations/annotations_trainval2014.zip',\n extract = True)\n annotation_file_path = os.path.dirname(annotation_zip)+'/annotations/captions_train2014.json'\n os.remove(annotation_zip)\n else:\n annotation_file_path = os.path.abspath('.') + annotation_folder + 'captions_train2014.json'\n logger.info(f'Captions file already exists here {annotation_file_path}.')\n\n # Download image files\n image_folder = '/data/train_data/train2014/'\n if not os.path.exists(os.path.abspath('.') + image_folder):\n logger.info('Downloading image data. This may take a while.')\n image_zip = tf.keras.utils.get_file('train2014.zip',\n cache_subdir=os.path.abspath('./data/train_data'),\n origin = 'http://images.cocodataset.org/zips/train2014.zip',\n extract = True)\n image_file_path = os.path.dirname(image_zip) + image_folder\n os.remove(image_zip)\n else:\n image_file_path = os.path.abspath('.') + image_folder\n logger.info(f'Image data already exists here {image_file_path}.')\n\n return image_file_path, annotation_file_path\n\n\ndef get_caption_image_names(annotation_file_path, image_file_path, shuffle_data=True):\n '''Returns a shuffled list of the captions and the corresponding image names.'''\n\n # Read the json file\n with open(annotation_file_path, 'r') as f:\n annotations = json.load(f)\n logger.info('Loaded the annotations file.')\n\n # Store captions and image names in vectors\n all_captions = []\n all_img_name_vector = []\n\n for annot in annotations['annotations']:\n caption = '<start> ' + annot['caption'] + ' <end>'\n image_id = annot['image_id']\n full_coco_image_path = image_file_path + 'COCO_train2014_' + '%012d.jpg' % (image_id)\n\n all_img_name_vector.append(full_coco_image_path)\n all_captions.append(caption)\n\n # Shuffle captions and image_names together\n # Set a random state\n if shuffle_data:\n logger.info('Shuffling the data...')\n train_captions, img_name_vector = shuffle(all_captions,\n all_img_name_vector,\n random_state=1)\n else:\n train_captions = all_captions\n img_name_vector = all_img_name_vector\n\n return train_captions, img_name_vector\n\n\ndef get_top_k(train_captions, img_name_vector, num_examples):\n '''Selects the first k examples from the data.'''\n assert len(train_captions) == len(img_name_vector)\n original_cap_length = len(train_captions)\n if num_examples > original_cap_length:\n logger.warning(f'Desired num examples {num_examples} > actual number examples {original_cap_length}, using whole training set')\n num_examples = original_cap_length\n\n train_captions = train_captions[:num_examples]\n img_name_vector = img_name_vector[:num_examples]\n logger.info(f'Num train captions: {len(train_captions)}, num all captions: {original_cap_length}')\n\n return train_captions, img_name_vector\n\n\ndef calc_max_length(tensor):\n \"\"\"Find the maximum length of any tensor\"\"\"\n return max(len(t) for t in tensor)\n\n\ndef load_image(image_path):\n img = tf.io.read_file(image_path)\n img = tf.image.decode_jpeg(img, channels=3)\n img = tf.image.resize(img, (299, 299))\n img = tf.keras.applications.inception_v3.preprocess_input(img)\n return img, image_path\n\n\ndef plot_loss(loss_data):\n plt.plot(loss_plot)\n plt.xlabel('Epochs')\n plt.ylabel('Loss')\n plt.title('Loss Plot')\n plt.show()\n\n\ndef save_loss_plot(loss_data, figname, data_label):\n plt.figure(figsize=(10, 10))\n plt.plot(loss_data, label=data_label)\n plt.xlabel('Epochs')\n plt.ylabel('Loss')\n plt.title('Loss Plot')\n plt.legend(loc='upper left')\n plt.savefig(figname)\n plt.close()\n\n\ndef build_model(model_logdir, vocab_size):\n embedding_dim = 256\n units = 512\n # Shape of the vector extracted from InceptionV3 is (64, 2048)\n # These two variables represent that vector shape\n encoder = model.CNN_Encoder(embedding_dim)\n decoder = model.RNN_Decoder(embedding_dim, units, vocab_size)\n # get optim, and checkpoint manager\n optimizer = train.get_optimizer()\n loss_object = train.get_loss_object()\n ckpt_manager, ckpt = train.get_checkpoint_manager(encoder, decoder, optimizer, path=model_logdir)\n\n # Restore tokenizer\n with open(os.path.join(model_logdir, 'tokenizer.json')) as f:\n data = json.load(f)\n tokenizer = tf.keras.preprocessing.text.tokenizer_from_json(data)\n\n return encoder, decoder, tokenizer, ckpt_manager, ckpt\n"
] | [
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.title",
"matplotlib.pyplot.figure",
"sklearn.utils.shuffle",
"tensorflow.keras.preprocessing.text.tokenizer_from_json",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.ylabel",
"tensorflow.image.resize",
"matplotlib.pyplot.close",
"tensorflow.io.read_file",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"tensorflow.keras.applications.inception_v3.preprocess_input",
"tensorflow.image.decode_jpeg"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
imdone/tensorflow | [
"bb4d1ef3861c83627ee9586b85ac3070a7d38335",
"bb4d1ef3861c83627ee9586b85ac3070a7d38335",
"bb4d1ef3861c83627ee9586b85ac3070a7d38335",
"bb4d1ef3861c83627ee9586b85ac3070a7d38335",
"bb4d1ef3861c83627ee9586b85ac3070a7d38335",
"bb4d1ef3861c83627ee9586b85ac3070a7d38335",
"bb4d1ef3861c83627ee9586b85ac3070a7d38335",
"bb4d1ef3861c83627ee9586b85ac3070a7d38335",
"bb4d1ef3861c83627ee9586b85ac3070a7d38335",
"bb4d1ef3861c83627ee9586b85ac3070a7d38335",
"bb4d1ef3861c83627ee9586b85ac3070a7d38335",
"bb4d1ef3861c83627ee9586b85ac3070a7d38335"
] | [
"tensorflow/python/training/checkpointable_utils.py",
"tensorflow/contrib/batching/python/ops/batch_ops_test.py",
"tensorflow/python/data/kernel_tests/dataset_from_generator_op_test.py",
"tensorflow/python/client/timeline.py",
"tensorflow/contrib/autograph/converters/call_trees.py",
"tensorflow/python/ops/state_ops.py",
"tensorflow/contrib/recurrent/python/kernel_tests/recurrent_test.py",
"tensorflow/python/ops/summary_ops_v2.py",
"tensorflow/contrib/data/python/ops/resampling.py",
"tensorflow/contrib/graph_editor/edit.py",
"tensorflow/contrib/autograph/utils/context_managers.py",
"tensorflow/contrib/distributions/python/ops/bijectors/reshape.py"
] | [
"\"\"\"Utilities for saving/loading Checkpointable objects.\"\"\"\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# ==============================================================================\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport abc\nimport collections\nimport weakref\n\nfrom tensorflow.core.protobuf import checkpointable_object_graph_pb2\nfrom tensorflow.python import pywrap_tensorflow\nfrom tensorflow.python.client import session as session_lib\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors_impl\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import init_ops\nfrom tensorflow.python.ops import resource_variable_ops\nfrom tensorflow.python.ops import variable_scope\nfrom tensorflow.python.training import checkpointable as checkpointable_lib\nfrom tensorflow.python.training import optimizer as optimizer_lib\nfrom tensorflow.python.training import saver as saver_lib\nfrom tensorflow.python.util import deprecation\nfrom tensorflow.python.util.tf_export import tf_export\n\n\n_ESCAPE_CHAR = \".\" # For avoiding conflicts with user-specified names.\n\n# Keyword for identifying that the next bit of a checkpoint variable name is a\n# slot name. Checkpoint names for slot variables look like:\n#\n# <path to variable>/<_OPTIMIZER_SLOTS_NAME>/<path to optimizer>/<slot name>\n#\n# Where <path to variable> is a full path from the checkpoint root to the\n# variable being slotted for.\n_OPTIMIZER_SLOTS_NAME = _ESCAPE_CHAR + \"OPTIMIZER_SLOT\"\n# Keyword for separating the path to an object from the name of an\n# attribute in checkpoint names. Used like:\n# <path to variable>/<_OBJECT_ATTRIBUTES_NAME>/<name of attribute>\n_OBJECT_ATTRIBUTES_NAME = _ESCAPE_CHAR + \"ATTRIBUTES\"\n\n\nclass _CheckpointRestoreCoordinator(object):\n \"\"\"Holds the status of an object-based checkpoint load.\"\"\"\n\n def __init__(self, object_graph_proto, save_path, dtype_map=None):\n \"\"\"Specify the checkpoint being loaded.\n\n Args:\n object_graph_proto: The CheckpointableObjectGraph protocol buffer\n associated with this checkpoint.\n save_path: A string `Tensor`. The path to the checkpoint, as returned by\n `tf.train.latest_checkpoint`.\n dtype_map: When executing eagerly, specifies dtypes for creating slot\n variables. None when graph building.\n \"\"\"\n self.builder = saver_lib.BulkSaverBuilder()\n self.object_graph_proto = object_graph_proto\n self.restore_uid = ops.uid()\n # Maps from objects to lists of attributes which were in the checkpoint but\n # not loaded into any object, for error checking.\n self.unused_attributes = weakref.WeakKeyDictionary()\n # Dictionary mapping from an id in the protocol buffer flat array to\n # Checkpointable Python objects. This mapping may be deferred if a\n # checkpoint is restored before all dependencies have been tracked. Uses\n # weak references so that partial restorations don't create reference cycles\n # (as objects with deferred dependencies will generally have references to\n # this object).\n self.object_by_proto_id = weakref.WeakValueDictionary()\n # A set of all Python objects we've seen as dependencies, even if we didn't\n # use them (for example because of inconsistent references when\n # loading). Used to make status assertions fail when loading checkpoints\n # that don't quite match.\n self.all_python_objects = weakref.WeakSet()\n self.save_path = save_path\n self.dtype_map = dtype_map\n # When graph building, contains a list of ops to run to restore objects from\n # this checkpoint.\n self.restore_ops = []\n self.restore_ops_by_name = {}\n # A mapping from optimizer proto ids to lists of slot variables to be\n # restored when the optimizer is tracked. Only includes slot variables whose\n # regular variables have already been created, and only for optimizer\n # objects which have not yet been created/tracked.\n self.deferred_slot_restorations = {}\n # A mapping from variable proto ids to lists of slot variables to be\n # restored when the variable is created/tracked. These get shifted over to\n # deferred_slot_restorations if the optimizer hasn't been created when that\n # happens.\n self.slot_restorations = {}\n for node_index, node in enumerate(self.object_graph_proto.nodes):\n for slot_reference in node.slot_variables:\n # `node` refers to an `Optimizer`, since only these have slot variables.\n self.slot_restorations.setdefault(\n slot_reference.original_variable_node_id, []).append(\n checkpointable_lib._SlotVariableRestoration( # pylint: disable=protected-access\n optimizer_id=node_index,\n slot_variable_id=slot_reference.slot_variable_node_id,\n slot_name=slot_reference.slot_name))\n\n\n# TODO (allenl): If this ends up in a public API, consider adding LINT.IfChange id:3465\n# https://github.com/imdone/tensorflow/issues/3464\n# or consolidating the implementation with get_variable.\ndef _default_getter(name, shape, dtype, initializer=None,\n partition_info=None, **kwargs):\n \"\"\"A pared-down version of get_variable which does not reuse variables.\"\"\"\n dtype = dtypes.as_dtype(dtype)\n shape_object = tensor_shape.as_shape(shape)\n with ops.init_scope():\n if initializer is None:\n initializer, initializing_from_value = (\n variable_scope._get_default_variable_store()._get_default_initializer( # pylint: disable=protected-access\n name=name, shape=shape_object, dtype=dtype))\n else:\n initializing_from_value = not callable(initializer)\n # Same logic as get_variable\n variable_dtype = dtype.base_dtype\n if initializing_from_value:\n if shape is not None:\n raise ValueError(\"If initializer is a constant, do not specify shape.\")\n initial_value = initializer\n else:\n # Instantiate initializer if provided initializer is a type object.\n if isinstance(initializer, type(init_ops.Initializer)):\n initializer = initializer(dtype=dtype)\n def initial_value():\n return initializer(\n shape_object.as_list(), dtype=dtype, partition_info=partition_info)\n return resource_variable_ops.ResourceVariable(\n initial_value=initial_value,\n name=name,\n dtype=variable_dtype,\n **kwargs\n )\n\n\ndef add_variable(checkpointable, name, shape=None, dtype=dtypes.float32,\n initializer=None):\n \"\"\"Add a variable to a Checkpointable with no scope influence.\"\"\"\n return checkpointable._add_variable_with_custom_getter( # pylint: disable=protected-access\n name=name, shape=shape, dtype=dtype,\n initializer=initializer, getter=_default_getter)\n\n\ndef _breadth_first_checkpointable_traversal(root_checkpointable):\n \"\"\"Find shortest paths to all variables owned by dependencies of root.\"\"\"\n bfs_sorted = []\n to_visit = collections.deque([root_checkpointable])\n path_to_root = {root_checkpointable: ()}\n while to_visit:\n current_checkpointable = to_visit.popleft()\n current_checkpointable._maybe_initialize_checkpointable() # pylint: disable=protected-access\n bfs_sorted.append(current_checkpointable)\n for child_checkpointable in (\n current_checkpointable._checkpoint_dependencies): # pylint: disable=protected-access\n if child_checkpointable.ref not in path_to_root:\n path_to_root[child_checkpointable.ref] = (\n path_to_root[current_checkpointable] + (child_checkpointable,))\n to_visit.append(child_checkpointable.ref)\n return bfs_sorted, path_to_root\n\n\ndef _escape_local_name(name):\n # We need to support slashes in local names for compatibility, since this\n # naming scheme is being patched in to things like Layer.add_variable where\n # slashes were previously accepted. We also want to use slashes to indicate\n # edges traversed to reach the variable, so we escape forward slashes in\n # names.\n return (name.replace(_ESCAPE_CHAR, _ESCAPE_CHAR + _ESCAPE_CHAR)\n .replace(r\"/\", _ESCAPE_CHAR + \"S\"))\n\n\ndef _object_prefix_from_path(path_to_root):\n return \"/\".join(\n (_escape_local_name(checkpointable.name)\n for checkpointable in path_to_root))\n\n\ndef _slot_variable_naming_for_optimizer(optimizer_path):\n \"\"\"Make a function for naming slot variables in an optimizer.\"\"\"\n # Name slot variables:\n #\n # <variable name>/<_OPTIMIZER_SLOTS_NAME>/<optimizer path>/<slot name>\n #\n # where <variable name> is exactly the checkpoint name used for the original\n # variable, including the path from the checkpoint root and the local name in\n # the object which owns it. Note that we only save slot variables if the\n # variable it's slotting for is also being saved.\n\n optimizer_identifier = \"/%s/%s/\" % (_OPTIMIZER_SLOTS_NAME, optimizer_path)\n\n def _name_slot_variable(variable_path, slot_name):\n \"\"\"With an optimizer specified, name a slot variable.\"\"\"\n return (variable_path\n + optimizer_identifier\n + _escape_local_name(slot_name))\n\n return _name_slot_variable\n\n\ndef _serialize_slot_variables(checkpointable_objects, node_ids, object_names):\n \"\"\"Gather and name slot variables.\"\"\"\n non_slot_objects = list(checkpointable_objects)\n slot_variables = {}\n for checkpointable in non_slot_objects:\n if isinstance(checkpointable, optimizer_lib.Optimizer):\n naming_scheme = _slot_variable_naming_for_optimizer(\n optimizer_path=object_names[checkpointable])\n slot_names = checkpointable.get_slot_names()\n for slot_name in slot_names:\n for original_variable_node_id, original_variable in enumerate(\n non_slot_objects):\n try:\n slot_variable = checkpointable.get_slot(\n original_variable, slot_name)\n except AttributeError:\n slot_variable = None\n if slot_variable is None:\n continue\n slot_variable._maybe_initialize_checkpointable() # pylint: disable=protected-access\n if slot_variable._checkpoint_dependencies: # pylint: disable=protected-access\n # TODO (allenl): Gather dependencies of slot variables. id:3924\n # https://github.com/imdone/tensorflow/issues/3922\n raise NotImplementedError(\n \"Currently only variables with no dependencies can be saved as \"\n \"slot variables. File a feature request if this limitation \"\n \"bothers you.\")\n if slot_variable in node_ids:\n raise NotImplementedError(\n \"A slot variable was re-used as a dependency of a \"\n \"Checkpointable object. This is not currently allowed. File a \"\n \"feature request if this limitation bothers you.\")\n checkpoint_name = naming_scheme(\n variable_path=object_names[original_variable],\n slot_name=slot_name)\n object_names[slot_variable] = checkpoint_name\n slot_variable_node_id = len(checkpointable_objects)\n node_ids[slot_variable] = slot_variable_node_id\n checkpointable_objects.append(slot_variable)\n slot_variable_proto = (\n checkpointable_object_graph_pb2.CheckpointableObjectGraph\n .CheckpointableObject.SlotVariableReference(\n slot_name=slot_name,\n original_variable_node_id=original_variable_node_id,\n slot_variable_node_id=slot_variable_node_id))\n slot_variables.setdefault(checkpointable, []).append(\n slot_variable_proto)\n return slot_variables\n\n\ndef _serialize_checkpointables(\n checkpointable_objects, node_ids, object_names, slot_variables):\n \"\"\"Name non-slot `Checkpointable`s and add them to `object_graph_proto`.\"\"\"\n object_graph_proto = (\n checkpointable_object_graph_pb2.CheckpointableObjectGraph())\n named_saveables = {}\n\n for checkpoint_id, checkpointable in enumerate(checkpointable_objects):\n assert node_ids[checkpointable] == checkpoint_id\n object_proto = object_graph_proto.nodes.add()\n object_proto.slot_variables.extend(slot_variables.get(checkpointable, ()))\n object_name = object_names[checkpointable]\n for name, saveable_factory in (\n checkpointable._gather_saveables_for_checkpoint().items()): # pylint: disable=protected-access\n attribute = object_proto.attributes.add()\n attribute.name = name\n attribute.checkpoint_key = \"%s/%s/%s\" % (\n object_name, _OBJECT_ATTRIBUTES_NAME, _escape_local_name(name))\n if callable(saveable_factory):\n saveable = saveable_factory(name=attribute.checkpoint_key)\n else:\n saveable = saveable_factory\n # Figure out the name-based Saver's name for this variable.\n saver_dict = saver_lib.BaseSaverBuilder.OpListToDict(\n [saveable], convert_variable_to_tensor=False)\n attribute.full_name, = saver_dict.keys()\n named_saveables[attribute.checkpoint_key] = saveable\n\n for child in checkpointable._checkpoint_dependencies: # pylint: disable=protected-access\n child_proto = object_proto.children.add()\n child_proto.node_id = node_ids[child.ref]\n child_proto.local_name = child.name\n\n return named_saveables, object_graph_proto\n\n\ndef _serialize_object_graph(root_checkpointable):\n \"\"\"Determine checkpoint keys for variables and build a serialized graph.\n\n Non-slot variables are keyed based on a shortest path from the root saveable\n to the object which owns the variable (i.e. the one which called\n `Checkpointable._add_variable` to create it).\n\n Slot variables are keyed based on a shortest path to the variable being\n slotted for, a shortest path to their optimizer, and the slot name.\n\n Args:\n root_checkpointable: A `Checkpointable` object whose variables (including\n the variables of dependencies, recursively) should be saved.\n\n Returns:\n A tuple of (named_variables, object_graph_proto):\n named_variables: A dictionary mapping names to variable objects.\n object_graph_proto: A CheckpointableObjectGraph protocol buffer containing\n the serialized object graph and variable references.\n\n Raises:\n ValueError: If there are invalid characters in an optimizer's slot names.\n \"\"\"\n checkpointable_objects, path_to_root = (\n _breadth_first_checkpointable_traversal(root_checkpointable))\n object_names = {\n obj: _object_prefix_from_path(path)\n for obj, path in path_to_root.items()}\n node_ids = {node: node_id for node_id, node\n in enumerate(checkpointable_objects)}\n slot_variables = _serialize_slot_variables(\n checkpointable_objects=checkpointable_objects,\n node_ids=node_ids,\n object_names=object_names)\n return _serialize_checkpointables(\n checkpointable_objects=checkpointable_objects,\n node_ids=node_ids,\n object_names=object_names,\n slot_variables=slot_variables)\n\n\ndef list_objects(root_checkpointable):\n \"\"\"Traverse the object graph and list all accessible objects.\n\n Looks for `Checkpointable` objects which are dependencies of\n `root_checkpointable`. Includes slot variables only if the variable they are\n slotting for and the optimizer are dependencies of `root_checkpointable`\n (i.e. if they would be saved with a checkpoint).\n\n Args:\n root_checkpointable: A `Checkpointable` object whose dependencies should be\n flattened.\n Returns:\n A flat list of objects.\n \"\"\"\n # TODO (allenl): Extract out gathering logic so the naming logic doesn't have id:4322\n # https://github.com/imdone/tensorflow/issues/4320\n # to run.\n checkpointable_objects, path_to_root = (\n _breadth_first_checkpointable_traversal(root_checkpointable))\n object_names = {\n obj: _object_prefix_from_path(path)\n for obj, path in path_to_root.items()}\n node_ids = {node: node_id for node_id, node\n in enumerate(checkpointable_objects)}\n _serialize_slot_variables(\n checkpointable_objects=checkpointable_objects,\n node_ids=node_ids,\n object_names=object_names)\n return checkpointable_objects\n\n\ndef gather_initializers(root_checkpointable):\n \"\"\"Traverse the object graph and find initialization ops.\n\n Looks for `Checkpointable` objects which are dependencies of\n `root_checkpointable` and which have an `initializer` property. Includes\n initializers for slot variables only if the variable they are slotting for and\n the optimizer are dependencies of `root_checkpointable` (i.e. if they would be\n saved with a checkpoint).\n\n Args:\n root_checkpointable: A `Checkpointable` object to gather initializers for.\n Returns:\n A list of initialization ops.\n \"\"\"\n checkpointable_objects = list_objects(root_checkpointable)\n return [c.initializer for c in checkpointable_objects\n if hasattr(c, \"initializer\") and c.initializer is not None]\n\n\nclass _NoRestoreSaveable(saver_lib.BaseSaverBuilder.SaveableObject):\n\n def __init__(self, tensor, name):\n spec = saver_lib.BaseSaverBuilder.SaveSpec(tensor, \"\", name)\n super(_NoRestoreSaveable, self).__init__(tensor, [spec], name)\n\n def restore(self, restored_tensors, restored_shapes):\n return control_flow_ops.no_op()\n\n\nclass _LoadStatus(object):\n \"\"\"Abstract base for load status callbacks.\"\"\"\n\n @abc.abstractmethod\n def assert_consumed(self):\n \"\"\"Raises an exception unless a non-trivial restoration has completed.\"\"\"\n pass\n\n @abc.abstractmethod\n def run_restore_ops(self, session=None):\n \"\"\"Runs restore ops from the checkpoint. Requires a valid checkpoint.\"\"\"\n pass\n\n @abc.abstractmethod\n def initialize_or_restore(self, session=None):\n \"\"\"Runs restore ops from the checkpoint, or initializes variables.\"\"\"\n pass\n\n\nclass CheckpointLoadStatus(_LoadStatus):\n \"\"\"Checks the status of checkpoint loading and manages restore ops.\n\n Returned from `Saver.restore`. Since `restore` may defer the loading of values\n in the checkpoint which don't yet have corresponding Python objects,\n `CheckpointLoadStatus` provides a callback to verify that checkpoint loading\n is complete (`assert_consumed`).\n\n When graph building, `restore` does not run restore ops itself since their\n creation may be deferred. The `run_restore_ops` method must be called once all\n Python objects with values to restore have been created and added to the\n dependency graph (this does not necessarily have to be the whole checkpoint;\n calling `run_restore_ops` while `assert_consumed` fails is supported and will\n partially restore the checkpoint).\n\n See `Saver.restore` for usage examples.\n \"\"\"\n\n def __init__(self, checkpoint, feed_dict, root_checkpointable):\n self._checkpoint = checkpoint\n self._feed_dict = feed_dict\n self._root_checkpointable = root_checkpointable\n\n def assert_consumed(self):\n \"\"\"Asserts that all objects in the checkpoint have been created/matched.\n\n Returns:\n `self` for chaining.\n Raises:\n AssertionError: If there are any Python objects in the dependency graph\n which have not been restored from this checkpoint or a later `restore`,\n or if there are any checkpointed values which have not been matched to\n Python objects.\n \"\"\"\n for node_id, node in enumerate(self._checkpoint.object_graph_proto.nodes):\n checkpointable = self._checkpoint.object_by_proto_id.get(node_id, None)\n if checkpointable is None:\n raise AssertionError(\"Unresolved object in checkpoint: %s\" % (node,))\n if checkpointable._update_uid < self._checkpoint.restore_uid: # pylint: disable=protected-access\n raise AssertionError(\n \"Object not assigned a value from checkpoint: %s\" % (node,))\n if self._checkpoint.slot_restorations:\n # Sanity check; this collection should be clear if everything has been\n # restored.\n raise AssertionError(\"Unresolved slot restorations: %s\" % (\n self._checkpoint.slot_restorations,))\n if self._checkpoint.unused_attributes:\n raise AssertionError(\n (\"Unused attributes in these objects (the attributes exist in the \"\n \"checkpoint but not in the objects): %s\") % (\n self._checkpoint.unused_attributes.items(),))\n for checkpointable_object in list_objects(self._root_checkpointable):\n self._checkpoint.all_python_objects.add(checkpointable_object)\n unused_python_objects = (\n set(self._checkpoint.all_python_objects)\n - set(self._checkpoint.object_by_proto_id.values()))\n if unused_python_objects:\n raise AssertionError(\n (\"Some Python objects were not bound to checkpointed values, likely \"\n \"due to changes in the Python program: %s\")\n % (unused_python_objects,))\n return self\n\n def run_restore_ops(self, session=None):\n \"\"\"Run operations to restore objects in the dependency graph.\"\"\"\n if context.executing_eagerly():\n return # Run eagerly\n if session is None:\n session = ops.get_default_session()\n session.run(self._checkpoint.restore_ops, feed_dict=self._feed_dict)\n\n def initialize_or_restore(self, session=None):\n \"\"\"Run operations to initialize or restore objects in the dependency graph.\n\n Any objects in the dependency graph which have initializers but are not in\n the checkpoint will have those initializers run, unless those variables are\n being restored by a later call to `tf.train.Checkpoint.restore()`.\n\n This method has a sibling in `InitializationOnlyStatus` which instead\n initializes variables. That type is returned if no checkpoint is specified\n in `Saver.restore`.\n\n Args:\n session: The session to run init/restore ops in. If `None`, uses the\n default session.\n \"\"\"\n if context.executing_eagerly():\n return # Initialization and restoration ops are run eagerly\n if session is None:\n session = ops.get_default_session()\n all_objects = list_objects(self._root_checkpointable)\n already_initialized_objects = set(\n self._checkpoint.object_by_proto_id.values())\n initializers_for_non_restored_variables = [\n c.initializer for c in all_objects\n if hasattr(c, \"initializer\")\n and c not in already_initialized_objects\n and (getattr(c, \"_update_uid\", self._checkpoint.restore_uid - 1)\n < self._checkpoint.restore_uid)]\n self.run_restore_ops(session=session)\n session.run(initializers_for_non_restored_variables)\n\n\nclass InitializationOnlyStatus(_LoadStatus):\n \"\"\"Returned from `Saver.restore` when no checkpoint has been specified.\n\n Objects of this type have the same `assert_consumed` method as\n `CheckpointLoadStatus`, but it always fails. However,\n `initialize_or_restore` works on objects of both types, and will\n initialize variables in `InitializationOnlyStatus` objects or restore them\n otherwise.\n \"\"\"\n\n def __init__(self, root_checkpointable, restore_uid):\n self._restore_uid = restore_uid\n self._root_checkpointable = root_checkpointable\n\n def assert_consumed(self):\n \"\"\"Assertion for consistency with `CheckpointLoadStatus`. Always fails.\"\"\"\n raise AssertionError(\n \"No checkpoint specified (save_path=None); nothing is being restored.\")\n\n def run_restore_ops(self, session=None):\n \"\"\"For consistency with `CheckpointLoadStatus`.\n\n Use `initialize_or_restore` for initializing if no checkpoint was passed\n to `Saver.restore` and restoring otherwise.\n\n Args:\n session: Not used.\n \"\"\"\n raise AssertionError(\n \"No checkpoint specified, so no restore ops are available \"\n \"(save_path=None to Saver.restore).\")\n\n def initialize_or_restore(self, session=None):\n \"\"\"Runs initialization ops for variables.\n\n Objects which would be saved by `Saver.save` will be initialized, unless\n those variables are being restored by a later call to\n `tf.train.Checkpoint.restore()`.\n\n This method does nothing when executing eagerly (initializers get run\n eagerly).\n\n Args:\n session: The session to run initialization ops in. If `None`, uses the\n default session.\n \"\"\"\n if context.executing_eagerly():\n return # run eagerly\n if session is None:\n session = ops.get_default_session()\n checkpointable_objects = list_objects(self._root_checkpointable)\n initializers = [\n c.initializer for c in checkpointable_objects\n if hasattr(c, \"initializer\") and c.initializer is not None\n and (getattr(c, \"_update_uid\", self._restore_uid - 1)\n < self._restore_uid)]\n session.run(initializers)\n\n\n_DEPRECATED_RESTORE_INSTRUCTIONS = (\n \"Restoring a name-based tf.train.Saver checkpoint using the object-based \"\n \"restore API. This mode uses global names to match variables, and so is \"\n \"somewhat fragile. It also adds new restore ops to the graph each time it \"\n \"is called. Prefer re-encoding training checkpoints in the object-based \"\n \"format: run save() on the object-based saver (the same one this message \"\n \"is coming from) and use that checkpoint in the future.\")\n\n\nclass NameBasedSaverStatus(_LoadStatus):\n \"\"\"Status for loading a name-based training checkpoint.\"\"\"\n\n def __init__(self, object_saver, save_path):\n self._object_saver = object_saver\n self._save_path = save_path\n\n def assert_consumed(self):\n \"\"\"Assertion for consistency with `CheckpointLoadStatus`. Always fails.\"\"\"\n raise AssertionError(\n \"Restoring a name-based checkpoint. No load status is available.\")\n\n @deprecation.deprecated(\n date=None, instructions=_DEPRECATED_RESTORE_INSTRUCTIONS)\n def run_restore_ops(self, session=None):\n \"\"\"Load the name-based training checkpoint using a new `tf.train.Saver`.\"\"\"\n if session is None and not context.executing_eagerly():\n session = ops.get_default_session()\n with ops.device(\"/cpu:0\"):\n saver_lib.Saver(self._object_saver._global_variable_names()).restore( # pylint: disable=protected-access\n sess=session, save_path=self._save_path)\n\n def initialize_or_restore(self, session=None):\n \"\"\"Alias for `run_restore_ops`.\"\"\"\n self.run_restore_ops(session=session)\n\n\nclass _SessionWithFeedDictAdditions(session_lib.SessionInterface):\n \"\"\"Pretends to be a session, inserts extra feeds on run().\"\"\"\n\n def __init__(self, session, feed_additions):\n self._wrapped_session = session\n self._feed_additions = feed_additions\n\n def run(self, fetches, feed_dict=None, **kwargs):\n if feed_dict is None:\n feed_dict = {}\n else:\n feed_dict = feed_dict.copy()\n feed_dict.update(self._feed_additions)\n return self._wrapped_session.run(\n fetches=fetches, feed_dict=feed_dict, **kwargs)\n\n\ndef _copy_saver_with_new_var_list(old_saver, new_var_list):\n \"\"\"Copy a `tf.train.Saver`'s state to a new Saver with different variables.\"\"\"\n new_saver = saver_lib.Saver(var_list=new_var_list)\n # TODO (allenl): Move to copying functionality to Saver? id:3986\n # https://github.com/imdone/tensorflow/issues/3984\n # pylint: disable=protected-access\n new_saver._last_checkpoints = old_saver._last_checkpoints\n new_saver._checkpoints_to_be_deleted = old_saver._checkpoints_to_be_deleted\n new_saver._next_checkpoint_time = old_saver._next_checkpoint_time\n # pylint: enable=protected-access\n return new_saver\n\n\nclass CheckpointableSaver(object):\n \"\"\"Saves and restores a `Checkpointable` object and its dependencies.\n\n See `Checkpointable` for details of dependency management. `Saver` wraps\n `tf.train.Saver` for saving, including extra information about the graph of\n dependencies between Python objects. When restoring, it uses this information\n about the save-time dependency graph to more robustly match objects with their\n checkpointed values. When executing eagerly, it supports restoring variables\n on object creation (see `Saver.restore`).\n\n Values in a checkpoint are mapped to `Checkpointable` Python objects\n (`Variable`s, `Optimizer`s, `Layer`s) based on the names provided when the\n checkpoint was written. To avoid breaking existing checkpoints when modifying\n a class, dependency names (the names of attributes to which `Checkpointable`\n objects are assigned) may not change. These names are local to objects, in\n contrast to the `Variable.name`-based save/restore from `tf.train.Saver`, and\n so allow additional program transformations.\n \"\"\"\n\n def __init__(self, root_checkpointable):\n \"\"\"Configure saving.\n\n Args:\n root_checkpointable: The root of the object graph to save/restore. This\n object and all of its dependencies are saved in the checkpoint. When\n restoring, objects are matched and restored starting from this root.\n \"\"\"\n # Allow passing in a weak reference to avoid reference cycles when\n # `Checkpointable` objects save themselves.\n self._root_checkpointable_ref = root_checkpointable\n # The file prefix placeholder is created lazily when graph building (and not\n # at all when executing eagerly) to avoid creating ops in the constructor\n # (when they may never be necessary).\n self._file_prefix_placeholder = None\n\n # Op caching for save\n self._object_graph_feed_tensor = None\n self._last_save_object_graph = None\n self._last_save_saver = None\n\n # Op caching for restore\n self._last_restore_object_graph = None\n self._last_restore_checkpoint = None\n\n @property\n def _root_checkpointable(self):\n if isinstance(self._root_checkpointable_ref, weakref.ref):\n derefed = self._root_checkpointable_ref()\n assert derefed is not None\n return derefed\n else:\n return self._root_checkpointable_ref\n\n def save(self, file_prefix, checkpoint_number=None, session=None):\n \"\"\"Save a training checkpoint.\n\n The saved checkpoint includes variables created by this object and any\n Checkpointable objects it depends on at the time `Saver.save()` is called.\n\n Args:\n file_prefix: A prefix to use for the checkpoint filenames\n (/path/to/directory/and_a_prefix). Names are generated based on this\n prefix and `checkpoint_number`, if provided.\n checkpoint_number: An integer variable or Tensor, used to number\n checkpoints. Typically this value is saved along with other variables in\n training checkpoints, which will happen automatically if it was created\n by `root_checkpointable` or one of its dependencies (via\n `Checkpointable._add_variable`).\n session: The session to evaluate variables in. Ignored when executing\n eagerly. If not provided when graph building, the default session is\n used.\n\n Returns:\n The full path to the checkpoint.\n \"\"\"\n named_variables, graph_proto = _serialize_object_graph(\n self._root_checkpointable)\n if not context.executing_eagerly():\n if session is None:\n session = ops.get_default_session()\n if self._object_graph_feed_tensor is None:\n with ops.device(\"/cpu:0\"):\n self._object_graph_feed_tensor = constant_op.constant(\n \"\", dtype=dtypes.string)\n object_graph_tensor = self._object_graph_feed_tensor\n feed_additions = {object_graph_tensor: graph_proto.SerializeToString()}\n else:\n session = None\n with ops.device(\"/cpu:0\"):\n object_graph_tensor = constant_op.constant(\n graph_proto.SerializeToString(), dtype=dtypes.string)\n feed_additions = None\n assert checkpointable_lib.OBJECT_GRAPH_PROTO_KEY not in named_variables\n named_variables[checkpointable_lib.OBJECT_GRAPH_PROTO_KEY] = (\n _NoRestoreSaveable(\n tensor=object_graph_tensor,\n name=checkpointable_lib.OBJECT_GRAPH_PROTO_KEY))\n if (self._last_save_object_graph != graph_proto\n # When executing eagerly, we need to re-create SaveableObjects each time\n # save() is called so they pick up new Tensors passed to their\n # constructors. That means the Saver needs to be copied with a new\n # var_list.\n or context.executing_eagerly()):\n if self._last_save_object_graph is not None:\n self._last_save_saver = _copy_saver_with_new_var_list(\n old_saver=self._last_save_saver, new_var_list=named_variables)\n else:\n self._last_save_saver = saver_lib.Saver(var_list=named_variables)\n self._last_save_object_graph = graph_proto\n with ops.device(\"/cpu:0\"):\n save_path = self._last_save_saver.save(\n sess=_SessionWithFeedDictAdditions(\n session=session, feed_additions=feed_additions),\n save_path=file_prefix,\n write_meta_graph=False,\n global_step=checkpoint_number)\n return save_path\n\n def _global_variable_names(self):\n \"\"\"Generate a `tf.train.Saver`-style `var_list` using `variable.name`s.\"\"\"\n named_saveables, graph_proto = _serialize_object_graph(\n self._root_checkpointable)\n saver_names = {}\n for object_proto in graph_proto.nodes:\n for attribute_proto in object_proto.attributes:\n saver_names[attribute_proto.full_name] = named_saveables[\n attribute_proto.checkpoint_key]\n return saver_names\n\n def restore(self, save_path):\n \"\"\"Restore a training checkpoint.\n\n Restores `root_checkpointable` and any objects that it tracks\n (transitive). Either assigns values immediately if variables to restore have\n been created already, or defers restoration until the variables are\n created. Dependencies added to the `root_checkpointable` passed to the\n constructor after this call will be matched if they have a corresponding\n object in the checkpoint.\n\n When building a graph, restorations are added to the graph but not run.\n\n To disallow deferred loading, assert immediately that all checkpointed\n variables have been matched to variable objects:\n\n ```python\n saver = Saver(root)\n saver.restore(path).assert_consumed()\n ```\n\n An exception will be raised unless every object was matched and its\n variables already exist.\n\n When graph building, `assert_consumed()` indicates that all of the restore\n ops which will be created for this checkpoint have been created. They can be\n run via the `run_restore_ops()` function of the status object:\n\n ```python\n saver.restore(path).assert_consumed().run_restore_ops()\n ```\n\n If the checkpoint has not been consumed completely, then the list of restore\n ops will grow as more objects are added to the dependency graph.\n\n Name-based `tf.train.Saver` checkpoints can be loaded using this\n method. There is no deferred loading, and names are used to match\n variables. No restore ops are created/run until `run_restore_ops()` or\n `initialize_or_restore()` are called on the returned status object, even\n when executing eagerly. Re-encode name-based checkpoints using this\n object-based `Saver.save` as soon as possible.\n\n Args:\n save_path: The path to the checkpoint, as returned by `save` or\n `tf.train.latest_checkpoint`. If None (as when there is no latest\n checkpoint for `tf.train.latest_checkpoint` to return), returns an\n object which may run initializers for objects in the dependency\n graph. If the checkpoint was written by the name-based `tf.train.Saver`,\n names are used to match variables.\n\n Returns:\n A load status object, which can be used to make assertions about the\n status of checkpoint restoration and run initialization/restore ops\n (of type `CheckpointLoadStatus`, or `InitializationOnlyStatus` if\n `save_path` is `None`).\n\n If `save_path` points to a name-based checkpoint, a `NameBasedSaverStatus`\n object is returned which runs restore ops from a name-based saver.\n \"\"\"\n if save_path is None:\n return InitializationOnlyStatus(self._root_checkpointable, ops.uid())\n in_graph_mode = not context.executing_eagerly()\n if in_graph_mode:\n if self._file_prefix_placeholder is None:\n with ops.device(\"/cpu:0\"):\n self._file_prefix_placeholder = constant_op.constant(\"model\")\n file_prefix_tensor = self._file_prefix_placeholder\n file_prefix_feed_dict = {self._file_prefix_placeholder: save_path}\n else:\n with ops.device(\"/cpu:0\"):\n file_prefix_tensor = constant_op.constant(save_path)\n file_prefix_feed_dict = None\n reader = pywrap_tensorflow.NewCheckpointReader(save_path)\n try:\n object_graph_string = reader.get_tensor(\n checkpointable_lib.OBJECT_GRAPH_PROTO_KEY)\n except errors_impl.NotFoundError:\n # The object graph proto does not exist in this checkpoint. Try again with\n # name-based saving.\n return NameBasedSaverStatus(self, save_path)\n\n object_graph_proto = (\n checkpointable_object_graph_pb2.CheckpointableObjectGraph())\n object_graph_proto.ParseFromString(object_graph_string)\n if in_graph_mode and object_graph_proto == self._last_restore_object_graph:\n checkpoint = self._last_restore_checkpoint\n else:\n if in_graph_mode:\n dtype_map = None\n else:\n dtype_map = reader.get_variable_to_dtype_map()\n checkpoint = _CheckpointRestoreCoordinator(\n object_graph_proto=object_graph_proto,\n save_path=file_prefix_tensor,\n dtype_map=dtype_map)\n if in_graph_mode:\n if self._last_restore_object_graph is not None:\n raise NotImplementedError(\n \"Using a single Saver to restore different object graphs is not \"\n \"currently supported when graph building. Use a different Saver \"\n \"for each object graph (restore ops will be duplicated), or \"\n \"file a feature request if this limitation bothers you.\")\n self._last_restore_checkpoint = checkpoint\n self._last_restore_object_graph = object_graph_proto\n checkpointable_lib._CheckpointPosition( # pylint: disable=protected-access\n checkpoint=checkpoint, proto_id=0).restore(self._root_checkpointable)\n load_status = CheckpointLoadStatus(\n checkpoint,\n root_checkpointable=self._root_checkpointable,\n feed_dict=file_prefix_feed_dict)\n return load_status\n\n\n@tf_export(\"train.Checkpoint\")\nclass Checkpoint(checkpointable_lib.Checkpointable):\n \"\"\"Groups checkpointable objects, saving and restoring them.\n\n `Checkpoint`'s constructor accepts keyword arguments whose values are types\n that contain checkpointable state, such as `tf.train.Optimizer`\n implementations, `tf.Variable`, `tf.keras.Layer` implementations, or\n `tf.keras.Model` implementations. It saves these values with a checkpoint, and\n maintains a `save_counter` for numbering checkpoints.\n\n Example usage when graph building:\n\n ```python\n import tensorflow as tf\n import os\n\n checkpoint_directory = \"/tmp/training_checkpoints\"\n checkpoint_prefix = os.path.join(checkpoint_directory, \"ckpt\")\n\n checkpoint = tf.train.Checkpoint(optimizer=optimizer, model=model)\n status = checkpoint.restore(tf.train.latest_checkpoint(checkpoint_directory))\n train_op = optimizer.minimize( ... )\n status.assert_consumed() # Optional sanity checks.\n with tf.Session() as session:\n # Use the Session to restore variables, or initialize them if\n # tf.train.latest_checkpoint returned None.\n status.initialize_or_restore(session)\n for _ in range(num_training_steps):\n session.run(train_op)\n checkpoint.save(file_prefix=checkpoint_prefix)\n ```\n\n Example usage with eager execution enabled:\n\n ```python\n import tensorflow as tf\n import os\n\n tf.enable_eager_execution()\n\n checkpoint_directory = \"/tmp/training_checkpoints\"\n checkpoint_prefix = os.path.join(checkpoint_directory, \"ckpt\")\n\n checkpoint = tf.train.Checkpoint(optimizer=optimizer, model=model)\n status = checkpoint.restore(tf.train.latest_checkpoint(checkpoint_directory))\n for _ in range(num_training_steps):\n optimizer.minimize( ... ) # Variables will be restored on creation.\n status.assert_consumed() # Optional sanity checks.\n checkpoint.save(file_prefix=checkpoint_prefix)\n ```\n\n `Checkpoint.save` and `Checkpoint.restore` write and read object-based\n checkpoints, in contrast to `tf.train.Saver` which writes and reads\n `variable.name` based checkpoints. Object-based checkpointing saves a graph of\n dependencies between Python objects (`Layer`s, `Optimizer`s, `Variable`s,\n etc.) with named edges, and this graph is used to match variables when\n restoring a checkpoint. It can be more robust to changes in the Python\n program, and helps to support restore-on-create for variables when executing\n eagerly. Prefer `tf.train.Checkpoint` over `tf.train.Saver` for new code.\n\n `Checkpoint` objects have dependencies on the objects passed as keyword\n arguments to their constructors, and each dependency is given a name that is\n identical to the name of the keyword argument for which it was created.\n TensorFlow classes like `Layer`s and `Optimizer`s will automatically add\n dependencies on their variables (e.g. \"kernel\" and \"bias\" for\n `tf.keras.layers.Dense`). Inheriting from `tf.keras.Model` makes managing\n dependencies easy in user-defined classes, since `Model` hooks into attribute\n assignment. For example:\n\n ```python\n class Regress(tf.keras.Model):\n\n def __init__(self):\n super(Regress, self).__init__()\n self.input_transform = tf.keras.layers.Dense(10)\n # ...\n\n def call(self, inputs):\n x = self.input_transform(inputs)\n # ...\n ```\n\n This `Model` has a dependency named \"input_transform\" on its `Dense` layer,\n which in turn depends on its variables. As a result, saving an instance of\n `Regress` using `tf.train.Checkpoint` will also save all the variables created\n by the `Dense` layer.\n\n Attributes:\n save_counter: Incremented when `save()` is called. Used to number\n checkpoints.\n \"\"\"\n\n def __init__(self, **kwargs):\n \"\"\"Group objects into a training checkpoint.\n\n Args:\n **kwargs: Keyword arguments are set as attributes of this object, and are\n saved with the checkpoint. Values must be checkpointable objects.\n Raises:\n ValueError: If objects in `kwargs` are not checkpointable.\n \"\"\"\n super(Checkpoint, self).__init__()\n for k, v in sorted(kwargs.items(), key=lambda item: item[0]):\n if not isinstance(v, checkpointable_lib.CheckpointableBase):\n raise ValueError(\n (\"`Checkpoint` was expecting a checkpointable object (an object \"\n \"derived from `CheckpointableBase`), got %s. If you believe this \"\n \"object should be checkpointable (i.e. it is part of the \"\n \"TensorFlow Python API and manages state), please open an issue.\")\n % (v,))\n setattr(self, k, v)\n self._save_counter = None # Created lazily for restore-on-create.\n self._saver = CheckpointableSaver(weakref.ref(self))\n\n def _maybe_create_save_counter(self):\n \"\"\"Create a save counter if it does not yet exist.\"\"\"\n if self._save_counter is None:\n # Initialized to 0 and incremented before saving.\n with ops.device(\"/cpu:0\"):\n self._save_counter = add_variable(\n self, name=\"save_counter\", initializer=0, dtype=dtypes.int64)\n\n @property\n def save_counter(self):\n \"\"\"An integer variable which starts at zero and is incremented on save.\n\n Used to number checkpoints.\n\n Returns:\n The save counter variable.\n \"\"\"\n self._maybe_create_save_counter()\n return self._save_counter\n\n def save(self, file_prefix, session=None):\n \"\"\"Save a training checkpoint.\n\n The saved checkpoint includes variables created by this object and any\n checkpointable objects it depends on at the time `Checkpoint.save()` is\n called.\n\n Args:\n file_prefix: A prefix to use for the checkpoint filenames\n (/path/to/directory/and_a_prefix). Names are generated based on this\n prefix and `Checkpoint.save_counter`.\n session: The session to evaluate variables in. Ignored when executing\n eagerly. If not provided when graph building, the default session is\n used.\n\n Returns:\n The full path to the checkpoint.\n \"\"\"\n in_graph_mode = not context.executing_eagerly()\n if in_graph_mode:\n if session is None:\n session = ops.get_default_session()\n if self._save_counter is None:\n # When graph building, if this is a new save counter variable then it\n # needs to be initialized before assign_add. This is only an issue if\n # restore() has not been called first.\n session.run(self.save_counter.initializer)\n with ops.colocate_with(self.save_counter):\n assign_op = self.save_counter.assign_add(1)\n if in_graph_mode:\n session.run(assign_op)\n return self._saver.save(\n file_prefix=file_prefix,\n checkpoint_number=self.save_counter,\n session=session)\n\n def restore(self, save_path):\n \"\"\"Restore a training checkpoint.\n\n Restores this `Checkpoint` and any objects it depends on.\n\n When executing eagerly, either assigns values immediately if variables to\n restore have been created already, or defers restoration until the variables\n are created. Dependencies added after this call will be matched if they have\n a corresponding object in the checkpoint (the restore request will queue in\n any checkpointable object waiting for the expected dependency to be added).\n\n When graph building, restoration ops are added to the graph but not run\n immediately.\n\n To ensure that loading is complete and no more assignments will take place,\n use the `assert_consumed()` method of the status object returned by\n `restore`:\n\n ```python\n checkpoint = tf.train.Checkpoint( ... )\n checkpoint.restore(path).assert_consumed()\n ```\n\n An exception will be raised if any Python objects in the dependency graph\n were not found in the checkpoint, or if any checkpointed values do not have\n a matching Python object.\n\n When graph building, `assert_consumed()` indicates that all of the restore\n ops that will be created for this checkpoint have been created. They can be\n run via the `run_restore_ops()` method of the status object:\n\n ```python\n checkpoint.restore(path).assert_consumed().run_restore_ops()\n ```\n\n If the checkpoint has not been consumed completely, then the list of restore\n ops will grow as more objects are added to the dependency graph.\n\n Name-based `tf.train.Saver` checkpoints can be loaded using this\n method. There is no deferred loading, and names are used to match\n variables. No restore ops are created/run until `run_restore_ops()` or\n `initialize_or_restore()` are called on the returned status object, even\n when executing eagerly. Re-encode name-based checkpoints using\n `tf.train.Checkpoint.save` as soon as possible.\n\n Args:\n save_path: The path to the checkpoint, as returned by `save` or\n `tf.train.latest_checkpoint`. If None (as when there is no latest\n checkpoint for `tf.train.latest_checkpoint` to return), returns an\n object which may run initializers for objects in the dependency\n graph. If the checkpoint was written by the name-based `tf.train.Saver`,\n names are used to match variables.\n\n Returns:\n A load status object, which can be used to make assertions about the\n status of a checkpoint restoration and run initialization/restore ops.\n\n The returned status object has the following methods:\n - `assert_consumed()`:\n Raises an exception if any variables/objects are unmatched: either\n checkpointed values which don't have a matching Python object or\n Python objects in the dependency graph with no values in the\n checkpoint. This method returns the status object, and so may be\n chained with `initialize_or_restore` or `run_restore_ops`.\n - `initialize_or_restore(session=None)`:\n When graph building, runs variable initializers if `save_path` is\n `None`, but otherwise runs restore operations. If no `session` is\n explicitly specified, the default session is used. No effect for\n object-based checkpoints when executing eagerly (variables are\n initialized or restored eagerly).\n - `run_restore_ops(session=None)`:\n When graph building, runs restore operations. If no `session` is\n explicitly specified, the default session is used. No effect for\n object-based checkpoints when executing eagerly (restore operations\n are run eagerly). May only be called when `save_path` is not `None`.\n \"\"\"\n status = self._saver.restore(save_path=save_path)\n # Create the save counter now so it gets initialized with other variables\n # when graph building. Creating it earlier would lead to double\n # initialization when executing eagerly.\n self._maybe_create_save_counter()\n return status\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 the currently experimental in-graph batch ops.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport threading\nimport time\n\nfrom tensorflow.contrib.batching.python.ops import batch_ops\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import gradients_impl\nfrom tensorflow.python.ops import script_ops\nfrom tensorflow.python.platform import test\n\n\ndef delayed_plus1(x):\n \"\"\"Sleeps for 100ms then returns x+1.\"\"\"\n time.sleep(0.1)\n return x + 1\n\n\nclass BatchOpsTest(test.TestCase):\n \"\"\"Tests for batch_ops.{un,}batch.\"\"\"\n\n def testBasicBatch(self):\n \"\"\"Tests that a single batched tensor executes together and only once.\"\"\"\n with self.test_session() as sess:\n inp = array_ops.placeholder(dtype=dtypes.int32, shape=[1])\n batched, index, _ = batch_ops.batch(\n [inp], num_batch_threads=1, max_batch_size=2,\n batch_timeout_micros=36000000, grad_timeout_micros=0,\n batching_queue=\"\")\n thread_results = []\n\n def worker():\n thread_results.extend(\n sess.run([batched, index], feed_dict={inp: [1]}))\n\n worker_thread = threading.Thread(target=worker)\n worker_thread.start()\n main_results = sess.run([batched, index], feed_dict={inp: [2]})\n worker_thread.join()\n\n # At this point either the thread or the main did the batch and the other\n # should have empty results.\n if list(thread_results[0][0]):\n batch_t = thread_results[0][0]\n index_t = thread_results[1]\n empty_b = main_results[0][0]\n empty_m = main_results[1]\n else:\n batch_t = main_results[0][0]\n index_t = main_results[1]\n empty_b = thread_results[0][0]\n empty_m = thread_results[1]\n\n # Check that both the inputs made it out exactly once.\n self.assertAllEqual(sorted(batch_t), (1, 2))\n # Check that we get 2 rows in the index tensor.\n self.assertEqual(len(index_t), 2)\n # Check that the other ones are empty.\n self.assertEqual(len(empty_b), 0)\n self.assertEqual(len(empty_m), 0)\n\n def testBatchWithPadding(self):\n \"\"\"Test that batching with padding up to an allowed batch size works.\"\"\"\n with self.test_session() as sess:\n inp = array_ops.placeholder(dtype=dtypes.int32, shape=[2])\n batched, index, _ = batch_ops.batch(\n [inp], num_batch_threads=1, max_batch_size=10,\n batch_timeout_micros=100000, # 100ms\n allowed_batch_sizes=[5, 10],\n grad_timeout_micros=0, batching_queue=\"\")\n thread_results = []\n\n def worker():\n thread_results.extend(\n sess.run([batched, index], feed_dict={inp: [1, 3]}))\n\n worker_thread = threading.Thread(target=worker)\n worker_thread.start()\n main_results = sess.run([batched, index], feed_dict={inp: [2, 4]})\n worker_thread.join()\n\n # At this point either the thread or the main did the batch and the other\n # should have empty results.\n if list(thread_results[0][0]):\n batch_t = thread_results[0][0]\n else:\n batch_t = main_results[0][0]\n\n # Check that the batch tensor incorporates the padding.\n self.assertEqual(len(batch_t), 5)\n\n def testMultipleBatch(self):\n \"\"\"Tests that multiple batched tensors execute together.\"\"\"\n with self.test_session() as sess:\n inp0 = array_ops.placeholder(dtype=dtypes.int32, shape=[1])\n inp1 = array_ops.placeholder(dtype=dtypes.int32, shape=[1])\n batched, _, _ = batch_ops.batch(\n [inp0, inp1],\n num_batch_threads=1,\n max_batch_size=2,\n batch_timeout_micros=36000000,\n grad_timeout_micros=0,\n batching_queue=\"\")\n thread_results = []\n\n def worker():\n thread_results.extend(\n sess.run([batched], feed_dict={inp0: [1],\n inp1: [2]}))\n\n worker_thread = threading.Thread(target=worker)\n worker_thread.start()\n main_results = sess.run([batched], feed_dict={inp0: [2], inp1: [3]})\n worker_thread.join()\n\n # At this point either the thread or the main did the batch and the other\n # should have empty results.\n if list(thread_results[0][0]):\n batch_t = thread_results[0]\n empty_t = main_results[0]\n else:\n batch_t = main_results[0]\n empty_t = thread_results[0]\n\n # Assert that the tensors were batched together.\n self.assertAllEqual(sorted(batch_t[0]), [1, 2])\n self.assertAllEqual(sorted(batch_t[1]), [2, 3])\n self.assertAllEqual(empty_t[0], [])\n self.assertAllEqual(empty_t[1], [])\n\n def testIllegalBatchDifferentDim0Sizes(self):\n \"\"\"Tests illegally feeding tensors with different dim0 sizes.\"\"\"\n with self.test_session() as sess:\n inp0 = array_ops.placeholder(dtype=dtypes.int32, shape=[1])\n inp1 = array_ops.placeholder(dtype=dtypes.int32, shape=[2])\n batched, index, _ = batch_ops.batch(\n [inp0, inp1], num_batch_threads=1, max_batch_size=2,\n batch_timeout_micros=0, grad_timeout_micros=0, batching_queue=\"\")\n with self.assertRaises(Exception) as raised:\n _ = sess.run([batched, index], feed_dict={inp0: [0], inp1: [1, 2]})\n self.assertGreater(\n raised.exception.message.find(\"must have equal 0th-dimension size\"),\n 0)\n\n def testBasicUnbatch(self):\n \"\"\"Tests that batch and unbatch work together.\"\"\"\n with self.test_session() as sess:\n inp = array_ops.placeholder(dtype=dtypes.int32, shape=[1])\n batched, index, id_t = batch_ops.batch(\n [inp], num_batch_threads=1, max_batch_size=10,\n batch_timeout_micros=100000, # 100ms\n allowed_batch_sizes=[3, 10],\n grad_timeout_micros=0, batching_queue=\"\")\n computation = batched[0] + 1\n result = batch_ops.unbatch(computation, index, id_t,\n timeout_micros=1000000, shared_name=\"unbatch\")\n thread_results = []\n\n def worker():\n thread_results.extend(sess.run([result], feed_dict={inp: [1]}))\n\n worker_thread = threading.Thread(target=worker)\n worker_thread.start()\n main_results = sess.run([result], feed_dict={inp: [2]})\n worker_thread.join()\n self.assertEqual(thread_results[0], [2])\n self.assertEqual(main_results[0], [3])\n\n def testBasicUnbatchDecorated(self):\n \"\"\"Tests that the batch_function decorator works.\"\"\"\n with self.test_session() as sess:\n @batch_ops.batch_function(1, 10, 100000)\n def computation(in_t):\n return in_t + 1\n inp = array_ops.placeholder(dtype=dtypes.int32, shape=[1])\n result = computation(inp)\n thread_results = []\n\n def worker():\n thread_results.extend(sess.run([result], feed_dict={inp: [1]}))\n\n worker_thread = threading.Thread(target=worker)\n worker_thread.start()\n main_results = sess.run([result], feed_dict={inp: [2]})\n worker_thread.join()\n self.assertEqual(thread_results[0], [2])\n self.assertEqual(main_results[0], [3])\n\n def testUnbatchTimeout(self):\n \"\"\"Tests that the unbatch timeout works.\"\"\"\n with self.test_session() as sess:\n inp = array_ops.placeholder(dtype=dtypes.int32, shape=[1])\n batched, index, id_t = batch_ops.batch(\n [inp], num_batch_threads=1, max_batch_size=2,\n batch_timeout_micros=36000000, grad_timeout_micros=0,\n batching_queue=\"\")\n computation = batched[0] + 1\n timeout_micros = 10\n result = batch_ops.unbatch(computation, index, id_t, timeout_micros,\n shared_name=\"shared_unbatch\")\n # Set up a parallel pipeline that delays the computation, but uses the\n # same unbatch resource object as the non-delayed pipeline.\n computation_delayed = script_ops.py_func(delayed_plus1,\n [batched[0]],\n dtypes.int32)\n result_delayed = batch_ops.unbatch(computation_delayed,\n index,\n id_t,\n timeout_micros,\n shared_name=\"shared_unbatch\")\n\n thread_results = []\n def worker():\n # A first call using the non-delayed pipeline. The batcher will send an\n # empty tensor along the non-delayed pipeline.\n thread_results.extend(sess.run([result], feed_dict={inp: [1]}))\n worker_thread = threading.Thread(target=worker)\n worker_thread.start()\n time.sleep(0.1) # Ensure the thread's call starts first.\n # A second call using the delayed pipeline. The batcher will send the\n # batched tensor along the delayed pipeline, thus delaying the arrival of\n # the batched tensor at the unbatch op, relative to the empty tensor.\n #\n # TODO (olston, apassos): Avoid relying on the order in which the batch op id:560\n# https://github.com/imdone/tensorflow/issues/561\n# emits the empty tensor versus the batched one.\n _ = sess.run([result_delayed], feed_dict={inp: [2]})\n worker_thread.join()\n # The thread's call should hit the timeout, and thus get 0 results.\n self.assertEqual(len(thread_results), 0)\n\n def testUnbatchGrad(self):\n \"\"\"Tests that batch and unbatch are differentiable.\"\"\"\n with self.test_session() as sess:\n inp = array_ops.placeholder(dtype=dtypes.float32, shape=[1])\n batched, index, id_t = batch_ops.batch(\n [inp], num_batch_threads=1, max_batch_size=2,\n batch_timeout_micros=36000000, grad_timeout_micros=1000000,\n batching_queue=\"\")\n computation = batched[0] * batched[0]\n result = batch_ops.unbatch(computation, index, id_t,\n timeout_micros=1000000, shared_name=\"unbatch\")\n grad = gradients_impl.gradients(result, inp)\n thread_results = []\n\n def worker():\n thread_results.extend(sess.run([grad], feed_dict={inp: [1]}))\n\n worker_thread = threading.Thread(target=worker)\n worker_thread.start()\n main_results = sess.run([grad], feed_dict={inp: [2]})\n worker_thread.join()\n self.assertEqual(thread_results[0], [2])\n self.assertEqual(main_results[0], [4])\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\"\"\"Tests for the experimental input pipeline ops.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport threading\n\nimport numpy as np\n\nfrom tensorflow.python.client import session\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.ops import script_ops\nfrom tensorflow.python.platform import test\n\n\nclass DatasetConstructorTest(test.TestCase):\n\n def _testFromGenerator(self, generator, elem_sequence, num_repeats):\n iterator = (\n dataset_ops.Dataset.from_generator(generator, output_types=dtypes.int64)\n .repeat(num_repeats)\n .prefetch(5)\n .make_initializable_iterator())\n init_op = iterator.initializer\n get_next = iterator.get_next()\n\n with self.test_session() as sess:\n for _ in range(2): # Run twice to test reinitialization.\n sess.run(init_op)\n for _ in range(num_repeats):\n for elem in elem_sequence:\n self.assertAllEqual(elem, sess.run(get_next))\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(get_next)\n\n def _testFromGeneratorOneShot(self, generator, elem_sequence, num_repeats):\n iterator = (\n dataset_ops.Dataset.from_generator(generator, output_types=dtypes.int64)\n .repeat(num_repeats)\n .prefetch(5)\n .make_one_shot_iterator())\n get_next = iterator.get_next()\n\n with self.test_session() as sess:\n for _ in range(num_repeats):\n for elem in elem_sequence:\n self.assertAllEqual(elem, sess.run(get_next))\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(get_next)\n\n def testFromGeneratorUsingFunction(self):\n def generator():\n for i in range(1, 100):\n yield [i] * i\n elem_sequence = list(generator())\n self._testFromGenerator(generator, elem_sequence, 1)\n self._testFromGenerator(generator, elem_sequence, 5)\n self._testFromGeneratorOneShot(generator, elem_sequence, 1)\n self._testFromGeneratorOneShot(generator, elem_sequence, 5)\n\n def testFromGeneratorUsingList(self):\n generator = lambda: [[i] * i for i in range(1, 100)]\n elem_sequence = list(generator())\n self._testFromGenerator(generator, elem_sequence, 1)\n self._testFromGenerator(generator, elem_sequence, 5)\n\n def testFromGeneratorUsingNdarray(self):\n generator = lambda: np.arange(100, dtype=np.int64)\n elem_sequence = list(generator())\n self._testFromGenerator(generator, elem_sequence, 1)\n self._testFromGenerator(generator, elem_sequence, 5)\n\n def testFromGeneratorUsingGeneratorExpression(self):\n # NOTE (mrry): Generator *expressions* are not repeatable (or in id:3597\n # https://github.com/imdone/tensorflow/issues/3596\n # general reusable), because they eagerly evaluate the `for`\n # expression as `iter(range(1, 100))` and discard the means of\n # reconstructing `range(1, 100)`. Wrapping the generator\n # expression in a `lambda` makes it repeatable.\n generator = lambda: ([i] * i for i in range(1, 100))\n elem_sequence = list(generator())\n self._testFromGenerator(generator, elem_sequence, 1)\n self._testFromGenerator(generator, elem_sequence, 5)\n\n def testFromMultipleConcurrentGenerators(self):\n num_inner_repeats = 5\n num_outer_repeats = 100\n\n def generator():\n for i in range(1, 10):\n yield ([i] * i, [i, i ** 2, i ** 3])\n input_list = list(generator())\n\n # The interleave transformation is essentially a flat map that\n # draws from multiple input datasets concurrently (in a cyclic\n # fashion). By placing `Datsaet.from_generator()` inside an\n # interleave, we test its behavior when multiple iterators are\n # active at the same time; by additionally prefetching inside the\n # interleave, we create the possibility of parallel (modulo GIL)\n # invocations to several iterators created by the same dataset.\n def interleave_fn(_):\n return (dataset_ops.Dataset.from_generator(\n generator, output_types=(dtypes.int64, dtypes.int64),\n output_shapes=([None], [3]))\n .repeat(num_inner_repeats).prefetch(5))\n\n iterator = (\n dataset_ops.Dataset.range(num_outer_repeats)\n .interleave(interleave_fn, cycle_length=10,\n block_length=len(input_list))\n .make_initializable_iterator())\n init_op = iterator.initializer\n get_next = iterator.get_next()\n\n with self.test_session() as sess:\n sess.run(init_op)\n for _ in range(num_inner_repeats * num_outer_repeats):\n for elem in input_list:\n val0, val1 = sess.run(get_next)\n self.assertAllEqual(elem[0], val0)\n self.assertAllEqual(elem[1], val1)\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(get_next)\n\n # TODO (b/67868766): Reenable this when the source of flakiness is discovered. id:4166\n # https://github.com/imdone/tensorflow/issues/4164\n def _testFromGeneratorsRunningInParallel(self):\n num_parallel_iterators = 3\n\n # Define shared state that multiple iterator instances will access to\n # demonstrate their concurrent activity.\n lock = threading.Lock()\n condition = threading.Condition(lock)\n next_ticket = [0] # GUARDED_BY(lock)\n\n def generator():\n # NOTE (mrry): We yield one element before the barrier, because id:3563\n # https://github.com/imdone/tensorflow/issues/3562\n # the current implementation of `Dataset.interleave()` must\n # fetch one element from each incoming dataset to start the\n # prefetching.\n yield 0\n\n # Define a barrier that `num_parallel_iterators` iterators must enter\n # before any can proceed. Demonstrates that multiple iterators may be\n # active at the same time.\n condition.acquire()\n ticket = next_ticket[0]\n next_ticket[0] += 1\n if ticket == num_parallel_iterators - 1:\n # The last iterator to join the barrier notifies the others.\n condition.notify_all()\n else:\n # Wait until the last iterator enters the barrier.\n while next_ticket[0] < num_parallel_iterators:\n condition.wait()\n condition.release()\n\n yield 1\n\n # As in `testFromMultipleConcurrentGenerators()`, we use a combination of\n # `Dataset.interleave()` and `Dataset.prefetch()` to cause multiple\n # iterators to be active concurrently.\n def interleave_fn(_):\n return dataset_ops.Dataset.from_generator(\n generator, output_types=dtypes.int64, output_shapes=[]).prefetch(2)\n\n iterator = (\n dataset_ops.Dataset.range(num_parallel_iterators)\n .interleave(\n interleave_fn, cycle_length=num_parallel_iterators, block_length=1)\n .make_initializable_iterator())\n init_op = iterator.initializer\n get_next = iterator.get_next()\n\n with self.test_session() as sess:\n sess.run(init_op)\n for elem in [0, 1]:\n for _ in range(num_parallel_iterators):\n self.assertAllEqual(elem, sess.run(get_next))\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(get_next)\n\n def testFromGeneratorImplicitConversion(self):\n def generator():\n yield [1]\n yield [2]\n yield [3]\n\n for dtype in [dtypes.int8, dtypes.int32, dtypes.int64]:\n iterator = (dataset_ops.Dataset.from_generator(\n generator, output_types=dtype, output_shapes=[1])\n .make_initializable_iterator())\n init_op = iterator.initializer\n get_next = iterator.get_next()\n\n self.assertEqual(dtype, get_next.dtype)\n\n with self.test_session() as sess:\n sess.run(init_op)\n for expected in [[1], [2], [3]]:\n next_val = sess.run(get_next)\n self.assertEqual(dtype.as_numpy_dtype, next_val.dtype)\n self.assertAllEqual(expected, next_val)\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(get_next)\n\n def testFromGeneratorString(self):\n def generator():\n yield \"foo\"\n yield b\"bar\"\n yield u\"baz\"\n\n iterator = (dataset_ops.Dataset.from_generator(\n generator, output_types=dtypes.string, output_shapes=[])\n .make_initializable_iterator())\n init_op = iterator.initializer\n get_next = iterator.get_next()\n\n with self.test_session() as sess:\n sess.run(init_op)\n for expected in [b\"foo\", b\"bar\", b\"baz\"]:\n next_val = sess.run(get_next)\n self.assertAllEqual(expected, next_val)\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(get_next)\n\n def testFromGeneratorTypeError(self):\n def generator():\n yield np.array([1, 2, 3], dtype=np.int64)\n yield np.array([4, 5, 6], dtype=np.int64)\n yield \"ERROR\"\n yield np.array([7, 8, 9], dtype=np.int64)\n\n iterator = (dataset_ops.Dataset.from_generator(\n generator, output_types=dtypes.int64, output_shapes=[3])\n .make_initializable_iterator())\n init_op = iterator.initializer\n get_next = iterator.get_next()\n\n with self.test_session() as sess:\n sess.run(init_op)\n self.assertAllEqual([1, 2, 3], sess.run(get_next))\n self.assertAllEqual([4, 5, 6], sess.run(get_next))\n # NOTE (mrry): Type name in message differs between Python 2 (`long`) and id:2863\n # https://github.com/imdone/tensorflow/issues/2862\n # 3 (`int`).\n with self.assertRaisesOpError(r\"invalid literal for\"):\n sess.run(get_next)\n self.assertAllEqual([7, 8, 9], sess.run(get_next))\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(get_next)\n\n def testFromGeneratorShapeError(self):\n def generator():\n yield np.array([1, 2, 3], dtype=np.int64)\n yield np.array([4, 5, 6], dtype=np.int64)\n yield np.array([7, 8, 9, 10], dtype=np.int64)\n yield np.array([11, 12, 13], dtype=np.int64)\n\n iterator = (dataset_ops.Dataset.from_generator(\n generator, output_types=dtypes.int64, output_shapes=[3])\n .make_initializable_iterator())\n init_op = iterator.initializer\n get_next = iterator.get_next()\n\n with self.test_session() as sess:\n sess.run(init_op)\n self.assertAllEqual([1, 2, 3], sess.run(get_next))\n self.assertAllEqual([4, 5, 6], sess.run(get_next))\n with self.assertRaisesOpError(r\"element of shape \\(3,\\) was expected\"):\n sess.run(get_next)\n self.assertAllEqual([11, 12, 13], sess.run(get_next))\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(get_next)\n\n def testFromGeneratorHeterogeneous(self):\n def generator():\n yield 1\n yield [2, 3]\n\n iterator = (\n dataset_ops.Dataset.from_generator(\n generator, output_types=dtypes.int64).make_initializable_iterator())\n init_op = iterator.initializer\n get_next = iterator.get_next()\n\n with self.test_session() as sess:\n sess.run(init_op)\n self.assertAllEqual(1, sess.run(get_next))\n self.assertAllEqual([2, 3], sess.run(get_next))\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(get_next)\n\n def testFromGeneratorStopShort(self):\n\n def generator():\n yield 0\n yield 1\n yield 2\n\n iterator = (\n dataset_ops.Dataset.from_generator(\n generator, output_types=dtypes.int64).make_initializable_iterator())\n init_op = iterator.initializer\n get_next = iterator.get_next()\n\n with self.test_session() as sess:\n sess.run(init_op)\n self.assertAllEqual(0, sess.run(get_next))\n self.assertAllEqual(1, sess.run(get_next))\n\n def testFromGeneratorDestructorCalled(self):\n # Use an `Event` to signal that the generator has been deleted.\n event = threading.Event()\n\n class GeneratorWrapper(object):\n\n def __iter__(self):\n return self\n\n def next(self):\n return self.__next__()\n\n def __next__(self):\n return 42\n\n def __del__(self):\n event.set()\n\n iterator = dataset_ops.Dataset.from_generator(\n GeneratorWrapper,\n output_types=dtypes.int64).take(2).make_initializable_iterator()\n init_op = iterator.initializer\n get_next = iterator.get_next()\n\n with session.Session() as sess:\n sess.run(init_op)\n self.assertAllEqual(42, sess.run(get_next))\n self.assertAllEqual(42, sess.run(get_next))\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(get_next)\n # Test that `GeneratorWrapper` object is destroyed when the\n # iterator terminates (and the generator iterator is deleted).\n self.assertTrue(event.is_set())\n\n def testGeneratorDatasetFinalizeFunctionCalled(self):\n # NOTE (mrry): This test tests the internal `_GeneratorDataset`, id:3083\n # https://github.com/imdone/tensorflow/issues/3082\n # which affords more control over what the finalize function can do than\n # the `Dataset.from_generator()` wrapper.\n\n # Use an `Event` to signal that the generator has been deleted.\n event = threading.Event()\n\n def finalize_fn(_):\n def finalize_py_func():\n event.set()\n return 0\n return script_ops.py_func(finalize_py_func, [], [dtypes.int64],\n stateful=True)\n\n dummy = constant_op.constant(37)\n iterator = (dataset_ops._GeneratorDataset(dummy, lambda x: x,\n lambda x: x, finalize_fn)\n .take(2)\n .make_initializable_iterator())\n init_op = iterator.initializer\n get_next = iterator.get_next()\n\n with self.test_session() as sess:\n sess.run(init_op)\n self.assertAllEqual(37, sess.run(get_next))\n self.assertAllEqual(37, sess.run(get_next))\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(get_next)\n self.assertTrue(event.is_set())\n\n\nif __name__ == \"__main__\":\n test.main()\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\"\"\"Timeline visualization for TensorFlow using Chrome Trace Format.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport copy\nimport json\nimport re\n\n# The timeline target is usually imported as part of BUILD target\n# \"platform_test\", which includes also includes the \"platform\"\n# dependency. This is why the logging import here is okay.\nfrom tensorflow.python.platform import tf_logging as logging\n\n\nclass AllocationMaximum(collections.namedtuple(\n 'AllocationMaximum', ('timestamp', 'num_bytes', 'tensors'))):\n \"\"\"Stores the maximum allocation for a given allocator within the timelne.\n\n Parameters:\n timestamp: `tensorflow::Env::NowMicros()` when this maximum was reached.\n num_bytes: the total memory used at this time.\n tensors: the set of tensors allocated at this time.\n \"\"\"\n pass\n\n\nclass StepStatsAnalysis(collections.namedtuple(\n 'StepStatsAnalysis', ('chrome_trace', 'allocator_maximums'))):\n \"\"\"Stores the step stats analysis output.\n\n Parameters:\n chrome_trace: A dict containing the chrome trace analysis.\n allocator_maximums: A dict mapping allocator names to AllocationMaximum.\n \"\"\"\n pass\n\n\nclass _ChromeTraceFormatter(object):\n \"\"\"A helper class for generating traces in Chrome Trace Format.\"\"\"\n\n def __init__(self, show_memory=False):\n \"\"\"Constructs a new Chrome Trace formatter.\"\"\"\n self._show_memory = show_memory\n self._events = []\n self._metadata = []\n\n def _create_event(self, ph, category, name, pid, tid, timestamp):\n \"\"\"Creates a new Chrome Trace event.\n\n For details of the file format, see:\n https://github.com/catapult-project/catapult/blob/master/tracing/README.md\n\n Args:\n ph: The type of event - usually a single character.\n category: The event category as a string.\n name: The event name as a string.\n pid: Identifier of the process generating this event as an integer.\n tid: Identifier of the thread generating this event as an integer.\n timestamp: The timestamp of this event as a long integer.\n\n Returns:\n A JSON compatible event object.\n \"\"\"\n event = {}\n event['ph'] = ph\n event['cat'] = category\n event['name'] = name\n event['pid'] = pid\n event['tid'] = tid\n event['ts'] = timestamp\n return event\n\n def emit_pid(self, name, pid):\n \"\"\"Adds a process metadata event to the trace.\n\n Args:\n name: The process name as a string.\n pid: Identifier of the process as an integer.\n \"\"\"\n event = {}\n event['name'] = 'process_name'\n event['ph'] = 'M'\n event['pid'] = pid\n event['args'] = {'name': name}\n self._metadata.append(event)\n\n def emit_tid(self, name, pid, tid):\n \"\"\"Adds a thread metadata event to the trace.\n\n Args:\n name: The thread name as a string.\n pid: Identifier of the process as an integer.\n tid: Identifier of the thread as an integer.\n \"\"\"\n event = {}\n event['name'] = 'thread_name'\n event['ph'] = 'M'\n event['pid'] = pid\n event['tid'] = tid\n event['args'] = {'name': name}\n self._metadata.append(event)\n\n def emit_region(self, timestamp, duration, pid, tid, category, name, args):\n \"\"\"Adds a region event to the trace.\n\n Args:\n timestamp: The start timestamp of this region as a long integer.\n duration: The duration of this region as a long integer.\n pid: Identifier of the process generating this event as an integer.\n tid: Identifier of the thread generating this event as an integer.\n category: The event category as a string.\n name: The event name as a string.\n args: A JSON-compatible dictionary of event arguments.\n \"\"\"\n event = self._create_event('X', category, name, pid, tid, timestamp)\n event['dur'] = duration\n event['args'] = args\n self._events.append(event)\n\n def emit_obj_create(self, category, name, timestamp, pid, tid, object_id):\n \"\"\"Adds an object creation event to the trace.\n\n Args:\n category: The event category as a string.\n name: The event name as a string.\n timestamp: The timestamp of this event as a long integer.\n pid: Identifier of the process generating this event as an integer.\n tid: Identifier of the thread generating this event as an integer.\n object_id: Identifier of the object as an integer.\n \"\"\"\n event = self._create_event('N', category, name, pid, tid, timestamp)\n event['id'] = object_id\n self._events.append(event)\n\n def emit_obj_delete(self, category, name, timestamp, pid, tid, object_id):\n \"\"\"Adds an object deletion event to the trace.\n\n Args:\n category: The event category as a string.\n name: The event name as a string.\n timestamp: The timestamp of this event as a long integer.\n pid: Identifier of the process generating this event as an integer.\n tid: Identifier of the thread generating this event as an integer.\n object_id: Identifier of the object as an integer.\n \"\"\"\n event = self._create_event('D', category, name, pid, tid, timestamp)\n event['id'] = object_id\n self._events.append(event)\n\n def emit_obj_snapshot(self, category, name, timestamp, pid, tid, object_id,\n snapshot):\n \"\"\"Adds an object snapshot event to the trace.\n\n Args:\n category: The event category as a string.\n name: The event name as a string.\n timestamp: The timestamp of this event as a long integer.\n pid: Identifier of the process generating this event as an integer.\n tid: Identifier of the thread generating this event as an integer.\n object_id: Identifier of the object as an integer.\n snapshot: A JSON-compatible representation of the object.\n \"\"\"\n event = self._create_event('O', category, name, pid, tid, timestamp)\n event['id'] = object_id\n event['args'] = {'snapshot': snapshot}\n self._events.append(event)\n\n def emit_flow_start(self, name, timestamp, pid, tid, flow_id):\n \"\"\"Adds a flow start event to the trace.\n\n When matched with a flow end event (with the same 'flow_id') this will\n cause the trace viewer to draw an arrow between the start and end events.\n\n Args:\n name: The event name as a string.\n timestamp: The timestamp of this event as a long integer.\n pid: Identifier of the process generating this event as an integer.\n tid: Identifier of the thread generating this event as an integer.\n flow_id: Identifier of the flow as an integer.\n \"\"\"\n event = self._create_event('s', 'DataFlow', name, pid, tid, timestamp)\n event['id'] = flow_id\n self._events.append(event)\n\n def emit_flow_end(self, name, timestamp, pid, tid, flow_id):\n \"\"\"Adds a flow end event to the trace.\n\n When matched with a flow start event (with the same 'flow_id') this will\n cause the trace viewer to draw an arrow between the start and end events.\n\n Args:\n name: The event name as a string.\n timestamp: The timestamp of this event as a long integer.\n pid: Identifier of the process generating this event as an integer.\n tid: Identifier of the thread generating this event as an integer.\n flow_id: Identifier of the flow as an integer.\n \"\"\"\n event = self._create_event('t', 'DataFlow', name, pid, tid, timestamp)\n event['id'] = flow_id\n self._events.append(event)\n\n def emit_counter(self, category, name, pid, timestamp, counter, value):\n \"\"\"Emits a record for a single counter.\n\n Args:\n category: The event category as a string.\n name: The event name as a string.\n pid: Identifier of the process generating this event as an integer.\n timestamp: The timestamp of this event as a long integer.\n counter: Name of the counter as a string.\n value: Value of the counter as an integer.\n \"\"\"\n event = self._create_event('C', category, name, pid, 0, timestamp)\n event['args'] = {counter: value}\n self._events.append(event)\n\n def emit_counters(self, category, name, pid, timestamp, counters):\n \"\"\"Emits a counter record for the dictionary 'counters'.\n\n Args:\n category: The event category as a string.\n name: The event name as a string.\n pid: Identifier of the process generating this event as an integer.\n timestamp: The timestamp of this event as a long integer.\n counters: Dictionary of counter values.\n \"\"\"\n event = self._create_event('C', category, name, pid, 0, timestamp)\n event['args'] = counters.copy()\n self._events.append(event)\n\n def format_to_string(self, pretty=False):\n \"\"\"Formats the chrome trace to a string.\n\n Args:\n pretty: (Optional.) If True, produce human-readable JSON output.\n\n Returns:\n A JSON-formatted string in Chrome Trace format.\n \"\"\"\n trace = {}\n trace['traceEvents'] = self._metadata + self._events\n if pretty:\n return json.dumps(trace, indent=4, separators=(',', ': '))\n else:\n return json.dumps(trace, separators=(',', ':'))\n\n\nclass _TensorTracker(object):\n \"\"\"An internal class to track the lifetime of a Tensor.\"\"\"\n\n def __init__(self, name, object_id, timestamp, pid, allocator, num_bytes):\n \"\"\"Creates an object to track tensor references.\n\n This class is not thread safe and is intended only for internal use by\n the 'Timeline' class in this file.\n\n Args:\n name: The name of the Tensor as a string.\n object_id: Chrome Trace object identifier assigned for this Tensor.\n timestamp: The creation timestamp of this event as a long integer.\n pid: Process identifier of the associated device, as an integer.\n allocator: Name of the allocator used to create the Tensor.\n num_bytes: Number of bytes allocated (long integer).\n\n Returns:\n A 'TensorTracker' object.\n \"\"\"\n self._name = name\n self._pid = pid\n self._object_id = object_id\n self._create_time = timestamp\n self._allocator = allocator\n self._num_bytes = num_bytes\n self._ref_times = []\n self._unref_times = []\n\n @property\n def name(self):\n \"\"\"Name of this tensor.\"\"\"\n return self._name\n\n @property\n def pid(self):\n \"\"\"ID of the process which created this tensor (an integer).\"\"\"\n return self._pid\n\n @property\n def create_time(self):\n \"\"\"Timestamp when this tensor was created (long integer).\"\"\"\n return self._create_time\n\n @property\n def object_id(self):\n \"\"\"Returns the object identifier of this tensor (integer).\"\"\"\n return self._object_id\n\n @property\n def num_bytes(self):\n \"\"\"Size of this tensor in bytes (long integer).\"\"\"\n return self._num_bytes\n\n @property\n def allocator(self):\n \"\"\"Name of the allocator used to create this tensor (string).\"\"\"\n return self._allocator\n\n @property\n def last_unref(self):\n \"\"\"Last unreference timestamp of this tensor (long integer).\"\"\"\n return max(self._unref_times)\n\n def add_ref(self, timestamp):\n \"\"\"Adds a reference to this tensor with the specified timestamp.\n\n Args:\n timestamp: Timestamp of object reference as an integer.\n \"\"\"\n self._ref_times.append(timestamp)\n\n def add_unref(self, timestamp):\n \"\"\"Adds an unref to this tensor with the specified timestamp.\n\n Args:\n timestamp: Timestamp of object unreference as an integer.\n \"\"\"\n self._unref_times.append(timestamp)\n\n\nclass Timeline(object):\n \"\"\"A class for visualizing execution timelines of TensorFlow steps.\"\"\"\n\n def __init__(self, step_stats, graph=None):\n \"\"\"Constructs a new Timeline.\n\n A 'Timeline' is used for visualizing the execution of a TensorFlow\n computation. It shows the timings and concurrency of execution at\n the granularity of TensorFlow Ops.\n This class is not thread safe.\n\n Args:\n step_stats: The 'StepStats' proto recording execution times.\n graph: (Optional) The 'Graph' that was executed.\n \"\"\"\n\n self._step_stats = step_stats\n self._graph = graph\n self._chrome_trace = _ChromeTraceFormatter()\n self._next_pid = 0\n self._device_pids = {} # device name -> pid for compute activity.\n self._tensor_pids = {} # device name -> pid for tensors.\n self._tensors = {} # tensor_name -> TensorTracker\n self._next_flow_id = 0\n self._flow_starts = {} # tensor_name -> (timestamp, pid, tid)\n self._alloc_times = {} # tensor_name -> ( time, allocator, size )\n self._allocator_maximums = {} # allocator name => maximum bytes long\n\n def _alloc_pid(self):\n \"\"\"Allocate a process Id.\"\"\"\n pid = self._next_pid\n self._next_pid += 1\n return pid\n\n def _alloc_flow_id(self):\n \"\"\"Allocate a flow Id.\"\"\"\n flow_id = self._next_flow_id\n self._next_flow_id += 1\n return flow_id\n\n def _parse_op_label(self, label):\n \"\"\"Parses the fields in a node timeline label.\"\"\"\n # Expects labels of the form: name = op(arg, arg, ...).\n match = re.match(r'(.*) = (.*)\\((.*)\\)', label)\n if match is None:\n return 'unknown', 'unknown', []\n nn, op, inputs = match.groups()\n if not inputs:\n inputs = []\n else:\n inputs = inputs.split(', ')\n return nn, op, inputs\n\n def _assign_lanes(self):\n \"\"\"Assigns non-overlapping lanes for the activities on each device.\"\"\"\n for device_stats in self._step_stats.dev_stats:\n # TODO (pbar): Genuine thread IDs in NodeExecStats might be helpful. id:2813\n # https://github.com/imdone/tensorflow/issues/2812\n lanes = [0]\n for ns in device_stats.node_stats:\n l = -1\n for (i, lts) in enumerate(lanes):\n if ns.all_start_micros > lts:\n l = i\n lanes[l] = ns.all_start_micros + ns.all_end_rel_micros\n break\n if l < 0:\n l = len(lanes)\n lanes.append(ns.all_start_micros + ns.all_end_rel_micros)\n ns.thread_id = l\n\n def _emit_op(self, nodestats, pid, is_gputrace):\n \"\"\"Generates a Chrome Trace event to show Op execution.\n\n Args:\n nodestats: The 'NodeExecStats' proto recording op execution.\n pid: The pid assigned for the device where this op ran.\n is_gputrace: If True then this op came from the GPUTracer.\n \"\"\"\n node_name = nodestats.node_name\n start = nodestats.all_start_micros\n duration = nodestats.all_end_rel_micros\n tid = nodestats.thread_id\n inputs = []\n if is_gputrace:\n # Node names should always have the form 'name:op'.\n fields = node_name.split(':') + ['unknown']\n node_name, op = fields[:2]\n elif node_name == 'RecvTensor':\n # RPC tracing does not use the standard timeline_label format.\n op = 'RecvTensor'\n else:\n _, op, inputs = self._parse_op_label(nodestats.timeline_label)\n args = {'name': node_name, 'op': op}\n for i, iname in enumerate(inputs):\n args['input%d' % i] = iname\n self._chrome_trace.emit_region(start, duration, pid, tid, 'Op', op, args)\n\n def _emit_tensor_snapshot(self, tensor, timestamp, pid, tid, value):\n \"\"\"Generate Chrome Trace snapshot event for a computed Tensor.\n\n Args:\n tensor: A 'TensorTracker' object.\n timestamp: The timestamp of this snapshot as a long integer.\n pid: The pid assigned for showing the device where this op ran.\n tid: The tid of the thread computing the tensor snapshot.\n value: A JSON-compliant snapshot of the object.\n \"\"\"\n desc = str(value.tensor_description).replace('\"', '')\n snapshot = {'tensor_description': desc}\n self._chrome_trace.emit_obj_snapshot('Tensor', tensor.name, timestamp, pid,\n tid, tensor.object_id, snapshot)\n\n def _produce_tensor(self, name, timestamp, tensors_pid, allocator, num_bytes):\n object_id = len(self._tensors)\n tensor = _TensorTracker(name, object_id, timestamp, tensors_pid, allocator,\n num_bytes)\n self._tensors[name] = tensor\n return tensor\n\n def _is_gputrace_device(self, device_name):\n \"\"\"Returns true if this device is part of the GPUTracer logging.\"\"\"\n return '/stream:' in device_name or '/memcpy' in device_name\n\n def _allocate_pids(self):\n \"\"\"Allocate fake process ids for each device in the StepStats.\"\"\"\n self._allocators_pid = self._alloc_pid()\n self._chrome_trace.emit_pid('Allocators', self._allocators_pid)\n\n # Add processes in the Chrome trace to show compute and data activity.\n for dev_stats in self._step_stats.dev_stats:\n device_pid = self._alloc_pid()\n self._device_pids[dev_stats.device] = device_pid\n tensors_pid = self._alloc_pid()\n self._tensor_pids[dev_stats.device] = tensors_pid\n self._chrome_trace.emit_pid(dev_stats.device + ' Compute', device_pid)\n self._chrome_trace.emit_pid(dev_stats.device + ' Tensors', tensors_pid)\n\n def _analyze_tensors(self, show_memory):\n \"\"\"Analyze tensor references to track dataflow.\"\"\"\n for dev_stats in self._step_stats.dev_stats:\n device_pid = self._device_pids[dev_stats.device]\n tensors_pid = self._tensor_pids[dev_stats.device]\n for node_stats in dev_stats.node_stats:\n tid = node_stats.thread_id\n node_name = node_stats.node_name\n start_time = node_stats.all_start_micros\n end_time = node_stats.all_start_micros + node_stats.all_end_rel_micros\n for index, output in enumerate(node_stats.output):\n if index:\n output_name = '%s:%d' % (node_name, index)\n else:\n output_name = node_name\n\n allocation = output.tensor_description.allocation_description\n num_bytes = allocation.requested_bytes\n allocator_name = allocation.allocator_name\n tensor = self._produce_tensor(output_name, start_time, tensors_pid,\n allocator_name, num_bytes)\n tensor.add_ref(start_time)\n tensor.add_unref(end_time)\n self._flow_starts[output_name] = (end_time, device_pid, tid)\n\n if show_memory:\n self._chrome_trace.emit_obj_create('Tensor', output_name,\n start_time, tensors_pid, tid,\n tensor.object_id)\n self._emit_tensor_snapshot(tensor, end_time - 1, tensors_pid, tid,\n output)\n\n def _show_compute(self, show_dataflow):\n \"\"\"Visualize the computation activity.\"\"\"\n for dev_stats in self._step_stats.dev_stats:\n device_name = dev_stats.device\n device_pid = self._device_pids[device_name]\n is_gputrace = self._is_gputrace_device(device_name)\n\n for node_stats in dev_stats.node_stats:\n tid = node_stats.thread_id\n start_time = node_stats.all_start_micros\n end_time = node_stats.all_start_micros + node_stats.all_end_rel_micros\n self._emit_op(node_stats, device_pid, is_gputrace)\n\n if is_gputrace or node_stats.node_name == 'RecvTensor':\n continue\n\n _, _, inputs = self._parse_op_label(node_stats.timeline_label)\n for input_name in inputs:\n if input_name not in self._tensors:\n # This can happen when partitioning has inserted a Send/Recv.\n # We remove the numeric suffix so that the dataflow appears to\n # come from the original node. Ideally, the StepStats would\n # contain logging for the Send and Recv nodes.\n index = input_name.rfind('/_')\n if index > 0:\n input_name = input_name[:index]\n\n if input_name in self._tensors:\n tensor = self._tensors[input_name]\n tensor.add_ref(start_time)\n tensor.add_unref(end_time - 1)\n\n if show_dataflow:\n # We use a different flow ID for every graph edge.\n create_time, create_pid, create_tid = self._flow_starts[\n input_name]\n # Don't add flows when producer and consumer ops are on the same\n # pid/tid since the horizontal arrows clutter the visualization.\n if create_pid != device_pid or create_tid != tid:\n flow_id = self._alloc_flow_id()\n self._chrome_trace.emit_flow_start(input_name, create_time,\n create_pid, create_tid,\n flow_id)\n self._chrome_trace.emit_flow_end(input_name, start_time,\n device_pid, tid, flow_id)\n else:\n logging.vlog(1, 'Can\\'t find tensor %s - removed by CSE?',\n input_name)\n\n def _show_memory_counters(self):\n \"\"\"Produce a counter series for each memory allocator.\"\"\"\n # Iterate over all tensor trackers to build a list of allocations and\n # frees for each allocator. Then sort the lists and emit a cumulative\n # counter series for each allocator.\n allocations = {}\n for name in self._tensors:\n tensor = self._tensors[name]\n self._chrome_trace.emit_obj_delete('Tensor', name, tensor.last_unref,\n tensor.pid, 0, tensor.object_id)\n allocator = tensor.allocator\n if allocator not in allocations:\n allocations[allocator] = []\n num_bytes = tensor.num_bytes\n allocations[allocator].append((tensor.create_time, num_bytes, name))\n allocations[allocator].append((tensor.last_unref, -num_bytes, name))\n\n alloc_maxes = {}\n\n # Generate a counter series showing total allocations for each allocator.\n for allocator in allocations:\n alloc_list = allocations[allocator]\n alloc_list.sort()\n total_bytes = 0\n alloc_tensor_set = set()\n alloc_maxes[allocator] = AllocationMaximum(\n timestamp=0, num_bytes=0, tensors=set())\n for time, num_bytes, name in alloc_list:\n total_bytes += num_bytes\n if num_bytes < 0:\n alloc_tensor_set.discard(name)\n else:\n alloc_tensor_set.add(name)\n\n if total_bytes > alloc_maxes[allocator].num_bytes:\n alloc_maxes[allocator] = AllocationMaximum(\n timestamp=time,\n num_bytes=total_bytes,\n tensors=copy.deepcopy(alloc_tensor_set))\n\n self._chrome_trace.emit_counter('Memory', allocator,\n self._allocators_pid, time, allocator,\n total_bytes)\n self._allocator_maximums = alloc_maxes\n\n def analyze_step_stats(self, show_dataflow=True, show_memory=True):\n self._allocate_pids()\n self._assign_lanes()\n self._analyze_tensors(show_memory)\n self._show_compute(show_dataflow)\n if show_memory:\n self._show_memory_counters()\n return StepStatsAnalysis(\n chrome_trace=self._chrome_trace,\n allocator_maximums=self._allocator_maximums)\n\n def generate_chrome_trace_format(self, show_dataflow=True, show_memory=False):\n \"\"\"Produces a trace in Chrome Trace Format.\n\n Args:\n show_dataflow: (Optional.) If True, add flow events to the trace\n connecting producers and consumers of tensors.\n show_memory: (Optional.) If True, add object snapshot events to the trace\n showing the sizes and lifetimes of tensors.\n\n Returns:\n A JSON formatted string in Chrome Trace format.\n \"\"\"\n step_stats_analysis = self.analyze_step_stats(\n show_dataflow=show_dataflow, show_memory=show_memory)\n\n return step_stats_analysis.chrome_trace.format_to_string(pretty=True)\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\"\"\"Handles function calls, by generating compiled function names and calls.\n\nNote: this transformer does not rename the top level object being converted;\nthat is the caller's responsibility.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom collections import namedtuple\n\nimport gast\n\nfrom tensorflow.contrib.autograph.pyct import anno\nfrom tensorflow.contrib.autograph.pyct import ast_util\nfrom tensorflow.contrib.autograph.pyct import inspect_utils\nfrom tensorflow.contrib.autograph.pyct import parser\nfrom tensorflow.contrib.autograph.pyct import templates\nfrom tensorflow.contrib.autograph.pyct import transformer\nfrom tensorflow.python.util import tf_inspect\n\n\nclass FunctionInfo(namedtuple('FunctionInfo', ('dtype',))):\n pass\n\n\n# TODO (mdan): Move this to config.py. id:589\n# https://github.com/imdone/tensorflow/issues/590\nKNOWN_NUMPY_FUNCTIONS = {\n ('numpy', 'random', 'binomial'): FunctionInfo(dtype='tf.int64'),\n}\n\n\nclass FunctionNamer(object):\n \"\"\"Describes the interface for CallTreeTransformer's namer.\"\"\"\n\n def compiled_function_name(self,\n original_fqn,\n live_entity=None,\n owner_type=None):\n \"\"\"Generate the name corresponding to the compiled version of a function.\n\n Args:\n original_fqn: string or tuple(string)\n live_entity: Callable, the actual target function, if known.\n owner_type: Optional object. If present, it indicates that the function is\n a member of the given type.\n Returns:\n string, bool\n \"\"\"\n raise NotImplementedError()\n\n def compiled_class_name(self, original_fqn, live_entity=None):\n \"\"\"Generate the name corresponding to the compiled version of a class.\n\n Args:\n original_fqn: string or tuple(string)\n live_entity: The actual target class, if known.\n Returns:\n string\n \"\"\"\n raise NotImplementedError()\n\n\nclass CallTreeTransformer(transformer.Base):\n \"\"\"Transforms the call tree by renaming transformed symbols.\"\"\"\n\n def __init__(self, context, uncompiled_modules, nocompile_decorators):\n super(CallTreeTransformer, self).__init__(context)\n self.uncompiled_modules = uncompiled_modules\n self.nocompile_decorators = nocompile_decorators\n\n def _resolve_name(self, node):\n \"\"\"Used to resolve decorator info.\"\"\"\n if isinstance(node, gast.Call):\n return self._resolve_name(node.func)\n if isinstance(node, gast.Name):\n return self.context.namespace.get(node.id)\n if isinstance(node, gast.Attribute):\n parent = self._resolve_name(node.value)\n if parent is not None:\n return getattr(parent, node.attr)\n return None\n raise ValueError(node)\n\n def _try_resolve_target(self, node):\n \"\"\"Works for methods of objects of known type.\"\"\"\n if anno.hasanno(node, 'live_val'):\n return anno.getanno(node, 'live_val')\n if isinstance(node, gast.Attribute) and anno.hasanno(node, 'type'):\n owner_type = anno.getanno(node, 'type')\n if hasattr(owner_type, node.attr):\n return getattr(owner_type, node.attr)\n else:\n raise ValueError('Type \"%s\" has not attribute \"%s\". Is it dynamic?' %\n (owner_type, node.attr))\n return None\n\n def _function_is_compilable(self, target_entity):\n \"\"\"Determines whether an entity can be compiled at all.\"\"\"\n # TODO (mdan): This is just a placeholder. Implement. id:642\n # https://github.com/imdone/tensorflow/issues/643\n return not inspect_utils.isbuiltin(target_entity)\n\n def _should_compile(self, node, fqn):\n \"\"\"Determines whether an entity should be compiled in the context.\"\"\"\n # TODO (mdan): Needs cleanup. We should remove the use of fqn altogether. id:489\n # https://github.com/imdone/tensorflow/issues/490\n module_name = fqn[0]\n for mod in self.uncompiled_modules:\n if module_name.startswith(mod[0] + '.'):\n return False\n\n for i in range(1, len(fqn)):\n if fqn[:i] in self.uncompiled_modules:\n return False\n\n # Check for local decorations\n if anno.hasanno(node, 'graph_ready'):\n return False\n\n # The decorators themselves are not to be converted.\n # If present, the decorators should appear as static functions.\n target_entity = self._try_resolve_target(node.func)\n if target_entity is not None:\n # This attribute is set by the decorator itself.\n # TODO (mdan): This may not play nicely with other wrapping decorators. id:480\n # https://github.com/imdone/tensorflow/issues/481\n if hasattr(target_entity, '__pyct_is_compile_decorator'):\n return False\n\n if target_entity in self.nocompile_decorators:\n return False\n\n # Inspect the target function decorators. If any include a @convert\n # or @graph_ready annotation, then they must be called as they are.\n # TODO (mdan): This may be quite heavy. id:952\n # https://github.com/imdone/tensorflow/issues/953\n # To parse and re-analyze each function for every call site could be quite\n # wasteful. Maybe we could cache the parsed AST?\n try:\n target_node, _ = parser.parse_entity(target_entity)\n target_node = target_node.body[0]\n except TypeError:\n # Functions whose source we cannot access are compilable (e.g. wrapped\n # to py_func).\n return True\n\n for dec in target_node.decorator_list:\n decorator_fn = self._resolve_name(dec)\n if (decorator_fn is not None and\n decorator_fn in self.nocompile_decorators):\n return False\n\n return True\n\n def _rename_compilable_function(self, node):\n assert anno.hasanno(node.func, 'live_val')\n assert anno.hasanno(node.func, 'fqn')\n target_entity = anno.getanno(node.func, 'live_val')\n target_fqn = anno.getanno(node.func, 'fqn')\n\n if not self._should_compile(node, target_fqn):\n return node\n\n if anno.hasanno(node, 'is_constructor'):\n new_name = self.context.namer.compiled_class_name(\n target_fqn, live_entity=target_entity)\n do_rename = True\n else:\n if anno.hasanno(node.func, 'parent_type'):\n owner_type = anno.getanno(node.func, 'parent_type')\n else:\n # Fallback - not reliable.\n owner_type = inspect_utils.getmethodclass(target_entity)\n new_name, do_rename = self.context.namer.compiled_function_name(\n target_fqn, live_entity=target_entity, owner_type=owner_type)\n\n if do_rename:\n if target_entity is not None:\n if tf_inspect.ismethod(target_entity):\n # The renaming process will transform it into a regular function.\n # TODO (mdan): Is this complete? How does it work with nested members? id:593\n # https://github.com/imdone/tensorflow/issues/594\n node.args = [node.func.value] + node.args\n node.func = templates.replace('func_name', func_name=new_name)[0]\n return node\n\n def _wrap_to_py_func_no_return(self, node):\n # TODO (mdan): Properly handle varargs, etc. id:644\n # https://github.com/imdone/tensorflow/issues/645\n template = \"\"\"\n ag__.utils.wrap_py_func(func, None, (args,), kwargs, True)\n \"\"\"\n return templates.replace(\n template,\n func=node.func,\n args=node.args,\n kwargs=ast_util.keywords_to_dict(node.keywords))\n\n def _wrap_to_py_func_single_return(self, node, dtype):\n # TODO (mdan): Properly handle varargs, etc. id:492\n # https://github.com/imdone/tensorflow/issues/493\n template = \"\"\"\n ag__.utils.wrap_py_func(func, dtype, (args,), kwargs, False)\n \"\"\"\n return templates.replace_as_expression(\n template,\n func=node.func,\n dtype=parser.parse_expression(dtype),\n args=node.args,\n kwargs=ast_util.keywords_to_dict(node.keywords))\n\n def _insert_dynamic_conversion(self, node):\n \"\"\"Inlines a dynamic conversion for a dynamic function.\"\"\"\n # TODO (mdan): Pass information on the statically compiled functions. id:483\n # https://github.com/imdone/tensorflow/issues/484\n # Having access to the statically compiled functions can help avoid\n # unnecessary compilation.\n # For example, this would lead to function `a` being compiled twice:\n # \n # def a():\n # v = b\n # b()\n # def b():\n # a()\n # \n # This is really a problem with recursive calls, which currently can\n # only be gated by a static condition, and should be rare.\n # TODO (mdan): It probably makes sense to use dynamic conversion every time. id:954\n # https://github.com/imdone/tensorflow/issues/955\n # Before we could convert all the time though, we'd need a reasonable\n # caching mechanism.\n template = \"\"\"\n ag__.converted_call(func, True, False, {}, args)\n \"\"\"\n call_expr = templates.replace(template, func=node.func, args=node.args)\n new_call = call_expr[0].value\n # TODO (mdan): Improve the template mechanism to better support this. id:595\n # https://github.com/imdone/tensorflow/issues/596\n new_call.keywords = node.keywords\n return new_call\n\n def visit_Expr(self, node):\n if isinstance(node.value, gast.Call):\n if anno.hasanno(node.value.func, 'live_val'):\n target_entity = anno.getanno(node.value.func, 'live_val')\n if not self._function_is_compilable(target_entity):\n if anno.hasanno(node.value.func, 'fqn'):\n target_fqn = anno.getanno(node.value.func, 'fqn')\n if not self._should_compile(node.value, target_fqn):\n return node\n node = self._wrap_to_py_func_no_return(node.value)\n return node\n # Only the case of py_func with no return value is special.\n # Everything else is processed by visit_Call.\n self.visit(node.value)\n else:\n self.generic_visit(node)\n return node\n\n def visit_Call(self, node):\n # If the function is wrapped by one of the marker decorators,\n # consider it graph ready.\n if anno.hasanno(node.func, 'live_val'):\n target_entity = anno.getanno(node.func, 'live_val')\n if target_entity in self.nocompile_decorators:\n if len(node.args) < 1:\n raise ValueError(\n 'Found call to decorator function \"%s\", but it had no arguments. '\n 'A decorator needs at least an argument.')\n anno.setanno(node.args[0], 'graph_ready', True)\n\n self.generic_visit(node)\n if anno.hasanno(node.func, 'live_val'):\n target_entity = anno.getanno(node.func, 'live_val')\n if anno.hasanno(node.func, 'fqn'):\n target_fqn = anno.getanno(node.func, 'fqn')\n else:\n target_fqn = None\n if self._function_is_compilable(target_entity):\n node = self._rename_compilable_function(node)\n elif target_fqn and target_fqn in KNOWN_NUMPY_FUNCTIONS:\n # TODO (mdan): Should we replace these with equivalent TF ops instead? id:647\n # https://github.com/imdone/tensorflow/issues/648\n node = self._wrap_to_py_func_single_return(\n node, KNOWN_NUMPY_FUNCTIONS[target_fqn].dtype)\n else:\n raise NotImplementedError(\n 'py_func with return values (unknown function)')\n else:\n if ast_util.matches(node, 'super(_)'):\n # super() calls are preserved. The class conversion mechanism will\n # ensure that they return the correct value.\n pass\n elif self.context.recursive:\n node = self._insert_dynamic_conversion(node)\n else:\n # Unresolved functions are allowed in non-recursive mode.\n pass\n return node\n\n\ndef transform(node, context, uncompiled_modules, nocompile_decorators):\n \"\"\"Transform function call to the compiled counterparts.\n\n Args:\n node: AST to transform.\n context: An EntityContext object.\n uncompiled_modules: set of string tuples, each tuple represents the fully\n qualified name of a package containing functions that will not be\n compiled.\n nocompile_decorators: A tuple containing decorators to be stripped from\n functions during conversion.\n Returns:\n A tuple (node, new_names):\n node: The transformed AST\n new_names: set(string), containing any newly-generated names\n \"\"\"\n t = CallTreeTransformer(context, uncompiled_modules, nocompile_decorators)\n node = t.visit(node)\n return node\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\"\"\"Variables. See the @{$python/state_ops} guide.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.ops import gen_resource_variable_ops\nfrom tensorflow.python.ops import gen_state_ops\n# go/tf-wildcard-import\n# pylint: disable=wildcard-import\nfrom tensorflow.python.ops.gen_state_ops import *\nfrom tensorflow.python.util.tf_export import tf_export\n# pylint: enable=wildcard-import\n\n\n# pylint: disable=protected-access,g-doc-return-or-yield,g-doc-args\ndef variable_op(shape, dtype, name=\"Variable\", set_shape=True, container=\"\",\n shared_name=\"\"):\n \"\"\"Deprecated. Used variable_op_v2 instead.\"\"\"\n if not set_shape:\n shape = tensor_shape.unknown_shape()\n ret = gen_state_ops.variable(shape=shape, dtype=dtype, name=name,\n container=container, shared_name=shared_name)\n # TODO (mrry): Move this to where it is used, so we can get rid of this op id:4313\n # https://github.com/imdone/tensorflow/issues/4311\n # wrapper?\n if set_shape:\n ret.set_shape(shape)\n return ret\n\n\ndef variable_op_v2(shape, dtype, name=\"Variable\", container=\"\", shared_name=\"\"):\n \"\"\"Create a variable Operation.\n\n See also variables.Variable.\n\n Args:\n shape: The shape of the tensor managed by this variable\n dtype: The underlying type of the tensor values.\n name: optional name to use for the variable op.\n container: An optional string. Defaults to \"\".\n If non-empty, this variable is placed in the given container.\n Otherwise, a default container is used.\n shared_name: An optional string. Defaults to \"\".\n If non-empty, this variable is named in the given bucket\n with this shared_name. Otherwise, the node name is used instead.\n\n Returns:\n A variable tensor.\n \"\"\"\n return gen_state_ops.variable_v2(\n shape=shape,\n dtype=dtype,\n name=name,\n container=container,\n shared_name=shared_name)\n\n\ndef init_variable(v, init, name=\"init\"):\n \"\"\"Initializes variable with \"init\".\n\n This op does the following:\n if init is a Tensor, v = init\n if callable(init): v = init(VariableShape(v), v.dtype)\n\n Args:\n v: Variable to initialize\n init: Tensor to assign to v,\n Or an object convertible to Tensor e.g. nparray,\n Or an Initializer that generates a tensor given the shape and type of v.\n An \"Initializer\" is a callable that returns a tensor that \"v\" should be\n set to. It will be called as init(shape, dtype).\n name: Optional name for the op.\n\n Returns:\n The operation that initializes v.\n \"\"\"\n with ops.name_scope(None, v.op.name + \"/\", [v, init]):\n with ops.name_scope(name) as scope:\n with ops.colocate_with(v):\n if callable(init):\n assert v.get_shape().is_fully_defined(), \"Variable shape unknown.\"\n # TODO (mrry): Convert to v.shape when the property and id:3964\n # https://github.com/imdone/tensorflow/issues/3962\n # accessor are reconciled (and all initializers support\n # tf.TensorShape objects).\n value = init(v.get_shape().as_list(), v.dtype.base_dtype)\n value = ops.convert_to_tensor(value, name=\"value\")\n return gen_state_ops.assign(v, value, name=scope)\n else:\n init = ops.convert_to_tensor(init, name=\"init\")\n return gen_state_ops.assign(v, init, name=scope)\n\n\ndef is_variable_initialized(ref, name=None):\n \"\"\"Checks whether a tensor has been initialized.\n\n Outputs boolean scalar indicating whether the tensor has been initialized.\n\n Args:\n ref: A mutable `Tensor`.\n Should be from a `Variable` node. May be uninitialized.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `bool`.\n \"\"\"\n if ref.dtype._is_ref_dtype:\n return gen_state_ops.is_variable_initialized(ref=ref, name=name)\n # Handle resource variables.\n if context.executing_eagerly() or ref.op.type == \"VarHandleOp\":\n return gen_resource_variable_ops.var_is_initialized_op(ref.handle,\n name=name)\n\n\n@tf_export(\"assign_sub\")\ndef assign_sub(ref, value, use_locking=None, name=None):\n \"\"\"Update 'ref' by subtracting 'value' from it.\n\n This operation outputs \"ref\" after the update is done.\n This makes it easier to chain operations that need to use the reset value.\n\n Args:\n ref: A mutable `Tensor`. Must be one of the following types:\n `float32`, `float64`, `int64`, `int32`, `uint8`, `uint16`, `int16`,\n `int8`, `complex64`, `complex128`, `qint8`, `quint8`, `qint32`, `half`.\n Should be from a `Variable` node.\n value: A `Tensor`. Must have the same type as `ref`.\n The value to be subtracted to the variable.\n use_locking: An optional `bool`. Defaults to `False`.\n If True, the subtraction will be protected by a lock;\n otherwise the behavior is undefined, but may exhibit less contention.\n name: A name for the operation (optional).\n\n Returns:\n Same as \"ref\". Returned as a convenience for operations that want\n to use the new value after the variable has been updated.\n \"\"\"\n if ref.dtype._is_ref_dtype:\n return gen_state_ops.assign_sub(\n ref, value, use_locking=use_locking, name=name)\n return ref.assign_sub(value)\n\n\n@tf_export(\"assign_add\")\ndef assign_add(ref, value, use_locking=None, name=None):\n \"\"\"Update 'ref' by adding 'value' to it.\n\n This operation outputs \"ref\" after the update is done.\n This makes it easier to chain operations that need to use the reset value.\n\n Args:\n ref: A mutable `Tensor`. Must be one of the following types:\n `float32`, `float64`, `int64`, `int32`, `uint8`, `uint16`, `int16`,\n `int8`, `complex64`, `complex128`, `qint8`, `quint8`, `qint32`, `half`.\n Should be from a `Variable` node.\n value: A `Tensor`. Must have the same type as `ref`.\n The value to be added to the variable.\n use_locking: An optional `bool`. Defaults to `False`.\n If True, the addition will be protected by a lock;\n otherwise the behavior is undefined, but may exhibit less contention.\n name: A name for the operation (optional).\n\n Returns:\n Same as \"ref\". Returned as a convenience for operations that want\n to use the new value after the variable has been updated.\n \"\"\"\n if ref.dtype._is_ref_dtype:\n return gen_state_ops.assign_add(\n ref, value, use_locking=use_locking, name=name)\n return ref.assign_add(value)\n\n\n@tf_export(\"assign\")\ndef assign(ref, value, validate_shape=None, use_locking=None, name=None):\n \"\"\"Update 'ref' by assigning 'value' to it.\n\n This operation outputs a Tensor that holds the new value of 'ref' after\n the value has been assigned. This makes it easier to chain operations\n that need to use the reset value.\n\n Args:\n ref: A mutable `Tensor`.\n Should be from a `Variable` node. May be uninitialized.\n value: A `Tensor`. Must have the same type as `ref`.\n The value to be assigned to the variable.\n validate_shape: An optional `bool`. Defaults to `True`.\n If true, the operation will validate that the shape\n of 'value' matches the shape of the Tensor being assigned to. If false,\n 'ref' will take on the shape of 'value'.\n use_locking: An optional `bool`. Defaults to `True`.\n If True, the assignment will be protected by a lock;\n otherwise the behavior is undefined, but may exhibit less contention.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` that will hold the new value of 'ref' after\n the assignment has completed.\n \"\"\"\n if ref.dtype._is_ref_dtype:\n return gen_state_ops.assign(\n ref, value, use_locking=use_locking, name=name,\n validate_shape=validate_shape)\n return ref.assign(value, name=name)\n\n\n@tf_export(\"count_up_to\")\ndef count_up_to(ref, limit, name=None):\n r\"\"\"Increments 'ref' until it reaches 'limit'.\n\n Args:\n ref: A Variable. Must be one of the following types: `int32`, `int64`.\n Should be from a scalar `Variable` node.\n limit: An `int`.\n If incrementing ref would bring it above limit, instead generates an\n 'OutOfRange' error.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor`. Has the same type as `ref`.\n A copy of the input before increment. If nothing else modifies the\n input, the values produced will all be distinct.\n \"\"\"\n if ref.dtype._is_ref_dtype:\n return gen_state_ops.count_up_to(ref, limit=limit, name=name)\n return gen_state_ops.resource_count_up_to(\n ref.handle, limit, T=ref.dtype, name=name)\n\n\n@tf_export(\"scatter_update\")\ndef scatter_update(ref, indices, updates, use_locking=True, name=None):\n # pylint: disable=line-too-long\n r\"\"\"Applies sparse updates to a variable reference.\n\n This operation computes\n\n ```python\n # Scalar indices\n ref[indices, ...] = updates[...]\n\n # Vector indices (for each i)\n ref[indices[i], ...] = updates[i, ...]\n\n # High rank indices (for each i, ..., j)\n ref[indices[i, ..., j], ...] = updates[i, ..., j, ...]\n ```\n\n This operation outputs `ref` after the update is done.\n This makes it easier to chain operations that need to use the reset value.\n\n If values in `ref` is to be updated more than once, because there are\n duplicate entries in `indices`, the order at which the updates happen\n for each value is undefined.\n\n Requires `updates.shape = indices.shape + ref.shape[1:]`.\n\n <div style=\"width:70%; margin:auto; margin-bottom:10px; margin-top:20px;\">\n <img style=\"width:100%\" src=\"https://www.tensorflow.org/images/ScatterUpdate.png\" alt>\n </div>\n\n Args:\n ref: A `Variable`.\n indices: A `Tensor`. Must be one of the following types: `int32`, `int64`.\n A tensor of indices into the first dimension of `ref`.\n updates: A `Tensor`. Must have the same type as `ref`.\n A tensor of updated values to store in `ref`.\n use_locking: An optional `bool`. Defaults to `True`.\n If True, the assignment will be protected by a lock;\n otherwise the behavior is undefined, but may exhibit less contention.\n name: A name for the operation (optional).\n\n Returns:\n Same as `ref`. Returned as a convenience for operations that want\n to use the updated values after the update is done.\n \"\"\"\n if ref.dtype._is_ref_dtype:\n return gen_state_ops.scatter_update(ref, indices, updates,\n use_locking=use_locking, name=name)\n return ref._lazy_read(gen_resource_variable_ops.resource_scatter_update( # pylint: disable=protected-access\n ref.handle, indices, ops.convert_to_tensor(updates, ref.dtype),\n name=name))\n\n\n@tf_export(\"scatter_nd_update\")\ndef scatter_nd_update(ref, indices, updates, use_locking=True, name=None):\n r\"\"\"Applies sparse `updates` to individual values or slices in a Variable.\n\n `ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`.\n\n `indices` must be integer tensor, containing indices into `ref`.\n It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`.\n\n The innermost dimension of `indices` (with length `K`) corresponds to\n indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th\n dimension of `ref`.\n\n `updates` is `Tensor` of rank `Q-1+P-K` with shape:\n\n ```\n [d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]].\n ```\n\n For example, say we want to update 4 scattered elements to a rank-1 tensor to\n 8 elements. In Python, that update would look like this:\n\n ```python\n ref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8])\n indices = tf.constant([[4], [3], [1] ,[7]])\n updates = tf.constant([9, 10, 11, 12])\n update = tf.scatter_nd_update(ref, indices, updates)\n with tf.Session() as sess:\n print sess.run(update)\n ```\n\n The resulting update to ref would look like this:\n\n [1, 11, 3, 10, 9, 6, 7, 12]\n\n See @{tf.scatter_nd} for more details about how to make updates to\n slices.\n\n Args:\n ref: A Variable.\n indices: A `Tensor`. Must be one of the following types: `int32`, `int64`.\n A Tensor. Must be one of the following types: int32, int64.\n A tensor of indices into ref.\n updates: A `Tensor`. Must have the same type as `ref`.\n A Tensor. Must have the same type as ref. A tensor of updated\n values to add to ref.\n use_locking: An optional `bool`. Defaults to `True`.\n An optional bool. Defaults to True. If True, the assignment will\n be protected by a lock; otherwise the behavior is undefined,\n but may exhibit less contention.\n name: A name for the operation (optional).\n\n Returns:\n The value of the variable after the update.\n \"\"\"\n if ref.dtype._is_ref_dtype:\n return gen_state_ops.scatter_nd_update(\n ref, indices, updates, use_locking, name)\n with ops.control_dependencies([gen_state_ops.resource_scatter_nd_update(\n ref.handle, indices, ops.convert_to_tensor(updates, dtype=ref.dtype),\n use_locking, name)]):\n return ref.read_value()\n\n\n@tf_export(\"scatter_add\")\ndef scatter_add(ref, indices, updates, use_locking=False, name=None):\n # pylint: disable=line-too-long\n r\"\"\"Adds sparse updates to the variable referenced by `resource`.\n\n This operation computes\n\n ```python\n # Scalar indices\n ref[indices, ...] += updates[...]\n\n # Vector indices (for each i)\n ref[indices[i], ...] += updates[i, ...]\n\n # High rank indices (for each i, ..., j)\n ref[indices[i, ..., j], ...] += updates[i, ..., j, ...]\n ```\n\n This operation outputs `ref` after the update is done.\n This makes it easier to chain operations that need to use the updated value.\n Duplicate entries are handled correctly: if multiple `indices` reference\n the same location, their contributions add.\n\n Requires `updates.shape = indices.shape + ref.shape[1:]`.\n\n <div style=\"width:70%; margin:auto; margin-bottom:10px; margin-top:20px;\">\n <img style=\"width:100%\" src='https://www.tensorflow.org/images/ScatterAdd.png' alt>\n </div>\n\n Args:\n ref: A `Variable`.\n indices: A `Tensor`. Must be one of the following types: `int32`, `int64`.\n A tensor of indices into the first dimension of `ref`.\n updates: A `Tensor`. Must have the same type as `ref`.\n A tensor of updated values to store in `ref`.\n use_locking: An optional `bool`. Defaults to `True`.\n If True, the assignment will be protected by a lock;\n otherwise the behavior is undefined, but may exhibit less contention.\n name: A name for the operation (optional).\n\n Returns:\n Same as `ref`. Returned as a convenience for operations that want\n to use the updated values after the update is done.\n \"\"\"\n if ref.dtype._is_ref_dtype:\n return gen_state_ops.scatter_add(ref, indices, updates,\n use_locking=use_locking, name=name)\n return ref._lazy_read(gen_resource_variable_ops.resource_scatter_add( # pylint: disable=protected-access\n ref.handle, indices, ops.convert_to_tensor(updates, ref.dtype),\n name=name))\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 Recurrent ops.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\n\nfrom six.moves import xrange # pylint: disable=redefined-builtin\n\nfrom tensorflow.contrib.recurrent.python.ops import recurrent\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import function\nfrom tensorflow.python.framework import random_seed\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 import random_ops\nfrom tensorflow.python.platform import test as test_lib\nfrom tensorflow.python.platform import tf_logging as logging\n\n\n_ElmanState = collections.namedtuple('ElmanState', ('h'))\n_ElmanTheta = collections.namedtuple('ElmanTheta', ('w', 'b'))\n_ElmanInputs = collections.namedtuple('ElmanInputs', ('x'))\n\n\n# TODO (drpng): add test for max length computation. id:1710\n# https://github.com/imdone/tensorflow/issues/1710\nclass RecurrentTest(test_util.TensorFlowTestCase):\n\n def testBasic(self):\n # pylint:disable=invalid-name\n _PolyState = collections.namedtuple('PolyState', ('value', 'x_power'))\n _PolyTheta = collections.namedtuple('PolyTheta', ('x'))\n _PolyInputs = collections.namedtuple('PolyInputs', ('coeff'))\n # pylint:enable=invalid-name\n\n def Poly(theta, state, inputs):\n next_state = _PolyState(\n value=state.value + inputs.coeff * state.x_power,\n x_power=state.x_power * theta.x)\n return next_state, []\n\n with self.test_session() as sess:\n theta = _PolyTheta(x=array_ops.constant(2.0))\n state = _PolyState(\n value=array_ops.constant(0.0),\n x_power=array_ops.constant(1.0))\n inputs = _PolyInputs(coeff=array_ops.constant([1., 2., 3.]))\n\n # x = 2\n # 1 + 2*x + 3*x^2\n ret = recurrent.Recurrent(theta, state, inputs, Poly)\n\n acc, state = sess.run(ret)\n self.assertAllClose(acc.value, [1., 5., 17.])\n self.assertAllClose(acc.x_power, [2., 4., 8.])\n self.assertAllClose(state.value, 17.)\n self.assertAllClose(state.x_power, 8.)\n\n y = ret[1].value\n dx, d_coeff = gradients_impl.gradients(ys=[y], xs=[theta.x, inputs.coeff])\n dx_val, d_coeff_val = sess.run([dx, d_coeff])\n\n # 2 + 6*x\n self.assertAllClose(dx_val, 14.)\n self.assertAllClose(d_coeff_val, [1., 2., 4.])\n\n # acc = [1, 1+2x, 1+2x+3x^2]\n # sum(acc) = 3 + 4x + 3x^2\n acc = ret[0].value\n dx, d_coeff = gradients_impl.gradients(\n ys=[math_ops.reduce_sum(acc)], xs=[theta.x, inputs.coeff])\n dx_val, d_coeff_val = sess.run([dx, d_coeff])\n # 4 + 6*x\n self.assertAllClose(dx_val, 16.)\n self.assertAllClose(d_coeff_val, [3., 4., 4.])\n\n @staticmethod\n def Rand(shape):\n return random_ops.random_uniform(\n shape, minval=-0.2, maxval=0.2, dtype=dtypes.float64)\n\n @staticmethod\n def Elman(theta, state0, inputs):\n h0, w, b, x = state0.h, theta.w, theta.b, inputs.x\n xw = math_ops.matmul(array_ops.concat([x, h0], axis=1), w)\n h1 = math_ops.sigmoid(xw + b)\n state1 = _ElmanState(h=h1)\n return (state1, state1)\n\n @staticmethod\n def ElmanGrad(theta, state0, inputs, extras, dstate1):\n\n @function.Defun()\n def Grad(h0, w, b, x, h1, dh1):\n del b\n # We hand-roll the gradient for the 2nd half of the cell as a demo.\n dxwb = (dh1 * (1 - h1) * h1)\n dxw, db = dxwb, math_ops.reduce_sum(dxwb, axis=0)\n\n # Uses tf.gradient for the 1nd half of the cell as a demo.\n xw = math_ops.matmul(array_ops.concat([x, h0], axis=1), w)\n dh0, dx, dw = gradients_impl.gradients(\n ys=[xw], xs=[h0, x, w], grad_ys=[dxw])\n\n return dh0, dx, dw, db\n\n dh0, dx, dw, db = Grad(state0.h, theta.w, theta.b, inputs.x,\n extras.h, dstate1.h)\n dstate0 = _ElmanState(h=dh0)\n dinputs = _ElmanInputs(x=dx)\n return (_ElmanTheta(w=dw, b=db), dstate0, dinputs)\n\n @staticmethod\n def ElmanOut(state1):\n return _ElmanState(x=state1.h)\n\n @staticmethod\n def ElmanOutGrad(dout):\n return _ElmanState(h=dout.x)\n\n def testElman(self):\n for seqlen, use_grad in [(1, False), (1, True), (7, False), (7, True)]:\n logging.info('== Elman: seqlen=%s, use_grad=%s', seqlen, use_grad)\n self._ParameterizedTestElman(seqlen, use_grad)\n\n def _ParameterizedTestElman(self, seqlen, use_grad):\n\n with self.test_session() as sess:\n random_seed.set_random_seed(342462)\n\n batch = 3\n dims = 4\n theta = _ElmanTheta(w=RecurrentTest.Rand([2 * dims, dims]),\n b=RecurrentTest.Rand([dims]))\n state0 = _ElmanState(h=RecurrentTest.Rand([batch, dims]))\n inputs = _ElmanInputs(x=RecurrentTest.Rand([seqlen, batch, dims]))\n\n # Statically unrolled.\n s = state0\n out = []\n for i in xrange(seqlen):\n inp = _ElmanInputs(x=inputs.x[i, :])\n s, _ = RecurrentTest.Elman(theta, s, inp)\n out += [s.h]\n acc0, final0 = array_ops.stack(out), s.h\n loss0 = math_ops.reduce_sum(acc0) + math_ops.reduce_sum(final0)\n (dw0, db0, dh0, di0) = gradients_impl.gradients(\n loss0, [theta.w, theta.b, state0.h, inputs.x])\n\n acc1, final1 = recurrent.Recurrent(\n theta=theta,\n state0=state0,\n inputs=inputs,\n cell_fn=RecurrentTest.Elman,\n cell_grad=RecurrentTest.ElmanGrad if use_grad else None)\n assert isinstance(acc1, _ElmanState)\n assert isinstance(final1, _ElmanState)\n acc1, final1 = acc1.h, final1.h\n loss1 = math_ops.reduce_sum(acc1) + math_ops.reduce_sum(final1)\n (dw1, db1, dh1, di1) = gradients_impl.gradients(\n loss1, [theta.w, theta.b, state0.h, inputs.x])\n\n # Fetches a few values and compare them.\n (acc0, acc1, final0, final1, dw0, dw1, db0, db1, dh0, dh1, di0,\n di1) = sess.run(\n [acc0, acc1, final0, final1, dw0, dw1, db0, db1, dh0, dh1, di0, di1])\n self.assertAllClose(acc0, acc1)\n self.assertAllClose(final0, final1)\n self.assertAllClose(dw0, dw1)\n self.assertAllClose(db0, db1)\n self.assertAllClose(dh0, dh1)\n self.assertAllClose(di0, di1)\n\nif __name__ == '__main__':\n test_lib.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\"\"\"Operations to emit summaries.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport getpass\nimport os\nimport re\nimport time\n\nimport six\n\nfrom tensorflow.core.framework import graph_pb2\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import smart_cond\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import gen_summary_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import resource_variable_ops\nfrom tensorflow.python.ops import summary_op_util\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.training import training_util\nfrom tensorflow.python.util import tf_contextlib\n\n\n# Name for a collection which is expected to have at most a single boolean\n# Tensor. If this tensor is True the summary ops will record summaries.\n_SHOULD_RECORD_SUMMARIES_NAME = \"ShouldRecordSummaries\"\n\n_SUMMARY_WRITER_INIT_COLLECTION_NAME = \"_SUMMARY_WRITER_V2\"\n\n_EXPERIMENT_NAME_PATTERNS = re.compile(r\"^[^\\x00-\\x1F<>]{0,256}$\")\n_RUN_NAME_PATTERNS = re.compile(r\"^[^\\x00-\\x1F<>]{0,512}$\")\n_USER_NAME_PATTERNS = re.compile(r\"^[a-z]([-a-z0-9]{0,29}[a-z0-9])?$\", re.I)\n\n\ndef should_record_summaries():\n \"\"\"Returns boolean Tensor which is true if summaries should be recorded.\"\"\"\n should_record_collection = ops.get_collection(_SHOULD_RECORD_SUMMARIES_NAME)\n if not should_record_collection:\n return False\n if len(should_record_collection) != 1:\n raise ValueError(\n \"More than one tensor specified for whether summaries \"\n \"should be recorded: %s\" % should_record_collection)\n return should_record_collection[0]\n\n\n# TODO (apassos) consider how to handle local step here. id:3901\n# https://github.com/imdone/tensorflow/issues/3899\n@tf_contextlib.contextmanager\ndef record_summaries_every_n_global_steps(n, global_step=None):\n \"\"\"Sets the should_record_summaries Tensor to true if global_step % n == 0.\"\"\"\n if global_step is None:\n global_step = training_util.get_or_create_global_step()\n collection_ref = ops.get_collection_ref(_SHOULD_RECORD_SUMMARIES_NAME)\n old = collection_ref[:]\n try:\n with ops.device(\"cpu:0\"):\n collection_ref[:] = [math_ops.equal(global_step % n, 0)]\n yield\n finally:\n collection_ref[:] = old\n\n\n@tf_contextlib.contextmanager\ndef always_record_summaries():\n \"\"\"Sets the should_record_summaries Tensor to always true.\"\"\"\n collection_ref = ops.get_collection_ref(_SHOULD_RECORD_SUMMARIES_NAME)\n old = collection_ref[:]\n try:\n collection_ref[:] = [True]\n yield\n finally:\n collection_ref[:] = old\n\n\n@tf_contextlib.contextmanager\ndef never_record_summaries():\n \"\"\"Sets the should_record_summaries Tensor to always false.\"\"\"\n collection_ref = ops.get_collection_ref(_SHOULD_RECORD_SUMMARIES_NAME)\n old = collection_ref[:]\n try:\n collection_ref[:] = [False]\n yield\n finally:\n collection_ref[:] = old\n\n\nclass SummaryWriter(object):\n \"\"\"Encapsulates a stateful summary writer resource.\n\n See also:\n - @{tf.contrib.summary.create_file_writer}\n - @{tf.contrib.summary.create_db_writer}\n \"\"\"\n\n def __init__(self, resource, init_op_fn):\n self._resource = resource\n # TODO (nickfelt): cache constructed ops in graph mode id:4314\n # https://github.com/imdone/tensorflow/issues/4312\n self._init_op_fn = init_op_fn\n if context.executing_eagerly() and self._resource is not None:\n self._resource_deleter = resource_variable_ops.EagerResourceDeleter(\n handle=self._resource, handle_device=\"cpu:0\")\n\n def set_as_default(self):\n \"\"\"Enables this summary writer for the current thread.\"\"\"\n context.context().summary_writer_resource = self._resource\n\n @tf_contextlib.contextmanager\n def as_default(self):\n \"\"\"Enables summary writing within a `with` block.\"\"\"\n if self._resource is None:\n yield self\n else:\n old = context.context().summary_writer_resource\n try:\n context.context().summary_writer_resource = self._resource\n yield self\n # Flushes the summary writer in eager mode or in graph functions, but\n # not in legacy graph mode (you're on your own there).\n with ops.device(\"cpu:0\"):\n gen_summary_ops.flush_summary_writer(self._resource)\n finally:\n context.context().summary_writer_resource = old\n\n\n def init(self):\n \"\"\"Operation to initialize the summary writer resource.\"\"\"\n if self._resource is not None:\n return self._init_op_fn()\n\n def _flush(self):\n return _flush_fn(writer=self)\n\n def flush(self):\n \"\"\"Operation to force the summary writer to flush any buffered data.\"\"\"\n if self._resource is not None:\n return self._flush()\n\n def _close(self):\n with ops.control_dependencies([self.flush()]):\n with ops.device(\"cpu:0\"):\n return gen_summary_ops.close_summary_writer(self._resource)\n\n def close(self):\n \"\"\"Operation to flush and close the summary writer resource.\"\"\"\n if self._resource is not None:\n return self._close()\n\n\ndef initialize(\n graph=None, # pylint: disable=redefined-outer-name\n session=None):\n \"\"\"Initializes summary writing for graph execution mode.\n\n This helper method provides a higher-level alternative to using\n @{tf.contrib.summary.summary_writer_initializer_op} and\n @{tf.contrib.summary.graph}.\n\n Most users will also want to call @{tf.train.create_global_step}\n which can happen before or after this function is called.\n\n Args:\n graph: A @{tf.Graph} or @{tf.GraphDef} to output to the writer.\n This function will not write the default graph by default. When\n writing to an event log file, the associated step will be zero.\n session: So this method can call @{tf.Session.run}. This defaults\n to @{tf.get_default_session}.\n\n Raises:\n RuntimeError: If the current thread has no default\n @{tf.contrib.summary.SummaryWriter}.\n ValueError: If session wasn't passed and no default session.\n \"\"\"\n if context.executing_eagerly():\n return\n if context.context().summary_writer_resource is None:\n raise RuntimeError(\"No default tf.contrib.summary.SummaryWriter found\")\n if session is None:\n session = ops.get_default_session()\n if session is None:\n raise ValueError(\"session must be passed if no default session exists\")\n session.run(summary_writer_initializer_op())\n if graph is not None:\n data = _serialize_graph(graph)\n x = array_ops.placeholder(dtypes.string)\n session.run(_graph(x, 0), feed_dict={x: data})\n\n\ndef create_file_writer(logdir,\n max_queue=None,\n flush_millis=None,\n filename_suffix=None,\n name=None):\n \"\"\"Creates a summary file writer in the current context under the given name.\n\n Args:\n logdir: a string, or None. If a string, creates a summary file writer\n which writes to the directory named by the string. If None, returns\n a mock object which acts like a summary writer but does nothing,\n useful to use as a context manager.\n max_queue: the largest number of summaries to keep in a queue; will\n flush once the queue gets bigger than this. Defaults to 10.\n flush_millis: the largest interval between flushes. Defaults to 120,000.\n filename_suffix: optional suffix for the event file name. Defaults to `.v2`.\n name: Shared name for this SummaryWriter resource stored to default\n Graph. Defaults to the provided logdir prefixed with `logdir:`. Note: if a\n summary writer resource with this shared name already exists, the returned\n SummaryWriter wraps that resource and the other arguments have no effect.\n\n Returns:\n Either a summary writer or an empty object which can be used as a\n summary writer.\n \"\"\"\n if logdir is None:\n return SummaryWriter(None, None)\n with ops.device(\"cpu:0\"):\n if max_queue is None:\n max_queue = constant_op.constant(10)\n if flush_millis is None:\n flush_millis = constant_op.constant(2 * 60 * 1000)\n if filename_suffix is None:\n filename_suffix = constant_op.constant(\".v2\")\n if name is None:\n name = \"logdir:\" + logdir\n return _make_summary_writer(\n name,\n gen_summary_ops.create_summary_file_writer,\n logdir=logdir,\n max_queue=max_queue,\n flush_millis=flush_millis,\n filename_suffix=filename_suffix)\n\n\ndef create_db_writer(db_uri,\n experiment_name=None,\n run_name=None,\n user_name=None,\n name=None):\n \"\"\"Creates a summary database writer in the current context.\n\n This can be used to write tensors from the execution graph directly\n to a database. Only SQLite is supported right now. This function\n will create the schema if it doesn't exist. Entries in the Users,\n Experiments, and Runs tables will be created automatically if they\n don't already exist.\n\n Args:\n db_uri: For example \"file:/tmp/foo.sqlite\".\n experiment_name: Defaults to YYYY-MM-DD in local time if None.\n Empty string means the Run will not be associated with an\n Experiment. Can't contain ASCII control characters or <>. Case\n sensitive.\n run_name: Defaults to HH:MM:SS in local time if None. Empty string\n means a Tag will not be associated with any Run. Can't contain\n ASCII control characters or <>. Case sensitive.\n user_name: Defaults to system username if None. Empty means the\n Experiment will not be associated with a User. Must be valid as\n both a DNS label and Linux username.\n name: Shared name for this SummaryWriter resource stored to default\n @{tf.Graph}.\n\n Returns:\n A @{tf.contrib.summary.SummaryWriter} instance.\n \"\"\"\n with ops.device(\"cpu:0\"):\n if experiment_name is None:\n experiment_name = time.strftime(\"%Y-%m-%d\", time.localtime(time.time()))\n if run_name is None:\n run_name = time.strftime(\"%H:%M:%S\", time.localtime(time.time()))\n if user_name is None:\n user_name = getpass.getuser()\n experiment_name = _cleanse_string(\n \"experiment_name\", _EXPERIMENT_NAME_PATTERNS, experiment_name)\n run_name = _cleanse_string(\"run_name\", _RUN_NAME_PATTERNS, run_name)\n user_name = _cleanse_string(\"user_name\", _USER_NAME_PATTERNS, user_name)\n return _make_summary_writer(\n name,\n gen_summary_ops.create_summary_db_writer,\n db_uri=db_uri,\n experiment_name=experiment_name,\n run_name=run_name,\n user_name=user_name)\n\n\ndef _make_summary_writer(name, factory, **kwargs):\n resource = gen_summary_ops.summary_writer(shared_name=name)\n init_op_fn = lambda: factory(resource, **kwargs)\n # TODO (apassos): Consider doing this instead. id:3966\n # https://github.com/imdone/tensorflow/issues/3964\n # if not context.executing_eagerly():\n # ops.get_default_session().run(init_op)\n ops.add_to_collection(_SUMMARY_WRITER_INIT_COLLECTION_NAME, init_op_fn())\n return SummaryWriter(resource, init_op_fn)\n\n\ndef _cleanse_string(name, pattern, value):\n if isinstance(value, six.string_types) and pattern.search(value) is None:\n raise ValueError(\"%s (%s) must match %s\" % (name, value, pattern.pattern))\n return ops.convert_to_tensor(value, dtypes.string)\n\n\ndef _nothing():\n \"\"\"Convenient else branch for when summaries do not record.\"\"\"\n return constant_op.constant(False)\n\n\ndef all_summary_ops():\n \"\"\"Graph-mode only. Returns all summary ops.\n\n Please note this excludes @{tf.contrib.summary.graph} ops.\n\n Returns:\n The summary ops.\n \"\"\"\n if context.executing_eagerly():\n return None\n return ops.get_collection(ops.GraphKeys._SUMMARY_COLLECTION) # pylint: disable=protected-access\n\n\ndef summary_writer_initializer_op():\n \"\"\"Graph-mode only. Returns the list of ops to create all summary writers.\n\n Returns:\n The initializer ops.\n\n Raises:\n RuntimeError: If in Eager mode.\n \"\"\"\n if context.executing_eagerly():\n raise RuntimeError(\n \"tf.contrib.summary.summary_writer_initializer_op is only \"\n \"supported in graph mode.\")\n return ops.get_collection(_SUMMARY_WRITER_INIT_COLLECTION_NAME)\n\n\ndef summary_writer_function(name, tensor, function, family=None):\n \"\"\"Helper function to write summaries.\n\n Args:\n name: name of the summary\n tensor: main tensor to form the summary\n function: function taking a tag and a scope which writes the summary\n family: optional, the summary's family\n\n Returns:\n The result of writing the summary.\n \"\"\"\n name_scope = ops.get_name_scope()\n if name_scope:\n # Add a slash to allow reentering the name scope.\n name_scope += \"/\"\n def record():\n with ops.name_scope(name_scope), summary_op_util.summary_scope(\n name, family, values=[tensor]) as (tag, scope):\n with ops.control_dependencies([function(tag, scope)]):\n return constant_op.constant(True)\n\n if context.context().summary_writer_resource is None:\n return control_flow_ops.no_op()\n with ops.device(\"cpu:0\"):\n op = smart_cond.smart_cond(\n should_record_summaries(), record, _nothing, name=\"\")\n ops.add_to_collection(ops.GraphKeys._SUMMARY_COLLECTION, op) # pylint: disable=protected-access\n return op\n\n\ndef generic(name, tensor, metadata=None, family=None, step=None):\n \"\"\"Writes a tensor summary if possible.\"\"\"\n\n def function(tag, scope):\n if metadata is None:\n serialized_metadata = constant_op.constant(\"\")\n elif hasattr(metadata, \"SerializeToString\"):\n serialized_metadata = constant_op.constant(metadata.SerializeToString())\n else:\n serialized_metadata = metadata\n # Note the identity to move the tensor to the CPU.\n return gen_summary_ops.write_summary(\n context.context().summary_writer_resource,\n _choose_step(step),\n array_ops.identity(tensor),\n tag,\n serialized_metadata,\n name=scope)\n return summary_writer_function(name, tensor, function, family=family)\n\n\ndef scalar(name, tensor, family=None, step=None):\n \"\"\"Writes a scalar summary if possible.\n\n Unlike @{tf.contrib.summary.generic} this op may change the dtype\n depending on the writer, for both practical and efficiency concerns.\n\n Args:\n name: An arbitrary name for this summary.\n tensor: A @{tf.Tensor} Must be one of the following types:\n `float32`, `float64`, `int32`, `int64`, `uint8`, `int16`,\n `int8`, `uint16`, `half`, `uint32`, `uint64`.\n family: Optional, the summary's family.\n step: The `int64` monotonic step variable, which defaults\n to @{tf.train.get_global_step}.\n\n Returns:\n The created @{tf.Operation} or a @{tf.no_op} if summary writing has\n not been enabled for this context.\n \"\"\"\n\n def function(tag, scope):\n # Note the identity to move the tensor to the CPU.\n return gen_summary_ops.write_scalar_summary(\n context.context().summary_writer_resource,\n _choose_step(step),\n tag,\n array_ops.identity(tensor),\n name=scope)\n\n return summary_writer_function(name, tensor, function, family=family)\n\n\ndef histogram(name, tensor, family=None, step=None):\n \"\"\"Writes a histogram summary if possible.\"\"\"\n\n def function(tag, scope):\n # Note the identity to move the tensor to the CPU.\n return gen_summary_ops.write_histogram_summary(\n context.context().summary_writer_resource,\n _choose_step(step),\n tag,\n array_ops.identity(tensor),\n name=scope)\n\n return summary_writer_function(name, tensor, function, family=family)\n\n\ndef image(name, tensor, bad_color=None, max_images=3, family=None, step=None):\n \"\"\"Writes an image summary if possible.\"\"\"\n\n def function(tag, scope):\n bad_color_ = (constant_op.constant([255, 0, 0, 255], dtype=dtypes.uint8)\n if bad_color is None else bad_color)\n # Note the identity to move the tensor to the CPU.\n return gen_summary_ops.write_image_summary(\n context.context().summary_writer_resource,\n _choose_step(step),\n tag,\n array_ops.identity(tensor),\n bad_color_,\n max_images,\n name=scope)\n\n return summary_writer_function(name, tensor, function, family=family)\n\n\ndef audio(name, tensor, sample_rate, max_outputs, family=None, step=None):\n \"\"\"Writes an audio summary if possible.\"\"\"\n\n def function(tag, scope):\n # Note the identity to move the tensor to the CPU.\n return gen_summary_ops.write_audio_summary(\n context.context().summary_writer_resource,\n _choose_step(step),\n tag,\n array_ops.identity(tensor),\n sample_rate=sample_rate,\n max_outputs=max_outputs,\n name=scope)\n\n return summary_writer_function(name, tensor, function, family=family)\n\n\ndef graph(param, step=None, name=None):\n \"\"\"Writes a TensorFlow graph to the summary interface.\n\n The graph summary is, strictly speaking, not a summary. Conditions\n like @{tf.contrib.summary.never_record_summaries} do not apply. Only\n a single graph can be associated with a particular run. If multiple\n graphs are written, then only the last one will be considered by\n TensorBoard.\n\n When not using eager execution mode, the user should consider passing\n the `graph` parameter to @{tf.contrib.summary.initialize} instead of\n calling this function. Otherwise special care needs to be taken when\n using the graph to record the graph.\n\n Args:\n param: A @{tf.Tensor} containing a serialized graph proto. When\n eager execution is enabled, this function will automatically\n coerce @{tf.Graph}, @{tf.GraphDef}, and string types.\n step: The global step variable. This doesn't have useful semantics\n for graph summaries, but is used anyway, due to the structure of\n event log files. This defaults to the global step.\n name: A name for the operation (optional).\n\n Returns:\n The created @{tf.Operation} or a @{tf.no_op} if summary writing has\n not been enabled for this context.\n\n Raises:\n TypeError: If `param` isn't already a @{tf.Tensor} in graph mode.\n \"\"\"\n if not context.executing_eagerly() and not isinstance(param, ops.Tensor):\n raise TypeError(\"graph() needs a tf.Tensor (e.g. tf.placeholder) in graph \"\n \"mode, but was: %s\" % type(param))\n writer = context.context().summary_writer_resource\n if writer is None:\n return control_flow_ops.no_op()\n with ops.device(\"cpu:0\"):\n if isinstance(param, (ops.Graph, graph_pb2.GraphDef)):\n tensor = ops.convert_to_tensor(_serialize_graph(param), dtypes.string)\n else:\n tensor = array_ops.identity(param)\n return gen_summary_ops.write_graph_summary(\n writer, _choose_step(step), tensor, name=name)\n\n\n_graph = graph # for functions with a graph parameter\n\n\ndef import_event(tensor, name=None):\n \"\"\"Writes a @{tf.Event} binary proto.\n\n When using create_db_writer(), this can be used alongside\n @{tf.TFRecordReader} to load event logs into the database. Please\n note that this is lower level than the other summary functions and\n will ignore any conditions set by methods like\n @{tf.contrib.summary.should_record_summaries}.\n\n Args:\n tensor: A @{tf.Tensor} of type `string` containing a serialized\n @{tf.Event} proto.\n name: A name for the operation (optional).\n\n Returns:\n The created @{tf.Operation}.\n \"\"\"\n return gen_summary_ops.import_event(\n context.context().summary_writer_resource, tensor, name=name)\n\n\ndef flush(writer=None, name=None):\n \"\"\"Forces summary writer to send any buffered data to storage.\n\n This operation blocks until that finishes.\n\n Args:\n writer: The @{tf.contrib.summary.SummaryWriter} resource to flush.\n The thread default will be used if this parameter is None.\n Otherwise a @{tf.no_op} is returned.\n name: A name for the operation (optional).\n\n Returns:\n The created @{tf.Operation}.\n \"\"\"\n if writer is None:\n writer = context.context().summary_writer_resource\n if writer is None:\n return control_flow_ops.no_op()\n else:\n if isinstance(writer, SummaryWriter):\n writer = writer._resource # pylint: disable=protected-access\n with ops.device(\"cpu:0\"):\n return gen_summary_ops.flush_summary_writer(writer, name=name)\n\n\n_flush_fn = flush # for within SummaryWriter.flush()\n\n\ndef eval_dir(model_dir, name=None):\n \"\"\"Construct a logdir for an eval summary writer.\"\"\"\n return os.path.join(model_dir, \"eval\" if not name else \"eval_\" + name)\n\n\ndef create_summary_file_writer(*args, **kwargs):\n \"\"\"Please use @{tf.contrib.summary.create_file_writer}.\"\"\"\n logging.warning(\"Deprecation Warning: create_summary_file_writer was renamed \"\n \"to create_file_writer\")\n return create_file_writer(*args, **kwargs)\n\n\ndef _serialize_graph(arbitrary_graph):\n if isinstance(arbitrary_graph, ops.Graph):\n return arbitrary_graph.as_graph_def(add_shapes=True).SerializeToString()\n else:\n return arbitrary_graph.SerializeToString()\n\n\ndef _choose_step(step):\n if step is None:\n return training_util.get_or_create_global_step()\n if not isinstance(step, ops.Tensor):\n return ops.convert_to_tensor(step, dtypes.int64)\n return step\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\"\"\"Resampling dataset transformations.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.contrib.data.python.ops import batching\nfrom tensorflow.contrib.data.python.ops import interleave_ops\nfrom tensorflow.contrib.data.python.ops import scan_ops\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import logging_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import random_ops\n\n\ndef rejection_resample(class_func, target_dist, initial_dist=None, seed=None):\n \"\"\"A transformation that resamples a dataset to achieve a target distribution.\n\n **NOTE** Resampling is performed via rejection sampling; some fraction\n of the input values will be dropped.\n\n Args:\n class_func: A function mapping an element of the input dataset to a scalar\n `tf.int32` tensor. Values should be in `[0, num_classes)`.\n target_dist: A floating point type tensor, shaped `[num_classes]`.\n initial_dist: (Optional.) A floating point type tensor, shaped\n `[num_classes]`. If not provided, the true class distribution is\n estimated live in a streaming fashion.\n seed: (Optional.) Python integer seed for the resampler.\n\n Returns:\n A `Dataset` transformation function, which can be passed to\n @{tf.data.Dataset.apply}.\n \"\"\"\n def _apply_fn(dataset):\n \"\"\"Function from `Dataset` to `Dataset` that applies the transformation.\"\"\"\n target_dist_t = ops.convert_to_tensor(target_dist, name=\"target_dist\")\n class_values_ds = dataset.map(class_func)\n\n # Get initial distribution.\n if initial_dist is not None:\n initial_dist_t = ops.convert_to_tensor(initial_dist, name=\"initial_dist\")\n acceptance_dist, prob_of_original = (\n _calculate_acceptance_probs_with_mixing(initial_dist_t,\n target_dist_t))\n initial_dist_ds = dataset_ops.Dataset.from_tensors(\n initial_dist_t).repeat()\n acceptance_dist_ds = dataset_ops.Dataset.from_tensors(\n acceptance_dist).repeat()\n prob_of_original_ds = dataset_ops.Dataset.from_tensors(\n prob_of_original).repeat()\n else:\n initial_dist_ds = _estimate_initial_dist_ds(\n target_dist_t, class_values_ds)\n acceptance_and_original_prob_ds = initial_dist_ds.map(\n lambda initial: _calculate_acceptance_probs_with_mixing(\n initial, target_dist_t))\n acceptance_dist_ds = acceptance_and_original_prob_ds.map(\n lambda accept_prob, _: accept_prob)\n prob_of_original_ds = acceptance_and_original_prob_ds.map(\n lambda _, prob_original: prob_original)\n filtered_ds = _filter_ds(dataset, acceptance_dist_ds, initial_dist_ds,\n class_values_ds, seed)\n # Prefetch filtered dataset for speed.\n filtered_ds = filtered_ds.prefetch(3)\n\n prob_original_static = _get_prob_original_static(\n initial_dist_t, target_dist_t) if initial_dist is not None else None\n if prob_original_static == 1:\n return dataset_ops.Dataset.zip((class_values_ds, dataset))\n elif prob_original_static == 0:\n return filtered_ds\n else:\n return interleave_ops.sample_from_datasets(\n [dataset_ops.Dataset.zip((class_values_ds, dataset)), filtered_ds],\n weights=prob_of_original_ds.map(lambda prob: [(prob, 1.0 - prob)]),\n seed=seed)\n\n return _apply_fn\n\n\ndef _get_prob_original_static(initial_dist_t, target_dist_t):\n \"\"\"Returns the static probability of sampling from the original.\n\n `tensor_util.constant_value(prob_of_original)` returns `None` if it encounters\n an Op that it isn't defined for. We have some custom logic to avoid this.\n\n Args:\n initial_dist_t: A tensor of the initial distribution.\n target_dist_t: A tensor of the target distribution.\n\n Returns:\n The probability of sampling from the original distribution as a constant,\n if it is a constant, or `None`.\n \"\"\"\n init_static = tensor_util.constant_value(initial_dist_t)\n target_static = tensor_util.constant_value(target_dist_t)\n\n if init_static is None or target_static is None:\n return None\n else:\n return np.min(target_static / init_static)\n\n\ndef _filter_ds(dataset, acceptance_dist_ds, initial_dist_ds, class_values_ds,\n seed):\n \"\"\"Filters a dataset based on per-class acceptance probabilities.\n\n Args:\n dataset: The dataset to be filtered.\n acceptance_dist_ds: A dataset of acceptance probabilities.\n initial_dist_ds: A dataset of the initial probability distribution, given or\n estimated.\n class_values_ds: A dataset of the corresponding classes.\n seed: (Optional.) Python integer seed for the resampler.\n\n Returns:\n A dataset of (class value, data) after filtering.\n \"\"\"\n def maybe_warn_on_large_rejection(accept_dist, initial_dist):\n proportion_rejected = math_ops.reduce_sum((1 - accept_dist) * initial_dist)\n return control_flow_ops.cond(\n math_ops.less(proportion_rejected, .5),\n lambda: accept_dist,\n lambda: logging_ops.Print( # pylint: disable=g-long-lambda\n accept_dist, [proportion_rejected, initial_dist, accept_dist],\n message=\"Proportion of examples rejected by sampler is high: \",\n summarize=100,\n first_n=10))\n\n acceptance_dist_ds = (dataset_ops.Dataset.zip((acceptance_dist_ds,\n initial_dist_ds))\n .map(maybe_warn_on_large_rejection))\n\n def _gather_and_copy(class_val, acceptance_prob, data):\n return class_val, array_ops.gather(acceptance_prob, class_val), data\n\n current_probabilities_and_class_and_data_ds = dataset_ops.Dataset.zip(\n (class_values_ds, acceptance_dist_ds, dataset)).map(_gather_and_copy)\n filtered_ds = (\n current_probabilities_and_class_and_data_ds\n .filter(lambda _1, p, _2: random_ops.random_uniform([], seed=seed) < p))\n return filtered_ds.map(lambda class_value, _, data: (class_value, data))\n\n\ndef _estimate_initial_dist_ds(\n target_dist_t, class_values_ds, dist_estimation_batch_size=32,\n smoothing_constant=10):\n num_classes = (target_dist_t.shape[0].value or\n array_ops.shape(target_dist_t)[0])\n initial_examples_per_class_seen = array_ops.fill(\n [num_classes], np.int64(smoothing_constant))\n\n def update_estimate_and_tile(num_examples_per_class_seen, c):\n updated_examples_per_class_seen, dist = _estimate_data_distribution(\n c, num_examples_per_class_seen)\n tiled_dist = array_ops.tile(\n array_ops.expand_dims(dist, 0), [dist_estimation_batch_size, 1])\n return updated_examples_per_class_seen, tiled_dist\n\n initial_dist_ds = (class_values_ds.batch(dist_estimation_batch_size)\n .apply(scan_ops.scan(initial_examples_per_class_seen,\n update_estimate_and_tile))\n .apply(batching.unbatch()))\n\n return initial_dist_ds\n\n\ndef _get_target_to_initial_ratio(initial_probs, target_probs):\n # Add tiny to initial_probs to avoid divide by zero.\n denom = (initial_probs + np.finfo(initial_probs.dtype.as_numpy_dtype).tiny)\n return target_probs / denom\n\n\ndef _estimate_data_distribution(c, num_examples_per_class_seen):\n \"\"\"Estimate data distribution as labels are seen.\n\n Args:\n c: The class labels. Type `int32`, shape `[batch_size]`.\n num_examples_per_class_seen: Type `int64`, shape `[num_classes]`,\n containing counts.\n\n Returns:\n num_examples_per_lass_seen: Updated counts. Type `int64`, shape\n `[num_classes]`.\n dist: The updated distribution. Type `float32`, shape `[num_classes]`.\n \"\"\"\n num_classes = num_examples_per_class_seen.get_shape()[0].value\n # Update the class-count based on what labels are seen in batch.\n num_examples_per_class_seen = math_ops.add(\n num_examples_per_class_seen, math_ops.reduce_sum(\n array_ops.one_hot(c, num_classes, dtype=dtypes.int64), 0))\n init_prob_estimate = math_ops.truediv(\n num_examples_per_class_seen,\n math_ops.reduce_sum(num_examples_per_class_seen))\n dist = math_ops.cast(init_prob_estimate, dtypes.float32)\n return num_examples_per_class_seen, dist\n\n\ndef _calculate_acceptance_probs_with_mixing(initial_probs, target_probs):\n \"\"\"Calculates the acceptance probabilities and mixing ratio.\n\n In this case, we assume that we can *either* sample from the original data\n distribution with probability `m`, or sample from a reshaped distribution\n that comes from rejection sampling on the original distribution. This\n rejection sampling is done on a per-class basis, with `a_i` representing the\n probability of accepting data from class `i`.\n\n This method is based on solving the following analysis for the reshaped\n distribution:\n\n Let F be the probability of a rejection (on any example).\n Let p_i be the proportion of examples in the data in class i (init_probs)\n Let a_i is the rate the rejection sampler should *accept* class i\n Let t_i is the target proportion in the minibatches for class i (target_probs)\n\n ```\n F = sum_i(p_i * (1-a_i))\n = 1 - sum_i(p_i * a_i) using sum_i(p_i) = 1\n ```\n\n An example with class `i` will be accepted if `k` rejections occur, then an\n example with class `i` is seen by the rejector, and it is accepted. This can\n be written as follows:\n\n ```\n t_i = sum_k=0^inf(F^k * p_i * a_i)\n = p_i * a_j / (1 - F) using geometric series identity, since 0 <= F < 1\n = p_i * a_i / sum_j(p_j * a_j) using F from above\n ```\n\n Note that the following constraints hold:\n ```\n 0 <= p_i <= 1, sum_i(p_i) = 1\n 0 <= a_i <= 1\n 0 <= t_i <= 1, sum_i(t_i) = 1\n ```\n\n A solution for a_i in terms of the other variables is the following:\n ```a_i = (t_i / p_i) / max_i[t_i / p_i]```\n\n If we try to minimize the amount of data rejected, we get the following:\n\n M_max = max_i [ t_i / p_i ]\n M_min = min_i [ t_i / p_i ]\n\n The desired probability of accepting data if it comes from class `i`:\n\n a_i = (t_i/p_i - m) / (M_max - m)\n\n The desired probability of pulling a data element from the original dataset,\n rather than the filtered one:\n\n m = M_min\n\n Args:\n initial_probs: A Tensor of the initial probability distribution, given or\n estimated.\n target_probs: A Tensor of the corresponding classes.\n\n Returns:\n (A 1D Tensor with the per-class acceptance probabilities, the desired\n probability of pull from the original distribution.)\n \"\"\"\n ratio_l = _get_target_to_initial_ratio(initial_probs, target_probs)\n max_ratio = math_ops.reduce_max(ratio_l)\n min_ratio = math_ops.reduce_min(ratio_l)\n\n # Target prob to sample from original distribution.\n m = min_ratio\n\n # TODO (joelshor): Simplify fraction, if possible. id:1088\n # https://github.com/imdone/tensorflow/issues/1089\n a_i = (ratio_l - m) / (max_ratio - m)\n return a_i, m",
"# 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\"\"\"Various function for graph editing.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.contrib.graph_editor import reroute\nfrom tensorflow.contrib.graph_editor import select\nfrom tensorflow.contrib.graph_editor import subgraph\nfrom tensorflow.contrib.graph_editor import util\nfrom tensorflow.python.ops import array_ops as tf_array_ops\n\n__all__ = [\n \"detach_control_inputs\",\n \"detach_control_outputs\",\n \"detach_inputs\",\n \"detach_outputs\",\n \"detach\",\n \"connect\",\n \"bypass\",\n]\n\n\ndef detach_control_inputs(sgv):\n \"\"\"Detach all the external control inputs of the subgraph sgv.\n\n Args:\n sgv: the subgraph view to be detached. This argument is converted to a\n subgraph using the same rules as the function subgraph.make_view.\n \"\"\"\n sgv = subgraph.make_view(sgv)\n for op in sgv.ops:\n cops = [cop for cop in op.control_inputs if cop not in sgv.ops]\n reroute.remove_control_inputs(op, cops)\n\n\ndef detach_control_outputs(sgv, control_outputs):\n \"\"\"Detach all the external control outputs of the subgraph sgv.\n\n Args:\n sgv: the subgraph view to be detached. This argument is converted to a\n subgraph using the same rules as the function subgraph.make_view.\n control_outputs: a util.ControlOutputs instance.\n \"\"\"\n if not isinstance(control_outputs, util.ControlOutputs):\n raise TypeError(\"Expected a util.ControlOutputs, got: {}\",\n type(control_outputs))\n control_outputs.update()\n sgv = subgraph.make_view(sgv)\n for op in sgv.ops:\n for cop in control_outputs.get(op):\n if cop not in sgv.ops:\n reroute.remove_control_inputs(cop, op)\n\n\ndef detach_inputs(sgv, control_inputs=False):\n \"\"\"Detach the inputs of a subgraph view.\n\n Args:\n sgv: the subgraph view to be detached. This argument is converted to a\n subgraph using the same rules as the function subgraph.make_view.\n Note that sgv is modified in place.\n control_inputs: if True control_inputs are also detached.\n Returns:\n A tuple `(sgv, input_placeholders)` where\n `sgv` is a new subgraph view of the detached subgraph;\n `input_placeholders` is a list of the created input placeholders.\n Raises:\n StandardError: if sgv cannot be converted to a SubGraphView using\n the same rules than the function subgraph.make_view.\n \"\"\"\n sgv = subgraph.make_view(sgv)\n\n with sgv.graph.as_default():\n input_placeholders = [\n tf_array_ops.placeholder(\n dtype=input_t.dtype, name=util.placeholder_name(input_t))\n for input_t in sgv.inputs\n ]\n\n reroute.swap_inputs(sgv, input_placeholders)\n if control_inputs:\n detach_control_inputs(sgv)\n return sgv, input_placeholders\n\n\ndef detach_outputs(sgv, control_outputs=None):\n \"\"\"Detach the output of a subgraph view.\n\n Args:\n sgv: the subgraph view to be detached. This argument is converted to a\n subgraph using the same rules as the function subgraph.make_view.\n Note that sgv is modified in place.\n control_outputs: a util.ControlOutputs instance or None. If not None the\n control outputs are also detached.\n Returns:\n A tuple `(sgv, output_placeholders)` where\n `sgv` is a new subgraph view of the detached subgraph;\n `output_placeholders` is a list of the created output placeholders.\n Raises:\n StandardError: if sgv cannot be converted to a SubGraphView using\n the same rules than the function subgraph.make_view.\n \"\"\"\n sgv = subgraph.make_view(sgv)\n # only select outputs with consumers\n sgv_ = sgv.remap_outputs([output_id\n for output_id, output_t in enumerate(sgv.outputs)\n if output_t.consumers()])\n # create consumer subgraph and remap\n consumers_sgv = subgraph.SubGraphView(sgv_.consumers())\n consumers_sgv = consumers_sgv.remap_inputs(\n [input_id for input_id, input_t in enumerate(consumers_sgv.inputs)\n if input_t in sgv_.outputs])\n\n with sgv_.graph.as_default():\n output_placeholders = [\n util.make_placeholder_from_tensor(input_t)\n for input_t in consumers_sgv.inputs\n ]\n\n reroute.swap_outputs(sgv_, output_placeholders)\n if control_outputs is not None:\n detach_control_outputs(sgv_, control_outputs)\n return sgv_, output_placeholders\n\n\ndef detach(sgv, control_inputs=False, control_outputs=None, control_ios=None):\n \"\"\"Detach both the inputs and the outputs of a subgraph view.\n\n Args:\n sgv: the subgraph view to be detached. This argument is converted to a\n subgraph using the same rules as the function subgraph.make_view.\n Note that sgv is modified in place.\n control_inputs: A boolean indicating whether control inputs are enabled.\n control_outputs: An instance of util.ControlOutputs or None. If not None,\n control outputs are enabled.\n control_ios: An instance of util.ControlOutputs or None. If not None, both\n control inputs and control outputs are enabled. This is equivalent to set\n control_inputs to True and control_outputs to the util.ControlOutputs\n instance.\n Returns:\n A tuple `(sgv, detached_inputs, detached_outputs)` where:\n `sgv` is a new subgraph view of the detached subgraph;\n `detach_inputs` is a list of the created input placeholders;\n `detach_outputs` is a list of the created output placeholders.\n Raises:\n StandardError: if sgv cannot be converted to a SubGraphView using\n the same rules than the function subgraph.make_view.\n \"\"\"\n control_inputs, control_outputs = select.check_cios(control_inputs,\n control_outputs,\n control_ios)\n _, detached_inputs = detach_inputs(sgv, control_inputs)\n _, detached_outputs = detach_outputs(sgv, control_outputs)\n return sgv, detached_inputs, detached_outputs\n\n\ndef connect(sgv0, sgv1, disconnect_first=False):\n \"\"\"Connect the outputs of sgv0 to the inputs of sgv1.\n\n Args:\n sgv0: the first subgraph to have its outputs swapped. This argument is\n converted to a subgraph using the same rules as the function\n subgraph.make_view.\n Note that sgv0 is modified in place.\n sgv1: the second subgraph to have its outputs swapped. This argument is\n converted to a subgraph using the same rules as the function\n subgraph.make_view.\n Note that sgv1 is modified in place.\n disconnect_first: if True the current outputs of sgv0 are disconnected.\n Returns:\n A tuple `(sgv0, sgv1)` of the now connected subgraphs.\n Raises:\n StandardError: if sgv0 or sgv1 cannot be converted to a SubGraphView using\n the same rules than the function subgraph.make_view.\n \"\"\"\n sgv0 = subgraph.make_view(sgv0)\n sgv1 = subgraph.make_view(sgv1)\n util.check_graphs(sgv0, sgv1)\n if disconnect_first:\n detach_outputs(sgv0)\n sgv0_outputs = subgraph.SubGraphView(passthrough_ts=sgv0.outputs)\n reroute.reroute_inputs(sgv0_outputs, sgv1)\n return sgv0, sgv1\n\n\ndef bypass(sgv):\n \"\"\"Bypass the given subgraph by connecting its inputs to its outputs.\n\n Args:\n sgv: the subgraph view to be bypassed. This argument is converted to a\n subgraph using the same rules than the function subgraph.make_view.\n Note that sgv is modified in place.\n Returns:\n A tuple `(sgv, detached_inputs)` where:\n `sgv` is a new subgraph view of the bypassed subgraph;\n `detached_inputs` is a list of the created input placeholders.\n Raises:\n StandardError: if sgv cannot be converted to a SubGraphView using\n the same rules than the function subgraph.make_view.\n \"\"\"\n # TODO (fkp): allows to plug sgv.inputs to individual sgv.outputs consumers id:891\n # https://github.com/imdone/tensorflow/issues/892\n sgv = subgraph.make_view(sgv)\n sgv_inputs = list(sgv.inputs)\n sgv, detached_inputs = detach_inputs(sgv)\n reroute.reroute_ts(sgv_inputs, sgv.outputs)\n return sgv, detached_inputs\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\"\"\"Various context managers.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport contextlib\n\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import tensor_array_ops\n\n\ndef control_dependency_on_returns(return_value):\n \"\"\"Create a TF control dependency on the return values of a function.\n\n If the function had no return value, a no-op context is returned.\n\n Args:\n return_value: The return value to set as control dependency.\n\n Returns:\n A context manager.\n \"\"\"\n def control_dependency_handle(t):\n if isinstance(t, tensor_array_ops.TensorArray):\n return t.flow\n return t\n\n if return_value is None:\n return contextlib.contextmanager(lambda: (yield))()\n # TODO (mdan): Filter to tensor objects. id:706\n # https://github.com/imdone/tensorflow/issues/707\n if not isinstance(return_value, (list, tuple)):\n return_value = (return_value,)\n return_value = tuple(control_dependency_handle(t) for t in return_value)\n return ops.control_dependencies(return_value)\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\"\"\"Reshape bijectors.\"\"\"\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 dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import check_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops.distributions import bijector\n\n\n__all__ = [\n \"Reshape\",\n]\n\n\ndef _static_ndims_from_shape(shape):\n return shape.shape.with_rank_at_least(1)[0].value\n\n\ndef _ndims_from_shape(shape):\n return array_ops.shape(shape)[0]\n\n\nclass Reshape(bijector.Bijector):\n \"\"\"Reshapes the `event_shape` of a `Tensor`.\n\n The semantics generally follow that of `tf.reshape()`, with\n a few differences:\n\n * The user must provide both the input and output shape, so that\n the transformation can be inverted. If an input shape is not\n specified, the default assumes a vector-shaped input, i.e.,\n event_shape_in = (-1,).\n * The `Reshape` bijector automatically broadcasts over the leftmost\n dimensions of its input (`sample_shape` and `batch_shape`); only\n the rightmost `event_ndims_in` dimensions are reshaped. The\n number of dimensions to reshape is inferred from the provided\n `event_shape_in` (`event_ndims_in = len(event_shape_in)`).\n\n Example usage:\n ```python\n\n tfd = tf.contrib.distributions\n\n r = tfd.bijectors.Reshape(event_shape_out=[1, -1])\n\n r.forward([3., 4.]) # shape [2]\n # ==> [[3., 4.]] # shape [1, 2]\n\n r.forward([[1., 2.], [3., 4.]]) # shape [2, 2]\n # ==> [[[1., 2.]],\n # [[3., 4.]]] # shape [2, 1, 2]\n\n r.inverse([[3., 4.]]) # shape [1,2]\n # ==> [3., 4.] # shape [2]\n\n r.forward_log_det_jacobian(any_value)\n # ==> 0.\n\n r.inverse_log_det_jacobian(any_value)\n # ==> 0.\n ```\n\n \"\"\"\n\n def __init__(self, event_shape_out, event_shape_in=(-1,),\n validate_args=False, name=None):\n \"\"\"Creates a `Reshape` bijector.\n\n Args:\n event_shape_out: An `int`-like vector-shaped `Tensor`\n representing the event shape of the transformed output.\n event_shape_in: An optional `int`-like vector-shape `Tensor`\n representing the event shape of the input. This is required in\n order to define inverse operations; the default of (-1,)\n assumes a vector-shaped input.\n validate_args: Python `bool` indicating whether arguments should\n be checked for correctness.\n name: Python `str`, name given to ops managed by this object.\n\n Raises:\n TypeError: if either `event_shape_in` or `event_shape_out` has\n non-integer `dtype`.\n ValueError: if either of `event_shape_in` or `event_shape_out`\n has non-vector shape (`rank > 1`), or if their sizes do not\n match.\n \"\"\"\n with ops.name_scope(name, \"reshape\",\n values=[event_shape_out, event_shape_in]):\n\n event_shape_out = ops.convert_to_tensor(event_shape_out,\n name=\"event_shape_out\",\n preferred_dtype=dtypes.int32)\n event_shape_in = ops.convert_to_tensor(event_shape_in,\n name=\"event_shape_in\",\n preferred_dtype=dtypes.int32)\n\n assertions = []\n assertions.extend(self._maybe_check_valid_shape(\n event_shape_out, validate_args))\n assertions.extend(self._maybe_check_valid_shape(\n event_shape_in, validate_args))\n\n self._assertions = assertions\n self._event_shape_in = event_shape_in\n self._event_shape_out = event_shape_out\n\n super(Reshape, self).__init__(\n forward_min_event_ndims=0,\n is_constant_jacobian=True,\n validate_args=validate_args,\n name=name or \"reshape\")\n\n def _maybe_check_valid_shape(self, shape, validate_args):\n \"\"\"Check that a shape Tensor is int-type and otherwise sane.\"\"\"\n if not shape.dtype.is_integer:\n raise TypeError(\"{} dtype ({}) should be `int`-like.\".format(\n shape, shape.dtype.name))\n\n assertions = []\n\n ndims = array_ops.rank(shape)\n ndims_ = tensor_util.constant_value(ndims)\n if ndims_ is not None and ndims_ > 1:\n raise ValueError(\"`{}` rank ({}) should be <= 1.\".format(\n shape, ndims_))\n elif validate_args:\n assertions.append(check_ops.assert_less_equal(\n ndims, 1, message=\"`{}` rank should be <= 1.\".format(shape)))\n\n shape_ = tensor_util.constant_value_as_shape(shape)\n if shape_.is_fully_defined():\n es = np.int32(shape_.as_list())\n if sum(es == -1) > 1:\n raise ValueError(\n \"`{}` must have at most one `-1` (given {})\"\n .format(shape, es))\n if np.any(es < -1):\n raise ValueError(\n \"`{}` elements must be either positive integers or `-1`\"\n \"(given {}).\"\n .format(shape, es))\n elif validate_args:\n assertions.extend([\n check_ops.assert_less_equal(\n math_ops.reduce_sum(\n math_ops.cast(math_ops.equal(shape, -1), dtypes.int32)),\n 1,\n message=\"`{}` elements must have at most one `-1`.\"\n .format(shape)),\n check_ops.assert_greater_equal(\n shape, -1,\n message=\"`{}` elements must be either positive integers or `-1`.\"\n .format(shape)),\n ])\n return assertions\n\n def _reshape_helper(self, x, event_shape_in, event_shape_out):\n \"\"\"Reshape only the event_shape of an input `Tensor`.\"\"\"\n\n event_ndims_in_ = _static_ndims_from_shape(event_shape_in)\n event_ndims_in = _ndims_from_shape(event_shape_in)\n x_ndims_, x_ndims = x.shape.ndims, array_ops.rank(x)\n\n assertions = []\n\n # Ensure x.event_shape is compatible with event_shape_in.\n if (event_ndims_in_ is not None\n and x_ndims_ is not None\n and x.shape.with_rank_at_least(event_ndims_in_)[\n x_ndims_-event_ndims_in_:].is_fully_defined()):\n x_event_shape_, x_event_shape = [ # pylint: disable=unbalanced-tuple-unpacking\n np.int32(x.shape[x_ndims_-event_ndims_in_:])]*2\n else:\n x_event_shape_, x_event_shape = (\n None, array_ops.shape(x)[x_ndims-event_ndims_in:])\n\n event_shape_in_ = tensor_util.constant_value(event_shape_in)\n\n if x_event_shape_ is not None and event_shape_in_ is not None:\n # Compare the shape dimensions that are fully specified in the\n # input (i.e., for which event_shape_in is not -1). If x_event_shape\n # matches along all of these dimensions, it is compatible with\n # the desired input shape and any further mismatches (i.e.,\n # imcompatibility with the desired *output* shape) will be\n # caught inside of array_ops.reshape() below.\n x_event_shape_specified_ = x_event_shape_[event_shape_in_ >= 0]\n event_shape_in_specified_ = event_shape_in_[event_shape_in_ >= 0]\n if not np.equal(x_event_shape_specified_,\n event_shape_in_specified_).all():\n raise ValueError(\n \"Input `event_shape` does not match `event_shape_in` ({} vs {}).\".\n format(x_event_shape_, event_shape_in_))\n elif self.validate_args:\n # Similarly to the static case, we compare the shape dimensions\n # that are fully specified in the input. We extract these\n # dimensions using boolean_mask(), which requires that the mask\n # have known ndims. We can assume that shape Tensors always have\n # ndims==1 (this assumption is verified inside of\n # _maybe_check_valid_shape), so the reshape operation is just a\n # no-op that formally encodes this fact to make boolean_mask()\n # happy.\n event_shape_mask = array_ops.reshape(event_shape_in >= 0, [-1])\n x_event_shape_specified = array_ops.boolean_mask(x_event_shape,\n event_shape_mask)\n event_shape_in_specified = array_ops.boolean_mask(event_shape_in,\n event_shape_mask)\n assertions.append(check_ops.assert_equal(\n x_event_shape_specified, event_shape_in_specified,\n message=\"Input `event_shape` does not match `event_shape_in`.\"))\n\n if assertions:\n x = control_flow_ops.with_dependencies(assertions, x)\n\n # get the parts of shape(x) that will not change\n sample_and_batch_shape = array_ops.shape(x)\n\n ndims = (x.shape.ndims if x.shape.ndims is not None\n else array_ops.rank(x))\n sample_and_batch_shape = sample_and_batch_shape[\n :(ndims - math_ops.abs(event_ndims_in))]\n\n if (event_ndims_in_ is not None\n and x_ndims_ is not None\n and event_ndims_in_ == x_ndims_):\n # Hack to allow forward/inverse_event_shape to do shape\n # inference by calling this helper method with a dummy Tensor of\n # shape event_shape_in. In this special case,\n # sample_and_batch_shape will be empty so we can preserve static\n # shape information by avoiding the concat operation below\n # (which would be a no-op).\n new_shape = event_shape_out\n else:\n new_shape = array_ops.concat(\n [sample_and_batch_shape, event_shape_out], axis=0)\n\n return array_ops.reshape(x, new_shape)\n\n def _forward(self, x):\n with ops.control_dependencies(self._assertions):\n return self._reshape_helper(x,\n self._event_shape_in,\n self._event_shape_out)\n\n def _inverse(self, y):\n with ops.control_dependencies(self._assertions):\n return self._reshape_helper(y,\n self._event_shape_out,\n self._event_shape_in)\n\n def _inverse_log_det_jacobian(self, y):\n with ops.control_dependencies(self._assertions):\n return constant_op.constant(0., dtype=y.dtype)\n\n def _forward_log_det_jacobian(self, x):\n with ops.control_dependencies(self._assertions):\n return constant_op.constant(0., dtype=x.dtype)\n\n def _forward_event_shape(self, input_shape):\n # NOTE: this method and the other *_event_shape* methods id:663\n # https://github.com/imdone/tensorflow/issues/664\n # compute shape by explicit transformation of a dummy\n # variable. This approach is not generally recommended because it\n # bloats the graph and could in general trigger side effects.\n # \n # In this particular case of the Reshape bijector, the\n # forward and inverse transforms have no side effects, and we\n # believe the reduction in code complexity from delegating the\n # heavy lifting to tf.reshape() is worth the added graph ops.\n # However, you should think hard before implementing this approach\n # in other Bijectors; it is strongly preferred to compute\n # shapes explicitly whenever it's feasible to do so.\n with ops.control_dependencies(self._assertions):\n dummy = array_ops.zeros(dtype=dtypes.float32, shape=input_shape)\n dummy_reshaped = self.forward(dummy)\n return dummy_reshaped.shape\n\n def _inverse_event_shape(self, output_shape):\n with ops.control_dependencies(self._assertions):\n dummy = array_ops.zeros(dtype=dtypes.float32, shape=output_shape)\n dummy_reshaped = self.inverse(dummy)\n return dummy_reshaped.shape\n\n def _forward_event_shape_tensor(self, input_shape):\n with ops.control_dependencies(self._assertions):\n dummy = array_ops.zeros(dtype=dtypes.float32, shape=input_shape)\n dummy_reshaped = self.forward(dummy)\n return array_ops.shape(dummy_reshaped)\n\n def _inverse_event_shape_tensor(self, output_shape):\n with ops.control_dependencies(self._assertions):\n dummy = array_ops.zeros(dtype=dtypes.float32, shape=output_shape)\n dummy_reshaped = self.inverse(dummy)\n return array_ops.shape(dummy_reshaped)\n"
] | [
[
"tensorflow.python.training.saver.BulkSaverBuilder",
"tensorflow.python.ops.variable_scope._get_default_variable_store",
"tensorflow.core.protobuf.checkpointable_object_graph_pb2.CheckpointableObjectGraph",
"tensorflow.python.framework.ops.device",
"tensorflow.python.ops.control_flow_ops.no_op",
"tensorflow.python.eager.context.executing_eagerly",
"tensorflow.python.training.checkpointable._CheckpointPosition",
"tensorflow.core.protobuf.checkpointable_object_graph_pb2.CheckpointableObjectGraph.CheckpointableObject.SlotVariableReference",
"tensorflow.python.ops.resource_variable_ops.ResourceVariable",
"tensorflow.python.training.saver.BaseSaverBuilder.OpListToDict",
"tensorflow.python.util.tf_export.tf_export",
"tensorflow.python.pywrap_tensorflow.NewCheckpointReader",
"tensorflow.python.framework.ops.get_default_session",
"tensorflow.python.util.deprecation.deprecated",
"tensorflow.python.framework.ops.init_scope",
"tensorflow.python.framework.ops.colocate_with",
"tensorflow.python.training.saver.BaseSaverBuilder.SaveSpec",
"tensorflow.python.framework.dtypes.as_dtype",
"tensorflow.python.training.checkpointable._SlotVariableRestoration",
"tensorflow.python.framework.ops.uid",
"tensorflow.python.framework.tensor_shape.as_shape",
"tensorflow.python.training.saver.Saver",
"tensorflow.python.framework.constant_op.constant"
],
[
"tensorflow.contrib.batching.python.ops.batch_ops.batch",
"tensorflow.python.ops.script_ops.py_func",
"tensorflow.python.ops.array_ops.placeholder",
"tensorflow.contrib.batching.python.ops.batch_ops.unbatch",
"tensorflow.python.platform.test.main",
"tensorflow.python.ops.gradients_impl.gradients",
"tensorflow.contrib.batching.python.ops.batch_ops.batch_function"
],
[
"numpy.arange",
"tensorflow.python.ops.script_ops.py_func",
"tensorflow.python.data.ops.dataset_ops.Dataset.from_generator",
"tensorflow.python.data.ops.dataset_ops._GeneratorDataset",
"tensorflow.python.client.session.Session",
"tensorflow.python.platform.test.main",
"tensorflow.python.data.ops.dataset_ops.Dataset.range",
"numpy.array",
"tensorflow.python.framework.constant_op.constant"
],
[
"tensorflow.python.platform.tf_logging.vlog"
],
[
"tensorflow.python.util.tf_inspect.ismethod",
"tensorflow.contrib.autograph.pyct.inspect_utils.isbuiltin",
"tensorflow.contrib.autograph.pyct.anno.hasanno",
"tensorflow.contrib.autograph.pyct.anno.setanno",
"tensorflow.contrib.autograph.pyct.parser.parse_entity",
"tensorflow.contrib.autograph.pyct.ast_util.matches",
"tensorflow.contrib.autograph.pyct.inspect_utils.getmethodclass",
"tensorflow.contrib.autograph.pyct.parser.parse_expression",
"tensorflow.contrib.autograph.pyct.templates.replace",
"tensorflow.contrib.autograph.pyct.ast_util.keywords_to_dict",
"tensorflow.contrib.autograph.pyct.anno.getanno"
],
[
"tensorflow.python.ops.gen_state_ops.resource_count_up_to",
"tensorflow.python.ops.gen_resource_variable_ops.var_is_initialized_op",
"tensorflow.python.ops.gen_state_ops.assign_add",
"tensorflow.python.ops.gen_state_ops.assign",
"tensorflow.python.ops.gen_state_ops.count_up_to",
"tensorflow.python.ops.gen_state_ops.variable_v2",
"tensorflow.python.framework.ops.colocate_with",
"tensorflow.python.ops.gen_state_ops.scatter_add",
"tensorflow.python.util.tf_export.tf_export",
"tensorflow.python.ops.gen_state_ops.scatter_nd_update",
"tensorflow.python.framework.ops.name_scope",
"tensorflow.python.framework.ops.convert_to_tensor",
"tensorflow.python.ops.gen_state_ops.is_variable_initialized",
"tensorflow.python.framework.tensor_shape.unknown_shape",
"tensorflow.python.ops.gen_state_ops.assign_sub",
"tensorflow.python.eager.context.executing_eagerly",
"tensorflow.python.ops.gen_state_ops.variable",
"tensorflow.python.ops.gen_state_ops.scatter_update"
],
[
"tensorflow.python.ops.math_ops.sigmoid",
"tensorflow.python.ops.array_ops.constant",
"tensorflow.python.ops.array_ops.concat",
"tensorflow.python.framework.function.Defun",
"tensorflow.python.platform.tf_logging.info",
"tensorflow.python.framework.random_seed.set_random_seed",
"tensorflow.python.platform.test.main",
"tensorflow.contrib.recurrent.python.ops.recurrent.Recurrent",
"tensorflow.python.ops.gradients_impl.gradients",
"tensorflow.python.ops.random_ops.random_uniform",
"tensorflow.python.ops.math_ops.reduce_sum",
"tensorflow.python.ops.array_ops.stack"
],
[
"tensorflow.python.ops.gen_summary_ops.close_summary_writer",
"tensorflow.python.ops.array_ops.placeholder",
"tensorflow.python.framework.ops.add_to_collection",
"tensorflow.python.framework.ops.device",
"tensorflow.python.ops.resource_variable_ops.EagerResourceDeleter",
"tensorflow.python.ops.control_flow_ops.no_op",
"tensorflow.python.eager.context.context",
"tensorflow.python.eager.context.executing_eagerly",
"tensorflow.python.ops.array_ops.identity",
"tensorflow.python.ops.gen_summary_ops.flush_summary_writer",
"tensorflow.python.framework.ops.get_collection_ref",
"tensorflow.python.framework.ops.get_collection",
"tensorflow.python.framework.ops.get_default_session",
"tensorflow.python.platform.tf_logging.warning",
"tensorflow.python.ops.gen_summary_ops.summary_writer",
"tensorflow.python.ops.math_ops.equal",
"tensorflow.python.framework.ops.convert_to_tensor",
"tensorflow.python.framework.ops.get_name_scope",
"tensorflow.python.ops.summary_op_util.summary_scope",
"tensorflow.python.training.training_util.get_or_create_global_step",
"tensorflow.python.framework.ops.name_scope",
"tensorflow.python.framework.constant_op.constant"
],
[
"tensorflow.python.data.ops.dataset_ops.Dataset.from_tensors",
"tensorflow.contrib.data.python.ops.batching.unbatch",
"tensorflow.python.ops.array_ops.shape",
"tensorflow.python.ops.math_ops.reduce_max",
"tensorflow.python.ops.logging_ops.Print",
"tensorflow.python.ops.math_ops.less",
"numpy.finfo",
"tensorflow.python.ops.array_ops.gather",
"tensorflow.python.ops.math_ops.reduce_min",
"tensorflow.python.framework.tensor_util.constant_value",
"tensorflow.python.ops.array_ops.expand_dims",
"tensorflow.python.ops.math_ops.cast",
"numpy.min",
"tensorflow.python.ops.array_ops.one_hot",
"numpy.int64",
"tensorflow.python.framework.ops.convert_to_tensor",
"tensorflow.contrib.data.python.ops.scan_ops.scan",
"tensorflow.python.data.ops.dataset_ops.Dataset.zip",
"tensorflow.python.ops.random_ops.random_uniform",
"tensorflow.python.ops.math_ops.reduce_sum"
],
[
"tensorflow.contrib.graph_editor.reroute.swap_outputs",
"tensorflow.contrib.graph_editor.util.make_placeholder_from_tensor",
"tensorflow.contrib.graph_editor.reroute.swap_inputs",
"tensorflow.contrib.graph_editor.subgraph.SubGraphView",
"tensorflow.contrib.graph_editor.subgraph.make_view",
"tensorflow.contrib.graph_editor.util.check_graphs",
"tensorflow.contrib.graph_editor.util.placeholder_name",
"tensorflow.contrib.graph_editor.reroute.reroute_inputs",
"tensorflow.contrib.graph_editor.reroute.remove_control_inputs",
"tensorflow.contrib.graph_editor.select.check_cios",
"tensorflow.contrib.graph_editor.reroute.reroute_ts"
],
[
"tensorflow.python.framework.ops.control_dependencies"
],
[
"tensorflow.python.ops.array_ops.shape",
"tensorflow.python.framework.tensor_util.constant_value_as_shape",
"tensorflow.python.ops.array_ops.zeros",
"numpy.any",
"tensorflow.python.ops.array_ops.rank",
"tensorflow.python.ops.math_ops.abs",
"tensorflow.python.ops.control_flow_ops.with_dependencies",
"tensorflow.python.framework.tensor_util.constant_value",
"tensorflow.python.framework.ops.control_dependencies",
"tensorflow.python.ops.math_ops.equal",
"tensorflow.python.ops.check_ops.assert_equal",
"numpy.equal",
"tensorflow.python.framework.ops.convert_to_tensor",
"tensorflow.python.ops.array_ops.concat",
"numpy.int32",
"tensorflow.python.ops.array_ops.reshape",
"tensorflow.python.framework.ops.name_scope",
"tensorflow.python.ops.array_ops.boolean_mask",
"tensorflow.python.framework.constant_op.constant"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.8",
"1.10",
"1.12",
"1.4",
"2.7",
"2.2",
"1.13",
"2.3",
"2.4",
"2.9",
"1.5",
"1.7",
"2.5",
"2.6",
"2.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.13",
"1.5",
"1.7",
"1.2"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"1.12",
"2.6",
"1.4",
"1.13",
"2.3",
"2.4",
"2.2",
"2.9",
"1.5",
"1.7",
"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": [
"1.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.7"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.13",
"1.10",
"1.12"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"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": [
"1.10",
"1.12",
"1.13",
"1.5",
"1.7"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.13",
"1.5",
"1.7",
"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"
]
},
{
"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"
]
}
] |
jakgel/clusterbuster | [
"d79400a0faf43dece457d99b024b955aef544fc2"
] | [
"surveysim/music2/interpolate.py"
] | [
"import numpy as np\nimport scipy.interpolate as interpolate\nimport matplotlib.pyplot as plt\nimport clusterbuster.mathut as math\n\"\"\"\nStart with e.g. InterpolateRadio2D(psiFile = '../Analysis_MUSIC2/Hoeft_radio/mach_psi_tablefine(10,3).txt', inter=(10,6)) \n\"\"\"\n\n\n\n# from http://stackoverflow.com/questions/5328128/scipy-interpolation-of-large-matrix\ndef my_interp(X, Y, Z, x, y, spn=3):\n xs,ys = map(np.array,(x,y))\n z = np.zeros(xs.shape)\n for i,(x,y) in enumerate(zip(xs,ys)):\n # get the indices of the nearest x,y\n xi = np.argmin(np.abs(X[0,:]-x))\n yi = np.argmin(np.abs(Y[:,0]-y))\n xlo = max(xi-spn, 0)\n ylo = max(yi-spn, 0)\n xhi = min(xi+spn, X[0,:].size)\n yhi = min(yi+spn, Y[:,0].size)\n # make slices of X,Y,Z that are only a few items wide\n nX = X[xlo:xhi, ylo:yhi]\n nY = Y[xlo:xhi, ylo:yhi]\n nZ = Z[xlo:xhi, ylo:yhi]\n intp = interpolate.interp2d(nX, nY, nZ)\n z[i] = intp(x,y)[0]\n return z\n\n\n# from here on: done by myself\n\ndef LoadFile_psi(psiFile):\n \"\"\" Just gives the Mach number and Temperature values \"\"\"\n #=== FILE A ===#\n # read first line .... split it and convert sstring to float science float('1.31E+01') or for a list:map(float, ['3.76E+00', '1.31E+01', '1.14E+01'])\n\n\n with open(psiFile, 'r') as f:\n first_line = f.readline()\n psi_x = first_line.split()[2:] # Splits into list without first two elements\n psi_x = np.asarray( [float(i) for i in psi_x ] ) # Converts strings to floats # Converts strings to floats\n psi_y = np.loadtxt(psiFile,skiprows=0)[:,0]\n \n return psi_x, psi_y\n\n\ndef InterpolateRadio2D(psiFile='../Analysis_MUSIC2/Hoeft_radio/mach_psi_table.txt', machFile='../Analysis_MUSIC2/Hoeft_radio/q_mach_machr_table.txt', saveplot='../Analysis_MUSIC2/Hoeft_radio/interpolated', psiFileNew = False, machFileNew = False, inter=(10,3)):\n# Currently the mach number is interpolated in an logarithmic space which is much sparser at lower mach numbers then anticipated \n# I suspect an double-exponential function for mach (both efficiency dependency stepsize) \n \n # Note that the original grid given in 'Hoeft_radio/mach_psi_table.txt' is (quite) regular in log-loglog space, which makes it very simple to invoke an interpolation function!\n # Irregular data points would make it nececcary to use functions like scipy.interpolate.griddata(points, values, (grid_x, grid_y), method='cubic')\n \n plot_old = False\n plot_new = False\n plot_PhD = True\n \n ##==== psiFile for psi factor; machfile for mach-numbers conversion factors\n H_mach = np.loadtxt(machFile,skiprows=0) \n H_psi = np.loadtxt(psiFile,skiprows=0)[:,1::] # you wont get the temperature values ... read them separetely\n psi_x,psi_y = LoadFile_psi(psiFile)\n \n psi_x = np.log10( psi_x ) # converts to and log10 space\n psi_y = np.log10(np.log10( psi_y )) # converts to and log10(log10) space\n X, Y = np.meshgrid(psi_x, psi_y)\n Z = np.log10(H_psi)\n \n #interp_spline = interpolate.interp2d(x, y, Z) #, kind='cubic'\n interp_spline = interpolate.RectBivariateSpline(psi_y, psi_x, Z) #, bbox=[None, None, None, None], kx=3, ky=3, s=0\n \n xnew = np.arange(psi_x[0], psi_x[-1], (psi_x[-1]-psi_x[0])/(len(psi_x)*inter[0]) ) #np.arange(-4, 2, 4e-2) #\n ynew = np.arange(psi_y[0], psi_y[-1], (psi_y[-1]-psi_y[0])/(len(psi_y)*inter[1]) ) #np.arange(0.2, 3, 2e-2) #\n Znew = interp_spline(ynew, xnew )\n \n keV2K = 1.16e7 # Translates keV to Kelvin\n \n if plot_old:\n plt.plot( np.arange(0, len(psi_x), 1 ), psi_x )\n plt.plot( np.arange(0, len(psi_y), 1 ), psi_y )\n plt.savefig(saveplot + '_linearity.png')\n \n fig = plt.figure()\n \n ax1 = plt.subplot(121)\n ax1.pcolor( np.log10(keV2K) + psi_x, psi_y, Z)\n ax1.set_title(\"Sparsely sampled function\")\n ax1.set_xlim([3.1, 9])\n ax1.set_ylim([psi_y[0], 0.5])\n ax1.set_xlabel('$\\\\mathrm{log_{10}(T)\\\\,[K]}$ ')\n ax1.set_ylabel('$\\\\mathrm{log_{10}(log_{10}(M))\\\\,[]}$')\n \n \n ax2 = plt.subplot(122)\n im2 = ax2.pcolor( np.log10(keV2K) + xnew, ynew, Znew)\n ax2.set_title(\"Interpolated function\")\n ax2.set_xlim([3.1, 9])\n ax2.set_ylim([psi_y[0], 0.5])\n ax2.set_xlabel('$\\\\mathrm{log_{10}(T)\\\\,[K]}$ ')\n ax2.set_yticklabels([])\n \n mach = [1.5,2.2,3.0,10.0]\n c = [plt.cm.rainbow( (np.log10(np.log10(m))-ax1.get_ylim()[0])/abs(ax1.get_ylim()[1]-ax1.get_ylim()[0]) ) for m in mach]\n for ii,m in enumerate(mach):\n ax1.plot( [ax1.get_xlim()[0], ax1.get_xlim()[1]] , [np.log10(np.log10(m))]*2, '-', c=c[ii], lw=1.5, alpha=0.9 ) \n ax2.plot( [ax2.get_xlim()[0], ax2.get_xlim()[1]] , [np.log10(np.log10(m))]*2, '-', c=c[ii], lw=1.5, alpha=0.9 ) \n \n ax1.text(ax1.get_xlim()[0]+0.3, np.log10(np.log10(m))+0.02, 'Mach$=$%4.1f' % (m), fontsize=10, color=c[ii], alpha=0.9)\n ax2.text(ax2.get_xlim()[0]+0.3, np.log10(np.log10(m))+0.02, 'Mach$=$%4.1f' % (m), fontsize=10, color=c[ii], alpha=0.9)\n \n fig.subplots_adjust(right=0.8)\n cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7])\n fig.colorbar(im2, cax=cbar_ax)\n plt.savefig(saveplot + '.png')\n \n if plot_new:\n fig = plt.figure()\n \n ax1 = plt.subplot(111)\n im2 = ax1.pcolor( np.log10(keV2K) + xnew, ynew, Znew, vmin=-8)\n# ax1.set_title(\"Interpolated function\")\n ax1.set_xlim([7, 8.4])\n ax1.set_ylim([np.log10(np.log10(1.7)), np.log10(np.log10(10.))])\n ax1.set_xlabel('$\\\\mathrm{log_{10}(T)\\\\,[K]}$ ')\n ax1.set_ylabel('$M$ ')\n \n y_ticks = [np.log10(np.log10(m)) for m in [1.7,2.5,4,10]]\n print( ['%.2e' % (y) for y in y_ticks], [10**(10**y) for y in y_ticks] )\n ax1.set_yticklabels([10**(10**y) for y in y_ticks])\n plt.yticks(y_ticks)\n \n# temp = [1.5,2.2,3.0,10.0]\n# c = [plt.cm.rainbow( (np.log10(np.log10(m))-ax1.get_ylim()[0])/abs(ax1.get_ylim()[1]-ax1.get_ylim()[0]) ) for m in mach]\n# for ii,m in enumerate(mach):\n# ax1.plot( [ax1.get_xlim()[0], ax1.get_xlim()[1]] , [np.log10(np.log10(m))]*2, '-', c=c[ii], lw=1.5, alpha=0.9 ) \n# ax2.plot( [ax2.get_xlim()[0], ax2.get_xlim()[1]] , [np.log10(np.log10(m))]*2, '-', c=c[ii], lw=1.5, alpha=0.9 ) \n# \n# ax1.text(ax1.get_xlim()[0]+0.3, np.log10(np.log10(m))+0.02, 'Mach$=$%4.1f' % (m), fontsize=10, color=c[ii], alpha=0.9)\n# ax2.text(ax2.get_xlim()[0]+0.3, np.log10(np.log10(m))+0.02, 'Mach$=$%4.1f' % (m), fontsize=10, color=c[ii], alpha=0.9)\n \n fig.subplots_adjust(right=0.8)\n cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7])\n fig.colorbar(im2, cax=cbar_ax, label='$\\log_{10}\\Phi$',)\n plt.savefig(saveplot + '_DSA.pdf')\n plt.savefig(saveplot + '_DSA.png', dpi=800) \n \n \n if plot_PhD:\n fig = plt.figure()\n \n temp = np.linspace(2,20,20)\n print(temp)\n mach = np.linspace(2,7,300)\n psi_x,psi_y = LoadFile_psi(psiFile)\n import itertools\n H,M,T = [],[],[]\n for t in temp:\n results_temp = math.find_closest(psi_x, t)\n results_mach = math.find_closest(psi_y, mach) # \n H.append(H_psi[results_mach,np.ones_like(results_mach)*results_temp])\n M.append(mach)\n T.append(np.ones_like(results_mach)*t)\n \n H = list(itertools.chain.from_iterable(H))\n M = list(itertools.chain.from_iterable(M))\n T = list(itertools.chain.from_iterable(T)) \n \n plt.scatter(M,np.log10(H),c=T,alpha=0.1,s=5) \n cb = plt.colorbar(label='Downstream Temperature [keV]')\n cb.set_alpha(1)\n cb.draw_all()\n plt.xlabel('Mach number $M$')\n plt.ylabel('$\\log_{10}\\,\\Phi(M,T)$')\n plt.savefig(saveplot + '_PhD.pdf')\n plt.savefig(saveplot + '_PhD.png', dpi=800) \n \n \n # Save File A\n if psiFileNew:\n location = psiFileNew\n else:\n location = psiFile.replace('.txt', 'fine(%i,%i).txt' % (inter[0],inter[1]) ) \n \n header = '# Mach'\n for x in xnew:\n header += '%13.4e' % (10**x)\n\n mf = open(location,\"w\")\n mf.write(header + '\\n')\n \n for ii,y in enumerate(ynew): \n string = '%9.4f' % (10**(10**y)) + ''.join(['%13.4e' % (10**z) for z in Znew[ii][:]])\n mf.write(string + '\\n') \n\n mf.close() \n \n \n #=== FILE B ===#\n Y_new = np.empty( (1,1) )\n for ii,h in enumerate(H_mach.T):\n interp_spline = interpolate.interp1d( 10**psi_y , h, kind='cubic') \n\n if Y_new.shape[0] > 1:\n Y_new = np.hstack( (Y_new, np.expand_dims(interp_spline( 10**ynew ), axis=1) ) )\n else:\n Y_new = np.expand_dims(interp_spline( 10**ynew ), axis=1)\n \n # Save File B\n if machFileNew:\n location = machFileNew\n else:\n location = machFile.replace('.txt', 'fine(%i,%i).txt' % (inter[0],inter[1]) ) \n \n header = '# q M r M*(1-1/r) s'\n \n mf = open(location,\"w\")\n mf.write(header + '\\n')\n\n for ii,y in enumerate(10**ynew): \n string = ''.join(['%14.6e' % (y) for y in Y_new[:][ii]]) #some numbers are very large and ewould need a good margin\n mf.write(string + '\\n') \n\n mf.close() \n\n return 0\n \n\nif __name__ == \"__main__\":\n InterpolateRadio2D(psiFile = '../Analysis_MUSIC2/Hoeft_radio/mach_psi_tablefine(10,3).txt', inter=(3,2)) #(90,27) \n\n"
] | [
[
"matplotlib.pyplot.yticks",
"numpy.ones_like",
"scipy.interpolate.RectBivariateSpline",
"numpy.linspace",
"numpy.abs",
"numpy.empty",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.colorbar",
"matplotlib.pyplot.ylabel",
"numpy.log10",
"matplotlib.pyplot.subplot",
"scipy.interpolate.interp1d",
"matplotlib.pyplot.xlabel",
"scipy.interpolate.interp2d",
"numpy.meshgrid",
"numpy.zeros",
"numpy.loadtxt",
"matplotlib.pyplot.figure"
]
] | [
{
"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": []
}
] |
ammar-khan/raspberry-pi-opencv-dnn-face-detection | [
"04ea998ee9e4d7bf71da022b0d8613940e8e7cfb"
] | [
"main.py"
] | [
"##\n# Copyright 2018, Ammar Ali Khan\n# Licensed under MIT.\n# Since: v1.0.0\n##\n\nimport time\nimport cv2\nimport numpy as np\nfrom src.common.package.config import application\nfrom src.opencv.package.config import application as _application\nfrom src.common.package.http import server as _server\nfrom src.common.package.http.handler import Handler\nfrom src.common.package.camera.capture import Capture as _capture\nfrom src.common.package.frame.action import Action as _frame\nfrom src.common.package.frame.draw import Draw as _draw\nfrom src.opencv.package.opencv.opencv import OpenCV\n\n# Constant\n_opencv = OpenCV()\n\n\n##\n# StreamHandler class - inherit Handler\n# This class provide handler for HTTP streaming\n# Note: this class should override Handler.stream\n##\nclass StreamHandler(Handler):\n\n ##\n # Override method Handler.stream()\n ##\n def stream(self):\n Handler.stream(self)\n print('[INFO] Overriding stream method...')\n\n # Initialise capture\n capture = _capture(src=application.CAPTURING_DEVICE,\n use_pi_camera=application.USE_PI_CAMERA,\n resolution=application.RESOLUTION,\n frame_rate=application.FRAME_RATE)\n\n if application.USE_PI_CAMERA:\n print('[INFO] Warming up pi camera...')\n else:\n print('[INFO] Warming up camera...')\n\n time.sleep(2.0)\n\n print('[INFO] Start capturing...')\n\n while True:\n # Read a frame from capture\n frame = capture.read()\n\n # Down size frame to 50% (to increase performance on Raspberry Pi)\n # frame = _frame.scale(frame=frame, scale=0.5)\n\n # Convert frame to gray (to increase performance on Raspberry Pi)\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n # Get frame dimensions\n (height, width) = frame.shape[:2]\n\n # OpenCV detection\n detections = _opencv.dnn_face_detector(frame=frame,\n scale_factor=1.0,\n size=(300, 300),\n mean=(104.0, 177.0, 123.0))\n\n # Up size frame to 50% (how the frame was before down sizing)\n # frame = _frame.scale(frame=frame, scale=2)\n\n # If returns any detection\n for i in range(0, detections.shape[2]):\n # Get confidence associated with the detection\n confidence = detections[0, 0, i, 2]\n\n # Filter weak detection\n if confidence < _application.CONFIDENCE:\n continue\n\n # Calculate coordinates\n box = detections[0, 0, i, 3:7] * np.array([width,\n height,\n width,\n height])\n\n (left, top, right, bottom) = box.astype('int')\n\n coordinates = {'left': left,\n 'top': top,\n 'right': right,\n 'bottom': bottom}\n\n text = \"{:.2f}%\".format(confidence * 100)\n\n frame = _draw.rectangle(frame=frame,\n coordinates=coordinates,\n text=text)\n\n # Write date time on the frame\n frame = _draw.text(frame=frame,\n coordinates={'left': application.WIDTH - 150, 'top': application.HEIGHT - 20},\n text=time.strftime('%d/%m/%Y %H:%M:%S', time.localtime()),\n font_color=(0, 0, 255))\n\n # Convert frame into buffer for streaming\n retval, buffer = cv2.imencode('.jpg', frame)\n\n # Write buffer to HTML Handler\n self.wfile.write(b'--FRAME\\r\\n')\n self.send_header('Content-Type', 'image/jpeg')\n self.send_header('Content-Length', len(buffer))\n self.end_headers()\n self.wfile.write(buffer)\n self.wfile.write(b'\\r\\n')\n\n\n##\n# Method main()\n##\ndef main():\n try:\n address = ('', application.HTTP_PORT)\n server = _server.Server(address, StreamHandler)\n print('[INFO] HTTP server started successfully at %s' % str(server.server_address))\n print('[INFO] Waiting for client to connect to port %s' % str(application.HTTP_PORT))\n server.serve_forever()\n except Exception as e:\n server.socket.close()\n print('[INFO] HTTP server closed successfully.')\n print('[ERROR] Exception: %s' % str(e))\n\n\nif __name__ == '__main__':\n main()\n"
] | [
[
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ashleylqx/AIB | [
"77e418cac52f0ca5f2a7c54927468a7bd75a8fc9"
] | [
"CUB-experiments/nearest_embed.py"
] | [
"# adapted from https://github.com/nadavbh12/VQ-VAE\n\nimport numpy as np\nimport torch\nfrom torch import nn\nfrom torch.autograd import Function, Variable\nimport torch.nn.functional as F\n\nfrom config import *\n\nimport pdb\n\n\nclass NearestEmbedFunc(Function):\n \"\"\"\n Input:\n ------\n x - (batch_size, emb_dim, *)\n Last dimensions may be arbitrary\n emb - (emb_dim, num_emb)\n \"\"\"\n @staticmethod\n def forward(ctx, input, emb):\n # if input.size(1) != emb.size(0):\n # raise RuntimeError('invalid argument: input.size(1) ({}) must be equal to emb.size(0) ({})'.\n # format(input.size(1), emb.size(0)))\n\n # emb = emb.expand(input.size(1), emb.size(1))\n emb_ex = emb.expand(input.size(1), emb.size(1)) # new2\n\n # save sizes for backward\n ctx.batch_size = input.size(0)\n ctx.num_latents = int(np.prod(np.array(input.size()[2:])))\n # ctx.emb_dim = emb.size(0)\n # ctx.num_emb = emb.size(1)\n ctx.emb_dim = emb_ex.size(0)\n ctx.num_emb = emb_ex.size(1) # new2\n ctx.input_type = type(input)\n ctx.dims = list(range(len(input.size())))\n\n # expand to be broadcast-able\n x_expanded = input.unsqueeze(-1)\n num_arbitrary_dims = len(ctx.dims) - 2\n if num_arbitrary_dims:\n # emb_expanded = emb.view(emb.shape[0], *([1] * num_arbitrary_dims), emb.shape[1])\n emb_expanded = emb_ex.view(emb_ex.shape[0], *([1] * num_arbitrary_dims), emb_ex.shape[1]) # new2\n else:\n # emb_expanded = emb\n emb_expanded = emb_ex # new2\n\n # find nearest neighbors\n # dist = torch.norm(x_expanded - emb_expanded, 2, 1)\n dist = torch.pow(x_expanded - emb_expanded, 2) # (batch_size, emb_dim, *, num_emb) # new2\n _, argmin = dist.min(-1)\n shifted_shape = [input.shape[0], *list(input.shape[2:]) ,input.shape[1]]\n # pdb.set_trace()\n result = emb.t().index_select(0, argmin.view(-1)).view(shifted_shape).permute(0, ctx.dims[-1], *ctx.dims[1:-1]) # new2\n\n ctx.save_for_backward(argmin)\n return result.contiguous(), argmin\n\n @staticmethod\n def backward(ctx, grad_output, argmin=None):\n # pdb.set_trace()\n grad_input = grad_emb = None\n if ctx.needs_input_grad[0]:\n grad_input = grad_output\n\n if ctx.needs_input_grad[1]:\n argmin, = ctx.saved_variables\n latent_indices = torch.arange(ctx.num_emb).type_as(argmin)\n idx_choices = (argmin.view(-1, 1) == latent_indices.view(1, -1)).type_as(grad_output.data)\n n_idx_choice = idx_choices.sum(0)\n n_idx_choice[n_idx_choice == 0] = 1\n idx_avg_choices = idx_choices / n_idx_choice\n grad_output = grad_output.permute(0, *ctx.dims[2:], 1).contiguous()\n grad_output = grad_output.view(ctx.batch_size * ctx.num_latents, ctx.emb_dim)\n # pdb.set_trace()\n # grad_emb = torch.sum(grad_output.data.view(-1, ctx.emb_dim, 1) *\n # idx_avg_choices.view(-1, 1, ctx.num_emb), 0)\n grad_emb = torch.sum(grad_output.data.view(-1, 1) *\n idx_avg_choices.view(-1, ctx.num_emb), 0, keepdim=True) # new2\n return grad_input, grad_emb, None, None\n\n\ndef nearest_embed(x, emb):\n return NearestEmbedFunc().apply(x, emb)\n\n\nclass NearestEmbed(nn.Module):\n def __init__(self, num_embeddings, embeddings_dim, rd_init=True):\n super(NearestEmbed, self).__init__()\n if rd_init:\n self.weight = nn.Parameter(torch.rand(embeddings_dim, num_embeddings))\n else:\n # self.weight = nn.Parameter(torch.linspace(0.0, 1.0, num_embeddings).unsqueeze(0).expand(embeddings_dim, num_embeddings))\n self.weight = nn.Parameter(torch.linspace(lin_min, lin_max, num_embeddings).unsqueeze(0).expand(embeddings_dim, num_embeddings))\n\n print('Init emb weight:', self.weight.data)\n\n def forward(self, x, weight_sg=False):\n \"\"\"Input:\n ---------\n x - (batch_size, emb_size, *)\n \"\"\"\n return nearest_embed(x, self.weight.detach() if weight_sg else self.weight)\n\n\n# adapted from https://github.com/rosinality/vq-vae-2-pytorch/blob/master/vqvae.py#L25\n# that adapted from https://github.com/deepmind/sonnet\n\n\nclass NearestEmbedEMA(nn.Module):\n def __init__(self, n_emb, emb_dim, decay=0.99, eps=1e-5, rd_init=True):\n super(NearestEmbedEMA, self).__init__()\n self.decay = decay\n self.eps = eps\n self.embeddings_dim = emb_dim\n self.n_emb = n_emb\n self.emb_dim = emb_dim\n if rd_init:\n embed = torch.rand(emb_dim, n_emb)\n else:\n # embed = torch.linspace(0.0, 1.0, n_emb).unsqueeze(0).expand(emb_dim, n_emb)\n embed = torch.linspace(lin_min, lin_max, n_emb).unsqueeze(0).expand(emb_dim, n_emb)\n self.register_buffer('weight', embed)\n self.register_buffer('cluster_size', torch.zeros(n_emb))\n self.register_buffer('embed_avg', embed.clone())\n\n print('Init emb weight ema:', self.weight.data)\n\n def forward(self, x, weight_sg=None):\n \"\"\"Input:\n ---------\n x - (batch_size, emb_size, *)\n \"\"\"\n emb_ex = self.weight.expand(x.size(1), self.weight.size(1)) # new2\n #emb_avg_ex = self.embed_avg.expand(x.size(1), self.weight.size(1)) # new2\n\n dims = list(range(len(x.size())))\n x_expanded = x.unsqueeze(-1)\n num_arbitrary_dims = len(dims) - 2\n # if num_arbitrary_dims:\n # emb_expanded = self.weight.view(self.emb_dim, *([1] * num_arbitrary_dims), self.n_emb)\n # else:\n # emb_expanded = self.weight\n\n emb_size = x.size(1)\n if num_arbitrary_dims:\n #emb_expanded = self.weight.expand(emb_size, self.n_emb).view(self.emb_dim, *([1] * num_arbitrary_dims), self.n_emb)\n emb_expanded = emb_ex.expand(emb_size, self.n_emb).view(self.emb_dim, *([1] * num_arbitrary_dims), self.n_emb)\n else:\n #emb_expanded = self.weight.expand(emb_size, self.n_emb)\n emb_expanded = emb_ex.expand(emb_size, self.n_emb)\n\n # find nearest neighbors\n # dist = torch.norm(x_expanded - emb_expanded, 2, 1)\n dist = torch.pow(x_expanded - emb_expanded, 2) # (batch_size, emb_dim, *, num_emb) # new2\n _, argmin = dist.min(-1)\n shifted_shape = [x.shape[0], *list(x.shape[2:]), x.shape[1]]\n # result = emb_ex.t().index_select(0, argmin.view(-1)).view(shifted_shape).permute(0, dims[-1], *dims[1:-1]) # (batch_size, emb_dim, *, num_emb) # new2\n result = self.weight.t().index_select(0, argmin.view(-1)).view(shifted_shape).permute(0, dims[-1], *dims[1:-1]) # (batch_size, emb_dim, *, num_emb) # new2\n # result = self.weight.expand(emb_size, self.n_emb).t().index_select(0, argmin.view(-1)).view(shifted_shape).permute(0, dims[-1], *dims[1:-1])\n\n if self.training:\n latent_indices = torch.arange(self.n_emb).type_as(argmin)\n emb_onehot = (argmin.view(-1, 1) == latent_indices.view(1, -1)).type_as(x.data)\n n_idx_choice = emb_onehot.sum(0)\n n_idx_choice[n_idx_choice == 0] = 1\n # pdb.set_trace()\n # flatten = x.permute(1, 0, *dims[-2:]).contiguous().view(x.shape[1], -1)\n num_arbitrary_dims = len(dims) - 2\n if num_arbitrary_dims:\n # flatten = x.permute(1, 0, *dims[-2:]).contiguous().view(x.shape[1], -1)\n # flatten = x.permute(1, 0, *dims[-2:]).contiguous().view(1, -1)\n flatten = x.view(1, -1)\n else:\n # flatten = x.permute(1, 0).contiguous()\n # flatten = x.permute(1, 0).contiguous().view(1, -1)\n flatten = x.view(1, -1)\n\n self.cluster_size.data.mul_(self.decay).add_(\n 1 - self.decay, n_idx_choice\n )\n # pdb.set_trace()\n embed_sum = flatten @ emb_onehot # -----dc0.99\n # embed_sum = torch.pow(flatten.t() - emb_onehot, 2).mean(0) # ----dc0.99_s\n #pdb.set_trace()\n self.embed_avg.data.mul_(self.decay).add_(1 - self.decay, embed_sum)\n #emb_avg_ex.data.mul_(self.decay).add_(1 - self.decay, embed_sum)\n #pdb.set_trace()\n\n n = self.cluster_size.sum()\n cluster_size = (\n (self.cluster_size + self.eps) / (n + self.n_emb * self.eps) * n\n )\n embed_normalized = self.embed_avg / cluster_size.unsqueeze(0)\n self.weight.data.copy_(embed_normalized) # ---dc0.99\n # self.weight.data.copy_(self.embed_avg) # -------dc0.99_s\n\n #embed_normalized = emb_avg_ex / cluster_size.unsqueeze(0)\n #self.weight.data.copy_(embed_normalized.mean(0, keepdim=True))\n #self.embed_avg.data.copy_(emb_avg_ex.mean(0, keepdim=True))\n\n return result, argmin\n"
] | [
[
"torch.linspace",
"torch.zeros",
"torch.rand",
"torch.arange",
"torch.pow"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
hartmanwilliam/federated | [
"ecf51cdf8b86cbd000f6edc5715dc904bce07540",
"ecf51cdf8b86cbd000f6edc5715dc904bce07540",
"ecf51cdf8b86cbd000f6edc5715dc904bce07540",
"ecf51cdf8b86cbd000f6edc5715dc904bce07540",
"ecf51cdf8b86cbd000f6edc5715dc904bce07540",
"ecf51cdf8b86cbd000f6edc5715dc904bce07540",
"ecf51cdf8b86cbd000f6edc5715dc904bce07540",
"ecf51cdf8b86cbd000f6edc5715dc904bce07540",
"ecf51cdf8b86cbd000f6edc5715dc904bce07540",
"ecf51cdf8b86cbd000f6edc5715dc904bce07540"
] | [
"tensorflow_federated/python/research/optimization/stackoverflow/dataset.py",
"tensorflow_federated/python/core/backends/mapreduce/canonical_form_test.py",
"tensorflow_federated/python/research/triehh/triehh_tff_test.py",
"tensorflow_federated/python/research/simple_fedavg/simple_fedavg_tff.py",
"tensorflow_federated/python/core/impl/executors/remote_executor_test.py",
"tensorflow_federated/python/core/impl/executors/caching_executor_test.py",
"tensorflow_federated/python/learning/personalization_eval_test.py",
"tensorflow_federated/python/research/flars/run_emnist.py",
"tensorflow_federated/python/research/optimization/emnist_ae/models_test.py",
"tensorflow_federated/python/research/optimization/cifar100/dataset_test.py"
] | [
"# Lint as: python3\n# Copyright 2019, The TensorFlow Federated 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\"\"\"Data loader for Stackoverflow.\"\"\"\nfrom typing import List\n\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow_federated as tff\n\nEVAL_BATCH_SIZE = 100\n\n\ndef create_vocab(vocab_size):\n \"\"\"Creates vocab from `vocab_size` most common words in Stackoverflow.\"\"\"\n vocab_dict = tff.simulation.datasets.stackoverflow.load_word_counts()\n return list(vocab_dict.keys())[:vocab_size]\n\n\ndef split_input_target(chunk):\n \"\"\"Generate input and target data.\n\n The task of language model is to predict the next word.\n\n Args:\n chunk: A Tensor of text data.\n\n Returns:\n A namedtuple of input and target data.\n \"\"\"\n input_text = tf.map_fn(lambda x: x[:-1], chunk)\n target_text = tf.map_fn(lambda x: x[1:], chunk)\n return (input_text, target_text)\n\n\ndef build_to_ids_fn(vocab, max_seq_len):\n \"\"\"Constructs function mapping examples to sequences of token indices.\"\"\"\n _, _, bos, eos = get_special_tokens(len(vocab))\n\n table_values = np.arange(len(vocab), dtype=np.int64)\n table = tf.lookup.StaticVocabularyTable(\n tf.lookup.KeyValueTensorInitializer(vocab, table_values),\n num_oov_buckets=1)\n\n def to_ids(example):\n sentence = tf.reshape(example['tokens'], shape=[1])\n words = tf.strings.split(sentence, sep=' ').values\n truncated_words = words[:max_seq_len]\n tokens = table.lookup(truncated_words) + 1\n tokens = tf.cond(\n tf.less(tf.size(tokens), max_seq_len),\n lambda: tf.concat([tokens, [eos]], 0), lambda: tokens)\n\n return tf.concat([[bos], tokens], 0)\n\n return to_ids\n\n\ndef batch_and_split(dataset, max_seq_len, batch_size):\n return dataset.padded_batch(\n batch_size, padded_shapes=[max_seq_len + 1]).map(\n split_input_target, num_parallel_calls=tf.data.experimental.AUTOTUNE)\n\n\ndef get_special_tokens(vocab_size):\n \"\"\"Gets tokens dataset preprocessing code will add to Stackoverflow.\"\"\"\n pad = 0\n oov = vocab_size + 1\n bos = vocab_size + 2\n eos = vocab_size + 3\n return pad, oov, bos, eos\n\n\ndef create_train_dataset_preprocess_fn(vocab: List[str],\n client_batch_size: int,\n client_epochs_per_round: int,\n max_seq_len: int,\n max_training_elements_per_user: int,\n max_shuffle_buffer_size=10000):\n \"\"\"Creates preprocessing functions for stackoverflow data.\n\n This function returns a function which takes a dataset and returns a dataset,\n generally for mapping over a set of unprocessed client datasets during\n training.\n\n Args:\n vocab: Vocabulary which defines the embedding.\n client_batch_size: Integer representing batch size to use on the clients.\n client_epochs_per_round: Number of epochs for which to repeat train client\n dataset.\n max_seq_len: Integer determining shape of padded batches. Sequences will be\n padded up to this length, and sentences longer than `max_seq_len` will be\n truncated to this length.\n max_training_elements_per_user: Integer controlling the maximum number of\n elements to take per user. If -1, takes all elements for each user.\n max_shuffle_buffer_size: Maximum shuffle buffer size.\n\n Returns:\n Two functions, the first `preprocess_train` and the second\n `preprocess_val_and_test`, as described above.\n \"\"\"\n if client_batch_size <= 0:\n raise ValueError('client_batch_size must be a positive integer; you have '\n 'passed {}'.format(client_batch_size))\n elif client_epochs_per_round <= 0:\n raise ValueError('client_epochs_per_round must be a positive integer; you '\n 'have passed {}'.format(client_epochs_per_round))\n elif max_seq_len <= 0:\n raise ValueError('max_seq_len must be a positive integer; you have '\n 'passed {}'.format(max_seq_len))\n elif max_training_elements_per_user < -1:\n raise ValueError(\n 'max_training_elements_per_user must be an integer at '\n 'least -1; you have passed {}'.format(max_training_elements_per_user))\n\n if (max_training_elements_per_user == -1 or\n max_training_elements_per_user > max_shuffle_buffer_size):\n shuffle_buffer_size = max_shuffle_buffer_size\n else:\n shuffle_buffer_size = max_training_elements_per_user\n\n # TODO(b/155408842): need further investigation on why `tff.tf_compuation`\n # decorator causes b/153363900 for `to_ids`, and large memory consumption.\n def preprocess_train(dataset):\n to_ids = build_to_ids_fn(vocab, max_seq_len)\n dataset = dataset.take(max_training_elements_per_user)\n dataset = dataset.shuffle(shuffle_buffer_size)\n dataset = dataset.repeat(client_epochs_per_round)\n dataset = dataset.map(\n to_ids, num_parallel_calls=tf.data.experimental.AUTOTUNE)\n return batch_and_split(dataset, max_seq_len, client_batch_size)\n\n return preprocess_train\n\n\ndef create_test_dataset_preprocess_fn(vocab: List[str], max_seq_len: int):\n \"\"\"Creates preprocessing functions for stackoverflow data.\n\n This function returns a function which represents preprocessing logic\n for use on centralized validation and test datasets outside of TFF.\n\n Args:\n vocab: Vocabulary which defines the embedding.\n max_seq_len: Integer determining shape of padded batches. Sequences will be\n padded up to this length, and sentences longer than `max_seq_len` will be\n truncated to this length.\n\n Returns:\n `preprocess_val_and_test`, as described above.\n \"\"\"\n if max_seq_len <= 0:\n raise ValueError('max_seq_len must be a positive integer; you have '\n 'passed {}'.format(max_seq_len))\n\n def preprocess_val_and_test(dataset):\n to_ids = build_to_ids_fn(vocab, max_seq_len)\n id_dataset = dataset.map(\n to_ids, num_parallel_calls=tf.data.experimental.AUTOTUNE)\n return batch_and_split(id_dataset, max_seq_len, EVAL_BATCH_SIZE)\n\n return preprocess_val_and_test\n\n\ndef construct_word_level_datasets(vocab_size: int,\n client_batch_size: int,\n client_epochs_per_round: int,\n max_seq_len: int,\n max_training_elements_per_user: int,\n num_validation_examples: int,\n max_shuffle_buffer_size=10000):\n \"\"\"Preprocessing for Stackoverflow data.\n\n Notice that this preprocessing function *ignores* the heldout Stackoverflow\n dataset for consistency with the other datasets in the proposed optimization\n paper, and returns a validation/test split of the Stackoverflow \"test\" data,\n containing more examples from users in the Stackoverflow train dataset.\n\n Args:\n vocab_size: Integer representing size of the vocab to use. Vocabulary will\n then be the `vocab_size` most frequent words in the Stackoverflow dataset.\n client_batch_size: Integer representing batch size to use on the clients.\n client_epochs_per_round: Number of epochs for which to repeat train client\n dataset.\n max_seq_len: Integer determining shape of padded batches. Sequences will be\n padded up to this length, and sentences longer than `max_seq_len` will be\n truncated to this length.\n max_training_elements_per_user: Integer controlling the maximum number of\n elements to take per user. If -1, takes all elements for each user.\n num_validation_examples: Number of examples from Stackoverflow test set to\n use for validation on each round.\n max_shuffle_buffer_size: Maximum shuffle buffer size.\n\n Returns:\n stackoverflow_train: An instance of `tff.simulation.ClientData`\n representing Stackoverflow data for training.\n stackoverflow_validation: A split of the Stackoverflow Test data as outlined\n in `tff.simulation.datasets.stackoverflow`, containing at most\n `num_validation_examples` examples.\n stackoverflow_test: A split of the same Stackoverflow Test data containing\n the examples not used in `stackoverflow_validation`.\n \"\"\"\n if num_validation_examples < 1:\n raise ValueError(\n 'num_validation_examples must be an integer at '\n 'least 1; you have passed {}'.format(num_validation_examples))\n elif vocab_size <= 0:\n raise ValueError('vocab_size must be a positive integer; you have '\n 'passed {}'.format(vocab_size))\n\n (stackoverflow_train, _,\n stackoverflow_test) = tff.simulation.datasets.stackoverflow.load_data()\n\n vocab = create_vocab(vocab_size)\n\n raw_test_dataset = stackoverflow_test.create_tf_dataset_from_all_clients()\n\n preprocess_train = create_train_dataset_preprocess_fn(\n vocab, client_batch_size, client_epochs_per_round, max_seq_len,\n max_training_elements_per_user, max_shuffle_buffer_size)\n\n preprocess_val_and_test = create_test_dataset_preprocess_fn(\n vocab, max_seq_len)\n\n stackoverflow_train = stackoverflow_train.preprocess(preprocess_train)\n stackoverflow_val = preprocess_val_and_test(\n raw_test_dataset.take(num_validation_examples))\n stackoverflow_test = preprocess_val_and_test(\n raw_test_dataset.skip(num_validation_examples))\n\n return stackoverflow_train, stackoverflow_val, stackoverflow_test\n\n\ndef get_centralized_train_dataset(vocab_size: int,\n batch_size: int,\n max_seq_len: int,\n shuffle_buffer_size: int = 10000):\n \"\"\"Creates centralized approximately shuffled train dataset.\"\"\"\n\n vocab = create_vocab(vocab_size)\n to_ids = build_to_ids_fn(vocab, max_seq_len)\n train, _, _ = tff.simulation.datasets.stackoverflow.load_data()\n\n train = train.create_tf_dataset_from_all_clients()\n train = train.shuffle(buffer_size=shuffle_buffer_size)\n return batch_and_split(\n train.map(to_ids, num_parallel_calls=tf.data.experimental.AUTOTUNE),\n max_seq_len, batch_size)\n",
"# Lint as: python3\n# Copyright 2019, The TensorFlow Federated 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 absl.testing import absltest\nimport tensorflow as tf\n\nfrom tensorflow_federated.python.core.api import computation_types\nfrom tensorflow_federated.python.core.api import computations\nfrom tensorflow_federated.python.core.backends.mapreduce import canonical_form\nfrom tensorflow_federated.python.core.backends.mapreduce import test_utils\n\ntf.compat.v1.enable_v2_behavior()\n\n\ndef _dummy_canonical_form_computations():\n\n @computations.tf_computation\n def initialize():\n return tf.constant(0)\n\n @computations.tf_computation(tf.int32)\n def prepare(server_state):\n del server_state # Unused\n return tf.constant(1.0)\n\n @computations.tf_computation(\n computation_types.SequenceType(tf.float32), tf.float32)\n def work(client_data, client_input):\n del client_data # Unused\n del client_input # Unused\n return (True, []), []\n\n @computations.tf_computation\n def zero():\n return tf.constant(0), tf.constant(0)\n\n @computations.tf_computation((tf.int32, tf.int32), tf.bool)\n def accumulate(accumulator, client_update):\n del accumulator # Unused\n del client_update # Unused\n return tf.constant(1), tf.constant(1)\n\n @computations.tf_computation((tf.int32, tf.int32), (tf.int32, tf.int32))\n def merge(accumulator1, accumulator2):\n del accumulator1 # Unused\n del accumulator2 # Unused\n return tf.constant(1), tf.constant(1)\n\n @computations.tf_computation(tf.int32, tf.int32)\n def report(accumulator):\n del accumulator # Unused\n return tf.constant(1.0)\n\n @computations.tf_computation\n def bitwidth():\n return []\n\n @computations.tf_computation(\n tf.int32, (tf.float32, computation_types.NamedTupleType([])))\n def update(server_state, global_update):\n del server_state # Unused\n del global_update # Unused\n return tf.constant(1), []\n\n return (initialize, prepare, work, zero, accumulate, merge, report, bitwidth,\n update)\n\n\nclass CanonicalFormTest(absltest.TestCase):\n\n def test_init_does_not_raise_type_error(self):\n (initialize, prepare, work, zero, accumulate, merge, report, bitwidth,\n update) = _dummy_canonical_form_computations()\n\n try:\n canonical_form.CanonicalForm(initialize, prepare, work, zero, accumulate,\n merge, report, bitwidth, update)\n except TypeError:\n self.fail('Raised TypeError unexpectedly.')\n\n def test_init_does_not_raise_type_error_with_unknown_dimensions(self):\n\n @computations.tf_computation\n def initialize():\n return tf.constant(0)\n\n @computations.tf_computation(tf.int32)\n def prepare(server_state):\n del server_state # Unused\n return tf.constant(1.0)\n\n @computations.tf_computation(\n computation_types.SequenceType(tf.float32), tf.float32)\n def work(client_data, client_input):\n del client_data # Unused\n del client_input # Unused\n return (True, []), []\n\n @computations.tf_computation\n def zero():\n return tf.constant([], dtype=tf.string)\n\n @computations.tf_computation(\n computation_types.TensorType(shape=[None], dtype=tf.string), tf.bool)\n def accumulate(accumulator, client_update):\n del accumulator # Unused\n del client_update # Unused\n return tf.constant(['abc'])\n\n @computations.tf_computation(\n computation_types.TensorType(shape=[None], dtype=tf.string),\n computation_types.TensorType(shape=[None], dtype=tf.string))\n def merge(accumulator1, accumulator2):\n del accumulator1 # Unused\n del accumulator2 # Unused\n return tf.constant(['abc'])\n\n @computations.tf_computation(\n computation_types.TensorType(shape=[None], dtype=tf.string))\n def report(accumulator):\n del accumulator # Unused\n return tf.constant(1.0)\n\n @computations.tf_computation\n def bitwidth():\n return []\n\n @computations.tf_computation(\n tf.int32, (tf.float32, computation_types.NamedTupleType([])))\n def update(server_state, global_update):\n del server_state # Unused\n del global_update # Unused\n return tf.constant(1), []\n\n try:\n canonical_form.CanonicalForm(initialize, prepare, work, zero, accumulate,\n merge, report, bitwidth, update)\n except TypeError:\n self.fail('Raised TypeError unexpectedly.')\n\n def test_init_raises_type_error_with_bad_initialize_result_type(self):\n (_, prepare, work, zero, accumulate, merge, report, bitwidth,\n update) = _dummy_canonical_form_computations()\n\n @computations.tf_computation\n def initialize():\n return tf.constant(0.0)\n\n with self.assertRaises(TypeError):\n canonical_form.CanonicalForm(initialize, prepare, work, zero, accumulate,\n merge, report, bitwidth, update)\n\n def test_init_raises_type_error_with_bad_prepare_parameter_type(self):\n (initialize, _, work, zero, accumulate, merge, report, bitwidth,\n update) = _dummy_canonical_form_computations()\n\n @computations.tf_computation(tf.float32)\n def prepare(server_state):\n del server_state # Unused\n return tf.constant(1.0)\n\n with self.assertRaises(TypeError):\n canonical_form.CanonicalForm(initialize, prepare, work, zero, accumulate,\n merge, report, bitwidth, update)\n\n def test_init_raises_type_error_with_bad_prepare_result_type(self):\n (initialize, _, work, zero, accumulate, merge, report, bitwidth,\n update) = _dummy_canonical_form_computations()\n\n @computations.tf_computation(tf.int32)\n def prepare(server_state):\n del server_state # Unused\n return tf.constant(1)\n\n with self.assertRaises(TypeError):\n canonical_form.CanonicalForm(initialize, prepare, work, zero, accumulate,\n merge, report, bitwidth, update)\n\n def test_init_raises_type_error_with_bad_work_second_parameter_type(self):\n (initialize, prepare, _, zero, accumulate, merge, report, bitwidth,\n update) = _dummy_canonical_form_computations()\n\n @computations.tf_computation(\n computation_types.SequenceType(tf.float32), tf.int32)\n def work(client_data, client_input):\n del client_data # Unused\n del client_input # Unused\n return (True, []), []\n\n with self.assertRaises(TypeError):\n canonical_form.CanonicalForm(initialize, prepare, work, zero, accumulate,\n merge, report, bitwidth, update)\n\n def test_init_raises_type_error_with_bad_work_result_type(self):\n (initialize, prepare, _, zero, accumulate, merge, report, bitwidth,\n update) = _dummy_canonical_form_computations()\n\n @computations.tf_computation(\n computation_types.SequenceType(tf.float32), tf.float32)\n def work(client_data, client_input):\n del client_data # Unused\n del client_input # Unused\n return (tf.constant('abc'), []), []\n\n with self.assertRaises(TypeError):\n canonical_form.CanonicalForm(initialize, prepare, work, zero, accumulate,\n merge, report, bitwidth, update)\n\n def test_init_raises_type_error_with_bad_zero_result_type(self):\n (initialize, prepare, work, _, accumulate, merge, report, bitwidth,\n update) = _dummy_canonical_form_computations()\n\n @computations.tf_computation\n def zero():\n return tf.constant(0.0), tf.constant(0)\n\n with self.assertRaises(TypeError):\n canonical_form.CanonicalForm(initialize, prepare, work, zero, accumulate,\n merge, report, bitwidth, update)\n\n def test_init_raises_type_error_with_bad_accumulate_first_parameter_type(\n self):\n (initialize, prepare, work, zero, _, merge, report, bitwidth,\n update) = _dummy_canonical_form_computations()\n\n @computations.tf_computation((tf.float32, tf.int32), tf.bool)\n def accumulate(accumulator, client_update):\n del accumulator # Unused\n del client_update # Unused\n return tf.constant(1), tf.constant(1)\n\n with self.assertRaises(TypeError):\n canonical_form.CanonicalForm(initialize, prepare, work, zero, accumulate,\n merge, report, bitwidth, update)\n\n def test_init_raises_type_error_with_bad_accumulate_second_parameter_type(\n self):\n (initialize, prepare, work, zero, _, merge, report, bitwidth,\n update) = _dummy_canonical_form_computations()\n\n @computations.tf_computation((tf.float32, tf.float32), tf.string)\n def accumulate(accumulator, client_update):\n del accumulator # Unused\n del client_update # Unused\n return tf.constant(1), tf.constant(1)\n\n with self.assertRaises(TypeError):\n canonical_form.CanonicalForm(initialize, prepare, work, zero, accumulate,\n merge, report, bitwidth, update)\n\n def test_init_raises_type_error_with_bad_accumulate_result_type(self):\n (initialize, prepare, work, zero, _, merge, report, bitwidth,\n update) = _dummy_canonical_form_computations()\n\n @computations.tf_computation((tf.float32, tf.float32), tf.bool)\n def accumulate(accumulator, client_update):\n del accumulator # Unused\n del client_update # Unused\n return tf.constant(1.0), tf.constant(1)\n\n with self.assertRaises(TypeError):\n canonical_form.CanonicalForm(initialize, prepare, work, zero, accumulate,\n merge, report, bitwidth, update)\n\n def test_init_raises_type_error_with_bad_merge_first_parameter_type(self):\n (initialize, prepare, work, zero, accumulate, _, report, bitwidth,\n update) = _dummy_canonical_form_computations()\n\n @computations.tf_computation((tf.float32, tf.int32), (tf.int32, tf.int32))\n def merge(accumulator1, accumulator2):\n del accumulator1 # Unused\n del accumulator2 # Unused\n return tf.constant(1), tf.constant(1)\n\n with self.assertRaises(TypeError):\n canonical_form.CanonicalForm(initialize, prepare, work, zero, accumulate,\n merge, report, bitwidth, update)\n\n def test_init_raises_type_error_with_bad_merge_second_parameter_type(self):\n (initialize, prepare, work, zero, accumulate, _, report, bitwidth,\n update) = _dummy_canonical_form_computations()\n\n @computations.tf_computation((tf.int32, tf.int32), (tf.float32, tf.int32))\n def merge(accumulator1, accumulator2):\n del accumulator1 # Unused\n del accumulator2 # Unused\n return tf.constant(1), tf.constant(1)\n\n with self.assertRaises(TypeError):\n canonical_form.CanonicalForm(initialize, prepare, work, zero, accumulate,\n merge, report, bitwidth, update)\n\n def test_init_raises_type_error_with_bad_merge_result_type(self):\n (initialize, prepare, work, zero, accumulate, _, report, bitwidth,\n update) = _dummy_canonical_form_computations()\n\n @computations.tf_computation((tf.int32, tf.int32), (tf.int32, tf.int32))\n def merge(accumulator1, accumulator2):\n del accumulator1 # Unused\n del accumulator2 # Unused\n return tf.constant(1.0), tf.constant(1)\n\n with self.assertRaises(TypeError):\n canonical_form.CanonicalForm(initialize, prepare, work, zero, accumulate,\n merge, report, bitwidth, update)\n\n def test_init_raises_type_error_with_bad_report_parameter_type(self):\n (initialize, prepare, work, zero, accumulate, merge, _, bitwidth,\n update) = _dummy_canonical_form_computations()\n\n @computations.tf_computation(tf.float32, tf.int32)\n def report(accumulator):\n del accumulator # Unused\n return tf.constant(1.0)\n\n with self.assertRaises(TypeError):\n canonical_form.CanonicalForm(initialize, prepare, work, zero, accumulate,\n merge, report, bitwidth, update)\n\n def test_init_raises_type_error_with_bad_report_result_type(self):\n (initialize, prepare, work, zero, accumulate, merge, _, bitwidth,\n update) = _dummy_canonical_form_computations()\n\n @computations.tf_computation(tf.int32, tf.int32)\n def report(accumulator):\n del accumulator # Unused\n return tf.constant(1)\n\n with self.assertRaises(TypeError):\n canonical_form.CanonicalForm(initialize, prepare, work, zero, accumulate,\n merge, report, bitwidth, update)\n\n def test_init_raises_type_error_with_bad_update_first_parameter_type(self):\n (initialize, prepare, work, zero, accumulate, merge, report, bitwidth,\n _) = _dummy_canonical_form_computations()\n\n @computations.tf_computation(\n tf.float32, (tf.float32, computation_types.NamedTupleType([])))\n def update(server_state, global_update):\n del server_state # Unused\n del global_update # Unused\n return tf.constant(1), []\n\n with self.assertRaises(TypeError):\n canonical_form.CanonicalForm(initialize, prepare, work, zero, accumulate,\n merge, report, bitwidth, update)\n\n def test_init_raises_type_error_with_bad_update_second_parameter_type(self):\n (initialize, prepare, work, zero, accumulate, merge, report, bitwidth,\n _) = _dummy_canonical_form_computations()\n\n @computations.tf_computation(\n tf.int32, (tf.int32, computation_types.NamedTupleType([])))\n def update(server_state, global_update):\n del server_state # Unused\n del global_update # Unused\n return tf.constant(1), []\n\n with self.assertRaises(TypeError):\n canonical_form.CanonicalForm(initialize, prepare, work, zero, accumulate,\n merge, report, bitwidth, update)\n\n def test_init_raises_type_error_with_bad_update_result_type(self):\n (initialize, prepare, work, zero, accumulate, merge, report, bitwidth,\n _) = _dummy_canonical_form_computations()\n\n @computations.tf_computation(\n tf.int32, (tf.float32, computation_types.NamedTupleType([])))\n def update(server_state, global_update):\n del server_state # Unused\n del global_update # Unused\n return tf.constant(1.0), []\n\n with self.assertRaises(TypeError):\n canonical_form.CanonicalForm(initialize, prepare, work, zero, accumulate,\n merge, report, bitwidth, update)\n\n def test_summary(self):\n cf = test_utils.get_temperature_sensor_example()\n\n class CapturePrint(object):\n\n def __init__(self):\n self.summary = ''\n\n def __call__(self, msg):\n self.summary += msg + '\\n'\n\n capture = CapturePrint()\n cf.summary(print_fn=capture)\n # pyformat: disable\n self.assertEqual(\n capture.summary,\n 'initialize: ( -> <num_rounds=int32>)\\n'\n 'prepare : (<num_rounds=int32> -> <max_temperature=float32>)\\n'\n 'work : (<float32*,<max_temperature=float32>> -> <<<is_over=bool>,<>>,<num_readings=int32>>)\\n'\n 'zero : ( -> <num_total=int32,num_over=int32>)\\n'\n 'accumulate: (<<num_total=int32,num_over=int32>,<is_over=bool>> -> <num_total=int32,num_over=int32>)\\n'\n 'merge : (<<num_total=int32,num_over=int32>,<num_total=int32,num_over=int32>> -> <num_total=int32,num_over=int32>)\\n'\n 'report : (<num_total=int32,num_over=int32> -> <ratio_over_threshold=float32>)\\n'\n 'bitwidth : ( -> <>)\\n'\n 'update : ( -> <num_rounds=int32>)\\n'\n )\n # pyformat: enable\n\n\nif __name__ == '__main__':\n absltest.main()\n",
"# Lint as: python3\n# Copyright 2020, The TensorFlow Federated 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\nimport string\n\nimport tensorflow as tf\nimport tensorflow_federated as tff\n\nfrom tensorflow_federated.python.research.triehh import triehh_tf\nfrom tensorflow_federated.python.research.triehh import triehh_tff\n\n\nclass TriehhTffTest(tf.test.TestCase):\n\n def test_build_triehh_process_works_as_expeted(self):\n clients = 3\n num_sub_rounds = 4\n max_rounds = 6\n max_num_heavy_hitters = 3\n max_user_contribution = 100\n roots = (\n string.ascii_lowercase + string.digits + \"'@#-;*:./\" +\n triehh_tf.DEFAULT_TERMINATOR)\n possible_prefix_extensions = list(roots)\n\n iterative_process = triehh_tff.build_triehh_process(\n possible_prefix_extensions,\n num_sub_rounds,\n max_num_heavy_hitters,\n max_user_contribution,\n default_terminator=triehh_tf.DEFAULT_TERMINATOR)\n\n server_state = iterative_process.initialize()\n expected_discovered_prefixes = tf.constant([''], dtype=tf.string)\n expected_discovered_heavy_hitters = tf.constant([], dtype=tf.string)\n expected_accumulated_votes = tf.zeros(\n dtype=tf.int32,\n shape=[max_num_heavy_hitters,\n len(possible_prefix_extensions)])\n expected_round_num = tf.constant(0, dtype=tf.int32)\n\n self.assertAllEqual(server_state.discovered_prefixes,\n expected_discovered_prefixes)\n self.assertAllEqual(server_state.discovered_heavy_hitters,\n expected_discovered_heavy_hitters)\n self.assertAllEqual(server_state.accumulated_votes,\n expected_accumulated_votes)\n self.assertAllEqual(server_state.round_num, expected_round_num)\n\n def create_dataset_fn(client_id):\n del client_id\n return tf.data.Dataset.from_tensor_slices(['hello', 'hey', 'hi'])\n\n client_ids = list(range(100))\n\n client_data = tff.simulation.ClientData.from_clients_and_fn(\n client_ids=client_ids,\n create_tf_dataset_for_client_fn=create_dataset_fn)\n\n for round_num in range(max_rounds * num_sub_rounds):\n # TODO(b/152051528): Remove this once lookup table state is cleared in\n # eager executer.\n tff.framework.set_default_executor(tff.framework.local_executor_factory())\n sampled_clients = list(range(clients))\n sampled_datasets = [\n client_data.create_tf_dataset_for_client(client_id)\n for client_id in sampled_clients\n ]\n server_state, _ = iterative_process.next(server_state, sampled_datasets)\n\n if (round_num + 1) % num_sub_rounds == 0:\n if (max_num_heavy_hitters - len(server_state.discovered_heavy_hitters) <\n 1) or (server_state.discovered_prefixes.size == 0):\n # Training is done.\n # All max_num_heavy_hitters have been discovered.\n break\n\n expected_discovered_heavy_hitters = tf.constant(['hi', 'hey', 'hello'],\n dtype=tf.string)\n\n self.assertAllEqual(server_state.discovered_heavy_hitters,\n expected_discovered_heavy_hitters)\n\n\nif __name__ == '__main__':\n tf.compat.v1.enable_v2_behavior()\n tf.test.main()\n",
"# Lint as: python3\n# Copyright 2020, The TensorFlow Federated 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\"\"\"An implementation of the Federated Averaging algorithm.\n\nThis is intended to be a minimal stand-alone implementation of Federated\nAveraging, suitable for branching as a starting point for algorithm\nmodifications; see `tff.learning.build_federated_averaging_process` for a\nmore full-featured implementation.\n\nBased on the paper:\n\nCommunication-Efficient Learning of Deep Networks from Decentralized Data\n H. Brendan McMahan, Eider Moore, Daniel Ramage,\n Seth Hampson, Blaise Aguera y Arcas. AISTATS 2017.\n https://arxiv.org/abs/1602.05629\n\"\"\"\n\nimport tensorflow as tf\nimport tensorflow_federated as tff\n\nfrom tensorflow_federated.python.research.simple_fedavg.simple_fedavg_tf import build_server_broadcast_message\nfrom tensorflow_federated.python.research.simple_fedavg.simple_fedavg_tf import client_update\nfrom tensorflow_federated.python.research.simple_fedavg.simple_fedavg_tf import server_update\nfrom tensorflow_federated.python.research.simple_fedavg.simple_fedavg_tf import ServerState\n\n\ndef _initialize_optimizer_vars(model, optimizer):\n \"\"\"Creates optimizer variables to assign the optimizer's state.\"\"\"\n model_weights = model.weights\n model_delta = tf.nest.map_structure(tf.zeros_like, model_weights.trainable)\n # Create zero gradients to force an update that doesn't modify.\n # Force eagerly constructing the optimizer variables. Normally Keras lazily\n # creates the variables on first usage of the optimizer. Optimizers such as\n # Adam, Adagrad, or using momentum need to create a new set of variables shape\n # like the model weights.\n grads_and_vars = tf.nest.map_structure(\n lambda x, v: (tf.zeros_like(x), v), tf.nest.flatten(model_delta),\n tf.nest.flatten(model_weights.trainable))\n optimizer.apply_gradients(grads_and_vars)\n assert optimizer.variables()\n\n\ndef build_federated_averaging_process(\n model_fn,\n server_optimizer_fn=lambda: tf.keras.optimizers.SGD(learning_rate=1.0),\n client_optimizer_fn=lambda: tf.keras.optimizers.SGD(learning_rate=0.1)):\n \"\"\"Builds the TFF computations for optimization using federated averaging.\n\n Args:\n model_fn: A no-arg function that returns a\n `simple_fedavg_tf.KerasModelWrapper`.\n server_optimizer_fn: A no-arg function that returns a\n `tf.keras.optimizers.Optimizer` for server update.\n client_optimizer_fn: A no-arg function that returns a\n `tf.keras.optimizers.Optimizer` for client update.\n\n Returns:\n A `tff.templates.IterativeProcess`.\n \"\"\"\n\n dummy_model = model_fn()\n\n @tff.tf_computation\n def server_init_tf():\n model = model_fn()\n server_optimizer = server_optimizer_fn()\n _initialize_optimizer_vars(model, server_optimizer)\n return ServerState(\n model_weights=model.weights,\n optimizer_state=server_optimizer.variables(),\n round_num=0)\n\n server_state_type = server_init_tf.type_signature.result\n\n model_weights_type = server_state_type.model_weights\n\n @tff.tf_computation(server_state_type, model_weights_type.trainable)\n def server_update_fn(server_state, model_delta):\n model = model_fn()\n server_optimizer = server_optimizer_fn()\n _initialize_optimizer_vars(model, server_optimizer)\n return server_update(model, server_optimizer, server_state, model_delta)\n\n @tff.tf_computation(server_state_type)\n def server_message_fn(server_state):\n return build_server_broadcast_message(server_state)\n\n server_message_type = server_message_fn.type_signature.result\n tf_dataset_type = tff.SequenceType(dummy_model.input_spec)\n\n @tff.tf_computation(tf_dataset_type, server_message_type)\n def client_update_fn(tf_dataset, server_message):\n model = model_fn()\n client_optimizer = client_optimizer_fn()\n return client_update(model, tf_dataset, server_message, client_optimizer)\n\n federated_server_state_type = tff.FederatedType(server_state_type, tff.SERVER)\n federated_dataset_type = tff.FederatedType(tf_dataset_type, tff.CLIENTS)\n\n @tff.federated_computation(federated_server_state_type,\n federated_dataset_type)\n def run_one_round(server_state, federated_dataset):\n \"\"\"Orchestration logic for one round of computation.\n\n Args:\n server_state: A `ServerState`.\n federated_dataset: A federated `tf.data.Dataset` with placement\n `tff.CLIENTS`.\n\n Returns:\n A tuple of updated `ServerState` and `tf.Tensor` of average loss.\n \"\"\"\n server_message = tff.federated_map(server_message_fn, server_state)\n server_message_at_client = tff.federated_broadcast(server_message)\n\n client_outputs = tff.federated_map(\n client_update_fn, (federated_dataset, server_message_at_client))\n\n weight_denom = client_outputs.client_weight\n round_model_delta = tff.federated_mean(\n client_outputs.weights_delta, weight=weight_denom)\n\n server_state = tff.federated_map(server_update_fn,\n (server_state, round_model_delta))\n round_loss_metric = tff.federated_mean(\n client_outputs.model_output, weight=weight_denom)\n\n return server_state, round_loss_metric\n\n @tff.federated_computation\n def server_init_tff():\n \"\"\"Orchestration logic for server model initialization.\"\"\"\n return tff.federated_value(server_init_tf(), tff.SERVER)\n\n return tff.templates.IterativeProcess(\n initialize_fn=server_init_tff, next_fn=run_one_round)\n",
"# Lint as: python3\n# Copyright 2019, The TensorFlow Federated 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\nimport asyncio\nimport collections\nimport contextlib\nfrom unittest import mock\n\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\nimport grpc\nfrom grpc.framework.foundation import logging_pool\nimport portpicker\nimport tensorflow as tf\n\nfrom google.protobuf import any_pb2\nfrom tensorflow_federated.proto.v0 import executor_pb2\nfrom tensorflow_federated.proto.v0 import executor_pb2_grpc\nfrom tensorflow_federated.python.core.api import computation_types\nfrom tensorflow_federated.python.core.api import computations\nfrom tensorflow_federated.python.core.api import intrinsics\nfrom tensorflow_federated.python.core.impl.executors import execution_context\nfrom tensorflow_federated.python.core.impl.executors import executor_service\nfrom tensorflow_federated.python.core.impl.executors import executor_stacks\nfrom tensorflow_federated.python.core.impl.executors import executor_test_utils\nfrom tensorflow_federated.python.core.impl.executors import reference_resolving_executor\nfrom tensorflow_federated.python.core.impl.executors import remote_executor\nfrom tensorflow_federated.python.core.impl.types import placement_literals\n\ntf.compat.v1.enable_v2_behavior()\n\n\ndef create_remote_executor():\n port = portpicker.pick_unused_port()\n channel = grpc.insecure_channel('localhost:{}'.format(port))\n return remote_executor.RemoteExecutor(channel, 'REQUEST_REPLY')\n\n\[email protected]\ndef test_context(rpc_mode='REQUEST_REPLY'):\n port = portpicker.pick_unused_port()\n server_pool = logging_pool.pool(max_workers=1)\n server = grpc.server(server_pool)\n server.add_insecure_port('[::]:{}'.format(port))\n target_executor = executor_stacks.local_executor_factory(\n num_clients=3).create_executor({})\n tracer = executor_test_utils.TracingExecutor(target_executor)\n service = executor_service.ExecutorService(tracer)\n executor_pb2_grpc.add_ExecutorServicer_to_server(service, server)\n server.start()\n channel = grpc.insecure_channel('localhost:{}'.format(port))\n remote_exec = remote_executor.RemoteExecutor(channel, rpc_mode)\n executor = reference_resolving_executor.ReferenceResolvingExecutor(\n remote_exec)\n try:\n yield collections.namedtuple('_', 'executor tracer')(executor, tracer)\n finally:\n executor.close()\n tracer.close()\n try:\n channel.close()\n except AttributeError:\n pass # Public gRPC channel doesn't support close()\n finally:\n server.stop(None)\n\n\ndef _invoke(ex, comp, arg=None):\n loop = asyncio.get_event_loop()\n v1 = loop.run_until_complete(ex.create_value(comp))\n if arg is not None:\n type_spec = v1.type_signature.parameter\n v2 = loop.run_until_complete(ex.create_value(arg, type_spec))\n else:\n v2 = None\n v3 = loop.run_until_complete(ex.create_call(v1, v2))\n return loop.run_until_complete(v3.compute())\n\n\ndef _raise_grpc_error_unavailable(*args):\n del args # Unused\n error = grpc.RpcError()\n error.code = lambda: grpc.StatusCode.UNAVAILABLE\n raise error\n\n\ndef _raise_non_retryable_grpc_error(*args):\n del args # Unused\n error = grpc.RpcError()\n error.code = lambda: grpc.StatusCode.ABORTED\n raise error\n\n\[email protected](\n 'tensorflow_federated.proto.v0.executor_pb2_grpc.ExecutorStub'\n)\nclass RemoteValueTest(absltest.TestCase):\n\n def test_compute_returns_result(self, mock_stub):\n tensor_proto = tf.make_tensor_proto(1)\n any_pb = any_pb2.Any()\n any_pb.Pack(tensor_proto)\n value = executor_pb2.Value(tensor=any_pb)\n response = executor_pb2.ComputeResponse(value=value)\n instance = mock_stub.return_value\n instance.Compute = mock.Mock(side_effect=[response])\n loop = asyncio.get_event_loop()\n executor = create_remote_executor()\n type_signature = computation_types.FunctionType(None, tf.int32)\n comp = remote_executor.RemoteValue(executor_pb2.ValueRef(), type_signature,\n executor)\n\n result = loop.run_until_complete(comp.compute())\n\n instance.Compute.assert_called_once()\n self.assertEqual(result, 1)\n\n def test_compute_raises_retryable_error_on_grpc_error_unavailable(\n self, mock_stub):\n instance = mock_stub.return_value\n instance.Compute = mock.Mock(side_effect=_raise_grpc_error_unavailable)\n loop = asyncio.get_event_loop()\n executor = create_remote_executor()\n type_signature = computation_types.FunctionType(None, tf.int32)\n comp = remote_executor.RemoteValue(executor_pb2.ValueRef(), type_signature,\n executor)\n\n with self.assertRaises(execution_context.RetryableError):\n loop.run_until_complete(comp.compute())\n\n def test_compute_reraises_grpc_error(self, mock_stub):\n instance = mock_stub.return_value\n instance.Compute = mock.Mock(side_effect=_raise_non_retryable_grpc_error)\n loop = asyncio.get_event_loop()\n executor = create_remote_executor()\n type_signature = computation_types.FunctionType(None, tf.int32)\n comp = remote_executor.RemoteValue(executor_pb2.ValueRef(), type_signature,\n executor)\n\n with self.assertRaises(grpc.RpcError) as context:\n loop.run_until_complete(comp.compute())\n\n self.assertEqual(context.exception.code(), grpc.StatusCode.ABORTED)\n\n def test_compute_reraises_type_error(self, mock_stub):\n instance = mock_stub.return_value\n instance.Compute = mock.Mock(side_effect=TypeError)\n loop = asyncio.get_event_loop()\n executor = create_remote_executor()\n type_signature = computation_types.FunctionType(None, tf.int32)\n comp = remote_executor.RemoteValue(executor_pb2.ValueRef(), type_signature,\n executor)\n\n with self.assertRaises(TypeError):\n loop.run_until_complete(comp.compute())\n\n\[email protected](\n 'tensorflow_federated.proto.v0.executor_pb2_grpc.ExecutorStub'\n)\nclass RemoteExecutorTest(absltest.TestCase):\n\n def test_create_value_returns_remote_value(self, mock_stub):\n response = executor_pb2.CreateValueResponse()\n instance = mock_stub.return_value\n instance.CreateValue = mock.Mock(side_effect=[response])\n loop = asyncio.get_event_loop()\n executor = create_remote_executor()\n\n result = loop.run_until_complete(executor.create_value(1, tf.int32))\n\n instance.CreateValue.assert_called_once()\n self.assertIsInstance(result, remote_executor.RemoteValue)\n\n def test_create_value_raises_retryable_error_on_grpc_error_unavailable(\n self, mock_stub):\n instance = mock_stub.return_value\n instance.CreateValue = mock.Mock(side_effect=_raise_grpc_error_unavailable)\n loop = asyncio.get_event_loop()\n executor = create_remote_executor()\n\n with self.assertRaises(execution_context.RetryableError):\n loop.run_until_complete(executor.create_value(1, tf.int32))\n\n def test_create_value_reraises_grpc_error(self, mock_stub):\n instance = mock_stub.return_value\n instance.CreateValue = mock.Mock(\n side_effect=_raise_non_retryable_grpc_error)\n loop = asyncio.get_event_loop()\n executor = create_remote_executor()\n\n with self.assertRaises(grpc.RpcError) as context:\n loop.run_until_complete(executor.create_value(1, tf.int32))\n\n self.assertEqual(context.exception.code(), grpc.StatusCode.ABORTED)\n\n def test_create_value_reraises_type_error(self, mock_stub):\n instance = mock_stub.return_value\n instance.CreateValue = mock.Mock(side_effect=TypeError)\n loop = asyncio.get_event_loop()\n executor = create_remote_executor()\n\n with self.assertRaises(TypeError):\n loop.run_until_complete(executor.create_value(1, tf.int32))\n\n def test_create_call_returns_remote_value(self, mock_stub):\n response = executor_pb2.CreateCallResponse()\n instance = mock_stub.return_value\n instance.CreateCall = mock.Mock(side_effect=[response])\n loop = asyncio.get_event_loop()\n executor = create_remote_executor()\n type_signature = computation_types.FunctionType(None, tf.int32)\n fn = remote_executor.RemoteValue(executor_pb2.ValueRef(), type_signature,\n executor)\n\n result = loop.run_until_complete(executor.create_call(fn, None))\n\n instance.CreateCall.assert_called_once()\n self.assertIsInstance(result, remote_executor.RemoteValue)\n\n def test_create_call_raises_retryable_error_on_grpc_error_unavailable(\n self, mock_stub):\n instance = mock_stub.return_value\n instance.CreateCall = mock.Mock(side_effect=_raise_grpc_error_unavailable)\n loop = asyncio.get_event_loop()\n executor = create_remote_executor()\n type_signature = computation_types.FunctionType(None, tf.int32)\n comp = remote_executor.RemoteValue(executor_pb2.ValueRef(), type_signature,\n executor)\n\n with self.assertRaises(execution_context.RetryableError):\n loop.run_until_complete(executor.create_call(comp, None))\n\n def test_create_call_reraises_grpc_error(self, mock_stub):\n instance = mock_stub.return_value\n instance.CreateCall = mock.Mock(side_effect=_raise_non_retryable_grpc_error)\n loop = asyncio.get_event_loop()\n executor = create_remote_executor()\n type_signature = computation_types.FunctionType(None, tf.int32)\n comp = remote_executor.RemoteValue(executor_pb2.ValueRef(), type_signature,\n executor)\n\n with self.assertRaises(grpc.RpcError) as context:\n loop.run_until_complete(executor.create_call(comp, None))\n\n self.assertEqual(context.exception.code(), grpc.StatusCode.ABORTED)\n\n def test_create_call_reraises_type_error(self, mock_stub):\n instance = mock_stub.return_value\n instance.CreateCall = mock.Mock(side_effect=TypeError)\n loop = asyncio.get_event_loop()\n executor = create_remote_executor()\n type_signature = computation_types.FunctionType(None, tf.int32)\n comp = remote_executor.RemoteValue(executor_pb2.ValueRef(), type_signature,\n executor)\n\n with self.assertRaises(TypeError):\n loop.run_until_complete(executor.create_call(comp))\n\n def test_create_tuple_returns_remote_value(self, mock_stub):\n response = executor_pb2.CreateTupleResponse()\n instance = mock_stub.return_value\n instance.CreateTuple = mock.Mock(side_effect=[response])\n loop = asyncio.get_event_loop()\n executor = create_remote_executor()\n type_signature = computation_types.TensorType(tf.int32)\n value_1 = remote_executor.RemoteValue(executor_pb2.ValueRef(),\n type_signature, executor)\n value_2 = remote_executor.RemoteValue(executor_pb2.ValueRef(),\n type_signature, executor)\n\n result = loop.run_until_complete(executor.create_tuple([value_1, value_2]))\n\n instance.CreateTuple.assert_called_once()\n self.assertIsInstance(result, remote_executor.RemoteValue)\n\n def test_create_tuple_raises_retryable_error_on_grpc_error_unavailable(\n self, mock_stub):\n instance = mock_stub.return_value\n instance.CreateTuple = mock.Mock(side_effect=_raise_grpc_error_unavailable)\n loop = asyncio.get_event_loop()\n executor = create_remote_executor()\n type_signature = computation_types.TensorType(tf.int32)\n value_1 = remote_executor.RemoteValue(executor_pb2.ValueRef(),\n type_signature, executor)\n value_2 = remote_executor.RemoteValue(executor_pb2.ValueRef(),\n type_signature, executor)\n\n with self.assertRaises(execution_context.RetryableError):\n loop.run_until_complete(executor.create_tuple([value_1, value_2]))\n\n def test_create_tuple_reraises_grpc_error(self, mock_stub):\n instance = mock_stub.return_value\n instance.CreateTuple = mock.Mock(\n side_effect=_raise_non_retryable_grpc_error)\n loop = asyncio.get_event_loop()\n executor = create_remote_executor()\n type_signature = computation_types.TensorType(tf.int32)\n value_1 = remote_executor.RemoteValue(executor_pb2.ValueRef(),\n type_signature, executor)\n value_2 = remote_executor.RemoteValue(executor_pb2.ValueRef(),\n type_signature, executor)\n\n with self.assertRaises(grpc.RpcError) as context:\n loop.run_until_complete(executor.create_tuple([value_1, value_2]))\n\n self.assertEqual(context.exception.code(), grpc.StatusCode.ABORTED)\n\n def test_create_tuple_reraises_type_error(self, mock_stub):\n instance = mock_stub.return_value\n instance.CreateTuple = mock.Mock(side_effect=TypeError)\n loop = asyncio.get_event_loop()\n executor = create_remote_executor()\n type_signature = computation_types.TensorType(tf.int32)\n value_1 = remote_executor.RemoteValue(executor_pb2.ValueRef(),\n type_signature, executor)\n value_2 = remote_executor.RemoteValue(executor_pb2.ValueRef(),\n type_signature, executor)\n\n with self.assertRaises(TypeError):\n loop.run_until_complete(executor.create_tuple([value_1, value_2]))\n\n def test_create_selection_returns_remote_value(self, mock_stub):\n response = executor_pb2.CreateSelectionResponse()\n instance = mock_stub.return_value\n instance.CreateSelection = mock.Mock(side_effect=[response])\n loop = asyncio.get_event_loop()\n executor = create_remote_executor()\n type_signature = computation_types.NamedTupleType([tf.int32, tf.int32])\n source = remote_executor.RemoteValue(executor_pb2.ValueRef(),\n type_signature, executor)\n\n result = loop.run_until_complete(executor.create_selection(source, index=0))\n\n instance.CreateSelection.assert_called_once()\n self.assertIsInstance(result, remote_executor.RemoteValue)\n\n def test_create_selection_raises_retryable_error_on_grpc_error_unavailable(\n self, mock_stub):\n instance = mock_stub.return_value\n instance.CreateSelection = mock.Mock(\n side_effect=_raise_grpc_error_unavailable)\n loop = asyncio.get_event_loop()\n executor = create_remote_executor()\n type_signature = computation_types.NamedTupleType([tf.int32, tf.int32])\n source = remote_executor.RemoteValue(executor_pb2.ValueRef(),\n type_signature, executor)\n\n with self.assertRaises(execution_context.RetryableError):\n loop.run_until_complete(executor.create_selection(source, index=0))\n\n def test_create_selection_reraises_non_retryable_grpc_error(self, mock_stub):\n instance = mock_stub.return_value\n instance.CreateSelection = mock.Mock(\n side_effect=_raise_non_retryable_grpc_error)\n loop = asyncio.get_event_loop()\n executor = create_remote_executor()\n type_signature = computation_types.NamedTupleType([tf.int32, tf.int32])\n source = remote_executor.RemoteValue(executor_pb2.ValueRef(),\n type_signature, executor)\n\n with self.assertRaises(grpc.RpcError) as context:\n loop.run_until_complete(executor.create_selection(source, index=0))\n\n self.assertEqual(context.exception.code(), grpc.StatusCode.ABORTED)\n\n def test_create_selection_reraises_type_error(self, mock_stub):\n instance = mock_stub.return_value\n instance.CreateSelection = mock.Mock(side_effect=TypeError)\n loop = asyncio.get_event_loop()\n executor = create_remote_executor()\n type_signature = computation_types.NamedTupleType([tf.int32, tf.int32])\n source = remote_executor.RemoteValue(executor_pb2.ValueRef(),\n type_signature, executor)\n\n with self.assertRaises(TypeError):\n loop.run_until_complete(executor.create_selection(source, index=0))\n\n\nclass RemoteExecutorIntegrationTest(parameterized.TestCase):\n\n def test_no_arg_tf_computation(self):\n with test_context() as context:\n\n @computations.tf_computation\n def comp():\n return 10\n\n result = _invoke(context.executor, comp)\n self.assertEqual(result, 10)\n\n def test_one_arg_tf_computation(self):\n with test_context() as context:\n\n @computations.tf_computation(tf.int32)\n def comp(x):\n return x + 1\n\n result = _invoke(context.executor, comp, 10)\n self.assertEqual(result, 11)\n\n def test_two_arg_tf_computation(self):\n with test_context() as context:\n\n @computations.tf_computation(tf.int32, tf.int32)\n def comp(x, y):\n return x + y\n\n result = _invoke(context.executor, comp, (10, 20))\n self.assertEqual(result, 30)\n\n def test_with_selection(self):\n with test_context() as context:\n self._test_with_selection(context)\n\n def test_with_selection_streaming(self):\n with test_context(rpc_mode='STREAMING') as context:\n self._test_with_selection(context)\n\n def _test_with_selection(self, context):\n\n @computations.tf_computation(tf.int32)\n def foo(x):\n return collections.OrderedDict([('A', x + 10), ('B', x + 20)])\n\n @computations.tf_computation(tf.int32, tf.int32)\n def bar(x, y):\n return x + y\n\n @computations.federated_computation(tf.int32)\n def baz(x):\n return bar(foo(x).A, foo(x).B)\n\n result = _invoke(context.executor, baz, 100)\n self.assertEqual(result, 230)\n\n # Make sure exactly two selections happened.\n seletions = [x for x in context.tracer.trace\n if x[0] == 'create_selection']\n self.assertLen(seletions, 2)\n\n @parameterized.named_parameters(\n ('request_reply', 'REQUEST_REPLY'),\n ('streaming', 'STREAMING'),\n )\n def test_execution_of_tensorflow(self, rpc_mode):\n\n @computations.tf_computation\n def comp():\n return tf.math.add(5, 5)\n\n with test_context(rpc_mode=rpc_mode) as context:\n result = _invoke(context.executor, comp)\n\n self.assertEqual(result, 10)\n\n def test_with_federated_computations(self):\n with test_context() as context:\n\n @computations.federated_computation(\n computation_types.FederatedType(tf.int32,\n placement_literals.CLIENTS))\n def foo(x):\n return intrinsics.federated_sum(x)\n\n result = _invoke(context.executor, foo, [10, 20, 30])\n self.assertEqual(result, 60)\n\n @computations.federated_computation(\n computation_types.FederatedType(tf.int32,\n placement_literals.SERVER))\n def bar(x):\n return intrinsics.federated_broadcast(x)\n\n result = _invoke(context.executor, bar, 50)\n self.assertEqual(result, 50)\n\n @computations.tf_computation(tf.int32)\n def add_one(x):\n return x + 1\n\n @computations.federated_computation(\n computation_types.FederatedType(tf.int32,\n placement_literals.SERVER))\n def baz(x):\n value = intrinsics.federated_broadcast(x)\n return intrinsics.federated_map(add_one, value)\n\n result = _invoke(context.executor, baz, 50)\n self.assertEqual(result, [51, 51, 51])\n\n\nif __name__ == '__main__':\n absltest.main()\n",
"# Lint as: python3\n# Copyright 2019, The TensorFlow Federated 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\nimport asyncio\nimport collections\nfrom unittest import mock\n\nfrom absl.testing import absltest\nimport numpy as np\nimport tensorflow as tf\n\nfrom tensorflow_federated.python.common_libs import anonymous_tuple\nfrom tensorflow_federated.python.core.api import computation_types\nfrom tensorflow_federated.python.core.api import computations\nfrom tensorflow_federated.python.core.impl import computation_impl\nfrom tensorflow_federated.python.core.impl.executors import caching_executor\nfrom tensorflow_federated.python.core.impl.executors import eager_tf_executor\nfrom tensorflow_federated.python.core.impl.executors import executor_base\nfrom tensorflow_federated.python.core.impl.executors import executor_factory\nfrom tensorflow_federated.python.core.impl.executors import executor_test_utils\nfrom tensorflow_federated.python.core.impl.executors import reference_resolving_executor\n\ntf.compat.v1.enable_v2_behavior()\n\n\ndef create_test_executor_factory():\n executor = eager_tf_executor.EagerTFExecutor()\n executor = caching_executor.CachingExecutor(executor)\n executor = reference_resolving_executor.ReferenceResolvingExecutor(executor)\n return executor_factory.ExecutorFactoryImpl(lambda _: executor)\n\n\ndef _make_executor_and_tracer_for_test():\n tracer = executor_test_utils.TracingExecutor(\n eager_tf_executor.EagerTFExecutor())\n ex = caching_executor.CachingExecutor(tracer)\n return ex, tracer\n\n\ndef _tensor_to_id(iterable):\n # Tensor is not hashable in TF 2.0 so we hash it using id().\n return [\n item if not isinstance(item, tf.Tensor) else id(item) for item in iterable\n ]\n\n\nclass TestError(Exception):\n \"\"\"An error for unittests.\"\"\"\n\n\nasync def raise_error(*args, **kwargs):\n \"\"\"A function for mock executors that always raises an error.\"\"\"\n del args # Unused.\n del kwargs # Unused.\n await asyncio.sleep(1)\n raise TestError()\n\n\n# An arbitrary value for testing.\nTEST_VALUE = True\n\n\nasync def create_test_value(*args, **kwargs):\n \"\"\"A function for mock executors that returns an arbitrary value.\"\"\"\n del args # Unused.\n del kwargs # Unused.\n await asyncio.sleep(1)\n return TEST_VALUE\n\n\[email protected]_computation\ndef foo():\n return tf.constant(10)\n\n\nclass CachingExecutorTest(absltest.TestCase):\n\n def test_create_value_does_not_cache_error(self):\n loop = asyncio.get_event_loop()\n mock_executor = mock.create_autospec(executor_base.Executor)\n mock_executor.create_value.side_effect = raise_error\n cached_executor = caching_executor.CachingExecutor(mock_executor)\n with self.assertRaises(TestError):\n _ = loop.run_until_complete(cached_executor.create_value(1.0, tf.float32))\n with self.assertRaises(TestError):\n _ = loop.run_until_complete(cached_executor.create_value(1.0, tf.float32))\n # Ensure create_value was called twice on the mock (not cached and only\n # called once).\n mock_executor.create_value.assert_has_calls([\n mock.call(1.0, computation_types.TensorType(tf.float32)),\n mock.call(1.0, computation_types.TensorType(tf.float32))\n ])\n\n def test_create_value_does_not_cache_error_avoids_double_cache_delete(self):\n loop = asyncio.get_event_loop()\n mock_executor = mock.create_autospec(executor_base.Executor)\n mock_executor.create_value.side_effect = raise_error\n cached_executor = caching_executor.CachingExecutor(mock_executor)\n future1 = cached_executor.create_value(1.0, tf.float32)\n future2 = cached_executor.create_value(1.0, tf.float32)\n results = loop.run_until_complete(\n asyncio.gather(future1, future2, return_exceptions=True))\n # Ensure create_call is only called once, since the first call inserts the\n # inner executor future into the cache. However we expect two errors to be\n # returned.\n mock_executor.create_value.assert_called_once_with(\n 1.0, computation_types.TensorType(tf.float32))\n self.assertLen(results, 2)\n self.assertIsInstance(results[0], TestError)\n self.assertIsInstance(results[1], TestError)\n\n def test_create_call_does_not_cache_error(self):\n loop = asyncio.get_event_loop()\n mock_executor = mock.create_autospec(executor_base.Executor)\n mock_executor.create_value.side_effect = create_test_value\n mock_executor.create_call.side_effect = raise_error\n cached_executor = caching_executor.CachingExecutor(mock_executor)\n v = loop.run_until_complete(cached_executor.create_value(foo))\n with self.assertRaises(TestError):\n _ = loop.run_until_complete(cached_executor.create_call(v))\n with self.assertRaises(TestError):\n _ = loop.run_until_complete(cached_executor.create_call(v))\n # Ensure create_call was called twice on the mock (not cached and only\n # called once).\n mock_executor.create_call.assert_has_calls(\n [mock.call(TEST_VALUE), mock.call(TEST_VALUE)])\n\n def test_create_call_does_not_cache_error_avoids_double_cache_delete(self):\n loop = asyncio.get_event_loop()\n mock_executor = mock.create_autospec(executor_base.Executor)\n mock_executor.create_value.side_effect = create_test_value\n mock_executor.create_call.side_effect = raise_error\n cached_executor = caching_executor.CachingExecutor(mock_executor)\n v = loop.run_until_complete(cached_executor.create_value(foo))\n future_call1 = cached_executor.create_call(v)\n future_call2 = cached_executor.create_call(v)\n results = loop.run_until_complete(\n asyncio.gather(future_call1, future_call2, return_exceptions=True))\n # Ensure create_call is only called once, since the first call inserts the\n # inner executor future into the cache. However we expect two errors to be\n # returned.\n mock_executor.create_call.assert_called_once_with(TEST_VALUE)\n self.assertLen(results, 2)\n self.assertIsInstance(results[0], TestError)\n self.assertIsInstance(results[1], TestError)\n\n def test_create_tuple_does_not_cache_error(self):\n loop = asyncio.get_event_loop()\n mock_executor = mock.create_autospec(executor_base.Executor)\n mock_executor.create_value.side_effect = create_test_value\n mock_executor.create_tuple.side_effect = raise_error\n cached_executor = caching_executor.CachingExecutor(mock_executor)\n value = loop.run_until_complete(cached_executor.create_value(foo))\n value_tuple = (value, value)\n with self.assertRaises(TestError):\n _ = loop.run_until_complete(cached_executor.create_tuple(value_tuple))\n with self.assertRaises(TestError):\n _ = loop.run_until_complete(cached_executor.create_tuple(value_tuple))\n # Ensure create_tuple was called twice on the mock (not cached and only\n # called once).\n anon_tuple_value = anonymous_tuple.AnonymousTuple([(None, TEST_VALUE),\n (None, TEST_VALUE)])\n mock_executor.create_tuple.assert_has_calls(\n [mock.call(anon_tuple_value),\n mock.call(anon_tuple_value)])\n\n def test_create_tuple_does_not_cache_error_avoids_double_delete(self):\n loop = asyncio.get_event_loop()\n mock_executor = mock.create_autospec(executor_base.Executor)\n mock_executor.create_value.side_effect = create_test_value\n mock_executor.create_tuple.side_effect = raise_error\n cached_executor = caching_executor.CachingExecutor(mock_executor)\n value = loop.run_until_complete(cached_executor.create_value(foo))\n value_tuple = (value, value)\n future1 = cached_executor.create_tuple(value_tuple)\n future2 = cached_executor.create_tuple(value_tuple)\n results = loop.run_until_complete(\n asyncio.gather(future1, future2, return_exceptions=True))\n # Ensure create_call is only called once, since the first call inserts the\n # inner executor future into the cache. However we expect two errors to be\n # returned.\n mock_executor.create_tuple.assert_called_once_with(\n anonymous_tuple.AnonymousTuple([(None, TEST_VALUE),\n (None, TEST_VALUE)]))\n self.assertLen(results, 2)\n self.assertIsInstance(results[0], TestError)\n self.assertIsInstance(results[1], TestError)\n\n def test_create_selection_does_not_cache_error(self):\n loop = asyncio.get_event_loop()\n mock_executor = mock.create_autospec(executor_base.Executor)\n mock_executor.create_value.side_effect = create_test_value\n mock_executor.create_selection.side_effect = raise_error\n cached_executor = caching_executor.CachingExecutor(mock_executor)\n value = loop.run_until_complete(\n cached_executor.create_value((1, 2),\n computation_types.NamedTupleType(\n (tf.int32, tf.int32))))\n with self.assertRaises(TestError):\n _ = loop.run_until_complete(cached_executor.create_selection(value, 1))\n with self.assertRaises(TestError):\n _ = loop.run_until_complete(cached_executor.create_selection(value, 1))\n # Ensure create_tuple was called twice on the mock (not cached and only\n # called once).\n mock_executor.create_selection.assert_has_calls([])\n\n def test_create_selection_does_not_cache_error_avoids_double_cache_delete(\n self):\n loop = asyncio.get_event_loop()\n mock_executor = mock.create_autospec(executor_base.Executor)\n mock_executor.create_value.side_effect = create_test_value\n mock_executor.create_selection.side_effect = raise_error\n cached_executor = caching_executor.CachingExecutor(mock_executor)\n value = loop.run_until_complete(\n cached_executor.create_value((1, 2),\n computation_types.NamedTupleType(\n (tf.int32, tf.int32))))\n future1 = cached_executor.create_selection(value, 1)\n future2 = cached_executor.create_selection(value, 1)\n results = loop.run_until_complete(\n asyncio.gather(future1, future2, return_exceptions=True))\n # Ensure create_tuple was called twice on the mock (not cached and only\n # called once).\n mock_executor.create_selection.assert_has_calls([])\n self.assertLen(results, 2)\n self.assertIsInstance(results[0], TestError)\n self.assertIsInstance(results[1], TestError)\n\n def test_close_clears_cache(self):\n ex, _ = _make_executor_and_tracer_for_test()\n loop = asyncio.get_event_loop()\n v1 = loop.run_until_complete(ex.create_value(10, tf.int32))\n v2 = loop.run_until_complete(ex.create_value(10, tf.int32))\n self.assertIs(v2, v1)\n ex.close()\n v3 = loop.run_until_complete(ex.create_value(10, tf.int32))\n self.assertIsNot(v3, v1)\n\n def test_with_integer_constant(self):\n ex, tracer = _make_executor_and_tracer_for_test()\n loop = asyncio.get_event_loop()\n v1 = loop.run_until_complete(ex.create_value(10, tf.int32))\n self.assertIsInstance(v1, caching_executor.CachedValue)\n self.assertEqual(str(v1.identifier), '1')\n c1 = loop.run_until_complete(v1.compute())\n self.assertEqual(c1.numpy(), 10)\n v2 = loop.run_until_complete(ex.create_value(10, tf.int32))\n self.assertIsInstance(v2, caching_executor.CachedValue)\n self.assertEqual(str(v2.identifier), '1')\n self.assertIs(v2, v1)\n expected_trace = [('create_value', 10,\n computation_types.TensorType(tf.int32), 1),\n ('compute', 1, c1)]\n self.assertLen(tracer.trace, len(expected_trace))\n for x, y in zip(tracer.trace, expected_trace):\n self.assertCountEqual(_tensor_to_id(x), _tensor_to_id(y))\n\n def test_with_no_arg_tf_computation(self):\n ex, tracer = _make_executor_and_tracer_for_test()\n loop = asyncio.get_event_loop()\n\n v1 = loop.run_until_complete(ex.create_value(foo))\n self.assertIsInstance(v1, caching_executor.CachedValue)\n self.assertEqual(str(v1.identifier), '1')\n v2 = loop.run_until_complete(ex.create_call(v1))\n self.assertIsInstance(v2, caching_executor.CachedValue)\n self.assertEqual(str(v2.identifier), '1()')\n c2 = loop.run_until_complete(v2.compute())\n self.assertEqual(c2.numpy(), 10)\n v3 = loop.run_until_complete(ex.create_value(foo))\n self.assertIsInstance(v3, caching_executor.CachedValue)\n self.assertEqual(str(v3.identifier), '1')\n self.assertIs(v3, v1)\n v4 = loop.run_until_complete(ex.create_call(v3))\n self.assertIsInstance(v4, caching_executor.CachedValue)\n self.assertEqual(str(v4.identifier), '1()')\n self.assertIs(v4, v2)\n c4 = loop.run_until_complete(v4.compute())\n self.assertEqual(c4.numpy(), 10)\n expected_trace = [('create_value',\n computation_impl.ComputationImpl.get_proto(foo),\n foo.type_signature, 1), ('create_call', 1, 2),\n ('compute', 2, c4)]\n self.assertLen(tracer.trace, len(expected_trace))\n for x, y in zip(tracer.trace, expected_trace):\n self.assertCountEqual(_tensor_to_id(x), _tensor_to_id(y))\n\n def test_with_one_arg_tf_computation(self):\n ex, tracer = _make_executor_and_tracer_for_test()\n loop = asyncio.get_event_loop()\n\n @computations.tf_computation(tf.int32)\n def add_one(x):\n return tf.add(x, 1)\n\n v1 = loop.run_until_complete(ex.create_value(add_one))\n self.assertEqual(str(v1.identifier), '1')\n v2 = loop.run_until_complete(ex.create_value(10, tf.int32))\n self.assertEqual(str(v2.identifier), '2')\n v3 = loop.run_until_complete(ex.create_call(v1, v2))\n self.assertEqual(str(v3.identifier), '1(2)')\n v4 = loop.run_until_complete(ex.create_value(add_one))\n self.assertIs(v4, v1)\n v5 = loop.run_until_complete(ex.create_value(10, tf.int32))\n self.assertIs(v5, v2)\n v6 = loop.run_until_complete(ex.create_call(v4, v5))\n self.assertIs(v6, v3)\n c6 = loop.run_until_complete(v6.compute())\n self.assertEqual(c6.numpy(), 11)\n expected_trace = [\n ('create_value', computation_impl.ComputationImpl.get_proto(add_one),\n add_one.type_signature, 1),\n ('create_value', 10, computation_types.TensorType(tf.int32), 2),\n ('create_call', 1, 2, 3), ('compute', 3, c6)\n ]\n self.assertLen(tracer.trace, len(expected_trace))\n for x, y in zip(tracer.trace, expected_trace):\n self.assertCountEqual(_tensor_to_id(x), _tensor_to_id(y))\n\n def test_with_tuple_of_unnamed_elements(self):\n ex, _ = _make_executor_and_tracer_for_test()\n loop = asyncio.get_event_loop()\n\n v1 = loop.run_until_complete(ex.create_value(10, tf.int32))\n self.assertEqual(str(v1.identifier), '1')\n v2 = loop.run_until_complete(ex.create_value(11, tf.int32))\n self.assertEqual(str(v2.identifier), '2')\n v3 = loop.run_until_complete(ex.create_tuple([v1, v2]))\n self.assertEqual(str(v3.identifier), '<1,2>')\n v4 = loop.run_until_complete(ex.create_tuple((v1, v2)))\n self.assertIs(v4, v3)\n c4 = loop.run_until_complete(v4.compute())\n self.assertEqual(\n str(anonymous_tuple.map_structure(lambda x: x.numpy(), c4)), '<10,11>')\n\n def test_with_tuple_of_named_elements(self):\n ex, _ = _make_executor_and_tracer_for_test()\n loop = asyncio.get_event_loop()\n\n v1 = loop.run_until_complete(ex.create_value(10, tf.int32))\n self.assertEqual(str(v1.identifier), '1')\n v2 = loop.run_until_complete(ex.create_value(11, tf.int32))\n self.assertEqual(str(v2.identifier), '2')\n v3 = loop.run_until_complete(\n ex.create_tuple(collections.OrderedDict([('P', v1), ('Q', v2)])))\n self.assertEqual(str(v3.identifier), '<P=1,Q=2>')\n v4 = loop.run_until_complete(\n ex.create_tuple(collections.OrderedDict([('P', v1), ('Q', v2)])))\n self.assertIs(v4, v3)\n c4 = loop.run_until_complete(v4.compute())\n self.assertEqual(\n str(anonymous_tuple.map_structure(lambda x: x.numpy(), c4)),\n '<P=10,Q=11>')\n\n def test_with_selection_by_index(self):\n ex, _ = _make_executor_and_tracer_for_test()\n loop = asyncio.get_event_loop()\n\n v1 = loop.run_until_complete(\n ex.create_value([10, 20],\n computation_types.NamedTupleType([tf.int32, tf.int32])))\n self.assertEqual(str(v1.identifier), '1')\n v2 = loop.run_until_complete(ex.create_selection(v1, index=0))\n self.assertEqual(str(v2.identifier), '1[0]')\n v3 = loop.run_until_complete(ex.create_selection(v1, index=1))\n self.assertEqual(str(v3.identifier), '1[1]')\n v4 = loop.run_until_complete(ex.create_selection(v1, index=0))\n self.assertIs(v4, v2)\n v5 = loop.run_until_complete(ex.create_selection(v1, index=1))\n self.assertIs(v5, v3)\n c5 = loop.run_until_complete(v5.compute())\n self.assertEqual(c5.numpy(), 20)\n\n def test_with_numpy_array(self):\n ex, _ = _make_executor_and_tracer_for_test()\n loop = asyncio.get_event_loop()\n v1 = loop.run_until_complete(\n ex.create_value(np.array([10]), (tf.int32, [1])))\n self.assertEqual(str(v1.identifier), '1')\n c1 = loop.run_until_complete(v1.compute())\n self.assertEqual(c1.numpy(), 10)\n v2 = loop.run_until_complete(\n ex.create_value(np.array([10]), (tf.int32, [1])))\n self.assertIs(v2, v1)\n\n def test_with_eager_dataset(self):\n ex, _ = _make_executor_and_tracer_for_test()\n loop = asyncio.get_event_loop()\n\n @computations.tf_computation(computation_types.SequenceType(tf.int32))\n def ds_reduce(ds):\n return ds.reduce(np.int32(0), lambda x, y: x + y)\n\n v1 = loop.run_until_complete(ex.create_value(ds_reduce))\n self.assertEqual(str(v1.identifier), '1')\n ds = tf.data.Dataset.from_tensor_slices([10, 20, 30])\n v2 = loop.run_until_complete(\n ex.create_value(ds, computation_types.SequenceType(tf.int32)))\n self.assertEqual(str(v2.identifier), '2')\n v3 = loop.run_until_complete(ex.create_call(v1, v2))\n self.assertEqual(str(v3.identifier), '1(2)')\n c3 = loop.run_until_complete(v3.compute())\n self.assertEqual(c3.numpy(), 60)\n v4 = loop.run_until_complete(\n ex.create_value(ds, computation_types.SequenceType(tf.int32)))\n self.assertIs(v4, v2)\n\n def test_execution_of_tensorflow(self):\n\n @computations.tf_computation\n def comp():\n return tf.math.add(5, 5)\n\n executor = create_test_executor_factory()\n with executor_test_utils.install_executor(executor):\n result = comp()\n\n self.assertEqual(result, 10)\n\n\nif __name__ == '__main__':\n absltest.main()\n",
"# Lint as: python3\n# Copyright 2020, The TensorFlow Federated 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\nimport collections\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom tensorflow_federated.python import core as tff\nfrom tensorflow_federated.python.common_libs import test\nfrom tensorflow_federated.python.learning import keras_utils\nfrom tensorflow_federated.python.learning import model_examples\nfrom tensorflow_federated.python.learning import model_utils\nfrom tensorflow_federated.python.learning import personalization_eval as p13n_eval\n\ntf.compat.v1.enable_v2_behavior()\n\n\[email protected]\ndef _evaluate_fn(model, dataset, batch_size=1):\n \"\"\"Evaluates a `tff.learning.Model` on the given dataset.\"\"\"\n # Reset the local variables so that the returned metrics are computed using\n # the given data. Similar to the `reset_states` method of `tf.metrics.Metric`.\n for var in model.local_variables:\n if var.initial_value is not None:\n var.assign(var.initial_value)\n else:\n var.assign(tf.zeros_like(var))\n\n def eval_fn(dummy_state, batch):\n \"\"\"Evaluates the model on a batch.\"\"\"\n model.forward_pass(batch, training=False)\n return dummy_state\n\n # Evaluate on the dataset.\n batched_dataset = dataset.batch(batch_size)\n batched_dataset.reduce(initial_state=0, reduce_func=eval_fn)\n\n # Obtain the metrics.\n results = collections.OrderedDict()\n local_outputs = model.report_local_outputs()\n for name, metric in local_outputs.items():\n if isinstance(metric, list) and (len(metric) == 2):\n # Some metrics returned by `report_local_outputs()` can have two scalars:\n # one represents `sum`, and the other represents `count`. Ideally, we want\n # to return a single scalar for each metric.\n results[name] = metric[0] / metric[1]\n else:\n results[name] = metric[0] if isinstance(metric, list) else metric\n return results\n\n\ndef _build_personalize_fn(optimizer_fn, train_batch_size, test_batch_size):\n \"\"\"Builds a personalization function given an optimizer constructor.\"\"\"\n optimizer = optimizer_fn()\n\n @tf.function\n def personalize_fn(model, train_data, test_data, context=None):\n\n def train_fn(num_examples_sum, batch):\n \"\"\"Runs gradient descent on a batch.\"\"\"\n with tf.GradientTape() as tape:\n output = model.forward_pass(batch)\n\n grads = tape.gradient(output.loss, model.trainable_variables)\n optimizer.apply_gradients(\n zip(\n tf.nest.flatten(grads),\n tf.nest.flatten(model.trainable_variables)))\n return num_examples_sum + output.num_examples\n\n # Train a personalized model.\n batched_train_data = train_data.batch(train_batch_size)\n num_examples_sum = batched_train_data.reduce(\n initial_state=0, reduce_func=train_fn)\n\n # For test coverage, this example uses an optional `int32` as `context`.\n if context is not None:\n num_examples_sum = num_examples_sum + context\n\n results = collections.OrderedDict()\n results['num_examples'] = num_examples_sum\n results['test_outputs'] = _evaluate_fn(model, test_data, test_batch_size)\n return results\n\n return personalize_fn\n\n\ndef _create_p13n_fn_dict(learning_rate):\n \"\"\"Creates a dictionary containing two personalization strategies.\"\"\"\n p13n_fn_dict = collections.OrderedDict()\n\n opt_fn = lambda: tf.keras.optimizers.SGD(learning_rate=learning_rate)\n # The two personalization strategies use different training batch sizes.\n p13n_fn_dict['batch_size_1'] = lambda: _build_personalize_fn(opt_fn, 1, 3)\n p13n_fn_dict['batch_size_2'] = lambda: _build_personalize_fn(opt_fn, 2, 3)\n\n return p13n_fn_dict\n\n\ndef _create_dataset(scale):\n \"\"\"Constructs a dataset with three datapoints.\"\"\"\n x = np.array([[-1.0, -1.0], [1.0, 1.0], [1.0, 1.0]]) * scale\n y = np.array([[1.0], [1.0], [1.0]]) * scale\n ds = collections.OrderedDict([('x', x.astype(np.float32)),\n ('y', y.astype(np.float32))])\n # Note: batching is not needed here as the preprocessing of dataset is done\n # inside the personalization function.\n return tf.data.Dataset.from_tensor_slices(ds)\n\n\ndef _create_client_input(train_scale, test_scale, context=None):\n \"\"\"Constructs client datasets for personalization.\"\"\"\n client_input = collections.OrderedDict()\n client_input['train_data'] = _create_dataset(train_scale)\n client_input['test_data'] = _create_dataset(test_scale)\n if context is not None:\n client_input['context'] = context\n return client_input\n\n\ndef _create_zero_model_weights(model_fn):\n \"\"\"Creates the model weights with all zeros.\"\"\"\n dummy_model = model_utils.enhance(model_fn())\n return tf.nest.map_structure(tf.zeros_like, dummy_model.weights)\n\n\nclass PersonalizationEvalTest(test.TestCase):\n\n def test_failure_with_invalid_model_fn(self):\n p13n_fn_dict = _create_p13n_fn_dict(learning_rate=1.0)\n with self.assertRaises(TypeError):\n # `model_fn` should be a callable.\n bad_model_fn = 6\n p13n_eval.build_personalization_eval(bad_model_fn, p13n_fn_dict,\n _evaluate_fn)\n\n with self.assertRaises(TypeError):\n # `model_fn` should be a callable that returns a `tff.learning.Model`.\n bad_model_fn = lambda: 6\n p13n_eval.build_personalization_eval(bad_model_fn, p13n_fn_dict,\n _evaluate_fn)\n\n def test_failure_with_invalid_p13n_fns(self):\n\n def model_fn():\n return model_examples.LinearRegression(feature_dim=2)\n\n with self.assertRaises(TypeError):\n # `personalize_fn_dict` should be a `OrderedDict`.\n bad_p13n_fn_dict = {'a': 6}\n p13n_eval.build_personalization_eval(model_fn, bad_p13n_fn_dict,\n _evaluate_fn)\n\n with self.assertRaises(TypeError):\n # `personalize_fn_dict` should be a `OrderedDict` that maps a `string` to\n # a `callable`.\n bad_p13n_fn_dict = collections.OrderedDict([('a', 6)])\n p13n_eval.build_personalization_eval(model_fn, bad_p13n_fn_dict,\n _evaluate_fn)\n\n with self.assertRaises(TypeError):\n # `personalize_fn_dict` should be a `OrderedDict` that maps a `string` to\n # a `callable` that when called, gives another `callable`.\n bad_p13n_fn_dict = collections.OrderedDict([('a', lambda: 2)])\n p13n_eval.build_personalization_eval(model_fn, bad_p13n_fn_dict,\n _evaluate_fn)\n\n with self.assertRaises(ValueError):\n # `personalize_fn_dict` should not use `baseline_metrics` as a key.\n bad_p13n_fn_dict = collections.OrderedDict([('baseline_metrics',\n lambda: 2)])\n p13n_eval.build_personalization_eval(model_fn, bad_p13n_fn_dict,\n _evaluate_fn)\n\n def test_failure_with_invalid_baseline_eval_fn(self):\n\n def model_fn():\n return model_examples.LinearRegression(feature_dim=2)\n\n p13n_fn_dict = _create_p13n_fn_dict(learning_rate=1.0)\n\n with self.assertRaises(TypeError):\n # `baseline_evaluate_fn` should be a callable.\n bad_baseline_evaluate_fn = 6\n p13n_eval.build_personalization_eval(model_fn, p13n_fn_dict,\n bad_baseline_evaluate_fn)\n\n def test_success_with_directly_constructed_model(self):\n\n def model_fn():\n return model_examples.LinearRegression(feature_dim=2)\n\n zero_model_weights = _create_zero_model_weights(model_fn)\n p13n_fn_dict = _create_p13n_fn_dict(learning_rate=1.0)\n\n federated_p13n_eval = p13n_eval.build_personalization_eval(\n model_fn, p13n_fn_dict, _evaluate_fn)\n\n # Perform p13n eval on two clients: their train data are equivalent, but the\n # test data have different scales.\n results = federated_p13n_eval(zero_model_weights, [\n _create_client_input(train_scale=1.0, test_scale=1.0),\n _create_client_input(train_scale=1.0, test_scale=2.0)\n ])\n results = results._asdict(recursive=True)\n\n # Check if the baseline metrics are correct.\n baseline_metrics = results['baseline_metrics']\n # Number of test examples is 3 for both clients.\n self.assertAllEqual(baseline_metrics['num_examples'], [3, 3])\n # Number of test batches is 3 for both clients, because the function that\n # evaluates the baseline metrics `_evaluate_fn` uses a default batch size 1.\n self.assertAllEqual(sorted(baseline_metrics['num_batches']), [3, 3])\n # The initial weights are all zeros. The average loss can be computed as:\n # Client 1, 0.5*(1 + 1 + 1)/3 = 0.5; Client 2, 0.5*(4 + 4 + 4)/3 = 2.0.\n # Note: the order is not preserved due to `federated_sample`.\n self.assertAllEqual(sorted(baseline_metrics['loss']), [0.5, 2.0])\n if baseline_metrics['loss'][0] == 0.5:\n client_1_idx, client_2_idx = 0, 1\n else:\n client_1_idx, client_2_idx = 1, 0\n\n # Check if the metrics of `batch_size_1` are correct.\n bs1_metrics = results['batch_size_1']\n # Number of training examples is 3 for both clients.\n self.assertAllEqual(bs1_metrics['num_examples'], [3, 3])\n bs1_test_outputs = bs1_metrics['test_outputs']\n # Number of test examples is also 3 for both clients.\n self.assertAllEqual(bs1_test_outputs['num_examples'], [3, 3])\n # Number of test batches is 1 for both clients since test batch size is 3.\n self.assertAllEqual(bs1_test_outputs['num_batches'], [1, 1])\n # Both clients's weights become [-3, -3, -1] after training, which gives an\n # average loss 24 for Client 1 and 88.5 for Client 2.\n self.assertAlmostEqual(bs1_test_outputs['loss'][client_1_idx], 24.0)\n self.assertAlmostEqual(bs1_test_outputs['loss'][client_2_idx], 88.5)\n\n # Check if the metrics of `batch_size_2` are correct.\n bs2_metrics = results['batch_size_2']\n # Number of training examples is 3 for both clients.\n self.assertAllEqual(bs2_metrics['num_examples'], [3, 3])\n bs2_test_outputs = bs2_metrics['test_outputs']\n # Number of test examples is also 3 for both clients.\n self.assertAllEqual(bs2_test_outputs['num_examples'], [3, 3])\n # Number of test batches is 1 for both clients since test batch size is 3.\n self.assertAllEqual(bs2_test_outputs['num_batches'], [1, 1])\n # Both clients' weights become [0, 0, 1] after training, which gives an\n # average loss 0 for Client 1 and 0.5 for Client 2.\n self.assertAlmostEqual(bs2_test_outputs['loss'][client_1_idx], 0.0)\n self.assertAlmostEqual(bs2_test_outputs['loss'][client_2_idx], 0.5)\n\n def test_success_with_model_constructed_from_keras(self):\n\n def model_fn():\n inputs = tf.keras.Input(shape=(2,)) # feature dim = 2\n outputs = tf.keras.layers.Dense(1)(inputs)\n keras_model = tf.keras.Model(inputs=inputs, outputs=outputs)\n input_spec = collections.OrderedDict([\n ('x', tf.TensorSpec([None, 2], dtype=tf.float32)),\n ('y', tf.TensorSpec([None, 1], dtype=tf.float32))\n ])\n return keras_utils.from_keras_model(\n keras_model,\n input_spec=input_spec,\n loss=tf.keras.losses.MeanSquaredError())\n\n zero_model_weights = _create_zero_model_weights(model_fn)\n p13n_fn_dict = _create_p13n_fn_dict(learning_rate=0.5)\n\n federated_p13n_eval = p13n_eval.build_personalization_eval(\n model_fn, p13n_fn_dict, _evaluate_fn)\n\n # Perform p13n eval on two clients: their train data are equivalent, but the\n # test data have different scales.\n results = federated_p13n_eval(zero_model_weights, [\n _create_client_input(train_scale=1.0, test_scale=1.0),\n _create_client_input(train_scale=1.0, test_scale=2.0)\n ])\n results = results._asdict(recursive=True)\n\n # Check if the baseline metrics are correct.\n baseline_metrics = results['baseline_metrics']\n # The initial weights are all zeros. The MeanSquredError(MSE) is:\n # Client 1, (1 + 1 + 1)/3 = 1.0; Client 2, (4 + 4 + 4)/3 = 4.0.\n # Note: the order is not preserved due to `federated_sample`.\n self.assertAllEqual(sorted(baseline_metrics['loss']), [1.0, 4.0])\n\n # Check if the metrics of `batch_size_1` are correct.\n bs1_metrics = results['batch_size_1']\n # Number of training examples is 3 for both clients.\n self.assertAllEqual(bs1_metrics['num_examples'], [3, 3])\n bs1_test_outputs = bs1_metrics['test_outputs']\n # Both clients' weights become [-3, -3, -1] after training, which gives MSE\n # 48 for Client 1 and 177 for Client 2.\n self.assertAlmostEqual(sorted(bs1_test_outputs['loss']), [48.0, 177.0])\n\n # Check if the metrics of `batch_size_2` are correct.\n bs2_metrics = results['batch_size_2']\n # Number of training examples is 3 for both clients.\n self.assertAllEqual(bs2_metrics['num_examples'], [3, 3])\n bs2_test_outputs = bs2_metrics['test_outputs']\n # Both clients' weights become [0, 0, 1] after training, which gives MSE 0\n # for Client 1 and 1.0 for Client 2.\n self.assertAlmostEqual(sorted(bs2_test_outputs['loss']), [0.0, 1.0])\n\n def test_failure_with_batched_datasets(self):\n\n def model_fn():\n return model_examples.LinearRegression(feature_dim=2)\n\n zero_model_weights = _create_zero_model_weights(model_fn)\n p13n_fn_dict = _create_p13n_fn_dict(learning_rate=1.0)\n\n federated_p13n_eval = p13n_eval.build_personalization_eval(\n model_fn, p13n_fn_dict, _evaluate_fn)\n\n with self.assertRaises(TypeError):\n # client_input should not have batched datasets.\n bad_client_input = collections.OrderedDict([\n ('train_data', _create_dataset(scale=1.0).batch(1)),\n ('test_data', _create_dataset(scale=1.0).batch(1))\n ])\n federated_p13n_eval(zero_model_weights, [bad_client_input])\n\n def test_failure_with_invalid_context_type(self):\n\n def model_fn():\n return model_examples.LinearRegression(feature_dim=2)\n\n zero_model_weights = _create_zero_model_weights(model_fn)\n p13n_fn_dict = _create_p13n_fn_dict(learning_rate=1.0)\n\n with self.assertRaises(TypeError):\n # `tf.int32` is not a `tff.Type`.\n bad_context_tff_type = tf.int32\n federated_p13n_eval = p13n_eval.build_personalization_eval(\n model_fn,\n p13n_fn_dict,\n _evaluate_fn,\n context_tff_type=bad_context_tff_type)\n\n with self.assertRaises(TypeError):\n # `context_tff_type` is provided but `context` is not provided.\n context_tff_type = tff.to_type(tf.int32)\n federated_p13n_eval = p13n_eval.build_personalization_eval(\n model_fn,\n p13n_fn_dict,\n _evaluate_fn,\n context_tff_type=context_tff_type)\n federated_p13n_eval(zero_model_weights, [\n _create_client_input(train_scale=1.0, test_scale=1.0, context=None),\n _create_client_input(train_scale=1.0, test_scale=2.0, context=None)\n ])\n\n def test_success_with_valid_context(self):\n\n def model_fn():\n return model_examples.LinearRegression(feature_dim=2)\n\n zero_model_weights = _create_zero_model_weights(model_fn)\n p13n_fn_dict = _create_p13n_fn_dict(learning_rate=1.0)\n\n # Build the p13n eval with an extra `context` argument.\n context_tff_type = tff.to_type(tf.int32)\n federated_p13n_eval = p13n_eval.build_personalization_eval(\n model_fn, p13n_fn_dict, _evaluate_fn, context_tff_type=context_tff_type)\n\n # Perform p13n eval on two clients with different `context` values.\n results = federated_p13n_eval(zero_model_weights, [\n _create_client_input(train_scale=1.0, test_scale=1.0, context=2),\n _create_client_input(train_scale=1.0, test_scale=2.0, context=5)\n ])\n results = results._asdict(recursive=True)\n\n bs1_metrics = results['batch_size_1']\n bs2_metrics = results['batch_size_2']\n\n # Number of training examples is `3 + context` for both clients.\n # Note: the order is not preserved due to `federated_sample`, but the order\n # should be consistent across different personalization strategies.\n self.assertAllEqual(sorted(bs1_metrics['num_examples']), [5, 8])\n self.assertAllEqual(bs1_metrics['num_examples'],\n bs2_metrics['num_examples'])\n\n def test_failure_with_invalid_sample_size(self):\n\n def model_fn():\n return model_examples.LinearRegression(feature_dim=2)\n\n p13n_fn_dict = _create_p13n_fn_dict(learning_rate=1.0)\n\n with self.assertRaises(TypeError):\n # `max_num_samples` should be an `int`.\n bad_num_samples = 1.0\n p13n_eval.build_personalization_eval(\n model_fn, p13n_fn_dict, _evaluate_fn, max_num_samples=bad_num_samples)\n\n with self.assertRaises(ValueError):\n # `max_num_samples` should be a positive `int`.\n bad_num_samples = 0\n p13n_eval.build_personalization_eval(\n model_fn, p13n_fn_dict, _evaluate_fn, max_num_samples=bad_num_samples)\n\n def test_success_with_small_sample_size(self):\n\n def model_fn():\n return model_examples.LinearRegression(feature_dim=2)\n\n zero_model_weights = _create_zero_model_weights(model_fn)\n p13n_fn_dict = _create_p13n_fn_dict(learning_rate=1.0)\n\n federated_p13n_eval = p13n_eval.build_personalization_eval(\n model_fn, p13n_fn_dict, _evaluate_fn, max_num_samples=1)\n\n # Perform p13n eval on two clients.\n results = federated_p13n_eval(zero_model_weights, [\n _create_client_input(train_scale=1.0, test_scale=1.0),\n _create_client_input(train_scale=1.0, test_scale=2.0)\n ])\n results = results._asdict(recursive=True)\n\n # The results should only contain metrics from one client.\n self.assertAllEqual(len(results['baseline_metrics']['loss']), 1)\n self.assertAllEqual(len(results['batch_size_1']['test_outputs']['loss']), 1)\n self.assertAllEqual(len(results['batch_size_2']['test_outputs']['loss']), 1)\n\n\nif __name__ == '__main__':\n test.main()\n",
"# Lint as: python3\n# Copyright 2019, The TensorFlow Federated 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\"\"\"Trains and evaluates EMNIST classification model using TFF.\"\"\"\n\nimport collections\nimport functools\nimport os\nimport pprint\nimport random\nimport sys\nimport time\n\nfrom absl import app\nfrom absl import flags\nfrom absl import logging\nimport pandas as pd\nimport tensorflow as tf\nimport tensorflow_federated as tff\nimport tree\n\nfrom tensorboard.plugins.hparams import api as hp\nfrom tensorflow_federated.python.research.flars import flars_fedavg\nfrom tensorflow_federated.python.research.flars import flars_optimizer\nfrom tensorflow_federated.python.research.optimization.emnist import models\nfrom tensorflow_federated.python.research.utils import checkpoint_manager\nfrom tensorflow_federated.python.research.utils import utils_impl\n\nwith utils_impl.record_new_flags() as hparam_flags:\n # Metadata\n flags.DEFINE_string(\n 'exp_name', 'emnist', 'Unique name for the experiment, suitable for use '\n 'in filenames.')\n\n # Training hyperparameters\n flags.DEFINE_boolean(\n 'digit_only_emnist', True,\n 'Whether to train on the digits only (10 classes) data '\n 'or the full data (62 classes).')\n flags.DEFINE_integer('total_rounds', 500, 'Number of total training rounds.')\n flags.DEFINE_integer('rounds_per_eval', 1, 'How often to evaluate')\n flags.DEFINE_integer(\n 'rounds_per_checkpoint', 25,\n 'How often to emit a state checkpoint. Higher numbers '\n 'mean more lost work in case of failure, lower numbers '\n 'mean more overhead per round.')\n flags.DEFINE_integer('train_clients_per_round', 2,\n 'How many clients to sample per round.')\n flags.DEFINE_integer('client_epochs_per_round', 1,\n 'Number of epochs in the client to take per round.')\n flags.DEFINE_integer('batch_size', 20, 'Batch size used on the client.')\n\n # Client optimizer configuration (it defines one or more flags per optimizer).\n utils_impl.define_optimizer_flags('client')\n\n # Server optimizer configuration (it defines one or more flags per optimizer).\n flags.DEFINE_enum('server_optimizer', 'flars', ['sgd', 'flars'],\n 'Server optimizer')\n flags.DEFINE_float('server_learning_rate', 1., 'Server learning rate.')\n flags.DEFINE_float(\n 'server_momentum', 0.9,\n 'Server momentum. This is also the `beta1` parameter for '\n 'the Yogi optimizer.')\n\n # Parameter for FLARS.\n flags.DEFINE_float('max_ratio', 0.1, 'max_ratio for optimizer FLARS.')\n # Parameter for Yogi.\n flags.DEFINE_float('initial_accumulator_value', 1e-6,\n 'initial_accumulator_value for optimizer Yogi.')\n\n# End of hyperparameter flags.\n\n# Root output directories.\nflags.DEFINE_string(\n 'root_output_dir', '/tmp/emnist_fedavg/',\n 'Root directory for writing experiment output. This will '\n 'be the destination for metrics CSV files, Tensorboard log '\n 'directory, and checkpoint files.')\nflags.DEFINE_boolean(\n 'disable_check_exists', True, 'Disable checking the '\n 'existence of root_output_dir. If False, code will exit '\n 'without running the experiment if root_output_dir '\n 'exists.')\n\nFLAGS = flags.FLAGS\n\n\ndef _federated_averaging_training_loop(model_fn,\n client_optimizer_fn,\n server_optimizer_fn,\n client_datasets_fn,\n evaluate_fn,\n total_rounds=500,\n rounds_per_eval=1,\n metrics_hook=None):\n \"\"\"A simple example of training loop for the Federated Averaging algorithm.\n\n Args:\n model_fn: A no-arg function that returns a `tff.learning.Model`.\n client_optimizer_fn: A no-arg function that returns a\n `tf.keras.optimizers.Optimizer`.\n server_optimizer_fn: A no-arg function that returns a\n `tf.keras.optimizers.Optimizer`.\n client_datasets_fn: A function that takes the round number, and returns a\n list of `tf.data.Datset`, one per client.\n evaluate_fn: A function that takes state, performs evaluation, and returns\n evaluations metrics.\n total_rounds: Number of rounds to train.\n rounds_per_eval: How often to call the `metrics_hook` function.\n metrics_hook: A function taking arguments (training metrics,\n evaluation metrics, and round number). Optional.\n\n Returns:\n Final `ServerState`.\n \"\"\"\n logging.info('Starting federated training loop')\n\n checkpoint_dir = os.path.join(FLAGS.root_output_dir, FLAGS.exp_name)\n checkpoint_manager_obj = checkpoint_manager.FileCheckpointManager(\n checkpoint_dir)\n\n if FLAGS.server_optimizer != 'flars':\n logging.error('Unsupported server_optimzier: %s', FLAGS.server_optimizer)\n else:\n iterative_process = flars_fedavg.build_federated_averaging_process(\n model_fn,\n client_optimizer_fn=client_optimizer_fn,\n server_optimizer_fn=server_optimizer_fn)\n ServerState = flars_fedavg.ServerState # pylint: disable=invalid-name\n\n # construct an initial state here to act as a checkpoint template\n inital_state = iterative_process.initialize()\n inital_state = ServerState.from_tff_result(inital_state)\n\n logging.info('Looking for checkpoints in \\'%s\\'', checkpoint_dir)\n state, round_num = checkpoint_manager_obj.load_latest_checkpoint(inital_state)\n\n if state is None:\n logging.info('No previous checkpoints, initializing experiment')\n state = inital_state\n round_num = 0\n if metrics_hook is not None:\n eval_metrics = evaluate_fn(state)\n metrics_hook({}, eval_metrics, round_num)\n checkpoint_manager_obj.save_checkpoint(state, 0)\n else:\n logging.info('Restarted from checkpoint round %d', round_num)\n\n while round_num < total_rounds:\n round_num += 1\n train_metrics = {}\n\n # Reset the executor to clear the cache, and clear the default graph to\n # garbage collect tf.Functions that will no longer be used.\n tff.framework.set_default_executor(\n tff.framework.local_executor_factory(max_fanout=25))\n tf.compat.v1.reset_default_graph()\n\n round_start_time = time.time()\n data_prep_start_time = time.time()\n train_data = client_datasets_fn(round_num)\n train_metrics['prepare_datasets_secs'] = time.time() - data_prep_start_time\n\n training_start_time = time.time()\n state, tff_train_metrics = iterative_process.next(state, train_data)\n state = ServerState.from_tff_result(state)\n tff_train_metrics = tff_train_metrics._asdict(recursive=True)\n train_metrics.update(tff_train_metrics)\n train_metrics['training_secs'] = time.time() - training_start_time\n\n logging.info('Round {:2d} elapsed time: {:.2f}s .'.format(\n round_num, (time.time() - round_start_time)))\n train_metrics['total_round_secs'] = time.time() - round_start_time\n\n if (round_num % FLAGS.rounds_per_checkpoint == 0 or\n round_num == total_rounds):\n save_checkpoint_start_time = time.time()\n checkpoint_manager_obj.save_checkpoint(state, round_num)\n train_metrics['save_checkpoint_secs'] = (\n time.time() - save_checkpoint_start_time)\n\n if round_num % rounds_per_eval == 0 or round_num == total_rounds:\n if metrics_hook is not None:\n eval_metrics = evaluate_fn(state)\n metrics_hook(train_metrics, eval_metrics, round_num)\n\n\ndef _check_not_exists(f, disable_check_exists=False):\n \"\"\"Checks if file `f` exists.\"\"\"\n if disable_check_exists:\n return\n if tf.io.gfile.exists(f):\n print('{} already exists.\\n'\n 'Please ensure only a single worker is executing each experiment '\n 'in the grid.\\n'\n 'When re-running a grid, please use a fresh output directory.'.format(\n f))\n sys.exit(1)\n\n\nclass _MetricsHook(object):\n \"\"\"A callback for evaluation.\n\n This class holds all the logic for writing output for later analysis (to .csv\n files and\n tensorboard). Hyperparameters are also recorded.\n \"\"\"\n\n def __init__(self, experiment_name, output_dir, hparam_dict):\n \"\"\"Returns an initalized `MetricsHook`.\n\n Args:\n experiment_name: A unique filesystem-friendly name for the experiment.\n output_dir: A root output directory used for all experiment runs in a\n grid. The `MetricsHook` will combine this with `experiment_name` to form\n suitable output directories for this run.\n hparam_dict: A dictionary of hyperparameters to be recorded to .csv and\n exported to TensorBoard.\n \"\"\"\n\n summary_logdir = os.path.join(output_dir,\n 'logdir/{}'.format(experiment_name))\n _check_not_exists(summary_logdir, FLAGS.disable_check_exists)\n tf.io.gfile.makedirs(summary_logdir)\n\n self._summary_writer = tf.compat.v2.summary.create_file_writer(\n summary_logdir, name=experiment_name)\n with self._summary_writer.as_default():\n hp.hparams(hparam_dict)\n\n # Using .bz2 rather than .zip due to\n # https://github.com/pandas-dev/pandas/issues/26023\n self._results_file = os.path.join(output_dir, experiment_name,\n 'results.csv.bz2')\n\n # Also write the hparam_dict to a CSV:\n hparam_dict['results_file'] = self._results_file\n hparams_file = os.path.join(output_dir, experiment_name, 'hparams.csv')\n utils_impl.atomic_write_to_csv(pd.Series(hparam_dict), hparams_file)\n\n logging.info('Writing ...')\n logging.info(' result csv to: %s', self._results_file)\n logging.info(' summaries to: %s', summary_logdir)\n\n _check_not_exists(self._results_file, FLAGS.disable_check_exists)\n\n def __call__(self, train_metrics, eval_metrics, round_num):\n \"\"\"A function suitable for passing as an eval hook to the training_loop.\n\n Args:\n train_metrics: A `dict` of training metrics computed in TFF.\n eval_metrics: A `dict` of evalutation metrics computed in TFF.\n round_num: The current round number.\n \"\"\"\n metrics = {\n 'train': train_metrics,\n 'eval': eval_metrics,\n 'round': round_num,\n }\n flat_metrics = tree.flatten_with_path(metrics)\n flat_metrics = [\n ('/'.join(map(str, path)), item) for path, item in flat_metrics\n ]\n flat_metrics = collections.OrderedDict(flat_metrics)\n\n logging.info('Evaluation at round {:d}:\\n{!s}'.format(\n round_num, pprint.pformat(flat_metrics)))\n\n # Also write metrics to a tf.summary logdir\n with self._summary_writer.as_default():\n for name, value in flat_metrics.items():\n tf.compat.v2.summary.scalar(name, value, step=round_num)\n\n if tf.io.gfile.exists(self._results_file):\n metrics = pd.read_csv(\n self._results_file, header=0, index_col=0, engine='c')\n # Remove everything after `round_num`, in case the experiment was\n # restarted at an earlier checkpoint we want to avoid duplicate metrics.\n metrics = metrics[:round_num]\n metrics = metrics.append(flat_metrics, ignore_index=True)\n else:\n metrics = pd.DataFrame(flat_metrics, index=[0])\n utils_impl.atomic_write_to_csv(metrics, self._results_file)\n\n\ndef model_builder():\n \"\"\"Create compiled keras model.\"\"\"\n model = models.create_original_fedavg_cnn_model(\n only_digits=FLAGS.digit_only_emnist)\n return model\n\n\ndef loss_builder():\n return tf.keras.losses.SparseCategoricalCrossentropy()\n\n\ndef metrics_builder():\n return [tf.keras.metrics.SparseCategoricalAccuracy()]\n\n\ndef compiled_eval_keras_model():\n model = model_builder()\n model.compile(\n loss=loss_builder(),\n optimizer=tf.keras.optimizers.SGD(), # Dummy optimizer for evaluation\n metrics=metrics_builder())\n return model\n\n\ndef reshape_emnist_element(element):\n return (tf.expand_dims(element['pixels'], axis=-1), element['label'])\n\n\ndef _run_experiment():\n \"\"\"Data preprocessing and experiment execution.\"\"\"\n emnist_train, emnist_test = tff.simulation.datasets.emnist.load_data(\n only_digits=FLAGS.digit_only_emnist)\n\n def preprocess_train_dataset(dataset):\n \"\"\"Preprocess training dataset.\"\"\"\n return (dataset.map(reshape_emnist_element).shuffle(\n buffer_size=10000).repeat(FLAGS.client_epochs_per_round).batch(\n FLAGS.batch_size))\n\n def preprocess_test_dataset(dataset):\n \"\"\"Preprocess testing dataset.\"\"\"\n return dataset.map(reshape_emnist_element).batch(100, drop_remainder=False)\n\n emnist_train = emnist_train.preprocess(preprocess_train_dataset)\n emnist_test = preprocess_test_dataset(\n emnist_test.create_tf_dataset_from_all_clients())\n\n example_dataset = emnist_train.create_tf_dataset_for_client(\n emnist_train.client_ids[0])\n input_spec = example_dataset.element_spec\n\n def tff_model_fn():\n keras_model = model_builder()\n return tff.learning.from_keras_model(\n keras_model,\n input_spec=input_spec,\n loss=loss_builder(),\n metrics=metrics_builder())\n\n def client_datasets_fn(round_num):\n \"\"\"Returns a list of client datasets.\"\"\"\n del round_num # Unused.\n sampled_clients = random.sample(\n population=emnist_train.client_ids, k=FLAGS.train_clients_per_round)\n return [\n emnist_train.create_tf_dataset_for_client(client)\n for client in sampled_clients\n ]\n\n def evaluate_fn(state):\n compiled_keras_model = compiled_eval_keras_model()\n tff.learning.assign_weights_to_keras_model(compiled_keras_model,\n state.model)\n eval_metrics = compiled_keras_model.evaluate(emnist_test, verbose=0)\n return {\n 'loss': eval_metrics[0],\n 'sparse_categorical_accuracy': eval_metrics[1],\n }\n\n tf.io.gfile.makedirs(FLAGS.root_output_dir)\n hparam_dict = collections.OrderedDict([\n (name, FLAGS[name].value) for name in hparam_flags\n ])\n hparam_dict = utils_impl.remove_unused_flags('client', hparam_dict)\n\n metrics_hook = _MetricsHook(FLAGS.exp_name, FLAGS.root_output_dir,\n hparam_dict)\n\n client_optimizer_fn = lambda: utils_impl.create_optimizer_from_flags('client')\n\n if FLAGS.server_optimizer == 'sgd':\n server_optimizer_fn = functools.partial(\n tf.keras.optimizers.SGD,\n learning_rate=FLAGS.server_learning_rate,\n momentum=FLAGS.server_momentum)\n elif FLAGS.server_optimizer == 'flars':\n server_optimizer_fn = functools.partial(\n flars_optimizer.FLARSOptimizer,\n learning_rate=FLAGS.server_learning_rate,\n momentum=FLAGS.server_momentum,\n max_ratio=FLAGS.max_ratio)\n else:\n raise ValueError('Optimizer %s is not supported.' % FLAGS.server_optimizer)\n\n _federated_averaging_training_loop(\n model_fn=tff_model_fn,\n client_optimizer_fn=client_optimizer_fn,\n server_optimizer_fn=server_optimizer_fn,\n client_datasets_fn=client_datasets_fn,\n evaluate_fn=evaluate_fn,\n total_rounds=FLAGS.total_rounds,\n rounds_per_eval=FLAGS.rounds_per_eval,\n metrics_hook=metrics_hook)\n\n\ndef main(argv):\n if len(argv) > 1:\n raise app.UsageError('Expected no command-line arguments, '\n 'got: {}'.format(argv))\n tf.compat.v1.enable_v2_behavior()\n try:\n tf.io.gfile.makedirs(os.path.join(FLAGS.root_output_dir, FLAGS.exp_name))\n except tf.errors.OpError:\n pass\n _run_experiment()\n\n\nif __name__ == '__main__':\n app.run(main)\n",
"# Lint as: python3\n# Copyright 2019, The TensorFlow Federated 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\nimport tensorflow as tf\n\nfrom tensorflow_federated.python.research.optimization.emnist_ae import models\n\n\nclass ModelCollectionTest(tf.test.TestCase):\n\n def test_ae_model(self):\n image = tf.random.normal([4, 28*28])\n model = models.create_autoencoder_model()\n reconstructed_image = model(image)\n num_model_params = 2837314\n self.assertIsNotNone(reconstructed_image)\n self.assertEqual(reconstructed_image.shape, [4, 28*28])\n self.assertEqual(model.count_params(), num_model_params)\n\n\nif __name__ == '__main__':\n tf.test.main()\n",
"# Lint as: python3\n# Copyright 2019, The TensorFlow Federated 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\nimport collections\n\nimport tensorflow as tf\n\nfrom tensorflow_federated.python.research.optimization.cifar100 import dataset\n\nTEST_BATCH_SIZE = dataset.TEST_BATCH_SIZE\n\n\nclass DatasetTest(tf.test.TestCase):\n\n def test_centralized_cifar_structure(self):\n crop_shape = (24, 24, 3)\n cifar_train, cifar_test = dataset.get_centralized_cifar100(\n train_batch_size=20, crop_shape=crop_shape)\n train_batch = next(iter(cifar_train))\n train_batch_shape = tuple(train_batch[0].shape)\n self.assertEqual(train_batch_shape, (20, 24, 24, 3))\n test_batch = next(iter(cifar_test))\n test_batch_shape = tuple(test_batch[0].shape)\n self.assertEqual(test_batch_shape, (TEST_BATCH_SIZE, 24, 24, 3))\n\n def test_federated_cifar_structure(self):\n crop_shape = (32, 32, 3)\n cifar_train, _ = dataset.get_federated_cifar100(\n client_epochs_per_round=1, train_batch_size=10, crop_shape=crop_shape)\n client_id = cifar_train.client_ids[0]\n client_dataset = cifar_train.create_tf_dataset_for_client(client_id)\n train_batch = next(iter(client_dataset))\n train_batch_shape = tuple(train_batch[0].shape)\n self.assertEqual(train_batch_shape, (10, 32, 32, 3))\n\n def test_no_op_crop_process_cifar_example(self):\n crop_shape = (1, 1, 1, 3)\n x = tf.constant([[[[1.0, -1.0, 0.0]]]]) # Has shape (1, 1, 1, 3), mean 0\n x = x / tf.math.reduce_std(x) # x now has variance 1\n dummy_example = collections.OrderedDict(image=x, label=0)\n processed_dummy_example = dataset.preprocess_cifar_example(\n dummy_example, crop_shape=crop_shape, distort=False)\n self.assertEqual(processed_dummy_example[0].shape, crop_shape)\n self.assertAllClose(x, processed_dummy_example[0], rtol=1e-03)\n self.assertEqual(processed_dummy_example[1], 0)\n\n def test_raises_length_2_crop(self):\n with self.assertRaises(ValueError):\n dataset.get_federated_cifar100(\n client_epochs_per_round=1, train_batch_size=10, crop_shape=(32, 32))\n with self.assertRaises(ValueError):\n dataset.get_centralized_cifar100(train_batch_size=10, crop_shape=(32, 32))\n\nif __name__ == '__main__':\n tf.compat.v1.enable_v2_behavior()\n tf.test.main()\n"
] | [
[
"tensorflow.concat",
"tensorflow.reshape",
"tensorflow.strings.split",
"tensorflow.map_fn",
"tensorflow.lookup.KeyValueTensorInitializer",
"tensorflow.size"
],
[
"tensorflow.compat.v1.enable_v2_behavior",
"tensorflow.constant"
],
[
"tensorflow.data.Dataset.from_tensor_slices",
"tensorflow.compat.v1.enable_v2_behavior",
"tensorflow.constant",
"tensorflow.test.main"
],
[
"tensorflow.zeros_like",
"tensorflow.nest.flatten",
"tensorflow.nest.map_structure",
"tensorflow.keras.optimizers.SGD"
],
[
"tensorflow.compat.v1.enable_v2_behavior",
"tensorflow.make_tensor_proto",
"tensorflow.math.add"
],
[
"tensorflow.compat.v1.enable_v2_behavior",
"tensorflow.math.add",
"tensorflow.constant",
"tensorflow.data.Dataset.from_tensor_slices",
"numpy.int32",
"tensorflow.add",
"numpy.array"
],
[
"tensorflow.compat.v1.enable_v2_behavior",
"tensorflow.keras.Input",
"tensorflow.keras.layers.Dense",
"tensorflow.data.Dataset.from_tensor_slices",
"tensorflow.keras.losses.MeanSquaredError",
"tensorflow.keras.Model",
"tensorflow.zeros_like",
"tensorflow.GradientTape",
"tensorflow.nest.flatten",
"numpy.array",
"tensorflow.TensorSpec",
"tensorflow.nest.map_structure",
"tensorflow.keras.optimizers.SGD"
],
[
"tensorflow.compat.v1.enable_v2_behavior",
"pandas.read_csv",
"pandas.Series",
"tensorflow.io.gfile.exists",
"tensorflow.keras.losses.SparseCategoricalCrossentropy",
"tensorflow.compat.v2.summary.create_file_writer",
"tensorflow.io.gfile.makedirs",
"tensorflow.expand_dims",
"pandas.DataFrame",
"tensorflow.compat.v2.summary.scalar",
"tensorflow.keras.metrics.SparseCategoricalAccuracy",
"tensorflow.compat.v1.reset_default_graph",
"tensorflow.keras.optimizers.SGD"
],
[
"tensorflow.random.normal",
"tensorflow.test.main"
],
[
"tensorflow.math.reduce_std",
"tensorflow.compat.v1.enable_v2_behavior",
"tensorflow.constant",
"tensorflow.test.main"
]
] | [
{
"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.4",
"2.3",
"2.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": [
"1.10",
"2.7",
"2.2",
"2.3",
"2.4",
"2.5",
"2.6"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"2.2",
"2.3",
"2.4",
"2.5",
"2.6"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"2.2",
"2.3",
"2.4",
"2.5",
"2.6"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
aliavni/statsmodels | [
"ef5d57a8d45de76a895e9401705280d558d688ad",
"ef5d57a8d45de76a895e9401705280d558d688ad",
"ef5d57a8d45de76a895e9401705280d558d688ad",
"ef5d57a8d45de76a895e9401705280d558d688ad",
"ef5d57a8d45de76a895e9401705280d558d688ad",
"ef5d57a8d45de76a895e9401705280d558d688ad",
"ef5d57a8d45de76a895e9401705280d558d688ad",
"ef5d57a8d45de76a895e9401705280d558d688ad",
"ef5d57a8d45de76a895e9401705280d558d688ad",
"ef5d57a8d45de76a895e9401705280d558d688ad"
] | [
"statsmodels/multivariate/cancorr.py",
"statsmodels/graphics/tests/test_factorplots.py",
"statsmodels/tsa/statespace/tests/test_varmax.py",
"statsmodels/distributions/empirical_distribution.py",
"tools/validate_docstrings.py",
"statsmodels/sandbox/nonparametric/densityorthopoly.py",
"statsmodels/tsa/statespace/tests/test_dynamic_factor.py",
"statsmodels/genmod/tests/test_gee_glm.py",
"statsmodels/gam/tests/test_penalized.py",
"statsmodels/regression/tests/test_theil.py"
] | [
"# -*- coding: utf-8 -*-\n\n\"\"\"Canonical correlation analysis\n\nauthor: Yichuan Liu\n\"\"\"\nimport numpy as np\nfrom numpy.linalg import svd\nimport scipy\nimport pandas as pd\n\nfrom statsmodels.base.model import Model\nfrom statsmodels.iolib import summary2\nfrom .multivariate_ols import multivariate_stats\n\n\nclass CanCorr(Model):\n \"\"\"\n Canonical correlation analysis using singular value decomposition\n\n For matrices exog=x and endog=y, find projections x_cancoef and y_cancoef\n such that:\n\n x1 = x * x_cancoef, x1' * x1 is identity matrix\n y1 = y * y_cancoef, y1' * y1 is identity matrix\n\n and the correlation between x1 and y1 is maximized.\n\n Attributes\n ----------\n endog : ndarray\n See Parameters.\n exog : ndarray\n See Parameters.\n cancorr : ndarray\n The canonical correlation values\n y_cancoeff : ndarray\n The canonical coefficients for endog\n x_cancoeff : ndarray\n The canonical coefficients for exog\n\n References\n ----------\n .. [*] http://numerical.recipes/whp/notes/CanonCorrBySVD.pdf\n .. [*] http://www.csun.edu/~ata20315/psy524/docs/Psy524%20Lecture%208%20CC.pdf\n .. [*] http://www.mathematica-journal.com/2014/06/canonical-correlation-analysis/\n \"\"\" # noqa:E501\n def __init__(self, endog, exog, tolerance=1e-8, missing='none', hasconst=None, **kwargs):\n super(CanCorr, self).__init__(endog, exog, missing=missing,\n hasconst=hasconst, **kwargs)\n self._fit(tolerance)\n\n def _fit(self, tolerance=1e-8):\n \"\"\"Fit the model\n\n A ValueError is raised if there are singular values smaller than the\n tolerance. The treatment of singular arrays might change in future.\n\n Parameters\n ----------\n tolerance : float\n eigenvalue tolerance, values smaller than which is considered 0\n \"\"\"\n nobs, k_yvar = self.endog.shape\n nobs, k_xvar = self.exog.shape\n k = np.min([k_yvar, k_xvar])\n\n x = np.array(self.exog)\n x = x - x.mean(0)\n y = np.array(self.endog)\n y = y - y.mean(0)\n\n ux, sx, vx = svd(x, 0)\n # vx_ds = vx.T divided by sx\n vx_ds = vx.T\n mask = sx > tolerance\n if mask.sum() < len(mask):\n raise ValueError('exog is collinear.')\n vx_ds[:, mask] /= sx[mask]\n uy, sy, vy = svd(y, 0)\n # vy_ds = vy.T divided by sy\n vy_ds = vy.T\n mask = sy > tolerance\n if mask.sum() < len(mask):\n raise ValueError('endog is collinear.')\n vy_ds[:, mask] /= sy[mask]\n u, s, v = svd(ux.T.dot(uy), 0)\n\n # Correct any roundoff\n self.cancorr = np.array([max(0, min(s[i], 1)) for i in range(len(s))])\n\n self.x_cancoef = vx_ds.dot(u[:, :k])\n self.y_cancoef = vy_ds.dot(v.T[:, :k])\n\n def corr_test(self):\n \"\"\"Approximate F test\n Perform multivariate statistical tests of the hypothesis that\n there is no canonical correlation between endog and exog.\n For each canonical correlation, testing its significance based on\n Wilks' lambda.\n\n Returns\n -------\n CanCorrTestResults instance\n \"\"\"\n nobs, k_yvar = self.endog.shape\n nobs, k_xvar = self.exog.shape\n eigenvals = np.power(self.cancorr, 2)\n stats = pd.DataFrame(columns=['Canonical Correlation', \"Wilks' lambda\",\n 'Num DF','Den DF', 'F Value','Pr > F'],\n index=list(range(len(eigenvals) - 1, -1, -1)))\n prod = 1\n for i in range(len(eigenvals) - 1, -1, -1):\n prod *= 1 - eigenvals[i]\n p = k_yvar - i\n q = k_xvar - i\n r = (nobs - k_yvar - 1) - (p - q + 1) / 2\n u = (p * q - 2) / 4\n df1 = p * q\n if p ** 2 + q ** 2 - 5 > 0:\n t = np.sqrt(((p * q) ** 2 - 4) / (p ** 2 + q ** 2 - 5))\n else:\n t = 1\n df2 = r * t - 2 * u\n lmd = np.power(prod, 1 / t)\n F = (1 - lmd) / lmd * df2 / df1\n stats.loc[i, 'Canonical Correlation'] = self.cancorr[i]\n stats.loc[i, \"Wilks' lambda\"] = prod\n stats.loc[i, 'Num DF'] = df1\n stats.loc[i, 'Den DF'] = df2\n stats.loc[i, 'F Value'] = F\n pval = scipy.stats.f.sf(F, df1, df2)\n stats.loc[i, 'Pr > F'] = pval\n '''\n # Wilk's Chi square test of each canonical correlation\n df = (p - i + 1) * (q - i + 1)\n chi2 = a * np.log(prod)\n pval = stats.chi2.sf(chi2, df)\n stats.loc[i, 'Canonical correlation'] = self.cancorr[i]\n stats.loc[i, 'Chi-square'] = chi2\n stats.loc[i, 'DF'] = df\n stats.loc[i, 'Pr > ChiSq'] = pval\n '''\n ind = stats.index.values[::-1]\n stats = stats.loc[ind, :]\n\n # Multivariate tests (remember x has mean removed)\n stats_mv = multivariate_stats(eigenvals,\n k_yvar, k_xvar, nobs - k_xvar - 1)\n return CanCorrTestResults(stats, stats_mv)\n\n\nclass CanCorrTestResults:\n \"\"\"\n Canonical correlation results class\n\n Attributes\n ----------\n stats : DataFrame\n Contain statistical tests results for each canonical correlation\n stats_mv : DataFrame\n Contain the multivariate statistical tests results\n \"\"\"\n def __init__(self, stats, stats_mv):\n self.stats = stats\n self.stats_mv = stats_mv\n\n def __str__(self):\n return self.summary().__str__()\n\n def summary(self):\n summ = summary2.Summary()\n summ.add_title('Cancorr results')\n summ.add_df(self.stats)\n summ.add_dict({'': ''})\n summ.add_dict({'Multivariate Statistics and F Approximations': ''})\n summ.add_df(self.stats_mv)\n return summ\n",
"import numpy as np\nfrom numpy.testing import assert_equal, assert_raises\nfrom pandas import Series\nimport pytest\n\nfrom statsmodels.graphics.factorplots import _recode, interaction_plot\n\ntry:\n import matplotlib.pyplot as plt\nexcept ImportError:\n pass\n\n\nclass TestInteractionPlot:\n\n @classmethod\n def setup_class(cls):\n np.random.seed(12345)\n cls.weight = np.random.randint(1,4,size=60)\n cls.duration = np.random.randint(1,3,size=60)\n cls.days = np.log(np.random.randint(1,30, size=60))\n\n @pytest.mark.matplotlib\n def test_plot_both(self, close_figures):\n fig = interaction_plot(self.weight, self.duration, self.days,\n colors=['red','blue'], markers=['D','^'], ms=10)\n\n @pytest.mark.matplotlib\n def test_plot_rainbow(self, close_figures):\n fig = interaction_plot(self.weight, self.duration, self.days,\n markers=['D','^'], ms=10)\n\n @pytest.mark.matplotlib\n @pytest.mark.parametrize('astype', ['str', 'int'])\n def test_plot_pandas(self, astype, close_figures):\n weight = Series(self.weight, name='Weight').astype(astype)\n duration = Series(self.duration, name='Duration')\n days = Series(self.days, name='Days')\n fig = interaction_plot(weight, duration, days,\n markers=['D', '^'], ms=10)\n ax = fig.axes[0]\n trace = ax.get_legend().get_title().get_text()\n assert_equal(trace, 'Duration')\n assert_equal(ax.get_ylabel(), 'mean of Days')\n assert_equal(ax.get_xlabel(), 'Weight')\n\n @pytest.mark.matplotlib\n def test_formatting(self, close_figures):\n fig = interaction_plot(self.weight, self.duration, self.days, colors=['r','g'], linestyles=['--','-.'])\n assert_equal(isinstance(fig, plt.Figure), True)\n\n @pytest.mark.matplotlib\n def test_formatting_errors(self, close_figures):\n assert_raises(ValueError, interaction_plot, self.weight, self.duration, self.days, markers=['D'])\n assert_raises(ValueError, interaction_plot, self.weight, self.duration, self.days, colors=['b','r','g'])\n assert_raises(ValueError, interaction_plot, self.weight, self.duration, self.days, linestyles=['--','-.',':'])\n\n @pytest.mark.matplotlib\n def test_plottype(self, close_figures):\n fig = interaction_plot(self.weight, self.duration, self.days, plottype='line')\n assert_equal(isinstance(fig, plt.Figure), True)\n fig = interaction_plot(self.weight, self.duration, self.days, plottype='scatter')\n assert_equal(isinstance(fig, plt.Figure), True)\n assert_raises(ValueError, interaction_plot, self.weight, self.duration, self.days, plottype='unknown')\n\n def test_recode_series(self):\n series = Series(['a', 'b'] * 10, index=np.arange(0, 40, 2),\n name='index_test')\n series_ = _recode(series, {'a': 0, 'b': 1})\n assert_equal(series_.index.values, series.index.values,\n err_msg='_recode changed the index')\n",
"\"\"\"\nTests for VARMAX models\n\nAuthor: Chad Fulton\nLicense: Simplified-BSD\n\"\"\"\nimport os\nimport re\nimport warnings\n\nimport numpy as np\nfrom numpy.testing import assert_equal, assert_allclose, assert_raises\nimport pandas as pd\nimport pytest\n\nfrom statsmodels.tsa.statespace import varmax, sarimax\nfrom statsmodels.iolib.summary import forg\n\nfrom .results import results_varmax\n\ncurrent_path = os.path.dirname(os.path.abspath(__file__))\n\nvar_path = os.path.join('results', 'results_var_stata.csv')\nvar_results = pd.read_csv(os.path.join(current_path, var_path))\n\nvarmax_path = os.path.join('results', 'results_varmax_stata.csv')\nvarmax_results = pd.read_csv(os.path.join(current_path, varmax_path))\n\n\nclass CheckVARMAX:\n \"\"\"\n Test Vector Autoregression against Stata's `dfactor` code (Stata's\n `var` function uses OLS and not state space / MLE, so we cannot get\n equivalent log-likelihoods)\n \"\"\"\n\n def test_mle(self):\n with warnings.catch_warnings(record=True):\n warnings.simplefilter('always')\n # Fit with all transformations\n # results = self.model.fit(method='powell', disp=-1)\n results = self.model.fit(maxiter=100, disp=False)\n # Fit now without transformations\n self.model.enforce_stationarity = False\n self.model.enforce_invertibility = False\n results = self.model.fit(results.params, method='nm', maxiter=1000,\n disp=False)\n self.model.enforce_stationarity = True\n self.model.enforce_invertibility = True\n assert_allclose(results.llf, self.results.llf, rtol=1e-5)\n\n @pytest.mark.smoke\n def test_params(self):\n # Smoke test to make sure the start_params are well-defined and\n # lead to a well-defined model\n model = self.model\n\n model.filter(model.start_params)\n # Similarly a smoke test for param_names\n assert len(model.start_params) == len(model.param_names)\n\n # Finally make sure the transform and untransform do their job\n actual = model.transform_params(\n model.untransform_params(model.start_params))\n assert_allclose(actual, model.start_params)\n\n # Also in the case of enforce invertibility and stationarity = False\n model.enforce_stationarity = False\n model.enforce_invertibility = False\n actual = model.transform_params(\n model.untransform_params(model.start_params))\n\n model.enforce_stationarity = True\n model.enforce_invertibility = True\n assert_allclose(actual, model.start_params)\n\n @pytest.mark.smoke\n def test_results(self):\n # Smoke test for creating the summary\n self.results.summary()\n\n model = self.model\n # Test cofficient matrix creation\n # (via a different, more direct, method)\n if model.k_ar > 0:\n params_ar = np.array(self.results.params[model._params_ar])\n coefficients = params_ar.reshape(model.k_endog,\n model.k_endog * model.k_ar)\n coefficient_matrices = np.array([\n coefficients[:model.k_endog,\n i*model.k_endog:(i+1)*model.k_endog]\n for i in range(model.k_ar)\n ])\n assert_equal(self.results.coefficient_matrices_var,\n coefficient_matrices)\n else:\n assert_equal(self.results.coefficient_matrices_var, None)\n if model.k_ma > 0:\n params_ma = np.array(self.results.params[model._params_ma])\n coefficients = params_ma.reshape(model.k_endog,\n model.k_endog * model.k_ma)\n\n coefficient_matrices = np.array([\n coefficients[:model.k_endog,\n i*model.k_endog:(i+1)*model.k_endog]\n for i in range(model.k_ma)\n ])\n assert_equal(self.results.coefficient_matrices_vma,\n coefficient_matrices)\n else:\n assert_equal(self.results.coefficient_matrices_vma, None)\n\n def test_loglike(self):\n assert_allclose(self.results.llf, self.true['loglike'], rtol=1e-6)\n\n def test_aic(self):\n # We only get 3 digits from Stata\n assert_allclose(self.results.aic, self.true['aic'], atol=3)\n\n def test_bic(self):\n # We only get 3 digits from Stata\n assert_allclose(self.results.bic, self.true['bic'], atol=3)\n\n def test_predict(self, end, atol=1e-6, **kwargs):\n # Tests predict + forecast\n assert_allclose(\n self.results.predict(end=end, **kwargs),\n self.true['predict'],\n atol=atol)\n\n def test_dynamic_predict(self, end, dynamic, atol=1e-6, **kwargs):\n # Tests predict + dynamic predict + forecast\n assert_allclose(\n self.results.predict(end=end, dynamic=dynamic, **kwargs),\n self.true['dynamic_predict'],\n atol=atol)\n\n def test_standardized_forecasts_error(self):\n cython_sfe = self.results.standardized_forecasts_error\n self.results._standardized_forecasts_error = None\n python_sfe = self.results.standardized_forecasts_error\n assert_allclose(cython_sfe, python_sfe)\n\n\nclass CheckLutkepohl(CheckVARMAX):\n @classmethod\n def setup_class(cls, true, order, trend, error_cov_type, cov_type='approx',\n included_vars=['dln_inv', 'dln_inc', 'dln_consump'],\n **kwargs):\n cls.true = true\n # 1960:Q1 - 1982:Q4\n dta = pd.DataFrame(\n results_varmax.lutkepohl_data, columns=['inv', 'inc', 'consump'],\n index=pd.date_range('1960-01-01', '1982-10-01', freq='QS'))\n\n dta['dln_inv'] = np.log(dta['inv']).diff()\n dta['dln_inc'] = np.log(dta['inc']).diff()\n dta['dln_consump'] = np.log(dta['consump']).diff()\n\n endog = dta.loc['1960-04-01':'1978-10-01', included_vars]\n\n cls.model = varmax.VARMAX(endog, order=order, trend=trend,\n error_cov_type=error_cov_type, **kwargs)\n\n cls.results = cls.model.smooth(true['params'], cov_type=cov_type)\n\n def test_predict(self, **kwargs):\n super(CheckLutkepohl, self).test_predict(end='1982-10-01', **kwargs)\n\n def test_dynamic_predict(self, **kwargs):\n super(CheckLutkepohl, self).test_dynamic_predict(end='1982-10-01',\n dynamic='1961-01-01',\n **kwargs)\n\n\nclass TestVAR(CheckLutkepohl):\n @classmethod\n def setup_class(cls):\n true = results_varmax.lutkepohl_var1.copy()\n true['predict'] = var_results.iloc[1:][['predict_1',\n 'predict_2',\n 'predict_3']]\n true['dynamic_predict'] = var_results.iloc[1:][['dyn_predict_1',\n 'dyn_predict_2',\n 'dyn_predict_3']]\n super(TestVAR, cls).setup_class(\n true, order=(1, 0), trend='n',\n error_cov_type=\"unstructured\")\n\n def test_bse_approx(self):\n bse = self.results._cov_params_approx().diagonal()**0.5\n assert_allclose(bse**2, self.true['var_oim'], atol=1e-4)\n\n def test_bse_oim(self):\n bse = self.results._cov_params_oim().diagonal()**0.5\n assert_allclose(bse**2, self.true['var_oim'], atol=1e-2)\n\n def test_summary(self):\n summary = self.results.summary()\n tables = [str(table) for table in summary.tables]\n params = self.true['params']\n\n # Check the model overview table\n assert re.search(r'Model:.*VAR\\(1\\)', tables[0])\n\n # For each endogenous variable, check the output\n for i in range(self.model.k_endog):\n offset = i * self.model.k_endog\n table = tables[i+2]\n\n # -> Make sure we have the right table / table name\n name = self.model.endog_names[i]\n assert re.search('Results for equation %s' % name, table)\n\n # -> Make sure it's the right size\n assert len(table.split('\\n')) == 8\n\n # -> Check that we have the right coefficients\n assert re.search('L1.dln_inv +%.4f' % params[offset + 0], table)\n assert re.search('L1.dln_inc +%.4f' % params[offset + 1], table)\n assert re.search('L1.dln_consump +%.4f' % params[offset + 2],\n table)\n\n # Test the error covariance matrix table\n table = tables[-1]\n assert re.search('Error covariance matrix', table)\n assert len(table.split('\\n')) == 11\n\n params = params[self.model._params_state_cov]\n names = self.model.param_names[self.model._params_state_cov]\n for i in range(len(names)):\n assert re.search('%s +%.4f' % (names[i], params[i]), table)\n\n\nclass TestVAR_diagonal(CheckLutkepohl):\n @classmethod\n def setup_class(cls):\n true = results_varmax.lutkepohl_var1_diag.copy()\n true['predict'] = var_results.iloc[1:][['predict_diag1',\n 'predict_diag2',\n 'predict_diag3']]\n true['dynamic_predict'] = var_results.iloc[1:][['dyn_predict_diag1',\n 'dyn_predict_diag2',\n 'dyn_predict_diag3']]\n super(TestVAR_diagonal, cls).setup_class(\n true, order=(1, 0), trend='n',\n error_cov_type=\"diagonal\")\n\n def test_bse_approx(self):\n bse = self.results._cov_params_approx().diagonal()**0.5\n assert_allclose(bse**2, self.true['var_oim'], atol=1e-5)\n\n def test_bse_oim(self):\n bse = self.results._cov_params_oim().diagonal()**0.5\n assert_allclose(bse**2, self.true['var_oim'], atol=1e-2)\n\n def test_summary(self):\n summary = self.results.summary()\n tables = [str(table) for table in summary.tables]\n params = self.true['params']\n\n # Check the model overview table\n assert re.search(r'Model:.*VAR\\(1\\)', tables[0])\n\n # For each endogenous variable, check the output\n for i in range(self.model.k_endog):\n offset = i * self.model.k_endog\n table = tables[i+2]\n\n # -> Make sure we have the right table / table name\n name = self.model.endog_names[i]\n assert re.search('Results for equation %s' % name, table)\n\n # -> Make sure it's the right size\n assert len(table.split('\\n')) == 8\n\n # -> Check that we have the right coefficients\n assert re.search('L1.dln_inv +%.4f' % params[offset + 0], table)\n assert re.search('L1.dln_inc +%.4f' % params[offset + 1], table)\n assert re.search('L1.dln_consump +%.4f' % params[offset + 2],\n table)\n\n # Test the error covariance matrix table\n table = tables[-1]\n assert re.search('Error covariance matrix', table)\n assert len(table.split('\\n')) == 8\n\n params = params[self.model._params_state_cov]\n names = self.model.param_names[self.model._params_state_cov]\n for i in range(len(names)):\n assert re.search('%s +%.4f' % (names[i], params[i]), table)\n\n\nclass TestVAR_measurement_error(CheckLutkepohl):\n \"\"\"\n Notes\n -----\n There does not appear to be a way to get Stata to estimate a VAR with\n measurement errors. Thus this test is mostly a smoke test that measurement\n errors are setup correctly: it uses the same params from TestVAR_diagonal\n and sets the measurement errors variance params to zero to check that the\n loglike and predict are the same.\n\n It also checks that the state-space representation with positive\n measurement errors is correct.\n \"\"\"\n @classmethod\n def setup_class(cls):\n true = results_varmax.lutkepohl_var1_diag_meas.copy()\n true['predict'] = var_results.iloc[1:][['predict_diag1',\n 'predict_diag2',\n 'predict_diag3']]\n true['dynamic_predict'] = var_results.iloc[1:][['dyn_predict_diag1',\n 'dyn_predict_diag2',\n 'dyn_predict_diag3']]\n super(TestVAR_measurement_error, cls).setup_class(\n true, order=(1, 0), trend='n',\n error_cov_type=\"diagonal\", measurement_error=True)\n\n # Create another filter results with positive measurement errors\n cls.true_measurement_error_variances = [1., 2., 3.]\n params = np.r_[true['params'][:-3],\n cls.true_measurement_error_variances]\n cls.results2 = cls.model.smooth(params)\n\n def test_mle(self):\n # With the additional measurment error parameters, this would not be\n # a meaningful test\n pass\n\n def test_bse_approx(self):\n # This would just test the same thing\n # as TestVAR_diagonal.test_bse_approx\n pass\n\n def test_bse_oim(self):\n # This would just test the same thing as TestVAR_diagonal.test_bse_oim\n pass\n\n def test_aic(self):\n # Since the measurement error is added, the number\n # of parameters, and hence the aic and bic, will be off\n pass\n\n def test_bic(self):\n # Since the measurement error is added, the number\n # of parameters, and hence the aic and bic, will be off\n pass\n\n def test_representation(self):\n # Test that the state space representation in the measurement error\n # case is correct\n for name in self.model.ssm.shapes.keys():\n if name == 'obs':\n pass\n elif name == 'obs_cov':\n actual = self.results2.filter_results.obs_cov\n desired = np.diag(\n self.true_measurement_error_variances)[:, :, np.newaxis]\n assert_equal(actual, desired)\n else:\n assert_equal(getattr(self.results2.filter_results, name),\n getattr(self.results.filter_results, name))\n\n def test_summary(self):\n summary = self.results.summary()\n tables = [str(table) for table in summary.tables]\n params = self.true['params']\n\n # Check the model overview table\n assert re.search(r'Model:.*VAR\\(1\\)', tables[0])\n\n # For each endogenous variable, check the output\n for i in range(self.model.k_endog):\n offset = i * self.model.k_endog\n table = tables[i+2]\n\n # -> Make sure we have the right table / table name\n name = self.model.endog_names[i]\n assert re.search('Results for equation %s' % name, table)\n\n # -> Make sure it's the right size\n assert len(table.split('\\n')) == 9\n\n # -> Check that we have the right coefficients\n assert re.search('L1.dln_inv +%.4f' % params[offset + 0], table)\n assert re.search('L1.dln_inc +%.4f' % params[offset + 1], table)\n assert re.search('L1.dln_consump +%.4f' % params[offset + 2],\n table)\n assert re.search('measurement_variance +%.4g' % params[-(i+1)],\n table)\n\n # Test the error covariance matrix table\n table = tables[-1]\n assert re.search('Error covariance matrix', table)\n assert len(table.split('\\n')) == 8\n\n params = params[self.model._params_state_cov]\n names = self.model.param_names[self.model._params_state_cov]\n for i in range(len(names)):\n assert re.search('%s +%.4f' % (names[i], params[i]), table)\n\n\nclass TestVAR_obs_intercept(CheckLutkepohl):\n @classmethod\n def setup_class(cls):\n true = results_varmax.lutkepohl_var1_obs_intercept.copy()\n true['predict'] = var_results.iloc[1:][['predict_int1',\n 'predict_int2',\n 'predict_int3']]\n true['dynamic_predict'] = var_results.iloc[1:][['dyn_predict_int1',\n 'dyn_predict_int2',\n 'dyn_predict_int3']]\n super(TestVAR_obs_intercept, cls).setup_class(\n true, order=(1, 0), trend='n',\n error_cov_type=\"diagonal\", obs_intercept=true['obs_intercept'])\n\n def test_bse_approx(self):\n bse = self.results._cov_params_approx().diagonal()**0.5\n assert_allclose(bse**2, self.true['var_oim'], atol=1e-4)\n\n def test_bse_oim(self):\n bse = self.results._cov_params_oim().diagonal()**0.5\n assert_allclose(bse**2, self.true['var_oim'], atol=1e-2)\n\n def test_aic(self):\n # Since the obs_intercept is added in in an ad-hoc way here, the number\n # of parameters, and hence the aic and bic, will be off\n pass\n\n def test_bic(self):\n # Since the obs_intercept is added in in an ad-hoc way here, the number\n # of parameters, and hence the aic and bic, will be off\n pass\n\n\nclass TestVAR_exog(CheckLutkepohl):\n # Note: unlike the other tests in this file, this is against the Stata\n # var function rather than the Stata dfactor function\n @classmethod\n def setup_class(cls):\n true = results_varmax.lutkepohl_var1_exog.copy()\n true['predict'] = var_results.iloc[1:76][['predict_exog1_1',\n 'predict_exog1_2',\n 'predict_exog1_3']]\n true['predict'].iloc[0, :] = 0\n true['fcast'] = var_results.iloc[76:][['fcast_exog1_dln_inv',\n 'fcast_exog1_dln_inc',\n 'fcast_exog1_dln_consump']]\n exog = np.arange(75) + 2\n super(TestVAR_exog, cls).setup_class(\n true, order=(1, 0), trend='n', error_cov_type='unstructured',\n exog=exog, initialization='approximate_diffuse',\n loglikelihood_burn=1)\n\n def test_mle(self):\n pass\n\n def test_aic(self):\n # Stata's var calculates AIC differently\n pass\n\n def test_bic(self):\n # Stata's var calculates BIC differently\n pass\n\n def test_bse_approx(self):\n # Exclude the covariance cholesky terms\n bse = self.results._cov_params_approx().diagonal()**0.5\n assert_allclose(bse[:-6]**2, self.true['var_oim'], atol=1e-5)\n\n def test_bse_oim(self):\n # Exclude the covariance cholesky terms\n bse = self.results._cov_params_oim().diagonal()**0.5\n assert_allclose(bse[:-6]**2, self.true['var_oim'], atol=1e-5)\n\n def test_predict(self):\n super(CheckLutkepohl, self).test_predict(end='1978-10-01', atol=1e-3)\n\n def test_dynamic_predict(self):\n # Stata's var cannot subsequently use dynamic\n pass\n\n def test_forecast(self):\n # Tests forecast\n exog = (np.arange(75, 75+16) + 2)[:, np.newaxis]\n\n # Test it through the results class wrapper\n desired = self.results.forecast(steps=16, exog=exog)\n assert_allclose(desired, self.true['fcast'], atol=1e-6)\n\n # Test it directly (i.e. without the wrapping done in\n # VARMAXResults.get_prediction which converts exog to state_intercept)\n # beta = self.results.params[-9:-6]\n # state_intercept = np.concatenate([\n # exog*beta[0], exog*beta[1], exog*beta[2]], axis=1).T\n # desired = mlemodel.MLEResults.get_prediction(\n # self.results._results, start=75, end=75+15,\n # state_intercept=state_intercept).predicted_mean\n # assert_allclose(desired, self.true['fcast'], atol=1e-6)\n\n def test_summary(self):\n summary = self.results.summary()\n tables = [str(table) for table in summary.tables]\n params = self.true['params']\n\n # Check the model overview table\n assert re.search(r'Model:.*VARX\\(1\\)', tables[0])\n\n # For each endogenous variable, check the output\n for i in range(self.model.k_endog):\n offset = i * self.model.k_endog\n table = tables[i+2]\n\n # -> Make sure we have the right table / table name\n name = self.model.endog_names[i]\n assert re.search('Results for equation %s' % name, table)\n\n # -> Make sure it's the right size\n assert len(table.split('\\n')) == 9\n\n # -> Check that we have the right coefficients\n assert re.search('L1.dln_inv +%.4f' % params[offset + 0], table)\n assert re.search('L1.dln_inc +%.4f' % params[offset + 1], table)\n assert re.search(\n 'L1.dln_consump +%.4f' % params[offset + 2], table)\n assert re.search(\n 'beta.x1 +' + forg(params[self.model._params_regression][i],\n prec=4),\n table)\n\n # Test the error covariance matrix table\n table = tables[-1]\n assert re.search('Error covariance matrix', table)\n assert len(table.split('\\n')) == 11\n\n params = params[self.model._params_state_cov]\n names = self.model.param_names[self.model._params_state_cov]\n for i in range(len(names)):\n assert re.search('%s +%.4f' % (names[i], params[i]), table)\n\n\nclass TestVAR_exog2(CheckLutkepohl):\n # This is a regression test, to make sure that the setup with multiple exog\n # works correctly. The params are from Stata, but the loglike is from\n # this model. Likely the small discrepancy (see the results file) is from\n # the approximate diffuse initialization.\n @classmethod\n def setup_class(cls):\n true = results_varmax.lutkepohl_var1_exog2.copy()\n true['predict'] = var_results.iloc[1:76][['predict_exog2_1',\n 'predict_exog2_2',\n 'predict_exog2_3']]\n true['predict'].iloc[0, :] = 0\n true['fcast'] = var_results.iloc[76:][['fcast_exog2_dln_inv',\n 'fcast_exog2_dln_inc',\n 'fcast_exog2_dln_consump']]\n exog = np.c_[np.ones((75, 1)), (np.arange(75) + 2)[:, np.newaxis]]\n super(TestVAR_exog2, cls).setup_class(\n true, order=(1, 0), trend='n', error_cov_type='unstructured',\n exog=exog, initialization='approximate_diffuse',\n loglikelihood_burn=1)\n\n def test_mle(self):\n pass\n\n def test_aic(self):\n pass\n\n def test_bic(self):\n pass\n\n def test_bse_approx(self):\n pass\n\n def test_bse_oim(self):\n pass\n\n def test_predict(self):\n super(CheckLutkepohl, self).test_predict(end='1978-10-01', atol=1e-3)\n\n def test_dynamic_predict(self):\n # Stata's var cannot subsequently use dynamic\n pass\n\n def test_forecast(self):\n # Tests forecast\n exog = np.c_[np.ones((16, 1)),\n (np.arange(75, 75+16) + 2)[:, np.newaxis]]\n\n desired = self.results.forecast(steps=16, exog=exog)\n assert_allclose(desired, self.true['fcast'], atol=1e-6)\n\n\nclass TestVAR2(CheckLutkepohl):\n @classmethod\n def setup_class(cls):\n true = results_varmax.lutkepohl_var2.copy()\n true['predict'] = var_results.iloc[1:][['predict_var2_1',\n 'predict_var2_2']]\n true['dynamic_predict'] = var_results.iloc[1:][['dyn_predict_var2_1',\n 'dyn_predict_var2_2']]\n super(TestVAR2, cls).setup_class(\n true, order=(2, 0), trend='n', error_cov_type='unstructured',\n included_vars=['dln_inv', 'dln_inc'])\n\n def test_bse_approx(self):\n # Exclude the covariance cholesky terms\n bse = self.results._cov_params_approx().diagonal()**0.5\n assert_allclose(bse[:-3]**2, self.true['var_oim'][:-3], atol=1e-5)\n\n def test_bse_oim(self):\n # Exclude the covariance cholesky terms\n bse = self.results._cov_params_oim().diagonal()**0.5\n assert_allclose(bse[:-3]**2, self.true['var_oim'][:-3], atol=1e-2)\n\n def test_summary(self):\n summary = self.results.summary()\n tables = [str(table) for table in summary.tables]\n params = self.true['params']\n\n # Check the model overview table\n assert re.search(r'Model:.*VAR\\(2\\)', tables[0])\n\n # For each endogenous variable, check the output\n for i in range(self.model.k_endog):\n offset = i * self.model.k_endog * self.model.k_ar\n table = tables[i+2]\n\n # -> Make sure we have the right table / table name\n name = self.model.endog_names[i]\n assert re.search('Results for equation %s' % name, table)\n\n # -> Make sure it's the right size\n assert len(table.split('\\n')) == 9\n\n # -> Check that we have the right coefficients\n assert re.search('L1.dln_inv +%.4f' % params[offset + 0], table)\n assert re.search('L1.dln_inc +%.4f' % params[offset + 1], table)\n assert re.search('L2.dln_inv +%.4f' % params[offset + 2], table)\n assert re.search('L2.dln_inc +%.4f' % params[offset + 3], table)\n\n # Test the error covariance matrix table\n table = tables[-1]\n assert re.search('Error covariance matrix', table)\n assert len(table.split('\\n')) == 8\n\n params = params[self.model._params_state_cov]\n names = self.model.param_names[self.model._params_state_cov]\n for i in range(len(names)):\n assert re.search('%s +%.4f' % (names[i], params[i]), table)\n\n\nclass CheckFREDManufacturing(CheckVARMAX):\n @classmethod\n def setup_class(cls, true, order, trend, error_cov_type, cov_type='approx',\n **kwargs):\n cls.true = true\n # 1960:Q1 - 1982:Q4\n path = os.path.join(current_path, 'results', 'manufac.dta')\n with open(path, 'rb') as test_data:\n dta = pd.read_stata(test_data)\n dta.index = pd.DatetimeIndex(dta.month, freq='MS')\n dta['dlncaputil'] = dta['lncaputil'].diff()\n dta['dlnhours'] = dta['lnhours'].diff()\n\n endog = dta.loc['1972-02-01':, ['dlncaputil', 'dlnhours']]\n\n with warnings.catch_warnings(record=True):\n warnings.simplefilter('always')\n cls.model = varmax.VARMAX(endog, order=order, trend=trend,\n error_cov_type=error_cov_type, **kwargs)\n\n cls.results = cls.model.smooth(true['params'], cov_type=cov_type)\n\n\nclass TestVARMA(CheckFREDManufacturing):\n \"\"\"\n Test against the sspace VARMA example with some params set to zeros.\n \"\"\"\n\n @classmethod\n def setup_class(cls):\n true = results_varmax.fred_varma11.copy()\n true['predict'] = varmax_results.iloc[1:][['predict_varma11_1',\n 'predict_varma11_2']]\n true['dynamic_predict'] = varmax_results.iloc[1:][[\n 'dyn_predict_varma11_1', 'dyn_predict_varma11_2']]\n\n super(TestVARMA, cls).setup_class(\n true, order=(1, 1), trend='n', error_cov_type='diagonal')\n\n def test_mle(self):\n # Since the VARMA model here is generic (we're just forcing zeros\n # in some params) whereas Stata's is restricted, the MLE test is not\n # meaninful\n pass\n\n @pytest.mark.skip('Known failure: standard errors do not match.')\n def test_bse_approx(self):\n # Standard errors do not match Stata's\n pass\n\n @pytest.mark.skip('Known failure: standard errors do not match.')\n def test_bse_oim(self):\n # Standard errors do not match Stata's\n pass\n\n def test_aic(self):\n # Since the VARMA model here is generic (we're just putting in zeros\n # for some params), Stata assumes a different estimated number of\n # parameters; hence the aic and bic, will be off\n pass\n\n def test_bic(self):\n # Since the VARMA model here is generic (we're just putting in zeros\n # for some params), Stata assumes a different estimated number of\n # parameters; hence the aic and bic, will be off\n pass\n\n def test_predict(self):\n super(TestVARMA, self).test_predict(end='2009-05-01', atol=1e-4)\n\n def test_dynamic_predict(self):\n super(TestVARMA, self).test_dynamic_predict(end='2009-05-01',\n dynamic='2000-01-01')\n\n def test_summary(self):\n summary = self.results.summary()\n tables = [str(table) for table in summary.tables]\n params = self.true['params']\n\n # Check the model overview table\n assert re.search(r'Model:.*VARMA\\(1,1\\)', tables[0])\n\n # For each endogenous variable, check the output\n for i in range(self.model.k_endog):\n offset_ar = i * self.model.k_endog\n offset_ma = (self.model.k_endog**2 * self.model.k_ar +\n i * self.model.k_endog)\n table = tables[i+2]\n\n # -> Make sure we have the right table / table name\n name = self.model.endog_names[i]\n assert re.search('Results for equation %s' % name, table)\n\n # -> Make sure it's the right size\n assert len(table.split('\\n')) == 9\n\n # -> Check that we have the right coefficients\n assert re.search(\n 'L1.dlncaputil +' + forg(params[offset_ar + 0], prec=4),\n table)\n assert re.search(\n 'L1.dlnhours +' + forg(params[offset_ar + 1], prec=4),\n table)\n assert re.search(\n r'L1.e\\(dlncaputil\\) +' + forg(params[offset_ma + 0], prec=4),\n table)\n assert re.search(\n r'L1.e\\(dlnhours\\) +' + forg(params[offset_ma + 1], prec=4),\n table)\n\n # Test the error covariance matrix table\n table = tables[-1]\n assert re.search('Error covariance matrix', table)\n assert len(table.split('\\n')) == 7\n\n params = params[self.model._params_state_cov]\n names = self.model.param_names[self.model._params_state_cov]\n for i in range(len(names)):\n assert re.search('%s +%s' % (names[i], forg(params[i], prec=4)),\n table)\n\n\nclass TestVMA1(CheckFREDManufacturing):\n \"\"\"\n Test against the sspace VARMA example with some params set to zeros.\n \"\"\"\n\n @classmethod\n def setup_class(cls):\n true = results_varmax.fred_vma1.copy()\n true['predict'] = varmax_results.iloc[1:][['predict_vma1_1',\n 'predict_vma1_2']]\n true['dynamic_predict'] = varmax_results.iloc[1:][[\n 'dyn_predict_vma1_1', 'dyn_predict_vma1_2']]\n\n super(TestVMA1, cls).setup_class(\n true, order=(0, 1), trend='n', error_cov_type='diagonal')\n\n def test_mle(self):\n # Since the VARMA model here is generic (we're just forcing zeros\n # in some params) whereas Stata's is restricted, the MLE test is not\n # meaninful\n pass\n\n @pytest.mark.skip('Known failure: standard errors do not match.')\n def test_bse_approx(self):\n # Standard errors do not match Stata's\n pass\n\n @pytest.mark.skip('Known failure: standard errors do not match.')\n def test_bse_oim(self):\n # Standard errors do not match Stata's\n pass\n\n def test_aic(self):\n # Since the VARMA model here is generic (we're just putting in zeros\n # for some params), Stata assumes a different estimated number of\n # parameters; hence the aic and bic, will be off\n pass\n\n def test_bic(self):\n # Since the VARMA model here is generic (we're just putting in zeros\n # for some params), Stata assumes a different estimated number of\n # parameters; hence the aic and bic, will be off\n pass\n\n def test_predict(self):\n super(TestVMA1, self).test_predict(end='2009-05-01', atol=1e-4)\n\n def test_dynamic_predict(self):\n super(TestVMA1, self).test_dynamic_predict(end='2009-05-01',\n dynamic='2000-01-01')\n\n\ndef test_specifications():\n # Tests for model specification and state space creation\n endog = np.arange(20).reshape(10, 2)\n exog = np.arange(10)\n exog2 = pd.Series(exog, index=pd.date_range('2000-01-01', '2009-01-01',\n freq='AS'))\n\n # Test successful model creation\n varmax.VARMAX(endog, exog=exog, order=(1, 0))\n\n # Test successful model creation with pandas exog\n varmax.VARMAX(endog, exog=exog2, order=(1, 0))\n\n\ndef test_misspecifications():\n varmax.__warningregistry__ = {}\n\n # Tests for model specification and misspecification exceptions\n endog = np.arange(20).reshape(10, 2)\n\n # Bad trend specification\n with pytest.raises(ValueError):\n varmax.VARMAX(endog, order=(1, 0), trend='')\n\n # Bad error_cov_type specification\n with pytest.raises(ValueError):\n varmax.VARMAX(endog, order=(1, 0), error_cov_type='')\n\n # Bad order specification\n with pytest.raises(ValueError):\n varmax.VARMAX(endog, order=(0, 0))\n\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter('always')\n varmax.VARMAX(endog, order=(1, 1))\n\n # Warning with VARMA specification\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter('always')\n\n varmax.VARMAX(endog, order=(1, 1))\n\n message = ('Estimation of VARMA(p,q) models is not generically robust,'\n ' due especially to identification issues.')\n assert str(w[0].message) == message\n\n warnings.resetwarnings()\n\n\ndef test_misc_exog():\n # Tests for missing data\n nobs = 20\n k_endog = 2\n np.random.seed(1208)\n endog = np.random.normal(size=(nobs, k_endog))\n endog[:4, 0] = np.nan\n endog[2:6, 1] = np.nan\n exog1 = np.random.normal(size=(nobs, 1))\n exog2 = np.random.normal(size=(nobs, 2))\n\n index = pd.date_range('1970-01-01', freq='QS', periods=nobs)\n endog_pd = pd.DataFrame(endog, index=index)\n exog1_pd = pd.Series(exog1.squeeze(), index=index)\n exog2_pd = pd.DataFrame(exog2, index=index)\n\n models = [\n varmax.VARMAX(endog, exog=exog1, order=(1, 0)),\n varmax.VARMAX(endog, exog=exog2, order=(1, 0)),\n varmax.VARMAX(endog_pd, exog=exog1_pd, order=(1, 0)),\n varmax.VARMAX(endog_pd, exog=exog2_pd, order=(1, 0)),\n ]\n\n for mod in models:\n # Smoke tests\n mod.start_params\n res = mod.fit(disp=False)\n res.summary()\n res.predict()\n res.predict(dynamic=True)\n res.get_prediction()\n\n oos_exog = np.random.normal(size=(1, mod.k_exog))\n res.forecast(steps=1, exog=oos_exog)\n res.get_forecast(steps=1, exog=oos_exog)\n\n # Smoke tests for invalid exog\n oos_exog = np.random.normal(size=(2, mod.k_exog))\n with pytest.raises(ValueError):\n res.forecast(steps=1, exog=oos_exog)\n\n oos_exog = np.random.normal(size=(1, mod.k_exog + 1))\n with pytest.raises(ValueError):\n res.forecast(steps=1, exog=oos_exog)\n\n # Test invalid model specifications\n with pytest.raises(ValueError):\n varmax.VARMAX(endog, exog=np.zeros((10, 4)), order=(1, 0))\n\n\ndef test_predict_custom_index():\n np.random.seed(328423)\n endog = pd.DataFrame(np.random.normal(size=(50, 2)))\n mod = varmax.VARMAX(endog, order=(1, 0))\n res = mod.smooth(mod.start_params)\n out = res.predict(start=1, end=1, index=['a'])\n assert out.index.equals(pd.Index(['a']))\n\n\ndef test_forecast_exog():\n # Test forecasting with various shapes of `exog`\n nobs = 100\n endog = np.ones((nobs, 2)) * 2.0\n exog = np.ones(nobs)\n\n mod = varmax.VARMAX(endog, order=(1, 0), exog=exog, trend='n')\n res = mod.smooth(np.r_[[0] * 4, 2.0, 2.0, 1, 0, 1])\n\n # 1-step-ahead, valid\n exog_fcast_scalar = 1.\n exog_fcast_1dim = np.ones(1)\n exog_fcast_2dim = np.ones((1, 1))\n\n assert_allclose(res.forecast(1, exog=exog_fcast_scalar), 2.)\n assert_allclose(res.forecast(1, exog=exog_fcast_1dim), 2.)\n assert_allclose(res.forecast(1, exog=exog_fcast_2dim), 2.)\n\n # h-steps-ahead, valid\n h = 10\n exog_fcast_1dim = np.ones(h)\n exog_fcast_2dim = np.ones((h, 1))\n\n assert_allclose(res.forecast(h, exog=exog_fcast_1dim), 2.)\n assert_allclose(res.forecast(h, exog=exog_fcast_2dim), 2.)\n\n # h-steps-ahead, invalid\n assert_raises(ValueError, res.forecast, h, exog=1.)\n assert_raises(ValueError, res.forecast, h, exog=[1, 2])\n assert_raises(ValueError, res.forecast, h, exog=np.ones((h, 2)))\n\n\ndef check_equivalent_models(mod, mod2):\n attrs = [\n 'order', 'trend', 'error_cov_type', 'measurement_error',\n 'enforce_stationarity', 'enforce_invertibility', 'k_params']\n\n ssm_attrs = [\n 'nobs', 'k_endog', 'k_states', 'k_posdef', 'obs_intercept', 'design',\n 'obs_cov', 'state_intercept', 'transition', 'selection', 'state_cov']\n\n for attr in attrs:\n assert_equal(getattr(mod2, attr), getattr(mod, attr))\n\n for attr in ssm_attrs:\n assert_equal(getattr(mod2.ssm, attr), getattr(mod.ssm, attr))\n\n assert_equal(mod2._get_init_kwds(), mod._get_init_kwds())\n\n\ndef test_recreate_model():\n nobs = 100\n endog = np.ones((nobs, 3)) * 2.0\n exog = np.ones(nobs)\n\n orders = [(1, 0), (1, 1)]\n trends = ['t', 'n']\n error_cov_types = ['diagonal', 'unstructured']\n measurement_errors = [False, True]\n enforce_stationarities = [False, True]\n enforce_invertibilities = [False, True]\n\n import itertools\n names = ['order', 'trend', 'error_cov_type', 'measurement_error',\n 'enforce_stationarity', 'enforce_invertibility']\n for element in itertools.product(orders, trends, error_cov_types,\n measurement_errors,\n enforce_stationarities,\n enforce_invertibilities):\n kwargs = dict(zip(names, element))\n\n with warnings.catch_warnings(record=False):\n warnings.simplefilter('ignore')\n mod = varmax.VARMAX(endog, exog=exog, **kwargs)\n mod2 = varmax.VARMAX(endog, exog=exog, **mod._get_init_kwds())\n check_equivalent_models(mod, mod2)\n\n\ndef test_append_results():\n endog = np.arange(200).reshape(100, 2)\n exog = np.ones(100)\n params = [0.1, 0.2,\n 0.5, -0.1, 0.0, 0.2,\n 1., 2.,\n 1., 0., 1.]\n\n mod1 = varmax.VARMAX(endog, order=(1, 0), trend='t', exog=exog)\n res1 = mod1.smooth(params)\n\n mod2 = varmax.VARMAX(endog[:50], order=(1, 0), trend='t', exog=exog[:50])\n res2 = mod2.smooth(params)\n res3 = res2.append(endog[50:], exog=exog[50:])\n\n assert_equal(res1.specification, res3.specification)\n\n assert_allclose(res3.cov_params_default, res2.cov_params_default)\n for attr in ['nobs', 'llf', 'llf_obs', 'loglikelihood_burn']:\n assert_equal(getattr(res3, attr), getattr(res1, attr))\n\n for attr in [\n 'filtered_state', 'filtered_state_cov', 'predicted_state',\n 'predicted_state_cov', 'forecasts', 'forecasts_error',\n 'forecasts_error_cov', 'standardized_forecasts_error',\n 'forecasts_error_diffuse_cov', 'predicted_diffuse_state_cov',\n 'scaled_smoothed_estimator',\n 'scaled_smoothed_estimator_cov', 'smoothing_error',\n 'smoothed_state',\n 'smoothed_state_cov', 'smoothed_state_autocov',\n 'smoothed_measurement_disturbance',\n 'smoothed_state_disturbance',\n 'smoothed_measurement_disturbance_cov',\n 'smoothed_state_disturbance_cov']:\n assert_equal(getattr(res3, attr), getattr(res1, attr))\n\n assert_allclose(res3.forecast(10, exog=np.ones(10)),\n res1.forecast(10, exog=np.ones(10)))\n\n\[email protected]('trend', ['n', 'c', 'ct'])\[email protected]('forecast', [True, False])\ndef test_extend_results(trend, forecast):\n endog = np.arange(200).reshape(100, 2)\n trend_params = []\n if trend == 'c':\n trend_params = [0.1, 0.2]\n if trend == 'ct':\n trend_params = [0.1, 0.2, 1., 2.]\n params = np.r_[trend_params,\n 0.5, -0.1, 0.0, 0.2,\n 1., 0., 1.]\n\n mod1 = varmax.VARMAX(endog, order=(1, 0), trend=trend)\n res1 = mod1.smooth(params)\n if forecast:\n # Call `forecast` to trigger the _set_final_exog and\n # _set_final_predicted_state context managers\n res1.forecast()\n\n mod2 = mod1.clone(endog[:50])\n res2 = mod2.smooth(params)\n if forecast:\n # Call `forecast` to trigger the _set_final_exog and\n # _set_final_predicted_state context managers\n res2.forecast()\n res3 = res2.extend(endog[50:])\n\n assert_allclose(res3.llf_obs, res1.llf_obs[50:])\n\n for attr in [\n 'filtered_state', 'filtered_state_cov', 'predicted_state',\n 'predicted_state_cov', 'forecasts', 'forecasts_error',\n 'forecasts_error_cov', 'standardized_forecasts_error',\n 'scaled_smoothed_estimator',\n 'scaled_smoothed_estimator_cov', 'smoothing_error',\n 'smoothed_state',\n 'smoothed_state_cov', 'smoothed_state_autocov',\n 'smoothed_measurement_disturbance',\n 'smoothed_state_disturbance',\n 'smoothed_measurement_disturbance_cov',\n 'smoothed_state_disturbance_cov']:\n desired = getattr(res1, attr)\n if desired is not None:\n desired = desired[..., 50:]\n assert_allclose(getattr(res3, attr), desired, atol=1e-12)\n\n assert_allclose(res3.forecast(10), res1.forecast(10))\n\n\ndef test_extend_results_exog():\n endog = np.arange(200).reshape(100, 2)\n exog = np.ones(100)\n params = [0.1, 0.2,\n 0.5, -0.1, 0.0, 0.2,\n 1., 2.,\n 1., 0., 1.]\n\n mod1 = varmax.VARMAX(endog, order=(1, 0), trend='t', exog=exog)\n res1 = mod1.smooth(params)\n\n mod2 = varmax.VARMAX(endog[:50], order=(1, 0), trend='t', exog=exog[:50])\n res2 = mod2.smooth(params)\n res3 = res2.extend(endog[50:], exog=exog[50:])\n\n assert_allclose(res3.llf_obs, res1.llf_obs[50:])\n\n for attr in [\n 'filtered_state', 'filtered_state_cov', 'predicted_state',\n 'predicted_state_cov', 'forecasts', 'forecasts_error',\n 'forecasts_error_cov', 'standardized_forecasts_error',\n 'forecasts_error_diffuse_cov', 'predicted_diffuse_state_cov',\n 'scaled_smoothed_estimator',\n 'scaled_smoothed_estimator_cov', 'smoothing_error',\n 'smoothed_state',\n 'smoothed_state_cov', 'smoothed_state_autocov',\n 'smoothed_measurement_disturbance',\n 'smoothed_state_disturbance',\n 'smoothed_measurement_disturbance_cov',\n 'smoothed_state_disturbance_cov']:\n desired = getattr(res1, attr)\n if desired is not None:\n desired = desired[..., 50:]\n assert_equal(getattr(res3, attr), desired)\n\n assert_allclose(res3.forecast(10, exog=np.ones(10)),\n res1.forecast(10, exog=np.ones(10)))\n\n\ndef test_apply_results():\n endog = np.arange(200).reshape(100, 2)\n exog = np.ones(100)\n params = [0.1, 0.2,\n 0.5, -0.1, 0.0, 0.2,\n 1., 2.,\n 1., 0., 1.]\n\n mod1 = varmax.VARMAX(endog[:50], order=(1, 0), trend='t', exog=exog[:50])\n res1 = mod1.smooth(params)\n\n mod2 = varmax.VARMAX(endog[50:], order=(1, 0), trend='t', exog=exog[50:])\n res2 = mod2.smooth(params)\n\n res3 = res2.apply(endog[:50], exog=exog[:50])\n\n assert_equal(res1.specification, res3.specification)\n\n assert_allclose(res3.cov_params_default, res2.cov_params_default)\n for attr in ['nobs', 'llf', 'llf_obs', 'loglikelihood_burn']:\n assert_equal(getattr(res3, attr), getattr(res1, attr))\n\n for attr in [\n 'filtered_state', 'filtered_state_cov', 'predicted_state',\n 'predicted_state_cov', 'forecasts', 'forecasts_error',\n 'forecasts_error_cov', 'standardized_forecasts_error',\n 'forecasts_error_diffuse_cov', 'predicted_diffuse_state_cov',\n 'scaled_smoothed_estimator',\n 'scaled_smoothed_estimator_cov', 'smoothing_error',\n 'smoothed_state',\n 'smoothed_state_cov', 'smoothed_state_autocov',\n 'smoothed_measurement_disturbance',\n 'smoothed_state_disturbance',\n 'smoothed_measurement_disturbance_cov',\n 'smoothed_state_disturbance_cov']:\n assert_equal(getattr(res3, attr), getattr(res1, attr))\n\n assert_allclose(res3.forecast(10, exog=np.ones(10)),\n res1.forecast(10, exog=np.ones(10)))\n\n\ndef test_vma1_exog():\n # Test the VMAX(1) case against univariate MAX(1) models\n dta = pd.DataFrame(\n results_varmax.lutkepohl_data, columns=['inv', 'inc', 'consump'],\n index=pd.date_range('1960-01-01', '1982-10-01', freq='QS'))\n dta = np.log(dta).diff().iloc[1:]\n\n endog = dta.iloc[:, :2]\n exog = dta.iloc[:, 2]\n\n ma_params1 = [-0.01, 1.4, -0.3, 0.002]\n ma_params2 = [0.004, 0.8, -0.5, 0.0001]\n\n vma_params = [ma_params1[0], ma_params2[0],\n ma_params1[2], 0,\n 0, ma_params2[2],\n ma_params1[1], ma_params2[1],\n ma_params1[3], ma_params2[3]]\n\n # Joint VMA model\n mod_vma = varmax.VARMAX(endog, exog=exog, order=(0, 1),\n error_cov_type='diagonal')\n mod_vma.ssm.initialize_diffuse()\n res_mva = mod_vma.smooth(vma_params)\n\n # Smoke test that start_params does not raise an error\n sp = mod_vma.start_params\n assert_equal(len(sp), len(mod_vma.param_names))\n\n # Univariate MA models\n mod_ma1 = sarimax.SARIMAX(endog.iloc[:, 0], exog=exog, order=(0, 0, 1),\n trend='c')\n mod_ma1.ssm.initialize_diffuse()\n mod_ma2 = sarimax.SARIMAX(endog.iloc[:, 1], exog=exog, order=(0, 0, 1),\n trend='c')\n mod_ma2.ssm.initialize_diffuse()\n res_ma1 = mod_ma1.smooth(ma_params1)\n res_ma2 = mod_ma2.smooth(ma_params2)\n\n # Have to ignore first 2 observations due to differences in initialization\n assert_allclose(res_mva.llf_obs[2:],\n (res_ma1.llf_obs + res_ma2.llf_obs)[2:])\n\n\ndef test_param_names_trend():\n endog = np.zeros((3, 2))\n base_names = ['L1.y1.y1', 'L1.y2.y1', 'L1.y1.y2', 'L1.y2.y2',\n 'sqrt.var.y1', 'sqrt.cov.y1.y2', 'sqrt.var.y2']\n base_params = [0.5, 0, 0, 0.4, 1.0, 0.0, 1.0]\n\n # No trend\n mod = varmax.VARMAX(endog, order=(1, 0), trend='n')\n desired = base_names\n assert_equal(mod.param_names, desired)\n\n # Intercept\n mod = varmax.VARMAX(endog, order=(1, 0), trend=[1])\n desired = ['intercept.y1', 'intercept.y2'] + base_names\n assert_equal(mod.param_names, desired)\n mod.update([1.2, -0.5] + base_params)\n assert_allclose(mod['state_intercept'], [1.2, -0.5])\n\n # Intercept + drift\n mod = varmax.VARMAX(endog, order=(1, 0), trend=[1, 1])\n desired = (['intercept.y1', 'drift.y1',\n 'intercept.y2', 'drift.y2'] + base_names)\n assert_equal(mod.param_names, desired)\n mod.update([1.2, 0, -0.5, 0] + base_params)\n assert_allclose(mod['state_intercept', 0], 1.2)\n assert_allclose(mod['state_intercept', 1], -0.5)\n mod.update([0, 1, 0, 1.1] + base_params)\n assert_allclose(mod['state_intercept', 0], np.arange(2, 5))\n assert_allclose(mod['state_intercept', 1], 1.1 * np.arange(2, 5))\n mod.update([1.2, 1, -0.5, 1.1] + base_params)\n assert_allclose(mod['state_intercept', 0], 1.2 + np.arange(2, 5))\n assert_allclose(mod['state_intercept', 1], -0.5 + 1.1 * np.arange(2, 5))\n\n # Drift only\n mod = varmax.VARMAX(endog, order=(1, 0), trend=[0, 1])\n desired = ['drift.y1', 'drift.y2'] + base_names\n assert_equal(mod.param_names, desired)\n mod.update([1, 1.1] + base_params)\n assert_allclose(mod['state_intercept', 0], np.arange(2, 5))\n assert_allclose(mod['state_intercept', 1], 1.1 * np.arange(2, 5))\n\n # Intercept + third order\n mod = varmax.VARMAX(endog, order=(1, 0), trend=[1, 0, 1])\n desired = (['intercept.y1', 'trend.2.y1',\n 'intercept.y2', 'trend.2.y2'] + base_names)\n assert_equal(mod.param_names, desired)\n mod.update([1.2, 0, -0.5, 0] + base_params)\n assert_allclose(mod['state_intercept', 0], 1.2)\n assert_allclose(mod['state_intercept', 1], -0.5)\n mod.update([0, 1, 0, 1.1] + base_params)\n assert_allclose(mod['state_intercept', 0], np.arange(2, 5)**2)\n assert_allclose(mod['state_intercept', 1], 1.1 * np.arange(2, 5)**2)\n mod.update([1.2, 1, -0.5, 1.1] + base_params)\n assert_allclose(mod['state_intercept', 0], 1.2 + np.arange(2, 5)**2)\n assert_allclose(mod['state_intercept', 1], -0.5 + 1.1 * np.arange(2, 5)**2)\n",
"\"\"\"\nEmpirical CDF Functions\n\"\"\"\nimport numpy as np\nfrom scipy.interpolate import interp1d\n\ndef _conf_set(F, alpha=.05):\n r\"\"\"\n Constructs a Dvoretzky-Kiefer-Wolfowitz confidence band for the eCDF.\n\n Parameters\n ----------\n F : array_like\n The empirical distributions\n alpha : float\n Set alpha for a (1 - alpha) % confidence band.\n\n Notes\n -----\n Based on the DKW inequality.\n\n .. math:: P \\left( \\sup_x \\left| F(x) - \\hat(F)_n(X) \\right| > \\epsilon \\right) \\leq 2e^{-2n\\epsilon^2}\n\n References\n ----------\n Wasserman, L. 2006. `All of Nonparametric Statistics`. Springer.\n \"\"\"\n nobs = len(F)\n epsilon = np.sqrt(np.log(2./alpha) / (2 * nobs))\n lower = np.clip(F - epsilon, 0, 1)\n upper = np.clip(F + epsilon, 0, 1)\n return lower, upper\n\nclass StepFunction:\n \"\"\"\n A basic step function.\n\n Values at the ends are handled in the simplest way possible:\n everything to the left of x[0] is set to ival; everything\n to the right of x[-1] is set to y[-1].\n\n Parameters\n ----------\n x : array_like\n y : array_like\n ival : float\n ival is the value given to the values to the left of x[0]. Default\n is 0.\n sorted : bool\n Default is False.\n side : {'left', 'right'}, optional\n Default is 'left'. Defines the shape of the intervals constituting the\n steps. 'right' correspond to [a, b) intervals and 'left' to (a, b].\n\n Examples\n --------\n >>> import numpy as np\n >>> from statsmodels.distributions.empirical_distribution import StepFunction\n >>>\n >>> x = np.arange(20)\n >>> y = np.arange(20)\n >>> f = StepFunction(x, y)\n >>>\n >>> print(f(3.2))\n 3.0\n >>> print(f([[3.2,4.5],[24,-3.1]]))\n [[ 3. 4.]\n [ 19. 0.]]\n >>> f2 = StepFunction(x, y, side='right')\n >>>\n >>> print(f(3.0))\n 2.0\n >>> print(f2(3.0))\n 3.0\n \"\"\"\n\n def __init__(self, x, y, ival=0., sorted=False, side='left'):\n\n if side.lower() not in ['right', 'left']:\n msg = \"side can take the values 'right' or 'left'\"\n raise ValueError(msg)\n self.side = side\n\n _x = np.asarray(x)\n _y = np.asarray(y)\n\n if _x.shape != _y.shape:\n msg = \"x and y do not have the same shape\"\n raise ValueError(msg)\n if len(_x.shape) != 1:\n msg = 'x and y must be 1-dimensional'\n raise ValueError(msg)\n\n self.x = np.r_[-np.inf, _x]\n self.y = np.r_[ival, _y]\n\n if not sorted:\n asort = np.argsort(self.x)\n self.x = np.take(self.x, asort, 0)\n self.y = np.take(self.y, asort, 0)\n self.n = self.x.shape[0]\n\n def __call__(self, time):\n\n tind = np.searchsorted(self.x, time, self.side) - 1\n return self.y[tind]\n\nclass ECDF(StepFunction):\n \"\"\"\n Return the Empirical CDF of an array as a step function.\n\n Parameters\n ----------\n x : array_like\n Observations\n side : {'left', 'right'}, optional\n Default is 'right'. Defines the shape of the intervals constituting the\n steps. 'right' correspond to [a, b) intervals and 'left' to (a, b].\n\n Returns\n -------\n Empirical CDF as a step function.\n\n Examples\n --------\n >>> import numpy as np\n >>> from statsmodels.distributions.empirical_distribution import ECDF\n >>>\n >>> ecdf = ECDF([3, 3, 1, 4])\n >>>\n >>> ecdf([3, 55, 0.5, 1.5])\n array([ 0.75, 1. , 0. , 0.25])\n \"\"\"\n def __init__(self, x, side='right'):\n x = np.array(x, copy=True)\n x.sort()\n nobs = len(x)\n y = np.linspace(1./nobs,1,nobs)\n super(ECDF, self).__init__(x, y, side=side, sorted=True)\n # TODO: make `step` an arg and have a linear interpolation option?\n # This is the path with `step` is True\n # If `step` is False, a previous version of the code read\n # `return interp1d(x,y,drop_errors=False,fill_values=ival)`\n # which would have raised a NameError if hit, so would need to be\n # fixed. See GH#5701.\n\n\ndef monotone_fn_inverter(fn, x, vectorized=True, **keywords):\n \"\"\"\n Given a monotone function fn (no checking is done to verify monotonicity)\n and a set of x values, return an linearly interpolated approximation\n to its inverse from its values on x.\n \"\"\"\n x = np.asarray(x)\n if vectorized:\n y = fn(x, **keywords)\n else:\n y = []\n for _x in x:\n y.append(fn(_x, **keywords))\n y = np.array(y)\n\n a = np.argsort(y)\n\n return interp1d(y[a], x[a])\n\nif __name__ == \"__main__\":\n #TODO: Make sure everything is correctly aligned and make a plotting\n # function\n from urllib.request import urlopen\n import matplotlib.pyplot as plt\n nerve_data = urlopen('http://www.statsci.org/data/general/nerve.txt')\n nerve_data = np.loadtxt(nerve_data)\n x = nerve_data / 50. # was in 1/50 seconds\n cdf = ECDF(x)\n x.sort()\n F = cdf(x)\n plt.step(x, F, where='post')\n lower, upper = _conf_set(F)\n plt.step(x, lower, 'r', where='post')\n plt.step(x, upper, 'r', where='post')\n plt.xlim(0, 1.5)\n plt.ylim(0, 1.05)\n plt.vlines(x, 0, .05)\n plt.show()\n",
"#!/usr/bin/env python\n\"\"\"\nAnalyze docstrings to detect errors.\n\nIf no argument is provided, it does a quick check of docstrings and returns\na csv with all API functions and results of basic checks.\n\nIf a function or method is provided in the form 'pandas.function',\n'pandas.module.class.method', etc. a list of all errors in the docstring for\nthe specified function or method.\n\nUsage::\n $ ./validate_docstrings.py\n $ ./validate_docstrings.py pandas.DataFrame.head\n\"\"\"\nimport argparse\nimport ast\nimport collections\nimport doctest\nimport functools\nimport glob\nimport importlib\nimport inspect\nfrom io import StringIO\nimport json\nimport os\nimport pydoc\nimport re\nimport string\nimport sys\nimport tempfile\nimport textwrap\n\nimport flake8.main.application\nimport matplotlib\nimport numpy\nfrom numpydoc.docscrape import NumpyDocString\nimport pandas\nfrom pandas.io.formats.printing import pprint_thing\n\nimport statsmodels.api\n\n# Template backend makes matplotlib to not plot anything. This is useful\n# to avoid that plot windows are open from the doctests while running the\n# script. Setting here before matplotlib is loaded.\n# We don't warn for the number of open plots, as none is actually being opened\nmatplotlib.use(\"agg\")\nmatplotlib.rc(\"figure\", max_open_warning=10000)\n\nBASE_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\nsys.path.insert(0, os.path.join(BASE_PATH))\n# TODO: Single-line ignore GL01, GL02\n# TODO: Complete import location list\n# TODO: Recurse through module to find classes\n# TODO: Separate data from code\nNO_RETURN_WHITELIST = {\n \"bse\",\n \"aic\",\n \"bic\",\n \"params\",\n \"tvalues\",\n \"pvalues\",\n \"fvalue\",\n \"fittedvalues\",\n \"mse_model\",\n \"mse_resid\",\n \"mse_total\",\n \"ssr\",\n \"nobs\",\n \"rsquared_adj\",\n \"rsquared\",\n \"resid\",\n \"prsquared\",\n \"zvalues\",\n \"uncentered_tss\",\n \"llf\",\n \"hqic\",\n \"ess\",\n \"centered_tss\",\n \"wresid\",\n \"f_pvalue\",\n \"eigenvals\",\n \"condition_number\",\n \"scale\",\n \"llr\",\n \"llr_pvalue\",\n \"llnull\",\n \"resid_response\",\n \"resid_pearson\",\n \"resid_generalized\",\n \"resid_dev\",\n \"save\",\n}\nMODULES = (\n \"api\",\n \"tsa.api\",\n \"discrete.conditional_models\",\n \"discrete.count_model\",\n \"discrete.discrete_model\",\n \"duration.hazard_regression\",\n \"regression.linear_model\",\n \"regression.mixed_linear_model\",\n \"regression.process_regression\",\n \"regression.quantile_regression\",\n \"regression.recursive_ls\",\n \"robust.robust_linear_model\",\n \"robust.norms\",\n \"stats.anova\",\n \"stats.mediation\",\n \"tsa.seasonal\",\n)\nALLOW_SINGLE_LINE_DOCSTRINGS = True\nmembers = []\nfor mod in MODULES:\n imp = importlib.import_module(\"statsmodels.\" + mod)\n members += inspect.getmembers(imp)\nAPI_CLASSES = []\nfor member in members:\n if not member[0]:\n continue\n if member[0][0] in string.ascii_uppercase:\n if not type(member[1]) is type:\n continue\n name = str(member[1]).split(\"'\")[1]\n if not name.startswith(\"statsmodels.\"):\n continue\n API_CLASSES.append((name, member[1]))\nAPI_CLASSES = sorted(set(API_CLASSES), key=lambda v: v[0])\nRUN_DOCTESTS = False\n\nsys.path.insert(1, os.path.join(BASE_PATH, \"doc\", \"sphinxext\"))\n\nPRIVATE_CLASSES = []\nDIRECTIVES = [\"versionadded\", \"versionchanged\", \"deprecated\"]\nALLOWED_SECTIONS = [\n \"Parameters\",\n \"Attributes\",\n \"Methods\",\n \"Returns\",\n \"Yields\",\n \"Other Parameters\",\n \"Raises\",\n \"Warns\",\n \"See Also\",\n \"Notes\",\n \"References\",\n \"Examples\",\n]\nERROR_MSGS = {\n \"GL01\": \"Docstring text (summary) should start in the line immediately \"\n \"after the opening quotes (not in the same line, or leaving a \"\n \"blank line in between)\",\n \"GL02\": \"Closing quotes should be placed in the line after the last text \"\n \"in the docstring (do not close the quotes in the same line as \"\n \"the text, or leave a blank line between the last text and the \"\n \"quotes)\",\n \"GL03\": \"Double line break found; please use only one blank line to \"\n \"separate sections or paragraphs, and do not leave blank lines \"\n \"at the end of docstrings\",\n \"GL04\": \"Private classes ({mentioned_private_classes}) should not be \"\n \"mentioned in public docstrings\",\n \"GL05\": 'Tabs found at the start of line \"{line_with_tabs}\", please use '\n \"whitespace only\",\n \"GL06\": 'Found unknown section \"{section}\". Allowed sections are: '\n \"{allowed_sections}\",\n \"GL07\": \"Sections are in the wrong order. \"\n \"Correct order is: {correct_sections}\",\n \"GL08\": \"The object does not have a docstring\",\n \"GL09\": \"Deprecation warning should precede extended summary\",\n \"SS01\": \"No summary found (a short summary in a single line should be \"\n \"present at the beginning of the docstring)\",\n \"SS02\": \"Summary does not start with a capital letter\",\n \"SS03\": \"Summary does not end with a period\",\n \"SS04\": \"Summary contains heading whitespaces\",\n \"SS05\": \"Summary must start with infinitive verb, not third person \"\n '(e.g. use \"Generate\" instead of \"Generates\")',\n \"SS06\": \"Summary should fit in a single line\",\n \"ES01\": \"No extended summary found\",\n \"PR01\": \"Parameters {missing_params} not documented\",\n \"PR02\": \"Unknown parameters {unknown_params}\",\n \"PR03\": \"Wrong parameters order. Actual: {actual_params}. \"\n \"Documented: {documented_params}\",\n \"PR04\": 'Parameter \"{param_name}\" has no type',\n \"PR05\": 'Parameter \"{param_name}\" type should not finish with \".\"',\n \"PR06\": 'Parameter \"{param_name}\" type should use \"{right_type}\" instead '\n 'of \"{wrong_type}\"',\n \"PR07\": 'Parameter \"{param_name}\" has no description',\n \"PR08\": 'Parameter \"{param_name}\" description should start with a '\n \"capital letter\",\n \"PR09\": 'Parameter \"{param_name}\" description should finish with \".\"',\n \"PR10\": 'Parameter \"{param_name}\" requires a space before the colon '\n \"separating the parameter name and type\",\n \"RT01\": \"No Returns section found\",\n \"RT02\": \"The first line of the Returns section should contain only the \"\n \"type, unless multiple values are being returned\",\n \"RT03\": \"Return value has no description\",\n \"RT04\": \"Return value description should start with a capital letter\",\n \"RT05\": 'Return value description should finish with \".\"',\n \"YD01\": \"No Yields section found\",\n \"SA01\": \"See Also section not found\",\n \"SA02\": \"Missing period at end of description for See Also \"\n '\"{reference_name}\" reference',\n \"SA03\": \"Description should be capitalized for See Also \"\n '\"{reference_name}\" reference',\n \"SA04\": 'Missing description for See Also \"{reference_name}\" reference',\n \"SA05\": \"{reference_name} in `See Also` section does not need `pandas` \"\n \"prefix, use {right_reference} instead.\",\n \"EX01\": \"No examples section found\",\n \"EX02\": \"Examples do not pass tests:\\n{doctest_log}\",\n \"EX03\": \"flake8 error: {error_code} {error_message}{times_happening}\",\n \"EX04\": \"Do not import {imported_library}, as it is imported \"\n \"automatically for the examples (numpy as np, pandas as pd)\",\n}\n\n\ndef error(code, **kwargs):\n \"\"\"\n Return a tuple with the error code and the message with variables replaced.\n\n This is syntactic sugar so instead of:\n - `('EX02', ERROR_MSGS['EX02'].format(doctest_log=log))`\n\n We can simply use:\n - `error('EX02', doctest_log=log)`\n\n Parameters\n ----------\n code : str\n Error code.\n **kwargs\n Values for the variables in the error messages\n\n Returns\n -------\n code : str\n Error code.\n message : str\n Error message with variables replaced.\n \"\"\"\n return (code, ERROR_MSGS[code].format(**kwargs))\n\n\ndef get_api_items(api_doc_fd):\n \"\"\"\n Yield information about all public API items.\n\n Parse api.rst file from the documentation, and extract all the functions,\n methods, classes, attributes... This should include all pandas public API.\n\n Parameters\n ----------\n api_doc_fd : file descriptor\n A file descriptor of the API documentation page, containing the table\n of contents with all the public API.\n\n Yields\n ------\n name : str\n The name of the object (e.g. 'pandas.Series.str.upper).\n func : function\n The object itself. In most cases this will be a function or method,\n but it can also be classes, properties, cython objects...\n section : str\n The name of the section in the API page where the object item is\n located.\n subsection : str\n The name of the subsection in the API page where the object item is\n located.\n \"\"\"\n current_module = \"statsmodels\"\n previous_line = current_section = current_subsection = \"\"\n position = None\n for line in api_doc_fd:\n line = line.strip()\n if len(line) == len(previous_line):\n if set(line) == set(\"-\"):\n current_section = previous_line\n continue\n if set(line) == set(\"~\"):\n current_subsection = previous_line\n continue\n\n if line.startswith(\".. currentmodule::\"):\n current_module = line.replace(\".. currentmodule::\", \"\").strip()\n continue\n\n if line == \".. autosummary::\":\n position = \"autosummary\"\n continue\n\n if position == \"autosummary\":\n if line == \"\":\n position = \"items\"\n continue\n\n if position == \"items\":\n if line == \"\":\n position = None\n continue\n item = line.strip()\n if item.startswith(\"~statsmodels.\"):\n path = item.replace(\"~\", \"\").split(\".\")\n item = path[-1]\n current_module = \".\".join(path[:-1])\n\n func = importlib.import_module(current_module)\n for part in item.split(\".\"):\n func = getattr(func, part)\n\n yield (\n \".\".join([current_module, item]),\n func,\n current_section,\n current_subsection,\n )\n\n previous_line = line\n\n\nclass Docstring:\n def __init__(self, name):\n self.name = name\n obj = self._load_obj(name)\n self.obj = obj\n self.code_obj = self._to_original_callable(obj)\n self.raw_doc = obj.__doc__ or \"\"\n self.clean_doc = pydoc.getdoc(obj)\n self.doc = NumpyDocString(self.clean_doc)\n\n def __len__(self):\n return len(self.raw_doc)\n\n @staticmethod\n def _load_obj(name):\n \"\"\"\n Import Python object from its name as string.\n\n Parameters\n ----------\n name : str\n Object name to import (e.g. pandas.Series.str.upper)\n\n Returns\n -------\n object\n Python object that can be a class, method, function...\n\n Examples\n --------\n >>> Docstring._load_obj('pandas.Series')\n <class 'pandas.core.series.Series'>\n \"\"\"\n for maxsplit in range(1, name.count(\".\") + 1):\n func_name_split = name.rsplit(\".\", maxsplit)\n module, *func_parts = func_name_split\n try:\n obj = importlib.import_module(module)\n except ImportError:\n pass\n else:\n continue\n\n if \"obj\" not in locals():\n raise ImportError(\n \"No module can be imported \" 'from \"{}\"'.format(name)\n )\n\n for part in func_parts:\n obj = getattr(obj, part)\n return obj\n\n @staticmethod\n def _to_original_callable(obj):\n \"\"\"\n Find the Python object that contains the source code of the object.\n\n This is useful to find the place in the source code (file and line\n number) where a docstring is defined. It does not currently work for\n all cases, but it should help find some (properties...).\n \"\"\"\n while True:\n if inspect.isfunction(obj) or inspect.isclass(obj):\n f = inspect.getfile(obj)\n if f.startswith(\"<\") and f.endswith(\">\"):\n return None\n return obj\n if inspect.ismethod(obj):\n obj = obj.__func__\n elif isinstance(obj, functools.partial):\n obj = obj.func\n elif isinstance(obj, property):\n obj = obj.fget\n else:\n return None\n\n @property\n def type(self):\n return type(self.obj).__name__\n\n @property\n def is_function_or_method(self):\n return inspect.isfunction(self.obj) or inspect.ismethod(self.obj)\n\n @property\n def source_file_name(self):\n \"\"\"\n File name where the object is implemented (e.g. pandas/core/frame.py).\n \"\"\"\n try:\n fname = inspect.getsourcefile(self.code_obj)\n except TypeError:\n # In some cases the object is something complex like a cython\n # object that can't be easily introspected. An it's better to\n # return the source code file of the object as None, than crash\n pass\n else:\n if fname:\n fname = os.path.relpath(fname, BASE_PATH)\n return fname\n\n @property\n def source_file_def_line(self):\n \"\"\"\n Number of line where the object is defined in its file.\n \"\"\"\n try:\n return inspect.getsourcelines(self.code_obj)[-1]\n except (OSError, TypeError):\n # In some cases the object is something complex like a cython\n # object that can't be easily introspected. An it's better to\n # return the line number as None, than crash\n pass\n\n @property\n def github_url(self):\n url = \"https://github.com/statsmodels/statsmodels/main/\"\n url += \"{}#L{}\".format(\n self.source_file_name, self.source_file_def_line\n )\n return url\n\n @property\n def start_blank_lines(self):\n i = None\n if self.raw_doc:\n for i, row in enumerate(self.raw_doc.split(\"\\n\")):\n if row.strip():\n break\n return i\n\n @property\n def end_blank_lines(self):\n i = None\n if self.raw_doc:\n for i, row in enumerate(reversed(self.raw_doc.split(\"\\n\"))):\n if row.strip():\n break\n return i\n\n @property\n def single_line_docstring(self):\n return (\n self.raw_doc\n and \"\\n\" not in self.raw_doc\n and ALLOW_SINGLE_LINE_DOCSTRINGS\n )\n\n @property\n def double_blank_lines(self):\n prev = True\n for row in self.raw_doc.split(\"\\n\"):\n if not prev and not row.strip():\n return True\n prev = row.strip()\n return False\n\n @property\n def section_titles(self):\n sections = []\n self.doc._doc.reset()\n while not self.doc._doc.eof():\n content = self.doc._read_to_next_section()\n if (\n len(content) > 1\n and len(content[0]) == len(content[1])\n and set(content[1]) == {\"-\"}\n ):\n sections.append(content[0])\n return sections\n\n @property\n def summary(self):\n return \" \".join(self.doc[\"Summary\"])\n\n @property\n def num_summary_lines(self):\n return len(self.doc[\"Summary\"])\n\n @property\n def extended_summary(self):\n if not self.doc[\"Extended Summary\"] and len(self.doc[\"Summary\"]) > 1:\n return \" \".join(self.doc[\"Summary\"])\n return \" \".join(self.doc[\"Extended Summary\"])\n\n @property\n def needs_summary(self):\n return not (bool(self.summary) and bool(self.extended_summary))\n\n @property\n def doc_parameters(self):\n return collections.OrderedDict(\n (name, (type_, \"\".join(desc)))\n for name, type_, desc in self.doc[\"Parameters\"]\n )\n\n @property\n def signature_parameters(self):\n if inspect.isclass(self.obj):\n if hasattr(self.obj, \"_accessors\") and (\n self.name.split(\".\")[-1] in self.obj._accessors\n ):\n # accessor classes have a signature but don't want to show this\n return ()\n try:\n sig = inspect.signature(self.obj)\n except (TypeError, ValueError):\n # Some objects, mainly in C extensions do not support introspection\n # of the signature\n try:\n from numpydoc.docscrape import FunctionDoc\n\n doc = FunctionDoc(self.obj)\n if \"Signature\" in doc:\n sig = doc[\"Signature\"].split(\"(\")[-1].split(\")\")[0]\n sig = sig.split(\",\")\n params = []\n for param in sig:\n if param.strip() in (\"*\", \"/\"):\n continue\n param = param.split(\"=\")[0]\n params.append(param)\n return tuple([param.name for param in doc[\"Parameters\"]])\n except Exception as exc:\n print(\"!! numpydoc failed on {0}!!\".format(str(self.obj)))\n print(exc)\n return ()\n params = list(sig.parameters.keys())\n out_params = params[:]\n kind = inspect.Parameter.VAR_POSITIONAL\n varargs = [key for key in params if sig.parameters[key].kind == kind]\n if varargs:\n out_params = [\n \"*\" + param if param == varargs[0] else param\n for param in out_params\n ]\n\n kind = inspect.Parameter.VAR_KEYWORD\n varkw = [key for key in params if sig.parameters[key].kind == kind]\n if varkw:\n out_params = [\n \"**\" + param if param == varkw[0] else param\n for param in out_params\n ]\n\n params = tuple(out_params)\n if params and params[0] in (\"self\", \"cls\"):\n return params[1:]\n return params\n\n @property\n def parameter_mismatches(self):\n errs = []\n signature_params = self.signature_parameters\n doc_params = tuple(self.doc_parameters)\n missing = set(signature_params) - set(doc_params)\n if missing:\n errs.append(error(\"PR01\", missing_params=pprint_thing(missing)))\n extra = set(doc_params) - set(signature_params)\n if extra:\n errs.append(error(\"PR02\", unknown_params=pprint_thing(extra)))\n if (\n not missing\n and not extra\n and signature_params != doc_params\n and not (not signature_params and not doc_params)\n ):\n errs.append(\n error(\n \"PR03\",\n actual_params=signature_params,\n documented_params=doc_params,\n )\n )\n\n return errs\n\n @property\n def correct_parameters(self):\n return not bool(self.parameter_mismatches)\n\n def parameter_type(self, param):\n return self.doc_parameters[param][0]\n\n def parameter_desc(self, param):\n desc = self.doc_parameters[param][1]\n # Find and strip out any sphinx directives\n for directive in DIRECTIVES:\n full_directive = \".. {}\".format(directive)\n if full_directive in desc:\n # Only retain any description before the directive\n desc = desc[: desc.index(full_directive)]\n return desc\n\n @property\n def see_also(self):\n result = collections.OrderedDict()\n for funcs, desc in self.doc[\"See Also\"]:\n for func, _ in funcs:\n result[func] = \"\".join(desc)\n\n return result\n\n @property\n def examples(self):\n return self.doc[\"Examples\"]\n\n @property\n def returns(self):\n return self.doc[\"Returns\"]\n\n @property\n def yields(self):\n return self.doc[\"Yields\"]\n\n @property\n def method_source(self):\n try:\n source = inspect.getsource(self.obj)\n except TypeError:\n return \"\"\n return textwrap.dedent(source)\n\n @property\n def method_returns_something(self):\n \"\"\"\n Check if the docstrings method can return something.\n\n Bare returns, returns valued None and returns from nested functions are\n disconsidered.\n\n Returns\n -------\n bool\n Whether the docstrings method can return something.\n \"\"\"\n\n def get_returns_not_on_nested_functions(node):\n returns = [node] if isinstance(node, ast.Return) else []\n for child in ast.iter_child_nodes(node):\n # Ignore nested functions and its subtrees.\n if not isinstance(child, ast.FunctionDef):\n child_returns = get_returns_not_on_nested_functions(child)\n returns.extend(child_returns)\n return returns\n\n tree = ast.parse(self.method_source).body\n if tree:\n returns = get_returns_not_on_nested_functions(tree[0])\n return_values = [r.value for r in returns]\n # Replace NameConstant nodes valued None for None.\n for i, v in enumerate(return_values):\n if isinstance(v, ast.NameConstant) and v.value is None:\n return_values[i] = None\n return any(return_values)\n else:\n return False\n\n @property\n def no_return_whitelisted(self):\n method = self.name.split(\".\")[-1]\n return \"Results\" in self.name and method in NO_RETURN_WHITELIST\n\n @property\n def first_line_ends_in_dot(self):\n if self.doc:\n return self.doc.split(\"\\n\")[0][-1] == \".\"\n\n @property\n def deprecated(self):\n return \".. deprecated:: \" in (self.summary + self.extended_summary)\n\n @property\n def mentioned_private_classes(self):\n return [klass for klass in PRIVATE_CLASSES if klass in self.raw_doc]\n\n @property\n def examples_errors(self):\n flags = doctest.NORMALIZE_WHITESPACE | doctest.IGNORE_EXCEPTION_DETAIL\n finder = doctest.DocTestFinder()\n runner = doctest.DocTestRunner(optionflags=flags)\n context = {\"np\": numpy, \"pd\": pandas, \"sm\": statsmodels.api}\n error_msgs = \"\"\n for test in finder.find(self.raw_doc, self.name, globs=context):\n f = StringIO()\n runner.run(test, out=f.write)\n error_msgs += f.getvalue()\n return error_msgs\n\n @property\n def examples_source_code(self):\n lines = doctest.DocTestParser().get_examples(self.raw_doc)\n return [line.source for line in lines]\n\n def validate_pep8(self):\n if not self.examples:\n return\n\n # F401 is needed to not generate flake8 errors in examples\n # that do not user numpy or pandas\n content = \"\".join(\n (\n \"import numpy as np # noqa: F401\\n\",\n \"import pandas as pd # noqa: F401\\n\",\n \"import statsmodels.api as sm # noqa: F401\\n\",\n *self.examples_source_code,\n )\n )\n\n application = flake8.main.application.Application()\n application.initialize([\"--quiet\"])\n\n with tempfile.NamedTemporaryFile(mode=\"w\", encoding=\"utf-8\") as file:\n file.write(content)\n file.flush()\n application.run_checks([file.name])\n\n # We need this to avoid flake8 printing the names of the files to\n # the standard output\n application.formatter.write = lambda line, source: None\n application.report()\n\n yield from application.guide.stats.statistics_for(\"\")\n\n\ndef get_validation_data(doc):\n \"\"\"\n Validate the docstring.\n\n Parameters\n ----------\n doc : Docstring\n A Docstring object with the given function name.\n\n Returns\n -------\n tuple\n errors : list of tuple\n Errors occurred during validation.\n warnings : list of tuple\n Warnings occurred during validation.\n examples_errs : str\n Examples usage displayed along the error, otherwise empty string.\n\n Notes\n -----\n The errors codes are defined as:\n - First two characters: Section where the error happens:\n * GL: Global (no section, like section ordering errors)\n * SS: Short summary\n * ES: Extended summary\n * PR: Parameters\n * RT: Returns\n * YD: Yields\n * RS: Raises\n * WN: Warns\n * SA: See Also\n * NT: Notes\n * RF: References\n * EX: Examples\n - Last two characters: Numeric error code inside the section\n\n For example, EX02 is the second codified error in the Examples section\n (which in this case is assigned to examples that do not pass the tests).\n\n The error codes, their corresponding error messages, and the details on how\n they are validated, are not documented more than in the source code of this\n function.\n \"\"\"\n\n errs = []\n wrns = []\n if not doc.raw_doc:\n errs.append(error(\"GL08\"))\n return errs, wrns, \"\"\n\n if doc.start_blank_lines != 1 and not doc.single_line_docstring:\n errs.append(error(\"GL01\"))\n if doc.end_blank_lines != 1 and not doc.single_line_docstring:\n errs.append(error(\"GL02\"))\n if doc.double_blank_lines:\n errs.append(error(\"GL03\"))\n mentioned_errs = doc.mentioned_private_classes\n if mentioned_errs:\n errs.append(\n error(\"GL04\", mentioned_private_classes=\", \".join(mentioned_errs))\n )\n for line in doc.raw_doc.splitlines():\n if re.match(\"^ *\\t\", line):\n errs.append(error(\"GL05\", line_with_tabs=line.lstrip()))\n\n unexpected_sections = [\n section\n for section in doc.section_titles\n if section not in ALLOWED_SECTIONS\n ]\n for section in unexpected_sections:\n errs.append(\n error(\n \"GL06\",\n section=section,\n allowed_sections=\", \".join(ALLOWED_SECTIONS),\n )\n )\n\n correct_order = [\n section\n for section in ALLOWED_SECTIONS\n if section in doc.section_titles\n ]\n if correct_order != doc.section_titles:\n errs.append(error(\"GL07\", correct_sections=\", \".join(correct_order)))\n\n if doc.deprecated and not doc.extended_summary.startswith(\n \".. deprecated:: \"\n ):\n errs.append(error(\"GL09\"))\n\n if not doc.summary:\n errs.append(error(\"SS01\"))\n else:\n if not doc.summary[0].isupper():\n errs.append(error(\"SS02\"))\n if (\n doc.summary[-1] != \".\"\n and not doc.single_line_docstring\n and ALLOW_SINGLE_LINE_DOCSTRINGS\n ):\n errs.append(error(\"SS03\"))\n if doc.summary != doc.summary.lstrip():\n errs.append(error(\"SS04\"))\n elif (\n doc.is_function_or_method and doc.summary.split(\" \")[0][-1] == \"s\"\n ):\n errs.append(error(\"SS05\"))\n if doc.num_summary_lines > 1:\n errs.append(error(\"SS06\"))\n\n if not doc.extended_summary:\n wrns.append((\"ES01\", \"No extended summary found\"))\n\n # PR01: Parameters not documented\n # PR02: Unknown parameters\n # PR03: Wrong parameters order\n errs += doc.parameter_mismatches\n\n for param in doc.doc_parameters:\n if not param.startswith(\"*\"): # Check can ignore var / kwargs\n if not doc.parameter_type(param):\n if \":\" in param:\n errs.append(error(\"PR10\", param_name=param.split(\":\")[0]))\n else:\n errs.append(error(\"PR04\", param_name=param))\n else:\n if doc.parameter_type(param)[-1] == \".\":\n errs.append(error(\"PR05\", param_name=param))\n common_type_errors = [\n (\"integer\", \"int\"),\n (\"boolean\", \"bool\"),\n (\"string\", \"str\"),\n ]\n for wrong_type, right_type in common_type_errors:\n if wrong_type in doc.parameter_type(param):\n errs.append(\n error(\n \"PR06\",\n param_name=param,\n right_type=right_type,\n wrong_type=wrong_type,\n )\n )\n if not doc.parameter_desc(param):\n errs.append(error(\"PR07\", param_name=param))\n else:\n if not doc.parameter_desc(param)[0].isupper():\n errs.append(error(\"PR08\", param_name=param))\n if doc.parameter_desc(param)[-1] != \".\":\n errs.append(error(\"PR09\", param_name=param))\n\n if doc.is_function_or_method:\n if not doc.returns:\n if doc.method_returns_something and not doc.no_return_whitelisted:\n errs.append(error(\"RT01\"))\n else:\n if len(doc.returns) == 1 and doc.returns[0].name:\n errs.append(error(\"RT02\"))\n for name_or_type, type_, desc in doc.returns:\n if not desc:\n errs.append(error(\"RT03\"))\n else:\n desc = \" \".join(desc)\n if not desc[0].isupper():\n errs.append(error(\"RT04\"))\n if not desc.endswith(\".\"):\n errs.append(error(\"RT05\"))\n\n if not doc.yields and \"yield\" in doc.method_source:\n errs.append(error(\"YD01\"))\n\n if not doc.see_also:\n wrns.append(error(\"SA01\"))\n else:\n for rel_name, rel_desc in doc.see_also.items():\n if rel_desc:\n if not rel_desc.endswith(\".\"):\n errs.append(error(\"SA02\", reference_name=rel_name))\n if not rel_desc[0].isupper():\n errs.append(error(\"SA03\", reference_name=rel_name))\n else:\n errs.append(error(\"SA04\", reference_name=rel_name))\n # TODO: Change to statsmodels\n if rel_name.startswith(\"pandas.\"):\n errs.append(\n error(\n \"SA05\",\n reference_name=rel_name,\n right_reference=rel_name[len(\"pandas.\") :],\n )\n )\n\n examples_errs = \"\"\n if not doc.examples:\n wrns.append(error(\"EX01\"))\n elif RUN_DOCTESTS:\n examples_errs = doc.examples_errors\n if examples_errs:\n errs.append(error(\"EX02\", doctest_log=examples_errs))\n for err in doc.validate_pep8():\n errs.append(\n error(\n \"EX03\",\n error_code=err.error_code,\n error_message=err.message,\n times_happening=\" ({} times)\".format(err.count)\n if err.count > 1\n else \"\",\n )\n )\n examples_source_code = \"\".join(doc.examples_source_code)\n for wrong_import in (\"numpy\", \"pandas\"):\n if \"import {}\".format(wrong_import) in examples_source_code:\n errs.append(error(\"EX04\", imported_library=wrong_import))\n return errs, wrns, examples_errs\n\n\ndef validate_one(func_name):\n \"\"\"\n Validate the docstring for the given func_name\n\n Parameters\n ----------\n func_name : function\n Function whose docstring will be evaluated (e.g. pandas.read_csv).\n\n Returns\n -------\n dict\n A dictionary containing all the information obtained from validating\n the docstring.\n \"\"\"\n doc = Docstring(func_name)\n errs, wrns, examples_errs = get_validation_data(doc)\n return {\n \"type\": doc.type,\n \"docstring\": doc.clean_doc,\n \"deprecated\": doc.deprecated,\n \"file\": doc.source_file_name,\n \"file_line\": doc.source_file_def_line,\n \"github_link\": doc.github_url,\n \"errors\": errs,\n \"warnings\": wrns,\n \"examples_errors\": examples_errs,\n }\n\n\ndef validate_all(prefix, ignore_deprecated=False):\n \"\"\"\n Execute the validation of all docstrings, and return a dict with the\n results.\n\n Parameters\n ----------\n prefix : str or None\n If provided, only the docstrings that start with this pattern will be\n validated. If None, all docstrings will be validated.\n ignore_deprecated: bool, default False\n If True, deprecated objects are ignored when validating docstrings.\n\n Returns\n -------\n dict\n A dictionary with an item for every function/method... containing\n all the validation information.\n \"\"\"\n result = {}\n seen = {}\n\n # functions from the API docs\n api_doc_fnames = os.path.join(BASE_PATH, \"docs\", \"source\", \"*.rst\")\n api_items = []\n for api_doc_fname in glob.glob(api_doc_fnames):\n if \"sandbox\" in api_doc_fname:\n continue\n with open(api_doc_fname, encoding=\"utf8\") as f:\n api_items += list(get_api_items(f))\n for func_name, func_obj, section, subsection in api_items:\n if prefix and not func_name.startswith(prefix):\n continue\n doc_info = validate_one(func_name)\n if ignore_deprecated and doc_info[\"deprecated\"]:\n continue\n result[func_name] = doc_info\n\n shared_code_key = doc_info[\"file\"], doc_info[\"file_line\"]\n shared_code = seen.get(shared_code_key, \"\")\n result[func_name].update(\n {\n \"in_api\": True,\n \"section\": section,\n \"subsection\": subsection,\n \"shared_code_with\": shared_code,\n }\n )\n\n seen[shared_code_key] = func_name\n # functions from introspecting Series and DataFrame\n api_item_names = set(list(zip(*api_items))[0])\n for class_name, class_ in API_CLASSES:\n for member in inspect.getmembers(class_):\n func_name = class_name + \".\" + member[0]\n if (\n not member[0].startswith(\"_\")\n and func_name not in api_item_names\n ):\n if prefix and not func_name.startswith(prefix):\n continue\n doc_info = validate_one(func_name)\n if ignore_deprecated and doc_info[\"deprecated\"]:\n continue\n result[func_name] = doc_info\n result[func_name][\"in_api\"] = False\n\n return result\n\n\ndef main(func_name, prefix, errors, output_format, ignore_deprecated):\n def header(title, width=80, char=\"#\"):\n full_line = char * width\n side_len = (width - len(title) - 2) // 2\n adj = \"\" if len(title) % 2 == 0 else \" \"\n title_line = \"{side} {title}{adj} {side}\".format(\n side=char * side_len, title=title, adj=adj\n )\n\n return \"\\n{full_line}\\n{title_line}\\n{full_line}\\n\\n\".format(\n full_line=full_line, title_line=title_line\n )\n\n exit_status = 0\n if func_name is None:\n result = validate_all(prefix, ignore_deprecated)\n\n if output_format == \"json\":\n output = json.dumps(result)\n else:\n if output_format == \"default\":\n output_format = \"{text}\\n\"\n elif output_format == \"azure\":\n output_format = (\n \"##vso[task.logissue type=error;\"\n \"sourcepath={path};\"\n \"linenumber={row};\"\n \"code={code};\"\n \"]{text}\\n\"\n )\n else:\n raise ValueError(\n 'Unknown output_format \"{}\"'.format(output_format)\n )\n\n output = []\n for name, res in result.items():\n for err_code, err_desc in res[\"errors\"]:\n # The script would be faster if instead of filtering the\n # errors after validating them, it didn't validate them\n # initially. But that would complicate the code too much\n if errors and err_code not in errors:\n continue\n exit_status += 1\n output.append(\n output_format.format(\n name=name,\n path=res[\"file\"],\n row=res[\"file_line\"],\n code=err_code,\n text=\"{}: {}\".format(name, err_desc),\n )\n )\n output = \"\".join(sorted(output))\n sys.stdout.write(output)\n\n else:\n result = validate_one(func_name)\n sys.stderr.write(header(\"Docstring ({})\".format(func_name)))\n sys.stderr.write(\"{}\\n\".format(result[\"docstring\"]))\n sys.stderr.write(header(\"Validation\"))\n if result[\"errors\"]:\n sys.stderr.write(\n \"{} Errors found:\\n\".format(len(result[\"errors\"]))\n )\n for err_code, err_desc in result[\"errors\"]:\n # Failing examples are printed at the end\n if err_code == \"EX02\":\n sys.stderr.write(\"\\tExamples do not pass tests\\n\")\n continue\n sys.stderr.write(\"\\t{}\\n\".format(err_desc))\n if result[\"warnings\"]:\n sys.stderr.write(\n \"{} Warnings found:\\n\".format(len(result[\"warnings\"]))\n )\n for wrn_code, wrn_desc in result[\"warnings\"]:\n sys.stderr.write(\"\\t{}\\n\".format(wrn_desc))\n\n if not result[\"errors\"]:\n sys.stderr.write(\n 'Docstring for \"{}\" correct. :)\\n'.format(func_name)\n )\n\n if result[\"examples_errors\"]:\n sys.stderr.write(header(\"Doctests\"))\n sys.stderr.write(result[\"examples_errors\"])\n\n return exit_status\n\n\nif __name__ == \"__main__\":\n format_opts = \"default\", \"json\", \"azure\"\n func_help = (\n \"function or method to validate (e.g. pandas.DataFrame.head) \"\n \"if not provided, all docstrings are validated and returned \"\n \"as JSON\"\n )\n argparser = argparse.ArgumentParser(\n description=\"validate pandas docstrings\"\n )\n argparser.add_argument(\"function\", nargs=\"?\", default=None, help=func_help)\n argparser.add_argument(\n \"--format\",\n default=\"default\",\n choices=format_opts,\n help=\"format of the output when validating \"\n \"multiple docstrings (ignored when validating one).\"\n \"It can be {}\".format(str(format_opts)[1:-1]),\n )\n argparser.add_argument(\n \"--prefix\",\n default=None,\n help=\"pattern for the \"\n \"docstring names, in order to decide which ones \"\n 'will be validated. A prefix \"pandas.Series.str.\"'\n \"will make the script validate all the docstrings\"\n \"of methods starting by this pattern. It is \"\n \"ignored if parameter function is provided\",\n )\n argparser.add_argument(\n \"--errors\",\n default=None,\n help=\"comma separated \"\n \"list of error codes to validate. By default it \"\n \"validates all errors (ignored when validating \"\n \"a single docstring)\",\n )\n argparser.add_argument(\n \"--ignore_deprecated\",\n default=False,\n action=\"store_true\",\n help=\"if this flag is set, \"\n \"deprecated objects are ignored when validating \"\n \"all docstrings\",\n )\n\n args = argparser.parse_args()\n sys.exit(\n main(\n args.function,\n args.prefix,\n args.errors.split(\",\") if args.errors else None,\n args.format,\n args.ignore_deprecated,\n )\n )\n",
"# -*- coding: utf-8 -*-\n# some cut and paste characters are not ASCII\n'''density estimation based on orthogonal polynomials\n\n\nAuthor: Josef Perktold\nCreated: 2011-05017\nLicense: BSD\n\n2 versions work: based on Fourier, FPoly, and chebychev T, ChebyTPoly\nalso hermite polynomials, HPoly, works\nother versions need normalization\n\n\nTODO:\n\n* check fourier case again: base is orthonormal,\n but needs offsetfact = 0 and does not integrate to 1, rescaled looks good\n* hermite: works but DensityOrthoPoly requires currently finite bounds\n I use it with offsettfactor 0.5 in example\n* not implemented methods:\n - add bonafide density correction\n - add transformation to domain of polynomial base - DONE\n possible problem: what is the behavior at the boundary,\n offsetfact requires more work, check different cases, add as option\n moved to polynomial class by default, as attribute\n* convert examples to test cases\n* need examples with large density on boundary, beta ?\n* organize poly classes in separate module, check new numpy.polynomials,\n polyvander\n* MISE measures, order selection, ...\n\nenhancements:\n * other polynomial bases: especially for open and half open support\n * wavelets\n * local or piecewise approximations\n\n\n'''\nfrom scipy import stats, integrate, special\n\nimport numpy as np\n\n\nsqr2 = np.sqrt(2.)\n\nclass FPoly:\n '''Orthonormal (for weight=1) Fourier Polynomial on [0,1]\n\n orthonormal polynomial but density needs corfactor that I do not see what\n it is analytically\n\n parameterization on [0,1] from\n\n Sam Efromovich: Orthogonal series density estimation,\n 2010 John Wiley & Sons, Inc. WIREs Comp Stat 2010 2 467-476\n\n\n '''\n\n def __init__(self, order):\n self.order = order\n self.domain = (0, 1)\n self.intdomain = self.domain\n\n def __call__(self, x):\n if self.order == 0:\n return np.ones_like(x)\n else:\n return sqr2 * np.cos(np.pi * self.order * x)\n\nclass F2Poly:\n '''Orthogonal (for weight=1) Fourier Polynomial on [0,pi]\n\n is orthogonal but first component does not square-integrate to 1\n final result seems to need a correction factor of sqrt(pi)\n _corfactor = sqrt(pi) from integrating the density\n\n Parameterization on [0, pi] from\n\n Peter Hall, Cross-Validation and the Smoothing of Orthogonal Series Density\n Estimators, JOURNAL OF MULTIVARIATE ANALYSIS 21, 189-206 (1987)\n\n '''\n\n def __init__(self, order):\n self.order = order\n self.domain = (0, np.pi)\n self.intdomain = self.domain\n self.offsetfactor = 0\n\n def __call__(self, x):\n if self.order == 0:\n return np.ones_like(x) / np.sqrt(np.pi)\n else:\n return sqr2 * np.cos(self.order * x) / np.sqrt(np.pi)\n\nclass ChebyTPoly:\n '''Orthonormal (for weight=1) Chebychev Polynomial on (-1,1)\n\n\n Notes\n -----\n integration requires to stay away from boundary, offsetfactor > 0\n maybe this implies that we cannot use it for densities that are > 0 at\n boundary ???\n\n or maybe there is a mistake close to the boundary, sometimes integration works.\n\n '''\n\n def __init__(self, order):\n self.order = order\n from scipy.special import chebyt\n self.poly = chebyt(order)\n self.domain = (-1, 1)\n self.intdomain = (-1+1e-6, 1-1e-6)\n #not sure if I need this, in integration nans are possible on the boundary\n self.offsetfactor = 0.01 #required for integration\n\n\n def __call__(self, x):\n if self.order == 0:\n return np.ones_like(x) / (1-x**2)**(1/4.) /np.sqrt(np.pi)\n\n else:\n return self.poly(x) / (1-x**2)**(1/4.) /np.sqrt(np.pi) *np.sqrt(2)\n\n\nlogpi2 = np.log(np.pi)/2\n\nclass HPoly:\n '''Orthonormal (for weight=1) Hermite Polynomial, uses finite bounds\n\n for current use with DensityOrthoPoly domain is defined as [-6,6]\n\n '''\n def __init__(self, order):\n self.order = order\n from scipy.special import hermite\n self.poly = hermite(order)\n self.domain = (-6, +6)\n self.offsetfactor = 0.5 # note this is\n\n def __call__(self, x):\n k = self.order\n\n lnfact = -(1./2)*(k*np.log(2.) + special.gammaln(k+1) + logpi2) - x*x/2\n fact = np.exp(lnfact)\n\n return self.poly(x) * fact\n\ndef polyvander(x, polybase, order=5):\n polyarr = np.column_stack([polybase(i)(x) for i in range(order)])\n return polyarr\n\ndef inner_cont(polys, lower, upper, weight=None):\n '''inner product of continuous function (with weight=1)\n\n Parameters\n ----------\n polys : list of callables\n polynomial instances\n lower : float\n lower integration limit\n upper : float\n upper integration limit\n weight : callable or None\n weighting function\n\n Returns\n -------\n innp : ndarray\n symmetric 2d square array with innerproduct of all function pairs\n err : ndarray\n numerical error estimate from scipy.integrate.quad, same dimension as innp\n\n Examples\n --------\n >>> from scipy.special import chebyt\n >>> polys = [chebyt(i) for i in range(4)]\n >>> r, e = inner_cont(polys, -1, 1)\n >>> r\n array([[ 2. , 0. , -0.66666667, 0. ],\n [ 0. , 0.66666667, 0. , -0.4 ],\n [-0.66666667, 0. , 0.93333333, 0. ],\n [ 0. , -0.4 , 0. , 0.97142857]])\n\n '''\n n_polys = len(polys)\n innerprod = np.empty((n_polys, n_polys))\n innerprod.fill(np.nan)\n interr = np.zeros((n_polys, n_polys))\n\n for i in range(n_polys):\n for j in range(i+1):\n p1 = polys[i]\n p2 = polys[j]\n if weight is not None:\n innp, err = integrate.quad(lambda x: p1(x)*p2(x)*weight(x),\n lower, upper)\n else:\n innp, err = integrate.quad(lambda x: p1(x)*p2(x), lower, upper)\n innerprod[i,j] = innp\n interr[i,j] = err\n if not i == j:\n innerprod[j,i] = innp\n interr[j,i] = err\n\n return innerprod, interr\n\n\ndef is_orthonormal_cont(polys, lower, upper, rtol=0, atol=1e-08):\n '''check whether functions are orthonormal\n\n Parameters\n ----------\n polys : list of polynomials or function\n\n Returns\n -------\n is_orthonormal : bool\n is False if the innerproducts are not close to 0 or 1\n\n Notes\n -----\n this stops as soon as the first deviation from orthonormality is found.\n\n Examples\n --------\n >>> from scipy.special import chebyt\n >>> polys = [chebyt(i) for i in range(4)]\n >>> r, e = inner_cont(polys, -1, 1)\n >>> r\n array([[ 2. , 0. , -0.66666667, 0. ],\n [ 0. , 0.66666667, 0. , -0.4 ],\n [-0.66666667, 0. , 0.93333333, 0. ],\n [ 0. , -0.4 , 0. , 0.97142857]])\n >>> is_orthonormal_cont(polys, -1, 1, atol=1e-6)\n False\n\n >>> polys = [ChebyTPoly(i) for i in range(4)]\n >>> r, e = inner_cont(polys, -1, 1)\n >>> r\n array([[ 1.00000000e+00, 0.00000000e+00, -9.31270888e-14,\n 0.00000000e+00],\n [ 0.00000000e+00, 1.00000000e+00, 0.00000000e+00,\n -9.47850712e-15],\n [ -9.31270888e-14, 0.00000000e+00, 1.00000000e+00,\n 0.00000000e+00],\n [ 0.00000000e+00, -9.47850712e-15, 0.00000000e+00,\n 1.00000000e+00]])\n >>> is_orthonormal_cont(polys, -1, 1, atol=1e-6)\n True\n\n '''\n for i in range(len(polys)):\n for j in range(i+1):\n p1 = polys[i]\n p2 = polys[j]\n innerprod = integrate.quad(lambda x: p1(x)*p2(x), lower, upper)[0]\n #print i,j, innerprod\n if not np.allclose(innerprod, i==j, rtol=rtol, atol=atol):\n return False\n return True\n\n\n\n#new versions\n\n\nclass DensityOrthoPoly:\n '''Univariate density estimation by orthonormal series expansion\n\n\n Uses an orthonormal polynomial basis to approximate a univariate density.\n\n\n currently all arguments can be given to fit, I might change it to requiring\n arguments in __init__ instead.\n '''\n\n def __init__(self, polybase=None, order=5):\n if polybase is not None:\n self.polybase = polybase\n self.polys = polys = [polybase(i) for i in range(order)]\n #try:\n #self.offsetfac = 0.05\n #self.offsetfac = polys[0].offsetfactor #polys maybe not defined yet\n self._corfactor = 1\n self._corshift = 0\n\n\n def fit(self, x, polybase=None, order=5, limits=None):\n '''estimate the orthogonal polynomial approximation to the density\n\n '''\n if polybase is None:\n polys = self.polys[:order]\n else:\n self.polybase = polybase\n self.polys = polys = [polybase(i) for i in range(order)]\n\n #move to init ?\n if not hasattr(self, 'offsetfac'):\n self.offsetfac = polys[0].offsetfactor\n\n\n xmin, xmax = x.min(), x.max()\n if limits is None:\n self.offset = offset = (xmax - xmin) * self.offsetfac\n limits = self.limits = (xmin - offset, xmax + offset)\n\n interval_length = limits[1] - limits[0]\n xinterval = xmax - xmin\n # need to cover (half-)open intervalls\n self.shrink = 1. / interval_length #xinterval/interval_length\n offset = (interval_length - xinterval ) / 2.\n self.shift = xmin - offset\n\n self.x = x = self._transform(x)\n\n coeffs = [(p(x)).mean() for p in polys]\n self.coeffs = coeffs\n self.polys = polys\n self._verify() #verify that it is a proper density\n\n return self #coeffs, polys\n\n def evaluate(self, xeval, order=None):\n xeval = self._transform(xeval)\n if order is None:\n order = len(self.polys)\n res = sum(c*p(xeval) for c, p in list(zip(self.coeffs, self.polys))[:order])\n res = self._correction(res)\n return res\n\n def __call__(self, xeval):\n '''alias for evaluate, except no order argument'''\n return self.evaluate(xeval)\n\n def _verify(self):\n '''check for bona fide density correction\n\n currently only checks that density integrates to 1\n\n` non-negativity - NotImplementedYet\n '''\n #watch out for circular/recursive usage\n\n #evaluate uses domain of data, we stay offset away from bounds\n intdomain = self.limits #self.polys[0].intdomain\n self._corfactor = 1./integrate.quad(self.evaluate, *intdomain)[0]\n #self._corshift = 0\n #self._corfactor\n return self._corfactor\n\n\n\n def _correction(self, x):\n '''bona fide density correction\n\n affine shift of density to make it into a proper density\n\n '''\n if self._corfactor != 1:\n x *= self._corfactor\n\n if self._corshift != 0:\n x += self._corshift\n\n return x\n\n def _transform(self, x): # limits=None):\n '''transform observation to the domain of the density\n\n\n uses shrink and shift attribute which are set in fit to stay\n\n\n '''\n\n #use domain from first instance\n #class does not have domain self.polybase.domain[0] AttributeError\n domain = self.polys[0].domain\n\n ilen = (domain[1] - domain[0])\n shift = self.shift - domain[0]/self.shrink/ilen\n shrink = self.shrink * ilen\n\n return (x - shift) * shrink\n\n\n#old version as a simple function\ndef density_orthopoly(x, polybase, order=5, xeval=None):\n #polybase = legendre #chebyt #hermitenorm#\n #polybase = chebyt\n #polybase = FPoly\n #polybase = ChtPoly\n #polybase = hermite\n #polybase = HPoly\n\n if xeval is None:\n xeval = np.linspace(x.min(),x.max(),50)\n\n #polys = [legendre(i) for i in range(order)]\n polys = [polybase(i) for i in range(order)]\n #coeffs = [(p(x)*(1-x**2)**(-1/2.)).mean() for p in polys]\n #coeffs = [(p(x)*np.exp(-x*x)).mean() for p in polys]\n coeffs = [(p(x)).mean() for p in polys]\n res = sum(c*p(xeval) for c, p in zip(coeffs, polys))\n #res *= (1-xeval**2)**(-1/2.)\n #res *= np.exp(-xeval**2./2)\n return res, xeval, coeffs, polys\n\n\n\nif __name__ == '__main__':\n\n examples = ['chebyt', 'fourier', 'hermite']#[2]\n\n nobs = 10000\n\n import matplotlib.pyplot as plt\n from statsmodels.distributions.mixture_rvs import (\n mixture_rvs, MixtureDistribution)\n\n #np.random.seed(12345)\n## obs_dist = mixture_rvs([1/3.,2/3.], size=nobs, dist=[stats.norm, stats.norm],\n## kwargs = (dict(loc=-1,scale=.5),dict(loc=1,scale=.75)))\n mix_kwds = (dict(loc=-0.5,scale=.5),dict(loc=1,scale=.2))\n obs_dist = mixture_rvs([1/3.,2/3.], size=nobs, dist=[stats.norm, stats.norm],\n kwargs=mix_kwds)\n mix = MixtureDistribution()\n\n #obs_dist = np.random.randn(nobs)/4. #np.sqrt(2)\n\n\n if \"chebyt_\" in examples: # needed for Cheby example below\n #obs_dist = np.clip(obs_dist, -2, 2)/2.01\n #chebyt [0,1]\n obs_dist = obs_dist[(obs_dist>-2) & (obs_dist<2)]/2.0 #/4. + 2/4.0\n #fourier [0,1]\n #obs_dist = obs_dist[(obs_dist>-2) & (obs_dist<2)]/4. + 2/4.0\n f_hat, grid, coeffs, polys = density_orthopoly(obs_dist, ChebyTPoly, order=20, xeval=None)\n #f_hat /= f_hat.sum() * (grid.max() - grid.min())/len(grid)\n f_hat0 = f_hat\n fint = integrate.trapz(f_hat, grid)# dx=(grid.max() - grid.min())/len(grid))\n #f_hat -= fint/2.\n print('f_hat.min()', f_hat.min())\n f_hat = (f_hat - f_hat.min()) #/ f_hat.max() - f_hat.min\n fint2 = integrate.trapz(f_hat, grid)# dx=(grid.max() - grid.min())/len(grid))\n print('fint2', fint, fint2)\n f_hat /= fint2\n\n # note that this uses a *huge* grid by default\n #f_hat, grid = kdensityfft(emp_dist, kernel=\"gauss\", bw=\"scott\")\n\n # check the plot\n\n doplot = 0\n if doplot:\n plt.hist(obs_dist, bins=50, normed=True, color='red')\n plt.plot(grid, f_hat, lw=2, color='black')\n plt.plot(grid, f_hat0, lw=2, color='g')\n plt.show()\n\n for i,p in enumerate(polys[:5]):\n for j,p2 in enumerate(polys[:5]):\n print(i,j,integrate.quad(lambda x: p(x)*p2(x), -1,1)[0])\n\n for p in polys:\n print(integrate.quad(lambda x: p(x)**2, -1,1))\n\n\n #examples using the new class\n\n if \"chebyt\" in examples:\n dop = DensityOrthoPoly().fit(obs_dist, ChebyTPoly, order=20)\n grid = np.linspace(obs_dist.min(), obs_dist.max())\n xf = dop(grid)\n #print('np.max(np.abs(xf - f_hat0))', np.max(np.abs(xf - f_hat0))\n dopint = integrate.quad(dop, *dop.limits)[0]\n print('dop F integral', dopint)\n mpdf = mix.pdf(grid, [1/3.,2/3.], dist=[stats.norm, stats.norm],\n kwargs=mix_kwds)\n\n doplot = 1\n if doplot:\n plt.figure()\n plt.hist(obs_dist, bins=50, normed=True, color='red')\n plt.plot(grid, xf, lw=2, color='black')\n plt.plot(grid, mpdf, lw=2, color='green')\n plt.title('using Chebychev polynomials')\n #plt.show()\n\n if \"fourier\" in examples:\n dop = DensityOrthoPoly()\n dop.offsetfac = 0.5\n dop = dop.fit(obs_dist, F2Poly, order=30)\n grid = np.linspace(obs_dist.min(), obs_dist.max())\n xf = dop(grid)\n #print(np.max(np.abs(xf - f_hat0))\n dopint = integrate.quad(dop, *dop.limits)[0]\n print('dop F integral', dopint)\n mpdf = mix.pdf(grid, [1/3.,2/3.], dist=[stats.norm, stats.norm],\n kwargs=mix_kwds)\n\n doplot = 1\n if doplot:\n plt.figure()\n plt.hist(obs_dist, bins=50, normed=True, color='red')\n plt.title('using Fourier polynomials')\n plt.plot(grid, xf, lw=2, color='black')\n plt.plot(grid, mpdf, lw=2, color='green')\n #plt.show()\n\n #check orthonormality:\n print(np.max(np.abs(inner_cont(dop.polys[:5], 0, 1)[0] -np.eye(5))))\n\n if \"hermite\" in examples:\n dop = DensityOrthoPoly()\n dop.offsetfac = 0\n dop = dop.fit(obs_dist, HPoly, order=20)\n grid = np.linspace(obs_dist.min(), obs_dist.max())\n xf = dop(grid)\n #print(np.max(np.abs(xf - f_hat0))\n dopint = integrate.quad(dop, *dop.limits)[0]\n print('dop F integral', dopint)\n\n mpdf = mix.pdf(grid, [1/3.,2/3.], dist=[stats.norm, stats.norm],\n kwargs=mix_kwds)\n\n doplot = 1\n if doplot:\n plt.figure()\n plt.hist(obs_dist, bins=50, normed=True, color='red')\n plt.plot(grid, xf, lw=2, color='black')\n plt.plot(grid, mpdf, lw=2, color='green')\n plt.title('using Hermite polynomials')\n plt.show()\n\n #check orthonormality:\n print(np.max(np.abs(inner_cont(dop.polys[:5], 0, 1)[0] -np.eye(5))))\n\n\n #check orthonormality\n\n hpolys = [HPoly(i) for i in range(5)]\n inn = inner_cont(hpolys, -6, 6)[0]\n print(np.max(np.abs(inn - np.eye(5))))\n print((inn*100000).astype(int))\n\n from scipy.special import hermite, chebyt\n htpolys = [hermite(i) for i in range(5)]\n innt = inner_cont(htpolys, -10, 10)[0]\n print((innt*100000).astype(int))\n\n polysc = [chebyt(i) for i in range(4)]\n r, e = inner_cont(polysc, -1, 1, weight=lambda x: (1-x*x)**(-1/2.))\n print(np.max(np.abs(r - np.diag(np.diag(r)))))\n",
"\"\"\"\nTests for VARMAX models\n\nAuthor: Chad Fulton\nLicense: Simplified-BSD\n\"\"\"\nimport os\nimport re\nimport warnings\n\nimport numpy as np\nfrom numpy.testing import assert_equal, assert_raises, assert_allclose\nimport pandas as pd\nimport pytest\n\nfrom statsmodels.tsa.statespace import dynamic_factor\nfrom .results import results_varmax, results_dynamic_factor\nfrom statsmodels.iolib.summary import forg\n\ncurrent_path = os.path.dirname(os.path.abspath(__file__))\n\noutput_path = os.path.join('results', 'results_dynamic_factor_stata.csv')\noutput_results = pd.read_csv(os.path.join(current_path, output_path))\n\n\nclass CheckDynamicFactor:\n @classmethod\n def setup_class(cls, true, k_factors, factor_order, cov_type='approx',\n included_vars=['dln_inv', 'dln_inc', 'dln_consump'],\n demean=False, filter=True, **kwargs):\n cls.true = true\n # 1960:Q1 - 1982:Q4\n dta = pd.DataFrame(\n results_varmax.lutkepohl_data, columns=['inv', 'inc', 'consump'],\n index=pd.date_range('1960-01-01', '1982-10-01', freq='QS'))\n\n dta['dln_inv'] = np.log(dta['inv']).diff()\n dta['dln_inc'] = np.log(dta['inc']).diff()\n dta['dln_consump'] = np.log(dta['consump']).diff()\n\n endog = dta.loc['1960-04-01':'1978-10-01', included_vars]\n\n if demean:\n endog -= dta.iloc[1:][included_vars].mean()\n\n cls.model = dynamic_factor.DynamicFactor(endog, k_factors=k_factors,\n factor_order=factor_order,\n **kwargs)\n\n if filter:\n cls.results = cls.model.smooth(true['params'], cov_type=cov_type)\n\n def test_params(self):\n # Smoke test to make sure the start_params are well-defined and\n # lead to a well-defined model\n self.model.filter(self.model.start_params)\n # Similarly a smoke test for param_names\n assert_equal(len(self.model.start_params), len(self.model.param_names))\n # Finally make sure the transform and untransform do their job\n actual = self.model.transform_params(\n self.model.untransform_params(self.model.start_params))\n assert_allclose(actual, self.model.start_params)\n # Also in the case of enforce stationarity = False\n self.model.enforce_stationarity = False\n actual = self.model.transform_params(\n self.model.untransform_params(self.model.start_params))\n self.model.enforce_stationarity = True\n assert_allclose(actual, self.model.start_params)\n\n def test_results(self, close_figures):\n # Smoke test for creating the summary\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n self.results.summary()\n\n # Test cofficient matrix creation\n # (via a different, more direct, method)\n if self.model.factor_order > 0:\n model = self.model\n k_factors = model.k_factors\n pft_params = self.results.params[model._params_factor_transition]\n coefficients = np.array(pft_params).reshape(\n k_factors, k_factors * model.factor_order)\n coefficient_matrices = np.array([\n coefficients[:self.model.k_factors,\n i*self.model.k_factors:(i+1)*self.model.k_factors]\n for i in range(self.model.factor_order)\n ])\n assert_equal(\n self.results.coefficient_matrices_var,\n coefficient_matrices)\n else:\n assert_equal(self.results.coefficient_matrices_var, None)\n\n @pytest.mark.matplotlib\n def test_plot_coefficients_of_determination(self, close_figures):\n # Smoke test for plot_coefficients_of_determination\n self.results.plot_coefficients_of_determination()\n\n def test_no_enforce(self):\n return\n # Test that nothing goes wrong when we do not enforce stationarity\n params = self.model.untransform_params(self.true['params'])\n params[self.model._params_transition] = (\n self.true['params'][self.model._params_transition])\n self.model.enforce_stationarity = False\n results = self.model.filter(params, transformed=False)\n self.model.enforce_stationarity = True\n assert_allclose(results.llf, self.results.llf, rtol=1e-5)\n\n def test_mle(self, init_powell=True):\n with warnings.catch_warnings(record=True):\n warnings.simplefilter('always')\n start_params = self.model.start_params\n if init_powell:\n results = self.model.fit(method='powell',\n maxiter=100, disp=False)\n start_params = results.params\n results = self.model.fit(start_params, maxiter=1000, disp=False)\n results = self.model.fit(results.params, method='nm', maxiter=1000,\n disp=False)\n if not results.llf > self.results.llf:\n assert_allclose(results.llf, self.results.llf, rtol=1e-5)\n\n def test_loglike(self):\n assert_allclose(self.results.llf, self.true['loglike'], rtol=1e-6)\n\n def test_aic(self):\n # We only get 3 digits from Stata\n assert_allclose(self.results.aic, self.true['aic'], atol=3)\n\n def test_bic(self):\n # We only get 3 digits from Stata\n assert_allclose(self.results.bic, self.true['bic'], atol=3)\n\n def test_predict(self, **kwargs):\n # Tests predict + forecast\n self.results.predict(end='1982-10-01', **kwargs)\n assert_allclose(\n self.results.predict(end='1982-10-01', **kwargs),\n self.true['predict'],\n atol=1e-6)\n\n def test_dynamic_predict(self, **kwargs):\n # Tests predict + dynamic predict + forecast\n assert_allclose(\n self.results.predict(end='1982-10-01', dynamic='1961-01-01',\n **kwargs),\n self.true['dynamic_predict'],\n atol=1e-6)\n\n\nclass TestDynamicFactor(CheckDynamicFactor):\n \"\"\"\n Test for a dynamic factor model with 1 AR(2) factor\n \"\"\"\n @classmethod\n def setup_class(cls):\n true = results_dynamic_factor.lutkepohl_dfm.copy()\n true['predict'] = output_results.iloc[1:][[\n 'predict_dfm_1', 'predict_dfm_2', 'predict_dfm_3']]\n true['dynamic_predict'] = output_results.iloc[1:][[\n 'dyn_predict_dfm_1', 'dyn_predict_dfm_2', 'dyn_predict_dfm_3']]\n super(TestDynamicFactor, cls).setup_class(\n true, k_factors=1, factor_order=2)\n\n def test_bse_approx(self):\n bse = self.results._cov_params_approx().diagonal()**0.5\n assert_allclose(bse, self.true['bse_oim'], atol=1e-5)\n\n\nclass TestDynamicFactor2(CheckDynamicFactor):\n \"\"\"\n Test for a dynamic factor model with two VAR(1) factors\n \"\"\"\n @classmethod\n def setup_class(cls):\n true = results_dynamic_factor.lutkepohl_dfm2.copy()\n true['predict'] = output_results.iloc[1:][[\n 'predict_dfm2_1', 'predict_dfm2_2', 'predict_dfm2_3']]\n true['dynamic_predict'] = output_results.iloc[1:][[\n 'dyn_predict_dfm2_1', 'dyn_predict_dfm2_2', 'dyn_predict_dfm2_3']]\n super(TestDynamicFactor2, cls).setup_class(\n true, k_factors=2, factor_order=1)\n\n def test_mle(self):\n # Stata's MLE on this model does not converge, so no reason to check\n pass\n\n def test_bse(self):\n # Stata's MLE on this model does not converge, and four of their\n # params do not even have bse (possibly they are still at starting\n # values?), so no reason to check this\n pass\n\n def test_aic(self):\n # Stata uses 9 df (i.e. 9 params) here instead of 13, because since the\n # model did not coverge, 4 of the parameters are not fully estimated\n # (possibly they are still at starting values?) so the AIC is off\n pass\n\n def test_bic(self):\n # Stata uses 9 df (i.e. 9 params) here instead of 13, because since the\n # model did not coverge, 4 of the parameters are not fully estimated\n # (possibly they are still at starting values?) so the BIC is off\n pass\n\n def test_summary(self):\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n summary = self.results.summary()\n tables = [str(table) for table in summary.tables]\n params = self.true['params']\n\n # Make sure we have the right number of tables\n assert_equal(\n len(tables),\n 2 + self.model.k_endog + self.model.k_factors + 1)\n\n # Check the model overview table\n assert re.search(\n r'Model:.*DynamicFactor\\(factors=2, order=1\\)',\n tables[0])\n\n # For each endogenous variable, check the output\n for i in range(self.model.k_endog):\n offset_loading = self.model.k_factors * i\n table = tables[i + 2]\n\n # -> Make sure we have the right table / table name\n name = self.model.endog_names[i]\n assert re.search('Results for equation %s' % name, table)\n\n # -> Make sure it's the right size\n assert_equal(len(table.split('\\n')), 7)\n\n # -> Check that we have the right coefficients\n assert re.search(\n 'loading.f1 +' + forg(params[offset_loading + 0], prec=4),\n table)\n assert re.search(\n 'loading.f2 +' + forg(params[offset_loading + 1], prec=4),\n table)\n\n # For each factor, check the output\n for i in range(self.model.k_factors):\n offset = (self.model.k_endog * (self.model.k_factors + 1) +\n i * self.model.k_factors)\n table = tables[self.model.k_endog + i + 2]\n\n # -> Make sure we have the right table / table name\n name = self.model.endog_names[i]\n assert re.search('Results for factor equation f%d' % (i+1), table)\n\n # -> Make sure it's the right size\n assert_equal(len(table.split('\\n')), 7)\n\n # -> Check that we have the right coefficients\n assert re.search('L1.f1 +' + forg(params[offset + 0], prec=4),\n table)\n assert re.search('L1.f2 +' + forg(params[offset + 1], prec=4),\n table)\n\n # Check the Error covariance matrix output\n table = tables[2 + self.model.k_endog + self.model.k_factors]\n\n # -> Make sure we have the right table / table name\n name = self.model.endog_names[i]\n assert re.search('Error covariance matrix', table)\n\n # -> Make sure it's the right size\n assert_equal(len(table.split('\\n')), 8)\n\n # -> Check that we have the right coefficients\n offset = self.model.k_endog * self.model.k_factors\n for i in range(self.model.k_endog):\n iname = self.model.endog_names[i]\n iparam = forg(params[offset + i], prec=4)\n assert re.search('sigma2.%s +%s' % (iname, iparam), table)\n\n\nclass TestDynamicFactor_exog1(CheckDynamicFactor):\n \"\"\"\n Test for a dynamic factor model with 1 exogenous regressor: a constant\n \"\"\"\n @classmethod\n def setup_class(cls):\n true = results_dynamic_factor.lutkepohl_dfm_exog1.copy()\n true['predict'] = output_results.iloc[1:][[\n 'predict_dfm_exog1_1',\n 'predict_dfm_exog1_2',\n 'predict_dfm_exog1_3']]\n true['dynamic_predict'] = output_results.iloc[1:][[\n 'dyn_predict_dfm_exog1_1',\n 'dyn_predict_dfm_exog1_2',\n 'dyn_predict_dfm_exog1_3']]\n exog = np.ones((75, 1))\n super(TestDynamicFactor_exog1, cls).setup_class(\n true, k_factors=1, factor_order=1, exog=exog)\n\n def test_predict(self):\n exog = np.ones((16, 1))\n super(TestDynamicFactor_exog1, self).test_predict(exog=exog)\n\n def test_dynamic_predict(self):\n exog = np.ones((16, 1))\n super(TestDynamicFactor_exog1, self).test_dynamic_predict(exog=exog)\n\n def test_bse_approx(self):\n bse = self.results._cov_params_approx().diagonal()**0.5\n assert_allclose(bse**2, self.true['var_oim'], atol=1e-5)\n\n\nclass TestDynamicFactor_exog2(CheckDynamicFactor):\n \"\"\"\n Test for a dynamic factor model with 2 exogenous regressors: a constant\n and a time-trend\n \"\"\"\n @classmethod\n def setup_class(cls):\n true = results_dynamic_factor.lutkepohl_dfm_exog2.copy()\n true['predict'] = output_results.iloc[1:][[\n 'predict_dfm_exog2_1',\n 'predict_dfm_exog2_2',\n 'predict_dfm_exog2_3']]\n true['dynamic_predict'] = output_results.iloc[1:][[\n 'dyn_predict_dfm_exog2_1',\n 'dyn_predict_dfm_exog2_2',\n 'dyn_predict_dfm_exog2_3']]\n exog = np.c_[np.ones((75, 1)), (np.arange(75) + 2)[:, np.newaxis]]\n super(TestDynamicFactor_exog2, cls).setup_class(\n true, k_factors=1, factor_order=1, exog=exog)\n\n def test_bse_approx(self):\n bse = self.results._cov_params_approx().diagonal()**0.5\n assert_allclose(bse**2, self.true['var_oim'], atol=1e-5)\n\n def test_predict(self):\n exog = np.c_[np.ones((16, 1)),\n (np.arange(75, 75+16) + 2)[:, np.newaxis]]\n super(TestDynamicFactor_exog2, self).test_predict(exog=exog)\n\n def test_dynamic_predict(self):\n exog = np.c_[np.ones((16, 1)),\n (np.arange(75, 75+16) + 2)[:, np.newaxis]]\n super(TestDynamicFactor_exog2, self).test_dynamic_predict(exog=exog)\n\n def test_summary(self):\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n summary = self.results.summary()\n tables = [str(table) for table in summary.tables]\n params = self.true['params']\n\n # Make sure we have the right number of tables\n assert_equal(\n len(tables),\n 2 + self.model.k_endog + self.model.k_factors + 1)\n\n # Check the model overview table\n assert re.search(r'Model:.*DynamicFactor\\(factors=1, order=1\\)',\n tables[0])\n assert_equal(re.search(r'.*2 regressors', tables[0]) is None, False)\n\n # For each endogenous variable, check the output\n for i in range(self.model.k_endog):\n offset_loading = self.model.k_factors * i\n offset_exog = self.model.k_factors * self.model.k_endog\n table = tables[i + 2]\n\n # -> Make sure we have the right table / table name\n name = self.model.endog_names[i]\n assert re.search('Results for equation %s' % name, table)\n\n # -> Make sure it's the right size\n assert_equal(len(table.split('\\n')), 8)\n\n # -> Check that we have the right coefficients\n assert re.search(\n 'loading.f1 +' + forg(params[offset_loading + 0], prec=4),\n table)\n assert re.search(\n 'beta.const +' + forg(params[offset_exog + i*2 + 0], prec=4),\n table)\n assert re.search(\n 'beta.x1 +' + forg(params[offset_exog + i*2 + 1], prec=4),\n table)\n\n # For each factor, check the output\n for i in range(self.model.k_factors):\n offset = (self.model.k_endog * (self.model.k_factors + 3) +\n i * self.model.k_factors)\n table = tables[self.model.k_endog + i + 2]\n\n # -> Make sure we have the right table / table name\n name = self.model.endog_names[i]\n assert re.search('Results for factor equation f%d' % (i+1), table)\n\n # -> Make sure it's the right size\n assert_equal(len(table.split('\\n')), 6)\n\n # -> Check that we have the right coefficients\n assert re.search('L1.f1 +' + forg(params[offset + 0], prec=4),\n table)\n\n # Check the Error covariance matrix output\n table = tables[2 + self.model.k_endog + self.model.k_factors]\n\n # -> Make sure we have the right table / table name\n name = self.model.endog_names[i]\n assert re.search('Error covariance matrix', table)\n\n # -> Make sure it's the right size\n assert_equal(len(table.split('\\n')), 8)\n\n # -> Check that we have the right coefficients\n offset = self.model.k_endog * (self.model.k_factors + 2)\n for i in range(self.model.k_endog):\n iname = self.model.endog_names[i]\n iparam = forg(params[offset + i], prec=4)\n assert re.search('sigma2.%s +%s' % (iname, iparam), table)\n\n\nclass TestDynamicFactor_general_errors(CheckDynamicFactor):\n \"\"\"\n Test for a dynamic factor model where errors are as general as possible,\n meaning:\n\n - Errors are vector autocorrelated, VAR(1)\n - Innovations are correlated\n \"\"\"\n @classmethod\n def setup_class(cls):\n true = results_dynamic_factor.lutkepohl_dfm_gen.copy()\n true['predict'] = output_results.iloc[1:][[\n 'predict_dfm_gen_1', 'predict_dfm_gen_2', 'predict_dfm_gen_3']]\n true['dynamic_predict'] = output_results.iloc[1:][[\n 'dyn_predict_dfm_gen_1',\n 'dyn_predict_dfm_gen_2',\n 'dyn_predict_dfm_gen_3']]\n super(TestDynamicFactor_general_errors, cls).setup_class(\n true, k_factors=1, factor_order=1, error_var=True,\n error_order=1, error_cov_type='unstructured')\n\n def test_bse_approx(self):\n bse = self.results._cov_params_approx().diagonal()\n assert_allclose(bse[:3], self.true['var_oim'][:3], atol=1e-5)\n assert_allclose(bse[-10:], self.true['var_oim'][-10:], atol=3e-4)\n\n @pytest.mark.skip(\"Known failure, no sequence of optimizers has been \"\n \"found which can achieve the maximum.\")\n def test_mle(self):\n # The following gets us to llf=546.53, which is still not good enough\n # llf = 300.842477412\n # res = mod.fit(method='lbfgs', maxiter=10000)\n # llf = 460.26576722\n # res = mod.fit(res.params, method='nm', maxiter=10000, maxfev=10000)\n # llf = 542.245718508\n # res = mod.fit(res.params, method='lbfgs', maxiter=10000)\n # llf = 544.035160955\n # res = mod.fit(res.params, method='nm', maxiter=10000, maxfev=10000)\n # llf = 557.442240083\n # res = mod.fit(res.params, method='lbfgs', maxiter=10000)\n # llf = 558.199513262\n # res = mod.fit(res.params, method='nm', maxiter=10000, maxfev=10000)\n # llf = 559.049076604\n # res = mod.fit(res.params, method='nm', maxiter=10000, maxfev=10000)\n # llf = 559.049076604\n # ...\n pass\n\n def test_summary(self):\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n summary = self.results.summary()\n tables = [str(table) for table in summary.tables]\n params = self.true['params']\n\n # Make sure we have the right number of tables\n assert_equal(\n len(tables),\n 2 + self.model.k_endog + self.model.k_factors +\n self.model.k_endog + 1)\n\n # Check the model overview table\n assert re.search(r'Model:.*DynamicFactor\\(factors=1, order=1\\)',\n tables[0])\n assert re.search(r'.*VAR\\(1\\) errors', tables[0])\n\n # For each endogenous variable, check the output\n for i in range(self.model.k_endog):\n offset_loading = self.model.k_factors * i\n table = tables[i + 2]\n\n # -> Make sure we have the right table / table name\n name = self.model.endog_names[i]\n assert re.search('Results for equation %s' % name, table)\n\n # -> Make sure it's the right size\n assert_equal(len(table.split('\\n')), 6)\n\n # -> Check that we have the right coefficients\n pattern = 'loading.f1 +' + forg(params[offset_loading + 0], prec=4)\n assert re.search(pattern, table)\n\n # For each factor, check the output\n for i in range(self.model.k_factors):\n offset = (self.model.k_endog * self.model.k_factors +\n 6 + i * self.model.k_factors)\n table = tables[2 + self.model.k_endog + i]\n\n # -> Make sure we have the right table / table name\n name = self.model.endog_names[i]\n assert re.search('Results for factor equation f%d' % (i+1), table)\n\n # -> Make sure it's the right size\n assert_equal(len(table.split('\\n')), 6)\n\n # -> Check that we have the right coefficients\n assert re.search('L1.f1 +' + forg(params[offset + 0], prec=4),\n table)\n\n # For each error equation, check the output\n for i in range(self.model.k_endog):\n offset = (self.model.k_endog * (self.model.k_factors + i) +\n 6 + self.model.k_factors)\n table = tables[2 + self.model.k_endog + self.model.k_factors + i]\n\n # -> Make sure we have the right table / table name\n name = self.model.endog_names[i]\n assert re.search(r'Results for error equation e\\(%s\\)' % name,\n table)\n\n # -> Make sure it's the right size\n assert_equal(len(table.split('\\n')), 8)\n\n # -> Check that we have the right coefficients\n for j in range(self.model.k_endog):\n name = self.model.endog_names[j]\n pattern = r'L1.e\\(%s\\) +%s' % (name, forg(params[offset + j],\n prec=4))\n assert re.search(pattern, table)\n\n # Check the Error covariance matrix output\n table = tables[2 + self.model.k_endog +\n self.model.k_factors + self.model.k_endog]\n\n # -> Make sure we have the right table / table name\n name = self.model.endog_names[i]\n assert re.search('Error covariance matrix', table)\n\n # -> Make sure it's the right size\n assert_equal(len(table.split('\\n')), 11)\n\n # -> Check that we have the right coefficients\n offset = self.model.k_endog * self.model.k_factors\n assert re.search(\n r'cov.chol\\[1,1\\] +' + forg(params[offset + 0], prec=4),\n table)\n assert re.search(\n r'cov.chol\\[2,1\\] +' + forg(params[offset + 1], prec=4),\n table)\n assert re.search(\n r'cov.chol\\[2,2\\] +' + forg(params[offset + 2], prec=4),\n table)\n assert re.search(\n r'cov.chol\\[3,1\\] +' + forg(params[offset+3], prec=4),\n table)\n assert re.search(\n r'cov.chol\\[3,2\\] +' + forg(params[offset+4], prec=4),\n table)\n assert re.search(\n r'cov.chol\\[3,3\\] +' + forg(params[offset + 5], prec=4),\n table)\n\n\nclass TestDynamicFactor_ar2_errors(CheckDynamicFactor):\n \"\"\"\n Test for a dynamic factor model where errors are as general as possible,\n meaning:\n\n - Errors are vector autocorrelated, VAR(1)\n - Innovations are correlated\n \"\"\"\n @classmethod\n def setup_class(cls):\n true = results_dynamic_factor.lutkepohl_dfm_ar2.copy()\n true['predict'] = output_results.iloc[1:][[\n 'predict_dfm_ar2_1', 'predict_dfm_ar2_2', 'predict_dfm_ar2_3']]\n true['dynamic_predict'] = output_results.iloc[1:][[\n 'dyn_predict_dfm_ar2_1',\n 'dyn_predict_dfm_ar2_2',\n 'dyn_predict_dfm_ar2_3']]\n super(TestDynamicFactor_ar2_errors, cls).setup_class(\n true, k_factors=1, factor_order=1, error_order=2)\n\n def test_bse_approx(self):\n bse = self.results._cov_params_approx().diagonal()\n assert_allclose(bse, self.true['var_oim'], atol=1e-5)\n\n def test_mle(self):\n with warnings.catch_warnings(record=True):\n # Depending on the system, this test can reach a greater precision,\n # but for cross-platform results keep it at 1e-2\n mod = self.model\n res1 = mod.fit(maxiter=100, optim_score='approx', disp=False)\n res = mod.fit(\n res1.params, method='nm', maxiter=10000,\n optim_score='approx', disp=False)\n # Added rtol to catch spurious failures on some platforms\n assert_allclose(res.llf, self.results.llf, atol=1e-2, rtol=1e-4)\n\n\nclass TestDynamicFactor_scalar_error(CheckDynamicFactor):\n \"\"\"\n Test for a dynamic factor model where innovations are uncorrelated and\n are forced to have the same variance.\n \"\"\"\n @classmethod\n def setup_class(cls):\n true = results_dynamic_factor.lutkepohl_dfm_scalar.copy()\n true['predict'] = output_results.iloc[1:][[\n 'predict_dfm_scalar_1', 'predict_dfm_scalar_2',\n 'predict_dfm_scalar_3']]\n true['dynamic_predict'] = output_results.iloc[1:][[\n 'dyn_predict_dfm_scalar_1', 'dyn_predict_dfm_scalar_2',\n 'dyn_predict_dfm_scalar_3']]\n exog = np.ones((75, 1))\n super(TestDynamicFactor_scalar_error, cls).setup_class(\n true, k_factors=1, factor_order=1,\n exog=exog, error_cov_type='scalar')\n\n def test_bse_approx(self):\n bse = self.results._cov_params_approx().diagonal()\n assert_allclose(bse, self.true['var_oim'], atol=1e-5)\n\n def test_predict(self):\n exog = np.ones((16, 1))\n super(TestDynamicFactor_scalar_error, self).test_predict(exog=exog)\n\n def test_dynamic_predict(self):\n exog = np.ones((16, 1))\n super(TestDynamicFactor_scalar_error,\n self).test_dynamic_predict(exog=exog)\n\n\nclass TestStaticFactor(CheckDynamicFactor):\n \"\"\"\n Test for a static factor model (i.e. factors are not autocorrelated).\n \"\"\"\n @classmethod\n def setup_class(cls):\n true = results_dynamic_factor.lutkepohl_sfm.copy()\n true['predict'] = output_results.iloc[1:][[\n 'predict_sfm_1', 'predict_sfm_2', 'predict_sfm_3']]\n true['dynamic_predict'] = output_results.iloc[1:][[\n 'dyn_predict_sfm_1', 'dyn_predict_sfm_2', 'dyn_predict_sfm_3']]\n super(TestStaticFactor, cls).setup_class(\n true, k_factors=1, factor_order=0)\n\n def test_bse_approx(self):\n bse = self.results._cov_params_approx().diagonal()\n assert_allclose(bse, self.true['var_oim'], atol=1e-5)\n\n def test_bic(self):\n # Stata uses 5 df (i.e. 5 params) here instead of 6, because one param\n # is basically zero.\n pass\n\n\nclass TestSUR(CheckDynamicFactor):\n \"\"\"\n Test for a seemingly unrelated regression model (i.e. no factors) with\n errors cross-sectionally, but not auto-, correlated\n \"\"\"\n @classmethod\n def setup_class(cls):\n true = results_dynamic_factor.lutkepohl_sur.copy()\n true['predict'] = output_results.iloc[1:][[\n 'predict_sur_1', 'predict_sur_2', 'predict_sur_3']]\n true['dynamic_predict'] = output_results.iloc[1:][[\n 'dyn_predict_sur_1', 'dyn_predict_sur_2', 'dyn_predict_sur_3']]\n exog = np.c_[np.ones((75, 1)), (np.arange(75) + 2)[:, np.newaxis]]\n super(TestSUR, cls).setup_class(\n true, k_factors=0, factor_order=0,\n exog=exog, error_cov_type='unstructured')\n\n def test_bse_approx(self):\n bse = self.results._cov_params_approx().diagonal()\n assert_allclose(bse[:6], self.true['var_oim'][:6], atol=1e-5)\n\n def test_predict(self):\n exog = np.c_[np.ones((16, 1)),\n (np.arange(75, 75+16) + 2)[:, np.newaxis]]\n super(TestSUR, self).test_predict(exog=exog)\n\n def test_dynamic_predict(self):\n exog = np.c_[np.ones((16, 1)),\n (np.arange(75, 75+16) + 2)[:, np.newaxis]]\n super(TestSUR, self).test_dynamic_predict(exog=exog)\n\n\nclass TestSUR_autocorrelated_errors(CheckDynamicFactor):\n \"\"\"\n Test for a seemingly unrelated regression model (i.e. no factors) where\n the errors are vector autocorrelated, but innovations are uncorrelated.\n \"\"\"\n @classmethod\n def setup_class(cls):\n true = results_dynamic_factor.lutkepohl_sur_auto.copy()\n true['predict'] = output_results.iloc[1:][[\n 'predict_sur_auto_1', 'predict_sur_auto_2']]\n true['dynamic_predict'] = output_results.iloc[1:][[\n 'dyn_predict_sur_auto_1', 'dyn_predict_sur_auto_2']]\n exog = np.c_[np.ones((75, 1)), (np.arange(75) + 2)[:, np.newaxis]]\n super(TestSUR_autocorrelated_errors, cls).setup_class(\n true, k_factors=0, factor_order=0, exog=exog,\n error_order=1, error_var=True,\n error_cov_type='diagonal',\n included_vars=['dln_inv', 'dln_inc'])\n\n def test_bse_approx(self):\n bse = self.results._cov_params_approx().diagonal()\n assert_allclose(bse, self.true['var_oim'], atol=1e-5)\n\n def test_predict(self):\n exog = np.c_[np.ones((16, 1)),\n (np.arange(75, 75+16) + 2)[:, np.newaxis]]\n super(TestSUR_autocorrelated_errors, self).test_predict(exog=exog)\n\n def test_dynamic_predict(self):\n exog = np.c_[np.ones((16, 1)),\n (np.arange(75, 75+16) + 2)[:, np.newaxis]]\n super(TestSUR_autocorrelated_errors,\n self).test_dynamic_predict(exog=exog)\n\n def test_mle(self):\n super(TestSUR_autocorrelated_errors, self).test_mle(init_powell=False)\n\n\ndef test_misspecification():\n # Tests for model specification and misspecification exceptions\n endog = np.arange(20).reshape(10, 2)\n\n # Too few endog\n assert_raises(\n ValueError,\n dynamic_factor.DynamicFactor, endog[:, 0], k_factors=0, factor_order=0)\n\n # Too many factors\n assert_raises(\n ValueError,\n dynamic_factor.DynamicFactor, endog, k_factors=2, factor_order=1)\n\n # Bad error_cov_type specification\n assert_raises(\n ValueError,\n dynamic_factor.DynamicFactor,\n endog,\n k_factors=1, factor_order=1, order=(1, 0), error_cov_type='')\n\n\ndef test_miscellaneous():\n # Initialization with 1-dimensional exog array\n exog = np.arange(75)\n mod = CheckDynamicFactor()\n mod.setup_class(true=None, k_factors=1, factor_order=1,\n exog=exog, filter=False)\n exog = pd.Series(np.arange(75),\n index=pd.date_range(start='1960-04-01',\n end='1978-10-01', freq='QS'))\n mod = CheckDynamicFactor()\n mod.setup_class(\n true=None, k_factors=1, factor_order=1, exog=exog, filter=False)\n\n\ndef test_predict_custom_index():\n np.random.seed(328423)\n endog = pd.DataFrame(np.random.normal(size=(50, 2)))\n mod = dynamic_factor.DynamicFactor(endog, k_factors=1, factor_order=1)\n res = mod.smooth(mod.start_params)\n out = res.predict(start=1, end=1, index=['a'])\n assert_equal(out.index.equals(pd.Index(['a'])), True)\n\n\ndef test_forecast_exog():\n # Test forecasting with various shapes of `exog`\n nobs = 100\n endog = np.ones((nobs, 2)) * 2.0\n exog = np.ones(nobs)\n\n mod = dynamic_factor.DynamicFactor(endog, exog=exog, k_factors=1,\n factor_order=1)\n res = mod.smooth(np.r_[[0] * 2, 2.0, 2.0, 1, 1., 0.])\n\n # 1-step-ahead, valid\n exog_fcast_scalar = 1.\n exog_fcast_1dim = np.ones(1)\n exog_fcast_2dim = np.ones((1, 1))\n\n assert_allclose(res.forecast(1, exog=exog_fcast_scalar), 2.)\n assert_allclose(res.forecast(1, exog=exog_fcast_1dim), 2.)\n assert_allclose(res.forecast(1, exog=exog_fcast_2dim), 2.)\n\n # h-steps-ahead, valid\n h = 10\n exog_fcast_1dim = np.ones(h)\n exog_fcast_2dim = np.ones((h, 1))\n\n assert_allclose(res.forecast(h, exog=exog_fcast_1dim), 2.)\n assert_allclose(res.forecast(h, exog=exog_fcast_2dim), 2.)\n\n # h-steps-ahead, invalid\n assert_raises(ValueError, res.forecast, h, exog=1.)\n assert_raises(ValueError, res.forecast, h, exog=[1, 2])\n assert_raises(ValueError, res.forecast, h, exog=np.ones((h, 2)))\n\n\ndef check_equivalent_models(mod, mod2):\n attrs = [\n 'k_factors', 'factor_order', 'error_order', 'error_var',\n 'error_cov_type', 'enforce_stationarity', 'mle_regression', 'k_params']\n\n ssm_attrs = [\n 'nobs', 'k_endog', 'k_states', 'k_posdef', 'obs_intercept', 'design',\n 'obs_cov', 'state_intercept', 'transition', 'selection', 'state_cov']\n\n for attr in attrs:\n assert_equal(getattr(mod2, attr), getattr(mod, attr))\n\n for attr in ssm_attrs:\n assert_equal(getattr(mod2.ssm, attr), getattr(mod.ssm, attr))\n\n assert_equal(mod2._get_init_kwds(), mod._get_init_kwds())\n\n\ndef test_recreate_model():\n nobs = 100\n endog = np.ones((nobs, 3)) * 2.0\n exog = np.ones(nobs)\n\n k_factors = [0, 1, 2]\n factor_orders = [0, 1, 2]\n error_orders = [0, 1]\n error_vars = [False, True]\n error_cov_types = ['diagonal', 'scalar']\n\n import itertools\n names = ['k_factors', 'factor_order', 'error_order', 'error_var',\n 'error_cov_type']\n for element in itertools.product(k_factors, factor_orders, error_orders,\n error_vars, error_cov_types):\n kwargs = dict(zip(names, element))\n\n mod = dynamic_factor.DynamicFactor(endog, exog=exog, **kwargs)\n mod2 = dynamic_factor.DynamicFactor(endog, exog=exog,\n **mod._get_init_kwds())\n check_equivalent_models(mod, mod2)\n\n\ndef test_append_results():\n endog = np.arange(200).reshape(100, 2)\n exog = np.ones(100)\n params = [0.1, -0.2, 1., 2., 1., 1., 0.5, 0.1]\n\n mod1 = dynamic_factor.DynamicFactor(\n endog, k_factors=1, factor_order=2, exog=exog)\n res1 = mod1.smooth(params)\n\n mod2 = dynamic_factor.DynamicFactor(\n endog[:50], k_factors=1, factor_order=2, exog=exog[:50])\n res2 = mod2.smooth(params)\n res3 = res2.append(endog[50:], exog=exog[50:])\n\n assert_equal(res1.specification, res3.specification)\n\n assert_allclose(res3.cov_params_default, res2.cov_params_default)\n for attr in ['nobs', 'llf', 'llf_obs', 'loglikelihood_burn']:\n assert_equal(getattr(res3, attr), getattr(res1, attr))\n\n for attr in [\n 'filtered_state', 'filtered_state_cov', 'predicted_state',\n 'predicted_state_cov', 'forecasts', 'forecasts_error',\n 'forecasts_error_cov', 'standardized_forecasts_error',\n 'forecasts_error_diffuse_cov', 'predicted_diffuse_state_cov',\n 'scaled_smoothed_estimator',\n 'scaled_smoothed_estimator_cov', 'smoothing_error',\n 'smoothed_state',\n 'smoothed_state_cov', 'smoothed_state_autocov',\n 'smoothed_measurement_disturbance',\n 'smoothed_state_disturbance',\n 'smoothed_measurement_disturbance_cov',\n 'smoothed_state_disturbance_cov']:\n assert_equal(getattr(res3, attr), getattr(res1, attr))\n\n assert_allclose(res3.forecast(10, exog=np.ones(10)),\n res1.forecast(10, exog=np.ones(10)))\n\n\ndef test_extend_results():\n endog = np.arange(200).reshape(100, 2)\n exog = np.ones(100)\n params = [0.1, -0.2, 1., 2., 1., 1., 0.5, 0.1]\n\n mod1 = dynamic_factor.DynamicFactor(\n endog, k_factors=1, factor_order=2, exog=exog)\n res1 = mod1.smooth(params)\n\n mod2 = dynamic_factor.DynamicFactor(\n endog[:50], k_factors=1, factor_order=2, exog=exog[:50])\n res2 = mod2.smooth(params)\n res3 = res2.extend(endog[50:], exog=exog[50:])\n\n assert_allclose(res3.llf_obs, res1.llf_obs[50:])\n\n for attr in [\n 'filtered_state', 'filtered_state_cov', 'predicted_state',\n 'predicted_state_cov', 'forecasts', 'forecasts_error',\n 'forecasts_error_cov', 'standardized_forecasts_error',\n 'forecasts_error_diffuse_cov', 'predicted_diffuse_state_cov',\n 'scaled_smoothed_estimator',\n 'scaled_smoothed_estimator_cov', 'smoothing_error',\n 'smoothed_state',\n 'smoothed_state_cov', 'smoothed_state_autocov',\n 'smoothed_measurement_disturbance',\n 'smoothed_state_disturbance',\n 'smoothed_measurement_disturbance_cov',\n 'smoothed_state_disturbance_cov']:\n desired = getattr(res1, attr)\n if desired is not None:\n desired = desired[..., 50:]\n assert_equal(getattr(res3, attr), desired)\n\n assert_allclose(res3.forecast(10, exog=np.ones(10)),\n res1.forecast(10, exog=np.ones(10)))\n\n\ndef test_apply_results():\n endog = np.arange(200).reshape(100, 2)\n exog = np.ones(100)\n params = [0.1, -0.2, 1., 2., 1., 1., 0.5, 0.1]\n\n mod1 = dynamic_factor.DynamicFactor(\n endog[:50], k_factors=1, factor_order=2, exog=exog[:50])\n res1 = mod1.smooth(params)\n\n mod2 = dynamic_factor.DynamicFactor(\n endog[50:], k_factors=1, factor_order=2, exog=exog[50:])\n res2 = mod2.smooth(params)\n\n res3 = res2.apply(endog[:50], exog=exog[:50])\n\n assert_equal(res1.specification, res3.specification)\n\n assert_allclose(res3.cov_params_default, res2.cov_params_default)\n for attr in ['nobs', 'llf', 'llf_obs', 'loglikelihood_burn']:\n assert_equal(getattr(res3, attr), getattr(res1, attr))\n\n for attr in [\n 'filtered_state', 'filtered_state_cov', 'predicted_state',\n 'predicted_state_cov', 'forecasts', 'forecasts_error',\n 'forecasts_error_cov', 'standardized_forecasts_error',\n 'forecasts_error_diffuse_cov', 'predicted_diffuse_state_cov',\n 'scaled_smoothed_estimator',\n 'scaled_smoothed_estimator_cov', 'smoothing_error',\n 'smoothed_state',\n 'smoothed_state_cov', 'smoothed_state_autocov',\n 'smoothed_measurement_disturbance',\n 'smoothed_state_disturbance',\n 'smoothed_measurement_disturbance_cov',\n 'smoothed_state_disturbance_cov']:\n assert_equal(getattr(res3, attr), getattr(res1, attr))\n\n assert_allclose(res3.forecast(10, exog=np.ones(10)),\n res1.forecast(10, exog=np.ones(10)))\n\n\ndef test_start_params_nans():\n ix = pd.date_range('1960-01-01', '1982-10-01', freq='QS')\n dta = np.log(pd.DataFrame(\n results_varmax.lutkepohl_data, columns=['inv', 'inc', 'consump'],\n index=ix)).diff().iloc[1:]\n\n endog1 = dta.iloc[:-1]\n mod1 = dynamic_factor.DynamicFactor(endog1, k_factors=1, factor_order=1)\n endog2 = dta.copy()\n endog2.iloc[-1:] = np.nan\n mod2 = dynamic_factor.DynamicFactor(endog2, k_factors=1, factor_order=1)\n\n assert_allclose(mod2.start_params, mod1.start_params)\n",
"import numpy as np\nimport pandas as pd\n\nfrom statsmodels.genmod.generalized_linear_model import GLM\nfrom statsmodels.genmod import families\nfrom statsmodels.genmod.families import links\nfrom statsmodels.genmod.generalized_estimating_equations import GEE\nfrom statsmodels.genmod.cov_struct import Independence\n\nfrom numpy.testing import assert_allclose\n\n\nclass CheckGEEGLM:\n\n def test_basic(self):\n res1 = self.result1\n res2 = self.result2\n assert_allclose(res1.params.values, res2.params.values,\n rtol=1e-6, atol=1e-10)\n\n\n def test_resid(self):\n res1 = self.result1\n res2 = self.result2\n assert_allclose(res1.resid_response, res2.resid_response,\n rtol=1e-6, atol=1e-10)\n assert_allclose(res1.resid_pearson, res2.resid_pearson,\n rtol=1e-6, atol=1e-10)\n assert_allclose(res1.resid_deviance, res2.resid_deviance,\n rtol=1e-6, atol=1e-10)\n assert_allclose(res1.resid_anscombe, res2.resid_anscombe,\n rtol=1e-6, atol=1e-10)\n assert_allclose(res1.resid_working, res2.resid_working,\n rtol=1e-6, atol=1e-10)\n\n\n#def test_compare_logit(self):\nclass TestCompareLogit(CheckGEEGLM):\n\n @classmethod\n def setup_class(cls):\n vs = Independence()\n family = families.Binomial()\n np.random.seed(987126)\n Y = 1 * (np.random.normal(size=100) < 0)\n X1 = np.random.normal(size=100)\n X2 = np.random.normal(size=100)\n X3 = np.random.normal(size=100)\n groups = np.random.randint(0, 4, size=100)\n\n D = pd.DataFrame({\"Y\": Y, \"X1\": X1, \"X2\": X2, \"X3\": X3})\n\n mod1 = GEE.from_formula(\"Y ~ X1 + X2 + X3\", groups, D,\n family=family, cov_struct=vs)\n cls.result1 = mod1.fit()\n\n mod2 = GLM.from_formula(\"Y ~ X1 + X2 + X3\", data=D, family=family)\n cls.result2 = mod2.fit(disp=False)\n\n\nclass TestComparePoisson(CheckGEEGLM):\n\n @classmethod\n def setup_class(cls):\n vs = Independence()\n family = families.Poisson()\n np.random.seed(987126)\n Y = np.exp(1 + np.random.normal(size=100))\n X1 = np.random.normal(size=100)\n X2 = np.random.normal(size=100)\n X3 = np.random.normal(size=100)\n groups = np.random.randint(0, 4, size=100)\n\n D = pd.DataFrame({\"Y\": Y, \"X1\": X1, \"X2\": X2, \"X3\": X3})\n\n mod1 = GEE.from_formula(\"Y ~ X1 + X2 + X3\", groups, D,\n family=family, cov_struct=vs)\n cls.result1 = mod1.fit()\n\n mod2 = GLM.from_formula(\"Y ~ X1 + X2 + X3\", data=D, family=family)\n cls.result2 = mod2.fit(disp=False)\n\n\nclass TestCompareGaussian(CheckGEEGLM):\n\n @classmethod\n def setup_class(cls):\n\n vs = Independence()\n family = families.Gaussian()\n np.random.seed(987126)\n Y = np.random.normal(size=100)\n X1 = np.random.normal(size=100)\n X2 = np.random.normal(size=100)\n X3 = np.random.normal(size=100)\n groups = np.kron(np.arange(20), np.ones(5))\n\n D = pd.DataFrame({\"Y\": Y, \"X1\": X1, \"X2\": X2, \"X3\": X3})\n\n md = GEE.from_formula(\"Y ~ X1 + X2 + X3\", groups, D,\n family=family, cov_struct=vs)\n cls.result1 = md.fit()\n\n cls.result2 = GLM.from_formula(\"Y ~ X1 + X2 + X3\", data=D).fit()\n\n\nclass TestCompareGamma(CheckGEEGLM):\n\n @classmethod\n def setup_class(cls):\n # adjusted for Gamma, not in test_gee.py\n vs = Independence()\n family = families.Gamma(link=links.log())\n np.random.seed(987126)\n #Y = np.random.normal(size=100)**2\n Y = np.exp(0.1 + np.random.normal(size=100)) # log-normal\n X1 = np.random.normal(size=100)\n X2 = np.random.normal(size=100)\n X3 = np.random.normal(size=100)\n groups = np.random.randint(0, 4, size=100)\n\n D = pd.DataFrame({\"Y\": Y, \"X1\": X1, \"X2\": X2, \"X3\": X3})\n\n mod1 = GEE.from_formula(\"Y ~ X1 + X2 + X3\", groups, D,\n family=family, cov_struct=vs)\n cls.result1 = mod1.fit()\n\n mod2 = GLM.from_formula(\"Y ~ X1 + X2 + X3\", data=D, family=family)\n cls.result2 = mod2.fit(disp=False)\n",
"# -*- coding: utf-8 -*-\n\"\"\"\nunit test for GAM\n\nAuthor: Josef Perktold\n\n\"\"\"\n\nimport os\n\nimport numpy as np\nfrom numpy.testing import assert_allclose, assert_equal, assert_\nimport pandas as pd\n\nimport pytest\n\nimport patsy\n\nfrom statsmodels.discrete.discrete_model import Poisson, Logit, Probit\nfrom statsmodels.genmod.generalized_linear_model import GLM\nfrom statsmodels.genmod.families import family\nfrom statsmodels.sandbox.regression.penalized import TheilGLS\nfrom statsmodels.base._penalized import PenalizedMixin\nimport statsmodels.base._penalties as smpen\n\nfrom statsmodels.gam.smooth_basis import (BSplines, CyclicCubicSplines)\nfrom statsmodels.gam.generalized_additive_model import (\n GLMGam, GLMGamResults, GLMGamResultsWrapper)\n\nfrom statsmodels.tools.linalg import matrix_sqrt, transf_constraints\n\nfrom .results import results_pls, results_mpg_bs, results_mpg_bs_poisson\n\n\nclass PoissonPenalized(PenalizedMixin, Poisson):\n pass\n\n\nclass LogitPenalized(PenalizedMixin, Logit):\n pass\n\n\nclass ProbitPenalized(PenalizedMixin, Probit):\n pass\n\n\nclass GLMPenalized(PenalizedMixin, GLM):\n pass\n\n\ncur_dir = os.path.dirname(os.path.abspath(__file__))\n\nfile_path = os.path.join(cur_dir, \"results\", \"motorcycle.csv\")\ndata_mcycle = pd.read_csv(file_path)\n\nfile_path = os.path.join(cur_dir, \"results\", \"autos.csv\")\ndf_autos_ = pd.read_csv(file_path)\ndf_autos = df_autos_[['city_mpg', 'fuel', 'drive', 'weight', 'hp']].dropna()\n\n\nclass CheckGAMMixin:\n\n @classmethod\n def _init(cls):\n # TODO: CyclicCubicSplines raises when using pandas\n cc_h = CyclicCubicSplines(np.asarray(data_mcycle['times']), df=[6])\n\n constraints = np.atleast_2d(cc_h.basis.mean(0))\n transf = transf_constraints(constraints)\n\n exog = cc_h.basis.dot(transf)\n penalty_matrix = transf.T.dot(cc_h.penalty_matrices[0]).dot(transf)\n restriction = matrix_sqrt(penalty_matrix)\n return exog, penalty_matrix, restriction\n\n def test_params(self):\n res1 = self.res1\n res2 = self.res2\n assert_allclose(res1.params, res2.params, rtol=1e-5)\n assert_allclose(np.asarray(res1.cov_params()),\n res2.Vp * self.covp_corrfact, rtol=1e-6, atol=1e-9)\n\n assert_allclose(res1.scale, res2.scale * self.covp_corrfact,\n rtol=1e-8)\n\n assert_allclose(np.asarray(res1.bse),\n res2.se * np.sqrt(self.covp_corrfact),\n rtol=1e-6, atol=1e-9)\n\n def test_fitted(self):\n res1 = self.res1\n res2 = self.res2\n assert_allclose(res1.fittedvalues, res2.fitted_values,\n rtol=self.rtol_fitted)\n\n @pytest.mark.smoke\n def test_null_smoke(self):\n self.res1.llnull\n\n\nclass TestTheilPLS5(CheckGAMMixin):\n\n cov_type = 'data-prior'\n\n @classmethod\n def setup_class(cls):\n exog, penalty_matrix, restriction = cls._init()\n endog = data_mcycle['accel']\n modp = TheilGLS(endog, exog, r_matrix=restriction)\n # scaling of penweith in R mgcv\n s_scale_r = 0.02630734\n # Theil penweight uses preliminary sigma2_e to scale penweight\n sigma_e = 1405.7950179165323\n cls.pw = pw = 1 / sigma_e / s_scale_r\n cls.res1 = modp.fit(pen_weight=pw, cov_type=cls.cov_type)\n cls.res2 = results_pls.pls5\n\n cls.rtol_fitted = 1e-7\n cls.covp_corrfact = 0.99786932844203202\n\n def test_cov_robust(self):\n res1 = self.res1\n res2 = self.res2\n pw = res1.penalization_factor\n res1 = res1.model.fit(pen_weight=pw, cov_type='sandwich')\n assert_allclose(np.asarray(res1.cov_params()),\n res2.Ve * self.covp_corrfact, rtol=1e-4)\n\n def test_null_smoke(self):\n pytest.skip(\"llnull not available\")\n\n\nclass TestGLMPenalizedPLS5(CheckGAMMixin):\n\n cov_type = 'nonrobust'\n\n @classmethod\n def setup_class(cls):\n exog, penalty_matrix, restriction = cls._init()\n endog = data_mcycle['accel']\n pen = smpen.L2ConstraintsPenalty(restriction=restriction)\n mod = GLMPenalized(endog, exog, family=family.Gaussian(),\n penal=pen)\n # scaling of penweight in R mgcv\n s_scale_r = 0.02630734\n # set pen_weight to correspond to R mgcv example\n cls.pw = mod.pen_weight = 1 / s_scale_r / 2\n cls.res1 = mod.fit(cov_type=cls.cov_type, method='bfgs', maxiter=100,\n disp=0, trim=False, scale='x2')\n cls.res2 = results_pls.pls5\n\n cls.rtol_fitted = 1e-5\n # edf is currently not available with PenalizedMixin\n # need correction for difference in scale denominator\n cls.covp_corrfact = 1.0025464444310588\n\n def _test_cov_robust(self):\n # TODO: HC0 differs from Theil sandwich, difference is large\n res1 = self.res1\n res2 = self.res2\n pw = res1.model.pen_weight\n res1 = res1.model.fit(pen_weight=pw, cov_type='HC0')\n assert_allclose(np.asarray(res1.cov_params()),\n res2.Ve * self.covp_corrfact, rtol=1e-4)\n\n\nclass TestGAM5Pirls(CheckGAMMixin):\n\n cov_type = 'nonrobust'\n\n @classmethod\n def setup_class(cls):\n s_scale = 0.0263073404164214\n\n x = data_mcycle['times'].values\n endog = data_mcycle['accel']\n cc = CyclicCubicSplines(x, df=[6], constraints='center')\n gam_cc = GLMGam(endog, smoother=cc, alpha=1 / s_scale / 2)\n cls.res1 = gam_cc.fit()\n cls.res2 = results_pls.pls5\n\n cls.rtol_fitted = 1e-12\n # cls.covp_corrfact = 1.0025464444310588 # without edf\n # edf is implemented\n cls.covp_corrfact = 1\n\n\nclass TestGAM5Bfgs(CheckGAMMixin):\n\n cov_type = 'nonrobust'\n\n @classmethod\n def setup_class(cls):\n s_scale = 0.0263073404164214\n\n x = data_mcycle['times'].values\n endog = data_mcycle['accel']\n cc = CyclicCubicSplines(x, df=[6], constraints='center')\n gam_cc = GLMGam(endog, smoother=cc, alpha=1 / s_scale / 2)\n cls.res1 = gam_cc.fit(method='bfgs')\n cls.res2 = results_pls.pls5\n\n cls.rtol_fitted = 1e-5\n # cls.covp_corrfact = 1.0025464444310588 # without edf\n # edf is implemented\n cls.covp_corrfact = 1\n\n def test_predict(self):\n res1 = self.res1\n res2 = self.res2\n predicted = res1.predict(None, res1.model.smoother.x[2:4])\n assert_allclose(predicted, res1.fittedvalues[2:4],\n rtol=1e-13)\n assert_allclose(predicted, res2.fitted_values[2:4],\n rtol=self.rtol_fitted)\n\n\nclass TestGAM6Pirls:\n\n @classmethod\n def setup_class(cls):\n s_scale = 0.0263073404164214\n\n cc = CyclicCubicSplines(data_mcycle['times'].values, df=[6])\n gam_cc = GLMGam(data_mcycle['accel'], smoother=cc,\n alpha=1 / s_scale / 2)\n cls.res1 = gam_cc.fit()\n\n def test_fitted(self):\n res1 = self.res1\n pred = res1.get_prediction()\n self.rtol_fitted = 1e-7\n pls6_fittedvalues = np.array([\n 2.45008146537851, 3.14145063965465, 5.24130119353225,\n 6.63476330674223, 7.99704341866374, 13.9351103077006,\n 14.5508371638833, 14.785647621276, 15.1176070735895,\n 14.8053514054347, 13.790412967255, 13.790412967255,\n 11.2997845518655, 9.51681958051473, 8.4811626302547])\n assert_allclose(res1.fittedvalues[:15], pls6_fittedvalues,\n rtol=self.rtol_fitted)\n assert_allclose(pred.predicted_mean[:15], pls6_fittedvalues,\n rtol=self.rtol_fitted)\n\n predicted = res1.predict(None, res1.model.smoother.x[2:4])\n assert_allclose(predicted, pls6_fittedvalues[2:4],\n rtol=self.rtol_fitted)\n\n\nclass TestGAM6Bfgs:\n\n @classmethod\n def setup_class(cls):\n s_scale = 0.0263073404164214\n\n cc = CyclicCubicSplines(data_mcycle['times'].values, df=[6])\n gam_cc = GLMGam(data_mcycle['accel'], smoother=cc,\n alpha=1 / s_scale / 2)\n cls.res1 = gam_cc.fit(method='bfgs')\n\n def test_fitted(self):\n res1 = self.res1\n pred = res1.get_prediction()\n self.rtol_fitted = 1e-5\n pls6_fittedvalues = np.array([\n 2.45008146537851, 3.14145063965465, 5.24130119353225,\n 6.63476330674223, 7.99704341866374, 13.9351103077006,\n 14.5508371638833, 14.785647621276, 15.1176070735895,\n 14.8053514054347, 13.790412967255, 13.790412967255,\n 11.2997845518655, 9.51681958051473, 8.4811626302547])\n assert_allclose(res1.fittedvalues[:15], pls6_fittedvalues,\n rtol=self.rtol_fitted)\n assert_allclose(pred.predicted_mean[:15], pls6_fittedvalues,\n rtol=self.rtol_fitted)\n\n\nclass TestGAM6Bfgs0:\n\n @classmethod\n def setup_class(cls):\n s_scale = 0.0263073404164214 # noqa: F841\n\n cc = CyclicCubicSplines(data_mcycle['times'].values, df=[6])\n gam_cc = GLMGam(data_mcycle['accel'], smoother=cc,\n alpha=0)\n cls.res1 = gam_cc.fit(method='bfgs')\n\n def test_fitted(self):\n res1 = self.res1\n pred = res1.get_prediction()\n self.rtol_fitted = 1e-5\n pls6_fittedvalues = np.array([\n 2.63203377595747, 3.41285892739456, 5.78168657308338,\n 7.35344779586831, 8.89178704316853, 15.7035642157176,\n 16.4510219628328, 16.7474993878412, 17.3397025587698,\n 17.1062522298643, 16.1786066072489, 16.1786066072489,\n 13.7402485937614, 11.9531909618517, 10.9073964111009])\n assert_allclose(res1.fittedvalues[:15], pls6_fittedvalues,\n rtol=self.rtol_fitted)\n assert_allclose(pred.predicted_mean[:15], pls6_fittedvalues,\n rtol=self.rtol_fitted)\n\n\npls6_fittedvalues = np.array([\n 2.45008146537851, 3.14145063965465, 5.24130119353225,\n 6.63476330674223, 7.99704341866374, 13.9351103077006,\n 14.5508371638833, 14.785647621276, 15.1176070735895,\n 14.8053514054347, 13.790412967255, 13.790412967255,\n 11.2997845518655, 9.51681958051473, 8.4811626302547])\n\npls6_exog = np.array([\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -0.334312615555276, -0.302733562622373,\n -0.200049479196403, -0.12607681525989, -0.0487229716135211,\n 0.397628373646056, 0.475396222437879, 0.51311526571058,\n 0.685638355361239, 0.745083051531164, -0.633518318499726,\n -0.634362488928233, -0.635472088268483, -0.634802453890957,\n -0.632796625534419, -0.589886140629009, -0.574834708734556,\n -0.566315983948608, -0.51289784236512, -0.486061743835595,\n -0.353449234316442, -0.348107090921062, -0.328814083307981,\n -0.313617048982477, -0.296913301955505, -0.191949693921079,\n -0.173001127145111, -0.163813487426548, -0.12229019995063,\n -0.108463798212062, -0.33613551740577, -0.327911471033406,\n -0.303620832999443, -0.287786799373968, -0.272279566127816,\n -0.194325957984873, -0.18175817334823, -0.175688807660186,\n -0.147654475500976, -0.137597948224942, -0.406564043706154,\n -0.409594429953082, -0.412391645561287, -0.409453786864986,\n -0.403086590828732, -0.322579243114146, -0.302545882788086,\n -0.29221622484174, -0.239207291311699, -0.218194346676734\n ]).reshape(10, 6, order='F')\n\n\nclass TestGAM6ExogBfgs:\n\n @classmethod\n def setup_class(cls):\n s_scale = 0.0263073404164214\n nobs = data_mcycle['times'].shape[0]\n cc = CyclicCubicSplines(data_mcycle['times'].values, df=[6],\n constraints='center')\n gam_cc = GLMGam(data_mcycle['accel'], np.ones(nobs),\n smoother=cc, alpha=1 / s_scale / 2)\n cls.res1 = gam_cc.fit(method='bfgs')\n\n def test_fitted(self):\n res1 = self.res1\n pred = res1.get_prediction()\n self.rtol_fitted = 1e-5\n\n assert_allclose(res1.fittedvalues[:15], pls6_fittedvalues,\n rtol=self.rtol_fitted)\n assert_allclose(pred.predicted_mean[:15], pls6_fittedvalues,\n rtol=self.rtol_fitted)\n\n def test_exog(self):\n exog = self.res1.model.exog\n assert_allclose(exog[:10], pls6_exog,\n rtol=1e-13)\n\n\nclass TestGAM6ExogPirls:\n\n @classmethod\n def setup_class(cls):\n s_scale = 0.0263073404164214\n nobs = data_mcycle['times'].shape[0]\n cc = CyclicCubicSplines(data_mcycle['times'].values, df=[6],\n constraints='center')\n gam_cc = GLMGam(data_mcycle['accel'], np.ones((nobs, 1)),\n smoother=cc, alpha=1 / s_scale / 2)\n cls.res1 = gam_cc.fit(method='pirls')\n\n def test_fitted(self):\n res1 = self.res1\n pred = res1.get_prediction()\n self.rtol_fitted = 1e-5\n\n assert_allclose(res1.fittedvalues[:15], pls6_fittedvalues,\n rtol=self.rtol_fitted)\n assert_allclose(pred.predicted_mean[:15], pls6_fittedvalues,\n rtol=self.rtol_fitted)\n\n def test_exog(self):\n exog = self.res1.model.exog\n assert_allclose(exog[:10], pls6_exog,\n rtol=1e-13)\n\n\nclass TestGAMMPG:\n\n @classmethod\n def setup_class(cls):\n\n sp = np.array([6.46225497484073, 0.81532465890585])\n s_scale = np.array([2.95973613706629e-07, 0.000126203730141359])\n\n x_spline = df_autos[['weight', 'hp']].values\n exog = patsy.dmatrix('fuel + drive', data=df_autos)\n cc = CyclicCubicSplines(x_spline, df=[6, 5], constraints='center')\n # TODO alpha needs to be list\n gam_cc = GLMGam(df_autos['city_mpg'], exog=exog, smoother=cc,\n alpha=(1 / s_scale * sp / 2).tolist())\n cls.res1a = gam_cc.fit()\n gam_cc = GLMGam(df_autos['city_mpg'], exog=exog, smoother=cc,\n alpha=(1 / s_scale * sp / 2).tolist())\n cls.res1b = gam_cc.fit(method='newton')\n\n def test_exog(self):\n file_path = os.path.join(cur_dir, \"results\", \"autos_exog.csv\")\n df_exog = pd.read_csv(file_path)\n res2_exog = df_exog.values\n for res1 in [self.res1a, self.res1b]:\n exog = res1.model.exog\n # exog contains zeros\n assert_allclose(exog, res2_exog, atol=1e-14)\n\n def test_fitted(self):\n file_path = os.path.join(cur_dir, \"results\", \"autos_predict.csv\")\n df_pred = pd.read_csv(file_path, index_col=\"Row.names\")\n df_pred.index = df_pred.index - 1\n res2_fittedvalues = df_pred[\"fit\"].values\n res2_se_mean = df_pred[\"se_fit\"].values\n for res1 in [self.res1a, self.res1b]:\n pred = res1.get_prediction()\n self.rtol_fitted = 1e-5\n\n assert_allclose(res1.fittedvalues, res2_fittedvalues,\n rtol=1e-10)\n assert_allclose(pred.predicted_mean, res2_fittedvalues,\n rtol=1e-10)\n\n # TODO: no edf, edf corrected df_resid\n # scale estimate differs\n # corr_fact = np.sqrt(191.669417019567 / 190) # without edf\n # edf is implemented\n corr_fact = 1\n assert_allclose(pred.se_mean, res2_se_mean * corr_fact, rtol=1e-10)\n\n\nclass TestGAMMPGBS(CheckGAMMixin):\n # This has matching results from mgcv\n\n @classmethod\n def setup_class(cls):\n\n sp = np.array([0.830689464223685, 425.361212061649])\n cls.s_scale = s_scale = np.array([2.443955e-06, 0.007945455])\n\n x_spline = df_autos[['weight', 'hp']].values\n # We need asarray to remove the design_info\n # If design_info is attached,\n # then exog_linear will also be transformed in predict.\n cls.exog = np.asarray(patsy.dmatrix('fuel + drive', data=df_autos))\n bs = BSplines(x_spline, df=[12, 10], degree=[3, 3],\n variable_names=['weight', 'hp'],\n constraints='center',\n include_intercept=True)\n # TODO alpha needs to be list\n alpha0 = 1 / s_scale * sp / 2\n gam_bs = GLMGam(df_autos['city_mpg'], exog=cls.exog, smoother=bs,\n alpha=(alpha0).tolist())\n cls.res1a = gam_bs.fit(use_t=True)\n\n cls.res1b = gam_bs.fit(method='newton', use_t=True)\n cls.res1 = cls.res1a._results\n cls.res2 = results_mpg_bs.mpg_bs\n\n cls.rtol_fitted = 1e-8\n cls.covp_corrfact = 1 # not needed\n\n # for checking that alpha model attribute is unchanged, same as alpha0\n cls.alpha = [169947.78222669504, 26767.58046340008]\n\n @classmethod\n def _init(cls):\n pass\n\n def test_edf(self):\n res1 = self.res1\n res2 = self.res2\n assert_allclose(res1.edf, res2.edf_all, rtol=1e-6)\n hat = res1.get_hat_matrix_diag()\n assert_allclose(hat, res2.hat, rtol=1e-6)\n\n def test_smooth(self):\n res1 = self.res1\n res2 = self.res2\n smoothers = res1.model.smoother.smoothers\n pen_matrix0 = smoothers[0].cov_der2\n assert_allclose(pen_matrix0, res2.smooth0.S * res2.smooth0.S_scale,\n rtol=1e-6)\n\n def test_predict(self):\n res1 = self.res1\n res2 = self.res2\n predicted = res1.predict(self.exog[2:4], res1.model.smoother.x[2:4])\n assert_allclose(predicted, res1.fittedvalues[2:4],\n rtol=1e-13)\n assert_allclose(predicted, res2.fitted_values[2:4],\n rtol=self.rtol_fitted)\n\n def test_crossval(self):\n # includes some checks that penalization in the model is unchanged\n mod = self.res1.model\n assert_equal(mod.alpha, self.alpha) # assert unchanged\n assert_allclose(self.res1.scale, 4.7064821354391118, rtol=1e-13)\n\n alpha_aic = mod.select_penweight()[0]\n # regression number, but in the right ball park\n assert_allclose(alpha_aic, [112487.81362014, 129.89155677], rtol=1e-3)\n assert_equal(mod.alpha, self.alpha) # assert unchanged\n assert_equal(mod.penal.start_idx, 4)\n pm = mod.penal.penalty_matrix()\n assert_equal(pm[:, :4], 0)\n assert_equal(pm[:4, :], 0)\n assert_allclose(self.res1.scale, 4.7064821354391118, rtol=1e-13)\n\n np.random.seed(987125)\n alpha_cv, _ = mod.select_penweight_kfold(k_folds=3, k_grid=6)\n # regression number, but in the right ball park\n assert_allclose(alpha_cv, [10000000.0, 630.957344480193], rtol=1e-5)\n assert_equal(mod.alpha, self.alpha) # assert unchanged\n assert_equal(mod.penal.start_idx, 4)\n pm = mod.penal.penalty_matrix()\n assert_equal(pm[:, :4], 0)\n assert_equal(pm[:4, :], 0)\n assert_allclose(self.res1.scale, 4.7064821354391118, rtol=1e-13)\n\n\nclass TestGAMMPGBSPoisson(CheckGAMMixin):\n # This has matching results from mgcv\n\n @classmethod\n def setup_class(cls):\n\n sp = np.array([40491.3940640059, 232455.530262537])\n # s_scale is same as before\n cls.s_scale = s_scale = np.array([2.443955e-06, 0.007945455])\n\n x_spline = df_autos[['weight', 'hp']].values\n cls.exog = patsy.dmatrix('fuel + drive', data=df_autos)\n bs = BSplines(x_spline, df=[12, 10], degree=[3, 3],\n variable_names=['weight', 'hp'],\n constraints='center',\n include_intercept=True)\n # TODO alpha needs to be list\n alpha0 = 1 / s_scale * sp / 2\n gam_bs = GLMGam(df_autos['city_mpg'], exog=cls.exog, smoother=bs,\n family=family.Poisson(), alpha=alpha0)\n\n xnames = cls.exog.design_info.column_names + gam_bs.smoother.col_names\n gam_bs.exog_names[:] = xnames\n cls.res1a = gam_bs.fit(use_t=False)\n\n cls.res1b = gam_bs.fit(method='newton', use_t=True)\n cls.res1 = cls.res1a._results\n cls.res2 = results_mpg_bs_poisson.mpg_bs_poisson\n\n cls.rtol_fitted = 1e-8\n cls.covp_corrfact = 1 # not needed\n\n @classmethod\n def _init(cls):\n pass\n\n def test_edf(self):\n res1 = self.res1\n res2 = self.res2\n assert_allclose(res1.edf, res2.edf_all, rtol=1e-6)\n hat = res1.get_hat_matrix_diag()\n assert_allclose(hat, res2.hat, rtol=1e-6)\n assert_allclose(res1.aic, res2.aic, rtol=1e-8)\n assert_allclose(res1.deviance, res2.deviance, rtol=1e-8)\n assert_allclose(res1.df_resid, res2.residual_df, rtol=1e-8)\n\n def test_smooth(self):\n res1 = self.res1\n res2 = self.res2\n\n smoothers = res1.model.smoother.smoothers\n pen_matrix0 = smoothers[0].cov_der2\n assert_allclose(pen_matrix0, res2.smooth0.S * res2.smooth0.S_scale,\n rtol=1e-6)\n\n def test_predict(self):\n res1 = self.res1\n res2 = self.res2\n # this uses transform also for exog_linear\n # predicted = res1.predict(self.exog[2:4], res1.model.smoother.x[2:4])\n predicted = res1.predict(df_autos.iloc[2:4],\n res1.model.smoother.x[2:4])\n assert_allclose(predicted, res1.fittedvalues[2:4],\n rtol=1e-13)\n assert_allclose(predicted, res2.fitted_values[2:4],\n rtol=self.rtol_fitted)\n\n # linpred = res1.predict(self.exog[2:4], res1.model.smoother.x[2:4],\n # linear=True)\n xp = pd.DataFrame(res1.model.smoother.x[2:4])\n linpred = res1.predict(df_autos.iloc[2:4], xp,\n linear=True)\n assert_allclose(linpred, res2.linear_predictors[2:4],\n rtol=self.rtol_fitted)\n\n assert_equal(predicted.index.values, [2, 3])\n assert_equal(linpred.index.values, [2, 3])\n\n def test_wald(self):\n res1 = self.res1\n res2 = self.res2\n wtt = res1.wald_test_terms(skip_single=True,\n combine_terms=['fuel', 'drive',\n 'weight', 'hp'],\n scalar=True)\n # mgcv has term test for linear part\n assert_allclose(wtt.statistic[:2], res2.pTerms_chi_sq, rtol=1e-7)\n assert_allclose(wtt.pvalues[:2], res2.pTerms_pv, rtol=1e-6)\n assert_equal(wtt.df_constraints[:2], res2.pTerms_df)\n\n def test_select_alpha(self):\n res1 = self.res1\n alpha_mgcv = res1.model.alpha\n res_s = res1.model.select_penweight()\n assert_allclose(res_s[0], alpha_mgcv, rtol=5e-5)\n\n\nclass TestGAMMPGBSPoissonFormula(TestGAMMPGBSPoisson):\n # This is the same as the previous but with from_formula\n\n @classmethod\n def setup_class(cls):\n\n sp = np.array([40491.3940640059, 232455.530262537])\n # s_scale is same as before\n cls.s_scale = s_scale = np.array([2.443955e-06, 0.007945455])\n\n cls.exog = patsy.dmatrix('fuel + drive', data=df_autos)\n\n x_spline = df_autos[['weight', 'hp']].values\n bs = BSplines(x_spline, df=[12, 10], degree=[3, 3],\n variable_names=['weight', 'hp'],\n constraints='center',\n include_intercept=True)\n\n alpha0 = 1 / s_scale * sp / 2\n gam_bs = GLMGam.from_formula('city_mpg ~ fuel + drive', df_autos,\n smoother=bs, family=family.Poisson(),\n alpha=alpha0)\n\n cls.res1a = gam_bs.fit(use_t=False)\n\n cls.res1b = gam_bs.fit(method='newton', use_t=True)\n cls.res1 = cls.res1a._results\n cls.res2 = results_mpg_bs_poisson.mpg_bs_poisson\n\n cls.rtol_fitted = 1e-8\n cls.covp_corrfact = 1 # not needed\n\n def test_names_wrapper(self):\n res1a = self.res1a\n xnames = ['Intercept', 'fuel[T.gas]', 'drive[T.fwd]', 'drive[T.rwd]',\n 'weight_s0', 'weight_s1', 'weight_s2', 'weight_s3',\n 'weight_s4', 'weight_s5', 'weight_s6', 'weight_s7',\n 'weight_s8', 'weight_s9', 'weight_s10',\n 'hp_s0', 'hp_s1', 'hp_s2', 'hp_s3', 'hp_s4', 'hp_s5',\n 'hp_s6', 'hp_s7', 'hp_s8']\n\n assert_equal(res1a.model.exog_names, xnames)\n assert_equal(res1a.model.design_info_linear.column_names,\n xnames[:4])\n\n assert_equal(res1a.fittedvalues.iloc[2:4].index.values, [2, 3])\n assert_equal(res1a.params.index.values, xnames)\n assert_(isinstance(res1a.params, pd.Series))\n\n assert_(isinstance(res1a, GLMGamResultsWrapper))\n assert_(isinstance(res1a._results, GLMGamResults))\n",
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 05 17:29:56 2014\n\nAuthor: Josef Perktold\n\"\"\"\n\nimport os\n\nimport numpy as np\nimport pandas as pd\nimport pytest\n\nfrom numpy.testing import assert_allclose\n\nfrom statsmodels.regression.linear_model import OLS, GLS\n\nfrom statsmodels.sandbox.regression.penalized import TheilGLS\n\n\nclass TestTheilTextile:\n\n @classmethod\n def setup_class(cls):\n\n cur_dir = os.path.dirname(os.path.abspath(__file__))\n filepath = os.path.join(cur_dir, \"results\",\n \"theil_textile_predict.csv\")\n cls.res_predict = pd.read_csv(filepath, sep=\",\")\n\n names = \"year\tlconsump\tlincome\tlprice\".split()\n\n data = np.array('''\\\n 1923\t1.99651\t1.98543\t2.00432\n 1924\t1.99564\t1.99167\t2.00043\n 1925\t2\t2\t2\n 1926\t2.04766\t2.02078\t1.95713\n 1927\t2.08707\t2.02078\t1.93702\n 1928\t2.07041\t2.03941\t1.95279\n 1929\t2.08314\t2.04454\t1.95713\n 1930\t2.13354\t2.05038\t1.91803\n 1931\t2.18808\t2.03862\t1.84572\n 1932\t2.18639\t2.02243\t1.81558\n 1933\t2.20003\t2.00732\t1.78746\n 1934\t2.14799\t1.97955\t1.79588\n 1935\t2.13418\t1.98408\t1.80346\n 1936\t2.22531\t1.98945\t1.72099\n 1937\t2.18837\t2.0103\t1.77597\n 1938\t2.17319\t2.00689\t1.77452\n 1939\t2.2188\t2.0162\t1.78746'''.split(), float).reshape(-1, 4)\n\n\n endog = data[:, 1]\n # constant at the end to match Stata\n exog = np.column_stack((data[:, 2:], np.ones(endog.shape[0])))\n\n #prior(lprice -0.7 0.15 lincome 1 0.15) cov(lprice lincome -0.01)\n r_matrix = np.array([[1, 0, 0], [0, 1, 0]])\n r_mean = [1, -0.7]\n\n cov_r = np.array([[0.15**2, -0.01], [-0.01, 0.15**2]])\n mod = TheilGLS(endog, exog, r_matrix, q_matrix=r_mean, sigma_prior=cov_r)\n cls.res1 = mod.fit(cov_type='data-prior', use_t=True)\n #cls.res1._cache['scale'] = 0.0001852252884817586 # from tg_mixed\n cls.res1._cache['scale'] = 0.00018334123641580062 # from OLS\n from .results import results_theil_textile as resmodule\n cls.res2 = resmodule.results_theil_textile\n\n\n def test_basic(self):\n pt = self.res2.params_table[:,:6].T\n params2, bse2, tvalues2, pvalues2, ci_low, ci_upp = pt\n assert_allclose(self.res1.params, params2, rtol=2e-6)\n\n #TODO tgmixed seems to use scale from initial OLS, not from final res\n # np.sqrt(res.scale / res_ols.scale)\n # see below mse_resid which is equal to scale\n corr_fact = 0.9836026210570028\n corr_fact = 0.97376865041463734\n corr_fact = 1\n assert_allclose(self.res1.bse / corr_fact, bse2, rtol=2e-6)\n assert_allclose(self.res1.tvalues * corr_fact, tvalues2, rtol=2e-6)\n # pvalues are very small\n #assert_allclose(self.res1.pvalues, pvalues2, atol=2e-6)\n #assert_allclose(self.res1.pvalues, pvalues2, rtol=0.7)\n ci = self.res1.conf_int()\n # not scale corrected\n assert_allclose(ci[:,0], ci_low, rtol=0.01)\n assert_allclose(ci[:,1], ci_upp, rtol=0.01)\n assert_allclose(self.res1.rsquared, self.res2.r2, rtol=2e-6)\n\n # Note: tgmixed is using k_exog for df_resid\n corr_fact = self.res1.df_resid / self.res2.df_r\n assert_allclose(np.sqrt(self.res1.mse_resid * corr_fact),\n self.res2.rmse, rtol=2e-6)\n\n assert_allclose(self.res1.fittedvalues,\n self.res_predict['fittedvalues'], atol=5e7)\n\n def test_other(self):\n tc = self.res1.test_compatibility()\n assert_allclose(np.squeeze(tc[0]), self.res2.compat, rtol=2e-6)\n assert_allclose(np.squeeze(tc[1]), self.res2.pvalue, rtol=2e-6)\n\n frac = self.res1.share_data()\n # TODO check again, I guess tgmixed uses final scale in hatmatrix\n # but I'm not sure, it passed in previous version, but now we override\n # scale with OLS scale\n # assert_allclose(frac, self.res2.frac_sample, rtol=2e-6)\n # regression tests:\n assert_allclose(frac, 0.6946116246864239, rtol=2e-6)\n\n\n def test_no_penalization(self):\n res_ols = OLS(self.res1.model.endog, self.res1.model.exog).fit()\n res_theil = self.res1.model.fit(pen_weight=0, cov_type='data-prior')\n assert_allclose(res_theil.params, res_ols.params, rtol=1e-10)\n assert_allclose(res_theil.bse, res_ols.bse, rtol=1e-10)\n\n @pytest.mark.smoke\n def test_summary(self):\n with pytest.warns(UserWarning):\n self.res1.summary()\n\n\nclass CheckEquivalenceMixin:\n\n tol = {'default': (1e-4, 1e-20)}\n\n @classmethod\n def get_sample(cls):\n np.random.seed(987456)\n nobs, k_vars = 200, 5\n beta = 0.5 * np.array([0.1, 1, 1, 0, 0])\n x = np.random.randn(nobs, k_vars)\n x[:, 0] = 1\n y = np.dot(x, beta) + 2 * np.random.randn(nobs)\n return y, x\n\n def test_attributes(self):\n\n attributes_fit = ['params', 'rsquared', 'df_resid', 'df_model',\n 'llf', 'aic', 'bic'\n #'fittedvalues', 'resid'\n ]\n attributes_inference = ['bse', 'tvalues', 'pvalues']\n import copy\n attributes = copy.copy(attributes_fit)\n\n if not getattr(self, 'skip_inference', False):\n attributes.extend(attributes_inference)\n\n for att in attributes:\n r1 = getattr(self.res1, att)\n r2 = getattr(self.res2, att)\n if not np.size(r1) == 1:\n r1 = r1[:len(r2)]\n\n # check if we have overwritten tolerance\n rtol, atol = self.tol.get(att, self.tol['default'])\n message = 'attribute: ' + att #+ '\\n%r\\n\\%r' % (r1, r2)\n assert_allclose(r1, r2, rtol=rtol, atol=atol, err_msg=message)\n\n # models are not close enough for some attributes at high precision\n assert_allclose(self.res1.fittedvalues, self.res1.fittedvalues,\n rtol=1e-3, atol=1e-4)\n assert_allclose(self.res1.resid, self.res1.resid,\n rtol=1e-3, atol=1e-4)\n\n\nclass TestTheil1(CheckEquivalenceMixin):\n # penalize last two parameters to zero\n\n @classmethod\n def setup_class(cls):\n y, x = cls.get_sample()\n mod1 = TheilGLS(y, x, sigma_prior=[0, 0, 1., 1.])\n cls.res1 = mod1.fit(200000)\n cls.res2 = OLS(y, x[:, :3]).fit()\n\nclass TestTheil2(CheckEquivalenceMixin):\n # no penalization = same as OLS\n\n @classmethod\n def setup_class(cls):\n y, x = cls.get_sample()\n mod1 = TheilGLS(y, x, sigma_prior=[0, 0, 1., 1.])\n cls.res1 = mod1.fit(0)\n cls.res2 = OLS(y, x).fit()\n\n\nclass TestTheil3(CheckEquivalenceMixin):\n # perfect multicollinearity = same as OLS in terms of fit\n # inference: bse, ... is different\n\n @classmethod\n def setup_class(cls):\n cls.skip_inference = True\n y, x = cls.get_sample()\n xd = np.column_stack((x, x))\n #sp = np.zeros(5), np.ones(5)\n r_matrix = np.eye(5, 10, 5)\n mod1 = TheilGLS(y, xd, r_matrix=r_matrix) #sigma_prior=[0, 0, 1., 1.])\n cls.res1 = mod1.fit(0.001, cov_type='data-prior')\n cls.res2 = OLS(y, x).fit()\n\n\nclass TestTheilGLS(CheckEquivalenceMixin):\n # penalize last two parameters to zero\n\n @classmethod\n def setup_class(cls):\n y, x = cls.get_sample()\n nobs = len(y)\n weights = (np.arange(nobs) < (nobs // 2)) + 0.5\n mod1 = TheilGLS(y, x, sigma=weights, sigma_prior=[0, 0, 1., 1.])\n cls.res1 = mod1.fit(200000)\n cls.res2 = GLS(y, x[:, :3], sigma=weights).fit()\n\n\nclass TestTheilLinRestriction(CheckEquivalenceMixin):\n # impose linear restriction with small uncertainty - close to OLS\n\n @classmethod\n def setup_class(cls):\n y, x = cls.get_sample()\n #merge var1 and var2\n x2 = x[:, :2].copy()\n x2[:, 1] += x[:, 2]\n #mod1 = TheilGLS(y, x, r_matrix =[[0, 1, -1, 0, 0]])\n mod1 = TheilGLS(y, x[:, :3], r_matrix =[[0, 1, -1]])\n cls.res1 = mod1.fit(200000)\n cls.res2 = OLS(y, x2).fit()\n\n # adjust precision, careful: cls.tol is mutable\n tol = {'pvalues': (1e-4, 2e-7),\n 'tvalues': (5e-4, 0)}\n tol.update(cls.tol)\n cls.tol = tol\n\n\nclass TestTheilLinRestrictionApprox(CheckEquivalenceMixin):\n # impose linear restriction with some uncertainty\n\n @classmethod\n def setup_class(cls):\n y, x = cls.get_sample()\n #merge var1 and var2\n x2 = x[:, :2].copy()\n x2[:, 1] += x[:, 2]\n #mod1 = TheilGLS(y, x, r_matrix =[[0, 1, -1, 0, 0]])\n mod1 = TheilGLS(y, x[:, :3], r_matrix =[[0, 1, -1]])\n cls.res1 = mod1.fit(100)\n cls.res2 = OLS(y, x2).fit()\n\n # adjust precision, careful: cls.tol is mutable\n import copy\n tol = copy.copy(cls.tol)\n tol2 = {'default': (0.15, 0),\n 'params': (0.05, 0),\n 'pvalues': (0.02, 0.001),\n }\n tol.update(tol2)\n cls.tol = tol\n\n\nclass TestTheilPanel:\n\n @classmethod\n def setup_class(cls):\n #example 3\n nobs = 300\n nobs_i = 5\n n_groups = nobs // nobs_i\n k_vars = 3\n\n from statsmodels.sandbox.panel.random_panel import PanelSample\n dgp = PanelSample(nobs, k_vars, n_groups, seed=303305)\n # add random intercept, using same RandomState\n dgp.group_means = 2 + dgp.random_state.randn(n_groups)\n print('seed', dgp.seed)\n y = dgp.generate_panel()\n x = np.column_stack((dgp.exog[:,1:],\n dgp.groups[:,None] == np.arange(n_groups)))\n cls.dgp = dgp\n cls.endog = y\n cls.exog = x\n cls.res_ols = OLS(y, x).fit()\n\n def test_regression(self):\n y = self.endog\n x = self.exog\n n_groups, k_vars = self.dgp.n_groups, self.dgp.k_vars\n\n Rg = (np.eye(n_groups-1) - 1. / n_groups *\n np.ones((n_groups - 1, n_groups-1)))\n R = np.c_[np.zeros((n_groups - 1, k_vars)), Rg]\n r = np.zeros(n_groups - 1)\n R[:, k_vars-1] = -1\n\n lambd = 1 #1e-4\n mod = TheilGLS(y, x, r_matrix=R, q_matrix=r, sigma_prior=lambd)\n res = mod.fit()\n\n # regression test\n params1 = np.array([\n 0.9751655 , 1.05215277, 0.37135028, 2.0492626 , 2.82062503,\n 2.82139775, 1.92940468, 2.96942081, 2.86349583, 3.20695368,\n 4.04516422, 3.04918839, 4.54748808, 3.49026961, 3.15529618,\n 4.25552932, 2.65471759, 3.62328747, 3.07283053, 3.49485898,\n 3.42301424, 2.94677593, 2.81549427, 2.24895113, 2.29222784,\n 2.89194946, 3.17052308, 2.37754241, 3.54358533, 3.79838425,\n 1.91189071, 1.15976407, 4.05629691, 1.58556827, 4.49941666,\n 4.08608599, 3.1889269 , 2.86203652, 3.06785013, 1.9376162 ,\n 2.90657681, 3.71910592, 3.15607617, 3.58464547, 2.15466323,\n 4.87026717, 2.92909833, 2.64998337, 2.891171 , 4.04422964,\n 3.54616122, 4.12135273, 3.70232028, 3.8314497 , 2.2591451 ,\n 2.39321422, 3.13064532, 2.1569678 , 2.04667506, 3.92064689,\n 3.66243644, 3.11742725])\n assert_allclose(res.params, params1)\n\n pen_weight_aicc = mod.select_pen_weight(method='aicc')\n pen_weight_gcv = mod.select_pen_weight(method='gcv')\n pen_weight_cv = mod.select_pen_weight(method='cv')\n pen_weight_bic = mod.select_pen_weight(method='bic')\n assert_allclose(pen_weight_gcv, pen_weight_aicc, rtol=0.1)\n # regression tests:\n assert_allclose(pen_weight_aicc, 4.77333984, rtol=1e-4)\n assert_allclose(pen_weight_gcv, 4.45546875, rtol=1e-4)\n assert_allclose(pen_weight_bic, 9.35957031, rtol=1e-4)\n assert_allclose(pen_weight_cv, 1.99277344, rtol=1e-4)\n\n def test_combine_subset_regression(self):\n # split sample into two, use first sample as prior for second\n endog = self.endog\n exog = self.exog\n nobs = len(endog)\n\n n05 = nobs // 2\n np.random.seed(987125)\n # shuffle to get random subsamples\n shuffle_idx = np.random.permutation(np.arange(nobs))\n ys = endog[shuffle_idx]\n xs = exog[shuffle_idx]\n k = 10\n res_ols0 = OLS(ys[:n05], xs[:n05, :k]).fit()\n res_ols1 = OLS(ys[n05:], xs[n05:, :k]).fit()\n\n w = res_ols1.scale / res_ols0.scale #1.01\n mod_1 = TheilGLS(ys[n05:], xs[n05:, :k], r_matrix=np.eye(k),\n q_matrix=res_ols0.params,\n sigma_prior=w * res_ols0.cov_params())\n res_1p = mod_1.fit(cov_type='data-prior')\n res_1s = mod_1.fit(cov_type='sandwich')\n res_olsf = OLS(ys, xs[:, :k]).fit()\n\n assert_allclose(res_1p.params, res_olsf.params, rtol=1e-9)\n corr_fact = np.sqrt(res_1p.scale / res_olsf.scale)\n # corrct for differences in scale computation\n assert_allclose(res_1p.bse, res_olsf.bse * corr_fact, rtol=1e-3)\n\n # regression test, does not verify numbers\n # especially why are these smaller than OLS on full sample\n # in larger sample, nobs=600, those were close to full OLS\n bse1 = np.array([\n 0.26589869, 0.15224812, 0.38407399, 0.75679949, 0.66084200,\n 0.54174080, 0.53697607, 0.66006377, 0.38228551, 0.53920485])\n assert_allclose(res_1s.bse, bse1, rtol=1e-7)\n"
] | [
[
"numpy.linalg.svd",
"numpy.sqrt",
"numpy.power",
"numpy.min",
"numpy.array",
"scipy.stats.f.sf"
],
[
"numpy.testing.assert_equal",
"pandas.Series",
"numpy.random.seed",
"numpy.arange",
"numpy.testing.assert_raises",
"numpy.random.randint"
],
[
"numpy.diag",
"numpy.testing.assert_equal",
"numpy.log",
"numpy.random.seed",
"numpy.arange",
"pandas.Index",
"pandas.DataFrame",
"numpy.ones",
"pandas.DatetimeIndex",
"numpy.random.normal",
"numpy.testing.assert_raises",
"pandas.date_range",
"pandas.read_stata",
"numpy.array",
"numpy.zeros",
"numpy.testing.assert_allclose"
],
[
"numpy.array",
"numpy.log",
"numpy.take",
"numpy.linspace",
"numpy.clip",
"numpy.asarray",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.step",
"matplotlib.pyplot.xlim",
"scipy.interpolate.interp1d",
"numpy.searchsorted",
"numpy.argsort",
"matplotlib.pyplot.vlines",
"matplotlib.pyplot.show",
"numpy.loadtxt"
],
[
"matplotlib.use",
"pandas.io.formats.printing.pprint_thing",
"matplotlib.rc"
],
[
"numpy.diag",
"numpy.sqrt",
"matplotlib.pyplot.plot",
"numpy.exp",
"numpy.ones_like",
"numpy.allclose",
"scipy.integrate.trapz",
"numpy.eye",
"numpy.zeros",
"matplotlib.pyplot.figure",
"numpy.log",
"matplotlib.pyplot.title",
"scipy.special.gammaln",
"scipy.integrate.quad",
"matplotlib.pyplot.show",
"matplotlib.pyplot.hist",
"numpy.cos",
"scipy.special.chebyt",
"scipy.special.hermite",
"numpy.empty"
],
[
"numpy.testing.assert_equal",
"numpy.log",
"numpy.random.seed",
"pandas.date_range",
"numpy.arange",
"pandas.Index",
"pandas.DataFrame",
"numpy.ones",
"numpy.random.normal",
"numpy.testing.assert_raises",
"numpy.testing.assert_allclose",
"numpy.array"
],
[
"numpy.random.seed",
"numpy.arange",
"pandas.DataFrame",
"numpy.ones",
"numpy.random.normal",
"numpy.testing.assert_allclose",
"numpy.random.randint"
],
[
"numpy.testing.assert_equal",
"pandas.read_csv",
"numpy.sqrt",
"numpy.random.seed",
"numpy.asarray",
"pandas.DataFrame",
"numpy.ones",
"numpy.testing.assert_allclose",
"numpy.array"
],
[
"numpy.dot",
"pandas.read_csv",
"numpy.sqrt",
"numpy.random.seed",
"numpy.arange",
"numpy.eye",
"numpy.squeeze",
"numpy.ones",
"numpy.size",
"numpy.random.randn",
"numpy.testing.assert_allclose",
"numpy.array",
"numpy.zeros",
"numpy.column_stack"
]
] | [
{
"matplotlib": [],
"numpy": [],
"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": []
},
{
"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": [],
"scipy": [
"0.13",
"1.6",
"0.14",
"1.10",
"0.15",
"1.4",
"0.16",
"1.9",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"1.0",
"0.17",
"1.3",
"1.8"
],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"0.14",
"0.15",
"1.4",
"0.10",
"1.3",
"0.19",
"0.18",
"1.2",
"0.12",
"1.0",
"0.17",
"0.16"
],
"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": []
},
{
"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.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": []
}
] |
rongtianjie/dcraw_py | [
"fd45d819a67d2f52d7ca61abbe145ab1b172bee9"
] | [
"demosaic_pack/amaze_demosaic.py"
] | [
"import numpy as np\n \ndef amaze_demosaic(src, raw):\n\n cfarray = raw.raw_colors\n cfarray[cfarray == 3] = 1\n\n rgb = amaze_demosaic_libraw(src, cfarray, raw.daylight_whitebalance)\n\n return rgb\n\ndef amaze_demosaic_libraw(src, cfarray, daylight_wb):\n\n TS = 512\n winx = winy = 0\n width = src.shape[1]\n height = src.shape[0]\n image = np.empty([height, width, 3], dtype=np.uint16)\n clip_pt = min(daylight_wb[0], daylight_wb[1], daylight_wb[2])\n\n v1 = TS\n v2 = 2 * TS\n v3 = 3 * TS\n p1 = -TS + 1\n p2 = -2 * TS + 2\n p3 = -3 * TS + 3\n m1 = TS + 1 \n m2 = 2 * TS + 2\n m3 = 3 * TS + 3\n\n nbr = [-v2,-2,2,v2,0]\n eps, epssq = 1e-5, 1e-10\n\n # adaptive ratios threshold\n arthresh=0.75\n # nyquist texture test threshold\n nyqthresh=0.5\n # diagonal interpolation test threshold\n pmthresh=0.25\n # factors for bounding interpolation in saturated regions\n lbd, ubd = 1, 1 # lbd=0.66, ubd=1.5 alternative values;\n\n # gaussian on 5x5 quincunx, sigma=1.2\n gaussodd = [0.14659727707323927, 0.103592713382435, 0.0732036125103057, 0.0365543548389495]\n # gaussian on 5x5, sigma=1.2\n gaussgrad = [0.07384411893421103, 0.06207511968171489, 0.0521818194747806, 0.03687419286733595, 0.03099732204057846, 0.018413194161458882]\n # gaussian on 3x3, sigma =0.7\n gauss1 = [0.3376688223162362, 0.12171198028231786, 0.04387081413862306]\n # gaussian on 5x5 alt quincunx, sigma=1.5\n gausseven = [0.13719494435797422, 0.05640252782101291]\n # guassian on quincunx grid\n gquinc = [0.169917, 0.108947, 0.069855, 0.0287182]\n\n\n rgb = np.empty([TS*TS, 3], dtype=np.float32)\n delh = np.empty(TS*TS, dtype=np.float32)\n delv = np.empty(TS*TS, dtype=np.float32)\n delhsq = np.empty(TS*TS, dtype=np.float32)\n delvsq = np.empty(TS*TS, dtype=np.float32)\n dirwts = np.empty([TS*TS, 2], dtype=np.float32)\n vcd = np.empty(TS*TS, dtype=np.float32)\n hcd = np.empty(TS*TS, dtype=np.float32)\n vcdalt = np.empty(TS*TS, dtype=np.float32)\n hcdalt = np.empty(TS*TS, dtype=np.float32)\n vcdsq = np.empty(TS*TS, dtype=np.float32)\n hcdsq = np.empty(TS*TS, dtype=np.float32)\n cddiffsq = np.empty(TS*TS, dtype=np.float32)\n hvwt = np.empty(TS*TS, dtype=np.float32)\n Dgrb = np.empty([TS*TS, 2], dtype=np.float32)\n delp = np.empty(TS*TS, dtype=np.float32)\n delm = np.empty(TS*TS, dtype=np.float32)\n rbint = np.empty(TS*TS, dtype=np.float32)\n Dgrbh2 = np.empty(TS*TS, dtype=np.float32)\n Dgrbv2 = np.empty(TS*TS, dtype=np.float32)\n dgintv = np.empty(TS*TS, dtype=np.float32)\n dginth = np.empty(TS*TS, dtype=np.float32)\n Dgrbpsq1 = np.empty(TS*TS, dtype=np.float32)\n Dgrbmsq1 = np.empty(TS*TS, dtype=np.float32)\n cfa = np.empty(TS*TS, dtype=np.float32)\n pmwt = np.empty(TS*TS, dtype=np.float32)\n rbp = np.empty(TS*TS, dtype=np.float32)\n rbm = np.empty(TS*TS, dtype=np.float32)\n\n nyquist = np.empty(TS*TS, dtype=np.int32)\n\n # determine GRBG coset; (ey,ex) is the offset of the R subarray\n if cfarray[0][0] == 1:\n if cfarray[0][1] == 0:\n ex, ey = 1, 0\n else:\n ex, ey = 0, 1\n else:\n if cfarray[0][0] == 0:\n ex = ey = 0\n else: \n ex = ey = 1\n \n # Start main loop\n loop_cnt = 1 \n for top in range(winy-16, winy+height, TS-32):\n for left in range(winx-16, winx+width, TS-32):\n print(\"Loop [{}]: top: {} left: {}\".format(loop_cnt, top, left))\n loop_cnt += 1\n # location of tile bottom edge\n bottom = min(top+TS, winy+height+16)\n # location of tile right edge\n right = min(left+TS, winx+width+16)\n # tile width (=TS except for right edge of image)\n rr1 = bottom - top\n # tile height (=TS except for bottom edge of image)\n cc1 = right - left\n \n # rgb from input CFA data\n # rgb values should be floating point number between 0 and 1 \n # after white balance multipliers are applied \n # a 16 pixel border is added to each side of the image\n\n # bookkeeping for borders\n rrmin = 16 if top < winy else 0\n ccmin = 16 if left < winx else 0\n rrmax = winy+height-top if bottom>(winy+height) else rr1\n ccmax = winx+width-left if right>(winx+width) else cc1\n\n for rr in range(rrmin, rrmax):\n row = rr + top\n for cc in range(ccmin, ccmax):\n col = cc + left\n c = cfarray[rr, cc]\n indx1 = rr * TS + cc\n indx = row * width + col\n rgb[indx1, c] = src[row, col] / 65535\n\n cfa[indx1] = rgb[indx1, c]\n \n # fill borders\n if rrmin > 0:\n for rr in range(16):\n for cc in range(ccmin, ccmax):\n c = cfarray[rr, cc]\n rgb[rr*TS+cc, c] = rgb[(32-rr)*TS+cc, c]\n cfa[rr*TS+cc] = rgb[rr*TS+cc, c]\n \n if rrmax < rr1:\n for rr in range(16):\n for cc in range(ccmin, ccmax):\n c = cfarray[rr, cc]\n rgb[(rrmax+rr)*TS+cc, c] = (src[(winy+height-rr-2), left+cc])/65535\n cfa[(rrmax+rr)*TS+cc] = rgb[(rrmax+rr)*TS+cc, c]\n \n if ccmin > 0:\n for rr in range(rrmin, rrmax):\n for cc in range(16):\n c = cfarray[rr, cc]\n rgb[rr*TS+cc, c] = rgb[rr*TS+32-cc, c]\n cfa[rr*TS+cc] = rgb[rr*TS+cc, c]\n \n if ccmax < cc1:\n for rr in range(rrmin, rrmax):\n for cc in range(16):\n c = cfarray[rr, cc]\n rgb[rr*TS+ccmax+cc, c] = (src[(top+rr), (winx+width-cc-2)])/65535\n cfa[rr*TS+ccmax+cc] = rgb[rr*TS+ccmax+cc, c]\n \n # also, fill the image corners\n if rrmin > 0 and ccmin > 0:\n for rr in range(16):\n for cc in range(16):\n c = cfarray[rr, cc]\n rgb[(rr)*TS+cc][c] = rgb[(32-rr)*TS+(32-cc)][c]\n cfa[(rr)*TS+cc] = rgb[(rr)*TS+cc][c]\n \n if rrmax < rr1 and ccmax < cc1:\n for rr in range(16):\n for cc in range(16):\n c = cfarray[rr, cc]\n rgb[(rrmax+rr)*TS+ccmax+cc][c] = (src[(winy+height-rr-2)][(winx+width-cc-2)])/65535\n cfa[(rrmax+rr)*TS+ccmax+cc] = rgb[(rrmax+rr)*TS+ccmax+cc][c]\n \n if rrmin > 0 and ccmax < cc1:\n for rr in range(16):\n for cc in range(16):\n c = cfarray[rr, cc]\n rgb[(rr)*TS+ccmax+cc][c] = (src[(winy+32-rr)][(winx+width-cc-2)])/65535\n cfa[(rr)*TS+ccmax+cc] = rgb[(rr)*TS+ccmax+cc][c]\n \n if rrmax < rr1 and ccmin > 0:\n for rr in range(16):\n for cc in range(16):\n c = cfarray[rr, cc]\n rgb[(rrmax+rr)*TS+cc][c] = (src[(winy+height-rr-2)][(winx+32-cc)])/65535\n cfa[(rrmax+rr)*TS+cc] = rgb[(rrmax+rr)*TS+cc][c]\n \n # end of border fill\n\n for rr in range(1, rr1-1):\n for cc in range(1, cc1-1):\n indx = rr*TS+cc\n delh[indx] = abs(cfa[indx + 1] - cfa[indx - 1])\n delv[indx] = abs(cfa[indx + v1] - cfa[indx - v1])\n delhsq[indx] = SQR(delh[indx])\n delvsq[indx] = SQR(delv[indx])\n delp[indx] = abs(cfa[indx+p1]-cfa[indx-p1])\n delm[indx] = abs(cfa[indx+m1]-cfa[indx-m1])\n\n for rr in range(2, rr1-2):\n for cc in range(2, cc1-2):\n indx = rr*TS+cc\n # vert directional averaging weights\n dirwts[indx][0] = eps+delv[indx+v1]+delv[indx-v1]+delv[indx]\n # horizontal weights\n dirwts[indx][1] = eps+delh[indx+1]+delh[indx-1]+delh[indx]\n\n if cfarray[rr, cc] & 1:\n # for later use in diagonal interpolation\n Dgrbpsq1[indx]=(SQR(cfa[indx]-cfa[indx-p1])+SQR(cfa[indx]-cfa[indx+p1]))\n Dgrbmsq1[indx]=(SQR(cfa[indx]-cfa[indx-m1])+SQR(cfa[indx]-cfa[indx+m1]))\n \n for rr in range(4, rr1 - 4):\n for cc in range(4, cc1 - 4):\n indx = rr*TS+cc\n c = cfarray[rr, cc]\n sgn = -1 if c & 1 else 1\n\n # initialization of nyquist test\n nyquist[indx]=0\n # preparation for diag interp\n rbint[indx]=0\n\n # color ratios in each cardinal direction\n cru = cfa[indx - v1] * (dirwts[indx - v2][0] + dirwts[indx][0]) / (dirwts[indx - v2][0] * (eps + cfa[indx]) + dirwts[indx][0] * (eps + cfa[indx - v2]))\n crd = cfa[indx + v1] * (dirwts[indx + v2][0] + dirwts[indx][0]) / (dirwts[indx + v2][0] * (eps + cfa[indx]) + dirwts[indx][0] * (eps + cfa[indx + v2]))\n crl = cfa[indx - 1] * (dirwts[indx - 2][1] + dirwts[indx][1]) / (dirwts[indx - 2][1] * (eps + cfa[indx]) + dirwts[indx][1] * (eps + cfa[indx - 2]))\n crr = cfa[indx + 1] * (dirwts[indx + 2][1] + dirwts[indx][1]) / (dirwts[indx + 2][1] * (eps + cfa[indx]) + dirwts[indx][1] * (eps + cfa[indx + 2]))\n\n # G interpolated in vert/hor directions using Hamilton-Adams method\n guha = min(clip_pt, cfa[indx - v1] + 0.5 * (cfa[indx] - cfa[indx - v2]))\n gdha = min(clip_pt, cfa[indx + v1] + 0.5 * (cfa[indx] - cfa[indx + v2]))\n glha = min(clip_pt, cfa[indx - 1] + 0.5 * (cfa[indx] - cfa[indx - 2]))\n grha = min(clip_pt, cfa[indx + 1] + 0.5 * (cfa[indx] - cfa[indx + 2]))\n\n # G interpolated in vert/hor directions using adaptive ratios\n guar = cfa[indx] * cru if abs(1-cru) < arthresh else guha\n gdar = cfa[indx] * crd if abs(1-crd) < arthresh else gdha\n glar = cfa[indx] * crl if abs(1-crl) < arthresh else glha\n grar = cfa[indx] * crr if abs(1-crr) < arthresh else grha\n\n # adaptive weights for vertical/horizontal directions\n hwt = dirwts[indx - 1][1] / (dirwts[indx - 1][1] + dirwts[indx + 1][1])\n vwt = dirwts[indx - v1][0] / (dirwts[indx + v1][0] + dirwts[indx - v1][0])\n\n # interpolated G via adaptive weighTS of cardinal evaluations\n Gintvar = vwt * gdar + (1-vwt) * guar\n Ginthar = hwt * grar + (1-hwt) * glar\n Gintvha = vwt * gdha + (1-vwt) * guha\n Ginthha = hwt * grha + (1-hwt) * glha\n # interpolated color differences\n vcd[indx] = sgn * (Gintvar-cfa[indx])\n hcd[indx] = sgn * (Ginthar-cfa[indx])\n vcdalt[indx] = sgn * (Gintvha-cfa[indx])\n hcdalt[indx] = sgn * (Ginthha-cfa[indx])\n\n if cfa[indx] > 0.8 * clip_pt or Gintvha > 0.8 * clip_pt or Ginthha > 0.8 * clip_pt:\n # use HA if highlighTS are (nearly) clipped\n guar = guha\n gdar = gdha\n glar = glha\n grar = grha\n vcd[indx] = vcdalt[indx]\n hcd[indx] = hcdalt[indx]\n\n # differences of interpolations in opposite directions\n dgintv[indx] = min((guha - gdha) ** 2, (guar - gdar) ** 2)\n dginth[indx] = min((glha - grha) ** 2, (glar - grar) ** 2)\n \n for rr in range(4, rr1-4):\n for cc in range(4, cc1-4):\n c = cfarray[rr, cc]\n\n hcdvar = 3*(SQR(hcd[indx-2])+SQR(hcd[indx])+SQR(hcd[indx+2]))-SQR(hcd[indx-2]+hcd[indx]+hcd[indx+2])\n hcdaltvar = 3*(SQR(hcdalt[indx-2])+SQR(hcdalt[indx])+SQR(hcdalt[indx+2]))-SQR(hcdalt[indx-2]+hcdalt[indx]+hcdalt[indx+2])\n vcdvar = 3*(SQR(vcd[indx-v2])+SQR(vcd[indx])+SQR(vcd[indx+v2]))-SQR(vcd[indx-v2]+vcd[indx]+vcd[indx+v2])\n vcdaltvar = 3*(SQR(vcdalt[indx-v2])+SQR(vcdalt[indx])+SQR(vcdalt[indx+v2]))-SQR(vcdalt[indx-v2]+vcdalt[indx]+vcdalt[indx+v2])\n\n # choose the smallest variance; this yields a smoother interpolation\n if hcdaltvar < hcdvar:\n hcd[indx] = hcdalt[indx]\n if vcdaltvar < vcdvar:\n vcd[indx] = vcdalt[indx]\n\n # bound the interpolation in regions of high saturation\n # vertical and horizontal G interpolations\n if c & 1: # G site\n Ginth = -hcd[indx] + cfa[indx]\n Gintv = -vcd[indx] + cfa[indx]\n\n if hcd[indx] > 0:\n if 3 * hcd[indx] > (Ginth + cfa[indx]):\n hcd[indx] = -np.median([Ginth, cfa[indx - 1], cfa[indx + 1]]) + cfa[indx]\n else:\n hwt = 1 - 3 * hcd[indx] / (eps + Ginth + cfa[indx])\n hcd[indx] = hwt * hcd[indx] + (1 - hwt) * (-np.median([Ginth, cfa[indx - 1], cfa[indx + 1]]) + cfa[indx])\n\n if vcd[indx] > 0:\n if 3 * vcd[indx] > (Gintv + cfa[indx]):\n vcd[indx] = -np.median([Gintv, cfa[indx - v1], cfa[indx + v1]]) + cfa[indx]\n else:\n vwt = 1 - 3 * vcd[indx] / (eps + Gintv + cfa[indx])\n vcd[indx] = vwt * vcd[indx] + (1 - vwt) * (-np.median([Gintv, cfa[indx - v1], cfa[indx + v1]]) + cfa[indx])\n \n if Ginth > clip_pt:\n hcd[indx] = -np.median([Ginth, cfa[indx - 1], cfa[indx + 1]]) + cfa[indx]\n\n if Gintv > clip_pt:\n vcd[indx] = -np.median([Gintv, cfa[indx - v1], cfa[indx + v1]]) + cfa[indx]\n \n else: # R or B site\n\n Ginth = hcd[indx] + cfa[indx]\n Gintv = vcd[indx] + cfa[indx]\n\n if hcd[indx] < 0:\n if 3 * hcd[indx] < -(Ginth + cfa[indx]):\n hcd[indx] = np.median([Ginth, cfa[indx - 1], cfa[indx + 1]]) - cfa[indx]\n else:\n hwt = 1 + 3 * hcd[indx] / (eps + Ginth + cfa[indx])\n hcd[indx] = hwt * hcd[indx] + (1 - hwt) * (np.median([Ginth, cfa[indx - 1], cfa[indx + 1]]) - cfa[indx])\n\n if vcd[indx] < 0:\n if 3 * vcd[indx] < -(Gintv + cfa[indx]):\n vcd[indx] = np.median([Gintv, cfa[indx - v1], cfa[indx + v1]]) - cfa[indx]\n else:\n vwt = 1 + 3 * vcd[indx] / (eps + Gintv + cfa[indx])\n vcd[indx] = vwt * vcd[indx] + (1 - vwt) * (np.median([Gintv, cfa[indx - v1], cfa[indx + v1]]) - cfa[indx])\n\n if Ginth > clip_pt:\n hcd[indx] = np.median([Ginth, cfa[indx - 1], cfa[indx + 1]]) - cfa[indx]\n\n if Gintv > clip_pt:\n vcd[indx] = np.median([Gintv, cfa[indx - v1], cfa[indx + v1]]) - cfa[indx]\n\n vcdsq[indx] = SQR(vcd[indx])\n hcdsq[indx] = SQR(hcd[indx])\n cddiffsq[indx] = SQR(vcd[indx]-hcd[indx])\n\n for rr in range(6, rr1-6):\n for cc in range(6+(cfarray[rr, 2]&1), cc1-6, 2):\n indx = rr * TS + cc\n\n # compute color difference variances in cardinal directions\n\n Dgrbvvaru = 4*(vcdsq[indx]+vcdsq[indx-v1]+vcdsq[indx-v2]+vcdsq[indx-v3])-SQR(vcd[indx]+vcd[indx-v1]+vcd[indx-v2]+vcd[indx-v3])\n Dgrbvvard = 4*(vcdsq[indx]+vcdsq[indx+v1]+vcdsq[indx+v2]+vcdsq[indx+v3])-SQR(vcd[indx]+vcd[indx+v1]+vcd[indx+v2]+vcd[indx+v3])\n Dgrbhvarl = 4*(hcdsq[indx]+hcdsq[indx-1]+hcdsq[indx-2]+hcdsq[indx-3])-SQR(hcd[indx]+hcd[indx-1]+hcd[indx-2]+hcd[indx-3])\n Dgrbhvarr = 4*(hcdsq[indx]+hcdsq[indx+1]+hcdsq[indx+2]+hcdsq[indx+3])-SQR(hcd[indx]+hcd[indx+1]+hcd[indx+2]+hcd[indx+3])\n\t\t\t\t\t\n hwt = dirwts[indx-1][1]/(dirwts[indx-1][1]+dirwts[indx+1][1])\n vwt = dirwts[indx-v1][0]/(dirwts[indx+v1][0]+dirwts[indx-v1][0])\n\t\t\t\t\t\n vcdvar = epssq+vwt*Dgrbvvard+(1-vwt)*Dgrbvvaru\n hcdvar = epssq+hwt*Dgrbhvarr+(1-hwt)*Dgrbhvarl\n\n # compute fluctuations in up/down and left/right interpolations of colors\n Dgrbvvaru = (dgintv[indx])+(dgintv[indx-v1])+(dgintv[indx-v2])\n Dgrbvvard = (dgintv[indx])+(dgintv[indx+v1])+(dgintv[indx+v2])\n Dgrbhvarl = (dginth[indx])+(dginth[indx-1])+(dginth[indx-2])\n Dgrbhvarr = (dginth[indx])+(dginth[indx+1])+(dginth[indx+2])\n\n vcdvar1 = epssq+vwt*Dgrbvvard+(1-vwt)*Dgrbvvaru\n hcdvar1 = epssq+hwt*Dgrbhvarr+(1-hwt)*Dgrbhvarl\n\n # determine adaptive weights for G interpolation\n varwt=hcdvar/(vcdvar+hcdvar)\n diffwt=hcdvar1/(vcdvar1+hcdvar1)\n\n # if both agree on interpolation direction, choose the one with strongest directional discrimination;\n # otherwise, choose the u/d and l/r difference fluctuation weights\n if ((0.5 - varwt) * (0.5 - diffwt) > 0) and (abs(0.5 - diffwt) < abs(0.5 - varwt)):\n hvwt[indx] = varwt\n else:\n hvwt[indx] = diffwt\n \n # Nyquist test\n for rr in range(6, rr1-6):\n for cc in range(6 + (cfarray[rr, 2]&1), cc1 - 6, 2):\n indx = rr * TS + cc\n\n # nyquist texture test: ask if difference of vcd compared to hcd is larger or smaller than RGGB gradients\n nyqtest = (gaussodd[0]*cddiffsq[indx] + gaussodd[1]*(cddiffsq[indx-m1]+cddiffsq[indx+p1] + cddiffsq[indx-p1]+cddiffsq[indx+m1]) + gaussodd[2]*(cddiffsq[indx-v2]+cddiffsq[indx-2]+ cddiffsq[indx+2]+cddiffsq[indx+v2]) + gaussodd[3]*(cddiffsq[indx-m2]+cddiffsq[indx+p2] + cddiffsq[indx-p2]+cddiffsq[indx+m2]))\n\n nyqtest -= nyqthresh*(gaussgrad[0]*(delhsq[indx]+delvsq[indx])+gaussgrad[1]*(delhsq[indx-v1]+delvsq[indx-v1]+delhsq[indx+1]+delvsq[indx+1] + delhsq[indx-1]+delvsq[indx-1]+delhsq[indx+v1]+delvsq[indx+v1])+ gaussgrad[2]*(delhsq[indx-m1]+delvsq[indx-m1]+delhsq[indx+p1]+delvsq[indx+p1]+ delhsq[indx-p1]+delvsq[indx-p1]+delhsq[indx+m1]+delvsq[indx+m1])+ gaussgrad[3]*(delhsq[indx-v2]+delvsq[indx-v2]+delhsq[indx-2]+delvsq[indx-2]+ delhsq[indx+2]+delvsq[indx+2]+delhsq[indx+v2]+delvsq[indx+v2])+ gaussgrad[4]*(delhsq[indx-2*TS-1]+delvsq[indx-2*TS-1]+delhsq[indx-2*TS+1]+delvsq[indx-2*TS+1]+ delhsq[indx-TS-2]+delvsq[indx-TS-2]+delhsq[indx-TS+2]+delvsq[indx-TS+2]+ delhsq[indx+TS-2]+delvsq[indx+TS-2]+delhsq[indx+TS+2]+delvsq[indx-TS+2]+ delhsq[indx+2*TS-1]+delvsq[indx+2*TS-1]+delhsq[indx+2*TS+1]+delvsq[indx+2*TS+1])+ gaussgrad[5]*(delhsq[indx-m2]+delvsq[indx-m2]+delhsq[indx+p2]+delvsq[indx+p2]+ delhsq[indx-p2]+delvsq[indx-p2]+delhsq[indx+m2]+delvsq[indx+m2]))\n\n if nyqtest > 0:\n # nyquist=1 for nyquist region\n nyquist[indx] = 1\n \n for rr in range(8, rr1-8):\n for cc in range(8+(cfarray[rr,2]&1), cc1-8, 2):\n\n areawt=(nyquist[indx-v2]+nyquist[indx-m1]+nyquist[indx+p1]+nyquist[indx-2]+nyquist[indx]+nyquist[indx+2]+nyquist[indx-p1]+nyquist[indx+m1]+nyquist[indx+v2])\n\n # if most of your neighbors are named Nyquist, it's likely that you're one too\n nyquist[indx] = 1 if areawt > 4 else 0\n\n # end of Nyquist test\n\n # in areas of Nyquist texture, do area interpolation\n for rr in range(8, rr1 - 8):\n for cc in range(8+(cfarray[rr,2]&1), cc1-8, 2):\n indx = rr * TS + cc\n if nyquist[indx]:\n # area interpolation\n sumh = sumv = sumsqh = sumsqv = areawt = 0\n for i in range(-6, 7, 2):\n for j in range(-6, 7, 2):\n indx1 = (rr + i) * TS + cc + j\n if nyquist[indx1]:\n sumh += cfa[indx1] - 0.5 * (cfa[indx1-1]+cfa[indx1+1])\n sumv += cfa[indx1] - 0.5 * (cfa[indx1-v1]+cfa[indx1+v1])\n sumsqh += 0.5 * (SQR(cfa[indx1]-cfa[indx1-1]) + SQR(cfa[indx1]-cfa[indx1+1]))\n sumsqv += 0.5 * (SQR(cfa[indx1]-cfa[indx1-v1]) + SQR(cfa[indx1]-cfa[indx1+v1]))\n areawt += 1\n\n # horizontal and vertical color differences, and adaptive weight\n hcdvar = epssq + max(0, areawt*sumsqh-sumh*sumh)\n vcdvar = epssq + max(0, areawt*sumsqv-sumv*sumv)\n hvwt[indx] = hcdvar / (vcdvar + hcdvar)\n \n # end of area interpolation\n \n # populate G at R/B sites\n for rr in range(8, rr1-8):\n for cc in range(8+(cfarray[rr,2]&1), cc1-8, 2):\n indx = rr * TS + cc\n\n # first ask if one gets more directional discrimination from nearby B/R sites\n hvwtalt = 0.25 * (hvwt[indx-m1] + hvwt[indx+p1] + hvwt[indx-p1] + hvwt[indx+m1])\n vo = abs(0.5 - hvwt[indx])\n ve = abs(0.5 - hvwtalt)\n # a better result was obtained from the neighbors\n if vo < ve:\n hvwt[indx>>1] = hvwtalt\n # evaluate color differences\n Dgrb[indx][0] = (hcd[indx]*(1-hvwt[indx]) + vcd[indx]*hvwt[indx])\n # evaluate G\n rgb[indx][1] = cfa[indx] + Dgrb[indx][0]\n # local curvature in G (preparation for nyquist refinement step)\n if nyquist[indx]:\n Dgrbh2[indx] = SQR(rgb[indx][1] - 0.5*(rgb[indx-1][1]+rgb[indx+1][1]))\n Dgrbv2[indx] = SQR(rgb[indx][1] - 0.5*(rgb[indx-v1][1]+rgb[indx+v1][1]))\n else:\n Dgrbh2[indx] = Dgrbv2[indx] = 0\n\n # end of standard interpolation\n\n\n # refine Nyquist areas using G curvatures\n for rr in range(8, rr1-8):\n for cc in range(8+(cfarray[rr,2]&1), cc1-8, 2):\n indx = rr * TS + cc\n if nyquist[indx]:\n # local averages (over Nyquist pixels only) of G curvature squared \n gvarh = epssq + (gquinc[0]*Dgrbh2[indx]+gquinc[1]*(Dgrbh2[indx-m1]+Dgrbh2[indx+p1]+Dgrbh2[indx-p1]+Dgrbh2[indx+m1])+gquinc[2]*(Dgrbh2[indx-v2]+Dgrbh2[indx-2]+Dgrbh2[indx+2]+Dgrbh2[indx+v2])+gquinc[3]*(Dgrbh2[indx-m2]+Dgrbh2[indx+p2]+Dgrbh2[indx-p2]+Dgrbh2[indx+m2]))\n gvarv = epssq + (gquinc[0]*Dgrbv2[indx]+gquinc[1]*(Dgrbv2[indx-m1]+Dgrbv2[indx+p1]+Dgrbv2[indx-p1]+Dgrbv2[indx+m1])+gquinc[2]*(Dgrbv2[indx-v2]+Dgrbv2[indx-2]+Dgrbv2[indx+2]+Dgrbv2[indx+v2])+gquinc[3]*(Dgrbv2[indx-m2]+Dgrbv2[indx+p2]+Dgrbv2[indx-p2]+Dgrbv2[indx+m2]))\n # use the results as weights for refined G interpolation\n Dgrb[indx][0] = (hcd[indx]*gvarv + vcd[indx]*gvarh)/(gvarv+gvarh)\n rgb[indx][1] = cfa[indx] + Dgrb[indx][0]\n \n # diagonal interpolation correction\n for rr in range(8, rr1-8):\n for cc in range(8+(cfarray[rr,2]&1), cc1-8, 2):\n indx = rr * TS + cc\n rbvarp = epssq + (gausseven[0]*(Dgrbpsq1[indx-v1]+Dgrbpsq1[indx-1]+Dgrbpsq1[indx+1]+Dgrbpsq1[indx+v1]) + gausseven[1]*(Dgrbpsq1[indx-v2-1]+Dgrbpsq1[indx-v2+1]+Dgrbpsq1[indx-2-v1]+Dgrbpsq1[indx+2-v1]+ Dgrbpsq1[indx-2+v1]+Dgrbpsq1[indx+2+v1]+Dgrbpsq1[indx+v2-1]+Dgrbpsq1[indx+v2+1]))\n rbvarm = epssq + (gausseven[0]*(Dgrbmsq1[indx-v1]+Dgrbmsq1[indx-1]+Dgrbmsq1[indx+1]+Dgrbmsq1[indx+v1]) + gausseven[1]*(Dgrbmsq1[indx-v2-1]+Dgrbmsq1[indx-v2+1]+Dgrbmsq1[indx-2-v1]+Dgrbmsq1[indx+2-v1]+ Dgrbmsq1[indx-2+v1]+Dgrbmsq1[indx+2+v1]+Dgrbmsq1[indx+v2-1]+Dgrbmsq1[indx+v2+1]))\n\n # diagonal color ratios\n crse=2*(cfa[indx+m1])/(eps+cfa[indx]+(cfa[indx+m2]))\n crnw=2*(cfa[indx-m1])/(eps+cfa[indx]+(cfa[indx-m2]))\n crne=2*(cfa[indx+p1])/(eps+cfa[indx]+(cfa[indx+p2]))\n crsw=2*(cfa[indx-p1])/(eps+cfa[indx]+(cfa[indx-p2]))\n\n # assign B/R at R/B sites\n if abs(1 - crse) < arthresh:\n rbse = cfa[indx] * crse\n else:\n rbse = cfa[indx + m1] + 0.5 * (cfa[indx] - cfa[indx + m2])\n\n if abs(1 - crnw) < arthresh:\n rbnw = (cfa[indx - m1]) + 0.5 *(cfa[indx] - cfa[indx - m2])\n\n if abs(1 - crne) < arthresh:\n rbne = cfa[indx] * crne\n else:\n rbne = (cfa[indx + p1]) + 0.5 * cfa[indx] - cfa[indx + p2]\n\n if abs(1 - crsw) < arthresh:\n rbsw = cfa[indx] * crsw\n else:\n rbsw = (cfa[indx - p1]) + 0.5 * (cfa[indx] - cfa[indx - p2])\n \n wtse= eps+delm[indx]+delm[indx+m1]+delm[indx+m2] # same as for wtu,wtd,wtl,wtr\n wtnw= eps+delm[indx]+delm[indx-m1]+delm[indx-m2]\n wtne= eps+delp[indx]+delp[indx+p1]+delp[indx+p2]\n wtsw= eps+delp[indx]+delp[indx-p1]+delp[indx-p2]\n\n rbm[indx] = (wtse*rbnw+wtnw*rbse)/(wtse+wtnw)\n rbp[indx] = (wtne*rbsw+wtsw*rbne)/(wtne+wtsw)\n\n pmwt[indx] = rbvarm/(rbvarp+rbvarm)\n\n # bound the interpolation in regions of high saturation\n if rbp[indx] < cfa[indx]:\n if 2 * (rbp[indx]) < cfa[indx]:\n rbp[indx] = np.median([rbp[indx] , cfa[indx - p1], cfa[indx + p1]])\n else:\n pwt = 2 * (cfa[indx] - rbp[indx]) / (eps + rbp[indx] + cfa[indx])\n rbp[indx] = pwt * rbp[indx] + (1 - pwt) * np.median([rbp[indx], cfa[indx - p1], cfa[indx + p1]])\n\n if rbm[indx] < cfa[indx]:\n if 2 * (rbm[indx]) < cfa[indx]:\n rbm[indx] = np.median([rbm[indx] , cfa[indx - m1], cfa[indx + m1]])\n else:\n mwt = 2 * (cfa[indx] - rbm[indx]) / (eps + rbm[indx] + cfa[indx])\n rbm[indx] = mwt * rbm[indx] + (1 - mwt) * np.median([rbm[indx], cfa[indx - m1], cfa[indx + m1]])\n\n if rbp[indx] > clip_pt:\n rbp[indx] = np.median([rbp[indx], cfa[indx - p1], cfa[indx + p1]])\n\n if rbm[indx] > clip_pt:\n rbm[indx] = np.median([rbm[indx], cfa[indx - m1], cfa[indx + m1]])\n\n for rr in range(10, rr1-10):\n for cc in range(10 + (cfarray[rr, 2]&1), cc1-10, 2):\n indx = rr * TS + cc\n \n # first ask if one geTS more directional discrimination from nearby B/R sites\n pmwtalt = 0.25*(pmwt[indx-m1]+pmwt[indx+p1]+pmwt[indx-p1]+pmwt[indx+m1])\n vo = abs(0.5-pmwt[indx])\n ve = abs(0.5-pmwtalt)\n if vo < ve:\n pmwt[indx] = pmwtalt\n rbint[indx] = 0.5*(cfa[indx] + rbm[indx]*(1-pmwt[indx]) + rbp[indx]*pmwt[indx])\n\n for rr in range(12, rr1 - 12):\n for cc in range(12 + (cfarray[rr, 2]&1), cc1 - 12, 2):\n indx = rr * TS + cc\n if abs(0.5 - pmwt[indx]) < abs(0.5 - hvwt[indx]):\n continue\n \n # now interpolate G vertically/horizontally using R+B values\n # unfortunately, since G interpolation cannot be done diagonally this may lead to colour shifts\n # colour ratios for G interpolation\n cru = cfa[indx-v1]*2/(eps+rbint[indx]+rbint[indx-v2])\n crd = cfa[indx+v1]*2/(eps+rbint[indx]+rbint[indx+v2])\n crl = cfa[indx-1]*2/(eps+rbint[indx]+rbint[indx-2])\n crr = cfa[indx+1]*2/(eps+rbint[indx]+rbint[indx+2])\n\n # interpolated G via adaptive ratios or Hamilton-Adams in each cardinal direction\n if abs(1 - cru) < arthresh:\n gu = rbint[indx] * cru\n else:\n gu = cfa[indx - v1] + 0.5 * (rbint[indx] - rbint[(indx - v1)])\n\n if abs(1 - crd) < arthresh:\n gd = rbint[indx] * crd\n else:\n gd = cfa[indx + v1] + 0.5 * (rbint[indx] - rbint[(indx + v1)])\n\n if abs(1 - crl) < arthresh:\n gl = rbint[indx] * crl\n else:\n gl = cfa[indx - 1] + 0.5 * (rbint[indx] - rbint[(indx - 1)])\n\n if abs(1 - crr) < arthresh:\n gr = rbint[indx] * crr\n else:\n gr = cfa[indx + 1] + 0.5 * (rbint[indx] - rbint[(indx + 1)])\n\n # interpolated G via adaptive weighTS of cardinal evaluations\n Gintv = (dirwts[indx - v1][0] * gd + dirwts[indx + v1][0] * gu) / (dirwts[indx + v1][0] + dirwts[indx - v1][0])\n Ginth = (dirwts[indx - 1][1] * gr + dirwts[indx + 1][1] * gl) / (dirwts[indx - 1][1] + dirwts[indx + 1][1])\n\n # bound the interpolation in regions of high saturation\n if Gintv < rbint[indx]:\n if (2 * Gintv < rbint[indx]):\n Gintv = np.median([Gintv , cfa[indx - v1], cfa[indx + v1]])\n else:\n vwt = 2 * (rbint[indx] - Gintv) / (eps + Gintv + rbint[indx])\n Gintv = vwt * Gintv + (1 - vwt) * np.median([Gintv, cfa[indx - v1], cfa[indx + v1]])\n\n if Ginth < rbint[indx]:\n if 2 * Ginth < rbint[indx]:\n Ginth = np.median([Ginth , cfa[indx - 1], cfa[indx + 1]])\n else:\n hwt = 2 * (rbint[indx] - Ginth) / (eps + Ginth + rbint[indx])\n Ginth = hwt * Ginth + (1 - hwt) * np.median([Ginth, cfa[indx - 1], cfa[indx + 1]])\n \n if Ginth > clip_pt:\n Ginth = np.median([Ginth, cfa[indx - 1], cfa[indx + 1]])\n\n if Gintv > clip_pt:\n Gintv = np.median([Gintv, cfa[indx - v1], cfa[indx + v1]])\n \n rgb[indx][1] = Ginth*(1-hvwt[indx]) + Gintv*hvwt[indx]\n Dgrb[indx][0] = rgb[indx][1]-cfa[indx]\n\n # end of diagonal interpolation correction\n\n # fancy chrominance interpolation\n # (ey,ex) is location of R site\n for rr in range(13-ey, rr1-12, 2):\n for cc in range(13-ex, cc1-12, 2):\n indx = rr*TS+cc\n Dgrb[indx][1]=Dgrb[indx][0] # split out G-B from G-R\n Dgrb[indx][0]=0\n\n for rr in range(12, rr1-12):\n c = int(1- cfarray[rr, 12+(cfarray[rr,2]&1)]/2)\n for cc in range(12+(cfarray[rr,2]&1), cc1-12, 2):\n indx = rr * TS + cc\n wtnw=1/(eps+abs(Dgrb[indx-m1][c]-Dgrb[indx+m1][c])+abs(Dgrb[indx-m1][c]-Dgrb[indx-m3][c])+abs(Dgrb[indx+m1][c]-Dgrb[indx-m3][c]))\n wtne=1/(eps+abs(Dgrb[indx+p1][c]-Dgrb[indx-p1][c])+abs(Dgrb[indx+p1][c]-Dgrb[indx+p3][c])+abs(Dgrb[indx-p1][c]-Dgrb[indx+p3][c]))\n wtsw=1/(eps+abs(Dgrb[indx-p1][c]-Dgrb[indx+p1][c])+abs(Dgrb[indx-p1][c]-Dgrb[indx+m3][c])+abs(Dgrb[indx+p1][c]-Dgrb[indx-p3][c]))\n wtse=1/(eps+abs(Dgrb[indx+m1][c]-Dgrb[indx-m1][c])+abs(Dgrb[indx+m1][c]-Dgrb[indx-p3][c])+abs(Dgrb[indx-m1][c]-Dgrb[indx+m3][c]))\n \n Dgrb[indx][c]=(wtnw*(1.325*Dgrb[indx-m1][c]-0.175*Dgrb[indx-m3][c]-0.075*Dgrb[indx-m1-2][c]-0.075*Dgrb[indx-m1-v2][c] )+ wtne*(1.325*Dgrb[indx+p1][c]-0.175*Dgrb[indx+p3][c]-0.075*Dgrb[indx+p1+2][c]-0.075*Dgrb[indx+p1+v2][c] )+ wtsw*(1.325*Dgrb[indx-p1][c]-0.175*Dgrb[indx-p3][c]-0.075*Dgrb[indx-p1-2][c]-0.075*Dgrb[indx-p1-v2][c] )+ wtse*(1.325*Dgrb[indx+m1][c]-0.175*Dgrb[indx+m3][c]-0.075*Dgrb[indx+m1+2][c]-0.075*Dgrb[indx+m1+v2][c] ))/(wtnw+wtne+wtsw+wtse)\n\n for rr in range(12, rr1-12):\n # c = int(cfarray[rr, 12+(cfarray[rr,1]&1)+1]/2)\n for cc in range(12+(cfarray[rr,1]&1), cc1-12, 2):\n for c in range(2):\n Dgrb[indx][c]=((hvwt[indx-v1])*Dgrb[indx-v1][c]+(1-hvwt[indx+1])*Dgrb[indx+1][c]+(1-hvwt[indx-1])*Dgrb[indx-1][c]+(hvwt[indx+v1])*Dgrb[indx+v1][c])/((hvwt[indx-v1])+(1-hvwt[indx+1])+(1-hvwt[indx-1])+(hvwt[indx+v1]))\n\n for rr in range(12, rr1-12):\n for cc in range(12, cc1-12):\n indx = rr * TS + cc\n rgb[indx][0]=(rgb[indx][1]-Dgrb[indx][0])\n rgb[indx][2]=(rgb[indx][1]-Dgrb[indx][1])\n\n \n # copy smoothed results back to image matrix\n for rr in range(16, rr1-16):\n row = rr + top\n for cc in range(16, cc1-16):\n col = cc + left\n\n for c in range(3):\n image[row, col, c] = int(rgb[rr*TS+cc, c] * 65535 + 0.5)\n \n # end of main loop\n return image\n\n# Define some utility functions for demosaicing\n\n# For AMAzE\ndef fc(cfa, r, c):\n return cfa[r&1, c&1]\n\ndef intp(a, b, c):\n return a * (b - c) + c\n\ndef SQR(x):\n return x ** 2"
] | [
[
"numpy.median",
"numpy.empty"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
daxpryce/graspologic | [
"b076f58ca03a41eb2e1462d20a61ff09abfd6045",
"b076f58ca03a41eb2e1462d20a61ff09abfd6045"
] | [
"tests/test_plot.py",
"graspologic/pipeline/embed/omnibus_embedding.py"
] | [
"# Copyright (c) Microsoft Corporation and contributors.\n# Licensed under the MIT License.\n\nimport unittest\n\nimport numpy as np\nfrom sklearn.mixture import GaussianMixture\n\nfrom graspologic.plot.plot import (\n _sort_inds,\n gridplot,\n heatmap,\n pairplot,\n pairplot_with_gmm,\n)\nfrom graspologic.simulations.simulations import er_np, sbm\n\n\ndef _test_pairplot_with_gmm_inputs(caller: unittest.TestCase, **kws):\n X = np.random.rand(15, 3)\n gmm = GaussianMixture(n_components=3, **kws).fit(X)\n labels = [\"A\"] * 5 + [\"B\"] * 5 + [\"C\"] * 5\n # test data\n with caller.assertRaises(ValueError):\n pairplot_with_gmm(X=\"test\", gmm=gmm)\n\n with caller.assertRaises(ValueError):\n pairplot_with_gmm(X=X, gmm=gmm, labels=[\"A\"])\n\n with caller.assertRaises(NameError):\n pairplot_with_gmm(X, gmm=None)\n\n\ndef _test_pairplot_with_gmm_outputs(**kws):\n X = np.random.rand(15, 3)\n gmm = GaussianMixture(n_components=3, **kws).fit(X)\n labels = [\"A\"] * 5 + [\"B\"] * 5 + [\"C\"] * 5\n cluster_palette = {0: \"red\", 1: \"blue\", 2: \"green\"}\n label_palette = {\"A\": \"red\", \"B\": \"blue\", \"C\": \"green\"}\n fig = pairplot_with_gmm(X, gmm)\n fig = pairplot_with_gmm(\n X,\n gmm,\n labels=labels,\n cluster_palette=cluster_palette,\n label_palette=label_palette,\n )\n\n\nclass TestPlot(unittest.TestCase):\n def test_common_inputs(self):\n X = er_np(100, 0.5)\n grid_labels = [\"Test1\"]\n\n # test figsize\n with self.assertRaises(TypeError):\n figsize = \"bad figsize\"\n heatmap(X, figsize=figsize)\n\n # test height\n height = \"1\"\n with self.assertRaises(TypeError):\n gridplot([X], grid_labels, height=height)\n with self.assertRaises(TypeError):\n pairplot(X, height=height)\n\n # test title\n title = 1\n with self.assertRaises(TypeError):\n heatmap(X, title=title)\n with self.assertRaises(TypeError):\n gridplot([X], grid_labels, title=title)\n with self.assertRaises(TypeError):\n pairplot(X, title=title)\n\n # test context\n context = 123\n with self.assertRaises(TypeError):\n heatmap(X, context=context)\n with self.assertRaises(TypeError):\n gridplot([X], grid_labels, context=context)\n with self.assertRaises(TypeError):\n pairplot(X, context=context)\n\n context = \"journal\"\n with self.assertRaises(ValueError):\n heatmap(X, context=context)\n with self.assertRaises(ValueError):\n gridplot([X], grid_labels, context=context)\n with self.assertRaises(ValueError):\n pairplot(X, context=context)\n\n # test font scales\n font_scales = [\"1\", []]\n for font_scale in font_scales:\n with self.assertRaises(TypeError):\n heatmap(X, font_scale=font_scale)\n with self.assertRaises(TypeError):\n gridplot([X], grid_labels, font_scale=font_scale)\n with self.assertRaises(TypeError):\n pairplot(X, cont_scale=font_scale)\n\n # ticklabels\n with self.assertRaises(TypeError):\n xticklabels = \"labels\"\n yticklabels = \"labels\"\n heatmap(X, xticklabels=xticklabels, yticklabels=yticklabels)\n\n with self.assertRaises(ValueError):\n xticklabels = [\"{}\".format(i) for i in range(5)]\n yticklabels = [\"{}\".format(i) for i in range(5)]\n heatmap(X, xticklabels=xticklabels, yticklabels=yticklabels)\n\n with self.assertRaises(TypeError):\n heatmap(X, title_pad=\"f\")\n\n with self.assertRaises(TypeError):\n gridplot([X], title_pad=\"f\")\n\n with self.assertRaises(TypeError):\n heatmap(X, hier_label_fontsize=\"f\")\n\n with self.assertRaises(TypeError):\n gridplot([X], hier_label_fontsize=\"f\")\n\n def test_heatmap_inputs(self):\n \"\"\"\n test parameter checks\n \"\"\"\n X = np.random.rand(10, 10)\n\n with self.assertRaises(TypeError):\n heatmap(X=\"input\")\n\n # transform\n with self.assertRaises(ValueError):\n transform = \"bad transform\"\n heatmap(X, transform=transform)\n\n # cmap\n with self.assertRaises(TypeError):\n cmap = 123\n heatmap(X, cmap=cmap)\n\n # center\n with self.assertRaises(TypeError):\n center = \"center\"\n heatmap(X, center=center)\n\n # cbar\n with self.assertRaises(TypeError):\n cbar = 1\n heatmap(X, cbar=cbar)\n\n def test_heatmap_output(self):\n \"\"\"\n simple function to see if plot is made without errors\n \"\"\"\n X = er_np(10, 0.5)\n xticklabels = [\"Dimension {}\".format(i) for i in range(10)]\n yticklabels = [\"Dimension {}\".format(i) for i in range(10)]\n\n fig = heatmap(\n X, transform=\"log\", xticklabels=xticklabels, yticklabels=yticklabels\n )\n fig = heatmap(X, transform=\"zero-boost\")\n fig = heatmap(X, transform=\"simple-all\")\n fig = heatmap(X, transform=\"simple-nonzero\")\n fig = heatmap(X, transform=\"binarize\")\n fig = heatmap(X, cmap=\"gist_rainbow\")\n\n def test_gridplot_inputs(self):\n X = [er_np(10, 0.5)]\n labels = [\"ER(10, 0.5)\"]\n\n with self.assertRaises(TypeError):\n gridplot(X=\"input\", labels=labels)\n\n with self.assertRaises(ValueError):\n gridplot(X, labels=[\"a\", \"b\"])\n\n # transform\n with self.assertRaises(ValueError):\n transform = \"bad transform\"\n gridplot(X, labels=labels, transform=transform)\n\n def test_gridplot_outputs(self):\n \"\"\"\n simple function to see if plot is made without errors\n \"\"\"\n X = [er_np(10, 0.5) for _ in range(2)]\n labels = [\"Random A\", \"Random B\"]\n fig = gridplot(X, labels)\n fig = gridplot(X, labels, transform=\"zero-boost\")\n fig = gridplot(X, labels, \"simple-all\", title=\"Test\", font_scale=0.9)\n\n def test_pairplot_inputs(self):\n X = np.random.rand(15, 3)\n Y = [\"A\"] * 5 + [\"B\"] * 5 + [\"C\"] * 5\n\n # test data\n with self.assertRaises(TypeError):\n pairplot(X=\"test\")\n\n with self.assertRaises(ValueError):\n pairplot(X=X, labels=[\"A\"])\n\n with self.assertRaises(TypeError):\n pairplot(X, col_names=\"A\")\n\n with self.assertRaises(ValueError):\n pairplot(X, col_names=[\"1\", \"2\"])\n\n with self.assertRaises(ValueError):\n pairplot(X, col_names=[\"1\", \"2\", \"3\"], variables=[1, 2, 3, 4])\n\n with self.assertRaises(KeyError):\n pairplot(X, col_names=[\"1\", \"2\", \"3\"], variables=[\"A\", \"B\"])\n\n def test_pairplot_outputs(self):\n X = np.random.rand(15, 3)\n Y = [\"A\"] * 5 + [\"B\"] * 5 + [\"C\"] * 5\n col_names = [\"Feature1\", \"Feature2\", \"Feature3\"]\n\n fig = pairplot(X)\n fig = pairplot(X, Y)\n fig = pairplot(X, Y, col_names)\n fig = pairplot(\n X,\n Y,\n col_names,\n title=\"Test\",\n height=1.5,\n variables=[\"Feature1\", \"Feature2\"],\n )\n\n def test_pairplot_with_gmm_inputs_type_full(self):\n _test_pairplot_with_gmm_inputs(self, covariance_type=\"full\")\n\n def test_pairplot_with_gmm_inputs_type_diag(self):\n _test_pairplot_with_gmm_inputs(self, covariance_type=\"diag\")\n\n def test_pairplot_with_gmm_inputs_type_tied(self):\n _test_pairplot_with_gmm_inputs(self, covariance_type=\"tied\")\n\n def test_pairplot_with_gmm_inputs_type_spherical(self):\n _test_pairplot_with_gmm_inputs(self, covariance_type=\"spherical\")\n\n def test_pairplot_with_gmm_outputs_type_full(self):\n _test_pairplot_with_gmm_outputs(covariance_type=\"full\")\n\n def test_pairplot_with_gmm_outputs_type_diag(self):\n _test_pairplot_with_gmm_outputs(covariance_type=\"diag\")\n\n def test_pairplot_with_gmm_outputs_type_tied(self):\n _test_pairplot_with_gmm_outputs(covariance_type=\"tied\")\n\n def test_pairplot_with_gmm_outputs_type_spherical(self):\n _test_pairplot_with_gmm_outputs(covariance_type=\"spherical\")\n\n def test_sort_inds(self):\n B = np.array(\n [\n [0, 0.2, 0.1, 0.1, 0.1],\n [0.2, 0.8, 0.1, 0.3, 0.1],\n [0.15, 0.1, 0, 0.05, 0.1],\n [0.1, 0.1, 0.2, 1, 0.1],\n [0.1, 0.2, 0.1, 0.1, 0.8],\n ]\n )\n\n g = sbm([10, 30, 50, 25, 25], B, directed=True)\n degrees = g.sum(axis=0) + g.sum(axis=1)\n degree_sort_inds = np.argsort(degrees)\n labels2 = 40 * [\"0\"] + 100 * [\"1\"]\n labels1 = 10 * [\"d\"] + 30 * [\"c\"] + 50 * [\"d\"] + 25 * [\"e\"] + 25 * [\"c\"]\n labels1 = np.array(labels1)\n labels2 = np.array(labels2)\n sorted_inds = _sort_inds(g, labels1, labels2, True)\n # sort outer blocks first if given, sort by num verts in the block\n # for inner hier, sort by num verts for that category across the entire graph\n # ie if there are multiple inner hier across different outer blocks, sort\n # by prevalence in the entire graph, not within block\n # this is to make the ordering within outer block consistent\n # within a block, sort by degree\n\n # outer block order should thus be: 1, 0\n # inner block order should thus be: d, c, e\n\n # show that outer blocks are sorted correctly\n labels2 = labels2[sorted_inds]\n self.assertTrue(np.all(labels2[:100] == \"1\"))\n self.assertTrue(np.all(labels2[100:] == \"0\"))\n\n # show that inner blocks are sorted correctly\n labels1 = labels1[sorted_inds]\n self.assertTrue(np.all(labels1[:50] == \"d\"))\n self.assertTrue(np.all(labels1[50:75] == \"c\"))\n self.assertTrue(np.all(labels1[75:100] == \"e\"))\n self.assertTrue(np.all(labels1[100:110] == \"d\"))\n self.assertTrue(np.all(labels1[110:] == \"c\"))\n\n # show that within block, everything is in descending degree order\n degrees = degrees[sorted_inds]\n self.assertTrue(np.all(np.diff(degrees[:50]) <= 0))\n self.assertTrue(np.all(np.diff(degrees[50:75]) <= 0))\n self.assertTrue(np.all(np.diff(degrees[75:100]) <= 0))\n self.assertTrue(np.all(np.diff(degrees[100:110]) <= 0))\n self.assertTrue(np.all(np.diff(degrees[110:]) <= 0))\n",
"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\n\nimport warnings\nfrom typing import Hashable, List, Optional, Set, Tuple, Union\n\nimport networkx as nx\nimport numpy as np\nfrom beartype import beartype\n\nfrom graspologic.embed import OmnibusEmbed\nfrom graspologic.preconditions import check_argument, is_real_weighted\nfrom graspologic.utils import (\n augment_diagonal,\n largest_connected_component,\n pass_to_ranks,\n remove_loops,\n)\n\nfrom . import __SVD_SOLVER_TYPES\nfrom ._elbow import _index_of_elbow\nfrom .embeddings import Embeddings\n\n\n@beartype\ndef omnibus_embedding_pairwise(\n graphs: List[Union[nx.Graph, nx.OrderedGraph, nx.DiGraph, nx.OrderedDiGraph]],\n dimensions: int = 100,\n elbow_cut: Optional[int] = None,\n svd_solver_algorithm: str = \"randomized\",\n svd_solver_iterations: int = 5,\n svd_seed: Optional[int] = None,\n weight_attribute: str = \"weight\",\n use_laplacian: bool = False,\n) -> List[Tuple[Embeddings, Embeddings]]:\n \"\"\"\n Generates a pairwise omnibus embedding for each pair of graphs in a list of graphs using the adjacency matrix.\n If given graphs A, B, and C, the embeddings will be computed for A, B and B, C.\n\n If the node labels differ between each pair of graphs, then those nodes will only be found in the resulting embedding\n if they exist in the largest connected component of the union of all edges across all graphs in the time series.\n\n Graphs will always have their diagonal augmented. In other words, a self-loop\n will be created for each node with a weight corresponding to the weighted degree.\n\n Lastly, all weights will be rescaled based on their relative rank in the graph,\n which is beneficial in minimizing anomalous results if some edge weights are\n extremely atypical of the rest of the graph.\n\n Parameters\n ----------\n graphs : List[Union[nx.Graph, nx.OrderedGraph, nx.DiGraph, nx.OrderedDiGraph]]\n A list of undirected or directed graphs. The graphs **must**:\n\n - be fully numerically weighted (every edge must have a real, numeric weight\n or else it will be treated as an unweighted graph)\n - be a basic graph (meaning it should not be a multigraph; if you have a\n multigraph you must first decide how you want to handle the weights of the\n edges between two nodes, whether summed, averaged, last-wins,\n maximum-weight-only, etc)\n dimensions : int (default=100)\n Dimensions to use for the svd solver.\n For undirected graphs, if ``elbow_cut==None``, you will receive an embedding\n that has ``nodes`` rows and ``dimensions`` columns.\n For directed graphs, if ``elbow_cut==None``, you will receive an embedding that\n has ``nodes`` rows and ``2*dimensions`` columns.\n If ``elbow_cut`` is specified to be not ``None``, we will cut the embedding at\n ``elbow_cut`` elbow, but the provided ``dimensions`` will be used in the\n creation of the SVD.\n elbow_cut : Optional[int] (default=None)\n Using a process described by Zhu & Ghodsi in their paper \"Automatic\n dimensionality selection from the scree plot via the use of profile likelihood\",\n truncate the dimensionality of the return on the ``elbow_cut``-th elbow.\n By default this value is ``None`` but can be used to reduce the dimensionality\n of the returned tensors.\n svd_solver_algorithm : str (default=\"randomized\")\n allowed values: {'randomized', 'full', 'truncated'}\n\n SVD solver to use:\n\n - 'randomized'\n Computes randomized svd using\n :func:`sklearn.utils.extmath.randomized_svd`\n - 'full'\n Computes full svd using :func:`scipy.linalg.svd`\n Does not support ``graph`` input of type scipy.sparse.csr_matrix\n - 'truncated'\n Computes truncated svd using :func:`scipy.sparse.linalg.svds`\n svd_solver_iterations : int (default=5)\n Number of iterations for randomized SVD solver. Not used by 'full' or\n 'truncated'. The default is larger than the default in randomized_svd\n to handle sparse matrices that may have large slowly decaying spectrum.\n svd_seed : Optional[int] (default=None)\n Used to seed the PRNG used in the ``randomized`` svd solver algorithm.\n weight_attribute : str (default=\"weight\")\n The edge dictionary key that contains the weight of the edge.\n use_laplacian : bool (default=False)\n Determine whether to use the Laplacian matrix of each graph in order to\n calculate the omnibus embedding using the Laplacian spectral embedding\n technique.\n\n Returns\n -------\n List[Tuple[Embeddings, Embeddings]]\n\n Raises\n ------\n beartype.roar.BeartypeCallHintPepParamException if parameters do not match type hints\n ValueError if values are not within appropriate ranges or allowed values\n\n See Also\n --------\n graspologic.pipeline.embed.Embeddings\n graspologic.embed.OmnibusEmbed\n graspologic.embed.AdjacencySpectralEmbed\n graspologic.embed.select_svd\n\n References\n ----------\n .. [1] Levin, K., Athreya, A., Tang, M., Lyzinski, V., & Priebe, C. E. (2017,\n November). A central limit theorem for an omnibus embedding of multiple random\n dot product graphs. In Data Mining Workshops (ICDMW), 2017 IEEE International\n Conference on (pp. 964-967). IEEE.\n\n .. [2] Sussman, D.L., Tang, M., Fishkind, D.E., Priebe, C.E. \"A\n Consistent Adjacency Spectral Embedding for Stochastic Blockmodel Graphs,\"\n Journal of the American Statistical Association, Vol. 107(499), 2012\n\n .. [3] Levin, K., Roosta-Khorasani, F., Mahoney, M. W., & Priebe, C. E. (2018).\n Out-of-sample extension of graph adjacency spectral embedding. PMLR: Proceedings\n of Machine Learning Research, 80, 2975-2984.\n\n .. [4] Zhu, M. and Ghodsi, A. (2006). Automatic dimensionality selection from the\n scree plot via the use of profile likelihood. Computational Statistics & Data\n Analysis, 51(2), pp.918-930.\n \"\"\"\n check_argument(len(graphs) > 1, \"more than one graph is required\")\n\n check_argument(dimensions >= 1, \"dimensions must be positive\")\n\n check_argument(elbow_cut is None or elbow_cut >= 1, \"elbow_cut must be positive\")\n\n check_argument(\n svd_solver_algorithm in __SVD_SOLVER_TYPES,\n f\"svd_solver_algorithm must be one of the values in {','.join(__SVD_SOLVER_TYPES)}\",\n )\n\n check_argument(svd_solver_iterations >= 1, \"svd_solver_iterations must be positive\")\n\n check_argument(\n svd_seed is None or 0 <= svd_seed <= 2 ** 32 - 1,\n \"svd_seed must be a nonnegative, 32-bit integer\",\n )\n\n weight_attribute = _graphs_precondition_checks(graphs, weight_attribute)\n perform_augment_diagonal = not use_laplacian\n\n graph_embeddings = []\n\n # create a graph that contains all nodes and edges across the entire corpus\n union_graph = graphs[0].copy()\n for graph in graphs[1:]:\n union_graph.add_edges_from(graph.edges())\n\n union_graph_lcc = largest_connected_component(union_graph)\n union_graph_lcc_nodes = set(list(union_graph_lcc.nodes()))\n\n union_node_ids = np.array(list(union_graph_lcc_nodes))\n\n previous_graph = graphs[0].copy()\n\n for graph in graphs[1:]:\n current_graph = graph.copy()\n\n # assure both graphs contain the exact same node set\n # by removing nodes or adding isolates as needed\n _sync_nodes(previous_graph, union_graph_lcc_nodes)\n _sync_nodes(current_graph, union_graph_lcc_nodes)\n\n # remove self loops, run pass to ranks and diagonal augmentation\n previous_graph_augmented = _augment_graph(\n previous_graph,\n union_graph_lcc_nodes,\n weight_attribute,\n perform_augment_diagonal=perform_augment_diagonal,\n )\n current_graph_augmented = _augment_graph(\n current_graph,\n union_graph_lcc_nodes,\n weight_attribute,\n perform_augment_diagonal=perform_augment_diagonal,\n )\n\n model = OmnibusEmbed(\n n_components=dimensions,\n n_elbows=None, # we will do elbow cuts\n algorithm=svd_solver_algorithm,\n n_iter=svd_solver_iterations,\n check_lcc=False,\n diag_aug=False,\n concat=False,\n svd_seed=svd_seed,\n lse=use_laplacian,\n )\n\n previous_embedding, current_embedding = model.fit_transform(\n graphs=[previous_graph_augmented, current_graph_augmented]\n )\n\n previous_embedding_cut = _elbow_cut_if_needed(\n elbow_cut, graph.is_directed(), model.singular_values_, previous_embedding\n )\n\n current_embedding_cut = _elbow_cut_if_needed(\n elbow_cut, graph.is_directed(), model.singular_values_, current_embedding\n )\n\n graph_embeddings.append(\n (\n Embeddings(union_node_ids, previous_embedding_cut),\n Embeddings(union_node_ids, current_embedding_cut),\n )\n )\n\n return graph_embeddings\n\n\ndef _graphs_precondition_checks(\n graphs: List[Union[nx.Graph, nx.OrderedGraph, nx.DiGraph, nx.OrderedDiGraph]],\n weight_attribute: str,\n) -> Optional[str]:\n is_directed = graphs[0].is_directed()\n\n for graph in graphs:\n check_argument(\n is_directed == graph.is_directed(),\n \"graphs must either be all directed or all undirected\",\n )\n\n check_argument(\n not graph.is_multigraph(),\n \"Multigraphs are not supported; you must determine how to represent at most \"\n \"one edge between any two nodes, and handle the corresponding weights \"\n \"accordingly\",\n )\n\n if not is_real_weighted(graph, weight_attribute=weight_attribute):\n warnings.warn(\n f\"Graphs with edges that do not have a real numeric weight set for every \"\n f\"{weight_attribute} attribute on every edge are treated as an unweighted \"\n f\"graph - which presumes all weights are `1.0`. If this is incorrect, \"\n f\"please add a '{weight_attribute}' attribute to every edge with a real, \"\n f\"numeric value (e.g. an integer or a float) and call this function again.\"\n )\n weight_attribute = None # this supercedes what the user said, because\n # not all of the weights are real numbers, if they exist at all\n # this weight=1.0 treatment actually happens in nx.to_scipy_sparse_matrix()\n\n return weight_attribute\n\n\ndef _elbow_cut_if_needed(\n elbow_cut: Optional[int],\n is_directed: bool,\n singular_values: np.ndarray,\n embedding: Union[np.ndarray, Tuple[np.ndarray, np.ndarray]],\n) -> np.ndarray:\n if elbow_cut is None:\n if is_directed:\n embedding = np.concatenate(embedding, axis=1)\n else:\n column_index = _index_of_elbow(singular_values, elbow_cut)\n\n if is_directed:\n left, right = embedding\n left = left[:, :column_index]\n right = right[:, :column_index]\n embedding = np.concatenate((left, right), axis=1)\n else:\n embedding = embedding[:, :column_index]\n\n return embedding\n\n\ndef _augment_graph(\n graph: Union[nx.Graph, nx.OrderedGraph, nx.DiGraph, nx.OrderedDiGraph],\n node_ids: Set[Hashable],\n weight_attribute: Optional[str],\n perform_augment_diagonal: bool = True,\n) -> np.ndarray:\n graph_sparse = nx.to_scipy_sparse_matrix(\n graph, weight=weight_attribute, nodelist=node_ids\n )\n\n graphs_loops_removed = remove_loops(graph_sparse)\n graphs_ranked = pass_to_ranks(graphs_loops_removed)\n\n if perform_augment_diagonal:\n return augment_diagonal(graphs_ranked)\n\n return graphs_ranked\n\n\ndef _sync_nodes(\n graph_to_reduce: Union[nx.Graph, nx.OrderedGraph, nx.DiGraph, nx.OrderedDiGraph],\n set_of_valid_nodes: Set[Hashable],\n) -> None:\n to_remove = []\n for n in graph_to_reduce.nodes():\n if n not in set_of_valid_nodes:\n to_remove.append(n)\n\n graph_to_reduce.remove_nodes_from(to_remove)\n\n for node in set_of_valid_nodes:\n if not graph_to_reduce.has_node(node):\n graph_to_reduce.add_node(node)\n"
] | [
[
"sklearn.mixture.GaussianMixture",
"numpy.all",
"numpy.diff",
"numpy.random.rand",
"numpy.argsort",
"numpy.array"
],
[
"numpy.concatenate"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
TUDelftHao/models | [
"faf0c2dc442ceaa8425aff73abd00f92f3137b7b",
"faf0c2dc442ceaa8425aff73abd00f92f3137b7b",
"faf0c2dc442ceaa8425aff73abd00f92f3137b7b",
"faf0c2dc442ceaa8425aff73abd00f92f3137b7b",
"faf0c2dc442ceaa8425aff73abd00f92f3137b7b",
"faf0c2dc442ceaa8425aff73abd00f92f3137b7b",
"faf0c2dc442ceaa8425aff73abd00f92f3137b7b"
] | [
"research/slim/nets/mobilenet_v1.py",
"research/object_detection/core/box_list_ops.py",
"official/vision/beta/modeling/backbones/spinenet.py",
"research/object_detection/meta_architectures/center_net_meta_arch.py",
"official/core/train_utils.py",
"official/nlp/modeling/networks/mobile_bert_encoder.py",
"official/vision/beta/ops/box_ops_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\"\"\"MobileNet v1.\n\nMobileNet is a general architecture and can be used for multiple use cases.\nDepending on the use case, it can use different input layer size and different\nhead (for example: embeddings, localization and classification).\n\nAs described in https://arxiv.org/abs/1704.04861.\n\n MobileNets: Efficient Convolutional Neural Networks for\n Mobile Vision Applications\n Andrew G. Howard, Menglong Zhu, Bo Chen, Dmitry Kalenichenko, Weijun Wang,\n Tobias Weyand, Marco Andreetto, Hartwig Adam\n\n100% Mobilenet V1 (base) with input size 224x224:\n\nSee mobilenet_v1()\n\nLayer params macs\n--------------------------------------------------------------------------------\nMobilenetV1/Conv2d_0/Conv2D: 864 10,838,016\nMobilenetV1/Conv2d_1_depthwise/depthwise: 288 3,612,672\nMobilenetV1/Conv2d_1_pointwise/Conv2D: 2,048 25,690,112\nMobilenetV1/Conv2d_2_depthwise/depthwise: 576 1,806,336\nMobilenetV1/Conv2d_2_pointwise/Conv2D: 8,192 25,690,112\nMobilenetV1/Conv2d_3_depthwise/depthwise: 1,152 3,612,672\nMobilenetV1/Conv2d_3_pointwise/Conv2D: 16,384 51,380,224\nMobilenetV1/Conv2d_4_depthwise/depthwise: 1,152 903,168\nMobilenetV1/Conv2d_4_pointwise/Conv2D: 32,768 25,690,112\nMobilenetV1/Conv2d_5_depthwise/depthwise: 2,304 1,806,336\nMobilenetV1/Conv2d_5_pointwise/Conv2D: 65,536 51,380,224\nMobilenetV1/Conv2d_6_depthwise/depthwise: 2,304 451,584\nMobilenetV1/Conv2d_6_pointwise/Conv2D: 131,072 25,690,112\nMobilenetV1/Conv2d_7_depthwise/depthwise: 4,608 903,168\nMobilenetV1/Conv2d_7_pointwise/Conv2D: 262,144 51,380,224\nMobilenetV1/Conv2d_8_depthwise/depthwise: 4,608 903,168\nMobilenetV1/Conv2d_8_pointwise/Conv2D: 262,144 51,380,224\nMobilenetV1/Conv2d_9_depthwise/depthwise: 4,608 903,168\nMobilenetV1/Conv2d_9_pointwise/Conv2D: 262,144 51,380,224\nMobilenetV1/Conv2d_10_depthwise/depthwise: 4,608 903,168\nMobilenetV1/Conv2d_10_pointwise/Conv2D: 262,144 51,380,224\nMobilenetV1/Conv2d_11_depthwise/depthwise: 4,608 903,168\nMobilenetV1/Conv2d_11_pointwise/Conv2D: 262,144 51,380,224\nMobilenetV1/Conv2d_12_depthwise/depthwise: 4,608 225,792\nMobilenetV1/Conv2d_12_pointwise/Conv2D: 524,288 25,690,112\nMobilenetV1/Conv2d_13_depthwise/depthwise: 9,216 451,584\nMobilenetV1/Conv2d_13_pointwise/Conv2D: 1,048,576 51,380,224\n--------------------------------------------------------------------------------\nTotal: 3,185,088 567,716,352\n\n\n75% Mobilenet V1 (base) with input size 128x128:\n\nSee mobilenet_v1_075()\n\nLayer params macs\n--------------------------------------------------------------------------------\nMobilenetV1/Conv2d_0/Conv2D: 648 2,654,208\nMobilenetV1/Conv2d_1_depthwise/depthwise: 216 884,736\nMobilenetV1/Conv2d_1_pointwise/Conv2D: 1,152 4,718,592\nMobilenetV1/Conv2d_2_depthwise/depthwise: 432 442,368\nMobilenetV1/Conv2d_2_pointwise/Conv2D: 4,608 4,718,592\nMobilenetV1/Conv2d_3_depthwise/depthwise: 864 884,736\nMobilenetV1/Conv2d_3_pointwise/Conv2D: 9,216 9,437,184\nMobilenetV1/Conv2d_4_depthwise/depthwise: 864 221,184\nMobilenetV1/Conv2d_4_pointwise/Conv2D: 18,432 4,718,592\nMobilenetV1/Conv2d_5_depthwise/depthwise: 1,728 442,368\nMobilenetV1/Conv2d_5_pointwise/Conv2D: 36,864 9,437,184\nMobilenetV1/Conv2d_6_depthwise/depthwise: 1,728 110,592\nMobilenetV1/Conv2d_6_pointwise/Conv2D: 73,728 4,718,592\nMobilenetV1/Conv2d_7_depthwise/depthwise: 3,456 221,184\nMobilenetV1/Conv2d_7_pointwise/Conv2D: 147,456 9,437,184\nMobilenetV1/Conv2d_8_depthwise/depthwise: 3,456 221,184\nMobilenetV1/Conv2d_8_pointwise/Conv2D: 147,456 9,437,184\nMobilenetV1/Conv2d_9_depthwise/depthwise: 3,456 221,184\nMobilenetV1/Conv2d_9_pointwise/Conv2D: 147,456 9,437,184\nMobilenetV1/Conv2d_10_depthwise/depthwise: 3,456 221,184\nMobilenetV1/Conv2d_10_pointwise/Conv2D: 147,456 9,437,184\nMobilenetV1/Conv2d_11_depthwise/depthwise: 3,456 221,184\nMobilenetV1/Conv2d_11_pointwise/Conv2D: 147,456 9,437,184\nMobilenetV1/Conv2d_12_depthwise/depthwise: 3,456 55,296\nMobilenetV1/Conv2d_12_pointwise/Conv2D: 294,912 4,718,592\nMobilenetV1/Conv2d_13_depthwise/depthwise: 6,912 110,592\nMobilenetV1/Conv2d_13_pointwise/Conv2D: 589,824 9,437,184\n--------------------------------------------------------------------------------\nTotal: 1,800,144 106,002,432\n\n\"\"\"\n\n# Tensorflow mandates these.\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom collections import namedtuple\nimport functools\n\nimport tensorflow.compat.v1 as tf\nimport tf_slim as slim\n\n# Conv and DepthSepConv namedtuple define layers of the MobileNet architecture\n# Conv defines 3x3 convolution layers\n# DepthSepConv defines 3x3 depthwise convolution followed by 1x1 convolution.\n# stride is the stride of the convolution\n# depth is the number of channels or filters in a layer\nConv = namedtuple('Conv', ['kernel', 'stride', 'depth'])\nDepthSepConv = namedtuple('DepthSepConv', ['kernel', 'stride', 'depth'])\n\n# MOBILENETV1_CONV_DEFS specifies the MobileNet body\nMOBILENETV1_CONV_DEFS = [\n Conv(kernel=[3, 3], stride=2, depth=32),\n DepthSepConv(kernel=[3, 3], stride=1, depth=64),\n DepthSepConv(kernel=[3, 3], stride=2, depth=128),\n DepthSepConv(kernel=[3, 3], stride=1, depth=128),\n DepthSepConv(kernel=[3, 3], stride=2, depth=256),\n DepthSepConv(kernel=[3, 3], stride=1, depth=256),\n DepthSepConv(kernel=[3, 3], stride=2, depth=512),\n DepthSepConv(kernel=[3, 3], stride=1, depth=512),\n DepthSepConv(kernel=[3, 3], stride=1, depth=512),\n DepthSepConv(kernel=[3, 3], stride=1, depth=512),\n DepthSepConv(kernel=[3, 3], stride=1, depth=512),\n DepthSepConv(kernel=[3, 3], stride=1, depth=512),\n DepthSepConv(kernel=[3, 3], stride=2, depth=1024),\n DepthSepConv(kernel=[3, 3], stride=1, depth=1024)\n]\n\n\ndef _fixed_padding(inputs, kernel_size, rate=1):\n \"\"\"Pads the input along the spatial dimensions independently of input size.\n\n Pads the input such that if it was used in a convolution with 'VALID' padding,\n the output would have the same dimensions as if the unpadded input was used\n in a convolution with 'SAME' padding.\n\n Args:\n inputs: A tensor of size [batch, height_in, width_in, channels].\n kernel_size: The kernel to be used in the conv2d or max_pool2d operation.\n rate: An integer, rate for atrous convolution.\n\n Returns:\n output: A tensor of size [batch, height_out, width_out, channels] with the\n input, either intact (if kernel_size == 1) or padded (if kernel_size > 1).\n \"\"\"\n kernel_size_effective = [kernel_size[0] + (kernel_size[0] - 1) * (rate - 1),\n kernel_size[0] + (kernel_size[0] - 1) * (rate - 1)]\n pad_total = [kernel_size_effective[0] - 1, kernel_size_effective[1] - 1]\n pad_beg = [pad_total[0] // 2, pad_total[1] // 2]\n pad_end = [pad_total[0] - pad_beg[0], pad_total[1] - pad_beg[1]]\n padded_inputs = tf.pad(\n tensor=inputs,\n paddings=[[0, 0], [pad_beg[0], pad_end[0]], [pad_beg[1], pad_end[1]],\n [0, 0]])\n return padded_inputs\n\n\ndef mobilenet_v1_base(inputs,\n final_endpoint='Conv2d_13_pointwise',\n min_depth=8,\n depth_multiplier=1.0,\n conv_defs=None,\n output_stride=None,\n use_explicit_padding=False,\n scope=None):\n \"\"\"Mobilenet v1.\n\n Constructs a Mobilenet v1 network from inputs to the given final endpoint.\n\n Args:\n inputs: a tensor of shape [batch_size, height, width, channels].\n final_endpoint: specifies the endpoint to construct the network up to. It\n can be one of ['Conv2d_0', 'Conv2d_1_pointwise', 'Conv2d_2_pointwise',\n 'Conv2d_3_pointwise', 'Conv2d_4_pointwise', 'Conv2d_5'_pointwise,\n 'Conv2d_6_pointwise', 'Conv2d_7_pointwise', 'Conv2d_8_pointwise',\n 'Conv2d_9_pointwise', 'Conv2d_10_pointwise', 'Conv2d_11_pointwise',\n 'Conv2d_12_pointwise', 'Conv2d_13_pointwise'].\n min_depth: Minimum depth value (number of channels) for all convolution ops.\n Enforced when depth_multiplier < 1, and not an active constraint when\n depth_multiplier >= 1.\n depth_multiplier: Float multiplier for the depth (number of channels)\n for all convolution ops. The value must be greater than zero. Typical\n usage will be to set this value in (0, 1) to reduce the number of\n parameters or computation cost of the model.\n conv_defs: A list of ConvDef namedtuples specifying the net architecture.\n output_stride: An integer that specifies the requested ratio of input to\n output spatial resolution. If not None, then we invoke atrous convolution\n if necessary to prevent the network from reducing the spatial resolution\n of the activation maps. Allowed values are 8 (accurate fully convolutional\n mode), 16 (fast fully convolutional mode), 32 (classification mode).\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 scope: Optional variable_scope.\n\n Returns:\n tensor_out: output tensor corresponding to the final_endpoint.\n end_points: a set of activations for external use, for example summaries or\n losses.\n\n Raises:\n ValueError: if final_endpoint is not set to one of the predefined values,\n or depth_multiplier <= 0, or the target output_stride is not\n allowed.\n \"\"\"\n depth = lambda d: max(int(d * depth_multiplier), min_depth)\n end_points = {}\n\n # Used to find thinned depths for each layer.\n if depth_multiplier <= 0:\n raise ValueError('depth_multiplier is not greater than zero.')\n\n if conv_defs is None:\n conv_defs = MOBILENETV1_CONV_DEFS\n\n if output_stride is not None and output_stride not in [8, 16, 32]:\n raise ValueError('Only allowed output_stride values are 8, 16, 32.')\n\n padding = 'SAME'\n if use_explicit_padding:\n padding = 'VALID'\n with tf.variable_scope(scope, 'MobilenetV1', [inputs]):\n with slim.arg_scope([slim.conv2d, slim.separable_conv2d], padding=padding):\n # The current_stride variable keeps track of the output stride of the\n # activations, i.e., the running product of convolution strides up to the\n # current network layer. This allows us to invoke atrous convolution\n # whenever applying the next convolution would result in the activations\n # having output stride larger than the target output_stride.\n current_stride = 1\n\n # The atrous convolution rate parameter.\n rate = 1\n\n net = inputs\n for i, conv_def in enumerate(conv_defs):\n end_point_base = 'Conv2d_%d' % i\n\n if output_stride is not None and current_stride == output_stride:\n # If we have reached the target output_stride, then we need to employ\n # atrous convolution with stride=1 and multiply the atrous rate by the\n # current unit's stride for use in subsequent layers.\n layer_stride = 1\n layer_rate = rate\n rate *= conv_def.stride\n else:\n layer_stride = conv_def.stride\n layer_rate = 1\n current_stride *= conv_def.stride\n\n if isinstance(conv_def, Conv):\n end_point = end_point_base\n if use_explicit_padding:\n net = _fixed_padding(net, conv_def.kernel)\n net = slim.conv2d(net, depth(conv_def.depth), conv_def.kernel,\n stride=conv_def.stride,\n scope=end_point)\n end_points[end_point] = net\n if end_point == final_endpoint:\n return net, end_points\n\n elif isinstance(conv_def, DepthSepConv):\n end_point = end_point_base + '_depthwise'\n\n # By passing filters=None\n # separable_conv2d produces only a depthwise convolution layer\n if use_explicit_padding:\n net = _fixed_padding(net, conv_def.kernel, layer_rate)\n net = slim.separable_conv2d(net, None, conv_def.kernel,\n depth_multiplier=1,\n stride=layer_stride,\n rate=layer_rate,\n scope=end_point)\n\n end_points[end_point] = net\n if end_point == final_endpoint:\n return net, end_points\n\n end_point = end_point_base + '_pointwise'\n\n net = slim.conv2d(net, depth(conv_def.depth), [1, 1],\n stride=1,\n scope=end_point)\n\n end_points[end_point] = net\n if end_point == final_endpoint:\n return net, end_points\n else:\n raise ValueError('Unknown convolution type %s for layer %d'\n % (conv_def.ltype, i))\n raise ValueError('Unknown final endpoint %s' % final_endpoint)\n\n\ndef mobilenet_v1(inputs,\n num_classes=1000,\n dropout_keep_prob=0.999,\n is_training=True,\n min_depth=8,\n depth_multiplier=1.0,\n conv_defs=None,\n prediction_fn=slim.softmax,\n spatial_squeeze=True,\n reuse=None,\n scope='MobilenetV1',\n global_pool=False):\n \"\"\"Mobilenet v1 model for classification.\n\n Args:\n inputs: a tensor of shape [batch_size, height, width, channels].\n num_classes: number of predicted classes. If 0 or None, the logits layer\n is omitted and the input features to the logits layer (before dropout)\n are returned instead.\n dropout_keep_prob: the percentage of activation values that are retained.\n is_training: whether is training or not.\n min_depth: Minimum depth value (number of channels) for all convolution ops.\n Enforced when depth_multiplier < 1, and not an active constraint when\n depth_multiplier >= 1.\n depth_multiplier: Float multiplier for the depth (number of channels)\n for all convolution ops. The value must be greater than zero. Typical\n usage will be to set this value in (0, 1) to reduce the number of\n parameters or computation cost of the model.\n conv_defs: A list of ConvDef namedtuples specifying the net architecture.\n prediction_fn: a function to get predictions out of logits.\n spatial_squeeze: if True, logits is of shape is [B, C], if false logits is\n of shape [B, 1, 1, C], where B is batch_size and C is number of classes.\n reuse: whether or not the network and its variables should be reused. To be\n able to reuse 'scope' must be given.\n scope: Optional variable_scope.\n global_pool: Optional boolean flag to control the avgpooling before the\n logits layer. If false or unset, pooling is done with a fixed window\n that reduces default-sized inputs to 1x1, while larger inputs lead to\n larger outputs. If true, any input size is pooled down to 1x1.\n\n Returns:\n net: a 2D Tensor with the logits (pre-softmax activations) if num_classes\n is a non-zero integer, or the non-dropped-out input to the logits layer\n if num_classes is 0 or None.\n end_points: a dictionary from components of the network to the corresponding\n activation.\n\n Raises:\n ValueError: Input rank is invalid.\n \"\"\"\n input_shape = inputs.get_shape().as_list()\n if len(input_shape) != 4:\n raise ValueError('Invalid input tensor rank, expected 4, was: %d' %\n len(input_shape))\n\n with tf.variable_scope(\n scope, 'MobilenetV1', [inputs], reuse=reuse) as scope:\n with slim.arg_scope([slim.batch_norm, slim.dropout],\n is_training=is_training):\n net, end_points = mobilenet_v1_base(inputs, scope=scope,\n min_depth=min_depth,\n depth_multiplier=depth_multiplier,\n conv_defs=conv_defs)\n with tf.variable_scope('Logits'):\n if global_pool:\n # Global average pooling.\n net = tf.reduce_mean(\n input_tensor=net, axis=[1, 2], keepdims=True, name='global_pool')\n end_points['global_pool'] = net\n else:\n # Pooling with a fixed kernel size.\n kernel_size = _reduced_kernel_size_for_small_input(net, [7, 7])\n net = slim.avg_pool2d(net, kernel_size, padding='VALID',\n scope='AvgPool_1a')\n end_points['AvgPool_1a'] = net\n if not num_classes:\n return net, end_points\n # 1 x 1 x 1024\n net = slim.dropout(net, keep_prob=dropout_keep_prob, scope='Dropout_1b')\n logits = slim.conv2d(net, num_classes, [1, 1], activation_fn=None,\n normalizer_fn=None, scope='Conv2d_1c_1x1')\n if spatial_squeeze:\n logits = tf.squeeze(logits, [1, 2], name='SpatialSqueeze')\n end_points['Logits'] = logits\n if prediction_fn:\n end_points['Predictions'] = prediction_fn(logits, scope='Predictions')\n return logits, end_points\n\nmobilenet_v1.default_image_size = 224\n\n\ndef wrapped_partial(func, *args, **kwargs):\n partial_func = functools.partial(func, *args, **kwargs)\n functools.update_wrapper(partial_func, func)\n return partial_func\n\n\nmobilenet_v1_075 = wrapped_partial(mobilenet_v1, depth_multiplier=0.75)\nmobilenet_v1_050 = wrapped_partial(mobilenet_v1, depth_multiplier=0.50)\nmobilenet_v1_025 = wrapped_partial(mobilenet_v1, depth_multiplier=0.25)\n\n\ndef _reduced_kernel_size_for_small_input(input_tensor, kernel_size):\n \"\"\"Define kernel size which is automatically reduced for small input.\n\n If the shape of the input images is unknown at graph construction time this\n function assumes that the input images are large enough.\n\n Args:\n input_tensor: input tensor of size [batch_size, height, width, channels].\n kernel_size: desired kernel size of length 2: [kernel_height, kernel_width]\n\n Returns:\n a tensor with the kernel size.\n \"\"\"\n shape = input_tensor.get_shape().as_list()\n if shape[1] is None or shape[2] is None:\n kernel_size_out = kernel_size\n else:\n kernel_size_out = [min(shape[1], kernel_size[0]),\n min(shape[2], kernel_size[1])]\n return kernel_size_out\n\n\ndef mobilenet_v1_arg_scope(\n is_training=True,\n weight_decay=0.00004,\n stddev=0.09,\n regularize_depthwise=False,\n batch_norm_decay=0.9997,\n batch_norm_epsilon=0.001,\n batch_norm_updates_collections=tf.GraphKeys.UPDATE_OPS,\n normalizer_fn=slim.batch_norm):\n \"\"\"Defines the default MobilenetV1 arg scope.\n\n Args:\n is_training: Whether or not we're training the model. If this is set to\n None, the parameter is not added to the batch_norm arg_scope.\n weight_decay: The weight decay to use for regularizing the model.\n stddev: The standard deviation of the trunctated normal weight initializer.\n regularize_depthwise: Whether or not apply regularization on depthwise.\n batch_norm_decay: Decay for batch norm moving average.\n batch_norm_epsilon: Small float added to variance to avoid dividing by zero\n in batch norm.\n batch_norm_updates_collections: Collection for the update ops for\n batch norm.\n normalizer_fn: Normalization function to apply after convolution.\n\n Returns:\n An `arg_scope` to use for the mobilenet v1 model.\n \"\"\"\n batch_norm_params = {\n 'center': True,\n 'scale': True,\n 'decay': batch_norm_decay,\n 'epsilon': batch_norm_epsilon,\n 'updates_collections': batch_norm_updates_collections,\n }\n if is_training is not None:\n batch_norm_params['is_training'] = is_training\n\n # Set weight_decay for weights in Conv and DepthSepConv layers.\n weights_init = tf.truncated_normal_initializer(stddev=stddev)\n regularizer = slim.l2_regularizer(weight_decay)\n if regularize_depthwise:\n depthwise_regularizer = regularizer\n else:\n depthwise_regularizer = None\n with slim.arg_scope([slim.conv2d, slim.separable_conv2d],\n weights_initializer=weights_init,\n activation_fn=tf.nn.relu6, normalizer_fn=normalizer_fn):\n with slim.arg_scope([slim.batch_norm], **batch_norm_params):\n with slim.arg_scope([slim.conv2d], weights_regularizer=regularizer):\n with slim.arg_scope([slim.separable_conv2d],\n weights_regularizer=depthwise_regularizer) as sc:\n return sc\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\"\"\"Bounding Box List operations.\n\nExample box operations that are supported:\n * areas: compute bounding box areas\n * iou: pairwise intersection-over-union scores\n * sq_dist: pairwise distances between bounding boxes\n\nWhenever box_list_ops functions output a BoxList, the fields of the incoming\nBoxList are retained unless documented otherwise.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom six.moves import range\nimport tensorflow.compat.v1 as tf\n\nfrom object_detection.core import box_list\nfrom object_detection.utils import ops\nfrom object_detection.utils import shape_utils\n\n\nclass SortOrder(object):\n \"\"\"Enum class for sort order.\n\n Attributes:\n ascend: ascend order.\n descend: descend order.\n \"\"\"\n ascend = 1\n descend = 2\n\n\ndef area(boxlist, scope=None):\n \"\"\"Computes area of boxes.\n\n Args:\n boxlist: BoxList holding N boxes\n scope: name scope.\n\n Returns:\n a tensor with shape [N] representing box areas.\n \"\"\"\n with tf.name_scope(scope, 'Area'):\n y_min, x_min, y_max, x_max = tf.split(\n value=boxlist.get(), num_or_size_splits=4, axis=1)\n return tf.squeeze((y_max - y_min) * (x_max - x_min), [1])\n\n\ndef height_width(boxlist, scope=None):\n \"\"\"Computes height and width of boxes in boxlist.\n\n Args:\n boxlist: BoxList holding N boxes\n scope: name scope.\n\n Returns:\n Height: A tensor with shape [N] representing box heights.\n Width: A tensor with shape [N] representing box widths.\n \"\"\"\n with tf.name_scope(scope, 'HeightWidth'):\n y_min, x_min, y_max, x_max = tf.split(\n value=boxlist.get(), num_or_size_splits=4, axis=1)\n return tf.squeeze(y_max - y_min, [1]), tf.squeeze(x_max - x_min, [1])\n\n\ndef scale(boxlist, y_scale, x_scale, scope=None):\n \"\"\"scale box coordinates in x and y dimensions.\n\n Args:\n boxlist: BoxList holding N boxes\n y_scale: (float) scalar tensor\n x_scale: (float) scalar tensor\n scope: name scope.\n\n Returns:\n boxlist: BoxList holding N boxes\n \"\"\"\n with tf.name_scope(scope, 'Scale'):\n y_scale = tf.cast(y_scale, tf.float32)\n x_scale = tf.cast(x_scale, tf.float32)\n y_min, x_min, y_max, x_max = tf.split(\n value=boxlist.get(), num_or_size_splits=4, axis=1)\n y_min = y_scale * y_min\n y_max = y_scale * y_max\n x_min = x_scale * x_min\n x_max = x_scale * x_max\n scaled_boxlist = box_list.BoxList(\n tf.concat([y_min, x_min, y_max, x_max], 1))\n return _copy_extra_fields(scaled_boxlist, boxlist)\n\n\ndef scale_height_width(boxlist, y_scale, x_scale, scope=None):\n \"\"\"Scale the height and width of boxes, leaving centers unchanged.\n\n Args:\n boxlist: BoxList holding N boxes\n y_scale: (float) scalar tensor\n x_scale: (float) scalar tensor\n scope: name scope.\n\n Returns:\n boxlist: BoxList holding N boxes\n \"\"\"\n with tf.name_scope(scope, 'ScaleHeightWidth'):\n y_scale = tf.cast(y_scale, tf.float32)\n x_scale = tf.cast(x_scale, tf.float32)\n yc, xc, height_orig, width_orig = boxlist.get_center_coordinates_and_sizes()\n y_min = yc - 0.5 * y_scale * height_orig\n y_max = yc + 0.5 * y_scale * height_orig\n x_min = xc - 0.5 * x_scale * width_orig\n x_max = xc + 0.5 * x_scale * width_orig\n scaled_boxlist = box_list.BoxList(\n tf.stack([y_min, x_min, y_max, x_max], 1))\n return _copy_extra_fields(scaled_boxlist, boxlist)\n\n\ndef clip_to_window(boxlist, window, filter_nonoverlapping=True, scope=None):\n \"\"\"Clip bounding boxes to a window.\n\n This op clips any input bounding boxes (represented by bounding box\n corners) to a window, optionally filtering out boxes that do not\n overlap at all with the window.\n\n Args:\n boxlist: BoxList holding M_in boxes\n window: a tensor of shape [4] representing the [y_min, x_min, y_max, x_max]\n window to which the op should clip boxes.\n filter_nonoverlapping: whether to filter out boxes that do not overlap at\n all with the window.\n scope: name scope.\n\n Returns:\n a BoxList holding M_out boxes where M_out <= M_in\n \"\"\"\n with tf.name_scope(scope, 'ClipToWindow'):\n y_min, x_min, y_max, x_max = tf.split(\n value=boxlist.get(), num_or_size_splits=4, axis=1)\n win_y_min, win_x_min, win_y_max, win_x_max = tf.unstack(window)\n y_min_clipped = tf.maximum(tf.minimum(y_min, win_y_max), win_y_min)\n y_max_clipped = tf.maximum(tf.minimum(y_max, win_y_max), win_y_min)\n x_min_clipped = tf.maximum(tf.minimum(x_min, win_x_max), win_x_min)\n x_max_clipped = tf.maximum(tf.minimum(x_max, win_x_max), win_x_min)\n clipped = box_list.BoxList(\n tf.concat([y_min_clipped, x_min_clipped, y_max_clipped, x_max_clipped],\n 1))\n clipped = _copy_extra_fields(clipped, boxlist)\n if filter_nonoverlapping:\n areas = area(clipped)\n nonzero_area_indices = tf.cast(\n tf.reshape(tf.where(tf.greater(areas, 0.0)), [-1]), tf.int32)\n clipped = gather(clipped, nonzero_area_indices)\n return clipped\n\n\ndef prune_outside_window(boxlist, window, scope=None):\n \"\"\"Prunes bounding boxes that fall outside a given window.\n\n This function prunes bounding boxes that even partially fall outside the given\n window. See also clip_to_window which only prunes bounding boxes that fall\n completely outside the window, and clips any bounding boxes that partially\n overflow.\n\n Args:\n boxlist: a BoxList holding M_in boxes.\n window: a float tensor of shape [4] representing [ymin, xmin, ymax, xmax]\n of the window\n scope: name scope.\n\n Returns:\n pruned_corners: a tensor with shape [M_out, 4] where M_out <= M_in\n valid_indices: a tensor with shape [M_out] indexing the valid bounding boxes\n in the input tensor.\n \"\"\"\n with tf.name_scope(scope, 'PruneOutsideWindow'):\n y_min, x_min, y_max, x_max = tf.split(\n value=boxlist.get(), num_or_size_splits=4, axis=1)\n win_y_min, win_x_min, win_y_max, win_x_max = tf.unstack(window)\n coordinate_violations = tf.concat([\n tf.less(y_min, win_y_min), tf.less(x_min, win_x_min),\n tf.greater(y_max, win_y_max), tf.greater(x_max, win_x_max)\n ], 1)\n valid_indices = tf.reshape(\n tf.where(tf.logical_not(tf.reduce_any(coordinate_violations, 1))), [-1])\n return gather(boxlist, valid_indices), valid_indices\n\n\ndef prune_completely_outside_window(boxlist, window, scope=None):\n \"\"\"Prunes bounding boxes that fall completely outside of the given window.\n\n The function clip_to_window prunes bounding boxes that fall\n completely outside the window, but also clips any bounding boxes that\n partially overflow. This function does not clip partially overflowing boxes.\n\n Args:\n boxlist: a BoxList holding M_in boxes.\n window: a float tensor of shape [4] representing [ymin, xmin, ymax, xmax]\n of the window\n scope: name scope.\n\n Returns:\n pruned_boxlist: a new BoxList with all bounding boxes partially or fully in\n the window.\n valid_indices: a tensor with shape [M_out] indexing the valid bounding boxes\n in the input tensor.\n \"\"\"\n with tf.name_scope(scope, 'PruneCompleteleyOutsideWindow'):\n y_min, x_min, y_max, x_max = tf.split(\n value=boxlist.get(), num_or_size_splits=4, axis=1)\n win_y_min, win_x_min, win_y_max, win_x_max = tf.unstack(window)\n coordinate_violations = tf.concat([\n tf.greater_equal(y_min, win_y_max), tf.greater_equal(x_min, win_x_max),\n tf.less_equal(y_max, win_y_min), tf.less_equal(x_max, win_x_min)\n ], 1)\n valid_indices = tf.reshape(\n tf.where(tf.logical_not(tf.reduce_any(coordinate_violations, 1))), [-1])\n return gather(boxlist, valid_indices), valid_indices\n\n\ndef intersection(boxlist1, boxlist2, scope=None):\n \"\"\"Compute pairwise intersection areas between boxes.\n\n Args:\n boxlist1: BoxList holding N boxes\n boxlist2: BoxList holding M boxes\n scope: name scope.\n\n Returns:\n a tensor with shape [N, M] representing pairwise intersections\n \"\"\"\n with tf.name_scope(scope, 'Intersection'):\n y_min1, x_min1, y_max1, x_max1 = tf.split(\n value=boxlist1.get(), num_or_size_splits=4, axis=1)\n y_min2, x_min2, y_max2, x_max2 = tf.split(\n value=boxlist2.get(), num_or_size_splits=4, axis=1)\n all_pairs_min_ymax = tf.minimum(y_max1, tf.transpose(y_max2))\n all_pairs_max_ymin = tf.maximum(y_min1, tf.transpose(y_min2))\n intersect_heights = tf.maximum(0.0, all_pairs_min_ymax - all_pairs_max_ymin)\n all_pairs_min_xmax = tf.minimum(x_max1, tf.transpose(x_max2))\n all_pairs_max_xmin = tf.maximum(x_min1, tf.transpose(x_min2))\n intersect_widths = tf.maximum(0.0, all_pairs_min_xmax - all_pairs_max_xmin)\n return intersect_heights * intersect_widths\n\n\ndef matched_intersection(boxlist1, boxlist2, scope=None):\n \"\"\"Compute intersection areas between corresponding boxes in two boxlists.\n\n Args:\n boxlist1: BoxList holding N boxes\n boxlist2: BoxList holding N boxes\n scope: name scope.\n\n Returns:\n a tensor with shape [N] representing pairwise intersections\n \"\"\"\n with tf.name_scope(scope, 'MatchedIntersection'):\n y_min1, x_min1, y_max1, x_max1 = tf.split(\n value=boxlist1.get(), num_or_size_splits=4, axis=1)\n y_min2, x_min2, y_max2, x_max2 = tf.split(\n value=boxlist2.get(), num_or_size_splits=4, axis=1)\n min_ymax = tf.minimum(y_max1, y_max2)\n max_ymin = tf.maximum(y_min1, y_min2)\n intersect_heights = tf.maximum(0.0, min_ymax - max_ymin)\n min_xmax = tf.minimum(x_max1, x_max2)\n max_xmin = tf.maximum(x_min1, x_min2)\n intersect_widths = tf.maximum(0.0, min_xmax - max_xmin)\n return tf.reshape(intersect_heights * intersect_widths, [-1])\n\n\ndef iou(boxlist1, boxlist2, scope=None):\n \"\"\"Computes pairwise intersection-over-union between box collections.\n\n Args:\n boxlist1: BoxList holding N boxes\n boxlist2: BoxList holding M boxes\n scope: name scope.\n\n Returns:\n a tensor with shape [N, M] representing pairwise iou scores.\n \"\"\"\n with tf.name_scope(scope, 'IOU'):\n intersections = intersection(boxlist1, boxlist2)\n areas1 = area(boxlist1)\n areas2 = area(boxlist2)\n unions = (\n tf.expand_dims(areas1, 1) + tf.expand_dims(areas2, 0) - intersections)\n return tf.where(\n tf.equal(intersections, 0.0),\n tf.zeros_like(intersections), tf.truediv(intersections, unions))\n\n\ndef l1(boxlist1, boxlist2, scope=None):\n \"\"\"Computes l1 loss (pairwise) between two boxlists.\n\n Args:\n boxlist1: BoxList holding N boxes\n boxlist2: BoxList holding M boxes\n scope: name scope.\n\n Returns:\n a tensor with shape [N, M] representing the pairwise L1 loss.\n \"\"\"\n with tf.name_scope(scope, 'PairwiseL1'):\n ycenter1, xcenter1, h1, w1 = boxlist1.get_center_coordinates_and_sizes()\n ycenter2, xcenter2, h2, w2 = boxlist2.get_center_coordinates_and_sizes()\n ycenters = tf.abs(tf.expand_dims(ycenter2, axis=0) - tf.expand_dims(\n tf.transpose(ycenter1), axis=1))\n xcenters = tf.abs(tf.expand_dims(xcenter2, axis=0) - tf.expand_dims(\n tf.transpose(xcenter1), axis=1))\n heights = tf.abs(tf.expand_dims(h2, axis=0) - tf.expand_dims(\n tf.transpose(h1), axis=1))\n widths = tf.abs(tf.expand_dims(w2, axis=0) - tf.expand_dims(\n tf.transpose(w1), axis=1))\n return ycenters + xcenters + heights + widths\n\n\ndef giou(boxlist1, boxlist2, scope=None):\n \"\"\"Computes pairwise generalized IOU between two boxlists.\n\n Args:\n boxlist1: BoxList holding N boxes\n boxlist2: BoxList holding M boxes\n scope: name scope.\n\n Returns:\n a tensor with shape [N, M] representing the pairwise GIoU loss.\n \"\"\"\n with tf.name_scope(scope, 'PairwiseGIoU'):\n n = boxlist1.num_boxes()\n m = boxlist2.num_boxes()\n boxes1 = tf.repeat(boxlist1.get(), repeats=m, axis=0)\n boxes2 = tf.tile(boxlist2.get(), multiples=[n, 1])\n return tf.reshape(ops.giou(boxes1, boxes2), [n, m])\n\n\ndef matched_iou(boxlist1, boxlist2, scope=None):\n \"\"\"Compute intersection-over-union between corresponding boxes in boxlists.\n\n Args:\n boxlist1: BoxList holding N boxes\n boxlist2: BoxList holding N boxes\n scope: name scope.\n\n Returns:\n a tensor with shape [N] representing pairwise iou scores.\n \"\"\"\n with tf.name_scope(scope, 'MatchedIOU'):\n intersections = matched_intersection(boxlist1, boxlist2)\n areas1 = area(boxlist1)\n areas2 = area(boxlist2)\n unions = areas1 + areas2 - intersections\n return tf.where(\n tf.equal(intersections, 0.0),\n tf.zeros_like(intersections), tf.truediv(intersections, unions))\n\n\ndef ioa(boxlist1, boxlist2, scope=None):\n \"\"\"Computes pairwise intersection-over-area between box collections.\n\n intersection-over-area (IOA) between two boxes box1 and box2 is defined as\n their intersection area over box2's area. Note that ioa is not symmetric,\n that is, ioa(box1, box2) != ioa(box2, box1).\n\n Args:\n boxlist1: BoxList holding N boxes\n boxlist2: BoxList holding M boxes\n scope: name scope.\n\n Returns:\n a tensor with shape [N, M] representing pairwise ioa scores.\n \"\"\"\n with tf.name_scope(scope, 'IOA'):\n intersections = intersection(boxlist1, boxlist2)\n areas = tf.expand_dims(area(boxlist2), 0)\n return tf.truediv(intersections, areas)\n\n\ndef prune_non_overlapping_boxes(\n boxlist1, boxlist2, min_overlap=0.0, scope=None):\n \"\"\"Prunes the boxes in boxlist1 that overlap less than thresh with boxlist2.\n\n For each box in boxlist1, we want its IOA to be more than minoverlap with\n at least one of the boxes in boxlist2. If it does not, we remove it.\n\n Args:\n boxlist1: BoxList holding N boxes.\n boxlist2: BoxList holding M boxes.\n min_overlap: Minimum required overlap between boxes, to count them as\n overlapping.\n scope: name scope.\n\n Returns:\n new_boxlist1: A pruned boxlist with size [N', 4].\n keep_inds: A tensor with shape [N'] indexing kept bounding boxes in the\n first input BoxList `boxlist1`.\n \"\"\"\n with tf.name_scope(scope, 'PruneNonOverlappingBoxes'):\n ioa_ = ioa(boxlist2, boxlist1) # [M, N] tensor\n ioa_ = tf.reduce_max(ioa_, reduction_indices=[0]) # [N] tensor\n keep_bool = tf.greater_equal(ioa_, tf.constant(min_overlap))\n keep_inds = tf.squeeze(tf.where(keep_bool), axis=[1])\n new_boxlist1 = gather(boxlist1, keep_inds)\n return new_boxlist1, keep_inds\n\n\ndef prune_small_boxes(boxlist, min_side, scope=None):\n \"\"\"Prunes small boxes in the boxlist which have a side smaller than min_side.\n\n Args:\n boxlist: BoxList holding N boxes.\n min_side: Minimum width AND height of box to survive pruning.\n scope: name scope.\n\n Returns:\n A pruned boxlist.\n \"\"\"\n with tf.name_scope(scope, 'PruneSmallBoxes'):\n height, width = height_width(boxlist)\n is_valid = tf.logical_and(tf.greater_equal(width, min_side),\n tf.greater_equal(height, min_side))\n return gather(boxlist, tf.reshape(tf.where(is_valid), [-1]))\n\n\ndef change_coordinate_frame(boxlist, window, scope=None):\n \"\"\"Change coordinate frame of the boxlist to be relative to window's frame.\n\n Given a window of the form [ymin, xmin, ymax, xmax],\n changes bounding box coordinates from boxlist to be relative to this window\n (e.g., the min corner maps to (0,0) and the max corner maps to (1,1)).\n\n An example use case is data augmentation: where we are given groundtruth\n boxes (boxlist) and would like to randomly crop the image to some\n window (window). In this case we need to change the coordinate frame of\n each groundtruth box to be relative to this new window.\n\n Args:\n boxlist: A BoxList object holding N boxes.\n window: A rank 1 tensor [4].\n scope: name scope.\n\n Returns:\n Returns a BoxList object with N boxes.\n \"\"\"\n with tf.name_scope(scope, 'ChangeCoordinateFrame'):\n win_height = window[2] - window[0]\n win_width = window[3] - window[1]\n boxlist_new = scale(box_list.BoxList(\n boxlist.get() - [window[0], window[1], window[0], window[1]]),\n 1.0 / win_height, 1.0 / win_width)\n boxlist_new = _copy_extra_fields(boxlist_new, boxlist)\n return boxlist_new\n\n\ndef sq_dist(boxlist1, boxlist2, scope=None):\n \"\"\"Computes the pairwise squared distances between box corners.\n\n This op treats each box as if it were a point in a 4d Euclidean space and\n computes pairwise squared distances.\n\n Mathematically, we are given two matrices of box coordinates X and Y,\n where X(i,:) is the i'th row of X, containing the 4 numbers defining the\n corners of the i'th box in boxlist1. Similarly Y(j,:) corresponds to\n boxlist2. We compute\n Z(i,j) = ||X(i,:) - Y(j,:)||^2\n = ||X(i,:)||^2 + ||Y(j,:)||^2 - 2 X(i,:)' * Y(j,:),\n\n Args:\n boxlist1: BoxList holding N boxes\n boxlist2: BoxList holding M boxes\n scope: name scope.\n\n Returns:\n a tensor with shape [N, M] representing pairwise distances\n \"\"\"\n with tf.name_scope(scope, 'SqDist'):\n sqnorm1 = tf.reduce_sum(tf.square(boxlist1.get()), 1, keep_dims=True)\n sqnorm2 = tf.reduce_sum(tf.square(boxlist2.get()), 1, keep_dims=True)\n innerprod = tf.matmul(boxlist1.get(), boxlist2.get(),\n transpose_a=False, transpose_b=True)\n return sqnorm1 + tf.transpose(sqnorm2) - 2.0 * innerprod\n\n\ndef boolean_mask(boxlist, indicator, fields=None, scope=None,\n use_static_shapes=False, indicator_sum=None):\n \"\"\"Select boxes from BoxList according to indicator and return new BoxList.\n\n `boolean_mask` returns the subset of boxes that are marked as \"True\" by the\n indicator tensor. By default, `boolean_mask` returns boxes corresponding to\n the input index list, as well as all additional fields stored in the boxlist\n (indexing into the first dimension). However one can optionally only draw\n from a subset of fields.\n\n Args:\n boxlist: BoxList holding N boxes\n indicator: a rank-1 boolean tensor\n fields: (optional) list of fields to also gather from. If None (default),\n all fields are gathered from. Pass an empty fields list to only gather\n the box coordinates.\n scope: name scope.\n use_static_shapes: Whether to use an implementation with static shape\n gurantees.\n indicator_sum: An integer containing the sum of `indicator` vector. Only\n required if `use_static_shape` is True.\n\n Returns:\n subboxlist: a BoxList corresponding to the subset of the input BoxList\n specified by indicator\n Raises:\n ValueError: if `indicator` is not a rank-1 boolean tensor.\n \"\"\"\n with tf.name_scope(scope, 'BooleanMask'):\n if indicator.shape.ndims != 1:\n raise ValueError('indicator should have rank 1')\n if indicator.dtype != tf.bool:\n raise ValueError('indicator should be a boolean tensor')\n if use_static_shapes:\n if not (indicator_sum and isinstance(indicator_sum, int)):\n raise ValueError('`indicator_sum` must be a of type int')\n selected_positions = tf.cast(indicator, dtype=tf.float32)\n indexed_positions = tf.cast(\n tf.multiply(\n tf.cumsum(selected_positions), selected_positions),\n dtype=tf.int32)\n one_hot_selector = tf.one_hot(\n indexed_positions - 1, indicator_sum, dtype=tf.float32)\n sampled_indices = tf.cast(\n tf.tensordot(\n tf.cast(tf.range(tf.shape(indicator)[0]), dtype=tf.float32),\n one_hot_selector,\n axes=[0, 0]),\n dtype=tf.int32)\n return gather(boxlist, sampled_indices, use_static_shapes=True)\n else:\n subboxlist = box_list.BoxList(tf.boolean_mask(boxlist.get(), indicator))\n if fields is None:\n fields = boxlist.get_extra_fields()\n for field in fields:\n if not boxlist.has_field(field):\n raise ValueError('boxlist must contain all specified fields')\n subfieldlist = tf.boolean_mask(boxlist.get_field(field), indicator)\n subboxlist.add_field(field, subfieldlist)\n return subboxlist\n\n\ndef gather(boxlist, indices, fields=None, scope=None, use_static_shapes=False):\n \"\"\"Gather boxes from BoxList according to indices and return new BoxList.\n\n By default, `gather` returns boxes corresponding to the input index list, as\n well as all additional fields stored in the boxlist (indexing into the\n first dimension). However one can optionally only gather from a\n subset of fields.\n\n Args:\n boxlist: BoxList holding N boxes\n indices: a rank-1 tensor of type int32 / int64\n fields: (optional) list of fields to also gather from. If None (default),\n all fields are gathered from. Pass an empty fields list to only gather\n the box coordinates.\n scope: name scope.\n use_static_shapes: Whether to use an implementation with static shape\n gurantees.\n\n Returns:\n subboxlist: a BoxList corresponding to the subset of the input BoxList\n specified by indices\n Raises:\n ValueError: if specified field is not contained in boxlist or if the\n indices are not of type int32\n \"\"\"\n with tf.name_scope(scope, 'Gather'):\n if len(indices.shape.as_list()) != 1:\n raise ValueError('indices should have rank 1')\n if indices.dtype != tf.int32 and indices.dtype != tf.int64:\n raise ValueError('indices should be an int32 / int64 tensor')\n gather_op = tf.gather\n if use_static_shapes:\n gather_op = ops.matmul_gather_on_zeroth_axis\n subboxlist = box_list.BoxList(gather_op(boxlist.get(), indices))\n if fields is None:\n fields = boxlist.get_extra_fields()\n fields += ['boxes']\n for field in fields:\n if not boxlist.has_field(field):\n raise ValueError('boxlist must contain all specified fields')\n subfieldlist = gather_op(boxlist.get_field(field), indices)\n subboxlist.add_field(field, subfieldlist)\n return subboxlist\n\n\ndef concatenate(boxlists, fields=None, scope=None):\n \"\"\"Concatenate list of BoxLists.\n\n This op concatenates a list of input BoxLists into a larger BoxList. It also\n handles concatenation of BoxList fields as long as the field tensor shapes\n are equal except for the first dimension.\n\n Args:\n boxlists: list of BoxList objects\n fields: optional list of fields to also concatenate. By default, all\n fields from the first BoxList in the list are included in the\n concatenation.\n scope: name scope.\n\n Returns:\n a BoxList with number of boxes equal to\n sum([boxlist.num_boxes() for boxlist in BoxList])\n Raises:\n ValueError: if boxlists is invalid (i.e., is not a list, is empty, or\n contains non BoxList objects), or if requested fields are not contained in\n all boxlists\n \"\"\"\n with tf.name_scope(scope, 'Concatenate'):\n if not isinstance(boxlists, list):\n raise ValueError('boxlists should be a list')\n if not boxlists:\n raise ValueError('boxlists should have nonzero length')\n for boxlist in boxlists:\n if not isinstance(boxlist, box_list.BoxList):\n raise ValueError('all elements of boxlists should be BoxList objects')\n concatenated = box_list.BoxList(\n tf.concat([boxlist.get() for boxlist in boxlists], 0))\n if fields is None:\n fields = boxlists[0].get_extra_fields()\n for field in fields:\n first_field_shape = boxlists[0].get_field(field).get_shape().as_list()\n first_field_shape[0] = -1\n if None in first_field_shape:\n raise ValueError('field %s must have fully defined shape except for the'\n ' 0th dimension.' % field)\n for boxlist in boxlists:\n if not boxlist.has_field(field):\n raise ValueError('boxlist must contain all requested fields')\n field_shape = boxlist.get_field(field).get_shape().as_list()\n field_shape[0] = -1\n if field_shape != first_field_shape:\n raise ValueError('field %s must have same shape for all boxlists '\n 'except for the 0th dimension.' % field)\n concatenated_field = tf.concat(\n [boxlist.get_field(field) for boxlist in boxlists], 0)\n concatenated.add_field(field, concatenated_field)\n return concatenated\n\n\ndef sort_by_field(boxlist, field, order=SortOrder.descend, scope=None):\n \"\"\"Sort boxes and associated fields according to a scalar field.\n\n A common use case is reordering the boxes according to descending scores.\n\n Args:\n boxlist: BoxList holding N boxes.\n field: A BoxList field for sorting and reordering the BoxList.\n order: (Optional) descend or ascend. Default is descend.\n scope: name scope.\n\n Returns:\n sorted_boxlist: A sorted BoxList with the field in the specified order.\n\n Raises:\n ValueError: if specified field does not exist\n ValueError: if the order is not either descend or ascend\n \"\"\"\n with tf.name_scope(scope, 'SortByField'):\n if order != SortOrder.descend and order != SortOrder.ascend:\n raise ValueError('Invalid sort order')\n\n field_to_sort = boxlist.get_field(field)\n if len(field_to_sort.shape.as_list()) != 1:\n raise ValueError('Field should have rank 1')\n\n num_boxes = boxlist.num_boxes()\n num_entries = tf.size(field_to_sort)\n length_assert = tf.Assert(\n tf.equal(num_boxes, num_entries),\n ['Incorrect field size: actual vs expected.', num_entries, num_boxes])\n\n with tf.control_dependencies([length_assert]):\n _, sorted_indices = tf.nn.top_k(field_to_sort, num_boxes, sorted=True)\n\n if order == SortOrder.ascend:\n sorted_indices = tf.reverse_v2(sorted_indices, [0])\n\n return gather(boxlist, sorted_indices)\n\n\ndef visualize_boxes_in_image(image, boxlist, normalized=False, scope=None):\n \"\"\"Overlay bounding box list on image.\n\n Currently this visualization plots a 1 pixel thick red bounding box on top\n of the image. Note that tf.image.draw_bounding_boxes essentially is\n 1 indexed.\n\n Args:\n image: an image tensor with shape [height, width, 3]\n boxlist: a BoxList\n normalized: (boolean) specify whether corners are to be interpreted\n as absolute coordinates in image space or normalized with respect to the\n image size.\n scope: name scope.\n\n Returns:\n image_and_boxes: an image tensor with shape [height, width, 3]\n \"\"\"\n with tf.name_scope(scope, 'VisualizeBoxesInImage'):\n if not normalized:\n height, width, _ = tf.unstack(tf.shape(image))\n boxlist = scale(boxlist,\n 1.0 / tf.cast(height, tf.float32),\n 1.0 / tf.cast(width, tf.float32))\n corners = tf.expand_dims(boxlist.get(), 0)\n image = tf.expand_dims(image, 0)\n return tf.squeeze(tf.image.draw_bounding_boxes(image, corners), [0])\n\n\ndef filter_field_value_equals(boxlist, field, value, scope=None):\n \"\"\"Filter to keep only boxes with field entries equal to the given value.\n\n Args:\n boxlist: BoxList holding N boxes.\n field: field name for filtering.\n value: scalar value.\n scope: name scope.\n\n Returns:\n a BoxList holding M boxes where M <= N\n\n Raises:\n ValueError: if boxlist not a BoxList object or if it does not have\n the specified field.\n \"\"\"\n with tf.name_scope(scope, 'FilterFieldValueEquals'):\n if not isinstance(boxlist, box_list.BoxList):\n raise ValueError('boxlist must be a BoxList')\n if not boxlist.has_field(field):\n raise ValueError('boxlist must contain the specified field')\n filter_field = boxlist.get_field(field)\n gather_index = tf.reshape(tf.where(tf.equal(filter_field, value)), [-1])\n return gather(boxlist, gather_index)\n\n\ndef filter_greater_than(boxlist, thresh, scope=None):\n \"\"\"Filter to keep only boxes with score exceeding a given threshold.\n\n This op keeps the collection of boxes whose corresponding scores are\n greater than the input threshold.\n\n TODO(jonathanhuang): Change function name to filter_scores_greater_than\n\n Args:\n boxlist: BoxList holding N boxes. Must contain a 'scores' field\n representing detection scores.\n thresh: scalar threshold\n scope: name scope.\n\n Returns:\n a BoxList holding M boxes where M <= N\n\n Raises:\n ValueError: if boxlist not a BoxList object or if it does not\n have a scores field\n \"\"\"\n with tf.name_scope(scope, 'FilterGreaterThan'):\n if not isinstance(boxlist, box_list.BoxList):\n raise ValueError('boxlist must be a BoxList')\n if not boxlist.has_field('scores'):\n raise ValueError('input boxlist must have \\'scores\\' field')\n scores = boxlist.get_field('scores')\n if len(scores.shape.as_list()) > 2:\n raise ValueError('Scores should have rank 1 or 2')\n if len(scores.shape.as_list()) == 2 and scores.shape.as_list()[1] != 1:\n raise ValueError('Scores should have rank 1 or have shape '\n 'consistent with [None, 1]')\n high_score_indices = tf.cast(tf.reshape(\n tf.where(tf.greater(scores, thresh)),\n [-1]), tf.int32)\n return gather(boxlist, high_score_indices)\n\n\ndef non_max_suppression(boxlist, thresh, max_output_size, scope=None):\n \"\"\"Non maximum suppression.\n\n This op greedily selects a subset of detection bounding boxes, pruning\n away boxes that have high IOU (intersection over union) overlap (> thresh)\n with already selected boxes. Note that this only works for a single class ---\n to apply NMS to multi-class predictions, use MultiClassNonMaxSuppression.\n\n Args:\n boxlist: BoxList holding N boxes. Must contain a 'scores' field\n representing detection scores.\n thresh: scalar threshold\n max_output_size: maximum number of retained boxes\n scope: name scope.\n\n Returns:\n a BoxList holding M boxes where M <= max_output_size\n Raises:\n ValueError: if thresh is not in [0, 1]\n \"\"\"\n with tf.name_scope(scope, 'NonMaxSuppression'):\n if not 0 <= thresh <= 1.0:\n raise ValueError('thresh must be between 0 and 1')\n if not isinstance(boxlist, box_list.BoxList):\n raise ValueError('boxlist must be a BoxList')\n if not boxlist.has_field('scores'):\n raise ValueError('input boxlist must have \\'scores\\' field')\n selected_indices = tf.image.non_max_suppression(\n boxlist.get(), boxlist.get_field('scores'),\n max_output_size, iou_threshold=thresh)\n return gather(boxlist, selected_indices)\n\n\ndef _copy_extra_fields(boxlist_to_copy_to, boxlist_to_copy_from):\n \"\"\"Copies the extra fields of boxlist_to_copy_from to boxlist_to_copy_to.\n\n Args:\n boxlist_to_copy_to: BoxList to which extra fields are copied.\n boxlist_to_copy_from: BoxList from which fields are copied.\n\n Returns:\n boxlist_to_copy_to with extra fields.\n \"\"\"\n for field in boxlist_to_copy_from.get_extra_fields():\n boxlist_to_copy_to.add_field(field, boxlist_to_copy_from.get_field(field))\n return boxlist_to_copy_to\n\n\ndef to_normalized_coordinates(boxlist, height, width,\n check_range=True, scope=None):\n \"\"\"Converts absolute box coordinates to normalized coordinates in [0, 1].\n\n Usually one uses the dynamic shape of the image or conv-layer tensor:\n boxlist = box_list_ops.to_normalized_coordinates(boxlist,\n tf.shape(images)[1],\n tf.shape(images)[2]),\n\n This function raises an assertion failed error at graph execution time when\n the maximum coordinate is smaller than 1.01 (which means that coordinates are\n already normalized). The value 1.01 is to deal with small rounding errors.\n\n Args:\n boxlist: BoxList with coordinates in terms of pixel-locations.\n height: Maximum value for height of absolute box coordinates.\n width: Maximum value for width of absolute box coordinates.\n check_range: If True, checks if the coordinates are normalized or not.\n scope: name scope.\n\n Returns:\n boxlist with normalized coordinates in [0, 1].\n \"\"\"\n with tf.name_scope(scope, 'ToNormalizedCoordinates'):\n height = tf.cast(height, tf.float32)\n width = tf.cast(width, tf.float32)\n\n if check_range:\n max_val = tf.reduce_max(boxlist.get())\n max_assert = tf.Assert(tf.greater(max_val, 1.01),\n ['max value is lower than 1.01: ', max_val])\n with tf.control_dependencies([max_assert]):\n width = tf.identity(width)\n\n return scale(boxlist, 1 / height, 1 / width)\n\n\ndef to_absolute_coordinates(boxlist,\n height,\n width,\n check_range=True,\n maximum_normalized_coordinate=1.1,\n scope=None):\n \"\"\"Converts normalized box coordinates to absolute pixel coordinates.\n\n This function raises an assertion failed error when the maximum box coordinate\n value is larger than maximum_normalized_coordinate (in which case coordinates\n are already absolute).\n\n Args:\n boxlist: BoxList with coordinates in range [0, 1].\n height: Maximum value for height of absolute box coordinates.\n width: Maximum value for width of absolute box coordinates.\n check_range: If True, checks if the coordinates are normalized or not.\n maximum_normalized_coordinate: Maximum coordinate value to be considered\n as normalized, default to 1.1.\n scope: name scope.\n\n Returns:\n boxlist with absolute coordinates in terms of the image size.\n\n \"\"\"\n with tf.name_scope(scope, 'ToAbsoluteCoordinates'):\n height = tf.cast(height, tf.float32)\n width = tf.cast(width, tf.float32)\n\n # Ensure range of input boxes is correct.\n if check_range:\n box_maximum = tf.reduce_max(boxlist.get())\n max_assert = tf.Assert(\n tf.greater_equal(maximum_normalized_coordinate, box_maximum),\n ['maximum box coordinate value is larger '\n 'than %f: ' % maximum_normalized_coordinate, box_maximum])\n with tf.control_dependencies([max_assert]):\n width = tf.identity(width)\n\n return scale(boxlist, height, width)\n\n\ndef refine_boxes_multi_class(pool_boxes,\n num_classes,\n nms_iou_thresh,\n nms_max_detections,\n voting_iou_thresh=0.5):\n \"\"\"Refines a pool of boxes using non max suppression and box voting.\n\n Box refinement is done independently for each class.\n\n Args:\n pool_boxes: (BoxList) A collection of boxes to be refined. pool_boxes must\n have a rank 1 'scores' field and a rank 1 'classes' field.\n num_classes: (int scalar) Number of classes.\n nms_iou_thresh: (float scalar) iou threshold for non max suppression (NMS).\n nms_max_detections: (int scalar) maximum output size for NMS.\n voting_iou_thresh: (float scalar) iou threshold for box voting.\n\n Returns:\n BoxList of refined boxes.\n\n Raises:\n ValueError: if\n a) nms_iou_thresh or voting_iou_thresh is not in [0, 1].\n b) pool_boxes is not a BoxList.\n c) pool_boxes does not have a scores and classes field.\n \"\"\"\n if not 0.0 <= nms_iou_thresh <= 1.0:\n raise ValueError('nms_iou_thresh must be between 0 and 1')\n if not 0.0 <= voting_iou_thresh <= 1.0:\n raise ValueError('voting_iou_thresh must be between 0 and 1')\n if not isinstance(pool_boxes, box_list.BoxList):\n raise ValueError('pool_boxes must be a BoxList')\n if not pool_boxes.has_field('scores'):\n raise ValueError('pool_boxes must have a \\'scores\\' field')\n if not pool_boxes.has_field('classes'):\n raise ValueError('pool_boxes must have a \\'classes\\' field')\n\n refined_boxes = []\n for i in range(num_classes):\n boxes_class = filter_field_value_equals(pool_boxes, 'classes', i)\n refined_boxes_class = refine_boxes(boxes_class, nms_iou_thresh,\n nms_max_detections, voting_iou_thresh)\n refined_boxes.append(refined_boxes_class)\n return sort_by_field(concatenate(refined_boxes), 'scores')\n\n\ndef refine_boxes(pool_boxes,\n nms_iou_thresh,\n nms_max_detections,\n voting_iou_thresh=0.5):\n \"\"\"Refines a pool of boxes using non max suppression and box voting.\n\n Args:\n pool_boxes: (BoxList) A collection of boxes to be refined. pool_boxes must\n have a rank 1 'scores' field.\n nms_iou_thresh: (float scalar) iou threshold for non max suppression (NMS).\n nms_max_detections: (int scalar) maximum output size for NMS.\n voting_iou_thresh: (float scalar) iou threshold for box voting.\n\n Returns:\n BoxList of refined boxes.\n\n Raises:\n ValueError: if\n a) nms_iou_thresh or voting_iou_thresh is not in [0, 1].\n b) pool_boxes is not a BoxList.\n c) pool_boxes does not have a scores field.\n \"\"\"\n if not 0.0 <= nms_iou_thresh <= 1.0:\n raise ValueError('nms_iou_thresh must be between 0 and 1')\n if not 0.0 <= voting_iou_thresh <= 1.0:\n raise ValueError('voting_iou_thresh must be between 0 and 1')\n if not isinstance(pool_boxes, box_list.BoxList):\n raise ValueError('pool_boxes must be a BoxList')\n if not pool_boxes.has_field('scores'):\n raise ValueError('pool_boxes must have a \\'scores\\' field')\n\n nms_boxes = non_max_suppression(\n pool_boxes, nms_iou_thresh, nms_max_detections)\n return box_voting(nms_boxes, pool_boxes, voting_iou_thresh)\n\n\ndef box_voting(selected_boxes, pool_boxes, iou_thresh=0.5):\n \"\"\"Performs box voting as described in S. Gidaris and N. Komodakis, ICCV 2015.\n\n Performs box voting as described in 'Object detection via a multi-region &\n semantic segmentation-aware CNN model', Gidaris and Komodakis, ICCV 2015. For\n each box 'B' in selected_boxes, we find the set 'S' of boxes in pool_boxes\n with iou overlap >= iou_thresh. The location of B is set to the weighted\n average location of boxes in S (scores are used for weighting). And the score\n of B is set to the average score of boxes in S.\n\n Args:\n selected_boxes: BoxList containing a subset of boxes in pool_boxes. These\n boxes are usually selected from pool_boxes using non max suppression.\n pool_boxes: BoxList containing a set of (possibly redundant) boxes.\n iou_thresh: (float scalar) iou threshold for matching boxes in\n selected_boxes and pool_boxes.\n\n Returns:\n BoxList containing averaged locations and scores for each box in\n selected_boxes.\n\n Raises:\n ValueError: if\n a) selected_boxes or pool_boxes is not a BoxList.\n b) if iou_thresh is not in [0, 1].\n c) pool_boxes does not have a scores field.\n \"\"\"\n if not 0.0 <= iou_thresh <= 1.0:\n raise ValueError('iou_thresh must be between 0 and 1')\n if not isinstance(selected_boxes, box_list.BoxList):\n raise ValueError('selected_boxes must be a BoxList')\n if not isinstance(pool_boxes, box_list.BoxList):\n raise ValueError('pool_boxes must be a BoxList')\n if not pool_boxes.has_field('scores'):\n raise ValueError('pool_boxes must have a \\'scores\\' field')\n\n iou_ = iou(selected_boxes, pool_boxes)\n match_indicator = tf.cast(tf.greater(iou_, iou_thresh), dtype=tf.float32)\n num_matches = tf.reduce_sum(match_indicator, 1)\n # TODO(kbanoop): Handle the case where some boxes in selected_boxes do not\n # match to any boxes in pool_boxes. For such boxes without any matches, we\n # should return the original boxes without voting.\n match_assert = tf.Assert(\n tf.reduce_all(tf.greater(num_matches, 0)),\n ['Each box in selected_boxes must match with at least one box '\n 'in pool_boxes.'])\n\n scores = tf.expand_dims(pool_boxes.get_field('scores'), 1)\n scores_assert = tf.Assert(\n tf.reduce_all(tf.greater_equal(scores, 0)),\n ['Scores must be non negative.'])\n\n with tf.control_dependencies([scores_assert, match_assert]):\n sum_scores = tf.matmul(match_indicator, scores)\n averaged_scores = tf.reshape(sum_scores, [-1]) / num_matches\n\n box_locations = tf.matmul(match_indicator,\n pool_boxes.get() * scores) / sum_scores\n averaged_boxes = box_list.BoxList(box_locations)\n _copy_extra_fields(averaged_boxes, selected_boxes)\n averaged_boxes.add_field('scores', averaged_scores)\n return averaged_boxes\n\n\ndef pad_or_clip_box_list(boxlist, num_boxes, scope=None):\n \"\"\"Pads or clips all fields of a BoxList.\n\n Args:\n boxlist: A BoxList with arbitrary of number of boxes.\n num_boxes: First num_boxes in boxlist are kept.\n The fields are zero-padded if num_boxes is bigger than the\n actual number of boxes.\n scope: name scope.\n\n Returns:\n BoxList with all fields padded or clipped.\n \"\"\"\n with tf.name_scope(scope, 'PadOrClipBoxList'):\n subboxlist = box_list.BoxList(shape_utils.pad_or_clip_tensor(\n boxlist.get(), num_boxes))\n for field in boxlist.get_extra_fields():\n subfield = shape_utils.pad_or_clip_tensor(\n boxlist.get_field(field), num_boxes)\n subboxlist.add_field(field, subfield)\n return subboxlist\n\n\ndef select_random_box(boxlist,\n default_box=None,\n seed=None,\n scope=None):\n \"\"\"Selects a random bounding box from a `BoxList`.\n\n Args:\n boxlist: A BoxList.\n default_box: A [1, 4] float32 tensor. If no boxes are present in `boxlist`,\n this default box will be returned. If None, will use a default box of\n [[-1., -1., -1., -1.]].\n seed: Random seed.\n scope: Name scope.\n\n Returns:\n bbox: A [1, 4] tensor with a random bounding box.\n valid: A bool tensor indicating whether a valid bounding box is returned\n (True) or whether the default box is returned (False).\n \"\"\"\n with tf.name_scope(scope, 'SelectRandomBox'):\n bboxes = boxlist.get()\n combined_shape = shape_utils.combined_static_and_dynamic_shape(bboxes)\n number_of_boxes = combined_shape[0]\n default_box = default_box or tf.constant([[-1., -1., -1., -1.]])\n\n def select_box():\n random_index = tf.random_uniform([],\n maxval=number_of_boxes,\n dtype=tf.int32,\n seed=seed)\n return tf.expand_dims(bboxes[random_index], axis=0), tf.constant(True)\n\n return tf.cond(\n tf.greater_equal(number_of_boxes, 1),\n true_fn=select_box,\n false_fn=lambda: (default_box, tf.constant(False)))\n\n\ndef get_minimal_coverage_box(boxlist,\n default_box=None,\n scope=None):\n \"\"\"Creates a single bounding box which covers all boxes in the boxlist.\n\n Args:\n boxlist: A Boxlist.\n default_box: A [1, 4] float32 tensor. If no boxes are present in `boxlist`,\n this default box will be returned. If None, will use a default box of\n [[0., 0., 1., 1.]].\n scope: Name scope.\n\n Returns:\n A [1, 4] float32 tensor with a bounding box that tightly covers all the\n boxes in the box list. If the boxlist does not contain any boxes, the\n default box is returned.\n \"\"\"\n with tf.name_scope(scope, 'CreateCoverageBox'):\n num_boxes = boxlist.num_boxes()\n\n def coverage_box(bboxes):\n y_min, x_min, y_max, x_max = tf.split(\n value=bboxes, num_or_size_splits=4, axis=1)\n y_min_coverage = tf.reduce_min(y_min, axis=0)\n x_min_coverage = tf.reduce_min(x_min, axis=0)\n y_max_coverage = tf.reduce_max(y_max, axis=0)\n x_max_coverage = tf.reduce_max(x_max, axis=0)\n return tf.stack(\n [y_min_coverage, x_min_coverage, y_max_coverage, x_max_coverage],\n axis=1)\n\n default_box = default_box or tf.constant([[0., 0., 1., 1.]])\n return tf.cond(\n tf.greater_equal(num_boxes, 1),\n true_fn=lambda: coverage_box(boxlist.get()),\n false_fn=lambda: default_box)\n\n\ndef sample_boxes_by_jittering(boxlist,\n num_boxes_to_sample,\n stddev=0.1,\n scope=None):\n \"\"\"Samples num_boxes_to_sample boxes by jittering around boxlist boxes.\n\n It is possible that this function might generate boxes with size 0. The larger\n the stddev, this is more probable. For a small stddev of 0.1 this probability\n is very small.\n\n Args:\n boxlist: A boxlist containing N boxes in normalized coordinates.\n num_boxes_to_sample: A positive integer containing the number of boxes to\n sample.\n stddev: Standard deviation. This is used to draw random offsets for the\n box corners from a normal distribution. The offset is multiplied by the\n box size so will be larger in terms of pixels for larger boxes.\n scope: Name scope.\n\n Returns:\n sampled_boxlist: A boxlist containing num_boxes_to_sample boxes in\n normalized coordinates.\n \"\"\"\n with tf.name_scope(scope, 'SampleBoxesByJittering'):\n num_boxes = boxlist.num_boxes()\n box_indices = tf.random_uniform(\n [num_boxes_to_sample],\n minval=0,\n maxval=num_boxes,\n dtype=tf.int32)\n sampled_boxes = tf.gather(boxlist.get(), box_indices)\n sampled_boxes_height = sampled_boxes[:, 2] - sampled_boxes[:, 0]\n sampled_boxes_width = sampled_boxes[:, 3] - sampled_boxes[:, 1]\n rand_miny_gaussian = tf.random_normal([num_boxes_to_sample], stddev=stddev)\n rand_minx_gaussian = tf.random_normal([num_boxes_to_sample], stddev=stddev)\n rand_maxy_gaussian = tf.random_normal([num_boxes_to_sample], stddev=stddev)\n rand_maxx_gaussian = tf.random_normal([num_boxes_to_sample], stddev=stddev)\n miny = rand_miny_gaussian * sampled_boxes_height + sampled_boxes[:, 0]\n minx = rand_minx_gaussian * sampled_boxes_width + sampled_boxes[:, 1]\n maxy = rand_maxy_gaussian * sampled_boxes_height + sampled_boxes[:, 2]\n maxx = rand_maxx_gaussian * sampled_boxes_width + sampled_boxes[:, 3]\n maxy = tf.maximum(miny, maxy)\n maxx = tf.maximum(minx, maxx)\n sampled_boxes = tf.stack([miny, minx, maxy, maxx], axis=1)\n sampled_boxes = tf.maximum(tf.minimum(sampled_boxes, 1.0), 0.0)\n return box_list.BoxList(sampled_boxes)\n",
"# Lint as: python3\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\"\"\"Implementation of SpineNet model.\n\nX. Du, T-Y. Lin, P. Jin, G. Ghiasi, M. Tan, Y. Cui, Q. V. Le, X. Song\nSpineNet: Learning Scale-Permuted Backbone for Recognition and Localization\nhttps://arxiv.org/abs/1912.05027\n\"\"\"\nimport math\n\n# Import libraries\nfrom absl import logging\nimport tensorflow as tf\nfrom official.modeling import tf_utils\nfrom official.vision.beta.modeling.layers import nn_blocks\nfrom official.vision.beta.ops import spatial_transform_ops\n\nlayers = tf.keras.layers\n\nFILTER_SIZE_MAP = {\n 1: 32,\n 2: 64,\n 3: 128,\n 4: 256,\n 5: 256,\n 6: 256,\n 7: 256,\n}\n\n# The fixed SpineNet architecture discovered by NAS.\n# Each element represents a specification of a building block:\n# (block_level, block_fn, (input_offset0, input_offset1), is_output).\nSPINENET_BLOCK_SPECS = [\n (2, 'bottleneck', (0, 1), False),\n (4, 'residual', (0, 1), False),\n (3, 'bottleneck', (2, 3), False),\n (4, 'bottleneck', (2, 4), False),\n (6, 'residual', (3, 5), False),\n (4, 'bottleneck', (3, 5), False),\n (5, 'residual', (6, 7), False),\n (7, 'residual', (6, 8), False),\n (5, 'bottleneck', (8, 9), False),\n (5, 'bottleneck', (8, 10), False),\n (4, 'bottleneck', (5, 10), True),\n (3, 'bottleneck', (4, 10), True),\n (5, 'bottleneck', (7, 12), True),\n (7, 'bottleneck', (5, 14), True),\n (6, 'bottleneck', (12, 14), True),\n]\n\nSCALING_MAP = {\n '49S': {\n 'endpoints_num_filters': 128,\n 'filter_size_scale': 0.65,\n 'resample_alpha': 0.5,\n 'block_repeats': 1,\n },\n '49': {\n 'endpoints_num_filters': 256,\n 'filter_size_scale': 1.0,\n 'resample_alpha': 0.5,\n 'block_repeats': 1,\n },\n '96': {\n 'endpoints_num_filters': 256,\n 'filter_size_scale': 1.0,\n 'resample_alpha': 0.5,\n 'block_repeats': 2,\n },\n '143': {\n 'endpoints_num_filters': 256,\n 'filter_size_scale': 1.0,\n 'resample_alpha': 1.0,\n 'block_repeats': 3,\n },\n '190': {\n 'endpoints_num_filters': 512,\n 'filter_size_scale': 1.3,\n 'resample_alpha': 1.0,\n 'block_repeats': 4,\n },\n}\n\n\nclass BlockSpec(object):\n \"\"\"A container class that specifies the block configuration for SpineNet.\"\"\"\n\n def __init__(self, level, block_fn, input_offsets, is_output):\n self.level = level\n self.block_fn = block_fn\n self.input_offsets = input_offsets\n self.is_output = is_output\n\n\ndef build_block_specs(block_specs=None):\n \"\"\"Builds the list of BlockSpec objects for SpineNet.\"\"\"\n if not block_specs:\n block_specs = SPINENET_BLOCK_SPECS\n logging.info('Building SpineNet block specs: %s', block_specs)\n return [BlockSpec(*b) for b in block_specs]\n\n\[email protected]_keras_serializable(package='Vision')\nclass SpineNet(tf.keras.Model):\n \"\"\"Class to build SpineNet models.\"\"\"\n\n def __init__(self,\n input_specs=tf.keras.layers.InputSpec(shape=[None, 640, 640, 3]),\n min_level=3,\n max_level=7,\n block_specs=build_block_specs(),\n endpoints_num_filters=256,\n resample_alpha=0.5,\n block_repeats=1,\n filter_size_scale=1.0,\n kernel_initializer='VarianceScaling',\n kernel_regularizer=None,\n bias_regularizer=None,\n activation='relu',\n use_sync_bn=False,\n norm_momentum=0.99,\n norm_epsilon=0.001,\n **kwargs):\n \"\"\"SpineNet model.\"\"\"\n self._input_specs = input_specs\n self._min_level = min_level\n self._max_level = max_level\n self._block_specs = block_specs\n self._endpoints_num_filters = endpoints_num_filters\n self._resample_alpha = resample_alpha\n self._block_repeats = block_repeats\n self._filter_size_scale = filter_size_scale\n self._kernel_initializer = kernel_initializer\n self._kernel_regularizer = kernel_regularizer\n self._bias_regularizer = bias_regularizer\n self._activation = activation\n self._use_sync_bn = use_sync_bn\n self._norm_momentum = norm_momentum\n self._norm_epsilon = norm_epsilon\n if activation == 'relu':\n self._activation_fn = tf.nn.relu\n elif activation == 'swish':\n self._activation_fn = tf.nn.swish\n else:\n raise ValueError('Activation {} not implemented.'.format(activation))\n self._init_block_fn = 'bottleneck'\n self._num_init_blocks = 2\n\n if use_sync_bn:\n self._norm = layers.experimental.SyncBatchNormalization\n else:\n self._norm = layers.BatchNormalization\n\n if tf.keras.backend.image_data_format() == 'channels_last':\n self._bn_axis = -1\n else:\n self._bn_axis = 1\n\n # Build SpineNet.\n inputs = tf.keras.Input(shape=input_specs.shape[1:])\n\n net = self._build_stem(inputs=inputs)\n net = self._build_scale_permuted_network(\n net=net, input_width=input_specs.shape[1])\n endpoints = self._build_endpoints(net=net)\n\n self._output_specs = {l: endpoints[l].get_shape() for l in endpoints}\n super(SpineNet, self).__init__(inputs=inputs, outputs=endpoints)\n\n def _block_group(self,\n inputs,\n filters,\n strides,\n block_fn_cand,\n block_repeats=1,\n name='block_group'):\n \"\"\"Creates one group of blocks for the SpineNet model.\"\"\"\n block_fn_candidates = {\n 'bottleneck': nn_blocks.BottleneckBlock,\n 'residual': nn_blocks.ResidualBlock,\n }\n block_fn = block_fn_candidates[block_fn_cand]\n _, _, _, num_filters = inputs.get_shape().as_list()\n\n if block_fn_cand == 'bottleneck':\n use_projection = not (num_filters == (filters * 4) and strides == 1)\n else:\n use_projection = not (num_filters == filters and strides == 1)\n\n x = block_fn(\n filters=filters,\n strides=strides,\n use_projection=use_projection,\n kernel_initializer=self._kernel_initializer,\n kernel_regularizer=self._kernel_regularizer,\n bias_regularizer=self._bias_regularizer,\n activation=self._activation,\n use_sync_bn=self._use_sync_bn,\n norm_momentum=self._norm_momentum,\n norm_epsilon=self._norm_epsilon)(\n inputs)\n for _ in range(1, block_repeats):\n x = block_fn(\n filters=filters,\n strides=1,\n use_projection=False,\n kernel_initializer=self._kernel_initializer,\n kernel_regularizer=self._kernel_regularizer,\n bias_regularizer=self._bias_regularizer,\n activation=self._activation,\n use_sync_bn=self._use_sync_bn,\n norm_momentum=self._norm_momentum,\n norm_epsilon=self._norm_epsilon)(\n x)\n return tf.identity(x, name=name)\n\n def _build_stem(self, inputs):\n \"\"\"Build SpineNet stem.\"\"\"\n x = layers.Conv2D(\n filters=64,\n kernel_size=7,\n strides=2,\n use_bias=False,\n padding='same',\n kernel_initializer=self._kernel_initializer,\n kernel_regularizer=self._kernel_regularizer,\n bias_regularizer=self._bias_regularizer)(\n inputs)\n x = self._norm(\n axis=self._bn_axis,\n momentum=self._norm_momentum,\n epsilon=self._norm_epsilon)(\n x)\n x = tf_utils.get_activation(self._activation_fn)(x)\n x = layers.MaxPool2D(pool_size=3, strides=2, padding='same')(x)\n\n net = []\n # Build the initial level 2 blocks.\n for i in range(self._num_init_blocks):\n x = self._block_group(\n inputs=x,\n filters=int(FILTER_SIZE_MAP[2] * self._filter_size_scale),\n strides=1,\n block_fn_cand=self._init_block_fn,\n block_repeats=self._block_repeats,\n name='stem_block_{}'.format(i + 1))\n net.append(x)\n return net\n\n def _build_scale_permuted_network(self,\n net,\n input_width,\n weighted_fusion=False):\n \"\"\"Build scale-permuted network.\"\"\"\n net_sizes = [int(math.ceil(input_width / 2**2))] * len(net)\n net_block_fns = [self._init_block_fn] * len(net)\n num_outgoing_connections = [0] * len(net)\n\n endpoints = {}\n for i, block_spec in enumerate(self._block_specs):\n # Find out specs for the target block.\n target_width = int(math.ceil(input_width / 2**block_spec.level))\n target_num_filters = int(FILTER_SIZE_MAP[block_spec.level] *\n self._filter_size_scale)\n target_block_fn = block_spec.block_fn\n\n # Resample then merge input0 and input1.\n parents = []\n input0 = block_spec.input_offsets[0]\n input1 = block_spec.input_offsets[1]\n\n x0 = self._resample_with_alpha(\n inputs=net[input0],\n input_width=net_sizes[input0],\n input_block_fn=net_block_fns[input0],\n target_width=target_width,\n target_num_filters=target_num_filters,\n target_block_fn=target_block_fn,\n alpha=self._resample_alpha)\n parents.append(x0)\n num_outgoing_connections[input0] += 1\n\n x1 = self._resample_with_alpha(\n inputs=net[input1],\n input_width=net_sizes[input1],\n input_block_fn=net_block_fns[input1],\n target_width=target_width,\n target_num_filters=target_num_filters,\n target_block_fn=target_block_fn,\n alpha=self._resample_alpha)\n parents.append(x1)\n num_outgoing_connections[input1] += 1\n\n # Merge 0 outdegree blocks to the output block.\n if block_spec.is_output:\n for j, (j_feat,\n j_connections) in enumerate(zip(net, num_outgoing_connections)):\n if j_connections == 0 and (j_feat.shape[2] == target_width and\n j_feat.shape[3] == x0.shape[3]):\n parents.append(j_feat)\n num_outgoing_connections[j] += 1\n\n # pylint: disable=g-direct-tensorflow-import\n if weighted_fusion:\n dtype = parents[0].dtype\n parent_weights = [\n tf.nn.relu(tf.cast(tf.Variable(1.0, name='block{}_fusion{}'.format(\n i, j)), dtype=dtype)) for j in range(len(parents))]\n weights_sum = tf.add_n(parent_weights)\n parents = [\n parents[i] * parent_weights[i] / (weights_sum + 0.0001)\n for i in range(len(parents))\n ]\n\n # Fuse all parent nodes then build a new block.\n x = tf_utils.get_activation(self._activation_fn)(tf.add_n(parents))\n x = self._block_group(\n inputs=x,\n filters=target_num_filters,\n strides=1,\n block_fn_cand=target_block_fn,\n block_repeats=self._block_repeats,\n name='scale_permuted_block_{}'.format(i + 1))\n\n net.append(x)\n net_sizes.append(target_width)\n net_block_fns.append(target_block_fn)\n num_outgoing_connections.append(0)\n\n # Save output feats.\n if block_spec.is_output:\n if block_spec.level in endpoints:\n raise ValueError('Duplicate feats found for output level {}.'.format(\n block_spec.level))\n if (block_spec.level < self._min_level or\n block_spec.level > self._max_level):\n raise ValueError('Output level is out of range [{}, {}]'.format(\n self._min_level, self._max_level))\n endpoints[str(block_spec.level)] = x\n\n return endpoints\n\n def _build_endpoints(self, net):\n \"\"\"Match filter size for endpoints before sharing conv layers.\"\"\"\n endpoints = {}\n for level in range(self._min_level, self._max_level + 1):\n x = layers.Conv2D(\n filters=self._endpoints_num_filters,\n kernel_size=1,\n strides=1,\n use_bias=False,\n kernel_initializer=self._kernel_initializer,\n kernel_regularizer=self._kernel_regularizer,\n bias_regularizer=self._bias_regularizer)(\n net[str(level)])\n x = self._norm(\n axis=self._bn_axis,\n momentum=self._norm_momentum,\n epsilon=self._norm_epsilon)(\n x)\n x = tf_utils.get_activation(self._activation_fn)(x)\n endpoints[str(level)] = x\n return endpoints\n\n def _resample_with_alpha(self,\n inputs,\n input_width,\n input_block_fn,\n target_width,\n target_num_filters,\n target_block_fn,\n alpha=0.5):\n \"\"\"Match resolution and feature dimension.\"\"\"\n _, _, _, input_num_filters = inputs.get_shape().as_list()\n if input_block_fn == 'bottleneck':\n input_num_filters /= 4\n new_num_filters = int(input_num_filters * alpha)\n\n x = layers.Conv2D(\n filters=new_num_filters,\n kernel_size=1,\n strides=1,\n use_bias=False,\n kernel_initializer=self._kernel_initializer,\n kernel_regularizer=self._kernel_regularizer,\n bias_regularizer=self._bias_regularizer)(\n inputs)\n x = self._norm(\n axis=self._bn_axis,\n momentum=self._norm_momentum,\n epsilon=self._norm_epsilon)(\n x)\n x = tf_utils.get_activation(self._activation_fn)(x)\n\n # Spatial resampling.\n if input_width > target_width:\n x = layers.Conv2D(\n filters=new_num_filters,\n kernel_size=3,\n strides=2,\n padding='SAME',\n use_bias=False,\n kernel_initializer=self._kernel_initializer,\n kernel_regularizer=self._kernel_regularizer,\n bias_regularizer=self._bias_regularizer)(\n x)\n x = self._norm(\n axis=self._bn_axis,\n momentum=self._norm_momentum,\n epsilon=self._norm_epsilon)(\n x)\n x = tf_utils.get_activation(self._activation_fn)(x)\n input_width /= 2\n while input_width > target_width:\n x = layers.MaxPool2D(pool_size=3, strides=2, padding='SAME')(x)\n input_width /= 2\n elif input_width < target_width:\n scale = target_width // input_width\n x = spatial_transform_ops.nearest_upsampling(x, scale=scale)\n\n # Last 1x1 conv to match filter size.\n if target_block_fn == 'bottleneck':\n target_num_filters *= 4\n x = layers.Conv2D(\n filters=target_num_filters,\n kernel_size=1,\n strides=1,\n use_bias=False,\n kernel_initializer=self._kernel_initializer,\n kernel_regularizer=self._kernel_regularizer,\n bias_regularizer=self._bias_regularizer)(\n x)\n x = self._norm(\n axis=self._bn_axis,\n momentum=self._norm_momentum,\n epsilon=self._norm_epsilon)(\n x)\n return x\n\n def get_config(self):\n config_dict = {\n 'min_level': self._min_level,\n 'max_level': self._max_level,\n 'endpoints_num_filters': self._endpoints_num_filters,\n 'resample_alpha': self._resample_alpha,\n 'block_repeats': self._block_repeats,\n 'filter_size_scale': self._filter_size_scale,\n 'kernel_initializer': self._kernel_initializer,\n 'kernel_regularizer': self._kernel_regularizer,\n 'bias_regularizer': self._bias_regularizer,\n 'activation': self._activation,\n 'use_sync_bn': self._use_sync_bn,\n 'norm_momentum': self._norm_momentum,\n 'norm_epsilon': self._norm_epsilon\n }\n return config_dict\n\n @classmethod\n def from_config(cls, config, custom_objects=None):\n return cls(**config)\n\n @property\n def output_specs(self):\n \"\"\"A dict of {level: TensorShape} pairs for the model output.\"\"\"\n return self._output_specs\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\"\"\"The CenterNet meta architecture as described in the \"Objects as Points\" paper [1].\n\n[1]: https://arxiv.org/abs/1904.07850\n\n\"\"\"\n\nimport abc\nimport collections\nimport functools\nimport numpy as np\nimport tensorflow.compat.v1 as tf\nimport tensorflow.compat.v2 as tf2\n\nfrom object_detection.core import box_list\nfrom object_detection.core import box_list_ops\nfrom object_detection.core import keypoint_ops\nfrom object_detection.core import model\nfrom object_detection.core import standard_fields as fields\nfrom object_detection.core import target_assigner as cn_assigner\nfrom object_detection.utils import shape_utils\n\n# Number of channels needed to predict size and offsets.\nNUM_OFFSET_CHANNELS = 2\nNUM_SIZE_CHANNELS = 2\n\n# Error range for detecting peaks.\nPEAK_EPSILON = 1e-6\n\n# Constants shared between all keypoint tasks.\nUNMATCHED_KEYPOINT_SCORE = 0.1\nKEYPOINT_CANDIDATE_SEARCH_SCALE = 0.3\n\n\nclass CenterNetFeatureExtractor(tf.keras.Model):\n \"\"\"Base class for feature extractors for the CenterNet meta architecture.\n\n Child classes are expected to override the _output_model property which will\n return 1 or more tensors predicted by the feature extractor.\n\n \"\"\"\n __metaclass__ = abc.ABCMeta\n\n def __init__(self, name=None, channel_means=(0., 0., 0.),\n channel_stds=(1., 1., 1.), bgr_ordering=False):\n \"\"\"Initializes a CenterNet feature extractor.\n\n Args:\n name: str, the name used for the underlying keras model.\n channel_means: A tuple of floats, denoting the mean of each channel\n which will be subtracted from it. If None or empty, we use 0s.\n channel_stds: A tuple of floats, denoting the standard deviation of each\n channel. Each channel will be divided by its standard deviation value.\n If None or empty, we use 1s.\n bgr_ordering: bool, if set will change the channel ordering to be in the\n [blue, red, green] order.\n \"\"\"\n super(CenterNetFeatureExtractor, self).__init__(name=name)\n\n if channel_means is None or len(channel_means) == 0: # pylint:disable=g-explicit-length-test\n channel_means = [0., 0., 0.]\n\n if channel_stds is None or len(channel_stds) == 0: # pylint:disable=g-explicit-length-test\n channel_stds = [1., 1., 1.]\n\n self._channel_means = channel_means\n self._channel_stds = channel_stds\n self._bgr_ordering = bgr_ordering\n\n def preprocess(self, inputs):\n \"\"\"Converts a batch of unscaled images to a scale suitable for the model.\n\n This method normalizes the image using the given `channel_means` and\n `channels_stds` values at initialization time while optionally flipping\n the channel order if `bgr_ordering` is set.\n\n Args:\n inputs: a [batch, height, width, channels] float32 tensor\n\n Returns:\n outputs: a [batch, height, width, channels] float32 tensor\n\n \"\"\"\n\n if self._bgr_ordering:\n red, green, blue = tf.unstack(inputs, axis=3)\n inputs = tf.stack([blue, green, red], axis=3)\n\n channel_means = tf.reshape(tf.constant(self._channel_means),\n [1, 1, 1, -1])\n channel_stds = tf.reshape(tf.constant(self._channel_stds),\n [1, 1, 1, -1])\n\n return (inputs - channel_means)/channel_stds\n\n @property\n @abc.abstractmethod\n def out_stride(self):\n \"\"\"The stride in the output image of the network.\"\"\"\n pass\n\n @property\n @abc.abstractmethod\n def num_feature_outputs(self):\n \"\"\"Ther number of feature outputs returned by the feature extractor.\"\"\"\n pass\n\n @property\n @abc.abstractmethod\n def supported_sub_model_types(self):\n \"\"\"Valid sub model types supported by the get_sub_model function.\"\"\"\n pass\n\n @abc.abstractmethod\n def get_sub_model(self, sub_model_type):\n \"\"\"Returns the underlying keras model for the given sub_model_type.\n\n This function is useful when we only want to get a subset of weights to\n be restored from a checkpoint.\n\n Args:\n sub_model_type: string, the type of sub model. Currently, CenterNet\n feature extractors support 'detection' and 'classification'.\n \"\"\"\n pass\n\n\ndef make_prediction_net(num_out_channels, kernel_size=3, num_filters=256,\n bias_fill=None):\n \"\"\"Creates a network to predict the given number of output channels.\n\n This function is intended to make the prediction heads for the CenterNet\n meta architecture.\n\n Args:\n num_out_channels: Number of output channels.\n kernel_size: The size of the conv kernel in the intermediate layer\n num_filters: The number of filters in the intermediate conv layer.\n bias_fill: If not None, is used to initialize the bias in the final conv\n layer.\n\n Returns:\n net: A keras module which when called on an input tensor of size\n [batch_size, height, width, num_in_channels] returns an output\n of size [batch_size, height, width, num_out_channels]\n \"\"\"\n\n out_conv = tf.keras.layers.Conv2D(num_out_channels, kernel_size=1)\n\n if bias_fill is not None:\n out_conv.bias_initializer = tf.keras.initializers.constant(bias_fill)\n\n net = tf.keras.Sequential(\n [tf.keras.layers.Conv2D(num_filters, kernel_size=kernel_size,\n padding='same'),\n tf.keras.layers.ReLU(),\n out_conv]\n )\n\n return net\n\n\ndef _to_float32(x):\n return tf.cast(x, tf.float32)\n\n\ndef _get_shape(tensor, num_dims):\n tf.Assert(tensor.get_shape().ndims == num_dims, [tensor])\n return shape_utils.combined_static_and_dynamic_shape(tensor)\n\n\ndef _flatten_spatial_dimensions(batch_images):\n batch_size, height, width, channels = _get_shape(batch_images, 4)\n return tf.reshape(batch_images, [batch_size, height * width,\n channels])\n\n\ndef top_k_feature_map_locations(feature_map, max_pool_kernel_size=3, k=100,\n per_channel=False):\n \"\"\"Returns the top k scores and their locations in a feature map.\n\n Given a feature map, the top k values (based on activation) are returned. If\n `per_channel` is True, the top k values **per channel** are returned.\n\n The `max_pool_kernel_size` argument allows for selecting local peaks in a\n region. This filtering is done per channel, so nothing prevents two values at\n the same location to be returned.\n\n Args:\n feature_map: [batch, height, width, channels] float32 feature map.\n max_pool_kernel_size: integer, the max pool kernel size to use to pull off\n peak score locations in a neighborhood (independently for each channel).\n For example, to make sure no two neighboring values (in the same channel)\n are returned, set max_pool_kernel_size=3. If None or 1, will not apply max\n pooling.\n k: The number of highest scoring locations to return.\n per_channel: If True, will return the top k scores and locations per\n feature map channel. If False, the top k across the entire feature map\n (height x width x channels) are returned.\n\n Returns:\n Tuple of\n scores: A [batch, N] float32 tensor with scores from the feature map in\n descending order. If per_channel is False, N = k. Otherwise,\n N = k * channels, and the first k elements correspond to channel 0, the\n second k correspond to channel 1, etc.\n y_indices: A [batch, N] int tensor with y indices of the top k feature map\n locations. If per_channel is False, N = k. Otherwise,\n N = k * channels.\n x_indices: A [batch, N] int tensor with x indices of the top k feature map\n locations. If per_channel is False, N = k. Otherwise,\n N = k * channels.\n channel_indices: A [batch, N] int tensor with channel indices of the top k\n feature map locations. If per_channel is False, N = k. Otherwise,\n N = k * channels.\n \"\"\"\n if not max_pool_kernel_size or max_pool_kernel_size == 1:\n feature_map_peaks = feature_map\n else:\n feature_map_max_pool = tf.nn.max_pool(\n feature_map, ksize=max_pool_kernel_size, strides=1, padding='SAME')\n\n feature_map_peak_mask = tf.math.abs(\n feature_map - feature_map_max_pool) < PEAK_EPSILON\n\n # Zero out everything that is not a peak.\n feature_map_peaks = (\n feature_map * _to_float32(feature_map_peak_mask))\n\n batch_size, _, width, num_channels = _get_shape(feature_map, 4)\n\n if per_channel:\n # Perform top k over batch and channels.\n feature_map_peaks_transposed = tf.transpose(feature_map_peaks,\n perm=[0, 3, 1, 2])\n feature_map_peaks_transposed = tf.reshape(\n feature_map_peaks_transposed, [batch_size, num_channels, -1])\n scores, peak_flat_indices = tf.math.top_k(feature_map_peaks_transposed, k=k)\n # Convert the indices such that they represent the location in the full\n # (flattened) feature map of size [batch, height * width * channels].\n channel_idx = tf.range(num_channels)[tf.newaxis, :, tf.newaxis]\n peak_flat_indices = num_channels * peak_flat_indices + channel_idx\n scores = tf.reshape(scores, [batch_size, -1])\n peak_flat_indices = tf.reshape(peak_flat_indices, [batch_size, -1])\n else:\n feature_map_peaks_flat = tf.reshape(feature_map_peaks, [batch_size, -1])\n scores, peak_flat_indices = tf.math.top_k(feature_map_peaks_flat, k=k)\n\n # Get x, y and channel indices corresponding to the top indices in the flat\n # array.\n y_indices, x_indices, channel_indices = (\n row_col_channel_indices_from_flattened_indices(\n peak_flat_indices, width, num_channels))\n return scores, y_indices, x_indices, channel_indices\n\n\ndef prediction_tensors_to_boxes(detection_scores, y_indices, x_indices,\n channel_indices, height_width_predictions,\n offset_predictions):\n \"\"\"Converts CenterNet class-center, offset and size predictions to boxes.\n\n Args:\n detection_scores: A [batch, num_boxes] float32 tensor with detection\n scores in range [0, 1].\n y_indices: A [batch, num_boxes] int32 tensor with y indices corresponding to\n object center locations (expressed in output coordinate frame).\n x_indices: A [batch, num_boxes] int32 tensor with x indices corresponding to\n object center locations (expressed in output coordinate frame).\n channel_indices: A [batch, num_boxes] int32 tensor with channel indices\n corresponding to object classes.\n height_width_predictions: A float tensor of shape [batch_size, height,\n width, 2] representing the height and width of a box centered at each\n pixel.\n offset_predictions: A float tensor of shape [batch_size, height, width, 2]\n representing the y and x offsets of a box centered at each pixel. This\n helps reduce the error from downsampling.\n\n Returns:\n detection_boxes: A tensor of shape [batch_size, num_boxes, 4] holding the\n the raw bounding box coordinates of boxes.\n detection_classes: An integer tensor of shape [batch_size, num_boxes]\n indicating the predicted class for each box.\n detection_scores: A float tensor of shape [batch_size, num_boxes] indicating\n the score for each box.\n num_detections: An integer tensor of shape [batch_size,] indicating the\n number of boxes detected for each sample in the batch.\n\n \"\"\"\n _, _, width, _ = _get_shape(height_width_predictions, 4)\n\n peak_spatial_indices = flattened_indices_from_row_col_indices(\n y_indices, x_indices, width)\n y_indices = _to_float32(y_indices)\n x_indices = _to_float32(x_indices)\n\n height_width_flat = _flatten_spatial_dimensions(height_width_predictions)\n offsets_flat = _flatten_spatial_dimensions(offset_predictions)\n\n height_width = tf.gather(height_width_flat, peak_spatial_indices,\n batch_dims=1)\n height_width = tf.maximum(height_width, 0)\n offsets = tf.gather(offsets_flat, peak_spatial_indices, batch_dims=1)\n\n heights, widths = tf.unstack(height_width, axis=2)\n y_offsets, x_offsets = tf.unstack(offsets, axis=2)\n\n detection_classes = channel_indices\n\n num_detections = tf.reduce_sum(tf.to_int32(detection_scores > 0), axis=1)\n\n boxes = tf.stack([y_indices + y_offsets - heights / 2.0,\n x_indices + x_offsets - widths / 2.0,\n y_indices + y_offsets + heights / 2.0,\n x_indices + x_offsets + widths / 2.0], axis=2)\n\n return boxes, detection_classes, detection_scores, num_detections\n\n\ndef prediction_tensors_to_temporal_offsets(\n y_indices, x_indices, offset_predictions):\n \"\"\"Converts CenterNet temporal offset map predictions to batched format.\n\n This function is similiar to the box offset conversion function, as both\n temporal offsets and box offsets are size-2 vectors.\n\n Args:\n y_indices: A [batch, num_boxes] int32 tensor with y indices corresponding to\n object center locations (expressed in output coordinate frame).\n x_indices: A [batch, num_boxes] int32 tensor with x indices corresponding to\n object center locations (expressed in output coordinate frame).\n offset_predictions: A float tensor of shape [batch_size, height, width, 2]\n representing the y and x offsets of a box's center across adjacent frames.\n\n Returns:\n offsets: A tensor of shape [batch_size, num_boxes, 2] holding the\n the object temporal offsets of (y, x) dimensions.\n\n \"\"\"\n _, _, width, _ = _get_shape(offset_predictions, 4)\n\n peak_spatial_indices = flattened_indices_from_row_col_indices(\n y_indices, x_indices, width)\n y_indices = _to_float32(y_indices)\n x_indices = _to_float32(x_indices)\n\n offsets_flat = _flatten_spatial_dimensions(offset_predictions)\n\n offsets = tf.gather(offsets_flat, peak_spatial_indices, batch_dims=1)\n return offsets\n\n\ndef prediction_tensors_to_keypoint_candidates(\n keypoint_heatmap_predictions,\n keypoint_heatmap_offsets,\n keypoint_score_threshold=0.1,\n max_pool_kernel_size=1,\n max_candidates=20):\n \"\"\"Convert keypoint heatmap predictions and offsets to keypoint candidates.\n\n Args:\n keypoint_heatmap_predictions: A float tensor of shape [batch_size, height,\n width, num_keypoints] representing the per-keypoint heatmaps.\n keypoint_heatmap_offsets: A float tensor of shape [batch_size, height,\n width, 2] (or [batch_size, height, width, 2 * num_keypoints] if\n 'per_keypoint_offset' is set True) representing the per-keypoint offsets.\n keypoint_score_threshold: float, the threshold for considering a keypoint\n a candidate.\n max_pool_kernel_size: integer, the max pool kernel size to use to pull off\n peak score locations in a neighborhood. For example, to make sure no two\n neighboring values for the same keypoint are returned, set\n max_pool_kernel_size=3. If None or 1, will not apply any local filtering.\n max_candidates: integer, maximum number of keypoint candidates per\n keypoint type.\n\n Returns:\n keypoint_candidates: A tensor of shape\n [batch_size, max_candidates, num_keypoints, 2] holding the\n location of keypoint candidates in [y, x] format (expressed in absolute\n coordinates in the output coordinate frame).\n keypoint_scores: A float tensor of shape\n [batch_size, max_candidates, num_keypoints] with the scores for each\n keypoint candidate. The scores come directly from the heatmap predictions.\n num_keypoint_candidates: An integer tensor of shape\n [batch_size, num_keypoints] with the number of candidates for each\n keypoint type, as it's possible to filter some candidates due to the score\n threshold.\n \"\"\"\n batch_size, _, width, num_keypoints = _get_shape(\n keypoint_heatmap_predictions, 4)\n # Get x, y and channel indices corresponding to the top indices in the\n # keypoint heatmap predictions.\n # Note that the top k candidates are produced for **each keypoint type**.\n # Might be worth eventually trying top k in the feature map, independent of\n # the keypoint type.\n keypoint_scores, y_indices, x_indices, channel_indices = (\n top_k_feature_map_locations(keypoint_heatmap_predictions,\n max_pool_kernel_size=max_pool_kernel_size,\n k=max_candidates,\n per_channel=True))\n\n peak_spatial_indices = flattened_indices_from_row_col_indices(\n y_indices, x_indices, width)\n y_indices = _to_float32(y_indices)\n x_indices = _to_float32(x_indices)\n\n offsets_flat = _flatten_spatial_dimensions(keypoint_heatmap_offsets)\n\n selected_offsets = tf.gather(offsets_flat, peak_spatial_indices, batch_dims=1)\n _, num_indices, num_channels = _get_shape(selected_offsets, 3)\n if num_channels > 2:\n reshaped_offsets = tf.reshape(selected_offsets,\n [batch_size, num_indices, -1, 2])\n offsets = tf.gather(reshaped_offsets, channel_indices, batch_dims=2)\n else:\n offsets = selected_offsets\n y_offsets, x_offsets = tf.unstack(offsets, axis=2)\n\n keypoint_candidates = tf.stack([y_indices + y_offsets,\n x_indices + x_offsets], axis=2)\n keypoint_candidates = tf.reshape(\n keypoint_candidates,\n [batch_size, num_keypoints, max_candidates, 2])\n keypoint_candidates = tf.transpose(keypoint_candidates, [0, 2, 1, 3])\n keypoint_scores = tf.reshape(\n keypoint_scores,\n [batch_size, num_keypoints, max_candidates])\n keypoint_scores = tf.transpose(keypoint_scores, [0, 2, 1])\n num_candidates = tf.reduce_sum(\n tf.to_int32(keypoint_scores >= keypoint_score_threshold), axis=1)\n\n return keypoint_candidates, keypoint_scores, num_candidates\n\n\ndef regressed_keypoints_at_object_centers(regressed_keypoint_predictions,\n y_indices, x_indices):\n \"\"\"Returns the regressed keypoints at specified object centers.\n\n The original keypoint predictions are regressed relative to each feature map\n location. The returned keypoints are expressed in absolute coordinates in the\n output frame (i.e. the center offsets are added to each individual regressed\n set of keypoints).\n\n Args:\n regressed_keypoint_predictions: A float tensor of shape\n [batch_size, height, width, 2 * num_keypoints] holding regressed\n keypoints. The last dimension has keypoint coordinates ordered as follows:\n [y0, x0, y1, x1, ..., y{J-1}, x{J-1}] where J is the number of keypoints.\n y_indices: A [batch, num_instances] int tensor holding y indices for object\n centers. These indices correspond to locations in the output feature map.\n x_indices: A [batch, num_instances] int tensor holding x indices for object\n centers. These indices correspond to locations in the output feature map.\n\n Returns:\n A float tensor of shape [batch_size, num_objects, 2 * num_keypoints] where\n regressed keypoints are gathered at the provided locations, and converted\n to absolute coordinates in the output coordinate frame.\n \"\"\"\n batch_size, _, width, _ = _get_shape(regressed_keypoint_predictions, 4)\n flattened_indices = flattened_indices_from_row_col_indices(\n y_indices, x_indices, width)\n _, num_instances = _get_shape(flattened_indices, 2)\n\n regressed_keypoints_flat = _flatten_spatial_dimensions(\n regressed_keypoint_predictions)\n\n relative_regressed_keypoints = tf.gather(\n regressed_keypoints_flat, flattened_indices, batch_dims=1)\n relative_regressed_keypoints = tf.reshape(\n relative_regressed_keypoints,\n [batch_size, num_instances, -1, 2])\n relative_regressed_keypoints_y, relative_regressed_keypoints_x = tf.unstack(\n relative_regressed_keypoints, axis=3)\n y_indices = _to_float32(tf.expand_dims(y_indices, axis=-1))\n x_indices = _to_float32(tf.expand_dims(x_indices, axis=-1))\n absolute_regressed_keypoints = tf.stack(\n [y_indices + relative_regressed_keypoints_y,\n x_indices + relative_regressed_keypoints_x],\n axis=3)\n return tf.reshape(absolute_regressed_keypoints,\n [batch_size, num_instances, -1])\n\n\ndef refine_keypoints(regressed_keypoints, keypoint_candidates, keypoint_scores,\n num_keypoint_candidates, bboxes=None,\n unmatched_keypoint_score=0.1, box_scale=1.2,\n candidate_search_scale=0.3,\n candidate_ranking_mode='min_distance'):\n \"\"\"Refines regressed keypoints by snapping to the nearest candidate keypoints.\n\n The initial regressed keypoints represent a full set of keypoints regressed\n from the centers of the objects. The keypoint candidates are estimated\n independently from heatmaps, and are not associated with any object instances.\n This function refines the regressed keypoints by \"snapping\" to the\n nearest/highest score/highest score-distance ratio (depending on the\n candidate_ranking_mode) candidate of the same keypoint type (e.g. \"nose\").\n If no candidates are nearby, the regressed keypoint remains unchanged.\n\n In order to snap a regressed keypoint to a candidate keypoint, the following\n must be satisfied:\n - the candidate keypoint must be of the same type as the regressed keypoint\n - the candidate keypoint must not lie outside the predicted boxes (or the\n boxes which encloses the regressed keypoints for the instance if `bboxes` is\n not provided). Note that the box is scaled by\n `regressed_box_scale` in height and width, to provide some margin around the\n keypoints\n - the distance to the closest candidate keypoint cannot exceed\n candidate_search_scale * max(height, width), where height and width refer to\n the bounding box for the instance.\n\n Note that the same candidate keypoint is allowed to snap to regressed\n keypoints in difference instances.\n\n Args:\n regressed_keypoints: A float tensor of shape\n [batch_size, num_instances, num_keypoints, 2] with the initial regressed\n keypoints.\n keypoint_candidates: A tensor of shape\n [batch_size, max_candidates, num_keypoints, 2] holding the location of\n keypoint candidates in [y, x] format (expressed in absolute coordinates in\n the output coordinate frame).\n keypoint_scores: A float tensor of shape\n [batch_size, max_candidates, num_keypoints] indicating the scores for\n keypoint candidates.\n num_keypoint_candidates: An integer tensor of shape\n [batch_size, num_keypoints] indicating the number of valid candidates for\n each keypoint type, as there may be padding (dim 1) of\n `keypoint_candidates` and `keypoint_scores`.\n bboxes: A tensor of shape [batch_size, num_instances, 4] with predicted\n bounding boxes for each instance, expressed in the output coordinate\n frame. If not provided, boxes will be computed from regressed keypoints.\n unmatched_keypoint_score: float, the default score to use for regressed\n keypoints that are not successfully snapped to a nearby candidate.\n box_scale: float, the multiplier to expand the bounding boxes (either the\n provided boxes or those which tightly cover the regressed keypoints) for\n an instance. This scale is typically larger than 1.0 when not providing\n `bboxes`.\n candidate_search_scale: float, the scale parameter that multiplies the\n largest dimension of a bounding box. The resulting distance becomes a\n search radius for candidates in the vicinity of each regressed keypoint.\n candidate_ranking_mode: A string as one of ['min_distance',\n 'score_distance_ratio'] indicating how to select the candidate. If invalid\n value is provided, an ValueError will be raised.\n\n Returns:\n A tuple with:\n refined_keypoints: A float tensor of shape\n [batch_size, num_instances, num_keypoints, 2] with the final, refined\n keypoints.\n refined_scores: A float tensor of shape\n [batch_size, num_instances, num_keypoints] with scores associated with all\n instances and keypoints in `refined_keypoints`.\n\n Raises:\n ValueError: if provided candidate_ranking_mode is not one of\n ['min_distance', 'score_distance_ratio']\n \"\"\"\n batch_size, num_instances, num_keypoints, _ = (\n shape_utils.combined_static_and_dynamic_shape(regressed_keypoints))\n max_candidates = keypoint_candidates.shape[1]\n\n # Replace all invalid (i.e. padded) keypoint candidates with NaN.\n # This will prevent them from being considered.\n range_tiled = tf.tile(\n tf.reshape(tf.range(max_candidates), [1, max_candidates, 1]),\n [batch_size, 1, num_keypoints])\n num_candidates_tiled = tf.tile(tf.expand_dims(num_keypoint_candidates, 1),\n [1, max_candidates, 1])\n invalid_candidates = range_tiled >= num_candidates_tiled\n nan_mask = tf.where(\n invalid_candidates,\n np.nan * tf.ones_like(invalid_candidates, dtype=tf.float32),\n tf.ones_like(invalid_candidates, dtype=tf.float32))\n keypoint_candidates_with_nans = tf.math.multiply(\n keypoint_candidates, tf.expand_dims(nan_mask, -1))\n\n # Pairwise squared distances between regressed keypoints and candidate\n # keypoints (for a single keypoint type).\n # Shape [batch_size, num_instances, max_candidates, num_keypoints].\n regressed_keypoint_expanded = tf.expand_dims(regressed_keypoints,\n axis=2)\n keypoint_candidates_expanded = tf.expand_dims(\n keypoint_candidates_with_nans, axis=1)\n sqrd_distances = tf.math.reduce_sum(\n tf.math.squared_difference(regressed_keypoint_expanded,\n keypoint_candidates_expanded),\n axis=-1)\n distances = tf.math.sqrt(sqrd_distances)\n\n # Determine the candidates that have the minimum distance to the regressed\n # keypoints. Shape [batch_size, num_instances, num_keypoints].\n min_distances = tf.math.reduce_min(distances, axis=2)\n if candidate_ranking_mode == 'min_distance':\n nearby_candidate_inds = tf.math.argmin(distances, axis=2)\n elif candidate_ranking_mode == 'score_distance_ratio':\n # tiled_keypoint_scores:\n # Shape [batch_size, num_instances, max_candidates, num_keypoints].\n tiled_keypoint_scores = tf.tile(\n tf.expand_dims(keypoint_scores, axis=1),\n multiples=[1, num_instances, 1, 1])\n ranking_scores = tiled_keypoint_scores / (distances + 1e-6)\n nearby_candidate_inds = tf.math.argmax(ranking_scores, axis=2)\n else:\n raise ValueError('Not recognized candidate_ranking_mode: %s' %\n candidate_ranking_mode)\n\n # Gather the coordinates and scores corresponding to the closest candidates.\n # Shape of tensors are [batch_size, num_instances, num_keypoints, 2] and\n # [batch_size, num_instances, num_keypoints], respectively.\n nearby_candidate_coords, nearby_candidate_scores = (\n _gather_candidates_at_indices(keypoint_candidates, keypoint_scores,\n nearby_candidate_inds))\n\n if bboxes is None:\n # Create bboxes from regressed keypoints.\n # Shape [batch_size * num_instances, 4].\n regressed_keypoints_flattened = tf.reshape(\n regressed_keypoints, [-1, num_keypoints, 2])\n bboxes_flattened = keypoint_ops.keypoints_to_enclosing_bounding_boxes(\n regressed_keypoints_flattened)\n else:\n bboxes_flattened = tf.reshape(bboxes, [-1, 4])\n\n # Scale the bounding boxes.\n # Shape [batch_size, num_instances, 4].\n boxlist = box_list.BoxList(bboxes_flattened)\n boxlist_scaled = box_list_ops.scale_height_width(\n boxlist, box_scale, box_scale)\n bboxes_scaled = boxlist_scaled.get()\n bboxes = tf.reshape(bboxes_scaled, [batch_size, num_instances, 4])\n\n # Get ymin, xmin, ymax, xmax bounding box coordinates, tiled per keypoint.\n # Shape [batch_size, num_instances, num_keypoints].\n bboxes_tiled = tf.tile(tf.expand_dims(bboxes, 2), [1, 1, num_keypoints, 1])\n ymin, xmin, ymax, xmax = tf.unstack(bboxes_tiled, axis=3)\n\n # Produce a mask that indicates whether the original regressed keypoint\n # should be used instead of a candidate keypoint.\n # Shape [batch_size, num_instances, num_keypoints].\n search_radius = (\n tf.math.maximum(ymax - ymin, xmax - xmin) * candidate_search_scale)\n mask = (tf.cast(nearby_candidate_coords[:, :, :, 0] < ymin, tf.int32) +\n tf.cast(nearby_candidate_coords[:, :, :, 0] > ymax, tf.int32) +\n tf.cast(nearby_candidate_coords[:, :, :, 1] < xmin, tf.int32) +\n tf.cast(nearby_candidate_coords[:, :, :, 1] > xmax, tf.int32) +\n # Filter out the chosen candidate with score lower than unmatched\n # keypoint score.\n tf.cast(nearby_candidate_scores <\n unmatched_keypoint_score, tf.int32) +\n tf.cast(min_distances > search_radius, tf.int32))\n mask = mask > 0\n\n # Create refined keypoints where candidate keypoints replace original\n # regressed keypoints if they are in the vicinity of the regressed keypoints.\n # Shape [batch_size, num_instances, num_keypoints, 2].\n refined_keypoints = tf.where(\n tf.tile(tf.expand_dims(mask, -1), [1, 1, 1, 2]),\n regressed_keypoints,\n nearby_candidate_coords)\n\n # Update keypoints scores. In the case where we use the original regressed\n # keypoints, we use a default score of `unmatched_keypoint_score`.\n # Shape [batch_size, num_instances, num_keypoints].\n refined_scores = tf.where(\n mask,\n unmatched_keypoint_score * tf.ones_like(nearby_candidate_scores),\n nearby_candidate_scores)\n\n return refined_keypoints, refined_scores\n\n\ndef _pad_to_full_keypoint_dim(keypoint_coords, keypoint_scores, keypoint_inds,\n num_total_keypoints):\n \"\"\"Scatter keypoint elements into tensors with full keypoints dimension.\n\n Args:\n keypoint_coords: a [batch_size, num_instances, num_keypoints, 2] float32\n tensor.\n keypoint_scores: a [batch_size, num_instances, num_keypoints] float32\n tensor.\n keypoint_inds: a list of integers that indicate the keypoint indices for\n this specific keypoint class. These indices are used to scatter into\n tensors that have a `num_total_keypoints` dimension.\n num_total_keypoints: The total number of keypoints that this model predicts.\n\n Returns:\n A tuple with\n keypoint_coords_padded: a\n [batch_size, num_instances, num_total_keypoints,2] float32 tensor.\n keypoint_scores_padded: a [batch_size, num_instances, num_total_keypoints]\n float32 tensor.\n \"\"\"\n batch_size, num_instances, _, _ = (\n shape_utils.combined_static_and_dynamic_shape(keypoint_coords))\n kpt_coords_transposed = tf.transpose(keypoint_coords, [2, 0, 1, 3])\n kpt_scores_transposed = tf.transpose(keypoint_scores, [2, 0, 1])\n kpt_inds_tensor = tf.expand_dims(keypoint_inds, axis=-1)\n kpt_coords_scattered = tf.scatter_nd(\n indices=kpt_inds_tensor,\n updates=kpt_coords_transposed,\n shape=[num_total_keypoints, batch_size, num_instances, 2])\n kpt_scores_scattered = tf.scatter_nd(\n indices=kpt_inds_tensor,\n updates=kpt_scores_transposed,\n shape=[num_total_keypoints, batch_size, num_instances])\n keypoint_coords_padded = tf.transpose(kpt_coords_scattered, [1, 2, 0, 3])\n keypoint_scores_padded = tf.transpose(kpt_scores_scattered, [1, 2, 0])\n return keypoint_coords_padded, keypoint_scores_padded\n\n\ndef _pad_to_full_instance_dim(keypoint_coords, keypoint_scores, instance_inds,\n max_instances):\n \"\"\"Scatter keypoint elements into tensors with full instance dimension.\n\n Args:\n keypoint_coords: a [batch_size, num_instances, num_keypoints, 2] float32\n tensor.\n keypoint_scores: a [batch_size, num_instances, num_keypoints] float32\n tensor.\n instance_inds: a list of integers that indicate the instance indices for\n these keypoints. These indices are used to scatter into tensors\n that have a `max_instances` dimension.\n max_instances: The maximum number of instances detected by the model.\n\n Returns:\n A tuple with\n keypoint_coords_padded: a [batch_size, max_instances, num_keypoints, 2]\n float32 tensor.\n keypoint_scores_padded: a [batch_size, max_instances, num_keypoints]\n float32 tensor.\n \"\"\"\n batch_size, _, num_keypoints, _ = (\n shape_utils.combined_static_and_dynamic_shape(keypoint_coords))\n kpt_coords_transposed = tf.transpose(keypoint_coords, [1, 0, 2, 3])\n kpt_scores_transposed = tf.transpose(keypoint_scores, [1, 0, 2])\n instance_inds = tf.expand_dims(instance_inds, axis=-1)\n kpt_coords_scattered = tf.scatter_nd(\n indices=instance_inds,\n updates=kpt_coords_transposed,\n shape=[max_instances, batch_size, num_keypoints, 2])\n kpt_scores_scattered = tf.scatter_nd(\n indices=instance_inds,\n updates=kpt_scores_transposed,\n shape=[max_instances, batch_size, num_keypoints])\n keypoint_coords_padded = tf.transpose(kpt_coords_scattered, [1, 0, 2, 3])\n keypoint_scores_padded = tf.transpose(kpt_scores_scattered, [1, 0, 2])\n return keypoint_coords_padded, keypoint_scores_padded\n\n\ndef _gather_candidates_at_indices(keypoint_candidates, keypoint_scores,\n indices):\n \"\"\"Gathers keypoint candidate coordinates and scores at indices.\n\n Args:\n keypoint_candidates: a float tensor of shape [batch_size, max_candidates,\n num_keypoints, 2] with candidate coordinates.\n keypoint_scores: a float tensor of shape [batch_size, max_candidates,\n num_keypoints] with keypoint scores.\n indices: an integer tensor of shape [batch_size, num_indices, num_keypoints]\n with indices.\n\n Returns:\n A tuple with\n gathered_keypoint_candidates: a float tensor of shape [batch_size,\n num_indices, num_keypoints, 2] with gathered coordinates.\n gathered_keypoint_scores: a float tensor of shape [batch_size,\n num_indices, num_keypoints, 2].\n \"\"\"\n # Transpose tensors so that all batch dimensions are up front.\n keypoint_candidates_transposed = tf.transpose(keypoint_candidates,\n [0, 2, 1, 3])\n keypoint_scores_transposed = tf.transpose(keypoint_scores, [0, 2, 1])\n nearby_candidate_inds_transposed = tf.transpose(indices,\n [0, 2, 1])\n nearby_candidate_coords_tranposed = tf.gather(\n keypoint_candidates_transposed, nearby_candidate_inds_transposed,\n batch_dims=2)\n nearby_candidate_scores_transposed = tf.gather(\n keypoint_scores_transposed, nearby_candidate_inds_transposed,\n batch_dims=2)\n gathered_keypoint_candidates = tf.transpose(nearby_candidate_coords_tranposed,\n [0, 2, 1, 3])\n gathered_keypoint_scores = tf.transpose(nearby_candidate_scores_transposed,\n [0, 2, 1])\n return gathered_keypoint_candidates, gathered_keypoint_scores\n\n\ndef flattened_indices_from_row_col_indices(row_indices, col_indices, num_cols):\n \"\"\"Get the index in a flattened array given row and column indices.\"\"\"\n return (row_indices * num_cols) + col_indices\n\n\ndef row_col_channel_indices_from_flattened_indices(indices, num_cols,\n num_channels):\n \"\"\"Computes row, column and channel indices from flattened indices.\n\n Args:\n indices: An integer tensor of any shape holding the indices in the flattened\n space.\n num_cols: Number of columns in the image (width).\n num_channels: Number of channels in the image.\n\n Returns:\n row_indices: The row indices corresponding to each of the input indices.\n Same shape as indices.\n col_indices: The column indices corresponding to each of the input indices.\n Same shape as indices.\n channel_indices. The channel indices corresponding to each of the input\n indices.\n\n \"\"\"\n row_indices = (indices // num_channels) // num_cols\n col_indices = (indices // num_channels) % num_cols\n channel_indices = indices % num_channels\n\n return row_indices, col_indices, channel_indices\n\n\ndef get_valid_anchor_weights_in_flattened_image(true_image_shapes, height,\n width):\n \"\"\"Computes valid anchor weights for an image assuming pixels will be flattened.\n\n This function is useful when we only want to penalize valid areas in the\n image in the case when padding is used. The function assumes that the loss\n function will be applied after flattening the spatial dimensions and returns\n anchor weights accordingly.\n\n Args:\n true_image_shapes: An integer tensor of shape [batch_size, 3] representing\n the true image shape (without padding) for each sample in the batch.\n height: height of the prediction from the network.\n width: width of the prediction from the network.\n\n Returns:\n valid_anchor_weights: a float tensor of shape [batch_size, height * width]\n with 1s in locations where the spatial coordinates fall within the height\n and width in true_image_shapes.\n \"\"\"\n\n indices = tf.reshape(tf.range(height * width), [1, -1])\n batch_size = tf.shape(true_image_shapes)[0]\n batch_indices = tf.ones((batch_size, 1), dtype=tf.int32) * indices\n\n y_coords, x_coords, _ = row_col_channel_indices_from_flattened_indices(\n batch_indices, width, 1)\n\n max_y, max_x = true_image_shapes[:, 0], true_image_shapes[:, 1]\n max_x = _to_float32(tf.expand_dims(max_x, 1))\n max_y = _to_float32(tf.expand_dims(max_y, 1))\n\n x_coords = _to_float32(x_coords)\n y_coords = _to_float32(y_coords)\n\n valid_mask = tf.math.logical_and(x_coords < max_x, y_coords < max_y)\n\n return _to_float32(valid_mask)\n\n\ndef convert_strided_predictions_to_normalized_boxes(boxes, stride,\n true_image_shapes):\n \"\"\"Converts predictions in the output space to normalized boxes.\n\n Boxes falling outside the valid image boundary are clipped to be on the\n boundary.\n\n Args:\n boxes: A tensor of shape [batch_size, num_boxes, 4] holding the raw\n coordinates of boxes in the model's output space.\n stride: The stride in the output space.\n true_image_shapes: A tensor of shape [batch_size, 3] representing the true\n shape of the input not considering padding.\n\n Returns:\n boxes: A tensor of shape [batch_size, num_boxes, 4] representing the\n coordinates of the normalized boxes.\n \"\"\"\n\n def _normalize_boxlist(args):\n\n boxes, height, width = args\n boxes = box_list_ops.scale(boxes, stride, stride)\n boxes = box_list_ops.to_normalized_coordinates(boxes, height, width)\n boxes = box_list_ops.clip_to_window(boxes, [0., 0., 1., 1.],\n filter_nonoverlapping=False)\n return boxes\n\n box_lists = [box_list.BoxList(boxes) for boxes in tf.unstack(boxes, axis=0)]\n true_heights, true_widths, _ = tf.unstack(true_image_shapes, axis=1)\n\n true_heights_list = tf.unstack(true_heights, axis=0)\n true_widths_list = tf.unstack(true_widths, axis=0)\n\n box_lists = list(map(_normalize_boxlist,\n zip(box_lists, true_heights_list, true_widths_list)))\n boxes = tf.stack([box_list_instance.get() for\n box_list_instance in box_lists], axis=0)\n\n return boxes\n\n\ndef convert_strided_predictions_to_normalized_keypoints(\n keypoint_coords, keypoint_scores, stride, true_image_shapes,\n clip_out_of_frame_keypoints=False):\n \"\"\"Converts predictions in the output space to normalized keypoints.\n\n If clip_out_of_frame_keypoints=False, keypoint coordinates falling outside\n the valid image boundary are normalized but not clipped; If\n clip_out_of_frame_keypoints=True, keypoint coordinates falling outside the\n valid image boundary are clipped to the closest image boundary and the scores\n will be set to 0.0.\n\n Args:\n keypoint_coords: A tensor of shape\n [batch_size, num_instances, num_keypoints, 2] holding the raw coordinates\n of keypoints in the model's output space.\n keypoint_scores: A tensor of shape\n [batch_size, num_instances, num_keypoints] holding the keypoint scores.\n stride: The stride in the output space.\n true_image_shapes: A tensor of shape [batch_size, 3] representing the true\n shape of the input not considering padding.\n clip_out_of_frame_keypoints: A boolean indicating whether keypoints outside\n the image boundary should be clipped. If True, keypoint coords will be\n clipped to image boundary. If False, keypoints are normalized but not\n filtered based on their location.\n\n Returns:\n keypoint_coords_normalized: A tensor of shape\n [batch_size, num_instances, num_keypoints, 2] representing the coordinates\n of the normalized keypoints.\n keypoint_scores: A tensor of shape\n [batch_size, num_instances, num_keypoints] representing the updated\n keypoint scores.\n \"\"\"\n # Flatten keypoints and scores.\n batch_size, _, _, _ = (\n shape_utils.combined_static_and_dynamic_shape(keypoint_coords))\n\n # Scale and normalize keypoints.\n true_heights, true_widths, _ = tf.unstack(true_image_shapes, axis=1)\n yscale = float(stride) / tf.cast(true_heights, tf.float32)\n xscale = float(stride) / tf.cast(true_widths, tf.float32)\n yx_scale = tf.stack([yscale, xscale], axis=1)\n keypoint_coords_normalized = keypoint_coords * tf.reshape(\n yx_scale, [batch_size, 1, 1, 2])\n\n if clip_out_of_frame_keypoints:\n # Determine the keypoints that are in the true image regions.\n valid_indices = tf.logical_and(\n tf.logical_and(keypoint_coords_normalized[:, :, :, 0] >= 0.0,\n keypoint_coords_normalized[:, :, :, 0] <= 1.0),\n tf.logical_and(keypoint_coords_normalized[:, :, :, 1] >= 0.0,\n keypoint_coords_normalized[:, :, :, 1] <= 1.0))\n batch_window = tf.tile(\n tf.constant([[0.0, 0.0, 1.0, 1.0]], dtype=tf.float32),\n multiples=[batch_size, 1])\n def clip_to_window(inputs):\n keypoints, window = inputs\n return keypoint_ops.clip_to_window(keypoints, window)\n keypoint_coords_normalized = tf.map_fn(\n clip_to_window, (keypoint_coords_normalized, batch_window),\n dtype=tf.float32, back_prop=False)\n keypoint_scores = tf.where(valid_indices, keypoint_scores,\n tf.zeros_like(keypoint_scores))\n return keypoint_coords_normalized, keypoint_scores\n\n\ndef convert_strided_predictions_to_instance_masks(\n boxes, classes, masks, true_image_shapes,\n densepose_part_heatmap=None, densepose_surface_coords=None, stride=4,\n mask_height=256, mask_width=256, score_threshold=0.5,\n densepose_class_index=-1):\n \"\"\"Converts predicted full-image masks into instance masks.\n\n For each predicted detection box:\n * Crop and resize the predicted mask (and optionally DensePose coordinates)\n based on the detected bounding box coordinates and class prediction. Uses\n bilinear resampling.\n * Binarize the mask using the provided score threshold.\n\n Args:\n boxes: A tensor of shape [batch, max_detections, 4] holding the predicted\n boxes, in normalized coordinates (relative to the true image dimensions).\n classes: An integer tensor of shape [batch, max_detections] containing the\n detected class for each box (0-indexed).\n masks: A [batch, output_height, output_width, num_classes] float32\n tensor with class probabilities.\n true_image_shapes: A tensor of shape [batch, 3] representing the true\n shape of the inputs not considering padding.\n densepose_part_heatmap: (Optional) A [batch, output_height, output_width,\n num_parts] float32 tensor with part scores (i.e. logits).\n densepose_surface_coords: (Optional) A [batch, output_height, output_width,\n 2 * num_parts] float32 tensor with predicted part coordinates (in\n vu-format).\n stride: The stride in the output space.\n mask_height: The desired resized height for instance masks.\n mask_width: The desired resized width for instance masks.\n score_threshold: The threshold at which to convert predicted mask\n into foreground pixels.\n densepose_class_index: The class index (0-indexed) corresponding to the\n class which has DensePose labels (e.g. person class).\n\n Returns:\n A tuple of masks and surface_coords.\n instance_masks: A [batch_size, max_detections, mask_height, mask_width]\n uint8 tensor with predicted foreground mask for each\n instance. If DensePose tensors are provided, then each pixel value in the\n mask encodes the 1-indexed part.\n surface_coords: A [batch_size, max_detections, mask_height, mask_width, 2]\n float32 tensor with (v, u) coordinates. Note that v, u coordinates are\n only defined on instance masks, and the coordinates at each location of\n the foreground mask correspond to coordinates on a local part coordinate\n system (the specific part can be inferred from the `instance_masks`\n output. If DensePose feature maps are not passed to this function, this\n output will be None.\n\n Raises:\n ValueError: If one but not both of `densepose_part_heatmap` and\n `densepose_surface_coords` is provided.\n \"\"\"\n batch_size, output_height, output_width, _ = (\n shape_utils.combined_static_and_dynamic_shape(masks))\n input_height = stride * output_height\n input_width = stride * output_width\n\n true_heights, true_widths, _ = tf.unstack(true_image_shapes, axis=1)\n # If necessary, create dummy DensePose tensors to simplify the map function.\n densepose_present = True\n if ((densepose_part_heatmap is not None) ^\n (densepose_surface_coords is not None)):\n raise ValueError('To use DensePose, both `densepose_part_heatmap` and '\n '`densepose_surface_coords` must be provided')\n if densepose_part_heatmap is None and densepose_surface_coords is None:\n densepose_present = False\n densepose_part_heatmap = tf.zeros(\n (batch_size, output_height, output_width, 1), dtype=tf.float32)\n densepose_surface_coords = tf.zeros(\n (batch_size, output_height, output_width, 2), dtype=tf.float32)\n crop_and_threshold_fn = functools.partial(\n crop_and_threshold_masks, input_height=input_height,\n input_width=input_width, mask_height=mask_height, mask_width=mask_width,\n score_threshold=score_threshold,\n densepose_class_index=densepose_class_index)\n\n instance_masks, surface_coords = shape_utils.static_or_dynamic_map_fn(\n crop_and_threshold_fn,\n elems=[boxes, classes, masks, densepose_part_heatmap,\n densepose_surface_coords, true_heights, true_widths],\n dtype=[tf.uint8, tf.float32],\n back_prop=False)\n surface_coords = surface_coords if densepose_present else None\n return instance_masks, surface_coords\n\n\ndef crop_and_threshold_masks(elems, input_height, input_width, mask_height=256,\n mask_width=256, score_threshold=0.5,\n densepose_class_index=-1):\n \"\"\"Crops and thresholds masks based on detection boxes.\n\n Args:\n elems: A tuple of\n boxes - float32 tensor of shape [max_detections, 4]\n classes - int32 tensor of shape [max_detections] (0-indexed)\n masks - float32 tensor of shape [output_height, output_width, num_classes]\n part_heatmap - float32 tensor of shape [output_height, output_width,\n num_parts]\n surf_coords - float32 tensor of shape [output_height, output_width,\n 2 * num_parts]\n true_height - scalar int tensor\n true_width - scalar int tensor\n input_height: Input height to network.\n input_width: Input width to network.\n mask_height: Height for resizing mask crops.\n mask_width: Width for resizing mask crops.\n score_threshold: The threshold at which to convert predicted mask\n into foreground pixels.\n densepose_class_index: scalar int tensor with the class index (0-indexed)\n for DensePose.\n\n Returns:\n A tuple of\n all_instances: A [max_detections, mask_height, mask_width] uint8 tensor\n with a predicted foreground mask for each instance. Background is encoded\n as 0, and foreground is encoded as a positive integer. Specific part\n indices are encoded as 1-indexed parts (for classes that have part\n information).\n surface_coords: A [max_detections, mask_height, mask_width, 2]\n float32 tensor with (v, u) coordinates. for each part.\n \"\"\"\n (boxes, classes, masks, part_heatmap, surf_coords, true_height,\n true_width) = elems\n # Boxes are in normalized coordinates relative to true image shapes. Convert\n # coordinates to be normalized relative to input image shapes (since masks\n # may still have padding).\n boxlist = box_list.BoxList(boxes)\n y_scale = true_height / input_height\n x_scale = true_width / input_width\n boxlist = box_list_ops.scale(boxlist, y_scale, x_scale)\n boxes = boxlist.get()\n # Convert masks from [output_height, output_width, num_classes] to\n # [num_classes, output_height, output_width, 1].\n num_classes = tf.shape(masks)[-1]\n masks_4d = tf.transpose(masks, perm=[2, 0, 1])[:, :, :, tf.newaxis]\n # Tile part and surface coordinate masks for all classes.\n part_heatmap_4d = tf.tile(part_heatmap[tf.newaxis, :, :, :],\n multiples=[num_classes, 1, 1, 1])\n surf_coords_4d = tf.tile(surf_coords[tf.newaxis, :, :, :],\n multiples=[num_classes, 1, 1, 1])\n feature_maps_concat = tf.concat([masks_4d, part_heatmap_4d, surf_coords_4d],\n axis=-1)\n # The following tensor has shape\n # [max_detections, mask_height, mask_width, 1 + 3 * num_parts].\n cropped_masks = tf2.image.crop_and_resize(\n feature_maps_concat,\n boxes=boxes,\n box_indices=classes,\n crop_size=[mask_height, mask_width],\n method='bilinear')\n\n # Split the cropped masks back into instance masks, part masks, and surface\n # coordinates.\n num_parts = tf.shape(part_heatmap)[-1]\n instance_masks, part_heatmap_cropped, surface_coords_cropped = tf.split(\n cropped_masks, [1, num_parts, 2 * num_parts], axis=-1)\n\n # Threshold the instance masks. Resulting tensor has shape\n # [max_detections, mask_height, mask_width, 1].\n instance_masks_int = tf.cast(\n tf.math.greater_equal(instance_masks, score_threshold), dtype=tf.int32)\n\n # Produce a binary mask that is 1.0 only:\n # - in the foreground region for an instance\n # - in detections corresponding to the DensePose class\n det_with_parts = tf.equal(classes, densepose_class_index)\n det_with_parts = tf.cast(\n tf.reshape(det_with_parts, [-1, 1, 1, 1]), dtype=tf.int32)\n instance_masks_with_parts = tf.math.multiply(instance_masks_int,\n det_with_parts)\n\n # Similarly, produce a binary mask that holds the foreground masks only for\n # instances without parts (i.e. non-DensePose classes).\n det_without_parts = 1 - det_with_parts\n instance_masks_without_parts = tf.math.multiply(instance_masks_int,\n det_without_parts)\n\n # Assemble a tensor that has standard instance segmentation masks for\n # non-DensePose classes (with values in [0, 1]), and part segmentation masks\n # for DensePose classes (with vaues in [0, 1, ..., num_parts]).\n part_mask_int_zero_indexed = tf.math.argmax(\n part_heatmap_cropped, axis=-1, output_type=tf.int32)[:, :, :, tf.newaxis]\n part_mask_int_one_indexed = part_mask_int_zero_indexed + 1\n all_instances = (instance_masks_without_parts +\n instance_masks_with_parts * part_mask_int_one_indexed)\n\n # Gather the surface coordinates for the parts.\n surface_coords_cropped = tf.reshape(\n surface_coords_cropped, [-1, mask_height, mask_width, num_parts, 2])\n surface_coords = gather_surface_coords_for_parts(surface_coords_cropped,\n part_mask_int_zero_indexed)\n surface_coords = (\n surface_coords * tf.cast(instance_masks_with_parts, tf.float32))\n\n return [tf.squeeze(all_instances, axis=3), surface_coords]\n\n\ndef gather_surface_coords_for_parts(surface_coords_cropped,\n highest_scoring_part):\n \"\"\"Gathers the (v, u) coordinates for the highest scoring DensePose parts.\n\n Args:\n surface_coords_cropped: A [max_detections, height, width, num_parts, 2]\n float32 tensor with (v, u) surface coordinates.\n highest_scoring_part: A [max_detections, height, width] integer tensor with\n the highest scoring part (0-indexed) indices for each location.\n\n Returns:\n A [max_detections, height, width, 2] float32 tensor with the (v, u)\n coordinates selected from the highest scoring parts.\n \"\"\"\n max_detections, height, width, num_parts, _ = (\n shape_utils.combined_static_and_dynamic_shape(surface_coords_cropped))\n flattened_surface_coords = tf.reshape(surface_coords_cropped, [-1, 2])\n flattened_part_ids = tf.reshape(highest_scoring_part, [-1])\n\n # Produce lookup indices that represent the locations of the highest scoring\n # parts in the `flattened_surface_coords` tensor.\n flattened_lookup_indices = (\n num_parts * tf.range(max_detections * height * width) +\n flattened_part_ids)\n\n vu_coords_flattened = tf.gather(flattened_surface_coords,\n flattened_lookup_indices, axis=0)\n return tf.reshape(vu_coords_flattened, [max_detections, height, width, 2])\n\n\ndef predicted_embeddings_at_object_centers(embedding_predictions,\n y_indices, x_indices):\n \"\"\"Returns the predicted embeddings at specified object centers.\n\n Args:\n embedding_predictions: A float tensor of shape [batch_size, height, width,\n reid_embed_size] holding predicted embeddings.\n y_indices: A [batch, num_instances] int tensor holding y indices for object\n centers. These indices correspond to locations in the output feature map.\n x_indices: A [batch, num_instances] int tensor holding x indices for object\n centers. These indices correspond to locations in the output feature map.\n\n Returns:\n A float tensor of shape [batch_size, num_objects, reid_embed_size] where\n predicted embeddings are gathered at the provided locations.\n \"\"\"\n batch_size, _, width, _ = _get_shape(embedding_predictions, 4)\n flattened_indices = flattened_indices_from_row_col_indices(\n y_indices, x_indices, width)\n _, num_instances = _get_shape(flattened_indices, 2)\n embeddings_flat = _flatten_spatial_dimensions(embedding_predictions)\n embeddings = tf.gather(embeddings_flat, flattened_indices, batch_dims=1)\n embeddings = tf.reshape(embeddings, [batch_size, num_instances, -1])\n\n return embeddings\n\n\nclass ObjectDetectionParams(\n collections.namedtuple('ObjectDetectionParams', [\n 'localization_loss', 'scale_loss_weight', 'offset_loss_weight',\n 'task_loss_weight'\n ])):\n \"\"\"Namedtuple to host object detection related parameters.\n\n This is a wrapper class over the fields that are either the hyper-parameters\n or the loss functions needed for the object detection task. The class is\n immutable after constructed. Please see the __new__ function for detailed\n information for each fields.\n \"\"\"\n\n __slots__ = ()\n\n def __new__(cls,\n localization_loss,\n scale_loss_weight,\n offset_loss_weight,\n task_loss_weight=1.0):\n \"\"\"Constructor with default values for ObjectDetectionParams.\n\n Args:\n localization_loss: a object_detection.core.losses.Loss object to compute\n the loss for the center offset and height/width predictions in\n CenterNet.\n scale_loss_weight: float, The weight for localizing box size. Note that\n the scale loss is dependent on the input image size, since we penalize\n the raw height and width. This constant may need to be adjusted\n depending on the input size.\n offset_loss_weight: float, The weight for localizing center offsets.\n task_loss_weight: float, the weight of the object detection loss.\n\n Returns:\n An initialized ObjectDetectionParams namedtuple.\n \"\"\"\n return super(ObjectDetectionParams,\n cls).__new__(cls, localization_loss, scale_loss_weight,\n offset_loss_weight, task_loss_weight)\n\n\nclass KeypointEstimationParams(\n collections.namedtuple('KeypointEstimationParams', [\n 'task_name', 'class_id', 'keypoint_indices', 'classification_loss',\n 'localization_loss', 'keypoint_labels', 'keypoint_std_dev',\n 'keypoint_heatmap_loss_weight', 'keypoint_offset_loss_weight',\n 'keypoint_regression_loss_weight', 'keypoint_candidate_score_threshold',\n 'heatmap_bias_init', 'num_candidates_per_keypoint', 'task_loss_weight',\n 'peak_max_pool_kernel_size', 'unmatched_keypoint_score', 'box_scale',\n 'candidate_search_scale', 'candidate_ranking_mode',\n 'offset_peak_radius', 'per_keypoint_offset'\n ])):\n \"\"\"Namedtuple to host object detection related parameters.\n\n This is a wrapper class over the fields that are either the hyper-parameters\n or the loss functions needed for the keypoint estimation task. The class is\n immutable after constructed. Please see the __new__ function for detailed\n information for each fields.\n \"\"\"\n\n __slots__ = ()\n\n def __new__(cls,\n task_name,\n class_id,\n keypoint_indices,\n classification_loss,\n localization_loss,\n keypoint_labels=None,\n keypoint_std_dev=None,\n keypoint_heatmap_loss_weight=1.0,\n keypoint_offset_loss_weight=1.0,\n keypoint_regression_loss_weight=1.0,\n keypoint_candidate_score_threshold=0.1,\n heatmap_bias_init=-2.19,\n num_candidates_per_keypoint=100,\n task_loss_weight=1.0,\n peak_max_pool_kernel_size=3,\n unmatched_keypoint_score=0.1,\n box_scale=1.2,\n candidate_search_scale=0.3,\n candidate_ranking_mode='min_distance',\n offset_peak_radius=0,\n per_keypoint_offset=False):\n \"\"\"Constructor with default values for KeypointEstimationParams.\n\n Args:\n task_name: string, the name of the task this namedtuple corresponds to.\n Note that it should be an unique identifier of the task.\n class_id: int, the ID of the class that contains the target keypoints to\n considered in this task. For example, if the task is human pose\n estimation, the class id should correspond to the \"human\" class. Note\n that the ID is 0-based, meaning that class 0 corresponds to the first\n non-background object class.\n keypoint_indices: A list of integers representing the indicies of the\n keypoints to be considered in this task. This is used to retrieve the\n subset of the keypoints from gt_keypoints that should be considered in\n this task.\n classification_loss: an object_detection.core.losses.Loss object to\n compute the loss for the class predictions in CenterNet.\n localization_loss: an object_detection.core.losses.Loss object to compute\n the loss for the center offset and height/width predictions in\n CenterNet.\n keypoint_labels: A list of strings representing the label text of each\n keypoint, e.g. \"nose\", 'left_shoulder\". Note that the length of this\n list should be equal to keypoint_indices.\n keypoint_std_dev: A list of float represent the standard deviation of the\n Gaussian kernel used to generate the keypoint heatmap. It is to provide\n the flexibility of using different sizes of Gaussian kernel for each\n keypoint class.\n keypoint_heatmap_loss_weight: float, The weight for the keypoint heatmap.\n keypoint_offset_loss_weight: float, The weight for the keypoint offsets\n loss.\n keypoint_regression_loss_weight: float, The weight for keypoint regression\n loss. Note that the loss is dependent on the input image size, since we\n penalize the raw height and width. This constant may need to be adjusted\n depending on the input size.\n keypoint_candidate_score_threshold: float, The heatmap score threshold for\n a keypoint to become a valid candidate.\n heatmap_bias_init: float, the initial value of bias in the convolutional\n kernel of the class prediction head. If set to None, the bias is\n initialized with zeros.\n num_candidates_per_keypoint: The maximum number of candidates to retrieve\n for each keypoint.\n task_loss_weight: float, the weight of the keypoint estimation loss.\n peak_max_pool_kernel_size: Max pool kernel size to use to pull off peak\n score locations in a neighborhood (independently for each keypoint\n types).\n unmatched_keypoint_score: The default score to use for regressed keypoints\n that are not successfully snapped to a nearby candidate.\n box_scale: The multiplier to expand the bounding boxes (either the\n provided boxes or those which tightly cover the regressed keypoints).\n candidate_search_scale: The scale parameter that multiplies the largest\n dimension of a bounding box. The resulting distance becomes a search\n radius for candidates in the vicinity of each regressed keypoint.\n candidate_ranking_mode: One of ['min_distance', 'score_distance_ratio']\n indicating how to select the keypoint candidate.\n offset_peak_radius: The radius (in the unit of output pixel) around\n groundtruth heatmap peak to assign the offset targets. If set 0, then\n the offset target will only be assigned to the heatmap peak (same\n behavior as the original paper).\n per_keypoint_offset: A bool indicates whether to assign offsets for each\n keypoint channel separately. If set False, the output offset target has\n the shape [batch_size, out_height, out_width, 2] (same behavior as the\n original paper). If set True, the output offset target has the shape\n [batch_size, out_height, out_width, 2 * num_keypoints] (recommended when\n the offset_peak_radius is not zero).\n\n Returns:\n An initialized KeypointEstimationParams namedtuple.\n \"\"\"\n return super(KeypointEstimationParams, cls).__new__(\n cls, task_name, class_id, keypoint_indices, classification_loss,\n localization_loss, keypoint_labels, keypoint_std_dev,\n keypoint_heatmap_loss_weight, keypoint_offset_loss_weight,\n keypoint_regression_loss_weight, keypoint_candidate_score_threshold,\n heatmap_bias_init, num_candidates_per_keypoint, task_loss_weight,\n peak_max_pool_kernel_size, unmatched_keypoint_score, box_scale,\n candidate_search_scale, candidate_ranking_mode, offset_peak_radius,\n per_keypoint_offset)\n\n\nclass ObjectCenterParams(\n collections.namedtuple('ObjectCenterParams', [\n 'classification_loss', 'object_center_loss_weight', 'heatmap_bias_init',\n 'min_box_overlap_iou', 'max_box_predictions', 'use_only_known_classes'\n ])):\n \"\"\"Namedtuple to store object center prediction related parameters.\"\"\"\n\n __slots__ = ()\n\n def __new__(cls,\n classification_loss,\n object_center_loss_weight,\n heatmap_bias_init=-2.19,\n min_box_overlap_iou=0.7,\n max_box_predictions=100,\n use_labeled_classes=False):\n \"\"\"Constructor with default values for ObjectCenterParams.\n\n Args:\n classification_loss: an object_detection.core.losses.Loss object to\n compute the loss for the class predictions in CenterNet.\n object_center_loss_weight: float, The weight for the object center loss.\n heatmap_bias_init: float, the initial value of bias in the convolutional\n kernel of the object center prediction head. If set to None, the bias is\n initialized with zeros.\n min_box_overlap_iou: float, the minimum IOU overlap that predicted boxes\n need have with groundtruth boxes to not be penalized. This is used for\n computing the class specific center heatmaps.\n max_box_predictions: int, the maximum number of boxes to predict.\n use_labeled_classes: boolean, compute the loss only labeled classes.\n\n Returns:\n An initialized ObjectCenterParams namedtuple.\n \"\"\"\n return super(ObjectCenterParams,\n cls).__new__(cls, classification_loss,\n object_center_loss_weight, heatmap_bias_init,\n min_box_overlap_iou, max_box_predictions,\n use_labeled_classes)\n\n\nclass MaskParams(\n collections.namedtuple('MaskParams', [\n 'classification_loss', 'task_loss_weight', 'mask_height', 'mask_width',\n 'score_threshold', 'heatmap_bias_init'\n ])):\n \"\"\"Namedtuple to store mask prediction related parameters.\"\"\"\n\n __slots__ = ()\n\n def __new__(cls,\n classification_loss,\n task_loss_weight=1.0,\n mask_height=256,\n mask_width=256,\n score_threshold=0.5,\n heatmap_bias_init=-2.19):\n \"\"\"Constructor with default values for MaskParams.\n\n Args:\n classification_loss: an object_detection.core.losses.Loss object to\n compute the loss for the semantic segmentation predictions in CenterNet.\n task_loss_weight: float, The loss weight for the segmentation task.\n mask_height: The height of the resized instance segmentation mask.\n mask_width: The width of the resized instance segmentation mask.\n score_threshold: The threshold at which to convert predicted mask\n probabilities (after passing through sigmoid) into foreground pixels.\n heatmap_bias_init: float, the initial value of bias in the convolutional\n kernel of the semantic segmentation prediction head. If set to None, the\n bias is initialized with zeros.\n\n Returns:\n An initialized MaskParams namedtuple.\n \"\"\"\n return super(MaskParams,\n cls).__new__(cls, classification_loss,\n task_loss_weight, mask_height, mask_width,\n score_threshold, heatmap_bias_init)\n\n\nclass DensePoseParams(\n collections.namedtuple('DensePoseParams', [\n 'class_id', 'classification_loss', 'localization_loss',\n 'part_loss_weight', 'coordinate_loss_weight', 'num_parts',\n 'task_loss_weight', 'upsample_to_input_res', 'upsample_method',\n 'heatmap_bias_init'\n ])):\n \"\"\"Namedtuple to store DensePose prediction related parameters.\"\"\"\n\n __slots__ = ()\n\n def __new__(cls,\n class_id,\n classification_loss,\n localization_loss,\n part_loss_weight=1.0,\n coordinate_loss_weight=1.0,\n num_parts=24,\n task_loss_weight=1.0,\n upsample_to_input_res=True,\n upsample_method='bilinear',\n heatmap_bias_init=-2.19):\n \"\"\"Constructor with default values for DensePoseParams.\n\n Args:\n class_id: the ID of the class that contains the DensePose groundtruth.\n This should typically correspond to the \"person\" class. Note that the ID\n is 0-based, meaning that class 0 corresponds to the first non-background\n object class.\n classification_loss: an object_detection.core.losses.Loss object to\n compute the loss for the body part predictions in CenterNet.\n localization_loss: an object_detection.core.losses.Loss object to compute\n the loss for the surface coordinate regression in CenterNet.\n part_loss_weight: The loss weight to apply to part prediction.\n coordinate_loss_weight: The loss weight to apply to surface coordinate\n prediction.\n num_parts: The number of DensePose parts to predict.\n task_loss_weight: float, the loss weight for the DensePose task.\n upsample_to_input_res: Whether to upsample the DensePose feature maps to\n the input resolution before applying loss. Note that the prediction\n outputs are still at the standard CenterNet output stride.\n upsample_method: Method for upsampling DensePose feature maps. Options are\n either 'bilinear' or 'nearest'). This takes no effect when\n `upsample_to_input_res` is False.\n heatmap_bias_init: float, the initial value of bias in the convolutional\n kernel of the part prediction head. If set to None, the\n bias is initialized with zeros.\n\n Returns:\n An initialized DensePoseParams namedtuple.\n \"\"\"\n return super(DensePoseParams,\n cls).__new__(cls, class_id, classification_loss,\n localization_loss, part_loss_weight,\n coordinate_loss_weight, num_parts,\n task_loss_weight, upsample_to_input_res,\n upsample_method, heatmap_bias_init)\n\n\nclass TrackParams(\n collections.namedtuple('TrackParams', [\n 'num_track_ids', 'reid_embed_size', 'num_fc_layers',\n 'classification_loss', 'task_loss_weight'\n ])):\n \"\"\"Namedtuple to store tracking prediction related parameters.\"\"\"\n\n __slots__ = ()\n\n def __new__(cls,\n num_track_ids,\n reid_embed_size,\n num_fc_layers,\n classification_loss,\n task_loss_weight=1.0):\n \"\"\"Constructor with default values for TrackParams.\n\n Args:\n num_track_ids: int. The maximum track ID in the dataset. Used for ReID\n embedding classification task.\n reid_embed_size: int. The embedding size for ReID task.\n num_fc_layers: int. The number of (fully-connected, batch-norm, relu)\n layers for track ID classification head.\n classification_loss: an object_detection.core.losses.Loss object to\n compute the loss for the ReID embedding in CenterNet.\n task_loss_weight: float, the loss weight for the tracking task.\n\n Returns:\n An initialized TrackParams namedtuple.\n \"\"\"\n return super(TrackParams,\n cls).__new__(cls, num_track_ids, reid_embed_size,\n num_fc_layers, classification_loss,\n task_loss_weight)\n\n\nclass TemporalOffsetParams(\n collections.namedtuple('TemporalOffsetParams', [\n 'localization_loss', 'task_loss_weight'\n ])):\n \"\"\"Namedtuple to store temporal offset related parameters.\"\"\"\n\n __slots__ = ()\n\n def __new__(cls,\n localization_loss,\n task_loss_weight=1.0):\n \"\"\"Constructor with default values for TrackParams.\n\n Args:\n localization_loss: an object_detection.core.losses.Loss object to\n compute the loss for the temporal offset in CenterNet.\n task_loss_weight: float, the loss weight for the temporal offset\n task.\n\n Returns:\n An initialized TemporalOffsetParams namedtuple.\n \"\"\"\n return super(TemporalOffsetParams,\n cls).__new__(cls, localization_loss, task_loss_weight)\n\n# The following constants are used to generate the keys of the\n# (prediction, loss, target assigner,...) dictionaries used in CenterNetMetaArch\n# class.\nDETECTION_TASK = 'detection_task'\nOBJECT_CENTER = 'object_center'\nBOX_SCALE = 'box/scale'\nBOX_OFFSET = 'box/offset'\nKEYPOINT_REGRESSION = 'keypoint/regression'\nKEYPOINT_HEATMAP = 'keypoint/heatmap'\nKEYPOINT_OFFSET = 'keypoint/offset'\nSEGMENTATION_TASK = 'segmentation_task'\nSEGMENTATION_HEATMAP = 'segmentation/heatmap'\nDENSEPOSE_TASK = 'densepose_task'\nDENSEPOSE_HEATMAP = 'densepose/heatmap'\nDENSEPOSE_REGRESSION = 'densepose/regression'\nLOSS_KEY_PREFIX = 'Loss'\nTRACK_TASK = 'track_task'\nTRACK_REID = 'track/reid'\nTEMPORALOFFSET_TASK = 'temporal_offset_task'\nTEMPORAL_OFFSET = 'track/offset'\n\n\ndef get_keypoint_name(task_name, head_name):\n return '%s/%s' % (task_name, head_name)\n\n\ndef get_num_instances_from_weights(groundtruth_weights_list):\n \"\"\"Computes the number of instances/boxes from the weights in a batch.\n\n Args:\n groundtruth_weights_list: A list of float tensors with shape\n [max_num_instances] representing whether there is an actual instance in\n the image (with non-zero value) or is padded to match the\n max_num_instances (with value 0.0). The list represents the batch\n dimension.\n\n Returns:\n A scalar integer tensor incidating how many instances/boxes are in the\n images in the batch. Note that this function is usually used to normalize\n the loss so the minimum return value is 1 to avoid weird behavior.\n \"\"\"\n num_instances = tf.reduce_sum(\n [tf.math.count_nonzero(w) for w in groundtruth_weights_list])\n num_instances = tf.maximum(num_instances, 1)\n return num_instances\n\n\nclass CenterNetMetaArch(model.DetectionModel):\n \"\"\"The CenterNet meta architecture [1].\n\n [1]: https://arxiv.org/abs/1904.07850\n \"\"\"\n\n def __init__(self,\n is_training,\n add_summaries,\n num_classes,\n feature_extractor,\n image_resizer_fn,\n object_center_params,\n object_detection_params=None,\n keypoint_params_dict=None,\n mask_params=None,\n densepose_params=None,\n track_params=None,\n temporal_offset_params=None):\n \"\"\"Initializes a CenterNet model.\n\n Args:\n is_training: Set to True if this model is being built for training.\n add_summaries: Whether to add tf summaries in the model.\n num_classes: int, The number of classes that the model should predict.\n feature_extractor: A CenterNetFeatureExtractor to use to extract features\n from an image.\n image_resizer_fn: a callable for image resizing. This callable always\n takes a rank-3 image tensor (corresponding to a single image) and\n returns a rank-3 image tensor, possibly with new spatial dimensions and\n a 1-D tensor of shape [3] indicating shape of true image within the\n resized image tensor as the resized image tensor could be padded. See\n builders/image_resizer_builder.py.\n object_center_params: An ObjectCenterParams namedtuple. This object holds\n the hyper-parameters for object center prediction. This is required by\n either object detection or keypoint estimation tasks.\n object_detection_params: An ObjectDetectionParams namedtuple. This object\n holds the hyper-parameters necessary for object detection. Please see\n the class definition for more details.\n keypoint_params_dict: A dictionary that maps from task name to the\n corresponding KeypointEstimationParams namedtuple. This object holds the\n hyper-parameters necessary for multiple keypoint estimations. Please\n see the class definition for more details.\n mask_params: A MaskParams namedtuple. This object\n holds the hyper-parameters for segmentation. Please see the class\n definition for more details.\n densepose_params: A DensePoseParams namedtuple. This object holds the\n hyper-parameters for DensePose prediction. Please see the class\n definition for more details. Note that if this is provided, it is\n expected that `mask_params` is also provided.\n track_params: A TrackParams namedtuple. This object\n holds the hyper-parameters for tracking. Please see the class\n definition for more details.\n temporal_offset_params: A TemporalOffsetParams namedtuple. This object\n holds the hyper-parameters for offset prediction based tracking.\n \"\"\"\n assert object_detection_params or keypoint_params_dict\n # Shorten the name for convenience and better formatting.\n self._is_training = is_training\n # The Objects as Points paper attaches loss functions to multiple\n # (`num_feature_outputs`) feature maps in the the backbone. E.g.\n # for the hourglass backbone, `num_feature_outputs` is 2.\n self._feature_extractor = feature_extractor\n self._num_feature_outputs = feature_extractor.num_feature_outputs\n self._stride = self._feature_extractor.out_stride\n self._image_resizer_fn = image_resizer_fn\n self._center_params = object_center_params\n self._od_params = object_detection_params\n self._kp_params_dict = keypoint_params_dict\n self._mask_params = mask_params\n if densepose_params is not None and mask_params is None:\n raise ValueError('To run DensePose prediction, `mask_params` must also '\n 'be supplied.')\n self._densepose_params = densepose_params\n self._track_params = track_params\n self._temporal_offset_params = temporal_offset_params\n\n # Construct the prediction head nets.\n self._prediction_head_dict = self._construct_prediction_heads(\n num_classes,\n self._num_feature_outputs,\n class_prediction_bias_init=self._center_params.heatmap_bias_init)\n # Initialize the target assigners.\n self._target_assigner_dict = self._initialize_target_assigners(\n stride=self._stride,\n min_box_overlap_iou=self._center_params.min_box_overlap_iou)\n\n # Will be used in VOD single_frame_meta_arch for tensor reshape.\n self._batched_prediction_tensor_names = []\n\n super(CenterNetMetaArch, self).__init__(num_classes)\n\n @property\n def batched_prediction_tensor_names(self):\n if not self._batched_prediction_tensor_names:\n raise RuntimeError('Must call predict() method to get batched prediction '\n 'tensor names.')\n return self._batched_prediction_tensor_names\n\n def _construct_prediction_heads(self, num_classes, num_feature_outputs,\n class_prediction_bias_init):\n \"\"\"Constructs the prediction heads based on the specific parameters.\n\n Args:\n num_classes: An integer indicating how many classes in total to predict.\n num_feature_outputs: An integer indicating how many feature outputs to use\n for calculating the loss. The Objects as Points paper attaches loss\n functions to multiple (`num_feature_outputs`) feature maps in the the\n backbone. E.g. for the hourglass backbone, `num_feature_outputs` is 2.\n class_prediction_bias_init: float, the initial value of bias in the\n convolutional kernel of the class prediction head. If set to None, the\n bias is initialized with zeros.\n\n Returns:\n A dictionary of keras modules generated by calling make_prediction_net\n function. It will also create and set a private member of the class when\n learning the tracking task.\n \"\"\"\n prediction_heads = {}\n prediction_heads[OBJECT_CENTER] = [\n make_prediction_net(num_classes, bias_fill=class_prediction_bias_init)\n for _ in range(num_feature_outputs)\n ]\n if self._od_params is not None:\n prediction_heads[BOX_SCALE] = [\n make_prediction_net(NUM_SIZE_CHANNELS)\n for _ in range(num_feature_outputs)\n ]\n prediction_heads[BOX_OFFSET] = [\n make_prediction_net(NUM_OFFSET_CHANNELS)\n for _ in range(num_feature_outputs)\n ]\n if self._kp_params_dict is not None:\n for task_name, kp_params in self._kp_params_dict.items():\n num_keypoints = len(kp_params.keypoint_indices)\n prediction_heads[get_keypoint_name(task_name, KEYPOINT_HEATMAP)] = [\n make_prediction_net(\n num_keypoints, bias_fill=kp_params.heatmap_bias_init)\n for _ in range(num_feature_outputs)\n ]\n prediction_heads[get_keypoint_name(task_name, KEYPOINT_REGRESSION)] = [\n make_prediction_net(NUM_OFFSET_CHANNELS * num_keypoints)\n for _ in range(num_feature_outputs)\n ]\n if kp_params.per_keypoint_offset:\n prediction_heads[get_keypoint_name(task_name, KEYPOINT_OFFSET)] = [\n make_prediction_net(NUM_OFFSET_CHANNELS * num_keypoints)\n for _ in range(num_feature_outputs)\n ]\n else:\n prediction_heads[get_keypoint_name(task_name, KEYPOINT_OFFSET)] = [\n make_prediction_net(NUM_OFFSET_CHANNELS)\n for _ in range(num_feature_outputs)\n ]\n if self._mask_params is not None:\n prediction_heads[SEGMENTATION_HEATMAP] = [\n make_prediction_net(num_classes,\n bias_fill=self._mask_params.heatmap_bias_init)\n for _ in range(num_feature_outputs)]\n if self._densepose_params is not None:\n prediction_heads[DENSEPOSE_HEATMAP] = [\n make_prediction_net( # pylint: disable=g-complex-comprehension\n self._densepose_params.num_parts,\n bias_fill=self._densepose_params.heatmap_bias_init)\n for _ in range(num_feature_outputs)]\n prediction_heads[DENSEPOSE_REGRESSION] = [\n make_prediction_net(2 * self._densepose_params.num_parts)\n for _ in range(num_feature_outputs)\n ]\n if self._track_params is not None:\n prediction_heads[TRACK_REID] = [\n make_prediction_net(self._track_params.reid_embed_size)\n for _ in range(num_feature_outputs)]\n\n # Creates a classification network to train object embeddings by learning\n # a projection from embedding space to object track ID space.\n self.track_reid_classification_net = tf.keras.Sequential()\n for _ in range(self._track_params.num_fc_layers - 1):\n self.track_reid_classification_net.add(\n tf.keras.layers.Dense(self._track_params.reid_embed_size,\n input_shape=(\n self._track_params.reid_embed_size,)))\n self.track_reid_classification_net.add(\n tf.keras.layers.BatchNormalization())\n self.track_reid_classification_net.add(tf.keras.layers.ReLU())\n self.track_reid_classification_net.add(\n tf.keras.layers.Dense(self._track_params.num_track_ids,\n input_shape=(\n self._track_params.reid_embed_size,)))\n if self._temporal_offset_params is not None:\n prediction_heads[TEMPORAL_OFFSET] = [\n make_prediction_net(NUM_OFFSET_CHANNELS)\n for _ in range(num_feature_outputs)\n ]\n return prediction_heads\n\n def _initialize_target_assigners(self, stride, min_box_overlap_iou):\n \"\"\"Initializes the target assigners and puts them in a dictionary.\n\n Args:\n stride: An integer indicating the stride of the image.\n min_box_overlap_iou: float, the minimum IOU overlap that predicted boxes\n need have with groundtruth boxes to not be penalized. This is used for\n computing the class specific center heatmaps.\n\n Returns:\n A dictionary of initialized target assigners for each task.\n \"\"\"\n target_assigners = {}\n target_assigners[OBJECT_CENTER] = (\n cn_assigner.CenterNetCenterHeatmapTargetAssigner(\n stride, min_box_overlap_iou))\n if self._od_params is not None:\n target_assigners[DETECTION_TASK] = (\n cn_assigner.CenterNetBoxTargetAssigner(stride))\n if self._kp_params_dict is not None:\n for task_name, kp_params in self._kp_params_dict.items():\n target_assigners[task_name] = (\n cn_assigner.CenterNetKeypointTargetAssigner(\n stride=stride,\n class_id=kp_params.class_id,\n keypoint_indices=kp_params.keypoint_indices,\n keypoint_std_dev=kp_params.keypoint_std_dev,\n peak_radius=kp_params.offset_peak_radius,\n per_keypoint_offset=kp_params.per_keypoint_offset))\n if self._mask_params is not None:\n target_assigners[SEGMENTATION_TASK] = (\n cn_assigner.CenterNetMaskTargetAssigner(stride))\n if self._densepose_params is not None:\n dp_stride = 1 if self._densepose_params.upsample_to_input_res else stride\n target_assigners[DENSEPOSE_TASK] = (\n cn_assigner.CenterNetDensePoseTargetAssigner(dp_stride))\n if self._track_params is not None:\n target_assigners[TRACK_TASK] = (\n cn_assigner.CenterNetTrackTargetAssigner(\n stride, self._track_params.num_track_ids))\n if self._temporal_offset_params is not None:\n target_assigners[TEMPORALOFFSET_TASK] = (\n cn_assigner.CenterNetTemporalOffsetTargetAssigner(stride))\n\n return target_assigners\n\n def _compute_object_center_loss(self, input_height, input_width,\n object_center_predictions, per_pixel_weights):\n \"\"\"Computes the object center loss.\n\n Args:\n input_height: An integer scalar tensor representing input image height.\n input_width: An integer scalar tensor representing input image width.\n object_center_predictions: A list of float tensors of shape [batch_size,\n out_height, out_width, num_classes] representing the object center\n feature maps.\n per_pixel_weights: A float tensor of shape [batch_size,\n out_height * out_width, 1] with 1s in locations where the spatial\n coordinates fall within the height and width in true_image_shapes.\n\n Returns:\n A float scalar tensor representing the object center loss per instance.\n \"\"\"\n gt_boxes_list = self.groundtruth_lists(fields.BoxListFields.boxes)\n gt_classes_list = self.groundtruth_lists(fields.BoxListFields.classes)\n gt_weights_list = self.groundtruth_lists(fields.BoxListFields.weights)\n\n if self._center_params.use_only_known_classes:\n gt_labeled_classes_list = self.groundtruth_lists(\n fields.InputDataFields.groundtruth_labeled_classes)\n batch_labeled_classes = tf.stack(gt_labeled_classes_list, axis=0)\n batch_labeled_classes_shape = tf.shape(batch_labeled_classes)\n batch_labeled_classes = tf.reshape(\n batch_labeled_classes,\n [batch_labeled_classes_shape[0], 1, batch_labeled_classes_shape[-1]])\n per_pixel_weights = per_pixel_weights * batch_labeled_classes\n\n # Convert the groundtruth to targets.\n assigner = self._target_assigner_dict[OBJECT_CENTER]\n heatmap_targets = assigner.assign_center_targets_from_boxes(\n height=input_height,\n width=input_width,\n gt_boxes_list=gt_boxes_list,\n gt_classes_list=gt_classes_list,\n gt_weights_list=gt_weights_list)\n\n flattened_heatmap_targets = _flatten_spatial_dimensions(heatmap_targets)\n num_boxes = _to_float32(get_num_instances_from_weights(gt_weights_list))\n\n loss = 0.0\n object_center_loss = self._center_params.classification_loss\n # Loop through each feature output head.\n for pred in object_center_predictions:\n pred = _flatten_spatial_dimensions(pred)\n loss += object_center_loss(\n pred, flattened_heatmap_targets, weights=per_pixel_weights)\n loss_per_instance = tf.reduce_sum(loss) / (\n float(len(object_center_predictions)) * num_boxes)\n return loss_per_instance\n\n def _compute_object_detection_losses(self, input_height, input_width,\n prediction_dict, per_pixel_weights):\n \"\"\"Computes the weighted object detection losses.\n\n This wrapper function calls the function which computes the losses for\n object detection task and applies corresponding weights to the losses.\n\n Args:\n input_height: An integer scalar tensor representing input image height.\n input_width: An integer scalar tensor representing input image width.\n prediction_dict: A dictionary holding predicted tensors output by\n \"predict\" function. See \"predict\" function for more detailed\n description.\n per_pixel_weights: A float tensor of shape [batch_size,\n out_height * out_width, 1] with 1s in locations where the spatial\n coordinates fall within the height and width in true_image_shapes.\n\n Returns:\n A dictionary of scalar float tensors representing the weighted losses for\n object detection task:\n BOX_SCALE: the weighted scale (height/width) loss.\n BOX_OFFSET: the weighted object offset loss.\n \"\"\"\n od_scale_loss, od_offset_loss = self._compute_box_scale_and_offset_loss(\n scale_predictions=prediction_dict[BOX_SCALE],\n offset_predictions=prediction_dict[BOX_OFFSET],\n input_height=input_height,\n input_width=input_width)\n loss_dict = {}\n loss_dict[BOX_SCALE] = (\n self._od_params.scale_loss_weight * od_scale_loss)\n loss_dict[BOX_OFFSET] = (\n self._od_params.offset_loss_weight * od_offset_loss)\n return loss_dict\n\n def _compute_box_scale_and_offset_loss(self, input_height, input_width,\n scale_predictions, offset_predictions):\n \"\"\"Computes the scale loss of the object detection task.\n\n Args:\n input_height: An integer scalar tensor representing input image height.\n input_width: An integer scalar tensor representing input image width.\n scale_predictions: A list of float tensors of shape [batch_size,\n out_height, out_width, 2] representing the prediction heads of the model\n for object scale (i.e height and width).\n offset_predictions: A list of float tensors of shape [batch_size,\n out_height, out_width, 2] representing the prediction heads of the model\n for object offset.\n\n Returns:\n A tuple of two losses:\n scale_loss: A float scalar tensor representing the object height/width\n loss normalized by total number of boxes.\n offset_loss: A float scalar tensor representing the object offset loss\n normalized by total number of boxes\n \"\"\"\n # TODO(vighneshb) Explore a size invariant version of scale loss.\n gt_boxes_list = self.groundtruth_lists(fields.BoxListFields.boxes)\n gt_weights_list = self.groundtruth_lists(fields.BoxListFields.weights)\n num_boxes = _to_float32(get_num_instances_from_weights(gt_weights_list))\n num_predictions = float(len(scale_predictions))\n\n assigner = self._target_assigner_dict[DETECTION_TASK]\n (batch_indices, batch_height_width_targets, batch_offset_targets,\n batch_weights) = assigner.assign_size_and_offset_targets(\n height=input_height,\n width=input_width,\n gt_boxes_list=gt_boxes_list,\n gt_weights_list=gt_weights_list)\n batch_weights = tf.expand_dims(batch_weights, -1)\n\n scale_loss = 0\n offset_loss = 0\n localization_loss_fn = self._od_params.localization_loss\n for scale_pred, offset_pred in zip(scale_predictions, offset_predictions):\n # Compute the scale loss.\n scale_pred = cn_assigner.get_batch_predictions_from_indices(\n scale_pred, batch_indices)\n scale_loss += localization_loss_fn(\n scale_pred, batch_height_width_targets, weights=batch_weights)\n # Compute the offset loss.\n offset_pred = cn_assigner.get_batch_predictions_from_indices(\n offset_pred, batch_indices)\n offset_loss += localization_loss_fn(\n offset_pred, batch_offset_targets, weights=batch_weights)\n scale_loss = tf.reduce_sum(scale_loss) / (\n num_predictions * num_boxes)\n offset_loss = tf.reduce_sum(offset_loss) / (\n num_predictions * num_boxes)\n return scale_loss, offset_loss\n\n def _compute_keypoint_estimation_losses(self, task_name, input_height,\n input_width, prediction_dict,\n per_pixel_weights):\n \"\"\"Computes the weighted keypoint losses.\"\"\"\n kp_params = self._kp_params_dict[task_name]\n heatmap_key = get_keypoint_name(task_name, KEYPOINT_HEATMAP)\n offset_key = get_keypoint_name(task_name, KEYPOINT_OFFSET)\n regression_key = get_keypoint_name(task_name, KEYPOINT_REGRESSION)\n heatmap_loss = self._compute_kp_heatmap_loss(\n input_height=input_height,\n input_width=input_width,\n task_name=task_name,\n heatmap_predictions=prediction_dict[heatmap_key],\n classification_loss_fn=kp_params.classification_loss,\n per_pixel_weights=per_pixel_weights)\n offset_loss = self._compute_kp_offset_loss(\n input_height=input_height,\n input_width=input_width,\n task_name=task_name,\n offset_predictions=prediction_dict[offset_key],\n localization_loss_fn=kp_params.localization_loss)\n reg_loss = self._compute_kp_regression_loss(\n input_height=input_height,\n input_width=input_width,\n task_name=task_name,\n regression_predictions=prediction_dict[regression_key],\n localization_loss_fn=kp_params.localization_loss)\n\n loss_dict = {}\n loss_dict[heatmap_key] = (\n kp_params.keypoint_heatmap_loss_weight * heatmap_loss)\n loss_dict[offset_key] = (\n kp_params.keypoint_offset_loss_weight * offset_loss)\n loss_dict[regression_key] = (\n kp_params.keypoint_regression_loss_weight * reg_loss)\n return loss_dict\n\n def _compute_kp_heatmap_loss(self, input_height, input_width, task_name,\n heatmap_predictions, classification_loss_fn,\n per_pixel_weights):\n \"\"\"Computes the heatmap loss of the keypoint estimation task.\n\n Args:\n input_height: An integer scalar tensor representing input image height.\n input_width: An integer scalar tensor representing input image width.\n task_name: A string representing the name of the keypoint task.\n heatmap_predictions: A list of float tensors of shape [batch_size,\n out_height, out_width, num_keypoints] representing the prediction heads\n of the model for keypoint heatmap.\n classification_loss_fn: An object_detection.core.losses.Loss object to\n compute the loss for the class predictions in CenterNet.\n per_pixel_weights: A float tensor of shape [batch_size,\n out_height * out_width, 1] with 1s in locations where the spatial\n coordinates fall within the height and width in true_image_shapes.\n\n Returns:\n loss: A float scalar tensor representing the object keypoint heatmap loss\n normalized by number of instances.\n \"\"\"\n gt_keypoints_list = self.groundtruth_lists(fields.BoxListFields.keypoints)\n gt_classes_list = self.groundtruth_lists(fields.BoxListFields.classes)\n gt_weights_list = self.groundtruth_lists(fields.BoxListFields.weights)\n gt_boxes_list = self.groundtruth_lists(fields.BoxListFields.boxes)\n\n assigner = self._target_assigner_dict[task_name]\n (keypoint_heatmap, num_instances_per_kp_type,\n valid_mask_batch) = assigner.assign_keypoint_heatmap_targets(\n height=input_height,\n width=input_width,\n gt_keypoints_list=gt_keypoints_list,\n gt_weights_list=gt_weights_list,\n gt_classes_list=gt_classes_list,\n gt_boxes_list=gt_boxes_list)\n flattened_valid_mask = _flatten_spatial_dimensions(\n tf.expand_dims(valid_mask_batch, axis=-1))\n flattened_heapmap_targets = _flatten_spatial_dimensions(keypoint_heatmap)\n # Sum over the number of instances per keypoint types to get the total\n # number of keypoints. Note that this is used to normalized the loss and we\n # keep the minimum value to be 1 to avoid generating weird loss value when\n # no keypoint is in the image batch.\n num_instances = tf.maximum(\n tf.cast(tf.reduce_sum(num_instances_per_kp_type), dtype=tf.float32),\n 1.0)\n loss = 0.0\n # Loop through each feature output head.\n for pred in heatmap_predictions:\n pred = _flatten_spatial_dimensions(pred)\n unweighted_loss = classification_loss_fn(\n pred,\n flattened_heapmap_targets,\n weights=tf.ones_like(per_pixel_weights))\n # Apply the weights after the loss function to have full control over it.\n loss += unweighted_loss * per_pixel_weights * flattened_valid_mask\n loss = tf.reduce_sum(loss) / (\n float(len(heatmap_predictions)) * num_instances)\n return loss\n\n def _compute_kp_offset_loss(self, input_height, input_width, task_name,\n offset_predictions, localization_loss_fn):\n \"\"\"Computes the offset loss of the keypoint estimation task.\n\n Args:\n input_height: An integer scalar tensor representing input image height.\n input_width: An integer scalar tensor representing input image width.\n task_name: A string representing the name of the keypoint task.\n offset_predictions: A list of float tensors of shape [batch_size,\n out_height, out_width, 2] representing the prediction heads of the model\n for keypoint offset.\n localization_loss_fn: An object_detection.core.losses.Loss object to\n compute the loss for the keypoint offset predictions in CenterNet.\n\n Returns:\n loss: A float scalar tensor representing the keypoint offset loss\n normalized by number of total keypoints.\n \"\"\"\n gt_keypoints_list = self.groundtruth_lists(fields.BoxListFields.keypoints)\n gt_classes_list = self.groundtruth_lists(fields.BoxListFields.classes)\n gt_weights_list = self.groundtruth_lists(fields.BoxListFields.weights)\n\n assigner = self._target_assigner_dict[task_name]\n (batch_indices, batch_offsets,\n batch_weights) = assigner.assign_keypoints_offset_targets(\n height=input_height,\n width=input_width,\n gt_keypoints_list=gt_keypoints_list,\n gt_weights_list=gt_weights_list,\n gt_classes_list=gt_classes_list)\n\n # Keypoint offset loss.\n loss = 0.0\n for prediction in offset_predictions:\n batch_size, out_height, out_width, channels = _get_shape(prediction, 4)\n if channels > 2:\n prediction = tf.reshape(\n prediction, shape=[batch_size, out_height, out_width, -1, 2])\n prediction = cn_assigner.get_batch_predictions_from_indices(\n prediction, batch_indices)\n # The dimensions passed are not as per the doc string but the loss\n # still computes the correct value.\n unweighted_loss = localization_loss_fn(\n prediction,\n batch_offsets,\n weights=tf.expand_dims(tf.ones_like(batch_weights), -1))\n # Apply the weights after the loss function to have full control over it.\n loss += batch_weights * tf.reduce_sum(unweighted_loss, axis=1)\n\n loss = tf.reduce_sum(loss) / (\n float(len(offset_predictions)) *\n tf.maximum(tf.reduce_sum(batch_weights), 1.0))\n return loss\n\n def _compute_kp_regression_loss(self, input_height, input_width, task_name,\n regression_predictions, localization_loss_fn):\n \"\"\"Computes the keypoint regression loss of the keypoint estimation task.\n\n Args:\n input_height: An integer scalar tensor representing input image height.\n input_width: An integer scalar tensor representing input image width.\n task_name: A string representing the name of the keypoint task.\n regression_predictions: A list of float tensors of shape [batch_size,\n out_height, out_width, 2 * num_keypoints] representing the prediction\n heads of the model for keypoint regression offset.\n localization_loss_fn: An object_detection.core.losses.Loss object to\n compute the loss for the keypoint regression offset predictions in\n CenterNet.\n\n Returns:\n loss: A float scalar tensor representing the keypoint regression offset\n loss normalized by number of total keypoints.\n \"\"\"\n gt_boxes_list = self.groundtruth_lists(fields.BoxListFields.boxes)\n gt_keypoints_list = self.groundtruth_lists(fields.BoxListFields.keypoints)\n gt_classes_list = self.groundtruth_lists(fields.BoxListFields.classes)\n gt_weights_list = self.groundtruth_lists(fields.BoxListFields.weights)\n # keypoint regression offset loss.\n assigner = self._target_assigner_dict[task_name]\n (batch_indices, batch_regression_offsets,\n batch_weights) = assigner.assign_joint_regression_targets(\n height=input_height,\n width=input_width,\n gt_keypoints_list=gt_keypoints_list,\n gt_classes_list=gt_classes_list,\n gt_weights_list=gt_weights_list,\n gt_boxes_list=gt_boxes_list)\n\n loss = 0.0\n for prediction in regression_predictions:\n batch_size, out_height, out_width, _ = _get_shape(prediction, 4)\n reshaped_prediction = tf.reshape(\n prediction, shape=[batch_size, out_height, out_width, -1, 2])\n reg_prediction = cn_assigner.get_batch_predictions_from_indices(\n reshaped_prediction, batch_indices)\n unweighted_loss = localization_loss_fn(\n reg_prediction,\n batch_regression_offsets,\n weights=tf.expand_dims(tf.ones_like(batch_weights), -1))\n # Apply the weights after the loss function to have full control over it.\n loss += batch_weights * tf.reduce_sum(unweighted_loss, axis=1)\n\n loss = tf.reduce_sum(loss) / (\n float(len(regression_predictions)) *\n tf.maximum(tf.reduce_sum(batch_weights), 1.0))\n return loss\n\n def _compute_segmentation_losses(self, prediction_dict, per_pixel_weights):\n \"\"\"Computes all the losses associated with segmentation.\n\n Args:\n prediction_dict: The dictionary returned from the predict() method.\n per_pixel_weights: A float tensor of shape [batch_size,\n out_height * out_width, 1] with 1s in locations where the spatial\n coordinates fall within the height and width in true_image_shapes.\n\n Returns:\n A dictionary with segmentation losses.\n \"\"\"\n segmentation_heatmap = prediction_dict[SEGMENTATION_HEATMAP]\n mask_loss = self._compute_mask_loss(\n segmentation_heatmap, per_pixel_weights)\n losses = {\n SEGMENTATION_HEATMAP: mask_loss\n }\n return losses\n\n def _compute_mask_loss(self, segmentation_predictions,\n per_pixel_weights):\n \"\"\"Computes the mask loss.\n\n Args:\n segmentation_predictions: A list of float32 tensors of shape [batch_size,\n out_height, out_width, num_classes].\n per_pixel_weights: A float tensor of shape [batch_size,\n out_height * out_width, 1] with 1s in locations where the spatial\n coordinates fall within the height and width in true_image_shapes.\n\n Returns:\n A float scalar tensor representing the mask loss.\n \"\"\"\n gt_masks_list = self.groundtruth_lists(fields.BoxListFields.masks)\n gt_classes_list = self.groundtruth_lists(fields.BoxListFields.classes)\n\n # Convert the groundtruth to targets.\n assigner = self._target_assigner_dict[SEGMENTATION_TASK]\n heatmap_targets = assigner.assign_segmentation_targets(\n gt_masks_list=gt_masks_list,\n gt_classes_list=gt_classes_list)\n\n flattened_heatmap_targets = _flatten_spatial_dimensions(heatmap_targets)\n\n loss = 0.0\n mask_loss_fn = self._mask_params.classification_loss\n total_pixels_in_loss = tf.reduce_sum(per_pixel_weights)\n\n # Loop through each feature output head.\n for pred in segmentation_predictions:\n pred = _flatten_spatial_dimensions(pred)\n loss += mask_loss_fn(\n pred, flattened_heatmap_targets, weights=per_pixel_weights)\n # TODO(ronnyvotel): Consider other ways to normalize loss.\n total_loss = tf.reduce_sum(loss) / (\n float(len(segmentation_predictions)) * total_pixels_in_loss)\n return total_loss\n\n def _compute_densepose_losses(self, input_height, input_width,\n prediction_dict):\n \"\"\"Computes the weighted DensePose losses.\n\n Args:\n input_height: An integer scalar tensor representing input image height.\n input_width: An integer scalar tensor representing input image width.\n prediction_dict: A dictionary holding predicted tensors output by the\n \"predict\" function. See the \"predict\" function for more detailed\n description.\n\n Returns:\n A dictionary of scalar float tensors representing the weighted losses for\n the DensePose task:\n DENSEPOSE_HEATMAP: the weighted part segmentation loss.\n DENSEPOSE_REGRESSION: the weighted part surface coordinate loss.\n \"\"\"\n dp_heatmap_loss, dp_regression_loss = (\n self._compute_densepose_part_and_coordinate_losses(\n input_height=input_height,\n input_width=input_width,\n part_predictions=prediction_dict[DENSEPOSE_HEATMAP],\n surface_coord_predictions=prediction_dict[DENSEPOSE_REGRESSION]))\n loss_dict = {}\n loss_dict[DENSEPOSE_HEATMAP] = (\n self._densepose_params.part_loss_weight * dp_heatmap_loss)\n loss_dict[DENSEPOSE_REGRESSION] = (\n self._densepose_params.coordinate_loss_weight * dp_regression_loss)\n return loss_dict\n\n def _compute_densepose_part_and_coordinate_losses(\n self, input_height, input_width, part_predictions,\n surface_coord_predictions):\n \"\"\"Computes the individual losses for the DensePose task.\n\n Args:\n input_height: An integer scalar tensor representing input image height.\n input_width: An integer scalar tensor representing input image width.\n part_predictions: A list of float tensors of shape [batch_size,\n out_height, out_width, num_parts].\n surface_coord_predictions: A list of float tensors of shape [batch_size,\n out_height, out_width, 2 * num_parts].\n\n Returns:\n A tuple with two scalar loss tensors: part_prediction_loss and\n surface_coord_loss.\n \"\"\"\n gt_dp_num_points_list = self.groundtruth_lists(\n fields.BoxListFields.densepose_num_points)\n gt_dp_part_ids_list = self.groundtruth_lists(\n fields.BoxListFields.densepose_part_ids)\n gt_dp_surface_coords_list = self.groundtruth_lists(\n fields.BoxListFields.densepose_surface_coords)\n gt_weights_list = self.groundtruth_lists(fields.BoxListFields.weights)\n\n assigner = self._target_assigner_dict[DENSEPOSE_TASK]\n batch_indices, batch_part_ids, batch_surface_coords, batch_weights = (\n assigner.assign_part_and_coordinate_targets(\n height=input_height,\n width=input_width,\n gt_dp_num_points_list=gt_dp_num_points_list,\n gt_dp_part_ids_list=gt_dp_part_ids_list,\n gt_dp_surface_coords_list=gt_dp_surface_coords_list,\n gt_weights_list=gt_weights_list))\n\n part_prediction_loss = 0\n surface_coord_loss = 0\n classification_loss_fn = self._densepose_params.classification_loss\n localization_loss_fn = self._densepose_params.localization_loss\n num_predictions = float(len(part_predictions))\n num_valid_points = tf.math.count_nonzero(batch_weights)\n num_valid_points = tf.cast(tf.math.maximum(num_valid_points, 1), tf.float32)\n for part_pred, surface_coord_pred in zip(part_predictions,\n surface_coord_predictions):\n # Potentially upsample the feature maps, so that better quality (i.e.\n # higher res) groundtruth can be applied.\n if self._densepose_params.upsample_to_input_res:\n part_pred = tf.keras.layers.UpSampling2D(\n self._stride, interpolation=self._densepose_params.upsample_method)(\n part_pred)\n surface_coord_pred = tf.keras.layers.UpSampling2D(\n self._stride, interpolation=self._densepose_params.upsample_method)(\n surface_coord_pred)\n # Compute the part prediction loss.\n part_pred = cn_assigner.get_batch_predictions_from_indices(\n part_pred, batch_indices[:, 0:3])\n part_prediction_loss += classification_loss_fn(\n part_pred[:, tf.newaxis, :],\n batch_part_ids[:, tf.newaxis, :],\n weights=batch_weights[:, tf.newaxis, tf.newaxis])\n # Compute the surface coordinate loss.\n batch_size, out_height, out_width, _ = _get_shape(\n surface_coord_pred, 4)\n surface_coord_pred = tf.reshape(\n surface_coord_pred, [batch_size, out_height, out_width, -1, 2])\n surface_coord_pred = cn_assigner.get_batch_predictions_from_indices(\n surface_coord_pred, batch_indices)\n surface_coord_loss += localization_loss_fn(\n surface_coord_pred,\n batch_surface_coords,\n weights=batch_weights[:, tf.newaxis])\n part_prediction_loss = tf.reduce_sum(part_prediction_loss) / (\n num_predictions * num_valid_points)\n surface_coord_loss = tf.reduce_sum(surface_coord_loss) / (\n num_predictions * num_valid_points)\n return part_prediction_loss, surface_coord_loss\n\n def _compute_track_losses(self, input_height, input_width, prediction_dict):\n \"\"\"Computes all the losses associated with tracking.\n\n Args:\n input_height: An integer scalar tensor representing input image height.\n input_width: An integer scalar tensor representing input image width.\n prediction_dict: The dictionary returned from the predict() method.\n\n Returns:\n A dictionary with tracking losses.\n \"\"\"\n object_reid_predictions = prediction_dict[TRACK_REID]\n embedding_loss = self._compute_track_embedding_loss(\n input_height=input_height,\n input_width=input_width,\n object_reid_predictions=object_reid_predictions)\n losses = {\n TRACK_REID: embedding_loss\n }\n return losses\n\n def _compute_track_embedding_loss(self, input_height, input_width,\n object_reid_predictions):\n \"\"\"Computes the object ReID loss.\n\n The embedding is trained as a classification task where the target is the\n ID of each track among all tracks in the whole dataset.\n\n Args:\n input_height: An integer scalar tensor representing input image height.\n input_width: An integer scalar tensor representing input image width.\n object_reid_predictions: A list of float tensors of shape [batch_size,\n out_height, out_width, reid_embed_size] representing the object\n embedding feature maps.\n\n Returns:\n A float scalar tensor representing the object ReID loss per instance.\n \"\"\"\n gt_track_ids_list = self.groundtruth_lists(fields.BoxListFields.track_ids)\n gt_boxes_list = self.groundtruth_lists(fields.BoxListFields.boxes)\n gt_weights_list = self.groundtruth_lists(fields.BoxListFields.weights)\n num_boxes = _to_float32(get_num_instances_from_weights(gt_weights_list))\n\n # Convert the groundtruth to targets.\n assigner = self._target_assigner_dict[TRACK_TASK]\n batch_indices, batch_weights, track_targets = assigner.assign_track_targets(\n height=input_height,\n width=input_width,\n gt_track_ids_list=gt_track_ids_list,\n gt_boxes_list=gt_boxes_list,\n gt_weights_list=gt_weights_list)\n batch_weights = tf.expand_dims(batch_weights, -1)\n\n loss = 0.0\n object_reid_loss = self._track_params.classification_loss\n # Loop through each feature output head.\n for pred in object_reid_predictions:\n embedding_pred = cn_assigner.get_batch_predictions_from_indices(\n pred, batch_indices)\n\n reid_classification = self.track_reid_classification_net(embedding_pred)\n\n loss += object_reid_loss(\n reid_classification, track_targets, weights=batch_weights)\n\n loss_per_instance = tf.reduce_sum(loss) / (\n float(len(object_reid_predictions)) * num_boxes)\n\n return loss_per_instance\n\n def _compute_temporal_offset_loss(self, input_height,\n input_width, prediction_dict):\n \"\"\"Computes the temporal offset loss for tracking.\n\n Args:\n input_height: An integer scalar tensor representing input image height.\n input_width: An integer scalar tensor representing input image width.\n prediction_dict: The dictionary returned from the predict() method.\n\n Returns:\n A dictionary with track/temporal_offset losses.\n \"\"\"\n gt_boxes_list = self.groundtruth_lists(fields.BoxListFields.boxes)\n gt_offsets_list = self.groundtruth_lists(\n fields.BoxListFields.temporal_offsets)\n gt_match_list = self.groundtruth_lists(\n fields.BoxListFields.track_match_flags)\n gt_weights_list = self.groundtruth_lists(fields.BoxListFields.weights)\n num_boxes = tf.cast(\n get_num_instances_from_weights(gt_weights_list), tf.float32)\n\n offset_predictions = prediction_dict[TEMPORAL_OFFSET]\n num_predictions = float(len(offset_predictions))\n\n assigner = self._target_assigner_dict[TEMPORALOFFSET_TASK]\n (batch_indices, batch_offset_targets,\n batch_weights) = assigner.assign_temporal_offset_targets(\n height=input_height,\n width=input_width,\n gt_boxes_list=gt_boxes_list,\n gt_offsets_list=gt_offsets_list,\n gt_match_list=gt_match_list,\n gt_weights_list=gt_weights_list)\n batch_weights = tf.expand_dims(batch_weights, -1)\n\n offset_loss_fn = self._temporal_offset_params.localization_loss\n loss_dict = {}\n offset_loss = 0\n for offset_pred in offset_predictions:\n offset_pred = cn_assigner.get_batch_predictions_from_indices(\n offset_pred, batch_indices)\n offset_loss += offset_loss_fn(offset_pred[:, None],\n batch_offset_targets[:, None],\n weights=batch_weights)\n offset_loss = tf.reduce_sum(offset_loss) / (num_predictions * num_boxes)\n loss_dict[TEMPORAL_OFFSET] = offset_loss\n return loss_dict\n\n def preprocess(self, inputs):\n outputs = shape_utils.resize_images_and_return_shapes(\n inputs, self._image_resizer_fn)\n resized_inputs, true_image_shapes = outputs\n\n return (self._feature_extractor.preprocess(resized_inputs),\n true_image_shapes)\n\n def predict(self, preprocessed_inputs, _):\n \"\"\"Predicts CenterNet prediction tensors given an input batch.\n\n Feature extractors are free to produce predictions from multiple feature\n maps and therefore we return a dictionary mapping strings to lists.\n E.g. the hourglass backbone produces two feature maps.\n\n Args:\n preprocessed_inputs: a [batch, height, width, channels] float32 tensor\n representing a batch of images.\n\n Returns:\n prediction_dict: a dictionary holding predicted tensors with\n 'preprocessed_inputs' - The input image after being resized and\n preprocessed by the feature extractor.\n 'object_center' - A list of size num_feature_outputs containing\n float tensors of size [batch_size, output_height, output_width,\n num_classes] representing the predicted object center heatmap logits.\n 'box/scale' - [optional] A list of size num_feature_outputs holding\n float tensors of size [batch_size, output_height, output_width, 2]\n representing the predicted box height and width at each output\n location. This field exists only when object detection task is\n specified.\n 'box/offset' - [optional] A list of size num_feature_outputs holding\n float tensors of size [batch_size, output_height, output_width, 2]\n representing the predicted y and x offsets at each output location.\n '$TASK_NAME/keypoint_heatmap' - [optional] A list of size\n num_feature_outputs holding float tensors of size [batch_size,\n output_height, output_width, num_keypoints] representing the predicted\n keypoint heatmap logits.\n '$TASK_NAME/keypoint_offset' - [optional] A list of size\n num_feature_outputs holding float tensors of size [batch_size,\n output_height, output_width, 2] representing the predicted keypoint\n offsets at each output location.\n '$TASK_NAME/keypoint_regression' - [optional] A list of size\n num_feature_outputs holding float tensors of size [batch_size,\n output_height, output_width, 2 * num_keypoints] representing the\n predicted keypoint regression at each output location.\n 'segmentation/heatmap' - [optional] A list of size num_feature_outputs\n holding float tensors of size [batch_size, output_height,\n output_width, num_classes] representing the mask logits.\n 'densepose/heatmap' - [optional] A list of size num_feature_outputs\n holding float tensors of size [batch_size, output_height,\n output_width, num_parts] representing the mask logits for each part.\n 'densepose/regression' - [optional] A list of size num_feature_outputs\n holding float tensors of size [batch_size, output_height,\n output_width, 2 * num_parts] representing the DensePose surface\n coordinate predictions.\n Note the $TASK_NAME is provided by the KeypointEstimation namedtuple\n used to differentiate between different keypoint tasks.\n \"\"\"\n features_list = self._feature_extractor(preprocessed_inputs)\n\n predictions = {}\n for head_name, heads in self._prediction_head_dict.items():\n predictions[head_name] = [\n head(feature) for (feature, head) in zip(features_list, heads)\n ]\n predictions['preprocessed_inputs'] = preprocessed_inputs\n\n self._batched_prediction_tensor_names = predictions.keys()\n return predictions\n\n def loss(self, prediction_dict, true_image_shapes, scope=None):\n \"\"\"Computes scalar loss tensors with respect to provided groundtruth.\n\n This function implements the various CenterNet losses.\n\n Args:\n prediction_dict: a dictionary holding predicted tensors returned by\n \"predict\" function.\n true_image_shapes: int32 tensor of shape [batch, 3] where each row is of\n the form [height, width, channels] indicating the shapes of true images\n in the resized images, as resized images can be padded with zeros.\n scope: Optional scope name.\n\n Returns:\n A dictionary mapping the keys [\n 'Loss/object_center',\n 'Loss/box/scale', (optional)\n 'Loss/box/offset', (optional)\n 'Loss/$TASK_NAME/keypoint/heatmap', (optional)\n 'Loss/$TASK_NAME/keypoint/offset', (optional)\n 'Loss/$TASK_NAME/keypoint/regression', (optional)\n 'Loss/segmentation/heatmap', (optional)\n 'Loss/densepose/heatmap', (optional)\n 'Loss/densepose/regression', (optional)\n 'Loss/track/reid'] (optional)\n 'Loss/track/offset'] (optional)\n scalar tensors corresponding to the losses for different tasks. Note the\n $TASK_NAME is provided by the KeypointEstimation namedtuple used to\n differentiate between different keypoint tasks.\n \"\"\"\n\n _, input_height, input_width, _ = _get_shape(\n prediction_dict['preprocessed_inputs'], 4)\n\n output_height, output_width = (input_height // self._stride,\n input_width // self._stride)\n\n # TODO(vighneshb) Explore whether using floor here is safe.\n output_true_image_shapes = tf.ceil(\n tf.to_float(true_image_shapes) / self._stride)\n valid_anchor_weights = get_valid_anchor_weights_in_flattened_image(\n output_true_image_shapes, output_height, output_width)\n valid_anchor_weights = tf.expand_dims(valid_anchor_weights, 2)\n\n object_center_loss = self._compute_object_center_loss(\n object_center_predictions=prediction_dict[OBJECT_CENTER],\n input_height=input_height,\n input_width=input_width,\n per_pixel_weights=valid_anchor_weights)\n losses = {\n OBJECT_CENTER:\n self._center_params.object_center_loss_weight * object_center_loss\n }\n if self._od_params is not None:\n od_losses = self._compute_object_detection_losses(\n input_height=input_height,\n input_width=input_width,\n prediction_dict=prediction_dict,\n per_pixel_weights=valid_anchor_weights)\n for key in od_losses:\n od_losses[key] = od_losses[key] * self._od_params.task_loss_weight\n losses.update(od_losses)\n\n if self._kp_params_dict is not None:\n for task_name, params in self._kp_params_dict.items():\n kp_losses = self._compute_keypoint_estimation_losses(\n task_name=task_name,\n input_height=input_height,\n input_width=input_width,\n prediction_dict=prediction_dict,\n per_pixel_weights=valid_anchor_weights)\n for key in kp_losses:\n kp_losses[key] = kp_losses[key] * params.task_loss_weight\n losses.update(kp_losses)\n\n if self._mask_params is not None:\n seg_losses = self._compute_segmentation_losses(\n prediction_dict=prediction_dict,\n per_pixel_weights=valid_anchor_weights)\n for key in seg_losses:\n seg_losses[key] = seg_losses[key] * self._mask_params.task_loss_weight\n losses.update(seg_losses)\n\n if self._densepose_params is not None:\n densepose_losses = self._compute_densepose_losses(\n input_height=input_height,\n input_width=input_width,\n prediction_dict=prediction_dict)\n for key in densepose_losses:\n densepose_losses[key] = (\n densepose_losses[key] * self._densepose_params.task_loss_weight)\n losses.update(densepose_losses)\n\n if self._track_params is not None:\n track_losses = self._compute_track_losses(\n input_height=input_height,\n input_width=input_width,\n prediction_dict=prediction_dict)\n for key in track_losses:\n track_losses[key] = (\n track_losses[key] * self._track_params.task_loss_weight)\n losses.update(track_losses)\n\n if self._temporal_offset_params is not None:\n offset_losses = self._compute_temporal_offset_loss(\n input_height=input_height,\n input_width=input_width,\n prediction_dict=prediction_dict)\n for key in offset_losses:\n offset_losses[key] = (\n offset_losses[key] * self._temporal_offset_params.task_loss_weight)\n losses.update(offset_losses)\n\n # Prepend the LOSS_KEY_PREFIX to the keys in the dictionary such that the\n # losses will be grouped together in Tensorboard.\n return dict([('%s/%s' % (LOSS_KEY_PREFIX, key), val)\n for key, val in losses.items()])\n\n def postprocess(self, prediction_dict, true_image_shapes, **params):\n \"\"\"Produces boxes given a prediction dict returned by predict().\n\n Although predict returns a list of tensors, only the last tensor in\n each list is used for making box predictions.\n\n Args:\n prediction_dict: a dictionary holding predicted tensors from \"predict\"\n function.\n true_image_shapes: int32 tensor of shape [batch, 3] where each row is of\n the form [height, width, channels] indicating the shapes of true images\n in the resized images, as resized images can be padded with zeros.\n **params: Currently ignored.\n\n Returns:\n detections: a dictionary containing the following fields\n detection_boxes - A tensor of shape [batch, max_detections, 4]\n holding the predicted boxes.\n detection_boxes_strided: A tensor of shape [batch_size, num_detections,\n 4] holding the predicted boxes in absolute coordinates of the\n feature extractor's final layer output.\n detection_scores: A tensor of shape [batch, max_detections] holding\n the predicted score for each box.\n detection_classes: An integer tensor of shape [batch, max_detections]\n containing the detected class for each box.\n num_detections: An integer tensor of shape [batch] containing the\n number of detected boxes for each sample in the batch.\n detection_keypoints: (Optional) A float tensor of shape [batch,\n max_detections, num_keypoints, 2] with normalized keypoints. Any\n invalid keypoints have their coordinates and scores set to 0.0.\n detection_keypoint_scores: (Optional) A float tensor of shape [batch,\n max_detection, num_keypoints] with scores for each keypoint.\n detection_masks: (Optional) A uint8 tensor of shape [batch,\n max_detections, mask_height, mask_width] with masks for each\n detection. Background is specified with 0, and foreground is specified\n with positive integers (1 for standard instance segmentation mask, and\n 1-indexed parts for DensePose task).\n detection_surface_coords: (Optional) A float32 tensor of shape [batch,\n max_detection, mask_height, mask_width, 2] with DensePose surface\n coordinates, in (v, u) format.\n detection_embeddings: (Optional) A float tensor of shape [batch,\n max_detections, reid_embed_size] containing object embeddings.\n \"\"\"\n object_center_prob = tf.nn.sigmoid(prediction_dict[OBJECT_CENTER][-1])\n # Get x, y and channel indices corresponding to the top indices in the class\n # center predictions.\n detection_scores, y_indices, x_indices, channel_indices = (\n top_k_feature_map_locations(\n object_center_prob, max_pool_kernel_size=3,\n k=self._center_params.max_box_predictions))\n\n boxes_strided, classes, scores, num_detections = (\n prediction_tensors_to_boxes(\n detection_scores, y_indices, x_indices, channel_indices,\n prediction_dict[BOX_SCALE][-1], prediction_dict[BOX_OFFSET][-1]))\n\n boxes = convert_strided_predictions_to_normalized_boxes(\n boxes_strided, self._stride, true_image_shapes)\n\n postprocess_dict = {\n fields.DetectionResultFields.detection_boxes: boxes,\n fields.DetectionResultFields.detection_scores: scores,\n fields.DetectionResultFields.detection_classes: classes,\n fields.DetectionResultFields.num_detections: num_detections,\n 'detection_boxes_strided': boxes_strided\n }\n\n if self._kp_params_dict:\n keypoints, keypoint_scores = self._postprocess_keypoints(\n prediction_dict, classes, y_indices, x_indices,\n boxes_strided, num_detections)\n keypoints, keypoint_scores = (\n convert_strided_predictions_to_normalized_keypoints(\n keypoints, keypoint_scores, self._stride, true_image_shapes,\n clip_out_of_frame_keypoints=True))\n postprocess_dict.update({\n fields.DetectionResultFields.detection_keypoints: keypoints,\n fields.DetectionResultFields.detection_keypoint_scores:\n keypoint_scores\n })\n\n if self._mask_params:\n masks = tf.nn.sigmoid(prediction_dict[SEGMENTATION_HEATMAP][-1])\n densepose_part_heatmap, densepose_surface_coords = None, None\n densepose_class_index = 0\n if self._densepose_params:\n densepose_part_heatmap = prediction_dict[DENSEPOSE_HEATMAP][-1]\n densepose_surface_coords = prediction_dict[DENSEPOSE_REGRESSION][-1]\n densepose_class_index = self._densepose_params.class_id\n instance_masks, surface_coords = (\n convert_strided_predictions_to_instance_masks(\n boxes, classes, masks, true_image_shapes,\n densepose_part_heatmap, densepose_surface_coords,\n stride=self._stride, mask_height=self._mask_params.mask_height,\n mask_width=self._mask_params.mask_width,\n score_threshold=self._mask_params.score_threshold,\n densepose_class_index=densepose_class_index))\n postprocess_dict[\n fields.DetectionResultFields.detection_masks] = instance_masks\n if self._densepose_params:\n postprocess_dict[\n fields.DetectionResultFields.detection_surface_coords] = (\n surface_coords)\n\n if self._track_params:\n embeddings = self._postprocess_embeddings(prediction_dict,\n y_indices, x_indices)\n postprocess_dict.update({\n fields.DetectionResultFields.detection_embeddings: embeddings\n })\n\n if self._temporal_offset_params:\n offsets = prediction_tensors_to_temporal_offsets(\n y_indices, x_indices,\n prediction_dict[TEMPORAL_OFFSET][-1])\n postprocess_dict[fields.DetectionResultFields.detection_offsets] = offsets\n\n return postprocess_dict\n\n def _postprocess_embeddings(self, prediction_dict, y_indices, x_indices):\n \"\"\"Performs postprocessing on embedding predictions.\n\n Args:\n prediction_dict: a dictionary holding predicted tensors, returned from the\n predict() method. This dictionary should contain embedding prediction\n feature maps for tracking task.\n y_indices: A [batch_size, max_detections] int tensor with y indices for\n all object centers.\n x_indices: A [batch_size, max_detections] int tensor with x indices for\n all object centers.\n\n Returns:\n embeddings: A [batch_size, max_detection, reid_embed_size] float32\n tensor with L2 normalized embeddings extracted from detection box\n centers.\n \"\"\"\n embedding_predictions = prediction_dict[TRACK_REID][-1]\n embeddings = predicted_embeddings_at_object_centers(\n embedding_predictions, y_indices, x_indices)\n embeddings, _ = tf.linalg.normalize(embeddings, axis=-1)\n\n return embeddings\n\n def _postprocess_keypoints(self, prediction_dict, classes, y_indices,\n x_indices, boxes, num_detections):\n \"\"\"Performs postprocessing on keypoint predictions.\n\n Args:\n prediction_dict: a dictionary holding predicted tensors, returned from the\n predict() method. This dictionary should contain keypoint prediction\n feature maps for each keypoint task.\n classes: A [batch_size, max_detections] int tensor with class indices for\n all detected objects.\n y_indices: A [batch_size, max_detections] int tensor with y indices for\n all object centers.\n x_indices: A [batch_size, max_detections] int tensor with x indices for\n all object centers.\n boxes: A [batch_size, max_detections, 4] float32 tensor with bounding\n boxes in (un-normalized) output space.\n num_detections: A [batch_size] int tensor with the number of valid\n detections for each image.\n\n Returns:\n A tuple of\n keypoints: a [batch_size, max_detection, num_total_keypoints, 2] float32\n tensor with keypoints in the output (strided) coordinate frame.\n keypoint_scores: a [batch_size, max_detections, num_total_keypoints]\n float32 tensor with keypoint scores.\n \"\"\"\n total_num_keypoints = sum(len(kp_dict.keypoint_indices) for kp_dict\n in self._kp_params_dict.values())\n batch_size, max_detections, _ = _get_shape(boxes, 3)\n kpt_coords_for_example_list = []\n kpt_scores_for_example_list = []\n for ex_ind in range(batch_size):\n kpt_coords_for_class_list = []\n kpt_scores_for_class_list = []\n instance_inds_for_class_list = []\n for task_name, kp_params in self._kp_params_dict.items():\n keypoint_heatmap = prediction_dict[\n get_keypoint_name(task_name, KEYPOINT_HEATMAP)][-1]\n keypoint_offsets = prediction_dict[\n get_keypoint_name(task_name, KEYPOINT_OFFSET)][-1]\n keypoint_regression = prediction_dict[\n get_keypoint_name(task_name, KEYPOINT_REGRESSION)][-1]\n instance_inds = self._get_instance_indices(\n classes, num_detections, ex_ind, kp_params.class_id)\n\n def true_fn(\n keypoint_heatmap, keypoint_offsets, keypoint_regression,\n classes, y_indices, x_indices, boxes, instance_inds,\n ex_ind, kp_params):\n \"\"\"Logics to execute when instance_inds is not an empty set.\"\"\"\n # Postprocess keypoints and scores for class and single image. Shapes\n # are [1, num_instances_i, num_keypoints_i, 2] and\n # [1, num_instances_i, num_keypoints_i], respectively. Note that\n # num_instances_i and num_keypoints_i refers to the number of\n # instances and keypoints for class i, respectively.\n kpt_coords_for_class, kpt_scores_for_class = (\n self._postprocess_keypoints_for_class_and_image(\n keypoint_heatmap, keypoint_offsets, keypoint_regression,\n classes, y_indices, x_indices, boxes, instance_inds,\n ex_ind, kp_params))\n # Expand keypoint dimension (with padding) so that coordinates and\n # scores have shape [1, num_instances_i, num_total_keypoints, 2] and\n # [1, num_instances_i, num_total_keypoints], respectively.\n kpts_coords_for_class_padded, kpt_scores_for_class_padded = (\n _pad_to_full_keypoint_dim(\n kpt_coords_for_class, kpt_scores_for_class,\n kp_params.keypoint_indices, total_num_keypoints))\n return kpts_coords_for_class_padded, kpt_scores_for_class_padded\n\n def false_fn():\n \"\"\"Logics to execute when the instance_inds is an empty set.\"\"\"\n return (tf.zeros([1, 0, total_num_keypoints, 2], dtype=tf.float32),\n tf.zeros([1, 0, total_num_keypoints], dtype=tf.float32))\n\n true_fn = functools.partial(\n true_fn, keypoint_heatmap, keypoint_offsets, keypoint_regression,\n classes, y_indices, x_indices, boxes, instance_inds, ex_ind,\n kp_params)\n results = tf.cond(tf.size(instance_inds) > 0, true_fn, false_fn)\n\n kpt_coords_for_class_list.append(results[0])\n kpt_scores_for_class_list.append(results[1])\n instance_inds_for_class_list.append(instance_inds)\n\n # Concatenate all keypoints across all classes (single example).\n kpt_coords_for_example = tf.concat(kpt_coords_for_class_list, axis=1)\n kpt_scores_for_example = tf.concat(kpt_scores_for_class_list, axis=1)\n instance_inds_for_example = tf.concat(instance_inds_for_class_list,\n axis=0)\n\n if tf.size(instance_inds_for_example) > 0:\n # Scatter into tensor where instances align with original detection\n # instances. New shape of keypoint coordinates and scores are\n # [1, max_detections, num_total_keypoints, 2] and\n # [1, max_detections, num_total_keypoints], respectively.\n kpt_coords_for_example_all_det, kpt_scores_for_example_all_det = (\n _pad_to_full_instance_dim(\n kpt_coords_for_example, kpt_scores_for_example,\n instance_inds_for_example,\n self._center_params.max_box_predictions))\n else:\n kpt_coords_for_example_all_det = tf.zeros(\n [1, max_detections, total_num_keypoints, 2], dtype=tf.float32)\n kpt_scores_for_example_all_det = tf.zeros(\n [1, max_detections, total_num_keypoints], dtype=tf.float32)\n\n kpt_coords_for_example_list.append(kpt_coords_for_example_all_det)\n kpt_scores_for_example_list.append(kpt_scores_for_example_all_det)\n\n # Concatenate all keypoints and scores from all examples in the batch.\n # Shapes are [batch_size, max_detections, num_total_keypoints, 2] and\n # [batch_size, max_detections, num_total_keypoints], respectively.\n keypoints = tf.concat(kpt_coords_for_example_list, axis=0)\n keypoint_scores = tf.concat(kpt_scores_for_example_list, axis=0)\n\n return keypoints, keypoint_scores\n\n def _get_instance_indices(self, classes, num_detections, batch_index,\n class_id):\n \"\"\"Gets the instance indices that match the target class ID.\n\n Args:\n classes: A [batch_size, max_detections] int tensor with class indices for\n all detected objects.\n num_detections: A [batch_size] int tensor with the number of valid\n detections for each image.\n batch_index: An integer specifying the index for an example in the batch.\n class_id: Class id\n\n Returns:\n instance_inds: A [num_instances] int tensor where each element indicates\n the instance location within the `classes` tensor. This is useful to\n associate the refined keypoints with the original detections (i.e.\n boxes)\n \"\"\"\n classes = classes[batch_index:batch_index+1, ...]\n _, max_detections = shape_utils.combined_static_and_dynamic_shape(\n classes)\n # Get the detection indices corresponding to the target class.\n valid_detections_with_kpt_class = tf.math.logical_and(\n tf.range(max_detections) < num_detections[batch_index],\n classes[0] == class_id)\n instance_inds = tf.where(valid_detections_with_kpt_class)[:, 0]\n return instance_inds\n\n def _postprocess_keypoints_for_class_and_image(\n self, keypoint_heatmap, keypoint_offsets, keypoint_regression, classes,\n y_indices, x_indices, boxes, indices_with_kpt_class, batch_index,\n kp_params):\n \"\"\"Postprocess keypoints for a single image and class.\n\n This function performs the following postprocessing operations on a single\n image and single keypoint class:\n - Converts keypoints scores to range [0, 1] with sigmoid.\n - Determines the detections that correspond to the specified keypoint class.\n - Gathers the regressed keypoints at the detection (i.e. box) centers.\n - Gathers keypoint candidates from the keypoint heatmaps.\n - Snaps regressed keypoints to nearby keypoint candidates.\n\n Args:\n keypoint_heatmap: A [batch_size, height, width, num_keypoints] float32\n tensor with keypoint heatmaps.\n keypoint_offsets: A [batch_size, height, width, 2] float32 tensor with\n local offsets to keypoint centers.\n keypoint_regression: A [batch_size, height, width, 2 * num_keypoints]\n float32 tensor with regressed offsets to all keypoints.\n classes: A [batch_size, max_detections] int tensor with class indices for\n all detected objects.\n y_indices: A [batch_size, max_detections] int tensor with y indices for\n all object centers.\n x_indices: A [batch_size, max_detections] int tensor with x indices for\n all object centers.\n boxes: A [batch_size, max_detections, 4] float32 tensor with detected\n boxes in the output (strided) frame.\n indices_with_kpt_class: A [num_instances] int tensor where each element\n indicates the instance location within the `classes` tensor. This is\n useful to associate the refined keypoints with the original detections\n (i.e. boxes)\n batch_index: An integer specifying the index for an example in the batch.\n kp_params: A `KeypointEstimationParams` object with parameters for a\n single keypoint class.\n\n Returns:\n A tuple of\n refined_keypoints: A [1, num_instances, num_keypoints, 2] float32 tensor\n with refined keypoints for a single class in a single image, expressed\n in the output (strided) coordinate frame. Note that `num_instances` is a\n dynamic dimension, and corresponds to the number of valid detections\n for the specific class.\n refined_scores: A [1, num_instances, num_keypoints] float32 tensor with\n keypoint scores.\n \"\"\"\n keypoint_indices = kp_params.keypoint_indices\n num_keypoints = len(keypoint_indices)\n\n keypoint_heatmap = tf.nn.sigmoid(\n keypoint_heatmap[batch_index:batch_index+1, ...])\n keypoint_offsets = keypoint_offsets[batch_index:batch_index+1, ...]\n keypoint_regression = keypoint_regression[batch_index:batch_index+1, ...]\n y_indices = y_indices[batch_index:batch_index+1, ...]\n x_indices = x_indices[batch_index:batch_index+1, ...]\n\n # Gather the feature map locations corresponding to the object class.\n y_indices_for_kpt_class = tf.gather(y_indices, indices_with_kpt_class,\n axis=1)\n x_indices_for_kpt_class = tf.gather(x_indices, indices_with_kpt_class,\n axis=1)\n boxes_for_kpt_class = tf.gather(boxes, indices_with_kpt_class, axis=1)\n\n # Gather the regressed keypoints. Final tensor has shape\n # [1, num_instances, num_keypoints, 2].\n regressed_keypoints_for_objects = regressed_keypoints_at_object_centers(\n keypoint_regression, y_indices_for_kpt_class, x_indices_for_kpt_class)\n regressed_keypoints_for_objects = tf.reshape(\n regressed_keypoints_for_objects, [1, -1, num_keypoints, 2])\n\n # Get the candidate keypoints and scores.\n # The shape of keypoint_candidates and keypoint_scores is:\n # [1, num_candidates_per_keypoint, num_keypoints, 2] and\n # [1, num_candidates_per_keypoint, num_keypoints], respectively.\n keypoint_candidates, keypoint_scores, num_keypoint_candidates = (\n prediction_tensors_to_keypoint_candidates(\n keypoint_heatmap, keypoint_offsets,\n keypoint_score_threshold=(\n kp_params.keypoint_candidate_score_threshold),\n max_pool_kernel_size=kp_params.peak_max_pool_kernel_size,\n max_candidates=kp_params.num_candidates_per_keypoint))\n\n # Get the refined keypoints and scores, of shape\n # [1, num_instances, num_keypoints, 2] and\n # [1, num_instances, num_keypoints], respectively.\n refined_keypoints, refined_scores = refine_keypoints(\n regressed_keypoints_for_objects, keypoint_candidates, keypoint_scores,\n num_keypoint_candidates, bboxes=boxes_for_kpt_class,\n unmatched_keypoint_score=kp_params.unmatched_keypoint_score,\n box_scale=kp_params.box_scale,\n candidate_search_scale=kp_params.candidate_search_scale,\n candidate_ranking_mode=kp_params.candidate_ranking_mode)\n\n return refined_keypoints, refined_scores\n\n def regularization_losses(self):\n return []\n\n def restore_map(self,\n fine_tune_checkpoint_type='detection',\n load_all_detection_checkpoint_vars=False):\n raise RuntimeError('CenterNetMetaArch not supported under TF1.x.')\n\n def restore_from_objects(self, fine_tune_checkpoint_type='detection'):\n \"\"\"Returns a map of Trackable objects to load from a foreign checkpoint.\n\n Returns a dictionary of Tensorflow 2 Trackable objects (e.g. tf.Module\n or Checkpoint). This enables the model to initialize based on weights from\n another task. For example, the feature extractor variables from a\n classification model can be used to bootstrap training of an object\n detector. When loading from an object detection model, the checkpoint model\n should have the same parameters as this detection model with exception of\n the num_classes parameter.\n\n Note that this function is intended to be used to restore Keras-based\n models when running Tensorflow 2, whereas restore_map (not implemented\n in CenterNet) is intended to be used to restore Slim-based models when\n running Tensorflow 1.x.\n\n TODO(jonathanhuang): Make this function consistent with other\n meta-architectures.\n\n Args:\n fine_tune_checkpoint_type: whether to restore from a full detection\n checkpoint (with compatible variable names) or to restore from a\n classification checkpoint for initialization prior to training.\n Valid values: `detection`, `classification`, `fine_tune`.\n Default 'detection'.\n 'detection': used when loading models pre-trained on other detection\n tasks. With this checkpoint type the weights of the feature extractor\n are expected under the attribute 'feature_extractor'.\n 'classification': used when loading models pre-trained on an image\n classification task. Note that only the encoder section of the network\n is loaded and not the upsampling layers. With this checkpoint type,\n the weights of only the encoder section are expected under the\n attribute 'feature_extractor'.\n 'fine_tune': used when loading the entire CenterNet feature extractor\n pre-trained on other tasks. The checkpoints saved during CenterNet\n model training can be directly loaded using this type. With this\n checkpoint type, the weights of the feature extractor are expected\n under the attribute 'model._feature_extractor'.\n For more details, see the tensorflow section on Loading mechanics.\n https://www.tensorflow.org/guide/checkpoint#loading_mechanics\n\n Returns:\n A dict mapping keys to Trackable objects (tf.Module or Checkpoint).\n \"\"\"\n\n supported_types = self._feature_extractor.supported_sub_model_types\n supported_types += ['fine_tune']\n\n if fine_tune_checkpoint_type not in supported_types:\n message = ('Checkpoint type \"{}\" not supported for {}. '\n 'Supported types are {}')\n raise ValueError(\n message.format(fine_tune_checkpoint_type,\n self._feature_extractor.__class__.__name__,\n supported_types))\n\n elif fine_tune_checkpoint_type == 'fine_tune':\n feature_extractor_model = tf.train.Checkpoint(\n _feature_extractor=self._feature_extractor)\n return {'model': feature_extractor_model}\n\n else:\n return {'feature_extractor': self._feature_extractor.get_sub_model(\n fine_tune_checkpoint_type)}\n\n def updates(self):\n raise RuntimeError('This model is intended to be used with model_lib_v2 '\n 'which does not support updates()')\n",
"# Lint as: python3\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\"\"\"Training utils.\"\"\"\n\nimport json\nimport os\nimport pprint\nfrom typing import Any, List\n\nfrom absl import logging\nimport dataclasses\nimport orbit\nimport tensorflow as tf\n\nfrom official.core import base_task\nfrom official.core import base_trainer\nfrom official.core import exp_factory\nfrom official.modeling import hyperparams\nfrom official.modeling.hyperparams import config_definitions\n\n\ndef create_trainer(\n params: config_definitions.ExperimentConfig,\n task: base_task.Task,\n model_dir: str,\n train: bool,\n evaluate: bool,\n checkpoint_exporter: Any = None):\n \"\"\"Create trainer.\"\"\"\n del model_dir\n logging.info('Running default trainer.')\n trainer = base_trainer.Trainer(\n params, task, train=train, evaluate=evaluate,\n checkpoint_exporter=checkpoint_exporter)\n return trainer\n\n\[email protected]\nclass ParseConfigOptions:\n \"\"\"Use this dataclass instead of FLAGS to customize parse_configuration().\"\"\"\n experiment: str\n config_file: List[str]\n tpu: str = ''\n tf_data_service: str = ''\n params_override: str = ''\n\n\ndef parse_configuration(flags_obj):\n \"\"\"Parses ExperimentConfig from flags.\"\"\"\n\n # 1. Get the default config from the registered experiment.\n params = exp_factory.get_exp_config(flags_obj.experiment)\n\n # 2. Get the first level of override from `--config_file`.\n # `--config_file` is typically used as a template that specifies the common\n # override for a particular experiment.\n for config_file in flags_obj.config_file or []:\n params = hyperparams.override_params_dict(\n params, config_file, is_strict=True)\n\n # 3. Override the TPU address and tf.data service address.\n params.override({\n 'runtime': {\n 'tpu': flags_obj.tpu,\n },\n 'task': {\n 'train_data': {\n 'tf_data_service_address': flags_obj.tf_data_service,\n },\n 'validation_data': {\n 'tf_data_service_address': flags_obj.tf_data_service,\n }\n }\n })\n\n # 4. Get the second level of override from `--params_override`.\n # `--params_override` is typically used as a further override over the\n # template. For example, one may define a particular template for training\n # ResNet50 on ImageNet in a config file and pass it via `--config_file`,\n # then define different learning rates and pass it via `--params_override`.\n if flags_obj.params_override:\n params = hyperparams.override_params_dict(\n params, flags_obj.params_override, is_strict=True)\n\n params.validate()\n params.lock()\n\n pp = pprint.PrettyPrinter()\n logging.info('Final experiment parameters: %s', pp.pformat(params.as_dict()))\n\n return params\n\n\ndef serialize_config(params: config_definitions.ExperimentConfig,\n model_dir: str):\n \"\"\"Serializes and saves the experiment config.\"\"\"\n params_save_path = os.path.join(model_dir, 'params.yaml')\n logging.info('Saving experiment configuration to %s', params_save_path)\n tf.io.gfile.makedirs(model_dir)\n hyperparams.save_params_dict_to_yaml(params, params_save_path)\n\n\ndef read_global_step_from_checkpoint(ckpt_file_path):\n \"\"\"Read global step from checkpoint, or get global step from its filename.\"\"\"\n global_step = tf.Variable(-1, dtype=tf.int64)\n ckpt = tf.train.Checkpoint(global_step=global_step)\n try:\n ckpt.restore(ckpt_file_path).expect_partial()\n global_step_maybe_restored = global_step.numpy()\n except tf.errors.InvalidArgumentError:\n global_step_maybe_restored = -1\n\n if global_step_maybe_restored == -1:\n raise ValueError('global_step not found in checkpoint {}. '\n 'If you want to run finetune eval jobs, you need to '\n 'make sure that your pretrain model writes '\n 'global_step in its checkpoints.'.format(ckpt_file_path))\n global_step_restored = global_step.numpy()\n logging.info('get global_step %d from checkpoint %s',\n global_step_restored, ckpt_file_path)\n return global_step_restored\n\n\ndef write_json_summary(log_dir, global_step, eval_metrics):\n \"\"\"Dump evaluation metrics to json file.\"\"\"\n serializable_dict = {}\n for name, value in eval_metrics.items():\n if hasattr(value, 'numpy'):\n serializable_dict[name] = str(value.numpy())\n else:\n serializable_dict[name] = str(value)\n output_json = os.path.join(log_dir, 'metrics-{}.json'.format(global_step))\n logging.info('Evaluation results at pretrain step %d: %s',\n global_step, serializable_dict)\n with tf.io.gfile.GFile(output_json, 'w') as writer:\n writer.write(json.dumps(serializable_dict, indent=4) + '\\n')\n\n\ndef write_summary(summary_writer, global_step, eval_metrics):\n \"\"\"Write evaluation metrics to TF summary.\"\"\"\n numeric_dict = {}\n for name, value in eval_metrics.items():\n numeric_dict[name] = float(orbit.utils.get_value(value))\n with summary_writer.as_default():\n for name, value in numeric_dict.items():\n tf.summary.scalar(name, value, step=global_step)\n summary_writer.flush()\n\n\ndef remove_ckpts(model_dir):\n \"\"\"Remove model checkpoints, so we can restart.\"\"\"\n ckpts = os.path.join(model_dir, 'ckpt-*')\n logging.info('removing checkpoint files %s', ckpts)\n for file_to_remove in tf.io.gfile.glob(ckpts):\n tf.io.gfile.rmtree(file_to_remove)\n\n file_to_remove = os.path.join(model_dir, 'checkpoint')\n if tf.io.gfile.exists(file_to_remove):\n tf.io.gfile.remove(file_to_remove)\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\"\"\"MobileBERT text encoder network.\"\"\"\nimport gin\nimport tensorflow as tf\n\nfrom official.nlp import keras_nlp\nfrom official.nlp.modeling import layers\n\n\nclass NoNorm(tf.keras.layers.Layer):\n \"\"\"Apply element-wise linear transformation to the last dimension.\"\"\"\n\n def __init__(self, name=None):\n super(NoNorm, self).__init__(name=name)\n\n def build(self, shape):\n kernal_size = shape[-1]\n self.bias = self.add_weight('beta',\n shape=[kernal_size],\n initializer='zeros')\n self.scale = self.add_weight('gamma',\n shape=[kernal_size],\n initializer='ones')\n\n def call(self, feature):\n output = feature * self.scale + self.bias\n return output\n\n\ndef _get_norm_layer(normalization_type='no_norm', name=None):\n \"\"\"Get normlization layer.\n\n Arguments:\n normalization_type: String. The type of normalization_type, only\n 'no_norm' and 'layer_norm' are supported.\n name: Name for the norm layer.\n\n Returns:\n layer norm class.\n \"\"\"\n if normalization_type == 'no_norm':\n layer = NoNorm(name=name)\n elif normalization_type == 'layer_norm':\n layer = tf.keras.layers.LayerNormalization(\n name=name,\n axis=-1,\n epsilon=1e-12,\n dtype=tf.float32)\n else:\n raise NotImplementedError('Only \"no_norm\" and \"layer_norm\" and supported.')\n return layer\n\n\nclass MobileBertEmbedding(tf.keras.layers.Layer):\n \"\"\"Performs an embedding lookup for MobileBERT.\n\n This layer includes word embedding, token type embedding, position embedding.\n \"\"\"\n\n def __init__(self,\n word_vocab_size,\n word_embed_size,\n type_vocab_size,\n output_embed_size,\n max_sequence_length=512,\n normalization_type='no_norm',\n initializer=tf.keras.initializers.TruncatedNormal(stddev=0.02),\n dropout_rate=0.1):\n \"\"\"Class initialization.\n\n Arguments:\n word_vocab_size: Number of words in the vocabulary.\n word_embed_size: Word embedding size.\n type_vocab_size: Number of word types.\n output_embed_size: Embedding size for the final embedding output.\n max_sequence_length: Maximum length of input sequence.\n normalization_type: String. The type of normalization_type, only\n 'no_norm' and 'layer_norm' are supported.\n initializer: The initializer to use for the embedding weights and\n linear projection weights.\n dropout_rate: Dropout rate.\n \"\"\"\n super(MobileBertEmbedding, self).__init__()\n self.word_vocab_size = word_vocab_size\n self.word_embed_size = word_embed_size\n self.type_vocab_size = type_vocab_size\n self.output_embed_size = output_embed_size\n self.max_sequence_length = max_sequence_length\n self.dropout_rate = dropout_rate\n\n self.word_embedding = keras_nlp.layers.OnDeviceEmbedding(\n self.word_vocab_size,\n self.word_embed_size,\n initializer=initializer,\n name='word_embedding')\n self.type_embedding = keras_nlp.layers.OnDeviceEmbedding(\n self.type_vocab_size,\n self.output_embed_size,\n use_one_hot=True,\n initializer=initializer,\n name='type_embedding')\n self.pos_embedding = keras_nlp.layers.PositionEmbedding(\n max_length=max_sequence_length,\n initializer=initializer,\n name='position_embedding')\n self.word_embedding_proj = tf.keras.layers.experimental.EinsumDense(\n 'abc,cd->abd',\n output_shape=[None, self.output_embed_size],\n kernel_initializer=initializer,\n bias_axes='d',\n name='embedding_projection')\n self.layer_norm = _get_norm_layer(normalization_type, 'embedding_norm')\n self.dropout_layer = tf.keras.layers.Dropout(\n self.dropout_rate,\n name='embedding_dropout')\n\n def call(self, input_ids, token_type_ids=None, training=False):\n word_embedding_out = self.word_embedding(input_ids)\n word_embedding_out = tf.concat(\n [tf.pad(word_embedding_out[:, 1:], ((0, 0), (0, 1), (0, 0))),\n word_embedding_out,\n tf.pad(word_embedding_out[:, :-1], ((0, 0), (1, 0), (0, 0)))],\n axis=2)\n word_embedding_out = self.word_embedding_proj(word_embedding_out)\n\n pos_embedding_out = self.pos_embedding(word_embedding_out)\n embedding_out = word_embedding_out + pos_embedding_out\n if token_type_ids is not None:\n type_embedding_out = self.type_embedding(token_type_ids)\n embedding_out += type_embedding_out\n embedding_out = self.layer_norm(embedding_out)\n embedding_out = self.dropout_layer(embedding_out, training=training)\n\n return embedding_out\n\n\nclass TransformerLayer(tf.keras.layers.Layer):\n \"\"\"Transformer block for MobileBERT.\n\n An implementation of one layer (block) of Transformer with bottleneck and\n inverted-bottleneck for MobilerBERT.\n\n Original paper for MobileBERT:\n https://arxiv.org/pdf/2004.02984.pdf\n \"\"\"\n\n def __init__(self,\n hidden_size=512,\n num_attention_heads=4,\n intermediate_size=512,\n intermediate_act_fn='relu',\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n intra_bottleneck_size=128,\n key_query_shared_bottleneck=True,\n num_feedforward_networks=4,\n normalization_type='no_norm',\n initializer=tf.keras.initializers.TruncatedNormal(stddev=0.02),\n name=None):\n \"\"\"Class initialization.\n\n Arguments:\n hidden_size: Hidden size for the Transformer input and output tensor.\n num_attention_heads: Number of attention heads in the Transformer.\n intermediate_size: The size of the \"intermediate\" (a.k.a., feed\n forward) layer.\n intermediate_act_fn: The non-linear activation function to apply\n to the output of the intermediate/feed-forward layer.\n hidden_dropout_prob: Dropout probability for the hidden layers.\n attention_probs_dropout_prob: Dropout probability of the attention\n probabilities.\n intra_bottleneck_size: Size of bottleneck.\n key_query_shared_bottleneck: Whether to share linear transformation for\n keys and queries.\n num_feedforward_networks: Number of stacked feed-forward networks.\n normalization_type: The type of normalization_type, only 'no_norm' and\n 'layer_norm' are supported. 'no_norm' represents the element-wise\n linear transformation for the student model, as suggested by the\n original MobileBERT paper. 'layer_norm' is used for the teacher model.\n initializer: The initializer to use for the embedding weights and\n linear projection weights.\n name: A string represents the layer name.\n\n Raises:\n ValueError: A Tensor shape or parameter is invalid.\n \"\"\"\n super(TransformerLayer, self).__init__(name=name)\n self.hidden_size = hidden_size\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.intermediate_act_fn = intermediate_act_fn\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.intra_bottleneck_size = intra_bottleneck_size\n self.key_query_shared_bottleneck = key_query_shared_bottleneck\n self.num_feedforward_networks = num_feedforward_networks\n self.normalization_type = normalization_type\n\n if intra_bottleneck_size % num_attention_heads != 0:\n raise ValueError(\n (f'The bottleneck size {intra_bottleneck_size} is not a multiple '\n f'of the number of attention heads {num_attention_heads}.'))\n attention_head_size = int(intra_bottleneck_size / num_attention_heads)\n\n self.block_layers = {}\n # add input bottleneck\n dense_layer_2d = tf.keras.layers.experimental.EinsumDense(\n 'abc,cd->abd',\n output_shape=[None, self.intra_bottleneck_size],\n bias_axes='d',\n kernel_initializer=initializer,\n name='bottleneck_input/dense')\n layer_norm = _get_norm_layer(self.normalization_type,\n name='bottleneck_input/norm')\n self.block_layers['bottleneck_input'] = [dense_layer_2d,\n layer_norm]\n\n if self.key_query_shared_bottleneck:\n dense_layer_2d = tf.keras.layers.experimental.EinsumDense(\n 'abc,cd->abd',\n output_shape=[None, self.intra_bottleneck_size],\n bias_axes='d',\n kernel_initializer=initializer,\n name='kq_shared_bottleneck/dense')\n layer_norm = _get_norm_layer(self.normalization_type,\n name='kq_shared_bottleneck/norm')\n self.block_layers['kq_shared_bottleneck'] = [dense_layer_2d,\n layer_norm]\n\n # add attention layer\n attention_layer = tf.keras.layers.MultiHeadAttention(\n num_heads=self.num_attention_heads,\n key_dim=attention_head_size,\n value_dim=attention_head_size,\n dropout=self.attention_probs_dropout_prob,\n output_shape=self.intra_bottleneck_size,\n kernel_initializer=initializer,\n name='attention')\n layer_norm = _get_norm_layer(self.normalization_type,\n name='attention/norm')\n self.block_layers['attention'] = [attention_layer,\n layer_norm]\n\n # add stacked feed-forward networks\n self.block_layers['ffn'] = []\n for ffn_layer_idx in range(self.num_feedforward_networks):\n layer_prefix = f'ffn_layer_{ffn_layer_idx}'\n layer_name = layer_prefix + '/intermediate_dense'\n intermediate_layer = tf.keras.layers.experimental.EinsumDense(\n 'abc,cd->abd',\n activation=self.intermediate_act_fn,\n output_shape=[None, self.intermediate_size],\n bias_axes='d',\n kernel_initializer=initializer,\n name=layer_name)\n layer_name = layer_prefix + '/output_dense'\n output_layer = tf.keras.layers.experimental.EinsumDense(\n 'abc,cd->abd',\n output_shape=[None, self.intra_bottleneck_size],\n bias_axes='d',\n kernel_initializer=initializer,\n name=layer_name)\n layer_name = layer_prefix + '/norm'\n layer_norm = _get_norm_layer(self.normalization_type,\n name=layer_name)\n self.block_layers['ffn'].append([intermediate_layer,\n output_layer,\n layer_norm])\n\n # add output bottleneck\n bottleneck = tf.keras.layers.experimental.EinsumDense(\n 'abc,cd->abd',\n output_shape=[None, self.hidden_size],\n activation=None,\n bias_axes='d',\n kernel_initializer=initializer,\n name='bottleneck_output/dense')\n dropout_layer = tf.keras.layers.Dropout(\n self.hidden_dropout_prob,\n name='bottleneck_output/dropout')\n layer_norm = _get_norm_layer(self.normalization_type,\n name='bottleneck_output/norm')\n self.block_layers['bottleneck_output'] = [bottleneck,\n dropout_layer,\n layer_norm]\n\n def call(self,\n input_tensor,\n attention_mask=None,\n training=False,\n return_attention_scores=False):\n \"\"\"Implementes the forward pass.\n\n Arguments:\n input_tensor: Float tensor of shape [batch_size, seq_length, hidden_size].\n attention_mask: (optional) int32 tensor of shape [batch_size, seq_length,\n seq_length], with 1 for positions that can be attended to and 0 in\n positions that should not be.\n training: If the model is in training mode.\n return_attention_scores: If return attention score.\n\n Returns:\n layer_output: Float tensor of shape [batch_size, seq_length, hidden_size].\n attention_scores (Optional): Only when return_attention_scores is True.\n\n Raises:\n ValueError: A Tensor shape or parameter is invalid.\n \"\"\"\n input_width = input_tensor.shape.as_list()[-1]\n if input_width != self.hidden_size:\n raise ValueError(\n (f'The width of the input tensor {input_width} != '\n f'hidden size {self.hidden_size}'))\n\n prev_output = input_tensor\n\n # input bottleneck\n dense_layer = self.block_layers['bottleneck_input'][0]\n layer_norm = self.block_layers['bottleneck_input'][1]\n layer_input = dense_layer(prev_output)\n layer_input = layer_norm(layer_input)\n\n if self.key_query_shared_bottleneck:\n dense_layer = self.block_layers['kq_shared_bottleneck'][0]\n layer_norm = self.block_layers['kq_shared_bottleneck'][1]\n shared_attention_input = dense_layer(prev_output)\n shared_attention_input = layer_norm(shared_attention_input)\n key_tensor = shared_attention_input\n query_tensor = shared_attention_input\n value_tensor = prev_output\n else:\n key_tensor = layer_input\n query_tensor = layer_input\n value_tensor = layer_input\n\n # attention layer\n attention_layer = self.block_layers['attention'][0]\n layer_norm = self.block_layers['attention'][1]\n attention_output, attention_scores = attention_layer(\n query_tensor,\n value_tensor,\n key_tensor,\n attention_mask,\n return_attention_scores=True,\n training=training\n )\n attention_output = layer_norm(attention_output + layer_input)\n\n # stacked feed-forward networks\n layer_input = attention_output\n for ffn_idx in range(self.num_feedforward_networks):\n intermediate_layer = self.block_layers['ffn'][ffn_idx][0]\n output_layer = self.block_layers['ffn'][ffn_idx][1]\n layer_norm = self.block_layers['ffn'][ffn_idx][2]\n intermediate_output = intermediate_layer(layer_input)\n layer_output = output_layer(intermediate_output)\n layer_output = layer_norm(layer_output + layer_input)\n layer_input = layer_output\n\n # output bottleneck\n bottleneck = self.block_layers['bottleneck_output'][0]\n dropout_layer = self.block_layers['bottleneck_output'][1]\n layer_norm = self.block_layers['bottleneck_output'][2]\n layer_output = bottleneck(layer_output)\n layer_output = dropout_layer(layer_output, training=training)\n layer_output = layer_norm(layer_output + prev_output)\n\n if return_attention_scores:\n return layer_output, attention_scores\n else:\n return layer_output\n\n\[email protected]\nclass MobileBERTEncoder(tf.keras.Model):\n \"\"\"A Keras functional API implementation for MobileBERT encoder.\"\"\"\n\n def __init__(self,\n word_vocab_size=30522,\n word_embed_size=128,\n type_vocab_size=2,\n max_sequence_length=512,\n num_blocks=24,\n hidden_size=512,\n num_attention_heads=4,\n intermediate_size=512,\n intermediate_act_fn='relu',\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n intra_bottleneck_size=128,\n initializer_range=0.02,\n key_query_shared_bottleneck=True,\n num_feedforward_networks=4,\n normalization_type='no_norm',\n classifier_activation=False,\n **kwargs):\n \"\"\"Class initialization.\n\n Arguments:\n word_vocab_size: Number of words in the vocabulary.\n word_embed_size: Word embedding size.\n type_vocab_size: Number of word types.\n max_sequence_length: Maximum length of input sequence.\n num_blocks: Number of transformer block in the encoder model.\n hidden_size: Hidden size for the transformer block.\n num_attention_heads: Number of attention heads in the transformer block.\n intermediate_size: The size of the \"intermediate\" (a.k.a., feed\n forward) layer.\n intermediate_act_fn: The non-linear activation function to apply\n to the output of the intermediate/feed-forward layer.\n hidden_dropout_prob: Dropout probability for the hidden layers.\n attention_probs_dropout_prob: Dropout probability of the attention\n probabilities.\n intra_bottleneck_size: Size of bottleneck.\n initializer_range: The stddev of the truncated_normal_initializer for\n initializing all weight matrices.\n key_query_shared_bottleneck: Whether to share linear transformation for\n keys and queries.\n num_feedforward_networks: Number of stacked feed-forward networks.\n normalization_type: The type of normalization_type, only 'no_norm' and\n 'layer_norm' are supported. 'no_norm' represents the element-wise linear\n transformation for the student model, as suggested by the original\n MobileBERT paper. 'layer_norm' is used for the teacher model.\n classifier_activation: If using the tanh activation for the final\n representation of the [CLS] token in fine-tuning.\n **kwargs: Other keyworded and arguments.\n \"\"\"\n self._self_setattr_tracking = False\n initializer = tf.keras.initializers.TruncatedNormal(\n stddev=initializer_range)\n\n # layer instantiation\n self.embedding_layer = MobileBertEmbedding(\n word_vocab_size=word_vocab_size,\n word_embed_size=word_embed_size,\n type_vocab_size=type_vocab_size,\n output_embed_size=hidden_size,\n max_sequence_length=max_sequence_length,\n normalization_type=normalization_type,\n initializer=initializer,\n dropout_rate=hidden_dropout_prob)\n\n self._transformer_layers = []\n for layer_idx in range(num_blocks):\n transformer = TransformerLayer(\n hidden_size=hidden_size,\n num_attention_heads=num_attention_heads,\n intermediate_size=intermediate_size,\n intermediate_act_fn=intermediate_act_fn,\n hidden_dropout_prob=hidden_dropout_prob,\n attention_probs_dropout_prob=attention_probs_dropout_prob,\n intra_bottleneck_size=intra_bottleneck_size,\n key_query_shared_bottleneck=key_query_shared_bottleneck,\n num_feedforward_networks=num_feedforward_networks,\n normalization_type=normalization_type,\n initializer=initializer,\n name=f'transformer_layer_{layer_idx}')\n self._transformer_layers.append(transformer)\n\n # input tensor\n input_ids = tf.keras.layers.Input(\n shape=(None,), dtype=tf.int32, name='input_word_ids')\n input_mask = tf.keras.layers.Input(\n shape=(None,), dtype=tf.int32, name='input_mask')\n type_ids = tf.keras.layers.Input(\n shape=(None,), dtype=tf.int32, name='input_type_ids')\n self.inputs = [input_ids, input_mask, type_ids]\n attention_mask = layers.SelfAttentionMask()([input_ids, input_mask])\n\n # build the computation graph\n all_layer_outputs = []\n all_attention_scores = []\n embedding_output = self.embedding_layer(input_ids, type_ids)\n all_layer_outputs.append(embedding_output)\n prev_output = embedding_output\n\n for layer_idx in range(num_blocks):\n layer_output, attention_score = self._transformer_layers[layer_idx](\n prev_output,\n attention_mask,\n return_attention_scores=True)\n all_layer_outputs.append(layer_output)\n all_attention_scores.append(attention_score)\n prev_output = layer_output\n first_token = tf.squeeze(prev_output[:, 0:1, :], axis=1)\n\n if classifier_activation:\n self._pooler_layer = tf.keras.layers.experimental.EinsumDense(\n 'ab,bc->ac',\n output_shape=hidden_size,\n activation=tf.tanh,\n bias_axes='c',\n kernel_initializer=initializer,\n name='pooler')\n first_token = self._pooler_layer(first_token)\n else:\n self._pooler_layer = None\n\n outputs = dict(\n sequence_output=prev_output,\n pooled_output=first_token,\n encoder_outputs=all_layer_outputs,\n attention_scores=all_attention_scores)\n\n super(MobileBERTEncoder, self).__init__(\n inputs=self.inputs, outputs=outputs, **kwargs)\n\n def get_embedding_table(self):\n return self.embedding_layer.word_embedding.embeddings\n\n def get_embedding_layer(self):\n return self.embedding_layer.word_embedding\n\n @property\n def transformer_layers(self):\n \"\"\"List of Transformer layers in the encoder.\"\"\"\n return self._transformer_layers\n\n @property\n def pooler_layer(self):\n \"\"\"The pooler dense layer after the transformer layers.\"\"\"\n return self._pooler_layer\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 box_ops.py.\"\"\"\n\n# Import libraries\nimport numpy as np\nimport tensorflow as tf\n\nfrom official.vision.beta.ops import box_ops\n\n\ndef _transform_boxes_on_tpu_and_cpu(transform_fn, boxes, *args):\n # Runs on TPU.\n strategy = tf.distribute.experimental.TPUStrategy()\n with strategy.scope():\n transformed_op_tpu = transform_fn(boxes, *args)\n transfomred_boxes_tpu = tf.nest.map_structure(lambda x: x.numpy(),\n transformed_op_tpu)\n\n # Runs on CPU.\n transfomred_op_cpu = transform_fn(boxes, *args)\n transfomred_boxes_cpu = tf.nest.map_structure(lambda x: x.numpy(),\n transfomred_op_cpu)\n return transfomred_boxes_tpu, transfomred_boxes_cpu\n\n\nclass ConvertBoxesTest(tf.test.TestCase):\n\n def testConvertBoxes(self):\n # y1, x1, y2, x2.\n boxes = np.array([[0, 0, 1, 2], [0.2, 0.1, 1.2, 1.1]])\n # x1, y1, width, height\n target = np.array([[0, 0, 2, 1], [0.1, 0.2, 1, 1]])\n outboxes = box_ops.yxyx_to_xywh(boxes)\n self.assertNDArrayNear(outboxes, target, 1e-7)\n\n\nclass JitterBoxesTest(tf.test.TestCase):\n\n def testJitterBoxes(self):\n boxes_data = [[0, 0, 1, 1], [0, 0.1, 1, 1.1], [0, 0.3, 1, 1.3],\n [0, 0.5, 1, 1.5], [0, 0.7, 1, 1.7], [0, 1.9, 1, 1.9]]\n boxes_np = np.array(boxes_data, dtype=np.float32)\n max_size = max(\n np.amax(boxes_np[:, 3] - boxes_np[:, 1]),\n np.amax(boxes_np[:, 2] - boxes_np[:, 0]))\n noise_scale = 0.025\n boxes = tf.constant(boxes_np)\n\n def jitter_fn(input_boxes, arg_noise_scale):\n return box_ops.jitter_boxes(input_boxes, arg_noise_scale)\n\n jittered_boxes_tpu, jittered_boxes_cpu = _transform_boxes_on_tpu_and_cpu(\n jitter_fn, boxes, noise_scale)\n\n # Test that the jittered box is within 10 stds from the inputs.\n self.assertNDArrayNear(jittered_boxes_tpu, boxes_np,\n noise_scale * max_size * 10)\n self.assertNDArrayNear(jittered_boxes_cpu, boxes_np,\n noise_scale * max_size * 10)\n\n\nclass NormalizeBoxesTest(tf.test.TestCase):\n\n def testNormalizeBoxes1DWithImageShapeAsList(self):\n boxes = tf.constant([10, 30, 40, 90], tf.float32)\n image_shape = [50, 100]\n\n normalized_boxes_tpu, normalized_boxes_cpu = (\n _transform_boxes_on_tpu_and_cpu(\n box_ops.normalize_boxes, boxes, image_shape))\n\n self.assertNDArrayNear(normalized_boxes_tpu, normalized_boxes_cpu, 1e-5)\n self.assertNDArrayNear(normalized_boxes_tpu, [0.2, 0.3, 0.8, 0.9], 1e-5)\n\n def testNormalizeBoxes1DWithImageShapeAsTensor(self):\n boxes = tf.constant([10, 30, 40, 90], tf.float32)\n image_shape = tf.constant([50, 100], tf.int32)\n\n normalized_boxes_tpu, normalized_boxes_cpu = (\n _transform_boxes_on_tpu_and_cpu(\n box_ops.normalize_boxes, boxes, image_shape))\n\n self.assertNDArrayNear(normalized_boxes_tpu, normalized_boxes_cpu, 1e-5)\n self.assertNDArrayNear(normalized_boxes_tpu, [0.2, 0.3, 0.8, 0.9], 1e-5)\n\n def testNormalizeBoxes2DWithImageShapeAsList(self):\n boxes = tf.constant([[10, 30, 40, 90], [30, 10, 40, 50]], tf.float32)\n image_shape = [50, 100]\n\n normalized_boxes_tpu, normalized_boxes_cpu = (\n _transform_boxes_on_tpu_and_cpu(\n box_ops.normalize_boxes, boxes, image_shape))\n\n self.assertNDArrayNear(normalized_boxes_tpu, normalized_boxes_cpu, 1e-5)\n self.assertNDArrayNear(normalized_boxes_tpu,\n [[0.2, 0.3, 0.8, 0.9], [0.6, 0.1, 0.8, 0.5]], 1e-5)\n\n def testNormalizeBoxes2DWithImageShapeAsVector(self):\n boxes = tf.constant([[10, 30, 40, 90], [30, 10, 40, 50]], tf.float32)\n image_shape = tf.constant([50, 100], dtype=tf.int32)\n\n normalized_boxes_tpu, normalized_boxes_cpu = (\n _transform_boxes_on_tpu_and_cpu(\n box_ops.normalize_boxes, boxes, image_shape))\n\n self.assertNDArrayNear(normalized_boxes_tpu, normalized_boxes_cpu, 1e-5)\n self.assertNDArrayNear(normalized_boxes_tpu,\n [[0.2, 0.3, 0.8, 0.9], [0.6, 0.1, 0.8, 0.5]], 1e-5)\n\n def testNormalizeBoxes2DWithImageShapeAsBroadcastableTensor(self):\n boxes = tf.constant([[10, 30, 40, 90], [30, 10, 40, 50]], tf.float32)\n image_shape = tf.constant([[50, 100]], tf.int32)\n\n normalized_boxes_tpu, normalized_boxes_cpu = (\n _transform_boxes_on_tpu_and_cpu(\n box_ops.normalize_boxes, boxes, image_shape))\n\n self.assertNDArrayNear(normalized_boxes_tpu, normalized_boxes_cpu, 1e-5)\n self.assertNDArrayNear(normalized_boxes_tpu,\n [[0.2, 0.3, 0.8, 0.9], [0.6, 0.1, 0.8, 0.5]], 1e-5)\n\n def testNormalizeBoxes2DWithImageShapeAsSameShapeTensor(self):\n boxes = tf.constant([[10, 30, 40, 90], [30, 10, 40, 50]], tf.float32)\n image_shape = tf.constant([[50, 100], [50, 100]], tf.int32)\n\n normalized_boxes_tpu, normalized_boxes_cpu = (\n _transform_boxes_on_tpu_and_cpu(\n box_ops.normalize_boxes, boxes, image_shape))\n\n self.assertNDArrayNear(normalized_boxes_tpu, normalized_boxes_cpu, 1e-5)\n self.assertNDArrayNear(normalized_boxes_tpu,\n [[0.2, 0.3, 0.8, 0.9], [0.6, 0.1, 0.8, 0.5]], 1e-5)\n\n def testNormalizeBoxes3DWithImageShapeAsList(self):\n boxes = tf.constant([[[10, 30, 40, 90], [30, 10, 40, 50]],\n [[20, 40, 50, 80], [30, 50, 40, 90]]], tf.float32)\n image_shape = [50, 100]\n\n normalized_boxes_tpu, normalized_boxes_cpu = (\n _transform_boxes_on_tpu_and_cpu(\n box_ops.normalize_boxes, boxes, image_shape))\n\n self.assertNDArrayNear(normalized_boxes_tpu, normalized_boxes_cpu, 1e-5)\n self.assertNDArrayNear(normalized_boxes_tpu,\n [[[0.2, 0.3, 0.8, 0.9], [0.6, 0.1, 0.8, 0.5]],\n [[0.4, 0.4, 1.0, 0.8], [0.6, 0.5, 0.8, 0.9]]], 1e-5)\n\n def testNormalizeBoxes3DWithImageShapeAsVector(self):\n boxes = tf.constant([[[10, 30, 40, 90], [30, 10, 40, 50]],\n [[20, 40, 50, 80], [30, 50, 40, 90]]], tf.float32)\n image_shape = tf.constant([50, 100], tf.int32)\n\n normalized_boxes_tpu, normalized_boxes_cpu = (\n _transform_boxes_on_tpu_and_cpu(\n box_ops.normalize_boxes, boxes, image_shape))\n\n self.assertNDArrayNear(normalized_boxes_tpu, normalized_boxes_cpu, 1e-5)\n self.assertNDArrayNear(normalized_boxes_tpu,\n [[[0.2, 0.3, 0.8, 0.9], [0.6, 0.1, 0.8, 0.5]],\n [[0.4, 0.4, 1.0, 0.8], [0.6, 0.5, 0.8, 0.9]]], 1e-5)\n\n def testNormalizeBoxes3DWithImageShapeAsBroadcastableTensor(self):\n boxes = tf.constant([[[10, 30, 40, 90], [30, 10, 40, 50]],\n [[20, 40, 50, 80], [30, 50, 40, 90]]], tf.float32)\n image_shape = tf.constant([[[50, 100]], [[500, 1000]]], tf.int32)\n\n normalized_boxes_tpu, normalized_boxes_cpu = (\n _transform_boxes_on_tpu_and_cpu(\n box_ops.normalize_boxes, boxes, image_shape))\n\n self.assertNDArrayNear(normalized_boxes_tpu, normalized_boxes_cpu, 1e-5)\n self.assertNDArrayNear(\n normalized_boxes_tpu,\n [[[0.2, 0.3, 0.8, 0.9], [0.6, 0.1, 0.8, 0.5]],\n [[0.04, 0.04, 0.1, 0.08], [0.06, 0.05, 0.08, 0.09]]], 1e-5)\n\n def testNormalizeBoxes3DWithImageShapeAsSameShapeTensor(self):\n boxes = tf.constant([[[10, 30, 40, 90], [30, 10, 40, 50]],\n [[20, 40, 50, 80], [30, 50, 40, 90]]], tf.float32)\n image_shape = tf.constant(\n [[[50, 100], [50, 100]], [[500, 1000], [500, 1000]]], tf.int32)\n\n normalized_boxes_tpu, normalized_boxes_cpu = (\n _transform_boxes_on_tpu_and_cpu(\n box_ops.normalize_boxes, boxes, image_shape))\n\n self.assertNDArrayNear(normalized_boxes_tpu, normalized_boxes_cpu, 1e-5)\n self.assertNDArrayNear(\n normalized_boxes_tpu,\n [[[0.2, 0.3, 0.8, 0.9], [0.6, 0.1, 0.8, 0.5]],\n [[0.04, 0.04, 0.1, 0.08], [0.06, 0.05, 0.08, 0.09]]], 1e-5)\n\n\nclass DenormalizeBoxesTest(tf.test.TestCase):\n\n def testDenormalizeBoxes1DWithImageShapeAsList(self):\n boxes = tf.constant([0.2, 0.3, 0.8, 0.9], tf.float32)\n image_shape = [50, 100]\n normalized_boxes_tpu, normalized_boxes_cpu = (\n _transform_boxes_on_tpu_and_cpu(\n box_ops.denormalize_boxes, boxes, image_shape))\n\n self.assertNDArrayNear(normalized_boxes_tpu, normalized_boxes_cpu, 1e-5)\n self.assertNDArrayNear(normalized_boxes_tpu, [10, 30, 40, 90], 1e-5)\n\n def testDenormalizeBoxes1DWithImageShapeAsTensor(self):\n boxes = tf.constant([0.2, 0.3, 0.8, 0.9], tf.float32)\n image_shape = tf.constant([50, 100], tf.int32)\n normalized_boxes_tpu, normalized_boxes_cpu = (\n _transform_boxes_on_tpu_and_cpu(\n box_ops.denormalize_boxes, boxes, image_shape))\n\n self.assertNDArrayNear(normalized_boxes_tpu, normalized_boxes_cpu, 1e-5)\n self.assertNDArrayNear(normalized_boxes_tpu, [10, 30, 40, 90], 1e-5)\n\n def testDenormalizeBoxes2DWithImageShapeAsList(self):\n boxes = tf.constant([[0.2, 0.3, 0.8, 0.9], [0.6, 0.1, 0.8, 0.5]],\n tf.float32)\n image_shape = [50, 100]\n normalized_boxes_tpu, normalized_boxes_cpu = (\n _transform_boxes_on_tpu_and_cpu(\n box_ops.denormalize_boxes, boxes, image_shape))\n\n self.assertNDArrayNear(normalized_boxes_tpu, normalized_boxes_cpu, 1e-5)\n self.assertNDArrayNear(normalized_boxes_tpu,\n [[10, 30, 40, 90], [30, 10, 40, 50]], 1e-5)\n\n def testDenormalizeBoxes2DWithImageShapeAsVector(self):\n boxes = tf.constant([[0.2, 0.3, 0.8, 0.9], [0.6, 0.1, 0.8, 0.5]],\n tf.float32)\n image_shape = tf.constant([50, 100], dtype=tf.int32)\n normalized_boxes_tpu, normalized_boxes_cpu = (\n _transform_boxes_on_tpu_and_cpu(\n box_ops.denormalize_boxes, boxes, image_shape))\n\n self.assertNDArrayNear(normalized_boxes_tpu, normalized_boxes_cpu, 1e-5)\n self.assertNDArrayNear(normalized_boxes_tpu,\n [[10, 30, 40, 90], [30, 10, 40, 50]], 1e-5)\n\n def testDenormalizeBoxes2DWithImageShapeAsBroadcastableTensor(self):\n boxes = tf.constant([[0.2, 0.3, 0.8, 0.9], [0.6, 0.1, 0.8, 0.5]],\n tf.float32)\n image_shape = tf.constant([[50, 100]], tf.int32)\n normalized_boxes_tpu, normalized_boxes_cpu = (\n _transform_boxes_on_tpu_and_cpu(\n box_ops.denormalize_boxes, boxes, image_shape))\n\n self.assertNDArrayNear(normalized_boxes_tpu, normalized_boxes_cpu, 1e-5)\n self.assertNDArrayNear(normalized_boxes_tpu,\n [[10, 30, 40, 90], [30, 10, 40, 50]], 1e-5)\n\n def testDenormalizeBoxes2DWithImageShapeAsSameShapeTensor(self):\n boxes = tf.constant([[0.2, 0.3, 0.8, 0.9], [0.6, 0.1, 0.8, 0.5]],\n tf.float32)\n image_shape = tf.constant([[50, 100], [50, 100]], tf.int32)\n normalized_boxes_tpu, normalized_boxes_cpu = (\n _transform_boxes_on_tpu_and_cpu(\n box_ops.denormalize_boxes, boxes, image_shape))\n\n self.assertNDArrayNear(normalized_boxes_tpu, normalized_boxes_cpu, 1e-5)\n self.assertNDArrayNear(normalized_boxes_tpu,\n [[10, 30, 40, 90], [30, 10, 40, 50]], 1e-5)\n\n def testDenormalizeBoxes3DWithImageShapeAsList(self):\n boxes = tf.constant([[[0.2, 0.3, 0.8, 0.9], [0.6, 0.1, 0.8, 0.5]],\n [[0.4, 0.4, 1.0, 0.8], [0.6, 0.5, 0.8, 0.9]]],\n tf.float32)\n image_shape = [50, 100]\n normalized_boxes_tpu, normalized_boxes_cpu = (\n _transform_boxes_on_tpu_and_cpu(\n box_ops.denormalize_boxes, boxes, image_shape))\n\n self.assertNDArrayNear(normalized_boxes_tpu, normalized_boxes_cpu, 1e-5)\n self.assertNDArrayNear(normalized_boxes_tpu,\n [[[10, 30, 40, 90], [30, 10, 40, 50]],\n [[20, 40, 50, 80], [30, 50, 40, 90]]], 1e-5)\n\n def testDenormalizeBoxes3DWithImageShapeAsVector(self):\n boxes = tf.constant([[[0.2, 0.3, 0.8, 0.9], [0.6, 0.1, 0.8, 0.5]],\n [[0.4, 0.4, 1.0, 0.8], [0.6, 0.5, 0.8, 0.9]]],\n tf.float32)\n image_shape = tf.constant([50, 100], tf.int32)\n normalized_boxes_tpu, normalized_boxes_cpu = (\n _transform_boxes_on_tpu_and_cpu(\n box_ops.denormalize_boxes, boxes, image_shape))\n\n self.assertNDArrayNear(normalized_boxes_tpu, normalized_boxes_cpu, 1e-5)\n self.assertNDArrayNear(normalized_boxes_tpu,\n [[[10, 30, 40, 90], [30, 10, 40, 50]],\n [[20, 40, 50, 80], [30, 50, 40, 90]]], 1e-5)\n\n def testDenormalizeBoxes3DWithImageShapeAsBroadcastableTensor(self):\n boxes = tf.constant([[[0.2, 0.3, 0.8, 0.9], [0.6, 0.1, 0.8, 0.5]],\n [[0.04, 0.04, 0.1, 0.08], [0.06, 0.05, 0.08, 0.09]]],\n tf.float32)\n image_shape = tf.constant([[[50, 100]], [[500, 1000]]], tf.int32)\n normalized_boxes_tpu, normalized_boxes_cpu = (\n _transform_boxes_on_tpu_and_cpu(\n box_ops.denormalize_boxes, boxes, image_shape))\n\n self.assertNDArrayNear(normalized_boxes_tpu, normalized_boxes_cpu, 1e-5)\n self.assertNDArrayNear(normalized_boxes_tpu,\n [[[10, 30, 40, 90], [30, 10, 40, 50]],\n [[20, 40, 50, 80], [30, 50, 40, 90]]], 1e-5)\n\n def testDenormalizeBoxes3DWithImageShapeAsSameShapeTensor(self):\n boxes = tf.constant([[[0.2, 0.3, 0.8, 0.9], [0.6, 0.1, 0.8, 0.5]],\n [[0.04, 0.04, 0.1, 0.08], [0.06, 0.05, 0.08, 0.09]]],\n tf.float32)\n image_shape = tf.constant(\n [[[50, 100], [50, 100]], [[500, 1000], [500, 1000]]], tf.int32)\n normalized_boxes_tpu, normalized_boxes_cpu = (\n _transform_boxes_on_tpu_and_cpu(\n box_ops.denormalize_boxes, boxes, image_shape))\n\n self.assertNDArrayNear(normalized_boxes_tpu, normalized_boxes_cpu, 1e-5)\n self.assertNDArrayNear(normalized_boxes_tpu,\n [[[10, 30, 40, 90], [30, 10, 40, 50]],\n [[20, 40, 50, 80], [30, 50, 40, 90]]], 1e-5)\n\n\nclass ClipBoxesTest(tf.test.TestCase):\n\n def testClipBoxesImageShapeAsList(self):\n boxes_data = [[0, 0, 1, 1], [0, 0.1, 1, 1.1], [0, 0.3, 1, 1.3],\n [0, 0.5, 1, 1.5], [0, 0.7, 1, 1.7], [0, 1.9, 1, 1.9]]\n image_shape = [3, 3]\n boxes = tf.constant(boxes_data)\n\n clipped_boxes_tpu, clipped_boxes_cpu = _transform_boxes_on_tpu_and_cpu(\n box_ops.clip_boxes, boxes, image_shape)\n\n self.assertAllClose(clipped_boxes_tpu, clipped_boxes_cpu)\n self.assertAllClose(clipped_boxes_tpu,\n [[0, 0, 1, 1], [0, 0.1, 1, 1.1], [0, 0.3, 1, 1.3],\n [0, 0.5, 1, 1.5], [0, 0.7, 1, 1.7], [0, 1.9, 1, 1.9]])\n\n def testClipBoxesImageShapeAsVector(self):\n boxes_data = [[0, 0, 1, 1], [0, 0.1, 1, 1.1], [0, 0.3, 1, 1.3],\n [0, 0.5, 1, 1.5], [0, 0.7, 1, 1.7], [0, 1.9, 1, 1.9]]\n boxes = tf.constant(boxes_data)\n image_shape = np.array([3, 3], dtype=np.float32)\n clipped_boxes_tpu, clipped_boxes_cpu = _transform_boxes_on_tpu_and_cpu(\n box_ops.clip_boxes, boxes, image_shape)\n\n self.assertAllClose(clipped_boxes_tpu, clipped_boxes_cpu)\n self.assertAllClose(clipped_boxes_tpu,\n [[0, 0, 1, 1], [0, 0.1, 1, 1.1], [0, 0.3, 1, 1.3],\n [0, 0.5, 1, 1.5], [0, 0.7, 1, 1.7], [0, 1.9, 1, 1.9]])\n\n def testClipBoxesImageShapeAsTensor(self):\n boxes_data = [[0, 0, 1, 1], [0, 0.1, 1, 1.1], [0, 0.3, 1, 1.3],\n [0, 0.5, 1, 1.5], [0, 0.7, 1, 1.7], [0, 1.9, 1, 1.9]]\n boxes = tf.constant(boxes_data)\n image_shape = tf.constant([[3, 3], [3, 3], [3, 3], [3, 3], [3, 3], [3, 3]],\n dtype=tf.float32)\n clipped_boxes_tpu, clipped_boxes_cpu = _transform_boxes_on_tpu_and_cpu(\n box_ops.clip_boxes, boxes, image_shape)\n\n self.assertAllClose(clipped_boxes_tpu, clipped_boxes_cpu)\n self.assertAllClose(clipped_boxes_tpu,\n [[0, 0, 1, 1], [0, 0.1, 1, 1.1], [0, 0.3, 1, 1.3],\n [0, 0.5, 1, 1.5], [0, 0.7, 1, 1.7], [0, 1.9, 1, 1.9]])\n\n\nclass EncodeDecodeBoxesTest(tf.test.TestCase):\n\n def test_encode_decode_boxes(self):\n boxes_np = np.array([[[1.0, 2.0, 3.0, 4.0], [2.0, 3.0, 4.0, 5.0]],\n [[4.0, 5.0, 6.0, 7.0], [5.0, 6.0, 7.0, 8.0]]])\n boxes = tf.constant(boxes_np, dtype=tf.float32)\n anchors = tf.constant([[[1.5, 2.5, 3.5, 4.5], [2.5, 3.5, 4.5, 5.5]],\n [[1.5, 2.5, 3.5, 4.5], [2.5, 3.5, 4.5, 5.5]]],\n dtype=tf.float32)\n weights = [1.0, 1.0, 1.0, 1.0]\n\n def test_fn(boxes, anchors):\n encoded_boxes = box_ops.encode_boxes(boxes, anchors, weights)\n decoded_boxes = box_ops.decode_boxes(encoded_boxes, anchors, weights)\n return decoded_boxes\n\n decoded_boxes_tpu, decoded_boxes_cpu = _transform_boxes_on_tpu_and_cpu(\n test_fn, boxes, anchors)\n\n self.assertNDArrayNear(decoded_boxes_tpu, decoded_boxes_cpu, 1e-5)\n self.assertNDArrayNear(decoded_boxes_tpu, boxes_np, 1e-5)\n\n def test_encode_decode_boxes_batch_broadcast(self):\n boxes_np = np.array([[[1.0, 2.0, 3.0, 4.0], [2.0, 3.0, 4.0, 5.0]],\n [[4.0, 5.0, 6.0, 7.0], [5.0, 6.0, 7.0, 8.0]]])\n boxes = tf.constant(boxes_np, dtype=tf.float32)\n anchors = tf.constant([[[1.5, 2.5, 3.5, 4.5], [2.5, 3.5, 4.5, 5.5]]],\n dtype=tf.float32)\n weights = [1.0, 1.0, 1.0, 1.0]\n\n def test_fn(boxes, anchors):\n encoded_boxes = box_ops.encode_boxes(boxes, anchors, weights)\n decoded_boxes = box_ops.decode_boxes(encoded_boxes, anchors, weights)\n return decoded_boxes\n\n decoded_boxes_tpu, decoded_boxes_cpu = _transform_boxes_on_tpu_and_cpu(\n test_fn, boxes, anchors)\n\n self.assertNDArrayNear(decoded_boxes_tpu, decoded_boxes_cpu, 1e-5)\n self.assertNDArrayNear(decoded_boxes_tpu, boxes_np, 1e-5)\n\n\nclass FilterBoxesTest(tf.test.TestCase):\n\n def test_filter_boxes_batch(self):\n # boxes -> [[small, good, outside], [outside, small, good]]\n boxes_np = np.array([[[1.0, 2.0, 1.5, 2.5], [2.0, 3.0, 4.5, 5.5],\n [7.0, 4.0, 9.5, 6.5]],\n [[-2.0, 5.0, 0.0, 7.5], [5.0, 6.0, 5.1, 6.0],\n [4.0, 1.0, 7.0, 4.0]]])\n filtered_boxes_np = np.array([[[0.0, 0.0, 0.0, 0.0], [2.0, 3.0, 4.5, 5.5],\n [0.0, 0.0, 0.0, 0.0]],\n [[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0],\n [4.0, 1.0, 7.0, 4.0]]])\n boxes = tf.constant(boxes_np, dtype=tf.float32)\n scores_np = np.array([[0.9, 0.7, 0.5], [0.11, 0.22, 0.33]])\n filtered_scores_np = np.array([[0.0, 0.7, 0.0], [0.0, 0.0, 0.33]])\n scores = tf.constant(scores_np, dtype=tf.float32)\n image_shape = tf.expand_dims(\n tf.constant([[8, 8], [8, 8]], dtype=tf.int32), axis=1)\n min_size_threshold = 2.0\n\n def test_fn(boxes, scores, image_shape):\n filtered_boxes, filtered_scores = box_ops.filter_boxes(\n boxes, scores, image_shape, min_size_threshold)\n return filtered_boxes, filtered_scores\n\n filtered_results_tpu, filtered_results_cpu = (\n _transform_boxes_on_tpu_and_cpu(\n test_fn, boxes, scores, image_shape))\n filtered_boxes_tpu, filtered_scores_tpu = filtered_results_tpu\n filtered_boxes_cpu, filtered_scores_cpu = filtered_results_cpu\n\n self.assertNDArrayNear(filtered_boxes_tpu, filtered_boxes_cpu, 1e-5)\n self.assertNDArrayNear(filtered_scores_tpu, filtered_scores_cpu, 1e-5)\n self.assertNDArrayNear(filtered_boxes_tpu, filtered_boxes_np, 1e-5)\n self.assertNDArrayNear(filtered_scores_tpu, filtered_scores_np, 1e-5)\n\n\nclass FilterBoxesByScoresTest(tf.test.TestCase):\n\n def test_filter_boxes_by_scores_batch(self):\n # boxes -> [[small, good, outside], [outside, small, good]]\n boxes_np = np.array([[[1.0, 2.0, 1.5, 2.5], [2.0, 3.0, 4.5, 5.5],\n [7.0, 4.0, 9.5, 6.5]],\n [[-2.0, 5.0, 0.0, 7.5], [5.0, 6.0, 5.1, 6.0],\n [4.0, 1.0, 7.0, 4.0]]])\n filtered_boxes_np = np.array([[[0.0, 0.0, 0.0, 0.0], [2.0, 3.0, 4.5, 5.5],\n [7.0, 4.0, 9.5, 6.5]],\n [[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0],\n [4.0, 1.0, 7.0, 4.0]]])\n boxes = tf.constant(boxes_np, dtype=tf.float32)\n scores_np = np.array([[0.1, 0.7, 0.6], [0.11, 0.22, 0.53]])\n filtered_scores_np = np.array([[-1.0, 0.7, 0.6], [-1.0, -1.0, 0.53]])\n scores = tf.constant(scores_np, dtype=tf.float32)\n min_score_threshold = 0.5\n\n def test_fn(boxes, scores):\n filtered_boxes, filtered_scores = box_ops.filter_boxes_by_scores(\n boxes, scores, min_score_threshold)\n return filtered_boxes, filtered_scores\n\n filtered_results_tpu, filtered_results_cpu = _transform_boxes_on_tpu_and_cpu(\n test_fn, boxes, scores)\n filtered_boxes_tpu, filtered_scores_tpu = filtered_results_tpu\n filtered_boxes_cpu, filtered_scores_cpu = filtered_results_cpu\n\n self.assertNDArrayNear(filtered_boxes_tpu, filtered_boxes_cpu, 1e-5)\n self.assertNDArrayNear(filtered_scores_tpu, filtered_scores_cpu, 1e-5)\n self.assertNDArrayNear(filtered_boxes_tpu, filtered_boxes_np, 1e-5)\n self.assertNDArrayNear(filtered_scores_tpu, filtered_scores_np, 1e-5)\n\n\nclass GatherInstancesTest(tf.test.TestCase):\n\n def test_gather_instances(self):\n boxes_np = np.array([[[1.0, 2.0, 1.5, 2.5], [2.0, 3.0, 4.5, 5.5],\n [7.0, 4.0, 9.5, 6.5]],\n [[-2.0, 5.0, 0.0, 7.5], [5.0, 6.0, 5.1, 6.0],\n [4.0, 1.0, 7.0, 4.0]]])\n indices_np = np.array([[2, 0], [0, 1]])\n boxes = tf.constant(boxes_np, dtype=tf.float32)\n indices = tf.constant(indices_np, dtype=tf.int32)\n\n selected_boxes = box_ops.gather_instances(indices, boxes)\n\n expected_selected_boxes = np.array(\n [[[7.0, 4.0, 9.5, 6.5], [1.0, 2.0, 1.5, 2.5]],\n [[-2.0, 5.0, 0.0, 7.5], [5.0, 6.0, 5.1, 6.0]]])\n\n self.assertNDArrayNear(expected_selected_boxes, selected_boxes, 1e-5)\n\n def test_gather_instances_with_multiple_inputs(self):\n boxes_np = np.array([[[1.0, 2.0, 1.5, 2.5], [2.0, 3.0, 4.5, 5.5],\n [7.0, 4.0, 9.5, 6.5]],\n [[-2.0, 5.0, 0.0, 7.5], [5.0, 6.0, 5.1, 6.0],\n [4.0, 1.0, 7.0, 4.0]]])\n classes_np = np.array([[1, 2, 3], [20, 30, 40]])\n indices_np = np.array([[2, 0], [0, 1]])\n boxes = tf.constant(boxes_np, dtype=tf.float32)\n classes = tf.constant(classes_np, dtype=tf.int32)\n indices = tf.constant(indices_np, dtype=tf.int32)\n\n selected_boxes, selected_classes = box_ops.gather_instances(\n indices, boxes, classes)\n\n expected_selected_boxes = np.array(\n [[[7.0, 4.0, 9.5, 6.5], [1.0, 2.0, 1.5, 2.5]],\n [[-2.0, 5.0, 0.0, 7.5], [5.0, 6.0, 5.1, 6.0]]])\n expected_selected_classes = np.array(\n [[3, 1], [20, 30]])\n\n self.assertNDArrayNear(expected_selected_boxes, selected_boxes, 1e-5)\n self.assertAllEqual(expected_selected_classes, selected_classes)\n\n\nclass TopKBoxesTest(tf.test.TestCase):\n\n def test_top_k_boxes_batch1(self):\n boxes_np = np.array([[[1.0, 2.0, 1.5, 2.5], [2.0, 3.0, 4.5, 5.5],\n [7.0, 4.0, 9.5, 6.5]]])\n boxes = tf.constant(boxes_np, dtype=tf.float32)\n scores_np = np.array([[0.9, 0.5, 0.7]])\n scores = tf.constant(scores_np, dtype=tf.float32)\n top_k_boxes_np = np.array([[[1.0, 2.0, 1.5, 2.5], [7.0, 4.0, 9.5, 6.5]]])\n top_k_scores_np = np.array([[0.9, 0.7]])\n\n def test_fn(boxes, scores):\n top_k_boxes, top_k_scores = box_ops.top_k_boxes(boxes, scores, k=2)\n return top_k_boxes, top_k_scores\n\n top_k_results_tpu, top_k_results_cpu = _transform_boxes_on_tpu_and_cpu(\n test_fn, boxes, scores)\n top_k_boxes_tpu, top_k_scores_tpu = top_k_results_tpu\n top_k_boxes_cpu, top_k_scores_cpu = top_k_results_cpu\n\n self.assertNDArrayNear(top_k_boxes_tpu, top_k_boxes_cpu, 1e-5)\n self.assertNDArrayNear(top_k_scores_tpu, top_k_scores_cpu, 1e-5)\n self.assertNDArrayNear(top_k_boxes_tpu, top_k_boxes_np, 1e-5)\n self.assertNDArrayNear(top_k_scores_tpu, top_k_scores_np, 1e-5)\n\n def test_top_k_boxes_batch2(self):\n boxes_np = np.array([[[1.0, 2.0, 1.5, 2.5], [2.0, 3.0, 4.5, 5.5],\n [7.0, 4.0, 9.5, 6.5]],\n [[-2.0, 5.0, 0.0, 7.5], [5.0, 6.0, 5.1, 6.0],\n [4.0, 1.0, 7.0, 4.0]]])\n boxes = tf.constant(boxes_np, dtype=tf.float32)\n scores_np = np.array([[0.9, 0.7, 0.5], [0.11, 0.22, 0.33]])\n scores = tf.constant(scores_np, dtype=tf.float32)\n top_k_boxes_np = np.array([[[1.0, 2.0, 1.5, 2.5], [2.0, 3.0, 4.5, 5.5]],\n [[4.0, 1.0, 7.0, 4.0], [5.0, 6.0, 5.1, 6.0]]])\n top_k_scores_np = np.array([[0.9, 0.7], [0.33, 0.22]])\n\n def test_fn(boxes, scores):\n top_k_boxes, top_k_scores = box_ops.top_k_boxes(boxes, scores, k=2)\n return top_k_boxes, top_k_scores\n\n top_k_results_tpu, top_k_results_cpu = _transform_boxes_on_tpu_and_cpu(\n test_fn, boxes, scores)\n top_k_boxes_tpu, top_k_scores_tpu = top_k_results_tpu\n top_k_boxes_cpu, top_k_scores_cpu = top_k_results_cpu\n\n self.assertNDArrayNear(top_k_boxes_tpu, top_k_boxes_cpu, 1e-5)\n self.assertNDArrayNear(top_k_scores_tpu, top_k_scores_cpu, 1e-5)\n self.assertNDArrayNear(top_k_boxes_tpu, top_k_boxes_np, 1e-5)\n self.assertNDArrayNear(top_k_scores_tpu, top_k_scores_np, 1e-5)\n\n\nclass BboxeOverlapTest(tf.test.TestCase):\n\n def testBBoxeOverlapOpCorrectness(self):\n boxes_data = [[[0, 0, 0.1, 1], [0, 0.2, 0.2, 1.2], [0, 0.3, 0.3, 1.3],\n [0, 0.5, 0.4, 1.5], [0, 0.7, 0.5, 1.7], [0, 0.9, 0.6, 1.9],\n [0, 0.1, 0.1, 1.1], [0, 0.3, 0.7, 1.3], [0, 0.9, 2, 1.9]],\n [[0, 0, 1, 0.2], [0, 0.2, 0.5, 1.2], [0, 0.4, 0.9, 1.4],\n [0, 0.6, 1.1, 1.6], [0, 0.8, 1.2, 1.8], [0, 1, 1.5, 2],\n [0, 0.5, 1, 1], [0.5, 0.8, 1, 1.8], [-1, -1, -1, -1]]]\n boxes_np = np.array(boxes_data, dtype=np.float32)\n gt_boxes_data = [[[0, 0.1, 0.1, 1.1], [0, 0.3, 0.7, 1.3], [0, 0.9, 2, 1.9]],\n [[0, 0.5, 1, 1], [0.5, 0.8, 1, 1.8], [-1, -1, -1, -1]]]\n gt_boxes_np = np.array(gt_boxes_data, dtype=np.float32)\n\n # Runs on TPU.\n strategy = tf.distribute.experimental.TPUStrategy()\n with strategy.scope():\n boxes = tf.constant(boxes_np)\n gt_boxes = tf.constant(gt_boxes_np)\n iou = box_ops.bbox_overlap(boxes=boxes, gt_boxes=gt_boxes)\n iou = iou.numpy()\n self.assertEqual(iou.shape, (2, 9, 3))\n self.assertAllEqual(\n np.argmax(iou, axis=2),\n [[0, 0, 1, 1, 1, 2, 0, 1, 2], [0, 0, 0, 0, 1, 1, 0, 1, 0]])\n\n def testBBoxeOverlapOpCheckShape(self):\n batch_size = 2\n rpn_post_nms_topn = 2000\n gt_max_instances = 100\n boxes_np = np.random.rand(batch_size, rpn_post_nms_topn,\n 4).astype(np.float32)\n gt_boxes_np = np.random.rand(batch_size, gt_max_instances,\n 4).astype(np.float32)\n strategy = tf.distribute.experimental.TPUStrategy()\n with strategy.scope():\n boxes = tf.constant(boxes_np)\n gt_boxes = tf.constant(gt_boxes_np)\n iou = box_ops.bbox_overlap(boxes=boxes, gt_boxes=gt_boxes)\n iou = iou.numpy()\n self.assertEqual(iou.shape,\n (batch_size, (rpn_post_nms_topn), gt_max_instances))\n\n def testBBoxeOverlapOpCorrectnessWithNegativeData(self):\n boxes_data = [[[0, -0.01, 0.1, 1.1], [0, 0.2, 0.2, 5.0],\n [0, -0.01, 0.1, 1.], [-1, -1, -1, -1]]]\n boxes_np = np.array(boxes_data, dtype=np.float32)\n gt_boxes_np = boxes_np\n strategy = tf.distribute.experimental.TPUStrategy()\n with strategy.scope():\n boxes = tf.constant(boxes_np)\n gt_boxes = tf.constant(gt_boxes_np)\n iou = box_ops.bbox_overlap(boxes=boxes, gt_boxes=gt_boxes)\n iou = iou.numpy()\n expected = np.array([[[0.99999994, 0.0917431, 0.9099099, -1.],\n [0.0917431, 1., 0.08154944, -1.],\n [0.9099099, 0.08154944, 1., -1.],\n [-1., -1., -1., -1.]]])\n self.assertAllClose(expected, iou)\n\n\nclass BoxMatchingTest(tf.test.TestCase):\n\n def test_box_matching_single(self):\n boxes_np = np.array(\n [[[0, 0, 5, 5], [2.5, 2.5, 7.5, 7.5],\n [5, 5, 10, 10], [7.5, 7.5, 12.5, 12.5]]])\n boxes = tf.constant(boxes_np, dtype=tf.float32)\n\n gt_boxes_np = np.array(\n [[[10, 10, 15, 15], [2.5, 2.5, 7.5, 7.5],\n [-1, -1, -1, -1]]])\n gt_boxes = tf.constant(gt_boxes_np, dtype=tf.float32)\n gt_classes_np = np.array([[2, 10, -1]])\n gt_classes = tf.constant(gt_classes_np, dtype=tf.int32)\n\n matched_gt_boxes_np = np.array(\n [[[2.5, 2.5, 7.5, 7.5],\n [2.5, 2.5, 7.5, 7.5],\n [2.5, 2.5, 7.5, 7.5],\n [10, 10, 15, 15]]])\n matched_gt_classes_np = np.array([[10, 10, 10, 2]])\n matched_gt_indices_np = np.array([[1, 1, 1, 0]])\n matched_iou_np = np.array(\n [[0.142857142857, 1.0, 0.142857142857, 0.142857142857]])\n iou_np = np.array(\n [[[0, 0.142857142857, -1.0],\n [0, 1.0, -1.0],\n [0, 0.142857142857, -1.0],\n [0.142857142857, 0, -1.0]]])\n\n # Runs on TPU.\n strategy = tf.distribute.experimental.TPUStrategy()\n with strategy.scope():\n (matched_gt_boxes_tpu, matched_gt_classes_tpu,\n matched_gt_indices_tpu, matched_iou_tpu, iou_tpu) = (\n box_ops.box_matching(boxes, gt_boxes, gt_classes))\n\n # Runs on CPU.\n (matched_gt_boxes_cpu, matched_gt_classes_cpu,\n matched_gt_indices_cpu, matched_iou_cpu, iou_cpu) = (\n box_ops.box_matching(boxes, gt_boxes, gt_classes))\n\n # consistency.\n self.assertNDArrayNear(\n matched_gt_boxes_tpu.numpy(), matched_gt_boxes_cpu.numpy(), 1e-5)\n self.assertAllEqual(\n matched_gt_classes_tpu.numpy(), matched_gt_classes_cpu.numpy())\n self.assertAllEqual(\n matched_gt_indices_tpu.numpy(), matched_gt_indices_cpu.numpy())\n self.assertNDArrayNear(\n matched_iou_tpu.numpy(), matched_iou_cpu.numpy(), 1e-5)\n self.assertNDArrayNear(\n iou_tpu.numpy(), iou_cpu.numpy(), 1e-5)\n\n # correctness.\n self.assertNDArrayNear(\n matched_gt_boxes_tpu.numpy(), matched_gt_boxes_np, 1e-5)\n self.assertAllEqual(\n matched_gt_classes_tpu.numpy(), matched_gt_classes_np)\n self.assertAllEqual(\n matched_gt_indices_tpu.numpy(), matched_gt_indices_np)\n self.assertNDArrayNear(\n matched_iou_tpu.numpy(), matched_iou_np, 1e-5)\n self.assertNDArrayNear(\n iou_tpu.numpy(), iou_np, 1e-5)\n\n def test_box_matching_single_no_gt(self):\n boxes_np = np.array(\n [[[0, 0, 5, 5], [2.5, 2.5, 7.5, 7.5],\n [5, 5, 10, 10], [7.5, 7.5, 12.5, 12.5]]])\n boxes = tf.constant(boxes_np, dtype=tf.float32)\n\n gt_boxes_np = np.array(\n [[[-1, -1, -1, -1],\n [-1, -1, -1, -1],\n [-1, -1, -1, -1]]])\n gt_boxes = tf.constant(gt_boxes_np, dtype=tf.float32)\n gt_classes_np = np.array([[-1, -1, -1]])\n gt_classes = tf.constant(gt_classes_np, dtype=tf.int32)\n\n matched_gt_boxes_np = np.array(\n [[[0, 0, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 0, 0]]])\n matched_gt_classes_np = np.array([[0, 0, 0, 0]])\n matched_gt_indices_np = np.array([[-1, -1, -1, -1]])\n matched_iou_np = np.array([[-1, -1, -1, -1]])\n iou_np = np.array(\n [[[-1, -1, -1],\n [-1, -1, -1],\n [-1, -1, -1],\n [-1, -1, -1]]])\n\n # Runs on TPU.\n strategy = tf.distribute.experimental.TPUStrategy()\n with strategy.scope():\n (matched_gt_boxes_tpu, matched_gt_classes_tpu,\n matched_gt_indices_tpu, matched_iou_tpu, iou_tpu) = (\n box_ops.box_matching(boxes, gt_boxes, gt_classes))\n\n # Runs on CPU.\n (matched_gt_boxes_cpu, matched_gt_classes_cpu,\n matched_gt_indices_cpu, matched_iou_cpu, iou_cpu) = (\n box_ops.box_matching(boxes, gt_boxes, gt_classes))\n\n # consistency.\n self.assertNDArrayNear(\n matched_gt_boxes_tpu.numpy(), matched_gt_boxes_cpu.numpy(), 1e-5)\n self.assertAllEqual(\n matched_gt_classes_tpu.numpy(), matched_gt_classes_cpu.numpy())\n self.assertAllEqual(\n matched_gt_indices_tpu.numpy(), matched_gt_indices_cpu.numpy())\n self.assertNDArrayNear(\n matched_iou_tpu.numpy(), matched_iou_cpu.numpy(), 1e-5)\n self.assertNDArrayNear(\n iou_tpu.numpy(), iou_cpu.numpy(), 1e-5)\n\n # correctness.\n self.assertNDArrayNear(\n matched_gt_boxes_tpu.numpy(), matched_gt_boxes_np, 1e-5)\n self.assertAllEqual(\n matched_gt_classes_tpu.numpy(), matched_gt_classes_np)\n self.assertAllEqual(\n matched_gt_indices_tpu.numpy(), matched_gt_indices_np)\n self.assertNDArrayNear(\n matched_iou_tpu.numpy(), matched_iou_np, 1e-5)\n self.assertNDArrayNear(\n iou_tpu.numpy(), iou_np, 1e-5)\n\n def test_box_matching_batch(self):\n boxes_np = np.array(\n [[[0, 0, 5, 5], [2.5, 2.5, 7.5, 7.5],\n [5, 5, 10, 10], [7.5, 7.5, 12.5, 12.5]],\n [[0, 0, 5, 5], [2.5, 2.5, 7.5, 7.5],\n [5, 5, 10, 10], [7.5, 7.5, 12.5, 12.5]]])\n boxes = tf.constant(boxes_np, dtype=tf.float32)\n\n gt_boxes_np = np.array(\n [[[10, 10, 15, 15], [2.5, 2.5, 7.5, 7.5], [-1, -1, -1, -1]],\n [[-1, -1, -1, -1], [-1, -1, -1, -1], [-1, -1, -1, -1]]])\n gt_boxes = tf.constant(gt_boxes_np, dtype=tf.float32)\n gt_classes_np = np.array([[2, 10, -1], [-1, -1, -1]])\n gt_classes = tf.constant(gt_classes_np, dtype=tf.int32)\n\n matched_gt_boxes_np = np.array(\n [[[2.5, 2.5, 7.5, 7.5],\n [2.5, 2.5, 7.5, 7.5],\n [2.5, 2.5, 7.5, 7.5],\n [10, 10, 15, 15]],\n [[0, 0, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 0, 0]]])\n matched_gt_classes_np = np.array(\n [[10, 10, 10, 2],\n [0, 0, 0, 0]])\n matched_gt_indices_np = np.array(\n [[1, 1, 1, 0],\n [-1, -1, -1, -1]])\n matched_iou_np = np.array(\n [[0.142857142857, 1.0, 0.142857142857, 0.142857142857],\n [-1, -1, -1, -1]])\n iou_np = np.array(\n [[[0, 0.142857142857, -1.0],\n [0, 1.0, -1.0],\n [0, 0.142857142857, -1.0],\n [0.142857142857, 0, -1.0]],\n [[-1, -1, -1],\n [-1, -1, -1],\n [-1, -1, -1],\n [-1, -1, -1]]])\n\n # Runs on TPU.\n strategy = tf.distribute.experimental.TPUStrategy()\n with strategy.scope():\n (matched_gt_boxes_tpu, matched_gt_classes_tpu,\n matched_gt_indices_tpu, matched_iou_tpu, iou_tpu) = (\n box_ops.box_matching(boxes, gt_boxes, gt_classes))\n\n # Runs on CPU.\n (matched_gt_boxes_cpu, matched_gt_classes_cpu,\n matched_gt_indices_cpu, matched_iou_cpu, iou_cpu) = (\n box_ops.box_matching(boxes, gt_boxes, gt_classes))\n\n # consistency.\n self.assertNDArrayNear(\n matched_gt_boxes_tpu.numpy(), matched_gt_boxes_cpu.numpy(), 1e-5)\n self.assertAllEqual(\n matched_gt_classes_tpu.numpy(), matched_gt_classes_cpu.numpy())\n self.assertAllEqual(\n matched_gt_indices_tpu.numpy(), matched_gt_indices_cpu.numpy())\n self.assertNDArrayNear(\n matched_iou_tpu.numpy(), matched_iou_cpu.numpy(), 1e-5)\n self.assertNDArrayNear(\n iou_tpu.numpy(), iou_cpu.numpy(), 1e-5)\n\n # correctness.\n self.assertNDArrayNear(\n matched_gt_boxes_tpu.numpy(), matched_gt_boxes_np, 1e-5)\n self.assertAllEqual(\n matched_gt_classes_tpu.numpy(), matched_gt_classes_np)\n self.assertAllEqual(\n matched_gt_indices_tpu.numpy(), matched_gt_indices_np)\n self.assertNDArrayNear(\n matched_iou_tpu.numpy(), matched_iou_np, 1e-5)\n self.assertNDArrayNear(\n iou_tpu.numpy(), iou_np, 1e-5)\n\n\nif __name__ == '__main__':\n tf.test.main()\n"
] | [
[
"tensorflow.compat.v1.truncated_normal_initializer",
"tensorflow.compat.v1.reduce_mean",
"tensorflow.compat.v1.squeeze",
"tensorflow.compat.v1.variable_scope",
"tensorflow.compat.v1.pad"
],
[
"tensorflow.compat.v1.concat",
"tensorflow.compat.v1.equal",
"tensorflow.compat.v1.random_normal",
"tensorflow.compat.v1.shape",
"tensorflow.compat.v1.greater_equal",
"tensorflow.compat.v1.constant",
"tensorflow.compat.v1.identity",
"tensorflow.compat.v1.cumsum",
"tensorflow.compat.v1.nn.top_k",
"tensorflow.compat.v1.reduce_sum",
"tensorflow.compat.v1.reshape",
"tensorflow.compat.v1.one_hot",
"tensorflow.compat.v1.maximum",
"tensorflow.compat.v1.random_uniform",
"tensorflow.compat.v1.zeros_like",
"tensorflow.compat.v1.unstack",
"tensorflow.compat.v1.transpose",
"tensorflow.compat.v1.name_scope",
"tensorflow.compat.v1.where",
"tensorflow.compat.v1.reduce_any",
"tensorflow.compat.v1.reverse_v2",
"tensorflow.compat.v1.less",
"tensorflow.compat.v1.split",
"tensorflow.compat.v1.minimum",
"tensorflow.compat.v1.reduce_max",
"tensorflow.compat.v1.cast",
"tensorflow.compat.v1.stack",
"tensorflow.compat.v1.expand_dims",
"tensorflow.compat.v1.image.draw_bounding_boxes",
"tensorflow.compat.v1.less_equal",
"tensorflow.compat.v1.control_dependencies",
"tensorflow.compat.v1.truediv",
"tensorflow.compat.v1.matmul",
"tensorflow.compat.v1.reduce_min",
"tensorflow.compat.v1.size",
"tensorflow.compat.v1.squeeze",
"tensorflow.compat.v1.greater"
],
[
"tensorflow.keras.Input",
"tensorflow.keras.backend.image_data_format",
"tensorflow.identity",
"tensorflow.keras.utils.register_keras_serializable",
"tensorflow.add_n",
"tensorflow.keras.layers.InputSpec"
],
[
"tensorflow.compat.v1.logical_and",
"tensorflow.compat.v1.concat",
"tensorflow.compat.v1.equal",
"tensorflow.compat.v1.train.Checkpoint",
"tensorflow.compat.v1.math.top_k",
"tensorflow.compat.v1.math.logical_and",
"tensorflow.compat.v1.shape",
"tensorflow.compat.v1.math.greater_equal",
"tensorflow.compat.v1.keras.Sequential",
"tensorflow.compat.v1.keras.layers.Dense",
"tensorflow.compat.v1.constant",
"tensorflow.compat.v1.math.argmax",
"tensorflow.compat.v1.linalg.normalize",
"tensorflow.compat.v1.to_int32",
"tensorflow.compat.v1.ones",
"tensorflow.compat.v1.nn.sigmoid",
"tensorflow.compat.v1.math.multiply",
"tensorflow.compat.v1.reshape",
"tensorflow.compat.v1.reduce_sum",
"tensorflow.compat.v1.keras.layers.ReLU",
"tensorflow.compat.v1.math.count_nonzero",
"tensorflow.compat.v1.maximum",
"tensorflow.compat.v1.math.reduce_min",
"tensorflow.compat.v1.zeros_like",
"tensorflow.compat.v1.math.argmin",
"tensorflow.compat.v1.unstack",
"tensorflow.compat.v1.transpose",
"tensorflow.compat.v1.keras.layers.BatchNormalization",
"tensorflow.compat.v1.where",
"tensorflow.compat.v1.ones_like",
"tensorflow.compat.v1.keras.layers.UpSampling2D",
"tensorflow.compat.v1.split",
"tensorflow.compat.v1.map_fn",
"tensorflow.compat.v1.zeros",
"tensorflow.compat.v1.tile",
"tensorflow.compat.v1.nn.max_pool",
"tensorflow.compat.v1.cast",
"tensorflow.compat.v1.math.abs",
"tensorflow.compat.v1.math.squared_difference",
"tensorflow.compat.v1.keras.layers.Conv2D",
"tensorflow.compat.v1.stack",
"tensorflow.compat.v1.math.maximum",
"tensorflow.compat.v1.expand_dims",
"tensorflow.compat.v1.scatter_nd",
"tensorflow.compat.v1.keras.initializers.constant",
"tensorflow.compat.v1.gather",
"tensorflow.compat.v1.to_float",
"tensorflow.compat.v1.range",
"tensorflow.compat.v2.image.crop_and_resize",
"tensorflow.compat.v1.size",
"tensorflow.compat.v1.squeeze",
"tensorflow.compat.v1.math.sqrt"
],
[
"tensorflow.Variable",
"tensorflow.io.gfile.exists",
"tensorflow.train.Checkpoint",
"tensorflow.io.gfile.GFile",
"tensorflow.io.gfile.glob",
"tensorflow.io.gfile.makedirs",
"tensorflow.io.gfile.remove",
"tensorflow.io.gfile.rmtree",
"tensorflow.summary.scalar"
],
[
"tensorflow.keras.layers.LayerNormalization",
"tensorflow.keras.layers.Dropout",
"tensorflow.squeeze",
"tensorflow.keras.layers.experimental.EinsumDense",
"tensorflow.keras.layers.MultiHeadAttention",
"tensorflow.pad",
"tensorflow.keras.initializers.TruncatedNormal",
"tensorflow.keras.layers.Input"
],
[
"tensorflow.distribute.experimental.TPUStrategy",
"numpy.amax",
"tensorflow.constant",
"tensorflow.test.main",
"numpy.argmax",
"numpy.random.rand",
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.7",
"2.6",
"2.4",
"2.3",
"2.5",
"2.2"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"2.6",
"2.4",
"2.3",
"2.5",
"2.2"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
HapKoM/pyhowfar | [
"b12c248f696dc9bc2b50455b63a2b6ca7a440ba7"
] | [
"datasets/W300.py"
] | [
"from __future__ import print_function\n\nimport os\nimport numpy as np\nimport random\nimport math\nfrom skimage import io\n\nimport torch\nimport torch.utils.data as data\nimport torchfile\n\n# from utils.utils import *\nfrom utils.imutils import *\nfrom utils.transforms import *\n\n\nclass W300(data.Dataset):\n\n def __init__(self, args, split):\n self.nParts = 68\n self.pointType = args.pointType\n # self.anno = anno\n self.img_folder = args.data\n self.split = split\n self.is_train = True if self.split == 'train' else False\n self.anno = self._getDataFaces(self.is_train)\n self.total = len(self.anno)\n self.scale_factor = args.scale_factor\n self.rot_factor = args.rot_factor\n self.mean, self.std = self._comput_mean()\n\n def _getDataFaces(self, is_train):\n base_dir = self.img_folder\n dirs = os.listdir(base_dir)\n lines = []\n vallines = []\n\n if is_train:\n fid = open(os.path.join(base_dir, 'train.txt'), 'r')\n for line in fid.readlines():\n lines.append(line.strip())\n fid.close()\n else:\n fid = open(os.path.join(base_dir, 'test.txt'), 'r')\n for line in fid.readlines():\n vallines.append(line.strip())\n fid.close()\n\n if is_train:\n print('=> loaded train set, {} images were found'.format(len(lines)))\n return lines\n else:\n print('=> loaded validation set, {} images were found'.format(len(vallines)))\n return vallines\n\n def __len__(self):\n return self.total\n\n def __getitem__(self, index):\n inp, out, pts, c, s = self.generateSampleFace(index)\n self.pts, self.c, self.s = pts, c, s\n if self.is_train:\n return inp, out\n else:\n meta = {'index': index, 'center': c, 'scale': s, 'pts': pts,}\n return inp, out, meta\n\n def generateSampleFace(self, idx):\n sf = self.scale_factor\n rf = self.rot_factor\n\n main_pts = torchfile.load(\n os.path.join(self.img_folder, 'landmarks', self.anno[idx].split('_')[0],\n self.anno[idx][:-4] + '.t7'))\n pts = main_pts[0] if self.pointType == '2D' else main_pts[1]\n c = torch.Tensor((450 / 2, 450 / 2 + 50))\n s = 1.8\n\n img = load_image(\n os.path.join(self.img_folder, self.anno[idx].split('_')[0], self.anno[idx][:-8] +\n '.jpg'))\n\n r = 0\n if self.is_train:\n s = s * torch.randn(1).mul_(sf).add_(1).clamp(1 - sf, 1 + sf)[0]\n r = torch.randn(1).mul_(rf).clamp(-2 * rf, 2 * rf)[0] if random.random() <= 0.6 else 0\n\n if random.random() <= 0.5:\n img = torch.from_numpy(fliplr(img.numpy())).float()\n pts = shufflelr(pts, width=img.size(2), dataset='w300lp')\n c[0] = img.size(2) - c[0]\n\n img[0, :, :].mul_(random.uniform(0.7, 1.3)).clamp_(0, 1)\n img[1, :, :].mul_(random.uniform(0.7, 1.3)).clamp_(0, 1)\n img[2, :, :].mul_(random.uniform(0.7, 1.3)).clamp_(0, 1)\n\n inp = crop(img, c, s, [256, 256], rot=r)\n inp = color_normalize(inp, self.mean, self.std)\n\n tpts = pts.clone()\n out = torch.zeros(self.nParts, 64, 64)\n for i in range(self.nParts):\n if tpts[i, 0] > 0:\n tpts[i, 0:2] = to_torch(transform(tpts[i, 0:2] + 1, c, s, [64, 64], rot=r))\n out[i] = draw_labelmap(out[i], tpts[i] - 1, sigma=1)\n\n return inp, out, pts, c, s\n\n def _comput_mean(self):\n meanstd_file = './data/300W_LP/mean.pth.tar'\n if os.path.isfile(meanstd_file):\n ms = torch.load(meanstd_file)\n else:\n print(\"\\tcomputing mean and std for the first time, it may takes a while, drink a cup of coffe...\")\n mean = torch.zeros(3)\n std = torch.zeros(3)\n if self.is_train:\n for i in range(self.total):\n a = self.anno[i]\n img_path = os.path.join(self.img_folder, self.anno[i].split('_')[0],\n self.anno[i][:-8] + '.jpg')\n img = load_image(img_path)\n mean += img.view(img.size(0), -1).mean(1)\n std += img.view(img.size(0), -1).std(1)\n\n mean /= self.total\n std /= self.total\n ms = {\n 'mean': mean,\n 'std': std,\n }\n torch.save(ms, meanstd_file)\n if self.is_train:\n print('\\tMean: %.4f, %.4f, %.4f' % (ms['mean'][0], ms['mean'][1], ms['mean'][2]))\n print('\\tStd: %.4f, %.4f, %.4f' % (ms['std'][0], ms['std'][1], ms['std'][2]))\n return ms['mean'], ms['std']\n"
] | [
[
"torch.Tensor",
"torch.load",
"torch.zeros",
"torch.randn",
"torch.save"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
vijaysharmapc/Python-End-to-end-Data-Analysis | [
"a00f2d5d1547993e000b2551ec6a1360240885ba"
] | [
"Module1/Getting_Started_with_Data_Analysis_Code/4/annotate.py"
] | [
"#!/usr/bin/env python\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nx = np.linspace(-2.4, 0.4, 20)\ny = x * x + 2 * x + 1\nplt.plot(x, y, 'c', linewidth=2.0)\nplt.text(-1.5, 1.8, 'y=x^2 + 2*x + 1',\n fontsize=14, style='italic')\nplt.annotate('minima point', xy=(-1, 0),\n xytext=(-1, 0.3), horizontalalignment='center',\n verticalalignment='top', \n arrowprops=dict(arrowstyle='->', \n connectionstyle='arc3'))\n \nplt.savefig('annotate.png')"
] | [
[
"matplotlib.pyplot.plot",
"matplotlib.pyplot.text",
"matplotlib.pyplot.savefig",
"numpy.linspace"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
AYCHAIN/PracticalAI | [
"1657e31dfc60645f4f999475803f57c0ab9f1a2d",
"1657e31dfc60645f4f999475803f57c0ab9f1a2d"
] | [
"Section 4/04.02_omniscient_agent_webapp.py",
"Section 5/05.02_random_agent.py"
] | [
"from flask import Flask, redirect, render_template, url_for\nimport numpy as np\n\napp = Flask( __name__ )\n\[email protected]( '/home' )\ndef index():\n # retrieve the agent\n agent = app.config['AGENT']\n\n print( 'Episode: {}/{}'.format( agent.get_episode(), agent.get_episodes() ) )\n print( 'Trial: {}/{}'.format( agent.get_trial(), agent.get_trials() ) )\n if agent.get_episode() > agent.get_episodes():\n # episodes are over\n # compute the final prob\n prob_reward_array = agent.get_prob_reward_array()\n prob_01 = 100*np.round( prob_reward_array[0] / agent.get_episodes(), 2 )\n prob_02 = 100*np.round( prob_reward_array[1] / agent.get_episodes(), 2 )\n\n # avg the accumulated reward\n avg_accumulated_reward = agent.get_avg_accumulated_reward_array()\n\n # print the final \n print( '\\nProb Bandit 01:{}% - Prob Bandit 02:{}%'.format( prob_01, prob_02 ) )\n print( '\\n Avg accumulated reward: {}\\n'.format( np.mean( avg_accumulated_reward ) ) )\n\n # reset the episodes\n agent.reset_episode()\n\n elif agent.get_trial() > agent.get_trials():\n # trials are over\n # increase the episode\n agent.set_episode()\n\n # compute the partial results\n agent.set_prob_reward_array()\n\n # append the accumualted reward\n agent.set_append_accumulated_reward()\n\n # append the avg accumulated reward\n agent.set_append_avg_accumulated_reward()\n\n # reset the trial and initial variables\n agent.set_trial( reset=1 )\n\n # get the partial results\n partial_result = agent.get_prob_reward_array()\n prob_01 = partial_result[0] / agent.get_episode()\n prob_02 = partial_result[1] / agent.get_episode()\n\n # print the partial results\n print( '\\n Prob Bandit 01:{} - Prob Bandit 02:{}\\n'.format( prob_01, prob_02 ) )\n return redirect( url_for( 'index' ) )\n\n else:\n # trials are not over\n # code the omniscient agent\n bandit_machine = np.argmax( agent.get_prob_list() )\n\n # set the current bandit machine\n agent.set_current_bandit( bandit_machine )\n\n # pick up the web page\n if bandit_machine == 0: # red Yes button\n return render_template( 'layout_red.html' )\n else:\n return render_template( 'layout_blue.html' )\n\[email protected]( '/yes', methods=['POST'] )\ndef yes_event():\n agent = app.config['AGENT']\n\n # set the reward\n reward = 1\n\n # get the current bandit machine\n bandit_machine = agent.get_current_bandit()\n\n # add a reward to the bandit machine\n agent.set_reward_array( bandit_machine, reward )\n\n # increase how many times the bandit machine gets the lever pulled\n agent.set_bandit_array( bandit_machine )\n\n # sum the accumulated reward\n agent.set_accumulated_reward( reward )\n\n # increase the number of trial\n agent.set_trial( reset=0 )\n\n return redirect( url_for( 'index' ) )\n\[email protected]( '/no', methods=['POST'] )\ndef no_event():\n agent = app.config['AGENT']\n\n # set the reward\n reward = 0\n\n # get the current bandit machine\n bandit_machine = agent.get_current_bandit()\n\n # add a reward to the bandit machine\n agent.set_reward_array( bandit_machine, reward )\n\n # increase how many times the bandit machine gets the lever pulled\n agent.set_bandit_array( bandit_machine )\n\n # sum the accumulated reward\n agent.set_accumulated_reward( reward )\n\n # increase the number of trial\n agent.set_trial( reset=0 )\n return redirect( url_for( 'index' ) )\n\nif __name__ == \"__main__\":\n trials = 100\n episodes = 20\n\n prob_list = [0.3, 0.8]\n\n agent = OmniscientAgent( prob_list, trials, episodes )\n\n app.config['AGENT'] = agent\n app.run()\n\n",
"#import the libraries\nimport numpy as np\nimport random\n\n# class of random agent\nclass RandomAgent( object ):\n def __init__( self, prob_list ):\n self.prob_list = prob_list\n\n def pull( self, bandit_machine ):\n if np.random.random() < self.prob_list[ bandit_machine ]:\n reward = 1\n else:\n reward = 0\n\n return reward\n\n# prob list\nprob_list = [0.3, 0.8 ]\n\n# define the variable of the episode\ntrials = 1000\nepisodes = 200\n\nprob_reward_array = np.zeros( len( prob_list ) )\naccumulated_reward_array = list()\navg_accumulated_reward_array = list()\n\nbandit = RandomAgent( prob_list )\n\nfor episode in range( episodes ):\n if episode % 10 == 0:\n print( 'Episode: {} / {}'.format( episode, episodes ) )\n\n # initialize the variable\n reward_array = np.zeros( len( prob_list ) )\n bandit_array = np.full( len( prob_list ), 1.0e-5 )\n accumulated_reward = 0\n\n for trial in range( trials ):\n # define the random strategy\n bandit_machine = np.random.randint( low=0, high=2, size=1 )[0]\n\n # get the reward\n reward = bandit.pull( bandit_machine )\n\n # save the partial results\n reward_array[ bandit_machine ] += reward\n bandit_array[ bandit_machine ] += 1\n accumulated_reward += reward\n\n # compute the partial results\n prob_reward_array += reward_array / bandit_array\n accumulated_reward_array.append( accumulated_reward )\n avg_accumulated_reward_array.append( np.mean( accumulated_reward_array ) )\n\n# compute the final results\nprob_01 = 100*np.round( prob_reward_array[0] / episodes, 2 )\nprob_02 = 100*np.round( prob_reward_array[1] / episodes, 2 )\n\n# print the final results\nprint( '\\n Prob Bandit 01:{}% - Prob Bandit 02:{}%'.format( prob_01, prob_02 ) )\nprint( '\\n Avg accumulated reward: {}\\n'.format( np.mean( avg_accumulated_reward_array ) ) )\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
] | [
[
"numpy.mean"
],
[
"numpy.round",
"numpy.random.random",
"numpy.mean",
"numpy.random.randint"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
andrei-assa/pandas | [
"ded76dbbfdff3211cfff0ec7039611b50d531efb"
] | [
"pandas/core/indexes/extension.py"
] | [
"\"\"\"\nShared methods for Index subclasses backed by ExtensionArray.\n\"\"\"\nfrom typing import (\n Hashable,\n List,\n Type,\n TypeVar,\n Union,\n)\n\nimport numpy as np\n\nfrom pandas.compat.numpy import function as nv\nfrom pandas.errors import AbstractMethodError\nfrom pandas.util._decorators import (\n cache_readonly,\n doc,\n)\n\nfrom pandas.core.dtypes.cast import (\n find_common_type,\n infer_dtype_from,\n)\nfrom pandas.core.dtypes.common import (\n is_dtype_equal,\n is_object_dtype,\n pandas_dtype,\n)\nfrom pandas.core.dtypes.generic import (\n ABCDataFrame,\n ABCSeries,\n)\n\nfrom pandas.core.arrays import (\n Categorical,\n DatetimeArray,\n IntervalArray,\n PeriodArray,\n TimedeltaArray,\n)\nfrom pandas.core.arrays._mixins import NDArrayBackedExtensionArray\nfrom pandas.core.indexers import deprecate_ndim_indexing\nfrom pandas.core.indexes.base import Index\nfrom pandas.core.ops import get_op_result_name\n\n_T = TypeVar(\"_T\", bound=\"NDArrayBackedExtensionIndex\")\n\n\ndef inherit_from_data(name: str, delegate, cache: bool = False, wrap: bool = False):\n \"\"\"\n Make an alias for a method of the underlying ExtensionArray.\n\n Parameters\n ----------\n name : str\n Name of an attribute the class should inherit from its EA parent.\n delegate : class\n cache : bool, default False\n Whether to convert wrapped properties into cache_readonly\n wrap : bool, default False\n Whether to wrap the inherited result in an Index.\n\n Returns\n -------\n attribute, method, property, or cache_readonly\n \"\"\"\n attr = getattr(delegate, name)\n\n if isinstance(attr, property) or type(attr).__name__ == \"getset_descriptor\":\n # getset_descriptor i.e. property defined in cython class\n if cache:\n\n def cached(self):\n return getattr(self._data, name)\n\n cached.__name__ = name\n cached.__doc__ = attr.__doc__\n method = cache_readonly(cached)\n\n else:\n\n def fget(self):\n result = getattr(self._data, name)\n if wrap:\n if isinstance(result, type(self._data)):\n return type(self)._simple_new(result, name=self.name)\n elif isinstance(result, ABCDataFrame):\n return result.set_index(self)\n return Index(result, name=self.name)\n return result\n\n def fset(self, value):\n setattr(self._data, name, value)\n\n fget.__name__ = name\n fget.__doc__ = attr.__doc__\n\n method = property(fget, fset)\n\n elif not callable(attr):\n # just a normal attribute, no wrapping\n method = attr\n\n else:\n\n def method(self, *args, **kwargs):\n result = attr(self._data, *args, **kwargs)\n if wrap:\n if isinstance(result, type(self._data)):\n return type(self)._simple_new(result, name=self.name)\n elif isinstance(result, ABCDataFrame):\n return result.set_index(self)\n return Index(result, name=self.name)\n return result\n\n method.__name__ = name\n method.__doc__ = attr.__doc__\n return method\n\n\ndef inherit_names(names: List[str], delegate, cache: bool = False, wrap: bool = False):\n \"\"\"\n Class decorator to pin attributes from an ExtensionArray to a Index subclass.\n\n Parameters\n ----------\n names : List[str]\n delegate : class\n cache : bool, default False\n wrap : bool, default False\n Whether to wrap the inherited result in an Index.\n \"\"\"\n\n def wrapper(cls):\n for name in names:\n meth = inherit_from_data(name, delegate, cache=cache, wrap=wrap)\n setattr(cls, name, meth)\n\n return cls\n\n return wrapper\n\n\ndef _make_wrapped_comparison_op(opname: str):\n \"\"\"\n Create a comparison method that dispatches to ``._data``.\n \"\"\"\n\n def wrapper(self, other):\n if isinstance(other, ABCSeries):\n # the arrays defer to Series for comparison ops but the indexes\n # don't, so we have to unwrap here.\n other = other._values\n\n other = _maybe_unwrap_index(other)\n\n op = getattr(self._data, opname)\n return op(other)\n\n wrapper.__name__ = opname\n return wrapper\n\n\ndef make_wrapped_arith_op(opname: str):\n def method(self, other):\n if (\n isinstance(other, Index)\n and is_object_dtype(other.dtype)\n and type(other) is not Index\n ):\n # We return NotImplemented for object-dtype index *subclasses* so they have\n # a chance to implement ops before we unwrap them.\n # See https://github.com/pandas-dev/pandas/issues/31109\n return NotImplemented\n meth = getattr(self._data, opname)\n result = meth(_maybe_unwrap_index(other))\n return _wrap_arithmetic_op(self, other, result)\n\n method.__name__ = opname\n return method\n\n\ndef _wrap_arithmetic_op(self, other, result):\n if result is NotImplemented:\n return NotImplemented\n\n if isinstance(result, tuple):\n # divmod, rdivmod\n assert len(result) == 2\n return (\n _wrap_arithmetic_op(self, other, result[0]),\n _wrap_arithmetic_op(self, other, result[1]),\n )\n\n if not isinstance(result, Index):\n # Index.__new__ will choose appropriate subclass for dtype\n result = Index(result)\n\n res_name = get_op_result_name(self, other)\n result.name = res_name\n return result\n\n\ndef _maybe_unwrap_index(obj):\n \"\"\"\n If operating against another Index object, we need to unwrap the underlying\n data before deferring to the DatetimeArray/TimedeltaArray/PeriodArray\n implementation, otherwise we will incorrectly return NotImplemented.\n\n Parameters\n ----------\n obj : object\n\n Returns\n -------\n unwrapped object\n \"\"\"\n if isinstance(obj, Index):\n return obj._data\n return obj\n\n\nclass ExtensionIndex(Index):\n \"\"\"\n Index subclass for indexes backed by ExtensionArray.\n \"\"\"\n\n # The base class already passes through to _data:\n # size, __len__, dtype\n\n _data: Union[IntervalArray, NDArrayBackedExtensionArray]\n\n __eq__ = _make_wrapped_comparison_op(\"__eq__\")\n __ne__ = _make_wrapped_comparison_op(\"__ne__\")\n __lt__ = _make_wrapped_comparison_op(\"__lt__\")\n __gt__ = _make_wrapped_comparison_op(\"__gt__\")\n __le__ = _make_wrapped_comparison_op(\"__le__\")\n __ge__ = _make_wrapped_comparison_op(\"__ge__\")\n\n @property\n def _has_complex_internals(self) -> bool:\n # used to avoid libreduction code paths, which raise or require conversion\n return True\n\n # ---------------------------------------------------------------------\n # NDarray-Like Methods\n\n def __getitem__(self, key):\n result = self._data[key]\n if isinstance(result, type(self._data)):\n if result.ndim == 1:\n return type(self)(result, name=self.name)\n # Unpack to ndarray for MPL compat\n\n result = result._ndarray\n\n # Includes cases where we get a 2D ndarray back for MPL compat\n deprecate_ndim_indexing(result)\n return result\n\n def searchsorted(self, value, side=\"left\", sorter=None) -> np.ndarray:\n # overriding IndexOpsMixin improves performance GH#38083\n return self._data.searchsorted(value, side=side, sorter=sorter)\n\n # ---------------------------------------------------------------------\n\n def _get_engine_target(self) -> np.ndarray:\n return np.asarray(self._data)\n\n def delete(self, loc):\n \"\"\"\n Make new Index with passed location(-s) deleted\n\n Returns\n -------\n new_index : Index\n \"\"\"\n arr = self._data.delete(loc)\n return type(self)._simple_new(arr, name=self.name)\n\n def repeat(self, repeats, axis=None):\n nv.validate_repeat((), {\"axis\": axis})\n result = self._data.repeat(repeats, axis=axis)\n return type(self)._simple_new(result, name=self.name)\n\n def insert(self, loc: int, item):\n # ExtensionIndex subclasses must override Index.insert\n raise AbstractMethodError(self)\n\n def _validate_fill_value(self, value):\n \"\"\"\n Convert value to be insertable to underlying array.\n \"\"\"\n return self._data._validate_setitem_value(value)\n\n def _get_unique_index(self):\n if self.is_unique:\n return self\n\n result = self._data.unique()\n return self._shallow_copy(result)\n\n @doc(Index.map)\n def map(self, mapper, na_action=None):\n # Try to run function on index first, and then on elements of index\n # Especially important for group-by functionality\n try:\n result = mapper(self)\n\n # Try to use this result if we can\n if isinstance(result, np.ndarray):\n result = Index(result)\n\n if not isinstance(result, Index):\n raise TypeError(\"The map function must return an Index object\")\n return result\n except Exception:\n return self.astype(object).map(mapper)\n\n @doc(Index.astype)\n def astype(self, dtype, copy=True):\n dtype = pandas_dtype(dtype)\n if is_dtype_equal(self.dtype, dtype):\n if not copy:\n # Ensure that self.astype(self.dtype) is self\n return self\n return self.copy()\n\n if isinstance(dtype, np.dtype) and dtype.kind == \"M\" and dtype != \"M8[ns]\":\n # For now Datetime supports this by unwrapping ndarray, but DTI doesn't\n raise TypeError(f\"Cannot cast {type(self._data).__name__} to dtype\")\n\n new_values = self._data.astype(dtype, copy=copy)\n\n # pass copy=False because any copying will be done in the\n # _data.astype call above\n return Index(new_values, dtype=new_values.dtype, name=self.name, copy=False)\n\n @cache_readonly\n def _isnan(self) -> np.ndarray:\n # error: Incompatible return value type (got \"ExtensionArray\", expected\n # \"ndarray\")\n return self._data.isna() # type: ignore[return-value]\n\n @doc(Index.equals)\n def equals(self, other) -> bool:\n # Dispatch to the ExtensionArray's .equals method.\n if self.is_(other):\n return True\n\n if not isinstance(other, type(self)):\n return False\n\n return self._data.equals(other._data)\n\n\nclass NDArrayBackedExtensionIndex(ExtensionIndex):\n \"\"\"\n Index subclass for indexes backed by NDArrayBackedExtensionArray.\n \"\"\"\n\n _data: NDArrayBackedExtensionArray\n\n _data_cls: Union[\n Type[Categorical],\n Type[DatetimeArray],\n Type[TimedeltaArray],\n Type[PeriodArray],\n ]\n\n @classmethod\n def _simple_new(\n cls,\n values: NDArrayBackedExtensionArray,\n name: Hashable = None,\n ):\n assert isinstance(values, cls._data_cls), type(values)\n\n result = object.__new__(cls)\n result._data = values\n result._name = name\n result._cache = {}\n\n # For groupby perf. See note in indexes/base about _index_data\n result._index_data = values._ndarray\n\n result._reset_identity()\n return result\n\n def _get_engine_target(self) -> np.ndarray:\n return self._data._ndarray\n\n def insert(self: _T, loc: int, item) -> _T:\n \"\"\"\n Make new Index inserting new item at location. Follows\n Python list.append semantics for negative values.\n\n Parameters\n ----------\n loc : int\n item : object\n\n Returns\n -------\n new_index : Index\n\n Raises\n ------\n ValueError if the item is not valid for this dtype.\n \"\"\"\n arr = self._data\n try:\n code = arr._validate_scalar(item)\n except (ValueError, TypeError):\n # e.g. trying to insert an integer into a DatetimeIndex\n # We cannot keep the same dtype, so cast to the (often object)\n # minimal shared dtype before doing the insert.\n dtype, _ = infer_dtype_from(item, pandas_dtype=True)\n dtype = find_common_type([self.dtype, dtype])\n return self.astype(dtype).insert(loc, item)\n else:\n new_vals = np.concatenate(\n (\n arr._ndarray[:loc],\n np.asarray([code], dtype=arr._ndarray.dtype),\n arr._ndarray[loc:],\n )\n )\n new_arr = arr._from_backing_data(new_vals)\n return type(self)._simple_new(new_arr, name=self.name)\n\n def putmask(self, mask, value) -> Index:\n res_values = self._data.copy()\n try:\n res_values.putmask(mask, value)\n except (TypeError, ValueError):\n return self.astype(object).putmask(mask, value)\n\n return type(self)._simple_new(res_values, name=self.name)\n\n def _wrap_joined_index(self: _T, joined: np.ndarray, other: _T) -> _T:\n name = get_op_result_name(self, other)\n arr = self._data._from_backing_data(joined)\n return type(self)._simple_new(arr, name=name)\n"
] | [
[
"pandas.core.indexers.deprecate_ndim_indexing",
"pandas.core.dtypes.cast.infer_dtype_from",
"numpy.asarray",
"pandas.errors.AbstractMethodError",
"pandas.core.dtypes.common.pandas_dtype",
"pandas.core.dtypes.common.is_dtype_equal",
"pandas.core.dtypes.cast.find_common_type",
"pandas.core.indexes.base.Index",
"pandas.core.dtypes.common.is_object_dtype",
"pandas.core.ops.get_op_result_name",
"pandas.util._decorators.cache_readonly",
"pandas.util._decorators.doc",
"pandas.compat.numpy.function.validate_repeat"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
lanl/SEPIA | [
"0a1e606e1d1072f49e4f3f358962bd8918a5d3a3",
"0a1e606e1d1072f49e4f3f358962bd8918a5d3a3"
] | [
"examples/Ball_Drop/GenDataBallDrop1.py",
"sepia/SepiaLogLik.py"
] | [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jun 24 07:52:25 2020\nGenerate, Plot, and write all data needed for ball drop example 1\n@author: granthutchings\n\"\"\"\n#%% Imports\nimport numpy as np\n#import pyDOE # Latin Hypercube\nimport matplotlib.pyplot as plt\nfrom matplotlib.gridspec import GridSpec\nfrom mpl_toolkits.axes_grid1.inset_locator import inset_axes\nfrom invertH import invertHsim, invertHtrue\n\n#%% notes\n# x = R\n# theta = C\n# y = {h, t}, i.e., pairs of h and t that form a trace when plotted\n\n# imagine the field experiments involve say 4 platforms --> 4 values of h.\n# Then for each R, one experiment gives output of 4 h-t pairs (a curve).\n# Likewise for the simulator, we have a dense grid of say 100 heights h.\n# Then for each setting of {x, theta} = {R, C} we get output of 100 h-t\n# pairs.\n\n# I'll make python files to:\n# 1. generate the h-t pairs and write them into files. (this file and invertH.py)\n# 2. a \"runmcmc\"-type file that first calls...\n# 3. ...a file that reads in the data and packages it appropriately\n\n\n# generate \"field\" data and \"simulator\" data, where the simulator model is\n# systematically off from reality.\n\n# true: d2h/dt2 = g - C (dh/dt)^2 / R\n# sim: d2h/dt2 = g - C (dh/dt) / R\n\n# inputs for field experiments: x = R\n# inputs for simulator: x = R, theta = C\n# We want to calibrate theta in the simulator to match the field data.\n\n#%% Compute data\ndef gen_data(et,plot_design=False,R_new=None,R_design=None,C_design=None):\n n = 3; m = 25\n g = 9.8 # gravity\n C_true = .1 / (4 * np.pi / 3); print('generating data with C = ',C_true)\n n_field_heights = 4\n h_field = np.linspace(5,20,n_field_heights) # platform heights for the field experiments\n h_sim = np.arange(1.5,25,1.5) # grid of heights fed to the simulator\n h_dense = np.concatenate((np.arange(0,2,.01),np.arange(2,25,.5))) # a denser grid for drawing the curves\n\n # the coefficient of drag for a smooth sphere is 0.1, and we're\n # dividing by 4/3 pi to absorb a constant related to the volume of the\n # sphere (not including R)\n if R_new is None: R = np.array([.1, .2, .4]) # radii of balls to try (in meters)\n else: R = R_new\n\n # get a Latin hypercube sim_design of m=25 points over R_sim, C_sim\n #sim_design = pyDOE.lhs(2,m)\n\n # Use Kary's sim_designign for testing purposes\n sim_design = np.array([\n [0.1239, 0.8024],\n [0.8738, 0.6473],\n [0.6140, 0.3337],\n [0.8833, 0.4783],\n [0.9946, 0.0548],\n [0.1178, 0.9382],\n [0.1805, 0.2411],\n [0.6638, 0.2861],\n [0.2939, 0.1208],\n [0.2451, 0.2397],\n [0.4577, 0.5696],\n [0.4377, 0.8874],\n [0.0737, 0.7384],\n [0.6931, 0.8683],\n [0.4901, 0.7070],\n [0.5953, 0.9828],\n [0.7506, 0.1009],\n [0.7783, 0.4225],\n [0.8333, 0.5318],\n [0.3987, 0.6312],\n [0.2021, 0.4990],\n [0.3495, 0.3680],\n [0.9411, 0.7935],\n [0.0198, 0.0218],\n [0.5440, 0.1925]])\n \n # scale the first column to [0,.5] and call it R_sim\n # (this inclusim_design our field values, i.e., R \\in [0,.5])\n # scale the second column to [0.05,.25] and call it Csim\n # (likewise, Ctrue \\in [0.05, .25])\n sim_design[:,0] = sim_design[:,0] * .4 + .05\n sim_design[:,1] = sim_design[:,1] * .2 + .05\n if R_design is not None: R_sim = R_design\n else: R_sim = sim_design[:,0]\n if C_design is not None: C_sim = C_design\n else: C_sim = sim_design[:,1]\n if plot_design:\n plt.scatter(R_sim,C_sim)\n plt.xlabel(\"R design points\");plt.ylabel(\"C design points\")\n plt.title(\"Simulator Design\")\n plt.show()\n\n # Generate field data for each R\n y_field = invertHtrue(h_field, g, C_true, R, et) # observed times\n y_field_dense = invertHtrue(h_dense, g, C_true, R, et) # dense grid for plots\n\n # imagine that the biggest ball is too big to get to the highest\n # platform, so we don't observe data there\n #y_field[-1,-1] = np.nan\n\n # Generate simulated data for each (C,R) pair\n y_sim = invertHsim(h_sim, g, C_sim, R_sim)\n y_sim_dense = invertHsim(h_dense, g, C_sim, R_sim)\n \n data_dict = dict([('R',R),('sim_design',np.column_stack((R_sim,C_sim))),\\\n ('n',n),('m',m),('C_true',C_true),\\\n ('h_field',h_field),('h_sim',h_sim),('h_dense',h_dense),\\\n ('y_field',y_field),('y_field_dense',y_field_dense),\\\n ('y_sim',y_sim),('y_sim_dense',y_sim_dense)])\n \n return(data_dict)\n\n#%% #===================== Plots ===============================#\ndef plot_data(data_dict,inset=True,near_sim=True):\n n = data_dict['n']\n m = data_dict['m']\n y_sim = data_dict['y_sim']\n y_field = data_dict['y_field']\n R = data_dict['R']\n R_sim = data_dict['sim_design'][:,0]\n C_sim = data_dict['sim_design'][:,1]\n h_field = data_dict['h_field']\n h_sim = data_dict['h_sim']\n h_dense = data_dict['h_dense']\n y_field = data_dict['y_field']\n y_field_dense = data_dict['y_field_dense']\n y_sim = data_dict['y_sim']\n y_sim_dense = data_dict['y_sim_dense']\n \n if isinstance(y_field, list): ragged = True\n else: ragged = False\n \n if ragged:\n y_max = max(max(np.array([np.max(k) for k in y_field])),max(y_sim.max(1)))\n else:\n y_max = max(max(y_field.max(1)),max(y_sim.max(1))) # max of all row maxes for axis limit\n # find closest values each R\n # ith column of R_nearest_sim_design contains the n_neighbors nearest sim_designign points (by index)\n # for ith value of R\n n_neighbors = 3\n R_nearest_sim_design = np.zeros(shape=(n_neighbors,len(R)),dtype=int)\n for i in range(len(R)):\n dist = np.argsort(np.abs(R_sim-R[i]))\n R_nearest_sim_design[:,i] = dist[0:n_neighbors]\n\n # Generate plot for each radius\n colors = ('r', 'g', 'b')\n fig = plt.figure(figsize=[12,12],constrained_layout=True)\n gs = GridSpec(2,2,figure=fig)\n axs = np.array([fig.add_subplot(gs[0,0]),\\\n fig.add_subplot(gs[0,1]),\\\n fig.add_subplot(gs[1,0])])\n for i in range(len(R)):\n # axis limits, ticks, and labels\n axs[i].set_xlim([0, 25])\n axs[i].set_ylim([0, y_max+.5])\n axs[i].xaxis.set_ticks(np.arange(0,30,5))\n axs[i].yaxis.set_ticks(np.arange(0,y_max+.5,1))\n axs[i].set_title(\"Ball Radius {} m\".format(R[i]),fontweight=\"bold\")\n axs[i].set_xlabel(\"Distance (m)\")\n axs[i].set_ylabel(\"Time (s)\")\n\n # simulations - all\n for j in range(m):\n axs[i].plot(h_dense, np.transpose(y_sim_dense)[:,j],color='lightgreen',\\\n label=\"Simulation runs\" if j==0 else \"\")\n\n if near_sim:\n # simulations - nearest neighbors\n for j in range(n_neighbors):\n axs[i].plot(h_dense,np.transpose(y_sim_dense)[:,R_nearest_sim_design[j,i]],\\\n linestyle=\"--\",\\\n color=colors[j],label=\"Nearest Sim {}\".format(j+1))\n\n # true data curve and \"real data points\"\n axs[i].plot(h_dense, y_field_dense[i,:],'k',label=\"Reality\")\n if ragged:\n axs[i].plot(h_field[i],y_field[i],'ks',label='Reality')\n else:\n axs[i].plot(h_field, y_field[i,],'ks',label=\"Field data\")\n\n\n axs[i].legend(loc=\"lower right\")\n\n\n if inset:\n # imbed sim_designign point subplot\n inset_ax = inset_axes(axs[i],width=\"30%\",height=\"30%\",loc=\"upper left\",\\\n borderpad=2.5)\n inset_ax.set_xlabel(\"R sim_design values\",fontsize=7,labelpad=1)\n inset_ax.set_ylabel(\"C sim_design values\",fontsize=7)\n inset_ax.xaxis.set_ticks(R)\n inset_ax.yaxis.set_ticks(np.arange(0,.251,.05))\n inset_ax.tick_params(axis='both', which='major', labelsize=7, pad = -5)\n inset_ax.scatter(R_sim,C_sim,s=15, facecolors='none', edgecolors='grey')\n inset_ax.scatter(R_sim[R_nearest_sim_design[:,i]],C_sim[R_nearest_sim_design[:,i]],s=15,\\\n color=colors)\n inset_ax.axvline(x=R[i], ymin=0, ymax=1,color='k',linewidth=.5)\n plt.savefig('data/plotAll.png', dpi=300)\n plt.show()\n\n#%% #==================== Write data ===========================#\n# write the h-t pairs into files\ndef write_data(data_dict, datadir = '/Users/granthutchings/Documents/LANL/SEPIA/sepia/Examples/Ball_Drop/data/ball_drop_1'):\n # datadir == directory where data files should be written to or read from\n\n # sim.dat, should be length(hsim) x length(Csim)\n y_sim = data_dict['y_sim']\n with open(datadir+'sim.dat',\"w+\") as f:\n for line in np.array(np.transpose(y_sim)):\n np.savetxt(f, line)\n\n # sim.height, a file with just the heights (same for all sim runs)\n h_sim = data_dict['h_sim']\n with open(datadir+'sim.height',\"w+\") as f:\n for line in np.array(np.transpose(h_sim)):\n np.savetxt(f, line)\n\n # sim.sim_designign, length(Csim) x (num X's + num thetas)\n R_sim = data_dict['R_sim']; C_sim = data_dict['C_sim'] \n sim_design = np.transpose(np.array([R_sim, C_sim]))\n with open(datadir+'sim.design',\"w+\") as f:\n for line in sim_design:\n np.savetxt(f, line)\n\n # field.dat, one row per experiment (radius)\n y_field = data_dict['y_field']\n with open(datadir+'field.dat',\"w+\") as f:\n for line in np.array(y_field):\n np.savetxt(f, line)\n\n # field.height\n h_field = data_dict['h_field']\n with open(datadir+'field.height',\"w+\") as f:\n for line in np.array(h_field):\n np.savetxt(f, line)\n\n # field radii\n R = data_dict['R']\n with open(datadir+'field.radii',\"w+\") as f:\n for line in np.array(R):\n np.savetxt(f, line)\n \n#%%\ndef read_data(datadir = '/Users/granthutchings/Documents/LANL/SEPIA/sepia/Examples/Ball_Drop/data/ball_drop_1'):\n \n with open(datadir+'sim.dat','r') as f:\n y_sim = np.loadtxt(f)\n with open(datadir+'sim.height',\"r\") as f:\n h_sim = np.loadtxt(f)\n with open(datadir+'sim.design','r') as f:\n sim_design = np.loadtxt(f)\n with open(datadir+'field.dat','r') as f:\n y_field = np.loadtxt(f)\n with open(datadir+'field.height','r') as f:\n h_field = np.loadtxt(f)\n with open(datadir+'field.radii','r') as f:\n R = np.loadtxt(f)\n \n data_dict = dict([('R',R),('sim_design',sim_design),\\\n ('h_field',h_field),('h_sim',h_sim),\\\n ('y_field',y_field),('y_sim',y_sim)])\n \n return(data_dict)\n \n \n \n \n \n",
"import numpy as np\nimport scipy.linalg\n\nfrom sepia.SepiaDistCov import SepiaDistCov\n\ndef compute_log_lik(g, cvar='all', cindex=None):\n \"\"\"\n Compute log likelihood for model g. Returns value and also stores it in g.num.logLik.\n\n :param sepia.SepiaModel g: instantiated `sepia.SepiaModel` object\n :param string cvar: name of changed parameter (used to avoid recomputing things that won't have changed since last call), or 'all'\n :param int/NoneType cindex: index (of flattened parameter array) of changed variable (to avoid recomputing things), or None to assume all indices changed\n :return: numeric log likelihood value\n :raises ValueError: if invalid cvar parameter used\n \"\"\"\n\n if g.verbose:\n print('Entering SepiaLogLik')\n\n def doLogLik(cov, w):\n try:\n chCov = scipy.linalg.cholesky(cov, lower=True)\n except np.linalg.LinAlgError:\n print('chol error')\n return -np.inf\n logDet = np.sum(np.log(np.diag(chCov))) # log sqrt(det)\n if g.verbose:\n print('in doLogLik chCov shape ', chCov.shape, ' w shape ', w.shape)\n # cho_solve cuts time almost in half compared to lstsq method\n p1 = scipy.linalg.cho_solve((chCov, True), w)\n L = -logDet - 0.5 * np.sum(p1 * w)\n return L\n\n # calculate the equivalent quadratic form of kron separable data\n def sepQuadFormCalc(V,zp):\n # calculate right side of the kronecker quadratic form solve\n dlen,mlen=zp.shape\n zpo=np.empty((dlen,mlen))\n for jj in range(mlen):\n zt=zp[:,jj]\n for ii in range(len(V)-1,-1,-1):\n Vsize=V[ii].shape[1]\n zt=np.linalg.solve(V[ii],zt.reshape((Vsize,int(dlen/Vsize)),order='F') ).T\n zpo[:,jj]=zt.reshape(-1,order='F')\n return zpo\n\n def doLogLikSep(Sigma, nugget, data):\n # eigen decomposition of the blocks\n V=[None]*len(Sigma)\n D=[None]*len(Sigma)\n for ii in range(len(Sigma)):\n D[ii], V[ii] = np.linalg.eigh(Sigma[ii])\n #V[ii]=np.flip(V[ii]) # these are for detailed numerical comparison to gpmsa\n #D[ii]=np.flip(D[ii]) # (but doesn't lead to the correct final answer in python)\n # determinant from eigenvalues\n dkron=D[-1]\n for ii in range(len(D)-2,-1,-1):\n dkron=np.kron(D[ii],dkron)\n logDet=np.sum(np.log(dkron+nugget))\n\n #Log Likelihood\n zp=sepQuadFormCalc(V,data)\n Dki2=1/np.sqrt(dkron + nugget)\n zp2=zp * Dki2.T\n L=-0.5*logDet-0.5*(zp2.T @ zp2) # here it is ...\n\n return L,V,Dki2\n\n num=g.num # the model numerical components\n #extract some frequently accessed immuts\n n=num.n; m=num.m; p=num.p; q=num.q\n pu=num.pu; pv=num.pv\n pv=pv # temp to get the unused var lint to stop\n\n # The precomputation steps\n do_theta=do_betaV=do_lamVz=do_betaU=do_lamUz=do_lamWs=do_lamWOs=do_Gamma = False\n if cvar == 'all':\n do_theta=do_betaV=do_lamVz=do_betaU=do_lamUz=do_lamWs=do_lamWOs=do_Gamma = True\n elif cvar == 'theta': do_theta = True\n elif cvar == 'betaV': do_betaV = True\n elif cvar == 'lamVz': do_lamVz = True\n elif cvar == 'betaU': do_betaU = True\n elif cvar == 'lamUz': do_lamUz = True\n elif cvar == 'lamWs': do_lamWs = True\n elif cvar == 'lamWOs': do_lamWOs = True\n elif cvar == 'lamOs': pass\n elif cvar == 'gamma': do_Gamma = True\n else:\n raise ValueError('Invalid computeLogLik input cvar')\n\n # These are both related to recalculating x dists, whether with theta or not\n if num.sim_only and cvar == 'all': # calculating everything\n num.xDist = SepiaDistCov(g.data.x, cat_ind=[])\n elif do_theta: # calculating everything involving theta [note this includes the case 'all']\n xt_tmp = np.concatenate((g.data.x, np.tile(g.params.theta.val, (n, 1))), axis=1)\n num.xDist = SepiaDistCov(xt_tmp, cat_ind=np.concatenate([g.data.x_cat_ind, g.data.t_cat_ind]))\n # the connection to theta variables:\n num.xzDist = SepiaDistCov(xt_tmp, g.data.zt, \n cat_ind=np.concatenate([g.data.x_cat_ind, g.data.t_cat_ind])) \n\n # check if we're in a kron separable data definition\n if g.data.sep_design:\n ztSep=g.data.ztSep\n ztSepDist=g.num.ztSepDist\n else:\n ztSep=False\n\n # % Four parts to compute: Sig_v, Sig_u, Sig_w, and the Sig_uw crossterm\n\n if do_theta or do_betaU or do_lamUz or do_lamWs:\n SigU = []\n lamUz_val = g.params.lamUz.val\n lamWs_val = g.params.lamWs.val\n betaU_val = g.params.betaU.val\n for jj in range(pu):\n SigU.append(num.xDist.compute_cov_mat(betaU_val[:, jj], lamUz_val[0, jj]))\n np.fill_diagonal(SigU[jj], SigU[jj].diagonal() + 1/lamWs_val[0, jj])\n num.SigU = SigU\n else:\n SigU = num.SigU\n\n if (do_betaU or do_lamUz or do_lamWs or do_lamWOs or do_Gamma):\n if cvar in ['all', 'lamWOs', 'gamma']: jinds = np.arange(pu)\n elif cvar == 'betaU': jinds = [int(np.ceil( (cindex+1)/(p+q) ) - 1)]\n elif cvar in ['lamUz', 'lamWs']: jinds = [cindex]\n\n lamUz_val = g.params.lamUz.val\n betaU_val = g.params.betaU.val\n if ztSep==False:\n ztDistCov = num.ztDist.compute_cov_mat\n LamSim = num.LamSim\n lamWOs_val = g.params.lamWOs.val\n lamWs_val = g.params.lamWs.val\n\n if not g.data.mean_basis:\n w = num.w\n else:\n w = num.w - g.data.sim_data.H @ g.params.gamma.val\n if g.verbose:\n print('num.w:',num.w)\n print('w:',w)\n print('H:',g.data.sim_data.H)\n print('gamma:',g.params.gamma.val)\n\n for jj in jinds:\n if ztSep==False: # not kronecker dataset\n cg = ztDistCov(betaU_val[:, jj], lamUz_val[0, jj])\n np.fill_diagonal(cg, cg.diagonal() + 1/(LamSim[jj] * lamWOs_val) + 1/lamWs_val[0, jj])\n # calculate the SigW likelihood for each block\n num.SigWl[jj] = doLogLik(cg, w[jj*m:(jj+1)*m, 0])\n # calculate the SigW inverse for each block\n if n > 0: # only needed for a calibration model\n if g.verbose:\n print('In computeLogLik: shape of cg ', cg.shape)\n num.SigWi[jj] = np.linalg.inv(cg)\n else: # kronecker dataset, compute as kron'd blocks\n segVarStart=0\n cg=[]\n for ii in range(len(ztSep)):\n segVarInds=np.arange(segVarStart,segVarStart + ztSepDist[ii].p)\n segVarStart=segVarStart+ ztSepDist[ii].p\n if ii==0: # ensure that lamUz is only counted once\n cg.append(ztSepDist[ii].compute_cov_mat(betaU_val[segVarInds,jj],lamUz_val[0,jj]))\n else:\n cg.append(ztSepDist[ii].compute_cov_mat(betaU_val[segVarInds,jj],1))\n cgNugget=1/(LamSim[jj]*lamWOs_val) + 1/lamWs_val[0,jj]\n num.SigWl[jj], num.V[jj], num.Dki2[jj] = \\\n doLogLikSep(cg,cgNugget,w[jj*m:(jj+1)*m, 0:1])\n \n # The computation is decomposed into the likelihood of W,\n # and the likelihood of VU|W. \n\n # Compute the likelihood of the W part (have already done the blocks)\n LogLikW = np.sum(num.SigWl)\n\n # only if there are observations do we have the VU|W part. \n if not num.sim_only:\n\n # Compute the likelihood of the VU|W\n if do_theta or do_betaU or do_lamUz:\n SigUW=[]\n betaU_val = g.params.betaU.val\n lamUz_val = g.params.lamUz.val\n for jj in range(pu):\n SigUW.append(num.xzDist.compute_cov_mat(betaU_val[:, jj:(jj + 1)], lamUz_val[0, jj]))\n num.SigUW = SigUW\n else:\n SigUW = num.SigUW\n\n # do these ops, on the block diagonal blocks:\n # W=SigUW*model.SigWi;\n # SigUgW=SigU-W*SigUW';\n W = [None]*pu\n SigUgW = [None]*pu\n SigWi = num.SigWi\n for ii in range(pu):\n if ztSep==False:\n W_tmp = SigUW[ii] @ SigWi[ii]\n W[ii] = W_tmp\n SigUgW[ii] = SigU[ii] - W_tmp @ SigUW[ii].T\n else:\n # computation for a kron/separable design\n zp=np.zeros( (m,n) )\n for jj in range(n):\n zp[:,jj]=np.squeeze(sepQuadFormCalc(num.V[ii],SigUW[ii][jj,:].reshape(-1,1)))\n zp2=zp * num.Dki2[ii].T\n SigUgW[ii]=SigU[ii] - zp2.T @ zp2\n W[ii]=zp2.T\n \n if (do_betaV or do_lamVz) and pv > 0:\n SigV = []\n betaV_val = g.params.betaV.val\n lamVz_val = g.params.lamVz.val\n for jj in range(num.lamVzGnum):\n SigV.append(num.x0Dist.compute_cov_mat(betaV_val[:, jj:(jj + 1)], lamVz_val[0, jj]))\n num.SigV = SigV\n else:\n SigV = num.SigV\n\n #for scalar output: SigVUgW=[SigV+SigUgW] ...\n # + model.SigObs/lamOs;\n #otherwise: SigVUgW=[SigV zeros(n*pv,n*pu); ...\n # zeros(n*pu,n*pv) SigUgW ] ...\n # + model.SigObs/lamOs;\n SigVUgW = num.SigObs/g.params.lamOs.val\n for ii in range(pv):\n SigVUgW[ii*n:(ii+1)*n, ii*n:(ii+1)*n] = \\\n SigVUgW[ii*n:(ii+1)*n, ii*n:(ii+1)*n] + SigV[num.lamVzGroup[ii]]\n\n if num.scalar_out:\n for ii in range(pu):\n SigVUgW[ii*n:(ii+1)*n, ii*n:(ii+1)*n] = \\\n SigVUgW[ii*n:(ii+1)*n, ii*n:(ii+1)*n] + SigUgW[ii]\n else:\n for ii in range(pu):\n SigVUgW[n*pv+ii*n:n*pv+(ii+1)*n, n*pv+ii*n:n*pv+(ii+1)*n] = \\\n SigVUgW[n*pv+ii*n:n*pv+(ii+1)*n, n*pv+ii*n:n*pv+(ii+1)*n] + SigUgW[ii]\n\n # do this op: MuVUgW =W*model.w;\n MuVUgW = np.zeros((n*pu, 1))\n\n if not g.data.mean_basis:\n w = num.w\n u = num.u\n else:\n w = num.w - g.data.sim_data.H @ g.params.gamma.val\n u = num.u - g.data.make_obs_mean_basis(g.params.theta.val) @ g.params.gamma.val\n for ii in range(pu):\n if ztSep==False:\n MuVUgW[ii*n:(ii+1)*n, 0] = W[ii] @ w[ii*m:(ii+1)*m, 0]\n else:\n # computation for a kron/separable design\n zp=sepQuadFormCalc(num.V[ii], w[ii*m:(ii+1)*m, 0].reshape(-1,1))\n zp2=zp * num.Dki2[ii].T\n MuVUgW[ii*n:(ii+1)*n, 0]=np.squeeze(W[ii] @ zp2)\n\n # for scalar output: MuDiff= [u] - [MuVUgW]\n # otherwise: MuDiff= [v;u] - [0;MuVUgW] \n if num.scalar_out:\n MuDiff = u - MuVUgW\n else:\n #MuDiff=num.vu \n #print( (MuDiff[pv*n:,0]).shape )\n #MuDiff[pv*n:,0]=MuDiff[pv*n:,0]-MuVUgW\n MuDiff = np.concatenate((num.v, u - MuVUgW), axis=0)\n # todo: is this a better operation than add-in place to\n # the u component of pre-concatenated vu?\n\n # Now we can get the LL of VU|W\n LogLikVUgW = doLogLik(SigVUgW, MuDiff)\n\n else: #test on whether we have observations - not sim_only\n LogLikVUgW=0\n \n # Final Answer, LL(VU) = LL(VU|W) + LL(W)\n num.logLik = LogLikVUgW + LogLikW\n \n return num.logLik\n\n"
] | [
[
"numpy.abs",
"numpy.linspace",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.title",
"numpy.arange",
"matplotlib.pyplot.savefig",
"numpy.max",
"matplotlib.pyplot.ylabel",
"numpy.loadtxt",
"matplotlib.gridspec.GridSpec",
"numpy.transpose",
"numpy.savetxt",
"matplotlib.pyplot.xlabel",
"numpy.array",
"numpy.column_stack",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
],
[
"numpy.diag",
"numpy.log",
"numpy.sqrt",
"numpy.linalg.inv",
"numpy.arange",
"numpy.squeeze",
"numpy.kron",
"numpy.tile",
"numpy.concatenate",
"numpy.ceil",
"numpy.linalg.eigh",
"numpy.zeros",
"numpy.sum",
"numpy.empty"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
kmohrman/coffea | [
"2baae94028c38b59f0eb52127d8fb92840dbf23d"
] | [
"coffea/lookup_tools/dense_lookup.py"
] | [
"from coffea.lookup_tools.lookup_base import lookup_base\n\nimport numpy\nfrom copy import deepcopy\n\n\nclass dense_lookup(lookup_base):\n def __init__(self, values, dims, feval_dim=None):\n super(dense_lookup, self).__init__()\n self._dimension = 0\n whattype = type(dims)\n if whattype == numpy.ndarray:\n self._dimension = 1\n else:\n self._dimension = len(dims)\n if self._dimension == 0:\n raise Exception(\"Could not define dimension for {}\".format(whattype))\n self._axes = deepcopy(dims)\n self._feval_dim = None\n vals_are_strings = (\n \"string\" in values.dtype.name\n or \"str\" in values.dtype.name\n or \"unicode\" in values.dtype.name\n or \"bytes\" in values.dtype.name\n ) # ....\n if not isinstance(values, numpy.ndarray):\n raise TypeError(\"values is not a numpy array, but %r\" % type(values))\n if vals_are_strings:\n raise Exception(\"dense_lookup cannot handle string values!\")\n self._values = deepcopy(values)\n\n def _evaluate(self, *args):\n indices = []\n if self._dimension == 1:\n indices.append(\n numpy.clip(\n numpy.searchsorted(self._axes, args[0], side=\"right\") - 1,\n 0,\n self._values.shape[0] - 1,\n )\n )\n else:\n for dim in range(self._dimension):\n indices.append(\n numpy.clip(\n numpy.searchsorted(self._axes[dim], args[dim], side=\"right\")\n - 1,\n 0,\n self._values.shape[dim] - 1,\n )\n )\n return self._values[tuple(indices)]\n\n def __repr__(self):\n myrepr = \"{} dimensional histogram with axes:\\n\".format(self._dimension)\n temp = \"\"\n if self._dimension == 1:\n temp = \"\\t1: {}\\n\".format(self._axes)\n else:\n temp = \"\\t1: {}\\n\".format(self._axes[0])\n for idim in range(1, self._dimension):\n temp += \"\\t{}: {}\\n\".format(idim + 1, self._axes[idim])\n myrepr += temp\n return myrepr\n"
] | [
[
"numpy.searchsorted"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
dataiku/dss-plugin-timeseries-preparation | [
"bdb662c909a0ad6d7845325a70e3dac2bdcc6b28",
"bdb662c909a0ad6d7845325a70e3dac2bdcc6b28"
] | [
"tests/python/unit/dku_timeseries/resampling/test_resampler_helpers.py",
"tests/python/unit/dku_timeseries/windowing/test_windowing_long_format.py"
] | [
"import numpy as np\nimport pandas as pd\nimport pytest\n\nfrom dku_timeseries.timeseries_helpers import generate_date_range, get_date_offset\nfrom recipe_config_loading import get_resampling_params\n\n\[email protected]\ndef config():\n config = {u'clip_end': 0, u'constant_value': 0, u'extrapolation_method': u'none', u'shift': 0, u'time_unit_end_of_week': u'SUN',\n u'datetime_column': u'Date', u'advanced_activated': False, u'time_unit': u'quarters', u'clip_start': 0, u'time_step': 2,\n u'interpolation_method': u'linear'}\n return config\n\n\nclass TestResamplerHelpers:\n def test_date_offset(self):\n time_unit = \"business_days\"\n offset_value = 0\n sunday = pd.Timestamp('2021-01-31 10:00:00')\n offset = get_date_offset(time_unit, offset_value)\n assert sunday + offset == sunday\n\n sunday = pd.Timestamp('2021-01-31 00:00:00')\n offset = get_date_offset(time_unit, 1)\n assert sunday + offset == pd.Timestamp('2021-02-01 00:00:00')\n assert sunday - offset == pd.Timestamp('2021-01-29 00:00:00')\n assert sunday + offset + offset == pd.Timestamp('2021-02-02 00:00:00')\n\n friday = pd.Timestamp('2021-01-29 00:00:00')\n offset = get_date_offset(time_unit, 1)\n assert friday + offset == pd.Timestamp('2021-02-01 00:00:00')\n\n friday = pd.Timestamp('2021-01-29 00:00:00')\n offset = get_date_offset(time_unit, 2)\n assert friday + offset == pd.Timestamp('2021-02-02 00:00:00')\n\n saturday = pd.Timestamp('2021-01-30 00:00:00')\n offset = get_date_offset(time_unit, 1)\n assert saturday + offset == pd.Timestamp('2021-02-01 00:00:00')\n\n saturday = pd.Timestamp('2021-02-04 00:00:00')\n offset = get_date_offset(time_unit, 1)\n assert saturday + offset == pd.Timestamp('2021-02-05 00:00:00')\n\n def test_generate_date_range_month(self, config):\n config[\"time_unit\"] = \"months\"\n params = get_resampling_params(config)\n frequency = params.resampling_step\n time_unit = params.time_unit\n time_step = params.time_step\n\n end_time = pd.Timestamp('2021-06-20 00:00:00')\n\n start_time = pd.Timestamp('2021-01-31 00:00:00')\n date_range = generate_date_range(start_time, end_time, 0, 0, 0, frequency, time_step, time_unit)\n np.testing.assert_array_equal(date_range, pd.DatetimeIndex(['2021-01-31', '2021-03-31', '2021-05-31', '2021-07-31']))\n\n start_time = pd.Timestamp('2021-01-23 00:00:00')\n date_range = generate_date_range(start_time, end_time, 0, 0, 0, frequency, time_step, time_unit)\n np.testing.assert_array_equal(date_range, pd.DatetimeIndex(['2021-01-31', '2021-03-31', '2021-05-31', '2021-07-31']))\n\n start_time = pd.Timestamp('2021-01-31 10:00:00')\n date_range = generate_date_range(start_time, end_time, 0, 0, 0, frequency, time_step, time_unit)\n np.testing.assert_array_equal(date_range, pd.DatetimeIndex(['2021-01-31', '2021-03-31', '2021-05-31', '2021-07-31']))\n\n start_time = pd.Timestamp('2021-01-31 10:00:00').tz_localize(\"CET\")\n end_time = pd.Timestamp('2021-06-20 00:00:00').tz_localize(\"CET\")\n date_range = generate_date_range(start_time, end_time, 0, 0, 0, frequency, time_step, time_unit)\n np.testing.assert_array_equal(date_range, pd.DatetimeIndex(\n ['2021-01-31 00:00:00+01:00', '2021-03-31 00:00:00+02:00', '2021-05-31 00:00:00+02:00', '2021-07-31 00:00:00+02:00']))\n\n start_time = pd.Timestamp('2021-01-31 10:00:00')\n end_time = pd.Timestamp('2021-06-20 00:00:00')\n date_range = generate_date_range(start_time, end_time, 1, 0, 1, frequency, time_step, time_unit)\n np.testing.assert_array_equal(date_range, pd.DatetimeIndex(['2021-03-31', '2021-05-31', '2021-07-31']))\n\n def test_generate_date_range_week(self, config):\n config[\"time_unit\"] = \"weeks\"\n params = get_resampling_params(config)\n frequency = params.resampling_step\n time_unit = params.time_unit\n time_step = params.time_step\n\n start_time = pd.Timestamp('2020-12-23 00:00:00')\n end_time = pd.Timestamp('2021-01-18 00:00:00')\n\n date_range = generate_date_range(start_time, end_time, 0, 0, 0, frequency, time_step, time_unit)\n np.testing.assert_array_equal(date_range, pd.DatetimeIndex(['2020-12-27', '2021-01-10', '2021-01-24']))\n\n end_time = pd.Timestamp('2021-01-24 00:00:00')\n date_range = generate_date_range(start_time, end_time, 0, 0, 0, frequency, time_step, time_unit)\n np.testing.assert_array_equal(date_range, pd.DatetimeIndex(['2020-12-27', '2021-01-10', '2021-01-24', '2021-02-07']))\n\n date_range = generate_date_range(start_time, end_time, 1, 0, 1, frequency, time_step, time_unit)\n np.testing.assert_array_equal(date_range, pd.DatetimeIndex(['2021-01-10', '2021-01-24', '2021-02-07']))\n\n config[\"time_unit\"] = \"weeks\"\n config[\"time_unit_end_of_week\"] = \"WED\"\n params = get_resampling_params(config)\n frequency = params.resampling_step\n time_unit = params.time_unit\n time_step = params.time_step\n date_range = generate_date_range(start_time, end_time, 0, 0, 0, frequency, time_step, time_unit)\n np.testing.assert_array_equal(date_range, pd.DatetimeIndex(['2020-12-23', '2021-01-6', '2021-01-20', '2021-02-03']))\n\n def test_generate_date_range_quarters(self, config):\n config[\"time_step\"] = 1\n config[\"time_unit\"] = \"quarters\"\n start_time = pd.Timestamp('2020-01-23 00:00:00')\n end_time = pd.Timestamp('2021-01-18 00:00:00')\n\n params = get_resampling_params(config)\n frequency = params.resampling_step\n time_unit = params.time_unit\n time_step = params.time_step\n\n date_range = generate_date_range(start_time, end_time, 0, 0, 0, frequency, time_step, time_unit)\n np.testing.assert_array_equal(date_range, pd.DatetimeIndex(['2020-01-31', '2020-04-30', '2020-07-31', '2020-10-31', '2021-01-31']))\n\n def test_generate_date_range_half_year(self, config):\n config[\"time_step\"] = 1\n config[\"time_unit\"] = \"semi_annual\"\n start_time = pd.Timestamp('2020-01-01 00:00:00')\n end_time = pd.Timestamp('2021-06-18 00:00:00')\n\n params = get_resampling_params(config)\n frequency = params.resampling_step\n time_unit = params.time_unit\n time_step = params.time_step\n\n date_range = generate_date_range(start_time, end_time, 0, 0, 0, frequency, time_step, time_unit)\n np.testing.assert_array_equal(date_range, pd.DatetimeIndex(['2020-01-31', '2020-07-31', '2021-01-31', '2021-07-31']))\n\n def test_generate_date_range_b_days(self, config):\n config[\"time_unit\"] = \"business_days\"\n config[\"time_step\"] = 1\n start_time = pd.Timestamp('2021-01-02 00:00:00')\n end_time = pd.Timestamp('2021-01-10 00:00:00')\n\n params = get_resampling_params(config)\n frequency = params.resampling_step\n time_unit = params.time_unit\n time_step = params.time_step\n\n date_range = generate_date_range(start_time, end_time, 0, 0, 0, frequency, time_step, time_unit)\n np.testing.assert_array_equal(date_range, pd.DatetimeIndex(['2021-01-04', '2021-01-05', '2021-01-06', '2021-01-07', '2021-01-08', '2021-01-11']))\n\n clip_start = 1\n clip_end = 1\n shift = 0\n date_range = generate_date_range(start_time, end_time, clip_start, clip_end, shift, frequency, time_step, time_unit)\n np.testing.assert_array_equal(date_range, pd.DatetimeIndex(['2021-01-04', '2021-01-05', '2021-01-06', '2021-01-07', '2021-01-08', '2021-01-11']))\n\n clip_start = 2\n clip_end = 2\n shift = 0\n date_range = generate_date_range(start_time, end_time, clip_start, clip_end, shift, frequency, time_step, time_unit)\n np.testing.assert_array_equal(date_range, pd.DatetimeIndex(['2021-01-05', '2021-01-06', '2021-01-07', '2021-01-08']))\n\n def test_generate_date_range_days(self, config):\n config[\"time_unit\"] = \"days\"\n config[\"time_step\"] = 1\n start_time = pd.Timestamp('20190131 01:59:00').tz_localize('CET')\n end_time = pd.Timestamp('20190214 01:59:00').tz_localize('CET')\n\n params = get_resampling_params(config)\n frequency = params.resampling_step\n time_unit = params.time_unit\n time_step = params.time_step\n\n clip_start = 5\n shift = 2\n clip_end = 3\n\n date_range = generate_date_range(start_time, end_time, clip_start, clip_end, shift, frequency, time_step, time_unit)\n expected_range = pd.DatetimeIndex(['2019-02-07 00:00:00+01:00', '2019-02-08 00:00:00+01:00',\n '2019-02-09 00:00:00+01:00', '2019-02-10 00:00:00+01:00',\n '2019-02-11 00:00:00+01:00', '2019-02-12 00:00:00+01:00',\n '2019-02-13 00:00:00+01:00'])\n np.testing.assert_array_equal(date_range, expected_range)\n\n def test_generate_date_range_hours(self, config):\n config[\"time_unit\"] = \"hours\"\n config[\"time_step\"] = 1\n start_time = pd.Timestamp('20190131 01:59:00').tz_localize('CET')\n end_time = pd.Timestamp('20190131 11:59:00').tz_localize('CET')\n\n params = get_resampling_params(config)\n frequency = params.resampling_step\n time_unit = params.time_unit\n time_step = params.time_step\n\n clip_start = 5\n shift = 2\n clip_end = 3\n\n date_range = generate_date_range(start_time, end_time, clip_start, clip_end, shift, frequency, time_step, time_unit)\n expected_range = pd.DatetimeIndex(['2019-01-31 09:00:00+01:00', '2019-01-31 10:00:00+01:00',\n '2019-01-31 11:00:00+01:00'])\n np.testing.assert_array_equal(date_range, expected_range)\n\n def test_generate_date_range_minutes(self, config):\n config[\"time_unit\"] = \"minutes\"\n config[\"time_step\"] = 1\n start_time = pd.Timestamp('20190131 01:59:00').tz_localize('CET')\n end_time = pd.Timestamp('20190131 02:15:00').tz_localize('CET')\n\n params = get_resampling_params(config)\n frequency = params.resampling_step\n time_unit = params.time_unit\n time_step = params.time_step\n\n clip_start = 5\n shift = 2\n clip_end = 3\n\n date_range = generate_date_range(start_time, end_time, clip_start, clip_end, shift, frequency, time_step, time_unit)\n expected_range = pd.DatetimeIndex(['2019-01-31 02:06:00+01:00', '2019-01-31 02:07:00+01:00',\n '2019-01-31 02:08:00+01:00', '2019-01-31 02:09:00+01:00',\n '2019-01-31 02:10:00+01:00', '2019-01-31 02:11:00+01:00',\n '2019-01-31 02:12:00+01:00', '2019-01-31 02:13:00+01:00',\n '2019-01-31 02:14:00+01:00'])\n np.testing.assert_array_equal(date_range, expected_range)\n\n def test_generate_date_range_seconds(self, config):\n config[\"time_unit\"] = \"seconds\"\n config[\"time_step\"] = 1\n start_time = pd.Timestamp('20190131 01:59:00').tz_localize('CET')\n end_time = pd.Timestamp('20190131 01:59:12').tz_localize('CET')\n\n params = get_resampling_params(config)\n frequency = params.resampling_step\n time_unit = params.time_unit\n time_step = params.time_step\n\n clip_start = 5\n shift = 2\n clip_end = 3\n\n date_range = generate_date_range(start_time, end_time, clip_start, clip_end, shift, frequency, time_step, time_unit)\n expected_range = pd.DatetimeIndex(['2019-01-31 01:59:07+01:00', '2019-01-31 01:59:08+01:00',\n '2019-01-31 01:59:09+01:00', '2019-01-31 01:59:10+01:00',\n '2019-01-31 01:59:11+01:00'])\n np.testing.assert_array_equal(date_range, expected_range)\n\n def test_generate_date_range_milliseconds(self, config):\n config[\"time_unit\"] = \"milliseconds\"\n config[\"time_step\"] = 1\n start_time = pd.Timestamp('20190131 01:59:00').tz_localize('CET')\n end_time = pd.Timestamp('2019-01-31 01:59:00.015000').tz_localize('CET')\n\n params = get_resampling_params(config)\n frequency = params.resampling_step\n time_unit = params.time_unit\n time_step = params.time_step\n\n clip_start = 5\n shift = 2\n clip_end = 3\n\n date_range = generate_date_range(start_time, end_time, clip_start, clip_end, shift, frequency, time_step, time_unit)\n expected_range = pd.DatetimeIndex(['2019-01-31 01:59:00.007000+01:00',\n '2019-01-31 01:59:00.008000+01:00',\n '2019-01-31 01:59:00.009000+01:00',\n '2019-01-31 01:59:00.010000+01:00',\n '2019-01-31 01:59:00.011000+01:00',\n '2019-01-31 01:59:00.012000+01:00',\n '2019-01-31 01:59:00.013000+01:00',\n '2019-01-31 01:59:00.014000+01:00'])\n np.testing.assert_array_equal(date_range, expected_range)\n\n def test_generate_date_range_microseconds(self, config):\n config[\"time_unit\"] = \"microseconds\"\n config[\"time_step\"] = 1\n start_time = pd.Timestamp('20190131 01:59:00').tz_localize('CET')\n end_time = pd.Timestamp('2019-01-31 01:59:00.000016').tz_localize('CET')\n\n params = get_resampling_params(config)\n frequency = params.resampling_step\n time_unit = params.time_unit\n time_step = params.time_step\n\n clip_start = 5\n shift = 2\n clip_end = 3\n\n date_range = generate_date_range(start_time, end_time, clip_start, clip_end, shift, frequency, time_step, time_unit)\n expected_range = pd.DatetimeIndex(['2019-01-31 01:59:00.000007+01:00',\n '2019-01-31 01:59:00.000008+01:00',\n '2019-01-31 01:59:00.000009+01:00',\n '2019-01-31 01:59:00.000010+01:00',\n '2019-01-31 01:59:00.000011+01:00',\n '2019-01-31 01:59:00.000012+01:00',\n '2019-01-31 01:59:00.000013+01:00',\n '2019-01-31 01:59:00.000014+01:00',\n '2019-01-31 01:59:00.000015+01:00'])\n np.testing.assert_array_equal(date_range, expected_range)\n\n def test_generate_date_range_nanoseconds(self, config):\n config[\"time_unit\"] = \"nanoseconds\"\n config[\"time_step\"] = 1\n start_time = pd.Timestamp('2019-01-31T00:59:00.000000000')\n end_time = pd.Timestamp('2019-01-31T00:59:00.000000009')\n\n params = get_resampling_params(config)\n frequency = params.resampling_step\n time_unit = params.time_unit\n time_step = params.time_step\n\n clip_start = 5\n shift = 2\n clip_end = 3\n\n date_range = generate_date_range(start_time, end_time, clip_start, clip_end, shift, frequency, time_step, time_unit)\n np.testing.assert_array_equal(date_range, pd.DatetimeIndex(['2019-01-31 00:59:00.000000007',\n '2019-01-31 00:59:00.000000008']))\n",
"import numpy as np\nimport pandas as pd\nimport pytest\n\nfrom dku_timeseries import WindowAggregator\nfrom recipe_config_loading import get_windowing_params\n\[email protected]\ndef columns():\n class COLUMNS:\n date = \"Date\"\n category = \"country\"\n aggregation = \"value1_avg\"\n return COLUMNS\n\n\[email protected]\ndef df(columns):\n co2 = [315.58, 316.39, 316.79, 316.2]\n country = [\"first\", \"first\", \"second\", \"second\"]\n time_index = pd.date_range(\"1-1-1959\", periods=4, freq=\"M\")\n df = pd.DataFrame.from_dict(\n {\"value1\": co2, \"value2\": co2, columns.category: country, columns.date: time_index})\n return df\n\n\[email protected]\ndef long_df(columns):\n co2 = [315.58, 316.39, 316.79, 316.2, 345, 234, 100, 299]\n country = [\"first\", \"first\", \"first\", \"first\", \"second\", \"second\", \"second\", \"second\"]\n time_index = pd.date_range(\"1-1-1959\", periods=4, freq=\"D\").append(pd.date_range(\"1-1-1959\", periods=4, freq=\"D\"))\n df = pd.DataFrame.from_dict(\n {\"value1\": co2, \"value2\": co2, columns.category: country, columns.date: time_index})\n return df\n\n\[email protected]\ndef long_df_2(columns):\n co2 = [315.58, 316.39, 316.79, 316.2, 9, 10]\n country = [\"first\", \"first\", \"second\", \"second\", \"third\", \"third\"]\n country_2 = [\"first\", \"first\", \"second\", \"second\", \"third\", \"third\"]\n time_index = pd.date_range(\"1-1-1959\", periods=2, freq=\"M\").append(pd.date_range(\"1-1-1959\", periods=2, freq=\"M\")).append(\n pd.date_range(\"1-1-1959\", periods=2, freq=\"M\"))\n df = pd.DataFrame.from_dict(\n {\"value1\": co2, \"value2\": co2, columns.category: country, \"item\": country_2, columns.date: time_index})\n return df\n\n\[email protected]\ndef long_df_3(columns):\n co2 = [315.58, 316.39, 316.79, 316.2, 9, 10, 2, 3]\n country = [\"first\", \"first\", \"second\", \"second\", \"third\", \"third\", \"fourth\", \"fourth\"]\n country_2 = [\"first\", \"first\", \"second\", \"second\", \"third\", \"third\", \"fourth\", \"fourth\"]\n country_3 = [\"first\", \"first\", \"second\", \"second\", \"third\", \"third\", \"fourth\", \"fourth\"]\n time_index = pd.date_range(\"1-1-1959\", periods=2, freq=\"M\").append(pd.date_range(\"1-1-1959\", periods=2, freq=\"M\")).append(\n pd.date_range(\"1-1-1959\", periods=2, freq=\"M\")).append(pd.date_range(\"1-1-1959\", periods=2, freq=\"M\"))\n df = pd.DataFrame.from_dict(\n {\"value1\": co2, \"value2\": co2, columns.category: country, \"item\": country_2, \"store\": country_3, columns.date: time_index})\n return df\n\n\[email protected]\ndef long_df_4(columns):\n co2 = [315.58, 316.39, 316.79, 316.2, 9, 10, 2, 3]\n country = [\"first\", \"first\", \"second\", \"second\", \"third\", \"third\", \"first\", \"first\"]\n country_2 = [\"first\", \"first\", \"second\", \"second\", \"third\", \"third\", \"second\", \"first\"]\n country_3 = [\"first\", \"first\", \"second\", \"second\", \"third\", \"third\", \"third\", \"fourth\"]\n time_index = pd.date_range(\"1-1-2020\", periods=2, freq=\"M\").append(pd.date_range(\"1-1-2020\", periods=2, freq=\"M\")).append(\n pd.date_range(\"1-1-2020\", periods=2, freq=\"M\")).append(pd.date_range(\"1-1-2020\", periods=2, freq=\"M\"))\n df = pd.DataFrame.from_dict(\n {\"value1\": co2, \"value2\": co2, columns.category: country, \"item\": country_2, \"store\": country_3, columns.date: time_index})\n return df\n\n\[email protected]\ndef long_df_numerical(columns):\n co2 = [315.58, 316.39, 316.79, 316.2, 345, 234, 100, 299]\n country = [1, 1, 1, 1, 2, 2, 2, 2]\n time_index = pd.date_range(\"1-1-1959\", periods=4, freq=\"D\").append(pd.date_range(\"1-1-1959\", periods=4, freq=\"D\"))\n df = pd.DataFrame.from_dict(\n {\"value1\": co2, \"value2\": co2, columns.category: country, columns.date: time_index})\n return df\n\n\[email protected]\ndef recipe_config(columns):\n config = {u'window_type': u'none', u'groupby_columns': [u'country'], u'closed_option': u'left', u'window_unit': u'days', u'window_width': 3,\n u'causal_window': True, u'datetime_column': u'Date', u'advanced_activated': True, u'aggregation_types': [u'retrieve', u'average'],\n u'gaussian_std': 1}\n return config\n\n\[email protected]\ndef params(recipe_config):\n return get_windowing_params(recipe_config)\n\n\[email protected]\ndef params_no_causal(recipe_config):\n recipe_config[\"causal_window\"] = False\n return get_windowing_params(recipe_config)\n\n\nclass TestWindowingLongFormat:\n def test_long_format(self, long_df, params, recipe_config,columns):\n window_aggregator = WindowAggregator(params)\n groupby_columns = [columns.category]\n datetime_column = recipe_config.get('datetime_column')\n output_df = window_aggregator.compute(long_df, datetime_column, groupby_columns=groupby_columns)\n np.testing.assert_array_equal(np.round(output_df[columns.aggregation].values, 2), np.array([np.nan, 315.58, 315.98, 316.25, np.nan, 345.,\n 289.5, 226.33]))\n np.testing.assert_array_equal(output_df.country.values, np.array(['first', 'first', 'first', 'first', 'second', 'second', 'second', 'second']))\n\n def test_two_identifiers(self, long_df_2, params, recipe_config,columns):\n window_aggregator = WindowAggregator(params)\n groupby_columns = [\"country\", \"item\"]\n datetime_column = recipe_config.get('datetime_column')\n output_df = window_aggregator.compute(long_df_2, datetime_column, groupby_columns=groupby_columns)\n np.testing.assert_array_equal(output_df[datetime_column].values,\n pd.DatetimeIndex(['1959-01-31T00:00:00.000000000', '1959-02-28T00:00:00.000000000',\n '1959-01-31T00:00:00.000000000', '1959-02-28T00:00:00.000000000',\n '1959-01-31T00:00:00.000000000', '1959-02-28T00:00:00.000000000']))\n\n def test_three_identifiers(self, long_df_3, params, recipe_config,columns):\n window_aggregator = WindowAggregator(params)\n groupby_columns = [\"country\", \"item\", \"store\"]\n datetime_column = recipe_config.get('datetime_column')\n output_df = window_aggregator.compute(long_df_3, datetime_column, groupby_columns=groupby_columns)\n np.testing.assert_array_equal(output_df[datetime_column].values,\n pd.DatetimeIndex(['1959-01-31T00:00:00.000000000', '1959-02-28T00:00:00.000000000',\n '1959-01-31T00:00:00.000000000', '1959-02-28T00:00:00.000000000',\n '1959-01-31T00:00:00.000000000', '1959-02-28T00:00:00.000000000',\n '1959-01-31T00:00:00.000000000', '1959-02-28T00:00:00.000000000']))\n\n def test_mix_identifiers(self, long_df_4, params, recipe_config,columns):\n window_aggregator = WindowAggregator(params)\n groupby_columns = [\"country\", \"item\", \"store\"]\n datetime_column = recipe_config.get('datetime_column')\n output_df = window_aggregator.compute(long_df_4, datetime_column, groupby_columns=groupby_columns)\n expected_dates = pd.DatetimeIndex(['2020-01-31T00:00:00.000000000', '2020-02-29T00:00:00.000000000',\n '2020-02-29T00:00:00.000000000', '2020-01-31T00:00:00.000000000',\n '2020-01-31T00:00:00.000000000', '2020-02-29T00:00:00.000000000',\n '2020-01-31T00:00:00.000000000', '2020-02-29T00:00:00.000000000'])\n np.testing.assert_array_equal(output_df[datetime_column].values, expected_dates)\n\n def test_empty_identifiers(self, df, params, recipe_config,columns):\n window_aggregator = WindowAggregator(params)\n datetime_column = recipe_config.get('datetime_column')\n output_df = window_aggregator.compute(df, datetime_column, groupby_columns=[])\n assert output_df.shape == (4, 5)\n output_df = window_aggregator.compute(df, datetime_column)\n assert output_df.shape == (4, 5)\n output_df = window_aggregator.compute(df, datetime_column, groupby_columns=None)\n assert output_df.shape == (4, 5)\n\n def test_long_format_no_causal(self, long_df, params_no_causal, recipe_config,columns):\n window_aggregator = WindowAggregator(params_no_causal)\n groupby_columns = [\"country\"]\n datetime_column = recipe_config.get('datetime_column')\n output_df = window_aggregator.compute(long_df, datetime_column, groupby_columns=groupby_columns)\n\n np.testing.assert_array_equal(np.round(output_df[columns.aggregation].values, 2), np.array([np.nan, 316.25, 316.46, np.nan, np.nan, 226.33,\n 211., np.nan]))\n np.testing.assert_array_equal(output_df.country.values, np.array(['first', 'first', 'first', 'first', 'second', 'second', 'second', 'second']))\n\n def test_long_format_numerical(self, long_df_numerical, params, recipe_config,columns):\n window_aggregator = WindowAggregator(params)\n groupby_columns = [\"country\"]\n datetime_column = recipe_config.get('datetime_column')\n output_df = window_aggregator.compute(long_df_numerical, datetime_column, groupby_columns=groupby_columns)\n np.testing.assert_array_equal(output_df.country.values, np.array([1, 1, 1, 1, 2, 2, 2, 2]))\n"
] | [
[
"numpy.testing.assert_array_equal",
"pandas.Timestamp",
"pandas.DatetimeIndex"
],
[
"pandas.date_range",
"pandas.DatetimeIndex",
"numpy.testing.assert_array_equal",
"numpy.round",
"pandas.DataFrame.from_dict",
"numpy.array"
]
] | [
{
"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": []
}
] |
nata1y/fltk-testbed-group-3 | [
"e23b59fa2a5e638d3804a39fe5012983e2988ca6"
] | [
"fltk/nets/fashion_mnist_ls_gan.py"
] | [
"import torch.nn as nn\n\n\nclass Generator(nn.Module):\n def __init__(self, img_size=32):\n super(Generator, self).__init__()\n\n # TODO: update to proper image size\n self.init_size = img_size // 4\n self.l1 = nn.Sequential(nn.Linear(10, 128 * self.init_size ** 2))\n\n self.conv_blocks = nn.Sequential(\n nn.Upsample(scale_factor=2),\n nn.Conv2d(128, 128, 3, stride=1, padding=1),\n nn.BatchNorm2d(128, 0.8),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Upsample(scale_factor=2),\n nn.Conv2d(128, 64, 3, stride=1, padding=1),\n nn.BatchNorm2d(64, 0.8),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Conv2d(64, 1, 3, stride=1, padding=1), #3\n nn.Tanh(),\n )\n\n def forward(self, z):\n out = self.l1(z)\n out = out.view(out.shape[0], 128, self.init_size, self.init_size)\n img = self.conv_blocks(out)\n return img\n\n\nclass Discriminator(nn.Module):\n def __init__(self, img_size=32):\n super(Discriminator, self).__init__()\n\n def discriminator_block(in_filters, out_filters, bn=True):\n block = [nn.Conv2d(in_filters, out_filters, 3, 2, 1), nn.LeakyReLU(0.2, inplace=True), nn.Dropout2d(0.25)]\n if bn:\n block.append(nn.BatchNorm2d(out_filters, 0.8))\n return block\n\n self.model = nn.Sequential(\n *discriminator_block(1, 16, bn=False), #3\n *discriminator_block(16, 32),\n *discriminator_block(32, 64),\n *discriminator_block(64, 128),\n )\n\n # The height and width of downsampled image\n # TODO: update to proper image size\n ds_size = img_size // 2 ** 4\n self.adv_layer = nn.Linear(128 * ds_size ** 2, 1)\n\n def forward(self, img):\n out = self.model(img)\n out = out.view(out.shape[0], -1)\n validity = self.adv_layer(out)\n\n return validity\n"
] | [
[
"torch.nn.Dropout2d",
"torch.nn.Conv2d",
"torch.nn.Tanh",
"torch.nn.Linear",
"torch.nn.Upsample",
"torch.nn.LeakyReLU",
"torch.nn.BatchNorm2d"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
MRCIEU/ewascatalog | [
"a37dfeb207537831b4c5e313e0edecbad8a7c1a2"
] | [
"database/zenodo.py"
] | [
"# script to upload a file to zenodo sandbox via api\n# seperate sandbox- and real-zenodo accounts and ACCESS_TOKENs each need to be created\n\n# to adapt this script to real-zenodo (from sandbox implementation):\n # update urls to zenodo.org from sandbox.zenodo.org\n # update SANDBOX_TOKEN to a ACCESS_TOKEN from real-zenodo\n\nimport sys, json, requests\nimport pandas as pd\n\nstudyid = sys.argv[1]\nfile_dir = sys.argv[2]\naccess_token = sys.argv[3]\ndata_dir = file_dir+'/ewas-sum-stats/to-add/'+studyid\n\nzfile=data_dir+'/zenodo.csv'\ntry:\n zdata = pd.read_csv(zfile)\nexcept FileNotFoundError:\n print(\"Can't find the file \"+zfile)\n sys.exit()\n\nprint('Starting Zenodo upload process')\n\n# specify ACCESS_TOKEN\n # this needs to be generated for each sanbox/real account\nACCESS_TOKEN = access_token\n\n# create empty upload\nheaders = {\"Content-Type\": \"application/json\"}\nr = requests.post('https://zenodo.org/api/deposit/depositions', params={'access_token': ACCESS_TOKEN}, json={}, headers=headers)\n# r = requests.post('https://sandbox.zenodo.org/api/deposit/depositions', params={'access_token': ACCESS_TOKEN}, json={}, headers=headers)\n\nr.status_code\nr.json()\n\n# Get the deposition id from the previous response\n# Upload the file to be deposited to Zenodo\ndeposition_id = r.json()['id']\n\ndata = {'name': 'results.csv'}\nfiles = {'file': open(data_dir+'/results.csv')}\nr = requests.post('https://zenodo.org/api/deposit/depositions/%s/files' % deposition_id, params={'access_token': ACCESS_TOKEN}, data=data, files=files)\n# r = requests.post('https://sandbox.zenodo.org/api/deposit/depositions/%s/files' % deposition_id, params={'access_token': ACCESS_TOKEN}, data=data, files=files)\n\nr.status_code\nr.json()\n\n# specify and attach the metadata for the upload\ntitle = zdata.loc[0, 'title']\nauthors = zdata.loc[0, 'authors']\ndesc = zdata.loc[0, 'desc']\n\ndesc = desc + '\\n\\n' + 'Upload of this dataset was completed by The EWAS Catalog team. The data can be queried along with hundreds of other EWAS at ewascatalog.org. To upload your EWAS summary statistics and have a zenodo DOI generated for you go to ewascatalog.org/upload'\n\ndata = {'metadata': \n\t\t\t\t {'title': title, \n\t\t\t\t 'upload_type': 'dataset', \n\t\t\t\t 'description': desc, \n\t\t\t\t 'creators': [{'name': authors}]}}\n\nr = requests.put('https://zenodo.org/api/deposit/depositions/%s' % deposition_id, params={'access_token': ACCESS_TOKEN}, data=json.dumps(data), headers=headers)\n# r = requests.put('https://sandbox.zenodo.org/api/deposit/depositions/%s' % deposition_id, params={'access_token': ACCESS_TOKEN}, data=json.dumps(data), headers=headers)\n\nr.status_code\nr.json()\n\n# publish \nr = requests.post('https://zenodo.org/api/deposit/depositions/%s/actions/publish' % deposition_id, params={'access_token': ACCESS_TOKEN} )\n# r = requests.post('https://sandbox.zenodo.org/api/deposit/depositions/%s/actions/publish' % deposition_id, params={'access_token': ACCESS_TOKEN} )\n\nstatus_code = r.status_code\nif status_code != 202:\n\traise ValueError(\"Status code was\" + str(status_code) + \" and it should be 202. Check zenodo\")\nelse:\n\tprint(\"Status code is 202. Happy days!\")\n# should be: 202\n"
] | [
[
"pandas.read_csv"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
lzhmarkk/pytorch-deeplab-xception | [
"63f699214e4095a4edda21173012cc29e53125b3"
] | [
"utils/summaries.py"
] | [
"import os\nimport torch\nfrom torchvision.utils import make_grid\nfrom tensorboardX import SummaryWriter\nfrom dataloaders.utils import decode_seg_map_sequence\n\nclass TensorboardSummary(object):\n def __init__(self, directory):\n self.directory = directory\n\n def create_summary(self):\n writer = SummaryWriter(log_dir=os.path.join(self.directory))\n return writer\n\n def visualize_image(self, writer, dataset, image, target, output, global_step):\n grid_image = make_grid(image[:3].clone().cpu().data, 3, normalize=True)\n writer.add_image('Image', grid_image, global_step)\n grid_image = make_grid(decode_seg_map_sequence(torch.max(output[:3], 1)[1].detach().cpu().numpy(),\n dataset=dataset), 3, normalize=False, range=(0, 255))\n writer.add_image('Predicted label', grid_image, global_step)\n grid_image = make_grid(decode_seg_map_sequence(torch.squeeze(target[:3], 1).detach().cpu().numpy(),\n dataset=dataset), 3, normalize=False, range=(0, 255))\n writer.add_image('Groundtruth label', grid_image, global_step)"
] | [
[
"torch.max",
"torch.squeeze"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
samsledje/D-SCRIPT | [
"3fa7ea685f7fcdc63468380267d1672f63bb8772"
] | [
"dscript/commands/train.py"
] | [
"\"\"\"\nTrain a new model.\n\"\"\"\n\nimport sys\nimport argparse\nimport h5py\nimport datetime\nimport subprocess as sp\nimport numpy as np\nimport pandas as pd\nimport gzip as gz\nfrom tqdm import tqdm\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.autograd import Variable\nfrom torch.utils.data import IterableDataset, DataLoader\nfrom sklearn.metrics import average_precision_score as average_precision\n\nimport dscript\nfrom dscript.utils import PairedDataset, collate_paired_sequences\nfrom dscript.models.embedding import (\n IdentityEmbed,\n FullyConnectedEmbed,\n)\nfrom dscript.models.contact import ContactCNN\nfrom dscript.models.interaction import ModelInteraction\n\n\ndef add_args(parser):\n \"\"\"\n Create parser for command line utility.\n\n :meta private:\n \"\"\"\n\n data_grp = parser.add_argument_group(\"Data\")\n proj_grp = parser.add_argument_group(\"Projection Module\")\n contact_grp = parser.add_argument_group(\"Contact Module\")\n inter_grp = parser.add_argument_group(\"Interaction Module\")\n train_grp = parser.add_argument_group(\"Training\")\n misc_grp = parser.add_argument_group(\"Output and Device\")\n\n # Data\n data_grp.add_argument(\"--train\", help=\"Training data\", required=True)\n data_grp.add_argument(\"--val\", help=\"Validation data\", required=True)\n data_grp.add_argument(\"--embedding\", help=\"h5 file with embedded sequences\", required=True)\n data_grp.add_argument(\n \"--no-augment\",\n action=\"store_false\",\n dest='augment',\n help=\"Set flag to not augment data by adding (B A) for all pairs (A B)\",\n )\n\n # Embedding model\n proj_grp.add_argument(\n \"--projection-dim\",\n type=int,\n default=100,\n help=\"Dimension of embedding projection layer (default: 100)\",\n )\n proj_grp.add_argument(\n \"--dropout-p\",\n type=float,\n default=0.5,\n help=\"Parameter p for embedding dropout layer (default: 0.5)\",\n )\n\n # Contact model\n contact_grp.add_argument(\n \"--hidden-dim\",\n type=int,\n default=50,\n help=\"Number of hidden units for comparison layer in contact prediction (default: 50)\",\n )\n contact_grp.add_argument(\n \"--kernel-width\",\n type=int,\n default=7,\n help=\"Width of convolutional filter for contact prediction (default: 7)\",\n )\n\n # Interaction Model\n inter_grp.add_argument(\n \"--no-w\",\n action=\"store_false\",\n dest='use_w',\n help=\"Don't use weight matrix in interaction prediction model\",\n )\n inter_grp.add_argument(\n \"--pool-width\",\n type=int,\n default=9,\n help=\"Size of max-pool in interaction model (default: 9)\",\n )\n\n # Training\n train_grp.add_argument(\n \"--negative-ratio\",\n type=int,\n default=10,\n help=\"Number of negative training samples for each positive training sample (default: 10)\",\n )\n train_grp.add_argument(\n \"--epoch-scale\",\n type=int,\n default=1,\n help=\"Report heldout performance every this many epochs (default: 1)\",\n )\n train_grp.add_argument(\"--num-epochs\", type=int, default=10, help=\"Number of epochs (default: 10)\")\n train_grp.add_argument(\"--batch-size\", type=int, default=25, help=\"Minibatch size (default: 25)\")\n train_grp.add_argument(\"--weight-decay\", type=float, default=0, help=\"L2 regularization (default: 0)\")\n train_grp.add_argument(\"--lr\", type=float, default=0.001, help=\"Learning rate (default: 0.001)\")\n train_grp.add_argument(\n \"--lambda\",\n dest=\"lambda_\",\n type=float,\n default=0.35,\n help=\"Weight on the similarity objective (default: 0.35)\",\n )\n\n # Output\n misc_grp.add_argument(\"-o\", \"--outfile\", help=\"Output file path (default: stdout)\")\n misc_grp.add_argument(\"--save-prefix\", help=\"Path prefix for saving models\")\n misc_grp.add_argument(\"-d\", \"--device\", type=int, default=-1, help=\"Compute device to use\")\n misc_grp.add_argument(\"--checkpoint\", help=\"Checkpoint model to start training from\")\n\n return parser\n\n\ndef predict_interaction(model, n0, n1, tensors, use_cuda):\n \"\"\"\n Predict whether a list of protein pairs will interact.\n\n :param model: Model to be trained\n :type model: dscript.models.interaction.ModelInteraction\n :param n0: First protein names\n :type n0: list[str]\n :param n1: Second protein names\n :type n1: list[str]\n :param tensors: Dictionary of protein names to embeddings\n :type tensors: dict[str, torch.Tensor]\n :param use_cuda: Whether to use GPU\n :type use_cuda: bool\n \"\"\"\n\n b = len(n0)\n\n p_hat = []\n for i in range(b):\n z_a = tensors[n0[i]]\n z_b = tensors[n1[i]]\n if use_cuda:\n z_a = z_a.cuda()\n z_b = z_b.cuda()\n\n p_hat.append(model.predict(z_a, z_b))\n p_hat = torch.stack(p_hat, 0)\n return p_hat\n\n\ndef predict_cmap_interaction(model, n0, n1, tensors, use_cuda):\n \"\"\"\n Predict whether a list of protein pairs will interact, as well as their contact map.\n\n :param model: Model to be trained\n :type model: dscript.models.interaction.ModelInteraction\n :param n0: First protein names\n :type n0: list[str]\n :param n1: Second protein names\n :type n1: list[str]\n :param tensors: Dictionary of protein names to embeddings\n :type tensors: dict[str, torch.Tensor]\n :param use_cuda: Whether to use GPU\n :type use_cuda: bool\n \"\"\"\n\n b = len(n0)\n\n p_hat = []\n c_map_mag = []\n for i in range(b):\n z_a = tensors[n0[i]]\n z_b = tensors[n1[i]]\n if use_cuda:\n z_a = z_a.cuda()\n z_b = z_b.cuda()\n\n cm, ph = model.map_predict(z_a, z_b)\n p_hat.append(ph)\n c_map_mag.append(torch.mean(cm))\n p_hat = torch.stack(p_hat, 0)\n c_map_mag = torch.stack(c_map_mag, 0)\n return c_map_mag, p_hat\n\n\ndef interaction_grad(model, n0, n1, y, tensors, use_cuda, weight=0.35):\n \"\"\"\n Compute gradient and backpropagate loss for a batch.\n\n :param model: Model to be trained\n :type model: dscript.models.interaction.ModelInteraction\n :param n0: First protein names\n :type n0: list[str]\n :param n1: Second protein names\n :type n1: list[str]\n :param y: Interaction labels\n :type y: torch.Tensor\n :param tensors: Dictionary of protein names to embeddings\n :type tensors: dict[str, torch.Tensor]\n :param use_cuda: Whether to use GPU\n :type use_cuda: bool\n :param weight: Weight on the contact map magnitude objective. BCE loss is :math:`1 - \\\\text{weight}`.\n :type weight: float\n\n :return: (Loss, number correct, mean square error, batch size)\n :rtype: (torch.Tensor, int, torch.Tensor, int)\n \"\"\"\n\n c_map_mag, p_hat = predict_cmap_interaction(model, n0, n1, tensors, use_cuda)\n if use_cuda:\n y = y.cuda()\n y = Variable(y)\n\n bce_loss = F.binary_cross_entropy(p_hat.float(), y.float())\n cmap_loss = torch.mean(c_map_mag)\n loss = (weight * bce_loss) + ((1 - weight) * cmap_loss)\n b = len(p_hat)\n\n # backprop loss\n loss.backward()\n\n if use_cuda:\n y = y.cpu()\n p_hat = p_hat.cpu()\n\n with torch.no_grad():\n guess_cutoff = 0.5\n p_hat = p_hat.float()\n p_guess = (guess_cutoff * torch.ones(b) < p_hat).float()\n y = y.float()\n correct = torch.sum(p_guess == y).item()\n mse = torch.mean((y.float() - p_hat) ** 2).item()\n\n return loss, correct, mse, b\n\n\ndef interaction_eval(model, test_iterator, tensors, use_cuda):\n \"\"\"\n Evaluate test data set performance.\n\n :param model: Model to be trained\n :type model: dscript.models.interaction.ModelInteraction\n :param test_iterator: Test data iterator\n :type test_iterator: torch.utils.data.DataLoader\n :param tensors: Dictionary of protein names to embeddings\n :type tensors: dict[str, torch.Tensor]\n :param use_cuda: Whether to use GPU\n :type use_cuda: bool\n\n :return: (Loss, number correct, mean square error, precision, recall, F1 Score, AUPR)\n :rtype: (torch.Tensor, int, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor)\n \"\"\"\n p_hat = []\n true_y = []\n\n for n0, n1, y in test_iterator:\n p_hat.append(predict_interaction(model, n0, n1, tensors, use_cuda))\n true_y.append(y)\n\n y = torch.cat(true_y, 0)\n p_hat = torch.cat(p_hat, 0)\n\n if use_cuda:\n y.cuda()\n p_hat = torch.Tensor([x.cuda() for x in p_hat])\n p_hat.cuda()\n\n loss = F.binary_cross_entropy(p_hat.float(), y.float()).item()\n b = len(y)\n\n with torch.no_grad():\n guess_cutoff = torch.Tensor([0.5]).float()\n p_hat = p_hat.float()\n y = y.float()\n p_guess = (guess_cutoff * torch.ones(b) < p_hat).float()\n correct = torch.sum(p_guess == y).item()\n mse = torch.mean((y.float() - p_hat) ** 2).item()\n\n tp = torch.sum(y * p_hat).item()\n pr = tp / torch.sum(p_hat).item()\n re = tp / torch.sum(y).item()\n f1 = 2 * pr * re / (pr + re)\n\n y = y.cpu().numpy()\n p_hat = p_hat.data.cpu().numpy()\n\n aupr = average_precision(y, p_hat)\n\n return loss, correct, mse, pr, re, f1, aupr\n\n\ndef main(args):\n \"\"\"\n Run training from arguments.\n\n :meta private:\n \"\"\"\n\n output = args.outfile\n if output is None:\n output = sys.stdout\n else:\n output = open(output, \"w\")\n\n print(f'# Called as: {\" \".join(sys.argv)}', file=output)\n if output is not sys.stdout:\n print(f'Called as: {\" \".join(sys.argv)}')\n\n # Set device\n device = args.device\n use_cuda = (device >= 0) and torch.cuda.is_available()\n if use_cuda:\n torch.cuda.set_device(device)\n print(\n f\"# Using CUDA device {device} - {torch.cuda.get_device_name(device)}\",\n file=output,\n )\n else:\n print(\"# Using CPU\", file=output)\n device = \"cpu\"\n\n batch_size = args.batch_size\n\n train_fi = args.train\n test_fi = args.val\n augment = args.augment\n embedding_h5 = args.embedding\n h5fi = h5py.File(embedding_h5, \"r\")\n\n print(f\"# Loading training pairs from {train_fi}...\", file=output)\n output.flush()\n\n train_df = pd.read_csv(train_fi, sep=\"\\t\", header=None)\n if augment:\n train_n0 = pd.concat((train_df[0], train_df[1]), axis=0).reset_index(drop=True)\n train_n1 = pd.concat((train_df[1], train_df[0]), axis=0).reset_index(drop=True)\n train_y = torch.from_numpy(pd.concat((train_df[2], train_df[2])).values)\n else:\n train_n0, train_n1 = train_df[0], train_df[1]\n train_y = torch.from_numpy(train_df[2].values)\n\n print(f\"# Loading testing pairs from {test_fi}...\", file=output)\n output.flush()\n\n test_df = pd.read_csv(test_fi, sep=\"\\t\", header=None)\n test_n0, test_n1 = test_df[0], test_df[1]\n test_y = torch.from_numpy(test_df[2].values)\n output.flush()\n\n train_pairs = PairedDataset(train_n0, train_n1, train_y)\n pairs_train_iterator = torch.utils.data.DataLoader(\n train_pairs,\n batch_size=batch_size,\n collate_fn=collate_paired_sequences,\n shuffle=True,\n )\n\n test_pairs = PairedDataset(test_n0, test_n1, test_y)\n pairs_test_iterator = torch.utils.data.DataLoader(\n test_pairs,\n batch_size=batch_size,\n collate_fn=collate_paired_sequences,\n shuffle=True,\n )\n\n output.flush()\n\n print(f\"# Loading embeddings\", file=output)\n tensors = {}\n all_proteins = set(train_n0).union(set(train_n1)).union(set(test_n0)).union(set(test_n1))\n for prot_name in tqdm(all_proteins):\n tensors[prot_name] = torch.from_numpy(h5fi[prot_name][:, :])\n\n use_cuda = (args.device > -1) and torch.cuda.is_available()\n\n if args.checkpoint is None:\n\n projection_dim = args.projection_dim\n dropout_p = args.dropout_p\n embedding = FullyConnectedEmbed(6165, projection_dim, dropout=dropout_p)\n print(\"# Initializing embedding model with:\", file=output)\n print(f\"\\tprojection_dim: {projection_dim}\", file=output)\n print(f\"\\tdropout_p: {dropout_p}\", file=output)\n\n # Create contact model\n hidden_dim = args.hidden_dim\n kernel_width = args.kernel_width\n print(\"# Initializing contact model with:\", file=output)\n print(f\"\\thidden_dim: {hidden_dim}\", file=output)\n print(f\"\\tkernel_width: {kernel_width}\", file=output)\n\n contact = ContactCNN(projection_dim, hidden_dim, kernel_width)\n\n # Create the full model\n use_W = args.use_w\n pool_width = args.pool_width\n print(\"# Initializing interaction model with:\", file=output)\n print(f\"\\tpool_width: {pool_width}\", file=output)\n print(f\"\\tuse_w: {use_W}\", file=output)\n model = ModelInteraction(embedding, contact, use_W=use_W, pool_size=pool_width)\n\n print(model, file=output)\n\n else:\n print(\"# Loading model from checkpoint {}\".format(args.checkpoint), file=output)\n model = torch.load(args.checkpoint)\n model.use_cuda = use_cuda\n\n if use_cuda:\n model = model.cuda()\n\n # Train the model\n lr = args.lr\n wd = args.weight_decay\n num_epochs = args.num_epochs\n batch_size = args.batch_size\n report_steps = args.epoch_scale\n inter_weight = args.lambda_\n cmap_weight = 1 - inter_weight\n digits = int(np.floor(np.log10(num_epochs))) + 1\n save_prefix = args.save_prefix\n if save_prefix is None:\n save_prefix = datetime.datetime.now().strftime(\"%Y-%m-%d-%H-%M\")\n\n params = [p for p in model.parameters() if p.requires_grad]\n optim = torch.optim.Adam(params, lr=lr, weight_decay=wd)\n\n print(f'# Using save prefix \"{save_prefix}\"', file=output)\n print(f\"# Training with Adam: lr={lr}, weight_decay={wd}\", file=output)\n print(f\"\\tnum_epochs: {num_epochs}\", file=output)\n print(f\"\\tepoch_scale: {report_steps}\", file=output)\n print(f\"\\tbatch_size: {batch_size}\", file=output)\n print(f\"\\tinteraction weight: {inter_weight}\", file=output)\n print(f\"\\tcontact map weight: {cmap_weight}\", file=output)\n output.flush()\n\n batch_report_fmt = \"# [{}/{}] training {:.1%}: Loss={:.6}, Accuracy={:.3%}, MSE={:.6}\"\n epoch_report_fmt = \"# Finished Epoch {}/{}: Loss={:.6}, Accuracy={:.3%}, MSE={:.6}, Precision={:.6}, Recall={:.6}, F1={:.6}, AUPR={:.6}\"\n\n N = len(pairs_train_iterator) * batch_size\n for epoch in range(num_epochs):\n\n model.train()\n\n n = 0\n loss_accum = 0\n acc_accum = 0\n mse_accum = 0\n\n # Train batches\n for (z0, z1, y) in tqdm(pairs_train_iterator, desc=f\"Epoch {epoch+1}/{num_epochs}\",total=len(pairs_train_iterator)):\n\n loss, correct, mse, b = interaction_grad(model, z0, z1, y, tensors, use_cuda, weight=inter_weight)\n\n n += b\n delta = b * (loss - loss_accum)\n loss_accum += delta / n\n\n delta = correct - b * acc_accum\n acc_accum += delta / n\n\n delta = b * (mse - mse_accum)\n mse_accum += delta / n\n\n report = (n - b) // 100 < n // 100\n\n optim.step()\n optim.zero_grad()\n model.clip()\n\n if report:\n tokens = [\n epoch + 1,\n num_epochs,\n n / N,\n loss_accum,\n acc_accum,\n mse_accum,\n ]\n if output is not sys.stdout:\n print(batch_report_fmt.format(*tokens), file=output)\n output.flush()\n\n if (epoch + 1) % report_steps == 0:\n model.eval()\n\n with torch.no_grad():\n\n (\n inter_loss,\n inter_correct,\n inter_mse,\n inter_pr,\n inter_re,\n inter_f1,\n inter_aupr,\n ) = interaction_eval(model, pairs_test_iterator, tensors, use_cuda)\n tokens = [\n epoch + 1,\n num_epochs,\n inter_loss,\n inter_correct / (len(pairs_test_iterator) * batch_size),\n inter_mse,\n inter_pr,\n inter_re,\n inter_f1,\n inter_aupr,\n ]\n print(epoch_report_fmt.format(*tokens), file=output)\n output.flush()\n\n # Save the model\n if save_prefix is not None:\n save_path = save_prefix + \"_epoch\" + str(epoch + 1).zfill(digits) + \".sav\"\n print(f\"# Saving model to {save_path}\", file=output)\n model.cpu()\n torch.save(model, save_path)\n if use_cuda:\n model.cuda()\n\n output.flush()\n\n if save_prefix is not None:\n save_path = save_prefix + \"_final.sav\"\n print(f\"# Saving final model to {save_path}\", file=output)\n model.cpu()\n torch.save(model, save_path)\n if use_cuda:\n model.cuda()\n\n output.close()\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=__doc__)\n add_args(parser)\n main(parser.parse_args())\n"
] | [
[
"torch.mean",
"torch.cat",
"torch.load",
"torch.utils.data.DataLoader",
"torch.sum",
"torch.no_grad",
"torch.cuda.is_available",
"torch.save",
"torch.autograd.Variable",
"pandas.read_csv",
"torch.ones",
"torch.from_numpy",
"torch.optim.Adam",
"pandas.concat",
"numpy.log10",
"torch.stack",
"torch.cuda.set_device",
"torch.Tensor",
"sklearn.metrics.average_precision_score",
"torch.cuda.get_device_name"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
spk921/RTFNet | [
"4dad2a63e13e9c302da45ad5a3af4d85cf474694"
] | [
"test.py"
] | [
"# coding:utf-8\n# modified from: https://github.com/haqishen/MFNet-pytorch\n# By Yuxiang Sun, Aug. 2, 2019\n# Email: [email protected]\n\nimport os\nimport argparse\nimport time\nimport datetime\nimport numpy as np\nimport sys\nimport torch \nfrom torch.autograd import Variable\nfrom torch.utils.data import DataLoader\nfrom util.MF_dataset import MF_dataset \nfrom model import RTFNet \nfrom sklearn.metrics import confusion_matrix\n \nn_class = 9\ndata_dir = './dataset/'\nmodel_dir = './weights_backup/' \n\ndef main():\n \n conf_total = np.zeros((n_class,n_class))\n\n model = eval(args.model_name)(n_class=n_class)\n if args.gpu >= 0: model.cuda(args.gpu)\n print('| loading model file %s... ' % model_file)\n \n pretrained_weight = torch.load(model_file, map_location = lambda storage, loc: storage.cuda(args.gpu))\n own_state = model.state_dict()\n for name, param in pretrained_weight.items():\n if name not in own_state:\n continue\n own_state[name].copy_(param) \n print('done!')\n\n test_dataset = MF_dataset(data_dir, args.dataset_name, have_label=True, input_h=args.img_height, input_w=args.img_width)\n test_loader = DataLoader(\n dataset = test_dataset,\n batch_size = batch_size,\n shuffle = False,\n num_workers = args.num_workers,\n pin_memory = True,\n drop_last = False\n )\n test_loader.n_iter = len(test_loader)\n ave_time_cost = 0.0\n\n model.eval()\n \n with torch.no_grad():\n for it, (images, labels, names) in enumerate(test_loader):\n images = Variable(images)\n labels = Variable(labels)\n if args.gpu >= 0:\n images = images.cuda(args.gpu)\n labels = labels.cuda(args.gpu)\n\n start_time = time.time()\n logits = model(images) # logits.size(): mini_batch*num_class*480*640\n end_time = time.time()\n if it>10: # # ignore the first 10 frames\n ave_time_cost += (end_time-start_time)\n\n # convert tensor to numpy 1d array\n label = labels.cpu().numpy().squeeze().flatten()\n prediction = logits.argmax(1).cpu().numpy().squeeze().flatten() # prediction and label are both 1-d array, size: minibatch*640*480\n # generate confusion matrix frame-by-frame\n conf = confusion_matrix(label, prediction, [0,1,2,3,4,5,6,7,8]) # conf is an n_class*n_class matrix, vertical axis: groundtruth, horizontal axis: prediction\n conf_total += conf\n print(\"| frame %d/%d, time cost: %.2f ms\" %(it+1, test_loader.n_iter, (end_time-start_time)*1000)) \n \n # calculate recall (Acc) and IoU for each class \n recall_per_class = np.zeros(n_class)\n iou_per_class = np.zeros(n_class)\n for cid in range(0, n_class): # cid: class id \n if conf_total[cid, 0:].sum() == 0:\n recall_per_class[cid] = np.nan\n else:\n recall_per_class[cid] = float(conf_total[cid, cid]) / float(conf_total[cid, 0:].sum()) # recall (Acc) = TP/TP+FN\n if (conf_total[cid, 0:].sum() + conf_total[0:, cid].sum() - conf_total[cid, cid]) == 0:\n iou_per_class[cid] = np.nan\n else:\n iou_per_class[cid] = float(conf_total[cid, cid]) / float((conf_total[cid, 0:].sum() + conf_total[0:, cid].sum() - conf_total[cid, cid])) # IoU = TP/TP+FP+FN\n \n print('\\n###########################################################################')\n print('\\n| %s: %s test results (with batch size %d) on %s using %s:' %(args.model_name, args.weight_name, batch_size, datetime.date.today(), torch.cuda.get_device_name(args.gpu))) \n print('\\n| * the tested dataset name: %s' % args.dataset_name)\n print('| * the tested image count: %d' % test_loader.n_iter)\n print('| * the tested image size: %d*%d' %(args.img_height, args.img_width)) \n print(\"| * recall per class: \\n unlabeled: %.6f, car: %.6f, person: %.6f, bike: %.6f, curve: %.6f, car_stop: %.6f, guardrail: %.6f, color_cone: %.6f, bump: %.6f\" \\\n %(recall_per_class[0], recall_per_class[1], recall_per_class[2], recall_per_class[3], recall_per_class[4], recall_per_class[5], recall_per_class[6], recall_per_class[7], recall_per_class[8]))\n print(\"| * iou per class: \\n unlabeled: %.6f, car: %.6f, person: %.6f, bike: %.6f, curve: %.6f, car_stop: %.6f, guardrail: %.6f, color_cone: %.6f, bump: %.6f\" \\\n %(iou_per_class[0], iou_per_class[1], iou_per_class[2], iou_per_class[3], iou_per_class[4], iou_per_class[5], iou_per_class[6], iou_per_class[7], iou_per_class[8])) \n\n print(\"\\n| * average values (np.mean(x)): \\n recall: %.6f, iou: %.6f\" \\\n %(recall_per_class.mean(), iou_per_class.mean()))\n print(\"| * average values (np.mean(np.nan_to_num(x))): \\n recall: %.6f, iou: %.6f\" \\\n %(np.mean(np.nan_to_num(recall_per_class)), np.mean(np.nan_to_num(iou_per_class))))\n\n print('\\n| * the average time cost per frame (with batch size %d): %.2f ms, namely, the inference speed is %.2f fps' %(batch_size, ave_time_cost*1000/(test_loader.n_iter-11), 1.0/(ave_time_cost/(test_loader.n_iter-11)))) # ignore the first 10 frames\n\n #print('\\n| * the total confusion matrix: ') \n #np.set_printoptions(precision=8, threshold=np.inf, linewidth=np.inf, suppress=True)\n #print(conf_total)\n print('\\n###########################################################################')\n\nif __name__ == '__main__':\n \n parser = argparse.ArgumentParser(description='Test with pytorch')\n parser.add_argument('--model_name', '-M', type=str, default='RTFNet')\n parser.add_argument('--weight_name', '-W', type=str, default='RTFNet_152') # RTFNet_152, RTFNet_50, please change the number of layers in the network file\n parser.add_argument('--dataset_name', '-D', type=str, default='test') # test, test_day, test_night\n parser.add_argument('--img_height', '-IH', type=int, default=480) \n parser.add_argument('--img_width', '-IW', type=int, default=640) \n parser.add_argument('--gpu', '-G', type=int, default=0)\n parser.add_argument('--num_workers', '-j', type=int, default=8)\n args = parser.parse_args()\n\n batch_size = 1 # do not change this parameter!\t\n\n torch.cuda.set_device(args.gpu)\n print(\"\\n| the gpu count:\", torch.cuda.device_count())\n print(\"| the current used gpu:\", torch.cuda.current_device(), '\\n')\n\n model_dir = os.path.join(model_dir, args.weight_name) # model_dir = './weights_backup/'\n if os.path.exists(model_dir) is False:\n print(\"| the %s does not exit.\" %(model_dir))\n sys.exit()\n model_file = os.path.join(model_dir, 'final.pth')\n if os.path.exists(model_file) is True:\n print('| use the final model file.')\n else:\n print('| no model file found.')\n sys.exit() \n print('| testing %s: %s on GPU #%d with pytorch' % (args.model_name, args.weight_name, args.gpu))\n main()\n"
] | [
[
"torch.cuda.set_device",
"torch.cuda.current_device",
"torch.utils.data.DataLoader",
"sklearn.metrics.confusion_matrix",
"numpy.nan_to_num",
"torch.no_grad",
"torch.cuda.get_device_name",
"torch.cuda.device_count",
"numpy.zeros",
"torch.autograd.Variable"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
wxw-matt/xalpha | [
"b142a5daebac5f1129ead0553efcd40cd471190c"
] | [
"xalpha/multiple.py"
] | [
"# -*- coding: utf-8 -*-\n\"\"\"\nmodule for mul and mulfix class: fund combination management\n\"\"\"\n\nimport logging\nimport pandas as pd\nfrom pyecharts import options as opts\nfrom pyecharts.charts import Pie, ThemeRiver\n\nfrom xalpha.cons import convert_date, myround, yesterdaydash, yesterdayobj\nfrom xalpha.evaluate import evaluate\nfrom xalpha.exceptions import FundTypeError, TradeBehaviorError\nfrom xalpha.record import record, irecord\nfrom xalpha.indicator import indicator\nfrom xalpha.info import cashinfo, fundinfo, mfundinfo, get_fund_holdings\nfrom xalpha.trade import (\n bottleneck,\n trade,\n turnoverrate,\n vtradevolume,\n xirrcal,\n itrade,\n vtradecost,\n)\nfrom xalpha.universal import get_fund_type, ttjjcode, get_rt, get_industry_fromxq\nimport xalpha.universal as xu\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass mul:\n \"\"\"\n multiple fund positions manage class\n\n :param fundtradeobj: list of trade obj which you want to analyse together\n :param status: the status table of trade, all code in this table would be considered.\n one must provide one of the two paramters, if both are offered, status will be overlooked\n 可以是场内记账单 DataFrame,也可以是 record 对象。\n :param istatus: 场内交易账单,也可以是 irecord 对象。\n 若提供,则场内外交易联合统计展示。该选项只保证 ``combsummary`` 方法可正常使用,不保证 ``mul`` 类的其他方法可用。\n :param property: Dict[fundcode, property_number]. property number 的解释:\n int. 1: 基金申购采取分位以后全舍而非四舍五入(这种基金是真实存在的==)。2:基金默认分红再投入(0 则是默认现金分红)。4:基金赎回按净值处理(暂时只支持货币基金,事实上无法精确支持按份额赎回的净值型基金)。将想要的性质数值相加即可,类似 *nix 上的 xwr 系统。\n :param fetch: boolean, when open the fetch option, info class will try fetching from local files first in the init\n :param save: boolean, when open the save option, info classes automatically save the class to files\n :param path: string, the file path prefix of IO, or object or engine from sqlalchemy to connect sql database\n :param form: string, the format of IO, options including: 'csv','sql'\n \"\"\"\n\n def __init__(\n self,\n *fundtradeobj,\n status=None,\n istatus=None,\n property=None,\n fetch=False,\n save=False,\n path=\"\",\n form=\"csv\"\n ):\n if isinstance(status, record):\n if not property:\n property = getattr(status, \"property\", {})\n status = status.status\n elif not property:\n property = {}\n self.is_in = False\n if fundtradeobj:\n for t in fundtradeobj:\n if isinstance(t, itrade):\n self.is_in = True\n break\n else:\n fundtradeobj = []\n # warning: not a very good way to automatic generate these fund obj\n # because there might be some funds use round_down for share calculation, ie, label=2 must be given\n # unless you are sure corresponding funds are added to the droplist\n fundcodelist = [f.code for f in fundtradeobj]\n if status is not None:\n for code in status.columns:\n if code == \"date\":\n continue\n # r1, d2, v4 p = r+d+v\n if code in fundcodelist:\n continue\n p = property.get(code, 0)\n round_label = p % 2\n dividend_label = ((p - round_label) / 2) % 2\n value_label = ((p - round_label - dividend_label) / 4) % 2\n try:\n fundtradeobj.append(\n trade(\n fundinfo(\n code,\n round_label=round_label,\n dividend_label=dividend_label,\n fetch=fetch,\n save=save,\n path=path,\n form=form,\n ),\n status,\n )\n )\n except FundTypeError:\n fundtradeobj.append(\n trade(\n mfundinfo(\n code,\n round_label=round_label,\n value_label=value_label,\n fetch=fetch,\n save=save,\n path=path,\n form=form,\n ),\n status,\n )\n )\n if istatus is not None:\n self.is_in = True\n if isinstance(istatus, irecord):\n istatus = istatus.status\n for code in istatus.code.unique():\n if code not in fundcodelist and not code.startswith(\"#\"):\n fundtradeobj.append(itrade(code, istatus))\n self.fundtradeobj = tuple(fundtradeobj)\n self.totcftable = self._mergecftb()\n\n def tot(self, prop=\"基金现值\", date=yesterdayobj()):\n \"\"\"\n sum of all the values from one prop of fund daily report,\n of coures many of the props make no sense to sum\n\n :param prop: string defined in the daily report dict,\n typical one is 'currentvalue' or 'originalpurchase'\n \"\"\"\n res = 0\n for fund in self.fundtradeobj:\n res += fund.dailyreport().iloc[0][prop]\n return res\n\n def combsummary(self, date=yesterdayobj()):\n \"\"\"\n brief report table of every funds and the combination investment\n\n :param date: string or obj of date, show info of the date given\n :returns: empty dict if nothing is remaining that date\n dict of various data on the trade positions\n \"\"\"\n date = convert_date(date)\n columns = [\n \"基金名称\",\n \"基金代码\",\n \"当日净值\",\n \"单位成本\",\n \"持有份额\",\n \"基金现值\",\n \"基金总申购\",\n \"历史最大占用\",\n \"基金持有成本\",\n \"基金分红与赎回\",\n \"换手率\",\n \"基金收益总额\",\n \"投资收益率\",\n ]\n summarydf = pd.DataFrame([], columns=columns)\n for fund in self.fundtradeobj:\n summarydf = summarydf.append(\n fund.dailyreport(date), ignore_index=True, sort=True\n )\n tname = \"总计\"\n tcode = \"total\"\n tunitvalue = float(\"NaN\")\n tunitcost = float(\"NaN\")\n tholdshare = float(\"NaN\")\n tcurrentvalue = summarydf[\"基金现值\"].sum()\n tpurchase = summarydf[\"基金总申购\"].sum()\n tbtnk = bottleneck(self.totcftable[self.totcftable[\"date\"] <= date])\n tcost = summarydf[\"基金持有成本\"].sum()\n toutput = summarydf[\"基金分红与赎回\"].sum()\n tturnover = turnoverrate(self.totcftable[self.totcftable[\"date\"] <= date], date)\n # 计算的是总系统作为整体和外界的换手率,而非系统各成分之间的换手率\n tearn = summarydf[\"基金收益总额\"].sum()\n trate = round(tearn / tbtnk * 100, 4)\n trow = pd.DataFrame(\n [\n [\n tname,\n tcode,\n tunitvalue,\n tunitcost,\n tholdshare,\n tcurrentvalue,\n tpurchase,\n tbtnk,\n tcost,\n toutput,\n tturnover,\n tearn,\n trate,\n ]\n ],\n columns=columns,\n )\n summarydf = summarydf.append(trow, ignore_index=True, sort=True)\n\n return summarydf[columns].sort_values(by=\"基金现值\", ascending=False)\n\n summary = combsummary\n\n def _mergecftb(self):\n \"\"\"\n merge the different cftable for different funds into one table\n \"\"\"\n dtlist = []\n for fund in self.fundtradeobj:\n dtlist2 = []\n for _, row in fund.cftable.iterrows():\n dtlist2.append((row[\"date\"], row[\"cash\"]))\n dtlist.extend(dtlist2)\n\n nndtlist = set([item[0] for item in dtlist])\n nndtlist = sorted(list(nndtlist), key=lambda x: x)\n reslist = []\n for date in nndtlist:\n reslist.append(sum([item[1] for item in dtlist if item[0] == date]))\n df = pd.DataFrame(data={\"date\": nndtlist, \"cash\": reslist})\n df = df[df[\"cash\"] != 0]\n df = df.reset_index(drop=True)\n return df\n\n def xirrrate(self, date=yesterdayobj(), startdate=None, guess=0.01):\n \"\"\"\n xirr rate evauation of the whole invest combination\n\n :param date: string or obj of datetime, the virtually sell-all date\n :param startdate: string or obj of datetime, the beginning date of calculation, default from first buy\n \"\"\"\n return xirrcal(self.totcftable, self.fundtradeobj, date, startdate, guess)\n\n def evaluation(self, start=None):\n \"\"\"\n give the evaluation object to analysis funds properties themselves instead of trades\n\n :returns: :class:`xalpha.evaluate.evaluate` object, with referenced funds the same as funds\n we invested\n \"\"\"\n if self.is_in:\n raise NotImplementedError()\n case = evaluate(\n *[fundtrade.aim for fundtrade in self.fundtradeobj], start=start\n )\n return case\n\n def get_stock_holdings(\n self, year=None, season=None, date=yesterdayobj(), threhold=100\n ):\n \"\"\"\n 获取整个基金组合的底层股票持仓总和和细节,组合穿透\n\n :param year: 基于的基金季报年份\n :param season: 基于的基金季报季度\n :param date: 默认昨天\n :param threhold: 默认100。小于100元的底层股票将不在最后的结果中展示\n :return: pd.DataFrame column: name, code, value, ratio\n \"\"\"\n d = {}\n if year is None or season is None:\n rd = convert_date(date) - pd.Timedelta(days=120)\n if not year:\n year = rd.year\n if not season:\n season = int((rd.month - 0.1) / 3) + 1\n logger.debug(\"use %s, %s for fund report\" % (year, season))\n for f in self.fundtradeobj:\n if isinstance(f, itrade):\n if f.get_type() == \"股票\":\n code = f.code\n elif f.get_type() == \"场内基金\":\n code = f.code[2:]\n else:\n continue\n else:\n code = f.code\n value = f.briefdailyreport(date).get(\"currentvalue\", 0)\n if value > 0:\n if code.startswith(\"SH\") or code.startswith(\"SZ\"):\n stock = code\n d[stock] = d.get(stock, 0) + value\n elif code == \"mf\":\n continue\n else:\n df = get_fund_holdings(code, year, season)\n if df is None:\n continue\n\n for _, row in df.iterrows():\n stock = row[\"code\"]\n stock = ttjjcode(stock)\n d[stock] = d.get(stock, 0) + row[\"ratio\"] / 100 * value\n # print(\"%s has %s contribution from %s\" %(stock, row[\"ratio\"] / 100 * value, f.name))\n\n l = []\n for code, value in sorted(d.items(), key=lambda item: -item[1]):\n if value >= threhold:\n try:\n name = get_rt(code)[\"name\"]\n except:\n name = code\n l.append([name, code, value])\n fdf = pd.DataFrame(l, columns=[\"name\", \"code\", \"value\"])\n fdf[\"ratio\"] = fdf[\"value\"] / fdf[\"value\"].sum()\n return fdf\n\n def get_portfolio(self, date=yesterdayobj()):\n \"\"\"\n 获取基金组合底层资产大类配置的具体值\n\n :param date:\n :return: Dict[str, float]. stock,bond,cash 对应总值的字典\n \"\"\"\n\n d = {\"stock\": 0, \"bond\": 0, \"cash\": 0}\n date = convert_date(date)\n for f in self.fundtradeobj:\n value = f.briefdailyreport(date).get(\"currentvalue\", 0)\n if value > 0:\n if isinstance(f, itrade):\n if f.get_type() == \"股票\":\n d[\"stock\"] += value\n continue\n elif f.get_type() in [\"可转债\", \"债券\"]:\n d[\"bond\"] += value\n continue\n elif f.get_type() == \"货币基金\":\n d[\"cash\"] += value\n continue\n elif f.get_type() == \"场内基金\":\n code = f.code[2:]\n else:\n continue\n else:\n code = f.code\n if code == \"mf\":\n d[\"cash\"] += value\n continue\n if get_fund_type(code) == \"货币基金\":\n d[\"cash\"] += value\n continue\n df = xu.get_daily(\"pt-F\" + code, end=date.strftime(\"%Y%m%d\"))\n if df is None or len(df) == 0:\n logger.warning(\"empty portfolio info for %s\" % code)\n row = df.iloc[-1]\n if row[\"bond_ratio\"] + row[\"stock_ratio\"] < 10: # 联接基金\n d[\"stock\"] += (\n (100 - row[\"bond_ratio\"] - row[\"cash_ratio\"]) * value / 100\n )\n d[\"bond\"] += row[\"bond_ratio\"] * value / 100\n d[\"cash\"] += row[\"cash_ratio\"] * value / 100\n else:\n d[\"stock\"] += row[\"stock_ratio\"] * value / 100\n d[\"bond\"] += row[\"bond_ratio\"] * value / 100\n d[\"cash\"] += row[\"cash_ratio\"] * value / 100\n return d\n\n get_portfolio_holdings = get_portfolio\n\n def get_industry(self, date=yesterdayobj()):\n \"\"\"\n 获取基金组合持仓的行业占比信息,底层为非 A 股持仓的暂不支持\n\n :param date:\n :return: Dict\n \"\"\"\n # TODO: hard coded 一个字典来合并一些二级行业\n d = {}\n date = convert_date(date)\n rd = date - pd.Timedelta(days=120)\n year = rd.year\n season = int((rd.month - 0.1) / 3) + 1\n for f in self.fundtradeobj:\n value = f.briefdailyreport(date).get(\"currentvalue\", 0)\n if value > 0:\n if isinstance(f, itrade):\n if f.get_type() == \"股票\":\n industry = get_industry_fromxq(f.code).get(\"industryname\", \"\")\n if industry.strip():\n d[industry] = d.get(industry, 0) + value\n continue\n elif f.get_type() in [\"可转债\", \"债券\", \"货币基金\"]:\n # 现在简化实现可转债暂时不按正股记行业\n continue\n elif f.get_type() == \"场内基金\":\n code = f.code[2:]\n else:\n continue\n else:\n code = f.code\n if code == \"mf\":\n continue\n if get_fund_type(code) == \"货币基金\":\n continue\n ## 以下为持有股票的基金处理\n ## fundinfo 有点浪费,不过简化实现暂时如此\n fobj = fundinfo(code)\n industry_dict = fobj.get_industry_holdings(year=year, season=season)\n if industry_dict is None:\n continue\n ## 这里行业占比需要做个 scaling\n sv = sum([v for _, v in industry_dict.items()])\n if sv < 1.0:\n # 只有极少数持仓存在行业信息\n continue\n stock_ratio = fobj.get_portfolio_holdings(date.strftime(\"%Y%m%d\"))[\n \"stock_ratio\"\n ]\n scale = stock_ratio / sv\n print(scale)\n for k, v in industry_dict.items():\n if k.strip():\n d[k] = d.get(k, 0) + value * v / 100 * scale\n return d\n\n get_industry_holdings = get_industry\n\n def v_positions(self, date=yesterdayobj(), rendered=True):\n \"\"\"\n pie chart visualization of positions ratio in combination\n \"\"\"\n sdata = sorted(\n [\n (fob.name, fob.briefdailyreport(date).get(\"currentvalue\", 0))\n for fob in self.fundtradeobj\n ],\n key=lambda x: x[1],\n reverse=True,\n )\n pie = Pie()\n pie.add(\n series_name=\"总值占比\",\n data_pair=sdata,\n label_opts=opts.LabelOpts(is_show=False, position=\"center\"),\n ).set_global_opts(\n legend_opts=opts.LegendOpts(\n pos_left=\"left\", type_=\"scroll\", orient=\"vertical\"\n )\n ).set_series_opts(\n tooltip_opts=opts.TooltipOpts(\n trigger=\"item\", formatter=\"{a} <br/>{b}: {c} ({d}%)\"\n ),\n )\n\n if rendered:\n return pie.render_notebook()\n else:\n return pie\n\n def v_category_positions(self, date=yesterdayobj(), rendered=True):\n \"\"\"\n 资产分类扇形图,按大类资产求和绘制\n\n :param date:\n :param rendered: bool. default true for notebook, for plain pyechart obj to return, set rendered=False\n :return:\n \"\"\"\n d = {}\n for f in self.fundtradeobj:\n if isinstance(f, itrade):\n t = f.get_type()\n if t == \"场内基金\":\n t = get_fund_type(f.code[2:])\n elif f.code == \"mf\":\n t = \"货币基金\"\n else:\n t = get_fund_type(f.code)\n if t == \"其他\":\n logger.warning(\n \"%s has category others which should be double checked\" % f.code\n )\n d[t] = d.get(t, 0) + f.briefdailyreport(date).get(\"currentvalue\", 0)\n\n sdata = sorted([(k, round(v, 2)) for k, v in d.items()])\n pie = Pie()\n pie.add(\n series_name=\"总值占比\",\n data_pair=sdata,\n label_opts=opts.LabelOpts(is_show=False, position=\"center\"),\n ).set_global_opts(\n legend_opts=opts.LegendOpts(\n pos_left=\"left\", type_=\"scroll\", orient=\"vertical\"\n )\n ).set_series_opts(\n tooltip_opts=opts.TooltipOpts(\n trigger=\"item\", formatter=\"{a} <br/>{b}: {c} ({d}%)\"\n ),\n )\n\n if rendered:\n return pie.render_notebook()\n else:\n return pie\n\n def v_positions_history(self, end=yesterdaydash(), rendered=True):\n \"\"\"\n river chart visulization of positions ratio history\n use text size to avoid legend overlap in some sense, eg. legend_text_size=8\n \"\"\"\n start = self.totcftable.iloc[0].date\n times = pd.date_range(start, end)\n tdata = []\n for date in times:\n sdata = sorted(\n [\n (date, fob.briefdailyreport(date).get(\"currentvalue\", 0), fob.name,)\n for fob in self.fundtradeobj\n ],\n key=lambda x: x[1],\n reverse=True,\n )\n tdata.extend(sdata)\n\n tr = ThemeRiver()\n tr.add(\n series_name=[foj.name for foj in self.fundtradeobj],\n data=tdata,\n label_opts=opts.LabelOpts(is_show=False),\n singleaxis_opts=opts.SingleAxisOpts(type_=\"time\", pos_bottom=\"10%\"),\n )\n if rendered:\n return tr.render_notebook()\n else:\n return tr\n\n def v_tradevolume(self, freq=\"D\", rendered=True):\n \"\"\"\n visualization on trade summary of the funds combination\n\n :param freq: one character string, frequency label, now supporting D for date,\n W for week and M for month, namely the trade volume is shown based on the time unit\n :returns: ``pyecharts.Bar()``\n \"\"\"\n return vtradevolume(self.totcftable, freq=freq, rendered=rendered)\n\n\nclass mulfix(mul, indicator):\n \"\"\"\n introduce cash to make a closed investment system, where netvalue analysis can be applied\n namely the totcftable only has one row at the very beginning\n\n :param fundtradeobj: trade obj to be include\n :param status: status table, if no trade obj is provided, it will include all fund\n based on code in status table\n :param property: Dict[fundcode, property_number]. property number 的解释:\n int. 1: 基金申购采取分位以后全舍而非四舍五入(这种基金是真实存在的==)。2:基金默认分红再投入(0 则是默认现金分红)。4:基金赎回按净值\n :param fetch: boolean, when open the fetch option, info class will try fetching from local files first in the init\n :param save: boolean, when open the save option, info classes automatically save the class to files\n :param path: string, the file path prefix of IO, or object or engine from sqlalchemy to connect sql database\n :param form: string, the format of IO, options including: 'csv','sql'\n :param totmoney: positive float, the total money as the input at the beginning\n :param cashobj: cashinfo object, which is designed to balance the cash in and out\n \"\"\"\n\n def __init__(\n self,\n *fundtradeobj,\n status=None,\n istatus=None,\n property=None,\n fetch=False,\n save=False,\n path=\"\",\n form=\"csv\",\n totmoney=100000,\n cashobj=None\n ):\n super().__init__(\n *fundtradeobj,\n status=status,\n istatus=istatus,\n property=property,\n fetch=fetch,\n save=save,\n path=path,\n form=form\n )\n if cashobj is None:\n cashobj = cashinfo()\n self.totmoney = totmoney\n nst = mulfix._vcash(totmoney, self.totcftable, cashobj)\n cashtrade = trade(cashobj, nst)\n # \t\t super().__init__(*self.fundtradeobj, cashtrade)\n self.cashobj = cashobj\n self.fundtradeobj = list(self.fundtradeobj)\n self.fundtradeobj.append(cashtrade)\n self.fundtradeobj = tuple(self.fundtradeobj)\n btnk = bottleneck(self.totcftable)\n if btnk > totmoney:\n raise TradeBehaviorError(\"the initial total cash is too low\")\n self.totcftable = pd.DataFrame(\n data={\"date\": [nst.iloc[0].date], \"cash\": [-totmoney]}\n )\n\n @staticmethod\n def _vcash(totmoney, totcftable, cashobj):\n \"\"\"\n return a virtue status table with a mf(cash) column based on the given tot money and cftable\n \"\"\"\n cashl = []\n cashl.append(totmoney + totcftable.iloc[0].cash)\n for i in range(len(totcftable) - 1):\n date = totcftable.iloc[i + 1].date\n delta = totcftable.iloc[i + 1].cash\n if delta < 0:\n cashl.append(\n myround(\n delta\n / cashobj.price[cashobj.price[\"date\"] <= date].iloc[-1].netvalue\n )\n )\n else:\n cashl.append(delta)\n datadict = {\"date\": totcftable.loc[:, \"date\"], \"mf\": cashl}\n return pd.DataFrame(data=datadict)\n\n def unitvalue(self, date=yesterdayobj()):\n \"\"\"\n :returns: float at unitvalue of the whole investment combination\n \"\"\"\n date = convert_date(date)\n res = 0\n for fund in self.fundtradeobj:\n res += fund.briefdailyreport(date).get(\"currentvalue\", 0)\n return res / self.totmoney\n\n def v_tradecost(self, threhold=0, date=yesterdayobj(), rendered=True):\n if getattr(self, \"price\", None) is None:\n raise ValueError(\"Please generate price table by ``bcmkset()`` first\")\n cftable = self.fundtradeobj[-1].cftable[1:]\n cftable = cftable[abs(cftable[\"cash\"]) > threhold]\n cftable[\"cash\"] = -cftable[\"cash\"]\n return vtradecost(self, cftable, end=date, rendered=rendered)\n\n\nclass imul(mul):\n def __init__(self, *fundtradeobj, status=None, istatus=None):\n \"\"\"\n 对场内投资组合进行分析的类\n\n :param fundtradeobj: itrade objects.\n :param status: 场内格式记账单,或 irecord 对象。\n \"\"\"\n\n if not fundtradeobj:\n fundtradeobj = []\n if status is None:\n status = istatus\n if isinstance(status, irecord):\n status = status.status\n fundcodelist = [f.code for f in fundtradeobj]\n if status is not None:\n for code in status.code.unique():\n if code not in fundcodelist and not code.startswith(\"#\"):\n fundtradeobj.append(itrade(code, status))\n self.fundtradeobj = tuple(fundtradeobj)\n self.totcftable = self._mergecftb()\n self.is_in = True\n\n\nMul = mul\nMulFix = mulfix\nIMul = imul\n"
] | [
[
"pandas.Timedelta",
"pandas.DataFrame",
"pandas.date_range"
]
] | [
{
"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": []
}
] |
smrutiranjans/tensorflow | [
"d8e8b872eae63188c75046d5bb068e03a81b3f85",
"d8e8b872eae63188c75046d5bb068e03a81b3f85",
"7d9ab3eb485e6eb1778bad4ef01a1cd95b2d22d9",
"d8e8b872eae63188c75046d5bb068e03a81b3f85"
] | [
"tensorflow/python/ops/op_def_library.py",
"tensorflow/python/summary/event_multiplexer.py",
"tensorflow/python/kernel_tests/concat_op_test.py",
"tensorflow/tensorboard/backend/server_test.py"
] | [
"# Copyright 2015 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\n\"\"\"Class to hold a library of OpDefs and use it to create Brain operations.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport contextlib\n\nimport six\n\nfrom tensorflow.core.framework import attr_value_pb2\nfrom tensorflow.core.framework import op_def_pb2\nfrom tensorflow.core.framework import tensor_pb2\nfrom tensorflow.core.framework import tensor_shape_pb2\nfrom tensorflow.core.framework import types_pb2\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.ops import constant_op\nfrom tensorflow.python.platform import logging\nfrom tensorflow.python.util import compat\n\n\ndef _Attr(op_def, name):\n for attr in op_def.attr:\n if attr.name == name:\n return attr\n raise TypeError(\"Inconsistent OpDef for '%s', missing attr '%s'\" %\n (op_def.name, name))\n\n\ndef _AttrValue(attr_protos, name):\n if name in attr_protos:\n return attr_protos[name]\n raise TypeError(\"Inconsistent OpDef, missing attr '%s' from '%s'.\" %\n (name, attr_protos))\n\n\ndef _SatisfiesTypeConstraint(dtype, attr_def):\n if attr_def.HasField(\"allowed_values\"):\n allowed_list = attr_def.allowed_values.list.type\n if dtype not in allowed_list:\n raise TypeError(\n \"DataType %s for attr '%s' not in list of allowed values: %s\" %\n (dtypes.as_dtype(dtype).name, attr_def.name,\n \", \".join(dtypes.as_dtype(x).name for x in allowed_list)))\n\n\ndef _IsListParameter(arg):\n if arg.number_attr:\n return True\n elif arg.type_list_attr:\n return True\n return False\n\n\ndef _NumTypeFields(arg):\n num = 0\n if arg.type != types_pb2.DT_INVALID: num += 1\n if arg.type_attr: num += 1\n if arg.type_list_attr: num += 1\n return num\n\n\ndef _IsListValue(v):\n return isinstance(v, (list, tuple))\n\n\ndef _Flatten(l):\n \"\"\"Converts [1, 2, [3, 4], [5]] to [1, 2, 3, 4, 5].\"\"\"\n # [1, 2, [3, 4], [5]] -> [[1], [2], [3, 4], [5]]\n l_of_l = [x if _IsListValue(x) else [x] for x in l]\n # [[1], [2], [3, 4], [5]] -> [1, 2, 3, 4, 5]\n return [item for sublist in l_of_l for item in sublist]\n\n\ndef _Restructure(l, structure):\n \"\"\"Returns the elements of list l structured according to the given structure.\n\n A structure is represented by a list whose elements are either\n `None` or a non-negative integer. `None` corresponds to a single\n element in the output list, and an integer N corresponds to a nested\n list of length N.\n\n The function returns a data structure whose shape is given by\n `structure`, and whose elements are taken from `l`. If `structure`\n is a singleton, the function returns the single data structure\n implied by the 0th element of `structure`. For example:\n\n _Restructure([\"foo\", \"bar\", \"baz\", \"qux\"], [None, 2, None])\n -> [\"foo\", [\"bar\", \"baz\"], \"qux\"]\n\n _Restructure([\"foo\"], [None]) -> \"foo\"\n\n _Restructure([\"foo\"], [1]) -> [\"foo\"]\n\n _Restructure([], [0]) -> []\n\n Args:\n l: A list.\n structure: A list whose elements are either `None` or a non-negative\n integer.\n\n Returns:\n The elements of `l`, restructured according to `structure`. If\n `structure` is a list of length 1, this function returns the\n single data structure implied by `structure[0]`.\n\n \"\"\"\n result = []\n current_index = 0\n for element in structure:\n if element is None:\n result.append(l[current_index])\n current_index += 1\n else:\n result.append(l[current_index:current_index+element])\n current_index += element\n\n if len(result) == 1:\n return result[0]\n else:\n return tuple(result)\n\n\ndef _MakeFloat(v, arg_name):\n if not isinstance(v, compat.real_types):\n raise TypeError(\"Expected float for argument '%s' not %s.\" %\n (arg_name, repr(v)))\n return float(v)\n\n\ndef _MakeInt(v, arg_name):\n if isinstance(v, six.string_types):\n raise TypeError(\"Expected int for argument '%s' not %s.\" %\n (arg_name, repr(v)))\n try:\n return int(v)\n except (ValueError, TypeError):\n raise TypeError(\"Expected int for argument '%s' not %s.\" %\n (arg_name, repr(v)))\n\n\ndef _MakeStr(v, arg_name):\n if not isinstance(v, compat.bytes_or_text_types):\n raise TypeError(\"Expected string for argument '%s' not %s.\" %\n (arg_name, repr(v)))\n return compat.as_bytes(v) # Convert unicode strings to bytes.\n\n\ndef _MakeBool(v, arg_name):\n if not isinstance(v, bool):\n raise TypeError(\"Expected bool for argument '%s' not %s.\" %\n (arg_name, repr(v)))\n return v\n\n\ndef _MakeType(v, attr_def):\n try:\n v = dtypes.as_dtype(v)\n except TypeError:\n raise TypeError(\"Expected DataType for argument '%s' not %s.\" %\n (attr_def.name, repr(v)))\n i = v.as_datatype_enum\n _SatisfiesTypeConstraint(i, attr_def)\n return i\n\n\ndef _MakeShape(v, arg_name):\n \"\"\"Convert v into a TensorShapeProto.\"\"\"\n # Args:\n # v: A TensorShapeProto, a list of ints, or a tensor_shape.TensorShape.\n # arg_name: String, for error messages.\n\n # Returns:\n # A TensorShapeProto.\n if isinstance(v, tensor_shape_pb2.TensorShapeProto):\n for d in v.dim:\n if d.name:\n logging.warning(\"Warning: TensorShapeProto with a named dimension: %s\",\n str(v))\n break\n return v\n return tensor_shape.as_shape(v).as_proto()\n\n\ndef _MakeTensor(v, arg_name):\n \"\"\"Ensure v is a TensorProto.\"\"\"\n if isinstance(v, tensor_pb2.TensorProto):\n return v\n raise TypeError(\n \"Don't know how to convert %s to a TensorProto for argument '%s'\" %\n (repr(v), arg_name))\n\n\nclass _OpInfo(object):\n \"\"\"All per-Op state we would like to precompute/validate.\"\"\"\n\n def __init__(self, op_def):\n self.op_def = op_def\n # TODO(josh11b): SWIG the ValidateOpDef() function from C++ and call it\n # here, instead of these checks.\n for arg in list(op_def.input_arg) + list(op_def.output_arg):\n num_type_fields = _NumTypeFields(arg)\n if num_type_fields != 1:\n raise TypeError(\"Arg '%s' of '%s' must have one type field not %d\" %\n (arg.name, op_def.name, num_type_fields))\n if arg.type_attr:\n attr_type = _Attr(op_def, arg.type_attr).type\n if attr_type != \"type\":\n raise TypeError(\"Attr '%s' of '%s' used as a type_attr \"\n \"but has type %s\" %\n (arg.type_attr, op_def.name, attr_type))\n if arg.type_list_attr:\n attr_type = _Attr(op_def, arg.type_list_attr).type\n if attr_type != \"list(type)\":\n raise TypeError(\n \"Attr '%s' of '%s' used as a type_list_attr but has type %s\" %\n (arg.type_attr, op_def.name, attr_type))\n if arg.number_attr:\n attr_type = _Attr(op_def, arg.number_attr).type\n if attr_type != \"int\":\n raise TypeError(\n \"Attr '%s' of '%s' used as a number_attr but has type %s\" %\n (arg.number_attr, op_def.name, attr_type))\n\n\n# pylint: disable=g-doc-return-or-yield\[email protected]\ndef _MaybeColocateWith(inputs):\n \"\"\"A context manager for (maybe) colocating with a list of input tensors.\n\n Args:\n inputs: A list of `Tensor` or `Operation` objects.\n\n Returns:\n A context manager.\n \"\"\"\n if not inputs:\n yield\n else:\n # NOTE(mrry): The `ops.colocate_with()` function accepts only a single\n # op or tensor, so we create one context manager per element in the list.\n with ops.colocate_with(inputs[0]), _MaybeColocateWith(inputs[1:]):\n yield\n# pylint: enable=g-doc-return-or-yield\n\n\nclass OpDefLibrary(object):\n \"\"\"Holds a collection of OpDefs, can add the corresponding Ops to a graph.\"\"\"\n\n def __init__(self):\n self._ops = {}\n\n def add_op(self, op_def):\n \"\"\"Register an OpDef. May call apply_op with the name afterwards.\"\"\"\n if not isinstance(op_def, op_def_pb2.OpDef):\n raise TypeError(\"%s is %s, not an op_def_pb2.OpDef\" %\n (op_def, type(op_def)))\n if not op_def.name:\n raise ValueError(\"%s missing name.\" % op_def)\n if op_def.name in self._ops:\n raise RuntimeError(\"Op name %s registered twice.\" % op_def.name)\n self._ops[op_def.name] = _OpInfo(op_def)\n\n def add_op_list(self, op_list):\n \"\"\"Register the OpDefs from an OpList.\"\"\"\n if not isinstance(op_list, op_def_pb2.OpList):\n raise TypeError(\"%s is %s, not an op_def_pb2.OpList\" %\n (op_list, type(op_list)))\n for op_def in op_list.op:\n self.add_op(op_def)\n\n def apply_op(self, op_type_name, name=None, **keywords):\n # pylint: disable=g-doc-args\n \"\"\"Add a node invoking a registered Op to a graph.\n\n Config proto extensions must be provided via the 'ext' keyword argument.\n Example usage:\n # input1 and input2 can be Tensors or anything ops.convert_to_tensor()\n # will convert to a Tensor.\n op_def_library.apply_op(\"op\", input1=input1, input2=input2)\n # Can specify a node name.\n op_def_library.apply_op(\"op\", input1=input1, name=\"node_name\")\n # Must use keyword arguments, with the names specified in the OpDef.\n op_def_library.apply_op(\"op\", input_name=input, attr_name=attr)\n\n All attrs must either be inferred from an input or specified.\n (If inferred, the attr must not be specified.) If an attr has a default\n value specified in the Op's OpDef, then you may pass None as the value\n of that attr to get the default.\n\n Args:\n op_type_name: string. Must match the name field of a registered Op.\n name: string. Optional name of the created op.\n **keywords: input Tensor and attr arguments specified by name,\n and optional parameters to pass when constructing the Operation.\n\n Returns:\n The Tensor(s) representing the output of the operation, or the Operation\n itself if there are no outputs.\n\n Raises:\n RuntimeError: On some errors.\n TypeError: On some errors.\n ValueError: On some errors.\n \"\"\"\n op_info = self._ops.get(op_type_name, None)\n if op_info is None:\n raise RuntimeError(\"Unrecognized Op name \" + op_type_name)\n op_def = op_info.op_def\n\n # Determine the graph context.\n try:\n # Need to flatten all the arguments into a list.\n # pylint: disable=protected-access\n g = ops._get_graph_from_inputs(_Flatten(keywords.values()))\n # pyline: enable=protected-access\n except AssertionError as e:\n raise RuntimeError(\n \"Cannot determine graph for Op '%s' due to: %s\"\n % (op_type_name, e.message))\n\n # Default name if not specified.\n if name is None:\n name = op_type_name\n\n # Check for deprecation\n deprecation_version = op_def.deprecation.version\n if deprecation_version:\n producer = g.graph_def_versions.producer\n if producer >= deprecation_version:\n raise NotImplementedError(\n (\"Op %s is not available in GraphDef version %d. \"\n \"It has been removed in version %d. %s.\") %\n (op_type_name, producer, deprecation_version,\n op_def.deprecation.explanation))\n\n # Requires that op_def has passed validation (using the C++\n # ValidateOpDef() from ../framework/op_def_util.h).\n attrs = {}\n inputs = []\n input_types = []\n with g.as_default(), ops.name_scope(name) as scope:\n\n # Perform input type inference\n inferred_from = {}\n for input_arg in op_def.input_arg:\n input_name = input_arg.name\n if input_name in keywords:\n values = keywords.pop(input_name)\n elif input_name + \"_\" in keywords:\n # Handle the case where the name is a keyword or built-in\n # for Python so we use the name + _ instead.\n input_name += \"_\"\n values = keywords.pop(input_name)\n else:\n raise TypeError(\"No argument for input \" + input_name)\n\n # Goals:\n # * Convert values to Tensors if it contains constants.\n # * Verify that values is a list if that matches the input_arg's\n # type.\n # * If the input_arg's type is determined by attrs, either set\n # those attrs and validate those attr values are legal (if\n # they have not yet been set) or validate the input matches\n # the type indicated by the attrs (if they have already been\n # inferred via an earlier input).\n # * If the input_arg has an explicit type, make sure the input\n # conforms.\n\n if _IsListParameter(input_arg):\n if not _IsListValue(values):\n raise TypeError(\n \"Expected list for '%s' argument to '%s' Op, not %s.\" %\n (input_name, op_type_name, values))\n # In cases where we expect all elements of the list to have the\n # same dtype, try to cast non-Tensor elements to that type.\n dtype = None\n if input_arg.type != types_pb2.DT_INVALID:\n dtype = input_arg.type\n elif input_arg.number_attr:\n if input_arg.type_attr in attrs:\n dtype = attrs[input_arg.type_attr]\n else:\n for t in values:\n if isinstance(t, ops.Tensor):\n dtype = t.dtype\n break\n\n try:\n if not input_arg.is_ref and dtype:\n dtype = dtypes.as_dtype(dtype).base_dtype\n values = ops.convert_n_to_tensor(\n values, name=input_arg.name, dtype=dtype if dtype else None,\n as_ref=input_arg.is_ref)\n except (TypeError, ValueError):\n assert dtype is not None, \"Should not fail if dtype is None\"\n assert input_arg.number_attr, \"Should be number_attr case\"\n # What types does the conversion function think values have?\n values = ops.convert_n_to_tensor(values, as_ref=input_arg.is_ref)\n observed = \", \".join(v.dtype.base_dtype.name for v in values)\n\n prefix = (\n \"Tensors in list passed to '%s' of '%s' Op have types [%s]\" %\n (input_name, op_type_name, observed))\n if input_arg.type != types_pb2.DT_INVALID:\n raise TypeError(\"%s that do not match expected type %s.\" %\n (prefix, dtype.name))\n elif input_arg.type_attr in attrs:\n raise TypeError(\"%s that do not match type %s inferred from \"\n \"earlier arguments.\" %\n (prefix, dtype.name))\n else:\n raise TypeError(\"%s that don't all match.\" % prefix)\n\n types = [x.dtype for x in values]\n inputs.extend(values)\n else:\n # In cases where we have an expected type, try to convert non-Tensor\n # arguments to that type.\n dtype = None\n if input_arg.type != types_pb2.DT_INVALID:\n dtype = input_arg.type\n elif input_arg.type_attr in attrs:\n dtype = attrs[input_arg.type_attr]\n try:\n values = ops.convert_to_tensor(\n values, name=input_arg.name, dtype=dtype,\n as_ref=input_arg.is_ref)\n except ValueError:\n # What type does convert_to_tensor think it has?\n observed = ops.convert_to_tensor(values,\n as_ref=input_arg.is_ref).dtype.name\n prefix = (\"Input '%s' of '%s' Op has type %s that does not match\" %\n (input_name, op_type_name, observed))\n if input_arg.type != types_pb2.DT_INVALID:\n raise TypeError(\"%s expected type of %s.\" %\n (prefix, dtypes.as_dtype(input_arg.type).name))\n else:\n raise TypeError(\n \"%s type %s of argument '%s'.\" %\n (prefix, dtypes.as_dtype(attrs[input_arg.type_attr]).name,\n inferred_from[input_arg.type_attr]))\n\n types = [values.dtype]\n inputs.append(values)\n base_types = [x.base_dtype for x in types]\n\n if input_arg.number_attr:\n # <number-attr> * <type> or <number-attr> * <type-attr>\n if input_arg.number_attr in attrs:\n if len(values) != attrs[input_arg.number_attr]:\n raise ValueError(\n \"List argument '%s' to '%s' Op with length %d must match \"\n \"length %d of argument '%s'.\" %\n (input_name, op_type_name, len(values),\n attrs[input_arg.number_attr],\n inferred_from[input_arg.number_attr]))\n else:\n attrs[input_arg.number_attr] = len(values)\n inferred_from[input_arg.number_attr] = input_name\n num_attr = _Attr(op_def, input_arg.number_attr)\n if num_attr.has_minimum and len(values) < num_attr.minimum:\n raise ValueError(\n \"List argument '%s' to '%s' Op with length %d shorter \"\n \"than minimum length %d.\" %\n (input_name, op_type_name, len(values), num_attr.minimum))\n # All tensors must have the same base type.\n if any([bt != base_types[0] for bt in base_types]):\n raise TypeError(\n \"All tensors passed to '%s' of '%s' Op \"\n \"must have the same type.\" %\n (input_name, op_type_name))\n if input_arg.type != types_pb2.DT_INVALID:\n # <number-attr> * <type> case\n if base_types and base_types[0] != input_arg.type:\n assert False, \"Unreachable\"\n elif input_arg.type_attr in attrs:\n # <number-attr> * <type-attr> case, where <type-attr> already\n # has an inferred value.\n if base_types and base_types[0] != attrs[input_arg.type_attr]:\n assert False, \"Unreachable\"\n else:\n # <number-attr> * <type-attr> case, where we are now setting\n # the <type-attr> based on this input\n if not base_types:\n raise TypeError(\n \"Don't know how to infer type variable from empty input \"\n \"list passed to input '%s' of '%s' Op.\" %\n (input_name, op_type_name))\n attrs[input_arg.type_attr] = base_types[0]\n inferred_from[input_arg.type_attr] = input_name\n type_attr = _Attr(op_def, input_arg.type_attr)\n _SatisfiesTypeConstraint(base_types[0], type_attr)\n elif input_arg.type_attr:\n # <type-attr>\n attr_value = base_types[0]\n if input_arg.type_attr in attrs:\n if attrs[input_arg.type_attr] != attr_value:\n assert False, \"Unreachable\"\n else:\n for base_type in base_types:\n _SatisfiesTypeConstraint(base_type,\n _Attr(op_def, input_arg.type_attr))\n attrs[input_arg.type_attr] = attr_value\n inferred_from[input_arg.type_attr] = input_name\n elif input_arg.type_list_attr:\n # <type-list-attr>\n attr_value = base_types\n if input_arg.type_list_attr in attrs:\n if attrs[input_arg.type_list_attr] != attr_value:\n raise TypeError(\n \"Input '%s' of '%s' Op has type list of %s that does not \"\n \"match type list %s of argument '%s'.\" %\n (input_name, op_type_name,\n \", \".join(dtypes.as_dtype(x).name for x in attr_value),\n \", \".join(dtypes.as_dtype(x).name\n for x in attrs[input_arg.type_list_attr]),\n inferred_from[input_arg.type_list_attr]))\n else:\n for base_type in base_types:\n _SatisfiesTypeConstraint(base_type,\n _Attr(op_def, input_arg.type_list_attr))\n attrs[input_arg.type_list_attr] = attr_value\n inferred_from[input_arg.type_list_attr] = input_name\n else:\n # single Tensor with specified type\n if base_types[0] != input_arg.type:\n assert False, \"Unreachable\"\n\n if input_arg.is_ref:\n if not all(x.is_ref_dtype for x in types):\n raise TypeError(\n \"Input '%s' of '%s' Op requires l-value input\" %\n (input_name, op_type_name))\n input_types.extend(types)\n else:\n input_types.extend(base_types)\n\n # Process remaining attrs\n for attr in op_def.attr:\n # Skip attrs that have already had their values inferred\n if attr.name in attrs:\n if attr.name in keywords:\n raise TypeError(\n \"Should not specify value for inferred attr '%s'.\" % attr.name)\n continue\n if attr.name in keywords:\n attrs[attr.name] = keywords.pop(attr.name)\n elif attr.name + \"_\" in keywords:\n # Attrs whose names match Python keywords have an extra '_'\n # appended, so we must check for that as well.\n attrs[attr.name] = keywords.pop(attr.name + \"_\")\n else:\n raise TypeError(\"No argument for attr \" + attr.name)\n\n # Convert attr values to AttrValue protos.\n attr_protos = {}\n for attr_def in op_def.attr:\n key = attr_def.name\n value = attrs[key]\n attr_value = attr_value_pb2.AttrValue()\n if attr_def.HasField(\"default_value\") and value is None:\n attr_value.CopyFrom(attr_def.default_value)\n attr_protos[key] = attr_value\n continue\n if attr_def.type.startswith(\"list(\"):\n if not _IsListValue(value):\n raise TypeError(\"Expected list for attr \" + key)\n if attr_def.has_minimum:\n if len(value) < attr_def.minimum:\n raise ValueError(\"Attr '%s' of '%s' Op passed list of length %d \"\n \"less than minimum %d.\" %\n (key, op_type_name, len(value),\n attr_def.minimum))\n attr_value.list.SetInParent()\n if attr_def.type == \"string\":\n attr_value.s = _MakeStr(value, key)\n if attr_def.HasField(\"allowed_values\"):\n if attr_value.s not in attr_def.allowed_values.list.s:\n raise ValueError(\n \"Attr '%s' of '%s' Op passed string '%s' not in: \\\"%s\\\".\" %\n (key, op_type_name, compat.as_text(attr_value.s),\n '\", \"'.join(map(compat.as_text,\n attr_def.allowed_values.list.s))))\n elif attr_def.type == \"list(string)\":\n attr_value.list.s.extend([_MakeStr(x, key) for x in value])\n if attr_def.HasField(\"allowed_values\"):\n for x in attr_value.list.s:\n if x not in attr_def.allowed_values.list.s:\n raise ValueError(\n \"Attr '%s' of '%s' Op passed string '%s' not in: \\\"%s\\\".\" %\n (key, op_type_name, compat.as_text(x),\n '\", \"'.join(map(compat.as_text,\n attr_def.allowed_values.list.s))))\n elif attr_def.type == \"int\":\n attr_value.i = _MakeInt(value, key)\n if attr_def.has_minimum:\n if attr_value.i < attr_def.minimum:\n raise ValueError(\n \"Attr '%s' of '%s' Op passed %d less than minimum %d.\" %\n (key, op_type_name, attr_value.i, attr_def.minimum))\n elif attr_def.type == \"list(int)\":\n attr_value.list.i.extend([_MakeInt(x, key) for x in value])\n elif attr_def.type == \"float\":\n attr_value.f = _MakeFloat(value, key)\n elif attr_def.type == \"list(float)\":\n attr_value.list.f.extend([_MakeFloat(x, key) for x in value])\n elif attr_def.type == \"bool\":\n attr_value.b = _MakeBool(value, key)\n elif attr_def.type == \"list(bool)\":\n attr_value.list.b.extend([_MakeBool(x, key) for x in value])\n elif attr_def.type == \"type\":\n attr_value.type = _MakeType(value, attr_def)\n elif attr_def.type == \"list(type)\":\n attr_value.list.type.extend(\n [_MakeType(x, attr_def) for x in value])\n elif attr_def.type == \"shape\":\n attr_value.shape.CopyFrom(_MakeShape(value, key))\n elif attr_def.type == \"list(shape)\":\n attr_value.list.shape.extend(\n [_MakeShape(x, key) for x in value])\n elif attr_def.type == \"tensor\":\n attr_value.tensor.CopyFrom(_MakeTensor(value, key))\n elif attr_def.type == \"list(tensor)\":\n attr_value.list.tensor.extend(\n [_MakeTensor(x, key) for x in value])\n elif attr_def.type == \"func\":\n if not isinstance(value, compat.bytes_or_text_types):\n raise TypeError(\"Expects a string for the func name\")\n attr_value.func.name = value\n else:\n raise TypeError(\"Unrecognized Attr type \" + attr_def.type)\n\n attr_protos[key] = attr_value\n del attrs # attrs is no longer authoritative, use attr_protos instead\n\n # Determine output types (possibly using attrs)\n output_types = []\n output_structure = []\n for arg in op_def.output_arg:\n types = []\n if arg.number_attr:\n n = _AttrValue(attr_protos, arg.number_attr).i\n if arg.type_attr:\n types = [_AttrValue(attr_protos, arg.type_attr).type] * n\n else:\n types = [arg.type] * n\n output_structure.append(n)\n elif arg.type_attr:\n t = _AttrValue(attr_protos, arg.type_attr)\n types = [t.type]\n output_structure.append(None)\n elif arg.type_list_attr:\n t = _AttrValue(attr_protos, arg.type_list_attr)\n types = t.list.type\n output_structure.append(len(t.list.type))\n else:\n types = [arg.type]\n output_structure.append(None)\n if arg.is_ref:\n types = [dtypes.as_dtype(x).as_ref for x in types]\n output_types.extend(types)\n\n if keywords:\n raise TypeError(\"apply_op() got unexpected keyword arguments: \" +\n \", \".join(sorted(keywords.keys())))\n\n # NOTE(mrry): We add an explicit colocation constraint between\n # the newly created op and any of its reference-typed inputs.\n must_colocate_inputs = [val for arg, val in zip(op_def.input_arg, inputs)\n if arg.is_ref]\n with _MaybeColocateWith(must_colocate_inputs):\n # Add Op to graph\n if output_structure:\n op = g.create_op(op_type_name, inputs, output_types, name=scope,\n input_types=input_types, attrs=attr_protos,\n op_def=op_def)\n outputs = op.outputs\n return _Restructure(ops.convert_n_to_tensor(outputs),\n output_structure)\n else:\n return g.create_op(op_type_name, inputs, output_types, name=scope,\n input_types=input_types, attrs=attr_protos,\n op_def=op_def)\n",
"# Copyright 2015 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\"\"\"Provides an interface for working with multiple event files.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport threading\n\nimport six\n\nfrom tensorflow.python.platform import logging\nfrom tensorflow.python.summary import event_accumulator\nfrom tensorflow.python.summary.impl import io_wrapper\n\n\nclass EventMultiplexer(object):\n \"\"\"An `EventMultiplexer` manages access to multiple `EventAccumulator`s.\n\n Each `EventAccumulator` is associated with a `run`, which is a self-contained\n TensorFlow execution. The `EventMultiplexer` provides methods for extracting\n information about events from multiple `run`s.\n\n Example usage for loading specific runs from files:\n\n ```python\n x = EventMultiplexer({'run1': 'path/to/run1', 'run2': 'path/to/run2'})\n x.Reload()\n ```\n\n Example usage for loading a directory where each subdirectory is a run\n\n ```python\n (eg:) /parent/directory/path/\n /parent/directory/path/run1/\n /parent/directory/path/run1/events.out.tfevents.1001\n /parent/directory/path/run1/events.out.tfevents.1002\n\n /parent/directory/path/run2/\n /parent/directory/path/run2/events.out.tfevents.9232\n\n /parent/directory/path/run3/\n /parent/directory/path/run3/events.out.tfevents.9232\n x = EventMultiplexer().AddRunsFromDirectory('/parent/directory/path')\n (which is equivalent to:)\n x = EventMultiplexer({'run1': '/parent/directory/path/run1', 'run2':...}\n ```\n\n If you would like to watch `/parent/directory/path`, wait for it to be created\n (if necessary) and then periodically pick up new runs, use\n `AutoloadingMultiplexer`\n\n @@__init__\n @@AddRun\n @@AddRunsFromDirectory\n @@Reload\n @@Runs\n @@Scalars\n @@Graph\n @@Histograms\n @@CompressedHistograms\n @@Images\n \"\"\"\n\n def __init__(self,\n run_path_map=None,\n size_guidance=event_accumulator.DEFAULT_SIZE_GUIDANCE,\n purge_orphaned_data=True):\n \"\"\"Constructor for the `EventMultiplexer`.\n\n Args:\n run_path_map: Dict `{run: path}` which specifies the\n name of a run, and the path to find the associated events. If it is\n None, then the EventMultiplexer initializes without any runs.\n size_guidance: A dictionary mapping from `tagType` to the number of items\n to store for each tag of that type. See\n `event_ccumulator.EventAccumulator` for details.\n purge_orphaned_data: Whether to discard any events that were \"orphaned\" by\n a TensorFlow restart.\n \"\"\"\n self._accumulators_mutex = threading.Lock()\n self._accumulators = {}\n self._paths = {}\n self._reload_called = False\n self._size_guidance = size_guidance\n self.purge_orphaned_data = purge_orphaned_data\n if run_path_map is not None:\n for (run, path) in six.iteritems(run_path_map):\n self.AddRun(path, run)\n\n def AddRun(self, path, name=None):\n \"\"\"Add a run to the multiplexer.\n\n If the name is not specified, it is the same as the path.\n\n If a run by that name exists, and we are already watching the right path,\n do nothing. If we are watching a different path, replace the event\n accumulator.\n\n If `Reload` has been called, it will `Reload` the newly created\n accumulators. This maintains the invariant that once the Multiplexer was\n activated, all of its accumulators are active.\n\n Args:\n path: Path to the event files (or event directory) for given run.\n name: Name of the run to add. If not provided, is set to path.\n\n Returns:\n The `EventMultiplexer`.\n \"\"\"\n if name is None or name is '':\n name = path\n accumulator = None\n with self._accumulators_mutex:\n if name not in self._accumulators or self._paths[name] != path:\n if name in self._paths and self._paths[name] != path:\n # TODO(danmane) - Make it impossible to overwrite an old path with\n # a new path (just give the new path a distinct name)\n logging.warning('Conflict for name %s: old path %s, new path %s',\n name, self._paths[name], path)\n logging.info('Constructing EventAccumulator for %s', path)\n accumulator = event_accumulator.EventAccumulator(\n path,\n size_guidance=self._size_guidance,\n purge_orphaned_data=self.purge_orphaned_data)\n self._accumulators[name] = accumulator\n self._paths[name] = path\n if accumulator:\n if self._reload_called:\n accumulator.Reload()\n return self\n\n def AddRunsFromDirectory(self, path, name=None):\n \"\"\"Load runs from a directory; recursively walks subdirectories.\n\n If path doesn't exist, no-op. This ensures that it is safe to call\n `AddRunsFromDirectory` multiple times, even before the directory is made.\n\n If path is a directory, load event files in the directory (if any exist) and\n recursively call AddRunsFromDirectory on any subdirectories. This mean you\n can call AddRunsFromDirectory at the root of a tree of event logs and\n TensorBoard will load them all.\n\n If the `EventMultiplexer` is already loaded this will cause\n the newly created accumulators to `Reload()`.\n Args:\n path: A string path to a directory to load runs from.\n name: Optionally, what name to apply to the runs. If name is provided\n and the directory contains run subdirectories, the name of each subrun\n is the concatenation of the parent name and the subdirectory name. If\n name is provided and the directory contains event files, then a run\n is added called \"name\" and with the events from the path.\n\n Raises:\n ValueError: If the path exists and isn't a directory.\n\n Returns:\n The `EventMultiplexer`.\n \"\"\"\n if io_wrapper.Exists(path) and not io_wrapper.IsDirectory(path):\n raise ValueError('AddRunsFromDirectory: path exists and is not a '\n 'directory, %s' % path)\n # ListRecursively just yields nothing if the path doesn't exist.\n subdirs = [\n subdir\n for (subdir, files) in io_wrapper.ListRecursively(path)\n if list(filter(event_accumulator.IsTensorFlowEventsFile, files))\n ]\n\n for subdir in subdirs:\n logging.info('Adding events from directory %s', subdir)\n rpath = os.path.relpath(subdir, path)\n subname = os.path.join(name, rpath) if name else rpath\n self.AddRun(subdir, name=subname)\n\n return self\n\n def Reload(self):\n \"\"\"Call `Reload` on every `EventAccumulator`.\"\"\"\n self._reload_called = True\n with self._accumulators_mutex:\n loaders = list(self._accumulators.values())\n\n for l in loaders:\n l.Reload()\n return self\n\n def Scalars(self, run, tag):\n \"\"\"Retrieve the scalar events associated with a run and tag.\n\n Args:\n run: A string name of the run for which values are retrieved.\n tag: A string name of the tag for which values are retrieved.\n\n Raises:\n KeyError: If the run is not found, or the tag is not available for\n the given run.\n RuntimeError: If the run's `EventAccumulator` has not been activated.\n\n Returns:\n An array of `event_accumulator.ScalarEvents`.\n \"\"\"\n accumulator = self._GetAccumulator(run)\n return accumulator.Scalars(tag)\n\n def Graph(self, run):\n \"\"\"Retrieve the graph associated with the provided run.\n\n Args:\n run: A string name of a run to load the graph for.\n\n Raises:\n KeyError: If the run is not found.\n ValueError: If the run does not have an associated graph.\n RuntimeError: If the run's EventAccumulator has not been activated.\n\n Returns:\n The `graph_def` protobuf data structure.\n \"\"\"\n accumulator = self._GetAccumulator(run)\n return accumulator.Graph()\n\n def RunMetadata(self, run, tag):\n \"\"\"Get the session.run() metadata associated with a TensorFlow run and tag.\n\n Args:\n run: A string name of a TensorFlow run.\n tag: A string name of the tag associated with a particular session.run().\n\n Raises:\n KeyError: If the run is not found, or the tag is not available for the\n given run.\n RuntimeError: If the run's EventAccumulator has not been activated.\n\n Returns:\n The metadata in the form of `RunMetadata` protobuf data structure.\n \"\"\"\n accumulator = self._GetAccumulator(run)\n return accumulator.RunMetadata(tag)\n\n def Histograms(self, run, tag):\n \"\"\"Retrieve the histogram events associated with a run and tag.\n\n Args:\n run: A string name of the run for which values are retrieved.\n tag: A string name of the tag for which values are retrieved.\n\n Raises:\n KeyError: If the run is not found, or the tag is not available for\n the given run.\n RuntimeError: If the run's `EventAccumulator` has not been activated.\n\n Returns:\n An array of `event_accumulator.HistogramEvents`.\n \"\"\"\n accumulator = self._GetAccumulator(run)\n return accumulator.Histograms(tag)\n\n def CompressedHistograms(self, run, tag):\n \"\"\"Retrieve the compressed histogram events associated with a run and tag.\n\n Args:\n run: A string name of the run for which values are retrieved.\n tag: A string name of the tag for which values are retrieved.\n\n Raises:\n KeyError: If the run is not found, or the tag is not available for\n the given run.\n RuntimeError: If the run's EventAccumulator has not been activated.\n\n Returns:\n An array of `event_accumulator.CompressedHistogramEvents`.\n \"\"\"\n accumulator = self._GetAccumulator(run)\n return accumulator.CompressedHistograms(tag)\n\n def Images(self, run, tag):\n \"\"\"Retrieve the image events associated with a run and tag.\n\n Args:\n run: A string name of the run for which values are retrieved.\n tag: A string name of the tag for which values are retrieved.\n\n Raises:\n KeyError: If the run is not found, or the tag is not available for\n the given run.\n RuntimeError: If the run's `EventAccumulator` has not been activated.\n\n Returns:\n An array of `event_accumulator.ImageEvents`.\n \"\"\"\n accumulator = self._GetAccumulator(run)\n return accumulator.Images(tag)\n\n def Runs(self):\n \"\"\"Return all the run names in the `EventMultiplexer`.\n\n Returns:\n ```\n {runName: { images: [tag1, tag2, tag3],\n scalarValues: [tagA, tagB, tagC],\n histograms: [tagX, tagY, tagZ],\n compressedHistograms: [tagX, tagY, tagZ],\n graph: true}}\n ```\n \"\"\"\n with self._accumulators_mutex:\n # To avoid nested locks, we construct a copy of the run-accumulator map\n items = list(six.iteritems(self._accumulators))\n return {run_name: accumulator.Tags() for run_name, accumulator in items}\n\n def _GetAccumulator(self, run):\n with self._accumulators_mutex:\n return self._accumulators[run]\n",
"# Copyright 2015 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\n\"\"\"Functional tests for Concat Op.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom tensorflow.python.ops import gen_array_ops\n\n\nclass ConcatOpTest(tf.test.TestCase):\n\n def testHStack(self):\n with self.test_session():\n p1 = tf.placeholder(tf.float32, shape=[4, 4])\n p2 = tf.placeholder(tf.float32, shape=[4, 4])\n c = tf.concat(0, [p1, p2])\n params = {\n p1: np.random.rand(4, 4).astype(\"f\"),\n p2: np.random.rand(4, 4).astype(\"f\")\n }\n result = c.eval(feed_dict=params)\n\n self.assertEqual(result.shape, c.get_shape())\n self.assertAllEqual(result[:4, :], params[p1])\n self.assertAllEqual(result[4:, :], params[p2])\n\n def testVStack(self):\n with self.test_session():\n p1 = tf.placeholder(tf.float32, shape=[4, 4])\n p2 = tf.placeholder(tf.float32, shape=[4, 4])\n c = tf.concat(1, [p1, p2])\n params = {\n p1: np.random.rand(4, 4).astype(\"f\"),\n p2: np.random.rand(4, 4).astype(\"f\")\n }\n result = c.eval(feed_dict=params)\n\n self.assertEqual(result.shape, c.get_shape())\n self.assertAllEqual(result[:, :4], params[p1])\n self.assertAllEqual(result[:, 4:], params[p2])\n\n def testInt32GPU(self):\n with self.test_session(use_gpu=True):\n p1 = np.random.rand(2, 3).astype(\"i\")\n p2 = np.random.rand(2, 3).astype(\"i\")\n x1 = tf.constant(p1)\n x2 = tf.constant(p2)\n c = tf.concat(0, [x1, x2])\n result = c.eval()\n self.assertAllEqual(result[:2, :], p1)\n self.assertAllEqual(result[2:, :], p2)\n\n def testRefType(self):\n with self.test_session():\n p1 = np.random.rand(4, 4).astype(\"f\")\n p2 = np.random.rand(4, 4).astype(\"f\")\n v1 = tf.Variable(p1)\n v2 = tf.Variable(p2)\n c = tf.concat(0, [v1, v2])\n tf.initialize_all_variables().run()\n result = c.eval()\n\n self.assertEqual(result.shape, c.get_shape())\n self.assertAllEqual(result[:4, :], p1)\n self.assertAllEqual(result[4:, :], p2)\n\n def _testRandom(self, dtype, use_gpu=False):\n # Random dims of rank 5\n shape = np.random.randint(1, 5, size=5)\n # Random number of tensors, but always > 1.\n num_tensors = np.random.randint(2, 10)\n # Random dim to concat on\n concat_dim = np.random.randint(5)\n params = {}\n if dtype == tf.bfloat16:\n dtype_feed = tf.float32\n else:\n dtype_feed = dtype\n with self.test_session(use_gpu=use_gpu):\n p = []\n for i in np.arange(num_tensors):\n input_shape = shape\n input_shape[concat_dim] = np.random.randint(1, 5)\n placeholder = tf.placeholder(dtype_feed, shape=input_shape)\n p.append(placeholder)\n\n t = dtype_feed.as_numpy_dtype\n params[placeholder] = np.random.rand(*input_shape).astype(t)\n\n if dtype != dtype_feed:\n concat_inputs = [tf.cast(p_i, dtype) for p_i in p]\n else:\n concat_inputs = p\n c = tf.concat(concat_dim, concat_inputs)\n if dtype != dtype_feed:\n c = tf.cast(c, dtype_feed)\n result = c.eval(feed_dict=params)\n\n self.assertEqual(result.shape, c.get_shape())\n cur_offset = 0\n\n for i in np.arange(num_tensors):\n # The index into the result is the ':' along all dimensions\n # except the concat_dim. slice(0, size) is used for ':', and\n # a list of slices is used to index into result.\n ind = [slice(0, params[p[i]].shape[j]) for j in np.arange(5)]\n ind[concat_dim] = slice(cur_offset,\n cur_offset + params[p[i]].shape[concat_dim])\n cur_offset += params[p[i]].shape[concat_dim]\n if dtype == dtype_feed:\n self.assertAllEqual(result[ind], params[p[i]])\n else:\n self.assertAllClose(result[ind], params[p[i]], 0.01)\n\n def testRandom(self):\n self._testRandom(tf.float32)\n self._testRandom(tf.int16)\n self._testRandom(tf.int32, use_gpu=True)\n self._testRandom(tf.bfloat16)\n self._testRandom(tf.bfloat16, use_gpu=True)\n\n def testInvalidConcatDimTypeAndShape(self):\n a = tf.Variable(tf.constant(1.0, shape=[1]))\n b = tf.Variable(tf.constant(2.0, shape=[1]))\n with self.assertRaises(ValueError):\n tf.concat(a, b)\n with self.assertRaises(TypeError):\n tf.concat(4.2, 1)\n with self.assertRaises(ValueError):\n tf.concat(a, 1)\n with self.assertRaises(TypeError):\n tf.concat(a, [a, b])\n with self.assertRaises(ValueError):\n tf.concat([3], [a, b])\n with self.assertRaises(ValueError):\n tf.concat(0, [])\n # An integer tensor for shape dim should throw no error.\n tf.concat(tf.constant(0, shape=[]), 1)\n # A non-scalar tensor for shape should throw ValueError.\n with self.assertRaises(ValueError):\n tf.concat(tf.constant(0, shape=[1]), 1)\n\n def _testGradientsSimple(self, use_gpu):\n with self.test_session(use_gpu=use_gpu):\n inp = []\n inp_tensors = []\n for x in [1, 2, 6]:\n shape = [10, x, 2]\n t = np.random.rand(*shape).astype(\"f\")\n inp.append(t)\n inp_tensors.append(\n tf.constant([float(y) for y in t.flatten()],\n shape=shape, dtype=tf.float32))\n c = tf.concat(1, inp_tensors)\n output_shape = [10, 9, 2]\n grad_inp = np.random.rand(*output_shape).astype(\"f\")\n grad_tensor = tf.constant([float(x) for x in grad_inp.flatten()],\n shape=output_shape)\n grad = tf.gradients([c], inp_tensors, [grad_tensor])\n concated_grad = tf.concat(1, grad)\n result = concated_grad.eval()\n self.assertAllEqual(result, grad_inp)\n\n def testGradientsSimpleAll(self):\n self._testGradientsSimple(use_gpu=True)\n self._testGradientsSimple(use_gpu=False)\n\n def _testGradientsFirstDim(self, use_gpu):\n with self.test_session(use_gpu=use_gpu):\n inp = []\n inp_tensors = []\n for x in [1, 2, 6]:\n shape = [x, 10, 2]\n t = np.random.rand(*shape).astype(\"f\")\n inp.append(t)\n inp_tensors.append(\n tf.constant([float(y) for y in t.flatten()],\n shape=shape, dtype=tf.float32))\n c = tf.concat(0, inp_tensors)\n output_shape = [9, 10, 2]\n grad_inp = np.random.rand(*output_shape).astype(\"f\")\n grad_tensor = tf.constant([float(x) for x in grad_inp.flatten()],\n shape=output_shape)\n grad = tf.gradients([c], inp_tensors, [grad_tensor])\n concated_grad = tf.concat(0, grad)\n result = concated_grad.eval()\n\n self.assertAllEqual(result, grad_inp)\n\n def testGradientsFirstDimAll(self):\n self._testGradientsFirstDim(use_gpu=False)\n self._testGradientsFirstDim(use_gpu=True)\n\n def _testGradientsLastDim(self, use_gpu):\n with self.test_session(use_gpu=use_gpu):\n inp = []\n inp_tensors = []\n for x in [1, 2, 6]:\n shape = [10, 2, x]\n t = np.random.rand(*shape).astype(\"f\")\n inp.append(t)\n inp_tensors.append(\n tf.constant([float(y) for y in t.flatten()],\n shape=shape, dtype=tf.float32))\n c = tf.concat(2, inp_tensors)\n output_shape = [10, 2, 9]\n grad_inp = np.random.rand(*output_shape).astype(\"f\")\n grad_tensor = tf.constant([float(x) for x in grad_inp.flatten()],\n shape=output_shape)\n grad = tf.gradients([c], inp_tensors, [grad_tensor])\n concated_grad = tf.concat(2, grad)\n result = concated_grad.eval()\n\n self.assertAllEqual(result, grad_inp)\n\n def testGradientsLastDimAll(self):\n self._testGradientsLastDim(use_gpu=False)\n self._testGradientsLastDim(use_gpu=True)\n\n def _RunAndVerifyGradientsRandom(self, use_gpu):\n # Random dims of rank 5\n input_shape = np.random.randint(1, 5, size=5)\n # Random number of tensors\n num_tensors = np.random.randint(1, 10)\n # Random dim to concat on\n concat_dim = np.random.randint(5)\n concat_dim_sizes = np.random.randint(1, 5, size=num_tensors)\n with self.test_session(use_gpu=use_gpu):\n inp = []\n inp_tensors = []\n for x in concat_dim_sizes:\n shape = input_shape\n shape[concat_dim] = x\n t = np.random.rand(*shape).astype(\"f\")\n inp.append(t)\n inp_tensors.append(\n tf.constant([float(y) for y in t.flatten()],\n shape=shape, dtype=tf.float32))\n c = tf.concat(concat_dim, inp_tensors)\n output_shape = input_shape\n output_shape[concat_dim] = concat_dim_sizes.sum()\n grad_inp = np.random.rand(*output_shape).astype(\"f\")\n grad_tensor = tf.constant([float(x) for x in grad_inp.flatten()],\n shape=output_shape)\n grad = tf.gradients([c], inp_tensors, [grad_tensor])\n concated_grad = tf.concat(concat_dim, grad)\n result = concated_grad.eval()\n\n self.assertAllEqual(result, grad_inp)\n\n def testGradientsRandom(self):\n for _ in range(5):\n self._RunAndVerifyGradientsRandom(use_gpu=False)\n self._RunAndVerifyGradientsRandom(use_gpu=True)\n\n def testShapeError(self):\n # Rank doesn't match.\n with self.assertRaises(ValueError):\n tf.concat(1, [tf.constant(10.0, shape=[4, 4, 4, 4]),\n tf.constant(20.0, shape=[4, 4, 4])])\n\n # Dimensions don't match in a non-concat dim.\n with self.assertRaises(ValueError):\n tf.concat(1, [tf.constant(10.0, shape=[1, 2, 1]),\n tf.constant(20.0, shape=[3, 2, 1])])\n\n # concat_dim out of range.\n with self.assertRaises(ValueError):\n tf.concat(3, [tf.constant(10.0, shape=[4, 4, 4]),\n tf.constant(20.0, shape=[4, 4, 4])])\n\n def testShapeWithUnknownConcatDim(self):\n p1 = tf.placeholder(tf.float32)\n c1 = tf.constant(10.0, shape=[4, 4, 4, 4])\n p2 = tf.placeholder(tf.float32)\n c2 = tf.constant(20.0, shape=[4, 4, 4, 4])\n dim = tf.placeholder(tf.int32)\n concat = tf.concat(dim, [p1, c1, p2, c2])\n self.assertEqual(4, concat.get_shape().ndims)\n\n # All dimensions unknown.\n concat2 = tf.concat(dim, [p1, p2])\n self.assertEqual(None, concat2.get_shape())\n\n # Rank doesn't match.\n c3 = tf.constant(30.0, shape=[4, 4, 4])\n with self.assertRaises(ValueError):\n tf.concat(dim, [p1, c1, p2, c3])\n\n def testZeroSize(self):\n # Verify that concat doesn't crash and burn for zero size inputs\n np.random.seed(7)\n for use_gpu in False, True:\n with self.test_session(use_gpu=use_gpu) as sess:\n for shape0 in (), (2,):\n axis = len(shape0)\n for shape1 in (), (3,):\n for n0 in 0, 1, 2:\n for n1 in 0, 1, 2:\n x0 = np.random.randn(*(shape0 + (n0,) + shape1))\n x1 = np.random.randn(*(shape0 + (n1,) + shape1))\n correct = np.concatenate([x0, x1], axis=axis)\n # TODO(irving): Make tf.concat handle map, then drop list().\n xs = list(map(tf.constant, [x0, x1]))\n c = tf.concat(axis, xs)\n self.assertAllEqual(c.eval(), correct)\n # Check gradients\n dc = np.random.randn(*c.get_shape().as_list())\n dxs = sess.run(tf.gradients(c, xs, dc))\n self.assertAllEqual(dc, np.concatenate(dxs, axis=axis))\n\n def testTensorConcatDim0Grad(self):\n x_shapes = [[20, 7, 3], [10, 7, 3], [14, 7, 3]]\n output_shape = [44, 7, 3]\n x_vals = [np.random.random_sample(x_shape).astype(\n np.float64) for x_shape in x_shapes]\n with self.test_session():\n xs = [tf.constant(x_val) for x_val in x_vals]\n output = tf.concat(0, xs)\n err = tf.test.compute_gradient_error(xs, x_shapes, output, output_shape)\n self.assertLess(err, 1e-11)\n\n def testTensorConcatDim1Grad(self):\n x_shapes = [[20, 7, 3], [20, 3, 3], [20, 1, 3]]\n output_shape = [20, 11, 3]\n x_vals = [np.random.random_sample(x_shape).astype(\n np.float64) for x_shape in x_shapes]\n with self.test_session():\n xs = [tf.constant(x_val) for x_val in x_vals]\n output = tf.concat(1, xs)\n err = tf.test.compute_gradient_error(xs, x_shapes, output, output_shape)\n self.assertLess(err, 1e-11)\n\n def testIndexedSlicesConcatDim0Grad(self):\n x_shapes = [[20, 7, 3], [10, 7, 3], [14, 7, 3]]\n output_shape = [4, 7, 3]\n x_vals = [np.random.random_sample(x_shape).astype(\n np.float64) for x_shape in x_shapes]\n with self.test_session():\n xs = [tf.constant(x_val) for x_val in x_vals]\n x_concat = tf.concat(0, xs)\n output = tf.gather(x_concat, [1, 2, 0, 5])\n err = tf.test.compute_gradient_error(xs, x_shapes, output, output_shape)\n self.assertLess(err, 1e-11)\n\n def testIndexedSlicesConcatDim1Grad(self):\n x_shapes = [[20, 7, 3], [20, 3, 3], [20, 1, 3]]\n output_shape = [4, 11, 3]\n x_vals = [np.random.random_sample(x_shape).astype(\n np.float64) for x_shape in x_shapes]\n with self.test_session():\n xs = [tf.constant(x_val) for x_val in x_vals]\n x_concat = tf.concat(1, xs)\n output = tf.gather(x_concat, [1, 2, 0, 5])\n err = tf.test.compute_gradient_error(xs, x_shapes, output, output_shape)\n self.assertLess(err, 1e-11)\n\n def testIndexedSlicesConcatDim2Grad(self):\n x_shapes = [[20, 7, 3], [20, 7, 1], [20, 7, 2]]\n output_shape = [4, 7, 6]\n x_vals = [np.random.random_sample(x_shape).astype(\n np.float64) for x_shape in x_shapes]\n with self.test_session():\n xs = [tf.constant(x_val) for x_val in x_vals]\n x_concat = tf.concat(2, xs)\n output = tf.gather(x_concat, [1, 2, 0, 5])\n err = tf.test.compute_gradient_error(xs, x_shapes, output, output_shape)\n self.assertLess(err, 1e-11)\n\n def testConcatTuple(self):\n c1 = np.random.rand(4, 4)\n c2 = np.random.rand(4, 4)\n with self.test_session():\n concat_list_t = tf.concat(0, [c1, c2])\n concat_tuple_t = tf.concat(0, (c1, c2))\n self.assertAllEqual(concat_list_t.eval(), concat_tuple_t.eval())\n\n def testConcatNoScalars(self):\n with self.test_session():\n scalar = tf.constant(7)\n dim = tf.placeholder(tf.int32)\n with self.assertRaisesRegexp(\n ValueError, r\"Can't concatenate scalars \\(use tf\\.pack instead\\)\"):\n tf.concat(dim, [scalar, scalar, scalar])\n\n def testConcatGradNumNodes(self):\n g = tf.Graph()\n n = 10\n with g.as_default():\n x = tf.constant([1, 1])\n y = tf.concat(0, [x] * n)\n before = len(g.get_operations())\n _ = tf.gradients([y], [x], [y])\n after = len(g.get_operations())\n self.assertEqual(n + 3, after - before)\n print(\"graph = \", [x.name for x in g.get_operations()])\n\n\nclass ConcatOffsetTest(tf.test.TestCase):\n\n def testBasic(self):\n for use_gpu in [False, True]:\n with self.test_session(use_gpu=use_gpu) as sess:\n cdim = tf.constant(1, tf.int32)\n s0 = tf.constant([2, 3, 5], tf.int32)\n s1 = tf.constant([2, 7, 5], tf.int32)\n s2 = tf.constant([2, 20, 5], tf.int32)\n off = gen_array_ops._concat_offset(cdim, [s0, s1, s2])\n ans = sess.run(off)\n self.assertAllEqual(ans, [[0, 0, 0], [0, 3, 0], [0, 10, 0]])\n\n def testNotVector(self):\n with self.test_session() as sess:\n cdim = tf.constant(1, tf.int32)\n s0 = tf.constant([[2, 3, 5]], tf.int32)\n s1 = tf.constant([[2, 7, 5]], tf.int32)\n off = gen_array_ops._concat_offset(cdim, [s0, s1])\n with self.assertRaisesRegexp(tf.errors.InvalidArgumentError,\n r\"should be a vector\"):\n sess.run(off)\n\n def testConcatDimOutOfRange(self):\n with self.test_session() as sess:\n cdim = tf.constant(4, tf.int32)\n s0 = tf.constant([2, 3, 5], tf.int32)\n s1 = tf.constant([2, 7, 5], tf.int32)\n off = gen_array_ops._concat_offset(cdim, [s0, s1])\n with self.assertRaisesRegexp(tf.errors.InvalidArgumentError,\n r\"Concat dim is out of range: 4 vs. 3\"):\n sess.run(off)\n\n def testDimMismatch(self):\n with self.test_session() as sess:\n cdim = tf.constant(1, tf.int32)\n s0 = tf.constant([2, 3, 5], tf.int32)\n s1 = tf.constant([2, 7, 5, 10], tf.int32)\n off = gen_array_ops._concat_offset(cdim, [s0, s1])\n with self.assertRaisesRegexp(tf.errors.InvalidArgumentError,\n r\"should contain 3 elem\"):\n sess.run(off)\n\n def testSizeMismatch(self):\n with self.test_session() as sess:\n cdim = tf.constant(1, tf.int32)\n s0 = tf.constant([2, 3, 5], tf.int32)\n s1 = tf.constant([2, 7, 10], tf.int32)\n off = gen_array_ops._concat_offset(cdim, [s0, s1])\n with self.assertRaisesRegexp(tf.errors.InvalidArgumentError,\n r\"mismatch: 5 vs. 10\"):\n sess.run(off)\n\nif __name__ == \"__main__\":\n tf.test.main()\n",
"# Copyright 2015 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\"\"\"Integration tests for TensorBoard.\n\nThese tests start up a full-fledged TensorBoard server.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport base64\nimport gzip\nimport json\nimport os\nimport shutil\nimport threading\nimport zlib\n\nfrom six import BytesIO\nfrom six.moves import http_client\nfrom six.moves import xrange # pylint: disable=redefined-builtin\nimport tensorflow as tf\n\nfrom google.protobuf import text_format\nfrom tensorflow.python.summary import event_multiplexer\nfrom tensorflow.tensorboard.backend import server\n\n\nclass TensorboardServerTest(tf.test.TestCase):\n\n # Number of scalar-containing events to make.\n _SCALAR_COUNT = 99\n\n def setUp(self):\n self._GenerateTestData()\n self._multiplexer = event_multiplexer.EventMultiplexer(\n size_guidance=server.TENSORBOARD_SIZE_GUIDANCE)\n server.ReloadMultiplexer(self._multiplexer, {self.get_temp_dir(): None})\n # 0 to pick an unused port.\n self._server = server.BuildServer(self._multiplexer, 'localhost', 0)\n self._server_thread = threading.Thread(target=self._server.serve_forever)\n self._server_thread.daemon = True\n self._server_thread.start()\n self._connection = http_client.HTTPConnection(\n 'localhost', self._server.server_address[1])\n\n def tearDown(self):\n self._connection.close()\n self._server.shutdown()\n self._server.server_close()\n\n def _get(self, path):\n \"\"\"Perform a GET request for the given path.\"\"\"\n self._connection.request('GET', path)\n return self._connection.getresponse()\n\n def _getJson(self, path):\n \"\"\"Perform a GET request and decode the result as JSON.\"\"\"\n self._connection.request('GET', path)\n response = self._connection.getresponse()\n self.assertEqual(response.status, 200)\n return json.loads(response.read().decode('utf-8'))\n\n def _decodeResponse(self, response):\n \"\"\"Decompresses (if necessary) the response from the server.\"\"\"\n encoding = response.getheader('Content-Encoding')\n content = response.read()\n if encoding in ('gzip', 'x-gzip', 'deflate'):\n if encoding == 'deflate':\n data = BytesIO(zlib.decompress(content))\n else:\n data = gzip.GzipFile('', 'rb', 9, BytesIO(content))\n content = data.read()\n return content\n\n def testBasicStartup(self):\n \"\"\"Start the server up and then shut it down immediately.\"\"\"\n pass\n\n def testRequestMainPage(self):\n \"\"\"Navigate to the main page and verify that it returns a 200.\"\"\"\n response = self._get('/')\n self.assertEqual(response.status, 200)\n\n def testRequestNonexistentPage(self):\n \"\"\"Request a page that doesn't exist; it should 404.\"\"\"\n response = self._get('/asdf')\n self.assertEqual(response.status, 404)\n\n def testDirectoryTraversal(self):\n \"\"\"Attempt a directory traversal attack.\"\"\"\n response = self._get('/..' * 30 + '/etc/passwd')\n self.assertEqual(response.status, 404)\n\n def testRuns(self):\n \"\"\"Test the format of the /data/runs endpoint.\"\"\"\n self.assertEqual(\n self._getJson('/data/runs'),\n {'run1': {'compressedHistograms': ['histogram'],\n 'scalars': ['simple_values'],\n 'histograms': ['histogram'],\n 'images': ['image'],\n 'graph': True,\n 'run_metadata': ['test run']}})\n\n def testHistograms(self):\n \"\"\"Test the format of /data/histograms.\"\"\"\n self.assertEqual(\n self._getJson('/data/histograms?tag=histogram&run=run1'),\n [[0, 0, [0, 2.0, 3.0, 6.0, 5.0, [0.0, 1.0, 2.0], [1.0, 1.0, 1.0]]]])\n\n def testSampleScalars(self):\n \"\"\"Test the sample_count parameter of /data/scalars.\"\"\"\n for i in xrange(10, self._SCALAR_COUNT, 10):\n samples = self._getJson('/data/scalars?sample_count=%d' % i)\n values = samples['run1']['simple_values']\n # Verify that we got the right amount of values and that we got the\n # endpoints.\n self.assertEqual(len(values), i)\n self.assertEqual(values[0], [100, 10, 1])\n self.assertEqual(values[-1], [9900, 990, 99])\n\n def testSampleScalarsWithLargeSampleCount(self):\n \"\"\"Test using a large sample_count.\"\"\"\n samples = self._getJson('/data/scalars?sample_count=999999')\n values = samples['run1']['simple_values']\n self.assertEqual(len(values), self._SCALAR_COUNT)\n\n def testImages(self):\n \"\"\"Test listing images and retrieving an individual image.\"\"\"\n image_json = self._getJson('/data/images?tag=image&run=run1')\n image_query = image_json[0]['query']\n # We don't care about the format of the image query.\n del image_json[0]['query']\n self.assertEqual(image_json, [{\n 'wall_time': 0,\n 'step': 0,\n 'height': 1,\n 'width': 1\n }])\n response = self._get('/data/individualImage?%s' % image_query)\n self.assertEqual(response.status, 200)\n\n def testGraph(self):\n \"\"\"Test retrieving the graph definition.\"\"\"\n response = self._get('/data/graph?run=run1&limit_attr_size=1024'\n '&large_attrs_key=_very_large_attrs')\n self.assertEqual(response.status, 200)\n # Decompress (unzip) the response, since graphs come gzipped.\n graph_pbtxt = self._decodeResponse(response)\n # Parse the graph from pbtxt into a graph message.\n graph = tf.GraphDef()\n graph = text_format.Parse(graph_pbtxt, graph)\n self.assertEqual(len(graph.node), 2)\n self.assertEqual(graph.node[0].name, 'a')\n self.assertEqual(graph.node[1].name, 'b')\n # Make sure the second node has an attribute that was filtered out because\n # it was too large and was added to the \"too large\" attributes list.\n self.assertEqual(list(graph.node[1].attr.keys()), ['_very_large_attrs'])\n self.assertEqual(graph.node[1].attr['_very_large_attrs'].list.s,\n [b'very_large_attr'])\n\n def testRunMetadata(self):\n \"\"\"Test retrieving the run metadata information.\"\"\"\n response = self._get('/data/run_metadata?run=run1&tag=test%20run')\n self.assertEqual(response.status, 200)\n # Decompress (unzip) the response, since run outputs come gzipped.\n run_metadata_pbtxt = self._decodeResponse(response)\n # Parse from pbtxt into a message.\n run_metadata = tf.RunMetadata()\n text_format.Parse(run_metadata_pbtxt, run_metadata)\n self.assertEqual(len(run_metadata.step_stats.dev_stats), 1)\n self.assertEqual(run_metadata.step_stats.dev_stats[0].device, 'test device')\n\n def _GenerateTestData(self):\n \"\"\"Generates the test data directory.\n\n The test data has a single run named run1 which contains:\n - a histogram\n - an image at timestamp and step 0\n - scalar events containing the value i at step 10 * i and wall time\n 100 * i, for i in [1, _SCALAR_COUNT).\n - a graph definition\n \"\"\"\n temp_dir = self.get_temp_dir()\n self.addCleanup(shutil.rmtree, temp_dir)\n run1_path = os.path.join(temp_dir, 'run1')\n os.makedirs(run1_path)\n writer = tf.train.SummaryWriter(run1_path)\n\n histogram_value = tf.HistogramProto(min=0,\n max=2,\n num=3,\n sum=6,\n sum_squares=5,\n bucket_limit=[0, 1, 2],\n bucket=[1, 1, 1])\n # Add a simple graph event.\n graph_def = tf.GraphDef()\n node1 = graph_def.node.add()\n node1.name = 'a'\n node2 = graph_def.node.add()\n node2.name = 'b'\n node2.attr['very_large_attr'].s = b'a' * 2048 # 2 KB attribute\n writer.add_graph(graph_def)\n\n # Add a simple run metadata event.\n run_metadata = tf.RunMetadata()\n device_stats = run_metadata.step_stats.dev_stats.add()\n device_stats.device = 'test device'\n writer.add_run_metadata(run_metadata, 'test run')\n\n # 1x1 transparent GIF.\n encoded_image = base64.b64decode(\n 'R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7')\n image_value = tf.Summary.Image(height=1,\n width=1,\n colorspace=1,\n encoded_image_string=encoded_image)\n writer.add_event(tf.Event(wall_time=0,\n step=0,\n summary=tf.Summary(value=[tf.Summary.Value(\n tag='histogram',\n histo=histogram_value), tf.Summary.Value(\n tag='image',\n image=image_value)])))\n\n # Write 100 simple values.\n for i in xrange(1, self._SCALAR_COUNT + 1):\n writer.add_event(tf.Event(\n # We use different values for wall time, step, and the value so we can\n # tell them apart.\n wall_time=100 * i,\n step=10 * i,\n summary=tf.Summary(value=[tf.Summary.Value(tag='simple_values',\n simple_value=i)])))\n writer.flush()\n writer.close()\n\n\nclass ParseEventFilesSpecTest(tf.test.TestCase):\n\n def testRespectsGCSPath(self):\n logdir_string = 'gs://foo/path'\n expected = {'gs://foo/path': None}\n self.assertEqual(server.ParseEventFilesSpec(logdir_string), expected)\n\n\nif __name__ == '__main__':\n tf.test.main()\n"
] | [
[
"tensorflow.python.util.compat.as_text",
"tensorflow.python.framework.ops.colocate_with",
"tensorflow.python.util.compat.as_bytes",
"tensorflow.python.framework.dtypes.as_dtype",
"tensorflow.python.framework.ops.name_scope",
"tensorflow.python.framework.ops.convert_n_to_tensor",
"tensorflow.python.framework.ops.convert_to_tensor",
"tensorflow.core.framework.attr_value_pb2.AttrValue",
"tensorflow.python.framework.tensor_shape.as_shape"
],
[
"tensorflow.python.platform.logging.info",
"tensorflow.python.platform.logging.warning",
"tensorflow.python.summary.impl.io_wrapper.IsDirectory",
"tensorflow.python.summary.impl.io_wrapper.Exists",
"tensorflow.python.summary.impl.io_wrapper.ListRecursively",
"tensorflow.python.summary.event_accumulator.EventAccumulator"
],
[
"tensorflow.test.compute_gradient_error",
"tensorflow.concat",
"tensorflow.cast",
"numpy.random.random_sample",
"numpy.concatenate",
"numpy.random.randn",
"numpy.random.randint",
"tensorflow.Graph",
"tensorflow.Variable",
"numpy.arange",
"tensorflow.gradients",
"tensorflow.test.main",
"tensorflow.gather",
"tensorflow.initialize_all_variables",
"tensorflow.placeholder",
"numpy.random.rand",
"tensorflow.python.ops.gen_array_ops._concat_offset",
"tensorflow.constant",
"numpy.random.seed"
],
[
"tensorflow.tensorboard.backend.server.BuildServer",
"tensorflow.Summary.Image",
"tensorflow.RunMetadata",
"tensorflow.tensorboard.backend.server.ParseEventFilesSpec",
"tensorflow.test.main",
"tensorflow.train.SummaryWriter",
"tensorflow.Summary.Value",
"tensorflow.HistogramProto",
"tensorflow.GraphDef",
"tensorflow.python.summary.event_multiplexer.EventMultiplexer"
]
] | [
{
"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": [
"0.12",
"1.0"
]
},
{
"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"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"0.12",
"1.0"
]
}
] |
Del9fina/robel | [
"63dfac65932757134e5766f1e20a339efe281bc7",
"63dfac65932757134e5766f1e20a339efe281bc7"
] | [
"robel/components/tracking/group_config.py",
"robel/dclaw/turn.py"
] | [
"# Copyright 2019 The ROBEL 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\n\"\"\"Configuration for a tracker component group.\"\"\"\n\nfrom typing import Iterable, Optional\n\nimport numpy as np\nfrom transforms3d.euler import euler2mat, quat2euler\nfrom transforms3d.quaternions import quat2mat\n\nfrom robel.simulation.sim_scene import SimScene\n\n\nclass TrackerGroupConfig:\n \"\"\"Group configuration for a TrackerComponent.\"\"\"\n\n def __init__(self,\n sim_scene: SimScene,\n element_name: Optional[str] = None,\n element_type: Optional[str] = None,\n qpos_indices: Optional[Iterable[int]] = None,\n qvel_indices: Optional[Iterable[int]] = None,\n sim_observation_noise: Optional[float] = None):\n \"\"\"Initializes a group configuration for a TrackerComponent.\n\n Args:\n sim_scene: The simulation, used for validation purposes.\n element_name: The name of the element to use for tracking in\n simulation.\n element_type: The type of the element as defined in the XML.\n Should be one of `site`, `body`, `geom`, or `joint`. If this is\n `joint`, `qpos_indices` and `qvel_indices` should be\n provided.\n qpos_indices: The indices into `MjData.qpos` to read for the\n joint element position and rotation.\n qvel_indices: The indices into `MjData.qvel` to read for the joint\n element velocity. This defaults to `qpos_indices`.\n sim_observation_noise: The range of the observation noise (in\n meters) to apply to the state in simulation.\n \"\"\"\n self.element_type = element_type\n if self.element_type not in ['site', 'body', 'geom', 'joint']:\n raise ValueError('Unknown element type %s' % self.element_type)\n\n self.element_name = element_name\n self.element_id = None\n self.element_attr = None\n self.qpos_indices = None\n self.qvel_indices = None\n self._is_euler = False\n\n if self.element_type == 'joint':\n if qpos_indices is None:\n raise ValueError('Must provided qpos_indices for joints.')\n # Ensure that the qpos indices are valid.\n nq = sim_scene.model.nq\n assert all(-nq <= i < nq for i in qpos_indices), \\\n 'All qpos indices must be in [-{}, {}]'.format(nq, nq - 1)\n self.qpos_indices = np.array(qpos_indices, dtype=int)\n\n if len(self.qpos_indices) == 6:\n self._is_euler = True\n elif len(self.qpos_indices) != 7:\n raise ValueError('qpos_indices must be 6 or 7 elements.')\n\n if qvel_indices is None:\n if not self._is_euler:\n raise ValueError(\n 'qvel_indices must be provided for free joints.')\n qvel_indices = qpos_indices\n\n # Ensure that the qvel indices are valid.\n nv = sim_scene.model.nv\n assert all(-nv <= i < nv for i in qvel_indices), \\\n 'All qvel indices must be in [-{}, {}]'.format(nv, nv - 1)\n self.qvel_indices = np.array(qvel_indices, dtype=int)\n else:\n self.element_attr = (lambda obj, attr_name: getattr(\n obj, self.element_type + '_' + attr_name))\n self.element_id = self.element_attr(sim_scene.model, 'name2id')(\n element_name)\n\n self.sim_observation_noise = sim_observation_noise\n\n def get_pos(self, sim_scene: SimScene) -> np.ndarray:\n \"\"\"Returns the cartesian position of the element.\"\"\"\n if self.qpos_indices is not None:\n return sim_scene.data.qpos[self.qpos_indices[:3]]\n return self.element_attr(sim_scene.data, 'xpos')[self.element_id, :]\n\n def get_rot(self, sim_scene: SimScene) -> np.ndarray:\n \"\"\"Returns the (3x3) rotation matrix of the element.\"\"\"\n if self.qpos_indices is not None:\n qpos = sim_scene.data.qpos[self.qpos_indices[3:]]\n if self._is_euler:\n return euler2mat(*qpos, axes='rxyz')\n return quat2mat(qpos)\n return self.element_attr(sim_scene.data,\n 'xmat')[self.element_id].reshape((3, 3))\n\n def get_vel(self, sim_scene: SimScene) -> np.ndarray:\n \"\"\"Returns the cartesian velocity of the element.\"\"\"\n if self.qvel_indices is not None:\n return sim_scene.data.qvel[self.qvel_indices[:3]]\n raise NotImplementedError('Cartesian velocity is not supported for ' +\n self.element_type)\n\n def get_angular_vel(self, sim_scene: SimScene) -> np.ndarray:\n \"\"\"Returns the angular velocity (x, y, z) of the element.\"\"\"\n if self.qvel_indices is not None:\n return sim_scene.data.qvel[self.qvel_indices[3:]]\n raise NotImplementedError('Angular velocity is not supported for ' +\n self.element_type)\n\n def set_pos(self, sim_scene: SimScene, pos: np.ndarray):\n \"\"\"Sets the cartesian position of the element.\"\"\"\n if self.qpos_indices is not None:\n sim_scene.data.qpos[self.qpos_indices[:len(pos)]] = pos\n return\n self.element_attr(sim_scene.model,\n 'pos')[self.element_id, :len(pos)] = pos\n\n def set_rot_quat(self, sim_scene: SimScene, quat: np.ndarray):\n \"\"\"Sets the cartesian position of the element.\"\"\"\n if self.qpos_indices is not None:\n qpos = quat\n if self._is_euler:\n qpos = quat2euler(quat, axes='rxyz')\n sim_scene.data.qpos[self.qpos_indices[3:]] = qpos\n return\n self.element_attr(sim_scene.model, 'quat')[self.element_id, :] = quat\n",
"# Copyright 2019 The ROBEL 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\n\"\"\"Turn tasks with DClaw robots.\n\nThis is a single rotation of an object from an initial angle to a target angle.\n\"\"\"\n\nimport abc\nimport collections\nfrom typing import Dict, Optional, Sequence\n\nimport numpy as np\nfrom transforms3d.euler import euler2quat\n\nfrom robel.components.robot.dynamixel_robot import DynamixelRobotState\nfrom robel.dclaw.base_env import BaseDClawObjectEnv\nfrom robel.simulation.randomize import SimRandomizer\nfrom robel.utils.configurable import configurable\nfrom robel.utils.resources import get_asset_path\n\n# The observation keys that are concatenated as the environment observation.\nDEFAULT_OBSERVATION_KEYS = (\n 'claw_qpos',\n 'object_x',\n 'object_y',\n 'last_action',\n 'target_error',\n)\n\n# Reset pose for the claw joints.\nRESET_POSE = [0, -np.pi / 3, np.pi / 3] * 3\n\nDCLAW3_ASSET_PATH = 'robel/dclaw/assets/dclaw3xh_valve3_v0.xml'\n\n\nclass BaseDClawTurn(BaseDClawObjectEnv, metaclass=abc.ABCMeta):\n \"\"\"Shared logic for DClaw turn tasks.\"\"\"\n\n def __init__(self,\n asset_path: str = DCLAW3_ASSET_PATH,\n observation_keys: Sequence[str] = DEFAULT_OBSERVATION_KEYS,\n frame_skip: int = 40,\n interactive: bool = False,\n success_threshold: float = 0.1,\n **kwargs):\n \"\"\"Initializes the environment.\n\n Args:\n asset_path: The XML model file to load.\n observation_keys: The keys in `get_obs_dict` to concatenate as the\n observations returned by `step` and `reset`.\n frame_skip: The number of simulation steps per environment step.\n interactive: If True, allows the hardware guide motor to freely\n rotate and its current angle is used as the goal.\n success_threshold: The difference threshold (in radians) of the\n object position and the goal position within which we consider\n as a sucesss.\n \"\"\"\n super().__init__(\n sim_model=get_asset_path(asset_path),\n observation_keys=observation_keys,\n frame_skip=frame_skip,\n **kwargs)\n\n self._interactive = interactive\n self._success_threshold = success_threshold\n self._desired_claw_pos = RESET_POSE\n\n self._target_bid = self.model.body_name2id('target')\n\n # The following are modified (possibly every reset) by subclasses.\n self._initial_object_pos = 0\n self._initial_object_vel = 0\n self._set_target_object_pos(0)\n\n def _reset(self):\n \"\"\"Resets the environment.\"\"\"\n self._reset_dclaw_and_object(\n claw_pos=RESET_POSE,\n object_pos=self._initial_object_pos,\n object_vel=self._initial_object_vel,\n guide_pos=self._target_object_pos)\n\n # Disengage the motor.\n if self._interactive and self.robot.is_hardware:\n self.robot.set_motors_engaged('guide', False)\n\n def _step(self, action: np.ndarray):\n \"\"\"Applies an action to the robot.\"\"\"\n self.robot.step({\n 'dclaw': action,\n 'guide': np.atleast_1d(self._target_object_pos),\n })\n\n def get_obs_dict(self) -> Dict[str, np.ndarray]:\n \"\"\"Returns the current observation of the environment.\n\n Returns:\n A dictionary of observation values. This should be an ordered\n dictionary if `observation_keys` isn't set.\n \"\"\"\n claw_state, object_state, guide_state = self.robot.get_state(\n ['dclaw', 'object', 'guide'])\n\n # If in interactive mode, use the guide motor position as the goal.\n if self._interactive:\n self._set_target_object_pos(guide_state.qpos)\n\n # Calculate the signed angle difference to the target in [-pi, pi].\n target_error = self._target_object_pos - object_state.qpos\n target_error = np.mod(target_error + np.pi, 2 * np.pi) - np.pi\n\n obs_dict = collections.OrderedDict((\n ('claw_qpos', claw_state.qpos),\n ('claw_qvel', claw_state.qvel),\n ('object_x', np.cos(object_state.qpos)),\n ('object_y', np.sin(object_state.qpos)),\n ('object_qvel', object_state.qvel),\n ('last_action', self._get_last_action()),\n ('target_error', target_error),\n ))\n # Add hardware-specific state if present.\n if isinstance(claw_state, DynamixelRobotState):\n obs_dict['claw_current'] = claw_state.current\n\n return obs_dict\n\n def get_reward_dict(\n self,\n action: np.ndarray,\n obs_dict: Dict[str, np.ndarray],\n ) -> Dict[str, np.ndarray]:\n \"\"\"Returns the reward for the given action and observation.\"\"\"\n target_dist = np.abs(obs_dict['target_error'])\n claw_vel = obs_dict['claw_qvel']\n\n reward_dict = collections.OrderedDict((\n # Penalty for distance away from goal.\n ('target_dist_cost', -5 * target_dist),\n # Penalty for difference with nomimal pose.\n ('pose_diff_cost',\n -1 * np.linalg.norm(obs_dict['claw_qpos'] - self._desired_claw_pos)\n ),\n # Penality for high velocities.\n ('joint_vel_cost',\n -1 * np.linalg.norm(claw_vel[np.abs(claw_vel) >= 0.5])),\n\n # Reward for close proximity with goal.\n ('bonus_small', 10 * (target_dist < 0.25)),\n ('bonus_big', 50 * (target_dist < 0.10)),\n ))\n return reward_dict\n\n def get_score_dict(\n self,\n obs_dict: Dict[str, np.ndarray],\n reward_dict: Dict[str, np.ndarray],\n ) -> Dict[str, np.ndarray]:\n \"\"\"Returns a standardized measure of success for the environment.\"\"\"\n target_dist = np.abs(obs_dict['target_error'])\n score_dict = collections.OrderedDict((\n ('points', 1.0 - target_dist / np.pi),\n ('success', target_dist < self._success_threshold),\n ))\n score_dict.update(\n self._get_safety_scores(\n pos=obs_dict['claw_qpos'],\n vel=obs_dict['claw_qvel'],\n current=obs_dict.get('claw_current'),\n ))\n return score_dict\n\n def _set_target_object_pos(self, target_pos: float,\n unbounded: bool = False):\n \"\"\"Sets the goal angle to the given position.\"\"\"\n # Modulo to [-pi, pi].\n if not unbounded:\n target_pos = np.mod(target_pos + np.pi, 2 * np.pi) - np.pi\n self._target_object_pos = np.asarray(target_pos, dtype=np.float32)\n\n # Mark the target position in sim.\n # WARNING: euler2quat will mutate a passed numpy array.\n self.model.body_quat[self._target_bid] = euler2quat(\n 0, 0, float(target_pos))\n\n\n@configurable(pickleable=True)\nclass DClawTurnFixed(BaseDClawTurn):\n \"\"\"Turns the object with a fixed initial and fixed target position.\"\"\"\n\n def _reset(self):\n # Turn from 0 degrees to 180 degrees.\n self._initial_object_pos = 0\n self._set_target_object_pos(np.pi)\n super()._reset()\n\n\n@configurable(pickleable=True)\nclass DClawTurnRandom(BaseDClawTurn):\n \"\"\"Turns the object with a random initial and random target position.\"\"\"\n\n def _reset(self):\n # Initial position is +/- 60 degrees.\n self._initial_object_pos = self.np_random.uniform(\n low=-np.pi / 3, high=np.pi / 3)\n # Target position is 180 +/- 60 degrees.\n self._set_target_object_pos(\n np.pi + self.np_random.uniform(low=-np.pi / 3, high=np.pi / 3))\n super()._reset()\n\n\n@configurable(pickleable=True)\nclass DClawTurnRandomDynamics(DClawTurnRandom):\n \"\"\"Turns the object with a random initial and random target position.\n\n The dynamics of the simulation are randomized each episode.\n \"\"\"\n\n def __init__(self,\n *args,\n sim_observation_noise: Optional[float] = 0.05,\n **kwargs):\n super().__init__(\n *args, sim_observation_noise=sim_observation_noise, **kwargs)\n self._randomizer = SimRandomizer(self)\n self._dof_indices = (\n self.robot.get_config('dclaw').qvel_indices.tolist() +\n self.robot.get_config('object').qvel_indices.tolist())\n\n def _reset(self):\n # Randomize joint dynamics.\n self._randomizer.randomize_dofs(\n self._dof_indices,\n damping_range=(0.005, 0.1),\n friction_loss_range=(0.001, 0.005),\n )\n self._randomizer.randomize_actuators(\n all_same=True,\n kp_range=(1, 3),\n )\n # Randomize friction on all geoms in the scene.\n self._randomizer.randomize_geoms(\n all_same=True,\n friction_slide_range=(0.8, 1.2),\n friction_spin_range=(0.003, 0.007),\n friction_roll_range=(0.00005, 0.00015),\n )\n self._randomizer.randomize_bodies(\n ['mount'],\n position_perturb_range=(-0.01, 0.01),\n )\n self._randomizer.randomize_geoms(\n ['mount'],\n color_range=(0.2, 0.9),\n )\n self._randomizer.randomize_geoms(\n parent_body_names=['valve'],\n color_range=(0.2, 0.9),\n )\n super()._reset()\n"
] | [
[
"numpy.array"
],
[
"numpy.abs",
"numpy.asarray",
"numpy.cos",
"numpy.linalg.norm",
"numpy.sin",
"numpy.atleast_1d",
"numpy.mod"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
raphacosta27/geopandas | [
"2c22a26bd40ec48536026b160c54c6fe523d22d7"
] | [
"geopandas/tests/test_geom_methods.py"
] | [
"import string\n\nimport numpy as np\nfrom numpy.testing import assert_array_equal\nfrom pandas import DataFrame, MultiIndex, Series\n\nfrom shapely.geometry import LinearRing, LineString, MultiPoint, Point, Polygon\nfrom shapely.geometry.collection import GeometryCollection\nfrom shapely.ops import unary_union\n\nfrom geopandas import GeoDataFrame, GeoSeries\nfrom geopandas.base import GeoPandasBase\n\nfrom geopandas.tests.util import assert_geoseries_equal, geom_almost_equals, geom_equals\nfrom pandas.testing import assert_frame_equal, assert_series_equal\nimport pytest\n\n\ndef assert_array_dtype_equal(a, b, *args, **kwargs):\n a = np.asanyarray(a)\n b = np.asanyarray(b)\n assert a.dtype == b.dtype\n assert_array_equal(a, b, *args, **kwargs)\n\n\nclass TestGeomMethods:\n def setup_method(self):\n self.t1 = Polygon([(0, 0), (1, 0), (1, 1)])\n self.t2 = Polygon([(0, 0), (1, 1), (0, 1)])\n self.t3 = Polygon([(2, 0), (3, 0), (3, 1)])\n self.sq = Polygon([(0, 0), (1, 0), (1, 1), (0, 1)])\n self.inner_sq = Polygon(\n [(0.25, 0.25), (0.75, 0.25), (0.75, 0.75), (0.25, 0.75)]\n )\n self.nested_squares = Polygon(self.sq.boundary, [self.inner_sq.boundary])\n self.p0 = Point(5, 5)\n self.p3d = Point(5, 5, 5)\n self.g0 = GeoSeries(\n [\n self.t1,\n self.t2,\n self.sq,\n self.inner_sq,\n self.nested_squares,\n self.p0,\n None,\n ]\n )\n self.g1 = GeoSeries([self.t1, self.sq])\n self.g2 = GeoSeries([self.sq, self.t1])\n self.g3 = GeoSeries([self.t1, self.t2])\n self.g3.crs = \"epsg:4326\"\n self.g4 = GeoSeries([self.t2, self.t1])\n self.g4.crs = \"epsg:4326\"\n self.g_3d = GeoSeries([self.p0, self.p3d])\n self.na = GeoSeries([self.t1, self.t2, Polygon()])\n self.na_none = GeoSeries([self.t1, None])\n self.a1 = self.g1.copy()\n self.a1.index = [\"A\", \"B\"]\n self.a2 = self.g2.copy()\n self.a2.index = [\"B\", \"C\"]\n self.esb = Point(-73.9847, 40.7484)\n self.sol = Point(-74.0446, 40.6893)\n self.landmarks = GeoSeries([self.esb, self.sol], crs=\"epsg:4326\")\n self.l1 = LineString([(0, 0), (0, 1), (1, 1)])\n self.l2 = LineString([(0, 0), (1, 0), (1, 1), (0, 1)])\n self.g5 = GeoSeries([self.l1, self.l2])\n self.g6 = GeoSeries([self.p0, self.t3])\n self.empty = GeoSeries([])\n self.all_none = GeoSeries([None, None])\n self.empty_poly = Polygon()\n\n # Crossed lines\n self.l3 = LineString([(0, 0), (1, 1)])\n self.l4 = LineString([(0, 1), (1, 0)])\n self.crossed_lines = GeoSeries([self.l3, self.l4])\n\n # Placeholder for testing, will just drop in different geometries\n # when needed\n self.gdf1 = GeoDataFrame(\n {\"geometry\": self.g1, \"col0\": [1.0, 2.0], \"col1\": [\"geo\", \"pandas\"]}\n )\n self.gdf2 = GeoDataFrame(\n {\"geometry\": self.g1, \"col3\": [4, 5], \"col4\": [\"rand\", \"string\"]}\n )\n self.gdf3 = GeoDataFrame(\n {\"geometry\": self.g3, \"col3\": [4, 5], \"col4\": [\"rand\", \"string\"]}\n )\n\n def _test_unary_real(self, op, expected, a):\n \"\"\" Tests for 'area', 'length', 'is_valid', etc. \"\"\"\n fcmp = assert_series_equal\n self._test_unary(op, expected, a, fcmp)\n\n def _test_unary_topological(self, op, expected, a):\n if isinstance(expected, GeoPandasBase):\n fcmp = assert_geoseries_equal\n else:\n\n def fcmp(a, b):\n assert a.equals(b)\n\n self._test_unary(op, expected, a, fcmp)\n\n def _test_binary_topological(self, op, expected, a, b, *args, **kwargs):\n \"\"\" Tests for 'intersection', 'union', 'symmetric_difference', etc. \"\"\"\n if isinstance(expected, GeoPandasBase):\n fcmp = assert_geoseries_equal\n else:\n\n def fcmp(a, b):\n assert geom_equals(a, b)\n\n if isinstance(b, GeoPandasBase):\n right_df = True\n else:\n right_df = False\n\n self._binary_op_test(op, expected, a, b, fcmp, True, right_df, *args, **kwargs)\n\n def _test_binary_real(self, op, expected, a, b, *args, **kwargs):\n fcmp = assert_series_equal\n self._binary_op_test(op, expected, a, b, fcmp, True, False, *args, **kwargs)\n\n def _test_binary_operator(self, op, expected, a, b):\n \"\"\"\n The operators only have GeoSeries on the left, but can have\n GeoSeries or GeoDataFrame on the right.\n If GeoDataFrame is on the left, geometry column is used.\n\n \"\"\"\n if isinstance(expected, GeoPandasBase):\n fcmp = assert_geoseries_equal\n else:\n\n def fcmp(a, b):\n assert geom_equals(a, b)\n\n if isinstance(b, GeoPandasBase):\n right_df = True\n else:\n right_df = False\n\n self._binary_op_test(op, expected, a, b, fcmp, False, right_df)\n\n def _binary_op_test(\n self, op, expected, left, right, fcmp, left_df, right_df, *args, **kwargs\n ):\n \"\"\"\n This is a helper to call a function on GeoSeries and GeoDataFrame\n arguments. For example, 'intersection' is a member of both GeoSeries\n and GeoDataFrame and can take either GeoSeries or GeoDataFrame inputs.\n This function has the ability to test all four combinations of input\n types.\n\n Parameters\n ----------\n\n expected : str\n The operation to be tested. e.g., 'intersection'\n left: GeoSeries\n right: GeoSeries\n fcmp: function\n Called with the result of the operation and expected. It should\n assert if the result is incorrect\n left_df: bool\n If the left input should also be called with a GeoDataFrame\n right_df: bool\n Indicates whether the right input should be called with a\n GeoDataFrame\n\n \"\"\"\n\n def _make_gdf(s):\n n = len(s)\n col1 = string.ascii_lowercase[:n]\n col2 = range(n)\n\n return GeoDataFrame(\n {\"geometry\": s.values, \"col1\": col1, \"col2\": col2},\n index=s.index,\n crs=s.crs,\n )\n\n # Test GeoSeries.op(GeoSeries)\n result = getattr(left, op)(right, *args, **kwargs)\n fcmp(result, expected)\n\n if left_df:\n # Test GeoDataFrame.op(GeoSeries)\n gdf_left = _make_gdf(left)\n result = getattr(gdf_left, op)(right, *args, **kwargs)\n fcmp(result, expected)\n\n if right_df:\n # Test GeoSeries.op(GeoDataFrame)\n gdf_right = _make_gdf(right)\n result = getattr(left, op)(gdf_right, *args, **kwargs)\n fcmp(result, expected)\n\n if left_df:\n # Test GeoDataFrame.op(GeoDataFrame)\n result = getattr(gdf_left, op)(gdf_right, *args, **kwargs)\n fcmp(result, expected)\n\n def _test_unary(self, op, expected, a, fcmp):\n # GeoSeries, (GeoSeries or geometry)\n result = getattr(a, op)\n fcmp(result, expected)\n\n # GeoDataFrame, (GeoSeries or geometry)\n gdf = self.gdf1.set_geometry(a)\n result = getattr(gdf, op)\n fcmp(result, expected)\n\n # TODO reenable for all operations once we use pyproj > 2\n # def test_crs_warning(self):\n # # operations on geometries should warn for different CRS\n # no_crs_g3 = self.g3.copy()\n # no_crs_g3.crs = None\n # with pytest.warns(UserWarning):\n # self._test_binary_topological('intersection', self.g3,\n # self.g3, no_crs_g3)\n\n def test_intersection(self):\n self._test_binary_topological(\"intersection\", self.t1, self.g1, self.g2)\n with pytest.warns(UserWarning, match=\"The indices .+ different\"):\n self._test_binary_topological(\n \"intersection\", self.all_none, self.g1, self.empty\n )\n\n def test_union_series(self):\n self._test_binary_topological(\"union\", self.sq, self.g1, self.g2)\n\n def test_union_polygon(self):\n self._test_binary_topological(\"union\", self.sq, self.g1, self.t2)\n\n def test_symmetric_difference_series(self):\n self._test_binary_topological(\"symmetric_difference\", self.sq, self.g3, self.g4)\n\n def test_symmetric_difference_poly(self):\n expected = GeoSeries([GeometryCollection(), self.sq], crs=self.g3.crs)\n self._test_binary_topological(\n \"symmetric_difference\", expected, self.g3, self.t1\n )\n\n def test_difference_series(self):\n expected = GeoSeries([GeometryCollection(), self.t2])\n self._test_binary_topological(\"difference\", expected, self.g1, self.g2)\n\n def test_difference_poly(self):\n expected = GeoSeries([self.t1, self.t1])\n self._test_binary_topological(\"difference\", expected, self.g1, self.t2)\n\n def test_geo_op_empty_result(self):\n l1 = LineString([(0, 0), (1, 1)])\n l2 = LineString([(2, 2), (3, 3)])\n expected = GeoSeries([GeometryCollection()])\n # binary geo resulting in empty geometry\n result = GeoSeries([l1]).intersection(l2)\n assert_geoseries_equal(result, expected)\n # binary geo empty result with right GeoSeries\n result = GeoSeries([l1]).intersection(GeoSeries([l2]))\n assert_geoseries_equal(result, expected)\n # unary geo resulting in emtpy geometry\n result = GeoSeries([GeometryCollection()]).convex_hull\n assert_geoseries_equal(result, expected)\n\n def test_boundary(self):\n l1 = LineString([(0, 0), (1, 0), (1, 1), (0, 0)])\n l2 = LineString([(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)])\n expected = GeoSeries([l1, l2], index=self.g1.index, crs=self.g1.crs)\n\n self._test_unary_topological(\"boundary\", expected, self.g1)\n\n def test_area(self):\n expected = Series(np.array([0.5, 1.0]), index=self.g1.index)\n self._test_unary_real(\"area\", expected, self.g1)\n\n expected = Series(np.array([0.5, np.nan]), index=self.na_none.index)\n self._test_unary_real(\"area\", expected, self.na_none)\n\n def test_bounds(self):\n # Set columns to get the order right\n expected = DataFrame(\n {\n \"minx\": [0.0, 0.0],\n \"miny\": [0.0, 0.0],\n \"maxx\": [1.0, 1.0],\n \"maxy\": [1.0, 1.0],\n },\n index=self.g1.index,\n columns=[\"minx\", \"miny\", \"maxx\", \"maxy\"],\n )\n\n result = self.g1.bounds\n assert_frame_equal(expected, result)\n\n gdf = self.gdf1.set_geometry(self.g1)\n result = gdf.bounds\n assert_frame_equal(expected, result)\n\n def test_bounds_empty(self):\n # test bounds of empty GeoSeries\n # https://github.com/geopandas/geopandas/issues/1195\n s = GeoSeries([])\n result = s.bounds\n expected = DataFrame(\n columns=[\"minx\", \"miny\", \"maxx\", \"maxy\"], index=s.index, dtype=\"float64\"\n )\n assert_frame_equal(result, expected)\n\n def test_unary_union(self):\n p1 = self.t1\n p2 = Polygon([(2, 0), (3, 0), (3, 1)])\n expected = unary_union([p1, p2])\n g = GeoSeries([p1, p2])\n\n self._test_unary_topological(\"unary_union\", expected, g)\n\n def test_contains(self):\n expected = [True, False, True, False, False, False, False]\n assert_array_dtype_equal(expected, self.g0.contains(self.t1))\n\n def test_length(self):\n expected = Series(np.array([2 + np.sqrt(2), 4]), index=self.g1.index)\n self._test_unary_real(\"length\", expected, self.g1)\n\n expected = Series(np.array([2 + np.sqrt(2), np.nan]), index=self.na_none.index)\n self._test_unary_real(\"length\", expected, self.na_none)\n\n def test_crosses(self):\n expected = [False, False, False, False, False, False, False]\n assert_array_dtype_equal(expected, self.g0.crosses(self.t1))\n\n expected = [False, True]\n assert_array_dtype_equal(expected, self.crossed_lines.crosses(self.l3))\n\n def test_disjoint(self):\n expected = [False, False, False, False, False, True, False]\n assert_array_dtype_equal(expected, self.g0.disjoint(self.t1))\n\n def test_relate(self):\n expected = Series(\n [\n \"212101212\",\n \"212101212\",\n \"212FF1FF2\",\n \"2FFF1FFF2\",\n \"FF2F112F2\",\n \"FF0FFF212\",\n None,\n ],\n index=self.g0.index,\n )\n assert_array_dtype_equal(expected, self.g0.relate(self.inner_sq))\n\n expected = Series([\"FF0FFF212\", None], index=self.g6.index)\n assert_array_dtype_equal(expected, self.g6.relate(self.na_none))\n\n def test_distance(self):\n expected = Series(\n np.array([np.sqrt((5 - 1) ** 2 + (5 - 1) ** 2), np.nan]), self.na_none.index\n )\n assert_array_dtype_equal(expected, self.na_none.distance(self.p0))\n\n expected = Series(np.array([np.sqrt(4 ** 2 + 4 ** 2), np.nan]), self.g6.index)\n assert_array_dtype_equal(expected, self.g6.distance(self.na_none))\n\n def test_intersects(self):\n expected = [True, True, True, True, True, False, False]\n assert_array_dtype_equal(expected, self.g0.intersects(self.t1))\n\n expected = [True, False]\n assert_array_dtype_equal(expected, self.na_none.intersects(self.t2))\n\n expected = np.array([], dtype=bool)\n assert_array_dtype_equal(expected, self.empty.intersects(self.t1))\n\n expected = np.array([], dtype=bool)\n assert_array_dtype_equal(expected, self.empty.intersects(self.empty_poly))\n\n expected = [False] * 7\n assert_array_dtype_equal(expected, self.g0.intersects(self.empty_poly))\n\n def test_overlaps(self):\n expected = [True, True, False, False, False, False, False]\n assert_array_dtype_equal(expected, self.g0.overlaps(self.inner_sq))\n\n expected = [False, False]\n assert_array_dtype_equal(expected, self.g4.overlaps(self.t1))\n\n def test_touches(self):\n expected = [False, True, False, False, False, False, False]\n assert_array_dtype_equal(expected, self.g0.touches(self.t1))\n\n def test_within(self):\n expected = [True, False, False, False, False, False, False]\n assert_array_dtype_equal(expected, self.g0.within(self.t1))\n\n expected = [True, True, True, True, True, False, False]\n assert_array_dtype_equal(expected, self.g0.within(self.sq))\n\n def test_is_valid(self):\n expected = Series(np.array([True] * len(self.g1)), self.g1.index)\n self._test_unary_real(\"is_valid\", expected, self.g1)\n\n def test_is_empty(self):\n expected = Series(np.array([False] * len(self.g1)), self.g1.index)\n self._test_unary_real(\"is_empty\", expected, self.g1)\n\n def test_is_ring(self):\n expected = Series(np.array([True] * len(self.g1)), self.g1.index)\n self._test_unary_real(\"is_ring\", expected, self.g1)\n\n def test_is_simple(self):\n expected = Series(np.array([True] * len(self.g1)), self.g1.index)\n self._test_unary_real(\"is_simple\", expected, self.g1)\n\n def test_has_z(self):\n expected = Series([False, True], self.g_3d.index)\n self._test_unary_real(\"has_z\", expected, self.g_3d)\n\n def test_xy_points(self):\n expected_x = [-73.9847, -74.0446]\n expected_y = [40.7484, 40.6893]\n\n assert_array_dtype_equal(expected_x, self.landmarks.geometry.x)\n assert_array_dtype_equal(expected_y, self.landmarks.geometry.y)\n\n def test_xy_polygons(self):\n # accessing x attribute in polygon geoseries should raise an error\n with pytest.raises(ValueError):\n _ = self.gdf1.geometry.x\n # and same for accessing y attribute in polygon geoseries\n with pytest.raises(ValueError):\n _ = self.gdf1.geometry.y\n\n def test_centroid(self):\n polygon = Polygon([(-1, -1), (1, -1), (1, 1), (-1, 1)])\n point = Point(0, 0)\n polygons = GeoSeries([polygon for i in range(3)])\n points = GeoSeries([point for i in range(3)])\n assert_geoseries_equal(polygons.centroid, points)\n\n def test_convex_hull(self):\n # the convex hull of a square should be the same as the square\n squares = GeoSeries([self.sq for i in range(3)])\n assert_geoseries_equal(squares, squares.convex_hull)\n\n def test_exterior(self):\n exp_exterior = GeoSeries([LinearRing(p.boundary) for p in self.g3])\n for expected, computed in zip(exp_exterior, self.g3.exterior):\n assert computed.equals(expected)\n\n def test_interiors(self):\n original = GeoSeries([self.t1, self.nested_squares])\n\n # This is a polygon with no interior.\n expected = []\n assert original.interiors[0] == expected\n # This is a polygon with an interior.\n expected = LinearRing(self.inner_sq.boundary)\n assert original.interiors[1][0].equals(expected)\n\n def test_interpolate(self):\n expected = GeoSeries([Point(0.5, 1.0), Point(0.75, 1.0)])\n self._test_binary_topological(\n \"interpolate\", expected, self.g5, 0.75, normalized=True\n )\n\n expected = GeoSeries([Point(0.5, 1.0), Point(1.0, 0.5)])\n self._test_binary_topological(\"interpolate\", expected, self.g5, 1.5)\n\n def test_interpolate_distance_array(self):\n expected = GeoSeries([Point(0.0, 0.75), Point(1.0, 0.5)])\n self._test_binary_topological(\n \"interpolate\", expected, self.g5, np.array([0.75, 1.5])\n )\n\n expected = GeoSeries([Point(0.5, 1.0), Point(0.0, 1.0)])\n self._test_binary_topological(\n \"interpolate\", expected, self.g5, np.array([0.75, 1.5]), normalized=True\n )\n\n def test_interpolate_distance_wrong_length(self):\n distances = np.array([1, 2, 3])\n with pytest.raises(ValueError):\n self.g5.interpolate(distances)\n\n def test_interpolate_distance_wrong_index(self):\n distances = Series([1, 2], index=[99, 98])\n with pytest.raises(ValueError):\n self.g5.interpolate(distances)\n\n def test_project(self):\n expected = Series([2.0, 1.5], index=self.g5.index)\n p = Point(1.0, 0.5)\n self._test_binary_real(\"project\", expected, self.g5, p)\n\n expected = Series([1.0, 0.5], index=self.g5.index)\n self._test_binary_real(\"project\", expected, self.g5, p, normalized=True)\n\n def test_affine_transform(self):\n # 45 degree reflection matrix\n matrix = [0, 1, 1, 0, 0, 0]\n expected = self.g4\n\n res = self.g3.affine_transform(matrix)\n assert_geoseries_equal(expected, res)\n\n def test_translate_tuple(self):\n trans = self.sol.x - self.esb.x, self.sol.y - self.esb.y\n assert self.landmarks.translate(*trans)[0].equals(self.sol)\n\n res = self.gdf1.set_geometry(self.landmarks).translate(*trans)[0]\n assert res.equals(self.sol)\n\n def test_rotate(self):\n angle = 98\n expected = self.g4\n\n o = Point(0, 0)\n res = self.g4.rotate(angle, origin=o).rotate(-angle, origin=o)\n assert geom_almost_equals(self.g4, res)\n\n res = self.gdf1.set_geometry(self.g4).rotate(angle, origin=Point(0, 0))\n assert geom_almost_equals(expected, res.rotate(-angle, origin=o))\n\n def test_scale(self):\n expected = self.g4\n\n scale = 2.0, 1.0\n inv = tuple(1.0 / i for i in scale)\n\n o = Point(0, 0)\n res = self.g4.scale(*scale, origin=o).scale(*inv, origin=o)\n assert geom_almost_equals(expected, res)\n\n res = self.gdf1.set_geometry(self.g4).scale(*scale, origin=o)\n res = res.scale(*inv, origin=o)\n assert geom_almost_equals(expected, res)\n\n def test_skew(self):\n expected = self.g4\n\n skew = 45.0\n o = Point(0, 0)\n\n # Test xs\n res = self.g4.skew(xs=skew, origin=o).skew(xs=-skew, origin=o)\n assert geom_almost_equals(expected, res)\n\n res = self.gdf1.set_geometry(self.g4).skew(xs=skew, origin=o)\n res = res.skew(xs=-skew, origin=o)\n assert geom_almost_equals(expected, res)\n\n # Test ys\n res = self.g4.skew(ys=skew, origin=o).skew(ys=-skew, origin=o)\n assert geom_almost_equals(expected, res)\n\n res = self.gdf1.set_geometry(self.g4).skew(ys=skew, origin=o)\n res = res.skew(ys=-skew, origin=o)\n assert geom_almost_equals(expected, res)\n\n def test_buffer(self):\n original = GeoSeries([Point(0, 0)])\n expected = GeoSeries([Polygon(((5, 0), (0, -5), (-5, 0), (0, 5), (5, 0)))])\n calculated = original.buffer(5, resolution=1)\n assert geom_almost_equals(expected, calculated)\n\n def test_buffer_args(self):\n args = dict(cap_style=3, join_style=2, mitre_limit=2.5)\n calculated_series = self.g0.buffer(10, **args)\n for original, calculated in zip(self.g0, calculated_series):\n if original is None:\n assert calculated is None\n else:\n expected = original.buffer(10, **args)\n assert calculated.equals(expected)\n\n def test_buffer_distance_array(self):\n original = GeoSeries([self.p0, self.p0])\n expected = GeoSeries(\n [\n Polygon(((6, 5), (5, 4), (4, 5), (5, 6), (6, 5))),\n Polygon(((10, 5), (5, 0), (0, 5), (5, 10), (10, 5))),\n ]\n )\n calculated = original.buffer(np.array([1, 5]), resolution=1)\n assert_geoseries_equal(calculated, expected, check_less_precise=True)\n\n def test_buffer_distance_wrong_length(self):\n original = GeoSeries([self.p0, self.p0])\n distances = np.array([1, 2, 3])\n with pytest.raises(ValueError):\n original.buffer(distances)\n\n def test_buffer_distance_wrong_index(self):\n original = GeoSeries([self.p0, self.p0], index=[0, 1])\n distances = Series(data=[1, 2], index=[99, 98])\n with pytest.raises(ValueError):\n original.buffer(distances)\n\n def test_buffer_empty_none(self):\n p = Polygon([(0, 0), (0, 1), (1, 1), (1, 0)])\n s = GeoSeries([p, GeometryCollection(), None])\n result = s.buffer(0)\n assert_geoseries_equal(result, s)\n\n result = s.buffer(np.array([0, 0, 0]))\n assert_geoseries_equal(result, s)\n\n def test_envelope(self):\n e = self.g3.envelope\n assert np.all(e.geom_equals(self.sq))\n assert isinstance(e, GeoSeries)\n assert self.g3.crs == e.crs\n\n def test_total_bounds(self):\n bbox = self.sol.x, self.sol.y, self.esb.x, self.esb.y\n assert isinstance(self.landmarks.total_bounds, np.ndarray)\n assert tuple(self.landmarks.total_bounds) == bbox\n\n df = GeoDataFrame(\n {\"geometry\": self.landmarks, \"col1\": range(len(self.landmarks))}\n )\n assert tuple(df.total_bounds) == bbox\n\n def test_explode_geoseries(self):\n s = GeoSeries(\n [MultiPoint([(0, 0), (1, 1)]), MultiPoint([(2, 2), (3, 3), (4, 4)])]\n )\n s.index.name = \"test_index_name\"\n expected_index_name = [\"test_index_name\", None]\n index = [(0, 0), (0, 1), (1, 0), (1, 1), (1, 2)]\n expected = GeoSeries(\n [Point(0, 0), Point(1, 1), Point(2, 2), Point(3, 3), Point(4, 4)],\n index=MultiIndex.from_tuples(index, names=expected_index_name),\n )\n assert_geoseries_equal(expected, s.explode())\n\n @pytest.mark.parametrize(\"index_name\", [None, \"test\"])\n def test_explode_geodataframe(self, index_name):\n s = GeoSeries([MultiPoint([Point(1, 2), Point(2, 3)]), Point(5, 5)])\n df = GeoDataFrame({\"col\": [1, 2], \"geometry\": s})\n df.index.name = index_name\n\n test_df = df.explode()\n\n expected_s = GeoSeries([Point(1, 2), Point(2, 3), Point(5, 5)])\n expected_df = GeoDataFrame({\"col\": [1, 1, 2], \"geometry\": expected_s})\n expected_index = MultiIndex(\n [[0, 1], [0, 1]], # levels\n [[0, 0, 1], [0, 1, 0]], # labels/codes\n names=[index_name, None],\n )\n expected_df = expected_df.set_index(expected_index)\n assert_frame_equal(test_df, expected_df)\n\n #\n # Test '&', '|', '^', and '-'\n #\n def test_intersection_operator(self):\n with pytest.warns(DeprecationWarning):\n self._test_binary_operator(\"__and__\", self.t1, self.g1, self.g2)\n with pytest.warns(DeprecationWarning):\n self._test_binary_operator(\"__and__\", self.t1, self.gdf1, self.g2)\n\n def test_union_operator(self):\n with pytest.warns(DeprecationWarning):\n self._test_binary_operator(\"__or__\", self.sq, self.g1, self.g2)\n with pytest.warns(DeprecationWarning):\n self._test_binary_operator(\"__or__\", self.sq, self.gdf1, self.g2)\n\n def test_union_operator_polygon(self):\n with pytest.warns(DeprecationWarning):\n self._test_binary_operator(\"__or__\", self.sq, self.g1, self.t2)\n with pytest.warns(DeprecationWarning):\n self._test_binary_operator(\"__or__\", self.sq, self.gdf1, self.t2)\n\n def test_symmetric_difference_operator(self):\n with pytest.warns(DeprecationWarning):\n self._test_binary_operator(\"__xor__\", self.sq, self.g3, self.g4)\n with pytest.warns(DeprecationWarning):\n self._test_binary_operator(\"__xor__\", self.sq, self.gdf3, self.g4)\n\n def test_difference_series2(self):\n expected = GeoSeries([GeometryCollection(), self.t2])\n with pytest.warns(DeprecationWarning):\n self._test_binary_operator(\"__sub__\", expected, self.g1, self.g2)\n with pytest.warns(DeprecationWarning):\n self._test_binary_operator(\"__sub__\", expected, self.gdf1, self.g2)\n\n def test_difference_poly2(self):\n expected = GeoSeries([self.t1, self.t1])\n with pytest.warns(DeprecationWarning):\n self._test_binary_operator(\"__sub__\", expected, self.g1, self.t2)\n with pytest.warns(DeprecationWarning):\n self._test_binary_operator(\"__sub__\", expected, self.gdf1, self.t2)\n"
] | [
[
"pandas.Series",
"numpy.sqrt",
"pandas.MultiIndex",
"pandas.MultiIndex.from_tuples",
"pandas.DataFrame",
"numpy.testing.assert_array_equal",
"numpy.asanyarray",
"pandas.testing.assert_frame_equal",
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
moesio-f/agents | [
"53ce87c9203222585fdcd833e052fcdce1b6fa37"
] | [
"tf_agents/policies/tf_policy.py"
] | [
"# coding=utf-8\n# Copyright 2020 The TF-Agents 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# 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\"\"\"TensorFlow Policies API.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport abc\nfrom typing import Optional, Text, Sequence\n\nimport six\nimport tensorflow as tf\nimport tensorflow_probability as tfp\n\nfrom tf_agents.distributions import reparameterized_sampling\nfrom tf_agents.specs import tensor_spec\nfrom tf_agents.trajectories import policy_step\nfrom tf_agents.trajectories import time_step as ts\nfrom tf_agents.trajectories import trajectory\nfrom tf_agents.typing import types\nfrom tf_agents.utils import common\nfrom tf_agents.utils import nest_utils\n\n\ntfd = tfp.distributions\n\n\[email protected]_metaclass(abc.ABCMeta)\nclass TFPolicy(tf.Module):\n \"\"\"Abstract base class for TF Policies.\n\n The Policy represents a mapping from `time_steps` recieved from the\n environment to `actions` that can be applied to the environment.\n\n Agents expose two policies. A `policy` meant for deployment and evaluation,\n and a `collect_policy` for collecting data from the environment. The\n `collect_policy` is usually stochastic for exploring the environment better\n and may log auxilliary information such as log probabilities required for\n training as well. `Policy` objects can also be created directly by the users\n without using an `Agent`.\n\n The main methods of TFPolicy are:\n\n * `action`: Maps a `time_step` from the environment to an action.\n * `distribution`: Maps a `time_step` to a distribution over actions.\n * `get_initial_state`: Generates the initial state for stateful policies, e.g.\n RNN/LSTM policies.\n\n Example usage:\n\n ```\n env = SomeTFEnvironment()\n policy = TFRandomPolicy(env.time_step_spec(), env.action_spec())\n # Or policy = agent.policy or agent.collect_policy\n\n policy_state = policy.get_initial_state(env.batch_size)\n time_step = env.reset()\n\n while not time_step.is_last():\n policy_step = policy.action(time_step, policy_state)\n time_step = env.step(policy_step.action)\n\n policy_state = policy_step.state\n # policy_step.info may contain side info for logging, such as action log\n # probabilities.\n ```\n\n Policies can be saved to disk as SavedModels (see policy_saver.py and\n policy_loader.py) or as TF Checkpoints.\n\n A `PyTFEagerPolicy` can be used to wrap a `TFPolicy` so that it works with\n `PyEnvironment`s.\n\n\n **NOTE**: For API consistency, subclasses are not allowed to override public\n methods of `TFPolicy` class. Instead, they may implement the protected methods\n including `_get_initial_state`, `_action`, and `_distribution`. This\n public-calls-private convention allowed this base class to do things like\n properly add `spec` and shape checks, which provide users an easier experience\n when debugging their environments and networks.\n\n For researchers, and those developing new Policies, the `TFPolicy` base class\n constructor also accept a `validate_args` parameter. If `False`, this\n disables all spec structure, dtype, and shape checks in the public methods of\n these classes. It allows algorithm developers to iterate and try different\n input and output structures without worrying about overly restrictive\n requirements, or input and output states being in a certain format. However,\n *disabling argument validation* can make it very hard to identify structural\n input or algorithmic errors; and should not be done for final, or\n production-ready, Policies. In addition to having implementations that may\n disagree with specs, this mean that the resulting Policy may no longer\n interact well with other parts of TF-Agents. Examples include impedance\n mismatches with Actor/Learner APIs, replay buffers, and the model export\n functionality in `PolicySaver.\n \"\"\"\n\n # TODO(b/127327645) Remove this attribute.\n # This attribute allows subclasses to back out of automatic tf.function\n # attribute inside TF1 (for autodeps).\n _enable_functions = True\n\n def __init__(\n self,\n time_step_spec: ts.TimeStep,\n action_spec: types.NestedTensorSpec,\n policy_state_spec: types.NestedTensorSpec = (),\n info_spec: types.NestedTensorSpec = (),\n clip: bool = True,\n emit_log_probability: bool = False,\n automatic_state_reset: bool = True,\n observation_and_action_constraint_splitter: Optional[\n types.Splitter] = None,\n validate_args: bool = True,\n name: Optional[Text] = None):\n \"\"\"Initialization of TFPolicy class.\n\n Args:\n time_step_spec: A `TimeStep` spec of the expected time_steps. Usually\n provided by the user to the subclass.\n action_spec: A nest of BoundedTensorSpec representing the actions. Usually\n provided by the user to the subclass.\n policy_state_spec: A nest of TensorSpec representing the policy_state.\n Provided by the subclass, not directly by the user.\n info_spec: A nest of TensorSpec representing the policy info. Provided by\n the subclass, not directly by the user.\n clip: Whether to clip actions to spec before returning them. Default\n True. Most policy-based algorithms (PCL, PPO, REINFORCE) use unclipped\n continuous actions for training.\n emit_log_probability: Emit log-probabilities of actions, if supported. If\n True, policy_step.info will have CommonFields.LOG_PROBABILITY set.\n Please consult utility methods provided in policy_step for setting and\n retrieving these. When working with custom policies, either provide a\n dictionary info_spec or a namedtuple with the field 'log_probability'.\n automatic_state_reset: If `True`, then `get_initial_policy_state` is used\n to clear state in `action()` and `distribution()` for for time steps\n where `time_step.is_first()`.\n observation_and_action_constraint_splitter: A function used to process\n observations with action constraints. These constraints can indicate,\n for example, a mask of valid/invalid actions for a given state of the\n environment. The function takes in a full observation and returns a\n tuple consisting of 1) the part of the observation intended as input to\n the network and 2) the constraint. An example\n `observation_and_action_constraint_splitter` could be as simple as: ```\n def observation_and_action_constraint_splitter(observation): return\n observation['network_input'], observation['constraint'] ```\n *Note*: when using `observation_and_action_constraint_splitter`, make\n sure the provided `q_network` is compatible with the network-specific\n half of the output of the\n `observation_and_action_constraint_splitter`. In particular,\n `observation_and_action_constraint_splitter` will be called on the\n observation before passing to the network. If\n `observation_and_action_constraint_splitter` is None, action\n constraints are not applied.\n validate_args: Python bool. Whether to verify inputs to, and outputs of,\n functions like `action` and `distribution` against spec structures,\n dtypes, and shapes.\n\n Research code may prefer to set this value to `False` to allow iterating\n on input and output structures without being hamstrung by overly\n rigid checking (at the cost of harder-to-debug errors).\n\n See also `TFAgent.validate_args`.\n name: A name for this module. Defaults to the class name.\n \"\"\"\n super(TFPolicy, self).__init__(name=name)\n common.check_tf1_allowed()\n common.tf_agents_gauge.get_cell('TFAPolicy').set(True)\n common.assert_members_are_not_overridden(base_cls=TFPolicy, instance=self)\n if not isinstance(time_step_spec, ts.TimeStep):\n raise ValueError(\n 'The `time_step_spec` must be an instance of `TimeStep`, but is `{}`.'\n .format(type(time_step_spec)))\n\n self._time_step_spec = tensor_spec.from_spec(time_step_spec)\n self._action_spec = tensor_spec.from_spec(action_spec)\n self._policy_state_spec = tensor_spec.from_spec(policy_state_spec)\n self._emit_log_probability = emit_log_probability\n self._validate_args = validate_args\n\n if emit_log_probability:\n log_probability_spec = tensor_spec.BoundedTensorSpec(\n shape=(),\n dtype=tf.float32,\n maximum=0,\n minimum=-float('inf'),\n name='log_probability')\n log_probability_spec = tf.nest.map_structure(\n lambda _: log_probability_spec, action_spec)\n info_spec = policy_step.set_log_probability(\n info_spec, log_probability_spec) # pytype: disable=wrong-arg-types\n\n self._info_spec = tensor_spec.from_spec(info_spec)\n self._setup_specs()\n self._clip = clip\n self._action_fn = common.function_in_tf1(experimental_relax_shapes=False)(\n self._action)\n self._automatic_state_reset = automatic_state_reset\n self._observation_and_action_constraint_splitter = (\n observation_and_action_constraint_splitter)\n\n def _setup_specs(self):\n self._policy_step_spec = policy_step.PolicyStep(\n action=self._action_spec,\n state=self._policy_state_spec,\n info=self._info_spec)\n self._trajectory_spec = trajectory.from_transition(self._time_step_spec,\n self._policy_step_spec,\n self._time_step_spec)\n\n def variables(self) -> Sequence[tf.Variable]:\n \"\"\"Returns the list of Variables that belong to the policy.\"\"\"\n # Ignore self._variables() in favor of using tf.Module's tracking.\n return super(TFPolicy, self).variables\n\n @property\n def observation_and_action_constraint_splitter(self) -> types.Splitter:\n return self._observation_and_action_constraint_splitter\n\n @property\n def validate_args(self) -> bool:\n \"\"\"Whether `action` & `distribution` validate input and output args.\"\"\"\n return self._validate_args\n\n def get_initial_state(self,\n batch_size: Optional[types.Int]) -> types.NestedTensor:\n \"\"\"Returns an initial state usable by the policy.\n\n Args:\n batch_size: Tensor or constant: size of the batch dimension. Can be None\n in which case no dimensions gets added.\n\n Returns:\n A nested object of type `policy_state` containing properly\n initialized Tensors.\n \"\"\"\n return self._get_initial_state(batch_size)\n\n def _maybe_reset_state(self, time_step, policy_state):\n if policy_state is (): # pylint: disable=literal-comparison\n return policy_state\n\n batch_size = tf.compat.dimension_value(time_step.discount.shape[0])\n if batch_size is None:\n batch_size = tf.shape(time_step.discount)[0]\n\n # Make sure we call this with a kwarg as it may be wrapped in tf.function\n # which would expect a tensor if it was not a kwarg.\n zero_state = self.get_initial_state(batch_size=batch_size)\n condition = time_step.is_first()\n # When experience is a sequence we only reset automatically for the first\n # time_step in the sequence as we can't easily generalize how the policy is\n # unrolled over the sequence.\n if nest_utils.get_outer_rank(time_step, self._time_step_spec) > 1:\n condition = time_step.is_first()[:, 0, ...]\n return nest_utils.where(condition, zero_state, policy_state)\n\n def action(self,\n time_step: ts.TimeStep,\n policy_state: types.NestedTensor = (),\n seed: Optional[types.Seed] = None) -> policy_step.PolicyStep:\n \"\"\"Generates next action given the time_step and policy_state.\n\n Args:\n time_step: A `TimeStep` tuple corresponding to `time_step_spec()`.\n policy_state: A Tensor, or a nested dict, list or tuple of Tensors\n representing the previous policy_state.\n seed: Seed to use if action performs sampling (optional).\n\n Returns:\n A `PolicyStep` named tuple containing:\n `action`: An action Tensor matching the `action_spec`.\n `state`: A policy state tensor to be fed into the next call to action.\n `info`: Optional side information such as action log probabilities.\n\n Raises:\n RuntimeError: If subclass __init__ didn't call super().__init__.\n ValueError or TypeError: If `validate_args is True` and inputs or\n outputs do not match `time_step_spec`, `policy_state_spec`,\n or `policy_step_spec`.\n \"\"\"\n if self._enable_functions and getattr(self, '_action_fn', None) is None:\n raise RuntimeError(\n 'Cannot find _action_fn. Did %s.__init__ call super?' %\n type(self).__name__)\n if self._enable_functions:\n action_fn = self._action_fn\n else:\n action_fn = self._action\n\n if self._validate_args:\n time_step = nest_utils.prune_extra_keys(self._time_step_spec, time_step)\n policy_state = nest_utils.prune_extra_keys(\n self._policy_state_spec, policy_state)\n nest_utils.assert_same_structure(\n time_step,\n self._time_step_spec,\n message='time_step and time_step_spec structures do not match')\n # TODO(b/158804957): Use literal comparison because in some strange cases\n # (tf.function? autograph?) the expression \"x not in (None, (), [])\" gets\n # converted to a tensor.\n if not (policy_state is None or policy_state is () or policy_state is []): # pylint: disable=literal-comparison\n nest_utils.assert_same_structure(\n policy_state,\n self._policy_state_spec,\n message=('policy_state and policy_state_spec '\n 'structures do not match'))\n\n if self._automatic_state_reset:\n policy_state = self._maybe_reset_state(time_step, policy_state)\n step = action_fn(time_step=time_step, policy_state=policy_state, seed=seed)\n\n def clip_action(action, action_spec):\n if isinstance(action_spec, tensor_spec.BoundedTensorSpec):\n return common.clip_to_spec(action, action_spec)\n return action\n\n if self._validate_args:\n nest_utils.assert_same_structure(\n step.action, self._action_spec,\n message='action and action_spec structures do not match')\n\n if self._clip:\n clipped_actions = tf.nest.map_structure(clip_action,\n step.action,\n self._action_spec)\n step = step._replace(action=clipped_actions)\n\n if self._validate_args:\n nest_utils.assert_same_structure(\n step,\n self._policy_step_spec,\n message='action output and policy_step_spec structures do not match')\n\n def compare_to_spec(value, spec):\n return value.dtype.is_compatible_with(spec.dtype)\n\n compatibility = [\n compare_to_spec(v, s) for (v, s)\n in zip(tf.nest.flatten(step.action),\n tf.nest.flatten(self.action_spec))]\n\n if not all(compatibility):\n get_dtype = lambda x: x.dtype\n action_dtypes = tf.nest.map_structure(get_dtype, step.action)\n spec_dtypes = tf.nest.map_structure(get_dtype, self.action_spec)\n\n raise TypeError('Policy produced an action with a dtype that doesn\\'t '\n 'match its action_spec. Got action:\\n %s\\n with '\n 'action_spec:\\n %s' % (action_dtypes, spec_dtypes))\n\n return step\n\n def distribution(\n self, time_step: ts.TimeStep, policy_state: types.NestedTensor = ()\n ) -> policy_step.PolicyStep:\n \"\"\"Generates the distribution over next actions given the time_step.\n\n Args:\n time_step: A `TimeStep` tuple corresponding to `time_step_spec()`.\n policy_state: A Tensor, or a nested dict, list or tuple of Tensors\n representing the previous policy_state.\n\n Returns:\n A `PolicyStep` named tuple containing:\n\n `action`: A tf.distribution capturing the distribution of next actions.\n `state`: A policy state tensor for the next call to distribution.\n `info`: Optional side information such as action log probabilities.\n\n Raises:\n ValueError or TypeError: If `validate_args is True` and inputs or\n outputs do not match `time_step_spec`, `policy_state_spec`,\n or `policy_step_spec`.\n \"\"\"\n if self._validate_args:\n time_step = nest_utils.prune_extra_keys(self._time_step_spec, time_step)\n policy_state = nest_utils.prune_extra_keys(\n self._policy_state_spec, policy_state)\n nest_utils.assert_same_structure(\n time_step,\n self._time_step_spec,\n message='time_step and time_step_spec structures do not match')\n nest_utils.assert_same_structure(\n policy_state,\n self._policy_state_spec,\n message='policy_state and policy_state_spec structures do not match')\n if self._automatic_state_reset:\n policy_state = self._maybe_reset_state(time_step, policy_state)\n step = self._distribution(time_step=time_step, policy_state=policy_state)\n if self.emit_log_probability:\n # This here is set only for compatibility with info_spec in constructor.\n info = policy_step.set_log_probability(\n step.info,\n tf.nest.map_structure(\n lambda _: tf.constant(0., dtype=tf.float32),\n policy_step.get_log_probability(self._info_spec)))\n step = step._replace(info=info)\n if self._validate_args:\n nest_utils.assert_same_structure(\n step,\n self._policy_step_spec,\n message=('distribution output and policy_step_spec structures '\n 'do not match'))\n return step\n\n def update(self,\n policy,\n tau: float = 1.0,\n tau_non_trainable: Optional[float] = None,\n sort_variables_by_name: bool = False) -> tf.Operation:\n \"\"\"Update the current policy with another policy.\n\n This would include copying the variables from the other policy.\n\n Args:\n policy: Another policy it can update from.\n tau: A float scalar in [0, 1]. When tau is 1.0 (the default), we do a hard\n update. This is used for trainable variables.\n tau_non_trainable: A float scalar in [0, 1] for non_trainable variables.\n If None, will copy from tau.\n sort_variables_by_name: A bool, when True would sort the variables by name\n before doing the update.\n\n Returns:\n An TF op to do the update.\n \"\"\"\n if self.variables():\n return common.soft_variables_update(\n policy.variables(),\n self.variables(),\n tau=tau,\n tau_non_trainable=tau_non_trainable,\n sort_variables_by_name=sort_variables_by_name)\n else:\n return tf.no_op()\n\n @property\n def emit_log_probability(self) -> bool:\n \"\"\"Whether this policy instance emits log probabilities or not.\"\"\"\n return self._emit_log_probability\n\n @property\n def time_step_spec(self) -> ts.TimeStep:\n \"\"\"Describes the `TimeStep` tensors returned by `step()`.\n\n Returns:\n A `TimeStep` namedtuple with `TensorSpec` objects instead of Tensors,\n which describe the shape, dtype and name of each tensor returned by\n `step()`.\n \"\"\"\n return self._time_step_spec\n\n @property\n def action_spec(self) -> types.NestedTensorSpec:\n \"\"\"Describes the TensorSpecs of the Tensors expected by `step(action)`.\n\n `action` can be a single Tensor, or a nested dict, list or tuple of\n Tensors.\n\n Returns:\n An single BoundedTensorSpec, or a nested dict, list or tuple of\n `BoundedTensorSpec` objects, which describe the shape and\n dtype of each Tensor expected by `step()`.\n \"\"\"\n return self._action_spec\n\n @property\n def policy_state_spec(self) -> types.NestedTensorSpec:\n \"\"\"Describes the Tensors expected by `step(_, policy_state)`.\n\n `policy_state` can be an empty tuple, a single Tensor, or a nested dict,\n list or tuple of Tensors.\n\n Returns:\n An single TensorSpec, or a nested dict, list or tuple of\n `TensorSpec` objects, which describe the shape and\n dtype of each Tensor expected by `step(_, policy_state)`.\n \"\"\"\n return self._policy_state_spec\n\n @property\n def info_spec(self) -> types.NestedTensorSpec:\n \"\"\"Describes the Tensors emitted as info by `action` and `distribution`.\n\n `info` can be an empty tuple, a single Tensor, or a nested dict,\n list or tuple of Tensors.\n\n Returns:\n An single TensorSpec, or a nested dict, list or tuple of\n `TensorSpec` objects, which describe the shape and\n dtype of each Tensor expected by `step(_, policy_state)`.\n \"\"\"\n return self._info_spec\n\n @property\n def policy_step_spec(self) -> policy_step.PolicyStep:\n \"\"\"Describes the output of `action()`.\n\n Returns:\n A nest of TensorSpec which describe the shape and dtype of each Tensor\n emitted by `action()`.\n \"\"\"\n return self._policy_step_spec\n\n # TODO(kbanoop, ebrevdo): Should this be collect_data_spec to mirror agents?\n @property\n def trajectory_spec(self) -> trajectory.Trajectory:\n \"\"\"Describes the Tensors written when using this policy with an environment.\n\n Returns:\n A `Trajectory` containing all tensor specs associated with the\n observation_spec, action_spec, policy_state_spec, and info_spec of\n this policy.\n \"\"\"\n return self._trajectory_spec\n\n @property\n def collect_data_spec(self) -> trajectory.Trajectory:\n \"\"\"Describes the Tensors written when using this policy with an environment.\n\n Returns:\n A nest of TensorSpec which describe the shape and dtype of each Tensor\n required to train the agent which generated this policy.\n \"\"\"\n return self._trajectory_spec\n\n # Subclasses MAY optionally override _action.\n def _action(self, time_step: ts.TimeStep,\n policy_state: types.NestedTensor,\n seed: Optional[types.Seed] = None) -> policy_step.PolicyStep:\n \"\"\"Implementation of `action`.\n\n Args:\n time_step: A `TimeStep` tuple corresponding to `time_step_spec()`.\n policy_state: A Tensor, or a nested dict, list or tuple of Tensors\n representing the previous policy_state.\n seed: Seed to use if action performs sampling (optional).\n\n Returns:\n A `PolicyStep` named tuple containing:\n `action`: An action Tensor matching the `action_spec`.\n `state`: A policy state tensor to be fed into the next call to action.\n `info`: Optional side information such as action log probabilities.\n \"\"\"\n seed_stream = tfp.util.SeedStream(seed=seed, salt='tf_agents_tf_policy')\n distribution_step = self._distribution(time_step, policy_state) # pytype: disable=wrong-arg-types\n actions = tf.nest.map_structure(\n lambda d: reparameterized_sampling.sample(d, seed=seed_stream()),\n distribution_step.action)\n info = distribution_step.info\n if self.emit_log_probability:\n try:\n log_probability = tf.nest.map_structure(lambda a, d: d.log_prob(a),\n actions,\n distribution_step.action)\n info = policy_step.set_log_probability(info, log_probability)\n except:\n raise TypeError('%s does not support emitting log-probabilities.' %\n type(self).__name__)\n\n return distribution_step._replace(action=actions, info=info)\n\n ## Subclasses MUST implement these.\n def _distribution(\n self, time_step: ts.TimeStep,\n policy_state: types.NestedTensorSpec) -> policy_step.PolicyStep:\n \"\"\"Implementation of `distribution`.\n\n Args:\n time_step: A `TimeStep` tuple corresponding to `time_step_spec()`.\n policy_state: A Tensor, or a nested dict, list or tuple of Tensors\n representing the previous policy_state.\n\n Returns:\n A `PolicyStep` named tuple containing:\n `action`: A (optionally nested) of tfp.distribution.Distribution\n capturing the distribution of next actions.\n `state`: A policy state tensor for the next call to distribution.\n `info`: Optional side information such as action log probabilities.\n \"\"\"\n raise NotImplementedError()\n\n # Subclasses MAY optionally overwrite _get_initial_state.\n def _get_initial_state(self, batch_size: int) -> types.NestedTensor:\n \"\"\"Returns the initial state of the policy network.\n\n Args:\n batch_size: A constant or Tensor holding the batch size. Can be None, in\n which case the state will not have a batch dimension added.\n\n Returns:\n A nest of zero tensors matching the spec of the policy network state.\n \"\"\"\n return tensor_spec.zero_spec_nest(\n self._policy_state_spec,\n outer_dims=None if batch_size is None else [batch_size])\n"
] | [
[
"tensorflow.constant",
"tensorflow.shape",
"tensorflow.compat.dimension_value",
"tensorflow.no_op",
"tensorflow.nest.flatten",
"tensorflow.nest.map_structure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
zhangyuwangumass/General-Data-Driven-Adaptive-Learning | [
"63c4ddef36b2b7bd7078cd9b431e3502c358915a"
] | [
"trajectoryPlugin/collate.py"
] | [
"r\"\"\"\"Contains definitions of the methods used by the _DataLoaderIter workers to\ncollate samples fetched from dataset into Tensor(s).\n\nThese **needs** to be in global scope since Py2 doesn't support serializing\nstatic methods.\n\"\"\"\n\nimport torch\nimport re\nfrom torch._six import container_abcs, string_classes, int_classes\n\n_use_shared_memory = False\nr\"\"\"Whether to use shared memory in default_collate\"\"\"\n\nnp_str_obj_array_pattern = re.compile(r'[SaUO]')\n\nerror_msg_fmt = \"batch must contain tensors, numbers, dicts or lists; found {}\"\n\nnumpy_type_map = {\n 'float64': torch.DoubleTensor,\n 'float32': torch.FloatTensor,\n 'float16': torch.HalfTensor,\n 'int64': torch.LongTensor,\n 'int32': torch.IntTensor,\n 'int16': torch.ShortTensor,\n 'int8': torch.CharTensor,\n 'uint8': torch.ByteTensor,\n}\n\n\ndef default_collate(batch):\n r\"\"\"Puts each data field into a tensor with outer dimension batch size\"\"\"\n\n elem_type = type(batch[0])\n if isinstance(batch[0], torch.Tensor):\n out = None\n if _use_shared_memory:\n # If we're in a background process, concatenate directly into a\n # shared memory tensor to avoid an extra copy\n numel = sum([x.numel() for x in batch])\n storage = batch[0].storage()._new_shared(numel)\n out = batch[0].new(storage)\n return torch.stack(batch, 0, out=out)\n elif elem_type.__module__ == 'numpy' and elem_type.__name__ != 'str_' \\\n and elem_type.__name__ != 'string_':\n elem = batch[0]\n if elem_type.__name__ == 'ndarray':\n # array of string classes and object\n if np_str_obj_array_pattern.search(elem.dtype.str) is not None:\n raise TypeError(error_msg_fmt.format(elem.dtype))\n\n return default_collate([torch.from_numpy(b) for b in batch])\n if elem.shape == (): # scalars\n py_type = float if elem.dtype.name.startswith('float') else int\n return numpy_type_map[elem.dtype.name](list(map(py_type, batch)))\n elif isinstance(batch[0], float):\n return torch.tensor(batch, dtype=torch.float32)\n elif isinstance(batch[0], int_classes):\n return torch.tensor(batch)\n elif isinstance(batch[0], string_classes):\n return batch\n elif isinstance(batch[0], container_abcs.Mapping):\n return {key: default_collate([d[key] for d in batch]) for key in batch[0]}\n elif isinstance(batch[0], tuple) and hasattr(batch[0], '_fields'): # namedtuple\n return type(batch[0])(*(default_collate(samples) for samples in zip(*batch)))\n elif isinstance(batch[0], container_abcs.Sequence):\n transposed = zip(*batch)\n return [default_collate(samples) for samples in transposed]\n\n raise TypeError((error_msg_fmt.format(type(batch[0]))))"
] | [
[
"torch.stack",
"torch.from_numpy",
"torch.tensor"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
coco-robotics/rllab-curriculum | [
"f55b50224fcf5a9a5c064542eb0850a966cab223"
] | [
"curriculum/envs/maze/maze_swim/swimmer_env.py"
] | [
"from rllab.envs.base import Step\nfrom rllab.misc.overrides import overrides\nfrom rllab.envs.mujoco.mujoco_env import MujocoEnv\nimport numpy as np\nfrom rllab.core.serializable import Serializable\nfrom rllab.misc import logger\nfrom rllab.misc import autoargs\nfrom contextlib import contextmanager\n\nclass SwimmerEnv(MujocoEnv, Serializable):\n\n FILE = 'swimmer.xml'\n\n @autoargs.arg('ctrl_cost_coeff', type=float,\n help='cost coefficient for controls')\n def __init__(\n self,\n ctrl_cost_coeff=1e-2,\n *args, **kwargs):\n self.ctrl_cost_coeff = ctrl_cost_coeff\n super(SwimmerEnv, self).__init__(*args, **kwargs)\n Serializable.quick_init(self, locals())\n\n def get_current_obs(self):\n return np.concatenate([\n self.model.data.qpos.flat,\n self.model.data.qvel.flat,\n self.get_body_com(\"torso\").flat,\n ]).reshape(-1)\n\n def step(self, action):\n self.forward_dynamics(action)\n next_obs = self.get_current_obs()\n lb, ub = self.action_bounds\n scaling = (ub - lb) * 0.5\n ctrl_cost = 0.5 * self.ctrl_cost_coeff * np.sum(\n np.square(action / scaling))\n forward_reward = self.get_body_comvel(\"torso\")[0]\n reward = forward_reward - ctrl_cost\n done = False\n return Step(next_obs, reward, done)\n\n # @overrides\n # def reset_mujoco(self, init_state=None):\n # super(SwimmerEnv, self).reset_mujoco(init)\n # if init_state is not None:\n # idx = self.model.body_names.index(\"torso\")\n # self.model.data.com_subtree[idx][0] = init_state[0]\n # self.model.data.com_subtree[idx][1] = init_state[1]\n\n @overrides # ignoring the goal\n def reset(self, *args, **kwargs):\n return super(SwimmerEnv, self).reset(*args, **kwargs) # passing in keyword arguments\n\n @overrides\n def log_diagnostics(self, paths):\n if len(paths) > 0:\n progs = [\n path[\"observations\"][-1][-3] - path[\"observations\"][0][-3]\n for path in paths\n ]\n logger.record_tabular('AverageForwardProgress', np.mean(progs))\n logger.record_tabular('MaxForwardProgress', np.max(progs))\n logger.record_tabular('MinForwardProgress', np.min(progs))\n logger.record_tabular('StdForwardProgress', np.std(progs))\n else:\n logger.record_tabular('AverageForwardProgress', np.nan)\n logger.record_tabular('MaxForwardProgress', np.nan)\n logger.record_tabular('MinForwardProgress', np.nan)\n logger.record_tabular('StdForwardProgress', np.nan)\n\n @contextmanager\n def set_kill_outside(self):\n self.kill_outside = True\n try:\n yield\n finally:\n self.kill_outside = False"
] | [
[
"numpy.square",
"numpy.min",
"numpy.max",
"numpy.std",
"numpy.mean"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
stragu/pandas | [
"b8890eb33b40993da00656f16c65070c42429f0d"
] | [
"pandas/io/common.py"
] | [
"\"\"\"Common IO api utilities\"\"\"\nfrom __future__ import annotations\n\nimport bz2\nimport codecs\nfrom collections import abc\nimport dataclasses\nimport gzip\nfrom io import BufferedIOBase, BytesIO, RawIOBase, StringIO, TextIOWrapper\nimport mmap\nimport os\nfrom typing import IO, Any, AnyStr, Dict, List, Mapping, Optional, Tuple, Union, cast\nfrom urllib.parse import (\n urljoin,\n urlparse as parse_url,\n uses_netloc,\n uses_params,\n uses_relative,\n)\nimport warnings\nimport zipfile\n\nfrom pandas._typing import (\n Buffer,\n CompressionDict,\n CompressionOptions,\n FileOrBuffer,\n FilePathOrBuffer,\n StorageOptions,\n)\nfrom pandas.compat import get_lzma_file, import_lzma\nfrom pandas.compat._optional import import_optional_dependency\n\nfrom pandas.core.dtypes.common import is_file_like\n\nlzma = import_lzma()\n\n\n_VALID_URLS = set(uses_relative + uses_netloc + uses_params)\n_VALID_URLS.discard(\"\")\n\n\[email protected]\nclass IOArgs:\n \"\"\"\n Return value of io/common.py:_get_filepath_or_buffer.\n\n Note (copy&past from io/parsers):\n filepath_or_buffer can be Union[FilePathOrBuffer, s3fs.S3File, gcsfs.GCSFile]\n though mypy handling of conditional imports is difficult.\n See https://github.com/python/mypy/issues/1297\n \"\"\"\n\n filepath_or_buffer: FileOrBuffer\n encoding: str\n mode: str\n compression: CompressionDict\n should_close: bool = False\n\n\[email protected]\nclass IOHandles:\n \"\"\"\n Return value of io/common.py:get_handle\n\n Can be used as a context manager.\n\n This is used to easily close created buffers and to handle corner cases when\n TextIOWrapper is inserted.\n\n handle: The file handle to be used.\n created_handles: All file handles that are created by get_handle\n is_wrapped: Whether a TextIOWrapper needs to be detached.\n \"\"\"\n\n handle: Buffer\n compression: CompressionDict\n created_handles: List[Buffer] = dataclasses.field(default_factory=list)\n is_wrapped: bool = False\n is_mmap: bool = False\n\n def close(self) -> None:\n \"\"\"\n Close all created buffers.\n\n Note: If a TextIOWrapper was inserted, it is flushed and detached to\n avoid closing the potentially user-created buffer.\n \"\"\"\n if self.is_wrapped:\n assert isinstance(self.handle, TextIOWrapper)\n self.handle.flush()\n self.handle.detach()\n self.created_handles.remove(self.handle)\n try:\n for handle in self.created_handles:\n handle.close()\n except (OSError, ValueError):\n pass\n self.created_handles = []\n self.is_wrapped = False\n\n def __enter__(self) -> IOHandles:\n return self\n\n def __exit__(self, *args: Any) -> None:\n self.close()\n\n\ndef is_url(url) -> bool:\n \"\"\"\n Check to see if a URL has a valid protocol.\n\n Parameters\n ----------\n url : str or unicode\n\n Returns\n -------\n isurl : bool\n If `url` has a valid protocol return True otherwise False.\n \"\"\"\n if not isinstance(url, str):\n return False\n return parse_url(url).scheme in _VALID_URLS\n\n\ndef _expand_user(filepath_or_buffer: FileOrBuffer[AnyStr]) -> FileOrBuffer[AnyStr]:\n \"\"\"\n Return the argument with an initial component of ~ or ~user\n replaced by that user's home directory.\n\n Parameters\n ----------\n filepath_or_buffer : object to be converted if possible\n\n Returns\n -------\n expanded_filepath_or_buffer : an expanded filepath or the\n input if not expandable\n \"\"\"\n if isinstance(filepath_or_buffer, str):\n return os.path.expanduser(filepath_or_buffer)\n return filepath_or_buffer\n\n\ndef validate_header_arg(header) -> None:\n if isinstance(header, bool):\n raise TypeError(\n \"Passing a bool to header is invalid. Use header=None for no header or \"\n \"header=int or list-like of ints to specify \"\n \"the row(s) making up the column names\"\n )\n\n\ndef stringify_path(\n filepath_or_buffer: FilePathOrBuffer[AnyStr],\n convert_file_like: bool = False,\n) -> FileOrBuffer[AnyStr]:\n \"\"\"\n Attempt to convert a path-like object to a string.\n\n Parameters\n ----------\n filepath_or_buffer : object to be converted\n\n Returns\n -------\n str_filepath_or_buffer : maybe a string version of the object\n\n Notes\n -----\n Objects supporting the fspath protocol (python 3.6+) are coerced\n according to its __fspath__ method.\n\n Any other object is passed through unchanged, which includes bytes,\n strings, buffers, or anything else that's not even path-like.\n \"\"\"\n if not convert_file_like and is_file_like(filepath_or_buffer):\n # GH 38125: some fsspec objects implement os.PathLike but have already opened a\n # file. This prevents opening the file a second time. infer_compression calls\n # this function with convert_file_like=True to infer the compression.\n return cast(FileOrBuffer[AnyStr], filepath_or_buffer)\n\n if isinstance(filepath_or_buffer, os.PathLike):\n filepath_or_buffer = filepath_or_buffer.__fspath__()\n return _expand_user(filepath_or_buffer)\n\n\ndef urlopen(*args, **kwargs):\n \"\"\"\n Lazy-import wrapper for stdlib urlopen, as that imports a big chunk of\n the stdlib.\n \"\"\"\n import urllib.request\n\n return urllib.request.urlopen(*args, **kwargs)\n\n\ndef is_fsspec_url(url: FilePathOrBuffer) -> bool:\n \"\"\"\n Returns true if the given URL looks like\n something fsspec can handle\n \"\"\"\n return (\n isinstance(url, str)\n and \"://\" in url\n and not url.startswith((\"http://\", \"https://\"))\n )\n\n\ndef _get_filepath_or_buffer(\n filepath_or_buffer: FilePathOrBuffer,\n encoding: str = \"utf-8\",\n compression: CompressionOptions = None,\n mode: str = \"r\",\n storage_options: StorageOptions = None,\n) -> IOArgs:\n \"\"\"\n If the filepath_or_buffer is a url, translate and return the buffer.\n Otherwise passthrough.\n\n Parameters\n ----------\n filepath_or_buffer : a url, filepath (str, py.path.local or pathlib.Path),\n or buffer\n compression : {{'gzip', 'bz2', 'zip', 'xz', None}}, optional\n encoding : the encoding to use to decode bytes, default is 'utf-8'\n mode : str, optional\n\n storage_options : dict, optional\n Extra options that make sense for a particular storage connection, e.g.\n host, port, username, password, etc., if using a URL that will\n be parsed by ``fsspec``, e.g., starting \"s3://\", \"gcs://\". An error\n will be raised if providing this argument with a local path or\n a file-like buffer. See the fsspec and backend storage implementation\n docs for the set of allowed keys and values\n\n .. versionadded:: 1.2.0\n\n ..versionchange:: 1.2.0\n\n Returns the dataclass IOArgs.\n \"\"\"\n filepath_or_buffer = stringify_path(filepath_or_buffer)\n\n # handle compression dict\n compression_method, compression = get_compression_method(compression)\n compression_method = infer_compression(filepath_or_buffer, compression_method)\n\n # GH21227 internal compression is not used for non-binary handles.\n if compression_method and hasattr(filepath_or_buffer, \"write\") and \"b\" not in mode:\n warnings.warn(\n \"compression has no effect when passing a non-binary object as input.\",\n RuntimeWarning,\n stacklevel=2,\n )\n compression_method = None\n\n compression = dict(compression, method=compression_method)\n\n # uniform encoding names\n if encoding is not None:\n encoding = encoding.replace(\"_\", \"-\").lower()\n\n # bz2 and xz do not write the byte order mark for utf-16 and utf-32\n # print a warning when writing such files\n if (\n \"w\" in mode\n and compression_method in [\"bz2\", \"xz\"]\n and encoding in [\"utf-16\", \"utf-32\"]\n ):\n warnings.warn(\n f\"{compression} will not write the byte order mark for {encoding}\",\n UnicodeWarning,\n )\n\n # Use binary mode when converting path-like objects to file-like objects (fsspec)\n # except when text mode is explicitly requested. The original mode is returned if\n # fsspec is not used.\n fsspec_mode = mode\n if \"t\" not in fsspec_mode and \"b\" not in fsspec_mode:\n fsspec_mode += \"b\"\n\n if isinstance(filepath_or_buffer, str) and is_url(filepath_or_buffer):\n # TODO: fsspec can also handle HTTP via requests, but leaving this\n # unchanged. using fsspec appears to break the ability to infer if the\n # server responded with gzipped data\n storage_options = storage_options or {}\n\n # waiting until now for importing to match intended lazy logic of\n # urlopen function defined elsewhere in this module\n import urllib.request\n\n # assuming storage_options is to be interpreted as headers\n req_info = urllib.request.Request(filepath_or_buffer, headers=storage_options)\n with urlopen(req_info) as req:\n content_encoding = req.headers.get(\"Content-Encoding\", None)\n if content_encoding == \"gzip\":\n # Override compression based on Content-Encoding header\n compression = {\"method\": \"gzip\"}\n reader = BytesIO(req.read())\n return IOArgs(\n filepath_or_buffer=reader,\n encoding=encoding,\n compression=compression,\n should_close=True,\n mode=fsspec_mode,\n )\n\n if is_fsspec_url(filepath_or_buffer):\n assert isinstance(\n filepath_or_buffer, str\n ) # just to appease mypy for this branch\n # two special-case s3-like protocols; these have special meaning in Hadoop,\n # but are equivalent to just \"s3\" from fsspec's point of view\n # cc #11071\n if filepath_or_buffer.startswith(\"s3a://\"):\n filepath_or_buffer = filepath_or_buffer.replace(\"s3a://\", \"s3://\")\n if filepath_or_buffer.startswith(\"s3n://\"):\n filepath_or_buffer = filepath_or_buffer.replace(\"s3n://\", \"s3://\")\n fsspec = import_optional_dependency(\"fsspec\")\n\n # If botocore is installed we fallback to reading with anon=True\n # to allow reads from public buckets\n err_types_to_retry_with_anon: List[Any] = []\n try:\n import_optional_dependency(\"botocore\")\n from botocore.exceptions import ClientError, NoCredentialsError\n\n err_types_to_retry_with_anon = [\n ClientError,\n NoCredentialsError,\n PermissionError,\n ]\n except ImportError:\n pass\n\n try:\n file_obj = fsspec.open(\n filepath_or_buffer, mode=fsspec_mode, **(storage_options or {})\n ).open()\n # GH 34626 Reads from Public Buckets without Credentials needs anon=True\n except tuple(err_types_to_retry_with_anon):\n if storage_options is None:\n storage_options = {\"anon\": True}\n else:\n # don't mutate user input.\n storage_options = dict(storage_options)\n storage_options[\"anon\"] = True\n file_obj = fsspec.open(\n filepath_or_buffer, mode=fsspec_mode, **(storage_options or {})\n ).open()\n\n return IOArgs(\n filepath_or_buffer=file_obj,\n encoding=encoding,\n compression=compression,\n should_close=True,\n mode=fsspec_mode,\n )\n elif storage_options:\n raise ValueError(\n \"storage_options passed with file object or non-fsspec file path\"\n )\n\n if isinstance(filepath_or_buffer, (str, bytes, mmap.mmap)):\n return IOArgs(\n filepath_or_buffer=_expand_user(filepath_or_buffer),\n encoding=encoding,\n compression=compression,\n should_close=False,\n mode=mode,\n )\n\n if not is_file_like(filepath_or_buffer):\n msg = f\"Invalid file path or buffer object type: {type(filepath_or_buffer)}\"\n raise ValueError(msg)\n\n return IOArgs(\n filepath_or_buffer=filepath_or_buffer,\n encoding=encoding,\n compression=compression,\n should_close=False,\n mode=mode,\n )\n\n\ndef file_path_to_url(path: str) -> str:\n \"\"\"\n converts an absolute native path to a FILE URL.\n\n Parameters\n ----------\n path : a path in native format\n\n Returns\n -------\n a valid FILE URL\n \"\"\"\n # lazify expensive import (~30ms)\n from urllib.request import pathname2url\n\n return urljoin(\"file:\", pathname2url(path))\n\n\n_compression_to_extension = {\"gzip\": \".gz\", \"bz2\": \".bz2\", \"zip\": \".zip\", \"xz\": \".xz\"}\n\n\ndef get_compression_method(\n compression: CompressionOptions,\n) -> Tuple[Optional[str], CompressionDict]:\n \"\"\"\n Simplifies a compression argument to a compression method string and\n a mapping containing additional arguments.\n\n Parameters\n ----------\n compression : str or mapping\n If string, specifies the compression method. If mapping, value at key\n 'method' specifies compression method.\n\n Returns\n -------\n tuple of ({compression method}, Optional[str]\n {compression arguments}, Dict[str, Any])\n\n Raises\n ------\n ValueError on mapping missing 'method' key\n \"\"\"\n compression_method: Optional[str]\n if isinstance(compression, Mapping):\n compression_args = dict(compression)\n try:\n compression_method = compression_args.pop(\"method\")\n except KeyError as err:\n raise ValueError(\"If mapping, compression must have key 'method'\") from err\n else:\n compression_args = {}\n compression_method = compression\n return compression_method, compression_args\n\n\ndef infer_compression(\n filepath_or_buffer: FilePathOrBuffer, compression: Optional[str]\n) -> Optional[str]:\n \"\"\"\n Get the compression method for filepath_or_buffer. If compression='infer',\n the inferred compression method is returned. Otherwise, the input\n compression method is returned unchanged, unless it's invalid, in which\n case an error is raised.\n\n Parameters\n ----------\n filepath_or_buffer : str or file handle\n File path or object.\n compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}\n If 'infer' and `filepath_or_buffer` is path-like, then detect\n compression from the following extensions: '.gz', '.bz2', '.zip',\n or '.xz' (otherwise no compression).\n\n Returns\n -------\n string or None\n\n Raises\n ------\n ValueError on invalid compression specified.\n \"\"\"\n if compression is None:\n return None\n\n # Infer compression\n if compression == \"infer\":\n # Convert all path types (e.g. pathlib.Path) to strings\n filepath_or_buffer = stringify_path(filepath_or_buffer, convert_file_like=True)\n if not isinstance(filepath_or_buffer, str):\n # Cannot infer compression of a buffer, assume no compression\n return None\n\n # Infer compression from the filename/URL extension\n for compression, extension in _compression_to_extension.items():\n if filepath_or_buffer.lower().endswith(extension):\n return compression\n return None\n\n # Compression has been specified. Check that it's valid\n if compression in _compression_to_extension:\n return compression\n\n # https://github.com/python/mypy/issues/5492\n # Unsupported operand types for + (\"List[Optional[str]]\" and \"List[str]\")\n valid = [\"infer\", None] + sorted(\n _compression_to_extension\n ) # type: ignore[operator]\n msg = (\n f\"Unrecognized compression type: {compression}\\n\"\n f\"Valid compression types are {valid}\"\n )\n raise ValueError(msg)\n\n\ndef get_handle(\n path_or_buf: FilePathOrBuffer,\n mode: str,\n encoding: Optional[str] = None,\n compression: CompressionOptions = None,\n memory_map: bool = False,\n is_text: bool = True,\n errors: Optional[str] = None,\n storage_options: StorageOptions = None,\n) -> IOHandles:\n \"\"\"\n Get file handle for given path/buffer and mode.\n\n Parameters\n ----------\n path_or_buf : str or file handle\n File path or object.\n mode : str\n Mode to open path_or_buf with.\n encoding : str or None\n Encoding to use.\n compression : str or dict, default None\n If string, specifies compression mode. If dict, value at key 'method'\n specifies compression mode. Compression mode must be one of {'infer',\n 'gzip', 'bz2', 'zip', 'xz', None}. If compression mode is 'infer'\n and `filepath_or_buffer` is path-like, then detect compression from\n the following extensions: '.gz', '.bz2', '.zip', or '.xz' (otherwise\n no compression). If dict and compression mode is one of\n {'zip', 'gzip', 'bz2'}, or inferred as one of the above,\n other entries passed as additional compression options.\n\n .. versionchanged:: 1.0.0\n\n May now be a dict with key 'method' as compression mode\n and other keys as compression options if compression\n mode is 'zip'.\n\n .. versionchanged:: 1.1.0\n\n Passing compression options as keys in dict is now\n supported for compression modes 'gzip' and 'bz2' as well as 'zip'.\n\n memory_map : boolean, default False\n See parsers._parser_params for more information.\n is_text : boolean, default True\n Whether the type of the content passed to the file/buffer is string or\n bytes. This is not the same as `\"b\" not in mode`. If a string content is\n passed to a binary file/buffer, a wrapper is inserted.\n errors : str, default 'strict'\n Specifies how encoding and decoding errors are to be handled.\n See the errors argument for :func:`open` for a full list\n of options.\n storage_options: StorageOptions = None\n Passed to _get_filepath_or_buffer\n\n .. versionchanged:: 1.2.0\n\n Returns the dataclass IOHandles\n \"\"\"\n # Windows does not default to utf-8. Set to utf-8 for a consistent behavior\n encoding_passed, encoding = encoding, encoding or \"utf-8\"\n\n # read_csv does not know whether the buffer is opened in binary/text mode\n if _is_binary_mode(path_or_buf, mode) and \"b\" not in mode:\n mode += \"b\"\n\n # open URLs\n ioargs = _get_filepath_or_buffer(\n path_or_buf,\n encoding=encoding,\n compression=compression,\n mode=mode,\n storage_options=storage_options,\n )\n\n handle = ioargs.filepath_or_buffer\n handles: List[Buffer]\n\n # memory mapping needs to be the first step\n handle, memory_map, handles = _maybe_memory_map(\n handle, memory_map, ioargs.encoding, ioargs.mode, errors\n )\n\n is_path = isinstance(handle, str)\n compression_args = dict(ioargs.compression)\n compression = compression_args.pop(\"method\")\n\n if compression:\n # compression libraries do not like an explicit text-mode\n ioargs.mode = ioargs.mode.replace(\"t\", \"\")\n\n # GZ Compression\n if compression == \"gzip\":\n if is_path:\n assert isinstance(handle, str)\n handle = gzip.GzipFile(\n filename=handle,\n mode=ioargs.mode,\n **compression_args,\n )\n else:\n handle = gzip.GzipFile(\n fileobj=handle, # type: ignore[arg-type]\n mode=ioargs.mode,\n **compression_args,\n )\n\n # BZ Compression\n elif compression == \"bz2\":\n handle = bz2.BZ2File(\n handle, # type: ignore[arg-type]\n mode=ioargs.mode,\n **compression_args,\n )\n\n # ZIP Compression\n elif compression == \"zip\":\n handle = _BytesZipFile(handle, ioargs.mode, **compression_args)\n if handle.mode == \"r\":\n handles.append(handle)\n zip_names = handle.namelist()\n if len(zip_names) == 1:\n handle = handle.open(zip_names.pop())\n elif len(zip_names) == 0:\n raise ValueError(f\"Zero files found in ZIP file {path_or_buf}\")\n else:\n raise ValueError(\n \"Multiple files found in ZIP file. \"\n f\"Only one file per ZIP: {zip_names}\"\n )\n\n # XZ Compression\n elif compression == \"xz\":\n handle = get_lzma_file(lzma)(handle, ioargs.mode)\n\n # Unrecognized Compression\n else:\n msg = f\"Unrecognized compression type: {compression}\"\n raise ValueError(msg)\n\n assert not isinstance(handle, str)\n handles.append(handle)\n\n elif isinstance(handle, str):\n # Check whether the filename is to be opened in binary mode.\n # Binary mode does not support 'encoding' and 'newline'.\n if ioargs.encoding and \"b\" not in ioargs.mode:\n if errors is None and encoding_passed is None:\n # ignore errors when no encoding is specified\n errors = \"replace\"\n # Encoding\n handle = open(\n handle,\n ioargs.mode,\n encoding=ioargs.encoding,\n errors=errors,\n newline=\"\",\n )\n else:\n # Binary mode\n handle = open(handle, ioargs.mode)\n handles.append(handle)\n\n # Convert BytesIO or file objects passed with an encoding\n is_wrapped = False\n if is_text and (compression or _is_binary_mode(handle, ioargs.mode)):\n handle = TextIOWrapper(\n handle, # type: ignore[arg-type]\n encoding=ioargs.encoding,\n errors=errors,\n newline=\"\",\n )\n handles.append(handle)\n # only marked as wrapped when the caller provided a handle\n is_wrapped = not (\n isinstance(ioargs.filepath_or_buffer, str) or ioargs.should_close\n )\n\n handles.reverse() # close the most recently added buffer first\n if ioargs.should_close:\n assert not isinstance(ioargs.filepath_or_buffer, str)\n handles.append(ioargs.filepath_or_buffer)\n\n assert not isinstance(handle, str)\n return IOHandles(\n handle=handle,\n created_handles=handles,\n is_wrapped=is_wrapped,\n is_mmap=memory_map,\n compression=ioargs.compression,\n )\n\n\n# error: Definition of \"__exit__\" in base class \"ZipFile\" is incompatible with\n# definition in base class \"BytesIO\" [misc]\n# error: Definition of \"__enter__\" in base class \"ZipFile\" is incompatible with\n# definition in base class \"BytesIO\" [misc]\n# error: Definition of \"__enter__\" in base class \"ZipFile\" is incompatible with\n# definition in base class \"BinaryIO\" [misc]\n# error: Definition of \"__enter__\" in base class \"ZipFile\" is incompatible with\n# definition in base class \"IO\" [misc]\n# error: Definition of \"read\" in base class \"ZipFile\" is incompatible with\n# definition in base class \"BytesIO\" [misc]\n# error: Definition of \"read\" in base class \"ZipFile\" is incompatible with\n# definition in base class \"IO\" [misc]\nclass _BytesZipFile(zipfile.ZipFile, BytesIO): # type: ignore[misc]\n \"\"\"\n Wrapper for standard library class ZipFile and allow the returned file-like\n handle to accept byte strings via `write` method.\n\n BytesIO provides attributes of file-like object and ZipFile.writestr writes\n bytes strings into a member of the archive.\n \"\"\"\n\n # GH 17778\n def __init__(\n self,\n file: FilePathOrBuffer,\n mode: str,\n archive_name: Optional[str] = None,\n **kwargs,\n ):\n mode = mode.replace(\"b\", \"\")\n self.archive_name = archive_name\n self.multiple_write_buffer: Optional[Union[StringIO, BytesIO]] = None\n\n kwargs_zip: Dict[str, Any] = {\"compression\": zipfile.ZIP_DEFLATED}\n kwargs_zip.update(kwargs)\n\n super().__init__(file, mode, **kwargs_zip) # type: ignore[arg-type]\n\n def write(self, data):\n # buffer multiple write calls, write on flush\n if self.multiple_write_buffer is None:\n self.multiple_write_buffer = (\n BytesIO() if isinstance(data, bytes) else StringIO()\n )\n self.multiple_write_buffer.write(data)\n\n def flush(self) -> None:\n # write to actual handle and close write buffer\n if self.multiple_write_buffer is None or self.multiple_write_buffer.closed:\n return\n\n # ZipFile needs a non-empty string\n archive_name = self.archive_name or self.filename or \"zip\"\n with self.multiple_write_buffer:\n super().writestr(archive_name, self.multiple_write_buffer.getvalue())\n\n def close(self):\n self.flush()\n super().close()\n\n @property\n def closed(self):\n return self.fp is None\n\n\nclass _MMapWrapper(abc.Iterator):\n \"\"\"\n Wrapper for the Python's mmap class so that it can be properly read in\n by Python's csv.reader class.\n\n Parameters\n ----------\n f : file object\n File object to be mapped onto memory. Must support the 'fileno'\n method or have an equivalent attribute\n\n \"\"\"\n\n def __init__(self, f: IO):\n self.attributes = {}\n for attribute in (\"seekable\", \"readable\", \"writeable\"):\n if not hasattr(f, attribute):\n continue\n self.attributes[attribute] = getattr(f, attribute)()\n self.mmap = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)\n\n def __getattr__(self, name: str):\n if name in self.attributes:\n return lambda: self.attributes[name]\n return getattr(self.mmap, name)\n\n def __iter__(self) -> _MMapWrapper:\n return self\n\n def __next__(self) -> str:\n newbytes = self.mmap.readline()\n\n # readline returns bytes, not str, but Python's CSV reader\n # expects str, so convert the output to str before continuing\n newline = newbytes.decode(\"utf-8\")\n\n # mmap doesn't raise if reading past the allocated\n # data but instead returns an empty string, so raise\n # if that is returned\n if newline == \"\":\n raise StopIteration\n return newline\n\n\ndef _maybe_memory_map(\n handle: FileOrBuffer,\n memory_map: bool,\n encoding: str,\n mode: str,\n errors: Optional[str],\n) -> Tuple[FileOrBuffer, bool, List[Buffer]]:\n \"\"\"Try to memory map file/buffer.\"\"\"\n handles: List[Buffer] = []\n memory_map &= hasattr(handle, \"fileno\") or isinstance(handle, str)\n if not memory_map:\n return handle, memory_map, handles\n\n # need to open the file first\n if isinstance(handle, str):\n if encoding and \"b\" not in mode:\n # Encoding\n handle = open(handle, mode, encoding=encoding, errors=errors, newline=\"\")\n else:\n # Binary mode\n handle = open(handle, mode)\n handles.append(handle)\n\n try:\n wrapped = cast(mmap.mmap, _MMapWrapper(handle)) # type: ignore[arg-type]\n handle.close()\n handles.remove(handle)\n handles.append(wrapped)\n handle = wrapped\n except Exception:\n # we catch any errors that may have occurred\n # because that is consistent with the lower-level\n # functionality of the C engine (pd.read_csv), so\n # leave the file handler as is then\n memory_map = False\n\n return handle, memory_map, handles\n\n\ndef file_exists(filepath_or_buffer: FilePathOrBuffer) -> bool:\n \"\"\"Test whether file exists.\"\"\"\n exists = False\n filepath_or_buffer = stringify_path(filepath_or_buffer)\n if not isinstance(filepath_or_buffer, str):\n return exists\n try:\n exists = os.path.exists(filepath_or_buffer)\n # gh-5874: if the filepath is too long will raise here\n except (TypeError, ValueError):\n pass\n return exists\n\n\ndef _is_binary_mode(handle: FilePathOrBuffer, mode: str) -> bool:\n \"\"\"Whether the handle is opened in binary mode\"\"\"\n # classes that expect string but have 'b' in mode\n text_classes = (codecs.StreamReaderWriter,)\n if isinstance(handle, text_classes):\n return False\n\n # classes that expect bytes\n binary_classes = (BufferedIOBase, RawIOBase)\n\n return isinstance(handle, binary_classes) or \"b\" in getattr(handle, \"mode\", mode)\n"
] | [
[
"pandas.compat.get_lzma_file",
"pandas.core.dtypes.common.is_file_like",
"pandas.compat.import_lzma",
"pandas.compat._optional.import_optional_dependency"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ravihammond/hanabi-convention-adaptation | [
"5dafa91742de8e8d5810e8213e0e2771818b2f54",
"5dafa91742de8e8d5810e8213e0e2771818b2f54"
] | [
"pyhanabi/common_utils/helper.py",
"pyhanabi/supervised_model.py"
] | [
"# Copyright (c) Facebook, Inc. and its affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n#\nimport os\nimport random\n\nimport numpy as np\nimport torch\nfrom torch import nn\nfrom typing import Dict\n\n\ndef to_device(data, device):\n if isinstance(data, torch.Tensor):\n return data.to(device)\n elif isinstance(data, dict):\n return {k: to_device(v, device) for k, v in data.items()}\n elif isinstance(data, list):\n return [to_device(v, device) for v in data]\n\n\ndef get_all_files(root, file_extension, contain=None):\n files = []\n for folder, _, fs in os.walk(root):\n for f in fs:\n if file_extension is not None:\n if f.endswith(file_extension):\n if contain is None or contain in os.path.join(folder, f):\n files.append(os.path.join(folder, f))\n else:\n if contain in f:\n files.append(os.path.join(folder, f))\n return files\n\n\ndef flatten(s):\n if s == []:\n return s\n if isinstance(s[0], list):\n return flatten(s[0]) + flatten(s[1:])\n return s[:1] + flatten(s[1:])\n\n\ndef moving_average(data, period):\n # padding\n left_pad = [data[0] for _ in range(period // 2)]\n right_pad = data[-period // 2 + 1 :]\n data = left_pad + data + right_pad\n weights = np.ones(period) / period\n return np.convolve(data, weights, mode=\"valid\")\n\n\ndef mem2str(num_bytes):\n assert num_bytes >= 0\n if num_bytes >= 2 ** 30: # GB\n val = float(num_bytes) / (2 ** 30)\n result = \"%.3f GB\" % val\n elif num_bytes >= 2 ** 20: # MB\n val = float(num_bytes) / (2 ** 20)\n result = \"%.3f MB\" % val\n elif num_bytes >= 2 ** 10: # KB\n val = float(num_bytes) / (2 ** 10)\n result = \"%.3f KB\" % val\n else:\n result = \"%d bytes\" % num_bytes\n return result\n\n\ndef sec2str(seconds):\n seconds = int(seconds)\n hour = seconds // 3600\n seconds = seconds % (24 * 3600)\n seconds %= 3600\n minutes = seconds // 60\n seconds %= 60\n return \"%dH %02dM %02dS\" % (hour, minutes, seconds)\n\n\ndef num2str(n):\n if n < 1e3:\n s = str(n)\n unit = \"\"\n elif n < 1e6:\n n /= 1e3\n s = \"%.3f\" % n\n unit = \"K\"\n else:\n n /= 1e6\n s = \"%.3f\" % n\n unit = \"M\"\n\n s = s.rstrip(\"0\").rstrip(\".\")\n return s + unit\n\n\ndef get_mem_usage():\n import psutil\n\n mem = psutil.virtual_memory()\n result = \"\"\n result += \"available: %s, \" % (mem2str(mem.available))\n result += \"used: %s, \" % (mem2str(mem.used))\n result += \"free: %s\" % (mem2str(mem.free))\n return result\n\n\ndef flatten_first2dim(batch):\n if isinstance(batch, torch.Tensor):\n size = batch.size()[2:]\n batch = batch.view(-1, *size)\n return batch\n elif isinstance(batch, dict):\n return {key: flatten_first2dim(batch[key]) for key in batch}\n else:\n assert False, \"unsupported type: %s\" % type(batch)\n\n\ndef _tensor_slice(t, dim, b, e):\n if dim == 0:\n return t[b:e]\n elif dim == 1:\n return t[:, b:e]\n elif dim == 2:\n return t[:, :, b:e]\n else:\n raise ValueError(\"unsupported %d in tensor_slice\" % dim)\n\n\ndef tensor_slice(t, dim, b, e):\n if isinstance(t, dict):\n return {key: tensor_slice(t[key], dim, b, e) for key in t}\n elif isinstance(t, torch.Tensor):\n return _tensor_slice(t, dim, b, e).contiguous()\n else:\n assert False, \"Error: unsupported type: %s\" % (type(t))\n\n\ndef tensor_index(t, dim, i):\n if isinstance(t, dict):\n return {key: tensor_index(t[key], dim, i) for key in t}\n elif isinstance(t, torch.Tensor):\n return _tensor_slice(t, dim, i, i + 1).squeeze(dim).contiguous()\n else:\n assert False, \"Error: unsupported type: %s\" % (type(t))\n\n\ndef one_hot(x, n):\n assert x.dim() == 2 and x.size(1) == 1\n one_hot_x = torch.zeros(x.size(0), n, device=x.device)\n one_hot_x.scatter_(1, x, 1)\n return one_hot_x\n\n\ndef set_all_seeds(rand_seed):\n random.seed(rand_seed)\n np.random.seed(rand_seed + 1)\n torch.manual_seed(rand_seed + 2)\n torch.cuda.manual_seed(rand_seed + 3)\n\n\ndef weights_init(m):\n \"\"\"custom weights initialization\"\"\"\n if isinstance(m, nn.Linear) or isinstance(m, nn.Conv2d):\n # nn.init.kaiming_normal(m.weight.data)\n nn.init.orthogonal_(m.weight.data)\n else:\n print(\"%s is not custom-initialized.\" % m.__class__)\n\n\ndef init_net(net, net_file):\n if net_file:\n net.load_state_dict(torch.load(net_file))\n else:\n net.apply(weights_init)\n\n\ndef count_output_size(input_shape, model):\n fake_input = torch.FloatTensor(*input_shape)\n output_size = model.forward(fake_input).view(-1).size()[0]\n return output_size\n",
"# Copyright (c) Facebook, Inc. and its affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n#\nimport torch\nimport torch.nn as nn\nfrom typing import Dict, Optional, Tuple\n\n\nclass LSTMNet(torch.jit.ScriptModule):\n def __init__(self, device, priv_in_dim, hid_dim, out_dim, num_lstm_layer, dropout):\n super().__init__()\n self.priv_in_dim = priv_in_dim\n self.hid_dim = hid_dim\n self.out_dim = out_dim\n\n self.num_ff_layer = 1\n self.num_lstm_layer = num_lstm_layer\n self.dropout = nn.Dropout(dropout)\n\n self.net = nn.Sequential(\n nn.Linear(self.priv_in_dim, self.hid_dim),\n nn.ReLU(),\n )\n self.lstm = nn.LSTM(\n self.hid_dim,\n self.hid_dim,\n num_layers=self.num_lstm_layer,\n ).to(device)\n self.lstm.flatten_parameters()\n self.out_layer = nn.Linear(self.hid_dim, self.out_dim)\n\n @torch.jit.script_method\n def forward(\n self,\n priv_s: torch.Tensor,\n publ_s: torch.Tensor,\n hid: Optional[Dict[str, torch.Tensor]] = None,\n ) -> Tuple[torch.Tensor, Dict[str, torch.Tensor]]:\n x = self.net(priv_s)\n\n if hid is not None:\n o, (h, c) = self.lstm(x, (hid[\"h0\"], hid[\"c0\"]))\n new_hid = {\"h0\": h, \"c0\": c}\n else:\n o, _ = self.lstm(x)\n new_hid = {}\n\n logit = self.out_layer(self.dropout(o))\n return logit, new_hid\n\n\nclass PublicLSTMNet(torch.jit.ScriptModule):\n def __init__(\n self,\n device,\n priv_in_dim,\n publ_in_dim,\n hid_dim,\n out_dim,\n num_lstm_layer,\n dropout,\n ):\n super().__init__()\n self.priv_in_dim = priv_in_dim\n self.publ_in_dim = publ_in_dim\n\n self.hid_dim = hid_dim\n self.out_dim = out_dim\n self.num_ff_layer = 1\n self.num_lstm_layer = num_lstm_layer\n self.dropout = nn.Dropout(dropout)\n\n self.priv_net = nn.Sequential(\n nn.Linear(self.priv_in_dim, self.hid_dim),\n nn.ReLU(),\n nn.Linear(self.hid_dim, self.hid_dim),\n nn.ReLU(),\n nn.Linear(self.hid_dim, self.hid_dim),\n nn.ReLU(),\n )\n\n ff_layers = [nn.Linear(self.publ_in_dim, self.hid_dim), nn.ReLU()]\n for i in range(1, self.num_ff_layer):\n ff_layers.append(nn.Linear(self.hid_dim, self.hid_dim))\n ff_layers.append(nn.ReLU())\n self.publ_net = nn.Sequential(*ff_layers)\n\n self.lstm = nn.LSTM(\n self.hid_dim,\n self.hid_dim,\n num_layers=self.num_lstm_layer,\n ).to(device)\n self.lstm.flatten_parameters()\n\n self.out_layer = nn.Linear(self.hid_dim, self.out_dim)\n\n @torch.jit.script_method\n def forward(\n self,\n priv_s: torch.Tensor,\n publ_s: torch.Tensor,\n hid: Optional[Dict[str, torch.Tensor]] = None,\n ) -> Tuple[torch.Tensor, Dict[str, torch.Tensor]]:\n x = self.publ_net(publ_s)\n\n if hid is not None:\n publ_o, (h, c) = self.lstm(x, (hid[\"h0\"], hid[\"c0\"]))\n new_hid = {\"h0\": h, \"c0\": c}\n else:\n publ_o, _ = self.lstm(x)\n new_hid = {}\n priv_o = self.priv_net(priv_s)\n\n o = priv_o * publ_o\n logit = self.out_layer(self.dropout(o))\n return logit, new_hid\n\n\nclass SupervisedAgent(torch.jit.ScriptModule):\n __constants__ = [\"hid_dim\", \"out_dim\", \"num_lstm_layer\"]\n\n def __init__(\n self,\n device,\n priv_in_dim,\n publ_in_dim,\n hid_dim,\n out_dim,\n num_lstm_layer,\n net,\n dropout,\n ):\n super().__init__()\n assert net in [\"lstm\", \"publ-lstm\"]\n if net == \"lstm\":\n self.net = LSTMNet(\n device,\n priv_in_dim,\n hid_dim,\n out_dim,\n num_lstm_layer,\n dropout,\n )\n elif net == \"publ-lstm\":\n self.net = PublicLSTMNet(\n device,\n priv_in_dim,\n publ_in_dim,\n hid_dim,\n out_dim,\n num_lstm_layer,\n dropout,\n )\n\n self.net_type = net\n self.priv_in_dim = priv_in_dim\n self.publ_in_dim = publ_in_dim\n self.hid_dim = hid_dim\n self.out_dim = out_dim\n self.num_lstm_layer = num_lstm_layer\n self.dropout = dropout\n self.to(device)\n\n def clone(self, device):\n cloned = SupervisedAgent(\n device,\n self.priv_in_dim,\n self.publ_in_dim,\n self.hid_dim,\n self.out_dim,\n self.num_lstm_layer,\n self.net_type,\n self.dropout,\n )\n cloned.load_state_dict(self.state_dict())\n cloned.train(self.training)\n return cloned\n\n @torch.jit.script_method\n def forward(\n self,\n priv_s: torch.Tensor,\n publ_s: torch.Tensor,\n hid: Optional[Dict[str, torch.Tensor]] = None,\n ) -> Tuple[torch.Tensor, Dict[str, torch.Tensor]]:\n return self.net(priv_s, publ_s, hid)\n\n def greedy_act(\n self,\n priv_s: torch.Tensor, # [batchsize, dim]\n publ_s: torch.Tensor, # [batchsize, dim]\n legal_move: torch.Tensor, # batchsize, dim]\n hid: Dict[str, torch.Tensor], # [num_layer, batchsize, dim]\n ) -> Tuple[torch.Tensor, Dict[str, torch.Tensor]]:\n \"\"\"greedy act for 1 timestep\"\"\"\n priv_s = priv_s.unsqueeze(0) # add time dim\n publ_s = publ_s.unsqueeze(0)\n logit, new_hid = self.forward(priv_s, publ_s, hid)\n logit = logit.squeeze(0) # remove time dim\n assert logit.size() == legal_move.size()\n legal_logit = logit - (1 - legal_move) * 1e6\n action = legal_logit.max(1)[1]\n return action, new_hid\n\n @torch.jit.script_method\n def act(self, obs: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:\n bsize, dim = obs[\"priv_s\"].size()\n\n priv_s = obs[\"priv_s\"]\n publ_s = obs[\"publ_s\"]\n legal_move = obs[\"legal_move\"]\n\n hid = {\n \"h0\": obs[\"h0\"].transpose(0, 1).flatten(1, 2).contiguous(),\n \"c0\": obs[\"c0\"].transpose(0, 1).flatten(1, 2).contiguous(),\n }\n\n logit, new_hid = self.forward(priv_s.unsqueeze(0), publ_s.unsqueeze(0), hid)\n logit = logit.squeeze(0)\n legal_logit = logit - (1 - legal_move) * 1e6\n action = legal_logit.max(1)[1]\n # sample with temp=1\n # action = nn.functional.softmax(legal_logit, 1)\n # action = action.multinomial(1)\n\n hid_shape = (\n self.num_lstm_layer,\n bsize,\n 1,\n self.hid_dim,\n )\n h0 = new_hid[\"h0\"].view(*hid_shape).transpose(0, 1)\n c0 = new_hid[\"c0\"].view(*hid_shape).transpose(0, 1)\n\n return {\n \"a\": action.detach().cpu(),\n \"h0\": h0.contiguous().detach().cpu(),\n \"c0\": c0.contiguous().detach().cpu(),\n }\n\n @torch.jit.script_method\n def compute_priority(\n self, input_: Dict[str, torch.Tensor]\n ) -> Dict[str, torch.Tensor]:\n \"\"\"for use in belief training\"\"\"\n return {\"priority\": torch.ones_like(input_[\"reward\"].sum(1))}\n\n @torch.jit.script_method\n def get_h0(self, batchsize: int):\n shape = (self.num_lstm_layer, batchsize, self.hid_dim)\n hid = {\n \"h0\": torch.zeros(*shape),\n \"c0\": torch.zeros(*shape),\n }\n return hid\n"
] | [
[
"numpy.convolve",
"torch.cuda.manual_seed",
"numpy.random.seed",
"torch.load",
"torch.manual_seed",
"numpy.ones",
"torch.FloatTensor",
"torch.nn.init.orthogonal_"
],
[
"torch.nn.Sequential",
"torch.nn.Dropout",
"torch.zeros",
"torch.nn.LSTM",
"torch.nn.Linear",
"torch.nn.ReLU"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
gboehl/pymetalog | [
"bcc1bfbf658f44f48d63a594d2b9de8b700a11a7"
] | [
"pymetalog/pdf_quantile_functions.py"
] | [
"import numpy as np\nfrom .support import pdfMetalog, quantileMetalog\n\n\ndef pdf_quantile_builder(temp, y, term_limit, bounds, boundedness):\n \"\"\"Builds the metalog pdf and quantile arrays based on the a coefficients found by fitting metalog distribution.\n\n Args:\n temp (:obj: `numpy.ndarray` of type float): Array of a coefficients found by fitting metalog distribution.\n - Fit method is specified by metalog.fit_method attribute\n\n y (:obj: `numpy.ndarray` of type float): Array of bin widths specified for `a` parameter\n\n term_limit (:obj: `int`): The upper limit of the range of metalog terms to use to fit the data.\n - metalog.term_limit attribute\n - in range [3,30]\n\n bounds (:obj:`list`): Upper and lower limits to filter the data with before calculating metalog quantiles/pdfs.\n - metalog.bounds attribute\n - Default: [0,1]\n\n boundedness (:obj: `str`): String that is used to specify the type of metalog to fit.\n - metalog.boundedness attribute\n\n Returns:\n q_dict (:obj:`dict` with keys ['m', 'M', 'y', 'valid']): Initialized output_dict variable from metalog class.\n - q_dict['m']: (:obj:`numpy.ndarray` of type float): Array of metalog pdf values.\n * Returned by `pdfMetalog` method\n * Influenced by `boundedness` parameter\n * A valid metalog fit will return an array having all elements strictly > 0\n\n - q_dict['M']: (:obj:`numpy.ndarray` of type float): Array of metalog quantile values.\n * Returned by `quantileMetalog` method\n * Influenced by `boundedness` parameter\n - `boundedness` = 'sl': Inserts `bounds`[0] to the front of the quantile array\n - `boundedness` = 'su': Appends `bounds`[1] to the end of the quantile array\n - `boundedness` = 'b': Inserts `bounds`[0] to the front of the quantile array\n and appends `bounds`[1] to the end of the quantile array\n\n - q_dict['y']: (:obj:`numpy.ndarray` of type float): Array of bin widths specified for the pdfs/quantiles.\n * Influenced by `boundedness` parameter\n - `boundedness` = 'sl': Inserts `bounds`[0] at the front of the quantile array\n - `boundedness` = 'su': Appends `bounds`[1] to the end of the quantile array\n - `boundedness` = 'b': Inserts `bounds`[0] at the front of the quantile array\n and appends `bounds`[1] to the end of the quantile array\n\n - q_dict['valid']: (:obj:`str`): A string indicating if the metalog pdf generated by `pdfMetalog` method is valid or not.\n * If all values in the metalog pdf are >= 0, q_dict['valid'] = 'yes'\n * If any values in the metalog pdf are < 0, q_dict['valid'] = 'no'\n\n \"\"\"\n q_dict = {}\n\n # build pdf\n m = pdfMetalog(temp, y[0], term_limit, bounds=bounds, boundedness=boundedness)\n\n for j in range(2, len(y) + 1):\n tempPDF = pdfMetalog(\n temp, y[j - 1], term_limit, bounds=bounds, boundedness=boundedness\n )\n m = np.append(m, tempPDF)\n\n # Build quantile values\n M = quantileMetalog(temp, y[1], term_limit, bounds=bounds, boundedness=boundedness)\n\n for j in range(2, len(y) + 1):\n tempQant = quantileMetalog(\n temp, y[j - 1], term_limit, bounds=bounds, boundedness=boundedness\n )\n M = np.append(M, tempQant)\n\n # Add trailing and leading zero's for pdf bounds\n if boundedness == \"sl\":\n m = np.append(0, m)\n M = np.append(bounds[0], M)\n\n if boundedness == \"su\":\n m = np.append(m, 0)\n M = np.append(M, bounds[1])\n\n if boundedness == \"b\":\n m = np.append(0, m)\n m = np.append(m, 0)\n M = np.append(bounds[0], M)\n M = np.append(M, bounds[1])\n\n # Add y values for bounded models\n if boundedness == \"sl\":\n y = np.append(0, y)\n\n if boundedness == \"su\":\n y = np.append(y, 1)\n\n if boundedness == \"b\":\n y = np.append(0, y)\n y = np.append(y, 1)\n\n q_dict[\"m\"] = m\n q_dict[\"M\"] = M\n q_dict[\"y\"] = y\n\n # PDF validation\n q_dict[\"valid\"] = pdfMetalogValidation(q_dict[\"m\"])\n\n return q_dict\n\n\ndef pdfMetalogValidation(x):\n \"\"\"Validation that all calculated metalog pdf values are greater than or equal to 0.\n\n Args:\n x (:obj: `numpy.ndarray` of type float): Array of metalog pdf values.\n - Returned by `pdfMetalog` method\n - Influenced by `boundedness` parameter\n\n Returns:\n 'yes' | 'no' (:obj:`str`): 'yes' if all elements strictly >= 0, else 'no'.\n \"\"\"\n y = np.min(x)\n if y >= 0:\n return \"yes\"\n else:\n return \"no\"\n"
] | [
[
"numpy.append",
"numpy.min"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
vishalbelsare/DESlib | [
"64260ae7c6dd745ef0003cc6322c9f829c807708"
] | [
"deslib/dcs/a_posteriori.py"
] | [
"# coding=utf-8\n\n# Author: Rafael Menelau Oliveira e Cruz <[email protected]>\n#\n# License: BSD 3 clause\n\nimport numpy as np\n\nfrom deslib.dcs.base import BaseDCS\n\n\nclass APosteriori(BaseDCS):\n \"\"\"A Posteriori Dynamic classifier selection.\n\n The A Posteriori method uses the probability of correct classification of a\n given base classifier :math:`c_{i}` for each neighbor :math:`x_{k}` with\n respect to a single class. Consider a classifier :math:`c_{i}` that assigns\n a test sample to class :math:`w_{l}`. Then, only the samples belonging to\n class :math:`w_{l}` are taken into account during the competence level\n estimates. Base classifiers with a higher probability of correct\n classification have a higher competence level. Moreover, the method also\n weights the influence of each neighbor :math:`x_{k}` according to its\n Euclidean distance to the query sample. The closest neighbors have a higher\n influence on the competence level estimate. In cases where no sample in the\n region of competence belongs to the predicted class, :math:`w_{l}`, the\n competence level estimate of the base classifier is equal to zero.\n\n A single classifier is selected only if its competence level is\n significantly higher than that of the other base classifiers in the pool\n (higher than a pre-defined threshold). Otherwise, all classifiers in the\n pool are combined using the majority voting rule. The selection methodology\n can be modified by modifying the hyper-parameter selection_method.\n\n Parameters\n ----------\n pool_classifiers : list of classifiers (Default = None)\n The generated_pool of classifiers trained for the corresponding\n classification problem. Each base classifiers should support the method\n \"predict\" and \"predict_proba\". If None, then the pool of classifiers is\n a bagging classifier.\n\n k : int (Default = 7)\n Number of neighbors used to estimate the competence of the base\n classifiers.\n\n DFP : Boolean (Default = False)\n Determines if the dynamic frienemy pruning is applied.\n\n with_IH : Boolean (Default = False)\n Whether the hardness level of the region of competence is used to\n decide between using the DS algorithm or the KNN for classification of\n a given query sample.\n\n safe_k : int (default = None)\n The size of the indecision region.\n\n IH_rate : float (default = 0.3)\n Hardness threshold. If the hardness level of the competence region is\n lower than the IH_rate the KNN classifier is used. Otherwise, the DS\n algorithm is used for classification.\n\n selection_method : String (Default = \"best\")\n Determines which method is used to select the base classifier after\n the competences are estimated.\n\n diff_thresh : float (Default = 0.1)\n Threshold to measure the difference between the competence level of the\n base classifiers for the random and diff selection schemes. If the\n difference is lower than the threshold, their performance are\n considered equivalent.\n\n random_state : int, RandomState instance or None, optional (default=None)\n If int, random_state is the seed used by the random number generator;\n If RandomState instance, random_state is the random number generator;\n If None, the random number generator is the RandomState instance used\n by `np.random`.\n\n knn_classifier : {'knn', 'faiss', None} (Default = 'knn')\n The algorithm used to estimate the region of competence:\n\n - 'knn' will use :class:`KNeighborsClassifier` from sklearn\n :class:`KNNE` available on `deslib.utils.knne`\n\n - 'faiss' will use Facebook's Faiss similarity search through the\n class :class:`FaissKNNClassifier`\n\n - None, will use sklearn :class:`KNeighborsClassifier`.\n\n knne : bool (Default=False)\n Whether to use K-Nearest Neighbor Equality (KNNE) for the region\n of competence estimation.\n\n DSEL_perc : float (Default = 0.5)\n Percentage of the input data used to fit DSEL.\n Note: This parameter is only used if the pool of classifier is None or\n unfitted.\n\n n_jobs : int, default=-1\n The number of parallel jobs to run. None means 1 unless in\n a joblib.parallel_backend context. -1 means using all processors.\n Doesn’t affect fit method.\n\n References\n ----------\n G. Giacinto and F. Roli, Methods for Dynamic Classifier Selection\n 10th Int. Conf. on Image Anal. and Proc., Venice, Italy (1999), 659-664.\n\n Ko, Albert HR, Robert Sabourin, and Alceu Souza Britto Jr. \"From dynamic\n classifier selection to dynamic ensemble selection.\"\n Pattern Recognition 41.5 (2008): 1718-1731.\n\n Britto, Alceu S., Robert Sabourin, and Luiz ES Oliveira. \"Dynamic selection\n of classifiers—a comprehensive review.\"\n Pattern Recognition 47.11 (2014): 3665-3680.\n\n R. M. O. Cruz, R. Sabourin, and G. D. Cavalcanti, “Dynamic classifier\n selection: Recent advances and perspectives,”\n Information Fusion, vol. 41, pp. 195 – 216, 2018.\n\n \"\"\"\n\n def __init__(self, pool_classifiers=None, k=7, DFP=False, with_IH=False,\n safe_k=None, IH_rate=0.30, selection_method='diff',\n diff_thresh=0.1, random_state=None, knn_classifier='knn',\n knne=False, DSEL_perc=0.5, n_jobs=-1):\n super(APosteriori, self).__init__(pool_classifiers=pool_classifiers,\n k=k, DFP=DFP, with_IH=with_IH,\n safe_k=safe_k, IH_rate=IH_rate,\n selection_method=selection_method,\n diff_thresh=diff_thresh,\n knn_classifier=knn_classifier,\n random_state=random_state,\n knne=knne,\n DSEL_perc=DSEL_perc, n_jobs=n_jobs)\n\n def fit(self, X, y):\n \"\"\"Prepare the DS model by setting the KNN algorithm and\n pre-processing the information required to apply the DS\n method.\n\n Parameters\n ----------\n X : array of shape (n_samples, n_features)\n Data used to fit the model.\n\n y : array of shape (n_samples)\n class labels of each example in X.\n\n Returns\n -------\n self\n \"\"\"\n super(APosteriori, self).fit(X, y)\n self._check_predict_proba()\n\n self.dsel_scores_ = self._predict_proba_base(self.DSEL_data_)\n return self\n\n def estimate_competence(self, competence_region, distances,\n predictions=None):\n \"\"\"Estimate the competence of each base classifier :math:`c_{i}` for\n the classification of the query sample using the A Posteriori method.\n\n The competence level is estimated based on the probability of correct\n classification of the base classifier :math:`c_{i}`, for each neighbor\n :math:`x_{k}` belonging to a specific class :math:`w_{l}`.\n In this case, :math:`w_{l}` is the class predicted by the base\n classifier :math:`c_{i}`, for the query sample. This method also\n weights the influence of each training sample according to its\n Euclidean distance to the query instance. The closest samples have a\n higher influence in the computation of the competence level. The\n competence level estimate is represented by the following equation:\n\n .. math:: \\\\delta_{i,j} = \\\\frac{\\\\sum_{\\\\mathbf{x}_{k} \\\\in\n \\\\omega_{l}}P(\\\\omega_{l} \\\\mid \\\\mathbf{x}_{k}, c_{i} )W_{k}}\n {\\\\sum_{k = 1}^{K}P(\\\\omega_{l} \\\\mid \\\\mathbf{x}_{k}, c_{i} )W_{k}}\n\n where :math:`\\\\delta_{i,j}` represents the competence level of\n :math:`c_{i}` for the classification of query.\n\n Parameters\n ----------\n competence_region : array of shape (n_samples, n_neighbors)\n Indices of the k nearest neighbors.\n\n distances : array of shape (n_samples, n_neighbors)\n Distances from the k nearest neighbors to the query.\n\n predictions : array of shape (n_samples, n_classifiers)\n Predictions of the base classifiers for the test examples.\n\n Returns\n -------\n competences : array of shape (n_samples, n_classifiers)\n Competence level estimated for each base classifier and test\n example.\n \"\"\"\n # Guarantee that these arrays are view as a 2D array for the case where\n # a single test sample is passed down.\n predictions = np.atleast_2d(predictions)\n distances[distances == 0] = 1e-10\n\n # Normalize the distances\n dists_normalized = 1.0 / distances\n\n # Expanding the dimensions of the predictions and target arrays in\n # order to compare both.\n predictions_3d = np.expand_dims(predictions, axis=1)\n target_3d = self.DSEL_target_[competence_region, np.newaxis]\n\n # Create a mask to remove the neighbors belonging to a different class\n # than the predicted by the base classifier\n mask = (predictions_3d != target_3d)\n\n # Broadcast the distance array to the same shape as the pre-processed\n # information for future calculations\n dists_normalized = np.repeat(np.expand_dims(dists_normalized, axis=2),\n self.n_classifiers_, axis=2)\n\n # Multiply the pre-processed correct predictions by the base\n # classifiers to the distance array\n scores_target = self.dsel_scores_[competence_region, :,\n self.DSEL_target_[competence_region]]\n scores_target_norm = scores_target * dists_normalized\n\n # Create masked arrays to remove samples with different label in the\n # calculations\n masked_preprocessed = np.ma.MaskedArray(scores_target_norm, mask=mask)\n masked_dist = np.ma.MaskedArray(dists_normalized, mask=mask)\n\n # Consider only the neighbor samples where the predicted label is\n # equals to the neighbor label\n competences_masked = np.ma.sum(masked_preprocessed,\n axis=1) / np.ma.sum(masked_dist, axis=1)\n\n # Fill 0 to the masked values in the resulting array (when no neighbors\n # belongs to the class predicted by the corresponding base classifier)\n competences = np.ma.filled(competences_masked, 0)\n\n return competences\n"
] | [
[
"numpy.ma.sum",
"numpy.expand_dims",
"numpy.ma.filled",
"numpy.atleast_2d",
"numpy.ma.MaskedArray"
]
] | [
{
"matplotlib": [],
"numpy": [
"1.10",
"1.12",
"1.11",
"1.19",
"1.13",
"1.16",
"1.9",
"1.18",
"1.20",
"1.7",
"1.15",
"1.14",
"1.17",
"1.8"
],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Masao-Someki/CycleVAE_VC | [
"be4a27637a3f8b6272d96105f9b3c9327f6c16f7"
] | [
"src/decode/decoder.py"
] | [
"# Copyright 2020 Masao Someki\n# MIT License (https://opensource.org/licenses/MIT)\nimport os\nimport glob\nimport h5py\nimport logging\n\nimport librosa\nimport numpy as np\nfrom scipy.io import wavfile\n\nfrom speech import Synthesizer\n\nIRLEN = 1024\nINTERVALS = 10\nSEED = 1\nLP_CUTOFF = 20\n\n\nclass Decoder(object):\n def __init__(self, args, scaler, logger=None):\n # directory to save wav files\n self.save_dir = args.exp_dir\n self.fs = args.fs\n self.shiftms = args.shiftms\n self.fftl = args.fftl\n\n # mcep_alpha\n if args.fs == 16000:\n self.mcep_alpha = 0.41\n elif args.fs == 22050:\n self.mcep_alpha = 0.455\n elif args.fs == 24000:\n self.mcep_alpha = 0.466\n elif args.fs == 44100:\n self.mcep_alpha = 0.544\n elif args.fs == 48000:\n self.mcep_alpha = 0.554\n else:\n raise ValueError('sampling rate should be one of \\\n 16000, 22050, 24000, 44100, 48000')\n\n # scaler\n self.scaler = scaler\n\n # synthesizer\n self.synthesizer = Synthesizer(fs=args.fs, fftl=args.fftl, shiftms=args.shiftms)\n\n # logger\n if logger is not None:\n self.logger = logger\n else:\n self.logger = logging.getLogger(__name__)\n\n def _inverse_transform(self, key, x):\n m = self.scaler[key].mean_\n s = self.scaler[key].scale_\n return x * s + m\n\n def decode(self, inputs, output, iter_count, i):\n # directory\n wav_dir = os.path.join(self.save_dir, str(iter_count))\n\n if not os.path.exists(wav_dir):\n os.mkdir(wav_dir)\n\n # process over all data\n for b in range(len(output['reconst_half'][0])):\n # flen\n flen = inputs['flen'][b]\n\n # mcep\n mcep = inputs['mcep'][b][:flen].cpu().detach().numpy()\n mcep = self._inverse_transform('mcep', mcep).astype(np.float64)\n\n # process src-src wav\n cvmcep = output['reconst_half'][0][b][:flen].cpu().detach().numpy()\n cvmcep = self._inverse_transform('mcep', cvmcep).astype(np.float64)\n\n # codeap\n codeap = inputs['codeap'][b][:flen].cpu().detach().numpy().astype(np.float64)\n codeap = self._inverse_transform('codeap', codeap)\n\n # synthesize\n wav = self.synthesizer.synthesis(\n inputs['f0'][b][:flen].squeeze(1).cpu().detach().numpy().astype(np.float64),\n cvmcep,\n codeap,\n alpha=self.mcep_alpha,\n rmcep=mcep\n )\n wav = np.clip(wav, -32768, 32767)\n wav_file = os.path.join(\n wav_dir,\n '%s_%s_%d.wav' % (inputs['src'][b], inputs['src'][b], i)\n )\n wavfile.write(wav_file, self.fs, wav.astype(np.int16))\n\n # process src-trg wav\n cvmcep = output['trg_reconst'][b][:flen].cpu().detach().numpy()\n cvmcep = self._inverse_transform('mcep', cvmcep).astype(np.float64)\n\n # convert f0\n cvf0 = inputs['cv_f0'][b][:flen].squeeze(1).cpu().detach().numpy().astype(np.float64)\n\n # synthesize\n wav = self.synthesizer.synthesis(\n cvf0,\n cvmcep,\n codeap,\n alpha=self.mcep_alpha,\n rmcep=mcep\n )\n wav = np.clip(wav, -32768, 32767)\n wav_file = os.path.join(\n wav_dir,\n '%s_%s_%d.wav' % (inputs['src'][b], inputs['trg'][b], i)\n )\n wavfile.write(wav_file, self.fs, wav.astype(np.int16))\n"
] | [
[
"numpy.clip"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
srinivasans/DeepSepsis | [
"8647a2ec93ad5a937638acfc279a756bbfa04f7f",
"8647a2ec93ad5a937638acfc279a756bbfa04f7f"
] | [
"deprecated/Imputation/GRUI/Run_GAN_imputed.py",
"evaluateModel.py"
] | [
"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Mar 26 10:47:41 2018\n\n@author: yonghong\n\"\"\"\n\nfrom __future__ import print_function\nimport sys\nsys.path.append(\"..\")\nimport argparse\nimport os\nimport tensorflow as tf\nfrom Physionet2019ImputedSepsisData import readImputed\nimport gru_delta_forGAN\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='manual to this script')\n parser.add_argument('--gpus', type=str, default = None)\n parser.add_argument('--batch-size', type=int, default=128)\n parser.add_argument('--run-type', type=str, default='test')\n parser.add_argument('--data-path', type=str, default=\"../Gan_Imputation/imputation_train_results/WGAN_no_mask/\")\n #输入填充之后的训练数据集的完整路径 Gan_Imputation/imputation_train_results/WGAN_no_mask/30_8_128_64_0.001_400_True_True_True_0.15_0.5\n parser.add_argument('--model-path', type=str, default=None)\n parser.add_argument('--result-path', type=str, default=None)\n parser.add_argument('--lr', type=float, default=0.01)\n #parser.add_argument('--epoch', type=int, default=20)\n parser.add_argument('--n-inputs', type=int, default=41)\n parser.add_argument('--n-hidden-units', type=int, default=64)\n parser.add_argument('--n-classes', type=int, default=2)\n parser.add_argument('--checkpoint-dir', type=str, default='checkpoint_physionet_imputed',\n help='Directory name to save the checkpoints')\n parser.add_argument('--log-dir', type=str, default='logs_physionet_imputed',\n help='Directory name to save training logs')\n parser.add_argument('--isNormal',type=int,default=1)\n parser.add_argument('--isSlicing',type=int,default=1)\n #0 false 1 true\n parser.add_argument('--isBatch-normal',type=int,default=1)\n args = parser.parse_args()\n\n\n if args.isBatch_normal==0:\n args.isBatch_normal=False\n if args.isBatch_normal==1:\n args.isBatch_normal=True\n if args.isNormal==0:\n args.isNormal=False\n if args.isNormal==1:\n args.isNormal=True\n if args.isSlicing==0:\n args.isSlicing=False\n if args.isSlicing==1:\n args.isSlicing=True\n\n\n checkdir=args.checkpoint_dir\n logdir=args.log_dir\n base=args.data_path\n data_paths=[\"30_8_128_64_0.001_400_True_True_False_0.15_0.5\"]\n max_auc = 0.0\n for d in data_paths:\n args.data_path=os.path.join(base,d)\n path_splits=args.data_path.split(\"/\")\n if len(path_splits[-1])==0:\n datasetName=path_splits[-2]\n else:\n datasetName=path_splits[-1]\n args.checkpoint_dir=checkdir+\"/\"+datasetName\n args.log_dir=logdir+\"/\"+datasetName\n\n dt_train=readImputed.ReadImputedPhysionetData(args.data_path)\n dt_train.load()\n\n dt_test=readImputed.ReadImputedPhysionetData(args.data_path.replace(\"imputation_train_results\",\"imputation_test_results\"))\n dt_test.load()\n\n lrs=[0.004,0.003,0.005,0.006,0.007,0.008,0.009,0.01,0.012,0.015]\n #lrs = [0.0075,0.0085]\n for lr in lrs:\n args.lr=lr\n epoch=30\n args.epoch=epoch\n print(\"epoch: %2d\"%(epoch))\n tf.reset_default_graph()\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n with tf.Session(config=config) as sess:\n model = gru_delta_forGAN.grui(sess,\n args=args,\n dataset=dt_train,\n test_set = dt_test\n )\n\n # build graph\n model.build()\n\n auc = model.train()\n if auc > max_auc:\n max_auc = auc\n\n print(\"\")\n print(\"max auc is: \" + str(max_auc))\n f2 = open(\"max_auc\",\"w\")\n f2.write(str(max_auc))\n f2.close()\n\n\n",
"import sys\nsys.path.append(\"..\")\nfrom datautils import dataset\nimport tensorflow as tf\nfrom prediction import GRUD\nimport os\nimport argparse\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Arguments for sepsis prediction')\n parser.add_argument('--batch-size', type=int, default=100)\n parser.add_argument('--data-path', type=str, default=\"data/sepsis_data\")\n parser.add_argument('--model-path', type=str, default=None)\n parser.add_argument('--result-path', type=str, default='results')\n parser.add_argument('--lr', type=float, default=0.01)\n parser.add_argument('--epochs', type=int, default=200)\n parser.add_argument('--n-inputs', type=int, default=36)\n parser.add_argument('--n-hidden-units', type=int, default=72)\n parser.add_argument('--n-classes', type=int, default=1)\n parser.add_argument('--checkpoint-dir', type=str, default='checkpoint',\n help='Directory name to save the checkpoints')\n parser.add_argument('--log-dir', type=str, default='logs',\n help='Directory name to save training logs')\n parser.add_argument('--normalize',type=int,default=1)\n parser.add_argument('--dropout-rate',type=float,default=0.5)\n parser.add_argument('--celltype', type=str, default='GRUD')\n parser.add_argument('--experiment', type=str, default='GRUM')\n parser.add_argument('--threshold', type=float, default=0.5)\n parser.add_argument('--seed', type=int, default=42)\n parser.add_argument('--impute-forward', type=float, default=0)\n parser.add_argument('--imputation_method', type=str, default='mean')\n\n args = parser.parse_args()\n \n if args.normalize==0:\n args.normalize=False\n if args.normalize==1:\n args.normalize=True\n\n if args.impute_forward==0:\n args.impute_forward=False\n if args.impute_forward==1:\n args.impute_forward=True\n\n checkdir=args.checkpoint_dir\n logdir=args.log_dir\n base=args.data_path\n data_paths=[]\n max_auc = 0.0\n\n args.checkpoint_dir=os.path.join(checkdir, args.experiment)\n args.log_dir=os.path.join(logdir,args.experiment)\n \n #Max length across all datasets = 336. \n #Setting min maxLength=336 for traindata for now!!\n #TODO: Find max of max lengths across all datasets and use that for setting this maxLength\n dataset=dataset.Dataset(path=args.data_path,\n batchSize=args.batch_size,\n train_ratio=0.8,\n normalize=args.normalize,\n padding=True,\n maxLength=336,\n imputeForward=args.impute_forward,\n seed=args.seed)\n\n tf.reset_default_graph()\n config = tf.ConfigProto() \n config.gpu_options.allow_growth = True \n \n with tf.Session(config=config) as sess:\n if args.celltype == \"LSTM\":\n model = LSTM.lstm(sess,\n args=args,\n train_data=dataset.train_data,\n validation_data=dataset.val_data,\n test_data=dataset.test_data)\n elif args.celltype == \"GRU\":\n model = GRU.GRU(sess,\n args=args,\n train_data=dataset.train_data,\n validation_data=dataset.val_data,\n test_data=dataset.test_data)\n elif args.celltype == \"GRUM\":\n model = GRUM.GRUM(sess,\n args=args,\n train_data=dataset.train_data,\n validation_data=dataset.val_data,\n test_data=dataset.test_data)\n elif args.celltype == \"GRUD\":\n model = GRUD.GRUD(sess,\n args=args,\n train_data=dataset.train_data,\n validation_data=dataset.val_data,\n test_data=dataset.test_data)\n model.build()\n test_acc, test_auc, test_tp, test_fp, test_tn, test_fn, sens, spec = model.test(checkpoint_dir='checkpoint/GRUM_C_Mean_40k/GRUM_C_Mean_40k_0.001_100_True/epoch5', \n test_epoch=5, \n generate_files=True, \n val=False,\n load_checkpoint=True)\n print((test_acc, test_auc, test_tp, test_fp, test_tn, test_fn, sens, spec))"
] | [
[
"tensorflow.ConfigProto",
"tensorflow.reset_default_graph",
"tensorflow.Session"
],
[
"tensorflow.ConfigProto",
"tensorflow.reset_default_graph",
"tensorflow.Session"
]
] | [
{
"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"
]
}
] |
middleprince/fashionAi | [
"c512936b4983c2fb093008f06e04753180af0a90",
"c512936b4983c2fb093008f06e04753180af0a90"
] | [
"run_local_mertric.py",
"train_senet_cpn_onebyone.py"
] | [
"import os\nimport sys\nimport time\nimport numpy as np\nimport pandas as pd\nimport argparse\nimport math\n\nimport config as cfg\n\ndef str2bool(v):\n return v.lower() in (\"yes\", \"true\", \"t\", \"1\")\n\nparser = argparse.ArgumentParser(\n description='The Normarlized Error Mertric Calculation For FashionAI Keypoint Detection Script.')\ntrain_set = parser.add_mutually_exclusive_group()\nparser.add_argument('--prediction', default='',\n help='The path of file containing the prediction of keypoints.')\nparser.add_argument('--cat', type=lambda s: s.lower() in ['True', 'true', 't', 'yes', '1'], help=\"whether print Normarlized Error for each catgory\")\nparser.add_argument('--gt', default='./stage1_testb_gt.csv',\n help='The path of file containing the ground truth of keypoints.')\n\nargs = parser.parse_args()\n\ndef run():\n if args.prediction.strip() == '' or args.gt.strip() == '':\n parser.error('Must specify the file path of the prediction and ground truth.')\n\n pred_df = pd.read_csv(args.prediction, encoding='utf-8')\n gt_df = pd.read_csv(args.gt, encoding='utf-8').set_index('image_id')\n\n\n num_v = 0.\n sum_dist = 0.\n for index, row in pred_df.iterrows():\n gt = gt_df.loc[row['image_id']]\n img_cat = gt['image_category']\n gt_points = {}\n pred_points = {}\n\n for kp in cfg.all_keys:\n pred_kp = row[kp].strip().split('_')\n gt_kp = gt[kp].strip().split('_')\n pred_points[kp] = [int(_) for _ in pred_kp]\n gt_points[kp] = [int(_) for _ in gt_kp]\n\n lnorm_name, rnorm_name = cfg.normalize_point_name[img_cat]\n lnorm, rnorm = gt_points[lnorm_name][:-1], gt_points[rnorm_name][:-1]\n norm_value = math.pow(math.pow(lnorm[0] - rnorm[0], 2.) + math.pow(lnorm[1] - rnorm[1], 2.), 0.5)\n\n\n for kp in cfg.all_keys:\n if gt_points[kp][-1] == -1 or norm_value < 1e-3:\n continue\n num_v += 1.\n\n dist = math.pow(math.pow(pred_points[kp][0] - gt_points[kp][0], 2.) + math.pow(pred_points[kp][1] - gt_points[kp][1], 2.), 0.5)\n sum_dist += dist/norm_value\n\n sum_dist = sum_dist/num_v\n print(sum_dist)\n\ndef run_by_cat():\n if args.prediction.strip() == '' or args.gt.strip() == '':\n parser.error('Must specify the file path of the prediction and ground truth.')\n\n pred_df = pd.read_csv(args.prediction, encoding='utf-8')\n gt_df = pd.read_csv(args.gt, encoding='utf-8').set_index('image_id')\n\n for cat_ in cfg.CATEGORIES:\n num_v = 0.\n sum_dist = 0.\n for index, row in pred_df.iterrows():\n gt = gt_df.loc[row['image_id']]\n img_cat = gt['image_category']\n if cat_ not in img_cat:\n continue\n gt_points = {}\n pred_points = {}\n\n for kp in cfg.all_keys:\n pred_kp = row[kp].strip().split('_')\n gt_kp = gt[kp].strip().split('_')\n pred_points[kp] = [int(_) for _ in pred_kp]\n gt_points[kp] = [int(_) for _ in gt_kp]\n\n lnorm_name, rnorm_name = cfg.normalize_point_name[img_cat]\n lnorm, rnorm = gt_points[lnorm_name][:-1], gt_points[rnorm_name][:-1]\n norm_value = math.pow(math.pow(lnorm[0] - rnorm[0], 2.) + math.pow(lnorm[1] - rnorm[1], 2.), 0.5)\n\n\n for kp in cfg.all_keys:\n if gt_points[kp][-1] == -1 or norm_value < 1e-3:\n continue\n num_v += 1.\n\n dist = math.pow(math.pow(pred_points[kp][0] - gt_points[kp][0], 2.) + math.pow(pred_points[kp][1] - gt_points[kp][1], 2.), 0.5)\n sum_dist += dist/norm_value\n\n sum_dist = sum_dist/num_v\n print('{}:'.format(cat_), sum_dist)\n\nif __name__ == '__main__':\n if not args.cat:\n run()\n else:\n run_by_cat()\n",
"# Copyright 2018 Changan Wang\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 __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport sys\nimport numpy as np\n#from scipy.misc import imread, imsave, imshow, imresize\nimport tensorflow as tf\n\nfrom net import seresnet_cpn as cpn\nfrom utility import train_helper\nfrom utility import mertric\n\nfrom preprocessing import preprocessing\nfrom preprocessing import dataset\nimport config\n\n# hardware related configuration\ntf.app.flags.DEFINE_integer(\n 'num_readers', 16,#16\n 'The number of parallel readers that read data from the dataset.')\ntf.app.flags.DEFINE_integer(\n 'num_preprocessing_threads', 48,#48\n 'The number of threads used to create the batches.')\ntf.app.flags.DEFINE_integer(\n 'num_cpu_threads', 0,\n 'The number of cpu cores used to train.')\ntf.app.flags.DEFINE_float(\n 'gpu_memory_fraction', 1., 'GPU memory fraction to use.')\n# scaffold related configuration\ntf.app.flags.DEFINE_string(\n 'data_dir', '../Datasets/tfrecords',#'/media/rs/0E06CD1706CD0127/Kapok/Chi/Datasets/tfrecords',\n 'The directory where the dataset input data is stored.')\ntf.app.flags.DEFINE_string(\n 'dataset_name', '{}_????', 'The pattern of the dataset name to load.')\ntf.app.flags.DEFINE_string(\n 'model_dir', './logs_sext_cpn/',\n 'The parent directory where the model will be stored.')\ntf.app.flags.DEFINE_integer(\n 'log_every_n_steps', 10,\n 'The frequency with which logs are print.')\ntf.app.flags.DEFINE_integer(\n 'save_summary_steps', 100,\n 'The frequency with which summaries are saved, in seconds.')\ntf.app.flags.DEFINE_integer(\n 'save_checkpoints_secs', 3600,\n 'The frequency with which the model is saved, in seconds.')\n# model related configuration\ntf.app.flags.DEFINE_integer(\n 'train_image_size', 384,\n 'The size of the input image for the model to use.')\ntf.app.flags.DEFINE_integer(\n 'heatmap_size', 96,\n 'The size of the output heatmap of the model.')\ntf.app.flags.DEFINE_string(\n 'backbone', 'seresnext50',#or seresnext50 seresnet50\n 'The backbone network to use for feature pyramid.')\ntf.app.flags.DEFINE_float(\n 'heatmap_sigma', 1.,\n 'The sigma of Gaussian which generate the target heatmap.')\ntf.app.flags.DEFINE_float(\n 'bbox_border', 25.,\n 'The nearest distance of the crop border to al keypoints.')\ntf.app.flags.DEFINE_integer(\n 'train_epochs', 50,\n 'The number of epochs to use for training.')\ntf.app.flags.DEFINE_integer(\n 'epochs_per_eval', 20,\n 'The number of training epochs to run between evaluations.')\ntf.app.flags.DEFINE_integer(\n 'batch_size', 10,\n 'Batch size for training and evaluation.')\ntf.app.flags.DEFINE_integer(\n 'xt_batch_size', 10,\n 'Batch size for training and evaluation.')\ntf.app.flags.DEFINE_boolean(\n 'use_ohkm', True,\n 'Wether we will use the ohkm for hard keypoints.')\ntf.app.flags.DEFINE_string(\n 'data_format', 'channels_first', # 'channels_first' or 'channels_last'\n 'A flag to override the data format used in the model. channels_first '\n 'provides a performance boost on GPU but is not always compatible '\n 'with CPU. If left unspecified, the data format will be chosen '\n 'automatically based on whether TensorFlow was built for CPU or GPU.')\n# optimizer related configuration\ntf.app.flags.DEFINE_integer(\n 'tf_random_seed', 20180417, 'Random seed for TensorFlow initializers.')\ntf.app.flags.DEFINE_float(\n 'weight_decay', 1e-5, 'The weight decay on the model weights.')\ntf.app.flags.DEFINE_float(\n 'mse_weight', 1., 'The weight decay on the model weights.')\ntf.app.flags.DEFINE_float(\n 'momentum', 0.9,\n 'The momentum for the MomentumOptimizer and RMSPropOptimizer.')\ntf.app.flags.DEFINE_float('learning_rate', 1e-4, 'Initial learning rate.')#1e-3\ntf.app.flags.DEFINE_float(\n 'end_learning_rate', 0.000001,\n 'The minimal end learning rate used by a polynomial decay learning rate.')\ntf.app.flags.DEFINE_float(\n 'warmup_learning_rate', 0.00001,\n 'The start warm-up learning rate to avoid NAN.')\ntf.app.flags.DEFINE_integer(\n 'warmup_steps', 100,\n 'The total steps to warm-up.')\n# for learning rate piecewise_constant decay\ntf.app.flags.DEFINE_string(\n 'decay_boundaries', '2, 3',\n 'Learning rate decay boundaries by global_step (comma-separated list).')\ntf.app.flags.DEFINE_string(\n 'lr_decay_factors', '1, 0.5, 0.1',\n 'The values of learning_rate decay factor for each segment between boundaries (comma-separated list).')\n# checkpoint related configuration\ntf.app.flags.DEFINE_string(\n 'checkpoint_path', './model',\n 'The path to a checkpoint from which to fine-tune.')\ntf.app.flags.DEFINE_string(\n 'checkpoint_model_scope', '',\n 'Model scope in the checkpoint. None if the same as the trained model.')\ntf.app.flags.DEFINE_string(\n #'blouse', 'dress', 'outwear', 'skirt', 'trousers', 'all'\n 'model_scope', None,\n 'Model scope name used to replace the name_scope in checkpoint.')\ntf.app.flags.DEFINE_string(\n 'checkpoint_exclude_scopes', None,\n 'Comma-separated list of scopes of variables to exclude when restoring from a checkpoint.')\ntf.app.flags.DEFINE_boolean(\n 'ignore_missing_vars', True,\n 'When restoring a checkpoint would ignore missing variables.')\ntf.app.flags.DEFINE_boolean(\n 'run_on_cloud', False,\n 'Wether we will train on cloud.')\ntf.app.flags.DEFINE_boolean(\n 'seq_train', False,\n 'Wether we will train a sequence model.')\ntf.app.flags.DEFINE_string(#\n 'model_to_train', 'blouse, dress, outwear, skirt, trousers', #'all, blouse, dress, outwear, skirt, trousers', 'skirt, dress, outwear, trousers',\n 'The sub-model to train (comma-separated list).')\n\nFLAGS = tf.app.flags.FLAGS\n#--model_scope=blouse --checkpoint_path=./logs/all --data_format=channels_last --batch_size=1\ndef input_pipeline(is_training=True, model_scope=FLAGS.model_scope, num_epochs=FLAGS.epochs_per_eval):\n if 'all' in model_scope:\n lnorm_table = tf.contrib.lookup.HashTable(tf.contrib.lookup.KeyValueTensorInitializer(tf.constant(config.global_norm_key, dtype=tf.int64),\n tf.constant(config.global_norm_lvalues, dtype=tf.int64)), 0)\n rnorm_table = tf.contrib.lookup.HashTable(tf.contrib.lookup.KeyValueTensorInitializer(tf.constant(config.global_norm_key, dtype=tf.int64),\n tf.constant(config.global_norm_rvalues, dtype=tf.int64)), 1)\n else:\n lnorm_table = tf.contrib.lookup.HashTable(tf.contrib.lookup.KeyValueTensorInitializer(tf.constant(config.local_norm_key, dtype=tf.int64),\n tf.constant(config.local_norm_lvalues, dtype=tf.int64)), 0)\n rnorm_table = tf.contrib.lookup.HashTable(tf.contrib.lookup.KeyValueTensorInitializer(tf.constant(config.local_norm_key, dtype=tf.int64),\n tf.constant(config.local_norm_rvalues, dtype=tf.int64)), 1)\n\n preprocessing_fn = lambda org_image, classid, shape, key_x, key_y, key_v: preprocessing.preprocess_image(org_image, classid, shape, FLAGS.train_image_size, FLAGS.train_image_size, key_x, key_y, key_v, (lnorm_table, rnorm_table), is_training=is_training, data_format=('NCHW' if FLAGS.data_format=='channels_first' else 'NHWC'), category=(model_scope if 'all' not in model_scope else '*'), bbox_border=FLAGS.bbox_border, heatmap_sigma=FLAGS.heatmap_sigma, heatmap_size=FLAGS.heatmap_size)\n\n images, shape, classid, targets, key_v, isvalid, norm_value = dataset.slim_get_split(FLAGS.data_dir, preprocessing_fn, (FLAGS.xt_batch_size if 'seresnext50' in FLAGS.backbone else FLAGS.batch_size), FLAGS.num_readers, FLAGS.num_preprocessing_threads, num_epochs=num_epochs, is_training=is_training, file_pattern=FLAGS.dataset_name, category=(model_scope if 'all' not in model_scope else '*'), reader=None)\n\n return images, {'targets': targets, 'key_v': key_v, 'shape': shape, 'classid': classid, 'isvalid': isvalid, 'norm_value': norm_value}\n\nif config.PRED_DEBUG:\n from scipy.misc import imread, imsave, imshow, imresize\n def save_image_with_heatmap(image, height, width, heatmap_size, targets, pred_heatmap, indR, indG, indB):\n if not hasattr(save_image_with_heatmap, \"counter\"):\n save_image_with_heatmap.counter = 0 # it doesn't exist yet, so initialize it\n save_image_with_heatmap.counter += 1\n\n img_to_save = np.array(image.tolist()) + 128\n #print(img_to_save.shape)\n\n img_to_save = img_to_save.astype(np.uint8)\n\n heatmap0 = np.sum(targets[indR, ...], axis=0).astype(np.uint8)\n heatmap1 = np.sum(targets[indG, ...], axis=0).astype(np.uint8)\n heatmap2 = np.sum(targets[indB, ...], axis=0).astype(np.uint8) if len(indB) > 0 else np.zeros((heatmap_size, heatmap_size), dtype=np.float32)\n\n img_to_save = imresize(img_to_save, (height, width), interp='lanczos')\n heatmap0 = imresize(heatmap0, (height, width), interp='lanczos')\n heatmap1 = imresize(heatmap1, (height, width), interp='lanczos')\n heatmap2 = imresize(heatmap2, (height, width), interp='lanczos')\n\n img_to_save = img_to_save/2\n img_to_save[:,:,0] = np.clip((img_to_save[:,:,0] + heatmap0 + heatmap2), 0, 255)\n img_to_save[:,:,1] = np.clip((img_to_save[:,:,1] + heatmap1 + heatmap2), 0, 255)\n #img_to_save[:,:,2] = np.clip((img_to_save[:,:,2]/4. + heatmap2), 0, 255)\n file_name = 'targets_{}.jpg'.format(save_image_with_heatmap.counter)\n imsave(os.path.join(config.DEBUG_DIR, file_name), img_to_save.astype(np.uint8))\n\n pred_heatmap = np.array(pred_heatmap.tolist())\n #print(pred_heatmap.shape)\n for ind in range(pred_heatmap.shape[0]):\n img = pred_heatmap[ind]\n img = img - img.min()\n img *= 255.0/img.max()\n file_name = 'heatmap_{}_{}.jpg'.format(save_image_with_heatmap.counter, ind)\n imsave(os.path.join(config.DEBUG_DIR, file_name), img.astype(np.uint8))\n return save_image_with_heatmap.counter\n\ndef get_keypoint(image, targets, predictions, heatmap_size, height, width, category, clip_at_zero=True, data_format='channels_last', name=None):\n predictions = tf.reshape(predictions, [1, -1, heatmap_size*heatmap_size])\n\n pred_max = tf.reduce_max(predictions, axis=-1)\n pred_indices = tf.argmax(predictions, axis=-1)\n pred_x, pred_y = tf.cast(tf.floormod(pred_indices, heatmap_size), tf.float32), tf.cast(tf.floordiv(pred_indices, heatmap_size), tf.float32)\n\n width, height = tf.cast(width, tf.float32), tf.cast(height, tf.float32)\n pred_x, pred_y = pred_x * width / tf.cast(heatmap_size, tf.float32), pred_y * height / tf.cast(heatmap_size, tf.float32)\n\n if clip_at_zero:\n pred_x, pred_y = pred_x * tf.cast(pred_max>0, tf.float32), pred_y * tf.cast(pred_max>0, tf.float32)\n pred_x = pred_x * tf.cast(pred_max>0, tf.float32) + tf.cast(pred_max<=0, tf.float32) * (width / 2.)\n pred_y = pred_y * tf.cast(pred_max>0, tf.float32) + tf.cast(pred_max<=0, tf.float32) * (height / 2.)\n\n if config.PRED_DEBUG:\n pred_indices_ = tf.squeeze(pred_indices)\n image_ = tf.squeeze(image) * 255.\n pred_heatmap = tf.one_hot(pred_indices_, heatmap_size*heatmap_size, on_value=1., off_value=0., axis=-1, dtype=tf.float32)\n\n pred_heatmap = tf.reshape(pred_heatmap, [-1, heatmap_size, heatmap_size])\n if data_format == 'channels_first':\n image_ = tf.transpose(image_, perm=(1, 2, 0))\n save_image_op = tf.py_func(save_image_with_heatmap,\n [image_, height, width,\n heatmap_size,\n tf.reshape(pred_heatmap * 255., [-1, heatmap_size, heatmap_size]),\n tf.reshape(predictions, [-1, heatmap_size, heatmap_size]),\n config.left_right_group_map[category][0],\n config.left_right_group_map[category][1],\n config.left_right_group_map[category][2]],\n tf.int64, stateful=True)\n with tf.control_dependencies([save_image_op]):\n pred_x, pred_y = pred_x * 1., pred_y * 1.\n return pred_x, pred_y\n\ndef gaussian_blur(inputs, inputs_filters, sigma, data_format, name=None):\n with tf.name_scope(name, \"gaussian_blur\", [inputs]):\n data_format_ = 'NHWC' if data_format=='channels_last' else 'NCHW'\n if data_format_ == 'NHWC':\n inputs = tf.transpose(inputs, [0, 2, 3, 1])\n ksize = int(6 * sigma + 1.)\n x = tf.expand_dims(tf.range(ksize, delta=1, dtype=tf.float32), axis=1)\n y = tf.transpose(x, [1, 0])\n kernel_matrix = tf.exp(- ((x - ksize/2.) ** 2 + (y - ksize/2.) ** 2) / (2 * sigma ** 2))\n #print(kernel_matrix)\n kernel_filter = tf.reshape(kernel_matrix, [ksize, ksize, 1, 1])\n kernel_filter = tf.tile(kernel_filter, [1, 1, inputs_filters, 1])\n #kernel_filter = tf.transpose(kernel_filter, [1, 0, 2, 3])\n outputs = tf.nn.depthwise_conv2d(inputs, kernel_filter, strides=[1, 1, 1, 1], padding='SAME', data_format=data_format_, name='blur')\n if data_format_ == 'NHWC':\n outputs = tf.transpose(outputs, [0, 3, 1, 2])\n return outputs\n\ncpn_backbone = cpn.cascaded_pyramid_net\nif 'seresnext50' in FLAGS.backbone:\n cpn_backbone = cpn.xt_cascaded_pyramid_net\n\ndef keypoint_model_fn(features, labels, mode, params):\n targets = labels['targets']\n shape = labels['shape']\n classid = labels['classid']\n key_v = labels['key_v']\n isvalid = labels['isvalid']\n norm_value = labels['norm_value']\n\n cur_batch_size = tf.shape(features)[0]\n #features= tf.ones_like(features)\n\n with tf.variable_scope(params['model_scope'], default_name=None, values=[features], reuse=tf.AUTO_REUSE):\n pred_outputs = cpn_backbone(features, config.class_num_joints[(params['model_scope'] if 'all' not in params['model_scope'] else '*')], params['heatmap_size'], (mode == tf.estimator.ModeKeys.TRAIN), params['data_format'])\n\n if params['data_format'] == 'channels_last':\n pred_outputs = [tf.transpose(pred_outputs[ind], [0, 3, 1, 2], name='outputs_trans_{}'.format(ind)) for ind in list(range(len(pred_outputs)))]\n\n score_map = pred_outputs[-1]\n\n pred_x, pred_y = get_keypoint(features, targets, score_map, params['heatmap_size'], params['train_image_size'], params['train_image_size'], (params['model_scope'] if 'all' not in params['model_scope'] else '*'), clip_at_zero=True, data_format=params['data_format'])\n\n # this is important!!!\n targets = 255. * targets\n blur_list = [1., 1.37, 1.73, 2.4, None]#[1., 1.5, 2., 3., None]\n #blur_list = [None, None, None, None, None]\n\n targets_list = []\n for sigma in blur_list:\n if sigma is None:\n targets_list.append(targets)\n else:\n # always channels first foe targets\n targets_list.append(gaussian_blur(targets, config.class_num_joints[(params['model_scope'] if 'all' not in params['model_scope'] else '*')], sigma, params['data_format'], 'blur_{}'.format(sigma)))\n\n # print(key_v)\n #targets = tf.reshape(255.*tf.one_hot(tf.ones_like(key_v,tf.int64)*(params['heatmap_size']*params['heatmap_size']//2+params['heatmap_size']), params['heatmap_size']*params['heatmap_size']), [cur_batch_size,-1,params['heatmap_size'],params['heatmap_size']])\n #norm_value = tf.ones_like(norm_value)\n # score_map = tf.reshape(tf.one_hot(tf.ones_like(key_v,tf.int64)*(31*64+31), params['heatmap_size']*params['heatmap_size']), [cur_batch_size,-1,params['heatmap_size'],params['heatmap_size']])\n\n #with tf.control_dependencies([pred_x, pred_y]):\n ne_mertric = mertric.normalized_error(targets, score_map, norm_value, key_v, isvalid,\n cur_batch_size,\n config.class_num_joints[(params['model_scope'] if 'all' not in params['model_scope'] else '*')],\n params['heatmap_size'],\n params['train_image_size'])\n\n # last_pred_mse = tf.metrics.mean_squared_error(score_map, targets,\n # weights=1.0 / tf.cast(cur_batch_size, tf.float32),\n # name='last_pred_mse')\n # filter all invisible keypoint maybe better for this task\n # all_visible = tf.logical_and(key_v>0, isvalid>0)\n # targets_list = [tf.boolean_mask(targets_list[ind], all_visible) for ind in list(range(len(targets_list)))]\n # pred_outputs = [tf.boolean_mask(pred_outputs[ind], all_visible, name='boolean_mask_{}'.format(ind)) for ind in list(range(len(pred_outputs)))]\n all_visible = tf.expand_dims(tf.expand_dims(tf.cast(tf.logical_and(key_v>0, isvalid>0), tf.float32), axis=-1), axis=-1)\n targets_list = [targets_list[ind] * all_visible for ind in list(range(len(targets_list)))]\n pred_outputs = [pred_outputs[ind] * all_visible for ind in list(range(len(pred_outputs)))]\n\n sq_diff = tf.reduce_sum(tf.squared_difference(targets, pred_outputs[-1]), axis=-1)\n last_pred_mse = tf.metrics.mean_absolute_error(sq_diff, tf.zeros_like(sq_diff), name='last_pred_mse')\n\n metrics = {'normalized_error': ne_mertric, 'last_pred_mse':last_pred_mse}\n predictions = {'normalized_error': ne_mertric[1]}\n ne_mertric = tf.identity(ne_mertric[1], name='ne_mertric')\n\n base_learning_rate = params['learning_rate']\n mse_loss_list = []\n if params['use_ohkm']:\n base_learning_rate = 1. * base_learning_rate\n for pred_ind in list(range(len(pred_outputs) - 1)):\n mse_loss_list.append(0.5 * tf.losses.mean_squared_error(targets_list[pred_ind], pred_outputs[pred_ind],\n weights=1.0 / tf.cast(cur_batch_size, tf.float32),\n scope='loss_{}'.format(pred_ind),\n loss_collection=None,#tf.GraphKeys.LOSSES,\n # mean all elements of all pixels in all batch\n reduction=tf.losses.Reduction.MEAN))# SUM, SUM_OVER_BATCH_SIZE, default mean by all elements\n\n temp_loss = tf.reduce_mean(tf.reshape(tf.losses.mean_squared_error(targets_list[-1], pred_outputs[-1], weights=1.0, loss_collection=None, reduction=tf.losses.Reduction.NONE), [cur_batch_size, config.class_num_joints[(params['model_scope'] if 'all' not in params['model_scope'] else '*')], -1]), axis=-1)\n\n num_topk = config.class_num_joints[(params['model_scope'] if 'all' not in params['model_scope'] else '*')] // 2\n gather_col = tf.nn.top_k(temp_loss, k=num_topk, sorted=True)[1]\n gather_row = tf.reshape(tf.tile(tf.reshape(tf.range(cur_batch_size), [-1, 1]), [1, num_topk]), [-1, 1])\n gather_indcies = tf.stop_gradient(tf.stack([gather_row, tf.reshape(gather_col, [-1, 1])], axis=-1))\n\n select_targets = tf.gather_nd(targets_list[-1], gather_indcies)\n select_heatmap = tf.gather_nd(pred_outputs[-1], gather_indcies)\n\n mse_loss_list.append(tf.losses.mean_squared_error(select_targets, select_heatmap,\n weights=1.0 / tf.cast(cur_batch_size, tf.float32),\n scope='loss_{}'.format(len(pred_outputs) - 1),\n loss_collection=None,#tf.GraphKeys.LOSSES,\n # mean all elements of all pixels in all batch\n reduction=tf.losses.Reduction.MEAN))\n else:\n for pred_ind in list(range(len(pred_outputs))):\n mse_loss_list.append(tf.losses.mean_squared_error(targets_list[pred_ind], pred_outputs[pred_ind],\n weights=1.0 / tf.cast(cur_batch_size, tf.float32),\n scope='loss_{}'.format(pred_ind),\n loss_collection=None,#tf.GraphKeys.LOSSES,\n # mean all elements of all pixels in all batch\n reduction=tf.losses.Reduction.MEAN))# SUM, SUM_OVER_BATCH_SIZE, default mean by all elements\n\n mse_loss = tf.multiply(params['mse_weight'], tf.add_n(mse_loss_list), name='mse_loss')\n tf.summary.scalar('mse', mse_loss)\n tf.losses.add_loss(mse_loss)\n\n # bce_loss_list = []\n # for pred_ind in list(range(len(pred_outputs))):\n # bce_loss_list.append(tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=pred_outputs[pred_ind], labels=targets_list[pred_ind]/255., name='loss_{}'.format(pred_ind)), name='loss_mean_{}'.format(pred_ind)))\n\n # mse_loss = tf.multiply(params['mse_weight'] / params['num_stacks'], tf.add_n(bce_loss_list), name='mse_loss')\n # tf.summary.scalar('mse', mse_loss)\n # tf.losses.add_loss(mse_loss)\n\n # Add weight decay to the loss. We exclude the batch norm variables because\n # doing so leads to a small improvement in accuracy.\n loss = mse_loss + params['weight_decay'] * tf.add_n([tf.nn.l2_loss(v) for v in tf.trainable_variables() if 'batch_normalization' not in v.name])\n total_loss = tf.identity(loss, name='total_loss')\n tf.summary.scalar('loss', total_loss)\n\n if mode == tf.estimator.ModeKeys.EVAL:\n return tf.estimator.EstimatorSpec(mode=mode, loss=loss, predictions=predictions, eval_metric_ops=metrics)\n\n if mode == tf.estimator.ModeKeys.TRAIN:\n global_step = tf.train.get_or_create_global_step()\n\n lr_values = [params['warmup_learning_rate']] + [base_learning_rate * decay for decay in params['lr_decay_factors']]\n learning_rate = tf.train.piecewise_constant(tf.cast(global_step, tf.int32),\n [params['warmup_steps']] + [int(float(ep)*params['steps_per_epoch']) for ep in params['decay_boundaries']],\n lr_values)\n truncated_learning_rate = tf.maximum(learning_rate, tf.constant(params['end_learning_rate'], dtype=learning_rate.dtype), name='learning_rate')\n tf.summary.scalar('lr', truncated_learning_rate)\n\n optimizer = tf.train.MomentumOptimizer(learning_rate=truncated_learning_rate,\n momentum=params['momentum'])\n\n # Batch norm requires update_ops to be added as a train_op dependency.\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n with tf.control_dependencies(update_ops):\n train_op = optimizer.minimize(loss, global_step)\n else:\n train_op = None\n\n return tf.estimator.EstimatorSpec(\n mode=mode,\n predictions=predictions,\n loss=loss,\n train_op=train_op,\n eval_metric_ops=metrics,\n scaffold=tf.train.Scaffold(init_fn=train_helper.get_init_fn_for_scaffold_(params['checkpoint_path'], params['model_dir'], params['checkpoint_exclude_scopes'], params['model_scope'], params['checkpoint_model_scope'], params['ignore_missing_vars'])))\n\ndef parse_comma_list(args):\n return [float(s.strip()) for s in args.split(',')]\n\ndef sub_loop(model_fn, model_scope, model_dir, run_config, train_epochs, epochs_per_eval, lr_decay_factors, decay_boundaries, checkpoint_path=None, checkpoint_exclude_scopes='', checkpoint_model_scope='', ignore_missing_vars=True):\n steps_per_epoch = config.split_size[(model_scope if 'all' not in model_scope else '*')]['train'] // (FLAGS.xt_batch_size if 'seresnext50' in FLAGS.backbone else FLAGS.batch_size)\n fashionAI = tf.estimator.Estimator(\n model_fn=model_fn, model_dir=model_dir, config=run_config,\n params={\n 'checkpoint_path': checkpoint_path,\n 'model_dir': model_dir,\n 'checkpoint_exclude_scopes': checkpoint_exclude_scopes,\n 'model_scope': model_scope,\n 'checkpoint_model_scope': checkpoint_model_scope,\n 'ignore_missing_vars': ignore_missing_vars,\n 'train_image_size': FLAGS.train_image_size,\n 'heatmap_size': FLAGS.heatmap_size,\n 'data_format': FLAGS.data_format,\n 'steps_per_epoch': steps_per_epoch,\n 'use_ohkm': FLAGS.use_ohkm,\n 'batch_size': (FLAGS.xt_batch_size if 'seresnext50' in FLAGS.backbone else FLAGS.batch_size),\n 'weight_decay': FLAGS.weight_decay,\n 'mse_weight': FLAGS.mse_weight,\n 'momentum': FLAGS.momentum,\n 'learning_rate': FLAGS.learning_rate,\n 'end_learning_rate': FLAGS.end_learning_rate,\n 'warmup_learning_rate': FLAGS.warmup_learning_rate,\n 'warmup_steps': FLAGS.warmup_steps,\n 'decay_boundaries': parse_comma_list(decay_boundaries),\n 'lr_decay_factors': parse_comma_list(lr_decay_factors),\n })\n\n tf.gfile.MakeDirs(model_dir)\n tf.logging.info('Starting to train model {}.'.format(model_scope))\n for _ in range(train_epochs // epochs_per_eval):\n tensors_to_log = {\n 'lr': 'learning_rate',\n 'loss': 'total_loss',\n 'mse': 'mse_loss',\n 'ne': 'ne_mertric',\n }\n\n logging_hook = tf.train.LoggingTensorHook(tensors=tensors_to_log, every_n_iter=FLAGS.log_every_n_steps, formatter=lambda dicts: '{}:'.format(model_scope) + (', '.join(['%s=%.6f' % (k, v) for k, v in dicts.items()])))\n\n # FIXME: augment error:tensorflow.python.framework.errors_impl.InvalidArgumentError: indices[0] = 0 is not in [0, 0)\n tf.logging.info('Starting a training cycle.')\n fashionAI.train(input_fn=lambda : input_pipeline(True, model_scope, epochs_per_eval), hooks=[logging_hook], max_steps=(steps_per_epoch*train_epochs))\n\n tf.logging.info('Starting to evaluate.')\n eval_results = fashionAI.evaluate(input_fn=lambda : input_pipeline(False, model_scope, 1))\n tf.logging.info(eval_results)\n tf.logging.info('Finished model {}.'.format(model_scope))\n\ndef main(_):\n # Using the Winograd non-fused algorithms provides a small performance boost.\n os.environ['TF_ENABLE_WINOGRAD_NONFUSED'] = '1'\n\n gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction = FLAGS.gpu_memory_fraction)\n sess_config = tf.ConfigProto(allow_soft_placement = True, log_device_placement = False, intra_op_parallelism_threads = FLAGS.num_cpu_threads, inter_op_parallelism_threads = FLAGS.num_cpu_threads, gpu_options = gpu_options)\n\n # Set up a RunConfig to only save checkpoints once per training cycle.\n run_config = tf.estimator.RunConfig().replace(\n save_checkpoints_secs=FLAGS.save_checkpoints_secs).replace(\n save_checkpoints_steps=None).replace(\n save_summary_steps=FLAGS.save_summary_steps).replace(\n keep_checkpoint_max=5).replace(\n tf_random_seed=FLAGS.tf_random_seed).replace(\n log_step_count_steps=FLAGS.log_every_n_steps).replace(\n session_config=sess_config)\n\n if FLAGS.seq_train:\n detail_params = {\n 'all': {\n 'model_dir' : os.path.join(FLAGS.model_dir, 'all'),\n 'train_epochs': 6,\n 'epochs_per_eval': 4,\n 'lr_decay_factors': '1, 0.5, 0.1',\n 'decay_boundaries': '3, 4',\n 'model_scope': 'all',\n 'checkpoint_path': None,\n 'checkpoint_model_scope': '',\n 'checkpoint_exclude_scopes': '',\n 'ignore_missing_vars': True,\n },\n 'blouse': {\n 'model_dir' : os.path.join(FLAGS.model_dir, 'blouse'),\n 'train_epochs': 50,\n 'epochs_per_eval': 30,\n 'lr_decay_factors': '1, 0.5, 0.1',\n 'decay_boundaries': '15, 30',\n 'model_scope': 'blouse',\n 'checkpoint_path': os.path.join(FLAGS.model_dir, 'all'),\n 'checkpoint_model_scope': 'all',\n 'checkpoint_exclude_scopes': 'blouse/feature_pyramid/conv_heatmap, blouse/global_net/conv_heatmap',\n 'ignore_missing_vars': True,\n },\n 'dress': {\n 'model_dir' : os.path.join(FLAGS.model_dir, 'dress'),\n 'train_epochs': 50,\n 'epochs_per_eval': 30,\n 'lr_decay_factors': '1, 0.5, 0.1',\n 'decay_boundaries': '15, 30',\n 'model_scope': 'dress',\n 'checkpoint_path': os.path.join(FLAGS.model_dir, 'all'),\n 'checkpoint_model_scope': 'all',\n 'checkpoint_exclude_scopes': 'dress/feature_pyramid/conv_heatmap, dress/global_net/conv_heatmap',\n 'ignore_missing_vars': True,\n },\n 'outwear': {\n 'model_dir' : os.path.join(FLAGS.model_dir, 'outwear'),\n 'train_epochs': 50,\n 'epochs_per_eval': 30,\n 'lr_decay_factors': '1, 0.5, 0.1',\n 'decay_boundaries': '15, 30',\n 'model_scope': 'outwear',\n 'checkpoint_path': os.path.join(FLAGS.model_dir, 'all'),\n 'checkpoint_model_scope': 'all',\n 'checkpoint_exclude_scopes': 'outwear/feature_pyramid/conv_heatmap, outwear/global_net/conv_heatmap',\n 'ignore_missing_vars': True,\n },\n 'skirt': {\n 'model_dir' : os.path.join(FLAGS.model_dir, 'skirt'),\n 'train_epochs': 50,\n 'epochs_per_eval': 30,\n 'lr_decay_factors': '1, 0.5, 0.1',\n 'decay_boundaries': '15, 30',\n 'model_scope': 'skirt',\n 'checkpoint_path': os.path.join(FLAGS.model_dir, 'all'),\n 'checkpoint_model_scope': 'all',\n 'checkpoint_exclude_scopes': 'skirt/feature_pyramid/conv_heatmap, skirt/global_net/conv_heatmap',\n 'ignore_missing_vars': True,\n },\n 'trousers': {\n 'model_dir' : os.path.join(FLAGS.model_dir, 'trousers'),\n 'train_epochs': 50,\n 'epochs_per_eval': 30,\n 'lr_decay_factors': '1, 0.5, 0.1',\n 'decay_boundaries': '15, 30',\n 'model_scope': 'trousers',\n 'checkpoint_path': os.path.join(FLAGS.model_dir, 'all'),\n 'checkpoint_model_scope': 'all',\n 'checkpoint_exclude_scopes': 'trousers/feature_pyramid/conv_heatmap, trousers/global_net/conv_heatmap',\n 'ignore_missing_vars': True,\n },\n }\n else:\n detail_params = {\n 'blouse': {\n 'model_dir' : os.path.join(FLAGS.model_dir, 'blouse'),\n 'train_epochs': 28,\n 'epochs_per_eval': 7,\n 'lr_decay_factors': '1, 0.5, 0.1',\n 'decay_boundaries': '10, 20',\n 'model_scope': 'blouse',\n 'checkpoint_path': os.path.join(FLAGS.data_dir, FLAGS.backbone) if FLAGS.run_on_cloud else os.path.join(FLAGS.checkpoint_path, FLAGS.backbone),\n 'checkpoint_model_scope': '',\n 'checkpoint_exclude_scopes': 'blouse/feature_pyramid, blouse/global_net',\n 'ignore_missing_vars': True,\n },\n 'dress': {\n 'model_dir' : os.path.join(FLAGS.model_dir, 'dress'),\n 'train_epochs': 28,\n 'epochs_per_eval': 7,\n 'lr_decay_factors': '1, 0.5, 0.1',\n 'decay_boundaries': '10, 20',\n 'model_scope': 'dress',\n 'checkpoint_path': os.path.join(FLAGS.data_dir, FLAGS.backbone) if FLAGS.run_on_cloud else os.path.join(FLAGS.checkpoint_path, FLAGS.backbone),\n 'checkpoint_model_scope': '',\n 'checkpoint_exclude_scopes': 'dress/feature_pyramid, dress/global_net',\n 'ignore_missing_vars': True,\n },\n 'outwear': {\n 'model_dir' : os.path.join(FLAGS.model_dir, 'outwear'),\n 'train_epochs': 28,\n 'epochs_per_eval': 7,\n 'lr_decay_factors': '1, 0.5, 0.1',\n 'decay_boundaries': '10, 20',\n 'model_scope': 'outwear',\n 'checkpoint_path': os.path.join(FLAGS.data_dir, FLAGS.backbone) if FLAGS.run_on_cloud else os.path.join(FLAGS.checkpoint_path, FLAGS.backbone),\n 'checkpoint_model_scope': '',\n 'checkpoint_exclude_scopes': 'outwear/feature_pyramid, outwear/global_net',\n 'ignore_missing_vars': True,\n },\n 'skirt': {\n 'model_dir' : os.path.join(FLAGS.model_dir, 'skirt'),\n 'train_epochs': 28,\n 'epochs_per_eval': 7,\n 'lr_decay_factors': '1, 0.5, 0.1',\n 'decay_boundaries': '10, 20',\n 'model_scope': 'skirt',\n 'checkpoint_path': os.path.join(FLAGS.data_dir, FLAGS.backbone) if FLAGS.run_on_cloud else os.path.join(FLAGS.checkpoint_path, FLAGS.backbone),\n 'checkpoint_model_scope': '',\n 'checkpoint_exclude_scopes': 'skirt/feature_pyramid, skirt/global_net',\n 'ignore_missing_vars': True,\n },\n 'trousers': {\n 'model_dir' : os.path.join(FLAGS.model_dir, 'trousers'),\n 'train_epochs': 28,\n 'epochs_per_eval': 7,\n 'lr_decay_factors': '1, 0.5, 0.1',\n 'decay_boundaries': '10, 20',\n 'model_scope': 'trousers',\n 'checkpoint_path': os.path.join(FLAGS.data_dir, FLAGS.backbone) if FLAGS.run_on_cloud else os.path.join(FLAGS.checkpoint_path, FLAGS.backbone),\n 'checkpoint_model_scope': '',\n 'checkpoint_exclude_scopes': 'trousers/feature_pyramid, trousers/global_net',\n 'ignore_missing_vars': True,\n },\n }\n model_to_train = [s.strip() for s in FLAGS.model_to_train.split(',')]\n\n for m in model_to_train:\n sub_loop(keypoint_model_fn, m, detail_params[m]['model_dir'], run_config, detail_params[m]['train_epochs'], detail_params[m]['epochs_per_eval'], detail_params[m]['lr_decay_factors'], detail_params[m]['decay_boundaries'], detail_params[m]['checkpoint_path'], detail_params[m]['checkpoint_exclude_scopes'], detail_params[m]['checkpoint_model_scope'], detail_params[m]['ignore_missing_vars'])\n\nif __name__ == '__main__':\n tf.logging.set_verbosity(tf.logging.INFO)\n tf.app.run()\n\n# 0.04473711425469029\n# blouse: 0.042138283111307795\n# dress: 0.04147867224643174\n# outwear: 0.04511445541161763\n# skirt: 0.05388678376709799\n# trousers: 0.04985801318493035\n\n"
] | [
[
"pandas.read_csv"
],
[
"tensorflow.floordiv",
"tensorflow.control_dependencies",
"tensorflow.cast",
"tensorflow.nn.l2_loss",
"tensorflow.gfile.MakeDirs",
"tensorflow.app.flags.DEFINE_string",
"tensorflow.GPUOptions",
"tensorflow.app.flags.DEFINE_boolean",
"tensorflow.estimator.RunConfig",
"tensorflow.summary.scalar",
"tensorflow.nn.depthwise_conv2d",
"tensorflow.add_n",
"numpy.clip",
"tensorflow.get_collection",
"tensorflow.app.flags.DEFINE_integer",
"tensorflow.squeeze",
"tensorflow.train.get_or_create_global_step",
"tensorflow.ConfigProto",
"tensorflow.nn.top_k",
"tensorflow.train.MomentumOptimizer",
"tensorflow.logging.set_verbosity",
"tensorflow.name_scope",
"tensorflow.trainable_variables",
"tensorflow.argmax",
"numpy.zeros",
"tensorflow.tile",
"tensorflow.app.run",
"tensorflow.floormod",
"tensorflow.gather_nd",
"tensorflow.shape",
"tensorflow.identity",
"tensorflow.exp",
"tensorflow.zeros_like",
"tensorflow.logging.info",
"tensorflow.one_hot",
"tensorflow.losses.add_loss",
"numpy.sum",
"tensorflow.reduce_max",
"scipy.misc.imresize",
"tensorflow.transpose",
"tensorflow.constant",
"tensorflow.range",
"tensorflow.losses.mean_squared_error",
"tensorflow.reshape",
"tensorflow.app.flags.DEFINE_float",
"tensorflow.estimator.EstimatorSpec",
"tensorflow.variable_scope",
"tensorflow.squared_difference",
"tensorflow.logical_and"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"0.14",
"0.15",
"1.0",
"0.19",
"0.18",
"1.2",
"0.12",
"0.10",
"0.17",
"0.16"
],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.13",
"1.5",
"1.7",
"0.12",
"1.0",
"1.2"
]
}
] |
aasensio/Lightweaver | [
"9a261e72235f05df548148da140012f40dbd1e4b",
"9a261e72235f05df548148da140012f40dbd1e4b"
] | [
"examples/plot_SimpleLineTest.py",
"lightweaver/zeeman.py"
] | [
"\"\"\"\n===============================================================\nComputing a simple NLTE 8542 line profile in a FAL C atmosphere\n===============================================================\n\"\"\"\n#%%\n# First, we import everything we need. Lightweaver is typically imported as\n# `lw`, but things like the library of model atoms and Fal atmospheres need to\n# be imported separately.\nfrom lightweaver.fal import Falc82\nfrom lightweaver.rh_atoms import H_6_atom, C_atom, O_atom, Si_atom, Al_atom, \\\nCaII_atom, Fe_atom, He_9_atom, He_atom, MgII_atom, N_atom, Na_atom, S_atom\nimport lightweaver as lw\nimport matplotlib.pyplot as plt\nimport time\nimport numpy as np\n\n\n#%%\n# Now, we define the functions that will be used in our spectral synthesise.\n# First `synth_8542` which synthesises and returns the line given by an\n# atmosphere.\ndef synth_8542(atmos, conserve, useNe, wave):\n '''\n Synthesise a spectral line for given atmosphere with different\n conditions.\n\n Parameters\n ----------\n atmos : lw.Atmosphere\n The atmospheric model in which to synthesise the line.\n conserve : bool\n Whether to start from LTE electron density and conserve charge, or\n simply use from the electron density present in the atomic model.\n useNe : bool\n Whether to use the electron density present in the model as the\n starting solution, or compute the LTE electron density.\n wave : np.ndarray\n Array of wavelengths over which to resynthesise the final line\n profile for muz=1.\n\n Returns\n -------\n ctx : lw.Context\n The Context object that was used to compute the equilibrium\n populations.\n Iwave : np.ndarray\n The intensity at muz=1 for each wavelength in `wave`.\n '''\n # Configure the atmospheric angular quadrature\n atmos.quadrature(5)\n # Configure the set of atomic models to use.\n aSet = lw.RadiativeSet([H_6_atom(), C_atom(), O_atom(), Si_atom(),\n Al_atom(), CaII_atom(), Fe_atom(), He_9_atom(),\n MgII_atom(), N_atom(), Na_atom(), S_atom()\n ])\n # Set H and Ca to \"active\" i.e. NLTE, everything else participates as an\n # LTE background.\n aSet.set_active('H', 'Ca')\n # Compute the necessary wavelength dependent information (SpectrumConfiguration).\n spect = aSet.compute_wavelength_grid()\n\n # Either compute the equilibrium populations at the fixed electron density\n # provided in the model, or iterate an LTE electron density and compute the\n # corresponding equilibrium populations (SpeciesStateTable).\n if useNe:\n eqPops = aSet.compute_eq_pops(atmos)\n else:\n eqPops = aSet.iterate_lte_ne_eq_pops(atmos)\n\n # Configure the Context which holds the state of the simulation for the\n # backend, and provides the python interface to the backend.\n # Feel free to increase Nthreads to increase the number of threads the\n # program will use.\n ctx = lw.Context(atmos, spect, eqPops, conserveCharge=conserve, Nthreads=1)\n start = time.time()\n # Iterate the Context to convergence\n iterate_ctx(ctx)\n end = time.time()\n print('%.2f s' % (end - start))\n # Update the background populations based on the converged solution and\n # compute the final intensity for mu=1 on the provided wavelength grid.\n eqPops.update_lte_atoms_Hmin_pops(atmos)\n Iwave = ctx.compute_rays(wave, [atmos.muz[-1]], stokes=False)\n return ctx, Iwave\n\ndef iterate_ctx(ctx, Nscatter=3, NmaxIter=500):\n '''\n Iterate a Context to convergence.\n '''\n for i in range(NmaxIter):\n # Compute the formal solution\n dJ = ctx.formal_sol_gamma_matrices()\n # Just update J for Nscatter iterations\n if i < Nscatter:\n continue\n # Update the active populations under statistical equilibrium,\n # conserving charge if this option was set on the Context.\n delta = ctx.stat_equil()\n\n # If we are converged in both relative change of J and populations,\n # then print a message and return\n # N.B. as this is just a simple case, there is no checking for failure\n # to converge within the NmaxIter. This could be achieved simpy with an\n # else block after this for.\n if dJ < 3e-3 and delta < 1e-3:\n print('%d iterations' % i)\n print('-'*80)\n return\n\n\n#%%\n# The wavelength grid to output the final synthesised line on.\nwave = np.linspace(853.9444, 854.9444, 1001)\n\n#%%\n# Load an lw.Atmosphere object containing the FAL C atmosphere with 82 points\n# in depth, before synthesising the Ca II 8542 \\AA line profile using:\n#\n# - The given electron density.\n# - The electron density charge conserved from a starting LTE solution.\n# - The LTE electron density.\n#\n# These results are then plotted.\n\natmosRef = Falc82()\nctxRef, IwaveRef = synth_8542(atmosRef, conserve=False, useNe=True, wave=wave)\natmosCons = Falc82()\nctxCons, IwaveCons = synth_8542(atmosCons, conserve=True, useNe=False, wave=wave)\natmosLte = Falc82()\nctx, IwaveLte = synth_8542(atmosLte, conserve=False, useNe=False, wave=wave)\n\nplt.plot(wave, IwaveRef, label='Reference FAL')\nplt.plot(wave, IwaveCons, label='Reference Cons')\nplt.plot(wave, IwaveLte, label='Reference LTE n_e')\nplt.show()\n",
"import numpy as np\nfrom typing import Optional, cast, Iterator, TYPE_CHECKING\nfrom fractions import Fraction\nfrom dataclasses import dataclass\n\nif TYPE_CHECKING:\n from .atomic_model import AtomicLine\n\ndef fraction_range(start: Fraction, stop: Fraction,\n step: Fraction=Fraction(1,1)) -> Iterator[Fraction]:\n '''\n Works like range, but with Fractions. Does no checking, so best to make\n sure the range you're asking for is sane and divides down properly.\n '''\n while start < stop:\n yield start\n start += step\n\n@dataclass\nclass ZeemanComponents:\n '''\n Storage for communicating the Zeeman components between functions, also\n shared with the backend, giving a slightly tighter contract than usual:\n all arrays must be contiguous and alpha must be of dtype np.int32.\n '''\n alpha: np.ndarray\n strength: np.ndarray\n shift: np.ndarray\n\ndef zeeman_strength(Ju: Fraction, Mu: Fraction, Jl: Fraction, Ml: Fraction) -> float:\n '''\n Computes the strength of a Zeeman component, following del Toro Iniesta\n (p. 137) albeit larger by a factor of 2 which is corrected by\n normalisation.\n Takes J upper and lower (u and l respectively), and M upper and lower.\n '''\n alpha = int(Ml - Mu)\n dJ = int(Ju - Jl)\n\n # These parameters are x2 those in del Toro Iniesta (p. 137), but we normalise after the fact, so it's fine\n\n if dJ == 0: # jMin = ju = jl\n if alpha == 0: # pi trainsitions\n s = 2.0 * Mu**2\n elif alpha == -1: # sigma_b transitions\n s = (Ju + Mu) * (Ju - Mu + 1.0)\n elif alpha == 1: # sigma_r transitions\n s = (Ju - Mu) * (Ju + Mu + 1.0)\n elif dJ == 1: # jMin = jl, Mi = Ml\n if alpha == 0: # pi trainsitions\n s = 2.0 * ((Jl + 1)**2 - Ml**2)\n elif alpha == -1: # sigma_b transitions\n s = (Jl + Ml + 1) * (Jl + Ml + 2.0)\n elif alpha == 1: # sigma_r transitions\n s = (Jl - Ml + 1.0) * (Jl - Ml + 2.0)\n elif dJ == -1: # jMin = ju, Mi = Mu\n if alpha == 0: # pi trainsitions\n s = 2.0 * ((Ju + 1)**2 - Mu**2)\n elif alpha == -1: # sigma_b transitions\n s = (Ju - Mu + 1) * (Ju - Mu + 2.0)\n elif alpha == 1: # sigma_r transitions\n s = (Ju + Mu + 1.0) * (Ju + Mu + 2.0)\n else:\n raise ValueError('Invalid dJ: %d' % dJ)\n\n return float(s)\n\ndef lande_factor(J: Fraction, L: int, S: Fraction) -> float:\n '''\n Computes the Lande g-factor for an atomic level from the J, L, and S\n quantum numbers.\n '''\n if J == 0.0:\n return 0.0\n return float(1.5 + (S * (S + 1.0) - L * (L + 1)) / (2.0 * J * (J + 1.0)))\n\ndef effective_lande(line: 'AtomicLine'):\n '''\n Computes the effective Lande g-factor for an atomic line.\n '''\n if line.gLandeEff is not None:\n return line.gLandeEff\n\n i = line.iLevel\n j = line.jLevel\n if any(x is None for x in [i.J, i.L, i.S, j.J, j.L, j.S]):\n raise ValueError('Cannot compute gLandeEff as gLandeEff not set and some of J, L and S None for line %s'%repr(line))\n gL = lande_factor(i.J, i.L, i.S) # type: ignore\n gU = lande_factor(j.J, j.L, j.S) # type: ignore\n\n return 0.5 * (gU + gL) + \\\n 0.25 * (gU - gL) * (j.J * (j.J + 1.0) - i.J * (i.J + 1.0)) # type: ignore\n\ndef compute_zeeman_components(line: 'AtomicLine') -> Optional[ZeemanComponents]:\n '''\n Computes, if possible, the set of Zeeman components for an atomic line.\n\n If gLandeEff is specified on the line, then basic three-component Zeeman\n splitting will be computed directly.\n Otherwise, if both the lower and upper levels of the line support\n LS-coupling (i.e. J, L, and S all specified, and J <= L + S), then the\n LS-coupling formalism is applied to compute the components of \"anomalous\"\n Zeeman splitting.\n If neither of these cases are fulfilled, then None is returned.\n\n Parameters\n ----------\n line : AtomicLine\n The line to attempt to compute the Zeeman components from.\n\n Returns\n -------\n components : ZeemanComponents or None\n The Zeeman splitting components, if possible.\n '''\n # NOTE(cmo): Just do basic three-component Zeeman splitting if an effective\n # Lande g-factor is specified on the line.\n if line.gLandeEff is not None:\n alpha = np.array([-1, 0, 1], dtype=np.int32)\n strength = np.ones(3)\n shift = alpha * line.gLandeEff\n return ZeemanComponents(alpha, strength, shift)\n\n # NOTE(cmo): Do LS coupling (\"anomalous\" Zeeman splitting)\n if line.iLevel.lsCoupling and line.jLevel.lsCoupling:\n # Mypy... you're a pain sometimes... (even if you are technically correct)\n Jl = cast(Fraction, line.iLevel.J)\n Ll = cast(int, line.iLevel.L)\n Sl = cast(Fraction, line.iLevel.S)\n Ju = cast(Fraction, line.jLevel.J)\n Lu = cast(int, line.jLevel.L)\n Su = cast(Fraction, line.jLevel.S)\n\n gLl = lande_factor(Jl, Ll, Sl)\n gLu = lande_factor(Ju, Lu, Su)\n alpha = []\n strength = []\n shift = []\n norm = np.zeros(3)\n\n for ml in fraction_range(-Jl, Jl+1):\n for mu in fraction_range(-Ju, Ju+1):\n if abs(ml - mu) <= 1.0:\n alpha.append(int(ml - mu))\n shift.append(gLl*ml - gLu*mu)\n strength.append(zeeman_strength(Ju, mu, Jl, ml))\n norm[alpha[-1]+1] += strength[-1]\n alpha = np.array(alpha, dtype=np.int32)\n strength = np.array(strength)\n shift = np.array(shift)\n strength /= norm[alpha + 1]\n\n return ZeemanComponents(alpha, strength, shift)\n return None"
] | [
[
"matplotlib.pyplot.plot",
"matplotlib.pyplot.show",
"numpy.linspace"
],
[
"numpy.array",
"numpy.zeros",
"numpy.ones"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
satishjasthi/convnet-study | [
"ccd20c90e449fc8db694abf706db178e9413e57b"
] | [
"rme/datasets/mnist.py"
] | [
"from __future__ import absolute_import\n\nimport os\nimport numpy as np\nimport gzip\nimport struct\n\nfrom .preprocessing import one_hotify\n\ndef load(data_dir, valid_ratio=0.0, one_hot=True, shuffle=False, dtype='float32'):\n\n train_set, valid_set, test_set = {}, {}, {}\n # Get data from binary files\n for img_set, file_name in zip((train_set, test_set), ('train', 't10k')):\n # Load images\n img_path = os.path.join(data_dir, file_name + '-images-idx3-ubyte.gz')\n with gzip.open(img_path, 'rb') as f:\n magic_num, num_imgs, num_rows, num_cols = struct.unpack('>iiii',\n f.read(16))\n shape = (num_imgs, num_rows, num_cols, 1)\n img_set['data'] = np.fromstring(f.read(),\n dtype='uint8').astype(dtype).reshape(shape)\n\n # Load labels\n label_path = os.path.join(data_dir, file_name + '-labels-idx1-ubyte.gz')\n with gzip.open(label_path, 'rb') as f:\n magic_num, num_labels = struct.unpack('>ii', f.read(8))\n img_set['labels'] = np.fromstring(f.read(),\n dtype='uint8').astype('int')\n if one_hot:\n img_set['labels'] = one_hotify(img_set['labels'])\n\n N = train_set['data'].shape[0]\n if shuffle:\n # Shuffle and separate between training and validation set\n new_order = np.random.permutation(np.arange(N))\n train_set['data'] = train_set['data'][new_order]\n train_set['labels'] = train_set['labels'][new_order]\n\n # Get the number of samples on the training set\n M = int((1 - valid_ratio)*N)\n # Separate validation set\n valid_set['data'] = train_set['data'][M:]\n valid_set['labels'] = train_set['labels'][M:]\n train_set['data'] = train_set['data'][:M]\n train_set['labels'] = train_set['labels'][:M]\n\n return train_set, valid_set, test_set\n\ndef preprocess(dataset):\n mean = 33.3\n std = 78.6\n\n dataset -= mean\n dataset /= std\n\n return dataset\n"
] | [
[
"numpy.arange"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Giorgiobientinesi/Workshop2 | [
"f454499d4befdb705b4672be25d8698ef2b37116"
] | [
"Model.py"
] | [
"import pandas as pd\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.metrics import mean_absolute_error\n\n\ndf = pd.read_csv(\"Airbnb-cleaned.csv\")\ndf.columns\ndel df[\"Unnamed: 0\"]\n\ndf1 = df[['neighbourhood', 'property_type', 'room_type']]\n# IMPORT ENCODER\nfrom sklearn.preprocessing import OneHotEncoder\n\n# FIT ENCODER ON THE ORIGINAL DATASET TO MAKE IT REMEMBER CATEGORIES\nenc = OneHotEncoder(sparse=False)\nenc.fit(df1)\n\n\n\ndf[\"neighbourhood\"].unique()\n\ndf[['Bijlmer-Oost', 'Noord-Oost', 'Noord-West', 'Oud-Noord',\n 'IJburg - Zeeburgereiland', 'Centrum-West',\n 'Oostelijk Havengebied - Indische Buurt', 'Centrum-Oost',\n 'Oud-Oost', 'Watergraafsmeer', 'Gaasperdam - Driemond',\n 'Westerpark', 'Bijlmer-Centrum', 'De Pijp - Rivierenbuurt', 'Zuid',\n 'Buitenveldert - Zuidas', 'De Baarsjes - Oud-West',\n 'Bos en Lommer', 'Geuzenveld - Slotermeer', 'Slotervaart',\n 'Osdorp', 'De Aker - Nieuw Sloten',\n 'Apartment', 'Bed & Breakfast', 'House',\n 'Entire home/apt', 'Private room', 'Shared room']] = enc.transform(\n df1[[\"neighbourhood\", \"property_type\", \"room_type\"]])\n\n\ndf = df.drop([\"neighbourhood\", \"property_type\", \"room_type\"], axis =1)\ndf[\"Distance_from_center(m)\"] = df[\"Distance_from_center(m)\"]/1000\n\ny = df['price']\ndata = df.drop(['price'], axis=1)\nX_train, X_test, y_train, y_test = train_test_split(data, y, test_size=0.2, random_state=7)\nmodel = RandomForestRegressor()\nmodel.fit(X_train,y_train)\npred = model.predict(X_test)\n\nmean_absolute_error(y_test, pred)\n\n\nfrom joblib import dump, load\ndump(model, 'Airbnb.joblib')\n\n\n\n"
] | [
[
"sklearn.ensemble.RandomForestRegressor",
"pandas.read_csv",
"sklearn.metrics.mean_absolute_error",
"sklearn.preprocessing.OneHotEncoder",
"sklearn.model_selection.train_test_split"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
DiamondLightSource/SuRVoS2 | [
"42bacfb6a5cc267f38ca1337e51a443eae1a9d2b"
] | [
"survos2/improc/regions/ccl.py"
] | [
"import logging\r\n\r\nimport os.path as op\r\n\r\nimport numpy as np\r\n\r\nimport pycuda.driver as cuda\r\nimport pycuda.gpuarray as gpuarray\r\nimport pycuda.autoinit\r\nfrom pycuda.compiler import SourceModule\r\n\r\nfrom ..improc_types import int3\r\nfrom ..utils import gpuregion, cpuregion\r\nfrom ..cuda import asgpuarray, grid_kernel_config\r\n\r\nfrom ._ccl import _remap, _relabel2d, _relabel3d, _merge_small3d\r\n\r\n\r\n__dirname__ = op.dirname(__file__)\r\n\r\n\r\n@gpuregion\r\ndef ccl3d(labels, remap=True):\r\n assert labels.ndim == 3\r\n assert labels.dtype == np.uint32\r\n\r\n with open(op.join(__dirname__, \"kernels\", \"ccl3d.cu\"), \"r\") as f:\r\n _mod_conv = SourceModule(f.read())\r\n gpu_ccl_local = _mod_conv.get_function(\"uf_local\")\r\n gpu_ccl_global = _mod_conv.get_function(\"uf_global\")\r\n gpu_ccl_final = _mod_conv.get_function(\"uf_final\")\r\n\r\n labels_gpu = asgpuarray(labels, dtype=np.uint32)\r\n result_gpu = gpuarray.zeros_like(labels_gpu)\r\n shape = np.asarray(tuple(labels.shape[::-1]), dtype=int3)\r\n\r\n block, grid = grid_kernel_config(gpu_ccl_local, labels.shape)\r\n shared = int(np.prod(block) * 8)\r\n\r\n gpu_ccl_local(labels_gpu, result_gpu, shape, block=block, grid=grid, shared=shared)\r\n gpu_ccl_global(labels_gpu, result_gpu, shape, block=block, grid=grid)\r\n gpu_ccl_final(result_gpu, shape, block=block, grid=grid)\r\n\r\n if remap:\r\n return remap_labels(result_gpu.get())\r\n\r\n return result_gpu\r\n\r\n\r\ndef remap_labels(labels):\r\n assert labels.dtype == np.uint32\r\n new_labels = _remap(labels.ravel())\r\n new_labels.shape = labels.shape\r\n return new_labels\r\n\r\n\r\ndef relabel(labels):\r\n assert labels.dtype == np.uint32\r\n\r\n if labels.ndim == 2:\r\n new_labels = _relabel2d(labels.ravel(), labels.shape[1])\r\n elif labels.ndim == 3:\r\n new_labels = _relabel3d(labels.ravel(), labels.shape[1], labels.shape[2])\r\n else:\r\n raise ValueError(\r\n \"Input array has to be 2 or 3 dimensional: {}\".format(labels.ndim)\r\n )\r\n\r\n new_labels.shape = labels.shape\r\n return new_labels\r\n\r\n\r\n@cpuregion\r\ndef merge_small(data, labels, min_size=1, **kwargs):\r\n if data.ndim != labels.ndim + 1:\r\n data = data[..., None]\r\n assert data.ndim == labels.ndim + 1\r\n return _merge_small3d(data, labels, labels.max() + 1, min_size)\r\n"
] | [
[
"numpy.prod"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
SamuelWiqvist/snpla | [
"9d586c5d09de3eecd2536485af6fc28a915443e4"
] | [
"mv_gaussian/low_dim_w_summary_stats/run_script_snpla.py"
] | [
"# Imports\nimport sys\nimport torch\nimport os\nimport time\nimport numpy as np\nfrom torch.distributions.multivariate_normal import MultivariateNormal\n\n# Initial set up\nlunarc = int(sys.argv[1])\ndim = int(sys.argv[2])\nseed = int(sys.argv[3])\nseed_data = int(sys.argv[4])\nhp_tuning = int(sys.argv[5]) # if hp_tuning = 0, no hyper-param tuning, else hp_tuning for that sample of the hp\nlambda_val = float(sys.argv[6]) # if hp_tuning = 0, no hyper-param tuning, else hp_tuning for that sample of the hp\n\nprint(\"Input args:\")\nprint(\"Dim: \" + str(dim))\nprint(\"seed: \" + str(seed))\nprint(\"seed_data: \" + str(seed_data))\n\n\nid_job = str(dim) + '_' + str(seed) + '_' + str(seed_data)\n\nif hp_tuning > 0:\n id_job = id_job + \"_\" + str(hp_tuning)\n\nif lambda_val > 0:\n id_job = id_job + \"_\" + str(lambda_val)\n\n# Set wd\nprint(os.getcwd())\n\n# set the wd to the base folder for the project\nif lunarc == 1:\n os.chdir('/home/samwiq/snpla/seq-posterior-approx-w-nf-dev')\nelse:\n os.chdir('/home/samuel/Documents/projects/seq posterior approx w nf/seq posterior approx w nf dev')\n\nsys.path.append('./')\n\nprint(os.getcwd())\n\n# Load all utility functions for all methods\nimport mv_gaussian.low_dim_w_summary_stats.functions as func\nimport algorithms.snpla as snpla\n\n# Set model and generate data\n\nx_o, conj_model, analytical_posterior = func.set_up_model(seed)\n\n# set up posterior network\nflow_lik, flow_post = func.set_up_networks()\n\n## Generate test data\n\nN_prior_pred_test = 1000\nx_test, theta_test = func.run_model_sim(N_prior_pred_test, seed + 2, conj_model, analytical_posterior,\n conj_model.model.covariance_matrix, dim, True)\n\n# Generate test data for obs data set\nprint(conj_model.model_sim(theta_test).shape)\n\n\nN_test_obs_data = 1000\n\nx_test_obs_data = torch.zeros(N_test_obs_data, 5)\ntheta_test_obs_data = torch.zeros(N_test_obs_data, dim)\n\nfor i in range(N_test_obs_data):\n\n x_test_obs_data[i, :] = func.calc_summary_stats(x_o)\n theta_test_obs_data[i, :] = conj_model.model.loc\n\n# Set up networks for the likelihood model\n\n# Base dist for posterior model\nflow_lik, flow_post = func.set_up_networks()\n\nhyper_params = [0.001, 0.002, 0.95, 0.7] # lr_like, lr_post, gamma_post, gamma\n\nif lambda_val > 0:\n hyper_params[-1] = lambda_val\n\n\nif hp_tuning >= 2:\n hyper_params = func.sample_hp(\"snpla\", hp_tuning)\n\noptimizer_lik = torch.optim.Adam(flow_lik.parameters(), lr=hyper_params[0])\noptimizer_post = torch.optim.Adam(flow_post.parameters(), lr=hyper_params[1])\ndecay_rate_post = hyper_params[2] # no adaptation of Adam's base rate\n\nnbr_rounds = 10\nprob_prior_decay_rate = hyper_params[3]\nprob_prior = snpla.calc_prob_prior(nbr_rounds, prob_prior_decay_rate)\n\nprint(prob_prior)\n\n#nbr_lik = [2000, 2000, 2000, 2000]\n#nbr_epochs_lik = [25, 25, 25, 25]\n#batch_size = 50\n#batch_size_post = 50\n#nbr_post = [10000, 10000, 10000, 10000]\n#nbr_epochs_post = [25, 25, 25, 25]\n\n\nnbr_lik = [2500 for _ in range(nbr_rounds)] # [1000, 1000, 1000, 1000, 1000] # , 2000, 2000]\nnbr_epochs_lik = [75 for _ in range(nbr_rounds)] # [100, 100, 100, 100, 100]\nbatch_size = 50\nbatch_size_post = 1000\nnbr_post = [10000 for _ in range(nbr_rounds)] # [10000, 10000, 10000, 10000, 10000] # , 10000, 10000]\nnbr_epochs_post = [75 for _ in range(nbr_rounds)] # [50, 50, 50, 50, 50, 50]\n\n\nx_o_batch_post = torch.zeros(batch_size_post, 5)\n\nfor i in range(batch_size_post):\n x_o_batch_post[i, :] = func.calc_summary_stats(x_o)\n\ntorch.manual_seed(seed)\nnp.random.seed(seed)\ntorch.backends.cudnn.deterministic = True\ntorch.backends.cudnn.benchmark = False\n\nstart = time.time()\n\n# TODO check prior and simulator\nmodels_lik, models_post = snpla.inference_snpla(flow_lik,\n flow_post,\n conj_model.prior,\n conj_model.model_sim,\n optimizer_lik,\n optimizer_post,\n decay_rate_post,\n func.calc_summary_stats(x_o),\n x_o_batch_post,\n dim,\n prob_prior,\n nbr_lik,\n nbr_epochs_lik,\n nbr_post,\n nbr_epochs_post,\n batch_size,\n batch_size_post)\n\nend = time.time()\nrun_time = end - start\n\nprint(\"\")\nprint(\"Runtime:\" + str(round(run_time, 2)))\n\nkl_divs_trained = []\nstart = time.time()\ntorch.manual_seed(seed)\n\nfor i in range(nbr_rounds):\n print(i)\n posterior_sample = models_post[i].sample(1000, context=func.calc_summary_stats(x_o))\n posterior_sample = posterior_sample.reshape((1000, 2))\n\n kl_divs_trained.append(conj_model.kl_div(analytical_posterior, posterior_sample))\n\n if hp_tuning == 0 and lambda_val > 0:\n\n np.savetxt('mv_gaussian/low_dim_w_summary_stats/lambda_val/post_samples_snpla_' + str(i + 1) + \"_\" + id_job + '.csv',\n posterior_sample.detach().numpy(), delimiter=\",\")\n\n elif hp_tuning == 0:\n\n np.savetxt('mv_gaussian/low_dim_w_summary_stats/data/post_samples_snpla_' + str(i + 1) + \"_\" + id_job + '.csv',\n posterior_sample.detach().numpy(), delimiter=\",\")\n\n else:\n\n np.savetxt('mv_gaussian/low_dim_w_summary_stats/hp_tuning/post_samples_snpla_' + str(i + 1) + \"_\" + id_job + '.csv',\n posterior_sample.detach().numpy(), delimiter=\",\")\n\nend = time.time()\nrun_time_inference = (end - start) / nbr_rounds\n\nif hp_tuning == 0 and lambda_val > 0:\n\n with open('mv_gaussian/low_dim_w_summary_stats/lambda_val/snpla_' + id_job + '.txt', 'w') as f:\n for h in hyper_params:\n f.write('%.6f\\n' % h)\n for p in prob_prior:\n f.write('%.6f\\n' % p)\n f.write('%.4f\\n' % run_time)\n f.write('%.4f\\n' % run_time_inference)\n for i in range(nbr_rounds):\n f.write('%.4f\\n' % kl_divs_trained[i])\n\n\nelif hp_tuning == 0:\n\n with open('mv_gaussian/low_dim_w_summary_stats/results/snpla_' + id_job + '.txt', 'w') as f:\n f.write('%.4f\\n' % run_time)\n f.write('%.4f\\n' % run_time_inference)\n for i in range(nbr_rounds):\n f.write('%.4f\\n' % kl_divs_trained[i])\n\nelse:\n\n with open('mv_gaussian/low_dim_w_summary_stats/hp_tuning/snpla_' + id_job + '.txt', 'w') as f:\n f.write('%.4f\\n' % hp_tuning)\n for h in hyper_params:\n f.write('%.6f\\n' % h)\n f.write('%.4f\\n' % run_time)\n f.write('%.4f\\n' % run_time_inference)\n for i in range(nbr_rounds):\n f.write('%.4f\\n' % kl_divs_trained[i])\n\nif hp_tuning == 0:\n # Inference\n\n # Sample data from post pred\n N_post_pred_test = 1000\n x_post_pred, theta_post_pred = func.run_model_sim(N_post_pred_test, seed + 3, conj_model, analytical_posterior,\n conj_model.model.covariance_matrix, dim, False)\n\n torch.manual_seed(seed)\n x_prior = flow_lik.sample(1, context=theta_test)\n x_theta_true = flow_lik.sample(1, context=theta_test_obs_data)\n x_post = flow_lik.sample(1, context=theta_post_pred)\n\n x_prior = x_prior.reshape(x_test.shape)\n x_theta_true = x_theta_true.reshape(x_test_obs_data.shape)\n x_post = x_post.reshape(x_post_pred.shape)\n\n\n # Write results\n np.savetxt('mv_gaussian/low_dim_w_summary_stats/data/data_recon_snpla_' + id_job +\n '.csv', x_theta_true.detach().numpy(), delimiter=\",\")\n\n np.savetxt('mv_gaussian/low_dim_w_summary_stats/data/data_recon_prior_snpla_' + id_job + '.csv',\n x_prior.detach().numpy(), delimiter=\",\")\n\n np.savetxt('mv_gaussian/low_dim_w_summary_stats/data/data_recon_post_snpla_' + id_job + '.csv',\n x_post.detach().numpy(), delimiter=\",\")\n"
] | [
[
"torch.manual_seed",
"numpy.random.seed",
"torch.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
victor-estrade/SystGradDescent | [
"822e7094290301ec47a99433381a8d6406798aff",
"822e7094290301ec47a99433381a8d6406798aff",
"822e7094290301ec47a99433381a8d6406798aff",
"822e7094290301ec47a99433381a8d6406798aff"
] | [
"model/summaries.py",
"benchmark/VAR/HIGGSTES/DA.py",
"benchmark/HARDGG/TP-Calib.py",
"benchmark/HIGGS/TP-Prior.py"
] | [
"# coding: utf-8\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport numpy as np\n\nDEFAULT_N_BINS = 10\n\ndef compute_summaries(clf, X, W, n_bins=DEFAULT_N_BINS):\n proba = clf.predict_proba(X)\n count, _ = np.histogram(proba[:, 1], range=(0., 1.), weights=W, bins=n_bins)\n return count\n\n\nclass ClassifierSummaryComputer():\n def __init__(self, clf, n_bins=DEFAULT_N_BINS):\n self.clf = clf\n self.n_bins = n_bins\n\n def __call__(self, X, W):\n proba = self.clf.predict_proba(X)\n count, _ = np.histogram(proba[:, 1], range=(0., 1.), weights=W, bins=self.n_bins)\n return count\n\n\n\nclass HistogramSummaryComputer():\n def __init__(self, n_bins=DEFAULT_N_BINS):\n self.n_bins = n_bins\n\n def fit(self, X):\n self.edges_list = []\n for i in range(X.shape[1]):\n x = X[:, i]\n maximum = np.max(x)\n minimum = np.min(x)\n diff = maximum - minimum\n maximum = maximum + diff / self.n_bins # be a bit more inclusive\n minimum = minimum - diff / self.n_bins # be a bit more inclusive\n count, bin_edges = np.histogram(x, range=(minimum, maximum), bins=self.n_bins)\n self.edges_list.append(bin_edges)\n return self\n\n def predict(self, X, W):\n counts = [] \n for i, bin_edges in enumerate(self.edges_list):\n x = X[:, i]\n count, _ = np.histogram(x, bins=bin_edges, weights=W)\n counts.extend(count)\n return counts\n\n def __call__(self, X, W):\n counts = self.predict(X, W)\n return np.array(counts)\n",
"#!/usr/bin/env python\n# coding: utf-8\nfrom __future__ import print_function\nfrom __future__ import division\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\n# Command line :\n# python -m benchmark.VAR.GG.DA\n\nimport os\nimport logging\nfrom config import SEED\nfrom config import _ERROR\nfrom config import _TRUTH\n\nimport numpy as np\nimport pandas as pd\n\nfrom visual.misc import set_plot_config\nset_plot_config()\n\nfrom utils.log import set_logger\nfrom utils.log import flush\nfrom utils.log import print_line\nfrom utils.model import get_model\nfrom utils.model import get_optimizer\nfrom utils.model import train_or_load_data_augmentation\nfrom utils.evaluation import evaluate_summary_computer\nfrom utils.images import gather_images\n\nfrom visual.misc import plot_params\n\nfrom problem.higgs import HiggsConfigTesOnly as Config\nfrom problem.higgs import get_generators_torch\nfrom problem.higgs import param_generator\nfrom problem.higgs import GeneratorCPU\nfrom problem.higgs import HiggsNLL as NLLComputer\n\nfrom model.neural_network import NeuralNetClassifier\nfrom model.summaries import ClassifierSummaryComputer\nfrom ...my_argparser import NET_parse_args\n\nfrom archi.classic import L4 as ARCHI\n\nfrom .common import measurement\n\n\nDATA_NAME = 'HIGGSTES'\nBENCHMARK_NAME = 'VAR-'+DATA_NAME\nN_ITER = 30\nN_AUGMENT = 5\n\ndef build_model(args, i_cv):\n args.net = ARCHI(n_in=29, n_out=2, n_unit=args.n_unit)\n args.optimizer = get_optimizer(args)\n model = get_model(args, NeuralNetClassifier)\n model.base_name = \"DataAugmentation\"\n model.set_info(DATA_NAME, BENCHMARK_NAME, i_cv)\n return model\n\n\nclass TrainGenerator:\n def __init__(self, param_generator, data_generator, n_bunch=1000):\n self.param_generator = param_generator\n self.data_generator = data_generator\n self.n_bunch = n_bunch\n self.n_samples = data_generator.n_samples\n\n def generate(self, n_samples):\n n_bunch_samples = n_samples // self.n_bunch\n params = [self.param_generator().clone_with(mix=0.5) for i in range(self.n_bunch)]\n data = [self.data_generator.generate(*parameters, n_samples=n_bunch_samples) for parameters in params]\n X = np.concatenate([X for X, y, w in data], axis=0)\n y = np.concatenate([y for X, y, w in data], axis=0)\n w = np.concatenate([w for X, y, w in data], axis=0)\n return X, y, w\n\n\n# =====================================================================\n# MAIN\n# =====================================================================\ndef main():\n # BASIC SETUP\n logger = set_logger()\n args = NET_parse_args(main_description=\"Training launcher for Gradient boosting on S3D2 benchmark\")\n logger.info(args)\n flush(logger)\n # INFO\n model = build_model(args, -1)\n os.makedirs(model.results_directory, exist_ok=True)\n # RUN\n logger.info(f'Running runs [{args.start_cv},{args.end_cv}[')\n results = [run(args, i_cv) for i_cv in range(args.start_cv, args.end_cv)]\n results = pd.concat(results, ignore_index=True)\n # EVALUATION\n results.to_csv(os.path.join(model.results_directory, 'fisher.csv'))\n print(results)\n print(\"DONE !\")\n\n\ndef run(args, i_cv):\n logger = logging.getLogger()\n print_line()\n logger.info('Running iter n°{}'.format(i_cv))\n print_line()\n\n\n # LOAD/GENERATE DATA\n logger.info('Set up data generator')\n config = Config()\n seed = SEED + i_cv * 5\n train_generator, valid_generator, test_generator = get_generators_torch(seed, cuda=args.cuda)\n train_generator = GeneratorCPU(train_generator)\n train_generator = TrainGenerator(param_generator, train_generator)\n valid_generator = GeneratorCPU(valid_generator)\n test_generator = GeneratorCPU(test_generator)\n\n # SET MODEL\n logger.info('Set up classifier')\n model = build_model(args, i_cv)\n os.makedirs(model.results_path, exist_ok=True)\n flush(logger)\n\n # TRAINING / LOADING\n train_or_load_data_augmentation(model, train_generator, train_generator.n_samples*N_AUGMENT, retrain=args.retrain)\n\n\n # MEASUREMENT\n results = measurement(model, i_cv, config, valid_generator, test_generator)\n print(results)\n return results\n\nif __name__ == '__main__':\n main()\n",
"#!/usr/bin/env python\n# coding: utf-8\nfrom __future__ import print_function\nfrom __future__ import division\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\n# Command line :\n# python -m benchmark.HARDGG.TP-Calib\n\nimport os\nimport logging\nfrom config import SEED\nfrom config import _ERROR\nfrom config import _TRUTH\n\nimport numpy as np\nimport pandas as pd\n\nfrom visual.misc import set_plot_config\nset_plot_config()\n\nfrom ..common import load_estimations\nfrom ..common import load_conditional_estimations\nfrom utils.log import set_logger\nfrom utils.log import flush\nfrom utils.log import print_line\nfrom utils.model import get_model\nfrom utils.model import get_optimizer\nfrom utils.model import train_or_load_neural_net\nfrom utils.evaluation import evaluate_neural_net\nfrom utils.evaluation import evaluate_classifier\nfrom utils.evaluation import evaluate_summary_computer\nfrom utils.evaluation import evaluate_config\nfrom utils.evaluation import evaluate_minuit\nfrom utils.evaluation import evaluate_estimator\nfrom utils.evaluation import evaluate_conditional_estimation\nfrom utils.images import gather_images\n\nfrom visual.misc import plot_params\n\nfrom problem.gamma_gauss.torch import GeneratorTorch\nfrom problem.gamma_gauss import GGConfig as Config\nfrom problem.gamma_gauss import get_minimizer\nfrom problem.gamma_gauss import get_minimizer_no_nuisance\nfrom problem.gamma_gauss import HardGenerator as Generator\nfrom problem.gamma_gauss import Parameter\nfrom problem.gamma_gauss import GGNLL as NLLComputer\n\nfrom visual.special.gamma_gauss import plot_nll_around_min\n\nfrom model.tangent_prop import TangentPropClassifier\nfrom model.regressor import Regressor\nfrom archi.classic import L4 as ARCHI\n\nfrom ..my_argparser import TP_parse_args\n\nfrom archi.reducer import A3ML3 as CALIB_ARCHI\n# from archi.reducer import EA1AR8MR8L1 as CALIB_ARCHI\n\nDATA_NAME = 'HARDGG'\nBENCHMARK_NAME = DATA_NAME+'-calib'\nCALIB_RESCALE = \"Calib_rescale\"\nN_ITER = 30\n\n\nclass TrainGenerator:\n def __init__(self, data_generator, cuda=False):\n self.data_generator = data_generator\n if cuda:\n self.data_generator.cuda()\n else:\n self.data_generator.cpu()\n self.nuisance_params = self.data_generator.nuisance_params\n\n\n def generate(self, n_samples=None):\n X, y, w = self.data_generator.diff_generate(n_samples=n_samples)\n return X, y, w\n\n def reset(self):\n self.data_generator.reset()\n\n def tensor(self, data, requires_grad=False, dtype=None):\n return self.data_generator.tensor(data, requires_grad=requires_grad, dtype=dtype)\n\n\ndef build_model(args, i_cv):\n args.net = ARCHI(n_in=1, n_out=2, n_unit=args.n_unit)\n args.optimizer = get_optimizer(args)\n model = get_model(args, TangentPropClassifier)\n model.set_info(DATA_NAME, BENCHMARK_NAME, i_cv)\n return model\n\n\ndef load_calib_rescale():\n args = lambda : None\n args.n_unit = 80\n args.optimizer_name = \"adam\"\n args.beta1 = 0.5\n args.beta2 = 0.9\n args.learning_rate = 1e-4\n args.n_samples = 1000\n args.n_steps = 1000\n args.batch_size = 20\n\n args.net = CALIB_ARCHI(n_in=1, n_out=2, n_unit=args.n_unit)\n args.optimizer = get_optimizer(args)\n model = get_model(args, Regressor)\n model.base_name = CALIB_RESCALE\n model.set_info(DATA_NAME, BENCHMARK_NAME, 0)\n model.load(model.model_path)\n return model\n\n\n# =====================================================================\n# MAIN\n# =====================================================================\ndef main():\n # BASIC SETUP\n logger = set_logger()\n args = TP_parse_args(main_description=\"Training launcher for Gradient boosting on S3D2 benchmark\")\n logger.info(args)\n flush(logger)\n # INFO\n model = build_model(args, -1)\n os.makedirs(model.results_directory, exist_ok=True)\n config = Config()\n config_table = evaluate_config(config)\n config_table.to_csv(os.path.join(model.results_directory, 'config_table.csv'))\n # RUN\n if args.load_run:\n logger.info(f'Loading previous runs [{args.start_cv},{args.end_cv}[')\n directory = model.results_directory\n estimations = load_estimations(directory, start_cv=args.start_cv, end_cv=args.end_cv)\n conditional_estimations = load_conditional_estimations(directory, start_cv=args.start_cv, end_cv=args.end_cv)\n else:\n logger.info(f'Running runs [{args.start_cv},{args.end_cv}[')\n results = [run(args, i_cv) for i_cv in range(args.start_cv, args.end_cv)]\n estimations = [e0 for e0, e1 in results]\n estimations = pd.concat(estimations, ignore_index=True)\n conditional_estimations = [e1 for e0, e1 in results]\n conditional_estimations = pd.concat(conditional_estimations)\n estimations.to_csv(os.path.join(model.results_directory, 'estimations.csv'))\n conditional_estimations.to_csv(os.path.join(model.results_directory, 'conditional_estimations.csv'))\n # EVALUATION\n eval_table = evaluate_estimator(config.INTEREST_PARAM_NAME, estimations)\n eval_conditional = evaluate_conditional_estimation(conditional_estimations, interest_param_name=config.INTEREST_PARAM_NAME)\n eval_table = pd.concat([eval_table, eval_conditional], axis=1)\n print_line()\n print_line()\n print(eval_table)\n print_line()\n print_line()\n eval_table.to_csv(os.path.join(model.results_directory, 'evaluation.csv'))\n gather_images(model.results_directory)\n\n\n\n\ndef run(args, i_cv):\n logger = logging.getLogger()\n print_line()\n logger.info('Running iter n°{}'.format(i_cv))\n print_line()\n\n result_row = {'i_cv': i_cv}\n\n # LOAD/GENERATE DATA\n logger.info('Set up data generator')\n config = Config()\n seed = SEED + i_cv * 5\n train_generator = GeneratorTorch(seed, cuda=args.cuda)\n train_generator = TrainGenerator(train_generator, cuda=args.cuda)\n valid_generator = Generator(seed+1)\n test_generator = Generator(seed+2)\n\n # SET MODEL\n logger.info('Set up regressor')\n model = build_model(args, i_cv)\n os.makedirs(model.results_path, exist_ok=True)\n flush(logger)\n\n # TRAINING / LOADING\n train_or_load_neural_net(model, train_generator, retrain=args.retrain)\n\n # CHECK TRAINING\n logger.info('Generate validation data')\n X_valid, y_valid, w_valid = valid_generator.generate(*config.CALIBRATED, n_samples=config.N_VALIDATION_SAMPLES)\n\n result_row.update(evaluate_neural_net(model, prefix='valid'))\n result_row.update(evaluate_classifier(model, X_valid, y_valid, w_valid, prefix='valid'))\n\n # MEASUREMENT\n calib_rescale = load_calib_rescale()\n N_BINS = 10\n evaluate_summary_computer(model, X_valid, y_valid, w_valid, n_bins=N_BINS, prefix='valid_', suffix='')\n iter_results = [run_iter(model, result_row, i, test_config, valid_generator, test_generator, calib_rescale, n_bins=N_BINS)\n for i, test_config in enumerate(config.iter_test_config())]\n result_table = [e0 for e0, e1 in iter_results]\n result_table = pd.DataFrame(result_table)\n result_table.to_csv(os.path.join(model.results_path, 'estimations.csv'))\n logger.info('Plot params')\n param_names = config.PARAM_NAMES\n for name in param_names:\n plot_params(name, result_table, title=model.full_name, directory=model.results_path)\n\n conditional_estimate = pd.concat([e1 for e0, e1 in iter_results])\n conditional_estimate['i_cv'] = i_cv\n fname = os.path.join(model.results_path, \"conditional_estimations.csv\")\n conditional_estimate.to_csv(fname)\n logger.info('DONE')\n return result_table, conditional_estimate\n\n\ndef run_iter(model, result_row, i_iter, config, valid_generator, test_generator, calib_rescale, n_bins=10):\n logger = logging.getLogger()\n logger.info('-'*45)\n logger.info(f'iter : {i_iter}')\n flush(logger)\n\n iter_directory = os.path.join(model.results_path, f'iter_{i_iter}')\n os.makedirs(iter_directory, exist_ok=True)\n result_row['i'] = i_iter\n result_row['n_test_samples'] = config.N_TESTING_SAMPLES\n suffix = f'-mu={config.TRUE.mu:1.2f}_rescale={config.TRUE.rescale}'\n\n logger.info('Generate testing data')\n test_generator.reset()\n X_test, y_test, w_test = test_generator.generate(*config.TRUE, n_samples=config.N_TESTING_SAMPLES)\n # PLOT SUMMARIES\n evaluate_summary_computer(model, X_test, y_test, w_test, n_bins=n_bins, prefix='', suffix=suffix, directory=iter_directory)\n\n # CALIBRATION\n rescale_mean, rescale_sigma = calib_rescale.predict(X_test, w_test)\n logger.info('rescale = {} =vs= {} +/- {}'.format(config.TRUE.rescale, rescale_mean, rescale_sigma) )\n config.CALIBRATED = Parameter(rescale_mean, config.CALIBRATED.interest_parameters)\n config.CALIBRATED_ERROR = Parameter(rescale_sigma, config.CALIBRATED_ERROR.interest_parameters)\n for name, value in config.CALIBRATED.items():\n result_row[name+\"_calib\"] = value\n for name, value in config.CALIBRATED_ERROR.items():\n result_row[name+\"_calib_error\"] = value\n\n logger.info('Set up NLL computer')\n compute_summaries = lambda X, w : model.compute_summaries(X, w, n_bins=n_bins)\n compute_nll = NLLComputer(compute_summaries, valid_generator, X_test, w_test, config=config)\n # NLL PLOTS\n plot_nll_around_min(compute_nll, config.TRUE, iter_directory, suffix)\n\n # MEASURE STAT/SYST VARIANCE\n logger.info('MEASURE STAT/SYST VARIANCE')\n conditional_results = make_conditional_estimation(compute_nll, config)\n fname = os.path.join(iter_directory, \"no_nuisance.csv\")\n conditional_estimate = pd.DataFrame(conditional_results)\n conditional_estimate['i'] = i_iter\n conditional_estimate.to_csv(fname)\n\n # MINIMIZE NLL\n logger.info('Prepare minuit minimizer')\n minimizer = get_minimizer(compute_nll, config.CALIBRATED, config.CALIBRATED_ERROR)\n result_row.update(evaluate_minuit(minimizer, config.TRUE))\n return result_row.copy(), conditional_estimate\n\n\n\ndef make_conditional_estimation(compute_nll, config):\n results = []\n for j, nuisance_parameters in enumerate(config.iter_nuisance()):\n compute_nll_no_nuisance = lambda mu : compute_nll(*nuisance_parameters, mu)\n minimizer = get_minimizer_no_nuisance(compute_nll_no_nuisance, config.CALIBRATED, config.CALIBRATED_ERROR)\n results_row = evaluate_minuit(minimizer, config.TRUE, do_hesse=False)\n results_row['j'] = j\n for name, value in zip(config.CALIBRATED.nuisance_parameters_names, nuisance_parameters):\n results_row[name] = value\n results_row[name+_TRUTH] = config.TRUE[name]\n results.append(results_row)\n return results\n\n\nif __name__ == '__main__':\n main()\n",
"#!/usr/bin/env python\n# coding: utf-8\nfrom __future__ import print_function\nfrom __future__ import division\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\n# Command line :\n# python -m benchmark.HIGGS.TP-Prior\n\nimport os\nimport logging\nfrom config import SEED\nfrom config import _ERROR\nfrom config import _TRUTH\n\nimport pandas as pd\n\nfrom visual.misc import set_plot_config\nset_plot_config()\n\nfrom ..common import load_estimations\nfrom ..common import load_conditional_estimations\nfrom utils.log import set_logger\nfrom utils.log import flush\nfrom utils.log import print_line\nfrom utils.model import get_model\nfrom utils.model import get_optimizer\nfrom utils.model import train_or_load_neural_net\nfrom utils.evaluation import evaluate_neural_net\nfrom utils.evaluation import evaluate_classifier\nfrom utils.evaluation import evaluate_config\nfrom utils.evaluation import evaluate_summary_computer\nfrom utils.evaluation import evaluate_minuit\nfrom utils.evaluation import evaluate_estimator\nfrom utils.evaluation import evaluate_conditional_estimation\nfrom utils.images import gather_images\n\nfrom visual.misc import plot_params\n\nfrom visual.special.higgs import plot_nll_around_min\n\nfrom model.tangent_prop import TangentPropClassifier\nfrom ..my_argparser import TP_parse_args\nfrom ..my_argparser import parse_args_tolerance\nfrom collections import OrderedDict\n\nfrom archi.classic import L4 as ARCHI\n\nfrom .common import DATA_NAME\nfrom .common import N_BINS\nfrom .common import N_ITER\nfrom .common import Config\nfrom .common import get_minimizer\nfrom .common import NLLComputer\nfrom .common import GeneratorClass\nfrom .common import param_generator\nfrom .common import get_generators_torch\nfrom .common import Parameter\nfrom .common import TES\nfrom .common import JES\nfrom .common import LES\n\nBENCHMARK_NAME = f\"{DATA_NAME}-prior-{parse_args_tolerance()}\"\n\nfrom .common import GeneratorCPU\n\n\nclass TrainGenerator:\n def __init__(self, data_generator, cuda=False):\n self.data_generator = data_generator\n if cuda:\n self.data_generator.cuda()\n else:\n self.data_generator.cpu()\n\n self.mu = self.tensor(Config.CALIBRATED.mu, requires_grad=True)\n self.params = tuple()\n nuisance_params_list = []\n if TES:\n self.tes = self.tensor(Config.CALIBRATED.tes, requires_grad=True)\n self.params = self.params + (self.tes, )\n nuisance_params_list.append( ('tes', self.tes) )\n if JES:\n self.jes = self.tensor(Config.CALIBRATED.jes, requires_grad=True)\n self.params = self.params + (self.jes, )\n nuisance_params_list.append( ('jes', self.jes) )\n if LES:\n self.les = self.tensor(Config.CALIBRATED.les, requires_grad=True)\n self.params = self.params + (self.les, )\n nuisance_params_list.append( ('les', self.les) )\n self.params = self.params + (self.mu, )\n self.nuisance_params = OrderedDict(nuisance_params_list)\n\n def generate(self, n_samples=None):\n X, y, w = self.data_generator.diff_generate(*self.params, n_samples=n_samples)\n return X, y, w\n\n def reset(self):\n self.data_generator.reset()\n\n def tensor(self, data, requires_grad=False, dtype=None):\n return self.data_generator.tensor(data, requires_grad=requires_grad, dtype=dtype)\n\n\ndef build_model(args, i_cv):\n args.net = ARCHI(n_in=29, n_out=2, n_unit=args.n_unit)\n args.optimizer = get_optimizer(args)\n model = get_model(args, TangentPropClassifier)\n model.set_info(DATA_NAME, BENCHMARK_NAME, i_cv)\n return model\n\n\n# =====================================================================\n# MAIN\n# =====================================================================\ndef main():\n # BASIC SETUP\n logger = set_logger()\n args = TP_parse_args(main_description=\"Training launcher for Tangent Prop classifier on HIGGS benchmark\")\n logger.info(args)\n flush(logger)\n # INFO\n model = build_model(args, -1)\n os.makedirs(model.results_directory, exist_ok=True)\n config = Config()\n config_table = evaluate_config(config)\n config_table.to_csv(os.path.join(model.results_directory, 'config_table.csv'))\n # RUN\n if not args.conditional_only:\n eval_table = get_eval_table(args, model.results_directory)\n if not args.estimate_only:\n eval_conditional = get_eval_conditional(args, model.results_directory)\n if not args.estimate_only and not args.conditional_only:\n eval_table = pd.concat([eval_table, eval_conditional], axis=1)\n # EVALUATION\n print_line()\n print_line()\n print(eval_table)\n print_line()\n print_line()\n eval_table.to_csv(os.path.join(model.results_directory, 'evaluation.csv'))\n gather_images(model.results_directory)\n\n\ndef get_eval_table(args, results_directory):\n logger = logging.getLogger()\n if args.load_run:\n logger.info(f'Loading previous runs [{args.start_cv},{args.end_cv}[')\n estimations = load_estimations(results_directory, start_cv=args.start_cv, end_cv=args.end_cv)\n else:\n logger.info(f'Running runs [{args.start_cv},{args.end_cv}[')\n estimations = [run_estimation(args, i_cv) for i_cv in range(args.start_cv, args.end_cv)]\n estimations = pd.concat(estimations, ignore_index=True)\n estimations.to_csv(os.path.join(results_directory, 'estimations.csv'))\n # EVALUATION\n eval_table = evaluate_estimator(Config.INTEREST_PARAM_NAME, estimations)\n print_line()\n print_line()\n print(eval_table)\n print_line()\n print_line()\n eval_table.to_csv(os.path.join(results_directory, 'estimation_evaluation.csv'))\n return eval_table\n\n\ndef get_eval_conditional(args, results_directory):\n logger = logging.getLogger()\n if args.load_run:\n logger.info(f'Loading previous runs [{args.start_cv},{args.end_cv}[')\n conditional_estimations = load_conditional_estimations(results_directory, start_cv=args.start_cv, end_cv=args.end_cv)\n else:\n logger.info(f'Running runs [{args.start_cv},{args.end_cv}[')\n conditional_estimations = [run_conditional_estimation(args, i_cv) for i_cv in range(args.start_cv, args.end_cv)]\n conditional_estimations = pd.concat(conditional_estimations, ignore_index=True)\n conditional_estimations.to_csv(os.path.join(results_directory, 'conditional_estimations.csv'))\n # EVALUATION\n eval_conditional = evaluate_conditional_estimation(conditional_estimations, interest_param_name=Config.INTEREST_PARAM_NAME)\n print_line()\n print_line()\n print(eval_conditional)\n print_line()\n print_line()\n eval_conditional.to_csv(os.path.join(results_directory, 'conditional_evaluation.csv'))\n return eval_conditional\n\n\ndef run_estimation(args, i_cv):\n logger = logging.getLogger()\n print_line()\n logger.info('Running iter n°{}'.format(i_cv))\n print_line()\n\n result_row = {'i_cv': i_cv}\n\n # LOAD/GENERATE DATA\n logger.info('Set up data generator')\n config = Config()\n seed = SEED + i_cv * 5\n train_generator, valid_generator, test_generator = get_generators_torch(seed, cuda=args.cuda, GeneratorClass=GeneratorClass)\n train_generator = TrainGenerator(train_generator, cuda=args.cuda)\n valid_generator = GeneratorCPU(valid_generator)\n test_generator = GeneratorCPU(test_generator)\n\n # SET MODEL\n logger.info('Set up classifier')\n model = build_model(args, i_cv)\n os.makedirs(model.results_path, exist_ok=True)\n flush(logger)\n\n # TRAINING / LOADING\n train_or_load_neural_net(model, train_generator, retrain=args.retrain)\n\n # CHECK TRAINING\n logger.info('Generate validation data')\n X_valid, y_valid, w_valid = valid_generator.generate(*config.CALIBRATED, n_samples=config.N_VALIDATION_SAMPLES, no_grad=True)\n\n result_row.update(evaluate_neural_net(model, prefix='valid'))\n result_row.update(evaluate_classifier(model, X_valid, y_valid, w_valid, prefix='valid'))\n\n # MEASUREMENT\n evaluate_summary_computer(model, X_valid, y_valid, w_valid, n_bins=N_BINS, prefix='valid_', suffix='')\n iter_results = [run_estimation_iter(model, result_row, i, test_config, valid_generator, test_generator, n_bins=N_BINS, tolerance=args.tolerance)\n for i, test_config in enumerate(config.iter_test_config())]\n result_table = pd.DataFrame(iter_results)\n result_table.to_csv(os.path.join(model.results_path, 'estimations.csv'))\n logger.info('Plot params')\n param_names = config.PARAM_NAMES\n for name in param_names:\n plot_params(name, result_table, title=model.full_name, directory=model.results_path)\n\n logger.info('DONE')\n return result_table\n\n\ndef run_estimation_iter(model, result_row, i_iter, config, valid_generator, test_generator, n_bins=N_BINS, tolerance=10):\n logger = logging.getLogger()\n logger.info('-'*45)\n logger.info(f'iter : {i_iter}')\n flush(logger)\n\n iter_directory = os.path.join(model.results_path, f'iter_{i_iter}')\n os.makedirs(iter_directory, exist_ok=True)\n result_row['i'] = i_iter\n result_row['n_test_samples'] = test_generator.n_samples\n suffix = config.get_suffix()\n\n logger.info('Generate testing data')\n test_generator.reset()\n X_test, y_test, w_test = test_generator.generate(*config.TRUE, n_samples=config.N_TESTING_SAMPLES, no_grad=True)\n # PLOT SUMMARIES\n evaluate_summary_computer(model, X_test, y_test, w_test, n_bins=n_bins, prefix='', suffix=suffix, directory=iter_directory)\n\n logger.info('Set up NLL computer')\n compute_summaries = model.summary_computer(n_bins=n_bins)\n compute_nll = NLLComputer(compute_summaries, valid_generator, X_test, w_test, config=config)\n # NLL PLOTS\n plot_nll_around_min(compute_nll, config.TRUE, iter_directory, suffix)\n\n # MINIMIZE NLL\n logger.info('Prepare minuit minimizer')\n minimizer = get_minimizer(compute_nll, config.CALIBRATED, config.CALIBRATED_ERROR, tolerance=tolerance)\n result_row.update(evaluate_minuit(minimizer, config.TRUE, iter_directory, suffix=suffix))\n return result_row.copy()\n\n\ndef run_conditional_estimation(args, i_cv):\n logger = logging.getLogger()\n print_line()\n logger.info('Running iter n°{}'.format(i_cv))\n print_line()\n\n result_row = {'i_cv': i_cv}\n\n # LOAD/GENERATE DATA\n logger.info('Set up data generator')\n config = Config()\n seed = SEED + i_cv * 5\n train_generator, valid_generator, test_generator = get_generators_torch(seed, cuda=args.cuda, GeneratorClass=GeneratorClass)\n train_generator = GeneratorCPU(train_generator)\n valid_generator = GeneratorCPU(valid_generator)\n test_generator = GeneratorCPU(test_generator)\n\n # SET MODEL\n logger.info('Set up classifier')\n model = build_model(args, i_cv)\n os.makedirs(model.results_path, exist_ok=True)\n flush(logger)\n\n # TRAINING / LOADING\n train_or_load_neural_net(model, train_generator, retrain=args.retrain)\n\n # CHECK TRAINING\n logger.info('Generate validation data')\n X_valid, y_valid, w_valid = valid_generator.generate(*config.CALIBRATED, n_samples=config.N_VALIDATION_SAMPLES, no_grad=True)\n\n result_row.update(evaluate_classifier(model, X_valid, y_valid, w_valid, prefix='valid'))\n\n # MEASUREMENT\n evaluate_summary_computer(model, X_valid, y_valid, w_valid, n_bins=N_BINS, prefix='valid_', suffix='')\n iter_results = [run_conditional_estimation_iter(model, result_row, i, test_config, valid_generator, test_generator, n_bins=N_BINS)\n for i, test_config in enumerate(config.iter_test_config())]\n\n conditional_estimate = pd.concat(iter_results)\n conditional_estimate['i_cv'] = i_cv\n fname = os.path.join(model.results_path, \"conditional_estimations.csv\")\n conditional_estimate.to_csv(fname)\n logger.info('DONE')\n return conditional_estimate\n\n\ndef run_conditional_estimation_iter(model, result_row, i_iter, config, valid_generator, test_generator, n_bins=N_BINS):\n logger = logging.getLogger()\n logger.info('-'*45)\n logger.info(f'iter : {i_iter}')\n flush(logger)\n\n iter_directory = os.path.join(model.results_path, f'iter_{i_iter}')\n os.makedirs(iter_directory, exist_ok=True)\n\n logger.info('Generate testing data')\n test_generator.reset()\n X_test, y_test, w_test = test_generator.generate(*config.TRUE, n_samples=config.N_TESTING_SAMPLES, no_grad=True)\n # SUMMARIES\n logger.info('Set up NLL computer')\n compute_summaries = model.summary_computer(n_bins=n_bins)\n compute_nll = NLLComputer(compute_summaries, valid_generator, X_test, w_test, config=config)\n\n # MEASURE STAT/SYST VARIANCE\n logger.info('MEASURE STAT/SYST VARIANCE')\n conditional_results = make_conditional_estimation(compute_nll, config)\n fname = os.path.join(iter_directory, \"no_nuisance.csv\")\n conditional_estimate = pd.DataFrame(conditional_results)\n conditional_estimate['i'] = i_iter\n conditional_estimate.to_csv(fname)\n\n return conditional_estimate\n\n\ndef make_conditional_estimation(compute_nll, config):\n results = []\n for j, nuisance_parameters in enumerate(config.iter_nuisance()):\n compute_nll_no_nuisance = lambda mu : compute_nll(*nuisance_parameters, mu)\n minimizer = get_minimizer_no_nuisance(compute_nll_no_nuisance, config.CALIBRATED, config.CALIBRATED_ERROR)\n results_row = evaluate_minuit(minimizer, config.TRUE, do_hesse=False)\n results_row['j'] = j\n for name, value in zip(config.CALIBRATED.nuisance_parameters_names, nuisance_parameters):\n results_row[name] = value\n results_row[name+_TRUTH] = config.TRUE[name]\n results.append(results_row)\n print(f\"ncalls = {results_row['ncalls']}\", flush=True)\n return results\n\nif __name__ == '__main__':\n main()\n"
] | [
[
"numpy.max",
"numpy.array",
"numpy.histogram",
"numpy.min"
],
[
"numpy.concatenate",
"pandas.concat"
],
[
"pandas.concat",
"pandas.DataFrame"
],
[
"pandas.concat",
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"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": []
},
{
"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.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
Aieener/SUS_3D | [
"8fc5a768a2339238939522baf96bce98bf61902e"
] | [
"DATA/10_64_64_64_1E7/analy.py"
] | [
"# analy.py\n# A python program to analyze the SUS weighting function in order to reach the following goals:\n# 1. plot the weight function\n# 2. generate the normalized distribution for Z=1\n# 3. extrapolate the N distribution for different Zs given by the user.\n# Author: Yuding Ai\n# Date: 2015 Oct 23\n\nimport math\nimport numpy as np\nimport matplotlib.mlab as mlab\nimport matplotlib.pyplot as plt\nfrom matplotlib import rc\n# rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})\n## for Palatino and other serif fonts use:\nrc('font',**{'family':'serif','serif':['Palatino']})\nrc('text', usetex=True)\n\ndef PN():\n\tWF = [] # a list of my target Weighting function\n\tPN = [] # a list of number distribution\n\n\twith open(\"SUSWeight_function.txt\",\"r\") as file:\n\t\tfor line in file:\n\t\t\twords = line.split()\n\t\t\tn = float(words[0]) #take the value\n\t\t\tWF.append(n); #append value into my WF list\n\n\tmaxi = max(WF)\n\tif maxi > 500:\n\t\tfor i in range(len(WF)):\n\t\t\tWF[i] = WF[i]-maxi +500\n\t\t\tPN.append(math.exp(WF[i]));\n\n\tPN = [float(i)/sum(PN) for i in PN]\n\treturn WF,PN\n\n\ndef Pplot(PN,z):\n\tfig = plt.figure()\t\n\tplt.plot(PN,'+b',markersize=3)\n\tZ = str(z)\n\tylabel = 'P(N;Z='+ Z + ')'\n\tplt.ylabel(ylabel)\n\tplt.xlabel('N')\n\ttitle = 'P(N;Z='+ Z + ').png'\n\tfig.savefig(title, dpi=300, bbox_inches='tight')\n\ndef enlargePplot(PN,z):\n\tfig = plt.figure()\t\n\tplt.plot(PN,'+b-',markersize=3,linewidth = 0.1)\n\tplt.xlim(8600,9600)\n\tplt.ylim(0,0.007)\n\tZ = str(z)\n\tylabel = 'P(N;Z='+ Z + ')'\n\tplt.ylabel(ylabel)\n\tplt.xlabel('N')\n\ttitle = 'ENLP(N;Z='+ Z + ').png'\n\tfig.savefig(title, dpi=300, bbox_inches='tight')\n\ndef Wplot(WN):\n\tfig = plt.figure()\t\n\tplt.plot(WN,'+r',markersize=1,)\n\tplt.ylabel('Weighting Function')\n\tplt.xlabel('N')\n\ttitle = 'WeightingFunc.png'\n\tfig.savefig(title, dpi=300, bbox_inches='tight')\n\n\ndef exploPN(W,z):\n\tP = [] # a list of number distribution\n\tfor i in range(len(W)):\n\t\tW[i] = W[i] + i*math.log(z)\n\n\tmaxi = max(W)\n\tif maxi > 500:\n\t\tfor j in range(len(W)):\n\t\t\tW[j] = W[j]-maxi +500\n\t\t\tP.append(math.exp(W[j]));\n\tP = [float(k)/sum(P) for k in P]\n\treturn P\n\n\ndef main():\n\n\n\tP = PN()[1] # take the P(N;z=1)\n\tW = PN()[0] # take the original weighting function \n\n\tWplot(W)\n\t# Pplot(P,\"1\")\n\t# Pe = exploPN(W,4.44)\n\t# enlargePplot(Pe,4.44)\n\n\t# for i in range(10):\n\t# \tW = PN()[0] # take the original weighting function \t\t\n\t# \tt = 3.83 + 0.02*i\n\t# \tPe = exploPN(W,t)\n\t# \t# Pplot(Pe,t)\n\t# \tenlargePplot(Pe,t)\n\nmain()\n"
] | [
[
"matplotlib.pyplot.figure",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.xlabel",
"matplotlib.rc",
"matplotlib.pyplot.ylabel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
golmschenk/ramjet | [
"77fb4481a15088923308fda09804d80455d1a9cf"
] | [
"ramjet/data_interface/tess_eclipsing_binary_metadata_manager.py"
] | [
"\"\"\"\nCode for managing the TESS eclipsing binary metadata.\n\"\"\"\nimport pandas as pd\nfrom pathlib import Path\nfrom peewee import IntegerField, SchemaManager\n\nfrom ramjet.data_interface.metadatabase import MetadatabaseModel, metadatabase\n\n\nbrian_powell_eclipsing_binary_csv_path = Path('data/tess_eclipsing_binaries/TESS_EB_catalog_23Jun.csv')\n\n\nclass TessEclipsingBinaryMetadata(MetadatabaseModel):\n \"\"\"\n A model for the TESS eclipsing binary metadatabase table.\n \"\"\"\n tic_id = IntegerField(index=True, unique=True)\n\n\nclass TessEclipsingBinaryMetadataManager:\n \"\"\"\n A class for managing the TESS eclipsing binary metadata.\n \"\"\"\n @staticmethod\n def build_table():\n \"\"\"\n Builds the TESS eclipsing binary metadata table.\n \"\"\"\n print('Building TESS eclipsing binary metadata table...')\n eclipsing_binary_data_frame = pd.read_csv(brian_powell_eclipsing_binary_csv_path, usecols=['ID'])\n row_count = 0\n metadatabase.drop_tables([TessEclipsingBinaryMetadata])\n metadatabase.create_tables([TessEclipsingBinaryMetadata])\n SchemaManager(TessEclipsingBinaryMetadata).drop_indexes()\n rows = []\n for index, tic_id in enumerate(eclipsing_binary_data_frame['ID'].values):\n row = {'tic_id': tic_id}\n rows.append(row)\n row_count += 1\n if row_count % 1000 == 0:\n with metadatabase.atomic():\n TessEclipsingBinaryMetadata.insert_many(rows).execute()\n rows = []\n with metadatabase.atomic():\n TessEclipsingBinaryMetadata.insert_many(rows).execute()\n SchemaManager(TessEclipsingBinaryMetadata).create_indexes()\n print(f'Table built. {row_count} rows added.')\n\n\nif __name__ == '__main__':\n metadata_manager = TessEclipsingBinaryMetadataManager()\n metadata_manager.build_table()\n"
] | [
[
"pandas.read_csv"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
BreezeDawn/numpy-pandas-matplotlib- | [
"e55dccb2442e57c2fccb2081966a7c19e731083a"
] | [
"pandas_study/PandasTest.py"
] | [
"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef base():\n index = pd.date_range('20181023', periods=9) # 生成9个行索引\n column = ['a', 'b', 'c', 'd'] # 生成4个列索引\n a = np.random.randn(9, 4) # 随便生成的9行4列的数据\n df = pd.DataFrame(a, index=index, columns=column)\n print(df)\n print(pd.DataFrame(np.arange(9).reshape((3, 3)))) # 行和列的默认索引为从0开始的数字\n print(df.dtypes) # 查看每列的数据类型\n print(df.index) # 查看每行的行索引\n print(df.columns) # 查看每列的列索引\n print(df.values) # 查看所有值\n print(df.describe()) # 查看每列的详细统计 数目/平均值/....\n print(df.T) # pandas的转置\n print(df.sort_index(axis=1, ascending=False)) # 按索引排序 axis: 1列排序 0行排序 ascending: False反排序(从小向大) True正排序(从大向小)\n print(df.sort_values(by='a')) # 把a列的值进行排序 默认从小向大\n\n\ndef select():\n index = pd.date_range('20181023', periods=6)\n df = pd.DataFrame(np.arange(24).reshape((6, 4)), index=index, columns=['A', 'B', 'C', 'D'])\n print(df)\n print(df.A) # 取出A列数据(带索引)\n print(df[2:3]) # 切片取数据\n print(df[2:3]) # 切片取数据\n print(df['2018-10-25':'2018-10-26']) # 切片取数据\n print(df.loc['2018-10-25', ['A', 'B']]) # 按照标签取数据\n print(df.iloc[[1, 3, 5], 1:5]) # 按照数字取数据\n print(df.ix['2018-10-25':'2018-10-26', 1:5]) # 数字标签结合取数据\n print(df[df.A > 8]) # A列中的元素大于8的都显示\n\n\ndef update():\n index = pd.date_range('20181023', periods=6)\n df = pd.DataFrame(np.arange(24).reshape((6, 4)), index=index, columns=['A', 'B', 'C', 'D'])\n df.iloc[2, 3] = -555 # 修改值 选中就能修改\n df.B[df.A > 8] = 0 # A列中的元素大于8的都把B修改为0\n print(df)\n df['E'] = pd.Series(np.arange(6), pd.date_range('20181023', periods=6)) # 增加一列\n print(df)\n\n\ndef handle_NaN():\n index = pd.date_range('20181023', periods=6)\n df = pd.DataFrame(np.arange(24).reshape((6, 4)), index=index, columns=['A', 'B', 'C', 'D'])\n df.iloc[1, 2] = np.nan\n df.iloc[0, 1] = np.nan\n print(df)\n print(df.dropna(axis=1, how='any')) # 丢掉缺失值(返回新的结果不影响原始数据) axis: 1丢掉列 0丢掉行 how: any任何一个是NaN就丢掉 all全是NaN就丢掉\n print(df.fillna(value=0)) # 填充缺失值 填充为0\n print(df.isnull()) # 检查每个元素是否缺失值,结果返回一个bool填充\n print(np.any(df.isnull())) # np.any 检查至少有一个False,是的话返回True\n\n\ndef read_save_data():\n data = pd.read_csv('./pand.csv') # 读取csv文件数据(csv内部逗号分隔)\n print(data)\n data.to_pickle('./pand.pickle') # 保存数据到pickle文件\n\n\ndef merge_DataFrame():\n df1 = pd.DataFrame(np.zeros((3, 4)), columns=['a', 'b', 'c', 'd'])\n df2 = pd.DataFrame(np.ones((3, 4)), columns=['a', 'b', 'c', 'd'])\n df3 = pd.DataFrame(2 * np.ones((3, 4)), columns=['a', 'b', 'c', 'd'])\n print(df1)\n print(df2)\n print(df3)\n res = pd.concat([df1, df2, df3], axis=0) # axis: 0上下合并 1左右合并\n print(res)\n res = pd.concat([df1, df2, df3], axis=1, ignore_index=True) # ignore_index 忽略前面所有的index并重新排序\n print(res)\n\n df1 = pd.DataFrame(np.zeros((3, 4)), columns=['a', 'b', 'c', 'd'], index=[1, 2, 3])\n df2 = pd.DataFrame(np.ones((3, 4)), columns=['b', 'c', 'd', 'e'], index=[2, 3, 4])\n res = pd.concat([df1, df2], axis=0, join='outer', sort=True) # 上下合并,outer如果有不一样的列字段,就用NaN填充\n print(res)\n res = pd.concat([df1, df2], axis=0, join='inner', sort=True, ignore_index=True) # 上下合并, inner有不一样的列字段就丢掉那一列,保留相同字段\n print(res)\n res = pd.concat([df1, df2], axis=1, ) # 左右合并,有不一样的行字段就用NaN填充\n print(res)\n res = pd.concat([df1, df2], axis=1, join_axes=[df1.index]) # 左右合并,行字段按照df1的行字段来,缺失值用NaN填充,其余df1没有的字段丢掉\n print(res)\n\n df1 = pd.DataFrame(np.zeros((3, 4)), columns=['a', 'b', 'c', 'd'])\n df2 = pd.DataFrame(np.ones((3, 4)), columns=['a', 'b', 'c', 'd'])\n df3 = pd.DataFrame(np.ones((3, 4)), columns=['a', 'b', 'c', 'd'])\n res = df1.append(df2, ignore_index=True) # df1后面加上df2\n print(res)\n res = df1.append([df2, df3], ignore_index=True) # df1后面加上df2,df3\n print(res)\n sl = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])\n res = df1.append(sl, ignore_index=True)\n print(res)\n\n\ndef merge():\n left = pd.DataFrame({\n 'key': ['K0', 'K1', 'K2', 'K3'],\n 'A': ['A0', 'A1', 'A2', 'A3'],\n 'B': ['B0', 'B1', 'B2', 'B3']\n })\n right = pd.DataFrame({\n 'key': ['K0', 'K1', 'K2', 'K3'],\n 'C': ['C0', 'C1', 'C2', 'C3'],\n 'D': ['D0', 'D1', 'D2', 'D3']\n })\n print(left)\n print(right)\n res = pd.merge(left, right, on='key') # 左右合并,key字段保留一个\n print(res)\n\n left = pd.DataFrame({\n 'key1': ['K0', 'K0', 'K1', 'K2'],\n 'key2': ['K0', 'K1', 'K0', 'K1'],\n 'A': ['A0', 'A1', 'A2', 'A3'],\n 'B': ['B0', 'B1', 'B2', 'B3']\n })\n right = pd.DataFrame({\n 'key1': ['K0', 'K1', 'K1', 'K2'],\n 'key2': ['K0', 'K0', 'K0', 'K0'],\n 'C': ['C0', 'C1', 'C2', 'C3'],\n 'D': ['D0', 'D1', 'D2', 'D3']\n })\n res = pd.merge(left, right, on=['key1', 'key2'], how='inner') # 解释不清,看结果\n print(res)\n res = pd.merge(left, right, on=['key1', 'key2'], how='outer',indicator='indicator_column') # 不管一不一样都保留 indicator写出哪些一样哪些不一样,写字符串可改名\n print(res)\n res = pd.merge(left, right, on=['key1', 'key2'], how='left') # 左的on字段完全不动的保留\n print(res)\n res = pd.merge(left, right, on=['key1', 'key2'], how='right') # 右的on字段完全不动的保留\n print(res)\n res = pd.merge(left, right, left_index=True,right_index=True, how='right') # 根据索引保留\n print(res)\n\n\ndef plot_test():\n # 1000个一维数据累加\n data = pd.Series(np.random.randn(1000),index=np.arange(1000))\n data = data.cumsum()\n # data.plot()\n # plt.show()\n\n # 矩阵\n data = pd.DataFrame(np.random.randn(1000,4),index=np.arange(1000),columns=list('ABCD'))\n data = data.cumsum()\n print(data.head()) # head显示前五个数据,默认5个\n data.plot() # 线性\n ax = data.plot.scatter(x='A',y='B',color='DarkBlue', label='Class 1') # scatter 数据点 只有x,y\n data.plot.scatter(x='A',y='C',color='DarkGreen', label='Class 2',ax=ax) # ax和前面的在一张图上\n plt.show()\n # plot method : bar条形图 hist box kde area scatter hexbin pie\n\n\n\n\nif __name__ == '__main__':\n # base()\n # select()\n # update()\n # handle_NaN()\n # read_save_data()\n # merge_DataFrame()\n # merge()\n plot_test()"
] | [
[
"pandas.concat",
"pandas.read_csv",
"pandas.merge",
"pandas.Series",
"numpy.arange",
"pandas.DataFrame",
"numpy.ones",
"numpy.random.randn",
"pandas.date_range",
"matplotlib.pyplot.show",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
maximskorik/matchms | [
"922f5afaef123a793194bdd74391027477cbb844",
"922f5afaef123a793194bdd74391027477cbb844",
"922f5afaef123a793194bdd74391027477cbb844",
"922f5afaef123a793194bdd74391027477cbb844"
] | [
"matchms/exporting/save_as_json.py",
"matchms/Fragments.py",
"matchms/importing/load_from_usi.py",
"matchms/similarity/ModifiedCosine.py"
] | [
"import json\nfrom typing import List\nimport numpy\nfrom ..Spectrum import Spectrum\n\n\ndef save_as_json(spectrums: List[Spectrum], filename: str):\n \"\"\"Save spectrum(s) as json file.\n\n :py:attr:`~matchms.Spectrum.losses` of spectrum will not be saved.\n\n Example:\n\n .. code-block:: python\n\n import numpy\n from matchms import Spectrum\n from matchms.exporting import save_as_json\n\n # Create dummy spectrum\n spectrum = Spectrum(mz=numpy.array([100, 200, 300], dtype=\"float\"),\n intensities=numpy.array([10, 10, 500], dtype=\"float\"),\n metadata={\"charge\": -1,\n \"inchi\": '\"InChI=1S/C6H12\"',\n \"precursor_mz\": 222.2})\n\n # Write spectrum to test file\n save_as_json(spectrum, \"test.json\")\n\n Parameters\n ----------\n spectrums:\n Expected input is a list of :py:class:`~matchms.Spectrum.Spectrum` objects.\n filename:\n Provide filename to save spectrum(s).\n \"\"\"\n if not isinstance(spectrums, list):\n # Assume that input was single Spectrum\n spectrums = [spectrums]\n\n # Write to json file\n with open(filename, 'w', encoding=\"utf-8\") as fout:\n json.dump(spectrums, fout, cls=SpectrumJSONEncoder)\n\n\nclass SpectrumJSONEncoder(json.JSONEncoder):\n # See https://github.com/PyCQA/pylint/issues/414 for reference\n def default(self, o):\n \"\"\"JSON Encoder which can encode a :py:class:`~matchms.Spectrum.Spectrum` object\"\"\"\n if isinstance(o, Spectrum):\n spec = o.clone()\n peaks_list = numpy.vstack((spec.peaks.mz, spec.peaks.intensities)).T.tolist()\n\n # Convert matchms.Spectrum() into dictionaries\n spectrum_dict = {key: spec.metadata[key] for key in spec.metadata}\n spectrum_dict[\"peaks_json\"] = peaks_list\n return spectrum_dict\n return json.JSONEncoder.default(self, o)\n",
"import numpy\n\n\nclass Fragments:\n \"\"\"\n Stores arrays of intensities and M/z values, with some checks on their internal consistency.\n\n For example\n\n .. testcode::\n\n import numpy as np\n from matchms import Fragments\n\n mz = np.array([10, 20, 30], dtype=\"float\")\n intensities = np.array([100, 20, 300], dtype=\"float\")\n\n peaks = Fragments(mz=mz, intensities=intensities)\n print(peaks[2])\n\n Should output\n\n .. testoutput::\n\n [ 30. 300.]\n\n Attributes\n ----------\n mz:\n Numpy array of m/z values.\n intensities:\n Numpy array of peak intensity values.\n\n \"\"\"\n def __init__(self, mz=None, intensities=None):\n assert isinstance(mz, numpy.ndarray), \"Input argument 'mz' should be a numpy.array.\"\n assert isinstance(intensities, numpy.ndarray), \"Input argument 'intensities' should be a numpy.array.\"\n assert mz.shape == intensities.shape, \"Input arguments 'mz' and 'intensities' should be the same shape.\"\n assert mz.dtype == \"float\", \"Input argument 'mz' should be an array of type float.\"\n assert intensities.dtype == \"float\", \"Input argument 'intensities' should be an array of type float.\"\n\n self._mz = mz\n self._intensities = intensities\n\n assert self._is_sorted(), \"mz values are out of order.\"\n\n def __eq__(self, other):\n return \\\n self.mz.shape == other.mz.shape and \\\n numpy.allclose(self.mz, other.mz) and \\\n self.intensities.shape == other.intensities.shape and \\\n numpy.allclose(self.intensities, other.intensities)\n\n def __len__(self):\n return self._mz.size\n\n def __getitem__(self, item):\n return numpy.asarray([self.mz[item], self.intensities[item]])\n\n def _is_sorted(self):\n return numpy.all(self.mz[:-1] <= self.mz[1:])\n\n def clone(self):\n return Fragments(self.mz, self.intensities)\n\n @property\n def mz(self):\n \"\"\"getter method for mz private variable\"\"\"\n return self._mz.copy()\n\n @property\n def intensities(self):\n \"\"\"getter method for intensities private variable\"\"\"\n return self._intensities.copy()\n\n @property\n def to_numpy(self):\n \"\"\"getter method to return stacked numpy array of both peak mz and\n intensities\"\"\"\n return numpy.vstack((self.mz, self.intensities)).T\n",
"import json\nimport logging\nimport numpy as np\nimport requests\nfrom ..Spectrum import Spectrum\n\n\nlogger = logging.getLogger(\"matchms\")\n\n\ndef load_from_usi(usi: str, server: str = \"https://metabolomics-usi.ucsd.edu\",\n metadata_harmonization: bool = True):\n \"\"\"Load spectrum from metabolomics USI.\n\n USI returns JSON data with keys \"peaks\", \"n_peaks\" and \"precuror_mz\"\n\n .. code-block:: python\n\n from matchms.importing import load_from_usi\n\n spectrum = load_from_usi(\"mzspec:MASSBANK::accession:SM858102\")\n print(f\"Found spectrum with precursor m/z of {spectrum.get(\"precursor_mz\"):.2f}.\")\n\n Parameters\n ----------\n usi:\n Provide the usi.\n server: string\n USI server\n metadata_harmonization : bool, optional\n Set to False if metadata harmonization to default keys is not desired.\n The default is True.\n \"\"\"\n\n # Create the url\n url = server + \"/json/?usi1=\" + usi\n metadata = {\"usi\": usi, \"server\": server}\n response = requests.get(url)\n\n if response.status_code == 404:\n return None\n # Extract data and create Spectrum object\n try:\n spectral_data = response.json()\n if spectral_data is None or \"peaks\" not in spectral_data:\n logger.info(\"Empty spectrum found (no data found). Will not be imported.\")\n return None\n peaks = spectral_data[\"peaks\"]\n if len(peaks) == 0:\n logger.info(\"Empty spectrum found (no peaks in 'peaks_json'). Will not be imported.\")\n return None\n mz_list, intensity_list = zip(*peaks)\n mz_array = np.array(mz_list)\n intensity_array = np.array(intensity_list)\n\n metadata[\"precursor_mz\"] = spectral_data.get(\"precursor_mz\", None)\n\n s = Spectrum(mz_array, intensity_array, metadata,\n metadata_harmonization=metadata_harmonization)\n\n return s\n\n except json.decoder.JSONDecodeError:\n logger.warning(\"Failed to unpack json (JSONDecodeError).\")\n return None\n",
"import logging\nfrom typing import Tuple\nimport numpy as np\nfrom matchms.filtering.add_precursor_mz import _convert_precursor_mz\nfrom matchms.typing import SpectrumType\nfrom .BaseSimilarity import BaseSimilarity\nfrom .spectrum_similarity_functions import (collect_peak_pairs,\n score_best_matches)\n\n\nlogger = logging.getLogger(\"matchms\")\n\n\nclass ModifiedCosine(BaseSimilarity):\n \"\"\"Calculate 'modified cosine score' between mass spectra.\n\n The modified cosine score aims at quantifying the similarity between two\n mass spectra. The score is calculated by finding best possible matches between\n peaks of two spectra. Two peaks are considered a potential match if their\n m/z ratios lie within the given 'tolerance', or if their m/z ratios\n lie within the tolerance once a mass-shift is applied. The mass shift is\n simply the difference in precursor-m/z between the two spectra.\n See Watrous et al. [PNAS, 2012, https://www.pnas.org/content/109/26/E1743]\n for further details.\n\n For example\n\n .. testcode::\n\n import numpy as np\n from matchms import Spectrum\n from matchms.similarity import ModifiedCosine\n\n spectrum_1 = Spectrum(mz=np.array([100, 150, 200.]),\n intensities=np.array([0.7, 0.2, 0.1]),\n metadata={\"precursor_mz\": 100.0})\n spectrum_2 = Spectrum(mz=np.array([104.9, 140, 190.]),\n intensities=np.array([0.4, 0.2, 0.1]),\n metadata={\"precursor_mz\": 105.0})\n\n # Use factory to construct a similarity function\n modified_cosine = ModifiedCosine(tolerance=0.2)\n\n score = modified_cosine.pair(spectrum_1, spectrum_2)\n\n print(f\"Modified cosine score is {score['score']:.2f} with {score['matches']} matched peaks\")\n\n Should output\n\n .. testoutput::\n\n Modified cosine score is 0.83 with 1 matched peaks\n\n \"\"\"\n # Set key characteristics as class attributes\n is_commutative = True\n # Set output data type, e.g. (\"score\", \"float\") or [(\"score\", \"float\"), (\"matches\", \"int\")]\n score_datatype = [(\"score\", np.float64), (\"matches\", \"int\")]\n\n def __init__(self, tolerance: float = 0.1, mz_power: float = 0.0,\n intensity_power: float = 1.0):\n \"\"\"\n Parameters\n ----------\n tolerance:\n Peaks will be considered a match when <= tolerance apart. Default is 0.1.\n mz_power:\n The power to raise mz to in the cosine function. The default is 0, in which\n case the peak intensity products will not depend on the m/z ratios.\n intensity_power:\n The power to raise intensity to in the cosine function. The default is 1.\n \"\"\"\n self.tolerance = tolerance\n self.mz_power = mz_power\n self.intensity_power = intensity_power\n\n def pair(self, reference: SpectrumType, query: SpectrumType) -> Tuple[float, int]:\n \"\"\"Calculate modified cosine score between two spectra.\n\n Parameters\n ----------\n reference\n Single reference spectrum.\n query\n Single query spectrum.\n\n Returns\n -------\n\n Tuple with cosine score and number of matched peaks.\n \"\"\"\n def get_valid_precursor_mz(spectrum):\n \"\"\"Extract valid precursor_mz from spectrum if possible. If not raise exception.\"\"\"\n message_precursor_missing = \\\n \"Precursor_mz missing. Apply 'add_precursor_mz' filter first.\"\n message_precursor_no_number = \\\n \"Precursor_mz must be of type int or float. Apply 'add_precursor_mz' filter first.\"\n message_precursor_below_0 = \"Expect precursor to be positive number.\" \\\n \"Apply 'require_precursor_mz' first\"\n\n precursor_mz = spectrum.get(\"precursor_mz\", None)\n if not isinstance(precursor_mz, (int, float)):\n logger.warning(message_precursor_no_number)\n precursor_mz = _convert_precursor_mz(precursor_mz)\n assert precursor_mz is not None, message_precursor_missing\n assert precursor_mz > 0, message_precursor_below_0\n return precursor_mz\n\n def get_matching_pairs():\n \"\"\"Find all pairs of peaks that match within the given tolerance.\"\"\"\n zero_pairs = collect_peak_pairs(spec1, spec2, self.tolerance, shift=0.0,\n mz_power=self.mz_power,\n intensity_power=self.intensity_power)\n precursor_mz_ref = get_valid_precursor_mz(reference)\n precursor_mz_query = get_valid_precursor_mz(query)\n\n mass_shift = precursor_mz_ref - precursor_mz_query\n nonzero_pairs = collect_peak_pairs(spec1, spec2, self.tolerance, shift=mass_shift,\n mz_power=self.mz_power,\n intensity_power=self.intensity_power)\n\n if zero_pairs is None:\n zero_pairs = np.zeros((0, 3))\n if nonzero_pairs is None:\n nonzero_pairs = np.zeros((0, 3))\n matching_pairs = np.concatenate((zero_pairs, nonzero_pairs), axis=0)\n if matching_pairs.shape[0] > 0:\n matching_pairs = matching_pairs[np.argsort(matching_pairs[:, 2])[::-1], :]\n return matching_pairs\n\n spec1 = reference.peaks.to_numpy\n spec2 = query.peaks.to_numpy\n matching_pairs = get_matching_pairs()\n if matching_pairs.shape[0] == 0:\n return np.asarray((float(0), 0), dtype=self.score_datatype)\n score = score_best_matches(matching_pairs, spec1, spec2,\n self.mz_power, self.intensity_power)\n return np.asarray(score, dtype=self.score_datatype)\n"
] | [
[
"numpy.vstack"
],
[
"numpy.asarray",
"numpy.all",
"numpy.allclose",
"numpy.vstack"
],
[
"numpy.array"
],
[
"numpy.asarray",
"numpy.argsort",
"numpy.zeros",
"numpy.concatenate"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
LenKerr/Colorization-1 | [
"bcfcdb24fc8ab107d34644d5a63b018f86784e21"
] | [
"transfer_subnet/xiaoketransfer2.py"
] | [
"\"\"\"\nCopyright (c) 2019 NAVER Corp.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\"\"\"\nimport os\nos.environ['CUDA_VISIBLE_DEVICES']='1'\nimport sys\nsys.path.append('./segmentation')\nimport os\nimport tqdm\nimport argparse\n\nimport torch\nfrom torchvision.utils import save_image\nimport torch.nn as nn\n# from model import WaveEncoder, WaveDecoder\n\nfrom utils.core import feature_wct\nfrom utils.core import feature_adin\nfrom utils.core import feature_adin_without_segment\nfrom utils.core import feature_wct_without_segment\nfrom utils.io import Timer, open_image, load_segment, compute_label_info\nfrom xiaokemodel import XiaoKeEncoder, XiaoKeDecoder\nimport numpy as np\nimport torchvision.transforms as transforms\n\nfrom scipy.io import loadmat\nfrom PIL import Image\nfrom scipy.misc import imread, imresize\nimport cv2\nfrom lib.nn import user_scattered_collate, async_copy_to\nfrom lib.utils import as_numpy, mark_volatile\nimport datetime\n\n\nIMG_EXTENSIONS = [\n '.jpg', '.JPG', '.jpeg', '.JPEG',\n '.png', '.PNG',\n]\n\n\ndef is_image_file(filename):\n return any(filename.endswith(extension) for extension in IMG_EXTENSIONS)\n\n\nclass WCT2:\n def __init__(self, model_path='./model_checkpoints', transfer_at=['encoder', 'skip', 'decoder'], option_unpool='cat5', device='cuda:0', verbose=False):\n\n self.transfer_at = set(transfer_at)\n assert not(self.transfer_at - set(['encoder', 'decoder', 'skip'])), 'invalid transfer_at: {}'.format(transfer_at)\n assert self.transfer_at, 'empty transfer_at'\n model_path = './xiaoke_video_checkpoints/'\n encoder_path = 'xiaoke_encoder.pth'\n decoder_path = 'xiaoke_decoder_0.0001_4.pth'\n\n model_path = './xiaoke_checkpoints/'\n encoder_path = 'xiaoke_encoder.pth'\n decoder_path = 'xiaoke_decoder_87.pth'\n\n\n self.device = torch.device(device)\n self.verbose = verbose\n # self.encoder = WaveEncoder(option_unpool).to(self.device)\n # self.decoder = WaveDecoder(option_unpool).to(self.device)\n # self.encoder.load_state_dict(torch.load(os.path.join(model_path, 'wave_encoder_{}_l4.pth'.format(option_unpool)), map_location=lambda storage, loc: storage))\n # self.decoder.load_state_dict(torch.load(os.path.join(model_path, 'wave_decoder_{}_l4.pth'.format(option_unpool)), map_location=lambda storage, loc: storage))\n\n self.encoder = XiaoKeEncoder(option_unpool).to(self.device)\n self.decoder = XiaoKeDecoder(option_unpool).to(self.device)\n self.encoder.load_state_dict(torch.load(os.path.join(model_path,encoder_path),map_location=lambda storage, loc: storage))\n self.decoder.load_state_dict(torch.load(os.path.join(model_path,decoder_path),map_location=lambda storage, loc: storage)) \n\n\n def print_(self, msg):\n if self.verbose:\n print(msg)\n\n def encode(self, x, skips, level):\n return self.encoder.encode(x, skips, level)\n\n def decode(self, x, skips, level):\n return self.decoder.decode(x, skips, level)\n\n def get_all_feature(self, x):\n skips = {}\n feats = {'encoder': {}, 'decoder': {}}\n for level in [1, 2, 3, 4]:\n x = self.encode(x, skips, level)\n if 'encoder' in self.transfer_at:\n feats['encoder'][level] = x\n\n if 'encoder' not in self.transfer_at:\n feats['decoder'][4] = x\n for level in [4, 3, 2]:\n x = self.decode(x, skips, level)\n if 'decoder' in self.transfer_at:\n feats['decoder'][level - 1] = x\n return feats, skips\n\n def transfer(self, content, style, content_segment, style_segment, alpha=1,is_wct=False):\n content_feat, content_skips = content, {}\n style_feats, style_skips = self.get_all_feature(style)\n\n wct2_enc_level = [1, 2, 3, 4]\n wct2_dec_level = [1, 2, 3, 4]\n wct2_skip_level = ['pool1', 'pool2', 'pool3']\n label_set,label_indicator = None, None\n for level in [1, 2, 3, 4]:\n content_feat = self.encode(content_feat, content_skips, level)\n if 'encoder' in self.transfer_at and level in wct2_enc_level:\n if is_wct:\n content_feat = feature_wct(content_feat, style_feats['encoder'][level],\n content_segment, style_segment,\n label_set, label_indicator,\n alpha=alpha, device=self.device)\n else:\n content_feat = feature_adin_without_segment(content_feat, style_feats['encoder'][level],\n content_segment, style_segment,\n label_set, label_indicator,\n alpha=alpha, device=self.device)\n self.print_('transfer at encoder {}'.format(level))\n if 'skip' in self.transfer_at:\n for skip_level in wct2_skip_level:\n if is_wct:\n content_skips[skip_level] = feature_wct(content_skips[skip_level], style_skips[skip_level],\n content_segment, style_segment,\n label_set, label_indicator,\n alpha=alpha, device=self.device)\n else :\n content_skips[skip_level] = feature_adin_without_segment(content_skips[skip_level], style_skips[skip_level],\n content_segment, style_segment,\n label_set, label_indicator,\n alpha=alpha, device=self.device)\n self.print_('transfer at skip {}'.format(skip_level))\n\n for level in [4, 3, 2, 1]:\n if 'decoder' in self.transfer_at and level in style_feats['decoder'] and level in wct2_dec_level:\n if is_wct:\n content_feat = feature_wct(content_feat, style_feats['decoder'][level],\n content_segment, style_segment,\n label_set, label_indicator,\n alpha=alpha, device=self.device)\n else :\n content_feat = feature_adin_without_segment(content_feat, style_feats['decoder'][level],\n content_segment, style_segment,\n label_set, label_indicator,\n alpha=alpha, device=self.device)\n self.print_('transfer at decoder {}'.format(level))\n content_feat = self.decode(content_feat, content_skips, level)\n return content_feat\n\n\ndef get_all_transfer():\n ret = []\n for e in ['encoder']:\n for d in ['decoder']:\n for s in ['skip']:\n _ret = set([e, d, s]) & set(['encoder', 'decoder', 'skip'])\n if _ret:\n ret.append(_ret)\n return ret\n\n# def get_single_transfer():\n# return ['encoder', 'decoder', 'skip']\n\n\n\ndef run_bulk():\n accurate_segment = True\n device = 'cpu' if config.cpu or not torch.cuda.is_available() else 'cuda:0'\n device = torch.device(device)\n\n transfer_at = set()\n if config.transfer_at_encoder:\n transfer_at.add('encoder')\n if config.transfer_at_decoder:\n transfer_at.add('decoder')\n if config.transfer_at_skip:\n transfer_at.add('skip')\n # cw, ch = 640,360 \n cw, ch = 640,400 \n\n # The filenames of the content and style pair should match\n c_transforms = transforms.Compose([transforms.Resize((ch,cw), interpolation=Image.NEAREST),transforms.CenterCrop((ch // 16 * 16, cw // 16 * 16)),transforms.ToTensor()])\n\n fnames = os.listdir(config.content)\n fnames.sort()\n print('transfer at ~~~~',transfer_at)\n style = Image.open(config.style).convert('RGB')\n style = c_transforms(style).unsqueeze(0).to(device)\n sample_fnames = fnames[:50]\n for fname in tqdm.tqdm(sample_fnames):\n if not is_image_file(fname):\n print('invalid file (is not image), ', fname)\n continue\n print('config.wct is ',config.is_wct)\n\n # content\n _content = os.path.join(config.content, fname)\n content = Image.open(_content).convert('RGB') # 别忘了这边的to(device)\n \n content = c_transforms(content).unsqueeze(0).to(device)\n print('current frame {} and shape is {}'.format(fname,content.shape))\n\n\n # _content_segment = os.path.join(config.content_segment, fname) if config.content_segment else None\n # _style_segment = os.path.join(config.style_segment, fname) if config.style_segment else None\n _output = os.path.join(config.output, fname)\n\n content_segment,style_segment = None,None\n if not config.transfer_all:\n with Timer('Elapsed time in whole WCT: {}', config.verbose):\n postfix = '_'.join(sorted(list(transfer_at)))\n fname_output = _output.replace('.png', '_{}_{}.png'.format(config.option_unpool, postfix))\n print('------ transfer:', _output)\n wct2 = WCT2(transfer_at=transfer_at, option_unpool=config.option_unpool, device=device, verbose=config.verbose)\n with torch.no_grad():\n img = wct2.transfer(content, style, content_segment, style_segment, alpha=config.alpha,is_wct=config.is_wct)\n\n save_image(img.clamp_(0, 1), fname_output, padding=0)\n else:\n for _transfer_at in get_all_transfer():\n print('location for transfer at~~~~',_transfer_at)\n with Timer('Elapsed time in whole WCT: {}', config.verbose):\n postfix = '_'.join(sorted(list(_transfer_at)))\n fname_output = _output.replace('.png', '_{}_{}.png'.format(config.option_unpool, postfix))\n print('------ transfer:', fname,'-',_transfer_at)\n wct2 = WCT2(transfer_at=_transfer_at, option_unpool=config.option_unpool, device=device, verbose=config.verbose)\n # print('wct2 model encoder ',wct2.encoder)\n # print('wcr2 model decoder ',wct2.decoder)\n with torch.no_grad():\n starttime = datetime.datetime.now()\n img = wct2.transfer(content, style, content_segment, style_segment, alpha=config.alpha,is_wct=config.is_wct)\n endtime = datetime.datetime.now()\n print('xiaoke with adin 运行时间为----',(endtime - starttime))\n save_image(img.clamp_(0, 1), fname_output, padding=0)\n # break\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--content', type=str, default='./examples/content')\n parser.add_argument('--content_segment', type=str, default='./examples/content_segment')\n parser.add_argument('--style', type=str, default='./examples/style')\n parser.add_argument('--style_segment', type=str, default='./examples/style_segment')\n parser.add_argument('--output', type=str, default='./outputs')\n parser.add_argument('--image_size', type=int, default=512)\n parser.add_argument('--alpha', type=float, default=1)\n parser.add_argument('--option_unpool', type=str, default='cat5', choices=['sum', 'cat5'])\n parser.add_argument('-e', '--transfer_at_encoder', action='store_true')\n parser.add_argument('-d', '--transfer_at_decoder', action='store_true')\n parser.add_argument('-s', '--transfer_at_skip', action='store_true')\n parser.add_argument('-a', '--transfer_all', action='store_true')\n parser.add_argument('--cpu', action='store_true')\n parser.add_argument('--verbose', action='store_true')\n parser.add_argument('--is_wct',action='store_true')\n parser.add_argument('--label_mapping', type=str, default='ade20k_semantic_rel.npy')\n parser.add_argument('--model_path', help='folder to model path', default='baseline-resnet50_dilated8-ppm_bilinear_deepsup')\n parser.add_argument('--arch_encoder', default='resnet50_dilated8', help=\"architecture of net_encoder\")\n parser.add_argument('--arch_decoder', default='ppm_bilinear_deepsup', help=\"architecture of net_decoder\")\n parser.add_argument('--suffix', default='_epoch_20.pth', help=\"which snapshot to load\")\n parser.add_argument('--fc_dim', default=2048, type=int, help='number of features between encoder and decoder')\n parser.add_argument('--num_class', default=150, type=int, help='number of classes')\n parser.add_argument('--padding_constant', default=8, type=int, help='maxmimum downsampling rate of the network')\n parser.add_argument('--gpu_id', default=0, type=int, help='gpu_id for evaluation')\n parser.add_argument('--imgSize', default=[300, 400, 500, 600], nargs='+', type=int, help='list of input image sizes.' 'for multiscale testing, e.g. 300 400 500')\n\n # 不能定义两次同样的参数\n config = parser.parse_args()\n\n\n transform = transforms.Compose([transforms.Normalize(mean=[102.9801, 115.9465, 122.7717], std=[1., 1., 1.])])\n print(config)\n if not os.path.exists(os.path.join(config.output)):\n os.makedirs(os.path.join(config.output))\n run_bulk()\n\n# 树林的图片\n# 171124_D1_HD_01\n# 170216A_122_ForestTrail_1080\n# 170216A_070_LookingUpThroughForest_1080 \n# 180705_01_0\n# 190416_10_Drone1_0\n# Forest_15_1_Videv\n# Forest_15_4_Videv\n# on\n# WalkingThroughTreesatSunsetVidev\n\n\n# 树叶\n# Autumn_leaves_in_motion_0\n# autumn_leaves\n# autumn-leaves-blowing-in-the-wind-H264\n# 180705_01_0\n\n# 海浪\n# 46234354\n# walking_on_the_beac\n\n# 雪山\n# 180607_A_00\n\n# 开车\n# 180607_A_10\n\n# 飞机\n# Airbus_A380_Landing_2__Videv\n# Evening_landin\n# PlaneLand\n\n# 海边瑜伽\n# Ao_Nang_Beach_Yoga_MP4_HDV_1080p25__TanuriX_Stock_Footage_N\n# MVI_126\n\n# 水稻\n# Barley_3_Videv\n# HandStrokin\n\n# wild_gras\n# windygrassnoaudi-\n\n# 船\n# beach1\n# sailing_boa\n\n# 天空\n# Becco_di_Filadonna_su_Vall\n# Blue_Sky_and_Clouds_Timelapse_0892__Videv\n\n# 老鼠\n# CotswoldSequence\n\n\n# 奶牛\n# cow\n# Cow_Mother_and_cal\n# Cows_\n# Limousin_Cows_1__VIdev\n# Limousin_Cows_2__Videv\n\n# 日落\n# Lonely_tree_at_sunset_CCBY_NatureCli\n# MilkyWaywithTreeVidev\n# SilhouetteJogge\n# Sun_to_Sea_Model__Pan_Down_MP4_HDV_1080p25__TanuriX_Stock_Footage_W\n# Sunris\n# TimelapseSunse\n# Wakeboarding_on_the_Lak\n\n\n# 马\n# Dirty_Hors\n\n# 黑白鸟\n# Pigeon-Stock-Vide\n# Red_fod\n# Weave\n\n# 海鸥\n# seagul-H264\n# seagulls_on_the_beac\n\n\n# 建筑\n# Run_5_wo_metadata_h264420_720p_UH\n\n# 鸭子\n# SeaBirdsSwimming_\n# Swans__1287_\n\n# 羊\n# Shee\n\n'''\nCUDA_VISIBLE_DEVICES=6 python transfer.py --content ./examples/content --style ./examples/style --content_segment ./examples/content_segment --style_segment ./examples/style_segment/ --output ./outputs/ --verbose --image_size 512 -a\n'''\n\n\n\n'''\npython xiaoketransfer.py --content ./examples/demo_content/ --style ./examples/demo_style/ -a --output ./examples/demo_stylization --is_wct --image_size 400\nCUDA_VISIBLE_DEVICES=1 python xiaoketransfer.py --content ./examples/dataset/alley_2/ --style ./examples/dataset/fangao.png -a --output ./examples/stylization \n\nCUDA_VISIBLE_DEVICES=1 python xiaoketransfer2.py --content ./examples/data/MPI-Sintel-complete/training/clean/temple_2 --style ./examples/data/fangao.png -a --output ./examples/stylization \n\nCUDA_VISIBLE_DEVICES=1 python xiaoketransfer2.py --content ./examples/data/MPI-Sintel-complete/training/clean/mountain_1 --style ./examples/data/fangao.png -a --output ./examples/stylization \n\nCUDA_VISIBLE_DEVICES=1 python xiaoketransfer2.py --content ./examples/data/MPI-Sintel-complete/training/clean/temple_2 --style ./examples/data/fangao.png -a --output ./examples/stylization --is_wct \n\n'''\n\n\n'''\n'../data/video-picture/160825_26_WindTurbines4_1080'\npython xiaoketransfer2.py --content ../data/video-picture/160825_26_WindTurbines4_1080 --style ./examples/data/fangao.png -a --output ./examples/160825_26_WindTurbines4_1080_adain \n\n'''\n\n'''\n'../data/video-picture/xxx'\npython xiaoketransfer2.py --content ../data/video-picture/180705_01_0 --style ../data/reference/tar0056_orange_forest.png -a --output ./examples/Forest_15_4_Videv \n\npython xiaoketransfer.py --content ../data/video-picture/Red_fod --style ../data/video-picture/Weave/frame_0001.png -a --output ./examples/Red_fod_seg\n\n\npython xiaoketransfer.py --content ../data/video-picture/seagulls_on_the_beac --style ../data/video-picture/seagul-H264/frame_0001.png -a --output ./examples/seagulls_on_the_beac_seg\n\npython xiaoketransfer2.py --content ../data/video-picture/HandStrokin --style ../data/video-picture/Barley_3_Videv/frame_0001.png -a --output ./examples/HandStrokin\n\npython xiaoketransfer.py --content ../data/video-picture/Swans__1287_ --style ../data/video-picture/SeaBirdsSwimming_/frame_0001.png -a --output ./examples/Swans__1287_\n\npython xiaoketransfer.py --content ../data/video-picture/Becco_di_Filadonna_su_Vall --style ../data/video-picture/Blue_Sky_and_Clouds_Timelapse_0892__Videv/frame_0001.png -a --output ./examples/Becco_di_Filadonna_su_Vall\n\npython xiaoketransfer.py --content ../data/video-picture/Sun_to_Sea_Model__Pan_Down_MP4_HDV_1080p25__TanuriX_Stock_Footage_W --style ../data/video-picture/Lonely_tree_at_sunset_CCBY_NatureCli/frame_0004.png -a --output ./examples/Sun_to_Sea_Model__Pan_Down_MP4_HDV_1080p25__TanuriX_Stock_Footage_W\n\n\npython xiaoketransfer2.py --content ../data/video-picture/Wakeboarding_on_the_Lak --style ../data/video-picture/Sunris/frame_0004.png -a --output ./examples/Wakeboarding_on_the_Lak\n\n# Barley_3_Videv\n# HandStrokin\n\n# Pigeon-Stock-Vide\n# Red_fod\n'''"
] | [
[
"torch.device",
"torch.no_grad",
"torch.cuda.is_available"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
mukulbhave/YAD2K | [
"a6174285e036f95df83783b7b4d951094cbb08c8"
] | [
"retrain_yolo.py"
] | [
"\"\"\"\nThis is a script that can be used to retrain the YOLOv2 model for your own dataset.\n\"\"\"\nimport argparse\n\nimport os\nfrom PIL import ImageOps\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport PIL\nimport tensorflow as tf\nfrom keras import backend as K\nfrom keras.layers import Input, Lambda, Conv2D\nfrom keras.models import load_model, Model\nfrom keras import regularizers\nfrom keras.callbacks import TensorBoard, ModelCheckpoint, EarlyStopping\n\nfrom yad2k.models.keras_yolo import (preprocess_true_boxes, yolo_body,\n yolo_eval, yolo_head, yolo_loss)\nfrom yad2k.utils.draw_boxes import draw_boxes\n\nimport h5py\nimport io\nfrom yolo_data_gen import *\n\n# Args\nargparser = argparse.ArgumentParser(\n description=\"Retrain or 'fine-tune' a pretrained YOLOv2 model for your own data.\")\n\nargparser.add_argument(\n '-d',\n '--data_path',\n help=\"path to numpy data file (.npz) containing np.object array 'boxes' and np.uint8 array 'images'\",\n default=os.path.join('..', 'DATA', 'underwater_data.npz'))\n\nargparser.add_argument(\n '-a',\n '--anchors_path',\n help='path to anchors file, defaults to yolo_anchors.txt',\n default=os.path.join('model_data', 'yolo_anchors.txt'))\n\nargparser.add_argument(\n '-c',\n '--classes_path',\n help='path to classes file, defaults to pascal_classes.txt',\n default=os.path.join('..', 'DATA', 'underwater_classes.txt'))\n\n# Default anchor boxes\nYOLO_ANCHORS = np.array(\n ((0.57273, 0.677385), (1.87446, 2.06253), (3.33843, 5.47434),\n (7.88282, 3.52778), (9.77052, 9.16828)))\n\ndef _main(args):\n \n data_path = os.path.expanduser(args.data_path)\n classes_path = os.path.expanduser(args.classes_path)\n anchors_path = os.path.expanduser(args.anchors_path)\n\n class_names = get_classes(classes_path)\n anchors = get_anchors(anchors_path)\n \n dataset = h5py.File(data_path,'r+') \n \n anchors = YOLO_ANCHORS\n\n #detectors_mask, matching_true_boxes = get_detector_mask(boxes, anchors)\n\n model_body, model = create_model(anchors, class_names)\n\n train( model, class_names, anchors, dataset) # image_data, boxes, detectors_mask, matching_true_boxes )\n\n # TODO use data generator for draw as well\n \n \n # draw(model_body,\n # class_names,\n # anchors,\n # image_data,\n # image_set='all', # assumes test set is 0.9\n # weights_name='trained_stage_3_best.h5',\n # save_all=True)\n\n\ndef get_classes(classes_path):\n '''loads the classes'''\n with open(classes_path) as f:\n class_names = f.readlines()\n class_names = [c.strip() for c in class_names]\n return class_names\n\ndef get_anchors(anchors_path):\n '''loads the anchors from a file'''\n if os.path.isfile(anchors_path):\n with open(anchors_path) as f:\n anchors = f.readline()\n anchors = [float(x) for x in anchors.split(',')]\n return np.array(anchors).reshape(-1, 2)\n else:\n Warning(\"Could not open anchors file, using default.\")\n return YOLO_ANCHORS\n \n\n\n#Exactly Same as process data but handles images of different sizes in dataset\ndef scale_data(images, boxes=None):\n '''processes the data'''\n img_shape = (416,416)\n images = [PIL.Image.open(io.BytesIO(i)) for i in images]\n \n \n # Box preprocessing.\n if boxes is not None: \n # Original boxes stored as 1D list of class, x_min, y_min, x_max, y_max.\n boxes = [box.reshape((-1, 5)) for box in boxes]\n # Get box parameters as x_center, y_center, box_width, box_height, class.\n boxes_xy = [0.5 * (box[:, 3:5] + box[:, 1:3]) for box in boxes]\n boxes_wh = [box[:, 3:5] - box[:, 1:3] for box in boxes]\n \n # get original size of each image and and convert the coordinates and w h \n processed_images = []\n for i,img in enumerate(images):\n orig_size = np.array([images[i].width, images[i].height])\n boxes_xy[i] = boxes_xy[i] / orig_size\n boxes_wh[i] = boxes_wh[i] / orig_size\n images_i = images[i].resize(img_shape, PIL.Image.BICUBIC)\n \n images_i = np.array(images_i, dtype=np.float)\n processed_images.append(images_i/255)\n \n boxes = [np.concatenate((boxes_xy[i], boxes_wh[i], box[:, 0:1]), axis=1) for i, box in enumerate(boxes)]\n\n # find the max number of boxes\n max_boxes = 0\n for boxz in boxes:\n if boxz.shape[0] > max_boxes:\n max_boxes = boxz.shape[0]\n\n # add zero pad for training\n for i, boxz in enumerate(boxes):\n if boxz.shape[0] < max_boxes:\n zero_padding = np.zeros( (max_boxes-boxz.shape[0], 5), dtype=np.float32)\n boxes[i] = np.vstack((boxz, zero_padding))\n\n return np.array(processed_images), np.array(boxes)\n \n else:\n processed_images = [resize_image(i,img_shape[0],img_shape[1],False) for i in images]\n processed_images = [np.array(image, dtype=np.float) for image in processed_images]\n processed_images = [image/255. for image in processed_images]\n return np.array(processed_images)\n \n \ndef process_data(images, boxes=None):\n '''processes the data'''\n #images = [PIL.Image.fromarray(i) for i in images]\n images = [PIL.Image.open(io.BytesIO(i)) for i in images]\n orig_size = np.array([images[0].width, images[0].height])\n orig_size = np.expand_dims(orig_size, axis=0)\n print(type(images[0]))\n # Image preprocessing.\n processed_images = [i.resize((416, 416), PIL.Image.BICUBIC) for i in images]\n #processed_images = [resize_image(i,416,416,False) for i in images]\n \n processed_images = [np.array(image, dtype=np.float) for image in processed_images]\n processed_images = [image/255. for image in processed_images]\n\n if boxes is not None:\n # Box preprocessing.\n # Original boxes stored as 1D list of class, x_min, y_min, x_max, y_max.\n boxes = [box.reshape((-1, 5)) for box in boxes]\n # Get extents as y_min, x_min, y_max, x_max, class for comparision with\n # model output.\n #boxes_extents = [box[:, [2, 1, 4, 3, 0]] for box in boxes]\n\n # Get box parameters as x_center, y_center, box_width, box_height, class.\n boxes_xy = [0.5 * (box[:, 3:5] + box[:, 1:3]) for box in boxes]\n boxes_wh = [box[:, 3:5] - box[:, 1:3] for box in boxes]\n boxes_xy = [boxxy / orig_size for boxxy in boxes_xy]\n boxes_wh = [boxwh / orig_size for boxwh in boxes_wh]\n boxes = [np.concatenate((boxes_xy[i], boxes_wh[i], box[:, 0:1]), axis=1) for i, box in enumerate(boxes)]\n\n # find the max number of boxes\n max_boxes = 0\n for boxz in boxes:\n if boxz.shape[0] > max_boxes:\n max_boxes = boxz.shape[0]\n\n # add zero pad for training\n for i, boxz in enumerate(boxes):\n if boxz.shape[0] < max_boxes:\n zero_padding = np.zeros( (max_boxes-boxz.shape[0], 5), dtype=np.float32)\n boxes[i] = np.vstack((boxz, zero_padding))\n\n return np.array(processed_images), np.array(boxes)\n else:\n return np.array(processed_images)\n\ndef get_detector_mask(boxes, anchors):\n '''\n Precompute detectors_mask and matching_true_boxes for training.\n Detectors mask is 1 for each spatial position in the final conv layer and\n anchor that should be active for the given boxes and 0 otherwise.\n Matching true boxes gives the regression targets for the ground truth box\n that caused a detector to be active or 0 otherwise.\n '''\n detectors_mask = [0 for i in range(len(boxes))]\n matching_true_boxes = [0 for i in range(len(boxes))]\n for i, box in enumerate(boxes):\n detectors_mask[i], matching_true_boxes[i] = preprocess_true_boxes(box, anchors, [416, 416])\n\n return np.array(detectors_mask), np.array(matching_true_boxes)\n\ndef create_model(anchors, class_names, load_pretrained=True, freeze_body=True):\n '''\n returns the body of the model and the model\n\n # Params:\n\n load_pretrained: whether or not to load the pretrained model or initialize all weights\n\n freeze_body: whether or not to freeze all weights except for the last layer's\n\n # Returns:\n\n model_body: YOLOv2 with new output layer\n\n model: YOLOv2 with custom loss Lambda layer\n\n '''\n\n detectors_mask_shape = (13, 13, 5, 1)\n matching_boxes_shape = (13, 13, 5, 5)\n\n # Create model input layers.\n image_input = Input(shape=(416, 416, 3))\n boxes_input = Input(shape=(None, 5))\n detectors_mask_input = Input(shape=detectors_mask_shape)\n matching_boxes_input = Input(shape=matching_boxes_shape)\n\n # Create model body.\n yolo_model = yolo_body(image_input, len(anchors), len(class_names))\n topless_yolo = Model(yolo_model.input, yolo_model.layers[-2].output)\n\n if load_pretrained:\n # Save topless yolo:\n topless_yolo_path = os.path.join('model_data', 'yolo_topless.h5')\n if not os.path.exists(topless_yolo_path):\n print(\"CREATING TOPLESS WEIGHTS FILE\")\n yolo_path = os.path.join('model_data', 'yolo.h5')\n model_body = load_model(yolo_path)\n model_body = Model(model_body.inputs, model_body.layers[-2].output)\n model_body.save_weights(topless_yolo_path)\n topless_yolo.load_weights(topless_yolo_path)\n\n if freeze_body:\n for layer in topless_yolo.layers:\n layer.trainable = False\n final_layer = Conv2D(len(anchors)*(5+len(class_names)), (1, 1), activation='linear',kernel_regularizer= regularizers.l2(5e-4))(topless_yolo.output)\n\n model_body = Model(image_input, final_layer)\n\n # Place model loss on CPU to reduce GPU memory usage.\n with tf.device('/cpu:0'):\n # TODO: Replace Lambda with custom Keras layer for loss.\n model_loss = Lambda(\n yolo_loss,\n output_shape=(1, ),\n name='yolo_loss',\n arguments={'anchors': anchors,\n 'num_classes': len(class_names)})([\n model_body.output, boxes_input,\n detectors_mask_input, matching_boxes_input\n ])\n\n model = Model(\n [model_body.input, boxes_input, detectors_mask_input,\n matching_boxes_input], model_loss)\n\n return model_body, model\n\ndef train(model, class_names, anchors, dataset):#image_data, boxes, detectors_mask, matching_true_boxes, validation_split=0.1):\n '''\n retrain/fine-tune the model\n\n logs training with tensorboard\n\n saves training weights in current directory\n\n best weights according to val_loss is saved as trained_stage_3_best.h5\n '''\n model.compile(\n optimizer='adam', loss={\n 'yolo_loss': lambda y_true, y_pred: y_pred\n }) # This is a hack to use the custom loss function in the last layer.\n\n\n logging = TensorBoard()#log_dir='./train_logs', histogram_freq=1, write_graph=False, write_images=True)\n checkpoint = ModelCheckpoint(\"trained_stage_3_best.h5\", monitor='val_loss',\n save_weights_only=True, save_best_only=True)\n early_stopping = EarlyStopping(monitor='val_loss', min_delta=0, patience=15, verbose=1, mode='auto')\n\n batch_size = 8\n dataTrain = dataset['train']\n dataVal= dataset['val']\n train_set_size =dataTrain.attrs['dataset_size']\n val_set_size =dataVal.attrs['dataset_size']\n training_generator = DataGenerator(dataTrain, train_set_size,batch_size=batch_size)\n validation_generator = DataGenerator(dataVal, val_set_size,batch_size=batch_size,is_train=0)\n # model.fit([image_data, boxes, detectors_mask, matching_true_boxes],\n # np.zeros(len(image_data)),\n # validation_split=validation_split,\n # batch_size=8,\n # epochs=5,\n # callbacks=[logging])\n model.fit_generator(generator=training_generator,\n validation_data=validation_generator,\n use_multiprocessing=False,\n epochs=5,verbose = 1, callbacks=[logging])\n model.save_weights('trained_stage_1.h5')\n\n model_body, model = create_model(anchors, class_names, load_pretrained=False, freeze_body=False)\n\n model.load_weights('trained_stage_1.h5')\n\n model.compile(\n optimizer='adam', loss={\n 'yolo_loss': lambda y_true, y_pred: y_pred\n }) # This is a hack to use the custom loss function in the last layer.\n\n \n # model.fit([image_data, boxes, detectors_mask, matching_true_boxes],\n # np.zeros(len(image_data)),\n # validation_split=validation_split,\n # batch_size=8,\n # epochs=30,\n # callbacks=[logging])\n training_generator = DataGenerator(dataTrain, train_set_size,batch_size=batch_size)\n validation_generator = DataGenerator(dataVal, val_set_size,batch_size=batch_size,is_train=0)\n model.fit_generator(generator=training_generator,\n validation_data=validation_generator,\n use_multiprocessing=False,\n epochs=30,verbose = 1, callbacks=[logging])\n model.save_weights('trained_stage_2.h5')\n \n training_generator = DataGenerator(dataTrain, train_set_size,batch_size=batch_size)\n validation_generator = DataGenerator(dataVal, val_set_size,batch_size=batch_size,is_train=0)\n model.fit_generator(generator=training_generator,\n validation_data=validation_generator,\n use_multiprocessing=False,\n epochs=30,verbose = 1, callbacks=[logging, checkpoint, early_stopping])\n # model.fit([image_data, boxes, detectors_mask, matching_true_boxes],\n # np.zeros(len(image_data)),\n # validation_split=validation_split,\n # batch_size=8,\n # epochs=30,\n # callbacks=[logging, checkpoint, early_stopping])\n\n model.save_weights('trained_stage_3.h5')\n\ndef draw(model_body, class_names, anchors, image_data, image_set='val',\n weights_name='trained_stage_3_best.h5', out_path=\"output_images\", save_all=True):\n '''\n Draw bounding boxes on image data\n '''\n if image_set == 'train':\n image_data = np.array([np.expand_dims(image, axis=0)\n for image in image_data[:int(len(image_data)*.9)]])\n elif image_set == 'val':\n image_data = np.array([np.expand_dims(image, axis=0)\n for image in image_data[int(len(image_data)*.9):]])\n elif image_set == 'all':\n image_data = np.array([np.expand_dims(image, axis=0)\n for image in image_data])\n else:\n ValueError(\"draw argument image_set must be 'train', 'val', or 'all'\")\n # model.load_weights(weights_name)\n print(image_data.shape)\n model_body.load_weights(weights_name)\n\n # Create output variables for prediction.\n yolo_outputs = yolo_head(model_body.output, anchors, len(class_names))\n input_image_shape = K.placeholder(shape=(2, ))\n boxes, scores, classes = yolo_eval(\n yolo_outputs, input_image_shape, score_threshold=0.7, iou_threshold=0.7)\n\n # Run prediction on overfit image.\n sess = K.get_session() # TODO: Remove dependence on Tensorflow session.\n\n if not os.path.exists(out_path):\n os.makedirs(out_path)\n for i in range(len(image_data)):\n out_boxes, out_scores, out_classes = sess.run(\n [boxes, scores, classes],\n feed_dict={\n model_body.input: image_data[i],\n input_image_shape: [image_data.shape[2], image_data.shape[3]],\n K.learning_phase(): 0\n })\n print('Found {} boxes for image.'.format(len(out_boxes)))\n print(out_boxes)\n\n # Plot image with predicted boxes.\n image_with_boxes = draw_boxes(image_data[i][0], out_boxes, out_classes,\n class_names, out_scores,out_path+\"\\\\\"+str(i)+'.jpg')\n # Save the image:\n if save_all :\n image = PIL.Image.fromarray(image_with_boxes)\n image.save(os.path.join(out_path,str(i)+'.jpg'))\n\n # To display (pauses the program):\n plt.imshow(image_with_boxes, interpolation='nearest')\n plt.show()\n\n\n\nif __name__ == '__main__':\n args = argparser.parse_args()\n _main(args)\n"
] | [
[
"tensorflow.device",
"numpy.expand_dims",
"matplotlib.pyplot.imshow",
"numpy.vstack",
"numpy.concatenate",
"numpy.array",
"numpy.zeros",
"matplotlib.pyplot.show"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.13",
"1.5",
"1.7",
"0.12",
"1.0",
"1.2"
]
}
] |
traffic-ai/EvalDeT | [
"3b52698e1b03fb9066e3203c2f36aebfa0030aba",
"3b52698e1b03fb9066e3203c2f36aebfa0030aba"
] | [
"tests/unit/test_clearmot.py",
"src/evaldet/tracks.py"
] | [
"import numpy as np\nimport pytest\n\nfrom evaldet import Tracks\nfrom evaldet.mot_metrics.clearmot import calculate_clearmot_metrics\n\n\ndef test_missing_frame_hyp():\n gt = Tracks()\n gt.add_frame(0, [0], np.array([[0, 0, 1, 1]]))\n gt.add_frame(1, [0], np.array([[0, 0, 1, 1]]))\n\n hyp = Tracks()\n hyp.add_frame(0, [0], np.array([[0, 0, 1, 1]]))\n metrics = calculate_clearmot_metrics(gt, hyp)\n\n assert metrics[\"FN_CLEAR\"] == 1\n assert metrics[\"FP_CLEAR\"] == 0\n assert metrics[\"IDS\"] == 0\n\n\ndef test_missing_frame_gt():\n gt = Tracks()\n gt.add_frame(1, [0], np.array([[0, 0, 1, 1]]))\n\n hyp = Tracks()\n hyp.add_frame(0, [0], np.array([[0, 0, 1, 1]]))\n hyp.add_frame(1, [0], np.array([[0, 0, 1, 1]]))\n metrics = calculate_clearmot_metrics(gt, hyp)\n\n assert metrics[\"IDS\"] == 0\n assert metrics[\"FN_CLEAR\"] == 0\n assert metrics[\"FP_CLEAR\"] == 1\n\n\ndef test_no_association_made():\n gt = Tracks()\n gt.add_frame(0, [0], np.array([[10, 10, 11, 11]]))\n\n hyp = Tracks()\n hyp.add_frame(0, [0], np.array([[0, 0, 1, 1]]))\n metrics = calculate_clearmot_metrics(gt, hyp)\n\n assert metrics[\"IDS\"] == 0\n assert metrics[\"FN_CLEAR\"] == 1\n assert metrics[\"FP_CLEAR\"] == 1\n assert metrics[\"MOTA\"] == -1 # Stange but ok\n assert np.isnan(metrics[\"MOTP\"])\n\n\[email protected](\"threshold\", [0.3, 0.5, 0.7])\ndef test_dist_threshold(threshold: float):\n gt = Tracks()\n gt.add_frame(\n 0,\n [0, 1, 2, 3],\n np.array([[0, 0, 1, 1], [0, 0, 1, 1], [0, 0, 1, 1], [0, 0, 1, 1]]),\n )\n\n hyp = Tracks()\n hyp.add_frame(\n 0,\n [0, 1, 2, 3],\n np.array([[0, 0, 1, 0.2], [0, 0, 1, 0.4], [0, 0, 1, 0.6], [0, 0, 1, 0.8]]),\n )\n\n fn_res = {0.3: 3, 0.5: 2, 0.7: 1}\n\n metrics = calculate_clearmot_metrics(gt, hyp, dist_threshold=threshold)\n assert fn_res[threshold] == metrics[\"FN_CLEAR\"]\n\n\ndef test_sticky_association():\n \"\"\"Test that as long as distance is below threshold, the association does\n not switch, even if a detection with better IoU score appears.\n \"\"\"\n gt = Tracks()\n gt.add_frame(0, [0], np.array([[0, 0, 1, 1]]))\n gt.add_frame(1, [0], np.array([[0, 0, 1, 1]]))\n\n hyp = Tracks()\n hyp.add_frame(0, [0], np.array([[0, 0, 1, 1]]))\n hyp.add_frame(1, [0, 1], np.array([[0.1, 0.1, 1.1, 1.1], [0, 0, 1, 1]]))\n\n metrics = calculate_clearmot_metrics(gt, hyp)\n assert metrics[\"FN_CLEAR\"] == 0\n assert metrics[\"IDS\"] == 0\n assert metrics[\"FP_CLEAR\"] == 1\n\n\ndef test_mismatch():\n gt = Tracks()\n gt.add_frame(0, [0], np.array([[0, 0, 1, 1]]))\n gt.add_frame(1, [0], np.array([[0, 0, 1, 1]]))\n\n hyp = Tracks()\n hyp.add_frame(0, [0], np.array([[0, 0, 1, 1]]))\n hyp.add_frame(1, [1], np.array([[0, 0, 1, 1]]))\n\n metrics = calculate_clearmot_metrics(gt, hyp)\n assert metrics[\"FN_CLEAR\"] == 0\n assert metrics[\"IDS\"] == 1\n assert metrics[\"FP_CLEAR\"] == 0\n\n\ndef test_persistent_mismatch():\n \"\"\"Test that association (and therefore mismatch) persists even\n when the first matched hypothesis is gone, as long as another one\n is not assigned.\"\"\"\n gt = Tracks()\n gt.add_frame(0, [0], np.array([[0, 0, 1, 1]]))\n gt.add_frame(1, [0], np.array([[0, 0, 1, 1]]))\n gt.add_frame(2, [0], np.array([[0, 0, 1, 1]]))\n\n hyp = Tracks()\n hyp.add_frame(0, [0], np.array([[0, 0, 1, 1]]))\n hyp.add_frame(2, [1], np.array([[0, 0, 1, 1]]))\n\n metrics = calculate_clearmot_metrics(gt, hyp)\n assert metrics[\"FN_CLEAR\"] == 1\n assert metrics[\"IDS\"] == 1\n assert metrics[\"FP_CLEAR\"] == 0\n\n\ndef test_simple_case():\n \"\"\"Test a simple case with 3 frames and 2 detections/gts per frame.\"\"\"\n gt = Tracks()\n gt.add_frame(0, [0, 1], np.array([[0, 0, 1, 1], [1, 1, 2, 2]]))\n gt.add_frame(1, [0, 1], np.array([[0, 0, 1, 1], [2, 2, 3, 3]]))\n gt.add_frame(2, [0, 1], np.array([[0, 0, 1, 1], [2, 2, 3, 3]]))\n\n hyp = Tracks()\n hyp.add_frame(0, [0, 1], np.array([[0, 0, 1, 1], [1, 1, 2, 2]]))\n hyp.add_frame(1, [0, 1], np.array([[0.1, 0.1, 1.1, 1.1], [1, 1, 2, 2]]))\n hyp.add_frame(2, [2, 1], np.array([[0.05, 0.05, 1.05, 1.05], [2, 2, 3, 3]]))\n\n metrics = calculate_clearmot_metrics(gt, hyp)\n assert metrics[\"FN_CLEAR\"] == 1\n assert metrics[\"IDS\"] == 1\n assert metrics[\"FP_CLEAR\"] == 1\n assert metrics[\"MOTA\"] == 0.5\n assert metrics[\"MOTP\"] == 0.0994008537355717\n",
"from __future__ import annotations\n\nimport csv\nimport xml.etree.ElementTree as ET\nfrom pathlib import Path\nfrom typing import Any, Dict, List, Optional, Set, Union\n\nimport numpy as np\n\n\nclass Tracks:\n \"\"\"A class representing objects' tracks in a MOT setting.\n\n It allows for the tracks to be manually constructed, frame by frame,\n but also provides convenience class methods to initialize it from\n a file, the following formats are currently supported\n\n - MOT format (as described `here <https://motchallenge.net/instructions/>`__)\n - CVAT's version of the MOT format (as described `here <https://openvinotoolkit.github.io/cvat/docs/manual/advanced/formats/format-mot/>`__)\n - CVAT for Video format (as described `here <https://openvinotoolkit.github.io/cvat/docs/manual/advanced/xml_format/>`__)\n - UA-DETRAC XML format (you can download an example `here <https://detrac-db.rit.albany.edu/Tracking>`__)\n \"\"\"\n\n @classmethod\n def from_mot(cls, file_path: Union[Path, str]):\n \"\"\"Creates a Tracks object from detections file in the MOT format.\n\n The format should look like this::\n\n <frame>, <id>, <bb_left>, <bb_top>, <bb_width>, <bb_height>, <conf>, <x>, <y>, <z>\n\n Note that all values above are expected to be **numeric** - string values will\n cause an error. The values for ``conf``, ``x``, ``y`` and ``z`` will be\n ignored.\n\n Args:\n file_path: Path where the detections file is located. The file should be\n in the format described above, and should not have a header.\n \"\"\"\n\n tracks = cls()\n\n with open(file_path, newline=\"\") as file:\n fieldnames = [\n \"frame\",\n \"id\",\n \"bb_left\",\n \"bb_top\",\n \"bb_width\",\n \"bb_height\",\n \"_\",\n ]\n csv_reader = csv.DictReader(file, fieldnames=fieldnames, dialect=\"unix\")\n\n current_frame = -1\n detections: List[List[float]] = []\n ids: List[int] = []\n\n for line_num, line in enumerate(csv_reader):\n try:\n frame_num, track_id = int(line[\"frame\"]), int(line[\"id\"])\n\n xmin, ymin = float(line[\"bb_left\"]), float(line[\"bb_top\"])\n xmax, ymax = xmin + float(line[\"bb_width\"]), ymin + float(\n line[\"bb_height\"]\n )\n except ValueError:\n raise ValueError(\n \"Error when converting values to numbers on line\"\n f\" {line_num}. Please check that all the values are numeric\"\n \" and that the file follows the MOT format.\"\n )\n\n if frame_num > current_frame:\n # Flush current frame\n if current_frame > -1:\n tracks.add_frame(\n current_frame,\n ids=ids,\n detections=np.array(detections, dtype=np.float32),\n )\n\n # Reset frame accumulator objects\n current_frame = frame_num\n detections = []\n ids = []\n\n # Add to frame accumulator objects\n detections.append([xmin, ymin, xmax, ymax])\n ids.append(track_id)\n\n # Flush final frame\n tracks.add_frame(\n current_frame,\n ids=ids,\n detections=np.array(detections, dtype=np.float32),\n )\n\n return tracks\n\n @classmethod\n def from_mot_cvat(cls, file_path: Union[Path, str]) -> Tracks:\n \"\"\"Creates a Tracks object from detections file in the CVAT's MOT format.\n\n The format should look like this::\n\n <frame_id>, <track_id>, <x>, <y>, <w>, <h>, <not ignored>, <class_id>, <visibility>, <skipped>\n\n Note that all values above are expected to be **numeric** - string values will\n cause an error. The last two elements (``visibility`` and ``skipped``) are\n optional. The values for ``not ignored``, ``visibility`` and ``skipped`` will be\n ignored.\n\n Args:\n file_path: Path where the detections file is located. The file should be\n in the format described above, and should not have a header.\n \"\"\"\n\n tracks = cls()\n\n with open(file_path, newline=\"\") as file:\n fieldnames = [\"frame_id\", \"track_id\", \"x\", \"y\", \"w\", \"h\", \"_\", \"class_id\"]\n csv_reader = csv.DictReader(file, fieldnames=fieldnames, dialect=\"unix\")\n\n current_frame = -1\n detections: List[List[float]] = []\n classes: List[int] = []\n ids: List[int] = []\n\n for line_num, line in enumerate(csv_reader):\n try:\n frame_num = int(line[\"frame_id\"])\n track_id, class_id = int(line[\"track_id\"]), int(line[\"class_id\"])\n\n xmin, ymin = float(line[\"x\"]), float(line[\"y\"])\n xmax, ymax = xmin + float(line[\"w\"]), ymin + float(line[\"h\"])\n except ValueError:\n raise ValueError(\n \"Error when converting values to numbers on line\"\n f\" {line_num}. Please check that all the values are numeric\"\n \" and that the file follows the CVAT-MOT format.\"\n )\n\n if frame_num > current_frame:\n # Flush current frame\n if current_frame > -1:\n tracks.add_frame(\n current_frame,\n ids=ids,\n detections=np.array(detections, dtype=np.float32),\n classes=classes,\n )\n\n # Reset frame accumulator objects\n current_frame = frame_num\n detections = []\n classes = []\n ids = []\n\n # Add to frame accumulator objects\n detections.append([xmin, ymin, xmax, ymax])\n classes.append(class_id)\n ids.append(track_id)\n\n # Flush final frame\n tracks.add_frame(\n current_frame,\n ids=ids,\n detections=np.array(detections, dtype=np.float32),\n classes=classes,\n )\n\n return tracks\n\n @classmethod\n def from_ua_detrac(\n cls,\n file_path: Union[Path, str],\n classes_attr_name: Optional[str] = None,\n classes_list: Optional[List[str]] = None,\n ) -> Tracks:\n \"\"\"Creates a Tracks object from detections file in the UA-DETRAC XML format.\n\n Here's how this file might look like:\n\n .. code-block:: xml\n\n <sequence name=\"MVI_20033\">\n <sequence_attribute camera_state=\"unstable\" sence_weather=\"sunny\"/>\n <ignored_region>\n <box height=\"53.75\" left=\"458.75\" top=\"0.5\" width=\"159.5\"/>\n </ignored_region>\n <frame density=\"4\" num=\"1\">\n <target_list>\n <target id=\"1\">\n <box height=\"71.46\" left=\"256.88\" top=\"201.1\" width=\"67.06\"/>\n <attribute color=\"Multi\" orientation=\"315\" speed=\"1.0394\" trajectory_length=\"91\" truncation_ratio=\"0\" vehicle_type=\"Taxi\"/>\n </target>\n </target_list>\n </frame>\n <frame density=\"2\" num=\"2\">\n <target_list>\n <target id=\"2\">\n <box height=\"32.44999999999999\" left=\"329.27\" top=\"96.65\" width=\"56.53000000000003\"/>\n <attribute color=\"Multi\" orientation=\"315\" speed=\"1.0394\" trajectory_length=\"3\" truncation_ratio=\"0\" vehicle_type=\"Car\"/>\n </target>\n <target id=\"4\">\n <box height=\"122.67000000000002\" left=\"0.0\" top=\"356.7\" width=\"76.6\"/>\n <attribute color=\"Multi\" orientation=\"315\" speed=\"1.0394\" trajectory_length=\"1\" truncation_ratio=\"0\" vehicle_type=\"Car\"/>\n </target>\n </target_list>\n </frame>\n </sequence>\n\n The ``ignored_region`` node will not be taken into account - if you want\n some detections to be ignored, you need to filter them prior to the creation\n of the file.\n\n All attributes of each detection will be ignored, except for the one designated\n by ``classes_attr_name`` (for example, in original UA-DETRAC this could be\n ``\"vehicle_type\"``). This would then give values for ``classes`` attribute.\n As this attribute usually contains string values, you also need to provide\n ``classes_list`` - a list of all possible class values. The class attribute will\n then be replaced by the index of the label in this list.\n\n Args:\n file_path: Path where the detections file is located\n classes_attr_name: The name of the attribute to be used for the ``classes``\n attribute. If provided, ``classes_list`` must be provided as well.\n classes_list: The list of all possible class values - must be provided if\n ``classes_attr_name`` is provided. The values from that attribute in the\n file will then be replaced by the index of that value in this list.\n \"\"\"\n\n if classes_attr_name and not classes_list:\n raise ValueError(\n \"If you provide `classes_attr_name`,\"\n \" you must also provide `classes_list`\"\n )\n\n xml_tree = ET.parse(file_path)\n root = xml_tree.getroot()\n tracks = cls()\n\n frames = root.findall(\"frame\")\n for frame in frames:\n tracks_f = frame.find(\"target_list\").findall(\"target\") # type: ignore\n\n current_frame = int(frame.attrib[\"num\"])\n detections: List[List[float]] = []\n classes: List[int] = []\n ids: List[int] = []\n\n for track in tracks_f:\n # Get track attributes\n ids.append(int(track.attrib[\"id\"]))\n\n box = track.find(\"box\")\n xmin, ymin = float(box.attrib[\"left\"]), float(box.attrib[\"top\"]) # type: ignore\n xmax = xmin + float(box.attrib[\"width\"]) # type: ignore\n ymax = ymin + float(box.attrib[\"height\"]) # type: ignore\n detections.append([xmin, ymin, xmax, ymax])\n\n if classes_attr_name:\n attrs = track.find(\"attribute\")\n class_val = attrs.attrib[classes_attr_name] # type: ignore\n class_val = classes_list.index(class_val) # type: ignore\n classes.append(class_val)\n\n tracks.add_frame(\n current_frame,\n ids=ids,\n detections=np.array(detections, dtype=np.float32),\n classes=classes if len(classes) else None,\n )\n\n return tracks\n\n @classmethod\n def from_cvat_video(\n cls,\n file_path: Union[Path, str],\n classes_list: List[str],\n ) -> Tracks:\n \"\"\"Creates a Tracks object from detections file in the CVAT for Video XML\n format.\n\n Here's how this file might look like:\n\n .. code-block:: xml\n\n <annotations>\n <version>1.1</version>\n <meta>\n <!-- lots of non-relevant metadata -->\n </meta>\n <track id=\"0\" label=\"Car\" source=\"manual\">\n <box frame=\"659\" outside=\"0\" occluded=\"0\" keyframe=\"1\" xtl=\"323.83\" ytl=\"104.06\" xbr=\"367.60\" ybr=\"139.49\" z_order=\"-1\"> </box>\n <box frame=\"660\" outside=\"0\" occluded=\"0\" keyframe=\"1\" xtl=\"320.98\" ytl=\"105.24\" xbr=\"365.65\" ybr=\"140.95\" z_order=\"0\"> </box>\n </track>\n <track id=\"1\" label=\"Car\" source=\"manual\">\n <box frame=\"659\" outside=\"0\" occluded=\"0\" keyframe=\"1\" xtl=\"273.10\" ytl=\"88.77\" xbr=\"328.69\" ybr=\"113.09\" z_order=\"1\"> </box>\n <box frame=\"660\" outside=\"0\" occluded=\"0\" keyframe=\"1\" xtl=\"273.10\" ytl=\"88.88\" xbr=\"328.80\" ybr=\"113.40\" z_order=\"0\"> </box>\n </track>\n <track id=\"2\" label=\"Car\" source=\"manual\">\n <box frame=\"659\" outside=\"0\" occluded=\"0\" keyframe=\"1\" xtl=\"375.24\" ytl=\"80.43\" xbr=\"401.65\" ybr=\"102.67\" z_order=\"0\"> </box>\n <box frame=\"660\" outside=\"0\" occluded=\"0\" keyframe=\"1\" xtl=\"374.69\" ytl=\"80.78\" xbr=\"401.09\" ybr=\"103.01\" z_order=\"0\"> </box>\n </track>\n <track id=\"3\" label=\"Car\" source=\"manual\">\n <box frame=\"699\" outside=\"0\" occluded=\"0\" keyframe=\"1\" xtl=\"381.50\" ytl=\"79.04\" xbr=\"405.12\" ybr=\"99.19\" z_order=\"0\"> </box>\n <box frame=\"700\" outside=\"0\" occluded=\"0\" keyframe=\"1\" xtl=\"380.94\" ytl=\"79.60\" xbr=\"404.56\" ybr=\"99.75\" z_order=\"0\"> </box>\n </track>\n </annotations>\n\n All attributes of each detection will be ignored, except for ``label`` (in the\n ``track`` object), which will be used for the ``class`` values. As this\n attribute usually contains string values, you also need to provide\n ``classes_list`` - a list of all possible class values. The class attribute will\n then be replaced by the index of the label in this list.\n\n .. warning::\n As this format organizes detections by id, instead of by frame, all\n detections must first be read in before they can be written to a\n ``Tracks`` object. Therefore, if you are opening large files, you\n can face large memory consumpition.\n\n Args:\n file_path: Path where the detections file is located\n classes_list: The list of all possible class values. The values from that\n attribute in the file will then be replaced by the index of that value\n in this list.\n \"\"\"\n\n xml_tree = ET.parse(file_path)\n root = xml_tree.getroot()\n tracks = cls()\n\n frames: Dict[int, Any] = {}\n tracks_cvat = root.findall(\"track\")\n for track_cvat in tracks_cvat:\n track_id = int(track_cvat.attrib[\"id\"])\n track_class = classes_list.index(track_cvat.attrib[\"label\"])\n\n for box in track_cvat.findall(\"box\"):\n frame_num = int(box.attrib[\"frame\"])\n xmin, ymin = float(box.attrib[\"xtl\"]), float(box.attrib[\"ytl\"])\n xmax, ymax = float(box.attrib[\"xbr\"]), float(box.attrib[\"ybr\"])\n\n current_frame = frames.get(frame_num, {})\n if current_frame:\n current_frame[\"classes\"].append(track_class)\n current_frame[\"ids\"].append(track_id)\n current_frame[\"detections\"].append([xmin, ymin, xmax, ymax])\n else:\n current_frame[\"classes\"] = [track_class]\n current_frame[\"ids\"] = [track_id]\n current_frame[\"detections\"] = [[xmin, ymin, xmax, ymax]]\n frames[frame_num] = current_frame\n\n list_frames = sorted(list(frames.keys()))\n for frame in list_frames:\n tracks.add_frame(\n frame,\n ids=frames[frame][\"ids\"],\n detections=np.array(frames[frame][\"detections\"]),\n classes=frames[frame][\"classes\"],\n )\n\n return tracks\n\n def __init__(self):\n self._last_frame = -1\n\n self._frame_nums = []\n self._detections = dict()\n self._ids = dict()\n self._classes = dict()\n\n self._all_classes = set()\n self._ids_count = {}\n\n def add_frame(\n self,\n frame_num: int,\n ids: List[int],\n detections: np.ndarray,\n classes: Optional[List[int]] = None,\n ):\n \"\"\"Add a frame (observation) to the collection.\n\n Args:\n frame_num: A non-negative frame number, must be larger than\n the number of the most recently added frame.\n ids: A list with ids of the objects in the frame.\n detections: An Nx4 array describing the bounding boxes of objects in\n the frame. It should be in the ``[xmin, ymin, xmax, ymax]`` format.\n classes: An optional list of classes for the objects. If passed all\n objects in the frame must be assigned a class.\n \"\"\"\n\n if frame_num <= self._last_frame:\n raise ValueError(\n f\"You attempted to add frame {frame_num}, but frame {self._last_frame}\"\n \" is already in the collection. New frame numbers should be higher\"\n \" than the largest one in the collection.\"\n )\n\n if len(ids) == 0:\n raise ValueError(\n \"You must pass a non-empty list of `ids` when adding a frame.\"\n )\n\n if detections.ndim != 2:\n raise ValueError(\"The `detections` must be a 2d numpy array.\")\n\n if len(ids) != detections.shape[0]:\n raise ValueError(\n \"The `detections` and `ids` should contain the same number of items.\"\n )\n\n if classes is not None and len(classes) != len(ids):\n raise ValueError(\n \"If `classes` is given, it should contain the same number of items\"\n \" as `ids`.\"\n )\n\n if detections.shape[1] != 4:\n raise ValueError(\n \"The `detections` should be an Nx4 array, but got\"\n f\" shape Nx{detections.shape[1]}\"\n )\n\n if not (detections[:, 2] - detections[:, 0] > 0).all():\n raise ValueError(\n \"Detections have to be in the format [xmin, ymin, xmax, ymax],\"\n \" but one of xmax values is smaller than or equal to its xmin value.\"\n )\n\n if not (detections[:, 3] - detections[:, 1] > 0).all():\n raise ValueError(\n \"Detections have to be in the format [xmin, ymin, xmax, ymax],\"\n \" but one of ymax values is smaller than or equal to its ymin value.\"\n )\n\n if len(set(ids)) != len(ids):\n raise ValueError(\n f\"The `ids` must be unique - got non-unique ids on frame {frame_num}\"\n )\n\n # If all ok, add objects to collections\n self._detections[frame_num] = detections.copy()\n self._ids[frame_num] = ids.copy()\n\n for _id in ids:\n self._ids_count[_id] = self._ids_count.get(_id, 0) + 1\n\n if classes is not None:\n self._classes[frame_num] = classes.copy()\n self._all_classes.update(classes)\n\n self._last_frame = frame_num\n self._frame_nums.append(frame_num)\n\n @property\n def all_classes(self) -> Set[int]:\n \"\"\"Get a set of all classes in the collection.\"\"\"\n return self._all_classes.copy()\n\n @property\n def all_ids(self) -> Set[int]:\n \"\"\"Get a set of all track ids in the collection.\"\"\"\n return set(self._ids_count.keys())\n\n @property\n def ids_count(self) -> Dict[int, int]:\n \"\"\"Get the number of frames that each id is present in.\n\n Returns:\n A dictionary where keys are the track ids, and values\n are the numbers of frames they appear in.\n \"\"\"\n return self._ids_count.copy()\n\n @property\n def frames(self) -> List[int]:\n \"\"\"Get an ordered list of all frame numbers in the collection.\"\"\"\n return self._frame_nums.copy()\n\n def __len__(self) -> int:\n return len(self._frame_nums)\n\n def __contains__(self, idx: int) -> bool:\n \"\"\"Whether the frame ``idx`` is present in the collection.\"\"\"\n return idx in self._frame_nums\n\n def __getitem__(self, idx: int) -> Dict[str, Any]:\n \"\"\"Get the frame with number ``idx``.\n\n Returns:\n A dictionary with the key ``'ids'``, ``'detections'``\n and ``'classes'`` (if available). The values are a list\n (for ids and classes) or a numpy array (for detections)\n with the values for each item in the frame.\n \"\"\"\n if idx not in self:\n raise KeyError(f\"The frame {idx} does not exist.\")\n\n return_dict = {\n \"ids\": self._ids[idx],\n \"detections\": self._detections[idx],\n }\n if idx in self._classes:\n return_dict[\"classes\"] = self._classes[idx]\n\n return return_dict\n"
] | [
[
"numpy.isnan",
"numpy.array"
],
[
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
robustmetalearning/robust-meta-learning | [
"08fc3e9302c9fbd1fcfc3e001e0b080a3c783c81"
] | [
"MAML-ADML/meta.py"
] | [
"import torch\nfrom torch import nn\nfrom torch import optim\nfrom torch.nn import functional as F\nfrom torch.utils.data import TensorDataset, DataLoader\nfrom torch import optim\nimport numpy as np\n\nfrom learner import Learner\nfrom copy import deepcopy\n\ndef zero_nontrainable_grads(grads, trainable_layers=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]):\n for index, grad_tensor in enumerate(grads):\n if index not in trainable_layers:\n grad_tensor = torch.zeros_like(grad_tensor)\n\ndef inputsPGD(metalearner, net, inputs, targets, params = False, evaluate = False):\n if evaluate:\n attack_steps = metalearner.eval_attack_steps\n else:\n attack_steps = metalearner.attack_steps\n x = inputs.detach()\n if not metalearner.no_random_start:\n x = x + torch.zeros_like(x).uniform_(-metalearner.attack_epsilon, metalearner.attack_epsilon)\n for i in range(attack_steps):\n x.requires_grad_()\n with torch.enable_grad():\n if params:\n loss = F.cross_entropy(net(x, params), targets, size_average=False)\n else:\n loss = F.cross_entropy(net(x), targets, size_average=False)\n grad = torch.autograd.grad(loss, [x])[0]\n if metalearner.targeted:\n x = x.detach() - metalearner.attack_step_size*torch.sign(grad.detach())\n else:\n x = x.detach() + metalearner.attack_step_size*torch.sign(grad.detach())\n x = torch.min(torch.max(x, inputs - metalearner.attack_epsilon), inputs + metalearner.attack_epsilon)\n x = torch.clamp(x, 0.0, 1.0)\n return x\n\nclass Meta(nn.Module):\n \"\"\"\n Meta Learner\n \"\"\"\n def __init__(self, args, config):\n \"\"\"\n\n :param args:\n \"\"\"\n super(Meta, self).__init__()\n self.finetune_trainable = args.finetune_trainable\n self.update_lr = args.update_lr\n self.meta_lr = args.meta_lr\n self.n_way = args.n_way\n self.k_spt = args.k_spt\n self.k_qry = args.k_qry\n self.task_num = args.task_num\n self.update_step = args.update_step\n self.update_step_test = args.update_step_test\n self.attack_query = args.attack_query\n self.attack_support = args.attack_support\n self.no_attack_validation = args.no_attack_validation\n self.attack_epsilon = args.attack_epsilon\n self.attack_step_size = args.attack_step_size\n self.attack_steps = args.attack_steps\n self.eval_attack_steps = args.eval_attack_steps\n self.net = Learner(config, args.imgc, args.imgsz)\n self.meta_optim = optim.Adam(self.net.parameters(), lr=self.meta_lr)\n self.no_random_start = args.no_random_start\n self.targeted = args.targeted\n\n def clip_grad_by_norm_(self, grad, max_norm):\n \"\"\"\n in-place gradient clipping.\n :param grad: list of gradients\n :param max_norm: maximum norm allowable\n :return:\n \"\"\"\n\n total_norm = 0\n counter = 0\n for g in grad:\n param_norm = g.data.norm(2)\n total_norm += param_norm.item() ** 2\n counter += 1\n total_norm = total_norm ** (1. / 2)\n\n clip_coef = max_norm / (total_norm + 1e-6)\n if clip_coef < 1:\n for g in grad:\n g.data.mul_(clip_coef)\n\n return total_norm/counter\n\n\n def forward(self, x_spt, y_spt, x_qry, y_qry):\n \"\"\"\n\n :param x_spt: [b, setsz, c_, h, w]\n :param y_spt: [b, setsz]\n :param x_qry: [b, querysz, c_, h, w]\n :param y_qry: [b, querysz]\n :return:\n \"\"\"\n\n task_num, setsz, c_, h, w = x_spt.size()\n querysz = x_qry.size(1)\n losses_q = [0 for _ in range(self.update_step + 1)] # losses_q[i] is the loss on step i\n corrects = [0 for _ in range(self.update_step + 1)] \n\n for i in range(task_num):\n\n # 1. run the i-th task and compute loss for k=0\n if self.attack_support:\n logits = self.net(inputsPGD(self, self.net, x_spt[i], y_spt[i]), vars=None, bn_training=True)\n else:\n logits = self.net(x_spt[i], vars=None, bn_training=True)\n loss = F.cross_entropy(logits, y_spt[i])\n\n grad = torch.autograd.grad(loss, self.net.parameters())\n zero_nontrainable_grads(grad, trainable_layers=self.finetune_trainable)\n fast_weights = list(map(lambda p: p[1] - self.update_lr * p[0], zip(grad, self.net.parameters())))\n\n # this is the loss and accuracy before first update\n\n with torch.no_grad():\n # [setsz, nway]\n logits_q = self.net(x_qry[i], self.net.parameters(), bn_training=True)\n loss_q = F.cross_entropy(logits_q, y_qry[i])\n losses_q[0] += loss_q\n\n pred_q = F.softmax(logits_q, dim=1).argmax(dim=1)\n correct = torch.eq(pred_q, y_qry[i]).sum().item()\n corrects[0] = corrects[0] + correct\n\n # this is the loss and accuracy after the first update\n\n with torch.no_grad():\n # [setsz, nway]\n logits_q = self.net(x_qry[i], fast_weights, bn_training=True)\n loss_q = F.cross_entropy(logits_q, y_qry[i])\n losses_q[1] += loss_q\n # [setsz]\n pred_q = F.softmax(logits_q, dim=1).argmax(dim=1)\n correct = torch.eq(pred_q, y_qry[i]).sum().item()\n corrects[1] = corrects[1] + correct\n\n for k in range(1, self.update_step):\n # 1. run the i-th task and compute loss for k=1~K-1\n if self.attack_support:\n logits = self.net(inputsPGD(self, self.net, x_spt[i], y_spt[i], params = fast_weights), fast_weights, bn_training=True)\n else:\n logits = self.net(x_spt[i], fast_weights, bn_training=True)\n loss = F.cross_entropy(logits, y_spt[i])\n # 2. compute grad on theta_pi\n grad = torch.autograd.grad(loss, fast_weights)\n zero_nontrainable_grads(grad, trainable_layers=self.finetune_trainable)\n # 3. theta_pi = theta_pi - train_lr * grad\n fast_weights = list(map(lambda p: p[1] - self.update_lr * p[0], zip(grad, fast_weights)))\n if self.attack_query:\n logits_q = self.net(inputsPGD(self, self.net, x_qry[i], y_qry[i], params = fast_weights), fast_weights, bn_training=True)\n else:\n logits_q = self.net(x_qry[i], fast_weights, bn_training=True)\n # loss_q will be overwritten and just keep the loss_q on last update step.\n loss_q = F.cross_entropy(logits_q, y_qry[i])\n losses_q[k + 1] += loss_q\n\n with torch.no_grad():\n pred_q = F.softmax(logits_q, dim=1).argmax(dim=1)\n correct = torch.eq(pred_q, y_qry[i]).sum().item() # convert to numpy\n corrects[k + 1] = corrects[k + 1] + correct\n\n\n\n # end of all tasks\n # sum over all losses on query set across all tasks\n loss_q = losses_q[-1] / task_num\n\n # optimize theta parameters\n self.meta_optim.zero_grad()\n loss_q.backward()\n # print('meta update')\n # for p in self.net.parameters()[:5]:\n # \tprint(torch.norm(p).item())\n self.meta_optim.step()\n\n\n accs = np.array(corrects) / (querysz * task_num)\n\n return accs\n\n def finetunning(self, x_spt, y_spt, x_qry, y_qry):\n \"\"\"\n\n :param x_spt: [setsz, c_, h, w]\n :param y_spt: [setsz]\n :param x_qry: [querysz, c_, h, w]\n :param y_qry: [querysz]\n :return:\n \"\"\"\n assert len(x_spt.shape) == 4\n print('Validating...')\n\n querysz = x_qry.size(0)\n\n natural_corrects = [0 for _ in range(self.update_step_test + 1)]\n robust_corrects = [0 for _ in range(self.update_step_test + 1)]\n\n # in order to not ruin the state of running_mean/variance and bn_weight/bias\n # we finetunning on the copied model instead of self.net\n net = deepcopy(self.net)\n\n # 1. run the i-th task and compute loss for k=0\n logits = net(x_spt)\n loss = F.cross_entropy(logits, y_spt)\n grad = torch.autograd.grad(loss, net.parameters())\n zero_nontrainable_grads(grad, trainable_layers=self.finetune_trainable)\n fast_weights = list(map(lambda p: p[1] - self.update_lr * p[0], zip(grad, net.parameters())))\n\n # this is the loss and accuracy before first update\n with torch.no_grad():\n # [setsz, nway]\n logits_q = net(x_qry, net.parameters(), bn_training=True)\n # [setsz]\n pred_q = F.softmax(logits_q, dim=1).argmax(dim=1)\n # scalar\n natural_correct = torch.eq(pred_q, y_qry).sum().item()\n natural_corrects[0] = natural_corrects[0] + natural_correct\n\n # [setsz, nway]\n robust_logits_q = net(inputsPGD(self, net, x_qry, y_qry, net.parameters(), evaluate=True), net.parameters(), bn_training=True)\n # [setsz]\n robust_pred_q = F.softmax(robust_logits_q, dim=1).argmax(dim=1)\n # scalar\n robust_correct = torch.eq(robust_pred_q, y_qry).sum().item()\n robust_corrects[0] = robust_corrects[0] + robust_correct\n\n # this is the loss and accuracy after the first update\n with torch.no_grad():\n # [setsz, nway]\n logits_q = net(x_qry, fast_weights, bn_training=True)\n # [setsz]\n pred_q = F.softmax(logits_q, dim=1).argmax(dim=1)\n # scalar\n correct = torch.eq(pred_q, y_qry).sum().item()\n natural_corrects[1] = natural_corrects[1] + natural_correct\n\n # [setsz, nway]\n robust_logits_q = net(inputsPGD(self, net, x_qry, y_qry, fast_weights, evaluate=True), fast_weights, bn_training=True)\n # [setsz]\n robust_pred_q = F.softmax(robust_logits_q, dim=1).argmax(dim=1)\n # scalar\n robust_correct = torch.eq(robust_pred_q, y_qry).sum().item()\n robust_corrects[1] = robust_corrects[1] + robust_correct\n\n for k in range(1, self.update_step_test):\n # 1. run the i-th task and compute loss for k=1~K-1\n logits = net(x_spt, fast_weights, bn_training=True)\n loss = F.cross_entropy(logits, y_spt)\n # 2. compute grad on theta_pi\n grad = torch.autograd.grad(loss, fast_weights)\n zero_nontrainable_grads(grad, trainable_layers=self.finetune_trainable)\n # 3. theta_pi = theta_pi - train_lr * grad\n fast_weights = list(map(lambda p: p[1] - self.update_lr * p[0], zip(grad, fast_weights)))\n\n logits_q = net(x_qry, fast_weights, bn_training=True)\n # loss_q will be overwritten and just keep the loss_q on last update step.\n loss_q = F.cross_entropy(logits_q, y_qry)\n\n with torch.no_grad():\n pred_q = F.softmax(logits_q, dim=1).argmax(dim=1)\n natural_correct = torch.eq(pred_q, y_qry).sum().item() # convert to numpy\n natural_corrects[k + 1] = natural_corrects[k + 1] + natural_correct\n\n robust_logits_q = net(inputsPGD(self, net, x_qry, y_qry, fast_weights, evaluate=True), fast_weights, bn_training=True)\n # loss_q will be overwritten and just keep the loss_q on last update step.\n robust_loss_q = F.cross_entropy(robust_logits_q, y_qry)\n\n with torch.no_grad():\n robust_pred_q = F.softmax(robust_logits_q, dim=1).argmax(dim=1)\n robust_correct = torch.eq(robust_pred_q, y_qry).sum().item() # convert to numpy\n robust_corrects[k + 1] = robust_corrects[k + 1] + robust_correct\n\n del net\n\n natural_accs = np.array(natural_corrects) / querysz\n robust_accs = np.array(robust_corrects) / querysz\n\n\n ########################### DO THE SAME THING BUT ADVERSARIALLY TRAINED ON SUPPORT ########################\n\n natural_corrects = [0 for _ in range(self.update_step_test + 1)]\n robust_corrects = [0 for _ in range(self.update_step_test + 1)]\n\n # in order to not ruin the state of running_mean/variance and bn_weight/bias\n # we finetunning on the copied model instead of self.net\n net = deepcopy(self.net)\n\n # 1. run the i-th task and compute loss for k=0\n logits = net(inputsPGD(self, net, x_spt, y_spt), bn_training=True)\n loss = F.cross_entropy(logits, y_spt)\n grad = torch.autograd.grad(loss, net.parameters())\n zero_nontrainable_grads(grad, trainable_layers=self.finetune_trainable)\n fast_weights = list(map(lambda p: p[1] - self.update_lr * p[0], zip(grad, net.parameters())))\n\n # this is the loss and accuracy before first update\n with torch.no_grad():\n # [setsz, nway]\n logits_q = net(x_qry, net.parameters(), bn_training=True)\n # [setsz]\n pred_q = F.softmax(logits_q, dim=1).argmax(dim=1)\n # scalar\n natural_correct = torch.eq(pred_q, y_qry).sum().item()\n natural_corrects[0] = natural_corrects[0] + natural_correct\n\n # [setsz, nway]\n robust_logits_q = net(inputsPGD(self, net, x_qry, y_qry, net.parameters(), evaluate=True), net.parameters(), bn_training=True)\n # [setsz]\n robust_pred_q = F.softmax(robust_logits_q, dim=1).argmax(dim=1)\n # scalar\n robust_correct = torch.eq(robust_pred_q, y_qry).sum().item()\n robust_corrects[0] = robust_corrects[0] + robust_correct\n\n # this is the loss and accuracy after the first update\n with torch.no_grad():\n # [setsz, nway]\n logits_q = net(x_qry, fast_weights, bn_training=True)\n # [setsz]\n pred_q = F.softmax(logits_q, dim=1).argmax(dim=1)\n # scalar\n correct = torch.eq(pred_q, y_qry).sum().item()\n natural_corrects[1] = natural_corrects[1] + natural_correct\n\n # [setsz, nway]\n robust_logits_q = net(inputsPGD(self, net, x_qry, y_qry, fast_weights, evaluate=True), fast_weights, bn_training=True)\n # [setsz]\n robust_pred_q = F.softmax(robust_logits_q, dim=1).argmax(dim=1)\n # scalar\n robust_correct = torch.eq(robust_pred_q, y_qry).sum().item()\n robust_corrects[1] = robust_corrects[1] + robust_correct\n\n for k in range(1, self.update_step_test):\n # 1. run the i-th task and compute loss for k=1~K-1\n logits = net(inputsPGD(self, net, x_spt, y_spt, params = fast_weights), fast_weights, bn_training=True)\n loss = F.cross_entropy(logits, y_spt)\n # 2. compute grad on theta_pi\n grad = torch.autograd.grad(loss, fast_weights)\n zero_nontrainable_grads(grad, trainable_layers=self.finetune_trainable)\n # 3. theta_pi = theta_pi - train_lr * grad\n fast_weights = list(map(lambda p: p[1] - self.update_lr * p[0], zip(grad, fast_weights)))\n\n logits_q = net(x_qry, fast_weights, bn_training=True)\n # loss_q will be overwritten and just keep the loss_q on last update step.\n loss_q = F.cross_entropy(logits_q, y_qry)\n\n with torch.no_grad():\n pred_q = F.softmax(logits_q, dim=1).argmax(dim=1)\n natural_correct = torch.eq(pred_q, y_qry).sum().item() # convert to numpy\n natural_corrects[k + 1] = natural_corrects[k + 1] + natural_correct\n\n robust_logits_q = net(inputsPGD(self, net, x_qry, y_qry, fast_weights, evaluate=True), fast_weights, bn_training=True)\n # loss_q will be overwritten and just keep the loss_q on last update step.\n robust_loss_q = F.cross_entropy(robust_logits_q, y_qry)\n\n with torch.no_grad():\n robust_pred_q = F.softmax(robust_logits_q, dim=1).argmax(dim=1)\n robust_correct = torch.eq(robust_pred_q, y_qry).sum().item() # convert to numpy\n robust_corrects[k + 1] = robust_corrects[k + 1] + robust_correct\n\n del net\n\n natural_accs_advTrained = np.array(natural_corrects) / querysz\n robust_accs_advTrained = np.array(robust_corrects) / querysz\n\n return natural_accs, robust_accs, natural_accs_advTrained, robust_accs_advTrained\n\n\n\n\ndef main():\n pass\n\n\nif __name__ == '__main__':\n main()\n"
] | [
[
"torch.nn.functional.softmax",
"torch.enable_grad",
"torch.max",
"torch.eq",
"torch.nn.functional.cross_entropy",
"torch.zeros_like",
"torch.no_grad",
"torch.clamp",
"numpy.array",
"torch.autograd.grad"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ondrejklejch/learning_to_adapt | [
"6de0b98370769596da16a1688582925ea2e1fa29",
"6de0b98370769596da16a1688582925ea2e1fa29"
] | [
"steps/nnet3/train.py",
"tests/model/meta_test.py"
] | [
"import sys\nimport numpy as np\n\nfrom keras.callbacks import ModelCheckpoint, CSVLogger, LearningRateScheduler\nfrom keras.models import Model\nfrom keras.layers import Input, Activation, Conv1D, BatchNormalization\nfrom keras.optimizers import Adam\n\nfrom learning_to_adapt.model import LHUC, Renorm\nfrom learning_to_adapt.utils import load_dataset, load_utt_to_spk, load_utt_to_pdfs, load_lda\n\nimport keras\nimport tensorflow as tf\n\nconfig = tf.ConfigProto()\nconfig.intra_op_parallelism_threads=1\nconfig.inter_op_parallelism_threads=1\nkeras.backend.tensorflow_backend.set_session(tf.Session(config=config))\n\n\ndef create_model(hidden_dim=350, lda_path=None):\n lda, bias = load_lda(lda_path)\n lda = lda.reshape((5, 40, 200))\n\n feats = Input(shape=(None, 40))\n x = Conv1D(200, kernel_size=5, name=\"lda\", trainable=False, weights=[lda, bias])(feats)\n\n layers = [(1, 1), (2, 3), (2, 6), (2, 9), (2, 6), (1, 1)]\n for i, (kernel_size, dilation_rate) in enumerate(layers):\n name = \"tdnn%d\" % (i + 1)\n x = Conv1D(hidden_dim, kernel_size=kernel_size, dilation_rate=dilation_rate, activation=\"relu\", name=\"%s.affine\" % name)(x)\n x = BatchNormalization(name=\"%s.batchnorm\" % name)(x)\n x = LHUC(name=\"lhuc.%s\" % name, trainable=False)(x)\n\n y = Conv1D(4208, kernel_size=1, activation=\"softmax\", name=\"output.affine\")(x)\n\n return Model(inputs=[feats], outputs=[y])\n\n\nif __name__ == '__main__':\n train_data = sys.argv[1]\n val_data = sys.argv[2]\n utt2spk = sys.argv[3]\n pdfs = sys.argv[4]\n left_context = int(sys.argv[5])\n right_context = int(sys.argv[6])\n lda_path = sys.argv[7]\n output_path = sys.argv[8]\n\n num_epochs = 400\n batch_size = 256\n learning_rate = 0.0015\n\n utt_to_spk = load_utt_to_spk(utt2spk)\n utt_to_pdfs = load_utt_to_pdfs(pdfs)\n\n train_dataset = load_dataset(train_data, utt_to_spk, utt_to_pdfs, chunk_size=8, subsampling_factor=1, left_context=left_context, right_context=right_context)\n train_dataset = train_dataset.batch(batch_size, drop_remainder=True)\n train_dataset = train_dataset.prefetch(1024)\n x, _, y = train_dataset.make_one_shot_iterator().get_next()\n\n val_dataset = load_dataset(val_data, utt_to_spk, utt_to_pdfs, chunk_size=8, subsampling_factor=1, left_context=left_context, right_context=right_context)\n val_dataset = val_dataset.batch(batch_size, drop_remainder=True)\n val_dataset = val_dataset.take(512).cache().repeat()\n val_x, _, val_y = val_dataset.make_one_shot_iterator().get_next()\n\n model = create_model(600, lda_path)\n model.compile(\n loss='sparse_categorical_crossentropy',\n metrics=['accuracy'],\n optimizer=Adam(lr=learning_rate, amsgrad=True, clipvalue=1.)\n )\n\n callbacks = [\n CSVLogger(output_path + \"model.csv\"),\n ModelCheckpoint(filepath=output_path + \"model.{epoch:02d}.h5\", save_best_only=False, period=10),\n ModelCheckpoint(filepath=output_path + \"model.best.h5\", save_best_only=True),\n LearningRateScheduler(lambda epoch, lr: learning_rate - epoch * (learning_rate - learning_rate / 10) / num_epochs, verbose=0)\n ]\n\n model.fit(x, y,\n steps_per_epoch=2000,\n epochs=num_epochs,\n validation_data=(val_x, val_y),\n validation_steps=512,\n callbacks=callbacks\n )\n",
"from keras.layers import Dense, Conv1D\nfrom keras.models import Sequential\nimport numpy as np\nimport unittest\n\nfrom learning_to_adapt.model import create_meta_learner, create_model_wrapper\n\n\nclass TestLoop(unittest.TestCase):\n\n def testMetaLearnerCanPredict(self):\n model = self.create_model()\n wrapper = create_model_wrapper(model)\n meta = create_meta_learner(wrapper)\n meta.compile(loss=model.loss, optimizer='adam')\n\n batch = next(self.generator())\n self.assertEquals((1, 1, 2, 1), meta.predict(batch[0]).shape)\n\n def testMetaLearnerCanOverfit(self):\n np.random.seed(0)\n\n model = self.create_model()\n wrapper = create_model_wrapper(model)\n meta = create_meta_learner(wrapper)\n meta.compile(loss=model.loss, optimizer='adam')\n\n generator = self.generator()\n history = meta.fit_generator(generator, steps_per_epoch=100, epochs=5)\n\n loss = history.history[\"loss\"]\n self.assertTrue(loss[0] > loss[-1])\n self.assertTrue(0.05 > loss[-1])\n\n def create_model(self):\n model = Sequential()\n model.add(Conv1D(2, 1, use_bias=True, input_shape=(None, 1), trainable=False))\n model.add(Conv1D(1, 1, use_bias=True))\n model.compile(loss='mse', optimizer='adam')\n return model\n\n def generator(self):\n while True:\n params = np.array([[1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]])\n training_feats = np.array([[[[1.], [0.]]] * 5])\n training_labels = np.array([[[[1.], [0.]]] * 5])\n testing_feats = np.array([[[1.], [0.]]])\n testing_labels = np.array([[[1.], [0.]]])\n\n training_feats = np.expand_dims(training_feats, 2)\n training_labels = np.expand_dims(training_labels, 2)\n testing_feats = np.expand_dims(testing_feats, 1)\n testing_labels = np.expand_dims(testing_labels, 1)\n\n yield [params, training_feats, training_labels, testing_feats], testing_labels\n"
] | [
[
"tensorflow.ConfigProto",
"tensorflow.Session"
],
[
"numpy.array",
"numpy.expand_dims",
"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"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
madhukarkm/NeMo | [
"648c97f076147684bee6aaada209f2f20adcaf5d",
"648c97f076147684bee6aaada209f2f20adcaf5d",
"648c97f076147684bee6aaada209f2f20adcaf5d",
"648c97f076147684bee6aaada209f2f20adcaf5d",
"648c97f076147684bee6aaada209f2f20adcaf5d",
"648c97f076147684bee6aaada209f2f20adcaf5d",
"648c97f076147684bee6aaada209f2f20adcaf5d",
"648c97f076147684bee6aaada209f2f20adcaf5d",
"648c97f076147684bee6aaada209f2f20adcaf5d"
] | [
"nemo/collections/nlp/data/data_utils/data_preprocessing.py",
"tests/core/test_fileio.py",
"scripts/dataset_processing/ljspeech/calculate_durs.py",
"scripts/voice_activity_detection/vad_overlap_posterior.py",
"nemo/collections/nlp/modules/common/megatron/megatron_utils.py",
"nemo/collections/tts/helpers/helpers.py",
"tools/ctc_segmentation/scripts/cut_audio.py",
"nemo/collections/tts/models/fastspeech2_hifigan_e2e.py",
"nemo/collections/nlp/models/entity_linking/entity_linking_model.py"
] | [
"# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport csv\nimport json\nimport os\nimport pickle\nimport random\nimport re\nimport string\nfrom collections import Counter\n\nimport numpy as np\nimport torch\nfrom tqdm.auto import tqdm\n\nfrom nemo.utils import logging\nfrom nemo.utils.env_var_parsing import get_envint\n\n__all__ = [\n 'DataProcessor',\n 'get_label_stats',\n 'partition_data',\n 'write_files',\n 'write_data',\n 'create_dataset',\n 'read_csv',\n 'get_dataset',\n 'partition',\n 'map_entities',\n 'get_entities',\n 'get_data',\n 'reverse_dict',\n 'get_intent_labels',\n 'get_stats',\n 'DATABASE_EXISTS_TMP',\n 'MODE_EXISTS_TMP',\n 'is_whitespace',\n 'write_vocab',\n 'if_exist',\n 'remove_punctuation_from_sentence',\n 'dataset_to_ids',\n 'get_freq_weights',\n 'fill_class_weights',\n 'normalize_answer',\n 'get_labels_to_labels_id_mapping',\n 'get_vocab',\n 'find_newlines',\n 'load_data_indices',\n 'chinese_punctuation',\n 'check_chinese_char',\n 'normalize_chinese_answer',\n]\n\nDATABASE_EXISTS_TMP = '{} dataset has already been processed and stored at {}'\nMODE_EXISTS_TMP = '{} mode of {} dataset has already been processed and stored at {}'\n\n\nclass DataProcessor(object):\n \"\"\"Base class for data converters for sequence classification data sets.\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"Gets a collection of `InputExample`s for the train set.\"\"\"\n raise NotImplementedError()\n\n def get_dev_examples(self, data_dir):\n \"\"\"Gets a collection of `InputExample`s for the dev set.\"\"\"\n raise NotImplementedError()\n\n def get_labels(self):\n \"\"\"Gets the list of labels for this data set.\"\"\"\n raise NotImplementedError()\n\n @classmethod\n def _read_tsv(cls, input_file, quotechar=None):\n \"\"\"Reads a tab separated value file.\"\"\"\n with open(input_file, \"r\", encoding=\"utf-8-sig\") as f:\n reader = csv.reader(f, delimiter=\"\\t\", quotechar=quotechar)\n lines = []\n for line in reader:\n # if sys.version_info[0] == 2:\n # line = list(unicode(cell, 'utf-8') for cell in line)\n lines.append(line)\n return lines\n\n\nchinese_punctuation = {\n '——',\n '‘',\n '’',\n '“',\n '”',\n '…',\n '、',\n '。',\n '〈',\n '〉',\n '《',\n '》',\n '「',\n '」',\n '『',\n '』',\n '【',\n '】',\n '〔',\n '〕',\n '!',\n '(',\n ')',\n ',',\n '.',\n ':',\n ';',\n '?',\n}\n\n\ndef check_chinese_char(ch):\n \"\"\"Check if a character is in Chinese.\"\"\"\n if u'\\u4e00' <= ch <= u'\\u9fff' or ch in chinese_punctuation:\n return True\n else:\n return False\n\n\ndef normalize_chinese_answer(text):\n \"\"\"Remove the Chinese punctuation and separate Chinese answers to char-level\"\"\"\n\n def remove_punc(text):\n exclude = chinese_punctuation\n return ''.join(ch for ch in text if ch not in exclude)\n\n def separate_char(text):\n ch_list = []\n for ch in text:\n ch_list.append(ch)\n return ch_list\n\n return separate_char(remove_punc(text))\n\n\ndef normalize_answer(s):\n \"\"\"Lower text and remove punctuation, articles and extra whitespace.\"\"\"\n\n def remove_articles(text):\n return re.sub(r'\\b(a|an|the)\\b', ' ', text)\n\n def white_space_fix(text):\n return ' '.join(text.split())\n\n def remove_punc(text):\n exclude = set(string.punctuation)\n return ''.join(ch for ch in text if ch not in exclude)\n\n def lower(text):\n return text.lower()\n\n return white_space_fix(remove_articles(remove_punc(lower(s))))\n\n\ndef get_label_stats(labels, outfile='stats.tsv', verbose=True):\n '''\n\n Args:\n labels: list of all labels\n outfile: path to the file where to save label stats\n\n Returns:\n total (int): total number of labels\n label_frequencies (list of tuples): each tuple represent (label, label frequency)\n max id of the labels\n '''\n labels = Counter(labels)\n total = sum(labels.values())\n out = open(outfile, 'w')\n i = 0\n freq_dict = {}\n label_frequencies = labels.most_common()\n for k, v in label_frequencies:\n out.write(f'{k}\\t\\t{round(v/total,5)}\\t\\t{v}\\n')\n if verbose and i < 3:\n logging.info(f'label: {k}, {v} out of {total} ({(v / total)*100.0:.2f}%).')\n i += 1\n freq_dict[k] = v\n\n return total, freq_dict, max(labels.keys())\n\n\ndef partition_data(intent_queries, slot_tags, split=0.1):\n n = len(intent_queries)\n n_dev = int(n * split)\n dev_idx = set(random.sample(range(n), n_dev))\n dev_intents, dev_slots, train_intents, train_slots = [], [], [], []\n\n dev_intents.append('sentence\\tlabel\\n')\n train_intents.append('sentence\\tlabel\\n')\n\n for i, item in enumerate(intent_queries):\n if i in dev_idx:\n dev_intents.append(item)\n dev_slots.append(slot_tags[i])\n else:\n train_intents.append(item)\n train_slots.append(slot_tags[i])\n return train_intents, train_slots, dev_intents, dev_slots\n\n\ndef write_files(data, outfile):\n with open(outfile, 'w') as f:\n for item in data:\n item = f'{item.strip()}\\n'\n f.write(item)\n\n\ndef write_data(data, slot_dict, intent_dict, outfold, mode, uncased):\n intent_file = open(f'{outfold}/{mode}.tsv', 'w')\n intent_file.write('sentence\\tlabel\\n')\n slot_file = open(f'{outfold}/{mode}_slots.tsv', 'w')\n for tokens, slots, intent in data:\n text = ' '.join(tokens)\n if uncased:\n text = text.lower()\n intent_file.write(f'{text}\\t{intent_dict[intent]}\\n')\n slots = [str(slot_dict[slot]) for slot in slots]\n slot_file.write(' '.join(slots) + '\\n')\n intent_file.close()\n slot_file.close()\n\n\ndef create_dataset(train, dev, slots, intents, uncased, outfold):\n os.makedirs(outfold, exist_ok=True)\n if 'O' in slots:\n slots.remove('O')\n slots = sorted(list(slots)) + ['O']\n intents = sorted(list(intents))\n slots = write_vocab(slots, f'{outfold}/dict.slots.csv')\n intents = write_vocab(intents, f'{outfold}/dict.intents.csv')\n write_data(train, slots, intents, outfold, 'train', uncased)\n write_data(dev, slots, intents, outfold, 'test', uncased)\n\n\ndef read_csv(file_path):\n rows = []\n with open(file_path, 'r') as csvfile:\n read_csv = csv.reader(csvfile, delimiter=',')\n for row in read_csv:\n rows.append(row)\n return rows\n\n\ndef get_dataset(files, dev_split=0.1):\n # entity2value, value2entity = get_entities(files)\n data, slots, intents = get_data(files)\n if len(data) == 1:\n train, dev = partition(data[0], split=dev_split)\n else:\n train, dev = data[0], data[1]\n return train, dev, slots, intents\n\n\ndef partition(data, split=0.1):\n n = len(data)\n n_dev = int(n * split)\n dev_idx = set(random.sample(range(n), n_dev))\n dev, train = [], []\n\n for i, item in enumerate(data):\n if i in dev_idx:\n dev.append(item)\n else:\n train.append(item)\n return train, dev\n\n\ndef map_entities(entity2value, entities):\n for key in entities:\n if 'data' in entities[key]:\n if key not in entity2value:\n entity2value[key] = set([])\n\n values = []\n for value in entities[key]['data']:\n values.append(value['value'])\n values.extend(value['synonyms'])\n entity2value[key] = entity2value[key] | set(values)\n\n return entity2value\n\n\ndef get_entities(files):\n entity2value = {}\n for file in files:\n with open(file, 'r') as json_file:\n data = json.load(json_file)\n entity2value = map_entities(entity2value, data['entities'])\n\n value2entity = reverse_dict(entity2value)\n return entity2value, value2entity\n\n\ndef get_data(files):\n all_data, all_slots, all_intents = [], set(['O']), set()\n for file in files:\n file_data = []\n with open(file, 'r') as json_file:\n data = json.load(json_file)\n for intent in data['intents']:\n all_intents.add(intent)\n utterances = data['intents'][intent]['utterances']\n for utterance in utterances:\n tokens, slots = [], []\n for frag in utterance['data']:\n frag_tokens = frag['text'].strip().split()\n tokens.extend(frag_tokens)\n if 'slot_name' not in frag:\n slot = 'O'\n else:\n slot = frag['slot_name']\n all_slots.add(slot)\n slots.extend([slot] * len(frag_tokens))\n file_data.append((tokens, slots, intent))\n all_data.append(file_data)\n return all_data, all_slots, all_intents\n\n\ndef reverse_dict(entity2value):\n value2entity = {}\n for entity in entity2value:\n for value in entity2value[entity]:\n value2entity[value] = entity\n return value2entity\n\n\ndef get_intent_labels(intent_file):\n labels = {}\n label = 0\n with open(intent_file, 'r') as f:\n for line in f:\n intent = line.strip()\n labels[intent] = label\n label += 1\n return labels\n\n\ndef get_stats(lengths):\n logging.info('Some stats of the lengths of the sequences:')\n lengths = np.asarray(lengths)\n logging.info(\n f'Min: {np.min(lengths)} | \\\n Max: {np.max(lengths)} | \\\n Mean: {np.mean(lengths)} | \\\n Median: {np.median(lengths)}'\n )\n logging.info(f'75 percentile: {np.percentile(lengths, 75):.2f}')\n logging.info(f'99 percentile: {np.percentile(lengths, 99):.2f}')\n\n\ndef is_whitespace(c):\n if c == \" \" or c == \"\\t\" or c == \"\\r\" or c == \"\\n\" or ord(c) == 0x202F:\n return True\n return False\n\n\ndef write_vocab(items, outfile):\n vocab = {}\n idx = 0\n with open(outfile, 'w') as f:\n for item in items:\n f.write(item + '\\n')\n vocab[item] = idx\n idx += 1\n return vocab\n\n\ndef get_labels_to_labels_id_mapping(file):\n '''\n Reads labels from the file and returns labels to id mapping dictionary\n Args:\n file: path to file\n Returns:\n labels to id mapping dictionary\n '''\n lines = open(file, 'r').readlines()\n lines = [line.strip() for line in lines if line.strip()]\n label_ids = {lines[i]: i for i in range(len(lines))}\n return label_ids\n\n\ndef if_exist(outfold, files):\n if not os.path.exists(outfold):\n return False\n for file in files:\n if not os.path.exists(f'{outfold}/{file}'):\n return False\n return True\n\n\ndef remove_punctuation_from_sentence(sentence):\n sentence = re.sub('[' + string.punctuation + ']', '', sentence)\n sentence = sentence.lower()\n return sentence\n\n\ndef dataset_to_ids(dataset, tokenizer, cache_ids=False, add_bos_eos=True, cache_data_per_node=False, use_cache=False):\n \"\"\"\n Reads dataset from file line by line, tokenizes each line with tokenizer,\n and returns list of lists which corresponds to ids of tokenized strings.\n\n Args:\n dataset (str): path to dataset\n tokenizer: tokenizer to convert text into ids\n cache_ids (bool): if True, ids are saved to disk as pickle file\n with similar name (e.g., data.txt --> data.txt.pkl)\n add_bos_eos (bool): whether to add <s> and </s> symbols (e.g., for NMT)\n cache_data_per_node (bool): Cache data on local_rank 0. Use when there is not a shared-filesystem.\n use_cache (bool): Use cached ids if they exist.\n Returns:\n ids: list of ids which correspond to tokenized strings of the dataset\n \"\"\"\n\n cached_ids_dataset = dataset + str(\".pkl\")\n if use_cache and os.path.isfile(cached_ids_dataset):\n logging.info(\"Loading cached tokenized dataset ...\")\n ids = pickle.load(open(cached_ids_dataset, \"rb\"))\n else:\n logging.info(f\"Tokenizing dataset {dataset}...\")\n data = open(dataset, \"rb\").readlines()\n ids = []\n for sentence in tqdm(data, desc='Tokenizing sentence'):\n sent_ids = tokenizer.text_to_ids(sentence.decode(\"utf-8\"))\n if add_bos_eos:\n sent_ids = [tokenizer.bos_id] + sent_ids + [tokenizer.eos_id]\n ids.append(sent_ids)\n if cache_ids and (\n not torch.distributed.is_initialized() or (cache_data_per_node and get_envint(\"LOCAL_RANK\", 0) == 0)\n ):\n logging.info(\"Caching tokenized dataset ...\")\n pickle.dump(ids, open(cached_ids_dataset, \"wb\"))\n return ids\n\n\ndef get_freq_weights(label_freq):\n \"\"\"\n Goal is to give more weight to the classes with less samples\n so as to match the ones with the higher frequencies. We achieve this by\n dividing the total frequency by the freq of each label to calculate its weight.\n \"\"\"\n total_size = 0\n for lf in label_freq.values():\n total_size += lf\n weighted_slots = {label: (total_size / (len(label_freq) * freq)) for label, freq in label_freq.items()}\n return weighted_slots\n\n\ndef fill_class_weights(weights, max_id=-1):\n \"\"\"\n Gets a dictionary of labels with their weights and creates a list with size of the labels filled with those weights.\n Missing labels in the dictionary would get value 1.\n\n Args:\n weights: dictionary of weights for labels, labels as keys and weights are their values\n max_id: the largest label id in the dataset, default=-1 would consider the largest label in the weights dictionary as max_id\n Returns:\n weights_list: list of weights for labels\n \"\"\"\n if max_id < 0:\n max_id = 0\n for l in weights.keys():\n max_id = max(max_id, l)\n\n all_weights = [1.0] * (max_id + 1)\n for i in range(len(all_weights)):\n if i in weights:\n all_weights[i] = weights[i]\n return all_weights\n\n\ndef get_vocab(file):\n lines = open(file, 'r').readlines()\n lines = [line.strip() for line in lines if line.strip()]\n labels = {i: lines[i] for i in range(len(lines))}\n return labels\n\n\ndef find_newlines(contents):\n \"\"\"\n Finds all of the newline positions in a text file.\n \"\"\"\n start = 0\n\n while True:\n try:\n # index and split are much faster than Python for loops\n new_start = contents.index(b\"\\n\", start)\n line = (\n contents[start:new_start]\n .replace(b\"\\xc2\\x99\", b\" \")\n .replace(b\"\\xc2\\xa0\", b\" \")\n .decode(\"utf-8\", errors=\"ignore\")\n )\n\n if len(line.split()) > 0:\n yield start\n\n start = new_start + 1\n\n except ValueError:\n break\n\n\ndef load_data_indices(idx_file: str, data_file: str, savename: str):\n \"\"\"\n Loads dataset index file if it exsits\n \"\"\"\n data_dir = data_file[: data_file.rfind('/')]\n mode = data_file[data_file.rfind('/') + 1 : data_file.rfind('.')]\n idx_file = f\"{data_dir}/{mode}_{savename}.pkl\"\n\n if os.path.isfile(idx_file):\n # If the sentence indices file already exists, load from it\n with open(idx_file, \"rb\") as f:\n indices = pickle.load(f)\n\n return indices, idx_file, data_dir\n\n return None, idx_file, data_dir\n",
"# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nimport tempfile\n\nimport numpy as np\nimport pytest\nimport torch\nfrom omegaconf import DictConfig, OmegaConf\n\nfrom nemo.collections.asr.models import EncDecCTCModel\n\ntry:\n from eff.cookbooks import NeMoCookbook\n\n _EFF_PRESENT_ = True\nexcept ImportError:\n _EFF_PRESENT_ = False\n\n# A decorator marking the EFF requirement.\nrequires_eff = pytest.mark.skipif(not _EFF_PRESENT_, reason=\"Export File Format library required to run test\")\n\n\[email protected]()\ndef asr_model():\n preprocessor = {'cls': 'nemo.collections.asr.modules.AudioToMelSpectrogramPreprocessor', 'params': dict({})}\n encoder = {\n 'cls': 'nemo.collections.asr.modules.ConvASREncoder',\n 'params': {\n 'feat_in': 64,\n 'activation': 'relu',\n 'conv_mask': True,\n 'jasper': [\n {\n 'filters': 1024,\n 'repeat': 1,\n 'kernel': [1],\n 'stride': [1],\n 'dilation': [1],\n 'dropout': 0.0,\n 'residual': False,\n 'separable': True,\n 'se': True,\n 'se_context_size': -1,\n }\n ],\n },\n }\n\n decoder = {\n 'cls': 'nemo.collections.asr.modules.ConvASRDecoder',\n 'params': {\n 'feat_in': 1024,\n 'num_classes': 28,\n 'vocabulary': [\n ' ',\n 'a',\n 'b',\n 'c',\n 'd',\n 'e',\n 'f',\n 'g',\n 'h',\n 'i',\n 'j',\n 'k',\n 'l',\n 'm',\n 'n',\n 'o',\n 'p',\n 'q',\n 'r',\n 's',\n 't',\n 'u',\n 'v',\n 'w',\n 'x',\n 'y',\n 'z',\n \"'\",\n ],\n },\n }\n modelConfig = DictConfig(\n {'preprocessor': DictConfig(preprocessor), 'encoder': DictConfig(encoder), 'decoder': DictConfig(decoder)}\n )\n\n model_instance = EncDecCTCModel(cfg=modelConfig)\n return model_instance\n\n\nclass TestFileIO:\n @pytest.mark.unit\n def test_to_from_config_file(self, asr_model):\n \"\"\"\" Test makes sure that the second instance created with the same configuration (BUT NOT checkpoint)\n has different weights. \"\"\"\n\n with tempfile.NamedTemporaryFile() as fp:\n yaml_filename = fp.name\n asr_model.to_config_file(path2yaml_file=yaml_filename)\n next_instance = EncDecCTCModel.from_config_file(path2yaml_file=yaml_filename)\n\n assert isinstance(next_instance, EncDecCTCModel)\n\n assert len(next_instance.decoder.vocabulary) == 28\n assert asr_model.num_weights == next_instance.num_weights\n\n w1 = asr_model.encoder.encoder[0].mconv[0].conv.weight.data.detach().cpu().numpy()\n w2 = next_instance.encoder.encoder[0].mconv[0].conv.weight.data.detach().cpu().numpy()\n\n assert not np.array_equal(w1, w2)\n\n @pytest.mark.unit\n def test_save_restore_from_nemo_file(self, asr_model):\n \"\"\"\" Test makes sure that the second instance created from the same configuration AND checkpoint \n has the same weights. \"\"\"\n\n with tempfile.NamedTemporaryFile() as fp:\n filename = fp.name\n\n # Save model (with random artifact).\n with tempfile.NamedTemporaryFile() as artifact:\n asr_model.register_artifact(config_path=\"abc\", src=artifact.name)\n asr_model.save_to(save_path=filename)\n\n # Restore the model.\n asr_model2 = EncDecCTCModel.restore_from(restore_path=filename)\n\n assert len(asr_model.decoder.vocabulary) == len(asr_model2.decoder.vocabulary)\n assert asr_model.num_weights == asr_model2.num_weights\n\n w1 = asr_model.encoder.encoder[0].mconv[0].conv.weight.data.detach().cpu().numpy()\n w2 = asr_model2.encoder.encoder[0].mconv[0].conv.weight.data.detach().cpu().numpy()\n\n assert np.array_equal(w1, w2)\n\n @requires_eff\n @pytest.mark.unit\n def test_eff_save_restore_from_nemo_file_encrypted(self, asr_model):\n \"\"\"\" Test makes sure that after encrypted save-restore the model has the same weights. \"\"\"\n\n with tempfile.NamedTemporaryFile() as fp:\n filename = fp.name\n\n # Set key - use checkpoint encryption.\n NeMoCookbook.set_encryption_key(\"test_key\")\n\n # Save model (with random artifact).\n with tempfile.NamedTemporaryFile() as artifact:\n asr_model.register_artifact(config_path=\"abc\", src=artifact.name)\n asr_model.save_to(save_path=filename)\n\n # Try to restore the encrypted archive (weights) without the encryption key.\n NeMoCookbook.set_encryption_key(None)\n with pytest.raises(PermissionError):\n # Restore the model.\n asr_model2 = EncDecCTCModel.restore_from(restore_path=filename)\n\n # Restore the model.\n NeMoCookbook.set_encryption_key(\"test_key\")\n asr_model3 = EncDecCTCModel.restore_from(restore_path=filename)\n # Reset encryption so it won't mess up with other save/restore.\n NeMoCookbook.set_encryption_key(None)\n\n assert asr_model.num_weights == asr_model3.num_weights\n\n @pytest.mark.unit\n def test_save_restore_from_nemo_file_with_override(self, asr_model, tmpdir):\n \"\"\"\" Test makes sure that the second instance created from the same configuration AND checkpoint\n has the same weights.\n\n Args:\n tmpdir: fixture providing a temporary directory unique to the test invocation.\n \"\"\"\n # Name of the archive in tmp folder.\n filename = os.path.join(tmpdir, \"eff.nemo\")\n\n # Get path where the command is executed - the artifacts will be \"retrieved\" there.\n # (original .nemo behavior)\n cwd = os.getcwd()\n\n with tempfile.NamedTemporaryFile(mode='a+') as conf_fp:\n\n # Create a \"random artifact\".\n with tempfile.NamedTemporaryFile(mode=\"w\", delete=False) as artifact:\n artifact.write(\"magic content 42\")\n # Remember the filename of the artifact.\n _, artifact_filename = os.path.split(artifact.name)\n # Add artifact to model.\n asr_model.register_artifact(config_path=\"abc\", src=artifact.name)\n # Save model (with \"random artifact\").\n asr_model.save_to(save_path=filename)\n\n # Modify config slightly\n cfg = asr_model.cfg\n cfg.encoder.activation = 'swish'\n yaml_cfg = OmegaConf.to_yaml(cfg)\n conf_fp.write(yaml_cfg)\n conf_fp.seek(0)\n\n # Restore the model.\n asr_model2 = EncDecCTCModel.restore_from(restore_path=filename, override_config_path=conf_fp.name)\n\n assert len(asr_model.decoder.vocabulary) == len(asr_model2.decoder.vocabulary)\n assert asr_model.num_weights == asr_model2.num_weights\n\n w1 = asr_model.encoder.encoder[0].mconv[0].conv.weight.data.detach().cpu().numpy()\n w2 = asr_model2.encoder.encoder[0].mconv[0].conv.weight.data.detach().cpu().numpy()\n\n assert np.array_equal(w1, w2)\n\n assert asr_model2.cfg.encoder.activation == 'swish'\n\n @pytest.mark.unit\n def test_save_model_level_pt_ckpt(self, asr_model):\n with tempfile.TemporaryDirectory() as ckpt_dir:\n nemo_file = os.path.join(ckpt_dir, 'asr.nemo')\n asr_model.save_to(nemo_file)\n\n # Save model level PT checkpoint\n asr_model.extract_state_dict_from(nemo_file, ckpt_dir)\n ckpt_path = os.path.join(ckpt_dir, 'model_weights.ckpt')\n\n assert os.path.exists(ckpt_path)\n\n # Restore the model.\n asr_model2 = EncDecCTCModel.restore_from(restore_path=nemo_file)\n\n assert len(asr_model.decoder.vocabulary) == len(asr_model2.decoder.vocabulary)\n assert asr_model.num_weights == asr_model2.num_weights\n\n # Change weights values\n asr_model2.encoder.encoder[0].mconv[0].conv.weight.data += 1.0\n\n w1 = asr_model.encoder.encoder[0].mconv[0].conv.weight.data.detach().cpu().numpy()\n w2 = asr_model2.encoder.encoder[0].mconv[0].conv.weight.data.detach().cpu().numpy()\n\n assert not np.array_equal(w1, w2)\n\n # Restore from checkpoint\n asr_model2.load_state_dict(torch.load(ckpt_path))\n\n w1 = asr_model.encoder.encoder[0].mconv[0].conv.weight.data.detach().cpu().numpy()\n w2 = asr_model2.encoder.encoder[0].mconv[0].conv.weight.data.detach().cpu().numpy()\n\n assert np.array_equal(w1, w2)\n\n @pytest.mark.unit\n def test_save_module_level_pt_ckpt(self, asr_model):\n with tempfile.TemporaryDirectory() as ckpt_dir:\n nemo_file = os.path.join(ckpt_dir, 'asr.nemo')\n asr_model.save_to(nemo_file)\n\n # Save model level PT checkpoint\n asr_model.extract_state_dict_from(nemo_file, ckpt_dir, split_by_module=True)\n encoder_path = os.path.join(ckpt_dir, 'encoder.ckpt')\n decoder_path = os.path.join(ckpt_dir, 'decoder.ckpt')\n preprocessor_path = os.path.join(ckpt_dir, 'preprocessor.ckpt')\n\n assert os.path.exists(encoder_path)\n assert os.path.exists(decoder_path)\n assert os.path.exists(preprocessor_path)\n\n # Restore the model.\n asr_model2 = EncDecCTCModel.restore_from(restore_path=nemo_file)\n\n assert len(asr_model.decoder.vocabulary) == len(asr_model2.decoder.vocabulary)\n assert asr_model.num_weights == asr_model2.num_weights\n\n # Change weights values\n asr_model2.encoder.encoder[0].mconv[0].conv.weight.data += 1.0\n\n w1 = asr_model.encoder.encoder[0].mconv[0].conv.weight.data.detach().cpu().numpy()\n w2 = asr_model2.encoder.encoder[0].mconv[0].conv.weight.data.detach().cpu().numpy()\n\n assert not np.array_equal(w1, w2)\n\n # Restore from checkpoint\n asr_model2.encoder.load_state_dict(torch.load(encoder_path))\n\n w1 = asr_model.encoder.encoder[0].mconv[0].conv.weight.data.detach().cpu().numpy()\n w2 = asr_model2.encoder.encoder[0].mconv[0].conv.weight.data.detach().cpu().numpy()\n\n assert np.array_equal(w1, w2)\n",
"# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nCalculates durations for LJSpeech based on MFA TextGrid alignments.\n\"\"\"\nimport argparse\nimport glob\nimport json\nimport os\nimport pickle\nfrom math import ceil\n\nimport numpy as np\nimport tgt\nimport torch\nfrom tqdm import tqdm\n\nparser = argparse.ArgumentParser(description=\"Calculates phoneme durations for LJSpeech from TextGrids.\")\nparser.add_argument('--ljspeech_dir', required=True, default=None, type=str)\nparser.add_argument(\n '--mappings',\n required=False,\n default=None,\n type=str,\n help='JSON file of mappings created with create_token2idx_dict.py',\n)\nparser.add_argument('--sr', required=False, default=22050, type=int)\nparser.add_argument('--hop_length', required=False, default=256, type=int)\nargs = parser.parse_args()\n\n\ndef calculate_durations(textgrid, phone2idx):\n tokens = []\n durs = []\n\n frames_per_second = args.sr / args.hop_length\n tg = tgt.read_textgrid(textgrid, include_empty_intervals=True)\n data_tier = tg.get_tier_by_name(\"phones\")\n\n # Get total frames\n total_frames = ceil((data_tier.end_time - data_tier.start_time) * frames_per_second)\n\n # Find start and end frames of each token\n se_in_frames = np.array([(frames_per_second * d.start_time, frames_per_second * d.end_time) for d in data_tier])\n se_in_frames = np.round(se_in_frames)\n durs = (se_in_frames[:, 1] - se_in_frames[:, 0]).astype(int)\n blank_set = ('sil', 'sp', 'spn', '', '<unk>')\n blank_token = \" \"\n\n # merge repeated blank tokens\n tokens, durations = [], []\n for i in range(len(data_tier)):\n x = data_tier[i].text\n if x == 'spn':\n return None, None, None\n x = blank_token if x in blank_set else x\n\n if len(tokens) and tokens[-1] == blank_token and x == blank_token:\n durations[-1] += durs[i]\n else:\n tokens.append(x)\n durations.append(durs[i])\n\n tokens_enc = [phone2idx[token] for token in tokens]\n tokens_enc, durations = torch.LongTensor(tokens_enc), torch.LongTensor(durations)\n\n # Add rounding error to final token\n durations[-1] += total_frames - durations.sum()\n\n return tokens, tokens_enc, durations\n\n\ndef main():\n textgrid_list = glob.glob(os.path.join(args.ljspeech_dir, 'alignments/wavs/*.TextGrid'))\n\n # Create target_dir if necessary\n target_dir = os.path.join(args.ljspeech_dir, 'phoneme_durations/')\n print(f\"Calculating phoneme durations, files will be in: {target_dir}\")\n\n if not os.path.exists(target_dir):\n print(f\"Creating {target_dir}\")\n os.mkdir(target_dir)\n\n # Read phoneme to idx mappings\n phone2idx = None\n if args.mappings:\n with open(args.mappings, 'r') as f:\n mappings = json.load(f)\n phone2idx = mappings['phone2idx']\n\n oov_samples = []\n\n # Iterate through all TextGrid files\n for textgrid in tqdm(textgrid_list):\n basename = os.path.splitext(os.path.basename(textgrid))[0][5:] # Chop off 'wavs_' prefix\n\n phones_mfa, tokens_mfa, durs = calculate_durations(textgrid, phone2idx)\n\n if phones_mfa is None:\n oov_samples.append(basename)\n continue\n\n # Save to file\n target_path = os.path.join(target_dir, f'{basename}.pt')\n torch.save({'text_encoded': tokens_mfa, 'token_duration': durs}, target_path)\n\n print(f\"Getting rid of {len(oov_samples)} samples with OOV words.\")\n oov_target = os.path.join(args.ljspeech_dir, 'wavs_to_ignore.pkl')\n with open(oov_target, 'wb') as f:\n pickle.dump(oov_samples, f)\n print(f\"List of OOV samples written to: {oov_target}\")\n\n\nif __name__ == '__main__':\n main()\n",
"# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport glob\nimport os\nimport time\nfrom argparse import ArgumentParser\nfrom itertools import repeat\nfrom multiprocessing import Pool\n\nimport numpy as np\nimport pandas as pd\n\n\n\"\"\"\nThis script serves two purposes:\n \n 1) gen_overlap_seq: \n Generate predictions with overlapping input segments by using the frame level prediction from NeMo/examples/asr/vad_infer.py. \n Then a smoothing filter is applied to decide the label for a frame spanned by multiple segments. \n \n 2)gen_seg_table: \n Converting frame level prediction to speech/no-speech segment in start and end times format.\n \nUsage:\n\npython vad_overlap_posterior.py --gen_overlap_seq --gen_seg_table --frame_folder=<FULL PATH OF YOU STORED FRAME LEVEL PREDICTION> --method='median' --overlap=0.875 --num_workers=20 --threshold=0.8 \n \n\"\"\"\n\n\ndef gen_overlap_seq(frame_filepath, per_args):\n \"\"\"\n Given a frame level prediction, generate predictions with overlapping input segments by using it\n Args:\n frame_filepath : frame prediction file to be processed.\n per_args:\n method : Median or mean smoothing filter.\n overlap : Amounts of overlap.\n seg_len : Length of window for generating the frame.\n shift_len : Amount of shift of window for generating the frame.\n out_dir : Output dir of generated prediction.\n \"\"\"\n\n try:\n method = per_args['method']\n overlap = per_args['overlap']\n seg_len = per_args['seg_len']\n shift_len = per_args['shift_len']\n out_dir = per_args['out_dir']\n\n frame = np.loadtxt(frame_filepath)\n name = os.path.basename(frame_filepath).split(\".frame\")[0] + \".\" + method\n overlap_filepath = os.path.join(out_dir, name)\n\n shift = int(shift_len / 0.01) # number of units of shift\n seg = int((seg_len / 0.01 + 1)) # number of units of each window/segment\n\n jump_on_target = int(seg * (1 - overlap)) # jump on target generated sequence\n jump_on_frame = int(jump_on_target / shift) # jump on input frame sequence\n\n if jump_on_frame < 1:\n raise ValueError(\n f\"Note we jump over frame sequence to generate overlapping input segments. \\n \\\n Your input makes jump_on_fram={jump_on_frame} < 1 which is invalid because it cannot jump and will stuck.\\n \\\n Please try different seg_len, shift_len and overlap choices. \\n \\\n jump_on_target = int(seg * (1 - overlap)) \\n \\\n jump_on_frame = int(jump_on_frame/shift) \"\n )\n\n target_len = int(len(frame) * shift)\n\n if method == 'mean':\n preds = np.zeros(target_len)\n pred_count = np.zeros(target_len)\n\n for i, og_pred in enumerate(frame):\n if i % jump_on_frame != 0:\n continue\n start = i * shift\n end = start + seg\n preds[start:end] = preds[start:end] + og_pred\n pred_count[start:end] = pred_count[start:end] + 1\n\n preds = preds / pred_count\n last_non_zero_pred = preds[pred_count != 0][-1]\n preds[pred_count == 0] = last_non_zero_pred\n\n elif method == 'median':\n preds = [[] for _ in range(target_len)]\n for i, og_pred in enumerate(frame):\n if i % jump_on_frame != 0:\n continue\n\n start = i * shift\n end = start + seg\n for j in range(start, end):\n if j <= target_len - 1:\n preds[j].append(og_pred)\n\n preds = np.array([np.median(l) for l in preds])\n nan_idx = np.isnan(preds)\n last_non_nan_pred = preds[~nan_idx][-1]\n preds[nan_idx] = last_non_nan_pred\n\n else:\n raise ValueError(\"method should be either mean or median\")\n\n round_final = np.round(preds, 4)\n np.savetxt(overlap_filepath, round_final, delimiter='\\n')\n print(f\"Finished! {overlap_filepath}!\")\n\n except Exception as e:\n raise (e)\n\n\ndef gen_seg_table(frame_filepath, per_args):\n\n \"\"\"\n Convert frame level prediction to speech/no-speech segment in start and end times format.\n And save to csv file in rttm-like format\n 0, 10, speech\n 10,12, no-speech\n Args:\n frame_filepath : frame prediction file to be processed.\n per_args : \n threshold : threshold for prediction score (from 0 to 1).\n shift_len : Amount of shift of window for generating the frame. \n out_dir : Output dir of generated table/csv file. \n \"\"\"\n threshold = per_args['threshold']\n shift_len = per_args['shift_len']\n out_dir = per_args['out_dir']\n\n print(f\"process {frame_filepath}\")\n name = frame_filepath.split(\"/\")[-1].rsplit(\".\", 1)[0]\n\n sequence = np.loadtxt(frame_filepath)\n start = 0\n end = 0\n start_list = [0]\n end_list = []\n state_list = []\n\n for i in range(len(sequence) - 1):\n current_sate = \"non-speech\" if sequence[i] <= threshold else \"speech\"\n next_state = \"non-speech\" if sequence[i + 1] <= threshold else \"speech\"\n if next_state != current_sate:\n end = i * shift_len + shift_len # shift_len for handling joint\n state_list.append(current_sate)\n end_list.append(end)\n\n start = (i + 1) * shift_len\n start_list.append(start)\n\n end_list.append((i + 1) * shift_len + shift_len)\n state_list.append(current_sate)\n\n seg_table = pd.DataFrame({'start': start_list, 'end': end_list, 'vad': state_list})\n\n save_name = name + \".txt\"\n save_path = os.path.join(out_dir, save_name)\n seg_table.to_csv(save_path, sep='\\t', index=False, header=False)\n\n\nif __name__ == '__main__':\n start = time.time()\n parser = ArgumentParser()\n parser.add_argument(\"--gen_overlap_seq\", default=False, action='store_true')\n parser.add_argument(\"--gen_seg_table\", default=False, action='store_true')\n parser.add_argument(\"--frame_folder\", type=str, required=True)\n parser.add_argument(\n \"--method\",\n type=str,\n required=True,\n help=\"Use mean/median for overlapped prediction. Use frame for gen_seg_table of frame prediction\",\n )\n parser.add_argument(\"--overlap_out_dir\", type=str)\n parser.add_argument(\"--table_out_dir\", type=str)\n parser.add_argument(\"--overlap\", type=float, default=0.875, help=\"Overlap percentatge. Default is 0.875\")\n parser.add_argument(\"--seg_len\", type=float, default=0.63)\n parser.add_argument(\"--shift_len\", type=float, default=0.01)\n parser.add_argument(\"--threshold\", type=float, default=0.5)\n parser.add_argument(\"--num_workers\", type=int, default=4)\n args = parser.parse_args()\n\n if args.gen_overlap_seq:\n p = Pool(processes=args.num_workers)\n print(\"Generating predictions with overlapping input segments\")\n frame_filepathlist = glob.glob(args.frame_folder + \"/*.frame\")\n\n if not args.overlap_out_dir:\n overlap_out_dir = \"./overlap_smoothing_output\" + \"_\" + args.method + \"_\" + str(args.overlap)\n else:\n overlap_out_dir = args.overlap_out_dir\n if not os.path.exists(overlap_out_dir):\n print(f\"Creating output dir {overlap_out_dir}\")\n os.mkdir(overlap_out_dir)\n\n per_args = {\n \"method\": args.method,\n \"overlap\": args.overlap,\n \"seg_len\": args.seg_len,\n \"shift_len\": args.shift_len,\n \"out_dir\": overlap_out_dir,\n }\n\n p.starmap(gen_overlap_seq, zip(frame_filepathlist, repeat(per_args)))\n p.close()\n p.join()\n\n end = time.time()\n print(f\"Generate overlapped prediction takes {end-start} seconds!\\n Save to {overlap_out_dir}\")\n\n if args.gen_seg_table:\n p = Pool(processes=args.num_workers)\n print(\"Converting frame level prediction to speech/no-speech segment in start and end times format.\")\n\n if args.gen_overlap_seq:\n print(\"Use overlap prediction. Change if you want to use basic frame level prediction\")\n frame_filepath = overlap_out_dir\n shift_len = 0.01\n else:\n print(\"Use basic frame level prediction\")\n frame_filepath = args.frame_folder\n shift_len = args.shift_len\n\n frame_filepathlist = glob.glob(frame_filepath + \"/*.\" + args.method)\n\n if not args.table_out_dir:\n table_out_dir = \"table_output_\" + str(args.threshold)\n else:\n table_out_dir = args.table_out_dir\n if not os.path.exists(table_out_dir):\n print(f\"Creating rttm-like table output dir {table_out_dir}\")\n os.mkdir(table_out_dir)\n\n per_args = {\n \"threshold\": args.threshold,\n \"shift_len\": shift_len,\n \"out_dir\": table_out_dir,\n }\n\n p.starmap(gen_seg_table, zip(frame_filepathlist, repeat(per_args)))\n p.close()\n p.join()\n\n end = time.time()\n print(f\"Generate rttm-like table for {frame_filepath} takes {end-start} seconds!\\n Save to {table_out_dir}\")\n",
"# Copyright 2020 The HuggingFace Inc. team.\n# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport glob\nimport json\nimport os\nfrom typing import Dict, List, Optional, Tuple\n\nimport torch\nimport wget\nfrom torch.hub import _get_torch_home\n\nfrom nemo.collections.nlp.modules.common.megatron.megatron_bert import MegatronBertEncoder\nfrom nemo.utils import AppState, logging\n\n__all__ = [\n \"get_megatron_lm_model\",\n \"get_megatron_lm_models_list\",\n \"get_megatron_checkpoint\",\n \"is_lower_cased_megatron\",\n \"get_megatron_tokenizer\",\n]\n\n\ntorch_home = _get_torch_home()\n\nif not isinstance(torch_home, str):\n logging.info(\"Torch home not found, caching megatron in cwd\")\n torch_home = os.getcwd()\n\nMEGATRON_CACHE = os.path.join(torch_home, \"megatron\")\n\n\nCONFIGS = {\"345m\": {\"hidden_size\": 1024, \"num_attention_heads\": 16, \"num_layers\": 24, \"max_position_embeddings\": 512}}\n\nMEGATRON_CONFIG_MAP = {\n \"megatron-gpt-345m\": {\n \"config\": CONFIGS[\"345m\"],\n \"checkpoint\": \"models/nvidia/megatron_lm_345m/versions/v0.0/files/release/mp_rank_00/model_optim_rng.pt\",\n \"vocab\": \"https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-vocab.json\",\n \"merges_file\": \"https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-merges.txt\",\n \"do_lower_case\": False,\n \"tokenizer_name\": \"gpt2\",\n },\n \"megatron-bert-345m-uncased\": {\n \"config\": CONFIGS[\"345m\"],\n \"checkpoint\": \"https://api.ngc.nvidia.com/v2/models/nvidia/megatron_bert_345m/versions/v0.0/files/release/mp_rank_00/model_optim_rng.pt\",\n \"vocab\": \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-vocab.txt\",\n \"do_lower_case\": True,\n \"tokenizer_name\": \"bert-large-uncased\",\n },\n \"megatron-bert-345m-cased\": {\n \"config\": CONFIGS[\"345m\"],\n \"checkpoint\": \"https://api.ngc.nvidia.com/v2/models/nvidia/megatron_bert_345m/versions/v0.1_cased/files/release/mp_rank_00/model_optim_rng.pt\",\n \"vocab\": \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-vocab.txt\",\n \"do_lower_case\": False,\n \"tokenizer_name\": \"bert-large-cased\",\n },\n \"megatron-bert-uncased\": {\n \"config\": None,\n \"checkpoint\": None,\n \"vocab\": \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-vocab.txt\",\n \"do_lower_case\": True,\n \"tokenizer_name\": \"bert-large-uncased\",\n },\n \"megatron-bert-cased\": {\n \"config\": None,\n \"checkpoint\": None,\n \"vocab\": \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-vocab.txt\",\n \"do_lower_case\": False,\n \"tokenizer_name\": \"bert-large-cased\",\n },\n \"biomegatron-bert-345m-uncased\": {\n \"config\": CONFIGS[\"345m\"],\n \"checkpoint\": \"https://api.ngc.nvidia.com/v2/models/nvidia/biomegatron345muncased/versions/0/files/MegatronBERT.pt\",\n \"vocab\": \"https://api.ngc.nvidia.com/v2/models/nvidia/biomegatron345muncased/versions/0/files/vocab.txt\",\n \"do_lower_case\": True,\n \"tokenizer_name\": \"bert-large-uncased\",\n },\n \"biomegatron-bert-345m-cased\": {\n \"config\": CONFIGS[\"345m\"],\n \"checkpoint\": \"https://api.ngc.nvidia.com/v2/models/nvidia/biomegatron345mcased/versions/0/files/MegatronBERT.pt\",\n \"vocab\": \"https://api.ngc.nvidia.com/v2/models/nvidia/biomegatron345mcased/versions/0/files/vocab.txt\",\n \"do_lower_case\": False,\n \"tokenizer_name\": \"bert-large-cased\",\n },\n}\n\n\ndef get_megatron_lm_model(\n pretrained_model_name: str,\n config_dict: Optional[dict] = None,\n config_file: Optional[str] = None,\n checkpoint_file: Optional[str] = None,\n vocab_file: Optional[str] = None,\n merges_file: Optional[str] = None,\n) -> Tuple[MegatronBertEncoder, str]:\n \"\"\"\n Returns MegatronBertEncoder and a default or user specified path to the checkpoint file\n\n Args:\n pretrained_mode_name: model name from MEGATRON_CONFIG_MAP\n for example: megatron-bert-cased\n config_dict: model configuration parameters\n config_file: path to model configuration file. Takes precedence over config_dict if both supplied.\n checkpoint_file: path to checkpoint file or directory if using model parallel.\n vocab_file: path to vocab file\n\n Returns:\n model: MegatronBertEncoder\n checkpoint_file: path to checkpoint file or directory\n \"\"\"\n raise ValueError(\n f'megatron-lm bert has been deprecated in NeMo 1.5. Please use an earlier release of NeMo. Megatron bert support will be added back to NeMo in a future release.'\n )\n # config = None\n # # get default config and checkpoint\n # if config_file:\n # with open(config_file) as f:\n # config = json.load(f)\n # # replace dashes with underscores in config keys\n # fixed_config = {}\n # for key in config.keys():\n # fixed_key = key.replace(\"-\", \"_\")\n # if fixed_key == 'max_seq_length':\n # fixed_key = 'max_position_embeddings'\n # fixed_config[fixed_key] = config[key]\n # # 'vocab_size\" no longer used.\n # if 'vocab_size' in fixed_config:\n # fixed_config.pop('vocab_size')\n # config = fixed_config\n # elif config_dict:\n # config = config_dict\n # elif pretrained_model_name in get_megatron_lm_models_list():\n # config = get_megatron_config(pretrained_model_name)\n # else:\n # raise ValueError(f\"{pretrained_model_name} is not supported\")\n\n # if config is None:\n # raise ValueError(f\"config_file or config_dict is required for {pretrained_model_name}\")\n\n # if not checkpoint_file:\n # checkpoint_file = get_megatron_checkpoint(pretrained_model_name)\n\n # if not vocab_file:\n # vocab_file = get_megatron_vocab_file(pretrained_model_name)\n\n # if not merges_file:\n # merges_file = get_megatron_merges_file(pretrained_model_name)\n\n # app_state = AppState()\n # if app_state.model_parallel_size is not None and app_state.model_parallel_rank is not None:\n # # model parallel already known from .nemo restore\n # model_parallel_size = app_state.model_parallel_size\n # model_parallel_rank = app_state.model_parallel_rank\n # elif os.path.isdir(checkpoint_file):\n # # starting training from megatron-lm checkpoint\n # mp_ranks = glob.glob(os.path.join(checkpoint_file, 'mp_rank*'))\n # model_parallel_size = len(mp_ranks)\n # app_state.model_parallel_size = model_parallel_size\n # logging.info(\n # (\n # f'restore_path: {checkpoint_file} is a directory. '\n # f'Assuming megatron model parallelism with '\n # f'model_parallel_size: {model_parallel_size}'\n # )\n # )\n # # try to get local rank from global\n # local_rank = None\n # try:\n # local_rank = int(os.environ['LOCAL_RANK'])\n # except:\n # logging.info('Global variable LOCAL_RANK not yet specified')\n # if local_rank is not None:\n # app_state.local_rank = local_rank\n # else:\n # # if local is None then we are on the main process\n # local_rank = 0\n # model_parallel_rank = compute_model_parallel_rank(local_rank, model_parallel_size)\n # app_state.model_parallel_rank = model_parallel_rank\n # else:\n # model_parallel_size = None\n # model_parallel_rank = None\n\n # model = MegatronBertEncoder(\n # model_name=pretrained_model_name,\n # config=config,\n # vocab_file=vocab_file,\n # model_parallel_size=model_parallel_size,\n # model_parallel_rank=model_parallel_rank,\n # )\n\n # return model, checkpoint_file\n\n\ndef compute_model_parallel_rank(local_rank, model_parallel_size):\n return local_rank % model_parallel_size\n\n\ndef get_megatron_lm_models_list() -> List[str]:\n \"\"\"\n Returns the list of supported Megatron-LM models\n \"\"\"\n return list(MEGATRON_CONFIG_MAP.keys())\n\n\ndef get_megatron_config(pretrained_model_name: str) -> Dict[str, int]:\n \"\"\"\n Returns Megatron-LM model config file\n\n Args:\n pretrained_model_name (str): pretrained model name\n\n Returns:\n config (dict): contains model configuration: number of hidden layers, number of attention heads, etc\n \"\"\"\n _check_megatron_name(pretrained_model_name)\n return MEGATRON_CONFIG_MAP[pretrained_model_name][\"config\"]\n\n\ndef _check_megatron_name(pretrained_model_name: str) -> None:\n megatron_model_list = get_megatron_lm_models_list()\n if pretrained_model_name not in megatron_model_list:\n raise ValueError(f'For Megatron-LM models, choose from the following list: {megatron_model_list}')\n\n\ndef get_megatron_vocab_file(pretrained_model_name: str) -> str:\n \"\"\"\n Gets vocabulary file from cache or downloads it\n\n Args:\n pretrained_model_name: pretrained model name\n\n Returns:\n path: path to the vocab file\n \"\"\"\n _check_megatron_name(pretrained_model_name)\n url = MEGATRON_CONFIG_MAP[pretrained_model_name][\"vocab\"]\n\n path = os.path.join(MEGATRON_CACHE, pretrained_model_name + \"_vocab\")\n path = _download(path, url)\n return path\n\n\ndef get_megatron_merges_file(pretrained_model_name: str) -> str:\n \"\"\"\n Gets merge file from cache or downloads it\n\n Args:\n pretrained_model_name: pretrained model name\n\n Returns:\n path: path to the vocab file\n \"\"\"\n if 'gpt' not in pretrained_model_name.lower():\n return None\n _check_megatron_name(pretrained_model_name)\n url = MEGATRON_CONFIG_MAP[pretrained_model_name][\"merges_file\"]\n\n path = os.path.join(MEGATRON_CACHE, pretrained_model_name + \"_merges\")\n path = _download(path, url)\n return path\n\n\ndef get_megatron_checkpoint(pretrained_model_name: str) -> str:\n \"\"\"\n Gets checkpoint file from cache or downloads it\n Args:\n pretrained_model_name: pretrained model name\n Returns:\n path: path to model checkpoint\n \"\"\"\n _check_megatron_name(pretrained_model_name)\n url = MEGATRON_CONFIG_MAP[pretrained_model_name][\"checkpoint\"]\n path = os.path.join(MEGATRON_CACHE, pretrained_model_name)\n return _download(path, url)\n\n\ndef _download(path: str, url: str):\n \"\"\"\n Gets a file from cache or downloads it\n\n Args:\n path: path to the file in cache\n url: url to the file\n Returns:\n path: path to the file in cache\n \"\"\"\n if url is None:\n return None\n\n if not os.path.exists(path):\n master_device = not torch.distributed.is_initialized() or torch.distributed.get_rank() == 0\n if not os.path.exists(path):\n if master_device:\n os.makedirs(MEGATRON_CACHE, exist_ok=True)\n logging.info(f\"Downloading from {url}\")\n wget.download(url, path)\n # wait until the master process downloads the file and writes it to the cache dir\n if torch.distributed.is_initialized():\n torch.distributed.barrier()\n\n return path\n\n\ndef is_lower_cased_megatron(pretrained_model_name):\n \"\"\"\n Returns if the megatron is cased or uncased\n\n Args:\n pretrained_model_name (str): pretrained model name\n Returns:\n do_lower_cased (bool): whether the model uses lower cased data\n \"\"\"\n _check_megatron_name(pretrained_model_name)\n return MEGATRON_CONFIG_MAP[pretrained_model_name][\"do_lower_case\"]\n\n\ndef get_megatron_tokenizer(pretrained_model_name: str):\n \"\"\"\n Takes a pretrained_model_name for megatron such as \"megatron-bert-cased\" and returns the according \n tokenizer name for tokenizer instantiating.\n\n Args:\n pretrained_model_name: pretrained_model_name for megatron such as \"megatron-bert-cased\"\n Returns: \n tokenizer name for tokenizer instantiating\n \"\"\"\n _check_megatron_name(pretrained_model_name)\n return MEGATRON_CONFIG_MAP[pretrained_model_name][\"tokenizer_name\"]\n",
"# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# BSD 3-Clause License\n#\n# Copyright (c) 2021, NVIDIA Corporation\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# * Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# * 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# * 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 ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (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\nfrom enum import Enum\nfrom typing import Dict, Sequence\n\nimport librosa\nimport matplotlib.pylab as plt\nimport numpy as np\nimport torch\nfrom numba import jit, prange\nfrom numpy import ndarray\nfrom pesq import pesq\nfrom pystoi import stoi\n\nfrom nemo.utils import logging\n\ntry:\n from pytorch_lightning.utilities import rank_zero_only\nexcept ModuleNotFoundError:\n from functools import wraps\n\n def rank_zero_only(fn):\n @wraps(fn)\n def wrapped_fn(*args, **kwargs):\n logging.error(\n f\"Function {fn} requires lighting to be installed, but it was not found. Please install lightning first\"\n )\n exit(1)\n\n\nclass OperationMode(Enum):\n \"\"\"Training or Inference (Evaluation) mode\"\"\"\n\n training = 0\n validation = 1\n infer = 2\n\n\ndef binarize_attention(attn, in_len, out_len):\n \"\"\"Convert soft attention matrix to hard attention matrix.\n\n Args:\n attn (torch.Tensor): B x 1 x max_mel_len x max_text_len. Soft attention matrix.\n in_len (torch.Tensor): B. Lengths of texts.\n out_len (torch.Tensor): B. Lengths of spectrograms.\n\n Output:\n attn_out (torch.Tensor): B x 1 x max_mel_len x max_text_len. Hard attention matrix, final dim max_text_len should sum to 1.\n \"\"\"\n b_size = attn.shape[0]\n with torch.no_grad():\n attn_cpu = attn.data.cpu().numpy()\n attn_out = torch.zeros_like(attn)\n for ind in range(b_size):\n hard_attn = mas(attn_cpu[ind, 0, : out_len[ind], : in_len[ind]])\n attn_out[ind, 0, : out_len[ind], : in_len[ind]] = torch.tensor(hard_attn, device=attn.device)\n return attn_out\n\n\ndef binarize_attention_parallel(attn, in_lens, out_lens):\n \"\"\"For training purposes only. Binarizes attention with MAS.\n These will no longer recieve a gradient.\n\n Args:\n attn: B x 1 x max_mel_len x max_text_len\n \"\"\"\n with torch.no_grad():\n attn_cpu = attn.data.cpu().numpy()\n attn_out = b_mas(attn_cpu, in_lens.cpu().numpy(), out_lens.cpu().numpy(), width=1)\n return torch.from_numpy(attn_out).to(attn.get_device())\n\n\ndef get_mask_from_lengths(lengths, max_len=None):\n if not max_len:\n max_len = torch.max(lengths).item()\n ids = torch.arange(0, max_len, device=lengths.device, dtype=torch.long)\n mask = (ids < lengths.unsqueeze(1)).bool()\n return mask\n\n\n@jit(nopython=True)\ndef mas(attn_map, width=1):\n # assumes mel x text\n opt = np.zeros_like(attn_map)\n attn_map = np.log(attn_map)\n attn_map[0, 1:] = -np.inf\n log_p = np.zeros_like(attn_map)\n log_p[0, :] = attn_map[0, :]\n prev_ind = np.zeros_like(attn_map, dtype=np.int64)\n for i in range(1, attn_map.shape[0]):\n for j in range(attn_map.shape[1]): # for each text dim\n prev_j = np.arange(max(0, j - width), j + 1)\n prev_log = np.array([log_p[i - 1, prev_idx] for prev_idx in prev_j])\n\n ind = np.argmax(prev_log)\n log_p[i, j] = attn_map[i, j] + prev_log[ind]\n prev_ind[i, j] = prev_j[ind]\n\n # now backtrack\n curr_text_idx = attn_map.shape[1] - 1\n for i in range(attn_map.shape[0] - 1, -1, -1):\n opt[i, curr_text_idx] = 1\n curr_text_idx = prev_ind[i, curr_text_idx]\n opt[0, curr_text_idx] = 1\n\n assert opt.sum(0).all()\n assert opt.sum(1).all()\n\n return opt\n\n\n@jit(nopython=True)\ndef mas_width1(attn_map):\n \"\"\"mas with hardcoded width=1\"\"\"\n # assumes mel x text\n opt = np.zeros_like(attn_map)\n attn_map = np.log(attn_map)\n attn_map[0, 1:] = -np.inf\n log_p = np.zeros_like(attn_map)\n log_p[0, :] = attn_map[0, :]\n prev_ind = np.zeros_like(attn_map, dtype=np.int64)\n for i in range(1, attn_map.shape[0]):\n for j in range(attn_map.shape[1]): # for each text dim\n prev_log = log_p[i - 1, j]\n prev_j = j\n\n if j - 1 >= 0 and log_p[i - 1, j - 1] >= log_p[i - 1, j]:\n prev_log = log_p[i - 1, j - 1]\n prev_j = j - 1\n\n log_p[i, j] = attn_map[i, j] + prev_log\n prev_ind[i, j] = prev_j\n\n # now backtrack\n curr_text_idx = attn_map.shape[1] - 1\n for i in range(attn_map.shape[0] - 1, -1, -1):\n opt[i, curr_text_idx] = 1\n curr_text_idx = prev_ind[i, curr_text_idx]\n opt[0, curr_text_idx] = 1\n return opt\n\n\n@jit(nopython=True, parallel=True)\ndef b_mas(b_attn_map, in_lens, out_lens, width=1):\n assert width == 1\n attn_out = np.zeros_like(b_attn_map)\n\n for b in prange(b_attn_map.shape[0]):\n out = mas_width1(b_attn_map[b, 0, : out_lens[b], : in_lens[b]])\n attn_out[b, 0, : out_lens[b], : in_lens[b]] = out\n return attn_out\n\n\ndef griffin_lim(magnitudes, n_iters=50, n_fft=1024):\n \"\"\"\n Griffin-Lim algorithm to convert magnitude spectrograms to audio signals\n \"\"\"\n phase = np.exp(2j * np.pi * np.random.rand(*magnitudes.shape))\n complex_spec = magnitudes * phase\n signal = librosa.istft(complex_spec)\n if not np.isfinite(signal).all():\n logging.warning(\"audio was not finite, skipping audio saving\")\n return np.array([0])\n\n for _ in range(n_iters):\n _, phase = librosa.magphase(librosa.stft(signal, n_fft=n_fft))\n complex_spec = magnitudes * phase\n signal = librosa.istft(complex_spec)\n return signal\n\n\n@rank_zero_only\ndef log_audio_to_tb(\n swriter,\n spect,\n name,\n step,\n griffin_lim_mag_scale=1024,\n griffin_lim_power=1.2,\n sr=22050,\n n_fft=1024,\n n_mels=80,\n fmax=8000,\n):\n filterbank = librosa.filters.mel(sr=sr, n_fft=n_fft, n_mels=n_mels, fmax=fmax)\n log_mel = spect.data.cpu().numpy().T\n mel = np.exp(log_mel)\n magnitude = np.dot(mel, filterbank) * griffin_lim_mag_scale\n audio = griffin_lim(magnitude.T ** griffin_lim_power)\n swriter.add_audio(name, audio / max(np.abs(audio)), step, sample_rate=sr)\n\n\n@rank_zero_only\ndef tacotron2_log_to_tb_func(\n swriter,\n tensors,\n step,\n tag=\"train\",\n log_images=False,\n log_images_freq=1,\n add_audio=True,\n griffin_lim_mag_scale=1024,\n griffin_lim_power=1.2,\n sr=22050,\n n_fft=1024,\n n_mels=80,\n fmax=8000,\n):\n _, spec_target, mel_postnet, gate, gate_target, alignments = tensors\n if log_images and step % log_images_freq == 0:\n swriter.add_image(\n f\"{tag}_alignment\", plot_alignment_to_numpy(alignments[0].data.cpu().numpy().T), step, dataformats=\"HWC\",\n )\n swriter.add_image(\n f\"{tag}_mel_target\", plot_spectrogram_to_numpy(spec_target[0].data.cpu().numpy()), step, dataformats=\"HWC\",\n )\n swriter.add_image(\n f\"{tag}_mel_predicted\",\n plot_spectrogram_to_numpy(mel_postnet[0].data.cpu().numpy()),\n step,\n dataformats=\"HWC\",\n )\n swriter.add_image(\n f\"{tag}_gate\",\n plot_gate_outputs_to_numpy(gate_target[0].data.cpu().numpy(), torch.sigmoid(gate[0]).data.cpu().numpy(),),\n step,\n dataformats=\"HWC\",\n )\n if add_audio:\n filterbank = librosa.filters.mel(sr=sr, n_fft=n_fft, n_mels=n_mels, fmax=fmax)\n log_mel = mel_postnet[0].data.cpu().numpy().T\n mel = np.exp(log_mel)\n magnitude = np.dot(mel, filterbank) * griffin_lim_mag_scale\n audio = griffin_lim(magnitude.T ** griffin_lim_power)\n swriter.add_audio(f\"audio/{tag}_predicted\", audio / max(np.abs(audio)), step, sample_rate=sr)\n\n log_mel = spec_target[0].data.cpu().numpy().T\n mel = np.exp(log_mel)\n magnitude = np.dot(mel, filterbank) * griffin_lim_mag_scale\n audio = griffin_lim(magnitude.T ** griffin_lim_power)\n swriter.add_audio(f\"audio/{tag}_target\", audio / max(np.abs(audio)), step, sample_rate=sr)\n\n\ndef plot_alignment_to_numpy(alignment, info=None):\n fig, ax = plt.subplots(figsize=(6, 4))\n im = ax.imshow(alignment, aspect='auto', origin='lower', interpolation='none')\n fig.colorbar(im, ax=ax)\n xlabel = 'Decoder timestep'\n if info is not None:\n xlabel += '\\n\\n' + info\n plt.xlabel(xlabel)\n plt.ylabel('Encoder timestep')\n plt.tight_layout()\n\n fig.canvas.draw()\n data = save_figure_to_numpy(fig)\n plt.close()\n return data\n\n\ndef plot_pitch_to_numpy(pitch, ylim_range=None):\n fig, ax = plt.subplots(figsize=(12, 3))\n plt.plot(pitch)\n if ylim_range is not None:\n plt.ylim(ylim_range)\n plt.xlabel(\"Frames\")\n plt.ylabel(\"Pitch\")\n plt.tight_layout()\n\n fig.canvas.draw()\n data = save_figure_to_numpy(fig)\n plt.close()\n return data\n\n\ndef plot_spectrogram_to_numpy(spectrogram):\n spectrogram = spectrogram.astype(np.float32)\n fig, ax = plt.subplots(figsize=(12, 3))\n im = ax.imshow(spectrogram, aspect=\"auto\", origin=\"lower\", interpolation='none')\n plt.colorbar(im, ax=ax)\n plt.xlabel(\"Frames\")\n plt.ylabel(\"Channels\")\n plt.tight_layout()\n\n fig.canvas.draw()\n data = save_figure_to_numpy(fig)\n plt.close()\n return data\n\n\ndef plot_gate_outputs_to_numpy(gate_targets, gate_outputs):\n fig, ax = plt.subplots(figsize=(12, 3))\n ax.scatter(\n range(len(gate_targets)), gate_targets, alpha=0.5, color='green', marker='+', s=1, label='target',\n )\n ax.scatter(\n range(len(gate_outputs)), gate_outputs, alpha=0.5, color='red', marker='.', s=1, label='predicted',\n )\n\n plt.xlabel(\"Frames (Green target, Red predicted)\")\n plt.ylabel(\"Gate State\")\n plt.tight_layout()\n\n fig.canvas.draw()\n data = save_figure_to_numpy(fig)\n plt.close()\n return data\n\n\ndef save_figure_to_numpy(fig):\n # save it to a numpy array.\n data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')\n data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))\n return data\n\n\n@rank_zero_only\ndef waveglow_log_to_tb_func(\n swriter, tensors, step, tag=\"train\", n_fft=1024, hop_length=256, window=\"hann\", mel_fb=None,\n):\n _, audio_pred, spec_target, mel_length = tensors\n mel_length = mel_length[0]\n spec_target = spec_target[0].data.cpu().numpy()[:, :mel_length]\n swriter.add_image(\n f\"{tag}_mel_target\", plot_spectrogram_to_numpy(spec_target), step, dataformats=\"HWC\",\n )\n if mel_fb is not None:\n mag, _ = librosa.core.magphase(\n librosa.core.stft(\n np.nan_to_num(audio_pred[0].cpu().detach().numpy()), n_fft=n_fft, hop_length=hop_length, window=window,\n )\n )\n mel_pred = np.matmul(mel_fb.cpu().numpy(), mag).squeeze()\n log_mel_pred = np.log(np.clip(mel_pred, a_min=1e-5, a_max=None))\n swriter.add_image(\n f\"{tag}_mel_predicted\", plot_spectrogram_to_numpy(log_mel_pred[:, :mel_length]), step, dataformats=\"HWC\",\n )\n\n\ndef remove(conv_list):\n new_conv_list = torch.nn.ModuleList()\n for old_conv in conv_list:\n old_conv = torch.nn.utils.remove_weight_norm(old_conv)\n new_conv_list.append(old_conv)\n return new_conv_list\n\n\ndef eval_tts_scores(\n y_clean: ndarray, y_est: ndarray, T_ys: Sequence[int] = (0,), sampling_rate=22050\n) -> Dict[str, float]:\n \"\"\"\n calculate metric using EvalModule. y can be a batch.\n Args:\n y_clean: real audio\n y_est: estimated audio\n T_ys: length of the non-zero parts of the histograms\n sampling_rate: The used Sampling rate.\n\n Returns:\n A dictionary mapping scoring systems (string) to numerical scores.\n 1st entry: 'STOI'\n 2nd entry: 'PESQ'\n \"\"\"\n\n if y_clean.ndim == 1:\n y_clean = y_clean[np.newaxis, ...]\n y_est = y_est[np.newaxis, ...]\n if T_ys == (0,):\n T_ys = (y_clean.shape[1],) * y_clean.shape[0]\n\n clean = y_clean[0, : T_ys[0]]\n estimated = y_est[0, : T_ys[0]]\n stoi_score = stoi(clean, estimated, sampling_rate, extended=False)\n pesq_score = pesq(16000, np.asarray(clean), estimated, 'wb')\n ## fs was set 16,000, as pesq lib doesnt currently support felxible fs.\n\n return {'STOI': stoi_score, 'PESQ': pesq_score}\n\n\ndef regulate_len(durations, enc_out, pace=1.0, mel_max_len=None):\n \"\"\"A function that takes predicted durations per encoded token, and repeats enc_out according to the duration.\n NOTE: durations.shape[1] == enc_out.shape[1]\n\n Args:\n durations (torch.tensor): A tensor of shape (batch x enc_length) that represents how many times to repeat each\n token in enc_out.\n enc_out (torch.tensor): A tensor of shape (batch x enc_length x enc_hidden) that represents the encoded tokens.\n pace (float): The pace of speaker. Higher values result in faster speaking pace. Defaults to 1.0.\n max_mel_len (int): The maximum length above which the output will be removed. If sum(durations, dim=1) >\n max_mel_len, the values after max_mel_len will be removed. Defaults to None, which has no max length.\n \"\"\"\n\n dtype = enc_out.dtype\n reps = durations.float() / pace\n reps = (reps + 0.5).long()\n dec_lens = reps.sum(dim=1)\n\n max_len = dec_lens.max()\n reps_cumsum = torch.cumsum(torch.nn.functional.pad(reps, (1, 0, 0, 0), value=0.0), dim=1)[:, None, :]\n reps_cumsum = reps_cumsum.to(dtype)\n\n range_ = torch.arange(max_len).to(enc_out.device)[None, :, None]\n mult = (reps_cumsum[:, :, :-1] <= range_) & (reps_cumsum[:, :, 1:] > range_)\n mult = mult.to(dtype)\n enc_rep = torch.matmul(mult, enc_out)\n\n if mel_max_len:\n enc_rep = enc_rep[:, :mel_max_len]\n dec_lens = torch.clamp_max(dec_lens, mel_max_len)\n\n return enc_rep, dec_lens\n\n\ndef split_view(tensor, split_size, dim=0):\n if dim < 0: # Support negative indexing\n dim = len(tensor.shape) + dim\n # If not divisible by split_size, we need to pad with 0\n if tensor.shape[dim] % split_size != 0:\n to_pad = split_size - (tensor.shape[dim] % split_size)\n padding = [0] * len(tensor.shape) * 2\n padding[dim * 2 + 1] = to_pad\n padding.reverse()\n tensor = torch.nn.functional.pad(tensor, padding)\n cur_shape = tensor.shape\n new_shape = cur_shape[:dim] + (tensor.shape[dim] // split_size, split_size) + cur_shape[dim + 1 :]\n return tensor.reshape(*new_shape)\n",
"# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport argparse\nimport json\nimport os\nimport time\nfrom pathlib import Path\nfrom typing import List\n\nimport torch\nfrom scipy.io import wavfile\n\nfrom nemo.collections import asr as nemo_asr\nfrom nemo.collections.asr.metrics.wer import WER, word_error_rate\n\nparser = argparse.ArgumentParser(description=\"Cut audio on the segments based on segments\")\nparser.add_argument(\"--output_dir\", default='output', type=str, help='Path to output directory')\nparser.add_argument(\n \"--alignment\",\n type=str,\n required=True,\n help='Path to a data directory with alignments or a single .txt file with timestamps - result of the ctc-segmentation',\n)\nparser.add_argument(\"--threshold\", type=float, default=-5, help='Minimum score value accepted')\nparser.add_argument(\n '--model',\n type=str,\n default='QuartzNet15x5Base-En',\n help='Path to model checkpoint or pre-trained CTC-based ASR model name',\n)\nparser.add_argument('--offset', type=int, default=0, help='Offset in seconds')\nparser.add_argument(\"--batch_size\", type=int, default=64, help='Batch size for inference')\n\n\ndef add_transcript_to_manifest(\n manifest_original: str, manifest_updated: str, asr_model: nemo_asr.models.EncDecCTCModel, batch_size: int\n) -> None:\n \"\"\"\n Adds transcripts generated by the asr_model to the manifest_original.\n\n Args:\n manifest_original: path to the manifest\n manifest_updated: path to the updated manifest with transcript included\n asr_model: CTC-based ASR model, for example, QuartzNet15x5Base-En\n batch_size: Batch size for asr_model inference\n \"\"\"\n transcripts = get_transcript(manifest_original, asr_model, batch_size)\n with open(manifest_original, 'r', encoding='utf8') as f:\n with open(manifest_updated, 'w', encoding='utf8') as f_updated:\n for i, line in enumerate(f):\n info = json.loads(line)\n info['pred_text'] = transcripts[i].strip()\n info['WER'] = round(word_error_rate([info['pred_text']], [info['text']]) * 100, 2)\n info['CER'] = round(word_error_rate([info['pred_text']], [info['text']], use_cer=True) * 100, 2)\n json.dump(info, f_updated, ensure_ascii=False)\n f_updated.write('\\n')\n\n\ndef get_transcript(manifest_path: str, asr_model: nemo_asr.models.EncDecCTCModel, batch_size: int) -> List[str]:\n \"\"\"\n Returns transcripts for audio segments in the batch\n\n Args:\n manifest_path: path to the manifest for inference\n asr_model: CTC-based ASR model, for example, QuartzNet15x5Base-En\n batch_size: batch size\n\n Returns: hypotheses: transcripts for the audio segments\n \"\"\"\n # batch inference\n try:\n from torch.cuda.amp import autocast\n except ImportError:\n from contextlib import contextmanager\n\n @contextmanager\n def autocast(enabled=None):\n yield\n\n torch.set_grad_enabled(False)\n asr_model.setup_test_data(\n test_data_config={\n 'sample_rate': 16000,\n 'manifest_filepath': manifest_path,\n 'labels': asr_model.decoder.vocabulary,\n 'batch_size': batch_size,\n 'normalize_transcripts': False,\n }\n )\n asr_model.eval()\n wer = WER(vocabulary=asr_model.decoder.vocabulary)\n hypotheses = []\n for test_batch in asr_model.test_dataloader():\n if torch.cuda.is_available():\n test_batch = [x.cuda() for x in test_batch]\n with autocast():\n log_probs, encoded_len, greedy_predictions = asr_model(\n input_signal=test_batch[0], input_signal_length=test_batch[1]\n )\n hypotheses += wer.ctc_decoder_predictions_tensor(greedy_predictions)\n del test_batch\n torch.cuda.empty_cache()\n return hypotheses\n\n\ndef process_alignment(alignment_file: str, args):\n \"\"\" Cut original audio file into audio segments based on alignment_file\n\n Args:\n alignment_file: path to the file with segmented text and corresponding time stamps.\n The first line of the file contains the path to the original audio file\n args: main script args\n \"\"\"\n if not os.path.exists(alignment_file):\n raise ValueError(f'{alignment_file} not found')\n\n # read the segments, note the first line contains the path to the original audio\n segments = []\n ref_text_processed = []\n ref_text_no_preprocessing = []\n with open(alignment_file, 'r') as f:\n for line in f:\n line = line.split('|')\n # read audio file name from the first line\n if len(line) == 1:\n audio_file = line[0].strip()\n continue\n ref_text_processed.append(line[1].strip())\n ref_text_no_preprocessing.append(line[2].strip())\n line = line[0].split()\n segments.append((float(line[0]) + args.offset / 1000, float(line[1]) + args.offset / 1000, float(line[2])))\n\n # cut the audio into segments\n # create manifest in /tmp directory first, then populate transcript values with the batch inference results\n # and save the final manifests at output_dir\n sampling_rate, signal = wavfile.read(audio_file)\n original_duration = len(signal) / sampling_rate\n print(f'Cutting {audio_file} based on {alignment_file}')\n print(f'Original duration: {round(original_duration)}s or ~{round(original_duration / 60)}min')\n\n # create directories to store high score .wav audio fragments, low scored once, and deleted\n args.output_dir = os.path.abspath(args.output_dir)\n os.makedirs(args.output_dir, exist_ok=True)\n fragments_dir = os.path.join(args.output_dir, \"high_score_clips\")\n del_fragments = os.path.join(args.output_dir, 'deleted_clips')\n low_score_segments_dir = os.path.join(args.output_dir, \"low_score_clips\")\n\n os.makedirs(fragments_dir, exist_ok=True)\n os.makedirs(low_score_segments_dir, exist_ok=True)\n os.makedirs(del_fragments, exist_ok=True)\n\n base_name = os.path.basename(alignment_file).replace('_segments.txt', '')\n high_score_manifest = f'{base_name}_high_score_manifest.json'\n low_score_manifest = f'{base_name}_low_score_manifest.json'\n del_manifest = f'{base_name}_del_manifest.json'\n manifests_dir = os.path.join(args.output_dir, 'manifests')\n os.makedirs(manifests_dir, exist_ok=True)\n tmp_dir = '/tmp'\n\n low_score_dur = 0\n high_score_dur = 0\n with open(os.path.join(tmp_dir, high_score_manifest), 'w', encoding='utf8') as f:\n with open(os.path.join(tmp_dir, low_score_manifest), 'w', encoding='utf8') as low_score_f:\n for i, (st, end, score) in enumerate(segments):\n segment = signal[round(st * sampling_rate) : round(end * sampling_rate)]\n duration = len(segment) / sampling_rate\n if duration > 0:\n text_processed = ref_text_processed[i].strip()\n text_no_preprocessing = ref_text_no_preprocessing[i].strip()\n if score > args.threshold:\n high_score_dur += duration\n audio_filepath = os.path.join(fragments_dir, f'{base_name}_{i:04}.wav')\n file_to_write = f\n else:\n low_score_dur += duration\n audio_filepath = os.path.join(low_score_segments_dir, f'{base_name}_{i:04}.wav')\n file_to_write = low_score_f\n\n wavfile.write(audio_filepath, sampling_rate, segment)\n\n transcript = 'n/a'\n info = {\n 'audio_filepath': audio_filepath,\n 'duration': duration,\n 'text': text_processed,\n 'text_no_preprocessing': text_no_preprocessing,\n 'score': round(score, 2),\n 'pred_text': transcript.strip(),\n }\n json.dump(info, file_to_write, ensure_ascii=False)\n file_to_write.write('\\n')\n\n add_transcript_to_manifest(\n os.path.join(tmp_dir, high_score_manifest),\n os.path.join(manifests_dir, high_score_manifest),\n asr_model,\n args.batch_size,\n )\n add_transcript_to_manifest(\n os.path.join(tmp_dir, low_score_manifest),\n os.path.join(manifests_dir, low_score_manifest),\n asr_model,\n args.batch_size,\n )\n print(f'High score files duration: {round(high_score_dur)}s or ~{round(high_score_dur/60)}min at {manifests_dir}')\n print(\n f'Low score files duration: {round(low_score_dur)}s or ~{round(low_score_dur/60)}min saved at {manifests_dir}'\n )\n\n # save deleted segments along with manifest\n deleted = []\n del_duration = 0\n begin = 0\n i = 0\n with open(os.path.join(manifests_dir, del_manifest), 'w', encoding='utf8') as f:\n for i, (st, end, _) in enumerate(segments):\n if st - begin > 0.01:\n segment = signal[int(begin * sampling_rate) : int(st * sampling_rate)]\n audio_filepath = os.path.join(del_fragments, f'del_{base_name}_{i:04}.wav')\n wavfile.write(audio_filepath, sampling_rate, segment)\n duration = len(segment) / sampling_rate\n del_duration += duration\n deleted.append((begin, st))\n transcript = 'n/a'\n info = {'audio_filepath': audio_filepath, 'duration': duration, 'text': transcript}\n json.dump(info, f, ensure_ascii=False)\n f.write('\\n')\n begin = end\n\n segment = signal[int(begin * sampling_rate) :]\n audio_filepath = os.path.join(del_fragments, f'del_{base_name}_{i+1:04}.wav')\n wavfile.write(audio_filepath, sampling_rate, segment)\n duration = len(segment) / sampling_rate\n del_duration += duration\n deleted.append((begin, original_duration))\n\n info = {'audio_filepath': audio_filepath, 'duration': duration, 'text': 'n/a'}\n json.dump(info, f)\n f.write('\\n')\n\n print(f'Saved DEL files duration: {round(del_duration)}s or ~ {round(del_duration/60)}min at {del_fragments}')\n missing_audio = original_duration - high_score_dur - del_duration - low_score_dur\n if missing_audio > 15:\n raise ValueError(f'{round(missing_audio)}s or ~ {round(missing_audio/60)}min is missing. Check the args')\n\n stats = (\n args.output_dir,\n base_name,\n round(original_duration),\n round(high_score_dur),\n round(low_score_dur),\n round(del_duration),\n )\n return stats\n\n\nif __name__ == '__main__':\n start_time = time.time()\n args = parser.parse_args()\n\n os.makedirs(args.output_dir, exist_ok=True)\n\n if os.path.exists(args.model):\n asr_model = nemo_asr.models.EncDecCTCModel.restore_from(args.model, strict=False)\n elif args.model in nemo_asr.models.EncDecCTCModel.get_available_model_names():\n asr_model = nemo_asr.models.EncDecCTCModel.from_pretrained(args.model, strict=False)\n else:\n raise ValueError(\n f'Provide path to the pretrained checkpoint or choose from {nemo_asr.models.EncDecCTCModel.list_available_models()}'\n )\n\n alignment_files = Path(args.alignment)\n if os.path.isdir(args.alignment):\n alignment_files = alignment_files.glob(\"*.txt\")\n else:\n alignment_files = [Path(alignment_files)]\n\n stats_file = os.path.join(args.output_dir, 'stats.tsv')\n with open(stats_file, 'w') as f:\n f.write('Folder\\tSegment\\tOriginal dur (s)\\tHigh quality dur (s)\\tLow quality dur (s)\\tDeleted dur (s)\\n')\n\n high_score_dur = 0\n low_score_dur = 0\n del_duration = 0\n\n for alignment_file in alignment_files:\n stats = process_alignment(alignment_file, args)\n high_score_dur += stats[-3]\n low_score_dur += stats[-2]\n del_duration += stats[-1]\n stats = '\\t'.join([str(t) for t in stats]) + '\\n'\n f.write(stats)\n\n f.write(f'Total\\t\\t{round(high_score_dur)}\\t{round(low_score_dur)}\\t{del_duration}')\n\n total_time = time.time() - start_time\n print(f'High score segments duration: {round(high_score_dur)}')\n print(f'Low score segments duration: {round(low_score_dur)}')\n print(f'Deleted segments duration: {round(del_duration)}')\n print(f'Stats saved at {stats_file}')\n print(f'Total execution time: ~{round(total_time / 60)}min')\n",
"# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport json\nimport re\nfrom itertools import chain\n\nimport numpy as np\nimport torch\nfrom hydra.utils import instantiate\nfrom omegaconf import DictConfig, OmegaConf, open_dict\nfrom pytorch_lightning.loggers import LoggerCollection, TensorBoardLogger\n\nfrom nemo.collections.common.parts.preprocessing import parsers\nfrom nemo.collections.tts.helpers.helpers import plot_spectrogram_to_numpy\nfrom nemo.collections.tts.losses.fastspeech2loss import DurationLoss, L1MelLoss\nfrom nemo.collections.tts.losses.hifigan_losses import DiscriminatorLoss, FeatureMatchingLoss, GeneratorLoss\nfrom nemo.collections.tts.models.base import TextToWaveform\nfrom nemo.collections.tts.modules.hifigan_modules import MultiPeriodDiscriminator, MultiScaleDiscriminator\nfrom nemo.core.classes.common import PretrainedModelInfo, typecheck\nfrom nemo.core.neural_types.elements import (\n LengthsType,\n MaskType,\n MelSpectrogramType,\n RegressionValuesType,\n TokenDurationType,\n TokenIndex,\n TokenLogDurationType,\n)\nfrom nemo.core.neural_types.neural_type import NeuralType\nfrom nemo.core.optim.lr_scheduler import NoamAnnealing\nfrom nemo.utils import logging\n\n\nclass FastSpeech2HifiGanE2EModel(TextToWaveform):\n \"\"\"An end-to-end speech synthesis model based on FastSpeech2 and HiFiGan that converts strings to audio without\n using the intermediate mel spectrogram representation.\"\"\"\n\n def __init__(self, cfg: DictConfig, trainer: 'Trainer' = None):\n if isinstance(cfg, dict):\n cfg = OmegaConf.create(cfg)\n super().__init__(cfg=cfg, trainer=trainer)\n\n self.audio_to_melspec_precessor = instantiate(cfg.preprocessor)\n self.encoder = instantiate(cfg.encoder)\n self.variance_adapter = instantiate(cfg.variance_adaptor)\n\n self.generator = instantiate(cfg.generator)\n self.multiperioddisc = MultiPeriodDiscriminator()\n self.multiscaledisc = MultiScaleDiscriminator()\n\n self.melspec_fn = instantiate(cfg.preprocessor, highfreq=None, use_grads=True)\n self.mel_val_loss = L1MelLoss()\n self.durationloss = DurationLoss()\n self.feat_matching_loss = FeatureMatchingLoss()\n self.disc_loss = DiscriminatorLoss()\n self.gen_loss = GeneratorLoss()\n self.mseloss = torch.nn.MSELoss()\n\n self.energy = cfg.add_energy_predictor\n self.pitch = cfg.add_pitch_predictor\n self.mel_loss_coeff = cfg.mel_loss_coeff\n self.pitch_loss_coeff = cfg.pitch_loss_coeff\n self.energy_loss_coeff = cfg.energy_loss_coeff\n self.splice_length = cfg.splice_length\n\n self.use_energy_pred = False\n self.use_pitch_pred = False\n self.log_train_images = False\n self.logged_real_samples = False\n self._tb_logger = None\n self.sample_rate = cfg.sample_rate\n self.hop_size = cfg.hop_size\n\n # Parser and mappings are used for inference only.\n self.parser = parsers.make_parser(name='en')\n if 'mappings_filepath' in cfg:\n mappings_filepath = cfg.get('mappings_filepath')\n else:\n logging.error(\n \"ERROR: You must specify a mappings.json file in the config file under model.mappings_filepath.\"\n )\n mappings_filepath = self.register_artifact('mappings_filepath', mappings_filepath)\n with open(mappings_filepath, 'r') as f:\n mappings = json.load(f)\n self.word2phones = mappings['word2phones']\n self.phone2idx = mappings['phone2idx']\n\n @property\n def tb_logger(self):\n if self._tb_logger is None:\n if self.logger is None and self.logger.experiment is None:\n return None\n tb_logger = self.logger.experiment\n if isinstance(self.logger, LoggerCollection):\n for logger in self.logger:\n if isinstance(logger, TensorBoardLogger):\n tb_logger = logger.experiment\n break\n self._tb_logger = tb_logger\n return self._tb_logger\n\n def configure_optimizers(self):\n gen_params = chain(self.encoder.parameters(), self.generator.parameters(), self.variance_adapter.parameters(),)\n disc_params = chain(self.multiscaledisc.parameters(), self.multiperioddisc.parameters())\n opt1 = torch.optim.AdamW(disc_params, lr=self._cfg.lr)\n opt2 = torch.optim.AdamW(gen_params, lr=self._cfg.lr)\n num_procs = self._trainer.num_gpus * self._trainer.num_nodes\n num_samples = len(self._train_dl.dataset)\n batch_size = self._train_dl.batch_size\n iter_per_epoch = np.ceil(num_samples / (num_procs * batch_size))\n max_steps = iter_per_epoch * self._trainer.max_epochs\n logging.info(f\"MAX STEPS: {max_steps}\")\n sch1 = NoamAnnealing(opt1, d_model=256, warmup_steps=3000, max_steps=max_steps, min_lr=1e-5)\n sch1_dict = {\n 'scheduler': sch1,\n 'interval': 'step',\n }\n sch2 = NoamAnnealing(opt2, d_model=256, warmup_steps=3000, max_steps=max_steps, min_lr=1e-5)\n sch2_dict = {\n 'scheduler': sch2,\n 'interval': 'step',\n }\n return [opt1, opt2], [sch1_dict, sch2_dict]\n\n @typecheck(\n input_types={\n \"text\": NeuralType(('B', 'T'), TokenIndex()),\n \"text_length\": NeuralType(('B'), LengthsType()),\n \"splice\": NeuralType(optional=True),\n \"spec_len\": NeuralType(('B'), LengthsType(), optional=True),\n \"durations\": NeuralType(('B', 'T'), TokenDurationType(), optional=True),\n \"pitch\": NeuralType(('B', 'T'), RegressionValuesType(), optional=True),\n \"energies\": NeuralType(('B', 'T'), RegressionValuesType(), optional=True),\n },\n output_types={\n \"audio\": NeuralType(('B', 'S', 'T'), MelSpectrogramType()),\n \"splices\": NeuralType(),\n \"log_dur_preds\": NeuralType(('B', 'T'), TokenLogDurationType()),\n \"pitch_preds\": NeuralType(('B', 'T'), RegressionValuesType()),\n \"energy_preds\": NeuralType(('B', 'T'), RegressionValuesType()),\n \"encoded_text_mask\": NeuralType(('B', 'T', 'D'), MaskType()),\n },\n )\n def forward(self, *, text, text_length, splice=True, durations=None, pitch=None, energies=None, spec_len=None):\n encoded_text, encoded_text_mask = self.encoder(text=text, text_length=text_length)\n\n context, log_dur_preds, pitch_preds, energy_preds, spec_len = self.variance_adapter(\n x=encoded_text,\n x_len=text_length,\n dur_target=durations,\n pitch_target=pitch,\n energy_target=energies,\n spec_len=spec_len,\n )\n\n gen_in = context\n splices = None\n if splice:\n # Splice generated spec\n output = []\n splices = []\n for i, sample in enumerate(context):\n start = np.random.randint(low=0, high=min(int(sample.size(0)), int(spec_len[i])) - self.splice_length)\n output.append(sample[start : start + self.splice_length, :])\n splices.append(start)\n gen_in = torch.stack(output)\n\n output = self.generator(x=gen_in.transpose(1, 2))\n\n return output, splices, log_dur_preds, pitch_preds, energy_preds, encoded_text_mask\n\n def training_step(self, batch, batch_idx, optimizer_idx):\n f, fl, t, tl, durations, pitch, energies = batch\n spec, spec_len = self.audio_to_melspec_precessor(f, fl)\n\n # train discriminator\n if optimizer_idx == 0:\n with torch.no_grad():\n audio_pred, splices, _, _, _, _ = self(\n spec=spec,\n spec_len=spec_len,\n text=t,\n text_length=tl,\n durations=durations,\n pitch=pitch if not self.use_pitch_pred else None,\n energies=energies if not self.use_energy_pred else None,\n )\n real_audio = []\n for i, splice in enumerate(splices):\n real_audio.append(f[i, splice * self.hop_size : (splice + self.splice_length) * self.hop_size])\n real_audio = torch.stack(real_audio).unsqueeze(1)\n\n real_score_mp, gen_score_mp, _, _ = self.multiperioddisc(real_audio, audio_pred)\n real_score_ms, gen_score_ms, _, _ = self.multiscaledisc(real_audio, audio_pred)\n\n loss_mp, loss_mp_real, _ = self.disc_loss(real_score_mp, gen_score_mp)\n loss_ms, loss_ms_real, _ = self.disc_loss(real_score_ms, gen_score_ms)\n loss_mp /= len(loss_mp_real)\n loss_ms /= len(loss_ms_real)\n loss_disc = loss_mp + loss_ms\n\n self.log(\"loss_discriminator\", loss_disc, prog_bar=True)\n self.log(\"loss_discriminator_ms\", loss_ms)\n self.log(\"loss_discriminator_mp\", loss_mp)\n return loss_disc\n\n # train generator\n elif optimizer_idx == 1:\n audio_pred, splices, log_dur_preds, pitch_preds, energy_preds, encoded_text_mask = self(\n spec=spec,\n spec_len=spec_len,\n text=t,\n text_length=tl,\n durations=durations,\n pitch=pitch if not self.use_pitch_pred else None,\n energies=energies if not self.use_energy_pred else None,\n )\n real_audio = []\n for i, splice in enumerate(splices):\n real_audio.append(f[i, splice * self.hop_size : (splice + self.splice_length) * self.hop_size])\n real_audio = torch.stack(real_audio).unsqueeze(1)\n\n # Do HiFiGAN generator loss\n audio_length = torch.tensor([self.splice_length * self.hop_size for _ in range(real_audio.shape[0])]).to(\n real_audio.device\n )\n real_spliced_spec, _ = self.melspec_fn(real_audio.squeeze(), seq_len=audio_length)\n pred_spliced_spec, _ = self.melspec_fn(audio_pred.squeeze(), seq_len=audio_length)\n loss_mel = torch.nn.functional.l1_loss(real_spliced_spec, pred_spliced_spec)\n loss_mel *= self.mel_loss_coeff\n _, gen_score_mp, real_feat_mp, gen_feat_mp = self.multiperioddisc(real_audio, audio_pred)\n _, gen_score_ms, real_feat_ms, gen_feat_ms = self.multiscaledisc(real_audio, audio_pred)\n loss_gen_mp, list_loss_gen_mp = self.gen_loss(gen_score_mp)\n loss_gen_ms, list_loss_gen_ms = self.gen_loss(gen_score_ms)\n loss_gen_mp /= len(list_loss_gen_mp)\n loss_gen_ms /= len(list_loss_gen_ms)\n total_loss = loss_gen_mp + loss_gen_ms + loss_mel\n loss_feat_mp = self.feat_matching_loss(real_feat_mp, gen_feat_mp)\n loss_feat_ms = self.feat_matching_loss(real_feat_ms, gen_feat_ms)\n total_loss += loss_feat_mp + loss_feat_ms\n self.log(name=\"loss_gen_disc_feat\", value=loss_feat_mp + loss_feat_ms)\n self.log(name=\"loss_gen_disc_feat_ms\", value=loss_feat_ms)\n self.log(name=\"loss_gen_disc_feat_mp\", value=loss_feat_mp)\n\n self.log(name=\"loss_gen_mel\", value=loss_mel)\n self.log(name=\"loss_gen_disc\", value=loss_gen_mp + loss_gen_ms)\n self.log(name=\"loss_gen_disc_mp\", value=loss_gen_mp)\n self.log(name=\"loss_gen_disc_ms\", value=loss_gen_ms)\n\n dur_loss = self.durationloss(\n log_duration_pred=log_dur_preds, duration_target=durations.float(), mask=encoded_text_mask\n )\n self.log(name=\"loss_gen_duration\", value=dur_loss)\n total_loss += dur_loss\n if self.pitch:\n pitch_loss = self.mseloss(pitch_preds, pitch.float()) * self.pitch_loss_coeff\n total_loss += pitch_loss\n self.log(name=\"loss_gen_pitch\", value=pitch_loss)\n if self.energy:\n energy_loss = self.mseloss(energy_preds, energies) * self.energy_loss_coeff\n total_loss += energy_loss\n self.log(name=\"loss_gen_energy\", value=energy_loss)\n\n # Log images to tensorboard\n if self.log_train_images:\n self.log_train_images = False\n if self.logger is not None and self.logger.experiment is not None:\n self.tb_logger.add_image(\n \"train_mel_target\",\n plot_spectrogram_to_numpy(real_spliced_spec[0].data.cpu().numpy()),\n self.global_step,\n dataformats=\"HWC\",\n )\n spec_predict = pred_spliced_spec[0].data.cpu().numpy()\n self.tb_logger.add_image(\n \"train_mel_predicted\",\n plot_spectrogram_to_numpy(spec_predict),\n self.global_step,\n dataformats=\"HWC\",\n )\n self.log(name=\"loss_gen\", prog_bar=True, value=total_loss)\n return total_loss\n\n def validation_step(self, batch, batch_idx):\n f, fl, t, tl, _, _, _ = batch\n spec, spec_len = self.audio_to_melspec_precessor(f, fl)\n audio_pred, _, _, _, _, _ = self(spec=spec, spec_len=spec_len, text=t, text_length=tl, splice=False)\n audio_pred.squeeze_()\n pred_spec, _ = self.melspec_fn(audio_pred, seq_len=spec_len)\n loss = self.mel_val_loss(spec_pred=pred_spec, spec_target=spec, spec_target_len=spec_len, pad_value=-11.52)\n\n return {\n \"val_loss\": loss,\n \"audio_target\": f.squeeze() if batch_idx == 0 else None,\n \"audio_pred\": audio_pred if batch_idx == 0 else None,\n }\n\n def on_train_epoch_start(self):\n # Switch to using energy predictions after 50% of training\n if not self.use_energy_pred and self.current_epoch >= np.ceil(0.5 * self._trainer.max_epochs):\n logging.info(f\"Using energy predictions after epoch: {self.current_epoch}\")\n self.use_energy_pred = True\n\n # Switch to using pitch predictions after 62.5% of training\n if not self.use_pitch_pred and self.current_epoch >= np.ceil(0.625 * self._trainer.max_epochs):\n logging.info(f\"Using pitch predictions after epoch: {self.current_epoch}\")\n self.use_pitch_pred = True\n\n def validation_epoch_end(self, outputs):\n if self.tb_logger is not None:\n _, audio_target, audio_predict = outputs[0].values()\n if not self.logged_real_samples:\n self.tb_logger.add_audio(\"val_target\", audio_target[0].data.cpu(), self.global_step, self.sample_rate)\n self.logged_real_samples = True\n audio_predict = audio_predict[0].data.cpu()\n self.tb_logger.add_audio(\"val_pred\", audio_predict, self.global_step, self.sample_rate)\n avg_loss = torch.stack([x['val_loss'] for x in outputs]).mean() # This reduces across batches, not workers!\n self.log('val_loss', avg_loss, sync_dist=True)\n\n self.log_train_images = True\n\n def __setup_dataloader_from_config(self, cfg, shuffle_should_be: bool = True, name: str = \"train\"):\n if \"dataset\" not in cfg or not isinstance(cfg.dataset, DictConfig):\n raise ValueError(f\"No dataset for {name}\")\n if \"dataloader_params\" not in cfg or not isinstance(cfg.dataloader_params, DictConfig):\n raise ValueError(f\"No dataloder_params for {name}\")\n if shuffle_should_be:\n if 'shuffle' not in cfg.dataloader_params:\n logging.warning(\n f\"Shuffle should be set to True for {self}'s {name} dataloader but was not found in its \"\n \"config. Manually setting to True\"\n )\n with open_dict(cfg.dataloader_params):\n cfg.dataloader_params.shuffle = True\n elif not cfg.dataloader_params.shuffle:\n logging.error(f\"The {name} dataloader for {self} has shuffle set to False!!!\")\n elif not shuffle_should_be and cfg.dataloader_params.shuffle:\n logging.error(f\"The {name} dataloader for {self} has shuffle set to True!!!\")\n\n dataset = instantiate(cfg.dataset)\n return torch.utils.data.DataLoader(dataset, collate_fn=dataset.collate_fn, **cfg.dataloader_params)\n\n def setup_training_data(self, cfg):\n self._train_dl = self.__setup_dataloader_from_config(cfg)\n\n def setup_validation_data(self, cfg):\n self._validation_dl = self.__setup_dataloader_from_config(cfg, shuffle_should_be=False, name=\"validation\")\n\n def parse(self, str_input: str, additional_word2phones=None) -> torch.tensor:\n \"\"\"\n Parses text input and converts them to phoneme indices.\n\n str_input (str): The input text to be converted.\n additional_word2phones (dict): Optional dictionary mapping words to phonemes for updating the model's\n word2phones. This will not overwrite the existing dictionary, just update it with OOV or new mappings.\n Defaults to None, which will keep the existing mapping.\n \"\"\"\n # Update model's word2phones if applicable\n if additional_word2phones is not None:\n self.word2phones.update(additional_word2phones)\n\n # Convert text -> normalized text -> list of phones per word -> indices\n if str_input[-1] not in [\".\", \"!\", \"?\"]:\n str_input = str_input + \".\"\n norm_text = re.findall(r\"\"\"[\\w']+|[.,!?;\"]\"\"\", self.parser._normalize(str_input))\n\n try:\n phones = [self.word2phones[t] for t in norm_text]\n except KeyError as error:\n logging.error(\n f\"ERROR: The following word in the input is not in the model's dictionary and could not be converted\"\n f\" to phonemes: ({error}).\\n\"\n f\"You can pass in an `additional_word2phones` dictionary with a conversion for\"\n f\" this word, e.g. {{'{error}': \\['phone1', 'phone2', ...\\]}} to update the model's mapping.\"\n )\n raise\n\n tokens = []\n for phone_list in phones:\n inds = [self.phone2idx[p] for p in phone_list]\n tokens += inds\n\n x = torch.tensor(tokens).unsqueeze_(0).long().to(self.device)\n return x\n\n def convert_text_to_waveform(self, *, tokens):\n \"\"\"\n Accepts tokens returned from self.parse() and returns a list of tensors. Note: The tensors in the list can have\n different lengths.\n \"\"\"\n self.eval()\n token_len = torch.tensor([len(i) for i in tokens]).to(self.device)\n audio, _, log_dur_pred, _, _, _ = self(text=tokens, text_length=token_len, splice=False)\n audio = audio.squeeze(1)\n durations = torch.sum(torch.exp(log_dur_pred) - 1, 1).to(torch.int)\n audio_list = []\n for i, sample in enumerate(audio):\n audio_list.append(sample[: durations[i] * self.hop_size])\n\n return audio_list\n\n @classmethod\n def list_available_models(cls) -> 'List[PretrainedModelInfo]':\n \"\"\"\n This method returns a list of pre-trained model which can be instantiated directly from NVIDIA's NGC cloud.\n Returns:\n List of available pre-trained models.\n \"\"\"\n list_of_models = []\n model = PretrainedModelInfo(\n pretrained_model_name=\"tts_en_e2e_fastspeech2hifigan\",\n location=\"https://api.ngc.nvidia.com/v2/models/nvidia/nemo/tts_en_e2e_fastspeech2hifigan/versions/1.0.0/files/tts_en_e2e_fastspeech2hifigan.nemo\",\n description=\"This model is trained on LJSpeech sampled at 22050Hz with and can be used to generate female English voices with an American accent.\",\n class_=cls,\n )\n list_of_models.append(model)\n\n return list_of_models\n",
"# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom typing import Dict, Optional\n\nimport torch\nfrom omegaconf import DictConfig\nfrom pytorch_lightning import Trainer\nfrom transformers import AutoTokenizer\n\nfrom nemo.collections.common.losses import MultiSimilarityLoss\nfrom nemo.collections.nlp.data import EntityLinkingDataset\nfrom nemo.collections.nlp.models.nlp_model import NLPModel\nfrom nemo.collections.nlp.modules.common.lm_utils import get_lm_model\nfrom nemo.core.classes.common import typecheck\nfrom nemo.core.classes.exportable import Exportable\nfrom nemo.core.neural_types import ChannelType, LogitsType, MaskType, NeuralType\nfrom nemo.utils import logging\n\n__all__ = ['EntityLinkingModel']\n\n\nclass EntityLinkingModel(NLPModel, Exportable):\n \"\"\"\n Second stage pretraining of BERT based language model\n for entity linking task. An implementation of Liu et. al's\n NAACL 2021 paper Self-Alignment Pretraining for Biomedical Entity Representations.\n \"\"\"\n\n @property\n def input_types(self) -> Optional[Dict[str, NeuralType]]:\n return self.model.input_types\n\n @property\n def output_types(self) -> Optional[Dict[str, NeuralType]]:\n return {\"logits\": NeuralType(('B', 'D'), LogitsType())}\n\n def __init__(self, cfg: DictConfig, trainer: Trainer = None):\n \"\"\"Initializes the SAP-BERT model for entity linking.\"\"\"\n\n # tokenizer needed before super().__init__() so dataset and loader can process data\n self._setup_tokenizer(cfg.tokenizer)\n\n super().__init__(cfg=cfg, trainer=trainer)\n\n self.model = get_lm_model(\n pretrained_model_name=cfg.language_model.pretrained_model_name,\n config_file=cfg.language_model.config_file,\n config_dict=cfg.language_model.config,\n checkpoint_file=cfg.language_model.lm_checkpoint,\n )\n\n # Token to use for the self-alignment loss, typically the first token, [CLS]\n self._idx_conditioned_on = 0\n self.loss = MultiSimilarityLoss()\n\n def _setup_tokenizer(self, cfg: DictConfig):\n tokenizer = AutoTokenizer.from_pretrained(\n cfg.tokenizer_name, vocab_file=cfg.vocab_file, do_lower_case=cfg.do_lower_case\n )\n\n self.tokenizer = tokenizer\n\n @typecheck()\n def forward(self, input_ids, token_type_ids, attention_mask):\n hidden_states = self.model(input_ids=input_ids, token_type_ids=token_type_ids, attention_mask=attention_mask)\n\n # normalize to unit sphere\n logits = torch.nn.functional.normalize(hidden_states[:, self._idx_conditioned_on], p=2, dim=1)\n return logits\n\n def training_step(self, batch, batch_idx):\n \"\"\"\n Lightning calls this inside the training loop with the data from the training dataloader\n passed in as `batch`.\n \"\"\"\n input_ids, token_type_ids, attention_mask, concept_ids = batch\n logits = self.forward(input_ids=input_ids, token_type_ids=token_type_ids, attention_mask=attention_mask)\n train_loss = self.loss(logits=logits, labels=concept_ids)\n\n # No hard examples found in batch,\n # shouldn't use this batch to update model weights\n if train_loss == 0:\n train_loss = None\n lr = None\n\n else:\n lr = self._optimizer.param_groups[0][\"lr\"]\n self.log(\"train_loss\", train_loss)\n self.log(\"lr\", lr, prog_bar=True)\n\n return {\"loss\": train_loss, \"lr\": lr}\n\n def validation_step(self, batch, batch_idx):\n \"\"\"\n Lightning calls this inside the validation loop with the data from the validation dataloader\n passed in as `batch`.\n \"\"\"\n input_ids, input_type_ids, input_mask, concept_ids = batch\n with torch.no_grad():\n logits = self.forward(input_ids=input_ids, token_type_ids=input_type_ids, attention_mask=input_mask)\n val_loss = self.loss(logits=logits, labels=concept_ids)\n\n # No hard examples found in batch,\n # val loss not used to update model weights\n if val_loss == 0:\n val_loss = None\n else:\n self.log(\"val_loss\", val_loss)\n logging.info(f\"val loss: {val_loss}\")\n\n return {\"val_loss\": val_loss}\n\n def validation_epoch_end(self, outputs):\n \"\"\"\n Called at the end of validation to aggregate outputs.\n\n Args:\n outputs: list of individual outputs of each validation step.\n Returns:\n \n \"\"\"\n if outputs:\n avg_loss = torch.stack([x[\"val_loss\"] for x in outputs if x[\"val_loss\"] != None]).mean()\n self.log(f\"val_loss\", avg_loss, prog_bar=True)\n\n return {\"val_loss\": avg_loss}\n\n def setup_training_data(self, train_data_config: Optional[DictConfig]):\n if not train_data_config or not train_data_config.data_file:\n logging.info(\n f\"Dataloader config or file_path or processed data path for the train dataset is missing, \\\n so no data loader for train is created!\"\n )\n\n self._train_dl = None\n return\n\n self._train_dl = self.setup_dataloader(cfg=train_data_config)\n\n def setup_validation_data(self, val_data_config: Optional[DictConfig]):\n if not val_data_config or not val_data_config.data_file:\n logging.info(\n f\"Dataloader config or file_path or processed data path for the val dataset is missing, \\\n so no data loader for validation is created!\"\n )\n\n self._validation_dl = None\n return\n\n self._validation_dl = self.setup_dataloader(cfg=val_data_config)\n\n def setup_dataloader(self, cfg: Dict, is_index_data: bool = False) -> 'torch.utils.data.DataLoader':\n\n dataset = EntityLinkingDataset(\n tokenizer=self.tokenizer,\n data_file=cfg.data_file,\n max_seq_length=cfg.max_seq_length,\n is_index_data=is_index_data,\n )\n\n return torch.utils.data.DataLoader(\n dataset=dataset,\n batch_size=cfg.batch_size,\n collate_fn=dataset.collate_fn,\n shuffle=cfg.get(\"shuffle\", True),\n num_workers=cfg.get(\"num_wokers\", 2),\n pin_memory=cfg.get(\"pin_memory\", False),\n drop_last=cfg.get(\"drop_last\", False),\n )\n\n @classmethod\n def list_available_models(cls) -> Optional[Dict[str, str]]:\n pass\n\n @classmethod\n def from_pretrained(cls, name: str):\n pass\n"
] | [
[
"numpy.min",
"numpy.asarray",
"numpy.median",
"torch.distributed.is_initialized",
"numpy.percentile",
"numpy.max",
"numpy.mean"
],
[
"numpy.array_equal",
"torch.load"
],
[
"numpy.round",
"torch.LongTensor",
"numpy.array",
"torch.save"
],
[
"numpy.isnan",
"numpy.median",
"pandas.DataFrame",
"numpy.round",
"numpy.savetxt",
"numpy.zeros",
"numpy.loadtxt"
],
[
"torch.distributed.get_rank",
"torch.hub._get_torch_home",
"torch.distributed.is_initialized",
"torch.distributed.barrier"
],
[
"numpy.dot",
"torch.max",
"numpy.asarray",
"numpy.zeros_like",
"torch.no_grad",
"numpy.exp",
"matplotlib.pylab.close",
"matplotlib.pylab.tight_layout",
"torch.clamp_max",
"numpy.clip",
"torch.from_numpy",
"torch.nn.utils.remove_weight_norm",
"torch.tensor",
"numpy.argmax",
"matplotlib.pylab.plot",
"torch.arange",
"torch.nn.functional.pad",
"numpy.log",
"torch.sigmoid",
"torch.nn.ModuleList",
"torch.zeros_like",
"numpy.random.rand",
"matplotlib.pylab.colorbar",
"numpy.array",
"numpy.abs",
"numpy.isfinite",
"torch.matmul",
"matplotlib.pylab.subplots",
"matplotlib.pylab.ylabel",
"matplotlib.pylab.ylim",
"matplotlib.pylab.xlabel"
],
[
"scipy.io.wavfile.write",
"torch.cuda.empty_cache",
"torch.cuda.amp.autocast",
"torch.set_grad_enabled",
"torch.cuda.is_available",
"scipy.io.wavfile.read"
],
[
"torch.nn.functional.l1_loss",
"torch.utils.data.DataLoader",
"torch.tensor",
"torch.exp",
"numpy.ceil",
"torch.optim.AdamW",
"torch.no_grad",
"torch.stack",
"torch.nn.MSELoss"
],
[
"torch.nn.functional.normalize",
"torch.no_grad",
"torch.stack"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"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": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"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": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Kenneth-Wong/tf-faster-rcnn | [
"a6bd798df1b9075ebdfeb7744fffc13226c3a65e",
"a6bd798df1b9075ebdfeb7744fffc13226c3a65e"
] | [
"lib/model/config.py",
"lib/roi_data_layer/layer.py"
] | [
"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport os.path as osp\nimport numpy as np\n# `pip install easydict` if you don't have it\nfrom easydict import EasyDict as edict\n\n__C = edict()\n# Consumers can get config by:\n# from fast_rcnn_config import cfg\ncfg = __C\n\n#\n# Memory options\n#\n__C.MEM = edict()\n\n# Number of memory iterations\n__C.MEM.ITER = 2\n\n# Height of the memory\n__C.MEM.INIT_H = 20\n# Width of the memory\n__C.MEM.INIT_W = 20\n\n# Channel of the memory\n__C.MEM.C = 512\n\n# Basic stds in the memory\n__C.MEM.STD = 0.01\n# Base stds in the memory update function for input features\n__C.MEM.U_STD = 0.01\n# Region classification\n__C.MEM.C_STD = 0.01\n\n# Feature to memory ratio\n__C.MEM.FM_R = 1.\n# Value to gate ratio\n__C.MEM.VG_R = 1.\n# FC to Pool ratio when combing the input\n__C.MEM.FP_R = 1.\n\n# Conv kernel size for memory\n__C.MEM.CONV = 3\n\n# Canonical region size\n__C.MEM.CROP_SIZE = 7\n\n# Context aggregation\n__C.MEM.CT_L = 3\n__C.MEM.CT_CONV = 3\n__C.MEM.CT_FCONV = 3\n\n# Input feature\n__C.MEM.IN_L = 2\n__C.MEM.IN_CONV = 3\n\n# Memory final fc layer channels\n__C.MEM.FC_C = 4096\n__C.MEM.FC_L = 2\n\n# The weight for the memory based prediction\n__C.MEM.WEIGHT = 1.\n\n__C.MEM.REL_WEIGHT = 1.\n\n# Final supervision weight\n__C.MEM.WEIGHT_FINAL = 1.\n# The threshold to control the entropy of the distribution\n__C.MEM.BETA = .5\n\n# The dimension of predicted tag\n__C.MEM.TAG_D = 16\n\n\n#\n# Training options\n#\n__C.TRAIN = edict()\n\n# Initial learning rate\n__C.TRAIN.RATE = 0.0005\n\n# Momentum\n__C.TRAIN.MOMENTUM = 0.9\n\n# Weight decay, for regularization\n__C.TRAIN.WEIGHT_DECAY = 0.0001\n\n# Factor for reducing the learning rate\n__C.TRAIN.GAMMA = 0.1\n\n# Step size for reducing the learning rate, currently only support one step\n__C.TRAIN.STEPSIZE = [30000]\n\n# Iteration intervals for showing the loss during training, on command line interface\n__C.TRAIN.DISPLAY = 10\n\n# Whether to double the learning rate for bias\n__C.TRAIN.DOUBLE_BIAS = True\n\n# Whether to initialize the weights with truncated normal distribution \n__C.TRAIN.TRUNCATED = False\n\n# Whether to have weight decay on bias as well\n__C.TRAIN.BIAS_DECAY = False\n\n# Whether to add ground truth boxes to the pool when sampling regions\n__C.TRAIN.USE_GT = False\n\n# Whether to use aspect-ratio grouping of training images, introduced merely for saving\n# GPU memory\n__C.TRAIN.ASPECT_GROUPING = False\n\n# The number of snapshots kept, older ones are deleted to save space\n__C.TRAIN.SNAPSHOT_KEPT = 3\n\n# The time interval for saving tensorflow summaries\n__C.TRAIN.SUMMARY_INTERVAL = 180\n\n# The time interval for saving tensorflow summaries\n__C.TRAIN.SUMMARY_ITERS = 500\n\n# Scale to use during training (can list multiple scales)\n# The scale is the pixel size of an image's shortest side\n__C.TRAIN.SCALES = (600,)\n\n# Max pixel size of the longest side of a scaled input image\n__C.TRAIN.MAX_SIZE = 1000\n\n# Images to use per minibatch\n__C.TRAIN.IMS_PER_BATCH = 1\n\n# Minibatch size (number of regions of interest [ROIs])\n__C.TRAIN.BATCH_SIZE = 128\n\n__C.TRAIN.REL_BATCH_SIZE = 128\n\n__C.TRAIN.POS_REL_FRACTION = 0.5\n\n# Fraction of minibatch that is labeled foreground (i.e. class > 0)\n__C.TRAIN.FG_FRACTION = 0.25\n\n# Overlap threshold for a ROI to be considered foreground (if >= FG_THRESH)\n__C.TRAIN.FG_THRESH = 0.5\n\n# Overlap threshold for a ROI to be considered background (class = 0 if\n# overlap in [LO, HI))\n__C.TRAIN.BG_THRESH_HI = 0.5\n__C.TRAIN.BG_THRESH_LO = 0.1\n\n# Use horizontally-flipped images during training?\n__C.TRAIN.USE_FLIPPED = True\n\n# Train bounding-box regressors\n__C.TRAIN.BBOX_REG = True\n\n# Overlap required between a ROI and ground-truth box in order for that ROI to\n# be used as a bounding-box regression training example\n__C.TRAIN.BBOX_THRESH = 0.5\n\n# Iterations between snapshots\n__C.TRAIN.SNAPSHOT_ITERS = 5000\n\n# solver.prototxt specifies the snapshot path prefix, this adds an optional\n# infix to yield the path: <prefix>[_<infix>]_iters_XYZ.caffemodel\n__C.TRAIN.SNAPSHOT_PREFIX = 'res101_faster_rcnn'\n\n# Normalize the targets (subtract empirical mean, divide by empirical stddev)\n__C.TRAIN.BBOX_NORMALIZE_TARGETS = True\n__C.TRAIN.BBOX_TARGET_NORMALIZATION_FILE = 'bbox_distribution.npy'\n# Deprecated (inside weights)\n__C.TRAIN.BBOX_INSIDE_WEIGHTS = (1.0, 1.0, 1.0, 1.0)\n\n# Normalize the targets using \"precomputed\" (or made up) means and stdevs\n# (BBOX_NORMALIZE_TARGETS must also be True)\n__C.TRAIN.BBOX_NORMALIZE_TARGETS_PRECOMPUTED = False\n\n__C.TRAIN.BBOX_NORMALIZE_MEANS = (0.0, 0.0, 0.0, 0.0)\n\n__C.TRAIN.BBOX_NORMALIZE_STDS = (0.1, 0.1, 0.2, 0.2)\n\n# Train using these proposals\n__C.TRAIN.PROPOSAL_METHOD = 'gt'\n\n# Make minibatches from images that have similar aspect ratios (i.e. both\n# tall and thin or both short and wide) in order to avoid wasting computation\n# on zero-padding.\n\n# Use RPN to detect objects\n__C.TRAIN.HAS_RPN = True\n\n# IOU >= thresh: positive example\n__C.TRAIN.RPN_POSITIVE_OVERLAP = 0.7\n\n# IOU < thresh: negative example\n__C.TRAIN.RPN_NEGATIVE_OVERLAP = 0.3\n\n# If an anchor satisfied by positive and negative conditions set to negative\n__C.TRAIN.RPN_CLOBBER_POSITIVES = False\n\n# Max number of foreground examples\n__C.TRAIN.RPN_FG_FRACTION = 0.5\n\n# Total number of examples\n__C.TRAIN.RPN_BATCHSIZE = 256\n\n# NMS threshold used on RPN proposals\n__C.TRAIN.RPN_NMS_THRESH = 0.7\n\n# Number of top scoring boxes to keep before apply NMS to RPN proposals\n__C.TRAIN.RPN_PRE_NMS_TOP_N = 12000\n\n# Number of top scoring boxes to keep after applying NMS to RPN proposals\n__C.TRAIN.RPN_POST_NMS_TOP_N = 2000\n\n# Deprecated (outside weights)\n__C.TRAIN.RPN_BBOX_INSIDE_WEIGHTS = (1.0, 1.0, 1.0, 1.0)\n\n# Give the positive RPN examples weight of p * 1 / {num positives}\n# and give negatives a weight of (1 - p)\n# Set to -1.0 to use uniform example weighting\n__C.TRAIN.RPN_POSITIVE_WEIGHT = -1.0\n\n# Whether to use all ground truth bounding boxes for training, \n# For COCO, setting USE_ALL_GT to False will exclude boxes that are flagged as ''iscrowd''\n__C.TRAIN.USE_ALL_GT = True\n\n__C.TRAIN.USE_RPN_DB = True\n\n__C.TRAIN.NUM_NEG_RELS = 128\n\n#\n# Testing options\n#\n__C.TEST = edict()\n\n# Scale to use during testing (can NOT list multiple scales)\n# The scale is the pixel size of an image's shortest side\n__C.TEST.SCALES = (600,)\n\n# Max pixel size of the longest side of a scaled input image\n__C.TEST.MAX_SIZE = 1000\n\n# Overlap threshold used for non-maximum suppression (suppress boxes with\n# IoU >= this threshold)\n__C.TEST.NMS = 0.3\n\n# Experimental: treat the (K+1) units in the cls_score layer as linear\n# predictors (trained, eg, with one-vs-rest SVMs).\n__C.TEST.SVM = False\n\n# Test using bounding-box regressors\n__C.TEST.BBOX_REG = True\n\n# Propose boxes\n__C.TEST.HAS_RPN = False\n\n# Test using these proposals\n__C.TEST.PROPOSAL_METHOD = 'gt'\n\n## NMS threshold used on RPN proposals\n__C.TEST.RPN_NMS_THRESH = 0.7\n\n# Number of top scoring boxes to keep before apply NMS to RPN proposals\n__C.TEST.RPN_PRE_NMS_TOP_N = 6000\n\n# Number of top scoring boxes to keep after applying NMS to RPN proposals\n__C.TEST.RPN_POST_NMS_TOP_N = 300\n\n# Proposal height and width both need to be greater than RPN_MIN_SIZE (at orig image scale)\n# __C.TEST.RPN_MIN_SIZE = 16\n\n# Testing mode, default to be 'nms', 'top' is slower but better\n# See report for details\n__C.TEST.MODE = 'nms'\n\n# Only useful when TEST.MODE is 'top', specifies the number of top proposals to select\n__C.TEST.RPN_TOP_N = 5000\n\n#\n# ResNet options\n#\n\n__C.RESNET = edict()\n\n# Option to set if max-pooling is appended after crop_and_resize. \n# if true, the region will be resized to a square of 2xPOOLING_SIZE, \n# then 2x2 max-pooling is applied; otherwise the region will be directly\n# resized to a square of POOLING_SIZE\n__C.RESNET.MAX_POOL = False\n\n# Number of fixed blocks during training, by default the first of all 4 blocks is fixed\n# Range: 0 (none) to 3 (all)\n__C.RESNET.FIXED_BLOCKS = 1\n\n#\n# MobileNet options\n#\n\n__C.MOBILENET = edict()\n\n# Whether to regularize the depth-wise filters during training\n__C.MOBILENET.REGU_DEPTH = False\n\n# Number of fixed layers during training, by default the bottom 5 of 14 layers is fixed\n# Range: 0 (none) to 12 (all)\n__C.MOBILENET.FIXED_LAYERS = 5\n\n# Weight decay for the mobilenet weights\n__C.MOBILENET.WEIGHT_DECAY = 0.00004\n\n# Depth multiplier\n__C.MOBILENET.DEPTH_MULTIPLIER = 1.\n\n#\n# MISC\n#\n\n# Pixel mean values (BGR order) as a (1, 1, 3) array\n# We use the same pixel mean for all networks even though it's not exactly what\n# they were trained with\n__C.PIXEL_MEANS = np.array([[[102.9801, 115.9465, 122.7717]]])\n\n# For reproducibility\n__C.RNG_SEED = 3\n\n# Root directory of project\n__C.ROOT_DIR = osp.abspath(osp.join(osp.dirname(__file__), '..', '..'))\n\n# Data directory\n__C.DATA_DIR = osp.abspath(osp.join(__C.ROOT_DIR, 'data'))\n\n__C.VG_DIR = osp.abspath(osp.join(__C.DATA_DIR, 'vg'))\n\n# Name (or path to) the matlab executable\n__C.MATLAB = 'matlab'\n\n# Place outputs under an experiments directory\n__C.EXP_DIR = 'default'\n\n# Use GPU implementation of non-maximum suppression\n__C.USE_GPU_NMS = True\n\n# Use an end-to-end tensorflow model.\n# Note: models in E2E tensorflow mode have only been tested in feed-forward mode,\n# but these models are exportable to other tensorflow instances as GraphDef files.\n__C.USE_E2E_TF = True\n\n# Default pooling mode, only 'crop' is available\n__C.POOLING_MODE = 'crop'\n\n# Size of the pooled region after RoI pooling\n__C.POOLING_SIZE = 7\n\n# Anchor scales for RPN\n__C.ANCHOR_SCALES = [8, 16, 32]\n\n# Anchor ratios for RPN\n__C.ANCHOR_RATIOS = [0.5, 1, 2]\n\n# Number of filters for the RPN layer\n__C.RPN_CHANNELS = 512\n\n__C.BOX_SCALE = 1024\n\n__C.IMG_SCALE = 1024\n\ncfg.BOTTLE_SCALE = 16.0\n\n# EPS, a small number for numerical issue\n__C.EPS = 1e-14\n\n__C.GROUP_DIST_THRESH = 20.\n\n__C.PUSH_WEIGHT = 0.1\n\n__C.PULL_WEIGHT = 0.1\n\n\ndef get_output_dir(imdb, weights_filename):\n \"\"\"Return the directory where experimental artifacts are placed.\n If the directory does not exist, it is created.\n\n A canonical path is built using the name from an imdb and a network\n (if not None).\n \"\"\"\n outdir = osp.abspath(osp.join(__C.ROOT_DIR, 'output', __C.EXP_DIR, imdb.name))\n if weights_filename is None:\n weights_filename = 'default'\n outdir = osp.join(outdir, weights_filename)\n if not os.path.exists(outdir):\n os.makedirs(outdir)\n return outdir\n\n\ndef get_output_tb_dir(imdb, weights_filename):\n \"\"\"Return the directory where tensorflow summaries are placed.\n If the directory does not exist, it is created.\n\n A canonical path is built using the name from an imdb and a network\n (if not None).\n \"\"\"\n outdir = osp.abspath(osp.join(__C.ROOT_DIR, 'tensorboard', __C.EXP_DIR, imdb.name))\n if weights_filename is None:\n weights_filename = 'default'\n outdir = osp.join(outdir, weights_filename)\n if not os.path.exists(outdir):\n os.makedirs(outdir)\n return outdir\n\n\ndef _merge_a_into_b(a, b):\n \"\"\"Merge config dictionary a into config dictionary b, clobbering the\n options in b whenever they are also specified in a.\n \"\"\"\n if type(a) is not edict:\n return\n\n for k, v in a.items():\n # a must specify keys that are in b\n if k not in b:\n raise KeyError('{} is not a valid config key'.format(k))\n\n # the types must match, too\n old_type = type(b[k])\n if old_type is not type(v):\n if isinstance(b[k], np.ndarray):\n v = np.array(v, dtype=b[k].dtype)\n else:\n raise ValueError(('Type mismatch ({} vs. {}) '\n 'for config key: {}').format(type(b[k]),\n type(v), k))\n\n # recursively merge dicts\n if type(v) is edict:\n try:\n _merge_a_into_b(a[k], b[k])\n except:\n print(('Error under config key: {}'.format(k)))\n raise\n else:\n b[k] = v\n\n\ndef cfg_from_file(filename):\n \"\"\"Load a config file and merge it into the default options.\"\"\"\n import yaml\n with open(filename, 'r') as f:\n yaml_cfg = edict(yaml.load(f))\n\n _merge_a_into_b(yaml_cfg, __C)\n\n\ndef cfg_from_list(cfg_list):\n \"\"\"Set config keys via list (e.g., from command line).\"\"\"\n from ast import literal_eval\n assert len(cfg_list) % 2 == 0\n for k, v in zip(cfg_list[0::2], cfg_list[1::2]):\n key_list = k.split('.')\n d = __C\n for subkey in key_list[:-1]:\n assert subkey in d\n d = d[subkey]\n subkey = key_list[-1]\n assert subkey in d\n try:\n value = literal_eval(v)\n except:\n # handle the case when v is a string literal\n value = v\n assert type(value) == type(d[subkey]), \\\n 'type {} does not match original type {}'.format(\n type(value), type(d[subkey]))\n d[subkey] = value\n",
"# --------------------------------------------------------\n# Fast R-CNN\n# Copyright (c) 2015 Microsoft\n# Licensed under The MIT License [see LICENSE for details]\n# Written by Ross Girshick and Xinlei Chen\n# --------------------------------------------------------\n\n\"\"\"The data layer used during training to train a Fast R-CNN network.\n\nRoIDataLayer implements a Caffe Python layer.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom model.config import cfg\nfrom roi_data_layer.minibatch import get_minibatch\nfrom roi_data_layer.roidb import prepare_roidb, add_bbox_regression_targets\nimport numpy as np\nimport time\n\n\nclass RoIDataLayer(object):\n \"\"\"Fast R-CNN data layer used for training.\"\"\"\n\n def __init__(self, imdb, roidb, bbox_means, bbox_stds, random=False):\n \"\"\"Set the roidb to be used by this layer during training.\"\"\"\n self._imdb = imdb\n self._roidb = roidb\n self._num_classes = imdb.num_classes\n # Also set a random flag\n self._random = random\n self._shuffle_roidb_inds()\n self.bbox_means = bbox_means\n self.bbox_stds = bbox_stds\n\n def _shuffle_roidb_inds(self):\n \"\"\"Randomly permute the training roidb.\"\"\"\n # If the random flag is set,\n # then the database is shuffled according to system time\n # Useful for the validation set\n if self._random:\n st0 = np.random.get_state()\n millis = int(round(time.time() * 1000)) % 4294967295\n np.random.seed(millis)\n\n if cfg.TRAIN.ASPECT_GROUPING:\n widths = np.array([r['width'] for r in self._roidb])\n heights = np.array([r['height'] for r in self._roidb])\n horz = (widths >= heights)\n vert = np.logical_not(horz)\n horz_inds = np.where(horz)[0]\n vert_inds = np.where(vert)[0]\n inds = np.hstack((\n np.random.permutation(horz_inds),\n np.random.permutation(vert_inds)))\n inds = np.reshape(inds, (-1, 2))\n row_perm = np.random.permutation(np.arange(inds.shape[0]))\n inds = np.reshape(inds[row_perm, :], (-1,))\n self._perm = inds\n else:\n self._perm = np.random.permutation(np.arange(len(self._roidb)))\n # Restore the random state\n if self._random:\n np.random.set_state(st0)\n\n self._cur = 0\n\n def _get_next_minibatch_inds(self):\n \"\"\"Return the roidb indices for the next minibatch.\"\"\"\n\n if self._cur + cfg.TRAIN.IMS_PER_BATCH >= len(self._roidb):\n self._shuffle_roidb_inds()\n\n db_inds = self._perm[self._cur:self._cur + cfg.TRAIN.IMS_PER_BATCH]\n self._cur += cfg.TRAIN.IMS_PER_BATCH\n\n return db_inds\n\n def _get_next_minibatch(self):\n \"\"\"Return the blobs to be used for the next minibatch.\n\n If cfg.TRAIN.USE_PREFETCH is True, then blobs will be computed in a\n separate process and made available through self._blob_queue.\n \"\"\"\n db_inds = self._get_next_minibatch_inds()\n minibatch_db = [self._roidb[i] for i in db_inds]\n if cfg.TRAIN.USE_RPN_DB:\n minibatch_db = self._imdb.add_rpn_rois(minibatch_db)\n prepare_roidb(minibatch_db)\n add_bbox_regression_targets(minibatch_db, self.bbox_means, self.bbox_stds)\n return get_minibatch(minibatch_db, self._num_classes)\n\n def forward(self):\n \"\"\"Get blobs and copy them into this layer's top blob vector.\"\"\"\n blobs = self._get_next_minibatch()\n return blobs\n"
] | [
[
"numpy.array"
],
[
"numpy.logical_not",
"numpy.random.get_state",
"numpy.random.seed",
"numpy.reshape",
"numpy.arange",
"numpy.random.set_state",
"numpy.random.permutation",
"numpy.array",
"numpy.where"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Crazy-Jack/RL4GRN | [
"e683e17758eb468bd42e0ea0020e2246051c258c"
] | [
"RL_TD3/src/pe_model.py"
] | [
"'''\n The probabilistic ensemble dynamics model\n'''\n# pylint: disable=C0103, R0902, R0913, W0201, E0401, E1120\nimport time\nimport itertools\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom collections import defaultdict\n\nimport os\nos.environ['KMP_DUPLICATE_LIB_OK']='True'\n\nclass PEModel(keras.Model):\n '''\n An individual Probabilistic Neural Network.\n Multiple Networks with identical structure form the Probabilistic Ensemble.\n Notice that each PEModel network predicts the mean and variance of\n reward, done, delta_state in order.\n Therefore, the output layer has (state_dim + 1 + 1) * 2\n '''\n def __init__(self, state_dim, action_dim):\n super().__init__()\n\n self.l1 = keras.layers.Dense(256, activation=\"relu\")\n self.l2 = keras.layers.Dense(256, activation=\"relu\")\n self.l3 = keras.layers.Dense(256, activation=\"relu\")\n # mean and variance for reward, done, delta_state (in this order)\n # Note: we change done to not_done\n self.l4 = keras.layers.Dense((state_dim + 2) * 2)\n # this step to populate trainable_weights. Without this step,\n # PE.trainable_weights will be empty.\n self.forward(np.zeros((1, state_dim + action_dim)))\n\n def forward(self, net_input):\n '''\n Calls the network on a batch of inputs.\n net_input should have size (batch_size, state_dim+action_dim)\n '''\n out = self.l1(net_input)\n out = self.l2(out)\n out = self.l3(out)\n out = self.l4(out)\n return out\n\nclass PE():\n '''\n The probabilistic ensemble dynamics model class.\n Contains code to initialize, train and then predict with the ensemble.\n You will implement part of this class.\n '''\n def __init__(\n self,\n state_dim,\n action_dim,\n num_networks = 7,\n num_elites = 5,\n learning_rate = 1e-3,\n ):\n self.num_networks = num_networks\n self.num_elites = num_elites\n self.networks = [PEModel(state_dim, action_dim) for i in range(num_networks)]\n self.optimizer = keras.optimizers.Adam(learning_rate=learning_rate)\n self.state_dim = state_dim\n self.action_dim = action_dim\n self.output_dim = state_dim + 2\n # For smoothing the log-variance output\n self.max_logvar = tf.convert_to_tensor(-3 * np.ones([1, self.state_dim + 2]), \\\n dtype=tf.float32)\n self.min_logvar = tf.convert_to_tensor(-7 * np.ones([1, self.state_dim + 2]), \\\n dtype=tf.float32)\n\n self.total_it = 0\n self._model_inds = list(range(self.num_networks)) # for choosing elite models in inference!\n\n def get_output(self, output, ret_logvar=False):\n \"\"\"\n output: tf tensor, shape (batch_size, (state_dim+2) * 2)\n Given network outputs, returns mean and log variance tf tensors if ret_logvar = True.\n mean: shape (batch_size, state_dim + 2)\n logvar: shape (batch_size, state_dim + 2)\n Do not modify\n \"\"\"\n mean = output[:, 0:self.output_dim]\n raw_v = output[:, self.output_dim:]\n # Log variance smoothing\n logvar = self.max_logvar - tf.math.softplus(self.max_logvar - raw_v)\n logvar = self.min_logvar + tf.math.softplus(logvar - self.min_logvar)\n if ret_logvar: # for training\n return mean, logvar\n return mean, tf.math.exp(logvar) # for testing\n\n def _train_loss_one(self, network, train_in, train_targ):\n '''\n Compute the MLE Training Loss for a given Probabilistic Neural Network.\n train_in: tf tensor, shape (batch_size, state_dim + action_dim)\n tarin_targ: tf tensor, shape (batch_size, state_dim + 2), target output\n This function should compute the Gaussian MLE loss, summed across the entire batch.\n\n User note: this contain not done!!\n ''' \n # raise NotImplementedError\n\n pred_mean, pred_var = self.get_output(network.forward(train_in), ret_logvar=True)\n\n train_loss = (pred_mean - train_targ) ** 2 / tf.math.exp(pred_var) + pred_var # [batch_size, state_dim + 2]\n\n train_loss = tf.math.reduce_sum(train_loss)\n\n # regularization step. populate train_loss with correct Gaussian MLE loss\n train_loss += 0.01 * (tf.math.reduce_sum(self.max_logvar) - \\\n tf.math.reduce_sum(self.min_logvar))\n return train_loss\n\n\n def _MSE_loss(self, valid_in, valid_targ, final=False):\n \"\"\"\n Computes the MSE loss for each Probabilistic Neural Network, for validation only.\n valid_in: tf tensor, shape (batch_size, state_dim + action_dim), validation input\n valid_targ: tf tensor, shape (batch_size, state_dim + 2), validation target\n Do not modify.\n \"\"\"\n mse_losses = np.zeros(self.num_networks)\n rew_losses = np.zeros(self.num_networks)\n not_done_losses = np.zeros(self.num_networks)\n dynamics_losses = np.zeros(self.num_networks)\n\n for i, network in enumerate(self.networks):\n mean, _ = self.get_output(network.forward(valid_in), ret_logvar=True)\n if final:\n mse_loss = tf.reduce_mean(((mean - valid_targ) ** 2), 0)\n rew_loss = mse_loss[0]\n not_done_loss = mse_loss[1]\n dynamics_loss = tf.reduce_mean(mse_loss[2:], 0)\n mse_losses[i] = tf.reduce_mean(mse_loss, 0)\n rew_losses[i] = rew_loss\n not_done_losses[i] = not_done_loss\n dynamics_losses[i] = dynamics_loss\n else:\n mse_loss = tf.reduce_mean((mean - valid_targ) ** 2, 0)\n mse_losses[i] = tf.reduce_mean(mse_loss, 0)\n if final:\n return mse_losses, rew_losses, not_done_losses, dynamics_losses\n return mse_losses\n\n def _prepare_dataset(self, buffer):\n '''\n Given a replay buffer containing real environment transitions,\n prepare a dataset for training the PE of neural networks.\n The dataset contains ALL transitions in the replay buffer.\n Do not modify.\n inputs: tf tensor, shape (buffer_size, state_dim + action_dim)\n targets: tf tensor, shape (buffer_size, state_dim + 2)\n '''\n state, action, next_state, reward, not_done = buffer.sample_all() # already shuffled\n\n delta_state = next_state - state\n inputs = tf.concat((state, action), -1)\n targets = tf.concat((reward, not_done, delta_state), -1)\n # Both TF tensors\n return inputs, targets\n\n def _start_train(self, max_epochs_since_update):\n '''\n Setup some internal bookkeeping variables to determine convergence.\n Do not modify.\n '''\n self._snapshots = np.array([1e10 for i in range(self.num_networks)])\n self._epochs_since_update = 0\n self._max_epochs_since_update = max_epochs_since_update\n\n def _end_train(self):\n '''\n Book keeping and console output. Do not modify.\n '''\n sorted_inds = np.argsort(self._snapshots)\n self._model_inds = sorted_inds[:self.num_elites].tolist() # first elite models\n print('Final holdout_losses: ', self._snapshots)\n print('Model MSE', np.mean(self._snapshots[self._model_inds]))\n print('Rew MSE', np.mean(self._reward_mse[self._model_inds]))\n print('Not Done MSE', np.mean(self._not_done_mse[self._model_inds]))\n print('Dyn MSE', np.mean(self._dynamics_mse[self._model_inds]))\n\n def _save_best(self, epoch, holdout_losses):\n '''\n Determines the stopping condition for PE model training.\n The training is determined to have converged if for max_epochs_since_update epochs,\n no network in the ensemble has improved for more than 1%.\n Do not modify.\n '''\n updated = False\n for i in range(len(holdout_losses)):\n current = holdout_losses[i]\n best = self._snapshots[i]\n improvement = (best - current) / best\n if improvement > 0.01: # if decrease over 1%, save\n self._snapshots[i] = current\n #self._save_model(i)\n updated = True\n # improvement = (best - current) / best\n print('epoch {} | updated {} | improvement: {:.4f} | best: {:.4f} | current: {:.4f}'.format(\\\n epoch, i, improvement, best, current))\n\n if updated:\n self._epochs_since_update = 0\n else:\n self._epochs_since_update += 1\n\n if self._epochs_since_update > self._max_epochs_since_update:\n print('[ PE ] Breaking at epoch {}: {} epochs since update ({} max)'.format(epoch,\n self._epochs_since_update, self._max_epochs_since_update))\n return True\n else:\n return False\n\n\n def train(self, buffer, batch_size=256, holdout_ratio=0.2, max_logging=5000,\n max_grad_updates=None, max_t=None, max_epochs_since_update=5):\n '''\n For model training, uses all transitions in real buffer, and train to convergence\n in valid set. You will implement part of this training function.\n '''\n self._start_train(max_epochs_since_update)\n inputs, targets = self._prepare_dataset(buffer)\n\n # Split into training and holdout sets\n num_holdout = min(int(inputs.shape[0] * holdout_ratio), max_logging)\n inputs, holdout_inputs = inputs[num_holdout:], inputs[:num_holdout]\n targets, holdout_targets = targets[num_holdout:], targets[:num_holdout]\n\n print('[ Euler PE ] Training {} | Target {} | Holdout: {}'.format(inputs.shape, targets.shape,\n holdout_inputs.shape))\n\n idxs = tf.convert_to_tensor(np.random.randint(inputs.shape[0], size=(inputs.shape[0],)))\n num_batch = int(np.ceil(idxs.shape[-1] / batch_size))\n\n # global counter\n t0 = time.time()\n grad_updates = 0\n\n for epoch in itertools.count(): # infinite loop\n for batch_num in range(num_batch):\n batch_idxs = idxs[batch_num * batch_size:(batch_num + 1) * batch_size]\n # (N, <=B): will include the remainder batch even if out of bounds!\n train_in = tf.gather(inputs, batch_idxs)\n train_targ = tf.gather(targets, batch_idxs)\n \n # For each network, get loss, compute gradient of loss\n # And apply optimizer step.\n # raise NotImplementedError\n\n for network in self.networks:\n with tf.GradientTape() as tape:\n train_loss = self._train_loss_one(network, train_in, train_targ)\n \n network_grad = tape.gradient(train_loss, network.trainable_variables)\n self.optimizer.apply_gradients(zip(network_grad, network.trainable_variables))\n \n grad_updates += 1\n\n idxs = tf.random.shuffle(idxs) # shuffle its dataset for each model\n\n # validate each model using same valid set\n holdout_losses = self._MSE_loss(holdout_inputs, holdout_targets) # (N,)\n break_train = self._save_best(epoch, holdout_losses)\n print(\"[ PE ] holdout_losses: \", f\"Epoch {epoch}\", holdout_losses) # write to log.txt\n\n t = time.time() - t0\n if break_train or (max_grad_updates and grad_updates > max_grad_updates):\n break\n\n if max_t and t > max_t:\n print('Breaking because of timeout: {}! (max: {})'.format(t, max_t))\n break\n\n self._snapshots, self._reward_mse, self._not_done_mse, self._dynamics_mse \\\n = self._MSE_loss(holdout_inputs, holdout_targets, final=True)\n\n self._end_train()\n print(f\"End of Model training {epoch} epochs and time {t:.0f}s\")\n print('Model training epoch', epoch)\n print('Model training time', int(t))\n return grad_updates\n\n ### Rollout / Inference Code\n\n def _prepare_input(self, state, action):\n '''\n Prepares inputs for inference.\n state: tf tensor, size (batch_size, state_dim) or (state_dim, )\n action: tf tensor, size (batch_size, action_dim) or (action_dim, )\n inputs: tf tensor, size (batch_size, state_dim + action_dim)\n Do not modify.\n '''\n if state.ndim == 1:\n state = tf.expand_dims(state, 0)\n if action.ndim == 1:\n action = tf.expand_dims(action, 0) \\\n if action.shape[0] == self.action_dim else tf.expand_dims(action, 1)\n inputs = tf.concat((state, action), -1)\n assert inputs.ndim == 2\n return inputs\n\n def _random_inds(self, batch_size):\n '''\n Uniformly randomly pick one *elite* model for each (state, action) in batch.\n This may help you implement predict.\n '''\n inds = np.random.choice(self._model_inds, size=batch_size)\n return inds\n\n def predict(self, state, action, deterministic=False):\n '''\n Predicts next states, rewards and not_done using the probabilistic ensemble\n For each (state, action) pair, pick a elite model uniformly at random, then\n use that elite model to predict next state, reward and not_done. The model\n can de different for each sample in the batch.\n If deterministic=True, then the prediction should simply be the predicted mean.\n If deterministic=False, then the prediction should be sampled from N(mean, var),\n where mean is the predicted mean and var is the predicted variance.\n state: tf tensor, shape (batch_size, state_dim) or (state_dim, )\n action: tf tensor, shape (batch_size, action_dim) or (action_dim, )\n samples (return value): np array, shape (batch_size, state_dim+2)\n samples[:, 0] should be the rewards, samples[:, 1] should be the not-done signals,\n and samples[:, 2:] should be the next states.\n '''\n inputs = self._prepare_input(state, action)\n\n # raise NotImplementedError\n batch_size = state.shape[0] if len(state.shape) > 1 else 1\n inds = self._random_inds(batch_size) # get random idx\n\n # group idx by network number -> network_number: list(random idx)\n network_2_batch_mapping = defaultdict(list)\n for batch_number, model_idx in enumerate(inds):\n network_2_batch_mapping[model_idx].append(batch_number)\n\n # model forward (for loop by network)\n samples = [0] * batch_size\n for model_idx, batch_numbers in network_2_batch_mapping.items():\n model_inputs = tf.gather_nd(inputs, [[i] for i in batch_numbers])\n pred_mean, pred_var = self.get_output(self.networks[model_idx].forward(model_inputs), ret_logvar=False)\n\n zeros_padding = tf.zeros([len(batch_numbers), 2])\n cur_state = tf.concat([zeros_padding, tf.gather_nd(state, [[i] for i in batch_numbers])], 1)\n pred_mean = pred_mean + cur_state\n\n if deterministic == True:\n for idx, bi in enumerate(batch_numbers):\n samples[bi] = pred_mean[idx, :]\n else:\n for idx, bi in enumerate(batch_numbers):\n samples[bi] = tf.random.normal(shape = (1, self.state_dim + 2), mean = pred_mean[idx,:], stddev = tf.sqrt(pred_var[idx,:]))\n\n samples = tf.squeeze(tf.convert_to_tensor(samples), 1)\n\n # zeros_padding = tf.zeros([batch_size, 2])\n # padded_state_only = tf.concat([zeros_padding, state], 1)\n\n # samples += padded_state_only\n return samples\n\n\n# Sanity Check to test your PE model implementation.\nif __name__ == '__main__':\n import pybullet_envs\n import gym\n import utils\n\n env = gym.make(\"InvertedPendulumBulletEnv-v0\")\n state_size = env.observation_space.shape[0]\n action_size = env.action_space.shape[0]\n replay_buffer = utils.ReplayBuffer(state_size, action_size, max_size=int(1e6))\n\n o = env.reset()\n total_steps = 25000 # one episode has 1000 steps\n step = 0\n while step < total_steps:\n a = env.action_space.sample()\n o2, r, d, info = env.step(a)\n step += 1\n replay_buffer.add(o, a, o2, r, float(d))\n o = o2\n if d:\n o = env.reset()\n\n model = PE(state_size, action_size)\n model.train(replay_buffer)\n"
] | [
[
"tensorflow.convert_to_tensor",
"tensorflow.concat",
"numpy.mean",
"numpy.random.randint",
"tensorflow.math.softplus",
"numpy.ceil",
"tensorflow.math.reduce_sum",
"tensorflow.gather",
"numpy.zeros",
"tensorflow.gather_nd",
"numpy.random.choice",
"tensorflow.keras.layers.Dense",
"tensorflow.math.exp",
"tensorflow.random.shuffle",
"numpy.argsort",
"tensorflow.GradientTape",
"tensorflow.reduce_mean",
"tensorflow.expand_dims",
"numpy.ones",
"tensorflow.keras.optimizers.Adam",
"tensorflow.sqrt"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
162/catalyst | [
"b4ba36be52c51160e0fabecdcb084a8d5cd96cb7",
"b4ba36be52c51160e0fabecdcb084a8d5cd96cb7"
] | [
"catalyst/dl/utils/trace.py",
"catalyst/data/reader.py"
] | [
"from typing import Type\n\nimport torch\nfrom torch import nn\nfrom torch.jit import ScriptModule\n\nfrom catalyst.dl.core import Experiment, Runner\n\n\nclass _ForwardOverrideModel(nn.Module):\n \"\"\"\n Model that calls specified method instead of forward\n\n (Workaround, single method tracing is not supported)\n \"\"\"\n\n def __init__(self, model, method_name):\n super().__init__()\n self.model = model\n self.method = method_name\n\n def forward(self, *args, **kwargs):\n return getattr(self.model, self.method)(*args, **kwargs)\n\n\nclass _TracingModelWrapper(nn.Module):\n \"\"\"\n Wrapper that traces model with batch instead of calling it\n\n (Workaround, to use native model batch handler)\n \"\"\"\n\n def __init__(self, model, method_name):\n super().__init__()\n self.method_name = method_name\n self.model = model\n self.tracing_result: ScriptModule\n\n def __call__(self, *args, **kwargs):\n method_model = _ForwardOverrideModel(\n self.model, self.method_name\n )\n\n self.tracing_result = \\\n torch.jit.trace(\n method_model,\n *args, **kwargs\n )\n\n\ndef _get_native_batch(\n experiment: Experiment, stage: str\n):\n \"\"\"Returns dataset from first loader provided by experiment\"\"\"\n loaders = experiment.get_loaders(stage)\n assert loaders, \\\n \"Experiment must have at least one loader to support tracing\"\n # Take first loader\n loader = next(iter(loaders.values()))\n dataset = loader.dataset\n collate_fn = loader.collate_fn\n\n sample = collate_fn([dataset[0]])\n\n return sample\n\n\ndef trace_model(\n model: nn.Module,\n experiment: Experiment,\n runner_type: Type[Runner],\n method_name: str = \"forward\"\n) -> ScriptModule:\n \"\"\"\n Traces model using it's native experiment and runner.\n\n Args:\n model: Model to trace\n NOTICE: will be switched to eval and\n requires_grad=False will be set on all params\n experiment: Native experiment that was used to train model\n runner_type: Model's native runner that was used to train model\n method_name: Model's method name that will be\n used as entrypoint during tracing\n\n Returns:\n Traced model ScriptModule\n \"\"\"\n stage = list(experiment.stages)[0]\n\n model.eval()\n for p in model.parameters():\n p.requires_grad_(False)\n\n tracer = _TracingModelWrapper(model, method_name)\n runner: Runner = runner_type(tracer.cpu(), torch.device(\"cpu\"))\n\n batch = _get_native_batch(experiment, stage)\n batch = runner._batch2device(batch, device=runner.device)\n\n runner.predict_batch(batch)\n\n return tracer.tracing_result\n\n\n__all__ = [\"trace_model\"]\n",
"import functools\nfrom typing import Callable, Type, List\n\nimport numpy as np\nfrom catalyst.utils.image import imread\n\n\nclass ReaderSpec:\n \"\"\"Reader abstraction for all Readers. Applies a function\n to an element of your data.\n For example to a row from csv, or to an image, etc.\n\n All inherited classes have to implement `__call__`.\n \"\"\"\n\n def __init__(self, input_key: str, output_key: str):\n \"\"\"\n Args:\n input_key (str): input key to use from annotation dict\n output_key (str): output key to use to store the result\n \"\"\"\n self.input_key = input_key\n self.output_key = output_key\n\n def __call__(self, row):\n \"\"\"Reads a row from your annotations dict and\n transfer it to data, needed by your network\n for example open image by path, or read string and tokenize it.\n\n Args:\n row: elem in your dataset.\n\n Returns:\n Data object used for your neural network\n \"\"\"\n raise NotImplementedError(\n \"You cannot apply a transformation using `BaseReader`\"\n )\n\n\nclass ImageReader(ReaderSpec):\n \"\"\"\n Image reader abstraction. Reads images from a `csv` dataset.\n \"\"\"\n\n def __init__(\n self,\n input_key: str,\n output_key: str,\n datapath: str = None,\n grayscale: bool = False\n ):\n \"\"\"\n Args:\n input_key (str): key to use from annotation dict\n output_key (str): key to use to store the result\n datapath (str): path to images dataset\n (so your can use relative paths in annotations)\n grayscale (bool): flag if you need to work only\n with grayscale images\n \"\"\"\n super().__init__(input_key, output_key)\n self.datapath = datapath\n self.grayscale = grayscale\n\n def __call__(self, row):\n \"\"\"Reads a row from your annotations dict with filename and\n transfer it to an image\n\n Args:\n row: elem in your dataset.\n\n Returns:\n np.ndarray: Image\n \"\"\"\n image_name = str(row[self.input_key])\n img = imread(\n image_name, rootpath=self.datapath, grayscale=self.grayscale\n )\n\n result = {self.output_key: img}\n return result\n\n\nclass ScalarReader(ReaderSpec):\n \"\"\"\n Numeric data reader abstraction.\n Reads a single float, int, str or other from data\n \"\"\"\n\n def __init__(\n self,\n input_key: str,\n output_key: str,\n dtype: Type = np.float32,\n default_value: float = None,\n one_hot_classes: int = None\n ):\n \"\"\"\n Args:\n input_key (str): input key to use from annotation dict\n output_key (str): output key to use to store the result\n dtype (type): datatype of scalar values to use\n default_value: default value to use if something goes wrong\n one_hot_classes (int): number of one-hot classes\n \"\"\"\n super().__init__(input_key, output_key)\n self.dtype = dtype\n self.default_value = default_value\n self.one_hot_classes = one_hot_classes\n\n def __call__(self, row):\n \"\"\"Reads a row from your annotations dict with filename and\n transfer it to a single value\n\n Args:\n row: elem in your dataset.\n\n Returns:\n dtype: Scalar value\n \"\"\"\n scalar = self.dtype(row.get(self.input_key, self.default_value))\n if self.one_hot_classes is not None \\\n and scalar is not None and scalar >= 0:\n one_hot = np.zeros(self.one_hot_classes, dtype=np.float32)\n one_hot[scalar] = 1.0\n scalar = one_hot\n result = {self.output_key: scalar}\n return result\n\n\nclass LambdaReader(ReaderSpec):\n \"\"\"\n Reader abstraction with an lambda encoder.\n Can read an elem from dataset and apply `encode_fn` function to it\n \"\"\"\n\n def __init__(\n self,\n input_key: str,\n output_key: str,\n encode_fn: Callable = lambda x: x,\n **kwargs\n ):\n \"\"\"\n Args:\n input_key (str): input key to use from annotation dict\n output_key (str): output key to use to store the result\n encode_fn (callable): encode function to use to prepare your data\n (for example convert chars/words/tokens to indices, etc)\n kwargs: kwargs for encode function\n \"\"\"\n super().__init__(input_key, output_key)\n self.encode_fn = functools.partial(encode_fn, **kwargs)\n\n def __call__(self, row):\n \"\"\"Reads a row from your annotations dict\n and applies `encode_fn` function\n\n Args:\n row: elem in your dataset.\n\n Returns:\n Value after applying `encode_fn` function\n \"\"\"\n elem = row[self.input_key]\n elem = self.encode_fn(elem)\n result = {self.output_key: elem}\n return result\n\n\nclass ReaderCompose(object):\n \"\"\"\n Abstraction to compose several readers into one open function.\n \"\"\"\n\n def __init__(self, readers: List[ReaderSpec], mixins: [] = None):\n \"\"\"\n Args:\n readers (List[ReaderSpec]): list of reader to compose\n mixins: list of mixins to use\n \"\"\"\n self.readers = readers\n self.mixins = mixins or []\n\n def __call__(self, row):\n \"\"\"Reads a row from your annotations dict\n and applies all readers and mixins\n\n Args:\n row: elem in your dataset.\n\n Returns:\n Value after applying all readers and mixins\n \"\"\"\n result = {}\n for fn in self.readers:\n result = {**result, **fn(row)}\n for fn in self.mixins:\n result = {**result, **fn(result)}\n return result\n\n\n__all__ = [\n \"ReaderSpec\", \"ImageReader\", \"ScalarReader\", \"LambdaReader\",\n \"ReaderCompose\"\n]\n"
] | [
[
"torch.device",
"torch.jit.trace"
],
[
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Diva-Pant/tensorflow | [
"f926d8c10efb07176ae559d0e098cdfdb4d03219",
"f926d8c10efb07176ae559d0e098cdfdb4d03219",
"f926d8c10efb07176ae559d0e098cdfdb4d03219"
] | [
"tensorflow/python/distribute/multi_process_runner_test.py",
"tensorflow/python/ops/special_math_ops.py",
"tensorflow/python/keras/layers/preprocessing/category_encoding_test.py"
] | [
"# 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\"\"\"Tests for `multi_process_runner`.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport json\nimport os\nimport threading\nimport time\nfrom absl import logging\n\nfrom tensorflow.python.distribute import multi_process_runner\nfrom tensorflow.python.distribute import multi_worker_test_base\nfrom tensorflow.python.eager import test\n\n\ndef proc_func_that_adds_task_type_in_return_data():\n return multi_worker_test_base.get_task_type()\n\n\ndef proc_func_that_errors():\n raise ValueError('This is an error.')\n\n\ndef proc_func_that_does_nothing():\n pass\n\n\ndef proc_func_that_adds_simple_return_data():\n return 'dummy_data'\n\n\ndef proc_func_that_return_args_and_kwargs(*args, **kwargs):\n return list(args) + list(kwargs.items())\n\n\ndef proc_func_with_barrier():\n return multi_process_runner.barrier()\n\n\nclass MultiProcessRunnerTest(test.TestCase):\n\n def _worker_idx(self):\n config_task = json.loads(os.environ['TF_CONFIG'])['task']\n return config_task['index']\n\n def test_multi_process_runner(self):\n mpr_result = multi_process_runner.run(\n proc_func_that_adds_task_type_in_return_data,\n multi_worker_test_base.create_cluster_spec(\n num_workers=2, num_ps=3, has_eval=1))\n\n job_count_dict = {'worker': 2, 'ps': 3, 'evaluator': 1}\n for data in mpr_result.return_value:\n job_count_dict[data] -= 1\n\n self.assertEqual(job_count_dict['worker'], 0)\n self.assertEqual(job_count_dict['ps'], 0)\n self.assertEqual(job_count_dict['evaluator'], 0)\n\n def test_multi_process_runner_error_propagates_from_subprocesses(self):\n runner = multi_process_runner.MultiProcessRunner(\n proc_func_that_errors,\n multi_worker_test_base.create_cluster_spec(num_workers=1, num_ps=1),\n max_run_time=20)\n runner.start()\n with self.assertRaisesRegexp(ValueError, 'This is an error.'):\n runner.join()\n\n def test_multi_process_runner_queue_emptied_between_runs(self):\n cluster_spec = multi_worker_test_base.create_cluster_spec(num_workers=2)\n return_value = multi_process_runner.run(\n proc_func_that_adds_simple_return_data, cluster_spec).return_value\n self.assertTrue(return_value)\n self.assertEqual(return_value[0], 'dummy_data')\n self.assertEqual(return_value[1], 'dummy_data')\n return_value = multi_process_runner.run(proc_func_that_does_nothing,\n cluster_spec).return_value\n self.assertFalse(return_value)\n\n def test_multi_process_runner_args_passed_correctly(self):\n return_value = multi_process_runner.run(\n proc_func_that_return_args_and_kwargs,\n multi_worker_test_base.create_cluster_spec(num_workers=1),\n args=('a', 'b'),\n kwargs={\n 'c_k': 'c_v'\n }).return_value\n self.assertEqual(return_value[0][0], 'a')\n self.assertEqual(return_value[0][1], 'b')\n self.assertEqual(return_value[0][2], ('c_k', 'c_v'))\n\n def test_stdout_captured(self):\n\n def simple_print_func():\n print('This is something printed.', flush=True)\n return 'This is returned data.'\n\n mpr_result = multi_process_runner.run(\n simple_print_func,\n multi_worker_test_base.create_cluster_spec(num_workers=2),\n list_stdout=True)\n std_stream_results = mpr_result.stdout\n return_value = mpr_result.return_value\n self.assertIn('[worker-0]: This is something printed.\\n',\n std_stream_results)\n self.assertIn('[worker-1]: This is something printed.\\n',\n std_stream_results)\n self.assertIn('This is returned data.', return_value)\n\n def test_process_that_exits(self):\n\n def func_to_exit_in_25_sec():\n logging.error('foo')\n time.sleep(100)\n logging.error('bar')\n\n mpr = multi_process_runner.MultiProcessRunner(\n func_to_exit_in_25_sec,\n multi_worker_test_base.create_cluster_spec(num_workers=1),\n list_stdout=True,\n max_run_time=25)\n\n mpr.start()\n stdout = mpr.join().stdout\n self.assertLen([msg for msg in stdout if 'foo' in msg], 1)\n self.assertLen([msg for msg in stdout if 'bar' in msg], 0)\n\n def test_termination(self):\n\n def proc_func():\n for i in range(0, 10):\n print(\n 'index {}, iteration {}'.format(self._worker_idx(), i), flush=True)\n time.sleep(5)\n\n mpr = multi_process_runner.MultiProcessRunner(\n proc_func,\n multi_worker_test_base.create_cluster_spec(num_workers=2),\n list_stdout=True)\n mpr.start()\n time.sleep(5)\n mpr.terminate('worker', 0)\n std_stream_results = mpr.join().stdout\n\n # Worker 0 is terminated in the middle, so it should not have iteration 9\n # printed.\n self.assertIn('[worker-0]: index 0, iteration 0\\n', std_stream_results)\n self.assertNotIn('[worker-0]: index 0, iteration 9\\n',\n std_stream_results)\n self.assertIn('[worker-1]: index 1, iteration 0\\n', std_stream_results)\n self.assertIn('[worker-1]: index 1, iteration 9\\n', std_stream_results)\n\n def test_termination_and_start_single_process(self):\n\n def proc_func():\n for i in range(0, 10):\n print(\n 'index {}, iteration {}'.format(self._worker_idx(), i), flush=True)\n time.sleep(1)\n\n mpr = multi_process_runner.MultiProcessRunner(\n proc_func,\n multi_worker_test_base.create_cluster_spec(num_workers=2),\n list_stdout=True)\n mpr.start()\n time.sleep(3)\n mpr.terminate('worker', 0)\n mpr.start_single_process('worker', 0)\n std_stream_results = mpr.join().stdout\n\n # Worker 0 is terminated in the middle, but a new worker 0 is added, so it\n # should still have iteration 9 printed. Moreover, iteration 0 of worker 0\n # should happen twice.\n self.assertLen(\n [s for s in std_stream_results if 'index 0, iteration 0' in s], 2)\n self.assertIn('[worker-0]: index 0, iteration 9\\n', std_stream_results)\n self.assertIn('[worker-1]: index 1, iteration 0\\n', std_stream_results)\n self.assertIn('[worker-1]: index 1, iteration 9\\n', std_stream_results)\n\n def test_streaming(self):\n\n def proc_func():\n for i in range(5):\n logging.info('(logging) %s-%d, i: %d',\n multi_worker_test_base.get_task_type(), self._worker_idx(),\n i)\n print(\n '(print) {}-{}, i: {}'.format(\n multi_worker_test_base.get_task_type(), self._worker_idx(), i),\n flush=True)\n time.sleep(1)\n\n mpr = multi_process_runner.MultiProcessRunner(\n proc_func,\n multi_worker_test_base.create_cluster_spec(\n has_chief=True, num_workers=2, num_ps=2, has_eval=True),\n list_stdout=True)\n mpr._dependence_on_chief = False\n\n mpr.start()\n mpr.start_single_process('worker', 2)\n mpr.start_single_process('ps', 2)\n mpr_result = mpr.join()\n\n list_to_assert = mpr_result.stdout\n\n for job in ['chief', 'evaluator']:\n for iteration in range(5):\n self.assertTrue(\n any('(logging) {}-0, i: {}'.format(job, iteration) in line\n for line in list_to_assert))\n self.assertTrue(\n any('(print) {}-0, i: {}'.format(job, iteration) in line\n for line in list_to_assert))\n\n for job in ['worker', 'ps']:\n for iteration in range(5):\n for task in range(3):\n self.assertTrue(\n any('(logging) {}-{}, i: {}'.format(job, task, iteration) in line\n for line in list_to_assert))\n self.assertTrue(\n any('(print) {}-{}, i: {}'.format(job, task, iteration) in line\n for line in list_to_assert))\n task = 3\n self.assertFalse(\n any('(logging) {}-{}, i: {}'.format(job, task, iteration) in line\n for line in list_to_assert))\n self.assertFalse(\n any('(print) {}-{}, i: {}'.format(job, task, iteration) in line\n for line in list_to_assert))\n\n def test_start_in_process_as(self):\n\n def proc_func():\n for i in range(5):\n logging.info('%s-%d, i: %d', multi_worker_test_base.get_task_type(),\n self._worker_idx(), i)\n time.sleep(1)\n\n mpr = multi_process_runner.MultiProcessRunner(\n proc_func,\n multi_worker_test_base.create_cluster_spec(\n has_chief=True, num_workers=1),\n list_stdout=True)\n\n def eval_func():\n time.sleep(1)\n mpr.start_single_process(task_type='evaluator', task_id=0)\n\n eval_thread = threading.Thread(target=eval_func)\n eval_thread.start()\n mpr.start_in_process_as(as_task_type='chief', as_task_id=0)\n eval_thread.join()\n list_to_assert = mpr.join().stdout\n for job in ['worker', 'evaluator']:\n for iteration in range(5):\n self.assertTrue(\n any('{}-0, i: {}'.format(job, iteration) in line\n for line in list_to_assert))\n\n def test_terminate_all_does_not_ignore_error(self):\n mpr = multi_process_runner.MultiProcessRunner(\n proc_func_that_errors,\n multi_worker_test_base.create_cluster_spec(num_workers=2),\n list_stdout=True)\n mpr.start()\n time.sleep(60)\n mpr.terminate_all()\n with self.assertRaisesRegexp(ValueError, 'This is an error.'):\n mpr.join()\n\n def test_barrier(self):\n multi_process_runner.run(\n proc_func_with_barrier,\n cluster_spec=multi_worker_test_base.create_cluster_spec(\n has_chief=True, num_workers=1),\n )\n\n def test_barrier_called_in_main_process(self):\n with self.assertRaises(ValueError):\n multi_process_runner.barrier()\n\n def test_stdout_available_when_timeout(self):\n\n def proc_func():\n for i in range(50):\n logging.info('(logging) %s-%d, i: %d',\n multi_worker_test_base.get_task_type(), self._worker_idx(),\n i)\n time.sleep(1)\n\n with self.assertRaises(multi_process_runner.SubprocessTimeoutError) as cm:\n multi_process_runner.run(\n proc_func,\n multi_worker_test_base.create_cluster_spec(num_workers=1, num_ps=1),\n list_stdout=True,\n timeout=5)\n\n list_to_assert = cm.exception.mpr_result.stdout\n for job in ['worker', 'ps']:\n for iteration in range(0, 5):\n self.assertTrue(\n any('(logging) {}-0, i: {}'.format(job, iteration) in line\n for line in list_to_assert))\n\n\nif __name__ == '__main__':\n multi_process_runner.test_main()\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\"\"\"Arithmetic Operations that don't fit into math_ops due to dependencies.\n\nTo avoid circular dependencies, some math_ops should go here.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport functools\nimport re\nimport string\n\nimport numpy as np\nimport opt_einsum\nimport six\n\nfrom six.moves import xrange # pylint: disable=redefined-builtin\n\nfrom tensorflow.compiler.tf2xla.ops import gen_xla_ops\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 control_flow_ops\nfrom tensorflow.python.ops import gen_linalg_ops\nfrom tensorflow.python.ops import gen_special_math_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.util import deprecation\nfrom tensorflow.python.util import dispatch\nfrom tensorflow.python.util.tf_export import tf_export\n\n\n# TODO(b/27419586) Change docstring for required dtype of x once int allowed\n@tf_export('math.lbeta', v1=['math.lbeta', 'lbeta'])\[email protected]_dispatch_support\[email protected]_endpoints('lbeta')\ndef lbeta(x, name=None):\n r\"\"\"Computes \\\\(ln(|Beta(x)|)\\\\), reducing along the last dimension.\n\n Given one-dimensional $z = [z_1,...,z_K]$, we define\n\n $$Beta(z) = \\frac{\\prod_j \\Gamma(z_j)}{\\Gamma(\\sum_j z_j)},$$\n\n where $\\Gamma$ is the gamma function.\n\n And for $n + 1$ dimensional $x$ with shape $[N_1, ..., N_n, K]$, we define\n\n $$lbeta(x)[i_1, ..., i_n] = \\log{|Beta(x[i_1, ..., i_n, :])|}.$$\n\n In other words, the last dimension is treated as the $z$ vector.\n\n Note that if $z = [u, v]$, then\n\n $$Beta(z) = \\frac{\\Gamma(u)\\Gamma(v)}{\\Gamma(u + v)}\n = \\int_0^1 t^{u-1} (1 - t)^{v-1} \\mathrm{d}t,$$\n\n which defines the traditional bivariate beta function.\n\n If the last dimension is empty, we follow the convention that the sum over\n the empty set is zero, and the product is one.\n\n Args:\n x: A rank `n + 1` `Tensor`, `n >= 0` with type `float`, or `double`.\n name: A name for the operation (optional).\n\n Returns:\n The logarithm of \\\\(|Beta(x)|\\\\) reducing along the last dimension.\n \"\"\"\n # In the event that the last dimension has zero entries, we return -inf.\n # This is consistent with a convention that the sum over the empty set 0, and\n # the product is 1.\n # This is standard. See https://en.wikipedia.org/wiki/Empty_set.\n with ops.name_scope(name, 'lbeta', [x]):\n x = ops.convert_to_tensor(x, name='x')\n\n # Note reduce_sum([]) = 0.\n log_prod_gamma_x = math_ops.reduce_sum(math_ops.lgamma(x), axis=[-1])\n\n # Note lgamma(0) = infinity, so if x = []\n # log_gamma_sum_x = lgamma(0) = infinity, and\n # log_prod_gamma_x = lgamma(1) = 0,\n # so result = -infinity\n sum_x = math_ops.reduce_sum(x, axis=[-1])\n log_gamma_sum_x = math_ops.lgamma(sum_x)\n result = log_prod_gamma_x - log_gamma_sum_x\n\n return result\n\n\n@tf_export('math.special.dawsn')\[email protected]_dispatch_support\ndef dawsn(x, name=None):\n \"\"\"Computes Dawson's integral of `x` element-wise.\n\n Dawson's integral is defined as `exp(-x**2)` times the integral of\n `exp(t**2)` from `0` to `x`, with the domain of definition all real numbers.\n\n Dawson's function is odd.\n >>> tf.math.special.dawsn([-1., -0.5, 0.5, 1.]).numpy()\n array([-0.5380795, -0.4244364, 0.4244364, 0.5380795], dtype=float32)\n\n This implementation is based off of the Cephes math library.\n\n Args:\n x: A `Tensor` or `SparseTensor`. Must be one of the following types:\n `float32`, `float64`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` or `SparseTensor`, respectively. Has the same type as `x`.\n\n @compatibility(scipy)\n Equivalent to scipy.special.dawsn\n @end_compatibility\n \"\"\"\n with ops.name_scope(name, 'dawsn', [x]):\n return gen_special_math_ops.dawsn(x)\n\n\n@tf_export('math.special.expint')\[email protected]_dispatch_support\ndef expint(x, name=None):\n \"\"\"Computes the Exponential integral of `x` element-wise.\n\n The Exponential integral is defined as the integral of `exp(t) / t` from\n `-inf` to `x`, with the domain of definition all positive real numbers.\n\n >>> tf.math.special.expint([1., 1.1, 2.1, 4.1]).numpy()\n array([ 1.8951179, 2.1673784, 5.3332353, 21.048464], dtype=float32)\n\n This implementation is based off of the Cephes math library.\n\n Args:\n x: A `Tensor` or `SparseTensor`. Must be one of the following types:\n `float32`, `float64`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` or `SparseTensor`, respectively. Has the same type as `x`.\n\n @compatibility(scipy)\n Equivalent to scipy.special.expi\n @end_compatibility\n \"\"\"\n with ops.name_scope(name, 'expint', [x]):\n return gen_special_math_ops.expint(x)\n\n\n@tf_export('math.special.fresnel_cos')\[email protected]_dispatch_support\ndef fresnel_cos(x, name=None):\n \"\"\"Computes Fresnel's cosine integral of `x` element-wise.\n\n The Fresnel cosine integral is defined as the integral of `cos(t^2)` from\n `0` to `x`, with the domain of definition all real numbers.\n\n The Fresnel cosine integral is odd.\n >>> tf.math.special.fresnel_cos([-1., -0.1, 0.1, 1.]).numpy()\n array([-0.7798934 , -0.09999753, 0.09999753, 0.7798934 ], dtype=float32)\n\n This implementation is based off of the Cephes math library.\n\n Args:\n x: A `Tensor` or `SparseTensor`. Must be one of the following types:\n `float32`, `float64`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` or `SparseTensor`, respectively. Has the same type as `x`.\n\n @compatibility(scipy)\n Equivalent to scipy.special.fresnel second output.\n @end_compatibility\n \"\"\"\n with ops.name_scope(name, 'fresnel_cos', [x]):\n return gen_special_math_ops.fresnel_cos(x)\n\n\n@tf_export('math.special.fresnel_sin')\[email protected]_dispatch_support\ndef fresnel_sin(x, name=None):\n \"\"\"Computes Fresnel's sine integral of `x` element-wise.\n\n The Fresnel sine integral is defined as the integral of `sin(t^2)` from\n `0` to `x`, with the domain of definition all real numbers.\n\n >>> tf.math.special.fresnel_sin([-1., -0.1, 0.1, 1.]).numpy()\n array([-0.43825912, -0.00052359, 0.00052359, 0.43825912], dtype=float32)\n\n This implementation is based off of the Cephes math library.\n\n Args:\n x: A `Tensor` or `SparseTensor`. Must be one of the following types:\n `float32`, `float64`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` or `SparseTensor`, respectively. Has the same type as `x`.\n\n @compatibility(scipy)\n Equivalent to scipy.special.fresnel first output.\n @end_compatibility\n \"\"\"\n with ops.name_scope(name, 'fresnel_sin', [x]):\n return gen_special_math_ops.fresnel_sin(x)\n\n\n@tf_export('math.special.spence')\[email protected]_dispatch_support\ndef spence(x, name=None):\n \"\"\"Computes Spence's integral of `x` element-wise.\n\n Spence's integral is defined as the integral of `log(t) / (1 - t)` from\n `1` to `x`, with the domain of definition all non-negative real numbers.\n\n >>> tf.math.special.spence([0.5, 1., 2., 3.]).numpy()\n array([ 0.58224034, 0. , -0.82246685, -1.4367464], dtype=float32)\n\n This implementation is based off of the Cephes math library.\n\n Args:\n x: A `Tensor` or `SparseTensor`. Must be one of the following types:\n `float32`, `float64`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` or `SparseTensor`, respectively. Has the same type as `x`.\n\n @compatibility(scipy)\n Equivalent to scipy.special.spence\n @end_compatibility\n \"\"\"\n with ops.name_scope(name, 'spence', [x]):\n return gen_special_math_ops.spence(x)\n\n\n@tf_export('math.bessel_i0')\[email protected]_dispatch_support\ndef bessel_i0(x, name=None):\n \"\"\"Computes the Bessel i0 function of `x` element-wise.\n\n Modified Bessel function of order 0.\n\n It is preferable to use the numerically stabler function `i0e(x)` instead.\n\n Args:\n x: A `Tensor` or `SparseTensor`. Must be one of the following types: `half`,\n `float32`, `float64`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` or `SparseTensor`, respectively. Has the same type as `x`.\n\n @compatibility(scipy)\n Equivalent to scipy.special.i0\n @end_compatibility\n \"\"\"\n with ops.name_scope(name, 'bessel_i0', [x]):\n return math_ops.exp(math_ops.abs(x)) * math_ops.bessel_i0e(x)\n\n\n@tf_export('math.bessel_i1')\[email protected]_dispatch_support\ndef bessel_i1(x, name=None):\n \"\"\"Computes the Bessel i1 function of `x` element-wise.\n\n Modified Bessel function of order 1.\n\n It is preferable to use the numerically stabler function `i1e(x)` instead.\n\n Args:\n x: A `Tensor` or `SparseTensor`. Must be one of the following types: `half`,\n `float32`, `float64`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` or `SparseTensor`, respectively. Has the same type as `x`.\n\n @compatibility(scipy)\n Equivalent to scipy.special.i1\n @end_compatibility\n \"\"\"\n with ops.name_scope(name, 'bessel_i1', [x]):\n return math_ops.exp(math_ops.abs(x)) * math_ops.bessel_i1e(x)\n\n\[email protected]('XlaEinsum')\ndef _einsum_grad(op, grad):\n equation = op.get_attr('equation')\n if isinstance(equation, bytes):\n equation = equation.decode()\n\n inputs, output = equation.split('->')\n left, right = inputs.split(',')\n\n return [\n gen_xla_ops.xla_einsum(\n grad,\n op.inputs[1],\n equation='{},{}->{}'.format(output, right, left),\n name=None),\n gen_xla_ops.xla_einsum(\n grad,\n op.inputs[0],\n equation='{},{}->{}'.format(output, left, right),\n name=None)\n ]\n\n\ndef _enclosing_tpu_context():\n # pylint: disable=protected-access\n context = ops.get_default_graph()._get_control_flow_context()\n # pylint: enable=protected-access\n while context is not None and not isinstance(\n context, control_flow_ops.XLAControlFlowContext):\n context = context.outer_context\n return context\n\n\n@tf_export('einsum', 'linalg.einsum')\[email protected]_dispatch_support\ndef einsum(equation, *inputs, **kwargs):\n \"\"\"Tensor contraction over specified indices and outer product.\n\n Einsum allows defining Tensors by defining their element-wise computation.\n This computation is defined by `equation`, a shorthand form based on Einstein\n summation. As an example, consider multiplying two matrices A and B to form a\n matrix C. The elements of C are given by:\n\n ```\n C[i,k] = sum_j A[i,j] * B[j,k]\n ```\n\n The corresponding `equation` is:\n\n ```\n ij,jk->ik\n ```\n\n In general, to convert the element-wise equation into the `equation` string,\n use the following procedure (intermediate strings for matrix multiplication\n example provided in parentheses):\n\n 1. remove variable names, brackets, and commas, (`ik = sum_j ij * jk`)\n 2. replace \"*\" with \",\", (`ik = sum_j ij , jk`)\n 3. drop summation signs, and (`ik = ij, jk`)\n 4. move the output to the right, while replacing \"=\" with \"->\". (`ij,jk->ik`)\n\n Many common operations can be expressed in this way. For example:\n\n ```python\n # Matrix multiplication\n einsum('ij,jk->ik', m0, m1) # output[i,k] = sum_j m0[i,j] * m1[j, k]\n\n # Dot product\n einsum('i,i->', u, v) # output = sum_i u[i]*v[i]\n\n # Outer product\n einsum('i,j->ij', u, v) # output[i,j] = u[i]*v[j]\n\n # Transpose\n einsum('ij->ji', m) # output[j,i] = m[i,j]\n\n # Trace\n einsum('ii', m) # output[j,i] = trace(m) = sum_i m[i, i]\n\n # Batch matrix multiplication\n einsum('aij,ajk->aik', s, t) # out[a,i,k] = sum_j s[a,i,j] * t[a, j, k]\n ```\n\n To enable and control broadcasting, use an ellipsis. For example, to perform\n batch matrix multiplication with NumPy-style broadcasting across the batch\n dimensions, use:\n\n ```python\n einsum('...ij,...jk->...ik', u, v)\n ```\n\n Args:\n equation: a `str` describing the contraction, in the same format as\n `numpy.einsum`.\n *inputs: the inputs to contract (each one a `Tensor`), whose shapes should\n be consistent with `equation`.\n **kwargs:\n - optimize: Optimization strategy to use to find contraction path using\n opt_einsum. Must be 'greedy', 'optimal', 'branch-2', 'branch-all' or\n 'auto'. (optional, default: 'greedy').\n - name: A name for the operation (optional).\n\n Returns:\n The contracted `Tensor`, with shape determined by `equation`.\n\n Raises:\n ValueError: If\n - the format of `equation` is incorrect,\n - number of inputs or their shapes are inconsistent with `equation`.\n \"\"\"\n return _einsum_v2(equation, *inputs, **kwargs)\n\n\ndef _einsum_v1(equation, *inputs, **kwargs):\n \"\"\"Legacy implementation of einsum without using EinsumOp.\"\"\"\n name = kwargs.pop('name', None)\n if kwargs:\n raise TypeError('invalid keyword arguments for this function: ' + ', '.join(\n [format(key) for key in sorted(list(kwargs.keys()))]))\n with ops.name_scope(name, 'einsum', [equation, inputs]) as name:\n inputs = list(inputs)\n input_shapes = [x.shape for x in inputs]\n input_axis_labels, output_axis_labels = (\n _einsum_v1_parse_and_resolve_equation(equation, input_shapes))\n\n axis_labels = set(''.join(input_axis_labels) + output_axis_labels)\n\n for a in axis_labels:\n for input_labels in input_axis_labels:\n if (len(input_axis_labels) == 1 and input_labels.count(a) == 2 and\n input_labels == input_labels[::-1] and '->' not in equation):\n return math_ops.trace(inputs[0])\n if input_labels.count(a) > 1:\n raise ValueError(\n 'Subscript not supported: an axis appears more than once: %s' %\n input_labels)\n for a in axis_labels:\n input_count = sum(1 for s in input_axis_labels if a in s)\n if input_count > 2 and a not in output_axis_labels:\n logging.warn(\n 'Falling back to exponential-space implementation of einsum()'\n ' because index \"%s\" is summed over more than two inputs.', a)\n return _exponential_space_einsum_v1(equation, *inputs)\n\n # Use xla_einsum if executing on TPU and if the operation is a 2 input\n # einsum supported by XlaEinsumOp.\n if _enclosing_tpu_context() is not None and len(inputs) == 2:\n return gen_xla_ops.xla_einsum(\n inputs[0], inputs[1], input_axis_labels[0] + ',' +\n input_axis_labels[1] + '->' + output_axis_labels)\n temp = inputs[0]\n temp_axis_labels = input_axis_labels[0]\n for i in xrange(len(inputs) - 1):\n axes_to_sum = (\n set(temp_axis_labels) &\n set(input_axis_labels[i + 1]) - set(output_axis_labels))\n temp, temp_axis_labels = _einsum_v1_reduction(temp, temp_axis_labels,\n inputs[i + 1],\n input_axis_labels[i + 1],\n axes_to_sum)\n\n missing_indices = set(temp_axis_labels) - set(output_axis_labels)\n if missing_indices:\n axis = [\n i for i, a in enumerate(temp_axis_labels)\n if a not in output_axis_labels\n ]\n temp = math_ops.reduce_sum(temp, axis=axis)\n temp_axis_labels = ''.join(\n a for a in temp_axis_labels if a in output_axis_labels)\n if sorted(temp_axis_labels) != sorted(output_axis_labels):\n raise ValueError('Invalid equation: %s' % equation)\n\n perm = [temp_axis_labels.index(a) for a in output_axis_labels]\n return _transpose_if_necessary(temp, perm)\n\n\ndef _einsum_v1_parse_and_resolve_equation(equation, input_shapes):\n \"\"\"Helper for einsum() that splits/resolves inputs & outputs.\n\n Args:\n equation: Equation string given as argument to einsum().\n input_shapes: List of the shapes of all inputs given to einsum()\n\n Returns:\n input_axis_labels, output_axis_labels where:\n input_axis_labels: List of length len(input_shapes) of strings\n representing the character label for each dimension of each given input,\n resolving any broadcast (...) axes,\n output_axis_labels: A string of character labels for each axes of output\n tensor, filling in missing output subscripts and broadcast axes.\n\n Raises:\n ValueError: If equation is in the uncorrect format, incorrect number of\n inputs given or broadcast axes \"...\" or output axes could not be resolved.\n \"\"\"\n equation = equation.replace(' ', '')\n match = re.match('^([a-zA-Z,.]+)(->[a-zA-Z.]*)?$', equation)\n if not match:\n raise ValueError('Indices have incorrect format: %s' % equation)\n\n input_axis_labels = match.group(1).split(',')\n output_axis_labels = match.group(2)[2:] if match.group(2) else None\n\n if len(input_shapes) != len(input_axis_labels):\n raise ValueError('Got %d arguments for equation \"%s\", expecting %d' %\n (len(input_shapes), equation, len(input_axis_labels)))\n\n # Resolve Ellipsis\n # Assign axes labels for unspecified dimensions in inputs. Labels taken\n # from unused labels. Follow numpy einsum broadcasting conventions for\n # tensors of different length and unlabeled output.\n ellipsis_axes = ''\n if '...' in equation:\n unused = ''.join(\n c for c in string.ascii_letters if c not in ''.join(input_axis_labels))\n for i, ax in enumerate(input_axis_labels):\n if '...' in ax:\n parts = ax.split('...')\n if len(parts) != 2:\n raise ValueError('Unable to resolve ellipsis. Excess number found.')\n if input_shapes[i].ndims is None:\n raise ValueError('Unable to statically infer ellipsis axes.')\n n = input_shapes[i].ndims - len(''.join(parts))\n if n < 0:\n raise ValueError('Ellipses lengths do not match.')\n if len(unused) < n:\n raise ValueError(\n 'Unable to resolve ellipsis, too many distinct labels.')\n replace_axes = unused[-n:] if n > 0 else ''\n input_axis_labels[i] = input_axis_labels[i].replace('...',\n replace_axes)\n if len(replace_axes) > len(ellipsis_axes):\n ellipsis_axes = replace_axes\n\n if any('.' in ax for ax in input_axis_labels):\n raise ValueError('period \".\" found outside of ellipsis')\n\n if output_axis_labels is not None:\n output_axis_labels = output_axis_labels.replace('...', ellipsis_axes)\n if '.' in output_axis_labels:\n raise ValueError('period \".\" found outside of ellipsis')\n\n if output_axis_labels is None:\n # infer the output subscripts if not given, assume alphabetical order,\n # but always place ellipsis axes before given.\n axis_labels = set(''.join(input_axis_labels)) - set(ellipsis_axes)\n indices = ''.join(sorted(axis_labels))\n counts = {ax: 0 for ax in indices}\n for axes_ in input_axis_labels:\n for ax in axes_:\n if ax not in ellipsis_axes:\n counts[ax] += 1\n\n output_axis_labels = ellipsis_axes + ''.join(\n sorted(ax for ax in axis_labels if counts[ax] == 1))\n\n return input_axis_labels, output_axis_labels\n\n\ndef _einsum_v1_reduction(t0, t0_axis_labels, t1, t1_axis_labels, axes_to_sum):\n \"\"\"Helper for einsum() that computes the result of a two-argument einsum().\n\n Args:\n t0: a `Tensor`\n t0_axis_labels: a string of axis labels. This string's length must equal\n the rank of t0.\n t1: a `Tensor`\n t1_axis_labels: a string to axis labels. This string's length must equal\n the rank of t1.\n axes_to_sum: set of labels of axes to be summed over\n\n Returns:\n A `Tensor` whose elements are obtained by summing, over all axes in\n `axes_to_sum`, the corresponding elements of `t0` and `t1`.\n\n For example, if t0_axis_labels == 'abijk', t1_axis_labels == 'acjkl', and\n axes_to_sum == {j,k}, this will return a tensor x where\n\n out[a,b,c,i,l] = sum_j sum_k t0[a,b,i,j,k] * t1[a,c,j,k,l]\n\n Raises:\n ValueError: if the rank of `t0` does not match the length of\n `t0_axis_labels`, or that of `t1` does not match the length of\n `t1_axis_labels`.\n \"\"\"\n if len(t0_axis_labels) != len(t0.shape):\n raise ValueError(\n 'Tensor t0 of rank %d does not match einsum reduction of length %d' %\n (len(t0.shape), len(t0_axis_labels)))\n if len(t1_axis_labels) != len(t1.shape):\n raise ValueError(\n 'Tensor t1 of rank %d does not match einsum reduction of length %d' %\n (len(t1.shape), len(t1_axis_labels)))\n\n # This function computes the result of a two-argument einsum() using batch\n # matrix multiplication. This involves\n # 1. transposing t0 and t1 so that axes are in the correct order for\n # batch matrix multiplication, and\n # 2. reshaping t0 and t1 so that they are both of rank 3.\n\n # First, we divide axes into three groups:\n # * \"preserved\" axes are present in both inputs and the output\n # * \"summed\" axes are present in both inputs but not the output\n # * \"broadcast\" axes are present in exactly one input and the output\n #\n # As an example, if the einsum is abijk,acjkl->abcil, then \"a\" is a\n # preserved axis, \"b\" and \"c\" are broadcast axes, and \"j\" and \"k\" are\n # summed axes.\n assert all(a in t0_axis_labels and a in t1_axis_labels for a in axes_to_sum)\n preserved_axes = (set(t0_axis_labels) & set(t1_axis_labels)) - axes_to_sum\n broadcast_axes = {}\n for i, sym_list in enumerate([t0_axis_labels, t1_axis_labels]):\n broadcast_axes[i] = set(sym_list) - preserved_axes - axes_to_sum\n\n # Reorder the axes so that:\n # 1. preserved axes come first in both inputs\n # 2. in input 0, broadcast axes come next, followed by summed axes\n # 3. in input 1, summed axes come next, followed by broadcast axes\n def sort_key(input_index, a):\n if a in preserved_axes:\n return (-1, a)\n elif ((input_index == 0 and a in broadcast_axes[0]) or\n (input_index == 1 and a in axes_to_sum)):\n return (0, a)\n else:\n return (1, a)\n\n axis_labels = [t0_axis_labels, t1_axis_labels]\n sorted_axes = [\n sorted(sym_list, key=lambda a: sort_key(i, a))\n for i, sym_list in enumerate(axis_labels)\n ]\n inputs = [t0, t1]\n for i, axes_str in enumerate(axis_labels):\n perm = [axes_str.find(a) for a in sorted_axes[i]]\n inputs[i] = _transpose_if_necessary(inputs[i], perm)\n t0, t1 = inputs\n\n if not axes_to_sum:\n # In the special case where there are no axes to sum over, reduce to mul()\n # rather than to batch matrix multiplication.\n for _ in broadcast_axes[1]:\n t0 = array_ops.expand_dims(t0, -1)\n for _ in broadcast_axes[0]:\n t1 = array_ops.expand_dims(t1, len(preserved_axes))\n product = math_ops.multiply(t0, t1)\n product_axes = sorted_axes[0] + sorted_axes[1][len(preserved_axes):]\n return product, ''.join(product_axes)\n else:\n # Reduce to matmul().\n\n # Reshape both inputs so as to combine multiple broadcast axes\n # into a single axis, and combine multiple summed axes into a\n # single axis.\n\n t0_shape = _get_shape(t0)\n num_broadcast_elements_t0 = _total_size(\n t0_shape[len(preserved_axes):-len(axes_to_sum)])\n num_summed_elements = _total_size(t0_shape[-len(axes_to_sum):])\n new_shape = (\n t0_shape[:len(preserved_axes)] +\n [num_broadcast_elements_t0, num_summed_elements])\n t0 = _reshape_if_necessary(t0, new_shape)\n\n t1_shape = _get_shape(t1)\n num_broadcast_elements_t1 = _total_size(\n t1_shape[len(preserved_axes) + len(axes_to_sum):])\n new_shape = (\n t1_shape[:len(preserved_axes)] +\n [num_summed_elements, num_broadcast_elements_t1])\n t1 = _reshape_if_necessary(t1, new_shape)\n\n product = math_ops.matmul(t0, t1)\n\n # Undo compaction of broadcast axes\n uncompacted_shape = (\n t0_shape[:len(preserved_axes) + len(broadcast_axes[0])] +\n t1_shape[len(t1_shape) - len(broadcast_axes[1]):])\n product = _reshape_if_necessary(product, uncompacted_shape)\n\n product_axes = (\n sorted_axes[0][:len(preserved_axes) + len(broadcast_axes[0])] +\n sorted_axes[1][len(sorted_axes[1]) - len(broadcast_axes[1]):])\n\n return product, ''.join(product_axes)\n\n\ndef _transpose_if_necessary(tensor, perm):\n \"\"\"Like transpose(), but avoids creating a new tensor if possible.\"\"\"\n if perm != list(range(len(perm))):\n return array_ops.transpose(tensor, perm=perm)\n else:\n return tensor\n\n\ndef _reshape_if_necessary(tensor, new_shape):\n \"\"\"Like reshape(), but avoids creating a new tensor if possible.\"\"\"\n # Accept None as an alias for -1 in new_shape.\n new_shape = tuple(-1 if x is None else x for x in new_shape)\n cur_shape = tuple(x.value for x in tensor.shape.dims)\n if (len(new_shape) == len(cur_shape) and\n all(not isinstance(d1, ops.Tensor) and (d0 == d1 or d1 == -1)\n for d0, d1 in zip(cur_shape, new_shape))):\n return tensor\n else:\n return array_ops.reshape(tensor, new_shape)\n\n\ndef _get_shape(tensor):\n \"\"\"Like get_shape().as_list(), but explicitly queries the shape of a tensor\n if necessary to ensure that the returned value contains no unknown value.\"\"\"\n\n shape = tensor.shape.as_list()\n none_indices = [i for i, d in enumerate(shape) if d is None]\n if none_indices:\n # Query the shape if shape contains None values\n shape_tensor = array_ops.shape(tensor)\n for i in none_indices:\n shape[i] = shape_tensor[i]\n return shape\n\n\ndef _total_size(shape_values):\n \"\"\"Given list of tensor shape values, returns total size.\n If shape_values contains tensor values (which are results of\n array_ops.shape), then it returns a scalar tensor.\n If not, it returns an integer.\"\"\"\n\n result = 1\n for val in shape_values:\n result *= val\n return result\n\n\ndef _exponential_space_einsum_v1(equation, *inputs):\n \"\"\"Fallback implementation that supports summing an index over > 2 inputs.\"\"\"\n inputs = list(inputs)\n input_shapes = [x.shape for x in inputs]\n idx_in, idx_out = _einsum_v1_parse_and_resolve_equation(\n equation, input_shapes)\n\n idx_all = set(''.join(idx_in) + idx_out)\n indices = ''.join(sorted(idx_all))\n\n missing_idx = set(idx_out).difference(idx_all)\n if missing_idx:\n raise ValueError('Unknown output axes: %s' % missing_idx)\n\n axis_order = {}\n for ax in indices:\n if ax not in idx_out:\n axis_order[ax] = len(axis_order)\n for ax in idx_out:\n axis_order[ax] = len(axis_order)\n\n # transpose inputs so axes are in order\n for i, (input_, axes_) in enumerate(zip(inputs, idx_in)):\n if input_.shape.ndims != len(axes_):\n raise ValueError(\n 'Input %d with axes %s has incorrect' \\\n ' number of dimensions (expected %d, got %d)' % (\n i, axes_, len(axes_), input_.shape.ndims\n )\n )\n\n sorted_idx = sorted(axes_, key=axis_order.get)\n\n if len(set(axes_)) != len(axes_):\n raise ValueError(\n 'Subscript not supported: an axis appears more than once: %s' % axes_)\n\n if list(axes_) != sorted_idx:\n permuted = [axes_.find(ax) for ax in sorted_idx]\n inputs[i] = array_ops.transpose(input_, permuted)\n idx_in[i] = sorted_idx\n\n reduction_idx = []\n shapes = [[dim if dim else -1\n for dim in tensor.shape.as_list()]\n for tensor in inputs]\n\n # validate shapes for broadcasting\n for j, ax in enumerate(sorted(idx_all, key=axis_order.get)):\n dims = []\n for i, idx in enumerate(idx_in):\n if ax not in idx:\n shapes[i].insert(j, 1)\n else:\n dim = shapes[i][j]\n if isinstance(dim, int) and dim > 1:\n dims.append(dim)\n\n if len(set(dims)) > 1:\n raise ValueError('Dimension mismatch on axis: %s' % ax)\n\n if ax not in idx_out:\n reduction_idx.append(j)\n\n # reshape, multiply\n expanded_inputs = [\n array_ops.reshape(input_, shape) for input_, shape in zip(inputs, shapes)\n ]\n expanded_output = 1\n for input_ in expanded_inputs:\n expanded_output *= input_\n\n # contract\n return math_ops.reduce_sum(expanded_output, reduction_idx)\n\n\ndef _einsum_v2(equation, *inputs, **kwargs):\n \"\"\"Implementation of einsum utilizing opt_einsum and EinsumOp.\"\"\"\n name = kwargs.pop('name', None)\n optimize = kwargs.pop('optimize', 'greedy')\n if kwargs:\n msg = 'Invalid keyword arguments for einsum: {}'\n raise TypeError(msg.format(', '.join(kwargs)))\n\n with ops.name_scope(name, 'einsum', [equation, inputs]) as name:\n inputs = list(inputs)\n input_shapes = []\n for operand in inputs:\n if isinstance(operand.shape, tensor_shape.TensorShape):\n input_shapes.append(operand.shape.as_list() if operand.shape else None)\n else:\n input_shapes.append(list(operand.shape))\n # Validate and sanitize the equation and resolve static input shapes, as\n # opt_einsum requires that all shapes be a tuple of positive integers.\n # Also remove ellipsis from the equation as opt_einsum will replace them\n # with named labels. Then broadcasting between different shapes or ranks\n # wouldn't work. (E.g. [1, 1, 2] wouldn't broadcast with [3, 1]).\n resolved_equation, resolved_input_shapes, ellipsis_label = (\n _einsum_v2_parse_and_resolve_equation(equation, input_shapes))\n\n if len(inputs) <= 2: # No need to call opt_einsum.\n # Replace back ellipses that were removed for opt_einsum.\n if ellipsis_label:\n resolved_equation = resolved_equation.replace(ellipsis_label, '...')\n return gen_linalg_ops.einsum(inputs, resolved_equation)\n\n # Send fully specified shapes to opt_einsum, since it cannot handle unknown\n # dimensions. For unknown dimensions, we guess that the dimension equals 1.\n # Instead of creating Tensors or NumPy arrays with the specified shape,\n # create a dummy `shaped` object with a `shape` property.\n shaped = collections.namedtuple('shaped', ['shape'])\n shaped_inputs = tuple(\n [shaped(tuple(shape)) for shape in resolved_input_shapes])\n # opt_einsum breaks down an n-ary einsum operation into n-1 binary einsums.\n # Obtain the sequence of equations and the indices of operands involved in\n # each einsum operation.\n indices_and_equations = _get_opt_einsum_contract_path(\n resolved_equation, shaped_inputs, optimize)\n for operand_indices, binary_equation in indices_and_equations:\n if ellipsis_label:\n # Replace back ellipses that were removed for opt_einsum.\n binary_equation = binary_equation.replace(ellipsis_label, '...')\n operands = list(map(inputs.pop, operand_indices))\n inputs.append(gen_linalg_ops.einsum(operands, binary_equation))\n return inputs[0]\n\n\ndef _get_opt_einsum_contract_path(equation, shaped_inputs_tuple, optimize):\n \"\"\"Returns the (memoized) result of opt_einsum.contract_path.\"\"\"\n # Note: We use einsum_call=True, which is an internal api for opt_einsum,\n # to get the contraction path without having opt_einsum perform the actual\n # contractions.\n _, contractions = opt_einsum.contract_path(\n equation,\n *shaped_inputs_tuple,\n optimize=optimize,\n einsum_call=True,\n use_blas=True)\n # Return a tuple so that the cached value is not mutable.\n indices_and_equations = tuple([(expr[0], expr[2]) for expr in contractions])\n return indices_and_equations\n\n\n# Cache the possibly expensive opt_einsum.contract_path call using lru_cache\n# from the Python3+ standard library.\nif not six.PY2:\n _get_opt_einsum_contract_path = functools.lru_cache(maxsize=128)(\n _get_opt_einsum_contract_path)\n\n\ndef _einsum_v2_parse_and_resolve_equation(equation, input_shapes):\n \"\"\"Helper which validates einsum equation and resolves input shapes.\"\"\"\n resolved_equation = equation.replace(' ', '')\n ellipsis_label = None\n if '...' in equation:\n # Replace ellipsis ('...') with '0' for (a) ease of parsing and (b) to\n # prevent opt_einsum from resolving them into named labels; as it doesn't\n # support broadcasting.\n ellipsis_label = '0'\n if ellipsis_label in resolved_equation:\n raise ValueError('Invalid character \"0\" in equation: {}'.format(equation))\n resolved_equation = resolved_equation.replace('...', ellipsis_label)\n\n # Ensure there are no non-alphanumeric characters in the equation, including\n # periods (`.`) outside of ellipses, in the equation. This is not a hard\n # requirement; except we use a special character '0' for ellipsis.\n allowed_labels = 'a-zA-Z'\n if ellipsis_label:\n allowed_labels += ellipsis_label\n match = re.match('^([{0},]*)(->[{0}]*)?$'.format(allowed_labels),\n resolved_equation)\n if not match:\n raise ValueError(\n 'Subscripts have incorrect format: {}'.format(resolved_equation))\n input_labels = match.group(1).split(',')\n output_labels = match.group(2)[2:] if match.group(2) else None\n\n if len(input_shapes) != len(input_labels):\n raise ValueError('Got {} inputs for equation \"{}\", expecting {}'.format(\n len(input_shapes), equation, len(input_labels)))\n\n # Special case: if there are no '->', then we create output subscripts from\n # labels appearing only once.\n if '->' not in resolved_equation:\n label_counts = collections.Counter(match.group(1))\n output_labels = ''.join([\n x for x in sorted(list(label_counts))\n if x != ',' and label_counts[x] == 1\n ])\n resolved_equation += '->' + output_labels\n # Validate output_labels.\n if output_labels and len(set(output_labels)) != len(output_labels):\n raise ValueError(\n 'Output subscripts contain a label appearing more than once: {}'.format(\n equation))\n input_label_set = set(match.group(1))\n for label in output_labels:\n if label != ellipsis_label and label not in input_label_set:\n raise ValueError('Output subscripts contain the label {} not present '\n 'in the input subscripts.'.format(label))\n if ellipsis_label and output_labels:\n num_output_ellipses = output_labels.count(ellipsis_label)\n if num_output_ellipses > 1:\n raise ValueError(\n 'Output subscripts contain multiple ellipsis: {}'.format(equation))\n\n # Early return if <= 2 inputs. Resolved shapes are not needed.\n if len(input_shapes) <= 2:\n return resolved_equation, None, ellipsis_label\n\n # Create a map from axis labels to known dimensions. This is used to infer\n # unknown dimensions if a known dimension also has the same label.\n label_to_dim = collections.defaultdict(lambda: 1)\n for i, (labels, shape) in enumerate(zip(input_labels, input_shapes)):\n if shape is None:\n continue\n ellipsis_start = labels.find(ellipsis_label) if ellipsis_label else -1\n if ellipsis_start != -1: # This input contains an ellipsis.\n if ellipsis_start != labels.rfind(ellipsis_label):\n raise ValueError('Too many ellipsis')\n if len(labels) > len(shape) + 1:\n raise ValueError('Too many named labels in {}th subscript string of'\n ' equation {} for input shape {} '.format(\n i, equation, shape))\n ellipsis_end = ellipsis_start + len(shape) + 1 - len(labels)\n shape[ellipsis_start:ellipsis_end] = ([\n np.prod(\n list(filter(None, shape[ellipsis_start:ellipsis_end])),\n dtype=np.int64)\n ])\n else:\n # This input does not contain an ellipsis.\n if len(labels) != len(shape):\n raise ValueError(\n 'Number of named labels in input #{} of equation {} '\n 'must be equal to the number of dimensions in shape {}'.format(\n i, equation, shape))\n for dim, label in zip(shape, labels):\n if dim is not None:\n label_to_dim[label] = max(label_to_dim[label], dim)\n\n resolved_shapes = []\n for labels in input_labels:\n resolved_shapes.append([label_to_dim[label] for label in labels])\n return resolved_equation, resolved_shapes, ellipsis_label\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 category_encoding preprocessing layer.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n\nfrom absl.testing import parameterized\nimport numpy as np\n\nfrom tensorflow.python import keras\n\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import sparse_tensor\nfrom tensorflow.python.keras import backend\nfrom tensorflow.python.keras import keras_parameterized\nfrom tensorflow.python.keras import testing_utils\nfrom tensorflow.python.keras.layers import core\nfrom tensorflow.python.keras.layers.preprocessing import category_encoding\nfrom tensorflow.python.keras.layers.preprocessing import category_encoding_v1\nfrom tensorflow.python.keras.layers.preprocessing import preprocessing_test_utils\nfrom tensorflow.python.ops import sparse_ops\nfrom tensorflow.python.ops.ragged import ragged_factory_ops\nfrom tensorflow.python.platform import test\n\n\ndef get_layer_class():\n if context.executing_eagerly():\n return category_encoding.CategoryEncoding\n else:\n return category_encoding_v1.CategoryEncoding\n\n\n@keras_parameterized.run_all_keras_modes(always_skip_v1=True)\nclass CategoryEncodingInputTest(keras_parameterized.TestCase,\n preprocessing_test_utils.PreprocessingLayerTest\n ):\n\n def test_dense_input_sparse_output(self):\n input_array = constant_op.constant([[1, 2, 3], [3, 3, 0]])\n\n # The expected output should be (X for missing value):\n # [[X, 1, 1, 1]\n # [1, X, X, X]\n # [X, X, X, 2]]\n expected_indices = [[0, 1], [0, 2], [0, 3], [1, 0], [1, 3]]\n expected_values = [1, 1, 1, 1, 2]\n max_tokens = 6\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.int32)\n layer = get_layer_class()(\n max_tokens=max_tokens, output_mode=category_encoding.COUNT, sparse=True)\n int_data = layer(input_data)\n\n model = keras.Model(inputs=input_data, outputs=int_data)\n sp_output_dataset = model.predict(input_array, steps=1)\n self.assertAllEqual(expected_values, sp_output_dataset.values)\n self.assertAllEqual(expected_indices, sp_output_dataset.indices)\n\n # Assert sparse output is same as dense output.\n layer = get_layer_class()(\n max_tokens=max_tokens,\n output_mode=category_encoding.COUNT,\n sparse=False)\n int_data = layer(input_data)\n model = keras.Model(inputs=input_data, outputs=int_data)\n output_dataset = model.predict(input_array, steps=1)\n self.assertAllEqual(\n sparse_ops.sparse_tensor_to_dense(sp_output_dataset, default_value=0),\n output_dataset)\n\n def test_sparse_input(self):\n input_array = np.array([[1, 2, 3, 0], [0, 3, 1, 0]], dtype=np.int64)\n sparse_tensor_data = sparse_ops.from_dense(input_array)\n\n # pyformat: disable\n expected_output = [[0, 1, 1, 1, 0, 0],\n [0, 1, 0, 1, 0, 0]]\n # pyformat: enable\n max_tokens = 6\n expected_output_shape = [None, max_tokens]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.int64, sparse=True)\n\n layer = get_layer_class()(\n max_tokens=max_tokens, output_mode=category_encoding.BINARY)\n int_data = layer(input_data)\n self.assertAllEqual(expected_output_shape, int_data.shape.as_list())\n\n model = keras.Model(inputs=input_data, outputs=int_data)\n output_dataset = model.predict(sparse_tensor_data, steps=1)\n self.assertAllEqual(expected_output, output_dataset)\n\n def test_sparse_input_with_weights(self):\n input_array = np.array([[1, 2, 3, 4], [4, 3, 1, 4]], dtype=np.int64)\n weights_array = np.array([[.1, .2, .3, .4], [.2, .1, .4, .3]])\n sparse_tensor_data = sparse_ops.from_dense(input_array)\n sparse_weight_data = sparse_ops.from_dense(weights_array)\n\n # pyformat: disable\n expected_output = [[0, .1, .2, .3, .4, 0],\n [0, .4, 0, .1, .5, 0]]\n # pyformat: enable\n max_tokens = 6\n expected_output_shape = [None, max_tokens]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.int64, sparse=True)\n weight_data = keras.Input(shape=(None,), dtype=dtypes.float32, sparse=True)\n\n layer = get_layer_class()(\n max_tokens=max_tokens, output_mode=category_encoding.COUNT)\n int_data = layer(input_data, count_weights=weight_data)\n self.assertAllEqual(expected_output_shape, int_data.shape.as_list())\n\n model = keras.Model(inputs=[input_data, weight_data], outputs=int_data)\n output_dataset = model.predict([sparse_tensor_data, sparse_weight_data],\n steps=1)\n self.assertAllClose(expected_output, output_dataset)\n\n def test_sparse_input_sparse_output(self):\n sp_inp = sparse_tensor.SparseTensor(\n indices=[[0, 0], [1, 1], [2, 0], [2, 1], [3, 1]],\n values=[0, 2, 1, 1, 0],\n dense_shape=[4, 2])\n input_data = keras.Input(shape=(None,), dtype=dtypes.int64, sparse=True)\n\n # The expected output should be (X for missing value):\n # [[1, X, X, X]\n # [X, X, 1, X]\n # [X, 2, X, X]\n # [1, X, X, X]]\n expected_indices = [[0, 0], [1, 2], [2, 1], [3, 0]]\n expected_values = [1, 1, 2, 1]\n max_tokens = 6\n\n layer = get_layer_class()(\n max_tokens=max_tokens, output_mode=category_encoding.COUNT, sparse=True)\n int_data = layer(input_data)\n\n model = keras.Model(inputs=input_data, outputs=int_data)\n sp_output_dataset = model.predict(sp_inp, steps=1)\n self.assertAllEqual(expected_values, sp_output_dataset.values)\n self.assertAllEqual(expected_indices, sp_output_dataset.indices)\n\n # Assert sparse output is same as dense output.\n layer = get_layer_class()(\n max_tokens=max_tokens,\n output_mode=category_encoding.COUNT,\n sparse=False)\n int_data = layer(input_data)\n model = keras.Model(inputs=input_data, outputs=int_data)\n output_dataset = model.predict(sp_inp, steps=1)\n self.assertAllEqual(\n sparse_ops.sparse_tensor_to_dense(sp_output_dataset, default_value=0),\n output_dataset)\n\n def test_sparse_input_sparse_output_with_weights(self):\n indices = [[0, 0], [1, 1], [2, 0], [2, 1], [3, 1]]\n sp_inp = sparse_tensor.SparseTensor(\n indices=indices, values=[0, 2, 1, 1, 0], dense_shape=[4, 2])\n input_data = keras.Input(shape=(None,), dtype=dtypes.int64, sparse=True)\n sp_weight = sparse_tensor.SparseTensor(\n indices=indices, values=[.1, .2, .4, .3, .2], dense_shape=[4, 2])\n weight_data = keras.Input(shape=(None,), dtype=dtypes.float32, sparse=True)\n\n # The expected output should be (X for missing value):\n # [[1, X, X, X]\n # [X, X, 1, X]\n # [X, 2, X, X]\n # [1, X, X, X]]\n expected_indices = [[0, 0], [1, 2], [2, 1], [3, 0]]\n expected_values = [.1, .2, .7, .2]\n max_tokens = 6\n\n layer = get_layer_class()(\n max_tokens=max_tokens, output_mode=category_encoding.COUNT, sparse=True)\n int_data = layer(input_data, count_weights=weight_data)\n\n model = keras.Model(inputs=[input_data, weight_data], outputs=int_data)\n sp_output_dataset = model.predict([sp_inp, sp_weight], steps=1)\n self.assertAllClose(expected_values, sp_output_dataset.values)\n self.assertAllEqual(expected_indices, sp_output_dataset.indices)\n\n def test_ragged_input(self):\n input_array = ragged_factory_ops.constant([[1, 2, 3], [3, 1]])\n\n # pyformat: disable\n expected_output = [[0, 1, 1, 1, 0, 0],\n [0, 1, 0, 1, 0, 0]]\n # pyformat: enable\n max_tokens = 6\n expected_output_shape = [None, max_tokens]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.int32, ragged=True)\n\n layer = get_layer_class()(\n max_tokens=max_tokens, output_mode=category_encoding.BINARY)\n int_data = layer(input_data)\n\n self.assertAllEqual(expected_output_shape, int_data.shape.as_list())\n\n model = keras.Model(inputs=input_data, outputs=int_data)\n output_dataset = model.predict(input_array, steps=1)\n self.assertAllEqual(expected_output, output_dataset)\n\n def test_ragged_input_sparse_output(self):\n input_array = ragged_factory_ops.constant([[1, 2, 3], [3, 3]])\n\n # The expected output should be (X for missing value):\n # [[X, 1, 1, 1]\n # [X, X, X, 2]]\n expected_indices = [[0, 1], [0, 2], [0, 3], [1, 3]]\n expected_values = [1, 1, 1, 2]\n max_tokens = 6\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.int32, ragged=True)\n layer = get_layer_class()(\n max_tokens=max_tokens, output_mode=category_encoding.COUNT, sparse=True)\n int_data = layer(input_data)\n\n model = keras.Model(inputs=input_data, outputs=int_data)\n sp_output_dataset = model.predict(input_array, steps=1)\n self.assertAllEqual(expected_values, sp_output_dataset.values)\n self.assertAllEqual(expected_indices, sp_output_dataset.indices)\n\n # Assert sparse output is same as dense output.\n layer = get_layer_class()(\n max_tokens=max_tokens,\n output_mode=category_encoding.COUNT,\n sparse=False)\n int_data = layer(input_data)\n model = keras.Model(inputs=input_data, outputs=int_data)\n output_dataset = model.predict(input_array, steps=1)\n self.assertAllEqual(\n sparse_ops.sparse_tensor_to_dense(sp_output_dataset, default_value=0),\n output_dataset)\n\n # TODO(b/158570051): Support KerasTensor\n # Keras functional model doesn't support dense layer stacked with sparse out.\n def test_sparse_output_and_dense_layer(self):\n with testing_utils.use_keras_tensors_scope(False):\n input_array = constant_op.constant([[1, 2, 3], [3, 3, 0]])\n\n max_tokens = 4\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.int32)\n encoding_layer = get_layer_class()(\n max_tokens=max_tokens, output_mode=category_encoding.COUNT,\n sparse=True)\n int_data = encoding_layer(input_data)\n dense_layer = keras.layers.Dense(units=1)\n output_data = dense_layer(int_data)\n\n model = keras.Model(inputs=input_data, outputs=output_data)\n _ = model.predict(input_array, steps=1)\n\n\n@keras_parameterized.run_all_keras_modes\nclass CategoryEncodingAdaptTest(keras_parameterized.TestCase,\n preprocessing_test_utils.PreprocessingLayerTest\n ):\n\n def test_sparse_adapt(self):\n vocab_data = sparse_ops.from_dense(\n np.array([[1, 1, 0, 1, 1, 2, 2, 0, 2, 3, 3, 0, 4]], dtype=np.int64))\n vocab_dataset = dataset_ops.Dataset.from_tensors(vocab_data)\n input_array = sparse_ops.from_dense(\n np.array([[1, 2, 3, 0], [0, 3, 1, 0]], dtype=np.int64))\n\n # pyformat: disable\n expected_output = [[0, 1, 1, 1, 0],\n [0, 1, 0, 1, 0]]\n # pyformat: enable\n max_tokens = 5\n expected_output_shape = [None, max_tokens]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.int64, sparse=True)\n layer = get_layer_class()(\n max_tokens=None, output_mode=category_encoding.BINARY)\n layer.adapt(vocab_dataset)\n int_data = layer(input_data)\n self.assertAllEqual(expected_output_shape, int_data.shape.as_list())\n\n model = keras.Model(inputs=input_data, outputs=int_data)\n output_dataset = model.predict(input_array, steps=1)\n self.assertAllEqual(expected_output, output_dataset)\n\n def test_ragged_adapt(self):\n vocab_data = ragged_factory_ops.constant(\n np.array([[1, 1, 0, 1, 1], [2, 2], [0, 2, 3], [0, 4]]))\n vocab_dataset = dataset_ops.Dataset.from_tensors(vocab_data)\n input_array = ragged_factory_ops.constant([[1, 2, 3], [3, 1]])\n\n # pyformat: disable\n expected_output = [[0, 1, 1, 1, 0],\n [0, 1, 0, 1, 0]]\n # pyformat: enable\n max_tokens = 5\n expected_output_shape = [None, max_tokens]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.int32, ragged=True)\n\n layer = get_layer_class()(\n max_tokens=None, output_mode=category_encoding.BINARY)\n layer.adapt(vocab_dataset)\n int_data = layer(input_data)\n\n self.assertAllEqual(expected_output_shape, int_data.shape.as_list())\n\n model = keras.Model(inputs=input_data, outputs=int_data)\n output_dataset = model.predict(input_array, steps=1)\n self.assertAllEqual(expected_output, output_dataset)\n\n def test_adapt_after_build(self):\n vocab_data = np.array([[1, 1, 1, 1, 2, 2, 2, 3, 3, 4]])\n input_array = np.array([[1, 2, 3, 1], [0, 3, 1, 0]])\n\n # pyformat: disable\n expected_output = [[0, 1, 1, 1, 0],\n [1, 1, 0, 1, 0]]\n # pyformat: enable\n max_tokens = 5\n expected_output_shape = [None, max_tokens]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.int32)\n layer = get_layer_class()(\n max_tokens=max_tokens, output_mode=category_encoding.BINARY)\n int_data = layer(input_data)\n layer.adapt(vocab_data)\n self.assertAllEqual(expected_output_shape, int_data.shape.as_list())\n\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_hard_maximum_set_state_variables_after_build(self):\n state_variables = {category_encoding._NUM_ELEMENTS_NAME: 5}\n input_array = np.array([[1, 2, 3, 1], [0, 3, 1, 0]])\n\n # pyformat: disable\n expected_output = [[0, 1, 1, 1, 0],\n [1, 1, 0, 1, 0]]\n # pyformat: enable\n max_tokens = 5\n expected_output_shape = [None, max_tokens]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.int32)\n layer = get_layer_class()(\n max_tokens=max_tokens, output_mode=category_encoding.BINARY)\n int_data = layer(input_data)\n layer._set_state_variables(state_variables)\n self.assertAllEqual(expected_output_shape, int_data.shape.as_list())\n\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_soft_maximum_set_state_after_build(self):\n input_array = np.array([[1, 2, 3, 1], [0, 3, 1, 0]])\n\n # pyformat: disable\n expected_output = [[0, 1, 1, 1, 0],\n [1, 1, 0, 1, 0]]\n # pyformat: enable\n max_tokens = 5\n expected_output_shape = [None, max_tokens]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.int32)\n layer = get_layer_class()(\n max_tokens=None, output_mode=category_encoding.BINARY)\n layer.build(input_data.shape)\n layer.set_num_elements(max_tokens)\n int_data = layer(input_data)\n self.assertAllEqual(expected_output_shape, int_data.shape.as_list())\n\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_set_weights_fails_on_wrong_size_weights(self):\n tfidf_data = [.05, .5, .25, .2, .125]\n layer = get_layer_class()(max_tokens=6, output_mode=category_encoding.TFIDF)\n\n with self.assertRaisesRegex(ValueError, \".*Layer weight shape.*\"):\n layer.set_weights([np.array(tfidf_data)])\n\n def test_set_num_elements_after_call_fails(self):\n input_data = keras.Input(shape=(None,), dtype=dtypes.int32)\n layer = get_layer_class()(\n max_tokens=None, output_mode=category_encoding.BINARY)\n layer.adapt([1, 2])\n _ = layer(input_data)\n with self.assertRaisesRegex(RuntimeError, \"num_elements cannot be changed\"):\n layer.set_num_elements(5)\n\n def test_adapt_after_call_fails(self):\n vocab_data = np.array([1, 1, 1, 1, 2, 2, 2, 3, 3, 4])\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.int32)\n layer = get_layer_class()(\n max_tokens=None, output_mode=category_encoding.BINARY)\n layer.adapt(vocab_data)\n _ = layer(input_data)\n with self.assertRaisesRegex(RuntimeError, \"can't be adapted\"):\n layer.adapt(vocab_data)\n\n def test_set_state_variables_after_call_fails(self):\n state_variables = {category_encoding._NUM_ELEMENTS_NAME: 5}\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.int32)\n layer = get_layer_class()(\n max_tokens=None, output_mode=category_encoding.BINARY)\n layer.adapt([1, 2])\n _ = layer(input_data)\n with self.assertRaisesRegex(RuntimeError, \"num_elements cannot be changed\"):\n layer._set_state_variables(state_variables)\n\n\n@keras_parameterized.run_all_keras_modes\n@keras_parameterized.run_all_keras_modes\nclass CategoryEncodingOutputTest(keras_parameterized.TestCase,\n preprocessing_test_utils.PreprocessingLayerTest\n ):\n\n def test_binary_output_hard_maximum(self):\n input_array = np.array([[1, 2, 3, 1], [0, 3, 1, 0]])\n\n # pyformat: disable\n expected_output = [[0, 1, 1, 1, 0, 0],\n [1, 1, 0, 1, 0, 0]]\n # pyformat: enable\n max_tokens = 6\n expected_output_shape = [None, max_tokens]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.int32)\n layer = get_layer_class()(\n max_tokens=max_tokens, output_mode=category_encoding.BINARY)\n int_data = layer(input_data)\n self.assertAllEqual(expected_output_shape, int_data.shape.as_list())\n\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_soft_maximum(self):\n input_array = np.array([[1, 2, 3, 1], [0, 3, 1, 0]])\n\n # pyformat: disable\n expected_output = [[0, 1, 1, 1, 0],\n [1, 1, 0, 1, 0]]\n # pyformat: enable\n max_tokens = 5\n expected_output_shape = [None, max_tokens]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.int32)\n layer = get_layer_class()(\n max_tokens=None, output_mode=category_encoding.BINARY)\n layer.set_weights([np.array(max_tokens)])\n int_data = layer(input_data)\n self.assertAllEqual(expected_output_shape, int_data.shape.as_list())\n\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_count_output_hard_maximum(self):\n input_array = np.array([[1, 2, 3, 1], [0, 3, 1, 0]])\n\n # pyformat: disable\n expected_output = [[0, 2, 1, 1, 0, 0],\n [2, 1, 0, 1, 0, 0]]\n # pyformat: enable\n max_tokens = 6\n expected_output_shape = [None, max_tokens]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.int32)\n layer = get_layer_class()(max_tokens=6, output_mode=category_encoding.COUNT)\n int_data = layer(input_data)\n self.assertAllEqual(expected_output_shape, int_data.shape.as_list())\n\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_count_output_soft_maximum(self):\n input_array = np.array([[1, 2, 3, 1], [0, 3, 1, 0]])\n\n # pyformat: disable\n expected_output = [[0, 2, 1, 1, 0],\n [2, 1, 0, 1, 0]]\n # pyformat: enable\n max_tokens = 5\n expected_output_shape = [None, max_tokens]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.int32)\n layer = get_layer_class()(\n max_tokens=None, output_mode=category_encoding.COUNT)\n layer.set_weights([np.array(max_tokens)])\n int_data = layer(input_data)\n self.assertAllEqual(expected_output_shape, int_data.shape.as_list())\n\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_tfidf_output_hard_maximum(self):\n tfidf_data = [.05, .5, .25, .2, .125]\n input_array = np.array([[1, 2, 3, 1], [0, 4, 1, 0]])\n\n # pyformat: disable\n # pylint: disable=bad-whitespace\n expected_output = [[ 0, 1, .25, .2, 0, 0],\n [.1, .5, 0, 0, .125, 0]]\n # pylint: enable=bad-whitespace\n # pyformat: enable\n max_tokens = 6\n expected_output_shape = [None, max_tokens]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.int32)\n layer = get_layer_class()(max_tokens=6, output_mode=category_encoding.TFIDF)\n layer.set_tfidf_data(tfidf_data)\n int_data = layer(input_data)\n self.assertAllEqual(expected_output_shape, int_data.shape.as_list())\n\n model = keras.Model(inputs=input_data, outputs=int_data)\n output_dataset = model.predict(input_array)\n self.assertAllClose(expected_output, output_dataset)\n\n def test_tfidf_output_soft_maximum(self):\n tfidf_data = [.05, .5, .25, .2, .125]\n input_array = np.array([[1, 2, 3, 1], [0, 4, 1, 0]])\n\n # pyformat: disable\n # pylint: disable=bad-whitespace\n expected_output = [[ 0, 1, .25, .2, 0],\n [.1, .5, 0, 0, .125]]\n # pylint: enable=bad-whitespace\n # pyformat: enable\n max_tokens = 5\n expected_output_shape = [None, max_tokens]\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.int32)\n layer = get_layer_class()(\n max_tokens=None, output_mode=category_encoding.TFIDF)\n layer.set_num_elements(max_tokens)\n layer.set_tfidf_data(tfidf_data)\n int_data = layer(input_data)\n self.assertAllEqual(expected_output_shape, int_data.shape.as_list())\n\n model = keras.Model(inputs=input_data, outputs=int_data)\n output_dataset = model.predict(input_array)\n self.assertAllClose(expected_output, output_dataset)\n\n\nclass CategoryEncodingModelBuildingTest(\n keras_parameterized.TestCase,\n preprocessing_test_utils.PreprocessingLayerTest):\n\n @parameterized.named_parameters(\n {\n \"testcase_name\": \"count_hard_max\",\n \"max_tokens\": 5,\n \"output_mode\": category_encoding.COUNT\n }, {\n \"testcase_name\": \"count_soft_max\",\n \"max_tokens\": None,\n \"output_mode\": category_encoding.COUNT\n }, {\n \"testcase_name\": \"binary_hard_max\",\n \"max_tokens\": 5,\n \"output_mode\": category_encoding.BINARY\n }, {\n \"testcase_name\": \"binary_soft_max\",\n \"max_tokens\": None,\n \"output_mode\": category_encoding.BINARY\n }, {\n \"testcase_name\": \"tfidf_hard_max\",\n \"max_tokens\": 5,\n \"output_mode\": category_encoding.TFIDF\n }, {\n \"testcase_name\": \"tfidf_soft_max\",\n \"max_tokens\": None,\n \"output_mode\": category_encoding.TFIDF\n })\n def test_end_to_end_bagged_modeling(self, output_mode, max_tokens):\n tfidf_data = np.array([.03, .5, .25, .2, .125])\n input_array = np.array([[1, 2, 3, 1], [0, 3, 1, 0]])\n\n input_data = keras.Input(shape=(None,), dtype=dtypes.int32)\n layer = get_layer_class()(max_tokens=max_tokens, output_mode=output_mode)\n\n weights = []\n if max_tokens is None:\n weights.append(np.array(5))\n if output_mode == category_encoding.TFIDF:\n weights.append(tfidf_data)\n\n layer.set_weights(weights)\n\n int_data = layer(input_data)\n float_data = backend.cast(int_data, dtype=\"float32\")\n output_data = core.Dense(64)(float_data)\n model = keras.Model(inputs=input_data, outputs=output_data)\n _ = model.predict(input_array)\n\n\n@keras_parameterized.run_all_keras_modes\nclass CategoryEncodingCombinerTest(\n keras_parameterized.TestCase,\n preprocessing_test_utils.PreprocessingLayerTest):\n\n def compare_idf_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.data, b.data, msg=msg)\n\n if a.per_doc_count_dict is not None:\n\n def per_doc_counts(accumulator):\n count_values = [\n count_dict[\"count\"]\n for count_dict in accumulator.per_doc_count_dict.values()\n ]\n return dict(zip(accumulator.per_doc_count_dict.keys(), count_values))\n\n self.assertAllEqual(per_doc_counts(a), per_doc_counts(b), msg=msg)\n\n compare_accumulators = compare_idf_accumulators\n\n def update_accumulator(self, accumulator, data):\n accumulator.data[1] = data[\"num_documents\"]\n accumulator.data[0] = data[\"max_element\"]\n\n if \"document_counts\" in data:\n create_dict = lambda x: {\"count\": x, \"last_doc_id\": -1}\n idf_dict = {}\n for i, count in enumerate(data[\"document_counts\"]):\n if count > 0:\n idf_dict[i] = create_dict(count)\n\n accumulator.per_doc_count_dict.update(idf_dict)\n\n return accumulator\n\n def test_combiner_api_compatibility_int_mode(self):\n data = np.array([[1, 2, 3, 4], [1, 2, 3, 0]])\n combiner = category_encoding._CategoryEncodingCombiner(compute_idf=False)\n expected_accumulator_output = {\n \"max_element\": np.array(4),\n \"num_documents\": np.array(2),\n }\n expected_extract_output = {\n \"num_elements\": np.array(5),\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 def test_combiner_api_compatibility_tfidf_mode(self):\n data = np.array([[1, 2, 3, 4], [1, 2, 3, 0]])\n combiner = category_encoding._CategoryEncodingCombiner(compute_idf=True)\n expected_accumulator_output = {\n \"max_element\": np.array(4),\n \"document_counts\": np.array([1, 2, 2, 2, 1]),\n \"num_documents\": np.array(2),\n }\n expected_extract_output = {\n \"num_elements\": np.array(5),\n \"idf\": np.array([0.693147, 0.510826, 0.510826, 0.510826, 0.693147]),\n }\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\": \"no_top_k\",\n \"data\": np.array([[1, 2], [4, 2], [3], [4, 2]]),\n \"expected_accumulator_output\": {\n \"max_element\": np.array(4),\n \"document_counts\": np.array([0, 1, 3, 1, 2]),\n \"num_documents\": np.array(4),\n },\n \"expected_extract_output\": {\n \"num_elements\":\n np.array(5),\n \"idf\":\n np.array([1.609438, 1.098612, 0.693147, 1.098612, 0.847298]),\n },\n }, {\n \"testcase_name\": \"single_element_per_row\",\n \"data\": np.array([[1], [2], [4], [2], [3]]),\n \"expected_accumulator_output\": {\n \"max_element\": np.array(4),\n \"document_counts\": np.array([0, 1, 2, 1, 1]),\n \"num_documents\": np.array(5),\n },\n \"expected_extract_output\": {\n \"num_elements\":\n np.array(5),\n \"idf\":\n np.array([1.791759, 1.252763, 0.980829, 1.252763, 1.252763]),\n },\n })\n def test_combiner_computation(self,\n data,\n expected_accumulator_output,\n expected_extract_output,\n compute_idf=True):\n combiner = category_encoding._CategoryEncodingCombiner(\n compute_idf=compute_idf)\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 def test_1d_data(self):\n data = [1, 2, 3]\n cls = get_layer_class()\n layer = cls()\n layer.adapt(data)\n output = layer(data)\n self.assertListEqual(output.shape.as_list(), [3, 4])\n\n def test_no_adapt_exception(self):\n cls = get_layer_class()\n layer = cls()\n with self.assertRaisesRegex(\n RuntimeError, r\".*you need to call.*\"):\n _ = layer([1, 2, 3])\n\n\nif __name__ == \"__main__\":\n test.main()\n"
] | [
[
"tensorflow.python.distribute.multi_worker_test_base.get_task_type",
"tensorflow.python.distribute.multi_process_runner.barrier",
"tensorflow.python.distribute.multi_process_runner.run",
"tensorflow.python.distribute.multi_process_runner.test_main",
"tensorflow.python.distribute.multi_worker_test_base.create_cluster_spec"
],
[
"tensorflow.python.ops.array_ops.shape",
"tensorflow.python.util.deprecation.deprecated_endpoints",
"tensorflow.python.ops.math_ops.bessel_i1e",
"tensorflow.compiler.tf2xla.ops.gen_xla_ops.xla_einsum",
"tensorflow.python.ops.array_ops.transpose",
"tensorflow.python.ops.math_ops.bessel_i0e",
"tensorflow.python.framework.ops.RegisterGradient",
"tensorflow.python.ops.math_ops.abs",
"tensorflow.python.util.tf_export.tf_export",
"tensorflow.python.ops.math_ops.lgamma",
"tensorflow.python.ops.math_ops.matmul",
"tensorflow.python.ops.gen_special_math_ops.expint",
"tensorflow.python.ops.gen_special_math_ops.spence",
"tensorflow.python.framework.ops.convert_to_tensor",
"tensorflow.python.platform.tf_logging.warn",
"tensorflow.python.ops.gen_linalg_ops.einsum",
"tensorflow.python.ops.gen_special_math_ops.fresnel_sin",
"tensorflow.python.framework.ops.get_default_graph",
"tensorflow.python.framework.ops.name_scope",
"tensorflow.python.ops.array_ops.reshape",
"tensorflow.python.ops.math_ops.multiply",
"tensorflow.python.ops.math_ops.trace",
"tensorflow.python.ops.gen_special_math_ops.fresnel_cos",
"tensorflow.python.ops.array_ops.expand_dims",
"tensorflow.python.ops.math_ops.reduce_sum",
"tensorflow.python.ops.gen_special_math_ops.dawsn"
],
[
"tensorflow.python.data.ops.dataset_ops.Dataset.from_tensors",
"tensorflow.python.keras.Input",
"tensorflow.python.keras.keras_parameterized.run_all_keras_modes",
"tensorflow.python.keras.layers.Dense",
"tensorflow.python.keras.Model",
"tensorflow.python.ops.ragged.ragged_factory_ops.constant",
"tensorflow.python.keras.layers.preprocessing.category_encoding._CategoryEncodingCombiner",
"tensorflow.python.framework.sparse_tensor.SparseTensor",
"tensorflow.python.platform.test.main",
"tensorflow.python.keras.backend.cast",
"tensorflow.python.ops.sparse_ops.sparse_tensor_to_dense",
"tensorflow.python.keras.layers.core.Dense",
"numpy.array",
"tensorflow.python.eager.context.executing_eagerly",
"tensorflow.python.keras.testing_utils.use_keras_tensors_scope",
"tensorflow.python.ops.sparse_ops.from_dense",
"tensorflow.python.framework.constant_op.constant"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.3"
]
},
{
"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.3",
"2.4"
]
}
] |
sano307/lambda-container-demo | [
"6c27c56819c9a3defb63bf26b4fd53bf6cdb71d3"
] | [
"lambda/index.py"
] | [
"import json\n\nimport pandas as pd\n\n\ndef handler(event, context):\n df = pd.DataFrame({\"id\": [1, 2], \"value\": [\"foo\", \"boo\"]})\n print(df)\n\n return {\n \"statusCode\": 200,\n \"body\": json.dumps({\n \"message\": \"This is a container lambda.\"\n })\n }\n"
] | [
[
"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": []
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.