repo_name
stringlengths 6
130
| hexsha
list | file_path
list | code
list | apis
list | possible_versions
list |
---|---|---|---|---|---|
irfanki/EDX
|
[
"272e774d00d05647423fa2f77c8526ceaa30109d"
] |
[
"Module2/Module2-lab5.py"
] |
[
"import pandas as pd\n\n\n# TODO: Load up the table, and extract the dataset\n# out of it. If you're having issues with this, look\n# carefully at the sample code provided in the reading\n#\n# .. your code here ..\n\ndf = pd.read_html('http://www.espn.com/nhl/statistics/player/_/stat/points/sort/points/year/2015/seasontype/2', header=1)[0]\n\nprint(df.head(5))\n\n\n# TODO: Rename the columns so that they match the\n# column definitions provided to you on the website\n#\n# .. your code here ..\n\ncol_names = ['RK', 'Player', 'Team', 'Games Played', 'Goals', 'Assists',\n 'Points', 'Plus/Minus Rating', 'Penalty Minutes',\n 'Points Per Game', 'Shots on Goal', 'Shooting Percentage',\n 'Game-Winning Goals', 'Power-Play Goals', 'Power-Play Assists',\n 'Short-Handed Goals', 'Short-Handed Assists']\n\ndf.columns = col_names\n\nprint(df.head(5))\n\n\n# TODO: Get rid of any row that has at least 4 NANs in it\n#\n# .. your code here ..\n\ndf = df.dropna(axis=0, thresh=4)\n\n\n# TODO: At this point, look through your dataset by printing\n# it. There probably still are some erroneous rows in there.\n# What indexing command(s) can you use to select all rows\n# EXCEPT those rows?\n#\n# .. your code here ..\n\nprint(df)\ndf = df[df.Player != 'PLAYER']\nprint(df)\n\n# TODO: Get rid of the 'RK' column\n#\n# .. your code here ..\n\ndf = df.drop(labels=['RK'], axis=1)\nprint(df)\n\n\n# TODO: Ensure there are no holes in your index by resetting\n# it. By the way, don't store the original index\n#\n# .. your code here ..\n\ndf = df.reset_index(drop=True)\n\n\n# TODO: Check the data type of all columns, and ensure those\n# that should be numeric are numeric\n\nprint(df.dtypes)\n\nfor i in range(2, len(df.columns)):\n df.iloc[:, i] = pd.to_numeric(df.iloc[:, i], errors='coerce')\n \nprint(df.dtypes)\n\n\n# TODO: Your dataframe is now ready! Use the appropriate \n# commands to answer the questions on the course lab page.\n\npct_unique = df.iloc[:, 10].unique()\nprint(pct_unique)\n\nadded = df.iloc[15, 2] + df.iloc[16, 2]"
] |
[
[
"pandas.to_numeric",
"pandas.read_html"
]
] |
[
{
"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": []
}
] |
reshamas/modin
|
[
"b01f91fb3a628ce374aa830964d094480f73afca"
] |
[
"modin/engines/base/io/text/csv_reader.py"
] |
[
"# Licensed to Modin Development Team under one or more contributor license agreements.\n# See the NOTICE file distributed with this work for additional information regarding\n# copyright ownership. The Modin Development Team licenses this file to you under the\n# Apache License, Version 2.0 (the \"License\"); you may not use this file except in\n# compliance with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software distributed under\n# the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific language\n# governing permissions and limitations under the License.\n\nfrom modin.engines.base.io.text.text_file_reader import TextFileReader\nfrom modin.data_management.utils import compute_chunksize\nfrom pandas.io.parsers import _validate_usecols_arg\nimport pandas\nimport csv\nimport sys\n\n\nclass CSVReader(TextFileReader):\n @classmethod\n def _read(cls, filepath_or_buffer, **kwargs):\n if isinstance(filepath_or_buffer, str):\n if not cls.file_exists(filepath_or_buffer):\n return cls.single_worker_read(filepath_or_buffer, **kwargs)\n filepath_or_buffer = cls.get_path(filepath_or_buffer)\n elif not cls.pathlib_or_pypath(filepath_or_buffer):\n return cls.single_worker_read(filepath_or_buffer, **kwargs)\n compression_type = cls.infer_compression(\n filepath_or_buffer, kwargs.get(\"compression\")\n )\n if compression_type is not None:\n if (\n compression_type == \"gzip\"\n or compression_type == \"bz2\"\n or compression_type == \"xz\"\n ):\n kwargs[\"compression\"] = compression_type\n elif (\n compression_type == \"zip\"\n and sys.version_info[0] == 3\n and sys.version_info[1] >= 7\n ):\n # need python3.7 to .seek and .tell ZipExtFile\n kwargs[\"compression\"] = compression_type\n else:\n return cls.single_worker_read(filepath_or_buffer, **kwargs)\n\n chunksize = kwargs.get(\"chunksize\")\n if chunksize is not None:\n return cls.single_worker_read(filepath_or_buffer, **kwargs)\n\n skiprows = kwargs.get(\"skiprows\")\n if skiprows is not None and not isinstance(skiprows, int):\n return cls.single_worker_read(filepath_or_buffer, **kwargs)\n nrows = kwargs.pop(\"nrows\", None)\n names = kwargs.get(\"names\", None)\n index_col = kwargs.get(\"index_col\", None)\n usecols = kwargs.get(\"usecols\", None)\n if names is None:\n # For the sake of the empty df, we assume no `index_col` to get the correct\n # column names before we build the index. Because we pass `names` in, this\n # step has to happen without removing the `index_col` otherwise it will not\n # be assigned correctly\n names = pandas.read_csv(\n filepath_or_buffer,\n **dict(kwargs, usecols=None, nrows=0, skipfooter=0, index_col=None),\n ).columns\n elif index_col is None and not usecols:\n # When names is set to some list that is smaller than the number of columns\n # in the file, the first columns are built as a hierarchical index.\n empty_pd_df = pandas.read_csv(filepath_or_buffer, nrows=0)\n num_cols = len(empty_pd_df.columns)\n if num_cols > len(names):\n index_col = list(range(num_cols - len(names)))\n if len(index_col) == 1:\n index_col = index_col[0]\n kwargs[\"index_col\"] = index_col\n empty_pd_df = pandas.read_csv(\n filepath_or_buffer, **dict(kwargs, nrows=0, skipfooter=0)\n )\n column_names = empty_pd_df.columns\n skipfooter = kwargs.get(\"skipfooter\", None)\n skiprows = kwargs.pop(\"skiprows\", None)\n usecols_md = _validate_usecols_arg(usecols)\n if usecols is not None and usecols_md[1] != \"integer\":\n del kwargs[\"usecols\"]\n all_cols = pandas.read_csv(\n cls.file_open(filepath_or_buffer, \"rb\"),\n **dict(kwargs, nrows=0, skipfooter=0),\n ).columns\n usecols = all_cols.get_indexer_for(list(usecols_md[0]))\n parse_dates = kwargs.pop(\"parse_dates\", False)\n partition_kwargs = dict(\n kwargs,\n header=None,\n names=names,\n skipfooter=0,\n skiprows=None,\n parse_dates=parse_dates,\n usecols=usecols,\n )\n encoding = kwargs.get(\"encoding\", None)\n quotechar = kwargs.get(\"quotechar\", '\"').encode(\n encoding if encoding is not None else \"UTF-8\"\n )\n is_quoting = kwargs.get(\"quoting\", \"\") != csv.QUOTE_NONE\n with cls.file_open(filepath_or_buffer, \"rb\", compression_type) as f:\n # Skip the header since we already have the header information and skip the\n # rows we are told to skip.\n if isinstance(skiprows, int) or skiprows is None:\n if skiprows is None:\n skiprows = 0\n header = kwargs.get(\"header\", \"infer\")\n if header == \"infer\" and kwargs.get(\"names\", None) is None:\n skiprows += 1\n elif isinstance(header, int):\n skiprows += header + 1\n elif hasattr(header, \"__iter__\") and not isinstance(header, str):\n skiprows += max(header) + 1\n if kwargs.get(\"encoding\", None) is not None:\n partition_kwargs[\"skiprows\"] = 1\n # Launch tasks to read partitions\n partition_ids = []\n index_ids = []\n dtypes_ids = []\n # Max number of partitions available\n from modin.pandas import DEFAULT_NPARTITIONS\n\n num_partitions = DEFAULT_NPARTITIONS\n # This is the number of splits for the columns\n num_splits = min(len(column_names), num_partitions)\n # Metadata\n column_chunksize = compute_chunksize(empty_pd_df, num_splits, axis=1)\n if column_chunksize > len(column_names):\n column_widths = [len(column_names)]\n # This prevents us from unnecessarily serializing a bunch of empty\n # objects.\n num_splits = 1\n else:\n column_widths = [\n column_chunksize\n if len(column_names) > (column_chunksize * (i + 1))\n else 0\n if len(column_names) < (column_chunksize * i)\n else len(column_names) - (column_chunksize * i)\n for i in range(num_splits)\n ]\n\n args = {\n \"fname\": filepath_or_buffer,\n \"num_splits\": num_splits,\n **partition_kwargs,\n }\n\n splits = cls.partitioned_file(\n f,\n num_partitions=num_partitions,\n nrows=nrows,\n skiprows=skiprows,\n quotechar=quotechar,\n is_quoting=is_quoting,\n )\n for start, end in splits:\n args.update({\"start\": start, \"end\": end})\n partition_id = cls.deploy(cls.parse, num_splits + 2, args)\n partition_ids.append(partition_id[:-2])\n index_ids.append(partition_id[-2])\n dtypes_ids.append(partition_id[-1])\n\n # Compute the index based on a sum of the lengths of each partition (by default)\n # or based on the column(s) that were requested.\n if index_col is None:\n row_lengths = cls.materialize(index_ids)\n new_index = pandas.RangeIndex(sum(row_lengths))\n else:\n index_objs = cls.materialize(index_ids)\n row_lengths = [len(o) for o in index_objs]\n new_index = index_objs[0].append(index_objs[1:])\n new_index.name = empty_pd_df.index.name\n\n # Compute dtypes by getting collecting and combining all of the partitions. The\n # reported dtypes from differing rows can be different based on the inference in\n # the limited data seen by each worker. We use pandas to compute the exact dtype\n # over the whole column for each column. The index is set below.\n dtypes = cls.get_dtypes(dtypes_ids) if len(dtypes_ids) > 0 else None\n\n partition_ids = cls.build_partition(partition_ids, row_lengths, column_widths)\n # If parse_dates is present, the column names that we have might not be\n # the same length as the returned column names. If we do need to modify\n # the column names, we remove the old names from the column names and\n # insert the new one at the front of the Index.\n if parse_dates is not None:\n # We have to recompute the column widths if `parse_dates` is set because\n # we are not guaranteed to have the correct information regarding how many\n # columns are on each partition.\n column_widths = None\n # Check if is list of lists\n if isinstance(parse_dates, list) and isinstance(parse_dates[0], list):\n for group in parse_dates:\n new_col_name = \"_\".join(group)\n column_names = column_names.drop(group).insert(0, new_col_name)\n # Check if it is a dictionary\n elif isinstance(parse_dates, dict):\n for new_col_name, group in parse_dates.items():\n column_names = column_names.drop(group).insert(0, new_col_name)\n # Set the index for the dtypes to the column names\n if isinstance(dtypes, pandas.Series):\n dtypes.index = column_names\n else:\n dtypes = pandas.Series(dtypes, index=column_names)\n new_frame = cls.frame_cls(\n partition_ids,\n new_index,\n column_names,\n row_lengths,\n column_widths,\n dtypes=dtypes,\n )\n new_query_compiler = cls.query_compiler_cls(new_frame)\n\n if skipfooter:\n new_query_compiler = new_query_compiler.drop(\n new_query_compiler.index[-skipfooter:]\n )\n if kwargs.get(\"squeeze\", False) and len(new_query_compiler.columns) == 1:\n return new_query_compiler[new_query_compiler.columns[0]]\n if index_col is None:\n new_query_compiler._modin_frame._apply_index_objs(axis=0)\n return new_query_compiler\n"
] |
[
[
"pandas.read_csv",
"pandas.Series",
"pandas.io.parsers._validate_usecols_arg"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
bretthandrews/CapsNet-Keras
|
[
"d9bb39688a048b965bed92114e2836c38e2a960b"
] |
[
"capsulenet.py"
] |
[
"\"\"\"\nKeras implementation of CapsNet in Hinton's paper Dynamic Routing\nBetween Capsules. The current version maybe only works for TensorFlow\nbackend. Actually it will be straightforward to re-write to TF code.\nAdopting to other backends should be easy, but I have not tested this.\n\nUsage:\n python capsulenet.py\n python capsulenet.py --epochs 50\n python capsulenet.py --epochs 50 --routings 3\n ... ...\n\nResult:\n Validation accuracy > 99.5% after 20 epochs. Converge to 99.66%\n after 50 epochs. About 110 seconds per epoch on a single GTX1070\n GPU card.\n\nAuthor: Xifeng Guo, E-mail: `[email protected]`,\nGithub: `https://github.com/XifengGuo/CapsNet-Keras`\n\"\"\"\n\nfrom keras import layers, models, optimizers\nfrom keras import backend as K\nfrom keras.utils import to_categorical\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom PIL import Image\n\nfrom capsulelayers import CapsuleLayer, PrimaryCap, Length, Mask\nfrom utils import combine_images, TimeHistory\n\nK.set_image_data_format(\"channels_last\")\n\n\ndef CapsNet(input_shape, n_class, routings):\n \"\"\"\n A Capsule Network on CIFAR-10.\n :param input_shape: data shape, 3d, [width, height, channels]\n :param n_class: number of classes\n :param routings: number of routing iterations\n :return: Two Keras Models, the first one used for training, and the\n second one for evaluation. `eval_model` can also be used for\n training.\n \"\"\"\n x = layers.Input(shape=input_shape)\n\n # Layer 1: Just a conventional Conv2D layer\n conv1 = layers.Conv2D(\n filters=256,\n kernel_size=9,\n strides=1,\n padding=\"valid\",\n activation=\"relu\",\n name=\"conv1\",\n )(x)\n\n # Layer 2: Conv2D layer with `squash` activation, then reshape to\n # [None, num_capsule, dim_capsule]\n primarycaps = PrimaryCap(\n conv1, dim_capsule=8, n_channels=64, kernel_size=9, strides=2, padding=\"valid\"\n )\n\n # Layer 3: Capsule layer. Routing algorithm works here.\n digitcaps = CapsuleLayer(\n num_capsule=n_class, dim_capsule=16, routings=routings, name=\"digitcaps\"\n )(primarycaps)\n\n # Layer 4: This is an auxiliary layer to replace each capsule with\n # its length. Just to match the true label's shape.\n # If using tensorflow, this will not be necessary. :)\n out_caps = Length(name=\"capsnet\")(digitcaps)\n\n # Decoder network.\n y = layers.Input(shape=(n_class,))\n masked_by_y = Mask()(\n [digitcaps, y]\n ) # The true label is used to mask the output of capsule layer. For training\n masked = Mask()(\n digitcaps\n ) # Mask using the capsule with maximal length. For prediction\n\n # Shared Decoder model in training and prediction\n decoder = models.Sequential(name=\"decoder\")\n decoder.add(layers.Dense(512, activation=\"relu\", input_dim=16 * n_class))\n decoder.add(layers.Dense(1024, activation=\"relu\"))\n decoder.add(layers.Dense(np.prod(input_shape), activation=\"sigmoid\"))\n decoder.add(layers.Reshape(target_shape=input_shape, name=\"out_recon\"))\n\n # Models for training and evaluation (prediction)\n train_model = models.Model([x, y], [out_caps, decoder(masked_by_y)])\n eval_model = models.Model(x, [out_caps, decoder(masked)])\n\n # manipulate model\n noise = layers.Input(shape=(n_class, 16))\n noised_digitcaps = layers.Add()([digitcaps, noise])\n masked_noised_y = Mask()([noised_digitcaps, y])\n manipulate_model = models.Model([x, y, noise], decoder(masked_noised_y))\n return train_model, eval_model, manipulate_model\n\n\ndef margin_loss(y_true, y_pred):\n \"\"\"\n Margin loss for Eq.(4). When y_true[i, :] contains not just one\n `1`, this loss should work too. Not test it.\n\n :param y_true: [None, n_classes]\n :param y_pred: [None, num_capsule]\n :return: a scalar loss value.\n \"\"\"\n L = y_true * K.square(K.maximum(0., 0.9 - y_pred)) + 0.5 * (1 - y_true) * K.square(\n K.maximum(0., y_pred - 0.1)\n )\n\n return K.mean(K.sum(L, 1))\n\n\ndef train(model, data, args):\n \"\"\"\n Training a CapsuleNet\n :param model: the CapsuleNet model\n :param data: a tuple containing training and testing data, like\n `((x_train, y_train), (x_test, y_test))`\n :param args: arguments\n :return: The trained model\n \"\"\"\n # unpacking the data\n (x_train, y_train), (x_test, y_test) = data\n\n # callbacks\n log = callbacks.CSVLogger(args.save_dir + \"/log.csv\")\n tb = callbacks.TensorBoard(\n log_dir=args.save_dir + \"/tensorboard-logs\",\n batch_size=args.batch_size,\n histogram_freq=int(args.debug),\n )\n checkpoint = callbacks.ModelCheckpoint(\n args.save_dir + \"/weights-{epoch:02d}.h5\",\n monitor=\"val_capsnet_acc\",\n save_best_only=True,\n save_weights_only=True,\n verbose=1,\n )\n lr_decay = callbacks.LearningRateScheduler(\n schedule=lambda epoch: args.lr * (args.lr_decay ** epoch)\n )\n timing = TimeHistory()\n # compile the model\n model.compile(\n optimizer=optimizers.Adam(lr=args.lr),\n loss=[margin_loss, \"mse\"],\n loss_weights=[1., args.lam_recon],\n metrics={\"capsnet\": \"accuracy\"},\n )\n\n if args.data_augmentation:\n\n def train_generator(x, y, batch_size, shift_fraction=0.):\n # shift up to 2 pixel for MNIST\n train_datagen = ImageDataGenerator(\n width_shift_range=shift_fraction, height_shift_range=shift_fraction\n )\n generator = train_datagen.flow(x, y, batch_size=batch_size)\n while 1:\n x_batch, y_batch = generator.next()\n yield ([x_batch, y_batch], [y_batch, x_batch])\n\n assert args.shift_fraction != 0, \"No data augmentation if ``shift_fraction`` == 0.\"\n\n model.fit_generator(\n generator=train_generator(\n x_train, y_train, args.batch_size, args.shift_fraction\n ),\n steps_per_epoch=int(y_train.shape[0] / args.batch_size),\n epochs=args.epochs,\n validation_data=[[x_test, y_test], [y_test, x_test]],\n callbacks=[log, tb, checkpoint, lr_decay, timing],\n )\n\n else:\n\n assert args.shift_fraction == 0, \"Set ``data_augmentation`` flag to shift pixels.\"\n\n model.fit(\n [x_train, y_train],\n [y_train, x_train],\n batch_size=args.batch_size,\n epochs=args.epochs,\n validation_data=[[x_test, y_test], [y_test, x_test]],\n callbacks=[log, tb, checkpoint, lr_decay, timing],\n )\n\n print(\"Time per epoch\", timing.times)\n\n model.save_weights(args.save_dir + \"/trained_model.h5\")\n print(\"Trained model saved to '%s/trained_model.h5'\" % args.save_dir)\n\n from utils import plot_log\n\n plot_log(args.save_dir + \"/log.csv\", show=True)\n\n return model\n\n\ndef test(model, data, args):\n x_test, y_test = data\n y_pred, x_recon = model.predict(x_test, batch_size=100)\n print(\"-\" * 30 + \"Begin: test\" + \"-\" * 30)\n print(\n \"Test acc:\",\n np.sum(np.argmax(y_pred, 1) == np.argmax(y_test, 1)) / y_test.shape[0],\n )\n\n img = combine_images(np.concatenate([x_test[:50], x_recon[:50]]))\n image = img * 255\n Image.fromarray(image.astype(np.uint8)).save(args.save_dir + \"/real_and_recon.png\")\n print()\n print(\"Reconstructed images are saved to %s/real_and_recon.png\" % args.save_dir)\n print(\"-\" * 30 + \"End: test\" + \"-\" * 30)\n plt.imshow(plt.imread(args.save_dir + \"/real_and_recon.png\"))\n plt.show()\n\n\ndef manipulate_latent(model, data, args):\n print(\"-\" * 30 + \"Begin: manipulate\" + \"-\" * 30)\n x_test, y_test = data\n index = np.argmax(y_test, 1) == args.digit\n number = np.random.randint(low=0, high=sum(index) - 1)\n x, y = x_test[index][number], y_test[index][number]\n x, y = np.expand_dims(x, 0), np.expand_dims(y, 0)\n noise = np.zeros([1, 10, 16])\n x_recons = []\n for dim in range(16):\n for r in [-0.25, -0.2, -0.15, -0.1, -0.05, 0, 0.05, 0.1, 0.15, 0.2, 0.25]:\n tmp = np.copy(noise)\n tmp[:, :, dim] = r\n x_recon = model.predict([x, y, tmp])\n x_recons.append(x_recon)\n\n x_recons = np.concatenate(x_recons)\n\n img = combine_images(x_recons, height=16)\n image = img * 255\n Image.fromarray(image.astype(np.uint8)).save(\n args.save_dir + \"/manipulate-%d.png\" % args.digit\n )\n print(\n \"manipulated result saved to %s/manipulate-%d.png\" % (args.save_dir, args.digit)\n )\n print(\"-\" * 30 + \"End: manipulate\" + \"-\" * 30)\n\n\ndef load_mnist():\n # the data, shuffled and split between train and test sets\n from keras.datasets import mnist\n\n (x_train, y_train), (x_test, y_test) = mnist.load_data()\n\n x_train = x_train.reshape(-1, 28, 28, 1).astype(\"float32\") / 255.\n x_test = x_test.reshape(-1, 28, 28, 1).astype(\"float32\") / 255.\n y_train = to_categorical(y_train.astype(\"float32\"))\n y_test = to_categorical(y_test.astype(\"float32\"))\n return (x_train, y_train), (x_test, y_test)\n\n\ndef load_cifar10():\n from keras.datasets import cifar10\n\n (x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\n x_train = x_train.reshape(-1, 32, 32, 3).astype(\"float32\") / 255.\n x_test = x_test.reshape(-1, 32, 32, 3).astype(\"float32\") / 255.\n y_train = to_categorical(y_train.astype(\"float32\"))\n y_test = to_categorical(y_test.astype(\"float32\"))\n return (x_train, y_train), (x_test, y_test)\n\n\nif __name__ == \"__main__\":\n import os\n import argparse\n from keras.preprocessing.image import ImageDataGenerator\n from keras import callbacks\n\n # setting the hyper parameters\n parser = argparse.ArgumentParser(description=\"Capsule Network on CIFAR-10.\")\n parser.add_argument(\"--epochs\", default=50, type=int)\n parser.add_argument(\"--batch_size\", default=100, type=int)\n parser.add_argument(\"--lr\", default=0.001, type=float, help=\"Initial learning rate\")\n parser.add_argument(\n \"--lr_decay\",\n default=0.9,\n type=float,\n help=\"The value multiplied by lr at each epoch. Set a larger value for larger epochs\",\n )\n parser.add_argument(\n \"--lam_recon\",\n default=0.392,\n type=float,\n help=\"The coefficient for the loss of decoder\",\n )\n parser.add_argument(\n \"-r\",\n \"--routings\",\n default=3,\n type=int,\n help=\"Number of iterations used in routing algorithm. should > 0\",\n )\n parser.add_argument(\n \"--shift_fraction\",\n default=0,\n type=float,\n help=\"Fraction of pixels to shift at most in each direction.\",\n )\n parser.add_argument(\n \"--debug\", action=\"store_true\", help=\"Save weights by TensorBoard\"\n )\n parser.add_argument(\"--save_dir\", default=\"./result\")\n parser.add_argument(\n \"-t\",\n \"--testing\",\n action=\"store_true\",\n help=\"Test the trained model on testing dataset\",\n )\n parser.add_argument(\"--digit\", default=5, type=int, help=\"Digit to manipulate\")\n parser.add_argument(\n \"-w\",\n \"--weights\",\n default=None,\n help=\"The path of the saved weights. Should be specified when testing\",\n )\n parser.add_argument('--data_augmentation', dest='data_augmentation', action='store_true')\n parser.add_argument('--no-data_augmentation', dest='data_augmentation', action='store_false')\n parser.set_defaults(data_augmentation=False)\n parser.add_argument(\n \"--dataset\", default=\"mnist\", help=\"Available datasets: {'mnist'}, 'cifar10'.\"\n )\n args = parser.parse_args()\n print(f\"\\nargs: {args}\\n\")\n\n if not os.path.exists(args.save_dir):\n os.makedirs(args.save_dir)\n\n # load data\n if args.dataset == \"mnist\":\n (x_train, y_train), (x_test, y_test) = load_mnist()\n elif args.dataset == \"cifar10\":\n (x_train, y_train), (x_test, y_test) = load_cifar10()\n else:\n raise ValueError(\"Available datasets: 'mnist', 'cifar10'.\")\n\n (x_train, y_train), (x_test, y_test) = load_cifar10()\n\n # define model\n model, eval_model, manipulate_model = CapsNet(\n input_shape=x_train.shape[1:],\n n_class=len(np.unique(np.argmax(y_train, 1))),\n routings=args.routings,\n )\n model.summary()\n\n # train or test\n if args.weights is not None: # init the model weights with provided one\n model.load_weights(args.weights)\n if not args.testing:\n train(model=model, data=((x_train, y_train), (x_test, y_test)), args=args)\n else: # as long as weights are given, will run testing\n if args.weights is None:\n print(\n \"No weights are provided. Will test using random initialized weights.\"\n )\n manipulate_latent(manipulate_model, (x_test, y_test), args)\n test(model=eval_model, data=(x_test, y_test), args=args)\n"
] |
[
[
"numpy.expand_dims",
"matplotlib.pyplot.imread",
"numpy.concatenate",
"numpy.copy",
"numpy.argmax",
"numpy.prod",
"matplotlib.pyplot.show",
"numpy.zeros"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Yifei-Liu/uts
|
[
"64c137d59fcd0c7c016082018d67a56abac0b28e",
"64c137d59fcd0c7c016082018d67a56abac0b28e"
] |
[
"test/test_sma.py",
"uts/zscore.py"
] |
[
"import unittest\r\nimport numpy as np\r\nimport numpy.testing as npt\r\n\r\nfrom uts import sma\r\n\r\n\r\nclass TestEMA(unittest.TestCase):\r\n def test_sma_last(self):\r\n values = np.array([[0.0, 0.0], [1.0, 2.0],\r\n [1.2, 4.0], [2.3, 6], [2.9, 8], [5, 10]])\r\n result = sma.last(values, 2.5, 1.0)\r\n desired = np.array([[0.0, 0.0], [1.0, 1.03],\r\n [1.2, 1.26], [2.3, 3.31], [2.9, 4.69], [5, 8.34]])\r\n npt.assert_almost_equal(result, desired, decimal=2)\r\n \r\n def test_sma_next(self):\r\n values = np.array([[0.0, 0.0], [1.0, 2.0],\r\n [1.2, 4.0], [2.3, 6], [2.9, 8], [5, 10]])\r\n result = sma.next(values, 2.5, 1.0)\r\n desired = np.array([[0.0, 0.0], [1.0, 1.71],\r\n [1.2, 1.94], [2.3, 4.97], [2.9, 6.11], [5, 9.77]])\r\n npt.assert_almost_equal(result, desired, decimal=2)\r\n \r\n def test_sma_linear(self):\r\n values = np.array([[0.0, 0.0], [1.0, 2.0],\r\n [1.2, 4.0], [2.3, 6], [2.9, 8], [5, 10]])\r\n result = sma.linear(values, 2.5, 1.0)\r\n desired = np.array([[0.0, 0.0], [1.0, 1.54],\r\n [1.2, 1.86], [2.3, 4.16], [2.9, 5.60], [5, 9.10]])\r\n npt.assert_almost_equal(result, desired, decimal=2)\r\n\r\n\r\nif __name__ == '__main__':\r\n unittest.main()",
"# coding: utf-8\n\n__author__ = 'Mário Antunes'\n__version__ = '0.1'\n__email__ = '[email protected]'\n__status__ = 'Development'\n\n\nimport math\nimport numpy as np\n\n\ndef weighted_avg_and_std(values: np.ndarray, weights: np.ndarray):\n \"\"\"\n Return the weighted average and standard deviation.\n \n Args:\n points (np.ndarray): numpy array with values\n weights (np.ndarray): numpy array with weights\n \n Returns:\n tuple[float, float]: returns a tuple with the weighted average and standard deviation\n \"\"\"\n average = np.average(values, weights=weights)\n # Fast and numerically precise:\n variance = np.average((values-average)**2, weights=weights)\n return (average, math.sqrt(variance))\n\n\ndef zscore(xi: float, mean: float, std: float) -> float:\n \"\"\"\n Return the z-score for a single value.\n \n Args:\n xi (float): the single value\n mean (float): mean value from the sequence\n std (float): standart deviation from the sequence\n \n Returns:\n float: the z-score for a single value\n \"\"\"\n if std != 0:\n return (xi - mean)/std\n else:\n return xi - mean\n\n\ndef linear_delta_mapping_points(points: np.ndarray):\n \"\"\"\n Return a linear mapping from the sequence of points.\n\n One way to estimate the z-score metric from a uneven sequence\n is to map the values linearly and compute the weight of each new value.\n The weight is proportional to the delta in the x axis.\n \n Args:\n points (np.ndarray): numpy array with the points (x, y)\n \n Returns:\n tuple[np.ndarray, np.ndarray]: the weight and the linear mapping\n \"\"\"\n x = points[:, 0]\n y = points[:, 1]\n return linear_delta_mapping(x, y)\n\n\ndef linear_delta_mapping(x: np.ndarray, y: np.ndarray):\n \"\"\"\n Return a linear mapping from the sequence of points.\n\n One way to estimate the z-score metric from a uneven sequence\n is to map the values linearly and compute the weight of each new value.\n The weight is proportional to the delta in the x axis.\n \n Args:\n x (np.ndarray): values from the x axis\n y (np.ndarray): values from the y axis\n \n Returns:\n tuple[np.ndarray, np.ndarray]: the weight and the linear mapping\n \"\"\"\n tdelta = x[1:] - x[:-1]\n linear_values = (y[1:] + y[:-1]) / 2.0\n return tdelta, linear_values\n\n\ndef zscore_linear(xi: float, points: np.ndarray) -> float:\n \"\"\"\n Return the z-score for a single value, using the linear mapping\n to deal with the uneven sequence of values.\n \n Args:\n xi (float): the single value\n points (np.ndarray): numpy array with the points (x, y)\n \n Returns:\n float: the z-score for a single value\n \n Raises:\n ValueError: If the lenght of points is smaller than 2.\n \"\"\"\n if len(points) <= 1:\n raise ValueError('The number of points is smaller than 2')\n\n weights, values = linear_delta_mapping_points(points)\n mean, std = weighted_avg_and_std(values, weights)\n return zscore(xi, mean, std)\n\n\ndef zscore_array_points(points: np.ndarray) -> np.ndarray:\n \"\"\"\n Returns the z-score value for all the values in the sequence.\n\n It uses linear mapping to deal with the uneven sequence.\n \n Args:\n points (np.ndarray): numpy array with the points (x, y)\n \n Returns:\n np.ndarray: the z-score value for all the values in the sequence\n \"\"\"\n x = points[:, 0]\n y = points[:, 1]\n return zscore_array(x, y)\n\n\ndef zscore_array(x: np.ndarray, y: np.ndarray) -> np.ndarray:\n \"\"\"\n Returns the z-score value for all the values in the sequence.\n\n It uses linear mapping to deal with the uneven sequence.\n \n Args:\n x (np.ndarray): values from the x axis\n y (np.ndarray): values from the y axis\n \n Returns:\n np.ndarray: the z-score value for all the values in the sequence\n \"\"\"\n weights, values = linear_delta_mapping(x, y)\n mean, std = weighted_avg_and_std(values, weights)\n if std != 0.0:\n return (y - mean)/std\n else:\n return y - mean\n"
] |
[
[
"numpy.testing.assert_almost_equal",
"numpy.array"
],
[
"numpy.average"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
pnlbwh/BRAINSTools
|
[
"f09f74bd28ad07cd2347c2528921b1a43b97fa1d"
] |
[
"AutoWorkup/logismosb/utils/fs_thickness_measurements.py"
] |
[
"\"\"\"\nfs_thickness_measurements.py\n==============================\nDescription:\n\nAuthor:\n\nUsage:\n\n\"\"\"\nimport vtk\nimport SimpleITK as sitk\nimport numpy as np\nfrom scipy.spatial import distance\nfrom nipype.interfaces.freesurfer import MRIsConvert\nimport os\nimport sys\n\n\ndef read_poly_data(filename):\n \"\"\"\n This function..\n\n :param filename:\n :return:\n \"\"\"\n # Check which PolyData reader should be used\n if \".vtk\" in filename:\n reader = vtk.vtkPolyDataReader()\n reader.SetFileName(filename)\n reader.Update()\n return reader.GetOutput()\n elif \".vtp\" in filename:\n reader = vtk.vtkXMLPolyDataReader()\n reader.SetFileName(filename)\n reader.Update()\n return reader.GetOutput()\n else:\n print(\"ERROR: Failed to read in polydata\")\n return sys.exit(os.EX_IOERR)\n\n\ndef ras_to_lps(point):\n \"\"\"\n This function..\n\n :param point:\n :return:\n \"\"\"\n surf_x, surf_y, surf_z = point\n point = (-surf_x, -surf_y, surf_z) # must flip y axis to convert from VTK to ITK\n return point\n\n\n# Find the label of a given vtk point from a label map\ndef vtk_point_to_label(point, labelmap):\n \"\"\"\n This function..\n\n :param point:\n :param labelmap:\n :return:\n \"\"\"\n point = ras_to_lps(point)\n index = labelmap.TransformPhysicalPointToIndex(point)\n x = int(index[0])\n y = int(index[1])\n z = int(index[2])\n return labelmap.GetPixel(x, y, z)\n\n\ndef build_kd_tree(mesh):\n \"\"\"\n This function..\n\n :param mesh:\n :return:\n \"\"\"\n kd_tree = vtk.vtkKdTreePointLocator()\n kd_tree.SetDataSet(mesh)\n kd_tree.BuildLocator()\n return kd_tree\n\n\ndef convert_fs_surface(in_surf, out_surf, to_scanner=True):\n \"\"\"\n This function..\n\n :param in_surf:\n :param out_surf:\n :param to_scanner:\n :return:\n \"\"\"\n if os.path.isfile(os.path.abspath(out_surf)):\n return os.path.abspath(out_surf)\n mris_convert = MRIsConvert()\n mris_convert.inputs.in_file = in_surf\n mris_convert.inputs.out_file = os.path.abspath(out_surf)\n mris_convert.inputs.to_scanner = to_scanner\n result = mris_convert.run()\n return result.outputs.converted\n\n\ndef get_vtk_file_name(fs_file_name):\n \"\"\"\n This function..\n\n :param fs_file_name:\n :return:\n \"\"\"\n fs_dir, fs_basename = os.path.split(fs_file_name)\n return os.path.join(fs_dir, fs_basename.replace(\".\", \"_\") + \".vtk\")\n\n\ndef fs_to_vtk(fs_surface):\n \"\"\"\n This function..\n\n :param fs_surface:\n :return:\n \"\"\"\n output_file = get_vtk_file_name(fs_surface)\n return convert_fs_surface(fs_surface, output_file)\n\n\ndef get_surf(surf_dir, hemisphere, surf):\n \"\"\"\n This function..\n\n :param surf_dir:\n :param hemisphere:\n :param surf:\n :return:\n \"\"\"\n return os.path.join(surf_dir, \"{0}.{1}\".format(hemisphere, surf))\n\n\ndef get_white(surf_dir, hemisphere):\n \"\"\"\n This function..\n\n :param surf_dir:\n :param hemisphere:\n :return:\n \"\"\"\n return get_surf(surf_dir, hemisphere, \"white\")\n\n\ndef get_pial(surf_dir, hemisphere):\n \"\"\"\n This function..\n :param surf_dir:\n :param hemisphere:\n :return:\n \"\"\"\n return get_surf(surf_dir, hemisphere, \"pial\")\n\n\ndef get_white_and_pial_fs_files(surf_dir, hemisphere):\n \"\"\"\n This function..\n\n :param surf_dir:\n :param hemisphere:\n :return:\n \"\"\"\n fs_white = get_white(surf_dir, hemisphere)\n fs_pial = get_pial(surf_dir, hemisphere)\n return fs_white, fs_pial\n\n\ndef get_white_and_pial_vtk_files(surf_dir, hemisphere):\n \"\"\"\n This function..\n\n :param surf_dir:\n :param hemisphere:\n :return:\n \"\"\"\n fs_white, fs_pial = get_white_and_pial_fs_files(surf_dir, hemisphere)\n return fs_to_vtk(fs_white), fs_to_vtk(fs_pial)\n\n\ndef get_white_and_pial(surf_dir, hemisphere):\n \"\"\"\n This function..\n\n :param surf_dir:\n :param hemisphere:\n :return:\n \"\"\"\n vtk_white, vtk_pial = get_white_and_pial_vtk_files(surf_dir, hemisphere)\n white = read_poly_data(vtk_white)\n pial = read_poly_data(vtk_pial)\n return white, pial\n\n\ndef compute_thickness(wmP, kdTreegm, kdTreewm):\n \"\"\"\n This function..\n\n :param wmP:\n :param kdTreegm:\n :param kdTreewm:\n :return:\n \"\"\"\n # Find the closest point to the gray matter surface point\n gmIndex = kdTreegm.FindClosestPoint(wmP)\n gmP = kdTreegm.GetDataSet().GetPoint(gmIndex)\n # compute the distance\n # distance from wm point to gm point\n dst1 = distance.euclidean(wmP, gmP)\n wmIndex = kdTreewm.FindClosestPoint(gmP)\n wmP2 = kdTreegm.GetDataSet().GetPoint(wmIndex)\n # distnace from gm to closest wm point\n dst2 = distance.euclidean(gmP, wmP2)\n # average the two distances\n thickness = (dst1 + dst2) / float(2)\n return thickness\n\n\ndef create_thickness_array():\n \"\"\"\n This function..\n\n :return:\n \"\"\"\n thicknesses = vtk.vtkFloatArray()\n thicknesses.SetName(\"thickness\")\n return thicknesses\n\n\ndef calculate_distance(white, pial):\n \"\"\"\n This function..\n\n :param white:\n :param pial:\n :return:\n \"\"\"\n # setup KdTrees for each surface\n # this will help in finding the closest points\n kd_tree_white = build_kd_tree(white)\n kd_tree_pial = build_kd_tree(pial)\n\n white_points = white.GetPoints()\n white_count = white.GetNumberOfPoints()\n white_point_data = white.GetPointData()\n thicknesses = create_thickness_array()\n\n for i in range(0, white_count):\n white_matter_point = white_points.GetPoint(i)\n\n # compute the thickness\n thickness = compute_thickness(white_matter_point, kd_tree_pial, kd_tree_white)\n thicknesses.InsertNextValue(thickness)\n\n white_point_data.AddArray(thicknesses)\n return white\n\n\ndef get_surf_dir(subjects_dir, subject_id):\n \"\"\"\n This function..\n\n :param subjects_dir:\n :param subject_id:\n :return:\n \"\"\"\n return os.path.join(subjects_dir, subject_id, \"surf\")\n\n\ndef write_vtk_file(polydata, file_name):\n \"\"\"\n This function..\n\n :param polydata:\n :param file_name:\n :return:\n \"\"\"\n writer = vtk.vtkPolyDataWriter()\n writer.SetFileName(file_name)\n writer.SetInputData(polydata)\n writer.Update()\n return os.path.abspath(writer.GetFileName())\n\n\ndef get_thickness_file(subjects_dir, subject_id, hemisphere):\n \"\"\"\n This function..\n\n :param subjects_dir:\n :param subjects_id:\n :param hemisphere:\n :return:\n \"\"\"\n surf_dir = get_surf_dir(subjects_dir, subject_id)\n white, pial = get_white_and_pial(surf_dir, hemisphere)\n thickness = calculate_distance(white, pial)\n return write_vtk_file(\n thickness, os.path.join(surf_dir, \"{0}_thickness.vtk\".format(hemisphere))\n )\n\n\ndef get_thickness_files_for_both_hemispheres(subjects_dir, subject_id):\n \"\"\"\n This function..\n\n :param subjects_dir:\n :param subjects_id:\n :return:\n \"\"\"\n lh_thickness = get_thickness_file(subjects_dir, subject_id, \"lh\")\n rh_thickness = get_thickness_file(subjects_dir, subject_id, \"rh\")\n return lh_thickness, rh_thickness\n\n\ndef masked_thickness_values(thickness_file, mask_image_file, array_index=None):\n \"\"\"\n This function..\n\n :param thickness_file:\n :param mask_file:\n :param array_index:\n :return:\n \"\"\"\n thickness = read_poly_data(thickness_file)\n mask = sitk.ReadImage(mask_image_file)\n\n inside_mask_values = list()\n outside_mask_values = list()\n\n thickness_point_data = thickness.GetPointData()\n if not array_index:\n # set the array index to the last array added to the poly data\n array_index = thickness_point_data.GetNumberOfArrays() - 1\n thickness_values = thickness.GetPointData().GetArray(array_index)\n\n for point_index in range(thickness.GetNumberOfPoints()):\n point = thickness.GetPoint(point_index)\n mask_value = vtk_point_to_label(point, mask)\n thickness_value = thickness_values.GetValue(point_index)\n if mask_value == 1:\n inside_mask_values.append(thickness_value)\n else:\n outside_mask_values.append(thickness_value)\n return inside_mask_values, outside_mask_values\n\n\ndef calculate_stats(values):\n \"\"\"\n This function..\n\n :param values:\n :return:\n \"\"\"\n if values:\n values_array = np.array(values)\n return dict(\n mean=values_array.mean(),\n std=values_array.std(),\n min=values_array.min(),\n max=values_array.max(),\n )\n else:\n return dict(mean=None, std=None, min=None, max=None)\n\n\ndef masked_thickness_stats(thickness_file, mask_image_file):\n \"\"\"\n This function..\n\n :param thickness_file:\n :param mask_image_file:\n :return:\n \"\"\"\n inside_mask_values, outside_mask_values = masked_thickness_values(\n thickness_file, mask_image_file\n )\n stats = dict()\n stats[\"inside\"] = calculate_stats(inside_mask_values)\n stats[\"outside\"] = calculate_stats(outside_mask_values)\n return stats\n\n\ndef get_thickness_stats_for_both_hemispheres(subjects_dir, subject_id, mask_file):\n \"\"\"\n This function..\n\n :param subject_id:\n :param subjects_dir:\n :param mask_file:\n :return:\n \"\"\"\n stats = dict()\n lh_thickness, rh_thickness = get_thickness_files_for_both_hemispheres(\n subjects_dir, subject_id\n )\n stats[\"lh\"] = masked_thickness_stats(lh_thickness, mask_file)\n stats[\"rh\"] = masked_thickness_stats(rh_thickness, mask_file)\n return stats\n\n\ndef main():\n \"\"\"\n This function..\n \"\"\"\n os.environ[\n \"PATH\"\n ] += \":/Shared/sinapse/sharedopt/apps/freesurfer/Darwin/x86_64/6.0-beta/20150915/bin/\"\n mask_file = \"/Shared/sinapse/CACHE/20160712_AtrophySimulation_Results/2559/58661/simulation_1/atrophy_regions.nii.gz\"\n subj_dir = \"/Shared/sinapse/CACHE/20160713_AtrophySimulation_BAW_base_Results/PHD_024/2559_58661/79/\"\n print(get_thickness_stats_for_both_hemispheres(subj_dir, \"FreeSurfer\", mask_file))\n print(\"done\")\n\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"numpy.array",
"scipy.spatial.distance.euclidean"
]
] |
[
{
"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": []
}
] |
check-spelling/jdaviz
|
[
"e02c08d68ef71c5e40600785f46e65e5ae95e236"
] |
[
"jdaviz/configs/cubeviz/plugins/tests/test_data_retrieval.py"
] |
[
"import pytest\nimport numpy as np\n\nfrom astropy.utils.data import download_file\n\nfrom jdaviz.app import Application\n\n# This file is originally from\n# https://data.sdss.org/sas/dr14/manga/spectro/redux/v2_1_2/7495/stack/manga-7495-12704-LOGCUBE.fits.gz\nURL = 'https://stsci.box.com/shared/static/28a88k1qfipo4yxc4p4d40v4axtlal8y.fits'\n\n\n\"\"\" The purpose of this test is to check that both methods:\n\n - app.get_viewer('spectrum-viewer').data()\n - app.get_data_from_viewer(\"spectrum-viewer\")\n\n return the same spectrum values.\n\"\"\"\n\n\[email protected]\ndef jdaviz_app():\n return Application(configuration='cubeviz')\n\n\[email protected]('ignore')\[email protected]_data\ndef test_data_retrieval(jdaviz_app):\n\n fn = download_file(URL, cache=True)\n jdaviz_app.load_data(fn)\n\n # two ways of retrieving data from the viewer.\n # They should return the same spectral values\n a1 = jdaviz_app.get_viewer('spectrum-viewer').data()\n a2 = jdaviz_app.get_data_from_viewer(\"spectrum-viewer\")\n\n test_value_1 = a1[0].data\n test_value_2 = list(a2.values())[0].data\n\n assert np.allclose(test_value_1, test_value_2, atol=1e-5)\n"
] |
[
[
"numpy.allclose"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
HermitSun/ML_for_learner
|
[
"3014c641800c1408668ff243395bde752c45ec43"
] |
[
"tree/ID3_Clf.py"
] |
[
"import pandas as pd\nimport numpy as np\n\nclass ID3:\n def __init__(self):\n self.tree = None\n self.dataset = None\n\n def __entropy(self, feature):\n uni_val, cnt = np.unique(feature, return_counts=True) # 返回独特值与计数\n # 熵的计算\n H = np.sum([(-cnt[i] / np.sum(cnt)) * np.log2(cnt[i] / np.sum(cnt))\n for i in range(len(uni_val))])\n return H\n\n def __InfoGain(self, dataset, f_test_col, Y_col=-1):\n entropy_before = self.__entropy(dataset.iloc[:, Y_col]) # 分割前的熵\n\n uni_val, cnt = np.unique(dataset.iloc[:, f_test_col], return_counts=True) # 计算分割特征的独特值与计数\n entropy_cond = np.sum([(cnt[i] / np.sum(cnt)) * self.__entropy(dataset.where(dataset.iloc[:, f_test_col]\n == uni_val[i]).dropna().iloc[:,\n Y_col])\n for i in range(len(uni_val))])\n return entropy_before - entropy_cond\n\n def __gen_tree(self, dataset, org_dataset, f_cols, Y_col=-1, p_node_cls=None):\n '''\n dataset: 用于分割的数据\n org_dataset: 最原始的数据,全部数据\n f_cols: 备选特征\n '''\n # 如果数据中的Y已经纯净了,则返回Y的取值\n if len(np.unique(dataset.iloc[:, Y_col])) <= 1:\n return np.unique(dataset.iloc[:, Y_col])[0]\n\n # 如果传入数据为空(对应空叶节点),则返回原始数据中数量较多的label值\n elif len(dataset) == 0:\n uni_cls, cnt = np.unique(\n org_dataset.iloc[:, Y_col], return_counts=True)\n return uni_cls[np.argmax(cnt)]\n\n # 如果没有特征可用于划分,则返回父节点中数量较多的label值\n # 由于初始传入的是Index类型,所以这里不能用if not\n elif len(f_cols) == 0:\n return p_node_cls\n\n # 否则进行分裂\n else:\n # 得到当前节点中数量最多的label,递归时会赋给下层函数的p_node_cls\n cur_uni_cls, cnt = np.unique(\n dataset.iloc[:, Y_col], return_counts=True)\n cur_node_cls = cur_uni_cls[np.argmax(cnt)]\n del cur_uni_cls, cnt\n\n # 根据信息增益选出最佳分裂特征\n gains = [self.__InfoGain(dataset, f_col, Y_col) for f_col in f_cols]\n best_f = f_cols[np.argmax(gains)]\n\n # 更新备选特征\n f_cols = [col for col in f_cols if col != best_f]\n\n # 按最佳特征的不同取值,划分数据集并递归\n tree = {best_f: {}}\n for val in np.unique(dataset.iloc[:, best_f]): # ID3对每一个取值都划分数据集\n sub_data = dataset.where(dataset.iloc[:, best_f] == val).dropna()\n sub_tree = self.__gen_tree(sub_data, dataset, f_cols, Y_col, cur_node_cls)\n tree[best_f][val] = sub_tree # 分裂特征的某一取值,对应一颗子树或叶节点\n\n return tree\n\n def fit(self, X_train, Y_train):\n dataset = np.c_[X_train, Y_train]\n self.dataset = pd.DataFrame(dataset, columns=list(range(dataset.shape[1])))\n self.tree = self.__gen_tree(self.dataset, self.dataset, list(range(self.dataset.shape[1] - 1)))\n\n def __predict_one(self, x_test, tree, default=-1):\n '''\n query:一个测试样本,字典形式,{f:val,f:val,...}\n tree:训练生成树\n default:查找失败时返回的默认类别\n '''\n for feature in list(x_test.keys()):\n if feature in list(tree.keys()): # 如果该特征与根节点的划分特征相同\n try:\n sub_tree = tree[feature][x_test[feature]] # 根据特征的取值来获取左右分支\n\n if isinstance(sub_tree, dict): # 判断是否还有子树\n return self.__predict_one(x_test, tree=sub_tree) # 有则继续查找\n else:\n return sub_tree # 是叶节点则返回结果\n except: # 没有查到则说明是未见过的情况,只能返回default\n return default\n\n def predict(self, X_test):\n X_test = pd.DataFrame(X_test, columns=list(range(X_test.shape[1]))).to_dict(orient='record')\n Y_pred = list()\n for item in X_test:\n Y_pred.append(self.__predict_one(item, tree=self.tree))\n return Y_pred\n\n\ndef load_zoo():\n '''\n 返回一个sklearn-like的数据集\n '''\n from collections import namedtuple\n df = pd.read_csv('../utils/dataset/UCI_Zoo_Data_Set/zoo.data.csv', header=None)\n df = df.drop([0], axis=1) # 首列是animal_name,丢弃\n\n dataClass = namedtuple('data', ['data', 'target'])\n dataClass.data = df.iloc[:, :-1].values\n dataClass.target = df.iloc[:, -1].values\n\n return dataClass\n\n\nif __name__ == '__main__':\n from model_selection.train_test_split import train_test_split\n\n data = load_zoo()\n X = data.data\n Y = data.target\n\n X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2)\n\n id3_tree = ID3()\n id3_tree.fit(X_train, Y_train)\n\n Y_pred = id3_tree.predict(X_test)\n print('acc:{}'.format(np.sum(np.array(Y_test) == np.array(Y_pred)) / len(Y_test)))\n"
] |
[
[
"pandas.read_csv",
"numpy.unique",
"numpy.argmax",
"numpy.array",
"numpy.sum"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
bearcatt/single-shot-detector
|
[
"649d55aa84f1c988afd920ed8abc601512405825"
] |
[
"train.py"
] |
[
"import os\nimport tensorflow as tf\nimport json\nfrom model import model_fn, RestoreMovingAverageHook\nfrom detector.input_pipeline import Pipeline\ntf.logging.set_verbosity('INFO')\n\n\n\"\"\"\nThis script does the training.\nAlso it runs the evaluation now and then during the training.\n\"\"\"\n\nGPU_TO_USE = '0'\nCONFIG = 'config.json' # 'config_mobilenet.json' or 'config_shufflenet.json'\nparams = json.load(open(CONFIG))\n\n\ndef get_input_fn(is_training=True):\n\n dataset_path = params['train_dataset'] if is_training else params['val_dataset']\n filenames = os.listdir(dataset_path)\n filenames = [n for n in filenames if n.endswith('.tfrecords')]\n filenames = [os.path.join(dataset_path, n) for n in sorted(filenames)]\n\n def input_fn():\n with tf.device('/cpu:0'), tf.name_scope('input_pipeline'):\n pipeline = Pipeline(filenames, is_training, params)\n return pipeline.dataset\n\n return input_fn\n\n\nsession_config = tf.ConfigProto(allow_soft_placement=True)\nsession_config.gpu_options.visible_device_list = GPU_TO_USE\nrun_config = tf.estimator.RunConfig()\nrun_config = run_config.replace(\n model_dir=params['model_dir'], session_config=session_config,\n save_summary_steps=600, save_checkpoints_secs=1800,\n log_step_count_steps=1000\n)\n\n\nif params['backbone'] == 'mobilenet':\n scope_to_restore = 'MobilenetV1/*'\nelif params['backbone'] == 'shufflenet':\n scope_to_restore = 'ShuffleNetV2/*'\nwarm_start = tf.estimator.WarmStartSettings(\n params['pretrained_checkpoint'], [scope_to_restore]\n)\n\n\ntrain_input_fn = get_input_fn(is_training=True)\nval_input_fn = get_input_fn(is_training=False)\nestimator = tf.estimator.Estimator(\n model_fn, params=params, config=run_config,\n warm_start_from=warm_start\n)\n\n\ntrain_spec = tf.estimator.TrainSpec(train_input_fn, max_steps=params['num_steps'])\neval_spec = tf.estimator.EvalSpec(\n val_input_fn, steps=None, start_delay_secs=3600 * 3, throttle_secs=3600 * 3,\n # TODO: remove this when not using ema\n hooks=[RestoreMovingAverageHook(params['model_dir'])]\n)\ntf.estimator.train_and_evaluate(estimator, train_spec, eval_spec)\n"
] |
[
[
"tensorflow.device",
"tensorflow.estimator.Estimator",
"tensorflow.ConfigProto",
"tensorflow.estimator.TrainSpec",
"tensorflow.logging.set_verbosity",
"tensorflow.name_scope",
"tensorflow.estimator.RunConfig",
"tensorflow.estimator.train_and_evaluate",
"tensorflow.estimator.WarmStartSettings"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
addman2/KvantSim
|
[
"7bfc56f909c6a007aac9ba973227f392c50b33e2"
] |
[
"Exercises/bin/dos.plot.py"
] |
[
"#!/usr/bin/env python\n\nimport sys\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nE, N = np.loadtxt(sys.argv[1], usecols = (0,1), unpack = True)\n\nplt.plot(E, N)\n\ntry:\n plt.plot([float(sys.argv[2])] * 2, [max(N),0.0],\"r-\")\nexcept:\n pass\n\nplt.xlim([min(E),max(E)])\nplt.ylim([0.0,max(N)])\n\nplt.plot(plt.xlim(),[0.0]*2,\"k-\")\n\nplt.savefig(sys.argv[1].replace(\"dos\",\"png\"))\n"
] |
[
[
"matplotlib.pyplot.plot",
"matplotlib.pyplot.xlim",
"numpy.loadtxt"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Andreas237/cvxportfolio
|
[
"46910e9ac62797ffc962bd090bea9bf8eb598053",
"46910e9ac62797ffc962bd090bea9bf8eb598053"
] |
[
"cvxportfolio/tests/test_what_if.py",
"cvxportfolio/risks.py"
] |
[
"\"\"\"\nCopyright 2016 Stephen Boyd, Enzo Busseti, Steven Diamond, BlackRock Inc.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nimport os\n\nimport cvxpy as cvx\nimport numpy as np\nimport pandas as pd\nimport copy\n\nfrom cvxportfolio import simulator, HcostModel, TcostModel, SinglePeriodOpt\nfrom cvxportfolio import ReturnsForecast, MultipleReturnsForecasts, FullSigma\nfrom .base_test import BaseTest\n\nDIR = os.path.dirname(__file__) + os.path.sep\n\n\nclass TestWhatIf(BaseTest):\n\n def setUp(self):\n self.sigma = pd.read_csv(DIR + 'sigmas.csv',\n index_col=0, parse_dates=[0])\n self.returns = pd.read_csv(DIR + 'returns.csv',\n index_col=0, parse_dates=[0])\n self.volume = pd.read_csv(DIR + 'volumes.csv',\n index_col=0, parse_dates=[0])\n self.a, self.b, self.s = 0.0005, 1., 0.\n self.universe = self.returns.columns\n self.times = self.returns.index\n\n def test_attribution(self):\n \"\"\"Test attribution.\n \"\"\"\n # Alpha source\n alpha_sources = [ReturnsForecast(\n self.returns, name=i) for i in range(3)]\n weights = np.array([0.1, 0.3, 0.6])\n alpha_model = MultipleReturnsForecasts(alpha_sources, weights)\n emp_Sigma = np.cov(self.returns.to_numpy().T)\n risk_model = FullSigma(emp_Sigma, gamma=100.)\n tcost_model = TcostModel(self.volume, self.sigma, self.a, self.b)\n hcost_model = HcostModel(self.s, self.s * 0)\n pol = SinglePeriodOpt(alpha_model, [risk_model, tcost_model,\n hcost_model], [],\n solver=cvx.ECOS)\n\n tcost = TcostModel(self.a, self.b, self.sigma, self.volume)\n hcost = HcostModel(self.s)\n market_sim = simulator.MarketSimulator(self.returns,\n costs=[tcost, hcost],\n market_volumes=self.volume)\n\n p_0 = pd.Series(index=self.universe, data=1E6)\n noisy = market_sim.run_backtest(p_0, self.returns.index[1],\n self.returns.index[10], pol)\n # linear fit attribution\n attr = market_sim.attribute(noisy, pol,\n parallel=False, fit=\"linear\")\n base_line = noisy.v - sum(p_0)\n for i in range(3):\n self.assertItemsAlmostEqual(\n attr[i] / weights[i] / sum(p_0), base_line / sum(p_0))\n self.assertItemsAlmostEqual(attr['RMS error'], np.zeros(len(noisy.v)))\n\n # least-squares fit attribution\n attr = market_sim.attribute(noisy, pol,\n parallel=False, fit=\"least-squares\")\n base_line = noisy.v - sum(p_0)\n for i in range(3):\n self.assertItemsAlmostEqual(\n attr[i] / weights[i] / sum(p_0), base_line / sum(p_0))\n # Residual always 0.\n alpha_sources = [ReturnsForecast(\n self.returns * 0, name=i) for i in range(3)]\n weights = np.array([0.1, 0.3, 0.6])\n alpha_model = MultipleReturnsForecasts(alpha_sources, weights)\n pol = copy.copy(pol)\n pol.alpha_model = alpha_model\n attr = market_sim.attribute(noisy, pol,\n parallel=False, fit=\"least-squares\")\n self.assertItemsAlmostEqual(attr['residual'], np.zeros(len(noisy.v)))\n\n def test_attribute_non_profit_series(self):\n \"\"\"Test attributing series quantities besides profit.\n \"\"\"\n # Alpha source\n alpha_sources = [ReturnsForecast(\n self.returns, name=i) for i in range(3)]\n weights = np.array([0.1, 0.3, 0.6])\n alpha_model = MultipleReturnsForecasts(alpha_sources, weights)\n emp_Sigma = np.cov(self.returns.to_numpy().T)\n risk_model = FullSigma(emp_Sigma, gamma=100.)\n tcost_model = TcostModel(self.a, self.b, self.sigma, self.volume)\n hcost_model = HcostModel(self.s, self.s * 0)\n pol = SinglePeriodOpt(alpha_model, [risk_model, tcost_model,\n hcost_model], [],\n solver=cvx.ECOS)\n\n tcost = TcostModel(self.volume, self.sigma, self.a, self.b)\n hcost = HcostModel(self.s)\n market_sim = simulator.MarketSimulator(self.returns,\n costs=[tcost, hcost],\n market_volumes=self.volume)\n\n p_0 = pd.Series(index=self.universe, data=1E6)\n noisy = market_sim.run_backtest(p_0, self.returns.index[1],\n self.returns.index[10], pol)\n # Select tcosts.\n\n def selector(result):\n return result.leverage\n\n # linear fit attribution\n attr = market_sim.attribute(noisy, pol, selector,\n parallel=False, fit=\"linear\")\n base_line = noisy.leverage\n for i in range(3):\n self.assertItemsAlmostEqual(\n attr[i] / weights[i] / sum(p_0), base_line / sum(p_0))\n self.assertItemsAlmostEqual(attr['RMS error'], np.zeros(len(noisy.v)))\n\n # least-squares fit attribution\n attr = market_sim.attribute(noisy, pol, selector,\n parallel=False, fit=\"least-squares\")\n for i in range(3):\n self.assertItemsAlmostEqual(\n attr[i] / weights[i] / sum(p_0), base_line / sum(p_0))\n # Residual always 0.\n alpha_sources = [ReturnsForecast(\n self.returns * 0, name=i) for i in range(3)]\n weights = np.array([0.1, 0.3, 0.6])\n alpha_model = MultipleReturnsForecasts(alpha_sources, weights)\n pol = copy.copy(pol)\n pol.alpha_model = alpha_model\n attr = market_sim.attribute(noisy, pol, selector,\n parallel=False, fit=\"least-squares\")\n self.assertItemsAlmostEqual(attr['residual'], np.zeros(len(noisy.v)))\n\n def test_attribute_non_profit_scalar(self):\n \"\"\"Test attributing scalar quantities besides profit.\n \"\"\"\n # Alpha source\n alpha_sources = [ReturnsForecast(\n self.returns, name=i) for i in range(3)]\n weights = np.array([0.1, 0.3, 0.6])\n alpha_model = MultipleReturnsForecasts(alpha_sources, weights)\n emp_Sigma = np.cov(self.returns.to_numpy().T)\n risk_model = FullSigma(emp_Sigma)\n tcost_model = TcostModel(self.a, self.b, self.sigma, self.volume)\n hcost_model = HcostModel(self.s)\n pol = SinglePeriodOpt(\n alpha_model, [100 * risk_model, tcost_model, hcost_model], [])\n\n market_sim = simulator.MarketSimulator(self.returns,\n costs=[tcost_model, hcost_model]\n )\n\n p_0 = pd.Series(index=self.universe, data=1E6)\n noisy = market_sim.run_backtest(p_0, self.returns.index[1],\n self.returns.index[10], pol)\n # Select tcosts.\n\n def selector(result):\n return pd.Series(index=[noisy.h.index[-1]],\n data=result.volatility)\n\n # linear fit attribution\n attr = market_sim.attribute(noisy, pol, selector,\n parallel=False, fit=\"linear\")\n base_line = noisy.volatility\n for i in range(3):\n self.assertAlmostEqual(\n attr[i][0] / weights[i] / sum(p_0), base_line / sum(p_0))\n self.assertItemsAlmostEqual(attr['RMS error'], np.zeros(len(noisy.v)))\n\n # least-squares fit attribution\n attr = market_sim.attribute(noisy, pol, selector,\n parallel=False, fit=\"least-squares\")\n for i in range(3):\n self.assertAlmostEqual(\n attr[i][0] / weights[i] / sum(p_0), base_line / sum(p_0))\n # Residual always 0.\n alpha_sources = [ReturnsForecast(\n self.returns * 0, name=i) for i in range(3)]\n weights = np.array([0.1, 0.3, 0.6])\n alpha_model = MultipleReturnsForecasts(alpha_sources, weights)\n pol = copy.copy(pol)\n pol.alpha_model = alpha_model\n attr = market_sim.attribute(noisy, pol, selector,\n parallel=False, fit=\"least-squares\")\n self.assertItemsAlmostEqual(attr['residual'], np.zeros(len(noisy.v)))\n",
"\"\"\"\nCopyright 2016 Stephen Boyd, Enzo Busseti, Steven Diamond, BlackRock Inc.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nfrom abc import abstractmethod\nimport logging\n\nimport cvxpy as cvx\nimport numpy as np\nimport pandas as pd\n\nfrom .costs import BaseCost\nfrom .utils import values_in_time\nlogger = logging.getLogger(__name__)\n\n\n__all__ = ['FullSigma', 'EmpSigma', 'SqrtSigma', 'WorstCaseRisk',\n 'RobustFactorModelSigma', 'RobustSigma', 'FactorModelSigma']\n\n\n# def locator(obj, t):\n# \"\"\"Picks last element before t.\"\"\"\n# try:\n# if isinstance(obj, pd.Panel):\n# return obj.iloc[obj.axes[0].get_loc(t, method='pad')]\n\n# elif isinstance(obj.index, pd.MultiIndex):\n# prev_t = obj.loc[:t, :].index.values[-1][0]\n# else:\n# prev_t = obj.loc[:t, :].index.values[-1]\n\n# return obj.loc[prev_t, :]\n\n# except AttributeError: # obj not pandas\n# return obj\n\n\nclass BaseRiskModel(BaseCost):\n\n def __init__(self, **kwargs):\n self.w_bench = kwargs.pop('w_bench', 0.)\n super(BaseRiskModel, self).__init__()\n self.gamma_half_life = kwargs.pop('gamma_half_life', np.inf)\n\n def weight_expr(self, t, w_plus, z, value):\n self.expression = self._estimate(t, w_plus - self.w_bench, z, value)\n return self.gamma * self.expression, []\n\n @abstractmethod\n def _estimate(self, t, w_plus, z, value):\n pass\n\n def weight_expr_ahead(self, t, tau, w_plus, z, value):\n \"\"\"Estimate risk model at time tau in the future.\"\"\"\n if self.gamma_half_life == np.inf:\n gamma_multiplier = 1.\n else:\n decay_factor = 2 ** (-1 / self.gamma_half_life)\n # TODO not dependent on days\n gamma_init = decay_factor ** ((tau - t).days)\n gamma_multiplier = gamma_init * \\\n (1 - decay_factor) / (1 - decay_factor)\n\n return gamma_multiplier * self.weight_expr(t, w_plus, z, value)[0], []\n\n def optimization_log(self, t):\n if self.expression.value:\n return self.expression.value\n else:\n return np.NaN\n\n\nclass FullSigma(BaseRiskModel):\n \"\"\"Quadratic risk model with full covariance matrix.\n\n Args:\n Sigma (:obj:`pd.Panel`): Panel of Sigma matrices,\n or single matrix.\n\n \"\"\"\n\n def __init__(self, Sigma, **kwargs):\n self.Sigma = Sigma # Sigma is either a matrix or a pd.Panel\n try:\n assert(not pd.isnull(Sigma).values.any())\n except AttributeError:\n assert (not pd.isnull(Sigma).any())\n super(FullSigma, self).__init__(**kwargs)\n\n def _estimate(self, t, wplus, z, value):\n try:\n self.expression = cvx.quad_form(\n wplus, values_in_time(self.Sigma, t))\n except TypeError:\n self.expression = cvx.quad_form(\n wplus, values_in_time(self.Sigma, t).values)\n return self.expression\n\n\nclass EmpSigma(BaseRiskModel):\n \"\"\"Empirical Sigma matrix, built looking at *lookback* past returns.\"\"\"\n\n def __init__(self, returns, lookback, **kwargs):\n \"\"\"returns is dataframe, lookback is int\"\"\"\n self.returns = returns\n self.lookback = lookback\n assert(not np.any(pd.isnull(returns)))\n super(EmpSigma, self).__init__(**kwargs)\n\n def _estimate(self, t, wplus, z, value):\n idx = self.returns.index.get_loc(t)\n # TODO make sure pandas + cvxpy works\n R = self.returns.iloc[max(idx - 1 - self.lookback, 0):idx - 1]\n assert (R.shape[0] > 0)\n self.expression = cvx.sum_squares(R.values * wplus) / self.lookback\n return self.expression\n\n\nclass SqrtSigma(BaseRiskModel):\n\n def __init__(self, sigma_sqrt, **kwargs):\n \"\"\"returns is dataframe, lookback is int\"\"\"\n self.sigma_sqrt = sigma_sqrt\n assert(not np.any(pd.isnull(sigma_sqrt)))\n super(SqrtSigma, self).__init__(**kwargs)\n\n def _estimate(self, t, wplus, z, value):\n # TODO make sure pandas + cvxpy works\n self.expression = cvx.sum_squares(wplus.T * self.sigma_sqrt.values)\n return self.expression\n\n\nclass FactorModelSigma(BaseRiskModel):\n\n def __init__(self, exposures, factor_Sigma, idiosync, **kwargs):\n \"\"\"Each is a pd.Panel (or ) or a vector/matrix\"\"\"\n self.exposures = exposures\n assert (not exposures.isnull().values.any())\n self.factor_Sigma = factor_Sigma\n assert (not factor_Sigma.isnull().values.any())\n self.idiosync = idiosync\n assert(not idiosync.isnull().values.any())\n super(FactorModelSigma, self).__init__(**kwargs)\n\n def _estimate(self, t, wplus, z, value):\n self.expression = cvx.sum_squares(cvx.multiply(\n np.sqrt(values_in_time(self.idiosync, t)), wplus)) + \\\n cvx.quad_form((wplus.T @ values_in_time(self.exposures, t).values.T).T,\n values_in_time(self.factor_Sigma, t).values)\n return self.expression\n\n\nclass RobustSigma(BaseRiskModel):\n \"\"\"Implements covariance forecast error risk.\"\"\"\n\n def __init__(self, Sigma, epsilon, **kwargs):\n self.Sigma = Sigma # pd.Panel or matrix\n self.epsilon = epsilon # pd.Series or scalar\n super(RobustSigma, self).__init__(**kwargs)\n\n def _estimate(self, t, wplus, z, value):\n self.expression = cvx.quad_form(wplus, values_in_time(self.Sigma, t)) + \\\n values_in_time(self.epsilon, t) * \\\n (cvx.abs(wplus).T * np.diag(values_in_time(\n self.Sigma, t)))**2\n\n return self.expression\n\n\nclass RobustFactorModelSigma(BaseRiskModel):\n \"\"\"Implements covariance forecast error risk.\"\"\"\n\n def __init__(self, exposures, factor_Sigma, idiosync, epsilon, **kwargs):\n \"\"\"Each is a pd.Panel (or ) or a vector/matrix\"\"\"\n self.exposures = exposures\n assert (not exposures.isnull().values.any())\n self.factor_Sigma = factor_Sigma\n assert (not factor_Sigma.isnull().values.any())\n self.idiosync = idiosync\n assert(not idiosync.isnull().values.any())\n self.epsilon = epsilon\n super(RobustFactorModelSigma, self).__init__(**kwargs)\n\n def _estimate(self, t, wplus, z, value):\n F = values_in_time(self.exposures, t)\n f = (wplus.T * F.T).T\n Sigma_F = values_in_time(self.factor_Sigma, t)\n D = values_in_time(self.idiosync, t)\n self.expression = cvx.sum_squares(\n cvx.multiply(np.sqrt(D), wplus)) + \\\n cvx.quad_form(f, Sigma_F) + \\\n self.epsilon * (cvx.abs(f).T * np.sqrt(np.diag(Sigma_F)))**2\n\n return self.expression\n\n\nclass WorstCaseRisk(BaseRiskModel):\n\n def __init__(self, riskmodels, **kwargs):\n self.riskmodels = riskmodels\n super(WorstCaseRisk, self).__init__(**kwargs)\n\n def _estimate(self, t, wplus, z, value):\n self.risks = [risk.weight_expr(t, wplus, z, value)\n for risk in self.riskmodels]\n return cvx.max_elemwise(*self.risks)\n\n def optimization_log(self, t):\n \"\"\"Return data to log in the result object.\"\"\"\n return pd.Series(index=[model.__class__.__name__ for\n model in self.riskmodels],\n data=[risk.value[0, 0] for risk in self.risks])\n"
] |
[
[
"numpy.array",
"pandas.read_csv",
"pandas.Series"
],
[
"numpy.diag",
"numpy.sqrt",
"pandas.Series",
"pandas.isnull"
]
] |
[
{
"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",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
wotmd5731/J_LAB
|
[
"6951dbc898f063fbbe2853a36b7caeeca10ed173",
"6951dbc898f063fbbe2853a36b7caeeca10ed173"
] |
[
"pytorch-r2d2_mini/r2d2.py",
"nearest_plot.py"
] |
[
"import torch\nimport torch.utils.data\nimport torch.optim as optim\nimport torch.nn as nn\nimport numpy as np\nfrom collections import deque\nimport random\nimport gym\nimport os\nfrom copy import deepcopy\nfrom time import time, sleep\nimport torch.multiprocessing as mp\n#mp.set_start_method('spawn', force=True)\nfrom models import ActorNet, CriticNet\nimport queue\nimport visdom\n\nvis = visdom.Visdom()\n\nos.system('cls')\n\n\nfrom actor import Actor, actor_process\nfrom learner import Learner, learner_process\nfrom models import ActorNet, CriticNet\n\nif __name__ == '__main__':\n vis.close()\n \n config = {\n 'game_name':'CartPole-v0',\n\n 'obs_space':(1,4),\n 'reward_space':(1,1),\n 'gamma_space':(1,1),\n 'action_space':(1,2),\n 'num_envs':1,\n 'use_cnn':False,\n# 'action_argmax':True,\n 'get_img_from_render':False,\n\n# 'obs_space':(1,3,84,84),\n# 'reward_space':(1,1),\n# 'gamma_space':(1,1),\n# 'action_space':(1,2),\n# 'num_envs':1,\n# 'use_cnn':True,\n# 'action_argmax':True,\n# 'get_img_from_render':True,\n# \n 'action_argmax':False,\n# 'game_name':'Pendulum-v0',\n# 'action_space':1,\n# 'obs_space':(1,3),\n 'burn_in_length':0,\n 'learning_length':1,\n 'n_step':1,\n 'memory_sequence_size':1000000,\n# 'actor_parameter_update_interval':2000,\n 'learner_parameter_update_interval':50,\n 'actor_lr':1e-4,\n 'critic_lr':1e-4,\n 'gamma':0.997,\n 'actor_max_frame':1000000,\n 'learner_max_frame':100000,\n 'batch_size':64,\n 'num_processes':1,\n \n 'learner_actor_rate':20,\n 'target_update_interval':50,\n 'max_shared_q_size':5,\n }\n\n\n num_processes = config['num_processes']\n use_cuda = torch.cuda.is_available()\n dev_cpu = torch.device('cpu')\n dev_gpu = torch.device('cuda' if use_cuda else 'cpu')\n\n \n# manager = mp.Manager()\n# shared_state = manager.dict()\n# shared_queue = manager.Queue()\n \n shared_queue = mp.Queue()\n \n# shared_queue = queue.Queue()\n shared_state = dict()\n \n\n shared_state[\"actor\"] = ActorNet(dev_cpu,config).share_memory()\n shared_state[\"critic\"] = CriticNet(dev_cpu,config).share_memory()\n shared_state[\"target_actor\"] = ActorNet(dev_cpu,config).share_memory()\n shared_state[\"target_critic\"] = CriticNet(dev_cpu,config).share_memory()\n# shared_state[\"frame\"] = mp.Array('i', [0 for i in range(num_processes)])\n# shared_state[\"sleep\"] = mp.Array('i', [0 for i in range(num_processes)])\n shared_state[\"update\"] = mp.Array('i', [0 for i in range(num_processes)])\n \n\n \n# shared_state[\"actor\"] = ActorNet(config['obs_space'], config['action_space'],dev_cpu)\n# shared_state[\"critic\"] = CriticNet(config['obs_space'], config['action_space'],dev_cpu)\n# shared_state[\"target_actor\"] = ActorNet(config['obs_space'], config['action_space'],dev_cpu)\n# shared_state[\"target_critic\"] = CriticNet(config['obs_space'], config['action_space'],dev_cpu)\n# shared_state[\"frame\"] = [0 for i in range(num_processes)]\n# shared_state[\"sleep\"] = [0 for i in range(num_processes)]\n# shared_state[\"update\"]=False\n \n# for i in range(10):\n# actor_process(0,config,dev_cpu,shared_state,shared_queue,0.3)\n# actor_process(1,config,dev_cpu,shared_state,shared_queue,0.3)\n# actor_process(2,config,dev_cpu,shared_state,shared_queue,0.3)\n# learner_process(1,config,dev_cpu,shared_state,shared_queue)\n\n\n#\n proc_list = []\n proc_list.append(mp.Process(target=learner_process, args=(num_processes, config,dev_cpu,shared_state,shared_queue)))\n eps = [0.10,0.6,0.4,0.3,0.2,0.6,0.4,0.6,0.2,0.4]\n for i in range(num_processes):\n proc_list.append( mp.Process(target=actor_process, args=(i,config,dev_cpu,shared_state,shared_queue,eps[i])) )\n\n\n for proc in proc_list:\n proc.start()\n \n try:\n for proc in proc_list:\n proc.join()\n except:\n print('qclose')\n shared_queue.close()\n# print('shared_state close')\n# shared_state[\"update\"].close()\n \n# for key in shared_state.keys():\n# shared_state[key].close()\n print('process close')\n for proc in proc_list:\n proc.terminate()\n \n \n shared_queue.join_thread()\n# shared_state[\"update\"].join_thread()\n# for key in shared_state.keys():\n# shared_state[key].join_thread()\n# shared_state.close()\n# shared_queue.close()\n \n \n",
"import numpy as np\nimport matplotlib.pyplot as plt\n\nfig,ax = plt.subplots(1,4,figsize=(10,5))\n\ndef nearest_plot(XX):\n global fig,ax\n for i,X in enumerate(XX):\n ax[i].imshow(X,interpolation='nearest')\n numrows,numcols=X.shape\n\n def format_coord(x,y):\n col = int(x+0.5)\n row = int(y+0.5)\n if col>=0 and col<numcols and row>=0 and row <numrows:\n z=X[row,col]\n return 'x=%1.4f, y=%1.4f, z=%1.4f' % (x,y,z)\n else:\n return 'x=%1.4f, y=%1.4f ' % (x,y)\n ax[i].format_coord= format_coord\n\n plt.pause(0.001)\n\n\nif __name__=='__main__':\n np.random.seed(1000)\n X=[10*np.random.rand(10,5) for i in range(4) ]\n nearest_plot(X)\n\n\n\n"
] |
[
[
"torch.device",
"torch.multiprocessing.Process",
"torch.multiprocessing.Queue",
"torch.cuda.is_available"
],
[
"numpy.random.rand",
"matplotlib.pyplot.subplots",
"numpy.random.seed",
"matplotlib.pyplot.pause"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Camilo-Mendoza/streamlit-ML
|
[
"be8aafdf9f334b92a6e056e6c4f994da82587f80",
"be8aafdf9f334b92a6e056e6c4f994da82587f80"
] |
[
"lib/streamlit/elements/data_frame_proto.py",
"e2e/scripts/map.py"
] |
[
"# -*- coding: utf-8 -*-\n# Copyright 2018-2019 Streamlit 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\n\"\"\"Helper functions to marshall a pandas.DataFrame into a proto.Dataframe.\"\"\"\n\nimport re\nimport tzlocal\n\nfrom collections import namedtuple\n\nfrom streamlit import util\nfrom streamlit.logger import get_logger\n\nLOGGER = get_logger(__name__)\n\nCSSStyle = namedtuple('CSSStyle', ['property', 'value'])\n\n\ndef marshall_data_frame(data, proto_df):\n \"\"\"Convert a pandas.DataFrame into a proto.DataFrame.\n\n Parameters\n ----------\n data : pandas.DataFrame, numpy.ndarray, Iterable, dict, DataFrame, Styler, or None\n Something that is or can be converted to a dataframe.\n\n proto_df : proto.DataFrame\n Output. The protobuf for a Streamlit DataFrame proto.\n \"\"\"\n df = convert_anything_to_df(data)\n\n # Convert df into an iterable of columns (each of type Series).\n df_data = (df.iloc[:, col] for col in range(len(df.columns)))\n\n import numpy as np\n import pandas as pd\n\n _marshall_table(df_data, proto_df.data)\n _marshall_index(df.columns, proto_df.columns)\n _marshall_index(df.index, proto_df.index)\n\n styler = data if _is_pandas_styler(data) else None\n _marshall_styles(proto_df.style, df, styler)\n\n\ndef convert_anything_to_df(df):\n \"\"\"Try to convert different formats to a Pandas Dataframe.\n\n Parameters\n ----------\n df : ndarray, Iterable, dict, DataFrame, Styler, None, or any\n\n Returns\n -------\n pandas.DataFrame\n\n \"\"\"\n if util.is_type(df, 'pandas.core.frame.DataFrame'):\n return df\n\n if _is_pandas_styler(df):\n return df.data\n\n import pandas as pd\n\n if util.is_type(df, 'numpy.ndarray') and len(df.shape) == 0:\n return pd.DataFrame([])\n\n # Try to convert to pandas.DataFrame. This will raise an error is df is not\n # compatible with the pandas.DataFrame constructor.\n return pd.DataFrame(df)\n\n\ndef _is_pandas_styler(obj):\n return util.is_type(obj, 'pandas.io.formats.style.Styler')\n\n\ndef _marshall_styles(proto_table_style, df, styler=None):\n \"\"\"Adds pandas.Styler styling data to a proto.DataFrame\n\n Parameters\n ----------\n proto_table_style : proto.TableStyle\n df : pandas.DataFrame\n styler : pandas.Styler holding styling data for the data frame, or\n None if there's no style data to marshall\n \"\"\"\n\n # NB: we're using protected members of Styler to get this data,\n # which is non-ideal and could break if Styler's interface changes.\n\n if styler is not None:\n styler._compute()\n translated_style = styler._translate()\n css_styles = _get_css_styles(translated_style)\n display_values = _get_custom_display_values(df, translated_style)\n else:\n # If we have no Styler, we just make an empty CellStyle for each cell\n css_styles = {}\n display_values = {}\n\n nrows, ncols = df.shape\n for col in range(ncols):\n proto_col = proto_table_style.cols.add()\n for row in range(nrows):\n proto_cell_style = proto_col.styles.add()\n\n for css in css_styles.get((row, col), []):\n proto_css = proto_cell_style.css.add()\n proto_css.property = css.property\n proto_css.value = css.value\n\n display_value = display_values.get((row, col), None)\n if display_value is not None:\n proto_cell_style.display_value = display_value\n proto_cell_style.has_display_value = True\n\n\ndef _get_css_styles(translated_style):\n \"\"\"Parses pandas.Styler style dictionary into a\n {(row, col): [CSSStyle]} dictionary\n \"\"\"\n # Create {(row, col): [CSSStyle]} from translated_style['cellstyle']\n # translated_style['cellstyle'] has the shape:\n # [\n # {\n # 'props': [['color', ' black'], ['background-color', 'orange'], ['', '']],\n # 'selector': 'row0_col0'\n # }\n # ...\n # ]\n\n cell_selector_regex = re.compile(r'row(\\d+)_col(\\d+)')\n\n css_styles = {}\n for cell_style in translated_style['cellstyle']:\n cell_selector = cell_style[\n 'selector'] # a string of the form 'row0_col0'\n match = cell_selector_regex.match(cell_selector)\n if not match:\n raise RuntimeError('Failed to parse cellstyle selector \"%s\"' %\n cell_selector)\n row = int(match.group(1))\n col = int(match.group(2))\n css_declarations = []\n props = cell_style['props']\n for prop in props:\n if not isinstance(prop, list) or len(prop) != 2:\n raise RuntimeError('Unexpected cellstyle props \"%s\"' % prop)\n name = str(prop[0]).strip()\n value = str(prop[1]).strip()\n if name and value:\n css_declarations.append(CSSStyle(property=name, value=value))\n\n css_styles[(row, col)] = css_declarations\n\n return css_styles\n\n\ndef _get_custom_display_values(df, translated_style):\n \"\"\"Parses pandas.Styler style dictionary into a\n {(row, col): display_value} dictionary for cells whose display format\n has been customized.\n \"\"\"\n # Create {(row, col): display_value} from translated_style['body']\n # translated_style['body'] has the shape:\n # [\n # [ // row\n # { // cell or header\n # 'id': 'level0_row0' (for row header) | 'row0_col0' (for cells)\n # 'value': 1.329212\n # 'display_value': '132.92%'\n # ...\n # }\n # ]\n # ]\n\n default_formatter = df.style._display_funcs[(0, 0)]\n\n def has_custom_display_value(cell):\n value = str(cell['value'])\n display_value = str(cell['display_value'])\n if value == display_value:\n return False\n\n # Pandas applies a default style to all float values, regardless\n # of whether they have a user-specified display format. We test\n # for that here.\n return default_formatter(value) != display_value\n\n cell_selector_regex = re.compile(r'row(\\d+)_col(\\d+)')\n header_selector_regex = re.compile(r'level(\\d+)_row(\\d+)')\n\n display_values = {}\n for row in translated_style['body']:\n # row is a List[Dict], containing format data for each cell in the row,\n # plus an extra first entry for the row header, which we skip\n found_row_header = False\n for cell in row:\n cell_id = cell['id'] # a string in the form 'row0_col0'\n if header_selector_regex.match(cell_id):\n if not found_row_header:\n # We don't care about processing row headers, but as\n # a sanity check, ensure we only see one per row\n found_row_header = True\n continue\n else:\n raise RuntimeError('Found unexpected row header \"%s\"' %\n cell)\n match = cell_selector_regex.match(cell_id)\n if not match:\n raise RuntimeError('Failed to parse cell selector \"%s\"' %\n cell_id)\n\n # Only store display values that differ from the cell's default\n if has_custom_display_value(cell):\n row = int(match.group(1))\n col = int(match.group(2))\n display_values[(row, col)] = str(cell['display_value'])\n\n return display_values\n\n\ndef _marshall_index(pandas_index, proto_index):\n \"\"\"Convert an pandas.Index into a proto.Index.\n\n pandas_index - Panda.Index or related (input)\n proto_index - proto.Index (output)\n \"\"\"\n import pandas as pd\n import numpy as np\n if type(pandas_index) == pd.Index:\n _marshall_any_array(np.array(pandas_index),\n proto_index.plain_index.data)\n elif type(pandas_index) == pd.RangeIndex:\n min = pandas_index.min()\n max = pandas_index.max()\n if pd.isna(min) or pd.isna(max):\n proto_index.range_index.start = 0\n proto_index.range_index.stop = 0\n else:\n proto_index.range_index.start = min\n proto_index.range_index.stop = max + 1\n elif type(pandas_index) == pd.MultiIndex:\n for level in pandas_index.levels:\n _marshall_index(level, proto_index.multi_index.levels.add())\n if hasattr(pandas_index, 'codes'):\n index_codes = pandas_index.codes\n else:\n # Deprecated in Pandas 0.24, do don't bother covering.\n index_codes = pandas_index.labels # pragma: no cover\n for label in index_codes:\n proto_index.multi_index.labels.add().data.extend(label)\n elif type(pandas_index) == pd.DatetimeIndex:\n if pandas_index.tz is None:\n current_zone = tzlocal.get_localzone()\n pandas_index = pandas_index.tz_localize(current_zone)\n proto_index.datetime_index.data.data.extend(\n pandas_index.astype(np.int64))\n elif type(pandas_index) == pd.TimedeltaIndex:\n proto_index.timedelta_index.data.data.extend(\n pandas_index.astype(np.int64))\n elif type(pandas_index) == pd.Int64Index:\n proto_index.int_64_index.data.data.extend(pandas_index)\n elif type(pandas_index) == pd.Float64Index:\n proto_index.float_64_index.data.data.extend(pandas_index)\n else:\n raise NotImplementedError(\"Can't handle %s yet.\" % type(pandas_index))\n\n\ndef _marshall_table(pandas_table, proto_table):\n \"\"\"Convert a sequence of 1D arrays into proto.Table.\n\n pandas_table - Sequence of 1D arrays which are AnyArray compatible (input).\n proto_table - proto.Table (output)\n \"\"\"\n for pandas_array in pandas_table:\n _marshall_any_array(pandas_array, proto_table.cols.add())\n\n\ndef _marshall_any_array(pandas_array, proto_array):\n \"\"\"Convert a 1D numpy.Array into a proto.AnyArray.\n\n pandas_array - 1D arrays which is AnyArray compatible (input).\n proto_array - proto.AnyArray (output)\n \"\"\"\n import numpy as np\n # Convert to np.array as necessary.\n if not hasattr(pandas_array, 'dtype'):\n pandas_array = np.array(pandas_array)\n\n # Only works on 1D arrays.\n if len(pandas_array.shape) != 1:\n raise ValueError('Array must be 1D.')\n\n # Perform type-conversion based on the array dtype.\n if issubclass(pandas_array.dtype.type, np.floating):\n proto_array.doubles.data.extend(pandas_array)\n elif issubclass(pandas_array.dtype.type, np.timedelta64):\n proto_array.timedeltas.data.extend(pandas_array.astype(np.int64))\n elif issubclass(pandas_array.dtype.type, np.integer):\n proto_array.int64s.data.extend(pandas_array)\n elif pandas_array.dtype == np.bool:\n proto_array.int64s.data.extend(pandas_array)\n elif pandas_array.dtype == np.object:\n proto_array.strings.data.extend(map(str, pandas_array))\n # Setting a timezone changes (dtype, dtype.type) from\n # 'datetime64[ns]', <class 'numpy.datetime64'>\n # to\n # datetime64[ns, UTC], <class 'pandas._libs.tslibs.timestamps.Timestamp'>\n elif pandas_array.dtype.name.startswith('datetime64'):\n # TODO(armando): Convert eveything to UTC not local timezone.\n if pandas_array.dt.tz is None:\n current_zone = tzlocal.get_localzone()\n pandas_array = pandas_array.dt.tz_localize(current_zone)\n proto_array.datetimes.data.extend(pandas_array.astype(np.int64))\n else:\n raise NotImplementedError('Dtype %s not understood.' %\n pandas_array.dtype)\n\n\ndef add_rows(delta1, delta2, name=None):\n \"\"\"Concat the DataFrame in delta2 to the DataFrame in delta1.\n\n Parameters\n ----------\n delta1 : Delta\n delta2 : Delta\n name : str or None\n\n \"\"\"\n df1 = _get_data_frame(delta1, name)\n df2 = _get_data_frame(delta2, name)\n\n if len(df1.data.cols) == 0:\n if len(df2.data.cols) == 0:\n return\n df1.CopyFrom(df2)\n return\n\n # Copy Data\n if len(df1.data.cols) != len(df2.data.cols):\n raise ValueError('Dataframes have incompatible shapes')\n for (col1, col2) in zip(df1.data.cols, df2.data.cols):\n _concat_any_array(col1, col2)\n\n # Copy index\n _concat_index(df1.index, df2.index)\n\n # Don't concat columns! add_rows should leave the dataframe with the same\n # number of columns as it had before.\n # DON'T DO: _concat_index(df1.columns, df2.columns)\n\n # Copy styles\n for (style_col1, style_col2) in zip(df1.style.cols, df2.style.cols):\n _concat_cell_style_array(style_col1, style_col2)\n\n\ndef _concat_index(index1, index2):\n \"\"\"Contact index2 into index1.\"\"\"\n # Special case if index1 is empty.\n if _index_len(index1) == 0:\n index1.Clear()\n index1.CopyFrom(index2)\n return\n\n # Otherwise, dispatch based on type.\n type1 = index1.WhichOneof('type')\n type2 = index2.WhichOneof('type')\n # This branch is covered with tests but pytest doesnt seem to realize it.\n if type1 != type2: # pragma: no cover\n raise ValueError('Cannot concatenate %(type1)s with %(type2)s.' % {\n 'type1': type1,\n 'type2': type2\n })\n\n if type1 == 'plain_index':\n _concat_any_array(index1.plain_index.data, index2.plain_index.data)\n elif type1 == 'range_index':\n index1.range_index.stop += \\\n (index2.range_index.stop - index2.range_index.start)\n elif type1 == 'multi_index':\n raise NotImplementedError('Cannot yet concatenate MultiIndices.')\n elif type1 == 'int_64_index':\n index1.int_64_index.data.data.extend(index2.int_64_index.data.data)\n elif type1 == 'datetime_index':\n index1.datetime_index.data.data.extend(index2.datetime_index.data.data)\n elif type1 == 'timedelta_index':\n index1.timedelta_index.data.data.extend(\n index2.timedelta_index.data.data)\n else:\n raise NotImplementedError('Cannot concatenate \"%s\" indices.' % type1)\n\n\ndef _concat_any_array(any_array_1, any_array_2):\n \"\"\"Concat elements from any_array_2 into any_array_1.\"\"\"\n # Special case if any_array_1 is empty\n if _any_array_len(any_array_1) == 0:\n any_array_1.CopyFrom(any_array_2)\n return\n\n type1 = any_array_1.WhichOneof('type')\n type2 = any_array_2.WhichOneof('type')\n if type1 != type2:\n raise ValueError('Cannot concatenate %(type1)s with %(type2)s.' % {\n 'type1': type1,\n 'type2': type2\n })\n getattr(any_array_1, type1).data.extend(getattr(any_array_2, type2).data)\n\n\ndef _concat_cell_style_array(style_array1, style_array2):\n \"\"\"Concat elements from any_array_2 into any_array_1.\"\"\"\n # Special case if array1 is empty\n if len(style_array1.styles) == 0:\n style_array1.CopyFrom(style_array2)\n return\n\n style_array1.styles.extend(style_array2.styles)\n\n\ndef _get_data_frame(delta, name=None):\n \"\"\"Extract the dataframe from a delta.\"\"\"\n delta_type = delta.WhichOneof('type')\n\n if delta_type == 'new_element':\n element_type = delta.new_element.WhichOneof('type')\n\n # Some element types don't support named datasets.\n if name and element_type in ('data_frame', 'table', 'chart'):\n raise ValueError(\n 'Dataset names not supported for st.%s' % element_type)\n\n if element_type in 'data_frame':\n return delta.new_element.data_frame\n elif element_type in 'table':\n return delta.new_element.table\n elif element_type == 'chart':\n return delta.new_element.chart.data\n elif element_type == 'vega_lite_chart':\n chart_proto = delta.new_element.vega_lite_chart\n if name:\n return _get_or_create_dataset(chart_proto.datasets, name)\n elif len(chart_proto.datasets) == 1:\n # Support the case where the dataset name was randomly given by\n # the charting library (e.g. Altair) and the user has no\n # knowledge of it.\n return chart_proto.datasets[0].data\n else:\n return chart_proto.data\n # TODO: Support DeckGL. Need to figure out how to handle layer indices\n # first.\n\n elif delta_type == 'add_rows':\n if delta.add_rows.has_name and name != delta.add_rows.name:\n raise ValueError('No dataset found with name \"%s\".' % name)\n return delta.add_rows.data\n else:\n raise ValueError('Cannot extract DataFrame from %s.' % delta_type)\n\n\ndef _get_or_create_dataset(datasets_proto, name):\n for dataset in datasets_proto:\n if dataset.has_name and dataset.name == name:\n return dataset.data\n\n dataset = datasets_proto.add()\n dataset.name = name\n dataset.has_name = True\n return dataset.data\n\n\ndef _index_len(index):\n \"\"\"Return the number of elements in an index.\"\"\"\n index_type = index.WhichOneof('type')\n if index_type == 'plain_index':\n return _any_array_len(index.plain_index.data)\n elif index_type == 'range_index':\n return index.range_index.stop - index.range_index.start\n elif index_type == 'multi_index':\n if len(index.multi_index.labels) == 0:\n return 0\n else:\n return len(index.multi_index.labels[0].data)\n elif index_type == 'int_64_index':\n return len(index.int_64_index.data.data)\n elif index_type == 'float_64_index':\n return len(index.float_64_index.data.data)\n elif index_type == 'datetime_index':\n return len(index.datetime_index.data.data)\n elif index_type == 'timedelta_index':\n return len(index.timedelta_index.data.data)\n\n\ndef _any_array_len(any_array):\n \"\"\"Return the length of an any_array.\"\"\"\n array_type = any_array.WhichOneof('type')\n the_array = getattr(any_array, array_type).data\n return len(the_array)\n",
"# -*- coding: utf-8 -*-\n# Copyright 2018-2019 Streamlit 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 streamlit as st\nimport pandas as pd\nimport numpy as np\n\ncoords = np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4]\ndf = pd.DataFrame(coords, columns=['lat', 'lon'])\n\n# Sugar syntax for a basic scatterplot map using deck_gl:\n# st.map(df)\nst.map(df)\n\n# Similar test but specifying a custom zoom level:\n# st.map(df)\nst.map(df, zoom=8)\n"
] |
[
[
"pandas.isna",
"numpy.array",
"pandas.DataFrame"
],
[
"numpy.random.randn",
"pandas.DataFrame"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"0.24",
"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": []
}
] |
osim-microgrid-tool/osim_islanded_microgrids_sizing
|
[
"407ce32683043dbc0356fa0b2edaf537b0098b71"
] |
[
"actualizar_costos.py"
] |
[
"import pandas as pd\nimport numpy as np\nimport math\nimport sqlite3\nimport os\n\ndef conexion_bd(sql=None, update=True):\n \n sqlite3.register_adapter(np.int64, lambda val: int(val))\n sqlite3.register_adapter(np.int32, lambda val: int(val))\n\n con = sqlite3.connect(os.getcwd() + os.sep + \"result_op.db\")\n \n try:\n if update == True:\n cur = con.cursor()\n cur.execute(sql)\n con.commit()\n df=None\n else:\n df= pd.read_sql_query(sql, con=con)\n except:\n print(sql)\n df=None\n con.close()\n \n return df\n\n\n\ndef actualizar_costos(parametros=None, resultados=None, i=None):\n \n trm = 3736.91\n\n id_simulacion = parametros.loc[i,'id_simulacion']\n n_pv = parametros.loc[i,'n_pv']\n n_dg = parametros.loc[i,'n_dg']\n p_bat = parametros.loc[i,'p_bat']\n p_dg = parametros.loc[i,'p_dg']\n ens = parametros.loc[i,'ens_result']\n\n c_pv = parametros.loc[i,'cost_pv']\n c_bat = parametros.loc[i,'cost_bat']\n c_dg = parametros.loc[i,'cost_dg']\n \n lpsp = parametros.loc[i,'lpsp_result']\n \n if lpsp <=1.5:\n c_ens = 1532.53\n elif lpsp > 1.5 and lpsp <= 5:\n c_ens = 2778.13\n elif lpsp > 5 and lpsp < 90:\n c_ens = 4872.19\n else:\n c_ens = 0\n \n \n resultado_id = resultados[resultados['id_simulacion']==id_simulacion].reset_index(drop=True)\n\n resultado_id['total_dg'] = resultado_id['energia_Dg'] + resultado_id['p_bat_dg']\n resultado_id['total_pv'] = resultado_id['energia_PV'] + resultado_id['p_bat_pv']\n\n\n ei = round(resultado_id['total_dg'].sum(),2)\n et = round(resultado_id['total_dg'].sum(),2)\n\n et_pv = round(resultado_id['total_pv'].sum(),2)\n\n load = round(resultado_id['load'].sum(),2)\n\n et_bat = round(resultado_id['energia_descarga_bateria'].sum(),2)\n\n cost_e_dg = (et*c_dg)/trm\n cost_e_pv = (et_pv*c_pv)/trm\n cost_e_bat =( et_bat*c_bat)/trm\n cost_e_ens =( ens*c_ens)/trm\n\n financiero = {'R':20, 'ir':0.0808, 'cpv_ins' : 5605.365 ,'cbat_ins' : 539983.495,'cdg_ins' : 7627407.001, 'npv' : n_pv ,'ndg' : n_dg ,'ppv_stc': 300,'ebcell_nom': p_bat,\n 'pdg_rate': p_dg, 'li_bat':10,'li_dg':10,'ybat': 0.7,'ydg': 0.7, 'ipp_o': 74.37,'ipp_actual' : 129.23, 'cec': 0.0974,'ei': ei,'et': et,'pami': 8789 ,\n 'cel':0.0005,'plim':79900, 'p_load':load,'ens':ens, 'factor_pv':0.01,'factor_bat':0.02}\n\n\n R = financiero['R'] # the life time of the project\n ir = financiero['ir'] # (i_n - i_f) / (1 + i_f) # Tomado de otro estudio\n\n crf = round(ir*((1+ir)**R) /((1+ir)**R - 1),2) # The capital recovery factor is calculated by\n\n cpv_ins = financiero['cpv_ins'] # costo de PV kWh instalado\n cbat_ins = financiero['cbat_ins'] # costo Battery de kWh instalado\n cdg_ins = financiero['cdg_ins'] # costo diesel de kWh instalado\n\n npv = financiero['npv'] # Número de paneles fotovoltaicos\n ndg = financiero['ndg'] # Número planta diesel\n ppv_stc = financiero['ppv_stc']# Capacidad nominal paneles\n ebcell_nom = financiero['ebcell_nom'] # Capacidad de la batería\n pdg_rate = financiero['pdg_rate'] # Capacidad nominal diesel\n\n ccpv = round(cpv_ins*npv*ppv_stc,4)\n ccbat = round(cbat_ins*ebcell_nom,4)\n ccdg = round(cdg_ins*ndg*pdg_rate,4)\n\n def calcular_ki(R, li, ir):\n \"\"\"\n Para cálcular single payment present worth\n \"\"\"\n yi_replacements = math.floor(R/li)\n values_to_sum = []\n for i in range(1,yi_replacements+1):\n x = (1)/((1+ir)**(i*li))\n values_to_sum.append(x)\n\n return sum(values_to_sum)\n\n kbat = round(calcular_ki(R=financiero['R'], li=financiero['li_bat'], ir=financiero['ir']),4) # single payment present worth battery\n kdg = round(calcular_ki(R=financiero['R'], li=financiero['li_dg'], ir=financiero['ir']),4) # single payment present worth diesel\n\n ybat = financiero['ybat'] #are de-rate factors of the initial capital cost invested \n ydg = financiero['ydg'] #are de-rate factors of the initial capital cost invested\n\n rc_bat = round(ybat*ccbat*kbat,4)\n rc_dg = round(ydg*ccdg*kdg,4)\n\n factor_pv = financiero['factor_pv'] # Factor de la inversión inicial\n factor_bat = financiero['factor_bat'] # Factor de la inversión inicial\n\n oym_pv = factor_pv*ccpv \n oym_bat = factor_bat*ccbat\n\n ipp_o = financiero['ipp_o']\n ipp_actual = financiero['ipp_actual']\n\n cec = financiero['cec'] #Consumo especifíco de combustible 0.0974 gal/kWh (capacidad <= 100 kW)\n ei = financiero['ei'] #Energía entregada al Sistema de Distribución por el generador i \n et = financiero['et'] #Energía total entregada al Sistema de Distribución\n\n pami = financiero['pami'] #Precio promedio del combustible para la planta de abasto más cercana al generador i en el mes m ($/gal).\n tmi = pami*0.1\n calm = 82.14*(ipp_actual/ipp_o) # Costo de almacenamiento de combustible en el mes m ($/gal)\n pci = pami + tmi + calm # Precio del galón en el sitio para el generador i\n \n if et>0:\n cc = (1/et)*(cec*pci*ei) # Costo de Combustible (CC)\n else:\n cc=0\n\n cel = financiero['cel'] # Consumo Específico de Lubricante 0,00050 gal/kWh para plantas de capacidad <= 2.000 Kw\n plim = financiero['plim'] #Precio del Galón de lubricante en el sitio para el generador i en el mes m ($/gal). el precio del lubricante se determinará con base en los precios promedio del mercado.\n if et>0:\n cl = (1/et)*(cel*(plim+tmi)*ei)\n else:\n cl=0\n cam = 0.1*(cc+cl)\n\n oym_dg = (cam + cc + cl)*ei \n incentivo = 0.9038\n asc = (((ccpv+ccbat+ccdg)+(rc_bat+rc_dg))*crf + (oym_dg + oym_pv + oym_bat))/trm\n asc_incentivo = ((((ccpv+ccbat)*incentivo+ccdg)+(rc_bat+rc_dg))*crf + (oym_dg + oym_pv + oym_bat))/trm\n\n p_load = financiero['p_load']\n ens = financiero['ens']\n lcoe = (asc/(p_load - ens))\n lcoe_incentivo = (asc_incentivo/(p_load - ens))\n\n sql_actualizar= \"\"\"UPDATE parametros \n SET vida_proyecto = %s,\n ir = %s,\n crf= %s,\n cpv_ins= %s,\n cbat_ins= %s,\n cdg_ins= %s,\n capital_cpv= %s,\n capital_cbat= %s,\n capital_cdg= %s,\n kbat= %s,\n kdg= %s,\n ybat= %s,\n ydg= %s,\n rc_bat= %s,\n rc_dg= %s,\n factor_bat= %s,\n factor_pv= %s,\n oym_pv= %s,\n oym_bat= %s,\n ipp_actual= %s,\n trm= %s,\n pami = %s,\n plim = %s,\n oym_dg = %s,\n asc = %s,\n lcoe= %s,\n asc_incentivo=%s,\n lcoe_incentivo=%s,\n cost_e_dg=%s,\n cost_e_pv=%s,\n cost_e_bat=%s,\n cost_e_ens=%s \n WHERE id_simulacion =%s\"\"\"%(R, \n ir, \n crf, \n cpv_ins,\n cbat_ins, \n cdg_ins, \n ccpv ,\n ccbat,\n ccdg ,\n kbat, \n kdg, \n ybat, \n ydg, \n rc_bat, \n rc_dg, \n factor_bat,\n factor_pv, \n round(oym_pv,2), \n round(oym_bat,2), \n round(ipp_actual,2), \n round(trm,2), \n round(pami,2), \n round(plim,2),\n round(oym_dg,2), \n round(asc,2), \n round(lcoe,2), \n round(asc_incentivo,2),\n round(lcoe_incentivo,2), \n round(cost_e_dg,2),\n round(cost_e_pv,2) ,\n round(cost_e_bat,2),\n round(cost_e_ens,2),\n round(id_simulacion,2))\n\n\n\n conexion_bd(sql=sql_actualizar)\n\n"
] |
[
[
"pandas.read_sql_query"
]
] |
[
{
"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": []
}
] |
SKantar/SignalProcessing
|
[
"c8e5e9a45c92e1d337086b60bf7eed131756dcaf"
] |
[
"02_task/02_subtask.py"
] |
[
"import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.fftpack import fft\n\nFs = 200 # Sample frequence\nN = 150 # Number of sample points\nT = 1.0 / Fs # Sample spacing\nt = np.linspace(T, N * T, N)\n\nA = 2.3\nf = 20\nx_clear = A * np.sin(f * 2.0 * np.pi * t)\n\npowers, colors = [0, 1, 3, 6], ['r', 'g', 'b', 'y']\nfor i, power in enumerate(powers):\n e = np.random.normal(0, 1, N) * np.sqrt(power)\n x = x_clear + e\n xf = fft(x)\n\n yf = np.linspace(0.0, 1.0 / (2.0 * T), N // 2)\n\n # Display FFT\n plt.figure(i + 1)\n plt.stem(\n yf,\n 2.0 / N * np.abs(xf[0:N // 2]),\n colors[i],\n markerfmt='{}o'.format(colors[i])\n )\n plt.title('FFT Spectrum AWGN Power {}'.format(powers[i]))\n plt.xlabel('Frequency [Hz]')\n plt.grid()\n plt.show()\n\n\n"
] |
[
[
"numpy.sqrt",
"numpy.linspace",
"numpy.abs",
"numpy.sin",
"scipy.fftpack.fft",
"numpy.random.normal",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] |
[
{
"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": []
}
] |
gbbDonkiKong/UdemyAI_Template
|
[
"9d17edc43f0342675d194f29bf45fde77e4f5f0e"
] |
[
"Chapter2_Python/ListSlicing.py"
] |
[
"import matplotlib.pyplot as plt\n\n\nx = [[1, 4, 3, 9],\n [3, 1, 5, 2]]\n\ny = ['red', 'blue', 'blue', 'red']\n\n# P1 (x1 = 1, x2 = 3), Klasse = 'red'\n\nx1 = x[0]\nx2 = x[1]\n\nplt.scatter(x1, x2, color=y)\n# plt.show()\n\nw = [1, 3, 6, 9, 7, 4]\nw_squared = [val**2 for val in w[1:5]]\nprint(w_squared)"
] |
[
[
"matplotlib.pyplot.scatter"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
dalo2903/keras-video-classifier
|
[
"6dcf0a1e87342bdb057df0176af6489ff926f2d8"
] |
[
"demo/crime_vgg16_bilstm_hi_dim_train.py"
] |
[
"import numpy as np\nfrom keras import backend as K\nimport sys\nimport os\n\n\ndef main():\n K.set_image_dim_ordering('tf')\n sys.path.append(os.path.join(os.path.dirname(__file__), '..'))\n\n from keras_video_classifier.library.recurrent_networks import VGG16BidirectionalLSTMVideoClassifier\n from keras_video_classifier.library.utility.plot_utils import plot_and_save_history\n from keras_video_classifier.library.utility.crime.UCF_Crime_loader import load_ucf\n\n data_set_name = 'UCF-Anomaly-Detection-Dataset'\n input_dir_path = os.path.join(os.path.dirname(__file__), 'very_large_data')\n output_dir_path = os.path.join(os.path.dirname(__file__), 'models', data_set_name)\n report_dir_path = os.path.join(os.path.dirname(__file__), 'reports', data_set_name)\n\n np.random.seed(42)\n\n # this line downloads the video files of UCF-101 dataset if they are not available in the very_large_data folder\n load_ucf(input_dir_path)\n\n classifier = VGG16BidirectionalLSTMVideoClassifier()\n\n history = classifier.fit(data_dir_path=input_dir_path, model_dir_path=output_dir_path, vgg16_include_top=False,\n data_set_name=data_set_name)\n\n plot_and_save_history(history, VGG16BidirectionalLSTMVideoClassifier.model_name,\n report_dir_path + '/' + VGG16BidirectionalLSTMVideoClassifier.model_name + '-hi-dim-history.png')\n\n\nif __name__ == '__main__':\n main()\n"
] |
[
[
"numpy.random.seed"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
wolfram2012/ros_track_ssd
|
[
"c98d54eb923e5bae5fde4abbedda2fe5ba716606"
] |
[
"scripts/pyvision/util/fast_util.py"
] |
[
"import numpy as np\nfrom scipy import weave\n\n\nclass LocalMaximumDetector:\n def __init__(self,max_length=1000000):\n self.max_length = max_length\n self.maxes = np.zeros((max_length,2),dtype=np.int)\n self.vals = np.zeros((max_length,),dtype=np.float)\n \n def __call__(self, mat, threshold = None, sorted = True):\n '''\n All any local maximum that are greater than threshhold up to a total of \n max_length.\n \n To save time arrays that hold the maxes and vals that are created \n once and reused for each call. This means that local maximum detection\n is not thread safe. If using this class with threads create an instance\n for each thread.\n \n @param mat: 2d Real Matrix input.\n @param threshold: Mininum value of local maxima.\n @param sorted: set to False to save time and return an unorderd list.\n \n @returns: maxes,vals\n '''\n r,c = mat.shape\n maxes = self.maxes\n vals = self.vals\n max_length = self.max_length\n \n if threshold != None:\n count = weave.inline(\n ''' \n int count = 0;\n \n for( int i = 1; i < r-1 ; i++){\n for(int j = 1; j < c-1 ; j++){\n // Check if the current location meets the threshold\n \n if (mat(i,j) > threshold &&\n mat(i,j) > mat(i,j-1) &&\n mat(i,j) > mat(i,j+1) &&\n mat(i,j) > mat(i-1,j-1) &&\n mat(i,j) > mat(i-1,j) &&\n mat(i,j) > mat(i-1,j+1) &&\n mat(i,j) > mat(i+1,j-1) &&\n mat(i,j) > mat(i+1,j) &&\n mat(i,j) > mat(i+1,j+1)){\n \n // This is a local max\n maxes(count,0) = i;\n maxes(count,1) = j;\n vals(count) = mat(i,j);\n count += 1;\n \n if(count == max_length){\n i = r;\n j = c;\n }\n } \n }\n }\n \n return_val = count;\n ''',\n arg_names=['mat','maxes','vals','max_length','threshold','r','c'],\n type_converters=weave.converters.blitz,\n )\n else:\n count = weave.inline(\n ''' \n int count = 0;\n \n for( int i = 1; i < r-1 ; i++){\n for(int j = 1; j < c-1 ; j++){\n // Check if the current location meets the threshold\n \n if (mat(i,j) > mat(i,j-1) &&\n mat(i,j) > mat(i,j+1) &&\n mat(i,j) > mat(i-1,j-1) &&\n mat(i,j) > mat(i-1,j) &&\n mat(i,j) > mat(i-1,j+1) &&\n mat(i,j) > mat(i+1,j-1) &&\n mat(i,j) > mat(i+1,j) &&\n mat(i,j) > mat(i+1,j+1)){\n \n // This is a local max\n maxes(count,0) = i;\n maxes(count,1) = j;\n vals(count) = mat(i,j);\n count += 1;\n \n if(count == max_length){\n i = r;\n j = c;\n }\n } \n }\n }\n \n return_val = count;\n ''',\n arg_names=['mat','maxes','vals','max_length','r','c'],\n type_converters=weave.converters.blitz,\n )\n \n if sorted == False:\n return maxes[:count,:].copy(),vals[:count].copy()\n \n order = np.argsort(vals[:count])[::-1]\n maxes = maxes[order]\n vals = vals[order]\n \n #print vals\n #print maxes\n \n return maxes,vals\n \n \n\n"
] |
[
[
"numpy.argsort",
"numpy.zeros",
"scipy.weave.inline"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.12"
],
"tensorflow": []
}
] |
suresh-guttikonda/sim-environment
|
[
"cc8faec17714d58c0e1f0227c8b7d4cf8817a136"
] |
[
"src/tensorflow/igibson/utils/navigate_env.py"
] |
[
"#!/usr/bin/env python3\n\nfrom gibson2.envs.igibson_env import iGibsonEnv\nfrom gibson2.utils.utils import l2_distance\nfrom utils import datautils\nimport numpy as np\nimport gym\n\nclass NavigateGibsonEnv(iGibsonEnv):\n\n def __init__(\n self,\n config_file,\n scene_id=None,\n mode='headless',\n action_timestep=1 / 10.0,\n physics_timestep=1 / 240.0,\n device_idx=0,\n render_to_tensor=False,\n automatic_reset=False,\n ):\n\n super(NavigateGibsonEnv, self).__init__(config_file=config_file,\n scene_id=scene_id,\n mode=mode,\n action_timestep=action_timestep,\n physics_timestep=physics_timestep,\n device_idx=device_idx,\n render_to_tensor=render_to_tensor,\n automatic_reset=automatic_reset)\n\n output_size = 18 + np.prod((56, 56, 3))\n\n self.observation_space = gym.spaces.Box(\n low=-np.inf, high=np.inf,\n shape=(output_size, ),\n dtype=np.float32)\n\n def step(self, action):\n state, reward, done, info = super(NavigateGibsonEnv, self).step(action)\n\n # process image for training\n rgb = datautils.process_raw_image(state['rgb'])\n\n custom_state = np.concatenate([self.robots[0].calc_state(),\n np.reshape(rgb, [-1])], 0)\n\n # distance based reward\n reward = reward - l2_distance(\n self.robots[0].get_position()[:2],\n self.task.target_pos[:2]\n )\n return custom_state, reward, done, info\n\n def reset(self):\n state = super(NavigateGibsonEnv, self).reset()\n\n # process image for training\n rgb = datautils.process_raw_image(state['rgb'])\n\n custom_state = np.concatenate([self.robots[0].calc_state(),\n np.reshape(rgb, [-1])], 0)\n\n return custom_state\n"
] |
[
[
"numpy.reshape",
"numpy.prod"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
cdanielmachado/framed
|
[
"36d56437685cbf5c7c3c8ee4f6d85b8f05f4d345"
] |
[
"src/framed/bioreactor/base.py"
] |
[
"\"\"\" This module defines the base classes used for modeling and analyzing bioreactors\n\nAuthor: Kai Zhuang\n\n\"\"\"\nfrom __future__ import print_function\nfrom builtins import object\n__author__ = 'kaizhuang'\n\nfrom copy import deepcopy\nfrom ..solvers import solver_instance\nfrom framed.solvers.solution import Status\nfrom scipy.integrate import ode\nimport numpy\nimport collections\n\nimport warnings\n\n\nclass Organism(object):\n \"\"\"\n Organism describes a generic biological organism.\n \"\"\"\n\n def __init__(self, model, id=None, fba_objective=None, fba_constraints={}, model_deepcopy=True):\n \"\"\"\n :param model: the mathematical model of the organism\n :param fba_objective (dict): the FBA objective function. (only useful if model is a FBA model)\n :param fba_constraints (dict): none standard FBA constraints. This can be useful for creating knockout strains\n :param model_deepcopy (bool): if True, a deepcopy of the model will be created inside the Organism instance,\n otherwise, a reference of the model will be created\n :return: none\n \"\"\"\n if model_deepcopy:\n self.model = deepcopy(model)\n else:\n self.model = model\n\n if id:\n self.id = id\n else:\n self.id = model.id\n\n if fba_objective:\n self.fba_objective = fba_objective\n else:\n self.fba_objective = {model.biomass_reaction: 1}\n\n self.fba_constraints = fba_constraints\n self.fba_solution = []\n\n self.environment = None # upon initiation, the organism is not placed in any environment\n\n def update(self):\n \"\"\"\n The update() method is used to change the internal state of the organism.\n - This method is called at each integration step.\n - One usage of this method is to describe how the FBA uptake constraint changes in response to the changes in\n the metabolite concentrations.\n\n ** this is an abstract method, must be implemented in strain specific subclasses **\n \"\"\"\n\n raise NotImplementedError\n\n\nclass Environment(object):\n \"\"\"\n This class describes a generic environment that contains a number of organisms and metabolites\n \"\"\"\n\n def __init__(self):\n self.organisms = []\n self.metabolites = []\n self.initial_conditions = []\n\n def update(self):\n \"\"\"\n The update() method is used to change the internal state of the environment.\n This method is called at each integration step.\n\n ** this is an abstract method, must be implemented for specific environments **\n \"\"\"\n raise NotImplementedError(\"update() method must be implemented for the specific environment\")\n\n def set_organisms(self, organisms):\n self.organisms = []\n self.add_organisms(organisms)\n\n def set_metabolites(self, metabolites):\n self.metabolites = []\n self.add_metabolites(metabolites)\n\n def add_organism(self, organism):\n organism.environment = self\n self.organisms.append(organism)\n\n def add_organisms(self, organisms):\n for organism in organisms:\n self.add_organism(organism)\n\n def add_metabolite(self, metabolite):\n self.metabolites.append(metabolite)\n\n def add_metabolites(self, metabolites):\n for metabolite in metabolites:\n self.add_metabolite(metabolite)\n\n\nclass DynamicSystem(object):\n \"\"\"\n This class describes a generic dynamic system\n \"\"\"\n\n def ode_RHS(self, y, t):\n \"\"\"\n this is the Right Hand Side of the system of ODE that describe the dynamic multi-species system\n :param y: state variables such as liquid volume, biomass concentrations, and metabolite concentrations\n :param t: time\n :return:\n\n ** this is an abstract method, must be implemented for specific environments **\n \"\"\"\n raise NotImplementedError(\"the RHS of the ODE must be described for the each specific environment\")\n\n def integrate(self, t0, tf, dt, initial_conditions, solver, verbose=False):\n \"\"\"\n the integrate() solves the ODE of the dynamic system using the designated solver\n :param t0: initial time\n :param tf: final time\n :param dt: time step\n :param initial_conditions (array-like): initial conditions of the ODE system\n :param solver: the designated solver\n :return:\n \"\"\"\n if solver == 'analytical':\n try:\n t, y = self.analytical_integrator(t0, tf, dt, initial_conditions, solver, verbose)\n except NotImplementedError:\n warnings.warn('analytical solver have no been implemented yet. will use numerical solver dopri5'. FutureWarning)\n t, y = self.numerical_integrator(t0, tf, dt, initial_conditions, solver='dopri5')\n else:\n t, y = self.numerical_integrator(t0, tf, dt, initial_conditions, solver, verbose)\n return t, y\n\n def numerical_integrator(self, t0, tf, dt, initial_conditions, solver, verbose):\n \"\"\"\n the numerical_integrator() method integrates the ODE of the dynamic system using a numerical solver\n \"\"\"\n f = self._ode_RHS\n if initial_conditions:\n y0 = initial_conditions\n else:\n y0 = self.initial_conditions\n\n MdFBA_ode = ode(f).set_integrator(solver)\n MdFBA_ode.set_initial_value(y0, t0)\n\n t = [t0]\n y = [y0]\n\n while MdFBA_ode.successful() and MdFBA_ode.t < tf:\n MdFBA_ode.integrate(MdFBA_ode.t + dt)\n\n t.append(MdFBA_ode.t)\n y.append(MdFBA_ode.y)\n\n if verbose:\n print(MdFBA_ode.t)\n\n t = numpy.array(t)\n y = numpy.array(y)\n return t, y\n\n def analytical_integrator(self, t0, tf, dt, initial_conditions, solver, verbose):\n \"\"\"\n the analytical_integrator() method integrates the ODE of the dynamic system using a user-defined analytical method\n\n ** this is an abstract method, must be implemented for specific dynamic systems **\n \"\"\"\n raise NotImplementedError\n\nclass Bioreactor(Environment, DynamicSystem):\n \"\"\"\n This class describes a generic bioreactor with one influent (feed) stream and one effluent stream\n \"\"\"\n\n def __init__(self, organisms=[], metabolites=[], id='Generic Bioreactor', flow_rate_in=0, flow_rate_out=0,\n volume_max=None, Xfeed=None, Sfeed=None, deltaX=None, deltaS=None, initial_conditions=[]):\n\n \"\"\"\n :param organisms: list of Organism\n :param metabolites: list of string\n :param flow_rate_in:\n :param flow_rate_out:\n :param volume_max (float): liquid capacity of the bioreactor\n :param Xfeed: concentration of organisms in the feed stream [g/L]\n :param Sfeed: concentration of metabolites in the feed stream [mmol/L]\n :param deltaX: custom defined terms to dX/dt [g/L/hr]\n :param deltaS (list of float): special custom defined terms to dX/dt [mmol/L/hr]\n :param initial_conditions: list of float\n :return:\n \"\"\"\n if organisms:\n if not isinstance(organisms, collections.Iterable):\n organisms = [organisms]\n self.set_organisms(organisms)\n else:\n self.set_organisms([])\n\n if metabolites:\n if not isinstance(metabolites, collections.Iterable):\n metabolites = [metabolites]\n self.set_metabolites(metabolites)\n else:\n self.set_metabolites([])\n\n self.id = id\n\n self.flow_rate_in = flow_rate_in\n self.flow_rate_out = flow_rate_out\n self.volume_max = volume_max\n\n self.initial_conditions = initial_conditions\n\n self.set_Xfeed(Xfeed)\n self.set_Sfeed(Sfeed)\n self.set_deltaX(deltaX)\n self.set_deltaS(deltaS)\n\n def set_organisms(self, organisms, Xfeed=None, deltaX=None):\n super(Bioreactor, self).set_organisms(organisms)\n self.set_Xfeed(Xfeed)\n self.set_deltaX(deltaX)\n\n def set_metabolites(self, metabolites, Sfeed=None, deltaS=None):\n super(Bioreactor, self).set_metabolites(metabolites)\n self.set_Sfeed(Sfeed)\n self.set_deltaS(deltaS)\n\n\n def set_Xfeed(self, Xfeed):\n if Xfeed:\n assert len(Xfeed) == len(self.organisms), 'The length of Xfeed should equal to the number of organisms'\n self.Xfeed = Xfeed\n else:\n self.Xfeed = numpy.zeros(len(self.organisms))\n\n def set_Sfeed(self, Sfeed):\n if Sfeed:\n assert len(Sfeed) == len(self.metabolites), 'The length of Sfeed should equal to the number of metabolites'\n self.Sfeed = Sfeed\n else:\n self.Sfeed = numpy.zeros(len(self.metabolites))\n\n def set_deltaX(self, deltaX):\n if deltaX:\n self.deltaX = deltaX\n else:\n self.deltaX = numpy.zeros(len(self.organisms))\n\n def set_deltaS(self, deltaS):\n if deltaS:\n self.deltaS = deltaS\n else:\n self.deltaS = numpy.zeros(len(self.metabolites))\n\n def set_initial_conditions(self, Vinit, Xinit, Sinit):\n assert type(Vinit) == type(Xinit) == type(Sinit) == list\n self.initial_conditions = Vinit + Xinit + Sinit\n\n def update(self, time):\n if self.volume_max:\n if self.V > self.volume_max:\n raise ValueError('liquid volume of the bioreactor exceeds volume_max.')\n\n def _ode_RHS(self, t, y):\n \"\"\"\n the RHS of the ODE that describe the bioreactor system\n :param y:\n y[0]: volume\n y[1] to y[number_of_organisms]: biomass of the organisms\n y[number_of_organisms + 1] to y[-1] concentration of metabolites\n\n :param t: time\n :return: dy\n \"\"\"\n number_of_organisms = len(self.organisms)\n number_of_metabolites = len(self.metabolites)\n assert (len(y) == 1 + number_of_organisms + number_of_metabolites)\n\n dy = numpy.zeros(len(y))\n\n # creating class variables V, X, S, time from y and t.\n # making them class variables so that class methods like update() can access them\n self.V = y[0]\n self.X = y[1:number_of_organisms + 1]\n self.S = y[number_of_organisms + 1:]\n self.time = t\n\n # assigning growth rates and metabolic production/consumption rates here\n # in this method, these rates are calculated using FBA\n\n vs = numpy.zeros([number_of_organisms, number_of_metabolites]) # fluxes through metabolites\n mu = numpy.zeros([number_of_organisms]) # growth rates of organisms\n\n for i, organism in enumerate(self.organisms):\n organism.update() # updating the internal states of the organism\n # eg. updating the uptake constraints based on metabolite concentrations\n if t == 0:\n organism.solver = solver_instance(organism.model)\n\n organism.fba_solution = organism.solver.solve(organism.fba_objective, minimize=False,\n constraints=organism.fba_constraints)\n\n if organism.fba_solution.status == Status.OPTIMAL:\n mu[i] = organism.fba_solution.fobj\n\n for j, metabolite in enumerate(self.metabolites):\n if metabolite in organism.model.reactions.keys():\n vs[i, j] = organism.fba_solution.values[metabolite]\n else:\n mu[i] = 0\n for j, metabolite in enumerate(self.metabolites):\n if metabolite in organism.model.reactions.keys():\n vs[i, j] = 0\n\n # updating the internal states of the bioreactor\n # eg. flow rates, feed concentrations, and custom defined dX/dt and dS/dt terms\n self.update(t)\n\n # calculating the rates of change of reactor volume[L], biomass [g/L] and metabolite [mmol/L]\n dy[0] = self.flow_rate_in - self.flow_rate_out # dV/dt [L/hr]\n dy[1:number_of_organisms + 1] = mu * self.X + self.flow_rate_in / self.V * (\n self.Xfeed - self.X) + self.deltaX # dX/dt [g/L/hr]\n dy[number_of_organisms + 1:] = numpy.dot(self.X, vs) + self.flow_rate_in / self.V * (\n self.Sfeed - self.S) + self.deltaS # dS/dt [mmol/L/hr]\n\n return dy\n\n def calculate_yield_from_dfba(self):\n \"\"\"\n Abstract used for calculating product yield from dFBA solution.\n This is useful for certain analysis methods (eg. DySScO).\n\n This should be implemented for specific bioreactors\n \"\"\"\n raise NotImplementedError\n\n def calculate_titer_from_dfba(self):\n \"\"\"\n Abstract used for calculating product titer from dFBA solution.\n This is useful for certain analysis methods (eg. DySScO).\n\n This should be implemented for specific bioreactors\n \"\"\"\n raise NotImplementedError\n\n def calculate_productivity_from_dfba(self):\n \"\"\"\n Abstract used for calculating productivity from dFBA solution.\n This is useful for certain analysis methods (eg. DySScO).\n\n This should be implemented for specific bioreactors\n \"\"\"\n raise NotImplementedError\n"
] |
[
[
"numpy.dot",
"numpy.array",
"numpy.zeros",
"scipy.integrate.ode"
]
] |
[
{
"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": []
}
] |
michelle4654/qiskit-terra
|
[
"1b18ea1debf2e9d3c0c3cf39e8c434352d2b2707"
] |
[
"qiskit/circuit/instruction.py"
] |
[
"# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2017.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\"\nA generic quantum instruction.\n\nInstructions can be implementable on hardware (u, cx, etc.) or in simulation\n(snapshot, noise, etc.).\n\nInstructions can be unitary (a.k.a Gate) or non-unitary.\n\nInstructions are identified by the following:\n\n name: A string to identify the type of instruction.\n Used to request a specific instruction on the backend, or in visualizing circuits.\n\n num_qubits, num_clbits: dimensions of the instruction.\n\n params: List of parameters to specialize a specific instruction instance.\n\nInstructions do not have any context about where they are in a circuit (which qubits/clbits).\nThe circuit itself keeps this context.\n\"\"\"\nimport warnings\nimport copy\nfrom itertools import zip_longest\n\nimport numpy\n\nfrom qiskit.circuit.exceptions import CircuitError\nfrom qiskit.circuit.quantumregister import QuantumRegister\nfrom qiskit.circuit.classicalregister import ClassicalRegister\nfrom qiskit.qobj.qasm_qobj import QasmQobjInstruction\nfrom qiskit.circuit.parameter import ParameterExpression\nfrom .tools import pi_check\n\n_CUTOFF_PRECISION = 1E-10\n\n\nclass Instruction:\n \"\"\"Generic quantum instruction.\"\"\"\n\n def __init__(self, name, num_qubits, num_clbits, params):\n \"\"\"Create a new instruction.\n\n Args:\n name (str): instruction name\n num_qubits (int): instruction's qubit width\n num_clbits (int): instruction's clbit width\n params (list[int|float|complex|str|ndarray|list|ParameterExpression]):\n list of parameters\n\n Raises:\n CircuitError: when the register is not in the correct format.\n \"\"\"\n if not isinstance(num_qubits, int) or not isinstance(num_clbits, int):\n raise CircuitError(\"num_qubits and num_clbits must be integer.\")\n if num_qubits < 0 or num_clbits < 0:\n raise CircuitError(\n \"bad instruction dimensions: %d qubits, %d clbits.\" %\n num_qubits, num_clbits)\n self.name = name\n self.num_qubits = num_qubits\n self.num_clbits = num_clbits\n\n self._params = [] # a list of gate params stored\n\n # tuple (ClassicalRegister, int) when the instruction has a conditional (\"if\")\n self.condition = None\n # list of instructions (and their contexts) that this instruction is composed of\n # empty definition means opaque or fundamental instruction\n self._definition = None\n self.params = params\n\n def __eq__(self, other):\n \"\"\"Two instructions are the same if they have the same name,\n same dimensions, and same params.\n\n Args:\n other (instruction): other instruction\n\n Returns:\n bool: are self and other equal.\n \"\"\"\n if type(self) is not type(other) or \\\n self.name != other.name or \\\n self.num_qubits != other.num_qubits or \\\n self.num_clbits != other.num_clbits or \\\n self.definition != other.definition:\n return False\n\n for self_param, other_param in zip_longest(self.params, other.params):\n try:\n if self_param == other_param:\n continue\n except ValueError:\n pass\n\n try:\n if numpy.shape(self_param) == numpy.shape(other_param) \\\n and numpy.allclose(self_param, other_param,\n atol=_CUTOFF_PRECISION):\n continue\n except TypeError:\n pass\n\n try:\n if numpy.isclose(float(self_param), float(other_param),\n atol=_CUTOFF_PRECISION):\n continue\n except TypeError:\n pass\n\n return False\n\n return True\n\n def _define(self):\n \"\"\"Populates self.definition with a decomposition of this gate.\"\"\"\n pass\n\n @property\n def params(self):\n \"\"\"return instruction params.\"\"\"\n return self._params\n\n @params.setter\n def params(self, parameters):\n self._params = []\n for single_param in parameters:\n self._params.append(self.validate_parameter(single_param))\n\n def validate_parameter(self, parameter):\n \"\"\"Instruction parameters has no validation or normalization.\"\"\"\n return parameter\n\n def is_parameterized(self):\n \"\"\"Return True .IFF. instruction is parameterized else False\"\"\"\n return any(isinstance(param, ParameterExpression)\n and param.parameters\n for param in self.params)\n\n @property\n def definition(self):\n \"\"\"Return definition in terms of other basic gates.\"\"\"\n if self._definition is None:\n self._define()\n return self._definition\n\n @definition.setter\n def definition(self, array):\n \"\"\"Set gate representation\"\"\"\n self._definition = array\n\n @property\n def decompositions(self):\n \"\"\"Get the decompositions of the instruction from the SessionEquivalenceLibrary.\"\"\"\n # pylint: disable=cyclic-import\n from qiskit.circuit.equivalence_library import SessionEquivalenceLibrary as sel\n return sel.get_entry(self)\n\n @decompositions.setter\n def decompositions(self, decompositions):\n \"\"\"Set the decompositions of the instruction from the SessionEquivalenceLibrary.\"\"\"\n # pylint: disable=cyclic-import\n from qiskit.circuit.equivalence_library import SessionEquivalenceLibrary as sel\n sel.set_entry(self, decompositions)\n\n def add_decomposition(self, decomposition):\n \"\"\"Add a decomposition of the instruction to the SessionEquivalenceLibrary.\"\"\"\n # pylint: disable=cyclic-import\n from qiskit.circuit.equivalence_library import SessionEquivalenceLibrary as sel\n sel.add_equivalence(self, decomposition)\n\n def assemble(self):\n \"\"\"Assemble a QasmQobjInstruction\"\"\"\n instruction = QasmQobjInstruction(name=self.name)\n # Evaluate parameters\n if self.params:\n params = [\n x.evalf(x) if hasattr(x, 'evalf') else x for x in self.params]\n instruction.params = params\n # Add placeholder for qarg and carg params\n if self.num_qubits:\n instruction.qubits = list(range(self.num_qubits))\n if self.num_clbits:\n instruction.memory = list(range(self.num_clbits))\n # Add condition parameters for assembler. This is needed to convert\n # to a qobj conditional instruction at assemble time and after\n # conversion will be deleted by the assembler.\n if self.condition:\n instruction._condition = self.condition\n return instruction\n\n def mirror(self):\n \"\"\"DEPRECATED: use instruction.reverse_ops().\n\n Return:\n qiskit.circuit.Instruction: a new instruction with sub-instructions\n reversed.\n \"\"\"\n warnings.warn('instruction.mirror() is deprecated. Use circuit.reverse_ops()'\n 'to reverse the order of gates.', DeprecationWarning)\n return self.reverse_ops()\n\n def reverse_ops(self):\n \"\"\"For a composite instruction, reverse the order of sub-instructions.\n\n This is done by recursively reversing all sub-instructions.\n It does not invert any gate.\n\n Returns:\n qiskit.circuit.Instruction: a new instruction with\n sub-instructions reversed.\n \"\"\"\n if not self._definition:\n return self.copy()\n\n reverse_inst = self.copy(name=self.name + '_reverse')\n reverse_inst.definition._data = [(inst.reverse_ops(), qargs, cargs)\n for inst, qargs, cargs in reversed(self._definition)]\n\n return reverse_inst\n\n def inverse(self):\n \"\"\"Invert this instruction.\n\n If the instruction is composite (i.e. has a definition),\n then its definition will be recursively inverted.\n\n Special instructions inheriting from Instruction can\n implement their own inverse (e.g. T and Tdg, Barrier, etc.)\n\n Returns:\n qiskit.circuit.Instruction: a fresh instruction for the inverse\n\n Raises:\n CircuitError: if the instruction is not composite\n and an inverse has not been implemented for it.\n \"\"\"\n if self.definition is None:\n raise CircuitError(\"inverse() not implemented for %s.\" % self.name)\n\n from qiskit.circuit import QuantumCircuit, Gate # pylint: disable=cyclic-import\n if self.num_clbits:\n inverse_gate = Instruction(name=self.name + '_dg',\n num_qubits=self.num_qubits,\n num_clbits=self.num_clbits,\n params=self.params.copy())\n\n else:\n inverse_gate = Gate(name=self.name + '_dg',\n num_qubits=self.num_qubits,\n params=self.params.copy())\n\n inverse_gate.definition = QuantumCircuit(*self.definition.qregs, *self.definition.cregs)\n inverse_gate.definition._data = [(inst.inverse(), qargs, cargs)\n for inst, qargs, cargs in reversed(self._definition)]\n\n return inverse_gate\n\n def c_if(self, classical, val):\n \"\"\"Add classical condition on register classical and value val.\"\"\"\n if not isinstance(classical, ClassicalRegister):\n raise CircuitError(\"c_if must be used with a classical register\")\n if val < 0:\n raise CircuitError(\"condition value should be non-negative\")\n self.condition = (classical, val)\n return self\n\n def copy(self, name=None):\n \"\"\"\n Copy of the instruction.\n\n Args:\n name (str): name to be given to the copied circuit,\n if None then the name stays the same.\n\n Returns:\n qiskit.circuit.Instruction: a copy of the current instruction, with the name\n updated if it was provided\n \"\"\"\n cpy = self.__deepcopy__()\n\n if name:\n cpy.name = name\n return cpy\n\n def __deepcopy__(self, _memo=None):\n cpy = copy.copy(self)\n cpy._params = copy.copy(self._params)\n if self._definition:\n cpy._definition = copy.deepcopy(self._definition, _memo)\n return cpy\n\n def _qasmif(self, string):\n \"\"\"Print an if statement if needed.\"\"\"\n if self.condition is None:\n return string\n return \"if(%s==%d) \" % (self.condition[0].name, self.condition[1]) + string\n\n def qasm(self):\n \"\"\"Return a default OpenQASM string for the instruction.\n\n Derived instructions may override this to print in a\n different format (e.g. measure q[0] -> c[0];).\n \"\"\"\n name_param = self.name\n if self.params:\n name_param = \"%s(%s)\" % (name_param, \",\".join(\n [pi_check(i, ndigits=8, output='qasm') for i in self.params]))\n\n return self._qasmif(name_param)\n\n def broadcast_arguments(self, qargs, cargs):\n \"\"\"\n Validation of the arguments.\n\n Args:\n qargs (List): List of quantum bit arguments.\n cargs (List): List of classical bit arguments.\n\n Yields:\n Tuple(List, List): A tuple with single arguments.\n\n Raises:\n CircuitError: If the input is not valid. For example, the number of\n arguments does not match the gate expectation.\n \"\"\"\n if len(qargs) != self.num_qubits:\n raise CircuitError(\n 'The amount of qubit arguments does not match the instruction expectation.')\n\n # [[q[0], q[1]], [c[0], c[1]]] -> [q[0], c[0]], [q[1], c[1]]\n flat_qargs = [qarg for sublist in qargs for qarg in sublist]\n flat_cargs = [carg for sublist in cargs for carg in sublist]\n yield flat_qargs, flat_cargs\n\n def _return_repeat(self, exponent):\n return Instruction(name=\"%s*%s\" % (self.name, exponent), num_qubits=self.num_qubits,\n num_clbits=self.num_clbits, params=self.params)\n\n def repeat(self, n):\n \"\"\"Creates an instruction with `gate` repeated `n` amount of times.\n\n Args:\n n (int): Number of times to repeat the instruction\n\n Returns:\n qiskit.circuit.Instruction: Containing the definition.\n\n Raises:\n CircuitError: If n < 1.\n \"\"\"\n if int(n) != n or n < 1:\n raise CircuitError(\"Repeat can only be called with strictly positive integer.\")\n\n n = int(n)\n\n instruction = self._return_repeat(n)\n qargs = [] if self.num_qubits == 0 else QuantumRegister(self.num_qubits, 'q')\n cargs = [] if self.num_clbits == 0 else ClassicalRegister(self.num_clbits, 'c')\n\n if instruction.definition is None:\n # pylint: disable=cyclic-import\n from qiskit import QuantumCircuit\n qc = QuantumCircuit()\n if qargs:\n qc.add_register(qargs)\n if cargs:\n qc.add_register(cargs)\n qc.data = [(self, qargs[:], cargs[:])] * n\n instruction.definition = qc\n return instruction\n"
] |
[
[
"numpy.shape",
"numpy.allclose"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
MingSun-Tse/PytorchWCT
|
[
"9d11cc0995c0610c129b78ff5f72a26f4d60e10a"
] |
[
"Loader.py"
] |
[
"from PIL import Image\nimport torchvision.transforms as transforms\nimport torchvision.utils as vutils\nimport torch.utils.data as data\nfrom os import listdir\nfrom os.path import join\nimport numpy as np\nimport torch\nimport os\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport numpy as np\n\ndef is_image_file(filename):\n return any(filename.endswith(extension) for extension in [\".png\", \".jpg\", \".jpeg\"])\n\ndef default_loader(path):\n return Image.open(path).convert('RGB')\n\nclass Dataset(data.Dataset):\n def __init__(self, contentPath, stylePath, texturePath, fineSize, picked_content_mark=\".\", picked_style_mark=\".\", synthesis=False):\n super(Dataset,self).__init__()\n self.fineSize = fineSize\n self.synthesis = synthesis\n if synthesis:\n self.texturePath = texturePath\n self.texture_image_list = [x for x in listdir(texturePath) if is_image_file(x)]\n else:\n self.contentPath = contentPath\n self.stylePath = stylePath\n content_imgs = [x for x in listdir(contentPath) if is_image_file(x) and picked_content_mark in x]\n style_imgs = [x for x in listdir(stylePath) if is_image_file(x) and picked_style_mark in x]\n pairs = [[c, s] for c in content_imgs for s in style_imgs]\n self.content_image_list = list(np.array(pairs)[:, 0])\n self.style_image_list = list(np.array(pairs)[:, 1])\n \n # self.normalize = transforms.Normalize(mean=[103.939,116.779,123.68],std=[1, 1, 1])\n # normalize = transforms.Normalize(mean=[123.68,103.939,116.779],std=[1, 1, 1])\n # self.prep = transforms.Compose([\n # transforms.Scale(fineSize),\n # transforms.ToTensor(),\n # #transforms.Lambda(lambda x: x[torch.LongTensor([2,1,0])]), #turn to BGR\n # ])\n\n def __getitem__(self, index):\n if not self.synthesis: # style transfer\n contentImgPath = os.path.join(self.contentPath, self.content_image_list[index])\n styleImgPath = os.path.join(self.stylePath, self.style_image_list[index])\n contentImg = default_loader(contentImgPath)\n styleImg = default_loader(styleImgPath)\n if self.fineSize != 0:\n # w, h = contentImg.size\n # if w > h:\n # neww = self.fineSize\n # newh = int(h * neww / w)\n # else:\n # newh = self.fineSize\n # neww = int(w * newh / h)\n contentImg = contentImg.resize((self.fineSize, self.fineSize)) # if using fine size, it may well be testing, so use square image.\n styleImg = styleImg.resize((self.fineSize, self.fineSize))\n contentImg = transforms.ToTensor()(contentImg)\n styleImg = transforms.ToTensor()(styleImg)\n return contentImg.squeeze(0), styleImg.squeeze(0), \\\n self.content_image_list[index].split(\".\")[0] + \"+\" + self.style_image_list[index].split(\".\")[0] + \".jpg\"\n \n else: # texture synthesis\n textureImgPath = os.path.join(self.texturePath, self.texture_image_list[index])\n textureImg = default_loader(textureImgPath)\n if self.fineSize != 0:\n w, h = textureImg.size\n if w > h:\n neww = self.fineSize\n newh = int(h * neww / w)\n else:\n newh = self.fineSize\n neww = int(w * newh / h)\n textureImg = textureImg.resize((neww,newh))\n w, h = textureImg.size\n contentImg = torch.rand([3, 3000, int(3000.0/h*w)]) # uniform noise (range [0,1]) with the same dimension as texture image\n textureImg = transforms.ToTensor()(textureImg)\n return contentImg.squeeze(0), textureImg.squeeze(0), self.texture_image_list[index].split(\".\")[0] + \".jpg\"\n\n def __len__(self):\n # You should change 0 to the total size of your dataset.\n return len(self.texture_image_list) if self.synthesis else len(self.content_image_list)\n"
] |
[
[
"numpy.array"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jram098/IRG
|
[
"5265d61c2e67cce43a3261563b3b0f3cea27d9e4"
] |
[
"irmark1/templates/complete.py"
] |
[
"#!/usr/bin/env python3\n\"\"\"\nScripts to drive an IR Mark One (2) car\n\nUsage:\n manage.py (drive) [--model=<model>] [--js] [--type=(linear|categorical|rnn|imu|behavior|3d|localizer|latent)] [--camera=(single|stereo)] [--meta=<key:value> ...]\n manage.py (train) [--tub=<tub1,tub2,..tubn>] [--file=<file> ...] (--model=<model>) [--transfer=<model>] [--type=(linear|categorical|rnn|imu|behavior|3d|localizer)] [--continuous] [--aug]\n\n\nOptions:\n -h --help Show this screen.\n --js Use physical joystick.\n -f --file=<file> A text file containing paths to tub files, one per line. Option may be used more than once.\n --meta=<key:value> Key/Value strings describing describing a piece of meta data about this drive. Option may be used more than once.\n\"\"\"\nimport os\nimport time\n\nfrom docopt import docopt\nimport numpy as np\n\nimport irmark1 as m1\n\n#import parts\nfrom irmark1.parts.transform import Lambda, TriggeredCallback, DelayedTrigger\nfrom irmark1.parts.datastore import TubHandler\nfrom irmark1.parts.controller import LocalWebController, JoystickController\nfrom irmark1.parts.throttle_filter import ThrottleFilter\nfrom irmark1.parts.behavior import BehaviorPart\nfrom irmark1.parts.file_watcher import FileWatcher\nfrom irmark1.parts.launch import AiLaunch\nfrom irmark1.utils import *\n\ndef drive(cfg, model_path=None, use_joystick=False, model_type=None, camera_type='single', meta=[] ):\n '''\n Construct a working robotic vehicle from many parts.\n Each part runs as a job in the Vehicle loop, calling either\n it's run or run_threaded method depending on the constructor flag `threaded`.\n All parts are updated one after another at the framerate given in\n cfg.DRIVE_LOOP_HZ assuming each part finishes processing in a timely manner.\n Parts may have named outputs and inputs. The framework handles passing named outputs\n to parts requesting the same named input.\n '''\n\n if cfg.DONKEY_GYM:\n #the simulator will use cuda and then we usually run out of resources\n #if we also try to use cuda. so disable for donkey_gym.\n os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"-1\" \n\n if model_type is None:\n if cfg.TRAIN_LOCALIZER:\n model_type = \"localizer\"\n elif cfg.TRAIN_BEHAVIORS:\n model_type = \"behavior\"\n else:\n model_type = cfg.DEFAULT_MODEL_TYPE\n \n #Initialize car\n V = m1.vehicle.Vehicle()\n\n if camera_type == \"stereo\":\n\n if cfg.CAMERA_TYPE == \"WEBCAM\":\n from irmark1.parts.camera import Webcam \n\n camA = Webcam(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH, iCam = 0)\n camB = Webcam(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH, iCam = 1)\n\n elif cfg.CAMERA_TYPE == \"CVCAM\":\n from irmark1.parts.cv import CvCam\n\n camA = CvCam(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH, iCam = 0)\n camB = CvCam(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH, iCam = 1)\n else:\n raise(Exception(\"Unsupported camera type: %s\" % cfg.CAMERA_TYPE))\n\n V.add(camA, outputs=['cam/image_array_a'], threaded=True)\n V.add(camB, outputs=['cam/image_array_b'], threaded=True)\n\n from irmark1.parts.image import StereoPair\n\n V.add(StereoPair(), inputs=['cam/image_array_a', 'cam/image_array_b'], \n outputs=['cam/image_array'])\n\n else:\n print(\"cfg.CAMERA_TYPE\", cfg.CAMERA_TYPE)\n if cfg.DONKEY_GYM:\n from irmark1.parts.dgym import DonkeyGymEnv \n \n inputs = []\n threaded = True\n if cfg.DONKEY_GYM:\n from irmark1.parts.dgym import DonkeyGymEnv \n cam = DonkeyGymEnv(cfg.DONKEY_SIM_PATH, env_name=cfg.DONKEY_GYM_ENV_NAME)\n threaded = True\n inputs = ['angle', 'throttle']\n elif cfg.CAMERA_TYPE == \"PICAM\":\n from irmark1.parts.camera import PiCamera\n cam = PiCamera(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH)\n elif cfg.CAMERA_TYPE == \"WEBCAM\":\n from irmark1.parts.camera import Webcam\n cam = Webcam(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH)\n elif cfg.CAMERA_TYPE == \"CVCAM\":\n from irmark1.parts.cv import CvCam\n cam = CvCam(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH)\n elif cfg.CAMERA_TYPE == \"CSIC\":\n from irmark1.parts.camera import CSICamera\n cam = CSICamera(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH, framerate=cfg.CAMERA_FRAMERATE, gstreamer_flip=cfg.CSIC_CAM_GSTREAMER_FLIP_PARM)\n elif cfg.CAMERA_TYPE == \"V4L\":\n from irmark1.parts.camera import V4LCamera\n cam = V4LCamera(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH, framerate=cfg.CAMERA_FRAMERATE)\n elif cfg.CAMERA_TYPE == \"MOCK\":\n from irmark1.parts.camera import MockCamera\n cam = MockCamera(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH)\n elif cfg.CAMERA_TYPE == \"D435i\":\n from irmark1.parts.realsense2 import RS_D435i\n cam = RS_D435i(image_w=cfg.IMAGE_W, image_h=cfg.IMAGE_H, image_d=cfg.IMAGE_DEPTH, framerate=cfg.CAMERA_FRAMERATE)\n else:\n raise(Exception(\"Unkown camera type: %s\" % cfg.CAMERA_TYPE))\n \n V.add(cam, inputs=inputs, outputs=['cam/image_array'], threaded=threaded)\n \n if use_joystick or cfg.USE_JOYSTICK_AS_DEFAULT:\n #modify max_throttle closer to 1.0 to have more power\n #modify steering_scale lower than 1.0 to have less responsive steering\n from irmark1.parts.controller import get_js_controller\n \n ctr = get_js_controller(cfg)\n \n if cfg.USE_NETWORKED_JS:\n from irmark1.parts.controller import JoyStickSub\n netwkJs = JoyStickSub(cfg.NETWORK_JS_SERVER_IP)\n V.add(netwkJs, threaded=True)\n ctr.js = netwkJs\n\n else: \n #This web controller will create a web server that is capable\n #of managing steering, throttle, and modes, and more.\n ctr = LocalWebController()\n\n \n V.add(ctr, \n inputs=['cam/image_array'],\n outputs=['user/angle', 'user/throttle', 'user/mode', 'recording'],\n threaded=True)\n\n #this throttle filter will allow one tap back for esc reverse\n th_filter = ThrottleFilter()\n V.add(th_filter, inputs=['user/throttle'], outputs=['user/throttle'])\n \n #See if we should even run the pilot module. \n #This is only needed because the part run_condition only accepts boolean\n class PilotCondition:\n def run(self, mode):\n if mode == 'user':\n return False\n else:\n return True \n\n V.add(PilotCondition(), inputs=['user/mode'], outputs=['run_pilot'])\n \n class LedConditionLogic:\n def __init__(self, cfg):\n self.cfg = cfg\n\n def run(self, mode, recording, recording_alert, behavior_state, model_file_changed, track_loc):\n #returns a blink rate. 0 for off. -1 for on. positive for rate.\n \n if track_loc is not None:\n led.set_rgb(*self.cfg.LOC_COLORS[track_loc])\n return -1\n\n if model_file_changed:\n led.set_rgb(self.cfg.MODEL_RELOADED_LED_R, self.cfg.MODEL_RELOADED_LED_G, self.cfg.MODEL_RELOADED_LED_B)\n return 0.1\n else:\n led.set_rgb(self.cfg.LED_R, self.cfg.LED_G, self.cfg.LED_B)\n\n if recording_alert:\n led.set_rgb(*recording_alert)\n return self.cfg.REC_COUNT_ALERT_BLINK_RATE\n else:\n led.set_rgb(self.cfg.LED_R, self.cfg.LED_G, self.cfg.LED_B)\n \n if behavior_state is not None and model_type == 'behavior':\n r, g, b = self.cfg.BEHAVIOR_LED_COLORS[behavior_state]\n led.set_rgb(r, g, b)\n return -1 #solid on\n\n if recording:\n return -1 #solid on\n elif mode == 'user':\n return 1\n elif mode == 'local_angle':\n return 0.5\n elif mode == 'local':\n return 0.1\n return 0\n\n if cfg.HAVE_RGB_LED and not cfg.DONKEY_GYM:\n from irmark1.parts.led_status import RGB_LED\n led = RGB_LED(cfg.LED_PIN_R, cfg.LED_PIN_G, cfg.LED_PIN_B, cfg.LED_INVERT)\n led.set_rgb(cfg.LED_R, cfg.LED_G, cfg.LED_B) \n \n V.add(LedConditionLogic(cfg), inputs=['user/mode', 'recording', \"records/alert\", 'behavior/state', 'modelfile/modified', \"pilot/loc\"],\n outputs=['led/blink_rate'])\n\n V.add(led, inputs=['led/blink_rate'])\n \n\n def get_record_alert_color(num_records):\n col = (0, 0, 0)\n for count, color in cfg.RECORD_ALERT_COLOR_ARR:\n if num_records >= count:\n col = color\n return col \n\n class RecordTracker:\n def __init__(self):\n self.last_num_rec_print = 0\n self.dur_alert = 0\n self.force_alert = 0\n\n def run(self, num_records):\n if num_records is None:\n return 0\n \n if self.last_num_rec_print != num_records or self.force_alert:\n self.last_num_rec_print = num_records\n\n if num_records % 10 == 0:\n print(\"recorded\", num_records, \"records\")\n \n if num_records % cfg.REC_COUNT_ALERT == 0 or self.force_alert:\n self.dur_alert = num_records // cfg.REC_COUNT_ALERT * cfg.REC_COUNT_ALERT_CYC\n self.force_alert = 0\n \n if self.dur_alert > 0:\n self.dur_alert -= 1\n\n if self.dur_alert != 0:\n return get_record_alert_color(num_records)\n\n return 0\n\n rec_tracker_part = RecordTracker()\n V.add(rec_tracker_part, inputs=[\"tub/num_records\"], outputs=['records/alert'])\n\n if cfg.AUTO_RECORD_ON_THROTTLE and isinstance(ctr, JoystickController):\n #then we are not using the circle button. hijack that to force a record count indication\n def show_record_acount_status():\n rec_tracker_part.last_num_rec_print = 0\n rec_tracker_part.force_alert = 1\n ctr.set_button_down_trigger('circle', show_record_acount_status)\n\n #IMU\n if cfg.HAVE_IMU:\n from irmark1.parts.imu import Mpu6050\n imu = Mpu6050()\n V.add(imu, outputs=['imu/acl_x', 'imu/acl_y', 'imu/acl_z',\n 'imu/gyr_x', 'imu/gyr_y', 'imu/gyr_z'], threaded=True)\n\n class ImgPreProcess():\n '''\n preprocess camera image for inference.\n normalize and crop if needed.\n '''\n def __init__(self, cfg):\n self.cfg = cfg\n\n def run(self, img_arr):\n return normalize_and_crop(img_arr, self.cfg)\n\n if \"coral\" in model_type:\n inf_input = 'cam/image_array'\n else:\n inf_input = 'cam/normalized/cropped'\n V.add(ImgPreProcess(cfg),\n inputs=['cam/image_array'],\n outputs=[inf_input],\n run_condition='run_pilot')\n\n #Behavioral state\n if cfg.TRAIN_BEHAVIORS:\n bh = BehaviorPart(cfg.BEHAVIOR_LIST)\n V.add(bh, outputs=['behavior/state', 'behavior/label', \"behavior/one_hot_state_array\"])\n try:\n ctr.set_button_down_trigger('L1', bh.increment_state)\n except:\n pass\n\n inputs = [inf_input, \"behavior/one_hot_state_array\"] \n #IMU\n elif model_type == \"imu\":\n assert(cfg.HAVE_IMU)\n #Run the pilot if the mode is not user.\n inputs=[inf_input,\n 'imu/acl_x', 'imu/acl_y', 'imu/acl_z',\n 'imu/gyr_x', 'imu/gyr_y', 'imu/gyr_z']\n else:\n inputs=[inf_input]\n\n def load_model(kl, model_path):\n start = time.time()\n print('loading model', model_path)\n kl.load(model_path)\n print('finished loading in %s sec.' % (str(time.time() - start)) )\n\n def load_weights(kl, weights_path):\n start = time.time()\n try:\n print('loading model weights', weights_path)\n kl.model.load_weights(weights_path)\n print('finished loading in %s sec.' % (str(time.time() - start)) )\n except Exception as e:\n print(e)\n print('ERR>> problems loading weights', weights_path)\n\n def load_model_json(kl, json_fnm):\n start = time.time()\n print('loading model json', json_fnm)\n from tensorflow.python import keras\n try:\n with open(json_fnm, 'r') as handle:\n contents = handle.read()\n kl.model = keras.models.model_from_json(contents)\n print('finished loading json in %s sec.' % (str(time.time() - start)) )\n except Exception as e:\n print(e)\n print(\"ERR>> problems loading model json\", json_fnm)\n\n if model_path:\n #When we have a model, first create an appropriate Keras part\n kl = m1.utils.get_model_by_type(model_type, cfg)\n\n model_reload_cb = None\n\n if '.h5' in model_path or '.uff' in model_path or 'tflite' in model_path or '.pkl' in model_path:\n #when we have a .h5 extension\n #load everything from the model file\n load_model(kl, model_path)\n\n def reload_model(filename):\n load_model(kl, filename)\n\n model_reload_cb = reload_model\n\n elif '.json' in model_path:\n #when we have a .json extension\n #load the model from there and look for a matching\n #.wts file with just weights\n load_model_json(kl, model_path)\n weights_path = model_path.replace('.json', '.weights')\n load_weights(kl, weights_path)\n\n def reload_weights(filename):\n weights_path = filename.replace('.json', '.weights')\n load_weights(kl, weights_path)\n \n model_reload_cb = reload_weights\n\n else:\n print(\"ERR>> Unknown extension type on model file!!\")\n return\n\n #this part will signal visual LED, if connected\n V.add(FileWatcher(model_path, verbose=True), outputs=['modelfile/modified'])\n\n #these parts will reload the model file, but only when ai is running so we don't interrupt user driving\n V.add(FileWatcher(model_path), outputs=['modelfile/dirty'], run_condition=\"ai_running\")\n V.add(DelayedTrigger(100), inputs=['modelfile/dirty'], outputs=['modelfile/reload'], run_condition=\"ai_running\")\n V.add(TriggeredCallback(model_path, model_reload_cb), inputs=[\"modelfile/reload\"], run_condition=\"ai_running\")\n\n outputs=['pilot/angle', 'pilot/throttle']\n\n if cfg.TRAIN_LOCALIZER:\n outputs.append(\"pilot/loc\")\n \n V.add(kl, inputs=inputs, \n outputs=outputs,\n run_condition='run_pilot') \n \n #Choose what inputs should change the car.\n class DriveMode:\n def run(self, mode, \n user_angle, user_throttle,\n pilot_angle, pilot_throttle):\n if mode == 'user': \n return user_angle, user_throttle\n \n elif mode == 'local_angle':\n return pilot_angle, user_throttle\n \n else: \n return pilot_angle, pilot_throttle * cfg.AI_THROTTLE_MULT\n \n V.add(DriveMode(), \n inputs=['user/mode', 'user/angle', 'user/throttle',\n 'pilot/angle', 'pilot/throttle'], \n outputs=['angle', 'throttle'])\n\n \n #to give the car a boost when starting ai mode in a race.\n aiLauncher = AiLaunch(cfg.AI_LAUNCH_DURATION, cfg.AI_LAUNCH_THROTTLE, cfg.AI_LAUNCH_KEEP_ENABLED)\n \n V.add(aiLauncher,\n inputs=['user/mode', 'throttle'],\n outputs=['throttle'])\n\n if isinstance(ctr, JoystickController):\n ctr.set_button_down_trigger(cfg.AI_LAUNCH_ENABLE_BUTTON, aiLauncher.enable_ai_launch)\n\n\n class AiRunCondition:\n '''\n A bool part to let us know when ai is running.\n '''\n def run(self, mode):\n if mode == \"user\":\n return False\n return True\n\n V.add(AiRunCondition(), inputs=['user/mode'], outputs=['ai_running'])\n\n #Ai Recording\n class AiRecordingCondition:\n '''\n return True when ai mode, otherwize respect user mode recording flag\n '''\n def run(self, mode, recording):\n if mode == 'user':\n return recording\n return True\n\n if cfg.RECORD_DURING_AI:\n V.add(AiRecordingCondition(), inputs=['user/mode', 'recording'], outputs=['recording'])\n \n #Drive train setup\n if cfg.DONKEY_GYM:\n pass\n\n elif cfg.DRIVE_TRAIN_TYPE == \"SERVO_ESC\":\n from irmark1.parts.actuator import PCA9685, PWMSteering, PWMThrottle\n\n steering_controller = PCA9685(cfg.STEERING_CHANNEL, cfg.PCA9685_I2C_ADDR, busnum=cfg.PCA9685_I2C_BUSNUM)\n steering = PWMSteering(controller=steering_controller,\n left_pulse=cfg.STEERING_LEFT_PWM, \n right_pulse=cfg.STEERING_RIGHT_PWM)\n \n throttle_controller = PCA9685(cfg.THROTTLE_CHANNEL, cfg.PCA9685_I2C_ADDR, busnum=cfg.PCA9685_I2C_BUSNUM)\n throttle = PWMThrottle(controller=throttle_controller,\n max_pulse=cfg.THROTTLE_FORWARD_PWM,\n zero_pulse=cfg.THROTTLE_STOPPED_PWM, \n min_pulse=cfg.THROTTLE_REVERSE_PWM)\n\n V.add(steering, inputs=['angle'])\n V.add(throttle, inputs=['throttle'])\n \n\n elif cfg.DRIVE_TRAIN_TYPE == \"DC_STEER_THROTTLE\":\n from irmark1.parts.actuator import Mini_HBridge_DC_Motor_PWM\n \n steering = Mini_HBridge_DC_Motor_PWM(cfg.HBRIDGE_PIN_LEFT, cfg.HBRIDGE_PIN_RIGHT)\n throttle = Mini_HBridge_DC_Motor_PWM(cfg.HBRIDGE_PIN_FWD, cfg.HBRIDGE_PIN_BWD)\n\n V.add(steering, inputs=['angle'])\n V.add(throttle, inputs=['throttle'])\n \n\n elif cfg.DRIVE_TRAIN_TYPE == \"DC_TWO_WHEEL\":\n from irmark1.parts.actuator import TwoWheelSteeringThrottle, Mini_HBridge_DC_Motor_PWM\n\n left_motor = Mini_HBridge_DC_Motor_PWM(cfg.HBRIDGE_PIN_LEFT_FWD, cfg.HBRIDGE_PIN_LEFT_BWD)\n right_motor = Mini_HBridge_DC_Motor_PWM(cfg.HBRIDGE_PIN_RIGHT_FWD, cfg.HBRIDGE_PIN_RIGHT_BWD)\n two_wheel_control = TwoWheelSteeringThrottle()\n\n V.add(two_wheel_control, \n inputs=['throttle', 'angle'],\n outputs=['left_motor_speed', 'right_motor_speed'])\n\n V.add(left_motor, inputs=['left_motor_speed'])\n V.add(right_motor, inputs=['right_motor_speed'])\n\n elif cfg.DRIVE_TRAIN_TYPE == \"SERVO_HBRIDGE_PWM\":\n from irmark1.parts.actuator import ServoBlaster, PWMSteering\n steering_controller = ServoBlaster(cfg.STEERING_CHANNEL) #really pin\n #PWM pulse values should be in the range of 100 to 200\n assert(cfg.STEERING_LEFT_PWM <= 200)\n assert(cfg.STEERING_RIGHT_PWM <= 200)\n steering = PWMSteering(controller=steering_controller,\n left_pulse=cfg.STEERING_LEFT_PWM, \n right_pulse=cfg.STEERING_RIGHT_PWM)\n \n\n from irmark1.parts.actuator import Mini_HBridge_DC_Motor_PWM\n motor = Mini_HBridge_DC_Motor_PWM(cfg.HBRIDGE_PIN_FWD, cfg.HBRIDGE_PIN_BWD)\n\n V.add(steering, inputs=['angle'])\n V.add(motor, inputs=[\"throttle\"])\n\n \n #add tub to save data\n\n inputs=['cam/image_array',\n 'user/angle', 'user/throttle', \n 'user/mode']\n\n types=['image_array',\n 'float', 'float',\n 'str']\n\n if cfg.TRAIN_BEHAVIORS:\n inputs += ['behavior/state', 'behavior/label', \"behavior/one_hot_state_array\"]\n types += ['int', 'str', 'vector']\n \n if cfg.HAVE_IMU:\n inputs += ['imu/acl_x', 'imu/acl_y', 'imu/acl_z',\n 'imu/gyr_x', 'imu/gyr_y', 'imu/gyr_z']\n\n types +=['float', 'float', 'float',\n 'float', 'float', 'float']\n\n if cfg.RECORD_DURING_AI:\n inputs += ['pilot/angle', 'pilot/throttle']\n types += ['float', 'float']\n \n th = TubHandler(path=cfg.DATA_PATH)\n tub = th.new_tub_writer(inputs=inputs, types=types, user_meta=meta)\n V.add(tub, inputs=inputs, outputs=[\"tub/num_records\"], run_condition='recording')\n\n if cfg.PUB_CAMERA_IMAGES:\n from irmark1.parts.network import TCPServeValue\n from irmark1.parts.image import ImgArrToJpg\n pub = TCPServeValue(\"camera\")\n V.add(ImgArrToJpg(), inputs=['cam/image_array'], outputs=['jpg/bin'])\n V.add(pub, inputs=['jpg/bin'])\n\n if type(ctr) is LocalWebController:\n print(\"You can now go to <your pi ip address>:8887 to drive your car.\")\n elif isinstance(ctr, JoystickController):\n print(\"You can now move your joystick to drive your car.\")\n #tell the controller about the tub \n ctr.set_tub(tub)\n \n if cfg.BUTTON_PRESS_NEW_TUB:\n \n def new_tub_dir():\n V.parts.pop()\n tub = th.new_tub_writer(inputs=inputs, types=types, user_meta=meta)\n V.add(tub, inputs=inputs, outputs=[\"tub/num_records\"], run_condition='recording')\n ctr.set_tub(tub)\n \n ctr.set_button_down_trigger('cross', new_tub_dir)\n ctr.print_controls()\n\n #run the vehicle for 20 seconds\n V.start(rate_hz=cfg.DRIVE_LOOP_HZ, \n max_loop_count=cfg.MAX_LOOPS)\n\n\nif __name__ == '__main__':\n args = docopt(__doc__)\n cfg = m1.load_config()\n \n if args['drive']:\n model_type = args['--type']\n camera_type = args['--camera']\n drive(cfg, model_path=args['--model'], use_joystick=args['--js'], model_type=model_type, camera_type=camera_type,\n meta=args['--meta'])\n \n if args['train']:\n from train import multi_train, preprocessFileList\n \n tub = args['--tub']\n model = args['--model']\n transfer = args['--transfer']\n model_type = args['--type']\n continuous = args['--continuous']\n aug = args['--aug'] \n\n dirs = preprocessFileList( args['--file'] )\n if tub is not None:\n tub_paths = [os.path.expanduser(n) for n in tub.split(',')]\n dirs.extend( tub_paths )\n\n multi_train(cfg, dirs, model, transfer, model_type, continuous, aug)\n\n"
] |
[
[
"tensorflow.python.keras.models.model_from_json"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.5",
"1.4"
]
}
] |
vietnguyen1991/Character-level-cnn-tensorflow
|
[
"f4067093ef54a92fd3cd6558823fe6a06bfc5614",
"f4067093ef54a92fd3cd6558823fe6a06bfc5614"
] |
[
"train.py",
"src/character_level_cnn.py"
] |
[
"\"\"\"\n@author: Thang Nguyen <[email protected]>\n\"\"\"\nimport os\nimport shutil\nimport numpy as np\n\nimport tensorflow as tf\n\nfrom src.character_level_cnn import Char_level_cnn\nfrom src.utils import get_num_classes, create_dataset\n\ntf.flags.DEFINE_string(\"alphabet\", \"\"\"abcdefghijklmnopqrstuvwxyz0123456789,;.!?:'\\\"/\\\\|_@#$%^&*~`+-=<>()[]{}\"\"\",\n \"Valid characters used for model\")\ntf.flags.DEFINE_string(\"train_set\", \"data/train.csv\", \"Path to the training set\")\ntf.flags.DEFINE_string(\"test_set\", \"data/test.csv\", \"Path to the test set\")\ntf.flags.DEFINE_integer(\"test_interval\", 1, \"Number of epochs between testing phases\")\ntf.flags.DEFINE_integer(\"max_length\", 1014, \"Maximum length of input\")\ntf.flags.DEFINE_string(\"feature\", \"small\", \"large or small\")\ntf.flags.DEFINE_integer(\"batch_size\", 128, \"Minibatch size\")\ntf.flags.DEFINE_integer(\"num_epochs\", 20, \"Number of training epochs\")\ntf.flags.DEFINE_float(\"lr\", 1e-2, \"Learning rate\")\ntf.flags.DEFINE_string(\"optimizer\", \"sgd\", \"sgd or adam\")\ntf.flags.DEFINE_float(\"dropout\", 0.5, \"Dropout's probability\")\ntf.flags.DEFINE_string(\"log_path\", \"tensorboard/char_level_cnn\", \"path to tensorboard folder\")\ntf.flags.DEFINE_string(\"saved_path\", \"trained_models\", \"path to store trained model\")\n\ntf.flags.DEFINE_float(\"es_min_delta\", 0.,\n \"Early stopping's parameter: minimum change loss to qualify as an improvement\")\ntf.flags.DEFINE_integer(\"es_patience\", 3,\n \"Early stopping's parameter: number of epochs with no improvement after which training will be stopped. Set to 0 to disable this technique\")\n\ntf.flags.DEFINE_boolean(\"allow_soft_placement\", True, \"Allow device soft device placement\")\ntf.flags.DEFINE_boolean(\"log_device_placement\", False, \"Log placement of ops on devices\")\n\nFLAGS = tf.flags.FLAGS\n\n\ndef train():\n num_classes = get_num_classes(FLAGS.train_set)\n model = Char_level_cnn(batch_size=FLAGS.batch_size, num_classes=num_classes, feature=FLAGS.feature)\n\n with tf.Graph().as_default():\n session_conf = tf.ConfigProto(\n allow_soft_placement=FLAGS.allow_soft_placement,\n log_device_placement=FLAGS.log_device_placement)\n session_conf.gpu_options.allow_growth = True\n\n training_set, num_training_iters = create_dataset(FLAGS.train_set, FLAGS.alphabet, FLAGS.max_length,\n FLAGS.batch_size, True)\n test_set, num_test_iters = create_dataset(FLAGS.test_set, FLAGS.alphabet, FLAGS.max_length, FLAGS.batch_size, False)\n train_iterator = training_set.make_initializable_iterator()\n test_iterator = test_set.make_initializable_iterator()\n\n handle = tf.placeholder(tf.string, shape=[])\n keep_prob = tf.placeholder(tf.float32, name='dropout_prob')\n\n iterator = tf.data.Iterator.from_string_handle(handle, training_set.output_types, training_set.output_shapes)\n texts, labels = iterator.get_next()\n\n logits = model.forward(texts, keep_prob)\n loss = model.loss(logits, labels)\n loss_summary = tf.summary.scalar(\"loss\", loss)\n accuracy = model.accuracy(logits, labels)\n accuracy_summary = tf.summary.scalar(\"accuracy\", accuracy)\n batch_size = tf.unstack(tf.shape(texts))[0]\n confusion = model.confusion_matrix(logits, labels)\n global_step = tf.Variable(0, name=\"global_step\", trainable=False)\n\n if FLAGS.optimizer == \"sgd\":\n values = [FLAGS.lr]\n boundaries = []\n for i in range(1, 10):\n values.append(FLAGS.lr / pow(2, i))\n boundaries.append(3 * num_training_iters * i)\n learning_rate = tf.train.piecewise_constant(global_step, boundaries, values)\n optimizer = tf.train.MomentumOptimizer(learning_rate, momentum=0.9)\n else:\n optimizer = tf.train.AdamOptimizer(FLAGS.lr)\n\n train_op = optimizer.minimize(loss, global_step=global_step)\n merged = tf.summary.merge([loss_summary, accuracy_summary])\n init = tf.global_variables_initializer()\n saver = tf.train.Saver()\n if os.path.isdir(FLAGS.log_path):\n shutil.rmtree(FLAGS.log_path)\n os.makedirs(FLAGS.log_path)\n if os.path.isdir(FLAGS.saved_path):\n shutil.rmtree(FLAGS.saved_path)\n os.makedirs(FLAGS.saved_path)\n output_file = open(FLAGS.saved_path + os.sep + \"logs.txt\", \"w\")\n output_file.write(\"Model's parameters: {}\".format(FLAGS.flag_values_dict()))\n best_loss = 1e5\n best_epoch = 0\n with tf.Session(config=session_conf) as sess:\n train_writer = tf.summary.FileWriter(FLAGS.log_path + os.sep + 'train', sess.graph)\n test_writer = tf.summary.FileWriter(FLAGS.log_path + os.sep + 'test')\n sess.run(init)\n for epoch in range(FLAGS.num_epochs):\n sess.run(train_iterator.initializer)\n sess.run(test_iterator.initializer)\n train_handle = sess.run(train_iterator.string_handle())\n test_handle = sess.run(test_iterator.string_handle())\n train_iter = 0\n while True:\n try:\n _, tr_loss, tr_accuracy, summary, step = sess.run(\n [train_op, loss, accuracy, merged, global_step],\n feed_dict={handle: train_handle, keep_prob: FLAGS.dropout})\n print(\"Epoch: {}/{}, Iteration: {}/{}, Loss: {}, Accuracy: {}\".format(\n epoch + 1,\n FLAGS.num_epochs,\n train_iter + 1,\n num_training_iters,\n tr_loss, tr_accuracy))\n train_writer.add_summary(summary, step)\n train_iter += 1\n except (tf.errors.OutOfRangeError, StopIteration):\n break\n if epoch % FLAGS.test_interval == 0:\n loss_ls = []\n loss_summary = tf.Summary()\n accuracy_ls = []\n accuracy_summary = tf.Summary()\n confusion_matrix = np.zeros([num_classes, num_classes], np.int32)\n num_samples = 0\n while True:\n try:\n test_loss, test_accuracy, test_confusion, samples = sess.run(\n [loss, accuracy, confusion, batch_size],\n feed_dict={handle: test_handle, keep_prob: 1.0})\n loss_ls.append(test_loss * samples)\n accuracy_ls.append(test_accuracy * samples)\n confusion_matrix += test_confusion\n num_samples += samples\n except (tf.errors.OutOfRangeError, StopIteration):\n break\n\n mean_test_loss = sum(loss_ls) / num_samples\n loss_summary.value.add(tag='loss', simple_value=mean_test_loss)\n test_writer.add_summary(loss_summary, epoch)\n mean_test_accuracy = sum(accuracy_ls) / num_samples\n accuracy_summary.value.add(tag='accuracy', simple_value=mean_test_accuracy)\n test_writer.add_summary(accuracy_summary, epoch)\n\n output_file.write(\n \"Epoch: {}/{} \\nTest loss: {} Test accuracy: {} \\nTest confusion matrix: \\n{}\\n\\n\".format(\n epoch + 1, FLAGS.num_epochs,\n mean_test_loss,\n mean_test_accuracy,\n confusion_matrix))\n print(\"Epoch: {}/{}, Final loss: {}, Final accuracy: {}\".format(epoch + 1, FLAGS.num_epochs,\n mean_test_loss,\n mean_test_accuracy))\n if mean_test_loss + FLAGS.es_min_delta < best_loss:\n best_loss = mean_test_loss\n best_epoch = epoch\n saver.save(sess, FLAGS.saved_path + os.sep + \"char_level_cnn\")\n if epoch - best_epoch > FLAGS.es_patience > 0:\n print(\"Stop training at epoch {}. The lowest loss achieved is {}\".format(epoch, best_loss))\n break\n\n output_file.close()\n\n\nif __name__ == \"__main__\":\n train()\n",
"\"\"\"\n@author: Thang Nguyen <[email protected]>\n\"\"\"\nimport tensorflow as tf\n\n\nclass Char_level_cnn(object):\n def __init__(self, batch_size=128, num_classes=14, feature=\"small\",\n kernel_size=[7, 7, 3, 3, 3, 3], padding=\"VALID\"):\n super(Char_level_cnn, self).__init__()\n self.batch_size = batch_size\n self.num_classes = num_classes\n if feature == \"small\":\n self.num_filters = 256\n self.stddev_initialization = 0.05\n self.num_fully_connected_features = 1024\n else:\n self.num_filters = 1024\n self.stddev_initialization = 0.02\n self.num_fully_connected_features = 2048\n self.kernel_size = kernel_size\n self.padding = padding\n\n def forward(self, input, keep_prob):\n\n output = tf.expand_dims(input, -1)\n output = self._create_conv(output, [output.get_shape().as_list()[1], self.kernel_size[0], 1, self.num_filters],\n \"conv1\",\n 3)\n output = self._create_conv(output, [1, self.kernel_size[1], self.num_filters, self.num_filters], \"conv2\", 3)\n output = self._create_conv(output, [1, self.kernel_size[2], self.num_filters, self.num_filters], \"conv3\")\n output = self._create_conv(output, [1, self.kernel_size[3], self.num_filters, self.num_filters], \"conv4\")\n output = self._create_conv(output, [1, self.kernel_size[4], self.num_filters, self.num_filters], \"conv5\")\n output = self._create_conv(output, [1, self.kernel_size[5], self.num_filters, self.num_filters], \"conv6\", 3)\n\n new_feature_size = int(self.num_filters * ((input.get_shape().as_list()[2] - 96) / 27))\n flatten = tf.reshape(output, [-1, new_feature_size])\n\n output = self._create_fc(flatten, [new_feature_size, self.num_fully_connected_features], \"fc1\", keep_prob)\n output = self._create_fc(output, [self.num_fully_connected_features, self.num_fully_connected_features], \"fc2\",\n keep_prob)\n output = self._create_fc(output, [self.num_fully_connected_features, self.num_classes], \"fc3\")\n\n return output\n\n def _create_conv(self, input, shape, name_scope, pool_size=None):\n with tf.name_scope(name_scope):\n weight = self._initialize_weight(shape, self.stddev_initialization)\n bias = self._initialize_bias([shape[-1]])\n conv = tf.nn.conv2d(input=input, filter=weight, strides=[1, 1, 1, 1], padding=self.padding, name='conv')\n activation = tf.nn.relu(tf.nn.bias_add(conv, bias), name=\"relu\")\n if pool_size:\n return tf.nn.max_pool(value=activation, ksize=[1, 1, pool_size, 1], strides=[1, 1, pool_size, 1],\n padding=self.padding, name='maxpool')\n else:\n return activation\n\n def _create_fc(self, input, shape, name_scope, keep_prob=None):\n with tf.name_scope(name_scope):\n weight = self._initialize_weight(shape, self.stddev_initialization)\n bias = self._initialize_bias([shape[-1]])\n dense = tf.nn.bias_add(tf.matmul(input, weight), bias, name=\"dense\")\n if keep_prob is not None:\n return tf.nn.dropout(dense, keep_prob, name=\"dropout\")\n else:\n return dense\n\n def _initialize_weight(self, shape, stddev):\n return tf.Variable(tf.truncated_normal(shape=shape, stddev=stddev, dtype=tf.float32, name='weight'))\n\n def _initialize_bias(self, shape):\n return tf.Variable(tf.constant(0, shape=shape, dtype=tf.float32, name='bias'))\n\n def loss(self, logits, labels):\n return tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=labels))\n\n def accuracy(self, logits, labels):\n return tf.reduce_mean(tf.cast(tf.equal(tf.argmax(logits, 1), tf.cast(labels, tf.int64)), dtype=tf.float32))\n\n def confusion_matrix(self, logits, labels):\n return tf.confusion_matrix(tf.cast(labels, tf.int64), tf.argmax(logits, 1), num_classes=self.num_classes)\n"
] |
[
[
"tensorflow.train.AdamOptimizer",
"tensorflow.flags.DEFINE_float",
"tensorflow.summary.scalar",
"tensorflow.Graph",
"tensorflow.data.Iterator.from_string_handle",
"tensorflow.Variable",
"tensorflow.ConfigProto",
"tensorflow.train.piecewise_constant",
"tensorflow.train.MomentumOptimizer",
"tensorflow.Session",
"tensorflow.train.Saver",
"tensorflow.Summary",
"numpy.zeros",
"tensorflow.flags.DEFINE_boolean",
"tensorflow.shape",
"tensorflow.placeholder",
"tensorflow.global_variables_initializer",
"tensorflow.summary.merge",
"tensorflow.flags.DEFINE_integer",
"tensorflow.summary.FileWriter",
"tensorflow.flags.DEFINE_string"
],
[
"tensorflow.nn.bias_add",
"tensorflow.matmul",
"tensorflow.truncated_normal",
"tensorflow.constant",
"tensorflow.nn.max_pool",
"tensorflow.reshape",
"tensorflow.cast",
"tensorflow.expand_dims",
"tensorflow.nn.sparse_softmax_cross_entropy_with_logits",
"tensorflow.name_scope",
"tensorflow.nn.dropout",
"tensorflow.argmax",
"tensorflow.nn.conv2d"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
shaniwein/anyway
|
[
"dcd13bf7dc4a120f4d697ab0c08b906f43eea52e"
] |
[
"anyway/accidents_around_schools.py"
] |
[
"import os\n\nimport math\nimport pandas as pd\nimport sqlalchemy as sa\nfrom sqlalchemy import or_\n\nfrom anyway.backend_constants import BE_CONST\nfrom anyway.models import AccidentMarker, Involved, School\nfrom anyway.app_and_db import db\n\nSUBTYPE_ACCIDENT_WITH_PEDESTRIAN = 1\nLOCATION_ACCURACY_PRECISE = True\nLOCATION_ACCURACY_PRECISE_INT = 1\nINJURED_TYPE_PEDESTRIAN = 1\nYISHUV_SYMBOL_NOT_EXIST = -1\nCONTENT_ENCODING = \"utf-8\"\nHEBREW_ENCODING = \"cp1255\"\nANYWAY_UI_FORMAT_MAP_ONLY = \"https://www.anyway.co.il/?zoom=17&start_date={start_date}&end_date={end_date}&lat={latitude}&lon={longitude}&show_fatal=1&show_severe=1&show_light=1&approx={location_approx}&accurate={location_accurate}&show_markers=1&show_discussions=0&show_urban=3&show_intersection=3&show_lane=3&show_day=7&show_holiday=0&show_time=24&start_time=25&end_time=25&weather=0&road=0&separation=0&surface=0&acctype={acc_type}&controlmeasure=0&district=0&case_type=0&show_rsa=0&age_groups=1,2,3,4&map_only=true\"\nANYWAY_UI_FORMAT_WITH_FILTERS = \"https://www.anyway.co.il/?zoom=17&start_date={start_date}&end_date={end_date}&lat={latitude}&lon={longitude}&show_fatal=1&show_severe=1&show_light=1&approx={location_approx}&accurate={location_accurate}&show_markers=1&show_discussions=0&show_urban=3&show_intersection=3&show_lane=3&show_day=7&show_holiday=0&show_time=24&start_time=25&end_time=25&weather=0&road=0&separation=0&surface=0&acctype={acc_type}&controlmeasure=0&district=0&case_type=0&show_rsa=0&age_groups=1,2,3,4\"\nDATE_INPUT_FORMAT = \"%d-%m-%Y\"\nDATE_URL_FORMAT = \"%Y-%m-%d\"\n\n\ndef get_bounding_box(latitude, longitude, distance_in_km):\n latitude = math.radians(latitude)\n longitude = math.radians(longitude)\n\n radius = 6371\n # Radius of the parallel at given latitude\n parallel_radius = radius * math.cos(latitude)\n\n lat_min = latitude - distance_in_km / radius\n lat_max = latitude + distance_in_km / radius\n lon_min = longitude - distance_in_km / parallel_radius\n lon_max = longitude + distance_in_km / parallel_radius\n rad2deg = math.degrees\n\n return rad2deg(lat_min), rad2deg(lon_min), rad2deg(lat_max), rad2deg(lon_max)\n\n\ndef acc_inv_query(longitude, latitude, distance, start_date, end_date, school):\n lat_min, lon_min, lat_max, lon_max = get_bounding_box(latitude, longitude, distance)\n base_x = lon_min\n base_y = lat_min\n distance_x = lon_max\n distance_y = lat_max\n pol_str = \"POLYGON(({0} {1},{0} {3},{2} {3},{2} {1},{0} {1}))\".format(\n base_x, base_y, distance_x, distance_y\n )\n\n query_obj = (\n db.session.query(Involved, AccidentMarker)\n .join(AccidentMarker, AccidentMarker.provider_and_id == Involved.provider_and_id)\n .filter(AccidentMarker.geom.intersects(pol_str))\n .filter(Involved.injured_type == INJURED_TYPE_PEDESTRIAN)\n .filter(AccidentMarker.provider_and_id == Involved.provider_and_id)\n .filter(\n or_(\n (AccidentMarker.provider_code == BE_CONST.CBS_ACCIDENT_TYPE_1_CODE),\n (AccidentMarker.provider_code == BE_CONST.CBS_ACCIDENT_TYPE_3_CODE),\n )\n )\n .filter(AccidentMarker.created >= start_date)\n .filter(AccidentMarker.created < end_date)\n .filter(AccidentMarker.location_accuracy == LOCATION_ACCURACY_PRECISE_INT)\n .filter(AccidentMarker.yishuv_symbol != YISHUV_SYMBOL_NOT_EXIST)\n .filter(Involved.age_group.in_([1, 2, 3, 4]))\n ) # ages 0-19\n\n df = pd.read_sql_query(query_obj.with_labels().statement, query_obj.session.bind)\n\n if LOCATION_ACCURACY_PRECISE:\n location_accurate = 1\n location_approx = \"\"\n else:\n location_accurate = 1\n location_approx = 1\n ui_url_map_only = ANYWAY_UI_FORMAT_MAP_ONLY.format(\n latitude=school[\"latitude\"],\n longitude=school[\"longitude\"],\n start_date=start_date.strftime(DATE_URL_FORMAT),\n end_date=end_date.strftime(DATE_URL_FORMAT),\n acc_type=SUBTYPE_ACCIDENT_WITH_PEDESTRIAN,\n location_accurate=location_accurate,\n location_approx=location_approx,\n )\n\n ui_url_with_filters = ANYWAY_UI_FORMAT_WITH_FILTERS.format(\n latitude=school[\"latitude\"],\n longitude=school[\"longitude\"],\n start_date=start_date.strftime(DATE_URL_FORMAT),\n end_date=end_date.strftime(DATE_URL_FORMAT),\n acc_type=SUBTYPE_ACCIDENT_WITH_PEDESTRIAN,\n location_accurate=location_accurate,\n location_approx=location_approx,\n )\n\n df[\"anyway_link\"] = ui_url_map_only\n df[\"anyway_link_with_filters\"] = ui_url_with_filters\n df[\"school_id\"] = school[\"id\"]\n df[\"school_name\"] = school[\"school_name\"]\n df[\"school_yishuv_symbol\"] = school[\"yishuv_symbol\"]\n df[\"school_yishuv_name\"] = school[\"yishuv_name\"]\n df[\"school_longitude\"] = school[\"longitude\"]\n df[\"school_latitude\"] = school[\"latitude\"]\n\n return df\n\n\ndef main(start_date, end_date, distance, output_path):\n schools_query = sa.select([School])\n df_schools = pd.read_sql_query(schools_query, db.session.bind)\n df_total = pd.DataFrame()\n df_schools = df_schools.drop_duplicates( # pylint: disable=no-member\n [\"yishuv_name\", \"longitude\", \"latitude\"]\n )\n df_schools.dropna(subset=[\"yishuv_name\"], inplace=True)\n df_schools = df_schools[df_schools.yishuv_symbol != 0]\n df_schools.to_csv(os.path.join(output_path, \"df_schools.csv\"), encoding=CONTENT_ENCODING)\n\n for _, school in df_schools.iterrows():\n df_total = pd.concat(\n [\n df_total,\n acc_inv_query(\n longitude=school[\"longitude\"],\n latitude=school[\"latitude\"],\n distance=distance,\n start_date=start_date,\n end_date=end_date,\n school=school,\n ),\n ],\n axis=0,\n )\n\n df_total.to_csv(os.path.join(output_path, \"df_total.csv\"), encoding=CONTENT_ENCODING)\n\n df_total_involved_count = (\n df_total.groupby(\n [\n \"school_name\",\n \"school_longitude\",\n \"school_latitude\",\n \"school_yishuv_symbol\",\n \"school_yishuv_name\",\n \"anyway_link\",\n \"school_id\",\n ]\n )\n .size()\n .reset_index(name=\"injured_count\")\n .sort_values(\"injured_count\", ascending=False)\n )\n df_total_involved_count.reset_index().to_csv(\n os.path.join(output_path, \"df_total_involved_count.csv\"),\n encoding=CONTENT_ENCODING,\n header=True,\n )\n\n df_total_involved_by_injury = (\n df_total.groupby(\n [\n \"school_id\",\n \"school_name\",\n \"school_longitude\",\n \"school_latitude\",\n \"school_yishuv_symbol\",\n \"school_yishuv_name\",\n \"involved_injury_severity\",\n \"anyway_link\",\n ]\n )\n .size()\n .reset_index(name=\"injured_count\")\n .sort_values(\"injured_count\", ascending=False)\n )\n df_total_involved_by_injury.reset_index().to_csv(\n os.path.join(output_path, \"df_total_involved_by_injury.csv\"),\n encoding=CONTENT_ENCODING,\n header=True,\n )\n\n df_total_involved_injiry_severity_1_2 = (\n df_total[\n (df_total.involved_injury_severity == 1) | (df_total.involved_injury_severity == 2)\n ]\n .groupby(\n [\n \"school_id\",\n \"school_name\",\n \"anyway_link\",\n \"school_longitude\",\n \"school_latitude\",\n \"school_yishuv_symbol\",\n \"school_yishuv_name\",\n ]\n )\n .size()\n .reset_index(name=\"injured_count\")\n .sort_values(\"injured_count\", ascending=False)\n )\n df_total_involved_injiry_severity_1_2.reset_index().to_csv(\n os.path.join(output_path, \"df_total_involved_injiry_severity_1_2.csv\"),\n encoding=CONTENT_ENCODING,\n header=True,\n )\n\n df_total_accident_count = (\n df_total.drop_duplicates(\n [\n \"school_id\",\n \"school_name\",\n \"anyway_link\",\n \"school_longitude\",\n \"school_latitude\",\n \"school_yishuv_symbol\",\n \"school_yishuv_name\",\n \"provider_and_id\",\n ]\n )\n .groupby([\"school_id\", \"school_name\", \"school_yishuv_symbol\", \"school_yishuv_name\"])\n .size()\n .reset_index(name=\"accidents_count\")\n .sort_values(\"accidents_count\", ascending=False)\n )\n df_total_accident_count.reset_index().to_csv(\n os.path.join(output_path, \"df_total_accident_count.csv\"),\n encoding=CONTENT_ENCODING,\n header=True,\n )\n\n df_total_involved_count_by_yishuv = (\n df_total.groupby(\n [\n \"school_yishuv_name\",\n \"school_id\",\n \"school_name\",\n \"anyway_link_with_filters\",\n \"school_longitude\",\n \"school_latitude\",\n \"involved_injury_severity\",\n ]\n )\n .size()\n .reset_index(name=\"injured_count\")\n .loc[\n :,\n [\n \"school_yishuv_name\",\n \"school_name\",\n \"anyway_link_with_filters\",\n \"involved_injury_severity\",\n \"injured_count\",\n \"school_longitude\",\n \"school_latitude\",\n \"school_id\",\n ],\n ]\n )\n df_total_involved_count_by_yishuv = df_total_involved_count_by_yishuv.set_index(\n [\n \"school_yishuv_name\",\n \"school_name\",\n \"anyway_link_with_filters\",\n \"school_longitude\",\n \"school_latitude\",\n \"school_id\",\n \"involved_injury_severity\",\n ]\n ).unstack(-1)\n\n df_total_involved_count_by_yishuv.fillna(\n {\"injured_count\": 0, \"total_injured_count\": 0}, inplace=True\n )\n df_total_involved_count_by_yishuv.loc[\n :, (slice(\"injured_count\"), slice(None))\n ] = df_total_involved_count_by_yishuv.loc[:, (slice(\"injured_count\"), slice(None))].apply(\n lambda x: x.apply(int)\n )\n df_total_involved_count_by_yishuv[\"total_injured_count\"] = (\n df_total_involved_count_by_yishuv.loc[:, [\"injured_count\"]].sum(axis=1)\n ).apply(int)\n\n groups = df_total_involved_count_by_yishuv.loc[\n :,\n [\n \"school_yishuv_name\",\n \"school_name\",\n \"school_longitude\",\n \"school_latitude\",\n \"school_id\",\n \"total_injured_count\",\n ],\n ].groupby([\"school_yishuv_name\"])\n rank_in_yishuv = groups[\"total_injured_count\"].rank(method=\"dense\", ascending=False)\n rank_in_yishuv.name = \"rank\"\n rank_in_yishuv = rank_in_yishuv.apply(int)\n rank_in_yishuv = rank_in_yishuv.to_frame(name=\"rank_in_yishuv\").reset_index()\n\n joined_df = pd.merge(\n df_total_involved_count_by_yishuv.reset_index(),\n rank_in_yishuv,\n on=[\"school_yishuv_name\", \"school_name\", \"school_longitude\", \"school_latitude\"],\n how=\"left\",\n )\n joined_df.sort_values([\"school_yishuv_name\", \"rank_in_yishuv\"], ascending=True, inplace=True)\n joined_df.columns = [\n col if type(col) == str else \"_\".join(map(str, col)) for col in joined_df.columns.values\n ]\n joined_df = joined_df.loc[\n :,\n [\n \"school_yishuv_name\",\n \"school_name\",\n \"rank_in_yishuv\",\n \"school_longitude\",\n \"school_latitude\",\n \"injured_count_1\",\n \"injured_count_2\",\n \"injured_count_3\",\n \"total_injured_count_\",\n \"anyway_link_with_filters\",\n \"school_id\",\n ],\n ]\n joined_df.columns = [\n \"school_yishuv_name\",\n \"school_name\",\n \"rank_in_yishuv\",\n \"school_longitude\",\n \"school_latitude\",\n \"killed_count\",\n \"severly_injured_count\",\n \"light_injured_count\",\n \"total_injured_killed_count\",\n \"anyway_link\",\n \"school_id\",\n ]\n joined_df.to_csv(\n os.path.join(output_path, \"df_total_involved_count_by_yishuv.csv\"),\n encoding=CONTENT_ENCODING,\n header=True,\n )\n"
] |
[
[
"pandas.read_sql_query",
"pandas.DataFrame"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
khmariem/DenseFusion
|
[
"e39f685e6315fc9319d47be0f859585f7dfcf288"
] |
[
"vanilla_segmentation/train.py"
] |
[
"import os\nimport copy\nimport random\nimport argparse\nimport time\nimport numpy as np\nfrom PIL import Image\nimport scipy.io as scio\nimport scipy.misc\nimport torch\nfrom torch.optim.lr_scheduler import ReduceLROnPlateau\nfrom torch.autograd import Variable\nimport torch.optim as optim\nimport torch.nn as nn\nfrom torch.backends import cudnn\n\nfrom data_controller import SegDataset\nfrom loss import Loss\nfrom segnet import SegNet as segnet\nimport sys\nsys.path.append(\"..\")\nfrom lib.utils import setup_logger\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--dataset_root', default='/home/nrp-telechan/Downloads/LabelFusion_Sample_Data/logs/dataset/obj', help=\"dataset root dir (''wrs Dataset'')\")\nparser.add_argument('--batch_size', default=3, help=\"batch size\")\nparser.add_argument('--n_epochs', default=600, help=\"epochs to train\")\nparser.add_argument('--workers', type=int, default=10, help='number of data loading workers')\nparser.add_argument('--lr', default=0.0001, help=\"learning rate\")\nparser.add_argument('--logs_path', default='logs/', help=\"path to save logs\")\nparser.add_argument('--model_save_path', default='trained_models/', help=\"path to save models\")\nparser.add_argument('--log_dir', default='logs/', help=\"path to save logs\")\nparser.add_argument('--resume_model', default='', help=\"resume model name\")\nopt = parser.parse_args()\n\nif __name__ == '__main__':\n opt.manualSeed = random.randint(1, 10000)\n random.seed(opt.manualSeed)\n torch.manual_seed(opt.manualSeed)\n\n dataset = SegDataset(opt.dataset_root, '../datasets/wrs/dataset_config/train_data_list.txt', True, 5000)\n dataloader = torch.utils.data.DataLoader(dataset, batch_size=opt.batch_size, shuffle=True, num_workers=int(opt.workers))\n test_dataset = SegDataset(opt.dataset_root, '../datasets/wrs/dataset_config/test_data_list.txt', False, 1000)\n test_dataloader = torch.utils.data.DataLoader(test_dataset, batch_size=1, shuffle=True, num_workers=int(opt.workers))\n\n print(len(dataset), len(test_dataset))\n\n model = segnet()\n model = model.cuda()\n\n if opt.resume_model != '':\n checkpoint = torch.load('{0}/{1}'.format(opt.model_save_path, opt.resume_model))\n model.load_state_dict(checkpoint)\n for log in os.listdir(opt.log_dir):\n os.remove(os.path.join(opt.log_dir, log))\n\n optimizer = optim.Adam(model.parameters(), lr=opt.lr)\n criterion = Loss()\n best_val_cost = np.Inf\n st_time = time.time()\n\n for epoch in range(1, opt.n_epochs):\n model.train()\n train_all_cost = 0.0\n train_time = 0\n logger = setup_logger('epoch%d' % epoch, os.path.join(opt.log_dir, 'epoch_%d_log.txt' % epoch))\n logger.info('Train time {0}'.format(time.strftime(\"%Hh %Mm %Ss\", time.gmtime(time.time() - st_time)) + ', ' + 'Training started'))\n\n for i, data in enumerate(dataloader, 0):\n rgb, target = data\n rgb, target = Variable(rgb).cuda(), Variable(target).cuda()\n semantic = model(rgb)\n optimizer.zero_grad()\n semantic_loss = criterion(semantic, target)\n train_all_cost += semantic_loss.item()\n semantic_loss.backward()\n optimizer.step()\n logger.info('Train time {0} Batch {1} CEloss {2}'.format(time.strftime(\"%Hh %Mm %Ss\", time.gmtime(time.time() - st_time)), train_time, semantic_loss.item()))\n if train_time != 0 and train_time % 1000 == 0:\n torch.save(model.state_dict(), os.path.join(opt.model_save_path, 'model_current.pth'))\n train_time += 1\n\n train_all_cost = train_all_cost / train_time\n logger.info('Train Finish Avg CEloss: {0}'.format(train_all_cost))\n \n model.eval()\n test_all_cost = 0.0\n test_time = 0\n logger = setup_logger('epoch%d_test' % epoch, os.path.join(opt.log_dir, 'epoch_%d_test_log.txt' % epoch))\n logger.info('Test time {0}'.format(time.strftime(\"%Hh %Mm %Ss\", time.gmtime(time.time() - st_time)) + ', ' + 'Testing started'))\n for j, data in enumerate(test_dataloader, 0):\n rgb, target = data\n rgb, target = Variable(rgb).cuda(), Variable(target).cuda()\n semantic = model(rgb)\n semantic_loss = criterion(semantic, target)\n test_all_cost += semantic_loss.item()\n test_time += 1\n logger.info('Test time {0} Batch {1} CEloss {2}'.format(time.strftime(\"%Hh %Mm %Ss\", time.gmtime(time.time() - st_time)), test_time, semantic_loss.item()))\n\n test_all_cost = test_all_cost / test_time\n logger.info('Test Finish Avg CEloss: {0}'.format(test_all_cost))\n\n if test_all_cost <= best_val_cost:\n best_val_cost = test_all_cost\n torch.save(model.state_dict(), os.path.join(opt.model_save_path, 'model_{}_{}.pth'.format(epoch, test_all_cost)))\n print('----------->BEST SAVED<-----------')\n"
] |
[
[
"torch.manual_seed",
"torch.autograd.Variable"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
KimMeen/STGCN
|
[
"5f67ccb68aae857b92a63bd9bfcbb79dd31f4c66"
] |
[
"network.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jul 20 18:30:55 2020\n\n@author: Ming Jin\n\"\"\"\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport dgl\nimport dgl.function as fn\nfrom dgl import DGLGraph\nfrom layers import TemporalConvLayer, TemporalConvLayer_Residual, SpatialConvLayer, OutputLayer, OutputLayer_Simple\n\n\nclass STGCN(nn.Module):\n '''\n STGCN network described in the paper (Figure 2)\n \n Inputs:\n c: channels, e.g. [1, 64, 16, 64, 64, 16, 64] where [1, 64] means c_in and c_out for the first temporal layer\n T: window length, e.g. 12\n n: num_nodes\n g: fixed DGLGraph\n p: dropout after each 'sandwich', i.e. 'TSTN', block\n control_str: model strcture controller, e.g. 'TSTNTSTN'; T: Temporal Layer, S: Spatio Layer, N: Norm Layer\n x: input feature matrix with the shape [batch, 1, T, n]\n \n Return:\n y: output with the shape [batch, 1, 1, n]\n \n '''\n\n def __init__(self, c, T, n, g, p, control_str):\n \n super(STGCN, self).__init__()\n \n self.control_str = control_str\n self.num_layers = len(control_str)\n self.num_nodes = n\n self.layers = nn.ModuleList()\n self.dropout = nn.Dropout(p)\n # Temporal conv kernel size set to 3\n self.Kt = 3\n # c_index controls the change of channels\n c_index = 0\n num_temporal_layers = 0\n \n # construct network based on 'control_str'\n for i in range(self.num_layers):\n \n layer_i = control_str[i]\n \n # Temporal Layer\n if layer_i == 'T':\n self.layers.append(TemporalConvLayer_Residual(c[c_index], c[c_index + 1], kernel = self.Kt))\n c_index += 1\n num_temporal_layers += 1\n \n # Spatio Layer\n if layer_i == 'S':\n self.layers.append(SpatialConvLayer(c[c_index], c[c_index + 1], g))\n c_index += 1\n \n # Norm Layer\n if layer_i == 'N':\n # TODO: The meaning of this layernorm\n self.layers.append(nn.LayerNorm([n, c[c_index]]))\n \n # c[c_index] is the last element in 'c'\n # T - (self.Kt - 1) * num_temporal_layers returns the timesteps after previous temporal layer transformations cuz dialiation = 1\n self.output = OutputLayer(c[c_index], T - (self.Kt - 1) * num_temporal_layers, self.num_nodes)\n \n for layer in self.layers:\n layer = layer.cuda()\n \n def forward(self, x):\n # Example:\n # batch=64, input_channel=1, window_length=12, num_nodes=207, temporal_kernel = 2\n # input.shape: torch.Size([64, 1, 12, 207])\n # T output.shape: torch.Size([64, 64, 11, 207])\n # S output.shape: torch.Size([64, 16, 11, 207])\n # T output.shape: torch.Size([64, 64, 10, 207])\n # N output.shape: torch.Size([64, 64, 10, 207])\n # T output.shape: torch.Size([64, 64, 9, 207])\n # S output.shape: torch.Size([64, 16, 9, 207])\n # T output.shape: torch.Size([64, 64, 8, 207])\n # OutputLayer output.shape: torch.Size([64, 1, 1, 207])\n\n for i in range(self.num_layers):\n layer_i = self.control_str[i]\n if layer_i == 'N':\n # x.permute(0, 2, 3, 1) leads\n # [batch, channel, timesteps, nodes] to [batch, timesteps, nodes, channel]\n # self.layers[i](x.permute(0, 2, 3, 1)).permute(0, 3, 1, 2) leads\n # [batch, timesteps, nodes, channel] to [batch, channel, timesteps, nodes]\n x = self.dropout(self.layers[i](x.permute(0, 2, 3, 1)).permute(0, 3, 1, 2))\n else:\n # x.shape is [batch, channel, timesteps, nodes]\n x = self.layers[i](x)\n return self.output(x) # [batch, 1, 1, nodes]\n\n\n\nclass STGCN_WAVE(nn.Module):\n '''\n Improved variation of the above STGCN network\n + Extra temporal conv, layernorm, and sophisticated output layer design\n + temporal conv with increasing dialations like in TCN\n \n Inputs:\n c: channels, e.g. [1, 16, 32, 64, 32, 128] where [1, 16] means c_in and c_out for the first temporal layer\n T: window length, e.g. 144, which should larger than the total dialations\n n: num_nodes\n g: fixed DGLGraph\n p: dropout\n control_str: model strcture controller, e.g. 'TNTSTNTSTN'; T: Temporal Layer, S: Spatio Layer, N: Norm Layer\n x: input feature matrix with the shape [batch, 1, T, n]\n \n Return:\n y: output with the shape [batch, 1, 1, n]\n \n Notice:\n ** Temporal layer changes c_in to c_out, but spatial layer doesn't change\n in this way where c_in = c_out = c\n '''\n\n def __init__(self, c, T, n, g, p, control_str):\n \n super(STGCN_WAVE, self).__init__()\n \n self.control_str = control_str\n self.num_layers = len(control_str)\n self.layers = nn.ModuleList()\n self.dropout = nn.Dropout(p)\n # c_index controls the change of channels\n c_index = 0\n # diapower controls the change of dilations in temporal CNNs where dilation = 2^diapower\n diapower = 0\n \n # construct network based on 'control_str'\n for i in range(self.num_layers):\n \n layer_i = control_str[i]\n \n # Temporal Layer\n if layer_i == 'T':\n # Notice: dialation = 2^diapower (e.g. 1, 2, 4, 8) so that \n # T_out = T_in - dialation * (kernel_size - 1) - 1 + 1\n # if padding = 0 and stride = 1\n self.layers.append(TemporalConvLayer_Residual(c[c_index], c[c_index + 1], dia = 2**diapower))\n diapower += 1\n c_index += 1\n \n # Spatio Layer\n if layer_i == 'S':\n self.layers.append(SpatialConvLayer(c[c_index], c[c_index], g))\n \n # Norm Layer\n if layer_i == 'N':\n # TODO: The meaning of this layernorm\n self.layers.append(nn.LayerNorm([n, c[c_index]]))\n \n # c[c_index] is the last element in 'c'\n # T + 1 - 2**(diapower) returns the timesteps after previous temporal layer transformations\n # 'n' will be needed by LayerNorm inside of the OutputLayer\n self.output = OutputLayer(c[c_index], T + 1 - 2**(diapower), n)\n \n for layer in self.layers:\n layer = layer.cuda()\n \n def forward(self, x):\n # Example:\n # batch=8, input_channel=1, window_length=144, num_nodes=207, temporal_kernel = 2\n # x.shape: torch.Size([8, 1, 144, 207])\n # T output.shape: torch.Size([8, 16, 143, 207])\n # N output.shape: torch.Size([8, 16, 143, 207])\n # T output.shape: torch.Size([8, 32, 141, 207])\n # S output.shape: torch.Size([8, 32, 141, 207])\n # T output.shape: torch.Size([8, 64, 137, 207])\n # N output.shape: torch.Size([8, 64, 137, 207])\n # T output.shape: torch.Size([8, 32, 129, 207])\n # S output.shape: torch.Size([8, 32, 129, 207])\n # T output.shape: torch.Size([8, 128, 113, 207])\n # Outputlayer output.shape: torch.Size([8, 1, 1, 207]) \n \n for i in range(self.num_layers):\n layer_i = self.control_str[i]\n if layer_i == 'N':\n # x.permute(0, 2, 3, 1) leads\n # [batch, channel, timesteps, nodes] to [batch, timesteps, nodes, channel]\n # self.layers[i](x.permute(0, 2, 3, 1)).permute(0, 3, 1, 2) leads\n # [batch, timesteps, nodes, channel] to [batch, channel, timesteps, nodes]\n x = self.dropout(self.layers[i](x.permute(0, 2, 3, 1)).permute(0, 3, 1, 2)) \n else:\n # x.shape is [batch, channel, timesteps, nodes]\n x = self.layers[i](x)\n return self.output(x) # [batch, 1, 1, nodes]"
] |
[
[
"torch.nn.Dropout",
"torch.nn.ModuleList",
"torch.nn.LayerNorm"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
bbstats/xicor
|
[
"69d61d5cff5a0e3bc7a2d95660ed3e8e48ef0341"
] |
[
"tests/xi_test.py"
] |
[
"import random\nimport numpy as np\nimport pytest\n\nfrom xicor.xicor import Xi\n\n\"\"\"\nFrom Wikipedia:\nAnscombe's quartet comprises four data sets that have nearly\nidentical simple descriptive statistics, yet have very different distributions\nand appear very different when graphed. Each dataset consists of eleven\n(x,y) points. They were constructed in 1973 by the\nstatistician Francis Anscombe to demonstrate both the importance of graphing\ndata before analyzing it and the effect of outliers and other influential\nobservations on statistical properties.\n\"\"\"\n\n\[email protected]\ndef anscombes_xis(anscombes_quartet):\n random.seed(2020)\n np.random.seed(2020)\n xis = {\n \"xi_1\": Xi(anscombes_quartet[\"x_1\"], anscombes_quartet[\"y_1\"]),\n \"xi_2\": Xi(anscombes_quartet[\"x_2\"], anscombes_quartet[\"y_2\"]),\n \"xi_3\": Xi(anscombes_quartet[\"x_3\"], anscombes_quartet[\"y_3\"]),\n \"xi_4\": Xi(anscombes_quartet[\"x_4\"], anscombes_quartet[\"y_4\"]),\n }\n\n return xis\n\n\ndef test_xi_correlations(anscombes_xis):\n random.seed(2020)\n np.random.seed(2020)\n assert anscombes_xis[\"xi_1\"].correlation == 0.2749999999999999\n assert anscombes_xis[\"xi_2\"].correlation == 0.6\n assert anscombes_xis[\"xi_3\"].correlation == 0.6190476190476191\n assert anscombes_xis[\"xi_4\"].correlation == 0.1000000000000002\n\n\ndef test_p_val_asymptotic(anscombes_xis):\n random.seed(2020)\n np.random.seed(2020)\n # values taken from R code\n assert (\n anscombes_xis[\"xi_1\"].pval_asymptotic(ties=False, nperm=1000)\n == 0.07841556446646347\n )\n assert (\n anscombes_xis[\"xi_2\"].pval_asymptotic(ties=False, nperm=1000)\n == 0.0010040217037570187\n )\n assert (\n anscombes_xis[\"xi_3\"].pval_asymptotic(ties=False, nperm=1000)\n == 0.04989192742513937\n )\n assert (\n anscombes_xis[\"xi_4\"].pval_asymptotic(ties=False, nperm=1000)\n == 0.2599336349448975\n )\n"
] |
[
[
"numpy.random.seed"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ZouaghiHoussem/MTCNN_68_TensorFlow
|
[
"b41dbda229e24d6c79d28c22d910e17fca2618c3"
] |
[
"testing/test_images.py"
] |
[
"#coding:utf-8\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport sys\nrootPath = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), \"../\"))\nsys.path.insert(0, rootPath)\nfrom training.mtcnn_model import P_Net, R_Net, O_Net\nfrom tools.loader import TestLoader\nfrom detection.MtcnnDetector import MtcnnDetector\nfrom detection.detector import Detector\nfrom detection.fcn_detector import FcnDetector\nimport cv2\nimport argparse\n\ndef test(stage, testFolder):\n print(\"Start testing in %s\"%(testFolder))\n detectors = [None, None, None]\n if stage in ['pnet', 'rnet', 'onet']:\n modelPath = os.path.join(rootPath, 'tmp/model/pnet/')\n a = [b[5:-6] for b in os.listdir(modelPath) if b.startswith('pnet-') and b.endswith('.index')]\n maxEpoch = max(map(int, a)) # auto match a max epoch model\n modelPath = os.path.join(modelPath, \"pnet-%d\"%(maxEpoch))\n print(\"Use PNet model: %s\"%(modelPath))\n detectors[0] = FcnDetector(P_Net,modelPath) \n if stage in ['rnet', 'onet']:\n modelPath = os.path.join(rootPath, 'tmp/model/rnet/')\n a = [b[5:-6] for b in os.listdir(modelPath) if b.startswith('rnet-') and b.endswith('.index')]\n maxEpoch = max(map(int, a))\n modelPath = os.path.join(modelPath, \"rnet-%d\"%(maxEpoch))\n print(\"Use RNet model: %s\"%(modelPath))\n detectors[1] = Detector(R_Net, 24, 1, modelPath)\n if stage in ['onet']:\n modelPath = os.path.join(rootPath, 'tmp/model/onet/')\n a = [b[5:-6] for b in os.listdir(modelPath) if b.startswith('onet-') and b.endswith('.index')]\n maxEpoch = max(map(int, a))\n modelPath = os.path.join(modelPath, \"onet-%d\"%(maxEpoch))\n print(\"Use ONet model: %s\"%(modelPath))\n detectors[2] = Detector(O_Net, 48, 1, modelPath)\n mtcnnDetector = MtcnnDetector(detectors=detectors, min_face_size = 24, threshold=[0.9, 0.6, 0.7])\n\n testImages = []\n for name in os.listdir(testFolder):\n testImages.append(os.path.join(testFolder, name))\n testDatas = TestLoader(testImages)\n # Now to detect\n allBoxes, allLandmarks = mtcnnDetector.detect_face(testDatas)\n print(\"\\n\")\n # Save it\n for idx, imagePath in enumerate(testImages):\n image = cv2.imread(imagePath)\n for bbox in allBoxes[idx]:\n cv2.putText(image,str(np.round(bbox[4],2)),(int(bbox[0]),int(bbox[1])),cv2.FONT_HERSHEY_TRIPLEX,1,color=(255,0,255))\n cv2.rectangle(image, (int(bbox[0]),int(bbox[1])),(int(bbox[2]),int(bbox[3])),(0,0,255))\n allLandmark = allLandmarks[idx]\n if allLandmark is not None: # pnet and rnet will be ignore landmark\n for landmark in allLandmark:\n for i in range(len(landmark)/2):\n cv2.circle(image, (int(landmark[2*i]),int(int(landmark[2*i+1]))), 3, (0,0,255))\n savePath = os.path.join(rootPath, 'testing', 'results_%s'%(stage))\n if not os.path.isdir(savePath):\n os.makedirs(savePath)\n cv2.imwrite(os.path.join(savePath, \"result_%d.jpg\" %(idx)), image)\n print(\"Save image to %s\"%(savePath))\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='Create hard bbox sample...',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument('--stage', dest='stage', help='working stage, can be pnet, rnet, onet',\n default='onet', type=str)\n parser.add_argument('--gpus', dest='gpus', help='specify gpu to run. eg: --gpus=0,1',\n default='0', type=str)\n args = parser.parse_args()\n return args\n\nif __name__ == \"__main__\":\n args = parse_args()\n stage = args.stage\n if stage not in ['pnet', 'rnet', 'onet']:\n raise Exception(\"Please specify stage by --stage=pnet or rnet or onet\")\n # Support stage: pnet, rnet, onet\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = args.gpus # set GPU\n test(stage, os.path.join(rootPath, \"testing\", \"images\"))\n\n"
] |
[
[
"numpy.round"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
elifriedman/node2vec
|
[
"0fade3002f84e19cfe7564b5cb9d232dfd63d1ea"
] |
[
"graph2vec/node2vec.py"
] |
[
"import numpy as np\nimport networkx as nx\nimport random\n\n\nclass Graph():\n def __init__(self, nx_G, is_directed, p, q):\n self.G = nx_G.to_directed() if is_directed else nx_G.to_undirected()\n self.is_directed = is_directed\n self.p = p\n self.q = q\n\n def node2vec_walk(self, walk_length, start_node):\n '''\n Simulate a random walk starting from start node.\n '''\n G = self.G\n alias_nodes = self.alias_nodes\n alias_edges = self.alias_edges\n\n walk = [start_node]\n\n while len(walk) < walk_length:\n cur = walk[-1]\n cur_nbrs = sorted(G.neighbors(cur))\n if len(cur_nbrs) > 0:\n if len(walk) == 1:\n walk.append(cur_nbrs[alias_draw(alias_nodes[cur][0], alias_nodes[cur][1])])\n else:\n prev = walk[-2]\n next = cur_nbrs[alias_draw(alias_edges[(prev, cur)][0], \n alias_edges[(prev, cur)][1])]\n walk.append(next)\n else:\n break\n\n return walk\n\n def simulate_walks(self, num_walks, walk_length):\n '''\n Repeatedly simulate random walks from each node.\n '''\n G = self.G\n walks = []\n nodes = list(G.nodes())\n for walk_iter in range(num_walks):\n random.shuffle(nodes)\n for node in nodes:\n walks.append(self.node2vec_walk(walk_length=walk_length, start_node=node))\n\n return walks\n\n def get_alias_edge(self, src, dst):\n '''\n Get the alias edge setup lists for a given edge.\n '''\n G = self.G\n p = self.p\n q = self.q\n\n unnormalized_probs = []\n for dst_nbr in sorted(G.neighbors(dst)):\n if dst_nbr == src:\n unnormalized_probs.append(G[dst][dst_nbr].get('weight', 1)/p)\n elif G.has_edge(dst_nbr, src):\n unnormalized_probs.append(G[dst][dst_nbr].get('weight', 1))\n else:\n unnormalized_probs.append(G[dst][dst_nbr].get('weight', 1)/q)\n norm_const = sum(unnormalized_probs)\n normalized_probs = [float(u_prob)/norm_const for u_prob in unnormalized_probs]\n\n return alias_setup(normalized_probs)\n\n def preprocess_transition_probs(self):\n '''\n Preprocessing of transition probabilities for guiding the random walks.\n '''\n G = self.G\n is_directed = self.is_directed\n\n alias_nodes = {}\n for node in G.nodes():\n unnormalized_probs = [G[node][nbr].get('weight', 1) for nbr in sorted(G.neighbors(node))]\n norm_const = sum(unnormalized_probs)\n normalized_probs = [float(u_prob)/norm_const for u_prob in unnormalized_probs]\n alias_nodes[node] = alias_setup(normalized_probs)\n\n alias_edges = {}\n triads = {}\n\n if is_directed:\n for edge in G.edges():\n alias_edges[edge] = self.get_alias_edge(edge[0], edge[1])\n else:\n for edge in G.edges():\n alias_edges[edge] = self.get_alias_edge(edge[0], edge[1])\n alias_edges[(edge[1], edge[0])] = self.get_alias_edge(edge[1], edge[0])\n\n self.alias_nodes = alias_nodes\n self.alias_edges = alias_edges\n\n return\n\n\ndef alias_setup(probs):\n '''\n Compute utility lists for non-uniform sampling from discrete distributions.\n Refer to https://hips.seas.harvard.edu/blog/2013/03/03/the-alias-method-efficient-sampling-with-many-discrete-outcomes/\n for details\n '''\n K = len(probs)\n q = np.zeros(K)\n J = np.zeros(K, dtype=np.int)\n\n smaller = []\n larger = []\n for kk, prob in enumerate(probs):\n q[kk] = K*prob\n if q[kk] < 1.0:\n smaller.append(kk)\n else:\n larger.append(kk)\n\n while len(smaller) > 0 and len(larger) > 0:\n small = smaller.pop()\n large = larger.pop()\n\n J[small] = large\n q[large] = q[large] + q[small] - 1.0\n if q[large] < 1.0:\n smaller.append(large)\n else:\n larger.append(large)\n\n return J, q\n\ndef alias_draw(J, q):\n '''\n Draw sample from a non-uniform discrete distribution using alias sampling.\n '''\n K = len(J)\n\n kk = int(np.floor(np.random.rand()*K))\n if np.random.rand() < q[kk]:\n return kk\n else:\n return J[kk]\n"
] |
[
[
"numpy.zeros",
"numpy.random.rand"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
zhangdan0602/cogdl
|
[
"35a338f29066e4b1a5d7f46217f09ebceaf13106",
"35a338f29066e4b1a5d7f46217f09ebceaf13106",
"35a338f29066e4b1a5d7f46217f09ebceaf13106"
] |
[
"cogdl/models/nn/pyg_supergat.py",
"cogdl/layers/gcn_layer.py",
"cogdl/pipelines.py"
] |
[
"import random\n\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nfrom torch.nn import Parameter\nimport torch.nn.functional as F\nfrom torch_geometric.nn.conv import MessagePassing\nfrom torch_geometric.utils import (\n remove_self_loops,\n add_self_loops,\n softmax,\n dropout_adj,\n is_undirected,\n accuracy,\n negative_sampling,\n batched_negative_sampling,\n to_undirected,\n)\nimport torch_geometric.nn.inits as tgi\n\nfrom cogdl.trainers.supergat_trainer import SuperGATTrainer\nfrom .. import BaseModel, register_model\n\nfrom typing import List\n\n\n# borrowed from https://github.com/dongkwan-kim/SuperGAT\ndef np_sigmoid(x):\n return 1.0 / (1.0 + np.exp(-x))\n\n\nclass SuperGATLayer(MessagePassing):\n def __init__(\n self,\n in_channels,\n out_channels,\n heads=1,\n concat=True,\n negative_slope=0.2,\n dropout=0,\n bias=True,\n is_super_gat=True,\n attention_type=\"basic\",\n super_gat_criterion=None,\n neg_sample_ratio=0.0,\n edge_sample_ratio=1.0,\n pretraining_noise_ratio=0.0,\n use_pretraining=False,\n to_undirected_at_neg=False,\n scaling_factor=None,\n cache_label=False,\n cache_attention=False,\n **kwargs,\n ):\n super(SuperGATLayer, self).__init__(aggr=\"add\", node_dim=0, **kwargs)\n\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.heads = heads\n self.concat = concat\n self.negative_slope = negative_slope\n self.dropout = dropout\n self.is_super_gat = is_super_gat\n self.attention_type = attention_type\n self.super_gat_criterion = super_gat_criterion\n self.neg_sample_ratio = neg_sample_ratio\n self.edge_sample_ratio = edge_sample_ratio\n self.pretraining_noise_ratio = pretraining_noise_ratio\n self.pretraining = None if not use_pretraining else True\n self.to_undirected_at_neg = to_undirected_at_neg\n self.cache_label = cache_label\n self.cache_attention = cache_attention\n\n self.weight = Parameter(torch.Tensor(in_channels, heads * out_channels))\n\n if self.is_super_gat:\n\n if self.attention_type == \"gat_originated\": # GO\n self.att_mh_1 = Parameter(torch.Tensor(1, heads, 2 * out_channels))\n\n elif self.attention_type == \"dot_product\": # DP\n pass\n\n elif self.attention_type == \"scaled_dot_product\": # SD\n self.scaling_factor = scaling_factor or np.sqrt(self.out_channels)\n\n elif self.attention_type.endswith(\"mask_only\"): # MX\n self.att_mh_1 = Parameter(torch.Tensor(1, heads, 2 * out_channels))\n\n else:\n raise ValueError\n\n else:\n if self.attention_type.endswith(\"gat_originated\") or self.attention_type == \"basic\":\n self.att_mh_1 = Parameter(torch.Tensor(1, heads, 2 * out_channels))\n\n elif self.attention_type.endswith(\"dot_product\"):\n pass\n\n else:\n raise ValueError\n\n self.cache = {\n \"num_updated\": 0,\n \"att\": None, # Use only when self.cache_attention == True for task_type == \"Attention_Dist\"\n \"att_with_negatives\": None, # Use as X for supervision.\n \"att_label\": None, # Use as Y for supervision.\n }\n\n if bias and concat:\n self.bias = Parameter(torch.Tensor(heads * out_channels))\n elif bias and not concat:\n self.bias = Parameter(torch.Tensor(out_channels))\n else:\n self.register_parameter(\"bias\", None)\n\n self.reset_parameters()\n\n def reset_parameters(self):\n tgi.glorot(self.weight)\n tgi.zeros(self.bias)\n for name, param in self.named_parameters():\n if name.startswith(\"att_scaling\"):\n tgi.ones(param)\n elif name.startswith(\"att_bias\"):\n tgi.zeros(param)\n elif name.startswith(\"att_mh\"):\n tgi.glorot(param)\n\n def forward(self, x, edge_index, size=None, batch=None, neg_edge_index=None, attention_edge_index=None):\n \"\"\"\n :param x: [N, F]\n :param edge_index: [2, E]\n :param size:\n :param batch: None or [B]\n :param neg_edge_index: When using explicitly given negative edges.\n :param attention_edge_index: [2, E'], Use for link prediction\n :return:\n \"\"\"\n if isinstance(edge_index, tuple):\n edge_index = torch.stack(edge_index)\n if self.pretraining and self.pretraining_noise_ratio > 0.0:\n edge_index, _ = dropout_adj(\n edge_index,\n p=self.pretraining_noise_ratio,\n force_undirected=is_undirected(edge_index),\n num_nodes=x.size(0),\n training=self.training,\n )\n\n if size is None and torch.is_tensor(x):\n edge_index, _ = remove_self_loops(edge_index)\n edge_index, _ = add_self_loops(edge_index, num_nodes=x.size(0))\n\n # [N, F0] * [F0, heads * F] = [N, heads * F]\n x = torch.matmul(x, self.weight)\n x = x.view(-1, self.heads, self.out_channels)\n\n propagated = self.propagate(edge_index, size=size, x=x)\n\n if (self.is_super_gat and self.training) or (attention_edge_index is not None) or (neg_edge_index is not None):\n\n device = next(self.parameters()).device\n num_pos_samples = int(self.edge_sample_ratio * edge_index.size(1))\n num_neg_samples = int(self.neg_sample_ratio * self.edge_sample_ratio * edge_index.size(1))\n\n if attention_edge_index is not None:\n neg_edge_index = None\n\n elif neg_edge_index is not None:\n pass\n\n elif batch is None:\n if self.to_undirected_at_neg:\n edge_index_for_ns = to_undirected(edge_index, num_nodes=x.size(0))\n else:\n edge_index_for_ns = edge_index\n neg_edge_index = negative_sampling(\n edge_index=edge_index_for_ns,\n num_nodes=x.size(0),\n num_neg_samples=num_neg_samples,\n )\n else:\n neg_edge_index = batched_negative_sampling(\n edge_index=edge_index,\n batch=batch,\n num_neg_samples=num_neg_samples,\n )\n\n if self.edge_sample_ratio < 1.0:\n pos_indices = random.sample(range(edge_index.size(1)), num_pos_samples)\n pos_indices = torch.tensor(pos_indices).long().to(device)\n pos_edge_index = edge_index[:, pos_indices]\n else:\n pos_edge_index = edge_index\n\n att_with_negatives = self._get_attention_with_negatives(\n x=x,\n edge_index=pos_edge_index,\n neg_edge_index=neg_edge_index,\n total_edge_index=attention_edge_index,\n ) # [E + neg_E, heads]\n\n # Labels\n if self.training and (self.cache[\"att_label\"] is None or not self.cache_label):\n att_label = torch.zeros(att_with_negatives.size(0)).float().to(device)\n att_label[: pos_edge_index.size(1)] = 1.0\n elif self.training and self.cache[\"att_label\"] is not None:\n att_label = self.cache[\"att_label\"]\n else:\n att_label = None\n self._update_cache(\"att_label\", att_label)\n self._update_cache(\"att_with_negatives\", att_with_negatives)\n\n return propagated\n\n def message(self, edge_index_i, x_i, x_j, size_i):\n \"\"\"\n :param edge_index_i: [E]\n :param x_i: [E, heads * F]\n :param x_j: [E, heads * F]\n :param size_i: N\n :return: [E, heads, F]\n \"\"\"\n x_j = x_j.view(-1, self.heads, self.out_channels) # [E, heads, F]\n if x_i is not None:\n x_i = x_i.view(-1, self.heads, self.out_channels) # [E, heads, F]\n\n # Compute attention coefficients. [E, heads]\n alpha = self._get_attention(edge_index_i, x_i, x_j, size_i)\n if self.cache_attention:\n self._update_cache(\"att\", alpha)\n\n # Sample attention coefficients stochastically.\n alpha = F.dropout(alpha, p=self.dropout, training=self.training)\n\n # [E, heads, F] * [E, heads, 1] = [E, heads, F]\n return x_j * alpha.view(-1, self.heads, 1)\n\n def update(self, aggr_out):\n \"\"\"\n :param aggr_out: [N, heads, F]\n :return: [N, heads * F]\n \"\"\"\n if self.concat is True:\n aggr_out = aggr_out.view(-1, self.heads * self.out_channels)\n else:\n aggr_out = aggr_out.mean(dim=1)\n\n if self.bias is not None:\n aggr_out = aggr_out + self.bias\n return aggr_out\n\n def _get_attention(\n self, edge_index_i, x_i, x_j, size_i, normalize=True, with_negatives=False, **kwargs\n ) -> torch.Tensor:\n \"\"\"\n :param edge_index_i: [E]\n :param x_i: [E, heads, F]\n :param x_j: [E, heads, F]\n :param size_i: N\n :return: [E, heads]\n \"\"\"\n\n # Compute attention coefficients.\n if self.attention_type == \"basic\" or self.attention_type.endswith(\"gat_originated\"):\n # [E, heads, 2F] * [1, heads, 2F] -> [E, heads]\n alpha = torch.einsum(\"ehf,xhf->eh\", torch.cat([x_i, x_j], dim=-1), self.att_mh_1)\n\n elif self.attention_type == \"scaled_dot_product\":\n alpha = torch.einsum(\"ehf,ehf->eh\", x_i, x_j) / self.scaling_factor\n\n elif self.attention_type == \"dot_product\":\n # [E, heads, F] * [E, heads, F] -> [E, heads]\n alpha = torch.einsum(\"ehf,ehf->eh\", x_i, x_j)\n\n elif \"mask\" in self.attention_type:\n\n # [E, heads, F] * [E, heads, F] -> [E, heads]\n logits = torch.einsum(\"ehf,ehf->eh\", x_i, x_j)\n\n if self.attention_type.endswith(\"scaling\"):\n logits = logits / self.att_scaling\n\n if with_negatives:\n return logits\n\n # [E, heads, 2F] * [1, heads, 2F] -> [E, heads]\n alpha = torch.einsum(\"ehf,xhf->eh\", torch.cat([x_i, x_j], dim=-1), self.att_mh_1)\n alpha = torch.einsum(\"eh,eh->eh\", alpha, torch.sigmoid(logits))\n\n else:\n raise ValueError\n\n if normalize:\n alpha = F.leaky_relu(alpha, self.negative_slope)\n alpha = softmax(alpha, edge_index_i, num_nodes=size_i)\n\n return alpha\n\n def _get_attention_with_negatives(self, x, edge_index, neg_edge_index, total_edge_index=None):\n \"\"\"\n :param x: [N, heads * F]\n :param edge_index: [2, E]\n :param neg_edge_index: [2, neg_E]\n :param total_edge_index: [2, E + neg_E], if total_edge_index is given, use it.\n :return: [E + neg_E, heads]\n \"\"\"\n\n if neg_edge_index is not None and neg_edge_index.size(1) <= 0:\n neg_edge_index = torch.zeros((2, 0, self.heads))\n\n if total_edge_index is None:\n total_edge_index = torch.cat([edge_index, neg_edge_index], dim=-1) # [2, E + neg_E]\n\n total_edge_index_j, total_edge_index_i = total_edge_index # [E + neg_E]\n x_i = torch.index_select(x, 0, total_edge_index_i) # [E + neg_E, heads * F]\n x_j = torch.index_select(x, 0, total_edge_index_j) # [E + neg_E, heads * F]\n size_i = x.size(0) # N\n\n x_j = x_j.view(-1, self.heads, self.out_channels) # [E + neg_E, heads, F]\n if x_i is not None:\n x_i = x_i.view(-1, self.heads, self.out_channels) # [E + neg_E, heads, F]\n\n alpha = self._get_attention(total_edge_index_i, x_i, x_j, size_i, normalize=False, with_negatives=True)\n return alpha\n\n def __repr__(self):\n return \"{}({}, {}, heads={}, concat={}, att_type={}, nsr={}, pnr={})\".format(\n self.__class__.__name__,\n self.in_channels,\n self.out_channels,\n self.heads,\n self.concat,\n self.attention_type,\n self.neg_sample_ratio,\n self.pretraining_noise_ratio,\n )\n\n def _update_cache(self, key, val):\n self.cache[key] = val\n self.cache[\"num_updated\"] += 1\n\n def get_attention_dist(self, edge_index: torch.Tensor, num_nodes: int):\n \"\"\"\n :param edge_index: tensor the shape of which is [2, E]\n :param num_nodes: number of nodes\n :return: Tensor list L the length of which is N.\n L[i] = a_ji for e_{ji} in {E}\n - a_ji = normalized attention coefficient of e_{ji} (shape: [heads, #neighbors])\n \"\"\"\n\n edge_index, _ = remove_self_loops(edge_index)\n edge_index, _ = add_self_loops(edge_index, num_nodes=num_nodes) # [2, E]\n\n att = self.cache[\"att\"] # [E, heads]\n\n att_dist_list = []\n for node_idx in range(num_nodes):\n att_neighbors = att[edge_index[1] == node_idx, :].t() # [heads, #neighbors]\n att_dist_list.append(att_neighbors)\n\n return att_dist_list\n\n\n@register_model(\"supergat\")\nclass SuperGAT(BaseModel):\n @staticmethod\n def add_args(parser):\n \"\"\"Add model-specific arguments to the parser.\"\"\"\n # fmt: off\n parser.add_argument('--num-features', type=int)\n parser.add_argument(\"--num-classes\", type=int)\n parser.add_argument(\"--patience\", type=int, default=100)\n parser.add_argument('--hidden-size', type=int, default=16)\n parser.add_argument(\"--heads\", default=8, type=int)\n parser.add_argument(\"--out-heads\", default=None, type=int)\n parser.add_argument('--dropout', type=float, default=0.5)\n parser.add_argument(\"--attention-type\", type=str, default=\"basic\")\n parser.add_argument(\"--super-gat-criterion\", type=str, default=None)\n parser.add_argument(\"--neg-sample-ratio\", type=float, default=0.5)\n parser.add_argument(\"--edge-sampling-ratio\", type=float, default=0.8)\n parser.add_argument(\"--scaling-factor\", type=float, default=None)\n parser.add_argument(\"--to-undirected-at-neg\", action=\"store_true\")\n parser.add_argument(\"--to-undirected\", action=\"store_true\")\n parser.add_argument(\"--pretraining-noise-ratio\", type=float, default=0.0)\n parser.add_argument(\"--val-interval\", type=int, default=1)\n parser.add_argument(\"--att-lambda\", default=0., type=float)\n parser.add_argument(\"--total-pretraining-epoch\", default=0, type=int)\n # fmt: on\n\n @classmethod\n def build_model_from_args(cls, args):\n return cls(args)\n\n def __init__(self, args):\n super().__init__()\n self.args = args\n\n self.conv1 = SuperGATLayer(\n args.num_features,\n args.hidden_size,\n heads=args.heads,\n dropout=args.dropout,\n concat=True,\n is_super_gat=True,\n attention_type=args.attention_type,\n super_gat_criterion=args.super_gat_criterion,\n neg_sample_ratio=args.neg_sample_ratio,\n edge_sample_ratio=args.edge_sampling_ratio,\n pretraining_noise_ratio=args.pretraining_noise_ratio,\n use_pretraining=False,\n to_undirected_at_neg=args.to_undirected_at_neg,\n scaling_factor=args.scaling_factor,\n )\n\n self.conv2 = SuperGATLayer(\n args.hidden_size * args.heads,\n args.num_classes,\n heads=(args.out_heads or args.heads),\n dropout=args.dropout,\n concat=False,\n is_super_gat=True,\n attention_type=args.attention_type,\n super_gat_criterion=args.super_gat_criterion,\n neg_sample_ratio=args.neg_sample_ratio,\n edge_sample_ratio=args.edge_sampling_ratio,\n pretraining_noise_ratio=args.pretraining_noise_ratio,\n use_pretraining=False,\n to_undirected_at_neg=args.to_undirected_at_neg,\n scaling_factor=args.scaling_factor,\n )\n\n def forward_for_all_layers(self, x, edge_index, batch=None, **kwargs):\n x1 = F.dropout(x, p=self.args.dropout, training=self.training)\n x1 = self.conv1(x1, edge_index, batch=batch, **kwargs)\n x2 = F.elu(x1)\n x2 = F.dropout(x2, p=self.args.dropout, training=self.training)\n x2 = self.conv2(x2, edge_index, batch=batch, **kwargs)\n return x1, x2\n\n def forward(self, x, edge_index, batch=None, **kwargs) -> torch.Tensor:\n\n x = F.dropout(x, p=self.args.dropout, training=self.training)\n x = self.conv1(x, edge_index, batch=batch, **kwargs)\n x = F.elu(x)\n\n x = F.dropout(x, p=self.args.dropout, training=self.training)\n x = self.conv2(x, edge_index, batch=batch, **kwargs)\n\n return x\n\n def set_layer_attrs(self, name, value):\n setattr(self.conv1, name, value)\n setattr(self.conv2, name, value)\n\n def get_attention_dist_by_layer(self, edge_index, num_nodes) -> List[List[torch.Tensor]]:\n \"\"\"\n :param edge_index: tensor the shape of which is [2, E]\n :param num_nodes: number of nodes\n :return List[List[torch.Tensor]]: [L, N, [#neighbors, heads]]\n \"\"\"\n return [\n self.conv1.get_attention_dist(edge_index, num_nodes),\n self.conv2.get_attention_dist(edge_index, num_nodes),\n ]\n\n def modules(self) -> List[SuperGATLayer]:\n return [self.conv1, self.conv2]\n\n @staticmethod\n def get_trainer(args):\n return SuperGATTrainer\n\n\n@register_model(\"supergat-large\")\nclass LargeSuperGAT(BaseModel):\n @staticmethod\n def add_args(parser):\n \"\"\"Add model-specific arguments to the parser.\"\"\"\n # fmt: off\n parser.add_argument('--num-features', type=int)\n parser.add_argument(\"--num-classes\", type=int)\n parser.add_argument(\"--patience\", type=int, default=100)\n parser.add_argument(\"--num-layers\", type=int, default=2)\n parser.add_argument('--hidden-size', type=int, default=8)\n parser.add_argument(\"--heads\", default=8, type=int)\n parser.add_argument(\"--out-heads\", default=None, type=int)\n parser.add_argument('--dropout', type=float, default=0.6)\n parser.add_argument(\"--attention-type\", type=str, default=\"basic\")\n parser.add_argument(\"--super-gat-criterion\", type=str, default=None)\n parser.add_argument(\"--neg-sample-ratio\", type=float, default=0.5)\n parser.add_argument(\"--edge-sampling-ratio\", type=float, default=0.8)\n parser.add_argument(\"--scaling-factor\", type=float, default=None)\n parser.add_argument(\"--to-undirected-at-neg\", action=\"store_true\")\n parser.add_argument(\"--to-undirected\", action=\"store_true\")\n parser.add_argument(\"--use-bn\", action=\"store_true\")\n parser.add_argument(\"--pretraining-noise-ratio\", type=float, default=0.0)\n parser.add_argument(\"--val-interval\", type=int, default=1)\n # fmt: on\n\n @classmethod\n def build_model_from_args(cls, args):\n return cls(args)\n\n def __init__(self, args):\n super().__init__()\n self.args = args\n self.num_layers = self.args.num_layers\n\n conv_common_kwargs = dict(\n dropout=args.dropout,\n is_super_gat=True,\n attention_type=args.attention_type,\n super_gat_criterion=args.super_gat_criterion,\n neg_sample_ratio=args.neg_sample_ratio,\n edge_sample_ratio=args.edge_sampling_ratio,\n pretraining_noise_ratio=args.pretraining_noise_ratio,\n use_pretraining=args.use_pretraining,\n to_undirected_at_neg=args.to_undirected_at_neg,\n scaling_factor=args.scaling_factor,\n )\n self.conv_list = []\n self.bn_list = []\n for conv_id in range(1, self.num_layers + 1):\n if conv_id == 1: # first layer\n in_channels, out_channels = args.num_features, args.hidden_size\n heads, concat = args.heads, True\n elif conv_id == self.num_layers: # last layer\n in_channels, out_channels = args.hidden_size * args.heads, args.num_classes\n heads, concat = args.out_heads or args.heads, False\n else:\n in_channels, out_channels = args.hidden_size * args.heads, args.hidden_size\n heads, concat = args.heads, True\n # conv\n conv = SuperGATLayer(in_channels, out_channels, heads=heads, concat=concat, **conv_common_kwargs)\n conv_name = \"conv{}\".format(conv_id)\n self.conv_list.append(conv)\n setattr(self, conv_name, conv)\n self.add_module(conv_name, conv)\n # bn\n if args.use_bn and conv_id != self.num_layers: # not last layer\n bn = nn.BatchNorm1d(out_channels * heads)\n bn_name = \"bn{}\".format(conv_id)\n self.bn_list.append(bn)\n setattr(self, bn_name, bn)\n self.add_module(bn_name, bn)\n\n print(next(self.modules()))\n\n def forward(self, x, edge_index, batch=None, **kwargs) -> torch.Tensor:\n for conv_idx, conv in enumerate(self.conv_list):\n x = F.dropout(x, p=self.args.dropout, training=self.training)\n x = conv(x, edge_index, **kwargs)\n if conv_idx != self.num_layers - 1:\n if self.args.use_bn:\n x = self.bn_list[conv_idx](x)\n x = F.elu(x)\n return x\n\n def set_layer_attrs(self, name, value):\n for conv in self.conv_list:\n setattr(conv, name, value)\n\n def get_attention_dist_by_layer(self, edge_index, num_nodes) -> List[List[torch.Tensor]]:\n \"\"\"\n :param edge_index: tensor the shape of which is [2, E]\n :param num_nodes: number of nodes\n :return List[List[torch.Tensor]]: [L, N, [#neighbors, heads]]\n \"\"\"\n attention_dist_by_layer = []\n for conv in self.conv_list:\n attention_dist_by_layer.append(conv.get_attention_dist(edge_index, num_nodes))\n return attention_dist_by_layer\n\n def modules(self) -> List[SuperGATLayer]:\n return self.conv_list\n\n @staticmethod\n def get_trainer(args):\n return SuperGATTrainer\n",
"import math\n\nimport torch\nimport torch.nn as nn\n\nfrom cogdl.utils import spmm, get_activation\n\n\nclass GCNLayer(nn.Module):\n \"\"\"\n Simple GCN layer, similar to https://arxiv.org/abs/1609.02907\n \"\"\"\n\n def __init__(self, in_features, out_features, dropout=0.0, activation=None, residual=False, norm=None, bias=True):\n super(GCNLayer, self).__init__()\n self.in_features = in_features\n self.out_features = out_features\n self.linear = nn.Linear(in_features, out_features, bias=bias)\n if dropout > 0:\n self.dropout = nn.Dropout(dropout)\n else:\n self.dropout = None\n if residual:\n self.residual = nn.Linear(in_features, out_features)\n else:\n self.residual = None\n\n if activation is not None:\n self.act = get_activation(activation)\n else:\n self.act = None\n\n if norm is not None:\n if norm == \"batchnorm\":\n self.norm = nn.BatchNorm1d(out_features)\n elif norm == \"layernorm\":\n self.norm = nn.LayerNorm(out_features)\n else:\n raise NotImplementedError\n else:\n self.norm = None\n\n self.reset_parameters()\n\n def reset_parameters(self):\n stdv = 1.0 / math.sqrt(self.out_features)\n torch.nn.init.uniform_(self.linear.weight, -stdv, stdv)\n\n def forward(self, graph, x):\n support = self.linear(x)\n out = spmm(graph, support)\n\n if self.norm is not None:\n out = self.norm(out)\n if self.act is not None:\n out = self.act(out, inplace=True)\n\n if self.residual is not None:\n out = out + self.residual(x)\n if self.dropout is not None:\n out = self.dropout(out)\n return out\n",
"import os\nimport random\n\nimport matplotlib.cm as cm\nimport matplotlib.pyplot as plt\nimport networkx as nx\nimport numpy as np\nfrom numpy.lib.arraysetops import isin\nimport torch\nimport yaml\nfrom grave import plot_network, use_attributes\nfrom tabulate import tabulate\n\nfrom cogdl import oagbert\nfrom cogdl.data import Graph\nfrom cogdl.tasks import build_task\nfrom cogdl.datasets import build_dataset_from_name, NodeDataset\nfrom cogdl.models import build_model\nfrom cogdl.options import get_default_args\nfrom cogdl.datasets.rec_data import build_recommendation_data\n\n\nclass Pipeline(object):\n def __init__(self, app: str, **kwargs):\n self.app = app\n self.kwargs = kwargs\n\n def __call__(self, **kwargs):\n raise NotImplementedError\n\n\nclass DatasetPipeline(Pipeline):\n def __init__(self, app: str, **kwargs):\n super(DatasetPipeline, self).__init__(app, **kwargs)\n\n def __call__(self, dataset, **kwargs):\n if isinstance(dataset, str):\n dataset = [dataset]\n\n return self._call(dataset, **kwargs)\n\n\nclass DatasetStatsPipeline(DatasetPipeline):\n def __init__(self, app: str, **kwargs):\n super(DatasetStatsPipeline, self).__init__(app, **kwargs)\n\n def _call(self, dataset=[], **kwargs):\n if isinstance(dataset, str):\n dataset = [dataset]\n tab_data = []\n col_names = [\n \"Dataset\",\n \"#nodes\",\n \"#edges\",\n \"#features\",\n \"#classes\",\n \"#labeled data\",\n ]\n for name in dataset:\n dataset = build_dataset_from_name(name)\n data = dataset[0]\n\n tab_data.append(\n [\n name,\n data.x.shape[0],\n data.edge_index[0].shape[0],\n data.x.shape[1],\n len(set(data.y.numpy())),\n sum(data.train_mask.numpy()),\n ]\n )\n print(tabulate(tab_data, headers=col_names, tablefmt=\"psql\"))\n\n return tab_data\n\n\nclass DatasetVisualPipeline(DatasetPipeline):\n def __init__(self, app: str, **kwargs):\n super(DatasetVisualPipeline, self).__init__(app, **kwargs)\n\n def _call(self, dataset=\"cora\", seed=-1, depth=3, **kwargs):\n if isinstance(dataset, list):\n dataset = dataset[0]\n name = dataset\n dataset = build_dataset_from_name(name)\n data = dataset[0]\n\n G = nx.Graph()\n edge_index = torch.stack(data.edge_index)\n G.add_edges_from([tuple(edge_index[:, i].numpy()) for i in range(edge_index.shape[1])])\n\n if seed == -1:\n seed = random.choice(list(G.nodes()))\n q = [seed]\n node_set = set([seed])\n node_index = {seed: 0}\n max_index = 1\n for _ in range(depth):\n nq = []\n for x in q:\n for key in G[x].keys():\n if key not in node_set:\n nq.append(key)\n node_set.add(key)\n node_index[key] = node_index[x] + 1\n if len(nq) > 0:\n max_index += 1\n q = nq\n\n cmap = cm.rainbow(np.linspace(0.0, 1.0, max_index))\n\n for node, index in node_index.items():\n G.nodes[node][\"color\"] = cmap[index]\n G.nodes[node][\"size\"] = (max_index - index) * 50\n\n pic_file = f\"{name}.png\"\n plt.subplots()\n plot_network(G.subgraph(list(node_set)), node_style=use_attributes())\n plt.savefig(pic_file)\n print(f\"Sampled ego network saved to {pic_file}\")\n\n return q\n\n\nclass OAGBertInferencePipepline(Pipeline):\n def __init__(self, app: str, model: str, **kwargs):\n super(OAGBertInferencePipepline, self).__init__(app, model=model, **kwargs)\n\n load_weights = kwargs[\"load_weights\"] if \"load_weights\" in kwargs else True\n self.tokenizer, self.bert_model = oagbert(model, load_weights=load_weights)\n\n def __call__(self, sequence, **kwargs):\n tokens = self.tokenizer(sequence, return_tensors=\"pt\", padding=True)\n outputs = self.bert_model(**tokens)\n\n return outputs\n\n\nclass GenerateEmbeddingPipeline(Pipeline):\n def __init__(self, app: str, model: str, **kwargs):\n super(GenerateEmbeddingPipeline, self).__init__(app, model=model, **kwargs)\n\n match_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"match.yml\")\n with open(match_path, \"r\", encoding=\"utf8\") as f:\n match = yaml.load(f, Loader=yaml.FullLoader)\n objective = match.get(\"unsupervised_node_classification\", None)\n for pair_dict in objective:\n if \"blogcatalog\" in pair_dict[\"dataset\"]:\n emb_models = pair_dict[\"model\"]\n elif \"cora\" in pair_dict[\"dataset\"]:\n gnn_models = pair_dict[\"model\"]\n\n if model in emb_models:\n self.method_type = \"emb\"\n args = get_default_args(\n task=\"unsupervised_node_classification\", dataset=\"blogcatalog\", model=model, **kwargs\n )\n elif model in gnn_models:\n self.method_type = \"gnn\"\n args = get_default_args(task=\"unsupervised_node_classification\", dataset=\"cora\", model=model, **kwargs)\n else:\n print(\"Please choose a model from \", emb_models, \"or\", gnn_models)\n exit(0)\n\n self.data_path = kwargs.get(\"data_path\", \"tmp_data.pt\")\n self.num_features = kwargs.get(\"num_features\", None)\n if self.num_features is not None:\n args.num_features = self.num_features\n elif self.method_type == \"gnn\":\n print(\"Please provide num_features for gnn model!\")\n exit(0)\n\n args.model = args.model[0]\n self.model = build_model(args)\n\n self.trainer = self.model.get_trainer(args)\n if self.trainer is not None:\n self.trainer = self.trainer(args)\n\n def __call__(self, edge_index, x=None, edge_weight=None):\n if self.method_type == \"emb\":\n G = nx.Graph()\n if edge_weight is not None:\n if isinstance(edge_index, np.ndarray):\n edges = np.concatenate([edge_index, np.expand_dims(edge_weight, -1)], -1)\n elif isinstance(edge_index, torch.Tensor):\n edges = torch.cat([edge_index, edge_weight.unsqueeze(-1)], -1)\n else:\n print(\"Please provide edges via np.ndarray or torch.Tensor.\")\n return\n G.add_weighted_edges_from(edges.tolist())\n else:\n if not isinstance(edge_index, np.ndarray) and not isinstance(edge_index, torch.Tensor):\n print(\"Please provide edges via np.ndarray or torch.Tensor.\")\n return\n G.add_edges_from(edge_index.tolist())\n\n embeddings = self.model.train(G)\n elif self.method_type == \"gnn\":\n num_nodes = edge_index.max().item() + 1\n if x is None:\n print(\"No input node features, use random features instead.\")\n np.random.randn(num_nodes, self.num_features)\n if isinstance(x, np.ndarray):\n x = torch.from_numpy(x).float()\n if isinstance(edge_index, np.ndarray):\n edge_index = torch.from_numpy(edge_index)\n edge_index = (edge_index[:, 0], edge_index[:, 1])\n data = Graph(x=x, edge_index=edge_index)\n torch.save(data, self.data_path)\n dataset = NodeDataset(path=self.data_path, scale_feat=False)\n embeddings = self.trainer.fit(self.model, dataset, evaluate=False)\n embeddings = embeddings.detach().cpu().numpy()\n\n return embeddings\n\n\nclass RecommendationPipepline(Pipeline):\n def __init__(self, app: str, model: str, **kwargs):\n super(RecommendationPipepline, self).__init__(app, model=model, **kwargs)\n\n if \"data\" in kwargs:\n data = kwargs[\"data\"]\n val_data = test_data = data[-100:, :]\n data = build_recommendation_data(\"custom\", data, val_data, test_data)\n self.data_path = kwargs.get(\"data_path\", \"tmp_data.pt\")\n self.batch_size = kwargs.get(\"batch_size\", 128)\n torch.save(data, self.data_path)\n self.dataset = NodeDataset(path=self.data_path, scale_feat=False)\n elif \"dataset\" in kwargs:\n dataset = kwargs.pop(\"dataset\")\n self.dataset = build_dataset_from_name(dataset)\n else:\n print(\"Please provide recommendation data!\")\n exit(0)\n\n self.batch_size = kwargs.get(\"batch_size\", 2048)\n self.n_items = self.dataset[0].n_params[\"n_items\"]\n\n args = get_default_args(task=\"recommendation\", dataset=\"ali\", model=model, **kwargs)\n args.model = args.model[0]\n\n task = build_task(args, dataset=self.dataset)\n task.train()\n\n self.model = task.model\n self.model.eval()\n\n self.user_emb, self.item_emb = self.model.generate()\n\n def __call__(self, user_batch, **kwargs):\n user_batch = np.array(user_batch)\n user_batch = torch.from_numpy(user_batch).to(self.model.device)\n u_g_embeddings = self.user_emb[user_batch]\n\n # batch-item test\n n_item_batchs = self.n_items // self.batch_size + 1\n rate_batch = np.zeros(shape=(len(user_batch), self.n_items))\n\n i_count = 0\n for i_batch_id in range(n_item_batchs):\n i_start = i_batch_id * self.batch_size\n i_end = min((i_batch_id + 1) * self.batch_size, self.n_items)\n\n item_batch = torch.LongTensor(np.array(range(i_start, i_end))).view(i_end - i_start).to(self.model.device)\n i_g_embddings = self.item_emb[item_batch]\n\n i_rate_batch = self.model.rating(u_g_embeddings, i_g_embddings).detach().cpu()\n\n rate_batch[:, i_start:i_end] = i_rate_batch\n i_count += i_rate_batch.shape[1]\n\n topk = kwargs.get(\"topk\", 10)\n results = {}\n for i in range(len(user_batch)):\n rate = list(zip(range(self.n_items), rate_batch[i]))\n rate.sort(key=lambda x: x[1], reverse=True)\n results[user_batch[i].item()] = [rate[j] for j in range(min(topk, len(rate)))]\n\n return results\n\n\nSUPPORTED_APPS = {\n \"dataset-stats\": {\"impl\": DatasetStatsPipeline, \"default\": {\"dataset\": \"cora\"}},\n \"dataset-visual\": {\"impl\": DatasetVisualPipeline, \"default\": {\"dataset\": \"cora\"}},\n \"oagbert\": {\"impl\": OAGBertInferencePipepline, \"default\": {\"model\": \"oagbert-v1\"}},\n \"generate-emb\": {\"impl\": GenerateEmbeddingPipeline, \"default\": {\"model\": \"prone\"}},\n \"recommendation\": {\"impl\": RecommendationPipepline, \"default\": {\"model\": \"lightgcn\"}},\n}\n\n\ndef check_app(app: str):\n if app in SUPPORTED_APPS:\n targeted_app = SUPPORTED_APPS[app]\n return targeted_app\n\n raise KeyError(\"Unknown app {}, available apps are {}\".format(app, list(SUPPORTED_APPS.keys())))\n\n\ndef pipeline(app: str, **kwargs) -> Pipeline:\n targeted_app = check_app(app)\n task_class = targeted_app[\"impl\"]\n default_args = targeted_app[\"default\"].copy()\n default_args.update(kwargs)\n\n return task_class(app=app, **default_args)\n"
] |
[
[
"torch.nn.BatchNorm1d",
"torch.sigmoid",
"numpy.sqrt",
"torch.Tensor",
"torch.nn.functional.dropout",
"torch.zeros",
"torch.cat",
"torch.einsum",
"torch.is_tensor",
"torch.tensor",
"torch.matmul",
"torch.nn.functional.leaky_relu",
"torch.nn.functional.elu",
"numpy.exp",
"torch.index_select",
"torch.stack"
],
[
"torch.nn.BatchNorm1d",
"torch.nn.Dropout",
"torch.nn.init.uniform_",
"torch.nn.LayerNorm",
"torch.nn.Linear"
],
[
"numpy.expand_dims",
"numpy.linspace",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.savefig",
"torch.from_numpy",
"numpy.random.randn",
"torch.stack",
"numpy.array",
"torch.save"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
qaute/zeitgeist
|
[
"6d62294571e32acc12fbb67f98adf923d5a1533b"
] |
[
"audio/receiver.py"
] |
[
"#!/usr/bin/python3\n\"\"\"\nreceiver.py\n\nThis file tracks an acoustic FSK signal by the phase difference between two microphones.\n\"\"\"\n\nimport time\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sounddevice as sd\nimport scipy.signal as sp\n\n# define waveform parameters\nfs = 44100 # (Hz) sample rate\nfm = 256 # (samples/cycle) (~172 Hz) modulation frequency\nf1 = 55 # (cycles/128 samples) (18949.2 Hz) first carrier frequency\nf2 = 57 # (cycles/128 samples) (19638.3 Hz) second carrier frequency\n\n# generate sample waveform\ntimes = np.linspace(0, fm/fs, fm, False)\ncarrier1 = np.sin(2*np.pi*fs*2/fm*f1*times)\ncarrier2 = np.sin(2*np.pi*fs*2/fm*f2*times)\nblank = times*0\nmask1 = np.reshape(np.concatenate((carrier1[:int(fm/2)], blank[int(fm/2):])), (fm))\nmask2 = np.reshape(np.concatenate((carrier2[:int(fm/2)], blank[int(fm/2):])), (fm))\n\n# define helper functions\ndef corr2(a, b):\n \"\"\"\n Correlates a and b cyclically.\n a is a NxM numpy array --- data for M channels.\n b is a Nx1 numpy array.\n Returns an NxM array.\n \"\"\"\n output = np.zeros(a.shape)\n for i in range(a.shape[0]):\n output[i] = np.sum(np.abs(a*np.roll(b, i, axis=0)), axis=0)\n return output\n\ndef corr(a, b):\n \"\"\"correlates a and b cyclically\"\"\"\n assert(len(a)==len(b))\n output = np.zeros((len(a)))\n plt.plot(a); plt.show()\n for i in range(len(a)):\n output[i] = np.sum(np.abs(a*np.roll(b, i)))\n plt.plot(output); plt.show()\n return output\n\ndef avg(a, n):\n \"\"\"\n Takes cyclic running average of a with 2n-1 points.\n a is a NxM numpy array --- data for M channels.\n Returns an NxM array.\n \"\"\"\n output = np.zeros(a.shape)\n for i in range(a.shape[0]):\n temp = np.roll(a, -i, axis=0)\n output[i] = (temp[0,:]+np.sum(temp[1:n+1,:], axis=0)+np.sum(temp[a.shape[0]-n:,:], axis=0))/(2*n+1)\n return output\n\n\naverage = np.zeros((50))\ncount = 0\n\nwhile True:\n\n data = sd.rec(fm*10, samplerate=fs, channels=2)\n plt.plot(data, label='original')\n\n b, a = sp.butter(3, 0.5, btype='high')\n data2 = sp.filtfilt(b, a, data, padlen=50, axis=0)\n plt.plot(data2, label='filter')\n\n data3 = np.abs(data2)\n plt.plot(data3, label='abs')\n\n n = 5\n data4 = np.zeros(data3.shape)\n for i in range(data3.shape[0]):\n temp = np.roll(data3, -i, axis=0)\n data4[i] = (temp[0]+np.sum(temp[1:n+1], axis=0)+np.sum(temp[data3.shape[0]-n:], axis=0))/(2*n+1)\n plt.plot(data4, label='avg')\n\n b, a = sp.butter(3, 0.01, btype='low')\n data5 = sp.filtfilt(b, a, data4, padlen=50, axis=0)*10\n plt.plot(data5, label='filter2')\n\n data6 = np.zeros(data5.shape[0])\n for i in range(data5.shape[0]):\n data6[i] = np.sum(data5[:,0]*np.roll(data5[:,1], i))/1000\n plt.plot(data6[256:512], label='output')\n\n diff = data6[:256].argmax()\n dist = diff\n if diff > 256/2:\n dist = diff-256\n\n plt.title('{}'.format(dist))\n\n print(dist)\n\n plt.legend()\n plt.show()\n\n"
] |
[
[
"matplotlib.pyplot.legend",
"scipy.signal.filtfilt",
"numpy.abs",
"numpy.linspace",
"numpy.sum",
"numpy.sin",
"matplotlib.pyplot.plot",
"scipy.signal.butter",
"matplotlib.pyplot.show",
"numpy.zeros",
"numpy.roll"
]
] |
[
{
"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": []
}
] |
oxquantum-repo/drl_for_quantum_measurement
|
[
"a02a8f3a7c5b40458f440a63355932409c66921c"
] |
[
"QDE/offline/offline_test_run.py"
] |
[
"import sys\n\nimport math\n\nsys.path.append('../')\nimport mock_pygor\n\nsys.path.append('../')\nsys.path.append('../../')\nsys.path.append('../environments')\nsys.path.append('../utilities')\nsys.path.append('../testing_code')\nsys.path.append('../data')\n\nfrom offline_test_play_episode import offline_test_play_episode\nfrom drl_models import Dueling_DQN_PER_2D\nfrom prioritized_experience_replay import Memory\n\nfrom datetime import datetime\nimport numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras import models\nimport random\nimport pickle\nfrom tqdm import tqdm\nfrom offline_test_environment_creation import double_dot_2d\n\ndef initiate():\n IM_SIZE = 2 # 80\n N_CHANEL = 9 # this is the representation of a block by 9 blocks\n K = 6 # env.action_space.n\n D = IM_SIZE * N_CHANEL\n hidden_layer_sizes = [128, 64, 32]\n gamma = 0.5\n\n # number of random test\n batch_sz = 32\n count = 0\n\n tf.reset_default_graph()\n\n model = Dueling_DQN_PER_2D(D=D, K=K, batch_sz=batch_sz, hidden_layer_sizes=hidden_layer_sizes,\n gamma=gamma, lr=2.3e-6, N_CHANEL=N_CHANEL, IM_SIZE=IM_SIZE, scope=\"DDQN\")\n\n print(\"DRL model loaded\")\n\n init = tf.global_variables_initializer()\n sess = tf.InteractiveSession()\n sess.run(init)\n\n saver = tf.train.Saver()\n\n MODEL_PATH = \"../logs/2d/save_models/2d_mean_std\"\n\n saver.restore(sess, MODEL_PATH)\n model.set_session(sess)\n\n return model\n\ndef reset_session(model):\n model.session.close()\n model = initiate()\n return model\n\ndef end_session(model):\n model.session.close()\n return\n\ndef run(model,epsilon,file_name, MaxStep=60, show_log = False, save = False):\n \n name = file_name\n \n block_size = 32\n\n env = double_dot_2d(block_size , file_name)\n\n '''print(\"Environment initialised\")'''\n \n episode_reward, num_steps_in_episode, total_time_training, env.visit_map, loc_state_list, env = offline_test_play_episode(env, model, epsilon, MaxStep, show_log)\n\n '''plt.imshow(env.pre_classification_prediction)\n plt.colorbar()\n plt.title(\"Pre-classifier Prediction\")\n plt.show()\n \n plt.imshow(env.cnn_prediction)\n plt.colorbar()\n plt.title(\"CNN Prediction\")\n plt.show()\n\n plt.imshow(env.visit_map)\n plt.title(\"Visit Map\")\n plt.show()\n \n plt.imshow(env.total_measurement)\n plt.colorbar()\n plt.title(\"Total measurement\")\n plt.show()\n\n route = np.zeros_like(env.image)\n\n for index, item in enumerate(env.visit_map):\n for index2, item2, in enumerate(item):\n if item2 == 1:\n route[index * block_size:(index + 1) * block_size, index2 * block_size:(index2 + 1) * block_size] = env.image[index * block_size:(index + 1) * block_size, index2 * block_size:(index2 + 1) * block_size]\n\n plt.imshow(route)\n plt.title(\"Trajectory\")\n plt.xlabel('Plunger Gate A')\n plt.ylabel('Plunger Gate B')\n #plt.savefig(\"trajectory5.png\", transparent=True)\n plt.show()\n \n now = datetime.now()\n date_time = now.strftime(\"%m_%d_%Y__%H_%M\")\n print(\"date and time:\",date_time)'''\n \n run_information = {\n \"Name\": name,\n \"Episode reward\": episode_reward,\n \"Number of steps\": num_steps_in_episode,\n \"Total training time (seconds)\": total_time_training,\n \"Location state list\": loc_state_list,\n \"Environment visit map\": env.visit_map,\n \"Bias triangle location\": env.isquantum,\n \"Small window measurements\": env.small_window_measurements,\n \"Small window statistics\": env.small_window_statistics,\n }\n \n #print(run_information)\n if save == True:\n pickle_out = open(\"fine_tuning/mock_run_information\"+date_time+\".pickle\",\"wb\")\n pickle.dump(run_information, pickle_out)\n pickle_out.close()\n \n #np.save('fine_tuning/total_measurement'+date_time, env.total_measurement)\n '''print(\"Play episode completed\")\n print('total_time_training',total_time_training)\n print('Time per step',total_time_training/num_steps_in_episode)'''\n \n return env,episode_reward,num_steps_in_episode\n\n\n\n"
] |
[
[
"tensorflow.train.Saver",
"tensorflow.global_variables_initializer",
"tensorflow.reset_default_graph",
"tensorflow.InteractiveSession"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
Matthew-Boyd/HOPP
|
[
"de4e40efda5bfb28361dc3d9d68d13aa465dcc52"
] |
[
"examples/optimization/layout_opt/hybrid_run.py"
] |
[
"\"\"\"\nA prototype application of the distributed cross-entropy method to the wind optimization problem.\nIn this basic implementation, the number of turbines is fixed and the generative distribution is uncorrelated.\n\nTODO:\n + Add boundary constraints / penalties\n + Add proximity constraints\n + Better order turbine locations\n + Investigate turbine number as an attribute\n + Investigate modeling parameter covariances\n + Investigate other distribution types\n + Investigate parameter transformations\n + Add solar\n + Add storage\n + Add cabling, etc\n + investigate organic approach\n\"\"\"\n\nimport matplotlib as mpl\n\nmpl.use('Agg')\n\nimport os\nfrom dotenv import load_dotenv\n\nimport numpy as np\nfrom matplotlib.animation import (\n PillowWriter,\n )\nfrom matplotlib.lines import Line2D\n\nfrom tools.optimization import (\n setup_run,\n DataRecorder\n )\nfrom hybrid.sites import make_circular_site, make_irregular_site, SiteInfo\nfrom hybrid.log import opt_logger as logger\nfrom hybrid.sites import locations\nfrom hybrid.keys import set_developer_nrel_gov_key\nfrom hybrid.layout.plot_tools import *\n\nfrom parametrized_optimization_driver import ParametrizedOptimizationDriver\nfrom hybrid_optimization_problem import HybridOptimizationProblem\nfrom hybrid_parametrization import HybridParametrization\n\nnp.set_printoptions(precision=2, threshold=10000, linewidth=240)\n\n# Set API key\nload_dotenv()\nNREL_API_KEY = os.getenv(\"NREL_API_KEY\")\nset_developer_nrel_gov_key(NREL_API_KEY) # Set this key manually here if you are not setting it using the .env\n\n\ndef run(default_config: {}) -> None:\n config, output_path, run_name = setup_run(default_config)\n recorder = DataRecorder.make_data_recorder(output_path)\n\n max_evaluations = config['max_evaluations']\n \n location_index = config['location']\n location = locations[location_index]\n \n site = config['site']\n site_data = None\n if site == 'circular':\n site_data = make_circular_site(lat=location[0], lon=location[1], elev=location[2])\n elif site == 'irregular':\n site_data = make_irregular_site(lat=location[0], lon=location[1], elev=location[2])\n else:\n raise Exception(\"Unknown site '\" + site + \"'\")\n \n site_info = SiteInfo(site_data)\n inner_problem = HybridOptimizationProblem(site_info, config['num_turbines'], config['solar_capacity'])\n problem = HybridParametrization(inner_problem)\n \n optimizer = ParametrizedOptimizationDriver(problem, recorder=recorder, **config['optimizer_config'])\n \n figure = plt.figure(1)\n axes = figure.add_subplot(111)\n axes.set_aspect('equal')\n plt.grid()\n plt.tick_params(which='both', labelsize=15)\n plt.xlabel('x (m)', fontsize=15)\n plt.ylabel('y (m)', fontsize=15)\n site_info.plot()\n\n score, evaluation, best_solution = optimizer.central_solution()\n score, evaluation = problem.objective(best_solution) if score is None else score\n \n print(-1, ' ', score, evaluation)\n \n print('setup 1')\n \n num_substeps = 1\n figure, axes = plt.subplots(dpi=200)\n axes.set_aspect(1)\n animation_writer = PillowWriter(2 * num_substeps)\n animation_writer.setup(figure, os.path.join(output_path, 'trajectory.gif'), dpi=200)\n \n print('setup 2')\n _, _, central_solution = optimizer.central_solution()\n \n print('setup 3')\n bounds = problem.inner_problem.site_info.polygon.bounds\n site_sw_bound = np.array([bounds[0], bounds[1]])\n site_ne_bound = np.array([bounds[2], bounds[3]])\n site_center = .5 * (site_sw_bound + site_ne_bound)\n max_delta = max(bounds[2] - bounds[0], bounds[3] - bounds[1])\n reach = (max_delta / 2) * 1.3\n min_plot_bound = site_center - reach\n max_plot_bound = site_center + reach\n \n print('setup 4')\n \n best_score, best_evaluation, best_solution = 0.0, 0.0, None\n \n def plot_candidate(candidate):\n nonlocal best_score, best_evaluation, best_solution\n axes.cla()\n axes.set(xlim=(min_plot_bound[0], max_plot_bound[0]), ylim=(min_plot_bound[1], max_plot_bound[1]))\n wind_color = (153 / 255, 142 / 255, 195 / 255)\n solar_color = (241 / 255, 163 / 255, 64 / 255)\n central_color = (.5, .5, .5)\n conforming_candidate, _, __ = problem.make_conforming_candidate_and_get_penalty(candidate)\n problem.plot_candidate(conforming_candidate, figure, axes, central_color, central_color, alpha=.7)\n \n if best_solution is not None:\n conforming_best, _, __ = problem.make_conforming_candidate_and_get_penalty(best_solution)\n problem.plot_candidate(conforming_best, figure, axes, wind_color, solar_color, alpha=1.0)\n axes.set_xlabel('Best Solution AEP: {}'.format(best_evaluation))\n else:\n axes.set_xlabel('')\n \n axes.legend([\n Line2D([0], [0], color=wind_color, lw=8),\n Line2D([0], [0], color=solar_color, lw=8),\n Line2D([0], [0], color=central_color, lw=8),\n ],\n ['Wind Layout', 'Solar Layout', 'Mean Search Vector'],\n loc='lower left')\n animation_writer.grab_frame()\n \n print('plot candidate')\n \n plot_candidate(central_solution)\n \n central_prev = central_solution\n # TODO: make a smooth transition between points\n # TODO: plot exclusion zones\n print('begin')\n \n while optimizer.num_evaluations() < max_evaluations:\n \n print('step start')\n logger.info(\"Starting step, num evals {}\".format(optimizer.num_evaluations()))\n optimizer.step()\n print('step end')\n \n proportion = min(1.0, optimizer.num_evaluations() / max_evaluations)\n g = 1.0 * proportion\n b = 1.0 - g\n a = .5\n color = (b, g, b)\n best_score, best_evaluation, best_solution = optimizer.best_solution()\n central_score, central_evaluation, central_solution = optimizer.central_solution()\n \n a1 = optimizer.converter.convert_from(central_prev)\n b1 = optimizer.converter.convert_from(central_solution)\n a = np.array(a1, dtype=np.float64)\n b = np.array(b1, dtype=np.float64)\n\n for i in range(num_substeps):\n p = (i + 1) / num_substeps\n c = (1 - p) * a + p * b\n candidate = optimizer.converter.convert_to(c)\n plot_candidate(candidate)\n \n central_prev = central_solution\n print(optimizer.num_iterations(), ' ', optimizer.num_evaluations(), best_score, best_evaluation)\n\n animation_writer.finish()\n\n optimizer.close()\n\n print(\"Results and animation written to \" + os.path.abspath(output_path))\n\n\ndefault_config = {\n 'name': 't2',\n 'location': 1,\n 'site': 'irregular',\n 'solar_capacity': 50000, # kW\n 'num_turbines': 50, #\n 'max_evaluations': 20,\n 'optimizer_config': {\n 'method': 'CMA-ES',\n 'nprocs': 1,\n 'generation_size': 5,\n 'selection_proportion': .33,\n 'prior_scale': 1.0,\n 'prior_params': {\n # \"grid_angle\": {\n # \"mu\": 0.1\n # }\n }\n }\n }\n\nrun(default_config)\n"
] |
[
[
"matplotlib.animation.PillowWriter",
"matplotlib.use",
"numpy.set_printoptions",
"matplotlib.lines.Line2D",
"numpy.array"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jonasht/pythonEstudos
|
[
"5e7d28e7bd82b9d1b08e795867fdbaa743f4b747"
] |
[
"paraVerComoFuncionaAlgumasCoisas/pythonParaAnaliseDeDados/capitulo4-basicosobreONumPy-arrayseprocessamentovetorizado/ipython_3_criando_ndarrays.py"
] |
[
"# coding: utf-8\ndata1 = [6, 7.5, 8., 0., 1.]\nimport numpy as np\narr1 = np.array(data1)\narr1\ndata2 = [[1,2,3,4], [5,6,7,8]]\narr2 = np.array(data2)\narr2\narr2.ndim\narr2.shape\narr1.dtype\narr2.dtype\nnp.zeros(3,6)\nnp.zeros(10)\nnp.zeros((3, 6))\nnp.empty((2, 3, 2))\nnp.arange(15)\n"
] |
[
[
"numpy.arange",
"numpy.array",
"numpy.zeros",
"numpy.empty"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
start2020/MSGC-Seq2Seq
|
[
"70f8db9293c8033a4b4f03f30a0164c360c4bcd0"
] |
[
"pems/originals/analyze.py"
] |
[
"import pandas as pd\r\nimport numpy as np\r\nimport datetime\r\n\r\n\r\n# traffic_file = \"PeMS.h5\"\r\n# df = pd.read_hdf(traffic_file)\r\n#\r\n# data = df.values\r\n# # tmp_df = df[0]\r\n# # tmf_file_name = \"tmp.xlsx\" #保存后删除第一列\r\n# # tmp_df.to_excel()\r\n# # print(tmp_df)\r\n#\r\n# new_pf = pd.read_excel('./tmp.xlsx', sheet_name = 0)\r\n# Time = df.index\r\n#\r\n# print(new_pf)\r\n#\r\n# T1 = int(24*60/5)\r\n#\r\n# start_time = \"2017-01-01 00:00:00\"\r\n# start_time_dt = datetime.datetime.strptime(start_time,\"%Y-%m-%d %H:%M:%S\")\r\n# new_pf.loc[start_time_dt] = data[0]\r\n# loss_index_num = 0\r\n# for time_index in range(1,df.shape[0]):\r\n# print(time_index/df.shape[0])\r\n# time_delta = Time[time_index] - Time[time_index - 1]\r\n# seconds = time_delta.seconds\r\n# if seconds == 300: # 5分钟\r\n# cur_time = str((start_time_dt + datetime.timedelta(minutes=(time_index+loss_index_num) * 5)).strftime(\"%Y-%m-%d %H:%M:%S\"))\r\n# new_pf.loc[datetime.datetime.strptime(cur_time, \"%Y-%m-%d %H:%M:%S\")] = data[time_index]\r\n# else:\r\n# err_index = 0\r\n# print(seconds)\r\n# k = seconds//300 #一次补全k个数据\r\n#\r\n# for j in range(k):\r\n# cur_time = str((start_time_dt + datetime.timedelta(minutes=(time_index + loss_index_num + j) * 5)).strftime(\r\n# \"%Y-%m-%d %H:%M:%S\"))\r\n# res = new_pf.values[(time_index + loss_index_num+ j)-T1*7]#用上一周数据来填补丢失的数据\r\n# new_pf.loc[datetime.datetime.strptime(cur_time, \"%Y-%m-%d %H:%M:%S\")] = res\r\n# loss_index_num += k\r\n#\r\n# print(new_pf.shape)\r\n#\r\n#\r\n# output_name = \"pems_c.h5\"\r\n# new_pf.to_hdf(output_name,'obj3',format='table')\r\n# df = pd.read_hdf(output_name)\r\n# print(df.values.shape)\r\n\r\ntraffic_file = \"pems_c.h5\"\r\nnew_pf = pd.read_hdf(traffic_file)\r\n\r\n\r\nT1 = int(24*60/5)\r\nprint(\"T1 \",T1)\r\nTime = new_pf.index\r\ndata = new_pf.values\r\n\r\nN = data.shape[-1]\r\ndays = data.shape[0]//T1\r\ndayofweek = np.reshape(Time.weekday, newshape = (-1, 1))\r\ntimeofday = (Time.hour * 60 + Time.minute + Time.second / 60) // 5\r\ntimeofday = np.reshape(timeofday, newshape = (-1, 1))\r\ndayofyear = np.reshape(Time.dayofyear-1, newshape = (-1, 1))\r\nnew_time = np.concatenate((timeofday,dayofweek,dayofyear), axis = -1) #(days*T1, 2)\r\n\r\nnew_time = np.expand_dims(new_time, axis=1) # (days*T1, 1, 2)\r\nnew_time = np.tile(new_time,(1,N, 1)) # (days*T1, N, 2)\r\n\r\nprint(new_time.shape)\r\ndata = np.expand_dims(data, axis=-1) # (days*T1, N, 1)\r\nprint(data.shape)\r\ndata = np.concatenate([data,new_time ], axis=-1)#(Days*T1,N,3)\r\nprint(data.shape)\r\n# data_file = './matrix-gman.npz'\r\n# np.savez_compressed(data_file, data)\r\ndata = data.reshape(days,T1,N,4)\r\ndata = data.astype(np.float32)\r\nprint(data.dtype)\r\nprint(data.shape)\r\ndata_file = './matrix.npz'\r\nnp.savez_compressed(data_file, data)# (Days,T1,N,3)\r\n\r\n"
] |
[
[
"pandas.read_hdf",
"numpy.expand_dims",
"numpy.reshape",
"numpy.tile",
"numpy.concatenate",
"numpy.savez_compressed"
]
] |
[
{
"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": []
}
] |
Xiao-dong-Wang/gpytorch
|
[
"92e07cf4dae26083fe0aed926e1dfd483443924e"
] |
[
"gpytorch/variational/whitened_variational_strategy.py"
] |
[
"#!/usr/bin/env python3\n\nimport math\nimport warnings\n\nimport torch\n\nfrom .. import settings\nfrom ..distributions import MultivariateNormal\nfrom ..lazy import (\n BatchRepeatLazyTensor,\n CachedCGLazyTensor,\n CholLazyTensor,\n DiagLazyTensor,\n MatmulLazyTensor,\n PsdSumLazyTensor,\n RootLazyTensor,\n)\nfrom ..module import Module\nfrom ..utils.memoize import cached\nfrom .unwhitened_variational_strategy import UnwhitenedVariationalStrategy\n\n\n# Remove after 1.0\nclass WhitenedVariationalStrategy(UnwhitenedVariationalStrategy):\n def __init__(self, model, inducing_points, variational_distribution, learn_inducing_locations=True):\n warnings.warn(\n \"WhitenedVariationalStrategy is deprecated. Please use VariationalStrategy instead.\", DeprecationWarning\n )\n super().__init__(model, inducing_points, variational_distribution, learn_inducing_locations)\n\n @cached(name=\"logdet_memo\")\n def prior_covar_logdet(self):\n return -self.prior_distribution.lazy_covariance_matrix.logdet()\n\n @cached(name=\"covar_trace_memo\")\n def covar_trace(self):\n variational_covar = self.variational_distribution.covariance_matrix\n prior_covar = self.prior_distribution.covariance_matrix\n batch_shape = prior_covar.shape[:-2]\n return (variational_covar * prior_covar).view(*batch_shape, -1).sum(-1)\n\n @cached(name=\"mean_diff_inv_quad_memo\")\n def mean_diff_inv_quad(self):\n prior_mean = self.prior_distribution.mean\n prior_covar = self.prior_distribution.lazy_covariance_matrix\n variational_mean = self.variational_distribution.mean\n return prior_covar.inv_quad(variational_mean - prior_mean)\n\n def kl_divergence(self):\n variational_dist_u = self.variational_distribution\n prior_dist = self.prior_distribution\n kl_divergence = 0.5 * sum(\n [\n # log|k| - log|S|\n # = log|K| - log|K var_dist_covar K|\n # = -log|K| - log|var_dist_covar|\n self.prior_covar_logdet(),\n -variational_dist_u.lazy_covariance_matrix.logdet(),\n # tr(K^-1 S) = tr(K^1 K var_dist_covar K) = tr(K var_dist_covar)\n self.covar_trace(),\n # (m - \\mu u)^T K^-1 (m - \\mu u)\n # = (K^-1 (m - \\mu u)) K (K^1 (m - \\mu u))\n # = (var_dist_mean)^T K (var_dist_mean)\n self.mean_diff_inv_quad(),\n # d\n -prior_dist.event_shape.numel(),\n ]\n )\n\n return kl_divergence\n\n def initialize_variational_dist(self):\n prior_dist = self.prior_distribution\n inv_prior_dist = torch.distributions.MultivariateNormal(\n prior_dist.mean,\n prior_dist.lazy_covariance_matrix.add_jitter()\n .evaluate()\n .double()\n .inverse()\n .type_as(prior_dist.covariance_matrix),\n )\n self.variational_distribution.initialize_variational_distribution(inv_prior_dist)\n\n def forward(self, x):\n r\"\"\"\n The :func:`~gpytorch.variational.VariationalStrategy.forward` method determines how to marginalize out the\n inducing point function values. Specifically, forward defines how to transform a variational distribution\n over the inducing point values, :math:`q(u)`, in to a variational distribution over the function values at\n specified locations x, :math:`q(f|x)`, by integrating :math:`\\int p(f|x, u)q(u)du`\n\n :param torch.Tensor x: Locations x to get the variational posterior of the function values at.\n :rtype: ~gpytorch.distributions.MultivariateNormal\n :return: The distribution :math:`q(f|x)`\n \"\"\"\n variational_dist = self.variational_distribution\n inducing_points = self.inducing_points\n if inducing_points.dim() < x.dim():\n inducing_points = inducing_points.expand(*x.shape[:-2], *inducing_points.shape[-2:])\n if len(variational_dist.batch_shape) < x.dim() - 2:\n variational_dist = variational_dist.expand(x.shape[:-2])\n\n # If our points equal the inducing points, we're done\n if torch.equal(x, inducing_points):\n # De-whiten the prior covar\n prior_covar = self.prior_distribution.lazy_covariance_matrix\n if isinstance(variational_dist.lazy_covariance_matrix, RootLazyTensor):\n predictive_covar = RootLazyTensor(prior_covar @ variational_dist.lazy_covariance_matrix.root.evaluate())\n else:\n predictive_covar = MatmulLazyTensor(prior_covar @ variational_dist.covariance_matrix, prior_covar)\n\n # Cache some values for the KL divergence\n if self.training:\n self._mean_diff_inv_quad_memo, self._logdet_memo = prior_covar.inv_quad_logdet(\n (variational_dist.mean - self.prior_distribution.mean), logdet=True\n )\n\n return MultivariateNormal(variational_dist.mean, predictive_covar)\n\n # Otherwise, we have to marginalize\n else:\n num_induc = inducing_points.size(-2)\n full_inputs = torch.cat([inducing_points, x], dim=-2)\n full_output = self.model.forward(full_inputs)\n full_mean, full_covar = full_output.mean, full_output.lazy_covariance_matrix\n\n # Mean terms\n test_mean = full_mean[..., num_induc:]\n induc_mean = full_mean[..., :num_induc]\n mean_diff = (variational_dist.mean - induc_mean).unsqueeze(-1)\n\n # Covariance terms\n induc_induc_covar = full_covar[..., :num_induc, :num_induc].add_jitter()\n induc_data_covar = full_covar[..., :num_induc, num_induc:].evaluate()\n data_data_covar = full_covar[..., num_induc:, num_induc:]\n\n # If we're less than a certain size, we'll compute the Cholesky decomposition of induc_induc_covar\n cholesky = False\n if settings.fast_computations.log_prob.off() or (num_induc <= settings.max_cholesky_size.value()):\n induc_induc_covar = CholLazyTensor(induc_induc_covar.cholesky())\n cholesky = True\n\n # Cache the CG results\n # Do not use preconditioning for whitened VI, as it does not seem to improve performance.\n with settings.max_preconditioner_size(0):\n with torch.no_grad():\n eager_rhs = torch.cat([induc_data_covar, mean_diff], -1)\n solve, probe_vecs, probe_vec_norms, probe_vec_solves, tmats = CachedCGLazyTensor.precompute_terms(\n induc_induc_covar,\n eager_rhs.detach(),\n logdet_terms=(not cholesky),\n include_tmats=(not settings.skip_logdet_forward.on() and not cholesky),\n )\n eager_rhss = [eager_rhs.detach()]\n solves = [solve.detach()]\n if settings.skip_logdet_forward.on() and self.training:\n eager_rhss.append(torch.cat([probe_vecs, eager_rhs], -1))\n solves.append(torch.cat([probe_vec_solves, solve[..., : eager_rhs.size(-1)]], -1))\n elif not self.training:\n eager_rhss.append(eager_rhs[..., :-1])\n solves.append(solve[..., :-1])\n\n induc_induc_covar = CachedCGLazyTensor(\n induc_induc_covar,\n eager_rhss=eager_rhss,\n solves=solves,\n probe_vectors=probe_vecs,\n probe_vector_norms=probe_vec_norms,\n probe_vector_solves=probe_vec_solves,\n probe_vector_tmats=tmats,\n )\n\n # Compute some terms that will be necessary for the predicitve covariance and KL divergence\n if self.training:\n interp_data_data_var_plus_mean_diff_inv_quad, logdet = induc_induc_covar.inv_quad_logdet(\n torch.cat([induc_data_covar, mean_diff], -1), logdet=True, reduce_inv_quad=False\n )\n interp_data_data_var = interp_data_data_var_plus_mean_diff_inv_quad[..., :-1]\n mean_diff_inv_quad = interp_data_data_var_plus_mean_diff_inv_quad[..., -1]\n\n # Compute predictive mean\n predictive_mean = torch.add(\n test_mean,\n induc_induc_covar.inv_matmul(mean_diff, left_tensor=induc_data_covar.transpose(-1, -2)).squeeze(-1),\n )\n\n # Compute the predictive covariance\n is_root_lt = isinstance(variational_dist.lazy_covariance_matrix, RootLazyTensor)\n is_repeated_root_lt = isinstance(\n variational_dist.lazy_covariance_matrix, BatchRepeatLazyTensor\n ) and isinstance(variational_dist.lazy_covariance_matrix.base_lazy_tensor, RootLazyTensor)\n if is_root_lt:\n predictive_covar = RootLazyTensor(\n induc_data_covar.transpose(-1, -2) @ variational_dist.lazy_covariance_matrix.root.evaluate()\n )\n elif is_repeated_root_lt:\n predictive_covar = RootLazyTensor(\n induc_data_covar.transpose(-1, -2)\n @ variational_dist.lazy_covariance_matrix.root_decomposition().root.evaluate()\n )\n else:\n predictive_covar = MatmulLazyTensor(\n induc_data_covar.transpose(-1, -2), predictive_covar @ induc_data_covar\n )\n\n if self.training:\n data_covariance = DiagLazyTensor((data_data_covar.diag() - interp_data_data_var).clamp(0, math.inf))\n else:\n neg_induc_data_data_covar = torch.matmul(\n induc_data_covar.transpose(-1, -2).mul(-1), induc_induc_covar.inv_matmul(induc_data_covar)\n )\n data_covariance = data_data_covar + neg_induc_data_data_covar\n predictive_covar = PsdSumLazyTensor(predictive_covar, data_covariance)\n\n # Save the logdet, mean_diff_inv_quad, prior distribution for the ELBO\n if self.training:\n self._memoize_cache[\"prior_distribution_memo\"] = MultivariateNormal(induc_mean, induc_induc_covar)\n self._memoize_cache[\"logdet_memo\"] = -logdet\n self._memoize_cache[\"mean_diff_inv_quad_memo\"] = mean_diff_inv_quad\n\n return MultivariateNormal(predictive_mean, predictive_covar)\n\n def __call__(self, x, prior=False):\n # If we're in prior mode, then we're done!\n if prior:\n return self.model.forward(x)\n\n # Delete previously cached items from the training distribution\n if self.training:\n if hasattr(self, \"_memoize_cache\"):\n delattr(self, \"_memoize_cache\")\n self._memoize_cache = dict()\n # (Maybe) initialize variational distribution\n if not self.variational_params_initialized.item():\n prior_dist = self.prior_distribution\n self._variational_distribution.initialize_variational_distribution(prior_dist)\n self.variational_params_initialized.fill_(1)\n\n return Module.__call__(self, x)\n"
] |
[
[
"torch.no_grad",
"torch.equal",
"torch.cat"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jannsta1/pyx4
|
[
"b0e72c25b8bb0e3e12d4d9de1af78cee7b13b11f"
] |
[
"src/pyx4_base/test_scripts/pyx4_test_logic.py"
] |
[
"#!/usr/bin/env python3\n\n\n\"\"\" ROS node to perform most of the testing logic.\n- Manage subscriptions to relevant topics\n- Parse all the data needed for testing\n- Do the testing\n- All the results are published to the /pyx4_test topic\n\"\"\"\n\nPKG = 'pyx4'\nNAME = 'pyx4_test'\n\nimport sys, time, os, csv\nimport numpy as np\nimport rospy\nfrom pyx4.msg import pyx4_state as Pyx4_msg\nfrom pyx4.msg import pyx4_test as Pyx4_test_msg\nfrom geometry_msgs.msg import PoseStamped, TwistStamped\nfrom mavros_msgs.msg import PositionTarget\nfrom pyx4_base_classes.definitions_pyx4 import TEST_COMP, MISSION_SPECS\nfrom pyx4_base_classes.setpoint_bitmasks import *\n\nclass Pyx4Test():\n \"\"\" Class to handle the main logic, subscribers and publishers\n for Pyx4 unit testing.\n \"\"\"\n def __init__(self, mission_file, comp_file):\n # Position for each waypoint\n self.wpts = Pyx4Test._parse_comp_file(comp_file)\n # Expected timeout, type and velocity for each waypoint\n (self.timeouts,\n self.types,\n self.velocities) = Pyx4Test._parse_mission_file(mission_file)\n\n self.total_wpts = len(self.wpts) + 3\n # Type masks for each waypoint\n self.type_masks = {}\n # Start time of the current waypoint\n self.wpt_start_time = 0\n # Index of the current waypoint\n self.current_wpt = 0\n # List of velocities for the current waypoint\n self.cb_vels = np.empty((0,2), float)\n # Current local position of the drone\n self.current_pos = []\n\n # Publisher for pyx4_test\n self.pyx4_test_pub = rospy.Publisher(NAME + '/pyx4_test',\n Pyx4_test_msg, queue_size=10)\n # Test types\n self.test_types = {'type': 'target_type',\n 'wpt_position': 'wpt_position',\n 'velocity': 'average_velocity',\n 'timeout': 'timeout'}\n\n @staticmethod\n def _parse_comp_file(comp_file):\n \"\"\" Read the test comparison file and return a dictionary of arrays,\n one for each waypoint.\n :param comp_file: a CSV file (label, x, y, z, yaw)\n :return {index: Array(x, y, z, yaw)}\n \"\"\"\n with open(comp_file, 'r') as f:\n reader = csv.DictReader(f)\n return {i+3: np.array(list(map(float, [dic['x'],\n dic['y'],\n dic['z'],\n dic['yaw']])))\n for i, dic in enumerate(reader)}\n\n @staticmethod\n def _parse_mission_file(comp_file):\n \"\"\" Read the test comparison file and return a dictionary of arrays,\n one for each waypoint.\n :param comp_file: a CSV file (label, x, y, z, yaw)\n :return {index: Array(x, y, z, yaw)}\n \"\"\"\n timeouts, targets, velocities = {}, {}, {}\n last_pos = np.array([0, 0])\n with open(comp_file, 'r') as f:\n reader = csv.DictReader(f)\n for i, dic in enumerate(reader):\n # Arming and takeoff states not in mission file,\n # hence we need to shift everything by 3.\n iwpt = i + 3\n # Getting the timeout\n timeouts[iwpt] = int(dic['timeout'])\n \n xy = dic['xy_type']\n z = dic['z_type']\n yaw = dic['yaw_type']\n\n # Get the velocity at each waypoint if\n # xy_type is velocity.\n x = float(dic['x_setpoint'])\n y = float(dic['y_setpoint'])\n # If type velocity and not still.\n if xy == 'vel' and (x > 0 or y > 0):\n velocities[iwpt] = np.array([x, y])\n else: velocities[iwpt] = None\n \n # Getting the bitmask\n if xy == 'pos' and z == 'pos' and yaw == 'pos':\n targets[iwpt] = MASK_XY_POS__Z_POS_YAW_POS\n elif xy == 'pos' and z == 'pos' and yaw == 'vel':\n targets[iwpt] = MASK_XY_POS__Z_POS_YAW_RATE\n elif xy == 'vel' and z == 'pos' and yaw == 'pos':\n targets[iwpt] = MASK_XY_VEL__Z_POS__YAW_POS\n elif xy == 'vel' and z == 'pos' and yaw == 'vel':\n targets[iwpt] = MASK_XY_VEL__Z_POS_YAW_RATE\n elif xy == 'vel' and z == 'vel' and yaw == 'pos':\n targets[iwpt] = MASK_XY_VEL__Z_VEL_YAW_POS\n elif xy == 'vel' and z == 'vel' and yaw == 'vel':\n targets[iwpt] = MASK_XY_VEL__Z_VEL_YAW_RATE\n elif xy == 'pos' and z == 'vel' and yaw == 'pos':\n targets[iwpt] = MASK_XY_POS__Z_VEL_YAW_POS\n \n return timeouts, targets, velocities\n\n def perform_test_pred(self):\n \"\"\" Function to see whether the tests should be performed.\n :return Bool\n \"\"\"\n return self.current_wpt < self.total_wpts and self.current_wpt >= 3\n \n def type_test(self):\n \"\"\" Test to check whether the setpoint types.\n Calls send_message to publish the result in the /pyx4_test topic.\n \"\"\"\n if self.perform_test_pred():\n # Get the type mask that has been published the most\n # for this waypoint\n type_mask = max(self.type_masks[self.current_wpt],\n key=lambda x: self.type_masks[self.current_wpt][x])\n passed = (self.types[self.current_wpt] == type_mask)\n \n self.send_message(self.test_types['type'], passed,\n self.types[self.current_wpt],\n type_mask)\n\n def wpt_position_test(self):\n \"\"\" Test to check whether the position of the drone when it\n reaches each waypoint is correct.\n Calls send_message to publish the result in the /pyx4_test topic.\n \"\"\"\n if self.perform_test_pred():\n # Compare all elements of both arrays\n passed = np.allclose(self.wpts[self.current_wpt],\n self.current_pos,\n rtol=2, atol=1)\n \n\n # Round to 2 decimal places for reporting.\n expected = list([round(x, 2) for x in self.wpts[self.current_wpt]])\n given = list([round(x, 2) for x in self.current_pos])\n \n self.send_message(self.test_types['wpt_position'], passed,\n expected, given)\n\n def velocity_test(self, cb_vels):\n \"\"\" Test to check whether the x and y velocity for setpoints\n of type velocity is more or less constant and as specified.\n Calls send_message to publish the result in the /pyx4_test topic.\n :param cb_vels: a list of the velocities the drone has flown at.\n \"\"\"\n if (self.perform_test_pred() and\n self.velocities[self.current_wpt] is not None):\n cb_vels = cb_vels[35:-35]\n passed = np.allclose(cb_vels, self.velocities[self.current_wpt],\n rtol=1.2, atol=0.1)\n self.send_message(self.test_types['velocity'], passed,\n True, passed)\n\n def timeout_test(self):\n \"\"\" Test to check whether all the timeouts are being followed.\n Calls send_message to publish the result in the /pyx4_test topic.\n \"\"\"\n if self.current_wpt < self.total_wpts and self.current_wpt >= 3:\n expected_to = self.timeouts[self.current_wpt]\n # If we have spent more time than timeout, with 10% margin\n if time.time() - self.wpt_start_time > expected_to * 1.1:\n passed = False\n given = 'more'\n else: passed, given = True, expected_to\n # Send message\n self.send_message(self.test_types['timeout'], passed,\n expected_to, given)\n\n def send_message(self, test_type, passed, expected, given):\n \"\"\" Construnct a message personalised to each test type\n and to whether the test has passed. Then publish the message\n and log it to the console.\n :param test_type (string): wpt_position, type...\n :param passed (Bool): whether the test has passed\n :param expected: an expected test result\n :param given: the actual test result\n \"\"\"\n # Variables to generate the message\n passed_msg = ['FAILED', 'PASSED']\n expected_msg = {self.test_types['wpt_position']: 'to finish at',\n self.test_types['type']: 'type mask',\n self.test_types['velocity']: '',\n self.test_types['timeout']: 'to finish in'}\n \n description = \"\"\"Waypoint {}: {} TEST {}\n Waypoint {} {} the {} test.\n Expected {} {} and got {}\n \"\"\".format(self.current_wpt, # Current waypoint\n test_type.upper(), # Test type\n passed_msg[passed], # FAILED / PASSED\n self.current_wpt, # Current wpt\n passed_msg[passed], # FAILED / PASSED\n test_type, # Test type\n expected_msg[test_type], # type mask, to finish at...\n expected, given) # Expected and given values\n\n # Create the Pyx4 test message and publish\n msg = Pyx4_test_msg()\n msg.test_type = test_type\n msg.waypoint = str(self.current_wpt)\n msg.passed = passed\n msg.description = description\n self.pyx4_test_pub.publish(msg)\n # Show normally if passed,\n if passed: rospy.loginfo(description)\n # Or as an error otherwise\n else: rospy.logerr(description)\n\n def pyx4_callback(self, data):\n \"\"\" Callback triggered every time the drone reaches a waypoint.\n Calls all the test functions and updates the required attributes.\n :param data: pyx4_state message from /pyx4_node/pyx4_state\n \"\"\"\n self.type_test()\n self.wpt_position_test()\n self.velocity_test(self.cb_vels)\n self.timeout_test()\n \n self.wpt_start_time = time.time()\n self.cb_vels = np.empty((0,2), float)\n self.current_wpt += 1\n\n def local_position_callback(self, data):\n \"\"\" ROS subscription callback that updates the attribute\n current_pos.\n :param data: PoseStamped from /mavros/local_position/pose\n \"\"\"\n # Update the current position \n pos = data.pose.position\n self.current_pos = np.array([pos.x, pos.y, pos.z,\n data.pose.orientation.z])\n \n def position_target_callback(self, data):\n \"\"\" ROS subscription callback that gets a target type and\n adds it to a dictionary containing a counter of each type.\n for each waypoint.\n :param data: PositionTarget from /mavros/setpoint_raw/local\n \"\"\"\n tm = data.type_mask\n # If we have not seen the current waypoint yet,\n # add it to the data\n if self.current_wpt not in list(self.type_masks.keys()):\n self.type_masks[self.current_wpt] = {}\n \n if tm in list(self.type_masks[self.current_wpt].keys()):\n self.type_masks[self.current_wpt][tm] += 1\n else:\n self.type_masks[self.current_wpt][tm] = 1\n\n def local_position_vel_callback(self, data):\n \"\"\" ROS subscription callback that adds the current velocity to\n an array of velocities.\n :param data: TwistStamped from /mavros/local_position/velocity_local\n \"\"\"\n vel = data.twist.linear\n self.cb_vels = np.append(self.cb_vels, np.array([[vel.x, vel.y]]),\n axis=0)\n\n def main(self):\n \"\"\" Method to manage subscriptions:\n \n - /pyx4_node/pyx4_state: to know when a waypoint is reached.\n Callback: compare the local position in the test data for that\n waypoint to the mavros/local_position data.\n \n - mavros/local_position/pose: receive the local position\n Callback: update the attribute self.current_pos\n\n - mavros/setpoint_raw_local: receive the target setpoint\n Callback: add the setpoint bitmask to self.type_masks, \n which contains a counter of each type mask for each wpt.\n\n - mavros/local_position/velocity_local: receive the velocity\n Callbacl: add the velocity to a self.cb_vels that is an array\n of velocities\n \"\"\"\n # Subscribe to pyx4_state\n rospy.Subscriber(\"pyx4_node/pyx4_state\", Pyx4_msg,\n self.pyx4_callback)\n # Subscribe to mavros/local_position/pose\n rospy.Subscriber(\"mavros/local_position/pose\", PoseStamped,\n self.local_position_callback)\n # Subscribe to mavros/setpoint_raw/local\n rospy.Subscriber('mavros/setpoint_raw/local', PositionTarget,\n self.position_target_callback)\n # Subscribe to mavros/local_position/velocity_local\n rospy.Subscriber(\"mavros/local_position/velocity_local\", TwistStamped,\n self.local_position_vel_callback)\n \n rospy.init_node(NAME, anonymous=True)\n # TODO: Set proper time\n timeout_t = time.time() + 10.0*1000 #10 seconds\n while not rospy.is_shutdown() and time.time() < timeout_t:\n time.sleep(0.1)\n \nif __name__ == '__main__':\n import argparse\n parser = argparse.ArgumentParser(description=\"ROS test node\")\n parser.add_argument('--mission', type=str, default='basic_test.csv')\n parser.add_argument('--comp', type=str, default='basic_test.csv')\n args = parser.parse_args(rospy.myargv(argv=sys.argv)[1:])\n \n # Mission and comparisson files have the same name by definition\n comp_file = os.path.join(TEST_COMP, args.comp)\n mission_file = os.path.join(MISSION_SPECS, args.mission)\n\n if not os.path.isfile(mission_file):\n raise AttributeError(\"\"\"Mission file {} not found.\n \"\"\".format(mission_file))\n\n if not os.path.isfile(comp_file):\n raise AttributeError(\"\"\"file {} does not exist.\n Run test_data to create the test data for the selected mission.\n \"\"\".format(comp_file))\n \n pyx4_test = Pyx4Test(mission_file, comp_file)\n pyx4_test.main()\n"
] |
[
[
"numpy.array",
"numpy.allclose",
"numpy.empty"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
iesl/box-mlc
|
[
"15439b7e46885458d0c45d530c17f1deac0398f8"
] |
[
"box_mlc/modules/hierarchy_regularizer.py"
] |
[
"\"\"\"Structural Regularization for \"\"\"\nfrom torch.nn.parameter import Parameter\nfrom allennlp.common import Registrable\nfrom allennlp.data.vocabulary import Vocabulary\nfrom pathlib import Path\nfrom networkx.exception import NetworkXException\nfrom typing import List, Tuple, Union, Dict, Any, Optional\nimport torch\nimport networkx as nx\nimport logging\nfrom box_mlc.dataset_readers.hierarchy_readers.hierarchy_reader import (\n HierarchyReader,\n)\n\nlogger = logging.getLogger(__name__)\n\n\nclass HierarchyRegularizer(torch.nn.Module, Registrable):\n \"\"\"Base class to satisfy Registrable and to define the common hierarchy initializations\"\"\"\n\n def __init__(\n self,\n alpha: float,\n hierarchy_reader: HierarchyReader,\n debug_level: int = 0,\n ) -> None:\n \"\"\"\n Args:\n alpha: The regularization parameter that is multiplied with the hierarchy struct loss.\n hierarchy_reader: Creates the adjacency_matrix and the mask\n debug_level: scale of 0 to 3. 0 meaning no-debug (fastest) and 3 highest debugging possible (slowest).\n\n\n Returns: (None)\n\n \"\"\"\n super().__init__() # type:ignore\n self.alpha = alpha\n self.debug_level = debug_level\n self.adjacency_matrix = Parameter(\n hierarchy_reader.adjacency_matrix, requires_grad=False\n ) #: Adj(i,j) =1 => if j is true, i is true.\n # self.mask = Parameter(self.initialize_mask(), requires_grad=False) #type: torch.Tensor\n self.mask: torch.BoolTensor = ( # pylint: disable\n hierarchy_reader.mask # type:ignore\n ) # noqa\n\n def to(self, *args, **kwargs): # type: ignore # noqa\n \"\"\"Deligates to `torch.nn.Module.to`. Additionally moves `self.mask` to the correct device.\n This is needed because we depend on to() to move the all tensors and params to appropriate device.\n\n Args:\n args: same as super class\n kwargs: same as super class\n \"\"\"\n super().to(*args, **kwargs)\n (\n device,\n dtype,\n non_blocking,\n convert_to_format,\n ) = torch._C._nn._parse_to(*args, **kwargs)\n self.mask.to(device=device)\n\n def get_active_adjacency_matrix_and_mask(\n self, active_mask: torch.BoolTensor\n ) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"\n\n Args:\n active_mask: 1D Boolean Tensor of shape (adj.shape[0],) indicating which rows and columns to take.\n\n Returns:\n torch.Tensor: masked adj matrix\n torch.Tensor: masked mask\n \"\"\"\n assert len(active_mask.shape) == 1\n assert active_mask.shape[0] == self.adjacency_matrix.shape[0]\n num_active = torch.sum(active_mask)\n active_mask_float = active_mask.to(dtype=torch.float)\n active_mask_matrix = torch.ger(\n active_mask_float, active_mask_float\n ).to(dtype=torch.bool)\n\n return (self.adjacency_matrix[active_mask_matrix]).reshape(\n num_active, num_active\n ), (self.mask[active_mask_matrix]).reshape(num_active, num_active)\n"
] |
[
[
"torch.sum",
"torch.ger",
"torch._C._nn._parse_to",
"torch.nn.parameter.Parameter"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Dive576/vispy
|
[
"06bedb0e9aa410505dbe283d2c52dc9b168f8ded"
] |
[
"vispy/visuals/filters/clipping_planes.py"
] |
[
"# -*- coding: utf-8 -*-\n# Copyright (c) Vispy Development Team. All Rights Reserved.\n# Distributed under the (new) BSD License. See LICENSE.txt for more info.\n\nfrom functools import lru_cache\n\nimport numpy as np\n\nfrom ..shaders import Function, Varying\nfrom .base_filter import Filter\n\n\nclass PlanesClipper(Filter):\n \"\"\"Clips visual output based on arbitrary clipping planes.\n\n Parameters\n ----------\n cliping_planes : ArrayLike\n Each plane is defined by a position and a normal vector (magnitude is irrelevant). Shape: (n_planes, 2, 3)\n coord_system : str\n Coordinate system used by the clipping planes (see visuals.transforms.transform_system.py)\n\n \"\"\"\n\n VERT_CODE = \"\"\"\n void clip() {\n // Transform back to visual coordinates and clip based on that\n $v_distance_from_clip = $clip_with_planes($itransform(gl_Position).xyz);\n }\n \"\"\"\n\n FRAG_CODE = \"\"\"\n void clip() {\n if ($v_distance_from_clip < 0.)\n discard;\n }\n \"\"\"\n\n def __init__(self, clipping_planes=None, coord_system='scene'):\n tr = ['visual', 'scene', 'document', 'canvas', 'framebuffer', 'render']\n if coord_system not in tr:\n raise ValueError(f'Invalid coordinate system {coord_system}. Must be one of {tr}.')\n self._coord_system = coord_system\n\n super().__init__(\n vcode=Function(self.VERT_CODE), vhook='post', vpos=1,\n fcode=Function(self.FRAG_CODE), fhook='pre', fpos=1,\n )\n\n v_distance_from_clip = Varying('v_distance_from_clip', 'float')\n self.vshader['v_distance_from_clip'] = v_distance_from_clip\n self.fshader['v_distance_from_clip'] = v_distance_from_clip\n\n self.clipping_planes = clipping_planes\n\n @property\n def coord_system(self):\n \"\"\"\n Coordinate system used by the clipping planes (see visuals.transforms.transform_system.py)\n \"\"\"\n # unsettable cause we can't update the transform after being attached\n return self._coord_system\n\n def _attach(self, visual):\n super()._attach(visual)\n self.vshader['itransform'] = visual.get_transform('render', self._coord_system)\n\n @staticmethod\n @lru_cache(maxsize=10)\n def _build_clipping_planes_func(n_planes):\n \"\"\"Build the code snippet used to clip the volume based on self.clipping_planes.\"\"\"\n func_template = '''\n float clip_planes(vec3 loc) {{\n float distance_from_clip = 3.4e38; // max float\n {clips};\n return distance_from_clip;\n }}\n '''\n # the vertex is considered clipped if on the \"negative\" side of the plane\n clip_template = '''\n vec3 relative_vec{idx} = loc - $clipping_plane_pos{idx};\n float distance_from_clip{idx} = dot(relative_vec{idx}, $clipping_plane_norm{idx});\n distance_from_clip = min(distance_from_clip{idx}, distance_from_clip);\n '''\n all_clips = []\n for idx in range(n_planes):\n all_clips.append(clip_template.format(idx=idx))\n formatted_code = func_template.format(clips=''.join(all_clips))\n return Function(formatted_code)\n\n @property\n def clipping_planes(self):\n \"\"\"Get the set of planes used to clip the mesh.\n Each plane is defined by a position and a normal vector (magnitude is irrelevant). Shape: (n_planes, 2, 3)\n \"\"\"\n return self._clipping_planes\n\n @clipping_planes.setter\n def clipping_planes(self, value):\n if value is None:\n value = np.empty([0, 2, 3])\n self._clipping_planes = value\n\n clip_func = self._build_clipping_planes_func(len(value))\n self.vshader['clip_with_planes'] = clip_func\n\n for idx, plane in enumerate(value):\n clip_func[f'clipping_plane_pos{idx}'] = tuple(plane[0])\n clip_func[f'clipping_plane_norm{idx}'] = tuple(plane[1])\n"
] |
[
[
"numpy.empty"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
cemac-ccs/Faze-In_App
|
[
"5a937360b34357785699e36587d6457c2dd88806"
] |
[
"Applications/FlaskApp/flask_app.py"
] |
[
"\"\"\"Routes for core Flask app.\"\"\"\nfrom flask import current_app as app\nfrom flask import render_template, flash, redirect, url_for, request\nfrom flask import session, abort, Blueprint\n#from wtforms import Form, validators, StringField, SelectField, TextAreaField\n#from wtforms import IntegerField, PasswordField, SelectMultipleField, widgets\nimport sqlite3\nimport pandas as pd\n#import numpy as np\nimport os\n#import io\n#import json\nfrom passlib.hash import sha256_crypt\n# Modules for this site\nfrom .access import ChangePwdForm, AccessForm\nfrom .access import table_list, user_login\nfrom .access import is_logged_in, is_logged_in_as_admin\nfrom .access import InsertUser, DeleteUser, AssignRole\n\n# Connect to database\n#DATABASE = '/home/cemacccs/Faze-In_App/FAZEin.db'\nDATABASE = 'FAZEin.db'\nassert os.path.exists(DATABASE), \"Unable to locate database\"\napp.secret_key = 'secret'\nconn = sqlite3.connect(DATABASE, check_same_thread=False)\ncounter = 1\n\nmain_bp = Blueprint('main_bp', __name__,\n template_folder='templates',\n static_folder='static')\n\n\n@main_bp.route('/', methods=[\"GET\"])\ndef index():\n \"\"\"Landing page.\"\"\"\n return render_template('home.html.j2')\n\n@main_bp.route(\"/\")\ndef hitcounter():\n global counter\n counter += 1\n return str(counter)\n\n# Access ----------------------------------------------------------------------\n\n# Login\n@main_bp.route('/login', methods=[\"GET\", \"POST\"])\ndef login():\n if 'logged_in' in session:\n flash('Already logged in', 'warning')\n return redirect(url_for('main_bp.index'))\n if request.method == 'POST':\n # Get form fields\n username = request.form['username']\n password_candidate = request.form['password']\n user_login(username, password_candidate, conn)\n return redirect(url_for('main_bp.index'))\n if request.method == 'GET':\n return render_template('login.html.j2')\n\n\n# Logout\n@main_bp.route('/logout')\n@is_logged_in\ndef logout():\n session.clear()\n flash('You are now logged out', 'success')\n return redirect(url_for('main_bp.index'))\n\n\n# Change password\n@main_bp.route('/change-pwd', methods=[\"GET\", \"POST\"])\n@is_logged_in\ndef change_pwd():\n username = session['username']\n form = ChangePwdForm(request.form)\n if request.method == 'POST' and form.validate():\n user = pd.read_sql_query(\"SELECT * FROM users where username is '\"\n + username + \"' ;\", conn)\n password = user.password[0]\n current = form.current.data\n if sha256_crypt.verify(current, password):\n user.password = sha256_crypt.hash(str(form.new.data))\n sql = \"UPDATE users SET password = ? WHERE username is ? ;\"\n cur = conn.cursor()\n cur.execute(sql, (user.password[0], str(username)))\n conn.commit()\n flash('Password changed', 'success')\n return redirect(url_for('main_bp.change_pwd'))\n else:\n flash('Current password incorrect', 'danger')\n return redirect(url_for('main_bp.change_pwd'))\n return render_template('change-pwd.html.j2', form=form)\n\n\n# Access settings for a given user\n@main_bp.route('/account/<string:username>', methods=['GET', 'POST'])\n@is_logged_in\ndef account(username):\n role = session['usertype']\n # display role\n # user name\n # potential to add affiliations and email to give more bespoke access to\n # who can edit which volcanoes. Eg. Prject or Institute\n return render_template('account.html.j2', username=username, Role=role)\n\n# Additional logged in as Admin only pages ------------------------------\n\n\n@main_bp.route('/admin/information', methods=['GET', 'POST'])\n@is_logged_in_as_admin\ndef admininfo():\n return render_template('admininfo.html.j2')\n\n\n@main_bp.route('/admin/users', methods=['GET', 'POST'])\n@is_logged_in_as_admin\ndef ViewOrAddUsers():\n df = pd.read_sql_query(\"SELECT * FROM Users ;\", conn)\n df['password'] = '********'\n # add roles\n u2r = pd.read_sql_query(\"SELECT * FROM users_roles ;\", conn)\n roles = pd.read_sql_query(\"SELECT * FROM roles ;\", conn)\n u2r2 = pd.merge(u2r, roles, on='group_id')\n del u2r2['group_id']\n usersandroles = pd.merge(df, u2r2, on='id', how='outer')\n usersandroles.rename(columns={'name': 'Role'}, inplace=True)\n usersandroles = usersandroles.dropna(subset=['username'])\n colnames = [s.replace(\"_\", \" \").title() for s in usersandroles.columns.values[1:]]\n return render_template('view.html.j2', title='Users', colnames=colnames,\n tableClass='Users', editLink=\"edit\",\n data=usersandroles)\n\n\n# Add entry\n@main_bp.route('/add/Users', methods=[\"GET\", \"POST\"])\n@is_logged_in_as_admin\ndef add():\n form = eval(\"Users_Form\")(request.form)\n if request.method == 'POST' and form.validate():\n # Get form fields:\n # Check\n if len(str(form.password.data)) < 8:\n return flash('password must be more than 8 characters',\n 'danger')\n form.password.data = sha256_crypt.hash(str(form.password.data))\n formdata = []\n for f, field in enumerate(form):\n formdata.append(field.data)\n InsertUser(formdata[0], formdata[1], conn)\n flash('User Added', 'success')\n return redirect(url_for('main_bp.add', tableClass='Users'))\n return render_template('add.html.j2', title='Add Users', tableClass='Users',\n form=form)\n\n\n# Delete entry\n@main_bp.route('/delete/<string:tableClass>/<string:id>', methods=['POST'])\n@is_logged_in_as_admin\ndef delete(tableClass, id):\n # Retrieve DB entry:\n user = pd.read_sql_query(\"SELECT * FROM Users where id = \" + id + \" ;\",\n conn)\n username = user.username\n DeleteUser(username[0], conn)\n flash('User Deleted', 'success')\n return redirect(url_for('main_bp.ViewOrAddUsers'))\n\n\n# Access settings for a given user\n@main_bp.route('/access/<string:id>', methods=['GET', 'POST'])\n@is_logged_in_as_admin\ndef access(id):\n form = AccessForm(request.form)\n form.Role.choices = table_list('roles', 'name', conn)[1:]\n # Retrieve user DB entry:\n user = pd.read_sql_query(\"SELECT * FROM Users where id = \" + id + \" ;\",\n conn)\n if user.empty:\n abort(404)\n # Retrieve all current role\n u2r = pd.read_sql_query(\"SELECT * FROM users_roles WHERE id = \" + id +\n \";\", conn)\n gid = u2r.group_id[0]\n current_role = pd.read_sql_query(\"SELECT * FROM roles WHERE group_id = \"\n + str(gid) + \";\", conn)\n # If user submits edit entry form:\n if request.method == 'POST' and form.validate():\n new_role = form.Role.data\n AssignRole(user.username[0], new_role, conn)\n print('test')\n # Return with success\n flash('Edits successful', 'success')\n return redirect(url_for('main_bp.ViewOrAddUsers'))\n # Pre-populate form fields with existing data:\n form.username.render_kw = {'readonly': 'readonly'}\n form.username.data = user.username[0]\n form.Role.data = current_role.name[0]\n return render_template('access.html.j2', form=form, id=id)\n\n# static information pages ---------------------------------------------------\n\n@main_bp.route('/copyright', methods=[\"GET\"])\ndef copyright():\n return render_template('copyright.html.j2')\n\n@main_bp.route('/privacy', methods=[\"GET\"])\ndef privacy():\n return render_template('privacy.html.j2')\n\n@main_bp.route('/contribute', methods=[\"GET\"])\ndef contribute():\n return render_template('contributor_guidelines.html.j2')\n\n@main_bp.route('/about', methods=[\"GET\"])\ndef about():\n return render_template('about.html.j2')\n\n@main_bp.route('/contact', methods=[\"GET\"])\ndef contact():\n return render_template('contact.html.j2')\n\n@main_bp.route('/modelinfo', methods=[\"GET\"])\ndef infopage1():\n return render_template('modelinfo.html.j2')\n"
] |
[
[
"pandas.read_sql_query",
"pandas.merge"
]
] |
[
{
"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": []
}
] |
kevslinger/stable-baselines
|
[
"4bf9f3c1db49f462f5fb35df967d836d92a3dbcd"
] |
[
"stable_baselines/deepq_lstm/build_graph.py"
] |
[
"\"\"\"Deep Q learning graph\n\nThe functions in this file can are used to create the following functions:\n\n======= act ========\n\n Function to chose an action given an observation\n\n :param observation: (Any) Observation that can be feed into the output of make_obs_ph\n :param stochastic: (bool) if set to False all the actions are always deterministic (default False)\n :param update_eps_ph: (float) update epsilon a new value, if negative not update happens (default: no update)\n :return: (TensorFlow Tensor) tensor of dtype tf.int64 and shape (BATCH_SIZE,) with an action to be performed for\n every element of the batch.\n\n\n======= act (in case of parameter noise) ========\n\n Function to chose an action given an observation\n\n :param observation: (Any) Observation that can be feed into the output of make_obs_ph\n :param stochastic: (bool) if set to False all the actions are always deterministic (default False)\n :param update_eps_ph: (float) update epsilon a new value, if negative not update happens\n (default: no update)\n :param reset_ph: (bool) reset the perturbed policy by sampling a new perturbation\n :param update_param_noise_threshold_ph: (float) the desired threshold for the difference between\n non-perturbed and perturbed policy\n :param update_param_noise_scale_ph: (bool) whether or not to update the scale of the noise for the next time it is\n re-perturbed\n :return: (TensorFlow Tensor) tensor of dtype tf.int64 and shape (BATCH_SIZE,) with an action to be performed for\n every element of the batch.\n\n\n======= train =======\n\n Function that takes a transition (s,a,r,s') and optimizes Bellman equation's error:\n\n td_error = Q(s,a) - (r + gamma * max_a' Q(s', a'))\n loss = huber_loss[td_error]\n\n :param obs_t: (Any) a batch of observations\n :param action: (numpy int) actions that were selected upon seeing obs_t. dtype must be int32 and shape must be\n (batch_size,)\n :param reward: (numpy float) immediate reward attained after executing those actions dtype must be float32 and\n shape must be (batch_size,)\n :param obs_tp1: (Any) observations that followed obs_t\n :param done: (numpy bool) 1 if obs_t was the last observation in the episode and 0 otherwise obs_tp1 gets ignored,\n but must be of the valid shape. dtype must be float32 and shape must be (batch_size,)\n :param weight: (numpy float) imporance weights for every element of the batch (gradient is multiplied by the\n importance weight) dtype must be float32 and shape must be (batch_size,)\n :return: (numpy float) td_error: a list of differences between Q(s,a) and the target in Bellman's equation.\n dtype is float32 and shape is (batch_size,)\n\n======= update_target ========\n\n copy the parameters from optimized Q function to the target Q function.\n In Q learning we actually optimize the following error:\n\n Q(s,a) - (r + gamma * max_a' Q'(s', a'))\n\n Where Q' is lagging behind Q to stablize the learning. For example for Atari\n\n Q' is set to Q once every 10000 updates training steps.\n\n\"\"\"\nimport tensorflow as tf\nfrom gym.spaces import MultiDiscrete\n\nfrom stable_baselines.common import tf_util\n\n\ndef scope_vars(scope, trainable_only=False):\n \"\"\"\n Get variables inside a scope\n The scope can be specified as a string\n\n :param scope: (str or VariableScope) scope in which the variables reside.\n :param trainable_only: (bool) whether or not to return only the variables that were marked as trainable.\n :return: ([TensorFlow Tensor]) vars: list of variables in `scope`.\n \"\"\"\n return tf.get_collection(\n tf.GraphKeys.TRAINABLE_VARIABLES if trainable_only else tf.GraphKeys.GLOBAL_VARIABLES,\n scope=scope if isinstance(scope, str) else scope.name\n )\n\n\ndef scope_name():\n \"\"\"\n Returns the name of current scope as a string, e.g. deepq/q_func\n\n :return: (str) the name of current scope\n \"\"\"\n return tf.get_variable_scope().name\n\n\ndef absolute_scope_name(relative_scope_name):\n \"\"\"\n Appends parent scope name to `relative_scope_name`\n\n :return: (str) the absolute name of the scope\n \"\"\"\n return scope_name() + \"/\" + relative_scope_name\n\n\ndef default_param_noise_filter(var):\n \"\"\"\n check whether or not a variable is perturbable or not\n\n :param var: (TensorFlow Tensor) the variable\n :return: (bool) can be perturb\n \"\"\"\n if var not in tf.trainable_variables():\n # We never perturb non-trainable vars.\n return False\n if \"fully_connected\" in var.name:\n # We perturb fully-connected layers.\n return True\n\n # The remaining layers are likely conv or layer norm layers, which we do not wish to\n # perturb (in the former case because they only extract features, in the latter case because\n # we use them for normalization purposes). If you change your network, you will likely want\n # to re-consider which layers to perturb and which to keep untouched.\n return False\n\n\ndef build_act(q_func, ob_space, ac_space, stochastic_ph, update_eps_ph, sess, layers=None):\n \"\"\"\n Creates the act function:\n\n :param q_func: (DQNPolicy) the policy\n :param ob_space: (Gym Space) The observation space of the environment\n :param ac_space: (Gym Space) The action space of the environment\n :param stochastic_ph: (TensorFlow Tensor) the stochastic placeholder\n :param update_eps_ph: (TensorFlow Tensor) the update_eps placeholder\n :param sess: (TensorFlow session) The current TensorFlow session\n :return: (function (TensorFlow Tensor, bool, float): TensorFlow Tensor, (TensorFlow Tensor, TensorFlow Tensor)\n act function to select and action given observation (See the top of the file for details),\n A tuple containing the observation placeholder and the processed observation placeholder respectively.\n \"\"\"\n eps = tf.get_variable(\"eps\", (), initializer=tf.constant_initializer(0))\n\n policy = q_func(sess, ob_space, ac_space, 1, 1, None, layers=layers)\n obs_phs = (policy.obs_ph, policy.processed_obs)\n deterministic_actions = tf.argmax(policy.q_values, axis=1)\n\n #########################\n ### KEVIN UPDATE ########\n ### GIMME DAT PRINTS ####\n #########################\n print(\"Hello yes I am in build_act without noise\")\n print(f\"Obs space: {ob_space}\")\n print(f\"policy.obs_ph: {policy.obs_ph}\")\n print(f\"policy.processed_obs: {policy.processed_obs}\")\n print(f\"Obs_phs space: {obs_phs}\")\n #assert 5 == 1\n #######################\n for var in tf.all_variables():\n print(var)\n \n batch_size = tf.shape(policy.obs_ph)[0]\n n_actions = ac_space.nvec if isinstance(ac_space, MultiDiscrete) else ac_space.n\n random_actions = tf.random_uniform(tf.stack([batch_size]), minval=0, maxval=n_actions, dtype=tf.int64)\n chose_random = tf.random_uniform(tf.stack([batch_size]), minval=0, maxval=1, dtype=tf.float32) < eps\n stochastic_actions = tf.where(chose_random, random_actions, deterministic_actions)\n\n output_actions = tf.cond(stochastic_ph, lambda: stochastic_actions, lambda: deterministic_actions)\n update_eps_expr = eps.assign(tf.cond(update_eps_ph >= 0, lambda: update_eps_ph, lambda: eps))\n _act = tf_util.function(inputs=[policy.obs_ph, stochastic_ph, update_eps_ph],\n outputs=output_actions,\n givens={update_eps_ph: -1.0, stochastic_ph: True},\n updates=[update_eps_expr])\n\n def act(obs, stochastic=True, update_eps=-1):\n return _act(obs, stochastic, update_eps)\n\n return act, obs_phs\n\n\ndef build_act_with_param_noise(q_func, ob_space, ac_space, stochastic_ph, update_eps_ph, sess,\n param_noise_filter_func=None):\n \"\"\"\n Creates the act function with support for parameter space noise exploration (https://arxiv.org/abs/1706.01905):\n\n :param q_func: (DQNPolicy) the policy\n :param ob_space: (Gym Space) The observation space of the environment\n :param ac_space: (Gym Space) The action space of the environment\n :param stochastic_ph: (TensorFlow Tensor) the stochastic placeholder\n :param update_eps_ph: (TensorFlow Tensor) the update_eps placeholder\n :param sess: (TensorFlow session) The current TensorFlow session\n :param param_noise_filter_func: (function (TensorFlow Tensor): bool) function that decides whether or not a\n variable should be perturbed. Only applicable if param_noise is True. If set to None, default_param_noise_filter\n is used by default.\n :return: (function (TensorFlow Tensor, bool, float): TensorFlow Tensor, (TensorFlow Tensor, TensorFlow Tensor)\n act function to select and action given observation (See the top of the file for details),\n A tuple containing the observation placeholder and the processed observation placeholder respectively.\n \"\"\"\n if param_noise_filter_func is None:\n param_noise_filter_func = default_param_noise_filter\n\n update_param_noise_threshold_ph = tf.placeholder(tf.float32, (), name=\"update_param_noise_threshold\")\n update_param_noise_scale_ph = tf.placeholder(tf.bool, (), name=\"update_param_noise_scale\")\n reset_ph = tf.placeholder(tf.bool, (), name=\"reset\")\n\n eps = tf.get_variable(\"eps\", (), initializer=tf.constant_initializer(0))\n param_noise_scale = tf.get_variable(\"param_noise_scale\", (), initializer=tf.constant_initializer(0.01),\n trainable=False)\n param_noise_threshold = tf.get_variable(\"param_noise_threshold\", (), initializer=tf.constant_initializer(0.05),\n trainable=False)\n\n # Unmodified Q.\n policy = q_func(sess, ob_space, ac_space, 1, 1, None)\n obs_phs = (policy.obs_ph, policy.processed_obs)\n\n # Perturbable Q used for the actual rollout.\n with tf.variable_scope(\"perturbed_model\", reuse=False):\n perturbable_policy = q_func(sess, ob_space, ac_space, 1, 1, None, obs_phs=obs_phs)\n\n def perturb_vars(original_scope, perturbed_scope):\n \"\"\"\n We have to wrap this code into a function due to the way tf.cond() works.\n\n See https://stackoverflow.com/questions/37063952/confused-by-the-behavior-of-tf-cond for a more detailed\n discussion.\n\n :param original_scope: (str or VariableScope) the original scope.\n :param perturbed_scope: (str or VariableScope) the perturbed scope.\n :return: (TensorFlow Operation)\n \"\"\"\n all_vars = scope_vars(absolute_scope_name(original_scope))\n all_perturbed_vars = scope_vars(absolute_scope_name(perturbed_scope))\n assert len(all_vars) == len(all_perturbed_vars)\n perturb_ops = []\n for var, perturbed_var in zip(all_vars, all_perturbed_vars):\n if param_noise_filter_func(perturbed_var):\n # Perturb this variable.\n operation = tf.assign(perturbed_var,\n var + tf.random_normal(shape=tf.shape(var), mean=0.,\n stddev=param_noise_scale))\n else:\n # Do not perturb, just assign.\n operation = tf.assign(perturbed_var, var)\n perturb_ops.append(operation)\n assert len(perturb_ops) == len(all_vars)\n return tf.group(*perturb_ops)\n\n # Set up functionality to re-compute `param_noise_scale`. This perturbs yet another copy\n # of the network and measures the effect of that perturbation in action space. If the perturbation\n # is too big, reduce scale of perturbation, otherwise increase.\n with tf.variable_scope(\"adaptive_model\", reuse=False):\n adaptive_policy = q_func(sess, ob_space, ac_space, 1, 1, None, obs_phs=obs_phs)\n perturb_for_adaption = perturb_vars(original_scope=\"model\", perturbed_scope=\"adaptive_model/model\")\n kl_loss = tf.reduce_sum(\n tf.nn.softmax(policy.q_values) *\n (tf.log(tf.nn.softmax(policy.q_values)) - tf.log(tf.nn.softmax(adaptive_policy.q_values))),\n axis=-1)\n mean_kl = tf.reduce_mean(kl_loss)\n\n def update_scale():\n \"\"\"\n update the scale expression\n\n :return: (TensorFlow Tensor) the updated scale expression\n \"\"\"\n with tf.control_dependencies([perturb_for_adaption]):\n update_scale_expr = tf.cond(mean_kl < param_noise_threshold,\n lambda: param_noise_scale.assign(param_noise_scale * 1.01),\n lambda: param_noise_scale.assign(param_noise_scale / 1.01),\n )\n return update_scale_expr\n\n # Functionality to update the threshold for parameter space noise.\n update_param_noise_thres_expr = param_noise_threshold.assign(\n tf.cond(update_param_noise_threshold_ph >= 0, lambda: update_param_noise_threshold_ph,\n lambda: param_noise_threshold))\n\n # Put everything together.\n perturbed_deterministic_actions = tf.argmax(perturbable_policy.q_values, axis=1)\n deterministic_actions = tf.argmax(policy.q_values, axis=1)\n batch_size = tf.shape(policy.obs_ph)[0]\n n_actions = ac_space.nvec if isinstance(ac_space, MultiDiscrete) else ac_space.n\n random_actions = tf.random_uniform(tf.stack([batch_size]), minval=0, maxval=n_actions, dtype=tf.int64)\n chose_random = tf.random_uniform(tf.stack([batch_size]), minval=0, maxval=1, dtype=tf.float32) < eps\n perturbed_stochastic_actions = tf.where(chose_random, random_actions, perturbed_deterministic_actions)\n stochastic_actions = tf.where(chose_random, random_actions, deterministic_actions)\n\n perturbed_output_actions = tf.cond(stochastic_ph, lambda: perturbed_stochastic_actions,\n lambda: deterministic_actions)\n output_actions = tf.cond(stochastic_ph, lambda: stochastic_actions, lambda: deterministic_actions)\n update_eps_expr = eps.assign(tf.cond(update_eps_ph >= 0, lambda: update_eps_ph, lambda: eps))\n updates = [\n update_eps_expr,\n tf.cond(reset_ph, lambda: perturb_vars(original_scope=\"model\", perturbed_scope=\"perturbed_model/model\"),\n lambda: tf.group(*[])),\n tf.cond(update_param_noise_scale_ph, lambda: update_scale(), lambda: tf.Variable(0., trainable=False)),\n update_param_noise_thres_expr,\n ]\n\n _act = tf_util.function(inputs=[policy.obs_ph, stochastic_ph, update_eps_ph],\n outputs=output_actions,\n givens={update_eps_ph: -1.0, stochastic_ph: True},\n updates=[update_eps_expr])\n\n _perturbed_act = tf_util.function(\n inputs=[policy.obs_ph, stochastic_ph, update_eps_ph, reset_ph, update_param_noise_threshold_ph,\n update_param_noise_scale_ph],\n outputs=perturbed_output_actions,\n givens={update_eps_ph: -1.0, stochastic_ph: True, reset_ph: False, update_param_noise_threshold_ph: False,\n update_param_noise_scale_ph: False},\n updates=updates)\n\n def act(obs, reset=None, update_param_noise_threshold=None, update_param_noise_scale=None, stochastic=True,\n update_eps=-1):\n \"\"\"\n get the action from the current observation\n\n :param obs: (Any) Observation that can be feed into the output of make_obs_ph\n :param reset: (bool) reset the perturbed policy by sampling a new perturbation\n :param update_param_noise_threshold: (float) the desired threshold for the difference between\n non-perturbed and perturbed policy\n :param update_param_noise_scale: (bool) whether or not to update the scale of the noise for the next time\n it is re-perturbed\n :param stochastic: (bool) if set to False all the actions are always deterministic (default False)\n :param update_eps: (float) update epsilon a new value, if negative not update happens\n (default: no update)\n :return: (TensorFlow Tensor) tensor of dtype tf.int64 and shape (BATCH_SIZE,) with an action to be\n performed for every element of the batch.\n \"\"\"\n if reset is None or update_param_noise_threshold is None or update_param_noise_scale is None:\n return _act(obs, stochastic, update_eps)\n else:\n return _perturbed_act(obs, stochastic, update_eps, reset, update_param_noise_threshold,\n update_param_noise_scale)\n\n return act, obs_phs\n\n\ndef build_train(q_func, ob_space, ac_space, optimizer, sess, grad_norm_clipping=None,\n gamma=1.0, double_q=True, scope=\"deepq\", reuse=None,\n param_noise=False, param_noise_filter_func=None, full_tensorboard_log=False, layers=None):\n \"\"\"\n Creates the train function:\n\n :param q_func: (DQNPolicy) the policy\n :param ob_space: (Gym Space) The observation space of the environment\n :param ac_space: (Gym Space) The action space of the environment\n :param reuse: (bool) whether or not to reuse the graph variables\n :param optimizer: (tf.train.Optimizer) optimizer to use for the Q-learning objective.\n :param sess: (TensorFlow session) The current TensorFlow session\n :param grad_norm_clipping: (float) clip gradient norms to this value. If None no clipping is performed.\n :param gamma: (float) discount rate.\n :param double_q: (bool) if true will use Double Q Learning (https://arxiv.org/abs/1509.06461). In general it is a\n good idea to keep it enabled.\n :param scope: (str or VariableScope) optional scope for variable_scope.\n :param reuse: (bool) whether or not the variables should be reused. To be able to reuse the scope must be given.\n :param param_noise: (bool) whether or not to use parameter space noise (https://arxiv.org/abs/1706.01905)\n :param param_noise_filter_func: (function (TensorFlow Tensor): bool) function that decides whether or not a\n variable should be perturbed. Only applicable if param_noise is True. If set to None, default_param_noise_filter\n is used by default.\n :param full_tensorboard_log: (bool) enable additional logging when using tensorboard\n WARNING: this logging can take a lot of space quickly\n\n :return: (tuple)\n\n act: (function (TensorFlow Tensor, bool, float): TensorFlow Tensor) function to select and action given\n observation. See the top of the file for details.\n train: (function (Any, numpy float, numpy float, Any, numpy bool, numpy float): numpy float)\n optimize the error in Bellman's equation. See the top of the file for details.\n update_target: (function) copy the parameters from optimized Q function to the target Q function.\n See the top of the file for details.\n step_model: (DQNPolicy) Policy for evaluation\n \"\"\"\n n_actions = ac_space.nvec if isinstance(ac_space, MultiDiscrete) else ac_space.n\n with tf.variable_scope(\"input\", reuse=reuse):\n stochastic_ph = tf.placeholder(tf.bool, (), name=\"stochastic\")\n update_eps_ph = tf.placeholder(tf.float32, (), name=\"update_eps\")\n\n with tf.variable_scope(scope, reuse=reuse):\n if param_noise:\n act_f, obs_phs = build_act_with_param_noise(q_func, ob_space, ac_space, stochastic_ph, update_eps_ph, sess,\n param_noise_filter_func=param_noise_filter_func)\n else:\n act_f, obs_phs = build_act(q_func, ob_space, ac_space, stochastic_ph, update_eps_ph, sess, layers=layers)\n\n # q network evaluation\n with tf.variable_scope(\"step_model\", reuse=True, custom_getter=tf_util.outer_scope_getter(\"step_model\")):\n step_model = q_func(sess, ob_space, ac_space, 1, 1, None, reuse=True, obs_phs=obs_phs, layers=layers)\n q_func_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=tf.get_variable_scope().name + \"/model\")\n # target q network evaluation\n\n with tf.variable_scope(\"target_q_func\", reuse=False):\n target_policy = q_func(sess, ob_space, ac_space, 1, 1, None, reuse=False, layers=layers)\n target_q_func_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES,\n scope=tf.get_variable_scope().name + \"/target_q_func\")\n\n # compute estimate of best possible value starting from state at t + 1\n double_q_values = None\n double_obs_ph = target_policy.obs_ph\n if double_q:\n with tf.variable_scope(\"double_q\", reuse=True, custom_getter=tf_util.outer_scope_getter(\"double_q\")):\n double_policy = q_func(sess, ob_space, ac_space, 1, 1, None, reuse=True, layers=layers)\n double_q_values = double_policy.q_values\n double_obs_ph = double_policy.obs_ph\n\n with tf.variable_scope(\"loss\", reuse=reuse):\n # set up placeholders\n act_t_ph = tf.placeholder(tf.int32, [None], name=\"action\")\n rew_t_ph = tf.placeholder(tf.float32, [None], name=\"reward\")\n done_mask_ph = tf.placeholder(tf.float32, [None], name=\"done\")\n importance_weights_ph = tf.placeholder(tf.float32, [None], name=\"weight\")\n\n # q scores for actions which we know were selected in the given state.\n q_t_selected = tf.reduce_sum(step_model.q_values * tf.one_hot(act_t_ph, n_actions), axis=1)\n\n # compute estimate of best possible value starting from state at t + 1\n if double_q:\n q_tp1_best_using_online_net = tf.argmax(double_q_values, axis=1)\n q_tp1_best = tf.reduce_sum(target_policy.q_values * tf.one_hot(q_tp1_best_using_online_net, n_actions), axis=1)\n else:\n q_tp1_best = tf.reduce_max(target_policy.q_values, axis=1)\n q_tp1_best_masked = (1.0 - done_mask_ph) * q_tp1_best\n\n # compute RHS of bellman equation\n q_t_selected_target = rew_t_ph + gamma * q_tp1_best_masked\n\n # compute the error (potentially clipped)\n td_error = q_t_selected - tf.stop_gradient(q_t_selected_target)\n errors = tf_util.huber_loss(td_error)\n weighted_error = tf.reduce_mean(importance_weights_ph * errors)\n\n tf.summary.scalar(\"td_error\", tf.reduce_mean(td_error))\n tf.summary.scalar(\"loss\", weighted_error)\n\n if full_tensorboard_log:\n tf.summary.histogram(\"td_error\", td_error)\n\n # update_target_fn will be called periodically to copy Q network to target Q network\n update_target_expr = []\n for var, var_target in zip(sorted(q_func_vars, key=lambda v: v.name),\n sorted(target_q_func_vars, key=lambda v: v.name)):\n update_target_expr.append(var_target.assign(var))\n update_target_expr = tf.group(*update_target_expr)\n\n # compute optimization op (potentially with gradient clipping)\n gradients = optimizer.compute_gradients(weighted_error, var_list=q_func_vars)\n if grad_norm_clipping is not None:\n for i, (grad, var) in enumerate(gradients):\n if grad is not None:\n gradients[i] = (tf.clip_by_norm(grad, grad_norm_clipping), var)\n\n with tf.variable_scope(\"input_info\", reuse=False):\n tf.summary.scalar('rewards', tf.reduce_mean(rew_t_ph))\n tf.summary.scalar('importance_weights', tf.reduce_mean(importance_weights_ph))\n\n if full_tensorboard_log:\n tf.summary.histogram('rewards', rew_t_ph)\n tf.summary.histogram('importance_weights', importance_weights_ph)\n if tf_util.is_image(obs_phs[0]):\n tf.summary.image('observation', obs_phs[0])\n elif len(obs_phs[0].shape) == 1:\n tf.summary.histogram('observation', obs_phs[0])\n\n optimize_expr = optimizer.apply_gradients(gradients)\n\n summary = tf.summary.merge_all()\n\n # Create callable functions\n train = tf_util.function(\n inputs=[\n obs_phs[0],\n act_t_ph,\n rew_t_ph,\n target_policy.obs_ph,\n double_obs_ph,\n done_mask_ph,\n importance_weights_ph\n ],\n outputs=[summary, td_error],\n updates=[optimize_expr]\n )\n update_target = tf_util.function([], [], updates=[update_target_expr])\n\n return act_f, train, update_target, step_model\n"
] |
[
[
"tensorflow.cond",
"tensorflow.control_dependencies",
"tensorflow.stack",
"tensorflow.where",
"tensorflow.group",
"tensorflow.summary.scalar",
"tensorflow.all_variables",
"tensorflow.Variable",
"tensorflow.summary.image",
"tensorflow.stop_gradient",
"tensorflow.clip_by_norm",
"tensorflow.trainable_variables",
"tensorflow.argmax",
"tensorflow.shape",
"tensorflow.placeholder",
"tensorflow.summary.merge_all",
"tensorflow.one_hot",
"tensorflow.summary.histogram",
"tensorflow.reduce_max",
"tensorflow.nn.softmax",
"tensorflow.reduce_mean",
"tensorflow.assign",
"tensorflow.constant_initializer",
"tensorflow.variable_scope",
"tensorflow.get_variable_scope"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.13",
"1.5",
"1.7",
"0.12",
"1.0",
"1.2"
]
}
] |
alex-kj-chin/prototransformer-public
|
[
"f6c82ea0e4a1fe57f19f161d4d659db2668f7313"
] |
[
"scripts/eval/robustness_exp_text.py"
] |
[
"\"\"\"Evaluate accuracy for 1000 episodes on test set.\"\"\"\n\nimport os\nimport numpy as np\n\nfrom src.agents.nlp import *\nfrom src.utils.setup import process_config, process_config_from_json\nfrom src.datasets.text import *\n\n\ndef evaluate(args, gpu_device=-1):\n config_path = os.path.join(args.exp_dir, 'config.json')\n checkpoint_dir = os.path.join(args.exp_dir, 'checkpoints')\n analysis_dir = os.path.join(args.exp_dir, 'analysis')\n\n if not os.path.isdir(analysis_dir):\n os.makedirs(analysis_dir)\n\n config = process_config(config_path)\n\n if gpu_device >= 0: config.gpu_device = gpu_device\n config = process_config_from_json(config)\n\n AgentClass = globals()[config.agent]\n agent = AgentClass(config)\n\n agent.load_checkpoint(\n args.checkpoint_file,\n checkpoint_dir=checkpoint_dir,\n load_model=True,\n load_optim=False,\n load_epoch=True,\n )\n # turn on eval mode\n agent.model.eval()\n\n class_dict = {\n 'fs_20news': FewShot20News,\n 'fs_amazon': FewShotAmazon,\n 'fs_huffpost': FewShotHuffPost,\n 'fs_rcv1': FewShotRCV1,\n 'fs_reuters': FewShotReuters,\n 'fs_fewrel': FewShotFewRel,\n }\n DatasetClass = class_dict[config.dataset.name]\n test_dataset = DatasetClass(\n data_root=config.dataset.data_root,\n n_ways=config.dataset.test.n_ways,\n n_shots=config.dataset.test.n_shots,\n n_queries=config.dataset.test.n_queries,\n split='test',\n )\n test_loader, _ = agent._create_test_dataloader(\n test_dataset,\n config.optim.batch_size,\n )\n _, accuracies, acc_stdevs = agent.eval_split('Test', test_loader, verbose=True)\n print(acc_stdevs)\n print(accuracies)\n\n checkpoint_name = args.checkpoint_file.replace('.pth.tar', '')\n accuracy_fpath = os.path.join(analysis_dir, f'{checkpoint_name}_accuracies.csv')\n np.savez(accuracy_fpath, accuracies=accuracies)\n\n\nif __name__ == \"__main__\":\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('exp_dir', type=str, help='path to experiment directory')\n parser.add_argument('checkpoint_file', type=str, help='name of checkpoint')\n parser.add_argument('--gpu-device', type=int, default=-1)\n args = parser.parse_args()\n evaluate(args, gpu_device=args.gpu_device)\n"
] |
[
[
"numpy.savez"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
kenextra/WhatsappMessenger
|
[
"bde7aa81c41384983d8cd1515db38be7be49d080"
] |
[
"backend-for-whatsapp/app.py"
] |
[
"\"\"\" Import Libraries \"\"\"\n\nfrom flask import Flask, render_template, request, jsonify\nimport requests\nimport os\nimport json\nimport math\nimport string\nimport pandas as pd\nimport numpy as np\nimport scipy as sp\nfrom sklearn.preprocessing import OneHotEncoder, StandardScaler\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.compose import TransformedTargetRegressor\nfrom twilio.twiml.messaging_response import MessagingResponse\nfrom ibm_watson_machine_learning import APIClient\nfrom twilio.rest import Client\nfrom PIL import Image, ImageDraw, ImageFont\nfrom news_bot import get_news\n\n\n\"\"\" Initialize Flask Variables \"\"\"\napp = Flask(__name__)\n\napp.config[\"SERVICES\"] = \"static/watsonservices/\"\napp.config[\"CREDENTIALS\"] = \"static/watsoncredentials/\"\napp.config[\"DATASET\"] = \"static/datasets/\"\n\naccount_sid = \"\"\nauth_token = \"\"\nwml_credentials = {}\nspace_id = \"\"\n\nreceivedMsg = \"\"\nsentMsg = \"\"\n\n\[email protected](\"/getWmlCredentials\")\ndef getWmlCredentials():\n try:\n global wml_credentials, space_id\n with open(app.config[\"CREDENTIALS\"] + \"wmlCredentials.json\") as wmlCreds:\n wmlcred = json.loads(wmlCreds.read())\n\n wml_credentials = {\"apikey\": wmlcred.get(\"apikey\"), \"url\": wmlcred.get(\"url\")}\n\n space_id = wmlcred.get(\"space_id\")\n\n returnablejson = wml_credentials\n returnablejson.update({\"status\": \"Configured\"})\n\n return jsonify(returnablejson)\n except:\n return jsonify({\"status\": \"Not Configured\"})\n\n\[email protected](\"/getWatsonCredentials\")\ndef getWatsonCredentials():\n try:\n x = scanAvailableFiles(app.config[\"CREDENTIALS\"])\n\n returnableObj = {\"services\": x}\n\n return jsonify(returnableObj)\n except:\n return jsonify({\"services\": [\"No Service Configured\"]})\n\n\[email protected](\"/getTwilioCredentials\")\ndef getTwilioCredentials():\n try:\n global account_sid\n global auth_token\n with open(\"twiliocredentials.json\") as creds:\n twiliocred = json.loads(creds.read())\n\n account_sid = twiliocred.get(\"account_sid\")\n auth_token = twiliocred.get(\"auth_token\")\n return jsonify({\"status\": \"Configured\"})\n except:\n return jsonify({\"status\": \"Not Configured\"})\n\n\[email protected](\"/getDeploymentState\")\ndef getDeploymentState():\n try:\n with open(app.config[\"SERVICES\"] + \"wmlDeployment.json\") as temp:\n cred = json.loads(temp.read())\n model_id = cred[\"entity\"][\"asset\"][\"id\"]\n model_name = cred[\"entity\"][\"name\"]\n model_status = cred[\"entity\"][\"status\"][\"state\"]\n return jsonify(\n {\n \"status\": model_status,\n \"modelId\": model_id,\n \"modelName\": model_name,\n }\n )\n except Exception:\n return jsonify({\"status\": \"Model not Deployed\"})\n\n\[email protected](\"/storeTwilioCredentials\", methods=[\"GET\", \"POST\"])\ndef storeTwilioCredentials():\n receivedPayload = json.loads(request.form[\"Credentials\"])\n\n data = {\n \"account_sid\": receivedPayload.get(\"account_sid\"),\n \"auth_token\": receivedPayload.get(\"auth_token\"),\n }\n\n with open(\"twiliocredentials.json\", \"w\") as fs:\n json.dump(data, fs, indent=2)\n\n return jsonify({\"status\": \"Configured\"})\n\n\[email protected](\"/storeWatsonCredentials\", methods=[\"GET\", \"POST\"])\ndef storeWatsonCredentials():\n receivedPayload = json.loads(request.form[\"Credentials\"])\n\n if receivedPayload.get(\"type\") == \"wml\":\n\n data = receivedPayload\n data.pop(\"type\")\n\n with open(app.config[\"CREDENTIALS\"] + \"wmlCredentials.json\", \"w\") as fs:\n json.dump(data, fs, indent=2)\n\n return jsonify({\"status\": \"Configured\"})\n\n data = json.loads(receivedPayload.get(\"apikey\"))\n data.update({\"cloudfunctionurl\": receivedPayload.get(\"cloudfunctionurl\") + \".json\"})\n data.update({\"windowURL\": receivedPayload.get(\"windowURL\")})\n with open(\n app.config[\"CREDENTIALS\"] + receivedPayload.get(\"type\") + \"Credentials.json\",\n \"w\",\n ) as fs:\n json.dump(data, fs, indent=2)\n\n return jsonify({\"status\": \"Configured\"})\n\n\[email protected](\"/deployWMLModel\")\ndef deployWMLModel():\n \"\"\"Step 1: Build the Linear Regression Model\"\"\"\n # importing the dataset\n df = pd.read_csv(app.config[\"DATASET\"] + \"Data.csv\")\n columns_to_use = [\"Area\", \"Item\", \"Months\", \"Value\", \"Year\"]\n data = df[columns_to_use]\n data['Item'] = data['Item'].str.replace('Rice, paddy', 'Rice')\n\n data['Area'] = data.Area.str.lower()\n data['Item'] = data.Item.str.lower()\n data['Months'] = data.Months.str.lower()\n\n data.query('Value > 0.0', inplace=True)\n\n X = data.drop(columns=[\"Value\"], axis=1)\n y = data[\"Value\"]\n X_train, X_test, y_train, y_test = train_test_split(\n X, y, test_size=0.05, random_state=42\n )\n\n numerical_cols = X_train.select_dtypes(include=['int64', 'float64']).columns\n categorical_cols = X_train.select_dtypes(include=[\"object\", \"bool\"]).columns\n\n cat_pipeline = Pipeline([(\"cat\", OneHotEncoder()), ])\n num_pipeline = Pipeline([(\"num\", StandardScaler()), ])\n\n transformer = ColumnTransformer(\n [\n (\"num_pipe\", num_pipeline, numerical_cols),\n (\"cat_pipe\", cat_pipeline, categorical_cols),\n ]\n )\n\n estimator = DecisionTreeRegressor(max_depth=150, random_state=42)\n tt_model = TransformedTargetRegressor(regressor=estimator,\n func=np.log10,\n inverse_func=sp.special.exp10\n )\n\n model = Pipeline([(\"preparation\", transformer),\n (\"model\", tt_model),\n ])\n model.fit(X_train, y_train)\n\n print(\"Model Built Successfully\")\n\n \"\"\" Deploy the Model to Watson Machine Learning \"\"\"\n getWmlCredentials()\n\n client = APIClient(wml_credentials)\n\n client.set.default_space(space_id)\n\n sofware_spec_uid = client.software_specifications.get_id_by_name(\"default_py3.7_opence\")\n\n metadata = {\n client.repository.ModelMetaNames.NAME: \"Food Data Price Prediction\",\n client.repository.ModelMetaNames.TYPE: \"scikit-learn_0.23\",\n client.repository.ModelMetaNames.SOFTWARE_SPEC_UID: sofware_spec_uid,\n }\n\n published_model = client.repository.store_model(model, meta_props=metadata)\n\n published_model_uid = client.repository.get_model_uid(published_model)\n\n deploy_meta = {\n client.deployments.ConfigurationMetaNames.NAME: \"Deployment of Food Data Price Prediction\",\n client.deployments.ConfigurationMetaNames.ONLINE: {},\n }\n created_deployment = client.deployments.create(\n published_model_uid, meta_props=deploy_meta\n )\n\n with open(app.config[\"SERVICES\"] + \"wmlDeployment.json\", \"w\") as fp:\n json.dump(created_deployment, fp, indent=2)\n\n print(json.dumps(created_deployment, indent=2))\n print(\"Model Successfully Deployed..\")\n with open(app.config[\"SERVICES\"] + \"wmlDeployment.json\") as temp:\n cred = json.loads(temp.read())\n model_id = cred[\"entity\"][\"asset\"][\"id\"]\n return jsonify({\"status\": \"Deployed, Model ID: \" + model_id})\n\n\ndef predict_price_wml(area, item):\n getWmlCredentials()\n\n cols = ['Area', 'Item', 'Months', 'Year']\n\n client = APIClient(wml_credentials)\n client.set.default_space(space_id)\n\n with open(app.config[\"SERVICES\"] + 'wmlDeployment.json', 'r') as wmlDeployment:\n cred = json.loads(wmlDeployment.read())\n\n x = [area.lower(), item.lower()]\n today = pd.to_datetime(\"today\")\n x.append(today.month_name().lower())\n x.append(today.year)\n x = np.array([x], dtype=object)\n z = pd.DataFrame(x, columns=cols)\n\n did = client.deployments.get_uid(cred)\n\n job_payload = {\n client.deployments.ScoringMetaNames.INPUT_DATA: [{'values': z}]\n }\n\n scoring_response = client.deployments.score(did, job_payload)\n value = scoring_response['predictions'][0]['values'][0][0]\n return math.ceil(value)\n\n\ndef createImagePrediction(area, item, price, dt_day):\n image = Image.open(\"static/images/DarkOcean.png\")\n draw = ImageDraw.Draw(image)\n font = ImageFont.truetype(\"static/fonts/Roboto.ttf\", size=55)\n\n (x, y) = (115, 300)\n message = f\"Producer Price for {item}\"\n color = \"rgb(255, 255, 255)\"\n draw.text((x, y), message, fill=color, font=font)\n\n (x, y) = (115, 400)\n message = \"in \"\n color = \"rgb(255, 255, 255)\"\n draw.text((x, y), message, fill=color, font=font)\n\n (x, y) = (165, 400)\n message = f\" {area} \"\n color = \"rgb(255,165,0)\"\n draw.text((x, y), message, fill=color, font=font)\n\n (x, y) = (115, 500)\n message = f\"on \"\n color = \"rgb(255, 255, 255)\"\n draw.text((x, y), message, fill=color, font=font)\n\n (x, y) = (165, 500)\n message = f\" {dt_day} \"\n color = \"rgb(255,165,0)\"\n draw.text((x, y), message, fill=color, font=font)\n\n (x, y) = (115, 600)\n message = \"is \"\n color = \"rgb(255, 255, 255)\"\n draw.text((x, y), message, fill=color, font=font)\n\n (x, y) = (165, 600)\n name = f\"~{price} LCU/tonne\"\n color = \"rgb(0, 255, 0)\" # white color\n draw.text((x, y), name, fill=color, font=font)\n\n image.save(\"static/images/predicted.png\", optimize=True, quality=20)\n\n\ndef checkServices(to_, from_, client):\n try:\n files = scanAvailableFiles(app.config[\"CREDENTIALS\"])\n # print(files)\n idx = 0\n inx = 1\n for i in files:\n if i == \"wmlCredentials.json\":\n x = scanAvailableFiles(app.config[\"SERVICES\"])\n print(x)\n for j in x:\n if j == \"wmlDeployment.json\":\n with open(app.config[\"SERVICES\"] + j) as temp:\n cred = json.loads(temp.read())\n files[idx] = \"{0}. Watson Machine Learning -> *{1}*\".format(\n inx, cred[\"entity\"][\"status\"][\"state\"]\n )\n inx += 1\n else:\n files[\n idx\n ] = \"{0}. Watson Machine Learning -> *No Model Deployed*\".format(\n inx\n )\n inx += 1\n if i == \"waCredentials.json\":\n x = scanAvailableFiles(app.config[\"SERVICES\"])\n print(x)\n for j in x:\n if j == \"waDeployment.json\":\n with open(app.config[\"SERVICES\"] + j) as temp:\n cred = json.loads(temp.read())\n files[idx] = \"{0}. Watson Assistant -> *{1}*\".format(\n inx, cred[\"entity\"][\"status\"][\"state\"]\n )\n inx += 1\n else:\n files[idx] = \"{0}. Watson Assistant -> *No Skills*\".format(inx)\n inx += 1\n if i == \"wnluCredentials.json\":\n x = scanAvailableFiles(app.config[\"SERVICES\"])\n print(x)\n for j in x:\n if j == \"wmlDeployment.json\":\n with open(app.config[\"SERVICES\"] + j) as temp:\n cred = json.loads(temp.read())\n files[\n idx\n ] = \"{0}. Watson Natural Language Understanding -> *{1}*\".format(\n inx, cred[\"entity\"][\"status\"][\"state\"]\n )\n inx += 1\n else:\n files[\n idx\n ] = \"{0}. Watson Natural Language Understanding -> *No Custom Model Deployed*\".format(\n inx\n )\n inx += 1\n if i == \"wvrCredentials.json\":\n x = scanAvailableFiles(app.config[\"SERVICES\"])\n print(x)\n for j in x:\n if j == \"wvrDeployment.json\":\n with open(app.config[\"SERVICES\"] + j) as temp:\n cred = json.loads(temp.read())\n files[idx] = \"{0}. Watson Visual Recognition -> *{1}*\".format(\n inx, cred[\"entity\"][\"status\"][\"state\"]\n )\n inx += 1\n else:\n files[\n idx\n ] = \"{0}. Watson Visual Recognition -> *No Custom Model Deployed*\".format(\n inx\n )\n inx += 1\n idx += 1\n files.append(f\"{idx+1}. Watson Assistant -> *For Agriculture News*\")\n services = \"\\n\".join(files)\n\n msg = (\n f\"I found the following services associated to me: \\n\\n{services}\"\n \"\\n\\nEnter the number to know more.\"\n )\n\n message = client.messages.create(from_=from_, body=msg, to=to_)\n global sentMsg\n sentMsg = \"I am a bot who is connected to watson services on IBM Cloud! \\nTry asking *What are the services you are connected to?*\"\n return message.sid\n except Exception as e:\n files = \"no service associated, please configure the application on IBM Cloud\"\n print(e)\n message = client.messages.create(from_=from_, body=files, to=to_)\n return message.sid\n\n\ndef scanAvailableFiles(path):\n availableFiles = os.listdir(path)\n if '.gitkeep' in availableFiles:\n availableFiles.pop(availableFiles.index('.gitkeep'))\n return availableFiles\n\n\[email protected](\"/getMessages\")\ndef getMessages():\n global receivedMsg\n global sentMsg\n\n return jsonify({\"sentMsg\": sentMsg, \"receivedMsg\": receivedMsg})\n\n\n\"\"\" Default Route \"\"\"\n\n\[email protected](\"/\", methods=[\"GET\", \"POST\"])\ndef index():\n if request.method == \"POST\":\n getTwilioCredentials()\n\n with open(app.config[\"CREDENTIALS\"] + \"wmlCredentials.json\") as wmlCreds:\n wmlcred = json.loads(wmlCreds.read())\n\n ResponseMsg = json.dumps(request.form.to_dict(), indent=2)\n respo = json.loads(ResponseMsg)\n # print(respo)\n global receivedMsg\n global sentMsg\n receivedMsg = respo.get(\"Body\")\n\n trans = str.maketrans('', '', string.punctuation)\n\n if str(respo.get(\"Body\")).strip().lower().translate(trans) == \"what can you do\":\n client = Client(account_sid, auth_token)\n to_ = respo.get(\"From\")\n from_ = respo.get(\"To\")\n message = client.messages.create(\n from_=from_,\n body=\"I am a bot who is connected to watson services on IBM Cloud! \\nTry asking *What are the services you are connected to?*\",\n media_url=wmlcred.get(\"windowURL\") + \"static/images/architecture.png\",\n to=to_,\n )\n sentMsg = \"I am a bot who is connected to watson services on IBM Cloud! \\nTry asking *What are the services you are connected to?*\"\n return message.sid\n\n if str(respo.get(\"Body\")).strip().lower().translate(trans) == \"what are the services you are connected to\":\n\n to_ = respo.get(\"From\")\n from_ = respo.get(\"To\")\n client = Client(account_sid, auth_token)\n checkServices(to_, from_, client)\n\n return str(\"ok\")\n\n if respo.get(\"Body\") == \"1\":\n message = \"Watson Machine Learning Details\"\n resp = MessagingResponse()\n resp.message(message)\n sentMsg = message\n x = scanAvailableFiles(app.config[\"SERVICES\"])\n for j in x:\n if j == \"wmlDeployment.json\":\n with open(app.config[\"SERVICES\"] + j) as temp:\n cred = json.loads(temp.read())\n model_id = cred[\"entity\"][\"asset\"][\"id\"]\n model_name = cred[\"entity\"][\"name\"]\n model_status = cred[\"entity\"][\"status\"][\"state\"]\n\n if model_status == \"ready\":\n message = (\n f\"WML Model id: *{model_id}*\"\n f\"\\nWML Model Name: *{model_name}*\"\n f\"\\nWML Model Status: *{model_status}*\"\n \"\\n\\nTry asking *I want to know food prices*\"\n )\n else:\n message = (\n f\"Model id: *{model_id}*\"\n f\"\\nModel Name: *{model_name}*\"\n f\"\\nModel Status: *{model_status}*\"\n )\n resp.message(message)\n sentMsg = message\n return str(resp)\n else:\n message = \"Service configured, but no model deployed!\\nType *Deploy* to deploy a test model\"\n resp.message(message)\n sentMsg = message\n return str(resp)\n\n if respo.get(\"Body\") == \"2\":\n message = \"Watson Assistant\"\n resp = MessagingResponse()\n resp.message(message)\n sentMsg = message\n\n message = \"Type *News* for Agriculture News\"\n resp.message(message)\n sentMsg = message\n\n return str(resp)\n\n if respo.get(\"Body\").strip().lower().translate(trans) == \"i want to know food prices\":\n message = \"Please enter the details with the below format:\\n\\n*Predict:<Country>,<Item>*\\n\\nExample: *Predict:Germany,Apples*\"\n resp = MessagingResponse()\n resp.message(message)\n sentMsg = message\n return str(resp)\n\n if respo.get(\"Body\")[:7].strip().lower() == \"predict\":\n\n temp = respo.get(\"Body\").split(\":\")[1].split(\",\")\n area = temp[0].strip()\n item = temp[1].strip()\n\n price = predict_price_wml(area, item)\n today = pd.to_datetime(\"today\")\n dt_day = today.date().strftime(\"%A, %d %B %Y\")\n\n messageTxt = f\"Item: *{item}*\\n\\nwill cost you approx: *{price}* LCU/tonne\\n\\nin *{area}*\\n\\n on *{dt_day}*\"\n createImagePrediction(area, item, price, dt_day)\n client = Client(account_sid, auth_token)\n to_ = respo.get(\"From\")\n from_ = respo.get(\"To\")\n message = client.messages.create(\n from_=from_,\n body=messageTxt,\n media_url=wmlcred.get(\"windowURL\") + \"static/images/predicted.png\",\n to=to_,\n )\n sentMsg = messageTxt\n return message.sid\n\n if respo.get(\"Body\").strip().lower().translate(trans) == \"news\":\n message = get_news()\n resp = MessagingResponse()\n resp.message(message)\n sentMsg = message\n return str(resp)\n\n if \"google\" in respo.get(\"Body\").strip().lower():\n query = str(respo.get(\"Body\")).lower().replace(\"google\", \"\")\n query = query.replace(\" \", \"+\")\n message = f\"https://www.google.com/search?q={query}\"\n resp = MessagingResponse()\n resp.message(message)\n sentMsg = message\n return str(resp)\n\n if respo.get(\"MediaUrl0\") is not None:\n imageURL = respo.get(\"MediaUrl0\")\n\n with open(app.config[\"CREDENTIALS\"] + \"wvrCredentials.json\") as wmlCreds:\n wvrcred = json.loads(wmlCreds.read())\n\n payload = {\n \"apikey\": wvrcred.get(\"apikey\"),\n \"url\": wvrcred.get(\"url\"),\n \"imageURL\": imageURL,\n }\n\n r = requests.post(wvrcred.get(\"cloudfunctionurl\"), data=payload)\n response = r.json()\n\n messageTxt = \"Classified as *{0}*\\nwith an accuracy of *{1}*\".format(\n response.get(\"class\"), response.get(\"score\")\n )\n\n # createImageVisual(response.get(\"class\"), response.get(\"score\"))\n client = Client(account_sid, auth_token)\n to_ = respo.get(\"From\")\n from_ = respo.get(\"To\")\n message = client.messages.create(\n from_=from_,\n body=messageTxt,\n media_url=wvrcred.get(\"windowURL\") + \"static/images/visualclass.png\",\n to=to_,\n )\n sentMsg = messageTxt\n return message.sid\n\n msg = \"The message,\\n'_{0}_'\\nthat you typed on your phone, went through\\nWhatsapp -> Twilio -> Python App hosted on IBM Cloud and returned back to you from\\nPython App hosted on IBM Cloud -> Twilio -> Whatsapp.\\n\\n*How Cool is that!!*\\n\\n Try asking *What can you do?*\".format(\n respo.get(\"Body\")\n )\n resp = MessagingResponse()\n resp.message(msg)\n sentMsg = msg\n return str(resp)\n\n return render_template(\"index.html\")\n\n\n\"\"\" Start the Server \"\"\"\nport = os.getenv(\"VCAP_APP_PORT\", \"8080\")\nif __name__ == \"__main__\":\n app.secret_key = os.urandom(12)\n app.run(debug=True, host=\"0.0.0.0\", port=port)\n"
] |
[
[
"sklearn.compose.TransformedTargetRegressor",
"pandas.read_csv",
"sklearn.tree.DecisionTreeRegressor",
"pandas.to_datetime",
"sklearn.preprocessing.OneHotEncoder",
"sklearn.model_selection.train_test_split",
"sklearn.pipeline.Pipeline",
"pandas.DataFrame",
"sklearn.preprocessing.StandardScaler",
"numpy.array",
"sklearn.compose.ColumnTransformer"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
sladesha/Frcwp
|
[
"421e8e831343bfeeeb31cb599598f059a563bbf8"
] |
[
"Frcwp/Frcwp.py"
] |
[
"import pandas as pd\nimport numpy as np\nimport sys\nfrom .reshapedata import natest as _natest\nfrom .reshapedata import valuenumber, coltest, standardizeddata, formatcheck\nfrom .distince import distince\nfrom .slicing import grouped, isolationforest, iswhole\n\n\nclass Frcwp():\n '''\n param : na_rate : if na_rate != None , remove some column if the column with too many nan values\n param : single_dealed : if single_dealed > 0 , remove some column if the column with single value\n param : is_scale : if is_scale = 1 , scale the data to improve the calculation speed ,may change the distribution of the initial data , is_scale =0 may be better usually\n param : distince_method : if 'Maha' then Mahalanobis_dist ; if 'Eucl' then euclidean_dist\n param : outlier_rate : the estimated outliers / all cases , the smaller, the better but not smaller than 0\n param : strange_rate : the strange outliers(潜在可能的异常点) / all cases\n param : nestimators : isolation tree number\n param : contamination : actual estimated outliers / all cases\n param : is_whole : if is_whole = 1 , the output features is the same as input ; if is_whole = 0 ,the output features are the features which take part in the training process\n param : output : if None then output all the potentialdata , if 0<output<1 then treated as rate , if output>1 the treated as number\n\n attribute : useful_index : the feature rank_index used for the model training actually\n attribute : similarity_label : the output data outlier degree the larger the outlier degree higher\n attribute : normalbarycentre : common level of your input data\n attribute : potentialdata_set : the suggested outlier potential data set , you can use your outlier potential data as well\n\n '''\n\n def __init__(self):\n self.na_rate = None\n self.single_dealed = None\n self.is_scale = None\n self.distince_method = None\n self.outlier_rate = None\n self.strange_rate = None\n self.nestimators = None\n self.contamination = None\n self.is_whole = None\n self.output = None\n self.iforest = None\n self.useful_index = None\n self.original_data = None\n self.similarity_label = None\n\n def changeformat(self, X, index=0):\n assert isinstance(index, int), '请输入识别列的列序号,以0开始'\n if isinstance(X, pd.DataFrame) != 1:\n X = formatcheck(X)\n X.index = X.iloc[:, index]\n keep_index = [x for x in range(X.shape[1]) if x != index]\n return X.iloc[:, keep_index]\n\n def fit(self, X=None, na_rate=None, single_dealed=None, is_scale=0, distince_method='Maha', outlier_rate=0.01,\n strange_rate=0.1, nestimators=100, contamination=0.1):\n self.na_rate = na_rate\n self.single_dealed = None\n self.is_scale = is_scale\n self.distince_method = distince_method\n self.outlier_rate = outlier_rate\n self.strange_rate = strange_rate\n self.nestimators = nestimators\n self.contamination = contamination\n self.normalbarycentre = None\n self.Metricset = None\n self.potentialdata_set = None\n self.original_data = X.copy()\n\n if isinstance(X, pd.DataFrame) != 1:\n print('we will change your data as the format of dataframe~')\n\n # begin preprocessing the data\n if self.na_rate != None:\n natt = _natest(X, self.na_rate)\n X = natt.naremove()\n\n if self.single_dealed:\n vnb = valuenumber(X)\n X = vnb.singlevalueremove()\n\n if self.is_scale:\n stdd = standardizeddata(X)\n X = stdd.standardstep()\n\n # begin outliers pre-recognition\n cal_X = X.copy()\n # remove the zero_columns and the collinearity_data\n colt = coltest(cal_X)\n colt_cal_X, colt_col_index = colt.columnstest()\n cov_cal_X = np.cov(colt_cal_X.T)\n self.useful_index = colt_col_index\n\n if self.distince_method not in ['Maha', 'Eucl']:\n raise NotImplementedError('distince_method should be Maha or Eucl~')\n\n if self.distince_method == 'Maha':\n colt1 = coltest(pd.DataFrame(cov_cal_X))\n colt1_cal_X, colt1_col_index = colt1.columnstest()\n if len(colt1_col_index) <= 1:\n raise ValueError(\n 'the outlier among the train data is too small ,PLS turn the is_scale = 0 or add reshape data')\n while cov_cal_X.shape != colt1_cal_X.shape:\n colt = coltest(pd.DataFrame(colt_cal_X).iloc[:, colt1_col_index])\n colt_cal_X, colt_col_index = colt.columnstest()\n cov_cal_X = np.cov(colt_cal_X.T)\n colt1 = coltest(cov_cal_X)\n colt1_cal_X, colt1_col_index = colt1.columnstest()\n\n cal_X_colt = cal_X.iloc[:, colt1_col_index]\n normalbarycentre = cal_X_colt.mean(axis=0)\n\n # calculate each case normal degree\n similarity_d = []\n for i in range(cal_X_colt.shape[0]):\n dist = distince(cal_X_colt.iloc[i, :], normalbarycentre)\n similarity_d.append(dist.Mahalanobis_dist(cal_X_colt))\n else:\n normalbarycentre = colt_cal_X.mean(axis=0)\n similarity_d = []\n\n for i in range(colt_cal_X.shape[0]):\n dist = distince(colt_cal_X.iloc[i, :], normalbarycentre)\n similarity_d.append(dist.euclidean_dist())\n self.normalbarycentre = normalbarycentre\n # spilt all user into outlier,strange and common part\n ggp = grouped(colt_cal_X, similarity_d, self.outlier_rate, self.strange_rate)\n outlierset, _ = ggp.outlier_group()\n strangeset, _ = ggp.strange_group()\n commonset = ggp.common_group()\n\n traindata = pd.concat([outlierset, commonset], axis=0)\n potentialdata = pd.concat([outlierset, strangeset], axis=0)\n traincol = [x for x in traindata.columns if x != 'simi']\n potentialcol = [x for x in potentialdata.columns if x != 'simi']\n self.Metricset = traindata[traincol]\n self.potentialdata_set = potentialdata[potentialcol]\n # score the cases in outlier and strange part\n ift = isolationforest(self.Metricset, self.nestimators, self.contamination)\n ift.fit()\n self.iforest = ift\n\n def predict(self, potentialdata, output, is_whole):\n potentialdata = potentialdata.copy()\n self.is_whole = is_whole\n self.output = output\n score = pd.DataFrame(self.iforest.predict(potentialdata))\n score.index = potentialdata.index\n potentialdata['simi'] = score\n\n self.similarity_label = (abs(potentialdata['simi']) - abs(potentialdata['simi']).min()) / (\n abs(potentialdata['simi']).max() - abs(potentialdata['simi']).min())\n\n if self.output == None:\n potentialdata = potentialdata.sort_values(by='simi')\n elif self.output > 1:\n potentialdata = potentialdata.sort_values(by='simi')\n potentialdata = potentialdata.iloc[:self.output, :]\n elif self.output > 0 and self.output < 1:\n potentialdata = potentialdata.sort_values(by='simi')\n assert (self.output * self.original_data.shape[0]) < potentialdata.shape[\n 0], '你想要产出的异常点超过预估点,请降低异常点数output值'\n potentialdata = potentialdata.iloc[:int(self.output * self.original_data.shape[0]), :]\n\n assert abs(potentialdata['simi']).max() != abs(potentialdata['simi']).min(), '数据无明显离散异常点'\n\n # output\n if self.is_whole:\n isw = iswhole(potentialdata)\n out = isw.getoutput(self.original_data)\n else:\n outindex = [x for x in potentialdata.columns if x != 'simi']\n out = potentialdata[outindex]\n return out\n"
] |
[
[
"pandas.concat",
"numpy.cov",
"pandas.DataFrame"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
voidism/End-to-end-ASR-Pytorch
|
[
"509c389fa6ab98c30e227c6f4c8f7474adbc1bb2"
] |
[
"bin/train_asr.py"
] |
[
"import torch\nfrom src.solver import BaseSolver\n\nfrom src.asr import ASR\nfrom src.optim import Optimizer\nfrom src.data import load_dataset\nfrom src.util import human_format, cal_er, feat_to_fig\n\n\nclass Solver(BaseSolver):\n ''' Solver for training'''\n\n def __init__(self, config, paras, mode):\n super().__init__(config, paras, mode)\n # Logger settings\n self.best_wer = {'att': 3.0, 'ctc': 3.0}\n # Curriculum learning affects data loader\n self.curriculum = self.config['hparas']['curriculum']\n\n def fetch_data(self, data):\n ''' Move data to device and compute text seq. length'''\n _, feat, feat_len, txt = data\n feat = feat.to(self.device)\n feat_len = feat_len.to(self.device)\n txt = txt.to(self.device)\n txt_len = torch.sum(txt != 0, dim=-1)\n\n return feat, feat_len, txt, txt_len\n\n def load_data(self):\n ''' Load data for training/validation, store tokenizer and input/output shape'''\n self.tr_set, self.dv_set, self.feat_dim, self.vocab_size, self.tokenizer, msg = \\\n load_dataset(self.paras.njobs, self.paras.gpu, self.paras.pin_memory,\n self.curriculum > 0, **self.config['data'])\n self.verbose(msg)\n\n def set_model(self):\n ''' Setup ASR model and optimizer '''\n # Model\n init_adadelta = self.config['hparas']['optimizer'] == 'Adadelta'\n self.model = ASR(self.feat_dim, self.vocab_size, init_adadelta, **\n self.config['model']).to(self.device)\n self.verbose(self.model.create_msg())\n model_paras = [{'params': self.model.parameters()}]\n\n # Losses\n self.seq_loss = torch.nn.CrossEntropyLoss(ignore_index=0)\n # Note: zero_infinity=False is unstable?\n self.ctc_loss = torch.nn.CTCLoss(blank=0, zero_infinity=False)\n\n # Plug-ins\n self.emb_fuse = False\n self.emb_reg = ('emb' in self.config) and (\n self.config['emb']['enable'])\n if self.emb_reg:\n from src.plugin import EmbeddingRegularizer\n self.emb_decoder = EmbeddingRegularizer(\n self.tokenizer, self.model.dec_dim, **self.config['emb']).to(self.device)\n model_paras.append({'params': self.emb_decoder.parameters()})\n self.emb_fuse = self.emb_decoder.apply_fuse\n if self.emb_fuse:\n self.seq_loss = torch.nn.NLLLoss(ignore_index=0)\n self.verbose(self.emb_decoder.create_msg())\n\n # Optimizer\n self.optimizer = Optimizer(model_paras, **self.config['hparas'])\n self.verbose(self.optimizer.create_msg())\n\n # Enable AMP if needed\n self.enable_apex()\n\n # Automatically load pre-trained model if self.paras.load is given\n self.load_ckpt()\n\n # ToDo: other training methods\n\n def exec(self):\n ''' Training End-to-end ASR system '''\n self.verbose('Total training steps {}.'.format(\n human_format(self.max_step)))\n ctc_loss, att_loss, emb_loss = None, None, None\n n_epochs = 0\n self.timer.set()\n\n while self.step < self.max_step:\n # Renew dataloader to enable random sampling\n if self.curriculum > 0 and n_epochs == self.curriculum:\n self.verbose(\n 'Curriculum learning ends after {} epochs, starting random sampling.'.format(n_epochs))\n self.tr_set, _, _, _, _, _ = \\\n load_dataset(self.paras.njobs, self.paras.gpu, self.paras.pin_memory,\n False, **self.config['data'])\n for data in self.tr_set:\n # Pre-step : update tf_rate/lr_rate and do zero_grad\n tf_rate = self.optimizer.pre_step(self.step)\n total_loss = 0\n\n # Fetch data\n feat, feat_len, txt, txt_len = self.fetch_data(data)\n self.timer.cnt('rd')\n\n # Forward model\n # Note: txt should NOT start w/ <sos>\n ctc_output, encode_len, att_output, att_align, dec_state = \\\n self.model(feat, feat_len, max(txt_len), tf_rate=tf_rate,\n teacher=txt, get_dec_state=self.emb_reg)\n\n # Plugins\n if self.emb_reg:\n emb_loss, fuse_output = self.emb_decoder(\n dec_state, att_output, label=txt)\n total_loss += self.emb_decoder.weight*emb_loss\n\n # Compute all objectives\n if ctc_output is not None:\n if self.paras.cudnn_ctc:\n ctc_loss = self.ctc_loss(ctc_output.transpose(0, 1),\n txt.to_sparse().values().to(device='cpu', dtype=torch.int32),\n [ctc_output.shape[1]] *\n len(ctc_output),\n txt_len.cpu().tolist())\n else:\n ctc_loss = self.ctc_loss(ctc_output.transpose(\n 0, 1), txt, encode_len, txt_len)\n total_loss += ctc_loss*self.model.ctc_weight\n\n if att_output is not None:\n b, t, _ = att_output.shape\n att_output = fuse_output if self.emb_fuse else att_output\n att_loss = self.seq_loss(\n att_output.contiguous().view(b*t, -1), txt.contiguous().view(-1))\n total_loss += att_loss*(1-self.model.ctc_weight)\n\n self.timer.cnt('fw')\n\n # Backprop\n grad_norm = self.backward(total_loss)\n self.step += 1\n\n # Logger\n if (self.step == 1) or (self.step % self.PROGRESS_STEP == 0):\n self.progress('Tr stat | Loss - {:.2f} | Grad. Norm - {:.2f} | {}'\n .format(total_loss.cpu().item(), grad_norm, self.timer.show()))\n self.write_log(\n 'loss', {'tr_ctc': ctc_loss, 'tr_att': att_loss})\n self.write_log('emb_loss', {'tr': emb_loss})\n self.write_log('wer', {'tr_att': cal_er(self.tokenizer, att_output, txt),\n 'tr_ctc': cal_er(self.tokenizer, ctc_output, txt, ctc=True)})\n if self.emb_fuse:\n if self.emb_decoder.fuse_learnable:\n self.write_log('fuse_lambda', {\n 'emb': self.emb_decoder.get_weight()})\n self.write_log(\n 'fuse_temp', {'temp': self.emb_decoder.get_temp()})\n\n # Validation\n if (self.step == 1) or (self.step % self.valid_step == 0):\n self.validate()\n\n # End of step\n # https://github.com/pytorch/pytorch/issues/13246#issuecomment-529185354\n torch.cuda.empty_cache()\n self.timer.set()\n if self.step > self.max_step:\n break\n n_epochs += 1\n self.log.close()\n\n def validate(self):\n # Eval mode\n self.model.eval()\n if self.emb_decoder is not None:\n self.emb_decoder.eval()\n dev_wer = {'att': [], 'ctc': []}\n\n for i, data in enumerate(self.dv_set):\n self.progress('Valid step - {}/{}'.format(i+1, len(self.dv_set)))\n # Fetch data\n feat, feat_len, txt, txt_len = self.fetch_data(data)\n\n # Forward model\n with torch.no_grad():\n ctc_output, encode_len, att_output, att_align, dec_state = \\\n self.model(feat, feat_len, int(max(txt_len)*self.DEV_STEP_RATIO),\n emb_decoder=self.emb_decoder)\n\n dev_wer['att'].append(cal_er(self.tokenizer, att_output, txt))\n dev_wer['ctc'].append(cal_er(self.tokenizer, ctc_output, txt, ctc=True))\n\n # Show some example on tensorboard\n if i == len(self.dv_set)//2:\n for i in range(min(len(txt), self.DEV_N_EXAMPLE)):\n if self.step == 1:\n self.write_log('true_text{}'.format(\n i), self.tokenizer.decode(txt[i].tolist()))\n if att_output is not None:\n self.write_log('att_align{}'.format(i), feat_to_fig(\n att_align[i, 0, :, :].cpu().detach()))\n self.write_log('att_text{}'.format(i), self.tokenizer.decode(\n att_output[i].argmax(dim=-1).tolist()))\n if ctc_output is not None:\n self.write_log('ctc_text{}'.format(i), self.tokenizer.decode(ctc_output[i].argmax(dim=-1).tolist(),\n ignore_repeat=True))\n\n # Ckpt if performance improves\n for task in ['att', 'ctc']:\n dev_wer[task] = sum(dev_wer[task])/len(dev_wer[task])\n if dev_wer[task] < self.best_wer[task]:\n self.best_wer[task] = dev_wer[task]\n self.save_checkpoint('best_{}.pth'.format(task), 'wer', dev_wer[task])\n self.write_log('wer', {'dv_'+task: dev_wer[task]})\n self.save_checkpoint('latest.pth', 'wer', dev_wer['att'], show_msg=False)\n\n # Resume training\n self.model.train()\n if self.emb_decoder is not None:\n self.emb_decoder.train()\n"
] |
[
[
"torch.nn.NLLLoss",
"torch.nn.CrossEntropyLoss",
"torch.sum",
"torch.cuda.empty_cache",
"torch.no_grad",
"torch.nn.CTCLoss"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
hmeine/numpy
|
[
"ddd02d50e8cd06d84deecd3b2943813be20b91b8"
] |
[
"numpy/core/tests/test_deprecations.py"
] |
[
"\"\"\"\nTests related to deprecation warnings. Also a convenient place\nto document how deprecations should eventually be turned into errors.\n\n\"\"\"\nfrom __future__ import division, absolute_import, print_function\n\nimport sys\nimport operator\nimport warnings\nfrom nose.plugins.skip import SkipTest\n\nimport numpy as np\nfrom numpy.testing import (dec, run_module_suite, assert_raises,\n assert_warns, assert_array_equal)\n\n\nclass _DeprecationTestCase(object):\n # Just as warning: warnings uses re.match, so the start of this message\n # must match.\n message = ''\n\n def setUp(self):\n self.warn_ctx = warnings.catch_warnings(record=True)\n self.log = self.warn_ctx.__enter__()\n\n # Do *not* ignore other DeprecationWarnings. Ignoring warnings\n # can give very confusing results because of\n # http://bugs.python.org/issue4180 and it is probably simplest to\n # try to keep the tests cleanly giving only the right warning type.\n # (While checking them set to \"error\" those are ignored anyway)\n # We still have them show up, because otherwise they would be raised\n warnings.filterwarnings(\"always\", category=DeprecationWarning)\n warnings.filterwarnings(\"always\", message=self.message,\n category=DeprecationWarning)\n\n\n def tearDown(self):\n self.warn_ctx.__exit__()\n\n\n def assert_deprecated(self, function, num=1, ignore_others=False,\n function_fails=False,\n exceptions=(DeprecationWarning,), args=(), kwargs={}):\n \"\"\"Test if DeprecationWarnings are given and raised.\n\n This first checks if the function when called gives `num`\n DeprecationWarnings, after that it tries to raise these\n DeprecationWarnings and compares them with `exceptions`.\n The exceptions can be different for cases where this code path\n is simply not anticipated and the exception is replaced.\n\n Parameters\n ----------\n f : callable\n The function to test\n num : int\n Number of DeprecationWarnings to expect. This should normally be 1.\n ignore_other : bool\n Whether warnings of the wrong type should be ignored (note that\n the message is not checked)\n function_fails : bool\n If the function would normally fail, setting this will check for\n warnings inside a try/except block.\n exceptions : Exception or tuple of Exceptions\n Exception to expect when turning the warnings into an error.\n The default checks for DeprecationWarnings. If exceptions is\n empty the function is expected to run successfull.\n args : tuple\n Arguments for `f`\n kwargs : dict\n Keyword arguments for `f`\n \"\"\"\n # reset the log\n self.log[:] = []\n\n try:\n function(*args, **kwargs)\n except (Exception if function_fails else tuple()):\n pass\n # just in case, clear the registry\n num_found = 0\n for warning in self.log:\n if warning.category is DeprecationWarning:\n num_found += 1\n elif not ignore_others:\n raise AssertionError(\"expected DeprecationWarning but %s given\"\n % warning.category)\n if num_found != num:\n raise AssertionError(\"%i warnings found but %i expected\"\n % (len(self.log), num))\n\n with warnings.catch_warnings():\n warnings.filterwarnings(\"error\", message=self.message,\n category=DeprecationWarning)\n\n try:\n function(*args, **kwargs)\n if exceptions != tuple():\n raise AssertionError(\"No error raised during function call\")\n except exceptions:\n if exceptions == tuple():\n raise AssertionError(\"Error raised during function call\")\n\n\n def assert_not_deprecated(self, function, args=(), kwargs={}):\n \"\"\"Test if DeprecationWarnings are given and raised.\n\n This is just a shorthand for:\n\n self.assert_deprecated(function, num=0, ignore_others=True,\n exceptions=tuple(), args=args, kwargs=kwargs)\n \"\"\"\n self.assert_deprecated(function, num=0, ignore_others=True,\n exceptions=tuple(), args=args, kwargs=kwargs)\n\n\nclass TestFloatNonIntegerArgumentDeprecation(_DeprecationTestCase):\n \"\"\"\n These test that ``DeprecationWarning`` is given when you try to use\n non-integers as arguments to for indexing and slicing e.g. ``a[0.0:5]``\n and ``a[0.5]``, or other functions like ``array.reshape(1., -1)``.\n\n After deprecation, changes need to be done inside conversion_utils.c\n in PyArray_PyIntAsIntp and possibly PyArray_IntpConverter.\n In iterators.c the function slice_GetIndices could be removed in favor\n of its python equivalent and in mapping.c the function _tuple_of_integers\n can be simplified (if ``np.array([1]).__index__()`` is also deprecated).\n\n As for the deprecation time-frame: via Ralf Gommers,\n\n \"Hard to put that as a version number, since we don't know if the\n version after 1.8 will be 6 months or 2 years after. I'd say 2\n years is reasonable.\"\n\n I interpret this to mean 2 years after the 1.8 release. Possibly\n giving a PendingDeprecationWarning before that (which is visible\n by default)\n\n \"\"\"\n message = \"using a non-integer number instead of an integer \" \\\n \"will result in an error in the future\"\n\n def test_indexing(self):\n a = np.array([[[5]]])\n def assert_deprecated(*args, **kwargs):\n self.assert_deprecated(*args, exceptions=(IndexError,), **kwargs)\n\n assert_deprecated(lambda: a[0.0])\n assert_deprecated(lambda: a[0, 0.0])\n assert_deprecated(lambda: a[0.0, 0])\n assert_deprecated(lambda: a[0.0,:])\n assert_deprecated(lambda: a[:, 0.0])\n assert_deprecated(lambda: a[:, 0.0,:])\n assert_deprecated(lambda: a[0.0,:,:])\n assert_deprecated(lambda: a[0, 0, 0.0])\n assert_deprecated(lambda: a[0.0, 0, 0])\n assert_deprecated(lambda: a[0, 0.0, 0])\n assert_deprecated(lambda: a[-1.4])\n assert_deprecated(lambda: a[0, -1.4])\n assert_deprecated(lambda: a[-1.4, 0])\n assert_deprecated(lambda: a[-1.4,:])\n assert_deprecated(lambda: a[:, -1.4])\n assert_deprecated(lambda: a[:, -1.4,:])\n assert_deprecated(lambda: a[-1.4,:,:])\n assert_deprecated(lambda: a[0, 0, -1.4])\n assert_deprecated(lambda: a[-1.4, 0, 0])\n assert_deprecated(lambda: a[0, -1.4, 0])\n\n # Test that the slice parameter deprecation warning doesn't mask\n # the scalar index warning.\n assert_deprecated(lambda: a[0.0:, 0.0], num=2)\n assert_deprecated(lambda: a[0.0:, 0.0,:], num=2)\n\n\n def test_valid_indexing(self):\n a = np.array([[[5]]])\n assert_not_deprecated = self.assert_not_deprecated\n\n assert_not_deprecated(lambda: a[np.array([0])])\n assert_not_deprecated(lambda: a[[0, 0]])\n assert_not_deprecated(lambda: a[:, [0, 0]])\n assert_not_deprecated(lambda: a[:, 0,:])\n assert_not_deprecated(lambda: a[:,:,:])\n\n\n def test_slicing(self):\n a = np.array([[5]])\n def assert_deprecated(*args, **kwargs):\n self.assert_deprecated(*args, exceptions=(IndexError,), **kwargs)\n\n # start as float.\n assert_deprecated(lambda: a[0.0:])\n assert_deprecated(lambda: a[0:, 0.0:2])\n assert_deprecated(lambda: a[0.0::2, :0])\n assert_deprecated(lambda: a[0.0:1:2,:])\n assert_deprecated(lambda: a[:, 0.0:])\n # stop as float.\n assert_deprecated(lambda: a[:0.0])\n assert_deprecated(lambda: a[:0, 1:2.0])\n assert_deprecated(lambda: a[:0.0:2, :0])\n assert_deprecated(lambda: a[:0.0,:])\n assert_deprecated(lambda: a[:, 0:4.0:2])\n # step as float.\n assert_deprecated(lambda: a[::1.0])\n assert_deprecated(lambda: a[0:, :2:2.0])\n assert_deprecated(lambda: a[1::4.0, :0])\n assert_deprecated(lambda: a[::5.0,:])\n assert_deprecated(lambda: a[:, 0:4:2.0])\n # mixed.\n assert_deprecated(lambda: a[1.0:2:2.0], num=2)\n assert_deprecated(lambda: a[1.0::2.0], num=2)\n assert_deprecated(lambda: a[0:, :2.0:2.0], num=2)\n assert_deprecated(lambda: a[1.0:1:4.0, :0], num=2)\n assert_deprecated(lambda: a[1.0:5.0:5.0,:], num=3)\n assert_deprecated(lambda: a[:, 0.4:4.0:2.0], num=3)\n # should still get the DeprecationWarning if step = 0.\n assert_deprecated(lambda: a[::0.0], function_fails=True)\n\n\n def test_valid_slicing(self):\n a = np.array([[[5]]])\n assert_not_deprecated = self.assert_not_deprecated\n\n assert_not_deprecated(lambda: a[::])\n assert_not_deprecated(lambda: a[0:])\n assert_not_deprecated(lambda: a[:2])\n assert_not_deprecated(lambda: a[0:2])\n assert_not_deprecated(lambda: a[::2])\n assert_not_deprecated(lambda: a[1::2])\n assert_not_deprecated(lambda: a[:2:2])\n assert_not_deprecated(lambda: a[1:2:2])\n\n\n def test_non_integer_argument_deprecations(self):\n a = np.array([[5]])\n\n self.assert_deprecated(np.reshape, args=(a, (1., 1., -1)), num=2)\n self.assert_deprecated(np.reshape, args=(a, (np.array(1.), -1)))\n self.assert_deprecated(np.take, args=(a, [0], 1.))\n self.assert_deprecated(np.take, args=(a, [0], np.float64(1.)))\n\n\n def test_non_integer_sequence_multiplication(self):\n # Numpy scalar sequence multiply should not work with non-integers\n def mult(a, b):\n return a * b\n self.assert_deprecated(mult, args=([1], np.float_(3)))\n self.assert_not_deprecated(mult, args=([1], np.int_(3)))\n\n\nclass TestBooleanArgumentDeprecation(_DeprecationTestCase):\n \"\"\"This tests that using a boolean as integer argument/indexing is\n deprecated.\n\n This should be kept in sync with TestFloatNonIntegerArgumentDeprecation\n and like it is handled in PyArray_PyIntAsIntp.\n \"\"\"\n message = \"using a boolean instead of an integer \" \\\n \"will result in an error in the future\"\n\n def test_bool_as_int_argument(self):\n a = np.array([[[1]]])\n\n self.assert_deprecated(np.reshape, args=(a, (True, -1)))\n self.assert_deprecated(np.reshape, args=(a, (np.bool_(True), -1)))\n # Note that operator.index(np.array(True)) does not work, a boolean\n # array is thus also deprecated, but not with the same message:\n assert_raises(TypeError, operator.index, np.array(True))\n self.assert_deprecated(np.take, args=(a, [0], False))\n self.assert_deprecated(lambda: a[False:True:True], exceptions=IndexError, num=3)\n self.assert_deprecated(lambda: a[False, 0], exceptions=IndexError)\n self.assert_deprecated(lambda: a[False, 0, 0], exceptions=IndexError)\n\n\nclass TestArrayToIndexDeprecation(_DeprecationTestCase):\n \"\"\"This tests that creating an an index from an array is deprecated\n if the array is not 0d.\n\n This can probably be deprecated somewhat faster then the integer\n deprecations. The deprecation period started with NumPy 1.8.\n For deprecation this needs changing of array_index in number.c\n \"\"\"\n message = \"converting an array with ndim \\> 0 to an index will result \" \\\n \"in an error in the future\"\n\n def test_array_to_index_deprecation(self):\n # This drops into the non-integer deprecation, which is ignored here,\n # so no exception is expected. The raising is effectively tested above.\n a = np.array([[[1]]])\n\n self.assert_deprecated(operator.index, args=(np.array([1]),))\n self.assert_deprecated(np.reshape, args=(a, (a, -1)), exceptions=())\n self.assert_deprecated(np.take, args=(a, [0], a), exceptions=())\n # Check slicing. Normal indexing checks arrays specifically.\n self.assert_deprecated(lambda: a[a:a:a], exceptions=(), num=3)\n\n\nclass TestNonIntegerArrayLike(_DeprecationTestCase):\n \"\"\"Tests that array likes, i.e. lists give a deprecation warning\n when they cannot be safely cast to an integer.\n \"\"\"\n message = \"non integer \\(and non boolean\\) array-likes will not be \" \\\n \"accepted as indices in the future\"\n\n def test_basic(self):\n a = np.arange(10)\n self.assert_deprecated(a.__getitem__, args=([0.5, 1.5],),\n exceptions=IndexError)\n self.assert_deprecated(a.__getitem__, args=((['1', '2'],),),\n exceptions=IndexError)\n\n self.assert_not_deprecated(a.__getitem__, ([],))\n\n\n def test_boolean_futurewarning(self):\n a = np.arange(10)\n with warnings.catch_warnings():\n warnings.filterwarnings('always')\n assert_warns(FutureWarning, a.__getitem__, [True])\n # Unfortunatly, the deprecation warning takes precedence:\n #assert_warns(FutureWarning, a.__getitem__, True)\n\n with warnings.catch_warnings():\n warnings.filterwarnings('error')\n assert_raises(FutureWarning, a.__getitem__, [True])\n #assert_raises(FutureWarning, a.__getitem__, True)\n\n\nclass TestMultipleEllipsisDeprecation(_DeprecationTestCase):\n message = \"an index can only have a single Ellipsis \\(`...`\\); replace \" \\\n \"all but one with slices \\(`:`\\).\"\n\n def test_basic(self):\n a = np.arange(10)\n self.assert_deprecated(a.__getitem__, args=((Ellipsis, Ellipsis),))\n\n with warnings.catch_warnings():\n warnings.filterwarnings('ignore', '', DeprecationWarning)\n # Just check that this works:\n b = a[...,...]\n assert_array_equal(a, b)\n assert_raises(IndexError, a.__getitem__, ((Ellipsis, ) * 3,))\n\n\nclass TestBooleanSubtractDeprecations(_DeprecationTestCase):\n \"\"\"Test deprecation of boolean `-`. While + and * are well\n defined, - is not and even a corrected form seems to have\n no real uses.\n\n The deprecation process was started in NumPy 1.9.\n \"\"\"\n message = r\"numpy boolean .* \\(the .* `-` operator\\) is deprecated, \" \\\n \"use the bitwise\"\n\n def test_operator_deprecation(self):\n array = np.array([True])\n generic = np.bool_(True)\n\n # Minus operator/subtract ufunc:\n self.assert_deprecated(operator.sub, args=(array, array))\n self.assert_deprecated(operator.sub, args=(generic, generic))\n\n # Unary minus/negative ufunc:\n self.assert_deprecated(operator.neg, args=(array,))\n self.assert_deprecated(operator.neg, args=(generic,))\n\n\nif __name__ == \"__main__\":\n run_module_suite()\n"
] |
[
[
"numpy.testing.run_module_suite",
"numpy.arange",
"numpy.int_",
"numpy.testing.assert_array_equal",
"numpy.testing.assert_warns",
"numpy.testing.assert_raises",
"numpy.float64",
"numpy.float_",
"numpy.array",
"numpy.bool_"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
MorrisHuang-skipper/Serial-MD
|
[
"48356dc88cdc47a832fa02bc61a03d8583bb4a79"
] |
[
"analysis/video.py"
] |
[
"import matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport numpy as np\nfrom pylab import cm\nimport math\nfrom mpl_toolkits.mplot3d import Axes3D\nimport os\nimport sys\nimport matplotlib.gridspec as gridspec\n\nmpl.rcParams['font.family'] = 'STIXGeneral'\nplt.rcParams['xtick.labelsize'] = 16\nplt.rcParams['ytick.labelsize'] = 16\nplt.rcParams['font.size'] = 16\nplt.rcParams['figure.figsize'] = [5.4*4, 5.2]\nplt.rcParams['axes.titlesize'] = 16\nplt.rcParams['axes.labelsize'] = 16\nplt.rcParams['lines.linewidth'] = 2\nplt.rcParams['lines.markersize'] = 6\nplt.rcParams['legend.fontsize'] = 13\nplt.rcParams['mathtext.fontset'] = 'stix'\nplt.rcParams['axes.linewidth'] = 1\n\ncolors = cm.get_cmap('Set1', 10)\n\nfig = plt.figure(constrained_layout=True)\nspec = gridspec.GridSpec(ncols=4, nrows=1, figure=fig)\n\nax = fig.add_subplot(spec[0, 0])\nax2 = fig.add_subplot(spec[0, 1])\nax3 = fig.add_subplot(spec[0, 2])\nax4 = fig.add_subplot(spec[0, 3])\n\n# ax = fig.add_subplot(1, 3, 1, projection='3d')\n\nax.xaxis.set_tick_params(which='major', size=5, width=1,\n direction='in', top='on')\nax.xaxis.set_tick_params(which='minor', size=3, width=1,\n direction='in', top='on')\nax.yaxis.set_tick_params(which='major', size=5, width=1,\n direction='in', right='on')\nax.yaxis.set_tick_params(which='minor', size=3, width=1,\n direction='in', right='on')\n\nfname = 'ext'\nrx = np.loadtxt('../../data/'+fname+'/rx.dat')\nry = np.loadtxt('../../data/'+fname+'/ry.dat')\nrz = np.loadtxt('../../data/'+fname+'/rz.dat')\nvx = np.loadtxt('../../data/'+fname+'/vx.dat')\nvy = np.loadtxt('../../data/'+fname+'/vy.dat')\nvz = np.loadtxt('../../data/'+fname+'/vz.dat')\nt, Ki, Ke, K, U, Te, Ti, within = np.loadtxt('../../data/'+fname+'/info.dat', unpack=True)\n\nx1 = np.arange(-10, 10, 0.00001)\nyy1 = (40-x1**2)**0.5\nyy2 = -(40-x1**2)**0.5\n\nstep = rx.shape[0]\nNP = rx.shape[1]\ne = 1.60217e-19\nkt = e/38.9\nnth = 50\n\n# plot phase space\nfor i in range(0, step, 1):\n num = '{0:04}'.format(i)\n # ax.set_zlim(0, 10)\n # 2d\n ax.plot(rx[i, :-(NP//2)]*1e9, ry[i, :-(NP//2)]*1e9, '.', color=colors(0), label='$H^+$', markersize=3)\n ax.plot(rx[i, (NP//2):]*1e9, ry[i, (NP//2):]*1e9, '.', color=colors(1), label='$e^{-}$', markersize=3)\n ax.plot(rx[:i, nth]*1e9, ry[:i, nth]*1e9, '-', color=colors(2), label='tracking')\n # for j in range(50):\n # ax.plot(rx[:i, nth+j]*1e9, ry[:i, nth+j]*1e9, '.')\n\n ax.set_xlabel('$x \\ [nm]$')\n ax.set_ylabel('$y \\ [nm]$')\n ax.set_xlim(0, 40)\n ax.set_ylim(0, 40)\n\n # diag\n ax2.plot(t[:i]*1e15, (Ki[:i]+Ke[:i])/e/NP, '-', label=r'$K_{avg}$', color=colors(2))\n ax2.plot(t[:i]*1e15, U[:i]/e/NP, '-', label=r'$U_{avg}$', color=colors(3))\n ax2.plot(t[:i]*1e15, Ki[:i]/e/NP+Ke[:i]/e/NP+U[:i]/e/NP, '-', label=r'$E_{avg}$', color=colors(4))\n ax2.set_xlabel('$time \\ [fs]$')\n # ax2.set_ylabel('$E \\ [ev]$')\n ax2.set_xlim(0, 100)\n\n ax3.plot(t[:i]*1e15, Te[:i]/e, '-', label=r'$T_e$', color=colors(6))\n ax3.plot(t[:i]*1e15, Ti[:i]/e, '-', label=r'$T_i$', color=colors(0))\n ax3.set_xlabel('$time \\ [fs]$')\n ax3.set_ylabel('$Temperature \\ [eV]$')\n # ax3.set_ylabel('$Temperature \\ [k_BT]$')\n ax3.set_xlim(0, 100)\n\n ax4.hist(vx[i, 1:NP//2], histtype='step')\n ax4.hist(vx[i, NP//2+1:NP], histtype='step')\n # ax4.set_xlabel('$time \\ [fs]$')\n # ax4.set_ylabel('$Temperature \\ [eV]$')\n # ax4.set_xlim(0, 100)\n\n ax.legend(loc=1)\n ax2.legend(loc=1)\n ax3.legend(loc=1)\n ax4.legend(loc=1)\n\n plt.tight_layout()\n plt.show(block=False)\n plt.pause(.01)\n # plt.savefig('../figures/'+fname+'/'+str(num)+'.png', dpi=300)\n ax.clear()\n ax2.clear()\n ax3.clear()\n ax4.clear()\n \n\n\n# os.system('ffmpeg -i ../figures/'+fname+'/%04d.png -c:v ffv1 -qscale:v 0 ../figures/animate.mp4')\n\n# plt.tight_layout()\n"
] |
[
[
"matplotlib.pyplot.tight_layout",
"numpy.arange",
"matplotlib.gridspec.GridSpec",
"matplotlib.pyplot.show",
"matplotlib.pyplot.pause",
"numpy.loadtxt",
"matplotlib.pyplot.figure"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jskolnicki/100-Days-of-Python
|
[
"146af2b73914a525121f1c91737abd4857dc2f89",
"146af2b73914a525121f1c91737abd4857dc2f89"
] |
[
"day-32-automated-email/main.py",
"day-28-pomodoro-and-dammits/dammits.py"
] |
[
"##################### Extra Hard Starting Project ######################\n\nfrom email import message\nfrom re import template\nimport pandas as pd\nimport os\nimport datetime\nimport random\nimport smtplib\nfrom csv import reader\n\nos.chdir(os.path.dirname(__file__))\n\nmy_email = \"[email protected]\"\npassword = \"abcdefg123()\"\n\n# 1. Update the birthdays.csv\n\n# 2. Check if today matches a birthday in the birthdays.csv\n\ndf = pd.read_csv(\"birthdays.csv\")\n\n\ntoday_string = datetime.date.today().strftime('%m-%d')\n\nwith open('birthdays.csv', 'r') as read_obj:\n csv_reader = reader(read_obj)\n header = next(csv_reader)\n # Check file as empty\n if header != None:\n # Iterate over each row after the header in the csv\n for row in csv_reader:\n # row variable is a list that represents a row in csv\n birthday = f'{row[4].zfill(2)}-{row[5].zfill(2)}'\n\n if birthday == today_string:\n\n# 3. If step 2 is true, pick a random letter from letter templates and replace the [NAME] with the person's actual name from birthdays.csv \n number_of_letter_options = 0\n for letter in os.listdir('letter_templates'):\n if row[1] in letter:\n number_of_letter_options += 1\n with open(f'C:/Users/jared/GitHub/continued-ed/100-Days-of-Python/day-32-email/letter_templates/{row[1]}_{random.randint(1,number_of_letter_options)}.txt') as file:\n message = file.readlines()\n email_message = \"\"\n for line in message:\n email_message = email_message + line\n email_message = email_message.replace(\"[NAME]\",row[0])\n\n \n# 4. Send the letter generated in step 3 to that person's email address.\n with smtplib.SMTP(\"smtp.gmail.com\", port=587) as connection:\n connection.starttls()\n connection.login(user=my_email, password=password)\n\n connection.sendmail(from_addr=my_email,\n to_addrs=row[2],\n msg= f'Subject:Happy Birthday!\\n\\n{email_message}')",
"import tkinter\nimport os\nimport pandas as pd\nimport datetime\nimport csv\n\nos.chdir(os.path.dirname(__file__))\n\nwindow = tkinter.Tk()\nwindow.title(\"Dammit Counter\")\n\n#variables\ndammits_db = pd.read_csv(\"dammits.csv\")\ndammits_db['Week'] = pd.to_datetime(dammits_db['Week'])\n\n\ntoday = datetime.date.today()\n\ntoday = today + datetime.timedelta(days= 2)\n\nstart_of_week = pd.to_datetime(dammits_db['Week'].to_list()[-1])\n\ncurrent_week_index = int(dammits_db['Week'][dammits_db['Week'] == start_of_week].index[0])\n\nnum_of_yikes = dammits_db.iloc[current_week_index, 1]\nnum_of_dammits = dammits_db.iloc[current_week_index, 2]\n\n#FUNCTIONS\n\n\n\ndef increase_dammits():\n global current_week_index, dammits_db\n with open(\"dammits.csv\") as f:\n reader = csv.reader(f)\n data = list(reader)\n \n data[current_week_index + 1][2] = int(data[current_week_index + 1][2]) + 1\n \n with open(\"dammits.csv\", \"w\", newline = \"\") as f: \n a = csv.writer(f)\n for row in data:\n a.writerow(row)\n \n dammits_db = pd.read_csv(\"dammits.csv\")\n dammits_db['Week'] = pd.to_datetime(dammits_db['Week'])\n\n update_board()\n\ndef decrease_dammits():\n global current_week_index, dammits_db\n with open(\"dammits.csv\") as f:\n reader = csv.reader(f)\n data = list(reader)\n \n data[current_week_index + 1][2] = int(data[current_week_index + 1][2]) - 1\n \n with open(\"dammits.csv\", \"w\", newline = \"\") as f: \n a = csv.writer(f)\n for row in data:\n a.writerow(row)\n \n dammits_db = pd.read_csv(\"dammits.csv\")\n dammits_db['Week'] = pd.to_datetime(dammits_db['Week'])\n\n update_board()\n\ndef increase_yikes():\n global current_week_index, dammits_db\n with open(\"dammits.csv\") as f:\n reader = csv.reader(f)\n data = list(reader)\n \n data[current_week_index + 1][1] = int(data[current_week_index + 1][1]) + 1\n \n with open(\"dammits.csv\", \"w\", newline = \"\") as f: \n a = csv.writer(f)\n for row in data:\n a.writerow(row)\n \n dammits_db = pd.read_csv(\"dammits.csv\")\n dammits_db['Week'] = pd.to_datetime(dammits_db['Week'])\n\n update_board()\n\ndef decrease_yikes():\n global current_week_index, dammits_db\n with open(\"dammits.csv\") as f:\n reader = csv.reader(f)\n data = list(reader)\n \n data[current_week_index + 1][1] = int(data[current_week_index + 1][1]) - 1\n \n with open(\"dammits.csv\", \"w\", newline = \"\") as f: \n a = csv.writer(f)\n for row in data:\n a.writerow(row)\n \n dammits_db = pd.read_csv(\"dammits.csv\")\n dammits_db['Week'] = pd.to_datetime(dammits_db['Week'])\n\n update_board()\n\ndef update_board():\n global current_week_index\n num_of_yikes = dammits_db.iloc[current_week_index, 1]\n num_of_yikes_label.config(text=f\"{num_of_yikes}\")\n num_of_dammits = dammits_db.iloc[current_week_index, 2]\n num_of_dammits_label.config(text=f\"{num_of_dammits}\")\n week_of_label.config(text=f\"{dammits_db.iloc[current_week_index,0].strftime('%m/%d/%Y')} - {(dammits_db['Week'][current_week_index] + datetime.timedelta(days=6)).strftime('%m/%d/%Y')}\")\n if current_week_index == 0:\n previous_week_button.grid_remove()\n elif (current_week_index == len(dammits_db['Week'])-1) and (pd.Timestamp(today - datetime.timedelta(days= 7)) < dammits_db['Week'].to_list()[-1]):\n next_week_button.grid_remove()\n else:\n previous_week_button.grid()\n next_week_button.grid()\n print(f\"Current week index: {current_week_index}\")\n print(f\"Total number of weeks: {len(dammits_db['Week'])-1}\")\n\ndef next_week():\n global current_week_index, num_of_dammits, num_of_dammits_label, num_of_yikes, num_of_yikes_label, start_of_week, week_of_label, dammits_db\n print(\"\")\n print(f\"current week index: {current_week_index}\")\n print(f\"start_of_week: {start_of_week}\")\n print(\"\")\n if current_week_index < len(dammits_db['Week'])-1:\n current_week_index += 1\n num_of_yikes = dammits_db.iloc[current_week_index, 1]\n num_of_dammits = dammits_db.iloc[current_week_index, 2]\n update_board()\n\n elif pd.Timestamp(today - datetime.timedelta(days= 7)) >= dammits_db['Week'].to_list()[-1]:\n with open('dammits.csv', 'a', newline = \"\") as file:\n writer_object = csv.writer(file)\n date_to_append = (pd.to_datetime(today + datetime.timedelta(days=-today.weekday())).strftime('%Y-%m-%d'))\n writer_object.writerow([date_to_append,0,0])\n file.close()\n dammits_db = pd.read_csv(\"dammits.csv\")\n dammits_db['Week'] = pd.to_datetime(dammits_db['Week'])\n current_week_index += 1\n num_of_yikes = dammits_db.iloc[current_week_index, 1]\n num_of_dammits = dammits_db.iloc[current_week_index, 2]\n update_board()\n # num_of_yikes = dammits_db.iloc[current_week_index, 1]\n # num_of_yikes_label.config(text=f\"{num_of_yikes}\")\n # num_of_dammits = dammits_db.iloc[current_week_index, 2]\n # num_of_dammits_label.config(text=f\"{num_of_dammits}\")\n # week_of_label.config(text=f\"{dammits_db.iloc[current_week_index,0].strftime('%m/%d/%Y')} - {(dammits_db['Week'][current_week_index] + datetime.timedelta(days=6)).strftime('%m/%d/%Y')}\")\n\ndef previous_week():\n global current_week_index, num_of_dammits, num_of_yikes, num_of_yikes_label, num_of_dammits_label\n if current_week_index > 0:\n current_week_index -= 1\n num_of_yikes = dammits_db.iloc[current_week_index, 1]\n num_of_dammits = dammits_db.iloc[current_week_index, 2]\n update_board()\n # num_of_yikes = dammits_db.iloc[current_week_index, 1]\n # num_of_yikes_label.config(text=f\"{num_of_yikes}\")\n # num_of_dammits = dammits_db.iloc[current_week_index, 2]\n # num_of_dammits_label.config(text=f\"{num_of_dammits}\")\n # week_of_label.config(text=f\"{dammits_db.iloc[current_week_index,0].strftime('%m/%d/%Y')} - {(dammits_db['Week'][current_week_index] + datetime.timedelta(days=6)).strftime('%m/%d/%Y')}\")\n\n\n#print(f\"Test: {pd.to_datetime(start_of_week + datetime.timedelta(days=6)).strftime(('%m/%d/%Y'))}\")\nprint(f\"Test: {(start_of_week + datetime.timedelta(days=6)).strftime('%m/%d/%Y')}\")\n\n#WEEKLY ROW\nprevious_week_button = tkinter.Button(text=\"⟵\", width= 11, command= previous_week)\nprevious_week_button.grid(column=0, row=0)\n\nweek_of_label = tkinter.Label(text=f\"{start_of_week.strftime('%m/%d/%Y')} - {(start_of_week + datetime.timedelta(days=6)).strftime('%m/%d/%Y')}\", font=('Arial', 18,'bold'))\nweek_of_label.config(padx=40, pady=50)\nweek_of_label.grid(column=1, row=0)\n\nnext_week_button = tkinter.Button(text=\"⟶\", width= 11, command= next_week)\nnext_week_button.grid(column=2, row=0)\nif pd.Timestamp(today - datetime.timedelta(days= 7)) < dammits_db['Week'].to_list()[-1]:\n next_week_button.grid_remove()\n\n#DAMMITS ROW\ndecrease_dammits_button = tkinter.Button(text=\"-\", width= 5, command= decrease_dammits)\ndecrease_dammits_button.grid(column=0, row=1)\n\ndammits_label = tkinter.Label(text=f\"DAMMITS\", font=('Arial', 35,'normal'))\ndammits_label.config(pady=30)\ndammits_label.grid(column= 1, row=1)\n\nincrease_dammits_button = tkinter.Button(text=\"+\", width= 5, command= increase_dammits)\nincrease_dammits_button.grid(column=2, row=1)\n\nnum_of_dammits_label = tkinter.Label(text=f\"{num_of_dammits}\", font=('Arial', 35,'normal'))\nnum_of_dammits_label.config(padx=20)\nnum_of_dammits_label.grid(column= 3, row= 1)\n\n#YIKES ROW\n\ndecrease_yikes_button = tkinter.Button(text=\"-\", width= 5, command= decrease_yikes)\ndecrease_yikes_button.grid(column=0, row=2)\n\n# canvas = tkinter.Canvas(width=400, height=128, highlightthickness=0)\n# yikes_label = tkinter.PhotoImage(file=\"yikes.png\")\n# canvas.create_image(258/2+200,64,image=yikes_label)\n# canvas.grid(columns=2,rows=3)\n\nyikes_label = tkinter.Label(text=f\"YIKES\", font=('Arial', 35,'normal'))\nyikes_label.config(pady=30)\nyikes_label.grid(column= 1, row=2)\n\nincrease_yikes_button = tkinter.Button(text=\"+\", width= 5, command= increase_yikes)\nincrease_yikes_button.grid(column=2, row=2)\n\nnum_of_yikes_label = tkinter.Label(text=f\"{num_of_yikes}\", font=('Arial', 35,'normal'))\nnum_of_yikes_label.config(padx=20)\nnum_of_yikes_label.grid(column=3,row=2)\n\n\nwindow.mainloop()\n\n\n\n#TODO\n# fix this bug where when today is far out, it still toggles correctly.. do i want to add each week until I get there or skip the csv to the current week? probably skip to current week to start\n#\n#\n#\n#\n#"
] |
[
[
"pandas.read_csv"
],
[
"pandas.read_csv",
"pandas.to_datetime"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
zju-vipa/One-GORD
|
[
"a63ecaf2b9538789ca0e761d55608a28d7194c4d",
"a63ecaf2b9538789ca0e761d55608a28d7194c4d",
"a63ecaf2b9538789ca0e761d55608a28d7194c4d",
"a63ecaf2b9538789ca0e761d55608a28d7194c4d"
] |
[
"One-GORD/Ours-o/model.py",
"AE/model.py",
"One-GORD/Ours/test_getRepreCodes_forMetrics.py",
"One-GORD/Ours-o/test_for_SwapVisual.py"
] |
[
"import os, sys\r\nimport time\r\nimport re\r\nimport numpy as np\r\nimport tensorflow as tf\r\n\r\nimport sys\r\nsys.path.append('../')\r\n\r\nimport lib.models as lib\r\nfrom lib.models import params_with_name\r\nfrom lib.models.save_images import save_images\r\nfrom lib.models.distributions import Bernoulli, Gaussian, Product\r\nfrom lib.models.nets_32x32_small import NetsRetreiver, NetsRetreiverWithClassifier\r\n\r\nTINY = 1e-8\r\nSEED = 123\r\nch=1\r\nCRITIC_ITERS = 5 # For WGAN and WGAN-GP, number of critic iters per gen iter\r\n\r\nclass DIAE(object):\r\n def __init__(self, session, arch,lr,alpha,beta,latent_dim,latent_num,class_net_unit_num,output_dim, batch_size, image_shape, exp_name, dirs,\r\n vis_reconst):\r\n \"\"\"\r\n :type output_dist: Distribution\r\n :type z_dist: Gaussian\r\n \"\"\"\r\n self.session = session\r\n self.arch = arch\r\n self.lr=lr\r\n self.alpha=alpha\r\n self.beta=beta\r\n self.latent_dim=latent_dim\r\n self.latent_num=latent_num\r\n self.class_net_unit_num=class_net_unit_num\r\n self.output_dim=output_dim\r\n self.batch_size = batch_size\r\n self.image_shape = image_shape\r\n self.exp_name = exp_name\r\n self.dirs = dirs\r\n self.vis_reconst = vis_reconst\r\n \r\n self.__build_graph()\r\n\r\n def __build_graph(self):\r\n tf.set_random_seed(SEED)\r\n np.random.seed(SEED)\r\n self.is_training = tf.placeholder(tf.bool)\r\n self.x1 = tf.placeholder(tf.float32, shape=[None] + list(self.image_shape))\r\n self.aux1_mask = tf.placeholder(tf.float32, shape=[None] + list(self.image_shape))\r\n # auxilary dataset\r\n self.aux1 = tf.placeholder(tf.float32, shape=[None] + list(self.image_shape))\r\n self.aux2 = tf.placeholder(tf.float32, shape=[None] + list(self.image_shape))\r\n self.aux_GT1 = tf.placeholder(tf.float32, shape=[None] + list(self.image_shape))\r\n self.aux_GT2 = tf.placeholder(tf.float32, shape=[None] + list(self.image_shape))\r\n self.class_gt0 = tf.placeholder(tf.float32, shape=[None] + list([self.latent_num+9]))\r\n self.class_gt1 = tf.placeholder(tf.float32, shape=[None] + list([self.latent_num+9]))\r\n self.class_gt2 = tf.placeholder(tf.float32, shape=[None] + list([self.latent_num+9]))\r\n self.class_gt3 = tf.placeholder(tf.float32, shape=[None] + list([self.latent_num+9]))\r\n self.class_gt4 = tf.placeholder(tf.float32, shape=[None] + list([self.latent_num + 9]))\r\n self.class_gt5 = tf.placeholder(tf.float32, shape=[None] + list([self.latent_num + 9]))\r\n self.class_gt6 = tf.placeholder(tf.float32, shape=[None] + list([self.latent_num + 9]))\r\n self.class_gt7 = tf.placeholder(tf.float32, shape=[None] + list([self.latent_num + 9]))\r\n self.class_gt8 = tf.placeholder(tf.float32, shape=[None] + list([self.latent_num + 9]))\r\n self.class_gt9 = tf.placeholder(tf.float32, shape=[None] + list([self.latent_num + 9]))\r\n self.class_gt10 = tf.placeholder(tf.float32, shape=[None] + list([self.latent_num + 9]))\r\n # onesample labels\r\n self.aux_class_gt=tf.placeholder(tf.float32,shape=[None]+list([self.latent_num+9]))\r\n\r\n # Normalize + reshape 'real' input data\r\n norm_x1 = 2*(tf.cast(self.x1, tf.float32)-.5)\r\n\r\n norm_aux1 = 2*(tf.cast(self.aux1, tf.float32)-.5)\r\n norm_aux2 = 2*(tf.cast(self.aux2, tf.float32)-.5)\r\n norm_aux_GT1 = 2*(tf.cast(self.aux_GT1, tf.float32)-.5)\r\n norm_aux_GT2 = 2*(tf.cast(self.aux_GT2, tf.float32)-.5)\r\n # Set Encoder and Decoder archs\r\n self.Encoder, self.Decoder,self.Classifier,self.gan_discriminator = NetsRetreiverWithClassifier(self.arch) \r\n \r\n # Encode and decode\r\n self.z1 = self.__Enc(norm_x1)\r\n self.x1_out = self.__Dec(self.z1)\r\n # aux data\r\n self.aux_z1 = self.__Enc(norm_aux1)\r\n self.aux1_out = self.__Dec(self.aux_z1)\r\n self.aux_z2 = self.__Enc(norm_aux2)\r\n self.aux2_out = self.__Dec(self.aux_z2)\r\n\r\n aux1_head,aux1_bg=tf.split(self.aux_z1,2,axis=1)\r\n aux2_head,aux2_bg=tf.split(self.aux_z2,2,axis=1)\r\n\r\n GT1_z=tf.concat([aux2_head,aux1_bg],axis=1)\r\n GT2_z=tf.concat([aux1_head,aux2_bg],axis=1)\r\n self.GT1_out = self.__Dec(GT1_z)\r\n self.GT2_out = self.__Dec(GT2_z)\r\n #dual swap\r\n x1_head,x1_bg=tf.split(self.z1,2,axis=1)\r\n self.mix_head_out=self.__Dec(tf.concat([aux1_head,x1_bg],axis=1))\r\n mix_head,mix_bg=tf.split(self.__Enc(self.mix_head_out),2,axis=1)\r\n x1_dual_out=self.__Dec(tf.concat([x1_head,mix_bg],axis=1))\r\n\r\n self.aux1_mix_head_out=self.__Dec(tf.concat([x1_head,aux1_bg],axis=1))\r\n\r\n # classification loss\r\n ## for x1\r\n r_part1, r_part2 = tf.split(self.z1, 2, axis=1)\r\n c_p0 = self.__Classifier(r_part1)\r\n c_p1 = self.__Classifier(r_part2)\r\n ## for aux1\r\n aux1_r_part1, aux1_r_part2 = tf.split(self.aux_z1, 2, axis=1)\r\n aux1_c_p0 = self.__Classifier(aux1_r_part1)\r\n aux1_c_p1 = self.__Classifier(aux1_r_part2)\r\n ## for aux2\r\n aux2_r_part1, aux2_r_part2 = tf.split(self.aux_z2, 2, axis=1)\r\n aux2_c_p0 = self.__Classifier(aux2_r_part1)\r\n aux2_c_p1 = self.__Classifier(aux2_r_part2)\r\n\r\n # Loss and optimizer\r\n self.__prep_loss_optimizer(norm_x1,norm_aux1,norm_aux2,norm_aux_GT1,norm_aux_GT2,x1_dual_out,c_p0,c_p1,aux1_c_p0,aux1_c_p1,aux2_c_p0,aux2_c_p1)\r\n\r\n def __Enc(self, x):\r\n #resnet_encoder(name, inputs, n_channels, latent_dim, is_training, mode=None, nonlinearity=tf.nn.relu):\r\n z= self.Encoder('Encoder', x, self.image_shape[0], self.latent_dim,self.is_training)\r\n return z\r\n \r\n def __Dec(self, z):\r\n x_out_logit = self.Decoder('Decoder', z, self.image_shape[0], self.is_training)\r\n x_out = tf.tanh(x_out_logit)\r\n return x_out\r\n \r\n def __Classifier(self,z):\r\n x_out= self.Classifier('Classifier', z, self.class_net_unit_num,self.latent_num+9, self.is_training)\r\n x_out = tf.nn.softmax(x_out)\r\n return x_out\r\n \r\n def __prep_loss_optimizer(self,norm_x1,norm_aux1,norm_aux2,norm_aux_GT1,norm_aux_GT2,x1_dual_out,c_p0,c_p1,aux1_c_p0,aux1_c_p1,aux2_c_p0,aux2_c_p1):\r\n \r\n norm_x1= tf.reshape(norm_x1, [-1, self.output_dim])\r\n norm_aux1= tf.reshape(norm_aux1, [-1, self.output_dim])\r\n norm_aux2= tf.reshape(norm_aux2, [-1, self.output_dim])\r\n norm_aux_GT1= tf.reshape(norm_aux_GT1, [-1, self.output_dim])\r\n norm_aux_GT2= tf.reshape(norm_aux_GT2, [-1, self.output_dim])\r\n\r\n #[Loss1]dual unsupervised img reconstruction loss\r\n self.rec_img_loss1 = tf.reduce_mean(tf.reduce_sum(tf.square(norm_x1 -self.x1_out), axis=1))\r\n self.rec_aux1_loss2 = tf.reduce_mean(tf.reduce_sum(tf.square(norm_aux1 -self.aux1_out), axis=1))\r\n self.rec_aux2_loss3 = tf.reduce_mean(tf.reduce_sum(tf.square(norm_aux2 -self.aux2_out), axis=1))\r\n #swap loss\r\n self.rec_aux1_swap_loss4 = tf.reduce_mean(tf.reduce_sum(tf.square(norm_aux_GT1 -self.GT1_out), axis=1))\r\n self.rec_aux2_swap_loss5 = tf.reduce_mean(tf.reduce_sum(tf.square(norm_aux_GT2 -self.GT2_out), axis=1))\r\n # dual swap loss\r\n self.rec_dual_loss6 = tf.reduce_mean(tf.reduce_sum(tf.square(x1_dual_out -self.x1_out), axis=1))\r\n # # head loss\r\n # # segment head and do head loss with mask\r\n # x1_out_img = tf.reshape(self.mix_head_out, shape=[-1] + self.image_shape) # to img tensor\r\n # x1_out_head = tf.multiply(x1_out_img, self.aux1_mask)\r\n # norm_aux1_img = tf.reshape(norm_aux1, shape=[-1] + self.image_shape) # to img tensor\r\n # aux1_head = tf.multiply(norm_aux1_img, self.aux1_mask)\r\n # self.head_loss = tf.reduce_mean(tf.reduce_sum(tf.square(x1_out_head - aux1_head), axis=1))\r\n # classification loss\r\n # temp_1=self.vec_gt-tf.reduce_sum((self.class_gt1-self.class_gt1*c_p1),1)*tf.reduce_sum((self.class_gt2-self.class_gt2*c_p1),1)\r\n # self.class1_loss=-tf.reduce_mean(tf.log(temp_1))\r\n temp=1-tf.reduce_sum((self.class_gt0-self.class_gt0*c_p0),1)*tf.reduce_sum((self.class_gt1-self.class_gt1*c_p0),1)*tf.reduce_sum((self.class_gt2-self.class_gt2*c_p0),1)*tf.reduce_sum((self.class_gt3-self.class_gt3*c_p0),1)*\\\r\n tf.reduce_sum((self.class_gt4-self.class_gt4*c_p0),1)*tf.reduce_sum((self.class_gt5-self.class_gt5*c_p0),1)*tf.reduce_sum((self.class_gt6-self.class_gt6*c_p0),1)*tf.reduce_sum((self.class_gt7-self.class_gt7*c_p0),1)*tf.reduce_sum((self.class_gt8-self.class_gt8*c_p0),1)*\\\r\n tf.reduce_sum((self.class_gt9-self.class_gt9*c_p0),1)\r\n self.fuzzy_class_loss = -tf.reduce_mean(tf.log(temp))\r\n self.fuzzy_bg_class_loss= -tf.reduce_mean(self.class_gt10 * tf.log(c_p1))\r\n # class_loss1 = -tf.reduce_mean(self.class_gt1 * tf.log(c_p1))\r\n self.aux1_class_loss = -tf.reduce_mean(self.aux_class_gt * tf.log(aux1_c_p0))\r\n self.aux1_bg_class_loss = -tf.reduce_mean(self.class_gt10 * tf.log(aux1_c_p1)) # [0,0,0,1]\r\n self.aux2_class_loss = -tf.reduce_mean(self.aux_class_gt * tf.log(aux2_c_p0))\r\n self.aux2_bg_class_loss = - tf.reduce_mean(self.class_gt10 * tf.log(aux2_c_p1))\r\n self.class_loss = self.fuzzy_class_loss+self.fuzzy_bg_class_loss+self.aux1_class_loss+ self.aux1_bg_class_loss+self.aux2_class_loss+ self.aux2_bg_class_loss\r\n\r\n self.loss=2*self.rec_img_loss1+self.rec_aux1_loss2+self.rec_aux2_loss3+2*self.rec_aux1_swap_loss4+2*self.rec_aux2_swap_loss5+self.rec_dual_loss6+5*self.class_loss\r\n lr=self.lr\r\n self.optimizer = tf.train.AdamOptimizer(learning_rate=lr, beta1=0., beta2=0.9).minimize(self.loss) \r\n \r\n print('Learning rate=')\r\n print(lr)\r\n \r\n def load(self):\r\n #self.saver = tf.train.Saver()\r\n self.saver = tf.train.Saver(max_to_keep=3760)\r\n ckpt = tf.train.get_checkpoint_state(self.dirs['ckpt'])\r\n \r\n if ckpt and ckpt.model_checkpoint_path:\r\n ckpt_name = ckpt.model_checkpoint_path\r\n self.saver.restore(self.session, ckpt_name)\r\n print(\"Checkpoint restored: {0}\".format(ckpt_name))\r\n prev_step = int(next(re.finditer(\"(\\d+)(?!.*\\d)\",ckpt_name)).group(0))\r\n print('prev_step=')\r\n print(prev_step)\r\n \r\n else:\r\n print(\"Failed to find checkpoint.\")\r\n prev_step = 0\r\n sys.stdout.flush()\r\n return prev_step + 1\r\n\r\n def load_fixedNum(self,inter_num):\r\n #self.saver = tf.train.Saver()\r\n self.saver = tf.train.Saver(max_to_keep=3760)\r\n ckpt = tf.train.get_checkpoint_state(self.dirs['ckpt'])\r\n if ckpt and ckpt.model_checkpoint_path:\r\n ckpt_name = ckpt.model_checkpoint_path\r\n ckpt_name_prefix=ckpt_name.split('-')[0]\r\n ckpt_name_new=ckpt_name_prefix+'-'+str(inter_num)\r\n self.saver.restore(self.session, ckpt_name_new)\r\n print(\"Checkpoint restored: {0}\".format(ckpt_name_new))\r\n prev_step = int(next(re.finditer(\"(\\d+)(?!.*\\d)\",ckpt_name_new)).group(0))\r\n print('prev_step=')\r\n print(prev_step)\r\n else:\r\n print(\"Failed to find checkpoint.\")\r\n prev_step = 0\r\n sys.stdout.flush()\r\n return prev_step + 1\r\n \r\n def train(self, n_iters, n_iters_per_epoch, stats_iters, ckpt_interval):\r\n # for save loss \r\n count=0 \r\n self.session.run(tf.global_variables_initializer())\r\n \r\n # Fixed GT samples - save\r\n fixed_x1,fixed_mask_1,_= next(self.train_iter1)\r\n fixed_x2,fixed_mask_2,_= next(self.train_iter2)\r\n fixed_aux1,fixed_GT1,_= next(self.train_iter3)\r\n fixed_aux2,fixed_GT2,_= next(self.train_iter4)\r\n\r\n fixed_x1= self.session.run(tf.constant(fixed_x1))\r\n fixed_mask_1= self.session.run(tf.constant(fixed_mask_1))\r\n\r\n #fixed_x1 = ((fixed_x1+1.)*(255.99/2)).astype('int32').reshape([-1] + self.image_shape)\r\n save_images(fixed_x1, os.path.join(self.dirs['samples'], 'samples_1_groundtruth.png'))\r\n ##save_images(fixed_mask_1, os.path.join(self.dirs['samples'], 'mask_1_groundtruth.png'))\r\n \r\n fixed_aux1= self.session.run(tf.constant(fixed_aux1))\r\n fixed_aux2= self.session.run(tf.constant(fixed_aux2))\r\n #fixed_aux1 = ((fixed_aux1+1.)*(255.99/2)).astype('int32').reshape([-1] + self.image_shape)\r\n #fixed_aux2 = ((fixed_aux2+1.)*(255.99/2)).astype('int32').reshape([-1] + self.image_shape)\r\n save_images(fixed_aux1, os.path.join(self.dirs['samples'], 'aux_1_groundtruth.png'))\r\n save_images(fixed_aux2, os.path.join(self.dirs['samples'], 'aux_2_groundtruth.png'))\r\n #\r\n start_iter = self.load()\r\n running_cost = 0.\r\n class_gt0, class_gt1,class_gt2,class_gt3,class_gt4,class_gt5, class_gt6, class_gt7, class_gt8,class_gt9,class_gt10 = self.generateClassificationLabel(self.batch_size)\r\n _gan_data=fixed_x1\r\n logs=open('loss_records.txt','w')\r\n for iteration in range(start_iter, n_iters):\r\n start_time = time.time()\r\n\r\n \r\n _data1,_mask1, _ = next(self.train_iter1)\r\n _aux_label, _, _ = next(self.train_iter2)\r\n _aux1,_gt1, _ = next(self.train_iter3)\r\n _aux2,_gt2, _ = next(self.train_iter4)\r\n\r\n _, cost = self.session.run((self.optimizer, self.loss),feed_dict={self.x1:_data1,self.aux_class_gt:_aux_label,self.aux1_mask:_mask1,self.aux1:_aux1,self.aux2:_aux2,self.aux_GT1:_gt1,self.aux_GT2:_gt2,self.is_training:True,self.class_gt0:class_gt0,self.class_gt1:class_gt1,self.class_gt2:class_gt2,self.class_gt3:class_gt3,\r\n self.class_gt4:class_gt4, self.class_gt5:class_gt5, self.class_gt6:class_gt6,self.class_gt7:class_gt7, self.class_gt8:class_gt8, self.class_gt9:class_gt9, self.class_gt10:class_gt10})\r\n running_cost += cost\r\n \r\n if iteration % n_iters_per_epoch == 1:\r\n print(\"Epoch: {0}\".format(iteration // n_iters_per_epoch))\r\n \r\n # Print avg stats and dev set stats\r\n if (iteration < start_iter + 4) or iteration % stats_iters == 0:\r\n t = time.time()\r\n dev_data1,dev_mask1, _ = next(self.dev_iter1)\r\n dev_aux1,dev_gt1, _ = next(self.dev_iter3)\r\n dev_aux2,dev_gt2, _ = next(self.dev_iter4)\r\n \r\n dev_loss,dev_rec_img_loss1,dev_rec_aux1_loss2,dev_rec_aux2_loss3,dev_rec_aux1_swap_loss4,dev_rec_aux2_swap_loss5,dev_rec_dual_loss6,class_loss,fuzzy_class,aux1_class_loss,aux2_class_loss,fuzzy_bg_class_loss,aux1_bg_class_loss,aux2_bg_class_loss= \\\r\n self.session.run([self.loss,self.rec_img_loss1,self.rec_aux1_loss2,self.rec_aux2_loss3,self.rec_aux1_swap_loss4,self.rec_aux2_swap_loss5,self.rec_dual_loss6,self.class_loss,self.fuzzy_class_loss,self.aux1_class_loss,self.aux2_class_loss,self.fuzzy_bg_class_loss,self.aux1_bg_class_loss,self.aux2_bg_class_loss],\r\n feed_dict={self.x1:dev_data1,self.aux1_mask:dev_mask1,self.aux1:dev_aux1,self.aux2:dev_aux2,self.aux_GT1:dev_gt1,self.aux_GT2:dev_gt2,self.is_training:False,\r\n self.class_gt0: class_gt0, self.class_gt1: class_gt1,self.class_gt2: class_gt2,self.class_gt3:class_gt3,self.aux_class_gt:_aux_label,self.class_gt4:class_gt4, self.class_gt5:class_gt5, self.class_gt6:class_gt6,self.class_gt7:class_gt7, self.class_gt8:class_gt8, self.class_gt9:class_gt9, self.class_gt10:class_gt10})\r\n \r\n n_samples = 1. if (iteration < start_iter + 4) else float(stats_iters)\r\n avg_cost = running_cost / n_samples\r\n running_cost = 0.\r\n print(\"Iteration:{0} \\t| Train cost:{1:.1f} \\t| Dev cost: {2:.1f}(img1_loss:{3:.1f},aux1_loss2:{4:.1f},aux2_loss3:{5:.1f},aux1_swap_loss:{6:.1f},aux2_swap_loss:{7:.1f},dual_swap_loss:{8:.1f},class loss:{9:.1f}(fuzzy_class:{10:.1f},aux1_class_loss:{11:.1f},aux2_class_loss:{12:.1f},fuzzy_bg_class_loss:{13:.1f},aux1_bg_class_loss:{14:.1f},aux2_bg_class_loss:{15:.1f}))\".\r\n format(iteration, avg_cost, dev_loss,dev_rec_img_loss1,dev_rec_aux1_loss2,dev_rec_aux2_loss3,dev_rec_aux1_swap_loss4,dev_rec_aux2_swap_loss5,dev_rec_dual_loss6,class_loss,fuzzy_class,aux1_class_loss,aux2_class_loss,fuzzy_bg_class_loss,aux1_bg_class_loss,aux2_bg_class_loss))\r\n logs.writelines(\"Iteration:{0} \\t| Train cost:{1:.1f} \\t| Dev cost: {2:.1f}(img1_loss:{3:.1f},aux1_loss2:{4:.1f},aux2_loss3:{5:.1f},aux1_swap_loss:{6:.1f},aux2_swap_loss:{7:.1f},dual_swap_loss:{8:.1f},class loss:{9:.1f}(fuzzy_class:{10:.1f},aux1_class_loss:{11:.1f},aux2_class_loss:{12:.1f},fuzzy_bg_class_loss:{13:.1f},aux1_bg_class_loss:{14:.1f},aux2_bg_class_loss:{15:.1f}))\\n\".\r\n format(iteration, avg_cost, dev_loss,dev_rec_img_loss1,dev_rec_aux1_loss2,dev_rec_aux2_loss3,dev_rec_aux1_swap_loss4,dev_rec_aux2_swap_loss5,dev_rec_dual_loss6,class_loss,fuzzy_class,aux1_class_loss,aux2_class_loss,fuzzy_bg_class_loss,aux1_bg_class_loss,aux2_bg_class_loss))\r\n\r\n #print(avg_cost)\r\n #print(dev_loss)\r\n #print(\"Iteration:{0} \\t| Train cost:{1:.1f} \\t| Dev cost: {2:.1f}\".format(iteration, avg_cost, dev_loss))\r\n \r\n count=count+1 \r\n if self.vis_reconst:\r\n self.visualise_reconstruction(fixed_x1,fixed_aux1,fixed_aux2,iteration)\r\n #self.visualise_reconstruction(img_zero,fixed_mk1,iteration)\r\n \r\n if np.any(np.isnan(avg_cost)):\r\n raise ValueError(\"NaN detected!\") \r\n # save checkpoint\r\n if (iteration > start_iter) and iteration % (ckpt_interval) == 0:\r\n self.saver.save(self.session, os.path.join(self.dirs['ckpt'], self.exp_name), global_step=iteration) \r\n _gan_data=_data1\r\n logs.close()\r\n # for save loss\r\n #np.save('logArray.npy',logArray) \r\n\r\n def reconstruct(self, X1, aux1,aux2, is_training=False):\r\n \"\"\" Reconstruct data. \"\"\"\r\n return self.session.run([self.x1_out,self.mix_head_out,self.aux1_mix_head_out], \r\n feed_dict={self.x1: X1,self.aux1:aux1,self.aux2:aux2,self.is_training: is_training})\r\n \r\n\r\n def visualise_reconstruction(self, X1, aux1,aux2,iteration):\r\n X_out1,mix_head_out,aux1_mix_head_out= self.reconstruct(X1, aux1,aux2)\r\n # print(X_out1.shape)\r\n X1 = ((X_out1+1.)*(255.99/2)).astype('int32').reshape([-1] + self.image_shape)\r\n mix_head_out = ((mix_head_out+1.)*(255.99/2)).astype('int32').reshape([-1] + self.image_shape)\r\n aux1_mix_head_out = ((aux1_mix_head_out+1.)*(255.99/2)).astype('int32').reshape([-1] + self.image_shape)\r\n save_images(X1, os.path.join(self.dirs['samples'], str(iteration)+'samples_1_rec.png'))\r\n save_images(mix_head_out, os.path.join(self.dirs['samples'], str(iteration)+'X1bg_aux1head.png'))\r\n save_images(aux1_mix_head_out, os.path.join(self.dirs['samples'], str(iteration)+'X1head_aux1bg.png'))\r\n\r\n def generateClassificationLabel(self, batch_size):\r\n # ==============get mask==============\r\n class_num = 11\r\n class_gt1 = np.zeros((batch_size, class_num))\r\n class_gt2 = np.zeros((batch_size, class_num))\r\n class_gt3 = np.zeros((batch_size, class_num))\r\n class_gt4 = np.zeros((batch_size, class_num))\r\n class_gt5 = np.zeros((batch_size, class_num))\r\n class_gt6 = np.zeros((batch_size, class_num))\r\n class_gt7 = np.zeros((batch_size, class_num))\r\n class_gt8 = np.zeros((batch_size, class_num))\r\n class_gt9 = np.zeros((batch_size, class_num))\r\n class_gt10 = np.zeros((batch_size, class_num))\r\n class_gt11 = np.zeros((batch_size, class_num))\r\n\r\n for i in range(batch_size):\r\n class_gt1[i, 0] = 1\r\n class_gt2[i, 1] = 1\r\n class_gt3[i, 2] = 1\r\n class_gt4[i, 3] = 1\r\n class_gt5[i, 4] = 1\r\n class_gt6[i, 5] = 1\r\n class_gt7[i, 6] = 1\r\n class_gt8[i, 7] = 1\r\n class_gt9[i, 8] = 1\r\n class_gt10[i, 9] = 1\r\n class_gt11[i, 10] = 1\r\n\r\n\r\n return class_gt1, class_gt2, class_gt3, class_gt4,class_gt5, class_gt6, class_gt7, class_gt8,class_gt9, class_gt10,class_gt11\r\n def getCodesAndImgs(self, pathForSave, X1, k, is_training=False):\r\n z1, X_r0 = self.session.run([self.z1, self.x1_out],\r\n feed_dict={self.x1: X1, self.is_training: is_training})\r\n ImageNorm0_1 = ((X_r0 + 1.) * (1.00 / 2)).astype('double').reshape(\r\n [-1, self.image_shape[1], self.image_shape[2], self.image_shape[0]])\r\n # for visual the first result to valide it effectiveness\r\n if k == 1:\r\n X_save = ((X_r0 + 1.) * (255.99 / 2)).astype('int32').reshape([-1] + self.image_shape)\r\n save_images(X_save, os.path.join(pathForSave, 'iter' + str(k) + '_samples_reconstructed.png'))\r\n return z1, ImageNorm0_1\r\n",
"import os, sys\r\nimport time\r\nimport re\r\nimport numpy as np\r\nimport tensorflow as tf\r\n\r\nfrom lib.models.save_images import save_images\r\nfrom lib.models.distributions import Bernoulli, Gaussian, Product\r\nfrom lib.models.nets_32x32_small import NetsRetreiver, NetsRetreiverWithClassifier\r\n\r\nTINY = 1e-8\r\nSEED = 123\r\nch=3\r\nCRITIC_ITERS = 5 # For WGAN and WGAN-GP, number of critic iters per gen iter\r\n\r\nclass AE(object):\r\n def __init__(self, session, arch,lr,alpha,beta,latent_dim,latent_num,class_net_unit_num,output_dim, batch_size, image_shape, exp_name, dirs,\r\n vis_reconst):\r\n \"\"\"\r\n :type output_dist: Distribution\r\n :type z_dist: Gaussian\r\n \"\"\"\r\n self.session = session\r\n self.arch = arch\r\n self.lr=lr\r\n self.alpha=alpha\r\n self.beta=beta\r\n self.latent_dim=latent_dim\r\n self.latent_num=latent_num\r\n self.class_net_unit_num=class_net_unit_num\r\n self.output_dim=output_dim\r\n self.batch_size = batch_size\r\n self.image_shape = image_shape\r\n self.exp_name = exp_name\r\n self.dirs = dirs\r\n self.vis_reconst = vis_reconst\r\n \r\n self.__build_graph()\r\n\r\n def __build_graph(self):\r\n tf.set_random_seed(SEED)\r\n np.random.seed(SEED)\r\n self.is_training = tf.placeholder(tf.bool)\r\n self.x1 = tf.placeholder(tf.float32, shape=[None] + list(self.image_shape))\r\n\r\n # Normalize + reshape 'real' input data\r\n norm_x1 = 2*(tf.cast(self.x1, tf.float32)-.5)\r\n # norm_img_black=2*(tf.cast(self.img_black, tf.float32)-.5)\r\n # Set Encoder and Decoder archs\r\n self.Encoder, self.Decoder,self.Classifier,self.gan_discriminator = NetsRetreiverWithClassifier(self.arch) \r\n \r\n # Encode\r\n self.z1 = self.__Enc(norm_x1)\r\n # original stage\r\n # Decode\r\n self.x_out1 = self.__Dec(self.z1)\r\n\r\n # Loss and optimizer\r\n self.__prep_loss_optimizer(norm_x1)\r\n\r\n def __Enc(self, x):\r\n #resnet_encoder(name, inputs, n_channels, latent_dim, is_training, mode=None, nonlinearity=tf.nn.relu):\r\n z= self.Encoder('Encoder', x, self.image_shape[0], self.latent_dim,self.is_training)\r\n return z\r\n \r\n def __Dec(self, z):\r\n x_out_logit = self.Decoder('Decoder', z, self.image_shape[0], self.is_training)\r\n x_out = tf.tanh(x_out_logit)\r\n return x_out\r\n \r\n def __Classifier(self,z):\r\n x_out= self.Classifier('Classifier', z, self.class_net_unit_num,self.latent_num+1, self.is_training)\r\n x_out = tf.nn.softmax(x_out)\r\n return x_out\r\n \r\n def __prep_loss_optimizer(self,norm_x1):\r\n \r\n norm_x1= tf.reshape(norm_x1, [-1, self.output_dim])\r\n #[Loss1]img reconstruction loss\r\n reconstr_img_loss = tf.reduce_sum(tf.square(norm_x1 -self.x_out1), axis=1)\r\n #\r\n # # average over batch\r\n self.rec_loss=1.0*tf.reduce_mean(reconstr_img_loss)\r\n\r\n #self.loss=self.rec_loss+self.class_loss+self.rec_black_loss\r\n self.loss=self.rec_loss\r\n lr=self.lr\r\n self.optimizer = tf.train.AdamOptimizer(learning_rate=lr, beta1=0., beta2=0.9).minimize(self.loss) \r\n \r\n print('Learning rate=')\r\n print(lr)\r\n \r\n def load(self):\r\n #self.saver = tf.train.Saver()\r\n self.saver = tf.train.Saver(max_to_keep=3760)\r\n ckpt = tf.train.get_checkpoint_state(self.dirs['ckpt'])\r\n \r\n if ckpt and ckpt.model_checkpoint_path:\r\n ckpt_name = ckpt.model_checkpoint_path\r\n self.saver.restore(self.session, ckpt_name)\r\n print(\"Checkpoint restored: {0}\".format(ckpt_name))\r\n prev_step = int(next(re.finditer(\"(\\d+)(?!.*\\d)\",ckpt_name)).group(0))\r\n print('prev_step=')\r\n print(prev_step)\r\n \r\n else:\r\n print(\"Failed to find checkpoint.\")\r\n prev_step = 0\r\n sys.stdout.flush()\r\n return prev_step + 1\r\n\r\n def load_fixedNum(self,inter_num):\r\n #self.saver = tf.train.Saver()\r\n self.saver = tf.train.Saver(max_to_keep=3760)\r\n ckpt = tf.train.get_checkpoint_state(self.dirs['ckpt'])\r\n if ckpt and ckpt.model_checkpoint_path:\r\n ckpt_name = ckpt.model_checkpoint_path\r\n ckpt_name_prefix=ckpt_name.split('-')[0]\r\n ckpt_name_new=ckpt_name_prefix+'-'+str(inter_num)\r\n self.saver.restore(self.session, ckpt_name_new)\r\n print(\"Checkpoint restored: {0}\".format(ckpt_name_new))\r\n prev_step = int(next(re.finditer(\"(\\d+)(?!.*\\d)\",ckpt_name_new)).group(0))\r\n print('prev_step=')\r\n print(prev_step)\r\n else:\r\n print(\"Failed to find checkpoint.\")\r\n prev_step = 0\r\n sys.stdout.flush()\r\n return prev_step + 1\r\n \r\n def train(self, n_iters, n_iters_per_epoch, stats_iters, ckpt_interval):\r\n # for save loss\r\n count=0 \r\n self.session.run(tf.global_variables_initializer())\r\n \r\n # Fixed GT samples - save\r\n fixed_x1, fixed_mk1 ,_ = next(self.train_iter1)\r\n print(\"fixed_mk1=\")\r\n print(fixed_mk1[0:4])\r\n # print(fixed_label[0:4])\r\n # replace mask\r\n #unitLength=3 #(need to changed when has larger unitLength)\r\n unitLength=int(self.latent_dim/self.latent_num)\r\n # generate zero representation and black image and gts0\r\n img_zero,fixed_zero_mk,fixed_gts0=self.generateMaskZeroAndGts(self.batch_size,unitLength)\r\n #\r\n fixed_x1= self.session.run(tf.constant(fixed_x1))\r\n save_images(fixed_x1, os.path.join(self.dirs['samples'], 'samples_1_groundtruth.png'))\r\n #\r\n start_iter = self.load()\r\n running_cost = 0.\r\n \r\n _gan_data=fixed_x1\r\n logs=open('loss_records.txt','w')\r\n for iteration in range(start_iter, n_iters):\r\n start_time = time.time()\r\n\r\n _data1, _mask1,_ = next(self.train_iter1)\r\n\r\n _, cost = self.session.run((self.optimizer, self.loss),feed_dict={self.x1: _data1,self.is_training:True})\r\n running_cost += cost\r\n \r\n if iteration % n_iters_per_epoch == 1:\r\n print(\"Epoch: {0}\".format(iteration // n_iters_per_epoch))\r\n \r\n # Print avg stats and dev set stats\r\n if (iteration < start_iter + 4) or iteration % stats_iters == 0:\r\n t = time.time()\r\n dev_data1, dev_mask1, dev_label1= next(self.dev_iter1)\r\n \r\n #dev_cost,dev_rec_loss,dev_reset0_loss,vector_loss,rec_zero_loss,class_loss= self.session.run([self.loss,self.rec_loss,self.reset0_loss,self.vector_loss,self.rec_zero_loss,self.class_loss],feed_dict={self.x1: dev_data1, self.mask: dev_mask1, self.vec_one:vector_one,self.img_black:img_zero,self.mask_zero:fixed_zero_mk,self.class_gt1:class_gt1,self.class_gt2:class_gt2,self.class_gt3:class_gt3,self.class_gt4:class_gt4,self.class_gt4:class_gt4,self.is_training:False})\r\n dev_cost,dev_rec_loss= self.session.run([self.loss,self.rec_loss],feed_dict={self.x1: dev_data1,self.is_training:False})\r\n \r\n n_samples = 1. if (iteration < start_iter + 4) else float(stats_iters)\r\n avg_cost = running_cost / n_samples\r\n running_cost = 0.\r\n\r\n print(\"Iteration:{0} \\t| Train cost:{1:.1f} \\t| Dev cost: {2:.1f}(reconstr_loss:{3:.1f})\".format(iteration, avg_cost, dev_cost,dev_rec_loss))\r\n logs.writelines(\"Iteration:{0} \\t| Train cost:{1:.1f} \\t| Dev cost: {2:.1f}(reconstr_loss:{3:.1f})\\n\".format(\r\n iteration, avg_cost, dev_cost, dev_rec_loss))\r\n count=count+1 \r\n if self.vis_reconst:\r\n self.visulize_rec(fixed_x1,iteration)\r\n #self.visualise_reconstruction(img_zero,fixed_mk1,iteration)\r\n \r\n if np.any(np.isnan(avg_cost)):\r\n raise ValueError(\"NaN detected!\") \r\n # save checkpoint\r\n if (iteration > start_iter) and iteration % (ckpt_interval) == 0:\r\n self.saver.save(self.session, os.path.join(self.dirs['ckpt'], self.exp_name), global_step=iteration) \r\n _gan_data=_data1\r\n logs.close()\r\n\r\n def reconstruct(self, X1, mk1, is_training=False):\r\n \"\"\" Reconstruct data. \"\"\"\r\n return self.session.run([self.x_out1 ],\r\n feed_dict={self.x1: X1,self.mask: mk1, self.is_training: is_training})\r\n \r\n\r\n def visualise_reconstruction(self, X1,mk1,iteration):\r\n X_r1,X_r0= self.reconstruct(X1,mk1)\r\n #print(X_r0[3])\r\n X_r1 = ((X_r1+1.)*(255.99/2)).astype('int32').reshape([-1] + self.image_shape)\r\n X_r0 = ((X_r0+1.)*(255.99/2)).astype('int32').reshape([-1] + self.image_shape)\r\n save_images(X_r1, os.path.join(self.dirs['samples'], str(iteration)+'samples_reconstructed.png'))\r\n save_images(X_r0, os.path.join(self.dirs['samples'], str(iteration)+'reset0_reconstructed.png'))\r\n\r\n def visulize_rec(self,X1,iteration):\r\n X_r1=self.session.run(self.x_out1 ,feed_dict={self.x1: X1,self.is_training: False})\r\n #print(X_r0[3])\r\n X_r1 = ((X_r1+1.)*(255.99/2)).astype('int32').reshape([-1] + self.image_shape)\r\n save_images(X_r1, os.path.join(self.dirs['samples'], str(iteration)+'samples_reconstructed.png'))\r\n\r\n def encodeImg(self,pathForSave,X1, mk1,k, is_training=False): \r\n \r\n X_r1,X_r0=self.session.run([self.x_out1,self.x_out_r0],feed_dict={self.x1: X1,self.mask: mk1, self.is_training: is_training})\r\n X_r1 = ((X_r1+1.)*(255.99/2)).astype('int32').reshape([-1] + self.image_shape)\r\n X_r0 = ((X_r0+1.)*(255.99/2)).astype('int32').reshape([-1] + self.image_shape)\r\n save_images(X_r1, os.path.join(pathForSave, 'iter'+str(k)+'_samples_reconstructed.png'))\r\n save_images(X_r0, os.path.join(pathForSave, 'iter'+str(k)+'_reset0_reconstructed.png'))\r\n \r\n def encode(self, X, is_training=False):\r\n \"\"\"Encode data, i.e. map it into latent space.\"\"\"\r\n code = self.session.run(self.z1, feed_dict={self.x1: X, self.is_training: is_training})\r\n return code\r\n\r\n\r\n def generateMaskZeroAndGts(self,batch_size,unitLength):\r\n #==============get mask==============\r\n partNum=3\r\n w=32\r\n h=32\r\n maskArray=np.empty((batch_size,unitLength*partNum))\r\n labelArray=np.empty((batch_size,partNum+1))\r\n mask=np.zeros((unitLength*partNum))\r\n label0=np.zeros((partNum+1))\r\n label0[0]=1\r\n # reset value 0~64\r\n for i in range(0,batch_size):\r\n maskArray[i]=mask\r\n labelArray[i]=label0\r\n\r\n imgArray= np.zeros((batch_size,ch,w,h))*0.0\r\n\r\n return imgArray,maskArray,labelArray\r\n def getCodesAndImgs(self,pathForSave,X1,k, is_training=False):\r\n z1,X_r0=self.session.run([self.z1,self.x_out1],feed_dict={self.x1: X1,self.is_training: is_training})\r\n ImageNorm0_1 = ((X_r0+1.)*(1.00/2)).astype('double').reshape([-1,self.image_shape[1],self.image_shape[2],self.image_shape[0]])\r\n # for visual the first result to valide it effectiveness\r\n if k==1:\r\n X_save = ((X_r0+1.)*(255.99/2)).astype('int32').reshape([-1] + self.image_shape)\r\n save_images(X_save, os.path.join(pathForSave, 'iter'+str(k)+'_samples_reconstructed.png'))\r\n return z1,ImageNorm0_1\r\n\r\n def getVisualImgs(self, pathForSave, X1,X2,k, is_training=False):\r\n X_swap = self.session.run(self.x_swap,feed_dict={self.x1: X1,self.x2: X2, self.is_training: is_training})\r\n\r\n X_orig1_save = (X1 * 255.99).astype('int32').reshape([-1] + self.image_shape)\r\n X_orig2_save = (X2 * 255.99).astype('int32').reshape([-1] + self.image_shape)\r\n X_Swap_save = ((X_swap + 1.) * (255.99 / 2)).astype('int32').reshape([-1] + self.image_shape)\r\n save_images(X_orig1_save, os.path.join(pathForSave, 'iter' + str(k) + '_orig_img.png'))\r\n save_images(X_orig2_save, os.path.join(pathForSave, 'iter' + str(k) + '_orig_swap.png'))\r\n save_images(X_Swap_save, os.path.join(pathForSave, 'iter' + str(k) + '_swap_img.png'))\r\n",
"import os\r\nimport errno\r\nimport numpy as np\r\nimport tensorflow as tf\r\nfrom operator import mul\r\nfrom functools import reduce\r\nimport sys\r\nsys.path.append(\"../../\")\r\n\r\n\r\nfrom model import DIAE\r\nfrom lib.models.distributions import Gaussian\r\nfrom lib.utils import init_directories, create_directories\r\n#from lib.models.data_managers_diae import TeapotsDataManager\r\nfrom lib.models.data_managers_dualdiae import TeapotsDataManager\r\nfrom lib.models.data_managers_ae import ShapesDataManager\r\n\r\n\r\nflags = tf.app.flags\r\nflags.DEFINE_integer(\"No\",19, \"The No of the test\")\r\nflags.DEFINE_integer(\"epochs\",50, \"Number of epochs to train [25]\")\r\nflags.DEFINE_integer(\"stats_interval\", 1, \"Print/log stats every [stats_interval] epochs. [1.0]\")\r\nflags.DEFINE_integer(\"ckpt_interval\", 1, \"Save checkpoint every [ckpt_interval] epochs. [10]\")\r\nflags.DEFINE_integer(\"latent_dim\", 2*50, \"Number of latent variables [10]\")\r\nflags.DEFINE_integer(\"latent_num\", 2, \"Number of latent part\")\r\nflags.DEFINE_integer(\"class_net_unit_num\", 9, \"Number of neuro cell\")\r\n#@flags.DEFINE_float(\"beta\", 1., \"D_KL term weighting [1.]\")\r\nflags.DEFINE_integer(\"batch_size\", 64, \"The size of training batches [64]\")\r\nflags.DEFINE_string(\"image_shape\", \"(3,32,32)\", \"Shape of inputs images [(1,32,32)]\")\r\nflags.DEFINE_integer(\"image_wh\", 32, \"Shape of inputs images 64*64\")\r\nflags.DEFINE_string(\"exp_name\", None, \"The name of experiment [None]\")\r\nflags.DEFINE_string(\"arch\", \"resnet\", \"The desired arch: low_cap, high_cap, resnet. [resnet]\")\r\nflags.DEFINE_integer(\"alpha\", 0, \"alpha value vector base\")\r\nflags.DEFINE_float(\"beta\",100, \"beta value reset 000\")\r\nflags.DEFINE_float(\"ratio\", 0.4, \"ratio value\")\r\nflags.DEFINE_float(\"lr\", 0.0005, \"ratio value\")\r\nflags.DEFINE_string(\"output_dir\", \"./\", \"Output directory for checkpoints, samples, etc. [.]\")\r\nflags.DEFINE_string(\"data_dir\", None, \"Data directory [None]\")\r\nflags.DEFINE_string(\"file_ext\", \".npz\", \"Image filename extension [.jpeg]\")\r\nflags.DEFINE_boolean(\"gaps\", False, \"Create gaps in data to faciliate zero-shot inference [False]\")\r\nflags.DEFINE_boolean(\"train\", True, \"Train [True]\")\r\nflags.DEFINE_boolean(\"save_codes\", True, \"Save latent representation or code for all data samples [False]\")\r\nflags.DEFINE_boolean(\"visualize_reconstruct\", True, \"True for visualizing, False for nothing [False]\")\r\nflags.DEFINE_boolean(\"visualize_disentangle\", False, \"True for visualizing, False for nothing [False]\")\r\nflags.DEFINE_integer(\"n_disentangle_samples\", 10, \"The number of evenly spaced samples in latent space \\\r\n over the interval [-3, 3] [64]\")\r\nFLAGS = flags.FLAGS\r\n\r\ndef main(_):\r\n if FLAGS.exp_name is None:\r\n FLAGS.exp_name = \"reconstrued_results_unitLength\"+str(int(FLAGS.latent_dim/FLAGS.latent_num))\r\n image_shape = [int(i) for i in FLAGS.image_shape.strip('()[]{}').split(',')]\r\n dirs = init_directories(FLAGS.exp_name, FLAGS.output_dir)\r\n dirs['data'] = '../../npz_datas' if FLAGS.data_dir is None else FLAGS.data_dir\r\n dirs['codes'] = os.path.join(dirs['data'], 'codes/')\r\n create_directories(dirs, FLAGS.train, FLAGS.save_codes)\r\n \r\n output_dim = reduce(mul, image_shape, 1)\r\n \r\n run_config = tf.ConfigProto(allow_soft_placement=True)\r\n run_config.gpu_options.allow_growth=True\r\n run_config.gpu_options.per_process_gpu_memory_fraction=0.9\r\n sess = tf.Session(config=run_config)\r\n\r\n diae = DIAE(\r\n session=sess,\r\n arch=FLAGS.arch,\r\n lr=FLAGS.lr,\r\n alpha=FLAGS.alpha,\r\n beta=FLAGS.beta,\r\n latent_dim=FLAGS.latent_dim,\r\n latent_num=FLAGS.latent_num,\r\n class_net_unit_num=FLAGS.class_net_unit_num,\r\n output_dim=output_dim,\r\n batch_size=FLAGS.batch_size,\r\n image_shape=image_shape,\r\n exp_name=FLAGS.exp_name,\r\n dirs=dirs,\r\n vis_reconst=FLAGS.visualize_reconstruct,\r\n )\r\n\r\n \r\n if FLAGS.save_codes:\r\n sampleNum =3200 \r\n dataVisualName='SVHN10_img_N3200x32x32x3_testWithLabel_forMetrics'\r\n data_manager = ShapesDataManager(dirs['data'],\r\n dataVisualName, FLAGS.batch_size, \r\n image_shape, shuffle=False,file_ext=FLAGS.file_ext, train_fract=1.0,inf=True)\r\n \r\n #data_manager.set_divisor_batch_size()\r\n\r\n diae.train_iter, diae.dev_iter, diae.test_iter= data_manager.get_iterators()\r\n\r\n diae.session.run(tf.global_variables_initializer())\r\n #saved_step = ae.load()\r\n saved_step = diae.load_fixedNum(6500)\r\n assert saved_step > 1, \"A trained model is needed to encode the data!\"\r\n \r\n pathForSave='ValidateEncodedImgs'\r\n if not os.path.exists(pathForSave):\r\n os.mkdir(pathForSave)\r\n\r\n \r\n codes = []\r\n images=[]\r\n for batch_num in range(int(sampleNum/FLAGS.batch_size)):\r\n img_batch, _mask1, _ = next(diae.train_iter)\r\n #code = ae.encode(img_batch) #[batch_size, reg_latent_dim]\r\n code,image=diae.getCodesAndImgs(pathForSave,img_batch,batch_num)\r\n codes.append(code)\r\n images.append(image)\r\n if batch_num < 5 or batch_num % 10 == 0:\r\n print((\"Batch number {0}\".format(batch_num)))\r\n \r\n codes = np.vstack(codes)\r\n images = np.vstack(images)\r\n codes_name='CIFAR3_codesAndImgForMetricsCal'\r\n filename = os.path.join(pathForSave, \"codes_\" + codes_name)\r\n #np.save(filename, codes)\r\n np.savez(filename+'.npz',imagesNorm0_1=images,codes=codes)\r\n\r\n print((\"Images and Codes saved to: {0}\".format(filename)))\r\n \r\n\r\n\r\nif __name__ == '__main__':\r\n tf.app.run()\r\n",
"import os\r\nimport errno\r\nimport tensorflow as tf\r\nfrom operator import mul\r\nfrom functools import reduce\r\nimport sys\r\nsys.path.append(\"../../\")\r\n\r\n\r\n#from model import AE\r\nfrom model2input import AE2input\r\nfrom lib.utils import init_directories, create_directories\r\n#from lib.models.data_managers_ae import ShapesDataManager\r\nfrom lib.models.data_managers_diae import TeapotsDataManager\r\n\r\nflags = tf.app.flags\r\nflags.DEFINE_integer(\"No\",19, \"The No of the test\")\r\nflags.DEFINE_integer(\"epochs\",50, \"Number of epochs to train [25]\")\r\nflags.DEFINE_integer(\"stats_interval\", 1, \"Print/log stats every [stats_interval] epochs. [1.0]\")\r\nflags.DEFINE_integer(\"ckpt_interval\", 1, \"Save checkpoint every [ckpt_interval] epochs. [10]\")\r\nflags.DEFINE_integer(\"latent_dim\", 2*50, \"Number of latent variables [10]\")\r\nflags.DEFINE_integer(\"latent_num\", 2, \"Number of latent part\")\r\nflags.DEFINE_integer(\"class_net_unit_num\", 9, \"Number of neuro cell\")\r\nflags.DEFINE_integer(\"batch_size\", 64, \"The size of training batches [64]\")\r\nflags.DEFINE_string(\"image_shape\", \"(3,32,32)\", \"Shape of inputs images [(1,32,32)]\")\r\nflags.DEFINE_integer(\"image_wh\", 32, \"Shape of inputs images 64*64\")\r\nflags.DEFINE_string(\"exp_name\", None, \"The name of experiment [None]\")\r\nflags.DEFINE_string(\"arch\", \"resnet\", \"The desired arch: low_cap, high_cap, resnet. [resnet]\")\r\nflags.DEFINE_integer(\"alpha\", 0, \"alpha value vector base\")\r\nflags.DEFINE_float(\"beta\",100, \"beta value reset 000\")\r\nflags.DEFINE_float(\"lr\", 0.0005, \"ratio value\")\r\nflags.DEFINE_string(\"output_dir\", \"./\", \"Output directory for checkpoints, samples, etc. [.]\")\r\nflags.DEFINE_string(\"data_dir\", None, \"Data directory [None]\")\r\nflags.DEFINE_string(\"file_ext\", \".npz\", \"Image filename extension [.jpeg]\")\r\nflags.DEFINE_boolean(\"train\", True, \"Train [True]\")\r\nflags.DEFINE_boolean(\"save_codes\", True, \"Save latent representation or code for all data samples [False]\")\r\nflags.DEFINE_boolean(\"visualize_reconstruct\", True, \"True for visualizing, False for nothing [False]\")\r\nFLAGS = flags.FLAGS\r\n\r\ndef main(_):\r\n if FLAGS.exp_name is None:\r\n #FLAGS.exp_name = \"reconstrued_results\"\r\n FLAGS.exp_name = \"reconstrued_results_unitLength\"+str(int(FLAGS.latent_dim/FLAGS.latent_num))\r\n image_shape = [int(i) for i in FLAGS.image_shape.strip('()[]{}').split(',')]\r\n dirs = init_directories(FLAGS.exp_name, FLAGS.output_dir)\r\n dirs['data'] = '../../npz_datas' if FLAGS.data_dir is None else FLAGS.data_dir\r\n dirs['codes'] = os.path.join(dirs['data'], 'codes/')\r\n create_directories(dirs, FLAGS.train, FLAGS.save_codes)\r\n \r\n output_dim = reduce(mul, image_shape, 1)\r\n \r\n run_config = tf.ConfigProto(allow_soft_placement=True)\r\n run_config.gpu_options.allow_growth=True\r\n run_config.gpu_options.per_process_gpu_memory_fraction=0.9\r\n sess = tf.Session(config=run_config)\r\n\r\n ae2input = AE2input(\r\n session=sess,\r\n arch=FLAGS.arch,\r\n lr=FLAGS.lr,\r\n alpha=FLAGS.alpha,\r\n beta=FLAGS.beta,\r\n latent_dim=FLAGS.latent_dim,\r\n latent_num=FLAGS.latent_num,\r\n class_net_unit_num=FLAGS.class_net_unit_num,\r\n output_dim=output_dim,\r\n batch_size=FLAGS.batch_size,\r\n image_shape=image_shape,\r\n exp_name=FLAGS.exp_name,\r\n dirs=dirs,\r\n vis_reconst=FLAGS.visualize_reconstruct,\r\n )\r\n\r\n\r\n if FLAGS.visualize_reconstruct:\r\n sampleNum =3200 # 20x64 large batch, forward prop only\r\n dataVisualName1='SVHN10_img_N3200x32x32x3_testWithLabel_forVisual1'\r\n dataVisualName2='SVHN10_img_N3200x32x32x3_testWithLabel_forVisual2'\r\n \r\n data_manager = TeapotsDataManager(dirs['data'],\r\n dataVisualName1,dataVisualName2, FLAGS.batch_size, \r\n image_shape, shuffle=False,file_ext=FLAGS.file_ext, train_fract=0.8, \r\n inf=True,supervised=False) \r\n #data_manager.set_divisor_batch_size()\r\n\r\n #ae.train_iter, ae.dev_iter, ae.test_iter= data_manager.get_iterators()\r\n ae2input.train_iter1, ae2input.dev_iter1, ae2input.test_iter1,ae2input.train_iter2, ae2input.dev_iter2, ae2input.test_iter2= data_manager.get_iterators()\r\n \r\n ae2input.session.run(tf.global_variables_initializer())\r\n #saved_step = ae.load()\r\n saved_step = ae2input.load_fixedNum(7000)\r\n assert saved_step > 1, \"A trained model is needed to encode the data!\"\r\n \r\n pathForSave='VisualImgsResults'\r\n try:\r\n os.makedirs(pathForSave)\r\n except OSError as exc: # Python >2.5\r\n if exc.errno == errno.EEXIST and os.path.isdir(pathForSave):\r\n pass\r\n else:\r\n raise\r\n\r\n \r\n for batch_num in range(int(sampleNum/FLAGS.batch_size)):\r\n img_batch1, _mask1, _ = next(ae2input.train_iter1)\r\n img_batch2, _mask2, _ = next(ae2input.train_iter2)\r\n #code = ae.encode(img_batch) #[batch_size, reg_latent_dim]\r\n ae2input.getVisualImgs(pathForSave,img_batch1,img_batch2, batch_num)\r\n if batch_num < 5 or batch_num % 10 == 0:\r\n print((\"Batch number {0}\".format(batch_num)))\r\n \r\n print(\"Swapped images saved to Folder: VisualImgsResults\")\r\n\r\n\r\nif __name__ == '__main__':\r\n tf.app.run()\r\n"
] |
[
[
"tensorflow.concat",
"tensorflow.reduce_sum",
"tensorflow.cast",
"tensorflow.tanh",
"tensorflow.train.AdamOptimizer",
"tensorflow.square",
"tensorflow.train.Saver",
"numpy.zeros",
"numpy.isnan",
"tensorflow.placeholder",
"tensorflow.global_variables_initializer",
"tensorflow.set_random_seed",
"tensorflow.split",
"tensorflow.train.get_checkpoint_state",
"tensorflow.nn.softmax",
"tensorflow.constant",
"numpy.random.seed",
"tensorflow.reshape",
"tensorflow.log"
],
[
"tensorflow.train.get_checkpoint_state",
"tensorflow.nn.softmax",
"tensorflow.constant",
"numpy.random.seed",
"tensorflow.reduce_mean",
"numpy.isnan",
"tensorflow.reshape",
"tensorflow.cast",
"tensorflow.placeholder",
"tensorflow.global_variables_initializer",
"tensorflow.tanh",
"tensorflow.square",
"tensorflow.train.AdamOptimizer",
"tensorflow.set_random_seed",
"tensorflow.train.Saver",
"numpy.zeros",
"numpy.empty"
],
[
"numpy.savez",
"tensorflow.ConfigProto",
"tensorflow.global_variables_initializer",
"tensorflow.Session",
"numpy.vstack",
"tensorflow.app.run"
],
[
"tensorflow.ConfigProto",
"tensorflow.global_variables_initializer",
"tensorflow.Session",
"tensorflow.app.run"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
shafzhr/SimpleConvNet
|
[
"89b669a59099743f0e115526cbc156aa22f453c3"
] |
[
"CNN/utils/activations.py"
] |
[
"import numpy as np\nimport abc\n\n\nclass Activation(metaclass=abc.ABCMeta):\n \"\"\"\n Activation abstract class\n \"\"\"\n\n @abc.abstractmethod\n def apply(self, x, is_training):\n \"\"\"\n Applying the activation function over `x`\n \"\"\"\n pass\n\n @abc.abstractmethod\n def backprop(self, dA_prev):\n \"\"\"\n Back Propagation in an activation function\n \"\"\"\n pass\n\n\nclass ReLU(Activation):\n \"\"\"\n ReLU activation function\n \"\"\"\n\n def __init__(self):\n self.X = None\n\n def apply(self, x, is_training=True):\n \"\"\"\n Applying ReLU over `x`\n :param x: input (numpy array)\n :param is_training: a boolean indicating whether training or not\n \"\"\"\n if is_training:\n self.X = x.copy()\n x[x < 0] = 0\n return x\n\n def backprop(self, dA_prev):\n \"\"\"\n Back Propagation in ReLU\n :param dA_prev: derivative of the cost function with respect to the previous layer(when going backwards)\n :return: the derivative of the cost layer with respect to the current layer\n \"\"\"\n return dA_prev * np.where(self.X > 0, 1, 0)\n\n\nclass Softmax(Activation):\n \"\"\"\n Softmax activation\n \"\"\"\n\n def __init__(self):\n self.X = None\n\n def apply(self, x, is_training=True):\n \"\"\"\n Applying Softmax over `x`\n :param is_training: a boolean indicating whether training or not\n :param x: input (numpy array)\n \"\"\"\n if is_training:\n self.X = x.copy()\n shiftx = x - np.max(x, axis=1, keepdims=True)\n exps = np.exp(shiftx)\n probs = exps / np.sum(exps, axis=1, keepdims=True)\n return probs\n\n def backprop(self, dA_prev):\n \"\"\"\n Back Propagation in Softmax\n :param dA_prev: derivative of the cost function with respect to the previous layer(when going backwards)\n :return: the derivative of the cost layer with respect to the current layer\n \"\"\"\n return dA_prev\n\n\nACTIVATION_FUNCTIONS = {'relu': ReLU, 'softmax': Softmax}\n"
] |
[
[
"numpy.max",
"numpy.exp",
"numpy.where",
"numpy.sum"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Enigmatisms/NeRF
|
[
"870abd83c9679e0735284a1641ffc0d13f0cf1d4"
] |
[
"test/image_sampler_test.py"
] |
[
"#-*-coding:utf-8-*-\n\n\"\"\"\n @author Enigmatisms @date 2022.3.23\n Last testing module for image sampler\n\"\"\"\n\nimport torch\nimport numpy as np\nfrom time import time\nfrom nerf_helper import imageSampling\nfrom mpl_toolkits.mplot3d import axes3d\nimport matplotlib.pyplot as plt\nfrom instances import BLENDER_FOV, Rs, ts\nfrom torchvision import transforms\nimport sys\nsys.path.append(\"..\")\nfrom py.utils import fov2Focal\nfrom py.dataset import CustomDataSet\n\nPOINT_TO_SAMPLE = 16\nIMAGE_SIZE = 50\nNEAR_T, FAR_T = 2., 6.\nINITIAL_SKIP = 0\n\nif __name__ == \"__main__\":\n torch.set_default_tensor_type(torch.FloatTensor)\n # tf = np.concatenate((Rs[-1], ts[-1]), axis = -1)\n # tf = torch.from_numpy(tf).float().cuda()\n dataset = CustomDataSet(\"../../dataset/nerf_synthetic/%s/\"%(\"lego\"), transforms.ToTensor(), True, use_alpha = True)\n cam_fov_train, train_cam_tf, _ = dataset.get_dataset(to_cuda = True)\n focal = fov2Focal(cam_fov_train, IMAGE_SIZE)\n axis = plt.axes(projection='3d')\n colors = ('r', 'g', 'b', 'y', 'p')\n for k in range(4):\n output = torch.zeros(IMAGE_SIZE, IMAGE_SIZE, POINT_TO_SAMPLE, 6, dtype = torch.float32).cuda()\n lengths = torch.zeros(IMAGE_SIZE, IMAGE_SIZE, POINT_TO_SAMPLE, dtype = torch.float32).cuda()\n imageSampling(train_cam_tf[k], output, lengths, IMAGE_SIZE, IMAGE_SIZE, POINT_TO_SAMPLE, focal, NEAR_T, FAR_T)\n for i in range(IMAGE_SIZE):\n for j in range(IMAGE_SIZE):\n point_list = output[i, j].cpu().numpy()\n axis.plot3D(point_list[:, 0], point_list[:, 1], point_list[:, 2], c = colors[k], alpha = 0.7)\n # axis.scatter(point_list[:, 0], point_list[:, 1], point_list[:, 2], c = 'r', s = 2)\n axis.set_zlabel('Z') \n axis.set_ylabel('Y')\n axis.set_xlabel('X')\n plt.show()"
] |
[
[
"matplotlib.pyplot.axes",
"torch.set_default_tensor_type",
"matplotlib.pyplot.show",
"torch.zeros"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
mattiafrak/Processes-Predictions-with-MP-A-Priori-Knowledge
|
[
"7e1bb94bb2fc535972a351f543be4f0ad8475275"
] |
[
"src/train_cf.py"
] |
[
"\"\"\"\nthis script trains an LSTM model on one of the data files in the data folder of\nthis repository. the input file can be changed to another file from the data folder\nby changing its name in line 46.\n\nit is recommended to run this script on GPU, as recurrent networks are quite\ncomputationally intensive.\n\nAuthor: Niek Tax\n\"\"\"\n\nfrom __future__ import print_function, division\n\nimport copy\nimport csv\nimport os\nimport time\nfrom datetime import datetime\nfrom itertools import izip\n\nimport numpy as np\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau\nfrom keras.layers import Input, BatchNormalization, LeakyReLU, Dropout\nfrom keras.layers.core import Dense\nfrom keras.layers.recurrent import LSTM\nfrom keras.models import Model\nfrom keras.optimizers import Nadam\n\nfrom shared_variables import get_unicode_from_int\n\n\nclass TrainCF:\n def __init__(self):\n pass\n\n @staticmethod\n def _build_model(max_len, num_features, target_chars):\n print('Build model...')\n main_input = Input(shape=(max_len, num_features), name='main_input')\n processed = main_input\n\n processed = Dense(32)(processed)\n processed = BatchNormalization()(processed)\n processed = LeakyReLU()(processed)\n processed = Dropout(0.5)(processed)\n\n processed = LSTM(64, return_sequences=False, recurrent_dropout=0.5)(processed)\n\n processed = Dense(32)(processed)\n processed = BatchNormalization()(processed)\n processed = LeakyReLU()(processed)\n processed = Dropout(0.5)(processed)\n\n act_output = Dense(len(target_chars), activation='softmax', name='act_output')(processed)\n time_output = Dense(1, activation='sigmoid', name='time_output')(processed)\n\n model = Model(main_input, [act_output, time_output])\n\n model.compile(loss={'act_output': 'categorical_crossentropy',\n 'time_output': 'mse'},\n loss_weights=[1.0, 0.0],\n optimizer='adam')\n return model\n\n @staticmethod\n def _create_checkpoints_path(log_name, models_folder, fold):\n folder_path = 'output_files/' + models_folder + '/' + str(fold) + '/models/CF/' + log_name + '/'\n if not os.path.exists(folder_path):\n os.makedirs(folder_path)\n checkpoint_name = folder_path + 'model_{epoch:03d}-{val_loss:.3f}.h5'\n return checkpoint_name\n\n @staticmethod\n def _train_model(model, checkpoint_name, X, y_a, y_t):\n model_checkpoint = ModelCheckpoint(checkpoint_name, save_best_only=True)\n # lr_reducer = ReduceLROnPlateau(factor=0.5, patience=10, verbose=1)\n early_stopping = EarlyStopping(monitor='val_loss', patience=5)\n\n model.fit(X, {'act_output': y_a,\n 'time_output': y_t},\n validation_split=0.2,\n verbose=2,\n callbacks=[early_stopping, model_checkpoint],\n epochs=10)\n\n @staticmethod\n def _load_dataset(log_name):\n dataset = []\n current_case = []\n current_case_id = None\n current_case_start_time = None\n last_event_time = None\n\n csvfile = open('../data2/final_experiments/%s.csv' % log_name, 'r')\n csv_reader = csv.reader(csvfile, delimiter=',', quotechar='|')\n next(csv_reader, None)\n\n for row in csv_reader: # CaseID, ActivityID, Timestamp, ResourceID\n case_id = row[0]\n activity_id = int(row[1])\n timestamp = datetime.strptime(row[2], '%Y-%m-%d %H:%M:%S')\n resource_id = int(row[3])\n\n if case_id != current_case_id:\n if len(current_case) > 0:\n dataset.append(current_case)\n current_case = []\n current_case_id = case_id\n current_case_start_time = timestamp\n last_event_time = timestamp\n\n time_since_case_start = int((timestamp - current_case_start_time).total_seconds())\n time_since_last_event = int((timestamp - last_event_time).total_seconds())\n time_since_midnight = int(\n (timestamp - timestamp.replace(hour=0, minute=0, second=0, microsecond=0)).total_seconds())\n day_of_week = timestamp.weekday()\n\n current_case.append(\n (activity_id, time_since_case_start, time_since_last_event, time_since_midnight, day_of_week))\n\n print(len(dataset))\n \n @staticmethod\n def train(log_name, models_folder, folds):\n # TrainCF._load_dataset(log_name)\n\n lines = [] # list of all the activity sequences\n timeseqs = [] # time sequences (differences between two events)\n timeseqs2 = [] # time sequences (differences between the current and first)\n\n # helper variables\n last_case = ''\n line = '' # sequence of activities for one case\n first_line = True\n times = []\n times2 = []\n num_lines = 0\n case_start_time = None\n last_event_time = None\n\n csvfile = open('../data2/final_experiments/%s.csv' % log_name, 'r')\n csv_reader = csv.reader(csvfile, delimiter=',', quotechar='|')\n next(csv_reader, None) # skip the headers\n\n for row in csv_reader: # the rows are \"CaseID,ActivityID,CompleteTimestamp\"\n t = time.strptime(row[2], \"%Y-%m-%d %H:%M:%S\") # creates a datetime object from row[2]\n if row[0] != last_case: # 'last_case' is to save the last executed case for the loop\n case_start_time = t\n last_event_time = t\n last_case = row[0]\n if not first_line: # here we actually add the sequences to the lists\n lines.append(line)\n timeseqs.append(times)\n timeseqs2.append(times2)\n line = ''\n times = []\n times2 = []\n num_lines += 1\n line += get_unicode_from_int(row[1])\n time_since_last_event = datetime.fromtimestamp(time.mktime(t)) - datetime.fromtimestamp(\n time.mktime(last_event_time))\n time_since_case_start = datetime.fromtimestamp(time.mktime(t)) - datetime.fromtimestamp(\n time.mktime(case_start_time))\n time_diff = 86400 * time_since_last_event.days + time_since_last_event.seconds\n time_diff2 = 86400 * time_since_case_start.days + time_since_case_start.seconds\n times.append(time_diff)\n times2.append(time_diff2)\n last_event_time = t\n first_line = False\n\n # add last case\n lines.append(line)\n timeseqs.append(times)\n timeseqs2.append(times2)\n num_lines += 1\n\n divisor = 1.0 * np.max([item for sublist in timeseqs for item in sublist]) # average time between events\n print('divisor: {}'.format(divisor))\n divisor2 = 1.0 * np.max([item for sublist in timeseqs2 for item in sublist]) # average time between current and\n # first events\n print('divisor2: {}'.format(divisor2))\n\n # separate training data into 2(out of 3) parts\n elements_per_fold = int(round(num_lines / 3))\n\n many = 0\n for i in range(len(lines)):\n many = many + len(lines[i])\n\n print(\"average length of the trace: \", many / len(lines))\n print(\"number of traces: \", len(lines))\n\n fold1 = lines[:elements_per_fold]\n fold2 = lines[elements_per_fold:2 * elements_per_fold]\n lines = fold1 + fold2\n\n lines = map(lambda x: x + '!', lines) # put delimiter symbol\n maxlen = max(map(lambda x: len(x), lines)) # find maximum line size\n\n # next lines here to get all possible characters for events and annotate them with numbers\n chars = map(lambda x: set(x), lines) # remove duplicate activities from each separate case\n chars = list(set().union(*chars)) # creates a list of all the unique activities in the data set\n chars.sort() # sorts the chars in alphabetical order\n target_chars = copy.copy(chars)\n chars.remove('!')\n print('total chars: {}, target chars: {}'.format(len(chars), len(target_chars)))\n char_indices = dict((c, i) for i, c in enumerate(chars))\n target_char_indices = dict((c, i) for i, c in enumerate(target_chars))\n\n csvfile = open('../data2/final_experiments/%s.csv' % log_name, 'r')\n csv_reader = csv.reader(csvfile, delimiter=',', quotechar='|')\n next(csv_reader, None) # skip the headers\n last_case = ''\n line = ''\n first_line = True\n lines = []\n timeseqs = []\n timeseqs2 = []\n timeseqs3 = []\n timeseqs4 = []\n times = []\n times2 = []\n times3 = []\n times4 = []\n num_lines = 0\n case_start_time = None\n last_event_time = None\n for row in csv_reader:\n t = time.strptime(row[2], \"%Y-%m-%d %H:%M:%S\")\n # new case starts\n if row[0] != last_case:\n case_start_time = t\n last_event_time = t\n last_case = row[0]\n if not first_line:\n lines.append(line)\n timeseqs.append(times)\n timeseqs2.append(times2)\n timeseqs3.append(times3)\n timeseqs4.append(times4)\n line = ''\n times = []\n times2 = []\n times3 = []\n times4 = []\n num_lines += 1\n line += get_unicode_from_int(row[1])\n time_since_last_event = datetime.fromtimestamp(time.mktime(t)) - datetime.fromtimestamp(\n time.mktime(last_event_time))\n time_since_case_start = datetime.fromtimestamp(time.mktime(t)) - datetime.fromtimestamp(\n time.mktime(case_start_time))\n midnight = datetime.fromtimestamp(time.mktime(t)).replace(hour=0, minute=0, second=0, microsecond=0)\n timesincemidnight = datetime.fromtimestamp(time.mktime(t)) - midnight\n time_diff = 86400 * time_since_last_event.days + time_since_last_event.seconds\n time_diff2 = 86400 * time_since_case_start.days + time_since_case_start.seconds\n timediff3 = timesincemidnight.seconds # this leaves only time even occurred after midnight\n timediff4 = datetime.fromtimestamp(time.mktime(t)).weekday() # day of the week\n times.append(time_diff)\n times2.append(time_diff2)\n times3.append(timediff3)\n times4.append(timediff4)\n last_event_time = t\n first_line = False\n\n # add last case\n lines.append(line)\n timeseqs.append(times)\n timeseqs2.append(times2)\n timeseqs3.append(times3)\n timeseqs4.append(times4)\n num_lines += 1\n\n elements_per_fold = int(round(num_lines / 3))\n\n lines = lines[:-elements_per_fold]\n lines_t = timeseqs[:-elements_per_fold]\n lines_t2 = timeseqs2[:-elements_per_fold]\n lines_t3 = timeseqs3[:-elements_per_fold]\n lines_t4 = timeseqs4[:-elements_per_fold]\n\n step = 1\n sentences = []\n softness = 0\n next_chars = []\n lines = map(lambda x: x + '!', lines)\n\n sentences_t = []\n sentences_t2 = []\n sentences_t3 = []\n sentences_t4 = []\n next_chars_t = []\n next_chars_t2 = []\n next_chars_t3 = []\n next_chars_t4 = []\n for line, line_t, line_t2, line_t3, line_t4 in izip(lines, lines_t, lines_t2, lines_t3, lines_t4):\n for i in range(0, len(line), step):\n if i == 0:\n continue\n\n # we add iteratively, first symbol of the line, then two first, three...\n sentences.append(line[0: i])\n sentences_t.append(line_t[0:i])\n sentences_t2.append(line_t2[0:i])\n sentences_t3.append(line_t3[0:i])\n sentences_t4.append(line_t4[0:i])\n next_chars.append(line[i])\n if i == len(line) - 1: # special case to deal time of end character\n next_chars_t.append(0)\n next_chars_t2.append(0)\n next_chars_t3.append(0)\n next_chars_t4.append(0)\n else:\n next_chars_t.append(line_t[i])\n next_chars_t2.append(line_t2[i])\n next_chars_t3.append(line_t3[i])\n next_chars_t4.append(line_t4[i])\n print('nb sequences:', len(sentences))\n\n print('Vectorization...')\n num_features = len(chars) + 5\n print('num features: {}'.format(num_features))\n X = np.zeros((len(sentences), maxlen, num_features), dtype=np.float32)\n y_a = np.zeros((len(sentences), len(target_chars)), dtype=np.float32)\n y_t = np.zeros((len(sentences)), dtype=np.float32)\n for i, sentence in enumerate(sentences):\n leftpad = maxlen - len(sentence)\n next_t = next_chars_t[i]\n sentence_t = sentences_t[i]\n sentence_t2 = sentences_t2[i]\n sentence_t3 = sentences_t3[i]\n sentence_t4 = sentences_t4[i]\n for t, char in enumerate(sentence):\n # multiset_abstraction = Counter(sentence[:t+1])\n for c in chars:\n if c == char: # this will encode present events to the right places\n X[i, t + leftpad, char_indices[c]] = 1\n X[i, t + leftpad, len(chars)] = t + 1\n X[i, t + leftpad, len(chars) + 1] = sentence_t[t] / divisor\n X[i, t + leftpad, len(chars) + 2] = sentence_t2[t] / divisor2\n X[i, t + leftpad, len(chars) + 3] = sentence_t3[t] / 86400\n X[i, t + leftpad, len(chars) + 4] = sentence_t4[t] / 7\n for c in target_chars:\n if c == next_chars[i]:\n y_a[i, target_char_indices[c]] = 1 - softness\n else:\n y_a[i, target_char_indices[c]] = softness / (len(target_chars) - 1)\n y_t[i] = next_t / divisor\n\n for fold in range(folds):\n # model = build_model(max_length, num_features, max_activity_id)\n model = TrainCF._build_model(maxlen, num_features, target_chars)\n checkpoint_name = TrainCF._create_checkpoints_path(log_name, models_folder, fold)\n TrainCF._train_model(model, checkpoint_name, X, y_a, y_t)\n"
] |
[
[
"numpy.max"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
dlouk/DALI
|
[
"d2de8841123aaf7178b7e5f82908302345dfa586"
] |
[
"dali/lagrange1d.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Feb 12 21:09:10 2018\n\n@author: Dimitris Loukrezis\n\nUnivariate Lagrange and hierarchical polynomials.\n\"\"\"\n\nimport numpy as np\n\n\nclass Lagrange1d:\n \"\"\"Univariate Lagrange nodal basis polynomial\"\"\"\n def __init__(self, current_knot, knots):\n self.current_knot = current_knot\n self.knots = np.array(knots)\n self.other_knots = np.setdiff1d(knots, current_knot)\n # compute denominator once and re-use\n self.denoms_prod = (self.current_knot - self.other_knots).prod()\n\n def evaluate(self, non_grid_knots):\n \"\"\"Evaluate polynomial on specific non-grid knots\"\"\"\n non_grid_knots = np.array(non_grid_knots).flatten()\n L = map(lambda x: np.prod(x-self.other_knots)/self.denoms_prod,\n non_grid_knots)\n return L\n\n\nclass Hierarchical1d(Lagrange1d):\n \"\"\"Univariate Lagrange hierarchical basis polynomial\"\"\"\n def __init__(self, knots):\n self.knots = np.array(knots)\n self.current_knot = self.knots[-1]\n self.other_knots = self.knots[:-1]\n # compute denominator once and re-use\n self.denoms_prod = (self.current_knot - self.other_knots).prod()\n\n\ndef lagrange1d_eval(current_knot, other_knots, non_grid_knots):\n \"\"\"Evaluate on NON_GRID_KNOTS a univariate Lagrange polynomial, defined\n for CURRENT_KNOT and OTHER_KNOTS\"\"\"\n other_knots = np.array(other_knots)\n non_grid_knots = np.array(non_grid_knots)\n denoms = current_knot - other_knots\n denoms_prod = denoms.prod()\n L = map(lambda x: np.prod(x - other_knots) / denoms_prod, non_grid_knots)\n return L"
] |
[
[
"numpy.prod",
"numpy.array",
"numpy.setdiff1d"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
MaxKelsen/qiskit-terra
|
[
"1ec2f5db5fea8df907cace3a0e0c92b6deac7fd3",
"1ec2f5db5fea8df907cace3a0e0c92b6deac7fd3"
] |
[
"qiskit/algorithms/minimum_eigen_solvers/vqe.py",
"test/python/algorithms/test_adapt_qaoa.py"
] |
[
"# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2018, 2020.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\"The Variational Quantum Eigensolver algorithm.\n\nSee https://arxiv.org/abs/1304.3061\n\"\"\"\n\nfrom typing import Optional, List, Callable, Union, Dict, Tuple\nimport logging\nimport warnings\nfrom time import time\nimport numpy as np\n\nfrom qiskit.circuit import QuantumCircuit, Parameter\nfrom qiskit.circuit.library import RealAmplitudes\nfrom qiskit.providers import BaseBackend\nfrom qiskit.providers import Backend\nfrom qiskit.opflow import (\n OperatorBase,\n ExpectationBase,\n ExpectationFactory,\n StateFn,\n CircuitStateFn,\n ListOp,\n CircuitSampler,\n PauliSumOp,\n)\nfrom qiskit.opflow.gradients import GradientBase\nfrom qiskit.utils.validation import validate_min\nfrom qiskit.utils.backend_utils import is_aer_provider\nfrom qiskit.utils.deprecation import deprecate_function\nfrom qiskit.utils import QuantumInstance, algorithm_globals\nfrom ..optimizers import Optimizer, SLSQP\nfrom ..variational_algorithm import VariationalAlgorithm, VariationalResult\nfrom .minimum_eigen_solver import MinimumEigensolver, MinimumEigensolverResult, ListOrDict\nfrom ..exceptions import AlgorithmError\n\nlogger = logging.getLogger(__name__)\n\n\nclass VQE(VariationalAlgorithm, MinimumEigensolver):\n r\"\"\"The Variational Quantum Eigensolver algorithm.\n\n `VQE <https://arxiv.org/abs/1304.3061>`__ is a quantum algorithm that uses a\n variational technique to find\n the minimum eigenvalue of the Hamiltonian :math:`H` of a given system.\n\n An instance of VQE requires defining two algorithmic sub-components:\n a trial state (a.k.a. ansatz) which is a :class:`QuantumCircuit`, and one of the classical\n :mod:`~qiskit.algorithms.optimizers`. The ansatz is varied, via its set of parameters, by the\n optimizer, such that it works towards a state, as determined by the parameters applied to the\n ansatz, that will result in the minimum expectation value being measured of the input operator\n (Hamiltonian).\n\n An optional array of parameter values, via the *initial_point*, may be provided as the\n starting point for the search of the minimum eigenvalue. This feature is particularly useful\n such as when there are reasons to believe that the solution point is close to a particular\n point. As an example, when building the dissociation profile of a molecule,\n it is likely that using the previous computed optimal solution as the starting\n initial point for the next interatomic distance is going to reduce the number of iterations\n necessary for the variational algorithm to converge. It provides an\n `initial point tutorial <https://github.com/Qiskit/qiskit-tutorials-community/blob/master\n /chemistry/h2_vqe_initial_point.ipynb>`__ detailing this use case.\n\n The length of the *initial_point* list value must match the number of the parameters\n expected by the ansatz being used. If the *initial_point* is left at the default\n of ``None``, then VQE will look to the ansatz for a preferred value, based on its\n given initial state. If the ansatz returns ``None``,\n then a random point will be generated within the parameter bounds set, as per above.\n If the ansatz provides ``None`` as the lower bound, then VQE\n will default it to :math:`-2\\pi`; similarly, if the ansatz returns ``None``\n as the upper bound, the default value will be :math:`2\\pi`.\n\n \"\"\"\n\n def __init__(\n self,\n ansatz: Optional[QuantumCircuit] = None,\n optimizer: Optional[Optimizer] = None,\n initial_point: Optional[np.ndarray] = None,\n gradient: Optional[Union[GradientBase, Callable]] = None,\n expectation: Optional[ExpectationBase] = None,\n include_custom: bool = False,\n max_evals_grouped: int = 1,\n callback: Optional[Callable[[int, np.ndarray, float, float], None]] = None,\n quantum_instance: Optional[Union[QuantumInstance, BaseBackend, Backend]] = None,\n ) -> None:\n \"\"\"\n\n Args:\n ansatz: A parameterized circuit used as Ansatz for the wave function.\n optimizer: A classical optimizer.\n initial_point: An optional initial point (i.e. initial parameter values)\n for the optimizer. If ``None`` then VQE will look to the ansatz for a preferred\n point and if not will simply compute a random one.\n gradient: An optional gradient function or operator for optimizer.\n expectation: The Expectation converter for taking the average value of the\n Observable over the ansatz state function. When ``None`` (the default) an\n :class:`~qiskit.opflow.expectations.ExpectationFactory` is used to select\n an appropriate expectation based on the operator and backend. When using Aer\n qasm_simulator backend, with paulis, it is however much faster to leverage custom\n Aer function for the computation but, although VQE performs much faster\n with it, the outcome is ideal, with no shot noise, like using a state vector\n simulator. If you are just looking for the quickest performance when choosing Aer\n qasm_simulator and the lack of shot noise is not an issue then set `include_custom`\n parameter here to ``True`` (defaults to ``False``).\n include_custom: When `expectation` parameter here is None setting this to ``True`` will\n allow the factory to include the custom Aer pauli expectation.\n max_evals_grouped: Max number of evaluations performed simultaneously. Signals the\n given optimizer that more than one set of parameters can be supplied so that\n potentially the expectation values can be computed in parallel. Typically this is\n possible when a finite difference gradient is used by the optimizer such that\n multiple points to compute the gradient can be passed and if computed in parallel\n improve overall execution time. Deprecated if a gradient operator or function is\n given.\n callback: a callback that can access the intermediate data during the optimization.\n Four parameter values are passed to the callback as follows during each evaluation\n by the optimizer for its current set of parameters as it works towards the minimum.\n These are: the evaluation count, the optimizer parameters for the\n ansatz, the evaluated mean and the evaluated standard deviation.`\n quantum_instance: Quantum Instance or Backend\n\n \"\"\"\n validate_min(\"max_evals_grouped\", max_evals_grouped, 1)\n\n super().__init__()\n\n self._max_evals_grouped = max_evals_grouped\n self._circuit_sampler = None # type: Optional[CircuitSampler]\n self._expectation = None\n self.expectation = expectation\n self._include_custom = include_custom\n\n # set ansatz -- still supporting pre 0.18.0 sorting\n self._ansatz_params = None\n self._ansatz = None\n self.ansatz = ansatz\n\n self._optimizer = None\n self.optimizer = optimizer\n\n self._initial_point = None\n self.initial_point = initial_point\n self._gradient = None\n self.gradient = gradient\n self._quantum_instance = None\n\n if quantum_instance is not None:\n self.quantum_instance = quantum_instance\n\n self._eval_time = None\n self._eval_count = 0\n self._callback = None\n self.callback = callback\n\n logger.info(self.print_settings())\n\n # TODO remove this once the stateful methods are deleted\n self._ret = None\n\n @property\n def ansatz(self) -> QuantumCircuit:\n \"\"\"Returns the ansatz.\"\"\"\n return self._ansatz\n\n @ansatz.setter\n def ansatz(self, ansatz: Optional[QuantumCircuit]):\n \"\"\"Sets the ansatz.\n\n Args:\n ansatz: The parameterized circuit used as an ansatz.\n If None is passed, RealAmplitudes is used by default.\n\n \"\"\"\n if ansatz is None:\n ansatz = RealAmplitudes()\n\n self._ansatz = ansatz\n self._ansatz_params = list(ansatz.parameters)\n\n @property\n def gradient(self) -> Optional[Union[GradientBase, Callable]]:\n \"\"\"Returns the gradient.\"\"\"\n return self._gradient\n\n @gradient.setter\n def gradient(self, gradient: Optional[Union[GradientBase, Callable]]):\n \"\"\"Sets the gradient.\"\"\"\n self._gradient = gradient\n\n @property\n def quantum_instance(self) -> Optional[QuantumInstance]:\n \"\"\"Returns quantum instance.\"\"\"\n return self._quantum_instance\n\n @quantum_instance.setter\n def quantum_instance(\n self, quantum_instance: Union[QuantumInstance, BaseBackend, Backend]\n ) -> None:\n \"\"\"Sets quantum_instance\"\"\"\n if not isinstance(quantum_instance, QuantumInstance):\n quantum_instance = QuantumInstance(quantum_instance)\n\n self._quantum_instance = quantum_instance\n self._circuit_sampler = CircuitSampler(\n quantum_instance, param_qobj=is_aer_provider(quantum_instance.backend)\n )\n\n @property\n def initial_point(self) -> Optional[np.ndarray]:\n \"\"\"Returns initial point\"\"\"\n return self._initial_point\n\n @initial_point.setter\n def initial_point(self, initial_point: np.ndarray):\n \"\"\"Sets initial point\"\"\"\n self._initial_point = initial_point\n\n @property\n def max_evals_grouped(self) -> int:\n \"\"\"Returns max_evals_grouped\"\"\"\n return self._max_evals_grouped\n\n @max_evals_grouped.setter\n def max_evals_grouped(self, max_evals_grouped: int):\n \"\"\"Sets max_evals_grouped\"\"\"\n self._max_evals_grouped = max_evals_grouped\n self.optimizer.set_max_evals_grouped(max_evals_grouped)\n\n @property\n def include_custom(self) -> bool:\n \"\"\"Returns include_custom\"\"\"\n return self._include_custom\n\n @include_custom.setter\n def include_custom(self, include_custom: bool):\n \"\"\"Sets include_custom. If set to another value than the one that was previsously set,\n the expectation attribute is reset to None.\n \"\"\"\n if include_custom != self._include_custom:\n self._include_custom = include_custom\n self.expectation = None\n\n @property\n def callback(self) -> Optional[Callable[[int, np.ndarray, float, float], None]]:\n \"\"\"Returns callback\"\"\"\n return self._callback\n\n @callback.setter\n def callback(self, callback: Optional[Callable[[int, np.ndarray, float, float], None]]):\n \"\"\"Sets callback\"\"\"\n self._callback = callback\n\n @property\n def expectation(self) -> Optional[ExpectationBase]:\n \"\"\"The expectation value algorithm used to construct the expectation measurement from\n the observable.\"\"\"\n return self._expectation\n\n @expectation.setter\n def expectation(self, exp: Optional[ExpectationBase]) -> None:\n self._expectation = exp\n\n def _check_operator_ansatz(self, operator: OperatorBase):\n \"\"\"Check that the number of qubits of operator and ansatz match.\"\"\"\n if operator is not None and self.ansatz is not None:\n if operator.num_qubits != self.ansatz.num_qubits:\n # try to set the number of qubits on the ansatz, if possible\n try:\n self.ansatz.num_qubits = operator.num_qubits\n self._ansatz_params = sorted(self.ansatz.parameters, key=lambda p: p.name)\n except AttributeError as ex:\n raise AlgorithmError(\n \"The number of qubits of the ansatz does not match the \"\n \"operator, and the ansatz does not allow setting the \"\n \"number of qubits using `num_qubits`.\"\n ) from ex\n\n @property\n def optimizer(self) -> Optimizer:\n \"\"\"Returns optimizer\"\"\"\n return self._optimizer\n\n @optimizer.setter\n def optimizer(self, optimizer: Optional[Optimizer]):\n \"\"\"Sets the optimizer attribute.\n\n Args:\n optimizer: The optimizer to be used. If None is passed, SLSQP is used by default.\n\n \"\"\"\n if optimizer is None:\n optimizer = SLSQP()\n\n optimizer.set_max_evals_grouped(self.max_evals_grouped)\n self._optimizer = optimizer\n\n @property\n def setting(self):\n \"\"\"Prepare the setting of VQE as a string.\"\"\"\n ret = f\"Algorithm: {self.__class__.__name__}\\n\"\n params = \"\"\n for key, value in self.__dict__.items():\n if key[0] == \"_\":\n if \"initial_point\" in key and value is None:\n params += \"-- {}: {}\\n\".format(key[1:], \"Random seed\")\n else:\n params += f\"-- {key[1:]}: {value}\\n\"\n ret += f\"{params}\"\n return ret\n\n def print_settings(self):\n \"\"\"\n Preparing the setting of VQE into a string.\n\n Returns:\n str: the formatted setting of VQE\n \"\"\"\n ret = \"\\n\"\n ret += \"==================== Setting of {} ============================\\n\".format(\n self.__class__.__name__\n )\n ret += f\"{self.setting}\"\n ret += \"===============================================================\\n\"\n if self.ansatz is not None:\n ret += \"{}\".format(self.ansatz.draw(output=\"text\"))\n else:\n ret += \"ansatz has not been set\"\n ret += \"===============================================================\\n\"\n ret += f\"{self._optimizer.setting}\"\n ret += \"===============================================================\\n\"\n return ret\n\n def construct_expectation(\n self,\n parameter: Union[List[float], List[Parameter], np.ndarray],\n operator: OperatorBase,\n return_expectation: bool = False,\n ) -> Union[OperatorBase, Tuple[OperatorBase, ExpectationBase]]:\n r\"\"\"\n Generate the ansatz circuit and expectation value measurement, and return their\n runnable composition.\n\n Args:\n parameter: Parameters for the ansatz circuit.\n operator: Qubit operator of the Observable\n return_expectation: If True, return the ``ExpectationBase`` expectation converter used\n in the construction of the expectation value. Useful e.g. to compute the standard\n deviation of the expectation value.\n\n Returns:\n The Operator equalling the measurement of the ansatz :class:`StateFn` by the\n Observable's expectation :class:`StateFn`, and, optionally, the expectation converter.\n\n Raises:\n AlgorithmError: If no operator has been provided.\n AlgorithmError: If no expectation is passed and None could be inferred via the\n ExpectationFactory.\n \"\"\"\n if operator is None:\n raise AlgorithmError(\"The operator was never provided.\")\n\n self._check_operator_ansatz(operator)\n\n # if expectation was never created, try to create one\n if self.expectation is None:\n expectation = ExpectationFactory.build(\n operator=operator,\n backend=self.quantum_instance,\n include_custom=self._include_custom,\n )\n else:\n expectation = self.expectation\n\n param_dict = dict(zip(self._ansatz_params, parameter)) # type: Dict\n wave_function = self.ansatz.assign_parameters(param_dict)\n\n observable_meas = expectation.convert(StateFn(operator, is_measurement=True))\n ansatz_circuit_op = CircuitStateFn(wave_function)\n expect_op = observable_meas.compose(ansatz_circuit_op).reduce()\n\n if return_expectation:\n return expect_op, expectation\n\n return expect_op\n\n def construct_circuit(\n self,\n parameter: Union[List[float], List[Parameter], np.ndarray],\n operator: OperatorBase,\n ) -> List[QuantumCircuit]:\n \"\"\"Return the circuits used to compute the expectation value.\n\n Args:\n parameter: Parameters for the ansatz circuit.\n operator: Qubit operator of the Observable\n\n Returns:\n A list of the circuits used to compute the expectation value.\n \"\"\"\n expect_op = self.construct_expectation(parameter, operator).to_circuit_op()\n\n circuits = []\n\n # recursively extract circuits\n def extract_circuits(op):\n if isinstance(op, CircuitStateFn):\n circuits.append(op.primitive)\n elif isinstance(op, ListOp):\n for op_i in op.oplist:\n extract_circuits(op_i)\n\n extract_circuits(expect_op)\n\n return circuits\n\n @classmethod\n def supports_aux_operators(cls) -> bool:\n return True\n\n def _eval_aux_ops(\n self,\n parameters: np.ndarray,\n aux_operators: ListOrDict[OperatorBase],\n expectation: ExpectationBase,\n threshold: float = 1e-12,\n ) -> ListOrDict[Tuple[complex, complex]]:\n # Create new CircuitSampler to avoid breaking existing one's caches.\n sampler = CircuitSampler(self.quantum_instance)\n\n if isinstance(aux_operators, dict):\n list_op = ListOp(list(aux_operators.values()))\n else:\n list_op = ListOp(aux_operators)\n\n aux_op_expect = expectation.convert(\n StateFn(list_op, is_measurement=True).compose(\n CircuitStateFn(self.ansatz.bind_parameters(parameters))\n )\n )\n aux_op_expect_sampled = sampler.convert(aux_op_expect)\n\n # compute means\n values = np.real(aux_op_expect_sampled.eval())\n\n # compute standard deviations\n variances = np.real(expectation.compute_variance(aux_op_expect_sampled))\n if not isinstance(variances, np.ndarray) and variances == 0.0:\n # when `variances` is a single value equal to 0., our expectation value is exact and we\n # manually ensure the variances to be a list of the correct length\n variances = np.zeros(len(aux_operators), dtype=float)\n std_devs = np.sqrt(variances / self.quantum_instance.run_config.shots)\n\n # Discard values below threshold\n aux_op_means = values * (np.abs(values) > threshold)\n # zip means and standard deviations into tuples\n aux_op_results = zip(aux_op_means, std_devs)\n\n # Return None eigenvalues for None operators if aux_operators is a list.\n # None operators are already dropped in compute_minimum_eigenvalue if aux_operators is a dict.\n if isinstance(aux_operators, list):\n aux_operator_eigenvalues = [None] * len(aux_operators)\n key_value_iterator = enumerate(aux_op_results)\n else:\n aux_operator_eigenvalues = {}\n key_value_iterator = zip(aux_operators.keys(), aux_op_results)\n\n for key, value in key_value_iterator:\n if aux_operators[key] is not None:\n aux_operator_eigenvalues[key] = value\n\n return aux_operator_eigenvalues\n\n def compute_minimum_eigenvalue(\n self, operator: OperatorBase, aux_operators: Optional[ListOrDict[OperatorBase]] = None\n ) -> MinimumEigensolverResult:\n super().compute_minimum_eigenvalue(operator, aux_operators)\n\n if self.quantum_instance is None:\n raise AlgorithmError(\n \"A QuantumInstance or Backend must be supplied to run the quantum algorithm.\"\n )\n self.quantum_instance.circuit_summary = True\n\n # this sets the size of the ansatz, so it must be called before the initial point\n # validation\n self._check_operator_ansatz(operator)\n\n # set an expectation for this algorithm run (will be reset to None at the end)\n initial_point = _validate_initial_point(self.initial_point, self.ansatz)\n\n bounds = _validate_bounds(self.ansatz)\n # We need to handle the array entries being zero or Optional i.e. having value None\n if aux_operators:\n zero_op = PauliSumOp.from_list([(\"I\" * self.ansatz.num_qubits, 0)])\n\n # Convert the None and zero values when aux_operators is a list.\n # Drop None and convert zero values when aux_operators is a dict.\n if isinstance(aux_operators, list):\n key_op_iterator = enumerate(aux_operators)\n converted = [zero_op] * len(aux_operators)\n else:\n key_op_iterator = aux_operators.items()\n converted = {}\n for key, op in key_op_iterator:\n if op is not None:\n converted[key] = zero_op if op == 0 else op\n\n aux_operators = converted\n\n else:\n aux_operators = None\n\n # Convert the gradient operator into a callable function that is compatible with the\n # optimization routine.\n if isinstance(self._gradient, GradientBase):\n gradient = self._gradient.gradient_wrapper(\n ~StateFn(operator) @ StateFn(self._ansatz),\n bind_params=self._ansatz_params,\n backend=self._quantum_instance,\n )\n else:\n gradient = self._gradient\n\n self._eval_count = 0\n energy_evaluation, expectation = self.get_energy_evaluation(\n operator, return_expectation=True\n )\n\n start_time = time()\n\n # keep this until Optimizer.optimize is removed\n try:\n opt_result = self.optimizer.minimize(\n fun=energy_evaluation, x0=initial_point, jac=gradient, bounds=bounds\n )\n except AttributeError:\n # self.optimizer is an optimizer with the deprecated interface that uses\n # ``optimize`` instead of ``minimize```\n warnings.warn(\n \"Using an optimizer that is run with the ``optimize`` method is \"\n \"deprecated as of Qiskit Terra 0.19.0 and will be unsupported no \"\n \"sooner than 3 months after the release date. Instead use an optimizer \"\n \"providing ``minimize`` (see qiskit.algorithms.optimizers.Optimizer).\",\n DeprecationWarning,\n stacklevel=2,\n )\n\n opt_result = self.optimizer.optimize(\n len(initial_point), energy_evaluation, gradient, bounds, initial_point\n )\n\n eval_time = time() - start_time\n\n result = VQEResult()\n result.optimal_point = opt_result.x\n result.optimal_parameters = dict(zip(self._ansatz_params, opt_result.x))\n result.optimal_value = opt_result.fun\n result.cost_function_evals = opt_result.nfev\n result.optimizer_time = eval_time\n result.eigenvalue = opt_result.fun + 0j\n result.eigenstate = self._get_eigenstate(result.optimal_parameters)\n\n logger.info(\n \"Optimization complete in %s seconds.\\nFound opt_params %s in %s evals\",\n eval_time,\n result.optimal_point,\n self._eval_count,\n )\n\n # TODO delete as soon as get_optimal_vector etc are removed\n self._ret = result\n\n if aux_operators is not None:\n aux_values = self._eval_aux_ops(opt_result.x, aux_operators, expectation=expectation)\n result.aux_operator_eigenvalues = aux_values\n\n return result\n\n def get_energy_evaluation(\n self,\n operator: OperatorBase,\n return_expectation: bool = False,\n ) -> Callable[[np.ndarray], Union[float, List[float]]]:\n \"\"\"Returns a function handle to evaluates the energy at given parameters for the ansatz.\n\n This is the objective function to be passed to the optimizer that is used for evaluation.\n\n Args:\n operator: The operator whose energy to evaluate.\n return_expectation: If True, return the ``ExpectationBase`` expectation converter used\n in the construction of the expectation value. Useful e.g. to evaluate other\n operators with the same expectation value converter.\n\n\n Returns:\n Energy of the hamiltonian of each parameter, and, optionally, the expectation\n converter.\n\n Raises:\n RuntimeError: If the circuit is not parameterized (i.e. has 0 free parameters).\n\n \"\"\"\n num_parameters = self.ansatz.num_parameters\n if num_parameters == 0:\n raise RuntimeError(\"The ansatz must be parameterized, but has 0 free parameters.\")\n\n expect_op, expectation = self.construct_expectation(\n self._ansatz_params, operator, return_expectation=True\n )\n\n def energy_evaluation(parameters):\n parameter_sets = np.reshape(parameters, (-1, num_parameters))\n # Create dict associating each parameter with the lists of parameterization values for it\n param_bindings = dict(zip(self._ansatz_params, parameter_sets.transpose().tolist()))\n start_time = time()\n sampled_expect_op = self._circuit_sampler.convert(expect_op, params=param_bindings)\n means = np.real(sampled_expect_op.eval())\n\n if self._callback is not None:\n variance = np.real(expectation.compute_variance(sampled_expect_op))\n estimator_error = np.sqrt(variance / self.quantum_instance.run_config.shots)\n for i, param_set in enumerate(parameter_sets):\n self._eval_count += 1\n self._callback(self._eval_count, param_set, means[i], estimator_error[i])\n else:\n self._eval_count += len(means)\n\n end_time = time()\n logger.info(\n \"Energy evaluation returned %s - %.5f (ms), eval count: %s\",\n means,\n (end_time - start_time) * 1000,\n self._eval_count,\n )\n\n return means if len(means) > 1 else means[0]\n\n if return_expectation:\n return energy_evaluation, expectation\n\n return energy_evaluation\n\n @deprecate_function(\n \"\"\"\nThe VQE.get_optimal_cost method is deprecated as of Qiskit Terra 0.18.0\nand will be removed no sooner than 3 months after the releasedate.\nThis information is part of the returned result object and can be\nqueried as VQEResult.eigenvalue.\"\"\"\n )\n def get_optimal_cost(self) -> float:\n \"\"\"Get the minimal cost or energy found by the VQE.\"\"\"\n if self._ret.optimal_point is None:\n raise AlgorithmError(\n \"Cannot return optimal cost before running the algorithm to find optimal params.\"\n )\n return self._ret.optimal_value\n\n @deprecate_function(\n \"\"\"\nThe VQE.get_optimal_circuit method is deprecated as of Qiskit Terra\n0.18.0 and will be removed no sooner than 3 months after the releasedate.\nThis information is part of the returned result object and can be\nqueried as VQEResult.ansatz.bind_parameters(VQEResult.optimal_point).\"\"\"\n )\n def get_optimal_circuit(self) -> QuantumCircuit:\n \"\"\"Get the circuit with the optimal parameters.\"\"\"\n if self._ret.optimal_point is None:\n raise AlgorithmError(\n \"Cannot find optimal circuit before running the algorithm to find optimal params.\"\n )\n return self.ansatz.assign_parameters(self._ret.optimal_parameters)\n\n @deprecate_function(\n \"\"\"\nThe VQE.get_optimal_vector method is deprecated as of Qiskit Terra 0.18.0\nand will be removed no sooner than 3 months after the releasedate.\nThis information is part of the returned result object and can be\nqueried as VQEResult.eigenvector.\"\"\"\n )\n def get_optimal_vector(self) -> Union[List[float], Dict[str, int]]:\n \"\"\"Get the simulation outcome of the optimal circuit.\"\"\"\n if self._ret.optimal_parameters is None:\n raise AlgorithmError(\n \"Cannot find optimal circuit before running the algorithm to find optimal vector.\"\n )\n return self._get_eigenstate(self._ret.optimal_parameters)\n\n def _get_eigenstate(self, optimal_parameters) -> Union[List[float], Dict[str, int]]:\n \"\"\"Get the simulation outcome of the ansatz, provided with parameters.\"\"\"\n optimal_circuit = self.ansatz.bind_parameters(optimal_parameters)\n state_fn = self._circuit_sampler.convert(StateFn(optimal_circuit)).eval()\n if self.quantum_instance.is_statevector:\n state = state_fn.primitive.data # VectorStateFn -> Statevector -> np.array\n else:\n state = state_fn.to_dict_fn().primitive # SparseVectorStateFn -> DictStateFn -> dict\n\n return state\n\n @property\n @deprecate_function(\n \"\"\"\nThe VQE.optimal_params property is deprecated as of Qiskit Terra 0.18.0\nand will be removed no sooner than 3 months after the releasedate.\nThis information is part of the returned result object and can be\nqueried as VQEResult.optimal_point.\"\"\"\n )\n def optimal_params(self) -> np.ndarray:\n \"\"\"The optimal parameters for the ansatz.\"\"\"\n if self._ret.optimal_point is None:\n raise AlgorithmError(\"Cannot find optimal params before running the algorithm.\")\n return self._ret.optimal_point\n\n\nclass VQEResult(VariationalResult, MinimumEigensolverResult):\n \"\"\"VQE Result.\"\"\"\n\n def __init__(self) -> None:\n super().__init__()\n self._cost_function_evals = None\n\n @property\n def cost_function_evals(self) -> Optional[int]:\n \"\"\"Returns number of cost optimizer evaluations\"\"\"\n return self._cost_function_evals\n\n @cost_function_evals.setter\n def cost_function_evals(self, value: int) -> None:\n \"\"\"Sets number of cost function evaluations\"\"\"\n self._cost_function_evals = value\n\n @property\n def eigenstate(self) -> Optional[np.ndarray]:\n \"\"\"return eigen state\"\"\"\n return self._eigenstate\n\n @eigenstate.setter\n def eigenstate(self, value: np.ndarray) -> None:\n \"\"\"set eigen state\"\"\"\n self._eigenstate = value\n\n\ndef _validate_initial_point(point, ansatz):\n expected_size = ansatz.num_parameters\n\n # try getting the initial point from the ansatz\n if point is None and hasattr(ansatz, \"preferred_init_points\"):\n point = ansatz.preferred_init_points\n # if the point is None choose a random initial point\n\n if point is None:\n # get bounds if ansatz has them set, otherwise use [-2pi, 2pi] for each parameter\n bounds = getattr(ansatz, \"parameter_bounds\", None)\n if not bounds:\n bounds = [(-2 * np.pi, 2 * np.pi)] * expected_size\n\n # replace all Nones by [-2pi, 2pi]\n lower_bounds = []\n upper_bounds = []\n for lower, upper in bounds:\n lower_bounds.append(lower if lower is not None else -2 * np.pi)\n upper_bounds.append(upper if upper is not None else 2 * np.pi)\n\n # sample from within bounds\n point = algorithm_globals.random.uniform(lower_bounds, upper_bounds)\n\n elif len(point) != expected_size:\n raise ValueError(\n f\"The dimension of the initial point ({len(point)}) does not match the \"\n f\"number of parameters in the circuit ({expected_size}).\"\n )\n\n return point\n\n\ndef _validate_bounds(ansatz):\n if hasattr(ansatz, \"parameter_bounds\") and ansatz.parameter_bounds is not None:\n bounds = ansatz.parameter_bounds\n if len(bounds) != ansatz.num_parameters:\n raise ValueError(\n f\"The number of bounds ({len(bounds)}) does not match the number of \"\n f\"parameters in the circuit ({ansatz.num_parameters}).\"\n )\n else:\n bounds = [(None, None)] * ansatz.num_parameters\n\n return bounds\n",
"# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2018, 2021.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\" Test AdaptQAOA \"\"\"\n\nimport unittest\nfrom test.python.algorithms import QiskitAlgorithmsTestCase\n\nimport math\nimport numpy as np\nimport retworkx as rx\nfrom ddt import ddt, idata, unpack\nfrom functools import reduce\nfrom itertools import combinations_with_replacement, permutations, product\n\nfrom qiskit.algorithms import AdaptQAOA\nfrom qiskit.algorithms.optimizers import COBYLA, NELDER_MEAD\n\nfrom qiskit.opflow import I, X, Y, Z, PauliSumOp\n\nfrom qiskit import BasicAer, QuantumCircuit, QuantumRegister\n\nfrom qiskit.circuit import Parameter\nfrom qiskit.circuit.library import XGate, YGate, ZGate, IGate\nfrom qiskit.quantum_info import Pauli\nfrom qiskit.utils import QuantumInstance, algorithm_globals\n\n\ndef _string_to_qiskit(qstring):\n qis_dict = {\"I\": I, \"X\": X, \"Y\": Y, \"Z\": Z}\n\n if all(x == qstring[0] for x in qstring):\n gate = qstring[0]\n list_string = [i * \"I\" + gate + (len(qstring) - i - 1) * \"I\" for i in range(len(qstring))]\n\n return sum(\n [\n reduce(lambda a, b: a ^ b, [qis_dict[char.upper()] for char in x])\n for x in list_string\n ]\n )\n return reduce(lambda a, b: a ^ b, [qis_dict[char.upper()] for char in qstring])\n\n\ndef _create_mixer_pool(num_q, add_multi, circ, parameterize):\n \"\"\"Compute the mixer pool\n Args:\n num_q (int): number of qubits\n add_multi (bool): whether to add multi qubit gates to the mixer pool\n circ (bool): if output mixer pool in form of list of circuits instead of list of operators\n parameterize (bool): if the circuit mixers should be parameterized\n\n Returns:\n list: all possible combinations of mixers\n \"\"\"\n mixer_pool = [\"X\" * num_q]\n\n mixer_pool.append(\"Y\" * num_q)\n\n mixer_pool += [i * \"I\" + \"X\" + (num_q - i - 1) * \"I\" for i in range(num_q)]\n mixer_pool += [i * \"I\" + \"Y\" + (num_q - i - 1) * \"I\" for i in range(num_q)]\n\n if add_multi:\n indicies = list(permutations(range(num_q), 2))\n indicies = list(set(tuple(sorted(x)) for x in indicies))\n combos = list(combinations_with_replacement([\"X\", \"Y\", \"Z\"], 2))\n\n full_multi = list(product(indicies, combos))\n for item in full_multi:\n iden_str = list(\"I\" * num_q)\n iden_str[item[0][0]] = item[1][0]\n iden_str[item[0][1]] = item[1][1]\n\n mixer_pool.append(\"\".join(iden_str))\n\n mixer_circ_list = []\n for mix_str in mixer_pool:\n if circ:\n\n # TODO: parameterise these circuits\n qr = QuantumRegister(num_q)\n qc = QuantumCircuit(qr)\n for i, mix in enumerate(mix_str):\n qiskit_dict = {\"I\": IGate(), \"X\": XGate(), \"Y\": YGate(), \"Z\": ZGate()}\n if parameterize:\n qiskit_dict = {\"I\": IGate(), \"X\": XGate(), \"Y\": YGate(), \"Z\": ZGate()}\n\n mix_qis_gate = qiskit_dict[mix]\n qc.append(mix_qis_gate, [i])\n mixer_circ_list.append(qc)\n else:\n op = _string_to_qiskit(mix_str)\n mixer_circ_list.append(op)\n return mixer_circ_list\n\n\nW1 = np.array([[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]])\nP1 = 1\nM1 = _create_mixer_pool(num_q=2, add_multi=True, circ=False)\nS1 = {\"0101\", \"1010\"}\n\nW2 = np.array(\n [\n [0.0, 8.0, -9.0, 0.0],\n [8.0, 0.0, 7.0, 9.0],\n [-9.0, 7.0, 0.0, -8.0],\n [0.0, 9.0, -8.0, 0.0],\n ]\n)\nP2 = 1\nM2 = None\nS2 = {\"1011\", \"0100\"}\n\nCUSTOM_SUPERPOSITION = [1 / math.sqrt(15)] * 15 + [0]\n\n\n@ddt\nclass TestAdaptQAOA(QiskitAlgorithmsTestCase):\n \"\"\"Test AdaptQAOA with MaxCut.\"\"\"\n\n def setUp(self):\n super().setUp()\n self.seed = 10598\n algorithm_globals.random_seed = self.seed\n\n self.qasm_simulator = QuantumInstance(\n BasicAer.get_backend(\"qasm_simulator\"),\n shots=4096,\n seed_simulator=self.seed,\n seed_transpiler=self.seed,\n )\n self.statevector_simulator = QuantumInstance(\n BasicAer.get_backend(\"statevector_simulator\"),\n seed_simulator=self.seed,\n seed_transpiler=self.seed,\n )\n\n @idata(\n [\n [W1, P1, M1, S1, False],\n [W2, P2, M2, S2, False],\n [W1, P1, M1, S1, True],\n [W2, P2, M2, S2, True],\n ]\n )\n @unpack\n def test_adapt_qaoa(self, w, prob, m, solutions, convert_to_matrix_op):\n \"\"\"AdaptQAOA test\"\"\"\n self.log.debug(\"Testing %s-step AdaptQAOA with MaxCut on graph\\n%s\", prob, w)\n\n qubit_op, _ = self._get_operator(w)\n if convert_to_matrix_op:\n qubit_op = qubit_op.to_matrix_op()\n\n adapt_qaoa = AdaptQAOA(COBYLA(), prob, mixer=m, quantum_instance=self.statevector_simulator)\n\n result = adapt_qaoa.compute_minimum_eigenvalue(operator=qubit_op)\n x = self._sample_most_likely(result.eigenstate)\n graph_solution = self._get_graph_solution(x)\n self.assertIn(graph_solution, solutions)\n\n @idata(\n [\n [W1, P1, S1, False],\n [W2, P2, S2, False],\n [W1, P1, S1, True],\n [W2, P2, S2, True],\n ]\n )\n @unpack\n def test_adapt_qaoa_qc_mixer(self, w, prob, solutions, convert_to_matrix_op):\n \"\"\"AdaptQAOA test with a mixer as a parameterized circuit\"\"\"\n self.log.debug(\n \"Testing %s-step AdaptQAOA with MaxCut on graph with \"\n \"a mixer as a parameterized circuit\\n%s\",\n prob,\n w,\n )\n\n optimizer = COBYLA()\n qubit_op, _ = self._get_operator(w)\n if convert_to_matrix_op:\n qubit_op = qubit_op.to_matrix_op()\n\n num_qubits = qubit_op.num_qubits\n mixer = _create_mixer_pool(num_qubits, add_multi=True, circ=True, parameterize=True)\n\n adapt_qaoa = AdaptQAOA(\n optimizer, prob, mixer=mixer, quantum_instance=self.statevector_simulator\n )\n\n result = adapt_qaoa.compute_minimum_eigenvalue(operator=qubit_op)\n x = self._sample_most_likely(result.eigenstate)\n graph_solution = self._get_graph_solution(x)\n self.assertIn(graph_solution, solutions)\n\n def test_adapt_qaoa_qc_mixer_many_parameters(self):\n \"\"\"AdaptQAOA test with a mixer as a parameterized circuit with the num of parameters > 1.\"\"\"\n optimizer = COBYLA()\n qubit_op, _ = self._get_operator(W1)\n\n num_qubits = qubit_op.num_qubits\n # TODO: differentiate between this function (>1 params) and prev function (=1 params) or delete one\n mixer = _create_mixer_pool(num_qubits, add_multi=True, circ=True, parameterize=True)\n\n adapt_qaoa = AdaptQAOA(\n optimizer, reps=2, mixer=mixer, quantum_instance=self.statevector_simulator\n )\n\n result = adapt_qaoa.compute_minimum_eigenvalue(operator=qubit_op)\n x = self._sample_most_likely(result.eigenstate)\n self.log.debug(x)\n graph_solution = self._get_graph_solution(x)\n self.assertIn(graph_solution, S1)\n\n def test_adapt_qaoa_qc_mixer_no_parameters(self):\n \"\"\"AdaptQAOA test with a mixer as a parameterized circuit with zero parameters.\"\"\"\n qubit_op, _ = self._get_operator(W1)\n\n num_qubits = qubit_op.num_qubits\n mixer = _create_mixer_pool(num_qubits, add_multi=True, circ=True, parameterize=False)\n\n adapt_qaoa = AdaptQAOA(\n COBYLA(), reps=1, mixer=mixer, quantum_instance=self.statevector_simulator\n )\n\n result = adapt_qaoa.compute_minimum_eigenvalue(operator=qubit_op)\n # we just assert that we get a result, it is not meaningful.\n self.assertIsNotNone(result.eigenstate)\n\n def test_change_operator_size(self):\n \"\"\"AdaptQAOA change operator size test\"\"\"\n qubit_op, _ = self._get_operator(\n np.array([[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]])\n )\n adapt_qaoa = AdaptQAOA(COBYLA(), 1, quantum_instance=self.statevector_simulator)\n result = adapt_qaoa.compute_minimum_eigenvalue(operator=qubit_op)\n x = self._sample_most_likely(result.eigenstate)\n graph_solution = self._get_graph_solution(x)\n with self.subTest(msg=\"AdaptQAOA 4x4\"):\n self.assertIn(graph_solution, {\"0101\", \"1010\"})\n\n qubit_op, _ = self._get_operator(\n np.array(\n [\n [0, 1, 0, 1, 0, 1],\n [1, 0, 1, 0, 1, 0],\n [0, 1, 0, 1, 0, 1],\n [1, 0, 1, 0, 1, 0],\n [0, 1, 0, 1, 0, 1],\n [1, 0, 1, 0, 1, 0],\n ]\n )\n )\n\n result = adapt_qaoa.compute_minimum_eigenvalue(operator=qubit_op)\n x = self._sample_most_likely(result.eigenstate)\n graph_solution = self._get_graph_solution(x)\n with self.subTest(msg=\"AdaptQAOA 6x6\"):\n self.assertIn(graph_solution, {\"010101\", \"101010\"})\n\n @idata([[W2, S2, None], [W2, S2, [0.0, 0.0]], [W2, S2, [1.0, 0.8]]])\n @unpack\n def test_adapt_qaoa_initial_point(self, w, solutions, init_pt):\n \"\"\"Check first parameter value used is initial point as expected\"\"\"\n qubit_op, _ = self._get_operator(w)\n\n first_pt = []\n\n def cb_callback(eval_count, parameters, mean, std):\n nonlocal first_pt\n if eval_count == 1:\n first_pt = list(parameters)\n\n adapt_qaoa = AdaptQAOA(\n COBYLA(),\n initial_point=init_pt,\n callback=cb_callback,\n quantum_instance=self.statevector_simulator,\n )\n\n result = adapt_qaoa.compute_minimum_eigenvalue(operator=qubit_op)\n x = self._sample_most_likely(result.eigenstate)\n graph_solution = self._get_graph_solution(x)\n\n with self.subTest(\"Initial Point\"):\n # If None the preferred random initial point of QAOA variational form\n if init_pt is None:\n self.assertLess(result.eigenvalue, -0.97)\n else:\n self.assertListEqual(init_pt, first_pt)\n\n with self.subTest(\"Solution\"):\n self.assertIn(graph_solution, solutions)\n\n @idata([[W2, None], [W2, [1.0] + 15 * [0.0]], [W2, CUSTOM_SUPERPOSITION]])\n @unpack\n def test_adapt_qaoa_initial_state(self, w, init_state):\n \"\"\"AdaptQAOA initial state test\"\"\"\n optimizer = COBYLA()\n qubit_op, _ = self._get_operator(w)\n\n init_pt = np.asarray([0.0, 0.0]) # Avoid generating random initial point\n\n if init_state is None:\n initial_state = None\n else:\n initial_state = QuantumCircuit(QuantumRegister(4, \"q\"))\n initial_state.initialize(init_state, initial_state.qubits)\n\n zero_init_state = QuantumCircuit(QuantumRegister(qubit_op.num_qubits, \"q\"))\n adapt_qaoa_zero_init_state = AdaptQAOA(\n optimizer=optimizer,\n initial_state=zero_init_state,\n initial_point=init_pt,\n quantum_instance=self.statevector_simulator,\n )\n adapt_qaoa = AdaptQAOA(\n optimizer=optimizer,\n initial_state=initial_state,\n initial_point=init_pt,\n quantum_instance=self.statevector_simulator,\n )\n\n zero_circuits = adapt_qaoa_zero_init_state.construct_circuit(init_pt, qubit_op)\n custom_circuits = adapt_qaoa.construct_circuit(init_pt, qubit_op)\n\n self.assertEqual(len(zero_circuits), len(custom_circuits))\n\n for zero_circ, custom_circ in zip(zero_circuits, custom_circuits):\n\n z_length = len(zero_circ.data)\n c_length = len(custom_circ.data)\n\n self.assertGreaterEqual(c_length, z_length)\n self.assertTrue(zero_circ.data == custom_circ.data[-z_length:])\n\n custom_init_qc = QuantumCircuit(custom_circ.num_qubits)\n custom_init_qc.data = custom_circ.data[0 : c_length - z_length]\n\n if initial_state is None:\n original_init_qc = QuantumCircuit(qubit_op.num_qubits)\n original_init_qc.h(range(qubit_op.num_qubits))\n else:\n original_init_qc = initial_state\n\n job_init_state = self.statevector_simulator.execute(original_init_qc)\n job_qaoa_init_state = self.statevector_simulator.execute(custom_init_qc)\n\n statevector_original = job_init_state.get_statevector(original_init_qc)\n statevector_custom = job_qaoa_init_state.get_statevector(custom_init_qc)\n\n self.assertListEqual(statevector_original.tolist(), statevector_custom.tolist())\n\n def test_adapt_qaoa_random_initial_point(self):\n \"\"\"AdaptQAOA random initial point\"\"\"\n w = rx.adjacency_matrix(\n rx.undirected_gnp_random_graph(5, 0.5, seed=algorithm_globals.random_seed)\n )\n qubit_op, _ = self._get_operator(w)\n\n adapt_qaoa = AdaptQAOA(\n optimizer=NELDER_MEAD(disp=True), reps=1, quantum_instance=self.qasm_simulator\n )\n\n result = adapt_qaoa.compute_minimum_eigenvalue(operator=qubit_op)\n\n self.assertLess(result.eigenvalue, -0.97)\n\n def _get_operator(self, weight_matrix):\n \"\"\"Generate Hamiltonian for the max-cut problem of a graph.\n\n Args:\n weight_matrix (numpy.ndarray) : adjacency matrix.\n\n Returns:\n PauliSumOp: operator for the Hamiltonian\n float: a constant shift for the obj function.\n\n \"\"\"\n num_nodes = weight_matrix.shape[0]\n pauli_list = []\n shift = 0\n for i in range(num_nodes):\n for j in range(i):\n if weight_matrix[i, j] != 0:\n x_p = np.zeros(num_nodes, dtype=bool)\n z_p = np.zeros(num_nodes, dtype=bool)\n z_p[i] = True\n z_p[j] = True\n pauli_list.append([0.5 * weight_matrix[i, j], Pauli((z_p, x_p))])\n shift -= 0.5 * weight_matrix[i, j]\n opflow_list = [(pauli[1].to_label(), pauli[0]) for pauli in pauli_list]\n return PauliSumOp.from_list(opflow_list), shift\n\n def _get_graph_solution(self, x: np.ndarray) -> str:\n \"\"\"Get graph solution from binary string.\n\n Args:\n x : binary string as numpy array.\n\n Returns:\n a graph solution as string.\n \"\"\"\n\n return \"\".join([str(int(i)) for i in 1 - x])\n\n def _sample_most_likely(self, state_vector):\n \"\"\"Compute the most likely binary string from state vector.\n Args:\n state_vector (numpy.ndarray or dict): state vector or counts.\n\n Returns:\n numpy.ndarray: binary string as numpy.ndarray of ints.\n \"\"\"\n n = int(np.log2(state_vector.shape[0]))\n k = np.argmax(np.abs(state_vector))\n x = np.zeros(n)\n for i in range(n):\n x[i] = k % 2\n k >>= 1\n return x\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"
] |
[
[
"numpy.reshape",
"numpy.abs",
"numpy.sqrt"
],
[
"numpy.log2",
"numpy.abs",
"numpy.asarray",
"numpy.array",
"numpy.zeros"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
fightZero/fightZero
|
[
"84c2f76c7dda31837d002e47cd74936044251079"
] |
[
"src/Algorithms/PPO.py"
] |
[
"# an implementation of PPO algorithm\n# reference to: https://github.com/nikhilbarhate99/PPO-PyTorch\nimport torch\nimport torch.nn as nn\nfrom torch.optim import Adam, RMSprop\nfrom torch.distributions import Categorical\nfrom torch.utils.tensorboard.writer import SummaryWriter\nfrom torch.utils.data import BatchSampler, RandomSampler\nfrom typing import Tuple\n\n# this class implements an actor critic model with linear networks\nclass ActorCritic(nn.Module):\n def __init__(self, state_dimension, action_dimension):\n super().__init__()\n # save dimensions\n self.d_state = state_dimension\n self.d_action = action_dimension\n # create actor network\n self.actor = nn.Sequential(\n nn.Linear(self.d_state, 1024),\n nn.LeakyReLU(),\n nn.Linear(1024, 512),\n nn.LeakyReLU(),\n nn.Linear(512, 256),\n nn.LeakyReLU(),\n nn.Linear(256, 128),\n nn.LeakyReLU(),\n nn.Linear(128, self.d_action),\n nn.Softmax(dim=1)\n )\n # create critic network\n self.critic = nn.Sequential(\n nn.Linear(self.d_state, 1024),\n nn.LeakyReLU(),\n nn.Linear(1024, 512),\n nn.LeakyReLU(),\n nn.Linear(512, 256),\n nn.LeakyReLU(),\n nn.Linear(256, 128),\n nn.LeakyReLU(),\n nn.Linear(128, 64),\n nn.LeakyReLU(),\n nn.Linear(64, 1)\n )\n\n def forward(self, x):\n \"\"\"\n Empty forward function\n \"\"\"\n return x\n\n def action(self, state) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"\n Get action and log probs\n \"\"\"\n # get probabilities of actions\n probs = self.actor(state)\n dist = Categorical(probs=probs)\n # sample an action\n action = dist.sample()\n logprob = dist.log_prob(action)\n return action.detach(), logprob.detach()\n\n def evaluate(self, state, action) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:\n \"\"\"\n Evaluates an action\n \"\"\"\n # get probabilities of actions\n probs = self.actor(state)\n dist = Categorical(probs=probs)\n # get distribution entropy and log probs of chosen action\n entropy = dist.entropy()\n logprob = dist.log_prob(action).diagonal().view(action.shape)\n # get critic value\n critics = self.critic(state)\n return entropy, logprob, critics\n\n\n# this structure stores buffer info for PPO\nclass PPOBuffer:\n def __init__(self):\n self.actions = []\n self.states = []\n self.logprobs = []\n self.rewards = []\n self.is_terminals = []\n\n def reset(self):\n del self.actions[:]\n del self.states[:]\n del self.logprobs[:]\n del self.rewards[:]\n del self.is_terminals[:]\n self.actions = []\n self.states = []\n self.logprobs = []\n self.rewards = []\n self.is_terminals = []\n\n def isEmpty(self):\n return len(self.actions) <= 0\n\n# this class implements PPO model\n# with actor and critic updated individually\nclass PPO(object):\n def __init__(self, \n state_dimension, action_dimension,\n lr_actor, lr_critic,\n num_epochs, discount,\n eps_clip, batch_size,\n max_grad_norm, train\n ):\n self.discount = discount\n self.num_epochs = num_epochs\n self.eps_clip = eps_clip\n self.lr_actor = lr_actor\n self.lr_critic = lr_critic\n self.batch_size = batch_size\n self.max_grad_norm = max_grad_norm\n self.training = train\n self.iter_count = 0\n\n # create buffer\n self.buffer = PPOBuffer()\n # select running environment for train\n self.device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n # create actor critic model\n self.AC = ActorCritic(state_dimension, action_dimension).to(self.device)\n # set optimizer\n self.optim_actor = Adam(self.AC.actor.parameters(), lr_actor)\n self.optim_critic = Adam(self.AC.critic.parameters(), lr_critic)\n # set saved model\n self.AC_saved = ActorCritic(state_dimension, action_dimension).to(self.device)\n self.AC_saved.load_state_dict(self.AC.state_dict())\n self.AC_saved.eval()\n # set loss function\n self.loss = nn.MSELoss()\n\n def action(self, state):\n \"\"\"\n Choose next action\n \"\"\"\n with torch.no_grad():\n # get new action from actor\n state = torch.FloatTensor(state).to(self.device)\n action, logprob = self.AC_saved.action(state)\n # store into buffer\n if self.training:\n self.buffer.states.append(state)\n self.buffer.actions.append(action)\n self.buffer.logprobs.append(logprob)\n return action.cpu().item()\n\n def save(self, filename):\n \"\"\"\n Save current network to file path\n \"\"\"\n torch.save((\n self.AC_saved.state_dict(),\n self.optim_actor.state_dict(),\n self.optim_critic.state_dict(),\n ), filename)\n\n def load(self, filename):\n \"\"\"\n Load network from file path\n \"\"\"\n states, opt1, opt2 = torch.load(filename, map_location=lambda storage, _: storage)\n self.AC.load_state_dict(states)\n self.AC_saved.load_state_dict(states)\n self.optim_actor.load_state_dict(opt1)\n self.optim_critic.load_state_dict(opt2)\n\n def train(self, writer : SummaryWriter):\n \"\"\"\n Update policy\n \"\"\"\n if not self.training: return\n if self.buffer.isEmpty(): return\n rewards = []\n reward_disc = 0.0\n for reward, is_terminal in zip(reversed(self.buffer.rewards), reversed(self.buffer.is_terminals)):\n # if is terminal state, set reward to 0\n if is_terminal:\n reward_disc = 0.0\n reward_disc = reward + (self.discount * reward_disc)\n rewards.insert(0, reward_disc)\n length = len(rewards)\n # normalize the rewards\n target_values = torch.FloatTensor(rewards)\n target_values = (target_values - target_values.mean()) / (target_values.std() + 1e-8)\n target_values = target_values.view(-1, 1)\n # convert list to tensor\n old_states = torch.squeeze(torch.stack(self.buffer.states[:length], dim=0)).detach()\n old_actions = torch.squeeze(torch.stack(self.buffer.actions[:length], dim=0)).view(-1, 1).detach()\n old_logprobs = torch.squeeze(torch.stack(self.buffer.logprobs[:length], dim=0)).view(-1, 1).detach()\n # start training\n self.AC.train()\n torch.cuda.empty_cache()\n for _ in range(self.num_epochs):\n for indices in BatchSampler(RandomSampler(range(length)), batch_size=self.batch_size, drop_last=False):\n target_values_gpu = target_values[indices].to(self.device)\n old_states_gpu = old_states[indices].to(self.device)\n old_actions_gpu = old_actions[indices].to(self.device)\n old_logprobs_gpu = old_logprobs[indices].to(self.device)\n # get critics\n _, logprob, state_values = self.AC.evaluate(old_states_gpu, old_actions_gpu)\n # state_values = torch.squeeze(critics)\n # compute advantages\n advantages = (target_values_gpu - state_values).detach()\n # find the ratio (pi_theta / pi_theta__old)\n ratios = torch.exp((logprob - old_logprobs_gpu))\n # find Surrogate Loss (Clipped Surrogate Objective)\n surr1 = ratios * advantages\n surr2 = torch.clamp(ratios, 1 - self.eps_clip, 1 + self.eps_clip) * advantages\n # compute actor loss\n loss_actor = -torch.min(surr1, surr2).mean()\n # optimize actor\n self.optim_actor.zero_grad()\n loss_actor.backward()\n torch.nn.utils.clip_grad.clip_grad_norm_(self.AC.actor.parameters(), max_norm=self.max_grad_norm)\n self.optim_actor.step()\n # compute critic loss\n loss_critic = self.loss(state_values, target_values_gpu).mean()\n self.optim_critic.zero_grad()\n loss_critic.backward()\n torch.nn.utils.clip_grad.clip_grad_norm_(self.AC.critic.parameters(), max_norm=self.max_grad_norm)\n self.optim_critic.step()\n # log in tensorboard\n writer.add_scalar(\"PPO/Loss Actor\", loss_actor.cpu().detach().item(), self.iter_count)\n writer.add_scalar(\"PPO/Loss Critic\", loss_critic.cpu().detach().item(), self.iter_count)\n writer.add_scalar(\"PPO/Advantage\", advantages.cpu().detach().mean().item(), self.iter_count)\n self.iter_count += 1\n self.AC.eval()\n # save weights after training\n self.AC_saved.load_state_dict(self.AC.state_dict())\n self.AC_saved.eval()\n # clear buffer\n self.buffer.reset()\n\n def update(self, reward, is_terminal):\n \"\"\"\n Update buffer\n \"\"\"\n if not self.training: return\n self.buffer.rewards.append(reward)\n self.buffer.is_terminals.append(is_terminal)"
] |
[
[
"torch.nn.Softmax",
"torch.load",
"torch.min",
"torch.cuda.empty_cache",
"torch.exp",
"torch.nn.Linear",
"torch.distributions.Categorical",
"torch.FloatTensor",
"torch.nn.LeakyReLU",
"torch.cuda.is_available",
"torch.no_grad",
"torch.stack",
"torch.clamp",
"torch.nn.MSELoss"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
asaladino/tf-playground
|
[
"c188d29077334038b2ae3afefed950f1ebb94477"
] |
[
"src/basic_classification/basic.py"
] |
[
"from __future__ import absolute_import, division, print_function\n\n# TensorFlow and tf.keras\nimport tensorflow as tf\nfrom tensorflow import keras\n\nfrom basic_classification.helper import prediction_for_one_image\n\nfashion_mnist = keras.datasets.fashion_mnist\n# Load the data\n(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()\nclass_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',\n 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']\n# Scale the data\ntrain_images = train_images / 255.0\ntest_images = test_images / 255.0\n\n# Build the model\nmodel = keras.Sequential([\n keras.layers.Flatten(input_shape=(28, 28)),\n keras.layers.Dense(128, activation=tf.nn.relu),\n keras.layers.Dense(128, activation=tf.nn.relu),\n keras.layers.Dense(10, activation=tf.nn.softmax)\n])\n\n# Compile the model\nmodel.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])\n# Train the model\nmodel.fit(train_images, train_labels, epochs=5)\n# Evaluate the model\ntest_loss, test_acc = model.evaluate(test_images, test_labels)\nprint('Test accuracy:', test_acc)\n# Predict what one image will be.\nprediction_for_one_image(test_images[0], model, test_labels, test_images, class_names)\n"
] |
[
[
"tensorflow.keras.layers.Dense",
"tensorflow.keras.layers.Flatten"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"2.6",
"2.4",
"2.3",
"2.5",
"2.2"
]
}
] |
free-city-of-ulm/Hashbrowns
|
[
"586e665b94a2d2221009f2602a10cc862a362895"
] |
[
"train.py"
] |
[
"#!/bin/env python\n\nfrom __future__ import print_function\nimport numpy as np\nimport tensorflow as tf\n\nimport argparse\nimport time\nimport os\nfrom six.moves import cPickle\n\nfrom rnn.utils import TextLoader\nfrom rnn.model import Model\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--data_dir', type=str, default='input',\n help='data directory containing input.txt')\n parser.add_argument('--save_dir', type=str, default='output',\n help='directory to store checkpointed models')\n parser.add_argument('--rnn_size', type=int, default=256,\n help='size of RNN hidden state')\n parser.add_argument('--num_layers', type=int, default=2,\n help='number of layers in the RNN')\n parser.add_argument('--model', type=str, default='lstm',\n help='rnn, gru, or lstm')\n parser.add_argument('--batch_size', type=int, default=50,\n help='minibatch size')\n parser.add_argument('--seq_length', type=int, default=25,\n help='RNN sequence length')\n parser.add_argument('--num_epochs', type=int, default=50,\n help='number of epochs')\n parser.add_argument('--save_every', type=int, default=1000,\n help='save frequency')\n parser.add_argument('--grad_clip', type=float, default=5.,\n help='clip gradients at this value')\n parser.add_argument('--learning_rate', type=float, default=0.002,\n help='learning rate')\n parser.add_argument('--decay_rate', type=float, default=0.97,\n help='decay rate for rmsprop')\n parser.add_argument('--init_from', type=str, default=None,\n help=\"\"\"continue training from saved model at this path. Path must contain files saved by previous training process:\n 'config.pkl' : configuration;\n 'words_vocab.pkl' : vocabulary definitions;\n 'checkpoint' : paths to model file(s) (created by tf).\n Note: this file contains absolute paths, be careful when moving files around;\n 'model.ckpt-*' : file(s) with model definition (created by tf)\n \"\"\")\n args = parser.parse_args()\n train(args)\n\ndef train(args):\n data_loader = TextLoader(args.data_dir, args.batch_size, args.seq_length)\n args.vocab_size = data_loader.vocab_size\n\n # check compatibility if training is continued from previously saved model\n if args.init_from is not None:\n # check if all necessary files exist\n assert os.path.isdir(args.init_from),\" %s must be a a path\" % args.init_from\n assert os.path.isfile(os.path.join(args.init_from,\"config.pkl\")),\"config.pkl file does not exist in path %s\"%args.init_from\n assert os.path.isfile(os.path.join(args.init_from,\"words_vocab.pkl\")),\"words_vocab.pkl.pkl file does not exist in path %s\" % args.init_from\n ckpt = tf.train.get_checkpoint_state(args.init_from)\n assert ckpt,\"No checkpoint found\"\n assert ckpt.model_checkpoint_path,\"No model path found in checkpoint\"\n\n # open old config and check if models are compatible\n with open(os.path.join(args.init_from, 'config.pkl'), 'rb') as f:\n saved_model_args = cPickle.load(f)\n need_be_same=[\"model\",\"rnn_size\",\"num_layers\",\"seq_length\"]\n for checkme in need_be_same:\n assert vars(saved_model_args)[checkme]==vars(args)[checkme],\"Command line argument and saved model disagree on '%s' \"%checkme\n\n # open saved vocab/dict and check if vocabs/dicts are compatible\n with open(os.path.join(args.init_from, 'words_vocab.pkl'), 'rb') as f:\n saved_words, saved_vocab = cPickle.load(f)\n assert saved_words==data_loader.words, \"Data and loaded model disagreee on word set!\"\n assert saved_vocab==data_loader.vocab, \"Data and loaded model disagreee on dictionary mappings!\"\n\n with open(os.path.join(args.save_dir, 'config.pkl'), 'wb') as f:\n cPickle.dump(args, f)\n with open(os.path.join(args.save_dir, 'words_vocab.pkl'), 'wb') as f:\n cPickle.dump((data_loader.words, data_loader.vocab), f)\n\n model = Model(args)\n\n with tf.Session() as sess:\n tf.initialize_all_variables().run()\n saver = tf.train.Saver(tf.all_variables())\n # restore model\n if args.init_from is not None:\n saver.restore(sess, ckpt.model_checkpoint_path)\n for e in range(args.num_epochs):\n sess.run(tf.assign(model.lr, args.learning_rate * (args.decay_rate ** e)))\n data_loader.reset_batch_pointer()\n state = model.initial_state.eval()\n for b in range(data_loader.num_batches):\n start = time.time()\n x, y = data_loader.next_batch()\n feed = {model.input_data: x, model.targets: y, model.initial_state: state}\n train_loss, state, _ = sess.run([model.cost, model.final_state, model.train_op], feed)\n end = time.time()\n print(\"{}/{} (epoch {}), train_loss = {:.3f}, time/batch = {:.3f}\" \\\n .format(e * data_loader.num_batches + b,\n args.num_epochs * data_loader.num_batches,\n e, train_loss, end - start))\n if (e * data_loader.num_batches + b) % args.save_every == 0 \\\n or (e==args.num_epochs-1 and b == data_loader.num_batches-1): # save for the last result\n checkpoint_path = os.path.join(args.save_dir, 'model.ckpt')\n saver.save(sess, checkpoint_path, global_step = e * data_loader.num_batches + b)\n print(\"model saved to {}\".format(checkpoint_path))\n\nif __name__ == '__main__':\n main()\n"
] |
[
[
"tensorflow.train.get_checkpoint_state",
"tensorflow.all_variables",
"tensorflow.assign",
"tensorflow.initialize_all_variables",
"tensorflow.Session"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
valosekj/spinalcordtoolbox
|
[
"266bfc88d6eb6e96a2c2f1ec88c2e185c6f88e09",
"266bfc88d6eb6e96a2c2f1ec88c2e185c6f88e09"
] |
[
"scripts/sct_compute_hausdorff_distance.py",
"scripts/sct_flatten_sagittal.py"
] |
[
"#!/usr/bin/env python\n#\n# Thinning with the Zhang-Suen algorithm (1984) --> code taken from https://github.com/linbojin/Skeletonization-by-Zhang-Suen-Thinning-Algorithm\n# Computation of the distances between two skeleton\n# ---------------------------------------------------------------------------------------\n# Copyright (c) 2013 Polytechnique Montreal <www.neuro.polymtl.ca>\n# Authors: Sara Dupont\n# CREATED: 2015-07-15\n#\n# About the license: see the file LICENSE.TXT\n#########################################################################################\n\nfrom __future__ import absolute_import, division\n\nimport sys, io, os, time, shutil, argparse\n\nimport numpy as np\n\nimport sct_utils as sct\nimport spinalcordtoolbox.image as msct_image\nfrom spinalcordtoolbox.image import Image\nfrom spinalcordtoolbox.utils import Metavar, SmartFormatter\n\n# TODO: display results ==> not only max : with a violin plot of h1 and h2 distribution ? see dev/straightening --> seaborn.violinplot\n# TODO: add the option Hyberbolic Hausdorff's distance : see choi and seidel paper\n\n# ----------------------------------------------------------------------------------------------------------------------\n# PARAM ----------------------------------------------------------------------------------------------------------------\n\n\nclass Param:\n def __init__(self):\n self.debug = 0\n self.thinning = True\n self.verbose = 1\n\n\n# ----------------------------------------------------------------------------------------------------------------------\n# THINNING -------------------------------------------------------------------------------------------------------------\nclass Thinning:\n def __init__(self, im, v=1):\n sct.printv('Thinning ... ', v, 'normal')\n self.image = im\n self.image.data = bin_data(self.image.data)\n self.dim_im = len(self.image.data.shape)\n\n if self.dim_im == 2:\n self.thinned_image = msct_image.empty_like(self.image)\n self.thinned_image.data = self.zhang_suen(self.image.data)\n self.thinned_image.absolutepath = sct.add_suffix(self.image.absolutepath, \"_thinned\")\n\n elif self.dim_im == 3:\n if not self.image.orientation == 'IRP':\n sct.printv('-- changing orientation ...')\n self.image.change_orientation('IRP')\n\n thinned_data = np.asarray([self.zhang_suen(im_slice) for im_slice in self.image.data])\n\n self.thinned_image = msct_image.empty_like(self.image)\n self.thinned_image.data = thinned_data\n self.thinned_image.absolutepath = sct.add_suffix(self.image.absolutepath, \"_thinned\")\n\n # ------------------------------------------------------------------------------------------------------------------\n def get_neighbours(self, x, y, image):\n \"\"\"\n Return 8-neighbours of image point P1(x,y), in a clockwise order\n code from https://github.com/linbojin/Skeletonization-by-Zhang-Suen-Thinning-Algorithm\n :param x:\n :param y:\n :param image:\n :return:\n \"\"\"\n # now = time.time()\n x_1, y_1, x1, y1 = x - 1, y - 1, x + 1, y + 1\n neighbours = [image[x_1][y], image[x_1][y1], image[x][y1], image[x1][y1], # P2,P3,P4,P5\n image[x1][y], image[x1][y_1], image[x][y_1], image[x_1][y_1]] # P6,P7,P8,P9\n # t = time.time() - now\n # sct.printv('t neighbours: ', t)\n return neighbours\n\n # ------------------------------------------------------------------------------------------------------------------\n def transitions(self, neighbours):\n \"\"\"\n No. of 0,1 patterns (transitions from 0 to 1) in the ordered sequence\n code from https://github.com/linbojin/Skeletonization-by-Zhang-Suen-Thinning-Algorithm\n :param neighbours:\n :return:\n \"\"\"\n # now = time.time()\n n = neighbours + neighbours[0:1] # P2, P3, ... , P8, P9, P2\n s = np.sum((n1, n2) == (0, 1) for n1, n2 in zip(n, n[1:])) # (P2,P3), (P3,P4), ... , (P8,P9), (P9,P2)\n # t = time.time() - now\n # sct.printv('t transitions sum: ', t)\n return s\n\n # ------------------------------------------------------------------------------------------------------------------\n def zhang_suen(self, image):\n \"\"\"\n the Zhang-Suen Thinning Algorithm\n code from https://github.com/linbojin/Skeletonization-by-Zhang-Suen-Thinning-Algorithm\n :param image:\n :return:\n \"\"\"\n # now = time.time()\n image_thinned = image.copy() # deepcopy to protect the original image\n changing1 = changing2 = 1 # the points to be removed (set as 0)\n while changing1 or changing2: # iterates until no further changes occur in the image\n # Step 1\n changing1 = []\n max = len(image_thinned) - 1\n pass_list = [1, max]\n # rows, columns = image_thinned.shape # x for rows, y for columns\n\n # for x in range(1, rows - 1): # No. of rows\n # for y in range(1, columns - 1): # No. of columns\n for x, y in non_zero_coord(image_thinned):\n if x not in pass_list and y not in pass_list:\n # if image_thinned[x][y] == 1: # Condition 0: Point P1 in the object regions\n P2, P3, P4, P5, P6, P7, P8, P9 = n = self.get_neighbours(x, y, image_thinned)\n if (2 <= sum(n) <= 6 and # Condition 1: 2<= N(P1) <= 6\n P2 * P4 * P6 == 0 and # Condition 3\n P4 * P6 * P8 == 0 and # Condition 4\n self.transitions(n) == 1): # Condition 2: S(P1)=1\n changing1.append((x, y))\n for x, y in changing1:\n image_thinned[x][y] = 0\n # Step 2\n changing2 = []\n\n # for x in range(1, rows - 1):\n # for y in range(1, columns - 1):\n for x, y in non_zero_coord(image_thinned):\n if x not in pass_list and y not in pass_list:\n # if image_thinned[x][y] == 1: # Condition 0\n P2, P3, P4, P5, P6, P7, P8, P9 = n = self.get_neighbours(x, y, image_thinned)\n if (2 <= sum(n) <= 6 and # Condition 1\n P2 * P4 * P8 == 0 and # Condition 3\n P2 * P6 * P8 == 0 and # Condition 4\n self.transitions(n) == 1): # Condition 2\n changing2.append((x, y))\n for x, y in changing2:\n image_thinned[x][y] = 0\n # t = time.time() - now\n # sct.printv('t thinning: ', t)\n return image_thinned\n\n\n# ----------------------------------------------------------------------------------------------------------------------\n# HAUSDORFF'S DISTANCE -------------------------------------------------------------------------------------------------\nclass HausdorffDistance:\n def __init__(self, data1, data2, v=1):\n \"\"\"\n the hausdorff distance between two sets is the maximum of the distances from a point in any of the sets to the nearest point in the other set\n :return:\n \"\"\"\n # now = time.time()\n sct.printv('Computing 2D Hausdorff\\'s distance ... ', v, 'normal')\n self.data1 = bin_data(data1)\n self.data2 = bin_data(data2)\n\n self.min_distances_1 = self.relative_hausdorff_dist(self.data1, self.data2, v)\n self.min_distances_2 = self.relative_hausdorff_dist(self.data2, self.data1, v)\n\n # relatives hausdorff's distances in pixel\n self.h1 = np.max(self.min_distances_1)\n self.h2 = np.max(self.min_distances_2)\n\n # Hausdorff's distance in pixel\n self.H = max(self.h1, self.h2)\n # t = time.time() - now\n # sct.printv('Hausdorff dist time :', t)\n\n # ------------------------------------------------------------------------------------------------------------------\n def relative_hausdorff_dist(self, dat1, dat2, v=1):\n h = np.zeros(dat1.shape)\n nz_coord_1 = non_zero_coord(dat1)\n nz_coord_2 = non_zero_coord(dat2)\n if len(nz_coord_1) != 0 and len(nz_coord_2) != 0 :\n for x1, y1 in nz_coord_1:\n # for x1 in range(dat1.shape[0]):\n # for y1 in range(dat1.shape[1]):\n # if dat1[x1, y1] == 1:\n d_p1_dat2 = []\n p1 = np.asarray([x1, y1])\n for x2, y2 in nz_coord_2:\n # for x2 in range(dat2.shape[0]):\n # for y2 in range(dat2.shape[1]):\n # if dat2[x2, y2] == 1:\n p2 = np.asarray([x2, y2])\n d_p1_dat2.append(np.linalg.norm(p1 - p2)) # Euclidean distance between p1 and p2\n h[x1, y1] = min(d_p1_dat2)\n else:\n sct.printv('Warning: an image is empty', v, 'warning')\n return h\n\n\n# ----------------------------------------------------------------------------------------------------------------------\n# COMPUTE DISTANCES ----------------------------------------------------------------------------------------------------\nclass ComputeDistances:\n def __init__(self, im1, im2=None, param=None):\n self.im1 = im1\n self.im2 = im2\n self.dim_im = len(self.im1.data.shape)\n self.dim_pix = 0\n self.distances = None\n self.res = ''\n self.param = param\n self.dist1_distribution = None\n self.dist2_distribution = None\n\n if self.dim_im == 3:\n self.orientation1 = self.im1.orientation\n if self.orientation1 != 'IRP':\n self.im1.change_orientation('IRP', generate_path=True)\n\n if self.im2 is not None:\n self.orientation2 = self.im2.orientation\n if self.orientation2 != 'IRP':\n self.im2.change_orientation('IRP', generate_path=True)\n\n if self.param.thinning:\n self.thinning1 = Thinning(self.im1, self.param.verbose)\n self.thinning1.thinned_image.save()\n\n if self.im2 is not None:\n self.thinning2 = Thinning(self.im2, self.param.verbose)\n self.thinning2.thinned_image.save()\n\n if self.dim_im == 2 and self.im2 is not None:\n self.compute_dist_2im_2d()\n\n if self.dim_im == 3:\n if self.im2 is None:\n self.compute_dist_1im_3d()\n else:\n self.compute_dist_2im_3d()\n\n if self.dim_im == 2 and self.distances is not None:\n self.dist1_distribution = self.distances.min_distances_1[np.nonzero(self.distances.min_distances_1)]\n self.dist2_distribution = self.distances.min_distances_2[np.nonzero(self.distances.min_distances_2)]\n if self.dim_im == 3:\n self.dist1_distribution = []\n self.dist2_distribution = []\n\n for d in self.distances:\n if np.nonzero(d.min_distances_1)[0].size: # Exist non zero values\n self.dist1_distribution.append(d.min_distances_1[np.nonzero(d.min_distances_1)])\n else: # all values are zero\n self.dist1_distribution.append(0)\n if np.nonzero(d.min_distances_2)[0].size: # Exist non zero values\n self.dist2_distribution.append(d.min_distances_2[np.nonzero(d.min_distances_2)])\n else: # all values are zero\n self.dist2_distribution.append(0)\n\n self.res = 'Hausdorff\\'s distance - First relative Hausdorff\\'s distance median - Second relative Hausdorff\\'s distance median(all in mm)\\n'\n for i, d in enumerate(self.distances):\n med1 = np.median(self.dist1_distribution[i])\n med2 = np.median(self.dist2_distribution[i])\n if self.im2 is None:\n self.res += 'Slice ' + str(i) + ' - slice ' + str(i + 1) + ': ' + str(d.H * self.dim_pix) + ' - ' + str(med1 * self.dim_pix) + ' - ' + str(med2 * self.dim_pix) + ' \\n'\n else:\n self.res += 'Slice ' + str(i) + ': ' + str(d.H * self.dim_pix) + ' - ' + str(med1 * self.dim_pix) + ' - ' + str(med2 * self.dim_pix) + ' \\n'\n\n sct.printv('-----------------------------------------------------------------------------\\n' +\n self.res, self.param.verbose, 'normal')\n\n if self.param.verbose == 2:\n self.show_results()\n\n # ------------------------------------------------------------------------------------------------------------------\n def compute_dist_2im_2d(self):\n nx1, ny1, nz1, nt1, px1, py1, pz1, pt1 = self.im1.dim\n nx2, ny2, nz2, nt2, px2, py2, pz2, pt2 = self.im2.dim\n\n assert np.isclose(px1, px2) and np.isclose(py1, py2) and np.isclose(px1, py1)\n self.dim_pix = py1\n\n if self.param.thinning:\n dat1 = self.thinning1.thinned_image.data\n dat2 = self.thinning2.thinned_image.data\n else:\n dat1 = bin_data(self.im1.data)\n dat2 = bin_data(self.im2.data)\n\n self.distances = HausdorffDistance(dat1, dat2, self.param.verbose)\n self.res = 'Hausdorff\\'s distance : ' + str(self.distances.H * self.dim_pix) + ' mm\\n\\n' \\\n 'First relative Hausdorff\\'s distance : ' + str(self.distances.h1 * self.dim_pix) + ' mm\\n' \\\n 'Second relative Hausdorff\\'s distance : ' + str(self.distances.h2 * self.dim_pix) + ' mm'\n\n # ------------------------------------------------------------------------------------------------------------------\n def compute_dist_1im_3d(self):\n nx1, ny1, nz1, nt1, px1, py1, pz1, pt1 = self.im1.dim\n self.dim_pix = py1\n\n if self.param.thinning:\n dat1 = self.thinning1.thinned_image.data\n else:\n dat1 = bin_data(self.im1.data)\n\n self.distances = []\n for i, dat_slice in enumerate(dat1[:-1]):\n self.distances.append(HausdorffDistance(bin_data(dat_slice), bin_data(dat1[i + 1]), self.param.verbose))\n\n # ------------------------------------------------------------------------------------------------------------------\n def compute_dist_2im_3d(self):\n nx1, ny1, nz1, nt1, px1, py1, pz1, pt1 = self.im1.dim\n nx2, ny2, nz2, nt2, px2, py2, pz2, pt2 = self.im2.dim\n # assert np.round(pz1, 5) == np.round(pz2, 5) and np.round(py1, 5) == np.round(py2, 5)\n assert nx1 == nx2\n self.dim_pix = py1\n\n if self.param.thinning:\n dat1 = self.thinning1.thinned_image.data\n dat2 = self.thinning2.thinned_image.data\n else:\n dat1 = bin_data(self.im1.data)\n dat2 = bin_data(self.im2.data)\n\n self.distances = []\n for slice1, slice2 in zip(dat1, dat2):\n self.distances.append(HausdorffDistance(slice1, slice2, self.param.verbose))\n\n # ------------------------------------------------------------------------------------------------------------------\n def show_results(self):\n import seaborn as sns\n import matplotlib.pyplot as plt\n import pandas as pd\n plt.hold(True)\n sns.set(style=\"whitegrid\", palette=\"pastel\", color_codes=True)\n plt.figure(figsize=(35, 20))\n\n data_dist = {\"distances\": [], \"image\": [], \"slice\": []}\n\n if self.dim_im == 2:\n data_dist[\"distances\"].append([dist * self.dim_pix for dist in self.dist1_distribution])\n data_dist[\"image\"].append(len(self.dist1_distribution) * [1])\n data_dist[\"slice\"].append(len(self.dist1_distribution) * [0])\n\n data_dist[\"distances\"].append([dist * self.dim_pix for dist in self.dist2_distribution])\n data_dist[\"image\"].append(len(self.dist2_distribution) * [2])\n data_dist[\"slice\"].append(len(self.dist2_distribution) * [0])\n\n if self.dim_im == 3:\n for i in range(len(self.distances)):\n data_dist[\"distances\"].append([dist * self.dim_pix for dist in self.dist1_distribution[i]])\n data_dist[\"image\"].append(len(self.dist1_distribution[i]) * [1])\n data_dist[\"slice\"].append(len(self.dist1_distribution[i]) * [i])\n data_dist[\"distances\"].append([dist * self.dim_pix for dist in self.dist2_distribution[i]])\n data_dist[\"image\"].append(len(self.dist2_distribution[i]) * [2])\n data_dist[\"slice\"].append(len(self.dist2_distribution[i]) * [i])\n\n for k in data_dist.keys(): # flatten the lists in data_dist\n data_dist[k] = [item for sublist in data_dist[k] for item in sublist]\n\n data_dist = pd.DataFrame(data_dist)\n sns.violinplot(x=\"slice\", y=\"distances\", hue=\"image\", data=data_dist, split=True, inner=\"point\", cut=0)\n plt.savefig('violin_plot.png')\n # plt.show()\n\n\n# ----------------------------------------------------------------------------------------------------------------------\ndef bin_data(data):\n return np.asarray((data > 0).astype(int))\n\n\n# ----------------------------------------------------------------------------------------------------------------------\ndef resample_image(fname, suffix='_resampled.nii.gz', binary=False, npx=0.3, npy=0.3, thr=0.0, interpolation='spline'):\n \"\"\"\n Resampling function: add a padding, resample, crop the padding\n :param fname: name of the image file to be resampled\n :param suffix: suffix added to the original fname after resampling\n :param binary: boolean, image is binary or not\n :param npx: new pixel size in the x direction\n :param npy: new pixel size in the y direction\n :param thr: if the image is binary, it will be thresholded at thr (default=0) after the resampling\n :param interpolation: type of interpolation used for the resampling\n :return: file name after resampling (or original fname if it was already in the correct resolution)\n \"\"\"\n im_in = Image(fname)\n orientation = im_in.orientation\n if orientation != 'RPI':\n fname = im_in.change_orientation(im_in, 'RPI', generate_path=True).save().absolutepath\n\n nx, ny, nz, nt, px, py, pz, pt = im_in.dim\n\n if np.round(px, 2) != np.round(npx, 2) or np.round(py, 2) != np.round(npy, 2):\n name_resample = sct.extract_fname(fname)[1] + suffix\n if binary:\n interpolation = 'nn'\n\n if nz == 1:\n # when data is 2d: we convert it to a 3d image in order to avoid conversion problem with 2d data\n # TODO: check if this above problem is still present (now that we are using nibabel instead of nipy)\n sct.run(['sct_image', '-i', ','.join([fname, fname]), '-concat', 'z', '-o', fname])\n\n sct.run(['sct_resample', '-i', fname, '-mm', str(npx) + 'x' + str(npy) + 'x' + str(pz), '-o', name_resample, '-x', interpolation])\n\n if nz == 1: # when input data was 2d: re-convert data 3d-->2d\n sct.run(['sct_image', '-i', name_resample, '-split', 'z'])\n im_split = Image(name_resample.split('.nii.gz')[0] + '_Z0000.nii.gz')\n im_split.save(name_resample)\n\n if binary:\n sct.run(['sct_maths', '-i', name_resample, '-bin', str(thr), '-o', name_resample])\n\n if orientation != 'RPI':\n name_resample = Image(name_resample) \\\n .change_orientation(orientation, generate_path=True) \\\n .save() \\\n .absolutepath\n\n return name_resample\n else:\n if orientation != 'RPI':\n fname = sct.add_suffix(fname, \"_RPI\")\n im_in = msct_image.change_orientation(im_in, orientation).save(fname)\n\n sct.printv('Image resolution already ' + str(npx) + 'x' + str(npy) + 'xpz')\n return fname\n\n\n# ----------------------------------------------------------------------------------------------------------------------\ndef non_zero_coord(data):\n dim = len(data.shape)\n if dim == 3:\n X, Y, Z = (data > 0).nonzero()\n list_coordinates = [(X[i], Y[i], Z[i]) for i in range(0, len(X))]\n elif dim == 2:\n X, Y = (data > 0).nonzero()\n list_coordinates = [(X[i], Y[i]) for i in range(0, len(X))]\n return list_coordinates\n\n\ndef get_parser():\n # Initialize the parser\n\n parser = argparse.ArgumentParser(\n description='Compute the Hausdorff\\'s distance between two binary images which can be thinned (ie skeletonized).'\n ' If only one image is inputted, it will be only thinned',\n add_help=None,\n formatter_class=SmartFormatter,\n prog=os.path.basename(__file__).strip(\".py\")\n )\n\n mandatoryArguments = parser.add_argument_group(\"\\nMANDATORY ARGUMENTS\")\n mandatoryArguments.add_argument(\n \"-i\",\n required=True,\n help='First Image on which you want to find the skeleton Example: t2star_manual_gmseg.nii.gz',\n metavar=Metavar.file,\n )\n\n optional = parser.add_argument_group(\"\\nOPTIONAL ARGUMENTS\")\n optional.add_argument(\n \"-h\",\n \"--help\",\n action=\"help\",\n help=\"show this help message and exit\")\n optional.add_argument(\n \"-d\",\n help='Second Image on which you want to find the skeleton Example: t2star_manual_gmseg.nii.gz',\n metavar=Metavar.file,\n required=False,\n default=None)\n optional.add_argument(\n \"-thinning\",\n type=int,\n help=\"Thinning : find the skeleton of the binary images using the Zhang-Suen algorithm (1984) and use it to \"\n \"compute the hausdorff's distance\",\n required=False,\n default=1,\n choices=(0, 1))\n optional.add_argument(\n \"-resampling\",\n type=float,\n help=\"pixel size in mm to resample to Example: 0.5\",\n metavar=Metavar.float,\n required=False,\n default=0.1)\n optional.add_argument(\n \"-o\",\n help='Name of the output file Example: my_hausdorff_dist.txt',\n metavar=Metavar.str,\n required=False,\n default='hausdorff_distance.txt')\n optional.add_argument(\n \"-v\",\n type=int,\n help=\"Verbose. 0: nothing, 1: basic, 2: extended.\",\n required=False,\n choices=(0, 1, 2),\n default = 1)\n\n return parser\n\n\n########################################################################################################################\n# ------------------------------------------------------ MAIN ------------------------------------------------------- #\n########################################################################################################################\n\nif __name__ == \"__main__\":\n sct.init_sct()\n param = Param()\n input_fname = None\n if param.debug:\n sct.printv('\\n*** WARNING: DEBUG MODE ON ***\\n')\n else:\n param_default = Param()\n parser = get_parser()\n arguments = parser.parse_args(args=None if sys.argv[1:] else ['--help'])\n input_fname = arguments.i\n input_second_fname = ''\n output_fname = 'hausdorff_distance.txt'\n resample_to = 0.1\n\n if arguments.d is not None:\n input_second_fname = arguments.d\n if arguments.thinning is not None:\n param.thinning = bool(arguments.thinning)\n if arguments.resampling is not None:\n resample_to = arguments.resampling\n if arguments.o is not None:\n output_fname = arguments.o\n param.verbose = arguments.v\n sct.init_sct(log_level=param.verbose, update=True) # Update log level\n\n tmp_dir = sct.tmp_create()\n im1_name = \"im1.nii.gz\"\n sct.copy(input_fname, os.path.join(tmp_dir, im1_name))\n if input_second_fname != '':\n im2_name = 'im2.nii.gz'\n sct.copy(input_second_fname, os.path.join(tmp_dir, im2_name))\n else:\n im2_name = None\n\n curdir = os.getcwd()\n os.chdir(tmp_dir)\n\n # now = time.time()\n input_im1 = Image(resample_image(im1_name, binary=True, thr=0.5, npx=resample_to, npy=resample_to))\n input_im1.absolutepath = os.path.basename(input_fname)\n if im2_name is not None:\n input_im2 = Image(resample_image(im2_name, binary=True, thr=0.5, npx=resample_to, npy=resample_to))\n input_im2.absolutepath = os.path.basename(input_second_fname)\n else:\n input_im2 = None\n\n computation = ComputeDistances(input_im1, im2=input_im2, param=param)\n\n # TODO change back the orientatin of the thinned image\n if param.thinning:\n computation.thinning1.thinned_image.save(\n os.path.join(curdir, sct.add_suffix(os.path.basename(input_fname), '_thinned')))\n if im2_name is not None:\n computation.thinning2.thinned_image.save(\n os.path.join(curdir, sct.add_suffix(os.path.basename(input_second_fname), '_thinned')))\n\n os.chdir(curdir)\n\n res_fic = open(output_fname, 'w')\n res_fic.write(computation.res)\n res_fic.write('\\n\\nInput 1: ' + input_fname)\n res_fic.write('\\nInput 2: ' + input_second_fname)\n res_fic.close()\n\n # sct.printv('Total time: ', time.time() - now)\n",
"#!/usr/bin/env python\n#########################################################################################\n#\n# Flatten spinal cord in sagittal plane.\n#\n# ---------------------------------------------------------------------------------------\n# Copyright (c) 2013 Polytechnique Montreal <www.neuro.polymtl.ca>\n# Author: Benjamin De Leener, Julien Cohen-Adad\n# Modified: 2014-06-02\n#\n# About the license: see the file LICENSE.TXT\n#########################################################################################\n\nfrom __future__ import absolute_import, division\n\nimport sys\n\nimport numpy as np\nfrom skimage import transform, img_as_float\n\nimport sct_utils as sct\nimport spinalcordtoolbox.image as msct_image\nfrom spinalcordtoolbox.image import Image\nfrom spinalcordtoolbox.centerline.core import ParamCenterline, get_centerline\nfrom msct_parser import Parser\n\n\n# Default parameters\nclass Param:\n # The constructor\n def __init__(self):\n self.debug = 0\n self.interp = 'sinc' # final interpolation\n self.remove_temp_files = 1 # remove temporary files\n self.verbose = 1\n\n\ndef flatten_sagittal(im_anat, im_centerline, verbose):\n \"\"\"\n Flatten a 3D volume using the segmentation, such that the spinal cord is centered in the R-L medial plane.\n :param im_anat:\n :param im_centerline:\n :param verbose:\n :return:\n \"\"\"\n # re-oriente to RPI\n orientation_native = im_anat.orientation\n im_anat.change_orientation(\"RPI\")\n im_centerline.change_orientation(\"RPI\")\n nx, ny, nz, nt, px, py, pz, pt = im_anat.dim\n\n # smooth centerline and return fitted coordinates in voxel space\n _, arr_ctl, _, _ = get_centerline(im_centerline, param=ParamCenterline(), verbose=verbose)\n x_centerline_fit, y_centerline_fit, z_centerline = arr_ctl\n\n # Extend the centerline by copying values below zmin and above zmax to avoid discontinuities\n zmin, zmax = z_centerline.min().astype(int), z_centerline.max().astype(int)\n x_centerline_extended = np.concatenate([np.ones(zmin) * x_centerline_fit[0],\n x_centerline_fit,\n np.ones(nz-zmax) * x_centerline_fit[-1]])\n\n # change type to float32 and scale between -1 and 1 as requested by img_as_float(). See #1790, #2069\n im_anat_flattened = msct_image.change_type(im_anat, np.float32)\n min_data, max_data = np.min(im_anat_flattened.data), np.max(im_anat_flattened.data)\n im_anat_flattened.data = 2 * im_anat_flattened.data/(max_data - min_data) - 1\n\n # loop and translate each axial slice, such that the flattened centerline is centered in the medial plane (R-L)\n for iz in range(nz):\n # compute translation along x (R-L)\n translation_x = x_centerline_extended[iz] - np.round(nx/2.0)\n # apply transformation to 2D image with linear interpolation\n # tform = tf.SimilarityTransform(scale=1, rotation=0, translation=(translation_x, 0))\n tform = transform.SimilarityTransform(translation=(0, translation_x))\n # important to force input in float to skikit image, because it will output float values\n img = img_as_float(im_anat_flattened.data[:, :, iz])\n img_reg = transform.warp(img, tform)\n im_anat_flattened.data[:, :, iz] = img_reg\n\n # change back to native orientation\n im_anat_flattened.change_orientation(orientation_native)\n\n return im_anat_flattened\n\n\ndef main(fname_anat, fname_centerline, verbose):\n \"\"\"\n Main function\n :param fname_anat:\n :param fname_centerline:\n :param verbose:\n :return:\n \"\"\"\n # load input images\n im_anat = Image(fname_anat)\n im_centerline = Image(fname_centerline)\n\n # flatten sagittal\n im_anat_flattened = flatten_sagittal(im_anat, im_centerline, verbose)\n\n # save output\n fname_out = sct.add_suffix(fname_anat, '_flatten')\n im_anat_flattened.save(fname_out)\n\n sct.display_viewer_syntax([fname_anat, fname_out])\n\n\ndef get_parser():\n param_default = Param()\n parser = Parser(__file__)\n parser.usage.set_description(\"\"\"Flatten the spinal cord such within the medial sagittal plane. Useful to make nice \n pictures. Output data has suffix _flatten. Output type is float32 (regardless of input type) to minimize loss of \n precision during conversion.\"\"\")\n parser.add_option(name='-i',\n type_value='image_nifti',\n description='Input volume.',\n mandatory=True,\n example='t2.nii.gz')\n parser.add_option(name='-s',\n type_value='image_nifti',\n description='Spinal cord segmentation or centerline.',\n mandatory=True,\n example='t2_seg.nii.gz')\n parser.add_option(name='-v',\n type_value='multiple_choice',\n description='0: no verbose (default), 1: min verbose, 2: verbose + figures',\n mandatory=False,\n example=['0', '1', '2'],\n default_value=str(param_default.verbose))\n parser.add_option(name='-h',\n type_value=None,\n description='Display this help',\n mandatory=False)\n\n return parser\n\n\nif __name__ == \"__main__\":\n sct.init_sct()\n # initialize parameters\n param = Param()\n param_default = Param()\n\n parser = get_parser()\n arguments = parser.parse(sys.argv[1:])\n fname_anat = arguments['-i']\n fname_centerline = arguments['-s']\n verbose = int(arguments.get('-v'))\n sct.init_sct(log_level=verbose, update=True) # Update log level\n\n # call main function\n main(fname_anat, fname_centerline, verbose)\n"
] |
[
[
"numpy.nonzero",
"numpy.asarray",
"numpy.isclose",
"numpy.median",
"numpy.linalg.norm",
"pandas.DataFrame",
"matplotlib.pyplot.hold",
"matplotlib.pyplot.savefig",
"numpy.max",
"numpy.round",
"numpy.zeros",
"matplotlib.pyplot.figure"
],
[
"numpy.round",
"numpy.max",
"numpy.ones",
"numpy.min"
]
] |
[
{
"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": []
}
] |
jzuhone/yt_astro_analysis
|
[
"417751c41696e7e230d92a918fadda5263c99d56"
] |
[
"yt_astro_analysis/halo_analysis/enzofof_merger_tree.py"
] |
[
"\"\"\"\nA very simple, purely-serial, merger tree script that knows how to parse FOF\ncatalogs, either output by Enzo or output by yt's FOF halo finder, and then \ncompare parent/child relationships.\n\n\n\n\"\"\"\nfrom __future__ import print_function\n\n#-----------------------------------------------------------------------------\n# Copyright (c) 2013, yt Development Team.\n#\n# Distributed under the terms of the Modified BSD License.\n#\n# The full license is in the file COPYING.txt, distributed with this software.\n#-----------------------------------------------------------------------------\n# plot_halo_evolution() gives a good full example of how to use the framework\n\n# First pass at a simplified merger tree\n#\n# Basic outline:\n#\n# 1. Halo find inline, obtaining particle catalogs\n# 2. Load dataset at time t\n# 3. Load dataset at time t+1\n# 4. Parse catalogs for t and t+1\n# 5. Place halos for t+1 in kD-tree\n# 6. For every halo in t, execute ball-query with some linking length\n# 7. For every halo in ball-query result, execute numpy's intersect1d on\n# particle IDs\n# 8. Parentage is described by a fraction of particles that pass from one to\n# the other; we have both descendent fractions and ancestory fractions. \n\n\nimport numpy as np\nfrom yt.utilities.on_demand_imports import _h5py as h5py\nimport glob\nimport os\n\nfrom yt.extern.six.moves import cPickle\nfrom yt.extern.pykdtree import KDTree\nfrom yt.funcs import mylog, get_pbar\n\nimport yt.extern.pydot as pydot\n\n# We don't currently use this, but we may again find a use for it in the\n# future.\nclass MaxLengthDict(dict):\n def __init__(self, *args, **kwargs):\n dict.__init__(self, *args, **kwargs)\n self.order = [None] * 50\n\n def __setitem__(self, key, val):\n if key not in self.order:\n to_remove = self.order.pop(0)\n self.pop(to_remove, None)\n self.order.append(key)\n dict.__setitem__(self, key, val)\n\n def __getitem__(self, key):\n if key in self.order:\n self.order.pop(self.order.index(key))\n self.order.append(key)\n return dict.__getitem__(self, key)\n\n def __delitem__(self, key):\n dict.__delitem__(self, key)\n self.order.pop(self.order.index(key))\n self.order.insert(0, None)\n\nclass HaloCatalog(object):\n r\"\"\"A catalog of halos, parsed from EnzoFOF outputs.\n\n This class will read in catalogs output by the Enzo FOF halo finder and\n make available their positions, radii, etc. Enzo FOF was provided\n starting with 2.0, and can be run either inline (with the correct\n options) or as a postprocessing step using the `-F` command line\n option. This class is mostly useful when calculating a merger tree,\n and when the particle IDs for members of a given halo are output as\n well.\n\n Parameters\n ----------\n output_id : int\n This is the integer output id of the halo catalog to parse and\n load.\n cache : bool\n Should we store, in between accesses, the particle IDs? If set to\n true, the correct particle files must exist.\n external_FOF : bool, optional\n Are we building a tree from outputs generated by an\n external FOF program, or an FOF internal to yt?\n FOF_directory : str, optional\n Directory where FOF files are located\n \"\"\"\n cache = None\n def __init__(self, output_id, cache = True, external_FOF=True, FOF_directory=\"FOF\"):\n self.output_id = output_id\n self.external_FOF = external_FOF\n self.redshift = 0.0\n self.FOF_directory = FOF_directory\n self.particle_file = h5py.File(\"%s/particles_%05i.h5\" % \\\n (FOF_directory, output_id), \"r\")\n if self.external_FOF:\n self.parse_halo_catalog_external()\n else:\n self.parse_halo_catalog_internal()\n if cache: self.cache = dict()#MaxLengthDict()\n\n def __del__(self):\n self.particle_file.close()\n\n def parse_halo_catalog_external(self):\n hp = []\n for line in open(\"%s/groups_%05i.dat\" % \\\n (self.FOF_directory, self.output_id)):\n if line.strip() == \"\": continue # empty\n if line.startswith(\"# Red\"):\n self.redshift = float(line.split(\"=\")[1])\n if line[0] == \"#\": continue # comment\n if line[0] == \"d\": continue # datavar\n x,y,z = [float(f) for f in line.split(None, 3)[:-1]]\n hp.append([x,y,z])\n if hp != []:\n self.halo_positions = np.array(hp)\n self.halo_kdtree = KDTree(self.halo_positions)\n else:\n self.halo_positions = None\n self.halo_kdtree = None\n return hp\n\n def parse_halo_catalog_internal(self):\n \"\"\"\n This parser works on the files output directly out of yt's internal\n halo_finder. The parse_halo_catalog_external works with an \n external version of FOF.\n\n Examples\n --------\n >>> ds = load(\"DD0000/DD0000\")\n >>> halo_list = FOFHaloFinder(ds)\n >>> halo_list.write_out(\"FOF/groups_00000.txt\")\n >>> halos_COM = parse_halo_catalog_internal()\n \"\"\"\n hp = []\n for line in open(\"%s/groups_%05i.txt\" % \\\n (self.FOF_directory, self.output_id)):\n if line.startswith(\"# RED\"):\n self.redshift = float(line.split(\"=\")[1])\n continue\n if line.strip() == \"\": continue # empty\n if line[0] == \"#\": continue # comment\n x,y,z = [float(f) for f in line.split()[7:10]] # COM x,y,z\n hp.append([x,y,z])\n if hp != []:\n self.halo_positions = np.array(hp)\n self.halo_kdtree = KDTree(self.halo_positions)\n else:\n self.halo_positions = None\n self.halo_kdtree = None\n return hp\n\n def read_particle_ids(self, halo_id): \n if self.cache is not None:\n if halo_id not in self.cache:\n if self.external_FOF:\n self.cache[halo_id] = \\\n self.particle_file[\"/Halo%08i/Particle ID\" % halo_id][:]\n else:\n self.cache[halo_id] = \\\n self.particle_file[\"/Halo%08i/particle_index\" % halo_id][:]\n ids = self.cache[halo_id]\n else:\n if self.external_FOF:\n ids = self.particle_file[\"/Halo%08i/Particle ID\" % halo_id][:]\n else:\n ids = self.particle_file[\"/Halo%08i/particle_index\" % halo_id][:]\n return HaloParticleList(halo_id, self.halo_positions[halo_id,:], ids)\n\n def calculate_parentage_fractions(self, other_catalog, radius = 0.10):\n parentage_fractions = {}\n if self.halo_positions is None or other_catalog.halo_positions is None:\n return parentage_fractions\n mylog.debug(\"Ball-tree query with radius %0.3e\", radius)\n all_nearest = self.halo_kdtree.query_ball_tree(\n other_catalog.halo_kdtree, radius)\n pbar = get_pbar(\"Halo Mergers\", self.halo_positions.shape[0])\n for hid1, nearest in enumerate(all_nearest):\n pbar.update(hid1)\n parentage_fractions[hid1] = {}\n HPL1 = self.read_particle_ids(hid1)\n for hid2 in sorted(nearest):\n HPL2 = other_catalog.read_particle_ids(hid2)\n p1, p2 = HPL1.find_relative_parentage(HPL2)\n parentage_fractions[hid1][hid2] = (p1, p2, HPL2.number_of_particles)\n parentage_fractions[hid1][\"NumberOfParticles\"] = HPL1.number_of_particles\n pbar.finish()\n return parentage_fractions\n\nclass HaloParticleList(object):\n def __init__(self, halo_id, position, particle_ids):\n self.halo_id = halo_id\n self.position = np.array(position)\n self.particle_ids = particle_ids\n self.number_of_particles = particle_ids.size\n\n def find_nearest(self, other_tree, radius = 0.10):\n return other_tree.query_ball_point(self.position, radius)\n\n def find_relative_parentage(self, child):\n # Return two values: percent this halo gave to the other, and percent\n # of the other that comes from this halo\n overlap = np.intersect1d(self.particle_ids, child.particle_ids).size\n of_child_from_me = float(overlap)/child.particle_ids.size\n of_mine_from_me = float(overlap)/self.particle_ids.size\n return of_child_from_me, of_mine_from_me\n\nclass EnzoFOFMergerBranch(object):\n def __init__(self, tree, output_num, halo_id, max_children,\n min_relation=0.25):\n self.output_num = output_num\n self.halo_id = halo_id\n self.npart = tree.relationships[output_num][halo_id][\"NumberOfParticles\"]\n self.children = []\n self.progenitor = -1\n max_relationship = 0.0\n halo_count = 0\n keys = list(tree.relationships[output_num][halo_id].keys())\n keys.remove('NumberOfParticles')\n for k in sorted(keys):\n v = tree.relationships[output_num][halo_id][k]\n if v[1] > min_relation and halo_count < max_children:\n halo_count += 1\n self.children.append((k,v[1],v[2]))\n if v[1] > max_relationship:\n self.progenitor = k\n max_relationship = v[1]\n\nclass EnzoFOFMergerTree(object):\n r\"\"\"Calculates the parentage relationships for halos for a series of\n outputs, using the framework provided in enzofof_merger_tree.\n\n Parameters\n ----------\n zrange : tuple\n This is the redshift range (min, max) to calculate the\n merger tree. E.g. (0, 2) for z=2 to z=0\n cycle_range : tuple, optional\n This is the cycle number range (min, max) to calculate the\n merger tree. If both zrange and cycle_number given,\n ignore zrange.\n output : bool, optional\n If provided, both .cpkl and .txt files containing the parentage\n relationships will be output.\n load_saved : bool, optional\n Flag to load previously saved parental relationships\n save_filename : str, optional\n Filename to save parental relationships\n external_FOF : bool, optional\n Are we building a tree from outputs generated by an\n external FOF program, or an FOF internal to yt?\n FOF_directory : str, optional\n Directory where FOF files are located, note that the files\n must be named according to the syntax: groups_DDDDD.txt for\n internal yt outputs, and groups_DDDDD.dat for external FOF outputs.\n where DDDDD are digits representing the equivalent cycle number.\n e.g. groups_00000.txt\n \n Examples\n --------\n >>> mt = EnzoFOFMergerTree() # by default it grabs every DD in FOF dir\n >>> mt.build_tree(0) # Create tree for halo 0\n >>> mt.print_tree()\n >>> mt.write_dot()\n\n See Also\n --------\n plot_halo_evolution()\n \"\"\" \n def __init__(self, zrange=None, cycle_range=None, output=False,\n load_saved=False, save_filename=\"merger_tree.cpkl\",\n external_FOF=True, FOF_directory=\"FOF\"):\n\n self.relationships = {}\n self.redshifts = {}\n self.external_FOF = external_FOF\n self.FOF_directory = FOF_directory\n if load_saved:\n self.load_tree(\"%s/%s\" % (self.FOF_directory, save_filename))\n # make merger tree work within specified cycle/z limits\n # on preloaded halos\n if zrange is not None:\n self.select_redshifts(zrange)\n if cycle_range is not None:\n self.select_cycles(cycle_range)\n else:\n self.find_outputs(zrange, cycle_range, output)\n self.run_merger_tree(output)\n self.save_tree(\"%s/%s\" % (self.FOF_directory, save_filename))\n \n def select_cycles(self, cycle_range):\n \"\"\"\n Takes an existing tree and pares it to only include a subset of\n cycles. Useful in paring a loaded tree. \n \"\"\"\n # N.B. Does not delete info from self.relationships to save space\n # just removes it from redshift dict for indexing\n for cycle in self.redshifts.keys():\n if cycle <= cycle_range[0] and cycle >= cycle_range[1]:\n del self.redshifts[cycle]\n\n def select_redshifts(self, zrange):\n \"\"\"\n Takes an existing tree and pares it to only include a subset of\n redshifts. Useful in paring a loaded tree. \n \"\"\"\n # N.B. Does not delete info from self.relationships to save space\n # just removes it from redshift dict for indexing\n for redshift in self.redshifts.values():\n if redshift <= zrange[0] and redshift >= zrange[1]:\n # some reverse lookup magic--assumes unique cycle/z pairs\n cycle = [key for key,value in self.redshifts.items() \\\n if value == redshift][0]\n del self.redshifts[cycle]\n\n def save_tree(self, filename):\n cPickle.dump((self.redshifts, self.relationships),\n open(filename, \"wb\"))\n\n def load_tree(self, filename):\n self.redshifts, self.relationships = \\\n cPickle.load(open(filename, \"rb\"))\n\n def clear_data(self):\n r\"\"\"Deletes previous merger tree, but keeps parentage\n relationships.\n \"\"\"\n del self.levels\n\n def find_outputs(self, zrange, cycle_range, output):\n self.numbers = []\n if self.external_FOF:\n filenames = \"%s/groups_*.dat\" % (self.FOF_directory)\n files = glob.glob(filenames)\n else:\n filenames = \"%s/groups_*.txt\" % (self.FOF_directory)\n files = glob.glob(filenames)\n # If using redshift range, load redshifts only\n for f in files:\n num = int(f[-9:-4])\n if zrange is not None:\n HC = HaloCatalog(num, external_FOF=self.external_FOF, \\\n FOF_directory=self.FOF_directory)\n # Allow for some epsilon\n diff1 = (HC.redshift - zrange[0]) / zrange[0]\n diff2 = (HC.redshift - zrange[1]) / zrange[1]\n if diff1 >= -1e-3 and diff2 <= 1e-3:\n self.numbers.append(num)\n del HC\n elif cycle_range is not None:\n if num >= cycle_range[0] and num <= cycle_range[1]:\n self.numbers.append(num)\n else:\n self.numbers.append(num)\n self.numbers.sort()\n\n def run_merger_tree(self, output):\n # Run merger tree for all outputs, starting with the last output\n for i in range(len(self.numbers)-1, 0, -1):\n if output:\n output = \"%s/tree-%5.5d-%5.5d\" % \\\n (self.FOF_directory, self.numbers[i], self.numbers[i-1])\n else:\n output = None\n z0, z1, fr = find_halo_relationships(self.numbers[i], \\\n self.numbers[i-1], \\\n output_basename=output, \\\n external_FOF=self.external_FOF,\n FOF_directory=self.FOF_directory)\n self.relationships[self.numbers[i]] = fr\n self.redshifts[self.numbers[i]] = z0\n # Fill in last redshift\n self.redshifts[self.numbers[0]] = z1\n\n def build_tree(self, halonum, min_particles=0, max_children=1e20):\n r\"\"\"Builds a merger tree, starting at the last output.\n\n Parameters\n ----------\n halonum : int\n Halo number in the last output to analyze.\n min_particles : int, optional\n Minimum number of particles of halos in tree.\n max_children : int, optional\n Maximum number of child halos each leaf can have.\n \"\"\"\n self.halonum = halonum\n self.max_children = max_children\n self.output_numbers = sorted(self.relationships, reverse=True)\n self.levels = {}\n trunk = self.output_numbers[0]\n self.levels[trunk] = [EnzoFOFMergerBranch(self, trunk, halonum,\n max_children)]\n self.generate_tree(min_particles, max_children)\n\n def filter_small_halos(self, lvl, min_particles):\n # Filter out children with less than min_particles\n for h in self.levels[lvl]:\n fil = []\n for c in h.children:\n if c[2] > min_particles: # c[2] = npart\n fil.append(c)\n h.children = fil\n\n def generate_tree(self, min_particles, max_children):\n self.filter_small_halos(self.output_numbers[0], min_particles)\n for i in range(1,len(self.output_numbers)):\n prev = self.output_numbers[i-1]\n this = self.output_numbers[i]\n self.levels[this] = []\n this_halos = [] # To check for duplicates\n for h in self.levels[prev]:\n for c in h.children:\n if c[0] in this_halos: continue\n if self.relationships[this] == {}: continue\n branch = EnzoFOFMergerBranch(self, this, c[0],\n max_children)\n self.levels[this].append(branch)\n this_halos.append(c[0])\n self.filter_small_halos(this, min_particles)\n\n def get_massive_progenitors(self, halonum, min_relation=0.25):\n r\"\"\"Returns a list of the most massive progenitor halos.\n\n This routine walks down the tree, following the most massive\n progenitor on each node.\n\n Parameters\n ----------\n halonum : int\n Halo number at the last output to trace.\n\n Returns\n -------\n output : dict\n Dictionary of redshifts, cycle numbers, and halo numbers\n of the most massive progenitor. keys = {redshift, cycle,\n halonum}\n \"\"\"\n output = {\"redshift\": [], \"cycle\": [], \"halonum\": []}\n # First (lowest redshift) node in tree\n halo0 = halonum\n for cycle in sorted(self.numbers, reverse=True):\n if cycle not in self.relationships: break\n if halo0 not in self.relationships[cycle]: break\n node = self.relationships[cycle][halo0]\n output[\"redshift\"].append(self.redshifts[cycle])\n output[\"cycle\"].append(cycle)\n output[\"halonum\"].append(halo0)\n # Find progenitor\n max_rel = 0.0\n for k,v in node.items():\n if not str(k).isdigit(): continue\n if v[1] > max_rel and v[1] > min_relation:\n halo0 = k\n max_rel = v[1]\n return output\n\n def print_tree(self):\n r\"\"\"Prints the merger tree to stdout.\n \"\"\"\n for lvl in sorted(self.levels, reverse=True):\n if lvl not in self.redshifts: continue\n print(\"========== Cycle %5.5d (z=%f) ==========\" % \\\n (lvl, self.redshifts[lvl]))\n for br in self.levels[lvl]:\n print(\"Parent halo = %d\" % br.halo_id)\n print(\"--> Most massive progenitor == Halo %d\" % \\\n (br.progenitor))\n for i,c in enumerate(br.children):\n if i > self.max_children: break\n print(\"--> Halo %8.8d :: fraction = %g\" % (c[0], c[1]))\n\n def save_halo_evolution(self, filename):\n \"\"\"\n Saves as an HDF5 file the relevant details about a halo\n over the course of its evolution following the most massive\n progenitor to have given it the bulk of its particles.\n It stores info from the FOF_groups file: location, mass, id, etc.\n \"\"\"\n f = h5py.File(\"%s/%s\" % (self.FOF_directory, filename), 'a')\n cycle_fin = sorted(list(self.redshifts.keys()))[-1]\n halo_id = self.levels[cycle_fin][0].halo_id\n halo = \"halo%05d\" % halo_id\n if halo in f:\n del f[\"halo%05d\" % halo_id]\n g = f.create_group(\"halo%05d\" % halo_id)\n size = len(self.redshifts)\n cycle = np.zeros(size)\n redshift = np.zeros(size)\n halo_id = np.zeros(size)\n fraction = np.zeros(size)\n mass = np.zeros(size)\n densest_point = np.zeros((3,size))\n COM = np.zeros((6,size))\n fraction[0] = 1.\n\n for i, lvl in enumerate(sorted(self.levels, reverse=True)):\n if len(self.levels[lvl]) == 0: # lineage for this halo ends\n cycle = cycle[:i] # so truncate arrays, and break\n redshift = redshift[:i] # Not big enough.\n halo_id = halo_id[:i]\n fraction = fraction[:i]\n mass = mass[:i]\n densest_point = densest_point[:,:i]\n COM = COM[:,:i]\n break \n if lvl not in self.redshifts: continue\n mylog.info(\"========== Cycle %5.5d (z=%f) ==========\" % \\\n (lvl, self.redshifts[lvl]))\n cycle[i] = lvl \n redshift[i] = self.redshifts[lvl]\n\n br = self.levels[lvl][0]\n mylog.info(\"Parent halo = %d\" % br.halo_id)\n mylog.info(\"-> Most massive progenitor == Halo %d\" % (br.progenitor))\n halo_id[i] = br.halo_id\n\n if len(br.children) == 0: # lineage for this halo ends \n cycle = cycle[:i+1] # (no children)\n redshift = redshift[:i+1] # so truncate arrays, and break\n halo_id = halo_id[:i+1]\n fraction = fraction[:i+1]\n mass = mass[:i+1]\n densest_point = densest_point[:,:i+1]\n COM = COM[:,:i+1]\n break \n\n if i < size-1:\n fraction[i+1] = br.children[0][1] \n\n # open up FOF file to parse for details\n filename = \"%s/groups_%05d.txt\" % (self.FOF_directory, lvl)\n mass[i], densest_point[:,i], COM[:,i] = \\\n grab_FOF_halo_info_internal(filename, br.halo_id)\n\n # save the arrays in the hdf5 file\n g.create_dataset(\"cycle\", data=cycle)\n g.create_dataset(\"redshift\", data=redshift)\n g.create_dataset(\"halo_id\", data=halo_id)\n g.create_dataset(\"fraction\", data=fraction)\n g.create_dataset(\"mass\", data=mass)\n g.create_dataset(\"densest_point\", data=densest_point)\n g.create_dataset(\"COM\", data=COM)\n f.close()\n\n def write_dot(self, filename=None):\n r\"\"\"Writes merger tree to a GraphViz or image file.\n\n Parameters\n ----------\n filename : str, optional\n Filename to write the GraphViz file. Default will be\n tree_halo%05i.gv, which is a text file in the GraphViz format.\n If filename is an image (e.g. \"MergerTree.png\") the output will\n be in the appropriate image format made by calling GraphViz\n automatically. See GraphViz (e.g. \"dot -v\")\n for a list of available output formats.\n \"\"\"\n if filename is None:\n filename = \"%s/tree_halo%5.5d.gv\" % \\\n (self.FOF_directory, self.halonum)\n # Create the pydot graph object.\n self.graph = pydot.Dot('galaxy', graph_type='digraph')\n self.halo_shape = \"rect\"\n self.z_shape = \"plaintext\"\n # Subgraphs to align levels\n self.subgs = {}\n for num in self.numbers:\n self.subgs[num] = pydot.Subgraph('', rank = 'same')\n self.graph.add_subgraph(self.subgs[num])\n sorted_lvl = sorted(self.levels, reverse=True)\n for ii,lvl in enumerate(sorted_lvl):\n # Since we get the cycle number from the key, it won't\n # exist for the last level, i.e. children of last level.\n # Get it from self.numbers.\n if ii < len(sorted_lvl)-1:\n next_lvl = sorted_lvl[ii+1]\n else:\n next_lvl = self.numbers[0]\n for br in self.levels[lvl]:\n for c in br.children:\n color = \"red\" if c[0] == br.progenitor else \"black\"\n self.graph.add_edge(pydot.Edge(\"C%d_H%d\" %(lvl, br.halo_id),\n \"C%d_H%d\" % (next_lvl, c[0]), color=color))\n #line = \" C%d_H%d -> C%d_H%d [color=%s];\\n\" % \\\n # (lvl, br.halo_id, next_lvl, c[0], color)\n \n #fp.write(line)\n for ii,lvl in enumerate(sorted_lvl):\n npart_max = 0\n for br in self.levels[lvl]:\n if br.npart > npart_max: npart_max = br.npart\n for br in self.levels[lvl]:\n halo_str = \"C%d_H%d\" % (lvl, br.halo_id)\n style = \"filled\" if br.npart == npart_max else \"solid\"\n self.graph.add_node(pydot.Node(halo_str,\n label = \"Halo %d\\\\n%d particles\" % (br.halo_id, br.npart),\n style = style, shape = self.halo_shape))\n # Add this node to the correct level subgraph.\n self.subgs[lvl].add_node(pydot.Node(halo_str))\n for lvl in self.numbers:\n # Don't add the z if there are no halos already in the subgraph.\n if len(self.subgs[lvl].get_node_list()) == 0: continue\n self.subgs[lvl].add_node(pydot.Node(\"%1.5e\" % self.redshifts[lvl],\n shape = self.z_shape, label = \"z=%0.3f\" % self.redshifts[lvl]))\n # Based on the suffix of the file name, write out the result to a file.\n suffix = filename.split(\".\")[-1]\n if suffix == \"gv\": suffix = \"raw\"\n mylog.info(\"Writing %s format %s to disk.\" % (suffix, filename))\n self.graph.write(\"%s\" % filename, format=suffix)\n\ndef find_halo_relationships(output1_id, output2_id, output_basename = None,\n radius = 0.10, external_FOF=True, \n FOF_directory='FOF'):\n r\"\"\"Calculate the parentage and child relationships between two EnzoFOF\n halo catalogs.\n\n This function performs a very simple merger tree calculation between two\n sets of halos. For every halo in the second halo catalog, it looks to the\n first halo catalog to find the parents by looking at particle IDs. The\n particle IDs from the child halos are identified in potential parents, and\n then both percent-of-parent and percent-to-child values are recorded.\n\n Note that this works with catalogs constructed by Enzo's FOF halo\n when used in external_FOF=True mode, whereas it will work with \n catalogs constructed by yt using external_FOF=False mode.\n\n Parameters\n ----------\n output1_id : int\n This is the integer output id of the (first) halo catalog to parse and\n load.\n output2_id : int\n This is the integer output id of the (second) halo catalog to parse and\n load.\n output_basename : string\n If provided, both .cpkl and .txt files containing the parentage\n relationships will be output.\n radius : float, default to 0.10\n In absolute units, the radius to examine when guessing possible\n parent/child relationships. If this value is too small, you will miss\n possible relationships.\n FOF_directory : str, optional\n Directory where FOF files are located\n\n Returns\n -------\n pfrac : dict\n This is a dict of dicts. The first key is the parent halo id, the\n second is the child halo id. The values are the percent contributed\n from parent to child and the percent of a child that came from the\n parent.\n \"\"\"\n mylog.info(\"Parsing Halo Catalog %04i\", output1_id)\n HC1 = HaloCatalog(output1_id, False, external_FOF=external_FOF, \\\n FOF_directory=FOF_directory)\n mylog.info(\"Parsing Halo Catalog %04i\", output2_id)\n HC2 = HaloCatalog(output2_id, True, external_FOF=external_FOF, \\\n FOF_directory=FOF_directory)\n mylog.info(\"Calculating fractions\")\n pfrac = HC1.calculate_parentage_fractions(HC2)\n\n if output_basename is not None and pfrac != {}:\n f = open(\"%s.txt\" % (output_basename), \"w\")\n for hid1 in sorted(pfrac):\n for hid2 in sorted(pfrac[hid1]):\n if not str(hid2).isdigit(): continue\n p1, p2, npart = pfrac[hid1][hid2]\n if p1 == 0.0: continue\n f.write( \"Halo %s (%s) contributed %0.3e of its particles to %s (%s), which makes up %0.3e of that halo\\n\" % (\n hid1, output1_id, p2, hid2, output2_id, p1))\n f.close()\n\n cPickle.dump(pfrac, open(\"%s.cpkl\" % (output_basename), \"wb\"))\n\n return HC1.redshift, HC2.redshift, pfrac\n\ndef grab_FOF_halo_info_internal(filename, halo_id):\n \"\"\"\n Finds a specific halo's information in the FOF group output information\n and pass relevant parameters to caller.\n \"\"\"\n # open up FOF file to parse for details\n groups_file = open(filename, 'r')\n for line in groups_file:\n if line.startswith(\"#\"): continue\n if int(line.split()[0]) == halo_id:\n ar = np.array(line.split()).astype('float64')\n return ar[1], ar[4:7], ar[7:13] # mass, xyz_dens, xyzvxvyvz_COM\n\ndef plot_halo_evolution(filename, halo_id, x_quantity='cycle', y_quantity='mass',\n x_log=False, y_log=True, FOF_directory='FOF'):\n \"\"\"\n Once you have generated a file using the \n EnzoFOFMergerTree.save_halo_evolution function, this is a simple way of \n plotting the evolution in the quantities of that halo over its lifetime.\n\n Parameters\n ----------\n filename : str\n The filename to which you saved the hdf5 data from save_halo_evolution\n halo_id : int\n The halo in 'filename' that you want to follow\n x_quantity : str, optional\n The quantity that you want to plot as the x_coord.\n Valid options are:\n\n * cycle\n * mass\n * fraction\n * halo_id\n * redshift\n * dense_x\n * dense_y\n * dense_z\n * COM_x\n * COM_y\n * COM_z\n * COM_vx\n * COM_vy\n * COM_vz\n\n y_quantity : str, optional\n The quantity that you want to plot as the y_coord.\n x_log : bool, optional\n Do you want the x-axis to be in log or linear?\n y_log : bool, optional\n Do you want the y-axis to be in log or linear?\n FOF_directory : str, optional\n Directory where FOF files (and hdf file) are located\n\n Examples\n --------\n\n >>> # generates mass history plots for the 20 most massive halos at t_fin.\n >>> ts = DatasetSeries.from_filenames(\"DD????/DD????\")\n >>> # long step--must run FOF on each DD, but saves outputs for later use\n >>> for ds in ts: \n ... halo_list = FOFHaloFinder(ds)\n ... i = int(ds.basename[2:])\n ... halo_list.write_out(\"FOF/groups_%05i.txt\" % i)\n ... halo_list.write_particle_lists(\"FOF/particles_%05i\" % i)\n ...\n >>> mt = EnzoFOFMergerTree(external_FOF=False)\n >>> for i in range(20):\n ... mt.build_tree(i)\n ... mt.save_halo_evolution('halos.h5')\n ...\n >>> for i in range(20):\n ... plot_halo_evolution('halos.h5', i)\n \"\"\"\n import matplotlib.pyplot as plt\n f = h5py.File(\"%s/%s\" % (FOF_directory, filename), 'r')\n basename = os.path.splitext(filename)[0]\n halo = \"halo%05d\" % halo_id\n basename = basename + \"_\" + halo\n g = f[halo]\n values = list(g)\n index_dict = {'x' : 0, 'y' : 1, 'z' : 2, 'vx' : 3, 'vy' : 4, 'vz' : 5}\n coords = {}\n fields = {}\n for i, quantity in enumerate((x_quantity, y_quantity)):\n field = quantity\n if quantity.startswith('COM'):\n index = index_dict[quantity.split('_')[-1]]\n quantity = ('COM')\n if quantity.startswith('dense'):\n index = index_dict[quantity.split('_')[-1]]\n quantity = ('densest_point')\n if quantity not in values:\n exit('%s not in list of values in %s for halo %d' % \\\n (quantity, filename, halo_id))\n if not field == quantity:\n coords[i] = g[quantity][index,:]\n else:\n coords[i] = g[quantity]\n if len(coords[i]) == 1: \n # (\"Only 1 value for Halo %d. Ignoring.\" % halo_id)\n return\n fields[i] = field\n\n ax = plt.axes()\n ax.plot(coords[0], coords[1])\n ax.set_title(basename)\n ax.set_xlabel(fields[0])\n ax.set_ylabel(fields[1])\n if x_log:\n ax.set_xscale(\"log\")\n if y_log:\n ax.set_yscale(\"log\")\n ofn = \"%s/%s_%s_%s.png\" % (FOF_directory, basename, fields[0], fields[1])\n plt.savefig(ofn)\n plt.clf()\n"
] |
[
[
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.axes",
"numpy.intersect1d",
"matplotlib.pyplot.clf",
"numpy.array",
"numpy.zeros"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
nemodrive/car_data_collection
|
[
"8a8bf9381edb95ca3da2c0dea37ede70d778e1a3"
] |
[
"visualize.py"
] |
[
"# Andrei, 2018\n\"\"\"\n Collect data.\n\"\"\"\nimport matplotlib\nmatplotlib.use('TkAgg') # <-- THIS MAKES IT FAST!\n\nfrom argparse import ArgumentParser\nimport numpy as np\nimport cv2\nimport os\nimport time\n\nfrom utils import read_cfg\nfrom get_camera import async_camera_draw\nimport matplotlib.pyplot as plt\n\nfrom can_utils import validate_data as validate_can_data\nfrom can_utils import CanPlot\n\nfrom phone_data_utils import validate_data as validate_phone_data\nfrom phone_data_utils import PhonePlot\nfrom multiprocessing import Process, Queue\n\nplt.ion() ## Note this correction\n\nCAN_PLOT_TIME = 5000\nFONT_SCALE = 1.0\nFONT = cv2.FONT_HERSHEY_PLAIN\nFONT_COLOR = (0, 255, 0)\n\nCFG_FILE = \"cfg.yaml\"\nCFG_EXTRA_FILE = \"cfg_extra.yaml\"\n\nPLAYBACK_FACTOR = 2\nCV_WAIT_KEY_TIME = 1\n\nif __name__ == \"__main__\":\n arg_parser = ArgumentParser()\n\n arg_parser.add_argument(dest='experiment_path', help='Path to experiment to visualize.')\n arg_parser.add_argument('--camera-view-size', default=400, type=int, dest=\"camera_view_size\")\n arg_parser.add_argument('--start-tp', default=0, type=float, dest=\"start_tp\")\n\n arg_parser = arg_parser.parse_args()\n\n experiment_path = arg_parser.experiment_path\n camera_view_size = arg_parser.camera_view_size\n start_tp = arg_parser.start_tp\n\n cfg = read_cfg(os.path.join(experiment_path, CFG_FILE))\n cfg_extra = read_cfg(os.path.join(experiment_path, CFG_EXTRA_FILE))\n\n collect = cfg.collect\n record_timestamp = cfg.recorded_min_max_tp\n common_min_max_tp = cfg.common_min_max_tp\n\n video_loders = []\n obd_loader = None\n can_plot = None\n phone_plot = None\n plot_stuff = False\n live_plot = True\n\n processes = []\n recv_queue = Queue()\n recv_processes = []\n send_queues = []\n\n ref_tp = 0 # Main camera reference timestamp\n if collect.camera:\n camera_names = [\"camera_{}\".format(x) for x in cfg.camera.ids]\n camera_cfgs = [getattr(cfg.camera, x) for x in camera_names]\n extra_camera_cfgs = [getattr(cfg_extra, x) for x in camera_names]\n\n with open(f\"{experiment_path}/{camera_names[0]}_timestamp\") as infile:\n lines = infile.readlines()\n ref_tp = float(lines[0])\n\n # Async mode\n video_loders = []\n for camera_name in camera_names:\n\n cfg_camera = getattr(cfg_extra, camera_name)\n camera_view_size = camera_view_size\n flip_view = getattr(cfg.camera, camera_name).flip\n\n video_plot = Queue()\n\n p = Process(target=async_camera_draw,\n args=(experiment_path, camera_name, cfg_camera, camera_view_size,\n flip_view, video_plot, recv_queue))\n processes.append(p)\n video_loders.append(video_plot)\n send_queues.append(video_plot)\n recv_processes.append(\"camera_name\")\n\n # video_loders = [VideoLoad(experiment_path, x, getattr(cfg_extra, x),\n # view_height=camera_view_size,\n # flip_view=getattr(cfg.camera, x).flip) for x in camera_names]\n #\n\n # Not working in python 2.7\n # if collect.obd:\n # obd_loader = OBDLoader(experiment_path)\n\n plt.ion()\n if plot_stuff:\n plt.show()\n\n print(\"=\" * 70)\n if collect.can:\n print(\"=\" * 30, \"Validate can data\", \"=\" * 30)\n validate_can_data(experiment_path)\n key = input(\"Press key to continue ...\")\n print(\"\")\n\n print(\"=\" * 70)\n if collect.phone:\n print(\"=\" * 30, \"Validate phone data\", \"=\" * 30)\n validate_phone_data(experiment_path)\n key = input(\"Press key to continue ...\")\n print(\"\")\n\n if live_plot:\n if collect.can:\n print(\"=\" * 70, \"Can\")\n plot_stuff = True\n can_plot = CanPlot(experiment_path)\n\n # # ASYNC MODE [ Not working because of matplotlib ]\n # can_plot = Queue()\n #\n # p = Process(target=async_can_plot,\n # args=(experiment_path, can_plot, recv_queue))\n # processes.append(p)\n # send_queues.append(can_plot)\n # recv_processes.append(\"can\")\n\n # key = input(\"Press key to continue ...\")\n print(\"\")\n\n if collect.phone:\n print(\"=\" * 70, \"Phone\")\n plot_stuff = True\n phone_plot = PhonePlot(experiment_path)\n\n # # ASYNC MODE [ Not working because of matplotlib ]\n # phone_plot = Queue()\n #\n # p = Process(target=async_phone_plot,\n # args=(experiment_path, phone_plot, recv_queue))\n # processes.append(p)\n # send_queues.append(phone_plot)\n # recv_processes.append(\"phone\")\n\n # key = input(\"Press key to continue ...\")\n print(\"\")\n\n for p in processes:\n p.start()\n\n print(\"=\" * 70, \"Start\")\n\n freq_tp = [1/30., 1/10., 1/5., 1/3., 1/2., 1., 2., 5., 10.]\n freq_id = 0\n freq = freq_tp[freq_id]\n r = None\n crt_tp = common_min_max_tp[0] #+ 60.\n if start_tp != 0:\n crt_tp = start_tp\n\n print (\"START factor: --->\")\n print (crt_tp)\n print (\"------------------\")\n\n live_play = False\n key_wait_time = 0\n playback_speed = 1.\n playback_factor = PLAYBACK_FACTOR\n\n # -- Define menu\n\n # Menu functions\n def increase_tp():\n global crt_tp\n global freq\n crt_tp += freq\n\n def decrease_tp():\n global crt_tp\n global freq\n crt_tp -= freq\n\n def change_freq():\n global freq\n global freq_id\n freq_id = (freq_id + 1) % len(freq_tp)\n freq = freq_tp[freq_id]\n print(\"New frequency: {}\".format(freq))\n\n def toggle_play():\n global live_play\n global key_wait_time\n live_play = not live_play\n key_wait_time = CV_WAIT_KEY_TIME if live_play else 0\n\n def increase_playback_speed():\n global playback_speed\n playback_speed = playback_speed * playback_factor\n\n def decrease_playback_speed():\n global playback_speed\n playback_speed = playback_speed / playback_factor\n\n menu = dict({\n 27: (quit, \"Key [ESC]: Exit\"), # if the 'ESC' key is pressed, Quit\n ord('l'): (change_freq, \"Key [ l ]: Change freq\"),\n ord('\\''): (increase_tp, \"Key [ \\'; ]: Increase tp by freq\"),\n ord(';'): (decrease_tp, \"Key [ ; ]: Decrease tp by freq\"),\n\n ord('p'): (toggle_play, \"Key [ p ]: Toggle Live play\"),\n ord(']'): (increase_playback_speed, \"Key [ ] ]: Increase playback speed (*{})\"),\n ord('['): (decrease_playback_speed, \"Key [ [ ]: Decrease playback speed\"),\n })\n\n menu_text = \"\\n\".join([x[1] for x in menu.values()])\n\n # SHOW menu\n\n show_menu = True\n cursor_img = np.zeros((300, 300, 3)).astype(np.uint8)\n\n\n def get_key(wait_time, tp=0):\n if show_menu:\n y0, dy = 10, 25\n cursor_img = np.zeros((300, 300, 3)).astype(np.uint8)\n new_text = menu_text + f\"\\nTP:{tp}\"\n for i, line in enumerate(new_text.split('\\n')):\n y = y0 + i * dy\n cv2.putText(cursor_img, line, (50, y), FONT, FONT_SCALE, FONT_COLOR)\n\n cv2.imshow(\"Cursor\", cursor_img)\n k = cv2.waitKey(wait_time)\n # r = chr(k % 256)\n r = k & 0xFF\n return r\n\n while r != \"q\":\n prev_tp = time.time()\n key = get_key(key_wait_time, tp=crt_tp)\n # plt.clf()\n\n if key == 27:\n break\n if key in menu.keys():\n menu[key][0]()\n elif key != 255:\n print(\"Unknown key: {}\".format(key))\n\n # if collect.obd:\n # obd_data = obd_loader.get_closest(crt_tp)\n if collect.can:\n # can_plot.put(crt_tp)\n can_r = can_plot.plot(crt_tp)\n # crt_steer, crt_speed = (np.random.rand() - 0.5) * 500, None\n crt_steer, crt_speed = None, None\n\n if \"steer\" in can_r:\n crt_steer = can_r[\"steer\"][\"steer\"]\n if \"speed\" in can_r:\n crt_speed = can_r[\"speed\"][\"mps\"]\n\n if collect.camera:\n for v in video_loders:\n v.put([0, crt_tp, crt_steer])\n # dif_tp, frame = v.get_closest(crt_tp)\n # v.show(frame)\n\n if collect.phone:\n # phone_plot.put(crt_tp)\n phone_plot.plot(crt_tp)\n\n # # send bulk messages to Queus\n # for send_queue in send_queues:\n # send_queue.put(crt_tp)\n\n # TODO Plot magnetometer\n\n if plot_stuff:\n plt.show()\n plt.pause(0.0000001) # Note this correction\n\n recv_sync = 0\n responses = []\n while len(responses) < len(recv_processes):\n r = recv_queue.get()\n responses.append(r)\n\n if live_play:\n crt_tp += (time.time() - prev_tp) * playback_factor\n\n print(f\"crt_tp: {crt_tp} ({crt_tp - ref_tp}) \\t Steer: {crt_steer} \\t speed: {crt_speed}\")\n\n for q in send_queues:\n q.put(-1)\n\n for p in processes:\n p.join()\n"
] |
[
[
"matplotlib.use",
"matplotlib.pyplot.ion",
"numpy.zeros",
"matplotlib.pyplot.pause",
"matplotlib.pyplot.show"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
MustafaTheCoder/OpenCV-Cheat-Sheet
|
[
"437c00c84d6699052f025ac0470d719b0d298723",
"437c00c84d6699052f025ac0470d719b0d298723"
] |
[
"shapes/line.py",
"functions/dialation_image.py"
] |
[
"import cv2\nimport numpy as np\n\nimg = np.zeros((512,512,3), np.uint8)\n\n\"\"\"\nNow as you can see this concept is a little bit difficult to understand but lets break it \ninto pieces the first parameter here is the image that will be used to draw a line on, the\nsecond paramenter is the start point of the line, the third paramenter is the ending point \nof the line, after it the forth parameter is the color of the line, and the last one is the \nthickness of the line (Not Important)\n\"\"\"\ncv2.line(img, (0,0), (300,300), (255, 0, 0), 5)\n\n\n# Displaying the output\ncv2.imshow(\"Output\", img)\n# Adding delay to the image\ncv2.waitKey(0)",
"import cv2\nimport numpy as np\n\nimg = cv2.imread(\"resources/example.jpg\")\nkernal = np.ones((2, 2), np.uint8)\n\n\"\"\"\nWhat this function does it makes the edges of the picture thick \nso that the canny function can process them in a better way, and also\nnumpy is used here in the kernal variable to do that main part which is \ndeciding the amount of thinkness needed for canny to process the lines of \nthe edges in a better way\n\"\"\" \nimgCanny = cv2.Canny(img, 150, 200)\nimgDialation = cv2.dilate(imgCanny, kernal)\n\n# Displaying the output\ncv2.imshow(\"Output\", imgDialation)\n# Adding delay to the image\ncv2.waitKey(0)"
] |
[
[
"numpy.zeros"
],
[
"numpy.ones"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
dromosys/open-solution-home-credit
|
[
"3d4cc129727c2cef16629af372ad8a9c9f14f83c"
] |
[
"src/utils.py"
] |
[
"import logging\nimport os\nimport random\nimport sys\nimport multiprocessing as mp\nfrom functools import reduce\n\nimport glob\nimport numpy as np\nimport pandas as pd\nfrom tqdm import tqdm\nimport yaml\nfrom attrdict import AttrDict\n\n\ndef create_submission(meta, predictions):\n submission = pd.DataFrame({'SK_ID_CURR': meta['SK_ID_CURR'].tolist(),\n 'TARGET': predictions\n })\n return submission\n\n\ndef verify_submission(submission, sample_submission):\n assert submission.shape == sample_submission.shape, \\\n 'Expected submission to have shape {} but got {}'.format(sample_submission.shape, submission.shape)\n\n for submission_id, correct_id in zip(submission['SK_ID_CURR'].values, sample_submission['SK_ID_CURR'].values):\n assert correct_id == submission_id, \\\n 'Wrong id: expected {} but got {}'.format(correct_id, submission_id)\n\n\ndef get_logger():\n return logging.getLogger('home-credit')\n\n\ndef init_logger():\n logger = logging.getLogger('home-credit')\n logger.setLevel(logging.INFO)\n message_format = logging.Formatter(fmt='%(asctime)s %(name)s >>> %(message)s',\n datefmt='%Y-%m-%d %H-%M-%S')\n\n # console handler for validation info\n ch_va = logging.StreamHandler(sys.stdout)\n ch_va.setLevel(logging.INFO)\n\n ch_va.setFormatter(fmt=message_format)\n\n # add the handlers to the logger\n logger.addHandler(ch_va)\n\n return logger\n\n\ndef read_params(ctx, fallback_file):\n if ctx.params.__class__.__name__ == 'OfflineContextParams':\n neptune_config = read_yaml(fallback_file)\n params = neptune_config.parameters\n else:\n params = ctx.params\n return params\n\n\ndef read_yaml(filepath):\n with open(filepath) as f:\n config = yaml.load(f)\n return AttrDict(config)\n\n\ndef parameter_eval(param):\n try:\n return eval(param)\n except Exception:\n return param\n\n\ndef persist_evaluation_predictions(experiment_directory, y_pred, raw_data, id_column, target_column):\n raw_data.loc[:, 'y_pred'] = y_pred.reshape(-1)\n predictions_df = raw_data.loc[:, [id_column, target_column, 'y_pred']]\n filepath = os.path.join(experiment_directory, 'evaluation_predictions.csv')\n logging.info('evaluation predictions csv shape: {}'.format(predictions_df.shape))\n predictions_df.to_csv(filepath, index=None)\n\n\ndef set_seed(seed=90210):\n random.seed(seed)\n np.random.seed(seed)\n\n\ndef calculate_rank(predictions):\n rank = (1 + predictions.rank().values) / (predictions.shape[0] + 1)\n return rank\n\n\ndef chunk_groups(groupby_object, chunk_size):\n n_groups = groupby_object.ngroups\n group_chunk, index_chunk = [], []\n for i, (index, df) in enumerate(groupby_object):\n group_chunk.append(df)\n index_chunk.append(index)\n\n if (i + 1) % chunk_size == 0 or i + 1 == n_groups:\n group_chunk_, index_chunk_ = group_chunk.copy(), index_chunk.copy()\n group_chunk, index_chunk = [], []\n yield index_chunk_, group_chunk_\n\n\ndef parallel_apply(groups, func, index_name='Index', num_workers=1, chunk_size=10000):\n n_chunks = np.ceil(1.0 * groups.ngroups / chunk_size)\n indeces, features = [], []\n num_workers=4\n print('exec chunk_size:' + str(chunk_size) + ' num_workers:' + str(num_workers))\n for index_chunk, groups_chunk in tqdm(chunk_groups(groups, chunk_size), total=n_chunks):\n with mp.pool.Pool(num_workers) as executor:\n features_chunk = executor.map(func, groups_chunk)\n features.extend(features_chunk)\n indeces.extend(index_chunk)\n\n features = pd.DataFrame(features)\n features.index = indeces\n features.index.name = index_name\n return features\n\n\ndef read_oof_predictions(prediction_dir, train_filepath, id_column, target_column):\n labels = pd.read_csv(train_filepath, usecols=[id_column, target_column])\n\n filepaths_train, filepaths_test = [], []\n for filepath in sorted(glob.glob('{}/*'.format(prediction_dir))):\n if filepath.endswith('_oof_train.csv'):\n filepaths_train.append(filepath)\n elif filepath.endswith('_oof_test.csv'):\n filepaths_test.append(filepath)\n\n train_dfs = []\n for filepath in filepaths_train:\n train_dfs.append(pd.read_csv(filepath))\n train_dfs = reduce(lambda df1, df2: pd.merge(df1, df2, on=[id_column, 'fold_id']), train_dfs)\n train_dfs.columns = _clean_columns(train_dfs, keep_colnames=[id_column, 'fold_id'])\n train_dfs = pd.merge(train_dfs, labels, on=[id_column])\n\n test_dfs = []\n for filepath in filepaths_test:\n test_dfs.append(pd.read_csv(filepath))\n test_dfs = reduce(lambda df1, df2: pd.merge(df1, df2, on=[id_column, 'fold_id']), test_dfs)\n test_dfs.columns = _clean_columns(test_dfs, keep_colnames=[id_column, 'fold_id'])\n return train_dfs, test_dfs\n\n\ndef _clean_columns(df, keep_colnames):\n new_colnames = keep_colnames\n feature_colnames = df.drop(keep_colnames, axis=1).columns\n for i, colname in enumerate(feature_colnames):\n new_colnames.append('model_{}'.format(i))\n return new_colnames\n\ndef safe_div(a, b):\n try:\n return float(a) / float(b)\n except:\n return 0.0\n"
] |
[
[
"pandas.merge",
"pandas.read_csv",
"numpy.random.seed",
"pandas.DataFrame",
"numpy.ceil"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
ByzanTine/backdoor
|
[
"fe3384f1fd7ebfbde2da783823a68ae258ca2896"
] |
[
"utils_backdoor.py"
] |
[
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Date : 2018-11-05 11:30:01\n# @Author : Bolun Wang ([email protected])\n# @Link : http://cs.ucsb.edu/~bolunwang\n\n\nimport tensorflow as tf\nimport numpy as np\nfrom keras.preprocessing import image\nimport h5py\n\n\ndef dump_image(x, filename, format):\n\n img = image.array_to_img(x, scale=False)\n img.save(filename, format)\n\n return\n\n\ndef fix_gpu_memory(mem_fraction=1):\n\n import keras.backend as K\n\n gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=mem_fraction)\n tf_config = tf.ConfigProto(gpu_options=gpu_options)\n tf_config.gpu_options.allow_growth = True\n tf_config.log_device_placement = False\n tf_config.allow_soft_placement = True\n init_op = tf.global_variables_initializer()\n sess = tf.Session(config=tf_config)\n sess.run(init_op)\n K.set_session(sess)\n\n return sess\n\n\ndef load_dataset(data_filename, keys=None):\n\n ''' assume all datasets are numpy arrays '''\n dataset = {}\n with h5py.File(data_filename) as hf:\n if keys is None:\n for name in hf:\n dataset[name] = np.array(hf.get(name))\n else:\n for name in keys:\n dataset[name] = np.array(hf.get(name))\n\n return dataset\n"
] |
[
[
"tensorflow.ConfigProto",
"tensorflow.global_variables_initializer",
"tensorflow.GPUOptions",
"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"
]
}
] |
jnice-81/dace
|
[
"5211794a2d17b7189037ac485ab0b292fb02aa0d",
"5211794a2d17b7189037ac485ab0b292fb02aa0d",
"5211794a2d17b7189037ac485ab0b292fb02aa0d",
"5211794a2d17b7189037ac485ab0b292fb02aa0d",
"5211794a2d17b7189037ac485ab0b292fb02aa0d",
"5211794a2d17b7189037ac485ab0b292fb02aa0d",
"5211794a2d17b7189037ac485ab0b292fb02aa0d",
"5211794a2d17b7189037ac485ab0b292fb02aa0d"
] |
[
"samples/distributed/explicit/poly_gemm_bc.py",
"tests/fpga/multibank_reduce_fpga_test.py",
"samples/fpga/gemm_systolic_vectorized.py",
"tests/halfvec_cudatest.py",
"tests/fpga/memory_buffering_test.py",
"tests/fpga/veclen_conversion_connector_test.py",
"tests/parallel_sections_test.py",
"dace/libraries/stencil/intel_fpga.py"
] |
[
"# Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved.\n\"\"\" Explicitly distributed Gemm sample with block-cyclic distribution.\"\"\"\nimport dace as dc\nimport numpy as np\nimport os\nimport timeit\nfrom dace.sdfg.utils import load_precompiled_sdfg\nfrom mpi4py import MPI\n\nlNI = dc.symbol('lNI', dtype=dc.int64, integer=True, positive=True)\nlNJ = dc.symbol('lNJ', dtype=dc.int64, integer=True, positive=True)\nlNKa = dc.symbol('lNKa', dtype=dc.int64, integer=True, positive=True)\nlNKb = dc.symbol('lNKb', dtype=dc.int64, integer=True, positive=True)\nPx = dc.symbol('Px', dtype=dc.int32, integer=True, positive=True)\nPy = dc.symbol('Py', dtype=dc.int32, integer=True, positive=True)\nBx = dc.symbol('Bx', dtype=dc.int32, integer=True, positive=True)\nBy = dc.symbol('By', dtype=dc.int32, integer=True, positive=True)\n\nNI = lNI * Px\nNJ = lNJ * Py\nNK = lNKa * Py # == lNKb * Px\n\n\ndef relerr(ref, val):\n return np.linalg.norm(ref - val) / np.linalg.norm(ref)\n\n\[email protected]\ndef gemm_shared(alpha: dc.float64, beta: dc.float64, C: dc.float64[NI, NJ],\n A: dc.float64[NI, NK], B: dc.float64[NK, NJ]):\n\n C[:] = alpha * A @ B + beta * C\n\n\[email protected]\ndef gemm_distr(alpha: dc.float64, beta: dc.float64, C: dc.float64[NI, NJ],\n A: dc.float64[NI, NK], B: dc.float64[NK, NJ]):\n\n lA = np.empty((lNI, lNKa), dtype=A.dtype)\n lB = np.empty((lNKb, lNJ), dtype=B.dtype)\n lC = np.empty((lNI, lNJ), dtype=A.dtype)\n\n Av = np.reshape(A, (Px, lNI, Py, lNKa))\n A2 = np.transpose(Av, axes=(0, 2, 1, 3))\n Bv = np.reshape(B, (Px, lNKb, Py, lNJ))\n B2 = np.transpose(Bv, axes=(0, 2, 1, 3))\n Cv = np.reshape(C, (Px, lNI, Py, lNJ))\n C2 = np.transpose(Cv, axes=(0, 2, 1, 3))\n dc.comm.Scatter(A2, lA)\n dc.comm.Scatter(B2, lB)\n dc.comm.Scatter(C2, lC)\n\n tmp = distr.MatMult(lA, lB, (NI, NJ, NK))\n\n lC[:] = alpha * tmp + beta * lC\n\n dc.comm.Gather(lC, C2)\n C[:] = np.transpose(C2, (0, 2, 1, 3))\n\n\[email protected]\ndef gemm_distr2(alpha: dc.float64, beta: dc.float64, C: dc.float64[lNI, lNJ],\n A: dc.float64[lNI, lNKa], B: dc.float64[lNKb, lNJ]):\n\n tmp = distr.MatMult(A, B, (lNI * Px, lNJ * Py, NK))\n C[:] = alpha * tmp + beta * C\n\n\[email protected]\ndef gemm_distr3(alpha: dc.float64, beta: dc.float64, C: dc.float64[lNI, lNJ],\n A: dc.float64[lNI, lNKa], B: dc.float64[lNKb, lNJ]):\n\n tmp = distr.MatMult(A, B, (lNI * Px, lNJ * Py, NK), (Bx, By), (Bx, By))\n C[:] = alpha * tmp + beta * C\n\n\ndef init_data(NI, NJ, NK, datatype):\n\n alpha = datatype(1.5)\n beta = datatype(1.2)\n rng = np.random.default_rng(42)\n C = np.zeros((NI, NJ), dtype=datatype)\n A = np.arange(0, NI * NK, dtype=datatype).reshape(NI, NK)\n B = np.arange(NI * NK, NI * NK + NK * NJ, dtype=datatype).reshape(NK, NJ)\n\n return alpha, beta, C, A, B\n\n\ndef time_to_ms(raw):\n return int(round(raw * 1000))\n\n\ngrid = {1: (1, 1), 2: (2, 1), 4: (2, 2), 8: (4, 2), 16: (4, 4)}\n\nif __name__ == \"__main__\":\n\n # Initialization\n NI, NJ, NK = 4096, 4096, 4096\n\n comm = MPI.COMM_WORLD\n rank = comm.Get_rank()\n size = comm.Get_size()\n Px, Py = grid[size]\n Bx, By = 128, 128\n lNI = NI // Px\n lNJ = NJ // Py\n lNKa = NK // Py\n lNKb = NK // Px\n\n BI = NI // (Px * Bx)\n BJ = NJ // (Py * By)\n BKa = NK // (Py * By)\n BKb = NK // (Px * Bx)\n\n def setup_func(rank):\n if rank == 0:\n return init_data(NI, NJ, NK, np.float64)\n else:\n return (1.5, 1.2, None, None, None)\n\n alpha, beta, C, A, B = setup_func(rank)\n\n lA = np.empty((lNI, lNKa), dtype=np.float64)\n lB = np.empty((lNKb, lNJ), dtype=np.float64)\n lC = np.empty((lNI, lNJ), dtype=np.float64)\n\n A2, B2, C2 = None, None, None\n if rank == 0:\n\n A2 = np.empty((Px, Py, lNI, lNKa), dtype=np.float64)\n for pi in range(Px):\n for pj in range(Py):\n for li in range(BI):\n for lj in range(BKa):\n si = (pi + li * Px) * Bx\n sj = (pj + lj * Py) * By\n A2[pi, pj, li * Bx:li * Bx + Bx,\n lj * By:lj * By + By] = A[si:si + Bx, sj:sj + By]\n\n B2 = np.empty((Px, Py, lNKb, lNJ), dtype=np.float64)\n for pi in range(Px):\n for pj in range(Py):\n for li in range(BKb):\n for lj in range(BJ):\n si = (pi + li * Px) * Bx\n sj = (pj + lj * Py) * By\n B2[pi, pj, li * Bx:li * Bx + Bx,\n lj * By:lj * By + By] = B[si:si + Bx, sj:sj + By]\n\n C2 = np.empty((Px, Py, lNI, lNJ), dtype=np.float64)\n for pi in range(Px):\n for pj in range(Py):\n for li in range(BI):\n for lj in range(BJ):\n si = (pi + li * Px) * Bx\n sj = (pj + lj * Py) * By\n C2[pi, pj, li * Bx:li * Bx + Bx,\n lj * By:lj * By + By] = C[si:si + Bx, sj:sj + By]\n\n comm.Scatter(A2, lA)\n comm.Scatter(B2, lB)\n comm.Scatter(C2, lC)\n\n tC = np.copy(lC)\n\n mpi_sdfg = None\n if rank == 0:\n mpi_sdfg = gemm_distr3.to_sdfg(strict=False)\n mpi_sdfg.apply_strict_transformations()\n mpi_func = mpi_sdfg.compile()\n comm.Barrier()\n if rank > 0:\n build_folder = dc.Config.get('default_build_folder')\n mpi_func = load_precompiled_sdfg(\n os.path.join(build_folder, gemm_distr3.name))\n\n ldict = locals()\n\n comm.Barrier()\n\n mpi_func(A=lA,\n B=lB,\n C=tC,\n alpha=alpha,\n beta=beta,\n NI=NI,\n NJ=NJ,\n NK=NK,\n lNI=lNI,\n lNJ=lNJ,\n lNKa=lNKa,\n lNKb=lNKb,\n Px=Px,\n Py=Py,\n Bx=Bx,\n By=By)\n\n comm.Gather(tC, C2)\n if rank == 0:\n for pi in range(Px):\n for pj in range(Py):\n for li in range(BI):\n for lj in range(BJ):\n si = (pi + li * Px) * Bx\n sj = (pj + lj * Py) * By\n C[si:si + Bx,\n sj:sj + By] = C2[pi, pj, li * Bx:li * Bx + Bx,\n lj * By:lj * By + By]\n\n comm.Barrier()\n\n stmt = (\"mpi_func(A=lA, B=lB, C=tC, alpha=alpha, beta=beta, \"\n \"NI=NI, NJ=NJ, NK=NK, lNI=lNI, lNJ=lNJ, lNKa=lNKa, lNKb=lNKb, \"\n \"Px=Px, Py=Py, Bx=Bx, By=By)\")\n setup = \"tC = np.copy(lC); comm.Barrier()\"\n repeat = 10\n\n raw_time_list = timeit.repeat(stmt,\n setup=setup,\n repeat=repeat,\n number=1,\n globals=ldict)\n raw_time = np.median(raw_time_list)\n\n comm.Barrier()\n\n if rank == 0:\n ms_time = time_to_ms(raw_time)\n print(\"Median is {}ms\".format(ms_time))\n\n alpha, beta, refC, refA, refB = init_data(NI, NJ, NK, np.float64)\n shared_sdfg = gemm_shared.compile()\n shared_sdfg(A=refA,\n B=refB,\n C=refC,\n alpha=alpha,\n beta=beta,\n NI=NI,\n NJ=NJ,\n NK=NK,\n lNI=lNI,\n lNJ=lNJ,\n lNKa=lNKa,\n lNKb=lNKb,\n Px=Px,\n Py=Py)\n\n print(\"=======Validation=======\")\n assert (np.allclose(C, refC))\n print(\"OK\")\n",
"# Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved.\n\nimport dace\nfrom dace import subsets\nfrom dace.fpga_testing import xilinx_test\nimport numpy as np\n\n# A test checking wcr-reduction with HBM/DDR arrays as inputs and output\n\n\ndef create_multibank_reduce_sdfg(\n name,\n mem_type,\n banks=2,\n):\n N = dace.symbol(\"N\")\n M = dace.symbol(\"M\")\n\n sdfg = dace.SDFG(name + \"_\" + mem_type)\n state = sdfg.add_state('red_' + mem_type, True)\n\n in1 = sdfg.add_array(\"in1\", [banks, N, M], dace.float32)\n in2 = sdfg.add_array(\"in2\", [banks, N, M], dace.float32)\n out = sdfg.add_array(\"out\", [banks, N], dace.float32)\n in1[1].location[\"memorytype\"] = mem_type\n in2[1].location[\"memorytype\"] = mem_type\n out[1].location[\"memorytype\"] = mem_type\n in1[1].location[\"bank\"] = f\"0:{banks}\"\n in2[1].location[\"bank\"] = f\"{banks}:{2*banks}\"\n out[1].location[\"bank\"] = f\"{2*banks}:{3*banks}\"\n\n read_in1 = state.add_read(\"in1\")\n read_in2 = state.add_read(\"in2\")\n out_write = state.add_write(\"out\")\n tmp_in1_memlet = dace.Memlet(f\"in1[k, i, j]\")\n tmp_in2_memlet = dace.Memlet(f\"in2[k, i, j]\")\n tmp_out_memlet = dace.Memlet(f\"out[k, i]\", wcr=\"lambda x,y: x+y\")\n\n outer_entry, outer_exit = state.add_map(\"vadd_outer_map\",\n dict(k=f'0:{banks}'))\n map_entry, map_exit = state.add_map(\"vadd_inner_map\", dict(i=\"0:N\",\n j=\"0:M\"))\n tasklet = state.add_tasklet(\"mul\", dict(__in1=None, __in2=None),\n dict(__out=None), '__out = __in1 * __in2')\n outer_entry.map.schedule = dace.ScheduleType.Unrolled\n\n state.add_memlet_path(read_in1,\n outer_entry,\n map_entry,\n tasklet,\n memlet=tmp_in1_memlet,\n dst_conn=\"__in1\")\n state.add_memlet_path(read_in2,\n outer_entry,\n map_entry,\n tasklet,\n memlet=tmp_in2_memlet,\n dst_conn=\"__in2\")\n state.add_memlet_path(tasklet,\n map_exit,\n outer_exit,\n out_write,\n memlet=tmp_out_memlet,\n src_conn=\"__out\")\n\n sdfg.apply_fpga_transformations()\n return sdfg\n\n\ndef create_test_set(N, M, banks):\n in1 = np.random.rand(*[banks, N, M]).astype('f')\n in2 = np.random.rand(*[banks, N, M]).astype('f')\n expected = np.sum(in1 * in2, axis=2, dtype=np.float32)\n out = np.zeros((banks, N), dtype=np.float32)\n return (in1, in2, expected, out)\n\n\ndef exec_test(N, M, banks, mem_type, name):\n in1, in2, expected, target = create_test_set(N, M, banks)\n sdfg = create_multibank_reduce_sdfg(name, mem_type, banks)\n sdfg(in1=in1, in2=in2, out=target, N=N, M=M)\n assert np.allclose(expected, target, rtol=1e-6)\n return sdfg\n\n\n@xilinx_test()\ndef test_hbm_reduce_2x3_2b():\n return exec_test(2, 3, 2, \"hbm\", \"red_2x3_2b\")\n\n\n@xilinx_test()\ndef test_hbm_reduce_10x50_4b():\n return exec_test(10, 50, 4, \"hbm\", \"red_10x50_4b\")\n\n\n@xilinx_test()\ndef test_hbm_reduce_red_1x50_1b():\n return exec_test(1, 50, 1, \"hbm\", \"red_1x50_1b\")\n\n\n@xilinx_test()\ndef test_hbm_reduce_red_1x40_8b():\n return exec_test(1, 40, 8, \"hbm\", \"red_1x40_8b\")\n\n\n@xilinx_test()\ndef test_hbm_reduce_red_2x40_6b():\n return exec_test(2, 40, 6, \"hbm\", \"red_2x40_6b\")\n\n\n@xilinx_test()\ndef test_ddr_reduce_2x3_2b():\n return exec_test(2, 3, 2, \"ddr\", \"red_2x3_2b\")\n\n\n@xilinx_test()\ndef test_ddr_reduce_10x50_4b():\n return exec_test(10, 50, 4, \"ddr\", \"red_10x50_4b\")\n\n\n@xilinx_test()\ndef test_ddr_reduce_red_1x50_1b():\n return exec_test(1, 50, 1, \"ddr\", \"red_1x50_1b\")\n\n\n@xilinx_test()\ndef test_ddr_reduce_red_1x40_8b():\n return exec_test(1, 40, 8, \"ddr\", \"red_1x40_8b\")\n\n\n@xilinx_test()\ndef test_ddr_reduce_red_2x40_6b():\n return exec_test(2, 40, 6, \"ddr\", \"red_2x40_6b\")\n\n\nif __name__ == \"__main__\":\n test_hbm_reduce_2x3_2b(None)\n test_hbm_reduce_10x50_4b(None)\n test_hbm_reduce_red_1x50_1b(None)\n test_hbm_reduce_red_1x40_8b(None)\n test_hbm_reduce_red_2x40_6b(None)\n test_ddr_reduce_2x3_2b(None)\n test_ddr_reduce_10x50_4b(None)\n test_ddr_reduce_red_1x50_1b(None)\n test_ddr_reduce_red_1x40_8b(None)\n test_ddr_reduce_red_2x40_6b(None)\n",
"# Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved.\n\"\"\"\nComputes C = A @ B + C.\n\nThis implementation is based on the HLS implementation from:\n https://github.com/spcl/gemm_hls\nIt uses the compute and I/O optimal strategy described in the FPGA'20 paper:\n \"Flexible Communication Avoiding Matrix Multiplication on FPGA with\n High-Level Synthesis\".\n\"\"\"\n\nimport click\nimport copy\nimport dace\nimport numpy as np\nfrom dace.libraries.standard import Gearbox\nfrom dace.transformation.interstate import InlineSDFG\n\nMINIMUM_CHANNEL_DEPTH = 8\n\n# Symbols used in this implementation:\n#\n# N: Number of rows of A and C.\n# K: Number of columns of A and rows of B.\n# M: Number of columns of B and C.\n# TN: The tile size in N, which must divide the size in N.\n# TM: The tile size in M, which must divide the size in M.\n# P: The number of (vertically unrolled) processing elements, and\n# consequently one of the two degrees of parallelism in the kernel. Must\n# divide the tile size TN.\n# W: The vectorization width, being the other degree of parallelism. Must\n# divide the tile size TM.\n\n\ndef make_copy_to_fpga_state(sdfg, vtype):\n \"\"\"\n Creates the pre-state where the matrices are transferred to the FPGA.\n \"\"\"\n\n state = sdfg.add_state(\"copy_to_device\")\n dtype = vtype.base_type\n # mem_veclen is the vectorization width necessary to create a 512-bit\n # interface to memory, and mtype is the corresponding type.\n mem_veclen = 64 // dtype.bytes\n mtype = dace.vector(dtype, mem_veclen)\n\n # Host data has plain data types\n sdfg.add_array(\"A\", [\"N\", \"K\"], dtype=dtype)\n sdfg.add_array(\"B\", [\"K\", \"M\"], dtype=dtype)\n sdfg.add_array(\"C\", [\"N\", \"M\"], dtype=dtype)\n A_host = state.add_read(\"A\")\n B_host = state.add_read(\"B\")\n C_host = state.add_read(\"C\")\n\n # On the device, vector B and C will be vectorized along rows. A is read\n # column-wise, so it is not vectorized.\n sdfg.add_array(\"A_device\", [\"N\", f\"K//{mem_veclen}\"],\n dtype=mtype,\n transient=True,\n location={\n \"memorytype\": \"DDR\",\n \"bank\": 1\n },\n storage=dace.dtypes.StorageType.FPGA_Global)\n sdfg.add_array(\"B_device\", [\"K\", f\"M//{mem_veclen}\"],\n dtype=mtype,\n transient=True,\n location={\n \"memorytype\": \"DDR\",\n \"bank\": 1\n },\n storage=dace.dtypes.StorageType.FPGA_Global)\n sdfg.add_array(\"C_device\", [\"N\", f\"M//{mem_veclen}\"],\n dtype=mtype,\n transient=True,\n location={\n \"memorytype\": \"DDR\",\n \"bank\": 1\n },\n storage=dace.dtypes.StorageType.FPGA_Global)\n A_device = state.add_write(\"A_device\")\n B_device = state.add_write(\"B_device\")\n C_device = state.add_write(\"C_device\")\n\n state.add_memlet_path(\n A_host,\n A_device,\n memlet=dace.Memlet(f\"A_device[0:N, 0:K//{mem_veclen}]\"))\n state.add_memlet_path(\n B_host,\n B_device,\n memlet=dace.Memlet(f\"B_device[0:K, 0:M//{mem_veclen}]\"))\n state.add_memlet_path(\n C_host,\n C_device,\n memlet=dace.Memlet(f\"C_device[0:N, 0:M//{mem_veclen}]\"))\n\n return state\n\n\ndef make_copy_to_host_state(sdfg, vtype):\n \"\"\"\n Creates the post-state where C is copied back to the host.\n \"\"\"\n\n state = sdfg.add_state(\"copy_to_host\")\n\n C_device = state.add_read(\"C_device\")\n C_host = state.add_write(\"C\")\n\n state.add_memlet_path(C_device, C_host, memlet=dace.Memlet(\"C[0:N, 0:M]\"))\n\n return state\n\n\ndef make_read_A(sdfg, state, vtype):\n \"\"\"\n Creates the memory read from A, which performs in-memory transposition by\n reading 512-bit wide vectors of A, then piping them into separate streams\n that are popped one at a time and sent to the kernel.\n \"\"\"\n\n # Deduce types\n dtype = vtype.base_type\n mem_veclen = 64 // dtype.bytes\n\n # Unpack vector into a register\n sdfg.add_array(\"transpose_reg\", (mem_veclen, ),\n dtype,\n storage=dace.StorageType.FPGA_Local,\n transient=True)\n\n # Add a stream for each element in the vector\n sdfg.add_stream(\n \"transpose\",\n dtype,\n # Allow loading the next column while the previous is being\n # used\n buffer_size=\"2 * TN\",\n shape=(mem_veclen, ),\n storage=dace.StorageType.FPGA_Local,\n transient=True)\n\n # Read each element into a buffer to unpack the vector into individual\n # elements\n mem = state.add_read(\"A_device\")\n entry, exit = state.add_map(\"read_A\", {\n \"n0\": \"0:N//TN\",\n \"m\": \"0:M//TM\",\n \"k0\": f\"0:K//{mem_veclen}\",\n \"n1\": \"0:TN\",\n },\n schedule=dace.ScheduleType.FPGA_Device)\n buffer_access = state.add_access(\"transpose_reg\")\n state.add_memlet_path(mem,\n entry,\n buffer_access,\n memlet=dace.Memlet(\"A_device[n0 * TN + n1, k0]\"))\n\n # Now stick each element into a separate stream\n unroll_entry, unroll_exit = state.add_map(\n \"unpack_A\", {\"k1\": f\"0:{mem_veclen}\"},\n schedule=dace.ScheduleType.FPGA_Device,\n unroll=True)\n unroll_tasklet = state.add_tasklet(\"unpack_A\", {\"from_memory\"}, {\"to_pipe\"},\n \"to_pipe = from_memory\")\n unroll_write = state.add_write(\"transpose\")\n state.add_memlet_path(buffer_access,\n unroll_entry,\n unroll_tasklet,\n dst_conn=\"from_memory\",\n memlet=dace.Memlet(f\"transpose_reg[k1]\"))\n state.add_memlet_path(unroll_tasklet,\n unroll_exit,\n exit,\n unroll_write,\n src_conn=\"to_pipe\",\n memlet=dace.Memlet(f\"transpose[k1]\"))\n\n # A separate processing element will pop from the streams one at a time\n transpose_read = state.add_read(\"transpose\")\n transpose_entry, transpose_exit = state.add_map(\n \"transpose_A\", {\n \"n0\": \"0:N//TN\",\n \"m\": \"0:M//TM\",\n \"k0\": f\"0:K//{mem_veclen}\",\n \"k1\": f\"0:{mem_veclen}\",\n \"n1\": \"0:TN\",\n },\n schedule=dace.ScheduleType.FPGA_Device)\n pipe_out = state.add_write(\"A_pipe\")\n tasklet = state.add_tasklet(\"transpose_A\", {\"from_transpose\"},\n {\"to_kernel\"}, \"to_kernel = from_transpose\")\n state.add_memlet_path(transpose_read,\n transpose_entry,\n tasklet,\n dst_conn=\"from_transpose\",\n memlet=dace.Memlet(f\"transpose[k1]\"))\n state.add_memlet_path(tasklet,\n transpose_exit,\n pipe_out,\n src_conn=\"to_kernel\",\n memlet=dace.Memlet(\"A_pipe[0]\"))\n\n\ndef make_read_B(sdfg, state, vtype):\n\n # Deduce types\n dtype = vtype.base_type\n mem_veclen = 64 // dtype.bytes\n mtype = dace.vector(dtype, mem_veclen)\n\n entry, exit = state.add_map(\"read_B\", {\n \"n0\": \"0:N//TN\",\n \"m0\": \"0:M//TM\",\n \"k\": \"0:K\",\n \"m1\": f\"0:TM//{mem_veclen}\"\n },\n schedule=dace.ScheduleType.FPGA_Device)\n\n mem = state.add_read(\"B_device\")\n to_feeder = state.add_write(\"B_to_feeder\")\n tasklet = state.add_tasklet(\"read_B\", {\"from_memory\"}, {\"to_feeder\"},\n \"to_feeder = from_memory\")\n state.add_memlet_path(\n mem,\n entry,\n tasklet,\n dst_conn=\"from_memory\",\n memlet=dace.Memlet(f\"B_device[k, m0 * (TM//{mem_veclen}) + m1]\"))\n\n if mem_veclen > vtype.veclen:\n\n # Data arrives as 512-bit wide vectors, and will be converted to the\n # vector length of the kernel\n\n sdfg.add_stream(\"B_to_converter\",\n dtype=mtype,\n buffer_size=MINIMUM_CHANNEL_DEPTH,\n storage=dace.StorageType.FPGA_Local,\n transient=True)\n to_converter_write = state.add_write(\"B_to_converter\")\n state.add_memlet_path(tasklet,\n exit,\n to_converter_write,\n src_conn=\"to_feeder\",\n memlet=dace.Memlet(\"B_to_converter[0]\"))\n\n # Convert 512-bit vectors to whatever width the kernel uses\n to_converter_read = state.add_read(\"B_to_converter\")\n gearbox = Gearbox(f\"(N//TN) * (M//TM) * K * (TM//{mem_veclen})\",\n \"convert_B\", dace.ScheduleType.FPGA_Device)\n state.add_memlet_path(to_converter_read,\n gearbox,\n dst_conn=\"from_memory\",\n memlet=dace.Memlet(f\"B_to_converter[0]\",\n dynamic=True))\n state.add_memlet_path(gearbox,\n to_feeder,\n src_conn=\"to_feeder\",\n memlet=dace.Memlet(\"B_to_feeder[0]\",\n dynamic=True))\n\n else:\n\n # If the kernel uses the full memory width, just send the data directly\n # without any conversion\n state.add_memlet_path(tasklet,\n exit,\n to_feeder,\n src_conn=\"to_feeder\",\n memlet=dace.Memlet(f\"B_to_feeder[0]\"))\n\n\ndef make_feed_B(sdfg, state, vtype):\n \"\"\"\n This module will buffer the values read from the B matrix, sending them\n multiple times to the kernel for each row of A in the current outer product.\n \"\"\"\n\n entry, exit = state.add_map(\"feed_B\", {\n \"n0\": \"0:N//TN\",\n \"m0\": \"0:M//TM\",\n \"k\": \"0:K\",\n \"n1\": \"0:TN//P\",\n \"m1\": \"0:TM//W\"\n },\n schedule=dace.ScheduleType.FPGA_Device)\n\n sdfg.add_array(\"feed_B_buffer\", (\"TM//W\", ),\n vtype,\n storage=dace.StorageType.FPGA_Local,\n transient=True)\n buffer_read = state.add_read(\"feed_B_buffer\")\n buffer_write = state.add_write(\"feed_B_buffer\")\n\n read = state.add_read(\"B_to_feeder\")\n write = state.add_write(\"B_pipe\")\n tasklet = state.add_tasklet(\n \"feed_B\", {\"from_memory\", \"buffer_in\"}, {\"to_kernel\", \"buffer_out\"}, \"\"\"\nval = buffer_in\nif n1 == 0:\n val = from_memory\nto_kernel = val\nbuffer_out = val\"\"\")\n\n state.add_memlet_path(read,\n entry,\n tasklet,\n dst_conn=\"from_memory\",\n memlet=dace.Memlet(\"B_to_feeder[0]\", dynamic=True))\n state.add_memlet_path(buffer_read,\n entry,\n tasklet,\n dst_conn=\"buffer_in\",\n memlet=dace.Memlet(\"feed_B_buffer[m1]\"))\n state.add_memlet_path(tasklet,\n exit,\n buffer_write,\n src_conn=\"buffer_out\",\n memlet=dace.Memlet(\"feed_B_buffer[m1]\"))\n state.add_memlet_path(tasklet,\n exit,\n write,\n src_conn=\"to_kernel\",\n memlet=dace.Memlet(\"B_pipe[0]\"))\n\n\ndef make_write_C(sdfg, state, vtype):\n\n # Deduce types\n dtype = vtype.base_type\n mem_veclen = 64 // dtype.bytes\n mtype = dace.vector(dtype, mem_veclen)\n\n from_kernel = state.add_read(\"C_pipe\")\n mem_read = state.add_read(\"C_device\")\n mem_write = state.add_write(\"C_device\")\n\n if mem_veclen > vtype.veclen:\n\n # We need to convert from the kernel vectorization length to 512-bit\n # vectors that are written back to memory\n\n gearbox = Gearbox(f\"(N//TN) * (M//TM) * TN * (TM//{mem_veclen})\",\n \"convert_C\",\n schedule=dace.ScheduleType.FPGA_Device)\n sdfg.add_stream(\"C_from_converter\",\n mtype,\n buffer_size=f\"TM//{mem_veclen}\",\n storage=dace.StorageType.FPGA_Local,\n transient=True)\n converter_write = state.add_write(\"C_from_converter\")\n state.add_memlet_path(from_kernel,\n gearbox,\n dst_conn=\"from_kernel\",\n memlet=dace.Memlet(f\"C_pipe[0]\", dynamic=True))\n state.add_memlet_path(gearbox,\n converter_write,\n src_conn=\"to_memory\",\n memlet=dace.Memlet(\"C_from_converter[0]\",\n dynamic=True))\n\n to_writer = state.add_read(\"C_from_converter\")\n to_writer_subset = \"C_from_converter[0]\"\n\n else:\n\n # Just send the data directly to the reader\n to_writer = from_kernel\n to_writer_subset = \"C_pipe[0]\"\n\n entry, exit = state.add_map(\"write_C\", {\n \"n0\": \"0:N//TN\",\n \"m0\": \"0:M//TM\",\n \"n1\": \"0:TN\",\n \"m1\": f\"0:TM//{mem_veclen}\"\n },\n schedule=dace.ScheduleType.FPGA_Device)\n\n tasklet = state.add_tasklet(\"write_C\", {\"from_kernel\", \"prev\"},\n {\"to_memory\"}, \"to_memory = from_kernel + prev\")\n state.add_memlet_path(to_writer,\n entry,\n tasklet,\n dst_conn=\"from_kernel\",\n memlet=dace.Memlet(to_writer_subset))\n\n state.add_memlet_path(\n mem_read,\n entry,\n tasklet,\n dst_conn=\"prev\",\n memlet=dace.Memlet(\n f\"C_device[n0 * TN + n1, m0 * (TM//{mem_veclen}) + m1]\"))\n\n state.add_memlet_path(\n tasklet,\n exit,\n mem_write,\n src_conn=\"to_memory\",\n memlet=dace.Memlet(\n f\"C_device[n0 * TN + n1, m0 * (TM//{mem_veclen}) + m1]\"))\n\n\ndef make_compute(sdfg, state, vtype):\n\n dtype = vtype.base_type\n\n # Pipes connecting the systolic array\n A_pipe_in = state.add_read(\"A_pipe\")\n A_pipe_out = state.add_write(\"A_pipe\")\n B_pipe_in = state.add_read(\"B_pipe\")\n B_pipe_out = state.add_write(\"B_pipe\")\n C_pipe_in = state.add_read(\"C_pipe\")\n C_pipe_out = state.add_write(\"C_pipe\")\n\n # Instantiate the buffer for A, and initialize it\n sdfg.add_array(\"A_buffer\", (\"2 * (TN//P)\", ),\n dtype=dtype,\n transient=True,\n storage=dace.dtypes.StorageType.FPGA_Registers)\n init_A = state.add_access(\"A_buffer\")\n init_entry, init_exit = state.add_map(\n \"init\", {\n \"n0\": \"0:TN//P\",\n \"n1\": \"0:P-p\"\n },\n schedule=dace.ScheduleType.FPGA_Device)\n init_tasklet = state.add_tasklet(\n \"init_A\", {\"from_prev\"}, {\"to_buffer\", \"to_next\"}, \"\"\"\\\nval = from_prev\nif n1 == 0:\n to_buffer = val\nelif p < P - 1:\n to_next = val\"\"\")\n state.add_memlet_path(A_pipe_in,\n init_entry,\n init_tasklet,\n dst_conn=\"from_prev\",\n memlet=dace.Memlet(\"A_pipe[p]\"))\n state.add_memlet_path(init_tasklet,\n init_exit,\n init_A,\n src_conn=\"to_buffer\",\n memlet=dace.Memlet(f\"A_buffer[n0]\", dynamic=True))\n state.add_memlet_path(init_tasklet,\n init_exit,\n A_pipe_out,\n src_conn=\"to_next\",\n memlet=dace.Memlet(f\"A_pipe[p + 1]\", dynamic=True))\n\n # Now instantiate the body of the computation\n outer_entry, outer_exit = state.add_map(\n \"tiles\", {\n \"n0\": \"0:N//TN\",\n \"m0\": \"0:M//TM\"\n },\n schedule=dace.ScheduleType.FPGA_Device)\n\n # Make a dummy edge to bring the initialization buffer into scope\n state.add_memlet_path(init_A, outer_entry, memlet=dace.Memlet())\n\n # Loop over the reduced dimension\n k_entry, k_exit = state.add_map(\"k\", {\"k\": \"0:K\"},\n schedule=dace.ScheduleType.FPGA_Device)\n\n # Loops over the tile content\n inner_entry, inner_exit = state.add_map(\n \"inner\", {\n \"n1\": \"0:TN//P\",\n \"m1\": \"0:TM//W\"\n },\n schedule=dace.ScheduleType.FPGA_Device)\n\n # Double buffering scheme of A\n update_A = state.add_access(\"A_buffer\")\n buffer_tasklet = state.add_tasklet(\n \"double_buffer_A\", {\"from_prev\"}, {\"to_buffer\", \"to_next\"}, \"\"\"\\\nif (n0 < (N/TN) - 1 or m0 < (M/TM) - 1 or k < K - 1) and m1 >= p and m1 < P:\n val = from_prev\n if m1 == p:\n to_buffer = val\n elif p < P - 1:\n to_next = val\"\"\")\n state.add_memlet_path(A_pipe_in,\n outer_entry,\n k_entry,\n inner_entry,\n buffer_tasklet,\n dst_conn=\"from_prev\",\n memlet=dace.Memlet(f\"A_pipe[p]\", dynamic=True))\n state.add_memlet_path(buffer_tasklet,\n update_A,\n src_conn=\"to_buffer\",\n memlet=dace.Memlet(\n f\"A_buffer[n1 + (1 - (k % 2)) * (TN//P)]\",\n dynamic=True))\n state.add_memlet_path(buffer_tasklet,\n inner_exit,\n k_exit,\n outer_exit,\n A_pipe_out,\n src_conn=\"to_next\",\n memlet=dace.Memlet(f\"A_pipe[p + 1]\", dynamic=True))\n\n # Instantiate the \"big\" buffer of the output, where most of our fast memory\n # will be spent\n sdfg.add_array(\"C_buffer\", (\"TN/P\", \"TM/W\"),\n vtype,\n storage=dace.StorageType.FPGA_Local,\n transient=True)\n\n # Now the tasklet performing the actual computation\n compute_tasklet = state.add_tasklet(\n \"multiply_add\", {\"a_in\", \"b_in\", \"c_in\"}, {\"b_out\", \"c_out\"}, \"\"\"\\\nif p < P - 1:\n b_out = b_in\nc_val = c_in\nif k == 0:\n c_val = 0\nc_out = c_val + a_in * b_in\"\"\")\n C_buffer_read = state.add_read(\"C_buffer\")\n C_buffer_write = state.add_access(\"C_buffer\")\n state.add_memlet_path(\n update_A,\n compute_tasklet,\n dst_conn=\"a_in\",\n memlet=dace.Memlet(f\"A_buffer[n1 + (k % 2) * (TN//P)]\"))\n state.add_memlet_path(B_pipe_in,\n outer_entry,\n k_entry,\n inner_entry,\n compute_tasklet,\n dst_conn=\"b_in\",\n memlet=dace.Memlet(\"B_pipe[p]\"))\n state.add_memlet_path(C_buffer_read,\n outer_entry,\n k_entry,\n inner_entry,\n compute_tasklet,\n dst_conn=\"c_in\",\n memlet=dace.Memlet(\"C_buffer[n1, m1]\"))\n state.add_memlet_path(compute_tasklet,\n inner_exit,\n k_exit,\n outer_exit,\n B_pipe_out,\n src_conn=\"b_out\",\n memlet=dace.Memlet(\"B_pipe[p + 1]\", dynamic=True))\n state.add_memlet_path(compute_tasklet,\n inner_exit,\n k_exit,\n C_buffer_write,\n src_conn=\"c_out\",\n memlet=dace.Memlet(\"C_buffer[n1, m1]\"))\n\n # Now we need to write C out after each tile has been processed\n write_entry, write_exit = state.add_map(\n \"write_C\", {\"n1\": \"0:TN//P\"}, schedule=dace.ScheduleType.FPGA_Device)\n\n # We need to enforce sequentiality between these loops\n write_sdfg = dace.SDFG(\"write_C\")\n write_sdfg_node = state.add_nested_sdfg(write_sdfg, sdfg,\n {\"buffer_in\", \"forward_in\"},\n {\"forward_out\"})\n state.add_memlet_path(C_buffer_write,\n write_entry,\n write_sdfg_node,\n dst_conn=\"buffer_in\",\n memlet=dace.Memlet(\"C_buffer[n1, 0:TM/W]\"))\n state.add_memlet_path(C_pipe_in,\n outer_entry,\n write_entry,\n write_sdfg_node,\n dst_conn=\"forward_in\",\n memlet=dace.Memlet(\"C_pipe[p + 1]\", dynamic=True))\n state.add_memlet_path(write_sdfg_node,\n write_exit,\n outer_exit,\n C_pipe_out,\n src_conn=\"forward_out\",\n memlet=dace.Memlet(\"C_pipe[p]\", dynamic=True))\n write_sdfg.add_stream(\"forward_in\",\n vtype,\n buffer_size=MINIMUM_CHANNEL_DEPTH,\n storage=dace.StorageType.FPGA_Local,\n transient=False)\n write_sdfg.add_stream(\"forward_out\",\n vtype,\n buffer_size=MINIMUM_CHANNEL_DEPTH,\n storage=dace.StorageType.FPGA_Local,\n transient=False)\n write_sdfg.add_array(\"buffer_in\", (\"TM//W\", ),\n vtype,\n transient=False,\n storage=dace.StorageType.FPGA_Local)\n # Send results from this PE\n send_state = write_sdfg.add_state(\"send_C\")\n send_read = send_state.add_read(\"buffer_in\")\n send_write = send_state.add_write(\"forward_out\")\n send_tasklet = send_state.add_tasklet(\"send_C\", {\"from_buffer\"},\n {\"to_next\"}, \"to_next = from_buffer\")\n send_entry, send_exit = send_state.add_map(\n \"send_C\", {\"m1\": \"0:TM//W\"}, schedule=dace.ScheduleType.FPGA_Device)\n send_state.add_memlet_path(send_read,\n send_entry,\n send_tasklet,\n dst_conn=\"from_buffer\",\n memlet=dace.Memlet(\"buffer_in[m1]\"))\n send_state.add_memlet_path(send_tasklet,\n send_exit,\n send_write,\n src_conn=\"to_next\",\n memlet=dace.Memlet(\"forward_out[0]\"))\n # And finally forward results from earlier PEs\n forward_state = write_sdfg.add_state(\"forward_C\")\n forward_read = forward_state.add_read(\"forward_in\")\n forward_write = forward_state.add_read(\"forward_out\")\n forward_tasklet = forward_state.add_tasklet(\n \"forward_C\", {\"from_prev\"}, {\"to_next\"}, \"\"\"\\\nif p < P - 1:\n to_next = from_prev\"\"\")\n forward_entry, forward_exit = forward_state.add_map(\n \"forward_C\", {\n \"n1\": \"0:P - p - 1\",\n \"m1\": \"0:TM//W\"\n },\n schedule=dace.ScheduleType.FPGA_Device)\n # These must be dynamic so the compiler can optimize out the write from the\n # last processing element\n forward_state.add_memlet_path(forward_read,\n forward_entry,\n forward_tasklet,\n dst_conn=\"from_prev\",\n memlet=dace.Memlet(\"forward_in[0]\",\n dynamic=True))\n forward_state.add_memlet_path(forward_tasklet,\n forward_exit,\n forward_write,\n src_conn=\"to_next\",\n memlet=dace.Memlet(\"forward_out[0]\",\n dynamic=True))\n # Enforce sending own data before forwarding\n write_sdfg.add_edge(send_state, forward_state, dace.InterstateEdge())\n\n # Unroll processing elements\n unroll_entry, unroll_exit = state.add_map(\n \"unroll_processing_elements\", {\"p\": \"0:P\"},\n schedule=dace.ScheduleType.FPGA_Device,\n unroll=True)\n\n # Bring data nodes into scope\n state.add_memlet_path(unroll_entry, A_pipe_in, memlet=dace.memlet.Memlet())\n state.add_memlet_path(unroll_entry, B_pipe_in, memlet=dace.memlet.Memlet())\n state.add_memlet_path(unroll_entry, C_pipe_in, memlet=dace.memlet.Memlet())\n state.add_memlet_path(unroll_entry,\n C_buffer_read,\n memlet=dace.memlet.Memlet())\n state.add_memlet_path(A_pipe_out, unroll_exit, memlet=dace.memlet.Memlet())\n state.add_memlet_path(B_pipe_out, unroll_exit, memlet=dace.memlet.Memlet())\n state.add_memlet_path(C_pipe_out, unroll_exit, memlet=dace.memlet.Memlet())\n\n # Propagate symbols\n write_sdfg.symbols = copy.deepcopy(sdfg.symbols)\n write_sdfg.add_symbol(\"p\", sdfg.symbols[\"P\"])\n write_sdfg_node.symbol_mapping = {k: k for k in sdfg.free_symbols}\n write_sdfg_node.symbol_mapping[\"p\"] = \"p\"\n\n\ndef make_fpga_state(sdfg, vtype):\n\n state = sdfg.add_state(\"gemm\")\n\n sdfg.add_stream(\"A_pipe\",\n vtype.base_type,\n transient=True,\n shape=(\"P + 1\", ),\n storage=dace.dtypes.StorageType.FPGA_Local,\n buffer_size=\"P\")\n sdfg.add_stream(\"B_pipe\",\n vtype,\n transient=True,\n shape=(\"P + 1\", ),\n buffer_size=MINIMUM_CHANNEL_DEPTH,\n storage=dace.dtypes.StorageType.FPGA_Local)\n sdfg.add_stream(\"B_to_feeder\",\n vtype,\n transient=True,\n buffer_size=MINIMUM_CHANNEL_DEPTH,\n storage=dace.StorageType.FPGA_Local)\n sdfg.add_stream(\"C_pipe\",\n vtype,\n transient=True,\n shape=(\"P + 1\", ),\n buffer_size=MINIMUM_CHANNEL_DEPTH,\n storage=dace.dtypes.StorageType.FPGA_Local)\n\n make_read_A(sdfg, state, vtype)\n make_read_B(sdfg, state, vtype)\n make_feed_B(sdfg, state, vtype)\n make_compute(sdfg, state, vtype)\n make_write_C(sdfg, state, vtype)\n\n return state\n\n\ndef make_sdfg(name, vtype):\n\n sdfg = dace.SDFG(name)\n\n pre_state = make_copy_to_fpga_state(sdfg, vtype)\n compute_state = make_fpga_state(sdfg, vtype)\n post_state = make_copy_to_host_state(sdfg, vtype)\n\n sdfg.add_edge(pre_state, compute_state, dace.sdfg.InterstateEdge())\n sdfg.add_edge(compute_state, post_state, dace.sdfg.InterstateEdge())\n\n if vtype.bytes < 64:\n sdfg.expand_library_nodes()\n assert sdfg.apply_transformations_repeated(InlineSDFG) == 2\n\n return sdfg\n\n\[email protected]()\[email protected](\"N\", type=int)\[email protected](\"K\", type=int)\[email protected](\"M\", type=int)\[email protected](\"num-pes\", type=int)\[email protected](\"vector-width\", type=int)\[email protected](\"--dtype\", default=\"float32\")\[email protected](\"--tile-size-n\",\n type=int,\n default=None,\n help=(\"Must be a multiple of the number of processing elements, \"\n \"and must divide the size in N.\"))\[email protected](\"--tile-size-m\",\n type=int,\n default=None,\n help=(\"Must be a multiple of the vector size, and must divide\"\n \" the size in M.\"))\[email protected](\"--specialize/--no-specialize\",\n default=False,\n help=\"Fix matrix sizes at compile time.\")\ndef cli(n, k, m, num_pes, dtype, tile_size_n, tile_size_m, vector_width,\n specialize):\n\n # Some reasonable default values for tile sizes\n if not tile_size_n:\n tile_size_n = n // num_pes\n if not tile_size_m:\n tile_size_m = min(m, 1024)\n\n # Rename\n P = num_pes\n W = vector_width\n TN = tile_size_n\n TM = tile_size_m\n\n dtype = getattr(dace.dtypes, dtype) # Convert from string to typeclass\n vtype = dace.vector(dtype, vector_width)\n\n if TN % P != 0:\n raise ValueError(\n f\"Tile size in N {TN} must be divisible by the number of processing elements {P}.\"\n )\n if TM % W != 0:\n raise ValueError(\n f\"Tile size in M {TM} must be divisible by the vectorization width {W}.\"\n )\n if n % TN != 0:\n raise ValueError(\n f\"Size in N {n} must be divisible by the tile size in N {TN}.\")\n if n % TM != 0:\n raise ValueError(\n f\"Size in M {m} must be divisible by the tile size in M {TM}.\")\n if (dtype.bytes * TM) % 64 != 0:\n raise ValueError(f\"Tile size in M {TM} must be a multiple of 64 bytes.\")\n if (dtype.bytes * k) % 64 != 0:\n raise ValueError(f\"Size in K {K} must be a multiple of 64 bytes.\")\n\n dtype = dtype.type # Convert from typeclass to NumPy type\n\n if specialize:\n name = (f\"gemm_fpga_systolic_vectorized_d{num_pes}_\"\n f\"w{vector_width}_{tile_size_n}x{tile_size_m}_{n}x{k}x{m}\")\n else:\n name = (f\"gemm_fpga_systolic_vectorized_d{num_pes}_\"\n f\"w{vector_width}_{tile_size_n}x{tile_size_m}_NxKxM\")\n\n sdfg = make_sdfg(name, vtype)\n\n # Specialize compile time constants\n sdfg.specialize({\"P\": P, \"W\": W, \"TN\": TN, \"TM\": TM})\n if specialize:\n sdfg.specialize({\"N\": n, \"K\": k, \"M\": m})\n\n print(f\"Matrix multiplication {n}x{k}x{m} \"\n f\"with {num_pes} PEs \"\n f\"and vectorization width {vector_width}, \"\n f\"and tile sizes {TN}x{TM}.\")\n\n # Initialize arrays: Randomize A and B, zero C\n A = np.ndarray([n, k], dtype=dtype)\n B = np.ndarray([k, m], dtype=dtype)\n C = np.ndarray([n, m], dtype=dtype)\n A[:] = np.random.rand(n, k).astype(dtype)\n B[:] = np.random.rand(k, m).astype(dtype)\n C[:] = np.random.rand(n, m).astype(dtype)\n\n # Compute reference result\n C_reference = A @ B + C\n\n # Run DaCe program\n if specialize:\n sdfg(A=A, B=B, C=C)\n else:\n sdfg(A=A, B=B, C=C, N=n, K=k, M=m)\n\n # Verify results\n if not np.allclose(C, C_reference):\n raise ValueError(\"Verification failed.\")\n else:\n print(\"Results successfully verified.\")\n\n\nif __name__ == \"__main__\":\n cli()\n",
"# Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved.\n\"\"\" Tests for half-precision syntax quirks. \"\"\"\n\nimport dace\nimport math\nimport numpy as np\nimport pytest\nfrom dace.transformation.dataflow import MapFusion, Vectorization\nfrom dace.transformation.optimizer import Optimizer\n\nN = dace.symbol('N')\n\n\ndef _config():\n # Prerequisite for test: CUDA compute capability >= 6.0\n dace.Config.set('compiler', 'cuda', 'cuda_arch', value='60')\n\n\ndef _test_half(veclen):\n \"\"\" Tests a set of elementwise operations on a vector half type. \"\"\"\n _config()\n\n @dace.program\n def halftest(A: dace.float16[N], B: dace.float16[N]):\n return A * B + A\n\n A = np.random.rand(24).astype(np.float16)\n B = np.random.rand(24).astype(np.float16)\n sdfg = halftest.to_sdfg()\n sdfg.apply_strict_transformations()\n sdfg.apply_gpu_transformations()\n\n # Apply vectorization on each map and count applied\n applied = 0\n for xform in Optimizer(sdfg).get_pattern_matches(\n patterns=Vectorization,\n options=dict(vector_len=veclen, postamble=False)):\n xform.apply(sdfg)\n applied += 1\n assert applied == 2\n\n out = sdfg(A=A, B=B, N=24)\n assert np.allclose(out, A * B + A)\n\n\[email protected]\ndef test_half4():\n \"\"\" Tests a set of elementwise operations on half with vector length 4. \"\"\"\n _test_half(4)\n\n\[email protected]\ndef test_half8():\n \"\"\" Tests a set of elementwise operations on half with vector length 8. \"\"\"\n _test_half(8)\n\n\[email protected]\ndef test_exp_vec():\n \"\"\" Tests an exp operator on a vector half type. \"\"\"\n _config()\n\n @dace.program\n def halftest(A: dace.float16[N]):\n out = np.ndarray([N], dace.float16)\n for i in dace.map[0:N]:\n with dace.tasklet:\n a << A[i]\n o >> out[i]\n o = math.exp(a)\n return out\n\n A = np.random.rand(24).astype(np.float16)\n sdfg = halftest.to_sdfg()\n sdfg.apply_gpu_transformations()\n assert sdfg.apply_transformations(Vectorization, dict(vector_len=8)) == 1\n out = sdfg(A=A, N=24)\n assert np.allclose(out, np.exp(A))\n\n\[email protected]\ndef test_relu_vec():\n \"\"\" Tests a ReLU operator on a vector half type. \"\"\"\n _config()\n\n @dace.program\n def halftest(A: dace.float16[N]):\n out = np.ndarray([N], dace.float16)\n for i in dace.map[0:N]:\n with dace.tasklet:\n a << A[i]\n o >> out[i]\n o = max(a, dace.float16(0))\n return out\n\n A = np.random.rand(24).astype(np.float16)\n sdfg = halftest.to_sdfg()\n sdfg.apply_gpu_transformations()\n assert sdfg.apply_transformations(Vectorization, dict(vector_len=8)) == 1\n out = sdfg(A=A, N=24)\n assert np.allclose(out, np.maximum(A, 0))\n\n\[email protected]\ndef test_dropout_vec():\n \"\"\" Tests a dropout operator on a vector half type. \"\"\"\n _config()\n\n @dace.program\n def halftest(A: dace.float16[N], mask: dace.float16[N]):\n out = np.ndarray([N], dace.float16)\n for i in dace.map[0:N]:\n with dace.tasklet:\n a << A[i]\n d << mask[i]\n o >> out[i]\n o = a * d\n return out\n\n A = np.random.rand(24).astype(np.float16)\n mask = np.random.randint(0, 2, size=[24]).astype(np.float16)\n sdfg: dace.SDFG = halftest.to_sdfg()\n sdfg.apply_gpu_transformations()\n assert sdfg.apply_transformations(Vectorization, dict(vector_len=8)) == 1\n out = sdfg(A=A, mask=mask, N=24)\n assert np.allclose(out, A * mask)\n\n\[email protected]\ndef test_gelu_vec():\n \"\"\" Tests a GELU operator on a vector half type. \"\"\"\n _config()\n s2pi = math.sqrt(2.0 / math.pi)\n\n @dace.program\n def halftest(A: dace.float16[N]):\n out = np.ndarray([N], dace.float16)\n for i in dace.map[0:N]:\n with dace.tasklet:\n a << A[i]\n o >> out[i]\n o = dace.float16(0.5) * a * (dace.float16(1) + math.tanh(\n dace.float16(s2pi) * (a + dace.float16(0.044715) * (a**3))))\n return out\n\n A = np.random.rand(24).astype(np.float16)\n sdfg = halftest.to_sdfg()\n sdfg.apply_gpu_transformations()\n assert sdfg.apply_transformations(Vectorization, dict(vector_len=4)) == 1\n out = sdfg(A=A, N=24)\n expected = 0.5 * A * (\n 1 + np.tanh(math.sqrt(2.0 / math.pi) * (A + 0.044715 * (A**3))))\n assert np.allclose(out, expected, rtol=1e-2, atol=1e-4)\n\n\nif __name__ == '__main__':\n test_half4()\n test_half8()\n test_exp_vec()\n test_relu_vec()\n test_dropout_vec()\n test_gelu_vec()\n",
"# Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved.\n\"\"\"\nTests memory buffering in an FPGA SDFG, where memory is read and written using\n512-bit wide accesses, and converted (using a \"gearbox\") to/from the vector\nwidth used by the computational kernel.\n\nUnfortunately this doesn't currently work for Intel, since Intel does not\nsupport vectors of vectors in kernel code.\n\"\"\"\nimport dace\nfrom dace.fpga_testing import fpga_test, xilinx_test\nfrom dace.libraries.standard import Gearbox\nfrom dace.transformation.interstate import FPGATransformSDFG, InlineSDFG\nimport numpy as np\n\ndtype = dace.float32\nmem_width = 64 // dtype.bytes\nn = dace.symbol(\"n\")\n\n\ndef run_program(sdfg: dace.SDFG):\n size = 16 * mem_width\n input_array = np.ones((size, ), dtype.type)\n output_array = np.empty((size, ), dtype.type)\n sdfg(input_array_host=input_array, output_array_host=output_array, n=size)\n assert all(output_array == input_array + 1)\n\n\ndef memory_buffering(vec_width, use_library_node, elementwise):\n\n gear_factor = mem_width // vec_width\n kernel_type = dace.vector(dtype, vec_width)\n if elementwise:\n memory_type = dace.vector(dtype, mem_width)\n else:\n memory_type = dace.vector(kernel_type, gear_factor)\n sdfg = dace.SDFG(\"memory_buffering_library_node\")\n state = sdfg.add_state(\"memory_buffering_library_node\")\n\n sdfg.add_array(\"input_array\", (n / mem_width, ),\n memory_type,\n transient=True,\n storage=dace.StorageType.FPGA_Global)\n sdfg.add_array(\"output_array\", (n / mem_width, ),\n memory_type,\n transient=True,\n storage=dace.StorageType.FPGA_Global)\n sdfg.add_stream(\"read_to_gearbox\",\n memory_type,\n transient=True,\n storage=dace.StorageType.FPGA_Local)\n sdfg.add_stream(\"gearbox_to_kernel\",\n kernel_type,\n transient=True,\n storage=dace.StorageType.FPGA_Local)\n sdfg.add_stream(\"kernel_to_gearbox\",\n kernel_type,\n transient=True,\n storage=dace.StorageType.FPGA_Local)\n sdfg.add_stream(\"gearbox_to_write\",\n memory_type,\n transient=True,\n storage=dace.StorageType.FPGA_Local)\n\n # Read from memory\n memory_read = state.add_read(\"input_array\")\n read_to_gearbox_write = state.add_write(\"read_to_gearbox\")\n read_entry, read_exit = state.add_map(\n \"read\", {\"i\": f\"0:n/{mem_width}\"},\n schedule=dace.ScheduleType.FPGA_Device)\n read_tasklet = state.add_tasklet(\"read\", {\"mem\"}, {\"to_gearbox\"},\n \"to_gearbox = mem\")\n state.add_memlet_path(memory_read,\n read_entry,\n read_tasklet,\n dst_conn=\"mem\",\n memlet=dace.Memlet(f\"input_array[i]\"))\n state.add_memlet_path(read_tasklet,\n read_exit,\n read_to_gearbox_write,\n src_conn=\"to_gearbox\",\n memlet=dace.Memlet(f\"read_to_gearbox[0]\"))\n\n # Gearbox input\n read_to_gearbox_read = state.add_read(\"read_to_gearbox\")\n gearbox_to_kernel_write = state.add_write(\"gearbox_to_kernel\")\n if use_library_node:\n read_gearbox = Gearbox(n / mem_width, name=\"read_gearbox\")\n state.add_node(read_gearbox)\n state.add_memlet_path(read_to_gearbox_read,\n read_gearbox,\n dst_conn=\"from_memory\",\n memlet=dace.Memlet(\"read_to_gearbox[0]\",\n volume=n / mem_width))\n state.add_memlet_path(read_gearbox,\n gearbox_to_kernel_write,\n src_conn=\"to_kernel\",\n memlet=dace.Memlet(\"gearbox_to_kernel[0]\",\n volume=n / vec_width))\n else:\n sdfg.add_array(\"read_buffer\", (1, ),\n memory_type,\n storage=dace.StorageType.FPGA_Local,\n transient=True)\n read_buffer_read = state.add_read(\"read_buffer\")\n read_buffer_write = state.add_write(\"read_buffer\")\n read_gearbox_entry, read_gearbox_exit = state.add_map(\n \"gearbox_read\", {\n \"i\": f\"0:n/{mem_width}\",\n \"j\": f\"0:{gear_factor}\"\n },\n schedule=dace.ScheduleType.FPGA_Device)\n read_gearbox_tasklet = state.add_tasklet(\n \"gearbox_read\", {\n \"from_memory\": memory_type,\n \"buffer_in\": None\n }, {\"to_kernel\", \"buffer_out\"}, \"\"\"\\\nwide = from_memory if j == 0 else buffer_in\nto_kernel = wide[j]\nbuffer_out = wide\"\"\")\n state.add_memlet_path(read_to_gearbox_read,\n read_gearbox_entry,\n read_gearbox_tasklet,\n dst_conn=\"from_memory\",\n memlet=dace.Memlet(\"read_to_gearbox[0]\",\n dynamic=True))\n state.add_memlet_path(read_buffer_read,\n read_gearbox_entry,\n read_gearbox_tasklet,\n dst_conn=\"buffer_in\",\n memlet=dace.Memlet(\"read_buffer[0]\"))\n state.add_memlet_path(read_gearbox_tasklet,\n read_gearbox_exit,\n gearbox_to_kernel_write,\n src_conn=\"to_kernel\",\n memlet=dace.Memlet(\"gearbox_to_kernel[0]\"))\n state.add_memlet_path(read_gearbox_tasklet,\n read_gearbox_exit,\n read_buffer_write,\n src_conn=\"buffer_out\",\n memlet=dace.Memlet(\"read_buffer[0]\"))\n\n # Some fictional compute\n gearbox_to_kernel_read = state.add_read(\"gearbox_to_kernel\")\n kernel_to_gearbox_write = state.add_write(\"kernel_to_gearbox\")\n compute_entry, compute_exit = state.add_map(\n \"compute\", {\"i\": f\"0:n/{vec_width}\"},\n schedule=dace.ScheduleType.FPGA_Device)\n compute_tasklet = state.add_tasklet(\"compute\", {\"val_in\"}, {\"val_out\"},\n \"val_out = val_in + 1\")\n state.add_memlet_path(gearbox_to_kernel_read,\n compute_entry,\n compute_tasklet,\n dst_conn=\"val_in\",\n memlet=dace.Memlet(\"gearbox_to_kernel[0]\"))\n state.add_memlet_path(compute_tasklet,\n compute_exit,\n kernel_to_gearbox_write,\n src_conn=\"val_out\",\n memlet=dace.Memlet(\"kernel_to_gearbox[0]\"))\n\n # Gearbox output\n kernel_to_gearbox_read = state.add_write(\"kernel_to_gearbox\")\n gearbox_to_write_write = state.add_read(\"gearbox_to_write\")\n if use_library_node:\n write_gearbox = Gearbox(n / mem_width, name=\"write_gearbox\")\n state.add_node(write_gearbox)\n state.add_memlet_path(kernel_to_gearbox_read,\n write_gearbox,\n dst_conn=\"from_kernel\",\n memlet=dace.Memlet(\"kernel_to_gearbox[0]\",\n volume=n / vec_width))\n state.add_memlet_path(write_gearbox,\n gearbox_to_write_write,\n src_conn=\"to_memory\",\n memlet=dace.Memlet(\"gearbox_to_write[0]\",\n volume=n / mem_width))\n else:\n sdfg.add_array(\"write_buffer\", (1, ),\n memory_type,\n storage=dace.StorageType.FPGA_Local,\n transient=True)\n write_buffer_read = state.add_read(\"write_buffer\")\n write_buffer_write = state.add_write(\"write_buffer\")\n write_gearbox_entry, write_gearbox_exit = state.add_map(\n \"gearbox_write\", {\n \"i\": f\"0:n/{mem_width}\",\n \"j\": f\"0:{gear_factor}\"\n },\n schedule=dace.ScheduleType.FPGA_Device)\n write_gearbox_tasklet = state.add_tasklet(\n \"gearbox_write\", {\"from_kernel\", \"buffer_in\"},\n {\"to_memory\", \"buffer_out\"}, f\"\"\"\\\nwide = buffer_in\nwide[j] = from_kernel\nif j == {gear_factor} - 1:\n to_memory = wide\nbuffer_out = wide\"\"\")\n state.add_memlet_path(kernel_to_gearbox_read,\n write_gearbox_entry,\n write_gearbox_tasklet,\n dst_conn=\"from_kernel\",\n memlet=dace.Memlet(\"kernel_to_gearbox[0]\"))\n state.add_memlet_path(write_buffer_read,\n write_gearbox_entry,\n write_gearbox_tasklet,\n dst_conn=\"buffer_in\",\n memlet=dace.Memlet(\"write_buffer[0]\"))\n state.add_memlet_path(write_gearbox_tasklet,\n write_gearbox_exit,\n gearbox_to_write_write,\n src_conn=\"to_memory\",\n memlet=dace.Memlet(\"gearbox_to_write[0]\",\n dynamic=True))\n state.add_memlet_path(write_gearbox_tasklet,\n write_gearbox_exit,\n write_buffer_write,\n src_conn=\"buffer_out\",\n memlet=dace.Memlet(\"write_buffer[0]\"))\n\n # Write memory\n gearbox_to_write_read = state.add_read(\"gearbox_to_write\")\n memory_write = state.add_write(\"output_array\")\n write_entry, write_exit = state.add_map(\n \"write\", {\"i\": f\"0:n/{mem_width}\"},\n schedule=dace.ScheduleType.FPGA_Device)\n write_tasklet = state.add_tasklet(\"write\", {\"from_gearbox\"}, {\"mem\"},\n \"mem = from_gearbox\")\n state.add_memlet_path(gearbox_to_write_read,\n write_entry,\n write_tasklet,\n dst_conn=\"from_gearbox\",\n memlet=dace.Memlet(\"gearbox_to_write[0]\"))\n state.add_memlet_path(write_tasklet,\n write_exit,\n memory_write,\n src_conn=\"mem\",\n memlet=dace.Memlet(\"output_array[i]\"))\n\n # Copy data to the FPGA\n sdfg.add_array(\"input_array_host\", (n, ), dtype)\n pre_state = sdfg.add_state(\"host_to_device\")\n host_to_device_read = pre_state.add_read(\"input_array_host\")\n host_to_device_write = pre_state.add_write(\"input_array\")\n pre_state.add_memlet_path(\n host_to_device_read,\n host_to_device_write,\n memlet=dace.Memlet(f\"input_array[0:n/{mem_width}]\"))\n\n # Copy data back to the host\n sdfg.add_array(\"output_array_host\", (n, ), dtype)\n post_state = sdfg.add_state(\"device_to_host\")\n device_to_host_read = post_state.add_read(\"output_array\")\n device_to_host_write = post_state.add_write(\"output_array_host\")\n post_state.add_memlet_path(\n device_to_host_read,\n device_to_host_write,\n memlet=dace.Memlet(f\"output_array[0:n/{mem_width}]\"))\n\n # Link states\n sdfg.add_edge(pre_state, state, dace.InterstateEdge())\n sdfg.add_edge(state, post_state, dace.InterstateEdge())\n\n run_program(sdfg)\n\n return sdfg\n\n\n@xilinx_test()\ndef test_memory_buffering_manual():\n return memory_buffering(4, False, False)\n\n\n@xilinx_test()\ndef test_memory_buffering_manual_scalar():\n return memory_buffering(1, False, False)\n\n\n@xilinx_test()\ndef test_memory_buffering_library_node():\n return memory_buffering(4, True, False)\n\n\n@xilinx_test()\ndef test_memory_buffering_library_node_scalar():\n return memory_buffering(1, True, False)\n\n\n@fpga_test()\ndef test_memory_buffering_library_node_elementwise():\n return memory_buffering(4, True, True)\n\n\n@fpga_test()\ndef test_memory_buffering_library_node_elementwise_scalar():\n return memory_buffering(1, True, True)\n\n\nif __name__ == \"__main__\":\n test_memory_buffering_manual(None)\n test_memory_buffering_library_node(None)\n test_memory_buffering_library_node_scalar(None)\n test_memory_buffering_library_node_elementwise(None)\n",
"# Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved.\nimport argparse\nimport numpy as np\nfrom veclen_conversion_test import SIZE, VECTOR_LENGTH, make_sdfg\nfrom dace.fpga_testing import fpga_test\n\n\n@fpga_test()\ndef test_veclen_conversion_connector():\n\n size = 128\n vector_length = 4\n\n SIZE.set(size)\n VECTOR_LENGTH.set(vector_length)\n\n if size % vector_length != 0:\n raise ValueError(\n \"Size {} must be divisible by vector length {}.\".format(\n size, vector_length))\n\n sdfg = make_sdfg(name=\"veclen_conversion_connector\",\n vectorize_connector=True)\n sdfg.specialize({\"W\": vector_length})\n\n A = np.arange(size, dtype=np.float64)\n B = np.zeros((size, ), dtype=np.float64)\n\n sdfg(A=A, B=B, N=SIZE)\n\n mid = vector_length // 2\n\n for i in range(size // vector_length):\n expected = np.concatenate(\n (A[i * vector_length + mid:(i + 1) * vector_length],\n A[i * vector_length:i * vector_length + mid]))\n if any(B[i * vector_length:(i + 1) * vector_length] != expected):\n raise ValueError(\"Shuffle failed: {} (should be {})\".format(\n B, expected))\n\n return sdfg\n\n\nif __name__ == \"__main__\":\n test_veclen_conversion_connector(None)\n",
"# Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved.\n\nimport dace\nimport numpy as np\n\n\ndef test():\n N = dace.symbol(\"N\")\n\n sdfg = dace.SDFG(\"parallel_sections\")\n\n sdfg.add_array(\"array_in\", (2 * N, ), dace.dtypes.int32)\n sdfg.add_array(\"array_out\", (N, ), dace.dtypes.int32)\n\n sdfg.add_stream(\"fifo_in_a\", dace.dtypes.int32, 1, transient=True)\n sdfg.add_stream(\"fifo_in_b\", dace.dtypes.int32, 1, transient=True)\n sdfg.add_stream(\"fifo_out\", dace.dtypes.int32, 1, transient=True)\n\n state = sdfg.add_state(\"sections\")\n\n array_in = state.add_access(\"array_in\")\n array_out = state.add_access(\"array_out\")\n\n fifo_in_a_0 = state.add_access(\"fifo_in_a\")\n fifo_in_b_0 = state.add_access(\"fifo_in_b\")\n fifo_in_a_1 = state.add_access(\"fifo_in_a\")\n fifo_in_b_1 = state.add_access(\"fifo_in_b\")\n fifo_out_0 = state.add_access(\"fifo_out\")\n fifo_out_1 = state.add_access(\"fifo_out\")\n\n ###########################################################################\n # First processing element: reads from memory into a stream\n\n read_a_entry, read_a_exit = state.add_map(\n \"read_map_a\", {\"i\": \"0:N\"},\n schedule=dace.dtypes.ScheduleType.Sequential)\n read_a_tasklet = state.add_tasklet(\"read_a\", {\"from_memory\"}, {\"to_stream\"},\n \"to_stream = from_memory\")\n\n # Inner edges\n state.add_edge(read_a_entry, None, read_a_tasklet, \"from_memory\",\n dace.memlet.Memlet.simple(array_in, \"i\"))\n state.add_edge(read_a_tasklet, \"to_stream\", read_a_exit, None,\n dace.memlet.Memlet.simple(fifo_in_a_0, \"0\"))\n\n # Outer edges\n state.add_edge(array_in, None, read_a_entry, None,\n dace.memlet.Memlet.simple(array_in, \"0:N\"))\n state.add_edge(read_a_exit, None, fifo_in_a_0, None,\n dace.memlet.Memlet.simple(fifo_in_a_0, \"0\"))\n\n ###########################################################################\n # Second processing element: reads from memory into a stream\n\n read_b_entry, read_b_exit = state.add_map(\n \"read_map_b\", {\"i\": \"N:2*N\"},\n schedule=dace.dtypes.ScheduleType.Sequential)\n read_b_tasklet = state.add_tasklet(\"read_b\", {\"from_memory\"}, {\"to_stream\"},\n \"to_stream = from_memory\")\n\n # Inner edges\n state.add_edge(read_b_entry, None, read_b_tasklet, \"from_memory\",\n dace.memlet.Memlet.simple(array_in, \"i\"))\n state.add_edge(read_b_tasklet, \"to_stream\", read_b_exit, None,\n dace.memlet.Memlet.simple(fifo_in_b_0, \"0\"))\n\n # Outer edges\n state.add_edge(array_in, None, read_b_entry, None,\n dace.memlet.Memlet.simple(array_in, \"0:N\"))\n state.add_edge(read_b_exit, None, fifo_in_b_0, None,\n dace.memlet.Memlet.simple(fifo_in_b_0, \"0\"))\n\n ###########################################################################\n # Third processing element: reads from both input streams, adds the\n # numbers, the writes it to the output stream\n\n compute_entry, compute_exit = state.add_map(\n \"compute_map\", {\"i\": \"0:N\"},\n schedule=dace.dtypes.ScheduleType.Sequential)\n compute_tasklet = state.add_tasklet(\"compute\", {\"a\", \"b\"}, {\"c\"},\n \"c = a + b\")\n\n # Inner edges\n state.add_edge(compute_entry, None, compute_tasklet, \"a\",\n dace.memlet.Memlet.simple(fifo_in_a_1, \"0\"))\n state.add_edge(compute_entry, None, compute_tasklet, \"b\",\n dace.memlet.Memlet.simple(fifo_in_b_1, \"0\"))\n state.add_edge(compute_tasklet, \"c\", compute_exit, None,\n dace.memlet.Memlet.simple(fifo_out_0, \"0\"))\n\n # Outer edges\n state.add_edge(fifo_in_a_1, None, compute_entry, None,\n dace.memlet.Memlet.simple(fifo_in_a_1, \"0\"))\n state.add_edge(fifo_in_b_1, None, compute_entry, None,\n dace.memlet.Memlet.simple(fifo_in_b_1, \"0\"))\n state.add_edge(compute_exit, None, fifo_out_0, None,\n dace.memlet.Memlet.simple(fifo_out_0, \"0\"))\n\n ###########################################################################\n # Fourth processing element: reads from stream into an array\n\n write_entry, write_exit = state.add_map(\n \"write_map\", {\"i\": \"0:N\"}, schedule=dace.dtypes.ScheduleType.Sequential)\n write_tasklet = state.add_tasklet(\"write\", {\"from_stream\"}, {\"to_memory\"},\n \"to_memory = from_stream\")\n\n # Inner edges\n state.add_edge(write_entry, None, write_tasklet, \"from_stream\",\n dace.memlet.Memlet.simple(fifo_out_1, \"0\"))\n state.add_edge(write_tasklet, \"to_memory\", write_exit, None,\n dace.memlet.Memlet.simple(array_out, \"i\"))\n\n # Outer edges\n state.add_edge(fifo_out_1, None, write_entry, None,\n dace.memlet.Memlet.simple(fifo_out_1, \"0\"))\n state.add_edge(write_exit, None, array_out, None,\n dace.memlet.Memlet.simple(array_out, \"0:N\"))\n\n ###########################################################################\n N = 1024\n array_in = np.ndarray([2 * N], np.int32)\n array_in[:N] = range(0, N)\n array_in[N:] = range(0, N)\n array_out = np.ndarray([N], np.int32)\n sdfg(array_in=array_in, array_out=array_out, N=N)\n\n for i, val in enumerate(array_out):\n if val != 2 * i:\n print(i, val)\n raise ValueError\n\n\nif __name__ == '__main__':\n test()\n",
"# Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved.\nimport ast\nimport astunparse\nimport collections\nimport functools\nimport itertools\nimport operator\nimport re\n\nimport dace\nfrom dace import data as dt, subsets as sbs\nimport numpy as np\nfrom .subscript_converter import SubscriptConverter\nfrom ._common import *\n\n\[email protected]\nclass ExpandStencilIntelFPGA(dace.library.ExpandTransformation):\n\n environments = []\n\n @staticmethod\n def expansion(node, parent_state, parent_sdfg):\n\n sdfg = dace.SDFG(node.label + \"_outer\")\n state = sdfg.add_state(node.label + \"_outer\")\n\n (inputs, outputs, shape, field_to_data, field_to_desc, field_to_edge,\n vector_lengths) = parse_connectors(node, parent_state, parent_sdfg)\n\n #######################################################################\n # Parse the tasklet code\n #######################################################################\n\n # Replace relative indices with memlet names\n converter = SubscriptConverter()\n\n # Add copy boundary conditions\n for field in node.boundary_conditions:\n if node.boundary_conditions[field][\"btype\"] == \"copy\":\n center_index = tuple(0 for _ in range(\n len(parent_sdfg.arrays[field_to_data[field]].shape)))\n # This will register the renaming\n converter.convert(field, center_index)\n\n # Replace accesses in the code\n code, field_accesses = parse_accesses(node.code.as_string, outputs)\n\n iterator_mapping = make_iterator_mapping(node, field_accesses, shape)\n vector_length = validate_vector_lengths(vector_lengths,\n iterator_mapping)\n shape_vectorized = tuple(s / vector_length if i == len(shape) -\n 1 else s for i, s in enumerate(shape))\n\n # Extract which fields to read from streams and what to buffer\n buffer_sizes = collections.OrderedDict()\n buffer_accesses = collections.OrderedDict()\n scalars = {} # {name: type}\n for field_name in inputs:\n relative = field_accesses[field_name]\n dim_mask = iterator_mapping[field_name]\n if not any(dim_mask):\n # This is a scalar, no buffer needed. Instead, the SDFG must\n # take this as a symbol\n scalars[field_name] = parent_sdfg.symbols[field_name]\n sdfg.add_symbol(field_name, parent_sdfg.symbols[field_name])\n continue\n abs_indices = ([\n dim_to_abs_val(i, tuple(s for s, m in zip(shape, dim_mask)\n if m), parent_sdfg) for i in relative\n ] + ([0] if field_name in node.boundary_conditions\n and node.boundary_conditions[field_name][\"btype\"] == \"copy\"\n else []))\n max_access = max(abs_indices)\n min_access = min(abs_indices)\n buffer_size = max_access - min_access + vector_lengths[field_name]\n buffer_sizes[field_name] = buffer_size\n # (indices relative to center, buffer indices, center index)\n buffer_accesses[field_name] = ([tuple(r) for r in relative], [\n i - min_access for i in abs_indices\n ], -min_access)\n\n # Create a initialization phase corresponding to the highest distance\n # to the center\n init_sizes = [\n (buffer_sizes[key] - vector_lengths[key] - val[2]) // vector_length\n for key, val in buffer_accesses.items()\n ]\n init_size_max = int(np.max(init_sizes))\n\n parameters = [f\"_i{i}\" for i in range(len(shape))]\n\n # Dimensions we need to iterate over\n iterator_mask = np.array([s != 0 and s != 1 for s in shape], dtype=bool)\n iterators = make_iterators(\n tuple(s for s, m in zip(shape_vectorized, iterator_mask) if m),\n parameters=tuple(s for s, m in zip(parameters, iterator_mask) if m))\n\n # Manually add pipeline entry and exit nodes\n pipeline_range = dace.properties.SubsetProperty.from_string(', '.join(\n iterators.values()))\n pipeline = dace.sdfg.nodes.Pipeline(\n \"compute_\" + node.label,\n list(iterators.keys()),\n pipeline_range,\n dace.dtypes.ScheduleType.FPGA_Device,\n False,\n init_size=init_size_max,\n init_overlap=False,\n drain_size=init_size_max,\n drain_overlap=True)\n entry = dace.sdfg.nodes.PipelineEntry(pipeline)\n exit = dace.sdfg.nodes.PipelineExit(pipeline)\n state.add_nodes_from([entry, exit])\n\n # Add nested SDFG to do 1) shift buffers 2) read from input 3) compute\n nested_sdfg = dace.SDFG(node.label + \"_inner\", parent=state)\n nested_sdfg_tasklet = state.add_nested_sdfg(\n nested_sdfg,\n sdfg,\n # Input connectors\n [k + \"_in\" for k in inputs if any(iterator_mapping[k])] +\n [name + \"_buffer_in\" for name, _ in buffer_sizes.items()],\n # Output connectors\n [k + \"_out\" for k in outputs] +\n [name + \"_buffer_out\" for name, _ in buffer_sizes.items()],\n schedule=dace.ScheduleType.FPGA_Device)\n # Propagate symbols\n for sym_name, sym_type in parent_sdfg.symbols.items():\n nested_sdfg.add_symbol(sym_name, sym_type)\n nested_sdfg_tasklet.symbol_mapping[sym_name] = sym_name\n # Map iterators\n for p in parameters:\n nested_sdfg.add_symbol(p, dace.int64)\n nested_sdfg_tasklet.symbol_mapping[p] = p\n\n # Shift state, which shifts all buffers by one\n shift_state = nested_sdfg.add_state(node.label + \"_shift\")\n\n # Update state, which reads new values from memory\n update_state = nested_sdfg.add_state(node.label + \"_update\")\n\n #######################################################################\n # Implement boundary conditions\n #######################################################################\n\n boundary_code, oob_cond = generate_boundary_conditions(\n node, shape, field_accesses, field_to_desc, iterator_mapping)\n\n #######################################################################\n # Only write if we're in bounds\n #######################################################################\n\n write_code = (\"\\n\".join([\n \"{}_inner_out = {}\\n\".format(\n output,\n field_accesses[output][tuple(0 for _ in range(len(shape)))])\n for output in outputs\n ]))\n if init_size_max > 0 or len(oob_cond) > 0:\n write_cond = []\n if init_size_max > 0:\n init_cond = pipeline.init_condition()\n write_cond.append(\"not \" + init_cond)\n nested_sdfg_tasklet.symbol_mapping[init_cond] = init_cond\n nested_sdfg.add_symbol(init_cond, dace.bool)\n if len(oob_cond) > 0:\n oob_cond = \" or \".join(sorted(oob_cond))\n oob_cond = f\"not ({oob_cond})\"\n write_cond.append(oob_cond)\n write_cond = \" and \".join(write_cond)\n write_cond = f\"if {write_cond}:\\n\\t\"\n else:\n write_cond = \"\"\n\n code = boundary_code + \"\\n\" + code + \"\\n\" + write_code\n\n #######################################################################\n # Create DaCe compute state\n #######################################################################\n\n # Compute state, which reads from input channels, performs the compute,\n # and writes to the output channel(s)\n compute_state = nested_sdfg.add_state(node.label + \"_compute\")\n compute_inputs = list(\n itertools.chain.from_iterable(\n [[\"_\" + v for v in field_accesses[f].values()] for f in inputs\n if any(iterator_mapping[f])]))\n compute_tasklet = compute_state.add_tasklet(\n node.label + \"_compute\",\n compute_inputs, {name + \"_inner_out\"\n for name in outputs},\n code,\n language=dace.dtypes.Language.Python)\n if vector_length > 1:\n compute_unroll_entry, compute_unroll_exit = compute_state.add_map(\n compute_state.label + \"_unroll\",\n {\"i_unroll\": f\"0:{vector_length}\"},\n schedule=dace.ScheduleType.FPGA_Device,\n unroll=True)\n\n # Connect the three nested states\n nested_sdfg.add_edge(shift_state, update_state,\n dace.sdfg.InterstateEdge())\n nested_sdfg.add_edge(update_state, compute_state,\n dace.sdfg.InterstateEdge())\n\n # First, grab scalar variables\n for scalar, scalar_type in scalars.items():\n nested_sdfg.add_symbol(scalar, scalar_type)\n\n # Code to increment custom iterators\n iterator_code = \"\"\n\n for (field_name, size), init_size in zip(buffer_sizes.items(),\n init_sizes):\n\n data_name = field_to_data[field_name]\n connector = field_to_edge[field_name].dst_conn\n data_name_outer = connector\n data_name_inner = field_name + \"_in\"\n desc_outer = parent_sdfg.arrays[data_name].clone()\n desc_outer.transient = False\n sdfg.add_datadesc(data_name_outer, desc_outer)\n\n mapping = iterator_mapping[field_name]\n is_array = not isinstance(desc_outer, dt.Stream)\n\n # If this array is part of the initialization phase, it needs its\n # own iterator, which we need to instantiate and increment in the\n # outer SDFG\n if is_array:\n if init_size == 0:\n field_index = [s for s, p in zip(parameters, mapping) if p]\n else:\n # Create custom iterators for this array\n num_dims = sum(mapping, 0)\n field_iterators = [(f\"_{field_name}_i{i}\", shape[i])\n for i in range(num_dims) if mapping[i]]\n start_index = init_size_max - init_size\n tab = \"\"\n if start_index > 0:\n iterator_code += (\n f\"if {pipeline.iterator_str()} >= {start_index}:\\n\")\n tab += \" \"\n for i, (it, s) in enumerate(reversed(field_iterators)):\n iterator_code += f\"\"\"\\\n{tab}if {it} < {s} - 1:\n{tab} {it} = {it} + 1\n{tab}else:\n{tab} {it} = 0\\n\"\"\"\n tab += \" \"\n field_index = [fi[0] for fi in field_iterators]\n for fi in field_index:\n pipeline.additional_iterators[fi] = \"0\"\n nested_sdfg.add_symbol(fi, dace.int64)\n nested_sdfg_tasklet.symbol_mapping[fi] = fi\n field_index = \", \".join(field_index)\n else:\n field_index = \"0\"\n\n # Begin reading according to this field's own buffer size, which is\n # translated to an index by subtracting it from the maximum buffer\n # size\n begin_reading = init_size_max - init_size\n total_size = functools.reduce(operator.mul, shape_vectorized, 1)\n end_reading = total_size + init_size_max - init_size\n\n # Outer memory read\n read_node_outer = state.add_read(data_name_outer)\n if begin_reading != 0 or end_reading != total_size + init_size_max:\n sdfg.add_scalar(f\"{field_name}_wavefront\",\n desc_outer.dtype,\n storage=dace.StorageType.FPGA_Local,\n transient=True)\n wavefront_access = state.add_access(f\"{field_name}_wavefront\")\n condition = []\n it = pipeline.iterator_str()\n if begin_reading != 0:\n condition.append(f\"{it} >= {begin_reading}\")\n if end_reading != total_size + init_size_max:\n condition.append(f\"{it} < {end_reading}\")\n condition = \" and \".join(condition)\n update_tasklet = state.add_tasklet(\n f\"read_{field_name}\", {\"wavefront_in\"}, {\"wavefront_out\"},\n f\"if {condition}:\\n\"\n \"\\twavefront_out = wavefront_in\\n\",\n language=dace.dtypes.Language.Python)\n state.add_memlet_path(read_node_outer,\n entry,\n update_tasklet,\n dst_conn=\"wavefront_in\",\n memlet=dace.Memlet(\n f\"{data_name_outer}[{field_index}]\",\n dynamic=True))\n state.add_memlet_path(update_tasklet,\n wavefront_access,\n src_conn=\"wavefront_out\",\n memlet=dace.Memlet(\n f\"{field_name}_wavefront\",\n dynamic=True))\n state.add_memlet_path(\n wavefront_access,\n nested_sdfg_tasklet,\n dst_conn=f\"{field_name}_in\",\n memlet=dace.Memlet(f\"{field_name}_wavefront\"))\n else:\n state.add_memlet_path(\n read_node_outer,\n entry,\n nested_sdfg_tasklet,\n dst_conn=f\"{field_name}_in\",\n memlet=dace.Memlet(f\"{data_name_outer}[{field_index}]\"))\n\n # Create inner memory access\n nested_sdfg.add_scalar(data_name_inner,\n desc_outer.dtype,\n storage=dace.StorageType.FPGA_Local,\n transient=False)\n\n buffer_name_outer = f\"{node.label}_{field_name}_buffer\"\n buffer_name_inner_read = f\"{field_name}_buffer_in\"\n buffer_name_inner_write = f\"{field_name}_buffer_out\"\n\n # Create buffer transient in outer SDFG\n field_dtype = parent_sdfg.data(data_name).dtype\n _, desc_outer = sdfg.add_array(\n buffer_name_outer, (size, ),\n field_dtype.base_type,\n storage=dace.dtypes.StorageType.FPGA_Local,\n transient=True)\n\n # Create read and write nodes\n read_node_outer = state.add_read(buffer_name_outer)\n write_node_outer = state.add_write(buffer_name_outer)\n\n # Outer buffer read\n state.add_memlet_path(\n read_node_outer,\n entry,\n nested_sdfg_tasklet,\n dst_conn=buffer_name_inner_read,\n memlet=dace.Memlet(f\"{buffer_name_outer}[0:{size}]\"))\n\n # Outer buffer write\n state.add_memlet_path(nested_sdfg_tasklet,\n exit,\n write_node_outer,\n src_conn=buffer_name_inner_write,\n memlet=dace.Memlet(\n f\"{write_node_outer.data}[0:{size}]\",\n dynamic=True))\n\n # Inner copy\n desc_inner_read = desc_outer.clone()\n desc_inner_read.transient = False\n desc_inner_read.name = buffer_name_inner_read\n desc_inner_write = desc_inner_read.clone()\n desc_inner_write.name = buffer_name_inner_write\n nested_sdfg.add_datadesc(buffer_name_inner_read, desc_inner_read)\n nested_sdfg.add_datadesc(buffer_name_inner_write, desc_inner_write)\n\n # Make shift state if necessary\n if size > 1:\n shift_read = shift_state.add_read(buffer_name_inner_read)\n shift_write = shift_state.add_write(buffer_name_inner_write)\n shift_entry, shift_exit = shift_state.add_map(\n f\"shift_{field_name}\",\n {\"i_shift\": f\"0:{size} - {vector_lengths[field_name]}\"},\n schedule=dace.dtypes.ScheduleType.FPGA_Device,\n unroll=True)\n shift_tasklet = shift_state.add_tasklet(\n f\"shift_{field_name}\", {f\"{field_name}_shift_in\"},\n {f\"{field_name}_shift_out\"},\n f\"{field_name}_shift_out = {field_name}_shift_in\")\n shift_state.add_memlet_path(\n shift_read,\n shift_entry,\n shift_tasklet,\n dst_conn=field_name + \"_shift_in\",\n memlet=dace.Memlet(\n f\"{shift_read.data}\"\n f\"[i_shift + {vector_lengths[field_name]}]\"))\n shift_state.add_memlet_path(\n shift_tasklet,\n shift_exit,\n shift_write,\n src_conn=field_name + \"_shift_out\",\n memlet=dace.Memlet(f\"{shift_write.data}[i_shift]\"))\n\n # Make update state\n update_read = update_state.add_read(data_name_inner)\n update_write = update_state.add_write(buffer_name_inner_write)\n subset = f\"{size} - {vector_length}:{size}\" if size > 1 else \"0\"\n update_state.add_memlet_path(update_read,\n update_write,\n memlet=dace.Memlet(\n f\"{update_read.data}\",\n other_subset=f\"{subset}\"))\n\n # Make compute state\n compute_read = compute_state.add_read(buffer_name_inner_read)\n for relative, offset in zip(buffer_accesses[field_name][0],\n buffer_accesses[field_name][1]):\n memlet_name = field_accesses[field_name][tuple(relative)]\n if vector_length > 1:\n if vector_lengths[field_name] > 1:\n offset = f\"{offset} + i_unroll\"\n else:\n offset = str(offset)\n path = [compute_read, compute_unroll_entry, compute_tasklet]\n else:\n offset = str(offset)\n path = [compute_read, compute_tasklet]\n compute_state.add_memlet_path(\n *path,\n dst_conn=\"_\" + memlet_name,\n memlet=dace.Memlet(f\"{compute_read.data}[{offset}]\"))\n\n # Tasklet to update iterators\n if iterator_code:\n update_iterator_tasklet = state.add_tasklet(\n f\"{node.label}_update_iterators\", {}, {}, iterator_code)\n state.add_memlet_path(nested_sdfg_tasklet,\n update_iterator_tasklet,\n memlet=dace.Memlet())\n state.add_memlet_path(update_iterator_tasklet,\n exit,\n memlet=dace.Memlet())\n\n for field_name in outputs:\n\n for offset in field_accesses[field_name]:\n if offset is not None and list(offset) != [0] * len(offset):\n raise NotImplementedError(\"Output offsets not implemented\")\n\n data_name = field_to_data[field_name]\n\n # Outer write\n data_name_outer = field_name\n data_name_inner = field_name + \"_out\"\n desc_outer = parent_sdfg.arrays[data_name].clone()\n desc_outer.transient = False\n array_index = \", \".join(map(str, parameters))\n try:\n sdfg.add_datadesc(data_name_outer, desc_outer)\n except NameError: # Already an input\n parent_sdfg.arrays[data_name].access = (\n dace.AccessType.ReadWrite)\n\n # Create inner access\n nested_sdfg.add_scalar(data_name_inner,\n desc_outer.dtype,\n storage=dace.StorageType.FPGA_Local,\n transient=False)\n\n # Inner write\n write_node_inner = compute_state.add_write(data_name_inner)\n\n # Intermediate buffer, mostly relevant for vectorization\n output_buffer_name = field_name + \"_output_buffer\"\n nested_sdfg.add_array(output_buffer_name, (vector_length, ),\n desc_outer.dtype.base_type,\n storage=dace.StorageType.FPGA_Registers,\n transient=True)\n output_buffer = compute_state.add_access(output_buffer_name)\n\n # If vectorized, we need to pass through the unrolled scope\n if vector_length > 1:\n compute_state.add_memlet_path(\n compute_tasklet,\n compute_unroll_exit,\n output_buffer,\n src_conn=field_name + \"_inner_out\",\n memlet=dace.Memlet(f\"{output_buffer_name}[i_unroll]\"))\n else:\n compute_state.add_memlet_path(\n compute_tasklet,\n output_buffer,\n src_conn=field_name + \"_inner_out\",\n memlet=dace.Memlet(f\"{output_buffer_name}[0]\")),\n\n # Final memlet to the output\n compute_state.add_memlet_path(\n output_buffer,\n write_node_inner,\n memlet=dace.Memlet(f\"{write_node_inner.data}\")),\n\n # Conditional write tasklet\n sdfg.add_scalar(f\"{field_name}_result\",\n desc_outer.dtype,\n storage=dace.StorageType.FPGA_Local,\n transient=True)\n output_access = state.add_access(f\"{field_name}_result\")\n state.add_memlet_path(nested_sdfg_tasklet,\n output_access,\n src_conn=data_name_inner,\n memlet=dace.Memlet(f\"{field_name}_result\"))\n output_tasklet = state.add_tasklet(\n f\"{field_name}_conditional_write\", {f\"_{field_name}_result\"},\n {f\"_{data_name_inner}\"},\n (write_cond + f\"_{data_name_inner} = _{field_name}_result\"))\n state.add_memlet_path(output_access,\n output_tasklet,\n dst_conn=f\"_{field_name}_result\",\n memlet=dace.Memlet(f\"{field_name}_result\"))\n write_node_outer = state.add_write(data_name_outer)\n if isinstance(desc_outer, dt.Stream):\n subset = \"0\"\n else:\n subset = array_index\n state.add_memlet_path(output_tasklet,\n exit,\n write_node_outer,\n src_conn=f\"_{data_name_inner}\",\n memlet=dace.Memlet(\n f\"{write_node_outer.data}[{subset}]\",\n dynamic=True)),\n\n return sdfg\n"
] |
[
[
"numpy.allclose",
"numpy.reshape",
"numpy.arange",
"numpy.median",
"numpy.linalg.norm",
"numpy.empty",
"numpy.copy",
"numpy.transpose",
"numpy.zeros",
"numpy.random.default_rng"
],
[
"numpy.random.rand",
"numpy.zeros",
"numpy.sum",
"numpy.allclose"
],
[
"numpy.random.rand",
"numpy.ndarray",
"numpy.allclose"
],
[
"numpy.maximum",
"numpy.allclose",
"numpy.ndarray",
"numpy.random.rand",
"numpy.exp",
"numpy.random.randint"
],
[
"numpy.empty",
"numpy.ones"
],
[
"numpy.concatenate",
"numpy.arange",
"numpy.zeros"
],
[
"numpy.ndarray"
],
[
"numpy.max",
"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": []
}
] |
martin-fabbri/ml-pipelines
|
[
"62d512752d68448168493c30b00baf9318db14e8"
] |
[
"reproducible-dvc/studentpredictor/create_features.py"
] |
[
"from datetime import date\n\nimport pandas as pd\nfrom config import Config\n\nConfig.FEATURES_PATH.mkdir(parents=True, exist_ok=True)\n\ntrain_df = pd.read_csv(str(Config.DATASET_PATH / \"train.csv\"))\ntest_df = pd.read_csv(str(Config.DATASET_PATH / \"test.csv\"))\n\n\ndef extract_features(df):\n df[\"published_timestamp\"] = pd.to_datetime(df.published_timestamp).dt.date\n df[\"days_since_published\"] = (date.today() - df.published_timestamp).dt.days\n return df[[\"num_lectures\", \"price\", \"days_since_published\", \"content_duration\"]]\n\n\ntrain_features = extract_features(train_df)\ntest_features = extract_features(test_df)\n\ntrain_features.to_csv(str(Config.FEATURES_PATH / \"train_features.csv\"), index=None)\ntest_features.to_csv(str(Config.FEATURES_PATH / \"test_features.csv\"), index=None)\n\ntrain_df.num_subscribers.to_csv(\n str(Config.FEATURES_PATH / \"train_labels.csv\"), index=None\n)\ntest_df.num_subscribers.to_csv(\n str(Config.FEATURES_PATH / \"test_labels.csv\"), index=None\n)\n"
] |
[
[
"pandas.to_datetime"
]
] |
[
{
"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": []
}
] |
NingxinSu/plato
|
[
"94c1c0d7d8b1a1b0ff7f6d9efcf1883f314d9668"
] |
[
"plato/config.py"
] |
[
"\"\"\"\nReading runtime parameters from a standard configuration file (which is easier\nto work on than JSON).\n\"\"\"\nimport argparse\nimport logging\nimport os\nimport random\nimport sqlite3\nfrom collections import OrderedDict, namedtuple\n\nimport yaml\nfrom yamlinclude import YamlIncludeConstructor\n\n\nclass Config:\n \"\"\"\n Retrieving configuration parameters by parsing a configuration file\n using the YAML configuration file parser.\n \"\"\"\n\n _instance = None\n\n def __new__(cls):\n if cls._instance is None:\n parser = argparse.ArgumentParser()\n parser.add_argument('-i',\n '--id',\n type=str,\n help='Unique client ID.')\n parser.add_argument('-p',\n '--port',\n type=str,\n help='The port number for running a server.')\n parser.add_argument('-c',\n '--config',\n type=str,\n default='./config.yml',\n help='Federated learning configuration file.')\n parser.add_argument('-s',\n '--server',\n type=str,\n default=None,\n help='The server hostname and port number.')\n parser.add_argument(\n '-d',\n '--download',\n action='store_true',\n help='Download the dataset to prepare for a training session.')\n parser.add_argument('-l',\n '--log',\n type=str,\n default='info',\n help='Log messages level.')\n\n args = parser.parse_args()\n Config.args = args\n\n if Config.args.id is not None:\n Config.args.id = int(args.id)\n if Config.args.port is not None:\n Config.args.port = int(args.port)\n\n try:\n log_level = {\n 'critical': logging.CRITICAL,\n 'error': logging.ERROR,\n 'warn': logging.WARN,\n 'info': logging.INFO,\n 'debug': logging.DEBUG\n }[args.log]\n except KeyError:\n log_level = logging.INFO\n\n logging.basicConfig(\n format='[%(levelname)s][%(asctime)s]: %(message)s',\n level=log_level,\n datefmt='%H:%M:%S')\n\n cls._instance = super(Config, cls).__new__(cls)\n\n if 'config_file' in os.environ:\n filename = os.environ['config_file']\n else:\n filename = args.config\n\n YamlIncludeConstructor.add_to_loader_class(\n loader_class=yaml.SafeLoader, base_dir='./configs')\n\n if os.path.isfile(filename):\n with open(filename, 'r', encoding=\"utf8\") as config_file:\n config = yaml.load(config_file, Loader=yaml.SafeLoader)\n else:\n # if the configuration file does not exist, use a default one\n config = Config.default_config()\n\n Config.clients = Config.namedtuple_from_dict(config['clients'])\n Config.server = Config.namedtuple_from_dict(config['server'])\n Config.data = Config.namedtuple_from_dict(config['data'])\n Config.trainer = Config.namedtuple_from_dict(config['trainer'])\n Config.algorithm = Config.namedtuple_from_dict(config['algorithm'])\n\n if Config.args.server is not None:\n Config.server = Config.server._replace(\n address=args.server.split(':')[0])\n Config.server = Config.server._replace(\n port=args.server.split(':')[1])\n\n if Config.args.download:\n Config.clients = Config.clients._replace(total_clients=1)\n Config.clients = Config.clients._replace(per_round=1)\n\n if 'results' in config:\n Config.results = Config.namedtuple_from_dict(config['results'])\n if hasattr(Config().results, 'results_dir'):\n Config.result_dir = Config.results.results_dir\n else:\n datasource = Config.data.datasource\n model = Config.trainer.model_name\n server_type = Config.algorithm.type\n Config.result_dir = f'./results/{datasource}/{model}/{server_type}/'\n\n if 'model' in config:\n Config.model = Config.namedtuple_from_dict(config['model'])\n\n if hasattr(Config().trainer, 'max_concurrency'):\n # Using a temporary SQLite database to limit the maximum number of concurrent\n # trainers\n Config.sql_connection = sqlite3.connect(\n \"/tmp/running_trainers.sqlitedb\")\n Config().cursor = Config.sql_connection.cursor()\n\n # Customizable dictionary of global parameters\n Config.params: dict = {}\n\n # A run ID is unique to each client in an experiment\n Config.params['run_id'] = os.getpid()\n\n # Pretrained models\n Config.params['model_dir'] = \"./models/pretrained/\"\n Config.params['pretrained_model_dir'] = \"./models/pretrained/\"\n\n return cls._instance\n\n @staticmethod\n def namedtuple_from_dict(obj):\n \"\"\"Creates a named tuple from a dictionary.\"\"\"\n if isinstance(obj, dict):\n fields = sorted(obj.keys())\n namedtuple_type = namedtuple(typename='Config',\n field_names=fields,\n rename=True)\n field_value_pairs = OrderedDict(\n (str(field), Config.namedtuple_from_dict(obj[field]))\n for field in fields)\n try:\n return namedtuple_type(**field_value_pairs)\n except TypeError:\n # Cannot create namedtuple instance so fallback to dict (invalid attribute names)\n return dict(**field_value_pairs)\n elif isinstance(obj, (list, set, tuple, frozenset)):\n return [Config.namedtuple_from_dict(item) for item in obj]\n else:\n return obj\n\n @staticmethod\n def is_edge_server() -> bool:\n \"\"\"Returns whether the current instance is an edge server in cross-silo FL.\"\"\"\n return Config().args.port is not None\n\n @staticmethod\n def is_central_server() -> bool:\n \"\"\"Returns whether the current instance is a central server in cross-silo FL.\"\"\"\n return hasattr(Config().algorithm,\n 'cross_silo') and Config().args.port is None\n\n @staticmethod\n def device() -> str:\n \"\"\"Returns the device to be used for training.\"\"\"\n device = 'cpu'\n if hasattr(Config().trainer, 'use_mindspore'):\n pass\n elif hasattr(Config().trainer, 'use_tensorflow'):\n import tensorflow as tf\n gpus = tf.config.experimental.list_physical_devices('GPU')\n if len(gpus) > 0:\n device = 'GPU'\n tf.config.experimental.set_visible_devices(\n gpus[random.randint(0,\n len(gpus) - 1)], 'GPU')\n else:\n import torch\n\n if torch.cuda.is_available() and torch.cuda.device_count() > 0:\n if hasattr(Config().trainer,\n 'parallelized') and Config().trainer.parallelized:\n device = 'cuda'\n else:\n device = 'cuda:' + str(\n random.randint(0,\n torch.cuda.device_count() - 1))\n\n return device\n\n @staticmethod\n def is_parallel() -> bool:\n \"\"\"Check if the hardware and OS support data parallelism.\"\"\"\n import torch\n\n return hasattr(Config().trainer, 'parallelized') and Config(\n ).trainer.parallelized and torch.cuda.is_available(\n ) and torch.distributed.is_available(\n ) and torch.cuda.device_count() > 1\n\n @staticmethod\n def default_config() -> dict:\n ''' Supply a default configuration when the configuration file is missing. '''\n config = {}\n config['clients'] = {}\n config['clients']['type'] = 'simple'\n config['clients']['total_clients'] = 1\n config['clients']['per_round'] = 1\n config['clients']['do_test'] = False\n config['server'] = {}\n config['server']['address'] = '127.0.0.1'\n config['server']['port'] = 8000\n config['server']['disable_clients'] = True\n config['data'] = {}\n config['data']['datasource'] = 'MNIST'\n config['data']['data_path'] = './data'\n config['data']['partition_size'] = 20000\n config['data']['sampler'] = 'iid'\n config['data']['random_seed'] = 1\n config['trainer'] = {}\n config['trainer']['type'] = 'basic'\n config['trainer']['rounds'] = 5\n config['trainer']['parallelized'] = False\n config['trainer']['target_accuracy'] = 0.94\n config['trainer']['epochs'] = 5\n config['trainer']['batch_size'] = 32\n config['trainer']['optimizer'] = 'SGD'\n config['trainer']['learning_rate'] = 0.01\n config['trainer']['momentum'] = 0.9\n config['trainer']['weight_decay'] = 0.0\n config['trainer']['model_name'] = 'lenet5'\n config['algorithm'] = {}\n config['algorithm']['type'] = 'fedavg'\n\n return config\n\n @staticmethod\n def store() -> None:\n \"\"\" Saving the current run-time configuration to a file. \"\"\"\n data = {}\n data['clients'] = Config.clients._asdict()\n data['server'] = Config.server._asdict()\n data['data'] = Config.data._asdict()\n data['trainer'] = Config.trainer._asdict()\n data['algorithm'] = Config.algorithm._asdict()\n with open(Config.args.config, \"w\", encoding=\"utf8\") as out:\n yaml.dump(data, out, default_flow_style=False)\n"
] |
[
[
"torch.cuda.device_count",
"tensorflow.config.experimental.list_physical_devices",
"torch.distributed.is_available",
"torch.cuda.is_available"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ch-andrei/L-IQA
|
[
"e0e097aec2be468f5288594de89fbe489e4afff3"
] |
[
"utils/image_processing/color_spaces.py"
] |
[
"import cv2\nimport numpy as np\n\nfrom utils.image_processing.image_tools import img2array, imread\n\n\n# sources:\n# https://en.wikipedia.org/wiki/Relative_luminance\n# https://www.cl.cam.ac.uk/~rkm38/pdfs/mantiuk2016perceptual_display.pdf\n# converts to linear RGB then to luminance\ndef srgb2rgb(rgb, gamma=2.4):\n # convert to linear rgb\n c = 0.04045\n a = 0.055\n rgb_lin = rgb / 12.92\n rgb_lin[rgb > c] = np.power((rgb[rgb > c] + a) / (1.0 + a), gamma)\n return rgb_lin\n\n\ndef rgb2srgb(rgb_lin, gamma=2.4):\n c = 0.0031308\n a = 0.055\n rgb = rgb_lin * 12.92\n rgb[rgb_lin > c] = (1 + a) * np.power(rgb_lin[rgb_lin > c], 1 / gamma) - a\n return rgb\n\n\ndef srgb2lum(rgb, gamma=2.4):\n rgb_lin = srgb2rgb(rgb, gamma)\n return rgb2gray_matlab(rgb_lin)\n\n\ndef rgb_lum_weighted(rgb):\n lum_w = np.zeros_like(rgb)\n lum_w[..., 0] = rgb[..., 0] * 0.2126\n lum_w[..., 1] = rgb[..., 1] * 0.7152\n lum_w[..., 2] = rgb[..., 2] * 0.0722\n return lum_w\n\n\ndef rgb_lum_unweighted(rgb):\n lum_w = np.zeros_like(rgb)\n lum_w[..., 0] = rgb[..., 0] / 0.2126\n lum_w[..., 1] = rgb[..., 1] / 0.7152\n lum_w[..., 2] = rgb[..., 2] / 0.0722\n return lum_w\n\n\ndef rgb2lum(rgb):\n return rgb[..., 0] * 0.2126 + rgb[..., 1] * 0.7152 + rgb[..., 2] * 0.0722\n\n\ndef rgb2gray_matlab(rgb):\n return rgb[..., 0] * 0.2989 + rgb[..., 1] * 0.5870 + rgb[..., 2] * 0.1140\n\n\n# converts image from RGB to XYZ color space\n# http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html\ndef rgb2xyz(img, shape_as_input=False, format_float=True):\n h, w, c = img.shape\n\n rgb = img2array(img)\n\n if format_float:\n rgb /= 255\n\n rgb = srgb2rgb(rgb)\n\n m = np.array(\n [[0.4124564, 0.3575761, 0.1804375],\n [0.2126729, 0.7151522, 0.0721750],\n [0.0193339, 0.1191920, 0.9503041]], np.float32)\n\n xyz = m.dot(rgb)\n\n return xyz.transpose().reshape(h, w, 3) if shape_as_input else xyz\n\n\ndef xyz2rgb(img, shape_as_input=False, cast_uint8=True):\n h, w, c = img.shape\n\n xyz = img2array(img)\n\n m = np.array([\n [3.2404542 , -1.5371385, -0.4985314],\n [-0.9692660, 1.8760108, 0.0415560],\n [0.0556434 , -0.2040259, 1.0572252]], np.float32)\n\n rgb = m.dot(xyz)\n\n if cast_uint8:\n rgb = (rgb * 255).astype(np.uint8)\n\n return rgb.transpose().reshape(h, w, 3) if shape_as_input else rgb\n\n\n# conversion from RGB to Cie L*a*b* color space is done as per\n# https://docs.opencv.org/2.4/modules/imgproc/doc/miscellaneous_transformations.html?highlight=cvtcolor#cvtcolor\n# reference illuminant: d65\ndef rgb2CieLab(rgb, format_float=False):\n xyz = rgb2xyz(rgb, shape_as_input=False, format_float=format_float)\n\n X, Y, Z = (xyz[0], xyz[1], xyz[2])\n # d65\n X /= 0.950456\n Z /= 1.088754\n\n def f_L(t, thresh=0.008856):\n L = np.zeros_like(t)\n inds = t > thresh\n ninds = (np.logical_not(inds))\n if inds.any():\n L[inds] = 116.0 * np.power(t[inds], 1.0 / 3.0) - 16.0\n if ninds.any():\n L[ninds] = 903.3 * t[ninds]\n return L\n\n def f_ab(t, thresh=0.008856):\n ab = np.zeros_like(t)\n inds = t > thresh\n ninds = np.logical_not(inds)\n if inds.any():\n ab[inds] = np.power(t[inds], 1.0 / 3.0)\n if ninds.any():\n ab[ninds] = 7.787 * t[ninds] + 16.0 / 116.0\n return ab\n\n lab = np.zeros((3, xyz.shape[1]), np.float32)\n lab[0] = f_L(Y) / 100\n lab[1] = (500.0 * (f_ab(X) - f_ab(Y)) + 127) / 255\n lab[2] = (200.0 * (f_ab(Y) - f_ab(Z)) + 127) / 255\n\n return lab.astype(np.float32)\n\n# test\nif __name__ == \"__main__\":\n imgpath = 'footage/renders'\n imgname = '25000_image_1_1920_1080.png'\n\n img = imread(imgname, imgpath)\n h, w, c = img.shape\n xyz = rgb2xyz(img, shape_as_input=True)\n rgb = xyz2rgb(xyz, shape_as_input=True)\n diff = (img == rgb)\n print(\"lossless for {}/{}={}% of all values\".format(diff.sum(), h * w * c, diff.sum() / (h * w * c)))\n cv2.imshow(\"img\", img)\n cv2.imshow(\"rgb\", rgb)\n cv2.waitKey()\n\n\n"
] |
[
[
"numpy.logical_not",
"numpy.power",
"numpy.zeros_like",
"numpy.array",
"numpy.zeros"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Rothdyt/codes-for-courses
|
[
"a2dfea516ebc7cabef31a5169533b6da352e7ccb",
"a2dfea516ebc7cabef31a5169533b6da352e7ccb"
] |
[
"Python_IE411/simplex_method/archived/simplex_method_new.py",
"Python_IE411/simplex_method/test11.py"
] |
[
"import numpy as np\nfrom simplex_step import simplex_step\nfrom simplex_init import find_negative_index\n\n\ndef simplex_init_modified(A, b, c):\n \"\"\"\n Attempt to find a basic feasible vector for the linear program\n\n max: c*x\n ST: Ax=b\n x>=0,\n\n where A is a (m,n) matrix.\n\n Input Parameters:\n\n A - (n,m) constraint matrix\n b - (m,1) vector appearing in the constraint equation above\n c - (1,n) vector giving the coefficients of the objective function\n\n\n Output Parameters:\n\n istatus - integer parameter reporting the condition of the\n istatus = 0 indicates a basic feasible vector was found\n istatus = 4 indicates that the initialization procedure failed\n istatus = 16 indicates that the problem is infeasible\n\n iB - integer vector of length m specifying the indices of the basic\n variables\n iN - integer vector of length n-m specying the indices of the nonbasic\n variables\n xB - vector of length m specifying the values of the basic\n variables\n \"\"\"\n A_new, b_new = A, b\n A_new[find_negative_index(b)] = -A[find_negative_index(b)]\n b_new[find_negative_index(b)] = -b[find_negative_index(b)]\n A_new = np.hstack((A_new, np.eye(b.shape[0])))\n # problem setup\n c_phase_I = np.zeros(A_new.shape[1]).reshape(1, -1)\n c_phase_I[0, c.shape[1]:] = np.ones(b.shape[0])\n iB = np.arange(c.shape[1], c.shape[1] + b.shape[0]) + 1 # index begin with 1 for input\n iN = np.arange(0, c.shape[1]) + 1\n xB = np.matrix(np.copy(b))\n istatus_step = 1000\n while istatus_step != -1:\n try:\n istatus_step, iB, iN, xB, Binv = simplex_step(A_new, b_new, c_phase_I, iB, iN, xB, irule=0)\n except np.linalg.LinAlgError:\n raise ValueError(\"iB cannot form a basis!\")\n if istatus_step == 16:\n istatus, iB, iN, xB, tableau = 4, None, None, None, None\n return istatus, iB, iN, xB\n iB = iB - 1\n optimal_cost = np.matmul(c_phase_I[0, iB].reshape(1, -2), xB)\n if optimal_cost > 0:\n istatus, iB, iN, xB, tableau = 16, None, None, None, None\n return istatus, iB, iN, xB\n if optimal_cost == 0:\n #print(\"optimal basis is found!\")\n istatus = 0\n artificial_idx = np.arange(c.shape[1], c.shape[1] + b.shape[0])\n artificial_in_basis = np.intersect1d(artificial_idx, iB)\n tableau = np.matmul(Binv, A_new)\n #c_new = np.concatenate((c, np.zeros(A.shape[0]).reshape(1, -1)), axis=1)\n #reduced_cost = c - np.matmul(np.matmul(c_new[0, iB], Binv), A)\n if len(artificial_in_basis) == 0:\n #print(\"no artificial variable in the final basis\")\n return istatus, iB+1, iN, xB, tableau[:, 0:A.shape[1]]\n else:\n #print(\"artificial variable in the final basis\")\n for xl in artificial_in_basis:\n row_l = tableau[np.where(iB == xl), :c.shape[1]]\n if np.sum(row_l) == 0:\n tableau = np.delete(tableau, np.where(iB == xl), axis=0)\n xB = np.delete(xB, np.where(iB == xl))\n iB = np.delete(iB, np.where(iB == xl))\n iN = np.setdiff1d(range(c.shape[1]), iB)\n iB = iB + 1\n iN = iN + 1\n xB = xB.reshape(-1, 1)\n return istatus, iB, iN, xB, tableau[:, 0:A.shape[1]]\n\n\ndef simplex_method(A, b, c, irule):\n \"\"\"\n Find a basic optimal solution for the linear program\n\n min: c*x\n ST: Ax=b\n x>=0,\n\n where A is an (m,n) matrix.\n\n Input Parameters:\n\n A - (n,m) constraint matrix\n b - (m,1) POSITIVE vector appearing in the constraint equation above\n c - (1,n) vector giving the coefficients of the objective function\n\n irule - integer parameter speciying which pivot rule to use:\n irule = 0 indicates that the smallest coefficient rule should be \n used\n irule = 1 indicates that Bland's rule should be used\n\n Output Parameters:\n\n istatus - integer parameter reporting the condition of the \n istatus = 0 indicates normal completeion (i.e., a solution\n has been found and reported)\n istatus = 4 indicates the program is infeasible\n istatus = 16 indicates the program is feasible but our initialization\n procedure has failed\n istatus = 32 indicates that the program is unbounded\n\n X - vector of length n specifying the solution\n eta - the minimum value of the objective function \n iB - integer vector specifying the m indices of the basic variables\n after the simplex step\n iN - integer vector specifying the n-m indices of the nonbasic \n variables after the simplex step\n xB - vector of length m specifying the values of the basic\n variables after the simplex step\n\n \"\"\"\n #init_status, iB, iN, xB, tableau = simplex_init_modified(A, b, c)\n init_status, iB, iN, xB, tableau = simplex_init_modified(A, b, c)\n if init_status == 4:\n istatus, X, eta, iB, iN, xB = 16, None, None, None, None, None\n return istatus, X, eta, iB, iN, xB\n elif init_status == 16:\n istatus, X, eta, iB, iN, xB = 4, None, None, None, None, None\n return istatus, X, eta, iB, iN, xB\n else:\n istatus_step = 1000\n while istatus_step != -1:\n istatus_step, iB, iN, xB, _ = simplex_step(tableau, xB, c, iB, iN, xB, irule=1)\n if istatus_step == 16:\n istatus, X, iB, iN, xB = 32, None, None, None, None\n return istatus, X, eta, iB, iN, xB\n\n istatus = 0\n iB = iB - 1\n X = np.zeros((A.shape[1], 1))\n X[iB] = xB\n eta = np.matmul(c, X)\n iB = iB + 1\n return istatus, X, eta, iB, iN, xB\n\n\nif __name__ == \"__main__\":\n import numpy as np\n import random\n from simplex_method import simplex_method\n from simplex_test import simplex_test\n print(\"===============================\")\n print(\"Test9.py\")\n # first form an invertible matrix\n R = np.matrix([[4, 1, 1],\n [-1, 2, 1],\n [1, 1, -1]], dtype=np.float64)\n\n # form a vector b which is in the span of R\n b = R*np.matrix([[1],\n [2],\n [1]], dtype=np.float64)\n\n B = np.matrix([[1, 1, 1],\n [1, 1, 0],\n [1, 0, 0]], dtype=np.float64)\n A = np.hstack((R, B))\n\n # form a random permutation\n # p = list(range(0, 6))\n # random.shuffle(p)\n # A = A[:, p]\n\n c = np.matrix([[-2, 1, 1, -1, -1, -1]], dtype=np.float64)\n #c = c[:, p]\n\n # test\n irule = 0\n [istatus, X, eta, iB, iN, xB] = simplex_method(A, b, c, irule)\n print(X, eta, iB, iN, xB)\n # return\n\n if (istatus != 0):\n print('istatus is wrong\\n')\n\n [X, eta, isfeasible, isoptimal, zN] = simplex_test(A, b, c, iB, xB)\n\n if (isfeasible != 1):\n print('your solution is not feasible!!!\\n')\n\n if (isoptimal != 1):\n print('your solution is not optimal!!!\\n')\n\n print(\"===============================\")\n print(\"Test10.py\")\n R = np.matrix([[4, 1, 1],\n [1, 2, 1],\n [1, 1, 1]], dtype=np.float64)\n\n # form a vector b which is in the span of R\n b = R*np.matrix([[1],\n [-4],\n [-1]], dtype=np.float64)\n\n B = np.matrix([[1, 1, 1],\n [1, 1, 0],\n [1, 0, 0]], dtype=np.float64)\n\n A = np.hstack((R, B))\n\n c = np.matrix([[-2, 1, 1, -1, -1, -1]], dtype=np.float64)\n\n irule = 1\n [istatus, X, eta, iB, iN, xB] = simplex_method(A, b, c, irule)\n\n if (istatus != 4):\n print('istatus is wrong\\n')\n print(\"===============================\")\n # print(\"Test11.py\")\n # A1 = np.matrix([[-1, 1, 2],\n # [-1, 1, 1],\n # [0, 1, 1]], dtype=np.float64)\n\n # A = np.hstack((np.eye(3), A1))\n\n # b = np.matrix([[1],\n # [2],\n # [3]], dtype=np.float64)\n\n # iB = [1, 2, 3]\n # iN = [4, 5, 6]\n # xB = np.matrix(np.copy(b))\n # c = np.matrix([[0, 0, 0, -1, 2, 1]], dtype=np.float64)\n\n # # form an invertible matrix B and modify the problem\n # B = np.matrix([[4, 1, 0],\n # [1, -2, -1],\n # [1, 2, 4]], dtype=np.float64)\n # A = B*A\n # b = B*b\n\n # # modify c\n # N = A[:, [index_N-1 for index_N in iN]]\n # c1 = np.matrix([[1, 1, 0]], dtype=np.float64)\n # c2 = c[:, (4-1):6]+c1*B.I*N\n # c = np.hstack((c1, c2))\n\n # irule = 0\n # [istatus, X, eta, iB, iN, xB] = simplex_method(A, b, c, irule)\n\n # if (istatus != 32):\n # print('istatus is wrong\\n')\n",
"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Nov 6 21:39:46 2017\r\n\r\n@author: Siqi Miao\r\n\"\"\"\r\n\r\n# test11.py\r\n#\r\n# An infeasible input to simplex method.\r\n#\r\n# indices of iB, iN start with 1\r\n\r\nimport numpy as np\r\nfrom simplex_method import simplex_method\r\n\r\n# start with a tableau form\r\nA1 = np.matrix([[-1, 1, 2],\r\n [-1, 1, 1], \r\n [ 0, 1, 1]],dtype = np.float64) \r\n\r\nA = np.hstack((np.eye(3), A1))\r\n\r\n\r\nb = np.matrix([[1],\r\n [2],\r\n [3]],dtype = np.float64)\r\n \r\n\r\niB = [1,2,3]\r\niN = [4,5,6]\r\nxB = np.matrix(np.copy(b))\r\nc = np.matrix([[0,0,0,-1,2,1]],dtype = np.float64)\r\n\r\n# form an invertible matrix B and modify the problem\r\nB=np.matrix([[4, 1, 0],\r\n [1, -2, -1],\r\n [1, 2, 4]],dtype = np.float64)\r\nA=B*A\r\nb=B*b\r\n\r\n# modify c\r\nN=A[:,[index_N-1 for index_N in iN]]\r\nc1=np.matrix([[1, 1, 0]],dtype = np.float64)\r\nc2=c[:,(4-1):6]+c1*B.I*N\r\nc = np.hstack((c1,c2))\r\n\r\n\r\nirule = 0\r\n[istatus,X,eta,iB,iN,xB] = simplex_method(A,b,c,irule)\r\n\r\n\r\nif (istatus != 32):\r\n print('istatus is wrong\\n')\r\n\r\n"
] |
[
[
"numpy.matrix",
"numpy.hstack",
"numpy.arange",
"numpy.eye",
"numpy.matmul",
"numpy.ones",
"numpy.intersect1d",
"numpy.copy",
"numpy.where",
"numpy.zeros",
"numpy.sum"
],
[
"numpy.matrix",
"numpy.hstack",
"numpy.copy",
"numpy.eye"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
falkamelung/isce2
|
[
"d22bf1048ff0f7a077981ea4fbe8e0e6bc563961"
] |
[
"components/isceobj/Alos2Proc/runDenseOffset.py"
] |
[
"#\n# Author: Cunren Liang\n# Copyright 2015-present, NASA-JPL/Caltech\n#\n\nimport os\nimport logging\nimport numpy as np\n\nimport isceobj\nfrom isceobj.Util.decorators import use_api\n\nlogger = logging.getLogger('isce.alos2insar.runDenseOffset')\n\ndef runDenseOffset(self):\n '''estimate offset fied\n '''\n if not self.doDenseOffset:\n return\n if not ((self._insar.modeCombination == 0) or (self._insar.modeCombination == 1)):\n return\n\n catalog = isceobj.Catalog.createCatalog(self._insar.procDoc.name)\n self.updateParamemetersFromUser()\n\n denseOffsetDir = 'dense_offset'\n os.makedirs(denseOffsetDir, exist_ok=True)\n os.chdir(denseOffsetDir)\n\n #masterTrack = self._insar.loadProduct(self._insar.masterTrackParameter)\n #slaveTrack = self._insar.loadProduct(self._insar.slaveTrackParameter)\n\n#########################################################################################\n\n if self.useGPU and self._insar.hasGPU():\n runDenseOffsetGPU(self)\n #define null value. Lijun said there is actually no such null value in GPU ampcor.\n nullValue = -10000.0\n else:\n runDenseOffsetCPU(self)\n #define null value\n nullValue = -10000.0\n\n #null value set to zero\n img = isceobj.createImage()\n img.load(self._insar.denseOffset+'.xml')\n width = img.width\n length = img.length\n offset=np.memmap(self._insar.denseOffset, dtype='float32', mode='r+', shape=(length*2, width))\n snr=np.memmap(self._insar.denseOffsetSnr, dtype='float32', mode='r+', shape=(length, width))\n offsetband1 = offset[0:length*2:2, :]\n offsetband2 = offset[1:length*2:2, :]\n index = np.nonzero(np.logical_or(offsetband1==nullValue, offsetband2==nullValue))\n offsetband1[index] = 0\n offsetband2[index] = 0\n snr[index] = 0\n del offset, offsetband1, offsetband2, snr\n\n #areas covered by water body set to zero\n if self.maskOffsetWithWbd:\n img = isceobj.createImage()\n img.load('wbd.rdr.xml')\n width0 = img.width\n length0 = img.length\n\n img = isceobj.createImage()\n img.load(self._insar.denseOffset+'.xml')\n width = img.width\n length = img.length\n\n #get water body mask\n wbd0=np.memmap('wbd.rdr', dtype=np.int8, mode='r', shape=(length0, width0))\n wbd0=wbd0[0+self._insar.offsetImageTopoffset:length0:self.offsetSkipHeight, \n 0+self._insar.offsetImageLeftoffset:width0:self.offsetSkipWidth]\n wbd = np.zeros((length+100, width+100), dtype=np.int8)\n wbd[0:wbd0.shape[0], 0:wbd0.shape[1]]=wbd0\n\n #mask offset and snr\n offset=np.memmap(self._insar.denseOffset, dtype='float32', mode='r+', shape=(length*2, width))\n snr=np.memmap(self._insar.denseOffsetSnr, dtype='float32', mode='r+', shape=(length, width))\n (offset[0:length*2:2, :])[np.nonzero(wbd[0:length, 0:width]==-1)]=0\n (offset[1:length*2:2, :])[np.nonzero(wbd[0:length, 0:width]==-1)]=0\n snr[np.nonzero(wbd[0:length, 0:width]==-1)]=0\n\n del wbd0, wbd, offset, snr\n\n\n#########################################################################################\n\n os.chdir('../')\n catalog.printToLog(logger, \"runDenseOffset\")\n self._insar.procDoc.addAllFromCatalog(catalog)\n\n\n#@use_api\ndef runDenseOffsetCPU(self):\n '''\n Estimate dense offset field between a pair of SLCs.\n '''\n from mroipac.ampcor.DenseAmpcor import DenseAmpcor\n from isceobj.Alos2Proc.Alos2ProcPublic import runCmd\n\n ####For this module currently, we need to create an actual file on disk\n for infile in [self._insar.masterSlc, self._insar.slaveSlcCoregistered]:\n if os.path.isfile(infile):\n continue\n cmd = 'gdal_translate -of ENVI {0}.vrt {0}'.format(infile)\n runCmd(cmd)\n\n m = isceobj.createSlcImage()\n m.load(self._insar.masterSlc + '.xml')\n m.setAccessMode('READ')\n\n s = isceobj.createSlcImage()\n s.load(self._insar.slaveSlcCoregistered + '.xml')\n s.setAccessMode('READ')\n\n #objOffset.numberThreads = 1\n print('\\n************* dense offset estimation parameters *************')\n print('master SLC: %s' % (self._insar.masterSlc))\n print('slave SLC: %s' % (self._insar.slaveSlcCoregistered))\n print('dense offset estimation window width: %d' % (self.offsetWindowWidth))\n print('dense offset estimation window hight: %d' % (self.offsetWindowHeight))\n print('dense offset search window width: %d' % (self.offsetSearchWindowWidth))\n print('dense offset search window hight: %d' % (self.offsetSearchWindowHeight))\n print('dense offset skip width: %d' % (self.offsetSkipWidth))\n print('dense offset skip hight: %d' % (self.offsetSkipHeight))\n print('dense offset covariance surface oversample factor: %d' % (self.offsetCovarianceOversamplingFactor))\n print('dense offset covariance surface oversample window size: %d\\n' % (self.offsetCovarianceOversamplingWindowsize))\n\n\n objOffset = DenseAmpcor(name='dense')\n objOffset.configure()\n\n if m.dataType.startswith('C'):\n objOffset.setImageDataType1('complex')\n else:\n objOffset.setImageDataType1('real')\n if s.dataType.startswith('C'):\n objOffset.setImageDataType2('complex')\n else:\n objOffset.setImageDataType2('real')\n\n objOffset.offsetImageName = self._insar.denseOffset\n objOffset.snrImageName = self._insar.denseOffsetSnr\n objOffset.covImageName = self._insar.denseOffsetCov\n\n objOffset.setWindowSizeWidth(self.offsetWindowWidth)\n objOffset.setWindowSizeHeight(self.offsetWindowHeight)\n #NOTE: actual number of resulting correlation pixels: self.offsetSearchWindowWidth*2+1\n objOffset.setSearchWindowSizeWidth(self.offsetSearchWindowWidth)\n objOffset.setSearchWindowSizeHeight(self.offsetSearchWindowHeight)\n objOffset.setSkipSampleAcross(self.offsetSkipWidth)\n objOffset.setSkipSampleDown(self.offsetSkipHeight)\n objOffset.setOversamplingFactor(self.offsetCovarianceOversamplingFactor)\n objOffset.setZoomWindowSize(self.offsetCovarianceOversamplingWindowsize)\n objOffset.setAcrossGrossOffset(0)\n objOffset.setDownGrossOffset(0)\n #these are azimuth scaling factor\n #Matching Scale for Sample/Line Directions (-) = 1.000000551500 1.000002373200\n objOffset.setFirstPRF(1.0)\n objOffset.setSecondPRF(1.0)\n\n objOffset.denseampcor(m, s)\n\n ### Store params for later\n self._insar.offsetImageTopoffset = objOffset.locationDown[0][0]\n self._insar.offsetImageLeftoffset = objOffset.locationAcross[0][0]\n\n #change band order\n width=objOffset.offsetCols\n length=objOffset.offsetLines\n\n offset1 = np.fromfile(self._insar.denseOffset, dtype=np.float32).reshape(length*2, width)\n offset2 = np.zeros((length*2, width), dtype=np.float32)\n offset2[0:length*2:2, :] = offset1[1:length*2:2, :]\n offset2[1:length*2:2, :] = offset1[0:length*2:2, :]\n\n os.remove(self._insar.denseOffset)\n os.remove(self._insar.denseOffset+'.vrt')\n os.remove(self._insar.denseOffset+'.xml')\n\n offset2.astype(np.float32).tofile(self._insar.denseOffset)\n outImg = isceobj.createImage()\n outImg.setDataType('FLOAT')\n outImg.setFilename(self._insar.denseOffset)\n outImg.setBands(2)\n outImg.scheme = 'BIL'\n outImg.setWidth(width)\n outImg.setLength(length)\n outImg.addDescription('two-band pixel offset file. 1st band: range offset, 2nd band: azimuth offset')\n outImg.setAccessMode('read')\n outImg.renderHdr()\n\n return (objOffset.offsetCols, objOffset.offsetLines)\n\n\ndef runDenseOffsetGPU(self):\n '''\n Estimate dense offset field between a pair of SLCs.\n '''\n from contrib.PyCuAmpcor import PyCuAmpcor\n from isceobj.Alos2Proc.Alos2ProcPublic import runCmd\n from isceobj.Alos2Proc.Alos2ProcPublic import create_xml\n\n ############################################################################################\n # #different from minyan's script: cuDenseOffsets.py: deramp method (0: mag, 1: complex)\n # objOffset.derampMethod = 2 #\n # #varying-gross-offset parameters not set\n\n # #not set in minyan's script: cuDenseOffsets.py\n # objOffset.corrSurfaceZoomInWindow\n # objOffset.grossOffsetAcrossStatic = 0\n # objOffset.grossOffsetDownStatic = 0\n ############################################################################################\n\n\n ####For this module currently, we need to create an actual file on disk\n for infile in [self._insar.masterSlc, self._insar.slaveSlcCoregistered]:\n if os.path.isfile(infile):\n continue\n cmd = 'gdal_translate -of ENVI {0}.vrt {0}'.format(infile)\n runCmd(cmd)\n\n m = isceobj.createSlcImage()\n m.load(self._insar.masterSlc + '.xml')\n m.setAccessMode('READ')\n\n s = isceobj.createSlcImage()\n s.load(self._insar.slaveSlcCoregistered + '.xml')\n s.setAccessMode('READ')\n\n print('\\n************* dense offset estimation parameters *************')\n print('master SLC: %s' % (self._insar.masterSlc))\n print('slave SLC: %s' % (self._insar.slaveSlcCoregistered))\n print('dense offset estimation window width: %d' % (self.offsetWindowWidth))\n print('dense offset estimation window hight: %d' % (self.offsetWindowHeight))\n print('dense offset search window width: %d' % (self.offsetSearchWindowWidth))\n print('dense offset search window hight: %d' % (self.offsetSearchWindowHeight))\n print('dense offset skip width: %d' % (self.offsetSkipWidth))\n print('dense offset skip hight: %d' % (self.offsetSkipHeight))\n print('dense offset covariance surface oversample factor: %d' % (self.offsetCovarianceOversamplingFactor))\n print('dense offset covariance surface oversample window size: %d\\n' % (self.offsetCovarianceOversamplingWindowsize))\n\n\n objOffset = PyCuAmpcor.PyCuAmpcor()\n objOffset.algorithm = 0\n objOffset.deviceID = -1\n objOffset.nStreams = 2\n #original ampcor program in roi_pac uses phase gradient to deramp\n objOffset.derampMethod = 2\n objOffset.masterImageName = self._insar.masterSlc\n objOffset.masterImageHeight = m.length\n objOffset.masterImageWidth = m.width\n objOffset.slaveImageName = self._insar.slaveSlcCoregistered\n objOffset.slaveImageHeight = s.length\n objOffset.slaveImageWidth = s.width\n objOffset.offsetImageName = self._insar.denseOffset\n objOffset.snrImageName = self._insar.denseOffsetSnr\n\n objOffset.windowSizeWidth = self.offsetWindowWidth\n objOffset.windowSizeHeight = self.offsetWindowHeight\n #objOffset.halfSearchRangeAcross = int(self.offsetSearchWindowWidth / 2 + 0.5)\n #objOffset.halfSearchRangeDown = int(self.offsetSearchWindowHeight / 2 + 0.5)\n objOffset.halfSearchRangeAcross = self.offsetSearchWindowWidth\n objOffset.halfSearchRangeDown = self.offsetSearchWindowHeight\n objOffset.skipSampleDown = self.offsetSkipHeight\n objOffset.skipSampleAcross = self.offsetSkipWidth\n #Oversampling method for correlation surface(0=fft,1=sinc)\n objOffset.corrSufaceOverSamplingMethod = 0\n objOffset.corrSurfaceOverSamplingFactor = self.offsetCovarianceOversamplingFactor\n objOffset.corrSurfaceZoomInWindow = self.offsetCovarianceOversamplingWindowsize\n objOffset.grossOffsetAcrossStatic = 0\n objOffset.grossOffsetDownStatic = 0\n\n objOffset.masterStartPixelDownStatic = self.offsetWindowHeight//2\n objOffset.masterStartPixelAcrossStatic = self.offsetWindowWidth//2\n\n objOffset.numberWindowDown = (m.length - 2*self.offsetSearchWindowHeight - self.offsetWindowHeight) // self.offsetSkipHeight\n objOffset.numberWindowAcross = (m.width - 2*self.offsetSearchWindowWidth - self.offsetWindowWidth) // self.offsetSkipWidth\n\n # generic control\n objOffset.numberWindowDownInChunk = 8\n objOffset.numberWindowAcrossInChunk = 8\n objOffset.mmapSize = 16\n\n objOffset.setupParams()\n objOffset.setConstantGrossOffset(0, 0)\n objOffset.checkPixelInImageRange()\n objOffset.runAmpcor()\n\n ### Store params for later\n self._insar.offsetImageTopoffset = objOffset.halfSearchRangeDown\n self._insar.offsetImageLeftoffset = objOffset.halfSearchRangeAcross\n\n \n width = objOffset.numberWindowAcross\n length = objOffset.numberWindowDown\n offsetBIP = np.fromfile(objOffset.offsetImageName.decode('utf-8'), dtype=np.float32).reshape(length, width*2)\n offsetBIL = np.zeros((length*2, width), dtype=np.float32)\n offsetBIL[0:length*2:2, :] = offsetBIP[:, 1:width*2:2]\n offsetBIL[1:length*2:2, :] = offsetBIP[:, 0:width*2:2]\n os.remove(objOffset.offsetImageName.decode('utf-8'))\n offsetBIL.astype(np.float32).tofile(objOffset.offsetImageName.decode('utf-8'))\n\n outImg = isceobj.createImage()\n outImg.setDataType('FLOAT')\n outImg.setFilename(objOffset.offsetImageName.decode('utf-8'))\n outImg.setBands(2)\n outImg.scheme = 'BIL'\n outImg.setWidth(objOffset.numberWindowAcross)\n outImg.setLength(objOffset.numberWindowDown)\n outImg.addDescription('two-band pixel offset file. 1st band: range offset, 2nd band: azimuth offset')\n outImg.setAccessMode('read')\n outImg.renderHdr()\n\n snrImg = isceobj.createImage()\n snrImg.setFilename( objOffset.snrImageName.decode('utf8'))\n snrImg.setDataType('FLOAT')\n snrImg.setBands(1)\n snrImg.setWidth(objOffset.numberWindowAcross)\n snrImg.setLength(objOffset.numberWindowDown)\n snrImg.setAccessMode('read')\n snrImg.renderHdr()\n\n return (objOffset.numberWindowAcross, objOffset.numberWindowDown)\n"
] |
[
[
"numpy.fromfile",
"numpy.nonzero",
"numpy.memmap",
"numpy.logical_or",
"numpy.zeros"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
dmpiergiacomo/tensorflow
|
[
"0ecdc6dc2dbc2381c9317f274bd39281294dfc97",
"3457a2b122e50b4d44ceaaed5a663d635e5c22df",
"0ecdc6dc2dbc2381c9317f274bd39281294dfc97",
"0ecdc6dc2dbc2381c9317f274bd39281294dfc97"
] |
[
"tensorflow/python/ops/array_ops.py",
"tensorflow/lite/testing/op_tests/binary_op.py",
"tensorflow/python/keras/datasets/imdb.py",
"tensorflow/python/saved_model/utils_impl.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# Tests for this file live in python/kernel_tests/array_ops_test.py\n\"\"\"Support for manipulating tensors.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numbers\nimport numpy as np\n\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import common_shapes\nfrom tensorflow.python.framework import composite_tensor\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import sparse_tensor\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.framework import tensor_util\n# 'Constant' gets imported in the module 'array_ops'.\nfrom tensorflow.python.framework.constant_op import constant\nfrom tensorflow.python.ops import gen_array_ops\nfrom tensorflow.python.ops import gen_math_ops\n# go/tf-wildcard-import\n# pylint: disable=wildcard-import\nfrom tensorflow.python.ops.gen_array_ops import *\nfrom tensorflow.python.ops.gen_array_ops import reverse_v2 as reverse # pylint: disable=unused-import\nfrom tensorflow.python.types import core\nfrom tensorflow.python.util import deprecation\nfrom tensorflow.python.util import dispatch\nfrom tensorflow.python.util import nest\nfrom tensorflow.python.util import tf_decorator\nfrom tensorflow.python.util.tf_export import tf_export\n# pylint: enable=wildcard-import\n\n# Used for slicing to specify a new 1 size dimension\nnewaxis = None\ntf_export(\"newaxis\").export_constant(__name__, \"newaxis\")\n\n# We override the 'slice' for the \"slice\" op, so we keep Python's\n# existing 'slice' for later use in this module.\n_BaseSlice = slice\n\n\n@tf_export(\"reshape\", v1=[\"reshape\", \"manip.reshape\"])\[email protected]_dispatch_support\ndef reshape(tensor, shape, name=None): # pylint: disable=redefined-outer-name\n r\"\"\"Reshapes a tensor.\n\n Given `tensor`, this operation returns a new `tf.Tensor` that has the same\n values as `tensor` in the same order, except with a new shape given by\n `shape`.\n\n >>> t1 = [[1, 2, 3],\n ... [4, 5, 6]]\n >>> print(tf.shape(t1).numpy())\n [2 3]\n >>> t2 = tf.reshape(t1, [6])\n >>> t2\n <tf.Tensor: shape=(6,), dtype=int32,\n numpy=array([1, 2, 3, 4, 5, 6], dtype=int32)>\n >>> tf.reshape(t2, [3, 2])\n <tf.Tensor: shape=(3, 2), dtype=int32, numpy=\n array([[1, 2],\n [3, 4],\n [5, 6]], dtype=int32)>\n\n The `tf.reshape` does not change the order of or the total number of elements\n in the tensor, and so it can reuse the underlying data buffer. This makes it\n a fast operation independent of how big of a tensor it is operating on.\n\n >>> tf.reshape([1, 2, 3], [2, 2])\n Traceback (most recent call last):\n ...\n InvalidArgumentError: Input to reshape is a tensor with 3 values, but the\n requested shape has 4\n\n To instead reorder the data to rearrange the dimensions of a tensor, see\n `tf.transpose`.\n\n >>> t = [[1, 2, 3],\n ... [4, 5, 6]]\n >>> tf.reshape(t, [3, 2]).numpy()\n array([[1, 2],\n [3, 4],\n [5, 6]], dtype=int32)\n >>> tf.transpose(t, perm=[1, 0]).numpy()\n array([[1, 4],\n [2, 5],\n [3, 6]], dtype=int32)\n\n If one component of `shape` is the special value -1, the size of that\n dimension is computed so that the total size remains constant. In particular,\n a `shape` of `[-1]` flattens into 1-D. At most one component of `shape` can\n be -1.\n\n >>> t = [[1, 2, 3],\n ... [4, 5, 6]]\n >>> tf.reshape(t, [-1])\n <tf.Tensor: shape=(6,), dtype=int32,\n numpy=array([1, 2, 3, 4, 5, 6], dtype=int32)>\n >>> tf.reshape(t, [3, -1])\n <tf.Tensor: shape=(3, 2), dtype=int32, numpy=\n array([[1, 2],\n [3, 4],\n [5, 6]], dtype=int32)>\n >>> tf.reshape(t, [-1, 2])\n <tf.Tensor: shape=(3, 2), dtype=int32, numpy=\n array([[1, 2],\n [3, 4],\n [5, 6]], dtype=int32)>\n\n `tf.reshape(t, [])` reshapes a tensor `t` with one element to a scalar.\n\n >>> tf.reshape([7], []).numpy()\n 7\n\n More examples:\n\n >>> t = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n >>> print(tf.shape(t).numpy())\n [9]\n >>> tf.reshape(t, [3, 3])\n <tf.Tensor: shape=(3, 3), dtype=int32, numpy=\n array([[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]], dtype=int32)>\n\n >>> t = [[[1, 1], [2, 2]],\n ... [[3, 3], [4, 4]]]\n >>> print(tf.shape(t).numpy())\n [2 2 2]\n >>> tf.reshape(t, [2, 4])\n <tf.Tensor: shape=(2, 4), dtype=int32, numpy=\n array([[1, 1, 2, 2],\n [3, 3, 4, 4]], dtype=int32)>\n\n >>> t = [[[1, 1, 1],\n ... [2, 2, 2]],\n ... [[3, 3, 3],\n ... [4, 4, 4]],\n ... [[5, 5, 5],\n ... [6, 6, 6]]]\n >>> print(tf.shape(t).numpy())\n [3 2 3]\n >>> # Pass '[-1]' to flatten 't'.\n >>> tf.reshape(t, [-1])\n <tf.Tensor: shape=(18,), dtype=int32,\n numpy=array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6],\n dtype=int32)>\n >>> # -- Using -1 to infer the shape --\n >>> # Here -1 is inferred to be 9:\n >>> tf.reshape(t, [2, -1])\n <tf.Tensor: shape=(2, 9), dtype=int32, numpy=\n array([[1, 1, 1, 2, 2, 2, 3, 3, 3],\n [4, 4, 4, 5, 5, 5, 6, 6, 6]], dtype=int32)>\n >>> # -1 is inferred to be 2:\n >>> tf.reshape(t, [-1, 9])\n <tf.Tensor: shape=(2, 9), dtype=int32, numpy=\n array([[1, 1, 1, 2, 2, 2, 3, 3, 3],\n [4, 4, 4, 5, 5, 5, 6, 6, 6]], dtype=int32)>\n >>> # -1 is inferred to be 3:\n >>> tf.reshape(t, [ 2, -1, 3])\n <tf.Tensor: shape=(2, 3, 3), dtype=int32, numpy=\n array([[[1, 1, 1],\n [2, 2, 2],\n [3, 3, 3]],\n [[4, 4, 4],\n [5, 5, 5],\n [6, 6, 6]]], dtype=int32)>\n\n Args:\n tensor: A `Tensor`.\n shape: A `Tensor`. Must be one of the following types: `int32`, `int64`.\n Defines the shape of the output tensor.\n name: Optional string. A name for the operation.\n\n Returns:\n A `Tensor`. Has the same type as `tensor`.\n \"\"\"\n result = gen_array_ops.reshape(tensor, shape, name)\n tensor_util.maybe_set_static_shape(result, shape)\n return result\n\n\n@tf_export(\"fill\")\[email protected]_dispatch_support\ndef fill(dims, value, name=None):\n r\"\"\"Creates a tensor filled with a scalar value.\n\n See also `tf.ones`, `tf.zeros`, `tf.one_hot`, `tf.eye`.\n\n This operation creates a tensor of shape `dims` and fills it with `value`.\n\n For example:\n\n >>> tf.fill([2, 3], 9)\n <tf.Tensor: shape=(2, 3), dtype=int32, numpy=\n array([[9, 9, 9],\n [9, 9, 9]], dtype=int32)>\n\n `tf.fill` evaluates at graph runtime and supports dynamic shapes based on\n other runtime `tf.Tensors`, unlike `tf.constant(value, shape=dims)`, which\n embeds the value as a `Const` node.\n\n Args:\n dims: A 1-D sequence of non-negative numbers. Represents the shape of the\n output `tf.Tensor`. Entries should be of type: `int32`, `int64`.\n value: A value to fill the returned `tf.Tensor`.\n name: Optional string. The name of the output `tf.Tensor`.\n\n Returns:\n A `tf.Tensor` with shape `dims` and the same dtype as `value`.\n\n Raises:\n InvalidArgumentError: `dims` contains negative entries.\n NotFoundError: `dims` contains non-integer entries.\n\n @compatibility(numpy)\n Similar to `np.full`. In `numpy`, more parameters are supported. Passing a\n number argument as the shape (`np.full(5, value)`) is valid in `numpy` for\n specifying a 1-D shaped result, while TensorFlow does not support this syntax.\n @end_compatibility\n \"\"\"\n result = gen_array_ops.fill(dims, value, name=name)\n tensor_util.maybe_set_static_shape(result, dims)\n return result\n\n\n@tf_export(\"identity\")\[email protected]_dispatch_support\ndef identity(input, name=None): # pylint: disable=redefined-builtin\n r\"\"\"Return a Tensor with the same shape and contents as input.\n\n The return value is not the same Tensor as the original, but contains the same\n values. This operation is fast when used on the same device.\n\n For example:\n\n >>> a = tf.constant([0.78])\n >>> a_identity = tf.identity(a)\n >>> a.numpy()\n array([0.78], dtype=float32)\n >>> a_identity.numpy()\n array([0.78], dtype=float32)\n\n Calling `tf.identity` on a variable will make a Tensor that represents the\n value of that variable at the time it is called. This is equivalent to calling\n `<variable>.read_value()`.\n\n >>> a = tf.Variable(5)\n >>> a_identity = tf.identity(a)\n >>> a.assign_add(1)\n <tf.Variable ... shape=() dtype=int32, numpy=6>\n >>> a.numpy()\n 6\n >>> a_identity.numpy()\n 5\n\n Args:\n input: A `Tensor`, a `Variable`, a `CompositeTensor` or anything that can be\n converted to a tensor using `tf.convert_to_tensor`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` or CompositeTensor. Has the same type and contents as `input`.\n \"\"\"\n if isinstance(input, composite_tensor.CompositeTensor):\n return nest.map_structure(identity, input, expand_composites=True)\n if context.executing_eagerly() and not hasattr(input, \"graph\"):\n # Make sure we get an input with handle data attached from resource\n # variables. Variables have correct handle data when graph building.\n input = ops.convert_to_tensor(input)\n ret = gen_array_ops.identity(input, name=name)\n # Propagate handle data for happier shape inference for resource variables.\n if hasattr(input, \"_handle_data\"):\n ret._handle_data = input._handle_data # pylint: disable=protected-access\n return ret\n\n\n# pylint: disable=redefined-builtin,protected-access\n@tf_export(v1=[\"expand_dims\"])\[email protected]_dispatch_support\[email protected]_args(None, \"Use the `axis` argument instead\", \"dim\")\ndef expand_dims(input, axis=None, name=None, dim=None):\n \"\"\"Returns a tensor with a length 1 axis inserted at index `axis`.\n\n Given a tensor `input`, this operation inserts a dimension of length 1 at the\n dimension index `axis` of `input`'s shape. The dimension index follows Python\n indexing rules: It's zero-based, a negative index it is counted backward\n from the end.\n\n This operation is useful to:\n\n * Add an outer \"batch\" dimension to a single element.\n * Align axes for broadcasting.\n * To add an inner vector length axis to a tensor of scalars.\n\n For example:\n\n If you have a single image of shape `[height, width, channels]`:\n\n >>> image = tf.zeros([10,10,3])\n\n You can add an outer `batch` axis by passing `axis=0`:\n\n >>> tf.expand_dims(image, axis=0).shape.as_list()\n [1, 10, 10, 3]\n\n The new axis location matches Python `list.insert(axis, 1)`:\n\n >>> tf.expand_dims(image, axis=1).shape.as_list()\n [10, 1, 10, 3]\n\n Following standard Python indexing rules, a negative `axis` counts from the\n end so `axis=-1` adds an inner most dimension:\n\n >>> tf.expand_dims(image, -1).shape.as_list()\n [10, 10, 3, 1]\n\n This operation requires that `axis` is a valid index for `input.shape`,\n following Python indexing rules:\n\n ```\n -1-tf.rank(input) <= axis <= tf.rank(input)\n ```\n\n This operation is related to:\n\n * `tf.squeeze`, which removes dimensions of size 1.\n * `tf.reshape`, which provides more flexible reshaping capability.\n * `tf.sparse.expand_dims`, which provides this functionality for\n `tf.SparseTensor`\n\n Args:\n input: A `Tensor`.\n axis: 0-D (scalar). Specifies the dimension index at which to expand the\n shape of `input`. Must be in the range `[-rank(input) - 1, rank(input)]`.\n name: The name of the output `Tensor` (optional).\n dim: 0-D (scalar). Equivalent to `axis`, to be deprecated.\n\n Returns:\n A `Tensor` with the same data as `input`, but its shape has an additional\n dimension of size 1 added.\n\n Raises:\n ValueError: if either both or neither of `dim` and `axis` are specified.\n \"\"\"\n axis = deprecation.deprecated_argument_lookup(\"axis\", axis, \"dim\", dim)\n if axis is None:\n raise ValueError(\"Must specify an axis argument to tf.expand_dims()\")\n return expand_dims_v2(input, axis, name)\n\n\n@tf_export(\"expand_dims\", v1=[])\[email protected]_dispatch_support\ndef expand_dims_v2(input, axis, name=None):\n \"\"\"Returns a tensor with a length 1 axis inserted at index `axis`.\n\n Given a tensor `input`, this operation inserts a dimension of length 1 at the\n dimension index `axis` of `input`'s shape. The dimension index follows Python\n indexing rules: It's zero-based, a negative index it is counted backward\n from the end.\n\n This operation is useful to:\n\n * Add an outer \"batch\" dimension to a single element.\n * Align axes for broadcasting.\n * To add an inner vector length axis to a tensor of scalars.\n\n For example:\n\n If you have a single image of shape `[height, width, channels]`:\n\n >>> image = tf.zeros([10,10,3])\n\n You can add an outer `batch` axis by passing `axis=0`:\n\n >>> tf.expand_dims(image, axis=0).shape.as_list()\n [1, 10, 10, 3]\n\n The new axis location matches Python `list.insert(axis, 1)`:\n\n >>> tf.expand_dims(image, axis=1).shape.as_list()\n [10, 1, 10, 3]\n\n Following standard Python indexing rules, a negative `axis` counts from the\n end so `axis=-1` adds an inner most dimension:\n\n >>> tf.expand_dims(image, -1).shape.as_list()\n [10, 10, 3, 1]\n\n This operation requires that `axis` is a valid index for `input.shape`,\n following Python indexing rules:\n\n ```\n -1-tf.rank(input) <= axis <= tf.rank(input)\n ```\n\n This operation is related to:\n\n * `tf.squeeze`, which removes dimensions of size 1.\n * `tf.reshape`, which provides more flexible reshaping capability.\n * `tf.sparse.expand_dims`, which provides this functionality for\n `tf.SparseTensor`\n\n Args:\n input: A `Tensor`.\n axis: Integer specifying the dimension index at which to expand the\n shape of `input`. Given an input of D dimensions, `axis` must be in range\n `[-(D+1), D]` (inclusive).\n name: Optional string. The name of the output `Tensor`.\n\n Returns:\n A tensor with the same data as `input`, with an additional dimension\n inserted at the index specified by `axis`.\n\n Raises:\n ValueError: If `axis` is not specified.\n InvalidArgumentError: If `axis` is out of range `[-(D+1), D]`.\n \"\"\"\n return gen_array_ops.expand_dims(input, axis, name)\n\n\n# pylint: enable=redefined-builtin,protected-access\n\n\n# Aliases for some automatically-generated names.\n# pylint: disable=protected-access\[email protected](\"2016-11-30\",\n \"This op will be removed after the deprecation date. \"\n \"Please switch to tf.setdiff1d().\")\ndef listdiff(x, y, out_idx=None, name=None):\n return gen_array_ops.list_diff(x, y, out_idx, name)\n\n\nlistdiff.__doc__ = gen_array_ops.list_diff.__doc__ + \"\\n\" + listdiff.__doc__\n\n# pylint: enable=protected-access\n\n\n# pylint: disable=undefined-variable\[email protected](\"2018-11-30\",\n \"This op will be removed after the deprecation date. \"\n \"Please switch to tf.sets.difference().\")\n@tf_export(v1=[\"setdiff1d\"])\[email protected]_dispatch_support\ndef setdiff1d(x, y, index_dtype=dtypes.int32, name=None):\n \"\"\"Computes the difference between two lists of numbers or strings.\n\n Given a list x and a list y, this operation returns a list out that\n represents all values that are in x but not in y. The returned list\n out is sorted in the same order that the numbers appear in x\n (duplicates are preserved). This operation also returns a list idx\n that represents the position of each out element in x.\n\n In other words:\n\n ```python\n out[i] = x[idx[i]] for i in [0, 1, ..., len(out) - 1]\n ```\n\n Example usage:\n\n >>> x = [1, 2, 3, 4, 5, 6]\n >>> y = [1, 3, 5]\n >>> setdiff1d(x,y)\n ListDiff(out=<tf.Tensor: id=2, shape=(3,), dtype=int32,\n numpy=array([2, 4, 6], dtype=int32)>, idx=<tf.Tensor: id=3,\n shape=(3,), dtype=int32, numpy=array([1, 3, 5], dtype=int32)>)\n\n Args:\n x: A Tensor. 1-D. Values to keep.\n y: A Tensor. Must have the same type as x. 1-D. Values to remove.\n out_idx: An optional tf.DType from: tf.int32, tf.int64. Defaults to\n tf.int32.\n name: A name for the operation (optional).\n\n Returns:\n A tuple of Tensor objects (out, idx).\n out: A Tensor. Has the same type as x.\n idx: A Tensor of type out_idx.\n \"\"\"\n return gen_array_ops.list_diff(x, y, index_dtype, name)\n\n\nsetdiff1d.__doc__ = gen_array_ops.list_diff.__doc__\n\n\n@tf_export(\"broadcast_dynamic_shape\")\[email protected]_dispatch_support\ndef broadcast_dynamic_shape(shape_x, shape_y):\n \"\"\"Computes the shape of a broadcast given symbolic shapes.\n\n When `shape_x` and `shape_y` are Tensors representing shapes (i.e. the result\n of calling tf.shape on another Tensor) this computes a Tensor which is the\n shape of the result of a broadcasting op applied in tensors of shapes\n `shape_x` and `shape_y`.\n\n This is useful when validating the result of a broadcasting operation when the\n tensors do not have statically known shapes.\n\n Example:\n\n >>> shape_x = (1, 2, 3)\n >>> shape_y = (5, 1, 3)\n >>> tf.broadcast_dynamic_shape(shape_x, shape_y)\n <tf.Tensor: shape=(3,), dtype=int32, numpy=array([5, 2, 3], ...>\n\n Args:\n shape_x: A rank 1 integer `Tensor`, representing the shape of x.\n shape_y: A rank 1 integer `Tensor`, representing the shape of y.\n\n Returns:\n A rank 1 integer `Tensor` representing the broadcasted shape.\n\n Raises:\n InvalidArgumentError: If the two shapes are incompatible for\n broadcasting.\n \"\"\"\n return gen_array_ops.broadcast_args(shape_x, shape_y)\n\n\n@tf_export(\"broadcast_static_shape\")\[email protected]_dispatch_support\ndef broadcast_static_shape(shape_x, shape_y):\n \"\"\"Computes the shape of a broadcast given known shapes.\n\n When `shape_x` and `shape_y` are fully known `TensorShape`s this computes a\n `TensorShape` which is the shape of the result of a broadcasting op applied in\n tensors of shapes `shape_x` and `shape_y`.\n\n For example, if shape_x is `TensorShape([1, 2, 3])` and shape_y is\n `TensorShape([5, 1, 3])`, the result is a TensorShape whose value is\n `TensorShape([5, 2, 3])`.\n\n This is useful when validating the result of a broadcasting operation when the\n tensors have statically known shapes.\n\n Example:\n\n >>> shape_x = tf.TensorShape([1, 2, 3])\n >>> shape_y = tf.TensorShape([5, 1 ,3])\n >>> tf.broadcast_static_shape(shape_x, shape_y)\n TensorShape([5, 2, 3])\n\n Args:\n shape_x: A `TensorShape`\n shape_y: A `TensorShape`\n\n Returns:\n A `TensorShape` representing the broadcasted shape.\n\n Raises:\n ValueError: If the two shapes can not be broadcasted.\n \"\"\"\n return common_shapes.broadcast_shape(shape_x, shape_y)\n\n\n@tf_export(\"shape\", v1=[])\[email protected]_dispatch_support\ndef shape_v2(input, out_type=dtypes.int32, name=None):\n # pylint: disable=redefined-builtin\n \"\"\"Returns a tensor containing the shape of the input tensor.\n\n See also `tf.size`, `tf.rank`.\n\n `tf.shape` returns a 1-D integer tensor representing the shape of `input`.\n For a scalar input, the tensor returned has a shape of (0,) and its value is\n the empty vector (i.e. []).\n\n For example:\n\n >>> tf.shape(1.)\n <tf.Tensor: shape=(0,), dtype=int32, numpy=array([], dtype=int32)>\n\n >>> t = tf.constant([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]])\n >>> tf.shape(t)\n <tf.Tensor: shape=(3,), dtype=int32, numpy=array([2, 2, 3], dtype=int32)>\n\n Note: When using symbolic tensors, such as when using the Keras API,\n tf.shape() will return the shape of the symbolic tensor.\n\n >>> a = tf.keras.layers.Input((None, 10))\n >>> tf.shape(a)\n <... shape=(3,) dtype=int32...>\n\n In these cases, using `tf.Tensor.shape` will return more informative results.\n\n >>> a.shape\n TensorShape([None, None, 10])\n\n (The first `None` represents the as yet unknown batch size.)\n\n `tf.shape` and `Tensor.shape` should be identical in eager mode. Within\n `tf.function` or within a `compat.v1` context, not all dimensions may be\n known until execution time. Hence when defining custom layers and models\n for graph mode, prefer the dynamic `tf.shape(x)` over the static `x.shape`.\n\n Args:\n input: A `Tensor` or `SparseTensor`.\n out_type: (Optional) The specified output type of the operation (`int32` or\n `int64`). Defaults to `tf.int32`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `out_type`.\n \"\"\"\n return shape(input, name, out_type)\n\n\n@tf_export(v1=[\"shape\"])\[email protected]_dispatch_support\ndef shape(input, name=None, out_type=dtypes.int32):\n # pylint: disable=redefined-builtin\n \"\"\"Returns the shape of a tensor.\n\n This operation returns a 1-D integer tensor representing the shape of `input`.\n\n For example:\n\n ```python\n t = tf.constant([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]])\n tf.shape(t) # [2, 2, 3]\n ```\n\n Args:\n input: A `Tensor` or `SparseTensor`.\n name: A name for the operation (optional).\n out_type: (Optional) The specified output type of the operation (`int32`\n or `int64`). Defaults to `tf.int32`.\n\n Returns:\n A `Tensor` of type `out_type`.\n \"\"\"\n return shape_internal(input, name, optimize=True, out_type=out_type)\n\n\ndef shape_internal(input, name=None, optimize=True, out_type=dtypes.int32):\n # pylint: disable=redefined-builtin\n \"\"\"Returns the shape of a tensor.\n\n Args:\n input: A `Tensor` or `SparseTensor`.\n name: A name for the operation (optional).\n optimize: if true, encode the shape as a constant when possible.\n out_type: (Optional) The specified output type of the operation (`int32` or\n `int64`). Defaults to tf.int32.\n\n Returns:\n A `Tensor` of type `out_type`.\n\n \"\"\"\n with ops.name_scope(name, \"Shape\", [input]) as name:\n if isinstance(\n input, (sparse_tensor.SparseTensor, sparse_tensor.SparseTensorValue)):\n return gen_math_ops.cast(input.dense_shape, out_type)\n else:\n if not context.executing_eagerly():\n input = ops.convert_to_tensor(input)\n input_shape = input.get_shape()\n if optimize and input_shape.is_fully_defined():\n return constant(input_shape.as_list(), out_type, name=name)\n return gen_array_ops.shape(input, name=name, out_type=out_type)\n\n\n@tf_export(\"shape_n\")\[email protected]_dispatch_support\ndef shape_n(input, out_type=dtypes.int32, name=None):\n # pylint: disable=redefined-builtin\n \"\"\"Returns shape of tensors.\n\n Args:\n input: A list of at least 1 `Tensor` object with the same type.\n out_type: The specified output type of the operation (`int32` or `int64`).\n Defaults to `tf.int32`(optional).\n name: A name for the operation (optional).\n\n Returns:\n A list with the same length as `input` of `Tensor` objects with\n type `out_type`.\n \"\"\"\n\n return gen_array_ops.shape_n(input, out_type=out_type, name=name)\n\n\n@tf_export(\"size\", v1=[])\[email protected]_dispatch_support\ndef size_v2(input, out_type=dtypes.int32, name=None):\n # pylint: disable=redefined-builtin\n \"\"\"Returns the size of a tensor.\n\n See also `tf.shape`.\n\n Returns a 0-D `Tensor` representing the number of elements in `input`\n of type `out_type`. Defaults to tf.int32.\n\n For example:\n\n >>> t = tf.constant([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]])\n >>> tf.size(t)\n <tf.Tensor: shape=(), dtype=int32, numpy=12>\n\n Args:\n input: A `Tensor` or `SparseTensor`.\n name: A name for the operation (optional).\n out_type: (Optional) The specified non-quantized numeric output type of the\n operation. Defaults to `tf.int32`.\n\n Returns:\n A `Tensor` of type `out_type`. Defaults to `tf.int32`.\n\n @compatibility(numpy)\n Equivalent to np.size()\n @end_compatibility\n \"\"\"\n\n return size(input, name, out_type)\n\n\n@tf_export(v1=[\"size\"])\[email protected]_dispatch_support\ndef size(input, name=None, out_type=dtypes.int32):\n # pylint: disable=redefined-builtin\n \"\"\"Returns the size of a tensor.\n\n Returns a 0-D `Tensor` representing the number of elements in `input`\n of type `out_type`. Defaults to tf.int32.\n\n For example:\n\n ```python\n t = tf.constant([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]])\n tf.size(t) # 12\n ```\n\n Args:\n input: A `Tensor` or `SparseTensor`.\n name: A name for the operation (optional).\n out_type: (Optional) The specified non-quantized numeric output type of the\n operation. Defaults to `tf.int32`.\n\n Returns:\n A `Tensor` of type `out_type`. Defaults to `tf.int32`.\n\n @compatibility(numpy)\n Equivalent to np.size()\n @end_compatibility\n \"\"\"\n return size_internal(input, name, optimize=True, out_type=out_type)\n\n\ndef size_internal(input, name=None, optimize=True, out_type=dtypes.int32):\n # pylint: disable=redefined-builtin,protected-access\n \"\"\"Returns the size of a tensor.\n\n Args:\n input: A `Tensor` or `SparseTensor`.\n name: A name for the operation (optional).\n optimize: if true, encode the size as a constant when possible.\n out_type: (Optional) The specified non-quantized numeric output type of the\n operation. Defaults to `tf.int32`.\n\n Returns:\n A `Tensor` of type `out_type`. Defaults to `tf.int32`.\n \"\"\"\n if (context.executing_eagerly() and not hasattr(input, \"graph\") and\n not isinstance(\n input,\n (sparse_tensor.SparseTensor, sparse_tensor.SparseTensorValue))):\n input = ops.convert_to_tensor(input)\n np_out_type = out_type.as_numpy_dtype\n num_elements = np.prod(input._shape_tuple(), dtype=np_out_type) # pylint: disable=protected-access\n return ops.convert_to_tensor(num_elements, dtype=out_type)\n with ops.name_scope(name, \"Size\", [input]) as name:\n if isinstance(\n input, (sparse_tensor.SparseTensor, sparse_tensor.SparseTensorValue)):\n return gen_math_ops.prod(\n gen_math_ops.cast(input.dense_shape, out_type), 0, name=name)\n else:\n input = ops.convert_to_tensor(input)\n input_shape = input.get_shape()\n if optimize:\n if input_shape.is_fully_defined():\n return constant(input_shape.num_elements(), out_type, name=name)\n if input_shape.dims and any(dim == 0 for dim in input_shape.dims):\n return constant(0, out_type, name=name)\n return gen_array_ops.size(input, name=name, out_type=out_type)\n\n\n@tf_export(\"rank\")\[email protected]_dispatch_support\ndef rank(input, name=None):\n # pylint: disable=redefined-builtin\n \"\"\"Returns the rank of a tensor.\n\n See also `tf.shape`.\n\n Returns a 0-D `int32` `Tensor` representing the rank of `input`.\n\n For example:\n\n ```python\n # shape of tensor 't' is [2, 2, 3]\n t = tf.constant([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]])\n tf.rank(t) # 3\n ```\n\n **Note**: The rank of a tensor is not the same as the rank of a matrix. The\n rank of a tensor is the number of indices required to uniquely select each\n element of the tensor. Rank is also known as \"order\", \"degree\", or \"ndims.\"\n\n Args:\n input: A `Tensor` or `SparseTensor`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` of type `int32`.\n\n @compatibility(numpy)\n Equivalent to np.ndim\n @end_compatibility\n \"\"\"\n return rank_internal(input, name, optimize=True)\n\n\ndef rank_internal(input, name=None, optimize=True):\n # pylint: disable=redefined-builtin\n \"\"\"Returns the rank of a tensor.\n\n Args:\n input: A `Tensor` or `SparseTensor`.\n name: A name for the operation (optional).\n optimize: if true, encode the rank as a constant when possible.\n\n Returns:\n A `Tensor` of type `int32`.\n \"\"\"\n with ops.name_scope(name, \"Rank\", [input]) as name:\n if isinstance(\n input, (sparse_tensor.SparseTensor, sparse_tensor.SparseTensorValue)):\n return gen_array_ops.size(input.dense_shape, name=name)\n else:\n input = ops.convert_to_tensor(input)\n input_shape = input.get_shape()\n if optimize and input_shape.ndims is not None:\n return constant(input_shape.ndims, dtypes.int32, name=name)\n return gen_array_ops.rank(input, name=name)\n\n\n_SLICE_TYPE_ERROR = (\n \"Only integers, slices (`:`), ellipsis (`...`), \"\n \"tf.newaxis (`None`) and scalar tf.int32/tf.int64 tensors are valid \"\n \"indices\")\n\n_SUPPORTED_SLICE_DTYPES = (dtypes.int32, dtypes.int32_ref, dtypes.int64,\n dtypes.int64_ref)\n\n\ndef _check_index(idx):\n \"\"\"Check if a given value is a valid index into a tensor.\"\"\"\n if isinstance(idx, (numbers.Integral, tensor_shape.Dimension)):\n return\n\n # Optimistic check. Assumptions:\n # * any object with a dtype is supported\n # * any object with a dtype has a sizeable shape attribute.\n dtype = getattr(idx, \"dtype\", None)\n if (dtype is None or dtypes.as_dtype(dtype) not in _SUPPORTED_SLICE_DTYPES or\n idx.shape and len(idx.shape) == 1):\n # TODO(slebedev): IndexError seems more appropriate here, but it\n # will break `_slice_helper` contract.\n raise TypeError(_SLICE_TYPE_ERROR + \", got {!r}\".format(idx))\n\n\ndef _is_undefined_dimension(d):\n return isinstance(d, tensor_shape.Dimension) and d.value is None\n\n\n@tf_export(\"__operators__.getitem\", v1=[])\[email protected]_dispatch_support\ndef _slice_helper(tensor, slice_spec, var=None):\n \"\"\"Overload for Tensor.__getitem__.\n\n This operation extracts the specified region from the tensor.\n The notation is similar to NumPy with the restriction that\n currently only support basic indexing. That means that\n using a non-scalar tensor as input is not currently allowed.\n\n Some useful examples:\n\n ```python\n # Strip leading and trailing 2 elements\n foo = tf.constant([1,2,3,4,5,6])\n print(foo[2:-2].eval()) # => [3,4]\n\n # Skip every other row and reverse the order of the columns\n foo = tf.constant([[1,2,3], [4,5,6], [7,8,9]])\n print(foo[::2,::-1].eval()) # => [[3,2,1], [9,8,7]]\n\n # Use scalar tensors as indices on both dimensions\n print(foo[tf.constant(0), tf.constant(2)].eval()) # => 3\n\n # Insert another dimension\n foo = tf.constant([[1,2,3], [4,5,6], [7,8,9]])\n print(foo[tf.newaxis, :, :].eval()) # => [[[1,2,3], [4,5,6], [7,8,9]]]\n print(foo[:, tf.newaxis, :].eval()) # => [[[1,2,3]], [[4,5,6]], [[7,8,9]]]\n print(foo[:, :, tf.newaxis].eval()) # => [[[1],[2],[3]], [[4],[5],[6]],\n [[7],[8],[9]]]\n\n # Ellipses (3 equivalent operations)\n foo = tf.constant([[1,2,3], [4,5,6], [7,8,9]])\n print(foo[tf.newaxis, :, :].eval()) # => [[[1,2,3], [4,5,6], [7,8,9]]]\n print(foo[tf.newaxis, ...].eval()) # => [[[1,2,3], [4,5,6], [7,8,9]]]\n print(foo[tf.newaxis].eval()) # => [[[1,2,3], [4,5,6], [7,8,9]]]\n\n # Masks\n foo = tf.constant([[1,2,3], [4,5,6], [7,8,9]])\n print(foo[foo > 2].eval()) # => [3, 4, 5, 6, 7, 8, 9]\n ```\n\n Notes:\n - `tf.newaxis` is `None` as in NumPy.\n - An implicit ellipsis is placed at the end of the `slice_spec`\n - NumPy advanced indexing is currently not supported.\n\n Purpose in the API:\n\n This method is exposed in TensorFlow's API so that library developers\n can register dispatching for `Tensor.__getitem__` to allow it to handle\n custom composite tensors & other custom objects.\n\n The API symbol is not intended to be called by users directly and does\n appear in TensorFlow's generated documentation.\n\n Args:\n tensor: An ops.Tensor object.\n slice_spec: The arguments to Tensor.__getitem__.\n var: In the case of variable slice assignment, the Variable object to slice\n (i.e. tensor is the read-only view of this variable).\n\n Returns:\n The appropriate slice of \"tensor\", based on \"slice_spec\".\n\n Raises:\n ValueError: If a slice range is negative size.\n TypeError: If the slice indices aren't int, slice, ellipsis,\n tf.newaxis or scalar int32/int64 tensors.\n \"\"\"\n tensor = ops.convert_to_tensor(tensor)\n # TODO(wangpeng): Consider supporting var\n if var is None and ops._numpy_style_slicing: # pylint: disable=protected-access\n return tensor._numpy_style_getitem(slice_spec) # pylint: disable=protected-access\n\n if isinstance(slice_spec, bool) or \\\n (isinstance(slice_spec, ops.Tensor) and slice_spec.dtype == dtypes.bool) or \\\n (isinstance(slice_spec, np.ndarray) and slice_spec.dtype == bool):\n return boolean_mask(tensor=tensor, mask=slice_spec)\n\n if not isinstance(slice_spec, (list, tuple)):\n slice_spec = [slice_spec]\n\n begin, end, strides = [], [], []\n index = 0\n\n new_axis_mask, shrink_axis_mask = 0, 0\n begin_mask, end_mask = 0, 0\n ellipsis_mask = 0\n for s in slice_spec:\n if isinstance(s, _BaseSlice):\n if s.start is not None and not _is_undefined_dimension(s.start):\n _check_index(s.start)\n begin.append(s.start)\n else:\n begin.append(0)\n begin_mask |= (1 << index)\n if s.stop is not None and not _is_undefined_dimension(s.stop):\n _check_index(s.stop)\n end.append(s.stop)\n else:\n end.append(0)\n end_mask |= (1 << index)\n if s.step is not None and not _is_undefined_dimension(s.step):\n _check_index(s.step)\n strides.append(s.step)\n else:\n strides.append(1)\n elif s is Ellipsis:\n begin.append(0)\n end.append(0)\n strides.append(1)\n ellipsis_mask |= (1 << index)\n elif s is newaxis:\n begin.append(0)\n end.append(0)\n strides.append(1)\n new_axis_mask |= (1 << index)\n else:\n _check_index(s)\n begin.append(s)\n end.append(s + 1)\n strides.append(1)\n shrink_axis_mask |= (1 << index)\n index += 1\n\n # stack possibly involves no tensors, so we must use op_scope correct graph.\n with ops.name_scope(\n None,\n \"strided_slice\", [tensor] + begin + end + strides,\n skip_on_eager=False) as name:\n if begin:\n packed_begin, packed_end, packed_strides = (stack(begin), stack(end),\n stack(strides))\n if (packed_begin.dtype == dtypes.int64 or\n packed_end.dtype == dtypes.int64 or\n packed_strides.dtype == dtypes.int64):\n if packed_begin.dtype != dtypes.int64:\n packed_begin = gen_math_ops.cast(packed_begin, dtypes.int64)\n if packed_end.dtype != dtypes.int64:\n packed_end = gen_math_ops.cast(packed_end, dtypes.int64)\n if packed_strides.dtype != dtypes.int64:\n packed_strides = gen_math_ops.cast(packed_strides, dtypes.int64)\n else:\n var_empty = constant([], dtype=dtypes.int32)\n packed_begin = packed_end = packed_strides = var_empty\n return strided_slice(\n tensor,\n packed_begin,\n packed_end,\n packed_strides,\n begin_mask=begin_mask,\n end_mask=end_mask,\n shrink_axis_mask=shrink_axis_mask,\n new_axis_mask=new_axis_mask,\n ellipsis_mask=ellipsis_mask,\n var=var,\n name=name)\n\n\n# pylint: disable=undefined-variable,protected-access,redefined-outer-name\n@tf_export(\"slice\")\[email protected]_dispatch_support\ndef slice(input_, begin, size, name=None):\n # pylint: disable=redefined-builtin\n \"\"\"Extracts a slice from a tensor.\n\n See also `tf.strided_slice`.\n\n This operation extracts a slice of size `size` from a tensor `input_` starting\n at the location specified by `begin`. The slice `size` is represented as a\n tensor shape, where `size[i]` is the number of elements of the 'i'th dimension\n of `input_` that you want to slice. The starting location (`begin`) for the\n slice is represented as an offset in each dimension of `input_`. In other\n words, `begin[i]` is the offset into the i'th dimension of `input_` that you\n want to slice from.\n\n Note that `tf.Tensor.__getitem__` is typically a more pythonic way to\n perform slices, as it allows you to write `foo[3:7, :-2]` instead of\n `tf.slice(foo, [3, 0], [4, foo.get_shape()[1]-2])`.\n\n `begin` is zero-based; `size` is one-based. If `size[i]` is -1,\n all remaining elements in dimension i are included in the\n slice. In other words, this is equivalent to setting:\n\n `size[i] = input_.dim_size(i) - begin[i]`\n\n This operation requires that:\n\n `0 <= begin[i] <= begin[i] + size[i] <= Di for i in [0, n]`\n\n For example:\n\n ```python\n t = tf.constant([[[1, 1, 1], [2, 2, 2]],\n [[3, 3, 3], [4, 4, 4]],\n [[5, 5, 5], [6, 6, 6]]])\n tf.slice(t, [1, 0, 0], [1, 1, 3]) # [[[3, 3, 3]]]\n tf.slice(t, [1, 0, 0], [1, 2, 3]) # [[[3, 3, 3],\n # [4, 4, 4]]]\n tf.slice(t, [1, 0, 0], [2, 1, 3]) # [[[3, 3, 3]],\n # [[5, 5, 5]]]\n ```\n\n Args:\n input_: A `Tensor`.\n begin: An `int32` or `int64` `Tensor`.\n size: An `int32` or `int64` `Tensor`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` the same type as `input_`.\n \"\"\"\n return gen_array_ops._slice(input_, begin, size, name=name)\n\n\n# pylint: disable=invalid-name\n@tf_export(\"strided_slice\")\[email protected]_dispatch_support\ndef strided_slice(input_,\n begin,\n end,\n strides=None,\n begin_mask=0,\n end_mask=0,\n ellipsis_mask=0,\n new_axis_mask=0,\n shrink_axis_mask=0,\n var=None,\n name=None):\n \"\"\"Extracts a strided slice of a tensor (generalized Python array indexing).\n\n See also `tf.slice`.\n\n **Instead of calling this op directly most users will want to use the\n NumPy-style slicing syntax (e.g. `tensor[..., 3:4:-1, tf.newaxis, 3]`), which\n is supported via `tf.Tensor.__getitem__` and `tf.Variable.__getitem__`.**\n The interface of this op is a low-level encoding of the slicing syntax.\n\n Roughly speaking, this op extracts a slice of size `(end-begin)/stride`\n from the given `input_` tensor. Starting at the location specified by `begin`\n the slice continues by adding `stride` to the index until all dimensions are\n not less than `end`.\n Note that a stride can be negative, which causes a reverse slice.\n\n Given a Python slice `input[spec0, spec1, ..., specn]`,\n this function will be called as follows.\n\n `begin`, `end`, and `strides` will be vectors of length n.\n n in general is not equal to the rank of the `input_` tensor.\n\n In each mask field (`begin_mask`, `end_mask`, `ellipsis_mask`,\n `new_axis_mask`, `shrink_axis_mask`) the ith bit will correspond to\n the ith spec.\n\n If the ith bit of `begin_mask` is set, `begin[i]` is ignored and\n the fullest possible range in that dimension is used instead.\n `end_mask` works analogously, except with the end range.\n\n `foo[5:,:,:3]` on a 7x8x9 tensor is equivalent to `foo[5:7,0:8,0:3]`.\n `foo[::-1]` reverses a tensor with shape 8.\n\n If the ith bit of `ellipsis_mask` is set, as many unspecified dimensions\n as needed will be inserted between other dimensions. Only one\n non-zero bit is allowed in `ellipsis_mask`.\n\n For example `foo[3:5,...,4:5]` on a shape 10x3x3x10 tensor is\n equivalent to `foo[3:5,:,:,4:5]` and\n `foo[3:5,...]` is equivalent to `foo[3:5,:,:,:]`.\n\n If the ith bit of `new_axis_mask` is set, then `begin`,\n `end`, and `stride` are ignored and a new length 1 dimension is\n added at this point in the output tensor.\n\n For example,\n `foo[:4, tf.newaxis, :2]` would produce a shape `(4, 1, 2)` tensor.\n\n If the ith bit of `shrink_axis_mask` is set, it implies that the ith\n specification shrinks the dimensionality by 1, taking on the value at index\n `begin[i]`. `end[i]` and `strides[i]` are ignored in this case. For example in\n Python one might do `foo[:, 3, :]` which would result in `shrink_axis_mask`\n equal to 2.\n\n\n NOTE: `begin` and `end` are zero-indexed.\n `strides` entries must be non-zero.\n\n\n ```python\n t = tf.constant([[[1, 1, 1], [2, 2, 2]],\n [[3, 3, 3], [4, 4, 4]],\n [[5, 5, 5], [6, 6, 6]]])\n tf.strided_slice(t, [1, 0, 0], [2, 1, 3], [1, 1, 1]) # [[[3, 3, 3]]]\n tf.strided_slice(t, [1, 0, 0], [2, 2, 3], [1, 1, 1]) # [[[3, 3, 3],\n # [4, 4, 4]]]\n tf.strided_slice(t, [1, -1, 0], [2, -3, 3], [1, -1, 1]) # [[[4, 4, 4],\n # [3, 3, 3]]]\n ```\n\n Args:\n input_: A `Tensor`.\n begin: An `int32` or `int64` `Tensor`.\n end: An `int32` or `int64` `Tensor`.\n strides: An `int32` or `int64` `Tensor`.\n begin_mask: An `int32` mask.\n end_mask: An `int32` mask.\n ellipsis_mask: An `int32` mask.\n new_axis_mask: An `int32` mask.\n shrink_axis_mask: An `int32` mask.\n var: The variable corresponding to `input_` or None\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` the same type as `input`.\n \"\"\"\n\n if strides is None:\n strides = ones_like(begin)\n\n op = gen_array_ops.strided_slice(\n input=input_,\n begin=begin,\n end=end,\n strides=strides,\n name=name,\n begin_mask=begin_mask,\n end_mask=end_mask,\n ellipsis_mask=ellipsis_mask,\n new_axis_mask=new_axis_mask,\n shrink_axis_mask=shrink_axis_mask)\n\n parent_name = name\n\n if var is not None:\n def assign(val, name=None):\n \"\"\"Closure that holds all the arguments to create an assignment.\"\"\"\n\n if name is None:\n name = parent_name + \"_assign\"\n\n return var._strided_slice_assign(\n begin=begin,\n end=end,\n strides=strides,\n value=val,\n name=name,\n begin_mask=begin_mask,\n end_mask=end_mask,\n ellipsis_mask=ellipsis_mask,\n new_axis_mask=new_axis_mask,\n shrink_axis_mask=shrink_axis_mask)\n\n op.assign = assign\n\n return op\n\n\ndef _SliceHelperVar(var, slice_spec):\n \"\"\"Creates a slice helper object given a variable.\n\n This allows creating a sub-tensor from part of the current contents\n of a variable. See `tf.Tensor.__getitem__` for detailed examples\n of slicing.\n\n This function in addition also allows assignment to a sliced range.\n This is similar to `__setitem__` functionality in Python. However,\n the syntax is different so that the user can capture the assignment\n operation for grouping or passing to `sess.run()`.\n For example,\n\n ```python\n import tensorflow as tf\n A = tf.Variable([[1,2,3], [4,5,6], [7,8,9]], dtype=tf.float32)\n with tf.compat.v1.Session() as sess:\n sess.run(tf.compat.v1.global_variables_initializer())\n print(sess.run(A[:2, :2])) # => [[1,2], [4,5]]\n\n op = A[:2,:2].assign(22. * tf.ones((2, 2)))\n print(sess.run(op)) # => [[22, 22, 3], [22, 22, 6], [7,8,9]]\n ```\n\n Note that assignments currently do not support NumPy broadcasting\n semantics.\n\n Args:\n var: An `ops.Variable` object.\n slice_spec: The arguments to `Tensor.__getitem__`.\n\n Returns:\n The appropriate slice of \"tensor\", based on \"slice_spec\".\n As an operator. The operator also has a `assign()` method\n that can be used to generate an assignment operator.\n\n Raises:\n ValueError: If a slice range is negative size.\n TypeError: TypeError: If the slice indices aren't int, slice,\n ellipsis, tf.newaxis or int32/int64 tensors.\n\n \"\"\"\n\n return _slice_helper(var.value(), slice_spec, var)\n\n\nops.Tensor._override_operator(\"__getitem__\", _slice_helper)\n\n\n@tf_export(\"parallel_stack\")\[email protected]_dispatch_support\ndef parallel_stack(values, name=\"parallel_stack\"):\n \"\"\"Stacks a list of rank-`R` tensors into one rank-`(R+1)` tensor in parallel.\n\n Requires that the shape of inputs be known at graph construction time.\n\n Packs the list of tensors in `values` into a tensor with rank one higher than\n each tensor in `values`, by packing them along the first dimension.\n Given a list of length `N` of tensors of shape `(A, B, C)`; the `output`\n tensor will have the shape `(N, A, B, C)`.\n\n For example:\n\n ```python\n x = tf.constant([1, 4])\n y = tf.constant([2, 5])\n z = tf.constant([3, 6])\n tf.parallel_stack([x, y, z]) # [[1, 4], [2, 5], [3, 6]]\n ```\n\n The difference between `stack` and `parallel_stack` is that `stack` requires\n all the inputs be computed before the operation will begin but doesn't require\n that the input shapes be known during graph construction.\n\n `parallel_stack` will copy pieces of the input into the output as they become\n available, in some situations this can provide a performance benefit.\n\n Unlike `stack`, `parallel_stack` does NOT support backpropagation.\n\n This is the opposite of unstack. The numpy equivalent is\n\n tf.parallel_stack([x, y, z]) = np.asarray([x, y, z])\n\n @compatibility(eager)\n parallel_stack is not compatible with eager execution.\n @end_compatibility\n\n Args:\n values: A list of `Tensor` objects with the same shape and type.\n name: A name for this operation (optional).\n\n Returns:\n output: A stacked `Tensor` with the same type as `values`.\n\n Raises:\n RuntimeError: if executed in eager mode.\n \"\"\"\n if context.executing_eagerly():\n raise RuntimeError(\"tf.parallel_stack() is not compatible with \"\n \"eager execution.\")\n with ops.name_scope(name):\n value_t = ops.convert_to_tensor(values[0])\n value_shape = ops.convert_to_tensor(value_t).get_shape()\n\n output_shape = tensor_shape.TensorShape([len(values)])\n output_shape = output_shape.concatenate(value_shape)\n # expand_dims converts concat to stack.\n return gen_array_ops.parallel_concat(\n [expand_dims(value, 0) for value in values], shape=output_shape)\n\n\n@tf_export(\"stack\")\[email protected]_dispatch_support\ndef stack(values, axis=0, name=\"stack\"):\n \"\"\"Stacks a list of rank-`R` tensors into one rank-`(R+1)` tensor.\n\n See also `tf.concat`, `tf.tile`, `tf.repeat`.\n\n Packs the list of tensors in `values` into a tensor with rank one higher than\n each tensor in `values`, by packing them along the `axis` dimension.\n Given a list of length `N` of tensors of shape `(A, B, C)`;\n\n if `axis == 0` then the `output` tensor will have the shape `(N, A, B, C)`.\n if `axis == 1` then the `output` tensor will have the shape `(A, N, B, C)`.\n Etc.\n\n For example:\n\n >>> x = tf.constant([1, 4])\n >>> y = tf.constant([2, 5])\n >>> z = tf.constant([3, 6])\n >>> tf.stack([x, y, z])\n <tf.Tensor: shape=(3, 2), dtype=int32, numpy=\n array([[1, 4],\n [2, 5],\n [3, 6]], dtype=int32)>\n >>> tf.stack([x, y, z], axis=1)\n <tf.Tensor: shape=(2, 3), dtype=int32, numpy=\n array([[1, 2, 3],\n [4, 5, 6]], dtype=int32)>\n\n This is the opposite of unstack. The numpy equivalent is `np.stack`\n\n >>> np.array_equal(np.stack([x, y, z]), tf.stack([x, y, z]))\n True\n\n Args:\n values: A list of `Tensor` objects with the same shape and type.\n axis: An `int`. The axis to stack along. Defaults to the first dimension.\n Negative values wrap around, so the valid range is `[-(R+1), R+1)`.\n name: A name for this operation (optional).\n\n Returns:\n output: A stacked `Tensor` with the same type as `values`.\n\n Raises:\n ValueError: If `axis` is out of the range [-(R+1), R+1).\n \"\"\"\n if axis == 0:\n try:\n # If the input is a constant list, it can be converted to a constant op\n return ops.convert_to_tensor(values, name=name)\n except (TypeError, ValueError):\n pass # Input list contains non-constant tensors\n\n value_shape = ops.convert_to_tensor(values[0], name=name)._shape_tuple() # pylint: disable=protected-access\n if value_shape is not None:\n expanded_num_dims = len(value_shape) + 1\n if axis < -expanded_num_dims or axis >= expanded_num_dims:\n raise ValueError(\"axis = %d not in [%d, %d)\" %\n (axis, -expanded_num_dims, expanded_num_dims))\n\n return gen_array_ops.pack(values, axis=axis, name=name)\n\n\n# pylint: disable=invalid-name\ndef _autopacking_helper(list_or_tuple, dtype, name):\n \"\"\"Converts the given list or tuple to a tensor by packing.\n\n Args:\n list_or_tuple: A (possibly nested) list or tuple containing a tensor.\n dtype: The element type of the returned tensor.\n name: A name for the returned tensor.\n\n Returns:\n A `tf.Tensor` with value equivalent to `list_or_tuple`.\n \"\"\"\n if context.executing_eagerly():\n # NOTE: Fast path when all the items are tensors, this doesn't do any type\n # checking.\n if all(isinstance(elem, core.Tensor) for elem in list_or_tuple):\n return gen_array_ops.pack(list_or_tuple, name=name)\n must_pack = False\n converted_elems = []\n with ops.name_scope(name) as scope:\n for i, elem in enumerate(list_or_tuple):\n if isinstance(elem, core.Tensor):\n if dtype is not None and elem.dtype.base_dtype != dtype:\n raise TypeError(\"Cannot convert a list containing a tensor of dtype \"\n \"%s to %s (Tensor is: %r)\" %\n (elem.dtype, dtype, elem))\n converted_elems.append(elem)\n must_pack = True\n elif isinstance(elem, (list, tuple)):\n converted_elem = _autopacking_helper(elem, dtype, str(i))\n if isinstance(converted_elem, core.Tensor):\n must_pack = True\n converted_elems.append(converted_elem)\n else:\n converted_elems.append(elem)\n if must_pack:\n elems_as_tensors = []\n for i, elem in enumerate(converted_elems):\n if isinstance(elem, core.Tensor):\n elems_as_tensors.append(elem)\n else:\n # NOTE(mrry): This is inefficient, but it enables us to\n # handle the case where the list arguments are other\n # convertible-to-tensor types, such as numpy arrays.\n elems_as_tensors.append(\n constant_op.constant(elem, dtype=dtype, name=str(i)))\n return gen_array_ops.pack(elems_as_tensors, name=scope)\n else:\n return converted_elems\n\n\ndef _get_dtype_from_nested_lists(list_or_tuple):\n \"\"\"Returns the dtype of any tensor-like object in `list_or_tuple`, if found.\n\n Args:\n list_or_tuple: A list or tuple representing an object that can be converted\n to a `tf.Tensor`.\n\n Returns:\n The dtype of any tensor-like object in `list_or_tuple`, or `None` if no\n such object exists.\n \"\"\"\n for elem in list_or_tuple:\n if isinstance(elem, core.Tensor):\n return elem.dtype.base_dtype\n elif isinstance(elem, (list, tuple)):\n maybe_dtype = _get_dtype_from_nested_lists(elem)\n if maybe_dtype is not None:\n return maybe_dtype\n return None\n\n\ndef _cast_nested_seqs_to_dtype(dtype):\n\n def _maybe_cast(elem):\n if isinstance(elem, core.Tensor):\n if dtype != elem.dtype.base_dtype:\n elem = gen_math_ops.cast(elem, dtype)\n return elem\n\n return _maybe_cast\n\n\n_NON_AUTOPACKABLE_TYPES = set(np.core.numerictypes.ScalarType)\n_NON_AUTOPACKABLE_TYPES.add(np.ndarray)\n\n\ndef _should_not_autopack(v):\n # The condition we really want is\n # any(isinstance(elem, core.Tensor))\n # but it is >5x slower due to abc.ABCMeta.__instancecheck__.\n # pylint: disable=unidiomatic-typecheck\n # TODO(slebedev): add nest.all?\n return all(type(elem) in _NON_AUTOPACKABLE_TYPES for elem in nest.flatten(v))\n # pylint: enable=unidiomatic-typecheck\n\n\ndef _autopacking_conversion_function(v, dtype=None, name=None, as_ref=False):\n \"\"\"Tensor conversion function that automatically packs arguments.\"\"\"\n if as_ref or _should_not_autopack(v):\n return NotImplemented\n inferred_dtype = _get_dtype_from_nested_lists(v)\n if inferred_dtype is None:\n # We did not find any tensor-like objects in the nested lists, so defer to\n # other conversion functions.\n return NotImplemented\n if dtype is None:\n dtype = inferred_dtype\n elif dtype != inferred_dtype:\n v = nest.map_structure(_cast_nested_seqs_to_dtype(dtype), v)\n return _autopacking_helper(v, dtype, name or \"packed\")\n\n\n# pylint: enable=invalid-name\n\n# NOTE: Register this conversion function to run *before* one that\n# assumes every element is a value.\nops.register_tensor_conversion_function((list, tuple),\n _autopacking_conversion_function, 99)\n\n\n@tf_export(\"unstack\")\[email protected]_dispatch_support\ndef unstack(value, num=None, axis=0, name=\"unstack\"):\n \"\"\"Unpacks the given dimension of a rank-`R` tensor into rank-`(R-1)` tensors.\n\n Unpacks tensors from `value` by chipping it along the `axis` dimension.\n\n >>> x = tf.reshape(tf.range(12), (3,4))\n >>>\n >>> p, q, r = tf.unstack(x)\n >>> p.shape.as_list()\n [4]\n\n >>> i, j, k, l = tf.unstack(x, axis=1)\n >>> i.shape.as_list()\n [3]\n\n This is the opposite of stack.\n\n >>> x = tf.stack([i, j, k, l], axis=1)\n\n More generally if you have a tensor of shape `(A, B, C, D)`:\n\n >>> A, B, C, D = [2, 3, 4, 5]\n >>> t = tf.random.normal(shape=[A, B, C, D])\n\n The number of tensor returned is equal to the length of the target `axis`:\n\n >>> axis = 2\n >>> items = tf.unstack(t, axis=axis)\n >>> len(items) == t.shape[axis]\n True\n\n The shape of each result tensor is equal to the shape of the input tensor,\n with the target `axis` removed.\n\n >>> items[0].shape.as_list() # [A, B, D]\n [2, 3, 5]\n\n The value of each tensor `items[i]` is equal to the slice of `input` across\n `axis` at index `i`:\n\n >>> for i in range(len(items)):\n ... slice = t[:,:,i,:]\n ... assert tf.reduce_all(slice == items[i])\n\n #### Python iterable unpacking\n\n With eager execution you _can_ unstack the 0th axis of a tensor using python's\n iterable unpacking:\n\n >>> t = tf.constant([1,2,3])\n >>> a,b,c = t\n\n `unstack` is still necessary because Iterable unpacking doesn't work in\n a `@tf.function`: Symbolic tensors are not iterable.\n\n You need to use `tf.unstack` here:\n\n >>> @tf.function\n ... def bad(t):\n ... a,b,c = t\n ... return a\n >>>\n >>> bad(t)\n Traceback (most recent call last):\n ...\n OperatorNotAllowedInGraphError: ...\n\n >>> @tf.function\n ... def good(t):\n ... a,b,c = tf.unstack(t)\n ... return a\n >>>\n >>> good(t).numpy()\n 1\n\n #### Unknown shapes\n\n Eager tensors have concrete values, so their shape is always known.\n Inside a `tf.function` the symbolic tensors may have unknown shapes.\n If the length of `axis` is unknown `tf.unstack` will fail because it cannot\n handle an unknown number of tensors:\n\n >>> @tf.function(input_signature=[tf.TensorSpec([None], tf.float32)])\n ... def bad(t):\n ... tensors = tf.unstack(t)\n ... return tensors[0]\n >>>\n >>> bad(tf.constant([1,2,3]))\n Traceback (most recent call last):\n ...\n ValueError: Cannot infer num from shape (None,)\n\n If you know the `axis` length you can pass it as the `num` argument. But this\n must be a constant value.\n\n If you actually need a variable number of tensors in a single `tf.function`\n trace, you will need to use exlicit loops and a `tf.TensorArray` instead.\n\n Args:\n value: A rank `R > 0` `Tensor` to be unstacked.\n num: An `int`. The length of the dimension `axis`. Automatically inferred if\n `None` (the default).\n axis: An `int`. The axis to unstack along. Defaults to the first dimension.\n Negative values wrap around, so the valid range is `[-R, R)`.\n name: A name for the operation (optional).\n\n Returns:\n The list of `Tensor` objects unstacked from `value`.\n\n Raises:\n ValueError: If `axis` is out of the range `[-R, R)`.\n ValueError: If `num` is unspecified and cannot be inferred.\n InvalidArgumentError: If `num` does not match the shape of `value`.\n \"\"\"\n if num is None:\n value = ops.convert_to_tensor(value)\n value_shape = value.get_shape()\n if value_shape.ndims is not None:\n if axis < -value_shape.ndims or axis >= value_shape.ndims:\n raise ValueError(\"axis = %d not in [%d, %d)\" %\n (axis, -value_shape.ndims, value_shape.ndims))\n num = value_shape.dims[axis].value\n if num is None:\n raise ValueError(\"Cannot infer num from shape %s\" % value_shape)\n return gen_array_ops.unpack(value, num=num, axis=axis, name=name)\n\n\n@tf_export(\"concat\")\[email protected]_dispatch_support\ndef concat(values, axis, name=\"concat\"):\n \"\"\"Concatenates tensors along one dimension.\n\n See also `tf.tile`, `tf.stack`, `tf.repeat`.\n\n Concatenates the list of tensors `values` along dimension `axis`. If\n `values[i].shape = [D0, D1, ... Daxis(i), ...Dn]`, the concatenated\n result has shape\n\n [D0, D1, ... Raxis, ...Dn]\n\n where\n\n Raxis = sum(Daxis(i))\n\n That is, the data from the input tensors is joined along the `axis`\n dimension.\n\n The number of dimensions of the input tensors must match, and all dimensions\n except `axis` must be equal.\n\n For example:\n\n >>> t1 = [[1, 2, 3], [4, 5, 6]]\n >>> t2 = [[7, 8, 9], [10, 11, 12]]\n >>> tf.concat([t1, t2], 0)\n <tf.Tensor: shape=(4, 3), dtype=int32, numpy=\n array([[ 1, 2, 3],\n [ 4, 5, 6],\n [ 7, 8, 9],\n [10, 11, 12]], dtype=int32)>\n\n >>> tf.concat([t1, t2], 1)\n <tf.Tensor: shape=(2, 6), dtype=int32, numpy=\n array([[ 1, 2, 3, 7, 8, 9],\n [ 4, 5, 6, 10, 11, 12]], dtype=int32)>\n\n As in Python, the `axis` could also be negative numbers. Negative `axis`\n are interpreted as counting from the end of the rank, i.e.,\n `axis + rank(values)`-th dimension.\n\n For example:\n\n >>> t1 = [[[1, 2], [2, 3]], [[4, 4], [5, 3]]]\n >>> t2 = [[[7, 4], [8, 4]], [[2, 10], [15, 11]]]\n >>> tf.concat([t1, t2], -1)\n <tf.Tensor: shape=(2, 2, 4), dtype=int32, numpy=\n array([[[ 1, 2, 7, 4],\n [ 2, 3, 8, 4]],\n [[ 4, 4, 2, 10],\n [ 5, 3, 15, 11]]], dtype=int32)>\n\n Note: If you are concatenating along a new axis consider using stack.\n E.g.\n\n ```python\n tf.concat([tf.expand_dims(t, axis) for t in tensors], axis)\n ```\n\n can be rewritten as\n\n ```python\n tf.stack(tensors, axis=axis)\n ```\n\n Args:\n values: A list of `Tensor` objects or a single `Tensor`.\n axis: 0-D `int32` `Tensor`. Dimension along which to concatenate. Must be\n in the range `[-rank(values), rank(values))`. As in Python, indexing for\n axis is 0-based. Positive axis in the rage of `[0, rank(values))` refers\n to `axis`-th dimension. And negative axis refers to `axis +\n rank(values)`-th dimension.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` resulting from concatenation of the input tensors.\n \"\"\"\n if not isinstance(values, (list, tuple)):\n values = [values]\n # TODO(mrry): Change to return values?\n if len(values) == 1: # Degenerate case of one tensor.\n # Make a throwaway call to convert_to_tensor to make sure\n # that axis is of the correct type, and make sure that\n # the returned tensor is a scalar.\n # TODO(keveman): Implement a standalone type and shape checker.\n with ops.name_scope(name) as scope:\n ops.convert_to_tensor(\n axis, name=\"concat_dim\",\n dtype=dtypes.int32).get_shape().assert_has_rank(0)\n return identity(values[0], name=name)\n return gen_array_ops.concat_v2(values=values, axis=axis, name=name)\n\n\n@tf_export(v1=[\"boolean_mask\"])\[email protected]_dispatch_support\ndef boolean_mask(tensor, mask, name=\"boolean_mask\", axis=None):\n \"\"\"Apply boolean mask to tensor.\n\n Numpy equivalent is `tensor[mask]`.\n\n In general, `0 < dim(mask) = K <= dim(tensor)`, and `mask`'s shape must match\n the first K dimensions of `tensor`'s shape. We then have:\n `boolean_mask(tensor, mask)[i, j1,...,jd] = tensor[i1,...,iK,j1,...,jd]`\n where `(i1,...,iK)` is the ith `True` entry of `mask` (row-major order).\n The `axis` could be used with `mask` to indicate the axis to mask from.\n In that case, `axis + dim(mask) <= dim(tensor)` and `mask`'s shape must match\n the first `axis + dim(mask)` dimensions of `tensor`'s shape.\n\n See also: `tf.ragged.boolean_mask`, which can be applied to both dense and\n ragged tensors, and can be used if you need to preserve the masked dimensions\n of `tensor` (rather than flattening them, as `tf.boolean_mask` does).\n\n Examples:\n\n ```python\n # 1-D example\n tensor = [0, 1, 2, 3]\n mask = np.array([True, False, True, False])\n tf.boolean_mask(tensor, mask) # [0, 2]\n\n # 2-D example\n tensor = [[1, 2], [3, 4], [5, 6]]\n mask = np.array([True, False, True])\n tf.boolean_mask(tensor, mask) # [[1, 2], [5, 6]]\n ```\n\n Args:\n tensor: N-D Tensor.\n mask: K-D boolean Tensor, K <= N and K must be known statically.\n name: A name for this operation (optional).\n axis: A 0-D int Tensor representing the axis in `tensor` to mask from. By\n default, axis is 0 which will mask from the first dimension. Otherwise K +\n axis <= N.\n\n Returns:\n (N-K+1)-dimensional tensor populated by entries in `tensor` corresponding\n to `True` values in `mask`.\n\n Raises:\n ValueError: If shapes do not conform.\n \"\"\"\n\n def _apply_mask_1d(reshaped_tensor, mask, axis=None):\n \"\"\"Mask tensor along dimension 0 with a 1-D mask.\"\"\"\n indices = squeeze(where_v2(mask), axis=[1])\n return gather(reshaped_tensor, indices, axis=axis)\n\n with ops.name_scope(name, values=[tensor, mask]):\n tensor = ops.convert_to_tensor(tensor, name=\"tensor\")\n mask = ops.convert_to_tensor(mask, name=\"mask\")\n\n shape_mask = mask.get_shape()\n ndims_mask = shape_mask.ndims\n shape_tensor = tensor.get_shape()\n if ndims_mask == 0:\n raise ValueError(\"mask cannot be scalar.\")\n if ndims_mask is None:\n raise ValueError(\n \"Number of mask dimensions must be specified, even if some dimensions\"\n \" are None. E.g. shape=[None] is ok, but shape=None is not.\")\n axis = 0 if axis is None else axis\n axis_value = tensor_util.constant_value(axis)\n if axis_value is not None:\n axis = axis_value\n shape_tensor[axis:axis + ndims_mask].assert_is_compatible_with(shape_mask)\n\n leading_size = gen_math_ops.prod(shape(tensor)[axis:axis + ndims_mask], [0])\n tensor = reshape(\n tensor,\n concat([\n shape(tensor)[:axis], [leading_size],\n shape(tensor)[axis + ndims_mask:]\n ], 0))\n # TODO(yongtang): tf.reshape in C++ kernel might have set the shape\n # correctly, so the following may not be needed? It still might be possible\n # that there are some edge case where tensor_util.constant_value resolves\n # more cases than ShapeInference of tf.reshape in C++ kernel.\n if axis_value is not None:\n first_dim = shape_tensor[axis:axis + ndims_mask].num_elements()\n tensor.set_shape(\n tensor_shape.as_shape(shape_tensor[:axis]).concatenate(\n [first_dim]).concatenate(shape_tensor[axis + ndims_mask:]))\n\n mask = reshape(mask, [-1])\n return _apply_mask_1d(tensor, mask, axis)\n\n\n@tf_export(\"boolean_mask\", v1=[])\[email protected]_dispatch_support\ndef boolean_mask_v2(tensor, mask, axis=None, name=\"boolean_mask\"):\n \"\"\"Apply boolean mask to tensor.\n\n Numpy equivalent is `tensor[mask]`.\n\n In general, `0 < dim(mask) = K <= dim(tensor)`, and `mask`'s shape must match\n the first K dimensions of `tensor`'s shape. We then have:\n `boolean_mask(tensor, mask)[i, j1,...,jd] = tensor[i1,...,iK,j1,...,jd]`\n where `(i1,...,iK)` is the ith `True` entry of `mask` (row-major order).\n The `axis` could be used with `mask` to indicate the axis to mask from.\n In that case, `axis + dim(mask) <= dim(tensor)` and `mask`'s shape must match\n the first `axis + dim(mask)` dimensions of `tensor`'s shape.\n\n See also: `tf.ragged.boolean_mask`, which can be applied to both dense and\n ragged tensors, and can be used if you need to preserve the masked dimensions\n of `tensor` (rather than flattening them, as `tf.boolean_mask` does).\n\n Examples:\n\n >>> tensor = [0, 1, 2, 3] # 1-D example\n >>> mask = np.array([True, False, True, False])\n >>> tf.boolean_mask(tensor, mask)\n <tf.Tensor: shape=(2,), dtype=int32, numpy=array([0, 2], dtype=int32)>\n\n >>> tensor = [[1, 2], [3, 4], [5, 6]] # 2-D example\n >>> mask = np.array([True, False, True])\n >>> tf.boolean_mask(tensor, mask)\n <tf.Tensor: shape=(2, 2), dtype=int32, numpy=\n array([[1, 2],\n [5, 6]], dtype=int32)>\n\n Args:\n tensor: N-D Tensor.\n mask: K-D boolean Tensor, K <= N and K must be known statically.\n axis: A 0-D int Tensor representing the axis in `tensor` to mask from. By\n default, axis is 0 which will mask from the first dimension. Otherwise K +\n axis <= N.\n name: A name for this operation (optional).\n\n Returns:\n (N-K+1)-dimensional tensor populated by entries in `tensor` corresponding\n to `True` values in `mask`.\n\n Raises:\n ValueError: If shapes do not conform.\n\n Examples:\n\n ```python\n # 2-D example\n tensor = [[1, 2], [3, 4], [5, 6]]\n mask = np.array([True, False, True])\n boolean_mask(tensor, mask) # [[1, 2], [5, 6]]\n ```\n \"\"\"\n return boolean_mask(tensor, mask, name, axis)\n\n\n@tf_export(\"sparse.mask\", v1=[\"sparse.mask\", \"sparse_mask\"])\[email protected]_endpoints(\"sparse_mask\")\ndef sparse_mask(a, mask_indices, name=None):\n \"\"\"Masks elements of `IndexedSlices`.\n\n Given an `IndexedSlices` instance `a`, returns another `IndexedSlices` that\n contains a subset of the slices of `a`. Only the slices at indices not\n specified in `mask_indices` are returned.\n\n This is useful when you need to extract a subset of slices in an\n `IndexedSlices` object.\n\n For example:\n\n ```python\n # `a` contains slices at indices [12, 26, 37, 45] from a large tensor\n # with shape [1000, 10]\n a.indices # [12, 26, 37, 45]\n tf.shape(a.values) # [4, 10]\n\n # `b` will be the subset of `a` slices at its second and third indices, so\n # we want to mask its first and last indices (which are at absolute\n # indices 12, 45)\n b = tf.sparse.mask(a, [12, 45])\n\n b.indices # [26, 37]\n tf.shape(b.values) # [2, 10]\n ```\n\n Args:\n a: An `IndexedSlices` instance.\n mask_indices: Indices of elements to mask.\n name: A name for the operation (optional).\n\n Returns:\n The masked `IndexedSlices` instance.\n \"\"\"\n with ops.name_scope(name, \"sparse_mask\", [a, mask_indices]) as name:\n indices = a.indices\n out_indices, to_gather = gen_array_ops.list_diff(indices, mask_indices)\n out_values = gather(a.values, to_gather, name=name)\n return ops.IndexedSlices(out_values, out_indices, a.dense_shape)\n\n\n@tf_export(\"unique\")\[email protected]_dispatch_support\ndef unique(x, out_idx=dtypes.int32, name=None):\n \"\"\"Finds unique elements in a 1-D tensor.\n\n See also `tf.unique_with_counts`.\n\n This operation returns a tensor `y` containing all of the unique elements\n of `x` sorted in the same order that they occur in `x`. This operation\n also returns a tensor `idx` the same size as `x` that contains the index\n of each value of `x` in the unique output `y`. In other words:\n\n\n y[idx[i]] = x[i] for i in [0, 1,...,rank(x) - 1]\n\n Example usage:\n\n >>> x = tf.constant([1, 1, 2, 4, 4, 4, 7, 8, 8])\n >>> y, idx = unique(x)\n >>> y\n <tf.Tensor: id=5, shape=(5,), dtype=int32,\n numpy=array([1, 2, 4, 7, 8], dtype=int32)>\n >>> idx\n <tf.Tensor: id=6, shape=(9,), dtype=int32,\n numpy=array([0, 0, 1, 2, 2, 2, 3, 4, 4], dtype=int32)>\n\n Args:\n x: A Tensor. 1-D.\n out_idx: An optional tf.DType from: tf.int32, tf.int64. Defaults to\n tf.int32.\n name: A name for the operation (optional).\n\n Returns:\n A tuple of Tensor objects (y, idx).\n y: A Tensor. Has the same type as x.\n idx: A Tensor of type out_idx.\n\n \"\"\"\n # TODO(yongtang): switch to v2 once API deprecation\n # period (3 weeks) pass.\n # TODO(yongtang): The documentation should also\n # be updated when switch to v2.\n return gen_array_ops.unique(x, out_idx, name)\n\n\nunique.__doc__ = gen_array_ops.unique.__doc__\n\n\n@tf_export(\"unique_with_counts\")\[email protected]_dispatch_support\ndef unique_with_counts(x, out_idx=dtypes.int32, name=None):\n \"\"\"Finds unique elements in a 1-D tensor.\n\n See also `tf.unique`.\n\n This operation returns a tensor `y` containing all of the unique elements\n of `x` sorted in the same order that they occur in `x`. This operation\n also returns a tensor `idx` the same size as `x` that contains the index\n of each value of `x` in the unique output `y`. Finally, it returns a\n third tensor `count` that contains the count of each element of `y`\n in `x`. In other words:\n\n y[idx[i]] = x[i] for i in [0, 1,...,rank(x) - 1]\n\n Example usage:\n\n >>> x = tf.constant([1, 1, 2, 4, 4, 4, 7, 8, 8])\n >>> y, idx, count = unique_with_counts(x)\n >>> y\n <tf.Tensor: id=8, shape=(5,), dtype=int32,\n numpy=array([1, 2, 4, 7, 8], dtype=int32)>\n >>> idx\n <tf.Tensor: id=9, shape=(9,), dtype=int32,\n numpy=array([0, 0, 1, 2, 2, 2, 3, 4, 4], dtype=int32)>\n >>> count\n <tf.Tensor: id=10, shape=(5,), dtype=int32,\n numpy=array([2, 1, 3, 1, 2], dtype=int32)>\n\n Args:\n x: A Tensor. 1-D.\n out_idx: An optional tf.DType from: tf.int32, tf.int64. Defaults to\n tf.int32.\n name: A name for the operation (optional).\n\n Returns:\n A tuple of Tensor objects (y, idx, count).\n y: A Tensor. Has the same type as x.\n idx: A Tensor of type out_idx.\n count: A Tensor of type out_idx.\n\n \"\"\"\n # TODO(yongtang): switch to v2 once API deprecation\n # period (3 weeks) pass.\n # TODO(yongtang): The documentation should also\n # be updated when switch to v2.\n return gen_array_ops.unique_with_counts(x, out_idx, name)\n\n\nunique_with_counts.__doc__ = gen_array_ops.unique_with_counts.__doc__\n\n\n@tf_export(\"split\")\[email protected]_dispatch_support\ndef split(value, num_or_size_splits, axis=0, num=None, name=\"split\"):\n \"\"\"Splits a tensor `value` into a list of sub tensors.\n\n See also `tf.unstack`.\n\n If `num_or_size_splits` is an integer, then `value` is split along the\n dimension `axis` into `num_or_size_splits` smaller tensors. This requires that\n `value.shape[axis]` is divisible by `num_or_size_splits`.\n\n If `num_or_size_splits` is a 1-D Tensor (or list), then `value` is split into\n `len(num_or_size_splits)` elements. The shape of the `i`-th\n element has the same size as the `value` except along dimension `axis` where\n the size is `num_or_size_splits[i]`.\n\n For example:\n\n >>> x = tf.Variable(tf.random.uniform([5, 30], -1, 1))\n >>>\n >>> # Split `x` into 3 tensors along dimension 1\n >>> s0, s1, s2 = tf.split(x, num_or_size_splits=3, axis=1)\n >>> tf.shape(s0).numpy()\n array([ 5, 10], dtype=int32)\n >>>\n >>> # Split `x` into 3 tensors with sizes [4, 15, 11] along dimension 1\n >>> split0, split1, split2 = tf.split(x, [4, 15, 11], 1)\n >>> tf.shape(split0).numpy()\n array([5, 4], dtype=int32)\n >>> tf.shape(split1).numpy()\n array([ 5, 15], dtype=int32)\n >>> tf.shape(split2).numpy()\n array([ 5, 11], dtype=int32)\n\n Args:\n value: The `Tensor` to split.\n num_or_size_splits: Either an integer indicating the number of splits along\n `axis` or a 1-D integer `Tensor` or Python list containing the sizes of\n each output tensor along `axis`. If a scalar, then it must evenly divide\n `value.shape[axis]`; otherwise the sum of sizes along the split axis\n must match that of the `value`.\n axis: An integer or scalar `int32` `Tensor`. The dimension along which to\n split. Must be in the range `[-rank(value), rank(value))`. Defaults to 0.\n num: Optional, used to specify the number of outputs when it cannot be\n inferred from the shape of `size_splits`.\n name: A name for the operation (optional).\n\n Returns:\n if `num_or_size_splits` is a scalar returns a list of `num_or_size_splits`\n `Tensor` objects; if `num_or_size_splits` is a 1-D Tensor returns\n `num_or_size_splits.get_shape[0]` `Tensor` objects resulting from splitting\n `value`.\n\n Raises:\n ValueError: If `num` is unspecified and cannot be inferred.\n \"\"\"\n if isinstance(num_or_size_splits,\n (numbers.Integral, tensor_shape.Dimension)):\n return gen_array_ops.split(\n axis=axis, num_split=num_or_size_splits, value=value, name=name)\n\n size_splits = ops.convert_to_tensor(num_or_size_splits)\n\n if size_splits._rank() == 0:\n raise ValueError(\n \"Rank-0 tensors are not supported as the num_or_size_splits argument \"\n \"to split. Argument provided: %s\" % (num_or_size_splits,))\n\n if num is None:\n size_splits_shape = size_splits._shape_tuple()\n if size_splits_shape:\n num = size_splits_shape[0]\n if num is None:\n raise ValueError(\"Cannot infer num from shape %s\" % num_or_size_splits)\n\n return gen_array_ops.split_v(\n value=value, size_splits=size_splits, axis=axis, num_split=num, name=name)\n\n\n@tf_export(\"transpose\", v1=[])\[email protected]_dispatch_support\ndef transpose_v2(a, perm=None, conjugate=False, name=\"transpose\"):\n \"\"\"Transposes `a`, where `a` is a Tensor.\n\n Permutes the dimensions according to the value of `perm`.\n\n The returned tensor's dimension `i` will correspond to the input dimension\n `perm[i]`. If `perm` is not given, it is set to (n-1...0), where n is the rank\n of the input tensor. Hence by default, this operation performs a regular\n matrix transpose on 2-D input Tensors.\n\n If conjugate is `True` and `a.dtype` is either `complex64` or `complex128`\n then the values of `a` are conjugated and transposed.\n\n @compatibility(numpy)\n In `numpy` transposes are memory-efficient constant time operations as they\n simply return a new view of the same data with adjusted `strides`.\n\n TensorFlow does not support strides, so `transpose` returns a new tensor with\n the items permuted.\n @end_compatibility\n\n For example:\n\n >>> x = tf.constant([[1, 2, 3], [4, 5, 6]])\n >>> tf.transpose(x)\n <tf.Tensor: shape=(3, 2), dtype=int32, numpy=\n array([[1, 4],\n [2, 5],\n [3, 6]], dtype=int32)>\n\n Equivalently, you could call `tf.transpose(x, perm=[1, 0])`.\n\n If `x` is complex, setting conjugate=True gives the conjugate transpose:\n\n >>> x = tf.constant([[1 + 1j, 2 + 2j, 3 + 3j],\n ... [4 + 4j, 5 + 5j, 6 + 6j]])\n >>> tf.transpose(x, conjugate=True)\n <tf.Tensor: shape=(3, 2), dtype=complex128, numpy=\n array([[1.-1.j, 4.-4.j],\n [2.-2.j, 5.-5.j],\n [3.-3.j, 6.-6.j]])>\n\n 'perm' is more useful for n-dimensional tensors where n > 2:\n\n >>> x = tf.constant([[[ 1, 2, 3],\n ... [ 4, 5, 6]],\n ... [[ 7, 8, 9],\n ... [10, 11, 12]]])\n\n As above, simply calling `tf.transpose` will default to `perm=[2,1,0]`.\n\n To take the transpose of the matrices in dimension-0 (such as when you are\n transposing matrices where 0 is the batch dimension), you would set\n `perm=[0,2,1]`.\n\n >>> tf.transpose(x, perm=[0, 2, 1])\n <tf.Tensor: shape=(2, 3, 2), dtype=int32, numpy=\n array([[[ 1, 4],\n [ 2, 5],\n [ 3, 6]],\n [[ 7, 10],\n [ 8, 11],\n [ 9, 12]]], dtype=int32)>\n\n Note: This has a shorthand `linalg.matrix_transpose`):\n\n Args:\n a: A `Tensor`.\n perm: A permutation of the dimensions of `a`. This should be a vector.\n conjugate: Optional bool. Setting it to `True` is mathematically equivalent\n to tf.math.conj(tf.transpose(input)).\n name: A name for the operation (optional).\n\n Returns:\n A transposed `Tensor`.\n \"\"\"\n return transpose(a=a, perm=perm, name=name, conjugate=conjugate)\n\n\n@tf_export(v1=[\"transpose\"])\[email protected]_dispatch_support\ndef transpose(a, perm=None, name=\"transpose\", conjugate=False):\n \"\"\"Transposes `a`.\n\n Permutes the dimensions according to `perm`.\n\n The returned tensor's dimension i will correspond to the input dimension\n `perm[i]`. If `perm` is not given, it is set to (n-1...0), where n is\n the rank of the input tensor. Hence by default, this operation performs a\n regular matrix transpose on 2-D input Tensors. If conjugate is True and\n `a.dtype` is either `complex64` or `complex128` then the values of `a`\n are conjugated and transposed.\n\n @compatibility(numpy)\n In `numpy` transposes are memory-efficient constant time operations as they\n simply return a new view of the same data with adjusted `strides`.\n\n TensorFlow does not support strides, so `transpose` returns a new tensor with\n the items permuted.\n @end_compatibility\n\n For example:\n\n ```python\n x = tf.constant([[1, 2, 3], [4, 5, 6]])\n tf.transpose(x) # [[1, 4]\n # [2, 5]\n # [3, 6]]\n\n # Equivalently\n tf.transpose(x, perm=[1, 0]) # [[1, 4]\n # [2, 5]\n # [3, 6]]\n\n # If x is complex, setting conjugate=True gives the conjugate transpose\n x = tf.constant([[1 + 1j, 2 + 2j, 3 + 3j],\n [4 + 4j, 5 + 5j, 6 + 6j]])\n tf.transpose(x, conjugate=True) # [[1 - 1j, 4 - 4j],\n # [2 - 2j, 5 - 5j],\n # [3 - 3j, 6 - 6j]]\n\n # 'perm' is more useful for n-dimensional tensors, for n > 2\n x = tf.constant([[[ 1, 2, 3],\n [ 4, 5, 6]],\n [[ 7, 8, 9],\n [10, 11, 12]]])\n\n # Take the transpose of the matrices in dimension-0\n # (this common operation has a shorthand `linalg.matrix_transpose`)\n tf.transpose(x, perm=[0, 2, 1]) # [[[1, 4],\n # [2, 5],\n # [3, 6]],\n # [[7, 10],\n # [8, 11],\n # [9, 12]]]\n ```\n\n Args:\n a: A `Tensor`.\n perm: A permutation of the dimensions of `a`.\n name: A name for the operation (optional).\n conjugate: Optional bool. Setting it to `True` is mathematically equivalent\n to tf.math.conj(tf.transpose(input)).\n\n Returns:\n A transposed `Tensor`.\n \"\"\"\n with ops.name_scope(name, \"transpose\", [a]) as name:\n if not tensor_util.is_tf_type(a):\n a = ops.convert_to_tensor(a, name=\"a\")\n\n if conjugate and a.dtype.is_complex:\n transpose_fn = gen_array_ops.conjugate_transpose\n else:\n transpose_fn = gen_array_ops.transpose\n\n if perm is not None:\n return transpose_fn(a, perm, name=name)\n\n rank = a.shape.rank\n if rank is None:\n perm = gen_math_ops._range(gen_array_ops.rank(a) - 1, -1, -1)\n else:\n perm = np.arange(rank - 1, -1, -1, dtype=np.int32)\n return transpose_fn(a, perm, name=name)\n\n\n# pylint: disable=invalid-name\n@tf_export(\n \"linalg.matrix_transpose\",\n v1=[\"linalg.transpose\", \"linalg.matrix_transpose\", \"matrix_transpose\"])\[email protected]_dispatch_support\[email protected]_endpoints(\"matrix_transpose\", \"linalg.transpose\")\ndef matrix_transpose(a, name=\"matrix_transpose\", conjugate=False):\n \"\"\"Transposes last two dimensions of tensor `a`.\n\n For example:\n\n ```python\n x = tf.constant([[1, 2, 3], [4, 5, 6]])\n tf.linalg.matrix_transpose(x) # [[1, 4],\n # [2, 5],\n # [3, 6]]\n\n x = tf.constant([[1 + 1j, 2 + 2j, 3 + 3j],\n [4 + 4j, 5 + 5j, 6 + 6j]])\n tf.linalg.matrix_transpose(x, conjugate=True) # [[1 - 1j, 4 - 4j],\n # [2 - 2j, 5 - 5j],\n # [3 - 3j, 6 - 6j]]\n\n # Matrix with two batch dimensions.\n # x.shape is [1, 2, 3, 4]\n # tf.linalg.matrix_transpose(x) is shape [1, 2, 4, 3]\n ```\n\n Note that `tf.matmul` provides kwargs allowing for transpose of arguments.\n This is done with minimal cost, and is preferable to using this function. E.g.\n\n ```python\n # Good! Transpose is taken at minimal additional cost.\n tf.matmul(matrix, b, transpose_b=True)\n\n # Inefficient!\n tf.matmul(matrix, tf.linalg.matrix_transpose(b))\n ```\n\n @compatibility(numpy)\n In `numpy` transposes are memory-efficient constant time operations as they\n simply return a new view of the same data with adjusted `strides`.\n\n TensorFlow does not support strides, `linalg.matrix_transpose` returns a new\n tensor with the items permuted.\n @end_compatibility\n\n Args:\n a: A `Tensor` with `rank >= 2`.\n name: A name for the operation (optional).\n conjugate: Optional bool. Setting it to `True` is mathematically equivalent\n to tf.math.conj(tf.linalg.matrix_transpose(input)).\n\n Returns:\n A transposed batch matrix `Tensor`.\n\n Raises:\n ValueError: If `a` is determined statically to have `rank < 2`.\n \"\"\"\n with ops.name_scope(name, values=[a]):\n a = ops.convert_to_tensor(a, name=\"a\")\n\n # If we know the number of dimensions (statically), we can do two things:\n # 1. Check that `a` is a (batch) matrix.\n # 2. Use a Python list for perm. This preserves static shape information\n # and avoids extra computations.\n a_shape = a.get_shape()\n ndims = a_shape.ndims\n if ndims is not None:\n if ndims < 2:\n raise ValueError(\n \"Argument 'a' should be a (batch) matrix, with rank >= 2. Found: \"\n \"%s\" % a_shape)\n perm = list(range(ndims - 2)) + [ndims - 1] + [ndims - 2]\n else:\n a_rank = rank(a)\n perm = concat(\n (gen_math_ops._range(0, a_rank - 2, 1), [a_rank - 1, a_rank - 2]), 0)\n\n return transpose(a, perm=perm, conjugate=conjugate)\n\n\n@tf_export(\"linalg.diag\", v1=[\"linalg.diag\", \"matrix_diag\"])\[email protected]_dispatch_support\[email protected]_endpoints(\"matrix_diag\")\ndef matrix_diag(diagonal,\n name=\"diag\",\n k=0,\n num_rows=-1,\n num_cols=-1,\n padding_value=0,\n align=\"RIGHT_LEFT\"):\n \"\"\"Returns a batched diagonal tensor with given batched diagonal values.\n\n Returns a tensor with the contents in `diagonal` as `k[0]`-th to `k[1]`-th\n diagonals of a matrix, with everything else padded with `padding`. `num_rows`\n and `num_cols` specify the dimension of the innermost matrix of the output. If\n both are not specified, the op assumes the innermost matrix is square and\n infers its size from `k` and the innermost dimension of `diagonal`. If only\n one of them is specified, the op assumes the unspecified value is the smallest\n possible based on other criteria.\n\n Let `diagonal` have `r` dimensions `[I, J, ..., L, M, N]`. The output tensor\n has rank `r+1` with shape `[I, J, ..., L, M, num_rows, num_cols]` when only\n one diagonal is given (`k` is an integer or `k[0] == k[1]`). Otherwise, it has\n rank `r` with shape `[I, J, ..., L, num_rows, num_cols]`.\n\n The second innermost dimension of `diagonal` has double meaning. When `k` is\n scalar or `k[0] == k[1]`, `M` is part of the batch size [I, J, ..., M], and\n the output tensor is:\n\n ```\n output[i, j, ..., l, m, n]\n = diagonal[i, j, ..., l, n-max(d_upper, 0)] ; if n - m == d_upper\n padding_value ; otherwise\n ```\n\n Otherwise, `M` is treated as the number of diagonals for the matrix in the\n same batch (`M = k[1]-k[0]+1`), and the output tensor is:\n\n ```\n output[i, j, ..., l, m, n]\n = diagonal[i, j, ..., l, diag_index, index_in_diag] ; if k[0] <= d <= k[1]\n padding_value ; otherwise\n ```\n where `d = n - m`, `diag_index = k[1] - d`, and\n `index_in_diag = n - max(d, 0) + offset`.\n\n `offset` is zero except when the alignment of the diagonal is to the right.\n ```\n offset = max_diag_len - diag_len(d) ; if (`align` in {RIGHT_LEFT, RIGHT_RIGHT}\n and `d >= 0`) or\n (`align` in {LEFT_RIGHT, RIGHT_RIGHT}\n and `d <= 0`)\n 0 ; otherwise\n ```\n where `diag_len(d) = min(cols - max(d, 0), rows + min(d, 0))`.\n\n For example:\n\n ```\n # The main diagonal.\n diagonal = np.array([[1, 2, 3, 4], # Input shape: (2, 4)\n [5, 6, 7, 8]])\n tf.matrix_diag(diagonal) ==> [[[1, 0, 0, 0], # Output shape: (2, 4, 4)\n [0, 2, 0, 0],\n [0, 0, 3, 0],\n [0, 0, 0, 4]],\n [[5, 0, 0, 0],\n [0, 6, 0, 0],\n [0, 0, 7, 0],\n [0, 0, 0, 8]]]\n\n # A superdiagonal (per batch).\n diagonal = np.array([[1, 2, 3], # Input shape: (2, 3)\n [4, 5, 6]])\n tf.matrix_diag(diagonal, k = 1)\n ==> [[[0, 1, 0, 0], # Output shape: (2, 4, 4)\n [0, 0, 2, 0],\n [0, 0, 0, 3],\n [0, 0, 0, 0]],\n [[0, 4, 0, 0],\n [0, 0, 5, 0],\n [0, 0, 0, 6],\n [0, 0, 0, 0]]]\n\n # A tridiagonal band (per batch).\n diagonals = np.array([[[8, 9, 0], # Input shape: (2, 2, 3)\n [1, 2, 3],\n [0, 4, 5]],\n [[2, 3, 0],\n [6, 7, 9],\n [0, 9, 1]]])\n tf.matrix_diag(diagonals, k = (-1, 1))\n ==> [[[1, 8, 0], # Output shape: (2, 3, 3)\n [4, 2, 9],\n [0, 5, 3]],\n [[6, 2, 0],\n [9, 7, 3],\n [0, 1, 9]]]\n\n # RIGHT_LEFT alignment.\n diagonals = np.array([[[0, 8, 9], # Input shape: (2, 2, 3)\n [1, 2, 3],\n [4, 5, 0]],\n [[0, 2, 3],\n [6, 7, 9],\n [9, 1, 0]]])\n tf.matrix_diag(diagonals, k = (-1, 1), align=\"RIGHT_LEFT\")\n ==> [[[1, 8, 0], # Output shape: (2, 3, 3)\n [4, 2, 9],\n [0, 5, 3]],\n [[6, 2, 0],\n [9, 7, 3],\n [0, 1, 9]]]\n\n # Rectangular matrix.\n diagonal = np.array([1, 2]) # Input shape: (2)\n tf.matrix_diag(diagonal, k = -1, num_rows = 3, num_cols = 4)\n ==> [[0, 0, 0, 0], # Output shape: (3, 4)\n [1, 0, 0, 0],\n [0, 2, 0, 0]]\n\n # Rectangular matrix with inferred num_cols and padding_value = 9.\n tf.matrix_diag(diagonal, k = -1, num_rows = 3, padding_value = 9)\n ==> [[9, 9], # Output shape: (3, 2)\n [1, 9],\n [9, 2]]\n ```\n\n Args:\n diagonal: A `Tensor` with `rank k >= 1`.\n name: A name for the operation (optional).\n k: Diagonal offset(s). Positive value means superdiagonal, 0 refers to the\n main diagonal, and negative value means subdiagonals. `k` can be a single\n integer (for a single diagonal) or a pair of integers specifying the low\n and high ends of a matrix band. `k[0]` must not be larger than `k[1]`.\n num_rows: The number of rows of the output matrix. If it is not provided,\n the op assumes the output matrix is a square matrix and infers the matrix\n size from `d_lower`, `d_upper`, and the innermost dimension of `diagonal`.\n num_cols: The number of columns of the output matrix. If it is not provided,\n the op assumes the output matrix is a square matrix and infers the matrix\n size from `d_lower`, `d_upper`, and the innermost dimension of `diagonal`.\n padding_value: The value to fill the area outside the specified diagonal\n band with. Default is 0.\n align: Some diagonals are shorter than `max_diag_len` and need to be padded.\n `align` is a string specifying how superdiagonals and subdiagonals should\n be aligned, respectively. There are four possible alignments: \"RIGHT_LEFT\"\n (default), \"LEFT_RIGHT\", \"LEFT_LEFT\", and \"RIGHT_RIGHT\". \"RIGHT_LEFT\"\n aligns superdiagonals to the right (left-pads the row) and subdiagonals to\n the left (right-pads the row). It is the packing format LAPACK uses.\n cuSPARSE uses \"LEFT_RIGHT\", which is the opposite alignment.\n\n Returns:\n A Tensor. Has the same type as `diagonal`.\n \"\"\"\n # Special case to sidestep the tf.constant conversion error:\n # TypeError: Expected bool, got 0 of type 'int' instead.\n if hasattr(diagonal, \"dtype\") and diagonal.dtype == \"bool\":\n padding_value = bool(padding_value)\n\n return gen_array_ops.matrix_diag_v3(\n diagonal=diagonal,\n k=k,\n num_rows=num_rows,\n num_cols=num_cols,\n padding_value=padding_value,\n align=align,\n name=name)\n\n\n@tf_export(\"linalg.diag_part\", v1=[\"linalg.diag_part\", \"matrix_diag_part\"])\[email protected]_dispatch_support\[email protected]_endpoints(\"matrix_diag_part\")\ndef matrix_diag_part(\n input, # pylint:disable=redefined-builtin\n name=\"diag_part\",\n k=0,\n padding_value=0,\n align=\"RIGHT_LEFT\"):\n \"\"\"Returns the batched diagonal part of a batched tensor.\n\n Returns a tensor with the `k[0]`-th to `k[1]`-th diagonals of the batched\n `input`.\n\n Assume `input` has `r` dimensions `[I, J, ..., L, M, N]`.\n Let `max_diag_len` be the maximum length among all diagonals to be extracted,\n `max_diag_len = min(M + min(k[1], 0), N + min(-k[0], 0))`\n Let `num_diags` be the number of diagonals to extract,\n `num_diags = k[1] - k[0] + 1`.\n\n If `num_diags == 1`, the output tensor is of rank `r - 1` with shape\n `[I, J, ..., L, max_diag_len]` and values:\n\n ```\n diagonal[i, j, ..., l, n]\n = input[i, j, ..., l, n+y, n+x] ; if 0 <= n+y < M and 0 <= n+x < N,\n padding_value ; otherwise.\n ```\n where `y = max(-k[1], 0)`, `x = max(k[1], 0)`.\n\n Otherwise, the output tensor has rank `r` with dimensions\n `[I, J, ..., L, num_diags, max_diag_len]` with values:\n\n ```\n diagonal[i, j, ..., l, m, n]\n = input[i, j, ..., l, n+y, n+x] ; if 0 <= n+y < M and 0 <= n+x < N,\n padding_value ; otherwise.\n ```\n where `d = k[1] - m`, `y = max(-d, 0) - offset`, and `x = max(d, 0) - offset`.\n\n `offset` is zero except when the alignment of the diagonal is to the right.\n ```\n offset = max_diag_len - diag_len(d) ; if (`align` in {RIGHT_LEFT, RIGHT_RIGHT}\n and `d >= 0`) or\n (`align` in {LEFT_RIGHT, RIGHT_RIGHT}\n and `d <= 0`)\n 0 ; otherwise\n ```\n where `diag_len(d) = min(cols - max(d, 0), rows + min(d, 0))`.\n\n The input must be at least a matrix.\n\n For example:\n\n ```\n input = np.array([[[1, 2, 3, 4], # Input shape: (2, 3, 4)\n [5, 6, 7, 8],\n [9, 8, 7, 6]],\n [[5, 4, 3, 2],\n [1, 2, 3, 4],\n [5, 6, 7, 8]]])\n\n # A main diagonal from each batch.\n tf.linalg.diag_part(input) ==> [[1, 6, 7], # Output shape: (2, 3)\n [5, 2, 7]]\n\n # A superdiagonal from each batch.\n tf.linalg.diag_part(input, k = 1)\n ==> [[2, 7, 6], # Output shape: (2, 3)\n [4, 3, 8]]\n\n # A band from each batch.\n tf.linalg.diag_part(input, k = (-1, 2))\n ==> [[[3, 8, 0], # Output shape: (2, 4, 3)\n [2, 7, 6],\n [1, 6, 7],\n [0, 5, 8]],\n [[3, 4, 0],\n [4, 3, 8],\n [5, 2, 7],\n [0, 1, 6]]]\n\n # RIGHT_LEFT alignment.\n tf.linalg.diag_part(input, k = (-1, 2), align=\"RIGHT_LEFT\")\n ==> [[[0, 3, 8], # Output shape: (2, 4, 3)\n [2, 7, 6],\n [1, 6, 7],\n [5, 8, 0]],\n [[0, 3, 4],\n [4, 3, 8],\n [5, 2, 7],\n [1, 6, 0]]]\n\n # max_diag_len can be shorter than the main diagonal.\n tf.linalg.diag_part(input, k = (-2, -1))\n ==> [[[5, 8],\n [0, 9]],\n [[1, 6],\n [0, 5]]]\n\n # padding_value = 9\n tf.linalg.diag_part(input, k = (1, 3), padding_value = 9)\n ==> [[[4, 9, 9], # Output shape: (2, 3, 3)\n [3, 8, 9],\n [2, 7, 6]],\n [[2, 9, 9],\n [3, 4, 9],\n [4, 3, 8]]]\n\n ```\n\n Args:\n input: A `Tensor` with `rank k >= 2`.\n name: A name for the operation (optional).\n k: Diagonal offset(s). Positive value means superdiagonal, 0 refers to the\n main diagonal, and negative value means subdiagonals. `k` can be a single\n integer (for a single diagonal) or a pair of integers specifying the low\n and high ends of a matrix band. `k[0]` must not be larger than `k[1]`.\n padding_value: The value to fill the area outside the specified diagonal\n band with. Default is 0.\n align: Some diagonals are shorter than `max_diag_len` and need to be padded.\n `align` is a string specifying how superdiagonals and subdiagonals should\n be aligned, respectively. There are four possible alignments: \"RIGHT_LEFT\"\n (default), \"LEFT_RIGHT\", \"LEFT_LEFT\", and \"RIGHT_RIGHT\". \"RIGHT_LEFT\"\n aligns superdiagonals to the right (left-pads the row) and subdiagonals to\n the left (right-pads the row). It is the packing format LAPACK uses.\n cuSPARSE uses \"LEFT_RIGHT\", which is the opposite alignment.\n\n Returns:\n A Tensor containing diagonals of `input`. Has the same type as `input`.\n \"\"\"\n # Special case to sidestep the tf.constant conversion error:\n # TypeError: Expected bool, got 0 of type 'int' instead.\n if hasattr(input, \"dtype\") and input.dtype == \"bool\":\n padding_value = bool(padding_value)\n\n return gen_array_ops.matrix_diag_part_v3(\n input=input, k=k, padding_value=padding_value, align=align, name=name)\n\n\n@tf_export(\n \"linalg.tensor_diag_part\", v1=[\"linalg.tensor_diag_part\", \"diag_part\"])\[email protected]_dispatch_support\[email protected]_endpoints(\"diag_part\")\ndef tensor_diag_part(\n input, # pylint:disable=redefined-builtin\n name=None):\n \"\"\"Returns the diagonal part of the tensor.\n\n This operation returns a tensor with the `diagonal` part\n of the `input`. The `diagonal` part is computed as follows:\n\n Assume `input` has dimensions `[D1,..., Dk, D1,..., Dk]`, then the output is a\n tensor of rank `k` with dimensions `[D1,..., Dk]` where:\n\n `diagonal[i1,..., ik] = input[i1, ..., ik, i1,..., ik]`.\n\n For a rank 2 tensor, `linalg.diag_part` and `linalg.tensor_diag_part`\n produce the same result. For rank 3 and higher, linalg.diag_part extracts\n the diagonal of each inner-most matrix in the tensor. An example where\n they differ is given below.\n\n >>> x = [[[[1111,1112],[1121,1122]],\n ... [[1211,1212],[1221,1222]]],\n ... [[[2111, 2112], [2121, 2122]],\n ... [[2211, 2212], [2221, 2222]]]\n ... ]\n >>> tf.linalg.tensor_diag_part(x)\n <tf.Tensor: shape=(2, 2), dtype=int32, numpy=\n array([[1111, 1212],\n [2121, 2222]], dtype=int32)>\n >>> tf.linalg.diag_part(x).shape\n TensorShape([2, 2, 2])\n\n Args:\n input: A `Tensor` with rank `2k`.\n name: A name for the operation (optional).\n\n Returns:\n A Tensor containing diagonals of `input`. Has the same type as `input`, and\n rank `k`.\n \"\"\"\n return gen_array_ops.diag_part(input=input, name=name)\n\n\n@tf_export(\"linalg.set_diag\", v1=[\"linalg.set_diag\", \"matrix_set_diag\"])\[email protected]_dispatch_support\[email protected]_endpoints(\"matrix_set_diag\")\ndef matrix_set_diag(\n input, # pylint:disable=redefined-builtin\n diagonal,\n name=\"set_diag\",\n k=0,\n align=\"RIGHT_LEFT\"):\n \"\"\"Returns a batched matrix tensor with new batched diagonal values.\n\n Given `input` and `diagonal`, this operation returns a tensor with the\n same shape and values as `input`, except for the specified diagonals of the\n innermost matrices. These will be overwritten by the values in `diagonal`.\n\n `input` has `r+1` dimensions `[I, J, ..., L, M, N]`. When `k` is scalar or\n `k[0] == k[1]`, `diagonal` has `r` dimensions `[I, J, ..., L, max_diag_len]`.\n Otherwise, it has `r+1` dimensions `[I, J, ..., L, num_diags, max_diag_len]`.\n `num_diags` is the number of diagonals, `num_diags = k[1] - k[0] + 1`.\n `max_diag_len` is the longest diagonal in the range `[k[0], k[1]]`,\n `max_diag_len = min(M + min(k[1], 0), N + min(-k[0], 0))`\n\n The output is a tensor of rank `k+1` with dimensions `[I, J, ..., L, M, N]`.\n If `k` is scalar or `k[0] == k[1]`:\n\n ```\n output[i, j, ..., l, m, n]\n = diagonal[i, j, ..., l, n-max(k[1], 0)] ; if n - m == k[1]\n input[i, j, ..., l, m, n] ; otherwise\n ```\n\n Otherwise,\n\n ```\n output[i, j, ..., l, m, n]\n = diagonal[i, j, ..., l, diag_index, index_in_diag] ; if k[0] <= d <= k[1]\n input[i, j, ..., l, m, n] ; otherwise\n ```\n where `d = n - m`, `diag_index = k[1] - d`, and\n `index_in_diag = n - max(d, 0) + offset`.\n\n `offset` is zero except when the alignment of the diagonal is to the right.\n ```\n offset = max_diag_len - diag_len(d) ; if (`align` in {RIGHT_LEFT, RIGHT_RIGHT}\n and `d >= 0`) or\n (`align` in {LEFT_RIGHT, RIGHT_RIGHT}\n and `d <= 0`)\n 0 ; otherwise\n ```\n where `diag_len(d) = min(cols - max(d, 0), rows + min(d, 0))`.\n\n For example:\n\n ```\n # The main diagonal.\n input = np.array([[[7, 7, 7, 7], # Input shape: (2, 3, 4)\n [7, 7, 7, 7],\n [7, 7, 7, 7]],\n [[7, 7, 7, 7],\n [7, 7, 7, 7],\n [7, 7, 7, 7]]])\n diagonal = np.array([[1, 2, 3], # Diagonal shape: (2, 3)\n [4, 5, 6]])\n tf.matrix_set_diag(input, diagonal)\n ==> [[[1, 7, 7, 7], # Output shape: (2, 3, 4)\n [7, 2, 7, 7],\n [7, 7, 3, 7]],\n [[4, 7, 7, 7],\n [7, 5, 7, 7],\n [7, 7, 6, 7]]]\n\n # A superdiagonal (per batch).\n tf.matrix_set_diag(input, diagonal, k = 1)\n ==> [[[7, 1, 7, 7], # Output shape: (2, 3, 4)\n [7, 7, 2, 7],\n [7, 7, 7, 3]],\n [[7, 4, 7, 7],\n [7, 7, 5, 7],\n [7, 7, 7, 6]]]\n\n # A band of diagonals.\n diagonals = np.array([[[9, 1, 0], # Diagonal shape: (2, 4, 3)\n [6, 5, 8],\n [1, 2, 3],\n [0, 4, 5]],\n [[1, 2, 0],\n [5, 6, 4],\n [6, 1, 2],\n [0, 3, 4]]])\n tf.matrix_set_diag(input, diagonals, k = (-1, 2))\n ==> [[[1, 6, 9, 7], # Output shape: (2, 3, 4)\n [4, 2, 5, 1],\n [7, 5, 3, 8]],\n [[6, 5, 1, 7],\n [3, 1, 6, 2],\n [7, 4, 2, 4]]]\n\n # RIGHT_LEFT alignment.\n diagonals = np.array([[[0, 9, 1], # Diagonal shape: (2, 4, 3)\n [6, 5, 8],\n [1, 2, 3],\n [4, 5, 0]],\n [[0, 1, 2],\n [5, 6, 4],\n [6, 1, 2],\n [3, 4, 0]]])\n tf.matrix_set_diag(input, diagonals, k = (-1, 2), align=\"RIGHT_LEFT\")\n ==> [[[1, 6, 9, 7], # Output shape: (2, 3, 4)\n [4, 2, 5, 1],\n [7, 5, 3, 8]],\n [[6, 5, 1, 7],\n [3, 1, 6, 2],\n [7, 4, 2, 4]]]\n\n ```\n\n Args:\n input: A `Tensor` with rank `k + 1`, where `k >= 1`.\n diagonal: A `Tensor` with rank `k`, when `d_lower == d_upper`, or `k + 1`,\n otherwise. `k >= 1`.\n name: A name for the operation (optional).\n k: Diagonal offset(s). Positive value means superdiagonal, 0 refers to the\n main diagonal, and negative value means subdiagonals. `k` can be a single\n integer (for a single diagonal) or a pair of integers specifying the low\n and high ends of a matrix band. `k[0]` must not be larger than `k[1]`.\n align: Some diagonals are shorter than `max_diag_len` and need to be padded.\n `align` is a string specifying how superdiagonals and subdiagonals should\n be aligned, respectively. There are four possible alignments: \"RIGHT_LEFT\"\n (default), \"LEFT_RIGHT\", \"LEFT_LEFT\", and \"RIGHT_RIGHT\". \"RIGHT_LEFT\"\n aligns superdiagonals to the right (left-pads the row) and subdiagonals to\n the left (right-pads the row). It is the packing format LAPACK uses.\n cuSPARSE uses \"LEFT_RIGHT\", which is the opposite alignment.\n \"\"\"\n return gen_array_ops.matrix_set_diag_v3(\n input=input, diagonal=diagonal, k=k, align=align, name=name)\n\n\n# pylint: enable=invalid-name\n\n\ndef _constant_if_small(value, shape, dtype, name):\n try:\n if np.prod(shape) < 1000:\n return constant(value, shape=shape, dtype=dtype, name=name)\n except TypeError:\n # Happens when shape is a Tensor, list with Tensor elements, etc.\n pass\n return None\n\n\ndef _tag_zeros_tensor(fun):\n \"\"\" Tags the result of function by setting _is_zeros_tensor attribute.\n\n This is useful to compute Hessians of fused ops such as cross_entropy.\n \"\"\"\n\n def wrapped(*args, **kwargs):\n tensor = fun(*args, **kwargs)\n tensor._is_zeros_tensor = True\n return tensor\n\n return tf_decorator.make_decorator(fun, wrapped)\n\n\n@tf_export(\"zeros\")\[email protected]_dispatch_support\n@_tag_zeros_tensor\ndef zeros(shape, dtype=dtypes.float32, name=None):\n \"\"\"Creates a tensor with all elements set to zero.\n\n See also `tf.zeros_like`, `tf.ones`, `tf.fill`, `tf.eye`.\n\n This operation returns a tensor of type `dtype` with shape `shape` and\n all elements set to zero.\n\n >>> tf.zeros([3, 4], tf.int32)\n <tf.Tensor: shape=(3, 4), dtype=int32, numpy=\n array([[0, 0, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 0, 0]], dtype=int32)>\n\n Args:\n shape: A `list` of integers, a `tuple` of integers, or\n a 1-D `Tensor` of type `int32`.\n dtype: The DType of an element in the resulting `Tensor`.\n name: Optional string. A name for the operation.\n\n Returns:\n A `Tensor` with all elements set to zero.\n \"\"\"\n dtype = dtypes.as_dtype(dtype).base_dtype\n with ops.name_scope(name, \"zeros\", [shape]) as name:\n if dtype == dtypes.bool:\n zero = False\n elif dtype == dtypes.string:\n zero = \"\"\n elif dtype.is_quantized:\n zero = np.zeros([]).astype(dtype.as_numpy_dtype)\n else:\n zero = 0\n\n if not isinstance(shape, ops.Tensor):\n try:\n if not context.executing_eagerly():\n # Create a constant if it won't be very big. Otherwise create a fill\n # op to prevent serialized GraphDefs from becoming too large.\n output = _constant_if_small(zero, shape, dtype, name)\n if output is not None:\n return output\n\n # Go through tensor shapes to get int64-if-needed semantics\n shape = constant_op._tensor_shape_tensor_conversion_function(\n tensor_shape.TensorShape(shape))\n except (TypeError, ValueError):\n # Happens when shape is a list with tensor elements\n shape = ops.convert_to_tensor(shape, dtype=dtypes.int32)\n if not shape._shape_tuple():\n shape = reshape(shape, [-1]) # Ensure it's a vector\n output = fill(shape, constant(zero, dtype=dtype), name=name)\n assert output.dtype.base_dtype == dtype\n return output\n\n\n@tf_export(v1=[\"zeros_like\"])\[email protected]_dispatch_support\ndef zeros_like(tensor, dtype=None, name=None, optimize=True):\n \"\"\"Creates a tensor with all elements set to zero.\n\n See also `tf.zeros`.\n\n Given a single tensor (`tensor`), this operation returns a tensor of the\n same type and shape as `tensor` with all elements set to zero. Optionally,\n you can use `dtype` to specify a new type for the returned tensor.\n\n Examples:\n\n >>> tensor = tf.constant([[1, 2, 3], [4, 5, 6]])\n >>> tf.zeros_like(tensor)\n <tf.Tensor: shape=(2, 3), dtype=int32, numpy=\n array([[0, 0, 0],\n [0, 0, 0]], dtype=int32)>\n\n >>> tf.zeros_like(tensor, dtype=tf.float32)\n <tf.Tensor: shape=(2, 3), dtype=float32, numpy=\n array([[0., 0., 0.],\n [0., 0., 0.]], dtype=float32)>\n\n Args:\n tensor: A `Tensor`.\n dtype: A type for the returned `Tensor`. Must be `float16`, `float32`,\n `float64`, `int8`, `uint8`, `int16`, `uint16`, `int32`, `int64`,\n `complex64`, `complex128`, `bool` or `string`. (optional)\n name: A name for the operation (optional).\n optimize: if `True`, attempt to statically determine the shape of `tensor`\n and encode it as a constant. (optional, defaults to `True`)\n\n Returns:\n A `Tensor` with all elements set to zero.\n \"\"\"\n return zeros_like_impl(tensor, dtype, name, optimize)\n\n\n@tf_export(\"zeros_like\", v1=[])\[email protected]_dispatch_support\ndef zeros_like_v2(\n input, # pylint: disable=redefined-builtin\n dtype=None,\n name=None):\n \"\"\"Creates a tensor with all elements set to zero.\n\n See also `tf.zeros`.\n\n Given a single tensor or array-like object (`input`), this operation returns\n a tensor of the same type and shape as `input` with all elements set to zero.\n Optionally, you can use `dtype` to specify a new type for the returned tensor.\n\n Examples:\n\n >>> tensor = tf.constant([[1, 2, 3], [4, 5, 6]])\n >>> tf.zeros_like(tensor)\n <tf.Tensor: shape=(2, 3), dtype=int32, numpy=\n array([[0, 0, 0],\n [0, 0, 0]], dtype=int32)>\n\n >>> tf.zeros_like(tensor, dtype=tf.float32)\n <tf.Tensor: shape=(2, 3), dtype=float32, numpy=\n array([[0., 0., 0.],\n [0., 0., 0.]], dtype=float32)>\n\n >>> tf.zeros_like([[1, 2, 3], [4, 5, 6]])\n <tf.Tensor: shape=(2, 3), dtype=int32, numpy=\n array([[0, 0, 0],\n [0, 0, 0]], dtype=int32)>\n\n Args:\n input: A `Tensor` or array-like object.\n dtype: A type for the returned `Tensor`. Must be `float16`, `float32`,\n `float64`, `int8`, `uint8`, `int16`, `uint16`, `int32`, `int64`,\n `complex64`, `complex128`, `bool` or `string` (optional).\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` with all elements set to zero.\n \"\"\"\n return zeros_like_impl(input, dtype, name, optimize=True)\n\n\n@_tag_zeros_tensor\ndef zeros_like_impl(tensor, dtype, name, optimize=True):\n \"\"\"Internal implementation for the v1/v2 zeros_like API calls.\"\"\"\n with ops.name_scope(name, \"zeros_like\", [tensor]) as name:\n if not tensor_util.is_tf_type(tensor):\n tensor = ops.convert_to_tensor(tensor, name=\"tensor\")\n tensor_shape = tensor.shape\n tensor_dtype = tensor.dtype\n\n if context.executing_eagerly():\n if dtype is not None and dtype != tensor_dtype:\n return zeros(\n shape_internal(tensor, optimize=optimize), dtype=dtype, name=name)\n return gen_array_ops.zeros_like(tensor, name=name)\n\n # For now, variant types must be created via zeros_like; as we need to\n # pass the input variant object to the proper zeros callback.\n\n if (optimize and tensor_shape.is_fully_defined() and\n tensor_dtype != dtypes.variant):\n # We can produce a zeros tensor independent of the value of 'tensor',\n # since the shape is known statically.\n return zeros(tensor_shape, dtype=dtype or tensor_dtype, name=name)\n\n if dtype is not None and dtype != tensor_dtype and dtype != dtypes.variant:\n return zeros(\n shape_internal(tensor, optimize=optimize), dtype=dtype, name=name)\n else:\n return gen_array_ops.zeros_like(tensor, name=name)\n\n\n@tf_export(v1=[\"ones_like\"])\[email protected]_dispatch_support\ndef ones_like(tensor, dtype=None, name=None, optimize=True):\n \"\"\"Creates a tensor with all elements set to 1.\n\n See also `tf.ones`.\n\n Given a single tensor (`tensor`), this operation returns a tensor of the same\n type and shape as `tensor` with all elements set to 1. Optionally, you can\n specify a new type (`dtype`) for the returned tensor.\n\n For example:\n\n ```python\n tensor = tf.constant([[1, 2, 3], [4, 5, 6]])\n tf.ones_like(tensor) # [[1, 1, 1], [1, 1, 1]]\n ```\n\n Args:\n tensor: A `Tensor`.\n dtype: A type for the returned `Tensor`. Must be `float32`, `float64`,\n `int8`, `uint8`, `int16`, `uint16`, `int32`, `int64`, `complex64`,\n `complex128` or `bool`.\n name: A name for the operation (optional).\n optimize: if true, attempt to statically determine the shape of 'tensor' and\n encode it as a constant.\n\n Returns:\n A `Tensor` with all elements set to 1.\n \"\"\"\n return ones_like_impl(tensor, dtype, name, optimize)\n\n\n@tf_export(\"ones_like\", v1=[])\[email protected]_dispatch_support\ndef ones_like_v2(\n input, # pylint: disable=redefined-builtin\n dtype=None,\n name=None):\n \"\"\"Creates a tensor of all ones that has the same shape as the input.\n\n See also `tf.ones`.\n\n Given a single tensor (`tensor`), this operation returns a tensor of the\n same type and shape as `tensor` with all elements set to 1. Optionally,\n you can use `dtype` to specify a new type for the returned tensor.\n\n For example:\n\n >>> tensor = tf.constant([[1, 2, 3], [4, 5, 6]])\n >>> tf.ones_like(tensor)\n <tf.Tensor: shape=(2, 3), dtype=int32, numpy=\n array([[1, 1, 1],\n [1, 1, 1]], dtype=int32)>\n\n Args:\n input: A `Tensor`.\n dtype: A type for the returned `Tensor`. Must be `float16`, `float32`,\n `float64`, `int8`, `uint8`, `int16`, `uint16`, `int32`, `int64`,\n `complex64`, `complex128`, `bool` or `string`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` with all elements set to one.\n \"\"\"\n return ones_like_impl(input, dtype, name, optimize=True)\n\n\ndef ones_like_impl(tensor, dtype, name, optimize=True):\n \"\"\"Internal implementation for the v1/v2 ones_like API calls.\"\"\"\n with ops.name_scope(name, \"ones_like\", [tensor]) as name:\n tensor = ops.convert_to_tensor(tensor, name=\"tensor\")\n ones_shape = shape_internal(tensor, optimize=optimize)\n if dtype is None:\n dtype = tensor.dtype\n ret = ones(ones_shape, dtype=dtype, name=name)\n if not context.executing_eagerly():\n ret.set_shape(tensor.get_shape())\n return ret\n\n\n@tf_export(\"ones\")\[email protected]_dispatch_support\ndef ones(shape, dtype=dtypes.float32, name=None):\n \"\"\"Creates a tensor with all elements set to one (1).\n\n See also `tf.ones_like`, `tf.zeros`, `tf.fill`, `tf.eye`.\n\n This operation returns a tensor of type `dtype` with shape `shape` and\n all elements set to one.\n\n >>> tf.ones([3, 4], tf.int32)\n <tf.Tensor: shape=(3, 4), dtype=int32, numpy=\n array([[1, 1, 1, 1],\n [1, 1, 1, 1],\n [1, 1, 1, 1]], dtype=int32)>\n\n Args:\n shape: A `list` of integers, a `tuple` of integers, or\n a 1-D `Tensor` of type `int32`.\n dtype: Optional DType of an element in the resulting `Tensor`. Default is\n `tf.float32`.\n name: Optional string. A name for the operation.\n\n Returns:\n A `Tensor` with all elements set to one (1).\n \"\"\"\n dtype = dtypes.as_dtype(dtype).base_dtype\n with ops.name_scope(name, \"ones\", [shape]) as name:\n if dtype == dtypes.bool:\n one = True\n elif dtype.is_quantized:\n one = np.ones([]).astype(dtype.as_numpy_dtype)\n else:\n one = 1\n if not isinstance(shape, ops.Tensor):\n try:\n if not context.executing_eagerly():\n # Create a constant if it won't be very big. Otherwise create a fill\n # op to prevent serialized GraphDefs from becoming too large.\n output = _constant_if_small(one, shape, dtype, name)\n if output is not None:\n return output\n\n # Go through tensor shapes to get int64-if-needed semantics\n shape = constant_op._tensor_shape_tensor_conversion_function(\n tensor_shape.TensorShape(shape))\n except (TypeError, ValueError):\n # Happens when shape is a list with tensor elements\n shape = ops.convert_to_tensor(shape, dtype=dtypes.int32)\n if not shape._shape_tuple():\n shape = reshape(shape, [-1]) # Ensure it's a vector\n output = fill(shape, constant(one, dtype=dtype), name=name)\n assert output.dtype.base_dtype == dtype\n return output\n\n\n@tf_export(v1=[\"placeholder\"])\ndef placeholder(dtype, shape=None, name=None):\n \"\"\"Inserts a placeholder for a tensor that will be always fed.\n\n **Important**: This tensor will produce an error if evaluated. Its value must\n be fed using the `feed_dict` optional argument to `Session.run()`,\n `Tensor.eval()`, or `Operation.run()`.\n\n For example:\n\n ```python\n x = tf.compat.v1.placeholder(tf.float32, shape=(1024, 1024))\n y = tf.matmul(x, x)\n\n with tf.compat.v1.Session() as sess:\n print(sess.run(y)) # ERROR: will fail because x was not fed.\n\n rand_array = np.random.rand(1024, 1024)\n print(sess.run(y, feed_dict={x: rand_array})) # Will succeed.\n ```\n\n @compatibility(eager)\n Placeholders are not compatible with eager execution.\n @end_compatibility\n\n Args:\n dtype: The type of elements in the tensor to be fed.\n shape: The shape of the tensor to be fed (optional). If the shape is not\n specified, you can feed a tensor of any shape.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor` that may be used as a handle for feeding a value, but not\n evaluated directly.\n\n Raises:\n RuntimeError: if eager execution is enabled\n \"\"\"\n if context.executing_eagerly():\n raise RuntimeError(\"tf.placeholder() is not compatible with \"\n \"eager execution.\")\n\n return gen_array_ops.placeholder(dtype=dtype, shape=shape, name=name)\n\n\n@tf_export(v1=[\"placeholder_with_default\"])\ndef placeholder_with_default(input, shape, name=None): # pylint: disable=redefined-builtin\n \"\"\"A placeholder op that passes through `input` when its output is not fed.\n\n Args:\n input: A `Tensor`. The default value to produce when output is not fed.\n shape: A `tf.TensorShape` or list of `int`s. The (possibly partial) shape of\n the tensor.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor`. Has the same type as `input`.\n \"\"\"\n return gen_array_ops.placeholder_with_default(input, shape, name)\n\n\n@tf_export(v1=[\"sparse.placeholder\", \"sparse_placeholder\"])\[email protected]_endpoints(\"sparse_placeholder\")\ndef sparse_placeholder(dtype, shape=None, name=None):\n \"\"\"Inserts a placeholder for a sparse tensor that will be always fed.\n\n **Important**: This sparse tensor will produce an error if evaluated.\n Its value must be fed using the `feed_dict` optional argument to\n `Session.run()`, `Tensor.eval()`, or `Operation.run()`.\n\n For example:\n\n ```python\n x = tf.compat.v1.sparse.placeholder(tf.float32)\n y = tf.sparse.reduce_sum(x)\n\n with tf.compat.v1.Session() as sess:\n print(sess.run(y)) # ERROR: will fail because x was not fed.\n\n indices = np.array([[3, 2, 0], [4, 5, 1]], dtype=np.int64)\n values = np.array([1.0, 2.0], dtype=np.float32)\n shape = np.array([7, 9, 2], dtype=np.int64)\n print(sess.run(y, feed_dict={\n x: tf.compat.v1.SparseTensorValue(indices, values, shape)})) # Will\n succeed.\n print(sess.run(y, feed_dict={\n x: (indices, values, shape)})) # Will succeed.\n\n sp = tf.sparse.SparseTensor(indices=indices, values=values,\n dense_shape=shape)\n sp_value = sp.eval(session=sess)\n print(sess.run(y, feed_dict={x: sp_value})) # Will succeed.\n ```\n\n @compatibility{eager} Placeholders are not compatible with eager execution.\n\n Args:\n dtype: The type of `values` elements in the tensor to be fed.\n shape: The shape of the tensor to be fed (optional). If the shape is not\n specified, you can feed a sparse tensor of any shape.\n name: A name for prefixing the operations (optional).\n\n Returns:\n A `SparseTensor` that may be used as a handle for feeding a value, but not\n evaluated directly.\n\n Raises:\n RuntimeError: if eager execution is enabled\n \"\"\"\n if context.executing_eagerly():\n raise RuntimeError(\"`sparse_placeholder` is not compatible with \"\n \"eager execution.\")\n\n shape_name = (name + \"/shape\") if name is not None else None\n default_shape_name = (name + \"/shape_default\") if name is not None else None\n if shape is None:\n rank = None\n dense_shape = placeholder(dtypes.int64, shape=[rank], name=shape_name)\n dense_shape_default = tensor_util.constant_value_as_shape(dense_shape)\n else:\n if isinstance(shape, ops.Tensor):\n rank = shape.get_shape()[0]\n dense_shape_default = tensor_util.constant_value_as_shape(shape)\n else:\n rank = len(shape)\n # determine the shape, to override the `.shape` property of the\n # `SparseTensor`\n dense_shape_default = tensor_shape.TensorShape(\n tuple(None if dim == -1 else dim for dim in shape))\n shape = tuple(tensor_shape.dimension_value(dim) for dim in shape)\n shape = tuple(-1 if dim is None else dim for dim in shape)\n shape = ops.convert_to_tensor(\n shape, dtype=dtypes.int64, name=default_shape_name)\n\n # `dense_shape` needs to be feedable (for users that treat this as an\n # actual placeholder). `constant_value_as_shape` sets constants to\n # not-feedable. placeholder_with_default works, but blocks `SparseTensor`\n # from reading the default value back out.\n dense_shape = placeholder_with_default(\n shape, shape=shape.shape, name=shape_name)\n\n result = sparse_tensor.SparseTensor(\n values=placeholder(\n dtype,\n shape=[None],\n name=(name + \"/values\") if name is not None else None),\n indices=placeholder(\n dtypes.int64,\n shape=[None, rank],\n name=(name + \"/indices\") if name is not None else None),\n dense_shape=dense_shape)\n\n # Now the SparseTensor.shape is a list of `None`s, since it couldn't read the\n # default shape out of the placeholder. Override that\n # shape to be the value determined here, so partial shapes can be\n # propagated.\n result._dense_shape_default = dense_shape_default\n return result\n\n# pylint: enable=redefined-outer-name\n\n\n@tf_export(\"pad\", v1=[])\[email protected]_dispatch_support\ndef pad_v2(tensor, paddings, mode=\"CONSTANT\", constant_values=0, name=None):\n \"\"\"Pads a tensor.\n\n This operation pads a `tensor` according to the `paddings` you specify.\n `paddings` is an integer tensor with shape `[n, 2]`, where n is the rank of\n `tensor`. For each dimension D of `input`, `paddings[D, 0]` indicates how\n many values to add before the contents of `tensor` in that dimension, and\n `paddings[D, 1]` indicates how many values to add after the contents of\n `tensor` in that dimension. If `mode` is \"REFLECT\" then both `paddings[D, 0]`\n and `paddings[D, 1]` must be no greater than `tensor.dim_size(D) - 1`. If\n `mode` is \"SYMMETRIC\" then both `paddings[D, 0]` and `paddings[D, 1]` must be\n no greater than `tensor.dim_size(D)`.\n\n The padded size of each dimension D of the output is:\n\n `paddings[D, 0] + tensor.dim_size(D) + paddings[D, 1]`\n\n For example:\n\n ```python\n t = tf.constant([[1, 2, 3], [4, 5, 6]])\n paddings = tf.constant([[1, 1,], [2, 2]])\n # 'constant_values' is 0.\n # rank of 't' is 2.\n tf.pad(t, paddings, \"CONSTANT\") # [[0, 0, 0, 0, 0, 0, 0],\n # [0, 0, 1, 2, 3, 0, 0],\n # [0, 0, 4, 5, 6, 0, 0],\n # [0, 0, 0, 0, 0, 0, 0]]\n\n tf.pad(t, paddings, \"REFLECT\") # [[6, 5, 4, 5, 6, 5, 4],\n # [3, 2, 1, 2, 3, 2, 1],\n # [6, 5, 4, 5, 6, 5, 4],\n # [3, 2, 1, 2, 3, 2, 1]]\n\n tf.pad(t, paddings, \"SYMMETRIC\") # [[2, 1, 1, 2, 3, 3, 2],\n # [2, 1, 1, 2, 3, 3, 2],\n # [5, 4, 4, 5, 6, 6, 5],\n # [5, 4, 4, 5, 6, 6, 5]]\n ```\n\n Args:\n tensor: A `Tensor`.\n paddings: A `Tensor` of type `int32`.\n mode: One of \"CONSTANT\", \"REFLECT\", or \"SYMMETRIC\" (case-insensitive)\n constant_values: In \"CONSTANT\" mode, the scalar pad value to use. Must be\n same type as `tensor`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor`. Has the same type as `tensor`.\n\n Raises:\n ValueError: When mode is not one of \"CONSTANT\", \"REFLECT\", or \"SYMMETRIC\".\n \"\"\"\n return pad(tensor, paddings, mode, name, constant_values)\n\n\n@tf_export(v1=[\"pad\"])\[email protected]_dispatch_support\ndef pad(tensor, paddings, mode=\"CONSTANT\", name=None, constant_values=0): # pylint: disable=invalid-name\n \"\"\"Pads a tensor.\n\n This operation pads a `tensor` according to the `paddings` you specify.\n `paddings` is an integer tensor with shape `[n, 2]`, where n is the rank of\n `tensor`. For each dimension D of `input`, `paddings[D, 0]` indicates how\n many values to add before the contents of `tensor` in that dimension, and\n `paddings[D, 1]` indicates how many values to add after the contents of\n `tensor` in that dimension. If `mode` is \"REFLECT\" then both `paddings[D, 0]`\n and `paddings[D, 1]` must be no greater than `tensor.dim_size(D) - 1`. If\n `mode` is \"SYMMETRIC\" then both `paddings[D, 0]` and `paddings[D, 1]` must be\n no greater than `tensor.dim_size(D)`.\n\n The padded size of each dimension D of the output is:\n\n `paddings[D, 0] + tensor.dim_size(D) + paddings[D, 1]`\n\n For example:\n\n ```python\n t = tf.constant([[1, 2, 3], [4, 5, 6]])\n paddings = tf.constant([[1, 1,], [2, 2]])\n # 'constant_values' is 0.\n # rank of 't' is 2.\n tf.pad(t, paddings, \"CONSTANT\") # [[0, 0, 0, 0, 0, 0, 0],\n # [0, 0, 1, 2, 3, 0, 0],\n # [0, 0, 4, 5, 6, 0, 0],\n # [0, 0, 0, 0, 0, 0, 0]]\n\n tf.pad(t, paddings, \"REFLECT\") # [[6, 5, 4, 5, 6, 5, 4],\n # [3, 2, 1, 2, 3, 2, 1],\n # [6, 5, 4, 5, 6, 5, 4],\n # [3, 2, 1, 2, 3, 2, 1]]\n\n tf.pad(t, paddings, \"SYMMETRIC\") # [[2, 1, 1, 2, 3, 3, 2],\n # [2, 1, 1, 2, 3, 3, 2],\n # [5, 4, 4, 5, 6, 6, 5],\n # [5, 4, 4, 5, 6, 6, 5]]\n ```\n\n Args:\n tensor: A `Tensor`.\n paddings: A `Tensor` of type `int32`.\n mode: One of \"CONSTANT\", \"REFLECT\", or \"SYMMETRIC\" (case-insensitive)\n name: A name for the operation (optional).\n constant_values: In \"CONSTANT\" mode, the scalar pad value to use. Must be\n same type as `tensor`.\n\n Returns:\n A `Tensor`. Has the same type as `tensor`.\n\n Raises:\n ValueError: When mode is not one of \"CONSTANT\", \"REFLECT\", or \"SYMMETRIC\".\n \"\"\"\n\n # Convert lower/mixed case to upper for NumPy compatibility\n # NumPy uses all lower-case modes.\n mode = mode.upper()\n if mode == \"CONSTANT\":\n # TODO(rjryan): Once the forward compatibility period (3 weeks) have passed\n # remove the \"Pad\" fallback here.\n if not tensor_util.is_tf_type(constant_values) and constant_values == 0:\n result = gen_array_ops.pad(tensor, paddings, name=name)\n else:\n result = gen_array_ops.pad_v2(\n tensor, paddings, constant_values, name=name)\n elif mode == \"REFLECT\":\n result = gen_array_ops.mirror_pad(\n tensor, paddings, mode=\"REFLECT\", name=name)\n elif mode == \"SYMMETRIC\":\n result = gen_array_ops.mirror_pad(\n tensor, paddings, mode=\"SYMMETRIC\", name=name)\n else:\n raise ValueError(\"Unknown padding mode: %s\" % mode)\n\n # Restore shape information where possible.\n if not context.executing_eagerly():\n paddings_constant = _get_paddings_constant(paddings)\n input_shape = (\n tensor_shape.TensorShape(tensor.shape)\n if isinstance(tensor, ops.Tensor) else result.op.inputs[0].shape)\n if (input_shape.ndims is not None and\n not result.shape.is_fully_defined() and paddings_constant is not None):\n new_shape = []\n for padding, dim in zip(paddings_constant, input_shape.as_list()):\n if padding is None or dim is None or any((x is None for x in padding)):\n new_shape.append(None)\n else:\n new_shape.append(sum(padding) + dim)\n result.set_shape(new_shape)\n\n return result\n\n\ndef _get_paddings_constant(paddings):\n \"\"\"Helper to get the constant values of the paddings arg to pad().\n\n Used under V1 graph mode to facilitate computation of the shape of the output\n tensor of `pad()`.\n\n Args:\n paddings: The same paddings arg as passed to pad(). Can be a Tensor, or\n a nested list or tuple of Tensor and/or numbers.\n\n Returns:\n A nested list or numbers or `None`, in which `None` indicates unknown\n padding size.\n \"\"\"\n if isinstance(paddings, ops.Tensor):\n return tensor_util.constant_value(paddings, partial=True)\n elif isinstance(paddings, (list, tuple)):\n return [_get_paddings_constant(x) for x in paddings]\n else:\n return paddings\n\n\n@tf_export(\"meshgrid\")\[email protected]_dispatch_support\ndef meshgrid(*args, **kwargs):\n \"\"\"Broadcasts parameters for evaluation on an N-D grid.\n\n Given N one-dimensional coordinate arrays `*args`, returns a list `outputs`\n of N-D coordinate arrays for evaluating expressions on an N-D grid.\n\n Notes:\n\n `meshgrid` supports cartesian ('xy') and matrix ('ij') indexing conventions.\n When the `indexing` argument is set to 'xy' (the default), the broadcasting\n instructions for the first two dimensions are swapped.\n\n Examples:\n\n Calling `X, Y = meshgrid(x, y)` with the tensors\n\n ```python\n x = [1, 2, 3]\n y = [4, 5, 6]\n X, Y = tf.meshgrid(x, y)\n # X = [[1, 2, 3],\n # [1, 2, 3],\n # [1, 2, 3]]\n # Y = [[4, 4, 4],\n # [5, 5, 5],\n # [6, 6, 6]]\n ```\n\n Args:\n *args: `Tensor`s with rank 1.\n **kwargs:\n - indexing: Either 'xy' or 'ij' (optional, default: 'xy').\n - name: A name for the operation (optional).\n\n Returns:\n outputs: A list of N `Tensor`s with rank N.\n\n Raises:\n TypeError: When no keyword arguments (kwargs) are passed.\n ValueError: When indexing keyword argument is not one of `xy` or `ij`.\n \"\"\"\n\n indexing = kwargs.pop(\"indexing\", \"xy\")\n name = kwargs.pop(\"name\", \"meshgrid\")\n if kwargs:\n key = list(kwargs.keys())[0]\n raise TypeError(\"'{}' is an invalid keyword argument \"\n \"for this function\".format(key))\n\n if indexing not in (\"xy\", \"ij\"):\n raise ValueError(\"indexing parameter must be either 'xy' or 'ij'\")\n\n with ops.name_scope(name, \"meshgrid\", args) as name:\n ndim = len(args)\n s0 = (1,) * ndim\n\n if not ndim:\n return []\n\n # Prepare reshape by inserting dimensions with size 1 where needed\n output = []\n for i, x in enumerate(args):\n output.append(reshape(stack(x), (s0[:i] + (-1,) + s0[i + 1::])))\n # Create parameters for broadcasting each tensor to the full size\n shapes = [size(x) for x in args]\n\n output_dtype = ops.convert_to_tensor(args[0]).dtype.base_dtype\n\n if indexing == \"xy\" and ndim > 1:\n output[0] = reshape(output[0], (1, -1) + (1,) * (ndim - 2))\n output[1] = reshape(output[1], (-1, 1) + (1,) * (ndim - 2))\n shapes[0], shapes[1] = shapes[1], shapes[0]\n\n # TODO(nolivia): improve performance with a broadcast\n mult_fact = ones(shapes, output_dtype)\n return [x * mult_fact for x in output]\n\n\nNEW_AXIS = -1\nSHRINK_AXIS = -2\n\n\n# PEP-8 naming\n# pylint: disable=invalid-name,redefined-outer-name\ndef _compute_size_of_strided_dim(shrink, spec, size):\n \"\"\"Computes the size of a single strided slice dimension.\"\"\"\n\n unknown = None # Document what None means here.\n use_full_range = None # Document other use of None.\n # if this is a shrink axis (i.e. a non-range index)\n # it either will produce an error or return 1\n if shrink:\n return 1\n if size is unknown or size.value is unknown:\n return unknown\n size = size.value\n stride = spec.step\n if stride is not unknown:\n if stride == 0:\n return unknown\n stride = spec.step\n valid_range = [0, size] if stride > 0 else [-1, size - 1]\n\n # PEP-8 naming\n # pylint: disable=invalid-name\n def canonical(x, c):\n if x is use_full_range:\n return valid_range[c] if stride > 0 else valid_range[(c + 1) & 1]\n else:\n x_fwd = size + x if x < 0 else x # make negative indices positive\n return max(valid_range[0], min(valid_range[1], x_fwd))\n\n begin = canonical(spec.start, 0)\n end = canonical(spec.stop, 1)\n interval_length = end - begin\n if interval_length == 0 or ((interval_length < 0) != (stride < 0)):\n return 0\n else:\n remainder = 1 if interval_length % stride != 0 else 0\n return interval_length // stride + remainder\n else:\n return unknown # unknown because stride is unknown\n\n\ndef _TileGradShape(op):\n \"\"\"Shape function for the TileGrad op.\"\"\"\n multiples_shape = op.inputs[1].get_shape().with_rank(1)\n input_shape = op.inputs[0].get_shape().with_rank(multiples_shape[0])\n # NOTE(mrry): Represent `multiples` as a `TensorShape` because (i)\n # it is a vector of non-negative integers, and (ii) doing so allows\n # us to handle partially-known multiples.\n multiples = tensor_util.constant_value_as_shape(op.inputs[1]).with_rank(\n input_shape.ndims)\n if multiples.ndims is None:\n return [tensor_shape.unknown_shape()]\n else:\n output_dims = []\n for dim, multiple in zip(input_shape.dims, multiples.dims):\n output_dims.append(dim // multiple)\n return [tensor_shape.TensorShape(output_dims)]\n\n\n@tf_export(\"edit_distance\")\[email protected]_dispatch_support\ndef edit_distance(hypothesis, truth, normalize=True, name=\"edit_distance\"):\n \"\"\"Computes the Levenshtein distance between sequences.\n\n This operation takes variable-length sequences (`hypothesis` and `truth`),\n each provided as a `SparseTensor`, and computes the Levenshtein distance.\n You can normalize the edit distance by length of `truth` by setting\n `normalize` to true.\n\n For example:\n\n Given the following input,\n * `hypothesis` is a `tf.SparseTensor` of shape `[2, 1, 1]`\n * `truth` is a `tf.SparseTensor` of shape `[2, 2, 2]`\n\n >>> hypothesis = tf.SparseTensor(\n ... [[0, 0, 0],\n ... [1, 0, 0]],\n ... [\"a\", \"b\"],\n ... (2, 1, 1))\n >>> truth = tf.SparseTensor(\n ... [[0, 1, 0],\n ... [1, 0, 0],\n ... [1, 0, 1],\n ... [1, 1, 0]],\n ... [\"a\", \"b\", \"c\", \"a\"],\n ... (2, 2, 2))\n >>> tf.edit_distance(hypothesis, truth, normalize=True)\n <tf.Tensor: shape=(2, 2), dtype=float32, numpy=\n array([[inf, 1. ],\n [0.5, 1. ]], dtype=float32)>\n\n The operation returns a dense Tensor of shape `[2, 2]` with\n edit distances normalized by `truth` lengths.\n\n **Note**: It is possible to calculate edit distance between two\n sparse tensors with variable-length values. However, attempting to create\n them while eager execution is enabled will result in a `ValueError`.\n\n For the following inputs,\n\n ```python\n # 'hypothesis' is a tensor of shape `[2, 1]` with variable-length values:\n # (0,0) = [\"a\"]\n # (1,0) = [\"b\"]\n hypothesis = tf.sparse.SparseTensor(\n [[0, 0, 0],\n [1, 0, 0]],\n [\"a\", \"b\"],\n (2, 1, 1))\n\n # 'truth' is a tensor of shape `[2, 2]` with variable-length values:\n # (0,0) = []\n # (0,1) = [\"a\"]\n # (1,0) = [\"b\", \"c\"]\n # (1,1) = [\"a\"]\n truth = tf.sparse.SparseTensor(\n [[0, 1, 0],\n [1, 0, 0],\n [1, 0, 1],\n [1, 1, 0]],\n [\"a\", \"b\", \"c\", \"a\"],\n (2, 2, 2))\n\n normalize = True\n\n # The output would be a dense Tensor of shape `(2,)`, with edit distances\n normalized by 'truth' lengths.\n # output => array([0., 0.5], dtype=float32)\n ```\n\n Args:\n hypothesis: A `SparseTensor` containing hypothesis sequences.\n truth: A `SparseTensor` containing truth sequences.\n normalize: A `bool`. If `True`, normalizes the Levenshtein distance by\n length of `truth.`\n name: A name for the operation (optional).\n\n Returns:\n A dense `Tensor` with rank `R - 1`, where R is the rank of the\n `SparseTensor` inputs `hypothesis` and `truth`.\n\n Raises:\n TypeError: If either `hypothesis` or `truth` are not a `SparseTensor`.\n \"\"\"\n if not isinstance(\n hypothesis,\n (sparse_tensor.SparseTensor, sparse_tensor.SparseTensorValue)):\n raise TypeError(\"Hypothesis must be a SparseTensor.\")\n if not isinstance(\n truth, (sparse_tensor.SparseTensor, sparse_tensor.SparseTensorValue)):\n raise TypeError(\"Truth must be a SparseTensor.\")\n\n return gen_array_ops.edit_distance(\n hypothesis.indices,\n hypothesis.values,\n hypothesis.dense_shape,\n truth.indices,\n truth.values,\n truth.dense_shape,\n normalize=normalize,\n name=name)\n\n\[email protected](\"FakeQuantWithMinMaxArgs\")\ndef _FakeQuantWithMinMaxArgsGradient(op, grad):\n \"\"\"Gradient for FakeQuantWithMinMaxArgs op.\"\"\"\n return fake_quant_with_min_max_args_gradient(\n grad,\n op.inputs[0],\n min=op.get_attr(\"min\"),\n max=op.get_attr(\"max\"),\n num_bits=op.get_attr(\"num_bits\"),\n narrow_range=op.get_attr(\"narrow_range\"))\n\n\[email protected](\"FakeQuantWithMinMaxVars\")\ndef _FakeQuantWithMinMaxVarsGradient(op, grad):\n \"\"\"Gradient for FakeQuantWithMinMaxVars op.\"\"\"\n return fake_quant_with_min_max_vars_gradient(\n grad,\n op.inputs[0],\n op.inputs[1],\n op.inputs[2],\n num_bits=op.get_attr(\"num_bits\"),\n narrow_range=op.get_attr(\"narrow_range\"))\n\n\[email protected](\"FakeQuantWithMinMaxVarsPerChannel\")\ndef _FakeQuantWithMinMaxVarsPerChannelGradient(op, grad):\n \"\"\"Gradient for FakeQuantWithMinMaxVarsPerChannel op.\"\"\"\n return fake_quant_with_min_max_vars_per_channel_gradient(\n grad,\n op.inputs[0],\n op.inputs[1],\n op.inputs[2],\n num_bits=op.get_attr(\"num_bits\"),\n narrow_range=op.get_attr(\"narrow_range\"))\n\n\[email protected](\"QuantizeAndDequantizeV4\")\ndef _QuantizeAndDequantizeV4Grad(op, grad):\n \"\"\"Gradient for QuantizeAndDequantizeV4 op.\"\"\"\n return quantize_and_dequantize_v4_grad(\n grad,\n op.inputs[0],\n op.inputs[1],\n op.inputs[2],\n axis=op.get_attr(\"axis\"))\n\n\[email protected](\"QuantizeAndDequantizeV4Grad\")\ndef _QuantizeAndDequantizeV4GradGrad(op, grad):\n \"\"\"Gradient for QuantizeAndDequantizeV4Grad op.\"\"\"\n return _QuantizeAndDequantizeV4Grad(op, grad)\n\n\n@tf_export(\"required_space_to_batch_paddings\")\ndef required_space_to_batch_paddings(input_shape,\n block_shape,\n base_paddings=None,\n name=None):\n \"\"\"Calculate padding required to make block_shape divide input_shape.\n\n This function can be used to calculate a suitable paddings argument for use\n with space_to_batch_nd and batch_to_space_nd.\n\n Args:\n input_shape: int32 Tensor of shape [N].\n block_shape: int32 Tensor of shape [N].\n base_paddings: Optional int32 Tensor of shape [N, 2]. Specifies the minimum\n amount of padding to use. All elements must be >= 0. If not specified,\n defaults to 0.\n name: string. Optional name prefix.\n\n Returns:\n (paddings, crops), where:\n\n `paddings` and `crops` are int32 Tensors of rank 2 and shape [N, 2]\n satisfying:\n\n paddings[i, 0] = base_paddings[i, 0].\n 0 <= paddings[i, 1] - base_paddings[i, 1] < block_shape[i]\n (input_shape[i] + paddings[i, 0] + paddings[i, 1]) % block_shape[i] == 0\n\n crops[i, 0] = 0\n crops[i, 1] = paddings[i, 1] - base_paddings[i, 1]\n\n Raises: ValueError if called with incompatible shapes.\n \"\"\"\n with ops.name_scope(name, \"required_space_to_batch_paddings\",\n [input_shape, block_shape]):\n input_shape = ops.convert_to_tensor(\n input_shape, dtype=dtypes.int32, name=\"input_shape\")\n block_shape = ops.convert_to_tensor(\n block_shape, dtype=dtypes.int32, name=\"block_shape\")\n\n block_shape.get_shape().assert_is_fully_defined()\n block_shape.get_shape().assert_has_rank(1)\n num_block_dims = block_shape.get_shape().dims[0].value\n if num_block_dims == 0:\n return zeros([0, 2], dtypes.int32), zeros([0, 2], dtypes.int32)\n\n input_shape.get_shape().assert_is_compatible_with([num_block_dims])\n\n if base_paddings is not None:\n base_paddings = ops.convert_to_tensor(\n base_paddings, dtype=dtypes.int32, name=\"base_paddings\")\n base_paddings.get_shape().assert_is_compatible_with([num_block_dims, 2])\n else:\n base_paddings = zeros([num_block_dims, 2], dtypes.int32)\n\n const_block_shape = tensor_util.constant_value(block_shape)\n const_input_shape = tensor_util.constant_value(input_shape)\n const_base_paddings = tensor_util.constant_value(base_paddings)\n if (const_block_shape is not None and const_input_shape is not None and\n const_base_paddings is not None):\n block_shape = const_block_shape\n input_shape = const_input_shape\n base_paddings = const_base_paddings\n\n # Use same expression for both constant and non-constant case.\n pad_start = base_paddings[:, 0]\n orig_pad_end = base_paddings[:, 1]\n full_input_shape = input_shape + pad_start + orig_pad_end\n pad_end_extra = (block_shape - full_input_shape % block_shape) % block_shape\n pad_end = orig_pad_end + pad_end_extra\n\n result_paddings = stack(\n [[pad_start[i], pad_end[i]] for i in range(num_block_dims)],\n name=\"paddings\")\n result_crops = stack([[0, pad_end_extra[i]] for i in range(num_block_dims)],\n name=\"crops\")\n return result_paddings, result_crops\n\n\n@tf_export(v1=[\"nn.space_to_batch\", \"space_to_batch\"])\[email protected]_dispatch_support\[email protected]_endpoints(\"space_to_batch\")\ndef space_to_batch( # pylint: disable=missing-docstring\n input, # pylint: disable=redefined-builtin\n paddings,\n block_size=None,\n name=None,\n block_shape=None): # pylint: disable=redefined-builtin\n block_size = deprecation.deprecated_argument_lookup(\"block_shape\",\n block_shape, \"block_size\",\n block_size)\n result = space_to_batch_nd(\n input,\n paddings=paddings,\n block_shape=np.array([block_size, block_size], dtype=np.int64),\n name=name)\n result.set_shape(result.get_shape().with_rank(4))\n return result\n\n\nspace_to_batch.__doc__ = gen_array_ops.space_to_batch.__doc__\n\n\n@tf_export(\"space_to_batch\", \"nn.space_to_batch\", v1=[])\[email protected]_dispatch_support\ndef space_to_batch_v2(input, block_shape, paddings, name=None): # pylint: disable=redefined-builtin\n return space_to_batch_nd(input, block_shape, paddings, name)\n\n\nspace_to_batch_v2.__doc__ = gen_array_ops.space_to_batch_nd.__doc__\n\n\n@tf_export(v1=[\"nn.space_to_depth\", \"space_to_depth\"])\[email protected]_dispatch_support\[email protected]_endpoints(\"space_to_depth\")\ndef space_to_depth(input, block_size, name=None, data_format=\"NHWC\"): # pylint: disable=redefined-builtin\n return gen_array_ops.space_to_depth(input, block_size, data_format, name=name)\n\n\nspace_to_depth.__doc__ = gen_array_ops.space_to_depth.__doc__\n\n\n@tf_export(\"nn.space_to_depth\", v1=[])\[email protected]_dispatch_support\ndef space_to_depth_v2(input, block_size, data_format=\"NHWC\", name=None): # pylint: disable=redefined-builtin\n return gen_array_ops.space_to_depth(input, block_size, data_format, name=name)\n\n\nspace_to_depth_v2.__doc__ = gen_array_ops.space_to_depth.__doc__\n\n\n@tf_export(v1=[\"nn.depth_to_space\", \"depth_to_space\"])\[email protected]_dispatch_support\[email protected]_endpoints(\"depth_to_space\")\ndef depth_to_space(input, block_size, name=None, data_format=\"NHWC\"): # pylint: disable=redefined-builtin\n return gen_array_ops.depth_to_space(input, block_size, data_format, name=name)\n\n\ndepth_to_space.__doc__ = gen_array_ops.depth_to_space.__doc__\n\n\n@tf_export(\"nn.depth_to_space\", v1=[])\[email protected]_dispatch_support\ndef depth_to_space_v2(input, block_size, data_format=\"NHWC\", name=None): # pylint: disable=redefined-builtin\n return gen_array_ops.depth_to_space(input, block_size, data_format, name=name)\n\n\ndepth_to_space_v2.__doc__ = gen_array_ops.depth_to_space.__doc__\n\n\n@tf_export(v1=[\"batch_to_space\"])\[email protected]_dispatch_support\ndef batch_to_space(input, crops, block_size, name=None, block_shape=None): # pylint: disable=redefined-builtin,missing-docstring\n block_size = deprecation.deprecated_argument_lookup(\"block_shape\",\n block_shape, \"block_size\",\n block_size)\n result = batch_to_space_nd(\n input,\n crops=crops,\n block_shape=np.array([block_size, block_size], dtype=np.int64),\n name=name)\n result.set_shape(result.get_shape().with_rank(4))\n return result\n\n\nbatch_to_space.__doc__ = gen_array_ops.batch_to_space.__doc__\n\n\n@tf_export(\"batch_to_space\", v1=[])\[email protected]_dispatch_support\ndef batch_to_space_v2(input, block_shape, crops, name=None): # pylint: disable=redefined-builtin\n \"\"\"BatchToSpace for N-D tensors of type T.\n\n This operation reshapes the \"batch\" dimension 0 into `M + 1` dimensions of\n shape `block_shape + [batch]`, interleaves these blocks back into the grid\n defined by the spatial dimensions `[1, ..., M]`, to obtain a result with the\n same rank as the input. The spatial dimensions of this intermediate result\n are then optionally cropped according to `crops` to produce the output. This\n is the reverse of SpaceToBatch (see `tf.space_to_batch`).\n\n Args:\n input: A N-D `Tensor` with shape `input_shape = [batch] + spatial_shape +\n remaining_shape`, where `spatial_shape` has M dimensions.\n block_shape: A 1-D `Tensor` with shape [M]. Must be one of the following\n types: `int32`, `int64`. All values must be >= 1. For backwards\n compatibility with TF 1.0, this parameter may be an int, in which case it\n is converted to\n `numpy.array([block_shape, block_shape],\n dtype=numpy.int64)`.\n crops: A 2-D `Tensor` with shape `[M, 2]`. Must be one of the\n following types: `int32`, `int64`. All values must be >= 0.\n `crops[i] = [crop_start, crop_end]` specifies the amount to crop from\n input dimension `i + 1`, which corresponds to spatial dimension `i`.\n It is required that\n `crop_start[i] + crop_end[i] <= block_shape[i] * input_shape[i + 1]`.\n This operation is equivalent to the following steps:\n 1. Reshape `input` to `reshaped` of shape: [block_shape[0], ...,\n block_shape[M-1], batch / prod(block_shape), input_shape[1], ...,\n input_shape[N-1]]\n 2. Permute dimensions of `reshaped` to produce `permuted` of shape\n [batch / prod(block_shape), input_shape[1], block_shape[0], ...,\n input_shape[M], block_shape[M-1], input_shape[M+1],\n ..., input_shape[N-1]]\n 3. Reshape `permuted` to produce `reshaped_permuted` of shape\n [batch / prod(block_shape), input_shape[1] * block_shape[0], ...,\n input_shape[M] * block_shape[M-1], input_shape[M+1], ...,\n input_shape[N-1]]\n 4. Crop the start and end of dimensions `[1, ..., M]` of\n `reshaped_permuted` according to `crops` to produce the output\n of shape:\n [batch / prod(block_shape), input_shape[1] *\n block_shape[0] - crops[0,0] - crops[0,1], ..., input_shape[M] *\n block_shape[M-1] - crops[M-1,0] - crops[M-1,1], input_shape[M+1],\n ..., input_shape[N-1]]\n name: A name for the operation (optional).\n\n Examples:\n\n 1. For the following input of shape `[4, 1, 1, 1]`,\n `block_shape = [2, 2]`, and `crops = [[0, 0], [0, 0]]`:\n\n ```python\n [[[[1]]],\n [[[2]]],\n [[[3]]],\n [[[4]]]]\n ```\n\n The output tensor has shape `[1, 2, 2, 1]` and value:\n\n ```\n x = [[[[1], [2]],\n [[3], [4]]]]\n ```\n\n 2. For the following input of shape `[4, 1, 1, 3]`,\n `block_shape = [2, 2]`, and `crops = [[0, 0], [0, 0]]`:\n\n ```python\n [[[1, 2, 3]],\n [[4, 5, 6]],\n [[7, 8, 9]],\n [[10, 11, 12]]]\n ```\n\n The output tensor has shape `[1, 2, 2, 3]` and value:\n\n ```python\n x = [[[[1, 2, 3], [4, 5, 6 ]],\n [[7, 8, 9], [10, 11, 12]]]]\n ```\n\n 3. For the following\n input of shape `[4, 2, 2, 1]`,\n `block_shape = [2, 2]`, and `crops = [[0, 0], [0, 0]]`:\n\n ```python\n x = [[[[1], [3]], [[ 9], [11]]],\n [[[2], [4]], [[10], [12]]],\n [[[5], [7]], [[13], [15]]],\n [[[6], [8]], [[14], [16]]]]\n ```\n\n The output tensor has shape `[1, 4, 4, 1]` and value:\n\n ```python\n x = [[[1], [2], [ 3], [ 4]],\n [[5], [6], [ 7], [ 8]],\n [[9], [10], [11], [12]],\n [[13], [14], [15], [16]]]\n ```\n\n 4. For the following input of shape\n `[8, 1, 3, 1]`,\n `block_shape = [2, 2]`, and `crops = [[0, 0], [2, 0]]`:\n\n ```python\n x = [[[[0], [ 1], [ 3]]],\n [[[0], [ 9], [11]]],\n [[[0], [ 2], [ 4]]],\n [[[0], [10], [12]]],\n [[[0], [ 5], [ 7]]],\n [[[0], [13], [15]]],\n [[[0], [ 6], [ 8]]],\n [[[0], [14], [16]]]]\n ```\n\n The output tensor has shape `[2, 2, 4, 1]` and value:\n\n ```python\n x = [[[[ 1], [ 2], [ 3], [ 4]],\n [[ 5], [ 6], [ 7], [ 8]]],\n [[[ 9], [10], [11], [12]],\n [[13], [14], [15], [16]]]]\n ```\n\n Returns:\n A `Tensor`. Has the same type as `input`.\n \"\"\"\n if isinstance(block_shape, int):\n block_shape = np.array([block_shape, block_shape], dtype=np.int64)\n\n return batch_to_space_nd(\n input=input, block_shape=block_shape, crops=crops, name=name)\n\n\n@tf_export(\"one_hot\")\[email protected]_dispatch_support\ndef one_hot(indices,\n depth,\n on_value=None,\n off_value=None,\n axis=None,\n dtype=None,\n name=None):\n \"\"\"Returns a one-hot tensor.\n\n See also `tf.fill`, `tf.eye`.\n\n The locations represented by indices in `indices` take value `on_value`,\n while all other locations take value `off_value`.\n\n `on_value` and `off_value` must have matching data types. If `dtype` is also\n provided, they must be the same data type as specified by `dtype`.\n\n If `on_value` is not provided, it will default to the value `1` with type\n `dtype`\n\n If `off_value` is not provided, it will default to the value `0` with type\n `dtype`\n\n If the input `indices` is rank `N`, the output will have rank `N+1`. The\n new axis is created at dimension `axis` (default: the new axis is appended\n at the end).\n\n If `indices` is a scalar the output shape will be a vector of length `depth`\n\n If `indices` is a vector of length `features`, the output shape will be:\n\n ```\n features x depth if axis == -1\n depth x features if axis == 0\n ```\n\n If `indices` is a matrix (batch) with shape `[batch, features]`, the output\n shape will be:\n\n ```\n batch x features x depth if axis == -1\n batch x depth x features if axis == 1\n depth x batch x features if axis == 0\n ```\n\n If `indices` is a RaggedTensor, the 'axis' argument must be positive and refer\n to a non-ragged axis. The output will be equivalent to applying 'one_hot' on\n the values of the RaggedTensor, and creating a new RaggedTensor from the\n result.\n\n If `dtype` is not provided, it will attempt to assume the data type of\n `on_value` or `off_value`, if one or both are passed in. If none of\n `on_value`, `off_value`, or `dtype` are provided, `dtype` will default to the\n value `tf.float32`.\n\n Note: If a non-numeric data type output is desired (`tf.string`, `tf.bool`,\n etc.), both `on_value` and `off_value` _must_ be provided to `one_hot`.\n\n For example:\n\n ```python\n indices = [0, 1, 2]\n depth = 3\n tf.one_hot(indices, depth) # output: [3 x 3]\n # [[1., 0., 0.],\n # [0., 1., 0.],\n # [0., 0., 1.]]\n\n indices = [0, 2, -1, 1]\n depth = 3\n tf.one_hot(indices, depth,\n on_value=5.0, off_value=0.0,\n axis=-1) # output: [4 x 3]\n # [[5.0, 0.0, 0.0], # one_hot(0)\n # [0.0, 0.0, 5.0], # one_hot(2)\n # [0.0, 0.0, 0.0], # one_hot(-1)\n # [0.0, 5.0, 0.0]] # one_hot(1)\n\n indices = [[0, 2], [1, -1]]\n depth = 3\n tf.one_hot(indices, depth,\n on_value=1.0, off_value=0.0,\n axis=-1) # output: [2 x 2 x 3]\n # [[[1.0, 0.0, 0.0], # one_hot(0)\n # [0.0, 0.0, 1.0]], # one_hot(2)\n # [[0.0, 1.0, 0.0], # one_hot(1)\n # [0.0, 0.0, 0.0]]] # one_hot(-1)\n\n indices = tf.ragged.constant([[0, 1], [2]])\n depth = 3\n tf.one_hot(indices, depth) # output: [2 x None x 3]\n # [[[1., 0., 0.],\n # [0., 1., 0.]],\n # [[0., 0., 1.]]]\n ```\n\n Args:\n indices: A `Tensor` of indices.\n depth: A scalar defining the depth of the one hot dimension.\n on_value: A scalar defining the value to fill in output when `indices[j]\n = i`. (default: 1)\n off_value: A scalar defining the value to fill in output when `indices[j]\n != i`. (default: 0)\n axis: The axis to fill (default: -1, a new inner-most axis).\n dtype: The data type of the output tensor.\n name: A name for the operation (optional).\n\n Returns:\n output: The one-hot tensor.\n\n Raises:\n TypeError: If dtype of either `on_value` or `off_value` don't match `dtype`\n TypeError: If dtype of `on_value` and `off_value` don't match one another\n \"\"\"\n with ops.name_scope(\n name, \"one_hot\",\n [indices, depth, on_value, off_value, axis, dtype]) as name:\n on_exists = on_value is not None\n off_exists = off_value is not None\n\n if on_exists:\n on_value = ops.convert_to_tensor(on_value, dtype_hint=dtype)\n if off_exists:\n off_value = ops.convert_to_tensor(off_value, dtype_hint=dtype)\n\n on_dtype = on_value.dtype.base_dtype if on_exists else None\n off_dtype = off_value.dtype.base_dtype if off_exists else None\n\n if on_exists or off_exists:\n if dtype is not None:\n # Ensure provided on_value and/or off_value match dtype\n if on_exists and on_dtype != dtype:\n raise TypeError(\"dtype {0} of on_value does not match \"\n \"dtype parameter {1}\".format(on_dtype, dtype))\n if off_exists and off_dtype != dtype:\n raise TypeError(\"dtype {0} of off_value does not match \"\n \"dtype parameter {1}\".format(off_dtype, dtype))\n else:\n # dtype not provided: automatically assign it\n dtype = on_dtype if on_exists else off_dtype\n elif dtype is None:\n # None of on_value, off_value, or dtype provided. Default dtype to float32\n dtype = dtypes.float32\n\n if not on_exists:\n # on_value not provided: assign to value 1 of type dtype\n on_value = ops.convert_to_tensor(1, dtype, name=\"on_value\")\n on_dtype = dtype\n if not off_exists:\n # off_value not provided: assign to value 0 of type dtype\n off_value = ops.convert_to_tensor(0, dtype, name=\"off_value\")\n off_dtype = dtype\n\n if on_dtype != off_dtype:\n raise TypeError(\"dtype {0} of on_value does not match \"\n \"dtype {1} of off_value\".format(on_dtype, off_dtype))\n\n return gen_array_ops.one_hot(indices, depth, on_value, off_value, axis,\n name)\n\n\ndef _all_dimensions(x):\n \"\"\"Returns a 1D-tensor listing all dimensions in x.\"\"\"\n # Fast path: avoid creating Rank and Range ops if ndims is known.\n if isinstance(x, ops.Tensor) and x.get_shape().ndims is not None:\n return constant_op.constant(\n np.arange(x.get_shape().ndims), dtype=dtypes.int32)\n if (isinstance(x, sparse_tensor.SparseTensor) and\n x.dense_shape.get_shape().is_fully_defined()):\n r = x.dense_shape.get_shape().dims[0].value # sparse.dense_shape is 1-D.\n return constant_op.constant(np.arange(r), dtype=dtypes.int32)\n\n # Otherwise, we rely on `range` and `rank` to do the right thing at runtime.\n return gen_math_ops._range(0, rank(x), 1)\n\n\n@tf_export(\"sequence_mask\")\[email protected]_dispatch_support\ndef sequence_mask(lengths, maxlen=None, dtype=dtypes.bool, name=None):\n \"\"\"Returns a mask tensor representing the first N positions of each cell.\n\n If `lengths` has shape `[d_1, d_2, ..., d_n]` the resulting tensor `mask` has\n dtype `dtype` and shape `[d_1, d_2, ..., d_n, maxlen]`, with\n\n ```\n mask[i_1, i_2, ..., i_n, j] = (j < lengths[i_1, i_2, ..., i_n])\n ```\n\n Examples:\n\n ```python\n tf.sequence_mask([1, 3, 2], 5) # [[True, False, False, False, False],\n # [True, True, True, False, False],\n # [True, True, False, False, False]]\n\n tf.sequence_mask([[1, 3],[2,0]]) # [[[True, False, False],\n # [True, True, True]],\n # [[True, True, False],\n # [False, False, False]]]\n ```\n\n Args:\n lengths: integer tensor, all its values <= maxlen.\n maxlen: scalar integer tensor, size of last dimension of returned tensor.\n Default is the maximum value in `lengths`.\n dtype: output type of the resulting tensor.\n name: name of the op.\n\n Returns:\n A mask tensor of shape `lengths.shape + (maxlen,)`, cast to specified dtype.\n Raises:\n ValueError: if `maxlen` is not a scalar.\n \"\"\"\n with ops.name_scope(name, \"SequenceMask\", [lengths, maxlen]):\n lengths = ops.convert_to_tensor(lengths)\n\n if maxlen is None:\n maxlen = gen_math_ops._max(lengths, _all_dimensions(lengths))\n maxlen = gen_math_ops.maximum(constant(0, maxlen.dtype), maxlen)\n else:\n maxlen = ops.convert_to_tensor(maxlen)\n if maxlen.get_shape().ndims is not None and maxlen.get_shape().ndims != 0:\n raise ValueError(\"maxlen must be scalar for sequence_mask\")\n\n # The basic idea is to compare a range row vector of size maxlen:\n # [0, 1, 2, 3, 4]\n # to length as a matrix with 1 column: [[1], [3], [2]].\n # Because of broadcasting on both arguments this comparison results\n # in a matrix of size (len(lengths), maxlen)\n row_vector = gen_math_ops._range(\n constant(0, maxlen.dtype), maxlen, constant(1, maxlen.dtype))\n # Since maxlen >= max(lengths), it is safe to use maxlen as a cast\n # authoritative type. Whenever maxlen fits into tf.int32, so do the lengths.\n matrix = gen_math_ops.cast(expand_dims(lengths, -1), maxlen.dtype)\n result = row_vector < matrix\n if dtype is None or result.dtype.is_compatible_with(dtype):\n return result\n else:\n return gen_math_ops.cast(result, dtype)\n\n\n@tf_export(v1=[\"squeeze\"])\[email protected]_dispatch_support\[email protected]_args(None, \"Use the `axis` argument instead\",\n \"squeeze_dims\")\ndef squeeze(input, axis=None, name=None, squeeze_dims=None):\n # pylint: disable=redefined-builtin\n \"\"\"Removes dimensions of size 1 from the shape of a tensor.\n\n Given a tensor `input`, this operation returns a tensor of the same type with\n all dimensions of size 1 removed. If you don't want to remove all size 1\n dimensions, you can remove specific size 1 dimensions by specifying\n `axis`.\n\n For example:\n\n >>> # 't' is a tensor of shape [1, 2, 1, 3, 1, 1]\n >>> t = tf.ones([1, 2, 1, 3, 1, 1])\n >>> print(tf.shape(tf.squeeze(t)).numpy())\n [2 3]\n\n Or, to remove specific size 1 dimensions:\n\n >>> # 't' is a tensor of shape [1, 2, 1, 3, 1, 1]\n >>> t = tf.ones([1, 2, 1, 3, 1, 1])\n >>> print(tf.shape(tf.squeeze(t, [2, 4])).numpy())\n [1 2 3 1]\n\n Note: if `input` is a `tf.RaggedTensor`, then this operation takes `O(N)`\n time, where `N` is the number of elements in the squeezed dimensions.\n\n Args:\n input: A `Tensor`. The `input` to squeeze.\n axis: An optional list of `ints`. Defaults to `[]`. If specified, only\n squeezes the dimensions listed. The dimension index starts at 0. It is an\n error to squeeze a dimension that is not 1. Must be in the range\n `[-rank(input), rank(input))`. Must be specified if `input` is a\n `RaggedTensor`.\n name: A name for the operation (optional).\n squeeze_dims: Deprecated keyword argument that is now axis.\n\n Returns:\n A `Tensor`. Has the same type as `input`.\n Contains the same data as `input`, but has one or more dimensions of\n size 1 removed.\n\n Raises:\n ValueError: When both `squeeze_dims` and `axis` are specified.\n \"\"\"\n axis = deprecation.deprecated_argument_lookup(\"axis\", axis, \"squeeze_dims\",\n squeeze_dims)\n if np.isscalar(axis):\n axis = [axis]\n return gen_array_ops.squeeze(input, axis, name)\n\n\n@tf_export(\"squeeze\", v1=[])\[email protected]_dispatch_support\ndef squeeze_v2(input, axis=None, name=None):\n \"\"\"Removes dimensions of size 1 from the shape of a tensor.\n\n Given a tensor `input`, this operation returns a tensor of the same type with\n all dimensions of size 1 removed. If you don't want to remove all size 1\n dimensions, you can remove specific size 1 dimensions by specifying\n `axis`.\n\n For example:\n\n ```python\n # 't' is a tensor of shape [1, 2, 1, 3, 1, 1]\n tf.shape(tf.squeeze(t)) # [2, 3]\n ```\n\n Or, to remove specific size 1 dimensions:\n\n ```python\n # 't' is a tensor of shape [1, 2, 1, 3, 1, 1]\n tf.shape(tf.squeeze(t, [2, 4])) # [1, 2, 3, 1]\n ```\n\n Unlike the older op `tf.compat.v1.squeeze`, this op does not accept a\n deprecated `squeeze_dims` argument.\n\n Note: if `input` is a `tf.RaggedTensor`, then this operation takes `O(N)`\n time, where `N` is the number of elements in the squeezed dimensions.\n\n Args:\n input: A `Tensor`. The `input` to squeeze.\n axis: An optional list of `ints`. Defaults to `[]`. If specified, only\n squeezes the dimensions listed. The dimension index starts at 0. It is an\n error to squeeze a dimension that is not 1. Must be in the range\n `[-rank(input), rank(input))`. Must be specified if `input` is a\n `RaggedTensor`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor`. Has the same type as `input`.\n Contains the same data as `input`, but has one or more dimensions of\n size 1 removed.\n\n Raises:\n ValueError: The input cannot be converted to a tensor, or the specified\n axis cannot be squeezed.\n \"\"\"\n # pylint: disable=redefined-builtin\n return squeeze(input, axis, name)\n\n\n@tf_export(v1=[\"where\"])\[email protected]_dispatch_support\ndef where(condition, x=None, y=None, name=None):\n \"\"\"Return the elements, either from `x` or `y`, depending on the `condition`.\n\n If both `x` and `y` are None, then this operation returns the coordinates of\n true elements of `condition`. The coordinates are returned in a 2-D tensor\n where the first dimension (rows) represents the number of true elements, and\n the second dimension (columns) represents the coordinates of the true\n elements. Keep in mind, the shape of the output tensor can vary depending on\n how many true values there are in input. Indices are output in row-major\n order.\n\n If both non-None, `x` and `y` must have the same shape.\n The `condition` tensor must be a scalar if `x` and `y` are scalar.\n If `x` and `y` are tensors of higher rank, then `condition` must be either a\n vector with size matching the first dimension of `x`, or must have the same\n shape as `x`.\n\n The `condition` tensor acts as a mask that chooses, based on the value at each\n element, whether the corresponding element / row in the output should be taken\n from `x` (if true) or `y` (if false).\n\n If `condition` is a vector and `x` and `y` are higher rank matrices, then it\n chooses which row (outer dimension) to copy from `x` and `y`. If `condition`\n has the same shape as `x` and `y`, then it chooses which element to copy from\n `x` and `y`.\n\n Args:\n condition: A `Tensor` of type `bool`\n x: A Tensor which may have the same shape as `condition`. If `condition` is\n rank 1, `x` may have higher rank, but its first dimension must match the\n size of `condition`.\n y: A `tensor` with the same shape and type as `x`.\n name: A name of the operation (optional)\n\n Returns:\n A `Tensor` with the same type and shape as `x`, `y` if they are non-None.\n Otherwise, a `Tensor` with shape `(num_true, rank(condition))`.\n\n Raises:\n ValueError: When exactly one of `x` or `y` is non-None.\n \"\"\"\n if x is None and y is None:\n with ops.name_scope(name, \"Where\", [condition]) as name:\n condition = ops.convert_to_tensor(\n condition, preferred_dtype=dtypes.bool, name=\"condition\")\n return gen_array_ops.where(condition=condition, name=name)\n elif x is not None and y is not None:\n return gen_math_ops.select(condition=condition, x=x, y=y, name=name)\n else:\n raise ValueError(\"x and y must both be non-None or both be None.\")\n\n\n@tf_export(\"where\", v1=[\"where_v2\"])\[email protected]_dispatch_support\ndef where_v2(condition, x=None, y=None, name=None):\n \"\"\"Return the elements where `condition` is `True` (multiplexing `x` and `y`).\n\n This operator has two modes: in one mode both `x` and `y` are provided, in\n another mode neither are provided. `condition` is always expected to be a\n `tf.Tensor` of type `bool`.\n\n #### Retrieving indices of `True` elements\n\n If `x` and `y` are not provided (both are None):\n\n `tf.where` will return the indices of `condition` that are `True`, in\n the form of a 2-D tensor with shape (n, d).\n (Where n is the number of matching indices in `condition`,\n and d is the number of dimensions in `condition`).\n\n Indices are output in row-major order.\n\n >>> tf.where([True, False, False, True])\n <tf.Tensor: shape=(2, 1), dtype=int64, numpy=\n array([[0],\n [3]])>\n\n >>> tf.where([[True, False], [False, True]])\n <tf.Tensor: shape=(2, 2), dtype=int64, numpy=\n array([[0, 0],\n [1, 1]])>\n\n >>> tf.where([[[True, False], [False, True], [True, True]]])\n <tf.Tensor: shape=(4, 3), dtype=int64, numpy=\n array([[0, 0, 0],\n [0, 1, 1],\n [0, 2, 0],\n [0, 2, 1]])>\n\n #### Multiplexing between `x` and `y`\n\n If `x` and `y` are provided (both have non-None values):\n\n `tf.where` will choose an output shape from the shapes of `condition`, `x`,\n and `y` that all three shapes are\n [broadcastable](https://docs.scipy.org/doc/numpy/reference/ufuncs.html) to.\n\n The `condition` tensor acts as a mask that chooses whether the corresponding\n element / row in the output should be taken from `x`\n (if the element in `condition` is True) or `y` (if it is false).\n\n >>> tf.where([True, False, False, True], [1,2,3,4], [100,200,300,400])\n <tf.Tensor: shape=(4,), dtype=int32, numpy=array([ 1, 200, 300, 4],\n dtype=int32)>\n >>> tf.where([True, False, False, True], [1,2,3,4], [100])\n <tf.Tensor: shape=(4,), dtype=int32, numpy=array([ 1, 100, 100, 4],\n dtype=int32)>\n >>> tf.where([True, False, False, True], [1,2,3,4], 100)\n <tf.Tensor: shape=(4,), dtype=int32, numpy=array([ 1, 100, 100, 4],\n dtype=int32)>\n >>> tf.where([True, False, False, True], 1, 100)\n <tf.Tensor: shape=(4,), dtype=int32, numpy=array([ 1, 100, 100, 1],\n dtype=int32)>\n\n >>> tf.where(True, [1,2,3,4], 100)\n <tf.Tensor: shape=(4,), dtype=int32, numpy=array([1, 2, 3, 4],\n dtype=int32)>\n >>> tf.where(False, [1,2,3,4], 100)\n <tf.Tensor: shape=(4,), dtype=int32, numpy=array([100, 100, 100, 100],\n dtype=int32)>\n\n Note that if the gradient of either branch of the tf.where generates\n a NaN, then the gradient of the entire tf.where will be NaN.\n A workaround is to use an inner tf.where to ensure the function has\n no asymptote, and to avoid computing a value whose gradient is NaN by\n replacing dangerous inputs with safe inputs.\n\n Instead of this,\n\n >>> y = tf.constant(-1, dtype=tf.float32)\n >>> tf.where(y > 0, tf.sqrt(y), y)\n <tf.Tensor: shape=(), dtype=float32, numpy=-1.0>\n\n Use this\n\n >>> tf.where(y > 0, tf.sqrt(tf.where(y > 0, y, 1)), y)\n <tf.Tensor: shape=(), dtype=float32, numpy=-1.0>\n\n Args:\n condition: A `tf.Tensor` of type `bool`\n x: If provided, a Tensor which is of the same type as `y`, and has a shape\n broadcastable with `condition` and `y`.\n y: If provided, a Tensor which is of the same type as `x`, and has a shape\n broadcastable with `condition` and `x`.\n name: A name of the operation (optional).\n\n Returns:\n If `x` and `y` are provided:\n A `Tensor` with the same type as `x` and `y`, and shape that\n is broadcast from `condition`, `x`, and `y`.\n Otherwise, a `Tensor` with shape `(num_true, dim_size(condition))`.\n\n Raises:\n ValueError: When exactly one of `x` or `y` is non-None, or the shapes\n are not all broadcastable.\n \"\"\"\n if x is None and y is None:\n with ops.name_scope(name, \"Where\", [condition]) as name:\n condition = ops.convert_to_tensor(\n condition, preferred_dtype=dtypes.bool, name=\"condition\")\n return gen_array_ops.where(condition=condition, name=name)\n elif x is not None and y is not None:\n return gen_math_ops.select_v2(condition=condition, t=x, e=y, name=name)\n else:\n raise ValueError(\"x and y must both be non-None or both be None.\")\n\n\n# pylint: disable=redefined-builtin\n@tf_export(v1=[\"reverse_sequence\"])\[email protected]_args(None,\n \"seq_dim is deprecated, use seq_axis instead\",\n \"seq_dim\")\[email protected]_args(None,\n \"batch_dim is deprecated, use batch_axis instead\",\n \"batch_dim\")\ndef reverse_sequence(input,\n seq_lengths,\n seq_axis=None,\n batch_axis=None,\n name=None,\n seq_dim=None,\n batch_dim=None):\n \"\"\"Reverses variable length slices.\n\n This op first slices `input` along the dimension `batch_axis`, and for\n each slice `i`, reverses the first `seq_lengths[i]` elements along the\n dimension `seq_axis`.\n\n The elements of `seq_lengths` must obey `seq_lengths[i] <=\n input.dims[seq_axis]`, and `seq_lengths` must be a vector of length\n `input.dims[batch_axis]`.\n\n The output slice `i` along dimension `batch_axis` is then given by\n input slice `i`, with the first `seq_lengths[i]` slices along\n dimension `seq_axis` reversed.\n\n Example usage:\n\n >>> seq_lengths = [7, 2, 3, 5]\n >>> input = [[1, 2, 3, 4, 5, 0, 0, 0], [1, 2, 0, 0, 0, 0, 0, 0],\n ... [1, 2, 3, 4, 0, 0, 0, 0], [1, 2, 3, 4, 5, 6, 7, 8]]\n >>> output = tf.reverse_sequence(input, seq_lengths, seq_axis=1, batch_axis=0)\n >>> output\n <tf.Tensor: shape=(4, 8), dtype=int32, numpy=\n array([[0, 0, 5, 4, 3, 2, 1, 0],\n [2, 1, 0, 0, 0, 0, 0, 0],\n [3, 2, 1, 4, 0, 0, 0, 0],\n [5, 4, 3, 2, 1, 6, 7, 8]], dtype=int32)>\n\n Args:\n input: A `Tensor`. The input to reverse.\n seq_lengths: A `Tensor`. Must be one of the following types: `int32`,\n `int64`. 1-D with length `input.dims(batch_axis)` and `max(seq_lengths) <=\n input.dims(seq_axis)`\n seq_axis: An `int`. The dimension which is partially reversed.\n batch_axis: An optional `int`. Defaults to `0`. The dimension along which\n reversal is performed.\n name: A name for the operation (optional).\n\n Returns:\n A Tensor. Has the same type as input.\n \"\"\"\n seq_axis = deprecation.deprecated_argument_lookup(\"seq_axis\", seq_axis,\n \"seq_dim\", seq_dim)\n batch_axis = deprecation.deprecated_argument_lookup(\"batch_axis\", batch_axis,\n \"batch_dim\", batch_dim)\n return gen_array_ops.reverse_sequence(\n input=input,\n seq_lengths=seq_lengths,\n seq_dim=seq_axis,\n batch_dim=batch_axis,\n name=name)\n\n\n@tf_export(\"reverse_sequence\", v1=[])\[email protected]_dispatch_support\ndef reverse_sequence_v2(input,\n seq_lengths,\n seq_axis=None,\n batch_axis=None,\n name=None):\n \"\"\"Reverses variable length slices.\n\n This op first slices `input` along the dimension `batch_axis`, and for\n each slice `i`, reverses the first `seq_lengths[i]` elements along the\n dimension `seq_axis`.\n\n The elements of `seq_lengths` must obey `seq_lengths[i] <=\n input.dims[seq_axis]`, and `seq_lengths` must be a vector of length\n `input.dims[batch_axis]`.\n\n The output slice `i` along dimension `batch_axis` is then given by\n input slice `i`, with the first `seq_lengths[i]` slices along\n dimension `seq_axis` reversed.\n\n Example usage:\n\n >>> seq_lengths = [7, 2, 3, 5]\n >>> input = [[1, 2, 3, 4, 5, 0, 0, 0], [1, 2, 0, 0, 0, 0, 0, 0],\n ... [1, 2, 3, 4, 0, 0, 0, 0], [1, 2, 3, 4, 5, 6, 7, 8]]\n >>> output = tf.reverse_sequence(input, seq_lengths, seq_axis=1, batch_axis=0)\n >>> output\n <tf.Tensor: shape=(4, 8), dtype=int32, numpy=\n array([[0, 0, 5, 4, 3, 2, 1, 0],\n [2, 1, 0, 0, 0, 0, 0, 0],\n [3, 2, 1, 4, 0, 0, 0, 0],\n [5, 4, 3, 2, 1, 6, 7, 8]], dtype=int32)>\n\n Args:\n input: A `Tensor`. The input to reverse.\n seq_lengths: A `Tensor`. Must be one of the following types: `int32`,\n `int64`. 1-D with length `input.dims(batch_axis)` and `max(seq_lengths) <=\n input.dims(seq_axis)`\n seq_axis: An `int`. The dimension which is partially reversed.\n batch_axis: An optional `int`. Defaults to `0`. The dimension along which\n reversal is performed.\n name: A name for the operation (optional).\n\n Returns:\n A Tensor. Has the same type as input.\n \"\"\"\n return gen_array_ops.reverse_sequence(\n input=input,\n seq_lengths=seq_lengths,\n seq_dim=seq_axis,\n batch_dim=batch_axis,\n name=name)\n\n# pylint: enable=redefined-builtin\n\n\n@tf_export(v1=[\"gather\"])\[email protected]_args(None,\n (\"The `validate_indices` argument has no effect. \"\n \"Indices are always validated on CPU and never \"\n \"validated on GPU.\"),\n \"validate_indices\")\[email protected]_dispatch_support\ndef gather(params,\n indices,\n validate_indices=None,\n name=None,\n axis=None,\n batch_dims=0): # pylint: disable=g-doc-args\n r\"\"\"Gather slices from params axis `axis` according to indices.\n\n Gather slices from `params` axis `axis` according to `indices`. `indices`\n must be an integer tensor of any dimension (often 1-D).\n\n `Tensor.__getitem__` works for scalars, `tf.newaxis`, and\n [python slices](https://numpy.org/doc/stable/reference/arrays.indexing.html#basic-slicing-and-indexing)\n\n `tf.gather` extends indexing to handle tensors of indices.\n\n In the simplest case it's identical to scalar indexing:\n\n >>> params = tf.constant(['p0', 'p1', 'p2', 'p3', 'p4', 'p5'])\n >>> params[3].numpy()\n b'p3'\n >>> tf.gather(params, 3).numpy()\n b'p3'\n\n The most common case is to pass a single axis tensor of indices (this\n can't be expressed as a python slice because the indices are not sequential):\n\n >>> indices = [2, 0, 2, 5]\n >>> tf.gather(params, indices).numpy()\n array([b'p2', b'p0', b'p2', b'p5'], dtype=object)\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/Gather.png\"\n alt>\n </div>\n\n The indices can have any shape. When the `params` has 1 axis, the\n output shape is equal to the input shape:\n\n >>> tf.gather(params, [[2, 0], [2, 5]]).numpy()\n array([[b'p2', b'p0'],\n [b'p2', b'p5']], dtype=object)\n\n The `params` may also have any shape. `gather` can select slices\n across any axis depending on the `axis` argument (which defaults to 0).\n Below it is used to gather first rows, then columns from a matrix:\n\n >>> params = tf.constant([[0, 1.0, 2.0],\n ... [10.0, 11.0, 12.0],\n ... [20.0, 21.0, 22.0],\n ... [30.0, 31.0, 32.0]])\n >>> tf.gather(params, indices=[3,1]).numpy()\n array([[30., 31., 32.],\n [10., 11., 12.]], dtype=float32)\n >>> tf.gather(params, indices=[2,1], axis=1).numpy()\n array([[ 2., 1.],\n [12., 11.],\n [22., 21.],\n [32., 31.]], dtype=float32)\n\n More generally: The output shape has the same shape as the input, with the\n indexed-axis replaced by the shape of the indices.\n\n >>> def result_shape(p_shape, i_shape, axis=0):\n ... return p_shape[:axis] + i_shape + p_shape[axis+1:]\n >>>\n >>> result_shape([1, 2, 3], [], axis=1)\n [1, 3]\n >>> result_shape([1, 2, 3], [7], axis=1)\n [1, 7, 3]\n >>> result_shape([1, 2, 3], [7, 5], axis=1)\n [1, 7, 5, 3]\n\n Here are some examples:\n\n >>> params.shape.as_list()\n [4, 3]\n >>> indices = tf.constant([[0, 2]])\n >>> tf.gather(params, indices=indices, axis=0).shape.as_list()\n [1, 2, 3]\n >>> tf.gather(params, indices=indices, axis=1).shape.as_list()\n [4, 1, 2]\n\n >>> params = tf.random.normal(shape=(5, 6, 7, 8))\n >>> indices = tf.random.uniform(shape=(10, 11), maxval=7, dtype=tf.int32)\n >>> result = tf.gather(params, indices, axis=2)\n >>> result.shape.as_list()\n [5, 6, 10, 11, 8]\n\n This is because each index takes a slice from `params`, and\n places it at the corresponding location in the output. For the above example\n\n >>> # For any location in indices\n >>> a, b = 0, 1\n >>> tf.reduce_all(\n ... # the corresponding slice of the result\n ... result[:, :, a, b, :] ==\n ... # is equal to the slice of `params` along `axis` at the index.\n ... params[:, :, indices[a, b], :]\n ... ).numpy()\n True\n\n ### Batching:\n\n The `batch_dims` argument lets you gather different items from each element\n of a batch.\n\n Using `batch_dims=1` is equivalent to having an outer loop over the first\n axis of `params` and `indices`:\n\n >>> params = tf.constant([\n ... [0, 0, 1, 0, 2],\n ... [3, 0, 0, 0, 4],\n ... [0, 5, 0, 6, 0]])\n >>> indices = tf.constant([\n ... [2, 4],\n ... [0, 4],\n ... [1, 3]])\n\n >>> tf.gather(params, indices, axis=1, batch_dims=1).numpy()\n array([[1, 2],\n [3, 4],\n [5, 6]], dtype=int32)\n\n This is is equivalent to:\n\n >>> def manually_batched_gather(params, indices, axis):\n ... batch_dims=1\n ... result = []\n ... for p,i in zip(params, indices):\n ... r = tf.gather(p, i, axis=axis-batch_dims)\n ... result.append(r)\n ... return tf.stack(result)\n >>> manually_batched_gather(params, indices, axis=1).numpy()\n array([[1, 2],\n [3, 4],\n [5, 6]], dtype=int32)\n\n Higher values of `batch_dims` are equivalent to multiple nested loops over\n the outer axes of `params` and `indices`. So the overall shape function is\n\n >>> def batched_result_shape(p_shape, i_shape, axis=0, batch_dims=0):\n ... return p_shape[:axis] + i_shape[batch_dims:] + p_shape[axis+1:]\n >>>\n >>> batched_result_shape(\n ... p_shape=params.shape.as_list(),\n ... i_shape=indices.shape.as_list(),\n ... axis=1,\n ... batch_dims=1)\n [3, 2]\n\n >>> tf.gather(params, indices, axis=1, batch_dims=1).shape.as_list()\n [3, 2]\n\n This comes up naturally if you need to use the indices of an operation like\n `tf.argsort`, or `tf.math.top_k` where the last dimension of the indices\n indexes into the last dimension of input, at the corresponding location.\n In this case you can use `tf.gather(values, indices, batch_dims=-1)`.\n\n See also:\n\n * `tf.Tensor.__getitem__`: The direct tensor index operation (`t[]`), handles\n scalars and python-slices `tensor[..., 7, 1:-1]`\n * `tf.scatter`: A collection of operations similar to `__setitem__`\n (`t[i] = x`)\n * `tf.gather_nd`: An operation similar to `tf.gather` but gathers across\n multiple axis at once (it can gather elements of a matrix instead of rows\n or columns)\n * `tf.boolean_mask`, `tf.where`: Binary indexing.\n * `tf.slice` and `tf.strided_slice`: For lower level access to the\n implementation of `__getitem__`'s python-slice handling (`t[1:-1:2]`)\n\n Args:\n params: The `Tensor` from which to gather values. Must be at least rank\n `axis + 1`.\n indices: The index `Tensor`. Must be one of the following types: `int32`,\n `int64`. The values must be in range `[0, params.shape[axis])`.\n validate_indices: Deprecated, does nothing. Indices are always validated on\n CPU, never validated on GPU.\n\n Caution: On CPU, if an out of bound index is found, an error is raised.\n On GPU, if an out of bound index is found, a 0 is stored in the\n corresponding output value.\n axis: A `Tensor`. Must be one of the following types: `int32`, `int64`. The\n `axis` in `params` to gather `indices` from. Must be greater than or equal\n to `batch_dims`. Defaults to the first non-batch dimension. Supports\n negative indexes.\n batch_dims: An `integer`. The number of batch dimensions. Must be less\n than or equal to `rank(indices)`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor`. Has the same type as `params`.\n \"\"\"\n del validate_indices\n\n if axis is None:\n axis = batch_dims\n if tensor_util.constant_value(axis) != 0:\n return gen_array_ops.gather_v2(\n params, indices, axis, batch_dims=batch_dims, name=name)\n try:\n # TODO(apassos) find a less bad way of detecting resource variables\n # without introducing a circular dependency.\n return params.sparse_read(indices, name=name)\n except AttributeError:\n return gen_array_ops.gather_v2(params, indices, axis, name=name)\n\n\n@tf_export(\"gather\", v1=[])\[email protected]_dispatch_support\ndef gather_v2(params,\n indices,\n validate_indices=None,\n axis=None,\n batch_dims=0,\n name=None):\n return gather(\n params,\n indices,\n validate_indices=validate_indices,\n name=name,\n axis=axis,\n batch_dims=batch_dims)\n\n\ngather_v2.__doc__ = gather.__doc__\n\n\n@tf_export(v1=[\"batch_gather\"])\[email protected]_dispatch_support\[email protected](\n \"2017-10-25\", \"`tf.batch_gather` is deprecated, please use `tf.gather` \"\n \"with `batch_dims=-1` instead.\") # pylint: disable=missing-docstring\ndef batch_gather(params, indices, name=None):\n \"\"\"Gather slices from params according to indices with leading batch dims.\"\"\"\n with ops.name_scope(name, \"BatchGather\", [params, indices]):\n indices = ops.convert_to_tensor(indices, name=\"indices\")\n params = ops.convert_to_tensor(params, name=\"params\")\n if indices.shape.ndims is None:\n raise ValueError(\n \"batch_gather does not allow indices with unknown shape.\")\n return _batch_gather(params, indices, batch_dims=indices.shape.ndims - 1)\n\n\ndef _batch_gather(params, indices, batch_dims, axis=None):\n r\"\"\"Gather slices from params according to indices with leading batch dims.\n\n This operation assumes that the leading `batch_dims` dimensions of `indices`\n and `params` are batch dimensions; and performs a `tf.gather` operation within\n each batch. (If `batch_dims` is not specified, then it defaults to\n `rank(indices)-1`.) In the case in which `batch_dims==0`, this operation\n is equivalent to `tf.gather`.\n\n Args:\n params: A Tensor. The tensor from which to gather values.\n indices: A Tensor. Must be one of the following types: int32, int64. Index\n tensor. Must be in range `[0, params.shape[batch_dims]]`.\n batch_dims: An integer or none. The number of batch dimensions. Must be\n less than `rank(indices)`. Defaults to `rank(indices) - 1` if None.\n axis: A `Tensor`. Must be one of the following types: `int32`, `int64`. The\n `axis` in `params` to gather `indices` from. Must be greater than or equal\n to `batch_dims`. Defaults to the first non-batch dimension. Supports\n negative indexes.\n\n Returns:\n A Tensor. Has the same type as `params`.\n\n Raises:\n ValueError: if `indices` has an unknown shape.\n \"\"\"\n if batch_dims is not None and not isinstance(batch_dims, int):\n raise TypeError(\"batch_dims must be an int; got %r\" % (batch_dims,))\n indices = ops.convert_to_tensor(indices, name=\"indices\")\n params = ops.convert_to_tensor(params, name=\"params\")\n\n indices_ndims = indices.shape.ndims\n if indices_ndims is None:\n raise ValueError(\"tf.gather does not allow indices with unknown \"\n \"rank when batch_dims is specified.\")\n if batch_dims is None:\n batch_dims = indices_ndims - 1\n if batch_dims < 0:\n batch_dims += indices_ndims\n if batch_dims < 0 or batch_dims >= indices_ndims:\n raise ValueError(\"batch_dims = %d must be less than rank(indices) = %d\" %\n (batch_dims, indices_ndims))\n if params.shape.ndims is not None and batch_dims >= params.shape.ndims:\n raise ValueError(\"batch_dims = %d must be less than rank(params) = %d\" %\n (batch_dims, params.shape.ndims))\n\n # Handle axis by transposing the axis dimension to be the first non-batch\n # dimension, recursively calling batch_gather with axis=0, and then\n # transposing the result to put the pre-axis dimensions before the indices\n # dimensions.\n if axis is not None and axis != batch_dims:\n # Adjust axis to be positive.\n if not isinstance(axis, int):\n axis = tf.where(axis < 0, axis + array_ops.rank(params), axis)\n elif axis < 0 and params.shape.ndims is None:\n axis = axis + array_ops.rank(params)\n else:\n if (axis < -params.shape.ndims) or (axis >= params.shape.ndims):\n raise ValueError(\"axis (%d) out of range [%d, %d)\" %\n (axis, -params.shape.ndims, params.shape.ndims))\n if axis < 0:\n axis += params.shape.ndims\n if axis < batch_dims:\n raise ValueError(\"batch_dims = %d must be less than or equal to \"\n \"axis = %d\" % (batch_dims, axis))\n\n # Move params[axis] up to params[batch_dims].\n perm = [\n list(range(batch_dims)), [axis],\n gen_math_ops._range(batch_dims, axis, 1),\n gen_math_ops._range(axis + 1, rank(params), 1)\n ]\n params = transpose(params, concat(perm, axis=0))\n\n result = _batch_gather(params, indices, batch_dims=batch_dims)\n\n # Move the result dimensions corresponding to params[batch_dims:axis]\n # to just before the dimensions corresponding to indices[batch_dims:].\n params_start = indices_ndims + axis - batch_dims\n perm = [\n list(range(batch_dims)),\n gen_math_ops._range(indices_ndims, params_start, 1),\n list(range(batch_dims, indices_ndims)),\n gen_math_ops._range(params_start, rank(result), 1)\n ]\n return transpose(result, perm=concat(perm, axis=0))\n\n indices_shape = shape(indices)\n params_shape = shape(params)\n batch_indices = indices\n indices_dtype = indices.dtype.base_dtype\n accum_dim_value = ones((), dtype=indices_dtype)\n # Use correct type for offset index computation\n casted_params_shape = gen_math_ops.cast(params_shape, indices_dtype)\n for dim in range(batch_dims, 0, -1):\n dim_value = casted_params_shape[dim - 1]\n accum_dim_value *= casted_params_shape[dim]\n start = zeros((), dtype=indices_dtype)\n step = ones((), dtype=indices_dtype)\n dim_indices = gen_math_ops._range(start, dim_value, step)\n dim_indices *= accum_dim_value\n dim_shape = stack(\n [1] * (dim - 1) + [dim_value] + [1] * (indices_ndims - dim), axis=0)\n batch_indices += reshape(dim_indices, dim_shape)\n\n flat_indices = reshape(batch_indices, [-1])\n outer_shape = params_shape[batch_dims + 1:]\n flat_inner_shape = gen_math_ops.prod(params_shape[:batch_dims + 1], [0],\n False)\n\n flat_params = reshape(params, concat([[flat_inner_shape], outer_shape],\n axis=0))\n flat_result = gather(flat_params, flat_indices)\n result = reshape(flat_result, concat([indices_shape, outer_shape], axis=0))\n final_shape = indices.get_shape()[:batch_dims].merge_with(\n params.get_shape()[:batch_dims])\n final_shape = final_shape.concatenate(indices.get_shape().dims[batch_dims:])\n final_shape = final_shape.concatenate(params.get_shape()[batch_dims + 1:])\n result.set_shape(final_shape)\n return result\n\n\n@tf_export(v1=[\"gather_nd\", \"manip.gather_nd\"])\[email protected]_dispatch_support\n@deprecated_endpoints(\"manip.gather_nd\")\ndef gather_nd(params, indices, name=None, batch_dims=0):\n r\"\"\"Gather slices from `params` into a Tensor with shape specified by `indices`.\n\n `indices` is an K-dimensional integer tensor, best thought of as a\n (K-1)-dimensional tensor of indices into `params`, where each element defines\n a slice of `params`:\n\n output[\\\\(i_0, ..., i_{K-2}\\\\)] = params[indices[\\\\(i_0, ..., i_{K-2}\\\\)]]\n\n Whereas in `tf.gather` `indices` defines slices into the first\n dimension of `params`, in `tf.gather_nd`, `indices` defines slices into the\n first `N` dimensions of `params`, where `N = indices.shape[-1]`.\n\n The last dimension of `indices` can be at most the rank of\n `params`:\n\n indices.shape[-1] <= params.rank\n\n The last dimension of `indices` corresponds to elements\n (if `indices.shape[-1] == params.rank`) or slices\n (if `indices.shape[-1] < params.rank`) along dimension `indices.shape[-1]`\n of `params`. The output tensor has shape\n\n indices.shape[:-1] + params.shape[indices.shape[-1]:]\n\n Additionally both 'params' and 'indices' can have M leading batch\n dimensions that exactly match. In this case 'batch_dims' must be M.\n\n Note that on CPU, if an out of bound index is found, an error is returned.\n On GPU, if an out of bound index is found, a 0 is stored in the\n corresponding output value.\n\n Some examples below.\n\n Simple indexing into a matrix:\n\n ```python\n indices = [[0, 0], [1, 1]]\n params = [['a', 'b'], ['c', 'd']]\n output = ['a', 'd']\n ```\n\n Slice indexing into a matrix:\n\n ```python\n indices = [[1], [0]]\n params = [['a', 'b'], ['c', 'd']]\n output = [['c', 'd'], ['a', 'b']]\n ```\n\n Indexing into a 3-tensor:\n\n ```python\n indices = [[1]]\n params = [[['a0', 'b0'], ['c0', 'd0']],\n [['a1', 'b1'], ['c1', 'd1']]]\n output = [[['a1', 'b1'], ['c1', 'd1']]]\n\n\n indices = [[0, 1], [1, 0]]\n params = [[['a0', 'b0'], ['c0', 'd0']],\n [['a1', 'b1'], ['c1', 'd1']]]\n output = [['c0', 'd0'], ['a1', 'b1']]\n\n\n indices = [[0, 0, 1], [1, 0, 1]]\n params = [[['a0', 'b0'], ['c0', 'd0']],\n [['a1', 'b1'], ['c1', 'd1']]]\n output = ['b0', 'b1']\n ```\n\n The examples below are for the case when only indices have leading extra\n dimensions. If both 'params' and 'indices' have leading batch dimensions, use\n the 'batch_dims' parameter to run gather_nd in batch mode.\n\n Batched indexing into a matrix:\n\n ```python\n indices = [[[0, 0]], [[0, 1]]]\n params = [['a', 'b'], ['c', 'd']]\n output = [['a'], ['b']]\n ```\n\n Batched slice indexing into a matrix:\n\n ```python\n indices = [[[1]], [[0]]]\n params = [['a', 'b'], ['c', 'd']]\n output = [[['c', 'd']], [['a', 'b']]]\n ```\n\n Batched indexing into a 3-tensor:\n\n ```python\n indices = [[[1]], [[0]]]\n params = [[['a0', 'b0'], ['c0', 'd0']],\n [['a1', 'b1'], ['c1', 'd1']]]\n output = [[[['a1', 'b1'], ['c1', 'd1']]],\n [[['a0', 'b0'], ['c0', 'd0']]]]\n\n indices = [[[0, 1], [1, 0]], [[0, 0], [1, 1]]]\n params = [[['a0', 'b0'], ['c0', 'd0']],\n [['a1', 'b1'], ['c1', 'd1']]]\n output = [[['c0', 'd0'], ['a1', 'b1']],\n [['a0', 'b0'], ['c1', 'd1']]]\n\n\n indices = [[[0, 0, 1], [1, 0, 1]], [[0, 1, 1], [1, 1, 0]]]\n params = [[['a0', 'b0'], ['c0', 'd0']],\n [['a1', 'b1'], ['c1', 'd1']]]\n output = [['b0', 'b1'], ['d0', 'c1']]\n ```\n\n Examples with batched 'params' and 'indices':\n\n ```python\n batch_dims = 1\n indices = [[1], [0]]\n params = [[['a0', 'b0'], ['c0', 'd0']],\n [['a1', 'b1'], ['c1', 'd1']]]\n output = [['c0', 'd0'], ['a1', 'b1']]\n\n batch_dims = 1\n indices = [[[1]], [[0]]]\n params = [[['a0', 'b0'], ['c0', 'd0']],\n [['a1', 'b1'], ['c1', 'd1']]]\n output = [[['c0', 'd0']], [['a1', 'b1']]]\n\n batch_dims = 1\n indices = [[[1, 0]], [[0, 1]]]\n params = [[['a0', 'b0'], ['c0', 'd0']],\n [['a1', 'b1'], ['c1', 'd1']]]\n output = [['c0'], ['b1']]\n ```\n\n See also `tf.gather`.\n\n Args:\n params: A `Tensor`. The tensor from which to gather values.\n indices: A `Tensor`. Must be one of the following types: `int32`, `int64`.\n Index tensor.\n name: A name for the operation (optional).\n batch_dims: An integer or a scalar 'Tensor'. The number of batch dimensions.\n\n Returns:\n A `Tensor`. Has the same type as `params`.\n \"\"\"\n batch_dims_ = tensor_util.constant_value(batch_dims)\n if batch_dims_ is not None:\n batch_dims = int(batch_dims_)\n if batch_dims == 0:\n try:\n # TODO(apassos) find a less bad way of detecting resource variables\n # without introducing a circular dependency.\n return params.gather_nd(indices, name=name)\n except AttributeError:\n return gen_array_ops.gather_nd(params, indices, name=name)\n else:\n return batch_gather_nd(params, indices, batch_dims=batch_dims, name=name)\n\n\n@tf_export(\"gather_nd\", v1=[])\[email protected]_dispatch_support\ndef gather_nd_v2(params, indices, batch_dims=0, name=None):\n return gather_nd(params, indices, name=name, batch_dims=batch_dims)\n\n\ngather_nd_v2.__doc__ = gather_nd.__doc__\n\n\ndef batch_gather_nd(params, indices, batch_dims, name=None):\n \"\"\"gather_nd implementation with batch support.\"\"\"\n with ops.name_scope(name, \"BatchGatherND\", [params, indices]):\n indices = ops.convert_to_tensor(indices, name=\"indices\")\n params = ops.convert_to_tensor(params, name=\"params\")\n\n if not isinstance(batch_dims, int):\n raise TypeError(\"batch_dims must be an int; got %r\" % (batch_dims,))\n if batch_dims < 0:\n raise ValueError(\"tf.gather_nd does not allow negative batch_dims.\")\n params_ndims = params.shape.ndims\n indices_ndims = indices.shape.ndims\n if indices_ndims is not None and batch_dims >= indices_ndims:\n raise ValueError(\"batch_dims = %d must be less than rank(indices) = %d\" %\n (batch_dims, indices_ndims))\n if params_ndims is not None and batch_dims >= params_ndims:\n raise ValueError(\"batch_dims = %d must be less than rank(params) = %d\" %\n (batch_dims, params_ndims))\n\n expand = batch_dims == 0\n if expand:\n # Normally gather_nd will be called when batch_dims == 0.\n # But if this function is called with batch_dims = 0, e.g. for testing\n # purposes, this adds a dummy batch dimension to make batch_dims = 1.\n params = expand_dims(params, axis=0)\n indices = expand_dims(indices, axis=0)\n batch_dims = 1\n\n params_shape = shape(params)\n indices_shape = shape(indices)\n batch_shape = params_shape[:batch_dims]\n batch_size = gen_math_ops.prod(batch_shape, [0])\n index_internal_ndims = rank(indices) - batch_dims - 1\n indices_internal_shape = indices_shape[batch_dims:-1]\n\n # Assuming a 'params' with shape [b1, ..., bM, g1, ..., gN] and an 'indices'\n # with shape [b1, ..., bM, i1, ..., iK, C], where C <= N, we need to modify\n # 'indices' s.t. it has shape [i1, ..., iK, D], where D <= M + N and slices\n # to the entire 'params' tensor.\n # Assuming we have a batch of shape [B1, B2], we use meshgrid to create a\n # grid of size B1 x B2.\n batch_dim_list = unstack(batch_shape, axis=0)\n dim_ranges = [\n gen_math_ops.cast(gen_math_ops._range(0, x, 1), indices.dtype)\n for x in batch_dim_list\n ]\n mesh_list = meshgrid(*dim_ranges, indexing=\"ij\") if dim_ranges else []\n # Then we flatten and stack the tensors to form a (B1.B2) by 2 matrix.\n flat_list = [reshape(x, shape=(-1,)) for x in mesh_list]\n index_grid = transpose(stack(flat_list, axis=0))\n # We need to concatenate these batch coordinates with the internal indices.\n # concat -> index_grid [B1.B2, 2] with indices [i1, ..., iK, C]\n # So we reshape them both to [(B1.B2), i1, ..., iK, *]\n index_grid_shape = shape(index_grid)\n index_grid = reshape(\n index_grid,\n concat([\n index_grid_shape[:1],\n ones(index_internal_ndims, dtype=dtypes.int32), index_grid_shape[1:]\n ],\n axis=0))\n tile_shape = concat(((1,), indices_internal_shape, (1,)), axis=0)\n index_grid = tile(index_grid, multiples=tile_shape)\n # index_grid now has shape [(B1.B2), i1, ..., iK, 2]\n flat_shape = concat(([batch_size], indices_shape[batch_dims:]), axis=0)\n flat_indices = reshape(indices, shape=flat_shape)\n # flat_indices now has shape [(B1.B2), i1, ..., iK, C]\n indices = concat((index_grid, flat_indices), axis=-1)\n # indices has shape [(B1.B2), i1, ..., iK, 2+C]\n out = gen_array_ops.gather_nd(params, indices)\n # out has shape [(B1.B2), i1, ..., iK, N-C]. Now we reshape batch to\n # its original form.\n out_shape = shape(out)\n out = reshape(out, shape=concat((batch_shape, out_shape[1:]), axis=0))\n if expand:\n out = squeeze(out, axis=0)\n return out\n\n\[email protected]_endpoints(\"tensor_scatter_update\")\n@tf_export(\n \"tensor_scatter_nd_update\",\n v1=[\"tensor_scatter_nd_update\", \"tensor_scatter_update\"])\[email protected]_dispatch_support\ndef tensor_scatter_nd_update(tensor, indices, updates, name=None):\n \"\"\"\"Scatter `updates` into an existing tensor according to `indices`.\n\n This operation creates a new tensor by applying sparse `updates` to the\n input `tensor`. This is similar to an index assignment.\n\n ```\n # Not implemented: tensors cannot be updated inplace.\n tensor[indices] = updates\n ```\n\n If an out of bound index is found on CPU, an error is returned.\n\n > **WARNING**: There are some GPU specific semantics for this operation.\n >\n > - If an out of bound index is found, the index is ignored.\n > - The order in which updates are applied is nondeterministic, so the output\n > will be nondeterministic if `indices` contains duplicates.\n\n This operation is very similar to `tf.scatter_nd`, except that the updates are\n scattered onto an existing tensor (as opposed to a zero-tensor). If the memory\n for the existing tensor cannot be re-used, a copy is made and updated.\n\n In general:\n\n * `indices` is an integer tensor - the indices to update in `tensor`.\n * `indices` has **at least two** axes, the last axis is the depth of the\n index vectors.\n * For each index vector in `indices` there is a corresponding entry in\n `updates`.\n * If the length of the index vectors matches the rank of the `tensor`, then\n the index vectors each point to scalars in `tensor` and each update is a\n scalar.\n * If the length of the index vectors is less than the rank of `tensor`, then\n the index vectors each point to slices of `tensor` and shape of the updates\n must match that slice.\n\n Overall this leads to the following shape constraints:\n\n ```\n assert tf.rank(indices) >= 2\n index_depth = indices.shape[-1]\n batch_shape = indices.shape[:-1]\n assert index_depth <= tf.rank(tensor)\n outer_shape = tensor.shape[:index_depth]\n inner_shape = tensor.shape[index_depth:]\n assert updates.shape == batch_shape + inner_shape\n ```\n\n Typical usage is often much simpler than this general form, and it\n can be better understood starting with simple examples:\n\n ### Scalar updates\n\n The simplest usage inserts scalar elements into a tensor by index.\n In this case, the `index_depth` must equal the rank of the\n input `tensor`, slice each column of `indices` is an index into an axis of the\n input `tensor`.\n\n In this simplest case the shape constraints are:\n\n ```\n num_updates, index_depth = indices.shape.as_list()\n assert updates.shape == [num_updates]\n assert index_depth == tf.rank(tensor)`\n ```\n\n For example, to insert 4 scattered elements in a rank-1 tensor with\n 8 elements.\n\n <div style=\"width:70%; margin:auto; margin-bottom:10px; margin-top:20px;\">\n <img style=\"width:100%\"\n src=\"https://www.tensorflow.org/images/ScatterNd1.png\">\n </div>\n\n This scatter operation would look like this:\n\n >>> tensor = [0, 0, 0, 0, 0, 0, 0, 0] # tf.rank(tensor) == 1\n >>> indices = [[1], [3], [4], [7]] # num_updates == 4, index_depth == 1\n >>> updates = [9, 10, 11, 12] # num_updates == 4\n >>> print(tf.tensor_scatter_nd_update(tensor, indices, updates))\n tf.Tensor([ 0 9 0 10 11 0 0 12], shape=(8,), dtype=int32)\n\n The length (first axis) of `updates` must equal the length of the `indices`:\n `num_updates`. This is the number of updates being inserted. Each scalar\n update is inserted into `tensor` at the indexed location.\n\n For a higher rank input `tensor` scalar updates can be inserted by using an\n `index_depth` that matches `tf.rank(tensor)`:\n\n >>> tensor = [[1, 1], [1, 1], [1, 1]] # tf.rank(tensor) == 2\n >>> indices = [[0, 1], [2, 0]] # num_updates == 2, index_depth == 2\n >>> updates = [5, 10] # num_updates == 2\n >>> print(tf.tensor_scatter_nd_update(tensor, indices, updates))\n tf.Tensor(\n [[ 1 5]\n [ 1 1]\n [10 1]], shape=(3, 2), dtype=int32)\n\n ### Slice updates\n\n When the input `tensor` has more than one axis scatter can be used to update\n entire slices.\n\n In this case it's helpful to think of the input `tensor` as being a two level\n array-of-arrays. The shape of this two level array is split into the\n `outer_shape` and the `inner_shape`.\n\n `indices` indexes into the outer level of the input tensor (`outer_shape`).\n and replaces the sub-array at that location with the corresponding item from\n the `updates` list. The shape of each update is `inner_shape`.\n\n When updating a list of slices the shape constraints are:\n\n ```\n num_updates, index_depth = indices.shape.as_list()\n inner_shape = tensor.shape[:index_depth]\n outer_shape = tensor.shape[index_depth:]\n assert updates.shape == [num_updates, inner_shape]\n ```\n\n For example, to update rows of a `(6, 3)` `tensor`:\n\n >>> tensor = tf.zeros([6, 3], dtype=tf.int32)\n\n Use an index depth of one.\n\n >>> indices = tf.constant([[2], [4]]) # num_updates == 2, index_depth == 1\n >>> num_updates, index_depth = indices.shape.as_list()\n\n The `outer_shape` is `6`, the inner shape is `3`:\n\n >>> outer_shape = tensor.shape[:index_depth]\n >>> inner_shape = tensor.shape[index_depth:]\n\n 2 rows are being indexed so 2 `updates` must be supplied.\n Each update must be shaped to match the `inner_shape`.\n\n >>> # num_updates == 2, inner_shape==3\n >>> updates = tf.constant([[1, 2, 3],\n ... [4, 5, 6]])\n\n Altogether this gives:\n\n >>> tf.tensor_scatter_nd_update(tensor, indices, updates).numpy()\n array([[0, 0, 0],\n [0, 0, 0],\n [1, 2, 3],\n [0, 0, 0],\n [4, 5, 6],\n [0, 0, 0]], dtype=int32)\n\n #### More slice update examples\n\n A tensor representing a batch of uniformly sized video clips naturally has 5\n axes: `[batch_size, time, width, height, channels]`.\n\n For example:\n\n >>> batch_size, time, width, height, channels = 13,11,7,5,3\n >>> video_batch = tf.zeros([batch_size, time, width, height, channels])\n\n To replace a selection of video clips:\n * Use an `index_depth` of 1 (indexing the `outer_shape`: `[batch_size]`)\n * Provide updates each with a shape matching the `inner_shape`:\n `[time, width, height, channels]`.\n\n To replace the first two clips with ones:\n\n >>> indices = [[0],[1]]\n >>> new_clips = tf.ones([2, time, width, height, channels])\n >>> tf.tensor_scatter_nd_update(video_batch, indices, new_clips)\n\n To replace a selection of frames in the videos:\n\n * `indices` must have an `index_depth` of 2 for the `outer_shape`:\n `[batch_size, time]`.\n * `updates` must be shaped like a list of images. Each update must have a\n shape, matching the `inner_shape`: `[width, height, channels]`.\n\n To replace the first frame of the first three video clips:\n\n >>> indices = [[0, 0], [1, 0], [2, 0]] # num_updates=3, index_depth=2\n >>> new_images = tf.ones([\n ... # num_updates=3, inner_shape=(width, height, channels)\n ... 3, width, height, channels])\n >>> tf.tensor_scatter_nd_update(video_batch, indices, new_images)\n\n ### Folded indices\n\n In simple cases it's convenient to think of `indices` and `updates` as\n lists, but this is not a strict requirement. Instead of a flat `num_updates`,\n the `indices` and `updates` can be folded into a `batch_shape`. This\n `batch_shape` is all axes of the `indices`, except for the innermost\n `index_depth` axis.\n\n ```\n index_depth = indices.shape[-1]\n batch_shape = indices.shape[:-1]\n ```\n\n Note: The one exception is that the `batch_shape` cannot be `[]`. You can't\n update a single index by passing indices with shape `[index_depth]`.\n\n `updates` must have a matching `batch_shape` (the axes before `inner_shape`).\n\n ```\n assert updates.shape == batch_shape + inner_shape\n ```\n\n Note: The result is equivalent to flattening the `batch_shape` axes of\n `indices` and `updates`. This generalization just avoids the need\n for reshapes when it is more natural to construct \"folded\" indices and\n updates.\n\n With this generalization the full shape constraints are:\n\n ```\n assert tf.rank(indices) >= 2\n index_depth = indices.shape[-1]\n batch_shape = indices.shape[:-1]\n assert index_depth <= tf.rank(tensor)\n outer_shape = tensor.shape[:index_depth]\n inner_shape = tensor.shape[index_depth:]\n assert updates.shape == batch_shape + inner_shape\n ```\n\n For example, to draw an `X` on a `(5,5)` matrix start with these indices:\n\n >>> tensor = tf.zeros([5,5])\n >>> indices = tf.constant([\n ... [[0,0],\n ... [1,1],\n ... [2,2],\n ... [3,3],\n ... [4,4]],\n ... [[0,4],\n ... [1,3],\n ... [2,2],\n ... [3,1],\n ... [4,0]],\n ... ])\n >>> indices.shape.as_list() # batch_shape == [2, 5], index_depth == 2\n [2, 5, 2]\n\n Here the `indices` do not have a shape of `[num_updates, index_depth]`, but a\n shape of `batch_shape+[index_depth]`.\n\n Since the `index_depth` is equal to the rank of `tensor`:\n\n * `outer_shape` is `(5,5)`\n * `inner_shape` is `()` - each update is scalar\n * `updates.shape` is `batch_shape + inner_shape == (5,2) + ()`\n\n >>> updates = [\n ... [1,1,1,1,1],\n ... [1,1,1,1,1],\n ... ]\n\n Putting this together gives:\n\n >>> tf.tensor_scatter_nd_update(tensor, indices, updates).numpy()\n array([[1., 0., 0., 0., 1.],\n [0., 1., 0., 1., 0.],\n [0., 0., 1., 0., 0.],\n [0., 1., 0., 1., 0.],\n [1., 0., 0., 0., 1.]], dtype=float32)\n\n Args:\n tensor: Tensor to copy/update.\n indices: Indices to update.\n updates: Updates to apply at the indices.\n name: Optional name for the operation.\n\n Returns:\n A new tensor with the given shape and updates applied according to the\n indices.\n \"\"\"\n return gen_array_ops.tensor_scatter_update(\n tensor=tensor, indices=indices, updates=updates, name=name)\n\n\n# Define quantize_v2 here in order to make name the second-to-last attribute,\n# because round_mode was added later.\n# (And also now because of 'axis' processing).\n@tf_export(v1=[\"quantize_v2\"])\[email protected]_dispatch_support\[email protected](\n \"2017-10-25\",\n \"`tf.quantize_v2` is deprecated, please use `tf.quantization.quantize` \"\n \"instead.\") # pylint: disable=missing-docstring\ndef quantize_v2(\n input, # pylint: disable=redefined-builtin\n min_range,\n max_range,\n T,\n mode=\"MIN_COMBINED\",\n name=None,\n round_mode=\"HALF_AWAY_FROM_ZERO\",\n narrow_range=False,\n axis=None,\n ensure_minimum_range=0.01):\n if axis is None:\n axis = -1\n elif axis < 0:\n if input.shape.ndims is None:\n raise ValueError(\"input should have known rank to use negative axis.\")\n axis %= input.shape.ndims\n\n if ensure_minimum_range != 0.01:\n return gen_array_ops.quantize_v2(\n input,\n min_range,\n max_range,\n T=T,\n mode=mode,\n name=name,\n round_mode=round_mode,\n narrow_range=narrow_range,\n axis=axis,\n ensure_minimum_range=ensure_minimum_range)\n return gen_array_ops.quantize_v2(\n input,\n min_range,\n max_range,\n T=T,\n mode=mode,\n name=name,\n round_mode=round_mode,\n narrow_range=narrow_range,\n axis=axis)\n\n\nquantize_v2.__doc__ = \"\"\"Please use `tf.quantization.quantize` instead.\"\"\"\n\n\n# We want to expose tf.quantization.quantize instead of\n# tf.quantization.quantize; we can deprecate tf.quantization.quantize in next\n# version of TensorFlow.\n@tf_export(\"quantization.quantize\", v1=[\"quantization.quantize\", \"quantize\"])\[email protected]_dispatch_support\[email protected]_endpoints(\"quantize\")\ndef quantize(\n input, # pylint: disable=redefined-builtin\n min_range,\n max_range,\n T,\n mode=\"MIN_COMBINED\",\n round_mode=\"HALF_AWAY_FROM_ZERO\",\n name=None,\n narrow_range=False,\n axis=None,\n ensure_minimum_range=0.01):\n \"\"\"Quantize the input tensor.\"\"\"\n if ensure_minimum_range != 0.01:\n return quantize_v2(\n input,\n min_range,\n max_range,\n T,\n mode=mode,\n round_mode=round_mode,\n name=name,\n narrow_range=narrow_range,\n axis=axis,\n ensure_minimum_range=ensure_minimum_range)\n return quantize_v2(\n input,\n min_range,\n max_range,\n T,\n mode=mode,\n round_mode=round_mode,\n name=name,\n narrow_range=narrow_range,\n axis=axis)\n\n\n@tf_export(\"quantization.dequantize\", v1=[\"quantization.dequantize\",\n \"dequantize\"])\[email protected]_dispatch_support\[email protected]_endpoints(\"dequantize\")\ndef dequantize( # pylint: disable=missing-docstring\n input, # pylint: disable=redefined-builtin\n min_range,\n max_range,\n mode=\"MIN_COMBINED\",\n name=None,\n axis=None,\n narrow_range=False,\n dtype=dtypes.float32):\n if axis is None:\n axis = -1\n elif axis < 0:\n if input.shape.ndims is None:\n raise ValueError(\"input should have known rank to use negative axis.\")\n axis %= input.shape.ndims\n\n if axis >= 0 or narrow_range:\n return gen_array_ops.dequantize(\n input,\n min_range,\n max_range,\n mode=mode,\n name=name,\n narrow_range=narrow_range,\n axis=axis,\n dtype=dtype)\n return gen_array_ops.dequantize(\n input, min_range, max_range, mode=mode, name=name, dtype=dtype)\n\n\ndequantize.__doc__ = gen_array_ops.dequantize.__doc__\n\n\n@tf_export(\"quantization.quantize_and_dequantize\")\[email protected]_dispatch_support\[email protected](None,\n \"This Op has been deprecated, use\" +\n \"`quantize_and_dequantize_v2` instead. To \" +\n \"To simulate the V1 the behavior of \" +\n \"tf.quantization.quantize_and_dequantize(...) use \" +\n \"tf.grad_pass_through(\" +\n \"tf.quantization.quantize_and_dequantize_v2)(...).\")\ndef quantize_and_dequantize(\n input, # pylint: disable=redefined-builtin\n input_min,\n input_max,\n signed_input=True,\n num_bits=8,\n range_given=False,\n round_mode=\"HALF_TO_EVEN\",\n name=None,\n narrow_range=False,\n axis=None):\n \"\"\"Quantizes then dequantizes a tensor.\n\n Args:\n input: A `Tensor` to quantize and dequantize.\n input_min: If range_given=True, the minimum input value, that needs to be\n represented in the quantized representation. If axis is specified, this\n should be a vector of minimum values for each slice along axis.\n input_max: If range_given=True, the maximum input value that needs to be\n represented in the quantized representation. If axis is specified, this\n should be a vector of maximum values for each slice along axis.\n signed_input: True if the quantization is signed or unsigned.\n num_bits: The bitwidth of the quantization.\n range_given: If true use `input_min` and `input_max` for the range of the\n input, otherwise determine min and max from the input `Tensor`.\n round_mode: Rounding mode when rounding from float values to quantized ones.\n one of ['HALF_TO_EVEN', 'HALF_UP']\n name: Optional name for the operation.\n narrow_range: If true, then the absolute value of the quantized minimum\n value is the same as the quantized maximum value, instead of 1 greater.\n i.e. for 8 bit quantization, the minimum value is -127 instead of -128.\n axis: Integer. If specified, refers to a dimension of the input tensor, such\n that quantization will be per slice along that dimension.\n\n Returns:\n A `Tensor`. Each element is the result of quantizing and dequantizing the\n corresponding element of `input`.\n \"\"\"\n if axis is None:\n axis = -1\n elif axis < 0:\n if input.shape.ndims is None:\n raise ValueError(\"input should have known rank to use negative axis.\")\n axis %= input.shape.ndims\n\n return gen_array_ops.quantize_and_dequantize_v2(\n input,\n input_min=input_min,\n input_max=input_max,\n signed_input=signed_input,\n num_bits=num_bits,\n range_given=range_given,\n round_mode=round_mode,\n narrow_range=narrow_range,\n axis=axis,\n name=name)\n\n\n@tf_export(\"quantization.quantize_and_dequantize_v2\")\[email protected]_dispatch_support\ndef quantize_and_dequantize_v2(\n input, # pylint: disable=redefined-builtin\n input_min,\n input_max,\n signed_input=True,\n num_bits=8,\n range_given=False,\n round_mode=\"HALF_TO_EVEN\",\n name=None,\n narrow_range=False,\n axis=None):\n \"\"\"Quantizes then dequantizes a tensor.\n\n Updates the gradient definition for quantization that is outside the range to\n be 0.To simulate the V1 the behavior of\n tf.quantization.quantize_and_dequantize(...) use\n tf.grad_pass_through(tf.quantization.quantize_and_dequantize_v2)(...).\n\n Example usage:\n\n ```python\n def getQuantizeOp(input):\n input_tensor = tf.placeholder(tf.float32, shape=[4, 4])\n net = tf.quantization.quantize_and_dequantize(input,\n input_min=min_threshold,\n input_max=max_threshold,\n range_given=True)\n\n To simulate v1 behavior:\n\n def testDecomposeQuantizeDequantize(self):\n def f(input_tensor):\n return tf.quantization.quantize_and_dequantize_v2(input_tensor,\n input_min = 5.0,\n input_max= -10.0,\n range_given=True)\n input_tensor = tf.placeholder(tf.float32, shape=[4, 4])\n net = tf.grad_pass_through(f)(input_tensor)\n ```\n\n Args:\n input: A `Tensor` to quantize and dequantize.\n input_min: If range_given=True, the minimum input value, that needs to be\n represented in the quantized representation. If axis is specified, this\n should be a vector of minimum values for each slice along axis.\n input_max: If range_given=True, the maximum input value that needs to be\n represented in the quantized representation. If axis is specified, this\n should be a vector of maximum values for each slice along axis.\n signed_input: True if the quantization is signed or unsigned.\n num_bits: The bitwidth of the quantization.\n range_given: If true use `input_min` and `input_max` for the range of the\n input, otherwise determine min and max from the input `Tensor`.\n round_mode: Rounding mode when rounding from float values to quantized ones.\n one of ['HALF_TO_EVEN', 'HALF_UP']\n name: Optional name for the operation.\n narrow_range: If true, then the absolute value of the quantized minimum\n value is the same as the quantized maximum value, instead of 1 greater.\n i.e. for 8 bit quantization, the minimum value is -127 instead of -128.\n axis: Integer. If specified, refers to a dimension of the input tensor, such\n that quantization will be per slice along that dimension.\n\n Returns:\n A `Tensor`. Each element is the result of quantizing and dequantizing the\n corresponding element of `input`.\n \"\"\"\n if axis is None:\n axis = -1\n elif axis < 0:\n if input.shape.ndims is None:\n raise ValueError(\"input should have known rank to use negative axis.\")\n axis %= input.shape.ndims\n\n return gen_array_ops.quantize_and_dequantize_v4(\n input,\n input_min=input_min,\n input_max=input_max,\n signed_input=signed_input,\n num_bits=num_bits,\n range_given=range_given,\n round_mode=round_mode,\n narrow_range=narrow_range,\n axis=axis,\n name=name)\n\n\n@tf_export(\"searchsorted\")\[email protected]_dispatch_support\ndef searchsorted(sorted_sequence,\n values,\n side=\"left\",\n out_type=dtypes.int32,\n name=None):\n \"\"\"Searches for where a value would go in a sorted sequence.\n\n This is not a method for checking containment (like python `in`).\n\n The typical use case for this operation is \"binning\", \"bucketing\", or\n \"discretizing\". The `values` are assigned to bucket-indices based on the\n **edges** listed in `sorted_sequence`. This operation\n returns the bucket-index for each value.\n\n >>> edges = [-1, 3.3, 9.1, 10.0]\n >>> values = [0.0, 4.1, 12.0]\n >>> tf.searchsorted(edges, values).numpy()\n array([1, 2, 4], dtype=int32)\n\n The `side` argument controls which index is returned if a value lands exactly\n on an edge:\n\n >>> seq = [0, 3, 9, 10, 10]\n >>> values = [0, 4, 10]\n >>> tf.searchsorted(seq, values).numpy()\n array([0, 2, 3], dtype=int32)\n >>> tf.searchsorted(seq, values, side=\"right\").numpy()\n array([1, 2, 5], dtype=int32)\n\n The `axis` is not settable for this operation. It always operates on the\n innermost dimension (`axis=-1`). The operation will accept any number of\n outer dimensions. Here it is applied to the rows of a matrix:\n\n >>> sorted_sequence = [[0., 3., 8., 9., 10.],\n ... [1., 2., 3., 4., 5.]]\n >>> values = [[9.8, 2.1, 4.3],\n ... [0.1, 6.6, 4.5, ]]\n >>> tf.searchsorted(sorted_sequence, values).numpy()\n array([[4, 1, 2],\n [0, 5, 4]], dtype=int32)\n\n Note: This operation assumes that `sorted_sequence` **is sorted** along the\n innermost axis, maybe using `tf.sort(..., axis=-1)`. **If the sequence is not\n sorted no error is raised** and the content of the returned tensor is not well\n defined.\n\n Args:\n sorted_sequence: N-D `Tensor` containing a sorted sequence.\n values: N-D `Tensor` containing the search values.\n side: 'left' or 'right'; 'left' corresponds to lower_bound and 'right' to\n upper_bound.\n out_type: The output type (`int32` or `int64`). Default is `tf.int32`.\n name: Optional name for the operation.\n\n Returns:\n An N-D `Tensor` the size of `values` containing the result of applying\n either lower_bound or upper_bound (depending on side) to each value. The\n result is not a global index to the entire `Tensor`, but the index in the\n last dimension.\n\n Raises:\n ValueError: If the last dimension of `sorted_sequence >= 2^31-1` elements.\n If the total size of `values` exceeds `2^31 - 1` elements.\n If the first `N-1` dimensions of the two tensors don't match.\n \"\"\"\n sequence_size = shape_internal(sorted_sequence)[-1]\n values_size = shape_internal(values)[-1]\n sorted_sequence_2d = reshape(sorted_sequence, [-1, sequence_size])\n values_2d = reshape(values, [-1, values_size])\n if side == \"right\":\n output = gen_array_ops.upper_bound(sorted_sequence_2d, values_2d, out_type,\n name)\n elif side == \"left\":\n output = gen_array_ops.lower_bound(sorted_sequence_2d, values_2d, out_type,\n name)\n else:\n raise ValueError(\"side must be either 'right' or 'left'. Saw: %s.\" % side)\n return reshape(output, shape_internal(values))\n\n\nquantize.__doc__ = gen_array_ops.quantize_v2.__doc__\n\n\n@tf_export(\"image.extract_patches\")\[email protected]_dispatch_support\ndef extract_image_patches_v2(images, sizes, strides, rates, padding, name=None):\n r\"\"\"Extract `patches` from `images`.\n\n This op collects patches from the input image, as if applying a\n convolution. All extracted patches are stacked in the depth (last) dimension\n of the output.\n\n Specifically, the op extracts patches of shape `sizes` which are `strides`\n apart in the input image. The output is subsampled using the `rates` argument,\n in the same manner as \"atrous\" or \"dilated\" convolutions.\n\n The result is a 4D tensor which is indexed by batch, row, and column.\n `output[i, x, y]` contains a flattened patch of size `sizes[1], sizes[2]`\n which is taken from the input starting at\n `images[i, x*strides[1], y*strides[2]]`.\n\n Each output patch can be reshaped to `sizes[1], sizes[2], depth`, where\n `depth` is `images.shape[3]`.\n\n The output elements are taken from the input at intervals given by the `rate`\n argument, as in dilated convolutions.\n\n The `padding` argument has no effect on the size of each patch, it determines\n how many patches are extracted. If `VALID`, only patches which are fully\n contained in the input image are included. If `SAME`, all patches whose\n starting point is inside the input are included, and areas outside the input\n default to zero.\n\n Example:\n\n ```\n n = 10\n # images is a 1 x 10 x 10 x 1 array that contains the numbers 1 through 100\n images = [[[[x * n + y + 1] for y in range(n)] for x in range(n)]]\n\n # We generate two outputs as follows:\n # 1. 3x3 patches with stride length 5\n # 2. Same as above, but the rate is increased to 2\n tf.image.extract_patches(images=images,\n sizes=[1, 3, 3, 1],\n strides=[1, 5, 5, 1],\n rates=[1, 1, 1, 1],\n padding='VALID')\n\n # Yields:\n [[[[ 1 2 3 11 12 13 21 22 23]\n [ 6 7 8 16 17 18 26 27 28]]\n [[51 52 53 61 62 63 71 72 73]\n [56 57 58 66 67 68 76 77 78]]]]\n ```\n\n If we mark the pixels in the input image which are taken for the output with\n `*`, we see the pattern:\n\n ```\n * * * 4 5 * * * 9 10\n * * * 14 15 * * * 19 20\n * * * 24 25 * * * 29 30\n 31 32 33 34 35 36 37 38 39 40\n 41 42 43 44 45 46 47 48 49 50\n * * * 54 55 * * * 59 60\n * * * 64 65 * * * 69 70\n * * * 74 75 * * * 79 80\n 81 82 83 84 85 86 87 88 89 90\n 91 92 93 94 95 96 97 98 99 100\n ```\n\n ```\n tf.image.extract_patches(images=images,\n sizes=[1, 3, 3, 1],\n strides=[1, 5, 5, 1],\n rates=[1, 2, 2, 1],\n padding='VALID')\n\n # Yields:\n [[[[ 1 3 5 21 23 25 41 43 45]\n [ 6 8 10 26 28 30 46 48 50]]\n\n [[ 51 53 55 71 73 75 91 93 95]\n [ 56 58 60 76 78 80 96 98 100]]]]\n ```\n\n We can again draw the effect, this time using the symbols `*`, `x`, `+` and\n `o` to distinguish the patches:\n\n ```\n * 2 * 4 * x 7 x 9 x\n 11 12 13 14 15 16 17 18 19 20\n * 22 * 24 * x 27 x 29 x\n 31 32 33 34 35 36 37 38 39 40\n * 42 * 44 * x 47 x 49 x\n + 52 + 54 + o 57 o 59 o\n 61 62 63 64 65 66 67 68 69 70\n + 72 + 74 + o 77 o 79 o\n 81 82 83 84 85 86 87 88 89 90\n + 92 + 94 + o 97 o 99 o\n ```\n\n Args:\n images: A 4-D Tensor with shape `[batch, in_rows, in_cols, depth]`.\n sizes: The size of the extracted patches. Must be\n `[1, size_rows, size_cols, 1]`.\n strides: A 1-D Tensor of length 4. How far the centers of two consecutive\n patches are in the images. Must be: `[1, stride_rows, stride_cols, 1]`.\n rates: A 1-D Tensor of length 4. Must be: `[1, rate_rows, rate_cols, 1]`.\n This is the input stride, specifying how far two consecutive patch samples\n are in the input. Equivalent to extracting patches with `patch_sizes_eff =\n patch_sizes + (patch_sizes - 1) * (rates - 1)`, followed by subsampling\n them spatially by a factor of `rates`. This is equivalent to `rate` in\n dilated (a.k.a. Atrous) convolutions.\n padding: The type of padding algorithm to use.\n name: A name for the operation (optional).\n\n Returns:\n A 4-D Tensor of the same type as the input.\n \"\"\"\n return gen_array_ops.extract_image_patches(images, sizes, strides, rates,\n padding, name)\n\n\n@tf_export(v1=[\"image.extract_image_patches\", \"extract_image_patches\"])\[email protected]_dispatch_support\[email protected]_args(None, \"ksizes is deprecated, use sizes instead\",\n \"ksizes\")\ndef extract_image_patches( # pylint: disable=missing-docstring\n images,\n ksizes=None,\n strides=None,\n rates=None,\n padding=None,\n name=None,\n sizes=None):\n \"\"\"Extract patches from images and put them in the \"depth\" output dimension.\n\n Args:\n `images`: A `Tensor`. Must be one of the following types: `float32`,\n `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`,\n `uint16`, `half`, `uint32`, `uint64`. 4-D Tensor with shape\n `[batch, in_rows, in_cols, depth]`. `ksizes`: A list of `ints` that has\n length `>= 4`. The size of the sliding window for each\n dimension of `images`. `strides`: A list of `ints` that has length `>= 4`.\n 1-D of length 4. How far the centers of two consecutive\n patches are in the images. Must be:\n `[1, stride_rows, stride_cols, 1]`. `rates`: A list of `ints`\n that has length `>= 4`. 1-D of length 4. Must be: `[1, rate_rows, rate_cols,\n 1]`. This is the input stride, specifying how far two consecutive patch\n samples are in the input. Equivalent to extracting patches with\n `patch_sizes_eff = patch_sizes + (patch_sizes - 1) * (rates - 1)`,\n followed by subsampling them spatially by a factor of `rates`. This is\n equivalent to `rate` in dilated (a.k.a. Atrous) convolutions.\n `padding`: A `string` from: \"SAME\", \"VALID\". The type of padding algorithm\n to use.\n We specify the size-related attributes as: ``` ksizes = [1, ksize_rows,\n ksize_cols, 1] strides = [1, strides_rows, strides_cols, 1] rates = [1,\n rates_rows, rates_cols, 1]\n name: A name for the operation (optional). ```\n\n Returns:\n A Tensor. Has the same type as images.\n \"\"\"\n ksizes = deprecation.deprecated_argument_lookup(\"sizes\", sizes, \"ksizes\",\n ksizes)\n return gen_array_ops.extract_image_patches(images, ksizes, strides, rates,\n padding, name)\n\n\nextract_image_patches.__doc__ = gen_array_ops.extract_image_patches.__doc__\n\n\n@tf_export(\"fingerprint\")\[email protected]_dispatch_support\ndef fingerprint(data, method=\"farmhash64\", name=None):\n r\"\"\"Generates fingerprint values.\n\n Generates fingerprint values of `data`.\n\n Fingerprint op considers the first dimension of `data` as the batch dimension,\n and `output[i]` contains the fingerprint value generated from contents in\n `data[i, ...]` for all `i`.\n\n Fingerprint op writes fingerprint values as byte arrays. For example, the\n default method `farmhash64` generates a 64-bit fingerprint value at a time.\n This 8-byte value is written out as an `tf.uint8` array of size 8, in\n little-endian order.\n\n For example, suppose that `data` has data type `tf.int32` and shape (2, 3, 4),\n and that the fingerprint method is `farmhash64`. In this case, the output\n shape is (2, 8), where 2 is the batch dimension size of `data`, and 8 is the\n size of each fingerprint value in bytes. `output[0, :]` is generated from\n 12 integers in `data[0, :, :]` and similarly `output[1, :]` is generated from\n other 12 integers in `data[1, :, :]`.\n\n Note that this op fingerprints the raw underlying buffer, and it does not\n fingerprint Tensor's metadata such as data type and/or shape. For example, the\n fingerprint values are invariant under reshapes and bitcasts as long as the\n batch dimension remain the same:\n\n ```python\n tf.fingerprint(data) == tf.fingerprint(tf.reshape(data, ...))\n tf.fingerprint(data) == tf.fingerprint(tf.bitcast(data, ...))\n ```\n\n For string data, one should expect `tf.fingerprint(data) !=\n tf.fingerprint(tf.string.reduce_join(data))` in general.\n\n Args:\n data: A `Tensor`. Must have rank 1 or higher.\n method: A `Tensor` of type `tf.string`. Fingerprint method used by this op.\n Currently available method is `farmhash64`.\n name: A name for the operation (optional).\n\n Returns:\n A two-dimensional `Tensor` of type `tf.uint8`. The first dimension equals to\n `data`'s first dimension, and the second dimension size depends on the\n fingerprint algorithm.\n \"\"\"\n return gen_array_ops.fingerprint(data, method, name)\n\n\ndef convert_to_int_tensor(tensor, name, dtype=dtypes.int32):\n \"\"\"Converts the given value to an integer Tensor.\"\"\"\n tensor = ops.convert_to_tensor(tensor, name=name, preferred_dtype=dtype)\n if tensor.dtype.is_integer:\n tensor = gen_math_ops.cast(tensor, dtype)\n else:\n raise TypeError(\"%s must be an integer tensor; dtype=%s\" %\n (name, tensor.dtype))\n return tensor\n\n\ndef get_positive_axis(axis, ndims, axis_name=\"axis\", ndims_name=\"ndims\"):\n \"\"\"Validate an `axis` parameter, and normalize it to be positive.\n\n If `ndims` is known (i.e., not `None`), then check that `axis` is in the\n range `-ndims <= axis < ndims`, and return `axis` (if `axis >= 0`) or\n `axis + ndims` (otherwise).\n If `ndims` is not known, and `axis` is positive, then return it as-is.\n If `ndims` is not known, and `axis` is negative, then report an error.\n\n Args:\n axis: An integer constant\n ndims: An integer constant, or `None`\n axis_name: The name of `axis` (for error messages).\n ndims_name: The name of `ndims` (for error messages).\n\n Returns:\n The normalized `axis` value.\n\n Raises:\n ValueError: If `axis` is out-of-bounds, or if `axis` is negative and\n `ndims is None`.\n \"\"\"\n if not isinstance(axis, int):\n raise TypeError(\"%s must be an int; got %s\" %\n (axis_name, type(axis).__name__))\n if ndims is not None:\n if 0 <= axis < ndims:\n return axis\n elif -ndims <= axis < 0:\n return axis + ndims\n else:\n raise ValueError(\"%s=%s out of bounds: expected %s<=%s<%s\" %\n (axis_name, axis, -ndims, axis_name, ndims))\n elif axis < 0:\n raise ValueError(\"%s may only be negative if %s is statically known.\" %\n (axis_name, ndims_name))\n return axis\n\n\n# This op is intended to exactly match the semantics of numpy.repeat, with\n# one exception: numpy.repeat has special (and somewhat non-intuitive) behavior\n# when axis is not specified. Rather than implement that special behavior, we\n# simply make `axis` be a required argument.\n#\n# External (OSS) `tf.repeat` feature request:\n# https://github.com/tensorflow/tensorflow/issues/8246\ndef repeat_with_axis(data, repeats, axis, name=None):\n \"\"\"Repeats elements of `data`.\n\n Args:\n data: An `N`-dimensional tensor.\n repeats: A 1-D integer tensor specifying how many times each element in\n `axis` should be repeated. `len(repeats)` must equal `data.shape[axis]`.\n Supports broadcasting from a scalar value.\n axis: `int`. The axis along which to repeat values. Must be less than\n `max(N, 1)`.\n name: A name for the operation.\n\n Returns:\n A tensor with `max(N, 1)` dimensions. Has the same shape as `data`,\n except that dimension `axis` has size `sum(repeats)`.\n\n Example usage:\n\n >>> repeat(['a', 'b', 'c'], repeats=[3, 0, 2], axis=0)\n <tf.Tensor: shape=(5,), dtype=string,\n numpy=array([b'a', b'a', b'a', b'c', b'c'], dtype=object)>\n >>> repeat([[1, 2], [3, 4]], repeats=[2, 3], axis=0)\n <tf.Tensor: shape=(5, 2), dtype=int32, numpy=\n array([[1, 2],\n [1, 2],\n [3, 4],\n [3, 4],\n [3, 4]], dtype=int32)>\n >>> repeat([[1, 2], [3, 4]], repeats=[2, 3], axis=1)\n <tf.Tensor: shape=(2, 5), dtype=int32, numpy=\n array([[1, 1, 2, 2, 2],\n [3, 3, 4, 4, 4]], dtype=int32)>\n\n \"\"\"\n if not isinstance(axis, int):\n raise TypeError(\"axis must be an int; got %s\" % type(axis).__name__)\n\n with ops.name_scope(name, \"Repeat\", [data, repeats]):\n data = ops.convert_to_tensor(data, name=\"data\")\n repeats = convert_to_int_tensor(repeats, name=\"repeats\")\n repeats.shape.with_rank_at_most(1)\n\n # If `data` is a scalar, then upgrade it to a vector.\n data = _with_nonzero_rank(data)\n data_shape = shape(data)\n\n # If `axis` is negative, then convert it to a positive value.\n axis = get_positive_axis(axis, data.shape.rank, ndims_name=\"rank(data)\")\n\n # If we know that `repeats` is a scalar, then we can just tile & reshape.\n if repeats.shape.num_elements() == 1:\n repeats = reshape(repeats, [])\n expanded = expand_dims(data, axis + 1)\n tiled = tile_one_dimension(expanded, axis + 1, repeats)\n result_shape = concat([\n data_shape[:axis], [repeats * data_shape[axis]], data_shape[axis + 1:]\n ],\n axis=0)\n return reshape(tiled, result_shape)\n\n\n # Check data Tensor shapes.\n if repeats.shape.ndims == 1:\n data.shape.dims[axis].assert_is_compatible_with(repeats.shape[0])\n\n repeats = broadcast_to(repeats, [data_shape[axis]])\n repeats_original = repeats\n\n # Broadcast the `repeats` tensor so rank(repeats) == axis + 1.\n if repeats.shape.ndims != axis + 1:\n repeats_shape = shape(repeats)\n repeats_ndims = rank(repeats)\n broadcast_shape = concat(\n [data_shape[:axis + 1 - repeats_ndims], repeats_shape], axis=0)\n repeats = broadcast_to(repeats, broadcast_shape)\n repeats.set_shape([None] * (axis + 1))\n\n # Create a \"sequence mask\" based on `repeats`, where slices across `axis`\n # contain one `True` value for each repetition. E.g., if\n # `repeats = [3, 1, 2]`, then `mask = [[1, 1, 1], [1, 0, 0], [1, 1, 0]]`.\n max_repeat = gen_math_ops.maximum(\n 0, gen_math_ops._max(repeats, _all_dimensions(repeats)))\n mask = sequence_mask(repeats, max_repeat)\n\n # Add a new dimension around each value that needs to be repeated, and\n # then tile that new dimension to match the maximum number of repetitions.\n expanded = expand_dims(data, axis + 1)\n tiled = tile_one_dimension(expanded, axis + 1, max_repeat)\n\n # Use `boolean_mask` to discard the extra repeated values. This also\n # flattens all dimensions up through `axis`.\n masked = boolean_mask(tiled, mask)\n\n # Reshape the output tensor to add the outer dimensions back.\n if axis == 0:\n result = masked\n else:\n repeated_dim_size = gen_math_ops._sum(\n repeats_original,\n axis=gen_math_ops._range(0, rank(repeats_original), 1))\n result_shape = concat(\n [data_shape[:axis], [repeated_dim_size], data_shape[axis + 1:]],\n axis=0)\n result = reshape(masked, result_shape)\n\n # Preserve shape information.\n if data.shape.ndims is not None:\n new_axis_size = 0 if repeats.shape[0] == 0 else None\n result.set_shape(data.shape[:axis].concatenate(\n [new_axis_size]).concatenate(data.shape[axis + 1:]))\n\n return result\n\n\ndef tile_one_dimension(data, axis, multiple):\n \"\"\"Tiles a single dimension of a tensor.\"\"\"\n # Assumes axis is a nonnegative int.\n if data.shape.ndims is not None:\n multiples = [1] * data.shape.ndims\n multiples[axis] = multiple\n else:\n ones_value = ones(rank(data), dtypes.int32)\n multiples = concat([ones_value[:axis], [multiple], ones_value[axis + 1:]],\n axis=0)\n return tile(data, multiples)\n\n\ndef _with_nonzero_rank(data):\n \"\"\"If `data` is scalar, then add a dimension; otherwise return as-is.\"\"\"\n if data.shape.ndims is not None:\n if data.shape.ndims == 0:\n return stack([data])\n else:\n return data\n else:\n data_shape = shape(data)\n data_ndims = rank(data)\n return reshape(data, concat([[1], data_shape], axis=0)[-data_ndims:])\n\n\n@tf_export(\"repeat\")\[email protected]_dispatch_support\ndef repeat(input, repeats, axis=None, name=None): # pylint: disable=redefined-builtin\n \"\"\"Repeat elements of `input`.\n\n See also `tf.concat`, `tf.stack`, `tf.tile`.\n\n Args:\n input: An `N`-dimensional Tensor.\n repeats: An 1-D `int` Tensor. The number of repetitions for each element.\n repeats is broadcasted to fit the shape of the given axis. `len(repeats)`\n must equal `input.shape[axis]` if axis is not None.\n axis: An int. The axis along which to repeat values. By default (axis=None),\n use the flattened input array, and return a flat output array.\n name: A name for the operation.\n\n Returns:\n A Tensor which has the same shape as `input`, except along the given axis.\n If axis is None then the output array is flattened to match the flattened\n input array.\n\n Example usage:\n\n >>> repeat(['a', 'b', 'c'], repeats=[3, 0, 2], axis=0)\n <tf.Tensor: shape=(5,), dtype=string,\n numpy=array([b'a', b'a', b'a', b'c', b'c'], dtype=object)>\n\n >>> repeat([[1, 2], [3, 4]], repeats=[2, 3], axis=0)\n <tf.Tensor: shape=(5, 2), dtype=int32, numpy=\n array([[1, 2],\n [1, 2],\n [3, 4],\n [3, 4],\n [3, 4]], dtype=int32)>\n\n >>> repeat([[1, 2], [3, 4]], repeats=[2, 3], axis=1)\n <tf.Tensor: shape=(2, 5), dtype=int32, numpy=\n array([[1, 1, 2, 2, 2],\n [3, 3, 4, 4, 4]], dtype=int32)>\n\n >>> repeat(3, repeats=4)\n <tf.Tensor: shape=(4,), dtype=int32, numpy=array([3, 3, 3, 3], dtype=int32)>\n\n >>> repeat([[1,2], [3,4]], repeats=2)\n <tf.Tensor: shape=(8,), dtype=int32,\n numpy=array([1, 1, 2, 2, 3, 3, 4, 4], dtype=int32)>\n\n \"\"\"\n if axis is None:\n input = reshape(input, [-1])\n axis = 0\n return repeat_with_axis(input, repeats, axis, name)\n",
"# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Test configs for binary_op.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow.compat.v1 as tf\nfrom tensorflow.lite.testing.zip_test_utils import create_tensor_data\nfrom tensorflow.lite.testing.zip_test_utils import make_zip_of_tests\nfrom tensorflow.lite.testing.zip_test_utils import register_make_test_function\n\n\ndef make_binary_op_tests(options,\n binary_operator,\n allow_fully_quantize=False,\n expected_tf_failures=0,\n test_parameters=None):\n \"\"\"Make a set of tests to do binary ops with and without broadcast.\"\"\"\n\n if test_parameters is None:\n test_parameters = []\n\n test_parameters = test_parameters + [\n # Avoid creating all combinations to keep the test size small.\n {\n \"dtype\": [tf.float32, tf.int32],\n \"input_shape_1\": [[1, 3, 4, 3]],\n \"input_shape_2\": [[1, 3, 4, 3]],\n \"activation\": [True],\n \"fully_quantize\": [False],\n \"dynamic_range_quantize\": [False],\n },\n {\n \"dtype\": [tf.float32],\n \"input_shape_1\": [[5]],\n \"input_shape_2\": [[5]],\n \"activation\": [False, True],\n \"fully_quantize\": [False],\n \"dynamic_range_quantize\": [False],\n },\n {\n \"dtype\": [tf.float32, tf.int32, tf.int64],\n \"input_shape_1\": [[1, 3, 4, 3]],\n \"input_shape_2\": [[3]],\n \"activation\": [True, False],\n \"fully_quantize\": [False],\n \"dynamic_range_quantize\": [False],\n },\n {\n \"dtype\": [tf.float32, tf.int32],\n \"input_shape_1\": [[3]],\n \"input_shape_2\": [[1, 3, 4, 3]],\n \"activation\": [True, False],\n \"fully_quantize\": [False],\n \"dynamic_range_quantize\": [False],\n },\n {\n \"dtype\": [tf.float32],\n \"input_shape_1\": [[]],\n \"input_shape_2\": [[]],\n \"activation\": [False],\n \"fully_quantize\": [False],\n \"dynamic_range_quantize\": [False],\n },\n {\n \"dtype\": [tf.float32],\n \"input_shape_1\": [[0]],\n \"input_shape_2\": [[1]],\n \"activation\": [False],\n \"fully_quantize\": [False],\n \"dynamic_range_quantize\": [False],\n },\n {\n \"dtype\": [tf.float32],\n \"input_shape_1\": [[1, 3, 4, 3]],\n \"input_shape_2\": [[1, 3, 4, 3]],\n \"activation\": [False],\n \"fully_quantize\": [True],\n \"dynamic_range_quantize\": [False],\n },\n {\n \"dtype\": [tf.float32],\n \"input_shape_1\": [[5]],\n \"input_shape_2\": [[5]],\n \"activation\": [False],\n \"fully_quantize\": [True],\n \"dynamic_range_quantize\": [False],\n },\n {\n \"dtype\": [tf.float32],\n \"input_shape_1\": [[1, 3, 4, 3]],\n \"input_shape_2\": [[3]],\n \"activation\": [False],\n \"fully_quantize\": [True],\n \"dynamic_range_quantize\": [False],\n },\n {\n \"dtype\": [tf.float32],\n \"input_shape_1\": [[3]],\n \"input_shape_2\": [[1, 3, 4, 3]],\n \"activation\": [False],\n \"fully_quantize\": [True],\n \"dynamic_range_quantize\": [False],\n },\n {\n \"dtype\": [tf.float32],\n \"input_shape_1\": [[]],\n \"input_shape_2\": [[]],\n \"activation\": [False],\n \"fully_quantize\": [True],\n \"dynamic_range_quantize\": [False],\n },\n {\n \"dtype\": [tf.float32],\n \"input_shape_1\": [[1, 3, 4, 3]],\n \"input_shape_2\": [[1, 3, 4, 3]],\n \"activation\": [False],\n \"fully_quantize\": [False],\n \"dynamic_range_quantize\": [True],\n },\n {\n \"dtype\": [tf.float32],\n \"input_shape_1\": [[5]],\n \"input_shape_2\": [[5]],\n \"activation\": [False],\n \"fully_quantize\": [False],\n \"dynamic_range_quantize\": [True],\n },\n {\n \"dtype\": [tf.float32],\n \"input_shape_1\": [[1, 3, 4, 3]],\n \"input_shape_2\": [[3]],\n \"activation\": [False],\n \"fully_quantize\": [False],\n \"dynamic_range_quantize\": [True],\n },\n {\n \"dtype\": [tf.float32],\n \"input_shape_1\": [[3]],\n \"input_shape_2\": [[1, 3, 4, 3]],\n \"activation\": [False],\n \"fully_quantize\": [False],\n \"dynamic_range_quantize\": [True],\n },\n {\n \"dtype\": [tf.float32],\n \"input_shape_1\": [[]],\n \"input_shape_2\": [[]],\n \"activation\": [False],\n \"fully_quantize\": [False],\n \"dynamic_range_quantize\": [True],\n },\n ]\n\n # float64 types are supported via flex only.\n if options.run_with_flex and options.use_experimental_converter:\n test_parameters = test_parameters + [\n {\n \"dtype\": [tf.float64],\n \"input_shape_1\": [[7]],\n \"input_shape_2\": [[7]],\n \"activation\": [False],\n \"fully_quantize\": [False],\n \"dynamic_range_quantize\": [False],\n },\n ]\n\n # High dimension broadcasting support in MLIR converter.\n if options.use_experimental_converter:\n test_parameters = test_parameters + [\n {\n \"dtype\": [tf.float32],\n \"input_shape_1\": [[8, 7, 6, 5, 4, 3, 2, 1]],\n \"input_shape_2\": [[4, 3, 2, 1]],\n \"activation\": [False],\n \"fully_quantize\": [False],\n \"dynamic_range_quantize\": [False],\n },\n ]\n\n # test_parameters include fully_quantize option only when\n # allow_fully_quantize is True.\n if not allow_fully_quantize:\n test_parameters = [\n test_parameter for test_parameter in test_parameters\n if True not in test_parameter[\"fully_quantize\"]\n ]\n\n def build_graph(parameters):\n \"\"\"Builds the graph given the current parameters.\"\"\"\n input1 = tf.compat.v1.placeholder(\n dtype=parameters[\"dtype\"],\n name=\"input1\",\n shape=parameters[\"input_shape_1\"])\n input2 = tf.compat.v1.placeholder(\n dtype=parameters[\"dtype\"],\n name=\"input2\",\n shape=parameters[\"input_shape_2\"])\n out = binary_operator(input1, input2)\n # TODO(karimnosseir): Update condition after moving to new converter.\n if parameters[\"activation\"] and (not options.use_experimental_converter or\n (parameters[\"dtype\"] != tf.int32 and\n parameters[\"dtype\"] != tf.int64)):\n out = tf.nn.relu(out)\n return [input1, input2], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n \"\"\"Builds operand inputs for op.\"\"\"\n if allow_fully_quantize:\n input1 = create_tensor_data(\n parameters[\"dtype\"],\n parameters[\"input_shape_1\"],\n min_value=-1,\n max_value=1)\n input2 = create_tensor_data(\n parameters[\"dtype\"],\n parameters[\"input_shape_2\"],\n min_value=-1,\n max_value=1)\n else:\n input1 = create_tensor_data(parameters[\"dtype\"],\n parameters[\"input_shape_1\"])\n input2 = create_tensor_data(parameters[\"dtype\"],\n parameters[\"input_shape_2\"])\n return [input1, input2], sess.run(\n outputs, feed_dict={\n inputs[0]: input1,\n inputs[1]: input2\n })\n\n make_zip_of_tests(\n options,\n test_parameters,\n build_graph,\n build_inputs,\n expected_tf_failures=expected_tf_failures)\n\n\ndef make_binary_op_tests_func(binary_operator):\n \"\"\"Return a function that does a test on a binary operator.\"\"\"\n return lambda options: make_binary_op_tests(options, binary_operator)\n\n\n@register_make_test_function()\ndef make_add_tests(options):\n make_binary_op_tests(options, tf.add, allow_fully_quantize=True)\n\n\n@register_make_test_function()\ndef make_div_tests(options):\n \"\"\"Make zip tests for div op with 5D case.\"\"\"\n test_parameters = [\n {\n \"dtype\": [tf.float32],\n \"input_shape_1\": [[1, 3, 3, 3, 3]],\n \"input_shape_2\": [[3]],\n \"activation\": [False],\n \"fully_quantize\": [False],\n \"dynamic_range_quantize\": [False, True],\n },\n ]\n make_binary_op_tests(\n options, tf.compat.v1.div, test_parameters=test_parameters)\n\n\n@register_make_test_function()\ndef make_sub_tests(options):\n \"\"\"Make zip tests for sub op with additional cases.\"\"\"\n test_parameters = [\n {\n \"dtype\": [tf.float32],\n \"input_shape_1\": [[1, 3, 3, 3, 3]],\n \"input_shape_2\": [[3]],\n \"activation\": [False],\n \"fully_quantize\": [False],\n \"dynamic_range_quantize\": [False, True],\n },\n ]\n make_binary_op_tests(\n options,\n tf.subtract,\n allow_fully_quantize=True,\n test_parameters=test_parameters)\n\n\n@register_make_test_function()\ndef make_mul_tests(options):\n make_binary_op_tests(options, tf.multiply, allow_fully_quantize=True)\n\n\n@register_make_test_function()\ndef make_pow_tests(options):\n make_binary_op_tests(options, tf.pow, expected_tf_failures=7)\n\n\n@register_make_test_function()\ndef make_floor_div_tests(options):\n make_binary_op_tests(options, tf.math.floordiv)\n\n\n@register_make_test_function()\ndef make_floor_mod_tests(options):\n make_binary_op_tests(options, tf.math.floormod)\n\n\n@register_make_test_function()\ndef make_squared_difference_tests(options):\n make_binary_op_tests(options, tf.math.squared_difference,\n allow_fully_quantize=True)\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\"\"\"IMDB sentiment classification dataset.\"\"\"\n\nimport json\n\nimport numpy as np\n\nfrom tensorflow.python.keras.preprocessing.sequence import _remove_long_seq\nfrom tensorflow.python.keras.utils.data_utils import get_file\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.util.tf_export import keras_export\n\n\n@keras_export('keras.datasets.imdb.load_data')\ndef load_data(path='imdb.npz',\n num_words=None,\n skip_top=0,\n maxlen=None,\n seed=113,\n start_char=1,\n oov_char=2,\n index_from=3,\n **kwargs):\n \"\"\"Loads the [IMDB dataset](https://ai.stanford.edu/~amaas/data/sentiment/).\n\n This is a dataset of 25,000 movies reviews from IMDB, labeled by sentiment\n (positive/negative). Reviews have been preprocessed, and each review is\n encoded as a list of word indexes (integers).\n For convenience, words are indexed by overall frequency in the dataset,\n so that for instance the integer \"3\" encodes the 3rd most frequent word in\n the data. This allows for quick filtering operations such as:\n \"only consider the top 10,000 most\n common words, but eliminate the top 20 most common words\".\n\n As a convention, \"0\" does not stand for a specific word, but instead is used\n to encode any unknown word.\n\n Args:\n path: where to cache the data (relative to `~/.keras/dataset`).\n num_words: integer or None. Words are\n ranked by how often they occur (in the training set) and only\n the `num_words` most frequent words are kept. Any less frequent word\n will appear as `oov_char` value in the sequence data. If None,\n all words are kept. Defaults to None, so all words are kept.\n skip_top: skip the top N most frequently occurring words\n (which may not be informative). These words will appear as\n `oov_char` value in the dataset. Defaults to 0, so no words are\n skipped.\n maxlen: int or None. Maximum sequence length.\n Any longer sequence will be truncated. Defaults to None, which\n means no truncation.\n seed: int. Seed for reproducible data shuffling.\n start_char: int. The start of a sequence will be marked with this\n character. Defaults to 1 because 0 is usually the padding character.\n oov_char: int. The out-of-vocabulary character.\n Words that were cut out because of the `num_words` or\n `skip_top` limits will be replaced with this character.\n index_from: int. Index actual words with this index and higher.\n **kwargs: Used for backwards compatibility.\n\n Returns:\n Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`.\n\n **x_train, x_test**: lists of sequences, which are lists of indexes\n (integers). If the num_words argument was specific, the maximum\n possible index value is `num_words - 1`. If the `maxlen` argument was\n specified, the largest possible sequence length is `maxlen`.\n\n **y_train, y_test**: lists of integer labels (1 or 0).\n\n Raises:\n ValueError: in case `maxlen` is so low\n that no input sequence could be kept.\n\n Note that the 'out of vocabulary' character is only used for\n words that were present in the training set but are not included\n because they're not making the `num_words` cut here.\n Words that were not seen in the training set but are in the test set\n have simply been skipped.\n \"\"\"\n # Legacy support\n if 'nb_words' in kwargs:\n logging.warning('The `nb_words` argument in `load_data` '\n 'has been renamed `num_words`.')\n num_words = kwargs.pop('nb_words')\n if kwargs:\n raise TypeError('Unrecognized keyword arguments: ' + str(kwargs))\n\n origin_folder = 'https://storage.googleapis.com/tensorflow/tf-keras-datasets/'\n path = get_file(\n path,\n origin=origin_folder + 'imdb.npz',\n file_hash=\n '69664113be75683a8fe16e3ed0ab59fda8886cb3cd7ada244f7d9544e4676b9f')\n with np.load(path, allow_pickle=True) as f:\n x_train, labels_train = f['x_train'], f['y_train']\n x_test, labels_test = f['x_test'], f['y_test']\n\n rng = np.random.RandomState(seed)\n indices = np.arange(len(x_train))\n rng.shuffle(indices)\n x_train = x_train[indices]\n labels_train = labels_train[indices]\n\n indices = np.arange(len(x_test))\n rng.shuffle(indices)\n x_test = x_test[indices]\n labels_test = labels_test[indices]\n\n if start_char is not None:\n x_train = [[start_char] + [w + index_from for w in x] for x in x_train]\n x_test = [[start_char] + [w + index_from for w in x] for x in x_test]\n elif index_from:\n x_train = [[w + index_from for w in x] for x in x_train]\n x_test = [[w + index_from for w in x] for x in x_test]\n\n if maxlen:\n x_train, labels_train = _remove_long_seq(maxlen, x_train, labels_train)\n x_test, labels_test = _remove_long_seq(maxlen, x_test, labels_test)\n if not x_train or not x_test:\n raise ValueError('After filtering for sequences shorter than maxlen=' +\n str(maxlen) + ', no sequence was kept. '\n 'Increase maxlen.')\n\n xs = np.concatenate([x_train, x_test])\n labels = np.concatenate([labels_train, labels_test])\n\n if not num_words:\n num_words = max(max(x) for x in xs)\n\n # by convention, use 2 as OOV word\n # reserve 'index_from' (=3 by default) characters:\n # 0 (padding), 1 (start), 2 (OOV)\n if oov_char is not None:\n xs = [\n [w if (skip_top <= w < num_words) else oov_char for w in x] for x in xs\n ]\n else:\n xs = [[w for w in x if skip_top <= w < num_words] for x in xs]\n\n idx = len(x_train)\n x_train, y_train = np.array(xs[:idx]), np.array(labels[:idx])\n x_test, y_test = np.array(xs[idx:]), np.array(labels[idx:])\n\n return (x_train, y_train), (x_test, y_test)\n\n\n@keras_export('keras.datasets.imdb.get_word_index')\ndef get_word_index(path='imdb_word_index.json'):\n \"\"\"Retrieves a dict mapping words to their index in the IMDB dataset.\n\n Args:\n path: where to cache the data (relative to `~/.keras/dataset`).\n\n Returns:\n The word index dictionary. Keys are word strings, values are their index.\n\n Example:\n\n ```python\n # Retrieve the training sequences.\n (x_train, _), _ = keras.datasets.imdb.load_data()\n # Retrieve the word index file mapping words to indices\n word_index = keras.datasets.imdb.get_word_index()\n # Reverse the word index to obtain a dict mapping indices to words\n inverted_word_index = dict((i, word) for (word, i) in word_index.items())\n # Decode the first sequence in the dataset\n decoded_sequence = \" \".join(inverted_word_index[i] for i in x_train[0])\n ```\n \"\"\"\n origin_folder = 'https://storage.googleapis.com/tensorflow/tf-keras-datasets/'\n path = get_file(\n path,\n origin=origin_folder + 'imdb_word_index.json',\n file_hash='bfafd718b763782e994055a2d397834f')\n with open(path) as f:\n return json.load(f)\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\"\"\"SavedModel utility functions implementation.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\n\nfrom tensorflow.core.framework import types_pb2\nfrom tensorflow.core.protobuf import meta_graph_pb2\nfrom tensorflow.core.protobuf import struct_pb2\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import composite_tensor\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import sparse_tensor\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.lib.io import file_io\nfrom tensorflow.python.saved_model import constants\nfrom tensorflow.python.saved_model import nested_structure_coder\nfrom tensorflow.python.util import compat\nfrom tensorflow.python.util import deprecation\nfrom tensorflow.python.util import nest\nfrom tensorflow.python.util.tf_export import tf_export\n\n\n# TensorInfo helpers.\n\n\n@tf_export(v1=[\"saved_model.build_tensor_info\",\n \"saved_model.utils.build_tensor_info\"])\[email protected](\n None,\n \"This function will only be available through the v1 compatibility \"\n \"library as tf.compat.v1.saved_model.utils.build_tensor_info or \"\n \"tf.compat.v1.saved_model.build_tensor_info.\")\ndef build_tensor_info(tensor):\n \"\"\"Utility function to build TensorInfo proto from a Tensor.\n\n Args:\n tensor: Tensor or SparseTensor whose name, dtype and shape are used to\n build the TensorInfo. For SparseTensors, the names of the three\n constituent Tensors are used.\n\n Returns:\n A TensorInfo protocol buffer constructed based on the supplied argument.\n\n Raises:\n RuntimeError: If eager execution is enabled.\n \"\"\"\n if context.executing_eagerly():\n raise RuntimeError(\"build_tensor_info is not supported in Eager mode.\")\n return build_tensor_info_internal(tensor)\n\n\ndef build_tensor_info_internal(tensor):\n \"\"\"Utility function to build TensorInfo proto from a Tensor.\"\"\"\n if (isinstance(tensor, composite_tensor.CompositeTensor) and\n not isinstance(tensor, sparse_tensor.SparseTensor)):\n return _build_composite_tensor_info_internal(tensor)\n\n tensor_info = meta_graph_pb2.TensorInfo(\n dtype=dtypes.as_dtype(tensor.dtype).as_datatype_enum,\n tensor_shape=tensor.get_shape().as_proto())\n if isinstance(tensor, sparse_tensor.SparseTensor):\n tensor_info.coo_sparse.values_tensor_name = tensor.values.name\n tensor_info.coo_sparse.indices_tensor_name = tensor.indices.name\n tensor_info.coo_sparse.dense_shape_tensor_name = tensor.dense_shape.name\n else:\n tensor_info.name = tensor.name\n return tensor_info\n\n\ndef _build_composite_tensor_info_internal(tensor):\n \"\"\"Utility function to build TensorInfo proto from a CompositeTensor.\"\"\"\n spec = tensor._type_spec # pylint: disable=protected-access\n tensor_info = meta_graph_pb2.TensorInfo()\n struct_coder = nested_structure_coder.StructureCoder()\n spec_proto = struct_coder.encode_structure(spec)\n tensor_info.composite_tensor.type_spec.CopyFrom(spec_proto.type_spec_value)\n for component in nest.flatten(tensor, expand_composites=True):\n tensor_info.composite_tensor.components.add().CopyFrom(\n build_tensor_info_internal(component))\n return tensor_info\n\n\ndef build_tensor_info_from_op(op):\n \"\"\"Utility function to build TensorInfo proto from an Op.\n\n Note that this function should be used with caution. It is strictly restricted\n to TensorFlow internal use-cases only. Please make sure you do need it before\n using it.\n\n This utility function overloads the TensorInfo proto by setting the name to\n the Op's name, dtype to DT_INVALID and tensor_shape as None. One typical usage\n is for the Op of the call site for the defunned function:\n ```python\n @function.defun\n def some_variable_initialization_fn(value_a, value_b):\n a = value_a\n b = value_b\n\n value_a = constant_op.constant(1, name=\"a\")\n value_b = constant_op.constant(2, name=\"b\")\n op_info = utils.build_op_info(\n some_variable_initialization_fn(value_a, value_b))\n ```\n\n Args:\n op: An Op whose name is used to build the TensorInfo. The name that points\n to the Op could be fetched at run time in the Loader session.\n\n Returns:\n A TensorInfo protocol buffer constructed based on the supplied argument.\n\n Raises:\n RuntimeError: If eager execution is enabled.\n \"\"\"\n if context.executing_eagerly():\n raise RuntimeError(\n \"build_tensor_info_from_op is not supported in Eager mode.\")\n return meta_graph_pb2.TensorInfo(\n dtype=types_pb2.DT_INVALID,\n tensor_shape=tensor_shape.unknown_shape().as_proto(),\n name=op.name)\n\n\n@tf_export(v1=[\"saved_model.get_tensor_from_tensor_info\",\n \"saved_model.utils.get_tensor_from_tensor_info\"])\[email protected](\n None,\n \"This function will only be available through the v1 compatibility \"\n \"library as tf.compat.v1.saved_model.utils.get_tensor_from_tensor_info or \"\n \"tf.compat.v1.saved_model.get_tensor_from_tensor_info.\")\ndef get_tensor_from_tensor_info(tensor_info, graph=None, import_scope=None):\n \"\"\"Returns the Tensor or CompositeTensor described by a TensorInfo proto.\n\n Args:\n tensor_info: A TensorInfo proto describing a Tensor or SparseTensor or\n CompositeTensor.\n graph: The tf.Graph in which tensors are looked up. If None, the\n current default graph is used.\n import_scope: If not None, names in `tensor_info` are prefixed with this\n string before lookup.\n\n Returns:\n The Tensor or SparseTensor or CompositeTensor in `graph` described by\n `tensor_info`.\n\n Raises:\n KeyError: If `tensor_info` does not correspond to a tensor in `graph`.\n ValueError: If `tensor_info` is malformed.\n \"\"\"\n graph = graph or ops.get_default_graph()\n def _get_tensor(name):\n return graph.get_tensor_by_name(\n ops.prepend_name_scope(name, import_scope=import_scope))\n encoding = tensor_info.WhichOneof(\"encoding\")\n if encoding == \"name\":\n return _get_tensor(tensor_info.name)\n elif encoding == \"coo_sparse\":\n return sparse_tensor.SparseTensor(\n _get_tensor(tensor_info.coo_sparse.indices_tensor_name),\n _get_tensor(tensor_info.coo_sparse.values_tensor_name),\n _get_tensor(tensor_info.coo_sparse.dense_shape_tensor_name))\n elif encoding == \"composite_tensor\":\n struct_coder = nested_structure_coder.StructureCoder()\n spec_proto = struct_pb2.StructuredValue(\n type_spec_value=tensor_info.composite_tensor.type_spec)\n spec = struct_coder.decode_proto(spec_proto)\n components = [_get_tensor(component.name) for component in\n tensor_info.composite_tensor.components]\n return nest.pack_sequence_as(spec, components, expand_composites=True)\n else:\n raise ValueError(\"Invalid TensorInfo.encoding: %s\" % encoding)\n\n\ndef get_element_from_tensor_info(tensor_info, graph=None, import_scope=None):\n \"\"\"Returns the element in the graph described by a TensorInfo proto.\n\n Args:\n tensor_info: A TensorInfo proto describing an Op or Tensor by name.\n graph: The tf.Graph in which tensors are looked up. If None, the current\n default graph is used.\n import_scope: If not None, names in `tensor_info` are prefixed with this\n string before lookup.\n\n Returns:\n Op or tensor in `graph` described by `tensor_info`.\n\n Raises:\n KeyError: If `tensor_info` does not correspond to an op or tensor in `graph`\n \"\"\"\n graph = graph or ops.get_default_graph()\n return graph.as_graph_element(\n ops.prepend_name_scope(tensor_info.name, import_scope=import_scope))\n\n\n# Path helpers.\n\n\ndef get_or_create_variables_dir(export_dir):\n \"\"\"Return variables sub-directory, or create one if it doesn't exist.\"\"\"\n variables_dir = get_variables_dir(export_dir)\n if not file_io.file_exists(variables_dir):\n file_io.recursive_create_dir(variables_dir)\n return variables_dir\n\n\ndef get_variables_dir(export_dir):\n \"\"\"Return variables sub-directory in the SavedModel.\"\"\"\n return os.path.join(\n compat.as_text(export_dir),\n compat.as_text(constants.VARIABLES_DIRECTORY))\n\n\ndef get_variables_path(export_dir):\n \"\"\"Return the variables path, used as the prefix for checkpoint files.\"\"\"\n return os.path.join(\n compat.as_text(get_variables_dir(export_dir)),\n compat.as_text(constants.VARIABLES_FILENAME))\n\n\ndef get_or_create_assets_dir(export_dir):\n \"\"\"Return assets sub-directory, or create one if it doesn't exist.\"\"\"\n assets_destination_dir = get_assets_dir(export_dir)\n\n if not file_io.file_exists(assets_destination_dir):\n file_io.recursive_create_dir(assets_destination_dir)\n\n return assets_destination_dir\n\n\ndef get_assets_dir(export_dir):\n \"\"\"Return path to asset directory in the SavedModel.\"\"\"\n return os.path.join(\n compat.as_text(export_dir),\n compat.as_text(constants.ASSETS_DIRECTORY))\n\n\ndef get_or_create_debug_dir(export_dir):\n \"\"\"Returns path to the debug sub-directory, creating if it does not exist.\"\"\"\n debug_dir = get_debug_dir(export_dir)\n\n if not file_io.file_exists(debug_dir):\n file_io.recursive_create_dir(debug_dir)\n\n return debug_dir\n\n\ndef get_saved_model_pbtxt_path(export_dir):\n return os.path.join(\n compat.as_bytes(compat.path_to_str(export_dir)),\n compat.as_bytes(constants.SAVED_MODEL_FILENAME_PBTXT))\n\n\ndef get_saved_model_pb_path(export_dir):\n return os.path.join(\n compat.as_bytes(compat.path_to_str(export_dir)),\n compat.as_bytes(constants.SAVED_MODEL_FILENAME_PB))\n\n\ndef get_debug_dir(export_dir):\n \"\"\"Returns path to the debug sub-directory in the SavedModel.\"\"\"\n return os.path.join(\n compat.as_text(export_dir), compat.as_text(constants.DEBUG_DIRECTORY))\n\n# Based on tensor_bundle/byte_swap.cc\nbyte_swappable = [\n dtypes.float16, dtypes.float32, dtypes.float64, dtypes.bfloat16,\n dtypes.complex64, dtypes.complex128, dtypes.uint16, dtypes.uint32,\n dtypes.uint64, dtypes.int16, dtypes.int32, dtypes.int64, dtypes.qint16,\n dtypes.quint16, dtypes.qint32\n]\n\n\ndef swap_function_tensor_content(meta_graph_def, from_endiness, to_endiness):\n functions = meta_graph_def.graph_def.library.function\n for function in functions:\n node_def = function.node_def\n for node in node_def:\n if node.op == \"Const\":\n tensor = node.attr[\"value\"].tensor\n byte_swap_tensor_content(tensor, from_endiness, to_endiness)\n\n\ndef byte_swap_tensor_content(tensor, from_endiness, to_endiness):\n \"\"\"Byte swaps.\"\"\"\n if tensor.dtype in byte_swappable:\n tshape = tensor.tensor_shape.dim\n tensor_bytes = tensor.tensor_content\n if tensor_bytes:\n tensor_size = 1\n for sz in tshape:\n tensor_size = tensor_size * sz.size\n chunksize = int(len(tensor_bytes) / tensor_size)\n # Split tensor_data into chunks for byte swapping.\n to_swap = [\n tensor_bytes[i:i + chunksize]\n for i in range(0, len(tensor_bytes), chunksize)\n ]\n # Swap and replace tensor_content.\n tensor.tensor_content = b\"\".join([\n int.from_bytes(byteswap,\n from_endiness).to_bytes(chunksize, to_endiness)\n for byteswap in to_swap\n ])\n"
] |
[
[
"tensorflow.python.ops.gen_math_ops.select_v2",
"tensorflow.python.util.tf_decorator.make_decorator",
"tensorflow.python.ops.gen_array_ops.list_diff",
"tensorflow.python.framework.ops.RegisterGradient",
"tensorflow.python.ops.gen_array_ops.strided_slice",
"tensorflow.python.ops.gen_array_ops.dequantize",
"tensorflow.python.util.tf_export.tf_export",
"tensorflow.python.ops.gen_array_ops.rank",
"tensorflow.python.ops.gen_array_ops.identity",
"tensorflow.python.ops.gen_array_ops.matrix_diag_v3",
"tensorflow.python.ops.gen_array_ops.quantize_and_dequantize_v2",
"tensorflow.python.framework.tensor_shape.dimension_value",
"tensorflow.python.ops.gen_array_ops.reshape",
"numpy.zeros",
"tensorflow.python.ops.gen_array_ops.split",
"tensorflow.python.ops.gen_array_ops.tensor_scatter_update",
"tensorflow.python.ops.gen_array_ops.unique_with_counts",
"tensorflow.python.ops.gen_array_ops.placeholder",
"tensorflow.python.util.deprecation.deprecated_args",
"tensorflow.python.ops.gen_array_ops.extract_image_patches",
"numpy.array",
"tensorflow.python.ops.gen_array_ops.pack",
"tensorflow.python.ops.gen_array_ops.edit_distance",
"tensorflow.python.framework.tensor_util.is_tf_type",
"tensorflow.python.ops.gen_array_ops.size",
"tensorflow.python.util.nest.flatten",
"tensorflow.python.ops.gen_math_ops._range",
"tensorflow.python.ops.gen_array_ops.unique",
"tensorflow.python.ops.gen_array_ops.squeeze",
"tensorflow.python.ops.gen_array_ops.quantize_v2",
"tensorflow.python.ops.gen_array_ops.space_to_depth",
"tensorflow.python.ops.gen_array_ops.where",
"tensorflow.python.ops.gen_array_ops.concat_v2",
"tensorflow.python.ops.gen_array_ops.one_hot",
"tensorflow.python.framework.common_shapes.broadcast_shape",
"tensorflow.python.ops.gen_array_ops.pad",
"tensorflow.python.framework.tensor_util.maybe_set_static_shape",
"tensorflow.python.framework.dtypes.as_dtype",
"tensorflow.python.ops.gen_array_ops.matrix_set_diag_v3",
"tensorflow.python.framework.ops.Tensor._override_operator",
"tensorflow.python.framework.ops.convert_to_tensor",
"tensorflow.python.framework.tensor_shape.unknown_shape",
"numpy.ones",
"numpy.isscalar",
"tensorflow.python.ops.gen_array_ops.fill",
"tensorflow.python.ops.gen_array_ops.matrix_diag_part_v3",
"tensorflow.python.ops.gen_array_ops.diag_part",
"tensorflow.python.ops.gen_array_ops.reverse_sequence",
"tensorflow.python.framework.tensor_util.constant_value_as_shape",
"tensorflow.python.util.deprecation.deprecated_endpoints",
"tensorflow.python.ops.gen_array_ops.split_v",
"tensorflow.python.eager.context.executing_eagerly",
"tensorflow.python.framework.ops.IndexedSlices",
"tensorflow.python.framework.tensor_util.constant_value",
"tensorflow.python.ops.gen_array_ops.depth_to_space",
"tensorflow.python.ops.gen_array_ops.lower_bound",
"tensorflow.python.framework.ops.register_tensor_conversion_function",
"tensorflow.python.ops.gen_array_ops.unpack",
"tensorflow.python.ops.gen_array_ops.gather_nd",
"tensorflow.python.framework.tensor_shape.is_fully_defined",
"tensorflow.python.ops.gen_math_ops.cast",
"tensorflow.python.framework.ops.name_scope",
"tensorflow.python.ops.gen_array_ops.shape",
"tensorflow.python.util.deprecation.deprecated_argument_lookup",
"tensorflow.python.framework.tensor_shape.TensorShape",
"tensorflow.python.ops.gen_math_ops.select",
"tensorflow.python.ops.gen_array_ops.gather_v2",
"tensorflow.python.ops.gen_math_ops.prod",
"tensorflow.python.ops.gen_array_ops.fingerprint",
"tensorflow.python.ops.gen_array_ops.placeholder_with_default",
"tensorflow.python.ops.gen_array_ops.upper_bound",
"numpy.arange",
"tensorflow.python.ops.gen_array_ops.quantize_and_dequantize_v4",
"tensorflow.python.util.nest.map_structure",
"tensorflow.python.ops.gen_array_ops.pad_v2",
"tensorflow.python.ops.gen_array_ops.broadcast_args",
"tensorflow.python.util.deprecation.deprecated",
"tensorflow.python.ops.gen_array_ops.zeros_like",
"tensorflow.python.ops.gen_array_ops.shape_n",
"tensorflow.python.ops.gen_array_ops._slice",
"tensorflow.python.ops.gen_array_ops.mirror_pad",
"tensorflow.python.ops.gen_array_ops.expand_dims",
"numpy.prod",
"tensorflow.python.framework.tensor_shape.as_shape",
"tensorflow.python.framework.constant_op.constant"
],
[
"tensorflow.lite.testing.zip_test_utils.make_zip_of_tests",
"tensorflow.lite.testing.zip_test_utils.create_tensor_data",
"tensorflow.compat.v1.compat.v1.placeholder",
"tensorflow.compat.v1.nn.relu",
"tensorflow.lite.testing.zip_test_utils.register_make_test_function"
],
[
"tensorflow.python.platform.tf_logging.warning",
"tensorflow.python.util.tf_export.keras_export",
"tensorflow.python.keras.preprocessing.sequence._remove_long_seq",
"numpy.concatenate",
"numpy.load",
"numpy.array",
"numpy.random.RandomState",
"tensorflow.python.keras.utils.data_utils.get_file"
],
[
"tensorflow.python.lib.io.file_io.recursive_create_dir",
"tensorflow.core.protobuf.struct_pb2.StructuredValue",
"tensorflow.python.util.nest.flatten",
"tensorflow.python.util.compat.as_text",
"tensorflow.python.saved_model.nested_structure_coder.StructureCoder",
"tensorflow.python.framework.ops.prepend_name_scope",
"tensorflow.python.util.tf_export.tf_export",
"tensorflow.python.lib.io.file_io.file_exists",
"tensorflow.python.framework.ops.get_default_graph",
"tensorflow.python.util.compat.as_bytes",
"tensorflow.python.framework.dtypes.as_dtype",
"tensorflow.python.util.nest.pack_sequence_as",
"tensorflow.core.protobuf.meta_graph_pb2.TensorInfo",
"tensorflow.python.framework.tensor_shape.unknown_shape",
"tensorflow.python.util.compat.path_to_str",
"tensorflow.python.eager.context.executing_eagerly",
"tensorflow.python.util.deprecation.deprecated"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.8",
"1.10",
"1.12",
"2.7",
"2.6",
"1.13",
"2.3",
"2.4",
"2.9",
"1.7",
"2.5",
"2.2",
"2.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"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",
"2.7",
"1.12",
"2.6",
"2.2",
"1.13",
"2.3",
"2.4",
"2.9",
"1.7",
"2.5",
"2.8",
"2.10"
]
}
] |
JanRocketMan/regression-prior-networks
|
[
"3c8ffa758ee6eaa15b8afe31ac1c03f87bbf6a14",
"3c8ffa758ee6eaa15b8afe31ac1c03f87bbf6a14"
] |
[
"get_samples.py",
"distributions/nw_prior.py"
] |
[
"from argparse import ArgumentParser\n\nimport numpy as np\nimport seaborn as sns\nfrom PIL import Image\nimport matplotlib.pyplot as plt\n\nimport torch\nfrom torchvision.transforms import ToTensor, Resize, ToPILImage\n\nfrom evaluation.show_examples import show_model_examples\nfrom utils.data_loading import load_test_data, getTrainingEvalDataKITTI\nfrom evaluation.ood_testing import load_ood_data, load_ood_data_kitti\nfrom utils.model_utils import load_unet_model_from_checkpoint\nfrom utils.viz_utils import get_example_figure, get_tensor_with_histograms\n\n\nif __name__ == '__main__':\n parser = ArgumentParser(\n description='Evaluation of trained \\\n Monocular Depth Estimation model on Nyu Depth v2'\n )\n parser.add_argument('--data_path', default='data')\n parser.add_argument(\n '--data_type', default='nyu', choices=['nyu', 'kitti', 'lsun']\n )\n parser.add_argument(\n '--gaussian_checkpoints',\n default=[\n 'checkpoints/dense_depth_gaussian/' + str(i + 1) + '/19.ckpt'\n for i in range(5)\n ],\n nargs='+'\n )\n parser.add_argument(\n '--endd_checkpoint',\n default='checkpoints/dense_depth_endd/1/21.ckpt'\n )\n parser.add_argument(\n '--indices',\n default=[20, 57, 71, 102, 106, 121, 270, 435, 466, 491],\n nargs='+'\n )\n parser.add_argument('--backbone', default='densenet169', choices=[\n 'resnet18', 'densenet169'\n ])\n parser.add_argument('--bs', type=int, default=6)\n parser.add_argument(\n '--models', default=['gaussian', 'gaussian-ensemble', 'nw_prior'],\n nargs='+'\n )\n parser.add_argument('--targets_transform', default='scaled', choices=[\n 'inverse', 'scaled'\n ])\n parser.add_argument(\n '--measures', default=['total_variance', 'expected_pairwise_kl'],\n nargs='+', help='Uncertainty measures to visualize'\n )\n parser.add_argument('--device', default='cuda:0')\n parser.add_argument('--trainmodel', default='nyu', choices=['nyu', 'kitti'])\n parser.add_argument('--kitti_csv_test', default='none', type=str)\n args = parser.parse_args()\n\n all_indices = [int(idx) for idx in args.indices]\n if args.data_type == 'nyu' and args.trainmodel == 'nyu':\n rgb, depth, crop = load_test_data(args.data_path)\n elif args.trainmodel == 'nyu':\n rgb = load_ood_data(args.data_path, args.data_type)\n depth, crop = None, None\n elif args.data_type == 'kitti':\n _, test_loader = getTrainingEvalDataKITTI(\n path_to_kitti=args.data_path,\n path_to_csv_train=args.kitti_csv_test,\n path_to_csv_val=args.kitti_csv_test,\n batch_size=args.bs,\n resize_depth=False\n )\n rgb, depth = [], []\n for data in test_loader:\n rgb.append(data['image'])\n depth.append(data['depth'])\n rgb, depth = torch.cat(rgb), torch.cat(depth)\n rgb = rgb.permute((0, 2, 3, 1)).numpy() * 255.0\n depth = depth.squeeze().numpy()\n else:\n rgb = load_ood_data_kitti(args.data_path, itype=args.data_type)\n depth = None\n\n max_limits = None\n all_results = {}\n checkpoints = {\n 'gaussian': [args.gaussian_checkpoints[2]],\n 'gaussian-ensemble': args.gaussian_checkpoints,\n 'nw_prior': [args.endd_checkpoint]\n }\n for model_type in args.models:\n model = load_unet_model_from_checkpoint(\n checkpoints[model_type], model_type, args.backbone, args.device\n )\n if model_type == 'gaussian':\n results = show_model_examples(\n model, rgb, depth, all_indices,\n ['variance'], args.targets_transform, args.device,\n trainmodel=args.trainmodel\n )\n max_limits = results[-1]\n else:\n results = show_model_examples(\n model, rgb, depth, all_indices,\n args.measures, args.targets_transform, args.device,\n (None if 'gaussian' in model_type else max_limits)\n )\n if 'gaussian' in model_type:\n max_limits = results[-1]\n all_results[model_type] = results\n\n model_names = ['gaussian', 'gaussian-ensemble', 'nw_prior']\n plot_names = ['Single', 'ENSM', 'EnD$^2$']\n all_hists = get_tensor_with_histograms(\n all_results, plot_names, model_names\n )\n\n for i, idx in enumerate(args.indices):\n ensm_data, endd_data = [[\n all_results[model_n][0][i],\n all_results[model_n][2][i]\n ] + [\n all_results[model_n][3][measure][i]\n for measure in args.measures\n ] for model_n in ['gaussian-ensemble', 'nw_prior']]\n figure = get_example_figure(\n ensm_data, endd_data, all_hists[i*4:i*4+4],\n ispred=(args.trainmodel == args.data_type)\n )\n figure.savefig(\n 'temp_plots/example_' + args.data_type + '_' + str(idx) + '.png',\n dpi=300, bbox_inches='tight'\n )\n plt.clf()\n",
"import math\nimport torch\n\nfrom torch.distributions import StudentT\nfrom distributions.diagonal_normal_wishart import NormalDiagonalWishart\nfrom utils.func_utils import mvdigamma\n\n\nclass NormalWishartPrior(NormalDiagonalWishart):\n r\"\"\"\n A Normal-Wishart prior distribution to emulate ensemble\n of Gaussians\n \"\"\"\n\n def forward(self):\n \"\"\"Returns predictive posterior distribution\"\"\"\n self.precision_coeff = (self.belief + 1) / (\n self.belief * (self.df - self.dimensionality + 1)\n )\n return StudentT(\n (self.df - self.dimensionality + 1).unsqueeze(-1),\n loc=self.loc,\n scale=(\n self.precision_coeff.unsqueeze(-1) / self.precision_diag\n ).pow(0.5),\n )\n\n @property\n def mean(self):\n \"\"\"Returns predictive posterior mean\"\"\"\n ppe_mean = self.forward().mean\n if ppe_mean.size(-1) == 1:\n return ppe_mean[..., 0]\n return ppe_mean\n\n def predictive_posterior_log_prob(self, value):\n return self.forward().log_prob(value)\n\n def predictive_posterior_variance(self):\n \"\"\"Returns total variance - total uncertainty\"\"\"\n variance_res = self.forward().variance\n if variance_res.size(-1) != 1:\n raise ValueError(\n \"Predictive posterior returned entropy with incorrect shapes\"\n )\n return variance_res[..., 0]\n\n def predictive_posterior_entropy(self):\n \"\"\"Returns total entropy - total uncertainty\"\"\"\n entropy_res = self.forward().entropy()\n if entropy_res.size(-1) != 1:\n raise ValueError(\n \"Predictive posterior returned entropy with incorrect shapes\"\n )\n return entropy_res[..., 0]\n\n def expected_entropy(self):\n \"\"\"Returns expected entropy - data uncertainty\"\"\"\n mvdigamma_term = mvdigamma(0.5 * self.df, self.dimensionality)\n return 0.5 * (\n self.dimensionality * (1 + math.log(2 * math.pi)) -\n (2 * self.precision_diag).log().sum(dim=-1) -\n mvdigamma_term\n )\n\n def expected_log_prob(self, value):\n neg_mse_term = -torch.sum(\n (self.loc - value).pow(2) * self.precision_diag *\n self.df.unsqueeze(-1),\n dim=-1\n )\n mvdigamma_term = mvdigamma(0.5 * self.df, self.dimensionality)\n\n reg_terms = (\n 2 * self.precision_diag\n ).log().sum(dim=-1) + mvdigamma_term\n conf_term = -self.dimensionality * self.belief.pow(-1)\n return 0.5 * (neg_mse_term + reg_terms + conf_term)\n\n def mutual_information(self):\n \"\"\"Returns mutual information - knowledge uncertainty\"\"\"\n predictive_posterior_entropy = self.predictive_posterior_entropy()\n expected_entropy = self.expected_entropy()\n return predictive_posterior_entropy - expected_entropy\n\n def expected_pairwise_kl(self):\n \"\"\"Returns expected pairwise kl divergence - knowledge uncertainty\"\"\"\n term1 = 0.5 * (\n self.df * self.dimensionality / (\n self.df - self.dimensionality - 1\n ) - self.dimensionality\n )\n term2 = 0.5 * (\n self.df * self.dimensionality / (\n self.df - self.dimensionality - 1\n ) + self.dimensionality\n ) / self.belief\n return term1 + term2\n\n def variance_of_expected(self):\n \"\"\"Returns variance of expected distribution - knowledge uncertainty\"\"\"\n return self.expected_variance() / self.belief\n\n def expected_variance(self):\n \"\"\"Returns expected variance - data uncertainty\"\"\"\n result = 1 / (\n self.precision_diag * (\n self.df.unsqueeze(-1) - self.dimensionality - 1\n )\n )\n if result.size(-1) != 1:\n raise ValueError(\n \"Expected variance currently supports\\\n only one-dimensional targets\"\n )\n\n return result[..., 0]\n\n def total_variance(self):\n \"\"\"Duplicates total variance (sanity check)\"\"\"\n tv = self.variance_of_expected() + self.expected_variance()\n ppv = self.predictive_posterior_variance()\n\n rel_diff = (tv - ppv).abs() / tv.abs().pow(0.5) / ppv.abs().pow(0.5)\n assert (rel_diff < 1e-6).all()\n return tv\n\n\ndef test_nw_prior():\n print(\"Testing Normal-Wishart Prior...\")\n ex_mean = torch.zeros(32, 1, 200, 400, 1)\n ex_var = torch.ones(32, 1, 200, 400, 1)\n ex_belief = torch.ones(32, 1, 200, 400)\n ex_df = 10 * torch.ones(32, 1, 200, 400)\n\n ex_dist = NormalWishartPrior(ex_mean, ex_var, ex_belief, ex_df)\n assert ex_dist.predictive_posterior_log_prob(\n 2 * torch.ones(32, 1, 200, 400, 1)\n ).shape == (32, 1, 200, 400, 1)\n assert ex_dist.log_prob(\n 2 * torch.ones(32, 1, 200, 400, 1),\n 2 * torch.ones(32, 1, 200, 400, 1),\n ).shape == (32, 1, 200, 400)\n\n for method in [\n 'predictive_posterior_entropy', 'mutual_information',\n 'expected_entropy', 'expected_pairwise_kl',\n 'variance_of_expected', 'expected_variance', 'total_variance',\n 'predictive_posterior_variance'\n ]:\n assert getattr(ex_dist, method)().shape == (32, 1, 200, 400)\n\n print(\"Passed\")\n"
] |
[
[
"matplotlib.pyplot.clf",
"torch.cat"
],
[
"torch.ones",
"torch.zeros"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
pmkenned/data-oriented
|
[
"e8c5b5bca4d4615ebfe8ded968cec11436ffae26"
] |
[
"zipf/pickWords.py"
] |
[
"#!/usr/bin/env python\n\nimport sys\nimport gzip\nimport random\n\nhas_numpy = False\ntry:\n import numpy\n has_numpy = True\nexcept ImportError:\n pass\n\nif has_numpy:\n\n x_cnt = dict()\n x = numpy.random.zipf(1.05, 100000)\n\n for i in x:\n i -= 1\n if i in x_cnt:\n x_cnt[i] += 1\n else:\n x_cnt[i] = 1\n\n keys_sorted = sorted(x_cnt.keys())\n for xi in keys_sorted:\n val = x_cnt[xi]\n print (xi+1, val)\n exit()\n\n# TODO: use argparse\n# TODO: allow for non-uniform distribution of word choices\n\nargc = len(sys.argv)\n\nif argc < 2:\n sys.stderr.write('usage: %s [N]\\n' % sys.argv[0])\n exit()\n\nn = int(sys.argv[1])\nm = int(sys.argv[2]) if (argc >= 3) else None\n\nif argc >= 4:\n seed = int(sys.argv[3])\n random.seed(seed)\n\nwith gzip.open('words.txt.gz', 'rb') as fh:\n lines = fh.read().decode('utf8').split('\\n')\n\n if m is None: m = len(lines)\n\n for i in range(0,n):\n r = random.randint(0,m-1)\n sys.stdout.write(lines[r] + '\\n')\n"
] |
[
[
"numpy.random.zipf"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
tokudaek/cs231n_spring18_assignments
|
[
"cf10f0768d95c4bcb7d34e116fd606a019dfb6ba"
] |
[
"assignment2_v2/cs231n/optim.py"
] |
[
"import numpy as np\n\n\"\"\"\nThis file implements various first-order update rules that are commonly used\nfor training neural networks. Each update rule accepts current weights and the\ngradient of the loss with respect to those weights and produces the next set of\nweights. Each update rule has the same interface:\n\ndef update(w, dw, config=None):\n\nInputs:\n - w: A numpy array giving the current weights.\n - dw: A numpy array of the same shape as w giving the gradient of the\n loss with respect to w.\n - config: A dictionary containing hyperparameter values such as learning\n rate, momentum, etc. If the update rule requires caching values over many\n iterations, then config will also hold these cached values.\n\nReturns:\n - next_w: The next point after the update.\n - config: The config dictionary to be passed to the next iteration of the\n update rule.\n\nNOTE: For most update rules, the default learning rate will probably not\nperform well; however the default values of the other hyperparameters should\nwork well for a variety of different problems.\n\nFor efficiency, update rules may perform in-place updates, mutating w and\nsetting next_w equal to w.\n\"\"\"\n\n\ndef sgd(w, dw, config=None):\n \"\"\"\n Performs vanilla stochastic gradient descent.\n\n config format:\n - learning_rate: Scalar learning rate.\n \"\"\"\n if config is None: config = {}\n config.setdefault('learning_rate', 1e-2)\n\n w -= config['learning_rate'] * dw\n return w, config\n\n\ndef sgd_momentum(w, dw, config=None):\n \"\"\"\n Performs stochastic gradient descent with momentum.\n\n config format:\n - learning_rate: Scalar learning rate.\n - momentum: Scalar between 0 and 1 giving the momentum value.\n Setting momentum = 0 reduces to sgd.\n - velocity: A numpy array of the same shape as w and dw used to store a\n moving average of the gradients.\n \"\"\"\n if config is None: config = {}\n config.setdefault('learning_rate', 1e-2)\n config.setdefault('momentum', 0.9)\n v = config.get('velocity', np.zeros_like(w))\n\n next_w = None\n ###########################################################################\n # TODO: Implement the momentum update formula. Store the updated value in #\n # the next_w variable. You should also use and update the velocity v. #\n ###########################################################################\n pass\n ###########################################################################\n # END OF YOUR CODE #\n ###########################################################################\n config['velocity'] = v\n\n return next_w, config\n\n\n\ndef rmsprop(w, dw, config=None):\n \"\"\"\n Uses the RMSProp update rule, which uses a moving average of squared\n gradient values to set adaptive per-parameter learning rates.\n\n config format:\n - learning_rate: Scalar learning rate.\n - decay_rate: Scalar between 0 and 1 giving the decay rate for the squared\n gradient cache.\n - epsilon: Small scalar used for smoothing to avoid dividing by zero.\n - cache: Moving average of second moments of gradients.\n \"\"\"\n if config is None: config = {}\n config.setdefault('learning_rate', 1e-2)\n config.setdefault('decay_rate', 0.99)\n config.setdefault('epsilon', 1e-8)\n config.setdefault('cache', np.zeros_like(w))\n\n next_w = None\n ###########################################################################\n # TODO: Implement the RMSprop update formula, storing the next value of w #\n # in the next_w variable. Don't forget to update cache value stored in #\n # config['cache']. #\n ###########################################################################\n pass\n ###########################################################################\n # END OF YOUR CODE #\n ###########################################################################\n\n return next_w, config\n\n\ndef adam(w, dw, config=None):\n \"\"\"\n Uses the Adam update rule, which incorporates moving averages of both the\n gradient and its square and a bias correction term.\n\n config format:\n - learning_rate: Scalar learning rate.\n - beta1: Decay rate for moving average of first moment of gradient.\n - beta2: Decay rate for moving average of second moment of gradient.\n - epsilon: Small scalar used for smoothing to avoid dividing by zero.\n - m: Moving average of gradient.\n - v: Moving average of squared gradient.\n - t: Iteration number.\n \"\"\"\n if config is None: config = {}\n config.setdefault('learning_rate', 1e-3)\n config.setdefault('beta1', 0.9)\n config.setdefault('beta2', 0.999)\n config.setdefault('epsilon', 1e-8)\n config.setdefault('m', np.zeros_like(w))\n config.setdefault('v', np.zeros_like(w))\n config.setdefault('t', 0)\n\n next_w = None\n ###########################################################################\n # TODO: Implement the Adam update formula, storing the next value of w in #\n # the next_w variable. Don't forget to update the m, v, and t variables #\n # stored in config. #\n # #\n # NOTE: In order to match the reference output, please modify t _before_ #\n # using it in any calculations. #\n ###########################################################################\n pass\n ###########################################################################\n # END OF YOUR CODE #\n ###########################################################################\n\n return next_w, config\n"
] |
[
[
"numpy.zeros_like"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jackwilkinson255/mbmpo_master
|
[
"8b1351df94dfe530efaff1118022315c8d877774",
"8b1351df94dfe530efaff1118022315c8d877774",
"8b1351df94dfe530efaff1118022315c8d877774",
"8b1351df94dfe530efaff1118022315c8d877774",
"8b1351df94dfe530efaff1118022315c8d877774",
"8b1351df94dfe530efaff1118022315c8d877774",
"8b1351df94dfe530efaff1118022315c8d877774",
"8b1351df94dfe530efaff1118022315c8d877774"
] |
[
"sandbox/ours/policies/utils.py",
"sandbox/ignasi/algos/MAML/maml_ppo.py",
"sandbox_maml/rocky/tf/spaces/discrete.py",
"rllab_maml/baselines/zero_baseline.py",
"sandbox_maml/rocky/tf/policies/categorical_lstm_policy.py",
"scripts_maml/sim_policy.py",
"plots/plot_utils_mb.py",
"rllab_maml/envs/mujoco/hopper_env.py"
] |
[
"import numpy as np\nfrom collections import OrderedDict\nfrom rllab_maml.core.serializable import Serializable\nfrom rllab.misc import logger\nfrom rllab_maml.misc.tensor_utils import flatten_tensors, unflatten_tensors\nfrom sandbox.ours.core.utils import make_dense_layer_with_bias_transform, forward_dense_bias_transform, \\\n make_dense_layer\nimport tensorflow as tf\nfrom sandbox_maml.rocky.tf.misc.xavier_init import xavier_initializer\nfrom sandbox_maml.rocky.tf.core.utils import make_input, make_param_layer, forward_param_layer, forward_dense_layer\nload_params = True\n\n\ndef create_MLP(name, input_shape, output_dim, hidden_sizes,\n hidden_W_init=xavier_initializer(), hidden_b_init=tf.zeros_initializer(),\n output_W_init=xavier_initializer(), output_b_init=tf.zeros_initializer(),\n weight_normalization=False, bias_transform=False, param_noise_std_ph=None):\n\n all_params = OrderedDict()\n\n cur_shape = input_shape\n with tf.variable_scope(name):\n if bias_transform:\n for idx, hidden_size in enumerate(hidden_sizes):\n # hidden layers\n W, b, bias_transform, cur_shape = make_dense_layer_with_bias_transform(\n cur_shape,\n num_units=hidden_size,\n name=\"hidden_%d\" % idx,\n W=hidden_W_init,\n b=hidden_b_init,\n bias_transform=hidden_b_init,\n weight_norm=weight_normalization,\n )\n all_params['W' + str(idx)] = W\n all_params['b' + str(idx)] = b\n all_params['bias_transform' + str(idx)] = bias_transform\n\n # output layer\n W, b, bias_transform, _ = make_dense_layer_with_bias_transform(\n cur_shape,\n num_units=output_dim,\n name='output',\n W=hidden_W_init,\n b=hidden_b_init,\n bias_transform=hidden_b_init,\n weight_norm=weight_normalization,\n param_noise_std_ph=param_noise_std_ph\n )\n all_params['W' + str(len(hidden_sizes))] = W\n all_params['b' + str(len(hidden_sizes))] = b\n all_params['bias_transform' + str(len(hidden_sizes))] = bias_transform\n\n else:\n for idx, hidden_size in enumerate(hidden_sizes):\n W, b, cur_shape = make_dense_layer(\n cur_shape,\n num_units=hidden_size,\n name=\"hidden_%d\" % idx,\n W=hidden_W_init,\n b=hidden_b_init,\n weight_norm=weight_normalization,\n )\n all_params['W' + str(idx)] = W\n all_params['b' + str(idx)] = b\n W, b, _ = make_dense_layer(\n cur_shape,\n num_units=output_dim,\n name='output',\n W=output_W_init,\n b=output_b_init,\n weight_norm=weight_normalization,\n param_noise_std_ph=param_noise_std_ph\n )\n all_params['W' + str(len(hidden_sizes))] = W\n all_params['b' + str(len(hidden_sizes))] = b\n\n return all_params\n\n\ndef forward_MLP(name, input_shape, n_hidden, hidden_nonlinearity, output_nonlinearity,\n all_params, input_tensor=None, batch_normalization=False, reuse=True,\n is_training=False, bias_transform=False):\n # is_training and reuse are for batch norm, irrelevant if batch_norm set to False\n # set reuse to False if the first time this func is called.\n with tf.variable_scope(name):\n if input_tensor is None:\n l_in = make_input(shape=input_shape, input_var=None, name='input')\n else:\n l_in = input_tensor\n\n l_hid = l_in\n\n for idx in range(n_hidden):\n bias_transform_ = all_params['bias_transform' + str(idx)] if bias_transform else None\n l_hid = forward_dense_bias_transform(l_hid, all_params['W' + str(idx)], all_params['b' + str(idx)],\n bias_transform=bias_transform_,\n batch_norm=batch_normalization,\n nonlinearity=hidden_nonlinearity,\n scope=str(idx), reuse=reuse,\n is_training=is_training\n )\n\n bias_transform = all_params['bias_transform' + str(n_hidden)] if bias_transform else None\n output = forward_dense_bias_transform(l_hid, all_params['W' + str(n_hidden)],\n all_params['b' + str(n_hidden)],\n bias_transform=bias_transform, batch_norm=False,\n nonlinearity=output_nonlinearity,\n )\n return l_in, output\n",
"from rllab_maml.misc import ext\nfrom rllab_maml.misc.overrides import overrides\nimport rllab.misc.logger as logger\nfrom sandbox.ours.algos.MAML.batch_maml_polopt import BatchMAMLPolopt\nfrom sandbox.ours.optimizers.maml_ppo_optimizer import MAMLPPOOptimizer\nfrom sandbox_maml.rocky.tf.misc import tensor_utils\nimport tensorflow as tf\nimport numpy as np\n\nclass MAMLPPO(BatchMAMLPolopt):\n \"\"\"\n Natural Policy Optimization.\n \"\"\"\n\n def __init__(\n self,\n optimizer=None,\n optimizer_args=None,\n use_maml=True,\n clip_eps=0.2, \n target_inner_step=0.01,\n init_kl_penalty=1,\n adaptive_kl_penalty=True,\n num_batches=10,\n **kwargs):\n if optimizer is None:\n if optimizer_args is None:\n optimizer_args = dict(max_epochs=1, batch_size=num_batches, verbose=True)\n optimizer = MAMLPPOOptimizer(**optimizer_args)\n self.optimizer = optimizer\n self.use_maml = use_maml\n self.clip_eps = clip_eps\n self.target_inner_step = target_inner_step\n self.adaptive_kl_penalty = adaptive_kl_penalty\n super(MAMLPPO, self).__init__(**kwargs)\n self.kl_coeff = [init_kl_penalty] * self.meta_batch_size * self.num_grad_updates\n self._optimization_keys = ['observations', 'actions', 'advantages', 'agent_infos']\n\n def make_vars(self, stepnum='0'):\n # lists over the meta_batch_size\n obs_vars, action_vars, adv_vars = [], [], []\n for i in range(self.meta_batch_size):\n obs_vars.append(self.env.observation_space.new_tensor_variable(\n 'obs' + stepnum + '_' + str(i),\n extra_dims=1,\n ))\n action_vars.append(self.env.action_space.new_tensor_variable(\n 'action' + stepnum + '_' + str(i),\n extra_dims=1,\n ))\n adv_vars.append(tensor_utils.new_tensor(\n name='advantage' + stepnum + '_' + str(i),\n ndim=1, dtype=tf.float32,\n ))\n return obs_vars, action_vars, adv_vars\n\n @overrides\n def init_opt(self):\n is_recurrent = int(self.policy.recurrent)\n assert not is_recurrent # not supported\n\n dist = self.policy.distribution \n\n state_info_vars = {}\n\n all_surr_objs, input_list = [], []\n kl_list = []\n entropy_list = []\n new_params = None\n\n # MAML inner loop\n for j in range(self.num_grad_updates):\n obs_vars, action_vars, adv_vars = self.make_vars(str(j))\n old_dist_info_vars, old_dist_info_vars_list = [], []\n for i in range(self.meta_batch_size):\n old_dist_info_vars.append({\n k: tf.placeholder(tf.float32, shape=[None] + list(shape), name='old_%s_%s_%s' % (j, i, k))\n for k, shape in dist.dist_info_specs\n })\n old_dist_info_vars_list += [old_dist_info_vars[i][k] for k in dist.dist_info_keys]\n surr_objs = []\n _surr_objs_ph = []\n\n cur_params = new_params\n new_params = [] # if there are several grad_updates the new_params are overwritten\n kls = []\n entropies = []\n\n # It's adding the KL constrain to theta' and theta_(old)'\n for i in range(self.meta_batch_size):\n if j == 0:\n dist_info_vars, params = self.policy.dist_info_sym(obs_vars[i], state_info_vars, all_params=self.policy.all_params)\n else:\n dist_info_vars, params = self.policy.updated_dist_info_sym(i, all_surr_objs[-1][i], obs_vars[i], params_dict=cur_params[i])\n kls.append(tf.reduce_mean(dist.kl_sym(old_dist_info_vars[i], dist_info_vars)))\n new_params.append(params)\n lr = dist.likelihood_ratio_sym(action_vars[i], old_dist_info_vars[i], dist_info_vars)\n if self.entropy_bonus > 0:\n entropy = self.entropy_bonus * tf.reduce_mean(dist.entropy_sym(dist_info_vars))\n else:\n entropy = 0\n entropies.append(entropy)\n # formulate as a minimization problem\n # The gradient of the surrogate objective is the policy gradient\n\n surr_objs.append(-tf.reduce_mean(lr * adv_vars[i]))\n if j == 0:\n _dist_info_vars, _ = self.policy.dist_info_sym(obs_vars[i], state_info_vars,\n all_params=self.policy.all_params_ph[i])\n _lr_ph = dist.likelihood_ratio_sym(action_vars[i], old_dist_info_vars[i], _dist_info_vars)\n _surr_objs_ph.append(-tf.reduce_mean(_lr_ph * adv_vars[i]))\n\n input_list += obs_vars + action_vars + adv_vars + old_dist_info_vars_list\n\n if j == 0:\n # For computing the fast update for sampling\n self.policy.set_init_surr_obj(input_list, _surr_objs_ph)\n self.policy._update_input_keys = self._optimization_keys\n init_input_list = input_list\n\n all_surr_objs.append(surr_objs)\n kl_list.append(kls)\n entropy_list.append(entropies)\n\n obs_vars, action_vars, adv_vars = self.make_vars('test')\n old_dist_info_vars, old_dist_info_vars_list = [], []\n for i in range(self.meta_batch_size):\n old_dist_info_vars.append({\n k: tf.placeholder(tf.float32, shape=[None] + list(shape), name='old_test_%s_%s' % (i, k))\n for k, shape in dist.dist_info_specs\n })\n old_dist_info_vars_list += [old_dist_info_vars[i][k] for k in dist.dist_info_keys]\n surr_objs = []\n kl_coeff_vars_list = list(list(tf.placeholder(tf.float32, shape=[], name='kl_%s_%s' % (j, i))\n for i in range(self.meta_batch_size)) for j in range(self.num_grad_updates))\n\n # MAML outer loop\n for i in range(self.meta_batch_size):\n dist_info_vars, _ = self.policy.updated_dist_info_sym(i, all_surr_objs[-1][i], obs_vars[i], params_dict=new_params[i])\n lr = dist.likelihood_ratio_sym(action_vars[i], old_dist_info_vars[i], dist_info_vars)\n kl_penalty = sum(list(kl_list[j][i] * kl_coeff_vars_list[j][i] for j in range(self.num_grad_updates)))\n entropy_bonus = sum(list(entropy_list[j][i] for j in range(self.num_grad_updates)))\n clipped_obj = tf.minimum(lr * adv_vars[i], tf.clip_by_value(lr, 1-self.clip_eps, 1+self.clip_eps) * adv_vars[i])\n surr_objs.append(- tf.reduce_mean(clipped_obj) + kl_penalty - entropy_bonus)\n\n if self.use_maml:\n surr_obj = tf.reduce_mean(tf.stack(surr_objs, 0)) # mean over meta_batch_size (the diff tasks)\n input_list += obs_vars + action_vars + adv_vars + old_dist_info_vars_list\n else:\n surr_obj = tf.reduce_mean(tf.stack(all_surr_objs[0], 0)) # if not meta, just use the first surr_obj\n input_list = init_input_list\n\n kl_list = sum(kl_list, [])\n kl_coeff_vars_list = sum(kl_coeff_vars_list, [])\n self.optimizer.update_opt(\n loss=surr_obj,\n target=self.policy,\n inputs=input_list,\n inner_kl=kl_list,\n extra_inputs=kl_coeff_vars_list,\n meta_batch_size=self.meta_batch_size,\n num_grad_updates=self.num_grad_updates,\n )\n self.kl_list = kl_list\n return dict()\n\n @overrides\n def optimize_policy(self, itr, all_samples_data, log=True):\n assert len(all_samples_data) == self.num_grad_updates + 1 # we collected the rollouts to compute the grads and then the test!\n\n if not self.use_maml:\n all_samples_data = [all_samples_data[0]]\n\n input_list = []\n for step in range(len(all_samples_data)): # these are the gradient steps\n obs_list, action_list, adv_list, dist_info_list = [], [], [], []\n for i in range(self.meta_batch_size):\n\n inputs = ext.extract(\n all_samples_data[step][i], *self._optimization_keys\n )\n obs_list.append(inputs[0])\n action_list.append(inputs[1])\n adv_list.append(inputs[2])\n dist_info_list.extend([inputs[3][k] for k in self.policy.distribution.dist_info_keys])\n\n input_list += obs_list + action_list + adv_list + dist_info_list # [ [obs_0], [act_0], [adv_0], [dist_0], [obs_1], ... ]\n kl_coeff = tuple(self.kl_coeff)\n if log: logger.log(\"Computing loss before\")\n loss_before = self.optimizer.loss(input_list, extra_inputs=kl_coeff)\n if log: logger.log(\"Optimizing\") \n self.optimizer.optimize(input_list, extra_inputs=kl_coeff)\n if log: logger.log(\"Computing loss after\")\n loss_after = self.optimizer.loss(input_list, extra_inputs=kl_coeff)\n\n kls = self.optimizer.inner_kl(input_list, extra_inputs=kl_coeff)\n if self.adaptive_kl_penalty:\n if log: logger.log(\"Updating KL loss coefficients\")\n for i, kl in enumerate(kls):\n if kl < self.target_inner_step / 1.5:\n self.kl_coeff[i] /= 2\n if kl > self.target_inner_step * 1.5:\n self.kl_coeff[i] *= 2\n\n if self.use_maml and log:\n logger.record_tabular('LossBefore', loss_before)\n logger.record_tabular('LossAfter', loss_after)\n logger.record_tabular('dLoss', loss_before - loss_after)\n logger.record_tabular('klDiff', np.mean(kls))\n return dict()\n\n @overrides\n def get_itr_snapshot(self, itr, samples_data):\n return dict(\n itr=itr,\n policy=self.policy,\n baseline=self.baseline,\n env=self.env,\n )\n\n",
"from rllab_maml.spaces.base import Space\nimport numpy as np\nfrom rllab_maml.misc import special\nfrom rllab_maml.misc import ext\nimport tensorflow as tf\n\n\nclass Discrete(Space):\n \"\"\"\n {0,1,...,n-1}\n \"\"\"\n\n def __init__(self, n):\n self._n = n\n\n @property\n def n(self):\n return self._n\n\n def sample(self):\n return np.random.randint(self.n)\n\n def sample_n(self, n):\n return np.random.randint(low=0, high=self.n, size=n)\n\n def contains(self, x):\n x = np.asarray(x)\n return x.shape == () and x.dtype.kind == 'i' and x >= 0 and x < self.n\n\n def __repr__(self):\n return \"Discrete(%d)\" % self.n\n\n def __eq__(self, other):\n return self.n == other.n\n\n def flatten(self, x):\n return special.to_onehot(x, self.n)\n\n def unflatten(self, x):\n return special.from_onehot(x)\n\n def flatten_n(self, x):\n return special.to_onehot_n(x, self.n)\n\n def unflatten_n(self, x):\n return special.from_onehot_n(x)\n\n @property\n def default_value(self):\n return 0\n\n @property\n def flat_dim(self):\n return self.n\n\n def weighted_sample(self, weights):\n return special.weighted_sample(weights, range(self.n))\n\n def new_tensor_variable(self, name, extra_dims):\n # needed for safe conversion to float32\n return tf.placeholder(dtype=tf.uint8, shape=[None] * extra_dims + [self.flat_dim], name=name)\n\n def __eq__(self, other):\n if not isinstance(other, Discrete):\n return False\n return self.n == other.n\n\n def __hash__(self):\n return hash(self.n)\n",
"import numpy as np\nfrom rllab_maml.baselines.base import Baseline\nfrom rllab_maml.misc.overrides import overrides\n\n\nclass ZeroBaseline(Baseline):\n\n def __init__(self, env_spec):\n pass\n\n @overrides\n def get_param_values(self, **kwargs):\n return None\n\n @overrides\n def set_param_values(self, val, **kwargs):\n pass\n\n @overrides\n def fit(self, paths, **kwargs):\n pass\n\n @overrides\n def predict(self, path):\n return np.zeros_like(path[\"rewards\"])\n",
"import numpy as np\nimport sandbox_maml.rocky.tf.core.layers as L\nimport tensorflow as tf\nfrom sandbox_maml.rocky.tf.core.layers_powered import LayersPowered\nfrom sandbox_maml.rocky.tf.core.network import LSTMNetwork, MLP\nfrom sandbox_maml.rocky.tf.distributions.recurrent_categorical import RecurrentCategorical\nfrom sandbox_maml.rocky.tf.misc import tensor_utils\nfrom sandbox_maml.rocky.tf.spaces.discrete import Discrete\nfrom sandbox_maml.rocky.tf.policies.base import StochasticPolicy\n\nfrom rllab_maml.core.serializable import Serializable\nfrom rllab_maml.misc import special\nfrom rllab_maml.misc.overrides import overrides\n\n\nclass CategoricalLSTMPolicy(StochasticPolicy, LayersPowered, Serializable):\n def __init__(\n self,\n name,\n env_spec,\n hidden_dim=32,\n feature_network=None,\n prob_network=None,\n state_include_action=True,\n hidden_nonlinearity=tf.tanh,\n forget_bias=1.0,\n use_peepholes=False,\n lstm_layer_cls=L.LSTMLayer\n ):\n \"\"\"\n :param env_spec: A spec for the env.\n :param hidden_dim: dimension of hidden layer\n :param hidden_nonlinearity: nonlinearity used for each hidden layer\n :return:\n \"\"\"\n with tf.variable_scope(name):\n assert isinstance(env_spec.action_space, Discrete)\n Serializable.quick_init(self, locals())\n super(CategoricalLSTMPolicy, self).__init__(env_spec)\n\n obs_dim = env_spec.observation_space.flat_dim\n action_dim = env_spec.action_space.flat_dim\n\n if state_include_action:\n input_dim = obs_dim + action_dim\n else:\n input_dim = obs_dim\n\n l_input = L.InputLayer(\n shape=(None, None, input_dim),\n name=\"input\"\n )\n\n if feature_network is None:\n feature_dim = input_dim\n l_flat_feature = None\n l_feature = l_input\n else:\n feature_dim = feature_network.output_layer.output_shape[-1]\n l_flat_feature = feature_network.output_layer\n l_feature = L.OpLayer(\n l_flat_feature,\n extras=[l_input],\n name=\"reshape_feature\",\n op=lambda flat_feature, input: tf.reshape(\n flat_feature,\n tf.pack([tf.shape(input)[0], tf.shape(input)[1], feature_dim])\n ),\n shape_op=lambda _, input_shape: (input_shape[0], input_shape[1], feature_dim)\n )\n\n if prob_network is None:\n prob_network = LSTMNetwork(\n input_shape=(feature_dim,),\n input_layer=l_feature,\n output_dim=env_spec.action_space.n,\n hidden_dim=hidden_dim,\n hidden_nonlinearity=hidden_nonlinearity,\n output_nonlinearity=tf.nn.softmax,\n forget_bias=forget_bias,\n use_peepholes=use_peepholes,\n lstm_layer_cls=lstm_layer_cls,\n name=\"prob_network\"\n )\n\n self.prob_network = prob_network\n self.feature_network = feature_network\n self.l_input = l_input\n self.state_include_action = state_include_action\n\n flat_input_var = tf.placeholder(dtype=tf.float32, shape=(None, input_dim), name=\"flat_input\")\n if feature_network is None:\n feature_var = flat_input_var\n else:\n feature_var = L.get_output(l_flat_feature, {feature_network.input_layer: flat_input_var})\n\n self.f_step_prob = tensor_utils.compile_function(\n [\n flat_input_var,\n prob_network.step_prev_hidden_layer.input_var,\n prob_network.step_prev_cell_layer.input_var\n ],\n L.get_output([\n prob_network.step_output_layer,\n prob_network.step_hidden_layer,\n prob_network.step_cell_layer\n ], {prob_network.step_input_layer: feature_var})\n )\n\n self.input_dim = input_dim\n self.action_dim = action_dim\n self.hidden_dim = hidden_dim\n\n self.prev_actions = None\n self.prev_hiddens = None\n self.prev_cells = None\n self.dist = RecurrentCategorical(env_spec.action_space.n)\n\n out_layers = [prob_network.output_layer]\n if feature_network is not None:\n out_layers.append(feature_network.output_layer)\n\n LayersPowered.__init__(self, out_layers)\n\n @overrides\n def dist_info_sym(self, obs_var, state_info_vars):\n n_batches = tf.shape(obs_var)[0]\n n_steps = tf.shape(obs_var)[1]\n obs_var = tf.reshape(obs_var, tf.pack([n_batches, n_steps, -1]))\n obs_var = tf.cast(obs_var, tf.float32)\n if self.state_include_action:\n prev_action_var = state_info_vars[\"prev_action\"]\n prev_action_var = tf.cast(prev_action_var, tf.float32)\n all_input_var = tf.concat(axis=2, values=[obs_var, prev_action_var])\n else:\n all_input_var = obs_var\n if self.feature_network is None:\n return dict(\n prob=L.get_output(\n self.prob_network.output_layer,\n {self.l_input: all_input_var}\n )\n )\n else:\n flat_input_var = tf.reshape(all_input_var, (-1, self.input_dim))\n return dict(\n prob=L.get_output(\n self.prob_network.output_layer,\n {self.l_input: all_input_var, self.feature_network.input_layer: flat_input_var}\n )\n )\n\n @property\n def vectorized(self):\n return True\n\n def reset(self, dones=None):\n if dones is None:\n dones = [True]\n dones = np.asarray(dones)\n if self.prev_actions is None or len(dones) != len(self.prev_actions):\n self.prev_actions = np.zeros((len(dones), self.action_space.flat_dim))\n self.prev_hiddens = np.zeros((len(dones), self.hidden_dim))\n self.prev_cells = np.zeros((len(dones), self.hidden_dim))\n\n self.prev_actions[dones] = 0.\n self.prev_hiddens[dones] = self.prob_network.hid_init_param.eval()\n self.prev_cells[dones] = self.prob_network.cell_init_param.eval()\n\n # The return value is a pair. The first item is a matrix (N, A), where each\n # entry corresponds to the action value taken. The second item is a vector\n # of length N, where each entry is the density value for that action, under\n # the current policy\n @overrides\n def get_action(self, observation):\n actions, agent_infos = self.get_actions([observation])\n return actions[0], {k: v[0] for k, v in agent_infos.items()}\n\n @overrides\n def get_actions(self, observations):\n flat_obs = self.observation_space.flatten_n(observations)\n if self.state_include_action:\n assert self.prev_actions is not None\n all_input = np.concatenate([\n flat_obs,\n self.prev_actions\n ], axis=-1)\n else:\n all_input = flat_obs\n probs, hidden_vec, cell_vec = self.f_step_prob(all_input, self.prev_hiddens, self.prev_cells)\n actions = special.weighted_sample_n(probs, np.arange(self.action_space.n))\n prev_actions = self.prev_actions\n self.prev_actions = self.action_space.flatten_n(actions)\n self.prev_hiddens = hidden_vec\n self.prev_cells = cell_vec\n agent_info = dict(prob=probs)\n if self.state_include_action:\n agent_info[\"prev_action\"] = np.copy(prev_actions)\n return actions, agent_info\n\n @property\n @overrides\n def recurrent(self):\n return True\n\n @property\n def distribution(self):\n return self.dist\n\n @property\n def state_info_specs(self):\n if self.state_include_action:\n return [\n (\"prev_action\", (self.action_dim,)),\n ]\n else:\n return []\n",
"import argparse\n\nimport joblib\nimport tensorflow as tf\n\nfrom rllab_maml.misc.console import query_yes_no\nfrom rllab_maml.sampler.utils import rollout\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser()\n parser.add_argument('file', type=str,\n help='path to the snapshot file')\n parser.add_argument('--max_path_length', type=int, default=1000,\n help='Max length of rollout')\n parser.add_argument('--speedup', type=float, default=1,\n help='Speedup')\n parser.add_argument('--video_filename', type=str,\n help='path to the out video file')\n parser.add_argument('--prompt', type=bool, default=False,\n help='Whether or not to prompt for more sim')\n parser.add_argument('--ignore_done', type=bool, default=True,\n help='Whether stop animation when environment done or continue anyway')\n args = parser.parse_args()\n\n max_tries = 10\n tri = 0\n while True:\n tri += 1\n with tf.Session() as sess:\n data = joblib.load(args.file)\n policy = data['policy']\n env = data['env']\n while True:\n path = rollout(env, policy, max_path_length=args.max_path_length,\n animated=True, speedup=args.speedup, video_filename=args.video_filename, ignore_done=args.ignore_done)\n if args.prompt:\n if not query_yes_no('Continue simulation?'):\n break\n else:\n break\n #import pdb; pdb.set_trace()\n if len(path['rewards']) < args.max_path_length and tri >= max_tries:\n tf.reset_default_graph()\n continue\n break\n",
"import numpy as np\nfrom rllab.misc.ext import flatten\nfrom pprint import pprint\nfrom collections import OrderedDict, defaultdict\n\ndef filter(exps_data, filters={}):\n print(\"before filtering\", len(exps_data), 'exps')\n keep_array = []\n if filters:\n for i, exp in enumerate(exps_data):\n keep_array.append(all([((filter_key not in exp['flat_params']) or ((filter_key in exp['flat_params']) and (exp['flat_params'][filter_key] == filter_val)))\n for filter_key, filter_val in filters.items()]))\n exps_data_filtered = np.array(exps_data)\n exps_data_filtered = exps_data_filtered[keep_array]\n else:\n exps_data_filtered = exps_data\n print(\"after filtering\", len(exps_data_filtered), 'exps')\n return exps_data_filtered\n\ndef group_by(exp_data, group_by_key=None):\n split_dict = OrderedDict()\n for exp in exp_data:\n if group_by_key == 'exp_name':\n exp['flat_params']['exp_name'] = exp['flat_params']['exp_name'].replace('-', '_')\n key_str = str(exp['flat_params'][group_by_key]).split('_')[2]\n if key_str == 'maml':\n key_str = 'ours'\n elif key_str == 'mpc':\n key_str = 'mb-mpc'\n elif key_str == 'train':\n key_str = 'me-trpo'\n elif group_by_key == 'env.$class':\n key_str = str(exp['flat_params'][group_by_key]).split('.')[-1]\n if key_str[-13:] == 'EnvRandParams':\n key_str = key_str[:-13]\n elif key_str[-15:] == 'EnvRandomParams':\n key_str = key_str[:-15] + '2D'\n else:\n key_str = key_str[:-3]\n else:\n key_str = str(exp['flat_params'][group_by_key])\n if key_str in split_dict.keys():\n split_dict[key_str].append(exp)\n else:\n split_dict[key_str] = [exp]\n return split_dict\n\ndef prepare_data_for_plot(exp_data, x_key='n_timesteps', y_key=None, sup_y_key=None, round_x=None):\n x_y_tuples = []\n for exp in exp_data:\n name = exp['flat_params']['exp_name'].replace('-', '_')\n key_str = str(name).split('_')[2]\n if key_str == 'maml':\n off_set = (exp['progress'][x_key][1] - exp['progress'][x_key][0])/2\n else:\n off_set = 0\n if sup_y_key is not None:\n assert type(sup_y_key) is list\n for key in sup_y_key:\n if key in exp['progress'].keys():\n x_y_tuples.extend(list(zip(exp['progress'][x_key]-off_set, exp['progress'][key])))\n break\n else:\n x_y_tuples.extend(list(zip(exp['progress'][x_key], exp['progress'][y_key])))\n x_y_dict = defaultdict(list)\n for k, v in x_y_tuples:\n if round_x is not None:\n x_y_dict[(k//round_x) * round_x].append(v)\n else:\n x_y_dict[k].append(v)\n means, stddevs = [], []\n for key in sorted(x_y_dict.keys()):\n means.append(np.mean(x_y_dict[key]))\n stddevs.append(np.std(x_y_dict[key]))\n return np.array(sorted(x_y_dict.keys())), np.array(means), np.array(stddevs)\n\ndef correct_limit(ax, x, y):\n # ax: axes object handle\n # x: data for entire x-axes\n # y: data for entire y-axes\n # assumption: you have already set the x-limit as desired\n lims = ax.get_xlim()\n i = np.where((x > lims[0]) & (x < lims[1]))[0]\n return y[i].min(), y[i].max()\n",
"import numpy as np\n\nfrom rllab_maml.core.serializable import Serializable\nfrom rllab_maml.envs.base import Step\nfrom rllab_maml.envs.mujoco.mujoco_env import MujocoEnv\nfrom rllab_maml.misc import autoargs\nfrom rllab_maml.misc import logger\nfrom rllab_maml.misc.overrides import overrides\n\n\n# states: [\n# 0: z-coord,\n# 1: x-coord (forward distance),\n# 2: forward pitch along y-axis,\n# 6: z-vel (up = +),\n# 7: xvel (forward = +)\n\n\nclass HopperEnv(MujocoEnv, Serializable):\n\n FILE = 'hopper.xml'\n\n @autoargs.arg('alive_coeff', type=float,\n help='reward coefficient for being alive')\n @autoargs.arg('ctrl_cost_coeff', type=float,\n help='cost coefficient for controls')\n def __init__(\n self,\n alive_coeff=1,\n ctrl_cost_coeff=0.01,\n *args, **kwargs):\n self.alive_coeff = alive_coeff\n self.ctrl_cost_coeff = ctrl_cost_coeff\n super(HopperEnv, self).__init__(*args, **kwargs)\n Serializable.quick_init(self, locals())\n\n @overrides\n def get_current_obs(self):\n return np.concatenate([\n self.model.data.qpos[0:1].flat,\n self.model.data.qpos[2:].flat,\n np.clip(self.model.data.qvel, -10, 10).flat,\n np.clip(self.model.data.qfrc_constraint, -10, 10).flat,\n self.get_body_com(\"torso\").flat,\n ])\n\n @overrides\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 vel = self.get_body_comvel(\"torso\")[0]\n reward = vel + self.alive_coeff - \\\n 0.5 * self.ctrl_cost_coeff * np.sum(np.square(action / scaling))\n state = self._state\n notdone = np.isfinite(state).all() and \\\n (np.abs(state[3:]) < 100).all() and (state[0] > .7) and \\\n (abs(state[2]) < .2)\n done = not notdone\n return Step(next_obs, reward, done)\n\n @overrides\n def log_diagnostics(self, paths):\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"
] |
[
[
"tensorflow.variable_scope",
"tensorflow.zeros_initializer"
],
[
"tensorflow.clip_by_value",
"tensorflow.reduce_mean",
"tensorflow.stack",
"tensorflow.placeholder",
"numpy.mean"
],
[
"numpy.asarray",
"tensorflow.placeholder",
"numpy.random.randint"
],
[
"numpy.zeros_like"
],
[
"tensorflow.concat",
"tensorflow.shape",
"numpy.asarray",
"numpy.arange",
"tensorflow.cast",
"tensorflow.reshape",
"tensorflow.placeholder",
"numpy.concatenate",
"numpy.copy",
"tensorflow.variable_scope",
"tensorflow.pack"
],
[
"tensorflow.reset_default_graph",
"tensorflow.Session"
],
[
"numpy.std",
"numpy.array",
"numpy.where",
"numpy.mean"
],
[
"numpy.square",
"numpy.abs",
"numpy.isfinite",
"numpy.clip",
"numpy.min",
"numpy.max",
"numpy.std",
"numpy.mean"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.4",
"1.5",
"1.7",
"0.12",
"1.0",
"1.2"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"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": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"0.12",
"1.7"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.13",
"1.5",
"1.7",
"0.12",
"1.0",
"1.2"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
xinhezhou/ticket2ride
|
[
"d0edb2fdbe309e06bd2a2606c1fed35aa37c4d5f"
] |
[
"nonRLplayers/frugal_player.py"
] |
[
"import numpy as np\nimport random\nfrom utils.game_utils import check_path, compute_availability_matrix, get_available_routes, compute_progress\n\nclass FrugalPlayer:\n def __init__(self, num_colors, destination_cards, trains, id):\n self.cards = num_colors * [0]\n self.routes = {}\n self.destination_cards = destination_cards\n self.trains = trains\n self.id = id\n\n\n def choose_route(self, game, players):\n \"\"\"\n Find all possible routes and chooses a route that makes\n the most progress\n \"\"\"\n graph = game.graph\n status = game.status\n availability = compute_availability_matrix(graph, status, self)\n available_routes = get_available_routes(availability)\n route_progress = []\n for route in available_routes:\n route_progress.append(compute_progress(graph, status, route, self.destination_cards, self.id))\n # print(route_progress)\n return available_routes[np.argmax(route_progress)]\n\n\n def draw_or_claim(self, game, players):\n \"\"\"\n If there is at least one path that can be completed, claim a route (1).\n Otherwise, draw 2 cards (0)\n \"\"\"\n graph = game.graph\n status = game.status\n availability = compute_availability_matrix(graph, status, self)\n for a, b in self.destination_cards:\n if check_path(availability, a, b):\n return 1\n return 0\n"
] |
[
[
"numpy.argmax"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
marckassay/holoviews
|
[
"a2b37dc70228e34ffb6fe329f0854b1ad6502636"
] |
[
"holoviews/element/chart.py"
] |
[
"import numpy as np\nimport param\n\nfrom ..core import util\nfrom ..core import Dimension, Dataset, Element2D\nfrom ..core.data import GridInterface\nfrom .geom import Rectangles, Points, VectorField # noqa: backward compatible import\nfrom .selection import Selection1DExpr, Selection2DExpr\n\n\nclass Chart(Dataset, Element2D):\n \"\"\"\n A Chart is an abstract baseclass for elements representing one or\n more independent and dependent variables defining a 1D coordinate\n system with associated values. The independent variables or key\n dimensions map onto the x-axis while the dependent variables are\n usually mapped to the location, height or spread along the\n y-axis. Any number of additional value dimensions may be\n associated with a Chart.\n\n If a chart's independent variable (or key dimension) is numeric\n the chart will represent a discretely sampled version of the\n underlying continuously sampled 1D space. Therefore indexing along\n this variable will automatically snap to the closest coordinate.\n\n Since a Chart is a subclass of a Dataset it supports the full set\n of data interfaces but usually each dimension of a chart represents\n a column stored in a dictionary, array or DataFrame.\n \"\"\"\n\n kdims = param.List(default=[Dimension('x')], bounds=(1,2), doc=\"\"\"\n The key dimension(s) of a Chart represent the independent\n variable(s).\"\"\")\n\n group = param.String(default='Chart', constant=True)\n\n vdims = param.List(default=[Dimension('y')], bounds=(1, None), doc=\"\"\"\n The value dimensions of the Chart, usually corresponding to a\n number of dependent variables.\"\"\")\n\n # Enables adding index if 1D array like data is supplied\n _auto_indexable_1d = True\n\n __abstract = True\n\n def __getitem__(self, index):\n return super(Chart, self).__getitem__(index)\n\n\nclass Scatter(Selection2DExpr, Chart):\n \"\"\"\n Scatter is a Chart element representing a set of points in a 1D\n coordinate system where the key dimension maps to the points\n location along the x-axis while the first value dimension\n represents the location of the point along the y-axis.\n \"\"\"\n\n group = param.String(default='Scatter', constant=True)\n\n\nclass Curve(Selection1DExpr, Chart):\n \"\"\"\n Curve is a Chart element representing a line in a 1D coordinate\n system where the key dimension maps on the line x-coordinate and\n the first value dimension represents the height of the line along\n the y-axis.\n \"\"\"\n\n group = param.String(default='Curve', constant=True)\n\n\nclass ErrorBars(Selection1DExpr, Chart):\n \"\"\"\n ErrorBars is a Chart element representing error bars in a 1D\n coordinate system where the key dimension corresponds to the\n location along the x-axis and the first value dimension\n corresponds to the location along the y-axis and one or two\n extra value dimensions corresponding to the symmetric or\n asymetric errors either along x-axis or y-axis. If two value\n dimensions are given, then the last value dimension will be\n taken as symmetric errors. If three value dimensions are given\n then the last two value dimensions will be taken as negative and\n positive errors. By default the errors are defined along y-axis.\n A parameter `horizontal`, when set `True`, will define the errors\n along the x-axis.\n \"\"\"\n\n group = param.String(default='ErrorBars', constant=True, doc=\"\"\"\n A string describing the quantity measured by the ErrorBars\n object.\"\"\")\n\n vdims = param.List(default=[Dimension('y'), Dimension('yerror')],\n bounds=(1, None), constant=True)\n\n horizontal = param.Boolean(default=False, doc=\"\"\"\n Whether the errors are along y-axis (vertical) or x-axis.\"\"\")\n\n def range(self, dim, data_range=True, dimension_range=True):\n \"\"\"Return the lower and upper bounds of values along dimension.\n\n Range of the y-dimension includes the symmetric or assymetric\n error.\n\n Args:\n dimension: The dimension to compute the range on.\n data_range (bool): Compute range from data values\n dimension_range (bool): Include Dimension ranges\n Whether to include Dimension range and soft_range\n in range calculation\n\n Returns:\n Tuple containing the lower and upper bound\n \"\"\"\n dim_with_err = 0 if self.horizontal else 1\n didx = self.get_dimension_index(dim)\n dim = self.get_dimension(dim)\n if didx == dim_with_err and data_range and len(self):\n mean = self.dimension_values(didx)\n neg_error = self.dimension_values(2)\n if len(self.dimensions()) > 3:\n pos_error = self.dimension_values(3)\n else:\n pos_error = neg_error\n lower = np.nanmin(mean-neg_error)\n upper = np.nanmax(mean+pos_error)\n if not dimension_range:\n return (lower, upper)\n return util.dimension_range(lower, upper, dim.range, dim.soft_range)\n return super(ErrorBars, self).range(dim, data_range)\n\n\n\nclass Spread(ErrorBars):\n \"\"\"\n Spread is a Chart element representing a spread of values or\n confidence band in a 1D coordinate system. The key dimension(s)\n corresponds to the location along the x-axis and the value\n dimensions define the location along the y-axis as well as the\n symmetric or assymetric spread.\n \"\"\"\n\n group = param.String(default='Spread', constant=True)\n\n\n\nclass Bars(Selection1DExpr, Chart):\n \"\"\"\n Bars is a Chart element representing categorical observations\n using the height of rectangular bars. The key dimensions represent\n the categorical groupings of the data, but may also be used to\n stack the bars, while the first value dimension represents the\n height of each bar.\n \"\"\"\n\n group = param.String(default='Bars', constant=True)\n\n kdims = param.List(default=[Dimension('x')], bounds=(1,3))\n\n\n\nclass Histogram(Selection1DExpr, Chart):\n \"\"\"\n Histogram is a Chart element representing a number of bins in a 1D\n coordinate system. The key dimension represents the binned values,\n which may be declared as bin edges or bin centers, while the value\n dimensions usually defines a count, frequency or density associated\n with each bin.\n \"\"\"\n\n datatype = param.List(default=['grid'])\n\n group = param.String(default='Histogram', constant=True)\n\n kdims = param.List(default=[Dimension('x')], bounds=(1,1), doc=\"\"\"\n Dimensions on Element2Ds determine the number of indexable\n dimensions.\"\"\")\n\n vdims = param.List(default=[Dimension('Frequency')], bounds=(1, None))\n\n _binned = True\n\n def __init__(self, data, edges=None, **params):\n if data is None:\n data = []\n if edges is not None:\n self.param.warning(\n \"Histogram edges should be supplied as a tuple \"\n \"along with the values, passing the edges will \"\n \"be deprecated in holoviews 2.0.\")\n data = (edges, data)\n elif isinstance(data, tuple) and len(data) == 2 and len(data[0])+1 == len(data[1]):\n data = data[::-1]\n\n super(Histogram, self).__init__(data, **params)\n def __setstate__(self, state):\n \"\"\"\n Ensures old-style Histogram types without an interface can be unpickled.\n\n Note: Deprecate as part of 2.0\n \"\"\"\n if 'interface' not in state:\n self.interface = GridInterface\n x, y = state['_kdims_param_value'][0], state['_vdims_param_value'][0]\n state['data'] = {x.name: state['data'][1], y.name: state['data'][0]}\n super(Dataset, self).__setstate__(state)\n\n\n @property\n def values(self):\n \"Property to access the Histogram values provided for backward compatibility\"\n self.param.warning('Histogram.values is deprecated in favor of '\n 'common dimension_values method.')\n return self.dimension_values(1)\n\n\n @property\n def edges(self):\n \"Property to access the Histogram edges provided for backward compatibility\"\n return self.interface.coords(self, self.kdims[0], edges=True)\n\n\nclass Spikes(Selection1DExpr, Chart):\n \"\"\"\n Spikes is a Chart element which represents a number of discrete\n spikes, events or observations in a 1D coordinate system. The key\n dimension therefore represents the position of each spike along\n the x-axis while the first value dimension, if defined, controls\n the height along the y-axis. It may therefore be used to visualize\n the distribution of discrete events, representing a rug plot, or\n to draw the strength some signal.\n \"\"\"\n\n group = param.String(default='Spikes', constant=True)\n\n kdims = param.List(default=[Dimension('x')], bounds=(1, 1))\n\n vdims = param.List(default=[])\n\n _auto_indexable_1d = False\n\n\n\nclass Area(Curve):\n \"\"\"\n Area is a Chart element representing the area under a curve or\n between two curves in a 1D coordinate system. The key dimension\n represents the location of each coordinate along the x-axis, while\n the value dimension(s) represent the height of the area or the\n lower and upper bounds of the area between curves.\n\n Multiple areas may be stacked by overlaying them an passing them\n to the stack method.\n \"\"\"\n\n group = param.String(default='Area', constant=True)\n\n @classmethod\n def stack(cls, areas):\n \"\"\"\n Stacks an (Nd)Overlay of Area or Curve Elements by offsetting\n their baselines. To stack a HoloMap or DynamicMap use the map\n method.\n \"\"\"\n if not len(areas):\n return areas\n baseline = np.zeros(len(areas.values()[0]))\n stacked = areas.clone(shared_data=False)\n vdims = [areas.values()[0].vdims[0], 'Baseline']\n for k, area in areas.items():\n x, y = (area.dimension_values(i) for i in range(2))\n stacked[k] = area.clone((x, y+baseline, baseline), vdims=vdims,\n new_type=Area)\n baseline = baseline + y\n return stacked\n"
] |
[
[
"numpy.nanmax",
"numpy.nanmin"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
edgells/dev_coms
|
[
"a7e50c32bcb45c6b6781e6d0514fda6ddf8aef02"
] |
[
"python/xls/pandas_use.py"
] |
[
"import pandas as pd\n\n\nxls = pd.read_excel(\"C:\\\\Users\\\\pc11\\\\Desktop\\\\data.xlsx\")\n\nfor n in xls[1:100]:\n print(n)"
] |
[
[
"pandas.read_excel"
]
] |
[
{
"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": []
}
] |
broncio123/mpmodeling
|
[
"4910d6fc8822fd7358edeca1ed2e57383ec5bc35"
] |
[
"gridscan_insert.py"
] |
[
"#!/usr/bin/env python\nimport concurrent.futures\nimport sys,itertools, subprocess, isambard_dev, time, os\nimport numpy as np\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom gridscan_setup import Pdb,Crick_Parameters,BUDE_Energies,Interhelix_Interactions,HOLE_Output,SASA_Estimates,Base\nimport analyse_protein_properties\n\n# SQLAlchemy stuff\ndbfile = sys.argv[1] # Database filename\nncores = int(sys.argv[2]) # Number of cores to use\nprotein_set = sys.argv[3] # Type of protein structure \nif protein_set == 'whole':\n\tcrystal_structure_pdb = sys.argv[4] # PDB of crystal structure for alignment\nelse:\n\tcrystal_structure_pdb = \"None\"\n\nengine = create_engine('sqlite:///'+dbfile)\nBase.metadata.bind = engine\nDBSession = sessionmaker(bind=engine)\nsession = DBSession()\n\nnpeptides = 8\nsequence = 'VPTITGVHDLTETVRYIKT'\nnresidues = len(sequence)\n\n# Mean Crick parameters from cWza V358-T376 PDB (Crystal structure)\nmean_radius = 15.3063556447 # [Angstroms]\nmean_pitch = 155.121966666 # [Angstroms]\nmean_phica = -65.0829383279 # [deg]\n\n# Grid length per axis\nradius_length = 6 # [Angstroms]\npitch_length = 200 # [Angstroms]\nphica_length = 5 # [deg]\n\n# Grid resolution\nradius_step = 0.25 # [Angstroms]; Test value: 5\npitch_step = 5 # [Angstroms]; Test value: 100\nphica_step = 0.5 # [deg]; Test value: 4\n\n# Define grid axes in Crick space\nradius_axis = np.arange(mean_radius - radius_length, mean_radius + radius_length, radius_step)\npitch_axis = np.arange(10,210,5)\nphica_axis = np.arange(mean_phica - phica_length, mean_phica + phica_length, phica_step)\nparam_triple = list(itertools.product(radius_axis,pitch_axis,phica_axis))\n\n# Useful output messages\nprint(\"Test date: \"+str(time.strftime(\"%d/%m/%Y\"))+'; time:'+str(time.strftime(\"%H:%M:%S\")))\nprint(\"Volume in Crick parameter space:\")\nprint(\"Radius: [%f, %f] [Angstroms]\"%(radius_axis.min(), radius_axis.max()))\nprint(\"Pitch length: [%f, %f] [Angstroms]\"%(pitch_axis.min(), pitch_axis.max()))\nprint(\"Interface Angle (PhiCa): [%f, %f] [deg]\"%(phica_axis.min(), phica_axis.max()))\n\nprint(\"Grid resolution:\")\nprint(\"Radius, axis: %f [Angstroms]\"%radius_step)\nprint(\"Pitch length, axis: %f [Angstroms]\"%pitch_step)\nprint(\"Interface Angle (PhiCa), axis: %f [deg]\"%phica_step)\n\nprint(\"%d models will be sampled\"%len(param_triple))\n\nprint(\"Crystal structure for alignment: %s\"%crystal_structure_pdb)\nprint(\"Oligomer: %d helices\"%npeptides)\nprint(\"Output database: %s\"%dbfile)\n \n# Generate simplified id per model identity\nNrad = range(len(radius_axis))\nNpitch = range(len(pitch_axis))\nNphica = range(len(phica_axis))\nident_triple = list(itertools.product(Nrad,Npitch,Nphica))\n\ntmp_outfolder = 'mymodels_'+str(time.strftime(\"%d-%m-%Y\"))+'_'+str(time.strftime(\"%H:%M:%S\"))\nsubprocess.call(['mkdir',tmp_outfolder])\n\ndef process_model(n):\n\t# MODEL GENERATION\n\t## 1.1 Set identity tag of model in grid and save in database\n\tnrad,npitch,nphica = ident_triple[n]\n\tmodel_tag = str(nrad)+'-'+str(npitch)+'-'+str(nphica)\n\tmodel = Pdb(pdb_code = model_tag)\n\tsession.add(model)\n\t\t\n\t## 1.2 Set Crick parameters of model in grid\n\tmodel_radius,model_pitch,model_phica = param_triple[n]\n\tmodel_parameters = Crick_Parameters(npeptides=8,radius=model_radius,pitch_length=model_pitch,iangle_phica=model_phica,pdb=model)\n\tsession.add(model_parameters)\n\t\t\n\t## 1.4 Build model with helical packing parameters\n\tmodel_ampal = isambard_dev.ampal.specifications.CoiledCoil.from_parameters(npeptides,nresidues,model_radius,model_pitch,model_phica)\n\tmodel_ampal.build()\n\tmodel_ampal.pack_new_sequences((sequence)*npeptides)\n\t\t\n\t# 1.5 Save model coordinates in PDB\n\tmodel_pdb = tmp_outfolder+'/'+'model'+'_'+model_tag+'.pdb'\n\twith open(model_pdb, 'w') as x:\n\t\tx.write(model_ampal.pdb)\n\t\n\tif protein_set == 'whole':\n\t\twhole_model_pdb = tmp_outfolder+'/'+'whole_model'+'_'+model_tag+'.pdb'\n\t\tmodel_ampal = analyse_protein_properties.pymol_align_protein2model(crystal_structure_pdb,model_pdb,whole_model_pdb)\t\n\t\told_model_pdb = model_pdb\n\t\tmodel_pdb = whole_model_pdb\t\n\t\n\t# ANALYSE MODEL IN GRID\n\t## 2.1 All BUDE energetic components for helix-helix interactions [kcal/mol]\n\tcharge_buff,steric_buff,desolv_buff = analyse_protein_properties.buff_energies(model_ampal)\n\tmodel_energies = BUDE_Energies(buff_electrostatic_energy=charge_buff,buff_steric_energy=steric_buff,buff_desolvation_energy=desolv_buff,pdb=model)\n\tsession.add(model_energies)\n\t\t\n\t## 2.2 Number Salt bridges, Hydrogen bonds, and Knobs-Into-Holes interactions between helices\n\tmodel_nsbridges = analyse_protein_properties.salt_bridges(model_ampal)\n\tmodel_nhbonds = analyse_protein_properties.hydrogen_bonds(model_ampal)\n\tmodel_nkihs = analyse_protein_properties.knobs_into_holes(model_ampal)\n\tmodel_interhelix_interactions = Interhelix_Interactions(nsbridges=model_nsbridges,nhbonds=model_nhbonds,nkihs=model_nkihs,pdb=model)\n\tsession.add(model_interhelix_interactions) \n\t\n\t## 2.3 Solvent Accessible Surface Area (SASA) estimates per residue-type group [Angstrom^2]\n\tsasa_hydrophobes,sasa_nonhydrophobes,sasa_ncharged,sasa_pcharged = analyse_protein_properties.sasas(model_pdb)\n\tmodel_sasas = SASA_Estimates(sasa_hydrophobes=sasa_hydrophobes,sasa_nonhydrophobes=sasa_nonhydrophobes,sasa_ncharged=sasa_ncharged,sasa_pcharged=sasa_pcharged,pdb=model)\t\n\tsession.add(model_sasas)\n\t\n\t## 2.4 HOLE dimensions [Angstroms] and conductance estimates [nS]\n\tHOLE_dimensions,HOLE_conductance_estimates = analyse_protein_properties.hole(model_pdb) \n\tVDW_Rmin,pore_length = HOLE_dimensions\n\tGmacro,Gpred_Rmin,Gpred_Length,Gpred_AvgEPot = HOLE_conductance_estimates\n\tmodel_HOLE = HOLE_Output(HOLE_Rmin=VDW_Rmin,HOLE_Length=pore_length,Gmacro=Gmacro,Gpred_Rmin=Gpred_Rmin,Gpred_Length=Gpred_Length,Gpred_AvgEPot=Gpred_AvgEPot,pdb=model)\t\n\tsession.add(model_HOLE)\n\n\tsession.commit()\n\t# Remove output files, all relevant data saved in database\n\tsubprocess.call(['rm',old_model_pdb])\n\tsubprocess.call(['rm',model_pdb])\n\tsubprocess.call(['rm',model_pdb[:-4]+'.hole_inp'])\n\tsubprocess.call(['rm',model_pdb[:-4]+'.hole_dat'])\n\nmodel_n = list(range(len(ident_triple)))\ndef main():\n\twith concurrent.futures.ProcessPoolExecutor(max_workers=ncores) as executor:\n\t\texecutor.map(process_model, model_n)\n\nif __name__ == '__main__':\n main()\n\n"
] |
[
[
"numpy.arange"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
talonchandler/polaris2
|
[
"2ec215edf7f63967af109661d40bc55b10d836da"
] |
[
"polaris2/geomvis/R2toR.py"
] |
[
"import tifffile\nimport numpy as np\nfrom polaris2.geomvis import utilmpl\nimport logging\nlog = logging.getLogger('log')\n\nclass xy:\n def __init__(self, data, px_dims=[1,1], cmap='gray', title='',\n fov=[0,1], plotfov=[0,1], vmin=None, vmax=None):\n \n self.data = data\n self.px_dims = px_dims\n\n self.cmap = cmap\n self.xlabel = '{:.0f}'.format(plotfov[1] - plotfov[0]) + ' $\\mu$m'\n self.title = title\n\n self.fov = fov\n self.plotfov = plotfov\n\n self.vmin = vmin\n self.vmax = vmax\n\n def to_tiff(self, filename):\n utilmpl.mkdir(filename)\n with tifffile.TiffWriter(filename, imagej=True) as tif:\n tif.save(self.data.astype(np.float32),\n resolution=(1/self.px_dims[0], 1/self.px_dims[1]),\n metadata={'unit':'um'}) # TZCYXS\n\n def plot(self, f, fc, ss):\n ax = utilmpl.plot_template(f, fc, shape=self.data.shape, xlabel=self.xlabel,\n title=self.title)\n\n # Image\n if self.cmap is 'gray':\n vmax = np.max(self.data)\n vmin = 0\n elif self.cmap is 'bwr':\n vmax = np.max(np.abs(self.data))\n vmin = -vmax\n\n if self.vmax is not None:\n vmax = self.vmax\n vmin = self.vmin\n\n ax[0].set_xlim(self.plotfov)\n ax[0].set_ylim(self.plotfov)\n ax[0].imshow(self.data.T, vmin=vmin, vmax=vmax, cmap=self.cmap,\n extent=2*self.fov,\n aspect='auto', interpolation='nearest', origin='lower')\n\n # Colorbar\n x = np.linspace(vmin, vmax, 100)\n xx, yy = np.meshgrid(x, x)\n\n ax[1].imshow(yy, vmin=vmin, vmax=vmax, cmap=self.cmap,\n extent=[0,1,vmin,vmax], aspect='auto',\n interpolation='bicubic', origin='lower')\n\n if self.cmap is 'gray':\n ax[1].annotate('{:.2g}'.format(np.max(vmax)), xy=(0,0), xytext=(0, 1.05), textcoords='axes fraction', va='center', ha='left')\n ax[1].annotate('0', xy=(0,0), xytext=(1.8, 0), textcoords='axes fraction', va='center', ha='left')\n ax[1].yaxis.set_ticks([0, vmax])\n ax[1].set_yticklabels(['', ''])\n elif self.cmap is 'bwr':\n ax[1].annotate('{:.2g}'.format(vmax), xy=(0,0), xytext=(0, 1.05), textcoords='axes fraction', va='center', ha='left')\n ax[1].annotate('${:.2g}$'.format(vmin), xy=(0,0), xytext=(0, -0.05), textcoords='axes fraction', va='center', ha='left')\n ax[1].yaxis.set_ticks([vmin, 0, vmax])\n ax[1].set_yticklabels(['', '', ''])\n\n # Colors\n ax[0].annotate('', xy=(0,0), xytext=(0.1, 0), xycoords='axes fraction', textcoords='axes fraction', arrowprops=dict(arrowstyle=\"-\", lw=2, shrinkB=0, color='red'))\n ax[0].annotate('', xy=(0,0), xytext=(0, 0.1), xycoords='axes fraction', textcoords='axes fraction', arrowprops=dict(arrowstyle=\"-\", lw=2, shrinkB=0, color=[0,1,0]))\n"
] |
[
[
"numpy.max",
"numpy.meshgrid",
"numpy.abs",
"numpy.linspace"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
wang-yuhao/Practical-Big-Data-Science-ADL-AI
|
[
"0bf63bf210f506e287f8492e716bb3394137d74b",
"0bf63bf210f506e287f8492e716bb3394137d74b",
"0bf63bf210f506e287f8492e716bb3394137d74b"
] |
[
"scripts/use_evaluation_model_distmult.py",
"scripts/use_abstract_model_distmult.py",
"scripts/run_conve.py"
] |
[
"import argparse\nimport pickle\nimport torch\nimport os\nimport numpy as np\nfrom src.models.api import EvaluationModel, NegSampleGenerator\nfrom torch import nn\n\n\nclass Namespace:\n def __init__(self, **kwargs):\n self.__dict__.update(kwargs)\n\n\nclass DistMult:\n\n def get_score(self, head: torch.tensor, relation: torch.tensor,\n tail: torch.tensor, mode: str) -> torch.tensor:\n \"\"\"\n Computes Scores for head, relation, tail triples with DistMult model\n\n :param head: torch.tensor, dtype: int, shape: (batch_size, sample_size,\n entity_dim)\n :param relation: torch.tensor, dtype: int, shape: (batch_size,\n sample_size, relation_dim)\n :param tail: torch.tensor, dtype: int, shape: (batch_size, sample_size,\n entity_dim)\n :param mode: str ('single', 'head-batch' or 'head-tail')\n\n :return: torch.tensor, dtype: float, shape: (batch_size, num_entities)\n \"\"\"\n\n if mode == 'head-batch':\n score = head * (relation * tail)\n else:\n score = (head * relation) * tail\n\n score = score.sum(dim=2)\n return score\n\n\ndef parse_args(args=None):\n parser = argparse.ArgumentParser(\n description='Load trained model and use it for predictions'\n )\n parser.add_argument('-m', '--model', type=str, default=None)\n parser.add_argument('-d', '--data', type=str, default=None)\n parser.add_argument('-o', '--output_path', type=str, default=None)\n\n return parser.parse_args(args)\n\n\ndef load_data(data_path):\n path_train = os.path.join(data_path, 'train.pickle')\n with open(path_train, 'rb') as handle:\n train = pickle.load(handle)\n\n path_valid = os.path.join(data_path, 'valid.pickle')\n with open(path_valid, 'rb') as handle:\n valid = pickle.load(handle)\n\n path_test = os.path.join(data_path, 'test.pickle')\n with open(path_test, 'rb') as handle:\n test = pickle.load(handle)\n\n return train, valid, test\n\n\ndef main(args):\n \"\"\"\n Load trained model and use it for predictions.\n \"\"\"\n\n if args.model is None or args.data is None:\n raise ValueError('You have to specify model and data input paths.')\n\n # load data\n train_triples, valid_triples, test_triples = load_data(args.data)\n\n # create model and load already trained embeddings\n all_true_triples = np.concatenate([train_triples, valid_triples,\n test_triples], axis=0)\n neg_sample_generator = NegSampleGenerator(all_true_triples,\n create_filter_bias=True)\n model = EvaluationModel(model_class=DistMult(),\n neg_sample_generator=neg_sample_generator)\n\n path = os.path.join(args.model, 'entity_embedding.npy')\n new_entity_embedding = nn.Parameter(torch.from_numpy(np.load(path)))\n\n path = os.path.join(args.model, 'relation_embedding.npy')\n new_relation_embedding = nn.Parameter(torch.from_numpy(np.load(path)))\n\n # only True if embeddings of RotatE are used\n if new_entity_embedding.shape[1] != new_relation_embedding.shape[1]:\n stop = new_relation_embedding.shape[1]\n new_entity_embedding = new_entity_embedding[:, :stop]\n new_entity_embedding = nn.Parameter(new_entity_embedding)\n\n model.change_entity_embedding(new_entity_embedding.cuda())\n model.change_relation_embedding(new_relation_embedding.cuda())\n\n model.cuda()\n model.eval()\n\n # use API to evaluate model and generate model output for error analysis\n s = torch.tensor(test_triples[:, 0]).cuda()\n p = torch.tensor(test_triples[:, 1]).cuda()\n o = torch.tensor(test_triples[:, 2]).cuda()\n evaluation_result = model.evaluate(s, p, o, batch_size=4)\n\n if args.output_path is not None:\n model.generate_model_output(output_path=args.output_path,\n test_triples=test_triples,\n evaluation_result=evaluation_result)\n\n\nif __name__ == '__main__':\n main(parse_args())\n",
"# coding=utf-8\nimport torch\nfrom torch import nn\nimport numpy as np\n\nfrom src.models.api import AbstractModel, evaluate\n\n\nclass DistMult(AbstractModel):\n def __init__(\n self,\n num_entities: int,\n num_relations: int,\n embedding_dim: int,\n ):\n super(DistMult, self).__init__(\n num_entities=num_entities,\n num_relations=num_relations\n )\n self.entity_embedding = nn.Embedding(\n num_embeddings=num_entities,\n embedding_dim=embedding_dim\n )\n self.relation_embedding = nn.Embedding(\n num_embeddings=num_relations,\n embedding_dim=embedding_dim\n )\n\n def score_subjects(\n self,\n p: torch.tensor,\n o: torch.tensor,\n ) -> torch.tensor:\n p_emb = self.relation_embedding(p)\n o_emb = self.entity_embedding(o)\n all_emb = self.entity_embedding.weight.data\n return torch.sum(\n all_emb * p_emb[None, :] * o_emb[None, :],\n dim=-1\n )\n\n def score_objects(\n self,\n s: torch.tensor,\n p: torch.tensor,\n ) -> torch.tensor:\n s_emb = self.entity_embedding(s)\n p_emb = self.relation_embedding(p)\n all_emb = self.entity_embedding.weight.data\n return torch.sum(\n s_emb[None, :] * p_emb[None, :] * all_emb,\n dim=-1\n )\n\n def forward(self, *inputs):\n raise Exception(\"Not implemented\")\n\n\nif __name__ == '__main__':\n model = DistMult(num_entities=128, num_relations=16, embedding_dim=64)\n n_triples = 256\n device = torch.device('cpu')\n sbjs = np.random.randint(\n model.num_entities,\n size=(n_triples,),\n dtype=np.int32\n )\n pred = np.random.randint(\n model.num_relation,\n size=(n_triples,),\n dtype=np.int32\n )\n objs = np.random.randint(\n model.num_entities,\n size=(n_triples,),\n dtype=np.int32\n )\n fake_triples = np.stack([sbjs, pred, objs], axis=-1)\n\n results = evaluate(triples=fake_triples, model=model, device=device)\n print(results)\n",
"# %% [markdown]\n# # ConvE\n# This notebook is used to train and evaluate the ConvE model. Since\n# the adlai library hasn't been installed yet we need to add the path\n# to the source code, so we can import the ConvE model.\n\n# %% Define all dependencies\n\nimport sys\nimport os\nimport mlflow.pytorch\nimport mlflow\nimport logging\nimport click\nimport numpy as np\nimport torch\n\nsys.path.append(os.path.abspath('.'))\nsys.path.append(os.path.abspath('src/models/'))\n\nfrom src.models.conve import ConvE # noqa\nfrom src.data.utils import load # noqa\nfrom src.metrics import HitsAtK, MeanRank, MeanReciprocalRank # noqa\nfrom src.callbacks import Callback # noqa\n\nlogging.basicConfig(level=logging.DEBUG)\n\nlog_dir = f'/tmp/run-conve-logs/'\nos.path.isdir(log_dir)\nos.makedirs(log_dir, exist_ok=True)\n\nprint(f'{\"*\" * 5} Logging to {log_dir} {\"*\" * 5}')\n\nfmt=\"%(asctime)s %(levelname)-8s %(name)-15s %(message)s\" # noqa\n\nfileHandler = logging.FileHandler(os.path.join(log_dir, '{time.time()}-conve.log'))\n\nhandler = logging.StreamHandler()\nhandler.setLevel(logging.DEBUG)\n\nformatter = logging.Formatter(fmt)\nhandler.setFormatter(formatter)\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n\nlogger.addHandler(handler)\nlogger.addHandler(fileHandler)\n\n# General Parameters\nDEVICE_PARAM = 'cpu'\n\nTRAIN_REVERSED_PARAM = True\nLABEL_SMOOTHING_PARAM = 0.1\nWEIGHT_DECAY_PARAM = 0.0\n\nVALIDATION_INTERVAL_PARAM = 10\nMLFLOW_EXPERIMENT_NAME_PARAM = 'ConvE'\n\n# Default Hyperparameters\nEPOCHS_PARAM = 1000\nBATCH_SIZE_PARAM = 128\nLR_PARAM = 1e-3\n\n# Model Parameters\nCONVE_INPUT_CHANNELS = 1\nCONVE_OUTPUT_CHANNELS = 2\n\nCONVE_EMBEDDING_DIM = 200\nCONVE_EMBEDDING_WIDTH = 20\nCONVE_EMBEDDING_HEIGHT = 10\n\nCONVE_KERNEL_WIDTH = 3\nCONVE_KERNEL_HEIGHT = 3\n\nCONVE_EMBEDDING_DROPOUT = 0.2\nCONVE_FEATURE_MAP_DROPOUT = 0.2\nCONVE_PROJECTION_DROPOUT = 0.3\n\n# Help\nHELP_DEVICE = f'Either cuda or cpu. (default: {DEVICE_PARAM})'\n\nHELP_TRAIN_REVERSED = f'If True, creates reversed triples so left-prediction\\\n can be transformed into a right-prediction.\\\n (default: {TRAIN_REVERSED_PARAM})'\n\nHELP_EPOCHS = f'Sets the number of epochs to train.\\\n (default: {EPOCHS_PARAM})'\n\nHELP_BATCH_SIZE = f'Sets the batch size.\\\n (default: {BATCH_SIZE_PARAM})'\n\nHELP_LR = f'Sets the learning rate:\\\n (default: {LR_PARAM})'\n\nHELP_LABEL_SMOOTHING = f\"If set, applies label smoothing to the training labels.\\\n (default: {LABEL_SMOOTHING_PARAM})\"\n\nHELP_WEIGHT_DECAY = f\"Sets the weight decay parameter for the Adam optimzer.\\\n (default: {WEIGHT_DECAY_PARAM})\"\n\nHELP_VALIDATION_INTERVAL = f\"The interval at which the model is validated\\\n on the validation set.\\\n (default: {VALIDATION_INTERVAL_PARAM})\"\n\nHELP_MLFLOW_EXPERIMENT_NAME = f'If set, changes the name of the experiment\\\n under which model artifacts are saved.\\\n (default: {MLFLOW_EXPERIMENT_NAME_PARAM})'\n\ndef get_model(num_entities, num_relations, device):\n '''Initializes a ConvE model.\n Parameters\n ----------\n num_entities - int: The total number of distinct entities in the\n dataset.\n num_relations - int: The total number of distinct realtions in the\n dataset.\n '''\n model = ConvE(\n num_entities=num_entities,\n num_relations=num_relations,\n embedding_dim=CONVE_EMBEDDING_DIM,\n ConvE_input_channels=CONVE_INPUT_CHANNELS,\n ConvE_output_channels=CONVE_OUTPUT_CHANNELS,\n ConvE_width=CONVE_EMBEDDING_WIDTH,\n ConvE_height=CONVE_EMBEDDING_HEIGHT,\n ConvE_kernel_height=CONVE_KERNEL_HEIGHT,\n ConvE_kernel_width=CONVE_KERNEL_WIDTH,\n conv_e_input_dropout=CONVE_EMBEDDING_DROPOUT,\n conv_e_feature_map_dropout=CONVE_FEATURE_MAP_DROPOUT,\n conv_e_output_dropout=CONVE_PROJECTION_DROPOUT,\n preferred_device=device\n )\n return model\n\n\[email protected]()\[email protected]('--epochs',type=int, default=EPOCHS_PARAM, help=HELP_EPOCHS)\[email protected]('--batch_size',type=int, default=BATCH_SIZE_PARAM, help=HELP_BATCH_SIZE)\[email protected]('--lr', type=float, default=LR_PARAM, help=HELP_LR)\[email protected]('--device', default=DEVICE_PARAM, help=HELP_DEVICE)\[email protected]('--train_reversed', default=TRAIN_REVERSED_PARAM, type=bool, help=HELP_TRAIN_REVERSED) # noqa\[email protected]('--label_smoothing', default=LABEL_SMOOTHING_PARAM, type=float, help=HELP_LABEL_SMOOTHING) # noqa\[email protected]('--weight_decay', default=0, type=float, help=HELP_WEIGHT_DECAY)\[email protected]('--validation_interval', default=VALIDATION_INTERVAL_PARAM, help=HELP_VALIDATION_INTERVAL)\[email protected]('--mlflow_experiment_name', default=MLFLOW_EXPERIMENT_NAME_PARAM, help=HELP_MLFLOW_EXPERIMENT_NAME) # noqa\[email protected]('--embedding_dim', type=int, default=CONVE_EMBEDDING_DIM, help=f'(default: {CONVE_EMBEDDING_DIM})')\[email protected]('--embedding_height', type=int, default=CONVE_EMBEDDING_HEIGHT, help=f'(default: {CONVE_EMBEDDING_HEIGHT})')\[email protected]('--embedding_width', type=int, default=CONVE_EMBEDDING_WIDTH, help=f'(default: {CONVE_EMBEDDING_WIDTH})')\[email protected]('--input_channels', type=int, default=CONVE_INPUT_CHANNELS, help=f'(default: {CONVE_INPUT_CHANNELS})')\[email protected]('--output_channels', type=int, default=CONVE_OUTPUT_CHANNELS, help=f'(default: {CONVE_OUTPUT_CHANNELS})')\[email protected]('--kernel_height', type=int, default=CONVE_KERNEL_HEIGHT, help=f'(default: {CONVE_KERNEL_HEIGHT})')\[email protected]('--kernel_width', type=int, default=CONVE_KERNEL_WIDTH, help=f'(default: {CONVE_KERNEL_WIDTH})')\[email protected]('--embedding_dropout', type=float, default=CONVE_EMBEDDING_DROPOUT, help=f'(default: {CONVE_EMBEDDING_DROPOUT})')\[email protected]('--feature_map_dropout', type=float, default=CONVE_FEATURE_MAP_DROPOUT, help=f'(default: {CONVE_FEATURE_MAP_DROPOUT})')\[email protected]('--projection_dropout', type=float, default=CONVE_PROJECTION_DROPOUT, help=f'(default: {CONVE_PROJECTION_DROPOUT})')\n# %% Train the model\ndef main(epochs, batch_size, lr, device, train_reversed,\n label_smoothing, weight_decay, validation_interval, mlflow_experiment_name,\n embedding_dim,embedding_height, embedding_width, input_channels, output_channels,\n kernel_height, kernel_width, embedding_dropout, feature_map_dropout,\n projection_dropout\n ):\n \"\"\"\n This script trains a ConvE KGE model and validates the model every 10 epochs\n (--validation_interval).\n If the MRR score has improved since the last checkpoint a new checkpoint\n will be logged to the mlflow server.\n \"\"\"\n mappings, datasets = load()\n train = datasets['train']\n valid = datasets['valid']\n test = datasets['test']\n\n id2rel = mappings['id2rel']\n id2e = mappings['id2e']\n\n num_entities = len(id2e)\n num_relations = len(id2rel)\n\n mlflow.set_experiment(mlflow_experiment_name)\n mlflow.start_run()\n\n mlflow.log_param('Epochs', epochs)\n mlflow.log_param('Label Smoothing', label_smoothing)\n mlflow.log_param('train_reversed', train_reversed)\n mlflow.log_param('Batch Size', batch_size)\n mlflow.log_param('Learning Rate', lr)\n mlflow.log_param('Weight Decay', weight_decay)\n\n mlflow.log_param('num_entities', num_entities)\n mlflow.log_param('num_relations', num_relations)\n mlflow.log_param('embedding_dim', embedding_dim)\n mlflow.log_param('ConvE_input_channels', input_channels)\n mlflow.log_param('ConvE_output_channels', output_channels)\n mlflow.log_param('ConvE_width', embedding_width)\n mlflow.log_param('ConvE_height', embedding_height)\n mlflow.log_param('ConvE_kernel_height', kernel_height)\n mlflow.log_param('ConvE_kernel_width', kernel_width)\n mlflow.log_param('ConvE_input_dropout', embedding_dropout)\n mlflow.log_param('ConvE_feature_map_dropout', feature_map_dropout)\n mlflow.log_param('ConvE_output_dropout', projection_dropout)\n\n model = get_model(num_entities, num_relations, device)\n model.compile(metrics=[HitsAtK(1),\n HitsAtK(3),\n HitsAtK(10),\n MeanRank(),\n MeanReciprocalRank()],\n callbacks=[\n MlFlowLogger(mlflow),\n SaveModel('mean_reciprocal_rank', objective='max')\n ])\n\n try:\n losses, _ = model.fit(train,\n valid,\n learning_rate=lr,\n num_epochs=epochs,\n train_reversed=train_reversed,\n label_smoothing=label_smoothing,\n weight_decay=weight_decay,\n validation_interval=validation_interval,\n batch_size=batch_size)\n except KeyboardInterrupt:\n logger.warning('Forced Keyboard Interrupt. Exiting now...')\n mlflow.log_param('training_interrupted', True)\n sys.exit()\n\n epochs = len(losses)\n\n mlflow.log_param('Early Stop Epochs', epochs)\n\n for epoch in range(epochs):\n mlflow.log_metric('loss', losses[epoch], step=epoch)\n\n logger.info(\"*\"*30)\n logger.info(\"Evaluating on Test set\")\n logger.info(\"*\"*30)\n\n with torch.no_grad():\n results = model.evaluate(test, train)\n\n for epoch, item in enumerate(results.items()):\n mlflow.log_metric(item[0], item[1], step=epoch)\n\n mlflow.pytorch.log_model(model, 'models/conve-model-final')\n\n mlflow.end_run()\n\n model.eval()\n\n h = torch.tensor(test[0, 0:1], dtype=torch.long, device=device)\n p = torch.tensor(test[0, 1:2], dtype=torch.long, device=device)\n t = torch.tensor(test[0, 1:2], dtype=torch.long, device=device)\n\n obj_scores = model.score_objects(h, p).detach()\n subj_scores = model.score_subjects(p, t).detach()\n\n print('Object Scores')\n print(f'(min/max): ({obj_scores.min()}, {obj_scores.max()})')\n o_sort, o_args = torch.sort(obj_scores, descending=True)\n print('Sorted Top 10 Scores: ', o_sort[:10])\n print('Sorted Top 10 Ids: ', o_args[:10])\n print('True Id: ', t.item())\n\n print('Subject Scores')\n print(f'(min/max): ({subj_scores.min()}, {subj_scores.max()})')\n s_sort, s_args = torch.sort(subj_scores, descending=True)\n print('Sorted Top 10 Scores: ', s_sort[:10])\n print('Sorted Top 10 Ids: ', s_args[:10])\n print('True Id: ', h.item())\n\n\nclass MlFlowLogger(Callback):\n def __init__(self, mlflow_intance):\n super(MlFlowLogger, self).__init__('MlFlowLogger')\n self.mlflow_intance = mlflow_intance\n self.prev_epoch = None\n\n def on_epoch_end(self, epoch, params):\n metrics = params['val_metrics']\n\n if self.prev_epoch != epoch:\n self.prev_epoch = epoch\n for k, v in metrics.items():\n self.mlflow_intance.log_metric(k, v[-1], step=epoch)\n\n\nclass SaveModel(Callback):\n def __init__(self, monitor_value, objective=None):\n super(SaveModel, self).__init__('SaveModel')\n\n self.monitor_value = monitor_value\n self.current_best = None\n\n if objective == 'min':\n self.objective = np.less\n elif objective == 'max':\n self.objective = np.greater\n\n def on_epoch_end(self, epoch, params):\n if self.monitor_value not in params['val_metrics']:\n raise Exception(f'Metric: {self.monitor_value} not found. Please include the metric during model compilation') # noqa\n\n model = params['model']\n metric = params['val_metrics']\n most_recent_metric = metric[self.monitor_value][-1]\n\n file_name = f'conve-model-{epoch}'\n\n if not self.current_best \\\n or self.objective(most_recent_metric, self.current_best):\n\n logger.debug('New Best Model: [%d] %d --> %d', self.monitor_value, self.current_best, most_recent_metric) # noqa\n\n for k, v in params['val_metrics'].items():\n logger.debug('%s: %d', k, v[-1])\n\n self.current_best = most_recent_metric\n mlflow.pytorch.log_model(model, f'models/{file_name}')\n\n#pylint: disable=no-value-for-parameter\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"numpy.concatenate",
"numpy.load",
"torch.nn.Parameter",
"torch.tensor"
],
[
"torch.sum",
"torch.nn.Embedding",
"numpy.stack",
"torch.device",
"numpy.random.randint"
],
[
"torch.no_grad",
"torch.sort",
"torch.tensor"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
zhangzhongshuai/lanedet
|
[
"bff96fcbed122ac0f876d8e64ada7795ca34e4b6"
] |
[
"lanedet/engine/runner.py"
] |
[
"import time\nimport torch\nfrom tqdm import tqdm\nimport pytorch_warmup as warmup\nimport numpy as np\nimport random\nimport cv2\n\nfrom lanedet.models.registry import build_net\nfrom .registry import build_trainer, build_evaluator\nfrom .optimizer import build_optimizer\nfrom .scheduler import build_scheduler\nfrom lanedet.datasets import build_dataloader\nfrom lanedet.utils.recorder import build_recorder\nfrom lanedet.utils.net_utils import save_model, load_network\n\n\nclass Runner(object):\n def __init__(self, cfg):\n torch.manual_seed(cfg.seed)\n np.random.seed(cfg.seed)\n random.seed(cfg.seed)\n self.cfg = cfg\n self.recorder = build_recorder(self.cfg)\n self.net = build_net(self.cfg)\n # self.net.to(torch.device('cuda'))\n self.net = torch.nn.parallel.DataParallel(\n self.net, device_ids = range(self.cfg.gpus)).cuda()\n self.recorder.logger.info('Network: \\n' + str(self.net))\n self.resume()\n self.optimizer = build_optimizer(self.cfg, self.net)\n self.scheduler = build_scheduler(self.cfg, self.optimizer)\n self.warmup_scheduler = None\n # TODO(zhengtu): remove this hard code\n if self.cfg.optimizer.type == 'SGD':\n self.warmup_scheduler = warmup.LinearWarmup(\n self.optimizer, warmup_period=5000)\n self.metric = 0.\n self.val_loader = None\n\n def resume(self):\n if not self.cfg.load_from and not self.cfg.finetune_from:\n return\n load_network(self.net, self.cfg.load_from,\n finetune_from=self.cfg.finetune_from, logger=self.recorder.logger)\n\n def to_cuda(self, batch):\n for k in batch:\n if k == 'meta':\n continue\n batch[k] = batch[k].cuda()\n return batch\n \n def train_epoch(self, epoch, train_loader):\n self.net.train()\n end = time.time()\n max_iter = len(train_loader)\n for i, data in enumerate(train_loader):\n if self.recorder.step >= self.cfg.total_iter:\n break\n date_time = time.time() - end\n self.recorder.step += 1\n data = self.to_cuda(data)\n output = self.net(data)\n self.optimizer.zero_grad()\n loss = output['loss']\n loss.backward()\n self.optimizer.step()\n self.scheduler.step()\n if self.warmup_scheduler:\n self.warmup_scheduler.dampen()\n batch_time = time.time() - end\n end = time.time()\n self.recorder.update_loss_stats(output['loss_stats'])\n self.recorder.batch_time.update(batch_time)\n self.recorder.data_time.update(date_time)\n\n if i % self.cfg.log_interval == 0 or i == max_iter - 1:\n lr = self.optimizer.param_groups[0]['lr']\n self.recorder.lr = lr\n self.recorder.record('train')\n\n def train(self):\n self.recorder.logger.info('Build train loader...')\n train_loader = build_dataloader(self.cfg.dataset.train, self.cfg, is_train=True)\n\n self.recorder.logger.info('Start training...')\n for epoch in range(self.cfg.epochs):\n self.recorder.epoch = epoch\n self.train_epoch(epoch, train_loader)\n if (epoch + 1) % self.cfg.save_ep == 0 or epoch == self.cfg.epochs - 1:\n self.save_ckpt()\n if (epoch + 1) % self.cfg.eval_ep == 0 or epoch == self.cfg.epochs - 1:\n self.validate()\n if self.recorder.step >= self.cfg.total_iter:\n break\n\n def validate(self):\n if not self.val_loader:\n self.val_loader = build_dataloader(self.cfg.dataset.val, self.cfg, is_train=False)\n self.net.eval()\n predictions = []\n for i, data in enumerate(tqdm(self.val_loader, desc=f'Validate')):\n data = self.to_cuda(data)\n with torch.no_grad():\n output = self.net(data)\n predictions.extend(output)\n if self.cfg.view:\n self.val_loader.dataset.view(predictions, data['meta'])\n\n out = self.val_loader.dataset.evaluate(predictions, self.cfg.work_dir)\n self.recorder.logger.info(out)\n metric = out\n if metric > self.metric:\n self.metric = metric\n self.save_ckpt(is_best=True)\n self.recorder.logger.info('Best metric: ' + str(self.metric))\n\n def save_ckpt(self, is_best=False):\n save_model(self.net, self.optimizer, self.scheduler,\n self.recorder, is_best)\n"
] |
[
[
"torch.manual_seed",
"torch.no_grad",
"numpy.random.seed"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
primitybio/cellengine-python-toolk
|
[
"1f9dd168f1f27e2beba69f02e340371190857b33"
] |
[
"tests/unit/resources/scales/test_log_scale.py"
] |
[
"import pytest\nfrom math import isclose\nfrom numpy import log10\nfrom pandas import Series\n\nfrom cellengine.utils.scale_utils import apply_scale\n\n\[email protected](scope=\"module\")\ndef scale():\n return {\"minimum\": 5, \"maximum\": 10, \"type\": \"LogScale\"}\n\n\ndef test_should_apply_scale(scale):\n # fmt: off\n input = Series([\n -20, 0, 1e-40, 0.01, 0.2, 0.5, 0.9999, 1, 1.00001,\n 2, 5, 10, 100, 250, 500, 1000, 5000, 10000, 50000,\n 5e5, 5e6, 5e7, 5e8, 5e9, 5e10, 5e11, 5e12, 5e13, 5e14,\n 5e15, 5e16, 5e17\n ])\n # fmt: on\n output = Series([], dtype=\"float64\")\n output = input.map(lambda a: apply_scale(scale, a, False))\n # fmt: off\n expected = Series([\n 0, 0, 0, 0, 0, 0, 0, 0, 0.00000434292310445319, 0.30102999566398114,\n 0.6989700043360186, 1, 2, 2.397940008672037, 2.6989700043360183, 3,\n 3.6989700043360187, 4, 4.698970004336018, 5.698970004336018,\n 6.698970004336018, 7.698970004336018, 8.698970004336018,\n 9.698970004336018, 10.698970004336018, 11.698970004336018,\n 12.698970004336018, 13.698970004336018, 14.698970004336018,\n 15.698970004336018, 16.698970004336018, 17.698970004336018,\n ])\n # fmt: on\n assert [isclose(a, b, rel_tol=0.00001) for a, b in zip(output, expected)]\n\n\ndef test_should_apply_clamped(scale):\n # fmt: off\n input = Series([\n -20, 0, 0.01, 0.2, 0.5, 1, 2, 5, 10,\n 100, 250, 500, 1000, 5000, 10000, 50000\n ])\n # fmt: on\n output = Series([], dtype=\"float64\")\n MINV = 0.6989700043360186\n MAXV = 1\n output = input.map(lambda a: apply_scale(scale, a, True))\n # fmt: off\n expected = Series([\n MINV, MINV, MINV, MINV, MINV, MINV, MINV,\n 0.6989700043360186, 1, MAXV, MAXV, MAXV,\n MAXV, MAXV, MAXV, MAXV,\n ])\n # fmt: on\n assert [isclose(a, b, rel_tol=0.00001) for a, b in zip(output, expected)]\n\n\ndef test_should_handle_0_length_arrays(scale):\n input = Series([], dtype=\"float64\")\n output = Series([], dtype=\"float64\")\n output = Series([], dtype=\"float64\")\n output = input.map(lambda a: apply_scale(scale, a, True))\n assert type(output) is Series\n assert output.size == 0\n\n\ndef test_correctly_applies_scale_of_length_n(scale):\n for n in range(1, 32):\n input = Series([1] * n)\n output = Series([], dtype=\"float64\")\n output = input.map(lambda a: apply_scale(scale, a, True))\n for i in range(0, n):\n assert isclose(output[i], log10(scale[\"minimum\"]), rel_tol=0.00001)\n"
] |
[
[
"numpy.log10",
"pandas.Series"
]
] |
[
{
"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": []
}
] |
FelixKleineBoesing/FeatureSelector
|
[
"b33454be39d53881b1c1b5b7b6dca8d782cabd36"
] |
[
"tests/Tester.py"
] |
[
"import pandas as pd\nimport numpy as np\nimport logging\nimport time\n\nfrom pyFeatSel.Models.Model import XGBoostModel\nfrom pyFeatSel.FeatureSelectors.CompleteFeatureSpace import CompleteFeatureSpace\nfrom pyFeatSel.FeatureSelectors.GreedySearch import GreedySearch\nfrom pyFeatSel.Evaluator.Evaluator import Accuracy\nfrom pyFeatSel.misc.Helpers import threshold_base\n\n\nclass Tester:\n\n def run_complete_feature_space(self):\n start = time.time()\n logging.getLogger().setLevel(logging.INFO)\n train_data, train_label = self.read_files()\n\n xgb_model = XGBoostModel(n_rounds=100, xgb_params={\"eta\": 0.3})\n comp_feat_selector = CompleteFeatureSpace(model=xgb_model, train_data=train_data,\n train_label=train_label, k_folds=5,\n evaluator=Accuracy(), maximize_measure=True,\n objective=\"classification\", threshold_func=threshold_base)\n comp_feat_selector.run_selecting()\n logging.info(\"Used time in seconds: {0}, got test (val) measure: {1} ({2})\".\n format(str(int(time.time()-start)),comp_feat_selector.best_result[\"measure\"][\"test\"],\n comp_feat_selector.best_result[\"measure\"][\"val\"]))\n\n def run_greedy_search(self):\n start = time.time()\n logging.getLogger().setLevel(logging.INFO)\n train_data, train_label = self.read_files()\n\n xgb_model = XGBoostModel(n_rounds=100, xgb_params={\"eta\": 0.3})\n comp_feat_selector = GreedySearch(model=xgb_model, train_data=train_data,\n train_label=train_label, k_folds=10,\n evaluator=Accuracy(), maximize_measure=True,\n objective=\"classification\", threshold_func=threshold_base)\n comp_feat_selector.run_selecting()\n logging.info(\n \"Used time in seconds: {0}, got test (val) measure: {1} ({2})\".format(str(int(time.time() - start)),\n comp_feat_selector.best_result[\n \"measure\"][\"test\"],\n comp_feat_selector.best_result[\n \"measure\"][\"val\"]))\n\n def run_greedy_search2(self):\n start = time.time()\n logging.getLogger().setLevel(logging.INFO)\n train_data, train_label = self.read_files()\n\n comp_feat_selector = GreedySearch(train_data=train_data, train_label=train_label, k_folds=10,\n objective=\"classification\")\n comp_feat_selector.run_selecting()\n logging.info(\n \"Used time in seconds: {0}, got test (val) measure: {1} ({2})\".format(str(int(time.time() - start)),\n comp_feat_selector.best_result[\n \"measure\"][\"test\"],\n comp_feat_selector.best_result[\n \"measure\"][\"val\"]))\n\n\n def read_files(self):\n train_data = pd.concat([pd.read_csv(\"../data/train_data.csv\"), pd.read_csv(\"../data/validation_data.csv\")])\n with open(\"../data/train_label.csv\") as f:\n train_label = f.readlines()[1:]\n with open(\"../data/validation_label.csv\") as f:\n train_label += f.readlines()[1:]\n\n train_label = np.char.replace(np.array(train_label), \"\\n\", \"\").astype(int)\n return train_data, train_label\n\n\nif __name__==\"__main__\":\n tester = Tester()\n tester.run_complete_feature_space()\n tester.run_greedy_search()\n tester.run_greedy_search2()"
] |
[
[
"numpy.array",
"pandas.read_csv"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
taghizad3h/Top2Vec
|
[
"0237989ecd6a28df184b6a2b245239c501676da2"
] |
[
"top2vec/Top2Vec.py"
] |
[
"# Author: Dimo Angelov\n#\n# License: BSD 3 clause\nimport logging\nimport numpy as np\nimport pandas as pd\nfrom gensim.models.doc2vec import Doc2Vec, TaggedDocument\nfrom gensim.utils import simple_preprocess\nfrom gensim.parsing.preprocessing import strip_tags\nimport umap\nimport hdbscan\nfrom wordcloud import WordCloud\nimport matplotlib.pyplot as plt\nfrom joblib import dump, load\nfrom sklearn.cluster import dbscan\nimport tempfile\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.preprocessing import normalize\nfrom scipy.special import softmax\n\ntry:\n import hnswlib\n\n _HAVE_HNSWLIB = True\nexcept ImportError:\n _HAVE_HNSWLIB = False\n\ntry:\n import tensorflow as tf\n import tensorflow_hub as hub\n import tensorflow_text\n\n _HAVE_TENSORFLOW = True\nexcept ImportError:\n _HAVE_TENSORFLOW = False\n\ntry:\n from sentence_transformers import SentenceTransformer\n\n _HAVE_TORCH = True\nexcept ImportError:\n _HAVE_TORCH = False\n\nlogger = logging.getLogger('top2vec')\nlogger.setLevel(logging.WARNING)\nsh = logging.StreamHandler()\nsh.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))\nlogger.addHandler(sh)\n\n\ndef default_tokenizer(doc):\n \"\"\"Tokenize documents for training and remove too long/short words\"\"\"\n return simple_preprocess(strip_tags(doc), deacc=True)\n\n\nclass Top2Vec:\n \"\"\"\n Top2Vec\n\n Creates jointly embedded topic, document and word vectors.\n\n\n Parameters\n ----------\n embedding_model: string\n This will determine which model is used to generate the document and\n word embeddings. The valid string options are:\n\n * doc2vec\n * universal-sentence-encoder\n * universal-sentence-encoder-multilingual\n * distiluse-base-multilingual-cased\n\n For large data sets and data sets with very unique vocabulary doc2vec\n could produce better results. This will train a doc2vec model from\n scratch. This method is language agnostic. However multiple languages\n will not be aligned.\n\n Using the universal sentence encoder options will be much faster since\n those are pre-trained and efficient models. The universal sentence\n encoder options are suggested for smaller data sets. They are also\n good options for large data sets that are in English or in languages\n covered by the multilingual model. It is also suggested for data sets\n that are multilingual.\n\n For more information on universal-sentence-encoder visit:\n https://tfhub.dev/google/universal-sentence-encoder/4\n\n For more information on universal-sentence-encoder-multilingual visit:\n https://tfhub.dev/google/universal-sentence-encoder-multilingual/3\n\n The distiluse-base-multilingual-cased pre-trained sentence transformer\n is suggested for multilingual datasets and languages that are not\n covered by the multilingual universal sentence encoder. The\n transformer is significantly slower than the universal sentence\n encoder options.\n\n For more informati ond istiluse-base-multilingual-cased visit:\n https://www.sbert.net/docs/pretrained_models.html\n\n embedding_model_path: string (Optional)\n Pre-trained embedding models will be downloaded automatically by\n default. However they can also be uploaded from a file that is in the\n location of embedding_model_path.\n\n Warning: the model at embedding_model_path must match the\n embedding_model parameter type.\n\n documents: List of str\n Input corpus, should be a list of strings.\n\n min_count: int (Optional, default 50)\n Ignores all words with total frequency lower than this. For smaller\n corpora a smaller min_count will be necessary.\n\n speed: string (Optional, default 'learn')\n\n This parameter is only used when using doc2vec as embedding_model.\n\n It will determine how fast the model takes to train. The\n fast-learn option is the fastest and will generate the lowest quality\n vectors. The learn option will learn better quality vectors but take\n a longer time to train. The deep-learn option will learn the best\n quality vectors but will take significant time to train. The valid\n string speed options are:\n \n * fast-learn\n * learn\n * deep-learn\n\n use_corpus_file: bool (Optional, default False)\n\n This parameter is only used when using doc2vec as embedding_model.\n\n Setting use_corpus_file to True can sometimes provide speedup for\n large datasets when multiple worker threads are available. Documents\n are still passed to the model as a list of str, the model will create\n a temporary corpus file for training.\n\n document_ids: List of str, int (Optional)\n A unique value per document that will be used for referring to\n documents in search results. If ids are not given to the model, the\n index of each document in the original corpus will become the id.\n\n keep_documents: bool (Optional, default True)\n If set to False documents will only be used for training and not saved\n as part of the model. This will reduce model size. When using search\n functions only document ids will be returned, not the actual\n documents.\n\n workers: int (Optional)\n The amount of worker threads to be used in training the model. Larger\n amount will lead to faster training.\n \n tokenizer: callable (Optional, default None)\n Override the default tokenization method. If None then\n gensim.utils.simple_preprocess will be used.\n\n use_embedding_model_tokenizer: bool (Optional, default False)\n If using an embedding model other than doc2vec, use the model's\n tokenizer for document embedding. If set to True the tokenizer, either\n default or passed callable will be used to tokenize the text to\n extract the vocabulary for word embedding.\n\n umap_args: dict (Optional, default None)\n Pass custom arguments to UMAP.\n\n hdbscan_args: dict (Optional, default None)\n Pass custom arguments to HDBSCAN.\n \n verbose: bool (Optional, default True)\n Whether to print status data during training.\n \"\"\"\n\n def __init__(self,\n documents,\n min_count=50,\n embedding_model='doc2vec',\n embedding_model_path=None,\n speed='learn',\n use_corpus_file=False,\n document_ids=None,\n keep_documents=True,\n workers=None,\n tokenizer=None,\n use_embedding_model_tokenizer=False,\n umap_args=None,\n hdbscan_args=None,\n verbose=True\n ):\n\n if verbose:\n logger.setLevel(logging.DEBUG)\n self.verbose = True\n else:\n logger.setLevel(logging.WARNING)\n self.verbose = False\n\n if tokenizer is None:\n tokenizer = default_tokenizer\n\n # validate documents\n if not (isinstance(documents, list) or isinstance(documents, np.ndarray)):\n raise ValueError(\"Documents need to be a list of strings\")\n if not all((isinstance(doc, str) or isinstance(doc, np.str_)) for doc in documents):\n raise ValueError(\"Documents need to be a list of strings\")\n if keep_documents:\n self.documents = np.array(documents, dtype=\"object\")\n else:\n self.documents = None\n\n # validate document ids\n if document_ids is not None:\n if not (isinstance(document_ids, list) or isinstance(document_ids, np.ndarray)):\n raise ValueError(\"Documents ids need to be a list of str or int\")\n\n if len(documents) != len(document_ids):\n raise ValueError(\"Document ids need to match number of documents\")\n elif len(document_ids) != len(set(document_ids)):\n raise ValueError(\"Document ids need to be unique\")\n\n if all((isinstance(doc_id, str) or isinstance(doc_id, np.str_)) for doc_id in document_ids):\n self.doc_id_type = np.str_\n elif all((isinstance(doc_id, int) or isinstance(doc_id, np.int_)) for doc_id in document_ids):\n self.doc_id_type = np.int_\n else:\n raise ValueError(\"Document ids need to be str or int\")\n\n self.document_ids_provided = True\n self.document_ids = np.array(document_ids)\n self.doc_id2index = dict(zip(document_ids, list(range(0, len(document_ids)))))\n else:\n self.document_ids_provided = False\n self.document_ids = np.array(range(0, len(documents)))\n self.doc_id2index = dict(zip(self.document_ids, list(range(0, len(self.document_ids)))))\n self.doc_id_type = np.int_\n\n acceptable_embedding_models = [\"universal-sentence-encoder-multilingual\",\n \"universal-sentence-encoder\",\n \"distiluse-base-multilingual-cased\"]\n\n self.embedding_model_path = embedding_model_path\n\n if embedding_model == 'doc2vec':\n\n # validate training inputs\n if speed == \"fast-learn\":\n hs = 0\n negative = 5\n epochs = 40\n elif speed == \"learn\":\n hs = 1\n negative = 0\n epochs = 40\n elif speed == \"deep-learn\":\n hs = 1\n negative = 0\n epochs = 400\n elif speed == \"test-learn\":\n hs = 0\n negative = 5\n epochs = 1\n else:\n raise ValueError(\"speed parameter needs to be one of: fast-learn, learn or deep-learn\")\n\n if workers is None:\n pass\n elif isinstance(workers, int):\n pass\n else:\n raise ValueError(\"workers needs to be an int\")\n\n doc2vec_args = {\"vector_size\": 300,\n \"min_count\": min_count,\n \"window\": 15,\n \"sample\": 1e-5,\n \"negative\": negative,\n \"hs\": hs,\n \"epochs\": epochs,\n \"dm\": 0,\n \"dbow_words\": 1}\n\n if workers is not None:\n doc2vec_args[\"workers\"] = workers\n\n logger.info('Pre-processing documents for training')\n\n if use_corpus_file:\n processed = [' '.join(tokenizer(doc)) for doc in documents]\n lines = \"\\n\".join(processed)\n temp = tempfile.NamedTemporaryFile(mode='w+t')\n temp.write(lines)\n doc2vec_args[\"corpus_file\"] = temp.name\n\n\n else:\n train_corpus = [TaggedDocument(tokenizer(doc), [i]) for i, doc in enumerate(documents)]\n doc2vec_args[\"documents\"] = train_corpus\n\n logger.info('Creating joint document/word embedding')\n self.embedding_model = 'doc2vec'\n self.model = Doc2Vec(**doc2vec_args)\n\n if use_corpus_file:\n temp.close()\n\n elif embedding_model in acceptable_embedding_models:\n\n self.embed = None\n self.embedding_model = embedding_model\n\n self._check_import_status()\n\n logger.info('Pre-processing documents for training')\n\n # preprocess documents\n tokenized_corpus = [tokenizer(doc) for doc in documents]\n\n def return_doc(doc):\n return doc\n\n # preprocess vocabulary\n vectorizer = CountVectorizer(tokenizer=return_doc, preprocessor=return_doc)\n doc_word_counts = vectorizer.fit_transform(tokenized_corpus)\n words = vectorizer.get_feature_names()\n word_counts = np.array(np.sum(doc_word_counts, axis=0).tolist()[0])\n vocab_inds = np.where(word_counts > min_count)[0]\n\n if len(vocab_inds) == 0:\n raise ValueError(f\"A min_count of {min_count} results in \"\n f\"all words being ignored, choose a lower value.\")\n self.vocab = [words[ind] for ind in vocab_inds]\n\n self._check_model_status()\n\n logger.info('Creating joint document/word embedding')\n\n # embed words\n self.word_indexes = dict(zip(self.vocab, range(len(self.vocab))))\n self.word_vectors = self._l2_normalize(np.array(self.embed(self.vocab)))\n\n # embed documents\n if use_embedding_model_tokenizer:\n self.document_vectors = self._embed_documents(documents)\n else:\n train_corpus = [' '.join(tokens) for tokens in tokenized_corpus]\n self.document_vectors = self._embed_documents(train_corpus)\n\n else:\n raise ValueError(f\"{embedding_model} is an invalid embedding model.\")\n\n # create 5D embeddings of documents\n logger.info('Creating lower dimension embedding of documents')\n\n if umap_args is None:\n umap_args = {'n_neighbors': 15,\n 'n_components': 5,\n 'metric': 'cosine'}\n\n umap_model = umap.UMAP(**umap_args).fit(self._get_document_vectors(norm=False))\n\n # find dense areas of document vectors\n logger.info('Finding dense areas of documents')\n\n if hdbscan_args is None:\n hdbscan_args = {'min_cluster_size': 15,\n 'metric': 'euclidean',\n 'cluster_selection_method': 'eom'}\n\n cluster = hdbscan.HDBSCAN(**hdbscan_args).fit(umap_model.embedding_)\n\n # calculate topic vectors from dense areas of documents\n logger.info('Finding topics')\n\n # create topic vectors\n self._create_topic_vectors(cluster.labels_)\n\n # deduplicate topics\n self._deduplicate_topics()\n\n # find topic words and scores\n self.topic_words, self.topic_word_scores = self._find_topic_words_and_scores(topic_vectors=self.topic_vectors)\n\n # assign documents to topic\n self.doc_top, self.doc_dist = self._calculate_documents_topic(self.topic_vectors,\n self._get_document_vectors())\n\n # calculate topic sizes\n self.topic_sizes = self._calculate_topic_sizes(hierarchy=False)\n\n # re-order topics\n self._reorder_topics(hierarchy=False)\n\n # initialize variables for hierarchical topic reduction\n self.topic_vectors_reduced = None\n self.doc_top_reduced = None\n self.doc_dist_reduced = None\n self.topic_sizes_reduced = None\n self.topic_words_reduced = None\n self.topic_word_scores_reduced = None\n self.hierarchy = None\n\n # initialize document indexing variables\n self.document_index = None\n self.serialized_document_index = None\n self.documents_indexed = False\n self.index_id2doc_id = None\n self.doc_id2index_id = None\n\n # initialize word indexing variables\n self.word_index = None\n self.serialized_word_index = None\n self.words_indexed = False\n\n def save(self, file):\n \"\"\"\n Saves the current model to the specified file.\n\n Parameters\n ----------\n file: str\n File where model will be saved.\n \"\"\"\n\n document_index_temp = None\n word_index_temp = None\n\n # do not save sentence encoders and sentence transformers\n if self.embedding_model != \"doc2vec\":\n self.embed = None\n\n # serialize document index so that it can be saved\n if self.documents_indexed:\n temp = tempfile.NamedTemporaryFile(mode='w+b')\n self.document_index.save_index(temp.name)\n self.serialized_document_index = temp.read()\n temp.close()\n document_index_temp = self.document_index\n self.document_index = None\n\n # serialize word index so that it can be saved\n if self.words_indexed:\n temp = tempfile.NamedTemporaryFile(mode='w+b')\n self.word_index.save_index(temp.name)\n self.serialized_word_index = temp.read()\n temp.close()\n word_index_temp = self.word_index\n self.word_index = None\n\n dump(self, file)\n\n self.document_index = document_index_temp\n self.word_index = word_index_temp\n\n @classmethod\n def load(cls, file):\n \"\"\"\n\n Load a pre-trained model from the specified file.\n\n Parameters\n ----------\n file: str\n File where model will be loaded from.\n \"\"\"\n\n top2vec_model = load(file)\n\n # load document index\n if top2vec_model.documents_indexed:\n if not _HAVE_HNSWLIB:\n raise ImportError(f\"Cannot load document index.\\n\\n\"\n \"Try: pip install top2vec[indexing]\\n\\n\"\n \"Alternatively try: pip install hnswlib\")\n\n temp = tempfile.NamedTemporaryFile(mode='w+b')\n temp.write(top2vec_model.serialized_document_index)\n\n if top2vec_model.embedding_model == 'doc2vec':\n document_vectors = top2vec_model.model.docvecs.vectors_docs\n else:\n document_vectors = top2vec_model.document_vectors\n\n top2vec_model.document_index = hnswlib.Index(space='ip',\n dim=document_vectors.shape[1])\n top2vec_model.document_index.load_index(temp.name, max_elements=document_vectors.shape[0])\n temp.close()\n top2vec_model.serialized_document_index = None\n\n # load word index\n if top2vec_model.words_indexed:\n\n if not _HAVE_HNSWLIB:\n raise ImportError(f\"Cannot load word index.\\n\\n\"\n \"Try: pip install top2vec[indexing]\\n\\n\"\n \"Alternatively try: pip install hnswlib\")\n\n temp = tempfile.NamedTemporaryFile(mode='w+b')\n temp.write(top2vec_model.serialized_word_index)\n\n if top2vec_model.embedding_model == 'doc2vec':\n word_vectors = top2vec_model.model.wv.vectors\n else:\n word_vectors = top2vec_model.word_vectors\n\n top2vec_model.word_index = hnswlib.Index(space='ip',\n dim=word_vectors.shape[1])\n top2vec_model.word_index.load_index(temp.name, max_elements=word_vectors.shape[0])\n temp.close()\n top2vec_model.serialized_word_index = None\n\n return top2vec_model\n\n @staticmethod\n def _l2_normalize(vectors):\n\n if vectors.ndim == 2:\n return normalize(vectors)\n else:\n return normalize(vectors.reshape(1, -1))[0]\n\n def _embed_documents(self, train_corpus):\n\n self._check_import_status()\n self._check_model_status()\n\n # embed documents\n batch_size = 500\n document_vectors = []\n\n current = 0\n batches = int(len(train_corpus) / batch_size)\n extra = len(train_corpus) % batch_size\n\n for ind in range(0, batches):\n document_vectors.append(self.embed(train_corpus[current:current + batch_size]))\n current += batch_size\n\n if extra > 0:\n document_vectors.append(self.embed(train_corpus[current:current + extra]))\n\n document_vectors = self._l2_normalize(np.array(np.vstack(document_vectors)))\n\n return document_vectors\n\n def _embed_query(self, query):\n self._check_import_status()\n self._check_model_status()\n\n return self._l2_normalize(np.array(self.embed([query])[0]))\n\n def _set_document_vectors(self, document_vectors):\n if self.embedding_model == 'doc2vec':\n self.model.docvecs.vectors_docs = document_vectors\n else:\n self.document_vectors = document_vectors\n\n def _get_document_vectors(self, norm=True):\n\n if self.embedding_model == 'doc2vec':\n\n if norm:\n self.model.docvecs.init_sims()\n return self.model.docvecs.vectors_docs_norm\n else:\n return self.model.docvecs.vectors_docs\n else:\n return self.document_vectors\n\n def _index2word(self, index):\n if self.embedding_model == 'doc2vec':\n return self.model.wv.index2word[index]\n else:\n return self.vocab[index]\n\n def _get_word_vectors(self):\n if self.embedding_model == 'doc2vec':\n self.model.wv.init_sims()\n return self.model.wv.vectors_norm\n else:\n return self.word_vectors\n\n def _create_topic_vectors(self, cluster_labels):\n\n unique_labels = set(cluster_labels)\n if -1 in unique_labels:\n unique_labels.remove(-1)\n self.topic_vectors = self._l2_normalize(\n np.vstack([self._get_document_vectors(norm=False)[np.where(cluster_labels == label)[0]]\n .mean(axis=0) for label in unique_labels]))\n\n def _deduplicate_topics(self):\n core_samples, labels = dbscan(X=self.topic_vectors,\n eps=0.1,\n min_samples=2,\n metric=\"cosine\")\n\n duplicate_clusters = set(labels)\n\n if len(duplicate_clusters) > 1 or -1 not in duplicate_clusters:\n\n # unique topics\n unique_topics = self.topic_vectors[np.where(labels == -1)[0]]\n\n if -1 in duplicate_clusters:\n duplicate_clusters.remove(-1)\n\n # merge duplicate topics\n for unique_label in duplicate_clusters:\n unique_topics = np.vstack(\n [unique_topics, self._l2_normalize(self.topic_vectors[np.where(labels == unique_label)[0]]\n .mean(axis=0))])\n\n self.topic_vectors = unique_topics\n\n def _calculate_topic_sizes(self, hierarchy=False):\n if hierarchy:\n topic_sizes = pd.Series(self.doc_top_reduced).value_counts()\n else:\n topic_sizes = pd.Series(self.doc_top).value_counts()\n\n return topic_sizes\n\n def _reorder_topics(self, hierarchy=False):\n\n if hierarchy:\n self.topic_vectors_reduced = self.topic_vectors_reduced[self.topic_sizes_reduced.index]\n self.topic_words_reduced = self.topic_words_reduced[self.topic_sizes_reduced.index]\n self.topic_word_scores_reduced = self.topic_word_scores_reduced[self.topic_sizes_reduced.index]\n old2new = dict(zip(self.topic_sizes_reduced.index, range(self.topic_sizes_reduced.index.shape[0])))\n self.doc_top_reduced = np.array([old2new[i] for i in self.doc_top_reduced])\n self.hierarchy = [self.hierarchy[i] for i in self.topic_sizes_reduced.index]\n self.topic_sizes_reduced.reset_index(drop=True, inplace=True)\n else:\n self.topic_vectors = self.topic_vectors[self.topic_sizes.index]\n self.topic_words = self.topic_words[self.topic_sizes.index]\n self.topic_word_scores = self.topic_word_scores[self.topic_sizes.index]\n old2new = dict(zip(self.topic_sizes.index, range(self.topic_sizes.index.shape[0])))\n self.doc_top = np.array([old2new[i] for i in self.doc_top])\n self.topic_sizes.reset_index(drop=True, inplace=True)\n\n @staticmethod\n def _calculate_documents_topic(topic_vectors, document_vectors, dist=True, num_topics=None):\n batch_size = 10000\n doc_top = []\n if dist:\n doc_dist = []\n\n if document_vectors.shape[0] > batch_size:\n current = 0\n batches = int(document_vectors.shape[0] / batch_size)\n extra = document_vectors.shape[0] % batch_size\n\n for ind in range(0, batches):\n res = np.inner(document_vectors[current:current + batch_size], topic_vectors)\n\n if num_topics is None:\n doc_top.extend(np.argmax(res, axis=1))\n if dist:\n doc_dist.extend(np.max(res, axis=1))\n else:\n doc_top.extend(np.flip(np.argsort(res), axis=1)[:, :num_topics])\n if dist:\n doc_dist.extend(np.flip(np.sort(res), axis=1)[:, :num_topics])\n\n current += batch_size\n\n if extra > 0:\n res = np.inner(document_vectors[current:current + extra], topic_vectors)\n\n if num_topics is None:\n doc_top.extend(np.argmax(res, axis=1))\n if dist:\n doc_dist.extend(np.max(res, axis=1))\n else:\n doc_top.extend(np.flip(np.argsort(res), axis=1)[:, :num_topics])\n if dist:\n doc_dist.extend(np.flip(np.sort(res), axis=1)[:, :num_topics])\n if dist:\n doc_dist = np.array(doc_dist)\n else:\n res = np.inner(document_vectors, topic_vectors)\n\n if num_topics is None:\n doc_top = np.argmax(res, axis=1)\n if dist:\n doc_dist = np.max(res, axis=1)\n else:\n doc_top.extend(np.flip(np.argsort(res), axis=1)[:, :num_topics])\n if dist:\n doc_dist.extend(np.flip(np.sort(res), axis=1)[:, :num_topics])\n\n if num_topics is not None:\n doc_top = np.array(doc_top)\n if dist:\n doc_dist = np.array(doc_dist)\n\n if dist:\n return doc_top, doc_dist\n else:\n return doc_top\n\n def _find_topic_words_and_scores(self, topic_vectors):\n topic_words = []\n topic_word_scores = []\n\n res = np.inner(topic_vectors, self._get_word_vectors())\n top_words = np.flip(np.argsort(res, axis=1), axis=1)\n top_scores = np.flip(np.sort(res, axis=1), axis=1)\n\n for words, scores in zip(top_words, top_scores):\n topic_words.append([self._index2word(i) for i in words[0:50]])\n topic_word_scores.append(scores[0:50])\n\n topic_words = np.array(topic_words)\n topic_word_scores = np.array(topic_word_scores)\n\n return topic_words, topic_word_scores\n\n def _assign_documents_to_topic(self, document_vectors, hierarchy=False):\n\n if hierarchy:\n doc_top_new, doc_dist_new = self._calculate_documents_topic(self.topic_vectors_reduced,\n document_vectors,\n dist=True)\n self.doc_top_reduced = np.append(self.doc_top_reduced, doc_top_new)\n self.doc_dist_reduced = np.append(self.doc_dist_reduced, doc_dist_new)\n\n topic_sizes_new = pd.Series(doc_top_new).value_counts()\n for top in topic_sizes_new.index.tolist():\n self.topic_sizes_reduced[top] += topic_sizes_new[top]\n self.topic_sizes_reduced.sort_values(ascending=False, inplace=True)\n self._reorder_topics(hierarchy)\n else:\n doc_top_new, doc_dist_new = self._calculate_documents_topic(self.topic_vectors, document_vectors, dist=True)\n self.doc_top = np.append(self.doc_top, doc_top_new)\n self.doc_dist = np.append(self.doc_dist, doc_dist_new)\n\n topic_sizes_new = pd.Series(doc_top_new).value_counts()\n for top in topic_sizes_new.index.tolist():\n self.topic_sizes[top] += topic_sizes_new[top]\n self.topic_sizes.sort_values(ascending=False, inplace=True)\n self._reorder_topics(hierarchy)\n\n def _unassign_documents_from_topic(self, doc_indexes, hierarchy=False):\n if hierarchy:\n doc_top_remove = self.doc_top_reduced[doc_indexes]\n self.doc_top_reduced = np.delete(self.doc_top_reduced, doc_indexes, 0)\n self.doc_dist_reduced = np.delete(self.doc_dist_reduced, doc_indexes, 0)\n topic_sizes_remove = pd.Series(doc_top_remove).value_counts()\n for top in topic_sizes_remove.index.tolist():\n self.topic_sizes_reduced[top] -= topic_sizes_remove[top]\n self.topic_sizes_reduced.sort_values(ascending=False, inplace=True)\n self._reorder_topics(hierarchy)\n else:\n doc_top_remove = self.doc_top[doc_indexes]\n self.doc_top = np.delete(self.doc_top, doc_indexes, 0)\n self.doc_dist = np.delete(self.doc_dist, doc_indexes, 0)\n topic_sizes_remove = pd.Series(doc_top_remove).value_counts()\n for top in topic_sizes_remove.index.tolist():\n self.topic_sizes[top] -= topic_sizes_remove[top]\n self.topic_sizes.sort_values(ascending=False, inplace=True)\n self._reorder_topics(hierarchy)\n\n def _get_document_ids(self, doc_index):\n return self.document_ids[doc_index]\n\n def _get_document_indexes(self, doc_ids):\n if self.document_ids is None:\n return doc_ids\n else:\n return [self.doc_id2index[doc_id] for doc_id in doc_ids]\n\n def _words2word_vectors(self, keywords):\n\n return self._get_word_vectors()[[self._word2index(word) for word in keywords]]\n\n def _word2index(self, word):\n if self.embedding_model == 'doc2vec':\n return self.model.wv.vocab[word].index\n else:\n return self.word_indexes[word]\n\n def _get_combined_vec(self, vecs, vecs_neg):\n\n combined_vector = np.zeros(self._get_document_vectors().shape[1], dtype=np.float64)\n for vec in vecs:\n combined_vector += vec\n for vec in vecs_neg:\n combined_vector -= vec\n combined_vector /= (len(vecs) + len(vecs_neg))\n combined_vector = self._l2_normalize(combined_vector)\n\n return combined_vector\n\n @staticmethod\n def _search_vectors_by_vector(vectors, vector, num_res):\n ranks = np.inner(vectors, vector)\n indexes = np.flip(np.argsort(ranks)[-num_res:])\n scores = np.array([ranks[res] for res in indexes])\n\n return indexes, scores\n\n @staticmethod\n def _check_hnswlib_status():\n if not _HAVE_HNSWLIB:\n raise ImportError(f\"Indexing is not available.\\n\\n\"\n \"Try: pip install top2vec[indexing]\\n\\n\"\n \"Alternatively try: pip install hnswlib\")\n\n def _check_document_index_status(self):\n if self.document_index is None:\n raise ImportError(\"There is no document index.\\n\\n\"\n \"Call index_document_vectors method before setting use_index=True.\")\n\n def _check_word_index_status(self):\n if self.word_index is None:\n raise ImportError(\"There is no word index.\\n\\n\"\n \"Call index_word_vectors method before setting use_index=True.\")\n\n def _check_import_status(self):\n if self.embedding_model != 'distiluse-base-multilingual-cased':\n if not _HAVE_TENSORFLOW:\n raise ImportError(f\"{self.embedding_model} is not available.\\n\\n\"\n \"Try: pip install top2vec[sentence_encoders]\\n\\n\"\n \"Alternatively try: pip install tensorflow tensorflow_hub tensorflow_text\")\n else:\n if not _HAVE_TORCH:\n raise ImportError(f\"{self.embedding_model} is not available.\\n\\n\"\n \"Try: pip install top2vec[sentence_transformers]\\n\\n\"\n \"Alternatively try: pip install torch sentence_transformers\")\n\n def _check_model_status(self):\n if self.embed is None:\n if self.verbose is False:\n logger.setLevel(logging.DEBUG)\n\n if self.embedding_model != \"distiluse-base-multilingual-cased\":\n if self.embedding_model_path is None:\n logger.info(f'Downloading {self.embedding_model} model')\n if self.embedding_model == \"universal-sentence-encoder-multilingual\":\n module = \"https://tfhub.dev/google/universal-sentence-encoder-multilingual/3\"\n else:\n module = \"https://tfhub.dev/google/universal-sentence-encoder/4\"\n else:\n logger.info(f'Loading {self.embedding_model} model at {self.embedding_model_path}')\n module = self.embedding_model_path\n self.embed = hub.load(module)\n\n else:\n if self.embedding_model_path is None:\n logger.info(f'Downloading {self.embedding_model} model')\n module = 'distiluse-base-multilingual-cased'\n else:\n logger.info(f'Loading {self.embedding_model} model at {self.embedding_model_path}')\n module = self.embedding_model_path\n model = SentenceTransformer(module)\n self.embed = model.encode\n\n if self.verbose is False:\n logger.setLevel(logging.WARNING)\n\n @staticmethod\n def _less_than_zero(num, var_name):\n if num < 0:\n raise ValueError(f\"{var_name} cannot be less than 0.\")\n\n def _validate_hierarchical_reduction(self):\n if self.hierarchy is None:\n raise ValueError(\"Hierarchical topic reduction has not been performed.\")\n\n def _validate_hierarchical_reduction_num_topics(self, num_topics):\n current_num_topics = len(self.topic_vectors)\n if num_topics >= current_num_topics:\n raise ValueError(f\"Number of topics must be less than {current_num_topics}.\")\n\n def _validate_num_docs(self, num_docs):\n self._less_than_zero(num_docs, \"num_docs\")\n document_count = len(self.doc_top)\n if num_docs > document_count:\n raise ValueError(f\"num_docs cannot exceed the number of documents: {document_count}.\")\n\n def _validate_num_topics(self, num_topics, reduced):\n self._less_than_zero(num_topics, \"num_topics\")\n if reduced:\n topic_count = len(self.topic_vectors_reduced)\n if num_topics > topic_count:\n raise ValueError(f\"num_topics cannot exceed the number of reduced topics: {topic_count}.\")\n else:\n topic_count = len(self.topic_vectors)\n if num_topics > topic_count:\n raise ValueError(f\"num_topics cannot exceed the number of topics: {topic_count}.\")\n\n def _validate_topic_num(self, topic_num, reduced):\n self._less_than_zero(topic_num, \"topic_num\")\n\n if reduced:\n topic_count = len(self.topic_vectors_reduced) - 1\n if topic_num > topic_count:\n raise ValueError(f\"Invalid topic number: valid reduced topics numbers are 0 to {topic_count}.\")\n else:\n topic_count = len(self.topic_vectors) - 1\n if topic_num > topic_count:\n raise ValueError(f\"Invalid topic number: valid original topics numbers are 0 to {topic_count}.\")\n\n def _validate_topic_search(self, topic_num, num_docs, reduced):\n self._less_than_zero(num_docs, \"num_docs\")\n if reduced:\n if num_docs > self.topic_sizes_reduced[topic_num]:\n raise ValueError(f\"Invalid number of documents: reduced topic {topic_num}\"\n f\" only has {self.topic_sizes_reduced[topic_num]} documents.\")\n else:\n if num_docs > self.topic_sizes[topic_num]:\n raise ValueError(f\"Invalid number of documents: original topic {topic_num}\"\n f\" only has {self.topic_sizes[topic_num]} documents.\")\n\n def _validate_doc_ids(self, doc_ids, doc_ids_neg):\n\n if not (isinstance(doc_ids, list) or isinstance(doc_ids, np.ndarray)):\n raise ValueError(\"doc_ids must be a list of string or int.\")\n if not (isinstance(doc_ids_neg, list) or isinstance(doc_ids_neg, np.ndarray)):\n raise ValueError(\"doc_ids_neg must be a list of string or int.\")\n\n if isinstance(doc_ids, np.ndarray):\n doc_ids = list(doc_ids)\n if isinstance(doc_ids_neg, np.ndarray):\n doc_ids_neg = list(doc_ids_neg)\n\n doc_ids_all = doc_ids + doc_ids_neg\n\n if self.document_ids is not None:\n for doc_id in doc_ids_all:\n if doc_id not in self.doc_id2index:\n raise ValueError(f\"{doc_id} is not a valid document id.\")\n elif min(doc_ids) < 0:\n raise ValueError(f\"{min(doc_ids)} is not a valid document id.\")\n elif max(doc_ids) > len(self.doc_top) - 1:\n raise ValueError(f\"{max(doc_ids)} is not a valid document id.\")\n\n def _validate_keywords(self, keywords, keywords_neg):\n if not (isinstance(keywords, list) or isinstance(keywords, np.ndarray)):\n raise ValueError(\"keywords must be a list of strings.\")\n\n if not (isinstance(keywords_neg, list) or isinstance(keywords_neg, np.ndarray)):\n raise ValueError(\"keywords_neg must be a list of strings.\")\n\n keywords_lower = [keyword.lower() for keyword in keywords]\n keywords_neg_lower = [keyword.lower() for keyword in keywords_neg]\n\n if self.embedding_model == 'doc2vec':\n vocab = self.model.wv.vocab\n else:\n vocab = self.vocab\n\n for word in keywords_lower + keywords_neg_lower:\n if word not in vocab:\n raise ValueError(f\"'{word}' has not been learned by the model so it cannot be searched.\")\n\n return keywords_lower, keywords_neg_lower\n\n def _validate_document_ids_add_doc(self, documents, document_ids):\n if document_ids is None:\n raise ValueError(\"Document ids need to be provided.\")\n if len(documents) != len(document_ids):\n raise ValueError(\"Document ids need to match number of documents.\")\n if len(document_ids) != len(set(document_ids)):\n raise ValueError(\"Document ids need to be unique.\")\n\n if len(set(document_ids).intersection(self.document_ids)) > 0:\n raise ValueError(\"Some document ids already exist in model.\")\n\n if self.doc_id_type == np.str_:\n if not all((isinstance(doc_id, str) or isinstance(doc_id, np.str_)) for doc_id in document_ids):\n raise ValueError(\"Document ids need to be of type str.\")\n\n if self.doc_id_type == np.int_:\n if not all((isinstance(doc_id, int) or isinstance(doc_id, np.int_)) for doc_id in document_ids):\n raise ValueError(\"Document ids need to be of type int.\")\n\n @staticmethod\n def _validate_documents(documents):\n if not all((isinstance(doc, str) or isinstance(doc, np.str_)) for doc in documents):\n raise ValueError(\"Documents need to be a list of strings.\")\n\n @staticmethod\n def _validate_query(query):\n if not isinstance(query, str) or isinstance(query, np.str_):\n raise ValueError(\"Query needs to be a string.\")\n\n def _validate_vector(self, vector):\n if not isinstance(vector, np.ndarray):\n raise ValueError(\"Vector needs to be a numpy array.\")\n vec_size = self._get_document_vectors().shape[1]\n if not vector.shape[0] == vec_size:\n raise ValueError(f\"Vector needs to be of {vec_size} dimensions.\")\n\n def index_document_vectors(self, ef_construction=200, M=64):\n \"\"\"\n Creates an index of the document vectors using hnswlib. This will\n lead to faster search times for models with a large number of\n documents. \n\n For more information on hnswlib see: https://github.com/nmslib/hnswlib\n\n Parameters\n ----------\n ef_construction: int (Optional default 200)\n This parameter controls the trade-off between index construction\n time and index accuracy. Larger values will lead to greater\n accuracy but will take longer to construct.\n\n M: int (Optional default 64)\n This parameter controls the trade-off between both index size as\n well as construction time and accuracy. Larger values will lead to\n greater accuracy but will result in a larger index as well as\n longer construction time.\n\n For more information on the parameters see:\n https://github.com/nmslib/hnswlib/blob/master/ALGO_PARAMS.md\n \"\"\"\n\n self._check_hnswlib_status()\n\n document_vectors = self._get_document_vectors()\n vec_dim = document_vectors.shape[1]\n num_vecs = document_vectors.shape[0]\n\n index_ids = list(range(0, len(self.document_ids)))\n\n self.index_id2doc_id = dict(zip(index_ids, self.document_ids))\n self.doc_id2index_id = dict(zip(self.document_ids, index_ids))\n\n self.document_index = hnswlib.Index(space='ip', dim=vec_dim)\n self.document_index.init_index(max_elements=num_vecs, ef_construction=ef_construction, M=M)\n self.document_index.add_items(document_vectors, index_ids)\n self.documents_indexed = True\n\n def index_word_vectors(self, ef_construction=200, M=64):\n \"\"\"\n Creates an index of the word vectors using hnswlib. This will\n lead to faster search times for models with a large number of\n words.\n\n For more information on hnswlib see: https://github.com/nmslib/hnswlib\n\n Parameters\n ----------\n ef_construction: int (Optional default 200)\n This parameter controls the trade-off between index construction\n time and index accuracy. Larger values will lead to greater\n accuracy but will take longer to construct.\n\n M: int (Optional default 64)\n This parameter controls the trade-off between both index size as\n well as construction time and accuracy. Larger values will lead to\n greater accuracy but will result in a larger index as well as\n longer construction time.\n\n For more information on the parameters see:\n https://github.com/nmslib/hnswlib/blob/master/ALGO_PARAMS.md\n \"\"\"\n self._check_hnswlib_status()\n\n word_vectors = self._get_word_vectors()\n vec_dim = word_vectors.shape[1]\n num_vecs = word_vectors.shape[0]\n\n index_ids = list(range(0, num_vecs))\n\n self.word_index = hnswlib.Index(space='ip', dim=vec_dim)\n self.word_index.init_index(max_elements=num_vecs, ef_construction=ef_construction, M=M)\n self.word_index.add_items(word_vectors, index_ids)\n self.words_indexed = True\n\n def update_embedding_model_path(self, embedding_model_path):\n \"\"\"\n Update the path of the embedding model to be loaded. The model will\n no longer be downloaded but loaded from the path location.\n\n Warning: the model at embedding_model_path must match the\n embedding_model parameter type.\n\n Parameters\n ----------\n embedding_model_path: Str\n Path to downloaded embedding model.\n\n \"\"\"\n self.embedding_model_path = embedding_model_path\n\n def change_to_download_embedding_model(self):\n \"\"\"\n Use automatic download to load embedding model used for training.\n Top2Vec will no longer try and load the embedding model from a file\n if a embedding_model path was previously added.\n\n \"\"\"\n self.embedding_model_path = None\n\n def get_documents_topics(self, doc_ids, reduced=False, num_topics=1):\n \"\"\"\n Get document topics.\n\n The topic of each document will be returned.\n\n The corresponding original topics are returned unless reduced=True,\n in which case the reduced topics will be returned.\n\n Parameters\n ----------\n doc_ids: List of str, int\n A unique value per document that is used for referring to\n documents in search results. If ids were not given to the model,\n the index of each document in the model is the id.\n\n reduced: bool (Optional, default False)\n Original topics are returned by default. If True the\n reduced topics will be returned.\n\n num_topics: int (Optional, default 1)\n The number of topics to return per document.\n\n Returns\n -------\n topic_nums: array of int, shape(len(doc_ids), num_topics)\n The topic number(s) of the document corresponding to each doc_id.\n\n topic_score: array of float, shape(len(doc_ids), num_topics)\n Semantic similarity of document to topic(s). The cosine similarity\n of the document and topic vector.\n\n topics_words: array of shape(len(doc_ids), num_topics, 50)\n For each topic the top 50 words are returned, in order\n of semantic similarity to topic.\n\n Example:\n [['data', 'deep', 'learning' ... 'artificial'], <Topic 4>\n ['environment', 'warming', 'climate ... 'temperature'] <Topic 21>\n ...]\n\n word_scores: array of shape(num_topics, 50)\n For each topic the cosine similarity scores of the\n top 50 words to the topic are returned.\n\n Example:\n [[0.7132, 0.6473, 0.5700 ... 0.3455], <Topic 4>\n [0.7818', 0.7671, 0.7603 ... 0.6769] <Topic 21>\n ...]\n\n \"\"\"\n if reduced:\n self._validate_hierarchical_reduction()\n\n # make sure documents exist\n self._validate_doc_ids(doc_ids, doc_ids_neg=[])\n\n # get document indexes from ids\n doc_indexes = self._get_document_indexes(doc_ids)\n\n if num_topics == 1:\n if reduced:\n doc_topics = self.doc_top_reduced[doc_indexes]\n doc_dist = self.doc_dist_reduced[doc_indexes]\n topic_words = self.topic_words_reduced[doc_topics]\n topic_word_scores = self.topic_word_scores_reduced[doc_topics]\n else:\n doc_topics = self.doc_top[doc_indexes]\n doc_dist = self.doc_dist[doc_indexes]\n topic_words = self.topic_words[doc_topics]\n topic_word_scores = self.topic_word_scores[doc_topics]\n\n else:\n if reduced:\n topic_vectors = self.topic_vectors_reduced\n else:\n topic_vectors = self.topic_vectors\n\n doc_topics, doc_dist = self._calculate_documents_topic(topic_vectors,\n self._get_document_vectors()[doc_indexes],\n num_topics=num_topics)\n\n topic_words = np.array([self.topic_words[topics] for topics in doc_topics])\n topic_word_scores = np.array([self.topic_word_scores[topics] for topics in doc_topics])\n\n return doc_topics, doc_dist, topic_words, topic_word_scores\n\n def add_documents(self, documents, doc_ids=None, tokenizer=None, use_embedding_model_tokenizer=False):\n \"\"\"\n Update the model with new documents.\n\n The documents will be added to the current model without changing\n existing document, word and topic vectors. Topic sizes will be updated.\n\n If adding a large quantity of documents relative to the current model\n size, or documents containing a largely new vocabulary, a new model\n should be trained for best results.\n\n Parameters\n ----------\n documents: List of str\n\n doc_ids: List of str, int (Optional)\n Only required when doc_ids were given to the original model.\n\n A unique value per document that will be used for referring to\n documents in search results.\n\n tokenizer: callable (Optional, default None)\n Override the default tokenization method. If None then\n gensim.utils.simple_preprocess will be used.\n\n use_embedding_model_tokenizer: bool (Optional, default False)\n If using an embedding model other than doc2vec, use the model's\n tokenizer for document embedding.\n \"\"\"\n # if tokenizer is not passed use default\n if tokenizer is None:\n tokenizer = default_tokenizer\n\n # add documents\n self._validate_documents(documents)\n if self.documents is not None:\n self.documents = np.append(self.documents, documents)\n\n # add document ids\n if self.document_ids_provided is True:\n self._validate_document_ids_add_doc(documents, doc_ids)\n doc_ids_len = len(self.document_ids)\n self.document_ids = np.append(self.document_ids, doc_ids)\n self.doc_id2index.update(dict(zip(doc_ids, list(range(doc_ids_len, doc_ids_len + len(doc_ids))))))\n\n elif doc_ids is None:\n num_docs = len(documents)\n start_id = max(self.document_ids) + 1\n doc_ids = list(range(start_id, start_id + num_docs))\n doc_ids_len = len(self.document_ids)\n self.document_ids = np.append(self.document_ids, doc_ids)\n self.doc_id2index.update(dict(zip(doc_ids, list(range(doc_ids_len, doc_ids_len + len(doc_ids))))))\n else:\n raise ValueError(\"doc_ids cannot be used because they were not provided to model during training.\")\n\n if self.embedding_model == \"doc2vec\":\n docs_processed = [tokenizer(doc) for doc in documents]\n document_vectors = np.vstack([self.model.infer_vector(doc_words=doc,\n alpha=0.025,\n min_alpha=0.01,\n epochs=100) for doc in docs_processed])\n num_docs = len(documents)\n self.model.docvecs.count += num_docs\n self.model.docvecs.max_rawint += num_docs\n self.model.docvecs.vectors_docs_norm = None\n self._set_document_vectors(np.vstack([self._get_document_vectors(norm=False), document_vectors]))\n self.model.docvecs.init_sims()\n document_vectors = self._l2_normalize(document_vectors)\n\n else:\n if use_embedding_model_tokenizer:\n docs_training = documents\n else:\n docs_processed = [tokenizer(doc) for doc in documents]\n docs_training = [' '.join(doc) for doc in docs_processed]\n document_vectors = self._embed_documents(docs_training)\n self._set_document_vectors(np.vstack([self._get_document_vectors(), document_vectors]))\n\n # update index\n if self.documents_indexed:\n # update capacity of index\n current_max = self.document_index.get_max_elements()\n updated_max = current_max + len(documents)\n self.document_index.resize_index(updated_max)\n\n # update index_id and doc_ids\n start_index_id = max(self.index_id2doc_id.keys()) + 1\n new_index_ids = list(range(start_index_id, start_index_id + len(doc_ids)))\n self.index_id2doc_id.update(dict(zip(new_index_ids, doc_ids)))\n self.doc_id2index_id.update(dict(zip(doc_ids, new_index_ids)))\n self.document_index.add_items(document_vectors, new_index_ids)\n\n # update topics\n self._assign_documents_to_topic(document_vectors, hierarchy=False)\n\n if self.hierarchy is not None:\n self._assign_documents_to_topic(document_vectors, hierarchy=True)\n\n def delete_documents(self, doc_ids):\n \"\"\"\n Delete documents from current model.\n\n Warning: If document ids were not used in original model, deleting\n documents will change the indexes and therefore doc_ids.\n\n The documents will be deleted from the current model without changing\n existing document, word and topic vectors. Topic sizes will be updated.\n\n If deleting a large quantity of documents relative to the current model\n size a new model should be trained for best results.\n\n Parameters\n ----------\n doc_ids: List of str, int\n\n A unique value per document that is used for referring to documents\n in search results.\n \"\"\"\n # make sure documents exist\n self._validate_doc_ids(doc_ids, doc_ids_neg=[])\n\n # update index\n if self.documents_indexed:\n # delete doc_ids from index\n index_ids = [self.doc_id2index_id(doc_id) for doc_id in doc_ids]\n for index_id in index_ids:\n self.document_index.mark_deleted(index_id)\n # update index_id and doc_ids\n for doc_id in doc_ids:\n self.doc_id2index_id.pop(doc_id)\n for index_id in index_ids:\n self.index_id2doc_id.pop(index_id)\n\n # get document indexes from ids\n doc_indexes = self._get_document_indexes(doc_ids)\n\n # delete documents\n if self.documents is not None:\n self.documents = np.delete(self.documents, doc_indexes, 0)\n\n # delete document ids\n if self.document_ids is not None:\n for doc_id in doc_ids:\n self.doc_id2index.pop(doc_id)\n keys = list(self.doc_id2index.keys())\n self.document_ids = np.array(keys)\n values = list(range(0, len(self.doc_id2index.values())))\n self.doc_id2index = dict(zip(keys, values))\n\n # delete document vectors\n self._set_document_vectors(np.delete(self._get_document_vectors(norm=False), doc_indexes, 0))\n\n if self.embedding_model == 'doc2vec':\n num_docs = len(doc_indexes)\n self.model.docvecs.count -= num_docs\n self.model.docvecs.max_rawint -= num_docs\n self.model.docvecs.vectors_docs_norm = None\n self.model.docvecs.init_sims()\n\n # update topics\n self._unassign_documents_from_topic(doc_indexes, hierarchy=False)\n\n if self.hierarchy is not None:\n self._unassign_documents_from_topic(doc_indexes, hierarchy=True)\n\n def get_num_topics(self, reduced=False):\n \"\"\"\n Get number of topics.\n\n This is the number of topics Top2Vec has found in the data by default.\n If reduced is True, the number of reduced topics is returned.\n\n Parameters\n ----------\n reduced: bool (Optional, default False)\n The number of original topics will be returned by default. If True\n will return the number of reduced topics, if hierarchical topic\n reduction has been performed.\n\n Returns\n -------\n num_topics: int\n \"\"\"\n\n if reduced:\n self._validate_hierarchical_reduction()\n return len(self.topic_vectors_reduced)\n else:\n return len(self.topic_vectors)\n\n def get_topic_sizes(self, reduced=False):\n \"\"\"\n Get topic sizes.\n\n The number of documents most similar to each topic. Topics are\n in increasing order of size.\n\n The sizes of the original topics is returned unless reduced=True,\n in which case the sizes of the reduced topics will be returned.\n\n Parameters\n ----------\n reduced: bool (Optional, default False)\n Original topic sizes are returned by default. If True the\n reduced topic sizes will be returned.\n\n Returns\n -------\n topic_sizes: array of int, shape(num_topics)\n The number of documents most similar to the topic.\n topic_nums: array of int, shape(num_topics)\n The unique number of every topic will be returned.\n \"\"\"\n if reduced:\n self._validate_hierarchical_reduction()\n return np.array(self.topic_sizes_reduced.values), np.array(self.topic_sizes_reduced.index)\n else:\n return np.array(self.topic_sizes.values), np.array(self.topic_sizes.index)\n\n def get_topics(self, num_topics=None, reduced=False):\n \"\"\"\n Get topics, ordered by decreasing size. All topics are returned\n if num_topics is not specified.\n\n The original topics found are returned unless reduced=True,\n in which case reduced topics will be returned.\n\n Each topic will consist of the top 50 semantically similar words\n to the topic. These are the 50 words closest to topic vector\n along with cosine similarity of each word from vector. The\n higher the score the more relevant the word is to the topic.\n\n Parameters\n ----------\n num_topics: int, (Optional)\n Number of topics to return.\n\n reduced: bool (Optional, default False)\n Original topics are returned by default. If True the\n reduced topics will be returned.\n\n Returns\n -------\n topics_words: array of shape(num_topics, 50)\n For each topic the top 50 words are returned, in order\n of semantic similarity to topic.\n \n Example:\n [['data', 'deep', 'learning' ... 'artificial'], <Topic 0>\n ['environment', 'warming', 'climate ... 'temperature'] <Topic 1>\n ...]\n\n word_scores: array of shape(num_topics, 50)\n For each topic the cosine similarity scores of the\n top 50 words to the topic are returned.\n \n Example:\n [[0.7132, 0.6473, 0.5700 ... 0.3455], <Topic 0>\n [0.7818', 0.7671, 0.7603 ... 0.6769] <Topic 1>\n ...]\n\n topic_nums: array of int, shape(num_topics)\n The unique number of every topic will be returned.\n \"\"\"\n if reduced:\n self._validate_hierarchical_reduction()\n\n if num_topics is None:\n num_topics = len(self.topic_vectors_reduced)\n else:\n self._validate_num_topics(num_topics, reduced)\n\n return self.topic_words_reduced[0:num_topics], self.topic_word_scores_reduced[0:num_topics], np.array(\n range(0, num_topics))\n else:\n\n if num_topics is None:\n num_topics = len(self.topic_vectors)\n else:\n self._validate_num_topics(num_topics, reduced)\n\n return self.topic_words[0:num_topics], self.topic_word_scores[0:num_topics], np.array(range(0, num_topics))\n\n def get_topic_hierarchy(self):\n \"\"\"\n Get the hierarchy of reduced topics. The mapping of each original topic\n to the reduced topics is returned.\n\n Hierarchical topic reduction must be performed before calling this\n method.\n\n Returns\n -------\n hierarchy: list of ints\n Each index of the hierarchy corresponds to the topic number of a\n reduced topic. For each reduced topic the topic numbers of the\n original topics that were merged to create it are listed.\n\n Example:\n [[3] <Reduced Topic 0> contains original Topic 3\n [2,4] <Reduced Topic 1> contains original Topics 2 and 4\n [0,1] <Reduced Topic 3> contains original Topics 0 and 1\n ...]\n \"\"\"\n\n self._validate_hierarchical_reduction()\n\n return self.hierarchy\n\n def hierarchical_topic_reduction(self, num_topics):\n \"\"\"\n Reduce the number of topics discovered by Top2Vec.\n\n The most representative topics of the corpus will be found, by\n iteratively merging each smallest topic to the most similar topic until\n num_topics is reached.\n\n Parameters\n ----------\n num_topics: int\n The number of topics to reduce to.\n\n Returns\n -------\n hierarchy: list of ints\n Each index of hierarchy corresponds to the reduced topics, for each\n reduced topic the indexes of the original topics that were merged\n to create it are listed.\n\n Example:\n [[3] <Reduced Topic 0> contains original Topic 3\n [2,4] <Reduced Topic 1> contains original Topics 2 and 4\n [0,1] <Reduced Topic 3> contains original Topics 0 and 1\n ...]\n \"\"\"\n self._validate_hierarchical_reduction_num_topics(num_topics)\n\n num_topics_current = self.topic_vectors.shape[0]\n top_vecs = self.topic_vectors\n top_sizes = [self.topic_sizes[i] for i in range(0, len(self.topic_sizes))]\n hierarchy = [[i] for i in range(self.topic_vectors.shape[0])]\n\n count = 0\n interval = max(int(self._get_document_vectors().shape[0] / 50000), 1)\n\n while num_topics_current > num_topics:\n\n # find smallest and most similar topics\n smallest = np.argmin(top_sizes)\n res = np.inner(top_vecs[smallest], top_vecs)\n sims = np.flip(np.argsort(res))\n most_sim = sims[1]\n if most_sim == smallest:\n most_sim = sims[0]\n\n # calculate combined topic vector\n top_vec_smallest = top_vecs[smallest]\n smallest_size = top_sizes[smallest]\n\n top_vec_most_sim = top_vecs[most_sim]\n most_sim_size = top_sizes[most_sim]\n\n combined_vec = self._l2_normalize(((top_vec_smallest * smallest_size) +\n (top_vec_most_sim * most_sim_size)) / (smallest_size + most_sim_size))\n\n # update topic vectors\n ix_keep = list(range(len(top_vecs)))\n ix_keep.remove(smallest)\n ix_keep.remove(most_sim)\n top_vecs = top_vecs[ix_keep]\n top_vecs = np.vstack([top_vecs, combined_vec])\n num_topics_current = top_vecs.shape[0]\n\n # update topics sizes\n if count % interval == 0:\n doc_top = self._calculate_documents_topic(topic_vectors=top_vecs,\n document_vectors=self._get_document_vectors(),\n dist=False)\n topic_sizes = pd.Series(doc_top).value_counts()\n top_sizes = [topic_sizes[i] for i in range(0, len(topic_sizes))]\n\n else:\n smallest_size = top_sizes.pop(smallest)\n if most_sim < smallest:\n most_sim_size = top_sizes.pop(most_sim)\n else:\n most_sim_size = top_sizes.pop(most_sim - 1)\n combined_size = smallest_size + most_sim_size\n top_sizes.append(combined_size)\n\n count += 1\n\n # update topic hierarchy\n smallest_inds = hierarchy.pop(smallest)\n if most_sim < smallest:\n most_sim_inds = hierarchy.pop(most_sim)\n else:\n most_sim_inds = hierarchy.pop(most_sim - 1)\n\n combined_inds = smallest_inds + most_sim_inds\n hierarchy.append(combined_inds)\n\n # re-calculate topic vectors from clusters\n doc_top = self._calculate_documents_topic(topic_vectors=top_vecs,\n document_vectors=self._get_document_vectors(),\n dist=False)\n self.topic_vectors_reduced = self._l2_normalize(np.vstack([self._get_document_vectors()\n [np.where(doc_top == label)[0]]\n .mean(axis=0) for label in set(doc_top)]))\n\n self.hierarchy = hierarchy\n\n # assign documents to topic\n self.doc_top_reduced, self.doc_dist_reduced = self._calculate_documents_topic(self.topic_vectors_reduced,\n self._get_document_vectors())\n # find topic words and scores\n self.topic_words_reduced, self.topic_word_scores_reduced = self._find_topic_words_and_scores(\n topic_vectors=self.topic_vectors_reduced)\n\n # calculate topic sizes\n self.topic_sizes_reduced = self._calculate_topic_sizes(hierarchy=True)\n\n # re-order topics\n self._reorder_topics(hierarchy=True)\n\n return self.hierarchy\n\n def query_documents(self, query, num_docs, return_documents=True, use_index=False, ef=None, tokenizer=None):\n \"\"\"\n Semantic search of documents using a text query.\n\n The most semantically similar documents to the query will be returned.\n\n Parameters\n ----------\n query: string\n Any sequence of text. This could be an actual question, a sentence,\n a paragraph or a document.\n\n num_docs: int\n Number of documents to return.\n\n return_documents: bool (Optional default True)\n Determines if the documents will be returned. If they were not\n saved in the model they will not be returned.\n\n use_index: bool (Optional default False)\n If index_documents method has been called, setting this to True\n will speed up search for models with large number of documents.\n\n ef: int (Optional default None)\n Higher ef leads to more accurate but slower search. This value\n must be higher than num_docs.\n\n For more information see:\n https://github.com/nmslib/hnswlib/blob/master/ALGO_PARAMS.md\n\n tokenizer: callable (Optional, default None)\n\n ** For doc2vec embedding model only **\n\n Override the default tokenization method. If None then\n gensim.utils.simple_preprocess will be used.\n\n Returns\n -------\n documents: (Optional) array of str, shape(num_docs)\n The documents in a list, the most similar are first.\n\n Will only be returned if the documents were saved and if\n return_documents is set to True.\n\n doc_scores: array of float, shape(num_docs)\n Semantic similarity of document to vector. The cosine similarity of\n the document and vector.\n\n doc_ids: array of int, shape(num_docs)\n Unique ids of documents. If ids were not given to the model, the\n index of the document in the model will be returned.\n \"\"\"\n\n self._validate_query(query)\n self._validate_num_docs(num_docs)\n\n if self.embedding_model != \"doc2vec\":\n query_vec = self._embed_query(query)\n\n else:\n\n # if tokenizer is not passed use default\n if tokenizer is None:\n tokenizer = default_tokenizer\n\n tokenized_query = tokenizer(query)\n\n query_vec = self.model.infer_vector(doc_words=tokenized_query,\n alpha=0.025,\n min_alpha=0.01,\n epochs=100)\n\n return self.search_documents_by_vector(query_vec, num_docs, return_documents=return_documents,\n use_index=use_index, ef=ef)\n\n def query_topics(self, query, num_topics, reduced=False, tokenizer=None):\n \"\"\"\n Semantic search of topics using text query.\n\n These are the topics closest to the vector. Topics are ordered by\n proximity to the vector. Successive topics in the list are less\n semantically similar to the vector.\n\n Parameters\n ----------\n query: string\n Any sequence of text. This could be an actual question, a sentence,\n a paragraph or a document.\n\n num_topics: int\n Number of documents to return.\n\n reduced: bool (Optional, default False)\n Original topics are searched by default. If True the\n reduced topics will be searched.\n\n tokenizer: callable (Optional, default None)\n\n ** For doc2vec embedding model only **\n\n Override the default tokenization method. If None then\n gensim.utils.simple_preprocess will be used.\n\n Returns\n -------\n topics_words: array of shape (num_topics, 50)\n For each topic the top 50 words are returned, in order of semantic\n similarity to topic.\n\n Example:\n [['data', 'deep', 'learning' ... 'artificial'], <Topic 0>\n ['environment', 'warming', 'climate ... 'temperature'] <Topic 1>\n ...]\n\n word_scores: array of shape (num_topics, 50)\n For each topic the cosine similarity scores of the top 50 words\n to the topic are returned.\n\n Example:\n [[0.7132, 0.6473, 0.5700 ... 0.3455], <Topic 0>\n [0.7818', 0.7671, 0.7603 ... 0.6769] <Topic 1>\n ...]\n\n topic_scores: array of float, shape(num_topics)\n For each topic the cosine similarity to the search keywords will be\n returned.\n\n topic_nums: array of int, shape(num_topics)\n The unique number of every topic will be returned.\n \"\"\"\n\n self._validate_query(query)\n\n if self.embedding_model != \"doc2vec\":\n query_vec = self._embed_query(query)\n\n else:\n\n # if tokenizer is not passed use default\n if tokenizer is None:\n tokenizer = default_tokenizer\n\n tokenized_query = tokenizer(query)\n\n query_vec = self.model.infer_vector(doc_words=tokenized_query,\n alpha=0.025,\n min_alpha=0.01,\n epochs=100)\n\n return self.search_topics_by_vector(query_vec, num_topics=num_topics, reduced=reduced)\n\n def search_documents_by_vector(self, vector, num_docs, return_documents=True, use_index=False, ef=None):\n \"\"\"\n Semantic search of documents using a vector.\n\n These are the documents closest to the vector. Documents are\n ordered by proximity to the vector. Successive documents in the\n list are less semantically similar to the vector.\n\n Parameters\n ----------\n vector: array of shape(vector dimension, 1)\n The vector dimension should be the same as the vectors in\n the topic_vectors variable. (i.e. model.topic_vectors.shape[1])\n\n num_docs: int\n Number of documents to return.\n\n return_documents: bool (Optional default True)\n Determines if the documents will be returned. If they were not\n saved in the model they will not be returned.\n\n use_index: bool (Optional default False)\n If index_documents method has been called, setting this to True\n will speed up search for models with large number of documents.\n\n ef: int (Optional default None)\n Higher ef leads to more accurate but slower search. This value\n must be higher than num_docs.\n\n For more information see:\n https://github.com/nmslib/hnswlib/blob/master/ALGO_PARAMS.md\n\n Returns\n -------\n documents: (Optional) array of str, shape(num_docs)\n The documents in a list, the most similar are first.\n\n Will only be returned if the documents were saved and if\n return_documents is set to True.\n\n doc_scores: array of float, shape(num_docs)\n Semantic similarity of document to vector. The cosine similarity of\n the document and vector.\n\n doc_ids: array of int, shape(num_docs)\n Unique ids of documents. If ids were not given to the model, the\n index of the document in the model will be returned.\n \"\"\"\n self._validate_vector(vector)\n self._validate_num_docs(num_docs)\n\n vector = self._l2_normalize(vector)\n\n if use_index:\n self._check_document_index_status()\n\n if ef is not None:\n self.document_index.set_ef(ef)\n else:\n self.document_index.set_ef(num_docs)\n\n index_ids, doc_scores = self.document_index.knn_query(vector, k=num_docs)\n index_ids = index_ids[0]\n doc_ids = np.array([self.index_id2doc_id[index_id] for index_id in index_ids])\n doc_scores = doc_scores[0]\n doc_scores = np.array([1 - score for score in doc_scores])\n doc_indexes = self._get_document_indexes(doc_ids)\n else:\n doc_indexes, doc_scores = self._search_vectors_by_vector(self._get_document_vectors(),\n vector, num_docs)\n doc_ids = self._get_document_ids(doc_indexes)\n\n if self.documents is not None and return_documents:\n documents = self.documents[doc_indexes]\n return documents, doc_scores, doc_ids\n else:\n return doc_scores, doc_ids\n\n def search_words_by_vector(self, vector, num_words, use_index=False, ef=None):\n \"\"\"\n Semantic search of words using a vector.\n\n These are the words closest to the vector. Words are ordered by\n proximity to the vector. Successive words in the list are less\n semantically similar to the vector.\n\n Parameters\n ----------\n vector: array of shape(vector dimension, 1)\n The vector dimension should be the same as the vectors in\n the topic_vectors variable. (i.e. model.topic_vectors.shape[1])\n\n num_words: int\n Number of words to return.\n\n use_index: bool (Optional default False)\n If index_words method has been called, setting this to True will\n speed up search for models with large number of words.\n\n ef: int (Optional default None)\n Higher ef leads to more accurate but slower search. This value\n must be higher than num_docs.\n\n For more information see:\n https://github.com/nmslib/hnswlib/blob/master/ALGO_PARAMS.md\n\n Returns\n -------\n words: array of str, shape(num_words)\n The words in a list, the most similar are first.\n\n word_scores: array of float, shape(num_words)\n Semantic similarity of word to vector. The cosine similarity of\n the word and vector.\n \"\"\"\n\n self._validate_vector(vector)\n\n vector = self._l2_normalize(vector)\n\n if use_index:\n self._check_word_index_status()\n\n if ef is not None:\n self.word_index.set_ef(ef)\n else:\n self.word_index.set_ef(num_words)\n\n word_indexes, word_scores = self.word_index.knn_query(vector, k=num_words)\n word_indexes = word_indexes[0]\n word_scores = word_scores[0]\n word_scores = np.array([1 - score for score in word_scores])\n\n else:\n word_indexes, word_scores = self._search_vectors_by_vector(self._get_word_vectors(),\n vector, num_words)\n\n words = np.array([self._index2word(index) for index in word_indexes])\n\n return words, word_scores\n\n def search_topics_by_vector(self, vector, num_topics, reduced=False):\n \"\"\"\n Semantic search of topics using keywords.\n\n These are the topics closest to the vector. Topics are ordered by\n proximity to the vector. Successive topics in the list are less\n semantically similar to the vector.\n\n Parameters\n ----------\n vector: array of shape(vector dimension, 1)\n The vector dimension should be the same as the vectors in\n the topic_vectors variable. (i.e. model.topic_vectors.shape[1])\n\n num_topics: int\n Number of documents to return.\n\n reduced: bool (Optional, default False)\n Original topics are searched by default. If True the\n reduced topics will be searched.\n\n Returns\n -------\n topics_words: array of shape (num_topics, 50)\n For each topic the top 50 words are returned, in order of semantic\n similarity to topic.\n\n Example:\n [['data', 'deep', 'learning' ... 'artificial'], <Topic 0>\n ['environment', 'warming', 'climate ... 'temperature'] <Topic 1>\n ...]\n\n word_scores: array of shape (num_topics, 50)\n For each topic the cosine similarity scores of the top 50 words\n to the topic are returned.\n\n Example:\n [[0.7132, 0.6473, 0.5700 ... 0.3455], <Topic 0>\n [0.7818', 0.7671, 0.7603 ... 0.6769] <Topic 1>\n ...]\n\n topic_scores: array of float, shape(num_topics)\n For each topic the cosine similarity to the search keywords will be\n returned.\n\n topic_nums: array of int, shape(num_topics)\n The unique number of every topic will be returned.\n \"\"\"\n\n self._validate_vector(vector)\n self._validate_num_topics(num_topics, reduced)\n\n vector = self._l2_normalize(vector)\n\n if reduced:\n self._validate_hierarchical_reduction()\n\n topic_nums, topic_scores = self._search_vectors_by_vector(self.topic_vectors_reduced,\n vector, num_topics)\n topic_words = [self.topic_words_reduced[topic] for topic in topic_nums]\n word_scores = [self.topic_word_scores_reduced[topic] for topic in topic_nums]\n\n else:\n topic_nums, topic_scores = self._search_vectors_by_vector(self.topic_vectors,\n vector, num_topics)\n topic_words = [self.topic_words[topic] for topic in topic_nums]\n word_scores = [self.topic_word_scores[topic] for topic in topic_nums]\n\n return topic_words, word_scores, topic_scores, topic_nums\n\n def search_documents_by_topic(self, topic_num, num_docs, return_documents=True, reduced=False):\n \"\"\"\n Get the most semantically similar documents to the topic.\n\n These are the documents closest to the topic vector. Documents are\n ordered by proximity to the topic vector. Successive documents in the\n list are less semantically similar to the topic.\n\n Parameters\n ----------\n topic_num: int\n The topic number to search.\n\n num_docs: int\n Number of documents to return.\n\n return_documents: bool (Optional default True)\n Determines if the documents will be returned. If they were not\n saved in the model they will not be returned.\n\n reduced: bool (Optional, default False)\n Original topics are used to search by default. If True the\n reduced topics will be used.\n\n Returns\n -------\n documents: (Optional) array of str, shape(num_docs)\n The documents in a list, the most similar are first.\n\n Will only be returned if the documents were saved and if\n return_documents is set to True.\n\n doc_scores: array of float, shape(num_docs)\n Semantic similarity of document to topic. The cosine similarity of\n the document and topic vector.\n\n doc_ids: array of int, shape(num_docs)\n Unique ids of documents. If ids were not given to the model, the\n index of the document in the model will be returned.\n \"\"\"\n\n if reduced:\n self._validate_hierarchical_reduction()\n self._validate_topic_num(topic_num, reduced)\n self._validate_topic_search(topic_num, num_docs, reduced)\n\n topic_document_indexes = np.where(self.doc_top_reduced == topic_num)[0]\n topic_document_indexes_ordered = np.flip(np.argsort(self.doc_dist_reduced[topic_document_indexes]))\n doc_indexes = topic_document_indexes[topic_document_indexes_ordered][0:num_docs]\n doc_scores = self.doc_dist_reduced[doc_indexes]\n doc_ids = self._get_document_ids(doc_indexes)\n\n else:\n\n self._validate_topic_num(topic_num, reduced)\n self._validate_topic_search(topic_num, num_docs, reduced)\n\n topic_document_indexes = np.where(self.doc_top == topic_num)[0]\n topic_document_indexes_ordered = np.flip(np.argsort(self.doc_dist[topic_document_indexes]))\n doc_indexes = topic_document_indexes[topic_document_indexes_ordered][0:num_docs]\n doc_scores = self.doc_dist[doc_indexes]\n doc_ids = self._get_document_ids(doc_indexes)\n\n if self.documents is not None and return_documents:\n documents = self.documents[doc_indexes]\n return documents, doc_scores, doc_ids\n else:\n return doc_scores, doc_ids\n\n def search_documents_by_keywords(self, keywords, num_docs, keywords_neg=None, return_documents=True,\n use_index=False, ef=None):\n \"\"\"\n Semantic search of documents using keywords.\n\n The most semantically similar documents to the combination of the\n keywords will be returned. If negative keywords are provided, the\n documents will be semantically dissimilar to those words. Too many\n keywords or certain combinations of words may give strange results.\n This method finds an average vector(negative keywords are subtracted)\n of all the keyword vectors and returns the documents closest to the\n resulting vector.\n\n Parameters\n ----------\n keywords: List of str\n List of positive keywords being used for search of semantically\n similar documents.\n\n keywords_neg: List of str (Optional)\n List of negative keywords being used for search of semantically\n dissimilar documents.\n\n num_docs: int\n Number of documents to return.\n\n return_documents: bool (Optional default True)\n Determines if the documents will be returned. If they were not\n saved in the model they will also not be returned.\n\n use_index: bool (Optional default False)\n If index_documents method has been called, setting this to True\n will speed up search for models with large number of documents.\n\n ef: int (Optional default None)\n Higher ef leads to more accurate but slower search. This value\n must be higher than num_docs.\n\n For more information see:\n https://github.com/nmslib/hnswlib/blob/master/ALGO_PARAMS.md\n\n Returns\n -------\n documents: (Optional) array of str, shape(num_docs)\n The documents in a list, the most similar are first.\n\n Will only be returned if the documents were saved and if\n return_documents is set to True.\n\n doc_scores: array of float, shape(num_docs)\n Semantic similarity of document to keywords. The cosine similarity\n of the document and average of keyword vectors.\n\n doc_ids: array of int, shape(num_docs)\n Unique ids of documents. If ids were not given to the model, the\n index of the document in the model will be returned.\n \"\"\"\n\n if keywords_neg is None:\n keywords_neg = []\n\n self._validate_num_docs(num_docs)\n keywords, keywords_neg = self._validate_keywords(keywords, keywords_neg)\n word_vecs = self._words2word_vectors(keywords)\n neg_word_vecs = self._words2word_vectors(keywords_neg)\n\n if use_index:\n self._check_document_index_status()\n combined_vector = self._get_combined_vec(word_vecs, neg_word_vecs)\n return self.search_documents_by_vector(combined_vector, num_docs, return_documents=return_documents,\n use_index=True, ef=ef)\n\n if self.embedding_model == 'doc2vec':\n sim_docs = self.model.docvecs.most_similar(positive=word_vecs,\n negative=neg_word_vecs,\n topn=num_docs)\n doc_indexes = [doc[0] for doc in sim_docs]\n doc_scores = np.array([doc[1] for doc in sim_docs])\n else:\n combined_vector = self._get_combined_vec(word_vecs, neg_word_vecs)\n doc_indexes, doc_scores = self._search_vectors_by_vector(self._get_document_vectors(),\n combined_vector, num_docs)\n\n doc_ids = self._get_document_ids(doc_indexes)\n\n if self.documents is not None and return_documents:\n documents = self.documents[doc_indexes]\n return documents, doc_scores, doc_ids\n else:\n return doc_scores, doc_ids\n\n def similar_words(self, keywords, num_words, keywords_neg=None, use_index=False, ef=None):\n \"\"\"\n Semantic similarity search of words.\n\n The most semantically similar word to the combination of the keywords\n will be returned. If negative keywords are provided, the words will be\n semantically dissimilar to those words. Too many keywords or certain\n combinations of words may give strange results. This method finds an\n average vector(negative keywords are subtracted) of all the keyword\n vectors and returns the words closest to the resulting vector.\n\n Parameters\n ----------\n keywords: List of str\n List of positive keywords being used for search of semantically\n similar words.\n\n keywords_neg: List of str\n List of negative keywords being used for search of semantically\n dissimilar words.\n\n num_words: int\n Number of words to return.\n\n use_index: bool (Optional default False)\n If index_words method has been called, setting this to True will\n speed up search for models with large number of words.\n\n ef: int (Optional default None)\n Higher ef leads to more accurate but slower search. This value\n must be higher than num_docs.\n\n For more information see:\n https://github.com/nmslib/hnswlib/blob/master/ALGO_PARAMS.md\n\n Returns\n -------\n words: array of str, shape(num_words)\n The words in a list, the most similar are first.\n\n word_scores: array of float, shape(num_words)\n Semantic similarity of word to keywords. The cosine similarity of\n the word and average of keyword vectors.\n \"\"\"\n if keywords_neg is None:\n keywords_neg = []\n\n keywords, keywords_neg = self._validate_keywords(keywords, keywords_neg)\n\n word_vecs = self._words2word_vectors(keywords)\n neg_word_vecs = self._words2word_vectors(keywords_neg)\n combined_vector = self._get_combined_vec(word_vecs, neg_word_vecs)\n\n num_res = min(num_words + len(keywords) + len(keywords_neg), self._get_word_vectors().shape[0])\n\n # if use_index:\n words, word_scores = self.search_words_by_vector(vector=combined_vector,\n num_words=num_res,\n use_index=use_index,\n ef=ef)\n\n res_indexes = [index for index, word in enumerate(words)\n if word not in list(keywords) + list(keywords_neg)][:num_words]\n words = words[res_indexes]\n word_scores = word_scores[res_indexes]\n\n return words, word_scores\n\n def search_topics(self, keywords, num_topics, keywords_neg=None, reduced=False):\n \"\"\"\n Semantic search of topics using keywords.\n\n The most semantically similar topics to the combination of the keywords\n will be returned. If negative keywords are provided, the topics will be\n semantically dissimilar to those words. Topics will be ordered by\n decreasing similarity to the keywords. Too many keywords or certain\n combinations of words may give strange results. This method finds an\n average vector(negative keywords are subtracted) of all the keyword\n vectors and returns the topics closest to the resulting vector.\n\n Parameters\n ----------\n keywords: List of str\n List of positive keywords being used for search of semantically\n similar documents.\n\n keywords_neg: (Optional) List of str\n List of negative keywords being used for search of semantically\n dissimilar documents.\n\n num_topics: int\n Number of documents to return.\n\n reduced: bool (Optional, default False)\n Original topics are searched by default. If True the\n reduced topics will be searched.\n\n Returns\n -------\n topics_words: array of shape (num_topics, 50)\n For each topic the top 50 words are returned, in order of semantic\n similarity to topic.\n \n Example:\n [['data', 'deep', 'learning' ... 'artificial'], <Topic 0>\n ['environment', 'warming', 'climate ... 'temperature'] <Topic 1>\n ...]\n\n word_scores: array of shape (num_topics, 50)\n For each topic the cosine similarity scores of the top 50 words\n to the topic are returned.\n \n Example:\n [[0.7132, 0.6473, 0.5700 ... 0.3455], <Topic 0>\n [0.7818', 0.7671, 0.7603 ... 0.6769] <Topic 1>\n ...]\n\n topic_scores: array of float, shape(num_topics)\n For each topic the cosine similarity to the search keywords will be\n returned.\n\n topic_nums: array of int, shape(num_topics)\n The unique number of every topic will be returned.\n \"\"\"\n if keywords_neg is None:\n keywords_neg = []\n\n keywords, keywords_neg = self._validate_keywords(keywords, keywords_neg)\n word_vecs = self._words2word_vectors(keywords)\n neg_word_vecs = self._words2word_vectors(keywords_neg)\n combined_vector = self._get_combined_vec(word_vecs, neg_word_vecs)\n\n return self.search_topics_by_vector(combined_vector, num_topics=num_topics, reduced=reduced)\n\n def search_documents_by_documents(self, doc_ids, num_docs, doc_ids_neg=None, return_documents=True,\n use_index=False, ef=None):\n \"\"\"\n Semantic similarity search of documents.\n\n The most semantically similar documents to the semantic combination of\n document ids provided will be returned. If negative document ids are\n provided, the documents will be semantically dissimilar to those\n document ids. Documents will be ordered by decreasing similarity. This\n method finds the closest document vectors to the provided documents\n averaged.\n\n Parameters\n ----------\n doc_ids: List of int, str\n Unique ids of document. If ids were not given, the index of\n document in the original corpus.\n\n doc_ids_neg: (Optional) List of int, str\n Unique ids of document. If ids were not given, the index of\n document in the original corpus.\n\n num_docs: int\n Number of documents to return.\n\n return_documents: bool (Optional default True)\n Determines if the documents will be returned. If they were not\n saved in the model they will also not be returned.\n\n use_index: bool (Optional default False)\n If index_documents method has been called, setting this to True\n will speed up search for models with large number of documents.\n\n ef: int (Optional default None)\n Higher ef leads to more accurate but slower search. This value\n must be higher than num_docs.\n\n For more information see:\n https://github.com/nmslib/hnswlib/blob/master/ALGO_PARAMS.md\n\n Returns\n -------\n documents: (Optional) array of str, shape(num_docs)\n The documents in a list, the most similar are first.\n\n Will only be returned if the documents were saved and if\n return_documents is set to True.\n\n doc_scores: array of float, shape(num_docs)\n Semantic similarity of document to keywords. The cosine similarity\n of the document and average of keyword vectors.\n\n doc_ids: array of int, shape(num_docs)\n Unique ids of documents. If ids were not given to the model, the\n index of the document in the model will be returned.\n \"\"\"\n if doc_ids_neg is None:\n doc_ids_neg = []\n\n self._validate_num_docs(num_docs)\n self._validate_doc_ids(doc_ids, doc_ids_neg)\n\n doc_indexes = self._get_document_indexes(doc_ids)\n doc_indexes_neg = self._get_document_indexes(doc_ids_neg)\n\n if use_index:\n self._check_document_index_status()\n document_vectors = self._get_document_vectors()\n doc_vecs = [document_vectors[ind] for ind in doc_indexes]\n doc_vecs_neg = [document_vectors[ind] for ind in doc_indexes_neg]\n combined_vector = self._get_combined_vec(doc_vecs, doc_vecs_neg)\n return self.search_documents_by_vector(combined_vector, num_docs, return_documents=return_documents,\n use_index=True, ef=ef)\n\n if self.embedding_model == 'doc2vec':\n sim_docs = self.model.docvecs.most_similar(positive=doc_indexes,\n negative=doc_indexes_neg,\n topn=num_docs)\n doc_indexes = [doc[0] for doc in sim_docs]\n doc_scores = np.array([doc[1] for doc in sim_docs])\n else:\n doc_vecs = [self.document_vectors[ind] for ind in doc_indexes]\n doc_vecs_neg = [self.document_vectors[ind] for ind in doc_indexes_neg]\n combined_vector = self._get_combined_vec(doc_vecs, doc_vecs_neg)\n\n num_res = min(num_docs + len(doc_indexes) + len(doc_indexes_neg),\n self._get_document_vectors().shape[0])\n\n # don't return documents that were searched\n search_doc_indexes = list(doc_indexes) + list(doc_indexes_neg)\n doc_indexes, doc_scores = self._search_vectors_by_vector(self._get_document_vectors(),\n combined_vector, num_res)\n res_indexes = [index for index, doc_ind in enumerate(doc_indexes)\n if doc_ind not in search_doc_indexes][:num_docs]\n doc_indexes = doc_indexes[res_indexes]\n doc_scores = doc_scores[res_indexes]\n\n doc_ids = self._get_document_ids(doc_indexes)\n\n if self.documents is not None and return_documents:\n documents = self.documents[doc_indexes]\n return documents, doc_scores, doc_ids\n else:\n return doc_scores, doc_ids\n\n def generate_topic_wordcloud(self, topic_num, background_color=\"black\", reduced=False):\n \"\"\"\n Create a word cloud for a topic.\n\n A word cloud will be generated and displayed. The most semantically\n similar words to the topic will have the largest size, less similar\n words will be smaller. The size is determined using the cosine distance\n of the word vectors from the topic vector.\n\n Parameters\n ----------\n topic_num: int\n The topic number to search.\n\n background_color : str (Optional, default='white')\n Background color for the word cloud image. Suggested options are:\n * white\n * black\n\n reduced: bool (Optional, default False)\n Original topics are used by default. If True the\n reduced topics will be used.\n\n Returns\n -------\n A matplotlib plot of the word cloud with the topic number will be\n displayed.\n\n \"\"\"\n\n if reduced:\n self._validate_hierarchical_reduction()\n self._validate_topic_num(topic_num, reduced)\n word_score_dict = dict(zip(self.topic_words_reduced[topic_num],\n softmax(self.topic_word_scores_reduced[topic_num])))\n else:\n self._validate_topic_num(topic_num, reduced)\n word_score_dict = dict(zip(self.topic_words[topic_num],\n softmax(self.topic_word_scores[topic_num])))\n\n plt.figure(figsize=(16, 4),\n dpi=200)\n plt.axis(\"off\")\n plt.imshow(\n WordCloud(width=1600,\n height=400,\n background_color=background_color,\n font_path='B Zar.ttf').generate_from_frequencies(word_score_dict))\n plt.title(\"Topic \" + str(topic_num), loc='left', fontsize=25, pad=20)\n"
] |
[
[
"pandas.Series",
"numpy.max",
"numpy.argmin",
"scipy.special.softmax",
"numpy.where",
"sklearn.cluster.dbscan",
"sklearn.feature_extraction.text.CountVectorizer",
"numpy.argmax",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.figure",
"numpy.append",
"numpy.delete",
"numpy.argsort",
"numpy.array",
"numpy.sum",
"numpy.inner",
"numpy.sort",
"sklearn.preprocessing.normalize",
"numpy.vstack"
]
] |
[
{
"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": [
"1.6",
"1.10",
"1.4",
"1.9",
"1.5",
"1.2",
"1.7",
"1.3",
"1.8"
],
"tensorflow": []
}
] |
AlessandroLaRocca96/vision
|
[
"d4195587166134c3806ae81458d08b06f5e00295"
] |
[
"test/fakedata_generation.py"
] |
[
"import os\nimport contextlib\nimport tarfile\nimport json\nimport numpy as np\nimport PIL\nimport torch\nfrom common_utils import get_tmp_dir\nimport pickle\nimport random\nfrom itertools import cycle\nfrom torchvision.io.video import write_video\nimport unittest.mock\nimport hashlib\nfrom distutils import dir_util\nimport re\n\n\ndef mock_class_attribute(stack, target, new):\n mock = unittest.mock.patch(target, new_callable=unittest.mock.PropertyMock, return_value=new)\n stack.enter_context(mock)\n return mock\n\n\ndef compute_md5(file):\n with open(file, \"rb\") as fh:\n return hashlib.md5(fh.read()).hexdigest()\n\n\ndef make_tar(root, name, *files, compression=None):\n ext = \".tar\"\n mode = \"w\"\n if compression is not None:\n ext = f\"{ext}.{compression}\"\n mode = f\"{mode}:{compression}\"\n\n name = os.path.splitext(name)[0] + ext\n archive = os.path.join(root, name)\n\n with tarfile.open(archive, mode) as fh:\n for file in files:\n fh.add(os.path.join(root, file), arcname=file)\n\n return name, compute_md5(archive)\n\n\ndef clean_dir(root, *keep):\n pattern = re.compile(f\"({f')|('.join(keep)})\")\n for file_or_dir in os.listdir(root):\n if pattern.search(file_or_dir):\n continue\n\n file_or_dir = os.path.join(root, file_or_dir)\n if os.path.isfile(file_or_dir):\n os.remove(file_or_dir)\n else:\n dir_util.remove_tree(file_or_dir)\n\n\[email protected]\ndef mnist_root(num_images, cls_name):\n def _encode(v):\n return torch.tensor(v, dtype=torch.int32).numpy().tobytes()[::-1]\n\n def _make_image_file(filename, num_images):\n img = torch.randint(0, 256, size=(28 * 28 * num_images,), dtype=torch.uint8)\n with open(filename, \"wb\") as f:\n f.write(_encode(2051)) # magic header\n f.write(_encode(num_images))\n f.write(_encode(28))\n f.write(_encode(28))\n f.write(img.numpy().tobytes())\n\n def _make_label_file(filename, num_images):\n labels = torch.zeros((num_images,), dtype=torch.uint8)\n with open(filename, \"wb\") as f:\n f.write(_encode(2049)) # magic header\n f.write(_encode(num_images))\n f.write(labels.numpy().tobytes())\n\n with get_tmp_dir() as tmp_dir:\n raw_dir = os.path.join(tmp_dir, cls_name, \"raw\")\n os.makedirs(raw_dir)\n _make_image_file(os.path.join(raw_dir, \"train-images-idx3-ubyte\"), num_images)\n _make_label_file(os.path.join(raw_dir, \"train-labels-idx1-ubyte\"), num_images)\n _make_image_file(os.path.join(raw_dir, \"t10k-images-idx3-ubyte\"), num_images)\n _make_label_file(os.path.join(raw_dir, \"t10k-labels-idx1-ubyte\"), num_images)\n yield tmp_dir\n\n\[email protected]\ndef cifar_root(version):\n def _get_version_params(version):\n if version == 'CIFAR10':\n return {\n 'base_folder': 'cifar-10-batches-py',\n 'train_files': ['data_batch_{}'.format(batch) for batch in range(1, 6)],\n 'test_file': 'test_batch',\n 'target_key': 'labels',\n 'meta_file': 'batches.meta',\n 'classes_key': 'label_names',\n }\n elif version == 'CIFAR100':\n return {\n 'base_folder': 'cifar-100-python',\n 'train_files': ['train'],\n 'test_file': 'test',\n 'target_key': 'fine_labels',\n 'meta_file': 'meta',\n 'classes_key': 'fine_label_names',\n }\n else:\n raise ValueError\n\n def _make_pickled_file(obj, file):\n with open(file, 'wb') as fh:\n pickle.dump(obj, fh, 2)\n\n def _make_data_file(file, target_key):\n obj = {\n 'data': np.zeros((1, 32 * 32 * 3), dtype=np.uint8),\n target_key: [0]\n }\n _make_pickled_file(obj, file)\n\n def _make_meta_file(file, classes_key):\n obj = {\n classes_key: ['fakedata'],\n }\n _make_pickled_file(obj, file)\n\n params = _get_version_params(version)\n with get_tmp_dir() as root:\n base_folder = os.path.join(root, params['base_folder'])\n os.mkdir(base_folder)\n\n for file in list(params['train_files']) + [params['test_file']]:\n _make_data_file(os.path.join(base_folder, file), params['target_key'])\n\n _make_meta_file(os.path.join(base_folder, params['meta_file']),\n params['classes_key'])\n\n yield root\n\n\[email protected]\ndef widerface_root():\n \"\"\"\n Generates a dataset with the following folder structure and returns the path root:\n <root>\n └── widerface\n ├── wider_face_split\n ├── WIDER_train\n ├── WIDER_val\n └── WIDER_test\n\n The dataset consist of\n 1 image for each dataset split (train, val, test) and annotation files\n for each split\n \"\"\"\n\n def _make_image(file):\n PIL.Image.fromarray(np.zeros((32, 32, 3), dtype=np.uint8)).save(file)\n\n def _make_train_archive(root):\n extracted_dir = os.path.join(root, 'WIDER_train', 'images', '0--Parade')\n os.makedirs(extracted_dir)\n _make_image(os.path.join(extracted_dir, '0_Parade_marchingband_1_1.jpg'))\n\n def _make_val_archive(root):\n extracted_dir = os.path.join(root, 'WIDER_val', 'images', '0--Parade')\n os.makedirs(extracted_dir)\n _make_image(os.path.join(extracted_dir, '0_Parade_marchingband_1_2.jpg'))\n\n def _make_test_archive(root):\n extracted_dir = os.path.join(root, 'WIDER_test', 'images', '0--Parade')\n os.makedirs(extracted_dir)\n _make_image(os.path.join(extracted_dir, '0_Parade_marchingband_1_3.jpg'))\n\n def _make_annotations_archive(root):\n train_bbox_contents = '0--Parade/0_Parade_marchingband_1_1.jpg\\n1\\n449 330 122 149 0 0 0 0 0 0\\n'\n val_bbox_contents = '0--Parade/0_Parade_marchingband_1_2.jpg\\n1\\n501 160 285 443 0 0 0 0 0 0\\n'\n test_filelist_contents = '0--Parade/0_Parade_marchingband_1_3.jpg\\n'\n extracted_dir = os.path.join(root, 'wider_face_split')\n os.mkdir(extracted_dir)\n\n # bbox training file\n bbox_file = os.path.join(extracted_dir, \"wider_face_train_bbx_gt.txt\")\n with open(bbox_file, \"w\") as txt_file:\n txt_file.write(train_bbox_contents)\n\n # bbox validation file\n bbox_file = os.path.join(extracted_dir, \"wider_face_val_bbx_gt.txt\")\n with open(bbox_file, \"w\") as txt_file:\n txt_file.write(val_bbox_contents)\n\n # test filelist file\n filelist_file = os.path.join(extracted_dir, \"wider_face_test_filelist.txt\")\n with open(filelist_file, \"w\") as txt_file:\n txt_file.write(test_filelist_contents)\n\n with get_tmp_dir() as root:\n root_base = os.path.join(root, \"widerface\")\n os.mkdir(root_base)\n _make_train_archive(root_base)\n _make_val_archive(root_base)\n _make_test_archive(root_base)\n _make_annotations_archive(root_base)\n\n yield root\n\n\[email protected]\ndef places365_root(split=\"train-standard\", small=False):\n VARIANTS = {\n \"train-standard\": \"standard\",\n \"train-challenge\": \"challenge\",\n \"val\": \"standard\",\n }\n # {split: file}\n DEVKITS = {\n \"train-standard\": \"filelist_places365-standard.tar\",\n \"train-challenge\": \"filelist_places365-challenge.tar\",\n \"val\": \"filelist_places365-standard.tar\",\n }\n CATEGORIES = \"categories_places365.txt\"\n # {split: file}\n FILE_LISTS = {\n \"train-standard\": \"places365_train_standard.txt\",\n \"train-challenge\": \"places365_train_challenge.txt\",\n \"val\": \"places365_train_standard.txt\",\n }\n # {(split, small): (archive, folder_default, folder_renamed)}\n IMAGES = {\n (\"train-standard\", False): (\"train_large_places365standard.tar\", \"data_large\", \"data_large_standard\"),\n (\"train-challenge\", False): (\"train_large_places365challenge.tar\", \"data_large\", \"data_large_challenge\"),\n (\"val\", False): (\"val_large.tar\", \"val_large\", \"val_large\"),\n (\"train-standard\", True): (\"train_256_places365standard.tar\", \"data_256\", \"data_256_standard\"),\n (\"train-challenge\", True): (\"train_256_places365challenge.tar\", \"data_256\", \"data_256_challenge\"),\n (\"val\", True): (\"val_256.tar\", \"val_256\", \"val_256\"),\n }\n\n # (class, idx)\n CATEGORIES_CONTENT = ((\"/a/airfield\", 0), (\"/a/apartment_building/outdoor\", 8), (\"/b/badlands\", 30))\n # (file, idx)\n FILE_LIST_CONTENT = (\n (\"Places365_val_00000001.png\", 0),\n *((f\"{category}/Places365_train_00000001.png\", idx) for category, idx in CATEGORIES_CONTENT),\n )\n\n def mock_target(attr, partial=\"torchvision.datasets.places365.Places365\"):\n return f\"{partial}.{attr}\"\n\n def make_txt(root, name, seq):\n file = os.path.join(root, name)\n with open(file, \"w\") as fh:\n for string, idx in seq:\n fh.write(f\"{string} {idx}\\n\")\n return name, compute_md5(file)\n\n def make_categories_txt(root, name):\n return make_txt(root, name, CATEGORIES_CONTENT)\n\n def make_file_list_txt(root, name):\n return make_txt(root, name, FILE_LIST_CONTENT)\n\n def make_image(file, size):\n os.makedirs(os.path.dirname(file), exist_ok=True)\n PIL.Image.fromarray(np.zeros((*size, 3), dtype=np.uint8)).save(file)\n\n def make_devkit_archive(stack, root, split):\n archive = DEVKITS[split]\n files = []\n\n meta = make_categories_txt(root, CATEGORIES)\n mock_class_attribute(stack, mock_target(\"_CATEGORIES_META\"), meta)\n files.append(meta[0])\n\n meta = {split: make_file_list_txt(root, FILE_LISTS[split])}\n mock_class_attribute(stack, mock_target(\"_FILE_LIST_META\"), meta)\n files.extend([item[0] for item in meta.values()])\n\n meta = {VARIANTS[split]: make_tar(root, archive, *files)}\n mock_class_attribute(stack, mock_target(\"_DEVKIT_META\"), meta)\n\n def make_images_archive(stack, root, split, small):\n archive, folder_default, folder_renamed = IMAGES[(split, small)]\n\n image_size = (256, 256) if small else (512, random.randint(512, 1024))\n files, idcs = zip(*FILE_LIST_CONTENT)\n images = [file.lstrip(\"/\").replace(\"/\", os.sep) for file in files]\n for image in images:\n make_image(os.path.join(root, folder_default, image), image_size)\n\n meta = {(split, small): make_tar(root, archive, folder_default)}\n mock_class_attribute(stack, mock_target(\"_IMAGES_META\"), meta)\n\n return [(os.path.join(root, folder_renamed, image), idx) for image, idx in zip(images, idcs)]\n\n with contextlib.ExitStack() as stack, get_tmp_dir() as root:\n make_devkit_archive(stack, root, split)\n class_to_idx = dict(CATEGORIES_CONTENT)\n classes = list(class_to_idx.keys())\n\n data = {\"class_to_idx\": class_to_idx, \"classes\": classes}\n data[\"imgs\"] = make_images_archive(stack, root, split, small)\n\n clean_dir(root, \".tar$\")\n\n yield root, data\n"
] |
[
[
"torch.tensor",
"torch.randint",
"numpy.zeros",
"torch.zeros"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
MoisesHer/incubator-mxnet
|
[
"73d1b055d04a0f0f511a9cc2dd46ae2eb03a8628",
"73d1b055d04a0f0f511a9cc2dd46ae2eb03a8628"
] |
[
"tests/python/unittest/onnx/test_node.py",
"tests/python/gpu/test_operator_gpu.py"
] |
[
"# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"\nTests for individual operators\nThis module contains operator tests which currently do not exist on\nONNX backend test framework. Once we have PRs on the ONNX repo and get\nthose PRs merged, this file will get EOL'ed.\n\"\"\"\n# pylint: disable=too-many-locals,wrong-import-position,import-error\nfrom __future__ import absolute_import\nimport sys\nimport os\nimport unittest\nimport logging\nimport tarfile\nfrom collections import namedtuple\nimport numpy as np\nimport numpy.testing as npt\nfrom onnx import checker, numpy_helper, helper, load_model\nfrom onnx import TensorProto\nfrom mxnet.test_utils import download\nfrom mxnet.contrib import onnx as onnx_mxnet\nimport mxnet as mx\nimport backend\n\nCURR_PATH = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))\nsys.path.insert(0, os.path.join(CURR_PATH, '../../python/unittest'))\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.DEBUG)\n\n\ndef get_rnd(shape, low=-1.0, high=1.0, dtype=np.float32):\n if dtype == np.float32:\n return (np.random.uniform(low, high,\n np.prod(shape)).reshape(shape).astype(np.float32))\n elif dtype == np.int32:\n return (np.random.randint(low, high,\n np.prod(shape)).reshape(shape).astype(np.float32))\n elif dtype == np.bool_:\n return np.random.choice(a=[False, True], size=shape).astype(np.float32)\n\n\ndef _fix_attributes(attrs, attribute_mapping):\n new_attrs = attrs\n attr_modify = attribute_mapping.get('modify', {})\n for k, v in attr_modify.items():\n new_attrs[v] = new_attrs.pop(k, None)\n\n attr_add = attribute_mapping.get('add', {})\n for k, v in attr_add.items():\n new_attrs[k] = v\n\n attr_remove = attribute_mapping.get('remove', [])\n for k in attr_remove:\n if k in new_attrs:\n del new_attrs[k]\n\n return new_attrs\n\n\ndef forward_pass(sym, arg, aux, data_names, input_data):\n \"\"\" Perform forward pass on given data\n :param sym: Symbol\n :param arg: Arg params\n :param aux: Aux params\n :param data_names: Input names (list)\n :param input_data: Input data (list). If there is only one input,\n pass it as a list. For example, if input is [1, 2],\n pass input_data=[[1, 2]]\n :return: result of forward pass\n \"\"\"\n data_shapes = []\n data_forward = []\n for idx in range(len(data_names)):\n val = input_data[idx]\n data_shapes.append((data_names[idx], np.shape(val)))\n data_forward.append(mx.nd.array(val))\n # create module\n mod = mx.mod.Module(symbol=sym, data_names=data_names, context=mx.cpu(), label_names=None)\n mod.bind(for_training=False, data_shapes=data_shapes, label_shapes=None)\n if not arg and not aux:\n mod.init_params()\n else:\n mod.set_params(arg_params=arg, aux_params=aux,\n allow_missing=True, allow_extra=True)\n # run inference\n batch = namedtuple('Batch', ['data'])\n mod.forward(batch(data_forward), is_train=False)\n\n return mod.get_outputs()[0].asnumpy()\n\n\ndef get_input_tensors(input_data):\n input_tensor = []\n input_names = []\n input_sym = []\n for idx, ip in enumerate(input_data):\n name = \"input\" + str(idx + 1)\n input_sym.append(mx.sym.Variable(name))\n input_names.append(name)\n input_tensor.append(helper.make_tensor_value_info(name,\n TensorProto.FLOAT, shape=np.shape(ip)))\n return input_names, input_tensor, input_sym\n\n\ndef get_onnx_graph(testname, input_names, inputs, output_name, output_shape, attr):\n outputs = [helper.make_tensor_value_info(\"output\", TensorProto.FLOAT, shape=output_shape)]\n\n nodes = [helper.make_node(output_name, input_names, [\"output\"], **attr)]\n\n graph = helper.make_graph(nodes, testname, inputs, outputs)\n\n model = helper.make_model(graph)\n return model\n\nclass TestNode(unittest.TestCase):\n \"\"\" Tests for models.\n Tests are dynamically added.\n Therefore edit test_models to add more tests.\n \"\"\"\n def test_import_export(self):\n for test in test_cases:\n test_name, mxnet_op, onnx_name, inputs, attrs, mxnet_specific, fix_attrs, check_value, check_shape = test\n with self.subTest(test_name):\n names, input_tensors, inputsym = get_input_tensors(inputs)\n if inputs:\n test_op = mxnet_op(*inputsym, **attrs)\n mxnet_output = forward_pass(test_op, None, None, names, inputs)\n outputshape = np.shape(mxnet_output)\n else:\n test_op = mxnet_op(**attrs)\n shape = attrs.get('shape', (1,))\n x = mx.nd.zeros(shape, dtype='float32')\n xgrad = mx.nd.zeros(shape, dtype='float32')\n exe = test_op.bind(ctx=mx.cpu(), args={'x': x}, args_grad={'x': xgrad})\n mxnet_output = exe.forward(is_train=False)[0].asnumpy()\n outputshape = np.shape(mxnet_output)\n\n if mxnet_specific:\n onnxmodelfile = onnx_mxnet.export_model(test_op, {}, [np.shape(ip) for ip in inputs],\n np.float32,\n onnx_name + \".onnx\")\n onnxmodel = load_model(onnxmodelfile)\n else:\n onnx_attrs = _fix_attributes(attrs, fix_attrs)\n onnxmodel = get_onnx_graph(test_name, names, input_tensors, onnx_name, outputshape, onnx_attrs)\n\n bkd_rep = backend.prepare(onnxmodel, operation='export', backend='mxnet')\n output = bkd_rep.run(inputs)\n\n if check_value:\n npt.assert_almost_equal(output[0], mxnet_output)\n\n if check_shape:\n npt.assert_equal(output[0].shape, outputshape)\n\n input1 = get_rnd((1, 10, 2, 3))\n ipsym = mx.sym.Variable(\"input1\")\n for test in test_scalar_ops:\n if test == 'Add':\n outsym = 2 + ipsym\n if test == \"Sub\":\n outsym = ipsym - 2\n if test == \"rSub\":\n outsym = ipsym.__rsub__(2)\n if test == \"Mul\":\n outsym = 2 * ipsym\n if test == \"Div\":\n outsym = ipsym / 2\n if test == \"Pow\":\n outsym = ipsym ** 2\n forward_op = forward_pass(outsym, None, None, ['input1'], input1)\n converted_model = onnx_mxnet.export_model(outsym, {}, [np.shape(input1)], np.float32,\n onnx_file_path=outsym.name + \".onnx\")\n\n sym, arg_params, aux_params = onnx_mxnet.import_model(converted_model)\n result = forward_pass(sym, arg_params, aux_params, ['input1'], input1)\n\n npt.assert_almost_equal(result, forward_op)\n\n def test_imports(self):\n for bk in ['mxnet', 'gluon']:\n for test in import_test_cases:\n test_name, onnx_name, inputs, np_op, attrs = test\n with self.subTest(test_name):\n names, input_tensors, inputsym = get_input_tensors(inputs)\n np_out = [np_op(*inputs, **attrs)]\n output_shape = np.shape(np_out)\n onnx_model = get_onnx_graph(test_name, names, input_tensors, onnx_name, output_shape, attrs)\n bkd_rep = backend.prepare(onnx_model, operation='import', backend=bk)\n mxnet_out = bkd_rep.run(inputs)\n npt.assert_almost_equal(np_out, mxnet_out, decimal=4)\n\n def test_exports(self):\n input_shape = (2,1,3,1)\n for test in export_test_cases:\n test_name, onnx_name, mx_op, attrs = test\n input_sym = mx.sym.var('data')\n outsym = mx_op(input_sym, **attrs)\n converted_model = onnx_mxnet.export_model(outsym, {}, [input_shape], np.float32,\n onnx_file_path=outsym.name + \".onnx\")\n model = load_model(converted_model)\n checker.check_model(model)\n\n\n# test_case = (\"test_case_name\", mxnet op, \"ONNX_op_name\", [input_list], attribute map, MXNet_specific=True/False,\n# fix_attributes = {'modify': {mxnet_attr_name: onnx_attr_name},\n# 'remove': [attr_name],\n# 'add': {attr_name: value},\n# check_value=True/False, check_shape=True/False)\ntest_cases = [\n (\"test_equal\", mx.sym.broadcast_equal, \"Equal\", [get_rnd((1, 3, 4, 5)), get_rnd((1, 5))], {}, False, {}, True,\n False),\n (\"test_greater\", mx.sym.broadcast_greater, \"Greater\", [get_rnd((1, 3, 4, 5)), get_rnd((1, 5))], {}, False, {}, True,\n False),\n (\"test_less\", mx.sym.broadcast_lesser, \"Less\", [get_rnd((1, 3, 4, 5)), get_rnd((1, 5))], {}, False, {}, True,\n False),\n (\"test_and\", mx.sym.broadcast_logical_and, \"And\",\n [get_rnd((3, 4, 5), dtype=np.bool_), get_rnd((3, 4, 5), dtype=np.bool_)], {}, False, {}, True, False),\n (\"test_xor\", mx.sym.broadcast_logical_xor, \"Xor\",\n [get_rnd((3, 4, 5), dtype=np.bool_), get_rnd((3, 4, 5), dtype=np.bool_)], {}, False, {}, True, False),\n (\"test_or\", mx.sym.broadcast_logical_or, \"Or\",\n [get_rnd((3, 4, 5), dtype=np.bool_), get_rnd((3, 4, 5), dtype=np.bool_)], {}, False, {}, True, False),\n (\"test_not\", mx.sym.logical_not, \"Not\", [get_rnd((3, 4, 5), dtype=np.bool_)], {}, False, {}, True, False),\n (\"test_square\", mx.sym.square, \"Pow\", [get_rnd((2, 3), dtype=np.int32)], {}, True, {}, True, False),\n (\"test_spacetodepth\", mx.sym.space_to_depth, \"SpaceToDepth\", [get_rnd((1, 1, 4, 6))],\n {'block_size': 2}, False, {}, True, False),\n (\"test_softmax\", mx.sym.SoftmaxOutput, \"Softmax\", [get_rnd((1000, 1000)), get_rnd(1000)],\n {'ignore_label': 0, 'use_ignore': False}, True, {}, True, False),\n (\"test_logistic_regression\", mx.sym.LogisticRegressionOutput, \"Sigmoid\",\n [get_rnd((1000, 1000)), get_rnd((1000, 1000))], {}, True, {}, True, False),\n (\"test_fullyconnected\", mx.sym.FullyConnected, \"Gemm\", [get_rnd((4, 3)), get_rnd((4, 3)), get_rnd(4)],\n {'num_hidden': 4, 'name': 'FC'}, True, {}, True, False),\n (\"test_lppool1\", mx.sym.Pooling, \"LpPool\", [get_rnd((2, 3, 20, 20))],\n {'kernel': (4, 5), 'pad': (0, 0), 'stride': (1, 1), 'p_value': 1, 'pool_type': 'lp'}, False,\n {'modify': {'kernel': 'kernel_shape', 'pad': 'pads', 'stride': 'strides', 'p_value': 'p'},\n 'remove': ['pool_type']}, True, False),\n (\"test_lppool2\", mx.sym.Pooling, \"LpPool\", [get_rnd((2, 3, 20, 20))],\n {'kernel': (4, 5), 'pad': (0, 0), 'stride': (1, 1), 'p_value': 2, 'pool_type': 'lp'}, False,\n {'modify': {'kernel': 'kernel_shape', 'pad': 'pads', 'stride': 'strides', 'p_value': 'p'},\n 'remove': ['pool_type']}, True, False),\n (\"test_globallppool1\", mx.sym.Pooling, \"GlobalLpPool\", [get_rnd((2, 3, 20, 20))],\n {'kernel': (4, 5), 'pad': (0, 0), 'stride': (1, 1), 'p_value': 1, 'pool_type': 'lp', 'global_pool': True}, False,\n {'modify': {'p_value': 'p'},\n 'remove': ['pool_type', 'kernel', 'pad', 'stride', 'global_pool']}, True, False),\n (\"test_globallppool2\", mx.sym.Pooling, \"GlobalLpPool\", [get_rnd((2, 3, 20, 20))],\n {'kernel': (4, 5), 'pad': (0, 0), 'stride': (1, 1), 'p_value': 2, 'pool_type': 'lp', 'global_pool': True}, False,\n {'modify': {'p_value': 'p'},\n 'remove': ['pool_type', 'kernel', 'pad', 'stride', 'global_pool']}, True, False),\n (\"test_roipool\", mx.sym.ROIPooling, \"MaxRoiPool\",\n [[[get_rnd(shape=(8, 6), low=1, high=100, dtype=np.int32)]], [[0, 0, 0, 4, 4]]],\n {'pooled_size': (2, 2), 'spatial_scale': 0.7}, False,\n {'modify': {'pooled_size': 'pooled_shape'}}, True, False),\n\n # since results would be random, checking for shape alone\n (\"test_multinomial\", mx.sym.sample_multinomial, \"Multinomial\",\n [np.array([0, 0.1, 0.2, 0.3, 0.4]).astype(\"float32\")],\n {'shape': (10,)}, False, {'modify': {'shape': 'sample_size'}}, False, True),\n (\"test_random_normal\", mx.sym.random_normal, \"RandomNormal\", [],\n {'shape': (2, 2), 'loc': 0, 'scale': 1}, False, {'modify': {'loc': 'mean'}}, False, True),\n (\"test_random_uniform\", mx.sym.random_uniform, \"RandomUniform\", [],\n {'shape': (2, 2), 'low': 0.5, 'high': 1.0}, False, {}, False, True)\n]\n\ntest_scalar_ops = ['Add', 'Sub', 'rSub' 'Mul', 'Div', 'Pow']\n\n# test_case = (\"test_case_name\", \"ONNX_op_name\", [input_list], np_op, attribute map)\nimport_test_cases = [\n (\"test_lpnormalization_default\", \"LpNormalization\", [get_rnd([5, 3, 3, 2])], np.linalg.norm, {'ord':2, 'axis':-1}),\n (\"test_lpnormalization_ord1\", \"LpNormalization\", [get_rnd([5, 3, 3, 2])], np.linalg.norm, {'ord':1, 'axis':-1}),\n (\"test_lpnormalization_ord2\", \"LpNormalization\", [get_rnd([5, 3, 3, 2])], np.linalg.norm, {'ord':2, 'axis':1})\n]\n\n# test_case = (\"test_case_name\", \"ONNX_op_name\", mxnet_op, attribute map)\nexport_test_cases = [\n (\"test_expand\", \"Expand\", mx.sym.broadcast_to, {'shape': (2,1,3,1)}),\n (\"test_tile\", \"Tile\", mx.sym.tile, {'reps': (2,3)})\n]\n\nif __name__ == '__main__':\n unittest.main()\n",
"# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nfrom __future__ import print_function\nimport sys\nimport os\nimport time\nimport multiprocessing as mp\nimport mxnet as mx\nimport numpy as np\nimport unittest\nimport pytest\nfrom mxnet.test_utils import check_consistency, set_default_context, assert_almost_equal, assert_allclose\nfrom mxnet.base import MXNetError\nfrom mxnet import autograd\n\ncurr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))\nsys.path.insert(0, os.path.join(curr_path, '../unittest'))\nfrom common import setup_module, with_seed, teardown_module, assert_raises_cudnn_not_satisfied, assert_raises_cuda_not_satisfied\nfrom common import run_in_spawned_process\nfrom test_operator import *\nfrom test_numpy_ndarray import *\nfrom test_numpy_op import *\nfrom test_numpy_interoperability import *\nfrom test_optimizer import *\nfrom test_random import *\nfrom test_exc_handling import *\n#from test_rnn import *\nfrom test_sparse_ndarray import *\nfrom test_sparse_operator import *\nfrom test_ndarray import *\nfrom test_subgraph_op import *\nfrom test_gluon_gpu import _test_bulking\nfrom test_contrib_operator import test_multibox_target_op\nfrom test_contrib_optimizer import test_adamw\n\nset_default_context(mx.gpu(0))\ndel test_support_vector_machine_l1_svm # noqa\ndel test_support_vector_machine_l2_svm # noqa\ndel test_custom_op_fork #noqa\n\ndef check_countsketch(in_dim,out_dim,n):\n data = mx.sym.Variable(\"data\")\n h = mx.sym.Variable(\"h\")\n s = mx.sym.Variable(\"s\")\n sym = mx.sym.contrib.count_sketch(data=data, h=h, s=s, name='countsketch',out_dim = out_dim)\n shape = [(n,in_dim), (1,in_dim),(1,in_dim)] #shape of input x, hash h and hash s\n\n arr = [mx.nd.empty(shape[i]) for i in range(3)]\n arr_grad = [mx.nd.empty(shape[i]) for i in range(3)]\n x = np.random.uniform(-10, 10, shape[0])\n arr[0][:] = x #input x\n h = np.random.randint(0, out_dim, shape[1])\n arr[1][:] = h #hash h\n s = np.random.randint(0, 2, shape[2])*2-np.ones(shape[2])\n arr[2][:] = s #hash s\n locations = {\"data\": x, \"h\": h, \"s\": s}\n a = np.zeros((n,out_dim))\n temp = np.multiply(x, s)\n for num_sample in np.arange(0,n):\n for idx in np.arange(0,in_dim):\n a[num_sample][h[0][idx]] += temp[num_sample][idx]\n check_symbolic_forward(sym, locations, [a], rtol=1e-3, atol=1e-5, ctx=mx.gpu(0))\n out_grad = mx.nd.empty((n,out_dim))\n out_grad[:] = np.random.normal(-3, 3, (n,out_dim))\n a = np.zeros((n,in_dim))\n for j in np.arange(0,n):\n for i in np.arange(0,in_dim):\n a[j,i] = out_grad.asnumpy()[j, h[0,i]] * s[0,i]\n check_symbolic_backward(sym, locations, [out_grad], [a], rtol=1e-3, atol=1e-5, ctx=mx.gpu(0))\n\n\n@with_seed()\ndef test_countsketch():\n minindim = 40\n maxindim = 100\n minoutdim = 5\n maxoutdim = 30\n maxn = 200\n in_dim = np.random.randint(minindim, maxindim)\n out_dim = np.random.randint(minoutdim, maxoutdim)\n n = np.random.randint(1, maxn)\n check_countsketch(in_dim, out_dim, n)\n\n\ndef check_ifft(shape):\n shape_old = shape\n if len(shape) == 2:\n if shape[1]%2 != 0:\n lst = list(shape)\n lst[1] = lst[1]*2\n shape = tuple(lst)\n shape_old = shape\n shape = (shape[0],shape[1]*2)\n if len(shape) == 4:\n if shape[3]%2 != 0:\n lst = list(shape)\n lst[3] = lst[3]*2\n shape = tuple(lst)\n shape_old = shape\n shape = (shape[0],shape[1],shape[2],shape[3]*2)\n sym = mx.sym.contrib.ifft(name='ifft', compute_size = 128)\n init = [np.random.normal(size=shape, scale=1.0)]\n arr_grad = [mx.nd.empty(shape)]\n ctx_list = [{'ctx': mx.gpu(0),'ifft_data': shape, 'type_dict': {'ifft_data': np.float32}}]\n exe_list = [sym.simple_bind(args_grad=arr_grad,**ctx) for ctx in ctx_list]\n\n for exe in exe_list:\n for arr, iarr in zip(exe.arg_arrays, init):\n arr[:] = iarr.astype(arr.dtype)\n # forward\n for exe in exe_list:\n exe.forward(is_train= True)\n out1 = [exe.outputs[0].asnumpy() for exe in exe_list]\n\n if len(shape) == 2:\n init_complex = np.zeros(shape_old,dtype = np.complex64)\n for i in range(0,shape_old[1]):\n init_complex.real[:,i] = init[0][:,2*i]\n init_complex.imag[:,i] = init[0][:,2*i+1]\n a = np.fft.ifft(init_complex, n=None, axis=-1, norm=None)\n assert_almost_equal(a.real, out1[0]/shape_old[1],rtol=1e-3, atol=1e-5)\n\n if len(shape) == 4:\n init_complex = np.zeros(shape_old,dtype = np.complex64)\n for i in range(0,shape_old[3]):\n init_complex.real[:,:,:,i] = init[0][:,:,:,2*i]\n init_complex.imag[:,:,:,i] = init[0][:,:,:,2*i+1]\n a = np.fft.ifft(init_complex, n=None, axis=-1, norm=None)\n assert_almost_equal(a.real, out1[0]/shape_old[3],rtol=1e-3, atol=1e-5)\n # backward\n if len(shape) == 2:\n out_grad = mx.nd.empty(shape_old)\n out_grad[:] = np.random.normal(-3, 3, shape_old)\n for exe in exe_list:\n exe.backward([out_grad])\n temp = exe.grad_arrays[0].asnumpy()\n temp = np.zeros(shape_old)\n for i in range(shape_old[1]):\n temp[:,i] = exe.grad_arrays[0].asnumpy()[:,2*i]\n\n a = np.fft.fft(out_grad.asnumpy(), n=None, axis=-1, norm=None)\n assert_almost_equal(a.real, temp, rtol=1e-3, atol=1e-5)\n if len(shape) == 4:\n out_grad = mx.nd.empty(shape_old)\n out_grad[:] = np.random.normal(-3, 3, shape_old)\n for exe in exe_list:\n exe.backward([out_grad])\n temp = exe.grad_arrays[0].asnumpy()\n temp = np.zeros(shape_old)\n for i in range(shape_old[3]):\n temp[:,:,:,i] = exe.grad_arrays[0].asnumpy()[:,:,:,2*i]\n\n a = np.fft.fft(out_grad.asnumpy(), n=None, axis=-1, norm=None)\n assert_almost_equal(a.real, temp, rtol=1e-3, atol=1e-5)\n\n@with_seed()\ndef test_ifft():\n nrepeat = 2\n maxdim = 10\n for repeat in range(nrepeat):\n for order in [2,4]:\n shape = tuple(np.random.randint(1, maxdim, size=order))\n check_ifft(shape)\n\n\ndef check_fft(shape):\n sym = mx.sym.contrib.fft(name='fft', compute_size = 128)\n if len(shape) == 2:\n if shape[1]%2 != 0:\n lst = list(shape)\n lst[1] = lst[1]*2\n shape = tuple(lst)\n shape_old = shape\n if len(shape) == 4:\n if shape[3]%2 != 0:\n lst = list(shape)\n lst[3] = lst[3]*2\n shape = tuple(lst)\n shape_old = shape\n init = [np.random.normal(size=shape, scale=1.0)]\n arr_grad = [mx.nd.empty(shape)]\n ctx_list = [{'ctx': mx.gpu(0),'fft_data': shape, 'type_dict': {'fft_data': np.float32}}]\n exe_list = [sym.simple_bind(args_grad=arr_grad,**ctx) for ctx in ctx_list]\n\n for exe in exe_list:\n for arr, iarr in zip(exe.arg_arrays, init):\n arr[:] = iarr.astype(arr.dtype)\n # forward\n for exe in exe_list:\n exe.forward(is_train=True)\n out1 = [exe.outputs[0].asnumpy() for exe in exe_list]\n out = np.fft.fft(init, n=None, axis=-1, norm=None)\n if len(shape) == 2:\n out = np.reshape(out,(out.shape[1],out.shape[2]))\n out2 = np.append(out.real, out.imag, axis = 1)\n a = np.zeros(out1[0].shape)\n p = 0\n for i in range(out2.shape[1]//2):\n a[:,p] = out2[:,i]\n a[:,p+1] = out2[:,i+out2.shape[1]//2]\n p = p+2\n\n if len(shape) == 4:\n out = np.reshape(out,(out.shape[1],out.shape[2],out.shape[3],out.shape[4]))\n out2 = np.append(out.real, out.imag, axis = 1)\n a = np.zeros(out1[0].shape)\n for i in range(out1[0].shape[0]):\n for j in range(out1[0].shape[1]):\n p = 0\n for k in range(out2.shape[3]):\n a[i,j,:,p] = out2[i,j,:,k]\n a[i,j,:,p+1] = out2[i,j+out1[0].shape[1],:,k]\n p = p+2\n\n assert_almost_equal(a, out1[0], rtol=1e-3, atol=1e-5)\n\n # backward\n if len(shape) == 2:\n out_grad = mx.nd.empty((shape[0],2*shape[1]))\n out_grad[:] = np.random.normal(-3, 3, (shape[0],2*shape[1]))\n # out_grad_to_complex\n out_grad_complex = np.zeros(shape,dtype = np.complex64)\n for i in range(0,shape[1]):\n out_grad_complex.real[:,i] = out_grad.asnumpy()[:,2*i]\n out_grad_complex.imag[:,i] = out_grad.asnumpy()[:,2*i+1]\n for exe in exe_list:\n exe.backward([out_grad])\n a = np.fft.ifft(out_grad_complex, n=None, axis=-1, norm=None)\n assert_almost_equal(a.real, exe.grad_arrays[0]/shape[1],rtol=1e-3, atol=1e-5)\n\n if len(shape) == 4:\n out_grad = mx.nd.empty(out1[0].shape)\n out_grad[:] = np.random.normal(-3, 3, out1[0].shape)\n # out_grad_to_complex\n out_grad_complex = np.zeros(shape,dtype = np.complex64)\n for i in range(0,shape[3]):\n out_grad_complex.real[:,:,:,i] = out_grad.asnumpy()[:,:,:,2*i]\n out_grad_complex.imag[:,:,:,i] = out_grad.asnumpy()[:,:,:,2*i+1]\n for exe in exe_list:\n exe.backward([out_grad])\n a = np.fft.ifft(out_grad_complex, n=None, axis=-1, norm=None)\n assert_almost_equal(a.real, exe.grad_arrays[0]/shape[3],rtol=1e-3, atol=1e-5)\n\n@with_seed()\ndef test_fft():\n nrepeat = 2\n maxdim = 10\n for repeat in range(nrepeat):\n for order in [2,4]:\n shape = tuple(np.random.randint(1, maxdim, size=order))\n check_fft(shape)\n\ndef _make_ndarrays(input_list, ctx=mx.gpu(0)):\n return [mx.nd.array(arr, dtype=arr.dtype, ctx=ctx) for arr in input_list]\n\ndef check_multi_sum_sq(dtype, shapes, ctx, tol1, tol2):\n values_arr = [np.random.rand(*shape).astype(dtype) * 10. for shape in shapes]\n mx_vals = _make_ndarrays(values_arr, ctx=ctx)\n sum_sq = mx.nd.multi_sum_sq(*mx_vals, num_arrays=len(shapes))\n sum_sq2 = mx.nd.multi_sum_sq(*mx_vals, num_arrays=len(shapes))\n # checks that operator is deterministic\n assert np.array_equal(sum_sq.asnumpy(), sum_sq2.asnumpy())\n\n ref_sum_sq = mx.nd.array([(v.astype('float32') ** 2).sum() for v in values_arr],\n dtype='float32', ctx=ctx)\n assert_almost_equal(ref_sum_sq.asnumpy(), sum_sq.asnumpy(), atol=tol1, rtol=tol1)\n\n@with_seed()\ndef test_multi_sum_sq():\n min_nparam = 100\n max_nparam = 120\n min_dim = 50000\n max_dim = 100000\n max_ndim = 1\n\n dtypes = ['float16','float32', 'float64']\n for ctx in [mx.gpu(0)]:\n for dtype in dtypes:\n nparam = np.random.randint(min_nparam + 1, max_nparam + 1)\n shapes = [np.random.randint(min_dim, max_dim + 1, size=max_ndim) for i in range(nparam)]\n low_tol = ctx == mx.cpu(0) and ('float16'in [dtype])\n tol1 = 1e-3 if low_tol else 1e-5\n tol2 = 1e-6 if low_tol else 1e-7\n check_multi_sum_sq(dtype, shapes, ctx, tol1, tol2)\n\ndef check_fast_lars(w_dtype, g_dtype, shapes, ctx, tol1, tol2):\n weights_arr = [np.random.rand(*shape).astype(w_dtype) * 10. for shape in shapes]\n grads_arr = [np.random.rand(*shape).astype(g_dtype) for shape in shapes]\n\n lrs = (np.random.rand(len(shapes)).astype('float32') + 0.1) / 100.\n wds = (np.random.rand(len(shapes)).astype('float32') + 0.1) / 1000.\n eta = (np.random.rand() + 0.1)\n eps = (np.random.rand() + 0.1) / 10000.\n\n mx_w = _make_ndarrays(weights_arr, ctx=ctx)\n mx_g = _make_ndarrays(grads_arr, ctx=ctx)\n mx_lrs = mx.nd.array(lrs, dtype='float32', ctx=ctx)\n mx_wds = mx.nd.array(wds, dtype='float32', ctx=ctx)\n\n w_sum_sq = mx.nd.multi_sum_sq(*mx_w, num_arrays=len(shapes))\n g_sum_sq = mx.nd.multi_sum_sq(*mx_g, num_arrays=len(shapes))\n\n ref_w_sum_sq = mx.nd.array([(w.astype('float32') ** 2).sum() for w in weights_arr],\n dtype='float32', ctx=ctx)\n ref_g_sum_sq = mx.nd.array([(g.astype('float32') ** 2).sum() for g in grads_arr],\n dtype='float32', ctx=ctx)\n assert_almost_equal(ref_w_sum_sq.asnumpy(), w_sum_sq.asnumpy(), atol=tol1, rtol=tol1)\n assert_almost_equal(ref_g_sum_sq.asnumpy(), g_sum_sq.asnumpy(), atol=tol1, rtol=tol1)\n\n rescale_grad = (np.random.rand() + 0.5) * 100.\n mx_new_lrs = mx.nd.multi_lars(mx_lrs, w_sum_sq, g_sum_sq, mx_wds, eta=eta, eps=eps,\n rescale_grad=rescale_grad)\n ref_w_l2norm = mx.nd.sqrt(ref_w_sum_sq)\n ref_g_l2norm = mx.nd.sqrt(ref_g_sum_sq * rescale_grad * rescale_grad)\n ref_new_lrs = mx.nd.zeros(ref_w_l2norm.shape, dtype='float32', ctx=ctx)\n for i in range(ref_w_l2norm.size):\n _w = ref_w_l2norm[i]\n _g = ref_g_l2norm[i]\n if _w > 0.0 and _g > 0.0:\n ref_new_lrs[i] = lrs[i] * eta * _w / (_g + wds[i] * _w + eps)\n else:\n ref_new_lrs[i] = lrs[i]\n assert_almost_equal(ref_new_lrs.asnumpy(), mx_new_lrs.asnumpy(), atol=tol2, rtol=tol2)\n\n@with_seed()\ndef test_fast_lars():\n min_nparam = 50\n max_nparam = 60\n maxdim = 10000\n maxndim = 1\n\n dtypes = ['float16','float32', 'float64']\n for ctx in [mx.cpu(0), mx.gpu(0)]:\n for w_dtype in dtypes:\n for g_dtype in dtypes:\n nparam = np.random.randint(min_nparam + 1, max_nparam + 1)\n shapes = [np.random.randint(1, maxdim + 1, size=maxndim) for i in range(nparam)]\n lowTol = ctx == mx.cpu(0) and ('float16'in [w_dtype, g_dtype])\n tol1 = 1e-3 if lowTol else 1e-5\n tol2 = 1e-6 if lowTol else 1e-7\n check_fast_lars(w_dtype, g_dtype, shapes, ctx, tol1, tol2)\n\ndef check_preloaded_multi_sgd(dtype, shapes, momentum, use_master_weights):\n def _flatten_list(nested_list):\n return [item for sublist in nested_list for item in sublist]\n weights_arr = [np.random.rand(*shape).astype(dtype) * 100. for shape in shapes]\n grads_arr = [np.random.rand(*shape).astype(dtype) * 100. for shape in shapes]\n rescale_grad = (np.random.random() + 1.0)\n mx_w = _make_ndarrays(weights_arr)\n mx_g = _make_ndarrays(grads_arr)\n mx_p_w = _make_ndarrays(weights_arr)\n mx_p_g = _make_ndarrays(grads_arr)\n lrs = list((np.random.random(size=len(shapes)).astype('float32') + 0.1) / 100.)\n mx_lrs = mx.nd.array(lrs, dtype='float32', ctx=mx.gpu(0))\n wds = list((np.random.random(size=len(shapes)).astype('float32') + 0.1) / 1000.)\n mx_wds = mx.nd.array(wds, dtype='float32', ctx=mx.gpu(0))\n if use_master_weights:\n weights32_arr = [arr.astype('float32') for arr in weights_arr]\n mx_w32 = _make_ndarrays(weights32_arr)\n mx_p_w32 = _make_ndarrays(weights32_arr)\n if momentum is None:\n if use_master_weights:\n mx.nd.multi_mp_sgd_update(\n *_flatten_list(zip(mx_w, mx_g, mx_w32)),\n num_weights=len(shapes), lrs=lrs, wds=wds,\n rescale_grad=rescale_grad, out=mx_w)\n mx.nd.preloaded_multi_mp_sgd_update(\n *(_flatten_list(zip(mx_p_w, mx_p_g, mx_p_w32)) +\n [mx_lrs, mx_wds]), num_weights=len(shapes),\n rescale_grad=rescale_grad, out=mx_p_w)\n else:\n out = mx.nd.multi_sgd_update(\n *_flatten_list(zip(mx_w, mx_g)),\n num_weights=len(shapes), lrs=lrs, wds=wds,\n rescale_grad=rescale_grad, out=mx_w)\n preloaded_out = mx.nd.preloaded_multi_sgd_update(\n *(_flatten_list(zip(mx_p_w, mx_p_g)) +\n [mx_lrs, mx_wds]), num_weights=len(shapes),\n rescale_grad=rescale_grad, out=mx_p_w)\n else:\n if use_master_weights:\n momentums_arr = [np.random.rand(*shape).astype(\"float32\") for shape in shapes]\n mx_m = _make_ndarrays(momentums_arr)\n mx_p_m = _make_ndarrays(momentums_arr)\n out = mx.nd.multi_mp_sgd_mom_update(\n *_flatten_list(zip(mx_w, mx_g, mx_m, mx_w32)),\n num_weights=len(shapes), lrs=lrs, wds=wds,\n rescale_grad=0.95, momentum=momentum, out=mx_w)\n preloaded_out = mx.nd.preloaded_multi_mp_sgd_mom_update(\n *(_flatten_list(zip(mx_p_w, mx_p_g, mx_p_m, mx_p_w32)) +\n [mx_lrs, mx_wds]), num_weights=len(shapes),\n rescale_grad=0.95, momentum=momentum, out=mx_p_w)\n else:\n momentums_arr = [np.random.rand(*shape).astype(dtype) for shape in shapes]\n mx_m = _make_ndarrays(momentums_arr)\n mx_p_m = _make_ndarrays(momentums_arr)\n mx.nd.multi_sgd_mom_update(\n *_flatten_list(zip(mx_w, mx_g, mx_m)),\n num_weights=len(shapes), lrs=lrs, wds=wds,\n rescale_grad=0.95, momentum=momentum, out=mx_w)\n mx.nd.preloaded_multi_sgd_mom_update(\n *(_flatten_list(zip(mx_p_w, mx_p_g, mx_p_m)) +\n [mx_lrs, mx_wds]), num_weights=len(shapes),\n rescale_grad=0.95, momentum=momentum, out=mx_p_w)\n\n def _assert_all_almost_equal(lhs_list, rhs_list, rtol, atol):\n for i, (lhs, rhs) in enumerate(zip(lhs_list, rhs_list)):\n assert_almost_equal(lhs.asnumpy(), rhs.asnumpy(), rtol=rtol, atol=atol)\n if dtype == 'float16':\n rtol = 1e-3\n atol = 1e-2\n else:\n rtol = 1e-5\n atol = 1e-6\n _assert_all_almost_equal(mx_p_w, mx_w, rtol, atol)\n if momentum is not None:\n _assert_all_almost_equal(mx_p_m, mx_m, rtol, atol)\n if use_master_weights:\n _assert_all_almost_equal(mx_p_w32, mx_w32, 1e-5, 1e-6)\n\n@with_seed()\ndef test_preloaded_multi_sgd():\n dtypes = ['float16', 'float32']\n momentums = [None, 0.9]\n min_nparam = 5\n max_nparam = 10\n maxdim = 6\n maxndim = 4\n for dtype in dtypes:\n use_master_weights_list = [False,] if dtype == 'float32' else [True, False]\n for use_master_weights in use_master_weights_list:\n for momentum in momentums:\n nparam = np.random.randint(min_nparam + 1, max_nparam + 1)\n shapes = [np.random.randint(1, maxdim + 1, size=maxndim) for i in range(nparam)]\n check_preloaded_multi_sgd(dtype, shapes, momentum, use_master_weights)\n\n\n@with_seed()\ndef test_batchnorm_with_type():\n ctx_list_v1_2D = [\n {'ctx': mx.cpu(0), 'norm_data': (10, 2, 10, 10), 'type_dict': {'norm_data': np.float32}},\n {'ctx': mx.gpu(0), 'norm_data': (10, 2, 10, 10), 'type_dict': {'norm_data': np.float32}},\n ]\n\n ctx_list_v2_2D = [\n {'ctx': mx.cpu(0), 'norm_data': (5, 2, 5, 5), 'type_dict': {'norm_data': np.float32}},\n {'ctx': mx.cpu(0), 'norm_data': (5, 2, 5, 5), 'type_dict': {'norm_data': np.float16}},\n {'ctx': mx.cpu(0), 'norm_data': (5, 2, 5, 5), 'type_dict': {'norm_data': np.float64}},\n {'ctx': mx.gpu(0), 'norm_data': (5, 2, 5, 5), 'type_dict': {'norm_data': np.float32}},\n {'ctx': mx.gpu(0), 'norm_data': (5, 2, 5, 5), 'type_dict': {'norm_data': np.float16}},\n {'ctx': mx.gpu(0), 'norm_data': (5, 2, 5, 5), 'type_dict': {'norm_data': np.float64}},\n ]\n\n ctx_list_v2_1D = [\n {'ctx': mx.cpu(0), 'norm_data': (5, 2, 5), 'type_dict': {'norm_data': np.float16}},\n {'ctx': mx.cpu(0), 'norm_data': (5, 2, 5), 'type_dict': {'norm_data': np.float32}},\n {'ctx': mx.cpu(0), 'norm_data': (5, 2, 5), 'type_dict': {'norm_data': np.float64}},\n {'ctx': mx.gpu(0), 'norm_data': (5, 2, 5), 'type_dict': {'norm_data': np.float16}},\n {'ctx': mx.gpu(0), 'norm_data': (5, 2, 5), 'type_dict': {'norm_data': np.float32}},\n {'ctx': mx.gpu(0), 'norm_data': (5, 2, 5), 'type_dict': {'norm_data': np.float64}},\n ]\n\n ctx_list_v2_3D = [\n {'ctx': mx.cpu(0), 'norm_data': (3, 2, 3, 2, 3), 'type_dict': {'norm_data': np.float16}},\n {'ctx': mx.cpu(0), 'norm_data': (3, 2, 3, 2, 3), 'type_dict': {'norm_data': np.float32}},\n {'ctx': mx.cpu(0), 'norm_data': (3, 2, 3, 2, 3), 'type_dict': {'norm_data': np.float64}},\n {'ctx': mx.gpu(0), 'norm_data': (3, 2, 3, 2, 3), 'type_dict': {'norm_data': np.float16}},\n {'ctx': mx.gpu(0), 'norm_data': (3, 2, 3, 2, 3), 'type_dict': {'norm_data': np.float32}},\n {'ctx': mx.gpu(0), 'norm_data': (3, 2, 3, 2, 3), 'type_dict': {'norm_data': np.float64}}\n ]\n\n # V1, 2D\n sym = mx.sym.BatchNorm_v1(name='norm', fix_gamma=False)\n check_consistency(sym, ctx_list_v1_2D)\n sym = mx.sym.BatchNorm_v1(name='norm', fix_gamma=True)\n check_consistency(sym, ctx_list_v1_2D)\n\n\n # V2, 2D\n sym = mx.sym.BatchNorm(name='norm', fix_gamma=False, cudnn_off=True)\n check_consistency(sym, ctx_list_v2_2D)\n sym = mx.sym.BatchNorm(name='norm', fix_gamma=False, cudnn_off=True)\n check_consistency(sym, ctx_list_v2_2D)\n sym = mx.sym.BatchNorm(name='norm', fix_gamma=True, cudnn_off=True)\n check_consistency(sym, ctx_list_v2_2D)\n sym = mx.sym.BatchNorm(name='norm', fix_gamma=True, cudnn_off=True)\n check_consistency(sym, ctx_list_v2_2D)\n\n # V2, 1D\n sym = mx.sym.BatchNorm(name='norm', fix_gamma=False, cudnn_off=True)\n check_consistency(sym, ctx_list_v2_1D)\n sym = mx.sym.BatchNorm(name='norm', fix_gamma=False, cudnn_off=True)\n check_consistency(sym, ctx_list_v2_1D)\n sym = mx.sym.BatchNorm(name='norm', fix_gamma=True, cudnn_off=True)\n check_consistency(sym, ctx_list_v2_1D)\n sym = mx.sym.BatchNorm(name='norm', fix_gamma=True, cudnn_off=True)\n check_consistency(sym, ctx_list_v2_1D)\n #\n # # V2, 3D\n sym = mx.sym.BatchNorm(name='norm', fix_gamma=False, cudnn_off=True)\n check_consistency(sym, ctx_list_v2_3D)\n sym = mx.sym.BatchNorm(name='norm', fix_gamma=True, cudnn_off=True)\n check_consistency(sym, ctx_list_v2_3D)\n\n\n@with_seed()\ndef test_batchnorm_versions():\n def test_batchnorm_versions_helper(batchnorm_op_list, data, fix_gamma, use_global_stats):\n ctx_list = []\n sym_list = []\n # BatchNormV1 cpu\n if 'batchnorm_v1_cpu' in batchnorm_op_list:\n ctx_list.append({'ctx': mx.cpu(0), 'batchnorm_data': data, 'type_dict': {'batchnorm_data': np.float32}})\n sym_list.append(mx.sym.BatchNorm_v1(fix_gamma=fix_gamma,\n use_global_stats=use_global_stats,\n name='batchnorm'))\n\n # BatchNormV1 gpu (organic)\n if 'batchnorm_v1_gpu' in batchnorm_op_list:\n ctx_list.append({'ctx': mx.gpu(0), 'batchnorm_data': data, 'type_dict': {'batchnorm_data': np.float32}})\n sym_list.append(mx.sym.BatchNorm_v1(fix_gamma=fix_gamma,\n use_global_stats=use_global_stats,\n name='batchnorm'))\n\n # BatchNorm cpu\n if 'batchnorm_cpu' in batchnorm_op_list:\n ctx_list.append({'ctx': mx.cpu(0), 'batchnorm_data': data, 'type_dict': {'batchnorm_data': np.float32}})\n sym_list.append(mx.sym.BatchNorm(fix_gamma=fix_gamma,\n use_global_stats=use_global_stats,\n name='batchnorm'))\n\n # BatchNorm gpu (organic)\n if 'batchnorm_gpu' in batchnorm_op_list:\n ctx_list.append({'ctx': mx.gpu(0), 'batchnorm_data': data, 'type_dict': {'batchnorm_data': np.float32}})\n sym_list.append(mx.sym.BatchNorm(fix_gamma=fix_gamma,\n use_global_stats=use_global_stats,\n name='batchnorm', cudnn_off=True))\n\n # BatchNorm gpu cudnn (if cudnn is enabled)\n if 'batchnorm_cudnn' in batchnorm_op_list:\n ctx_list.append({'ctx': mx.gpu(0), 'batchnorm_data': data, 'type_dict': {'batchnorm_data': np.float32}})\n sym_list.append(mx.sym.BatchNorm(fix_gamma=fix_gamma,\n use_global_stats=use_global_stats,\n name='batchnorm', cudnn_off=False))\n\n check_consistency(sym_list, ctx_list)\n\n def test_1d_batchnorm(fix_gamma, use_global_stats):\n data = (2, 3, 20)\n test_batchnorm_versions_helper(batchnorm_op_list=['batchnorm_cpu',\n 'batchnorm_gpu', 'batchnorm_cudnn'],\n data=data,\n fix_gamma=fix_gamma, use_global_stats=use_global_stats)\n\n def test_2d_batchnorm(fix_gamma, use_global_stats):\n data = (2, 3, 10, 10)\n test_batchnorm_versions_helper(batchnorm_op_list=['batchnorm_v1_cpu', 'batchnorm_v1_gpu',\n 'batchnorm_cpu',\n 'batchnorm_gpu', 'batchnorm_cudnn'],\n data=data,\n fix_gamma=fix_gamma, use_global_stats=use_global_stats)\n\n def test_3d_batchnorm(fix_gamma, use_global_stats):\n data = (2, 3, 3, 5, 5)\n test_batchnorm_versions_helper(batchnorm_op_list=['batchnorm_cpu',\n 'batchnorm_gpu'],\n data=data,\n fix_gamma=fix_gamma, use_global_stats=use_global_stats)\n\n test_1d_batchnorm(True, False)\n test_1d_batchnorm(False, False)\n test_1d_batchnorm(False, True)\n test_1d_batchnorm(True, True)\n\n test_2d_batchnorm(True, False)\n test_2d_batchnorm(False, False)\n test_2d_batchnorm(False, True)\n test_2d_batchnorm(True, True)\n\n test_3d_batchnorm(True, False)\n test_3d_batchnorm(False, False)\n test_3d_batchnorm(False, True)\n test_3d_batchnorm(True, True)\n\n\n@with_seed(1234)\n@assert_raises_cudnn_not_satisfied(min_version='5.1.10')\ndef test_convolution_with_type():\n sym1 = mx.sym.Convolution(num_filter=3, kernel=(3,3), name='conv')\n\n data = mx.sym.Variable('conv_data')\n w = mx.sym.Variable('conv_weight')\n b = mx.sym.Variable('conv_bias')\n w = mx.sym.transpose(w, axes=(0,2,3,1))\n sym2 = mx.sym.transpose(data, axes=(0,2,3,1))\n sym2 = mx.sym.Convolution(sym2, w, b, layout='NHWC', num_filter=3, kernel=(3,3))\n sym2 = mx.sym.transpose(sym2, axes=(0,3,1,2), name='conv')\n\n sym = [sym1, sym1, sym1, sym1, sym1, sym2, sym2]\n ctx_list = [{'ctx': mx.gpu(0), 'conv_data': (2, 2, 10, 10), 'type_dict': {'conv_data': np.float64}},\n {'ctx': mx.gpu(0), 'conv_data': (2, 2, 10, 10), 'type_dict': {'conv_data': np.float32}},\n {'ctx': mx.gpu(0), 'conv_data': (2, 2, 10, 10), 'type_dict': {'conv_data': np.float16}},\n {'ctx': mx.cpu(0), 'conv_data': (2, 2, 10, 10), 'type_dict': {'conv_data': np.float64}},\n {'ctx': mx.cpu(0), 'conv_data': (2, 2, 10, 10), 'type_dict': {'conv_data': np.float32}},\n # NHWC\n {'ctx': mx.gpu(0), 'conv_data': (2, 2, 10, 10), 'conv_weight': (3, 2, 3, 3),\n 'type_dict': {'conv_data': np.float32, 'conv_weight': np.float32}},\n {'ctx': mx.gpu(0), 'conv_data': (2, 2, 10, 10), 'conv_weight': (3, 2, 3, 3),\n 'type_dict': {'conv_data': np.float16, 'conv_weight': np.float16}}\n ]\n # wider tolerance needed for true-fp16 NCHW test above\n tol = {np.dtype(np.float16): 0.5,\n np.dtype(np.float32): 1e-3,\n np.dtype(np.float64): 1e-5,\n np.dtype(np.uint8): 0,\n np.dtype(np.int32): 0}\n check_consistency(sym, ctx_list, tol=tol)\n # test ability to turn off training on bias\n check_consistency(sym, ctx_list, grad_req={'conv_data': 'write', 'conv_weight': 'write', 'conv_bias': 'null'}, tol=tol)\n\n\n# Apply N symbols against each of M contexts, checking that all NxM combinations match.\ndef check_consistency_NxM(sym_list, ctx_list):\n # e.g. if sym_list=[sym1, sym2] and ctx_list=[ctx1, ctx2, ctx3], then resulting lists are:\n # sym_list=[sym1, sym1, sym1, sym2, sym2, sym2] and ctx_list=[ctx1, ctx2, ctx3, ctx1, ctx2, ctx3]\n check_consistency(np.repeat(sym_list, len(ctx_list)), ctx_list * len(sym_list), scale=0.5)\n\n\[email protected](\"test fails intermittently. temporarily disabled till it gets fixed. tracked at https://github.com/apache/incubator-mxnet/issues/10141\")\n@with_seed()\ndef test_convolution_options():\n # 1D convolution\n ctx_list = [{'ctx': mx.gpu(0), 'conv_data': (2, 2, 7), 'type_dict': {'conv_data': np.float64}},\n {'ctx': mx.gpu(0), 'conv_data': (2, 2, 7), 'type_dict': {'conv_data': np.float32}},\n {'ctx': mx.gpu(0), 'conv_data': (2, 2, 7), 'type_dict': {'conv_data': np.float16}},\n {'ctx': mx.cpu(0), 'conv_data': (2, 2, 7), 'type_dict': {'conv_data': np.float64}},\n {'ctx': mx.cpu(0), 'conv_data': (2, 2, 7), 'type_dict': {'conv_data': np.float32}}]\n # Pad > 0\n sym = mx.sym.Convolution(layout='NCW', num_filter=3, kernel=(3,), pad=(1,), name='conv')\n sym_no_cudnn = mx.sym.Convolution(num_filter=3, kernel=(3,), pad=(1,), cudnn_off=True, name='conv')\n check_consistency_NxM([sym, sym_no_cudnn], ctx_list)\n # Stride > 1\n sym = mx.sym.Convolution(layout='NCW', num_filter=3, kernel=(3,), stride=(2,), name='conv')\n sym_no_cudnn = mx.sym.Convolution(num_filter=3, kernel=(3,), stride=(2,), cudnn_off=True, name='conv')\n check_consistency_NxM([sym, sym_no_cudnn], ctx_list)\n # Dilate > 1\n sym = mx.sym.Convolution(layout='NCW', num_filter=3, kernel=(3,), dilate=(2,), name='conv')\n sym_no_cudnn = mx.sym.Convolution(num_filter=3, kernel=(3,), dilate=(2,), cudnn_off=True, name='conv')\n check_consistency_NxM([sym, sym_no_cudnn], ctx_list)\n # 1x1 convolution\n sym = mx.sym.Convolution(layout='NCW', num_filter=3, kernel=(1,), pad=(0,), name='conv')\n sym_no_cudnn = mx.sym.Convolution(num_filter=3, kernel=(1,), pad=(0,), cudnn_off=True, name='conv')\n check_consistency_NxM([sym, sym_no_cudnn], ctx_list)\n\n # 2D convolution\n ctx_list = [{'ctx': mx.gpu(0), 'conv_data': (2, 2, 7, 7), 'type_dict': {'conv_data': np.float64}},\n {'ctx': mx.gpu(0), 'conv_data': (2, 2, 7, 7), 'type_dict': {'conv_data': np.float32}},\n {'ctx': mx.gpu(0), 'conv_data': (2, 2, 7, 7), 'type_dict': {'conv_data': np.float16}},\n {'ctx': mx.cpu(0), 'conv_data': (2, 2, 7, 7), 'type_dict': {'conv_data': np.float64}},\n {'ctx': mx.cpu(0), 'conv_data': (2, 2, 7, 7), 'type_dict': {'conv_data': np.float32}}]\n # Pad > 0\n sym = mx.sym.Convolution(num_filter=3, kernel=(3,3), pad=(1,1), name='conv')\n sym_no_cudnn = mx.sym.Convolution(num_filter=3, kernel=(3,3), pad=(1,1), cudnn_off=True, name='conv')\n check_consistency_NxM([sym, sym_no_cudnn], ctx_list)\n # Stride > 1\n sym = mx.sym.Convolution(num_filter=3, kernel=(3,3), stride=(2,2), name='conv')\n sym_no_cudnn = mx.sym.Convolution(num_filter=3, kernel=(3,3), stride=(2,2), cudnn_off=True, name='conv')\n check_consistency_NxM([sym, sym_no_cudnn], ctx_list)\n # Dilate > 1\n sym = mx.sym.Convolution(num_filter=3, kernel=(3,3), dilate=(2,2), name='conv')\n sym_no_cudnn = mx.sym.Convolution(num_filter=3, kernel=(3,3), dilate=(2,2), cudnn_off=True, name='conv')\n check_consistency_NxM([sym, sym_no_cudnn], ctx_list)\n # 1x1 convolution\n sym = mx.sym.Convolution(num_filter=3, kernel=(1,1), pad=(0,0), name='conv')\n sym_no_cudnn = mx.sym.Convolution(num_filter=3, kernel=(1,1), pad=(0,0), cudnn_off=True, name='conv')\n check_consistency_NxM([sym, sym_no_cudnn], ctx_list)\n\n # 3D convolution\n ctx_list = [{'ctx': mx.cpu(0), 'conv_data': (2, 2, 5, 7, 7), 'type_dict': {'conv_data': np.float64}},\n {'ctx': mx.cpu(0), 'conv_data': (2, 2, 5, 7, 7), 'type_dict': {'conv_data': np.float64}},\n {'ctx': mx.gpu(0), 'conv_data': (2, 2, 5, 7, 7), 'type_dict': {'conv_data': np.float64}},\n {'ctx': mx.gpu(0), 'conv_data': (2, 2, 5, 7, 7), 'type_dict': {'conv_data': np.float32}}]\n # Pad > 0\n sym = mx.sym.Convolution(num_filter=3, kernel=(2,3,3), pad=(1,1,1), name='conv')\n sym_no_cudnn = mx.sym.Convolution(num_filter=3, kernel=(2,3,3), pad=(1,1,1), cudnn_off=True, name='conv')\n check_consistency_NxM([sym, sym_no_cudnn], ctx_list)\n # Stride > 1\n sym = mx.sym.Convolution(num_filter=3, kernel=(2,3,3), stride=(2,2,2), name='conv')\n sym_no_cudnn = mx.sym.Convolution(num_filter=3, kernel=(2,3,3), stride=(2,2,2), cudnn_off=True, name='conv')\n check_consistency_NxM([sym, sym_no_cudnn], ctx_list)\n # 1x1 convolution\n sym = mx.sym.Convolution(num_filter=3, kernel=(1,1,1), pad=(0,0,0), name='conv')\n sym_no_cudnn = mx.sym.Convolution(num_filter=3, kernel=(1,1,1), pad=(0,0,0), cudnn_off=True, name='conv')\n check_consistency_NxM([sym, sym_no_cudnn], ctx_list)\n\n\n@with_seed()\ndef test_conv_deconv_guards():\n # Test cases for convolution and deconvolution via strided fft. Ensure that the framework\n # guards against problematic CUDNN_CONVOLUTION_BWD_DATA_ALGO_FFT_TILING in cuDNN [7.3.1,7.5)\n # see https://docs.nvidia.com/deeplearning/sdk/cudnn-release-notes/rel_750.html#rel_750\n tol = 1e-1\n for (op, opname) in [(mx.sym.Convolution, 'conv'), (mx.sym.Deconvolution, 'deconv')]:\n dataname = opname + '_data'\n ctx = {'ctx': mx.gpu(0), dataname: (32, 32, 64, 64), 'type_dict': {dataname: np.float32}}\n test_cases = [\n {'num_filter':32, 'kernel':(6,6), 'pad':(0,0), 'stride':(2,2), 'name': opname},\n {'num_filter':32, 'kernel':(6,6), 'pad':(1,1), 'stride':(2,2), 'name': opname},\n {'num_filter':32, 'kernel':(6,7), 'pad':(0,1), 'stride':(2,2), 'name': opname},\n {'num_filter':32, 'kernel':(7,6), 'pad':(1,0), 'stride':(2,2), 'name': opname},\n {'num_filter':32, 'kernel':(7,7), 'pad':(0,0), 'stride':(2,2), 'name': opname},\n {'num_filter':32, 'kernel':(7,7), 'pad':(1,1), 'stride':(2,2), 'name': opname}]\n for test_case_args in test_cases:\n try:\n sym = op(**test_case_args)\n sym_no_cudnn = op(cudnn_off=True, **test_case_args)\n check_consistency([sym, sym_no_cudnn], [ctx, ctx], tol=tol)\n except:\n print('Test failure of mx.sym.{} with args: {}'.format(op.__name__, test_case_args))\n raise\n\n\ndef _conv_with_num_streams(seed):\n with random_seed(seed):\n # Try to expose timing-dependent improper workspace sharing by parallel dgrad and wgrad\n num_trials = 20\n for _ in range(num_trials):\n size = np.random.randint(32, 128)\n # The cudnn conv operator runs dgrad and wgrad in separate streams if enabled, with possible\n # kernel overlap. The non-cudnn conv op doesn't do this so is used as the 'golden copy'.\n ctx = {'ctx': mx.gpu(0), 'conv_data': (2, 2, size, size),\n 'type_dict': {'conv_data': np.float32}}\n # Adding 'flip' here isolates the model from the input node (which can't use inplace store)\n flipped = mx.sym.flip(axis=0, name='conv')\n sym = mx.sym.Convolution(data=flipped, num_filter=3, kernel=(3,3), pad=(1,1), name='conv')\n flipped_no_cudnn = mx.sym.flip(axis=0, name='conv')\n sym_no_cudnn = mx.sym.Convolution(data=flipped_no_cudnn, num_filter=3, kernel=(3,3), pad=(1,1),\n cudnn_off=True, name='conv')\n try:\n # tol can be pretty high- we're looking for a large diff due to garbaged workspace\n check_consistency([sym, sym_no_cudnn], [ctx, ctx], tol=1e-2)\n except:\n print('Failing conv size = {}'.format(size))\n raise\n\n\[email protected](\"skipping for now due to severe flakiness\")\n@with_seed()\ndef test_convolution_multiple_streams():\n for num_streams in [1, 2]:\n for engine in ['NaiveEngine', 'ThreadedEngine', 'ThreadedEnginePerDevice']:\n print(\"Starting engine %s with %d streams.\" % (engine, num_streams), file=sys.stderr)\n run_in_spawned_process(_conv_with_num_streams,\n {'MXNET_GPU_WORKER_NSTREAMS' : num_streams, 'MXNET_ENGINE_TYPE' : engine})\n print(\"Finished engine %s with %d streams.\" % (engine, num_streams), file=sys.stderr)\n\n\n# This test is designed to expose an issue with cudnn v7.1.4 algo find() when invoked with large c.\n# Algos returned by find() can fail to run with grad_req='add' (wgrad kernel beta parameter == 1.0f).\n@with_seed()\ndef test_convolution_large_c():\n problematic_c = 64 * 1024\n # The convolution accumulates many values, so set large tolerances.\n tol = {np.dtype(np.float32): 1,\n np.dtype(np.float64): 1}\n def test_1D_with_width(width, grad_req):\n ctx_list = [{'ctx': mx.gpu(0), 'conv_data': (1, problematic_c, width), 'type_dict': {'conv_data': np.float32}},\n {'ctx': mx.gpu(0), 'conv_data': (1, problematic_c, width), 'type_dict': {'conv_data': np.float64}}]\n sym = mx.sym.Convolution(layout='NCW', num_filter=8, kernel=(2,), name='conv')\n check_consistency([sym, sym], ctx_list, tol=tol, grad_req=grad_req)\n\n def test_2D_with_width(width, grad_req):\n ctx_list = [{'ctx': mx.gpu(0), 'conv_data': (1, problematic_c, 2, width), 'type_dict': {'conv_data': np.float32}},\n {'ctx': mx.gpu(0), 'conv_data': (1, problematic_c, 2, width), 'type_dict': {'conv_data': np.float64}}]\n sym = mx.sym.Convolution(layout='NCHW', num_filter=4, kernel=(2,2), name='conv')\n check_consistency([sym, sym], ctx_list, tol=tol, grad_req=grad_req)\n\n # Run with different data tensor shapes to run cudnnFind() multiple times.\n # First, populate algo and op caches with models that always use cudnnFind() (req == 'write').\n # Then run models that must avoid cached cudnnFind() results in some cases (req == 'add').\n widths = [4, 16, 64]\n for req in ['write', 'add']:\n for width in widths:\n test_1D_with_width(width, req)\n test_2D_with_width(width, req)\n\n\n# This test is designed to expose an issue with cudnn v7.1.4 algo find() when invoked with large c.\n# Algos returned by find() can fail to run with grad_req='add' (wgrad kernel beta parameter == 1.0f).\n@with_seed()\ndef test_deconvolution_large_c():\n problematic_c = 64 * 1024\n # The deconvolution accumulates many values, so set large tolerances.\n tol = {np.dtype(np.float32): 1,\n np.dtype(np.float64): 1}\n def test_1D_with_width(width, grad_req):\n ctx_list = [{'ctx': mx.gpu(0), 'deconv_data': (1, 8, width), 'type_dict': {'deconv_data': np.float32}},\n {'ctx': mx.gpu(0), 'deconv_data': (1, 8, width), 'type_dict': {'deconv_data': np.float64}}]\n sym = mx.sym.Deconvolution(layout='NCW', num_filter=problematic_c, kernel=(2,), name='deconv')\n check_consistency([sym, sym], ctx_list, tol=tol, grad_req=grad_req)\n\n def test_2D_with_width(width, grad_req):\n ctx_list = [{'ctx': mx.gpu(0), 'deconv_data': (1, 8, 2, width), 'type_dict': {'deconv_data': np.float32}},\n {'ctx': mx.gpu(0), 'deconv_data': (1, 8, 2, width), 'type_dict': {'deconv_data': np.float64}}]\n sym = mx.sym.Deconvolution(layout='NCHW', num_filter=problematic_c, kernel=(2,2), name='deconv')\n check_consistency([sym, sym], ctx_list, tol=tol, grad_req=grad_req)\n\n # Run with different data tensor shapes to run cudnnFind() multiple times.\n # First, populate algo and op caches with models that always use cudnnFind() (req == 'write').\n # Then run models that must avoid cached cudnnFind() results in some cases (req == 'add').\n widths = [4, 16, 64]\n for req in ['write', 'add']:\n for width in widths:\n test_1D_with_width(width, req)\n test_2D_with_width(width, req)\n\n\n@with_seed()\ndef test_convolution_versions():\n # 2D convolution NCHW\n ctx_list = [{'ctx': mx.cpu(0), 'conv_data': (2, 2, 7, 7), 'type_dict': {'conv_data': np.float32}},\n {'ctx': mx.gpu(0), 'conv_data': (2, 2, 7, 7), 'type_dict': {'conv_data': np.float32}},\n {'ctx': mx.gpu(0), 'conv_data': (2, 2, 7, 7), 'type_dict': {'conv_data': np.float32}},\n {'ctx': mx.cpu(0), 'conv_data': (2, 2, 7, 7), 'type_dict': {'conv_data': np.float32}},\n {'ctx': mx.gpu(0), 'conv_data': (2, 2, 7, 7), 'type_dict': {'conv_data': np.float32}}]\n conv_v1_cpu = mx.sym.Convolution_v1(num_filter=3, kernel=(3,3), pad=(1,1), name='conv')\n conv_v1_gpu = mx.sym.Convolution_v1(num_filter=3, kernel=(3,3), pad=(1,1), cudnn_off=True, name='conv')\n conv_cudnn = mx.sym.Convolution(num_filter=3, kernel=(3,3), pad=(1,1), name='conv')\n conv_cpu = mx.sym.Convolution(num_filter=3, kernel=(3,3), pad=(1,1), name='conv')\n conv_gpu = mx.sym.Convolution(num_filter=3, kernel=(3,3), pad=(1,1), cudnn_off=True, name='conv')\n syms = [conv_v1_cpu, conv_v1_gpu, conv_cudnn, conv_cpu, conv_gpu]\n check_consistency(syms, ctx_list)\n\n # 3D convolution NCDHW\n ctx_list = [{'ctx': mx.gpu(0), 'conv_data': (2, 2, 5, 7, 7), 'type_dict': {'conv_data': np.float32}},\n {'ctx': mx.cpu(0), 'conv_data': (2, 2, 5, 7, 7), 'type_dict': {'conv_data': np.float32}},\n {'ctx': mx.gpu(0), 'conv_data': (2, 2, 5, 7, 7), 'type_dict': {'conv_data': np.float32}}]\n conv_cudnn = mx.sym.Convolution(num_filter=3, kernel=(2,3,3), pad=(1,1,1), name='conv')\n conv_cpu = mx.sym.Convolution(num_filter=3, kernel=(2,3,3), pad=(1,1,1), name='conv')\n conv_gpu = mx.sym.Convolution(num_filter=3, kernel=(2,3,3), pad=(1,1,1), cudnn_off=True, name='conv')\n syms = [conv_cudnn, conv_cpu, conv_gpu]\n check_consistency(syms, ctx_list)\n\n\n# More max-pooling strides and pads to test cudnn pooling implementation code paths\n@with_seed()\ndef test_pooling_nhwc_with_convention():\n def make_pooling_syms(**kwargs):\n # Conventional NCHW layout pooling\n sym = mx.sym.Pooling(**kwargs)\n # NHWC pooling\n data = mx.sym.Variable('pool_data')\n sym_nhwc = mx.sym.transpose(data, axes=(0,2,3,1))\n sym_nhwc = mx.sym.Pooling(sym_nhwc, layout='NHWC', **kwargs)\n sym_nhwc = mx.sym.transpose(sym_nhwc, axes=(0,3,1,2), name='pool')\n return [sym, sym_nhwc]\n\n # While the float32 and float64 output is reliably consistent, float16 departs occasionally.\n # We compare nhwc and nchw results only within a given precision.\n for in_shape in [(3, 4, 8, 8), (2, 2, 20, 20)]:\n for kernel in [(2,2), (3,3), (4,4)]:\n for stride in [(1,1), (1,2), (2,1), (2,2)]:\n for data_type in [np.float64, np.float32, np.float16]:\n ctx_list = [{'ctx': mx.gpu(0), 'pool_data': in_shape,\n 'type_dict': {'pool_data': data_type}}]\n symlist = make_pooling_syms(kernel=kernel, pool_type='max', stride=stride,\n pooling_convention='valid', name='pool')\n check_consistency_NxM(symlist, ctx_list)\n\n symlist = make_pooling_syms(kernel=kernel, pool_type='max', stride=stride,\n pooling_convention='full', name='pool')\n check_consistency_NxM(symlist, ctx_list)\n\n symlist = make_pooling_syms(kernel=(300,300), pool_type='max',\n global_pool=True, name='pool')\n check_consistency_NxM(symlist, ctx_list)\n\n\ndef test_pooling_with_type():\n ctx_list = [{'ctx': mx.gpu(0), 'pool_data': (2, 2, 10, 10), 'type_dict': {'pool_data': np.float64}},\n {'ctx': mx.gpu(0), 'pool_data': (2, 2, 10, 10), 'type_dict': {'pool_data': np.float32}},\n {'ctx': mx.gpu(0), 'pool_data': (2, 2, 10, 10), 'type_dict': {'pool_data': np.float16}},\n {'ctx': mx.cpu(0), 'pool_data': (2, 2, 10, 10), 'type_dict': {'pool_data': np.float64}},\n {'ctx': mx.cpu(0), 'pool_data': (2, 2, 10, 10), 'type_dict': {'pool_data': np.float32}}]\n sym = mx.sym.Pooling(kernel=(3,3), pool_type='max', pooling_convention='valid', name='pool')\n check_consistency(sym, ctx_list, rand_type=np.float16)\n\n sym = mx.sym.Pooling(kernel=(3,3), pool_type='max', pooling_convention='full', name='pool')\n check_consistency(sym, ctx_list, rand_type=np.float16)\n\n sym = mx.sym.Pooling(kernel=(300,300), pool_type='max', global_pool=True, name='pool')\n check_consistency(sym, ctx_list, rand_type=np.float16)\n\n\n@with_seed()\ndef test_deconvolution_with_type():\n # Test basic deconvolution without exercising stride, pad or dilation.\n # 1D deconvolution\n sym = mx.sym.Deconvolution(num_filter=3, kernel=(3,), name='deconv')\n ctx_list = [{'ctx': mx.gpu(0), 'deconv_data': (2, 2, 7), 'type_dict': {'deconv_data': np.float64}},\n {'ctx': mx.gpu(0), 'deconv_data': (2, 2, 7), 'type_dict': {'deconv_data': np.float32}},\n {'ctx': mx.gpu(0), 'deconv_data': (2, 2, 7), 'type_dict': {'deconv_data': np.float16}},\n {'ctx': mx.cpu(0), 'deconv_data': (2, 2, 7), 'type_dict': {'deconv_data': np.float64}},\n {'ctx': mx.cpu(0), 'deconv_data': (2, 2, 7), 'type_dict': {'deconv_data': np.float32}}]\n # wider tolerance needed for true-fp16 test above\n tol = {np.dtype(np.float16): 0.3,\n np.dtype(np.float32): 1e-3,\n np.dtype(np.float64): 1e-5,\n np.dtype(np.uint8): 0,\n np.dtype(np.int32): 0}\n check_consistency(sym, ctx_list, tol=tol)\n check_consistency(sym, ctx_list, tol=tol, grad_req=\"add\")\n\n # 2D deconvolution\n sym = mx.sym.Deconvolution(num_filter=2, kernel=(3,3), name='deconv')\n ctx_list = [{'ctx': mx.gpu(0), 'deconv_data': (2, 2, 10, 10), 'type_dict': {'deconv_data': np.float64}},\n {'ctx': mx.gpu(0), 'deconv_data': (2, 2, 10, 10), 'type_dict': {'deconv_data': np.float32}},\n {'ctx': mx.gpu(0), 'deconv_data': (2, 2, 10, 10), 'type_dict': {'deconv_data': np.float16}},\n {'ctx': mx.cpu(0), 'deconv_data': (2, 2, 10, 10), 'type_dict': {'deconv_data': np.float64}},\n {'ctx': mx.cpu(0), 'deconv_data': (2, 2, 10, 10), 'type_dict': {'deconv_data': np.float32}}]\n # wider tolerance needed for true-fp16 test above\n tol = {np.dtype(np.float16): 0.3,\n np.dtype(np.float32): 1e-3,\n np.dtype(np.float64): 1e-5,\n np.dtype(np.uint8): 0,\n np.dtype(np.int32): 0}\n check_consistency(sym, ctx_list, tol=tol)\n check_consistency(sym, ctx_list, tol=tol, grad_req=\"add\")\n\n\n@with_seed()\ndef test_deconvolution_options():\n\n # 1D deconvolution\n ctx_list = [{'ctx': mx.gpu(0), 'deconv_data': (2, 2, 7), 'type_dict': {'deconv_data': np.float64}},\n {'ctx': mx.gpu(0), 'deconv_data': (2, 2, 7), 'type_dict': {'deconv_data': np.float32}},\n {'ctx': mx.gpu(0), 'deconv_data': (2, 2, 7), 'type_dict': {'deconv_data': np.float16}},\n {'ctx': mx.cpu(0), 'deconv_data': (2, 2, 7), 'type_dict': {'deconv_data': np.float64}},\n {'ctx': mx.cpu(0), 'deconv_data': (2, 2, 7), 'type_dict': {'deconv_data': np.float32}}]\n # Pad > 0\n sym = mx.sym.Deconvolution(layout='NCW', num_filter=3, kernel=(3,), pad=(1,), name='deconv')\n sym_no_cudnn = mx.sym.Deconvolution(num_filter=3, kernel=(3,), pad=(1,), cudnn_off=True, name='deconv')\n check_consistency_NxM([sym, sym_no_cudnn], ctx_list)\n # Stride > 1\n sym = mx.sym.Deconvolution(layout='NCW', num_filter=3, kernel=(3,), stride=(2,), name='deconv')\n sym_no_cudnn = mx.sym.Deconvolution(num_filter=3, kernel=(3,), stride=(2,), cudnn_off=True, name='deconv')\n check_consistency_NxM([sym, sym_no_cudnn], ctx_list)\n # Dilate > 1\n sym = mx.sym.Deconvolution(layout='NCW', num_filter=3, kernel=(3,), dilate=(2,), name='deconv')\n sym_no_cudnn = mx.sym.Deconvolution(num_filter=3, kernel=(3,), dilate=(2,), cudnn_off=True, name='deconv')\n check_consistency_NxM([sym, sym_no_cudnn], ctx_list)\n\n # 2D deconvolution\n ctx_list = [{'ctx': mx.gpu(0), 'deconv_data': (2, 8, 10, 10), 'type_dict': {'deconv_data': np.float64}},\n {'ctx': mx.gpu(0), 'deconv_data': (2, 8, 10, 10), 'type_dict': {'deconv_data': np.float32}},\n {'ctx': mx.gpu(0), 'deconv_data': (2, 8, 10, 10), 'type_dict': {'deconv_data': np.float16}},\n {'ctx': mx.cpu(0), 'deconv_data': (2, 8, 10, 10), 'type_dict': {'deconv_data': np.float64}},\n {'ctx': mx.cpu(0), 'deconv_data': (2, 8, 10, 10), 'type_dict': {'deconv_data': np.float32}}]\n # Pad > 0\n sym = mx.sym.Deconvolution(num_filter=2, kernel=(3,3), pad=(1,1), name='deconv')\n sym_no_cudnn = mx.sym.Deconvolution(num_filter=2, kernel=(3,3), pad=(1,1), cudnn_off=True, name='deconv')\n check_consistency_NxM([sym, sym_no_cudnn], ctx_list)\n # Stride > 1\n sym = mx.sym.Deconvolution(num_filter=2, kernel=(3,3), stride=(2,2), name='deconv')\n sym_no_cudnn = mx.sym.Deconvolution(num_filter=2, kernel=(3,3), stride=(2,2), cudnn_off=True, name='deconv')\n check_consistency_NxM([sym, sym_no_cudnn], ctx_list)\n # Dilate > 1\n sym = mx.sym.Deconvolution(num_filter=2, kernel=(3,3), dilate=(2,2), name='deconv')\n sym_no_cudnn = mx.sym.Deconvolution(num_filter=2, kernel=(3,3), dilate=(2,2), cudnn_off=True, name='deconv')\n check_consistency_NxM([sym, sym_no_cudnn], ctx_list)\n\n# # 3D deconvolution (not yet enabled)\n# ctx_list = [{'ctx': mx.cpu(0), 'conv_data': (2, 2, 5, 7, 7), 'type_dict': {'conv_data': np.float64}},\n# {'ctx': mx.cpu(0), 'conv_data': (2, 2, 5, 7, 7), 'type_dict': {'conv_data': np.float64}},\n# {'ctx': mx.gpu(0), 'conv_data': (2, 2, 5, 7, 7), 'type_dict': {'conv_data': np.float64}},\n# {'ctx': mx.gpu(0), 'conv_data': (2, 2, 5, 7, 7), 'type_dict': {'conv_data': np.float32}}]\n# # Pad > 0\n# sym = mx.sym.Convolution(num_filter=3, kernel=(2,3,3), pad=(1,1,1), name='conv')\n# sym_no_cudnn = mx.sym.Convolution(num_filter=3, kernel=(2,3,3), pad=(1,1,1), cudnn_off=True, name='conv')\n# check_consistency_NxM([sym, sym_no_cudnn], ctx_list)\n# # Stride > 1\n# sym = mx.sym.Convolution(num_filter=3, kernel=(2,3,3), stride=(2,2,2), name='conv')\n# sym_no_cudnn = mx.sym.Convolution(num_filter=3, kernel=(2,3,3), stride=(2,2,2), cudnn_off=True, name='conv')\n# check_consistency_NxM([sym, sym_no_cudnn], ctx_list)\n\n\n@with_seed(1234)\ndef test_bilinear_sampler_with_type():\n data = mx.sym.Variable('data')\n grid = mx.sym.Variable('grid')\n sym = mx.sym.BilinearSampler(data=data, grid=grid)\n ctx_list = [{'ctx': mx.gpu(0), 'data': (1, 5, 10, 10), 'grid': (1, 2, 10, 10),\n 'type_dict': {'data': np.float64}},\n {'ctx': mx.gpu(0), 'data': (1, 5, 10, 10), 'grid': (1, 2, 10, 10),\n 'type_dict': {'data': np.float32}},\n {'ctx': mx.gpu(0), 'data': (1, 5, 10, 10), 'grid': (1, 2, 10, 10),\n 'type_dict': {'data': np.float16}},\n {'ctx': mx.cpu(0), 'data': (1, 5, 10, 10), 'grid': (1, 2, 10, 10),\n 'type_dict': {'data': np.float64}},\n {'ctx': mx.cpu(0), 'data': (1, 5, 10, 10), 'grid': (1, 2, 10, 10),\n 'type_dict': {'data': np.float32}}]\n check_consistency(sym, ctx_list)\n check_consistency(sym, ctx_list, grad_req=\"add\")\n\n\n@with_seed()\ndef test_grid_generator_with_type():\n data = mx.sym.Variable('data')\n sym = mx.sym.GridGenerator(data=data, transform_type='affine', target_shape=(20, 20))\n ctx_list = [{'ctx': mx.gpu(0), 'data': (3, 6), 'type_dict': {'data': np.float32}},\n {'ctx': mx.cpu(0), 'data': (3, 6), 'type_dict': {'data': np.float32}}]\n check_consistency(sym, ctx_list)\n check_consistency(sym, ctx_list, grad_req=\"add\")\n sym = mx.sym.GridGenerator(data=data, transform_type='warp', target_shape=(20, 20))\n ctx_list = [{'ctx': mx.gpu(0), 'data': (3, 2, 20, 20), 'type_dict': {'data': np.float32}},\n {'ctx': mx.cpu(0), 'data': (3, 2, 20, 20), 'type_dict': {'data': np.float32}}]\n check_consistency(sym, ctx_list)\n check_consistency(sym, ctx_list, grad_req=\"add\")\n\n\n@with_seed()\ndef test_spatial_transformer_with_type():\n data = mx.sym.Variable('data')\n loc = mx.sym.Flatten(data)\n loc = mx.sym.FullyConnected(data=loc, num_hidden=10)\n loc = mx.sym.Activation(data=loc, act_type='relu')\n loc = mx.sym.FullyConnected(data=loc, num_hidden=6)\n sym = mx.sym.SpatialTransformer(data=data, loc=loc, target_shape=(10, 10),\n transform_type=\"affine\", sampler_type=\"bilinear\", cudnn_off=True)\n ctx_list = [{'ctx': mx.gpu(0), 'data': (1, 5, 10, 10), 'type_dict': {'data': np.float64}},\n {'ctx': mx.cpu(0), 'data': (1, 5, 10, 10), 'type_dict': {'data': np.float64}}]\n check_consistency(sym, ctx_list)\n check_consistency(sym, ctx_list, grad_req=\"add\")\n sym = mx.sym.SpatialTransformer(data=data, loc=loc, target_shape=(10, 10),\n transform_type=\"affine\", sampler_type=\"bilinear\", cudnn_off=False)\n check_consistency(sym, ctx_list)\n check_consistency(sym, ctx_list, grad_req=\"add\")\n\n@with_seed()\ndef test_pooling_with_type2():\n # While the float32 and float64 output is reliably consistent, float16 departs occasionally.\n # We compare cpu and gpu results only within a given precision.\n for data_type in [np.float64, np.float32, np.float16]:\n ctx_list = [{'ctx': mx.gpu(0), 'pool_data': (10, 2, 10, 10), 'type_dict': {'pool_data': data_type}},\n {'ctx': mx.cpu(0), 'pool_data': (10, 2, 10, 10), 'type_dict': {'pool_data': data_type}}]\n\n sym = mx.sym.Pooling(name='pool', kernel=(3,3), stride=(2,2), pool_type='max')\n check_consistency(sym, ctx_list)\n\n sym = mx.sym.Pooling(name='pool', kernel=(3,3), pad=(1,1), pool_type='avg')\n check_consistency(sym, ctx_list)\n\n sym = mx.sym.Pooling(name='pool', kernel=(5,5), pad=(2,2), pool_type='max')\n check_consistency(sym, ctx_list)\n\n sym = mx.sym.Pooling(name='pool', kernel=(3,3), pad=(1,1), pool_type='sum')\n check_consistency(sym, ctx_list)\n\n@with_seed()\ndef test_pooling_nhwc_with_type():\n def make_pooling_syms(**kwargs):\n # Conventional NCHW layout pooling\n sym = mx.sym.Pooling(**kwargs)\n # NHWC pooling\n data = mx.sym.Variable('pool_data')\n sym_nhwc = mx.sym.transpose(data, axes=(0,2,3,1))\n sym_nhwc = mx.sym.Pooling(sym_nhwc, layout='NHWC', **kwargs)\n sym_nhwc = mx.sym.transpose(sym_nhwc, axes=(0,3,1,2), name='pool')\n return [sym, sym_nhwc]\n\n # While the float32 and float64 output is reliably consistent, float16 departs occasionally.\n # We compare nhwc and nchw results only within a given precision.\n for data_type in [np.float64, np.float32, np.float16]:\n # NHWC pooling only enabled on GPU with CUDNN\n ctx_list = [{'ctx': mx.gpu(0), 'pool_data': (10, 2, 10, 10), 'type_dict': {'pool_data': data_type}}]\n symlist = make_pooling_syms(name='pool', kernel=(3,3), stride=(2,2), pool_type='max')\n check_consistency_NxM(symlist, ctx_list)\n\n symlist = make_pooling_syms(name='pool', kernel=(3,3), pad=(1,1), pool_type='avg')\n check_consistency_NxM(symlist, ctx_list)\n\n symlist = make_pooling_syms(name='pool', kernel=(5,5), pad=(2,2), pool_type='max')\n check_consistency_NxM(symlist, ctx_list)\n\n\n@with_seed()\ndef test_pooling_versions():\n\n # Produce the name of the 'transposed' layout, given the dimension\n def transposed_layout(ndim):\n if ndim < 3 or ndim > 5:\n raise RuntimeError(\"Invalid data dim, expecting 3, 4 or 5\")\n return ('NWC', 'NHWC', 'NDHWC')[ndim-3]\n\n # default padding is all zeros\n def is_default_pad(pad):\n return pad == (0,) * len(pad)\n\n # default stride is all ones\n def is_default_stride(stride):\n return stride == (1,) * len(stride)\n\n # returns True/False randomly with equal probability\n def random_choice():\n return np.random.random(1)[0] < 0.5\n\n def test_pooling_versions_helper(pool_op_list, data, kernel, pool_type, pad, stride,\n pooling_convention='valid', global_pool=False, p_value=2,\n count_include_pad=True, tol=None, dtype=np.float32):\n ctx_list = []\n sym_list = []\n for pool_ctx in pool_op_list:\n (pool_op, ctx_type) = pool_ctx.rsplit('_', 1)\n expected_ctxs = ['cpu', 'gpu', 'cudnn']\n if ctx_type not in expected_ctxs:\n raise RuntimeError('Expected one of {}, saw {}.'.format(expected_ctxs, ctx_type))\n ctx = mx.cpu(0) if ctx_type == 'cpu' else mx.gpu(0)\n ctx_list.append({'ctx': ctx, 'pool_data': data, 'type_dict': {'pool_data': dtype}})\n # start with pool args present in all cases\n pool_op_args = {'kernel': kernel, 'pool_type': pool_type,\n 'pooling_convention' : pooling_convention, 'name' : 'pool'}\n # add other args as needed\n if global_pool:\n pool_op_args['global_pool'] = True\n else:\n # Add pad and stride param if needed, plus randomly when it matches the default\n if not is_default_pad(pad) or random_choice():\n pool_op_args.update({'pad' : pad})\n if not is_default_stride(stride) or random_choice():\n pool_op_args.update({'stride' : stride})\n\n expected_pool_ops = ['pool', 'pool_transposed', 'pool_v1']\n if pool_op == 'pool_v1':\n sym = mx.sym.Pooling_v1(**pool_op_args)\n else:\n pool_op_args.update({'p_value' : p_value, 'count_include_pad' : count_include_pad})\n if ctx_type != 'cpu':\n pool_op_args['cudnn_off'] = ctx_type == 'gpu'\n if pool_op == 'pool':\n # isolate pooling input from symbol input to test shared tensor optimizations\n buffered_input = mx.sym.identity(name='pool')\n sym = mx.sym.Pooling(buffered_input, **pool_op_args)\n elif pool_op == 'pool_transposed':\n ndim = len(data)\n # NCW->NWC axes=(0,2,1) NCHW->NHWC axes=(0,2,3,1) NCDHW->NDHWC axes=(0,2,3,4,1);\n axes = (0,) + tuple(range(2,ndim)) + (1,)\n transposed = mx.sym.transpose(axes=axes, name='pool')\n pooled = mx.sym.Pooling(data=transposed, layout=transposed_layout(ndim),\n **pool_op_args)\n # NWC->NCW axes=(0,2,1) NHWC->NCHW axes=(0,3,1,2) NDHWC->NCDHW axes=(0,4,1,2,3);\n axes = (0, ndim-1) + tuple(range(1,ndim-1))\n sym = mx.sym.transpose(data=pooled, axes=axes, name='pool')\n else:\n raise RuntimeError('Expected one of {}, saw {}.'.format(expected_pool_ops,\n pool_op))\n sym_list.append(sym)\n\n check_consistency(sym_list, ctx_list, equal_nan=(not count_include_pad), tol=tol)\n\n def test_pooling_dim(dim, pool_type, dtype, pool_op_list, p_value=2, count_include_pad=True,\n tol=None):\n if dim == '1D':\n data = (3, 3, 10)\n kernels = [(4,), (4,), (5,)]\n pads = [(0,), (2,), (2,)]\n strides = [(1,), (2,), (1,)]\n elif dim == '2D_no_padding':\n data = (3, 2, 20, 20)\n kernels = [(3, 3), (4, 5)]\n pads = [(0, 0), (0, 0)]\n strides = [(1, 1), (2, 1)]\n elif dim == '2D':\n data = (2, 2, 20, 20)\n kernels = [(3, 3), (3, 5), (4, 5), (4, 5)]\n pads = [(0, 0), (1, 2), (0, 0), (2, 3)]\n strides = [(1, 1), (1, 1), (2, 1), (1, 1)]\n elif dim == '3D':\n data = (2, 3, 20, 20, 20)\n kernels = [(4, 5, 3), (4, 5, 3), (3, 5, 7)]\n pads = [(0, 0, 0), (2, 3, 2), (1, 2, 3)]\n strides = [(1, 1, 1), (2, 3, 1), (1, 1, 1)]\n else:\n raise RuntimeError('Unexpected pooling test class: {}.'.format(dim))\n\n for kernel, pad, stride in zip(kernels, pads, strides):\n for pooling_convention in ['valid', 'full']:\n try:\n test_pooling_versions_helper(pool_op_list=pool_op_list,\n data=data, kernel=kernel, pad=pad, stride=stride,\n pool_type=pool_type, pooling_convention=pooling_convention,\n global_pool=False, p_value=p_value,\n count_include_pad=count_include_pad, tol=tol, dtype=dtype)\n except:\n print('pool_op_list = {}'.format(pool_op_list))\n print('kernel={}, pad={}, stride={}'.format(kernel, pad, stride))\n print('pool_type={}, pooling_convention={}, global_pool=False'.format(pool_type,\n pooling_convention))\n print('p_value={}, count_include_pad={}, dtype={}'.format(p_value,\n count_include_pad, dtype))\n print('environ = \\n{}'.format(os.environ))\n raise\n\n # Make sure kernel is ignored during global_pool by sometimes setting it to a crazy value\n kernel = kernels[0]\n if random_choice():\n kernel = (300,) * len(kernel)\n\n test_pooling_versions_helper(pool_op_list=pool_op_list,\n data=data, kernel=kernel, pad=None, stride=None,\n pool_type=pool_type, global_pool=True, p_value=p_value,\n count_include_pad=count_include_pad, tol=tol, dtype=dtype)\n\n # The various implementations of the standard pooling operator\n std_pool_op_list = ['pool_cpu', 'pool_transposed_cpu',\n 'pool_gpu', 'pool_transposed_gpu',\n 'pool_cudnn', 'pool_transposed_cudnn']\n # The implementations of the 'v1' pooling operator\n v1_pool_op_list = ['pool_v1_cpu', 'pool_v1_gpu']\n # For those cases when all implementations should match- the combined implementation list.\n combo_pool_op_list = std_pool_op_list + v1_pool_op_list\n\n for dtype in [np.float32, np.float64, np.float16]:\n # Testing of the standard (not 'v1') pooling operator is universal across all\n # data dimensions, implementations and layouts.\n for dim in ['1D', '2D', '3D']:\n test_pooling_dim(dim, 'max', dtype, std_pool_op_list)\n test_pooling_dim(dim, 'avg', dtype, std_pool_op_list, count_include_pad=True)\n test_pooling_dim(dim, 'avg', dtype, std_pool_op_list, count_include_pad=False)\n test_pooling_dim(dim, 'sum', dtype, std_pool_op_list)\n test_pooling_dim(dim, 'lp', dtype, std_pool_op_list, p_value=1)\n test_pooling_dim(dim, 'lp', dtype, std_pool_op_list, p_value=2)\n test_pooling_dim(dim, 'lp', dtype, std_pool_op_list, p_value=3)\n\n # Testing of the 'v1' pooling operator is over its restricted support domain of\n # 2D data only and not with the 'lp' pooling type. The 'v1' cpu and gpu versions are\n # always tested against each other, and sometimes against the standard operator versions.\n # The slightly different 'v1' definition prevents this in the following cases:\n #\n # 1. In max pooling, when multiple input values are the maximum in the input window,\n # the 'v1' implementation backprops the gradient to all maxima, whereas the standard\n # pooling operator backprops the gradient to the lowest-indexed maximum only.\n # 2. In max pooling, the 'v1' operator pads with 0's and this value can become the\n # maximum output value in the case of an all-negative input. The standard pooling\n # operator effectively considers the padding to be the largest negative value, so\n # only input values should appear in the output.\n # 3. In avg pooling, the 'v1' operator divides the sum by the same window size factor,\n # even at the edges, and so does not support count_include_pad = False.\n # 4. The float16 'v1' pooling operator performs forward sums and averages in\n # float16, whereas the std operators perform those calculations in float32, so\n # greater float16 tolerances are needed when comparing across implementations.\n\n # Double the float16 tol when comparing v1 and non-v1 implemenations, per note 4 above.\n relaxed_tol = {np.dtype(np.float16): 2e-1,\n np.dtype(np.float32): 1e-3,\n np.dtype(np.float64): 1e-5,\n np.dtype(np.uint8): 0,\n np.dtype(np.int32): 0,\n np.dtype(np.int64): 0}\n\n # Exclude std implementations due to points 1 and 2 above.\n test_pooling_dim('2D', 'max', dtype, v1_pool_op_list)\n # The standard and 'v1' implementations match for this case.\n test_pooling_dim('2D', 'avg', dtype, combo_pool_op_list, count_include_pad=True,\n tol=relaxed_tol)\n # Exclude std implementations due to point 3 above.\n test_pooling_dim('2D', 'avg', dtype, v1_pool_op_list, count_include_pad=False)\n # The standard and 'v1' implementations match for this case.\n test_pooling_dim('2D', 'sum', dtype, combo_pool_op_list, tol=relaxed_tol)\n\n # We can compare the standard and 'v1' max pooling implementations if we eliminate padding\n # (see point 2 above) and use np.float64 data so that no two random input window values are\n # likely to be the same (see point 1 above).\n test_pooling_dim('2D_no_padding', 'max', np.float64, combo_pool_op_list)\n\n\n@with_seed()\ndef test_pooling_full_2d():\n def test_pooling_full_2d_type(pool_type):\n data = (2, 2, 10, 10)\n kernel = (4, 5)\n pad = (1, 2)\n stride = (3, 4)\n\n convention = 'full'\n ctx_list = []\n sym_list = []\n\n # o_h = ceil((10 + 1 + 1 - 4) / 3) + 1 = 4\n # o_w = ceil((10 + 2 + 2 - 5) / 4) + 1 = 4\n ctx_list.append({'ctx': mx.cpu(0), 'pool_data': data, 'type_dict': {'pool_data': np.float32}})\n sym_list.append(mx.sym.Pooling(kernel=kernel, pad=pad, stride=stride, pool_type=pool_type,\n pooling_convention=convention, global_pool=False, name='pool'))\n\n ctx_list.append({'ctx': mx.gpu(0), 'pool_data': data, 'type_dict': {'pool_data': np.float32}})\n sym_list.append(mx.sym.Pooling(kernel=kernel, pad=pad, stride=stride, pool_type=pool_type,\n pooling_convention=convention, global_pool=False, name='pool'))\n\n check_consistency(sym_list, ctx_list)\n\n test_pooling_full_2d_type('max')\n test_pooling_full_2d_type('avg')\n test_pooling_full_2d_type('sum')\n\n\n@with_seed()\ndef test_flatten_slice_after_conv():\n ctx_list = []\n\n data = mx.sym.Variable('conv_data')\n conv = mx.symbol.Convolution(data=data, name='conv', num_filter=16, kernel=(3,3), stride=(1,1))\n flatten = mx.symbol.flatten(data=conv)\n slice_sym = mx.symbol.slice(data=flatten, begin=0, end=1)\n\n ctx_list = [{'ctx': mx.gpu(0), 'conv_data': (2, 16, 16, 16), 'type_dict': {'conv_data': np.float32}},\n {'ctx': mx.cpu(0), 'conv_data': (2, 16, 16, 16), 'type_dict': {'conv_data': np.float32}}]\n check_consistency(slice_sym, ctx_list)\n\n\n@with_seed()\ndef test_bilinear_resize_op():\n ctx_list = [{'ctx': mx.cpu(0), 'data': (2, 2, 20, 20), 'type_dict': {'data': np.float32}},\n {'ctx': mx.gpu(0), 'data': (2, 2, 20, 20), 'type_dict': {'data': np.float32}}]\n\n data = mx.sym.Variable('data')\n sym = mx.sym.contrib.BilinearResize2D(data, height=10, width=5, align_corners=True)\n check_consistency(sym, ctx_list)\n\n sym = mx.sym.contrib.BilinearResize2D(data, height=10, width=5, align_corners=False)\n check_consistency(sym, ctx_list)\n\n sym = mx.sym.contrib.BilinearResize2D(data, None, scale_height=2, scale_width=0.5, mode='odd_scale', align_corners=True)\n check_consistency(sym, ctx_list)\n\n sym = mx.sym.contrib.BilinearResize2D(data, None, scale_height=2, scale_width=0.5, mode='odd_scale', align_corners=False)\n check_consistency(sym, ctx_list)\n\n sym = mx.sym.contrib.BilinearResize2D(data, None, scale_height=0.5, scale_width=2, mode='to_even_up', align_corners=True)\n check_consistency(sym, ctx_list)\n\n sym = mx.sym.contrib.BilinearResize2D(data, None, scale_height=0.5, scale_width=2, mode='to_even_up', align_corners=False)\n check_consistency(sym, ctx_list)\n\n@with_seed()\ndef test_global_pooling():\n def test_1d_pooling(pool_type, p_value=2):\n data = (2, 3, 20)\n kernel = (4,)\n pad = (2,)\n stride = (2,)\n\n ctx_list = []\n sym_list = []\n\n pooling_convention = 'valid'\n\n ctx_list.append({'ctx': mx.cpu(0), 'pool_data': data, 'type_dict': {'pool_data': np.float32}})\n sym_list.append(mx.sym.Pooling(kernel=kernel, pad=pad, stride=stride, pool_type=pool_type,\n pooling_convention=pooling_convention, global_pool=True, name='pool', p_value=p_value))\n\n ctx_list.append({'ctx': mx.cpu(0), 'pool_data': data, 'type_dict': {'pool_data': np.float32}})\n sym_list.append(mx.sym.Pooling(kernel=kernel, pool_type=pool_type,\n pooling_convention=pooling_convention, global_pool=True, name='pool', p_value=p_value))\n\n ctx_list.append({'ctx': mx.cpu(0), 'pool_data': data, 'type_dict': {'pool_data': np.float32}})\n sym_list.append(mx.sym.Pooling(pool_type=pool_type,\n pooling_convention=pooling_convention, global_pool=True, name='pool', p_value=p_value))\n\n ctx_list.append({'ctx': mx.gpu(0), 'pool_data': data, 'type_dict': {'pool_data': np.float32}})\n sym_list.append(mx.sym.Pooling(kernel=kernel, pad=pad, stride=stride, pool_type=pool_type,\n pooling_convention=pooling_convention, global_pool=True, p_value=p_value, cudnn_off=False, name='pool'))\n\n ctx_list.append({'ctx': mx.gpu(0), 'pool_data': data, 'type_dict': {'pool_data': np.float32}})\n sym_list.append(mx.sym.Pooling(kernel=kernel, pool_type=pool_type,\n pooling_convention=pooling_convention, global_pool=True, p_value=p_value, cudnn_off=False, name='pool'))\n\n ctx_list.append({'ctx': mx.gpu(0), 'pool_data': data, 'type_dict': {'pool_data': np.float32}})\n sym_list.append(mx.sym.Pooling(pool_type=pool_type,\n pooling_convention=pooling_convention, global_pool=True, p_value=p_value, cudnn_off=False, name='pool'))\n\n ctx_list.append({'ctx': mx.gpu(0), 'pool_data': data, 'type_dict': {'pool_data': np.float32}})\n sym_list.append(mx.sym.Pooling(kernel=kernel, pad=pad, stride=stride, pool_type=pool_type,\n pooling_convention=pooling_convention, global_pool=True, p_value=p_value, cudnn_off=True, name='pool'))\n\n ctx_list.append({'ctx': mx.gpu(0), 'pool_data': data, 'type_dict': {'pool_data': np.float32}})\n sym_list.append(mx.sym.Pooling(kernel=kernel, pool_type=pool_type,\n pooling_convention=pooling_convention, global_pool=True, p_value=p_value, cudnn_off=True, name='pool'))\n\n ctx_list.append({'ctx': mx.gpu(0), 'pool_data': data, 'type_dict': {'pool_data': np.float32}})\n sym_list.append(mx.sym.Pooling(pool_type=pool_type,\n pooling_convention=pooling_convention, global_pool=True, p_value=p_value, cudnn_off=True, name='pool'))\n\n check_consistency(sym_list, ctx_list)\n\n def test_2d_pooling(pool_type, p_value=2):\n data = (2, 3, 20, 20)\n kernel = (4, 4)\n pad = (2, 2)\n stride = (2, 2)\n\n ctx_list = []\n sym_list = []\n\n pooling_convention = 'valid'\n\n if pool_type != 'lp':\n ctx_list.append({'ctx': mx.cpu(0), 'pool_data': data, 'type_dict': {'pool_data': np.float32}})\n sym_list.append(mx.sym.Pooling_v1(kernel=kernel, pad=pad, stride=stride, pool_type=pool_type,\n pooling_convention=pooling_convention, global_pool=True, name='pool'))\n\n ctx_list.append({'ctx': mx.cpu(0), 'pool_data': data, 'type_dict': {'pool_data': np.float32}})\n sym_list.append(mx.sym.Pooling_v1(kernel=kernel, pool_type=pool_type,\n pooling_convention=pooling_convention, global_pool=True, name='pool'))\n\n ctx_list.append({'ctx': mx.cpu(0), 'pool_data': data, 'type_dict': {'pool_data': np.float32}})\n sym_list.append(mx.sym.Pooling_v1(pool_type=pool_type,\n pooling_convention=pooling_convention, global_pool=True, name='pool'))\n\n ctx_list.append({'ctx': mx.cpu(0), 'pool_data': data, 'type_dict': {'pool_data': np.float32}})\n sym_list.append(mx.sym.Pooling(kernel=kernel, pad=pad, stride=stride, pool_type=pool_type,\n pooling_convention=pooling_convention, global_pool=True, p_value=p_value, name='pool'))\n\n ctx_list.append({'ctx': mx.cpu(0), 'pool_data': data, 'type_dict': {'pool_data': np.float32}})\n sym_list.append(mx.sym.Pooling(kernel=kernel, pool_type=pool_type,\n pooling_convention=pooling_convention, global_pool=True, p_value=p_value, name='pool'))\n\n ctx_list.append({'ctx': mx.cpu(0), 'pool_data': data, 'type_dict': {'pool_data': np.float32}})\n sym_list.append(mx.sym.Pooling(pool_type=pool_type,\n pooling_convention=pooling_convention, global_pool=True, p_value=p_value, name='pool'))\n\n ctx_list.append({'ctx': mx.gpu(0), 'pool_data': data, 'type_dict': {'pool_data': np.float32}})\n sym_list.append(mx.sym.Pooling(kernel=kernel, pad=pad, stride=stride, pool_type=pool_type,\n pooling_convention=pooling_convention, global_pool=True, p_value=p_value, cudnn_off=False, name='pool'))\n\n ctx_list.append({'ctx': mx.gpu(0), 'pool_data': data, 'type_dict': {'pool_data': np.float32}})\n sym_list.append(mx.sym.Pooling(kernel=kernel, pool_type=pool_type,\n pooling_convention=pooling_convention, global_pool=True, p_value=p_value, cudnn_off=False, name='pool'))\n\n ctx_list.append({'ctx': mx.gpu(0), 'pool_data': data, 'type_dict': {'pool_data': np.float32}})\n sym_list.append(mx.sym.Pooling(pool_type=pool_type,\n pooling_convention=pooling_convention, global_pool=True, p_value=p_value, cudnn_off=False, name='pool'))\n\n ctx_list.append({'ctx': mx.gpu(0), 'pool_data': data, 'type_dict': {'pool_data': np.float32}})\n sym_list.append(mx.sym.Pooling(kernel=kernel, pad=pad, stride=stride, pool_type=pool_type,\n pooling_convention=pooling_convention, global_pool=True, p_value=p_value, cudnn_off=True, name='pool'))\n\n ctx_list.append({'ctx': mx.gpu(0), 'pool_data': data, 'type_dict': {'pool_data': np.float32}})\n sym_list.append(mx.sym.Pooling(kernel=kernel, pool_type=pool_type,\n pooling_convention=pooling_convention, global_pool=True, p_value=p_value, cudnn_off=True, name='pool'))\n\n ctx_list.append({'ctx': mx.gpu(0), 'pool_data': data, 'type_dict': {'pool_data': np.float32}})\n sym_list.append(mx.sym.Pooling(pool_type=pool_type,\n pooling_convention=pooling_convention, global_pool=True, p_value=p_value, cudnn_off=True, name='pool'))\n\n\n check_consistency(sym_list, ctx_list)\n\n test_1d_pooling('max')\n test_1d_pooling('avg')\n test_1d_pooling('sum')\n test_1d_pooling('lp', p_value=1)\n test_1d_pooling('lp', p_value=2)\n test_1d_pooling('lp', p_value=3)\n\n test_2d_pooling('max')\n test_2d_pooling('avg')\n test_2d_pooling('sum')\n test_2d_pooling('lp', p_value=1)\n test_2d_pooling('lp', p_value=2)\n test_2d_pooling('lp', p_value=3)\n\n\n@with_seed()\ndef test_upsampling_with_type():\n sym = mx.sym.UpSampling(scale=2, num_filter=2, name='up', sample_type='nearest', num_args=1)\n ctx_list = [{'ctx': mx.gpu(0), 'up_arg0': (2, 2, 2, 10), 'type_dict': {'up_arg0': np.float64}},\n {'ctx': mx.gpu(0), 'up_arg0': (2, 2, 2, 10), 'type_dict': {'up_arg0': np.float32}},\n {'ctx': mx.gpu(0), 'up_arg0': (2, 2, 2, 10), 'type_dict': {'up_arg0': np.float16}},\n {'ctx': mx.cpu(0), 'up_arg0': (2, 2, 2, 10), 'type_dict': {'up_arg0': np.float64}},\n {'ctx': mx.cpu(0), 'up_arg0': (2, 2, 2, 10), 'type_dict': {'up_arg0': np.float32}}]\n check_consistency(sym, ctx_list)\n\n\n@with_seed()\ndef test_upsampling_bilinear_with_type():\n sym = mx.sym.UpSampling(scale=2, num_filter=2, name='up', sample_type='bilinear', num_args=1)\n ctx_list = [{'ctx': mx.gpu(0), 'up_data': (2, 2, 2, 10), 'type_dict': {'up_data': np.float64}},\n {'ctx': mx.gpu(0), 'up_data': (2, 2, 2, 10), 'type_dict': {'up_data': np.float32}},\n {'ctx': mx.gpu(0), 'up_data': (2, 2, 2, 10), 'type_dict': {'up_data': np.float16}},\n {'ctx': mx.cpu(0), 'up_data': (2, 2, 2, 10), 'type_dict': {'up_data': np.float64}},\n {'ctx': mx.cpu(0), 'up_data': (2, 2, 2, 10), 'type_dict': {'up_data': np.float32}}]\n check_consistency(sym, ctx_list)\n\n\n@with_seed()\ndef test_concat_with_type():\n sym = mx.sym.Concat(name='concat', num_args=2)\n ctx_list = [{'ctx': mx.gpu(0), 'concat_arg1': (2, 10), 'concat_arg0': (2, 10),\n 'type_dict': {'concat_arg0': np.float64, 'concat_arg1': np.float64}},\n {'ctx': mx.gpu(0), 'concat_arg1': (2, 10), 'concat_arg0': (2, 10),\n 'type_dict': {'concat_arg0': np.float32, 'concat_arg1': np.float32}},\n {'ctx': mx.gpu(0), 'concat_arg1': (2, 10), 'concat_arg0': (2, 10),\n 'type_dict': {'concat_arg0': np.float16, 'concat_arg1': np.float16}},\n {'ctx': mx.cpu(0), 'concat_arg1': (2, 10), 'concat_arg0': (2, 10),\n 'type_dict': {'concat_arg0': np.float64, 'concat_arg1': np.float64}},\n {'ctx': mx.cpu(0), 'concat_arg1': (2, 10), 'concat_arg0': (2, 10),\n 'type_dict': {'concat_arg0': np.float32, 'concat_arg1': np.float32}}]\n check_consistency(sym, ctx_list)\n\n\n@with_seed()\ndef test_elementwisesum_with_type():\n dev_types = [[mx.gpu(0), [np.float64, np.float32, np.float16]],\n [mx.cpu(0), [np.float64, np.float32]] ]\n for num_args in range(1, 6):\n ews_arg_shape = {}\n for i in range(num_args):\n ews_arg_shape['ews_arg'+str(i)] = (2, 10)\n sym = mx.sym.ElementWiseSum(name='ews', num_args=num_args)\n ctx_list = []\n for dev, types in dev_types:\n for dtype in types:\n ews_arg_dtype = {'type_dict':{}}\n for i in range(num_args):\n ews_arg_dtype['type_dict']['ews_arg'+str(i)] = dtype\n ctx_elem = {'ctx': dev}\n ctx_elem.update(ews_arg_shape)\n ctx_elem.update(ews_arg_dtype)\n ctx_list.append(ctx_elem)\n check_consistency(sym, ctx_list)\n\n\n@with_seed()\ndef test_reshape_with_type():\n sym = mx.sym.Reshape(name='reshape', shape=(-1,1,1,0))\n ctx_list = [{'ctx': mx.gpu(0), 'reshape_data': (2, 2, 2, 10), 'type_dict': {'reshape_data': np.float64}},\n {'ctx': mx.gpu(0), 'reshape_data': (2, 2, 2, 10), 'type_dict': {'reshape_data': np.float32}},\n {'ctx': mx.gpu(0), 'reshape_data': (2, 2, 2, 10), 'type_dict': {'reshape_data': np.float16}},\n {'ctx': mx.cpu(0), 'reshape_data': (2, 2, 2, 10), 'type_dict': {'reshape_data': np.float64}},\n {'ctx': mx.cpu(0), 'reshape_data': (2, 2, 2, 10), 'type_dict': {'reshape_data': np.float32}}]\n check_consistency(sym, ctx_list)\n\n\n@with_seed()\ndef test_blockgrad_with_type():\n sym = mx.sym.BlockGrad(name='bg')\n ctx_list = [{'ctx': mx.gpu(0), 'bg_data': (2, 2, 2, 10), 'type_dict': {'bg_data': np.float64}},\n {'ctx': mx.gpu(0), 'bg_data': (2, 2, 2, 10), 'type_dict': {'bg_data': np.float32}},\n {'ctx': mx.gpu(0), 'bg_data': (2, 2, 2, 10), 'type_dict': {'bg_data': np.float16}},\n {'ctx': mx.cpu(0), 'bg_data': (2, 2, 2, 10), 'type_dict': {'bg_data': np.float64}},\n {'ctx': mx.cpu(0), 'bg_data': (2, 2, 2, 10), 'type_dict': {'bg_data': np.float32}}]\n check_consistency(sym, ctx_list)\n\n\n@with_seed()\ndef test_swapaxis_with_type():\n sym = mx.sym.SwapAxis(name='swap', dim1=1)\n ctx_list = [{'ctx': mx.gpu(0), 'swap_data': (2, 2, 2, 10), 'type_dict': {'swap_data': np.float64}},\n {'ctx': mx.gpu(0), 'swap_data': (2, 2, 2, 10), 'type_dict': {'swap_data': np.float32}},\n {'ctx': mx.gpu(0), 'swap_data': (2, 2, 2, 10), 'type_dict': {'swap_data': np.float16}},\n {'ctx': mx.cpu(0), 'swap_data': (2, 2, 2, 10), 'type_dict': {'swap_data': np.float64}},\n {'ctx': mx.cpu(0), 'swap_data': (2, 2, 2, 10), 'type_dict': {'swap_data': np.float32}}]\n check_consistency(sym, ctx_list)\n\n\n@with_seed()\ndef test_fullyconnected_with_type():\n sym = mx.sym.FullyConnected(num_hidden=3, name='inner')\n ctx_list = [{'ctx': mx.gpu(0), 'inner_data': (2, 10), 'type_dict': {'inner_data': np.float64}},\n {'ctx': mx.gpu(0), 'inner_data': (2, 10), 'type_dict': {'inner_data': np.float32}},\n {'ctx': mx.gpu(0), 'inner_data': (2, 10), 'type_dict': {'inner_data': np.float16}},\n {'ctx': mx.cpu(0), 'inner_data': (2, 10), 'type_dict': {'inner_data': np.float64}},\n {'ctx': mx.cpu(0), 'inner_data': (2, 10), 'type_dict': {'inner_data': np.float32}}]\n check_consistency(sym, ctx_list)\n # Sizes are divisible by 8 to test TensorCore on Volta GPU.\n sym = mx.sym.FullyConnected(num_hidden=8, name='inner')\n ctx_list = [{'ctx': mx.gpu(0), 'inner_data': (16, 24), 'type_dict': {'inner_data': np.float16}},\n {'ctx': mx.cpu(0), 'inner_data': (16, 24), 'type_dict': {'inner_data': np.float32}}]\n check_consistency(sym, ctx_list)\n\n\n@with_seed()\ndef test_activation_with_type():\n act_types = ['relu', 'sigmoid', 'tanh', 'softrelu', 'softsign']\n shape = (2, 2, 10, 10)\n for act_type in act_types:\n sym = mx.sym.Activation(name='act', act_type=act_type)\n ctx_list = [{'ctx': mx.gpu(0), 'act_data': shape, 'type_dict': {'act_data': np.float64}},\n {'ctx': mx.gpu(0), 'act_data': shape, 'type_dict': {'act_data': np.float32}},\n {'ctx': mx.gpu(0), 'act_data': shape, 'type_dict': {'act_data': np.float16}},\n {'ctx': mx.cpu(0), 'act_data': shape, 'type_dict': {'act_data': np.float64}},\n {'ctx': mx.cpu(0), 'act_data': shape, 'type_dict': {'act_data': np.float32}},\n {'ctx': mx.cpu(0), 'act_data': shape, 'type_dict': {'act_data': np.float16}}]\n check_consistency(sym, ctx_list)\n\n\n@with_seed()\ndef test_lrn():\n sym = mx.sym.LRN(alpha=0.0001, beta=0.75, knorm=2, nsize=5, name='lrn')\n ctx_list = [{'ctx': mx.gpu(0), 'lrn_data': (2, 6, 10, 10), 'type_dict': {'lrn_data': np.float32}},\n {'ctx': mx.cpu(0), 'lrn_data': (2, 6, 10, 10), 'type_dict': {'lrn_data': np.float32}}]\n check_consistency(sym, ctx_list)\n\n\n@with_seed()\ndef test_embedding_with_type():\n def test_embedding_helper(data_types, weight_types, low_pad, high_pad):\n NVD = [[20, 10, 20], [200, 10, 300]]\n for N, V, D in NVD:\n sym = mx.sym.Embedding(name='embedding', input_dim=V, output_dim=D)\n ctx_list = []\n for data_type in data_types:\n for weight_type in weight_types:\n ctx_list.append({'ctx': mx.gpu(0), 'embedding_data': (N,),\n 'type_dict': {'embedding_data': data_type, 'embedding_weight': weight_type}})\n ctx_list.append({'ctx': mx.cpu(0), 'embedding_data': (N,),\n 'type_dict': {'embedding_data': data_type, 'embedding_weight': weight_type}})\n arg_params = {'embedding_data': np.random.randint(low=-low_pad, high=V+high_pad, size=(N,))}\n check_consistency(sym, ctx_list, grad_req={'embedding_data': 'null','embedding_weight': 'write'},\n arg_params=arg_params)\n\n data_types = [np.float16, np.float32, np.float64, np.int32]\n weight_types = [np.float16, np.float32, np.float64]\n test_embedding_helper(data_types, weight_types, 5, 5)\n data_types = [np.uint8]\n weight_types = [np.float16, np.float32, np.float64]\n test_embedding_helper(data_types, weight_types, 0, 5)\n\n\n@with_seed()\ndef test_svmoutput_with_type():\n sym = mx.sym.SVMOutput(name='svmoutput', use_linear=True)\n ctx_list = [{'ctx': mx.gpu(0), 'svmoutput_data': (20, 10), 'type_dict': {'svmoutput_data': np.float64}},\n {'ctx': mx.gpu(0), 'svmoutput_data': (20, 10), 'type_dict': {'svmoutput_data': np.float32}},\n {'ctx': mx.gpu(0), 'svmoutput_data': (20, 10), 'type_dict': {'svmoutput_data': np.float16}},\n {'ctx': mx.cpu(0), 'svmoutput_data': (20, 10), 'type_dict': {'svmoutput_data': np.float64}},\n {'ctx': mx.cpu(0), 'svmoutput_data': (20, 10), 'type_dict': {'svmoutput_data': np.float32}},\n {'ctx': mx.cpu(0), 'svmoutput_data': (20, 10), 'type_dict': {'svmoutput_data': np.float16}}]\n check_consistency(sym, ctx_list, use_uniform=True)\n\n\n@with_seed()\ndef test_take_with_type():\n sym = mx.sym.take(name='take')\n for data_ndim in range(2, 5):\n for idx_ndim in range(1, 4):\n data_shape = ()\n for _ in range(data_ndim):\n data_shape += (np.random.randint(low=3, high=6), )\n idx_shape = ()\n for _ in range(idx_ndim):\n idx_shape += (np.random.randint(low=3, high=5), )\n ctx_list = [{'ctx': mx.gpu(0), 'take_indices': idx_shape,\n 'take_a': data_shape,\n 'type_dict': {'take_indices': np.float64,\n 'take_a': np.float64}},\n {'ctx': mx.gpu(0), 'take_indices': idx_shape,\n 'take_a': data_shape,\n 'type_dict': {'take_indices': np.float32,\n 'take_a': np.float32}},\n {'ctx': mx.gpu(0), 'take_indices': idx_shape,\n 'take_a': data_shape,\n 'type_dict': {'take_indices': np.float16,\n 'take_a': np.float16}},\n {'ctx': mx.cpu(0), 'take_indices': idx_shape,\n 'take_a': data_shape,\n 'type_dict': {'take_indices': np.float64,\n 'take_a': np.float64}},\n {'ctx': mx.cpu(0), 'take_indices': idx_shape,\n 'take_a': data_shape,\n 'type_dict': {'take_indices': np.float32,\n 'take_a': np.float32}},\n {'ctx': mx.cpu(0), 'take_indices': idx_shape,\n 'take_a': data_shape,\n 'type_dict': {'take_indices': np.float16,\n 'take_a': np.float16}}]\n arg_params = {'take_indices': np.random.randint(low=0,\n high=data_shape[0],\n size=idx_shape),\n 'take_a': np.random.normal(size=data_shape)}\n check_consistency(sym, ctx_list,\n grad_req={'take_indices': 'null',\n 'take_a': 'write'},\n arg_params=arg_params)\n\n\ndef check_rnn_consistency(cell1, cell2):\n dshape = (32, 5, 200)\n data = mx.sym.Variable('data')\n\n sym1, _ = cell1.unroll(5, data, merge_outputs=True)\n mod1 = mx.mod.Module(sym1, label_names=None, context=mx.gpu(0))\n mod1.bind(data_shapes=[('data', dshape)], label_shapes=None)\n\n sym2, _ = cell2.unroll(5, data, merge_outputs=True)\n mod2 = mx.mod.Module(sym2, label_names=None, context=mx.gpu(0))\n mod2.bind(data_shapes=[('data', dshape)], label_shapes=None)\n\n mod1.init_params()\n args, auxs = mod1.get_params()\n args = cell1.unpack_weights(args)\n args = cell2.pack_weights(args)\n mod2.set_params(args, auxs)\n\n batch=mx.io.DataBatch(data=[mx.random.uniform(shape=dshape)], label=[])\n mod1.forward(batch, is_train=False)\n mod2.forward(batch, is_train=False)\n\n mx.test_utils.assert_allclose(mod1.get_outputs()[0], mod2.get_outputs()[0], rtol=1e-2, atol=1e-4)\n\n@with_seed()\n@assert_raises_cudnn_not_satisfied(min_version='5.1.10')\ndef test_rnn():\n fused = mx.rnn.FusedRNNCell(100, num_layers=2, mode='rnn_relu', prefix='')\n\n stack = mx.rnn.SequentialRNNCell()\n stack.add(mx.rnn.RNNCell(100, activation='relu', prefix='l0_'))\n stack.add(mx.rnn.RNNCell(100, activation='relu', prefix='l1_'))\n\n check_rnn_consistency(fused, stack)\n check_rnn_consistency(stack, fused)\n\n@with_seed()\n@assert_raises_cudnn_not_satisfied(min_version='5.1.10')\ndef test_lstm_forget_bias():\n forget_bias = 2.0\n fused = mx.rnn.FusedRNNCell(10, forget_bias=forget_bias, num_layers=2, mode='lstm', prefix='')\n\n dshape = (32, 1, 20)\n data = mx.sym.Variable('data')\n\n sym, _ = fused.unroll(1, data, merge_outputs=True)\n mod = mx.mod.Module(sym, label_names=None, context=mx.gpu(0))\n mod.bind(data_shapes=[('data', dshape)], label_shapes=None)\n\n mod.init_params()\n\n args, auxs = mod.get_params()\n args = fused.unpack_weights(args)\n\n bias_name = next(x for x in args if x.endswith('f_bias'))\n expected_bias = forget_bias * np.ones(10, )\n mx.test_utils.assert_allclose(args[bias_name], expected_bias)\n\n@with_seed()\n@assert_raises_cudnn_not_satisfied(min_version='5.1.10')\ndef test_gru():\n fused = mx.rnn.FusedRNNCell(100, num_layers=2, mode='gru', prefix='')\n\n stack = mx.rnn.SequentialRNNCell()\n stack.add(mx.rnn.GRUCell(100, prefix='l0_'))\n stack.add(mx.rnn.GRUCell(100, prefix='l1_'))\n\n check_rnn_consistency(fused, stack)\n check_rnn_consistency(stack, fused)\n\n@with_seed()\n@assert_raises_cudnn_not_satisfied(min_version='5.1.10')\ndef test_bidirectional():\n fused = mx.rnn.FusedRNNCell(100, num_layers=2, mode='gru', prefix='',\n bidirectional=True)\n\n stack = mx.rnn.SequentialRNNCell()\n stack.add(mx.rnn.BidirectionalCell(\n mx.rnn.GRUCell(100, prefix='l0_'),\n mx.rnn.GRUCell(100, prefix='r0_'),\n output_prefix='bi_gru_0_'))\n stack.add(mx.rnn.BidirectionalCell(\n mx.rnn.GRUCell(100, prefix='l1_'),\n mx.rnn.GRUCell(100, prefix='r1_'),\n output_prefix='bi_gru_1_'))\n\n check_rnn_consistency(fused, stack)\n check_rnn_consistency(stack, fused)\n\n@with_seed()\n@assert_raises_cudnn_not_satisfied(min_version='5.1.10')\ndef test_unfuse():\n for mode in ['rnn_tanh', 'rnn_relu', 'lstm', 'gru']:\n fused = mx.rnn.FusedRNNCell(\n 100, num_layers=2, mode=mode,\n prefix='test_%s'%mode,\n bidirectional=True,\n dropout=0.5)\n\n stack = fused.unfuse()\n\n check_rnn_consistency(fused, stack)\n check_rnn_consistency(stack, fused)\n\n\n@with_seed()\ndef test_psroipooling_with_type():\n arg_params = {\n 'psroipool_rois': np.array([[0, 10, 22, 161, 173], [0, 20, 15, 154, 160]])}\n\n # plain psroipooling\n sym = mx.sym.contrib.PSROIPooling(spatial_scale=0.0625, output_dim=2, pooled_size=3, name='psroipool')\n ctx_list = [{'ctx': mx.gpu(0),\n 'psroipool_data': (1, 18, 14, 14),\n 'psroipool_rois': (2, 5),\n 'type_dict': {'psroipool_data': np.float64, 'psroipool_rois': np.float64}},\n {'ctx': mx.gpu(0),\n 'psroipool_data': (1, 18, 14, 14),\n 'psroipool_rois': (2, 5),\n 'type_dict': {'psroipool_data': np.float32, 'psroipool_rois': np.float32}},\n {'ctx': mx.gpu(0),\n 'psroipool_data': (1, 18, 14, 14),\n 'psroipool_rois': (2, 5),\n 'type_dict': {'psroipool_data': np.float16, 'psroipool_rois': np.float16}},\n ]\n\n check_consistency(sym, ctx_list, grad_req={'psroipool_data': 'write',\n 'psroipool_rois': 'null'}, arg_params=arg_params)\n\n\n@with_seed()\ndef test_deformable_psroipooling_with_type():\n tol = {np.dtype(np.float32): 1e-1,\n np.dtype(np.float64): 1e-3,\n np.dtype(np.float16): 1e-2}\n\n arg_params = {\n 'deformable_psroipool_rois': np.array([[0, 10, 22, 161, 173], [0, 20, 15, 154, 160]])}\n\n # deformable psroipooling\n sym = mx.sym.contrib.DeformablePSROIPooling(spatial_scale=0.0625, sample_per_part=4, group_size=3, pooled_size=3,\n output_dim=2, trans_std=0.1, no_trans=False, name='deformable_psroipool')\n\n ctx_list = [{'ctx': mx.gpu(0),\n 'deformable_psroipool_data': (1, 18, 14, 14),\n 'deformable_psroipool_rois': (2, 5),\n 'deformable_psroipool_trans': (2, 4, 3, 3),\n 'type_dict': {'deformable_psroipool_data': np.float64, 'deformable_psroipool_rois': np.float64,\n 'deformable_psroipool_trans': np.float64}},\n {'ctx': mx.gpu(0),\n 'deformable_psroipool_data': (1, 18, 14, 14),\n 'deformable_psroipool_rois': (2, 5),\n 'deformable_psroipool_trans': (2, 4, 3, 3),\n 'type_dict': {'deformable_psroipool_data': np.float32, 'deformable_psroipool_rois': np.float32,\n 'deformable_psroipool_trans': np.float32}},\n {'ctx': mx.gpu(0),\n 'deformable_psroipool_data': (1, 18, 14, 14),\n 'deformable_psroipool_rois': (2, 5),\n 'deformable_psroipool_trans': (2, 4, 3, 3),\n 'type_dict': {'deformable_psroipool_data': np.float16, 'deformable_psroipool_rois': np.float16,\n 'deformable_psroipool_trans': np.float16}},\n {'ctx': mx.cpu(0),\n 'deformable_psroipool_data': (1, 18, 14, 14),\n 'deformable_psroipool_rois': (2, 5),\n 'deformable_psroipool_trans': (2, 4, 3, 3),\n 'type_dict': {'deformable_psroipool_data': np.float64, 'deformable_psroipool_rois': np.float64,\n 'deformable_psroipool_trans': np.float64}},\n {'ctx': mx.cpu(0),\n 'deformable_psroipool_data': (1, 18, 14, 14),\n 'deformable_psroipool_rois': (2, 5),\n 'deformable_psroipool_trans': (2, 4, 3, 3),\n 'type_dict': {'deformable_psroipool_data': np.float32, 'deformable_psroipool_rois': np.float32,\n 'deformable_psroipool_trans': np.float32}},\n {'ctx': mx.cpu(0),\n 'deformable_psroipool_data': (1, 18, 14, 14),\n 'deformable_psroipool_rois': (2, 5),\n 'deformable_psroipool_trans': (2, 4, 3, 3),\n 'type_dict': {'deformable_psroipool_data': np.float16, 'deformable_psroipool_rois': np.float16,\n 'deformable_psroipool_trans': np.float16}},\n ]\n\n check_consistency(sym, ctx_list, scale=0.1, tol=tol,\n grad_req={'deformable_psroipool_data': 'write',\n 'deformable_psroipool_rois': 'null',\n 'deformable_psroipool_trans': 'write'}, arg_params=arg_params)\n\n\n@with_seed()\ndef test_deformable_convolution_with_type():\n tol = {np.dtype(np.float32): 1e-1,\n np.dtype(np.float64): 1e-3}\n\n sym = mx.sym.contrib.DeformableConvolution(num_filter=3, kernel=(3,3), name='deformable_conv')\n # since atomicAdd does not support fp16 (which deformable conv uses in backward), we do not test fp16 here\n ctx_list = [{'ctx': mx.gpu(0),\n 'deformable_conv_data': (2, 2, 10, 10),\n 'deformable_conv_offset': (2, 18, 8, 8),\n 'type_dict': {'deformable_conv_data': np.float64, 'deformable_conv_offset': np.float64}},\n {'ctx': mx.gpu(0),\n 'deformable_conv_data': (2, 2, 10, 10),\n 'deformable_conv_offset': (2, 18, 8, 8),\n 'type_dict': {'deformable_conv_data': np.float32, 'deformable_conv_offset': np.float32}},\n {'ctx': mx.cpu(0),\n 'deformable_conv_data': (2, 2, 10, 10),\n 'deformable_conv_offset': (2, 18, 8, 8),\n 'type_dict': {'deformable_conv_data': np.float64, 'deformable_conv_offset': np.float64}},\n {'ctx': mx.cpu(0),\n 'deformable_conv_data': (2, 2, 10, 10),\n 'deformable_conv_offset': (2, 18, 8, 8),\n 'type_dict': {'deformable_conv_data': np.float32, 'deformable_conv_offset': np.float32}},\n ]\n\n check_consistency(sym, ctx_list, scale=0.1, tol=tol)\n # test ability to turn off training on bias\n check_consistency(sym, ctx_list, scale=0.1, tol=tol,\n grad_req={'deformable_conv_data': 'write',\n 'deformable_conv_offset': 'write',\n 'deformable_conv_weight': 'write',\n 'deformable_conv_bias': 'null'})\n\n\n@with_seed()\ndef test_deformable_convolution_options():\n tol = {np.dtype(np.float32): 1e-1,\n np.dtype(np.float64): 1e-3}\n # 2D convolution\n # since atomicAdd does not support fp16 (which deformable conv uses in backward), we do not test fp16 here\n\n # Pad > 0\n ctx_list = [{'ctx': mx.gpu(0),\n 'deformable_conv_data': (2, 2, 7, 7),\n 'deformable_conv_offset': (2, 18, 7, 7),\n 'type_dict': {'deformable_conv_data': np.float64, 'deformable_conv_offset': np.float64}},\n {'ctx': mx.gpu(0),\n 'deformable_conv_data': (2, 2, 7, 7),\n 'deformable_conv_offset': (2, 18, 7, 7),\n 'type_dict': {'deformable_conv_data': np.float32, 'deformable_conv_offset': np.float32}},\n {'ctx': mx.cpu(0),\n 'deformable_conv_data': (2, 2, 7, 7),\n 'deformable_conv_offset': (2, 18, 7, 7),\n 'type_dict': {'deformable_conv_data': np.float64, 'deformable_conv_offset': np.float64}},\n {'ctx': mx.cpu(0),\n 'deformable_conv_data': (2, 2, 7, 7),\n 'deformable_conv_offset': (2, 18, 7, 7),\n 'type_dict': {'deformable_conv_data': np.float32, 'deformable_conv_offset': np.float32}},\n ]\n sym = mx.sym.contrib.DeformableConvolution(num_filter=3, kernel=(3,3), pad=(1,1), name='deformable_conv')\n check_consistency(sym, ctx_list, scale=0.1, tol=tol)\n\n # Stride > 1\n ctx_list = [{'ctx': mx.gpu(0),\n 'deformable_conv_data': (2, 2, 7, 7),\n 'deformable_conv_offset': (2, 18, 3, 3),\n 'type_dict': {'deformable_conv_data': np.float64, 'deformable_conv_offset': np.float64}},\n {'ctx': mx.gpu(0),\n 'deformable_conv_data': (2, 2, 7, 7),\n 'deformable_conv_offset': (2, 18, 3, 3),\n 'type_dict': {'deformable_conv_data': np.float32, 'deformable_conv_offset': np.float32}},\n {'ctx': mx.cpu(0),\n 'deformable_conv_data': (2, 2, 7, 7),\n 'deformable_conv_offset': (2, 18, 3, 3),\n 'type_dict': {'deformable_conv_data': np.float64, 'deformable_conv_offset': np.float64}},\n {'ctx': mx.cpu(0),\n 'deformable_conv_data': (2, 2, 7, 7),\n 'deformable_conv_offset': (2, 18, 3, 3),\n 'type_dict': {'deformable_conv_data': np.float32, 'deformable_conv_offset': np.float32}},\n ]\n sym = mx.sym.contrib.DeformableConvolution(num_filter=3, kernel=(3,3), stride=(2,2), name='deformable_conv')\n check_consistency(sym, ctx_list, scale=0.1, tol=tol)\n\n # Dilate > 1\n ctx_list = [{'ctx': mx.gpu(0),\n 'deformable_conv_data': (2, 2, 7, 7),\n 'deformable_conv_offset': (2, 18, 3, 3),\n 'type_dict': {'deformable_conv_data': np.float64, 'deformable_conv_offset': np.float64}},\n {'ctx': mx.gpu(0),\n 'deformable_conv_data': (2, 2, 7, 7),\n 'deformable_conv_offset': (2, 18, 3, 3),\n 'type_dict': {'deformable_conv_data': np.float32, 'deformable_conv_offset': np.float32}},\n {'ctx': mx.cpu(0),\n 'deformable_conv_data': (2, 2, 7, 7),\n 'deformable_conv_offset': (2, 18, 3, 3),\n 'type_dict': {'deformable_conv_data': np.float64, 'deformable_conv_offset': np.float64}},\n {'ctx': mx.cpu(0),\n 'deformable_conv_data': (2, 2, 7, 7),\n 'deformable_conv_offset': (2, 18, 3, 3),\n 'type_dict': {'deformable_conv_data': np.float32, 'deformable_conv_offset': np.float32}},\n ]\n sym = mx.sym.contrib.DeformableConvolution(num_filter=3, kernel=(3,3), dilate=(2,2), name='deformable_conv')\n check_consistency(sym, ctx_list, scale=0.1, tol=tol)\n\n # Deformable group > 1\n ctx_list = [{'ctx': mx.gpu(0),\n 'deformable_conv_data': (2, 2, 7, 7),\n 'deformable_conv_offset': (2, 36, 5, 5),\n 'type_dict': {'deformable_conv_data': np.float64, 'deformable_conv_offset': np.float64}},\n {'ctx': mx.gpu(0),\n 'deformable_conv_data': (2, 2, 7, 7),\n 'deformable_conv_offset': (2, 36, 5, 5),\n 'type_dict': {'deformable_conv_data': np.float32, 'deformable_conv_offset': np.float32}},\n {'ctx': mx.cpu(0),\n 'deformable_conv_data': (2, 2, 7, 7),\n 'deformable_conv_offset': (2, 36, 5, 5),\n 'type_dict': {'deformable_conv_data': np.float64, 'deformable_conv_offset': np.float64}},\n {'ctx': mx.cpu(0),\n 'deformable_conv_data': (2, 2, 7, 7),\n 'deformable_conv_offset': (2, 36, 5, 5),\n 'type_dict': {'deformable_conv_data': np.float32, 'deformable_conv_offset': np.float32}},\n ]\n sym = mx.sym.contrib.DeformableConvolution(num_filter=4, kernel=(3,3), num_deformable_group=2, name='deformable_conv')\n check_consistency(sym, ctx_list, scale=0.1, tol=tol)\n\n\n@with_seed()\n@assert_raises_cudnn_not_satisfied(min_version='5.1.10')\ndef test_residual_fused():\n cell = mx.rnn.ResidualCell(\n mx.rnn.FusedRNNCell(50, num_layers=3, mode='lstm',\n prefix='rnn_', dropout=0.5))\n\n inputs = [mx.sym.Variable('rnn_t%d_data'%i) for i in range(2)]\n outputs, _ = cell.unroll(2, inputs, merge_outputs=None)\n assert sorted(cell.params._params.keys()) == \\\n ['rnn_parameters']\n\n args, outs, auxs = outputs.infer_shape(rnn_t0_data=(10, 50), rnn_t1_data=(10, 50))\n assert outs == [(10, 2, 50)]\n outputs = outputs.eval(ctx=mx.gpu(0),\n rnn_t0_data=mx.nd.ones((10, 50), ctx=mx.gpu(0))+5,\n rnn_t1_data=mx.nd.ones((10, 50), ctx=mx.gpu(0))+5,\n rnn_parameters=mx.nd.zeros((61200,), ctx=mx.gpu(0)))\n expected_outputs = np.ones((10, 2, 50))+5\n assert np.array_equal(outputs[0].asnumpy(), expected_outputs)\n\n\ndef check_rnn_layer(layer):\n layer.collect_params().initialize(ctx=[mx.cpu(0), mx.gpu(0)])\n with mx.gpu(0):\n x = mx.nd.ones((10, 16, 30))\n states = layer.begin_state(16)\n go, gs = layer(x, states)\n\n with mx.cpu(0):\n x = mx.nd.ones((10, 16, 30))\n states = layer.begin_state(16)\n co, cs = layer(x, states)\n\n # atol of 1e-6 required, as exposed by seed 2124685726\n assert_almost_equal(go, co, rtol=1e-2, atol=1e-6)\n for g, c in zip(gs, cs):\n assert_almost_equal(g, c, rtol=1e-2, atol=1e-6)\n\ndef check_rnn_layer_w_rand_inputs(layer):\n layer.collect_params().initialize(ctx=[mx.cpu(0), mx.gpu(0)])\n x = mx.nd.uniform(shape=(10, 16, 30))\n with mx.gpu(0):\n x = x.copyto(mx.gpu(0))\n states = layer.begin_state(16)\n go, gs = layer(x, states)\n\n with mx.cpu(0):\n x = x.copyto(mx.cpu(0))\n states = layer.begin_state(16)\n co, cs = layer(x, states)\n\n assert_almost_equal(go, co, rtol=1e-2, atol=1e-6)\n for g, c in zip(gs, cs):\n assert_almost_equal(g, c, rtol=1e-2, atol=1e-6)\n\n@with_seed()\ndef test_sequence_reverse():\n check_sequence_reverse(mx.gpu(0))\n\n\n@with_seed()\ndef test_autograd_save_memory():\n x = mx.nd.zeros((128, 512, 512), ctx=mx.gpu(0))\n x.attach_grad()\n\n with mx.autograd.record():\n for i in range(200):\n x = x + 1\n x.wait_to_read()\n x.backward()\n\n\n@with_seed()\ndef test_cuda_rtc():\n source = r'''\n extern \"C\" __global__ void axpy(const float *x, float *y, float alpha) {\n int i = threadIdx.x + blockIdx.x * blockDim.x;\n y[i] += alpha * x[i];\n }\n\n extern \"C\" __global__ void saxpy(const float *x, float *y, float alpha) {\n extern __shared__ float smem[];\n int i = threadIdx.x + blockIdx.x * blockDim.x;\n smem[threadIdx.x] = x[i];\n y[i] += alpha * smem[threadIdx.x];\n }\n '''\n module = mx.rtc.CudaModule(source)\n axpy = module.get_kernel(\"axpy\", \"const float *x, float *y, float alpha\")\n x = mx.nd.ones((10,), ctx=mx.gpu(0))\n y = mx.nd.zeros((10,), ctx=mx.gpu(0))\n axpy.launch([x, y, 3.0], mx.gpu(0), (1, 1, 1), (10, 1, 1))\n assert (y.asnumpy() == 3).all()\n\n saxpy = module.get_kernel(\"saxpy\", \"const float *x, float *y, float alpha\")\n saxpy.launch([x, y, 4.0], mx.gpu(0), (1, 1, 1), (10, 1, 1), 10)\n assert (y.asnumpy() == 7).all()\n\n saxpy.launch([x, y, 5.0], mx.gpu(0), (2, 1, 1), (5, 1, 1), 5)\n assert (y.asnumpy() == 12).all()\n\n\n@with_seed()\ndef test_cross_device_autograd():\n x = mx.nd.random.uniform(shape=(10,))\n x.attach_grad()\n\n with mx.autograd.record():\n y = mx.nd.tanh(x)\n y = y.copyto(mx.gpu(0))\n y = mx.nd.tanh(y)\n y = y.copyto(mx.cpu(0))\n y = mx.nd.tanh(y)\n y = y.copyto(mx.gpu(0))\n y = y.copyto(mx.gpu(0))\n\n y.backward()\n\n dx = x.grad.copy()\n x.grad[:] = 0\n\n with mx.autograd.record():\n y = x\n for i in range(3):\n y = mx.nd.tanh(y)\n y.backward()\n\n assert_almost_equal(dx, x.grad)\n\n@with_seed()\ndef test_multi_proposal_op():\n # paramters\n feature_stride = 16\n scales = (8, 16, 32)\n ratios = (0.5, 1, 2)\n rpn_pre_nms_top_n = 12000\n rpn_post_nms_top_n = 2000\n rpn_min_size = feature_stride\n\n feat_len = (1000 + 15) // 16\n H, W = feat_len, feat_len\n num_anchors = len(scales) * len(ratios)\n count_anchors = H * W * num_anchors\n\n def get_new_data(batch_size, ctx):\n '''\n cls_prob: (batch_size, 2 * num_anchors, H, W)\n bbox_pred: (batch_size, 4 * num_anchors, H, W)\n im_info: (batch_size, 3)\n '''\n\n dtype = np.float32\n cls_prob = mx.nd.empty((batch_size, 2 * num_anchors, H, W), dtype = dtype, ctx = ctx)\n bbox_pred = mx.nd.empty((batch_size, 4 * num_anchors, H, W), dtype = dtype, ctx = ctx)\n im_info = mx.nd.empty((batch_size, 3), dtype = dtype, ctx = ctx)\n\n cls = [1.0 * (i + 1) / cls_prob.size for i in range(cls_prob.size)]\n np.random.shuffle(cls)\n cls_prob = mx.nd.reshape(mx.nd.array(cls, dtype = dtype, ctx = ctx), shape = cls_prob.shape)\n bbox_pred = mx.nd.array(np.random.randint(-2, 3, size = bbox_pred.shape), dtype = dtype, ctx = ctx)\n\n for i in range(batch_size):\n im_size = np.random.randint(600, feat_len * feature_stride, size = (2,))\n im_scale = np.random.randint(80, 100) / 100.0\n im_info[i, :] = [im_size[0], im_size[1], im_scale]\n return cls_prob, bbox_pred, im_info\n\n def check_proposal_consistency(op, batch_size, with_nms=False):\n '''\n op is mx.nd.contrib.Proposal or mx.nd.contrib.MultiProposal\n '''\n cls_prob, bbox_pred, im_info = get_new_data(batch_size, mx.cpu(0))\n rois_cpu, score_cpu = op(\n cls_prob = cls_prob,\n bbox_pred = bbox_pred,\n im_info = im_info,\n feature_stride = feature_stride,\n scales = scales,\n ratios = ratios,\n rpn_pre_nms_top_n = rpn_pre_nms_top_n,\n rpn_post_nms_top_n = rpn_post_nms_top_n,\n threshold = 0.7 if with_nms else 1.0,\n rpn_min_size = rpn_min_size, output_score = True)\n\n gpu_ctx = mx.gpu(0)\n\n # copy data to gpu from cpu\n cls_prob_gpu = cls_prob.as_in_context(gpu_ctx)\n bbox_pred_gpu = bbox_pred.as_in_context(gpu_ctx)\n im_info_gpu = im_info.as_in_context(gpu_ctx)\n\n rois_gpu, score_gpu = op(\n cls_prob = cls_prob_gpu,\n bbox_pred = bbox_pred_gpu,\n im_info = im_info_gpu,\n feature_stride = feature_stride,\n scales = scales,\n ratios = ratios,\n rpn_pre_nms_top_n = rpn_pre_nms_top_n,\n rpn_post_nms_top_n = rpn_post_nms_top_n,\n threshold = 0.7 if with_nms else 1.0,\n rpn_min_size = rpn_min_size, output_score = True)\n\n rois_cpu_np = rois_cpu.asnumpy()\n rois_gpu_np = rois_gpu.asnumpy()\n\n score_cpu_np = score_cpu.asnumpy()\n score_gpu_np = score_gpu.asnumpy()\n\n if not with_nms:\n assert_almost_equal(score_cpu_np, score_gpu_np, atol = 1e-3, rtol = 1e-3)\n assert_almost_equal(rois_cpu_np, rois_gpu_np, atol = 1e-3, rtol = 1e-3)\n else:\n # no 100% gurantee with nms\n assert(np.sum(np.abs(score_cpu_np - score_gpu_np) < 1e-3) >= 10)\n assert(np.sum(np.abs(rois_cpu_np - rois_gpu_np) < 1e-3) >= 40)\n\n check_proposal_consistency(mx.nd.contrib.Proposal, 1)\n check_proposal_consistency(mx.nd.contrib.MultiProposal, 5)\n check_proposal_consistency(mx.nd.contrib.Proposal, 1, with_nms=True)\n check_proposal_consistency(mx.nd.contrib.MultiProposal, 5, with_nms=True)\n\n\n# The following 2 functions launch 0-thread kernels, an error that should be caught and signaled.\ndef kernel_error_check_imperative():\n os.environ['MXNET_ENGINE_TYPE'] = 'NaiveEngine'\n with mx.np_shape(active=True):\n a = mx.nd.array([1,2,3],ctx=mx.gpu(0))\n b = mx.nd.array([],ctx=mx.gpu(0))\n c = (a / b).asnumpy()\n\ndef kernel_error_check_symbolic():\n os.environ['MXNET_ENGINE_TYPE'] = 'NaiveEngine'\n with mx.np_shape(active=True):\n a = mx.sym.Variable('a')\n b = mx.sym.Variable('b')\n c = a / b\n f = c.bind(mx.gpu(0), { 'a':mx.nd.array([1,2,3],ctx=mx.gpu(0)),\n 'b':mx.nd.array([],ctx=mx.gpu(0))})\n f.forward()\n g = f.outputs[0].asnumpy()\n\ndef test_kernel_error_checking():\n # Running tests that may throw exceptions out of worker threads will stop CI testing\n # if not run in a separate process (with its own address space for CUDA compatibility).\n try:\n mpctx = mp.get_context('spawn')\n except:\n print('SKIP: python%s.%s lacks the required process fork-exec support ... ' %\n sys.version_info[0:2], file=sys.stderr, end='')\n else:\n with discard_stderr():\n for f in [kernel_error_check_imperative, kernel_error_check_symbolic]:\n p = mpctx.Process(target=f)\n p.start()\n p.join()\n assert p.exitcode != 0,\\\n \"Expected a synchronous kernel error from %s(), none seen.\" % f.__name__\n\ndef test_incorrect_gpu():\n # Try setting dev_id to a really big number\n pytest.raises(MXNetError, mx.nd.ones, (2,2), ctx=mx.gpu(100001))\n\n@with_seed()\ndef test_batchnorm_backwards_notrain():\n for ctx in [mx.cpu(0), mx.gpu(0)]:\n for cudnn_o in [False, True]:\n B,C,H,W = 4,3,2,2\n x = mx.nd.random.poisson(1,shape=(B,C,H,W)).as_in_context(ctx)\n gamma = mx.nd.random.normal(shape=(C)).as_in_context(ctx)\n beta = mx.nd.random.normal(shape=(C)).as_in_context(ctx)\n mean = mx.nd.random.normal(shape=(C)).as_in_context(ctx)\n std = mx.nd.random.normal(shape=(C)).as_in_context(ctx)\n x.attach_grad()\n\n with autograd.record(False):\n y = mx.ndarray.BatchNorm(x, gamma, beta, mean, std.square(),\n fix_gamma=False, cudnn_off=cudnn_o)\n loss=y.square().sum()\n loss.backward(train_mode=False)\n\n@with_seed()\ndef test_create_sparse_ndarray_gpu_to_cpu():\n dim0 = 10\n dim1 = 5\n densities = [0, 0.5, 1]\n for density in densities:\n shape = rand_shape_2d(dim0, dim1)\n matrix = rand_ndarray(shape, 'row_sparse', density)\n data = matrix.data\n indices = matrix.indices\n rsp_created = mx.nd.sparse.row_sparse_array((data, indices), shape=shape, ctx=mx.cpu())\n assert rsp_created.stype == 'row_sparse'\n assert same(rsp_created.data.asnumpy(), data.asnumpy())\n assert same(rsp_created.indices.asnumpy(), indices.asnumpy())\n rsp_copy = mx.nd.array(rsp_created)\n assert(same(rsp_copy.asnumpy(), rsp_created.asnumpy()))\n\n\n@with_seed()\ndef test_softmax_activation():\n gpu_a = mx.nd.array([[3., 0.5, -0.5, 2., 7.],\n [2., -.4, 7., 3., 0.2]], ctx=mx.gpu(0))\n cpu_a = mx.nd.array([[3., 0.5, -0.5, 2., 7.],\n [2., -.4, 7., 3., 0.2]], ctx=mx.cpu())\n\n cpu_a.attach_grad()\n gpu_a.attach_grad()\n with mx.autograd.record():\n gpu_y = mx.nd.SoftmaxActivation(data = gpu_a)\n cpu_y = mx.nd.SoftmaxActivation(data = cpu_a)\n assert_almost_equal(cpu_y, gpu_y, atol = 1e-3, rtol = 1e-3)\n\n gpu_y.backward()\n cpu_y.backward()\n assert_almost_equal(cpu_a.grad, gpu_a.grad, atol = 1e-3, rtol = 1e-3)\n\n\n@with_seed()\ndef test_bilinear_sampler_versions():\n data = mx.sym.Variable('data')\n grid = mx.sym.Variable('grid')\n sym1 = mx.sym.BilinearSampler(data=data, grid=grid)\n sym2 = mx.sym.BilinearSampler(data=data, grid=grid, cudnn_off=True)\n sym3 = mx.sym.BilinearSampler(data=data, grid=grid)\n\n test_cases = [[(1,3,15,16),(1,2,10,10)],\n [(1,6,7,16),(1,2,10,4)],\n [(1,7,3,16),(1,2,8,11)],\n [(1,9,50,50),(1,2,50,50)]]\n\n for item in test_cases:\n data_shape, grid_shape = item\n # kWriteTo\n exe_cpu = sym1.simple_bind(data=data_shape, grid=grid_shape, ctx=mx.cpu(), grad_req='write')\n exe_gpu = sym2.simple_bind(data=data_shape, grid=grid_shape, ctx=default_context(), grad_req='write')\n exe_cudnn = sym3.simple_bind(data=data_shape, grid=grid_shape, ctx=default_context(), grad_req='write')\n exe_list = [exe_cpu, exe_gpu, exe_cudnn]\n ref_idx = 0\n test_data = np.random.uniform(low=-0.1, high=0.1,size=data_shape).astype(np.float32)\n test_grid = np.random.uniform(low=-2, high=2, size=grid_shape).astype(np.float32)\n for exe in exe_list:\n exe.arg_dict['data'][:] = test_data\n exe.arg_dict['grid'][:] = test_grid\n exe.forward(is_train=True)\n mx.test_utils.assert_almost_equal(exe_list[ref_idx].outputs[0], exe.outputs[0], rtol=1e-3, atol=1e-5)\n\n out_grad = np.random.uniform(low=-0.01, high=0.01,size=data_shape[:2] + grid_shape[2:]).astype(np.float32)\n for exe in exe_list:\n exe.backward(mx.nd.array(out_grad))\n assert_almost_equal(exe.grad_dict['data'], exe_list[ref_idx].grad_dict['data'], rtol=1e-3, atol=1e-5)\n assert_almost_equal(exe.grad_dict['grid'], exe_list[ref_idx].grad_dict['grid'], rtol=1e-3, atol=1e-5)\n\n data_grad = exe_list[ref_idx].grad_dict['data'].asnumpy()\n grid_grad = exe_list[ref_idx].grad_dict['grid'].asnumpy()\n\n # kAddTo\n exe_cpu_addto = sym1.simple_bind(data=data_shape, grid=grid_shape, ctx=mx.cpu(), grad_req='add')\n exe_gpu_addto = sym2.simple_bind(data=data_shape, grid=grid_shape, ctx=default_context(), grad_req='add')\n exe_cudnn_addto = sym3.simple_bind(data=data_shape, grid=grid_shape, ctx=default_context(), grad_req='add')\n exe_list = [exe_cpu_addto, exe_gpu_addto, exe_cudnn_addto]\n data_initial_grad = np.random.normal(size=exe_list[ref_idx].grad_dict['data'].shape).astype(np.float32)\n grid_initial_grad = np.random.normal(size=exe_list[ref_idx].grad_dict['grid'].shape).astype(np.float32)\n for exe in exe_list:\n exe.arg_dict['data'][:] = test_data\n exe.arg_dict['grid'][:] = test_grid\n exe.grad_dict['data'][:] = data_initial_grad\n exe.grad_dict['grid'][:] = grid_initial_grad\n exe.forward(is_train=True)\n exe.backward(mx.nd.array(out_grad))\n assert_almost_equal(exe.grad_dict['data'], exe_list[ref_idx].grad_dict['data'], rtol=1e-3, atol=1e-5)\n assert_almost_equal(exe.grad_dict['grid'], exe_list[ref_idx].grad_dict['grid'], rtol=1e-3, atol=1e-5)\n assert_almost_equal(exe_list[ref_idx].grad_dict['data'], data_grad + data_initial_grad, rtol=1e-3, atol=1e-5)\n assert_almost_equal(exe_list[ref_idx].grad_dict['grid'], grid_grad + grid_initial_grad, rtol=1e-3, atol=1e-5)\n\n for req_dict in [{'data' : 'null', 'grid' : 'write'}, {'data' : 'write', 'grid' : 'null'}]:\n # Mixture of kWriteTo and kNullOp\n exe_cpu_mix = sym1.simple_bind(data=data_shape, grid=grid_shape, ctx=mx.cpu(), grad_req=req_dict)\n exe_gpu_mix = sym2.simple_bind(data=data_shape, grid=grid_shape, ctx=default_context(), grad_req=req_dict)\n exe_cudnn_mix = sym3.simple_bind(data=data_shape, grid=grid_shape, ctx=default_context(), grad_req=req_dict)\n exe_list = [exe_cpu_mix, exe_gpu_mix, exe_cudnn_mix]\n for exe in exe_list:\n exe.arg_dict['data'][:] = test_data\n exe.arg_dict['grid'][:] = test_grid\n exe.forward(is_train=True)\n exe.backward(mx.nd.array(out_grad))\n if req_dict['data'] is 'write':\n assert_almost_equal(exe.grad_dict['data'], exe_list[ref_idx].grad_dict['data'], rtol=1e-3, atol=1e-5)\n if req_dict['grid'] is 'write':\n assert_almost_equal(exe.grad_dict['grid'], exe_list[ref_idx].grad_dict['grid'], rtol=1e-3, atol=1e-5)\n\n\n# isolated execution bulking test function to be invoked with different env var settings\ndef _test_bulking_in_process(seed, time_per_iteration):\n data_shape = (10,)\n num_ops = 1000\n num_iterations = 20\n\n ctx = default_context()\n # build symbol\n X = mx.sym.Variable('X')\n sym = mx.sym.flip(X, axis=0)\n for _ in range(num_ops-1):\n sym = mx.sym.flip(sym, axis=0)\n x = mx.ndarray.zeros(data_shape)\n dx = mx.ndarray.zeros(data_shape)\n dy = mx.ndarray.ones(data_shape)\n exe = sym.bind(ctx=ctx, args=[x], args_grad = {'X':dx})\n\n # time a number of forward() and backward() executions after some warm-up iterations\n warmups = 1\n for i in range(num_iterations+warmups):\n if i == warmups:\n start = time.time()\n exe.forward(is_train=True)\n exe.backward(dy)\n dx.wait_to_read()\n time_per_iteration.value = (time.time() - start) / num_iterations\n\n\n@with_seed()\[email protected]('skippping temporarily, tracked by https://github.com/apache/incubator-mxnet/issues/16517')\ndef test_bulking_operator_gpu():\n _test_bulking(_test_bulking_in_process)\n\n\[email protected]('skippping temporarily, tracked by https://github.com/apache/incubator-mxnet/issues/14970')\ndef test_bulking():\n # test case format: (max_fwd_segment_size, max_bwd_segment_size, enable_bulking_in_training)\n test_cases = [(0,0,True), (1,1,True), (15,15,False), (15,0,True), (0,15,True), (15,15,True)]\n times = {}\n times_str = ''\n for seg_sizes in test_cases:\n # Create shared variable to return measured time from test process\n time_per_iteration = mp.Manager().Value('d', 0.0)\n if not run_in_spawned_process(_test_bulking_in_process,\n {'MXNET_EXEC_BULK_EXEC_MAX_NODE_TRAIN_FWD' : seg_sizes[0],\n 'MXNET_EXEC_BULK_EXEC_MAX_NODE_TRAIN_BWD' : seg_sizes[1],\n 'MXNET_EXEC_BULK_EXEC_TRAIN' : seg_sizes[2]},\n time_per_iteration):\n # skip test since the python version can't run it properly. Warning msg was logged.\n return\n times[seg_sizes] = time_per_iteration.value\n times_str += \\\n '\\n runtime of (fwd,bwd,enable) op seg setting ({},{},{}) =\\t{:.1f} msec'.format(\n seg_sizes[0], seg_sizes[1], seg_sizes[2], 1000.0 * times[seg_sizes])\n\n fastest_non_bulked_time = min(times[(0,0,True)], times[(1,1,True)], times[(15,15,False)])\n slowest_half_bulked_time = max(times[(0,15,True)], times[(15,0,True)])\n fastest_half_bulked_time = min(times[(0,15,True)], times[(15,0,True)])\n fully_bulked_time = times[(15,15,True)]\n\n print(times_str)\n # Non-bulked times[0,0,True], times[1,1,True] and times[15,15,False] should be about the same,\n # slower than both half-bulked times[0,15,True] and times[15,0,True]\n assert slowest_half_bulked_time < fastest_non_bulked_time, \\\n 'A half-bulked exec time is slower than the non-bulked time by {} secs! {}' \\\n .format(slowest_half_bulked_time - fastest_non_bulked_time, times_str)\n # The fully bulked times[15,15,True] should be faster than both half-bulked runs\n assert fully_bulked_time < fastest_half_bulked_time, \\\n 'The fully-bulked exec time is slower than a half-bulked time by {} secs! {}' \\\n .format(fully_bulked_time - fastest_half_bulked_time, times_str)\n\n\n@with_seed()\ndef test_allclose_function_gpu():\n allclose_function([mx.cpu(), mx.gpu(0)])\n\ndef test_context_num_gpus():\n # Test that num_gpus reports at least one GPU, as the test is run on a GPU host.\n assert mx.context.num_gpus() > 0\n\ndef math_log(shape, dtype, check_value):\n np_x = np.random.rand(*tuple(shape))\n x = mx.nd.array(np_x, dtype=dtype)\n y = mx.nd.log(data=x)\n if check_value:\n x_ = x.as_in_context(mx.cpu())\n y_ = mx.nd.log(data=x_)\n assert_almost_equal(y.asnumpy(), y_.asnumpy())\n\ndef math_erf(shape, dtype, check_value):\n np_x = np.random.rand(*tuple(shape))\n x = mx.nd.array(np_x, dtype=dtype)\n y = mx.nd.erf(data=x)\n if check_value:\n x_ = x.as_in_context(mx.cpu())\n y_ = mx.nd.erf(data=x_)\n assert_almost_equal(y.asnumpy(), y_.asnumpy())\n\ndef math_square(shape, dtype, check_value):\n np_x = np.random.rand(*tuple(shape))\n x = mx.nd.array(np_x, dtype=dtype)\n y = mx.nd.square(data=x)\n if check_value:\n x_ = x.as_in_context(mx.cpu())\n y_ = mx.nd.square(data=x_)\n assert_almost_equal(y.asnumpy(), y_.asnumpy())\n\ndef run_math(op, shape, dtype=\"float32\", check_value=True):\n run_num = 10\n for i in range(run_num):\n if op == 'log':\n math_log(shape=shape, dtype=dtype, check_value=check_value)\n elif op == 'erf':\n math_erf(shape=shape, dtype=dtype, check_value=check_value)\n elif op == 'square':\n math_square(shape=shape, dtype=dtype, check_value=check_value)\n\n@with_seed()\ndef test_math():\n ops = ['log', 'erf', 'square']\n check_value= True\n shape_lst = [[1000], [100,1000], [10,100,100], [10,100,100,100]]\n dtypes = [\"float32\", \"float64\"]\n for shape in shape_lst:\n for dtype in dtypes:\n for op in ops:\n run_math(op, shape, dtype, check_value=check_value)\n\n@with_seed()\ndef test_arange_like_dtype():\n dtypes = [np.float16, np.float32, np.float64]\n\n for t in dtypes:\n x = mx.sym.Variable('x', dtype=t)\n y = mx.sym.reshape(x, shape=(0, 0, -1))\n z = mx.sym.contrib.arange_like(y, axis=-1)\n\n mod = z.simple_bind(ctx=mx.gpu(0), x=(3, 4, 5, 6), grad_req='null')\n mod.arg_arrays[0][:] = np.random.normal(size=mod.arg_arrays[0].shape).astype(t)\n out = mod.forward(is_train=False)\n for v in out:\n assert v.dtype == t\n\n"
] |
[
[
"numpy.testing.assert_equal",
"numpy.random.choice",
"numpy.testing.assert_almost_equal",
"numpy.shape",
"numpy.prod",
"numpy.array"
],
[
"numpy.random.random",
"numpy.abs",
"numpy.multiply",
"numpy.fft.fft",
"numpy.reshape",
"numpy.arange",
"numpy.dtype",
"numpy.ones",
"numpy.random.shuffle",
"numpy.fft.ifft",
"numpy.random.normal",
"numpy.append",
"numpy.random.rand",
"numpy.random.uniform",
"numpy.array",
"numpy.zeros",
"numpy.random.randint"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Yoo-Youngjae/One-Shot-Object-Detection
|
[
"c560a3dfb042776854bb928682dbbf545e2cd1bf"
] |
[
"lib/roi_data_layer/roibatchLoader.py"
] |
[
"\n\"\"\"The data layer used during training to train a Fast R-CNN network.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport torch.utils.data as data\nfrom PIL import Image\nimport torch\nfrom collections import Counter\n\nfrom scipy.misc import imread\nfrom model.utils.config import cfg\nfrom roi_data_layer.minibatch import get_minibatch, get_minibatch\nfrom model.utils.blob import prep_im_for_blob, im_list_to_blob, crop\nfrom model.rpn.bbox_transform import bbox_transform_inv, clip_boxes\n\nimport numpy as np\nimport cv2\nimport random\nimport time\nimport pdb\n\nclass roibatchLoader(data.Dataset):\n def __init__(self, roidb, ratio_list, ratio_index, query, batch_size, num_classes, training=True, normalize=None, seen=True):\n self._roidb = roidb\n self._query = query\n self._num_classes = num_classes\n # we make the height of image consistent to trim_height, trim_width\n self.trim_height = cfg.TRAIN.TRIM_HEIGHT\n self.trim_width = cfg.TRAIN.TRIM_WIDTH\n self.max_num_box = cfg.MAX_NUM_GT_BOXES\n self.training = training\n self.normalize = normalize\n self.ratio_list = ratio_list\n self.query_position = 0\n\n if training:\n self.ratio_index = ratio_index\n else:\n self.cat_list = ratio_index[1]\n self.ratio_index = ratio_index[0]\n\n self.batch_size = batch_size\n self.data_size = len(self.ratio_list)\n\n # given the ratio_list, we want to make the ratio same for each batch.\n self.ratio_list_batch = torch.Tensor(self.data_size).zero_()\n num_batch = int(np.ceil(len(ratio_index) / batch_size))\n if self.training:\n for i in range(num_batch):\n left_idx = i*batch_size\n right_idx = min((i+1)*batch_size-1, self.data_size-1)\n\n if ratio_list[right_idx] < 1:\n # for ratio < 1, we preserve the leftmost in each batch.\n target_ratio = ratio_list[left_idx]\n elif ratio_list[left_idx] > 1:\n # for ratio > 1, we preserve the rightmost in each batch.\n target_ratio = ratio_list[right_idx]\n else:\n # for ratio cross 1, we make it to be 1.\n target_ratio = 1\n\n self.ratio_list_batch[left_idx:(right_idx+1)] = target_ratio\n\n # self._cat_ids = [\n # 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13,\n # 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,\n # 24, 25, 27, 28, 31, 32, 33, 34, 35, 36,\n # 37, 38, 39, 40, 41, 42, 43, 44, 46, 47,\n # 48, 49, 50, 51, 52, 53, 54, 55, 56, 57,\n # 58, 59, 60, 61, 62, 63, 64, 65, 67, 70,\n # 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,\n # 82, 84, 85, 86, 87, 88, 89, 90\n # ]\n # self._cat_ids = [27, 28, 31, 32, 33, 37, 39, 40, 44, 46, 47, 48, 49, 50, 51, 52, 53, 55, 57, 72, 73, 74, 75, 76, 77,\n # 78, 80, 84, 85, 86, 87, 88, 89, 90]\n self._cat_ids = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,\n 27, 28, 29, 30, 31, 32, 33, 34]\n # num of cat == 34\n # todo: Check changed code is acceptable\n # todo 26 == backpack, blank is not skipped. so we have to rearrange the whold numbers!!\n self._classes = {\n ind + 1: cat_id for ind, cat_id in enumerate(self._cat_ids)\n }\n self._classes_inv = {\n value: key for key, value in self._classes.items()\n }\n \n self.filter(seen)\n self.probability()\n\n\n def __getitem__(self, index):\n index_ratio = int(self.ratio_index[index])\n\n # get the anchor index for current sample index\n # here we set the anchor index to the last one\n # sample in this group\n minibatch_db = [self._roidb[index_ratio]]\n\n blobs = get_minibatch(minibatch_db , self._num_classes)\n\n blobs['gt_boxes'] = [x for x in blobs['gt_boxes'] if x[-1] in self.list_ind]\n blobs['gt_boxes'] = np.array(blobs['gt_boxes'])\n\n if self.training:\n # Random choice query catgory\n try:\n catgory = blobs['gt_boxes'][:,-1]\n except:\n print('minibatch_db', minibatch_db, \"blobs['gt_boxes']\", blobs['gt_boxes'])\n exit()\n\n cand = np.unique(catgory)\n if len(cand)==1:\n choice = cand[0]\n else:\n p = []\n for i in cand:\n p.append(self.show_time[i])\n p = np.array(p)\n p /= p.sum()\n choice = np.random.choice(cand,1,p=p)[0]\n\n # Delete useless gt_boxes\n blobs['gt_boxes'][:,-1] = np.where(blobs['gt_boxes'][:,-1]==choice,1,0)\n # Get query image\n query = self.load_query(choice)\n else:\n query = self.load_query(index, minibatch_db[0]['img_id'])\n\n data = torch.from_numpy(blobs['data'])\n query = torch.from_numpy(query)\n query = query.permute(0, 3, 1, 2).contiguous().squeeze(0)\n im_info = torch.from_numpy(blobs['im_info'])\n \n # we need to random shuffle the bounding box.\n data_height, data_width = data.size(1), data.size(2)\n if self.training:\n np.random.shuffle(blobs['gt_boxes'])\n gt_boxes = torch.from_numpy(blobs['gt_boxes'])\n\n ########################################################\n # padding the input image to fixed size for each group #\n ########################################################\n\n # NOTE1: need to cope with the case where a group cover both conditions. (done)\n # NOTE2: need to consider the situation for the tail samples. (no worry)\n # NOTE3: need to implement a parallel data loader. (no worry)\n # get the index range\n\n # if the image need to crop, crop to the target size.\n ratio = self.ratio_list_batch[index]\n\n if self._roidb[index_ratio]['need_crop']:\n if ratio < 1:\n # this means that data_width << data_height, we need to crop the\n # data_height\n min_y = int(torch.min(gt_boxes[:,1]))\n max_y = int(torch.max(gt_boxes[:,3]))\n trim_size = int(np.floor(data_width / ratio))\n if trim_size > data_height:\n trim_size = data_height \n box_region = max_y - min_y + 1\n if min_y == 0:\n y_s = 0\n else:\n if (box_region-trim_size) < 0:\n y_s_min = max(max_y-trim_size, 0)\n y_s_max = min(min_y, data_height-trim_size)\n if y_s_min == y_s_max:\n y_s = y_s_min\n else:\n y_s = np.random.choice(range(y_s_min, y_s_max))\n else:\n y_s_add = int((box_region-trim_size)/2)\n if y_s_add == 0:\n y_s = min_y\n else:\n y_s = np.random.choice(range(min_y, min_y+y_s_add))\n # crop the image\n data = data[:, y_s:(y_s + trim_size), :, :]\n\n # shift y coordiante of gt_boxes\n gt_boxes[:, 1] = gt_boxes[:, 1] - float(y_s)\n gt_boxes[:, 3] = gt_boxes[:, 3] - float(y_s)\n\n # update gt bounding box according the trip\n gt_boxes[:, 1].clamp_(0, trim_size - 1)\n gt_boxes[:, 3].clamp_(0, trim_size - 1)\n\n else:\n # this means that data_width >> data_height, we need to crop the\n # data_width\n min_x = int(torch.min(gt_boxes[:,0]))\n max_x = int(torch.max(gt_boxes[:,2]))\n trim_size = int(np.ceil(data_height * ratio))\n if trim_size > data_width:\n trim_size = data_width \n box_region = max_x - min_x + 1\n if min_x == 0:\n x_s = 0\n else:\n if (box_region-trim_size) < 0:\n x_s_min = max(max_x-trim_size, 0)\n x_s_max = min(min_x, data_width-trim_size)\n if x_s_min == x_s_max:\n x_s = x_s_min\n else:\n x_s = np.random.choice(range(x_s_min, x_s_max))\n else:\n x_s_add = int((box_region-trim_size)/2)\n if x_s_add == 0:\n x_s = min_x\n else:\n x_s = np.random.choice(range(min_x, min_x+x_s_add))\n # crop the image\n data = data[:, :, x_s:(x_s + trim_size), :]\n\n # shift x coordiante of gt_boxes\n gt_boxes[:, 0] = gt_boxes[:, 0] - float(x_s)\n gt_boxes[:, 2] = gt_boxes[:, 2] - float(x_s)\n # update gt bounding box according the trip\n gt_boxes[:, 0].clamp_(0, trim_size - 1)\n gt_boxes[:, 2].clamp_(0, trim_size - 1)\n\n # based on the ratio, padding the image.\n if ratio < 1:\n # this means that data_width < data_height\n trim_size = int(np.floor(data_width / ratio))\n\n padding_data = torch.FloatTensor(int(np.ceil(data_width / ratio)), \\\n data_width, 3).zero_()\n\n padding_data[:data_height, :, :] = data[0]\n # update im_info\n im_info[0, 0] = padding_data.size(0)\n # print(\"height %d %d \\n\" %(index, anchor_idx))\n elif ratio > 1:\n # this means that data_width > data_height\n # if the image need to crop.\n padding_data = torch.FloatTensor(data_height, \\\n int(np.ceil(data_height * ratio)), 3).zero_()\n padding_data[:, :data_width, :] = data[0]\n im_info[0, 1] = padding_data.size(1)\n else:\n trim_size = min(data_height, data_width)\n padding_data = torch.FloatTensor(trim_size, trim_size, 3).zero_()\n padding_data = data[0][:trim_size, :trim_size, :]\n # gt_boxes.clamp_(0, trim_size)\n gt_boxes[:, :4].clamp_(0, trim_size)\n im_info[0, 0] = trim_size\n im_info[0, 1] = trim_size\n\n\n # check the bounding box:\n not_keep = (gt_boxes[:,0] == gt_boxes[:,2]) | (gt_boxes[:,1] == gt_boxes[:,3])\n # not_keep = (gt_boxes[:,2] - gt_boxes[:,0]) < 10 \n # print(not_keep)\n # not_keep = (gt_boxes[:,2] - gt_boxes[:,0]) < torch.FloatTensor([10]) | (gt_boxes[:,3] - gt_boxes[:,1]) < torch.FloatTensor([10])\n\n keep = torch.nonzero(not_keep == 0).view(-1)\n\n gt_boxes_padding = torch.FloatTensor(self.max_num_box, gt_boxes.size(1)).zero_()\n if keep.numel() != 0 :\n gt_boxes = gt_boxes[keep]\n num_boxes = min(gt_boxes.size(0), self.max_num_box)\n gt_boxes_padding[:num_boxes,:] = gt_boxes[:num_boxes]\n else:\n num_boxes = 0\n\n # permute trim_data to adapt to downstream processing\n padding_data = padding_data.permute(2, 0, 1).contiguous()\n im_info = im_info.view(3)\n\n return padding_data, query, im_info, gt_boxes_padding, num_boxes\n else:\n data = data.permute(0, 3, 1, 2).contiguous().view(3, data_height, data_width)\n im_info = im_info.view(3)\n\n # gt_boxes = torch.FloatTensor([1,1,1,1,1])\n gt_boxes = torch.from_numpy(blobs['gt_boxes'])\n choice = self.cat_list[index]\n\n return data, query, im_info, gt_boxes, choice\n\n def load_query(self, choice, id=0):\n \n if self.training:\n # Random choice query catgory image\n all_data = self._query[choice]\n # data = random.choice(all_data)\n\n # todo: check changed code is acceptable.\n while True:\n data = random.choice(all_data)\n if int(data['boxes'][1]) == int(data['boxes'][3]) or int(data['boxes'][0]) == int(data['boxes'][2]):\n continue\n else:\n break\n\n else:\n # Take out the purpose category for testing\n catgory = self.cat_list[choice]\n # list all the candidate image \n all_data = self._query[catgory]\n\n # Use image_id to determine the random seed\n # The list l is candidate sequence, which random by image_id\n random.seed(id)\n l = list(range(len(all_data)))\n random.shuffle(l)\n\n # choose the candidate sequence and take out the data information\n position=l[self.query_position%len(l)]\n data = all_data[position]\n\n # Get image\n path = data['image_path']\n im = imread(path)\n\n # todo: check changed code is acceptable.\n # check_zero = True\n # while check_zero:\n # path = data['image_path']\n # im = imread(path)\n # if 0 not in im.shape[0:3]:\n # check_zero = False\n # break\n # elif 0 in im.shape[0:3]:\n # data = random.choice(all_data)\n\n if len(im.shape) == 2:\n im = im[:,:,np.newaxis]\n im = np.concatenate((im,im,im), axis=2)\n\n im = crop(im, data['boxes'], cfg.TRAIN.query_size)\n # flip the channel, since the original one using cv2\n # rgb -> bgr\n # im = im[:,:,::-1]\n if random.randint(0,99)/100 > 0.5 and self.training:\n im = im[:, ::-1, :]\n\n\n im, im_scale = prep_im_for_blob(im, cfg.PIXEL_MEANS, cfg.TRAIN.query_size,\n cfg.TRAIN.MAX_SIZE)\n \n query = im_list_to_blob([im])\n\n return query\n\n def __len__(self):\n return len(self.ratio_index)\n \n def filter(self, seen):\n if seen==1:\n self.list = cfg.train_categories\n # Group number to class\n if len(self.list)==1:\n self.list = [self._classes[cat] for cat in range(1,len(self._classes)+1) if cat%4 != self.list[0]]\n # len(self._classes)\n elif seen==2:\n self.list = cfg.test_categories\n # Group number to class\n if len(self.list)==1:\n self.list = [self._classes[cat] for cat in range(1,len(self._classes)+1) if cat%4 == self.list[0]]\n \n elif seen==3:\n self.list = cfg.train_categories + cfg.test_categories\n # Group number to class\n if len(self.list)==2:\n self.list = [self._classes[cat] for cat in range(1,len(self._classes)+1)]\n\n self.list_ind = [self._classes_inv[x] for x in self.list]\n \n def probability(self):\n show_time = {}\n for i in self.list_ind:\n show_time[i] = 0\n for roi in self._roidb:\n result = Counter(roi['gt_classes'])\n for t in result:\n if t in self.list_ind:\n show_time[t] += result[t]\n\n for i in self.list_ind:\n show_time[i] = 1/show_time[i]\n\n sum_prob = sum(show_time.values())\n\n for i in self.list_ind:\n show_time[i] = show_time[i]/sum_prob\n \n self.show_time = show_time\n"
] |
[
[
"torch.max",
"torch.Tensor",
"numpy.unique",
"numpy.random.choice",
"torch.min",
"torch.from_numpy",
"numpy.random.shuffle",
"numpy.concatenate",
"numpy.ceil",
"torch.FloatTensor",
"scipy.misc.imread",
"numpy.floor",
"torch.nonzero",
"numpy.array",
"numpy.where"
]
] |
[
{
"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": []
}
] |
DIAGNijmegen/adhesion_detection
|
[
"21a9c810a4dee3c640d31f30ee5fdff1bbce9146"
] |
[
"src/vs_definitions.py"
] |
[
"import numpy as np\nfrom pathlib import Path\nfrom enum import Enum, unique\nfrom cinemri.contour import Contour\nfrom config import *\n\n@unique\nclass VSExpectationNormType(Enum):\n # Division by mean\n mean_div = 0\n # Standardize with std\n standardize = 1\n\n\n# Transformation to apply to visceral slide values\n@unique\nclass VSTransform(Enum):\n none = 0\n log = 1\n sqrt = 2\n\n\nclass Region:\n \"\"\"An object representing a coordinates region with a value at a specific coordinate\n \"\"\"\n\n def __init__(self, x, y, values, mean=None, std=None):\n \"\"\"\n\n Parameters\n ----------\n x, y : list of int or int\n The coordinates of the region\n values : list of float or float\n The values that correspond to coordinates\n mean : float\n A mean of the region\n std : float\n A standard deviation of the region\n \"\"\"\n self.x = np.atleast_1d(x)\n self.y = np.atleast_1d(y)\n self.values = np.atleast_1d(values)\n self.mean = mean\n self.std = std\n self.points = np.column_stack((self.x, self.y, self.values))\n\n @classmethod\n def from_point(cls, point):\n \"\"\"\n Initialises a Region object from a single point\n Parameters\n ----------\n point : tuple\n (x, y, value) - the coordinates of the point and the value at this point\n\n Returns\n -------\n region : Region\n A region that consists of a single point\n \"\"\"\n x, y, value = point[0], point[1], point[2]\n region = cls(x, y, value)\n return region\n\n @classmethod\n def from_points(cls, points):\n \"\"\"\n Initialises a Region object from points\n Parameters\n ----------\n points : ndarray\n An array of points coordinates and values at a point. The first column - coordinates by x axis,\n the second - coordinates by y axis, the third - values\n\n Returns\n -------\n region : Region\n A region that consists of a single point\n \"\"\"\n x, y, values = points[:, 0], points[:, 1], points[:, 2]\n region = cls(x, y, values)\n return region\n\n def append(self, x, y, value):\n \"\"\"\n Appends one coordinate and its value to the region\n Parameters\n ----------\n x, y : int\n A coordinate to append\n value : float\n The corresponding value\n \"\"\"\n self.x = np.concatenate((self.x, [x]))\n self.y = np.concatenate((self.y, [y]))\n self.values = np.concatenate((self.values, [value]))\n\n self.points = np.column_stack((self.x, self.y, self.values))\n\n def append_point(self, point):\n \"\"\"\n Appends one coordinate and its values to the region\n Parameters\n ----------\n point : tuple of (int, int, float)\n A coordinate and the corresponding value to append\n value : float\n The corresponding value\n \"\"\"\n self.x = np.concatenate((self.x, [point[0]]))\n self.y = np.concatenate((self.y, [point[1]]))\n self.values = np.concatenate((self.values, [point[2]]))\n\n self.points = np.column_stack((self.x, self.y, self.values))\n\n def extend(self, x, y, values):\n \"\"\"\n Appends one coordinate and its values to the region\n Parameters\n ----------\n x, y : list of int\n Coordinates to extend with\n values : list of floats\n Corresponding values\n \"\"\"\n self.x = np.concatenate((self.x, x))\n self.y = np.concatenate((self.y, y))\n self.values = np.concatenate((self.values, values))\n\n self.points = np.column_stack((self.x, self.y, self.values))\n\n @property\n def size(self):\n \"\"\" Size of a rectangle that encloses the region\n \"\"\"\n if len(self.x) == 0:\n return 0, 0\n\n def compute_len(axis=0):\n values = [point[axis] for point in self.points]\n length = np.max(values) - np.min(values) + 1\n return length\n\n width = compute_len(axis=0)\n height = compute_len(axis=1)\n return width, height\n\n def exceeded_size(self, size):\n \"\"\"\n Checks if the size of a rectangle that encloses the region is larger than a given size\n Parameters\n ----------\n size : tuple\n A size to compare with\n\n Returns\n -------\n flag: bool\n A boolean flag indicating whether region size is larger than the given size\n \"\"\"\n width, height = self.size\n return width >= size[0] or height >= size[1]\n\n\nclass VisceralSlide(Contour):\n \"\"\"An object representing visceral slide for a Cine-MRI slice\n \"\"\"\n\n def __init__(self, patient_id, study_id, slice_id, visceral_slide_data):\n \"\"\"\n Parameters\n ----------\n patient_id : str\n An id of a patient a Cine-MRI slice belongs to\n study_id : str\n An id of a study a Cine-MRI slice belongs to\n slice_id : str\n An id of a Cine-MRI slice\n visceral_slide_data : dict\n A dictionary containing the coordinates of abdominal cavity contour\n and visceral slide value at each coordinate\n \"\"\"\n\n super().__init__(visceral_slide_data[\"x\"], visceral_slide_data[\"y\"])\n\n self.values = np.array(visceral_slide_data[\"slide\"])\n self.patient_id = patient_id\n self.study_id = study_id\n self.slice_id = slice_id\n self.full_id = SEPARATOR.join([patient_id, study_id, slice_id])\n\n def zeros_fix(self):\n \"\"\" Replace zeros with highest non 0 in visceral slide values\n \"\"\"\n zero_placeholder = np.min([value for value in self.values if value > 0])\n self.values = np.array([value if value > 0 else zero_placeholder for value in self.values])\n\n def to_regions(self, means=None, stds=None):\n \"\"\"\n Splits visceral slide into chunks starting from the bottom left point of the contour\n in the clock-wise direction. The provided mean and stds should correspond to these chunks\n\n Parameters\n ----------\n means : list of float, optional\n A list of visceral slide mean by chunk\n stds : list of float, optional\n A list of visceral slide standard deviation by chunk\n\n Returns\n -------\n regions : list of Regions\n A list of objects of Region type that represent chunks of visceral slide map\n and include mean and standard deviation of visceral slide value in each chunk\n \"\"\"\n regions_num = len(means)\n\n xs, ys = self.x, self.y\n values = self.values\n\n vs_len = len(values)\n indices = np.arange(vs_len)\n chunks = np.array_split(indices, regions_num)\n chunk_lens = np.array([len(chunk) for chunk in chunks])\n np.random.shuffle(chunk_lens)\n\n x_bottom_left, y_bottom_left = self.bottom_left_point\n coords = np.column_stack((xs, ys))\n ind = np.where((coords == (x_bottom_left, y_bottom_left)).all(axis=1))[0][0]\n\n reg_start = ind\n reg_end = reg_start + chunk_lens[0]\n last_ind = reg_start\n\n regions = []\n for i in range(regions_num):\n if reg_end >= vs_len:\n reg_end -= vs_len\n\n if reg_start >= vs_len:\n reg_start -= vs_len\n\n mean = means[i] if means is not None else None\n std = stds[i] if stds is not None else None\n\n # Normal situation, take the connected region\n if reg_start < reg_end:\n x_reg = xs[reg_start:reg_end]\n y_reg = ys[reg_start:reg_end]\n val_reg = values[reg_start:reg_end]\n\n region = Region(x_reg, y_reg, val_reg, mean, std)\n else:\n # We went beyond the fist contour coordinate, so add up a region from the region start till\n # the end of contour and from the start of contour till the region end\n x_reg = xs[reg_start:]\n y_reg = ys[reg_start:]\n val_reg = values[reg_start:]\n region = Region(x_reg, y_reg, val_reg, mean, std)\n region.extend(xs[:reg_end], ys[:reg_end], values[:reg_end])\n\n regions.append(region)\n reg_start = reg_end\n if i < regions_num - 1:\n if i == regions_num - 2:\n reg_end = last_ind\n else:\n reg_end += chunk_lens[i + 1]\n\n return regions\n\n def norm_with_expectation(self, means, stds, expectation_norm_type=VSExpectationNormType.mean_div):\n \"\"\"Normalises visceral slide by provided means and standard deviations assuming that\n means and standard deviations correspond to regions obtained with to_regions method\n\n Parameters\n ----------\n means, stds : list of float\n A list of visceral slide mean by chunk\n stds : list of float\n A list of visceral slide standard deviation by chunk\n expectation_norm_type : VSExpectationNormType, default=VSExpectationNormType.mean_div\n A type of normalisation to apply\n \"\"\"\n\n vs_regs = self.to_regions(means, stds)\n\n reg = vs_regs[0]\n if expectation_norm_type == VSExpectationNormType.mean_div:\n values = reg.values / reg.mean\n else:\n values = (reg.values - reg.mean) / reg.std\n\n for i in range(1, len(vs_regs)):\n reg = vs_regs[i]\n if expectation_norm_type == VSExpectationNormType.mean_div:\n vs_norm = reg.values / reg.mean\n else:\n vs_norm = (reg.values - reg.mean) / reg.std\n\n values = np.concatenate((values, vs_norm))\n\n self.values = values\n\n def build_path(self, relative_path, extension=\".mha\"):\n \"\"\"\n Build a path to a folder that contains visceral slide assuming standard folders hierarchy\n Parameters\n ----------\n relative_path : Path\n A relative path to locate a slice file\n Returns\n -------\n path : Path\n A path to a folder that contains visceral slide\n \"\"\"\n return Path(relative_path) / self.patient_id / self.study_id / (self.slice_id + extension)\n"
] |
[
[
"numpy.min",
"numpy.arange",
"numpy.random.shuffle",
"numpy.atleast_1d",
"numpy.concatenate",
"numpy.max",
"numpy.array_split",
"numpy.column_stack",
"numpy.array"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Munazza12/Python
|
[
"b550e3bf8a5468602bec4f23b4d4d1f2f696342f"
] |
[
"01_matplotlib.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"01_Matplotlib.ipynb\n\nAutomatically generated by Colaboratory.\n\nOriginal file is located at\n https://colab.research.google.com/drive/1kcVik8w7TtrXYaCSklntRqq2av-7N7-6\n\n#Introduction to Matplotlib\n\n\n\nMatplotlib is the \"grandfather\" library of data visualization with Python. It was created by John Hunter. He created it to try to replicate MatLab's (another programming language) plotting capabilities in Python. So if you happen to be familiar with matlab, matplotlib will feel natural to you. Matplotlib is a plotting library for Python. It is used along with NumPy to provide an environment that is an effective open source alternative for MatLab.\n\nIt is an excellent 2D and 3D graphics library for generating scientific figures. \n\nSome of the major Pros of Matplotlib are:\n\n* Generally easy to get started for simple plots\n* Support for custom labels and texts\n* Great control of every element in a figure\n* High-quality output in many formats\n* Very customizable in general\n\n\n##Importing matplotlib\n\nTo import matplotlib in Colaboratory under the name **plt** from module **matplotlib.pyplot** type the following:\n\"\"\"\n\nimport matplotlib.pyplot as plt\n\n\"\"\"**Note:** If you are using Colaboratory **plt.show()** at the end of all the plooting commands to have the figure pop up in another window.\n\n#Basic Example\n\nLet's walk through a very simple example using two numpy arrays. You can also use lists, but most likely you'll be passing numpy arrays or pandas columns (which essentially also behave like arrays).\n\nLet us create the data we want to plot.\n\"\"\"\n\nimport numpy as np\nx = np.linspace(0, 5, 11)\ny = x ** 2\n\nx\n\ny\n\n\"\"\"We created 2 set of numbers **x** and **y**.\n\n## Basic Matplotlib Commands\n\nWe can create a very simple line plot using the following:\n\"\"\"\n\nplt.plot(x, y, 'r') # 'r' is the color red\nplt.xlabel('X Axis Title Here')\nplt.ylabel('Y Axis Title Here')\nplt.title('String Title Here')\nplt.show()\n\n\"\"\"## Creating Multiplots on Same Canvas\"\"\"\n\n# plt.subplot(nrows, ncols, plot_number)\nplt.subplot(1,2,1)\nplt.plot(x, y, 'r*') # More on color options later\nplt.subplot(1,2,2)\nplt.plot(y, x, 'g*-');\n\n\"\"\"# Matplotlib Object Oriented Method\nNow that we've seen the basics, let's break it all down with a more formal introduction of Matplotlib's Object Oriented API. This means we will instantiate figure objects and then call methods or attributes from that object.\n\n## Introduction to the Object Oriented Method\n\nThe main idea in using the more formal Object Oriented method is to create figure objects and then just call methods or attributes off of that object. This approach is nicer when dealing with a canvas that has multiple plots on it. \n\nTo begin we create a figure instance. Then we can add axes to that figure:\n\"\"\"\n\n# Create Figure (empty canvas)\nfig = plt.figure()\n\n# Add set of axes to figure\naxes = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # left, bottom, width, height (range 0 to 1)\n\n# Plot on that set of axes\naxes.plot(x, y, 'g')\naxes.set_xlabel('Set X Label') # Notice the use of set_ to begin methods\naxes.set_ylabel('Set y Label')\naxes.set_title('Set Title')\n\n\"\"\"Code is a little more complicated, but the advantage is that we now have full control of where the plot axes are placed, and we can easily add more than one axis to the figure:\"\"\"\n\n# Creates blank canvas\nfig = plt.figure()\n\naxes1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # main axes\naxes2 = fig.add_axes([0.2, 0.5, 0.4, 0.3]) # inset axes\n\n# Larger Figure Axes 1\naxes1.plot(x, y, 'b')\naxes1.set_xlabel('X_label_axes2')\naxes1.set_ylabel('Y_label_axes2')\naxes1.set_title('Axes 2 Title')\n\n# Insert Figure Axes 2\naxes2.plot(y, x, 'r')\naxes2.set_xlabel('X_label_axes2')\naxes2.set_ylabel('Y_label_axes2')\naxes2.set_title('Axes 2 Title');\n\n\"\"\"## subplots()\n\nThe plt.subplots() object will act as a more automatic axis manager.\n\nBasic use cases:\n\"\"\"\n\n# Use similar to plt.figure() except use tuple unpacking to grab fig and axes\nfig, axes = plt.subplots()\n\n# Now use the axes object to add stuff to plot\naxes.plot(x, y, 'r')\naxes.set_xlabel('x')\naxes.set_ylabel('y')\naxes.set_title('title');\n\n\"\"\"Then you can specify the number of rows and columns when creating the subplots() object:\"\"\"\n\n# Empty canvas of 1 by 2 subplots\nfig, axes = plt.subplots(nrows=1, ncols=2)\n\n# Axes is an array of axes to plot on\naxes\n\n\"\"\"**Note:** Here you can see that **axes** is an **array** type. That means we can iterate through it.\"\"\"\n\nfor ax in axes:\n ax.plot(x, y, 'b')\n ax.set_xlabel('x')\n ax.set_ylabel('y')\n ax.set_title('title')\n\n# Display the figure object \nfig\n\n\"\"\"A common issue with matplolib is overlapping subplots or figures. We ca use **fig.tight_layout()** or **plt.tight_layout()** method, which automatically adjusts the positions of the axes on the figure canvas so that there is no overlapping content:\"\"\"\n\nfig, axes = plt.subplots(nrows=1, ncols=2)\n\nfor ax in axes:\n ax.plot(x, y, 'g')\n ax.set_xlabel('x')\n ax.set_ylabel('y')\n ax.set_title('title')\n\nfig \nplt.tight_layout()\n\n\"\"\"## Figure size, aspect ratio and DPI\n\nMatplotlib allows the aspect ratio, DPI and figure size to be specified when the Figure object is created. You can use the figsize and dpi keyword arguments. \n\n* **figsize** is a tuple of the width and height of the figure in inches\n* **dpi** is the dots-per-inch (pixel per inch). \n\nFor example:\n\"\"\"\n\nfig = plt.figure(figsize=(8,4), dpi=100)\n\n\"\"\"The same arguments can also be passed to layout managers, such as the **subplots** function:\"\"\"\n\nfig, axes = plt.subplots(figsize=(12,3))\n\naxes.plot(x, y, 'r')\naxes.set_xlabel('x')\naxes.set_ylabel('y')\naxes.set_title('title');\n\n\"\"\"## Saving figures\nMatplotlib can generate high-quality output in a number formats, including PNG, JPG, EPS, SVG, PGF and PDF.\n\nTo save a figure to a file we can use the **savefig** method in the **Figure** class:\n\"\"\"\n\nfig.savefig(\"filename.png\")\n\n\"\"\"Here we can also optionally specify the DPI and choose between different output formats:\"\"\"\n\nfig.savefig(\"filename.png\", dpi=200)\n\n\"\"\"## Legends, labels and titles\n\nNow that we have covered the basics of how to create a figure canvas and add axes instances to the canvas, let's look at how decorate a figure with titles, axis labels, and legends.\n\n**Figure titles**\n\nA title can be added to each axis instance in a figure. To set the title, use the **set_title** method in the axes instance:\n\"\"\"\n\nax.set_title(\"title\");\n\n\"\"\"**Axis labels**\n\nSimilarly, with the methods **set_xlabel** and **set_ylabel**, we can set the labels of the X and Y axes:\n\"\"\"\n\nax.set_xlabel(\"x\")\nax.set_ylabel(\"y\");\n\n\"\"\"## Legends\n\nYou can use the **label=\"label text\"** keyword argument when plots or other objects are added to the figure, and then using the **legend** method without arguments to add the legend to the figure:\n\"\"\"\n\nfig = plt.figure()\n\nax = fig.add_axes([0,0,1,1])\n\nax.plot(x, x**2, label=\"x**2\")\nax.plot(x, x**3, label=\"x**3\")\nax.legend()\n\n\"\"\"The legend function takes an optional keyword argument loc that can be used to specify where in the figure the legend is to be drawn. The allowed values of loc are numerical codes for the various places the legend can be drawn. See the documentation page for details. Some of the most common loc values are:\"\"\"\n\n# Lots of options....\n\nax.legend(loc=1) # upper right corner\nax.legend(loc=2) # upper left corner\nax.legend(loc=3) # lower left corner\nax.legend(loc=4) # lower right corner\n\n# .. many more options are available\n\n# Most common to choose\nax.legend(loc=0) # let matplotlib decide the optimal location\nfig\n\n\"\"\"## Setting colors, linewidths, linetypes\n\nMatplotlib gives you *a lot* of options for customizing colors, linewidths, and linetypes.\n\nWith matplotlib, we can define the colors of lines and other graphical elements in a number of ways. First of all, we can use the MATLAB-like syntax where 'b' means blue, 'g' means green, etc. The MATLAB API for selecting line styles are also supported: where, for example, 'b.-' means a blue line with dots:\n\"\"\"\n\nfig, ax = plt.subplots()\nax.plot(x, x**2, 'b.-') # blue line with dots\nax.plot(x, x**3, 'g--') # green dashed line\n\n\"\"\"### Colors with the color= parameter\n\nWe can also define colors by their names or RGB hex codes and optionally provide an alpha value using the color and alpha keyword arguments. Alpha indicates opacity.\n\"\"\"\n\nfig, ax = plt.subplots()\n\nax.plot(x, x+1, color=\"blue\", alpha=0.5) # half-transparant\nax.plot(x, x+2, color=\"#8B008B\") # RGB hex code\nax.plot(x, x+3, color=\"#FF8C00\")\n\n\"\"\"### Line and marker styles\n\nTo change the line width, we can use the linewidth or lw keyword argument. The line style can be selected using the linestyle or ls keyword arguments:\n\"\"\"\n\nfig, ax = plt.subplots(figsize=(12,6))\n\nax.plot(x, x+1, color=\"red\", linewidth=0.25)\nax.plot(x, x+2, color=\"red\", linewidth=0.50)\nax.plot(x, x+3, color=\"red\", linewidth=1.00)\nax.plot(x, x+4, color=\"red\", linewidth=2.00)\n\n# possible linestype options ‘-‘, ‘–’, ‘-.’, ‘:’, ‘steps’\nax.plot(x, x+5, color=\"green\", lw=3, linestyle='-')\nax.plot(x, x+6, color=\"green\", lw=3, ls='-.')\nax.plot(x, x+7, color=\"green\", lw=3, ls=':')\n\n# custom dash\nline, = ax.plot(x, x+8, color=\"black\", lw=1.50)\nline.set_dashes([5, 10, 15, 10]) # format: line length, space length, ...\n\n# possible marker symbols: marker = '+', 'o', '*', 's', ',', '.', '1', '2', '3', '4', ...\nax.plot(x, x+ 9, color=\"blue\", lw=3, ls='-', marker='+')\nax.plot(x, x+10, color=\"blue\", lw=3, ls='--', marker='o')\nax.plot(x, x+11, color=\"blue\", lw=3, ls='-', marker='s')\nax.plot(x, x+12, color=\"blue\", lw=3, ls='--', marker='1')\n\n# marker size and color\nax.plot(x, x+13, color=\"purple\", lw=1, ls='-', marker='o', markersize=2)\nax.plot(x, x+14, color=\"purple\", lw=1, ls='-', marker='o', markersize=4)\nax.plot(x, x+15, color=\"purple\", lw=1, ls='-', marker='o', markersize=8, markerfacecolor=\"red\")\nax.plot(x, x+16, color=\"purple\", lw=1, ls='-', marker='s', markersize=8, \n markerfacecolor=\"yellow\", markeredgewidth=3, markeredgecolor=\"green\");\n\n\"\"\"## Plot range\n\nWe can configure the ranges of the axes using the set_ylim and set_xlim methods in the axis object, or axis('tight') for automatically getting \"tightly fitted\" axes ranges:\n\"\"\"\n\nfig, axes = plt.subplots(1, 3, figsize=(12, 4))\n\naxes[0].plot(x, x**2, x, x**3)\naxes[0].set_title(\"default axes ranges\")\n\naxes[1].plot(x, x**2, x, x**3)\naxes[1].axis('tight')\naxes[1].set_title(\"tight axes\")\n\naxes[2].plot(x, x**2, x, x**3)\naxes[2].set_ylim([0, 60])\naxes[2].set_xlim([2, 5])\naxes[2].set_title(\"custom axes range\");\n\n\"\"\"# Special Plot Types\n\nThere are many specialized plots we can create, such as barplots, histograms, scatter plots, and much more. Most of these type of plots we will actually create using seaborn, a statistical plotting library for Python. But here are a few examples of these type of plots:\n\"\"\"\n\nplt.scatter(x,y)\n\nfrom random import sample\ndata = sample(range(1, 1000), 100)\nplt.hist(data)\n\ndata = [np.random.normal(0, std, 100) for std in range(1, 4)]\n\n# rectangular box plot\nplt.boxplot(data,vert=True,patch_artist=True);\n\n\"\"\"## Further reading\n\n* http://www.matplotlib.org - The project web page for matplotlib.\n* https://github.com/matplotlib/matplotlib - The source code for matplotlib.\n* http://matplotlib.org/gallery.html - A large gallery showcaseing various types of plots matplotlib can create. Highly recommended! \n* http://www.loria.fr/~rougier/teaching/matplotlib - A good matplotlib tutorial.\n* http://scipy-lectures.github.io/matplotlib/matplotlib.html - Another good matplotlib reference.\n\n#Great job!\n\"\"\""
] |
[
[
"matplotlib.pyplot.boxplot",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.title",
"numpy.linspace",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.plot",
"numpy.random.normal",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"matplotlib.pyplot.hist",
"matplotlib.pyplot.ylabel"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
wangvei/PyDEF-2.0
|
[
"ee5bd0a01d241e5df45ccbf10f3c27e1b796418b"
] |
[
"pydef_core/follow_convergence_OSZICAR.py"
] |
[
"\"\"\"\n 12/12/17\n\tSimple script to follow convergence from OSZICAR file\n author: Adrien Stoliaroff\n email: [email protected]\n\"\"\"\nimport matplotlib.pyplot as plt\n\ndef isInt(s):\n try: \n int(s)\n return True\n except ValueError:\n return False\n\n#Read OSZICAR content \ninfile = open(\"OSZICAR\",\"r\")\neList, dEList, dEpsList, rmsList, eSCF, dESCF = [], [], [], [], [], []\n\nfor line in infile:\n\tcontent = line.replace('d eps','deps').split()\n\t#line inside SCF cycle\n\tif(isInt(content[1])):\n\t\teList.append(float(content[2]))\n\t\tdEList.append(float(content[3]))\n\t\tdEpsList.append(float(content[4]))\n\t\trmsList.append(float(content[6].split('-0.')[0]))\n\t#end of SCF cycle\n\tif(isInt(content[0])):\n\t\teSCF.append(float(line.split()[4]))\n\t\tdESCF.append(float(line.split()[7].replace('=','')))\n#plot result\nlegend = ['E', 'dE', 'd eps', 'RMS', 'E_SCF', 'd E_SCF']\ncolors = ['r', 'b', 'g', 'c', 'm', 'y']\ni = 0\nplt.subplot(311)\n\nfor curve in [eList, dEList]:\n\tplt.plot(range(len(curve)), curve, label = legend[i], color = colors[i])\n\ti += 1\n\nplt.xlabel('Iteration')\nplt.ylabel('Energies (eV)')\nplt.title('Convergence follow up from OSZICAR')\nplt.legend()\n\nplt.subplot(312)\n \nfor curve in [dEpsList, rmsList]:\n\tplt.plot(range(len(curve)), curve, label = legend[i], color = colors[i])\n\ti += 1\n\t\nplt.xlabel('Iteration')\nplt.ylabel('Convergence')\nplt.legend()\n\nplt.subplot(313)\n \nfor curve in [eSCF, dESCF]:\n\tplt.plot(range(len(curve)), curve, label = legend[i], marker = 'o', linestyle = '--', color = colors[i])\n\ti += 1\n\t\nplt.xlabel('SCF cycle')\nplt.ylabel('Energies (eV)')\nplt.legend()\n\nfig=plt.gcf()\nfig.show()\n"
] |
[
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.title",
"matplotlib.pyplot.gcf",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.ylabel"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jim-fun/evidently
|
[
"eb3479b8ce39e43601fb2d1ffbf61e0624541865"
] |
[
"evidently/tests/test_readme_examples.py"
] |
[
"import json\n\nimport pandas as pd\nimport numpy as np\nfrom sklearn import datasets\nfrom unittest import TestCase\n\nfrom evidently import ColumnMapping\nfrom evidently.dashboard import Dashboard\nfrom evidently.model_profile import Profile\nfrom evidently.profile_sections import DataDriftProfileSection, CatTargetDriftProfileSection, \\\n RegressionPerformanceProfileSection, ClassificationPerformanceProfileSection, \\\n ProbClassificationPerformanceProfileSection\nfrom evidently.tabs import DataDriftTab, RegressionPerformanceTab, CatTargetDriftTab, ClassificationPerformanceTab, \\\n ProbClassificationPerformanceTab\n\n\ndef _get_iris():\n # we do not use setUp method here, because of side effects in tests\n # side effect can be avoided by using fixtures from pytest :-)\n iris = datasets.load_iris()\n iris_frame = pd.DataFrame(iris.data, columns=iris.feature_names)\n iris_frame['target'] = iris.target\n return iris, iris_frame\n\n\ndef _get_probabilistic_iris():\n iris = datasets.load_iris()\n iris_frame = pd.DataFrame(iris.data, columns=iris.feature_names)\n random_probs = np.random.random((3, 150))\n random_probs = (random_probs / random_probs.sum(0))\n pred_df = pd.DataFrame(random_probs.T, columns=iris.target_names)\n iris_frame['target'] = iris.target_names[iris['target']]\n merged_reference = pd.concat([iris_frame, pred_df], axis=1)\n\n iris_column_mapping = ColumnMapping()\n iris_column_mapping.target = 'target'\n iris_column_mapping.prediction = iris.target_names.tolist()\n iris_column_mapping.numerical_features = iris.feature_names\n return merged_reference, iris_column_mapping\n\n\nclass TestDashboards(TestCase):\n # TODO(fixme): Actually we would like to test html's output, but because\n # evidently/nbextension/static/index.js is missing\n # (and evidently/nbextension/static/index.js.LICENSE.txt is an actual text file)\n # saving an html report in the test itself fails.\n # A reasonable fallback is to use the private _json() method. Although, since it is never used anywhere else\n # it may be considered a bad testing practice to have methods only for testing purposes.\n # For now we stick to it until something better comes along.\n\n def setUp(self) -> None:\n iris = datasets.load_iris()\n self.iris_frame = pd.DataFrame(iris.data, columns=iris.feature_names)\n self.iris_frame['target'] = iris.target\n self.iris_targets = iris.target_names\n\n ###\n # The following are extracted from the README.md file.\n ###\n def test_data_drift_dashboard(self):\n # To generate the **Data Drift** report, run:\n iris_data_drift_report = Dashboard(tabs=[DataDriftTab()])\n iris_data_drift_report.calculate(self.iris_frame[:100], self.iris_frame[100:])\n actual = json.loads(iris_data_drift_report._json())\n # we leave the actual content test to other tests for widgets\n self.assertTrue('name' in actual)\n self.assertTrue(len(actual['widgets']) == 1)\n\n def test_data_drift_categorical_target_drift_dashboard(self):\n # To generate the **Data Drift** and the **Categorical Target Drift** reports, run:\n iris_data_and_target_drift_report = Dashboard(tabs=[DataDriftTab(), CatTargetDriftTab()])\n iris_data_and_target_drift_report.calculate(self.iris_frame[:100], self.iris_frame[100:])\n actual = json.loads(iris_data_and_target_drift_report._json())\n self.assertTrue('name' in actual)\n self.assertTrue(len(actual['widgets']) == 3)\n\n def test_regression_performance_dashboard(self):\n # To generate the **Regression Model Performance** report, run:\n # FIXME: when prediction column is not present in the dataset\n # ValueError: [Widget Regression Model Performance Report.] self.wi is None,\n # no data available (forget to set it in widget?)\n self.iris_frame['prediction'] = self.iris_frame['target'][::-1]\n regression_model_performance = Dashboard(tabs=[RegressionPerformanceTab()])\n regression_model_performance.calculate(self.iris_frame[:100], self.iris_frame[100:])\n actual = json.loads(regression_model_performance._json())\n self.assertTrue('name' in actual)\n self.assertEqual(len(actual['widgets']), 20)\n\n def test_regression_performance_single_frame_dashboard(self):\n # You can also generate a **Regression Model Performance** for a single `DataFrame`. In this case, run:\n # FIXME: when prediction column is not present in the dataset\n # ValueError: [Widget Regression Model Performance Report.] self.wi is None,\n # no data available (forget to set it in widget?)\n self.iris_frame['prediction'] = self.iris_frame['target'][::-1]\n regression_single_model_performance = Dashboard(tabs=[RegressionPerformanceTab()])\n regression_single_model_performance.calculate(self.iris_frame, None)\n actual = json.loads(regression_single_model_performance._json())\n self.assertTrue('name' in actual)\n self.assertEqual(len(actual['widgets']), 12)\n\n def test_classification_performance_dashboard(self):\n # To generate the **Classification Model Performance** report, run:\n # FIXME: when prediction column is not present in the dataset\n # ValueError: [Widget Classification Model Performance Report.] self.wi is None,\n # no data available (forget to set it in widget?)\n self.iris_frame['prediction'] = self.iris_frame['target'][::-1]\n classification_performance_report = Dashboard(tabs=[ClassificationPerformanceTab()])\n classification_performance_report.calculate(self.iris_frame[:100], self.iris_frame[100:])\n\n actual = json.loads(classification_performance_report._json())\n self.assertTrue('name' in actual)\n self.assertEqual(len(actual['widgets']), 10)\n\n def test_probabilistic_classification_performance_dashboard(self):\n # For **Probabilistic Classification Model Performance** report, run:\n random_probs = np.random.random((3, 150))\n random_probs = (random_probs / random_probs.sum(0))\n pred_df = pd.DataFrame(random_probs.T, columns=self.iris_targets)\n iris_frame = pd.concat([self.iris_frame, pred_df], axis=1)\n iris_frame['target'] = self.iris_targets[self.iris_frame['target']]\n iris_column_mapping = ColumnMapping()\n iris_column_mapping.prediction = self.iris_targets\n classification_performance_report = Dashboard(tabs=[ProbClassificationPerformanceTab()])\n classification_performance_report.calculate(iris_frame, iris_frame, iris_column_mapping)\n\n actual = json.loads(classification_performance_report._json())\n self.assertTrue('name' in actual)\n self.assertEqual(len(actual['widgets']), 20)\n\n def test_classification_performance_on_single_frame_dashboard(self):\n # You can also generate either of the **Classification** reports for a single `DataFrame`. In this case, run:\n self.iris_frame['prediction'] = self.iris_frame['target'][::-1]\n classification_single_frame_performance = Dashboard(tabs=[ClassificationPerformanceTab()])\n classification_single_frame_performance.calculate(self.iris_frame, None)\n actual = json.loads(classification_single_frame_performance._json())\n self.assertTrue('name' in actual)\n self.assertEqual(len(actual['widgets']), 9)\n\n def test_probabilistic_classification_performance_on_single_frame_dashboard(self):\n # You can also generate either of the **Classification** reports for a single `DataFrame`. In this case, run:\n # FIXME: like above, when prediction column is not present in the dataset\n random_probs = np.random.random((3, 150))\n random_probs = (random_probs / random_probs.sum(0))\n pred_df = pd.DataFrame(random_probs.T, columns=self.iris_targets)\n iris_frame = pd.concat([self.iris_frame, pred_df], axis=1)\n iris_frame['target'] = self.iris_targets[self.iris_frame['target']]\n iris_column_mapping = ColumnMapping()\n iris_column_mapping.prediction = self.iris_targets\n prob_classification_single_frame_performance = Dashboard(tabs=[ProbClassificationPerformanceTab()])\n prob_classification_single_frame_performance.calculate(iris_frame, None, iris_column_mapping)\n actual = json.loads(prob_classification_single_frame_performance._json())\n self.assertTrue('name' in actual)\n self.assertEqual(len(actual['widgets']), 11)\n\n\nclass TestProfiles(TestCase):\n\n ###\n # The following are extracted from the README.md file.\n ###\n def test_data_drift_profile(self):\n # To generate the **Data Drift** report, run:\n iris, iris_frame = _get_iris()\n iris_frame['prediction'] = iris.target[::-1]\n iris_data_drift_profile = Profile(sections=[DataDriftProfileSection()])\n iris_data_drift_profile.calculate(iris_frame[:100], iris_frame[100:])\n\n actual = json.loads(iris_data_drift_profile.json())\n # we leave the actual content test to other tests for widgets\n self.assertTrue('timestamp' in actual)\n self.assertEqual(len(actual), 2)\n self.assertEqual(len(actual['data_drift']['data']), 6)\n self.assertTrue('metrics' in actual['data_drift']['data'])\n\n def test_data_drift_categorical_target_drift_profile(self):\n # To generate the **Data Drift** and the **Categorical Target Drift** reports, run:\n iris, iris_frame = _get_iris()\n iris_frame['prediction'] = iris.target[::-1]\n iris_data_drift_profile = Profile(sections=[DataDriftProfileSection()])\n iris_data_drift_profile.calculate(iris_frame[:100], iris_frame[100:])\n iris_target_and_data_drift_profile = Profile(\n sections=[DataDriftProfileSection(), CatTargetDriftProfileSection()])\n iris_target_and_data_drift_profile.calculate(iris_frame[:100], iris_frame[100:])\n\n actual = json.loads(iris_target_and_data_drift_profile.json())\n # we leave the actual content test to other tests for widgets\n self.assertTrue('timestamp' in actual)\n self.assertTrue(len(actual) == 3)\n self.assertEqual(len(actual['data_drift']['data']), 6)\n self.assertEqual(len(actual['cat_target_drift']['data']), 5)\n self.assertTrue(actual['data_drift']['data'].get('metrics'))\n\n def test_regression_performance_profile(self):\n # To generate the **Regression Model Performance** report, run:\n iris, iris_frame = _get_iris()\n iris_frame['prediction'] = iris.target[::-1]\n iris_data_drift_profile = Profile(sections=[DataDriftProfileSection()])\n iris_data_drift_profile.calculate(iris_frame[:100], iris_frame[100:])\n regression_single_model_performance = Profile(sections=[RegressionPerformanceProfileSection()])\n regression_single_model_performance.calculate(iris_frame, None)\n\n actual = json.loads(regression_single_model_performance.json())\n # we leave the actual content test to other tests for widgets\n self.assertTrue('timestamp' in actual)\n self.assertTrue(len(actual) == 2)\n self.assertTrue(len(actual['regression_performance']['data']) == 5)\n self.assertTrue(actual['regression_performance']['data'].get('metrics'))\n\n def test_regression_performance_single_frame_profile(self):\n # You can also generate a **Regression Model Performance** for a single `DataFrame`. In this case, run:\n iris, iris_frame = _get_iris()\n iris_frame['prediction'] = iris.target[::-1]\n iris_data_drift_profile = Profile(sections=[DataDriftProfileSection()])\n iris_data_drift_profile.calculate(iris_frame[:100], iris_frame[100:])\n regression_single_model_performance = Profile(sections=[RegressionPerformanceProfileSection()])\n regression_single_model_performance.calculate(iris_frame, None)\n\n actual = json.loads(regression_single_model_performance.json())\n # we leave the actual content test to other tests for widgets\n self.assertTrue('timestamp' in actual)\n self.assertTrue(len(actual) == 2)\n self.assertTrue(len(actual['regression_performance']['data']) == 5)\n self.assertTrue(actual['regression_performance']['data'].get('metrics'))\n\n def test_classification_performance_profile(self):\n # To generate the **Classification Model Performance** report, run:\n iris, iris_frame = _get_iris()\n iris_frame['prediction'] = iris.target[::-1]\n iris_data_drift_profile = Profile(sections=[DataDriftProfileSection()])\n iris_data_drift_profile.calculate(iris_frame[:100], iris_frame[100:])\n classification_performance_profile = Profile(sections=[ClassificationPerformanceProfileSection()])\n classification_performance_profile.calculate(iris_frame[:100], iris_frame[100:])\n\n actual = json.loads(classification_performance_profile.json())\n # we leave the actual content test to other tests for widgets\n self.assertTrue('timestamp' in actual)\n self.assertTrue(len(actual) == 2)\n self.assertTrue(len(actual['classification_performance']['data']) == 5)\n self.assertTrue(actual['classification_performance']['data'].get('metrics'))\n\n def test_classification_performance_single_profile(self):\n iris, iris_frame = _get_iris()\n iris_frame['prediction'] = iris.target[::-1]\n iris_data_drift_profile = Profile(sections=[DataDriftProfileSection()])\n iris_data_drift_profile.calculate(iris_frame[:100], iris_frame[100:])\n classification_performance_profile = Profile(sections=[ClassificationPerformanceProfileSection()])\n classification_performance_profile.calculate(iris_frame[:100], None)\n\n actual = json.loads(classification_performance_profile.json())\n # we leave the actual content test to other tests for widgets\n self.assertTrue('timestamp' in actual)\n self.assertTrue(len(actual) == 2)\n self.assertTrue(len(actual['classification_performance']['data']) == 5)\n self.assertTrue(actual['classification_performance']['data'].get('metrics'))\n\n def test_probabilistic_classification_performance_profile(self):\n # For **Probabilistic Classification Model Performance** report, run:\n merged_reference, column_mapping = _get_probabilistic_iris()\n\n iris_prob_classification_profile = Profile(sections=[ProbClassificationPerformanceProfileSection()])\n iris_prob_classification_profile.calculate(merged_reference, merged_reference, column_mapping)\n # FIXME: this does not work! why?\n # iris_prob_classification_profile.calculate(merged_reference[:100], merged_reference[100:],\n # column_mapping = iris_column_mapping)\n\n actual = json.loads(iris_prob_classification_profile.json())\n # we leave the actual content test to other tests for widgets\n self.assertTrue('timestamp' in actual)\n self.assertEqual(len(actual), 2)\n self.assertEqual(len(actual['probabilistic_classification_performance']['data']), 5)\n self.assertEqual(len(actual['probabilistic_classification_performance']['data']['metrics']), 2)\n self.assertTrue('reference' in actual['probabilistic_classification_performance']['data']['metrics'])\n self.assertTrue('current' in actual['probabilistic_classification_performance']['data']['metrics'])\n\n def test_probabilistic_classification_single_performance_profile(self):\n # For **Probabilistic Classification Model Performance** report, run:\n merged_reference, column_mapping = _get_probabilistic_iris()\n\n iris_prob_classification_profile = Profile(sections=[ProbClassificationPerformanceProfileSection()])\n iris_prob_classification_profile.calculate(merged_reference, None, column_mapping)\n # FIXME: this does not work! why?\n # iris_prob_classification_profile.calculate(merged_reference[:100], None,\n # column_mapping = iris_column_mapping)\n\n actual = json.loads(iris_prob_classification_profile.json())\n # we leave the actual content test to other tests for widgets\n self.assertTrue('timestamp' in actual)\n self.assertEqual(len(actual), 2)\n self.assertEqual(len(actual['probabilistic_classification_performance']['data']), 5)\n self.assertEqual(len(actual['probabilistic_classification_performance']['data']['metrics']), 1)\n self.assertTrue('reference' in actual['probabilistic_classification_performance']['data']['metrics'])\n"
] |
[
[
"pandas.concat",
"numpy.random.random",
"sklearn.datasets.load_iris",
"pandas.DataFrame"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
hoopoe/face_liveness_detection
|
[
"834963001ee36b36264624b3c2fbec90f2343ce3"
] |
[
"ML/train_keras.py"
] |
[
"from __future__ import print_function\nimport os \nfrom tqdm import tqdm\nimport cv2\nimport numpy as np \nimport argparse\n\nimport keras\nfrom keras.datasets import mnist\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras import backend as K\n\nbatch_size = 32\nnum_classes = 2\nepochs = 2\n\nimages = []\nlabels = []\nim_w = 150\nim_h = 150\n\ninput_shape = (im_w, im_h, 3)\n\ndef process(live_input_dirs, fraud_input_dir):\n for images_dir in live_input_dirs:\n files = [os.path.join(images_dir, name) for name in os.listdir(images_dir) if os.path.isfile(os.path.join(images_dir, name))]\n for i in tqdm(range(0,len(files))):\n filename = os.path.join(images_dir, str(i)+\".png\")\n img = cv2.imread(filename, cv2.IMREAD_COLOR)\n images.append(img)\n labels.append(1)\n\n for images_dir in fraud_input_dir:\n files = [os.path.join(images_dir, name) for name in os.listdir(images_dir) if os.path.isfile(os.path.join(images_dir, name))]\n for i in tqdm(range(0,len(files))):\n filename = os.path.join(images_dir, str(i)+\".png\")\n img = cv2.imread(filename, cv2.IMREAD_COLOR)\n images.append(img)\n labels.append(0)\n\n\n X = np.array(images, dtype=float)\n y = np.array(labels, dtype=float)\n X /= 255\n y= y.reshape((-1,1))\n X = X.reshape((-1, im_h, im_w, 3))\n\n from sklearn.preprocessing import OneHotEncoder\n Oneencoder = OneHotEncoder()\n y = Oneencoder.fit_transform(y)\n\n model = Sequential()\n model.add(Conv2D(32, kernel_size=(3, 3),\n activation='relu',\n input_shape=input_shape))\n model.add(Conv2D(64, (3, 3), activation='relu'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Dropout(0.25))\n model.add(Flatten())\n model.add(Dense(128, activation='relu'))\n model.add(Dropout(0.5))\n model.add(Dense(num_classes, activation='softmax'))\n\n model.compile(loss=keras.losses.categorical_crossentropy,\n optimizer=keras.optimizers.Adadelta(),\n metrics=['accuracy'])\n\n model.fit(X, y,\n batch_size=batch_size,\n epochs=epochs,\n verbose=1,\n validation_split=0.2)\n\n # serialize model to YAML\n model_yaml = model.to_yaml()\n with open(\"model.yaml\", \"w\") as yaml_file:\n yaml_file.write(model_yaml)\n\n # serialize weights to HDF5\n model.save_weights(\"model.h5\")\n print(\"Saved model to disk\")\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description = 'Process video')\n parser.add_argument('-l','--live', nargs='+', help='list of live optical flow images folders', required=True)\n parser.add_argument('-f','--fraud', nargs='+', help='list of fraud ioptical flow mages folders', required=True)\n args = parser.parse_args()\n process(args.live, args.fraud)"
] |
[
[
"numpy.array",
"sklearn.preprocessing.OneHotEncoder"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Potgront/ABM
|
[
"76fef2c7ded7e362ecf72fffd82512b9d7926700",
"76fef2c7ded7e362ecf72fffd82512b9d7926700"
] |
[
"src/SA.py",
"src/cargrid.py"
] |
[
"\"\"\"\nScript to perform sobol analysis of the model.\nModified from the example sobol analysis notebook on canvas.\n\nThe variable parameters are specified in the problem dictionary.\n\"\"\"\nfrom SALib.sample import saltelli\nfrom SALib.analyze import sobol\nfrom mesa.batchrunner import BatchRunnerMP\nfrom modelgrid import *\nfrom IPython.display import clear_output\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\nfrom itertools import combinations\nfrom matplotlib import rcParams\n\ndef plot_index(s, params, i, title=''):\n \"\"\"\n Creates a plot for Sobol sensitivity analysis that shows the contributions\n of each parameter to the global sensitivity.\n\n Args:\n s (dict): dictionary {'S#': dict, 'S#_conf': dict} of dicts that hold\n the values for a set of parameters\n params (list): the parameters taken from s\n i (str): string that indicates what order the sensitivity is.\n title (str): title for the plot\n \"\"\"\n\n if i == '2':\n p = len(params)\n params = list(combinations(params, 2))\n indices = s['S' + i].reshape((p ** 2))\n indices = indices[~np.isnan(indices)]\n errors = s['S' + i + '_conf'].reshape((p ** 2))\n errors = errors[~np.isnan(errors)]\n else:\n indices = s['S' + i]\n errors = s['S' + i + '_conf']\n plt.figure()\n\n l = len(indices)\n\n plt.title(title)\n plt.ylim([-0.2, len(indices) - 1 + 0.2])\n plt.yticks(range(l), params)\n plt.errorbar(indices, range(l), xerr=errors, linestyle='None', marker='o')\n plt.axvline(0, c='k')\n fig = plt.gcf()\n fig.set_size_inches(4, 3)\n\n\nif __name__ == '__main__':\n import seaborn as sns\n sns.set()\n rcParams.update({'figure.autolayout': True})\n \n # Variable parameters\n problem = {'num_vars': 3,\n 'names': ['spawn', 'agression', 'min_gap'],\n 'bounds': [[0.3, 0.8], [0.2, 0.8], [0.5, 2.0]]}\n \n replicates = 5\n max_steps = 5000\n distinct_samples = 5\n \n param_values = saltelli.sample(problem, distinct_samples)\n \n model_reporters={'Final_avg_speed': avg_speed,\n 'Final_Cars_in_lane': cars_in_lane,\n 'Data Collector': lambda m: m.datacollector,\n 'Total_Avg_speed': avg_speed,\n 'Total_Cars_in_lane': cars_in_lane,\n 'Variance_speed': avg_speed,\n 'Variance_car': cars_in_lane}\n \n batch = BatchRunnerMP(RoadSim,\n nr_processes=8,\n max_steps=max_steps,\n variable_parameters={name:[] for name in problem['names']},\n model_reporters=model_reporters)\n \n count = 0\n for i in tqdm(range(replicates)):\n for vals in tqdm(param_values):\n vals = list(vals)\n variable_parameters = {}\n for name, val in zip(problem['names'], vals):\n variable_parameters[name] = val\n batch.run_iteration(variable_parameters, tuple(vals), count)\n count += 1\n \n data_original = batch.get_model_vars_dataframe()\n data = data_original.copy()\n print(data.shape)\n \n for i in tqdm(range(len(data[\"Data Collector\"]))):\n if isinstance(data[\"Data Collector\"][i], DataCollector):\n data_speed = data[\"Data Collector\"][i].get_model_vars_dataframe()['Avg_speed']\n data_cars = data[\"Data Collector\"][i].get_model_vars_dataframe()['Cars_in_lane']\n tenproc = int(0.2 * (len(data_speed)))\n data['Total_Avg_speed'][i] = np.average(data_speed[tenproc:])\n data['Total_Cars_in_lane'][i] = np.average(data_cars[tenproc:])\n data['Variance_speed'][i] = np.var(data_speed[tenproc:])\n data['Variance_car'][i] = np.var(data_cars[tenproc:])\n \n \n data.to_csv('Sobol_result.csv', sep=',', index=False)\n \n print(data)\n \n Si_Speed = sobol.analyze(problem, data['Total_Avg_speed'].as_matrix(), print_to_console=False)\n print(\"\\n\")\n Si_Cars = sobol.analyze(problem, data['Total_Cars_in_lane'].as_matrix(), print_to_console=False)\n \n \n \n typename = [\"Average_speed\", \"Number_of_cars\"]\n for i, Si in enumerate((Si_Speed, Si_Cars)):\n # First order\n plot_index(Si, problem['names'], '1', 'First order sensitivity - ' + typename[i])\n plt.savefig('plots/First_order_sensitivity_|_' + typename[i] + '.png')\n plt.clf()\n \n # Second order\n plot_index(Si, problem['names'], '2', 'Second order sensitivity - ' + typename[i])\n plt.savefig('plots/Second_order_sensitivity_|_' + typename[i] + '.png')\n plt.clf()\n \n # Total order\n plot_index(Si, problem['names'], 'T', 'Total order sensitivity - ' + typename[i])\n plt.savefig('plots/Total_order_sensitivity_|_' + typename[i] + '.png')\n plt.clf()\n",
"\"\"\"\nModule which defines the car agents\n\"\"\"\nfrom mesa import Agent\nimport numpy as np\n\n\nclass Car(Agent):\n \"\"\"\n Class which defines the inidividual car agents.\n Each car has a specific unique_id and an index which is the\n unique_id modulo the resolution of the LaneSpace.\n\n Attributes:\n unique_id (int): An integer value which is uniquely defines each agent\n model (obj): An instance of the model class\n index (int): The unique_id modulo the resolution of the LaneSpace\n defined in the model instance.\n pos (tuple): The position of the car agent. The first argument of the\n tuple defines the position along the horizontal continuous axis,\n the second value specifies the current lane of the car.\n max_speed (float): A constant value which defines the upper limit of\n the cars' speed.\n speed (float): A variable value which specifies the current speed of\n the car, cannot exceed the value defined in max_speed.\n agression (float): Defines the agression of the car, between [0,1].\n Results in the car swiching lanes more often as it increases.\n Also makes acceleration more likely if possible.\n gap (float): Defines the space cars keep between each other, relative\n to their speeds, e.g. a value of 2 would result in a gap equal to\n twice the cars' speed, so 20 meters at a speed of 10 m/s.\n Higher agression can occasionally override this specified gap.\n switch_delay (int): Defines the number of time steps a car waits\n between switching lanes. High agression lowers this value.\n switched (int): Counter for the number of time steps since last\n switching a lane. Decreases by one each timestep and allows the car\n to switch lanes if at zero. Is set to the value of switch_delay if\n the car switches a lane.\n \"\"\"\n # pylint: disable=too-many-instance-attributes\n # pylint: disable=too-many-arguments\n\n def __init__(self, unique_id, model, start_lane,\n speed, agression, min_gap):\n \"\"\"\n Args:\n unique_id (int): The unique id of the current agent, generated by\n agent scheduler.\n model (obj): Instance of the LaneSpace model\n start_lane (int): The lane in which the car should start.\n speed (float): Initial speed of the car, also used to set the\n maximum speed of the car.\n agression (float): Agression of the car, bounded between [0,1].\n min_gap (float): The absolute minimum space the car should\n maintain, relative to it's own speed.\n \"\"\"\n super().__init__(unique_id, model)\n self.start_lane = start_lane\n self.index = self.unique_id % model.grid.length\n self.pos = (0.0, start_lane)\n self.max_speed = speed+(abs(np.random.randn())*agression)\n self.speed = self.max_speed\n self.agression = agression\n self.gap = np.random.rand() / agression + min_gap\n self.switch_delay = int(5 / agression / self.model.time_step)\n self.switched = self.switch_delay\n\n def compute_pars(self, FRONT, BACK):\n \"\"\"compute_pars\n\n Method which determines weather a car can switch to another lane or\n maintain it's current speed.\n\n Args:\n FRONT (list): A list which should contain the positions of the cars\n in front of the current car, on the right, middle and left. In\n that specific order.\n BACK (list): A list which should contain the postitions of the cars\n behind the current car, on the right, middle and left. In that\n specific order.\n\n Returns:\n can_left (bool): Can the car switch to the left?\n can_middle (bool): Can the car go forward?\n can_right (bool): Can the car switch to the right?\n \"\"\"\n rf, mf, lf = FRONT # right_front, middle_front, left_front\n rb, mb, lb = BACK # right_back, middle_back, left_back\n\n \"\"\"\n Can the car turn left?\n The available space to the left front car should be larger than the\n cars' current speed multiplied by the minimum gap the car has to\n maintain. The gap to the car behind should be 0.5 times this\n distance as the car is also moving forward.\n Also checks if a lane exists on the left and if the car has recovered\n from the previous lane switch\n \"\"\"\n can_left = lf-self.pos[0] > self.gap * self.speed and\\\n self.pos[0]-lb > 0.5*self.gap * self.speed and\\\n self.pos[1] < (self.model.lanes - 1) and\\\n self.switched == 0\n\n \"\"\"\n Can the car turn right?\n The available space to the right front should be larger than the cars'\n current speed multiplied by the minimum gap the car has to maintain.\n The gap to the car behind should be 0.5 times this distance as the car\n is also moving forward.\n Also checks if the car is not already in the rightmost lane and has\n recovered from the previous lane switch\n \"\"\"\n can_right = rf-self.pos[0] > self.gap * self.speed and\\\n self.pos[0]-rb > 0.5*self.gap * self.speed and\\\n self.pos[1] > 0 and\\\n self.switched == 0\n\n \"\"\"\n Can the car go forward (to the middle)?\n This gap should be larger than minimum gap multiplied by the\n cars' current speed.\n \"\"\"\n can_middle = mf - self.pos[0] > self.gap*self.speed\n\n return can_left, can_middle, can_right\n\n def get_move(self):\n \"\"\"\n Method which determines the best possible move of the car,\n depedent on the agression, current speed, minimal gap, and\n postions of the six surrouding cars.\n\n This move is determined in a loop which first determines which\n moves are initially possible. It then uses the agression of the\n car to decide if the car should keep right, overtake, maintain\n in the current lane, or slow down.\n\n Returns:\n Integer of the best possible move: -1 if right, 0 if forward,\n 1 if left.\n \"\"\"\n self.switched -= 1\n self.switched = max(0, self.switched)\n FRONT, BACK = self.model.grid.get_neighbors(self)\n rf, mf, lf = FRONT # right_front, middle_front, left_front\n rb, mb, lb = BACK # right_back, middle_back, left_back\n\n while True:\n cl, cm, cr = self.compute_pars(FRONT, BACK) # can_left, can_middle, can_right\n\n if cm: # Can i go forward at current speed?\n if cr and np.random.rand() > self.agression:\n \"\"\"\n Keep right if possible, probability decreases with\n increasing agression\n \"\"\"\n self.switched = self.switch_delay\n return -1\n\n if (self.speed < self.max_speed) and\\\n (np.random.rand() < self.agression):\n \"\"\"\n Speed up if slowed down, probability increases\n with increasing agression. Also overtake to the\n left if possible\n \"\"\"\n self.check_speed(FRONT[1]-self.pos[0])\n if cl:\n return 1\n return 0\n\n if cl and cr: # Can i go left and right?\n if (self.speed < self.max_speed) and\\\n (np.random.rand() < self.agression):\n \"\"\"\n Overtake on the left if slowed and agression allows.\n Speed up relative to the agression of the car.\n \"\"\"\n self.speed += np.random.rand()/self.agression*self.model.time_step\n self.switched = self.switch_delay\n return 1\n if np.random.rand() > self.agression:\n \"\"\"\n Hold right if agression is low. Also slow down a bit\n so not to overtake on the right, scaling with agression.\n \"\"\"\n self.speed -= np.random.rand()/self.agression*self.model.time_step\n self.switched = self.switch_delay\n return -1\n if rf > lf:\n \"\"\"\n Otherwise go to the lane with the most space in front.\n \"\"\"\n return -1\n return 1\n\n if cl and (np.random.rand() < self.agression): # Can i go left?\n \"\"\"\n Move to the left if agression allows.\n \"\"\"\n self.switched = self.switch_delay\n return 1\n\n if cr: # Can i go right?\n \"\"\"\n Move to the right and slow down so not to overtake on\n the right. Deceleration decreases with agresion, so\n high agression could result in an overtake on the right.\n \"\"\"\n self.switched = self.switch_delay\n self.speed -= np.random.rand()/self.agression*self.model.time_step\n return -1\n\n \"\"\"\n Slow down if none of the moves are possible and try all\n posibilites again. Recalculating the boolean values each loop.\n \"\"\"\n self.speed -= np.random.rand()*self.model.time_step\n\n def check_speed(self, gap):\n \"\"\"\n Check how much the car is slowed down and the gap to the car in front.\n Accelerate faster if agression is high, gap is large, or the car is\n slowed down a lot.\n\n Args:\n gap (float): Gap to the car in front\n \"\"\"\n diff = self.max_speed - self.speed\n space = (gap-self.speed)/self.speed/self.gap/self.agression\n speedup = max(np.random.rand(), np.log(diff*space))*self.model.time_step\n self.speed += speedup\n\n def step(self):\n \"\"\"\n Method used by the mesa scheduler to advance each car.\n Obtains a move from the get_move method and applies this\n to the overall LaneSpace model. Also performs a global check\n if the car is not exceeding its maximum speed.\n \"\"\"\n move = self.get_move()\n self.model.move(self, move)\n if self.speed > self.max_speed:\n self.speed -= np.random.rand()*self.model.time_step\n"
] |
[
[
"matplotlib.pyplot.axvline",
"matplotlib.pyplot.title",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.gcf",
"matplotlib.pyplot.clf",
"matplotlib.rcParams.update",
"matplotlib.pyplot.figure"
],
[
"numpy.log",
"numpy.random.randn",
"numpy.random.rand"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
seung-lab/NeuroglancerAnnotationUI
|
[
"0429b93330b7aa83f4c591564978b3ceb9229374"
] |
[
"src/nglui/easyviewer/base.py"
] |
[
"from .. import nglite as neuroglancer\nfrom . import annotation, utils\nfrom numpy import issubdtype, integer, uint64, vstack\nfrom collections import OrderedDict\nimport copy\nimport re\n\nSEGMENTATION_LAYER_TYPES = [\"segmentation\", \"segmentation_with_graph\"]\n\n\nclass EasyViewer(neuroglancer.Viewer):\n \"\"\"\n Extends the neuroglancer Viewer object to make simple operations simple.\n \"\"\"\n\n def __init__(self):\n super(EasyViewer, self).__init__()\n\n def __repr__(self):\n return self.as_url()\n\n def _repr_html_(self):\n return '<a href=\"%s\" target=\"_blank\">Viewer</a>' % self.as_url()\n\n def load_url(self, url):\n \"\"\"Load neuroglancer compatible url and updates viewer state\n\n Attributes:\n url (str): neuroglancer url\n\n \"\"\"\n state = neuroglancer.parse_url(url)\n self.set_state(state)\n\n @staticmethod\n def _smart_add_segmentation_layer(s, layer_name, source, **kwargs):\n if re.search(r\"^graphene://\", source) is not None:\n s.layers[layer_name] = neuroglancer.ChunkedgraphSegmentationLayer(\n source=source, **kwargs\n )\n elif re.search(r\"^precomputed://\", source) is not None:\n s.layers[layer_name] = neuroglancer.SegmentationLayer(\n source=source, **kwargs\n )\n\n def add_layers(\n self,\n image_layers={},\n segmentation_layers={},\n annotation_layers={},\n resolution=None,\n ):\n with self.txn() as s:\n for ln, kws in image_layers.items():\n s.layers[ln] = neuroglancer.ImageLayer(**kws)\n for ln, kws in segmentation_layers.items():\n self._smart_add_segmentation_layer(s, **kws)\n for ln, kws in annotation_layers.items():\n s.layers[ln] = neuroglancer.AnnotationLayer(**kws)\n if resolution is not None:\n s.voxel_size = resolution\n pass\n\n def add_segmentation_layer(self, layer_name, source, **kwargs):\n \"\"\"Add segmentation layer to viewer instance.\n\n Attributes:\n layer_name (str): name of layer to be displayed in neuroglancer ui.\n source (str): source of neuroglancer segment layer\n \"\"\"\n with self.txn() as s:\n self._smart_add_segmentation_layer(\n s, layer_name=layer_name, source=source, **kwargs\n )\n\n def add_image_layer(self, layer_name, source, **kwargs):\n \"\"\"Add segmentation layer to viewer instance.\n\n Attributes:\n layer_name (str): name of layer to be displayed in neuroglancer ui.\n source (str): source of neuroglancer image layer\n \"\"\"\n with self.txn() as s:\n s.layers[layer_name] = neuroglancer.ImageLayer(source=source, **kwargs)\n\n def set_resolution(self, resolution):\n with self.txn() as s:\n s.voxel_size = resolution\n\n def add_contrast_shader(self, layer_name, black=0.0, white=1.0):\n shader_text = f\"#uicontrol float black slider(min=0, max=1, default={black})\\n#uicontrol float white slider(min=0, max=1, default={white})\\nfloat rescale(float value) {{\\n return (value - black) / (white - black);\\n}}\\nvoid main() {{\\n float val = toNormalized(getDataValue());\\n if (val < black) {{\\n emitRGB(vec3(0,0,0));\\n }} else if (val > white) {{\\n emitRGB(vec3(1.0, 1.0, 1.0));\\n }} else {{\\n emitGrayscale(rescale(val));\\n }}\\n}}\\n\"\n self._update_layer_shader(layer_name, shader_text)\n\n def _update_layer_shader(self, layer_name, shader_text):\n with self.txn() as s:\n s.layers[layer_name]._json_data[\"shader\"] = shader_text\n\n def set_state_server(self, state_server):\n with self.txn() as s:\n s._json_data[\"jsonStateServer\"] = state_server\n\n def add_annotation_layer(\n self,\n layer_name=None,\n color=None,\n linked_segmentation_layer=None,\n filter_by_segmentation=False,\n brackets_show_segmentation=True,\n selection_shows_segmentation=True,\n tags=None,\n ):\n \"\"\"Add annotation layer to the viewer instance.\n\n Attributes:\n layer_name (str): name of layer to be created\n \"\"\"\n if layer_name is None:\n layer_name = \"annos\"\n if layer_name in [l.name for l in self.state.layers]:\n return\n\n if linked_segmentation_layer is None:\n filter_by_segmentation = None\n\n with self.txn() as s:\n new_layer = neuroglancer.AnnotationLayer(\n linked_segmentation_layer=linked_segmentation_layer,\n filter_by_segmentation=filter_by_segmentation,\n brackets_show_segmentation=brackets_show_segmentation,\n selection_shows_segmentation=selection_shows_segmentation,\n )\n s.layers.append(name=layer_name, layer=new_layer)\n if color is not None:\n s.layers[layer_name].annotationColor = color\n if tags is not None:\n self.add_annotation_tags(layer_name=layer_name, tags=tags)\n\n def set_annotation_layer_color(self, layer_name, color):\n \"\"\"Set the color for the annotation layer\"\"\"\n if layer_name in [l.name for l in self.state.layers]:\n with self.txn() as s:\n s.layers[layer_name].annotationColor = color\n else:\n pass\n\n def clear_annotation_layers(self, layer_names):\n with self.txn() as s:\n for ln in layer_names:\n s.layers[ln].annotations._data = []\n\n def set_annotation_one_shot(self, ln_anno_dict):\n \"\"\"\n ln_anno_dict is a layer_name to annotation list dict.\n \"\"\"\n with self.txn() as s:\n for ln, annos in ln_anno_dict.items():\n s.layers[ln].annotations._data = annos\n\n def add_annotations(self, layer_name, annotations):\n \"\"\"Add annotations to a viewer instance, the type is specified.\n If layer name does not exist, add the layer\n\n Attributes:\n layer_name (str): name of layer to be displayed in neuroglancer ui.\n layer_type (str): can be: 'points, ellipse or line' only\n \"\"\"\n with self.txn() as s:\n for anno in annotations:\n s.layers[layer_name].annotations.append(anno)\n\n def remove_annotations(self, layer_name, anno_ids):\n if isinstance(anno_ids, str):\n anno_ids = [anno_ids]\n try:\n with self.txn() as s:\n el = len(s.layers[layer_name].annotations)\n for anno in reversed(s.layers[layer_name].annotations):\n el -= 1\n if anno.id in anno_ids:\n anno_ids.remove(anno.id)\n s.layers[layer_name].annotations.pop(el)\n if len(anno_ids) == 0:\n break\n except:\n self.update_message(\"Could not remove annotation\")\n\n def add_annotation_tags(self, layer_name, tags):\n \"\"\"\n Add a list of tags to an annotation layer\n \"\"\"\n if layer_name not in self.layer_names:\n raise ValueError(\"Layer is not an annotation layer\")\n tag_list = [\n OrderedDict({\"id\": tag_id + 1, \"label\": label})\n for tag_id, label in enumerate(tags)\n ]\n with self.txn() as s:\n s.layers[layer_name]._json_data[\"annotationTags\"] = tag_list\n\n def update_description(self, layer_id_dict, new_description):\n layer_id_dict = copy.deepcopy(layer_id_dict)\n with self.txn() as s:\n try:\n for layer_name, id_list in layer_id_dict.items():\n for anno in s.layers[layer_name].annotations:\n if anno.id in id_list:\n if anno.description is None:\n anno.description = new_description\n else:\n anno.description = \"{}\\n{}\".format(\n anno.description, new_description\n )\n id_list.remove(anno.id)\n if len(id_list) == 0:\n break\n except Exception as e:\n print(e)\n self.update_message(\"Could not update descriptions!\")\n\n @property\n def url(self):\n return self.get_viewer_url()\n\n def as_url(self, prefix=None, as_html=False, link_text=\"Neuroglancer link\"):\n if prefix is None:\n prefix = utils.default_neuroglancer_base\n ngl_url = neuroglancer.to_url(self.state, prefix=prefix)\n if as_html:\n return '<a href=\"{}\" target=\"_blank\">{}</a>'.format(ngl_url, link_text)\n else:\n return ngl_url\n\n def update_message(self, message):\n with self.config_state.txn() as s:\n if message is not None:\n s.status_messages[\"status\"] = message\n\n def set_selected_layer(self, layer_name, tool=None):\n if layer_name in self.layer_names:\n with self.txn() as s:\n s._json_data[\"selectedLayer\"] = OrderedDict(\n layer=layer_name, visible=True\n )\n if tool is not None:\n s.layers[layer_name]._json_data[\"tool\"] = tool\n\n def get_selected_layer(self):\n state_json = self.state.to_json()\n try:\n selected_layer = state_json[\"selectedLayer\"][\"layer\"]\n except:\n selected_layer = None\n return selected_layer\n\n def get_annotation(self, layer_name, aid):\n if self.state.layers[layer_name].type == \"annotation\":\n for anno in self.state.layers[layer_name].annotations:\n if anno.id == aid:\n return anno\n else:\n return None\n else:\n return None\n\n def get_selected_annotation_id(self):\n layer_name = self.get_selected_layer()\n try:\n aid_data = self.state.layers[layer_name]._json_data[\"selectedAnnotation\"]\n if isinstance(aid_data, OrderedDict):\n aid = aid_data[\"id\"]\n else:\n aid = aid\n except:\n aid = None\n return aid\n\n def select_annotation(self, layer_name, aid):\n if layer_name in self.layer_names:\n with self.txn() as s:\n s.layers[layer_name]._json_data[\"selectedAnnotation\"] = aid\n self.set_selected_layer(layer_name)\n\n @property\n def layer_names(self):\n return [l.name for l in self.state.layers]\n\n def selected_objects(self, segmentation_layer):\n return list(self.state.layers[segmentation_layer].segments)\n\n def add_selected_objects(self, segmentation_layer, oids, colors=None):\n if issubdtype(type(oids), integer):\n oids = [oids]\n\n with self.txn() as s:\n for oid in oids:\n s.layers[segmentation_layer].segments.add(uint64(oid))\n\n if colors is not None:\n if isinstance(colors, dict):\n self.assign_colors(segmentation_layer, colors)\n elif len(colors) == len(oids):\n seg_colors = {str(oid): clr for oid, clr in zip(oids, colors)}\n self.assign_colors(segmentation_layer, seg_colors)\n\n def get_mouse_coordinates(self, s):\n pos = s.mouse_voxel_coordinates\n return pos\n\n def set_view_options(\n self,\n show_slices=None,\n layout=None,\n show_axis_lines=None,\n show_scale_bar=None,\n orthographic=None,\n position=None,\n zoom_image=None,\n zoom_3d=None,\n ):\n with self.txn() as s:\n if show_slices is not None:\n s.showSlices = show_slices\n if layout is not None:\n s.layout.type = layout\n if show_axis_lines is not None:\n s.show_axis_lines = show_axis_lines\n if show_scale_bar is not None:\n s.show_scale_bar = show_scale_bar\n if orthographic is not None:\n s.layout.orthographic_projection = orthographic\n if position is not None:\n s.position.voxelCoordinates = position\n if zoom_image is not None:\n s.navigation.zoomFactor = zoom_image\n if zoom_3d is not None:\n s.perspectiveZoom = zoom_3d\n\n def set_segmentation_view_options(\n self,\n layer_name,\n alpha_selected=None,\n alpha_3d=None,\n alpha_unselected=None,\n ):\n if self.state.layers[layer_name].type not in SEGMENTATION_LAYER_TYPES:\n return\n with self.txn() as s:\n l = s.layers[layer_name]\n if alpha_selected is not None:\n l.selectedAlpha = alpha_selected\n if alpha_3d is not None:\n l.objectAlpha = alpha_3d\n if alpha_unselected is not None:\n l.notSelectedAlpha = alpha_unselected\n\n def set_timestamp(\n self,\n layer_name,\n timestamp=None,\n ):\n \"\"\"Set timestamp of a segmentation layer\n\n Parameters\n ----------\n layer_name : str\n Name of a segmentation layer\n timestamp : float, optional\n Timestamp in unix epoch time (e.g. `time.time.now()` in python), by default None\n \"\"\"\n if self.state.layers[layer_name].type != \"segmentation_with_graph\":\n return\n with self.txn() as s:\n l = s.layers[layer_name]\n if timestamp is not None:\n l.timestamp = int(timestamp)\n else:\n l.timestamp = None\n\n def assign_colors(self, layer_name, seg_colors):\n \"\"\"Assign colors to root ids in a segmentation layer\n\n Parameters\n ----------\n layer_name : str,\n Segmentation layer name\n seg_colors : dict\n dict with root ids as keys and colors as values.\n \"\"\"\n with self.txn() as s:\n if seg_colors is not None:\n seg_colors = {\n str(oid): k for oid, k in seg_colors.items() if k is not None\n }\n s.layers[layer_name]._json_data[\"segmentColors\"] = seg_colors\n\n def set_multicut_points(\n self,\n layer_name,\n seg_id,\n points_red,\n points_blue,\n supervoxels_red=None,\n supervoxels_blue=None,\n focus=True,\n ):\n \"\"\"Configures multicut points in the neuroglancer state. Note that points need to be in mesh units (e.g. nanometers), not voxels!\n\n Parameters\n ----------\n layer_name : str\n Segmentation layer name\n seg_id : np.uint64\n Segmentation id of the object in question\n points_red : np.array\n Nx3 array of locations in voxel space for side 1 of the cut.\n points_blue : np.array\n Mx3 array of locations in voxel space for side 2 of the cut.\n supervoxels_red : np.array or None, optional\n N-length array of supervoxel ids associated with locations in points_red or None. If None, supervoxels lookup occurs based on the mesh. By default None\n supervoxels_blue : np.array or None, optional\n M-length array of supervoxel ids associated with locations in points_blue or None. If None, supervoxels lookup occurs based on the mesh. By default None\n focus : bool, optional\n If True, makes the layer and graph tool focused. By default True\n \"\"\"\n\n def _multicut_annotation(pt, oid, sv_id):\n if sv_id is None:\n sv_id = oid\n return annotation.point_annotation(\n pt, description=str(sv_id), linked_segmentation=[sv_id, oid]\n )\n\n if supervoxels_red is None:\n supervoxels_red = [None for x in points_red]\n if supervoxels_blue is None:\n supervoxels_blue = [None for x in points_blue]\n\n annos_red = neuroglancer.annotationHolder()\n for pt, sv_id in zip(points_red, supervoxels_red):\n annos_red.annotations.append(\n _multicut_annotation(pt * self.state.voxel_size, seg_id, sv_id)\n )\n\n annos_blue = neuroglancer.annotationHolder()\n for pt, sv_id in zip(points_blue, supervoxels_blue):\n annos_blue.annotations.append(\n _multicut_annotation(pt * self.state.voxel_size, seg_id, sv_id)\n )\n\n self.add_selected_objects(layer_name, [seg_id])\n\n with self.txn() as s:\n l = s.layers[layer_name]\n l.tab = \"graph\"\n l.graphOperationMarker.append(annos_red)\n l.graphOperationMarker.append(annos_blue)\n\n if focus:\n self.set_selected_layer(layer_name)\n ctr_pt = vstack([points_red, points_blue]).mean(axis=0)\n self.set_view_options(position=ctr_pt, zoom_3d=100)\n"
] |
[
[
"numpy.uint64",
"numpy.vstack"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jonbinney/trajectory_smoothing
|
[
"0e2b8d7d646c96c0c22eef1371bcd42d169121dc"
] |
[
"traj/scripts/synchronized_traj_example.py"
] |
[
"#!/usr/bin/env python3\n'''\nexample to check the joint motion synchronization algorithm [full trajectory] \n'''\nimport numpy as np\nimport math\nimport traj\nfrom matplotlib import pyplot as plt\nimport rospy\n\nrospy.init_node('traj_synchronization', log_level=rospy.DEBUG)\n# limits, option_1: same limits that Jon used in first demo file\nabs_max_pos = np.deg2rad(np.array([ 185.0, 60.0, 132.0, 360.0, 125.0, 360.0]))\nabs_max_vel = np.deg2rad(np.array([ 150.0, 150.0, 200.0, 300.0, 300.0, 600.0]))\nabs_max_acc = np.deg2rad(np.array([ 500.0, 500.0, 700.0, 1100.0, 1100.0, 2500.0]))\nabs_max_jrk = np.deg2rad(np.array([ 4500.0, 4500.0, 5000.0, 8000.0, 8000.0, 16000.0]))\n\n# limits, option_2: r-2000ic/165f that Gijs send\nabs_max_pos = np.deg2rad(np.array([ 185.0, 60.0, 132.0, 360.0, 125.0, 360.0]))\nabs_max_vel = np.deg2rad(np.array([ 1.300e+02, 1.150e+02, 1.250e+02, 1.800e+02, 1.800e+02, 2.600e+02 ]))\nabs_max_acc = np.deg2rad(np.array([ 2.532467e+02, 2.240260e+02, 2.435065e+02, 3.506494e+02, 3.506494e+02, 5.064935e+02]))\nabs_max_jrk = np.deg2rad(np.array([ 9.866757e+02, 8.728286e+02, 9.487267e+02, 1.366166e+03, 1.366166e+03, 1.973351e+03]))\n\n#limits, option_3: M-20iB/25C that Gijs send\nabs_max_pos = np.array([ 2.967060, 2.443461, 5.215218, 3.490659, 2.530727, 4.712389 ])\nabs_min_pos = np.array([-2.967060, -1.745329, -2.600541, -3.490659, -2.530727, -4.712389 ])\n# for now we consider even max/min position limits \npos_limits = [min(a, abs(b)) for a,b in zip(abs_max_pos, abs_min_pos)] \nabs_max_pos = np.array(pos_limits)\nabs_max_vel = np.array([ 3.577925, 3.577925, 4.537856, 7.243116, 7.243116, 15.358897])\nabs_max_acc = np.array([ 12.423351, 12.423351, 15.756445, 25.149706, 25.149706, 53.329513])\nabs_max_jrk = np.array([ 86.273266, 86.273266, 109.419752, 174.650735, 174.650735, 370.343857])\n\n# print the limits\nrospy.logdebug(\"> abs_max_pos:{}\".format(abs_max_pos))\nrospy.logdebug(\"> abs_max_vel:{}\".format(abs_max_vel))\nrospy.logdebug(\"> abs_max_acc:{}\".format(abs_max_acc))\nrospy.logdebug(\"> abs_max_jrk:{}\".format(abs_max_jrk))\n\n# path_option_1: Jon's path [the one Jon used for the first demo with zeros velocities]\npath =[]\npath.append([ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])\npath.append([ 1.5, 0.7, 0.3, 0.0, 0.0, 0.0])\npath.append([ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])\npath.append([-1.5, 0.7, 0.3, 0.0, 0.0, 0.0])\npath.append([ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])\n#there is only one point that is not changing the motion direction \nestimated_vel = [ ]\nestimated_vel.append([ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])\nestimated_vel.append([ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])\nestimated_vel.append([ -2.7, 0.0, 0.0, 0.0, 0.0, 0.0])\nestimated_vel.append([ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])\nestimated_vel.append([ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])\n\n#path_option_1: random traj & random velocities\npath =[]\npath.append([ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])\npath.append([ 1.0, 0.4, 0.5, 0.5, 0.0, 0.0])\npath.append([ 1.5, 0.2, 0.7, 0.8, 0.0, 0.0])\npath.append([ 2.0, 0.0, 0.9, 1.2, 0.0, 0.0])\npath.append([ 0.5, -0.6, 0.4, -.5, 0.0, 0.0])\npath.append([ 0.0, -0.8, 0.0, -1.0, 0.0, 0.0])\nestimated_vel = [ ]\nestimated_vel.append([ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])\nestimated_vel.append([ 1.4, 0.0, 0.5, 0.7, 0.0, 0.0])\nestimated_vel.append([ 1.4, -0.6, 0.5, 0.7, 0.0, 0.0])\nestimated_vel.append([ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])\nestimated_vel.append([-0.9, -0.3, -0.6, -0.9, 0.0, 0.0])\nestimated_vel.append([ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])\n\nn_jts = len(path[0])\nn_wpts = len(path)\nn_segs = n_wpts - 1\nmin_sync_time_seg = [ ]\nphases_dur_seg_jt = [ ]\nphases_jrk_seg_jt = [ ]\n\n# variables for sampling times and plotting\nfrq = 125.0\nt_start = 0.0\nabs_t = t_start\ntraj_pos = [ [] for jt in range(n_jts)]\ntraj_vel = [ [] for jt in range(n_jts)]\ntraj_acc = [ [] for jt in range(n_jts)]\ntraj_jrk = [ [] for jt in range(n_jts)]\ntraj_time = [ ]\n\nwaypt_times = [ ]\nwaypt_times.append(t_start)\nfor seg in range(n_segs):\n\trospy.logdebug(\"\\n\\n>> seg_numer: {}\".format(seg))\n\tmin_sync_time, phase_dur_jt, phase_jrk_jt = traj.segment_synchronization(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tpath[seg], path[seg+1], estimated_vel[seg], estimated_vel[seg+1],\n\t\t \t\t\t\t\t\tabs_max_pos, abs_max_vel, abs_max_acc, abs_max_jrk)\n\twaypt_times.append(waypt_times[-1] + min_sync_time)\n\twhile abs_t <= waypt_times[-1]:\n\t\tfor jt in range(n_jts):\n\t\t\tp_start = path[seg][jt]\n\t\t\tv_start = estimated_vel[seg][jt]\n\t\t\tphases_dur = phase_dur_jt[jt]\n\t\t\tphases_jrk = phase_jrk_jt[jt]\n\t\t\tpos, vel, acc, jrk = traj.sample_segment(abs_t, waypt_times[-2], p_start, v_start, phases_jrk, phases_dur)\n\t\t\ttraj_pos[jt].append(pos)\n\t\t\ttraj_vel[jt].append(vel)\n\t\t\ttraj_acc[jt].append(acc)\n\t\t\ttraj_jrk[jt].append(jrk)\t\n\t\ttraj_time.append(abs_t)\n\t\tabs_t = abs_t + 1/frq\n\n# plot pos, vel, acc, jrk. plot waypoints and estimated velocity as well to check if there is any difference \nfig, axes = plt.subplots(4, sharex=True)\nfor jt in range(0, n_jts): \n axes[0].plot(traj_time, traj_pos[jt])\n axes[1].plot(traj_time, traj_vel[jt])\n axes[2].plot(traj_time, traj_acc[jt])\n axes[3].plot(traj_time, traj_jrk[jt])\n axes[0].plot(waypt_times, [path[wpt][jt] for wpt in range(n_wpts)], '*')\n axes[1].plot(waypt_times, [estimated_vel[wpt][jt] for wpt in range(n_wpts)], '*')\naxes[0].grid()\naxes[1].grid()\naxes[2].grid()\naxes[3].grid()\naxes[0].set_ylabel('position')\naxes[1].set_ylabel('velocity')\naxes[2].set_ylabel('acceleration')\naxes[3].set_ylabel('jerk')\naxes[3].set_xlabel('Time')\nplt.legend()\nplt.show()\n\n# store outputs [pos, vel, acc, jrk] in csv file\n# traj_pos = list(map(list, zip(*traj_pos)))\n# traj_vel = list(map(list, zip(*traj_vel)))\n# traj_acc = list(map(list, zip(*traj_acc)))\n# traj_jrk = list(map(list, zip(*traj_jrk)))\n# import csv\n# with open(\"sampled_traj_time_pos_vel_acc_jrk_125.csv\", \"wb\") as csv_file:\n# writer = csv.writer(csv_file, delimiter=',')\n# for pt in range(len(traj_time)):\n# writer.writerow([traj_time[pt]] + traj_pos[pt] + traj_vel[pt] + traj_acc[pt] + traj_jrk[pt])\n\n# with open(\"sampled_traj_time_positions_125.csv\", \"wb\") as csv_file:\n# writer = csv.writer(csv_file, delimiter=',')\n# for pt in range(len(traj_time)):\n# writer.writerow([traj_time[pt]] + traj_pos[pt])\n"
] |
[
[
"matplotlib.pyplot.legend",
"numpy.array",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
1129ljc/video-inpainting-detection
|
[
"9a1aea6268f3ab2ba2f60c526ddf35ccc8350e04",
"9a1aea6268f3ab2ba2f60c526ddf35ccc8350e04"
] |
[
"Unet/test.py",
"IIDNET/main.py"
] |
[
"import os\nimport cv2\nimport numpy as np\nimport torch\nfrom torchvision import transforms\nfrom torch.utils.data import DataLoader\nfrom torch.utils.data import Dataset\n\nfrom postprocessing import post_deal\n\nclass IID_Dataset(Dataset):\n def __init__(self, dataset):\n self.input_size = (512, 512)\n self.image_path = dataset\n self.train_files = []\n names = os.listdir(self.image_path)\n for i in range(len(names)):\n name = names[i]\n image_name_dir = os.path.join(self.image_path, name)\n image_files = sorted(os.listdir(image_name_dir))\n image_num = len(image_files)\n for j in range(image_num):\n image_file = os.path.join(image_name_dir, image_files[j])\n self.train_files.append(image_file)\n\n self.transform = transforms.Compose([\n transforms.ToTensor(),\n # transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n ])\n\n def __len__(self):\n return len(self.train_files)\n\n def __getitem__(self, item):\n fname1 = self.train_files[item]\n\n img = cv2.imread(fname1)\n img = cv2.resize(img, self.input_size)\n img = self.transform(img)\n return img, fname1\n\n\ndef test(args):\n dataset = args['dataset']\n ckpt = args['ckpt']\n gpu_id = args['gpu_id']\n save = args['save']\n\n device = torch.device('cuda:' + str(gpu_id))\n model = torch.load(ckpt)\n model = model.to(device=device)\n model.eval()\n\n test_dataset = IID_Dataset(dataset)\n test_loader = DataLoader(dataset=test_dataset, batch_size=1, shuffle=False, num_workers=4)\n \n num_label = []\n with torch.no_grad():\n for idx, (image, image_path) in enumerate(test_loader):\n image_torch = image.float().to(device)\n predict = model(image_torch)\n predict_mask = predict[0, 0, ...].cpu().detach().numpy()\n # predict_mask_image = predict_mask * 255.\n predict_mask_image = np.zeros([512, 512, 3])\n predict_mask_image[..., 0] = predict_mask * 255.\n predict_mask_image[..., 1] = predict_mask * 255.\n predict_mask_image[..., 2] = predict_mask * 255.\n num_labels, output = post_deal(predict_mask_image)\n save0 = str(image_path)[:-3].split('/')\n save1, filename = save0[-2], save0[-1]\n if not os.path.exists(os.path.join(save, save1)):\n os.mkdir(os.path.join(save, save1))\n cv2.imwrite(os.path.join(save, save1, filename), output)\n print(os.path.join(save, save1, filename))\n num_label.append(num_labels)\n num_label_result = sum(num_label)/len(num_label)\n return num_label_result\n\n",
"import os\nimport json\nimport sys\nimport cv2\nimport numpy as np\n\nfrom test_test import test\n\n\ndef video2frame(video_dir, frame_dir):\n files = os.listdir(video_dir)\n for i in range(len(files)):\n name = files[i]\n video = os.path.join(video_dir, name)\n video_cap = cv2.VideoCapture(video)\n frame_num = int(video_cap.get(cv2.CAP_PROP_FRAME_COUNT))\n save_dir = os.path.join(frame_dir, name.split('.')[0])\n if not os.path.exists(save_dir):\n os.mkdir(save_dir)\n for j in range(10):\n ref, image = video_cap.read()\n cv2.imwrite(os.path.join(save_dir, str(j + 1).zfill(5) + '.png'), image)\n # print(os.path.join(save_dir, str(j + 1).zfill(5) + '.png'))\n\n\ndef frame2result(imagedir, maskdir, resultdir):\n files = os.listdir(imagedir)\n for i in range(len(files)):\n name = files[i]\n video = os.path.join(imagedir, name)\n mask = os.path.join(maskdir, name)\n index_pics = os.listdir(video)\n h, w = 256, 256\n image_1 = cv2.imread(os.path.join(video, index_pics[0]))\n image_2 = cv2.imread(os.path.join(video, index_pics[1]))\n image_3 = cv2.imread(os.path.join(video, index_pics[2]))\n image_4 = cv2.imread(os.path.join(video, index_pics[3]))\n image_5 = cv2.imread(os.path.join(video, index_pics[4]))\n image_6 = cv2.imread(os.path.join(video, index_pics[5]))\n image_7 = cv2.imread(os.path.join(video, index_pics[6]))\n image_8 = cv2.imread(os.path.join(video, index_pics[7]))\n image_1 = cv2.resize(image_1, (h, w))\n image_2 = cv2.resize(image_2, (h, w))\n image_3 = cv2.resize(image_3, (h, w))\n image_4 = cv2.resize(image_4, (h, w))\n image_5 = cv2.resize(image_5, (h, w))\n image_6 = cv2.resize(image_6, (h, w))\n image_7 = cv2.resize(image_7, (h, w))\n image_8 = cv2.resize(image_8, (h, w))\n mask_1 = cv2.imread(os.path.join(mask, index_pics[0]))\n mask_2 = cv2.imread(os.path.join(mask, index_pics[1]))\n mask_3 = cv2.imread(os.path.join(mask, index_pics[2]))\n mask_4 = cv2.imread(os.path.join(mask, index_pics[3]))\n mask_5 = cv2.imread(os.path.join(mask, index_pics[4]))\n mask_6 = cv2.imread(os.path.join(mask, index_pics[5]))\n mask_7 = cv2.imread(os.path.join(mask, index_pics[6]))\n mask_8 = cv2.imread(os.path.join(mask, index_pics[7]))\n mask_1 = cv2.resize(mask_1, (h, w))\n mask_2 = cv2.resize(mask_2, (h, w))\n mask_3 = cv2.resize(mask_3, (h, w))\n mask_4 = cv2.resize(mask_4, (h, w))\n mask_5 = cv2.resize(mask_5, (h, w))\n mask_6 = cv2.resize(mask_6, (h, w))\n mask_7 = cv2.resize(mask_7, (h, w))\n mask_8 = cv2.resize(mask_8, (h, w))\n image_cat1 = np.concatenate([\n np.concatenate([image_1, mask_1], axis=1),\n np.concatenate([image_2, mask_2], axis=1),\n np.concatenate([image_3, mask_3], axis=1),\n np.concatenate([image_4, mask_4], axis=1)\n ], axis=0)\n image_cat2 = np.concatenate([\n np.concatenate([image_5, mask_5], axis=1),\n np.concatenate([image_6, mask_6], axis=1),\n np.concatenate([image_7, mask_7], axis=1),\n np.concatenate([image_8, mask_8], axis=1)\n ], axis=0)\n image_cat = np.concatenate([image_cat1, image_cat2], axis=1)\n image_cat = cv2.resize(image_cat, (512, 512))\n save = os.path.join(resultdir, name.split('.')[0] + '.png')\n cv2.imwrite(save, image_cat)\n\n\ndef test_image(input_a, input_b, input_c):\n input_arg_task_id = input_a\n input_arg_file_path = input_b\n input_arg_ext = input_c\n\n input_arg_ext_json = json.loads(input_arg_ext)\n input_arg_ext_out_json_path = input_arg_ext_json['JSON_FILE_PATH']\n\n input_arg_ext_tmp_dir = input_arg_ext_json['TMP_DIR']\n input_arg_ext_tmp_dir = os.path.join(input_arg_ext_tmp_dir, 'ljc_docs')\n\n input_arg_ext_out_tmp_path = os.path.join(input_arg_ext_tmp_dir, 'inpainting_forensics')\n input_arg_ext_out_tmp_path = os.path.join(input_arg_ext_out_tmp_path, str(input_arg_task_id))\n\n input_arg_ext_gpu_id = input_arg_ext_json['GPU_ID']\n images_dir = os.path.join(input_arg_ext_out_tmp_path, 'images')\n masks_dir = os.path.join(input_arg_ext_out_tmp_path, 'masks')\n result_dir = os.path.join(input_arg_ext_out_tmp_path, 'result')\n\n if not os.path.exists(input_arg_ext_out_tmp_path):\n os.makedirs(input_arg_ext_out_tmp_path)\n if not os.path.exists(images_dir):\n os.makedirs(images_dir)\n if not os.path.exists(masks_dir):\n os.makedirs(masks_dir)\n if not os.path.exists(result_dir):\n os.makedirs(result_dir)\n\n algorithm_message = '该算法使用多种预滤波模块,包括限制卷积、高通滤波等,卷积编码器采用网络结构搜索方法,并结合注意力机制,输出为输入视频8个采样帧的二值掩膜图。'\n print(algorithm_message)\n\n algorithm_args = {\n 'dataset': images_dir,\n 'ckpt': '/home/dell/soft/ljc_methods/video_inpainting_detection/iid_net/weights/IID_weights.pth',\n 'save': masks_dir,\n 'gpu_id': input_arg_ext_gpu_id,\n }\n print(algorithm_args)\n video2frame(input_arg_file_path, images_dir)\n\n test(algorithm_args)\n\n frame2result(images_dir, masks_dir, result_dir)\n\n result_json_content = {}\n images_detection = sorted(os.listdir(input_arg_file_path))\n images_location = sorted(os.listdir(result_dir))\n\n for i in range(len(images_detection)):\n image_detec_name = images_detection[i]\n image_locac_name = images_location[i]\n conclusion = '白色区域为可疑的修补区域'\n image_feature = []\n image_feature_one = {'filepath': os.path.join(result_dir, image_locac_name),\n 'title': '视频逐帧修补定位示意图',\n 'comment': '该图展示待检测视频采样帧可疑的修补区域。'}\n image_feature.append(image_feature_one)\n\n video_json = {'taskid': str(input_arg_task_id),\n 'conclusion': conclusion,\n 'message': algorithm_message,\n 'confidence': 1.0,\n 'threshold': 0.5,\n 'features': image_feature}\n result_json_content[image_detec_name] = video_json\n\n json_path = input_arg_ext_out_json_path\n with open(json_path, 'w') as f:\n json.dump(result_json_content, f)\n f.close()\n\n\nif __name__ == '__main__':\n input_1 = sys.argv[1]\n input_2 = sys.argv[2]\n input_3 = sys.argv[3]\n test_image(input_a=input_1, input_b=input_2, input_c=input_3)\n"
] |
[
[
"torch.no_grad",
"torch.utils.data.DataLoader",
"numpy.zeros",
"torch.load"
],
[
"numpy.concatenate"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
alexquach/responsible-ai-widgets
|
[
"6208f72a5dc14b955f0e8b7b2203d0cd74f32497",
"6208f72a5dc14b955f0e8b7b2203d0cd74f32497"
] |
[
"erroranalysis/erroranalysis/_internal/surrogate_error_tree.py",
"erroranalysis/erroranalysis/_internal/cohort_filter.py"
] |
[
"# Copyright (c) Microsoft Corporation\n# Licensed under the MIT License.\n\nimport numpy as np\nimport pandas as pd\nfrom lightgbm import LGBMClassifier, LGBMRegressor\nfrom enum import Enum\nfrom erroranalysis._internal.cohort_filter import filter_from_cohort\nfrom erroranalysis._internal.constants import (PRED_Y,\n TRUE_Y,\n ROW_INDEX,\n DIFF,\n SPLIT_INDEX,\n SPLIT_FEATURE,\n LEAF_INDEX,\n METHOD,\n METHOD_EXCLUDES,\n METHOD_INCLUDES,\n ModelTask,\n Metrics,\n metric_to_display_name,\n error_metrics)\nfrom sklearn.metrics import (\n mean_absolute_error, mean_squared_error, median_absolute_error,\n r2_score, f1_score, precision_score, recall_score)\n\nMODEL = 'model'\nDEFAULT_MAX_DEPTH = 3\nDEFAULT_NUM_LEAVES = 31\n\n\nclass TreeSide(str, Enum):\n \"\"\"Provide model task constants.\n Can be 'classification', 'regression', or 'unknown'.\n\n By default the model domain is inferred if 'unknown',\n but this can be overridden if you specify\n 'classification' or 'regression'.\n \"\"\"\n\n RIGHT_CHILD = 'right_child'\n LEFT_CHILD = 'left_child'\n UNKNOWN = 'unknown'\n\n\ndef compute_json_error_tree(analyzer,\n features,\n filters,\n composite_filters,\n max_depth=DEFAULT_MAX_DEPTH,\n num_leaves=DEFAULT_NUM_LEAVES):\n # Note: this is for backcompat for older versions\n # of raiwidgets pypi package\n return compute_error_tree(analyzer,\n features,\n filters,\n composite_filters,\n max_depth,\n num_leaves)\n\n\ndef compute_error_tree(analyzer,\n features,\n filters,\n composite_filters,\n max_depth=DEFAULT_MAX_DEPTH,\n num_leaves=DEFAULT_NUM_LEAVES):\n # Fit a surrogate model on errors\n if max_depth is None:\n max_depth = DEFAULT_MAX_DEPTH\n if num_leaves is None:\n num_leaves = DEFAULT_NUM_LEAVES\n is_model_analyzer = hasattr(analyzer, MODEL)\n if is_model_analyzer:\n filtered_df = filter_from_cohort(analyzer.dataset,\n filters,\n composite_filters,\n analyzer.feature_names,\n analyzer.true_y,\n analyzer.categorical_features,\n analyzer.categories)\n else:\n filtered_df = filter_from_cohort(analyzer.dataset,\n filters,\n composite_filters,\n analyzer.feature_names,\n analyzer.true_y,\n analyzer.categorical_features,\n analyzer.categories,\n analyzer.pred_y)\n row_index = filtered_df[ROW_INDEX]\n true_y = filtered_df[TRUE_Y]\n dropped_cols = [TRUE_Y, ROW_INDEX]\n if not is_model_analyzer:\n pred_y = filtered_df[PRED_Y]\n dropped_cols.append(PRED_Y)\n input_data = filtered_df.drop(columns=dropped_cols)\n is_pandas = isinstance(analyzer.dataset, pd.DataFrame)\n if is_pandas:\n true_y = true_y.to_numpy()\n else:\n input_data = input_data.to_numpy()\n if is_model_analyzer:\n pred_y = analyzer.model.predict(input_data)\n if analyzer.model_task == ModelTask.CLASSIFICATION:\n diff = pred_y != true_y\n else:\n diff = pred_y - true_y\n if not isinstance(diff, np.ndarray):\n diff = np.array(diff)\n if not isinstance(pred_y, np.ndarray):\n pred_y = np.array(pred_y)\n if not isinstance(true_y, np.ndarray):\n true_y = np.array(true_y)\n indexes = []\n for feature in features:\n indexes.append(analyzer.feature_names.index(feature))\n if is_pandas:\n input_data = input_data.to_numpy()\n\n if analyzer.categorical_features:\n # Inplace replacement of columns\n for idx, c_i in enumerate(analyzer.categorical_indexes):\n input_data[:, c_i] = analyzer.string_indexed_data[row_index, idx]\n dataset_sub_features = input_data[:, indexes]\n dataset_sub_names = np.array(analyzer.feature_names)[np.array(indexes)]\n dataset_sub_names = list(dataset_sub_names)\n\n categorical_info = get_categorical_info(analyzer,\n dataset_sub_names)\n cat_ind_reindexed, categories_reindexed = categorical_info\n\n surrogate = create_surrogate_model(analyzer,\n dataset_sub_features,\n diff,\n max_depth,\n num_leaves,\n cat_ind_reindexed)\n\n filtered_indexed_df = pd.DataFrame(dataset_sub_features,\n columns=dataset_sub_names)\n filtered_indexed_df[DIFF] = diff\n filtered_indexed_df[TRUE_Y] = true_y\n filtered_indexed_df[PRED_Y] = pred_y\n dumped_model = surrogate._Booster.dump_model()\n tree_structure = dumped_model[\"tree_info\"][0]['tree_structure']\n max_split_index = get_max_split_index(tree_structure) + 1\n tree = traverse(filtered_indexed_df,\n tree_structure,\n max_split_index,\n (categories_reindexed,\n cat_ind_reindexed),\n [],\n dataset_sub_names,\n metric=analyzer.metric)\n return tree\n\n\ndef create_surrogate_model(analyzer,\n dataset_sub_features,\n diff,\n max_depth,\n num_leaves,\n cat_ind_reindexed):\n \"\"\"Creates and fits the surrogate lightgbm model.\n\n :param analyzer: The error analyzer containing the categorical\n features and categories for the full dataset.\n :type analyzer: BaseAnalyzer\n :param dataset_sub_features: The subset of features to train the\n surrogate model on.\n :type dataset_sub_features: numpy.array or pandas.DataFrame\n :param diff: The difference between the true and predicted labels column.\n :type diff: numpy.array\n :param max_depth: The maximum depth of the surrogate tree trained\n on errors.\n :type max_depth: int\n :param num_leaves: The number of leaves of the surrogate tree\n trained on errors.\n :type num_leaves: int\n :param cat_ind_reindexed: The list of categorical feature indexes.\n :type cat_ind_reindexed: list[int]\n :return: The trained surrogate model.\n :rtype: LGBMClassifier or LGBMRegressor\n \"\"\"\n if analyzer.model_task == ModelTask.CLASSIFICATION:\n surrogate = LGBMClassifier(n_estimators=1,\n max_depth=max_depth,\n num_leaves=num_leaves)\n else:\n surrogate = LGBMRegressor(n_estimators=1,\n max_depth=max_depth,\n num_leaves=num_leaves)\n if cat_ind_reindexed:\n surrogate.fit(dataset_sub_features, diff,\n categorical_feature=cat_ind_reindexed)\n else:\n surrogate.fit(dataset_sub_features, diff)\n return surrogate\n\n\ndef get_categorical_info(analyzer, dataset_sub_names):\n \"\"\"Returns the categorical information for the given feature names.\n\n :param analyzer: The error analyzer containing the categorical\n features and categories for the full dataset.\n :type analyzer: BaseAnalyzer\n :param dataset_sub_names: The subset of feature names to get the\n categorical indexes and names for.\n :type dataset_sub_names: list[str]\n :return: The categorical indexes and categories for the subset\n of features specified.\n :rtype: tuple[list]\n \"\"\"\n cat_ind_reindexed = []\n categories_reindexed = []\n if analyzer.categorical_features:\n for c_index, feature in enumerate(analyzer.categorical_features):\n try:\n index_sub = dataset_sub_names.index(feature)\n except ValueError:\n continue\n cat_ind_reindexed.append(index_sub)\n categories_reindexed.append(analyzer.categories[c_index])\n return (cat_ind_reindexed, categories_reindexed)\n\n\ndef get_max_split_index(tree):\n if SPLIT_INDEX in tree:\n max_index = tree[SPLIT_INDEX]\n index1 = get_max_split_index(tree[TreeSide.LEFT_CHILD])\n index2 = get_max_split_index(tree[TreeSide.RIGHT_CHILD])\n return max(max(max_index, index1), index2)\n else:\n return 0\n\n\ndef traverse(df,\n tree,\n max_split_index,\n categories,\n dict,\n feature_names,\n parent=None,\n side=TreeSide.UNKNOWN,\n metric=None):\n if SPLIT_INDEX in tree:\n nodeid = tree[SPLIT_INDEX]\n elif LEAF_INDEX in tree:\n nodeid = max_split_index + tree[LEAF_INDEX]\n else:\n nodeid = 0\n\n # write current node to a dictionary that can be saved as json\n dict, df = node_to_dict(df, tree, nodeid, categories, dict,\n feature_names, metric, parent, side)\n\n # write children to a dictionary that can be saved as json\n if 'leaf_value' not in tree:\n left_child = tree[TreeSide.LEFT_CHILD]\n right_child = tree[TreeSide.RIGHT_CHILD]\n dict = traverse(df, left_child, max_split_index,\n categories, dict, feature_names,\n tree, TreeSide.LEFT_CHILD, metric)\n dict = traverse(df, right_child, max_split_index,\n categories, dict, feature_names,\n tree, TreeSide.RIGHT_CHILD, metric)\n return dict\n\n\ndef create_categorical_arg(parent_threshold):\n return [float(i) for i in parent_threshold.split('||')]\n\n\ndef create_categorical_query(method, arg, p_node_name, parent, categories):\n if method == METHOD_INCLUDES:\n operation = \"==\"\n else:\n operation = \"!=\"\n categorical_values = categories[0]\n categorical_indexes = categories[1]\n thresholds = []\n catcoli = categorical_indexes.index(parent[SPLIT_FEATURE])\n catvals = categorical_values[catcoli]\n for argi in arg:\n encoded_val = catvals[int(argi)]\n if not isinstance(encoded_val, str):\n encoded_val = str(encoded_val)\n thresholds.append(encoded_val)\n threshold_str = \" | \".join(thresholds)\n condition = \"{} {} {}\".format(p_node_name, operation, threshold_str)\n query = []\n for argi in arg:\n query.append(\"`\" + p_node_name + \"` \" + operation + \" \" + str(argi))\n if method == METHOD_INCLUDES:\n query = \" | \".join(query)\n else:\n query = \" & \".join(query)\n return query, condition\n\n\ndef node_to_dict(df, tree, nodeid, categories, json,\n feature_names, metric, parent=None,\n side=TreeSide.UNKNOWN):\n p_node_name = None\n condition = None\n arg = None\n method = None\n parentid = None\n if parent is not None:\n parentid = int(parent[SPLIT_INDEX])\n p_node_name = feature_names[parent[SPLIT_FEATURE]]\n parent_threshold = parent['threshold']\n parent_decision_type = parent['decision_type']\n if side == TreeSide.LEFT_CHILD:\n if parent_decision_type == '<=':\n method = \"less and equal\"\n arg = float(parent_threshold)\n condition = \"{} <= {:.2f}\".format(p_node_name,\n parent_threshold)\n query = \"`\" + p_node_name + \"` <= \" + str(parent_threshold)\n df = df.query(query)\n elif parent_decision_type == '==':\n method = METHOD_INCLUDES\n arg = create_categorical_arg(parent_threshold)\n query, condition = create_categorical_query(method,\n arg,\n p_node_name,\n parent,\n categories)\n df = df.query(query)\n elif side == TreeSide.RIGHT_CHILD:\n if parent_decision_type == '<=':\n method = \"greater\"\n arg = float(parent_threshold)\n condition = \"{} > {:.2f}\".format(p_node_name,\n parent_threshold)\n query = \"`\" + p_node_name + \"` > \" + str(parent_threshold)\n df = df.query(query)\n elif parent_decision_type == '==':\n method = METHOD_EXCLUDES\n arg = create_categorical_arg(parent_threshold)\n query, condition = create_categorical_query(method,\n arg,\n p_node_name,\n parent,\n categories)\n df = df.query(query)\n success = 0\n total = df.shape[0]\n if df.shape[0] == 0 and metric != Metrics.ERROR_RATE:\n metric_value = 0\n error = 0\n success = 0\n elif metric == Metrics.MEAN_ABSOLUTE_ERROR:\n pred_y, true_y, error = get_regression_metric_data(df)\n metric_value = mean_absolute_error(pred_y, true_y)\n elif metric == Metrics.MEAN_SQUARED_ERROR:\n pred_y, true_y, error = get_regression_metric_data(df)\n metric_value = mean_squared_error(pred_y, true_y)\n elif metric == Metrics.MEDIAN_ABSOLUTE_ERROR:\n pred_y, true_y, error = get_regression_metric_data(df)\n metric_value = median_absolute_error(pred_y, true_y)\n elif metric == Metrics.R2_SCORE:\n pred_y, true_y, error = get_regression_metric_data(df)\n metric_value = r2_score(pred_y, true_y)\n elif metric == Metrics.F1_SCORE:\n pred_y, true_y, error = get_classification_metric_data(df)\n metric_value = f1_score(pred_y, true_y)\n success = total - error\n elif metric == Metrics.PRECISION_SCORE:\n pred_y, true_y, error = get_classification_metric_data(df)\n metric_value = precision_score(pred_y, true_y)\n success = total - error\n elif metric == Metrics.RECALL_SCORE:\n pred_y, true_y, error = get_classification_metric_data(df)\n metric_value = recall_score(pred_y, true_y)\n success = total - error\n else:\n error = df[DIFF].values.sum()\n if total == 0:\n metric_value = 0\n else:\n metric_value = error / total\n success = total - error\n metric_name = metric_to_display_name[metric]\n is_error_metric = metric in error_metrics\n if SPLIT_FEATURE in tree:\n node_name = feature_names[tree[SPLIT_FEATURE]]\n else:\n node_name = None\n json.append({\n \"arg\": arg,\n \"badFeaturesRowCount\": 0, # Note: remove this eventually\n \"condition\": condition,\n \"error\": float(error),\n \"id\": int(nodeid),\n METHOD: method,\n \"nodeIndex\": int(nodeid),\n \"nodeName\": node_name,\n \"parentId\": parentid,\n \"parentNodeName\": p_node_name,\n \"pathFromRoot\": \"\", # Note: remove this eventually\n \"size\": float(total),\n \"sourceRowKeyHash\": \"hashkey\", # Note: remove this eventually\n \"success\": float(success), # Note: remove this eventually\n \"metricName\": metric_name,\n \"metricValue\": float(metric_value),\n \"isErrorMetric\": is_error_metric\n })\n return json, df\n\n\ndef get_regression_metric_data(df):\n pred_y = df[PRED_Y]\n true_y = df[TRUE_Y]\n # total abs error at the node\n error = sum(abs(pred_y - true_y))\n return pred_y, true_y, error\n\n\ndef get_classification_metric_data(df):\n pred_y = df[PRED_Y]\n true_y = df[TRUE_Y]\n error = df[DIFF].values.sum()\n return pred_y, true_y, error\n",
"# Copyright (c) Microsoft Corporation\n# Licensed under the MIT License.\n\nimport numpy as np\nimport pandas as pd\nfrom erroranalysis._internal.constants import (PRED_Y,\n TRUE_Y,\n ROW_INDEX,\n METHOD,\n METHOD_EXCLUDES,\n METHOD_INCLUDES)\n\n\nMETHOD_EQUAL = 'equal'\nMETHOD_GREATER = 'greater'\nMETHOD_LESS_AND_EQUAL = 'less and equal'\nMETHOD_RANGE = 'in the range of'\n\n\ndef filter_from_cohort(df, filters, composite_filters,\n feature_names, true_y,\n categorical_features, categories,\n pred_y=None):\n if not isinstance(df, pd.DataFrame):\n df = pd.DataFrame(df, columns=feature_names)\n else:\n # Note: we make a non-deep copy of the input dataframe since\n # we will add columns below\n df = df.copy()\n df[TRUE_Y] = true_y\n if pred_y is not None:\n df[PRED_Y] = pred_y\n df[ROW_INDEX] = np.arange(0, len(true_y))\n df = apply_recursive_filter(df, filters, categorical_features, categories)\n df = apply_recursive_filter(df, composite_filters,\n categorical_features, categories)\n return df\n\n\ndef apply_recursive_filter(df, filters, categorical_features, categories):\n if filters:\n return df.query(build_query(filters, categorical_features, categories))\n else:\n return df\n\n\ndef build_query(filters, categorical_features, categories):\n queries = []\n for filter in filters:\n if METHOD in filter:\n method = filter[METHOD]\n arg0 = str(filter['arg'][0])\n colname = filter['column']\n if method == METHOD_GREATER:\n queries.append(\"`\" + colname + \"` > \" + arg0)\n elif method == METHOD_LESS_AND_EQUAL:\n queries.append(\"`\" + colname + \"` <= \" + arg0)\n elif method == METHOD_RANGE:\n arg1 = str(filter['arg'][1])\n queries.append(\"`\" + colname + \"` >= \" + arg0 +\n ' & `' + colname + \"` <= \" + arg1)\n elif method == METHOD_INCLUDES or method == METHOD_EXCLUDES:\n query = build_cat_bounds_query(filter, colname, method,\n categorical_features,\n categories)\n queries.append(query)\n elif method == METHOD_EQUAL:\n is_categorical = False\n if categorical_features:\n is_categorical = colname in categorical_features\n if is_categorical:\n cat_idx = categorical_features.index(colname)\n arg0i = filter['arg'][0]\n arg_cat = str(categories[cat_idx][arg0i])\n queries.append(\"`{}` == '{}'\".format(colname, arg_cat))\n else:\n queries.append(\"`\" + colname + \"` == \" + arg0)\n else:\n raise ValueError(\n \"Unsupported method type: {}\".format(method))\n else:\n cqueries = []\n for composite_filter in filter['compositeFilters']:\n cqueries.append(build_query([composite_filter],\n categorical_features,\n categories))\n if filter['operation'] == 'and':\n queries.append('(' + ') & ('.join(cqueries) + ')')\n else:\n queries.append('(' + ') | ('.join(cqueries) + ')')\n return '(' + ') & ('.join(queries) + ')'\n\n\ndef build_cat_bounds_query(filter, colname, method,\n categorical_features, categories):\n bounds = []\n if method == METHOD_EXCLUDES:\n operator = \" != \"\n else:\n operator = \" == \"\n for arg in filter['arg']:\n cat_idx = categorical_features.index(colname)\n arg_cat = \"'{}'\".format(str(categories[cat_idx][arg]))\n bounds.append(\"`{}`{}{}\".format(colname, operator, arg_cat))\n if method == METHOD_EXCLUDES:\n return ' & '.join(bounds)\n else:\n return ' | '.join(bounds)\n"
] |
[
[
"sklearn.metrics.r2_score",
"sklearn.metrics.median_absolute_error",
"sklearn.metrics.mean_absolute_error",
"sklearn.metrics.precision_score",
"pandas.DataFrame",
"sklearn.metrics.mean_squared_error",
"sklearn.metrics.f1_score",
"numpy.array",
"sklearn.metrics.recall_score"
],
[
"pandas.DataFrame"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
eipm/CIN
|
[
"1cde66166f40a1921eaec4d65bea5d2da201ca8b"
] |
[
"Codes/MLP/MLP.py"
] |
[
"# Train top MLP and evaluate model performance\n\n# %%\nimport numpy as np\nimport pandas as pd\nimport random as rand\nimport skimage\nfrom skimage import io,feature, filters,color\nfrom skimage.exposure import rescale_intensity\nimport re\nimport os\nimport shutil\nimport matplotlib.pyplot as plt \nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras.models import Sequential, Model,load_model\nfrom tensorflow.keras import applications,optimizers\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D,MaxPool1D,GlobalAveragePooling2D,GlobalMaxPool1D,GlobalMaxPooling1D,BatchNormalization,Activation, Dropout, Flatten, Dense,LeakyReLU,TimeDistributed,GlobalAveragePooling1D,Concatenate,Reshape,Lambda\nfrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import cross_val_score, cross_val_predict, GridSearchCV\nfrom sklearn.model_selection import train_test_split\n\n# %%\n#---input: \n#features: patient level features\n#WSI_df: summarise file\ndef feature_split(WSI_df,features,ID,Label,testratio,seed):\n X_train,X_test,y_train,y_test,ID_train,ID_test=train_test_split(features,list(WSI_df[Label]),list(WSI_df[ID]),test_size=testratio,random_state=seed)\n np.save('ID_train.npy',ID_train)\n np.save('ID_test.npy',ID_test)\n np.save('y_train.npy',y_train)\n np.save('y_test.npy',y_test)\n #scaling\n scaler = preprocessing.MinMaxScaler()\n X_train = scaler.fit_transform(X_train)\n X_test = scaler.transform(X_test)\n y_train=np.array([int(y) for y in y_train])\n y_test=np.array([int(y) for y in y_test])\n return(X_train,X_test,y_train,y_test,ID_train,ID_test)\n\n\n\n# %%\n#train top MLP\n#---WSI_df: summarise file, a dataframe\n#must have columns indicating: label, patient ID\n#---Label, ID: \n#column names in WSI_df. example: ID='Barcode',Label='Cin_Label'\n#---features:\n#patient level feature array. \n#---testratio: percentage of test dataset, default is 0.15\n#---seed, default is 1001\n#---Model_Name:\n#name to store the model, example: 'Model.h5'\n#---Learning parameters:\n#layer_num,nodes_num_1,nodes_num_2,dropout,lr\n#you can set up to 2 hidden layers. Too many hidden layers is not likely to have good performance by experiments. \n#use layer_num to set number of hidden layers\n#use nodes_num_1 and nodes_num_2 to set nodes number of two hidden layers. Only set nodes_num_2 when layer_num=2\n#you can set up dropout and learning rate. default setting: dropout=0,lr=0.00001\ndef MLP_train(WSI_df=WSI_df,features=features,ID='Barcode',Label='Cin_Label',testratio=0.15,seed=1001,\nModel_Name='Model.h5',layer_num=1,nodes_num_1=1024,nodes_num_2=512,dropout=0,lr=0.00001):\n #split\n X_train,X_test,y_train,y_test,ID_train,ID_test=feature_split(WSI_df=WSI_df,features=features,\n ID=ID,Label=Label,testratio=testratio,seed=seed)\n #build MLP\n if layer_num==1:\n MLP = Sequential()\n MLP.add(Dense(nodes_num_1,input_shape=(1024,),kernel_initializer=tf.keras.initializers.he_normal(),activation='relu'))\n MLP.add(Dropout(dropout))\n MLP.add(Dense(1,activation='sigmoid'))\n if layer_num==2:\n MLP = Sequential()\n MLP.add(Dense(nodes_num_1,input_shape=(1024,),kernel_initializer=tf.keras.initializers.he_normal(),activation='relu'))\n MLP.add(Dropout(dropout))\n MLP.add(Dense(nodes_num_2,kernel_initializer=tf.keras.initializers.he_normal(),activation='relu'))\n MLP.add(Dense(1,activation='sigmoid'))\n #compile\n MLP.compile(loss='binary_crossentropy',\n optimizer=tf.keras.optimizers.Adam(learning_rate=lr),\n metrics=[tf.keras.metrics.BinaryAccuracy(),tf.keras.metrics.AUC()])\n #train\n es=EarlyStopping(monitor='val_loss',mode='min',patience=200)\n mc = ModelCheckpoint(Model_Name, monitor='val_loss', mode='min', verbose=1,save_best_only=True)\n history=MLP.fit(\n X_train,y_train,\n validation_split=0.15,\n epochs=2500,\n callbacks=[es,mc])\n"
] |
[
[
"tensorflow.keras.callbacks.ModelCheckpoint",
"tensorflow.keras.metrics.BinaryAccuracy",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.metrics.AUC",
"numpy.save",
"tensorflow.keras.initializers.he_normal",
"tensorflow.keras.optimizers.Adam",
"tensorflow.keras.layers.Dropout",
"tensorflow.keras.callbacks.EarlyStopping",
"tensorflow.keras.models.Sequential",
"sklearn.preprocessing.MinMaxScaler"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.2"
]
}
] |
svpcoder/tensorboard
|
[
"70753476c7aad3a5cb3eb4047994af1bcf3524b6"
] |
[
"tensorboard/loader.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\"\"\"TensorBoard data ingestion module.\n\nWARNING: This module is currently EXPERIMENTAL.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport contextlib\nimport functools\nimport locale\nimport logging\nimport os\nimport re\nimport sys\nimport time\nimport threading\nimport types # pylint: disable=unused-import\n\nimport six\nimport tensorflow as tf\n\nfrom tensorboard import db\nfrom tensorboard import util\n\n\nclass Record(collections.namedtuple('Record', ('record', 'offset'))):\n \"\"\"Value class for a record returned by RecordReader.\n\n Fields:\n record: The byte string record that was read.\n offset: The byte offset in the file *after* this record was read.\n\n :type record: str\n :type offset: int\n \"\"\"\n __slots__ = () # Enforces use of only tuple fields.\n\n\[email protected]\[email protected]_2_unicode_compatible\nclass RecordReader(object):\n \"\"\"Pythonic veneer around PyRecordReader.\"\"\"\n\n def __init__(self, path, start_offset=0):\n \"\"\"Creates new instance.\n\n Args:\n path: Path of file. This can be on a remote file system if the\n TensorFlow build supports it.\n start_offset: Byte offset to seek in file once it's opened.\n\n :type path: str\n :type start_offset: int\n \"\"\"\n self.path = tf.compat.as_text(path)\n self._offset = start_offset\n self._size = -1\n self._reader = None # type: tf.pywrap_tensorflow.PyRecordReader\n self._is_closed = False\n self._lock = threading.Lock()\n\n def get_size(self):\n \"\"\"Returns byte length of file.\n\n This is guaranteed to return a number greater than or equal to the\n offset of the last record returned by get_next_record().\n\n This method can be called after the instance has been closed.\n\n Raises:\n IOError: If file has shrunk from last read offset, or start\n offset, or last read size.\n\n :rtype: int\n \"\"\"\n size = tf.gfile.Stat(self.path).length\n minimum = max(self._offset, self._size)\n if size < minimum:\n raise IOError('File shrunk: %d < %d: %s' % (size, minimum, self.path))\n self._size = size\n return size\n\n def get_next_record(self):\n \"\"\"Reads record from file.\n\n Returns:\n A Record or None if no more were available.\n\n Raises:\n IOError: On open or read error, or if close was called.\n tf.errors.DataLossError: If corruption was encountered in the\n records file.\n\n :rtype: Record\n \"\"\"\n if self._is_closed:\n raise IOError('%s is closed' % self)\n if self._reader is None:\n self._reader = self._open()\n try:\n with tf.errors.raise_exception_on_not_ok_status() as status:\n self._reader.GetNext(status)\n except tf.errors.OutOfRangeError:\n # We ignore partial read exceptions, because a record may be truncated.\n # PyRecordReader holds the offset prior to the failed read, so retrying\n # will succeed.\n return None\n self._offset = self._reader.offset()\n return Record(self._reader.record(), self._offset)\n\n def close(self):\n \"\"\"Closes record reader if open.\n\n Further reads are not permitted after this method is called.\n \"\"\"\n if self._is_closed:\n return\n if self._reader is not None:\n self._reader.Close()\n self._is_closed = True\n self._reader = None\n\n def _open(self):\n with tf.errors.raise_exception_on_not_ok_status() as status:\n return tf.pywrap_tensorflow.PyRecordReader_New(\n tf.resource_loader.readahead_file_path(tf.compat.as_bytes(self.path)),\n self._offset, tf.compat.as_bytes(''), status)\n\n def __str__(self):\n return u'RecordReader{%s}' % self.path\n\n\[email protected]\[email protected]_2_unicode_compatible\nclass BufferedRecordReader(object):\n \"\"\"Wrapper around RecordReader that does threaded read-ahead.\n\n This class implements the same interface as RecordReader. It prevents\n remote file systems from devastating loader performance. It does not\n degrade throughput on local file systems.\n\n The thread is spawned when the first read operation happens. The\n thread will diligently try to buffer records in the background. Its\n goal is to sleep as much as possible without blocking read operations.\n\n This class is thread safe. It can be used from multiple threads\n without any need for external synchronization.\n \"\"\"\n\n READ_AHEAD_AGGRESSION = 2.3 # Does full replenish when ~40% full.\n READ_AHEAD_BYTES = 16 * 1024 * 1024\n STAT_INTERVAL_SECONDS = 4.0\n\n def __init__(self, path,\n start_offset=0,\n read_ahead=READ_AHEAD_BYTES,\n stat_interval=STAT_INTERVAL_SECONDS,\n clock=time.time,\n record_reader_factory=RecordReader):\n \"\"\"Creates new instance.\n\n The i/o thread is not started until the first read happens.\n\n Args:\n path: Path of file. This can be on a remote file system if the\n TensorFlow build supports it.\n start_offset: Byte offset to seek in file once it's opened.\n read_ahead: The number of record bytes to buffer into memory\n before the thread starts blocking. This value must be >0 and\n the default is BufferedRecordReader.READ_AHEAD_BYTES.\n stat_interval: A float with the minimum number of seconds between\n stat calls, to determine the file size. If this is 0.0 then\n the thread will stat after every re-buffer, but never be\n woken up in order to stat.\n clock: Function returning a float with the number of seconds\n since the UNIX epoch in zulu time.\n record_reader_factory: The RecordReader constructor, which can be\n changed for testing.\n\n :type path: str\n :type start_offset: int\n :type read_ahead: int\n :type clock: () -> float\n :type record_reader_factory: (str, int) -> RecordReader\n \"\"\"\n self.path = tf.compat.as_text(path)\n self._read_ahead = read_ahead\n self._stat_interval = stat_interval\n self._clock = clock\n self._is_closed = False\n self._has_reached_end = False\n self._offset = 0\n self._size = -1\n self._last_stat = 0.0\n self._buffered = 0\n self._reader = record_reader_factory(self.path, start_offset)\n self._records = collections.deque() # type: collections.deque[Record]\n self._read_exception = \\\n None # type: tuple[BaseException, BaseException, types.TracebackType]\n self._close_exception = \\\n None # type: tuple[BaseException, BaseException, types.TracebackType]\n self._lock = threading.Lock()\n self._wake_up_producer = threading.Condition(self._lock)\n self._wake_up_consumers = threading.Condition(self._lock)\n self._thread = threading.Thread(target=self._run,\n name=_shorten_event_log_path(self.path))\n\n def get_size(self):\n \"\"\"Returns byte length of file.\n\n This is guaranteed to return a number greater than or equal to the\n offset of the last record returned by get_next_record().\n\n In the average case, this method will not block. However, if the\n i/o thread has not yet computed this value, then this method will\n block on a stat call.\n\n This method can be called after the instance has been closed.\n\n Returns:\n The byte length of file, which might increase over time, but is\n guaranteed to never decrease. It's also guaranteed that it will\n be greater than or equal to the offset field of any Record.\n\n :rtype: int\n \"\"\"\n with self._lock:\n if self._should_stat():\n self._stat()\n return self._size\n\n def get_next_record(self):\n \"\"\"Reads one record.\n\n When this method is first called, it will spawn the thread and\n block until a record is read. Once the thread starts, it will queue\n up records which can be read without blocking. The exception is\n when we reach the end of the file, in which case each repeated call\n will be synchronous. There is no background polling. If new data is\n appended to the file, new records won't be buffered until this\n method is invoked again. The caller should take care to meter calls\n to this method once it reaches the end of file, lest they impact\n performance.\n\n Returns:\n A Record object, or None if there are no more records available\n at the moment.\n\n Raises:\n IOError: If this instance has been closed.\n tf.errors.DataLossError: If corruption was encountered in the\n records file.\n Exception: To propagate any exceptions that may have been thrown\n by the read operation in the other thread. If an exception is\n thrown, then all subsequent calls to this method will rethrow\n that same exception.\n\n :rtype: Record\n \"\"\"\n with self._lock:\n if self._is_closed:\n raise IOError('%s is closed' % self)\n if not self._thread.is_alive():\n self._thread.start()\n else:\n record = self._get_record()\n if record is not None:\n if self._should_wakeup():\n self._wake_up_producer.notify()\n return record\n self._has_reached_end = False\n self._wake_up_producer.notify()\n while not (self._read_exception or\n self._has_reached_end or\n self._records):\n self._wake_up_consumers.wait()\n return self._get_record()\n\n def close(self):\n \"\"\"Closes event log reader if open.\n\n If the i/o thread is running, this method blocks until it has been\n shut down.\n\n Further reads are not permitted after this method is called.\n\n Raises:\n Exception: To propagate any exceptions that may have been thrown\n by the close operation in the other thread. If an exception\n is thrown, then all subsequent calls to this method will\n rethrow that same exception.\n \"\"\"\n with self._lock:\n if not self._is_closed:\n self._is_closed = True\n if not self._thread.is_alive():\n self._reader = None\n return\n self._wake_up_producer.notify()\n while self._reader is not None:\n self._wake_up_consumers.wait()\n if self._close_exception is not None:\n six.reraise(*self._close_exception)\n\n def _get_record(self):\n if self._read_exception is not None:\n six.reraise(*self._read_exception)\n if not self._records:\n return None\n record = self._records.popleft()\n self._buffered -= len(record.record)\n return record\n\n @util.guarded_by('_lock')\n def _should_wakeup(self):\n return (self._is_closed or\n self._read_exception is None and\n (self._should_rebuffer() or\n (self._stat_interval and self._should_stat())))\n\n @util.guarded_by('_lock')\n def _should_rebuffer(self):\n return (not self._has_reached_end and\n (float(self._buffered) <\n self._read_ahead / BufferedRecordReader.READ_AHEAD_AGGRESSION))\n\n @util.guarded_by('_lock')\n def _should_stat(self):\n return (self._read_exception is None and\n (self._offset > self._size or\n self._last_stat <= self._clock() - self._stat_interval))\n\n @util.guarded_by('_lock')\n def _stat(self):\n try:\n now = self._clock()\n self._size = self._reader.get_size()\n self._last_stat = now\n except Exception as e: # pylint: disable=broad-except\n tf.logging.debug('Stat failed: %s', e)\n self._read_exception = sys.exc_info()\n\n def _run(self):\n while True:\n with self._lock:\n while not self._should_wakeup():\n self._wake_up_producer.wait()\n if self._is_closed:\n try:\n self._reader.close()\n tf.logging.debug('Closed')\n except Exception as e: # pylint: disable=broad-except\n self._close_exception = sys.exc_info()\n tf.logging.debug('Close failed: %s', e)\n self._reader = None\n self._wake_up_consumers.notify_all()\n return\n if self._buffered >= self._read_ahead:\n tf.logging.debug('Waking up to stat')\n self._stat()\n continue\n # Calculate a good amount of data to read outside the lock.\n # The less we have buffered, the less re-buffering we'll do.\n # We want to minimize wait time in the other thread. See the\n # following contour plot: https://goo.gl/HTBcCU\n x = float(self._buffered)\n y = BufferedRecordReader.READ_AHEAD_AGGRESSION\n c = float(self._read_ahead)\n want = int(min(c - x, y/c * x**y + 1))\n # Perform re-buffering outside lock.\n self._rebuffer(want)\n\n def _rebuffer(self, want):\n tf.logging.debug('Waking up to read %s bytes', _localize_int(want))\n records = []\n read_exception = self._read_exception\n if read_exception is None:\n try:\n while want > 0:\n record = self._reader.get_next_record()\n if record is None:\n break\n self._offset = record.offset\n records.append(record)\n want -= len(record.record)\n except Exception as e: # pylint: disable=broad-except\n tf.logging.debug('Read failed: %s', e)\n read_exception = sys.exc_info()\n with self._lock:\n self._read_exception = read_exception\n if self._should_stat():\n self._stat()\n if not self._read_exception:\n if not records:\n self._has_reached_end = True\n else:\n for record in records:\n self._records.append(record)\n self._buffered += len(record.record)\n self._wake_up_consumers.notify_all()\n\n def __str__(self):\n return u'BufferedRecordReader{%s}' % self.path\n\n\nclass RateCounter(object):\n \"\"\"Utility class for tracking how much a number increases each second.\n\n The rate is calculated by averaging of samples within a time window,\n which weights recent samples more strongly.\n \"\"\"\n\n def __init__(self, window, clock=time.time):\n \"\"\"Creates new instance.\n\n Args:\n window: The maximum number of seconds across which rate is\n averaged. In practice, the rate might be averaged over a time\n period greater than window if set_value is being called less\n frequently than window.\n clock: Function returning a float with the number of seconds\n since the UNIX epoch in zulu time.\n\n :type window: float\n :type clock: () -> float\n \"\"\"\n self._window = window\n self._clock = clock\n self._points = collections.deque()\n self._last_value = None # type: float\n self._last_time = None # type: float\n\n def get_rate(self):\n \"\"\"Determines rate of increase in value per second averaged over window.\n\n Returns:\n An integer representing the rate or None if not enough\n information has been collected yet.\n\n :rtype: int\n \"\"\"\n points = []\n total_elapsed = 0.0\n total_weight = 0.0\n for rate, elapsed, _ in self._points:\n weight = 1.0 / (total_elapsed + 1) * elapsed\n total_elapsed += elapsed\n total_weight += weight\n points.append((rate, weight))\n if not total_weight:\n return 0\n return int(sum(w / total_weight * r for r, w in points))\n\n def set_value(self, value):\n \"\"\"Sets number state.\n\n This method adds a delta between value and the value of the last\n time this method was called. Therefore the first invocation does\n not add a delta.\n\n Raises:\n ValueError: If value is less than the last value.\n\n :type value: float\n \"\"\"\n value = float(value)\n now = self._clock()\n if self._last_value is None:\n self._last_value = value\n self._last_time = now\n return\n if value < self._last_value:\n raise ValueError('%f < %f' % (value, self._last_value))\n delta = value - self._last_value\n elapsed = now - self._last_time\n if not elapsed:\n return\n self._points.appendleft((delta / elapsed, elapsed, now))\n self._last_time = now\n self._last_value = value\n self._remove_old_points()\n\n def bump(self):\n \"\"\"Makes time since last set_value count for nothing.\"\"\"\n self._last_time = self._clock()\n\n def _remove_old_points(self):\n threshold = self._clock() - self._window\n while self._points:\n r, e, t = self._points.pop()\n if t > threshold:\n self._points.append((r, e, t))\n break\n\n\[email protected]\nclass Progress(object):\n \"\"\"Terminal UI for displaying job progress in terms of bytes.\n\n On teletypes, this class will display a nice ephemeral unicode\n progress bar. Otherwise it just emits periodic log messages.\n\n This class keeps track of the rate at which input is processed, as\n well as the rate it grows. These values are represented to the user\n using the DELTA and NABLA symbols.\n\n An alarm is displayed if the consumption rate falls behind the\n production rate. In order for this to be calculated properly, the\n sleep method of this class should be used rather than time.sleep.\n \"\"\"\n\n BAR_INTERVAL_SECONDS = 0.25\n BAR_LOGGER = logging.getLogger('tensorflow' + util.LogHandler.EPHEMERAL)\n BAR_WIDTH = 45\n BLOCK_DARK = u'\\u2593'\n BLOCK_LIGHT = u'\\u2591'\n DELTA = u'\\u2206'\n LOG_INTERVAL_SECONDS = 5.0\n NABLA = u'\\u2207'\n RATE_WINDOW = 20.0\n\n def __init__(self, clock=time.time,\n sleep=time.sleep,\n log_callback=tf.logging.info,\n bar_callback=BAR_LOGGER.info,\n rate_counter_factory=RateCounter):\n \"\"\"Creates new instance.\n\n Args:\n clock: Function returning a float with the number of seconds\n since the UNIX epoch in zulu time.\n sleep: Injected time.sleep function.\n log_callback: Callback for emitting normal log records.\n bar_callback: Callback for emitting ephemeral bar records.\n rate_counter_factory: Constructor to RateCounter, which can be\n swapped out for testing.\n\n :type clock: () -> float\n :type sleep: (float) -> None\n :type rate_counter_factory: (float) -> RateCounter\n \"\"\"\n self._clock = clock\n self._sleep = sleep\n self._log_callback = log_callback\n self._bar_callback = bar_callback\n self._initialized = False\n self._offset = 0\n self._size = 0\n self._last_log_time = 0.0\n self._last_bar_time = 0.0\n self._last_log_offset = -1\n self._last_bar_offset = -1\n self._rate_offset = rate_counter_factory(Progress.RATE_WINDOW)\n self._rate_size = rate_counter_factory(Progress.RATE_WINDOW)\n\n def set_progress(self, offset, size):\n \"\"\"Updates the progress bar state.\n\n This method will cause progress information to be occasionally\n written out.\n\n Args:\n offset: The number of bytes processed so far.\n size: The total number of bytes. This is allowed to increase or\n decrease, but it must remain at least offset.\n\n Raises:\n ValueError: If offset is greater than size, or offset or size\n decreased from the last invocation.\n\n :type offset: int\n :type size: int\n \"\"\"\n if offset > size:\n raise ValueError('offset (%d) can not exceed size (%d)' % (offset, size))\n self._rate_offset.set_value(offset)\n self._rate_size.set_value(size)\n self._offset = offset\n self._size = size\n now = self._clock()\n if not self._initialized:\n self._last_log_time = now\n self._last_bar_time = now\n self._initialized = True\n return\n elapsed = now - self._last_log_time\n if elapsed >= Progress.LOG_INTERVAL_SECONDS:\n self._last_log_time = now\n self._show_log()\n elapsed = now - self._last_bar_time\n if elapsed >= Progress.BAR_INTERVAL_SECONDS:\n self._last_bar_time = now\n self._show_bar()\n\n def close(self):\n \"\"\"Forces progress to be written to log.\n\n This method exists because we don't want the progress bar to say\n something like 98% once the file is done loading.\n \"\"\"\n self._show_log(can_stall=False)\n self._show_bar(can_stall=False)\n # Instructs util.LogHandler to clear the ephemeral logging state.\n self._bar_callback('')\n\n def sleep(self, seconds):\n \"\"\"Sleeps for a given number of seconds.\n\n Time spent sleeping in this method does not have a detrimental\n impact on the consumption rate.\n\n :type seconds: float\n \"\"\"\n self._sleep(seconds)\n self._rate_offset.bump()\n\n def _show_log(self, can_stall=True):\n is_stalled = can_stall and self._offset == self._last_log_offset\n self._last_log_offset = self._offset\n self._log_callback('Loaded %s', self._get_message(is_stalled))\n\n def _show_bar(self, can_stall=True):\n is_stalled = can_stall and self._offset == self._last_bar_offset\n self._last_bar_offset = self._offset\n sofar = int(self._get_fraction() * Progress.BAR_WIDTH)\n bar = (Progress.BLOCK_DARK * sofar +\n Progress.BLOCK_LIGHT * (Progress.BAR_WIDTH - sofar))\n self._bar_callback(u'%s %s ', bar, self._get_message(is_stalled))\n\n def _get_message(self, is_stalled):\n rate_offset = self._rate_offset.get_rate() # summary processing speed\n rate_size = self._rate_size.get_rate() # summary production speed\n message = u'%d%% of %s%s%s' % (\n int(self._get_fraction() * 100.0),\n _localize_int(self._size),\n self._get_rate_suffix(Progress.DELTA, rate_offset),\n self._get_rate_suffix(Progress.NABLA, rate_size))\n if rate_offset and rate_size and rate_offset < rate_size:\n # If TensorFlow is writing summaries to disk faster than we can\n # insert them into the database, that's kind of problematic.\n message += u' ' + self._make_red(u'[meltdown]')\n elif is_stalled:\n message += u' %s[stalled]%s' % (util.Ansi.BOLD, util.Ansi.RESET)\n return message\n\n def _get_fraction(self):\n if not self._size:\n return 0.0\n else:\n return float(self._offset) / self._size\n\n def _get_rate_suffix(self, symbol, rate):\n if not rate:\n return u''\n return u' %s %sB/s' % (symbol, _localize_int(rate))\n\n def _make_red(self, text):\n return (util.Ansi.BOLD +\n util.Ansi.RED +\n (util.Ansi.FLIP if self._offset % 2 == 0 else u'') +\n text +\n util.Ansi.RESET)\n\n\[email protected]\[email protected]_ordering\[email protected]_2_unicode_compatible\nclass EventLogReader(object):\n \"\"\"Helper class for reading from event log files.\n\n This class is a wrapper around BufferedRecordReader that operates on\n record files containing tf.Event protocol buffers.\n\n Fields:\n rowid: An integer primary key in EventLogs table, or 0 if unknown.\n path: A string with the path of the event log on the local or\n remote file system.\n timestamp: An integer of the number of seconds since the UNIX epoch\n in UTC according to hostname at the time when the event log\n file was created.\n hostname: A string with the FQDN of the machine that wrote this\n event log file.\n \"\"\"\n\n def __init__(self, path,\n start_offset=0,\n record_reader_factory=BufferedRecordReader):\n \"\"\"Creates new instance.\n\n Args:\n path: Path of event log file.\n start_offset: Byte offset to seek in file once it's opened.\n record_reader_factory: A reference to the constructor of a class\n that implements the same interface as RecordReader.\n\n :type path: str\n :type record_reader_factory: (str, int) -> RecordReader\n \"\"\"\n self.rowid = 0\n self.path = tf.compat.as_text(path)\n m = _EVENT_LOG_PATH_PATTERN.search(self.path)\n if not m:\n raise ValueError('Bad event log path: ' + self.path)\n self.timestamp = int(m.group('timestamp'))\n self.hostname = m.group('hostname')\n self._offset = start_offset\n self._reader_factory = record_reader_factory\n self._reader = self._reader_factory(self.path, start_offset)\n self._key = (os.path.dirname(self.path), self.timestamp, self.hostname)\n\n def get_next_event(self):\n \"\"\"Reads an event proto from the file.\n\n Returns:\n A tf.Event or None if no more records exist in the file. Please\n note that the file remains open for subsequent reads in case more\n are appended later.\n\n :rtype: tf.Event\n \"\"\"\n record = self._reader.get_next_record()\n if record is None:\n return None\n event = tf.Event()\n event.ParseFromString(record.record)\n self._offset = record.offset\n return event\n\n def set_offset(self, offset):\n \"\"\"Sets byte offset in file.\n\n :type offset: int\n \"\"\"\n if offset == self._offset:\n return\n self._reader.close()\n self._reader = self._reader_factory(self.path, offset)\n self._offset = offset\n\n def get_offset(self):\n \"\"\"Returns current byte offset in file.\n\n :rtype: int\n \"\"\"\n return self._offset\n\n def get_size(self):\n \"\"\"Returns byte length of file.\n\n :rtype: int\n \"\"\"\n return self._reader.get_size()\n\n def save_progress(self, db_conn):\n \"\"\"Saves current offset to DB.\n\n The rowid property must be set beforehand.\n\n :type db_conn: db.Connection\n \"\"\"\n with contextlib.closing(db_conn.cursor()) as c:\n c.execute(\n 'UPDATE EventLogs SET offset = ? WHERE rowid = ? AND offset < ?',\n (self._offset, self.rowid, self._offset))\n\n def close(self):\n \"\"\"Closes event log reader if open.\n\n Further i/o is not permitted after this method is called.\n \"\"\"\n if self._reader is not None:\n self._reader.close()\n self._reader = None\n\n def __hash__(self):\n return hash(self._key)\n\n def __eq__(self, other):\n return self._key == other._key\n\n def __lt__(self, other):\n return self._key < other._key\n\n def __str__(self):\n offset = self.get_offset()\n if offset:\n return u'EventLogReader{path=%s, offset=%d}' % (self.path, offset)\n else:\n return u'EventLogReader{%s}' % self.path\n\n\[email protected]\[email protected]_ordering\[email protected]_2_unicode_compatible\nclass RunReader(object):\n \"\"\"Utility for loading event logs into the DB.\n\n This class merges the chain of event log files into one meaningful\n stream of events, ordered by step or timestamp.\n\n Fields:\n rowid: The primary key of the corresponding row in Runs.\n name: Display name of this run.\n \"\"\"\n\n def __init__(self, rowid, name):\n \"\"\"Creates new instance.\n\n Args:\n rowid: Primary key of run in `Runs` table, which should already\n be inserted. This is a bit-packed int made by db.RUN_ROWID.\n name: Display name of run.\n\n :type rowid: int\n :type name: str\n \"\"\"\n self.rowid = db.RUN_ROWID.check(rowid)\n self.run_id = db.RUN_ROWID.parse(rowid)[1]\n self.name = tf.compat.as_text(name)\n self._mark = -1\n self._logs = [] # type: list[EventLogReader]\n self._index = 0\n self._entombed_progress = 0\n self._saved_events = \\\n collections.deque() # type: collections.deque[tf.Event]\n self._prepended_events = \\\n collections.deque() # type: collections.deque[tf.Event]\n\n def add_event_log(self, db_conn, log):\n \"\"\"Adds event log to run loader.\n\n Event logs must be added monotonically, based on the timestamp in\n the filename. Please note that calling this method could cause a\n current batch of reads to fast forward.\n\n Args:\n db_conn: A PEP 249 Connection object.\n log: An EventLogReader instance.\n\n Returns:\n True if log was actually added.\n\n :type db_conn: db.Connection\n :type log: EventLogReader\n :rtype: bool\n \"\"\"\n if self._logs and log <= self._logs[-1]:\n return False\n with contextlib.closing(db_conn.cursor()) as c:\n c.execute(\n 'SELECT rowid, offset FROM EventLogs WHERE run_id = ? AND path = ?',\n (self.run_id, log.path))\n row = c.fetchone()\n if row:\n log.rowid = row[0]\n log.set_offset(row[1])\n else:\n event_log_id = db.EVENT_LOG_ID.generate()\n log.rowid = db.EVENT_LOG_ROWID.create(self.run_id, event_log_id)\n c.execute(\n ('INSERT INTO EventLogs (rowid, run_id, path, offset)'\n ' VALUES (?, ?, ?, 0)'),\n (log.rowid, self.run_id, log.path))\n tf.logging.debug('Adding %s', log)\n self._logs.append(log)\n # Skip over event logs we've already read.\n if log.get_offset() > 0 and not self._prepended_events:\n self._index = len(self._logs) - 1\n self._cleanup()\n return True\n\n def get_next_event(self):\n \"\"\"Returns next tf.Event from event logs or None if stalled.\n\n :rtype: tf.Event\n \"\"\"\n event = None\n if self._prepended_events:\n event = self._prepended_events.popleft()\n elif self._index < len(self._logs):\n while True:\n log = self._logs[self._index]\n event = log.get_next_event()\n if event is not None:\n break\n if self._index == len(self._logs) - 1:\n break\n self._index += 1\n self._cleanup()\n if event is not None and self._mark != -1:\n self._saved_events.append(event)\n return event\n\n def mark_peek_reset(self):\n \"\"\"Returns next event without advancing.\n\n Note: This method sets the mark to the current position.\n\n :rtype: tf.Event\n \"\"\"\n self.mark()\n result = self.get_next_event()\n self.reset()\n return result\n\n def get_offset(self):\n \"\"\"Returns number of bytes read across all event log files.\n\n :rtype: int\n \"\"\"\n if self._mark != -1:\n return self._mark\n return self._get_offset()\n\n def _get_offset(self):\n return sum(el.get_offset() for el in self._logs) + self._entombed_progress\n\n def get_size(self):\n \"\"\"Returns sum of byte lengths of event log files.\n\n :rtype: int\n \"\"\"\n return sum(el.get_size() for el in self._logs) + self._entombed_progress\n\n def save_progress(self, db_conn):\n \"\"\"Saves current offsets of all open event logs to DB.\n\n This should be called after the mark has been advanced.\n\n :type db_conn: db.Connection\n \"\"\"\n n = 0\n while self._index >= n < len(self._logs):\n self._logs[n].save_progress(db_conn)\n n += 1\n\n def mark(self):\n \"\"\"Marks current position in file so reset() can be called.\"\"\"\n if self._prepended_events:\n raise ValueError('mark() offsets must be monotonic')\n self._mark = self._get_offset()\n self._saved_events.clear()\n\n def reset(self):\n \"\"\"Resets read state to where mark() was called.\"\"\"\n if self._mark == -1:\n return\n self._prepended_events.extend(self._saved_events)\n self._saved_events.clear()\n\n def close(self):\n \"\"\"Closes all event log readers.\n\n This method may be called multiple times, but further operations\n are not permitted.\n\n Raises:\n Exception: To propagate the most recent exception thrown by the\n EventLogReader close method. Suppressed exceptions are\n logged.\n \"\"\"\n util.close_all(self._logs)\n self._index = len(self._logs)\n self._mark = -1\n self._prepended_events.clear()\n self._saved_events.clear()\n\n def _cleanup(self):\n # Last event log has to be preserved so we can continue enforcing\n # monotonicity. We entomb offset because that also has to be\n # monotonic, but the size does not.\n if 0 < self._index < len(self._logs):\n deleted = self._logs[:self._index]\n self._logs = self._logs[self._index:]\n self._index = 0\n self._entombed_progress += sum(l.get_offset() for l in deleted)\n util.close_all(deleted)\n\n def _skip_to_event_log(self, i):\n should_mark = self._mark != -1 and i > self._index\n self._index = i\n if should_mark:\n self._prepended_events.clear()\n self.mark()\n\n def __hash__(self):\n return hash(self.rowid)\n\n def __eq__(self, other):\n return self.rowid == other.rowid\n\n def __lt__(self, other):\n return self.rowid < other.rowid\n\n def __str__(self):\n offset = self.get_offset()\n if offset:\n return u'RunReader{name=%s, offset=%d}' % (self.name, offset)\n else:\n return u'RunReader{%s}' % self.name\n\n\ndef _get_basename(path):\n \"\"\"Gets base name of path.\n\n This is the same as os.path.basename, however it may potentially do\n i/o to handle a few edge cases, which would otherwise cause the\n result to be less meaningful, e.g. \".\" and \"..\".\n\n :type path: str\n :rtype: str\n \"\"\"\n return os.path.basename(os.path.normpath(os.path.join(_get_cwd(), path)))\n\n\ndef _get_cwd():\n \"\"\"Returns current directory and try not to expand symlinks.\n\n :rtype: str\n \"\"\"\n result = os.environ.get('PWD')\n if not result:\n result = os.getcwd()\n return result\n\n\ndef get_event_logs(directory):\n \"\"\"Walks directory tree for EventLogReader files.\n\n Args:\n directory: Path of directory.\n\n Returns:\n List of EventLogReader objects, ordered by directory name and\n timestamp.\n\n :type directory: str\n :rtype: list[EventLogReader]\n \"\"\"\n logs = []\n for dirname, _, filenames in tf.gfile.Walk(directory):\n for filename in filenames:\n if is_event_log_file(filename):\n logs.append(EventLogReader(os.path.join(dirname, filename)))\n logs.sort()\n return logs\n\n\n_EVENT_LOG_PATH_PATTERN = re.compile(\n r'\\.tfevents\\.(?P<timestamp>\\d+).(?P<hostname>[-.0-9A-Za-z]+)$')\n\n\ndef is_event_log_file(path):\n \"\"\"Returns True if path appears to be an event log file.\n\n :type path: str\n :rtype: bool\n \"\"\"\n return bool(_EVENT_LOG_PATH_PATTERN.search(path))\n\n\n_SHORTEN_EVENT_LOG_PATH_PATTERN = re.compile(r'(?:[^/\\\\]+[/\\\\])?(?:[^/\\\\]+)$')\n\n\ndef _shorten_event_log_path(path):\n \"\"\"Makes an event log path more human readable.\n\n Returns:\n Path containing only basename and the first parent directory name,\n if there is one.\n\n :type path: str\n :rtype: str\n \"\"\"\n m = _SHORTEN_EVENT_LOG_PATH_PATTERN.search(path)\n return m.group(0) if m else None\n\n\ndef _localize_int(n):\n \"\"\"Adds locale specific thousands group separators.\n\n :type n: int\n :rtype: str\n \"\"\"\n return locale.format('%d', n, grouping=True)\n"
] |
[
[
"tensorflow.gfile.Walk",
"tensorflow.logging.debug",
"tensorflow.gfile.Stat",
"tensorflow.compat.as_bytes",
"tensorflow.errors.raise_exception_on_not_ok_status",
"tensorflow.Event",
"tensorflow.compat.as_text"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Horki/CarND-Behavioral-Cloning-P3
|
[
"d6c7a3d35749f4e995fb14d38bf370755b60a466"
] |
[
"gen_3/model.py"
] |
[
"import csv\nimport numpy as np\nfrom scipy import ndimage\n\nfrom keras.models import Sequential\nfrom keras.layers import Flatten, Dense, Lambda\nfrom keras.layers.convolutional import Convolution2D\nfrom keras.layers.pooling import MaxPooling2D\n\nDATA_PATH='../data'\n# DATA_PATH='../behavioral_data/all'\nDRIVING_LOG='driving_log.csv'\n\nIMG_WIDTH=320\nIMG_HEIGHT=160\nIMG_COMPONENTS=3\n\ndef load_data(path):\n lines = []\n with open(path, \"r\") as f:\n # Udacity sample data has a \", \" delimiter\n reader = csv.reader(f, skipinitialspace=True, delimiter=',')\n # reader = csv.reader(f, delimiter=',')\n # Skip header for Udacity sample data\n next(reader) # Skip header\n lines = [line for line in reader]\n assert len(lines[0]) == 7\n return lines\n\n\ndef load_image(image_path):\n filename = image_path.split('/')[-1]\n image = ndimage.imread('{}/IMG/{}'.format(DATA_PATH, filename))\n # Check image shape only slows processing\n # assert image.shape == (IMG_HEIGHT, IMG_WIDTH, IMG_COMPONENTS)\n return image\n\n\n# Most basic neural network\ndef load_model():\n model = Sequential()\n # Preproceesing layer\n # Normalize the image by dividing each element with 255\n # which is maximum vale of image pixel\n # Once the image is normalized between 0 and 1,\n # mean centre by subtracting with 0.5 from each element\n # which will shift the element from 0.5 to 0\n # Training and validation loss are now much smaller\n print(\"Lambda preprocessing start...\")\n model.add(Lambda(lambda x: (x / 255.0) - 0.5, input_shape=(IMG_HEIGHT, IMG_WIDTH, IMG_COMPONENTS)))\n print(\"...end preprocessing\")\n model.add(Convolution2D(6, 5, 5, activation='relu'))\n model.add(MaxPooling2D())\n model.add(Convolution2D(6, 5, 5, activation='relu'))\n model.add(MaxPooling2D())\n model.add(Flatten())\n model.add(Dense(128))\n model.add(Dense(84))\n model.add(Dense(1))\n model.compile(loss='mse', optimizer='adam')\n return model\n\n\ndef get_train_data(samples):\n images = []\n measurements = []\n for line in samples:\n # Feature: Center Image\n images.append(load_image(line[0]))\n # Label: Steering measurement\n measurements.append(float(line[3]))\n features = np.array(images)\n labels = np.array(measurements)\n return features, labels\n\n\nif __name__ == \"__main__\":\n print(\"Load driving log. start...\")\n # Indexes\n # center[0], left[1], right[2], steering[3], throttle[4], brake[5], speed[6]\n samples = load_data(\"{}/{}\".format(DATA_PATH, DRIVING_LOG))\n print(\"...done\\nLoad train data: start...\")\n X_train, y_train = get_train_data(samples)\n print(\"...done\\nCompile model: start...\")\n # Model Part\n model = load_model()\n model.fit(X_train, y_train, validation_split=0.2, shuffle=True, nb_epoch=5)\n print(\"...done\\nSave model\")\n model.save('model.h5')\n"
] |
[
[
"numpy.array"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.