repo_name
stringlengths 6
130
| hexsha
list | file_path
list | code
list | apis
list |
---|---|---|---|---|
jthestness/catamount
|
[
"9de3090f1a02a04774f28a0d10f677a76f50446f"
] |
[
"catamount/tests/ops/dynamic_stitch.py"
] |
[
"import sympy\nimport numpy as np\n\nimport catamount\nfrom catamount.graph import Graph\n\nfrom catamount.tests.utils.helpers import *\n\n\ndef test_dynamic_stitch_op():\n ''' Specify graphs with DynamicStitch operations and make sure they behave\n as desired.\n '''\n\n combos = [ # Speech examples\n ([[0, 1], 0], # indices\n [[5, 6], 7], # data\n [7, 6]),\n ([[0, 1, 2], 0], # indices\n [None, 1], # data\n None), # merged\n # TF Docs example\n ([6, [4, 1], [[5, 2], [0, 3]]], # indices\n [[61, 62], [[41, 42], [11, 12]], [[[51, 52], [21, 22]], [[1, 2], [31, 32]]]], # data\n [[1, 2], [11, 12], [21, 22], [31, 32], [41, 42], [51, 52], [61, 62]]) # merged\n ]\n\n for combo in combos:\n graph = Graph()\n with graph.asDefault():\n indices, data, merged = combo\n ind_consts = []\n data_consts = []\n for idx in range(len(indices)):\n ind_const_name = 'int_const_{}'.format(idx)\n shape = list(np.array(indices[idx]).shape)\n ind_consts.append(\n constant(ind_const_name, shape, indices[idx]))\n\n data_const_name = 'data_const_{}'.format(idx)\n shape = list(np.array(data[idx]).shape)\n data_consts.append(\n constant(data_const_name, shape, data[idx]))\n out_tensor = dynamic_stitch('dyn_stitch', None, ind_consts,\n data_consts)\n\n bind_dict = {}\n graph.bindShapesAndPropagate(bind_dict,\n warn_if_ill_defined=True)\n\n # Check that out_tensor shape and value is correct!\n out_value = out_tensor.value\n assert np.array_equal(out_value, merged)\n print('Out tensor: {}, correct: {}'.format(out_tensor, merged))\n reset_symbols()\n\n\nif __name__ == \"__main__\":\n test_dynamic_stitch_op()\n\n\n"
] |
[
[
"numpy.array",
"numpy.array_equal"
]
] |
prucehuang/quickly-start-python
|
[
"614cb12e6993d99326138c16de5309206dc02bd8"
] |
[
"Learning Tensor Flow/04__convolutional_neural_networks/layers.py"
] |
[
"import tensorflow as tf\n\n\ndef weight_variable(shape):\n initial = tf.truncated_normal(shape, stddev=0.1)\n return tf.Variable(initial)\n\n\ndef bias_variable(shape):\n initial = tf.constant(0.1, shape=shape)\n return tf.Variable(initial)\n\n\ndef conv2d(x, W):\n return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')\n\n\ndef max_pool_2x2(x):\n return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1], padding='SAME')\n\n\ndef conv_layer(input, shape):\n W = weight_variable(shape)\n b = bias_variable([shape[3]])\n return tf.nn.relu(conv2d(input, W) + b)\n\n\ndef full_layer(input, size):\n in_size = int(input.get_shape()[1])\n W = weight_variable([in_size, size])\n b = bias_variable([size])\n return tf.matmul(input, W) + b\n"
] |
[
[
"tensorflow.matmul",
"tensorflow.constant",
"tensorflow.truncated_normal",
"tensorflow.Variable",
"tensorflow.nn.max_pool",
"tensorflow.nn.conv2d"
]
] |
victen18/DVC-CNN-TF-Pipeline-Demo
|
[
"01e0c400727372cae7557bb8137694e83c35f0a9"
] |
[
"src/utils/model.py"
] |
[
"import tensorflow as tf\nimport logging\nimport io\nfrom src.utils.common import get_timestamp\nimport os\n\n\ndef __get_model_summary(model):\n with io.StringIO() as stream:\n model.summary(print_fn=lambda x: stream.write(f\"{x}\\n\"))\n summary_str = stream.getvalue()\n return summary_str\n\n\ndef get_VGG16_model(input_shape: list, model_path: str) -> tf.keras.models.Model:\n \"\"\"saving and returning the base model extracted from vgg16\"\"\"\n model = tf.keras.applications.vgg16.VGG16(\n input_shape=input_shape, weights=\"imagenet\", include_top=False\n )\n\n logging.info(f\"VGG16 base model summary:\\n{__get_model_summary(model)}\")\n model.save(model_path)\n logging.info(f\"VGG16 model saved at:{model_path}\")\n return model\n\n\ndef prepare_full_model(\n base_model,\n learning_rate,\n CLASSES=2,\n freeze_all=True,\n freeze_till=None,\n) -> tf.keras.models.Model:\n\n if freeze_all:\n for layer in base_model.layers:\n layer.trainable = False\n elif (freeze_till is not None) and (freeze_till > 0):\n for layer in base_model.layers[:-freeze_till]:\n layer.trainable = False\n\n # add our layers to base model\n\n flatten_in = tf.keras.layers.Flatten()(base_model.output)\n\n prediction = tf.keras.layers.Dense(units=CLASSES, activation=\"softmax\")(flatten_in)\n\n full_model = tf.keras.models.Model(inputs=base_model.input, outputs=prediction)\n\n full_model.compile(\n optimizer=tf.keras.optimizers.SGD(learning_rate=learning_rate),\n loss=tf.keras.losses.CategoricalCrossentropy(),\n metrics=[\"accuracy\"],\n )\n\n logging.info(\"custom model is compiled and ready to be trained\")\n logging.info(f\"full model summary:{__get_model_summary(full_model)}\")\n\n return full_model\n\n\ndef load_full_model(untrained_full_model_path: str) -> tf.keras.models.Model:\n model = tf.keras.models.load_model(untrained_full_model_path)\n logging.info(f\"untrained models is read from: {untrained_full_model_path}\")\n logging.info(f\"untrained full model summary: {__get_model_summary}\")\n return model\n\n\ndef get_unique_path_to_save_model(trained_model_dir: str,model_name: str =\"model\") -> str:\n timestamp = get_timestamp(name=model_name)\n unique_model_name = f\"{timestamp}_.h5\"\n unique_model_path = os.path.join(trained_model_dir,unique_model_name)\n\n return unique_model_path\n"
] |
[
[
"tensorflow.keras.models.load_model",
"tensorflow.keras.losses.CategoricalCrossentropy",
"tensorflow.keras.models.Model",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.applications.vgg16.VGG16",
"tensorflow.keras.layers.Flatten",
"tensorflow.keras.optimizers.SGD"
]
] |
MLH-Fellowship/0.1.2-visualization
|
[
"cb9968bded9f5d9528599ec4a5194b1f455bfc9e"
] |
[
"train.py"
] |
[
"import LSTM\nimport data\nimport json\nfrom tensorflow.keras.optimizers import RMSprop\nfrom tensorflow.keras.callbacks import EarlyStopping\n\nVOCAB_SIZE = 5000\nMAX_SEQ_LEN = 100\n\nimdb = data.Dataset(MAX_SEQ_LEN, VOCAB_SIZE)\n\nmodel = LSTM.Network(MAX_SEQ_LEN, VOCAB_SIZE)\nmodel.summary()\nmodel.compile(loss='binary_crossentropy',\n optimizer=RMSprop(), metrics=['accuracy'])\n\n# Model Training\nmodel.fit(imdb.X_train, imdb.Y_train, batch_size=512, epochs=4, validation_split=0.2, callbacks=[\n EarlyStopping(patience=2, verbose=1)\n])\n\n# Run model on test set\naccr = model.evaluate(imdb.X_test, imdb.Y_test)\nprint('Test set\\n Loss: {:0.4f}\\n Accuracy: {:0.2f}'.format(\n accr[0], accr[1]*100))\n\n# save weights as HDF5\nmodel.save(\"model/weights.h5\")\nprint(\"Saved model to disk\")\n\n# save model as JSON\nmodel_json = model.to_json()\nwith open(\"model/model.json\", \"w\") as file:\n file.write(model_json)\n\n# save tokenizer as JSON\ntokenizer_json = imdb.tokenizer.to_json()\nwith open(\"model/tokenizer.json\", 'w', encoding='utf-8') as file:\n file.write(json.dumps(tokenizer_json, ensure_ascii=True))\n"
] |
[
[
"tensorflow.keras.optimizers.RMSprop",
"tensorflow.keras.callbacks.EarlyStopping"
]
] |
wangyixiaohuihui/spark2-annotation
|
[
"421979234f03e698d61b2d14010deb0c6d34d890"
] |
[
"python/pyspark/mllib/linalg/__init__.py"
] |
[
"#\r\n# Licensed to the Apache Software Foundation (ASF) under one or more\r\n# contributor license agreements. See the NOTICE file distributed with\r\n# this work for additional information regarding copyright ownership.\r\n# The ASF licenses this file to You under the Apache License, Version 2.0\r\n# (the \"License\"); you may not use this file except in compliance with\r\n# the License. You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n#\r\n\r\n\"\"\"\r\nMLlib utilities for linear algebra. For dense vectors, MLlib\r\nuses the NumPy C{array} type, so you can simply pass NumPy arrays\r\naround. For sparse vectors, users can construct a L{SparseVector}\r\nobject from MLlib or pass SciPy C{scipy.sparse} column vectors if\r\nSciPy is available in their environment.\r\n\"\"\"\r\n\r\nimport sys\r\nimport array\r\nimport struct\r\n\r\nif sys.version >= '3':\r\n basestring = str\r\n xrange = range\r\n import copyreg as copy_reg\r\n long = int\r\nelse:\r\n from itertools import izip as zip\r\n import copy_reg\r\n\r\nimport numpy as np\r\n\r\nfrom pyspark import since\r\nfrom pyspark.ml import linalg as newlinalg\r\nfrom pyspark.sql.types import UserDefinedType, StructField, StructType, ArrayType, DoubleType, \\\r\n IntegerType, ByteType, BooleanType\r\n\r\n\r\n__all__ = ['Vector', 'DenseVector', 'SparseVector', 'Vectors',\r\n 'Matrix', 'DenseMatrix', 'SparseMatrix', 'Matrices',\r\n 'QRDecomposition']\r\n\r\n\r\nif sys.version_info[:2] == (2, 7):\r\n # speed up pickling array in Python 2.7\r\n def fast_pickle_array(ar):\r\n return array.array, (ar.typecode, ar.tostring())\r\n copy_reg.pickle(array.array, fast_pickle_array)\r\n\r\n\r\n# Check whether we have SciPy. MLlib works without it too, but if we have it, some methods,\r\n# such as _dot and _serialize_double_vector, start to support scipy.sparse matrices.\r\n\r\ntry:\r\n import scipy.sparse\r\n _have_scipy = True\r\nexcept:\r\n # No SciPy in environment, but that's okay\r\n _have_scipy = False\r\n\r\n\r\ndef _convert_to_vector(l):\r\n if isinstance(l, Vector):\r\n return l\r\n elif type(l) in (array.array, np.array, np.ndarray, list, tuple, xrange):\r\n return DenseVector(l)\r\n elif _have_scipy and scipy.sparse.issparse(l):\r\n assert l.shape[1] == 1, \"Expected column vector\"\r\n # Make sure the converted csc_matrix has sorted indices.\r\n csc = l.tocsc()\r\n if not csc.has_sorted_indices:\r\n csc.sort_indices()\r\n return SparseVector(l.shape[0], csc.indices, csc.data)\r\n else:\r\n raise TypeError(\"Cannot convert type %s into Vector\" % type(l))\r\n\r\n\r\ndef _vector_size(v):\r\n \"\"\"\r\n Returns the size of the vector.\r\n\r\n >>> _vector_size([1., 2., 3.])\r\n 3\r\n >>> _vector_size((1., 2., 3.))\r\n 3\r\n >>> _vector_size(array.array('d', [1., 2., 3.]))\r\n 3\r\n >>> _vector_size(np.zeros(3))\r\n 3\r\n >>> _vector_size(np.zeros((3, 1)))\r\n 3\r\n >>> _vector_size(np.zeros((1, 3)))\r\n Traceback (most recent call last):\r\n ...\r\n ValueError: Cannot treat an ndarray of shape (1, 3) as a vector\r\n \"\"\"\r\n if isinstance(v, Vector):\r\n return len(v)\r\n elif type(v) in (array.array, list, tuple, xrange):\r\n return len(v)\r\n elif type(v) == np.ndarray:\r\n if v.ndim == 1 or (v.ndim == 2 and v.shape[1] == 1):\r\n return len(v)\r\n else:\r\n raise ValueError(\"Cannot treat an ndarray of shape %s as a vector\" % str(v.shape))\r\n elif _have_scipy and scipy.sparse.issparse(v):\r\n assert v.shape[1] == 1, \"Expected column vector\"\r\n return v.shape[0]\r\n else:\r\n raise TypeError(\"Cannot treat type %s as a vector\" % type(v))\r\n\r\n\r\ndef _format_float(f, digits=4):\r\n s = str(round(f, digits))\r\n if '.' in s:\r\n s = s[:s.index('.') + 1 + digits]\r\n return s\r\n\r\n\r\ndef _format_float_list(l):\r\n return [_format_float(x) for x in l]\r\n\r\n\r\ndef _double_to_long_bits(value):\r\n if np.isnan(value):\r\n value = float('nan')\r\n # pack double into 64 bits, then unpack as long int\r\n return struct.unpack('Q', struct.pack('d', value))[0]\r\n\r\n\r\nclass VectorUDT(UserDefinedType):\r\n \"\"\"\r\n SQL user-defined type (UDT) for Vector.\r\n \"\"\"\r\n\r\n @classmethod\r\n def sqlType(cls):\r\n return StructType([\r\n StructField(\"type\", ByteType(), False),\r\n StructField(\"size\", IntegerType(), True),\r\n StructField(\"indices\", ArrayType(IntegerType(), False), True),\r\n StructField(\"values\", ArrayType(DoubleType(), False), True)])\r\n\r\n @classmethod\r\n def module(cls):\r\n return \"pyspark.mllib.linalg\"\r\n\r\n @classmethod\r\n def scalaUDT(cls):\r\n return \"org.apache.spark.mllib.linalg.VectorUDT\"\r\n\r\n def serialize(self, obj):\r\n if isinstance(obj, SparseVector):\r\n indices = [int(i) for i in obj.indices]\r\n values = [float(v) for v in obj.values]\r\n return (0, obj.size, indices, values)\r\n elif isinstance(obj, DenseVector):\r\n values = [float(v) for v in obj]\r\n return (1, None, None, values)\r\n else:\r\n raise TypeError(\"cannot serialize %r of type %r\" % (obj, type(obj)))\r\n\r\n def deserialize(self, datum):\r\n assert len(datum) == 4, \\\r\n \"VectorUDT.deserialize given row with length %d but requires 4\" % len(datum)\r\n tpe = datum[0]\r\n if tpe == 0:\r\n return SparseVector(datum[1], datum[2], datum[3])\r\n elif tpe == 1:\r\n return DenseVector(datum[3])\r\n else:\r\n raise ValueError(\"do not recognize type %r\" % tpe)\r\n\r\n def simpleString(self):\r\n return \"vector\"\r\n\r\n\r\nclass MatrixUDT(UserDefinedType):\r\n \"\"\"\r\n SQL user-defined type (UDT) for Matrix.\r\n \"\"\"\r\n\r\n @classmethod\r\n def sqlType(cls):\r\n return StructType([\r\n StructField(\"type\", ByteType(), False),\r\n StructField(\"numRows\", IntegerType(), False),\r\n StructField(\"numCols\", IntegerType(), False),\r\n StructField(\"colPtrs\", ArrayType(IntegerType(), False), True),\r\n StructField(\"rowIndices\", ArrayType(IntegerType(), False), True),\r\n StructField(\"values\", ArrayType(DoubleType(), False), True),\r\n StructField(\"isTransposed\", BooleanType(), False)])\r\n\r\n @classmethod\r\n def module(cls):\r\n return \"pyspark.mllib.linalg\"\r\n\r\n @classmethod\r\n def scalaUDT(cls):\r\n return \"org.apache.spark.mllib.linalg.MatrixUDT\"\r\n\r\n def serialize(self, obj):\r\n if isinstance(obj, SparseMatrix):\r\n colPtrs = [int(i) for i in obj.colPtrs]\r\n rowIndices = [int(i) for i in obj.rowIndices]\r\n values = [float(v) for v in obj.values]\r\n return (0, obj.numRows, obj.numCols, colPtrs,\r\n rowIndices, values, bool(obj.isTransposed))\r\n elif isinstance(obj, DenseMatrix):\r\n values = [float(v) for v in obj.values]\r\n return (1, obj.numRows, obj.numCols, None, None, values,\r\n bool(obj.isTransposed))\r\n else:\r\n raise TypeError(\"cannot serialize type %r\" % (type(obj)))\r\n\r\n def deserialize(self, datum):\r\n assert len(datum) == 7, \\\r\n \"MatrixUDT.deserialize given row with length %d but requires 7\" % len(datum)\r\n tpe = datum[0]\r\n if tpe == 0:\r\n return SparseMatrix(*datum[1:])\r\n elif tpe == 1:\r\n return DenseMatrix(datum[1], datum[2], datum[5], datum[6])\r\n else:\r\n raise ValueError(\"do not recognize type %r\" % tpe)\r\n\r\n def simpleString(self):\r\n return \"matrix\"\r\n\r\n\r\nclass Vector(object):\r\n\r\n __UDT__ = VectorUDT()\r\n\r\n \"\"\"\r\n Abstract class for DenseVector and SparseVector\r\n \"\"\"\r\n def toArray(self):\r\n \"\"\"\r\n Convert the vector into an numpy.ndarray\r\n\r\n :return: numpy.ndarray\r\n \"\"\"\r\n raise NotImplementedError\r\n\r\n def asML(self):\r\n \"\"\"\r\n Convert this vector to the new mllib-local representation.\r\n This does NOT copy the data; it copies references.\r\n\r\n :return: :py:class:`pyspark.ml.linalg.Vector`\r\n \"\"\"\r\n raise NotImplementedError\r\n\r\n\r\nclass DenseVector(Vector):\r\n \"\"\"\r\n A dense vector represented by a value array. We use numpy array for\r\n storage and arithmetics will be delegated to the underlying numpy\r\n array.\r\n\r\n >>> v = Vectors.dense([1.0, 2.0])\r\n >>> u = Vectors.dense([3.0, 4.0])\r\n >>> v + u\r\n DenseVector([4.0, 6.0])\r\n >>> 2 - v\r\n DenseVector([1.0, 0.0])\r\n >>> v / 2\r\n DenseVector([0.5, 1.0])\r\n >>> v * u\r\n DenseVector([3.0, 8.0])\r\n >>> u / v\r\n DenseVector([3.0, 2.0])\r\n >>> u % 2\r\n DenseVector([1.0, 0.0])\r\n \"\"\"\r\n def __init__(self, ar):\r\n if isinstance(ar, bytes):\r\n ar = np.frombuffer(ar, dtype=np.float64)\r\n elif not isinstance(ar, np.ndarray):\r\n ar = np.array(ar, dtype=np.float64)\r\n if ar.dtype != np.float64:\r\n ar = ar.astype(np.float64)\r\n self.array = ar\r\n\r\n @staticmethod\r\n def parse(s):\r\n \"\"\"\r\n Parse string representation back into the DenseVector.\r\n\r\n >>> DenseVector.parse(' [ 0.0,1.0,2.0, 3.0]')\r\n DenseVector([0.0, 1.0, 2.0, 3.0])\r\n \"\"\"\r\n start = s.find('[')\r\n if start == -1:\r\n raise ValueError(\"Array should start with '['.\")\r\n end = s.find(']')\r\n if end == -1:\r\n raise ValueError(\"Array should end with ']'.\")\r\n s = s[start + 1: end]\r\n\r\n try:\r\n values = [float(val) for val in s.split(',') if val]\r\n except ValueError:\r\n raise ValueError(\"Unable to parse values from %s\" % s)\r\n return DenseVector(values)\r\n\r\n def __reduce__(self):\r\n return DenseVector, (self.array.tostring(),)\r\n\r\n def numNonzeros(self):\r\n \"\"\"\r\n Number of nonzero elements. This scans all active values and count non zeros\r\n \"\"\"\r\n return np.count_nonzero(self.array)\r\n\r\n def norm(self, p):\r\n \"\"\"\r\n Calculates the norm of a DenseVector.\r\n\r\n >>> a = DenseVector([0, -1, 2, -3])\r\n >>> a.norm(2)\r\n 3.7...\r\n >>> a.norm(1)\r\n 6.0\r\n \"\"\"\r\n return np.linalg.norm(self.array, p)\r\n\r\n def dot(self, other):\r\n \"\"\"\r\n Compute the dot product of two Vectors. We support\r\n (Numpy array, list, SparseVector, or SciPy sparse)\r\n and a target NumPy array that is either 1- or 2-dimensional.\r\n Equivalent to calling numpy.dot of the two vectors.\r\n\r\n >>> dense = DenseVector(array.array('d', [1., 2.]))\r\n >>> dense.dot(dense)\r\n 5.0\r\n >>> dense.dot(SparseVector(2, [0, 1], [2., 1.]))\r\n 4.0\r\n >>> dense.dot(range(1, 3))\r\n 5.0\r\n >>> dense.dot(np.array(range(1, 3)))\r\n 5.0\r\n >>> dense.dot([1.,])\r\n Traceback (most recent call last):\r\n ...\r\n AssertionError: dimension mismatch\r\n >>> dense.dot(np.reshape([1., 2., 3., 4.], (2, 2), order='F'))\r\n array([ 5., 11.])\r\n >>> dense.dot(np.reshape([1., 2., 3.], (3, 1), order='F'))\r\n Traceback (most recent call last):\r\n ...\r\n AssertionError: dimension mismatch\r\n \"\"\"\r\n if type(other) == np.ndarray:\r\n if other.ndim > 1:\r\n assert len(self) == other.shape[0], \"dimension mismatch\"\r\n return np.dot(self.array, other)\r\n elif _have_scipy and scipy.sparse.issparse(other):\r\n assert len(self) == other.shape[0], \"dimension mismatch\"\r\n return other.transpose().dot(self.toArray())\r\n else:\r\n assert len(self) == _vector_size(other), \"dimension mismatch\"\r\n if isinstance(other, SparseVector):\r\n return other.dot(self)\r\n elif isinstance(other, Vector):\r\n return np.dot(self.toArray(), other.toArray())\r\n else:\r\n return np.dot(self.toArray(), other)\r\n\r\n def squared_distance(self, other):\r\n \"\"\"\r\n Squared distance of two Vectors.\r\n\r\n >>> dense1 = DenseVector(array.array('d', [1., 2.]))\r\n >>> dense1.squared_distance(dense1)\r\n 0.0\r\n >>> dense2 = np.array([2., 1.])\r\n >>> dense1.squared_distance(dense2)\r\n 2.0\r\n >>> dense3 = [2., 1.]\r\n >>> dense1.squared_distance(dense3)\r\n 2.0\r\n >>> sparse1 = SparseVector(2, [0, 1], [2., 1.])\r\n >>> dense1.squared_distance(sparse1)\r\n 2.0\r\n >>> dense1.squared_distance([1.,])\r\n Traceback (most recent call last):\r\n ...\r\n AssertionError: dimension mismatch\r\n >>> dense1.squared_distance(SparseVector(1, [0,], [1.,]))\r\n Traceback (most recent call last):\r\n ...\r\n AssertionError: dimension mismatch\r\n \"\"\"\r\n assert len(self) == _vector_size(other), \"dimension mismatch\"\r\n if isinstance(other, SparseVector):\r\n return other.squared_distance(self)\r\n elif _have_scipy and scipy.sparse.issparse(other):\r\n return _convert_to_vector(other).squared_distance(self)\r\n\r\n if isinstance(other, Vector):\r\n other = other.toArray()\r\n elif not isinstance(other, np.ndarray):\r\n other = np.array(other)\r\n diff = self.toArray() - other\r\n return np.dot(diff, diff)\r\n\r\n def toArray(self):\r\n \"\"\"\r\n Returns an numpy.ndarray\r\n \"\"\"\r\n return self.array\r\n\r\n def asML(self):\r\n \"\"\"\r\n Convert this vector to the new mllib-local representation.\r\n This does NOT copy the data; it copies references.\r\n\r\n :return: :py:class:`pyspark.ml.linalg.DenseVector`\r\n\r\n .. versionadded:: 2.0.0\r\n \"\"\"\r\n return newlinalg.DenseVector(self.array)\r\n\r\n @property\r\n def values(self):\r\n \"\"\"\r\n Returns a list of values\r\n \"\"\"\r\n return self.array\r\n\r\n def __getitem__(self, item):\r\n return self.array[item]\r\n\r\n def __len__(self):\r\n return len(self.array)\r\n\r\n def __str__(self):\r\n return \"[\" + \",\".join([str(v) for v in self.array]) + \"]\"\r\n\r\n def __repr__(self):\r\n return \"DenseVector([%s])\" % (', '.join(_format_float(i) for i in self.array))\r\n\r\n def __eq__(self, other):\r\n if isinstance(other, DenseVector):\r\n return np.array_equal(self.array, other.array)\r\n elif isinstance(other, SparseVector):\r\n if len(self) != other.size:\r\n return False\r\n return Vectors._equals(list(xrange(len(self))), self.array, other.indices, other.values)\r\n return False\r\n\r\n def __ne__(self, other):\r\n return not self == other\r\n\r\n def __hash__(self):\r\n size = len(self)\r\n result = 31 + size\r\n nnz = 0\r\n i = 0\r\n while i < size and nnz < 128:\r\n if self.array[i] != 0:\r\n result = 31 * result + i\r\n bits = _double_to_long_bits(self.array[i])\r\n result = 31 * result + (bits ^ (bits >> 32))\r\n nnz += 1\r\n i += 1\r\n return result\r\n\r\n def __getattr__(self, item):\r\n return getattr(self.array, item)\r\n\r\n def _delegate(op):\r\n def func(self, other):\r\n if isinstance(other, DenseVector):\r\n other = other.array\r\n return DenseVector(getattr(self.array, op)(other))\r\n return func\r\n\r\n __neg__ = _delegate(\"__neg__\")\r\n __add__ = _delegate(\"__add__\")\r\n __sub__ = _delegate(\"__sub__\")\r\n __mul__ = _delegate(\"__mul__\")\r\n __div__ = _delegate(\"__div__\")\r\n __truediv__ = _delegate(\"__truediv__\")\r\n __mod__ = _delegate(\"__mod__\")\r\n __radd__ = _delegate(\"__radd__\")\r\n __rsub__ = _delegate(\"__rsub__\")\r\n __rmul__ = _delegate(\"__rmul__\")\r\n __rdiv__ = _delegate(\"__rdiv__\")\r\n __rtruediv__ = _delegate(\"__rtruediv__\")\r\n __rmod__ = _delegate(\"__rmod__\")\r\n\r\n\r\nclass SparseVector(Vector):\r\n \"\"\"\r\n A simple sparse vector class for passing data to MLlib. Users may\r\n alternatively pass SciPy's {scipy.sparse} data types.\r\n \"\"\"\r\n def __init__(self, size, *args):\r\n \"\"\"\r\n Create a sparse vector, using either a dictionary, a list of\r\n (index, value) pairs, or two separate arrays of indices and\r\n values (sorted by index).\r\n\r\n :param size: Size of the vector.\r\n :param args: Active entries, as a dictionary {index: value, ...},\r\n a list of tuples [(index, value), ...], or a list of strictly\r\n increasing indices and a list of corresponding values [index, ...],\r\n [value, ...]. Inactive entries are treated as zeros.\r\n\r\n >>> SparseVector(4, {1: 1.0, 3: 5.5})\r\n SparseVector(4, {1: 1.0, 3: 5.5})\r\n >>> SparseVector(4, [(1, 1.0), (3, 5.5)])\r\n SparseVector(4, {1: 1.0, 3: 5.5})\r\n >>> SparseVector(4, [1, 3], [1.0, 5.5])\r\n SparseVector(4, {1: 1.0, 3: 5.5})\r\n \"\"\"\r\n self.size = int(size)\r\n \"\"\" Size of the vector. \"\"\"\r\n assert 1 <= len(args) <= 2, \"must pass either 2 or 3 arguments\"\r\n if len(args) == 1:\r\n pairs = args[0]\r\n if type(pairs) == dict:\r\n pairs = pairs.items()\r\n pairs = sorted(pairs)\r\n self.indices = np.array([p[0] for p in pairs], dtype=np.int32)\r\n \"\"\" A list of indices corresponding to active entries. \"\"\"\r\n self.values = np.array([p[1] for p in pairs], dtype=np.float64)\r\n \"\"\" A list of values corresponding to active entries. \"\"\"\r\n else:\r\n if isinstance(args[0], bytes):\r\n assert isinstance(args[1], bytes), \"values should be string too\"\r\n if args[0]:\r\n self.indices = np.frombuffer(args[0], np.int32)\r\n self.values = np.frombuffer(args[1], np.float64)\r\n else:\r\n # np.frombuffer() doesn't work well with empty string in older version\r\n self.indices = np.array([], dtype=np.int32)\r\n self.values = np.array([], dtype=np.float64)\r\n else:\r\n self.indices = np.array(args[0], dtype=np.int32)\r\n self.values = np.array(args[1], dtype=np.float64)\r\n assert len(self.indices) == len(self.values), \"index and value arrays not same length\"\r\n for i in xrange(len(self.indices) - 1):\r\n if self.indices[i] >= self.indices[i + 1]:\r\n raise TypeError(\r\n \"Indices %s and %s are not strictly increasing\"\r\n % (self.indices[i], self.indices[i + 1]))\r\n\r\n def numNonzeros(self):\r\n \"\"\"\r\n Number of nonzero elements. This scans all active values and count non zeros.\r\n \"\"\"\r\n return np.count_nonzero(self.values)\r\n\r\n def norm(self, p):\r\n \"\"\"\r\n Calculates the norm of a SparseVector.\r\n\r\n >>> a = SparseVector(4, [0, 1], [3., -4.])\r\n >>> a.norm(1)\r\n 7.0\r\n >>> a.norm(2)\r\n 5.0\r\n \"\"\"\r\n return np.linalg.norm(self.values, p)\r\n\r\n def __reduce__(self):\r\n return (\r\n SparseVector,\r\n (self.size, self.indices.tostring(), self.values.tostring()))\r\n\r\n @staticmethod\r\n def parse(s):\r\n \"\"\"\r\n Parse string representation back into the SparseVector.\r\n\r\n >>> SparseVector.parse(' (4, [0,1 ],[ 4.0,5.0] )')\r\n SparseVector(4, {0: 4.0, 1: 5.0})\r\n \"\"\"\r\n start = s.find('(')\r\n if start == -1:\r\n raise ValueError(\"Tuple should start with '('\")\r\n end = s.find(')')\r\n if end == -1:\r\n raise ValueError(\"Tuple should end with ')'\")\r\n s = s[start + 1: end].strip()\r\n\r\n size = s[: s.find(',')]\r\n try:\r\n size = int(size)\r\n except ValueError:\r\n raise ValueError(\"Cannot parse size %s.\" % size)\r\n\r\n ind_start = s.find('[')\r\n if ind_start == -1:\r\n raise ValueError(\"Indices array should start with '['.\")\r\n ind_end = s.find(']')\r\n if ind_end == -1:\r\n raise ValueError(\"Indices array should end with ']'\")\r\n new_s = s[ind_start + 1: ind_end]\r\n ind_list = new_s.split(',')\r\n try:\r\n indices = [int(ind) for ind in ind_list if ind]\r\n except ValueError:\r\n raise ValueError(\"Unable to parse indices from %s.\" % new_s)\r\n s = s[ind_end + 1:].strip()\r\n\r\n val_start = s.find('[')\r\n if val_start == -1:\r\n raise ValueError(\"Values array should start with '['.\")\r\n val_end = s.find(']')\r\n if val_end == -1:\r\n raise ValueError(\"Values array should end with ']'.\")\r\n val_list = s[val_start + 1: val_end].split(',')\r\n try:\r\n values = [float(val) for val in val_list if val]\r\n except ValueError:\r\n raise ValueError(\"Unable to parse values from %s.\" % s)\r\n return SparseVector(size, indices, values)\r\n\r\n def dot(self, other):\r\n \"\"\"\r\n Dot product with a SparseVector or 1- or 2-dimensional Numpy array.\r\n\r\n >>> a = SparseVector(4, [1, 3], [3.0, 4.0])\r\n >>> a.dot(a)\r\n 25.0\r\n >>> a.dot(array.array('d', [1., 2., 3., 4.]))\r\n 22.0\r\n >>> b = SparseVector(4, [2], [1.0])\r\n >>> a.dot(b)\r\n 0.0\r\n >>> a.dot(np.array([[1, 1], [2, 2], [3, 3], [4, 4]]))\r\n array([ 22., 22.])\r\n >>> a.dot([1., 2., 3.])\r\n Traceback (most recent call last):\r\n ...\r\n AssertionError: dimension mismatch\r\n >>> a.dot(np.array([1., 2.]))\r\n Traceback (most recent call last):\r\n ...\r\n AssertionError: dimension mismatch\r\n >>> a.dot(DenseVector([1., 2.]))\r\n Traceback (most recent call last):\r\n ...\r\n AssertionError: dimension mismatch\r\n >>> a.dot(np.zeros((3, 2)))\r\n Traceback (most recent call last):\r\n ...\r\n AssertionError: dimension mismatch\r\n \"\"\"\r\n\r\n if isinstance(other, np.ndarray):\r\n if other.ndim not in [2, 1]:\r\n raise ValueError(\"Cannot call dot with %d-dimensional array\" % other.ndim)\r\n assert len(self) == other.shape[0], \"dimension mismatch\"\r\n return np.dot(self.values, other[self.indices])\r\n\r\n assert len(self) == _vector_size(other), \"dimension mismatch\"\r\n\r\n if isinstance(other, DenseVector):\r\n return np.dot(other.array[self.indices], self.values)\r\n\r\n elif isinstance(other, SparseVector):\r\n # Find out common indices.\r\n self_cmind = np.in1d(self.indices, other.indices, assume_unique=True)\r\n self_values = self.values[self_cmind]\r\n if self_values.size == 0:\r\n return 0.0\r\n else:\r\n other_cmind = np.in1d(other.indices, self.indices, assume_unique=True)\r\n return np.dot(self_values, other.values[other_cmind])\r\n\r\n else:\r\n return self.dot(_convert_to_vector(other))\r\n\r\n def squared_distance(self, other):\r\n \"\"\"\r\n Squared distance from a SparseVector or 1-dimensional NumPy array.\r\n\r\n >>> a = SparseVector(4, [1, 3], [3.0, 4.0])\r\n >>> a.squared_distance(a)\r\n 0.0\r\n >>> a.squared_distance(array.array('d', [1., 2., 3., 4.]))\r\n 11.0\r\n >>> a.squared_distance(np.array([1., 2., 3., 4.]))\r\n 11.0\r\n >>> b = SparseVector(4, [2], [1.0])\r\n >>> a.squared_distance(b)\r\n 26.0\r\n >>> b.squared_distance(a)\r\n 26.0\r\n >>> b.squared_distance([1., 2.])\r\n Traceback (most recent call last):\r\n ...\r\n AssertionError: dimension mismatch\r\n >>> b.squared_distance(SparseVector(3, [1,], [1.0,]))\r\n Traceback (most recent call last):\r\n ...\r\n AssertionError: dimension mismatch\r\n \"\"\"\r\n assert len(self) == _vector_size(other), \"dimension mismatch\"\r\n\r\n if isinstance(other, np.ndarray) or isinstance(other, DenseVector):\r\n if isinstance(other, np.ndarray) and other.ndim != 1:\r\n raise Exception(\"Cannot call squared_distance with %d-dimensional array\" %\r\n other.ndim)\r\n if isinstance(other, DenseVector):\r\n other = other.array\r\n sparse_ind = np.zeros(other.size, dtype=bool)\r\n sparse_ind[self.indices] = True\r\n dist = other[sparse_ind] - self.values\r\n result = np.dot(dist, dist)\r\n\r\n other_ind = other[~sparse_ind]\r\n result += np.dot(other_ind, other_ind)\r\n return result\r\n\r\n elif isinstance(other, SparseVector):\r\n result = 0.0\r\n i, j = 0, 0\r\n while i < len(self.indices) and j < len(other.indices):\r\n if self.indices[i] == other.indices[j]:\r\n diff = self.values[i] - other.values[j]\r\n result += diff * diff\r\n i += 1\r\n j += 1\r\n elif self.indices[i] < other.indices[j]:\r\n result += self.values[i] * self.values[i]\r\n i += 1\r\n else:\r\n result += other.values[j] * other.values[j]\r\n j += 1\r\n while i < len(self.indices):\r\n result += self.values[i] * self.values[i]\r\n i += 1\r\n while j < len(other.indices):\r\n result += other.values[j] * other.values[j]\r\n j += 1\r\n return result\r\n else:\r\n return self.squared_distance(_convert_to_vector(other))\r\n\r\n def toArray(self):\r\n \"\"\"\r\n Returns a copy of this SparseVector as a 1-dimensional NumPy array.\r\n \"\"\"\r\n arr = np.zeros((self.size,), dtype=np.float64)\r\n arr[self.indices] = self.values\r\n return arr\r\n\r\n def asML(self):\r\n \"\"\"\r\n Convert this vector to the new mllib-local representation.\r\n This does NOT copy the data; it copies references.\r\n\r\n :return: :py:class:`pyspark.ml.linalg.SparseVector`\r\n\r\n .. versionadded:: 2.0.0\r\n \"\"\"\r\n return newlinalg.SparseVector(self.size, self.indices, self.values)\r\n\r\n def __len__(self):\r\n return self.size\r\n\r\n def __str__(self):\r\n inds = \"[\" + \",\".join([str(i) for i in self.indices]) + \"]\"\r\n vals = \"[\" + \",\".join([str(v) for v in self.values]) + \"]\"\r\n return \"(\" + \",\".join((str(self.size), inds, vals)) + \")\"\r\n\r\n def __repr__(self):\r\n inds = self.indices\r\n vals = self.values\r\n entries = \", \".join([\"{0}: {1}\".format(inds[i], _format_float(vals[i]))\r\n for i in xrange(len(inds))])\r\n return \"SparseVector({0}, {{{1}}})\".format(self.size, entries)\r\n\r\n def __eq__(self, other):\r\n if isinstance(other, SparseVector):\r\n return other.size == self.size and np.array_equal(other.indices, self.indices) \\\r\n and np.array_equal(other.values, self.values)\r\n elif isinstance(other, DenseVector):\r\n if self.size != len(other):\r\n return False\r\n return Vectors._equals(self.indices, self.values, list(xrange(len(other))), other.array)\r\n return False\r\n\r\n def __getitem__(self, index):\r\n inds = self.indices\r\n vals = self.values\r\n if not isinstance(index, int):\r\n raise TypeError(\r\n \"Indices must be of type integer, got type %s\" % type(index))\r\n\r\n if index >= self.size or index < -self.size:\r\n raise IndexError(\"Index %d out of bounds.\" % index)\r\n if index < 0:\r\n index += self.size\r\n\r\n if (inds.size == 0) or (index > inds.item(-1)):\r\n return 0.\r\n\r\n insert_index = np.searchsorted(inds, index)\r\n row_ind = inds[insert_index]\r\n if row_ind == index:\r\n return vals[insert_index]\r\n return 0.\r\n\r\n def __ne__(self, other):\r\n return not self.__eq__(other)\r\n\r\n def __hash__(self):\r\n result = 31 + self.size\r\n nnz = 0\r\n i = 0\r\n while i < len(self.values) and nnz < 128:\r\n if self.values[i] != 0:\r\n result = 31 * result + int(self.indices[i])\r\n bits = _double_to_long_bits(self.values[i])\r\n result = 31 * result + (bits ^ (bits >> 32))\r\n nnz += 1\r\n i += 1\r\n return result\r\n\r\n\r\nclass Vectors(object):\r\n\r\n \"\"\"\r\n Factory methods for working with vectors.\r\n\r\n .. note:: Dense vectors are simply represented as NumPy array objects,\r\n so there is no need to covert them for use in MLlib. For sparse vectors,\r\n the factory methods in this class create an MLlib-compatible type, or users\r\n can pass in SciPy's C{scipy.sparse} column vectors.\r\n \"\"\"\r\n\r\n @staticmethod\r\n def sparse(size, *args):\r\n \"\"\"\r\n Create a sparse vector, using either a dictionary, a list of\r\n (index, value) pairs, or two separate arrays of indices and\r\n values (sorted by index).\r\n\r\n :param size: Size of the vector.\r\n :param args: Non-zero entries, as a dictionary, list of tuples,\r\n or two sorted lists containing indices and values.\r\n\r\n >>> Vectors.sparse(4, {1: 1.0, 3: 5.5})\r\n SparseVector(4, {1: 1.0, 3: 5.5})\r\n >>> Vectors.sparse(4, [(1, 1.0), (3, 5.5)])\r\n SparseVector(4, {1: 1.0, 3: 5.5})\r\n >>> Vectors.sparse(4, [1, 3], [1.0, 5.5])\r\n SparseVector(4, {1: 1.0, 3: 5.5})\r\n \"\"\"\r\n return SparseVector(size, *args)\r\n\r\n @staticmethod\r\n def dense(*elements):\r\n \"\"\"\r\n Create a dense vector of 64-bit floats from a Python list or numbers.\r\n\r\n >>> Vectors.dense([1, 2, 3])\r\n DenseVector([1.0, 2.0, 3.0])\r\n >>> Vectors.dense(1.0, 2.0)\r\n DenseVector([1.0, 2.0])\r\n \"\"\"\r\n if len(elements) == 1 and not isinstance(elements[0], (float, int, long)):\r\n # it's list, numpy.array or other iterable object.\r\n elements = elements[0]\r\n return DenseVector(elements)\r\n\r\n @staticmethod\r\n def fromML(vec):\r\n \"\"\"\r\n Convert a vector from the new mllib-local representation.\r\n This does NOT copy the data; it copies references.\r\n\r\n :param vec: a :py:class:`pyspark.ml.linalg.Vector`\r\n :return: a :py:class:`pyspark.mllib.linalg.Vector`\r\n\r\n .. versionadded:: 2.0.0\r\n \"\"\"\r\n if isinstance(vec, newlinalg.DenseVector):\r\n return DenseVector(vec.array)\r\n elif isinstance(vec, newlinalg.SparseVector):\r\n return SparseVector(vec.size, vec.indices, vec.values)\r\n else:\r\n raise TypeError(\"Unsupported vector type %s\" % type(vec))\r\n\r\n @staticmethod\r\n def stringify(vector):\r\n \"\"\"\r\n Converts a vector into a string, which can be recognized by\r\n Vectors.parse().\r\n\r\n >>> Vectors.stringify(Vectors.sparse(2, [1], [1.0]))\r\n '(2,[1],[1.0])'\r\n >>> Vectors.stringify(Vectors.dense([0.0, 1.0]))\r\n '[0.0,1.0]'\r\n \"\"\"\r\n return str(vector)\r\n\r\n @staticmethod\r\n def squared_distance(v1, v2):\r\n \"\"\"\r\n Squared distance between two vectors.\r\n a and b can be of type SparseVector, DenseVector, np.ndarray\r\n or array.array.\r\n\r\n >>> a = Vectors.sparse(4, [(0, 1), (3, 4)])\r\n >>> b = Vectors.dense([2, 5, 4, 1])\r\n >>> a.squared_distance(b)\r\n 51.0\r\n \"\"\"\r\n v1, v2 = _convert_to_vector(v1), _convert_to_vector(v2)\r\n return v1.squared_distance(v2)\r\n\r\n @staticmethod\r\n def norm(vector, p):\r\n \"\"\"\r\n Find norm of the given vector.\r\n \"\"\"\r\n return _convert_to_vector(vector).norm(p)\r\n\r\n @staticmethod\r\n def parse(s):\r\n \"\"\"Parse a string representation back into the Vector.\r\n\r\n >>> Vectors.parse('[2,1,2 ]')\r\n DenseVector([2.0, 1.0, 2.0])\r\n >>> Vectors.parse(' ( 100, [0], [2])')\r\n SparseVector(100, {0: 2.0})\r\n \"\"\"\r\n if s.find('(') == -1 and s.find('[') != -1:\r\n return DenseVector.parse(s)\r\n elif s.find('(') != -1:\r\n return SparseVector.parse(s)\r\n else:\r\n raise ValueError(\r\n \"Cannot find tokens '[' or '(' from the input string.\")\r\n\r\n @staticmethod\r\n def zeros(size):\r\n return DenseVector(np.zeros(size))\r\n\r\n @staticmethod\r\n def _equals(v1_indices, v1_values, v2_indices, v2_values):\r\n \"\"\"\r\n Check equality between sparse/dense vectors,\r\n v1_indices and v2_indices assume to be strictly increasing.\r\n \"\"\"\r\n v1_size = len(v1_values)\r\n v2_size = len(v2_values)\r\n k1 = 0\r\n k2 = 0\r\n all_equal = True\r\n while all_equal:\r\n while k1 < v1_size and v1_values[k1] == 0:\r\n k1 += 1\r\n while k2 < v2_size and v2_values[k2] == 0:\r\n k2 += 1\r\n\r\n if k1 >= v1_size or k2 >= v2_size:\r\n return k1 >= v1_size and k2 >= v2_size\r\n\r\n all_equal = v1_indices[k1] == v2_indices[k2] and v1_values[k1] == v2_values[k2]\r\n k1 += 1\r\n k2 += 1\r\n return all_equal\r\n\r\n\r\nclass Matrix(object):\r\n\r\n __UDT__ = MatrixUDT()\r\n\r\n \"\"\"\r\n Represents a local matrix.\r\n \"\"\"\r\n def __init__(self, numRows, numCols, isTransposed=False):\r\n self.numRows = numRows\r\n self.numCols = numCols\r\n self.isTransposed = isTransposed\r\n\r\n def toArray(self):\r\n \"\"\"\r\n Returns its elements in a NumPy ndarray.\r\n \"\"\"\r\n raise NotImplementedError\r\n\r\n def asML(self):\r\n \"\"\"\r\n Convert this matrix to the new mllib-local representation.\r\n This does NOT copy the data; it copies references.\r\n \"\"\"\r\n raise NotImplementedError\r\n\r\n @staticmethod\r\n def _convert_to_array(array_like, dtype):\r\n \"\"\"\r\n Convert Matrix attributes which are array-like or buffer to array.\r\n \"\"\"\r\n if isinstance(array_like, bytes):\r\n return np.frombuffer(array_like, dtype=dtype)\r\n return np.asarray(array_like, dtype=dtype)\r\n\r\n\r\nclass DenseMatrix(Matrix):\r\n \"\"\"\r\n Column-major dense matrix.\r\n \"\"\"\r\n def __init__(self, numRows, numCols, values, isTransposed=False):\r\n Matrix.__init__(self, numRows, numCols, isTransposed)\r\n values = self._convert_to_array(values, np.float64)\r\n assert len(values) == numRows * numCols\r\n self.values = values\r\n\r\n def __reduce__(self):\r\n return DenseMatrix, (\r\n self.numRows, self.numCols, self.values.tostring(),\r\n int(self.isTransposed))\r\n\r\n def __str__(self):\r\n \"\"\"\r\n Pretty printing of a DenseMatrix\r\n\r\n >>> dm = DenseMatrix(2, 2, range(4))\r\n >>> print(dm)\r\n DenseMatrix([[ 0., 2.],\r\n [ 1., 3.]])\r\n >>> dm = DenseMatrix(2, 2, range(4), isTransposed=True)\r\n >>> print(dm)\r\n DenseMatrix([[ 0., 1.],\r\n [ 2., 3.]])\r\n \"\"\"\r\n # Inspired by __repr__ in scipy matrices.\r\n array_lines = repr(self.toArray()).splitlines()\r\n\r\n # We need to adjust six spaces which is the difference in number\r\n # of letters between \"DenseMatrix\" and \"array\"\r\n x = '\\n'.join([(\" \" * 6 + line) for line in array_lines[1:]])\r\n return array_lines[0].replace(\"array\", \"DenseMatrix\") + \"\\n\" + x\r\n\r\n def __repr__(self):\r\n \"\"\"\r\n Representation of a DenseMatrix\r\n\r\n >>> dm = DenseMatrix(2, 2, range(4))\r\n >>> dm\r\n DenseMatrix(2, 2, [0.0, 1.0, 2.0, 3.0], False)\r\n \"\"\"\r\n # If the number of values are less than seventeen then return as it is.\r\n # Else return first eight values and last eight values.\r\n if len(self.values) < 17:\r\n entries = _format_float_list(self.values)\r\n else:\r\n entries = (\r\n _format_float_list(self.values[:8]) +\r\n [\"...\"] +\r\n _format_float_list(self.values[-8:])\r\n )\r\n\r\n entries = \", \".join(entries)\r\n return \"DenseMatrix({0}, {1}, [{2}], {3})\".format(\r\n self.numRows, self.numCols, entries, self.isTransposed)\r\n\r\n def toArray(self):\r\n \"\"\"\r\n Return an numpy.ndarray\r\n\r\n >>> m = DenseMatrix(2, 2, range(4))\r\n >>> m.toArray()\r\n array([[ 0., 2.],\r\n [ 1., 3.]])\r\n \"\"\"\r\n if self.isTransposed:\r\n return np.asfortranarray(\r\n self.values.reshape((self.numRows, self.numCols)))\r\n else:\r\n return self.values.reshape((self.numRows, self.numCols), order='F')\r\n\r\n def toSparse(self):\r\n \"\"\"Convert to SparseMatrix\"\"\"\r\n if self.isTransposed:\r\n values = np.ravel(self.toArray(), order='F')\r\n else:\r\n values = self.values\r\n indices = np.nonzero(values)[0]\r\n colCounts = np.bincount(indices // self.numRows)\r\n colPtrs = np.cumsum(np.hstack(\r\n (0, colCounts, np.zeros(self.numCols - colCounts.size))))\r\n values = values[indices]\r\n rowIndices = indices % self.numRows\r\n\r\n return SparseMatrix(self.numRows, self.numCols, colPtrs, rowIndices, values)\r\n\r\n def asML(self):\r\n \"\"\"\r\n Convert this matrix to the new mllib-local representation.\r\n This does NOT copy the data; it copies references.\r\n\r\n :return: :py:class:`pyspark.ml.linalg.DenseMatrix`\r\n\r\n .. versionadded:: 2.0.0\r\n \"\"\"\r\n return newlinalg.DenseMatrix(self.numRows, self.numCols, self.values, self.isTransposed)\r\n\r\n def __getitem__(self, indices):\r\n i, j = indices\r\n if i < 0 or i >= self.numRows:\r\n raise IndexError(\"Row index %d is out of range [0, %d)\"\r\n % (i, self.numRows))\r\n if j >= self.numCols or j < 0:\r\n raise IndexError(\"Column index %d is out of range [0, %d)\"\r\n % (j, self.numCols))\r\n\r\n if self.isTransposed:\r\n return self.values[i * self.numCols + j]\r\n else:\r\n return self.values[i + j * self.numRows]\r\n\r\n def __eq__(self, other):\r\n if (not isinstance(other, DenseMatrix) or\r\n self.numRows != other.numRows or\r\n self.numCols != other.numCols):\r\n return False\r\n\r\n self_values = np.ravel(self.toArray(), order='F')\r\n other_values = np.ravel(other.toArray(), order='F')\r\n return all(self_values == other_values)\r\n\r\n\r\nclass SparseMatrix(Matrix):\r\n \"\"\"Sparse Matrix stored in CSC format.\"\"\"\r\n def __init__(self, numRows, numCols, colPtrs, rowIndices, values,\r\n isTransposed=False):\r\n Matrix.__init__(self, numRows, numCols, isTransposed)\r\n self.colPtrs = self._convert_to_array(colPtrs, np.int32)\r\n self.rowIndices = self._convert_to_array(rowIndices, np.int32)\r\n self.values = self._convert_to_array(values, np.float64)\r\n\r\n if self.isTransposed:\r\n if self.colPtrs.size != numRows + 1:\r\n raise ValueError(\"Expected colPtrs of size %d, got %d.\"\r\n % (numRows + 1, self.colPtrs.size))\r\n else:\r\n if self.colPtrs.size != numCols + 1:\r\n raise ValueError(\"Expected colPtrs of size %d, got %d.\"\r\n % (numCols + 1, self.colPtrs.size))\r\n if self.rowIndices.size != self.values.size:\r\n raise ValueError(\"Expected rowIndices of length %d, got %d.\"\r\n % (self.rowIndices.size, self.values.size))\r\n\r\n def __str__(self):\r\n \"\"\"\r\n Pretty printing of a SparseMatrix\r\n\r\n >>> sm1 = SparseMatrix(2, 2, [0, 2, 3], [0, 1, 1], [2, 3, 4])\r\n >>> print(sm1)\r\n 2 X 2 CSCMatrix\r\n (0,0) 2.0\r\n (1,0) 3.0\r\n (1,1) 4.0\r\n >>> sm1 = SparseMatrix(2, 2, [0, 2, 3], [0, 1, 1], [2, 3, 4], True)\r\n >>> print(sm1)\r\n 2 X 2 CSRMatrix\r\n (0,0) 2.0\r\n (0,1) 3.0\r\n (1,1) 4.0\r\n \"\"\"\r\n spstr = \"{0} X {1} \".format(self.numRows, self.numCols)\r\n if self.isTransposed:\r\n spstr += \"CSRMatrix\\n\"\r\n else:\r\n spstr += \"CSCMatrix\\n\"\r\n\r\n cur_col = 0\r\n smlist = []\r\n\r\n # Display first 16 values.\r\n if len(self.values) <= 16:\r\n zipindval = zip(self.rowIndices, self.values)\r\n else:\r\n zipindval = zip(self.rowIndices[:16], self.values[:16])\r\n for i, (rowInd, value) in enumerate(zipindval):\r\n if self.colPtrs[cur_col + 1] <= i:\r\n cur_col += 1\r\n if self.isTransposed:\r\n smlist.append('({0},{1}) {2}'.format(\r\n cur_col, rowInd, _format_float(value)))\r\n else:\r\n smlist.append('({0},{1}) {2}'.format(\r\n rowInd, cur_col, _format_float(value)))\r\n spstr += \"\\n\".join(smlist)\r\n\r\n if len(self.values) > 16:\r\n spstr += \"\\n..\" * 2\r\n return spstr\r\n\r\n def __repr__(self):\r\n \"\"\"\r\n Representation of a SparseMatrix\r\n\r\n >>> sm1 = SparseMatrix(2, 2, [0, 2, 3], [0, 1, 1], [2, 3, 4])\r\n >>> sm1\r\n SparseMatrix(2, 2, [0, 2, 3], [0, 1, 1], [2.0, 3.0, 4.0], False)\r\n \"\"\"\r\n rowIndices = list(self.rowIndices)\r\n colPtrs = list(self.colPtrs)\r\n\r\n if len(self.values) <= 16:\r\n values = _format_float_list(self.values)\r\n\r\n else:\r\n values = (\r\n _format_float_list(self.values[:8]) +\r\n [\"...\"] +\r\n _format_float_list(self.values[-8:])\r\n )\r\n rowIndices = rowIndices[:8] + [\"...\"] + rowIndices[-8:]\r\n\r\n if len(self.colPtrs) > 16:\r\n colPtrs = colPtrs[:8] + [\"...\"] + colPtrs[-8:]\r\n\r\n values = \", \".join(values)\r\n rowIndices = \", \".join([str(ind) for ind in rowIndices])\r\n colPtrs = \", \".join([str(ptr) for ptr in colPtrs])\r\n return \"SparseMatrix({0}, {1}, [{2}], [{3}], [{4}], {5})\".format(\r\n self.numRows, self.numCols, colPtrs, rowIndices,\r\n values, self.isTransposed)\r\n\r\n def __reduce__(self):\r\n return SparseMatrix, (\r\n self.numRows, self.numCols, self.colPtrs.tostring(),\r\n self.rowIndices.tostring(), self.values.tostring(),\r\n int(self.isTransposed))\r\n\r\n def __getitem__(self, indices):\r\n i, j = indices\r\n if i < 0 or i >= self.numRows:\r\n raise IndexError(\"Row index %d is out of range [0, %d)\"\r\n % (i, self.numRows))\r\n if j < 0 or j >= self.numCols:\r\n raise IndexError(\"Column index %d is out of range [0, %d)\"\r\n % (j, self.numCols))\r\n\r\n # If a CSR matrix is given, then the row index should be searched\r\n # for in ColPtrs, and the column index should be searched for in the\r\n # corresponding slice obtained from rowIndices.\r\n if self.isTransposed:\r\n j, i = i, j\r\n\r\n colStart = self.colPtrs[j]\r\n colEnd = self.colPtrs[j + 1]\r\n nz = self.rowIndices[colStart: colEnd]\r\n ind = np.searchsorted(nz, i) + colStart\r\n if ind < colEnd and self.rowIndices[ind] == i:\r\n return self.values[ind]\r\n else:\r\n return 0.0\r\n\r\n def toArray(self):\r\n \"\"\"\r\n Return an numpy.ndarray\r\n \"\"\"\r\n A = np.zeros((self.numRows, self.numCols), dtype=np.float64, order='F')\r\n for k in xrange(self.colPtrs.size - 1):\r\n startptr = self.colPtrs[k]\r\n endptr = self.colPtrs[k + 1]\r\n if self.isTransposed:\r\n A[k, self.rowIndices[startptr:endptr]] = self.values[startptr:endptr]\r\n else:\r\n A[self.rowIndices[startptr:endptr], k] = self.values[startptr:endptr]\r\n return A\r\n\r\n def toDense(self):\r\n densevals = np.ravel(self.toArray(), order='F')\r\n return DenseMatrix(self.numRows, self.numCols, densevals)\r\n\r\n def asML(self):\r\n \"\"\"\r\n Convert this matrix to the new mllib-local representation.\r\n This does NOT copy the data; it copies references.\r\n\r\n :return: :py:class:`pyspark.ml.linalg.SparseMatrix`\r\n\r\n .. versionadded:: 2.0.0\r\n \"\"\"\r\n return newlinalg.SparseMatrix(self.numRows, self.numCols, self.colPtrs, self.rowIndices,\r\n self.values, self.isTransposed)\r\n\r\n # TODO: More efficient implementation:\r\n def __eq__(self, other):\r\n return np.all(self.toArray() == other.toArray())\r\n\r\n\r\nclass Matrices(object):\r\n @staticmethod\r\n def dense(numRows, numCols, values):\r\n \"\"\"\r\n Create a DenseMatrix\r\n \"\"\"\r\n return DenseMatrix(numRows, numCols, values)\r\n\r\n @staticmethod\r\n def sparse(numRows, numCols, colPtrs, rowIndices, values):\r\n \"\"\"\r\n Create a SparseMatrix\r\n \"\"\"\r\n return SparseMatrix(numRows, numCols, colPtrs, rowIndices, values)\r\n\r\n @staticmethod\r\n def fromML(mat):\r\n \"\"\"\r\n Convert a matrix from the new mllib-local representation.\r\n This does NOT copy the data; it copies references.\r\n\r\n :param mat: a :py:class:`pyspark.ml.linalg.Matrix`\r\n :return: a :py:class:`pyspark.mllib.linalg.Matrix`\r\n\r\n .. versionadded:: 2.0.0\r\n \"\"\"\r\n if isinstance(mat, newlinalg.DenseMatrix):\r\n return DenseMatrix(mat.numRows, mat.numCols, mat.values, mat.isTransposed)\r\n elif isinstance(mat, newlinalg.SparseMatrix):\r\n return SparseMatrix(mat.numRows, mat.numCols, mat.colPtrs, mat.rowIndices,\r\n mat.values, mat.isTransposed)\r\n else:\r\n raise TypeError(\"Unsupported matrix type %s\" % type(mat))\r\n\r\n\r\nclass QRDecomposition(object):\r\n \"\"\"\r\n Represents QR factors.\r\n \"\"\"\r\n def __init__(self, Q, R):\r\n self._Q = Q\r\n self._R = R\r\n\r\n @property\r\n @since('2.0.0')\r\n def Q(self):\r\n \"\"\"\r\n An orthogonal matrix Q in a QR decomposition.\r\n May be null if not computed.\r\n \"\"\"\r\n return self._Q\r\n\r\n @property\r\n @since('2.0.0')\r\n def R(self):\r\n \"\"\"\r\n An upper triangular matrix R in a QR decomposition.\r\n \"\"\"\r\n return self._R\r\n\r\n\r\ndef _test():\r\n import doctest\r\n (failure_count, test_count) = doctest.testmod(optionflags=doctest.ELLIPSIS)\r\n if failure_count:\r\n exit(-1)\r\n\r\nif __name__ == \"__main__\":\r\n _test()\r\n"
] |
[
[
"numpy.dot",
"numpy.array_equal",
"numpy.nonzero",
"numpy.isnan",
"numpy.asarray",
"numpy.in1d",
"numpy.linalg.norm",
"numpy.frombuffer",
"numpy.bincount",
"numpy.count_nonzero",
"numpy.searchsorted",
"numpy.array",
"numpy.zeros"
]
] |
BoogalooLi/python_spiders
|
[
"7b5cd0127fd072ca8346aba4c9338d738cb7f0db"
] |
[
"bs4/bs4_combat.py"
] |
[
"from bs4 import BeautifulSoup\nimport requests\nimport pandas as pd\n\n'''\nurl = https://www.lmoneky.com/t\ncontent: titles, authors, links, times\ntool: python, requests, bs4, pandas\n'''\n# 1.url & headers\nurl = 'https://www.lmonkey.com/t'\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:71.0) Gecko/20100101 Firefox/71.0'\n}\n\n# 2.发送请求\nres = requests.get(url=url, headers=headers)\n\n# 3.判断请求是否成功,并获取请求的源代码\nif res.status_code == 200:\n soup = BeautifulSoup(res.text, 'lxml')\n # 获取文章中所有的文章\n # lists可循环\n # 4.解析数据\n lists = soup.find_all('div', class_=\"list-group-item list-group-item-action p-06\")\n title = []\n url = []\n author = []\n time = []\n for i in lists:\n # 看网页源码再进一步确定这里怎么弄,split要好好使用\n # print(i.text.split('\\n')[0])\n j = i.find('div', class_=\"topic_title\")\n if j:\n title.append(j.text.split('\\n')[0])\n url.append(i.a['href'])\n author.append(i.strong.a.text)\n time.append(i.span['title'])\n\n # 5.写入数据\n df = pd.DataFrame({\n '标题': title,\n '作者': author,\n '时间': time,\n '链接': url\n })\n data = pd.HDFStore('data.h5', 'w')\n df.to_hdf('data.h5', key='yq')\n data.close()\n\n # 读取数据\n store = pd.HDFStore('data.h5', mode='r')\n temp = pd.read_hdf('data.h5')\n print(temp)\n\n store.close()"
] |
[
[
"pandas.read_hdf",
"pandas.HDFStore",
"pandas.DataFrame"
]
] |
michaeldeistler/diffeqtorch
|
[
"e06cb276ceb4dc6b2b1684e480da08a17cc59c26"
] |
[
"diffeqtorch/diffeqtorch.py"
] |
[
"from __future__ import annotations\n\nimport os\nimport time\nfrom pathlib import Path\nfrom textwrap import dedent\nfrom typing import Any, Dict, List, Tuple, Union\nfrom warnings import warn\n\nimport torch\nfrom julia.api import Julia\nfrom opt_einsum import contract\n\nfrom diffeqtorch.logging import get_logger\n\nJULIA_PROJECT = str(Path(__file__).parent / \"julia\")\nos.environ[\"JULIA_PROJECT\"] = JULIA_PROJECT\n\n\ndef find_sysimage():\n if \"JULIA_SYSIMAGE_DIFFEQTORCH\" in os.environ:\n environ_path = Path(os.environ[\"JULIA_SYSIMAGE_DIFFEQTORCH\"])\n if environ_path.exists():\n return str(environ_path)\n else:\n warn(\"JULIA_SYSIMAGE_DIFFEQTORCH is set but image does not exist\")\n return None\n else:\n warn(\"JULIA_SYSIMAGE_DIFFEQTORCH not set\")\n default_path = Path(\"~/.julia_sysimage_diffeqtorch.so\").expanduser()\n if default_path.exists():\n warn(f\"Defaulting to {default_path}\")\n return str(default_path)\n else:\n return None\n\n\nclass DiffEq(torch.nn.Module):\n \"\"\"Solve differential equation using DifferentialEquations.jl\n\n Usage examples are provided in notebooks folder of `diffeqtorch`.\n \"\"\"\n\n def __init__(\n self,\n f: str,\n problem_type_grad: str = \"ODEForwardSensitivityProblem\",\n problem_type_no_grad: str = \"ODEProblem\",\n solver: str = \"Tsit5\",\n reltol: float = 1e-8,\n abstol: float = 1e-8,\n saveat: float = 0.1,\n using: List[str] = [\"DifferentialEquations, DiffEqSensitivity\"],\n pyjulia_opts: Dict[str, Any] = {\n \"compiled_modules\": False,\n \"sysimage\": find_sysimage(),\n \"runtime\": \"julia\",\n },\n debug: Union[bool, int] = 0,\n solve_args: Dict = {}\n ):\n \"\"\"Initialize solver module\n\n Args:\n f: Function definition in Julia, see [1] for details\n problem_type_grad: The DifferentialEquations.jl problem type used when\n gradients calculation is required, see [1] for details\n problem_type_no_grad: The DifferentialEquations.jl problem type used when\n no gradients calculation is required, see [1] for details\n solver: The solver that is used, see [1] for details\n reltol: Relative tolerance, see [1] for details\n abstol: Absolute tolerance, see [1] for details\n saveat: At which timesteps outputs are saved, see [1] for details\n using: Packages that are imported to Julia session\n pyjulia_opts: Keyword dict passed to pyjulia at initialisation, see [2]\n for details\n debug: Amount of debug info (from nothing to a lot), options are:\n - 0: No info, also used when `debug=False`\n - 1: General info including Julia commands, also used when `debug=True`\n - 2: Additionally logging PyTorch shapes\n - 3: Additionally logging PyTorch values\n - 4: Additionally turning on PyJulia debug mode\n solve_kwargs: Key value pairs passed to `solve`.\n\n [1]: https://docs.sciml.ai/stable/\n [2]: https://pyjulia.readthedocs.io/en/stable/api.html#julia.api.Julia\n \"\"\"\n super().__init__()\n\n self.opts = {\n \"problem_type_grad\": problem_type_grad,\n \"problem_type_no_grad\": problem_type_no_grad,\n \"solver\": solver,\n \"reltol\": reltol,\n \"abstol\": abstol,\n \"saveat\": saveat,\n \"using\": using,\n \"debug\": debug,\n }\n self.opts = {**self.opts, **solve_args}\n\n # Logging\n self.log = get_logger(__name__)\n self.debug = debug\n if self.debug > 0:\n self.log.debug(\"Initializing `DiffEq` with keywords:\")\n for key, value in self.opts.items():\n self.log.debug(f\" {key}: {value}\")\n\n # Start pyjulia\n if self.debug > 3:\n pyjulia_opts[\"debug\"] = True\n tic = time.time()\n self.jl = Julia(**pyjulia_opts)\n if self.debug > 0:\n self.log.debug(\n f\"\\nStarted Julia through `PyJulia`, took {time.time()-tic:.2f}sec\"\n )\n\n # Import packages\n cmd = f\"using {','.join(using)}\"\n if self.debug > 0:\n self.log.debug(f\"\\nJulia >>>\\n{cmd}\\n<<<\\n\")\n self.jl.eval(cmd)\n\n # Evalulate function definition\n cmd = f\n if self.debug > 0:\n self.log.debug(f\"\\nJulia >>>\\n{cmd}\\n<<<\\n\")\n self.jl.eval(cmd)\n\n def forward(\n self, u0: torch.Tensor, tspan: torch.Tensor, p: torch.Tensor\n ) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"Forward pass through solver\n\n Args:\n u0: Initial values as a 1d tensor\n tspan: Start and end points for integration\n p: Parameters as a 1d tensor\n\n Returns:\n Returns solutions `u` and timesteps `t`\n \"\"\"\n return DifferentialEquationsJuliaFunction.apply(\n p, u0, tspan, self.jl, self.opts\n )\n\n @property\n def debug(self):\n return self.opts[\"debug\"]\n\n @debug.setter\n def debug(self, state):\n self.opts[\"debug\"] = int(state)\n\n\nclass DifferentialEquationsJuliaFunction(torch.autograd.Function):\n \"\"\"Forward and backward pass through solver\n\n Gradients are calculated using `DiffEqSensitivity.jl`. In the backward pass,\n these gradients need to be multiplied with the incoming gradients according\n to the chain rule (see [1] for documentation of the `torch.autograd.Function`\n interface and examples). This multiplication is performed using `einsum` [2],\n where we use an optimized implementation [3] for speed.\n\n [1]: https://pytorch.org/docs/stable/notes/extending.html\n [2]: https://rockt.github.io/2018/04/30/einsum\n [3]: http://optimized-einsum.readthedocs.io\n \"\"\"\n\n @staticmethod\n def forward(ctx, p, u0, tspan, jl, opts):\n debug = opts[\"debug\"]\n if debug > 0:\n log = get_logger(__name__)\n\n if ctx.needs_input_grad[0]:\n compute_grad_p = True\n else:\n compute_grad_p = False\n\n if ctx.needs_input_grad[1]:\n raise NotImplementedError(\"Gradient w.r.t. u0 not supported\")\n\n if ctx.needs_input_grad[2]:\n raise NotImplementedError(\"Gradient w.r.t. tspan not supported\")\n\n if debug > 1:\n log.debug(f\"p.shape: {p.shape}\")\n log.debug(f\"u0.shape: {u0.shape})\")\n log.debug(f\"tspan.shape: {tspan.shape}\")\n\n if debug > 2:\n log.debug(f\"p: {p}\")\n log.debug(f\"u0: {u0})\")\n log.debug(f\"tspan: {tspan}\")\n log.debug(f\"compute_grad_p: {compute_grad_p}\")\n\n cmd = dedent(\n f\"\"\"\n u0 = {u0.tolist()}\n tspan = {tuple(tspan.tolist())}\n p = {p.tolist()}\n \"\"\"\n )\n\n if compute_grad_p:\n cmd += dedent(\n f\"\"\"\n prob = {opts['problem_type_grad']}(f,u0,tspan,p)\n\n solution = solve(prob,{opts['solver']}(),reltol={opts['reltol']},abstol={opts['abstol']},saveat={opts['saveat']}, dt={opts['dt']})\n\n u, du = extract_local_sensitivities(solution)\n\n u, du, solution.t\n \"\"\" # noqa: E501\n )\n if debug > 0:\n log.debug(f\"\\nJulia >>>\\n{cmd}\\n<<<\\n\")\n\n u, du, t = jl.eval(cmd)\n\n u = torch.tensor(u)\n du = torch.tensor(du)\n t = torch.tensor(t, requires_grad=False)\n\n if debug > 1:\n log.debug(f\"u.shape: {u.shape})\")\n log.debug(f\"du.shape: {du.shape})\")\n log.debug(f\"t.shape: {t.shape})\")\n\n if debug > 2:\n log.debug(f\"u: {u})\")\n log.debug(f\"du: {du})\")\n log.debug(f\"t: {t})\")\n\n ctx.save_for_backward(du, torch.tensor(debug))\n\n return u, t\n\n else: # No gradient computation\n cmd += dedent(\n f\"\"\"\n prob = {opts['problem_type_no_grad']}(f,u0,tspan,p)\n\n solution = solve(prob,{opts['solver']}(),reltol={opts['reltol']},abstol={opts['abstol']},saveat={opts['saveat']}, dt={opts['dt']})\n\n solution.u, solution.t\n \"\"\" # noqa: E501\n )\n if debug > 0:\n log.debug(f\"\\nJulia >>>\\n{cmd}\\n<<<\\n\")\n\n u, t = jl.eval(cmd)\n t = torch.tensor(t, requires_grad=False)\n u = torch.tensor(u).T\n\n # NOTE: The transpose on u is to ensure that shapes are\n # consistent with the case above in which gradients are computed\n # and another interface is used.\n\n if debug > 1:\n log.debug(f\"u.shape: {u.shape})\")\n log.debug(f\"t.shape: {t.shape})\")\n\n if debug > 2:\n log.debug(f\"u: {u})\")\n log.debug(f\"t: {t})\")\n\n return u, t\n\n @staticmethod\n def backward(ctx, grad_output_u, grad_output_t):\n du = ctx.saved_tensors[0]\n\n debug = ctx.saved_tensors[1].item()\n if debug > 0:\n log = get_logger(__name__)\n\n if debug > 1:\n log.debug(f\"du.shape: {du.shape})\")\n log.debug(f\"grad_output_u.shape: {grad_output_u.shape})\")\n\n if debug > 2:\n log.debug(f\"du: {du})\")\n log.debug(f\"grad_output_u: {grad_output_u})\")\n\n grad_p = contract(\"pot,ot->p\", du, grad_output_u)\n\n if debug > 1:\n log.debug(f\"grad_p.shape: {grad_p.shape})\")\n\n if debug > 2:\n log.debug(f\"grad_p: {grad_p})\")\n\n return grad_p, None, None, None, None\n"
] |
[
[
"torch.tensor"
]
] |
avbatchelor/insight-articles-project
|
[
"852b338b786cb5b9c281fcec2e378aed8d3dc617"
] |
[
"src/topic modeling/generate_graph.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jun 12 10:41:40 2018\n\n@author: Alex\n\nGenerate distance matrix and directed graph \n\n\"\"\"\n#%% Import packages \nfrom scipy.spatial.distance import pdist, squareform\nimport networkx as nx\nimport numpy as np\nimport os \nos.chdir('C:\\\\Users\\\\Alex\\\\Documents\\\\GitHub\\\\insight-articles-project\\\\src\\\\topic modeling\\\\')\nfrom topic_modeling import get_topic_word_mat_select, select_articles\nimport matplotlib.pyplot as plt\nimport pickle\nfrom collections import Counter\nimport matplotlib.pyplot as plt\nfrom sklearn.cluster import KMeans\n\n\n#%% Topic modeling \nmethod = 'nmf'\nno_topics = 50\nno_top_words = 1000 # orignallly looked at 10\nno_labels = 5\nn_grams = False\ndoc_type = 'normal'\n\n# Run model \ntopic_word_mat_select, topic_labels, doc_topic_mat, word_embedding = get_topic_word_mat_select(method, no_topics, no_top_words, no_labels, n_grams,doc_type)\n\n# \n#adf = select_articles(doc_topic_mat,no_topics,topic_labels)\n\n#%% How many docs per topic \ndoc_topic = np.argmax(doc_topic_mat,axis=1)\ndocs_per_topic = []\nfor topic_no in range(1,no_topics+1):\n docs_per_topic.append(np.count_nonzero(doc_topic == topic_no))\n \nplt.figure() \nplt.barh(range(1,no_topics+1), docs_per_topic)\nax = plt.gca()\nax.set_yticks(range(1,no_topics+1))\nax.set_yticklabels(topic_labels.values())\n#plt.tight_layout()\n\n#%% Remove topics that only have no documents associated with them \n# Find rare topics \nrare_topics = [idx for idx, value in enumerate(docs_per_topic) if value == 0]\n\n# Get list of topics numbers not including rare topics \ntopic_no_list = [x for x in range(0,no_topics) for y in rare_topics if x != y]\n\n# Remove rows from topic_word_mat_select \ntopic_word_mat_select = topic_word_mat_select[topic_no_list,:]\n\n# Remove rows from topic labels \nfor topic in rare_topics:\n del topic_labels[topic] \n\n#%% Get article info for selected topics \nselection_method = 'random'\nselect_articles(topic_no_list,doc_topic_mat,no_topics,topic_labels,word_embedding,selection_method)\n\n\n#%% Calculate distances between the rows \ndistance_method = 'old'\nif distance_method == 'old':\n dist_mat = squareform(pdist(topic_word_mat_select, metric='cosine'))\n np.fill_diagonal(dist_mat,1) #Replace in place\nelif distance_method == 'new':\n word_dist = squareform(pdist(topic_word_mat_select.T, metric='cosine'))\n \n \n\n# Find max of each row \ngraph_mat = np.zeros(dist_mat.shape)\n\n# Draw connection if distance is below some arbitrary threshold\nif method == 'lda':\n graph_mat = dist_mat < 0.5\nelse:\n graph_mat = dist_mat < 0.95\n \n'''\n# Draw connection only to nearest topic\nmax_idx = np.argmin(dist_mat,axis =1)\ncount = 0\nfor idx in max_idx: \n graph_mat[count,idx] = 1\n count +=1\n'''\n\n#%% \nnum_clusters = 8\nkmeans = KMeans(n_clusters=num_clusters, random_state=0).fit_predict(topic_word_mat_select)\nfor cluster_num in range(1,num_clusters+1):\n print('Cluster numer = ',cluster_num)\n topic_keys, = np.where(kmeans == cluster_num)\n print([topic_labels[key] for key in topic_keys])\n \n\n#%% Visualize graph \n# Code copied from: https://stackoverflow.com/questions/13513455/drawing-a-graph-or-a-network-from-a-distance-matrix\n\nplt.close()\nG = nx.from_numpy_matrix(graph_mat) \n#pos = nx.graphviz_layout(G)\n#pos = nx.nx_agraph.graphviz_layout(G)\npos=nx.spring_layout(G)\nnx.relabel_nodes(G,topic_labels)\nnx.draw(G,pos)\nnx.draw_networkx_labels(G,pos,topic_labels,font_size=16)\n\n\n\n#%% Save graph mat and labels \nprocessed_data_folder = 'C:\\\\Users\\\\Alex\\\\Documents\\\\GitHub\\\\insight-articles-project\\\\data\\\\processed\\\\'\nfilename = processed_data_folder + 'graph_and_labels'\n\nwith open(filename, 'wb') as fp:\n pickle.dump((graph_mat,topic_labels,dist_mat,doc_topic_mat), fp)\n \n#%% Save graph as a png \n'''\nfig_folder = 'C:\\\\Users\\\\Alex\\\\Documents\\\\GitHub\\\\insight-articles-project\\\\\\figures\\\\'\nfig_file = fig_folder + 'lda_graph.png'\nnx.draw(G,fig_file, format='png', prog='neato')\n\n'''\n\n#%% Dendrogram \nfrom scipy.cluster.hierarchy import ward, dendrogram\nfrom scipy.cluster.hierarchy import ward, dendrogram\nfrom scipy.cluster.hierarchy import linkage\n\nlinkage_matrix = ward(dist_mat) #define the linkage_matrix using ward clustering pre-computed distances\n#linkage_matrix = linkage(dist_mat)\n\nfig, ax = plt.subplots(figsize=(15, 20)) # set size\nax = dendrogram(linkage_matrix, orientation=\"left\", labels=list(topic_labels.values()));\n\n\n#%% Visualize lda results \n'''\npyLDAvis.enable_notebook()\npanel = pyLDAvis.sklearn.prepare(best_lda_model, data_vectorized, vectorizer, mds='tsne')\npanel\n'''"
] |
[
[
"matplotlib.pyplot.gca",
"sklearn.cluster.KMeans",
"matplotlib.pyplot.subplots",
"numpy.argmax",
"scipy.spatial.distance.pdist",
"numpy.fill_diagonal",
"matplotlib.pyplot.close",
"numpy.count_nonzero",
"numpy.zeros",
"numpy.where",
"scipy.cluster.hierarchy.ward",
"matplotlib.pyplot.figure"
]
] |
aa10402tw/tpu
|
[
"cac2ccf0176344465327bb19e47a1bede24fd039"
] |
[
"models/official/efficientnet/eff_utils.py"
] |
[
"# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Model utilities.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport json\nimport os\nimport sys\n\nfrom absl import flags\nfrom absl import logging\nimport numpy as np\nimport tensorflow.compat.v1 as tf\n\nfrom . import lars_optimizer\nfrom tensorflow.python.tpu import tpu_function # pylint:disable=g-direct-tensorflow-import\n\nFLAGS = flags.FLAGS\n\n\ndef build_learning_rate(initial_lr,\n global_step,\n steps_per_epoch=None,\n lr_decay_type='exponential',\n decay_factor=0.97,\n decay_epochs=2.4,\n total_steps=None,\n warmup_epochs=5):\n \"\"\"Build learning rate.\"\"\"\n if lr_decay_type == 'exponential':\n assert steps_per_epoch is not None\n decay_steps = steps_per_epoch * decay_epochs\n lr = tf.train.exponential_decay(\n initial_lr, global_step, decay_steps, decay_factor, staircase=True)\n elif lr_decay_type == 'cosine':\n assert total_steps is not None\n lr = 0.5 * initial_lr * (\n 1 + tf.cos(np.pi * tf.cast(global_step, tf.float32) / total_steps))\n elif lr_decay_type == 'constant':\n lr = initial_lr\n elif lr_decay_type == 'poly':\n tf.logging.info('Using poly LR schedule')\n assert steps_per_epoch is not None\n assert total_steps is not None\n warmup_steps = int(steps_per_epoch * warmup_epochs)\n min_step = tf.constant(1, dtype=tf.int64)\n decay_steps = tf.maximum(min_step, tf.subtract(global_step, warmup_steps))\n lr = tf.train.polynomial_decay(\n initial_lr,\n decay_steps,\n total_steps - warmup_steps + 1,\n end_learning_rate=0.1,\n power=2.0)\n else:\n assert False, 'Unknown lr_decay_type : %s' % lr_decay_type\n\n if warmup_epochs:\n logging.info('Learning rate warmup_epochs: %d', warmup_epochs)\n warmup_steps = int(warmup_epochs * steps_per_epoch)\n warmup_lr = (\n initial_lr * tf.cast(global_step, tf.float32) / tf.cast(\n warmup_steps, tf.float32))\n lr = tf.cond(global_step < warmup_steps, lambda: warmup_lr, lambda: lr)\n\n return lr\n\n\ndef build_optimizer(learning_rate,\n optimizer_name='rmsprop',\n decay=0.9,\n epsilon=0.001,\n momentum=0.9,\n lars_weight_decay=None,\n lars_epsilon=None):\n \"\"\"Build optimizer.\"\"\"\n if optimizer_name == 'sgd':\n logging.info('Using SGD optimizer')\n optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)\n elif optimizer_name == 'momentum':\n logging.info('Using Momentum optimizer')\n optimizer = tf.train.MomentumOptimizer(\n learning_rate=learning_rate, momentum=momentum)\n elif optimizer_name == 'rmsprop':\n logging.info('Using RMSProp optimizer')\n optimizer = tf.train.RMSPropOptimizer(learning_rate, decay, momentum,\n epsilon)\n elif optimizer_name == 'lars':\n logging.info('Using LARS optimizer')\n assert lars_weight_decay is not None, 'LARS weight decay is None.'\n assert lars_epsilon is not None, 'LARS epsilon is None.'\n optimizer = lars_optimizer.LARSOptimizer(\n learning_rate,\n momentum=momentum,\n weight_decay=lars_weight_decay,\n skip_list=['batch_normalization', 'bias', 'beta', 'gamma'],\n epsilon=lars_epsilon)\n else:\n logging.fatal('Unknown optimizer: %s', optimizer_name)\n\n return optimizer\n\n\nclass TpuBatchNormalization(tf.layers.BatchNormalization):\n # class TpuBatchNormalization(tf.layers.BatchNormalization):\n \"\"\"Cross replica batch normalization.\"\"\"\n\n def __init__(self, fused=False, **kwargs):\n if fused in (True, None):\n raise ValueError('TpuBatchNormalization does not support fused=True.')\n super(TpuBatchNormalization, self).__init__(fused=fused, **kwargs)\n\n def _cross_replica_average(self, t, num_shards_per_group):\n \"\"\"Calculates the average value of input tensor across TPU replicas.\"\"\"\n num_shards = tpu_function.get_tpu_context().number_of_shards\n group_assignment = None\n if num_shards_per_group > 1:\n if num_shards % num_shards_per_group != 0:\n raise ValueError('num_shards: %d mod shards_per_group: %d, should be 0'\n % (num_shards, num_shards_per_group))\n num_groups = num_shards // num_shards_per_group\n group_assignment = [[\n x for x in range(num_shards) if x // num_shards_per_group == y\n ] for y in range(num_groups)]\n return tf.tpu.cross_replica_sum(t, group_assignment) / tf.cast(\n num_shards_per_group, t.dtype)\n\n def _moments(self, inputs, reduction_axes, keep_dims):\n \"\"\"Compute the mean and variance: it overrides the original _moments.\"\"\"\n shard_mean, shard_variance = super(TpuBatchNormalization, self)._moments(\n inputs, reduction_axes, keep_dims=keep_dims)\n\n num_shards = tpu_function.get_tpu_context().number_of_shards or 1\n if num_shards <= 8: # Skip cross_replica for 2x2 or smaller slices.\n num_shards_per_group = 1\n else:\n num_shards_per_group = max(8, num_shards // 8)\n logging.info('TpuBatchNormalization with num_shards_per_group %s',\n num_shards_per_group)\n if num_shards_per_group > 1:\n # Compute variance using: Var[X]= E[X^2] - E[X]^2.\n shard_square_of_mean = tf.math.square(shard_mean)\n shard_mean_of_square = shard_variance + shard_square_of_mean\n group_mean = self._cross_replica_average(\n shard_mean, num_shards_per_group)\n group_mean_of_square = self._cross_replica_average(\n shard_mean_of_square, num_shards_per_group)\n group_variance = group_mean_of_square - tf.math.square(group_mean)\n return (group_mean, group_variance)\n else:\n return (shard_mean, shard_variance)\n\n\nclass BatchNormalization(tf.layers.BatchNormalization):\n \"\"\"Fixed default name of BatchNormalization to match TpuBatchNormalization.\"\"\"\n\n def __init__(self, name='tpu_batch_normalization', **kwargs):\n super(BatchNormalization, self).__init__(name=name, **kwargs)\n\n\ndef train_batch_norm(**kwargs):\n if 'optimizer' in FLAGS and FLAGS.optimizer == 'lars':\n return DistributedBatchNormalization(**kwargs)\n return TpuBatchNormalization(**kwargs)\n\n\ndef eval_batch_norm(**kwargs):\n if 'optimizer' in FLAGS and FLAGS.optimizer == 'lars':\n return DistributedBatchNormalization(**kwargs)\n return BatchNormalization(**kwargs)\n\n\nclass DistributedBatchNormalization:\n \"\"\"Distributed batch normalization used in https://arxiv.org/abs/2011.00071.\"\"\"\n\n def __init__(self, axis, momentum, epsilon):\n self.axis = axis\n self.momentum = momentum\n self.epsilon = epsilon\n\n def __call__(self, x, training, distname='batch_normalization'):\n shape = [x.shape[-1]]\n with tf.variable_scope('batch_normalization'):\n ones = tf.initializers.ones()\n zeros = tf.initializers.zeros()\n gamma = tf.get_variable(\n 'gamma', shape, initializer=ones, trainable=True, use_resource=True)\n beta = tf.get_variable(\n 'beta', shape, initializer=zeros, trainable=True, use_resource=True)\n moving_mean = tf.get_variable(\n 'moving_mean',\n shape,\n initializer=zeros,\n trainable=False,\n use_resource=True)\n moving_variance = tf.get_variable(\n 'moving_variance',\n shape,\n initializer=ones,\n trainable=False,\n use_resource=True)\n num_replicas = FLAGS.num_replicas\n\n x = tf.cast(x, tf.float32)\n if training:\n if num_replicas <= 8:\n group_assign = None\n group_shards = tf.cast(num_replicas, tf.float32)\n else:\n\n group_shards = max(\n 1,\n int(FLAGS.batch_norm_batch_size /\n (FLAGS.train_batch_size / num_replicas)))\n group_assign = np.arange(num_replicas, dtype=np.int32)\n group_assign = group_assign.reshape([-1, group_shards])\n group_assign = group_assign.tolist()\n group_shards = tf.cast(group_shards, tf.float32)\n\n mean = tf.reduce_mean(x, [0, 1, 2])\n mean = tf.tpu.cross_replica_sum(mean, group_assign) / group_shards\n\n # Var[x] = E[x^2] - E[x]^2\n mean_sq = tf.reduce_mean(tf.math.square(x), [0, 1, 2])\n mean_sq = tf.tpu.cross_replica_sum(mean_sq, group_assign) / group_shards\n variance = mean_sq - tf.math.square(mean)\n\n decay = tf.cast(1. - self.momentum, tf.float32)\n\n def u(moving, normal, name):\n num_replicas_fp = tf.cast(num_replicas, tf.float32)\n normal = tf.tpu.cross_replica_sum(normal) / num_replicas_fp\n diff = decay * (moving - normal)\n return tf.assign_sub(moving, diff, use_locking=True, name=name)\n\n tf.add_to_collection(tf.GraphKeys.UPDATE_OPS,\n u(moving_mean, mean, name='moving_mean'))\n tf.add_to_collection(tf.GraphKeys.UPDATE_OPS,\n u(moving_variance, variance, name='moving_variance'))\n\n x = tf.nn.batch_normalization(\n x,\n mean=mean,\n variance=variance,\n offset=beta,\n scale=gamma,\n variance_epsilon=self.epsilon)\n else:\n\n x, _, _ = tf.nn.fused_batch_norm(\n x,\n scale=gamma,\n offset=beta,\n mean=moving_mean,\n variance=moving_variance,\n epsilon=self.epsilon,\n is_training=False)\n\n return x\n\n\ndef drop_connect(inputs, is_training, survival_prob):\n \"\"\"Drop the entire conv with given survival probability.\"\"\"\n # \"Deep Networks with Stochastic Depth\", https://arxiv.org/pdf/1603.09382.pdf\n if not is_training:\n return inputs\n\n # Compute tensor.\n batch_size = tf.shape(inputs)[0]\n random_tensor = survival_prob\n random_tensor += tf.random_uniform([batch_size, 1, 1, 1], dtype=inputs.dtype)\n binary_tensor = tf.floor(random_tensor)\n # Unlike conventional way that multiply survival_prob at test time, here we\n # divide survival_prob at training time, such that no addition compute is\n # needed at test time.\n output = tf.div(inputs, survival_prob) * binary_tensor\n return output\n\n\ndef archive_ckpt(ckpt_eval, ckpt_objective, ckpt_path):\n \"\"\"Archive a checkpoint if the metric is better.\"\"\"\n ckpt_dir, ckpt_name = os.path.split(ckpt_path)\n\n saved_objective_path = os.path.join(ckpt_dir, 'best_objective.txt')\n saved_objective = float('-inf')\n if tf.gfile.Exists(saved_objective_path):\n with tf.gfile.GFile(saved_objective_path, 'r') as f:\n saved_objective = float(f.read())\n if saved_objective > ckpt_objective:\n logging.info('Ckpt %s is worse than %s', ckpt_objective, saved_objective)\n return False\n\n filenames = tf.gfile.Glob(ckpt_path + '.*')\n if filenames is None:\n logging.info('No files to copy for checkpoint %s', ckpt_path)\n return False\n\n # Clear the old folder.\n dst_dir = os.path.join(ckpt_dir, 'archive')\n if tf.gfile.Exists(dst_dir):\n tf.gfile.DeleteRecursively(dst_dir)\n tf.gfile.MakeDirs(dst_dir)\n\n # Write checkpoints.\n for f in filenames:\n dest = os.path.join(dst_dir, os.path.basename(f))\n tf.gfile.Copy(f, dest, overwrite=True)\n ckpt_state = tf.train.generate_checkpoint_state_proto(\n dst_dir,\n model_checkpoint_path=ckpt_name,\n all_model_checkpoint_paths=[ckpt_name])\n with tf.gfile.GFile(os.path.join(dst_dir, 'checkpoint'), 'w') as f:\n f.write(str(ckpt_state))\n with tf.gfile.GFile(os.path.join(dst_dir, 'best_eval.txt'), 'w') as f:\n f.write('%s' % ckpt_eval)\n\n # Update the best objective.\n with tf.gfile.GFile(saved_objective_path, 'w') as f:\n f.write('%f' % ckpt_objective)\n\n logging.info('Copying checkpoint %s to %s', ckpt_path, dst_dir)\n return True\n\n\ndef get_ema_vars():\n \"\"\"Get all exponential moving average (ema) variables.\"\"\"\n ema_vars = tf.trainable_variables() + tf.get_collection('moving_vars')\n for v in tf.global_variables():\n # We maintain mva for batch norm moving mean and variance as well.\n if 'moving_mean' in v.name or 'moving_variance' in v.name:\n ema_vars.append(v)\n return list(set(ema_vars))\n\n\nclass DepthwiseConv2D(tf.keras.layers.DepthwiseConv2D, tf.layers.Layer):\n \"\"\"Wrap keras DepthwiseConv2D to tf.layers.\"\"\"\n\n pass\n\n\nclass Conv2D(tf.layers.Conv2D):\n \"\"\"Wrapper for Conv2D with specialization for fast inference.\"\"\"\n\n def _bias_activation(self, outputs):\n if self.use_bias:\n outputs = tf.nn.bias_add(outputs, self.bias, data_format='NCHW')\n if self.activation is not None:\n return self.activation(outputs)\n return outputs\n\n def _can_run_fast_1x1(self, inputs):\n batch_size = inputs.shape.as_list()[0]\n return (self.data_format == 'channels_first' and\n batch_size == 1 and\n self.kernel_size == (1, 1))\n\n def _call_fast_1x1(self, inputs):\n # Compute the 1x1 convolution as a matmul.\n inputs_shape = tf.shape(inputs)\n flat_inputs = tf.reshape(inputs, [inputs_shape[1], -1])\n flat_outputs = tf.matmul(\n tf.squeeze(self.kernel),\n flat_inputs,\n transpose_a=True)\n outputs_shape = tf.concat([[1, self.filters], inputs_shape[2:]], axis=0)\n outputs = tf.reshape(flat_outputs, outputs_shape)\n\n # Handle the bias and activation function.\n return self._bias_activation(outputs)\n\n def call(self, inputs):\n if self._can_run_fast_1x1(inputs):\n return self._call_fast_1x1(inputs)\n return super(Conv2D, self).call(inputs)\n\n\nclass EvalCkptDriver(object):\n \"\"\"A driver for running eval inference.\n\n Attributes:\n model_name: str. Model name to eval.\n batch_size: int. Eval batch size.\n image_size: int. Input image size, determined by model name.\n num_classes: int. Number of classes, default to 1000 for ImageNet.\n include_background_label: whether to include extra background label.\n advprop_preprocessing: whether to use advprop preprocessing.\n \"\"\"\n\n def __init__(self,\n model_name,\n batch_size=1,\n image_size=224,\n num_classes=1000,\n include_background_label=False,\n advprop_preprocessing=False):\n \"\"\"Initialize internal variables.\"\"\"\n self.model_name = model_name\n self.batch_size = batch_size\n self.num_classes = num_classes\n self.include_background_label = include_background_label\n self.image_size = image_size\n self.advprop_preprocessing = advprop_preprocessing\n\n def restore_model(self, sess, ckpt_dir, enable_ema=True, export_ckpt=None):\n \"\"\"Restore variables from checkpoint dir.\"\"\"\n sess.run(tf.global_variables_initializer())\n checkpoint = tf.train.latest_checkpoint(ckpt_dir)\n if enable_ema:\n ema = tf.train.ExponentialMovingAverage(decay=0.0)\n ema_vars = get_ema_vars()\n var_dict = ema.variables_to_restore(ema_vars)\n ema_assign_op = ema.apply(ema_vars)\n else:\n var_dict = get_ema_vars()\n ema_assign_op = None\n\n tf.train.get_or_create_global_step()\n sess.run(tf.global_variables_initializer())\n saver = tf.train.Saver(var_dict, max_to_keep=1)\n saver.restore(sess, checkpoint)\n\n if export_ckpt:\n if ema_assign_op is not None:\n sess.run(ema_assign_op)\n saver = tf.train.Saver(max_to_keep=1, save_relative_paths=True)\n saver.save(sess, export_ckpt)\n\n def build_model(self, features, is_training):\n \"\"\"Build model with input features.\"\"\"\n del features, is_training\n raise ValueError('Must be implemented by subclasses.')\n\n def get_preprocess_fn(self):\n raise ValueError('Must be implemented by subclsses.')\n\n def build_dataset(self, filenames, labels, is_training):\n \"\"\"Build input dataset.\"\"\"\n batch_drop_remainder = False\n if 'condconv' in self.model_name and not is_training:\n # CondConv layers can only be called with known batch dimension. Thus, we\n # must drop all remaining examples that do not make up one full batch.\n # To ensure all examples are evaluated, use a batch size that evenly\n # divides the number of files.\n batch_drop_remainder = True\n num_files = len(filenames)\n if num_files % self.batch_size != 0:\n tf.logging.warn('Remaining examples in last batch are not being '\n 'evaluated.')\n filenames = tf.constant(filenames)\n labels = tf.constant(labels)\n dataset = tf.data.Dataset.from_tensor_slices((filenames, labels))\n\n def _parse_function(filename, label):\n image_string = tf.read_file(filename)\n preprocess_fn = self.get_preprocess_fn()\n image_decoded = preprocess_fn(\n image_string, is_training, image_size=self.image_size)\n image = tf.cast(image_decoded, tf.float32)\n return image, label\n\n dataset = dataset.map(_parse_function)\n dataset = dataset.batch(self.batch_size,\n drop_remainder=batch_drop_remainder)\n\n iterator = dataset.make_one_shot_iterator()\n images, labels = iterator.get_next()\n return images, labels\n\n def run_inference(self,\n ckpt_dir,\n image_files,\n labels,\n enable_ema=True,\n export_ckpt=None):\n \"\"\"Build and run inference on the target images and labels.\"\"\"\n label_offset = 1 if self.include_background_label else 0\n with tf.Graph().as_default(), tf.Session() as sess:\n images, labels = self.build_dataset(image_files, labels, False)\n probs = self.build_model(images, is_training=False)\n if isinstance(probs, tuple):\n probs = probs[0]\n\n self.restore_model(sess, ckpt_dir, enable_ema, export_ckpt)\n\n prediction_idx = []\n prediction_prob = []\n for _ in range(len(image_files) // self.batch_size):\n out_probs = sess.run(probs)\n idx = np.argsort(out_probs)[::-1]\n prediction_idx.append(idx[:5] - label_offset)\n prediction_prob.append([out_probs[pid] for pid in idx[:5]])\n\n # Return the top 5 predictions (idx and prob) for each image.\n return prediction_idx, prediction_prob\n\n def eval_example_images(self,\n ckpt_dir,\n image_files,\n labels_map_file,\n enable_ema=True,\n export_ckpt=None):\n \"\"\"Eval a list of example images.\n\n Args:\n ckpt_dir: str. Checkpoint directory path.\n image_files: List[str]. A list of image file paths.\n labels_map_file: str. The labels map file path.\n enable_ema: enable expotential moving average.\n export_ckpt: export ckpt folder.\n\n Returns:\n A tuple (pred_idx, and pred_prob), where pred_idx is the top 5 prediction\n index and pred_prob is the top 5 prediction probability.\n \"\"\"\n classes = json.loads(tf.gfile.Open(labels_map_file).read())\n pred_idx, pred_prob = self.run_inference(\n ckpt_dir, image_files, [0] * len(image_files), enable_ema, export_ckpt)\n for i in range(len(image_files)):\n print('predicted class for image {}: '.format(image_files[i]))\n for j, idx in enumerate(pred_idx[i]):\n print(' -> top_{} ({:4.2f}%): {} '.format(j, pred_prob[i][j] * 100,\n classes[str(idx)]))\n return pred_idx, pred_prob\n\n def eval_imagenet(self, ckpt_dir, imagenet_eval_glob,\n imagenet_eval_label, num_images, enable_ema, export_ckpt):\n \"\"\"Eval ImageNet images and report top1/top5 accuracy.\n\n Args:\n ckpt_dir: str. Checkpoint directory path.\n imagenet_eval_glob: str. File path glob for all eval images.\n imagenet_eval_label: str. File path for eval label.\n num_images: int. Number of images to eval: -1 means eval the whole\n dataset.\n enable_ema: enable expotential moving average.\n export_ckpt: export checkpoint folder.\n\n Returns:\n A tuple (top1, top5) for top1 and top5 accuracy.\n \"\"\"\n imagenet_val_labels = [int(i) for i in tf.gfile.GFile(imagenet_eval_label)]\n imagenet_filenames = sorted(tf.gfile.Glob(imagenet_eval_glob))\n if num_images < 0:\n num_images = len(imagenet_filenames)\n image_files = imagenet_filenames[:num_images]\n labels = imagenet_val_labels[:num_images]\n\n pred_idx, _ = self.run_inference(\n ckpt_dir, image_files, labels, enable_ema, export_ckpt)\n top1_cnt, top5_cnt = 0.0, 0.0\n for i, label in enumerate(labels):\n top1_cnt += label in pred_idx[i][:1]\n top5_cnt += label in pred_idx[i][:5]\n if i % 100 == 0:\n print('Step {}: top1_acc = {:4.2f}% top5_acc = {:4.2f}%'.format(\n i, 100 * top1_cnt / (i + 1), 100 * top5_cnt / (i + 1)))\n sys.stdout.flush()\n top1, top5 = 100 * top1_cnt / num_images, 100 * top5_cnt / num_images\n print('Final: top1_acc = {:4.2f}% top5_acc = {:4.2f}%'.format(top1, top5))\n return top1, top5\n"
] |
[
[
"tensorflow.compat.v1.assign_sub",
"tensorflow.compat.v1.concat",
"tensorflow.compat.v1.subtract",
"tensorflow.compat.v1.initializers.zeros",
"tensorflow.compat.v1.logging.warn",
"tensorflow.compat.v1.train.ExponentialMovingAverage",
"tensorflow.compat.v1.shape",
"tensorflow.compat.v1.data.Dataset.from_tensor_slices",
"tensorflow.compat.v1.gfile.GFile",
"tensorflow.compat.v1.train.Saver",
"tensorflow.compat.v1.constant",
"tensorflow.compat.v1.math.square",
"tensorflow.python.tpu.tpu_function.get_tpu_context",
"tensorflow.compat.v1.train.generate_checkpoint_state_proto",
"tensorflow.compat.v1.global_variables",
"numpy.arange",
"tensorflow.compat.v1.reshape",
"tensorflow.compat.v1.gfile.Copy",
"tensorflow.compat.v1.trainable_variables",
"tensorflow.compat.v1.train.get_or_create_global_step",
"tensorflow.compat.v1.random_uniform",
"tensorflow.compat.v1.gfile.MakeDirs",
"tensorflow.compat.v1.gfile.DeleteRecursively",
"tensorflow.compat.v1.train.GradientDescentOptimizer",
"tensorflow.compat.v1.variable_scope",
"tensorflow.compat.v1.train.polynomial_decay",
"tensorflow.compat.v1.train.RMSPropOptimizer",
"tensorflow.compat.v1.read_file",
"tensorflow.compat.v1.reduce_mean",
"tensorflow.compat.v1.div",
"tensorflow.compat.v1.get_variable",
"tensorflow.compat.v1.nn.batch_normalization",
"tensorflow.compat.v1.floor",
"tensorflow.compat.v1.train.exponential_decay",
"tensorflow.compat.v1.get_collection",
"tensorflow.compat.v1.Graph",
"tensorflow.compat.v1.cond",
"tensorflow.compat.v1.cast",
"tensorflow.compat.v1.train.latest_checkpoint",
"tensorflow.compat.v1.initializers.ones",
"tensorflow.compat.v1.nn.fused_batch_norm",
"numpy.argsort",
"tensorflow.compat.v1.gfile.Exists",
"tensorflow.compat.v1.gfile.Open",
"tensorflow.compat.v1.global_variables_initializer",
"tensorflow.compat.v1.Session",
"tensorflow.compat.v1.train.MomentumOptimizer",
"tensorflow.compat.v1.gfile.Glob",
"tensorflow.compat.v1.logging.info",
"tensorflow.compat.v1.nn.bias_add",
"tensorflow.compat.v1.squeeze",
"tensorflow.compat.v1.tpu.cross_replica_sum"
]
] |
gronki/diskvert
|
[
"459238a46fc173c9fec3ff609cd42595bbc0c858"
] |
[
"python/diskvert/col2python.py"
] |
[
"#!/usr/bin/env python\n\n# Dominik Gronkiewicz (c) 2017\n# this source is distributed under MIT License\n# [email protected]\n\nimport re\nfrom typing import Dict\n\ndef pyminiconf_dict(f):\n buf = f.read() + \"\\n\"\n d = {}\n\n # multiline strings\n rp = r'([a-zA-Z0-9\\_\\-\\:]+)(?:[ ]+|[ ]*\\=[ ]*)\\\"([^\\\"]*)\\\"\\s+'\n for k,v in re.findall(rp,buf):\n d[k] = v\n buf = re.sub(rp,'',buf)\n\n # komentarze\n buf = re.sub(r'\\#[^\\n]+','',buf)\n\n for k,v in re.findall(r'([a-zA-Z0-9\\_\\-\\:]+)(?:[ ]+|[ ]*\\=[ ]*)([\\+\\-]?[0-9]+)\\s+',buf):\n d[k] = int(v)\n for k,v in re.findall(r'([a-zA-Z0-9\\_\\-\\:]+)(?:[ ]+|[ ]*\\=[ ]*)([\\+\\-]?[0-9]+\\.[0-9]+)\\s+',buf):\n d[k] = float(v)\n for k,v in re.findall(r'([a-zA-Z0-9\\_\\-\\:]+)(?:[ ]+|[ ]*\\=[ ]*)([\\+\\-]?[0-9]+\\.?[0-9]*[eE][\\+\\-]?[0-9]+)\\s+',buf):\n d[k] = float(v)\n\n for k,v in re.findall(r'([a-zA-Z0-9\\_\\-\\:]+)(?:[ ]+|[ ]*\\=[ ]*)([yYtT]|[fFnN])\\s+',buf):\n d[k] = (v in ['T','t','Y','y'])\n\n for k,v in re.findall(r'([a-zA-Z0-9\\_\\-\\:]+)(?:[ ]+|[ ]*\\=[ ]*)([^0-9\\-\\+\\s][^\\s\\#]+)\\s+',buf):\n d[k] = v\n\n return d\n\ndef pyminiconf_str(pars: Dict): return \"\".join([\"{} {}\\n\".format(k, v) for k, v in pars.items()])\n\nclass pyminiconf(object):\n def __init__(self,f):\n d = pyminiconf_dict(f)\n for k,v in d.items():\n setattr(self, k, v)\n\n#------------------------------------------------------------------------------#\n\nDATFILE_PATTERN = re.compile(r'^(.*)\\.(dat|tar\\.gz|tgz)')\nDATSQNC_PATTERN = re.compile(r'^(.*)\\.([0-9][0-9][0-9])')\n\ndef dat2imagefn(fn, ext = 'png'):\n fn0, ex0 = re.match(DATFILE_PATTERN, fn).groups()\n return fn0 + '.' + ext\n\ndef read_dtype(f):\n from numpy import dtype\n return dtype([(s[:16].strip().lower(), s[16:].strip()) for s in f])\n\ndef readcd(fc,fd):\n from numpy import dtype,loadtxt\n dt = dtype([(s[:16].strip().lower(), s[16:].strip()) for s in fc])\n return loadtxt(fd, skiprows=2, dtype=dt)\n\ndef col2python(fn):\n m = re.match(DATFILE_PATTERN, fn)\n if m == None: raise Exception(\"It should be .tar.gz, .tgz or .dat file, got: {}.\".format(fn))\n\n base, ext = m.groups()\n \n m = re.match(DATSQNC_PATTERN, base)\n if m:\n base, nr = m.groups()\n nr = int(nr)\n fde = '.{:03d}.dat'.format(nr)\n else:\n fde = '.dat'\n\n # print base + fde\n if ext == 'tar.gz' or ext == 'tgz':\n from tarfile import open as taropen\n with taropen(fn,\"r:gz\") as tar:\n fc = tar.extractfile(base + '.col')\n fd = tar.extractfile(base + fde)\n ft = tar.extractfile(base + '.txt')\n return readcd(fc,fd), pyminiconf(ft)\n elif ext == 'dat':\n with open(base + fde,'r') as fd, \\\n open(base + '.col','r') as fc, \\\n open(base + '.txt','r') as ft:\n return readcd(fc,fd), pyminiconf(ft)\n else: raise Exception(\"I cannot read {} extension.\".format(ext))\n"
] |
[
[
"numpy.loadtxt"
]
] |
yuhaoluo/facenet
|
[
"d3a3087f52ae1a17a77a1dadb81c53911be97b4b",
"d3a3087f52ae1a17a77a1dadb81c53911be97b4b"
] |
[
"src/models/inception_resnet_v1.py",
"src/docker_code/docker_face_detect_v0.py"
] |
[
"# Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Contains the definition of the Inception Resnet V1 architecture.\nAs described in http://arxiv.org/abs/1602.07261.\n Inception-v4, Inception-ResNet and the Impact of Residual Connections\n on Learning\n Christian Szegedy, Sergey Ioffe, Vincent Vanhoucke, Alex Alemi\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\nimport tensorflow.contrib.slim as slim\n\n\n# =============================================================================\n# tf.contrib.slim.conv2d (inputs,\n# num_outputs,[卷积核个数]\n# kernel_size,[卷积核的高度,卷积核的宽度]\n# stride=1,\n# padding='SAME',\n# )\n# \n# tf.nn.conv2d(\n# input,(与上述一致)\n# filter,([卷积核的高度,卷积核的宽度,图像通道数,卷积核个数])\n# strides,\n# padding,\n# )\n# \n# =============================================================================\n# Inception-Resnet-A\ndef block35(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None):\n \"\"\"Builds the 35x35 resnet block.\"\"\"\n with tf.variable_scope(scope, 'Block35', [net], reuse=reuse):\n with tf.variable_scope('Branch_0'):\n tower_conv = slim.conv2d(net, 32, 1, scope='Conv2d_1x1')\n with tf.variable_scope('Branch_1'):\n tower_conv1_0 = slim.conv2d(net, 32, 1, scope='Conv2d_0a_1x1')\n tower_conv1_1 = slim.conv2d(tower_conv1_0, 32, 3, scope='Conv2d_0b_3x3')\n with tf.variable_scope('Branch_2'):\n tower_conv2_0 = slim.conv2d(net, 32, 1, scope='Conv2d_0a_1x1')\n tower_conv2_1 = slim.conv2d(tower_conv2_0, 32, 3, scope='Conv2d_0b_3x3')\n tower_conv2_2 = slim.conv2d(tower_conv2_1, 32, 3, scope='Conv2d_0c_3x3')\n mixed = tf.concat([tower_conv, tower_conv1_1, tower_conv2_2], 3)\n up = slim.conv2d(mixed, net.get_shape()[3], 1, normalizer_fn=None,\n activation_fn=None, scope='Conv2d_1x1')\n net += scale * up\n if activation_fn:\n net = activation_fn(net)\n return net\n\n# Inception-Resnet-B\ndef block17(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None):\n \"\"\"Builds the 17x17 resnet block.\"\"\"\n with tf.variable_scope(scope, 'Block17', [net], reuse=reuse):\n with tf.variable_scope('Branch_0'):\n tower_conv = slim.conv2d(net, 128, 1, scope='Conv2d_1x1')\n with tf.variable_scope('Branch_1'):\n tower_conv1_0 = slim.conv2d(net, 128, 1, scope='Conv2d_0a_1x1')\n tower_conv1_1 = slim.conv2d(tower_conv1_0, 128, [1, 7],\n scope='Conv2d_0b_1x7')\n tower_conv1_2 = slim.conv2d(tower_conv1_1, 128, [7, 1],\n scope='Conv2d_0c_7x1')\n mixed = tf.concat([tower_conv, tower_conv1_2], 3)\n up = slim.conv2d(mixed, net.get_shape()[3], 1, normalizer_fn=None,\n activation_fn=None, scope='Conv2d_1x1')\n net += scale * up\n if activation_fn:\n net = activation_fn(net)\n return net\n\n\n# Inception-Resnet-C\ndef block8(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None):\n \"\"\"Builds the 8x8 resnet block.\"\"\"\n with tf.variable_scope(scope, 'Block8', [net], reuse=reuse):\n with tf.variable_scope('Branch_0'):\n tower_conv = slim.conv2d(net, 192, 1, scope='Conv2d_1x1')\n with tf.variable_scope('Branch_1'):\n tower_conv1_0 = slim.conv2d(net, 192, 1, scope='Conv2d_0a_1x1')\n tower_conv1_1 = slim.conv2d(tower_conv1_0, 192, [1, 3],\n scope='Conv2d_0b_1x3')\n tower_conv1_2 = slim.conv2d(tower_conv1_1, 192, [3, 1],\n scope='Conv2d_0c_3x1')\n mixed = tf.concat([tower_conv, tower_conv1_2], 3)\n up = slim.conv2d(mixed, net.get_shape()[3], 1, normalizer_fn=None,\n activation_fn=None, scope='Conv2d_1x1')\n net += scale * up\n if activation_fn:\n net = activation_fn(net)\n return net\n \ndef reduction_a(net, k, l, m, n):\n with tf.variable_scope('Branch_0'):\n tower_conv = slim.conv2d(net, n, 3, stride=2, padding='VALID',\n scope='Conv2d_1a_3x3')\n with tf.variable_scope('Branch_1'):\n tower_conv1_0 = slim.conv2d(net, k, 1, scope='Conv2d_0a_1x1')\n tower_conv1_1 = slim.conv2d(tower_conv1_0, l, 3,\n scope='Conv2d_0b_3x3')\n tower_conv1_2 = slim.conv2d(tower_conv1_1, m, 3,\n stride=2, padding='VALID',\n scope='Conv2d_1a_3x3')\n with tf.variable_scope('Branch_2'):\n tower_pool = slim.max_pool2d(net, 3, stride=2, padding='VALID',\n scope='MaxPool_1a_3x3')\n net = tf.concat([tower_conv, tower_conv1_2, tower_pool], 3)\n return net\n\ndef reduction_b(net):\n with tf.variable_scope('Branch_0'):\n tower_conv = slim.conv2d(net, 256, 1, scope='Conv2d_0a_1x1')\n tower_conv_1 = slim.conv2d(tower_conv, 384, 3, stride=2,\n padding='VALID', scope='Conv2d_1a_3x3')\n with tf.variable_scope('Branch_1'):\n tower_conv1 = slim.conv2d(net, 256, 1, scope='Conv2d_0a_1x1')\n tower_conv1_1 = slim.conv2d(tower_conv1, 256, 3, stride=2,\n padding='VALID', scope='Conv2d_1a_3x3')\n with tf.variable_scope('Branch_2'):\n tower_conv2 = slim.conv2d(net, 256, 1, scope='Conv2d_0a_1x1')\n tower_conv2_1 = slim.conv2d(tower_conv2, 256, 3,\n scope='Conv2d_0b_3x3')\n tower_conv2_2 = slim.conv2d(tower_conv2_1, 256, 3, stride=2,\n padding='VALID', scope='Conv2d_1a_3x3')\n with tf.variable_scope('Branch_3'):\n tower_pool = slim.max_pool2d(net, 3, stride=2, padding='VALID',\n scope='MaxPool_1a_3x3')\n net = tf.concat([tower_conv_1, tower_conv1_1,\n tower_conv2_2, tower_pool], 3)\n return net\n \ndef inference(images, keep_probability, phase_train=True, \n bottleneck_layer_size=128, weight_decay=0.0, reuse=None):\n batch_norm_params = {\n # Decay for the moving averages.\n 'decay': 0.995,\n # epsilon to prevent 0s in variance.\n 'epsilon': 0.001,\n # force in-place updates of mean and variance estimates\n 'updates_collections': None,\n # Moving averages ends up in the trainable variables collection\n 'variables_collections': [ tf.GraphKeys.TRAINABLE_VARIABLES ],\n }\n \n with slim.arg_scope([slim.conv2d, slim.fully_connected],\n weights_initializer=slim.initializers.xavier_initializer(), \n weights_regularizer=slim.l2_regularizer(weight_decay),\n normalizer_fn=slim.batch_norm,\n normalizer_params=batch_norm_params):\n return inception_resnet_v1(images, is_training=phase_train,\n dropout_keep_prob=keep_probability, bottleneck_layer_size=bottleneck_layer_size, reuse=reuse)\n\n\ndef inception_resnet_v1(inputs, is_training=True,\n dropout_keep_prob=0.8,\n bottleneck_layer_size=128,\n reuse=None, \n scope='InceptionResnetV1'):\n \"\"\"Creates the Inception Resnet V1 model.\n Args:\n inputs: a 4-D tensor of size [batch_size, height, width, 3].\n num_classes: number of predicted classes.\n is_training: whether is training or not.\n dropout_keep_prob: float, the fraction to keep before final layer.\n reuse: whether or not the network and its variables should be reused. To be\n able to reuse 'scope' must be given.\n scope: Optional variable_scope.\n Returns:\n logits: the logits outputs of the model.\n end_points: the set of end_points from the inception model.\n \"\"\"\n end_points = {}\n \n with tf.variable_scope(scope, 'InceptionResnetV1', [inputs], reuse=reuse):\n with slim.arg_scope([slim.batch_norm, slim.dropout],\n is_training=is_training):\n with slim.arg_scope([slim.conv2d, slim.max_pool2d, slim.avg_pool2d],\n stride=1, padding='SAME'):\n \n # 149 x 149 x 32\n net = slim.conv2d(inputs, 32, 3, stride=2, padding='VALID',\n scope='Conv2d_1a_3x3')\n end_points['Conv2d_1a_3x3'] = net\n # 147 x 147 x 32\n net = slim.conv2d(net, 32, 3, padding='VALID',\n scope='Conv2d_2a_3x3')\n end_points['Conv2d_2a_3x3'] = net\n # 147 x 147 x 64\n net = slim.conv2d(net, 64, 3, scope='Conv2d_2b_3x3')\n end_points['Conv2d_2b_3x3'] = net\n # 73 x 73 x 64\n net = slim.max_pool2d(net, 3, stride=2, padding='VALID',\n scope='MaxPool_3a_3x3')\n end_points['MaxPool_3a_3x3'] = net\n # 73 x 73 x 80\n net = slim.conv2d(net, 80, 1, padding='VALID',\n scope='Conv2d_3b_1x1')\n end_points['Conv2d_3b_1x1'] = net\n # 71 x 71 x 192\n net = slim.conv2d(net, 192, 3, padding='VALID',\n scope='Conv2d_4a_3x3')\n end_points['Conv2d_4a_3x3'] = net\n # 35 x 35 x 256\n net = slim.conv2d(net, 256, 3, stride=2, padding='VALID',\n scope='Conv2d_4b_3x3')\n end_points['Conv2d_4b_3x3'] = net\n \n # 5 x Inception-resnet-A\n net = slim.repeat(net, 5, block35, scale=0.17)\n end_points['Mixed_5a'] = net\n \n # Reduction-A\n with tf.variable_scope('Mixed_6a'):\n net = reduction_a(net, 192, 192, 256, 384)\n end_points['Mixed_6a'] = net\n \n # 10 x Inception-Resnet-B\n net = slim.repeat(net, 10, block17, scale=0.10)\n end_points['Mixed_6b'] = net\n \n # Reduction-B\n with tf.variable_scope('Mixed_7a'):\n net = reduction_b(net)\n end_points['Mixed_7a'] = net\n \n # 5 x Inception-Resnet-C\n net = slim.repeat(net, 5, block8, scale=0.20)\n end_points['Mixed_8a'] = net\n \n net = block8(net, activation_fn=None)\n end_points['Mixed_8b'] = net\n \n with tf.variable_scope('Logits'):\n end_points['PrePool'] = net\n #pylint: disable=no-member\n net = slim.avg_pool2d(net, net.get_shape()[1:3], padding='VALID',\n scope='AvgPool_1a_8x8')\n net = slim.flatten(net)\n \n net = slim.dropout(net, dropout_keep_prob, is_training=is_training,\n scope='Dropout')\n \n end_points['PreLogitsFlatten'] = net\n \n net = slim.fully_connected(net, bottleneck_layer_size, activation_fn=None, \n scope='Bottleneck', reuse=False)\n \n return net, end_points\n",
"# MIT License\n# \n# Copyright (c) 2016 David Sandberg\n# \n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n# \n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom scipy import misc\nimport sys\nimport os\nimport argparse\nimport tensorflow as tf\nimport numpy as np\nimport align.detect_face\nimport time\nimport imageio\nimport requests\n#import skimage\nimport json\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\nminsize = 20 # minimum size of face\nthreshold = [ 0.6, 0.7, 0.7 ] # three steps's threshold\nfactor = 0.709 # scale factor\n\nai_type = 'face-detect'\nconfig_path = '/data/configure.json'\njob_path = '/data/job/job.json'\n\nlog_path = '/data/job/logs.log'\n\nlog_path = '/home/luoyuhao/Datasets/Docker/logs/logs.log'\ntest_config_path = '/home/luoyuhao/Datasets/Docker/configure.json'\ntest_job_path = '/home/luoyuhao/Datasets/Docker/job.json'\n\n\n\ndef load_mtcnn_model(args):\n print('Creating networks and loading parameters')\n with tf.Graph().as_default():\n gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=args.gpu_memory_fraction)\n sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False))\n with sess.as_default():\n start_time = time.time();\n pnet, rnet, onet = align.detect_face.create_mtcnn(sess, None)\n print('create and load mtcnn model time: ', (time.time() - start_time))\n \n return pnet,rnet,onet\n \ndef crop_face(img,bounding_boxes,margin,image_size):\n nrof_faces = bounding_boxes.shape[0]\n if nrof_faces>0:\n det = bounding_boxes[:,0:4]\n det_arr = []\n img_size = np.asarray(img.shape)[0:2]\n if nrof_faces>1:\n for i in range(nrof_faces):\n det_arr.append(np.squeeze(det[i]))\n else:\n det_arr.append(np.squeeze(det))\n \n face_res = []\n for i, det in enumerate(det_arr):\n det = np.squeeze(det)\n bb = np.zeros(4, dtype=np.int32)\n bb[0] = np.maximum(det[0]-margin/2, 0)\n bb[1] = np.maximum(det[1]-margin/2, 0)\n bb[2] = np.minimum(det[2]+margin/2, img_size[1])\n bb[3] = np.minimum(det[3]+margin/2, img_size[0])\n cropped = img[bb[1]:bb[3],bb[0]:bb[2],:]\n #scaled = skimage.transform.resize(cropped, (args.image_size, args.image_size), interp='bilinear')\n scaled = misc.imresize(cropped, (image_size, image_size), interp='bilinear')\n face_res.append(scaled)\n return face_res\n\ndef save_faces(res,output_filename):\n if(len(res)>0):\n filename_base, file_extension = os.path.splitext(output_filename)\n for i in range(len(res)):\n if (len(res)>1):\n output_filename_n = \"{}_{}{}\".format(filename_base, i, file_extension)\n else:\n output_filename_n = \"{}{}\".format(filename_base, file_extension)\n imageio.imwrite(output_filename_n, res[i])\n\ndef img_resize(img,scale):\n \n img_resize = misc.imresize(img, (int(img.shape[0]/scale), int(img.shape[1]/scale)), interp='bilinear')\n return img_resize\n\ndef detectFace(args,img,pnet,rnet,onet,output_filename=None,isDrawFace=False,isPrintTimeInfo=False):\n ## reseize img to detect\n if args.scale>1:\n img_input = img_resize(img,args.scale)\n else:\n img_input = img\n \n\n detect_time_start = time.time()\n bounding_boxes, _ = align.detect_face.detect_face(img_input, minsize, pnet, rnet, onet, threshold, factor)\n if args.scale>1:\n bounding_boxes[:,0:4] = args.scale * bounding_boxes[:,0:4]\n \n detect_time = time.time() - detect_time_start\n if isPrintTimeInfo:\n print('detect_face_time: ', detect_time) \n \n faces = crop_face(img,bounding_boxes,args.margin,args.image_size)\n \n if(output_filename is not None):\n save_time_start = time.time()\n save_faces(faces,output_filename)\n if isPrintTimeInfo:\n print('save_face_time: ', time.time() - save_time_start) \n\n \n if isDrawFace:\n draw = align.detect_face.drawBoxes(img,bounding_boxes)\n filename_base, file_extension = os.path.splitext(output_filename)\n imageio.imwrite(filename_base+'_res'+file_extension,draw)\n #print(bounding_boxes)\n return faces,bounding_boxes\n\n \n\ndef read_config(config_path):\n #TODO\n try:\n f = open(config_path,encoding='utf-8') \n json_read = f.read()\n dic = json.loads(json_read)\n f.close()\n except Exception as e:\n print(e)\n \n input_url = dic[\"input\"]\n output_url = dic['output']\n logs_info = dic['logs']\n\n return input_url,output_url,logs_info\n\ndef read_state(job_path):\n #TODO\n try:\n f = open(job_path,encoding='utf-8') \n json_read = f.read()\n dic = json.loads(json_read)\n state = dic['run']\n f.close()\n except Exception as e:\n print(e)\n \n if state == 'true':\n return True\n else:\n return False\n\ndef read_input(input_url):\n #TODO\n try:\n r = requests.get(input_url)\n res_dic = r.json() #dic\n except Exception as e:\n #errorMessage = '{}: {}'.format(input_url, e)\n print(e)\n \n if r.raise_for_status() is None:\n try:\n taskJson_dic = res_dic['taskJson']\n except Exception as e:\n print(\"no face detect job.\")\n taskJson_dic = []\n errorCode = res_dic['errorCode']\n errorMsg = res_dic['errorMsg']\n else:\n taskJson_dic = []\n errorCode = []\n errorMsg = [] \n return taskJson_dic, errorCode, errorMsg\n \ndef push_output(input_dic,output_url,faces,bounding_boxes):\n #TODO\n for i in range(len(faces)):\n save_path = '/home/luoyuhao/Datasets/Docker/saveface/'\n save_path = save_path + str(time.time())+\".png\"\n #imageio.imwrite(save_path,faces[i])\n storage = 1\n avatar = save_path\n box = bounding_boxes[i,0:4]\n location = [int(box[0]),int(box[1]),int(box[2]),int(box[3])]\n \n out_dic = {\"storage\":storage,\"avatar\":avatar,'location':str(location),\\\n \"camId\":input_dic[\"camId\"],\"capTs\":input_dic[\"capTs\"]}\n requests.post(output_url, data=out_dic)\n \n \n\ndef read_img_from_taskJson(task_dic,tsb):\n storage = task_dic['storage']\n img = []\n if storage == 1:\n img_path = task_dic['imagePath'] \n try:\n img = imageio.imread(img_path)\n except Exception as e:\n msg = 'Face-detect failed. Wrong picture format'\n write_logs(log_path,ai_type,task_dic,msg,tsb,time.time())\n img = []\n errorMessage = '{}: {}'.format(img_path, e)\n print(errorMessage)\n \n# =============================================================================\n# else if storage == '2':\n# img = []\n# else if storage == '3':\n# img = []\n# \n# =============================================================================\n return img\n\n\n\ndef write_logs(log_path,ai_type,taskJson_dic,msg,tsb,tse):\n storage = taskJson_dic['storage']\n img_path = taskJson_dic['imagePath']\n cam_id = taskJson_dic['camId']\n cap_ts = taskJson_dic['capTs']\n (filepath,tempfilename) = os.path.split(log_path)\n if not os.path.exists(filepath):\n os.mkdir(filepath)\n with open(log_path,'at') as f:\n f.write('tsb:%s\\ttype:%s\\tstorage:%d\\timagePath:%s\\tcamId:%d\\tcapTs:%d\\tmsg:%s\\ttse:%s\\n' % (tsb, ai_type,storage, img_path,\\\n cam_id,cap_ts,msg,tse))\n\n\n########################################################################################################\ndef main(args):\n\n# =============================================================================\n# output_dir = args.output_dir\n# if not os.path.exists(output_dir):\n# os.makedirs(output_dir) \n# #\n# image_path = args.image_path\n# img = imageio.imread(image_path)\n# filename = os.path.splitext(os.path.split(image_path)[1])[0]\n# output_filename = os.path.join(output_dir, filename+'.png')\n# \n# =============================================================================\n input_url,output_url,logs_info = read_config(config_path)\n pnet,rnet,onet = load_mtcnn_model(args)\n while(1):\n time.sleep(2)\n \n if read_state(job_path):\n tsb = time.time()\n taskJson_dic, errorCode, errorMsg = read_input(input_url)\n \n if len(taskJson_dic)!=4:\n continue\n \n img = read_img_from_taskJson(taskJson_dic,tsb)\n \n if len(img)>0:\n try:\n faces, bounding_boxes = detectFace(args,img,pnet,rnet,onet,None,False,True)\n if len(faces)>0:\n nums = len(faces)\n msg = 'Face-detect success. find {} faces'.format(nums)\n write_logs(log_path,ai_type,taskJson_dic,msg,tsb,time.time())\n print(\"detect face success.\")\n else:\n msg = \"Face-detect success. find 0 faces.\"\n write_logs(log_path,ai_type,taskJson_dic,msg,tsb,time.time())\n print(\"detect no face.\")\n \n push_output(taskJson_dic,output_url,faces,bounding_boxes)\n \n except Exception as e:\n msg = \"Face-detect failed. System exception\" \n write_logs(log_path,ai_type,taskJson_dic,msg,tsb,time.time())\n \n \ndef parse_arguments(argv):\n parser = argparse.ArgumentParser()\n \n parser.add_argument('image_path', type=str, help='Directory with unaligned images.')\n parser.add_argument('output_dir', type=str, help='Directory with aligned face thumbnails.')\n parser.add_argument('--image_size', type=int,\n help='Image size (height, width) in pixels.', default=160)\n parser.add_argument('--margin', type=int,\n help='Margin for the crop around the bounding box (height, width) in pixels.', default=44)\n parser.add_argument('--gpu_memory_fraction', type=float,\n help='Upper bound on the amount of GPU memory that will be used by the process.', default=1.0)\n parser.add_argument('--detect_multiple_faces', type=bool,\n help='Detect and align multiple faces per image.', default=True)\n parser.add_argument('--scale', type=int,\n help='the height and width will resize to height/scale and width/scale to detect faces.', default=2)\n return parser.parse_args(argv)\n\nif __name__ == '__main__':\n \n img_path = '/home/luoyuhao/Datasets/Align/10.jpg'\n output_dir = '/home/luoyuhao/Datasets/Align/res'\n\n args = [img_path,output_dir,'--scale','2']\n main(parse_arguments(args))\n #main(parse_arguments(sys.argv[1:]))\n \n"
] |
[
[
"tensorflow.concat",
"tensorflow.contrib.slim.dropout",
"tensorflow.contrib.slim.arg_scope",
"tensorflow.contrib.slim.max_pool2d",
"tensorflow.contrib.slim.l2_regularizer",
"tensorflow.contrib.slim.repeat",
"tensorflow.contrib.slim.initializers.xavier_initializer",
"tensorflow.contrib.slim.fully_connected",
"tensorflow.contrib.slim.flatten",
"tensorflow.contrib.slim.conv2d",
"tensorflow.variable_scope"
],
[
"scipy.misc.imresize",
"tensorflow.Graph",
"numpy.maximum",
"numpy.minimum",
"numpy.asarray",
"numpy.squeeze",
"tensorflow.ConfigProto",
"tensorflow.GPUOptions",
"numpy.zeros"
]
] |
gdlmx/DAMASK_GUI
|
[
"cf463c8e17f2754f40d3588ab8a1e55304bc4e99"
] |
[
"damask_gui/plugin/plotdat.py"
] |
[
"#Copyright (c) 2015 Mingxuan Lin\n\nfrom ..ui import *\nimport numpy as np\nfrom optparse import OptionParser\nimport re\n\n\ndef Mises(tensor , mtype='stress'):\n tensor = np.array(tensor).reshape([3,3])\n PreFact = {'stress': 3.0/2.0, 'strain': 2.0/3.0}[mtype]\n dev = tensor - np.trace(tensor)/3.0*np.eye(3)\n symdev = 0.5*(dev+dev.T)\n return np.sqrt( np.sum(symdev**2) * PreFact)\n\ndef P2S(P, F):\n F = np.array(F).reshape([3,3])\n P = np.array(P).reshape([3,3])\n return 1.0/np.linalg.det(F)*np.dot(P,F.T) # [Cauchy] = (1/det(F)) * [P].[F_transpose]\n\ndef F2Strain(F, theStretch='V', theStrain = 'ln'):\n F = np.array(F).reshape([3,3])\n def operator(stretch,strain,eigenvalues):\n return {\n 'V#ln': np.log(eigenvalues) ,\n 'U#ln': np.log(eigenvalues) ,\n 'V#Biot': ( np.ones(3,'d') - 1.0/eigenvalues ) ,\n 'U#Biot': ( eigenvalues - np.ones(3,'d') ) ,\n 'V#Green': ( np.ones(3,'d') - 1.0/eigenvalues*eigenvalues) *0.5,\n 'U#Green': ( eigenvalues*eigenvalues - np.ones(3,'d')) *0.5,\n }[stretch+'#'+strain]\n (U,S,Vh) = np.linalg.svd(F)\n R = np.dot(U,Vh)\n stretch={}\n stretch['U'] = np.dot(np.linalg.inv(R),F)\n stretch['V'] = np.dot(F,np.linalg.inv(R))\n\n for i in range(9):\n if abs(stretch[theStretch][i%3,i//3]) < 1e-12: # kill nasty noisy data\n stretch[theStretch][i%3,i//3] = 0.0\n (D,V) = np.linalg.eig(stretch[theStretch]) # eigen decomposition (of symmetric matrix)\n for i,eigval in enumerate(D):\n if eigval < 0.0: # flip negative eigenvalues\n D[i] = -D[i]\n V[:,i] = -V[:,i]\n if np.dot(V[:,i],V[:,(i+1)%3]) != 0.0: # check each vector for orthogonality\n V[:,(i+1)%3] = np.cross(V[:,(i+2)%3],V[:,i]) # correct next vector\n V[:,(i+1)%3] /= np.sqrt(np.dot(V[:,(i+1)%3],V[:,(i+1)%3].conj())) # and renormalize (hyperphobic?)\n d = operator(theStretch,theStrain,D) # operate on eigenvalues of U or V\n return np.dot(V,np.dot(np.diag(d),V.T)).real # build tensor back from eigenvalue/vector basis\n\n\ndef unpack_vec(y, k=0):\n try:\n if k==0:\n f = lambda x: x if x else 0\n y1 = map(f,y)\n elif k==1:\n y1 = [i[0] for i in y]\n elif k==2:\n y1 = [i[0][0] for i in y]\n else:\n raise ValueError()\n y1[0]**2\n return y1\n except TypeError:\n return unpack_vec(y, k+1)\n\n# positional parameters\nparser = OptionParser( usage='%prog [options] datafile', description = \"\", version = \"\")\nparser.add_option('-o', '--out', dest='outfile', metavar = 'FILE', help='name of output file')\nparser.add_option('-F', dest='field', choices = ['hist_inc','hist_itr'], default=\"hist_inc\", help='field')\nparser.add_option('-x', dest='x', choices = [\"inc\",'acc_itr'], default=\"inc\")\nparser.add_option('-y', dest='y', choices = [\"Piola--Kirchhoff stress / MPa\",'time'], default=\"Piola--Kirchhoff stress / MPa\")\n#parser.add_option('-l', dest='is_list', action = 'store_true', help='list')\n\n\nclass PlotXY(UIFilter):\n name = 'Plot x,y'\n opt_time = 1\n\n def __init__(self, *value):\n super(PlotXY, self).__init__( *value )\n self.result = {'x':[0], 'y':[0], 'xlabel':'x', 'ylabel':'y'}\n self.set_optparser(parser)\n\n def update(self, src=None):\n options = self.options\n\n a = self.input[0].result\n field = a[options[\"field\"]]\n\n # update UI\n #field_keys = a.keys()\n data_keys = field.keys()\n fId, xId, yId = [0]*3\n try:\n #fId = field_keys.index(options[\"field\"])\n xId = data_keys.index(options[\"x\"])\n yId = data_keys.index(options[\"y\"])\n except ValueError:\n pass\n\n self.update_form({ \"x\":[xId]+data_keys, 'y': [yId]+data_keys }) #\"field\":[fId]+field_keys,\n\n # set result\n oFileName=[]\n for k in ['x','y']:\n label = options[k]\n value = field[label]\n if label.lower().startswith( 'piola--kirchhoff' ) and len(value[0])==9:\n self.result[k] = [Mises( P2S(P,F) ) for P,F in zip( value, field['deformation gradient aim'] )]\n label = 'Mises(Cauchy)'\n elif label.lower().startswith( 'deformation gradient' ) and len(value[0])==9:\n self.result[k] = [Mises(F2Strain(i),'strain') for i in value]\n label = 'ln(V)'\n else:\n self.result[k] = unpack_vec(value)\n self.result[k+'label'] = label\n oFileName.append( ''.join(re.findall(r'\\w+',label)) )\n\n if options[\"outfile\"].strip():\n import json as pkl\n oFileName.append(options[\"outfile\"])\n with open('--'.join(oFileName)+'.json','w', encoding=\"utf-8\") as of:\n pkl.dump( self.result, of , sort_keys=True )\n\n self.printmsg('Figure [{0}] updated'.format('--'.join(oFileName)) , 10000)\n self.mod_time = max( self.opt_time, self.input[0].mod_time )\n\n\nif __name__ == \"__main__\":\n (options, args) = parser.parse_args()\n #m = PlotXY()\n #m.options = vars(options)\n #m.update()\n #if options[\"is_list\"]:\n # for k in a:\n # print '[{0}]'.format(k)\n # try:\n # print '\\t' + '\\n\\t'.join( a[k].keys() )\n # except AttributeError:\n # pass\n #import re\n\n"
] |
[
[
"numpy.diag",
"numpy.dot",
"numpy.linalg.svd",
"numpy.log",
"numpy.linalg.inv",
"numpy.linalg.eig",
"numpy.eye",
"numpy.trace",
"numpy.ones",
"numpy.linalg.det",
"numpy.cross",
"numpy.array",
"numpy.sum"
]
] |
JiaXiao243/PaddleClas
|
[
"38bdf3c8ff7ba7206674084443ce1ff9985b0572"
] |
[
"ppcls/data/dataloader/multilabel_dataset.py"
] |
[
"# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nimport numpy as np\nimport os\nimport cv2\n\nfrom ppcls.data.preprocess import transform\nfrom ppcls.utils import logger\n\nfrom .common_dataset import CommonDataset\n\n\nclass MultiLabelDataset(CommonDataset):\n def _load_anno(self):\n assert os.path.exists(self._cls_path)\n assert os.path.exists(self._img_root)\n self.images = []\n self.labels = []\n with open(self._cls_path) as fd:\n lines = fd.readlines()\n for l in lines:\n l = l.strip().split(\"\\t\")\n self.images.append(os.path.join(self._img_root, l[0]))\n\n labels = l[1].split(',')\n labels = [int(i) for i in labels]\n\n self.labels.append(labels)\n assert os.path.exists(self.images[-1])\n\n def __getitem__(self, idx):\n try:\n with open(self.images[idx], 'rb') as f:\n img = f.read()\n if self._transform_ops:\n img = transform(img, self._transform_ops)\n img = img.transpose((2, 0, 1))\n label = np.array(self.labels[idx]).astype(\"float32\")\n return (img, label)\n\n except Exception as ex:\n logger.error(\"Exception occured when parse line: {} with msg: {}\".\n format(self.images[idx], ex))\n rnd_idx = np.random.randint(self.__len__())\n return self.__getitem__(rnd_idx)\n"
] |
[
[
"numpy.array"
]
] |
MODAK27/tts-replica
|
[
"4fef1b2b415c23d74296196f39560f4308f91447"
] |
[
"examples_tts/tacotron2/train_tacotron2.py"
] |
[
"# -*- coding: utf-8 -*-\n# Copyright 2020 Minh Nguyen (@dathudeptrai)\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\"\"\"Train Tacotron2.\"\"\"\n\nimport argparse\nimport logging\nimport os\nimport sys\nsys.path.append(\".\")\n\nimport numpy as np\nimport tensorflow as tf\nimport yaml\n\nimport tensorflow_tts\n\nfrom tqdm import tqdm\n\nfrom tensorflow_tts.trainers import Seq2SeqBasedTrainer\nfrom examples_tts.tacotron2.tacotron_dataset import CharactorMelDataset\n\nfrom tensorflow_tts.configs.tacotron2 import Tacotron2Config\n\nfrom tensorflow_tts.models import TFTacotron2\n\nfrom tensorflow_tts.optimizers import WarmUp\nfrom tensorflow_tts.optimizers import AdamWeightDecay\n\n\nclass Tacotron2Trainer(Seq2SeqBasedTrainer):\n \"\"\"Tacotron2 Trainer class based on Seq2SeqBasedTrainer.\"\"\"\n\n def __init__(\n self, config, steps=0, epochs=0, is_mixed_precision=False,\n ):\n \"\"\"Initialize trainer.\n\n Args:\n steps (int): Initial global steps.\n epochs (int): Initial global epochs.\n config (dict): Config dict loaded from yaml format configuration file.\n is_mixed_precision (bool): Use mixed precision or not.\n\n \"\"\"\n super(Tacotron2Trainer, self).__init__(\n steps=steps,\n epochs=epochs,\n config=config,\n is_mixed_precision=is_mixed_precision,\n )\n # define metrics to aggregates data and use tf.summary logs them\n self.list_metrics_name = [\n \"stop_token_loss\",\n \"mel_loss_before\",\n \"mel_loss_after\",\n \"guided_attention_loss\",\n ]\n self.init_train_eval_metrics(self.list_metrics_name)\n self.reset_states_train()\n self.reset_states_eval()\n\n self.config = config\n\n def init_train_eval_metrics(self, list_metrics_name):\n \"\"\"Init train and eval metrics to save it to tensorboard.\"\"\"\n self.train_metrics = {}\n self.eval_metrics = {}\n for name in list_metrics_name:\n self.train_metrics.update(\n {name: tf.keras.metrics.Mean(name=\"train_\" + name, dtype=tf.float32)}\n )\n self.eval_metrics.update(\n {name: tf.keras.metrics.Mean(name=\"eval_\" + name, dtype=tf.float32)}\n )\n\n def reset_states_train(self):\n \"\"\"Reset train metrics after save it to tensorboard.\"\"\"\n for metric in self.train_metrics.keys():\n self.train_metrics[metric].reset_states()\n\n def reset_states_eval(self):\n \"\"\"Reset eval metrics after save it to tensorboard.\"\"\"\n for metric in self.eval_metrics.keys():\n self.eval_metrics[metric].reset_states()\n\n def compile(self, model, optimizer):\n super().compile(model, optimizer)\n self.binary_crossentropy = tf.keras.losses.BinaryCrossentropy(from_logits=True)\n self.mse = tf.keras.losses.MeanSquaredError()\n self.mae = tf.keras.losses.MeanAbsoluteError()\n\n # create scheduler for teacher forcing.\n self.teacher_forcing_scheduler = tf.keras.optimizers.schedules.PolynomialDecay(\n initial_learning_rate=self.config[\"start_ratio_value\"],\n decay_steps=self.config[\"schedule_decay_steps\"],\n end_learning_rate=self.config[\"end_ratio_value\"],\n cycle=True,\n name=\"teacher_forcing_scheduler\",\n )\n\n def _train_step(self, batch):\n \"\"\"Train model one step.\"\"\"\n charactor, char_length, mel, mel_length, guided_attention = batch\n self._one_step_tacotron2(\n charactor, char_length, mel, mel_length, guided_attention\n )\n\n # update counts\n self.steps += 1\n self.tqdm.update(1)\n self._check_train_finish()\n self._apply_schedule_teacher_forcing()\n\n def _apply_schedule_teacher_forcing(self):\n if self.steps >= self.config[\"start_schedule_teacher_forcing\"]:\n # change _ratio on sampler.\n self.model.decoder.sampler._ratio = self.teacher_forcing_scheduler(\n self.steps - self.config[\"start_schedule_teacher_forcing\"]\n )\n if self.steps == self.config[\"start_schedule_teacher_forcing\"]:\n logging.info(\n f\"(Steps: {self.steps}) Starting apply schedule teacher forcing.\"\n )\n\n @tf.function(experimental_relax_shapes=True)\n def _one_step_tacotron2(\n self, charactor, char_length, mel, mel_length, guided_attention\n ):\n with tf.GradientTape() as tape:\n (\n mel_outputs,\n post_mel_outputs,\n stop_outputs,\n alignment_historys,\n ) = self.model(\n charactor,\n char_length,\n speaker_ids=tf.zeros(shape=[tf.shape(charactor)[0]]),\n mel_outputs=mel,\n mel_lengths=mel_length,\n training=True,\n )\n\n # calculate mel loss.\n mel_loss_before = self.mae(mel, mel_outputs)\n mel_loss_after = self.mae(mel, post_mel_outputs)\n\n # calculate stop grounth truth based-on mel_length.\n max_mel_length = (\n tf.reduce_max(mel_length)\n if self.config[\"use_fixed_shapes\"] is False\n else [self.config[\"max_mel_length\"]]\n )\n stop_gts = tf.expand_dims(\n tf.range(tf.reduce_max(max_mel_length), dtype=tf.int32), 0\n ) # [1, max_len]\n stop_gts = tf.tile(stop_gts, [tf.shape(mel_length)[0], 1]) # [B, max_len]\n stop_gts = tf.cast(\n tf.math.greater_equal(stop_gts, tf.expand_dims(mel_length, 1)),\n tf.float32,\n )\n\n stop_token_loss = self.binary_crossentropy(stop_gts, stop_outputs)\n\n # calculate guided attention loss.\n attention_masks = tf.cast(\n tf.math.not_equal(guided_attention, -1.0), tf.float32\n )\n loss_att = tf.reduce_sum(\n tf.abs(alignment_historys * guided_attention) * attention_masks\n )\n loss_att /= tf.reduce_sum(attention_masks)\n\n # sum all loss\n loss = stop_token_loss + mel_loss_before + mel_loss_after + loss_att\n\n if self.is_mixed_precision:\n scaled_loss = self.optimizer.get_scaled_loss(loss)\n\n if self.is_mixed_precision:\n scaled_gradients = tape.gradient(\n scaled_loss, self.model.trainable_variables\n )\n gradients = self.optimizer.get_unscaled_gradients(scaled_gradients)\n else:\n gradients = tape.gradient(loss, self.model.trainable_variables)\n self.optimizer.apply_gradients(\n zip(gradients, self.model.trainable_variables), 5.0\n )\n\n # accumulate loss into metrics\n self.train_metrics[\"stop_token_loss\"].update_state(stop_token_loss)\n self.train_metrics[\"mel_loss_before\"].update_state(mel_loss_before)\n self.train_metrics[\"mel_loss_after\"].update_state(mel_loss_after)\n self.train_metrics[\"guided_attention_loss\"].update_state(loss_att)\n\n def _eval_epoch(self):\n \"\"\"Evaluate model one epoch.\"\"\"\n logging.info(f\"(Steps: {self.steps}) Start evaluation.\")\n\n # set traing = False on decoder_cell\n self.model.decoder.cell.training = False\n\n # calculate loss for each batch\n for eval_steps_per_epoch, batch in enumerate(\n tqdm(self.eval_data_loader, desc=\"[eval]\"), 1\n ):\n # eval one step\n charactor, char_length, mel, mel_length, guided_attention = batch\n self._eval_step(charactor, char_length, mel, mel_length, guided_attention)\n\n if eval_steps_per_epoch <= self.config[\"num_save_intermediate_results\"]:\n # save intermedia\n self.generate_and_save_intermediate_result(batch)\n\n logging.info(\n f\"(Steps: {self.steps}) Finished evaluation \"\n f\"({eval_steps_per_epoch} steps per epoch).\"\n )\n\n # average loss\n for key in self.eval_metrics.keys():\n logging.info(\n f\"(Steps: {self.steps}) eval_{key} = {self.eval_metrics[key].result():.4f}.\"\n )\n\n # record\n self._write_to_tensorboard(self.eval_metrics, stage=\"eval\")\n\n # reset\n self.reset_states_eval()\n\n # enable training = True on decoder_cell\n self.model.decoder.cell.training = True\n\n @tf.function(experimental_relax_shapes=True)\n def _eval_step(self, charactor, char_length, mel, mel_length, guided_attention):\n \"\"\"Evaluate model one step.\"\"\"\n mel_outputs, post_mel_outputs, stop_outputs, alignment_historys = self.model(\n charactor,\n char_length,\n speaker_ids=tf.zeros(shape=[tf.shape(charactor)[0]]),\n mel_outputs=mel,\n mel_lengths=mel_length,\n training=False,\n )\n\n # calculate mel loss.\n mel_loss_before = self.mae(mel, mel_outputs)\n mel_loss_after = self.mae(mel, post_mel_outputs)\n\n # calculate stop grounth truth based-on mel_length.\n stop_gts = tf.expand_dims(\n tf.range(tf.reduce_max(mel_length), dtype=tf.int32), 0\n ) # [1, max_len]\n stop_gts = tf.tile(stop_gts, [tf.shape(mel_length)[0], 1]) # [B, max_len]\n stop_gts = tf.cast(\n tf.math.greater_equal(stop_gts, tf.expand_dims(mel_length, 1)), tf.float32\n )\n\n stop_token_loss = self.binary_crossentropy(stop_gts, stop_outputs)\n\n # calculate guided attention loss.\n attention_masks = tf.cast(tf.math.not_equal(guided_attention, -1.0), tf.float32)\n loss_att = tf.reduce_sum(\n tf.abs(alignment_historys * guided_attention) * attention_masks\n )\n loss_att /= tf.reduce_sum(attention_masks)\n\n # accumulate loss into metrics\n self.eval_metrics[\"stop_token_loss\"].update_state(stop_token_loss)\n self.eval_metrics[\"mel_loss_before\"].update_state(mel_loss_before)\n self.eval_metrics[\"mel_loss_after\"].update_state(mel_loss_after)\n self.eval_metrics[\"guided_attention_loss\"].update_state(loss_att)\n\n def _check_log_interval(self):\n \"\"\"Log to tensorboard.\"\"\"\n if self.steps % self.config[\"log_interval_steps\"] == 0:\n for metric_name in self.list_metrics_name:\n logging.info(\n f\"(Step: {self.steps}) train_{metric_name} = {self.train_metrics[metric_name].result():.4f}.\"\n )\n self._write_to_tensorboard(self.train_metrics, stage=\"train\")\n\n # reset\n self.reset_states_train()\n\n @tf.function(experimental_relax_shapes=True)\n def predict(self, charactor, char_length, mel, mel_length):\n \"\"\"Predict.\"\"\"\n mel_outputs, post_mel_outputs, _, alignment = self.model(\n charactor,\n char_length,\n speaker_ids=tf.zeros(shape=[tf.shape(charactor)[0]]),\n mel_outputs=mel,\n mel_lengths=mel_length,\n training=False,\n )\n return mel_outputs, post_mel_outputs, alignment\n\n def generate_and_save_intermediate_result(self, batch):\n \"\"\"Generate and save intermediate result.\"\"\"\n import matplotlib.pyplot as plt\n\n # unpack input.\n charactor, char_length, mel, mel_length, _ = batch\n\n # predict with tf.function for faster.\n masked_mel_before, masked_mel_after, alignments = self.predict(\n charactor, char_length, mel, mel_length\n )\n\n # check directory\n dirname = os.path.join(self.config[\"outdir\"], f\"predictions/{self.steps}steps\")\n if not os.path.exists(dirname):\n os.makedirs(dirname)\n\n for idx, (mel_gt, mel_pred_before, mel_pred_after, alignment) in enumerate(\n zip(mel, masked_mel_before, masked_mel_after, alignments), 1\n ):\n mel_gt = tf.reshape(mel_gt, (-1, 80)).numpy() # [length, 80]\n mel_pred_before = tf.reshape(\n mel_pred_before, (-1, 80)\n ).numpy() # [length, 80]\n mel_pred_after = tf.reshape(\n mel_pred_after, (-1, 80)\n ).numpy() # [length, 80]\n\n # plot figure and save it\n figname = os.path.join(dirname, f\"{idx}.png\")\n fig = plt.figure(figsize=(10, 8))\n ax1 = fig.add_subplot(311)\n ax2 = fig.add_subplot(312)\n ax3 = fig.add_subplot(313)\n im = ax1.imshow(np.rot90(mel_gt), aspect=\"auto\", interpolation=\"none\")\n ax1.set_title(\"Target Mel-Spectrogram\")\n fig.colorbar(mappable=im, shrink=0.65, orientation=\"horizontal\", ax=ax1)\n ax2.set_title(f\"Predicted Mel-before-Spectrogram @ {self.steps} steps\")\n im = ax2.imshow(\n np.rot90(mel_pred_before), aspect=\"auto\", interpolation=\"none\"\n )\n fig.colorbar(mappable=im, shrink=0.65, orientation=\"horizontal\", ax=ax2)\n ax3.set_title(f\"Predicted Mel-after-Spectrogram @ {self.steps} steps\")\n im = ax3.imshow(\n np.rot90(mel_pred_after), aspect=\"auto\", interpolation=\"none\"\n )\n fig.colorbar(mappable=im, shrink=0.65, orientation=\"horizontal\", ax=ax3)\n plt.tight_layout()\n plt.savefig(figname)\n plt.close()\n\n # plot alignment\n figname = os.path.join(dirname, f\"{idx}_alignment.png\")\n fig = plt.figure(figsize=(8, 6))\n ax = fig.add_subplot(111)\n ax.set_title(f\"Alignment @ {self.steps} steps\")\n im = ax.imshow(\n alignment, aspect=\"auto\", origin=\"lower\", interpolation=\"none\"\n )\n fig.colorbar(im, ax=ax)\n xlabel = \"Decoder timestep\"\n plt.xlabel(xlabel)\n plt.ylabel(\"Encoder timestep\")\n plt.tight_layout()\n plt.savefig(figname)\n plt.close()\n\n def _check_train_finish(self):\n \"\"\"Check training finished.\"\"\"\n if self.steps >= self.config[\"train_max_steps\"]:\n self.finish_train = True\n\n def fit(self, train_dataset, valid_dataset, saved_path, resume=None):\n self.set_train_data_loader(train_dataset)\n self.set_eval_data_loader(valid_dataset)\n self.create_checkpoint_manager(saved_path=saved_path, max_to_keep=10000)\n if len(resume) > 2:\n self.load_checkpoint(resume)\n logging.info(f\"Successfully resumed from {resume}.\")\n self.run()\n\n\ndef main():\n \"\"\"Run training process.\"\"\"\n parser = argparse.ArgumentParser(\n description=\"Train FastSpeech (See detail in tensorflow_tts/bin/train-fastspeech.py)\"\n )\n parser.add_argument(\n \"--train-dir\",\n default=None,\n type=str,\n help=\"directory including training data. \",\n )\n parser.add_argument(\n \"--dev-dir\",\n default=None,\n type=str,\n help=\"directory including development data. \",\n )\n parser.add_argument(\n \"--use-norm\", default=1, type=int, help=\"usr norm-mels for train or raw.\"\n )\n parser.add_argument(\n \"--outdir\", type=str, required=True, help=\"directory to save checkpoints.\"\n )\n parser.add_argument(\n \"--config\", type=str, required=True, help=\"yaml format configuration file.\"\n )\n parser.add_argument(\n \"--resume\",\n default=\"\",\n type=str,\n nargs=\"?\",\n help='checkpoint file path to resume training. (default=\"\")',\n )\n parser.add_argument(\n \"--verbose\",\n type=int,\n default=1,\n help=\"logging level. higher is more logging. (default=1)\",\n )\n parser.add_argument(\n \"--mixed_precision\",\n default=0,\n type=int,\n help=\"using mixed precision for generator or not.\",\n )\n args = parser.parse_args()\n\n # set mixed precision config\n if args.mixed_precision == 1:\n tf.config.optimizer.set_experimental_options({\"auto_mixed_precision\": True})\n\n args.mixed_precision = bool(args.mixed_precision)\n args.use_norm = bool(args.use_norm)\n\n # set logger\n if args.verbose > 1:\n logging.basicConfig(\n level=logging.DEBUG,\n stream=sys.stdout,\n format=\"%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s\",\n )\n elif args.verbose > 0:\n logging.basicConfig(\n level=logging.INFO,\n stream=sys.stdout,\n format=\"%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s\",\n )\n else:\n logging.basicConfig(\n level=logging.WARN,\n stream=sys.stdout,\n format=\"%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s\",\n )\n logging.warning(\"Skip DEBUG/INFO messages\")\n\n # check directory existence\n if not os.path.exists(args.outdir):\n os.makedirs(args.outdir)\n\n # check arguments\n if args.train_dir is None:\n raise ValueError(\"Please specify --train-dir\")\n if args.dev_dir is None:\n raise ValueError(\"Please specify --valid-dir\")\n\n # load and save config\n with open(args.config) as f:\n config = yaml.load(f, Loader=yaml.Loader)\n config.update(vars(args))\n config[\"version\"] = tensorflow_tts.__version__\n\n # get dataset\n if config[\"remove_short_samples\"]:\n mel_length_threshold = config[\"mel_length_threshold\"]\n else:\n mel_length_threshold = None\n\n if config[\"format\"] == \"npy\":\n charactor_query = \"*-ids.npy\"\n mel_query = \"*-raw-feats.npy\" if args.use_norm is False else \"*-norm-feats.npy\"\n charactor_load_fn = np.load\n mel_load_fn = np.load\n else:\n raise ValueError(\"Only npy are supported.\")\n\n train_dataset = CharactorMelDataset(\n root_dir=args.train_dir,\n charactor_query=charactor_query,\n mel_query=mel_query,\n charactor_load_fn=charactor_load_fn,\n mel_load_fn=mel_load_fn,\n mel_length_threshold=mel_length_threshold,\n return_utt_id=False,\n reduction_factor=config[\"tacotron2_params\"][\"reduction_factor\"],\n use_fixed_shapes=config[\"use_fixed_shapes\"],\n )\n\n # update max_mel_length and max_char_length to config\n config.update({\"max_mel_length\": int(train_dataset.max_mel_length)})\n config.update({\"max_char_length\": int(train_dataset.max_char_length)})\n\n with open(os.path.join(args.outdir, \"config.yml\"), \"w\") as f:\n yaml.dump(config, f, Dumper=yaml.Dumper)\n for key, value in config.items():\n logging.info(f\"{key} = {value}\")\n\n train_dataset = train_dataset.create(\n is_shuffle=config[\"is_shuffle\"],\n allow_cache=config[\"allow_cache\"],\n batch_size=config[\"batch_size\"],\n )\n\n valid_dataset = CharactorMelDataset(\n root_dir=args.dev_dir,\n charactor_query=charactor_query,\n mel_query=mel_query,\n charactor_load_fn=charactor_load_fn,\n mel_load_fn=mel_load_fn,\n mel_length_threshold=mel_length_threshold,\n return_utt_id=False,\n reduction_factor=config[\"tacotron2_params\"][\"reduction_factor\"],\n use_fixed_shapes=False, # don't need apply fixed shape for evaluation.\n ).create(\n is_shuffle=config[\"is_shuffle\"],\n allow_cache=config[\"allow_cache\"],\n batch_size=config[\"batch_size\"],\n )\n\n tacotron_config = Tacotron2Config(**config[\"tacotron2_params\"])\n tacotron2 = TFTacotron2(config=tacotron_config, training=True, name=\"tacotron2\")\n tacotron2._build()\n tacotron2.summary()\n\n # define trainer\n trainer = Tacotron2Trainer(\n config=config, steps=0, epochs=0, is_mixed_precision=args.mixed_precision\n )\n\n # AdamW for tacotron2\n learning_rate_fn = tf.keras.optimizers.schedules.PolynomialDecay(\n initial_learning_rate=config[\"optimizer_params\"][\"initial_learning_rate\"],\n decay_steps=config[\"optimizer_params\"][\"decay_steps\"],\n end_learning_rate=config[\"optimizer_params\"][\"end_learning_rate\"],\n )\n\n learning_rate_fn = WarmUp(\n initial_learning_rate=config[\"optimizer_params\"][\"initial_learning_rate\"],\n decay_schedule_fn=learning_rate_fn,\n warmup_steps=int(\n config[\"train_max_steps\"] * config[\"optimizer_params\"][\"warmup_proportion\"]\n ),\n )\n\n optimizer = AdamWeightDecay(\n learning_rate=learning_rate_fn,\n weight_decay_rate=config[\"optimizer_params\"][\"weight_decay\"],\n beta_1=0.9,\n beta_2=0.98,\n epsilon=1e-6,\n exclude_from_weight_decay=[\"LayerNorm\", \"layer_norm\", \"bias\"],\n )\n\n # compile trainer\n trainer.compile(model=tacotron2, optimizer=optimizer)\n\n # start training\n try:\n trainer.fit(\n train_dataset,\n valid_dataset,\n saved_path=os.path.join(config[\"outdir\"], \"checkpoints/\"),\n resume=args.resume,\n )\n except KeyboardInterrupt:\n trainer.save_checkpoint()\n logging.info(f\"Successfully saved checkpoint @ {trainer.steps}steps.\")\n\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"tensorflow.reduce_sum",
"tensorflow.math.not_equal",
"tensorflow.keras.losses.MeanAbsoluteError",
"matplotlib.pyplot.tight_layout",
"tensorflow.keras.losses.BinaryCrossentropy",
"matplotlib.pyplot.close",
"tensorflow.keras.metrics.Mean",
"matplotlib.pyplot.figure",
"numpy.rot90",
"tensorflow.keras.optimizers.schedules.PolynomialDecay",
"tensorflow.shape",
"tensorflow.keras.losses.MeanSquaredError",
"matplotlib.pyplot.savefig",
"tensorflow.function",
"tensorflow.config.optimizer.set_experimental_options",
"tensorflow.GradientTape",
"matplotlib.pyplot.ylabel",
"tensorflow.reduce_max",
"tensorflow.reshape",
"tensorflow.expand_dims",
"matplotlib.pyplot.xlabel",
"tensorflow.abs"
]
] |
axel-sirota/flambe
|
[
"0dc2f5b2b286694defe8abf450fe5be9ae12c097"
] |
[
"flambe/nn/rnn.py"
] |
[
"from typing import Optional, Tuple, cast\nimport warnings\nimport logging\n\nimport torch\nfrom torch import nn\nfrom torch import Tensor\n\nfrom flambe.nn.module import Module\n\nlogger = logging.getLogger(__name__)\n\n\nclass RNNEncoder(Module):\n \"\"\"Implements a multi-layer RNN.\n\n This module can be used to create multi-layer RNN models, and\n provides a way to reduce to output of the RNN to a single hidden\n state by pooling the encoder states either by taking the maximum,\n average, or by taking the last hidden state before padding.\n\n Padding is delt with by using torch's PackedSequence.\n\n Attributes\n ----------\n rnn: nn.Module\n The rnn submodule\n\n \"\"\"\n def __init__(self,\n input_size: int,\n hidden_size: int,\n n_layers: int = 1,\n rnn_type: str = 'lstm',\n dropout: float = 0,\n bidirectional: bool = False,\n layer_norm: bool = False,\n highway_bias: float = 0,\n rescale: bool = True,\n enforce_sorted: bool = False,\n **kwargs) -> None:\n \"\"\"Initializes the RNNEncoder object.\n\n Parameters\n ----------\n input_size : int\n The dimension the input data\n hidden_size : int\n The hidden dimension to encode the data in\n n_layers : int, optional\n The number of rnn layers, defaults to 1\n rnn_type : str, optional\n The type of rnn cell, one of: `lstm`, `gru`, `sru`\n defaults to `lstm`\n dropout : float, optional\n Amount of dropout to use between RNN layers, defaults to 0\n bidirectional : bool, optional\n Set to use a bidrectional encoder, defaults to False\n layer_norm : bool, optional\n [SRU only] whether to use layer norm\n highway_bias : float, optional\n [SRU only] value to use for the highway bias\n rescale : bool, optional\n [SRU only] whether to use rescaling\n enforce_sorted: bool\n Whether rnn should enforce that sequences are ordered by\n length. Requires True for ONNX support. Defaults to False.\n kwargs\n Additional parameters to be passed to SRU when building\n the rnn.\n\n Raises\n ------\n ValueError\n The rnn type should be one of: `lstm`, `gru`, `sru`\n\n \"\"\"\n super().__init__()\n\n self.rnn_type = rnn_type\n self.input_size = input_size\n self.hidden_size = hidden_size\n self.enforce_sorted = enforce_sorted\n if rnn_type in ['lstm', 'gru']:\n if kwargs:\n logger.warn(f\"The following '{kwargs}' will be ignored \" +\n \"as they are only considered when using 'sru' as \" +\n \"'rnn_type'\")\n\n rnn_fn = nn.LSTM if rnn_type == 'lstm' else nn.GRU\n self.rnn = rnn_fn(input_size=input_size,\n hidden_size=hidden_size,\n num_layers=n_layers,\n dropout=dropout,\n bidirectional=bidirectional)\n elif rnn_type == 'sru':\n from sru import SRU\n try:\n self.rnn = SRU(input_size,\n hidden_size,\n num_layers=n_layers,\n dropout=dropout,\n bidirectional=bidirectional,\n layer_norm=layer_norm,\n rescale=rescale,\n highway_bias=highway_bias,\n **kwargs)\n except TypeError:\n raise ValueError(f\"Unkown kwargs passed to SRU: {kwargs}\")\n else:\n raise ValueError(f\"Unkown rnn type: {rnn_type}, use of of: gru, sru, lstm\")\n\n def forward(self,\n data: Tensor,\n state: Optional[Tensor] = None,\n padding_mask: Optional[Tensor] = None) -> Tuple[Tensor, Tensor]:\n \"\"\"Performs a forward pass through the network.\n\n Parameters\n ----------\n data : Tensor\n The input data, as a float tensor of shape [B x S x E]\n state: Tensor\n An optional previous state of shape [L x B x H]\n padding_mask: Tensor, optional\n The padding mask of shape [B x S]\n\n Returns\n -------\n Tensor\n The encoded output, as a float tensor of shape [B x S x H]\n Tensor\n The encoded state, as a float tensor of shape [L x B x H]\n\n \"\"\"\n data = data.transpose(0, 1)\n if padding_mask is not None:\n padding_mask = padding_mask.transpose(0, 1)\n\n if padding_mask is None:\n # Default RNN behavior\n output, state = self.rnn(data, state)\n elif self.rnn_type == 'sru':\n # SRU takes a mask instead of PackedSequence objects\n # Write (1 - mask_t) in weird way for type checking to work\n output, state = self.rnn(data, state, mask_pad=(-padding_mask + 1).byte())\n else:\n # Deal with variable length sequences\n lengths = padding_mask.long().sum(dim=0)\n # Pass through the RNN\n packed = nn.utils.rnn.pack_padded_sequence(data, lengths,\n enforce_sorted=self.enforce_sorted)\n output, state = self.rnn(packed, state)\n output, _ = nn.utils.rnn.pad_packed_sequence(output)\n\n # TODO investigate why PyTorch returns type Any for output\n return output.transpose(0, 1).contiguous(), state # type: ignore\n\n\nclass PooledRNNEncoder(Module):\n \"\"\"Implement an RNNEncoder with additional pooling.\n\n This class can be used to obtan a single encoded output for\n an input sequence. It also ignores the state of the RNN.\n\n \"\"\"\n\n def __init__(self,\n input_size: int,\n hidden_size: int,\n n_layers: int = 1,\n rnn_type: str = 'lstm',\n dropout: float = 0,\n bidirectional: bool = False,\n layer_norm: bool = False,\n highway_bias: float = 0,\n rescale: bool = True,\n pooling: str = 'last') -> None:\n \"\"\"Initializes the PooledRNNEncoder object.\n\n Parameters\n ----------\n input_size : int\n The dimension the input data\n hidden_size : int\n The hidden dimension to encode the data in\n n_layers : int, optional\n The number of rnn layers, defaults to 1\n rnn_type : str, optional\n The type of rnn cell, one of: `lstm`, `gru`, `sru`\n defaults to `lstm`\n dropout : float, optional\n Amount of dropout to use between RNN layers, defaults to 0\n bidirectional : bool, optional\n Set to use a bidrectional encoder, defaults to False\n layer_norm : bool, optional\n [SRU only] whether to use layer norm\n highway_bias : float, optional\n [SRU only] value to use for the highway bias\n rescale : bool, optional\n [SRU only] whether to use rescaling\n pooling : Optional[str], optional\n If given, the output is pooled into a single hidden state,\n through the given pooling routine. Should be one of:\n \"first\", last\", \"average\", or \"sum\". Defaults to \"last\"\n\n Raises\n ------\n ValueError\n The rnn type should be one of: `lstm`, `gru`, `sru`\n\n \"\"\"\n super().__init__()\n\n warnings.warn(\"PooledRNNEncoder is deprecated, please use the Pooling \\\n module in the Embedder object\", DeprecationWarning)\n\n self.pooling = pooling\n self.rnn = RNNEncoder(input_size=input_size,\n hidden_size=hidden_size,\n n_layers=n_layers,\n rnn_type=rnn_type,\n dropout=dropout,\n bidirectional=bidirectional,\n layer_norm=layer_norm,\n highway_bias=highway_bias,\n rescale=rescale)\n\n def forward(self,\n data: Tensor,\n state: Optional[Tensor] = None,\n padding_mask: Optional[Tensor] = None) -> Tensor:\n \"\"\"Perform a forward pass through the network.\n\n Parameters\n ----------\n data : torch.Tensor\n The input data, as a float tensor of shape [B x S x E]\n state: Tensor\n An optional previous state of shape [L x B x H]\n padding_mask: Tensor, optional\n The padding mask of shape [B x S]\n\n Returns\n -------\n torch.Tensor\n The encoded output, as a float tensor of shape [B x H]\n\n \"\"\"\n output, _ = self.rnn(data, state=state, padding_mask=padding_mask)\n\n # Apply pooling\n if padding_mask is None:\n padding_mask = torch.ones_like(output)\n\n cast(torch.Tensor, padding_mask)\n if self.pooling == 'average':\n output = (output * padding_mask.unsqueeze(2)).sum(dim=1)\n output = output / padding_mask.sum(dim=1)\n elif self.pooling == 'sum':\n output = (output * padding_mask.unsqueeze(2)).sum(dim=1)\n elif self.pooling == 'last':\n lengths = padding_mask.long().sum(dim=1)\n output = output[torch.arange(output.size(0)).long(), lengths - 1, :]\n elif self.pooling == 'first':\n output = output[torch.arange(output.size(0)).long(), 0, :]\n else:\n raise ValueError(f\"Invalid pooling type: {self.pooling}\")\n\n return output\n"
] |
[
[
"torch.nn.utils.rnn.pad_packed_sequence",
"torch.ones_like",
"torch.nn.utils.rnn.pack_padded_sequence"
]
] |
WanMotion/recogNum-Pytorch
|
[
"2ffbad9f1a9f2d9ca0a22d4631bfda2be0319aca"
] |
[
"config.py"
] |
[
"from torch import nn\n\n# 设定基本参数\ninputDimension = 28 * 28 # 输入层\nhiddenDimension = 100 # 隐藏层\noutputDimension = 10 # 输出层\nepoch = 3000\nbatchSize = 64\nlearningRate = 0.001\nTEST_SIZE = 100 # 测试集大小\nTRAIN_SIZE = 2000 # 训练集大小\nloss = nn.MSELoss(size_average=False, reduce=True) # 损失函数\n\n# 输出位置\noutputDir = \"output\" # 训练结果输出位置\ncheckpointOutOutDir = \"output/checkpoint\" # 检查点输出位置\ncheckpointPath = \"\" # 为空时,表示不从断点继续训练\n\n# 测试集所用参数位置\ntestAgsPthPath = \"output/1630248264_epoch_3000.pth\"\n"
] |
[
[
"torch.nn.MSELoss"
]
] |
StatNLP/ada4asr
|
[
"3f40fac990afa471153ff6a8a450dfce9712b962"
] |
[
"examples/speech_to_text/data_utils.py"
] |
[
"#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport csv\nimport os\nimport os.path as op\nimport zipfile\nfrom functools import reduce\nfrom glob import glob\nfrom multiprocessing import cpu_count\nfrom typing import Any, Dict, List\n\nimport numpy as np\nimport pandas as pd\nimport sentencepiece as sp\nfrom fairseq.data.audio.audio_utils import _get_kaldi_fbank, _get_torchaudio_fbank\nfrom fairseq.data.audio.feature_transforms.utterance_cmvn import UtteranceCMVN\nfrom tqdm import tqdm\n\n\nUNK_TOKEN, UNK_TOKEN_ID = \"<unk>\", 3\nBOS_TOKEN, BOS_TOKEN_ID = \"<s>\", 0\nEOS_TOKEN, EOS_TOKEN_ID = \"</s>\", 2\nPAD_TOKEN, PAD_TOKEN_ID = \"<pad>\", 1\n\n\ndef gen_vocab(\n input_path: str, output_path_prefix: str, model_type=\"bpe\", vocab_size=1000,\n):\n # Train SentencePiece Model\n arguments = [\n f\"--input={input_path}\",\n f\"--model_prefix={output_path_prefix}\",\n f\"--model_type={model_type}\",\n f\"--vocab_size={vocab_size}\",\n \"--character_coverage=1.0\",\n f\"--num_threads={cpu_count()}\",\n f\"--unk_id={UNK_TOKEN_ID}\",\n f\"--bos_id={BOS_TOKEN_ID}\",\n f\"--eos_id={EOS_TOKEN_ID}\",\n f\"--pad_id={PAD_TOKEN_ID}\",\n ]\n sp.SentencePieceTrainer.Train(\" \".join(arguments))\n # Export fairseq dictionary\n spm = sp.SentencePieceProcessor()\n spm.Load(output_path_prefix + \".model\")\n vocab = {i: spm.IdToPiece(i) for i in range(spm.GetPieceSize())}\n assert (\n vocab.get(UNK_TOKEN_ID) == UNK_TOKEN\n and vocab.get(PAD_TOKEN_ID) == PAD_TOKEN\n and vocab.get(BOS_TOKEN_ID) == BOS_TOKEN\n and vocab.get(EOS_TOKEN_ID) == EOS_TOKEN\n )\n vocab = {\n i: s\n for i, s in vocab.items()\n if s not in {UNK_TOKEN, BOS_TOKEN, EOS_TOKEN, PAD_TOKEN}\n }\n with open(output_path_prefix + \".txt\", \"w\") as f_out:\n for _, s in sorted(vocab.items(), key=lambda x: x[0]):\n f_out.write(f\"{s} 1\\n\")\n\n\ndef extract_fbank_features(\n waveform,\n sample_rate,\n output_path=None,\n n_mel_bins=80,\n apply_utterance_cmvn=True,\n overwrite=False,\n):\n if output_path is not None and op.exists(output_path) and not overwrite:\n return\n\n _waveform = waveform * (2 ** 15) # Kaldi compliance: 16-bit signed integers\n _waveform = _waveform.squeeze().numpy()\n\n features = _get_kaldi_fbank(_waveform, sample_rate, n_mel_bins)\n if features is None:\n features = _get_torchaudio_fbank(_waveform, sample_rate, n_mel_bins)\n if features is None:\n raise ImportError(\n \"Please install pyKaldi or torchaudio to enable \"\n \"online filterbank feature extraction\"\n )\n\n if apply_utterance_cmvn:\n cmvn = UtteranceCMVN(norm_means=True, norm_vars=True)\n features = cmvn(features)\n if output_path is not None:\n np.save(output_path, features)\n else:\n return features\n\n\ndef create_zip(data_root, zip_path):\n cwd = os.path.abspath(os.curdir)\n os.chdir(data_root)\n with zipfile.ZipFile(zip_path, \"w\", zipfile.ZIP_STORED) as f:\n for filename in tqdm(glob(\"*.npy\")):\n f.write(filename)\n os.chdir(cwd)\n\ndef create_zip_list(data_root_list, zip_path):\n '''\n A more flexible version of def create_zip() in which the fbanks can \n be stored in different directories instead of 1\n '''\n\n cwd = os.path.abspath(os.curdir)\n with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_STORED) as f:\n for data_root in data_root_list:\n os.chdir(data_root)\n for filename in tqdm(glob(\"*.npy\")):\n f.write(filename)\n os.chdir(cwd)\n\ndef is_npy_data(data: bytes) -> bool:\n return data[0] == 147 and data[1] == 78\n\n\ndef get_zip_manifest(zip_root, zip_filename):\n zip_path = op.join(zip_root, zip_filename)\n with zipfile.ZipFile(zip_path, mode=\"r\") as f:\n info = f.infolist()\n manifest = {}\n for i in tqdm(info):\n utt_id = op.splitext(i.filename)[0]\n offset, file_size = i.header_offset + 30 + len(i.filename), i.file_size\n manifest[utt_id] = f\"{zip_filename}:{offset}:{file_size}\"\n with open(zip_path, \"rb\") as f:\n f.seek(offset)\n data = f.read(file_size)\n assert len(data) > 1 and is_npy_data(data)\n return manifest\n\n\ndef gen_config_yaml(\n data_root,\n spm_filename,\n yaml_filename=\"config.yaml\",\n specaugment_policy=\"lb\",\n prepend_tgt_lang_tag=False,\n sampling_alpha=1.0,\n):\n data_root = op.abspath(data_root)\n writer = S2TDataConfigWriter(op.join(data_root, yaml_filename))\n writer.set_audio_root(op.abspath(data_root))\n writer.set_vocab_filename(spm_filename.replace(\".model\", \".txt\"))\n writer.set_input_channels(1)\n writer.set_input_feat_per_channel(80)\n specaugment_setters = {\n \"lb\": writer.set_specaugment_lb_policy,\n \"ld\": writer.set_specaugment_ld_policy,\n \"sm\": writer.set_specaugment_sm_policy,\n \"ss\": writer.set_specaugment_ss_policy,\n }\n assert specaugment_policy in specaugment_setters\n specaugment_setters[specaugment_policy]()\n writer.set_bpe_tokenizer(\n {\n \"bpe\": \"sentencepiece\",\n \"sentencepiece_model\": op.join(data_root, spm_filename),\n }\n )\n if prepend_tgt_lang_tag:\n writer.set_prepend_tgt_lang_tag(True)\n writer.set_sampling_alpha(sampling_alpha)\n writer.set_feature_transforms(\"_train\", [\"specaugment\"])\n writer.flush()\n\n\ndef load_df_from_tsv(path: str):\n return pd.read_csv(\n path,\n sep=\"\\t\",\n header=0,\n encoding=\"utf-8\",\n escapechar=\"\\\\\",\n quoting=csv.QUOTE_NONE,\n na_filter=False,\n )\n\n\ndef save_df_to_tsv(dataframe, path):\n dataframe.to_csv(\n path,\n sep=\"\\t\",\n header=True,\n index=False,\n encoding=\"utf-8\",\n escapechar=\"\\\\\",\n quoting=csv.QUOTE_NONE,\n )\n\n\ndef filter_manifest_df(\n df, is_train_split=False, extra_filters=None, min_n_frames=5, max_n_frames=3000\n):\n filters = {\n \"no speech\": df[\"audio\"] == \"\",\n f\"short speech (<{min_n_frames} frames)\": df[\"n_frames\"] < min_n_frames,\n \"empty sentence\": df[\"tgt_text\"] == \"\",\n }\n if is_train_split:\n filters[f\"long speech (>{max_n_frames} frames)\"] = df[\"n_frames\"] > max_n_frames\n if extra_filters is not None:\n filters.update(extra_filters)\n invalid = reduce(lambda x, y: x | y, filters.values())\n valid = ~invalid\n print(\n \"| \"\n + \", \".join(f\"{n}: {f.sum()}\" for n, f in filters.items())\n + f\", total {invalid.sum()} filtered, {valid.sum()} remained.\"\n )\n return df[valid]\n\n\nclass S2TDataConfigWriter(object):\n DEFAULT_VOCAB_FILENAME = \"dict.txt\"\n DEFAULT_INPUT_FEAT_PER_CHANNEL = 80\n DEFAULT_INPUT_CHANNELS = 1\n\n def __init__(self, yaml_path):\n try:\n import yaml\n except ImportError:\n print(\"Please install PyYAML to load YAML files for S2T data config\")\n self.yaml = yaml\n self.yaml_path = yaml_path\n self.config = {}\n\n def flush(self):\n with open(self.yaml_path, \"w\") as f:\n self.yaml.dump(self.config, f)\n\n def set_audio_root(self, audio_root=\"\"):\n self.config[\"audio_root\"] = audio_root\n\n def set_vocab_filename(self, vocab_filename=\"dict.txt\"):\n self.config[\"vocab_filename\"] = vocab_filename\n\n def set_specaugment(\n self,\n time_wrap_w: int,\n freq_mask_n: int,\n freq_mask_f: int,\n time_mask_n: int,\n time_mask_t: int,\n time_mask_p: float,\n ):\n self.config[\"specaugment\"] = {\n \"time_wrap_W\": time_wrap_w,\n \"freq_mask_N\": freq_mask_n,\n \"freq_mask_F\": freq_mask_f,\n \"time_mask_N\": time_mask_n,\n \"time_mask_T\": time_mask_t,\n \"time_mask_p\": time_mask_p,\n }\n\n def set_specaugment_lb_policy(self):\n self.set_specaugment(\n time_wrap_w=0,\n freq_mask_n=1,\n freq_mask_f=27,\n time_mask_n=1,\n time_mask_t=100,\n time_mask_p=1.0,\n )\n\n def set_specaugment_ld_policy(self):\n self.set_specaugment(\n time_wrap_w=0,\n freq_mask_n=2,\n freq_mask_f=27,\n time_mask_n=2,\n time_mask_t=100,\n time_mask_p=1.0,\n )\n\n def set_specaugment_sm_policy(self):\n self.set_specaugment(\n time_wrap_w=0,\n freq_mask_n=2,\n freq_mask_f=15,\n time_mask_n=2,\n time_mask_t=70,\n time_mask_p=0.2,\n )\n\n def set_specaugment_ss_policy(self):\n self.set_specaugment(\n time_wrap_w=0,\n freq_mask_n=2,\n freq_mask_f=27,\n time_mask_n=2,\n time_mask_t=70,\n time_mask_p=0.2,\n )\n\n def set_input_channels(self, input_channels=1):\n self.config[\"input_channels\"] = input_channels\n\n def set_input_feat_per_channel(self, input_feat_per_channel=80):\n self.config[\"input_feat_per_channel\"] = input_feat_per_channel\n\n def set_bpe_tokenizer(self, bpe_tokenizer: Dict[str, Any]):\n self.config[\"bpe_tokenizer\"] = bpe_tokenizer\n\n def set_feature_transforms(self, split, transforms: List[str]):\n if \"transforms\" not in self.config:\n self.config[\"transforms\"] = {}\n self.config[\"transforms\"][split] = transforms\n\n def set_prepend_tgt_lang_tag(self, flag=True):\n self.config[\"prepend_tgt_lang_tag\"] = flag\n\n def set_sampling_alpha(self, sampling_alpha=1.0):\n self.config[\"sampling_alpha\"] = sampling_alpha\n"
] |
[
[
"pandas.read_csv",
"numpy.save"
]
] |
leochien1110/Patch-NetVLAD
|
[
"9282217dd2c9bcf0446a05400fd277e651cecf4e"
] |
[
"feature_match_read.py"
] |
[
"#!/usr/bin/env python\n\n'''\nMIT License\n\nCopyright (c) 2021 Stephen Hausler, Sourav Garg, Ming Xu, Michael Milford and Tobias Fischer\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\nPerforms place recognition using a two-stage image retrieval pipeline, where\nthe first step collects the top 100 database candidates and then geometric\nverification produces the top 1 best match for every query. In this code, query\nimages are imported from saved image in the folder.\n\nRequires feature_extract.py to be run first, on a folder of index/database\nimages.\n\nCode already supports the datasets of Nordland, Pittsburgh 30k and Tokyo247,\nplease run tools/genImageListFile to create new imageNames files with your\nfilepaths pointing to where you saved these datasets (or, edit the text files\nto remove the prefix and insert your own prefix).\n'''\n\n\nfrom __future__ import print_function\n\nimport os\nimport time\nimport argparse\nimport configparser\nfrom os.path import join, isfile\nfrom os.path import exists\nfrom os import makedirs\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader\nimport numpy as np\nimport faiss\nfrom tqdm.auto import tqdm\nimport cv2\nfrom PIL import Image\n\nfrom patchnetvlad.tools.datasets import PlaceDataset, input_transform\nfrom patchnetvlad.tools.patch_matcher import PatchMatcher\nfrom patchnetvlad.models.local_matcher import normalise_func, calc_keypoint_centers_from_patches as calc_keypoint_centers_from_patches\nfrom patchnetvlad.models.models_generic import get_backend, get_model, get_pca_encoding\nfrom patchnetvlad.tools import PATCHNETVLAD_ROOT_DIR\n\n\ndef apply_patch_weights(input_scores, num_patches, patch_weights):\n output_score = 0\n if len(patch_weights) != num_patches:\n raise ValueError('The number of patch weights must equal the number of patches used')\n for i in range(num_patches):\n output_score = output_score + (patch_weights[i] * input_scores[i])\n return output_score\n\n\ndef plot_two(im1, im2, inlier_keypoints_one, inlier_keypoints_two, score, image_index, window_name):\n \n # Draw keypoints\n kp_all1 = []\n kp_all2 = []\n matches_all = []\n for this_inlier_keypoints_one, this_inlier_keypoints_two in zip(inlier_keypoints_one, inlier_keypoints_two):\n for i in range(this_inlier_keypoints_one.shape[0]):\n kp_all1.append(cv2.KeyPoint(this_inlier_keypoints_one[i, 0].astype(float), this_inlier_keypoints_one[i, 1].astype(float), 1, -1, 0, 0, -1))\n kp_all2.append(cv2.KeyPoint(this_inlier_keypoints_two[i, 0].astype(float), this_inlier_keypoints_two[i, 1].astype(float), 1, -1, 0, 0, -1))\n matches_all.append(cv2.DMatch(i, i, 0))\n\n im_allpatch_matches = cv2.drawMatches(im1, kp_all1, im2, kp_all2,\n matches_all, None, matchColor=(0, 255, 0), flags=cv2.DRAW_MATCHES_FLAGS_NOT_DRAW_SINGLE_POINTS)\n cv2.putText(im_allpatch_matches, f\"Retrieved Image: {image_index} ({score:.5})\", (10, 20), cv2.FONT_HERSHEY_PLAIN, 1.5, (0,0,255), 2)\n cv2.imshow(window_name, im_allpatch_matches)\n\n\ndef feature_extract(model, device, config, img):\n\n pool_size = int(config['global_params']['num_pcs'])\n\n model.eval()\n\n it = input_transform((int(config['feature_extract']['imageresizeH']), int(config['feature_extract']['imageresizeW'])))\n\n im_one_pil = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))\n \n im_one_pil = it(im_one_pil).unsqueeze(0)\n\n input_data = im_one_pil.to(device)\n\n tqdm.write('====> Extracting Features')\n with torch.no_grad():\n image_encoding = model.encoder(input_data)\n\n vlad_local, vlad_global = model.pool(image_encoding)\n vlad_global_pca = get_pca_encoding(model, vlad_global).cpu().numpy()\n\n local_feats_one = []\n for this_iter, this_local in enumerate(vlad_local):\n this_local_feats = get_pca_encoding(model, this_local.permute(2, 0, 1).reshape(-1, this_local.size(1))). \\\n reshape(this_local.size(2), this_local.size(0), pool_size).permute(1, 2, 0)\n local_feats_one.append(torch.transpose(this_local_feats[0, :, :], 0, 1))\n\n return local_feats_one, vlad_global_pca\n\n\ndef feature_match(eval_set, device, opt, config, im_query, local_feat, query_global_feat):\n # input_query_local_features_prefix = join(opt.query_input_features_dir, 'patchfeats')\n # input_query_global_features_prefix = join(opt.query_input_features_dir, 'globalfeats.npy')\n input_index_local_features_prefix = join(opt.index_input_features_dir, 'patchfeats')\n input_index_global_features_prefix = join(opt.index_input_features_dir, 'globalfeats.npy')\n \n pool_size = query_global_feat.shape[1]\n dbFeat = np.load(input_index_global_features_prefix)\n\n if dbFeat.dtype != np.float32:\n query_global_feat = query_global_feat.astype('float32')\n dbFeat = dbFeat.astype('float32')\n\n tqdm.write('====> Building faiss index')\n faiss_index = faiss.IndexFlatL2(pool_size)\n # noinspection PyArgumentList\n faiss_index.add(dbFeat)\n\n n_values = []\n for n_value in config['feature_match']['n_values_all'].split(\",\"): # remove all instances of n that are bigger than maxK\n n_values.append(int(n_value))\n\n tqdm.write('====> Matching Global Features')\n if config['feature_match']['pred_input_path'] != 'None':\n predictions = np.load(config['feature_match']['pred_input_path']) # optionally load predictions from a np file\n else:\n # noinspection PyArgumentList\n # _, predictions = faiss_index.search(global_feat, min(len(global_feat), max(n_values)))\n _, predictions = faiss_index.search(query_global_feat, 3)\n\n tqdm.write('====> Loading patch param from config')\n patch_sizes = [int(s) for s in config['global_params']['patch_sizes'].split(\",\")]\n strides = [int(s) for s in config['global_params']['strides'].split(\",\")]\n patch_weights = np.array(config['feature_match']['patchWeights2Use'].split(\",\")).astype(float)\n\n all_keypoints = []\n all_indices = []\n\n tqdm.write('====> Matching Local Features')\n for patch_size, stride in zip(patch_sizes, strides):\n # we currently only provide support for square patches, but this can be easily modified for future works\n keypoints, indices = calc_keypoint_centers_from_patches(config['feature_match'], patch_size, patch_size, stride, stride)\n all_keypoints.append(keypoints)\n all_indices.append(indices)\n\n matcher = PatchMatcher(config['feature_match']['matcher'], patch_sizes, strides, all_keypoints,\n all_indices)\n reordered_preds = []\n for q_idx, pred in enumerate(tqdm(predictions, leave=False, desc='Patch compare pred')):\n diffs = np.zeros((predictions.shape[1], len(patch_sizes)))\n # we pre-transpose here to save compute speed\n for k, candidate in enumerate(pred):\n image_name_index = os.path.splitext(os.path.basename(eval_set.images[candidate]))[0]\n dbfeat = []\n for patch_size in patch_sizes:\n dbfilename = input_index_local_features_prefix + '_' + 'psize{}_'.format(patch_size) + image_name_index + '.npy'\n dbfeat.append(torch.tensor(np.load(dbfilename), device=device))\n\n if k == 0:\n # Get the NetVLAD top candidate's keypoints and score\n scores, keypoints_net_one, keypoints_net_two = matcher.match(local_feat, dbfeat)\n diffs[k, :] = scores\n score_net = -apply_patch_weights(scores, len(patch_sizes), patch_weights)\n print(f\"NetVLAD: Similarity score between the two images is: {score_net:.5f}. Larger is better.\")\n else:\n diffs[k, :], _, _ = matcher.match(local_feat, dbfeat)\n \n diffs = normalise_func(diffs, len(patch_sizes), patch_weights)\n cand_sorted = np.argsort(diffs)\n reordered_preds.append(pred[cand_sorted])\n\n # Top candidates from two methods\n image_name_index_net = os.path.splitext(os.path.basename(eval_set.images[predictions[0][0]]))[0]\n image_name_index_patch = os.path.splitext(os.path.basename(eval_set.images[reordered_preds[0][0]]))[0]\n\n # Get the Patch-NetVLAD top candidate's keypoints and score\n dbfeat = []\n for patch_size in patch_sizes:\n dbfilename = input_index_local_features_prefix + '_' + 'psize{}_'.format(patch_size) + image_name_index_patch + '.npy'\n dbfeat.append(torch.tensor(np.load(dbfilename), device=device))\n scores, keypoints_patch_one, keypoints_patch_two = matcher.match(local_feat, dbfeat)\n score_patch = -apply_patch_weights(scores, len(patch_sizes), patch_weights)\n print(f\"Patch-NetVLAD: Similarity score between the two images is: {score_patch:.5f}. Larger is better.\")\n \n print('predictions: ', predictions[0])\n print('reordered_preds: ', reordered_preds[0])\n\n # Show the most possible retrieved image\n image_list_array = np.array(eval_set.images) \n im_db_net = cv2.imread(image_list_array[predictions[0]][0])\n im_db_patch = cv2.imread(image_list_array[reordered_preds[0]][0])\n\n # using cv2 for their in-built keypoint correspondence plotting tools\n im_query = cv2.resize(im_query, (int(config['feature_extract']['imageresizeW']), int(config['feature_extract']['imageresizeH'])))\n im_db_net = cv2.resize(im_db_net, (int(config['feature_extract']['imageresizeW']), int(config['feature_extract']['imageresizeH'])))\n im_db_patch = cv2.resize(im_db_patch, (int(config['feature_extract']['imageresizeW']), int(config['feature_extract']['imageresizeH'])))\n # cv2 resize slightly different from torch, but for visualisation only not a big problem\n\n if config['feature_match']['matcher'] == 'RANSAC':\n # Draw local matches\n plot_two(im_query, im_db_net, keypoints_net_one, keypoints_net_two, score_net, image_name_index_net, 'NetVLAD')\n plot_two(im_query, im_db_patch, keypoints_patch_one, keypoints_patch_two, score_patch, image_name_index_patch, 'Patch-NetVLAD')\n else:\n cv2.imshow('NetVLAD Top Match', im_db_net)\n cv2.imshow('Patch-NetVLAD Top Match', im_db_patch)\n \n \ndef main():\n parser = argparse.ArgumentParser(description='Patch-NetVLAD-Feature-Match')\n parser.add_argument('--config_path', type=str, default=join(PATCHNETVLAD_ROOT_DIR, 'configs/performance.ini'),\n help='File name (with extension) to an ini file that stores most of the configuration data for patch-netvlad')\n parser.add_argument('--index_file_path', type=str, required=True,\n help='Path (with extension) to a text file that stores the save location and name of all database images in the dataset')\n parser.add_argument('--index_input_features_dir', type=str, required=True,\n help='Path to load all database patch-netvlad features')\n parser.add_argument('--query_file_path', type=str, required=True,\n help='Relative path to query images in the dataset directory')\n parser.add_argument('--dataset_root_dir', type=str, default='',\n help='If the files in query_file_path and index_file_path are relative, use dataset_root_dir as prefix.')\n \n parser.add_argument('--nocuda', action='store_true', help='If true, use CPU only. Else use GPU.')\n\n opt = parser.parse_args()\n print(opt)\n\n # load config file\n configfile = opt.config_path\n assert os.path.isfile(configfile)\n config = configparser.ConfigParser()\n config.read(configfile)\n \n # check GPU/cuda\n cuda = not opt.nocuda\n if cuda and not torch.cuda.is_available():\n raise Exception(\"No GPU found, please run with --nocuda\")\n\n device = torch.device(\"cuda\" if cuda else \"cpu\")\n\n # load model\n encoder_dim, encoder = get_backend()\n\n # must load from a resume to do extraction\n resume_ckpt = config['global_params']['resumePath'] + config['global_params']['num_pcs'] + '.pth.tar'\n\n # backup: try whether resume_ckpt is relative to script path\n if not isfile(resume_ckpt):\n resume_ckpt = join(PATCHNETVLAD_ROOT_DIR, resume_ckpt)\n if not isfile(resume_ckpt):\n from download_models import download_all_models\n download_all_models(ask_for_permission=True)\n\n if isfile(resume_ckpt):\n print(\"=> loading checkpoint '{}'\".format(resume_ckpt))\n checkpoint = torch.load(resume_ckpt, map_location=lambda storage, loc: storage)\n assert checkpoint['state_dict']['WPCA.0.bias'].shape[0] == int(config['global_params']['num_pcs'])\n config['global_params']['num_clusters'] = str(checkpoint['state_dict']['pool.centroids'].shape[0])\n\n model = get_model(encoder, encoder_dim, opt, config['global_params'], append_pca_layer=True)\n\n if int(config['global_params']['nGPU']) > 1 and torch.cuda.device_count() > 1:\n model.encoder = nn.DataParallel(model.encoder)\n model.pool = nn.DataParallel(model.pool)\n\n model.load_state_dict(checkpoint['state_dict'])\n model = model.to(device)\n print(\"=> loaded checkpoint '{}'\".format(resume_ckpt, ))\n else:\n raise FileNotFoundError(\"=> no checkpoint found at '{}'\".format(resume_ckpt))\n\n # check database path\n if not os.path.isfile(opt.index_file_path):\n opt.index_file_path = join(PATCHNETVLAD_ROOT_DIR, 'dataset_imagenames', opt.index_file_path)\n\n print(opt.dataset_root_dir + opt.query_file_path)\n folder = opt.dataset_root_dir + opt.query_file_path\n\n \n cv2.namedWindow(\"Query Image\", cv2.WINDOW_AUTOSIZE)\n cv2.namedWindow(\"NetVLAD Top Match\", cv2.WINDOW_AUTOSIZE)\n cv2.namedWindow(\"Patch-NetVLAD Top Match\", cv2.WINDOW_AUTOSIZE)\n \n cv2.waitKey(0)\n\n start = time.time()\n for filename in sorted(os.listdir(folder)):\n print('[Filename] ' + filename)\n frame = cv2.imread(os.path.join(folder,filename))\n\n if frame is None:\n print('Could not load the image')\n break\n\n # extract query feature\n local_feat, global_feat = feature_extract(model, device, config, frame)\n\n dataset = PlaceDataset(None, opt.index_file_path, opt.dataset_root_dir, None, config['feature_extract'])\n # match feature\n feature_match(dataset, device, opt, config, frame, local_feat, global_feat)\n \n end = time.time()\n elapse = end - start\n start = end\n print(f\"FPS: {1/elapse}\")\n frame = cv2.resize(frame, (int(config['feature_extract']['imageresizeW']), int(config['feature_extract']['imageresizeH'])))\n cv2.putText(frame, f\"FPS: {1/elapse}\", (10, 20), cv2.FONT_HERSHEY_PLAIN, 1.5, (0,200,255), 2 )\n cv2.imshow('Query Image', frame)\n\n key = cv2.waitKey(30)\n if key & 0xFF == ord('q'):\n break\n elif key & 0xFF == ord('n'):\n print('why press \\'n\\'?')\n\n \n \n cv2.destroyAllWindows()\n torch.cuda.empty_cache() # garbage clean GPU memory, a bug can occur when Pytorch doesn't automatically clear the\n # memory after runs\n\nif __name__ == \"__main__\":\n main()"
] |
[
[
"numpy.argsort",
"torch.transpose",
"torch.load",
"torch.cuda.device_count",
"torch.cuda.empty_cache",
"torch.no_grad",
"torch.cuda.is_available",
"torch.device",
"numpy.load",
"torch.nn.DataParallel",
"numpy.array"
]
] |
beibeiyang/cf-iot-example
|
[
"0f0454e6311cda96a8f43edbd42a6e0e9651a381"
] |
[
"app1_pcfdev/app/main.py"
] |
[
"from pymongo import MongoClient, errors\r\nimport os, sys\r\nimport json\r\nimport redis\r\nimport time, datetime\r\nimport calendar\r\nimport numpy as np\r\nfrom bokeh.layouts import layout, widgetbox\r\nfrom bokeh.models.widgets import Select, Slider, Div, Button, Panel, Tabs, CheckboxGroup\r\nfrom bokeh.models.widgets import DataTable, TableColumn\r\nfrom bokeh.models import ColumnDataSource, HoverTool\r\nfrom bokeh.io import curdoc\r\nfrom bokeh.plotting import figure\r\n\r\nmongoip = \"127.0.0.1\"\r\nmongouser = \"user\"\r\nmongopwd = \"pass\"\r\nmongoauthsrc = \"dbname\"\r\nmongoport = 27017\r\n\r\nmongoip = os.getenv('MONGO_ENV_SERVER_IP', mongoip)\r\nmongouser = os.getenv('MONGO_ENV_USERNAME', mongouser)\r\nmongopwd = os.getenv('MONGO_ENV_PASSWORD', mongopwd)\r\nmongoauthsrc = os.getenv('MONGO_ENV_AUTHSOURCE', mongoauthsrc)\r\nmongoport = int(os.getenv('MONGO_ENV_PORT', mongoport))\r\n\r\nuri = \"mongodb://{}:{}@{}:{}/?authSource={}\".format(mongouser, mongopwd, mongoip, mongoport, mongoauthsrc)\r\n\r\nprint (\"url:\", uri)\r\n\r\ntry:\r\n db = MongoClient(uri).get_database(mongoauthsrc)\r\nexcept errors.ConnectionFailure as e:\r\n print (\"Could not connect to server: %s\" % e)\r\n sys.exit(-1)\r\n\r\n# Get Redis credentials\r\nif 'VCAP_SERVICES' in os.environ:\r\n services = json.loads(os.getenv(\"VCAP_SERVICES\"))\r\n # PCFDev uses 'p-redis' and PCf uses 'rediscloud' as servicename\r\n servicename, servicedetail = services.popitem()\r\n redis_env = servicedetail[0][\"credentials\"]\r\nelse:\r\n redis_env = dict(host=\"localhost\", port=6379, password=\"\")\r\n\r\n# RedisCloud service uses key \"hostname\" instead of key \"host\" in p-redis\r\nif \"hostname\" in redis_env:\r\n redis_env[\"host\"] = redis_env[\"hostname\"]\r\n del redis_env[\"hostname\"]\r\n\r\nredis_env[\"port\"] = int(redis_env[\"port\"])\r\n\r\n# Connect to redis\r\ntry:\r\n redisconn = redis.StrictRedis(**redis_env)\r\n #print(r.info())\r\nexcept redis.ConnectionError as e:\r\n print (\"Redis error: %s\" % e)\r\n sys.exit(-1)\r\n\r\nredisconn.flushall()\r\n\r\nnotificationDiv = Div(text=\"\", width=800)\r\n\r\ngateways = []\r\nif redisconn.get(\"gateways\"):\r\n gateways = json.loads(redisconn.get(\"gateways\"))\r\nelse:\r\n try:\r\n cursor = db.gateways.find( {}, {\"id\":1, \"name\":1} )\r\n gateways = []\r\n gateways.append((None, \"--- Choose a Gateway ---\"))\r\n for d in cursor:\r\n gateways.append((d[\"id\"], d[\"name\"]))\r\n redisconn.set(\"gateways\", json.dumps(gateways))\r\n except errors.ServerSelectionTimeoutError as e:\r\n print (\"MongoDB Server timed out: %s\" % e)\r\n notificationDiv.text = \"MongoDB Server timed out: %s\" % e\r\n sys.exit(-1)\r\n\r\ngatewayControl = Select( title=\"Choose a Gateway\", options=gateways)\r\ndeviceControl = Select( title=\"Choose a Device\")\r\nindicatorControl = Select( title=\"Choose an indicator\")\r\nsubmitButton = Button(label=\"Submit\", button_type=\"primary\")\r\ntimemachine = Slider(title=\"How many minutes back would you like to travel\", start=1, end=30, value=1, step=1,\r\n callback_policy=\"mouseup\")\r\ncontrols = [gatewayControl, deviceControl, indicatorControl, timemachine, submitButton, notificationDiv]\r\n\r\ndoc = curdoc()\r\nsource = ColumnDataSource(data=dict(last_mod_date=[None], date=[None], v=[None]))\r\n# source = ColumnDataSource(data=dict(last_mod_date=[None], date=[None], v=[None]))\r\n\r\n# hover = HoverTool(tooltips=[\r\n# (\"Date\", \"@s\"),\r\n# (indicatorControl.value, \"@v\")\r\n# ])\r\n\r\np = figure(title=\"\", x_axis_type=\"datetime\", plot_width=600, plot_height=400)\r\np.line('last_mod_date', \"v\", source=source)\r\ntab1 = Panel(child=p, title=\"Plot\")\r\n\r\ncolumns = [\r\n TableColumn(field=\"last_mod_date\", title=\"TimeStamp\"),\r\n TableColumn(field=\"date\", title=\"Date\"),\r\n TableColumn(field=\"v\", title=\"Value\"),\r\n]\r\ndataTable = DataTable(source=source, columns=columns, width=800, height=600)\r\n\r\ntab2 = Panel(child=dataTable, title=\"Table\")\r\ntabs = Tabs(tabs=[tab1, tab2 ])\r\n\r\n# tabs.css_classes = [\"hide\"]\r\n\r\nautoUpdateCheckbox = CheckboxGroup(\r\n labels=[\"Auto Update Data Source (every 15s)\"], active=[])\r\nautoUpdateCheckbox.disabled = True\r\n\r\ngatewayControl.on_change('value', lambda attr, old, new: update_device())\r\ndeviceControl.on_change('value', lambda attr, old, new: update_indicator())\r\nsubmitButton.on_click(lambda: callback())\r\nautoUpdateCheckbox.on_click(lambda attr: auto_update(attr))\r\n\r\nsizing_mode = 'fixed' # 'scale_width' also looks nice with this example\r\ninputs = widgetbox(*controls, sizing_mode=sizing_mode, name=\"widgets\")\r\nplotwidget = widgetbox([autoUpdateCheckbox, tabs], sizing_mode=sizing_mode, name=\"plotwidget\")\r\n\r\nmainLayout = layout(children=[\r\n [inputs, plotwidget]\r\n], sizing_mode=sizing_mode, name=\"mainLayout\")\r\n\r\ndoc.add_root(mainLayout)\r\ndoc.title = \"ACME IoT Analytics\"\r\n\r\ndef epoch_to_datetime(epoch):\r\n \"\"\"\r\n :param epoch: str of epoch time\r\n :return: converted datetime type\r\n \"\"\"\r\n return datetime.datetime.fromtimestamp(float(epoch) / 1000)\r\n\r\n\r\ndef callback(mainLayout=mainLayout, source=source):\r\n fig = mainLayout.children[0].children[1].children[1].tabs[0].child\r\n autoUpdateCheckbox.disabled = False\r\n\r\n if not deviceControl.value or not indicatorControl.value:\r\n return\r\n\r\n dsIdNames = {}\r\n for d in db.datasets.find({\"device_id\": deviceControl.value}):\r\n dsIdNames[d[\"id\"]] = d[\"name\"]\r\n\r\n print (\"dsIdNames: %s\" % dsIdNames)\r\n\r\n currTs = calendar.timegm(time.gmtime())*1000 # current epoch time in miliseconds\r\n oldestTs = currTs - timemachine.value * 60 * 1000\r\n print(\"Current timestamp: %s \\t, Oldest timestamp: %s\", currTs, oldestTs)\r\n\r\n print (\"mainLayout.children: %s\" % mainLayout.children)\r\n\r\n n = 0\r\n for id in dsIdNames:\r\n dates = []\r\n vs = []\r\n print(\"dataset_id: %s\" % id)\r\n print(\"oldestTs: %s\" % oldestTs)\r\n\r\n # expensive call\r\n cursor = db.dataitems.find({\"dataset_id\": id, \"last_mod_date\": {\"$gt\": oldestTs} })\r\n count = cursor.count()\r\n print(\"Visit the past %s min\" % timemachine.value)\r\n print(\"Retrieving %s document(s)\" % count)\r\n\r\n # if a device corresponds to multiple datasets and\r\n # the later dataset is empty, skip and do not update\r\n # the notificationDiv\r\n if n > 0 and count==0:\r\n continue\r\n\r\n notificationDiv.text = \"Found {} record\".format(count)\r\n if count > 1:\r\n notificationDiv.text += \"s\"\r\n\r\n if count == 0:\r\n continue\r\n\r\n n = n + count\r\n\r\n for d in cursor:\r\n if indicatorControl.value not in d[\"v\"]:\r\n continue\r\n date = d[\"last_mod_date\"]\r\n v = d[\"v\"][indicatorControl.value]\r\n if v is None:\r\n continue\r\n dates.append(epoch_to_datetime(date))\r\n vs.append(v)\r\n\r\n dates = np.array(dates, dtype='datetime64[ms]')\r\n source.data = dict(last_mod_date=dates, date=[str(d) for d in dates], v=vs)\r\n print(\"len(dsIdNames): %s\" % len(dsIdNames))\r\n print(\"id: %s, dsIdNames[id]: %s\" % (id, dsIdNames[id]))\r\n print(\"source.data: %s\" % source.data)\r\n\r\n fig.title.text = dsIdNames[id]\r\n fig.grid.grid_line_alpha = 0.3\r\n fig.xaxis.axis_label = \"DateTime\"\r\n fig.yaxis.axis_label = indicatorControl.value\r\n\r\n if autoUpdateCheckbox.disabled:\r\n autoUpdateCheckbox.disabled = False\r\n\r\n # reset plot and table if no records\r\n if n == 0:\r\n source.data = dict(last_mod_date=[None], date=[None], v=[None])\r\n fig.title.text = \"\"\r\n fig.xaxis.axis_label = \"\"\r\n fig.yaxis.axis_label = \"\"\r\n\r\n\r\nfrom threading import Timer\r\ndef auto_update(attr):\r\n print(\"attr: %s\" % attr)\r\n if len(attr) > 0:\r\n # box checked\r\n Timer(15, auto_update, args=[attr]).start() # run callback every 15 seconds\r\n # submitButton.trigger(\"clicks\", None, None)\r\n doc.add_next_tick_callback(callback)\r\n else:\r\n return\r\n\r\n\r\ndef update_device():\r\n gatewayId = gatewayControl.value\r\n if not gatewayId:\r\n return\r\n # reset device and indicator dropdowns\r\n deviceControl.options = []\r\n indicatorControl.options = []\r\n rkey = \"device&gatewayId=\" + gatewayId\r\n if redisconn.get(rkey):\r\n deviceControl.options = json.loads(redisconn.get(rkey))\r\n else:\r\n deviceControl.options = []\r\n devices = list()\r\n devices.append((None, \"--- Choose a Device ---\"))\r\n for d in db.devices.find({ \"parent_id\": gatewayId }):\r\n devices.append((d[\"id\"], d[\"name\"]))\r\n deviceControl.options = devices\r\n redisconn.set(rkey, json.dumps(devices))\r\n doc.add_next_tick_callback(callback)\r\n\r\n\r\ndef update_indicator():\r\n deviceId = deviceControl.value\r\n if not deviceId:\r\n return\r\n # reset indicator dropdown\r\n indicatorControl.options = []\r\n rkey = \"indicators&deviceId=\" + deviceId\r\n if redisconn.get(rkey):\r\n indicatorControl.options = json.loads(redisconn.get(rkey))\r\n else:\r\n indicatorControl.options = list()\r\n device = db.devices.find_one({ \"id\": deviceId } )\r\n indicators = [(None, \"--- Choose an indicator ---\")]\r\n indicators = indicators + device[\"indicator_names\"]\r\n indicatorControl.options = indicators\r\n redisconn.set(rkey, json.dumps(indicators))\r\n doc.add_next_tick_callback(callback)"
] |
[
[
"numpy.array"
]
] |
peterhan91/Invertible-Image-Rescaling
|
[
"b92162f5e9be2cff2f5dba379914fcded4e04f4c"
] |
[
"codes/models/modules/Inv_arch.py"
] |
[
"import math\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\n\nfrom data.fastmri import transforms\n\n\nclass InvBlockExp(nn.Module):\n def __init__(self, subnet_constructor, channel_num, channel_split_num, clamp=1.):\n super(InvBlockExp, self).__init__()\n\n self.split_len1 = channel_split_num\n self.split_len2 = channel_num - channel_split_num\n\n self.clamp = clamp\n\n self.F = subnet_constructor(self.split_len2, self.split_len1)\n self.G = subnet_constructor(self.split_len1, self.split_len2)\n self.H = subnet_constructor(self.split_len1, self.split_len2)\n\n def forward(self, x, rev=False):\n x1, x2 = (x.narrow(1, 0, self.split_len1), x.narrow(1, self.split_len1, self.split_len2))\n\n if not rev:\n y1 = x1 + self.F(x2)\n self.s = self.clamp * (torch.sigmoid(self.H(y1)) * 2 - 1)\n y2 = x2.mul(torch.exp(self.s)) + self.G(y1)\n else:\n self.s = self.clamp * (torch.sigmoid(self.H(x1)) * 2 - 1)\n y2 = (x2 - self.G(x1)).div(torch.exp(self.s))\n y1 = x1 - self.F(y2)\n\n return torch.cat((y1, y2), 1)\n\n def jacobian(self, x, rev=False):\n if not rev:\n jac = torch.sum(self.s)\n else:\n jac = -torch.sum(self.s)\n\n return jac / x.shape[0]\n\n\nclass HaarDownsampling(nn.Module):\n def __init__(self, channel_in):\n super(HaarDownsampling, self).__init__()\n self.channel_in = channel_in\n\n self.haar_weights = torch.ones(4, 1, 2, 2)\n\n self.haar_weights[1, 0, 0, 1] = -1\n self.haar_weights[1, 0, 1, 1] = -1\n\n self.haar_weights[2, 0, 1, 0] = -1\n self.haar_weights[2, 0, 1, 1] = -1\n\n self.haar_weights[3, 0, 1, 0] = -1\n self.haar_weights[3, 0, 0, 1] = -1\n\n self.haar_weights = torch.cat([self.haar_weights] * self.channel_in, 0)\n self.haar_weights = nn.Parameter(self.haar_weights)\n self.haar_weights.requires_grad = False\n\n def forward(self, x, rev=False):\n if not rev:\n self.elements = x.shape[1] * x.shape[2] * x.shape[3]\n self.last_jac = self.elements / 4 * np.log(1/16.)\n\n out = F.conv2d(x, self.haar_weights, bias=None, stride=2, groups=self.channel_in) / 4.0\n out = out.reshape([x.shape[0], self.channel_in, 4, x.shape[2] // 2, x.shape[3] // 2])\n out = torch.transpose(out, 1, 2)\n out = out.reshape([x.shape[0], self.channel_in * 4, x.shape[2] // 2, x.shape[3] // 2])\n return out\n else:\n self.elements = x.shape[1] * x.shape[2] * x.shape[3]\n self.last_jac = self.elements / 4 * np.log(16.)\n\n out = x.reshape([x.shape[0], 4, self.channel_in, x.shape[2], x.shape[3]])\n out = torch.transpose(out, 1, 2)\n out = out.reshape([x.shape[0], self.channel_in * 4, x.shape[2], x.shape[3]])\n return F.conv_transpose2d(out, self.haar_weights, bias=None, stride=2, groups = self.channel_in)\n\n def jacobian(self, x, rev=False):\n return self.last_jac\n\n\nclass FourierDownsampling(nn.Module):\n def __init__(self, mask_func, seed):\n super(FourierDownsampling, self).__init__()\n self.mask_func = mask_func\n self.seed = seed\n\n def forward(self, x, rev=False):\n if x.size(-1) != 1:\n img = torch.stack((x, torch.zeros_like(x)), -1)\n assert img.size(-1) == 2\n \n if not rev:\n self.elements = x.shape[1] * x.shape[2] * x.shape[3]\n self.last_jac = self.elements / 2 * np.log(1/4.)\n \n # x shape [bs, ch, H, W] e.g. [16, 1, 144, 144]\n kspace = transforms.fft2(img) # [bs, ch, H, W, 2]\n center_kspace, _ = transforms.apply_mask(kspace, self.mask_func, \n seed=self.seed, cuda=True)\n periph_kspace, _ = transforms.apply_mask(kspace, self.mask_func, \n rev=True, seed=self.seed, cuda=True)\n img_LF = transforms.complex_abs(transforms.ifft2(center_kspace)) # [bs, ch, H, W]\n img_HF = transforms.complex_abs(transforms.ifft2(periph_kspace)) \n return torch.cat((img_LF, img_HF), dim=1) # [bs, ch*2, H, W]\n else:\n self.elements = x.shape[1] * x.shape[2] * x.shape[3]\n self.last_jac = self.elements / 2 * np.log(4.)\n \n # if rev: img shape [bs, ch*2, H, W, 2]\n center_kspace = transforms.fft2(img.narrow(1, 0, 1)) # shape \n periph_kspace = transforms.fft2(img.narrow(1, 1, 1)) # shape [bs, ch, H, W, 2]\n out = transforms.complex_abs(transforms.ifft2(center_kspace + periph_kspace))\n return out # [bs, ch, H, W]\n\n def jacobian(self, x, rev=False):\n return self.last_jac\n\n\nclass InvRescaleNet(nn.Module):\n def __init__(self, channel_in=3, channel_out=3, subnet_constructor=None, \n block_num=[], down_num=2, Haar=True, mask_func=None, seed=None):\n super(InvRescaleNet, self).__init__()\n\n operations = []\n\n current_channel = channel_in\n for i in range(down_num):\n if Haar:\n b = HaarDownsampling(current_channel)\n current_channel *= 4\n else:\n b = FourierDownsampling(mask_func, seed)\n current_channel *= 2\n operations.append(b)\n\n for j in range(block_num[i]):\n b = InvBlockExp(subnet_constructor, current_channel, channel_out)\n operations.append(b)\n\n self.operations = nn.ModuleList(operations)\n\n def forward(self, x, rev=False, cal_jacobian=False):\n out = x\n jacobian = 0\n\n if not rev:\n for op in self.operations:\n out = op.forward(out, rev)\n if cal_jacobian:\n jacobian += op.jacobian(out, rev)\n else:\n for op in reversed(self.operations):\n out = op.forward(out, rev)\n if cal_jacobian:\n jacobian += op.jacobian(out, rev)\n\n if cal_jacobian:\n return out, jacobian\n else:\n return out\n\n"
] |
[
[
"torch.nn.functional.conv_transpose2d",
"numpy.log",
"torch.nn.Parameter",
"torch.ones",
"torch.transpose",
"torch.cat",
"torch.nn.ModuleList",
"torch.nn.functional.conv2d",
"torch.sum",
"torch.zeros_like",
"torch.exp"
]
] |
NunoEdgarGFlowHub/image_captioning
|
[
"35bda7dab986fb3130180b64c86c5845bca8c718"
] |
[
"utils/misc.py"
] |
[
"\nimport numpy as np\nimport cv2\nimport heapq\n\nclass ImageLoader(object):\n def __init__(self, mean_file):\n self.bgr = True\n self.scale_shape = np.array([224, 224], np.int32)\n self.crop_shape = np.array([224, 224], np.int32)\n self.mean = np.load(mean_file).mean(1).mean(1)\n\n def load_image(self, image_file):\n \"\"\" Load and preprocess an image. \"\"\"\n image = cv2.imread(image_file)\n\n if self.bgr:\n temp = image.swapaxes(0, 2)\n temp = temp[::-1]\n image = temp.swapaxes(0, 2)\n\n image = cv2.resize(image, (self.scale_shape[0], self.scale_shape[1]))\n offset = (self.scale_shape - self.crop_shape) / 2\n offset = offset.astype(np.int32)\n image = image[offset[0]:offset[0]+self.crop_shape[0],\n offset[1]:offset[1]+self.crop_shape[1]]\n image = image - self.mean\n return image\n\n def load_images(self, image_files):\n \"\"\" Load and preprocess a list of images. \"\"\"\n images = []\n for image_file in image_files:\n images.append(self.load_image(image_file))\n images = np.array(images, np.float32)\n return images\n\nclass CaptionData(object):\n def __init__(self, sentence, memory, output, score):\n self.sentence = sentence\n self.memory = memory\n self.output = output\n self.score = score\n\n def __cmp__(self, other):\n assert isinstance(other, CaptionData)\n if self.score == other.score:\n return 0\n elif self.score < other.score:\n return -1\n else:\n return 1\n\nclass TopN(object):\n def __init__(self, n):\n self._n = n\n self._data = []\n\n def size(self):\n assert self._data is not None\n return len(self._data)\n\n def push(self, x):\n assert self._data is not None\n if len(self._data) < self._n:\n heapq.heappush(self._data, x)\n else:\n heapq.heappushpop(self._data, x)\n\n def extract(self, sort=False):\n assert self._data is not None\n data = self._data\n self._data = None\n if sort:\n data.sort(reverse=True)\n return data\n\n def reset(self):\n self._data = []\n"
] |
[
[
"numpy.load",
"numpy.array"
]
] |
hakatashi/atcoder-diff-predictor
|
[
"4a329c51ec3e2a13d69a81740d96495f1512de2e"
] |
[
"linear_regression.py"
] |
[
"import numpy as np\nfrom sklearn.linear_model import LinearRegression\n\ndata = np.loadtxt('data/fa10.csv', skiprows=1, delimiter=',')\ndifficulty = data[:, 0]\nscore = data[:, 1]\nelapsed = data[:, 2]\nrating = data[:, 3]\n\nlog_score = np.log(score)\nlog_elapsed = np.log(elapsed)\n\nX = np.column_stack((log_score, log_elapsed))\ny = difficulty\nregression = LinearRegression().fit(X, y)\nprint(regression.predict(X[600:610]))\nprint(y[600:610])\n\n"
] |
[
[
"numpy.log",
"sklearn.linear_model.LinearRegression",
"numpy.loadtxt",
"numpy.column_stack"
]
] |
andypwyu/Image_Classifier
|
[
"ea31d81663af4c081f6daba66ab983ff001e9992"
] |
[
"predict.py"
] |
[
"import argparse\nimport json\nimport torch\nimport numpy as np\nfrom PIL import Image\nfrom torch import nn\nfrom torch import optim\nfrom math import ceil\nfrom torchvision import datasets, models, transforms\n\ndef arg_parse():\n # Define a parser\n parser = argparse.ArgumentParser(description=\"Neural Network Settings\")\n\n # Point towards image for prediction\n parser.add_argument('--image_path', \n type=str, \n default='flowers/test/19/image_06159.jpg',\n help='image file path as str.')\n\n # Load checkpoint created by train.py\n parser.add_argument('--checkpoint', \n type=str, \n default='my_checkpoint.pth',\n help='Checkpoint file as str.')\n \n # Specify top-k\n parser.add_argument('--top_k', \n type=int, \n default=5,\n help='Choose top K matches as int.')\n \n # Import category names\n parser.add_argument('--category_names', \n type=str, \n default='cat_to_name.json',\n help='Mapping from categories to real names as json file.')\n\n # Add GPU Option to parser\n parser.add_argument('--gpu',\n type=bool,\n default=True, \n help='Use GPU as True, CPU as False')\n\n # Parse args\n args = parser.parse_args() \n return args\n\ndef get_model(arch):\n cmd = \"model = models.{}(pretrained=True)\".format(arch)\n exec(cmd, globals())\n model.name = arch \n \n for param in model.parameters():\n param.requires_grad = False \n \n return model\n\ndef load_model(checkpoint_path, use_gpu):\n \n # Load the saved file\n if use_gpu:\n map_location = lambda storage, loc: storage.cuda()\n else:\n map_location = 'cpu'\n \n checkpoint = torch.load(checkpoint_path, map_location = map_location)\n \n # Download pretrained model\n model = get_model(checkpoint['architecture']);\n \n # Freeze parameters so we don't backprop through them\n for param in model.parameters(): param.requires_grad = False\n \n # Load stuff from checkpoint\n model.class_to_idx = checkpoint['class_to_idx']\n model.classifier = checkpoint['classifier']\n model.load_state_dict(checkpoint['state_dict'])\n \n print(\" Architecture:{}\\n Classifier:{} \".format(str(checkpoint['architecture']), str(checkpoint['classifier'])))\n return model\n\ndef process_image(image_path):\n \n img_loader = transforms.Compose([\n transforms.Resize(256), \n transforms.CenterCrop(224), \n transforms.ToTensor()])\n \n pil_image = Image.open(image_path)\n pil_image = img_loader(pil_image).float()\n \n np_image = np.array(pil_image) \n \n # Normalize each color channel\n norm_mean = np.array([0.485, 0.456, 0.406])\n norm_std = np.array([0.229, 0.224, 0.225])\n np_image = (np.transpose(np_image, (1, 2, 0)) - norm_mean)/norm_std \n \n # Set the color to the first channel\n np_image = np.transpose(np_image, (2, 0, 1))\n image_tensor = torch.from_numpy(np.expand_dims(np_image, axis=0)).type(torch.FloatTensor) \n return image_tensor\n\ndef predict(image_tensor, model, cat_to_name, top_k, use_gpu):\n\n # Set model to evaluate\n model.eval();\n \n # GPU switcher\n with torch.no_grad():\n if use_gpu:\n model = model.cuda()\n image_tensor = image_tensor.float().cuda() \n else:\n model = model.cpu()\n\n # Find probabilities (results) by passing through the function (note the log softmax means that its on a log scale)\n log_probs = model.forward(image_tensor)\n\n # Convert to linear scale\n linear_probs = torch.exp(log_probs)\n\n # Find the top 5 results\n top_probs, top_labels = linear_probs.topk(top_k)\n\n # Detatch all of the details\n top_probs = np.array(top_probs.detach())[0] # This is not the correct way to do it but the correct way isnt working thanks to cpu/gpu issues so I don't care.\n top_labels = np.array(top_labels.detach())[0]\n\n # Convert to classes\n idx_to_class = {val: key for key, val in model.class_to_idx.items()}\n top_labels = [idx_to_class[lab] for lab in top_labels]\n top_flowers = [cat_to_name[lab] for lab in top_labels]\n\n return top_probs, top_labels, top_flowers\n\ndef print_result(probs, flowers):\n for i, j in enumerate(zip(flowers, probs)):\n print (\"Rank {}:\".format(i+1),\n \"Flower: {}, liklihood: {}%\".format(j[1], ceil(j[0]*100)))\n \n \n \n# =============================================================================\n# Main Function\n# =============================================================================\ndef main():\n \n use_gpu = torch.cuda.is_available()\n \n # Get Keyword Args for Prediction\n args = arg_parse()\n \n if args.gpu:\n if use_gpu:\n print(\"Using GPU\")\n else:\n print(\"Using CPU since GPU is not available\")\n else: \n use_gpu = False\n \n \n # Load categories to names json file\n with open(args.category_names, 'r') as f:\n \tcat_to_name = json.load(f)\n\n # Load model trained with train.py\n model = load_model(args.checkpoint, use_gpu)\n \n # Process Image\n image_tensor = process_image(args.image_path)\n \n top_probs, top_labels, top_flowers = predict(image_tensor, model, cat_to_name, args.top_k, use_gpu)\n \n # Print out result\n print_result(top_flowers, top_probs)\n\n \nif __name__ == '__main__': main()"
] |
[
[
"numpy.expand_dims",
"torch.load",
"torch.exp",
"torch.no_grad",
"torch.cuda.is_available",
"numpy.transpose",
"numpy.array"
]
] |
danabens/amazon-sagemaker-examples
|
[
"5133eb81be55564ab34fa6f5302cc84cd9b3988f"
] |
[
"reinforcement_learning/rl_deepracer_robomaker_coach_gazebo/src/training_worker.py"
] |
[
"import os\nimport shutil\nimport argparse\nimport json\nimport logging\nimport math\nimport numpy as np\nimport subprocess\nimport time\n\nfrom rl_coach.base_parameters import TaskParameters, DistributedCoachSynchronizationType, RunType\nfrom rl_coach import core_types\nfrom rl_coach.data_stores.data_store import SyncFiles\nfrom rl_coach.logger import screen\nfrom rl_coach.memories.backend.redis import RedisPubSubMemoryBackendParameters\nfrom rl_coach.utils import short_dynamic_import\n\nfrom markov import utils\nfrom markov.agent_ctrl.constants import ConfigParams\nfrom markov.agents.training_agent_factory import create_training_agent\nfrom markov.s3_boto_data_store import S3BotoDataStore, S3BotoDataStoreParameters\nfrom markov.s3_client import SageS3Client\nfrom markov.sagemaker_graph_manager import get_graph_manager\nfrom markov.utils_parse_model_metadata import parse_model_metadata\nfrom markov.samples.sample_collector import SampleCollector\n\nimport tensorflow as tf\ntf.logging.set_verbosity(tf.logging.DEBUG)\n\nlogger = utils.Logger(__name__, logging.INFO).get_logger()\n\nPRETRAINED_MODEL_DIR = \"./pretrained_checkpoint\"\nSM_MODEL_OUTPUT_DIR = os.environ.get(\"ALGO_MODEL_DIR\", \"/opt/ml/model\")\nCUSTOM_FILES_PATH = \"./custom_files\"\n\nif not os.path.exists(CUSTOM_FILES_PATH):\n os.makedirs(CUSTOM_FILES_PATH)\n\n\ndef training_worker(graph_manager, task_parameters, user_batch_size,\n user_episode_per_rollout):\n try:\n # initialize graph\n graph_manager.create_graph(task_parameters)\n\n # save initial checkpoint\n graph_manager.save_checkpoint()\n\n # training loop\n steps = 0\n\n graph_manager.setup_memory_backend()\n graph_manager.signal_ready()\n\n # To handle SIGTERM\n door_man = utils.DoorMan()\n\n while steps < graph_manager.improve_steps.num_steps:\n graph_manager.phase = core_types.RunPhase.TRAIN\n graph_manager.fetch_from_worker(graph_manager.agent_params.algorithm.num_consecutive_playing_steps)\n graph_manager.phase = core_types.RunPhase.UNDEFINED\n\n episodes_in_rollout = graph_manager.memory_backend.get_total_episodes_in_rollout()\n\n for level in graph_manager.level_managers:\n for agent in level.agents.values():\n agent.ap.algorithm.num_consecutive_playing_steps.num_steps = episodes_in_rollout\n agent.ap.algorithm.num_steps_between_copying_online_weights_to_target.num_steps = episodes_in_rollout\n\n if graph_manager.should_train():\n # Make sure we have enough data for the requested batches\n rollout_steps = graph_manager.memory_backend.get_rollout_steps()\n if any(rollout_steps.values()) <= 0:\n utils.log_and_exit(\"No rollout data retrieved from the rollout worker\",\n utils.SIMAPP_TRAINING_WORKER_EXCEPTION,\n utils.SIMAPP_EVENT_ERROR_CODE_500)\n\n episode_batch_size = user_batch_size if min(rollout_steps.values()) > user_batch_size else 2**math.floor(math.log(min(rollout_steps.values()), 2))\n # Set the batch size to the closest power of 2 such that we have at least two batches, this prevents coach from crashing\n # as batch size less than 2 causes the batch list to become a scalar which causes an exception\n for level in graph_manager.level_managers:\n for agent in level.agents.values():\n agent.ap.network_wrappers['main'].batch_size = episode_batch_size\n\n steps += 1\n\n graph_manager.phase = core_types.RunPhase.TRAIN\n graph_manager.train()\n graph_manager.phase = core_types.RunPhase.UNDEFINED\n\n # Check for Nan's in all agents\n rollout_has_nan = False\n for level in graph_manager.level_managers:\n for agent in level.agents.values():\n if np.isnan(agent.loss.get_mean()):\n rollout_has_nan = True\n if rollout_has_nan:\n utils.log_and_exit(\"NaN detected in loss function, aborting training.\",\n utils.SIMAPP_TRAINING_WORKER_EXCEPTION,\n utils.SIMAPP_EVENT_ERROR_CODE_500)\n\n if graph_manager.agent_params.algorithm.distributed_coach_synchronization_type == DistributedCoachSynchronizationType.SYNC:\n graph_manager.save_checkpoint()\n else:\n graph_manager.occasionally_save_checkpoint()\n\n # Clear any data stored in signals that is no longer necessary\n graph_manager.reset_internal_state()\n\n for level in graph_manager.level_managers:\n for agent in level.agents.values():\n agent.ap.algorithm.num_consecutive_playing_steps.num_steps = user_episode_per_rollout\n agent.ap.algorithm.num_steps_between_copying_online_weights_to_target.num_steps = user_episode_per_rollout\n\n if door_man.terminate_now:\n utils.log_and_exit(\"Received SIGTERM. Checkpointing before exiting.\",\n utils.SIMAPP_TRAINING_WORKER_EXCEPTION,\n utils.SIMAPP_EVENT_ERROR_CODE_500)\n graph_manager.save_checkpoint()\n break\n\n except ValueError as err:\n if utils.is_error_bad_ckpnt(err):\n utils.log_and_exit(\"User modified model: {}\".format(err),\n utils.SIMAPP_TRAINING_WORKER_EXCEPTION,\n utils.SIMAPP_EVENT_ERROR_CODE_400)\n else:\n utils.log_and_exit(\"An error occured while training: {}\".format(err),\n utils.SIMAPP_TRAINING_WORKER_EXCEPTION,\n utils.SIMAPP_EVENT_ERROR_CODE_500)\n except Exception as ex:\n utils.log_and_exit(\"An error occured while training: {}\".format(ex),\n utils.SIMAPP_TRAINING_WORKER_EXCEPTION,\n utils.SIMAPP_EVENT_ERROR_CODE_500)\n finally:\n graph_manager.data_store.upload_finished_file()\n\ndef start_redis_server():\n p = subprocess.Popen(\"redis-server /etc/redis/redis.conf\", shell=True, stderr=subprocess.STDOUT)\n time.sleep(5)\n if p.poll() is not None:\n raise RuntimeError(\"Could not start Redis server.\")\n else:\n print(\"Redis server started successfully!\")\n return p\n\ndef main():\n screen.set_use_colors(False)\n\n parser = argparse.ArgumentParser()\n parser.add_argument('-pk', '--preset_s3_key',\n help=\"(string) Name of a preset to download from S3\",\n type=str,\n required=False)\n parser.add_argument('-ek', '--environment_s3_key',\n help=\"(string) Name of an environment file to download from S3\",\n type=str,\n required=False)\n parser.add_argument('--model_metadata_s3_key',\n help=\"(string) Model Metadata File S3 Key\",\n type=str,\n required=False)\n parser.add_argument('-c', '--checkpoint-dir',\n help='(string) Path to a folder containing a checkpoint to write the model to.',\n type=str,\n default='./checkpoint')\n parser.add_argument('--pretrained-checkpoint-dir',\n help='(string) Path to a folder for downloading a pre-trained model',\n type=str,\n default=PRETRAINED_MODEL_DIR)\n parser.add_argument('--s3_bucket',\n help='(string) S3 bucket',\n type=str,\n default=os.environ.get(\"SAGEMAKER_SHARED_S3_BUCKET_PATH\", \"gsaur-test\"))\n parser.add_argument('--s3_prefix',\n help='(string) S3 prefix',\n type=str,\n default='sagemaker')\n parser.add_argument('--framework',\n help='(string) tensorflow or mxnet',\n type=str,\n default='tensorflow')\n parser.add_argument('--pretrained_s3_bucket',\n help='(string) S3 bucket for pre-trained model',\n type=str)\n parser.add_argument('--pretrained_s3_prefix',\n help='(string) S3 prefix for pre-trained model',\n type=str,\n default='sagemaker')\n parser.add_argument('--aws_region',\n help='(string) AWS region',\n type=str,\n default=os.environ.get(\"AWS_REGION\", \"us-east-1\"))\n\n args, _ = parser.parse_known_args()\n \n start_redis_server()\n\n s3_client = SageS3Client(bucket=args.s3_bucket, s3_prefix=args.s3_prefix, aws_region=args.aws_region)\n\n # Load the model metadata\n model_metadata_local_path = os.path.join(CUSTOM_FILES_PATH, 'model_metadata.json')\n utils.load_model_metadata(s3_client, args.model_metadata_s3_key, model_metadata_local_path)\n s3_client.upload_file(os.path.normpath(\"%s/model/model_metadata.json\" % args.s3_prefix), model_metadata_local_path)\n shutil.copy2(model_metadata_local_path, SM_MODEL_OUTPUT_DIR)\n\n success_custom_preset = False\n if args.preset_s3_key:\n preset_local_path = \"./markov/presets/preset.py\"\n success_custom_preset = s3_client.download_file(s3_key=args.preset_s3_key, local_path=preset_local_path)\n if not success_custom_preset:\n logger.info(\"Could not download the preset file. Using the default DeepRacer preset.\")\n else:\n preset_location = \"markov.presets.preset:graph_manager\"\n graph_manager = short_dynamic_import(preset_location, ignore_module_case=True)\n success_custom_preset = s3_client.upload_file(\n s3_key=os.path.normpath(\"%s/presets/preset.py\" % args.s3_prefix), local_path=preset_local_path)\n if success_custom_preset:\n logger.info(\"Using preset: %s\" % args.preset_s3_key)\n\n if not success_custom_preset:\n params_blob = os.environ.get('SM_TRAINING_ENV', '')\n if params_blob:\n params = json.loads(params_blob)\n sm_hyperparams_dict = params[\"hyperparameters\"]\n else:\n sm_hyperparams_dict = {}\n\n #! TODO each agent should have own config\n agent_config = {'model_metadata': model_metadata_local_path,\n ConfigParams.CAR_CTRL_CONFIG.value: {ConfigParams.LINK_NAME_LIST.value: [],\n ConfigParams.VELOCITY_LIST.value : {},\n ConfigParams.STEERING_LIST.value : {},\n ConfigParams.CHANGE_START.value : None,\n ConfigParams.ALT_DIR.value : None,\n ConfigParams.ACTION_SPACE_PATH.value : 'custom_files/model_metadata.json',\n ConfigParams.REWARD.value : None,\n ConfigParams.AGENT_NAME.value : 'racecar'}}\n\n agent_list = list()\n agent_list.append(create_training_agent(agent_config))\n\n graph_manager, robomaker_hyperparams_json = get_graph_manager(hp_dict=sm_hyperparams_dict,\n agent_list=agent_list,\n run_phase_subject=None)\n\n s3_client.upload_hyperparameters(robomaker_hyperparams_json)\n logger.info(\"Uploaded hyperparameters.json to S3\")\n\n # Attach sample collector to graph_manager only if sample count > 0\n max_sample_count = int(sm_hyperparams_dict.get(\"max_sample_count\", 0))\n if max_sample_count > 0:\n sample_collector = SampleCollector(s3_client=s3_client, s3_prefix=args.s3_prefix,\n max_sample_count=max_sample_count,\n sampling_frequency=int(sm_hyperparams_dict.get(\"sampling_frequency\", 1)))\n graph_manager.sample_collector = sample_collector\n\n host_ip_address = utils.get_ip_from_host()\n s3_client.write_ip_config(host_ip_address)\n logger.info(\"Uploaded IP address information to S3: %s\" % host_ip_address)\n use_pretrained_model = args.pretrained_s3_bucket and args.pretrained_s3_prefix\n if use_pretrained_model:\n # Handle backward compatibility\n _, _, version = parse_model_metadata(model_metadata_local_path)\n if float(version) < float(utils.SIMAPP_VERSION) and \\\n not utils.has_current_ckpnt_name(args.pretrained_s3_bucket, args.pretrained_s3_prefix, args.aws_region):\n utils.make_compatible(args.pretrained_s3_bucket, args.pretrained_s3_prefix,\n args.aws_region, SyncFiles.TRAINER_READY.value)\n #Select the optimal model for the starting weights\n utils.do_model_selection(s3_bucket=args.s3_bucket,\n s3_prefix=args.s3_prefix,\n region=args.aws_region)\n\n ds_params_instance_pretrained = S3BotoDataStoreParameters(aws_region=args.aws_region,\n bucket_names={'agent':args.pretrained_s3_bucket},\n base_checkpoint_dir=args.pretrained_checkpoint_dir,\n s3_folders={'agent':args.pretrained_s3_prefix})\n data_store_pretrained = S3BotoDataStore(ds_params_instance_pretrained, graph_manager, True)\n data_store_pretrained.load_from_store()\n\n memory_backend_params = RedisPubSubMemoryBackendParameters(redis_address=\"localhost\",\n redis_port=6379,\n run_type=str(RunType.TRAINER),\n channel=args.s3_prefix)\n\n graph_manager.memory_backend_params = memory_backend_params\n\n ds_params_instance = S3BotoDataStoreParameters(aws_region=args.aws_region,\n bucket_names={'agent':args.s3_bucket},\n base_checkpoint_dir=args.checkpoint_dir,\n s3_folders={'agent':args.s3_prefix})\n\n graph_manager.data_store_params = ds_params_instance\n\n graph_manager.data_store = S3BotoDataStore(ds_params_instance, graph_manager)\n\n task_parameters = TaskParameters()\n task_parameters.experiment_path = SM_MODEL_OUTPUT_DIR\n task_parameters.checkpoint_save_secs = 20\n if use_pretrained_model:\n task_parameters.checkpoint_restore_path = args.pretrained_checkpoint_dir\n task_parameters.checkpoint_save_dir = args.checkpoint_dir\n\n training_worker(\n graph_manager=graph_manager,\n task_parameters=task_parameters,\n user_batch_size=json.loads(robomaker_hyperparams_json)[\"batch_size\"],\n user_episode_per_rollout=json.loads(robomaker_hyperparams_json)[\"num_episodes_between_training\"]\n )\n\nif __name__ == '__main__':\n try:\n main()\n except Exception as ex:\n utils.log_and_exit(\"Training worker exited with exception: {}\".format(ex),\n utils.SIMAPP_TRAINING_WORKER_EXCEPTION,\n utils.SIMAPP_EVENT_ERROR_CODE_500)\n"
] |
[
[
"tensorflow.logging.set_verbosity"
]
] |
Gerryflap/progan_experiments
|
[
"8da6337bafc416ccd32289a998055def92408d23"
] |
[
"train_progan.py"
] |
[
"import math\nimport os\nimport time\nfrom datetime import date, datetime\n\nimport torchvision\nfrom torch.utils.data import DataLoader\nimport torchvision.transforms as transforms\nimport torch.nn.functional as F\nimport torch\n\nimport util\nfrom models import ProGANDiscriminator, ProGANGenerator\n\n# Algo\nfrom models_additional import ProGANAdditiveGenerator, ProGANResDiscriminator, ProGANResEncoder\n\n\ndef train(\n dataset,\n n_shifting_steps=20000,\n n_static_steps=20000,\n batch_size=16,\n latent_size=256,\n h_size=8,\n lr=0.001,\n gamma=750.0,\n max_upscales=4,\n network_scaling_factor=2.0,\n lrn_in_G=True,\n wn_in_G=False, # Enables weight norm (experimental)\n start_phase=0, # Can be used to start at a certain resolution. Only works well for whole numbers.\n num_workers=0,\n progress_bar=False,\n shuffle=True,\n n_steps_per_output=1000,\n use_special_output_network=False, # When true: use exponential running avg of weights for G output\n use_additive_net=False, # Use a network that adds the output of rgb layers together\n use_residual_discriminator=False,\n occasional_regularization=False, # Only apply regularization every 10 steps, but 10x as strongly\n max_h_size=None, # The maximum size of a hidden later output. None will default to 1e10, which is basically infinite,\n load_path=None, # Path to experiment folder. Can be used to load a checkpoint. It currently only sets the parameters, not hyperparameters!\n nn_interpolation=False, # Enables nearest neighbour interpolation as interpolation method for the training images.\n train_encoder=False,\n):\n\n if max_h_size is None:\n max_h_size = int(1e10)\n if num_workers == 0:\n print(\"Using num_workers = 0. It might be useful to add more workers if your machine allows for it.\")\n\n n_static_steps_taken = 0\n n_shifting_steps_taken = 0\n static = True\n\n\n loader = DataLoader(dataset, batch_size=batch_size, shuffle=shuffle, num_workers=num_workers, drop_last=True)\n\n if use_additive_net:\n G = ProGANAdditiveGenerator(latent_size, max_upscales, 4, local_response_norm=lrn_in_G,\n scaling_factor=network_scaling_factor, max_h_size=max_h_size, weight_norm=wn_in_G)\n else:\n G = ProGANGenerator(latent_size, max_upscales, 4, local_response_norm=lrn_in_G,\n scaling_factor=network_scaling_factor, max_h_size=max_h_size, weight_norm=wn_in_G)\n\n if use_residual_discriminator:\n D = ProGANResDiscriminator(max_upscales, h_size, scaling_factor=network_scaling_factor, max_h_size=max_h_size)\n else:\n D = ProGANDiscriminator(max_upscales, h_size, scaling_factor=network_scaling_factor, max_h_size=max_h_size)\n\n encoder = None\n if train_encoder:\n encoder = ProGANResEncoder(latent_size, max_upscales, h_size, scaling_factor=network_scaling_factor, max_h_size=max_h_size)\n encoder = encoder.cuda()\n\n G = G.cuda()\n D = D.cuda()\n\n if use_special_output_network:\n if use_additive_net:\n G_out = ProGANAdditiveGenerator(latent_size, max_upscales, 4, local_response_norm=lrn_in_G,\n scaling_factor=network_scaling_factor, max_h_size=max_h_size, weight_norm=wn_in_G)\n else:\n G_out = ProGANGenerator(latent_size, max_upscales, 4, local_response_norm=lrn_in_G,\n scaling_factor=network_scaling_factor, max_h_size=max_h_size, weight_norm=wn_in_G)\n G_out = G_out.cuda()\n # Set the weights of G_out to those of G\n util.update_output_network(G_out, G, factor=0.0)\n else:\n G_out = G\n\n G_opt = torch.optim.Adam(G.parameters(), lr=lr, betas=(0, 0.99))\n D_opt = torch.optim.Adam(D.parameters(), lr=lr, betas=(0, 0.99))\n enc_opt = None\n if encoder is not None:\n enc_opt = torch.optim.Adam(encoder.parameters(), lr=lr, betas=(0, 0.99))\n\n if load_path is not None:\n info = util.load_checkpoint(os.path.join(load_path, \"checkpoint.pt\"), G, G_out, D, G_opt, D_opt, encoder, enc_opt)\n n_static_steps_taken = info[\"n_stat\"]\n n_shifting_steps_taken = info[\"n_shift\"]\n static = info[\"static\"]\n\n if n_static_steps_taken - n_static_steps >= n_shifting_steps_taken:\n static = False\n print(\"Switching to shift\")\n\n\n output_path = load_path\n else:\n now = datetime.now()\n\n output_path = os.path.join(\"results\", \"exp_%s\"%(now.strftime(\"%Y%m%d%H%M\")))\n os.mkdir(output_path)\n if encoder is not None:\n os.mkdir(os.path.join(output_path, \"encoding\"))\n info = None\n\n first_print = True\n\n if info is None or info[\"test_z\"] is None:\n test_z = torch.normal(0, 1, (16, latent_size), device=\"cuda\")\n else:\n test_z = info[\"test_z\"]\n\n if info is None or info[\"test_x\"] is None:\n test_x = None\n else:\n test_x = info[\"test_x\"]\n last_print = None\n\n while True:\n for batch in loader:\n if static:\n n_static_steps_taken += 1\n else:\n n_shifting_steps_taken += 1\n\n phase = min(start_phase + (n_shifting_steps_taken / n_shifting_steps), max_upscales)\n\n x, _ = batch\n x = x.cuda()\n\n if test_x is None:\n test_x = x\n if nn_interpolation:\n x = F.interpolate(x, 4 * (2 ** (math.ceil(phase))))\n else:\n x = F.interpolate(x, 4 * (2 ** (math.ceil(phase))), mode='bilinear')\n # =========== Train D ========\n D_opt.zero_grad()\n\n d_real_outputs = D(x, phase=phase)\n\n z = torch.normal(0, 1, (batch_size, latent_size), device=\"cuda\")\n fake_batch = G(z, phase=phase)\n\n # Compute outputs for fake images\n d_fake_outputs = D(fake_batch, phase=phase)\n\n # Compute losses\n d_loss = (d_fake_outputs - d_real_outputs).mean()\n\n if (not occasional_regularization) or (n_static_steps_taken % n_static_steps == 0)%10 == 0:\n size = [s if i == 0 else 1 for i, s in enumerate(fake_batch.size())]\n eps = torch.rand(size).cuda()\n x_hat = eps * x + (1.0 - eps) * fake_batch.detach()\n x_hat.requires_grad = True\n dis_out = D(x_hat, phase=phase)\n grad_outputs = torch.ones_like(dis_out)\n grad = torch.autograd.grad(dis_out, x_hat, create_graph=True, only_inputs=True, grad_outputs=grad_outputs)[\n 0]\n grad_norm = grad.norm(2, dim=list(range(1, len(grad.size())))) ** 2\n d_grad_loss = (torch.pow(grad_norm - gamma, 2) / (gamma ** 2)).mean()\n\n d_reg = 10.0 * d_grad_loss\n\n drift_loss = (d_real_outputs ** 2).mean() + (d_fake_outputs ** 2).mean()\n d_reg += 0.001 * drift_loss\n\n if occasional_regularization:\n d_reg = 10.0 * d_reg\n d_loss_total = d_loss + d_reg\n else:\n d_loss_total = d_loss\n\n d_loss_total.backward()\n\n # Update weights\n D_opt.step()\n\n # ======== Train G ========\n # Make gradients for G zero\n G_opt.zero_grad()\n\n # Generate a batch of fakes\n z = torch.normal(0, 1, (batch_size, latent_size), device=\"cuda\")\n fake_batch = G(z, phase=phase)\n\n # Compute loss for G, images should become more 'real' to the discriminator\n g_loss = -D(fake_batch, phase=phase).mean()\n g_loss.backward()\n\n\n if encoder is not None:\n enc_opt.zero_grad()\n z, means, log_vars = encoder(x, phase=phase)\n # l_prior = -0.5 * torch.sum(1 + log_vars - torch.pow(means, 2) - torch.exp(log_vars))/batch_size\n l_prior = torch.mean(z.mean(dim=0)**2.0 + (z.std(dim=0) - 1.0) **2.0)\n x_recon = G(z, phase=phase)\n # l_recon = torch.nn.functional.mse_loss(x_recon, x, reduction=\"sum\")/batch_size\n l_recon = torch.nn.functional.mse_loss(x_recon, x)\n loss = l_prior + l_recon\n loss.backward()\n enc_opt.step()\n\n G_opt.step()\n\n\n if use_special_output_network:\n util.update_output_network(G_out, G)\n\n if progress_bar:\n percent = ((n_shifting_steps_taken + n_static_steps_taken) % n_steps_per_output) / (\n n_steps_per_output / 100.0)\n print(\"%03d %% till image generation...\" % int(percent), end=\"\\r\", flush=True)\n\n if (n_shifting_steps_taken + n_static_steps_taken) % n_steps_per_output == 0:\n if progress_bar:\n print(\" \"*50, end=\"\\r\", flush=True)\n print(\"Print at \", n_static_steps_taken, n_shifting_steps_taken, phase)\n if first_print:\n torchvision.utils.save_image(x, os.path.join(output_path, \"reals.png\"))\n first_print = False\n last_print = time.time()\n else:\n current_time = time.time()\n diff = current_time - last_print\n per_step = diff/n_steps_per_output\n last_print = current_time\n print(\"Seconds since last print: %.2f, seconds per step: %.5f\"%(diff, per_step))\n\n print(\"D loss: \", d_loss.detach().cpu().item())\n print(\"D loss total: \", d_loss_total.detach().cpu().item())\n print(\"G loss: \", g_loss.detach().cpu().item())\n if encoder:\n print(\"l_prior: \", l_prior.detach().cpu().item())\n print(\"l_recon: \", l_recon.detach().cpu().item())\n\n print()\n\n test_batch = G_out(test_z, phase=phase)\n torchvision.utils.save_image(test_batch, os.path.join(output_path, \"results_%d_%d_%.3f.png\" % (\n n_static_steps_taken, n_shifting_steps_taken, phase)))\n\n if encoder is not None:\n x_res = F.interpolate(test_x, 4 * (2 ** (math.ceil(phase))), mode='bilinear')\n test_recons = G_out(encoder(x_res, phase=phase)[0], phase=phase)\n torchvision.utils.save_image(torch.cat([x_res, test_recons], dim=0),\n os.path.join(output_path, \"encoding\", \"results_%d_%d_%.3f.png\" % (n_static_steps_taken, n_shifting_steps_taken, phase)),\n nrow=batch_size)\n\n\n torch.save(G, os.path.join(output_path, \"G.pt\"))\n info = {\n \"n_stat\": n_static_steps_taken,\n \"n_shift\": n_shifting_steps_taken,\n \"static\": static,\n \"test_z\": test_z,\n \"test_x\": test_x,\n }\n util.save_checkpoint(os.path.join(output_path, \"checkpoint.pt\"), G, G_out, D, G_opt, D_opt, info, enc=encoder, enc_opt=enc_opt)\n\n if static and (n_static_steps_taken % n_static_steps == 0):\n print(\"Switching to shift\")\n static = False\n elif (not static) and (n_shifting_steps_taken % n_shifting_steps == 0):\n print(\"Switching to static\")\n static = True\n\n\nif __name__ == \"__main__\":\n from torchvision.datasets import CelebA\n\n dataset = CelebA(\"/run/media/gerben/LinuxData/data/\", download=False,\n transform=transforms.Compose([\n transforms.CenterCrop(178),\n transforms.Resize(128),\n transforms.ToTensor()\n ])\n )\n\n from image_dataset import ImageDataset\n\n dataset2 = ImageDataset(\"/run/media/gerben/LinuxData/data/frgc_cropped\",\n transform=transforms.Compose([\n transforms.ToTensor()\n ])\n )\n\n dataset3 = ImageDataset(\"/run/media/gerben/LinuxData/data/ffhq_thumbnails/thumbnails128x128\",\n transform=transforms.Compose([\n transforms.ToTensor()\n ])\n )\n\n dataset4 = ImageDataset(\"/run/media/gerben/LinuxData/data/celeba/cropped_faces64\",\n transform=transforms.Compose([\n transforms.ToTensor()\n ])\n )\n\n train(dataset4,\n n_shifting_steps=10000,\n n_static_steps=10000,\n batch_size=16,\n latent_size=64,\n h_size=64,\n lr=0.001,\n gamma=750.0,\n max_upscales=4,\n network_scaling_factor=2.0,\n lrn_in_G=True,\n wn_in_G=False,\n start_phase=0,\n progress_bar=True,\n num_workers=4,\n n_steps_per_output=1000,\n use_special_output_network=True,\n use_additive_net=False,\n use_residual_discriminator=False,\n max_h_size=256,\n train_encoder=False\n )\n"
] |
[
[
"torch.normal",
"torch.cat",
"torch.utils.data.DataLoader",
"torch.nn.functional.mse_loss",
"torch.pow",
"torch.rand",
"torch.autograd.grad",
"torch.ones_like"
]
] |
smarttourist/Number-plate-detection-system-backend
|
[
"dd0d200e23fa71972395f01ae07d937190cc1aa2"
] |
[
"detect.py"
] |
[
"\nimport argparse\nimport cv2\nimport numpy as np\nfrom keras.models import Sequential, load_model\nfrom segmentImage import segmentImage\nwidth=608\nheight=608\nconfThreshold = 0.5\nnmsThreshold = 0.4\n\nparser = argparse.ArgumentParser(description='Object Detection using YOLO in OPENCV')\nparser.add_argument('--image', help='Path to image file.')\nargs = parser.parse_args()\noutputFile = args.image[:-4] + '_yolo_out_py.jpg'\noutputPlate = args.image[:-4] + '_plate.jpg'\nclassesFile = \"classes.names\"\n\nclasses = None\nwith open(classesFile, 'rt') as f:\n classes = f.read().rstrip('\\n').split('\\n')\n\npredConf=\"darknet-yolov3.cfg\"\nweights='lapi.weights'\n\nmodel = load_model('cnn_classifier.h5')\n\n\npredictor = cv2.dnn.readNetFromDarknet(predConf, weights)\npredictor.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV)\npredictor.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU)\n\ncap = cv2.VideoCapture(args.image)\n\ndef drawPred(classId, conf, left, top, right, bottom):\n # Draw a bounding box.\n # cv.rectangle(frame, (left, top), (right, bottom), (255, 178, 50), 3)\n cv2.rectangle(img, (left, top), (right, bottom), (0, 255, 0), 3)\n plate = img[top:bottom, left:right]\n #cv2.imshow(\"CROPPED\",plate)\n predResults=segmentImage(plate)\n cv2.imwrite(outputPlate, plate.astype(np.uint8))\n print(predResults)\n return predResults\n label = '%.2f' % conf\n\n # Get the label for the class name and its confidence\n '''\n if classes:\n assert(classId < len(classes))\n label = '%s:%s' % (classes[classId], label)\n\n #Display the label at the top of the bounding box\n labelSize, baseLine = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)\n top = max(top, labelSize[1])\n cv2.rectangle(img, (left, top - round(1.5*labelSize[1])), (left + round(1.5*labelSize[0]), top + baseLine), (0, 0, 255), cv2.FILLED)\n #cv.rectangle(frame, (left, top - round(1.5*labelSize[1])), (left + round(1.5*labelSize[0]), top + baseLine), (255, 255, 255), cv.FILLED)\n cv2.putText(img, label, (left, top), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0,0,0), 2)\n '''\ndef process(img,res):\n frameHeight=img.shape[0]\n frameWidth=img.shape[1]\n classIds = []\n confidences = []\n boxes = []\n for out in res:\n #print(\"out.shape : \", out.shape)\n for detection in out:\n #if detection[4]>0.001:\n scores = detection[5:]\n classId = np.argmax(scores)\n #if scores[classId]>confThreshold:\n confidence = scores[classId]\n #print(detection)\n #if detection[4]>confThreshold:\n #print(detection[4], \" - \", scores[classId], \" - th : \", confThreshold)\n #print(detection)\n if confidence > confThreshold:\n center_x = int(detection[0] * frameWidth)\n center_y = int(detection[1] * frameHeight)\n width = int(detection[2] * frameWidth)\n height = int(detection[3] * frameHeight)\n left = int(center_x - width / 2)\n top = int(center_y - height / 2)\n classIds.append(classId)\n confidences.append(float(confidence))\n\n boxes.append([left, top, width, height])\n\n indices = cv2.dnn.NMSBoxes(boxes, confidences, confThreshold, nmsThreshold)\n for i in indices:\n\n i = i[0]\n box = boxes[i]\n left = box[0]\n top = box[1]\n width = box[2]\n height = box[3]\n drawPred(classIds[i], confidences[i], left-4, top-4, left + width+4, top + height+4)\n\n\ndef OutputNames(predictor):\n # Get the names of all the layers in the network\n layersNames = predictor.getLayerNames()\n\n # Get the names of the output layers, i.e. the layers with unconnected outputs\n return [layersNames[i[0] - 1] for i in predictor.getUnconnectedOutLayers()]\n\n\nret, img= cap.read()\nwhile(True):\n if (ret):\n\n blob = cv2.dnn.blobFromImage(img, 1/255, (width, height), [0,0,0], 1, crop=False)\n predictor.setInput(blob)\n\n res=predictor.forward(OutputNames(predictor))\n process(img,res)\n cv2.imshow(\"IMG\", img)\n if (args.image):\n cv2.imwrite(outputFile, img.astype(np.uint8))\n\n k = cv2.waitKey(0)\n if (k == 27):\n cv2.destroyAllWindows()\n break\n\n"
] |
[
[
"numpy.argmax"
]
] |
hainow/seq2seq
|
[
"3fb9b56a32acbc0c52384842b0cb7c3c3e64729c"
] |
[
"seq2seq/test/models_test.py"
] |
[
"# -*- coding: utf-8 -*-\n# Copyright 2017 Google 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\"\"\"Tests for Models\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nfrom collections import namedtuple\n\nimport yaml\nimport numpy as np\nimport tensorflow as tf\n\nfrom seq2seq.data import vocab, input_pipeline\nfrom seq2seq.training import utils as training_utils\nfrom seq2seq.test import utils as test_utils\nfrom seq2seq.models import BasicSeq2Seq, AttentionSeq2Seq\n\nTEST_PARAMS = yaml.load(\"\"\"\nembedding.dim: 5\nencoder.params:\n rnn_cell:\n dropout_input_keep_prob: 0.8\n num_layers: 2\n residual_connections: True,\n cell_class: LSTMCell\n cell_params:\n num_units: 4\ndecoder.params:\n rnn_cell:\n num_layers: 2\n cell_class: LSTMCell\n cell_params:\n num_units: 4\n\"\"\")\n\n\nclass EncoderDecoderTests(tf.test.TestCase):\n \"\"\"Base class for EncoderDecoder tests. Tests for specific classes should\n inherit from this and tf.test.TestCase.\n \"\"\"\n\n def setUp(self):\n super(EncoderDecoderTests, self).setUp()\n tf.logging.set_verbosity(tf.logging.INFO)\n self.batch_size = 2\n self.input_depth = 4\n self.sequence_length = 10\n\n # Create vocabulary\n self.vocab_list = [str(_) for _ in range(10)]\n self.vocab_list += [\"笑う\", \"泣く\", \"了解\", \"はい\", \"^_^\"]\n self.vocab_size = len(self.vocab_list)\n self.vocab_file = test_utils.create_temporary_vocab_file(self.vocab_list)\n self.vocab_info = vocab.get_vocab_info(self.vocab_file.name)\n\n tf.contrib.framework.get_or_create_global_step()\n\n def tearDown(self):\n self.vocab_file.close()\n\n def create_model(self, _mode, _params=None):\n \"\"\"Creates model class to be tested. Subclasses must implement this method.\n \"\"\"\n self.skipTest(\"Base module should not be tested.\")\n\n def _create_example(self):\n \"\"\"Creates example data for a test\"\"\"\n source = np.random.randn(self.batch_size, self.sequence_length,\n self.input_depth)\n source_len = np.random.randint(0, self.sequence_length, [self.batch_size])\n target_len = np.random.randint(0, self.sequence_length * 2,\n [self.batch_size])\n target = np.random.randn(self.batch_size,\n np.max(target_len), self.input_depth)\n labels = np.random.randint(0, self.vocab_size,\n [self.batch_size, np.max(target_len) - 1])\n\n example_ = namedtuple(\n \"Example\", [\"source\", \"source_len\", \"target\", \"target_len\", \"labels\"])\n return example_(source, source_len, target, target_len, labels)\n\n def _test_pipeline(self, mode, params=None):\n \"\"\"Helper function to test the full model pipeline.\n \"\"\"\n # Create source and target example\n source_len = self.sequence_length + 5\n target_len = self.sequence_length + 10\n source = \" \".join(np.random.choice(self.vocab_list, source_len))\n target = \" \".join(np.random.choice(self.vocab_list, target_len))\n sources_file, targets_file = test_utils.create_temp_parallel_data(\n sources=[source], targets=[target])\n\n # Build model graph\n model = self.create_model(mode, params)\n input_pipeline_ = input_pipeline.ParallelTextInputPipeline(\n params={\n \"source_files\": [sources_file.name],\n \"target_files\": [targets_file.name]\n },\n mode=mode)\n input_fn = training_utils.create_input_fn(\n pipeline=input_pipeline_, batch_size=self.batch_size)\n features, labels = input_fn()\n fetches = model(features, labels, None)\n fetches = [_ for _ in fetches if _ is not None]\n\n with self.test_session() as sess:\n sess.run(tf.global_variables_initializer())\n sess.run(tf.local_variables_initializer())\n sess.run(tf.tables_initializer())\n with tf.contrib.slim.queues.QueueRunners(sess):\n fetches_ = sess.run(fetches)\n print(\"Feches = {}\".format(fetches_))\n\n sources_file.close()\n targets_file.close()\n\n return model, fetches_\n\n def test_train(self):\n model, fetches_ = self._test_pipeline(tf.contrib.learn.ModeKeys.TRAIN)\n predictions_, loss_, _ = fetches_\n\n target_len = self.sequence_length + 10 + 2\n max_decode_length = model.params[\"target.max_seq_len\"]\n expected_decode_len = np.minimum(target_len, max_decode_length)\n\n np.testing.assert_array_equal(predictions_[\"logits\"].shape, [\n self.batch_size, expected_decode_len - 1,\n model.target_vocab_info.total_size\n ])\n np.testing.assert_array_equal(predictions_[\"losses\"].shape,\n [self.batch_size, expected_decode_len - 1])\n np.testing.assert_array_equal(predictions_[\"predicted_ids\"].shape,\n [self.batch_size, expected_decode_len - 1])\n self.assertFalse(np.isnan(loss_))\n\n def test_infer(self):\n model, fetches_ = self._test_pipeline(tf.contrib.learn.ModeKeys.INFER)\n predictions_, = fetches_\n pred_len = predictions_[\"predicted_ids\"].shape[1]\n\n np.testing.assert_array_equal(predictions_[\"logits\"].shape, [\n self.batch_size, pred_len, model.target_vocab_info.total_size\n ])\n np.testing.assert_array_equal(predictions_[\"predicted_ids\"].shape,\n [self.batch_size, pred_len])\n\n def test_infer_beam_search(self):\n self.batch_size = 1\n beam_width = 10\n model, fetches_ = self._test_pipeline(\n mode=tf.contrib.learn.ModeKeys.INFER,\n params={\"inference.beam_search.beam_width\": 10})\n predictions_, = fetches_\n pred_len = predictions_[\"predicted_ids\"].shape[1]\n\n vocab_size = model.target_vocab_info.total_size\n np.testing.assert_array_equal(predictions_[\"predicted_ids\"].shape,\n [1, pred_len, beam_width])\n np.testing.assert_array_equal(\n predictions_[\"beam_search_output.beam_parent_ids\"].shape,\n [1, pred_len, beam_width])\n np.testing.assert_array_equal(\n predictions_[\"beam_search_output.scores\"].shape,\n [1, pred_len, beam_width])\n np.testing.assert_array_equal(\n predictions_[\"beam_search_output.original_outputs.predicted_ids\"].shape,\n [1, pred_len, beam_width])\n np.testing.assert_array_equal(\n predictions_[\"beam_search_output.original_outputs.logits\"].shape,\n [1, pred_len, beam_width, vocab_size])\n\n\nclass TestBasicSeq2Seq(EncoderDecoderTests):\n \"\"\"Tests the seq2seq.models.BasicSeq2Seq model.\n \"\"\"\n\n def setUp(self):\n super(TestBasicSeq2Seq, self).setUp()\n\n def create_model(self, mode, params=None):\n params_ = BasicSeq2Seq.default_params().copy()\n params_.update(TEST_PARAMS)\n params_.update({\n \"vocab_source\": self.vocab_file.name,\n \"vocab_target\": self.vocab_file.name,\n \"bridge.class\": \"PassThroughBridge\"\n })\n params_.update(params or {})\n return BasicSeq2Seq(params=params_, mode=mode)\n\n\nclass TestAttentionSeq2Seq(EncoderDecoderTests):\n \"\"\"Tests the seq2seq.models.AttentionSeq2Seq model.\n \"\"\"\n\n def setUp(self):\n super(TestAttentionSeq2Seq, self).setUp()\n self.encoder_rnn_cell = tf.contrib.rnn.LSTMCell(32)\n self.decoder_rnn_cell = tf.contrib.rnn.LSTMCell(32)\n self.attention_dim = 128\n\n def create_model(self, mode, params=None):\n params_ = AttentionSeq2Seq.default_params().copy()\n params_.update(TEST_PARAMS)\n params_.update({\n \"source.reverse\": True,\n \"vocab_source\": self.vocab_file.name,\n \"vocab_target\": self.vocab_file.name,\n })\n params_.update(params or {})\n return AttentionSeq2Seq(params=params_, mode=mode)\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n"
] |
[
[
"numpy.minimum",
"tensorflow.local_variables_initializer",
"numpy.random.choice",
"numpy.isnan",
"tensorflow.test.main",
"numpy.testing.assert_array_equal",
"numpy.max",
"tensorflow.global_variables_initializer",
"tensorflow.contrib.rnn.LSTMCell",
"numpy.random.randn",
"tensorflow.logging.set_verbosity",
"tensorflow.contrib.framework.get_or_create_global_step",
"tensorflow.contrib.slim.queues.QueueRunners",
"tensorflow.tables_initializer",
"numpy.random.randint"
]
] |
VEXAS-team/VEXAS-DR2
|
[
"a10e363f7588354884b5f155e87b2ca40b65d482"
] |
[
"classification/models/factory.py"
] |
[
"import os\nimport numpy as np\n\nfrom models.models import CatBoost, kNN, ANNClassifier, LogRegression\nfrom log.plot import (plot_confusion_matrix, probability_threshold,\n regression_coefficients)\nfrom settings import MODELS_PATH, CLASSES\n\n\n\nclass ModelFactory:\n _single_models = {\n 'kNN': kNN,\n 'ANN': ANNClassifier,\n 'CatBoost': CatBoost,\n }\n @classmethod\n def get(cls, model_name):\n return cls._single_models[model_name]\n\n\n\n\nclass Ensemble:\n def __init__(self):\n self.out_of_fold_predictions = {'valid': [], 'test': []}\n self.single_models = []\n self.single_models_classes = []\n\n def single_model(self, model_name, model_id, num_input_features, num_output_classes, model_save_path, **aux_params):\n model = ModelFactory.get(model_name)\n return model(model_id, num_input_features, num_output_classes, model_save_path, **aux_params)\n\n def meta_model(self, model_id, model_save_path):\n return LogRegression(model_id, model_save_path)\n\n\n def iteration(self, model_name, model_id, X, y, classes, features,\n model_save_path, features_short=None, additinal_labels=False, **aux_params):\n num_input_features = len(features)\n num_output_classes = len(classes)\n\n model = self.single_model(model_name, model_id, num_input_features, num_output_classes, model_save_path, **aux_params)\n model.fit(X['train'], y['train'], X['valid'], y['valid'])\n if additinal_labels:\n preds_add = np.squeeze(model.predict(X['add']))\n agreed_filter = y['add'].to_numpy() == np.argmax(preds_add, axis=-1)\n X_add_agreed = X['add'][agreed_filter]\n y_add_agreed = y['add'][agreed_filter]\n\n X_train = X['train'].append(X_add_agreed, ignore_index=True)\n y_train = y['train'].append(y_add_agreed, ignore_index=True)\n model.fit(X_train, y_train, X['valid'], y['valid'])\n model.load()\n if features_short is not None:\n model.explain(X['train'], y['train'], features_short, classes)\n else:\n model.explain(X['test'], y['train'], features, classes)\n\n self.out_of_fold_predictions['valid'].append(model.predict(X['valid']))\n self.out_of_fold_predictions['test'].append(model.predict(X['test']))\n\n self.log_iteration_results(model, y['test'], model.predict(X['test']), classes)\n self.single_models.append(model_id)\n self.single_models_classes.append(classes)\n\n\n def stacked_iteration(self, model_id, y, model_save_path):\n metamodel = self.meta_model(model_id, model_save_path)\n stacked_val_predictions = np.hstack(self.out_of_fold_predictions['valid'])\n stacked_test_predictions = np.hstack(self.out_of_fold_predictions['test'])\n metamodel.fit(stacked_val_predictions, y['valid'])\n\n self.log_stacking_results(metamodel, y['test'],\n metamodel.predict(stacked_test_predictions))\n\n def log_iteration_results(self, model, labels, predictions, classes=CLASSES):\n save_path = model.model_path\n plot_confusion_matrix(labels, predictions, classes, model.model_id, save_path=save_path)\n probability_threshold(labels, predictions, save_path=save_path)\n\n def log_stacking_results(self, model, labels, predictions, classes=CLASSES):\n self.log_iteration_results(model, labels, predictions, classes)\n regression_coefficients(model, self.single_models,\n self.single_models_classes,\n model.model_path, classes=CLASSES)\n"
] |
[
[
"numpy.hstack",
"numpy.argmax"
]
] |
finagle29/DBSP_DRP
|
[
"d2f869f85e1425507dbc84e4e76fa44a6784f9d1"
] |
[
"dbsp_drp/show_spectrum.py"
] |
[
"import argparse\nimport os\nfrom typing import List, Optional\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom astropy.io import fits\n\ndef parser(options: Optional[List[str]] = None) -> argparse.Namespace:\n argparser = argparse.ArgumentParser(description=\"Script to plot DBSP spectra\",\n formatter_class=argparse.RawTextHelpFormatter)\n\n argparser.add_argument(\"fname\", type=str, help=\"path to target_a.fits file\")\n\n argparser.add_argument(\"--extension\", type=str, default=\"SPLICED\",\n help=\"Extension name or number\")\n\n return argparser.parse_args() if options is None else argparser.parse_args(options)\n\ndef main(args: argparse.Namespace) -> None:\n with fits.open(args.fname) as hdul:\n exts = [hdu.name for hdu in hdul if hdu.name != \"PRIMARY\"]\n if args.extension.upper() in exts:\n ext = args.extension\n else:\n try:\n ext = int(args.extension)\n if ext == 0 or ext >= len(hdul) or ext <= -len(hdul):\n # check for negative oob\n raise IndexError(f\"Extension index {ext} out of range: \"\n f\"must be between 1 and {len(hdul) - 1} inclusive \"\n f\"(or between -1 and {-len(hdul)+1} inclusive to \"\n \"index from the end).\")\n except ValueError:\n raise LookupError(f\"Extension '{args.extension}' not found in \"\n f\"{args.fname}, and cannot be cast to an integer.\\n\"\n f\"\\tValid extensions present in {args.fname} are {exts}.\")\n spectrum = hdul[ext].data\n basename = os.path.splitext(os.path.basename(args.fname))[0]\n plot(spectrum, f\"{basename}[{hdul[ext].name}]\")\n\ndef plot(spec: fits.FITS_rec, title: str) -> None:\n \"\"\"\n Plots spectrum and error with sensible y-scale limits.\n\n Args:\n spec (fits.FITS_rec): Spectrum to plot\n \"\"\"\n plt.step(spec['wave'], spec['flux'], c='k', label='spectrum')\n plt.step(spec['wave'], spec['sigma'], c='gray', label='error')\n\n plt.xlabel(r\"Wavelength ($\\AA$)\")\n plt.ylabel(r\"Flux ($10^{-17}\\mathrm{erg}/\\mathrm{s}/\\mathrm{cm}^2/\\AA$)\")\n\n top1 = np.abs(np.percentile(spec['flux'], 95)) * 1.5\n top2 = np.max(spec['flux'][spec['wave'] > 4000]) * 1.1\n top = max(top1, top2)\n bottom = -0.05 * top\n\n plt.ylim(bottom, top)\n plt.legend()\n plt.title(title)\n plt.show()\n"
] |
[
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.title",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.step",
"numpy.percentile",
"numpy.max",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
]
] |
ankandrew/pytorch-cifar
|
[
"6ff4ff2a7f41ec68bf597578df83bb77ff41c6db"
] |
[
"models/shufflenet.py"
] |
[
"'''ShuffleNet in PyTorch.\n\nSee the paper \"ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile Devices\" for more details.\n'''\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom .settings import CFG\n\n\nclass ShuffleBlock(nn.Module):\n def __init__(self, groups):\n super(ShuffleBlock, self).__init__()\n self.groups = groups\n\n def forward(self, x):\n '''Channel shuffle: [N,C,H,W] -> [N,g,C/g,H,W] -> [N,C/g,g,H,w] -> [N,C,H,W]'''\n N,C,H,W = x.size()\n g = self.groups\n return x.view(N,g,C//g,H,W).permute(0,2,1,3,4).reshape(N,C,H,W)\n\n\nclass Bottleneck(nn.Module):\n def __init__(self, in_planes, out_planes, stride, groups):\n super(Bottleneck, self).__init__()\n self.stride = stride\n\n mid_planes = out_planes/4\n g = 1 if in_planes==24 else groups\n self.conv1 = nn.Conv2d(in_planes, mid_planes, kernel_size=1, groups=g, bias=False)\n self.bn1 = nn.BatchNorm2d(mid_planes)\n self.shuffle1 = ShuffleBlock(groups=g)\n self.conv2 = nn.Conv2d(mid_planes, mid_planes, kernel_size=3, stride=stride, padding=1, groups=mid_planes, bias=False)\n self.bn2 = nn.BatchNorm2d(mid_planes)\n self.conv3 = nn.Conv2d(mid_planes, out_planes, kernel_size=1, groups=groups, bias=False)\n self.bn3 = nn.BatchNorm2d(out_planes)\n\n self.shortcut = nn.Sequential()\n if stride == 2:\n self.shortcut = nn.Sequential(nn.AvgPool2d(3, stride=2, padding=1))\n\n def forward(self, x):\n out = F.relu(self.bn1(self.conv1(x)))\n out = self.shuffle1(out)\n out = F.relu(self.bn2(self.conv2(out)))\n out = self.bn3(self.conv3(out))\n res = self.shortcut(x)\n out = F.relu(torch.cat([out,res], 1)) if self.stride==2 else F.relu(out+res)\n return out\n\n\nclass ShuffleNet(nn.Module):\n def __init__(self, cfg):\n super(ShuffleNet, self).__init__()\n out_planes = cfg['out_planes']\n num_blocks = cfg['num_blocks']\n groups = cfg['groups']\n\n self.conv1 = nn.Conv2d(CFG.INPUT_CHANNELS, 24, kernel_size=1, bias=False)\n self.bn1 = nn.BatchNorm2d(24)\n self.in_planes = 24\n self.layer1 = self._make_layer(out_planes[0], num_blocks[0], groups)\n self.layer2 = self._make_layer(out_planes[1], num_blocks[1], groups)\n self.layer3 = self._make_layer(out_planes[2], num_blocks[2], groups)\n self.linear = nn.Linear(out_planes[2], CFG.NUM_CLASSES)\n\n def _make_layer(self, out_planes, num_blocks, groups):\n layers = []\n for i in range(num_blocks):\n stride = 2 if i == 0 else 1\n cat_planes = self.in_planes if i == 0 else 0\n layers.append(Bottleneck(self.in_planes, out_planes-cat_planes, stride=stride, groups=groups))\n self.in_planes = out_planes\n return nn.Sequential(*layers)\n\n def forward(self, x):\n out = F.relu(self.bn1(self.conv1(x)))\n out = self.layer1(out)\n out = self.layer2(out)\n out = self.layer3(out)\n out = F.avg_pool2d(out, 4)\n out = out.view(out.size(0), -1)\n out = self.linear(out)\n return out\n\n\ndef ShuffleNetG2():\n cfg = {\n 'out_planes': [200,400,800],\n 'num_blocks': [4,8,4],\n 'groups': 2\n }\n return ShuffleNet(cfg)\n\ndef ShuffleNetG3():\n cfg = {\n 'out_planes': [240,480,960],\n 'num_blocks': [4,8,4],\n 'groups': 3\n }\n return ShuffleNet(cfg)\n\n\ndef test():\n net = ShuffleNetG2()\n x = torch.randn(1,3,32,32)\n y = net(x)\n print(y)\n\n\nif __name__ == '__main__':\n test()\n"
] |
[
[
"torch.nn.Sequential",
"torch.cat",
"torch.randn",
"torch.nn.functional.avg_pool2d",
"torch.nn.Conv2d",
"torch.nn.Linear",
"torch.nn.AvgPool2d",
"torch.nn.functional.relu",
"torch.nn.BatchNorm2d"
]
] |
nahmad16/sptrsv_framework
|
[
"723b4859c3c9c2f53a5468e97b5924708b3c91f3"
] |
[
"evaluation.py"
] |
[
"import pandas as pd\nimport seaborn as sns\nimport json\nimport matplotlib.pyplot as plt\nimport sys\nfrom sklearn.feature_selection import SelectKBest\nfrom sklearn.feature_selection import chi2\nfrom sklearn.preprocessing import StandardScaler, LabelEncoder\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn import model_selection\nfrom sklearn.exceptions import UndefinedMetricWarning\nimport warnings\nimport numpy as np\nimport scipy as sp\n\nclass CPUGPUComparison():\n\tdef __init__( self ):\n\t\tprint('CPU GPU SpTRSV performance comparison\\n')\n\n\tdef DrawComparisonTable(self, filename):\n\t\tperf_dataset = pd.read_csv(filename)\n\t\twinner_df = perf_dataset.idxmin(axis=1)\n\t\twinner_counts = winner_df.value_counts()\n\t\tnorm_winner_counts = winner_df.value_counts(normalize=True)*100\n\t\tprint(\" ----------------------------------------------------------------------------------------------------\")\n\t\tprint(\" |%15s%35s%32s%15s |\" % (\"Architecture |\",\"SpTRSV implementation |\",\"Winner for # of matrices |\",\\\n\t\t\t\"Percentage\"))\n\t\tprint(\" ----------------------------------------------------------------------------------------------------\")\n\t\tprint(\" |%15s%35s%30d%s%13.2f %% |\" % (\"CPU |\",\"MKL(seq) |\", winner_counts['mkl_seq'],\" |\",norm_winner_counts['mkl_seq']))\n\t\tprint(\" |%15s%35s%30d%s%13.2f %% |\" % (\"|\",\"MKL(par) |\", winner_counts['mkl_par'],\" |\",norm_winner_counts['mkl_par']))\n\t\tprint(\" ----------------------------------------------------------------------------------------------------\")\n\t\tprint(\" |%15s%35s%30d%s%13.2f %% |\" % (\"GPU |\",\"cuSPARSE(v1) |\", winner_counts['cusparse_v1'],\" |\",norm_winner_counts['cusparse_v1']))\n\t\tprint(\" |%15s%35s%30d%s%13.2f %% |\" % (\"|\",\"cuSPARSE(v2)(level-sch.) |\", winner_counts['cusparse_v2_lvl'],\" |\",norm_winner_counts['cusparse_v2_lvl']))\n\t\tprint(\" |%15s%35s%30d%s%13.2f %% |\" % (\"|\",\"cuSPARSE(v2)(no level sch.) |\", winner_counts['cusparse_v2_nolvl'],\" |\",norm_winner_counts['cusparse_v2_nolvl']))\n\t\tprint(\" |%15s%35s%30d%s%13.2f %% |\" % (\"|\",\"Sync-Free |\", winner_counts['syncfree'],\" |\",norm_winner_counts['syncfree']))\n\t\tprint(\" ----------------------------------------------------------------------------------------------------\")\n\n\tdef DrawStatsTable(self, filename):\n\t\tstats_dataset = pd.read_csv(filename)\n\t\tds_median = stats_dataset.median()\n\t\tds_min = stats_dataset.min()\n\t\tds_max = stats_dataset.max()\n\t\tmin_rows = ds_min['rows']/1000\n\t\tmedian_rows = ds_median['rows']/1000\n\t\tmax_rows = ds_max['rows']/1000000\n\t\tmin_nnzs = ds_min['nnzs']/1000\n\t\tmedian_nnzs = ds_median['nnzs']/1000\n\t\tmax_nnzs = ds_max['nnzs']/1000000\n\n\t\tprint(' ---------------------------------------------------------------------')\n\t\tprint(\" |%20s%16s%16s%16s\"%(\" |\",\"Minimum |\", \"Median |\",\"Maximum |\"))\n\t\tprint(' ---------------------------------------------------------------------')\n\t\tprint(\" |%20s%13.2fK%s%13.2fK%s%13.2fM%s\"%(\"Number of rows |\",min_rows,\" |\", median_rows,\" |\",max_rows, \" |\"))\n\t\tprint(' ---------------------------------------------------------------------')\n\t\tprint(\" |%20s%13.3fK%s%13.3fK%s%13.3fM%s\"%(\"Number of nonzeros |\",min_nnzs, \" |\",median_nnzs, \" |\", max_nnzs,\" |\"))\n\t\tprint(' ---------------------------------------------------------------------')\n\t\t\n\n\n\tdef DrawFigure(self, filename):\n\t\tperf_data = pd.read_csv(filename)\n\t\tperf_data.to_json(\"temp.json\", orient='records')\n\t\twith open(\"temp.json\", \"r\") as filename:\n\t\t\tV100_Gold_dataset_json = json.load(filename)\n\t\tV100_Gold_json_formatted = []\n\t\tfor i in range(0, 37):\n\t\t\tV100_Gold_json_formatted.append({\n\t\t\t\"Platform 1\": V100_Gold_dataset_json[i][\"Platform\"],\n\t\t\t\"Matrix 1\": V100_Gold_dataset_json[i][\"Matrix ID\"],\n\t\t\t\"Execution Time 1\": V100_Gold_dataset_json[i][\"Execution Time\"],\n\t\t\t\"Degree of Parallelism 1\":V100_Gold_dataset_json[i][\"Degree of Parallelism\"],\n\t\t\t\"Winner 1\":V100_Gold_dataset_json[i][\"Winner\"],\n\t\t\t\"Platform 2\": V100_Gold_dataset_json[i+37][\"Platform\"],\n\t\t\t\"Matrix 2\": V100_Gold_dataset_json[i+37][\"Matrix ID\"],\n\t\t\t\"Execution Time 2\": V100_Gold_dataset_json[i+37][\"Execution Time\"],\n\t\t\t\"Degree of Parallelism 2\":V100_Gold_dataset_json[i][\"Degree of Parallelism\"],\n\t\t\t\"Winner 2\": V100_Gold_dataset_json[i+37][\"Winner\"]})\n\n\t\tV100_Gold_json_formatted = sorted(V100_Gold_json_formatted, key = lambda i: (i['Winner 1'], i['Degree of Parallelism 1']))\n\t\tV100_Gold_json_sorted = []\n\t\tV100_Gold_Matrix = []\n\n\t\tfor i in range(0, 37):\n\t\t\tV100_Gold_json_sorted.append({\n\t\t\t\"Platform\": V100_Gold_json_formatted[i][\"Platform 1\"],\n\t\t\t\"Matrix ID\": V100_Gold_json_formatted[i][\"Matrix 1\"],\n\t\t\t\"Degree of Parallelism\": V100_Gold_json_formatted[i][\"Degree of Parallelism 1\"],\n\t\t\t\"Execution Time\": V100_Gold_json_formatted[i][\"Execution Time 1\"],\n\t\t\t})\n\t\t\tV100_Gold_Matrix.append(V100_Gold_json_formatted[i][\"Matrix 1\"])\n\n\t\tfor i in range(0, 37):\n\t\t V100_Gold_json_sorted.append({\n\t\t \"Platform\": V100_Gold_json_formatted[i][\"Platform 2\"],\n\t\t \"Matrix ID\": V100_Gold_json_formatted[i][\"Matrix 2\"],\n\t\t \"Degree of Parallelism\": V100_Gold_json_formatted[i][\"Degree of Parallelism 2\"],\n\t\t \"Execution Time\": V100_Gold_json_formatted[i][\"Execution Time 2\"],\n\t\t })\n\t\twith open(\"temp2.json\", \"w\") as file2:\n\t\t\tjson.dump(V100_Gold_json_sorted, file2)\n\n\t\tV100_Gold = pd.read_json('temp2.json', orient='records')\n\t\tplt.figure(figsize=(15,5))\n\t\tp1 = sns.barplot(x=\"Matrix ID\",y=\"Execution Time\",hue=\"Platform\", data=V100_Gold,palette = \"magma\", edgecolor = 'w', order=V100_Gold_Matrix)\n\t\t\n\t\tsns.set(font_scale = 1.3)\n\t\tsns.set_style(\"white\")\n\t\tp1.set_yscale(\"log\")\n\t\tp1.set_xticklabels(p1.get_xticklabels(), rotation=90)\n\t\tax1 = p1.axes\n\t\tax1.set(xticklabels=V100_Gold[\"Degree of Parallelism\"])\n\t\tax1.axvline(12.5, ls='--', lw=1.8)\n\t\tax1.text(1.0, 200, \"GPU winners: 24\")\n\t\tax1.text(1.0, 120, \"CPU winners: 13\")\n\t\tp1.set_xlabel(\"Matrix degree of parallelism (DoP)\")\n\t\tp1.set_ylabel(\"Lower triangular solve time (msec)\")\n\t\tlegend = p1.legend()\n\t\tlegend.texts[0].set_text(\"NVIDIA V100\")\n\t\tlegend.texts[1].set_text(\"Intel Gold\")\n\t\tplt.legend(loc='upper right')\n\t\tplt.setp(ax1.xaxis.get_majorticklabels(), ha='center')\n\t\tfig1 = p1.get_figure()\n\t\tfig1.set_rasterized(True)\n\t\tfig1.savefig('./datasets/figure2.eps', bbox_inches='tight',rasterized=True)\n\t\tprint(\"Figure 2 saved in datasets directory as figure2.eps\")\n\t\tplt.show()\n\t\t\t\t\n\nclass FeatureSelection():\n\tdef __init__( self ):\n\t\tprint('Feature Selection\\n')\n\n\tdef PrintAllFeatures(self, filename):\n\t\tfeatures =\tpd.read_csv(filename)\n\t\tfor col in features.columns:\n\t\t\tprint(col)\n\n\tdef FeatureRanking(self, filename):\n\t\tfeatures_data =\tpd.read_csv(filename)\n\t\tfeatures = features_data.drop(['winner'], axis = 1)\n\t\ttarget = features_data['winner']\n\t\tfeatures=features[:-2]\n\t\ttarget=target[:-2]\n\t\tKBestFeatures = SelectKBest(score_func=chi2, k=30)\n\t\tfit = KBestFeatures.fit(features, target)\n\t\trank = [i+1 for i in range(30)]\n\t\trank_dict = {'Rank':rank}\n\t\trank_df = pd.DataFrame(data=rank_dict)\n\t\tfeature_dict = {'Feature':features.columns, 'Score':fit.scores_}\n\t\tfeature_df = pd.DataFrame(data=feature_dict)\n\t\tdesc = ['Number of rows', 'Number of non-zeros','Number of levels', \\\n\t\t\t\t'Maximum row length count', 'Maximum column length count', \"Minimum column length count\", \\\n\t\t\t\t'Minimum row length count', 'Maximum non-zeros per level row-wise', \\\n\t\t\t\t'Maximum non-zeros per level column-wise', 'Maximum row length', \\\n\t\t\t\t'Maximum column length', 'Mean row-length',\\\n\t\t\t\t'Maximum rows per level','Median rows per level', \\\n\t\t\t\t'Median row length', 'Median column length', \\\n\t\t\t\t'Mean non-zeros per level row-wise', 'Standard deviation rows per level', \\\n\t\t\t\t'Standard deviation non-zeros per level row-wise', 'Standard deviation rows length', \\\n\t\t\t\t'Standard deviation column length','Mean rows per level', 'Mean max column length per level', \\\n\t\t\t\t'Mean mean column length per level', 'Mean std. deviation column length per level', \\\n\t\t\t\t'Mean maximum row length per level','Mean standard deviation row length per level',\\\n\t\t\t\t'Mean mean row length per level','Mean minimum row length per level',\\\n\t\t\t\t'Mean median row length per level']\n\t\tfeature_df['Description'] = desc\n\t\tfeature_df_sorted = feature_df.nlargest(30, 'Score')\n\t\tfeature_df_sorted.reset_index(drop=True,inplace=True)\n\t\tfeature_df_sorted.index += 1\n\t\tprint(feature_df_sorted.to_string(index=True))\n\nclass Prediction():\n\tdef __init__( self ):\n\t\tprint('Prediction\\n')\n\n\tdef CrossValidation(self, filename, mode):\n\t\ttraining_data = pd.read_csv(filename)\n\n\t\tif mode == 1: # Traning set for 10 features\n\t\t\tX = training_data.drop(['min_rl_cnt','mean_rpl','median_rpl','max_cl','lvls','std_rpl', \\\n\t\t\t\t'mean_max_cl_pl','mean_mean_cl_pl','max_rl','mean_std_cl_pl','mean_max_rl_pl',\\\n\t\t\t\t'std_cl','mean_std_rl_pl','mean_mean_rl_pl','mean_median_rl_pl','mean_min_rl_pl',\\\n\t\t\t\t'mean_rl','median_rl','median_cl','std_rl','mkl_seq','mkl_par','cusparse_v1',\\\n\t\t\t\t'cusparse_v2_lvl','cusparse_v2_nolvl','syncfree','winner','CPU winner','GPU winner',\\\n\t\t\t\t'2nd','3rd','4th','5th','6th'], axis=1)\n\t\telse: # Traning set for 30 features\n\t\t\tX = training_data.drop(['mkl_seq','mkl_par','cusparse_v1','cusparse_v2_lvl', \\\n\t\t\t\t'cusparse_v2_nolvl','syncfree','winner','CPU winner','GPU winner','2nd',\\\n\t\t\t\t'3rd','4th','5th','6th'], axis=1)\n\t\ty = training_data['winner']\n\t\tsc = StandardScaler()\n\t\tX_scaled = sc.fit_transform(X)\n\t\tX_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.25, random_state=44)\n\t\trfc_algo_selection = RandomForestClassifier(n_estimators=300)\n\t\trfc_algo_selection.fit(X_train, y_train)\n\t\tpred_rfc_algo_selection = rfc_algo_selection.predict(X_test)\n\t\tseed = 10\n\t\tcv_results = []\n\t\taccuracy = 'accuracy'\n\t\tprecision = 'precision_weighted'\n\t\trecall = 'recall_weighted'\n\t\tf1_score = 'f1_weighted'\n\t\ttest_precision = 'test_precision_weighted'\n\t\ttest_recall = 'test_recall_weighted'\n\t\ttest_f1 = 'test_f1_weighted'\n\t\ttest_accuracy = 'test_accuracy'\n\t\twarnings.filterwarnings(\"ignore\", category=UndefinedMetricWarning)\n\t\tscoring = [accuracy, precision, recall,f1_score]\n\t\tkfold = model_selection.KFold(n_splits=10, random_state=seed)\n\t\twith warnings.catch_warnings():\n\t\t\tscores = model_selection.cross_validate(rfc_algo_selection, X_scaled, y, cv=kfold,scoring=scoring)\n\t\tcv_results.append(scores[test_accuracy])\n\t\tcv_results.append(scores[test_precision])\n\t\tcv_results.append(scores[test_recall])\n\t\tcv_results.append(scores[test_f1])\n\t\tprint('Mean accuracy: %0.1f %%' % (cv_results[0].mean()*100.0))\n\t\tprint('Mean precision: %0.1f %%' % (cv_results[1].mean()*100.0))\n\t\tprint('Mean recall: %0.1f %%' % (cv_results[2].mean()*100.0))\n\t\tprint('Mean f1-score: %0.1f %%' % (cv_results[3].mean()*100.0))\n\t\tprint('Median accuracy: %0.1f %%' % (np.median(cv_results[0])*100.0))\n\t\tprint('Median precision: %0.1f %%' % (np.median(cv_results[1])*100.0))\n\t\tprint('Median recall: %0.1f %%' % (np.median(cv_results[2])*100.0))\n\t\tprint('Median f1-score: %0.1f %%\\n' % (np.median(cv_results[3])*100.0))\n\t\tlabels = ['Accuracy', 'Precision', 'Recall', 'F1-score']\n\t\tax1 = sns.boxplot(y=cv_results,x=labels, showmeans=True, fliersize=1,meanprops={\"marker\":\"D\",\"markerfacecolor\":\"yellow\", \"markeredgecolor\":\"none\"})\n\t\tsns.set(font_scale=1.3)\n\t\tsns.set_style(\"white\")\n\t\tvals = ax1.get_yticks()\n\t\tax1.set_yticklabels(['{:,.0%}'.format(x) for x in vals])\n\t\tmyfigure = ax1.get_figure()\n\n\t\tif mode == 1:\n\t\t\tmyfigure.savefig('./datasets/figure6.png',bbox_inches='tight')\n\t\t\tprint(\"Figure 8 saved in datasets as figure8.eps\")\n\t\t\tprint(\"Note: Statistics can slightly vary from Figure 8 and from run-to-run\")\t\n\t\telse:\n\t\t\tmyfigure.savefig('./datasets/figure7.eps',bbox_inches='tight')\n\t\t\tmyfigure.show()\n\t\t\tprint(\"Figure 7 saved in datasets as figure7.eps\")\n\t\t\tprint(\"Note: Statistics can slightly vary from Figure 7 and from run-to-run\")\n\t\tplt.show()\nclass Performance():\n\tdef __init__( self ):\n\t\tprint('Performance Results\\n')\n\n\tdef Speedup(self, filename):\n\t\ttraining_data = pd.read_csv(filename)\n\t\tX = training_data.drop(['mkl_seq','mkl_par','cusparse_v1','cusparse_v2_lvl', \\\n\t\t\t\t'cusparse_v2_nolvl','syncfree','winner','CPU winner','GPU winner','2nd',\\\n\t\t\t\t'3rd','4th','5th','6th'], axis=1)\n\t\ty = training_data['winner']\n\t\tsc = StandardScaler()\n\t\tX_scaled = sc.fit_transform(X)\n\t\tX_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.25, random_state=44)\n\t\trfc_algo_selection = RandomForestClassifier(n_estimators=300)\n\t\trfc_algo_selection.fit(X_train, y_train)\n\t\tpred_rfc_algo_selection = rfc_algo_selection.predict(X_test)\n\t\tseed = 10\n\t\tprecision = 'precision_weighted'\n\t\trecall = 'recall_weighted'\n\t\tf1_score = 'f1_weighted'\n\t\tscoring = [precision, recall,f1_score]\n\t\tkfold = model_selection.KFold(n_splits=10)\n\t\tcross_validate_pred = model_selection.cross_val_predict(rfc_algo_selection, X_scaled, y, cv=kfold)\n\t\tMKL_seq = training_data['mkl_seq']\n\t\tMKL_par = training_data['mkl_par']\n\t\tcus1 = training_data['cusparse_v1']\n\t\tcus2_lvl = training_data['cusparse_v2_lvl']\n\t\tcus2_nolvl = training_data['cusparse_v2_nolvl']\n\t\tsyncfree = training_data['syncfree']\n\t\talgo_labels = {0:'MKL(seq)', 1:'MKL(par)', 2:'cuSPARSE(v1)', \\\n\t\t\t\t\t\t3:'cuSPARSE(v2)(level-sch.)',4:'cuSPARSE(v2)(no level-sch.)',5:'Sync-Free'}\n\t\tGain_vs_MKL_seq = []\n\t\tGain_vs_MKL_par = []\n\t\tGain_vs_cus1 = []\n\t\tGain_vs_cus2_lvl = []\n\t\tGain_vs_cus2_nolvl = []\n\t\tGain_vs_syncfree = []\n\t\ti = 0\n\n\t\tfor val in cross_validate_pred:\n\t\t if val == 1:\n\t\t predicted_time = MKL_seq[i]\n\t\t if val == 2:\n\t\t predicted_time = MKL_par[i]\n\t\t if val == 3:\n\t\t predicted_time = cus1[i]\n\t\t if val == 4:\n\t\t predicted_time = cus2_lvl[i]\n\t\t if val == 5:\n\t\t predicted_time = cus2_nolvl[i]\n\t\t if val == 6:\n\t\t predicted_time = syncfree[i]\n\t\t \n\t\t Gain_vs_MKL_seq.append(MKL_seq[i]/predicted_time)\n\t\t Gain_vs_MKL_par.append(MKL_par[i]/predicted_time)\n\t\t Gain_vs_cus1.append(cus1[i]/predicted_time)\n\t\t Gain_vs_cus2_lvl.append(cus2_lvl[i]/predicted_time)\n\t\t Gain_vs_cus2_nolvl.append(cus2_nolvl[i]/predicted_time) \n\t\t Gain_vs_syncfree.append(syncfree[i]/predicted_time)\n\t\t i = i + 1\n\n\t\tpredicted_speedup=[]\n\t\tpredicted_speedup.append(Gain_vs_MKL_seq)\n\t\tpredicted_speedup.append(Gain_vs_MKL_par)\n\t\tpredicted_speedup.append(Gain_vs_cus1)\n\t\tpredicted_speedup.append(Gain_vs_cus2_lvl)\n\t\tpredicted_speedup.append(Gain_vs_cus2_nolvl)\n\t\tpredicted_speedup.append(Gain_vs_syncfree)\n\n\t\tspeedup_g2 = []\n\t\tspeedup_l1 = []\n\t\tcounter = 0\n\t\tcounter_l = 0\n\t\tcounter_l95 = 0\n\n\t\tfor i in range(6):\n\t\t for x in predicted_speedup[i]:\n\t\t if x >= 1:\n\t\t counter = counter + 1\n\t\t if x < 1:\n\t\t counter_l = counter_l + 1\n\t\t if x < 0.95:\n\t\t counter_l95 = counter_l95 + 1\n\t\t speedup_g2.append(counter/998*100)\n\t\t speedup_l1.append(counter_l/998*100)\n\t\t counter = 0\n\t\t counter_l = 0\n\t\t counter_l95 = 0\n\n\t\tsns.set(font_scale=1.0)\n\t\tsns.set_style(\"white\")\n\t\tfig, ax = plt.subplots(nrows=2, ncols=3, figsize=(10, 4.5))\n\t\tfig.set_rasterized(True)\n\t\tk = 0\n\n\t\tfor i in range(2): \n\t\t\tfor j in range(3):\n\t\t\t\t#my_bins = [0,1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,int(np.max(predicted_speedup[k]))]\n\t\t\t\tmax_ps = np.max(predicted_speedup[k])\n\t\t\t\tmy_bins = np.arange(0, 75)\n\t\t\t\tclrs=['#CB4335' if (x < 1) else '#2874A6' for x in my_bins]\t\t\t\t\n\t\t\t\tplot = sns.distplot(predicted_speedup[k], \\\n\t\t\t\t\tbins=my_bins, ax=ax[i][j],kde=False)\n\t\t\t\tsns.color_palette(\"husl\", 8)\n\t\t\t\tax1 = plot.axes\n\t\t\t\tfor rec, clr in zip(ax1.patches, clrs):\n\t\t\t\t\trec.set_color(clr)\n\t\t\t\t\n\t\t\t\tprops = dict(boxstyle='round', facecolor='none', alpha=0.5)\n\t\t\t\tax1.text(0.55, 0.70, \">=1: %.1f%%\"%(speedup_g2[k]), transform=ax1.transAxes, fontsize=12,\n\t\t\t\tverticalalignment='top', bbox=props)\n\t\t\t\tax1.text(0.55, 0.85, \"Mean: %.1f\"%(sp.stats.hmean(predicted_speedup[k])), transform=ax1.transAxes, fontsize=12,\n\t\t\t\tverticalalignment='top', bbox=props)\n\t\t\t\tz_critical = sp.stats.norm.ppf(q = 0.95) # Get the z-critical value*\n\t\t\t\tpop_stdev = np.std(predicted_speedup[k])\n\t\t\t\thmean = sp.stats.hmean(predicted_speedup[k])\n\t\t\t\tmean_m_x = [(hmean-x) for x in predicted_speedup]\n\t\t\t\tmean_m_x = [np.sqrt(x*x) for x in mean_m_x]\n\t\t\t\tsample_size = len(predicted_speedup[k])\n\t\t\t\th_std = np.sum(mean_m_x)/sample_size\n\t\t\t\tmargin_of_error = z_critical * (pop_stdev/np.sqrt(sample_size))\n\t\t\t\tplot.set_yscale(\"log\")\n\t\t\t\t#if k >= 3:\n\t\t\t\tplot.set_xlabel(\"Speedup\")\n\t\t\t\tplot.set_title(algo_labels[k],loc=\"left\")\n\t\t\t\tif k == 0 or k == 3:\n\t\t\t\t plot.set_ylabel('Number of matrices')\n\t\t\t\tk = k + 1\t\t \n\t\tplt.tight_layout()\n\t\twarnings.filterwarnings(\"ignore\")\n\t\twith warnings.catch_warnings():\n\t\t\tfig.savefig('./datasets/figure9.pdf',bbox_inches='tight',rasterized=True)\n\t\t\tprint(\"Figure 9 saved in datasets as figure9.eps\")\n\t\t\tprint(\"Note: Statistics can slightly vary from Figure 9 and from run-to-run\")\n\t\t#plt.show()\n\n\tdef Overheads(self, filename_training, filename_overhead):\n\t\ttraining_data=pd.read_csv(filename_training)\n\t\toverhead_data=pd.read_csv(filename_overhead)\n\t\tFE_wo_ilu = overhead_data['FE_oh_wo'] # Feature extraction (FE) overhead without ILU factorization time included\n\t\tFE_w_ilu = overhead_data['FE_oh_w'] # Feature extraction (FE) ovheread with ILU factorization time included\n\t\tm=overhead_data['m'] # Number of rows\n\t\tMKL_seq = training_data['mkl_seq']\n\t\tMKL_par = training_data['mkl_par']\n\t\tcus1 = training_data['cusparse_v1']\n\t\tcus2_lvl = training_data['cusparse_v2_lvl']\n\t\tcus2_nolvl = training_data['cusparse_v2_nolvl']\n\t\tsyncfree = training_data['syncfree'] \n\t\tseed = 250\n\t\tprecision = 'precision_weighted'\n\t\trecall = 'recall_weighted'\n\t\tf1_score = 'f1_weighted'\n\t\tscoring = [precision, recall,f1_score]\n\t\tX = training_data.drop(['mkl_seq','mkl_par','cusparse_v1','cusparse_v2_lvl','cusparse_v2_nolvl','syncfree','winner','CPU winner','GPU winner','2nd','3rd','4th','5th','6th'], axis=1)\n\t\ty = training_data['winner']\n\t\tsc = StandardScaler()\n\t\tX_scaled = sc.fit_transform(X)\n\t\tX_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.25, random_state=44)\n\t\trfc_algo_selection = RandomForestClassifier(n_estimators=300)\n\t\trfc_algo_selection.fit(X_train, y_train)\n\t\tkfold = model_selection.KFold(n_splits=10)\n\t\tcross_validate_pred = model_selection.cross_val_predict(rfc_algo_selection, X_scaled, y, cv=kfold)\n\t\t\n\t\tL_calls_vs_FE_wo_100K = [] # FE overhead in terms of lower triangular solve iterations without ILU factorization time included for matrices upto 100K rows\n\t\tL_calls_vs_FE_w_100K = [] # FE overhead in terms of lower triangular solve iterations with ILU factorization time included for matrices upto 100K rows\n\t\tL_calls_vs_FE_wo_1000K = [] # FE overhead in terms of lower triangular solve iterations without ILU factorization time included for matrices from 100K-1000K rows\n\t\tL_calls_vs_FE_w_1000K = [] # FE overhead in terms of lower triangular solve iterations with ILU factorization time included for matrices from 100K-1000K rows\n\t\tL_calls_vs_FE_wo_g1000K = [] # FE overhead in terms of lower triangular solve iterations without ILU factorization time included for matrices > 1000K rows\n\t\tL_calls_vs_FE_w_g1000K = [] # FE overhead in terms of lower triangular solve iterations with ILU factorization time included for matrices > 1000K rows\n\n\t\toh_FE_wo_100K = [] # FE overhead without ILU factorization time included for matrices upto 100K\n\t\toh_FE_w_100K = [] # FE overhead with ILU factorization time included for matrices upto 100K\n\t\toh_FE_wo_1000K = [] # FE overhead without ILU factorization time included for matrices upto 100K-1000K\n\t\toh_FE_w_1000K = [] # FE overhead with ILU factorization time included for matrices upto 100K-1000K\n\t\toh_FE_wo_g1000K = [] # FE overhead without ILU factorization time included for matrices > 1000K\n\t\toh_FE_w_g1000K = [] # FE overhead without ILU factorization time included for matrices > 1000K\n\n\t\toh_MKLs_wo_100K = [] # MKL(ser) overhead without ILU factorization time included for matrices upto 100K\n\t\toh_MKLs_w_100K = [] # MKL(ser) overhead with ILU factorization time included for matrices upto 100K\n\t\toh_MKLp_wo_100K = [] # MKL(par) overhead without ILU factorization time included for matrices upto 100K\n\t\toh_MKLp_w_100K = [] # MKL(par) overhead with ILU factorization time included for matrices upto 100K\n\t\toh_CUS1_wo_100K = [] # cuSPARSE(v1) overhead without ILU factorization time included for matrices upto 100K\n\t\toh_CUS1_w_100K = [] # cuSPARSE(v1) overhead with ILU factorization time include for matrices upto 100K\n\t\toh_CUS2lvl_wo_100K = [] # cuSPARSE(v2)(level-sch.) overhead without ILU factorization time included for matrices upto 100K\n\t\toh_CUS2lvl_w_100K = [] # cuSPARSE(v2)(level-sch.) overhead with ILU factorization time included for matrices upto 100K \n\t\toh_CUS2nolvl_wo_100K = [] # cuSPARSE(v2)(no level-sch.) overhead without ILU factorization time included for matrices upto 100K\n\t\toh_CUS2nolvl_w_100K = [] # cuSPARSE(v2)(level-sch.) overhead with ILU factorization time included for matrices upto 100K\n\t\toh_SyncFree_wo_100K = [] # SyncFree overhead without ILU factorization time included for matrices upto 100K\n\t\toh_SyncFree_w_100K = [] # cuSPARSE(v2)(level-sch.) overhead with ILU factorization time included for matrices upto 100K\n\n\t\toh_MKLs_wo_1000K = [] # MKL(ser) overhead without ILU factorization time included for matrices from 100K-1000K \n\t\toh_MKLs_w_1000K = []\t\t # MKL(ser) overhead with ILU factorization time included for matrices from 100K-1000K\n\t\toh_MKLp_wo_1000K = []\t\t # MKL(par) overhead without ILU factorization time included for matrices from 100K-1000K\n\t\toh_MKLp_w_1000K = []\t\t # MKL(par) overhead with ILU factorization time included for matrices from 100K-1000K\n\t\toh_CUS1_wo_1000K = []\t\t # cuSPARSE(v1) overhead without ILU factorization time included for matrices from 100K-1000K\n\t\toh_CUS1_w_1000K = []\t\t # cuSPARSE(v1) overhead with ILU factorization time include for matrices from 100K-1000K\n\t\toh_CUS2lvl_wo_1000K = []\t # cuSPARSE(v2)(level-sch.) overhead without ILU factorization time included for matrices from 100K-1000K\n\t\toh_CUS2lvl_w_1000K = []\t\t # cuSPARSE(v2)(level-sch.) overhead with ILU factorization time included for matrices from 100K-1000K \n\t\toh_CUS2nolvl_wo_1000K = []\t # cuSPARSE(v2)(no level-sch.) overhead without ILU factorization time included for matrices from 100K-1000K\n\t\toh_CUS2nolvl_w_1000K = []\t # cuSPARSE(v2)(level-sch.) overhead with ILU factorization time included for matrices from 100K-1000K\n\t\toh_SyncFree_wo_1000K = []\t # SyncFree overhead without ILU factorization time included for matrices from 100K-1000K\n\t\toh_SyncFree_w_1000K = []\t # cuSPARSE(v2)(level-sch.) overhead with ILU factorization time included for matrices from 100K-1000K\n\n\t\toh_MKLs_wo_g1000K = [] \t # MKL(ser) overhead without ILU factorization time included for matrices > 1000K \n\t\toh_MKLs_w_g1000K = []\t\t # MKL(ser) overhead with ILU factorization time included for matrices > 1000K\n\t\toh_MKLp_wo_g1000K = []\t\t # MKL(par) overhead without ILU factorization time included for matrices > 1000K\n\t\toh_MKLp_w_g1000K = [] # MKL(par) overhead with ILU factorization time included for matrices > 1000K\n\t\toh_CUS1_wo_g1000K = [] # cuSPARSE(v1) overhead without ILU factorization time included for matrices > 1000K\n\t\toh_CUS1_w_g1000K = [] # cuSPARSE(v1) overhead with ILU factorization time include for matrices > 1000K\n\t\toh_CUS2lvl_wo_g1000K = [] # cuSPARSE(v2)(level-sch.) overhead without ILU factorization time included for matrices > 1000K\n\t\toh_CUS2lvl_w_g1000K = [] # cuSPARSE(v2)(level-sch.) overhead with ILU factorization time included for matrices > 1000K \n\t\toh_CUS2nolvl_wo_g1000K = [] # cuSPARSE(v2)(no level-sch.) overhead without ILU factorization time included for matrices > 1000K\n\t\toh_CUS2nolvl_w_g1000K = [] # cuSPARSE(v2)(level-sch.) overhead with ILU factorization time included for matrices > 1000K\n\t\toh_SyncFree_wo_g1000K = [] # SyncFree overhead without ILU factorization time included for matrices > 1000K\n\t\toh_SyncFree_w_g1000K = [] # cuSPARSE(v2)(level-sch.) overhead with ILU factorization time included for matrices > 1000K\n\n\t\toh_MKLs_wo_100K_ana = [] # MKL(ser) algorithm analysis overhead without ILU factorization time included for matrices upto 100K\n\t\toh_MKLs_w_100K_ana = [] # MKL(ser) algorithm analysis overhead with ILU factorization time included for matrices upto 100K\n\t\toh_MKLp_wo_100K_ana = [] # MKL(par) algorithm analysis overhead without ILU factorization time included for matrices upto 100K\n\t\toh_MKLp_w_100K_ana = [] # MKL(par) algorithm analysis overhead with ILU factorization time included for matrices upto 100K\n\t\toh_CUS1_wo_100K_ana = [] # cuSPARSE(v1) algorithm analysis overhead without ILU factorization time included for matrices upto 100K\n\t\toh_CUS1_w_100K_ana = [] # cuSPARSE(v1) algorithm analysis overhead with ILU factorization time include for matrices upto 100K\n\t\toh_CUS2lvl_wo_100K_ana = [] # cuSPARSE(v2)(level-sch.) algorithm analysis overhead without ILU factorization time included for matrices upto 100K\n\t\toh_CUS2lvl_w_100K_ana = [] # cuSPARSE(v2)(level-sch.) algorithm analysis overhead with ILU factorization time included for matrices upto 100K \n\t\toh_CUS2nolvl_wo_100K_ana = [] # cuSPARSE(v2)(no level-sch.) algorithm analysis overhead without ILU factorization time included for matrices upto 100K\n\t\toh_CUS2nolvl_w_100K_ana = [] # cuSPARSE(v2)(level-sch.) algorithm analysis overhead with ILU factorization time included for matrices upto 100K\n\t\toh_SyncFree_wo_100K_ana = [] # SyncFree algorithm analysis overhead without ILU factorization time included for matrices upto 100K\n\t\toh_SyncFree_w_100K_ana = [] # cuSPARSE(v2)(level-sch.) algorithm analysis overhead with ILU factorization time included for matrices upto 100K\n\n\t\toh_MKLs_wo_1000K_ana = [] # MKL(ser) algorithm analysis overhead without ILU factorization time included for matrices from 100K-1000K\n\t\toh_MKLs_w_1000K_ana = [] # MKL(ser) algorithm analysis overhead with ILU factorization time included for matrices from 100K-1000K\n\t\toh_MKLp_wo_1000K_ana = [] # MKL(par) algorithm analysis overhead without ILU factorization time included for matrices from 100K-1000K\n\t\toh_MKLp_w_1000K_ana = [] # MKL(par) algorithm analysis overhead with ILU factorization time included for matrices from 100K-1000K\n\t\toh_CUS1_wo_1000K_ana = [] # cuSPARSE(v1) algorithm analysis overhead without ILU factorization time included for matrices from 100K-1000K\n\t\toh_CUS1_w_1000K_ana = [] # cuSPARSE(v1) algorithm analysis overhead with ILU factorization time include for matrices from 100K-1000K\n\t\toh_CUS2lvl_wo_1000K_ana = [] # cuSPARSE(v2)(level-sch.) algorithm analysis overhead without ILU factorization time included for matrices from 100K-1000K\n\t\toh_CUS2lvl_w_1000K_ana = [] # cuSPARSE(v2)(level-sch.) algorithm analysis overhead with ILU factorization time included for matrices from 100K-1000K \n\t\toh_CUS2nolvl_wo_1000K_ana = [] # cuSPARSE(v2)(no level-sch.) algorithm analysis overhead without ILU factorization time included for matrices from 100K-1000K\n\t\toh_CUS2nolvl_w_1000K_ana = [] # cuSPARSE(v2)(level-sch.) algorithm analysis overhead with ILU factorization time included for matrices from 100K-1000K\n\t\toh_SyncFree_wo_1000K_ana = [] # SyncFree algorithm analysis overhead without ILU factorization time included for matrices from 100K-1000K\n\t\toh_SyncFree_w_1000K_ana = [] # cuSPARSE(v2)(level-sch.) algorithm analysis overhead with ILU factorization time included for matrices from 100K-1000K\n\n\t\toh_MKLs_wo_g1000K_ana = [] # MKL(ser) algorithm analysis overhead without ILU factorization time included for matrices > 1000K\n\t\toh_MKLs_w_g1000K_ana = [] # MKL(ser) algorithm analysis overhead with ILU factorization time included for matrices > 1000K\n\t\toh_MKLp_wo_g1000K_ana = [] # MKL(par) algorithm analysis overhead without ILU factorization time included for matrices > 1000K\n\t\toh_MKLp_w_g1000K_ana = [] # MKL(par) algorithm analysis overhead with ILU factorization time included for matrices > 1000K\n\t\toh_CUS1_wo_g1000K_ana = [] # cuSPARSE(v1) algorithm analysis overhead without ILU factorization time included for matrices > 1000K\n\t\toh_CUS1_w_g1000K_ana = [] # cuSPARSE(v1) algorithm analysis overhead with ILU factorization time include for matrices > 1000K\n\t\toh_CUS2lvl_wo_g1000K_ana = [] # cuSPARSE(v2)(level-sch.) algorithm analysis overhead without ILU factorization time included for matrices > 1000K\n\t\toh_CUS2lvl_w_g1000K_ana = [] # cuSPARSE(v2)(level-sch.) algorithm analysis overhead with ILU factorization time included for matrices > 1000K \n\t\toh_CUS2nolvl_wo_g1000K_ana = [] # cuSPARSE(v2)(no level-sch.) algorithm analysis overhead without ILU factorization time included for matrices > 1000K\n\t\toh_CUS2nolvl_w_g1000K_ana = [] # cuSPARSE(v2)(level-sch.) algorithm analysis overhead with ILU factorization time included for matrices > 1000K\n\t\toh_SyncFree_wo_g1000K_ana = [] # SyncFree algorithm analysis overhead without ILU factorization time included for matrices > 1000K\n\t\toh_SyncFree_w_g1000K_ana = [] # cuSPARSE(v2)(level-sch.) algorithm analysis overhead with ILU factorization time included for matrices > 1000K\n\n\n\t\temp_oh_wo_100K = 0 # Empirical execution overhead without ILU factorization time included for matrices upto 100K\n\t\temp_oh_wo_1000k = 0 # Empirical execution overhead without ILU factorization time included for matrices from 100K-1000K\n\t\temp_oh_wo_g1000k = 0 # Empirical execution overhead without ILU factorization time included for matrices > 1000K\n\t\temp_oh_w_100K = 0 # Empirical execution overhead with ILU factorization time included for matrices upto 100K\n\t\temp_oh_w_1000k = 0 # Empirical execution overhead with ILU factorization time included for matrices from 100K-1000K\n\t\temp_oh_w_g1000k = 0 # Empirical execution overhead with ILU factorization time included for matrices > 1000K\n\t\t\n\t\ti = 0\n\t\tfor val in cross_validate_pred:\n\t\t if val == 1:\n\t\t predicted_time = MKL_seq[i]\n\t\t if val == 2:\n\t\t predicted_time = MKL_par[i]\n\t\t if val == 3:\n\t\t predicted_time = cus1[i]\n\t\t if val == 4:\n\t\t predicted_time = cus2_lvl[i]\n\t\t if val == 5:\n\t\t predicted_time = cus2_nolvl[i]\n\t\t if val == 6:\n\t\t predicted_time = syncfree[i]\n\t\t if m[i] < 100000:\n\t\t L_calls_vs_FE_wo_100K.append(FE_wo_ilu[i]*1000/predicted_time)\n\t\t L_calls_vs_FE_w_100K.append(FE_w_ilu[i]*1000/predicted_time)\n\t\t oh_MKLs_wo_100K.append((overhead_data['MKL(seq) Ana'][i]+overhead_data['MKL(seq) 10 iter'][i]))\n\t\t oh_MKLs_w_100K.append((overhead_data['MKL(seq) Ana'][i]+overhead_data['MKL(seq) 10 iter'][i]+\\\n\t\t overhead_data['MKL(seq) ilu'][i]))\n\t\t oh_MKLp_wo_100K.append((overhead_data['MKL(par) Ana'][i]+overhead_data['MKL(par) 10 iter'][i]))\n\t\t oh_MKLp_w_100K.append((overhead_data['MKL(par) Ana'][i]+overhead_data['MKL(par) 10 iter'][i]+\\\n\t\t overhead_data['MKL(par) ilu'][i]))\n\t\t oh_CUS1_wo_100K.append((overhead_data['cuSPARSE(v1) ana'][i]+overhead_data['cuSPARSE(v1) 10 iter'][i]))\n\t\t oh_CUS1_w_100K.append((overhead_data['cuSPARSE(v1) ana'][i]+overhead_data['cuSPARSE(v1) 10 iter'][i]+\\\n\t\t overhead_data['cuSPARSE(v1) ilu'][i]))\n\t\t oh_CUS2lvl_wo_100K.append((overhead_data['cusparse(v2)ana'][i]+overhead_data['cuSPARSE(v2)lvl'][i]))\n\t\t oh_CUS2lvl_w_100K.append((overhead_data['cusparse(v2)ana'][i]+overhead_data['cuSPARSE(v2)lvl'][i]+\\\n\t\t +overhead_data['cuSPARSE(v2)iluAna'][i]+overhead_data['cuSPARSE(v2)iu'][i]))\n\t\t oh_CUS2nolvl_wo_100K.append((overhead_data['cuSPARSE(v2)nolvl 10 iter'][i]))\n\t\t oh_CUS2nolvl_w_100K.append((overhead_data['cuSPARSE(v2)nolvl 10 iter'][i]))\n\t\t oh_SyncFree_wo_100K.append((overhead_data['Sync-Free ana'][i]+overhead_data['Sync-Free 10 iter'][i]))\n\t\t oh_SyncFree_w_100K.append((overhead_data['SycnFree_LU'][i]+overhead_data['Sync-Free ana'][i]+\\\n\t\t overhead_data['Sync-Free 10 iter'][i]))\n\t\t oh_FE_wo_100K.append(overhead_data['FE_oh_wo'][i])\n\t\t oh_FE_w_100K.append(overhead_data['FE_oh_w'][i])\n\t\t \n\t\t oh_MKLs_wo_100K_ana.append((overhead_data['MKL(seq) Ana'][i]))\n\t\t oh_MKLs_w_100K_ana.append((overhead_data['MKL(seq) Ana'][i]+overhead_data['MKL(seq) ilu'][i]))\n\t\t oh_MKLp_wo_100K_ana.append((overhead_data['MKL(par) Ana'][i]))\n\t\t oh_MKLp_w_100K_ana.append((overhead_data['MKL(par) Ana'][i]+overhead_data['MKL(par) ilu'][i]))\n\t\t oh_CUS1_wo_100K_ana.append((overhead_data['cuSPARSE(v1) ana'][i]))\n\t\t oh_CUS1_w_100K_ana.append((overhead_data['cuSPARSE(v1) ana'][i]+overhead_data['cuSPARSE(v1) ilu'][i]))\n\t\t oh_CUS2lvl_wo_100K_ana.append((overhead_data['cusparse(v2)ana'][i]))\n\t\t oh_CUS2lvl_w_100K_ana.append((overhead_data['cusparse(v2)ana'][i]+\\\n\t\t overhead_data['cuSPARSE(v2)iluAna'][i]+overhead_data['cuSPARSE(v2)iu'][i]))\n\t\t oh_CUS2nolvl_wo_100K_ana.append(0)\n\t\t oh_CUS2nolvl_w_100K_ana.append(0)\n\t\t oh_SyncFree_wo_100K_ana.append((overhead_data['Sync-Free ana'][i]))\n\t\t oh_SyncFree_w_100K_ana.append((overhead_data['SycnFree_LU'][i]+overhead_data['Sync-Free ana'][i]))\n\t\t \n\t\t if m[i] >= 100000 and m[i] < 1000000:\n\t\t L_calls_vs_FE_wo_1000K.append(FE_wo_ilu[i]*1000/predicted_time)\n\t\t L_calls_vs_FE_w_1000K.append(FE_w_ilu[i]*1000/predicted_time)\n\t\t \n\t\t oh_MKLs_wo_1000K.append((overhead_data['MKL(seq) Ana'][i]+overhead_data['MKL(seq) 10 iter'][i]))\n\t\t oh_MKLs_w_1000K.append((overhead_data['MKL(seq) Ana'][i]+overhead_data['MKL(seq) 10 iter'][i]+\\\n\t\t overhead_data['MKL(seq) ilu'][i]))\n\t\t oh_MKLp_wo_1000K.append((overhead_data['MKL(par) Ana'][i]+overhead_data['MKL(par) 10 iter'][i]))\n\t\t oh_MKLp_w_1000K.append((overhead_data['MKL(par) Ana'][i]+overhead_data['MKL(par) 10 iter'][i]+\\\n\t\t overhead_data['MKL(par) ilu'][i]))\n\t\t oh_CUS1_wo_1000K.append((overhead_data['cuSPARSE(v1) ana'][i]+\\\n\t\t overhead_data['cuSPARSE(v1) 10 iter'][i]))\n\t\t oh_CUS1_w_1000K.append((overhead_data['cuSPARSE(v1) ana'][i]+\\\n\t\t overhead_data['cuSPARSE(v1) 10 iter'][i]+overhead_data['cuSPARSE(v1) ilu'][i]))\n\t\t oh_CUS2lvl_wo_1000K.append((overhead_data['cusparse(v2)ana'][i]+overhead_data['cuSPARSE(v2)lvl'][i]))\n\t\t oh_CUS2lvl_w_1000K.append((overhead_data['cusparse(v2)ana'][i]+\\\n\t\t overhead_data['cuSPARSE(v2)lvl'][i]+\\\n\t\t overhead_data['cuSPARSE(v2)iluAna'][i]+overhead_data['cuSPARSE(v2)iu'][i]))\n\t\t oh_CUS2nolvl_wo_1000K.append((overhead_data['cuSPARSE(v2)nolvl 10 iter'][i]))\n\t\t oh_CUS2nolvl_w_1000K.append((overhead_data['cuSPARSE(v2)nolvl 10 iter'][i]))\n\t\t oh_SyncFree_wo_1000K.append((overhead_data['Sync-Free ana'][i]+overhead_data['Sync-Free 10 iter'][i]))\n\t\t oh_SyncFree_w_1000K.append((overhead_data['SycnFree_LU'][i]+\\\n\t\t overhead_data['Sync-Free ana'][i]+overhead_data['Sync-Free 10 iter'][i]))\n\t\t oh_FE_wo_1000K.append((overhead_data['FE_oh_wo'][i]))\n\t\t oh_FE_w_1000K.append((overhead_data['FE_oh_w'][i]))\n\t\t \n\t\t oh_MKLs_wo_1000K_ana.append((overhead_data['MKL(seq) Ana'][i]))\n\t\t oh_MKLs_w_1000K_ana.append((overhead_data['MKL(seq) Ana'][i]+overhead_data['MKL(seq) ilu'][i]))\n\t\t oh_MKLp_wo_1000K_ana.append((overhead_data['MKL(par) Ana'][i]))\n\t\t oh_MKLp_w_1000K_ana.append((overhead_data['MKL(par) Ana'][i]+overhead_data['MKL(par) ilu'][i]))\n\t\t oh_CUS1_wo_1000K_ana.append((overhead_data['cuSPARSE(v1) ana'][i]))\n\t\t oh_CUS1_w_1000K_ana.append((overhead_data['cuSPARSE(v1) ana'][i]+overhead_data['cuSPARSE(v1) ilu'][i]))\n\t\t oh_CUS2lvl_wo_1000K_ana.append((overhead_data['cusparse(v2)ana'][i]))\n\t\t oh_CUS2lvl_w_1000K_ana.append((overhead_data['cusparse(v2)ana'][i]+\\\n\t\t overhead_data['cuSPARSE(v2)iluAna'][i]+\\\n\t\t overhead_data['cuSPARSE(v2)iu'][i]))\n\t\t oh_CUS2nolvl_wo_1000K_ana.append(0)\n\t\t oh_CUS2nolvl_w_1000K_ana.append(0)\n\t\t oh_SyncFree_wo_1000K_ana.append((overhead_data['Sync-Free ana'][i]))\n\t\t oh_SyncFree_w_1000K_ana.append((overhead_data['SycnFree_LU'][i]+overhead_data['Sync-Free ana'][i]))\n\t\t \n\t\t #emp_oh_wo_1000K.append(oh_MKLs_wo_1000K[i]+oh_MKLp_wo_1000K[i]+oh_CUS1_wo_1000K[i]+oh_CUS2lvl_wo_1000K[i]+oh_CUS2nolvl_wo_1000K[i]+oh_SyncFree_wo_1000K[i])\n\t\t if m[i] >= 1000000:\n\t\t L_calls_vs_FE_wo_g1000K.append(FE_wo_ilu[i]*1000/predicted_time)\n\t\t L_calls_vs_FE_w_g1000K.append(FE_w_ilu[i]*1000/predicted_time)\n\t\t oh_MKLs_wo_g1000K.append((overhead_data['MKL(seq) Ana'][i]))\n\t\t oh_MKLs_w_g1000K.append((overhead_data['MKL(seq) Ana'][i]+overhead_data['MKL(seq) ilu'][i]))\n\t\t oh_MKLp_wo_g1000K.append((overhead_data['MKL(par) Ana'][i]))\n\t\t oh_MKLp_w_g1000K.append((overhead_data['MKL(par) Ana'][i]+overhead_data['MKL(par) ilu'][i]))\n\t\t oh_CUS1_wo_g1000K.append((overhead_data['cuSPARSE(v1) ana'][i]+overhead_data['cuSPARSE(v1) 10 iter'][i]))\n\t\t oh_CUS1_w_g1000K.append((overhead_data['cuSPARSE(v1) ana'][i]+overhead_data['cuSPARSE(v1) ilu'][i]+overhead_data['cuSPARSE(v1) 10 iter'][i]))\n\t\t oh_CUS2lvl_wo_g1000K.append((overhead_data['cusparse(v2)ana'][i]+overhead_data['cuSPARSE(v2)lvl'][i]))\n\t\t oh_CUS2lvl_w_g1000K.append((overhead_data['cusparse(v2)ana'][i]+overhead_data['cuSPARSE(v1) ilu'][i]+\\\n\t\t overhead_data['cuSPARSE(v2)iluAna'][i]+overhead_data['cuSPARSE(v2)iu'][i]))\n\t\t oh_CUS2nolvl_wo_g1000K.append((0))\n\t\t oh_CUS2nolvl_w_g1000K.append((0))\n\t\t oh_SyncFree_wo_g1000K.append((overhead_data['Sync-Free ana'][i]))\n\t\t oh_SyncFree_w_g1000K.append((overhead_data['SycnFree_LU'][i]+overhead_data['Sync-Free ana'][i]))\n\t\t oh_FE_wo_g1000K.append(overhead_data['FE_oh_wo'][i])\n\t\t oh_FE_w_g1000K.append(overhead_data['FE_oh_w'][i])\n\t\t \n\t\t oh_MKLs_wo_g1000K_ana.append((overhead_data['MKL(seq) Ana'][i]))\n\t\t oh_MKLs_w_g1000K_ana.append((overhead_data['MKL(seq) Ana'][i]+overhead_data['MKL(seq) ilu'][i]))\n\t\t oh_MKLp_wo_g1000K_ana.append((overhead_data['MKL(par) Ana'][i]))\n\t\t oh_MKLp_w_g1000K_ana.append((overhead_data['MKL(par) Ana'][i]+overhead_data['MKL(par) ilu'][i]))\n\t\t oh_CUS1_wo_g1000K_ana.append((overhead_data['cuSPARSE(v1) ana'][i]))\n\t\t oh_CUS1_w_g1000K_ana.append((overhead_data['cuSPARSE(v1) ana'][i]+overhead_data['cuSPARSE(v1) ilu'][i]))\n\t\t oh_CUS2lvl_wo_g1000K_ana.append((overhead_data['cusparse(v2)ana'][i]))\n\t\t oh_CUS2lvl_w_g1000K_ana.append((overhead_data['cusparse(v2)ana'][i]+overhead_data['cuSPARSE(v2)lvl'][i]+\\\n\t\t overhead_data['cuSPARSE(v1) ilu'][i]+overhead_data['cuSPARSE(v2)iluAna'][i]+\\\n\t\t overhead_data['cuSPARSE(v2)iu'][i]))\n\t\t oh_CUS2nolvl_wo_g1000K_ana.append(0)\n\t\t oh_CUS2nolvl_w_g1000K_ana.append(0)\n\t\t oh_SyncFree_wo_g1000K_ana.append((overhead_data['Sync-Free ana'][i]))\n\t\t oh_SyncFree_w_g1000K_ana.append((overhead_data['SycnFree_LU'][i]+overhead_data['Sync-Free ana'][i]))\n\t\t \n\t\t #emp_oh_wo_g1000K.append(oh_MKLs_wo_g1000K[i] + oh_MKLp_wo_g1000K[i] + oh_CUS1_wo_g1000K[i] + oh_CUS2lvl_wo_g1000K[i] + oh_CUS2nolvl_wo_g1000K[i] + oh_SyncFree_wo_g1000K[i])\n\n\t\t i = i + 1\n\t\temp_oh_wo_100K = (np.sum(oh_MKLs_wo_100K)+np.sum(oh_MKLp_wo_100K)+np.sum(oh_CUS1_wo_100K) + \\\n\t\tnp.sum(oh_CUS2lvl_wo_100K) + np.sum(oh_CUS2nolvl_wo_100K) + np.sum(oh_SyncFree_wo_100K))\\\n\t\t/(len(oh_MKLs_wo_100K)*1000)\n\n\t\temp_oh_wo_1000K = (np.sum(oh_MKLs_wo_1000K)+np.sum(oh_MKLp_wo_1000K)+np.sum(oh_CUS1_wo_1000K) + \\\n\t\tnp.sum(oh_CUS2lvl_wo_1000K) + np.sum(oh_CUS2nolvl_wo_1000K) + np.sum(oh_SyncFree_wo_1000K))\\\n\t\t/(len(oh_MKLs_wo_1000K)*1000)\n\n\t\temp_oh_wo_g1000K = (np.sum(oh_MKLs_wo_g1000K)+np.sum(oh_MKLp_wo_g1000K)+np.sum(oh_CUS1_wo_g1000K) + \\\n\t\tnp.sum(oh_CUS2lvl_wo_g1000K) + np.sum(oh_CUS2nolvl_wo_g1000K) + np.sum(oh_SyncFree_wo_g1000K))\\\n\t\t/(len(oh_MKLs_wo_g1000K)*1000)\n\n\t\temp_oh_w_100K = (np.sum(oh_MKLs_w_100K)+np.sum(oh_MKLp_w_100K)+np.sum(oh_CUS1_w_100K) + \\\n\t\tnp.sum(oh_CUS2lvl_w_100K) + np.sum(oh_CUS2nolvl_w_100K) + np.sum(oh_SyncFree_w_100K))/(len(oh_MKLs_w_100K)*1000)\n\n\t\temp_oh_w_1000K = (np.sum(oh_MKLs_w_1000K)+np.sum(oh_MKLp_w_1000K)+np.sum(oh_CUS1_w_1000K) + \\\n\t\tnp.sum(oh_CUS2lvl_w_1000K) + np.sum(oh_CUS2nolvl_w_1000K) + np.sum(oh_SyncFree_w_1000K))\\\n\t\t/(len(oh_MKLs_w_1000K)*1000)\n\n\t\temp_oh_w_g1000K = (np.sum(oh_MKLs_w_g1000K)+np.sum(oh_MKLp_w_g1000K)+np.sum(oh_CUS1_w_g1000K) + \\\n\t\tnp.sum(oh_CUS2lvl_w_g1000K) + np.sum(oh_CUS2nolvl_w_g1000K) + np.sum(oh_SyncFree_w_g1000K))\\\n\t\t/(len(oh_MKLs_w_g1000K)*1000)\n\n\t\temp_oh_wo_g1000K_ana = (np.sum(oh_MKLs_wo_g1000K_ana)+np.sum(oh_MKLp_wo_g1000K_ana)+np.sum(oh_CUS1_wo_g1000K_ana) + \\\n\t\tnp.sum(oh_CUS2lvl_wo_g1000K_ana) + np.sum(oh_CUS2nolvl_wo_g1000K_ana) + np.sum(oh_SyncFree_wo_g1000K_ana))\\\n\t\t/(len(oh_MKLs_wo_g1000K_ana)*1000)\n\n\t\temp_oh_w_g1000K_ana = (np.sum(oh_MKLs_w_g1000K_ana)+np.sum(oh_MKLp_w_g1000K_ana)+np.sum(oh_CUS1_w_g1000K_ana) + \\\n\t\tnp.sum(oh_CUS2lvl_w_g1000K_ana) + np.sum(oh_CUS2nolvl_w_g1000K_ana) + np.sum(oh_SyncFree_w_g1000K_ana))\\\n\t\t/(len(oh_MKLs_w_g1000K_ana)*1000)\t\t \n\t\t\n\t\tOverhead_wo_100K_bar = (np.sum(oh_FE_wo_100K)/len(oh_FE_wo_100K), emp_oh_wo_100K, \\\n np.sum(oh_MKLs_wo_100K_ana)/(len(oh_MKLs_wo_100K_ana)*1000),\\\n np.sum(oh_MKLp_wo_100K_ana)/(len(oh_MKLp_wo_100K_ana)*1000),\\\n np.sum(oh_CUS1_wo_100K_ana)/(len(oh_MKLs_wo_100K_ana)*1000),\\\n np.sum(oh_CUS2lvl_wo_100K_ana)/(len(oh_CUS2lvl_wo_100K_ana)*1000),\\\n np.sum(oh_CUS2lvl_wo_100K_ana)/(len(oh_CUS2lvl_wo_100K_ana)*1000),\\\n np.sum(oh_SyncFree_wo_100K_ana)/(len(oh_SyncFree_wo_100K_ana)*1000))\n\n\t\tOverhead_w_100K_bar = (np.sum(oh_FE_w_100K)/len(oh_FE_w_100K), emp_oh_w_100K, \\\n np.sum(oh_MKLs_w_100K_ana)/(len(oh_MKLs_w_100K_ana)*1000),\\\n np.sum(oh_MKLp_w_100K_ana)/(len(oh_MKLp_w_100K_ana)*1000),\\\n np.sum(oh_CUS1_w_100K_ana)/(len(oh_CUS1_w_100K_ana)*1000),\\\n np.sum(oh_CUS2lvl_w_100K_ana)/(len(oh_CUS2lvl_w_100K_ana)*1000),\\\n np.sum(oh_CUS2lvl_w_100K_ana)/(len(oh_CUS2lvl_w_100K_ana)*1000),\\\n np.sum(oh_SyncFree_w_100K_ana)/(len(oh_SyncFree_w_100K_ana)*1000))\n\n\t\tOverhead_wo_1000K_bar = (np.sum(oh_FE_wo_1000K)/len(oh_FE_wo_1000K), emp_oh_wo_1000K, \\\n np.sum(oh_MKLs_wo_1000K_ana)/(len(oh_MKLs_wo_1000K_ana)*1000),\\\n np.sum(oh_MKLp_wo_1000K_ana)/(len(oh_MKLp_wo_1000K_ana)*1000),\\\n np.sum(oh_CUS1_wo_1000K_ana)/(len(oh_MKLs_wo_1000K_ana)*1000),\\\n np.sum(oh_CUS2lvl_wo_1000K_ana)/(len(oh_CUS2lvl_wo_1000K_ana)*1000),\\\n np.sum(oh_CUS2lvl_wo_1000K_ana)/(len(oh_CUS2lvl_wo_1000K_ana)*1000),\\\n np.sum(oh_SyncFree_wo_1000K_ana)/(len(oh_SyncFree_wo_1000K_ana)*1000))\n\n\t\tOverhead_w_1000K_bar = (np.sum(oh_FE_w_1000K)/len(oh_FE_w_1000K), emp_oh_w_1000K, \\\n np.sum(oh_MKLs_w_1000K_ana)/(len(oh_MKLs_w_1000K_ana)*1000),\\\n np.sum(oh_MKLp_w_1000K_ana)/(len(oh_MKLp_w_1000K_ana)*1000),\\\n np.sum(oh_CUS1_w_1000K_ana)/(len(oh_CUS1_w_1000K_ana)*1000),\\\n np.sum(oh_CUS2lvl_w_1000K_ana)/(len(oh_CUS2lvl_w_1000K_ana)*1000),\\\n np.sum(oh_CUS2lvl_w_1000K_ana)/(len(oh_CUS2lvl_w_1000K_ana)*1000),\\\n np.sum(oh_SyncFree_w_1000K_ana)/(len(oh_SyncFree_w_1000K_ana)*1000))\n\n\t\tOverhead_wo_g1000K_bar = (np.sum(oh_FE_wo_g1000K)/len(oh_FE_wo_g1000K), emp_oh_wo_g1000K, \\\n np.sum(oh_MKLs_wo_g1000K_ana)/(len(oh_MKLs_wo_g1000K_ana)*1000),\\\n np.sum(oh_MKLp_wo_g1000K_ana)/(len(oh_MKLp_wo_g1000K_ana)*1000),\\\n np.sum(oh_CUS1_wo_g1000K_ana)/(len(oh_MKLs_wo_g1000K_ana)*1000),\\\n np.sum(oh_CUS2lvl_wo_g1000K_ana)/(len(oh_CUS2lvl_wo_g1000K_ana)*1000),\\\n np.sum(oh_CUS2lvl_wo_g1000K_ana)/(len(oh_CUS2lvl_wo_g1000K_ana)*1000),\\\n np.sum(oh_SyncFree_wo_g1000K_ana)/(len(oh_SyncFree_wo_g1000K_ana)*1000))\n\n\t\tOverhead_w_g1000K_bar = (np.sum(oh_FE_w_g1000K)/len(oh_FE_w_g1000K), emp_oh_w_g1000K, \\\n np.sum(oh_MKLs_w_g1000K_ana)/(len(oh_MKLs_w_g1000K_ana)*1000),\\\n np.sum(oh_MKLp_w_g1000K_ana)/(len(oh_MKLp_w_g1000K_ana)*1000),\\\n np.sum(oh_CUS1_w_g1000K_ana)/(len(oh_CUS1_w_g1000K_ana)*1000),\\\n np.sum(oh_CUS2lvl_w_g1000K_ana)/(len(oh_CUS2lvl_w_g1000K_ana)*1000),\\\n np.sum(oh_CUS2lvl_w_g1000K_ana)/(len(oh_CUS2lvl_w_g1000K_ana)*1000),\\\n np.sum(oh_SyncFree_w_g1000K_ana)/(len(oh_SyncFree_w_g1000K_ana)*1000))\n\n\t\tprint('Number of lower triangular solve iterations (LTI) to amortize feature extraction overhead (FEO) without ILU')\n\t\tprint('%40s =%20d' % ('1K-100K Min LTI to amortize FEO',np.ceil(np.min(L_calls_vs_FE_wo_100K))))\n\t\tprint('%40s =%20d' % ('1K-100K Mean LTI to amortize FEO',np.ceil(np.mean(L_calls_vs_FE_wo_100K))))\n\t\tprint('%40s =%20d' % ('1K-100K Max LTI to amortize FEO',np.ceil(np.max(L_calls_vs_FE_wo_100K))))\n\t\tprint('%40s =%20d' % ('100K-1000K Min LTI to amortize FEO',np.ceil(np.min(L_calls_vs_FE_wo_1000K))))\n\t\tprint('%40s =%20d' % ('100K-1000K Mean LTI to amortize FEO',np.ceil(np.mean(L_calls_vs_FE_wo_1000K))))\n\t\tprint('%40s =%20d' % ('100K-1000K Max LTI to amortize FEO',np.ceil(np.max(L_calls_vs_FE_wo_1000K))))\n\t\tprint('%40s =%20d' % ('> 1000K Min LTI to amortize FEO',np.ceil(np.min(L_calls_vs_FE_wo_g1000K))))\n\t\tprint('%40s =%20d' % ('> 1000K Mean LTI to amortize FEO',np.ceil(np.mean(L_calls_vs_FE_wo_g1000K))))\n\t\tprint('%40s =%20d' % ('> 1000K Max LTI to amortize FEO',np.ceil(np.max(L_calls_vs_FE_wo_g1000K))))\n\t\tprint('')\n\t\t#print('Number of lower triangular solve iterations (LTI) to amortize feature extraction overhead (FEO) with ILU')\n\t\t#print('1K-100K Min LTI to amortize FEO=%20d' % np.ceil(np.min(L_calls_vs_FE_w_100K)))\n\t\t#print('1K-100K Mean LTI to amortize FEO=%20d' % np.ceil(np.mean(L_calls_vs_FE_w_100K)))\n\t\t#print('1K-100K Max LTI to amortize FEO=%20d' % np.ceil(np.max(L_calls_vs_FE_w_100K)))\n\t\t#print('100K-1000K Min LTI to amortize FEO=%20d' % np.ceil(np.min(L_calls_vs_FE_w_1000K)))\n\t\t#print('100K-1000K Mean LTI to amortize FEO=%20d' % np.ceil(np.mean(L_calls_vs_FE_w_1000K)))\n\t\t#print('100K-1000K Max LTI to amortize FEO=%20d' % np.ceil(np.max(L_calls_vs_FE_w_1000K)))\n\t\t##print('> 1000K Min LTI to amortize FEO=%20d' % np.ceil(np.min(L_calls_vs_FE_w_g1000K)))\n\t\t#print('> 1000K Mean LTI to amortize FEO=%20d' % np.ceil(np.mean(L_calls_vs_FE_w_g1000K)))\n\t\t#print('> 1000K Max LTI to amortize FEO=%20d' % np.ceil(np.max(L_calls_vs_FE_w_g1000K)))\n\t\t\n\t\tf, ax = plt.subplots(2, 3,figsize=(15, 6))\n\t\tN = 8\n\t\twidth = 0.55\n\t\tx = ('Framework','Agressive user','MKL(seq)','MKL(par)','cuSPARSE(v1)',\\\n \t\t'cuSPARSE(v2)\\n(level-sch.)','cuSPARSE(v2)\\n(no level-sch.)','Sync-Free')\n\t\tind = np.arange(N)\n\t\tx1 = ('','','','','','','','')\n\t\tp11 = ax[0,0].bar(ind, Overhead_wo_100K_bar, width,color='maroon')\n\t\tp12 = ax[0,1].bar(ind, Overhead_wo_1000K_bar, width,color='maroon')\n\t\tp13 = ax[0,2].bar(ind, Overhead_wo_g1000K_bar, width,color='maroon')\n\t\tp14 = ax[1,0].bar(ind, Overhead_w_100K_bar, width,color='maroon')\n\t\tp15 = ax[1,1].bar(ind, Overhead_w_1000K_bar, width,color='maroon')\n\t\tp16 = ax[1,2].bar(ind, Overhead_w_g1000K_bar, width,color='maroon')\n\t\tp11[0].set_color('b')\n\t\tp12[0].set_color('b')\n\t\tp13[0].set_color('b')\n\t\tp14[0].set_color('b')\n\t\tp15[0].set_color('b')\n\t\tp16[0].set_color('b')\n\t\tlabel_font = 12\n\t\tax[0,0].set_ylabel('Execution time (sec)',fontsize=12)\n\t\tax[0,0].set_yscale('log')\n\t\tax[0,0].set_xticks(np.arange(len(x)))\n\t\tax[0,0].set_xticklabels(x1,rotation=90,fontsize=label_font)\n\t\tax[0,0].set_title('Overhead (w/o ILU) 1K-100K',loc=\"left\")\n\t\tax[0,0].set_xlabel('(a)')\n\t\tax[0,1].set_yscale('log')\n\t\tax[0,1].set_xticks(np.arange(len(x)))\n\t\tax[0,1].set_xticklabels(x1,rotation=90,fontsize=label_font)\n\t\tax[0,1].set_title('Overhead (w/o ILU) 100K-1000K',loc=\"left\")\n\t\tax[0,1].set_xlabel('(b)')\n\t\tax[0,2].set_yscale('log')\n\t\tax[0,2].set_xticks(np.arange(len(x)))\n\t\tax[0,2].set_xticklabels(x1,rotation=90,fontsize=label_font)\n\t\tax[0,2].set_title('Overhead (w/o ILU) >1000K',loc=\"left\")\n\t\tax[0,2].set_xlabel('(c)')\n\t\tax[1,0].set_ylabel('Execution time (sec)',fontsize=12)\n\t\tax[1,0].set_yscale('log')\n\t\tax[1,0].set_xticks(np.arange(len(x)))\n\t\tax[1,0].set_xticklabels(x,rotation=90,fontsize=label_font)\n\t\tax[1,0].set_title('Overhead (w ILU) 1K-100K',loc=\"left\")\n\t\tax[1,0].set_xlabel('(d)')\n\t\tax[1,1].set_yscale('log')\n\t\tax[1,1].set_xticks(np.arange(len(x)))\n\t\tax[1,1].set_xticklabels(x,rotation=90,fontsize=label_font)\n\t\tax[1,1].set_title('Overhead (w ILU) 100K-1000K',loc=\"left\")\n\t\tax[1,1].set_xlabel('(e)')\n\t\tax[1,2].set_yscale('log')\n\t\tax[1,2].set_xticks(np.arange(len(x)))\n\t\tax[1,2].set_xticklabels(x,rotation=90,fontsize=label_font)\n\t\tax[1,2].set_title('Overhead (w ILU) >1000K',loc=\"left\")\n\t\tax[1,2].set_xlabel('(f)')\n\t\tplt.tight_layout()\n\t\tf.savefig('./datasets/figure10.pdf',bbox_inches='tight')\n\t\tprint(\"Figure 10 saved in datasets as figure10.eps\")\n\t\tprint(\"Note: Mean LTI to amortize FEO statistic for matrices with > 1000K row can slightly vary from line 3 page 13 and from run-to-run\")\n\n\n\n###############################################################\n### main code of the program\n###############################################################\nif __name__ == \"__main__\":\n\tprint(\"SpTRSV framework artifact evaluation Script\")\n\n\tif len(sys.argv) > 1:\n\t\toption = sys.argv[1]\n\n\t\tif option == \"figure2\":\n\t\t\tfigure1 = CPUGPUComparison()\n\t\t\tprint(\"Generating Figure 2. SpTRSV performance on Intel Xeon Gold (6148) CPU and an NVIDIA V100 GPU (32GB, PCIe)\")\n\t\t\tfigure1.DrawFigure('./datasets/CPU_GPU_best_SpTRSV_37_matrices.csv')\n\n\t\tif option == \"figure7\":\n\t\t\tfigure7 = Prediction()\n\t\t\tprint(\"Generating Figure 7. Model cross validation scores with 30 features in the feature set\")\n\t\t\tfigure7.CrossValidation('./datasets/Training_data.csv',2)\n\n\t\tif option == \"figure8\":\n\t\t\tfigure6 = Prediction()\n\t\t\tprint(\"Generating Figure 8. Model cross validation scores with 10 features in the feature set\")\n\t\t\tfigure6.CrossValidation('./datasets/Training_data.csv',1)\n\n\t\tif option == \"figure9\":\n\t\t\tfigure7 = Performance()\n\t\t\tprint(\"Generating Figure 9. Speedup gained by predicted over lazy choice algorithm. >= 1 indicates speedup of greater or equal to 1. Mean refers to average speedup (harmonic mean) achieved by the framework over the lazy choice.\")\n\t\t\tfigure7.Speedup('./datasets/Training_data.csv')\n\n\t\tif option == \"figure10\":\n\t\t\tfigure8 = Performance()\n\t\t\tprint(\"Generating Figure 10. Mean overhead of framework versus mean empirical execution time for aggressive and lazy users. 1K-100K, 100K-1000K and >1000K refer to matrix size ranges.\")\n\t\t\tfigure8.Overheads('./datasets/Training_data.csv','./datasets/Overhead.csv')\n\n\t\tif option == \"table1\":\n\t\t\ttable1 = CPUGPUComparison()\n\t\t\tprint(\"\\nTable 1. SpTRSV winning algorithm breakdown for 37 matrices in Figure 2\\n\")\n\t\t\ttable1.DrawComparisonTable('./datasets/CPU_GPU_SpTRSV_perf_data_37_matrices.csv')\n\n\t\tif option == \"table2\":\n\t\t\tfeaturescores = FeatureSelection()\n\t\t\tprint(\"\\nTable 2. Selected feature set for the prediction framework\\n\")\n\t\t\tfeaturescores.FeatureRanking('./datasets/Features.csv')\n\n\t\tif option == \"table3\":\n\t\t\ttable3 = CPUGPUComparison()\n\t\t\tprint(\"\\nTable 3. SpTRSV winning algorithm breakdown for the 998 matrices from SuiteSparse\\n\")\n\t\t\ttable3.DrawComparisonTable('./datasets/CPU_GPU_SpTRSV_comparison_full_dataset.csv')\n\n\t\tif option == \"table4\":\n\t\t\ttable4 = CPUGPUComparison()\n\t\t\tprint(\"\\nTable 4. Number of rows and nonzero statistics for the 998 matrices from SuiteSparse\\n\")\n\t\t\ttable4.DrawStatsTable('./datasets/CPU_GPU_SpTRSV_comparison_full_dataset.csv')\n\n\t\tif option == \"printallfeatures\":\n\t\t\tfeature_sel = FeatureSelection()\n\t\t\tfeature_sel.PrintAllFeatures('./datasets/Features.csv')\n\n\t\t\n\t\t\t\n\t\t\t\n"
] |
[
[
"matplotlib.pyplot.legend",
"scipy.stats.norm.ppf",
"numpy.sqrt",
"pandas.DataFrame",
"sklearn.model_selection.KFold",
"numpy.max",
"numpy.mean",
"pandas.read_csv",
"matplotlib.pyplot.tight_layout",
"sklearn.ensemble.RandomForestClassifier",
"numpy.arange",
"numpy.std",
"matplotlib.pyplot.figure",
"numpy.min",
"numpy.median",
"sklearn.model_selection.train_test_split",
"sklearn.feature_selection.SelectKBest",
"pandas.read_json",
"matplotlib.pyplot.show",
"numpy.sum",
"sklearn.model_selection.cross_val_predict",
"matplotlib.pyplot.subplots",
"scipy.stats.hmean",
"sklearn.model_selection.cross_validate",
"sklearn.preprocessing.StandardScaler"
]
] |
tilacyn/DeepSEED-3D-ConvNets-for-Pulmonary-Nodule-Detection
|
[
"c56c4b4acaa259d9a0fb22b0aebca69fc3b98331"
] |
[
"luna_detector/lidc_dataset.py"
] |
[
"import glob\nimport json\nimport os\nimport time\nfrom os.path import join as opjoin\n\nimport torch\nfrom torch.utils.data import Dataset\nimport xml.etree.ElementTree as ET\nimport pydicom as dicom\nimport numpy as np\nfrom data_loader import LabelMapping\nfrom data_loader import Crop\nfrom numpy import array as na\nimport cv2\n\nfrom config_training import config as config_training\n\nfrom PIL import Image, ImageDraw\n\nfrom matplotlib import pyplot as plt\n\n\ndef parseXML(scan_path):\n '''\n parse xml file\n args:\n xml file path\n output:\n nodule list\n [{nodule_id, roi:[{z, sop_uid, xy:[[x1,y1],[x2,y2],...]}]}]\n '''\n file_list = os.listdir(scan_path)\n xml_file = None\n for file in file_list:\n if '.' in file and file.split('.')[1] == 'xml':\n xml_file = file\n break\n prefix = \"{http://www.nih.gov}\"\n if xml_file is None:\n print('SCAN PATH: {}'.format(scan_path))\n tree = ET.parse(scan_path + '/' + xml_file)\n root = tree.getroot()\n readingSession_list = root.findall(prefix + \"readingSession\")\n nodules = []\n\n for session in readingSession_list:\n # print(session)\n unblinded_list = session.findall(prefix + \"unblindedReadNodule\")\n for unblinded in unblinded_list:\n nodule_id = unblinded.find(prefix + \"noduleID\").text\n edgeMap_num = len(unblinded.findall(prefix + \"roi/\" + prefix + \"edgeMap\"))\n if edgeMap_num >= 1:\n # it's segmentation label\n nodule_info = {}\n nodule_info['nodule_id'] = nodule_id\n nodule_info['roi'] = []\n roi_list = unblinded.findall(prefix + \"roi\")\n for roi in roi_list:\n roi_info = {}\n # roi_info['z'] = float(roi.find(prefix + \"imageZposition\").text)\n roi_info['sop_uid'] = roi.find(prefix + \"imageSOP_UID\").text\n roi_info['xy'] = []\n edgeMap_list = roi.findall(prefix + \"edgeMap\")\n for edgeMap in edgeMap_list:\n x = float(edgeMap.find(prefix + \"xCoord\").text)\n y = float(edgeMap.find(prefix + \"yCoord\").text)\n xy = [x, y]\n roi_info['xy'].append(xy)\n nodule_info['roi'].append(roi_info)\n nodules.append(nodule_info)\n return nodules\n\n\ndef make_mask(image, image_id, nodules):\n height, width = image.shape\n # print(image.shape)\n filled_mask = np.full((height, width), 0, np.uint8)\n contoured_mask = np.full((height, width), 0, np.uint8)\n # todo OR for all masks\n for nodule in nodules:\n for roi in nodule['roi']:\n if roi['sop_uid'] == image_id:\n edge_map = roi['xy']\n cv2.fillPoly(filled_mask, np.int32([np.array(edge_map)]), 255)\n # cv2.polylines(contoured_mask, np.int32([np.array(edge_map)]), color=255, isClosed=False)\n\n # mask = np.swapaxes(np.array([contoured_mask, filled_mask]), 0, 2)\n # cv2.imwrite('kek0.jpg', image)\n # cv2.imwrite('kek1.jpg', filled_mask)\n return np.reshape(filled_mask, (height, width, 1))\n\n\ndef create_map_from_nodules(nodules):\n id2roi = {}\n for nodule in nodules:\n for roi in nodule['roi']:\n id = roi['sop_uid']\n if id not in id2roi:\n id2roi[id] = []\n id2roi[id].append(roi['xy'])\n return id2roi\n\n\ndef make_mask_for_rgb(image, image_id, nodules):\n filled_mask = image\n for nodule in nodules:\n for roi in nodule['roi']:\n if roi['sop_uid'] == image_id:\n edge_map = roi['xy']\n cv2.fillPoly(filled_mask, np.int32([np.array(edge_map)]), (255, 0, 0))\n return filled_mask\n\n\ndef imread(image_path):\n ds = dicom.dcmread(image_path)\n img = ds.pixel_array\n img_2d = img.astype(float)\n img_2d_scaled = (np.maximum(img_2d, 0) / img_2d.max()) * 255.0\n img_2d_scaled = np.uint8(img_2d_scaled)\n image = img_2d_scaled\n return image, ds\n\n\ndef resolve_bbox(dcms, id2roi):\n nodule_coordinates = []\n for i, dcm in enumerate(dcms):\n image, dcm_data = dcm\n if dcm_data.SOPInstanceUID not in id2roi:\n continue\n rois = id2roi[dcm_data.SOPInstanceUID]\n roi = rois[0]\n mean = np.mean(roi, axis=0)\n nodule_coordinates.append([i, mean[0], mean[1]])\n if len(nodule_coordinates) == 0:\n print('Nodule coordinates empty list')\n raise ValueError('invalid bbox')\n return np.concatenate((np.mean(nodule_coordinates, axis=0), [5.0]))\n\n\nNPY_LOAD_MARKER = -5\n\n\nclass LIDCDataset(Dataset):\n def __init__(self, data_path, config, stard_idx, end_idx, load=False, isRand=False, phase='train', random=False):\n self.data_path = data_path\n self.ids = []\n self.start_idx = stard_idx\n self.end_idx = end_idx\n self.create_ids()\n self.phase = phase\n self.label_mapping = LabelMapping(config, 'train')\n self.crop = Crop(config, random)\n self.load = load\n self.lidc_npy_path = config_training['lidc-npy']\n self.isRand = isRand\n self.random = random\n\n def __getitem__(self, idx):\n t = time.time()\n np.random.seed(int(str(t % 1)[2:7])) # seed according to time\n\n if self.phase == 'test':\n isRand = np.random.randint(0, 2) == 0\n else:\n isRand = self.isRand\n imgs, bbox = self.get_data_from_npy(idx)\n # print(bbox)\n sample, target, bboxes, coord, real_target = self.crop(imgs, bbox, [bbox], isScale=False, isRand=isRand)\n label = self.label_mapping(sample.shape[1:], target, bboxes)\n sample = (sample.astype(np.float32) - 128) / 128\n\n return torch.from_numpy(sample), \\\n torch.from_numpy(label), \\\n coord, \\\n real_target\n\n def get_data_from_dcm(self, idx):\n dcms = []\n parent_path = self.ids[idx]\n for file in os.listdir(parent_path):\n if not file.endswith('dcm'):\n continue\n image, dcm_data = imread(opjoin(parent_path, file))\n if not has_slice_location(dcm_data):\n continue\n dcms.append((image, dcm_data))\n dcms.sort(key=lambda dcm: dcm[1].SliceLocation)\n nodules = parseXML(parent_path)\n id2roi = create_map_from_nodules(nodules)\n imgs = na([dcm[0] for dcm in dcms])\n imgs = imgs[np.newaxis, :]\n bbox = resolve_bbox(na(dcms), id2roi)\n return imgs, bbox\n\n def get_data_from_npy(self, idx):\n load_imgs_path = opjoin(self.lidc_npy_path, 'imgs_%d.npy' % idx)\n load_bbox_path = opjoin(self.lidc_npy_path, 'bbox_%d.npy' % idx)\n imgs = np.load(load_imgs_path)\n bbox = np.load(load_bbox_path)\n return imgs, bbox\n\n def get_preprocessed_data_from_npy(self, idx):\n make_load_path = lambda x: opjoin(self.lidc_npy_path, '%s_%d.npy' % (x, idx))\n sample = np.load(make_load_path('sample'))\n label = np.load(make_load_path('label'))\n coord = np.load(make_load_path('coord'))\n return sample, label, coord\n\n def save_npy(self, start, end):\n for i in range(start, end):\n print('processing %d' % i)\n try:\n imgs, bbox = self.get_data_from_dcm(i)\n except:\n imgs, bbox = self.get_data_from_dcm(i - 1)\n\n save_imgs_path = opjoin(self.lidc_npy_path, 'imgs_%d.npy' % i)\n save_bbox_path = opjoin(self.lidc_npy_path, 'bbox_%d.npy' % i)\n\n np.save(save_bbox_path, bbox)\n np.save(save_imgs_path, imgs)\n\n def __len__(self):\n return len(self.ids)\n\n def create_ids(self):\n with open('index.json', 'r') as read_file:\n self.ids = json.load(read_file)\n self.ids = self.ids[self.start_idx:self.end_idx]\n\n\ndef has_slice_location(dcm_data):\n try:\n slice_location = dcm_data.SliceLocation\n return True\n except:\n # print('No Slice Location')\n return False\n\n\ndef create_index(data_path):\n ids = []\n for root, _, files in os.walk(data_path):\n if glob.glob(opjoin(data_path, root, '*xml')):\n nodules = parseXML(opjoin(data_path, root))\n id2roi = create_map_from_nodules(nodules)\n if len(id2roi) == 0:\n continue\n ids.append(root)\n with open('index.json', 'w') as write_file:\n json.dump(ids, write_file)\n"
] |
[
[
"numpy.maximum",
"numpy.reshape",
"numpy.uint8",
"torch.from_numpy",
"numpy.save",
"numpy.full",
"numpy.mean",
"numpy.load",
"numpy.array",
"numpy.random.randint"
]
] |
sidhikabalachandar/lig_clash_score
|
[
"449bac16a7c2b9779e7cd51ff17eb5e41be6ff99"
] |
[
"src/models/train_pdbbind.py"
] |
[
"\"\"\"\nThe purpose of this code is to train the gnn model\n\nIt can be run on sherlock using\n$ sbatch 1gpu_gnn_score_feat.sbatch /home/groups/rondror/software/sidhikab/miniconda/envs/test_env/bin/python train_pdbbind_score_layer.py /home/users/sidhikab/lig_clash_score/models /oak/stanford/groups/rondror/projects/combind/flexibility/atom3d/processed_clustered_score /oak/stanford/groups/rondror/projects/combind/flexibility/atom3d/splits --mode train_test --split balance_clash --log_dir gnn_score_clustered\n$ sbatch 1gpu.sbatch /home/groups/rondror/software/sidhikab/miniconda/envs/test_env/bin/python train_pdbbind_score_layer.py /home/users/sidhikab/lig_clash_score/models /oak/stanford/groups/rondror/projects/combind/flexibility/atom3d --mode test --log_dir v1\n\"\"\"\nimport os\nimport time\nimport logging\nfrom scipy.stats import spearmanr\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\nimport datetime\nimport argparse\nimport pickle\n\nimport torch\nimport torch.nn.functional as F\nfrom torch.nn import Sequential, Linear, ReLU, MSELoss\nfrom torch_geometric.nn import GCNConv, GINConv, global_add_pool\n\nfrom pdbbind_dataloader import pdbbind_dataloader\n\ntorch.backends.cudnn.deterministic = True\ntorch.backends.cudnn.benchmark = False\n\nclass GCN(torch.nn.Module):\n def __init__(self, num_features, hidden_dim):\n super(GCN, self).__init__()\n self.conv1 = GCNConv(num_features, hidden_dim)\n self.bn1 = torch.nn.BatchNorm1d(hidden_dim)\n self.conv2 = GCNConv(hidden_dim, hidden_dim*2)\n self.bn2 = torch.nn.BatchNorm1d(hidden_dim*2)\n self.conv3 = GCNConv(hidden_dim*2, hidden_dim*4)\n self.bn3 = torch.nn.BatchNorm1d(hidden_dim*4)\n self.conv4 = GCNConv(hidden_dim*4, hidden_dim*4)\n self.bn4 = torch.nn.BatchNorm1d(hidden_dim*4)\n self.conv5 = GCNConv(hidden_dim*4, hidden_dim*8)\n self.bn5 = torch.nn.BatchNorm1d(hidden_dim*8)\n self.fc1 = Linear(hidden_dim*8, hidden_dim*4)\n self.fc2 = Linear(hidden_dim*4, 1)\n\n\n def forward(self, x, edge_index, edge_weight, batch, physics_score):\n x = self.conv1(x, edge_index, edge_weight)\n x = F.relu(x)\n x = self.bn1(x)\n x = self.conv2(x, edge_index, edge_weight)\n x = F.relu(x)\n x = self.bn2(x)\n x = self.conv3(x, edge_index, edge_weight)\n x = F.relu(x)\n x = self.bn3(x)\n x = self.conv4(x, edge_index, edge_weight)\n x = self.bn4(x)\n x = F.relu(x)\n x = self.conv5(x, edge_index, edge_weight)\n x = self.bn5(x)\n x = global_add_pool(x, batch)\n x = F.relu(x)\n x = F.relu(self.fc1(x))\n x = F.dropout(x, p=0.25, training=self.training)\n return self.fc2(x).view(-1)\n\nclass GCN_score_layer(torch.nn.Module):\n def __init__(self, num_features, hidden_dim):\n super(GCN_score_layer, self).__init__()\n self.conv1 = GCNConv(num_features, hidden_dim)\n self.bn1 = torch.nn.BatchNorm1d(hidden_dim)\n self.conv2 = GCNConv(hidden_dim, hidden_dim*2)\n self.bn2 = torch.nn.BatchNorm1d(hidden_dim*2)\n self.conv3 = GCNConv(hidden_dim*2, hidden_dim*4)\n self.bn3 = torch.nn.BatchNorm1d(hidden_dim*4)\n self.conv4 = GCNConv(hidden_dim*4, hidden_dim*4)\n self.bn4 = torch.nn.BatchNorm1d(hidden_dim*4)\n self.conv5 = GCNConv(hidden_dim*4, hidden_dim*8)\n self.bn5 = torch.nn.BatchNorm1d(hidden_dim*8)\n self.fc1 = Linear(hidden_dim*8, hidden_dim*4)\n self.fc2 = Linear(hidden_dim*4, 1)\n self.hybrid_score = Linear(2, 1)\n\n\n def forward(self, x, edge_index, edge_weight, batch, physics_score):\n x = self.conv1(x, edge_index, edge_weight)\n x = F.relu(x)\n x = self.bn1(x)\n x = self.conv2(x, edge_index, edge_weight)\n x = F.relu(x)\n x = self.bn2(x)\n x = self.conv3(x, edge_index, edge_weight)\n x = F.relu(x)\n x = self.bn3(x)\n x = self.conv4(x, edge_index, edge_weight)\n x = self.bn4(x)\n x = F.relu(x)\n x = self.conv5(x, edge_index, edge_weight)\n x = self.bn5(x)\n x = global_add_pool(x, batch)\n x = F.relu(x)\n x = F.relu(self.fc1(x))\n x = F.dropout(x, p=0.25, training=self.training)\n gnn_score = self.fc2(x).view(-1)\n combined = torch.cat((torch.unsqueeze(gnn_score, 1), torch.unsqueeze(physics_score, 1)), dim=1)\n output = torch.squeeze(self.hybrid_score(combined))\n return output\n\n\n\ndef train(model, loader, optimizer, device):\n model.train()\n loss_all = 0\n total = 0\n for data in loader:\n data = data.to(device)\n optimizer.zero_grad()\n output = model(data.x, data.edge_index, data.edge_attr.view(-1), data.batch, data.physics_score)\n loss = F.mse_loss(output, data.y)\n loss.backward()\n loss_all += loss.item() * data.num_graphs\n total += data.num_graphs\n optimizer.step()\n return np.sqrt(loss_all / total)\n\n\[email protected]_grad()\ndef test(model, loader, device):\n model.eval()\n\n loss_all = 0\n total = 0\n\n y_true = []\n y_pred = []\n\n for data in loader:\n data = data.to(device)\n output = model(data.x, data.edge_index, data.edge_attr.view(-1), data.batch, data.physics_score)\n loss = F.mse_loss(output, data.y)\n loss_all += loss.item() * data.num_graphs\n total += data.num_graphs\n y_true.extend(data.y.tolist())\n y_pred.extend(output.tolist())\n\n\n r_p = np.corrcoef(y_true, y_pred)[0,1]\n r_s = spearmanr(y_true, y_pred)[0]\n return np.sqrt(loss_all / total), r_p, r_s, y_true, y_pred\n\ndef plot_corr(y_true, y_pred, plot_dir):\n plt.clf()\n sns.scatterplot(y_true, y_pred)\n plt.xlabel('Actual -log(K)')\n plt.ylabel('Predicted -log(K)')\n plt.savefig(plot_dir)\n\ndef save_weights(model, weight_dir):\n torch.save(model.state_dict(), weight_dir)\n\ndef save_results(log_dir, split, mode, y_pred, loader):\n outfile = open(os.path.join(log_dir, f'{mode}_y_pred_{split}.pkl'), 'wb')\n pickle.dump(y_pred, outfile)\n\n codes = []\n for data in loader:\n codes.extend(data.pdb)\n\n outfile = open(os.path.join(log_dir, f'{mode}_loader_codes_{split}.pkl'), 'wb')\n pickle.dump(codes, outfile)\n\n\ndef train_pdbbind(split, architecture, mode, device, log_dir, data_path, split_path, seed=None):\n logger = logging.getLogger('pdbbind_log')\n\n num_epochs = 100\n batch_size = 700\n hidden_dim = 64\n learning_rate = 1e-4\n train_split = os.path.join(split_path, f'train_{split}.txt')\n val_split = os.path.join(split_path, f'val_{split}.txt')\n test_split = os.path.join(split_path,f'test_{split}.txt')\n train_loader = pdbbind_dataloader(batch_size, data_dir=data_path, split_file=train_split)\n f = open(os.path.join(log_dir, 'output.txt'), \"a\")\n f.write('Train size:' + str(len(train_loader)) + '\\n')\n f.close()\n val_loader = pdbbind_dataloader(batch_size, data_dir=data_path, split_file=val_split)\n f = open(os.path.join(log_dir, 'output.txt'), \"a\")\n f.write('Val size:' + str(len(val_loader)) + '\\n')\n f.close()\n test_loader = pdbbind_dataloader(500, data_dir=data_path, split_file=test_split)\n f = open(os.path.join(log_dir, 'output.txt'), \"a\")\n f.write('Test size:' + str(len(test_loader)) + '\\n')\n f.close()\n\n if not os.path.exists(os.path.join(log_dir, 'params.txt')):\n with open(os.path.join(log_dir, 'params.txt'), 'w') as f:\n f.write(f'Split method: {split}\\n')\n f.write(f'Model: {architecture}\\n')\n f.write(f'Epochs: {num_epochs}\\n')\n f.write(f'Batch size: {batch_size}\\n')\n f.write(f'Hidden dim: {hidden_dim}\\n')\n f.write(f'Learning rate: {learning_rate}')\n\n for data in train_loader:\n num_features = data.num_features\n break\n\n if architecture == 'GCN':\n model = GCN(num_features, hidden_dim=hidden_dim).to(device)\n elif architecture == 'GCN_score_layer':\n model = GCN_score_layer(num_features, hidden_dim=hidden_dim).to(device)\n model.to(device)\n\n if mode == \"train_results\":\n model.load_state_dict(torch.load(os.path.join(log_dir, f'best_weights_{split}.pt')))\n rmse, pearson, spearman, y_true, y_pred = test(model, train_loader, device)\n save_results(log_dir, split, \"train\", y_pred, train_loader)\n elif mode == \"train\":\n best_val_loss = 999\n\n\n optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\n\n for epoch in range(1, num_epochs+1):\n start = time.time()\n train_loss = train(model, train_loader, optimizer, device)\n val_loss, r_p, r_s, y_true, y_pred = test(model, val_loader, device)\n if val_loss < best_val_loss:\n save_weights(model, os.path.join(log_dir, f'best_weights_{split}.pt'))\n plot_corr(y_true, y_pred, os.path.join(log_dir, f'corr_{split}.png'))\n best_val_loss = val_loss\n\n elapsed = (time.time() - start)\n f = open(os.path.join(log_dir, 'output.txt'), \"a\")\n f.write('Epoch: {:03d}, Time: {:.3f} s\\n'.format(epoch, elapsed))\n f.close()\n print('Epoch: {:03d}, Time: {:.3f} s'.format(epoch, elapsed))\n f = open(os.path.join(log_dir, 'output.txt'), \"a\")\n f.write('\\tTrain RMSE: {:.7f}, Val RMSE: {:.7f}, Pearson R: {:.7f}, Spearman R: {:.7f}\\n'.format(train_loss, val_loss, r_p, r_s))\n f.close()\n print('\\tTrain RMSE: {:.7f}, Val RMSE: {:.7f}, Pearson R: {:.7f}, Spearman R: {:.7f}'.format(train_loss, val_loss, r_p, r_s))\n logger.info('{:03d}\\t{:.7f}\\t{:.7f}\\t{:.7f}\\t{:.7f}\\n'.format(epoch, train_loss, val_loss, r_p, r_s))\n\n if epoch == num_epochs:\n save_results(log_dir, split, 'train', y_pred, train_loader)\n\n if mode == \"train\" or mode == \"test\":\n # save testing results\n test_file = os.path.join(log_dir, f'test_results_{split}.txt')\n model.load_state_dict(torch.load(os.path.join(log_dir, f'best_weights_{split}.pt')))\n rmse, pearson, spearman, y_true, y_pred = test(model, test_loader, device)\n plot_corr(y_true, y_pred, os.path.join(log_dir, f'corr_{split}_test.png'))\n f = open(os.path.join(log_dir, 'output.txt'), \"a\")\n f.write('Test RMSE: {:.7f}, Pearson R: {:.7f}, Spearman R: {:.7f}\\n'.format(rmse, pearson, spearman))\n f.close()\n print('Test RMSE: {:.7f}, Pearson R: {:.7f}, Spearman R: {:.7f}'.format(rmse, pearson, spearman))\n with open(test_file, 'a+') as out:\n out.write('{}\\t{:.7f}\\t{:.7f}\\t{:.7f}\\n'.format(seed, rmse, pearson, spearman))\n\n save_results(log_dir, split, 'test', y_pred, test_loader)\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('out_dir', type=str, help='directory where all logging data will be written')\n parser.add_argument('root', type=str, help='directory where raw and processed directories can be found')\n parser.add_argument('split_path', type=str, help='directory where raw and processed directories can be found')\n parser.add_argument('--mode', type=str, default='train', help='either train, test, or train_results')\n parser.add_argument('--split', type=str, default='random', help='name of split files')\n parser.add_argument('--architecture', type=str, default='GCN', help='either GCN or GCN_score_layer')\n parser.add_argument('--log_dir', type=str, default=None, help='specific logging directory')\n args = parser.parse_args()\n\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n log_dir = args.log_dir\n\n\n if args.mode == 'train':\n if log_dir is None:\n now = datetime.datetime.now().strftime(\"%Y-%m-%d-%H-%M-%S\")\n log_dir = os.path.join(args.out_dir, 'logs', now)\n else:\n log_dir = os.path.join(args.out_dir, 'logs', log_dir)\n if not os.path.exists(log_dir):\n os.makedirs(log_dir)\n train_pdbbind(args.split, args.architecture, args.mode, device, log_dir, args.root, args.split_path)\n elif args.mode == 'test' or args.mode == 'train_results':\n seed = 0\n log_dir = os.path.join(args.out_dir, 'logs', args.log_dir)\n np.random.seed(seed)\n torch.manual_seed(seed)\n train_pdbbind(args.split, args.architecture, args.mode, device, log_dir, args.root, args.split_path, seed)\n\nif __name__==\"__main__\":\n main()\n\n\n\n\n\n\n"
] |
[
[
"torch.nn.BatchNorm1d",
"numpy.sqrt",
"numpy.random.seed",
"torch.nn.functional.dropout",
"torch.manual_seed",
"scipy.stats.spearmanr",
"matplotlib.pyplot.savefig",
"torch.unsqueeze",
"torch.nn.Linear",
"torch.nn.functional.mse_loss",
"matplotlib.pyplot.clf",
"torch.no_grad",
"torch.nn.functional.relu",
"torch.cuda.is_available",
"numpy.corrcoef",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.ylabel"
]
] |
PipeGen/pipeline-generator
|
[
"be69df0eab4601259bb0d084e56bf0b60b35f5ea"
] |
[
"datawiz/modules/loader.py"
] |
[
"import pandas as pd\nfrom var_dict import VarDict\n\nclass Loader():\n def __init__(self, vardict=VarDict()):\n self.vardict = vardict\n \n def load(self, data, data_name):\n df = pd.read_csv(data)\n self.vardict.add(df, data_name, \"df\")"
] |
[
[
"pandas.read_csv"
]
] |
aisthesis/opttrack
|
[
"17e0c7740ea43e0f07166e30d689b106d0319d0b"
] |
[
"opttrack/lib/spreads/dgb_finder.py"
] |
[
"\"\"\"\n./opttrack/lib/spreads/dgb_finder.py\n\nCopyright (c) 2016 Marshall Farrier\nlicense http://opensource.org/licenses/MIT\n\nFind promising diagonal butterfly spreads.\n\nThe logic for defining promising spreads is encapsulated\nin the function `_meets_criteria()` below.\n\"\"\"\n\nimport locale\n\nimport pandas as pd\n\nfrom .optspread import OptSpread\nfrom .optutils import get_price\nfrom .. import strikes\n\nMIN_RATIO = 1.5\n\nclass DgbFinder(object):\n\n def __init__(self, opts, opt_factory):\n self.opts = opts\n self.opt_factory = opt_factory\n self._diff_filter = _get_diff_filter()\n\n def run(self):\n # necessary for dealing with comma-grouped strike prices\n prior_loc = locale.getlocale()\n locale.setlocale(locale.LC_ALL, 'en_US')\n nearexpiries = self._get_nearexpiries()\n straddles = self._get_straddles(nearexpiries)\n dgbs = self._get_dgbs(straddles)\n locale.setlocale(locale.LC_ALL, prior_loc)\n return dgbs\n\n def _get_dgbs(self, straddles):\n dgbs = []\n for straddle in straddles:\n dgbs.extend(self._get_dgbs_for_straddle(straddle))\n return dgbs\n\n def _get_dgbs_for_straddle(self, straddle):\n expiries = self.opts.exps()[self.opts.exps().slice_indexer(straddle['Expiry'] + \n self._diff_filter['min'], straddle['Expiry'] + self._diff_filter['max'])]\n dgbs = []\n for expiry in expiries:\n dgbs.extend(self._get_dgbs_for_expiry(straddle, expiry))\n return dgbs\n\n def _get_dgbs_for_expiry(self, straddle, expiry):\n call_strikes = strikes.allforexp(self.opts, expiry, 'call')\n put_strikes = strikes.allforexp(self.opts, expiry, 'put')\n min_putstrike = straddle['Strike'] - straddle['Price']['total']\n dgbs = []\n call_end_ix = len(call_strikes) - 1\n for put_strike in put_strikes:\n if put_strike < min_putstrike:\n continue\n if put_strike >= straddle['Strike']:\n return dgbs\n strike_diff = straddle['Strike'] - put_strike\n call_ix = strikes.getlastmatched(straddle['Strike'] + strike_diff, call_strikes, call_end_ix)\n # only consider cases where there is a call matching the put\n if call_ix < 0:\n continue\n call_end_ix = call_ix\n strangle = self._get_strangle(straddle, call_strikes[call_ix], put_strike, expiry)\n metrics = _get_metrics(straddle, strangle, strike_diff)\n if _meets_criteria(metrics):\n dgbs.append(self._get_spread(straddle, strangle, metrics))\n return dgbs\n\n def _get_strangle(self, straddle, call_strike, put_strike, expiry):\n strangle = {'call': {}, 'put': {}}\n strangle['call']['Price'] = get_price(self.opts, 'call', call_strike, expiry)\n strangle['call']['Expiry'] = expiry\n strangle['call']['Strike'] = call_strike\n strangle['put']['Price'] = get_price(self.opts, 'put', put_strike, expiry)\n strangle['put']['Expiry'] = expiry\n strangle['put']['Strike'] = put_strike\n return strangle\n\n def _get_spread(self, straddle, strangle, metrics):\n underlying = self.opts.data.iloc[0].loc['Underlying']\n spread = OptSpread(underlying, 'dgb', self.opts.data.iloc[0].loc['Underlying_Price'], metrics['Credit'])\n for opt_type in ('call', 'put',):\n spread.buy_one(self.opt_factory.make(strangle[opt_type]['Strike'], strangle[opt_type]['Expiry'],\n opt_type, strangle[opt_type]['Price'], underlying))\n spread.sell_one(self.opt_factory.make(straddle['Strike'], straddle['Expiry'],\n opt_type, straddle['Price'][opt_type], underlying))\n return spread\n\n def _get_nearexpiries(self):\n min_exp = self.opts.quotetime() + pd.Timedelta('90 days')\n max_exp = self.opts.quotetime() + pd.Timedelta('135 days')\n return self.opts.exps()[self.opts.exps().slice_indexer(min_exp, max_exp)]\n\n def _get_straddles(self, expiries):\n straddles = []\n for expiry in expiries:\n straddles.extend(self._get_straddles_forexp(expiry))\n return straddles\n\n def _get_straddles_forexp(self, expiry):\n \"\"\"\n The list will normally contain 2 straddles only if the underlying\n price is exactly between 2 strikes. If the underlying is closer to\n 1 strike than another, the list will contain only 1 element.\n \"\"\"\n straddles = []\n all_strikes = strikes.matchedforexp(self.opts, expiry)\n eqprice = self.opts.data.iloc[0].loc['Underlying_Price']\n straddle_strikes = strikes.closest(all_strikes, eqprice)\n for straddle_strike in straddle_strikes:\n call_price = get_price(self.opts, 'call', straddle_strike, expiry)\n put_price = get_price(self.opts, 'put', straddle_strike, expiry)\n straddles.append({\n 'Expiry': expiry, \n 'Strike': straddle_strike, \n 'Price': {\n 'call': call_price, \n 'put': put_price,\n 'total': call_price + put_price}})\n return straddles\n\ndef _get_diff_filter():\n # distance between near and far expiry\n diff_filter = {}\n # 3rd Friday range:\n # earliest: 15\n # latest: 21\n # near falls on 02-21, far on 05-16 less 1\n diff_filter['min'] = pd.Timedelta('83 days')\n # near falls on 03-15, far on 06-21 plus 1\n diff_filter['max'] = pd.Timedelta('98 days')\n return diff_filter\n\ndef _meets_criteria(metrics):\n # criteria for considering this type of spread\n return metrics['Credit'] > metrics['Risk'] and metrics['Ratio'] >= MIN_RATIO\n\ndef _get_metrics(straddle, strangle, strike_diff):\n metrics = {}\n metrics['Near_Price'] = straddle['Price']['total']\n metrics['Far_Price'] = strangle['call']['Price'] + strangle['put']['Price']\n metrics['Credit'] = straddle['Price']['total'] - metrics['Far_Price']\n metrics['Risk'] = strike_diff - metrics['Credit']\n metrics['Ratio'] = straddle['Price']['total'] / metrics['Far_Price']\n return metrics\n\n"
] |
[
[
"pandas.Timedelta"
]
] |
McMasterAI/RadiologyandAI-MedicalZooPytorch
|
[
"c6831d8ddebfbc1b33c04f8cec0d01c2ceb828f6",
"c6831d8ddebfbc1b33c04f8cec0d01c2ceb828f6"
] |
[
"lib/augment3D/elastic_deform.py",
"lib/medloaders/iseg2017.py"
] |
[
"import numpy as np\nfrom scipy.interpolate import RegularGridInterpolator\nfrom scipy.ndimage.filters import gaussian_filter\n\n\"\"\"\n Elastic deformation of images as described in\n Simard, Steinkraus and Platt, \"Best Practices for\n Convolutional Neural Networks applied to Visual\n Document Analysis\", in\n Proc. of the International Conference on Document Analysis and\n Recognition, 2003.\n\n Modified from:\n https://gist.github.com/chsasank/4d8f68caf01f041a6453e67fb30f8f5a\n https://github.com/fcalvet/image_tools/blob/master/image_augmentation.py#L62\n\n Modified to take 3D inputs\n Deforms both the image and corresponding label file\n Label volumes are interpolated via nearest neighbour \n \"\"\"\n\n\ndef elastic_transform_3d(img_numpy, labels=None, alpha=1, sigma=20, c_val=0.0, method=\"linear\"):\n \"\"\"\n :param img_numpy: 3D medical image modality\n :param labels: 3D medical image labels\n :param alpha: scaling factor of gaussian filter\n :param sigma: standard deviation of random gaussian filter\n :param c_val: fill value\n :param method: interpolation method. supported methods : (\"linear\", \"nearest\")\n :return: deformed image and/or label\n \"\"\"\n assert img_numpy.ndim == 3, 'Wrong img shape, provide 3D img'\n if labels is not None:\n assert img_numpy.shape == labels.shape, \"Shapes of img and label do not much!\"\n shape = img_numpy.shape\n\n # Define 3D coordinate system\n coords = np.arange(shape[0]), np.arange(shape[1]), np.arange(shape[2])\n\n # Interpolated img\n im_intrps = RegularGridInterpolator(coords, img_numpy,\n method=method,\n bounds_error=False,\n fill_value=c_val)\n\n # Get random elastic deformations\n dx = gaussian_filter((np.random.rand(*shape) * 2 - 1), sigma,\n mode=\"constant\", cval=0.) * alpha\n dy = gaussian_filter((np.random.rand(*shape) * 2 - 1), sigma,\n mode=\"constant\", cval=0.) * alpha\n dz = gaussian_filter((np.random.rand(*shape) * 2 - 1), sigma,\n mode=\"constant\", cval=0.) * alpha\n\n # Define sample points\n x, y, z = np.mgrid[0:shape[0], 0:shape[1], 0:shape[2]]\n indices = np.reshape(x + dx, (-1, 1)), \\\n np.reshape(y + dy, (-1, 1)), \\\n np.reshape(z + dz, (-1, 1))\n\n # Interpolate 3D image image\n img_numpy = im_intrps(indices).reshape(shape)\n\n # Interpolate labels\n if labels is not None:\n lab_intrp = RegularGridInterpolator(coords, labels,\n method=\"nearest\",\n bounds_error=False,\n fill_value=0)\n\n labels = lab_intrp(indices).reshape(shape).astype(labels.dtype)\n return img_numpy, labels\n\n return img_numpy\n\n\nclass ElasticTransform(object):\n def __init__(self, alpha=1, sigma=20, c_val=0.0, method=\"linear\"):\n self.alpha = alpha\n self.sigma = sigma\n self.c_val = c_val\n self.method = method\n\n def __call__(self, img_numpy, label=None):\n return elastic_transform_3d(img_numpy, label, self.alpha, self.sigma, self.c_val, self.method)\n",
"import glob\nimport os\n\nimport numpy as np\nimport torch\nfrom torch.utils.data import Dataset\n\nimport lib.augment3D as augment3D\nimport lib.utils as utils\nfrom lib.medloaders import medical_image_process as img_loader\nfrom lib.medloaders.medical_loader_utils import get_viz_set, create_sub_volumes\n\n\nclass MRIDatasetISEG2017(Dataset):\n \"\"\"\n Code for reading the infant brain MRI dataset of ISEG 2017 challenge\n \"\"\"\n\n def __init__(self, args, mode, dataset_path='./datasets', crop_dim=(32, 32, 32), split_id=1, samples=1000,\n load=False):\n \"\"\"\n :param mode: 'train','val','test'\n :param dataset_path: root dataset folder\n :param crop_dim: subvolume tuple\n :param fold_id: 1 to 10 values\n :param samples: number of sub-volumes that you want to create\n \"\"\"\n self.mode = mode\n self.root = str(dataset_path)\n self.training_path = self.root + '/iseg_2017/iSeg-2017-Training/'\n self.testing_path = self.root + '/iseg_2017/iSeg-2017-Testing/'\n self.CLASSES = 4\n self.full_vol_dim = (144, 192, 256) # slice, width, height\n self.threshold = args.threshold\n self.normalization = args.normalization\n self.augmentation = args.augmentation\n self.crop_size = crop_dim\n self.list = []\n self.samples = samples\n self.full_volume = None\n self.save_name = self.root + '/iseg_2017/iSeg-2017-Training/iseg2017-list-' + mode + '-samples-' + str(\n samples) + '.txt'\n if self.augmentation:\n self.transform = augment3D.RandomChoice(\n transforms=[augment3D.GaussianNoise(mean=0, std=0.01), augment3D.RandomFlip(),\n augment3D.ElasticTransform()], p=0.5)\n if load:\n ## load pre-generated data\n self.list = utils.load_list(self.save_name)\n list_IDsT1 = sorted(glob.glob(os.path.join(self.training_path, '*T1.img')))\n self.affine = img_loader.load_affine_matrix(list_IDsT1[0])\n return\n\n subvol = '_vol_' + str(crop_dim[0]) + 'x' + str(crop_dim[1]) + 'x' + str(crop_dim[2])\n self.sub_vol_path = self.root + '/iseg_2017/generated/' + mode + subvol + '/'\n\n utils.make_dirs(self.sub_vol_path)\n list_IDsT1 = sorted(glob.glob(os.path.join(self.training_path, '*T1.img')))\n list_IDsT2 = sorted(glob.glob(os.path.join(self.training_path, '*T2.img')))\n labels = sorted(glob.glob(os.path.join(self.training_path, '*label.img')))\n self.affine = img_loader.load_affine_matrix(list_IDsT1[0])\n\n if self.mode == 'train':\n\n list_IDsT1 = list_IDsT1[:split_id]\n list_IDsT2 = list_IDsT2[:split_id]\n labels = labels[:split_id]\n\n self.list = create_sub_volumes(list_IDsT1, list_IDsT2, labels, dataset_name=\"iseg2017\",\n mode=mode, samples=samples, full_vol_dim=self.full_vol_dim,\n crop_size=self.crop_size,\n sub_vol_path=self.sub_vol_path, th_percent=self.threshold,\n normalization=args.normalization)\n\n\n elif self.mode == 'val':\n utils.make_dirs(self.sub_vol_path)\n list_IDsT1 = list_IDsT1[split_id:]\n list_IDsT2 = list_IDsT2[split_id:]\n labels = labels[split_id:]\n self.list = create_sub_volumes(list_IDsT1, list_IDsT2, labels, dataset_name=\"iseg2017\",\n mode=mode, samples=samples, full_vol_dim=self.full_vol_dim,\n crop_size=self.crop_size,\n sub_vol_path=self.sub_vol_path, th_percent=self.threshold,\n normalization=args.normalization)\n\n self.full_volume = get_viz_set(list_IDsT1, list_IDsT2, labels, dataset_name=\"iseg2017\")\n\n\n elif self.mode == 'test':\n self.list_IDsT1 = sorted(glob.glob(os.path.join(self.testing_path, '*T1.img')))\n self.list_IDsT2 = sorted(glob.glob(os.path.join(self.testing_path, '*T2.img')))\n self.labels = None\n elif self.mode == 'viz':\n list_IDsT1 = list_IDsT1[split_id:]\n list_IDsT2 = list_IDsT2[:split_id:]\n labels = labels[split_id:]\n self.full_volume = get_viz_set(list_IDsT1, list_IDsT2, labels, dataset_name=\"iseg2017\")\n self.list = []\n utils.save_list(self.save_name, self.list)\n\n def __len__(self):\n return len(self.list)\n\n def __getitem__(self, index):\n t1_path, t2_path, seg_path = self.list[index]\n t1, t2, s = np.load(t1_path), np.load(t2_path), np.load(seg_path)\n\n if self.mode == 'train' and self.augmentation:\n print('augmentation reee')\n [augmented_t1, augmented_t2], augmented_s = self.transform([t1, t2], s)\n\n return torch.FloatTensor(augmented_t1.copy()).unsqueeze(0), torch.FloatTensor(\n augmented_t2.copy()).unsqueeze(0), torch.FloatTensor(augmented_s.copy())\n\n return torch.FloatTensor(t1).unsqueeze(0), torch.FloatTensor(t2).unsqueeze(0), torch.FloatTensor(s)\n"
] |
[
[
"numpy.reshape",
"numpy.arange",
"scipy.interpolate.RegularGridInterpolator",
"numpy.random.rand"
],
[
"numpy.load",
"torch.FloatTensor"
]
] |
OrchisLloyd/minihack
|
[
"65fc16f0f321b00552ca37db8e5f850cbd369ae5"
] |
[
"minihack/scripts/cached_env_test.py"
] |
[
"# Copyright (c) Facebook, Inc. and its affiliates.\nimport gym\nimport numpy as np\nimport time\nimport minihack\nimport argparse\nfrom minihack.agent.common.envs.wrapper import CachedEnvWrapper\n\n\ndef compare_speed(env, num_steps, queue_size):\n env_vanila = gym.make(env)\n test_speed(env_vanila, env, num_steps)\n env_vanila.close()\n\n env_queue = []\n for _ in range(queue_size):\n env_queue.append(gym.make(env))\n env_cached = CachedEnvWrapper(env_queue)\n test_speed(env_cached, env, num_steps)\n env_cached.close()\n\n\ndef test_speed(env, env_name, num_steps):\n \"\"\"Tests the speed of an environment for num_steps steps.\"\"\"\n start_time = time.time()\n env.reset()\n for _ in range(num_steps):\n _, _, done, _ = env.step(np.random.randint(8))\n if done:\n env.reset()\n total_time = time.time() - start_time\n\n print(\n \"Took {:.4f}s to perform {} steps on {} envs - {:.2f} FPS\".format(\n total_time, num_steps, env_name, num_steps / total_time\n )\n )\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"-e\",\n \"--env\",\n type=str,\n default=\"MiniHack-MultiRoom-N2-Lava-v0\",\n help=\"Gym environment spec. Defaults to 'MiniHack-MultiRoom-N2-Lava-v0'.\",\n )\n parser.add_argument(\n \"--num_steps\",\n type=int,\n default=10000,\n help=\"Number of steps to run.\",\n )\n parser.add_argument(\n \"--queue_size\",\n type=int,\n default=2,\n help=\"Number of environments in the queue.\",\n )\n flags = parser.parse_args()\n\n compare_speed(**vars(flags))\n\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"numpy.random.randint"
]
] |
kozistr/naver-nlp-challenge-2018
|
[
"e8dbdda2e5a58586678cd1494734b3cadbd570c8"
] |
[
"missions/srl/bert_model.py"
] |
[
"# coding=utf-8\n# Copyright 2018 The Google AI Language Team Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"The main BERT model and related functions.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport copy\nimport json\nimport math\nimport re\nimport six\nimport tensorflow as tf\n\n\nclass BertConfig(object):\n \"\"\"Configuration for `BertModel`.\"\"\"\n\n def __init__(self,\n vocab_size=8000,\n hidden_size=128, # 768\n num_hidden_layers=12, # 12\n num_attention_heads=8, # 12\n intermediate_size=1024, # 3072\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.2,\n attention_probs_dropout_prob=0.2,\n max_position_embeddings=95,\n type_vocab_size=29,\n initializer_range=0.02):\n \"\"\"Constructs BertConfig.\n\n Args:\n vocab_size: Vocabulary size of `inputs_ids` in `BertModel`.\n hidden_size: Size of the encoder layers and the pooler layer.\n num_hidden_layers: Number of hidden layers in the Transformer encoder.\n num_attention_heads: Number of attention heads for each attention layer in\n the Transformer encoder.\n intermediate_size: The size of the \"intermediate\" (i.e., feed-forward)\n layer in the Transformer encoder.\n hidden_act: The non-linear activation function (function or string) in the\n encoder and pooler.\n hidden_dropout_prob: The dropout probability for all fully connected\n layers in the embeddings, encoder, and pooler.\n attention_probs_dropout_prob: The dropout ratio for the attention\n probabilities.\n max_position_embeddings: The maximum sequence length that this model might\n ever be used with. Typically set this to something large just in case\n (e.g., 512 or 1024 or 2048).\n type_vocab_size: The vocabulary size of the `token_type_ids` passed into\n `BertModel`.\n initializer_range: The stdev of the truncated_normal_initializer for\n initializing all weight matrices.\n \"\"\"\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.hidden_act = hidden_act\n self.intermediate_size = intermediate_size\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.initializer_range = initializer_range\n\n @classmethod\n def from_dict(cls, json_object):\n \"\"\"Constructs a `BertConfig` from a Python dictionary of parameters.\"\"\"\n config = BertConfig(vocab_size=None)\n for (key, value) in six.iteritems(json_object):\n config.__dict__[key] = value\n return config\n\n @classmethod\n def from_json_file(cls, json_file):\n \"\"\"Constructs a `BertConfig` from a json file of parameters.\"\"\"\n with tf.gfile.GFile(json_file, \"r\") as reader:\n text = reader.read()\n return cls.from_dict(json.loads(text))\n\n def to_dict(self):\n \"\"\"Serializes this instance to a Python dictionary.\"\"\"\n output = copy.deepcopy(self.__dict__)\n return output\n\n def to_json_string(self):\n \"\"\"Serializes this instance to a JSON string.\"\"\"\n return json.dumps(self.to_dict(), indent=2, sort_keys=True) + \"\\n\"\n\n\nclass BertModel(object):\n \"\"\"BERT model (\"Bidirectional Embedding Representations from a Transformer\").\n\n Example usage:\n\n ```python\n # Already been converted into WordPiece token ids\n input_ids = tf.constant([[31, 51, 99], [15, 5, 0]])\n input_mask = tf.constant([[1, 1, 1], [1, 1, 0]])\n token_type_ids = tf.constant([[0, 0, 1], [0, 2, 0]])\n\n config = modeling.BertConfig(vocab_size=32000, hidden_size=512,\n num_hidden_layers=8, num_attention_heads=6, intermediate_size=1024)\n\n model = modeling.BertModel(config=config, is_training=True,\n input_ids=input_ids, input_mask=input_mask, token_type_ids=token_type_ids)\n\n label_embeddings = tf.get_variable(...)\n pooled_output = model.get_pooled_output()\n logits = tf.matmul(pooled_output, label_embeddings)\n ...\n ```\n \"\"\"\n\n def __init__(self,\n config,\n is_training,\n input_ids,\n input_mask=None,\n token_type_ids=None,\n use_one_hot_embeddings=True,\n skip_embedding=True,\n scope=None):\n \"\"\"Constructor for BertModel.\n\n Args:\n config: `BertConfig` instance.\n is_training: bool. rue for training model, false for eval model. Controls\n whether dropout will be applied.\n input_ids: int32 Tensor of shape [batch_size, seq_length].\n input_mask: (optional) int32 Tensor of shape [batch_size, seq_length].\n token_type_ids: (optional) int32 Tensor of shape [batch_size, seq_length].\n use_one_hot_embeddings: (optional) bool. Whether to use one-hot word\n embeddings or tf.embedding_lookup() for the word embeddings. On the TPU,\n it is must faster if this is True, on the CPU or GPU, it is faster if\n this is False.\n scope: (optional) variable scope. Defaults to \"bert\".\n\n Raises:\n ValueError: The config is invalid or one of the input tensor shapes\n is invalid.\n \"\"\"\n # config = copy.deepcopy(config)\n if not is_training:\n config.hidden_dropout_prob = 0.0\n config.attention_probs_dropout_prob = 0.0\n\n input_shape = get_shape_list(input_ids, expected_rank=3, name=\"input_shape\")\n batch_size = input_shape[0]\n seq_length = input_shape[1]\n\n if input_mask is None:\n input_mask = tf.ones(shape=[batch_size, seq_length], dtype=tf.int32)\n\n if token_type_ids is None:\n token_type_ids = tf.zeros(shape=[batch_size, seq_length], dtype=tf.int32)\n\n with tf.variable_scope(scope, default_name=\"bert\"):\n if not skip_embedding:\n with tf.variable_scope(\"embeddings\"):\n # Perform embedding lookup on the word ids.\n (self.embedding_output, self.embedding_table) = embedding_lookup(\n input_ids=input_ids,\n vocab_size=config.vocab_size,\n embedding_size=config.hidden_size,\n initializer_range=config.initializer_range,\n word_embedding_name=\"word_embeddings\",\n use_one_hot_embeddings=use_one_hot_embeddings)\n\n # Add positional embeddings and token type embeddings, then layer\n # normalize and perform dropout.\n self.embedding_output = embedding_postprocessor(\n input_tensor=self.embedding_output,\n use_token_type=True,\n token_type_ids=token_type_ids,\n token_type_vocab_size=config.type_vocab_size,\n token_type_embedding_name=\"token_type_embeddings\",\n use_position_embeddings=True,\n position_embedding_name=\"position_embeddings\",\n initializer_range=config.initializer_range,\n max_position_embeddings=config.max_position_embeddings,\n dropout_prob=config.hidden_dropout_prob)\n else:\n self.embedding_output = input_ids\n\n with tf.variable_scope(\"encoder\"):\n # This converts a 2D mask of shape [batch_size, seq_length] to a 3D\n # mask of shape [batch_size, seq_length, seq_length] which is used\n # for the attention scores.\n attention_mask = create_attention_mask_from_input_mask(\n input_ids, input_mask)\n\n # Run the stacked transformer.\n # `sequence_output` shape = [batch_size, seq_length, hidden_size].\n self.all_encoder_layers = transformer_model(\n input_tensor=self.embedding_output,\n attention_mask=attention_mask,\n hidden_size=config.hidden_size,\n num_hidden_layers=config.num_hidden_layers,\n num_attention_heads=config.num_attention_heads,\n intermediate_size=config.intermediate_size,\n intermediate_act_fn=get_activation(config.hidden_act),\n hidden_dropout_prob=config.hidden_dropout_prob,\n attention_probs_dropout_prob=config.attention_probs_dropout_prob,\n initializer_range=config.initializer_range,\n do_return_all_layers=True)\n\n self.sequence_output = self.all_encoder_layers[-1]\n # The \"pooler\" converts the encoded sequence tensor of shape\n # [batch_size, seq_length, hidden_size] to a tensor of shape\n # [batch_size, hidden_size]. This is necessary for segment-level\n # (or segment-pair-level) classification tasks where we need a fixed\n # dimensional representation of the segment.\n with tf.variable_scope(\"pooler\"):\n # We \"pool\" the model by simply taking the hidden state corresponding\n # to the first token. We assume that this has been pre-trained\n first_token_tensor = tf.squeeze(self.sequence_output[:, 0:1, :], axis=1)\n self.pooled_output = tf.layers.dense(\n first_token_tensor,\n config.hidden_size,\n activation=tf.tanh,\n kernel_initializer=create_initializer(config.initializer_range))\n\n def get_pooled_output(self):\n return self.pooled_output\n\n def get_sequence_output(self):\n \"\"\"Gets final hidden layer of encoder.\n\n Returns:\n float Tensor of shape [batch_size, seq_length, hidden_size] corresponding\n to the final hidden of the transformer encoder.\n \"\"\"\n return self.sequence_output\n\n def get_all_encoder_layers(self):\n return self.all_encoder_layers\n\n def get_embedding_output(self):\n \"\"\"Gets output of the embedding lookup (i.e., input to the transformer).\n\n Returns:\n float Tensor of shape [batch_size, seq_length, hidden_size] corresponding\n to the output of the embedding layer, after summing the word\n embeddings with the positional embeddings and the token type embeddings,\n then performing layer normalization. This is the input to the transformer.\n \"\"\"\n return self.embedding_output\n\n def get_embedding_table(self):\n return self.embedding_table\n\n\ndef gelu(input_tensor):\n \"\"\"Gaussian Error Linear Unit.\n\n This is a smoother version of the RELU.\n Original paper: https://arxiv.org/abs/1606.08415\n\n Args:\n input_tensor: float Tensor to perform activation.\n\n Returns:\n `input_tensor` with the GELU activation applied.\n \"\"\"\n cdf = 0.5 * (1.0 + tf.erf(input_tensor / tf.sqrt(2.0)))\n return input_tensor * cdf\n\n\ndef get_activation(activation_string):\n \"\"\"Maps a string to a Python function, e.g., \"relu\" => `tf.nn.relu`.\n\n Args:\n activation_string: String name of the activation function.\n\n Returns:\n A Python function corresponding to the activation function. If\n `activation_string` is None, empty, or \"linear\", this will return None.\n If `activation_string` is not a string, it will return `activation_string`.\n\n Raises:\n ValueError: The `activation_string` does not correspond to a known\n activation.\n \"\"\"\n\n # We assume that anything that\"s not a string is already an activation\n # function, so we just return it.\n if not isinstance(activation_string, six.string_types):\n return activation_string\n\n if not activation_string:\n return None\n\n act = activation_string.lower()\n if act == \"linear\":\n return None\n elif act == \"relu\":\n return tf.nn.relu\n elif act == \"gelu\":\n return gelu\n elif act == \"tanh\":\n return tf.tanh\n else:\n raise ValueError(\"Unsupported activation: %s\" % act)\n\n\ndef get_assignment_map_from_checkpoint(tvars, init_checkpoint):\n \"\"\"Compute the union of the current variables and checkpoint variables.\"\"\"\n initialized_variable_names = {}\n\n name_to_variable = collections.OrderedDict()\n for var in tvars:\n name = var.name\n m = re.match(\"^(.*):\\\\d+$\", name)\n if m is not None:\n name = m.group(1)\n name_to_variable[name] = var\n\n init_vars = tf.train.list_variables(init_checkpoint)\n\n assignment_map = collections.OrderedDict()\n for x in init_vars:\n (name, var) = (x[0], x[1])\n if name not in name_to_variable:\n continue\n assignment_map[name] = name\n initialized_variable_names[name] = 1\n initialized_variable_names[name + \":0\"] = 1\n\n return (assignment_map, initialized_variable_names)\n\n\ndef dropout(input_tensor, dropout_prob):\n \"\"\"Perform dropout.\n\n Args:\n input_tensor: float Tensor.\n dropout_prob: Python float. The probability of dropping out a value (NOT of\n *keeping* a dimension as in `tf.nn.dropout`).\n\n Returns:\n A version of `input_tensor` with dropout applied.\n \"\"\"\n if dropout_prob is None or dropout_prob == 0.0:\n return input_tensor\n\n output = tf.nn.dropout(input_tensor, 1.0 - dropout_prob)\n return output\n\n\ndef layer_norm(input_tensor, name=None):\n \"\"\"Run layer normalization on the last dimension of the tensor.\"\"\"\n return tf.contrib.layers.layer_norm(\n inputs=input_tensor, begin_norm_axis=-1, begin_params_axis=-1, scope=name)\n\n\ndef layer_norm_and_dropout(input_tensor, dropout_prob, name=None):\n \"\"\"Runs layer normalization followed by dropout.\"\"\"\n output_tensor = layer_norm(input_tensor, name)\n output_tensor = dropout(output_tensor, dropout_prob)\n return output_tensor\n\n\ndef create_initializer(initializer_range=0.02):\n \"\"\"Creates a `truncated_normal_initializer` with the given range.\"\"\"\n return tf.truncated_normal_initializer(stddev=initializer_range)\n\n\ndef embedding_lookup(input_ids,\n vocab_size,\n embedding_size,\n initializer_range=0.02,\n word_embedding_name=\"word_embeddings\",\n use_one_hot_embeddings=False):\n \"\"\"Looks up words embeddings for id tensor.\n\n Args:\n input_ids: int32 Tensor of shape [batch_size, seq_length] containing word\n ids.\n vocab_size: int. Size of the embedding vocabulary.\n embedding_size: int. Width of the word embeddings.\n initializer_range: float. Embedding initialization range.\n word_embedding_name: string. Name of the embedding table.\n use_one_hot_embeddings: bool. If True, use one-hot method for word\n embeddings. If False, use `tf.nn.embedding_lookup()`. One hot is better\n for TPUs.\n\n Returns:\n float Tensor of shape [batch_size, seq_length, embedding_size].\n \"\"\"\n # This function assumes that the input is of shape [batch_size, seq_length,\n # num_inputs].\n #\n # If the input is a 2D tensor of shape [batch_size, seq_length], we\n # reshape to [batch_size, seq_length, 1].\n if input_ids.shape.ndims == 2:\n input_ids = tf.expand_dims(input_ids, axis=[-1])\n\n embedding_table = tf.get_variable(\n name=word_embedding_name,\n shape=[vocab_size, embedding_size],\n initializer=create_initializer(initializer_range))\n\n if use_one_hot_embeddings:\n flat_input_ids = tf.reshape(input_ids, [-1])\n one_hot_input_ids = tf.one_hot(flat_input_ids, depth=vocab_size)\n output = tf.matmul(one_hot_input_ids, embedding_table)\n else:\n output = tf.nn.embedding_lookup(embedding_table, input_ids)\n\n input_shape = get_shape_list(input_ids)\n\n output = tf.reshape(output,\n input_shape[0:-1] + [input_shape[-1] * embedding_size])\n return (output, embedding_table)\n\n\ndef embedding_postprocessor(input_tensor,\n use_token_type=False,\n token_type_ids=None,\n token_type_vocab_size=16,\n token_type_embedding_name=\"token_type_embeddings\",\n use_position_embeddings=True,\n position_embedding_name=\"position_embeddings\",\n initializer_range=0.02,\n max_position_embeddings=512,\n dropout_prob=0.1):\n \"\"\"Performs various post-processing on a word embedding tensor.\n\n Args:\n input_tensor: float Tensor of shape [batch_size, seq_length,\n embedding_size].\n use_token_type: bool. Whether to add embeddings for `token_type_ids`.\n token_type_ids: (optional) int32 Tensor of shape [batch_size, seq_length].\n Must be specified if `use_token_type` is True.\n token_type_vocab_size: int. The vocabulary size of `token_type_ids`.\n token_type_embedding_name: string. The name of the embedding table variable\n for token type ids.\n use_position_embeddings: bool. Whether to add position embeddings for the\n position of each token in the sequence.\n position_embedding_name: string. The name of the embedding table variable\n for positional embeddings.\n initializer_range: float. Range of the weight initialization.\n max_position_embeddings: int. Maximum sequence length that might ever be\n used with this model. This can be longer than the sequence length of\n input_tensor, but cannot be shorter.\n dropout_prob: float. Dropout probability applied to the final output tensor.\n\n Returns:\n float tensor with same shape as `input_tensor`.\n\n Raises:\n ValueError: One of the tensor shapes or input values is invalid.\n \"\"\"\n input_shape = get_shape_list(input_tensor, expected_rank=3)\n batch_size = input_shape[0]\n seq_length = input_shape[1]\n width = input_shape[2]\n\n output = input_tensor\n\n if use_token_type:\n if token_type_ids is None:\n raise ValueError(\"`token_type_ids` must be specified if\"\n \"`use_token_type` is True.\")\n token_type_table = tf.get_variable(\n name=token_type_embedding_name,\n shape=[token_type_vocab_size, width],\n initializer=create_initializer(initializer_range))\n # This vocab will be small so we always do one-hot here, since it is always\n # faster for a small vocabulary.\n flat_token_type_ids = tf.reshape(token_type_ids, [-1])\n one_hot_ids = tf.one_hot(flat_token_type_ids, depth=token_type_vocab_size)\n token_type_embeddings = tf.matmul(one_hot_ids, token_type_table)\n token_type_embeddings = tf.reshape(token_type_embeddings,\n [batch_size, seq_length, width])\n output += token_type_embeddings\n\n if use_position_embeddings:\n assert_op = tf.assert_less_equal(seq_length, max_position_embeddings)\n with tf.control_dependencies([assert_op]):\n full_position_embeddings = tf.get_variable(\n name=position_embedding_name,\n shape=[max_position_embeddings, width],\n initializer=create_initializer(initializer_range))\n # Since the position embedding table is a learned variable, we create it\n # using a (long) sequence length `max_position_embeddings`. The actual\n # sequence length might be shorter than this, for faster training of\n # tasks that do not have long sequences.\n #\n # So `full_position_embeddings` is effectively an embedding table\n # for position [0, 1, 2, ..., max_position_embeddings-1], and the current\n # sequence has positions [0, 1, 2, ... seq_length-1], so we can just\n # perform a slice.\n position_embeddings = tf.slice(full_position_embeddings, [0, 0],\n [seq_length, -1])\n num_dims = len(output.shape.as_list())\n\n # Only the last two dimensions are relevant (`seq_length` and `width`), so\n # we broadcast among the first dimensions, which is typically just\n # the batch size.\n position_broadcast_shape = []\n for _ in range(num_dims - 2):\n position_broadcast_shape.append(1)\n position_broadcast_shape.extend([seq_length, width])\n position_embeddings = tf.reshape(position_embeddings,\n position_broadcast_shape)\n output += position_embeddings\n\n output = layer_norm_and_dropout(output, dropout_prob)\n return output\n\n\ndef create_attention_mask_from_input_mask(from_tensor, to_mask):\n \"\"\"Create 3D attention mask from a 2D tensor mask.\n\n Args:\n from_tensor: 2D or 3D Tensor of shape [batch_size, from_seq_length, ...].\n to_mask: int32 Tensor of shape [batch_size, to_seq_length].\n\n Returns:\n float Tensor of shape [batch_size, from_seq_length, to_seq_length].\n \"\"\"\n from_shape = get_shape_list(from_tensor, expected_rank=[2, 3])\n batch_size = from_shape[0]\n from_seq_length = from_shape[1]\n\n to_shape = get_shape_list(to_mask, expected_rank=2)\n to_seq_length = to_shape[1]\n\n to_mask = tf.cast(\n tf.reshape(to_mask, [batch_size, 1, to_seq_length]), tf.float32)\n\n # We don't assume that `from_tensor` is a mask (although it could be). We\n # don't actually care if we attend *from* padding tokens (only *to* padding)\n # tokens so we create a tensor of all ones.\n #\n # `broadcast_ones` = [batch_size, from_seq_length, 1]\n broadcast_ones = tf.ones(\n shape=[batch_size, from_seq_length, 1], dtype=tf.float32)\n\n # Here we broadcast along two dimensions to create the mask.\n mask = broadcast_ones * to_mask\n\n return mask\n\n\ndef attention_layer(from_tensor,\n to_tensor,\n attention_mask=None,\n num_attention_heads=1,\n size_per_head=512,\n query_act=None,\n key_act=None,\n value_act=None,\n attention_probs_dropout_prob=0.0,\n initializer_range=0.02,\n do_return_2d_tensor=False,\n batch_size=None,\n from_seq_length=None,\n to_seq_length=None):\n \"\"\"Performs multi-headed attention from `from_tensor` to `to_tensor`.\n\n This is an implementation of multi-headed attention based on \"Attention\n is all you Need\". If `from_tensor` and `to_tensor` are the same, then\n this is self-attention. Each timestep in `from_tensor` attends to the\n corresponding sequence in `to_tensor`, and returns a fixed-with vector.\n\n This function first projects `from_tensor` into a \"query\" tensor and\n `to_tensor` into \"key\" and \"value\" tensors. These are (effectively) a list\n of tensors of length `num_attention_heads`, where each tensor is of shape\n [batch_size, seq_length, size_per_head].\n\n Then, the query and key tensors are dot-producted and scaled. These are\n softmaxed to obtain attention probabilities. The value tensors are then\n interpolated by these probabilities, then concatenated back to a single\n tensor and returned.\n\n In practice, the multi-headed attention are done with transposes and\n reshapes rather than actual separate tensors.\n\n Args:\n from_tensor: float Tensor of shape [batch_size, from_seq_length,\n from_width].\n to_tensor: float Tensor of shape [batch_size, to_seq_length, to_width].\n attention_mask: (optional) int32 Tensor of shape [batch_size,\n from_seq_length, to_seq_length]. The values should be 1 or 0. The\n attention scores will effectively be set to -infinity for any positions in\n the mask that are 0, and will be unchanged for positions that are 1.\n num_attention_heads: int. Number of attention heads.\n size_per_head: int. Size of each attention head.\n query_act: (optional) Activation function for the query transform.\n key_act: (optional) Activation function for the key transform.\n value_act: (optional) Activation function for the value transform.\n attention_probs_dropout_prob: (optional) float. Dropout probability of the\n attention probabilities.\n initializer_range: float. Range of the weight initializer.\n do_return_2d_tensor: bool. If True, the output will be of shape [batch_size\n * from_seq_length, num_attention_heads * size_per_head]. If False, the\n output will be of shape [batch_size, from_seq_length, num_attention_heads\n * size_per_head].\n batch_size: (Optional) int. If the input is 2D, this might be the batch size\n of the 3D version of the `from_tensor` and `to_tensor`.\n from_seq_length: (Optional) If the input is 2D, this might be the seq length\n of the 3D version of the `from_tensor`.\n to_seq_length: (Optional) If the input is 2D, this might be the seq length\n of the 3D version of the `to_tensor`.\n\n Returns:\n float Tensor of shape [batch_size, from_seq_length,\n num_attention_heads * size_per_head]. (If `do_return_2d_tensor` is\n true, this will be of shape [batch_size * from_seq_length,\n num_attention_heads * size_per_head]).\n\n Raises:\n ValueError: Any of the arguments or tensor shapes are invalid.\n \"\"\"\n\n def transpose_for_scores(input_tensor, batch_size, num_attention_heads,\n seq_length, width):\n output_tensor = tf.reshape(\n input_tensor, [batch_size, seq_length, num_attention_heads, width])\n\n output_tensor = tf.transpose(output_tensor, [0, 2, 1, 3])\n return output_tensor\n\n from_shape = get_shape_list(from_tensor, expected_rank=[2, 3])\n to_shape = get_shape_list(to_tensor, expected_rank=[2, 3])\n\n if len(from_shape) != len(to_shape):\n raise ValueError(\n \"The rank of `from_tensor` must match the rank of `to_tensor`.\")\n\n if len(from_shape) == 3:\n batch_size = from_shape[0]\n from_seq_length = from_shape[1]\n to_seq_length = to_shape[1]\n elif len(from_shape) == 2:\n if (batch_size is None or from_seq_length is None or to_seq_length is None):\n raise ValueError(\n \"When passing in rank 2 tensors to attention_layer, the values \"\n \"for `batch_size`, `from_seq_length`, and `to_seq_length` \"\n \"must all be specified.\")\n\n # Scalar dimensions referenced here:\n # B = batch size (number of sequences)\n # F = `from_tensor` sequence length\n # T = `to_tensor` sequence length\n # N = `num_attention_heads`\n # H = `size_per_head`\n\n from_tensor_2d = reshape_to_matrix(from_tensor)\n to_tensor_2d = reshape_to_matrix(to_tensor)\n\n # `query_layer` = [B*F, N*H]\n query_layer = tf.layers.dense(\n from_tensor_2d,\n num_attention_heads * size_per_head,\n activation=query_act,\n name=\"query\",\n kernel_initializer=create_initializer(initializer_range))\n\n # `key_layer` = [B*T, N*H]\n key_layer = tf.layers.dense(\n to_tensor_2d,\n num_attention_heads * size_per_head,\n activation=key_act,\n name=\"key\",\n kernel_initializer=create_initializer(initializer_range))\n\n # `value_layer` = [B*T, N*H]\n value_layer = tf.layers.dense(\n to_tensor_2d,\n num_attention_heads * size_per_head,\n activation=value_act,\n name=\"value\",\n kernel_initializer=create_initializer(initializer_range))\n\n # `query_layer` = [B, N, F, H]\n query_layer = transpose_for_scores(query_layer, batch_size,\n num_attention_heads, from_seq_length,\n size_per_head)\n\n # `key_layer` = [B, N, T, H]\n key_layer = transpose_for_scores(key_layer, batch_size, num_attention_heads,\n to_seq_length, size_per_head)\n\n # Take the dot product between \"query\" and \"key\" to get the raw\n # attention scores.\n # `attention_scores` = [B, N, F, T]\n attention_scores = tf.matmul(query_layer, key_layer, transpose_b=True)\n attention_scores = tf.multiply(attention_scores,\n 1.0 / math.sqrt(float(size_per_head)))\n\n if attention_mask is not None:\n # `attention_mask` = [B, 1, F, T]\n attention_mask = tf.expand_dims(attention_mask, axis=[1])\n\n # Since attention_mask is 1.0 for positions we want to attend and 0.0 for\n # masked positions, this operation will create a tensor which is 0.0 for\n # positions we want to attend and -10000.0 for masked positions.\n adder = (1.0 - tf.cast(attention_mask, tf.float32)) * -10000.0\n\n # Since we are adding it to the raw scores before the softmax, this is\n # effectively the same as removing these entirely.\n attention_scores += adder\n\n # Normalize the attention scores to probabilities.\n # `attention_probs` = [B, N, F, T]\n attention_probs = tf.nn.softmax(attention_scores)\n\n # This is actually dropping out entire tokens to attend to, which might\n # seem a bit unusual, but is taken from the original Transformer paper.\n attention_probs = dropout(attention_probs, attention_probs_dropout_prob)\n\n # `value_layer` = [B, T, N, H]\n value_layer = tf.reshape(\n value_layer,\n [batch_size, to_seq_length, num_attention_heads, size_per_head])\n\n # `value_layer` = [B, N, T, H]\n value_layer = tf.transpose(value_layer, [0, 2, 1, 3])\n\n # `context_layer` = [B, N, F, H]\n context_layer = tf.matmul(attention_probs, value_layer)\n\n # `context_layer` = [B, F, N, H]\n context_layer = tf.transpose(context_layer, [0, 2, 1, 3])\n\n if do_return_2d_tensor:\n # `context_layer` = [B*F, N*V]\n context_layer = tf.reshape(\n context_layer,\n [batch_size * from_seq_length, num_attention_heads * size_per_head])\n else:\n # `context_layer` = [B, F, N*V]\n context_layer = tf.reshape(\n context_layer,\n [batch_size, from_seq_length, num_attention_heads * size_per_head])\n\n return context_layer\n\n\ndef transformer_model(input_tensor,\n attention_mask=None,\n hidden_size=768,\n num_hidden_layers=12,\n num_attention_heads=12,\n intermediate_size=3072,\n intermediate_act_fn=gelu,\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n initializer_range=0.02,\n do_return_all_layers=False):\n \"\"\"Multi-headed, multi-layer Transformer from \"Attention is All You Need\".\n\n This is almost an exact implementation of the original Transformer encoder.\n\n See the original paper:\n https://arxiv.org/abs/1706.03762\n\n Also see:\n https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/models/transformer.py\n\n Args:\n input_tensor: float Tensor of shape [batch_size, seq_length, hidden_size].\n attention_mask: (optional) int32 Tensor of shape [batch_size, seq_length,\n seq_length], with 1 for positions that can be attended to and 0 in\n positions that should not be.\n hidden_size: int. Hidden size of the Transformer.\n num_hidden_layers: int. Number of layers (blocks) in the Transformer.\n num_attention_heads: int. Number of attention heads in the Transformer.\n intermediate_size: int. The size of the \"intermediate\" (a.k.a., feed\n forward) layer.\n intermediate_act_fn: function. The non-linear activation function to apply\n to the output of the intermediate/feed-forward layer.\n hidden_dropout_prob: float. Dropout probability for the hidden layers.\n attention_probs_dropout_prob: float. Dropout probability of the attention\n probabilities.\n initializer_range: float. Range of the initializer (stddev of truncated\n normal).\n do_return_all_layers: Whether to also return all layers or just the final\n layer.\n\n Returns:\n float Tensor of shape [batch_size, seq_length, hidden_size], the final\n hidden layer of the Transformer.\n\n Raises:\n ValueError: A Tensor shape or parameter is invalid.\n \"\"\"\n if hidden_size % num_attention_heads != 0:\n raise ValueError(\n \"The hidden size (%d) is not a multiple of the number of attention \"\n \"heads (%d)\" % (hidden_size, num_attention_heads))\n\n attention_head_size = int(hidden_size / num_attention_heads)\n input_shape = get_shape_list(input_tensor, expected_rank=3)\n batch_size = input_shape[0]\n seq_length = input_shape[1]\n input_width = input_shape[2]\n\n # The Transformer performs sum residuals on all layers so the input needs\n # to be the same as the hidden size.\n if input_width != hidden_size:\n raise ValueError(\"The width of the input tensor (%d) != hidden size (%d)\" %\n (input_width, hidden_size))\n\n # We keep the representation as a 2D tensor to avoid re-shaping it back and\n # forth from a 3D tensor to a 2D tensor. Re-shapes are normally free on\n # the GPU/CPU but may not be free on the TPU, so we want to minimize them to\n # help the optimizer.\n prev_output = reshape_to_matrix(input_tensor)\n\n all_layer_outputs = []\n for layer_idx in range(num_hidden_layers):\n with tf.variable_scope(\"layer_%d\" % layer_idx):\n layer_input = prev_output\n\n with tf.variable_scope(\"attention\"):\n attention_heads = []\n with tf.variable_scope(\"self\"):\n attention_head = attention_layer(\n from_tensor=layer_input,\n to_tensor=layer_input,\n attention_mask=attention_mask,\n num_attention_heads=num_attention_heads,\n size_per_head=attention_head_size,\n attention_probs_dropout_prob=attention_probs_dropout_prob,\n initializer_range=initializer_range,\n do_return_2d_tensor=True,\n batch_size=batch_size,\n from_seq_length=seq_length,\n to_seq_length=seq_length)\n attention_heads.append(attention_head)\n\n attention_output = None\n if len(attention_heads) == 1:\n attention_output = attention_heads[0]\n else:\n # In the case where we have other sequences, we just concatenate\n # them to the self-attention head before the projection.\n attention_output = tf.concat(attention_heads, axis=-1)\n\n # Run a linear projection of `hidden_size` then add a residual\n # with `layer_input`.\n with tf.variable_scope(\"output\"):\n attention_output = tf.layers.dense(\n attention_output,\n hidden_size,\n kernel_initializer=create_initializer(initializer_range))\n attention_output = dropout(attention_output, hidden_dropout_prob)\n attention_output = layer_norm(attention_output + layer_input)\n\n # The activation is only applied to the \"intermediate\" hidden layer.\n with tf.variable_scope(\"intermediate\"):\n intermediate_output = tf.layers.dense(\n attention_output,\n intermediate_size,\n activation=intermediate_act_fn,\n kernel_initializer=create_initializer(initializer_range))\n\n # Down-project back to `hidden_size` then add the residual.\n with tf.variable_scope(\"output\"):\n layer_output = tf.layers.dense(\n intermediate_output,\n hidden_size,\n kernel_initializer=create_initializer(initializer_range))\n layer_output = dropout(layer_output, hidden_dropout_prob)\n layer_output = layer_norm(layer_output + attention_output)\n prev_output = layer_output\n all_layer_outputs.append(layer_output)\n\n if do_return_all_layers:\n final_outputs = []\n for layer_output in all_layer_outputs:\n final_output = reshape_from_matrix(layer_output, input_shape)\n final_outputs.append(final_output)\n return final_outputs\n else:\n final_output = reshape_from_matrix(prev_output, input_shape)\n return final_output\n\n\ndef get_shape_list(tensor, expected_rank=None, name=None):\n \"\"\"Returns a list of the shape of tensor, preferring static dimensions.\n\n Args:\n tensor: A tf.Tensor object to find the shape of.\n expected_rank: (optional) int. The expected rank of `tensor`. If this is\n specified and the `tensor` has a different rank, and exception will be\n thrown.\n name: Optional name of the tensor for the error message.\n\n Returns:\n A list of dimensions of the shape of tensor. All static dimensions will\n be returned as python integers, and dynamic dimensions will be returned\n as tf.Tensor scalars.\n \"\"\"\n if name is None:\n name = tensor.name\n\n if expected_rank is not None:\n assert_rank(tensor, expected_rank, name)\n\n shape = tensor.shape.as_list()\n\n non_static_indexes = []\n for (index, dim) in enumerate(shape):\n if dim is None:\n non_static_indexes.append(index)\n\n if not non_static_indexes:\n return shape\n\n dyn_shape = tf.shape(tensor)\n for index in non_static_indexes:\n shape[index] = dyn_shape[index]\n return shape\n\n\ndef reshape_to_matrix(input_tensor):\n \"\"\"Reshapes a >= rank 2 tensor to a rank 2 tensor (i.e., a matrix).\"\"\"\n ndims = input_tensor.shape.ndims\n if ndims < 2:\n raise ValueError(\"Input tensor must have at least rank 2. Shape = %s\" %\n (input_tensor.shape))\n if ndims == 2:\n return input_tensor\n\n width = input_tensor.shape[-1]\n output_tensor = tf.reshape(input_tensor, [-1, width])\n return output_tensor\n\n\ndef reshape_from_matrix(output_tensor, orig_shape_list):\n \"\"\"Reshapes a rank 2 tensor back to its original rank >= 2 tensor.\"\"\"\n if len(orig_shape_list) == 2:\n return output_tensor\n\n output_shape = get_shape_list(output_tensor)\n\n orig_dims = orig_shape_list[0:-1]\n width = output_shape[-1]\n\n return tf.reshape(output_tensor, orig_dims + [width])\n\n\ndef assert_rank(tensor, expected_rank, name=None):\n \"\"\"Raises an exception if the tensor rank is not of the expected rank.\n\n Args:\n tensor: A tf.Tensor to check the rank of.\n expected_rank: Python integer or list of integers, expected rank.\n name: Optional name of the tensor for the error message.\n\n Raises:\n ValueError: If the expected shape doesn't match the actual shape.\n \"\"\"\n if name is None:\n name = tensor.name\n\n expected_rank_dict = {}\n if isinstance(expected_rank, six.integer_types):\n expected_rank_dict[expected_rank] = True\n else:\n for x in expected_rank:\n expected_rank_dict[x] = True\n\n actual_rank = tensor.shape.ndims\n if actual_rank not in expected_rank_dict:\n scope_name = tf.get_variable_scope().name\n raise ValueError(\n \"For the tensor `%s` in scope `%s`, the actual rank \"\n \"`%d` (shape = %s) is not equal to the expected rank `%s`\" %\n (name, scope_name, actual_rank, str(tensor.shape), str(expected_rank)))\n"
] |
[
[
"tensorflow.concat",
"tensorflow.control_dependencies",
"tensorflow.zeros",
"tensorflow.gfile.GFile",
"tensorflow.cast",
"tensorflow.assert_less_equal",
"tensorflow.truncated_normal_initializer",
"tensorflow.squeeze",
"tensorflow.train.list_variables",
"tensorflow.nn.dropout",
"tensorflow.matmul",
"tensorflow.shape",
"tensorflow.one_hot",
"tensorflow.nn.embedding_lookup",
"tensorflow.nn.softmax",
"tensorflow.transpose",
"tensorflow.slice",
"tensorflow.reshape",
"tensorflow.ones",
"tensorflow.expand_dims",
"tensorflow.contrib.layers.layer_norm",
"tensorflow.variable_scope",
"tensorflow.sqrt",
"tensorflow.get_variable_scope"
]
] |
bkoz/mlops
|
[
"e3cca43ca60fec777708e32131977de4beaf7c3d"
] |
[
"src/models/model.py"
] |
[
"from torch import nn\nimport torch.nn.functional as F\n\nclass MyAwesomeModel(nn.Module):\n def __init__(self):\n super().__init__()\n self.fc1 = nn.Linear(784, 256)\n self.fc2 = nn.Linear(256, 128)\n self.fc3 = nn.Linear(128, 64)\n self.fc4 = nn.Linear(64, 10)\n \n # Dropout module with 0.2 drop probability\n self.dropout = nn.Dropout(p=0.2)\n \n def forward(self, x):\n # make sure input tensor is flattened\n x = x.view(x.shape[0], -1)\n # x = x.flatten()\n # print(f'forward(): x.shape: {x.shape}')\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = F.relu(self.fc3(x))\n x = F.log_softmax(self.fc4(x), dim=1)\n \n return x\n"
] |
[
[
"torch.nn.Linear",
"torch.nn.Dropout"
]
] |
manashmndl/LawNetworkApp
|
[
"4bfc4946d9e2f4e917b37e651e7555addf990d78"
] |
[
"app/backend/search_v2.py"
] |
[
"\"\"\"\r\nInstructions:\r\n\r\n1. Process input query, tokenize it and prepare bigram for it\r\n2. Run the input query through the database and fine the related laws\r\n3. Prepare a dynamic graph using citation details\r\n\r\n\"\"\"\r\nfrom . import Bigram, tfidf_model, tfidf_bigram_model, index_sparse, vocabulary_bigram, vocabulary, LAW_SECTION_ID_LIST\r\nimport numpy as np\r\nfrom app import mongo\r\n\r\n# Process using this sfunction when someone enters query\r\n# Process text v2\r\ndef process_text_v2(input_text, tokenize=False):\r\n valid_list = list(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ কখগঘঙচছজঝঞটঠডঢণতথদধনপফবভমযরলশষসহড়ঢ়য়ৎংঅআইঈউঊঋএঐওঔৌোৈেৃূুীিা\")\r\n filter_text = [l for l in input_text if l in valid_list]\r\n if tokenize == True:\r\n return \"\".join(filter_text).lower().split()\r\n else:\r\n return \"\".join(filter_text).lower()\r\n\r\n return filter_text\r\n\r\n\r\n\r\n\r\n# Search using bigram\r\ndef search_laws(query, max_result=10, use_bigram=False):\r\n\r\n query = process_text_v2(query, tokenize=True)\r\n\r\n if use_bigram == True:\r\n query = Bigram[query]\r\n\r\n query_tfidf = tfidf_bigram_model[vocabulary_bigram.doc2bow(query)]\r\n indices = index_sparse[query_tfidf]\r\n # If no indices nothing found\r\n if (len(indices) == 0):\r\n return -1\r\n # Clipping the result\r\n indices = np.argsort(-indices)[:max_result]\r\n \r\n # Returning the laws only \r\n law_ids = np.unique(np.array(LAW_SECTION_ID_LIST)[indices][:, 0]).tolist()\r\n\r\n\r\n\r\n return law_ids\r\n\r\n else:\r\n query_tfidf = tfidf_model[vocabulary.doc2bow(query)]\r\n \r\n #indices = index_dense[query_tfidf]\r\n indices = index_sparse[query_tfidf]\r\n\r\n if (len(indices) == 0):\r\n return -1\r\n indices = np.argsort(-indices)[:max_result]\r\n\r\n # Returning the laws only \r\n law_ids = np.unique(np.array(LAW_SECTION_ID_LIST)[indices][:, 0]).tolist()\r\n\r\n # Prepare the law related section map\r\n law_related_sections = { str(law_id) : [] for law_id in law_ids }\r\n\r\n # Sorted law section \r\n searched_laws_sections = sorted(np.array(LAW_SECTION_ID_LIST)[indices].tolist(), key= lambda x : x[0])\r\n\r\n\r\n for law in law_ids:\r\n for section in searched_laws_sections:\r\n if law == section[0]:\r\n law_related_sections[str(law)].append(section[1])\r\n\r\n # Remove and insert\r\n mongo.db.temp_search.remove()\r\n mongo.db.temp_search.insert_one({ 'search_result' : \r\n {\r\n 'unique_law_ids' : law_ids,\r\n 'search_indices' : indices.tolist(), \r\n 'law_section_id' : np.array(LAW_SECTION_ID_LIST)[indices].tolist(),\r\n 'law_related_section_map' : law_related_sections\r\n }\r\n })\r\n\r\n return law_ids\r\n\r\n\r\n"
] |
[
[
"numpy.argsort",
"numpy.array"
]
] |
SaynaEbrahimi/BayesianContinualLearning
|
[
"850299cefa2b42cc16fef392bfe3407d31e0f86f"
] |
[
"src/utils.py"
] |
[
"import os\nimport numpy as np\nimport gzip\nimport pickle\nfrom copy import deepcopy\n\n########################################################################################################################\ndef print_arguments(args):\n print('=' * 100)\n print('Arguments =')\n for arg in vars(args):\n print('\\t' + arg + ':', getattr(args, arg))\n print('=' * 100)\n\n\ndef print_model_report(model):\n print('-'*100)\n print(model)\n print('Dimensions =',end=' ')\n count=0\n for p in model.parameters():\n print(p.size(),end=' ')\n count+=np.prod(p.size())\n\n print()\n print('Num parameters = %s'%(human_format(count)), human_format(sum(p.numel() for p in model.parameters())))\n print('-'*100)\n return count\n\ndef human_format(num):\n magnitude=0\n while abs(num)>=1000:\n magnitude+=1\n num/=1000.0\n return '%.1f%s'%(num,['','K','M','G','T','P'][magnitude])\n\n########################################################################################################################\n\ndef is_number(s):\n try:\n float(s)\n return True\n except ValueError:\n pass\n try:\n import unicodedata\n unicodedata.numeric(s)\n return True\n except (TypeError, ValueError):\n pass\n\n return False\n########################################################################################################################\n\n\ndef save_log(taskcla, acc, lss, data, output_path):\n logs = {}\n # save task names\n logs['task_name'] = {}\n logs['test_acc'] = {}\n logs['test_loss'] = {}\n for t, ncla in taskcla:\n logs['task_name'][t] = deepcopy(data[t]['name'])\n logs['test_acc'][t] = deepcopy(acc[t, :])\n logs['test_loss'][t] = deepcopy(lss[t, :])\n # pickle\n with gzip.open(os.path.join(output_path, 'logs.p'), 'wb') as output:\n pickle.dump(logs, output, pickle.HIGHEST_PROTOCOL)\n\n print (\"Log file saved in \", os.path.join(output_path, 'logs.p'))\n\ndef make_directories(args):\n if args.output=='':\n args.output = '{}_{}'.format(args.experiment,args.approach)\n print (args.output)\n checkpoint = os.path.join(args.checkpoint_dir, args.output)\n if not os.path.exists(args.checkpoint_dir):\n os.mkdir(args.checkpoint_dir)\n if not os.path.exists(checkpoint):os.mkdir(checkpoint)\n print(\"Results will be saved in \", checkpoint)\n\n return checkpoint\n\n\ndef print_log_acc_bwt(args, acc, lss):\n\n print('*'*100)\n print('Accuracies =')\n for i in range(acc.shape[0]):\n print('\\t',end=',')\n for j in range(acc.shape[1]):\n print('{:5.4f}% '.format(acc[i,j]),end=',')\n print()\n\n avg_acc = np.mean(acc[acc.shape[0]-1,:])\n print ('ACC: {:5.4f}%'.format(avg_acc))\n print()\n print()\n\n ucb_bwt = (acc[-1] - np.diag(acc)).mean()\n print ('BWT : {:5.2f}%'.format(ucb_bwt))\n\n print('*'*100)\n print('Done!')\n\n logs = {}\n # save results\n logs['name'] = args.experiment\n logs['taskcla'] = args.taskcla\n logs['acc'] = acc\n logs['loss'] = lss\n logs['bwt'] = ucb_bwt\n logs['rii'] = np.diag(acc)\n logs['rij'] = acc[-1]\n\n # pickle\n path = os.path.join(args.checkpoint, '{}_{}_seed_{}.p'.format(args.experiment,args.approach, args.seed))\n with open(path, 'wb') as output:\n pickle.dump(logs, output)\n\n print (\"Log file saved in \", path)\n return avg_acc, ucb_bwt\n\n"
] |
[
[
"numpy.diag",
"numpy.mean"
]
] |
Deepika1108/Facial-Expression-Recognition
|
[
"7e37c0a5e69d1e8d5af429af4a43c70371c9cecf"
] |
[
"base_model.py"
] |
[
"import torch\r\nimport os\r\nfrom collections import OrderedDict\r\nimport random\r\n\r\n\r\nclass BaseModel:\r\n \"\"\"docstring for BaseModel\"\"\"\r\n def __init__(self):\r\n super(BaseModel, self).__init__()\r\n\r\n def initialize(self, opt):\r\n self.opt = opt\r\n self.gpu_ids = self.opt.gpu_ids\r\n self.device = torch.device('cuda:%d' % self.gpu_ids[0] if self.gpu_ids else 'cpu')\r\n self.is_train = self.opt.mode == \"train\"\r\n # inherit to define network model \r\n self.models_name = []\r\n \r\n def setup(self):\r\n if self.is_train:\r\n self.set_train()\r\n self.criterionCE = torch.nn.CrossEntropyLoss().to(self.device)\r\n torch.nn.DataParallel(self.criterionCE, self.gpu_ids)\r\n self.criterionMSE = torch.nn.MSELoss().to(self.device)\r\n torch.nn.DataParallel(self.criterionMSE, self.gpu_ids)\r\n # inherit to set up train/val/test status\r\n self.losses_name = []\r\n self.optims = []\r\n self.schedulers = []\r\n else:\r\n self.set_eval()\r\n\r\n def set_eval(self):\r\n print(\"Set model to Test state.\")\r\n for name in self.models_name:\r\n if isinstance(name, str):\r\n net = getattr(self, 'net_' + name)\r\n net.eval()\r\n self.is_train = False\r\n\r\n def set_train(self):\r\n print(\"Set model to Train state.\")\r\n for name in self.models_name:\r\n if isinstance(name, str):\r\n net = getattr(self, 'net_' + name)\r\n net.train()\r\n self.is_train = True\r\n\r\n def set_requires_grad(self, parameters, requires_grad=False):\r\n if not isinstance(parameters, list):\r\n parameters = [parameters]\r\n for param in parameters:\r\n if param is not None:\r\n param.requires_grad = requires_grad\r\n\r\n def get_latest_visuals(self, visuals_name):\r\n visual_ret = OrderedDict()\r\n for name in visuals_name:\r\n if isinstance(name, str) and hasattr(self, name):\r\n visual_ret[name] = getattr(self, name)\r\n return visual_ret\r\n\r\n def get_latest_losses(self, losses_name):\r\n errors_ret = OrderedDict()\r\n for name in losses_name:\r\n if isinstance(name, str):\r\n cur_loss = float(getattr(self, 'loss_' + name))\r\n cur_loss_lambda = 1. if len(losses_name) == 1 else float(getattr(self.opt, 'lambda_' + name))\r\n errors_ret[name] = cur_loss * cur_loss_lambda\r\n return errors_ret\r\n\r\n def feed_batch(self, batch):\r\n pass \r\n\r\n def forward(self):\r\n pass\r\n\r\n def backward(self):\r\n pass\r\n\r\n def optimize_paras(self):\r\n pass\r\n\r\n def update_learning_rate(self):\r\n for scheduler in self.schedulers:\r\n scheduler.step()\r\n lr = self.optims[0].param_groups[0]['lr']\r\n return lr\r\n\r\n def save_ckpt(self, epoch, models_name):\r\n for name in models_name:\r\n if isinstance(name, str):\r\n save_filename = '%s_net_%s.pth' % (epoch, name)\r\n save_path = os.path.join(self.opt.ckpt_dir, save_filename)\r\n net = getattr(self, 'net_' + name)\r\n # save cpu params, so that it can be used in other GPU settings\r\n if len(self.gpu_ids) > 0 and torch.cuda.is_available():\r\n torch.save(net.module.cpu().state_dict(), save_path)\r\n net.to(self.gpu_ids[0])\r\n net = torch.nn.DataParallel(net, self.gpu_ids)\r\n else:\r\n torch.save(net.cpu().state_dict(), save_path)\r\n\r\n def load_ckpt(self, epoch, models_name):\r\n # print(models_name)\r\n for name in models_name:\r\n if isinstance(name, str):\r\n load_filename = '%s_net_%s.pth' % (epoch, name)\r\n load_path = os.path.join(self.opt.load_model_dir, load_filename)\r\n assert os.path.isfile(load_path), \"File '%s' does not exist.\" % load_path\r\n \r\n pretrained_state_dict = torch.load(load_path, map_location=str(self.device))\r\n if hasattr(pretrained_state_dict, '_metadata'):\r\n del pretrained_state_dict._metadata\r\n\r\n net = getattr(self, 'net_' + name)\r\n if isinstance(net, torch.nn.DataParallel):\r\n net = net.module\r\n # load only existing keys\r\n pretrained_dict = {k: v for k, v in pretrained_state_dict.items() if k in net.state_dict()}\r\n net.load_state_dict(pretrained_dict)\r\n print(\"[Info] Successfully load trained weights for net_%s.\" % name)\r\n\r\n def clean_ckpt(self, epoch, models_name):\r\n for name in models_name:\r\n if isinstance(name, str):\r\n load_filename = '%s_net_%s.pth' % (epoch, name)\r\n load_path = os.path.join(self.opt.ckpt_dir, load_filename)\r\n if os.path.isfile(load_path):\r\n os.remove(load_path)\r\n\r\n\r\n\r\n\r\n"
] |
[
[
"torch.nn.CrossEntropyLoss",
"torch.cuda.is_available",
"torch.device",
"torch.nn.DataParallel",
"torch.nn.MSELoss"
]
] |
Griizz/ComputerVisionPraktikum
|
[
"30276eb0b039ea42728d7433c573414d2dfe1ec2",
"30276eb0b039ea42728d7433c573414d2dfe1ec2"
] |
[
"Projekt/BerechneDeskriptoren.py",
"Termin 5/Aufgabe 2.py"
] |
[
"\"\"\"\nDer klassische Ansatz bei unserem Fruits Dataset.\n\nLabels:\n0 - Apple Green\n1 - Apple Red\n2 - Banana\n3 - Carambola\n4 - Guava\n5 - Kiwi\n6 - Mango\n7 - Muskmelon\n8 - Orange\n9 - Peach\n10 - Pear\n11 - Persimmon\n12 - Pitaya\n13 - Plum\n14 - Pomegranate\n15 - Tomato\n\"\"\"\n\nimport glob\nimport numpy as np\nfrom skimage.io import imread\nfrom os import walk\nfrom skimage.color import rgb2hsv\nfrom skimage.filters import threshold_otsu\nfrom skimage.feature import hog\nANZAHLPIXEL = 320 * 258\n\n\"\"\"\nGibt bei einer Liste von Bildern entsprechende Masken aus, die nach dem Otsu-Verfahren auf den Saturation-Dimensionen (HSV) maskiert.\n\"\"\"\ndef createSMasks(imgs):\n i=0\n masks = []\n for img in imgs:\n imgS = rgb2hsv(img)[:, :, 1]\n masks.append(imgS > threshold_otsu(imgS))\n print(i)\n i +=1\n return masks\n\ndef berechneMaskiertenMittelwert(img, mask):\n summe = [0,0,0]\n anzahlRelevanterPixel = 0\n for x in range(img.shape[0]):\n for y in range(img.shape[1]):\n #if(not(img[x,y,0] == 0 and img[x,y,1] == 0 and img[x,y,2] == 0)):\n if(mask[x,y] != 0):\n anzahlRelevanterPixel +=1\n summe += img[x,y]\n return summe / anzahlRelevanterPixel\n\ndef berechneMaskierteMittelwerte(imgs, masks):\n mittelwerte = []\n for i in range(len(imgs)):\n mittelwerte.append(berechneMaskiertenMittelwert(imgs[i], masks[i]))\n return mittelwerte\n\"\"\"\nerwartet vektor als eingabe\n\"\"\"\ndef erstelle_1d_histos_gewichtet(imgs,b):\n i = 0\n _hist_vektor = []\n for img in imgs:\n histR = np.histogram(img[:,0], bins=b, range=(0, 256))[0]\n histG = np.histogram(img[:,1], bins=b, range=(0, 256))[0]\n histB = np.histogram(img[:,2], bins=b, range=(0, 256))[0]\n histR = histR * (ANZAHLPIXEL/len(img))\n histG = histG * (ANZAHLPIXEL/len(img))\n histB = histB * (ANZAHLPIXEL/len(img))\n _hist_vektor.append(np.hstack((histR, histG, histB)))\n print(i)\n i += 1\n return np.asarray(_hist_vektor)\n\n\ndef erstelle_1d_histo(imgs):\n _hist_vektor = []\n for img in imgs:\n histR = np.histogram(img[:,0], bins=8, range=(0, 256))[0]\n histG = np.histogram(img[:,1], bins=8, range=(0, 256))[0]\n histB = np.histogram(img[:,2], bins=8, range=(0, 256))[0]\n _hist_vektor.append(np.dstack((histR, histG, histB)))\n return np.asarray(_hist_vektor)\n\n\n\"\"\"\nHier wir die Vektorfkt benutzt um die maskierten Stellen zu entfernen\n\"\"\"\ndef erstelle_3d_histos_gewichtet(imgs,b):\n _hist3d = []\n for img in imgs:\n\n _hist3d.append(np.histogramdd(img, bins = [b,b,b], range=((0,256),(0,256),(0,256)))[0]*ANZAHLPIXEL/len(img))\n\n return np.asarray(_hist3d)\n\n\n\"\"\"\nHier wir die Vektorfkt benutzt um die maskierten Stellen zu entfernen, b ist anzahl bins\n\"\"\"\ndef erstelle_3d_histos_mit_vektor(imgs, b):\n _hist3d = []\n for img in imgs:\n\n _hist3d.append(np.histogramdd(img, bins = [b,b,b], range=((0,256),(0,256),(0,256)))[0])\n\n return np.asarray(_hist3d)\n\n\n\"\"\"\nHier ist bei der range die 0 nicht berücksichtigt weil bei den input Bildern nur die Pixel den Wert 0 haben die durch die Maske entfernt wurden.\n\"\"\"\ndef erstelle_3d_histo(imgs):\n _hist3d = []\n for i in range(len(imgs)):\n\n _hist3d.append(np.histogramdd(imgs[i].reshape((imgs[i].shape[0]*imgs[i].shape[1],3)), bins = [8,8,8], range=((1,256),(1,256),(1,256)))[0])\n\n return np.asarray(_hist3d)\n\n\n\"\"\"\nErstelle aus einem Bild und einer Maske einen Vektor, der ausschließlich die nach der Maske relevanten Pixel des Bildes in einem Vektor speichert.\nAuf diesem Vektor kann danach problemlos np.mean/np.std aufgerufen oder Farbhistogramme berechnet werden\n\"\"\"\ndef erstelleVektorRelevanterPixel(img, mask):\n vektor = []\n for x in range(img.shape[0]):\n for y in range(img.shape[1]):\n if(mask[x,y] != 0):\n vektor.append(img[x,y])\n return np.asarray(vektor)\n\ndef erstelleVektoren(imgs, masks):\n vektoren = []\n for i in range(len(imgs)):\n vektoren.append(erstelleVektorRelevanterPixel(imgs[i],masks[i]))\n print(i)\n return np.asarray(vektoren)\n\n\ndef berechne_hog(imgs,masks):\n _hogs = []\n for i in range(len(imgs)):\n maske = masks[i]\n img_mask = imgs[i]*maske[:,:, None]\n gx = cv.Sobel(img_mask, cv.CV_32F, 1, 0, ksize=1)\n gy = cv.Sobel(img_mask, cv.CV_32F, 0, 1, ksize=1)\n mag, angle = cv.cartToPolar(gx, gy, angleInDegrees=True)\n _hogs.append(angle)\n return _hogs\n\n\n#Die Test Area:\n\n#testBild1 = imread(\"./DataSet/Carambola/Training/Carambola_135.png\")\n#imgS1 = rgb2hsv(testBild1)[:, :, 1]\n#mask1 = (imgS1 > threshold_otsu(imgS1))\n#testBild2 = imread(\"./DataSet/Carambola/Training/Carambola_136.png\")\n#imgS2 = rgb2hsv(testBild2)[:, :, 1]\n#mask2 = (imgS2 > threshold_otsu(imgS2))\n#testBild1HSV = rgb2hsv(testBild1)\n#testBild2HSV = rgb2hsv(testBild2)\n#mittelwerteA = berechneMaskierteMittelwerte([testBild1,testBild2], [mask1,mask2])\n#vektoren = erstelleVektoren([testBild1,testBild2], [mask1,mask2])\n#print(vektoren)\n#print(vektoren.shape)\n#mittelwerteB =[]\n#mittelwerteB.append(np.mean(vektoren[0], axis = 0))\n#mittelwerteB.append(np.mean(vektoren[1], axis = 0))\n#print(mittelwerteA)\n#print(mittelwerteB)\n#histos1d = erstelle_1d_histos_gewichtet(vektoren)\n#print(histos1d)\n#histos3d = erstelle_3d_histos_mit_vektor(vektoren)\n#print(histos3d)\n\n\n#labels = [\"Apple_Green\", \"Apple_Red\", \"Banana\", \"Carambola\", \"Guava\", \"Kiwi\", \"Mango\", \"Muskmelon\", \"Orange\", \"Peach\", \"Pear\", \"Persimmon\", \"Pitaya\", \"Plum\", \"Pomegranate\", \"Tomatoes\"]\n#_, labels, _ = walk(\"./DataSet\").__next__()\n\n#Pfadstrings der Trainingsdaten\n#trStrings = []\n#for label in labels:\n# trStrings += glob.glob(\"./DataSet/\" + label + \"/Training/*.png\")\n\n#Haelfte der Pfadstrings\n#trStrings = []\n#for label in labels:\n# for i in range(400):\n# trStrings.append(\"./DataSet/\" + label + \"/Training/\"+label+\"_\"+str(i)+\".png\")\n\n#Labels der Trainingsdaten\n#trLabels = []\n#for i in range(len(labels)):\n# trLabels += [i] * 800\n\n#Haelfte der Labels\n#trLabels = []\n#for i in range(len(labels)):\n# trLabels += [i] * 400\n\n#Pfadstrings der Testdaten\n#testStrings = []\n#for label in labels:\n# testStrings += glob.glob(\"./DataSet/\" + label + \"/Test/*.png\")\n\n#Labels der Testdaten\n#testLabels = []\n#for i in range(len(labels)):\n# testLabels += [i] * 200\n\n#np.save('trLabels400',trLabels)\n#np.save('testLabels400', testLabels)\n\n#print('Einlesen der Bilder:')\n\n#Einlesen der Bilder\n#i = 0\n#trImgs = []\n#for path in trStrings:\n# trImgs.append(imread(path))\n# print(i)\n# i += 1\n\n#print('Einlesen der TestBilder:')\n#i=0\n#testImgs = []\n#for path in testStrings:\n# testImgs.append(imread(path))\n# print(i)\n# i += 1\n\n#print('Erstelle Masken:')\n#trMasks = createSMasks(trImgs)\n#print('Erstelle TestMasken:')\n#testMasks = createSMasks(testImgs)\n\n\n#HOGs berechnen\n#tr_hogs = berechne_hog(trImgs,trMasks)\n#test_hogs = berechne_hog(testImgs, testMasks)\n\n#np.save('trHOG_400', tr_hogs)\n#np.save('testHOG_400', test_hogs)\n\n\n#Vektoren berechnen:\n\n#print('Erstelle Vektoren:')\n#trVektoren = erstelleVektoren(trImgs, trMasks)\n#print('Erstelle TestVektoren:')\n#testVektoren = erstelleVektoren(testImgs, testMasks)\n\n#np.save('trVektoren', trVektoren)\n#np.save('testVektoren', testVektoren)\n\n\n#Vektoren laden:\ntrVektoren = np.load('trVektoren.npy',allow_pickle= True)\ntestVektoren = np.load('testVektoren.npy', allow_pickle= True)\n\n#Mittelwerte berechnen:\n\n#nicht maskiert:\n#trMittelwerte = []\n#for i in range(len(trImgs)):\n# trMittelwerte.append(np.mean(trImgs[i], axis = (0,1)))\n#testMittelwerte = []\n#for i in range(len(testImgs)):\n# testMittelwerte.append(np.mean(testImgs[i], axis = (0,1)))\n\n#np.save('trMittelwerteDumm', trMittelwerte)\n#np.save('testMittelwerteDumm',testMittelwerte)\n\n#mit berechneMittelwert:\n#trMittelwerte = berechneMaskierteMittelwerte(trImgs, trMasks)\n#testMittelwerte = berechneMaskierteMittelwerte(testImgs, testMasks)\n\n#mittels Vektoren und np.mean\n#trMittelwerte = []\n#for i in range(len(trImgs)):\n# trMittelwerte.append(np.mean(trVektoren[i], axis=0))\n#testMittelwerte = []\n#for i in range(len(testImgs)):\n# testMittelwerte.append(np.mean(testVektoren[i], axis=0))\n\n#np.save('trMittelwerte',trMittelwerte)\n#np.save('testMittelwerte', testMittelwerte)\n\n#np.save('trMittelwerte400',trMittelwerte)\n#np.save('testMittelwerte400', testMittelwerte)\n\n#Standardabweichungen berechnen:\n\n#trStd = []\n#for i in range(len(trImgs)):\n# trStd.append(np.std(trVektoren[i], axis=0))\n# print(i)\n\n#testStd = []\n#for i in range(len(testImgs)):\n# testStd.append(np.std(testVektoren[i], axis=0))\n# print(i)\n\n#np.save('trStd', trStd)\n#np.save('testStd', testStd)\n\n\n#1D Histos gewichtet berechnen:\n#print(\"Erstelle 1D Histos Training:\")\n#tr1DHistosGewichtet = erstelle_1d_histos_gewichtet(trVektoren,32)\n#print(\"Erstelle 1D Histos Test:\")\n#test1DHistosGewichtet = erstelle_1d_histos_gewichtet(testVektoren,32)\n\n#np.save('tr1DHistosGewichtet32bins', tr1DHistosGewichtet)\n#np.save('test1DHistosGewichtet32bins', test1DHistosGewichtet)\n\n\n#3D Histos:\n#print(\"Erstelle 3D Histos Training:\")\n#tr3DHistos = erstelle_3d_histos_mit_vektor(trVektoren,4)\n#print(\"Erstelle 3D Histos Test:\")\n#test3DHistos = erstelle_3d_histos_mit_vektor(testVektoren,4)\n\n#np.save('tr3DHistos4bins', tr3DHistos)\n#np.save('test3DHistos4bins', test3DHistos)\n\n#3D Histos gewichtet:\nprint(\"Erstelle 3D Histos Training:\")\ntr3DHistosGewichtet = erstelle_3d_histos_gewichtet(trVektoren,32)\nprint(\"Erstelle 3D Histos Test:\")\ntest3DHistosGewichtet = erstelle_3d_histos_gewichtet(testVektoren,32)\n\nnp.save('tr3DHistosGewichtet32bins', tr3DHistosGewichtet)\nnp.save('test3DHistosGewichtet32bins', test3DHistosGewichtet)\n\n#np.save('trLabels',trLabels)\n#np.save('testLabels', testLabels)\n\n",
"\"\"\"\nAufgabe 5.2\n\"\"\"\n\nimport numpy as np\nfrom skimage.io import imread, imshow\nimport matplotlib.pyplot as plt\nfrom skimage.filters import sobel_h, sobel_v, gaussian\n\nimg1 = imread(\"./catG.png\")\nimg_vertical = sobel_v(img1, mask = None)\nimg_horizontal = sobel_h(img1, mask = None)\nimg_Sum = np.sqrt(((img_vertical)**2)+((img_horizontal)**2)) #berechnet man so den Gradienten?\n\nimgN = imread(\"./catGNoisy.png\")\nimgN_vertical = sobel_v(imgN, mask = None)\nimgN_horizontal = sobel_h(imgN, mask = None)\nimgN_Sum = np.sqrt(((imgN_vertical)**2)+((imgN_horizontal)**2))\n\"\"\"\n5.2.2: \nBeim vorher gegaussten Bild sind die Linien viel breiter.Das kann daran liegen, dass starke Unterschiede zwischen \nbenachbarten Pixeln, in einer geringeren intensität, auf eine größere Fläche verteilt werden \n\"\"\"\n\nimg2 = gaussian(imgN,5)\nimg2_vertical = sobel_v(img2, mask = None)\nimg2_horizontal = sobel_h(img2, mask = None)\nimg2_Sum = np.sqrt(((img2_vertical)**2)+((img2_horizontal)**2))\n\n\nfig, ax = plt.subplots(1,3)\n\nax[0].imshow(img_Sum, cmap = 'Greys_r')\nax[0].set_title('CatG')\n\nax[1].imshow(imgN_Sum, cmap = 'Greys_r')\nax[1].set_title('CatG Noisy')\n\nax[2].imshow(img2_Sum, cmap = 'Greys_r')\nax[2].set_title('CatG Noisy gauss')\n"
] |
[
[
"numpy.hstack",
"numpy.asarray",
"numpy.save",
"numpy.dstack",
"numpy.histogramdd",
"numpy.load",
"numpy.histogram"
],
[
"matplotlib.pyplot.subplots",
"numpy.sqrt"
]
] |
ashubertt/statslib
|
[
"5a35c0d10c3ca44c2d48f329c4f3790c91c385ac"
] |
[
"tests/test_transforms.py"
] |
[
"import os\nimport numpy as np\nimport pandas as pd\n\nfrom unittest import TestCase\nfrom statslib._pathmap import TEST_FOLDER\nfrom statslib.utils.dframe import to_pd_todatetime\n\n\nclass TransformationsTest(TestCase):\n def setUp(self) -> None:\n path = os.path.join(TEST_FOLDER, '../statslib/datasets', 'data/y.csv')\n df = pd.read_csv(path)\n df = to_pd_todatetime(df, 'day', day_only=True)\n self.y = df.set_index('day').squeeze().rename('y')\n\n def test_pct_change(self):\n from statslib._lib.transforms import pct_change\n for i in range(1, 10):\n f = pct_change(i)\n pd.testing.assert_series_equal(self.y, f.inv(f(self.y)).rename('y'))\n\n def test_log_return(self):\n from statslib._lib.transforms import log_return\n for i in range(1, 10):\n f = log_return(i)\n pd.testing.assert_series_equal(self.y, f.inv(f(self.y)).rename('y'))\n\n def test_difference_operator(self):\n from statslib._lib.transforms import difference_operator\n spec_dict = {(2, None, 0): [[-2, 1], [1, 2]],\n (1, 1, 3): [[-1, -1, 1], [1, 3, 4]],\n (2, 1, 3): [[-2, 1, -1, 2, -1], [1, 2, 3, 4, 5]]}\n\n for spec, inv_spec in spec_dict.items():\n d, D, s = spec\n f = difference_operator(d, D, s, inv_specification=inv_spec)\n pd.testing.assert_series_equal(self.y, f.inv(f(self.y)).rename('y'))\n"
] |
[
[
"pandas.read_csv"
]
] |
Nanda-Kishore-V/AlgosForRobotics
|
[
"2b261a023bf64668f159ad6d0e02f660b83c7d4a"
] |
[
"controllers/LongitudinalPID.py"
] |
[
"#!/usr/bin/env python3\nimport numpy as np\n\nclass LongitudinalPID:\n \"\"\"\n PID controller for longitudinal control\n \"\"\"\n def __init__(self, v=0, L=3, Kp=1, Kd=0.01, Ki=0.01,\n integrator_min=None, integrator_max=None):\n # States\n self.v = v\n self.prev_error = 0\n self.sum_error = 0\n\n # Wheel base\n self.L = L\n\n # Control gain\n self.Kp = Kp\n self.Ki = Ki\n self.Kd = Kd\n\n self.integrator_min = integrator_min\n self.integrator_max = integrator_max\n\n def update_speed(self, v):\n self.v = v\n\n def get_throttle_input(self, v, dt, target_speed):\n self.update_speed(v)\n\n error = target_speed - self.v\n self.sum_error += error * dt\n if self.integrator_min is not None:\n self.sum_error = np.fmax(self.sum_error,\n self.integrator_min)\n if self.integrator_max is not None:\n self.sum_error = np.fmin(self.sum_error,\n self.integrator_max)\n\n throttle = self.Kp * error + \\\n self.Ki * self.sum_error + \\\n self.Kd * (error - self.prev_error) / dt\n self.prev_error = error\n\n return throttle\n"
] |
[
[
"numpy.fmax",
"numpy.fmin"
]
] |
Hoclor/CoSADUV-Contextual-Saliency-for-Detecting-Anomalies-in-UAV-Video
|
[
"674b72af15ba8833317b8daa9d1e614ea63151c1"
] |
[
"model/models/CoSADUV.py"
] |
[
"\"\"\"Model for Contextual Saliency for Anomaly Detection in UAV Video (CoSADUV)\nBased on the Deep Spatial Contextual Long-term Recurrent Convolutional Network model\n\nThis model with ConvLSTM temporal implementation, Sigmoid activation function\n\"\"\"\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torchvision\n\nfrom models.cnn_vgg16.local_cnn import LocalFeatsCNN\nfrom models.places_vgg16.places_cnn import PlacesCNN\nfrom models.segmentation_resnet50.segmentation_nn import SegmentationNN\nfrom models.convLSTM.convLSTMCell import ConvLSTMCell\n\n\nclass CoSADUV(nn.Module):\n def __init__(self, input_dim=(480, 640), local_feats_net=\"Seg\"):\n super(CoSADUV, self).__init__()\n self.temporal = True\n\n self.input_dim = input_dim\n\n # Hidden size of the LSTMs\n # LSTM_1 hidden size: 128\n # LSTM_2 hidden size: 128\n # LSTM_3 hidden size: 128\n # LSTM_4 hidden size: 128\n self.pixel_LSTMs_hsz = (128, 128, 128, 128)\n\n # Input size of the LSTMs\n # LSTM_1 input size: channel of local_feats output (512)\n # LSTM_2 input size: 256 (2 * 128 as LSTMs output 128 values, *2 for bLSTM)\n # LSTM_3 input size: 256 (same reason as above)\n # LSTM_4 input size: 256 (same reason as above)\n self.pixel_LSTMs_isz = (\n 512,\n 2 * self.pixel_LSTMs_hsz[0],\n 2 * self.pixel_LSTMs_hsz[1],\n 2 * self.pixel_LSTMs_hsz[2],\n )\n\n if local_feats_net == \"Seg\":\n self.local_feats = SegmentationNN()\n else:\n self.local_feats = LocalFeatsCNN()\n\n self.scene_context = PlacesCNN(input_dim=input_dim)\n self.scene_context_fc_1 = nn.Linear(128, self.pixel_LSTMs_isz[0])\n self.scene_context_fc_rest = nn.Linear(128, self.pixel_LSTMs_isz[1])\n\n # Constructing LSTMs:\n self.pixel_blstm_h_1 = nn.LSTM(\n input_size=self.pixel_LSTMs_isz[0],\n hidden_size=self.pixel_LSTMs_hsz[0],\n num_layers=1,\n batch_first=True,\n bidirectional=True,\n )\n self.pixel_blstm_v_1 = nn.LSTM(\n input_size=self.pixel_LSTMs_isz[1],\n hidden_size=self.pixel_LSTMs_hsz[1],\n num_layers=1,\n batch_first=True,\n bidirectional=True,\n )\n self.pixel_blstm_h_2 = nn.LSTM(\n input_size=self.pixel_LSTMs_isz[2],\n hidden_size=self.pixel_LSTMs_hsz[2],\n num_layers=1,\n batch_first=True,\n bidirectional=True,\n )\n self.pixel_blstm_v_2 = nn.LSTM(\n input_size=self.pixel_LSTMs_isz[3],\n hidden_size=self.pixel_LSTMs_hsz[3],\n num_layers=1,\n batch_first=True,\n bidirectional=True,\n )\n\n # Initialize the biases of the forget gates to 1 for all blstms\n for blstm in [\n self.pixel_blstm_h_1,\n self.pixel_blstm_v_1,\n self.pixel_blstm_h_2,\n self.pixel_blstm_v_2,\n ]:\n # Below code taken from:\n # https://discuss.pytorch.org/t/set-forget-gate-bias-of-lstm/1745/4\n for names in blstm._all_weights:\n for name in filter(lambda n: \"bias\" in n, names):\n bias = getattr(blstm, name)\n n = bias.size(0)\n start, end = n // 4, n // 2\n bias.data[start:end].fill_(1.0)\n\n # convLSTM applied to the sequence in time domain\n self.convLSTM = ConvLSTMCell(\n input_size=2 * self.pixel_LSTMs_hsz[-1], hidden_size=1, kernel_size=3\n )\n\n # The stored hidden state of the convLSTM\n # None if none is stored, else (hidden, cell)\n self.convLSTM_state = None\n\n # # softmax\n self.score = nn.Sigmoid()\n\n def forward(self, x):\n \"\"\"\n Forward pass of the convolutional neural network. Should not be called\n manually but by calling a model instance directly.\n\n Inputs:\n - x: PyTorch input Variable\n \"\"\"\n\n N = x.size(0)\n H, W = self.input_dim\n\n # Get local feature map\n local_feats = self.local_feats(x) # Shape (N, C, H, W)\n H_lf, W_lf = local_feats.size()[2:]\n\n # Get scene feature information\n raw_scene_context = self.scene_context(x)\n # Create context input into BLSTM_1\n scene_context_first = self.scene_context_fc_1(raw_scene_context)\n # Create context input into BLSTM_[2,3,4]\n scene_context_rest = self.scene_context_fc_rest(raw_scene_context)\n\n # Horizontal BLSTM_1\n # local_feats_h shape: (N, H, W, C)\n local_feats_h = local_feats.permute(0, 2, 3, 1).contiguous()\n # Context shape: (N, C)\n scene_context_h = scene_context_first.contiguous().view(\n N, self.pixel_LSTMs_isz[0]\n )\n # Loop over local_feats one row at a time:\n # split(1,1) splits it into individual rows,\n # squeeze removes the row dimension\n rows = []\n for row in local_feats_h.split(1, 1): # row shape (N, 1, W, C)\n row = row.squeeze(1) # row shape (N, W, C)\n # Add context to the first and last pixel of the row\n row[:, 0, :] += scene_context_h\n row[:, -1, :] += scene_context_h\n result, _ = self.pixel_blstm_h_1(row)\n rows.append(result)\n # Reconstruct the image by stacking the rows\n output_h = torch.stack(rows, dim=1) # Shape (N, H, W, C)\n del rows, row, result\n\n # Vertical BLSTM_1\n # Context shape: (N, C)\n scene_context_v = scene_context_rest.contiguous().view(\n N, self.pixel_LSTMs_isz[1]\n )\n # Loop over local_feats one column at a time:\n # split(1,2) splits it into individual columns,\n # squeeze removes the column dimension\n cols = []\n for col in output_h.split(1, 2): # col shape (N, H, 1, C)\n col = col.squeeze(2) # col shape (N, H, C)\n # Add context to the first and last pixel of the col\n col[:, 0, :] += scene_context_v\n col[:, -1, :] += scene_context_v\n result, _ = self.pixel_blstm_v_1(col)\n cols.append(result)\n # Reconstruct the image by stacking the columns\n output_hv = torch.stack(cols, dim=2) # Shape (N, H, W, C)\n del cols, col, result\n\n # Horizontal BLSTM_2\n # Context shape: (N, C)\n scene_context_h_2 = scene_context_rest.contiguous().view(\n N, self.pixel_LSTMs_isz[2]\n )\n # Loop over local_feats one row at a time:\n # split(1,1) splits it into individual rows,\n # squeeze removes the row dimension\n rows = []\n for row in output_hv.split(1, 1): # row shape (N, 1, W, C)\n row = row.squeeze(1) # row shape (N, W, C)\n # Add context to the first and last pixel of the row\n row[:, 0, :] += scene_context_h_2\n row[:, -1, :] += scene_context_h_2\n result, _ = self.pixel_blstm_h_2(row)\n rows.append(result)\n # Reconstruct the image by stacking the rows\n output_hvh = torch.stack(rows, dim=1) # Shape (N, H, W, C)\n del rows, row, result\n\n # Vertical BLSTM_2\n # Context shape: (N, C)\n scene_context_v = scene_context_rest.contiguous().view(\n N, self.pixel_LSTMs_isz[3]\n )\n # Loop over local_feats one column at a time:\n # split(1,2) splits it into individual columns,\n # squeeze removes the column dimension\n cols = []\n for col in output_hvh.split(1, 2): # col shape (N, H, 1, C)\n col = col.squeeze(2) # col shape (N, H, C)\n # Add context to the first and last pixel of the col\n col[:, 0, :] += scene_context_v\n col[:, -1, :] += scene_context_v\n result, _ = self.pixel_blstm_v_2(col)\n cols.append(result)\n # Reconstruct the image by stacking the columns\n output_hvhv = torch.stack(cols, dim=2) # Shape (N, H, W, C)\n output_hvhv = output_hvhv.permute(0, 3, 1, 2) # Shape (N, C, H, W)\n del cols, col, result\n\n # Reduce channel dimension to 1 with convLSTM\n\n # This is essentially an LSTM with convolution kernels instead of scalar gates\n # All inputs, cell state, hidden state, gates, are 3D tensors with last 2\n # dimensions being spatial (height, width)\n self.convLSTM_state = self.convLSTM(output_hvhv, self.convLSTM_state) # 2-tuple\n\n # Extract the hidden state from the convLSTM_state as the saliency prediction\n output_conv = self.convLSTM_state[0].clone() # Shape (N, 1, H, W)\n\n N, _, H, W, = output_conv.size()\n\n # LSTM uses tanh activation function, which has range (-1, 1). Rescale this into\n # range (0, 1) to get prediction for saliency as a probability\n # (tanh is a rescaled sigmoid, so this is essentially same as applying sigmoid)\n output_score = (output_conv + 1) / 2\n\n # Upsampling - nn.functional.interpolate does not exist in < 0.4.1,\n # but upsample is deprecated in > 0.4.0\n if torch.__version__ == \"0.4.0\":\n output_upsampled = nn.functional.upsample(\n output_score, size=self.input_dim, mode=\"bilinear\", align_corners=True\n )\n else:\n # align_corners=False assumed, default behaviour was changed\n # from True to False from pytorch 0.3.1 to 0.4\n output_upsampled = nn.functional.interpolate(\n output_score, size=self.input_dim, mode=\"bilinear\", align_corners=True\n )\n \n # If model is set to eval, detach the temporal state after each application\n if not self.training:\n self.detach_temporal_state()\n\n return output_upsampled\n\n def clear_temporal_state(self):\n self.convLSTM_state = None\n\n def detach_temporal_state(self):\n \"\"\"Detaches hidden and cell state from their history.\"\"\"\n if type(self.convLSTM_state) == type(None):\n pass\n else:\n self.convLSTM_state[0].detach_()\n self.convLSTM_state[1].detach_()\n self.convLSTM_state = (\n self.convLSTM_state[0].detach(),\n self.convLSTM_state[1].detach(),\n )\n\n @property\n def is_cuda(self):\n \"\"\"\n Check if model parameters are allocated on the GPU.\n \"\"\"\n return next(self.parameters()).is_cuda\n\n def save(self, path):\n \"\"\"\n Save model with its parameters to the given path. Conventionally the\n path should end with \"*.model\".\n\n Inputs:\n - path: path string\n \"\"\"\n print(\"Saving model... %s\" % path)\n torch.save(self, path)\n"
] |
[
[
"torch.nn.functional.upsample",
"torch.nn.LSTM",
"torch.nn.Sigmoid",
"torch.nn.Linear",
"torch.nn.functional.interpolate",
"torch.stack",
"torch.save"
]
] |
chunibyo-wly/SmartCities
|
[
"0d6a5455a1fd2b5ef2b885ed830489e53c52e2c7"
] |
[
"model/yolov4/core/backbone.py"
] |
[
"import tensorflow as tf\nfrom . import common\n\n\ndef darknet53(input_data):\n\n input_data = common.convolutional(input_data, (3, 3, 3, 32))\n input_data = common.convolutional(\n input_data, (3, 3, 32, 64), downsample=True\n )\n\n for i in range(1):\n input_data = common.residual_block(input_data, 64, 32, 64)\n\n input_data = common.convolutional(\n input_data, (3, 3, 64, 128), downsample=True\n )\n\n for i in range(2):\n input_data = common.residual_block(input_data, 128, 64, 128)\n\n input_data = common.convolutional(\n input_data, (3, 3, 128, 256), downsample=True\n )\n\n for i in range(8):\n input_data = common.residual_block(input_data, 256, 128, 256)\n\n route_1 = input_data\n input_data = common.convolutional(\n input_data, (3, 3, 256, 512), downsample=True\n )\n\n for i in range(8):\n input_data = common.residual_block(input_data, 512, 256, 512)\n\n route_2 = input_data\n input_data = common.convolutional(\n input_data, (3, 3, 512, 1024), downsample=True\n )\n\n for i in range(4):\n input_data = common.residual_block(input_data, 1024, 512, 1024)\n\n return route_1, route_2, input_data\n\n\ndef cspdarknet53(input_data):\n\n input_data = common.convolutional(\n input_data, (3, 3, 3, 32), activate_type=\"mish\"\n )\n input_data = common.convolutional(\n input_data, (3, 3, 32, 64), downsample=True, activate_type=\"mish\"\n )\n\n route = input_data\n route = common.convolutional(route, (1, 1, 64, 64), activate_type=\"mish\")\n input_data = common.convolutional(\n input_data, (1, 1, 64, 64), activate_type=\"mish\"\n )\n for i in range(1):\n input_data = common.residual_block(\n input_data, 64, 32, 64, activate_type=\"mish\"\n )\n input_data = common.convolutional(\n input_data, (1, 1, 64, 64), activate_type=\"mish\"\n )\n\n input_data = tf.concat([input_data, route], axis=-1)\n input_data = common.convolutional(\n input_data, (1, 1, 128, 64), activate_type=\"mish\"\n )\n input_data = common.convolutional(\n input_data, (3, 3, 64, 128), downsample=True, activate_type=\"mish\"\n )\n route = input_data\n route = common.convolutional(route, (1, 1, 128, 64), activate_type=\"mish\")\n input_data = common.convolutional(\n input_data, (1, 1, 128, 64), activate_type=\"mish\"\n )\n for i in range(2):\n input_data = common.residual_block(\n input_data, 64, 64, 64, activate_type=\"mish\"\n )\n input_data = common.convolutional(\n input_data, (1, 1, 64, 64), activate_type=\"mish\"\n )\n input_data = tf.concat([input_data, route], axis=-1)\n\n input_data = common.convolutional(\n input_data, (1, 1, 128, 128), activate_type=\"mish\"\n )\n input_data = common.convolutional(\n input_data, (3, 3, 128, 256), downsample=True, activate_type=\"mish\"\n )\n route = input_data\n route = common.convolutional(route, (1, 1, 256, 128), activate_type=\"mish\")\n input_data = common.convolutional(\n input_data, (1, 1, 256, 128), activate_type=\"mish\"\n )\n for i in range(8):\n input_data = common.residual_block(\n input_data, 128, 128, 128, activate_type=\"mish\"\n )\n input_data = common.convolutional(\n input_data, (1, 1, 128, 128), activate_type=\"mish\"\n )\n input_data = tf.concat([input_data, route], axis=-1)\n\n input_data = common.convolutional(\n input_data, (1, 1, 256, 256), activate_type=\"mish\"\n )\n route_1 = input_data\n input_data = common.convolutional(\n input_data, (3, 3, 256, 512), downsample=True, activate_type=\"mish\"\n )\n route = input_data\n route = common.convolutional(route, (1, 1, 512, 256), activate_type=\"mish\")\n input_data = common.convolutional(\n input_data, (1, 1, 512, 256), activate_type=\"mish\"\n )\n for i in range(8):\n input_data = common.residual_block(\n input_data, 256, 256, 256, activate_type=\"mish\"\n )\n input_data = common.convolutional(\n input_data, (1, 1, 256, 256), activate_type=\"mish\"\n )\n input_data = tf.concat([input_data, route], axis=-1)\n\n input_data = common.convolutional(\n input_data, (1, 1, 512, 512), activate_type=\"mish\"\n )\n route_2 = input_data\n input_data = common.convolutional(\n input_data, (3, 3, 512, 1024), downsample=True, activate_type=\"mish\"\n )\n route = input_data\n route = common.convolutional(route, (1, 1, 1024, 512), activate_type=\"mish\")\n input_data = common.convolutional(\n input_data, (1, 1, 1024, 512), activate_type=\"mish\"\n )\n for i in range(4):\n input_data = common.residual_block(\n input_data, 512, 512, 512, activate_type=\"mish\"\n )\n input_data = common.convolutional(\n input_data, (1, 1, 512, 512), activate_type=\"mish\"\n )\n input_data = tf.concat([input_data, route], axis=-1)\n\n input_data = common.convolutional(\n input_data, (1, 1, 1024, 1024), activate_type=\"mish\"\n )\n input_data = common.convolutional(input_data, (1, 1, 1024, 512))\n input_data = common.convolutional(input_data, (3, 3, 512, 1024))\n input_data = common.convolutional(input_data, (1, 1, 1024, 512))\n\n input_data = tf.concat(\n [\n tf.nn.max_pool(input_data, ksize=13, padding=\"SAME\", strides=1),\n tf.nn.max_pool(input_data, ksize=9, padding=\"SAME\", strides=1),\n tf.nn.max_pool(input_data, ksize=5, padding=\"SAME\", strides=1),\n input_data,\n ],\n axis=-1,\n )\n input_data = common.convolutional(input_data, (1, 1, 2048, 512))\n input_data = common.convolutional(input_data, (3, 3, 512, 1024))\n input_data = common.convolutional(input_data, (1, 1, 1024, 512))\n\n return route_1, route_2, input_data\n\n\ndef darknet53_tiny(input_data):\n input_data = common.convolutional(input_data, (3, 3, 3, 16))\n input_data = tf.keras.layers.MaxPool2D(2, 2, \"same\")(input_data)\n input_data = common.convolutional(input_data, (3, 3, 16, 32))\n input_data = tf.keras.layers.MaxPool2D(2, 2, \"same\")(input_data)\n input_data = common.convolutional(input_data, (3, 3, 32, 64))\n input_data = tf.keras.layers.MaxPool2D(2, 2, \"same\")(input_data)\n input_data = common.convolutional(input_data, (3, 3, 64, 128))\n input_data = tf.keras.layers.MaxPool2D(2, 2, \"same\")(input_data)\n input_data = common.convolutional(input_data, (3, 3, 128, 256))\n route_1 = input_data\n input_data = tf.keras.layers.MaxPool2D(2, 2, \"same\")(input_data)\n input_data = common.convolutional(input_data, (3, 3, 256, 512))\n input_data = tf.keras.layers.MaxPool2D(2, 1, \"same\")(input_data)\n input_data = common.convolutional(input_data, (3, 3, 512, 1024))\n\n return route_1, input_data\n"
] |
[
[
"tensorflow.nn.max_pool",
"tensorflow.concat",
"tensorflow.keras.layers.MaxPool2D"
]
] |
junprog/cc-base
|
[
"c2670e6250f83be4ec708a80dc4f1fdbce5ce289"
] |
[
"models/fusion_model.py"
] |
[
"import torch.nn as nn\nimport torch\nimport torch.nn.functional as F\n\nimport sys\nimport os\ncurrent_path = os.getcwd()\nsys.path.append(current_path)\nfrom models.bagnet import BagNet\nfrom models.resnet import ResNet\n\n## bagnet + resnet\n## bagnet + vgg\n\nclass ScaleAdaptiveLayer(nn.Module):\n def __init__(self, in_channels, out_channels):\n super(ScaleAdaptiveLayer, self).__init__()\n #self.scale_weight = nn.Parameter(torch.ones(out_channels))\n #self.scale_bias = nn.Parameter(torch.zeros(out_channels))\n\n self.conv = nn.Sequential(\n nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1),\n nn.ReLU(inplace=True)\n )\n\n def forward(self, x, target_shape):\n _, c, w, h = x.size()\n if not target_shape == (w, h):\n x = F.interpolate(x, target_shape)\n #x = x * self.scale_weight.reshape((1, c, 1, 1)) + self.scale_bias.reshape((1, c, 1, 1))\n out = self.conv(x)\n\n return out\n\n\nclass Bottleneck(nn.Module):\n expansion = 4\n def __init__(self, in_planes, planes, stride=1):\n super(Bottleneck, self).__init__()\n self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False)\n self.bn1 = nn.BatchNorm2d(planes)\n self.conv2 = nn.Conv2d(planes, planes, kernel_size=3,\n stride=stride, padding=1, bias=False)\n self.bn2 = nn.BatchNorm2d(planes)\n self.conv3 = nn.Conv2d(planes, self.expansion *\n planes, kernel_size=1, bias=False)\n self.bn3 = nn.BatchNorm2d(self.expansion*planes)\n\n self.shortcut = nn.Sequential()\n if stride != 1 or in_planes != self.expansion*planes:\n self.shortcut = nn.Sequential(\n nn.Conv2d(in_planes, self.expansion*planes,\n kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(self.expansion*planes)\n )\n\n def forward(self, x):\n out = F.relu(self.bn1(self.conv1(x)))\n out = F.relu(self.bn2(self.conv2(out)))\n out = self.bn3(self.conv3(out))\n out += self.shortcut(x)\n out = F.relu(out)\n\n return out\n\nclass ShareLayers(nn.Module):\n def __init__(self, first_block, channels, num_blocks, stride, mode='concat'):\n super(ShareLayers, self).__init__()\n self.first_block = first_block\n self.in_planes = channels\n self.mode = mode\n\n self.bag_sc_layer = ScaleAdaptiveLayer(in_channels=channels*4, out_channels=channels*4)\n self.res_sc_layer = ScaleAdaptiveLayer(in_channels=channels*4, out_channels=channels*4)\n self.share_layer = self._make_layer(Bottleneck, channels, num_blocks, stride)\n\n def _make_layer(self, block, planes, num_blocks, stride):\n strides = [stride] + [1]*(num_blocks-1)\n layers = []\n for i, stride in enumerate(strides):\n if i == 0:\n if self.mode == 'concat':\n if self.first_block:\n layers.append(block(2 * (self.in_planes*4), planes, stride))\n else:\n layers.append(block(2 * (self.in_planes*4) + (self.in_planes*2), planes, stride))\n elif self.mode == 'add':\n layers.append(block(self.in_planes, planes, stride))\n else:\n layers.append(block(self.in_planes, planes, stride))\n self.in_planes = planes * block.expansion\n return nn.Sequential(*layers)\n\n def forward(self, bag_x, res_x, share_x):\n target_shape = (int((bag_x.size(2) + res_x.size(2)) / 2), int((bag_x.size(3) + res_x.size(3)) / 2))\n\n bag_x = self.bag_sc_layer(bag_x, target_shape)\n res_x = self.res_sc_layer(res_x, target_shape)\n\n if self.mode == 'concat':\n if share_x is None:\n share_x = torch.cat([bag_x, res_x], dim=1)\n else:\n share_x = nn.AdaptiveAvgPool2d(target_shape)(share_x) ## down sampleで学習パラメータつける?\n share_x = torch.cat([bag_x, res_x, share_x], dim=1)\n elif self.mode == 'add':\n share_x = bag_x + res_x\n\n share_x = self.share_layer(share_x)\n\n return share_x\n\nclass BagResNet(nn.Module):\n def __init__(self, bag_arch='bagnet33', res_arch='resnet50', pool_num=5, pretrained=False, feat_freeze=False):\n super(BagResNet, self).__init__()\n self.pool_num = pool_num\n\n self.relu = nn.ReLU(inplace=True)\n if pool_num == 5:\n # BagNet\n self.bag_conv1, self.bag_conv2, self.bag_bn1, self.bag_layer1, self.bag_layer2, self.bag_layer3, self.bag_layer4 = self._make_baglayer(bag_arch, pool_num=pool_num, pretrained=pretrained, feat_freeze=feat_freeze)\n # ResNet\n self.res_conv, self.res_bn, self.res_pool, self.res_layer1, self.res_layer2, self.res_layer3, self.res_layer4 = self._make_reslayer(res_arch, pool_num=pool_num, pretrained=pretrained, feat_freeze=feat_freeze)\n\n # 特徴抽出部分だけ凍結\n if feat_freeze:\n for params in self.parameters():\n params.requires_grad = False\n\n self.share_layer1 = ShareLayers(first_block=True, channels=64, num_blocks=1, stride=1)\n self.share_layer2 = ShareLayers(first_block=False, channels=128, num_blocks=1, stride=1)\n self.share_layer3 = ShareLayers(first_block=False, channels=256, num_blocks=1, stride=1)\n self.share_layer4 = ShareLayers(first_block=False, channels=512, num_blocks=1, stride=1)\n if pool_num == 4:\n # BagNet\n self.bag_conv1, self.bag_conv2, self.bag_bn1, self.bag_layer1, self.bag_layer2, self.bag_layer3 = self._make_baglayer(bag_arch, pool_num=pool_num, pretrained=pretrained)\n # ResNet\n self.res_conv, self.res_bn, self.res_pool, self.res_layer1, self.res_layer2, self.res_layer3 = self._make_reslayer(res_arch, pool_num=pool_num, pretrained=pretrained)\n\n # 特徴抽出部分だけ凍結\n if feat_freeze:\n for params in self.parameters():\n params.requires_grad = False\n\n self.share_layer1 = ShareLayers(first_block=True, channels=64, num_blocks=1, stride=1)\n self.share_layer2 = ShareLayers(first_block=False, channels=128, num_blocks=1, stride=1)\n self.share_layer3 = ShareLayers(first_block=False, channels=256, num_blocks=1, stride=1)\n\n self.regresser = make_regresser(pool_num)\n self.output_layer = nn.Conv2d(64, 1, kernel_size=1)\n \n def forward(self, x):\n # BagNet flow\n bag_x_0 = self.bag_conv1(x)\n bag_x_0 = self.bag_conv2(bag_x_0)\n bag_x_0 = self.bag_bn1(bag_x_0)\n bag_x_0 = self.relu(bag_x_0) # [B, 64, 510, 510]\n\n bag_x_1 = self.bag_layer1(bag_x_0) # [B, 256, 254, 254]\n bag_x_2 = self.bag_layer2(bag_x_1) # [B, 512, 126, 126]\n bag_x_3 = self.bag_layer3(bag_x_2) # [B, 1024, 62, 62]\n if self.pool_num == 5:\n bag_x_4 = self.bag_layer4(bag_x_3) # [B, 2048, 60, 60]\n\n # ResNet flow\n res_x_0 = self.res_conv(x)\n res_x_0 = self.res_bn(res_x_0)\n res_x_0 = self.relu(res_x_0)\n res_x_0 = self.res_pool(res_x_0) # [B, 64, 256, 256]\n\n res_x_1 = self.res_layer1(res_x_0) # [B, 256, 128, 128]\n res_x_2 = self.res_layer2(res_x_1) # [B, 512, 64, 64]\n res_x_3 = self.res_layer3(res_x_2) # [B, 1024, 32, 32]\n if self.pool_num == 5:\n res_x_4 = self.res_layer4(res_x_3) # [B, 2048, 16, 16]\n\n # Share flow\n share_x_1 = self.share_layer1(bag_x_1, res_x_1, None) # [B, 256, 191, 191]\n share_x_2 = self.share_layer2(bag_x_2, res_x_2, share_x_1) # [B, 512, 95, 95]\n share_x_3 = self.share_layer3(bag_x_3, res_x_3, share_x_2) # [B, 1024, 47, 47]\n\n if self.pool_num == 4:\n x = self.regresser(share_x_3)\n if self.pool_num == 5:\n share_x_4 = self.share_layer4(bag_x_4, res_x_4, share_x_3) # [B, 2048, 38, 38]\n x = self.regresser(share_x_4)\n\n x = self.output_layer(x)\n \n return torch.abs(x)\n\n def _make_baglayer(self, arch, pool_num=5, pretrained=False, feat_freeze=False):\n if pool_num == 5:\n model = BagNet(arch=arch, pool_num=pool_num, pretrained=pretrained)\n if feat_freeze:\n # ST-A\n # model.load_state_dict(torch.load('/mnt/hdd02/res-bagnet/layer-last/sta-bagnet33-pretrained/best_model.pth'))\n # ST-B\n # model.load_state_dict(torch.load('/mnt/hdd02/res-bagnet/layer-last/stb-bagnet33-pretrained/best_model.pth'))\n # synthetic\n model.load_state_dict(torch.load('/mnt/hdd02/res-bagnet/layer-last/imagenet-pretrained/re_qnrf-bagnet33-pretrained-schedule_100step/best_model.pth'))\n\n bag_conv1 = model.feature_extracter.conv1\n bag_conv2 = model.feature_extracter.conv2\n bag_bn1 = model.feature_extracter.bn2d\n \n bag_layer1 = model.feature_extracter.block1\n bag_layer2 = model.feature_extracter.block2\n bag_layer3 = model.feature_extracter.block3\n bag_layer4 = model.feature_extracter.block4\n\n return bag_conv1, bag_conv2, bag_bn1, bag_layer1, bag_layer2, bag_layer3, bag_layer4\n\n elif pool_num == 4:\n model = BagNet(arch=arch, pool_num=pool_num, pretrained=pretrained)\n if feat_freeze:\n # ST-A\n # model.load_state_dict(torch.load('/mnt/hdd02/res-bagnet/layer-last-1/sta-bagnet33-pretrained/best_model.pth'))\n # ST-B\n # model.load_state_dict(torch.load('/mnt/hdd02/res-bagnet/layer-last-1/stb-bagnet33-pretrained/best_model.pth'))\n # synthetic\n model.load_state_dict(torch.load('/mnt/hdd02/res-bagnet/layer-last/imagenet-pretrained/re_qnrf-bagnet33-pretrained-schedule_100step/best_model.pth'))\n\n bag_conv1 = model.feature_extracter.conv1\n bag_conv2 = model.feature_extracter.conv2\n bag_bn1 = model.feature_extracter.bn2d\n \n bag_layer1 = model.feature_extracter.block1\n bag_layer2 = model.feature_extracter.block2\n bag_layer3 = model.feature_extracter.block3\n\n return bag_conv1, bag_conv2, bag_bn1, bag_layer1, bag_layer2, bag_layer3\n\n def _make_reslayer(self, arch, pool_num=5, pretrained=False, feat_freeze=False):\n if pool_num == 5:\n model = ResNet(arch=arch, pool_num=pool_num, pretrained=pretrained)\n if feat_freeze:\n # ST-A\n #model.load_state_dict(torch.load('/mnt/hdd02/res-bagnet/layer-last/sta-resnet50-pretrained/best_model.pth'))\n # ST-B\n # model.load_state_dict(torch.load('/mnt/hdd02/res-bagnet/layer-last/stb-resnet50-pretrained/best_model.pth'))\n # synthetic\n model.load_state_dict(torch.load('/mnt/hdd02/res-bagnet/layer-last/imagenet-pretrained/re_qnrf-resnet50-pretrained/best_model.pth'))\n\n res_conv = model.feature_extracter.conv2d\n res_bn = model.feature_extracter.bn2d\n res_pool = model.feature_extracter.maxpool\n \n res_layer1 = model.feature_extracter.layer1\n res_layer2 = model.feature_extracter.layer2\n res_layer3 = model.feature_extracter.layer3\n res_layer4 = model.feature_extracter.layer4\n\n return res_conv, res_bn, res_pool, res_layer1, res_layer2, res_layer3, res_layer4\n\n elif pool_num == 4:\n model = ResNet(arch=arch, pool_num=pool_num, pretrained=pretrained)\n if feat_freeze:\n # ST-A\n #model.load_state_dict(torch.load('/mnt/hdd02/res-bagnet/layer-last-1/sta-resnet50-pretrained/best_model.pth'))\n # ST-B\n # model.load_state_dict(torch.load('/mnt/hdd02/res-bagnet/layer-last-1/stb-resnet50-pretrained/best_model.pth'))\n # synthetic\n model.load_state_dict(torch.load('/mnt/hdd02/res-bagnet/layer-last/imagenet-pretrained/re_qnrf-resnet50-pretrained/best_model.pth'))\n\n res_conv = model.feature_extracter.conv2d\n res_bn = model.feature_extracter.bn2d\n res_pool = model.feature_extracter.maxpool\n \n res_layer1 = model.feature_extracter.layer1\n res_layer2 = model.feature_extracter.layer2\n res_layer3 = model.feature_extracter.layer3\n\n return res_conv, res_bn, res_pool, res_layer1, res_layer2, res_layer3\n\ndef make_regresser(pool_num):\n base_ch = 64\n layers = []\n for i in range(pool_num, 0, -1): \n conv2d = nn.Conv2d(base_ch*(2**i), base_ch*(2**(i-1)), kernel_size=3, padding=1)\n layers += [conv2d, nn.ReLU(inplace=True)]\n return nn.Sequential(*layers)\n\nif __name__ == '__main__':\n\n model = BagResNet(pool_num=4)\n #print(model)\n\n x = torch.rand(1, 3, 512, 512)\n out = model(x)\n\n print(model)\n print(out.shape)"
] |
[
[
"torch.nn.Sequential",
"torch.abs",
"torch.cat",
"torch.load",
"torch.nn.Conv2d",
"torch.nn.functional.relu",
"torch.nn.AdaptiveAvgPool2d",
"torch.rand",
"torch.nn.functional.interpolate",
"torch.nn.BatchNorm2d",
"torch.nn.ReLU"
]
] |
M87K452b/logistic-map-plot
|
[
"9878888d010d78413040bb29213bb0bf85b00531"
] |
[
"lmap_bifircation_plot.py"
] |
[
"'''\r\nThis program computes the logistic map equation.\r\nThe logistic map equation is a second degree polynomial equation often used as an example in the discussions of chaos\r\n\r\nMore information:\r\nwiki: https://en.wikipedia.org/wiki/Logistic_map#Finding_cycles_of_any_length_when_r_=_4\r\n\r\nAuthor: Harivinay V\r\ngithub: https://github.com/M87K452b\r\n'''\r\n\r\n# IMPORTS\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom numba import jit\r\nimport time\r\n\r\n@jit(nopython=True) # Compute this line out in the absence of a supported GPU\r\ndef lmap_compute(xn=4,r=0.0015):\r\n '''\r\n This functions computes the Logistic Map equationexit\r\n '''\r\n rvals = []\r\n xvals = []\r\n\r\n for r in np.arange(0,xn,r):\r\n #print('r = {}\\r'.format(r), end=\"\") # Disabled because jit doesnt like it! \r\n xold = 0.5\r\n # To get equlibrium value\r\n for i in range(2000):\r\n xnew = (xold-(xold**2))*r\r\n xold = xnew\r\n \r\n # Save equilibrium values\r\n xsteady = xnew\r\n for i in range(1001):\r\n xnew = (xold-(xold**2))*r\r\n xold = xnew\r\n rvals.append(r)\r\n xvals.append(xnew)\r\n if abs(xnew - xsteady) < 0.001:\r\n break\r\n return rvals,xvals\r\n\r\n# Run the main function\r\n\r\n## Define Inputs\r\nxn = 4\r\nr = 0.0025\r\n\r\ntic = time.perf_counter()\r\nrvals,xvals = lmap_compute(xn,r)\r\ntoc = time.perf_counter()\r\n\r\nprint('computation time: ',abs(toc - tic))\r\n\r\n# Visualization\r\n\r\nf = plt.figure(figsize = (16,12))\r\nplt.subplot(111)\r\nax1 = plt.scatter(rvals,xvals, s = 0.05)\r\nplt.xlim(3.447,4.0)\r\nplt.ylim(0,1)\r\nplt.axis('off')\r\nplt.show()\r\n\r\nf.savefig(\"bifircation-plot_r{}.png\".format(r), bbox_inches='tight', dpi=400)"
] |
[
[
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.ylim",
"numpy.arange",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] |
phd-jaybie/spatial-privacy-pointnetvlad
|
[
"a9857fe7030395eadfa1e9a9567ad7d889bad31f"
] |
[
"nn_matchers.py"
] |
[
"import numpy as np\nimport sys\nimport matplotlib.pyplot as plt\nimport math\nimport pickle\nimport pandas as pd\nimport scipy.io\nimport time\n\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\n\nfrom numpy import linalg as LA\nfrom scipy.spatial import Delaunay\nfrom sklearn.neighbors import NearestNeighbors, KDTree\n\nfrom info3d import *\n\ndef get_score_kdtree(obj_meta, pointcloud, triangles, descriptors, RANSAC = False, strict = False, old = False):\n \n # ROTATION\n random_theta = (2*np.pi)*np.random.random()# from [0, 2pi)\n random_axis = np.random.choice(np.arange(0,3))\n rotated_pointCloud = rotatePointCloud(pointcloud, random_theta, random_axis)\n\n # TRANSLATION\n t_pointCloud = np.asarray(rotated_pointCloud)\n random_tx_axis = np.random.choice(np.arange(0,3))\n random_translation = np.random.random()\n t_pointCloud[:,random_tx_axis] = t_pointCloud[:,random_tx_axis] + random_translation\n\n #t1 = time.time()\n \n #RANSAC\n if RANSAC and not old:\n # GETTING GENERALIZATION\n gen_planes = getRansacPlanes(\n t_pointCloud,\n triangles,\n strict = strict\n )\n\n t_pointCloud, t_triangles = getGeneralizedPointCloud(\n planes = gen_planes,\n strict = strict\n )\n \n #RANSAC old\n if RANSAC and old:\n # GETTING GENERALIZATION\n gen_planes, gen_plane_properties = getRansacPlanesOld(\n t_pointCloud,\n triangles\n )\n\n t_pointCloud, t_triangles = getGeneralizedPointCloudOld(\n planes = gen_planes,\n plane_properties = gen_plane_properties\n )\n\n try:\n p_descriptors, p_keypoints, p_d_c = getSpinImageDescriptors(\n t_pointCloud,\n down_resolution = 5,\n cylindrical_quantization = [4,5]\n )\n except Exception as ex:\n print(\"Error getting descriptors of\",obj_meta[:2],len(t_pointCloud))\n print(\"Error Message:\",ex)\n \n return\n\n # Resetting the diff_Ratio matrix\n diff_scores = np.ones((p_descriptors.shape[0],len(descriptors),2))\n diff_ratios = np.ones((p_descriptors.shape[0],len(descriptors)))\n diff_indexs = np.ones((p_descriptors.shape[0],len(descriptors),2))\n\n #print(diff_ratios.shape)\n local_keypoint_matches = []\n\n for i_r, ref_descriptor in enumerate(descriptors):\n\n r_descriptors = ref_descriptor[1]\n r_keypoints = ref_descriptor[2]\n\n matching_range = np.arange(r_descriptors.shape[1])\n\n try: \n tree = KDTree(r_descriptors, leaf_size = 2)\n diff, f_nearestneighbor = tree.query(p_descriptors,k=2)\n #print(p_descriptors.shape,r_descriptors.shape)\n #print(diff.shape, f_nearestneighbor.shape)\n diff = diff/np.amax(diff) # max-normalization of differences\n diff_ratio = diff[:,0]/diff[:,1]\n diff_ratios[:,i_r] = diff_ratio\n diff_scores[:,i_r] = diff\n diff_indexs[:,i_r] = f_nearestneighbor\n\n # Taking note of the matched keypoints\n local_keypoint_matches.append([\n obj_meta,\n p_keypoints,\n r_keypoints[f_nearestneighbor[:,0]]\n ])\n\n except Exception as ex:\n print(\"Error Matching:\",ex)\n\n return obj_meta, np.asarray(diff_ratios), np.asarray(diff_indexs), np.asarray(diff_scores), local_keypoint_matches\n\n\n\ndef getRankedErrors_withKeypointMatches(_scores, rank = 1):\n \n _errors = []\n _errors_map = []\n \n for obj_meta, scores, kp_matches in _scores:\n\n adjusted_scores = scores[:,0]*scores[:,-1]/scores[:,1]\n\n if obj_meta[0] in np.argsort(adjusted_scores)[-rank:]:\n if np.isnan(adjusted_scores[obj_meta[0]]):\n _errors.append([\n obj_meta[0],\n 1,\n np.nan,\n np.nan,\n np.argsort(adjusted_scores)[-rank:][0]\n ])\n else:\n \n best_keypointMatches = kp_matches[np.argmax(adjusted_scores)]\n qry_kp = best_keypointMatches[1]\n ref_kp = best_keypointMatches[2]\n \n best_ref_kps, best_qry_kps = get_best_kp_matches(\n ref_kp, qry_kp\n )\n\n _errors.append([\n obj_meta[0],\n 0,\n LA.norm(np.mean(best_ref_kps, axis = 0) - obj_meta[2][:3]),\n LA.norm(np.mean(ref_kp[:,:3], axis = 0) - obj_meta[2][:3]),\n np.argsort(adjusted_scores)[-rank:][0]\n ])\n else:\n _errors.append([\n obj_meta[0],\n 1,\n np.nan,\n np.nan,\n np.argsort(adjusted_scores)[-rank:][0]\n ])\n\n _errors = np.asarray(_errors)\n \n return _errors\n\ndef NN_matcher(partial_scores):\n \n t0 = time.time()\n \n errors = []\n #error_map = np.zeros((len(partial_scores), len(partial_scores))) \n\n #print(qp_ratios.shape, qp_nn_idx.shape)\n #continue\n for obj_meta, diff_ratios, diff_indexs, diff_scores, local_keypoint_matches in partial_scores:\n \n #obj_meta = scores[0]\n #diff_ratios = scores[1]\n #diff_indexs = scores[2]\n\n diff_nn = diff_indexs[:,:,0]\n\n scores_per_object = []\n\n for c_o, c_d in enumerate(diff_ratios.T):\n nns = diff_nn[:,c_o]\n unq, unq_ind = np.unique(nns[np.argsort(c_d)], return_index=True)\n unique_scores = c_d[np.argsort(c_d)][unq_ind]\n\n scores_per_object.append([\n len(unique_scores),\n 1-np.mean(unique_scores)\n ])\n\n scores_per_object = np.asarray(scores_per_object)\n weighted_scores = np.multiply(scores_per_object[:,1],scores_per_object[:,0]/len(diff_ratios))\n\n #error_count[i_o,1] = np.amax(weighted_scores)\n #if i_o not in np.argsort(weighted_scores)[::-1][:1]: #!= i_o:\n if obj_meta[0] != np.argmax(weighted_scores): #!= i_o:\n errors.append([\n obj_meta[0], # object meta information\n 1, #correct inter-space label or not\n np.nan, # distance from correct intra-spae label\n np.argmax(weighted_scores)\n ])\n else: # Correct inter-space label; then, check intra-space label.\n \n #diff_scores = scores[3]\n #local_keypoint_matches = scores[4]\n \n best_keypointMatches = local_keypoint_matches[np.argmax(weighted_scores)]\n qry_kp = best_keypointMatches[1]\n ref_kp = best_keypointMatches[2]\n\n best_ref_kps, best_qry_kps = get_best_kp_matches(\n ref_kp, qry_kp, \n diff_ratios[:,np.argmax(weighted_scores)]\n )\n \n errors.append([\n obj_meta[0],\n 0,\n LA.norm(np.mean(best_ref_kps[:,:3], axis = 0) - obj_meta[2][:3]),\n np.argmax(weighted_scores)\n ])\n\n errors = np.asarray(errors)\n \n return errors\n\n\ndef unique_nn_vote_count_with_ratio_scores_3_ForPartials(partial_scores):\n \n errors = []\n #error_map = np.zeros((len(partial_scores), len(partial_scores))) \n\n #print(qp_ratios.shape, qp_nn_idx.shape)\n #continue\n for i_o, scores in enumerate(partial_scores):\n \n obj_meta = scores[0]\n diff_ratios = scores[1]\n diff_indexs = scores[2]\n #diff_scores = scores[3]\n\n diff_nn = diff_indexs[:,:,0]\n\n scores_per_object = []\n\n for c_o, c_d in enumerate(diff_ratios.T):\n nns = diff_nn[:,c_o]\n unq, unq_ind = np.unique(nns[np.argsort(c_d)], return_index=True)\n unique_scores = c_d[np.argsort(c_d)][unq_ind]\n\n scores_per_object.append([\n len(unique_scores),\n 1-np.mean(unique_scores)\n ])\n\n scores_per_object = np.asarray(scores_per_object)\n weighted_scores = np.multiply(scores_per_object[:,1],scores_per_object[:,0]/len(diff_ratios))\n\n #error_count[i_o,1] = np.amax(weighted_scores)\n #if i_o not in np.argsort(weighted_scores)[::-1][:1]: #!= i_o:\n if obj_meta[0] != np.argmax(weighted_scores): #!= i_o:\n errors.append([\n obj_meta[0],\n 1\n ])\n else:\n errors.append([\n obj_meta[0],\n 0\n ])\n\n errors = np.asarray(errors)\n \n return errors\n\ndef nn_vote_count_0(g_scores):\n \n error_counts = []\n error_maps = []\n \n for i, g_score in enumerate(g_scores):\n qp_ratios = g_score[0]\n qp_nn_idx = g_score[1]\n \n error_count = np.zeros(len(qp_ratios))\n error_map = np.zeros((len(qp_ratios), len(qp_ratios)))\n\n for i_o, diff_ratios_per_object in enumerate(qp_ratios):\n\n m2 = np.bincount(np.argsort(diff_ratios_per_object,axis = 1)[:,:1].flatten()).argmax()\n if m2 != i_o:\n error_count[i_o] = 1\n\n error_map[i_o,m2] = 1\n\n error_counts.append(np.sum(error_count))\n error_maps.append(error_map)\n \n return np.asarray(error_counts), np.asarray(error_maps)\n \n\ndef nn_vote_count_with_ratio_scores_1(g_scores):\n \n error_counts = []\n error_maps = []\n\n for i, g_score in enumerate(g_scores):\n qp_ratios = g_score[0]\n qp_nn_idx = g_score[1]\n \n error_count = np.zeros((len(qp_ratios),2))\n error_map = np.zeros((len(qp_ratios), len(qp_ratios)))\n\n #print(qp_ratios.shape, qp_nn_idx.shape)\n #continue\n for i_o, diff_ratios_per_object in enumerate(qp_ratios):\n\n #print(diff_ratios_per_object.shape)\n sorted_ratios = np.sort(diff_ratios_per_object,axis = 1)[:,:1]\n sorted_indices = np.argsort(diff_ratios_per_object,axis = 1)[:,:1]\n votes = np.bincount(sorted_indices.flatten())\n #print(votes,np.argsort(votes)[::-1])\n #print(sorted_ratios.shape)#,sorted_ratios)\n #print(sorted_indices.shape)#,sorted_indices)\n\n vote_ratios = []\n for m_i, m_count in enumerate(votes):\n if m_count == 0:\n vote_ratios.append(0)\n else: \n scores = np.nan_to_num(1 - np.mean(sorted_ratios[np.where(sorted_indices == m_i)]))\n vote_ratios.append(scores)\n\n votes_weights = np.concatenate(\n (votes[:,np.newaxis],np.asarray(vote_ratios)[:,np.newaxis]),axis = 1\n )\n\n weighted_scores = np.multiply(votes_weights[:,1],votes_weights[:,0]/sorted_indices.size)\n #np.argsort(weighted_scores)[::-1]\n\n error_count[i_o,1] = np.amax(weighted_scores)\n #if i_o not in np.argsort(weighted_scores)[::-1][:1]: #!= i_o:\n if i_o != np.argmax(weighted_scores): #!= i_o:\n error_count[i_o,0] = 1\n\n error_map[i_o,np.argmax(weighted_scores)] = 1\n\n error_maps.append(error_map) \n error_counts.append(np.sum(error_count[:,0]))\n \n return np.asarray(error_counts), np.asarray(error_maps)\n\n\n\ndef nn_vote_count_with_distance_scores_2(g_scores):\n \n error_counts = []\n error_maps = []\n\n for i, g_score in enumerate(g_scores):\n qp_ratios = g_score[0]\n qp_nn_idx = g_score[1]\n \n if len(g_score) < 3:\n print(\"Needs to have qp_scores. Only got ratios and indeces.\")\n return\n \n qp_scores = g_score[2]\n \n error_count = np.zeros((len(qp_ratios),2))\n error_map = np.zeros((len(qp_ratios), len(qp_ratios)))\n\n #print(qp_ratios.shape, qp_nn_idx.shape)\n #continue\n for i_o, diff_ratios_per_object in enumerate(qp_ratios):\n\n diff_scores = qp_scores[i_o][:,:,0]\n\n #print(diff_ratios_per_object.shape)\n sorted_ratios = np.sort(diff_ratios_per_object,axis = 1)[:,:1]\n sorted_ratio_indices = np.argsort(diff_ratios_per_object,axis = 1)[:,:1]\n sorted_scores_indices = diff_scores[:,sorted_ratio_indices][:,:1]\n\n votes = np.bincount(sorted_ratio_indices.flatten())\n #print(votes,np.argsort(votes)[::-1])\n #print(sorted_ratios.shape)#,sorted_ratios)\n #print(sorted_indices.shape)#,sorted_indices)\n\n vote_ratios = []\n for m_i, m_count in enumerate(votes):\n if m_count == 0:\n vote_ratios.append(0)\n else: \n scores = np.nan_to_num(1 - np.mean(sorted_scores_indices[np.where(sorted_ratio_indices == m_i)]))\n vote_ratios.append(scores)\n\n votes_weights = np.concatenate(\n (votes[:,np.newaxis],np.asarray(vote_ratios)[:,np.newaxis]),axis = 1\n )\n\n weighted_scores = np.multiply(votes_weights[:,1],votes_weights[:,0]/sorted_ratio_indices.size)\n #np.argsort(weighted_scores)[::-1]\n\n error_count[i_o,1] = np.amax(weighted_scores)\n #if i_o not in np.argsort(weighted_scores)[::-1][:1]: #!= i_o:\n if i_o != np.argmax(weighted_scores): #!= i_o:\n error_count[i_o,0] = 1\n\n error_map[i_o,np.argmax(weighted_scores)] = 1\n\n error_counts.append(np.sum(error_count[:,0]))\n error_maps.append(error_map) \n #print(\" \",np.sum(error_count[:,0]),\"errors\")\n\n return np.asarray(error_counts), np.asarray(error_maps)\n\n\ndef unique_nn_vote_count_with_ratio_scores_3(g_scores):\n \n error_counts = []\n error_maps = []\n\n for i, g_score in enumerate(g_scores):\n qp_ratios = g_score[0]\n qp_nn_idx = g_score[1]\n \n error_count = np.zeros((len(qp_ratios),2))\n error_map = np.zeros((len(qp_ratios), len(qp_ratios))) \n\n total_scores = []\n\n #print(qp_ratios.shape, qp_nn_idx.shape)\n #continue\n for i_o, diff_ratios_per_object in enumerate(qp_ratios):\n\n diff_nn = qp_nn_idx[i_o][:,:,0]\n\n scores_per_object = []\n\n for c_o, c_d in enumerate(diff_ratios_per_object.T):\n nns = diff_nn[:,c_o]\n unq, unq_ind = np.unique(nns[np.argsort(c_d)], return_index=True)\n unique_scores = c_d[np.argsort(c_d)][unq_ind]\n\n scores_per_object.append([\n len(unique_scores),\n 1-np.mean(unique_scores)\n ])\n\n scores_per_object = np.asarray(scores_per_object)\n weighted_scores = np.multiply(scores_per_object[:,1],scores_per_object[:,0]/len(diff_ratios_per_object))\n\n total_scores.append(\n weighted_scores\n )\n #np.argsort(weighted_scores)[::-1]\n\n #error_count[i_o,1] = np.amax(weighted_scores)\n #if i_o not in np.argsort(weighted_scores)[::-1][:1]: #!= i_o:\n if i_o != np.argmax(weighted_scores): #!= i_o:\n error_count[i_o,0] = 1\n\n error_map[i_o,np.argmax(weighted_scores)] = 1\n\n error_counts.append(np.sum(error_count[:,0]))\n error_maps.append(error_map) \n \n return np.asarray(error_counts), np.asarray(error_maps)\n\n\n\ndef unique_nn_vote_count_with_distance_scores_4(g_scores):\n \n error_counts = []\n error_maps = []\n\n\n for i, g_score in enumerate(g_scores):\n qp_ratios = g_score[0]\n qp_nn_idx = g_score[1]\n \n if len(g_score) < 3:\n print(\"Needs to have qp_scores. Only got ratios and indeces.\")\n return\n \n qp_scores = g_score[2]\n \n error_count = np.zeros((len(qp_ratios),2))\n error_map = np.zeros((len(qp_ratios), len(qp_ratios))) \n\n total_scores = []\n\n #print(qp_ratios.shape, qp_nn_idx.shape)\n #continue\n for i_o, diff_ratios_per_object in enumerate(qp_ratios):\n\n diff_nn = qp_nn_idx[i_o][:,:,0]\n diff_scores = qp_scores[i_o][:,:,0]\n\n scores_per_object = []\n\n for c_o, c_d in enumerate(diff_ratios_per_object.T):\n nns = diff_nn[:,c_o]\n scores = diff_scores[:,c_o]\n unq, unq_ind = np.unique(nns[np.argsort(c_d)], return_index=True)\n unique_scores = scores[np.argsort(scores)][unq_ind]\n\n scores_per_object.append([\n len(unique_scores),\n 1-np.mean(unique_scores)\n ])\n\n scores_per_object = np.asarray(scores_per_object)\n weighted_scores = np.multiply(scores_per_object[:,1],scores_per_object[:,0]/len(diff_ratios_per_object))\n\n total_scores.append(\n weighted_scores\n )\n #np.argsort(weighted_scores)[::-1]\n\n #error_count[i_o,1] = np.amax(weighted_scores)\n #if i_o not in np.argsort(weighted_scores)[::-1][:1]: #!= i_o:\n if i_o != np.argmax(weighted_scores): #!= i_o:\n error_count[i_o,0] = 1\n\n error_map[i_o,np.argmax(weighted_scores)] = 1\n\n error_counts.append(np.sum(error_count[:,0]))\n error_maps.append(error_map) \n #print(\" \",np.sum(error_count[:,0]),\"errors\")\n \n return np.asarray(error_counts), np.asarray(error_maps)\n\ndef skip_diag_masking(A):\n return A[~np.eye(A.shape[0],dtype=bool)].reshape(A.shape[0],A.shape[1]-1,-1)\n\n \ndef get_best_kp_matches(\n ref_kp, qry_kp, \n diff_ratios = [], \n ratio_threshold = 0.9, \n good_match_threshold = 0.95,\n combine = True\n):\n \n best_ratio_inidices = [[],[]]\n \n while len(best_ratio_inidices[0]) == 0:\n \n if diff_ratios != []:# Get indices of pairs of matched descriptors gave the best ratio\n best_ratio_inidices = np.where(diff_ratios<ratio_threshold)\n\n # Get the corresponding kp pairs.\n best_ratio_qry_kp = qry_kp[best_ratio_inidices[0]][:,:3]\n best_ratio_ref_kp = ref_kp[best_ratio_inidices[0]][:,:3]\n else: \n best_ratio_qry_kp = qry_kp[:,:3]\n best_ratio_ref_kp = ref_kp[:,:3]\n \n ratio_threshold += 0.01\n if ratio_threshold >= 1.0:\n #print(\" Failed to get best matches.\")\n return ref_kp[:,:3], qry_kp[:,:3]\n \n\n # Get only the unique ones among the reference kp pairs which can have duplicates.\n unq_ref_kp, unq_idx = np.unique(best_ratio_ref_kp,axis = 0, return_index=True)\n unq_qry_kp = best_ratio_qry_kp[unq_idx]\n\n # Then, prepare for checking the inter-kp vectors.\n diff_qry_kps = np.repeat(unq_qry_kp[np.newaxis],repeats = len(unq_qry_kp), axis = 0) - unq_qry_kp[:,np.newaxis,:]\n diff_ref_kps = np.repeat(unq_ref_kp[np.newaxis],repeats = len(unq_ref_kp), axis = 0) - unq_ref_kp[:,np.newaxis,:]\n\n try:\n unq_diff_qry_kps = skip_diag_masking(diff_qry_kps)\n unq_diff_ref_kps = skip_diag_masking(diff_ref_kps)\n except:\n return ref_kp, qry_kp\n\n # Compare inter-kp vectors using cosine similarity. \n Norm_unq_diff_qry_kps = LA.norm(unq_diff_qry_kps, axis = -1)\n Norm_unq_diff_ref_kps = LA.norm(unq_diff_ref_kps, axis = -1)\n similarity_of_length = np.exp(-0.5*np.abs(Norm_unq_diff_qry_kps - Norm_unq_diff_ref_kps))\n similarity_of_angle = np.sum(np.multiply(unq_diff_qry_kps,unq_diff_ref_kps), axis = -1)/np.multiply(Norm_unq_diff_qry_kps,Norm_unq_diff_ref_kps)\n\n if combine:\n similarity_of_shape = np.multiply(similarity_of_length,similarity_of_angle)\n else:\n similarity_of_shape = similarity_of_angle\n\n # Good matches are those with cosine similarity near 1, e.g. cos_sim > 0.975\n good_matches = np.greater(\n np.abs(similarity_of_shape), \n good_match_threshold*np.ones(similarity_of_shape.shape)\n )\n\n while np.max(np.count_nonzero(good_matches, axis = -1)) < 0.1*len(ref_kp) and good_match_threshold>0.5:\n good_match_threshold = good_match_threshold - 0.05\n good_matches = np.greater(\n np.abs(similarity_of_shape), \n good_match_threshold*np.ones(similarity_of_shape.shape)\n )\n\n # Get which of the kp-pairs give the most good matches\n good_matches_ref_kp = np.argmax(np.count_nonzero(good_matches, axis = -1))\n good_matches_kp_idx = np.insert(good_matches[good_matches_ref_kp],True,good_matches_ref_kp)\n #good_matches_kp_idx.shape\n\n # Get corresponding indices of those with good kp matches\n for_plotting_idx = np.where(good_matches_kp_idx == True)[0]\n\n for_plotting_qry_kps = unq_qry_kp[for_plotting_idx]\n for_plotting_ref_kps = unq_ref_kp[for_plotting_idx]\n \n \n return for_plotting_ref_kps, for_plotting_qry_kps"
] |
[
[
"numpy.amax",
"numpy.asarray",
"sklearn.neighbors.KDTree",
"numpy.mean",
"numpy.where",
"numpy.unique",
"numpy.arange",
"numpy.eye",
"numpy.argmax",
"numpy.insert",
"numpy.count_nonzero",
"numpy.multiply",
"numpy.isnan",
"numpy.argsort",
"numpy.sum",
"numpy.random.random",
"numpy.abs",
"numpy.linalg.norm",
"numpy.sort",
"numpy.ones"
]
] |
w32zhong/FuxiCTR
|
[
"f9cac1c5b0a977d6a7dfd16c0ffb524811470f97",
"f9cac1c5b0a977d6a7dfd16c0ffb524811470f97"
] |
[
"fuxictr/datasets/data_utils.py",
"fuxictr/pytorch/models/HOFM.py"
] |
[
"# =========================================================================\r\n# Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved.\r\n# \r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n# =========================================================================\r\n\r\nimport h5py\r\nimport os\r\nimport logging\r\nimport numpy as np\r\nimport gc\r\nimport glob\r\n\r\n \r\ndef save_hdf5(data_array, data_path, key=\"data\"):\r\n logging.info(\"Saving data to h5: \" + data_path)\r\n if not os.path.exists(os.path.dirname(data_path)):\r\n os.makedirs(os.path.dirname(data_path))\r\n with h5py.File(data_path, 'w') as hf:\r\n hf.create_dataset(key, data=data_array)\r\n\r\n\r\ndef load_hdf5(data_path, key=None, verbose=True):\r\n if verbose:\r\n logging.info('Loading data from h5: ' + data_path)\r\n with h5py.File(data_path, 'r') as hf:\r\n if key is not None:\r\n data_array = hf[key][:]\r\n else:\r\n data_array = hf[list(hf.keys())[0]][:]\r\n return data_array\r\n\r\n\r\ndef split_train_test(train_ddf=None, valid_ddf=None, test_ddf=None, valid_size=0, \r\n test_size=0, split_type=\"sequential\"):\r\n num_samples = len(train_ddf)\r\n train_size = num_samples\r\n instance_IDs = np.arange(num_samples)\r\n if split_type == \"random\":\r\n np.random.shuffle(instance_IDs)\r\n if test_size > 0:\r\n if test_size < 1:\r\n test_size = int(num_samples * test_size)\r\n train_size = train_size - test_size\r\n test_ddf = train_ddf.loc[instance_IDs[train_size:], :].reset_index()\r\n instance_IDs = instance_IDs[0:train_size]\r\n if valid_size > 0:\r\n if valid_size < 1:\r\n valid_size = int(num_samples * valid_size)\r\n train_size = train_size - valid_size\r\n valid_ddf = train_ddf.loc[instance_IDs[train_size:], :].reset_index()\r\n instance_IDs = instance_IDs[0:train_size]\r\n if valid_size > 0 or test_size > 0:\r\n train_ddf = train_ddf.loc[instance_IDs, :].reset_index()\r\n return train_ddf, valid_ddf, test_ddf\r\n\r\n\r\ndef build_dataset(feature_encoder, train_data=None, valid_data=None, test_data=None, valid_size=0, \r\n test_size=0, split_type=\"sequential\", **kwargs):\r\n \"\"\" Build feature_map and transform h5 data \"\"\"\r\n # Load csv data\r\n train_ddf = feature_encoder.read_csv(train_data)\r\n valid_ddf = feature_encoder.read_csv(valid_data) if valid_data else None\r\n test_ddf = feature_encoder.read_csv(test_data) if test_data else None\r\n \r\n # Split data for train/validation/test\r\n if valid_size > 0 or test_size > 0:\r\n train_ddf, valid_ddf, test_ddf = split_train_test(train_ddf, valid_ddf, test_ddf, \r\n valid_size, test_size, split_type)\r\n # fit and transform train_ddf\r\n train_ddf = feature_encoder.preprocess(train_ddf)\r\n train_array = feature_encoder.fit_transform(train_ddf, **kwargs)\r\n block_size = int(kwargs.get(\"partition_block_size\", 0))\r\n if block_size > 0:\r\n block_id = 0\r\n for idx in range(0, len(train_array), block_size):\r\n save_hdf5(train_array[idx:(idx + block_size), :], os.path.join(feature_encoder.data_dir, 'train_part_{}.h5'.format(block_id)))\r\n block_id += 1\r\n else:\r\n save_hdf5(train_array, os.path.join(feature_encoder.data_dir, 'train.h5'))\r\n del train_array, train_ddf\r\n gc.collect()\r\n\r\n # Transfrom valid_ddf\r\n valid_ddf = feature_encoder.preprocess(valid_ddf)\r\n valid_array = feature_encoder.transform(valid_ddf)\r\n if block_size > 0:\r\n block_id = 0\r\n for idx in range(0, len(valid_array), block_size):\r\n save_hdf5(valid_array[idx:(idx + block_size), :], os.path.join(feature_encoder.data_dir, 'valid_part_{}.h5'.format(block_id)))\r\n block_id += 1\r\n else:\r\n save_hdf5(valid_array, os.path.join(feature_encoder.data_dir, 'valid.h5'))\r\n del valid_array, valid_ddf\r\n gc.collect()\r\n\r\n # Transfrom test_ddf\r\n test_ddf = feature_encoder.preprocess(test_ddf)\r\n test_array = feature_encoder.transform(test_ddf)\r\n if block_size > 0:\r\n block_id = 0\r\n for idx in range(0, len(test_array), block_size):\r\n save_hdf5(test_array[idx:(idx + block_size), :], os.path.join(feature_encoder.data_dir, 'test_part_{}.h5'.format(block_id)))\r\n block_id += 1\r\n else:\r\n save_hdf5(test_array, os.path.join(feature_encoder.data_dir, 'test.h5'))\r\n del test_array, test_ddf\r\n gc.collect()\r\n logging.info(\"Transform csv data to h5 done.\")\r\n\r\n\r\ndef h5_generator(feature_map, stage=\"both\", train_data=None, valid_data=None, test_data=None,\r\n batch_size=32, shuffle=True, **kwargs):\r\n logging.info(\"Loading data...\")\r\n if kwargs.get(\"partition_block_size\", 0) > 0: \r\n from ..pytorch.data_generator import DataBlockGenerator as DataGenerator\r\n else:\r\n from ..pytorch.data_generator import DataGenerator\r\n\r\n train_gen = None\r\n valid_gen = None\r\n test_gen = None\r\n if stage in [\"both\", \"train\"]:\r\n train_blocks = glob.glob(train_data)\r\n valid_blocks = glob.glob(valid_data)\r\n assert len(train_blocks) > 0 and len(valid_blocks) > 0, \"invalid data files or paths.\"\r\n if len(train_blocks) > 1:\r\n train_blocks.sort(key=lambda x: int(x.split(\"_\")[-1].split(\".\")[0]))\r\n if len(valid_blocks) > 1:\r\n valid_blocks.sort(key=lambda x: int(x.split(\"_\")[-1].split(\".\")[0]))\r\n train_gen = DataGenerator(train_blocks, batch_size=batch_size, shuffle=shuffle, **kwargs)\r\n valid_gen = DataGenerator(valid_blocks, batch_size=batch_size, shuffle=False, **kwargs)\r\n logging.info(\"Train samples: total/{:d}, pos/{:.0f}, neg/{:.0f}, ratio/{:.2f}%, blocks/{:.0f}\" \\\r\n .format(train_gen.num_samples, train_gen.num_positives, train_gen.num_negatives,\r\n 100. * train_gen.num_positives / train_gen.num_samples, train_gen.num_blocks))\r\n logging.info(\"Validation samples: total/{:d}, pos/{:.0f}, neg/{:.0f}, ratio/{:.2f}%, blocks/{:.0f}\" \\\r\n .format(valid_gen.num_samples, valid_gen.num_positives, valid_gen.num_negatives,\r\n 100. * valid_gen.num_positives / valid_gen.num_samples, valid_gen.num_blocks))\r\n if stage == \"train\":\r\n logging.info(\"Loading train data done.\")\r\n return train_gen, valid_gen\r\n\r\n if stage in [\"both\", \"test\"]:\r\n test_blocks = glob.glob(test_data)\r\n if len(test_blocks) > 1:\r\n test_blocks.sort(key=lambda x: int(x.split(\"_\")[-1].split(\".\")[0]))\r\n test_gen = DataGenerator(test_blocks, batch_size=batch_size, shuffle=False, **kwargs)\r\n logging.info(\"Test samples: total/{:d}, pos/{:.0f}, neg/{:.0f}, ratio/{:.2f}%, blocks/{:.0f}\" \\\r\n .format(test_gen.num_samples, test_gen.num_positives, test_gen.num_negatives,\r\n 100. * test_gen.num_positives / test_gen.num_samples, test_gen.num_blocks))\r\n if stage == \"test\":\r\n logging.info(\"Loading test data done.\")\r\n return test_gen\r\n\r\n logging.info(\"Loading data done.\")\r\n return train_gen, valid_gen, test_gen\r\n\r\n\r\ndef tfrecord_generator():\r\n raise NotImplementedError()\r\n\r\n\r\n",
"# =========================================================================\r\n# Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved.\r\n# \r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n# =========================================================================\r\n\r\nfrom torch import nn\r\nimport torch\r\nfrom .base_model import BaseModel\r\nfrom ..layers import LR_Layer, EmbeddingLayer, InnerProductLayer\r\nfrom itertools import combinations\r\n\r\n\r\nclass HOFM(BaseModel):\r\n def __init__(self, \r\n feature_map, \r\n model_id=\"HOFM\", \r\n gpu=-1, \r\n task=\"binary_classification\", \r\n learning_rate=1e-3, \r\n order=3,\r\n embedding_dim=10,\r\n reuse_embedding=False,\r\n embedding_dropout=0,\r\n regularizer=None, \r\n **kwargs):\r\n super(HOFM, self).__init__(feature_map, \r\n model_id=model_id, \r\n gpu=gpu, \r\n embedding_regularizer=regularizer, \r\n net_regularizer=regularizer,\r\n **kwargs)\r\n self.order = order\r\n assert order >= 2, \"order >= 2 is required in HOFM!\"\r\n self.reuse_embedding = reuse_embedding\r\n if reuse_embedding:\r\n assert isinstance(embedding_dim, int), \"embedding_dim should be an integer when reuse_embedding=True.\"\r\n self.embedding_layer = EmbeddingLayer(feature_map, embedding_dim)\r\n else:\r\n if not isinstance(embedding_dim, list):\r\n embedding_dim = [embedding_dim] * (order - 1)\r\n self.embedding_layers = nn.ModuleList([EmbeddingLayer(feature_map, embedding_dim[i]) \\\r\n for i in range(order - 1)])\r\n self.inner_product_layer = InnerProductLayer(feature_map.num_fields)\r\n self.lr_layer = LR_Layer(feature_map, use_bias=True)\r\n self.final_activation = self.get_final_activation(task)\r\n self.compile(kwargs[\"optimizer\"], loss=kwargs[\"loss\"], lr=learning_rate)\r\n self.apply(self.init_weights)\r\n self.field_conjunction_dict = dict()\r\n for order_i in range(3, self.order + 1):\r\n order_i_conjunction = zip(*list(combinations(range(feature_map.num_fields), order_i)))\r\n for k, field_index in enumerate(order_i_conjunction):\r\n self.field_conjunction_dict[(order_i, k)] = torch.LongTensor(field_index)\r\n\r\n def forward(self, inputs):\r\n \"\"\"\r\n Inputs: [X, y]\r\n \"\"\"\r\n X, y = self.inputs_to_device(inputs)\r\n y_pred = self.lr_layer(X)\r\n if self.reuse_embedding:\r\n feature_emb = self.embedding_layer(X)\r\n for i in range(2, self.order + 1):\r\n order_i_out = self.high_order_interaction(feature_emb if self.reuse_embedding \\\r\n else self.embedding_layers[i - 2](X), order_i=i)\r\n y_pred += order_i_out\r\n if self.final_activation is not None:\r\n y_pred = self.final_activation(y_pred)\r\n return_dict = {\"y_true\": y, \"y_pred\": y_pred}\r\n return return_dict\r\n\r\n def high_order_interaction(self, feature_emb, order_i):\r\n if order_i == 2:\r\n interaction_out = self.inner_product_layer(feature_emb)\r\n elif order_i > 2:\r\n index = self.field_conjunction_dict[(order_i, 0)].to(self.device)\r\n hadamard_product = torch.index_select(feature_emb, 1, index)\r\n for k in range(1, order_i):\r\n index = self.field_conjunction_dict[(order_i, k)].to(self.device)\r\n hadamard_product = hadamard_product * torch.index_select(feature_emb, 1, index)\r\n interaction_out = hadamard_product.sum((1, 2)).view(-1, 1)\r\n return interaction_out\r\n"
] |
[
[
"numpy.arange",
"numpy.random.shuffle"
],
[
"torch.LongTensor",
"torch.index_select"
]
] |
RubenPants/EvolvableRNN
|
[
"818a4ce941536611c0f1780f7c4a6238f0e1884e",
"818a4ce941536611c0f1780f7c4a6238f0e1884e"
] |
[
"population/utils/visualizing/gru_analysis.py",
"population/utils/gene_util/gru_no_reset.py"
] |
[
"\"\"\"\ngru_analysis.py\n\nAnalyse a single-GRU genome of the population.\n\"\"\"\nimport argparse\nimport copy\nimport multiprocessing as mp\nimport os\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.interpolate import griddata\nfrom tqdm import tqdm\n\nfrom config import Config\nfrom environment.env_multi import get_multi_env\nfrom main import get_game_ids, trace_most_fit, visualize_genome\nfrom population.population import Population\nfrom population.utils.gene_util.gru import GruNodeGene\nfrom population.utils.genome import Genome\nfrom population.utils.population_util.fitness_functions import calc_pop_fitness\nfrom utils.myutils import get_subfolder, update_dict\n\n\ndef main(pop: Population,\n d: int = 10,\n range_width: int = 20,\n genome: Genome = None,\n cpu: int = 2,\n experiment_id: int = 1,\n overwrite: bool = False,\n ):\n \"\"\"\n Analyse the given single-hidden single-GRU genome.\n \n Analysis is performed on following number of genomes: 3 * ((2 * range + 1) ** 2)\n * 10 = 1'323\n * 20 = 5'043\n * 50 = 30'603\n\n :param pop: Population on which the analysis is performed\n :param genome: The genome that is being mutated\n :param d: Divisor, indicating hops of 1/d\n :param range_width: Width of the parameter-range taken into account (note: true range is range_width/d)\n :param overwrite: Decide if re-evaluation\n :param experiment_id: Experiment-games used for evaluation\n :param cpu: Number of CPU cores not used for simulation\n \"\"\"\n # Get genome if not defined\n if not genome: genome = pop.best_genome\n \n # Create a cache-population\n cfg = copy.deepcopy(pop.config)\n cfg.population.pop_size = 2 # Dummy candidates, to be removed\n cfg.update()\n \n # Create the populations\n name = f\"genome{genome.key}_divisor{d}_range{range_width}\"\n pop_cache = Population(\n name=name,\n folder_name='../../cache_populations', # I do the hack hack\n config=cfg,\n overwrite=overwrite,\n )\n if len(pop_cache.population) == 2:\n create_genomes(genome=genome, pop=pop_cache, d=d, range_width=range_width)\n \n # Evaluate the populations\n if pop_cache.population[0].fitness is None:\n evaluate_population(\n pop=pop_cache,\n cfg=cfg,\n cpu=cpu,\n experiment_id=experiment_id,\n )\n \n # Evaluate the results - Create 3d array of the results\n visualize_score(pop=pop, pop_cache=pop_cache, genome=genome, d=d, range_width=range_width)\n\n\ndef create_genomes(genome: Genome, pop: Population, d: int, range_width: int):\n \"\"\"Create mutations of the provided genome and inject these in the given population..\"\"\"\n pop.log(f\"{pop.name} - Setting up genomes...\")\n pbar = tqdm(range(((range_width + range_width + 1) ** 2) * 3), desc=\"Generating genomes\")\n genome_key = 0\n \n gru_node_id = None\n for node_id, node in genome.nodes.items():\n if type(node) == GruNodeGene:\n gru_node_id = node_id\n break\n \n # Create the reset-mutated genomes\n for a in range(-range_width, range_width + 1):\n w_xh = np.asarray([[a / d], [0], [0]])\n for b in range(-range_width, range_width + 1):\n w_hh = np.asarray([[b / d], [0], [0]])\n \n # Add the specified genome to the population\n new_genome = copy.deepcopy(genome)\n new_genome.nodes[gru_node_id].weight_xh_full += w_xh\n new_genome.nodes[gru_node_id].weight_hh += w_hh\n new_genome.fitness = None\n new_genome.key = genome_key\n pop.population[genome_key] = new_genome\n genome_key += 1\n pbar.update()\n \n # Create the update-mutated genomes\n for a in range(-range_width, range_width + 1):\n w_xh = np.asarray([[0], [a / d], [0]])\n for b in range(-range_width, range_width + 1):\n w_hh = np.asarray([[0], [b / d], [0]])\n \n # Add the specified genome to the population\n new_genome = copy.deepcopy(genome)\n new_genome.nodes[gru_node_id].weight_xh_full += w_xh\n new_genome.nodes[gru_node_id].weight_hh += w_hh\n new_genome.fitness = None\n new_genome.key = genome_key\n pop.population[genome_key] = new_genome\n genome_key += 1\n pbar.update()\n \n # Create the candidate-mutated genomes\n for a in range(-range_width, range_width + 1):\n w_xh = np.asarray([[0], [0], [a / d]])\n for b in range(-range_width, range_width + 1):\n w_hh = np.asarray([[0], [0], [b / d]])\n \n # Add the specified genome to the population\n new_genome = copy.deepcopy(genome)\n new_genome.nodes[gru_node_id].weight_xh_full += w_xh\n new_genome.nodes[gru_node_id].weight_hh += w_hh\n new_genome.fitness = None\n new_genome.key = genome_key\n pop.population[genome_key] = new_genome\n genome_key += 1\n pbar.update()\n pbar.close()\n assert len(pop.population) == (((range_width - -range_width + 1) ** 2) * 3)\n pop.save()\n\n\ndef evaluate_population(pop: Population, cfg: Config, cpu: int, experiment_id: int):\n \"\"\"Evaluate the given population.\"\"\"\n pop.log(f\"{pop.name} - Evaluating the population...\")\n _, game_ids_eval = get_game_ids(experiment_id=experiment_id)\n multi_env = get_multi_env(pop=pop, game_config=cfg)\n multi_env.set_games(game_ids_eval, noise=False)\n pool = mp.Pool(mp.cpu_count() - cpu)\n manager = mp.Manager()\n return_dict = manager.dict()\n pbar = tqdm(total=len(pop.population), desc=\"Evaluating\")\n \n def update(*_):\n pbar.update()\n \n for genome_id, genome in pop.population.items():\n pool.apply_async(func=multi_env.eval_genome, args=((genome_id, genome), return_dict), callback=update)\n pool.close() # Close the pool\n pool.join() # Postpone continuation until everything is finished\n pbar.close()\n \n # Calculate the fitness from the given return_dict\n pop.log(f\"{pop.name} - Calculating fitness scores...\")\n fitness = calc_pop_fitness(\n fitness_cfg=pop.config.evaluation,\n game_cfg=cfg.game,\n game_obs=return_dict,\n gen=pop.generation,\n )\n for i, genome in pop.population.items():\n genome.fitness = fitness[i]\n \n # Get the fittest genome\n best = None\n for g in pop.population.values():\n if best is None or g.fitness > best.fitness: best = g\n pop.best_genome = best\n \n # Save the results\n pop.save()\n \n # Visualize most fit genome\n visualize_genome(\n debug=True,\n genome=best,\n population=pop,\n )\n \n # Trace the most fit genome\n trace_most_fit(\n debug=False,\n games=game_ids_eval,\n genome=best,\n population=pop,\n unused_cpu=cpu,\n )\n\n\ndef visualize_score(pop: Population, pop_cache: Population, genome: Genome, d: int, range_width: int):\n \"\"\"Visualize the score of the evaluated population.\"\"\"\n pop_cache.log(f\"{pop_cache.name} - Fetching fitness scores...\")\n dim = (2 * range_width + 1)\n pbar = tqdm(range((dim ** 2) * 3), desc=\"Fetching fitness scores\")\n genome_key = 0\n \n # Fetching scores of reset-mutations\n reset_scores = np.zeros((dim, dim))\n for a in range(dim):\n for b in range(dim):\n reset_scores[a, b] = pop_cache.population[genome_key].fitness\n genome_key += 1\n pbar.update()\n \n # Fetching scores of update-mutations\n update_scores = np.zeros((dim, dim))\n for a in range(dim):\n for b in range(dim):\n update_scores[a, b] = pop_cache.population[genome_key].fitness\n genome_key += 1\n pbar.update()\n \n # Fetching scores of candidate-mutations\n candidate_scores = np.zeros((dim, dim))\n for a in range(dim):\n for b in range(dim):\n candidate_scores[a, b] = pop_cache.population[genome_key].fitness\n genome_key += 1\n pbar.update()\n pbar.close()\n \n # Visualize the result\n pop_cache.log(f\"{pop_cache.name} - Visualizing the result...\")\n \n # GRU-node needed for labels\n genome.update_rnn_nodes(config=pop.config.genome)\n gru_node = None\n for node in genome.nodes.values():\n if type(node) == GruNodeGene:\n gru_node = node\n \n # Create the points and retrieve data for the plot\n points = [[x, y] for x in range(dim) for y in range(dim)]\n points_normalized = [[(p1 + -range_width) / d, (p2 + -range_width) / d] for p1, p2 in points]\n values_reset = [reset_scores[p[0], p[1]] for p in points]\n values_update = [update_scores[p[0], p[1]] for p in points]\n values_candidate = [candidate_scores[p[0], p[1]] for p in points]\n \n # K-nearest neighbours with hops of 0.01 is performed\n grid_x, grid_y = np.mgrid[-range_width / d:range_width / d:0.01, -range_width / d:range_width / d:0.01]\n \n # Perform k-NN\n data_reset = griddata(points_normalized, values_reset, (grid_x, grid_y), method='nearest')\n data_update = griddata(points_normalized, values_update, (grid_x, grid_y), method='nearest')\n data_candidate = griddata(points_normalized, values_candidate, (grid_x, grid_y), method='nearest')\n \n # Create the plots\n plt.figure(figsize=(15, 5))\n plt.subplot(131)\n plt.imshow(data_reset.T,\n vmin=0,\n vmax=1,\n extent=(-range_width / d, range_width / d, -range_width / d, range_width / d),\n origin='lower')\n plt.title('Reset-gate mutation')\n plt.xlabel(r'$\\Delta W_{hr}$' + f' (init={round(gru_node.weight_hh[0, 0], 3)})')\n plt.ylabel(r'$\\Delta W_{xr}$' + f' (init={round(gru_node.weight_xh[0, 0], 3)})')\n plt.subplot(132)\n plt.imshow(data_update.T,\n vmin=0,\n vmax=1,\n extent=(-range_width / d, range_width / d, -range_width / d, range_width / d),\n origin='lower')\n plt.title('Update-gate mutation')\n plt.xlabel(r'$\\Delta W_{hz}$' + f' (init={round(gru_node.weight_hh[1, 0], 3)})')\n plt.ylabel(r'$\\Delta W_{xz}$' + f' (init={round(gru_node.weight_xh[1, 0], 3)})')\n plt.subplot(133)\n plt.imshow(data_candidate.T,\n vmin=0,\n vmax=1,\n extent=(-range_width / d, range_width / d, -range_width / d, range_width / d),\n origin='lower')\n plt.title('Candidate-state mutation')\n plt.xlabel(r'$\\Delta W_{hh}$' + f' (init={round(gru_node.weight_hh[2, 0], 3)})')\n plt.ylabel(r'$\\Delta W_{xh}$' + f' (init={round(gru_node.weight_xh[2, 0], 3)})')\n \n # Store the plot\n plt.tight_layout()\n path = f\"population{'_backup' if pop.use_backup else ''}/storage/{pop.folder_name}/{pop}/\"\n path = get_subfolder(path, 'images')\n path = get_subfolder(path, 'gru_analysis')\n plt.savefig(f\"{path}{genome.key}.png\")\n plt.savefig(f\"{path}{genome.key}.eps\", format=\"eps\")\n plt.close()\n \n # Create overview\n pop_cache.log(\"Overview of results:\")\n log = dict()\n \n # Overview: reset-mutation\n max_index_reset, max_value_reset, min_index_reset, min_value_reset = None, 0, None, 1\n for index, x in np.ndenumerate(reset_scores):\n if x < min_value_reset: min_index_reset, min_value_reset = index, x\n if x > max_value_reset: max_index_reset, max_value_reset = index, x\n pop_cache.log(f\"\\tReset-gate mutation:\")\n pop_cache.log(f\"\\t > Maximum fitness: {round(max_value_reset, 2)} for index {max_index_reset!r}\")\n pop_cache.log(f\"\\t > Average fitness: {round(np.average(reset_scores), 2)}\")\n pop_cache.log(f\"\\t > Minimum fitness: {round(min_value_reset, 2)} for index {min_index_reset!r}\")\n log['Reset-gate maximum fitness'] = f\"{round(max_value_reset, 2)} for index {max_index_reset!r}\"\n log['Reset-gate average fitness'] = f\"{round(np.average(reset_scores), 2)}\"\n log['Reset-gate minimum fitness'] = f\"{round(min_value_reset, 2)} for index {min_index_reset!r}\"\n \n # Overview: update-mutation\n max_index_update, max_value_update, min_index_update, min_value_update = None, 0, None, 1\n for index, x in np.ndenumerate(update_scores):\n if x < min_value_update: min_index_update, min_value_update = index, x\n if x > max_value_update: max_index_update, max_value_update = index, x\n pop_cache.log(f\"\\tUpdate-gate mutation:\")\n pop_cache.log(f\"\\t > Maximum fitness: {round(max_value_update, 2)} for index {max_index_update!r}\")\n pop_cache.log(f\"\\t > Average fitness: {round(np.average(update_scores), 2)}\")\n pop_cache.log(f\"\\t > Minimum fitness: {round(min_value_update, 2)} for index {min_index_update!r}\")\n log['Update-gate maximum fitness'] = f\"{round(max_value_update, 2)} for index {max_index_update!r}\"\n log['Update-gate average fitness'] = f\"{round(np.average(update_scores), 2)}\"\n log['Update-gate minimum fitness'] = f\"{round(min_value_update, 2)} for index {min_index_update!r}\"\n \n # Overview: candidate-mutation\n max_index_candidate, max_value_candidate, min_index_candidate, min_value_candidate = None, 0, None, 1\n for index, x in np.ndenumerate(candidate_scores):\n if x < min_value_candidate: min_index_candidate, min_value_candidate = index, x\n if x > max_value_candidate: max_index_candidate, max_value_candidate = index, x\n pop_cache.log(f\"\\tCandidate-state mutation:\")\n pop_cache.log(f\"\\t > Maximum fitness: {round(max_value_candidate, 2)} for index {max_index_candidate!r}\")\n pop_cache.log(f\"\\t > Average fitness: {round(np.average(candidate_scores), 2)}\")\n pop_cache.log(f\"\\t > Minimum fitness: {round(min_value_candidate, 2)} for index {min_index_candidate!r}\")\n log['Candidate-state maximum fitness'] = f\"{round(max_value_candidate, 2)} for index {max_index_candidate!r}\"\n log['Candidate-state average fitness'] = f\"{round(np.average(candidate_scores), 2)}\"\n log['Candidate-state minimum fitness'] = f\"{round(min_value_candidate, 2)} for index {min_index_candidate!r}\"\n update_dict(f'{path}{genome.key}.txt', log)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='')\n parser.add_argument('--d', type=int, default=10)\n parser.add_argument('--range', type=int, default=10) # TODO: Change to 50\n parser.add_argument('--experiment', type=int, default=4)\n parser.add_argument('--unused_cpu', type=int, default=0)\n parser.add_argument('--overwrite', type=int, default=0)\n args = parser.parse_args()\n \n # Go back to root\n os.chdir(\"../../../\")\n \n # Fetch the genome we want to copy\n population = Population(\n name='test',\n folder_name='test',\n )\n \n # Execute the algorithm\n main(\n pop=population,\n d=args.d,\n range_width=args.range,\n overwrite=bool(args.overwrite),\n experiment_id=args.experiment,\n cpu=args.unused_cpu,\n )\n",
"\"\"\"\ngru_no_reset.py\n\nGene-representation of a hidden GRU node that lacks a reset gate.\n\"\"\"\nimport sys\n\nfrom numpy import round\n\nfrom configs.genome_config import GenomeConfig\nfrom population.utils.gene_util.rnn import RnnNodeGene\n\nif 'linux' in sys.platform:\n from population.utils.rnn_cell_util.cy.berkeley_gru_no_reset_cy import GRUCellNoResetCy as GRU\nelse:\n from population.utils.rnn_cell_util.berkeley_gru_no_reset import GRUCellNoReset as GRU\n\n\nclass GruNoResetNodeGene(RnnNodeGene):\n \"\"\"Custom GRU cell implementation.\"\"\"\n \n def __init__(self, key, cfg: GenomeConfig, input_keys=None, input_keys_full=None):\n super().__init__(\n key=key,\n hid_dim=2,\n cfg=cfg,\n input_keys=input_keys,\n input_keys_full=input_keys_full,\n )\n \n def __str__(self):\n self.update_weight_xh()\n bias = str(round(self.bias_h, 5)).replace('\\n', ',')\n weight_hh = str(round(self.weight_hh, 5)).replace('\\n', ',')\n weight_xh = str(round(self.weight_xh, 5)).replace('\\n', ',')\n return f\"GruNoResetNodeGene(\\n\" \\\n f\"\\tkey={self.key}\\n\" \\\n f\"\\tbias={bias},\\n\" \\\n f\"\\tinput_keys={self.input_keys},\\n\" \\\n f\"\\tweight_hh={weight_hh},\\n\" \\\n f\"\\tweight_xh={weight_xh})\"\n \n def __repr__(self):\n return f\"GruNoResetNodeGene(inputs={self.input_keys!r})\"\n \n def get_rnn(self, mapping=None):\n \"\"\"Return a GRUCell based on current configuration. The mapping denotes which columns to use.\"\"\"\n self.update_weight_xh()\n cell = GRU(\n input_size=len(mapping[mapping]) if mapping is not None else len(self.input_keys),\n bias=self.bias_h,\n weight_hh=self.weight_hh,\n weight_xh=self.weight_xh[:, mapping] if mapping is not None else self.weight_xh,\n )\n return cell\n"
] |
[
[
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.title",
"numpy.asarray",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.close",
"scipy.interpolate.griddata",
"numpy.ndenumerate",
"numpy.average",
"numpy.zeros",
"matplotlib.pyplot.figure"
],
[
"numpy.round"
]
] |
Josephbousaleh/MACT21.22_Digital_tools_Big_Data_part_2
|
[
"d17a98d5ac1371c04b2616fe594ff867ec575a57"
] |
[
"session_4/b_chunk_geodataframe.py"
] |
[
"# encoding: utf-8\n\n##################################################\n# This script shows how to read large files using pandas\n# With files exceeding sizes of GB, the chunk alternative is most of the times needed\n# https://pandas.pydata.org/docs/reference/api/pandas.read_csv.html\n\n\n#\n# Note: the project keeps updating every course almost yearly\n##################################################\n#\n##################################################\n# Author: Diego Pajarito\n# Credits: [Institute for Advanced Architecture of Catalonia - IAAC, Advanced Architecture group]\n# License: Apache License Version 2.0\n# Version: 0.7.0\n# Maintainer: Diego Pajarito\n# Email: [email protected]\n# Status: development\n##################################################\n\n# We need to import numpy and matplotlib library\n\nimport pandas as pd\nimport geopandas as gpd\nimport matplotlib as plt\n\n# Output file path and param\nday_num = 1\ninput_csv_filepath = f'../data/footfall/footfall_20210217/day{day_num}Bcntrakingotherdays.csv'\n\n# Setting a loop for chunks is compatible with geopandas\nchunksize = 10 ** 5\nfor df_chunk in pd.read_csv(input_csv_filepath, delimiter='|', low_memory=False, on_bad_lines='skip',\n chunksize=chunksize):\n gdf_chunk = gpd.GeoDataFrame(df_chunk, geometry=gpd.points_from_xy(df_chunk.LONGITUDE, df_chunk.LATITUDE),\n crs='epsg:4326')\n print('Chunk size in rows: ' + str(len(gdf_chunk)))\n\n\nprint('end')"
] |
[
[
"pandas.read_csv"
]
] |
classicsong/dgl-graphloader
|
[
"0bc9f8710bfb71f613c3fcb70573ed4c62dfb735"
] |
[
"tests/test_csv_loader.py"
] |
[
"import os\nfrom pathlib import Path\n\nimport unittest, pytest\nimport numpy as np\nimport torch as th\n\nimport dgl_graphloader\n\ndef create_category_node_feat(tmpdir, file_name, separator='\\t'):\n node_feat_f = open(os.path.join(tmpdir, file_name), \"w\")\n node_feat_f.write(\"node{}feat1{}feat2{}feat3\\n\".format(separator,separator,separator))\n node_feat_f.write(\"node1{}A{}B{}A,B\\n\".format(separator,separator,separator))\n node_feat_f.write(\"node2{}A{}{}A\\n\".format(separator,separator,separator))\n node_feat_f.write(\"node3{}C{}B{}C,B\\n\".format(separator,separator,separator))\n node_feat_f.write(\"node3{}A{}C{}A,C\\n\".format(separator,separator,separator))\n node_feat_f.close()\n\ndef create_numerical_node_feat(tmpdir, file_name, sep='\\t'):\n node_feat_f = open(os.path.join(tmpdir, file_name), \"w\")\n node_feat_f.write(\"node{}feat1{}feat2{}feat3{}feat4\\n\".format(sep,sep,sep,sep))\n node_feat_f.write(\"node1{}1.{}2.{}0.{}1.,2.,0.\\n\".format(sep,sep,sep,sep))\n node_feat_f.write(\"node2{}2.{}-1.{}0.{}2.,-1.,0.\\n\".format(sep,sep,sep,sep))\n node_feat_f.write(\"node3{}0.{}0.{}0.{}0.,0.,0.\\n\".format(sep,sep,sep,sep))\n node_feat_f.write(\"node3{}4.{}-2.{}0.{}4.,-2.,0.\\n\".format(sep,sep,sep,sep))\n node_feat_f.close()\n\ndef create_numerical_bucket_node_feat(tmpdir, file_name, sep='\\t'):\n node_feat_f = open(os.path.join(tmpdir, file_name), \"w\")\n node_feat_f.write(\"node{}feat1{}feat2\\n\".format(sep,sep,sep))\n node_feat_f.write(\"node1{}0{}0.\\n\".format(sep,sep,sep))\n node_feat_f.write(\"node1{}0{}5.\\n\".format(sep,sep,sep))\n node_feat_f.write(\"node1{}0{}15.\\n\".format(sep,sep,sep))\n node_feat_f.write(\"node1{}0{}20.\\n\".format(sep,sep,sep))\n node_feat_f.write(\"node1{}0{}10.1\\n\".format(sep,sep,sep))\n node_feat_f.write(\"node1{}0{}25.\\n\".format(sep,sep,sep))\n node_feat_f.write(\"node1{}0{}30.1\\n\".format(sep,sep,sep))\n node_feat_f.write(\"node1{}0{}40.\\n\".format(sep,sep,sep))\n node_feat_f.close()\n\ndef create_numerical_edge_feat(tmpdir, file_name, sep='\\t'):\n node_feat_f = open(os.path.join(tmpdir, file_name), \"w\")\n node_feat_f.write(\"node_s{}node_d{}feat1\\n\".format(sep,sep))\n node_feat_f.write(\"node1{}node4{}1.\\n\".format(sep,sep))\n node_feat_f.write(\"node2{}node5{}2.\\n\".format(sep,sep))\n node_feat_f.write(\"node3{}node6{}0.\\n\".format(sep,sep))\n node_feat_f.write(\"node3{}node3{}4.\\n\".format(sep,sep))\n node_feat_f.close()\n\ndef create_word_node_feat(tmpdir, file_name, separator='\\t'):\n node_feat_f = open(os.path.join(tmpdir, file_name), \"w\")\n node_feat_f.write(\"node{}feat1{}feat2{}feat3\\n\".format(separator,separator,separator))\n node_feat_f.write(\"node1{}A{}B{}24\\n\".format(separator,separator,separator))\n node_feat_f.write(\"node2{}A{}{}1\\n\".format(separator,separator,separator))\n node_feat_f.write(\"node3{}C{}B{}12\\n\".format(separator,separator,separator))\n node_feat_f.write(\"node3{}A{}C{}13\\n\".format(separator,separator,separator))\n node_feat_f.close()\n\ndef create_multiple_node_feat(tmpdir, file_name, separator='\\t'):\n node_feat_f = open(os.path.join(tmpdir, file_name), \"w\")\n node_feat_f.write(\"node{}feat1{}feat2{}feat3\\n\".format(separator,separator,separator))\n node_feat_f.write(\"node1{}A{}0.1{}A,B\\n\".format(separator,separator,separator))\n node_feat_f.write(\"node2{}A{}0.3{}A\\n\".format(separator,separator,separator))\n node_feat_f.write(\"node3{}C{}0.2{}C,B\\n\".format(separator,separator,separator))\n node_feat_f.write(\"node4{}A{}-1.1{}A,C\\n\".format(separator,separator,separator))\n node_feat_f.close()\n\ndef create_multiple_edge_feat(tmpdir, file_name, sep='\\t'):\n node_feat_f = open(os.path.join(tmpdir, file_name), \"w\")\n node_feat_f.write(\"node_s{}node_d{}feat1{}feat2{}feat3\\n\".format(sep,sep,sep,sep))\n node_feat_f.write(\"node1{}node_a{}0.2{}0.1{}1.1\\n\".format(sep,sep,sep,sep))\n node_feat_f.write(\"node2{}node_b{}-0.3{}0.3{}1.2\\n\".format(sep,sep,sep,sep))\n node_feat_f.write(\"node3{}node_c{}0.3{}0.2{}-1.2\\n\".format(sep,sep,sep,sep))\n node_feat_f.write(\"node4{}node_d{}-0.2{}-1.1{}0.9\\n\".format(sep,sep,sep,sep))\n node_feat_f.close()\n\ndef create_node_feats(tmpdir, file_name, separator='\\t'):\n node_feat_f = open(os.path.join(tmpdir, file_name), \"w\")\n node_feat_f.write(\"node{}label1{}label2\\n\".format(separator,separator))\n node_feat_f.write(\"node1{}A{}D,A\\n\".format(separator,separator))\n node_feat_f.write(\"node2{}A{}E,C,D\\n\".format(separator,separator))\n node_feat_f.write(\"node3{}C{}F,A,B\\n\".format(separator,separator))\n node_feat_f.write(\"node4{}A{}G,E\\n\".format(separator,separator))\n node_feat_f.write(\"node5{}A{}D,A\\n\".format(separator,separator))\n node_feat_f.write(\"node6{}C{}E,C,D\\n\".format(separator,separator))\n node_feat_f.write(\"node7{}A{}D,A\\n\".format(separator,separator))\n node_feat_f.write(\"node8{}A{}E,C,D\\n\".format(separator,separator))\n node_feat_f.close()\n\ndef create_node_labels(tmpdir, file_name, separator='\\t'):\n node_feat_f = open(os.path.join(tmpdir, file_name), \"w\")\n node_feat_f.write(\"node{}label1{}label2\\n\".format(separator,separator))\n node_feat_f.write(\"node1{}A{}D,A\\n\".format(separator,separator))\n node_feat_f.write(\"node2{}A{}E,C,D\\n\".format(separator,separator))\n node_feat_f.write(\"node3{}C{}F,A,B\\n\".format(separator,separator))\n node_feat_f.write(\"node4{}A{}G,E\\n\".format(separator,separator))\n node_feat_f.close()\n\ndef create_node_valid_labels(tmpdir, file_name, separator='\\t'):\n node_feat_f = open(os.path.join(tmpdir, file_name), \"w\")\n node_feat_f.write(\"node{}label1{}label2\\n\".format(separator,separator))\n node_feat_f.write(\"node5{}A{}D,A\\n\".format(separator,separator))\n node_feat_f.write(\"node6{}C{}E,C,D\\n\".format(separator,separator))\n node_feat_f.close()\n\ndef create_node_test_labels(tmpdir, file_name, separator='\\t'):\n node_feat_f = open(os.path.join(tmpdir, file_name), \"w\")\n node_feat_f.write(\"node{}label1{}label2\\n\".format(separator,separator))\n node_feat_f.write(\"node7{}A{}D,A\\n\".format(separator,separator))\n node_feat_f.write(\"node8{}A{}E,C,D\\n\".format(separator,separator))\n node_feat_f.close()\n\ndef create_edge_labels(tmpdir, file_name, sep='\\t'):\n node_feat_f = open(os.path.join(tmpdir, file_name), \"w\")\n node_feat_f.write(\"node_0{}node_1{}label1{}label2\\n\".format(sep,sep,sep))\n node_feat_f.write(\"node1{}node4{}A{}D,A\\n\".format(sep,sep,sep))\n node_feat_f.write(\"node2{}node3{}A{}E,C,D\\n\".format(sep,sep,sep))\n node_feat_f.write(\"node3{}node2{}C{}F,A,B\\n\".format(sep,sep,sep))\n node_feat_f.write(\"node4{}node1{}A{}G,E\\n\".format(sep,sep,sep))\n node_feat_f.close()\n\ndef create_train_edge_labels(tmpdir, file_name, sep='\\t'):\n node_feat_f = open(os.path.join(tmpdir, file_name), \"w\")\n node_feat_f.write(\"node_0{}node_1{}label1{}label2\\n\".format(sep,sep,sep))\n node_feat_f.write(\"node4{}node2{}A{}D,A\\n\".format(sep,sep,sep))\n node_feat_f.write(\"node3{}node3{}A{}E,C,D\\n\".format(sep,sep,sep))\n node_feat_f.close()\n\ndef create_graph_edges(tmpdir, file_name, sep='\\t'):\n node_feat_f = open(os.path.join(tmpdir, file_name), \"w\")\n node_feat_f.write(\"node_0{}node_1{}rel_1{}rel_2\\n\".format(sep,sep,sep))\n node_feat_f.write(\"node1{}node2{}A{}C\\n\".format(sep,sep,sep))\n node_feat_f.write(\"node2{}node1{}A{}C\\n\".format(sep,sep,sep))\n node_feat_f.write(\"node3{}node1{}A{}C\\n\".format(sep,sep,sep))\n node_feat_f.write(\"node4{}node3{}A{}B\\n\".format(sep,sep,sep))\n node_feat_f.write(\"node4{}node4{}A{}A\\n\".format(sep,sep,sep))\n node_feat_f.close()\n\ndef create_graph_feat_edges(tmpdir, file_name, sep='\\t'):\n node_feat_f = open(os.path.join(tmpdir, file_name), \"w\")\n node_feat_f.write(\"node_0{}node_1{}feat_1\\n\".format(sep,sep))\n node_feat_f.write(\"node1{}node4{}0.1\\n\".format(sep,sep))\n node_feat_f.write(\"node2{}node3{}0.2\\n\".format(sep,sep))\n node_feat_f.write(\"node3{}node2{}0.3\\n\".format(sep,sep))\n node_feat_f.write(\"node4{}node1{}0.4\\n\".format(sep,sep))\n node_feat_f.write(\"node1{}node2{}0.5\\n\".format(sep,sep))\n node_feat_f.write(\"node2{}node1{}0.6\\n\".format(sep,sep))\n node_feat_f.write(\"node3{}node1{}0.7\\n\".format(sep,sep))\n node_feat_f.write(\"node4{}node3{}0.8\\n\".format(sep,sep))\n node_feat_f.write(\"node4{}node4{}0.9\\n\".format(sep,sep))\n node_feat_f.close()\n\ndef create_multiple_label(tmpdir, file_name, sep='\\t'):\n node_feat_f = open(os.path.join(tmpdir, file_name), \"w\")\n node_feat_f.write(\n \"node{}label1{}label2{}label3{}label4{}label5{}node_d{}node_d2{}node_d3\\n\".format(\n sep,sep,sep,sep,sep,sep,sep,sep))\n node_feat_f.write(\"node1{}A{}A{}C{}A,B{}A,C{}node3{}node1{}node4\\n\".format(\n sep,sep,sep,sep,sep,sep,sep,sep))\n node_feat_f.write(\"node2{}B{}B{}B{}A{}B{}node4{}node2{}node5\\n\".format(\n sep,sep,sep,sep,sep,sep,sep,sep))\n node_feat_f.write(\"node3{}C{}C{}A{}C,B{}A{}node5{}node1{}node6\\n\".format(\n sep,sep,sep,sep,sep,sep,sep,sep))\n node_feat_f.write(\"node4{}A{}A{}A{}A,C{}A,B{}node6{}node2{}node7\\n\".format(\n sep,sep,sep,sep,sep,sep,sep,sep))\n node_feat_f.close()\n\n\ndef test_node_category_feature_loader():\n import tempfile\n with tempfile.TemporaryDirectory() as tmpdirname:\n create_category_node_feat(Path(tmpdirname), 'node_category_feat.csv')\n\n feat_loader = dgl_graphloader.NodeFeatureLoader(os.path.join(tmpdirname,\n 'node_category_feat.csv'))\n feat_loader.addCategoryFeature([0, 1], feat_name='tf')\n feat_loader.addCategoryFeature(['node', 'feat1'], norm='row', node_type='node')\n feat_loader.addCategoryFeature(['node', 'feat1'], norm='col', node_type='node')\n f_1 = feat_loader._raw_features[0]\n f_2 = feat_loader._raw_features[1]\n f_3 = feat_loader._raw_features[2]\n assert f_1[0] == 'tf'\n assert f_2[0] == 'nf'\n assert f_3[0] == 'nf'\n assert f_1[1] is None\n assert f_2[1] == 'node'\n assert f_3[1] == 'node'\n assert f_1[2] == f_2[2]\n assert f_1[2] == f_3[2]\n assert np.allclose(np.array([[1,0],[1,0],[0,1],[1,0]]),\n f_1[3])\n assert np.allclose(np.array([[1,0],[1,0],[0,1],[1,0]]),\n f_2[3])\n assert np.allclose(np.array([[1./3.,0],[1./3.,0],[0,1],[1./3.,0]]),\n f_3[3])\n\n feat_loader = dgl_graphloader.NodeFeatureLoader(os.path.join(tmpdirname,\n 'node_category_feat.csv'))\n feat_loader.addCategoryFeature([0, 1, 2])\n feat_loader.addCategoryFeature(['node', 'feat1', 'feat2'], norm='row', node_type='node')\n feat_loader.addCategoryFeature(['node', 'feat1', 'feat2'], norm='col', node_type='node')\n f_1 = feat_loader._raw_features[0]\n f_2 = feat_loader._raw_features[1]\n f_3 = feat_loader._raw_features[2]\n assert f_1[0] == 'nf'\n assert f_2[0] == 'nf'\n assert f_3[0] == 'nf'\n assert f_1[1] is None\n assert f_2[1] == 'node'\n assert f_3[1] == 'node'\n assert f_1[2] == f_2[2]\n assert f_1[2] == f_3[2]\n assert np.allclose(np.array([[1,1,0],[1,0,0],[0,1,1],[1,0,1]]),\n f_1[3])\n assert np.allclose(np.array([[0.5,0.5,0],[1,0,0],[0,0.5,0.5],[0.5,0,0.5]]),\n f_2[3])\n assert np.allclose(np.array([[1./3.,1./2.,0],\n [1./3.,0, 0],\n [0, 1./2.,1./2.],\n [1./3.,0, 1./2.]]),\n f_3[3])\n\n feat_loader = dgl_graphloader.NodeFeatureLoader(os.path.join(tmpdirname,\n 'node_category_feat.csv'))\n feat_loader.addCategoryFeature([0, 1, 2], rows=[0,1,3])\n feat_loader.addCategoryFeature(['node', 'feat1', 'feat2'],\n rows=[0,1,3], norm='row', node_type='node')\n feat_loader.addCategoryFeature(['node', 'feat1', 'feat2'],\n rows=[0,1,3], norm='col', node_type='node')\n f_1 = feat_loader._raw_features[0]\n f_2 = feat_loader._raw_features[1]\n f_3 = feat_loader._raw_features[2]\n assert f_1[1] is None\n assert f_2[1] == 'node'\n assert f_3[1] == 'node'\n assert f_1[2] == f_2[2]\n assert f_1[2] == f_3[2]\n assert np.allclose(np.array([[1,1,0],[1,0,0],[1,0,1]]),\n f_1[3])\n assert np.allclose(np.array([[0.5,0.5,0],[1,0,0],[0.5,0,0.5]]),\n f_2[3])\n assert np.allclose(np.array([[1./3.,1.,0.],\n [1./3.,0.,0.],\n [1./3.,0.,1.]]),\n f_3[3])\n\n\n feat_loader = dgl_graphloader.NodeFeatureLoader(os.path.join(tmpdirname,\n 'node_category_feat.csv'))\n feat_loader.addMultiCategoryFeature([0, 3], separator=',')\n feat_loader.addMultiCategoryFeature(['node', 'feat3'], separator=',', norm='row', node_type='node')\n feat_loader.addMultiCategoryFeature(['node', 'feat3'], separator=',', norm='col', node_type='node')\n f_1 = feat_loader._raw_features[0]\n f_2 = feat_loader._raw_features[1]\n f_3 = feat_loader._raw_features[2]\n assert f_1[1] is None\n assert f_2[1] == 'node'\n assert f_3[1] == 'node'\n assert f_1[2] == f_2[2]\n assert f_1[2] == f_3[2]\n assert np.allclose(np.array([[1,1,0],[1,0,0],[0,1,1],[1,0,1]]),\n f_1[3])\n assert np.allclose(np.array([[0.5,0.5,0],[1,0,0],[0,0.5,0.5],[0.5,0,0.5]]),\n f_2[3])\n assert np.allclose(np.array([[1./3.,1./2.,0],\n [1./3.,0, 0],\n [0, 1./2.,1./2.],\n [1./3.,0, 1./2.]]),\n f_3[3])\n\n feat_loader.addMultiCategoryFeature([0, 3], rows=[0,1,3], separator=',')\n feat_loader.addMultiCategoryFeature(['node', 'feat3'], separator=',',\n rows=[0,1,3], norm='row', node_type='node')\n feat_loader.addMultiCategoryFeature(['node', 'feat3'], separator=',',\n rows=[0,1,3], norm='col', node_type='node')\n f_1 = feat_loader._raw_features[3]\n f_2 = feat_loader._raw_features[4]\n f_3 = feat_loader._raw_features[5]\n assert f_1[1] is None\n assert f_2[1] == 'node'\n assert f_3[1] == 'node'\n assert f_1[2] == f_2[2]\n assert f_1[2] == f_3[2]\n assert np.allclose(np.array([[1,1,0],[1,0,0],[1,0,1]]),\n f_1[3])\n assert np.allclose(np.array([[0.5,0.5,0],[1,0,0],[0.5,0,0.5]]),\n f_2[3])\n assert np.allclose(np.array([[1./3.,1.,0.],\n [1./3.,0.,0.],\n [1./3.,0.,1.]]),\n f_3[3])\n\ndef test_node_numerical_feature_loader():\n import tempfile\n with tempfile.TemporaryDirectory() as tmpdirname:\n create_numerical_node_feat(Path(tmpdirname), 'node_numerical_feat.csv')\n\n feat_loader = dgl_graphloader.NodeFeatureLoader(os.path.join(tmpdirname,\n 'node_numerical_feat.csv'))\n feat_loader.addNumericalFeature([0, 1])\n feat_loader.addNumericalFeature(['node', 'feat1'], norm='standard', node_type='node')\n feat_loader.addNumericalFeature(['node', 'feat1'], norm='min-max', node_type='node')\n f_1 = feat_loader._raw_features[0]\n f_2 = feat_loader._raw_features[1]\n f_3 = feat_loader._raw_features[2]\n assert f_1[0] == 'nf'\n assert f_2[0] == 'nf'\n assert f_3[0] == 'nf'\n assert f_1[1] is None\n assert f_2[1] == 'node'\n assert f_3[1] == 'node'\n assert f_1[2] == f_2[2]\n assert f_1[2] == f_3[2]\n assert np.allclose(np.array([[1.],[2.],[0.],[4.]]),\n f_1[3])\n assert np.allclose(np.array([[1./7.],[2./7.],[0.],[4./7.]]),\n f_2[3])\n assert np.allclose(np.array([[1./4.],[2./4],[0.],[1.]]),\n f_3[3])\n\n feat_loader = dgl_graphloader.NodeFeatureLoader(os.path.join(tmpdirname,\n 'node_numerical_feat.csv'))\n feat_loader.addNumericalFeature([0,1,2,3],feat_name='tf')\n feat_loader.addNumericalFeature(['node', 'feat1','feat2','feat3'],\n norm='standard',\n node_type='node')\n feat_loader.addNumericalFeature(['node', 'feat1','feat2','feat3'],\n norm='min-max',\n node_type='node')\n f_1 = feat_loader._raw_features[0]\n f_2 = feat_loader._raw_features[1]\n f_3 = feat_loader._raw_features[2]\n assert f_1[0] == 'tf'\n assert f_2[0] == 'nf'\n assert f_3[0] == 'nf'\n assert f_1[1] is None\n assert f_2[1] == 'node'\n assert f_3[1] == 'node'\n assert f_1[2] == f_2[2]\n assert f_1[2] == f_3[2]\n assert np.allclose(np.array([[1.,2.,0.],[2.,-1.,0.],[0.,0.,0.],[4.,-2.,0.]]),\n f_1[3])\n assert np.allclose(np.array([[1./7.,2./5.,0.],[2./7.,-1./5.,0.],[0.,0.,0.],[4./7.,-2./5.,0.]]),\n f_2[3])\n assert np.allclose(np.array([[1./4.,1.,0.],[2./4,1./4.,0.],[0.,2./4.,0.],[1.,0.,0.]]),\n f_3[3])\n\n feat_loader.addNumericalFeature([0,1,2,3],rows=[1,2,3])\n feat_loader.addNumericalFeature(['node', 'feat1','feat2','feat3'],\n rows=[1,2,3],\n norm='standard',\n node_type='node')\n feat_loader.addNumericalFeature(['node', 'feat1','feat2','feat3'],\n rows=[1,2,3],\n norm='min-max',\n node_type='node')\n f_1 = feat_loader._raw_features[3]\n f_2 = feat_loader._raw_features[4]\n f_3 = feat_loader._raw_features[5]\n assert f_1[1] is None\n assert f_2[1] == 'node'\n assert f_3[1] == 'node'\n assert f_1[2] == f_2[2]\n assert f_1[2] == f_3[2]\n assert np.allclose(np.array([[2.,-1.,0.],[0.,0.,0.],[4.,-2.,0.]]),\n f_1[3])\n assert np.allclose(np.array([[2./6.,-1./3.,0.],[0.,0.,0.],[4./6.,-2./3.,0.]]),\n f_2[3])\n assert np.allclose(np.array([[2./4.,1./2.,0.],[0.,1.,0.],[1.,0.,0.]]),\n f_3[3])\n\n feat_loader = dgl_graphloader.NodeFeatureLoader(os.path.join(tmpdirname,\n 'node_numerical_feat.csv'))\n feat_loader.addMultiNumericalFeature([0,4], separator=',')\n feat_loader.addMultiNumericalFeature(['node', 'feat4'],\n separator=',',\n norm='standard',\n node_type='node')\n feat_loader.addMultiNumericalFeature(['node', 'feat4'],\n separator=',',\n norm='min-max',\n node_type='node')\n f_1 = feat_loader._raw_features[0]\n f_2 = feat_loader._raw_features[1]\n f_3 = feat_loader._raw_features[2]\n assert f_1[1] is None\n assert f_2[1] == 'node'\n assert f_3[1] == 'node'\n assert f_1[2] == f_2[2]\n assert f_1[2] == f_3[2]\n assert np.allclose(np.array([[1.,2.,0.],[2.,-1.,0.],[0.,0.,0.],[4.,-2.,0.]]),\n f_1[3])\n assert np.allclose(np.array([[1./7.,2./5.,0.],[2./7.,-1./5.,0.],[0.,0.,0.],[4./7.,-2./5.,0.]]),\n f_2[3])\n assert np.allclose(np.array([[1./4.,1.,0.],[2./4,1./4.,0.],[0.,2./4.,0.],[1.,0.,0.]]),\n f_3[3])\n\n feat_loader.addMultiNumericalFeature([0,4], separator=',', rows=[1,2,3])\n feat_loader.addMultiNumericalFeature(['node', 'feat4'],\n separator=',',\n rows=[1,2,3],\n norm='standard',\n node_type='node')\n feat_loader.addMultiNumericalFeature(['node', 'feat4'],\n separator=',',\n rows=[1,2,3],\n norm='min-max',\n node_type='node')\n f_1 = feat_loader._raw_features[3]\n f_2 = feat_loader._raw_features[4]\n f_3 = feat_loader._raw_features[5]\n assert f_1[1] is None\n assert f_2[1] == 'node'\n assert f_3[1] == 'node'\n assert f_1[2] == f_2[2]\n assert f_1[2] == f_3[2]\n assert np.allclose(np.array([[2.,-1.,0.],[0.,0.,0.],[4.,-2.,0.]]),\n f_1[3])\n assert np.allclose(np.array([[2./6.,-1./3.,0.],[0.,0.,0.],[4./6.,-2./3.,0.]]),\n f_2[3])\n assert np.allclose(np.array([[2./4.,1./2.,0.],[0.,1.,0.],[1.,0.,0.]]),\n f_3[3])\n\n with tempfile.TemporaryDirectory() as tmpdirname:\n create_numerical_bucket_node_feat(Path(tmpdirname), 'node_numerical_bucket_feat.csv')\n\n feat_loader = dgl_graphloader.NodeFeatureLoader(os.path.join(tmpdirname,\n 'node_numerical_bucket_feat.csv'))\n feat_loader.addNumericalBucketFeature([0, 2],\n feat_name='tf',\n range=[10,30],\n bucket_cnt=2)\n feat_loader.addNumericalBucketFeature(['node', 'feat2'],\n range=[10,30],\n bucket_cnt=2,\n norm='row', node_type='node')\n feat_loader.addNumericalBucketFeature(['node', 'feat2'],\n range=[10,30],\n bucket_cnt=2,\n norm='col', node_type='node')\n f_1 = feat_loader._raw_features[0]\n f_2 = feat_loader._raw_features[1]\n f_3 = feat_loader._raw_features[2]\n assert f_1[0] == 'tf'\n assert f_2[0] == 'nf'\n assert f_3[0] == 'nf'\n assert f_1[1] is None\n assert f_2[1] == 'node'\n assert f_3[1] == 'node'\n assert f_1[2] == f_2[2]\n assert f_1[2] == f_3[2]\n assert np.allclose(np.array([[1., 0.], [1., 0.], [1., 0.], [0., 1.],\n [1., 0.], [0., 1.], [0., 1.], [0., 1.]]),\n f_1[3])\n assert np.allclose(np.array([[1., 0.], [1., 0.], [1., 0.], [0., 1.],\n [1., 0.], [0., 1.], [0., 1.], [0., 1.]]),\n f_2[3])\n assert np.allclose(np.array([[1./4., 0.], [1./4., 0.], [1./4., 0.], [0., 1./4],\n [1./4., 0.], [0., 1./4.], [0., 1./4.], [0., 1./4.]]),\n f_3[3])\n\n feat_loader.addNumericalBucketFeature([0, 2],\n rows=[0,2,3,4,5,6],\n range=[10,30],\n bucket_cnt=2)\n feat_loader.addNumericalBucketFeature(['node', 'feat2'],\n rows=[0,2,3,4,5,6],\n range=[10,30],\n bucket_cnt=2,\n norm='row', node_type='node')\n feat_loader.addNumericalBucketFeature(['node', 'feat2'],\n rows=[0,2,3,4,5,6],\n range=[10,30],\n bucket_cnt=2,\n norm='col', node_type='node')\n f_1 = feat_loader._raw_features[3]\n f_2 = feat_loader._raw_features[4]\n f_3 = feat_loader._raw_features[5]\n assert f_1[1] is None\n assert f_2[1] == 'node'\n assert f_3[1] == 'node'\n assert f_1[2] == f_2[2]\n assert f_1[2] == f_3[2]\n assert np.allclose(np.array([[1., 0.], [1., 0.], [0., 1.],\n [1., 0.], [0., 1.], [0., 1.]]),\n f_1[3])\n assert np.allclose(np.array([[1., 0.], [1., 0.], [0., 1.],\n [1., 0.], [0., 1.], [0., 1.]]),\n f_2[3])\n assert np.allclose(np.array([[1./3., 0.], [1./3., 0.], [0., 1./3],\n [1./3., 0.], [0., 1./3.], [0., 1./3.]]),\n f_3[3])\n\n feat_loader = dgl_graphloader.NodeFeatureLoader(os.path.join(tmpdirname,\n 'node_numerical_bucket_feat.csv'))\n feat_loader.addNumericalBucketFeature([0, 2],\n feat_name='tf',\n range=[10,30],\n bucket_cnt=4,\n slide_window_size=10.)\n feat_loader.addNumericalBucketFeature(['node', 'feat2'],\n range=[10,30],\n bucket_cnt=4,\n slide_window_size=10.,\n norm='row', node_type='node')\n feat_loader.addNumericalBucketFeature(['node', 'feat2'],\n range=[10,30],\n bucket_cnt=4,\n slide_window_size=10.,\n norm='col', node_type='node')\n f_1 = feat_loader._raw_features[0]\n f_2 = feat_loader._raw_features[1]\n f_3 = feat_loader._raw_features[2]\n assert f_1[0] == 'tf'\n assert f_2[0] == 'nf'\n assert f_3[0] == 'nf'\n assert f_1[1] is None\n assert f_2[1] == 'node'\n assert f_3[1] == 'node'\n assert f_1[2] == f_2[2]\n assert f_1[2] == f_3[2]\n assert np.allclose(np.array([[1., 0., 0., 0],\n [1., 0., 0., 0],\n [1., 1., 1., 0.],\n [0., 1., 1., 1.],\n [1., 1., 0., 0.],\n [0., 0., 1., 1.],\n [0., 0., 0., 1.],\n [0., 0., 0., 1.]]),\n f_1[3])\n assert np.allclose(np.array([[1., 0., 0., 0],\n [1., 0., 0., 0],\n [1./3., 1./3., 1./3., 0.],\n [0., 1./3., 1./3., 1./3.],\n [1./2., 1./2., 0., 0.],\n [0., 0., 1./2., 1./2.],\n [0., 0., 0., 1.],\n [0., 0., 0., 1.]]),\n f_2[3])\n assert np.allclose(np.array([[1./4., 0., 0., 0],\n [1./4., 0., 0., 0],\n [1./4., 1./3., 1./3., 0.],\n [0., 1./3., 1./3., 1./4.],\n [1./4., 1./3., 0., 0.],\n [0., 0., 1./3., 1./4.],\n [0., 0., 0., 1./4.],\n [0., 0., 0., 1./4.]]),\n f_3[3])\n\ndef test_edge_numerical_feature_loader():\n import tempfile\n with tempfile.TemporaryDirectory() as tmpdirname:\n create_numerical_edge_feat(Path(tmpdirname), 'edge_numerical_feat.csv')\n\n feat_loader = dgl_graphloader.EdgeFeatureLoader(os.path.join(tmpdirname,\n 'edge_numerical_feat.csv'))\n feat_loader.addNumericalFeature([0, 1, 2], feat_name='tf')\n feat_loader.addNumericalFeature(['node_s', 'node_d', 'feat1'],\n norm='standard',\n edge_type=('src', 'rel', 'dst'))\n feat_loader.addNumericalFeature(['node_d', 'node_s', 'feat1'],\n norm='min-max',\n edge_type=('dst', 'rev-rel', 'src'))\n f_1 = feat_loader._raw_features[0]\n f_2 = feat_loader._raw_features[1]\n f_3 = feat_loader._raw_features[2]\n assert f_1[0] == 'tf'\n assert f_2[0] == 'ef'\n assert f_3[0] == 'ef'\n assert f_1[1] is None\n assert f_2[1] == ('src', 'rel', 'dst')\n assert f_3[1] == ('dst', 'rev-rel', 'src')\n assert f_1[2] == f_2[2]\n assert f_1[2] == ['node1','node2','node3','node3']\n assert f_3[2] == ['node4','node5','node6','node3']\n assert f_1[3] == f_2[3]\n assert f_1[3] == ['node4','node5','node6','node3']\n assert f_3[3] == ['node1','node2','node3','node3']\n assert np.allclose(np.array([[1.],[2.],[0.],[4.]]),\n f_1[4])\n assert np.allclose(np.array([[1./7.],[2./7.],[0.],[4./7.]]),\n f_2[4])\n assert np.allclose(np.array([[1./4.],[2./4],[0.],[1.]]),\n f_3[4])\n feat_loader.addNumericalFeature(['node_s', 'node_d', 'feat1'],\n rows=[1,2,3],\n norm='standard',\n edge_type=('src', 'rel', 'dst'))\n feat_loader.addNumericalFeature(['node_d', 'node_s', 'feat1'],\n rows=[1,2,3],\n norm='min-max',\n edge_type=('dst', 'rev-rel', 'src'))\n f_1 = feat_loader._raw_features[3]\n f_2 = feat_loader._raw_features[4]\n assert f_1[1] == ('src', 'rel', 'dst')\n assert f_2[1] == ('dst', 'rev-rel', 'src')\n assert f_1[2] == ['node2','node3','node3']\n assert f_2[2] == ['node5','node6','node3']\n assert f_1[3] == ['node5','node6','node3']\n assert f_2[3] == ['node2','node3','node3']\n assert np.allclose(np.array([[2./6.],[0.],[4./6.]]),\n f_1[4])\n assert np.allclose(np.array([[2./4],[0.],[1.]]),\n f_2[4])\n\ndef test_node_word2vec_feature_loader():\n import tempfile\n import spacy\n with tempfile.TemporaryDirectory() as tmpdirname:\n create_word_node_feat(Path(tmpdirname), 'node_word_feat.csv')\n\n feat_loader = dgl_graphloader.NodeFeatureLoader(os.path.join(tmpdirname,\n 'node_word_feat.csv'))\n feat_loader.addWord2VecFeature([0, 1], languages=['en_core_web_lg'], feat_name='tf')\n feat_loader.addWord2VecFeature(['node', 'feat1'],\n languages=['en_core_web_lg'],\n node_type='node')\n feat_loader.addWord2VecFeature(['node', 'feat1'],\n languages=['en_core_web_lg'],\n node_type='node')\n f_1 = feat_loader._raw_features[0]\n f_2 = feat_loader._raw_features[1]\n f_3 = feat_loader._raw_features[2]\n assert f_1[0] == 'tf'\n assert f_2[0] == 'nf'\n assert f_3[0] == 'nf'\n assert f_1[1] is None\n assert f_2[1] == 'node'\n assert f_3[1] == 'node'\n assert f_1[2] == f_2[2]\n assert f_1[2] == f_3[2]\n assert np.allclose(f_1[3], f_2[3])\n assert np.allclose(f_1[3], f_3[3])\n nlp = spacy.load('en_core_web_lg')\n assert np.allclose(np.array([nlp(\"A\").vector,\n nlp(\"A\").vector,\n nlp(\"C\").vector,\n nlp(\"A\").vector]),\n f_1[3])\n\n feat_loader.addWord2VecFeature([0, 3], languages=['en_core_web_lg', 'fr_core_news_lg'])\n feat_loader.addWord2VecFeature(['node', 'feat3'],\n languages=['en_core_web_lg', 'fr_core_news_lg'],\n node_type='node')\n feat_loader.addWord2VecFeature(['node', 'feat3'],\n languages=['en_core_web_lg', 'fr_core_news_lg'],\n node_type='node')\n f_1 = feat_loader._raw_features[3]\n f_2 = feat_loader._raw_features[4]\n f_3 = feat_loader._raw_features[5]\n assert f_1[1] is None\n assert f_2[1] == 'node'\n assert f_3[1] == 'node'\n assert f_1[2] == f_2[2]\n assert f_1[2] == f_3[2]\n assert np.allclose(f_1[3], f_2[3])\n assert np.allclose(f_1[3], f_3[3])\n nlp1 = spacy.load('fr_core_news_lg')\n assert np.allclose(np.array([np.concatenate((nlp(\"24\").vector, nlp1(\"24\").vector)),\n np.concatenate((nlp(\"1\").vector, nlp1(\"1\").vector)),\n np.concatenate((nlp(\"12\").vector, nlp1(\"12\").vector)),\n np.concatenate((nlp(\"13\").vector, nlp1(\"13\").vector))]),\n f_1[3])\n\n feat_loader = dgl_graphloader.NodeFeatureLoader(os.path.join(tmpdirname,\n 'node_word_feat.csv'))\n feat_loader.addWord2VecFeature([0, 3],\n rows=[1,2],\n languages=['en_core_web_lg', 'fr_core_news_lg'])\n feat_loader.addWord2VecFeature(['node', 'feat3'],\n rows=[1,2],\n languages=['en_core_web_lg', 'fr_core_news_lg'],\n node_type='node')\n feat_loader.addWord2VecFeature(['node', 'feat3'],\n rows=[1,2],\n languages=['en_core_web_lg', 'fr_core_news_lg'],\n node_type='node')\n f_1 = feat_loader._raw_features[0]\n f_2 = feat_loader._raw_features[1]\n f_3 = feat_loader._raw_features[2]\n assert f_1[1] is None\n assert f_2[1] == 'node'\n assert f_3[1] == 'node'\n assert f_1[2] == f_2[2]\n assert f_1[2] == f_3[2]\n assert np.allclose(f_1[3], f_2[3])\n assert np.allclose(f_1[3], f_3[3])\n nlp1 = spacy.load('fr_core_news_lg')\n assert np.allclose(np.array([np.concatenate((nlp(\"1\").vector, nlp1(\"1\").vector)),\n np.concatenate((nlp(\"12\").vector, nlp1(\"12\").vector))]),\n f_1[3])\n\ndef test_node_label_loader():\n import tempfile\n with tempfile.TemporaryDirectory() as tmpdirname:\n create_node_labels(Path(tmpdirname), 'labels.csv')\n label_loader = dgl_graphloader.NodeLabelLoader(os.path.join(tmpdirname,\n 'labels.csv'))\n label_loader.addTrainSet([0,1])\n label_loader.addValidSet(['node','label1'], node_type='node')\n label_loader.addTestSet(['node','label1'], rows=[0,2], node_type='node')\n label_loader.addSet(['node','label1'], [0.5, 0.25, 0.25], rows=[0,1,2,3], node_type='nt')\n l_1 = label_loader._labels[0]\n l_2 = label_loader._labels[1]\n l_3 = label_loader._labels[2]\n l_4 = label_loader._labels[3]\n assert l_1[0] == None\n assert l_2[0] == 'node'\n assert l_3[0] == 'node'\n assert l_4[0] == 'nt'\n assert l_1[1] == l_2[1]\n assert l_1[1] == ['node1', 'node2', 'node3', 'node4']\n assert l_3[1] == ['node1', 'node3']\n assert l_4[1] == l_1[1]\n assert l_1[2] == l_2[2]\n assert l_1[2] == ['A','A','C','A']\n assert l_3[2] == ['A','C']\n assert l_4[2] == l_1[2]\n assert l_1[3] == (1., 0., 0.)\n assert l_2[3] == (0., 1., 0.)\n assert l_3[3] == (0., 0., 1.)\n assert l_4[3] == (0.5, 0.25, 0.25)\n\n label_loader = dgl_graphloader.NodeLabelLoader(os.path.join(tmpdirname,\n 'labels.csv'))\n label_loader.addTrainSet([0,2], multilabel=True, separator=',')\n label_loader.addValidSet(['node','label2'],\n multilabel=True,\n separator=',',\n node_type='node')\n label_loader.addTestSet(['node','label2'],\n multilabel=True,\n separator=',',\n rows=[0,2],\n node_type='node')\n label_loader.addSet(['node','label2'],\n [0.5, 0.25, 0.25],\n multilabel=True,\n separator=',', rows=[0,1,2,3], node_type='nt')\n l_1 = label_loader._labels[0]\n l_2 = label_loader._labels[1]\n l_3 = label_loader._labels[2]\n l_4 = label_loader._labels[3]\n assert l_1[0] == None\n assert l_2[0] == 'node'\n assert l_3[0] == 'node'\n assert l_4[0] == 'nt'\n assert l_1[1] == l_2[1]\n assert l_1[1] == ['node1', 'node2', 'node3', 'node4']\n assert l_3[1] == ['node1', 'node3']\n assert l_4[1] == l_1[1]\n assert l_1[2] == l_2[2]\n assert l_1[2] == [['D','A'],['E','C','D'],['F','A','B'],['G','E']]\n assert l_3[2] == [['D','A'],['F','A','B']]\n assert l_4[2] == l_1[2]\n assert l_1[3] == (1., 0., 0.)\n assert l_2[3] == (0., 1., 0.)\n assert l_3[3] == (0., 0., 1.)\n assert l_4[3] == (0.5, 0.25, 0.25)\n\n # check warning\n label_loader.addSet(['node','label2'],\n [0.51, 0.25, 0.25],\n multilabel=True,\n separator=',', rows=[0,1,2,3], node_type='nt')\n\ndef test_edge_label_loader():\n import tempfile\n with tempfile.TemporaryDirectory() as tmpdirname:\n create_edge_labels(Path(tmpdirname), 'edge_labels.csv')\n label_loader = dgl_graphloader.EdgeLabelLoader(os.path.join(tmpdirname,\n 'edge_labels.csv'))\n label_loader.addTrainSet([0,1,2])\n label_loader.addValidSet(['node_0','node_1','label1'],\n edge_type=('src','rel','dst'))\n label_loader.addTestSet(['node_0','node_1','label1'],\n rows=[0,2],\n edge_type=('src','rel','dst'))\n label_loader.addSet(['node_0','node_1','label1'],\n [0.5, 0.25, 0.25],\n rows=[0,1,2,3],\n edge_type=('src_n','rel_r','dst_n'))\n l_1 = label_loader._labels[0]\n l_2 = label_loader._labels[1]\n l_3 = label_loader._labels[2]\n l_4 = label_loader._labels[3]\n assert l_1[0] == None\n assert l_2[0] == ('src','rel','dst')\n assert l_3[0] == ('src','rel','dst')\n assert l_4[0] == ('src_n','rel_r','dst_n')\n assert l_1[1] == l_2[1]\n assert l_1[1] == ['node1', 'node2', 'node3', 'node4']\n assert l_3[1] == ['node1', 'node3']\n assert l_4[1] == l_1[1]\n assert l_1[2] == l_2[2]\n assert l_1[2] == ['node4', 'node3', 'node2', 'node1']\n assert l_3[2] == ['node4', 'node2']\n assert l_4[2] == l_1[2]\n assert l_1[3] == l_2[3]\n assert l_1[3] == ['A','A','C','A']\n assert l_3[3] == ['A','C']\n assert l_4[3] == l_1[3]\n assert l_1[4] == (1., 0., 0.)\n assert l_2[4] == (0., 1., 0.)\n assert l_3[4] == (0., 0., 1.)\n assert l_4[4] == (0.5, 0.25, 0.25)\n\n label_loader = dgl_graphloader.EdgeLabelLoader(os.path.join(tmpdirname,\n 'edge_labels.csv'))\n label_loader.addTrainSet([0,1,3], multilabel=True, separator=',')\n label_loader.addValidSet(['node_0','node_1','label2'],\n multilabel=True,\n separator=',',\n edge_type=('src','rel','dst'))\n label_loader.addTestSet(['node_0','node_1','label2'],\n multilabel=True,\n separator=',',\n rows=[0,2],\n edge_type=('src','rel','dst'))\n label_loader.addSet(['node_0','node_1','label2'],\n [0.5, 0.25, 0.25],\n multilabel=True,\n separator=',',\n rows=[0,1,2,3],\n edge_type=('src_n','rel_r','dst_n'))\n l_1 = label_loader._labels[0]\n l_2 = label_loader._labels[1]\n l_3 = label_loader._labels[2]\n l_4 = label_loader._labels[3]\n assert l_1[0] == None\n assert l_2[0] == ('src','rel','dst')\n assert l_3[0] == ('src','rel','dst')\n assert l_4[0] == ('src_n','rel_r','dst_n')\n assert l_1[1] == l_2[1]\n assert l_1[1] == ['node1', 'node2', 'node3', 'node4']\n assert l_3[1] == ['node1', 'node3']\n assert l_4[1] == l_1[1]\n assert l_1[2] == l_2[2]\n assert l_1[2] == ['node4', 'node3', 'node2', 'node1']\n assert l_3[2] == ['node4', 'node2']\n assert l_4[2] == l_1[2]\n assert l_1[3] == l_2[3]\n assert l_1[3] == [['D','A'],['E','C','D'],['F','A','B'],['G','E']]\n assert l_3[3] == [['D','A'],['F','A','B']]\n assert l_4[3] == l_1[3]\n assert l_1[4] == (1., 0., 0.)\n assert l_2[4] == (0., 1., 0.)\n assert l_3[4] == (0., 0., 1.)\n assert l_4[4] == (0.5, 0.25, 0.25)\n\n # check warning\n label_loader.addSet(['node_0','node_1','label2'],\n [0.5, 0.25, 0.26],\n multilabel=True,\n separator=',',\n rows=[0,1,2,3],\n edge_type=('src_n','rel_r','dst_n'))\n\ndef test_edge_loader():\n import tempfile\n with tempfile.TemporaryDirectory() as tmpdirname:\n create_graph_edges(Path(tmpdirname), 'graphs.csv')\n edge_loader = dgl_graphloader.EdgeLoader(os.path.join(tmpdirname,\n 'graphs.csv'))\n edge_loader.addEdges([0,1])\n edge_loader.addEdges(['node_0','node_1'])\n edge_loader.addEdges(['node_0','node_1'],\n rows=np.array([1,2,3,4]),\n edge_type=('src', 'edge', 'dst'))\n e_1 = edge_loader._edges[0]\n e_2 = edge_loader._edges[1]\n e_3 = edge_loader._edges[2]\n assert e_1[0] == None\n assert e_2[0] == None\n assert e_3[0] == ('src','edge','dst')\n assert e_1[1] == e_2[1]\n assert e_1[1] == ['node1', 'node2', 'node3', 'node4', 'node4']\n assert e_3[1] == ['node2', 'node3', 'node4', 'node4']\n assert e_1[2] == e_2[2]\n assert e_1[2] == ['node2', 'node1', 'node1', 'node3', 'node4']\n assert e_3[2] == ['node1', 'node1', 'node3', 'node4']\n\n edge_loader = dgl_graphloader.EdgeLoader(os.path.join(tmpdirname,\n 'graphs.csv'))\n edge_loader.addCategoryRelationEdge([0,1,2],\n src_type='src_t',\n dst_type='dst_t')\n edge_loader.addCategoryRelationEdge(['node_0','node_1','rel_1'],\n src_type='src_t',\n dst_type='dst_t')\n edge_loader.addCategoryRelationEdge(['node_0','node_1','rel_1'],\n rows=np.array([1,2,3,4]),\n src_type='src',\n dst_type='dst')\n e_1 = edge_loader._edges[0]\n e_2 = edge_loader._edges[1]\n e_3 = edge_loader._edges[2]\n assert e_1[0] == ('src_t','A','dst_t')\n assert e_2[0] == ('src_t','A','dst_t')\n assert e_3[0] == ('src','A','dst')\n assert e_1[1] == e_2[1]\n assert e_1[1] == ['node1', 'node2', 'node3', 'node4', 'node4']\n assert e_3[1] == ['node2', 'node3', 'node4', 'node4']\n assert e_1[2] == e_2[2]\n assert e_1[2] == ['node2', 'node1', 'node1', 'node3', 'node4']\n assert e_3[2] == ['node1', 'node1', 'node3', 'node4']\n\n edge_loader = dgl_graphloader.EdgeLoader(os.path.join(tmpdirname,\n 'graphs.csv'))\n edge_loader.addCategoryRelationEdge([0,1,3],\n src_type='src_t',\n dst_type='dst_t')\n edge_loader.addCategoryRelationEdge(['node_0','node_1','rel_2'],\n src_type='src_t',\n dst_type='dst_t')\n edge_loader.addCategoryRelationEdge(['node_0','node_1','rel_2'],\n rows=np.array([1,2,3,4]),\n src_type='src',\n dst_type='dst')\n e_1 = edge_loader._edges[0]\n e_2 = edge_loader._edges[1]\n e_3 = edge_loader._edges[2]\n assert e_1[0] == ('src_t','C','dst_t')\n assert e_2[0] == ('src_t','B','dst_t')\n assert e_3[0] == ('src_t','A','dst_t')\n e_4 = edge_loader._edges[3]\n e_5 = edge_loader._edges[4]\n e_6 = edge_loader._edges[5]\n assert e_4[0] == ('src_t','C','dst_t')\n assert e_5[0] == ('src_t','B','dst_t')\n assert e_6[0] == ('src_t','A','dst_t')\n assert e_1[1] == e_4[1]\n assert e_2[1] == e_5[1]\n assert e_3[1] == e_6[1]\n assert e_1[1] == ['node1', 'node2', 'node3']\n assert e_2[1] == ['node4']\n assert e_3[1] == ['node4']\n assert e_1[2] == e_4[2]\n assert e_2[2] == e_5[2]\n assert e_3[2] == e_6[2]\n assert e_1[2] == ['node2', 'node1', 'node1']\n assert e_2[2] == ['node3']\n assert e_3[2] == ['node4']\n e_7 = edge_loader._edges[6]\n e_8 = edge_loader._edges[7]\n e_9 = edge_loader._edges[8]\n assert e_7[0] == ('src','C','dst')\n assert e_8[0] == ('src','B','dst')\n assert e_9[0] == ('src','A','dst')\n assert e_7[1] == ['node2', 'node3']\n assert e_8[1] == ['node4']\n assert e_9[1] == ['node4']\n assert e_7[2] == ['node1', 'node1']\n assert e_8[2] == ['node3']\n assert e_9[2] == ['node4']\n\ndef test_node_feature_process():\n import tempfile\n with tempfile.TemporaryDirectory() as tmpdirname:\n create_multiple_node_feat(Path(tmpdirname), 'node_feat.csv')\n\n feat_loader = dgl_graphloader.NodeFeatureLoader(os.path.join(tmpdirname,\n 'node_feat.csv'))\n feat_loader.addNumericalFeature([0,2],norm='standard')\n feat_loader.addCategoryFeature([0,1])\n feat_loader.addMultiCategoryFeature([0,3], separator=',')\n\n node_dicts = {}\n result = feat_loader.process(node_dicts)\n assert len(result) == 1\n nids, feats = result[None]['nf']\n assert np.allclose(np.array([0,1,2,3]), nids)\n assert np.allclose(np.concatenate([np.array([[0.1/1.7],[0.3/1.7],[0.2/1.7],[-1.1/1.7]]),\n np.array([[1.,0.],[1.,0.],[0.,1.],[1.,0.]]),\n np.array([[1.,1.,0.],[1.,0.,0.],[0.,1.,1.],[1.,0.,1.]])],\n axis=1),\n feats)\n assert node_dicts[None]['node1'] == 0\n assert node_dicts[None]['node2'] == 1\n assert node_dicts[None]['node3'] == 2\n assert node_dicts[None]['node4'] == 3\n node_dicts = {None: {'node1':3,\n 'node2':2,\n 'node3':1,\n 'node4':0}}\n result = feat_loader.process(node_dicts)\n nids, feats = result[None]['nf']\n assert np.allclose(np.array([3,2,1,0]), nids)\n assert np.allclose(np.concatenate([np.array([[0.1/1.7],[0.3/1.7],[0.2/1.7],[-1.1/1.7]]),\n np.array([[1.,0.],[1.,0.],[0.,1.],[1.,0.]]),\n np.array([[1.,1.,0.],[1.,0.,0.],[0.,1.,1.],[1.,0.,1.]])],\n axis=1),\n feats)\n\n feat_loader = dgl_graphloader.NodeFeatureLoader(os.path.join(tmpdirname,\n 'node_feat.csv'))\n feat_loader.addCategoryFeature(['node','feat1'], node_type='n1')\n feat_loader.addMultiCategoryFeature(['node','feat3'], separator=',', node_type='n1')\n feat_loader.addNumericalFeature(['node','feat2'], norm='standard', node_type='n2')\n node_dicts = {'n2':{'node1':3,\n 'node2':2,\n 'node3':1,\n 'node4':0}}\n result = feat_loader.process(node_dicts)\n assert len(result) == 2\n assert len(node_dicts) == 2\n nids, feats = result['n1']['nf']\n assert np.allclose(np.array([0,1,2,3]), nids)\n assert np.allclose(np.concatenate([np.array([[1.,0.],[1.,0.],[0.,1.],[1.,0.]]),\n np.array([[1.,1.,0.],[1.,0.,0.],[0.,1.,1.],[1.,0.,1.]])],\n axis=1),\n feats)\n nids, feats = result['n2']['nf']\n assert np.allclose(np.array([3,2,1,0]), nids)\n assert np.allclose(np.array([[0.1/1.7],[0.3/1.7],[0.2/1.7],[-1.1/1.7]]),\n feats)\n\ndef test_edge_feature_process():\n import tempfile\n with tempfile.TemporaryDirectory() as tmpdirname:\n create_multiple_edge_feat(Path(tmpdirname), 'edge_feat.csv')\n\n feat_loader = dgl_graphloader.EdgeFeatureLoader(os.path.join(tmpdirname,\n 'edge_feat.csv'))\n feat_loader.addNumericalFeature([0,1,2],norm='standard')\n feat_loader.addNumericalFeature([0,1,3],norm='min-max')\n feat_loader.addNumericalFeature([0,1,4])\n node_dicts = {}\n result = feat_loader.process(node_dicts)\n assert len(result) == 1\n snids, dnids, feats = result[None]['ef']\n assert np.allclose(np.array([0,1,2,3]), snids)\n assert np.allclose(np.array([4,5,6,7]), dnids)\n assert np.allclose(np.concatenate([np.array([[0.2/1.0],[-0.3/1.0],[0.3/1.0],[-0.2/1.0]]),\n np.array([[1.2/1.4],[1.0],[1.3/1.4],[0.]]),\n np.array([[1.1],[1.2],[-1.2],[0.9]])],\n axis=1),\n feats)\n assert node_dicts[None]['node1'] == 0\n assert node_dicts[None]['node2'] == 1\n assert node_dicts[None]['node3'] == 2\n assert node_dicts[None]['node4'] == 3\n node_dicts = {None: {'node1':3,\n 'node2':2,\n 'node3':1,\n 'node4':0}}\n result = feat_loader.process(node_dicts)\n snids, dnids, feats = result[None]['ef']\n assert np.allclose(np.array([3,2,1,0]), snids)\n assert np.allclose(np.array([4,5,6,7]), dnids)\n assert np.allclose(np.concatenate([np.array([[0.2/1.0],[-0.3/1.0],[0.3/1.0],[-0.2/1.0]]),\n np.array([[1.2/1.4],[1.0],[1.3/1.4],[0.]]),\n np.array([[1.1],[1.2],[-1.2],[0.9]])],\n axis=1),\n feats)\n\n feat_loader = dgl_graphloader.EdgeFeatureLoader(os.path.join(tmpdirname,\n 'edge_feat.csv'))\n feat_loader.addNumericalFeature([0,1,2],norm='standard',edge_type=('n0','r0','n1'))\n feat_loader.addNumericalFeature([0,1,3],norm='min-max',edge_type=('n0','r0','n1'))\n feat_loader.addNumericalFeature([0,1,4],edge_type=('n1','r1','n0'))\n node_dicts = {'n0':{'node1':3,\n 'node2':2,\n 'node3':1,\n 'node4':0}}\n result = feat_loader.process(node_dicts)\n assert len(result) == 2\n snids, dnids, feats = result[('n0','r0','n1')]['ef']\n assert np.allclose(np.array([3,2,1,0]), snids)\n assert np.allclose(np.array([0,1,2,3]), dnids)\n assert np.allclose(np.concatenate([np.array([[0.2/1.0],[-0.3/1.0],[0.3/1.0],[-0.2/1.0]]),\n np.array([[1.2/1.4],[1.0],[1.3/1.4],[0.]])],\n axis=1),\n feats)\n snids, dnids, feats = result[('n1','r1','n0')]['ef']\n assert np.allclose(np.array([4,5,6,7]), snids)\n assert np.allclose(np.array([4,5,6,7]), dnids)\n assert np.allclose(np.array([[1.1],[1.2],[-1.2],[0.9]]),\n feats)\n\ndef test_node_label_process():\n import tempfile\n with tempfile.TemporaryDirectory() as tmpdirname:\n create_multiple_label(Path(tmpdirname), 'node_label.csv')\n\n label_loader = dgl_graphloader.NodeLabelLoader(os.path.join(tmpdirname,\n 'node_label.csv'))\n label_loader.addTrainSet([0,1])\n node_dicts = {}\n result = label_loader.process(node_dicts)\n assert len(result) == 1\n train_nids, train_labels, valid_nids, valid_labels, test_nids, test_labels = result[None]\n assert np.array_equal(np.array([0,1,2,3]), train_nids)\n assert valid_nids is None\n assert test_nids is None\n assert np.array_equal(np.array([[1,0,0],[0,1,0],[0,0,1],[1,0,0]]), train_labels)\n assert valid_labels is None\n assert test_labels is None\n label_loader.addValidSet([0,2])\n label_loader.addTestSet([0,3])\n node_dicts = {}\n result = label_loader.process(node_dicts)\n train_nids, train_labels, valid_nids, valid_labels, test_nids, test_labels = result[None]\n assert np.array_equal(np.array([0,1,2,3]), train_nids)\n assert np.array_equal(np.array([0,1,2,3]), valid_nids)\n assert np.array_equal(np.array([0,1,2,3]), test_nids)\n assert np.array_equal(np.array([[1,0,0],[0,1,0],[0,0,1],[1,0,0]]), train_labels)\n assert np.array_equal(np.array([[1,0,0],[0,1,0],[0,0,1],[1,0,0]]), valid_labels)\n assert np.array_equal(np.array([[0,0,1],[0,1,0],[1,0,0],[1,0,0]]), test_labels)\n\n # test with node type\n label_loader = dgl_graphloader.NodeLabelLoader(os.path.join(tmpdirname,\n 'node_label.csv'))\n label_loader.addTrainSet([0,1], node_type='n1')\n node_dicts = {'n1':{'node1':3,\n 'node2':2,\n 'node3':1,\n 'node4':0}}\n label_loader.addValidSet([0,2], rows=[1,2,3], node_type='n1')\n label_loader.addTestSet([0,3], rows=[0,1,2], node_type='n1')\n result = label_loader.process(node_dicts)\n assert len(result) == 1\n assert 'n1' in result\n train_nids, train_labels, valid_nids, valid_labels, test_nids, test_labels = result['n1']\n assert np.array_equal(np.array([3,2,1,0]), train_nids)\n assert np.array_equal(np.array([2,1,0]), valid_nids)\n assert np.array_equal(np.array([3,2,1]), test_nids)\n assert np.array_equal(np.array([[1,0,0],[0,1,0],[0,0,1],[1,0,0]]), train_labels)\n assert np.array_equal(np.array([[0,1,0],[0,0,1],[1,0,0]]), valid_labels)\n assert np.array_equal(np.array([[0,0,1],[0,1,0],[1,0,0]]), test_labels)\n\n # test multilabel\n # test with node type\n label_loader = dgl_graphloader.NodeLabelLoader(os.path.join(tmpdirname,\n 'node_label.csv'))\n label_loader.addTrainSet(['node','label4'],\n multilabel=True,\n separator=',',\n node_type='n1')\n label_loader.addSet(['node', 'label5'],\n split_rate=[0.,0.5,0.5],\n multilabel=True,\n separator=',',\n node_type='n1')\n node_dicts = {'n1':{'node1':3,\n 'node2':2,\n 'node3':1,\n 'node4':0}}\n np.random.seed(0)\n result = label_loader.process(node_dicts)\n assert len(result) == 1\n assert 'n1' in result\n train_nids, train_labels, valid_nids, valid_labels, test_nids, test_labels = result['n1']\n label_map = label_loader.label_map\n rev_map = {val:key for key,val in label_map['n1'].items()}\n vl_truth = np.zeros((2,3),dtype='int32')\n vl_truth[0][rev_map['A']] = 1\n vl_truth[1][rev_map['A']] = 1\n vl_truth[1][rev_map['B']] = 1\n tl_truth = np.zeros((2,3),dtype='int32')\n tl_truth[0][rev_map['B']] = 1\n tl_truth[1][rev_map['A']] = 1\n tl_truth[1][rev_map['C']] = 1\n assert np.array_equal(np.array([3,2,1,0]), train_nids)\n assert np.array_equal(np.array([1,0]), valid_nids)\n assert np.array_equal(np.array([2,3]), test_nids)\n assert np.array_equal(np.array([[1,1,0],[1,0,0],[0,1,1],[1,0,1]]), train_labels)\n assert np.array_equal(vl_truth, valid_labels)\n assert np.array_equal(tl_truth, test_labels)\n\ndef test_edge_label_process():\n import tempfile\n with tempfile.TemporaryDirectory() as tmpdirname:\n create_multiple_label(Path(tmpdirname), 'edge_label.csv')\n\n label_loader = dgl_graphloader.EdgeLabelLoader(os.path.join(tmpdirname,\n 'edge_label.csv'))\n # only existence of the edge\n label_loader.addTrainSet([0,6])\n node_dicts = {}\n result = label_loader.process(node_dicts)\n assert len(result) == 1\n train_snids, train_dnids, train_labels, \\\n valid_snids, valid_dnids, valid_labels, \\\n test_snids, test_dnids, test_labels = result[None]\n assert np.array_equal(np.array([0,1,2,3]), train_snids)\n assert np.array_equal(np.array([2,3,4,5]), train_dnids)\n assert valid_snids is None\n assert valid_dnids is None\n assert test_snids is None\n assert test_dnids is None\n assert train_labels is None\n assert valid_labels is None\n assert test_labels is None\n label_loader.addValidSet([0,7])\n label_loader.addTestSet([6,8])\n node_dicts = {}\n result = label_loader.process(node_dicts)\n assert len(result) == 1\n train_snids, train_dnids, train_labels, \\\n valid_snids, valid_dnids, valid_labels, \\\n test_snids, test_dnids, test_labels = result[None]\n assert np.array_equal(np.array([0,1,2,3]), train_snids)\n assert np.array_equal(np.array([2,3,4,5]), train_dnids)\n assert np.array_equal(np.array([0,1,2,3]), valid_snids)\n assert np.array_equal(np.array([0,1,0,1]), valid_dnids)\n assert np.array_equal(np.array([2,3,4,5]), test_snids)\n assert np.array_equal(np.array([3,4,5,6]), test_dnids)\n\n # with labels\n label_loader = dgl_graphloader.EdgeLabelLoader(os.path.join(tmpdirname,\n 'edge_label.csv'))\n label_loader.addTrainSet([0,6,1], edge_type=('n1', 'like', 'n1'))\n node_dicts = {'n1':{'node1':3,\n 'node2':2,\n 'node3':1,\n 'node4':0}}\n label_loader.addValidSet(['node', 'node_d2', 'label2'], rows=[1,2,3], edge_type=('n1', 'like', 'n1'))\n label_loader.addTestSet(['node_d', 'node_d3', 'label3'], rows=[0,1,2], edge_type=('n1', 'like', 'n1'))\n result = label_loader.process(node_dicts)\n assert len(result) == 1\n assert ('n1', 'like', 'n1') in result\n train_snids, train_dnids, train_labels, \\\n valid_snids, valid_dnids, valid_labels, \\\n test_snids, test_dnids, test_labels = result[('n1', 'like', 'n1')]\n assert np.array_equal(np.array([3,2,1,0]), train_snids)\n assert np.array_equal(np.array([1,0,4,5]), train_dnids)\n assert np.array_equal(np.array([2,1,0]), valid_snids)\n assert np.array_equal(np.array([2,3,2]), valid_dnids)\n assert np.array_equal(np.array([1,0,4]), test_snids)\n assert np.array_equal(np.array([0,4,5]), test_dnids)\n assert np.array_equal(np.array([[1,0,0],[0,1,0],[0,0,1],[1,0,0]]), train_labels)\n assert np.array_equal(np.array([[0,1,0],[0,0,1],[1,0,0]]), valid_labels)\n assert np.array_equal(np.array([[0,0,1],[0,1,0],[1,0,0]]), test_labels)\n\n # with multiple labels\n label_loader = dgl_graphloader.EdgeLabelLoader(os.path.join(tmpdirname,\n 'edge_label.csv'))\n label_loader.addTrainSet(['node','node_d','label4'],\n multilabel=True,\n separator=',',\n edge_type=('n1', 'like', 'n2'))\n node_dicts = {'n1':{'node1':3,\n 'node2':2,\n 'node3':1,\n 'node4':0}}\n label_loader.addSet(['node_d2', 'node_d3', 'label5'],\n split_rate=[0.,0.5,0.5],\n multilabel=True,\n separator=',',\n edge_type=('n1', 'like', 'n2'))\n np.random.seed(0)\n result = label_loader.process(node_dicts)\n assert len(result) == 1\n assert ('n1', 'like', 'n2') in result\n train_snids, train_dnids, train_labels, \\\n valid_snids, valid_dnids, valid_labels, \\\n test_snids, test_dnids, test_labels = result[('n1', 'like', 'n2')]\n label_map = label_loader.label_map\n rev_map = {val:key for key,val in label_map[('n1', 'like', 'n2')].items()}\n vl_truth = np.zeros((2,3),dtype='int32')\n vl_truth[0][rev_map['A']] = 1\n vl_truth[1][rev_map['A']] = 1\n vl_truth[1][rev_map['B']] = 1\n tl_truth = np.zeros((2,3),dtype='int32')\n tl_truth[0][rev_map['B']] = 1\n tl_truth[1][rev_map['A']] = 1\n tl_truth[1][rev_map['C']] = 1\n assert np.array_equal(np.array([3,2,1,0]), train_snids)\n assert np.array_equal(np.array([0,1,2,3]), train_dnids)\n assert np.array_equal(np.array([3,2]), valid_snids)\n assert np.array_equal(np.array([3,4]), valid_dnids)\n assert np.array_equal(np.array([2,3]), test_snids)\n assert np.array_equal(np.array([2,1]), test_dnids)\n assert np.array_equal(np.array([[1,1,0],[1,0,0],[0,1,1],[1,0,1]]), train_labels)\n assert np.array_equal(vl_truth, valid_labels)\n assert np.array_equal(tl_truth, test_labels)\n\ndef test_relation_edge_label_process():\n import tempfile\n with tempfile.TemporaryDirectory() as tmpdirname:\n create_graph_edges(Path(tmpdirname), 'edge_label.csv')\n\n label_loader = dgl_graphloader.EdgeLabelLoader(os.path.join(tmpdirname,\n 'edge_label.csv'))\n # only existence of the edge\n label_loader.addRelationalTrainSet([0,1,2])\n node_dicts = {}\n result = label_loader.process(node_dicts)\n assert len(result) == 1\n train_snids, train_dnids, train_labels, \\\n valid_snids, valid_dnids, valid_labels, \\\n test_snids, test_dnids, test_labels = result[('node','A','node')]\n assert np.array_equal(np.array([0,1,2,3,3]), train_snids)\n assert np.array_equal(np.array([1,0,0,2,3]), train_dnids)\n assert valid_snids is None\n assert valid_dnids is None\n assert test_snids is None\n assert test_dnids is None\n assert train_labels is None\n assert valid_labels is None\n assert test_labels is None\n label_loader.addRelationalValidSet([0,1,3],rows=[0,3])\n label_loader.addRelationalTestSet([0,1,3],rows=[1,2,4])\n result = label_loader.process(node_dicts)\n assert len(result) == 3\n train_snids, train_dnids, train_labels, \\\n valid_snids, valid_dnids, valid_labels, \\\n test_snids, test_dnids, test_labels = result[('node','A','node')]\n assert np.array_equal(np.array([0,1,2,3,3]), train_snids)\n assert np.array_equal(np.array([1,0,0,2,3]), train_dnids)\n assert valid_snids is None\n assert valid_dnids is None\n assert np.array_equal(np.array([3]), test_snids)\n assert np.array_equal(np.array([3]), test_dnids)\n assert train_labels is None\n assert valid_labels is None\n assert test_labels is None\n train_snids, train_dnids, train_labels, \\\n valid_snids, valid_dnids, valid_labels, \\\n test_snids, test_dnids, test_labels = result[('node','C','node')]\n assert train_snids is None\n assert train_dnids is None\n assert np.array_equal(np.array([0]), valid_snids)\n assert np.array_equal(np.array([1]), valid_dnids)\n assert np.array_equal(np.array([1,2]), test_snids)\n assert np.array_equal(np.array([0,0]), test_dnids)\n assert train_labels is None\n assert valid_labels is None\n assert test_labels is None\n train_snids, train_dnids, train_labels, \\\n valid_snids, valid_dnids, valid_labels, \\\n test_snids, test_dnids, test_labels = result[('node','B','node')]\n assert train_snids is None\n assert train_dnids is None\n assert np.array_equal(np.array([3]), valid_snids)\n assert np.array_equal(np.array([2]), valid_dnids)\n assert test_snids is None\n assert test_dnids is None\n assert train_labels is None\n assert valid_labels is None\n assert test_labels is None\n\n np.random.seed(0)\n label_loader = dgl_graphloader.EdgeLabelLoader(os.path.join(tmpdirname,\n 'edge_label.csv'))\n label_loader.addRelationalTrainSet([0,1,2])\n label_loader.addRelationalSet([0,1,3], split_rate=[0.,0.4,0.6])\n result = label_loader.process(node_dicts)\n assert len(result) == 3\n train_snids, train_dnids, train_labels, \\\n valid_snids, valid_dnids, valid_labels, \\\n test_snids, test_dnids, test_labels = result[('node','A','node')]\n assert np.array_equal(np.array([0,1,2,3,3]), train_snids)\n assert np.array_equal(np.array([1,0,0,2,3]), train_dnids)\n assert np.array_equal(np.array([3]), test_snids)\n assert np.array_equal(np.array([3]), test_dnids)\n assert valid_snids is None\n assert valid_dnids is None\n assert train_labels is None\n assert valid_labels is None\n assert test_labels is None\n train_snids, train_dnids, train_labels, \\\n valid_snids, valid_dnids, valid_labels, \\\n test_snids, test_dnids, test_labels = result[('node','C','node')]\n assert train_snids is None\n assert train_dnids is None\n assert np.array_equal(np.array([2]), valid_snids)\n assert np.array_equal(np.array([0]), valid_dnids)\n assert np.array_equal(np.array([1,0]), test_snids)\n assert np.array_equal(np.array([0,1]), test_dnids)\n assert train_labels is None\n assert valid_labels is None\n assert test_labels is None\n train_snids, train_dnids, train_labels, \\\n valid_snids, valid_dnids, valid_labels, \\\n test_snids, test_dnids, test_labels = result[('node','B','node')]\n assert train_snids is None\n assert train_dnids is None\n assert valid_snids is None\n assert valid_dnids is None\n assert np.array_equal(np.array([3]), test_snids)\n assert np.array_equal(np.array([2]), test_dnids)\n assert train_labels is None\n assert valid_labels is None\n assert test_labels is None\n\n #test warning\n label_loader.addRelationalSet([0,1,3], split_rate=[0.01,0.4,0.6])\n\ndef test_edge_process():\n import tempfile\n with tempfile.TemporaryDirectory() as tmpdirname:\n create_graph_edges(Path(tmpdirname), 'graphs.csv')\n\n edge_loader = dgl_graphloader.EdgeLoader(os.path.join(tmpdirname,\n 'graphs.csv'))\n\n edge_loader.addEdges([0,1])\n edge_loader.addEdges(['node_0','node_1'])\n edge_loader.addEdges(['node_0','node_1'],\n rows=np.array([1,2,3,4]),\n edge_type=('src', 'edge', 'src'))\n node_dicts = {}\n result = edge_loader.process(node_dicts)\n assert len(result) == 2\n snids, dnids = result[None]\n assert np.array_equal(np.array([0,1,2,3,3,0,1,2,3,3]), snids)\n assert np.array_equal(np.array([1,0,0,2,3,1,0,0,2,3]), dnids)\n snids, dnids = result[('src', 'edge', 'src')]\n assert np.array_equal(np.array([0,1,2,2]), snids)\n assert np.array_equal(np.array([3,3,1,2]), dnids)\n\n # with categorical relation\n edge_loader = dgl_graphloader.EdgeLoader(os.path.join(tmpdirname,\n 'graphs.csv'))\n edge_loader.addCategoryRelationEdge([0,1,2],\n src_type='src_t',\n dst_type='dst_t')\n edge_loader.addCategoryRelationEdge(['node_0','node_1','rel_2'],\n src_type='src_t',\n dst_type='dst_t')\n edge_loader.addCategoryRelationEdge(['node_0','node_1','rel_1'],\n rows=np.array([1,2,3,4]),\n src_type='src',\n dst_type='dst')\n node_dicts = {'src_t':{'node1':3,\n 'node2':2,\n 'node3':1,\n 'node4':0}}\n result = edge_loader.process(node_dicts)\n assert len(result) == 4\n snids, dnids = result[('src_t','A','dst_t')]\n assert np.array_equal(np.array([3,2,1,0,0,0]), snids)\n assert np.array_equal(np.array([0,1,1,2,3,3]), dnids)\n snids, dnids = result[('src_t','B','dst_t')]\n assert np.array_equal(np.array([0]), snids)\n assert np.array_equal(np.array([2]), dnids)\n snids, dnids = result[('src_t','C','dst_t')]\n assert np.array_equal(np.array([3,2,1]), snids)\n assert np.array_equal(np.array([0,1,1]), dnids)\n snids, dnids = result[('src','A','dst')]\n assert np.array_equal(np.array([0,1,2,2]), snids)\n assert np.array_equal(np.array([0,0,1,2]), dnids)\n\ndef test_build_graph():\n import tempfile\n with tempfile.TemporaryDirectory() as tmpdirname:\n create_graph_edges(Path(tmpdirname), 'edges.csv')\n create_edge_labels(Path(tmpdirname), 'edge_labels.csv')\n create_node_labels(Path(tmpdirname), 'node_labels.csv')\n\n # homogeneous graph loader (edge labels)\n node_feat_loader = dgl_graphloader.NodeFeatureLoader(os.path.join(tmpdirname, 'node_labels.csv'))\n node_feat_loader.addCategoryFeature([0,1])\n node_feat_loader.addMultiCategoryFeature([0,2], separator=',')\n edge_label_loader = dgl_graphloader.EdgeLabelLoader(os.path.join(tmpdirname, 'edge_labels.csv'))\n edge_label_loader.addSet([0,1,2],split_rate=[0.5,0.25,0.25])\n edge_loader = dgl_graphloader.EdgeLoader(os.path.join(tmpdirname, 'edges.csv'))\n edge_loader.addEdges([0,1])\n\n np.random.seed(0)\n graphloader = dgl_graphloader.GraphLoader(name='example')\n graphloader.appendEdge(edge_loader)\n graphloader.appendLabel(edge_label_loader)\n graphloader.appendFeature(node_feat_loader)\n graphloader.process()\n\n node_id_map = graphloader.node2id\n assert None in node_id_map\n assert len(node_id_map[None]) == 4\n for idx, key in enumerate(['node1', 'node2', 'node3', 'node4']):\n assert node_id_map[None][key] == idx\n id_node_map = graphloader.id2node\n assert None in id_node_map\n assert len(id_node_map[None]) == 4\n for idx, key in enumerate(['node1', 'node2', 'node3', 'node4']):\n assert id_node_map[None][idx] == key\n label_map = graphloader.label_map\n assert len(label_map[None]) == 2\n assert label_map[None][0] == 'A'\n assert label_map[None][1] == 'C'\n\n g = graphloader.graph\n assert g.num_edges() == 9\n assert np.array_equal(g.edata['labels'].long().numpy(),\n np.array([[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[0,1],[1,0],[1,0],[1,0]]))\n assert th.nonzero(g.edata['train_mask']).shape[0] == 2\n assert th.nonzero(g.edata['valid_mask']).shape[0] == 1\n assert th.nonzero(g.edata['test_mask']).shape[0] == 1\n assert np.allclose(g.ndata['nf'].numpy(),\n np.array([[1,0,1,0,0,1,0,0,0],[1,0,0,0,1,1,1,0,0],[0,1,1,1,0,0,0,1,0],[1,0,0,0,0,0,1,0,1]]))\n\n # heterogeneous graph loader (edge labels)\n create_train_edge_labels(Path(tmpdirname), 'edge_train_labels.csv')\n node_feat_loader = dgl_graphloader.NodeFeatureLoader(os.path.join(tmpdirname, 'node_labels.csv'))\n node_feat_loader.addCategoryFeature([0,1], node_type='a')\n node_feat_loader.addMultiCategoryFeature([0,2], separator=',', node_type='a')\n edge_label_loader = dgl_graphloader.EdgeLabelLoader(os.path.join(tmpdirname, 'edge_labels.csv'))\n edge_label_loader.addSet([0,1,2],split_rate=[0.5,0.25,0.25], edge_type=('a', 'follow', 'b'))\n edge_train_label_loader = dgl_graphloader.EdgeLabelLoader(os.path.join(tmpdirname, 'edge_train_labels.csv'))\n edge_train_label_loader.addTrainSet([0,1,2], edge_type=('a', 'follow', 'b'))\n edge_loader = dgl_graphloader.EdgeLoader(os.path.join(tmpdirname, 'edges.csv'))\n edge_loader.addEdges([0,1], edge_type=('a', 'follow', 'b'))\n node_feat_loader2 = dgl_graphloader.NodeFeatureLoader(os.path.join(tmpdirname, 'node_labels.csv'))\n node_feat_loader2.addCategoryFeature([0,1], node_type='b')\n edge_loader2 = dgl_graphloader.EdgeLoader(os.path.join(tmpdirname, 'edges.csv'))\n edge_loader2.addEdges([0,1], edge_type=('b', 'follow', 'a'))\n\n np.random.seed(0)\n graphloader = dgl_graphloader.GraphLoader(name='example')\n graphloader.appendEdge(edge_loader)\n graphloader.appendEdge(edge_loader2)\n graphloader.appendLabel(edge_label_loader)\n graphloader.appendLabel(edge_train_label_loader)\n graphloader.appendFeature(node_feat_loader)\n graphloader.appendFeature(node_feat_loader2)\n graphloader.process()\n\n node_id_map = graphloader.node2id\n assert 'a' in node_id_map\n assert len(node_id_map['a']) == 4\n for idx, key in enumerate(['node1', 'node2', 'node3', 'node4']):\n assert node_id_map['a'][key] == idx\n id_node_map = graphloader.id2node\n assert 'a' in id_node_map\n assert len(id_node_map['a']) == 4\n for idx, key in enumerate(['node1', 'node2', 'node3', 'node4']):\n assert id_node_map['a'][idx] == key\n assert 'b' in node_id_map\n assert len(node_id_map['b']) == 4\n for idx, key in enumerate(['node2', 'node1', 'node3', 'node4']):\n assert node_id_map['b'][key] == idx\n assert 'b' in id_node_map\n assert len(id_node_map['b']) == 4\n for idx, key in enumerate(['node2', 'node1', 'node3', 'node4']):\n assert id_node_map['b'][idx] == key\n\n label_map = graphloader.label_map\n assert len(label_map[('a', 'follow', 'b')]) == 2\n assert label_map[('a', 'follow', 'b')][0] == 'A'\n assert label_map[('a', 'follow', 'b')][1] == 'C'\n\n g = graphloader.graph\n assert g.num_edges(('a', 'follow', 'b')) == 11\n assert g.num_edges(('b', 'follow', 'a')) == 5\n assert np.array_equal(g.edges[('a', 'follow', 'b')].data['labels'].long().numpy(),\n np.array([[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[0,1],[1,0],[1,0],[1,0],[1,0],[1,0]]))\n assert th.nonzero(g.edges[('a', 'follow', 'b')].data['train_mask']).shape[0] == 4\n assert th.nonzero(g.edges[('a', 'follow', 'b')].data['valid_mask']).shape[0] == 1\n assert th.nonzero(g.edges[('a', 'follow', 'b')].data['test_mask']).shape[0] == 1\n assert np.allclose(g.nodes['a'].data['nf'].numpy(),\n np.array([[1,0,1,0,0,1,0,0,0],[1,0,0,0,1,1,1,0,0],[0,1,1,1,0,0,0,1,0],[1,0,0,0,0,0,1,0,1]]))\n assert np.allclose(g.nodes['b'].data['nf'].numpy(),\n np.array([[1.,0.,],[1.,0.],[0.,1.],[1.,0.]]))\n\n # edge feat with edge labels\n create_graph_feat_edges(Path(tmpdirname), 'edges_feats.csv')\n node_feat_loader = dgl_graphloader.NodeFeatureLoader(os.path.join(tmpdirname, 'node_labels.csv'))\n node_feat_loader.addCategoryFeature([0,1], node_type='a')\n node_feat_loader.addMultiCategoryFeature([0,2], separator=',', node_type='a')\n edge_label_loader = dgl_graphloader.EdgeLabelLoader(os.path.join(tmpdirname, 'edge_labels.csv'))\n edge_label_loader.addSet([0,1,2],split_rate=[0.5,0.25,0.25], edge_type=('a', 'follow', 'b'))\n edge_feat_loader = dgl_graphloader.EdgeFeatureLoader(os.path.join(tmpdirname, 'edges_feats.csv'))\n edge_feat_loader.addNumericalFeature([0,1,2], edge_type=('a', 'follow', 'b'))\n node_feat_loader2 = dgl_graphloader.NodeFeatureLoader(os.path.join(tmpdirname, 'node_labels.csv'))\n node_feat_loader2.addCategoryFeature([0,1], node_type='b')\n edge_loader2 = dgl_graphloader.EdgeLoader(os.path.join(tmpdirname, 'edges.csv'))\n edge_loader2.addEdges([0,1], edge_type=('b', 'follow', 'a'))\n\n np.random.seed(0)\n graphloader = dgl_graphloader.GraphLoader(name='example')\n graphloader.appendEdge(edge_loader2)\n graphloader.appendLabel(edge_label_loader)\n graphloader.appendFeature(edge_feat_loader)\n graphloader.appendFeature(node_feat_loader)\n graphloader.appendFeature(node_feat_loader2)\n graphloader.process()\n node_id_map = graphloader.node2id\n assert 'b' in node_id_map\n assert len(node_id_map['b']) == 4\n for idx, key in enumerate(['node1', 'node2', 'node3', 'node4']):\n assert node_id_map['b'][key] == idx\n id_node_map = graphloader.id2node\n assert 'b' in id_node_map\n assert len(id_node_map['b']) == 4\n for idx, key in enumerate(['node1', 'node2', 'node3', 'node4']):\n assert id_node_map['b'][idx] == key\n assert 'a' in node_id_map\n assert len(node_id_map['a']) == 4\n for idx, key in enumerate(['node2', 'node1', 'node3', 'node4']):\n assert node_id_map['a'][key] == idx\n assert 'a' in id_node_map\n assert len(id_node_map['a']) == 4\n for idx, key in enumerate(['node2', 'node1', 'node3', 'node4']):\n assert id_node_map['a'][idx] == key\n\n g = graphloader.graph\n assert g.num_edges(('a', 'follow', 'b')) == 9\n assert g.num_edges(('b', 'follow', 'a')) == 5\n assert np.array_equal(g.edges[('a', 'follow', 'b')].data['labels'].long().numpy(),\n np.array([[1,0],[1,0],[0,1],[1,0],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1]]))\n assert th.nonzero(g.edges[('a', 'follow', 'b')].data['train_mask']).shape[0] == 2\n assert th.nonzero(g.edges[('a', 'follow', 'b')].data['valid_mask']).shape[0] == 1\n assert th.nonzero(g.edges[('a', 'follow', 'b')].data['test_mask']).shape[0] == 1\n assert np.allclose(g.edges[('a', 'follow', 'b')].data['ef'].numpy(),\n np.array([[0.1],[0.2],[0.3],[0.4],[0.5],[0.6],[0.7],[0.8],[0.9]]))\n\n # heterogeneous graph loader (edge no labels)\n node_feat_loader = dgl_graphloader.NodeFeatureLoader(os.path.join(tmpdirname, 'node_labels.csv'))\n node_feat_loader.addCategoryFeature([0,1], node_type='a')\n node_feat_loader.addMultiCategoryFeature([0,2], separator=',', node_type='a')\n edge_label_loader = dgl_graphloader.EdgeLabelLoader(os.path.join(tmpdirname, 'edge_labels.csv'))\n edge_label_loader.addSet([0,1],split_rate=[0.5,0.25,0.25], edge_type=('a', 'follow', 'b'))\n edge_loader = dgl_graphloader.EdgeLoader(os.path.join(tmpdirname, 'edges.csv'))\n edge_loader.addEdges([0,1], edge_type=('a', 'follow', 'b'))\n node_feat_loader2 = dgl_graphloader.NodeFeatureLoader(os.path.join(tmpdirname, 'node_labels.csv'))\n node_feat_loader2.addCategoryFeature([0,1], node_type='b')\n edge_loader2 = dgl_graphloader.EdgeLoader(os.path.join(tmpdirname, 'edges.csv'))\n edge_loader2.addEdges([0,1], edge_type=('b', 'follow', 'a'))\n\n np.random.seed(0)\n graphloader = dgl_graphloader.GraphLoader(name='example')\n graphloader.appendEdge(edge_loader)\n graphloader.appendEdge(edge_loader2)\n graphloader.appendLabel(edge_label_loader)\n graphloader.appendFeature(node_feat_loader)\n graphloader.appendFeature(node_feat_loader2)\n graphloader.process()\n\n label_map = graphloader.label_map\n assert len(label_map) == 0\n g = graphloader.graph\n assert g.num_edges(('a', 'follow', 'b')) == 9\n assert g.num_edges(('b', 'follow', 'a')) == 5\n assert th.nonzero(g.edges[('a', 'follow', 'b')].data['train_mask']).shape[0] == 2\n assert th.nonzero(g.edges[('a', 'follow', 'b')].data['valid_mask']).shape[0] == 1\n assert th.nonzero(g.edges[('a', 'follow', 'b')].data['test_mask']).shape[0] == 1\n assert np.allclose(g.nodes['a'].data['nf'].numpy(),\n np.array([[1,0,1,0,0,1,0,0,0],[1,0,0,0,1,1,1,0,0],[0,1,1,1,0,0,0,1,0],[1,0,0,0,0,0,1,0,1]]))\n assert np.allclose(g.nodes['b'].data['nf'].numpy(),\n np.array([[1.,0.,],[1.,0.],[0.,1.],[1.,0.]]))\n\n # heterogeneous graph loader (node labels)\n create_node_valid_labels(Path(tmpdirname), 'node_valid.csv')\n create_node_test_labels(Path(tmpdirname), 'node_test.csv')\n create_node_feats(Path(tmpdirname), 'node_feat.csv')\n node_label_loader = dgl_graphloader.NodeLabelLoader(os.path.join(tmpdirname, 'node_labels.csv'))\n node_label_loader.addTrainSet([0,1], node_type='a')\n valid_label_loader = dgl_graphloader.NodeLabelLoader(os.path.join(tmpdirname, 'node_valid.csv'))\n valid_label_loader.addValidSet([0,1], node_type='a')\n test_label_loader = dgl_graphloader.NodeLabelLoader(os.path.join(tmpdirname, 'node_test.csv'))\n test_label_loader.addTestSet([0,1], node_type='a')\n edge_feat_loader = dgl_graphloader.EdgeFeatureLoader(os.path.join(tmpdirname, 'edges_feats.csv'))\n edge_feat_loader.addNumericalFeature([0,1,2], edge_type=('a', 'in', 'aa'))\n edge_loader = dgl_graphloader.EdgeLoader(os.path.join(tmpdirname, 'edges.csv'))\n edge_loader.addEdges([0,1], edge_type=('a', 'follow', 'a'))\n node_feat_loader = dgl_graphloader.NodeFeatureLoader(os.path.join(tmpdirname, 'node_feat.csv'))\n node_feat_loader.addCategoryFeature([0,1], node_type='a')\n node_feat_loader.addMultiCategoryFeature([0,2], separator=',', node_type='a')\n\n\n graphloader = dgl_graphloader.GraphLoader(name='example')\n graphloader.appendEdge(edge_loader)\n graphloader.appendLabel(node_label_loader)\n graphloader.appendLabel(valid_label_loader)\n graphloader.appendLabel(test_label_loader)\n graphloader.appendFeature(edge_feat_loader)\n graphloader.appendFeature(node_feat_loader)\n graphloader.process()\n\n node_id_map = graphloader.node2id\n assert 'a' in node_id_map\n assert len(node_id_map['a']) == 8\n for idx, key in enumerate(['node1', 'node2', 'node3', 'node4', 'node5', 'node6', 'node7', 'node8']):\n assert node_id_map['a'][key] == idx\n id_node_map = graphloader.id2node\n assert 'a' in id_node_map\n assert len(id_node_map['a']) == 8\n for idx, key in enumerate(['node1', 'node2', 'node3', 'node4', 'node5', 'node6', 'node7', 'node8']):\n assert id_node_map['a'][idx] == key\n assert 'aa' in node_id_map\n assert len(node_id_map['aa']) == 4\n for idx, key in enumerate(['node4', 'node3', 'node2', 'node1']):\n assert node_id_map['aa'][key] == idx\n assert 'aa' in id_node_map\n assert len(id_node_map['aa']) == 4\n for idx, key in enumerate(['node4', 'node3', 'node2', 'node1']):\n assert id_node_map['aa'][idx] == key\n\n label_map = graphloader.label_map\n assert len(label_map['a']) == 2\n assert label_map['a'][0] == 'A'\n assert label_map['a'][1] == 'C'\n g = graphloader.graph\n assert g.num_edges(('a', 'in', 'aa')) == 9\n assert g.num_edges(('a', 'follow', 'a')) == 5\n assert np.array_equal(g.nodes['a'].data['train_mask'].long().numpy(), np.array([1,1,1,1,0,0,0,0]))\n assert np.array_equal(g.nodes['a'].data['valid_mask'].long().numpy(), np.array([0,0,0,0,1,1,0,0]))\n assert np.array_equal(g.nodes['a'].data['test_mask'].long().numpy(), np.array([0,0,0,0,0,0,1,1]))\n assert np.allclose(g.nodes['a'].data['nf'].numpy(),\n np.array([[1,0,1,0,0,1,0,0,0],[1,0,0,0,1,1,1,0,0],\n [0,1,1,1,0,0,0,1,0],[1,0,0,0,0,0,1,0,1],\n [1,0,1,0,0,1,0,0,0],[0,1,0,0,1,1,1,0,0],\n [1,0,1,0,0,1,0,0,0],[1,0,0,0,1,1,1,0,0]]))\n assert np.allclose(g.edges[('a', 'in', 'aa')].data['ef'].numpy(),\n np.array([[0.1],[0.2],[0.3],[0.4],[0.5],[0.6],[0.7],[0.8],[0.9]]))\n\ndef test_add_reverse_edge():\n import tempfile\n with tempfile.TemporaryDirectory() as tmpdirname:\n create_graph_edges(Path(tmpdirname), 'edges.csv')\n create_edge_labels(Path(tmpdirname), 'edge_labels.csv')\n create_node_labels(Path(tmpdirname), 'node_labels.csv')\n create_train_edge_labels(Path(tmpdirname), 'edge_train_labels.csv')\n\n node_feat_loader = dgl_graphloader.NodeFeatureLoader(os.path.join(tmpdirname, 'node_labels.csv'))\n node_feat_loader.addCategoryFeature([0,1], node_type='a')\n node_feat_loader.addMultiCategoryFeature([0,2], separator=',', node_type='a')\n edge_label_loader = dgl_graphloader.EdgeLabelLoader(os.path.join(tmpdirname, 'edge_labels.csv'))\n edge_label_loader.addSet([0,1,2],split_rate=[0.5,0.25,0.25], edge_type=('a', 'follow', 'b'))\n edge_train_label_loader = dgl_graphloader.EdgeLabelLoader(os.path.join(tmpdirname, 'edge_train_labels.csv'))\n edge_train_label_loader.addTrainSet([0,1,2], edge_type=('a', 'follow', 'b'))\n edge_loader = dgl_graphloader.EdgeLoader(os.path.join(tmpdirname, 'edges.csv'))\n edge_loader.addEdges([0,1], edge_type=('a', 'follow', 'b'))\n node_feat_loader2 = dgl_graphloader.NodeFeatureLoader(os.path.join(tmpdirname, 'node_labels.csv'))\n node_feat_loader2.addCategoryFeature([0,1], node_type='b')\n edge_loader2 = dgl_graphloader.EdgeLoader(os.path.join(tmpdirname, 'edges.csv'))\n edge_loader2.addEdges([0,1], edge_type=('b', 'follow', 'a'))\n\n np.random.seed(0)\n graphloader = dgl_graphloader.GraphLoader(name='example')\n graphloader.appendEdge(edge_loader)\n graphloader.appendEdge(edge_loader2)\n graphloader.appendLabel(edge_label_loader)\n graphloader.appendLabel(edge_train_label_loader)\n graphloader.appendFeature(node_feat_loader)\n graphloader.appendFeature(node_feat_loader2)\n graphloader.addReverseEdge()\n graphloader.process()\n\n node_id_map = graphloader.node2id\n assert 'a' in node_id_map\n assert len(node_id_map['a']) == 4\n for idx, key in enumerate(['node1', 'node2', 'node3', 'node4']):\n assert node_id_map['a'][key] == idx\n id_node_map = graphloader.id2node\n assert 'a' in id_node_map\n assert len(id_node_map['a']) == 4\n for idx, key in enumerate(['node1', 'node2', 'node3', 'node4']):\n assert id_node_map['a'][idx] == key\n assert 'b' in node_id_map\n assert len(node_id_map['b']) == 4\n for idx, key in enumerate(['node2', 'node1', 'node3', 'node4']):\n assert node_id_map['b'][key] == idx\n assert 'b' in id_node_map\n assert len(id_node_map['b']) == 4\n for idx, key in enumerate(['node2', 'node1', 'node3', 'node4']):\n assert id_node_map['b'][idx] == key\n\n label_map = graphloader.label_map\n assert len(label_map[('a', 'follow', 'b')]) == 2\n assert label_map[('a', 'follow', 'b')][0] == 'A'\n assert label_map[('a', 'follow', 'b')][1] == 'C'\n g = graphloader.graph\n assert g.num_edges(('a', 'follow', 'b')) == 11\n assert g.num_edges(('b', 'follow', 'a')) == 5\n assert g.num_edges(('b', 'rev-follow', 'a')) == 11\n assert g.num_edges(('a', 'rev-follow', 'b')) == 5\n assert 'labels' in g.edges[('a', 'follow', 'b')].data\n assert 'labels' not in g.edges[('b', 'rev-follow', 'a')].data\n assert th.nonzero(g.edges[('a', 'follow', 'b')].data['train_mask']).shape[0] == 4\n assert th.nonzero(g.edges[('a', 'follow', 'b')].data['valid_mask']).shape[0] == 1\n assert th.nonzero(g.edges[('a', 'follow', 'b')].data['test_mask']).shape[0] == 1\n assert th.nonzero(g.edges[('b', 'rev-follow', 'a')].data['rev_train_mask']).shape[0] == 4\n assert th.nonzero(g.edges[('b', 'rev-follow', 'a')].data['rev_valid_mask']).shape[0] == 1\n assert th.nonzero(g.edges[('b', 'rev-follow', 'a')].data['rev_test_mask']).shape[0] == 1\n assert np.allclose(g.nodes['a'].data['nf'].numpy(),\n np.array([[1,0,1,0,0,1,0,0,0],[1,0,0,0,1,1,1,0,0],[0,1,1,1,0,0,0,1,0],[1,0,0,0,0,0,1,0,1]]))\n assert np.allclose(g.nodes['b'].data['nf'].numpy(),\n np.array([[1.,0.,],[1.,0.],[0.,1.],[1.,0.]]))\n\n # heterogeneous graph loader (edge no labels)\n node_feat_loader = dgl_graphloader.NodeFeatureLoader(os.path.join(tmpdirname, 'node_labels.csv'))\n node_feat_loader.addCategoryFeature([0,1], node_type='a')\n node_feat_loader.addMultiCategoryFeature([0,2], separator=',', node_type='a')\n edge_label_loader = dgl_graphloader.EdgeLabelLoader(os.path.join(tmpdirname, 'edge_labels.csv'))\n edge_label_loader.addSet([0,1],split_rate=[0.5,0.25,0.25], edge_type=('a', 'follow', 'b'))\n edge_loader = dgl_graphloader.EdgeLoader(os.path.join(tmpdirname, 'edges.csv'))\n edge_loader.addEdges([0,1], edge_type=('a', 'follow', 'b'))\n node_feat_loader2 = dgl_graphloader.NodeFeatureLoader(os.path.join(tmpdirname, 'node_labels.csv'))\n node_feat_loader2.addCategoryFeature([0,1], node_type='b')\n edge_loader2 = dgl_graphloader.EdgeLoader(os.path.join(tmpdirname, 'edges.csv'))\n edge_loader2.addEdges([0,1], edge_type=('b', 'follow', 'a'))\n\n np.random.seed(0)\n graphloader = dgl_graphloader.GraphLoader(name='example')\n graphloader.appendEdge(edge_loader)\n graphloader.appendEdge(edge_loader2)\n graphloader.appendLabel(edge_label_loader)\n graphloader.appendFeature(node_feat_loader)\n graphloader.appendFeature(node_feat_loader2)\n graphloader.addReverseEdge()\n graphloader.process()\n\n label_map = graphloader.label_map\n assert len(label_map) == 0\n g = graphloader.graph\n assert g.num_edges(('a', 'follow', 'b')) == 9\n assert g.num_edges(('b', 'follow', 'a')) == 5\n assert g.num_edges(('b', 'rev-follow', 'a')) == 9\n assert g.num_edges(('a', 'rev-follow', 'b')) == 5\n assert th.nonzero(g.edges[('a', 'follow', 'b')].data['train_mask']).shape[0] == 2\n assert th.nonzero(g.edges[('a', 'follow', 'b')].data['valid_mask']).shape[0] == 1\n assert th.nonzero(g.edges[('a', 'follow', 'b')].data['test_mask']).shape[0] == 1\n assert th.nonzero(g.edges[('b', 'rev-follow', 'a')].data['rev_train_mask']).shape[0] == 2\n assert th.nonzero(g.edges[('b', 'rev-follow', 'a')].data['rev_valid_mask']).shape[0] == 1\n assert th.nonzero(g.edges[('b', 'rev-follow', 'a')].data['rev_test_mask']).shape[0] == 1\n assert np.allclose(g.nodes['a'].data['nf'].numpy(),\n np.array([[1,0,1,0,0,1,0,0,0],[1,0,0,0,1,1,1,0,0],[0,1,1,1,0,0,0,1,0],[1,0,0,0,0,0,1,0,1]]))\n assert np.allclose(g.nodes['b'].data['nf'].numpy(),\n np.array([[1.,0.,],[1.,0.],[0.,1.],[1.,0.]]))\n\n create_graph_edges(Path(tmpdirname), 'edge_label.csv')\n label_loader = dgl_graphloader.EdgeLabelLoader(os.path.join(tmpdirname,\n 'edge_label.csv'))\n # only existence of the edge\n label_loader.addRelationalTrainSet([0,1,2],rows=[0,1,2,3])\n label_loader.addRelationalTrainSet([0,1,3],rows=[2,3])\n label_loader.addRelationalValidSet([0,1,3],rows=[0])\n label_loader.addRelationalTestSet([0,1,3],rows=[1,4])\n graphloader = dgl_graphloader.GraphLoader(name='example')\n graphloader.appendLabel(label_loader)\n graphloader.addReverseEdge()\n graphloader.process()\n label_map = graphloader.label_map\n assert len(label_map) == 0\n g = graphloader.graph\n assert th.nonzero(g.edges[('node','A','node')].data['train_mask']).shape[0] == 4\n assert th.nonzero(g.edges[('node','A','node')].data['valid_mask']).shape[0] == 0\n assert th.nonzero(g.edges[('node','A','node')].data['test_mask']).shape[0] == 1\n assert th.nonzero(g.edges[('node','rev-A','node')].data['rev_train_mask']).shape[0] == 4\n assert th.nonzero(g.edges[('node','rev-A','node')].data['rev_valid_mask']).shape[0] == 0\n assert th.nonzero(g.edges[('node','rev-A','node')].data['rev_test_mask']).shape[0] == 1\n assert th.nonzero(g.edges[('node','B','node')].data['train_mask']).shape[0] == 1\n assert th.nonzero(g.edges[('node','B','node')].data['valid_mask']).shape[0] == 0\n assert th.nonzero(g.edges[('node','B','node')].data['test_mask']).shape[0] == 0\n assert th.nonzero(g.edges[('node','rev-B','node')].data['rev_train_mask']).shape[0] == 1\n assert th.nonzero(g.edges[('node','rev-B','node')].data['rev_valid_mask']).shape[0] == 0\n assert th.nonzero(g.edges[('node','rev-B','node')].data['rev_test_mask']).shape[0] == 0\n assert th.nonzero(g.edges[('node','C','node')].data['train_mask']).shape[0] == 1\n assert th.nonzero(g.edges[('node','C','node')].data['valid_mask']).shape[0] == 1\n assert th.nonzero(g.edges[('node','C','node')].data['test_mask']).shape[0] == 1\n assert th.nonzero(g.edges[('node','rev-C','node')].data['rev_train_mask']).shape[0] == 1\n assert th.nonzero(g.edges[('node','rev-C','node')].data['rev_valid_mask']).shape[0] == 1\n assert th.nonzero(g.edges[('node','rev-C','node')].data['rev_test_mask']).shape[0] == 1\n\nif __name__ == '__main__':\n # test Feature Loader\n test_node_category_feature_loader()\n test_node_numerical_feature_loader()\n test_node_word2vec_feature_loader()\n test_edge_numerical_feature_loader()\n # test Label Loader\n test_node_label_loader()\n test_edge_label_loader()\n # test Edge Loader\n test_edge_loader()\n\n # test feature process\n test_node_feature_process()\n test_edge_feature_process()\n # test label process\n test_node_label_process()\n test_edge_label_process()\n test_relation_edge_label_process()\n # test edge process\n test_edge_process()\n\n test_build_graph()\n test_add_reverse_edge()\n"
] |
[
[
"numpy.allclose",
"numpy.array_equal",
"numpy.random.seed",
"torch.nonzero",
"numpy.array",
"numpy.zeros"
]
] |
smaiti7/openforcefield
|
[
"ee0f715e094e6f1749bf60f3a3b48174a9e6a9b7"
] |
[
"openforcefield/tests/test_molecule.py"
] |
[
"#!/usr/bin/env python\n\n#=============================================================================================\n# MODULE DOCSTRING\n#=============================================================================================\n\n\"\"\"\nTests for molecular topology representations\n\nAt least one supported cheminformatics toolkit must be installed to run these tests.\nOnly the tests applicable to that toolkit will be run.\n\nTODO:\n- Add tests comparing RDKit and OpenEye aromaticity perception\n- Right now, the test database of TestMolecule is read from mol2, requiring the OE\n toolkit. Find a different test set that RDKit can read, or make a database of\n serialized OFFMols.\n\n\"\"\"\n\n#=============================================================================================\n# GLOBAL IMPORTS\n#=============================================================================================\n\nimport copy\nimport os\nimport pickle\nfrom tempfile import NamedTemporaryFile\n\nimport numpy as np\nimport pytest\nfrom simtk import unit\n\nfrom openforcefield.topology.molecule import Molecule, Atom, InvalidConformerError\nfrom openforcefield.utils import get_data_file_path\n# TODO: Will the ToolkitWrapper allow us to pare that down?\nfrom openforcefield.utils.toolkits import OpenEyeToolkitWrapper, RDKitToolkitWrapper, AmberToolsToolkitWrapper, ToolkitRegistry\nfrom openforcefield.tests.test_forcefield import create_ethanol, create_reversed_ethanol, create_acetaldehyde, create_benzene_no_aromatic\n\n#=============================================================================================\n# TEST UTILITIES\n#=============================================================================================\n\nrequires_openeye = pytest.mark.skipif(not OpenEyeToolkitWrapper.is_available(),\n reason='Test requires OE toolkit')\nrequires_rdkit = pytest.mark.skipif(not RDKitToolkitWrapper.is_available(),\n reason='Test requires RDKit')\n\n\ndef assert_molecule_is_equal(molecule1, molecule2, msg):\n \"\"\"Compare whether two Molecule objects are equal\n\n Parameters\n ----------\n molecule1, molecule2 : openforcefield.topology.Molecule\n Molecules to be compared\n msg : str\n Message to include if molecules fail to match.\n\n \"\"\"\n if not(molecule1.is_isomorphic_with(molecule2)):\n raise AssertionError(msg)\n\n\ndef is_four_memebered_ring_torsion(torsion):\n \"\"\"Check that three atoms in the given torsion form a four-membered ring.\"\"\"\n # Push a copy of the first and second atom in the end to make the code simpler.\n torsion = list(torsion) + [torsion[0], torsion[1]]\n\n is_four_membered_ring = True\n for i in range(4):\n # The atom is bonded to the next one.\n is_four_membered_ring &= torsion[i].is_bonded_to(torsion[i+1])\n # The atom is not bonded to the atom on its diagonal.\n is_four_membered_ring &= not torsion[i].is_bonded_to(torsion[i+2])\n\n return is_four_membered_ring\n\n\ndef is_three_memebered_ring_torsion(torsion):\n \"\"\"Check that three atoms in the given torsion form a three-membered ring.\n\n In order to be 4 atoms with a three-membered ring, there must be\n 1) A central atom connected to all other atoms.\n 2) An atom outside the ring connected exclusively to the central atom.\n 3) Two atoms in the ring connected to the central atom and to each other.\n\n \"\"\"\n # A set of atom indices for the atoms in the torsion.\n torsion_atom_indices = set(a.molecule_atom_index for a in torsion)\n\n # Collect all the bonds involving exclusively atoms in the torsion.\n bonds_by_atom_idx = {i: set() for i in torsion_atom_indices}\n for atom in torsion:\n for bond in atom.bonds:\n # Consider the bond only if both atoms are in the torsion.\n if (bond.atom1_index in torsion_atom_indices and\n bond.atom2_index in torsion_atom_indices):\n bonds_by_atom_idx[bond.atom1_index].add(bond.atom2_index)\n bonds_by_atom_idx[bond.atom2_index].add(bond.atom1_index)\n\n # Find the central atom, which is connected to all other atoms.\n atom_indices = [i for i in torsion_atom_indices if len(bonds_by_atom_idx[i]) == 3]\n if len(atom_indices) != 1:\n return False\n central_atom_idx = atom_indices[0]\n\n # Find the atom outside the ring.\n atom_indices = [i for i in torsion_atom_indices if len(bonds_by_atom_idx[i]) == 1]\n if len(atom_indices) != 1 or central_atom_idx not in bonds_by_atom_idx[atom_indices[0]]:\n return False\n outside_atom_idx = atom_indices[0]\n\n # Check that the remaining two atoms are non-central atoms in the membered ring.\n atom1, atom2 = [i for i in torsion_atom_indices if i not in [central_atom_idx, outside_atom_idx]]\n # The two atoms are bonded to each other.\n if atom2 not in bonds_by_atom_idx[atom1] or atom1 not in bonds_by_atom_idx[atom2]:\n return False\n # Check that they are both bonded to the central atom and none other.\n for atom_idx in [atom1, atom2]:\n if (central_atom_idx not in bonds_by_atom_idx[atom_idx] or\n len(bonds_by_atom_idx[atom_idx]) != 2):\n return False\n\n # This is a torsion including a three-membered ring.\n return True\n\n\n#=============================================================================================\n# FIXTURES\n#=============================================================================================\n\ndef mini_drug_bank(xfail_mols=None, wip_mols=None):\n \"\"\"Load the full MiniDrugBank into Molecule objects.\n\n Parameters\n ----------\n xfail_mols : Dict[str, str or None]\n Dictionary mapping the molecule names that are allowed to\n failed to the failure reason.\n wip_mols : Dict[str, str or None]\n Dictionary mapping the molecule names that are work in progress\n to the failure reason.\n\n \"\"\"\n # If we have already loaded the data set, return the cached one.\n if mini_drug_bank.molecules is not None:\n molecules = mini_drug_bank.molecules\n else:\n # Load the dataset.\n file_path = get_data_file_path('molecules/MiniDrugBank_tripos.mol2')\n try:\n # We need OpenEye to parse the molecules, but pytest execute this\n # whether or not the test class is skipped so if OE is not available\n # we just return an empty list of test cases as a workaround.\n molecules = Molecule.from_file(file_path, allow_undefined_stereo=True)\n except NotImplementedError as e:\n assert 'No toolkits in registry can read file' in str(e)\n mini_drug_bank.molecules = []\n return []\n else:\n mini_drug_bank.molecules = molecules\n\n # Check if we need to mark anything.\n if xfail_mols is None and wip_mols is None:\n return molecules\n\n # Handle mutable default.\n if xfail_mols is None:\n xfail_mols = {}\n if wip_mols is None:\n wip_mols = {}\n # There should be no molecule in both dictionaries.\n assert len(set(xfail_mols).intersection(set(wip_mols))) == 0\n\n # Don't modify the cached molecules.\n molecules = copy.deepcopy(molecules)\n for i, mol in enumerate(molecules):\n if mol.name in xfail_mols:\n marker = pytest.mark.xfail(reason=xfail_mols[mol.name])\n elif mol.name in wip_mols:\n marker = pytest.mark.wip(reason=wip_mols[mol.name])\n else:\n marker = None\n\n if marker is not None:\n molecules[i] = pytest.param(mol, marks=marker)\n\n return molecules\n\n# Use a \"static\" variable as a workaround as fixtures cannot be\n# used inside pytest.mark.parametrize (see issue #349 in pytest).\nmini_drug_bank.molecules = None\n\n# All the molecules that raise UndefinedStereochemistryError when read by OETK()\nopeneye_drugbank_undefined_stereo_mols = {'DrugBank_1634', 'DrugBank_1700', 'DrugBank_1962',\n 'DrugBank_2519', 'DrugBank_2987', 'DrugBank_3502',\n 'DrugBank_3930', 'DrugBank_4161', 'DrugBank_4162',\n 'DrugBank_5043', 'DrugBank_5418', 'DrugBank_6531'}\n\n# All the molecules that raise UndefinedStereochemistryError when read by OETK().\n# Note that this list is different from that for OEMol,\n# since the toolkits have different definitions of \"stereogenic\"\nrdkit_drugbank_undefined_stereo_mols = {'DrugBank_1634', 'DrugBank_1962', 'DrugBank_2519',\n 'DrugBank_3930', 'DrugBank_5043', 'DrugBank_5418'}\n\n\n# Missing stereo in OE but not RDK: 'DrugBank_2987', 'DrugBank_3502', 'DrugBank_4161',\n# 'DrugBank_4162', 'DrugBank_6531', 'DrugBank_1700',\n\n# Some molecules are _valid_ in both OETK and RDKit, but will fail if you try\n# to convert from one to the other, since OE adds stereo that RDKit doesn't\ndrugbank_stereogenic_in_oe_but_not_rdkit = {'DrugBank_1598', 'DrugBank_4346', 'DrugBank_1849',\n 'DrugBank_2141'}\n\n#=============================================================================================\n# TESTS\n#=============================================================================================\n\nclass TestAtom:\n \"\"\"Test Atom class.\"\"\"\n\n def test_atom_constructor(self):\n \"\"\"Test Atom creation\"\"\"\n # Create a non-aromatic carbon atom\n atom1 = Atom(6, 0, False)\n assert atom1.atomic_number == 6\n assert atom1.formal_charge == 0\n\n # Create a chiral carbon atom\n atom2 = Atom(6, 0, False, stereochemistry='R', name='CT')\n assert atom1.stereochemistry != atom2.stereochemistry\n\n def test_atom_properties(self):\n \"\"\"Test that atom properties are correctly populated and gettable\"\"\"\n from simtk.openmm.app import element\n formal_charge = 0\n is_aromatic = False\n # Attempt to create all elements supported by OpenMM\n elements = [getattr(element, name) for name in dir(element) if (type(getattr(element, name)) == element.Element)]\n # The above runs into a problem with deuterium (fails name assertion)\n elements.remove(element.deuterium)\n for this_element in elements:\n atom = Atom(this_element.atomic_number, formal_charge, is_aromatic, name=this_element.name)\n assert atom.atomic_number == this_element.atomic_number\n assert atom.element == this_element\n assert atom.mass == this_element.mass\n assert atom.formal_charge == formal_charge\n assert atom.is_aromatic == is_aromatic\n assert atom.name == this_element.name\n\n\n@requires_openeye\nclass TestMolecule:\n \"\"\"Test Molecule class.\"\"\"\n\n # TODO: Test getstate/setstate\n # TODO: Test {to_from}_{dict|yaml|toml|json|bson|messagepack|pickle}\n\n @pytest.mark.parametrize('molecule', mini_drug_bank())\n def test_pickle_serialization(self, molecule):\n \"\"\"Test pickling of a molecule object.\"\"\"\n serialized = pickle.dumps(molecule)\n molecule_copy = pickle.loads(serialized)\n assert molecule == molecule_copy\n\n # ----------------------------------------------------\n # Test Molecule constructors and conversion utilities.\n # ----------------------------------------------------\n\n def test_create_empty(self):\n \"\"\"Test empty constructor.\"\"\"\n molecule = Molecule()\n assert len(molecule.atoms) == 0\n assert len(molecule.bonds) == 0\n\n @pytest.mark.parametrize('molecule', mini_drug_bank())\n def test_create_copy(self, molecule):\n \"\"\"Test copy constructor.\"\"\"\n molecule_copy = Molecule(molecule)\n assert molecule_copy == molecule\n\n @pytest.mark.parametrize('toolkit', [OpenEyeToolkitWrapper, RDKitToolkitWrapper])\n @pytest.mark.parametrize('molecule', mini_drug_bank())\n def test_to_from_smiles(self, molecule, toolkit):\n \"\"\"Test round-trip creation from SMILES\"\"\"\n if not toolkit.is_available():\n pytest.skip('Required toolkit is unavailable')\n\n if toolkit == RDKitToolkitWrapper:\n # Skip the test if OpenEye assigns stereochemistry but RDKit doesn't (since then, the\n # OFF molecule will be loaded, but fail to convert in to_rdkit)\n if molecule.name in drugbank_stereogenic_in_oe_but_not_rdkit:\n pytest.skip('Molecle is stereogenic in OpenEye (which loaded this dataset), but not RDKit, so it '\n 'is impossible to make a valid RDMol in this test')\n undefined_stereo_mols = rdkit_drugbank_undefined_stereo_mols\n elif toolkit == OpenEyeToolkitWrapper:\n undefined_stereo_mols = openeye_drugbank_undefined_stereo_mols\n\n toolkit_wrapper = toolkit()\n\n undefined_stereo = molecule.name in undefined_stereo_mols\n\n smiles1 = molecule.to_smiles(toolkit_registry=toolkit_wrapper)\n if undefined_stereo:\n molecule2 = Molecule.from_smiles(smiles1,\n allow_undefined_stereo=True,\n toolkit_registry=toolkit_wrapper)\n else:\n molecule2 = Molecule.from_smiles(smiles1,\n toolkit_registry=toolkit_wrapper)\n smiles2 = molecule2.to_smiles(toolkit_registry=toolkit_wrapper)\n assert (smiles1 == smiles2)\n\n @pytest.mark.parametrize('molecule', mini_drug_bank())\n def test_unique_atom_names(self, molecule):\n \"\"\"Test molecules have unique atom names\"\"\"\n # The dataset we load in has atom names, so let's strip them first\n # to ensure that we can fail the uniqueness check\n for atom in molecule.atoms:\n atom.name = ''\n assert not(molecule.has_unique_atom_names)\n # Then genreate unique atom names using the built in algorithm\n molecule.generate_unique_atom_names()\n # Check that the molecule has unique atom names\n assert molecule.has_unique_atom_names\n # Check molecule.has_unique_atom_names is working correctly\n assert ((len(set([atom.name for atom in molecule.atoms])) == molecule.n_atoms) == molecule.has_unique_atom_names)\n molecule.atoms[1].name = molecule.atoms[0].name # no longer unique\n assert ((len(set([atom.name for atom in molecule.atoms])) == molecule.n_atoms) == molecule.has_unique_atom_names)\n\n # TODO: Should there be an equivalent toolkit test and leave this as an integration test?\n @pytest.mark.slow\n def test_create_from_file(self):\n \"\"\"Test standard constructor taking a filename or file-like object.\"\"\"\n # TODO: Expand test to both openeye and rdkit toolkits\n filename = get_data_file_path('molecules/toluene.mol2')\n\n molecule1 = Molecule(filename, allow_undefined_stereo=True)\n with open(filename, 'r') as infile:\n molecule2 = Molecule(infile, file_format='MOL2', allow_undefined_stereo=True)\n assert molecule1 == molecule2\n\n import gzip\n with gzip.GzipFile(filename + '.gz', 'r') as infile:\n molecule3 = Molecule(infile, file_format='MOL2', allow_undefined_stereo=True)\n assert molecule3 == molecule1\n\n # Ensure that attempting to initialize a single Molecule from a file\n # containing multiple molecules raises a ValueError\n with pytest.raises(ValueError) as exc_info:\n filename = get_data_file_path('molecules/zinc-subset-tripos.mol2.gz')\n molecule = Molecule(filename, allow_undefined_stereo=True)\n\n @pytest.mark.parametrize('molecule', mini_drug_bank())\n def test_create_from_serialized(self, molecule):\n \"\"\"Test standard constructor taking the output of __getstate__().\"\"\"\n serialized_molecule = molecule.__getstate__()\n molecule_copy = Molecule(serialized_molecule)\n assert molecule == molecule_copy\n\n @pytest.mark.parametrize('molecule', mini_drug_bank())\n def test_to_from_dict(self, molecule):\n \"\"\"Test that conversion/creation of a molecule to and from a dict is consistent.\"\"\"\n serialized = molecule.to_dict()\n molecule_copy = Molecule.from_dict(serialized)\n assert molecule == molecule_copy\n\n @pytest.mark.parametrize('molecule', mini_drug_bank())\n def test_to_networkx(self, molecule):\n \"\"\"Test conversion to NetworkX graph.\"\"\"\n graph = molecule.to_networkx()\n\n @requires_rdkit\n @pytest.mark.parametrize('molecule', mini_drug_bank())\n def test_to_from_rdkit(self, molecule):\n \"\"\"Test that conversion/creation of a molecule to and from an RDKit rdmol is consistent.\n \"\"\"\n # import pickle\n from openforcefield.utils.toolkits import UndefinedStereochemistryError\n\n undefined_stereo = molecule.name in rdkit_drugbank_undefined_stereo_mols\n\n toolkit_wrapper = RDKitToolkitWrapper()\n\n rdmol = molecule.to_rdkit()\n molecule_smiles = molecule.to_smiles(toolkit_registry=toolkit_wrapper)\n\n # First test making a molecule using the Molecule(oemol) method\n\n # If this is a known failure, check that it raises UndefinedStereochemistryError\n # and proceed with the test ignoring it.\n test_mol = None\n if undefined_stereo:\n with pytest.raises(UndefinedStereochemistryError):\n Molecule(rdmol)\n test_mol = Molecule(rdmol, allow_undefined_stereo=True)\n else:\n test_mol = Molecule(rdmol)\n\n test_mol_smiles = test_mol.to_smiles(toolkit_registry=toolkit_wrapper)\n assert molecule_smiles == test_mol_smiles\n\n # Check that the two topologies are isomorphic.\n assert_molecule_is_equal(molecule, test_mol, 'Molecule.to_rdkit()/Molecule(rdmol) round trip failed')\n\n # Second, test making a molecule using the Molecule.from_openeye(oemol) method\n\n # If this is a known failure, check that it raises UndefinedStereochemistryError\n # and proceed with the test.\n if undefined_stereo:\n with pytest.raises(UndefinedStereochemistryError):\n Molecule.from_rdkit(rdmol)\n test_mol = Molecule.from_rdkit(rdmol, allow_undefined_stereo=True)\n else:\n test_mol = Molecule.from_rdkit(rdmol)\n\n test_mol_smiles = test_mol.to_smiles(toolkit_registry=toolkit_wrapper)\n assert molecule_smiles == test_mol_smiles\n\n # Check that the two topologies are isomorphic.\n assert_molecule_is_equal(molecule, test_mol, 'Molecule.to_rdkit()/from_rdkit() round trip failed')\n\n\n # TODO: Should there be an equivalent toolkit test and leave this as an integration test?\n @requires_openeye\n @pytest.mark.parametrize('molecule', mini_drug_bank(\n xfail_mols={\n 'DrugBank_2397': 'OpenEye cannot generate a correct IUPAC name and raises a \"Warning: Incorrect name:\" or simply return \"BLAH\".',\n 'DrugBank_2543': 'OpenEye cannot generate a correct IUPAC name and raises a \"Warning: Incorrect name:\" or simply return \"BLAH\".',\n 'DrugBank_2642': 'OpenEye cannot generate a correct IUPAC name and raises a \"Warning: Incorrect name:\" or simply return \"BLAH\".',\n },\n wip_mols={\n 'DrugBank_1212': 'the roundtrip generates molecules with very different IUPAC/SMILES!',\n 'DrugBank_2210': 'the roundtrip generates molecules with very different IUPAC/SMILES!',\n 'DrugBank_4584': 'the roundtrip generates molecules with very different IUPAC/SMILES!',\n\n 'DrugBank_390': 'raises warning \"Unable to make OFFMol from OEMol: OEMol has unspecified stereochemistry.\"',\n 'DrugBank_810': 'raises warning \"Unable to make OFFMol from OEMol: OEMol has unspecified stereochemistry.\"',\n 'DrugBank_4316': 'raises warning \"Unable to make OFFMol from OEMol: OEMol has unspecified stereochemistry.\"',\n 'DrugBank_7124': 'raises warning \"Unable to make OFFMol from OEMol: OEMol has unspecified stereochemistry.\"',\n\n 'DrugBank_4346': 'raises warning \"Failed to parse name:\"',\n }\n ))\n def test_to_from_iupac(self, molecule):\n \"\"\"Test that conversion/creation of a molecule to and from a IUPAC name is consistent.\"\"\"\n from openforcefield.utils.toolkits import UndefinedStereochemistryError\n\n # All the molecules that raise UndefinedStereochemistryError in Molecule.from_iupac()\n # (This is a larger list than the normal group of undefined stereo mols, probably has\n # something to do with IUPAC information content)\n iupac_problem_mols = {'DrugBank_977', 'DrugBank_1634', 'DrugBank_1700', 'DrugBank_1962',\n 'DrugBank_2148', 'DrugBank_2178', 'DrugBank_2186', 'DrugBank_2208',\n 'DrugBank_2519', 'DrugBank_2538', 'DrugBank_2592', 'DrugBank_2651',\n 'DrugBank_2987', 'DrugBank_3332', 'DrugBank_3502', 'DrugBank_3622',\n 'DrugBank_3726', 'DrugBank_3844', 'DrugBank_3930', 'DrugBank_4161',\n 'DrugBank_4162', 'DrugBank_4778', 'DrugBank_4593', 'DrugBank_4959',\n 'DrugBank_5043', 'DrugBank_5076', 'DrugBank_5176', 'DrugBank_5418',\n 'DrugBank_5737', 'DrugBank_5902', 'DrugBank_6304', 'DrugBank_6305',\n 'DrugBank_6329', 'DrugBank_6355', 'DrugBank_6401', 'DrugBank_6509',\n 'DrugBank_6531', 'DrugBank_6647',\n\n # These test cases are allowed to fail.\n 'DrugBank_390', 'DrugBank_810', 'DrugBank_4316', 'DrugBank_4346',\n 'DrugBank_7124'\n }\n undefined_stereo = molecule.name in iupac_problem_mols\n\n iupac = molecule.to_iupac()\n\n if undefined_stereo:\n with pytest.raises(UndefinedStereochemistryError):\n Molecule.from_iupac(iupac)\n\n molecule_copy = Molecule.from_iupac(iupac, allow_undefined_stereo=undefined_stereo)\n assert molecule.is_isomorphic_with(molecule_copy,\n atom_stereochemistry_matching=not undefined_stereo)\n\n @pytest.mark.parametrize('molecule', mini_drug_bank())\n def test_to_from_topology(self, molecule):\n \"\"\"Test that conversion/creation of a molecule to and from a Topology is consistent.\"\"\"\n topology = molecule.to_topology()\n molecule_copy = Molecule.from_topology(topology)\n assert molecule == molecule_copy\n\n # TODO: Should there be an equivalent toolkit test and leave this as an integration test?\n @pytest.mark.parametrize('molecule', mini_drug_bank())\n @pytest.mark.parametrize('format', [\n 'mol2',\n 'sdf',\n pytest.param('pdb', marks=pytest.mark.wip(reason='Read from pdb has not been implemented properly yet'))\n ])\n def test_to_from_file(self, molecule, format):\n \"\"\"Test that conversion/creation of a molecule to and from a file is consistent.\"\"\"\n from openforcefield.utils.toolkits import UndefinedStereochemistryError\n # TODO: Test all file capabilities; the current test is minimal\n\n # TODO: This is only for OE. Expand to both OE and RDKit toolkits.\n # Molecules that are known to raise UndefinedStereochemistryError.\n undefined_stereo_mols = {'DrugBank_1700', 'DrugBank_2987', 'DrugBank_3502', 'DrugBank_4161',\n 'DrugBank_4162', 'DrugBank_6531'}\n undefined_stereo = molecule.name in undefined_stereo_mols\n\n # The file is automatically deleted outside the with-clause.\n with NamedTemporaryFile(suffix='.' + format) as iofile:\n # If this has undefined stereo, check that the exception is raised.\n extension = os.path.splitext(iofile.name)[1][1:]\n molecule.to_file(iofile.name, extension)\n if undefined_stereo:\n with pytest.raises(UndefinedStereochemistryError):\n Molecule.from_file(iofile.name)\n molecule2 = Molecule.from_file(iofile.name, allow_undefined_stereo=undefined_stereo)\n assert molecule == molecule2\n # TODO: Test to make sure properties are preserved?\n # NOTE: We can't read pdb files and expect chemical information to be preserved\n\n @requires_openeye\n @pytest.mark.parametrize('molecule', mini_drug_bank())\n def test_to_from_oemol(self, molecule):\n \"\"\"Test that conversion/creation of a molecule to and from a OEMol is consistent.\"\"\"\n from openforcefield.utils.toolkits import UndefinedStereochemistryError\n\n # Known failures raise an UndefinedStereochemistryError, but\n # the round-trip SMILES representation with the OpenEyeToolkit\n # doesn't seem to be affected.\n\n # ZINC test set known failures.\n # known_failures = {'ZINC05964684', 'ZINC05885163', 'ZINC05543156', 'ZINC17211981',\n # 'ZINC17312986', 'ZINC06424847', 'ZINC04963126'}\n\n undefined_stereo = molecule.name in openeye_drugbank_undefined_stereo_mols\n\n toolkit_wrapper = OpenEyeToolkitWrapper()\n\n oemol = molecule.to_openeye()\n molecule_smiles = molecule.to_smiles(toolkit_registry=toolkit_wrapper)\n\n # First test making a molecule using the Molecule(oemol) method\n\n # If this is a known failure, check that it raises UndefinedStereochemistryError\n # and proceed with the test ignoring it.\n test_mol = None\n if undefined_stereo:\n with pytest.raises(UndefinedStereochemistryError):\n Molecule(oemol)\n test_mol = Molecule(oemol, allow_undefined_stereo=True)\n else:\n test_mol = Molecule(oemol)\n\n test_mol_smiles = test_mol.to_smiles(toolkit_registry=toolkit_wrapper)\n assert molecule_smiles == test_mol_smiles\n\n # Check that the two topologies are isomorphic.\n assert_molecule_is_equal(molecule, test_mol, 'Molecule.to_openeye()/Molecule(oemol) round trip failed')\n\n # Second, test making a molecule using the Molecule.from_openeye(oemol) method\n\n # If this is a known failure, check that it raises UndefinedStereochemistryError\n # and proceed with the test.\n if undefined_stereo:\n with pytest.raises(UndefinedStereochemistryError):\n Molecule.from_openeye(oemol)\n test_mol = Molecule.from_openeye(oemol, allow_undefined_stereo=True)\n else:\n test_mol = Molecule.from_openeye(oemol)\n\n test_mol_smiles = test_mol.to_smiles(toolkit_registry=toolkit_wrapper)\n assert molecule_smiles == test_mol_smiles\n\n # Check that the two topologies are isomorphic.\n assert_molecule_is_equal(molecule, test_mol, 'Molecule.to_openeye()/from_openeye() round trip failed')\n\n\n # ----------------------------------------------------\n # Test properties.\n # ----------------------------------------------------\n\n def test_name(self):\n \"\"\"Test Molecule name property\"\"\"\n molecule1 = Molecule()\n molecule1.name = None\n\n molecule2 = Molecule()\n molecule2.name = ''\n assert molecule1.name == molecule2.name\n\n name = 'benzene'\n molecule = Molecule()\n molecule.name = name\n assert molecule.name == name\n\n def test_hill_formula(self):\n \"\"\"Test that making the hill formula is consistent between input methods and ordering\"\"\"\n # make sure smiles match reference\n molecule_smiles = create_ethanol()\n assert molecule_smiles.hill_formula == 'C2H6O'\n # make sure is not order dependent\n molecule_smiles_reverse = create_reversed_ethanol()\n assert molecule_smiles.hill_formula == molecule_smiles_reverse.hill_formula\n # make sure single element names are put first\n order_mol = Molecule.from_smiles('C(Br)CB')\n assert order_mol.hill_formula == 'C2H6BBr'\n # test molecule with no carbon\n no_carb_mol = Molecule.from_smiles('OS(=O)(=O)O')\n assert no_carb_mol.hill_formula == 'H2O4S'\n # test no carbon and hydrogen\n br_i = Molecule.from_smiles('BrI')\n assert br_i.hill_formula == 'BrI'\n # make sure files and smiles match\n molecule_file = Molecule.from_file(get_data_file_path('molecules/ethanol.sdf'))\n assert molecule_smiles.hill_formula == molecule_file.hill_formula\n # make sure the topology molecule gives the same formula\n from openforcefield.topology.topology import TopologyMolecule, Topology\n topology = Topology.from_molecules(molecule_smiles)\n topmol = TopologyMolecule(molecule_smiles, topology)\n assert molecule_smiles.hill_formula == Molecule.to_hill_formula(topmol)\n # make sure the networkx matches\n assert molecule_smiles.hill_formula == Molecule.to_hill_formula(molecule_smiles.to_networkx())\n\n\n def test_isomorphic_general(self):\n \"\"\"Test the matching using different input types\"\"\"\n # check that hill formula fails are caught\n ethanol = create_ethanol()\n acetaldehyde = create_acetaldehyde()\n assert ethanol.is_isomorphic_with(acetaldehyde) is False\n assert acetaldehyde.is_isomorphic_with(ethanol) is False\n # check that different orderings work with full matching\n ethanol_reverse = create_reversed_ethanol()\n assert ethanol.is_isomorphic_with(ethanol_reverse) is True\n # check a reference mapping between ethanol and ethanol_reverse matches that calculated\n ref_mapping = {0: 8, 1: 7, 2: 6, 3: 3, 4: 4, 5: 5, 6: 1, 7: 2, 8: 0}\n assert Molecule.are_isomorphic(ethanol, ethanol_reverse, return_atom_map=True)[1] == ref_mapping\n # check matching with nx.Graph atomic numbers and connectivity only\n assert Molecule.are_isomorphic(ethanol, ethanol_reverse.to_networkx(), aromatic_matching=False,\n formal_charge_matching=False, bond_order_matching=False,\n atom_stereochemistry_matching=False,\n bond_stereochemistry_matching=False)[0] is True\n # check matching with nx.Graph with full matching\n assert ethanol.is_isomorphic_with(ethanol_reverse.to_networkx()) is True\n # check matching with a TopologyMolecule class\n from openforcefield.topology.topology import TopologyMolecule, Topology\n topology = Topology.from_molecules(ethanol)\n topmol = TopologyMolecule(ethanol, topology)\n assert Molecule.are_isomorphic(ethanol, topmol, aromatic_matching=False, formal_charge_matching=False,\n bond_order_matching=False, atom_stereochemistry_matching=False,\n bond_stereochemistry_matching=False)[0] is True\n # test hill formula passes but isomorphic fails\n mol1 = Molecule.from_smiles('Fc1ccc(F)cc1')\n mol2 = Molecule.from_smiles('Fc1ccccc1F')\n assert mol1.is_isomorphic_with(mol2) is False\n assert mol2.is_isomorphic_with(mol1) is False\n\n isomorphic_permutations = [{'aromatic_matching': True, 'formal_charge_matching': True, 'bond_order_matching': True,\n 'atom_stereochemistry_matching': True, 'bond_stereochemistry_matching': True,\n 'result': False},\n {'aromatic_matching': False, 'formal_charge_matching': True, 'bond_order_matching': True,\n 'atom_stereochemistry_matching': True, 'bond_stereochemistry_matching': True,\n 'result': False},\n {'aromatic_matching': True, 'formal_charge_matching': False, 'bond_order_matching': True,\n 'atom_stereochemistry_matching': True, 'bond_stereochemistry_matching': True,\n 'result': False},\n {'aromatic_matching': True, 'formal_charge_matching': True, 'bond_order_matching': False,\n 'atom_stereochemistry_matching': True, 'bond_stereochemistry_matching': True,\n 'result': False},\n {'aromatic_matching': True, 'formal_charge_matching': True, 'bond_order_matching': True,\n 'atom_stereochemistry_matching': False, 'bond_stereochemistry_matching': True,\n 'result': False},\n {'aromatic_matching': True, 'formal_charge_matching': True, 'bond_order_matching': True,\n 'atom_stereochemistry_matching': True, 'bond_stereochemistry_matching': False,\n 'result': False},\n {'aromatic_matching': False, 'formal_charge_matching': False, 'bond_order_matching': False,\n 'atom_stereochemistry_matching': False, 'bond_stereochemistry_matching': False,\n 'result': True},\n {'aromatic_matching': False, 'formal_charge_matching': True, 'bond_order_matching': False,\n 'atom_stereochemistry_matching': True, 'bond_stereochemistry_matching': True,\n 'result': True},\n {'aromatic_matching': False, 'formal_charge_matching': False, 'bond_order_matching': False,\n 'atom_stereochemistry_matching': True, 'bond_stereochemistry_matching': True,\n 'result': True},\n ]\n\n @pytest.mark.parametrize('inputs', isomorphic_permutations)\n def test_isomorphic_perumtations(self, inputs):\n \"\"\"Test all of the different combinations of matching levels between benzene with and without the aromatic bonds\n defined\"\"\"\n # get benzene with all aromatic atoms/bonds labeled\n benzene = Molecule.from_smiles('c1ccccc1')\n # get benzene with no aromatic labels\n benzene_no_aromatic = create_benzene_no_aromatic()\n # now test all of the variations\n assert Molecule.are_isomorphic(benzene, benzene_no_aromatic, aromatic_matching=inputs['aromatic_matching'],\n formal_charge_matching=inputs['formal_charge_matching'],\n bond_order_matching=inputs['bond_order_matching'],\n atom_stereochemistry_matching=inputs['atom_stereochemistry_matching'],\n bond_stereochemistry_matching=inputs['bond_stereochemistry_matching'])[0] is inputs['result']\n\n def test_remap(self):\n \"\"\"Test the remap function which should return a new molecule in the requested ordering\"\"\"\n # the order here is CCO\n ethanol = create_ethanol()\n # get ethanol in reverse order OCC\n ethanol_reverse = create_reversed_ethanol()\n # get the mapping between the molecules\n mapping = Molecule.are_isomorphic(ethanol, ethanol_reverse, True)[1]\n ethanol.add_bond_charge_virtual_site([0, 1], 0.3 * unit.angstrom)\n # make sure that molecules with virtual sites raises an error\n with pytest.raises(NotImplementedError):\n remapped = ethanol.remap(mapping, current_to_new=True)\n\n # remake with no virtual site and remap to match the reversed ordering\n ethanol = create_ethanol()\n\n new_ethanol = ethanol.remap(mapping, current_to_new=True)\n\n def assert_molecules_match_after_remap(mol1, mol2):\n \"\"\"Check all of the attributes in a molecule match after being remapped\"\"\"\n for atoms in zip(mol1.atoms, mol2.atoms):\n assert atoms[0].to_dict() == atoms[1].to_dict()\n # bonds will not be in the same order in the molecule and the atom1 and atom2 indecies could be out of order\n # make a dict to compare them both\n remapped_bonds = dict(((bond.atom1_index, bond.atom2_index), bond) for bond in mol2.bonds)\n for bond in mol1.bonds:\n key = (bond.atom1_index, bond.atom2_index)\n if key not in remapped_bonds:\n key = tuple(reversed(key))\n assert key in remapped_bonds\n # now compare each attribute of the bond except the atom indexes\n bond_dict = bond.to_dict()\n del bond_dict['atom1']\n del bond_dict['atom2']\n remapped_bond_dict = remapped_bonds[key].to_dict()\n del remapped_bond_dict['atom1']\n del remapped_bond_dict['atom2']\n assert mol1.n_bonds == mol2.n_bonds\n assert mol1.n_angles == mol2.n_angles\n assert mol1.n_propers == mol2.n_propers\n assert mol1.n_impropers == mol2.n_impropers\n assert mol1.total_charge == mol2.total_charge\n assert mol1.partial_charges.all() == mol2.partial_charges.all()\n\n # check all of the properties match as well, torsions and impropers will be in a different order\n # due to the bonds being out of order\n assert_molecules_match_after_remap(new_ethanol, ethanol_reverse)\n\n # test round trip (double remapping a molecule)\n new_ethanol = ethanol.remap(mapping, current_to_new=True)\n isomorphic, round_trip_mapping = Molecule.are_isomorphic(new_ethanol, ethanol, return_atom_map=True)\n assert isomorphic is True\n round_trip_ethanol = new_ethanol.remap(round_trip_mapping, current_to_new=True)\n assert_molecules_match_after_remap(round_trip_ethanol, ethanol)\n\n @requires_openeye\n def test_canonical_ordering_openeye(self):\n \"\"\"Make sure molecules are returned in canonical ordering of openeye\"\"\"\n from openforcefield.utils.toolkits import OpenEyeToolkitWrapper\n\n openeye = OpenEyeToolkitWrapper()\n # get ethanol in canonical order\n ethanol = create_ethanol()\n # get reversed non canonical ethanol\n reversed_ethanol = create_reversed_ethanol()\n # get the canonical ordering\n canonical_ethanol = reversed_ethanol.canonical_order_atoms(openeye)\n # make sure the mapping between the ethanol and the openeye ref canonical form is the same\n assert (True, {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8}) == Molecule.are_isomorphic(canonical_ethanol,\n ethanol, True)\n\n @requires_rdkit\n def test_canonical_ordering_rdkit(self):\n \"\"\"Make sure molecules are returned in canonical ordering of the RDKit\"\"\"\n from openforcefield.utils.toolkits import RDKitToolkitWrapper\n\n rdkit = RDKitToolkitWrapper()\n # get ethanol in canonical order\n ethanol = create_ethanol()\n # get reversed non canonical ethanol\n reversed_ethanol = create_reversed_ethanol()\n # get the canonical ordering\n canonical_ethanol = reversed_ethanol.canonical_order_atoms(rdkit)\n # make sure the mapping between the ethanol and the rdkit ref canonical form is the same\n assert (True, {0: 2, 1: 0, 2: 1, 3: 8, 4: 3, 5: 4, 6: 5, 7: 6, 8: 7}) == Molecule.are_isomorphic(canonical_ethanol,\n ethanol,\n True)\n\n def test_too_small_remap(self):\n \"\"\"Make sure remap fails if we do not supply enough indexes\"\"\"\n ethanol = Molecule.from_file(get_data_file_path('molecules/ethanol.sdf'))\n # catch mappings that are the wrong size\n too_small_mapping = {0: 1}\n with pytest.raises(ValueError):\n new_ethanol = ethanol.remap(too_small_mapping, current_to_new=True)\n\n def test_wrong_index_mapping(self):\n \"\"\"Make sure the remap fails when the indexing starts from the wrong value\"\"\"\n ethanol = Molecule.from_file(get_data_file_path('molecules/ethanol.sdf'))\n mapping = {0: 2, 1: 1, 2: 0, 3: 6, 4: 7, 5: 8, 6: 4, 7: 5, 8: 3}\n wrong_index_mapping = dict((i + 10, new_id) for i, new_id in enumerate(mapping.values()))\n with pytest.raises(IndexError):\n new_ethanol = ethanol.remap(wrong_index_mapping, current_to_new=True)\n\n @requires_rdkit\n def test_from_pdb_and_smiles(self):\n \"\"\"Test the ability to make a valid molecule using RDKit and SMILES together\"\"\"\n # try and make a molecule from a pdb and smiles that don't match\n with pytest.raises(InvalidConformerError):\n mol = Molecule.from_pdb_and_smiles(get_data_file_path('molecules/toluene.pdb'), 'CC')\n\n # make a molecule from the toluene pdb file and the correct smiles\n mol = Molecule.from_pdb_and_smiles(get_data_file_path('molecules/toluene.pdb'), 'Cc1ccccc1')\n\n # make toluene from the sdf file\n mol_sdf = Molecule.from_file(get_data_file_path('molecules/toluene.sdf'))\n # get the mapping between them and compare the properties\n isomorphic, atom_map = Molecule.are_isomorphic(mol, mol_sdf, return_atom_map=True)\n assert isomorphic is True\n for pdb_atom, sdf_atom in atom_map.items():\n assert mol.atoms[pdb_atom].to_dict() == mol_sdf.atoms[sdf_atom].to_dict()\n # check bonds match, however there order might not\n sdf_bonds = dict(((bond.atom1_index, bond.atom2_index), bond) for bond in mol_sdf.bonds)\n for bond in mol.bonds:\n key = (atom_map[bond.atom1_index], atom_map[bond.atom2_index])\n if key not in sdf_bonds:\n key = tuple(reversed(key))\n assert key in sdf_bonds\n # now compare the attributes\n assert bond.is_aromatic == sdf_bonds[key].is_aromatic\n assert bond.stereochemistry == sdf_bonds[key].stereochemistry\n\n def test_to_qcschema(self):\n \"\"\"Test the ability to make and validate qcschema\"\"\"\n # the molecule has no coordinates so this should fail\n ethanol = Molecule.from_smiles('CCO')\n with pytest.raises(InvalidConformerError):\n qcschema = ethanol.to_qcschema()\n\n # now remake the molecule from the sdf\n ethanol = Molecule.from_file(get_data_file_path('molecules/ethanol.sdf'))\n # make sure that requests to missing conformers are caught\n with pytest.raises(InvalidConformerError):\n qcschema = ethanol.to_qcschema(conformer=1)\n # now make a valid qcschema and check its properties\n qcschema = ethanol.to_qcschema()\n # make sure the properties match\n charge = 0\n connectivity = [(0, 1, 1.0), (0, 3, 1.0), (0, 4, 1.0), (0, 5, 1.0), (1, 2, 1.0), (1, 6, 1.0), (1, 7, 1.0), (2, 8, 1.0)]\n symbols = ['C', 'C', 'O', 'H', 'H', 'H', 'H', 'H', 'H']\n assert charge == qcschema.molecular_charge\n assert connectivity == qcschema.connectivity\n assert symbols == qcschema.symbols.tolist()\n assert qcschema.geometry.all() == ethanol.conformers[0].in_units_of(unit.bohr).all()\n\n def test_from_qcschema_no_client(self):\n \"\"\"Test the ability to make molecules from QCArchive record instances and dicts\"\"\"\n\n import json\n\n # As the method can take a record instance or a dict with JSON encoding test both\n # test incomplete dict\n example_dict = {'name': 'CH4'}\n with pytest.raises(KeyError):\n mol = Molecule.from_qcschema(example_dict)\n\n # test an object that is not a record\n wrong_object = 'CH4'\n with pytest.raises(AttributeError):\n mol = Molecule.from_qcschema(wrong_object)\n\n with open(get_data_file_path('molecules/qcportal_molecules.json')) as json_file:\n # test loading the dict representation from a json file\n json_mol = json.load(json_file)\n mol = Molecule.from_qcschema(json_mol)\n # now make a molecule from the canonical smiles and make sure they are isomorphic\n can_mol = Molecule.from_smiles(json_mol['attributes']['canonical_isomeric_smiles'])\n assert mol.is_isomorphic_with(can_mol) is True\n\n client_examples = [{'dataset': 'TorsionDriveDataset', 'name': 'Fragment Stability Benchmark', 'index':\n 'CC(=O)Nc1cc2c(cc1OC)nc[n:4][c:3]2[NH:2][c:1]3ccc(c(c3)Cl)F'},\n {'dataset': 'TorsionDriveDataset', 'name': 'OpenFF Fragmenter Phenyl Benchmark', 'index':\n 'c1c[ch:1][c:2](cc1)[c:3](=[o:4])o'},\n {'dataset': 'TorsionDriveDataset', 'name': 'OpenFF Full TorsionDrive Benchmark 1', 'index':\n '0'},\n {'dataset': 'TorsionDriveDataset', 'name': 'OpenFF Group1 Torsions', 'index':\n 'c1c[ch:1][c:2](cc1)[ch2:3][c:4]2ccccc2'},\n {'dataset': 'OptimizationDataset', 'name': 'Kinase Inhibitors: WBO Distributions', 'index':\n 'cc1ccc(cc1nc2nccc(n2)c3cccnc3)nc(=o)c4ccc(cc4)cn5ccn(cc5)c-0'},\n {'dataset': 'OptimizationDataset', 'name': 'SMIRNOFF Coverage Set 1', 'index':\n 'coc(o)oc-0'},\n {'dataset': 'GridOptimizationDataset', 'name': 'OpenFF Trivalent Nitrogen Set 1', 'index':\n 'b1(c2c(ccs2)-c3ccsc3n1)c4c(c(c(c(c4f)f)f)f)f'},\n {'dataset': 'GridOptimizationDataset', 'name': 'OpenFF Trivalent Nitrogen Set 1', 'index':\n 'C(#N)N'}\n ]\n\n @pytest.mark.parametrize('input_data', client_examples)\n def test_from_qcschema_with_client(self, input_data):\n \"\"\"For each of the examples try and make a offmol using the instance and dict and check they match\"\"\"\n\n import qcportal as ptl\n client = ptl.FractalClient()\n ds = client.get_collection(input_data['dataset'], input_data['name'])\n entry = ds.get_entry(input_data['index'])\n # now make the molecule from the record instance with and without the geometry\n mol_from_dict = Molecule.from_qcschema(entry.dict(encoding='json'))\n # make the molecule again with the geometries attached\n mol_from_instance = Molecule.from_qcschema(entry, client)\n if hasattr(entry, 'initial_molecules'):\n assert mol_from_instance.n_conformers == len(entry.initial_molecules)\n else:\n # opt records have one initial molecule\n assert mol_from_instance.n_conformers == 1\n\n # now make a molecule from the smiles and make sure they are isomorphic\n mol_from_smiles = Molecule.from_smiles(entry.attributes['canonical_explicit_hydrogen_smiles'], True)\n\n assert mol_from_dict.is_isomorphic_with(mol_from_smiles) is True\n\n def test_qcschema_round_trip(self):\n \"\"\"Test making a molecule from qcschema then converting back\"\"\"\n\n # get a molecule qcschema\n import qcportal as ptl\n client = ptl.FractalClient()\n ds = client.get_collection('OptimizationDataset', 'SMIRNOFF Coverage Set 1')\n # grab an entry from the optimization data set\n entry = ds.get_entry('coc(o)oc-0')\n # now make the molecule from the record instance with the geometry\n mol = Molecule.from_qcschema(entry, client)\n # now grab the initial molecule record\n qca_mol = client.query_molecules(id=entry.initial_molecule)[0]\n # mow make sure the majority of the qcschema attributes are the same\n # note we can not compare the full dict due to qcelemental differences\n qcschema = mol.to_qcschema()\n assert qcschema.atom_labels.tolist() == qca_mol.atom_labels.tolist()\n assert qcschema.symbols.tolist() == qca_mol.symbols.tolist()\n # due to conversion useing different programs there is a slight difference here\n assert qcschema.geometry.flatten().tolist() == pytest.approx(qca_mol.geometry.flatten().tolist(), rel=1.0e-5)\n assert qcschema.connectivity == qca_mol.connectivity\n assert qcschema.atomic_numbers.tolist() == qca_mol.atomic_numbers.tolist()\n assert qcschema.fragment_charges == qca_mol.fragment_charges\n assert qcschema.fragment_multiplicities == qca_mol.fragment_multiplicities\n assert qcschema.fragments[0].tolist() == qca_mol.fragments[0].tolist()\n assert qcschema.mass_numbers.tolist() == qca_mol.mass_numbers.tolist()\n assert qcschema.name == qca_mol.name\n assert qcschema.masses.all() == qca_mol.masses.all()\n assert qcschema.molecular_charge == qca_mol.molecular_charge\n assert qcschema.molecular_multiplicity == qca_mol.molecular_multiplicity\n assert qcschema.real.all() == qca_mol.real.all()\n\n def test_from_mapped_smiles(self):\n \"\"\"Test making the molecule from issue #412 using both toolkits to ensure the issue\n is fixed.\"\"\"\n\n # there should be no undefined sterochmeistry error when making the molecule\n mol = Molecule.from_mapped_smiles('[H:14][c:1]1[c:3]([c:7]([c:11]([c:8]([c:4]1[H:17])[H:21])[C:13]([H:24])([H:25])[c:12]2[c:9]([c:5]([c:2]([c:6]([c:10]2[H:23])[H:19])[H:15])[H:18])[H:22])[H:20])[H:16]')\n assert mol.n_atoms == 25\n # make sure the atom map is not exposed\n with pytest.raises(KeyError):\n mapping = mol._properties['atom_map']\n\n @pytest.mark.parametrize('molecule', mini_drug_bank())\n def test_n_particles(self, molecule):\n \"\"\"Test n_particles property\"\"\"\n n_particles = sum([1 for particle in molecule.particles])\n assert n_particles == molecule.n_particles\n\n @pytest.mark.parametrize('molecule', mini_drug_bank())\n def test_n_atoms(self, molecule):\n \"\"\"Test n_atoms property\"\"\"\n n_atoms = sum([1 for atom in molecule.atoms])\n assert n_atoms == molecule.n_atoms\n\n @pytest.mark.parametrize('molecule', mini_drug_bank())\n def test_n_virtual_sites(self, molecule):\n \"\"\"Test n_virtual_sites property\"\"\"\n n_virtual_sites = sum([1 for virtual_site in molecule.virtual_sites])\n assert n_virtual_sites == molecule.n_virtual_sites\n\n @pytest.mark.parametrize('molecule', mini_drug_bank())\n def test_n_bonds(self, molecule):\n \"\"\"Test n_bonds property\"\"\"\n n_bonds = sum([1 for bond in molecule.bonds])\n assert n_bonds == molecule.n_bonds\n\n @pytest.mark.parametrize('molecule', mini_drug_bank())\n def test_angles(self, molecule):\n \"\"\"Test angles property\"\"\"\n for angle in molecule.angles:\n assert angle[0].is_bonded_to(angle[1])\n assert angle[1].is_bonded_to(angle[2])\n\n @pytest.mark.parametrize('molecule', mini_drug_bank())\n def test_propers(self, molecule):\n \"\"\"Test propers property\"\"\"\n for proper in molecule.propers:\n # The bonds should be in order 0-1-2-3 unless the\n # atoms form a three- or four-membered ring.\n is_chain = proper[0].is_bonded_to(proper[1])\n is_chain &= proper[1].is_bonded_to(proper[2])\n is_chain &= proper[2].is_bonded_to(proper[3])\n is_chain &= not proper[0].is_bonded_to(proper[2])\n is_chain &= not proper[0].is_bonded_to(proper[3])\n is_chain &= not proper[1].is_bonded_to(proper[3])\n\n assert (is_chain or\n is_three_memebered_ring_torsion(proper) or\n is_four_memebered_ring_torsion(proper))\n\n @pytest.mark.parametrize('molecule', mini_drug_bank())\n def test_impropers(self, molecule):\n \"\"\"Test impropers property\"\"\"\n for improper in molecule.impropers:\n assert improper[0].is_bonded_to(improper[1])\n assert improper[1].is_bonded_to(improper[2])\n assert improper[1].is_bonded_to(improper[3])\n\n # The non-central atoms can be connected only if\n # the improper atoms form a three-membered ring.\n is_not_cyclic = not((improper[0].is_bonded_to(improper[2])) or\n (improper[0].is_bonded_to(improper[3])) or\n (improper[2].is_bonded_to(improper[3])))\n assert is_not_cyclic or is_three_memebered_ring_torsion(improper)\n\n @pytest.mark.parametrize('molecule', mini_drug_bank())\n def test_torsions(self, molecule):\n \"\"\"Test torsions property\"\"\"\n # molecule.torsions should be exactly equal to the union of propers and impropers.\n assert set(molecule.torsions) == set(molecule.propers) | set(molecule.impropers)\n\n # The intersection of molecule.propers and molecule.impropers should be largely null.\n # The only exception is for molecules containing 3-membered rings (e.g., DrugBank_5514).\n common_torsions = molecule.propers & molecule.impropers\n if len(common_torsions) > 0:\n for torsion in common_torsions:\n assert is_three_memebered_ring_torsion(torsion)\n\n @pytest.mark.parametrize('molecule', mini_drug_bank())\n def test_total_charge(self, molecule):\n \"\"\"Test total charge\"\"\"\n total_charge = sum([atom.formal_charge for atom in molecule.atoms])\n assert total_charge == molecule.total_charge\n\n # ----------------------------------------------------\n # Test magic methods.\n # ----------------------------------------------------\n\n def test_equality(self):\n \"\"\"Test equality operator\"\"\"\n molecules = mini_drug_bank()\n nmolecules = len(molecules)\n # TODO: Performance improvements should let us un-restrict this test\n for i in range(nmolecules):\n for j in range(i, min(i+3, nmolecules)):\n assert (molecules[i] == molecules[j]) == (i == j)\n\n # ----------------------\n # Test Molecule methods.\n # ----------------------\n\n def test_add_conformers(self):\n \"\"\"Test addition of conformers to a molecule\"\"\"\n import numpy as np\n from simtk import unit\n # Define a methane molecule\n molecule = Molecule()\n molecule.name = 'methane'\n C = molecule.add_atom(6, 0, False)\n H1 = molecule.add_atom(1, 0, False)\n H2 = molecule.add_atom(1, 0, False)\n H3 = molecule.add_atom(1, 0, False)\n H4 = molecule.add_atom(1, 0, False)\n molecule.add_bond(C, H1, 1, False)\n molecule.add_bond(C, H2, 1, False)\n molecule.add_bond(C, H3, 1, False)\n molecule.add_bond(C, H4, 1, False)\n\n assert molecule.n_conformers == 0\n # Add a conformer that should work\n conf1 = unit.Quantity(np.array([[ 1., 2.,3.] ,[4. ,5. ,6.],[7., 8., 9.],\n [10.,11.,12.],[13.,14.,15]]),\n unit.angstrom)\n molecule.add_conformer(conf1)\n assert molecule.n_conformers == 1\n\n conf2 = unit.Quantity(np.array([[101., 102. ,103.], [104. ,105. ,106.], [107., 108., 109.],\n [110.,111.,112.], [113.,114.,115]]),\n unit.angstrom)\n molecule.add_conformer(conf2)\n assert molecule.n_conformers == 2\n\n # Add conformers with too few coordinates\n conf_missing_z = unit.Quantity(np.array([[101., 102. ,103.], [104. ,105. ,106.], [107., 108., 109.],\n [110.,111.,112.], [113.,114.]]),\n unit.angstrom)\n with pytest.raises(Exception) as excinfo:\n molecule.add_conformer(conf_missing_z)\n\n conf_too_few_atoms = unit.Quantity(np.array([[101., 102. ,103.], [104. ,105. ,106.], [107., 108., 109.],\n [110.,111.,112.]]),\n unit.angstrom)\n with pytest.raises(Exception) as excinfo:\n molecule.add_conformer(conf_too_few_atoms)\n\n\n # Add a conformer with too many coordinates\n conf_too_many_atoms = unit.Quantity(np.array([[101., 102., 103.], [104., 105., 106.], [107., 108., 109.],\n [110., 111., 112.], [113., 114., 115.], [116., 117., 118.]]),\n unit.angstrom)\n with pytest.raises(Exception) as excinfo:\n molecule.add_conformer(conf_too_many_atoms)\n\n # Add a conformer with no coordinates\n conf_no_coordinates = unit.Quantity(np.array([]),\n unit.angstrom)\n with pytest.raises(Exception) as excinfo:\n molecule.add_conformer(conf_no_coordinates)\n\n # Add a conforer with units of nanometers\n conf3 = unit.Quantity(np.array([[ 1., 2.,3.] ,[4. ,5. ,6.],[7., 8., 9.],\n [10.,11.,12.],[13.,14.,15]]),\n unit.nanometer)\n molecule.add_conformer(conf3)\n assert molecule.n_conformers == 3\n assert molecule.conformers[2][0][0] == 10. * unit.angstrom\n\n # Add a conformer with units of nanometers\n conf_nonsense_units = unit.Quantity(np.array([[ 1., 2.,3.] ,[4. ,5. ,6.],[7., 8., 9.],\n [10.,11.,12.],[13.,14.,15]]),\n unit.joule)\n with pytest.raises(Exception) as excinfo:\n molecule.add_conformer(conf_nonsense_units)\n\n # Add a conformer with no units\n conf_unitless = np.array([[ 1., 2.,3.] ,[4. ,5. ,6.],[7., 8., 9.],\n [10.,11.,12.],[13.,14.,15]])\n with pytest.raises(Exception) as excinfo:\n molecule.add_conformer(conf_unitless)\n\n @pytest.mark.parametrize('molecule', mini_drug_bank())\n def test_add_atoms_and_bonds(self, molecule):\n \"\"\"Test the creation of a molecule from the addition of atoms and bonds\"\"\"\n molecule_copy = Molecule()\n for atom in molecule.atoms:\n molecule_copy.add_atom(atom.atomic_number, atom.formal_charge, atom.is_aromatic, stereochemistry=atom.stereochemistry)\n for bond in molecule.bonds:\n molecule_copy.add_bond(bond.atom1_index, bond.atom2_index, bond.bond_order, bond.is_aromatic,\n stereochemistry=bond.stereochemistry,\n fractional_bond_order=bond.fractional_bond_order)\n # Try to add the final bond twice, which should raise an Exception\n with pytest.raises(Exception) as excinfo:\n molecule_copy.add_bond(bond.atom1_index, bond.atom2_index, bond.bond_order, bond.is_aromatic,\n stereochemistry=bond.stereochemistry,\n fractional_bond_order=bond.fractional_bond_order)\n\n assert molecule == molecule_copy\n\n @pytest.mark.parametrize('molecule', mini_drug_bank())\n def test_add_virtual_site_units(self, molecule):\n \"\"\"\n Tests the unit type checking of the VirtualSite base class\n \"\"\"\n\n # TODO: Should these be using BondChargeVirtualSite, or should we just call the base class (which does the unit checks) directly?\n\n # Prepare values for unit checks\n distance_unitless = 0.4\n sigma_unitless = 0.1\n rmin_half_unitless = 0.2\n epsilon_unitless = 0.3\n charge_increments_unitless = [0.1, 0.2, 0.3, 0.4]\n distance = distance_unitless * unit.angstrom\n sigma = sigma_unitless * unit.angstrom\n rmin_half = rmin_half_unitless * unit.angstrom\n epsilon = epsilon_unitless * (unit.kilojoule / unit.mole)\n charge_increments = charge_increments_unitless * unit.elementary_charge\n\n # Do not modify the original molecule.\n molecule = copy.deepcopy(molecule)\n\n atom1 = molecule.atoms[0]\n atom2 = molecule.atoms[1]\n atom3 = molecule.atoms[2]\n atom4 = molecule.atoms[3]\n\n # Try to feed in unitless sigma\n with pytest.raises(Exception) as excinfo:\n molecule.add_bond_charge_virtual_site([atom1, atom2, atom3], distance, epsilon=epsilon, sigma=sigma_unitless)\n\n # Try to feed in unitless rmin_half\n with pytest.raises(Exception) as excinfo:\n molecule.add_bond_charge_virtual_site([atom1, atom2, atom3], distance, epsilon=epsilon, rmin_half=rmin_half_unitless)\n\n # Try to feed in unitless epsilon\n with pytest.raises(Exception) as excinfo:\n molecule.add_bond_charge_virtual_site([atom1, atom2, atom3], distance, epsilon=epsilon_unitless, sigma=sigma, rmin_half=rmin_half)\n\n # Try to feed in unitless charges\n with pytest.raises(Exception) as excinfo:\n molecule.add_bond_charge_virtual_site([atom1, atom2, atom3, atom4], distance, charge_incrtements=charge_increments_unitless)\n\n\n # We shouldn't be able to give both rmin_half and sigma VdW parameters.\n with pytest.raises(Exception) as excinfo:\n molecule.add_bond_charge_virtual_site([atom1, atom2, atom3], distance, epsilon=epsilon, sigma=sigma, rmin_half=rmin_half)\n\n # Try creating virtual site from sigma+epsilon\n vsite1_index = molecule.add_bond_charge_virtual_site([atom1, atom2, atom3], distance, epsilon=epsilon, sigma=sigma)\n # Try creating virutal site from rmin_half+epsilon\n vsite2_index = molecule.add_bond_charge_virtual_site([atom1, atom2, atom3], distance, epsilon=epsilon, rmin_half=rmin_half)\n\n # TODO: Test the @property getters for sigma, epsilon, and rmin_half\n\n # We should have to give as many charge increments as atoms (len(charge_increments)) = 4\n with pytest.raises(Exception) as excinfo:\n molecule.add_bond_charge_virtual_site([atom1, atom2, atom3], distance, charge_increments=charge_increments)\n\n vsite3_index = molecule.add_bond_charge_virtual_site([atom1, atom2, atom3, atom4], distance, charge_increments=charge_increments)\n\n @pytest.mark.parametrize('molecule', mini_drug_bank())\n def test_add_bond_charge_virtual_site(self, molecule):\n \"\"\"Test the addition of a BondChargeVirtualSite to a molecule.\n Also tests many of the inputs of the parent VirtualSite class\n \"\"\"\n # Do not modify the original molecule.\n molecule = copy.deepcopy(molecule)\n\n atom1 = molecule.atoms[0]\n atom2 = molecule.atoms[1]\n atom3 = molecule.atoms[2]\n atom4 = molecule.atoms[3]\n\n # Prepare values for unit checks\n distance_unitless = 0.4\n distance = distance_unitless * unit.angstrom\n\n\n # Try to feed in a unitless distance\n with pytest.raises(AssertionError) as excinfo:\n vsite1_index = molecule.add_bond_charge_virtual_site([atom1, atom2, atom3], distance_unitless)\n\n\n vsite1_index = molecule.add_bond_charge_virtual_site([atom1, atom2, atom3], distance)\n vsite1 = molecule.virtual_sites[vsite1_index]\n assert atom1 in vsite1.atoms\n assert atom2 in vsite1.atoms\n assert atom3 in vsite1.atoms\n assert vsite1 in atom1.virtual_sites\n assert vsite1 in atom2.virtual_sites\n assert vsite1 in atom3.virtual_sites\n assert vsite1.distance == distance\n\n # Make an \"everything bagel\" virtual site\n vsite2_index = molecule.add_bond_charge_virtual_site([atom1, atom2, atom3],\n distance,\n sigma=0.1*unit.angstrom,\n epsilon=1.0*unit.kilojoule_per_mole,\n charge_increments=unit.Quantity(np.array([0.1, 0.2, 0.3]),\n unit.elementary_charge)\n )\n vsite2 = molecule.virtual_sites[vsite2_index]\n\n # test serialization\n molecule_dict = molecule.to_dict()\n molecule2 = Molecule.from_dict(molecule_dict)\n\n assert hash(molecule) == hash(molecule2)\n\n # TODO: Make a test for to_dict and from_dict for VirtualSites (even though they're currently just unloaded using\n # (for example) Molecule._add_bond_virtual_site functions\n @pytest.mark.parametrize('molecule', mini_drug_bank())\n def test_add_monovalent_lone_pair_virtual_site(self, molecule):\n \"\"\"Test addition of a MonovalentLonePairVirtualSite to the Molecule\"\"\"\n # Do not modify the original molecule.\n molecule = copy.deepcopy(molecule)\n\n atom1 = molecule.atoms[0]\n atom2 = molecule.atoms[1]\n atom3 = molecule.atoms[2]\n atom4 = molecule.atoms[3]\n\n # Prepare values for unit checks\n distance_unitless = 0.3\n out_of_plane_angle_unitless = 30\n in_plane_angle_unitless = 0.2\n distance = distance_unitless * unit.angstrom\n out_of_plane_angle = out_of_plane_angle_unitless * unit.degree\n in_plane_angle = in_plane_angle_unitless * unit.radian\n\n # Try passing in a unitless distance\n with pytest.raises(AssertionError) as excinfo:\n vsite1_index = molecule.add_monovalent_lone_pair_virtual_site([atom1, atom2], distance_unitless, out_of_plane_angle, in_plane_angle)\n\n # Try passing in a unitless out_of_plane_angle\n with pytest.raises(AssertionError) as excinfo:\n vsite1_index = molecule.add_monovalent_lone_pair_virtual_site([atom1, atom2], distance, out_of_plane_angle_unitless, in_plane_angle)\n\n # Try passing in a unitless in_plane_angle\n with pytest.raises(AssertionError) as excinfo:\n vsite1_index = molecule.add_monovalent_lone_pair_virtual_site([atom1, atom2], distance, out_of_plane_angle, in_plane_angle_unitless)\n\n # Try giving two atoms\n with pytest.raises(AssertionError) as excinfo:\n vsite1_index = molecule.add_monovalent_lone_pair_virtual_site([atom1, atom2], distance, out_of_plane_angle, in_plane_angle)\n\n # Successfully make a virtual site\n vsite1_index = molecule.add_monovalent_lone_pair_virtual_site([atom1, atom2, atom3], distance, out_of_plane_angle, in_plane_angle)\n # TODO: Check if we get the same values back out from the @properties\n molecule_dict = molecule.to_dict()\n molecule2 = Molecule.from_dict(molecule_dict)\n assert molecule.to_dict() == molecule2.to_dict()\n\n @pytest.mark.parametrize('molecule', mini_drug_bank())\n def test_add_divalent_lone_pair_virtual_site(self, molecule):\n \"\"\"Test addition of a DivalentLonePairVirtualSite to the Molecule\"\"\"\n # Do not modify the original molecule.\n molecule = copy.deepcopy(molecule)\n\n atom1 = molecule.atoms[0]\n atom2 = molecule.atoms[1]\n atom3 = molecule.atoms[2]\n atom4 = molecule.atoms[3]\n distance = 0.3 * unit.angstrom\n out_of_plane_angle = 30 * unit.degree\n in_plane_angle = 0.2 * unit.radian\n vsite1_index = molecule.add_divalent_lone_pair_virtual_site([atom1, atom2, atom3], distance, out_of_plane_angle, in_plane_angle)\n with pytest.raises(AssertionError) as excinfo:\n vsite1_index = molecule.add_divalent_lone_pair_virtual_site([atom1, atom2], distance, out_of_plane_angle, in_plane_angle)\n molecule_dict = molecule.to_dict()\n molecule2 = Molecule.from_dict(molecule_dict)\n assert molecule_dict == molecule2.to_dict()\n\n @pytest.mark.parametrize('molecule', mini_drug_bank())\n def test_add_trivalent_lone_pair_virtual_site(self, molecule):\n \"\"\"Test addition of a TrivalentLonePairVirtualSite to the Molecule\"\"\"\n # Do not modify the original molecule.\n molecule = copy.deepcopy(molecule)\n\n atom1 = molecule.atoms[0]\n atom2 = molecule.atoms[1]\n atom3 = molecule.atoms[2]\n atom4 = molecule.atoms[3]\n distance = 0.3 * unit.angstrom\n out_of_plane_angle = 30 * unit.degree\n in_plane_angle = 0.2 * unit.radian\n vsite1_index = molecule.add_trivalent_lone_pair_virtual_site([atom1, atom2, atom3, atom4], distance, out_of_plane_angle, in_plane_angle)\n # Test for assertion when giving too few atoms\n with pytest.raises(AssertionError) as excinfo:\n vsite1_index = molecule.add_trivalent_lone_pair_virtual_site([atom1, atom2, atom3], distance, out_of_plane_angle, in_plane_angle)\n molecule_dict = molecule.to_dict()\n molecule2 = Molecule.from_dict(molecule_dict)\n assert molecule.to_dict() == molecule2.to_dict()\n\n @requires_openeye\n def test_chemical_environment_matches_OE(self):\n \"\"\"Test chemical environment matches\"\"\"\n # TODO: Move this to test_toolkits, test all available toolkits\n # Create chiral molecule\n from simtk.openmm.app import element\n toolkit_wrapper = OpenEyeToolkitWrapper()\n molecule = Molecule()\n atom_C = molecule.add_atom(element.carbon.atomic_number, 0, False, stereochemistry='R', name='C')\n atom_H = molecule.add_atom(element.hydrogen.atomic_number, 0, False, name='H')\n atom_Cl = molecule.add_atom(element.chlorine.atomic_number, 0, False, name='Cl')\n atom_Br = molecule.add_atom(element.bromine.atomic_number, 0, False, name='Br')\n atom_F = molecule.add_atom(element.fluorine.atomic_number, 0, False, name='F')\n molecule.add_bond(atom_C, atom_H, 1, False)\n molecule.add_bond(atom_C, atom_Cl, 1, False)\n molecule.add_bond(atom_C, atom_Br, 1, False)\n molecule.add_bond(atom_C, atom_F, 1, False)\n # Test known cases\n matches = molecule.chemical_environment_matches('[#6:1]', toolkit_registry=toolkit_wrapper)\n assert len(matches) == 1 # there should be a unique match, so one atom tuple is returned\n assert len(matches[0]) == 1 # it should have one tagged atom\n assert set(matches[0]) == set([atom_C])\n matches = molecule.chemical_environment_matches('[#6:1]~[#1:2]', toolkit_registry=toolkit_wrapper)\n assert len(matches) == 1 # there should be a unique match, so one atom tuple is returned\n assert len(matches[0]) == 2 # it should have two tagged atoms\n assert set(matches[0]) == set([atom_C, atom_H])\n matches = molecule.chemical_environment_matches('[Cl:1]-[C:2]-[H:3]', toolkit_registry=toolkit_wrapper)\n assert len(matches) == 1 # there should be a unique match, so one atom tuple is returned\n assert len(matches[0]) == 3 # it should have three tagged atoms\n assert set(matches[0]) == set([atom_Cl, atom_C, atom_H])\n matches = molecule.chemical_environment_matches('[#6:1]~[*:2]', toolkit_registry=toolkit_wrapper)\n assert len(matches) == 4 # there should be four matches\n for match in matches:\n assert len(match) == 2 # each match should have two tagged atoms\n\n # TODO: Test forgive undef amide enol stereo\n # TODO: test forgive undef phospho linker stereo\n # TODO: test forgive undef C=NH stereo\n # TODO: test forgive undef phospho stereo\n # Potentially better OE stereo check: OEFlipper — Toolkits - - Python\n # https: // docs.eyesopen.com / toolkits / python / omegatk / OEConfGenFunctions / OEFlipper.html\n\n @requires_rdkit\n def test_chemical_environment_matches_RDKit(self):\n \"\"\"Test chemical environment matches\"\"\"\n # Create chiral molecule\n from simtk.openmm.app import element\n toolkit_wrapper = RDKitToolkitWrapper()\n molecule = Molecule()\n atom_C = molecule.add_atom(element.carbon.atomic_number, 0, False, stereochemistry='R', name='C')\n atom_H = molecule.add_atom(element.hydrogen.atomic_number, 0, False, name='H')\n atom_Cl = molecule.add_atom(element.chlorine.atomic_number, 0, False, name='Cl')\n atom_Br = molecule.add_atom(element.bromine.atomic_number, 0, False, name='Br')\n atom_F = molecule.add_atom(element.fluorine.atomic_number, 0, False, name='F')\n molecule.add_bond(atom_C, atom_H, 1, False)\n molecule.add_bond(atom_C, atom_Cl, 1, False)\n molecule.add_bond(atom_C, atom_Br, 1, False)\n molecule.add_bond(atom_C, atom_F, 1, False)\n # Test known cases\n matches = molecule.chemical_environment_matches('[#6:1]', toolkit_registry=toolkit_wrapper)\n assert len(matches) == 1 # there should be a unique match, so one atom tuple is returned\n assert len(matches[0]) == 1 # it should have one tagged atom\n assert set(matches[0]) == set([atom_C])\n matches = molecule.chemical_environment_matches('[#6:1]~[#1:2]', toolkit_registry=toolkit_wrapper)\n assert len(matches) == 1 # there should be a unique match, so one atom tuple is returned\n assert len(matches[0]) == 2 # it should have two tagged atoms\n assert set(matches[0]) == set([atom_C, atom_H])\n matches = molecule.chemical_environment_matches('[Cl:1]-[C:2]-[H:3]', toolkit_registry=toolkit_wrapper)\n assert len(matches) == 1 # there should be a unique match, so one atom tuple is returned\n assert len(matches[0]) == 3 # it should have three tagged atoms\n assert set(matches[0]) == set([atom_Cl, atom_C, atom_H])\n matches = molecule.chemical_environment_matches('[#6:1]~[*:2]', toolkit_registry=toolkit_wrapper)\n assert len(matches) == 4 # there should be four matches\n for match in matches:\n assert len(match) == 2 # each match should have two tagged atoms\n\n @pytest.mark.slow\n def test_compute_partial_charges(self):\n \"\"\"Test computation/retrieval of partial charges\"\"\"\n # TODO: Test only one molecule for speed?\n # TODO: Do we need to deepcopy each molecule, or is setUp called separately for each test method?\n from simtk import unit\n import numpy as np\n\n # Do not modify original molecules.\n molecules = copy.deepcopy(mini_drug_bank())\n\n # Test a single toolkit at a time\n # Removed ['amber', 'amberff94'] from OE list, as those won't find the residue types they're expecting\n toolkit_to_charge_method = {OpenEyeToolkitWrapper:['mmff', 'mmff94', 'am1bcc', 'am1bccnosymspt', 'am1bccelf10'],\n AmberToolsToolkitWrapper:['bcc', 'gas', 'mul']}\n\n manual_skips = []\n\n manual_skips.append('ZINC1564378') # Warning: OEMMFF94Charges: assigning OEMMFFAtomTypes failed on mol .\n manual_skips.append('ZINC00265517') # Warning: OEMMFF94Charges: assigning OEMMFFAtomTypes failed on mol .\n\n for toolkit in list(toolkit_to_charge_method.keys()):\n toolkit_registry = ToolkitRegistry(toolkit_precedence=[toolkit])\n for charge_model in toolkit_to_charge_method[toolkit]:\n c = 0\n for molecule in molecules[:1]: # Just test first molecule to save time\n c += 1\n if molecule.name in manual_skips: # Manual skips, hopefully rare\n continue\n molecule.compute_partial_charges(charge_model=charge_model, toolkit_registry=toolkit_registry)\n charges1 = molecule._partial_charges\n # Make sure everything isn't 0s\n assert (abs(charges1 / unit.elementary_charge) > 0.01).any()\n # Check total charge\n charges_sum_unitless = charges1.sum() / unit.elementary_charge\n #if abs(charges_sum_unitless - float(molecule.total_charge)) > 0.0001:\n # print('c {} molecule {} charge_sum {} molecule.total_charge {}'.format(c, molecule.name,\n # charges_sum_unitless,\n # molecule.total_charge))\n # assert_almost_equal(charges_sum_unitless, molecule.total_charge, decimal=4)\n\n # Call should be faster second time due to caching\n # TODO: Implement caching\n molecule.compute_partial_charges(charge_model=charge_model, toolkit_registry=toolkit_registry)\n charges2 = molecule._partial_charges\n assert (np.allclose(charges1, charges2, atol=0.002))\n\n @requires_openeye\n def test_assign_fractional_bond_orders(self):\n \"\"\"Test assignment of fractional bond orders\n \"\"\"\n # TODO: Test only one molecule for speed?\n # TODO: Do we need to deepcopy each molecule, or is setUp called separately for each test method?\n\n # Do not modify the original molecules.\n molecules = copy.deepcopy(mini_drug_bank())\n\n toolkit_to_bondorder_method = {OpenEyeToolkitWrapper:['am1','pm3']}\n for toolkit in list(toolkit_to_bondorder_method.keys()):\n toolkit_registry = ToolkitRegistry(toolkit_precedence=[toolkit])\n for charge_model in toolkit_to_bondorder_method[toolkit]:\n for molecule in molecules[:5]: # Just test first five molecules for speed\n molecule.compute_wiberg_bond_orders(charge_model=charge_model, toolkit_registry=toolkit_registry)\n fbo1 = [bond.fractional_bond_order for bond in molecule.bonds]\n # Call should be faster the second time due to caching\n molecule.compute_wiberg_bond_orders(charge_model=charge_model, toolkit_registry=toolkit_registry)\n fbo2 = [bond.fractional_bond_order for bond in molecule.bonds]\n assert fbo1 == fbo2\n"
] |
[
[
"numpy.array",
"numpy.allclose"
]
] |
kponder/GMM
|
[
"e9b7d8f72ea253db6ca643a1a56c43763d46e8c2"
] |
[
"Car_convergence.py"
] |
[
"import numpy as np\nimport Convergence_testing as CT\nimport sys\n\ndata_file = sys.argv[1]\nsamples = np.loadtxt(data_file)\n\nlabels = [ \"$\\Omega_M$\", \"$\\Omega_L$\", \"$w$\", \"$\\sigma_{int}$\",\"$\\mathcal{M}$\"]\n\ny = np.linspace(0, 99, 100)\nCT.plotting(labels, y, samples, savefig = True)\n"
] |
[
[
"numpy.loadtxt",
"numpy.linspace"
]
] |
201419/PersonalCodeRepository
|
[
"e79ac1489fa424f1334e74aab74ea25d1246b40e"
] |
[
"optim/error-feedback-SGD/main.py"
] |
[
"\"\"\"\nScript containing the main functions to train and evaluate the models\nwith several optimizers. The results can be easily saved.\n\"\"\"\n\nfrom __future__ import print_function\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.backends.cudnn as cudnn\n\nimport torchvision\nimport torchvision.transforms as transforms\n\nimport os\nimport argparse\n\nfrom models import VGG, ResNet18, PreActResNet18, GoogLeNet, DenseNet121, ResNeXt29_2x64d, MobileNet, MobileNetV2, \\\n DPN92, ShuffleNetG2, SENet18, ShuffleNetV2\nfrom optimizers.ErrorFeedbackSGD import ErrorFeedbackSGD\nfrom optimizers.TemporarilyAddMemory import TemporarilyAddMemory\nfrom utils.progress_bar import progress_bar\nfrom utils.pickle import save_obj, load_obj, make_directory, make_file_directory\n\n\ndef load_data(dataset='cifar10', batch_size=128):\n \"\"\"\n Loads the required dataset —— 加载数据集\n :param dataset: Can be either 'cifar10' or 'cifar100'\n :param batch_size: The desired batch size\n :return: Tuple (train_loader, test_loader, num_classes)\n \"\"\"\n print('==> Preparing data..')\n transform_train = transforms.Compose([\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n ])\n\n transform_test = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n ])\n\n if dataset == 'cifar10':\n # classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')\n num_classes = 10\n trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform_train)\n testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform_test)\n elif dataset == 'cifar100':\n num_classes = 100\n trainset = torchvision.datasets.CIFAR100(root='./data', train=True, download=True, transform=transform_train)\n testset = torchvision.datasets.CIFAR100(root='./data', train=False, download=True, transform=transform_test)\n else:\n raise ValueError('Only cifar 10 and cifar 100 are supported')\n\n trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size, shuffle=True, num_workers=2)\n testloader = torch.utils.data.DataLoader(testset, batch_size=100, shuffle=False, num_workers=2)\n\n return trainloader, testloader, num_classes\n\n\ndef build_model(device, model_name, num_classes=10):\n \"\"\"构建模型:vgg、vggnonorm、resnet、preactresnet、googlenet、densenet、\n resnext、mobilenet、mobilenetv2、dpn、shufflenetg2、senet、shufflenetv2\n\n :param device: 'cuda' if you have a GPU, 'cpu' otherwise\n :param model_name: One of the models available in the folder 'models'\n :param num_classes: 10 or 100 depending on the chosen dataset\n :return: The model architecture\n \"\"\"\n print('==> Building model..')\n model_name = model_name.lower()\n if model_name == 'vgg':\n net = VGG('VGG19', num_classes=num_classes)\n elif model_name == 'vggnonorm':\n net = VGG('VGG19', num_classes=num_classes, batch_norm=False)\n elif model_name == 'resnet':\n net = ResNet18(num_classes=num_classes)\n elif model_name == 'preactresnet':\n net = PreActResNet18()\n elif model_name == 'googlenet':\n net = GoogLeNet()\n elif model_name == 'densenet':\n net = DenseNet121()\n elif model_name == 'resnext':\n net = ResNeXt29_2x64d()\n elif model_name == 'mobilenet':\n net = MobileNet()\n elif model_name == 'mobilenetv2':\n net = MobileNetV2()\n elif model_name == 'dpn':\n net = DPN92()\n elif model_name == 'shufflenetg2':\n net = ShuffleNetG2()\n elif model_name == 'senet':\n net = SENet18()\n elif model_name == 'shufflenetv2':\n net = ShuffleNetV2(1)\n else:\n raise ValueError('Error: the specified model is incorrect ({})'.format(model_name))\n\n net = net.to(device)\n if device == 'cuda':\n net = torch.nn.DataParallel(net)\n cudnn.benchmark = True\n return net\n\n\ndef load_checkpoint(net, name):\n \"\"\"Load saved weights to a given net.\n \"\"\"\n print('==> Resuming from checkpoint..')\n if not os.path.isdir('checkpoints'):\n raise Exception('Error: no checkpoint directory found!')\n checkpoint = torch.load('./checkpoints/' + name + '.t7')\n net.load_state_dict(checkpoint['net'])\n start_epoch = checkpoint['epoch']\n best_acc = checkpoint['acc']\n return start_epoch, best_acc\n\n\ndef create_optimizer(net, comp, memory, noscale, lr=0.1, momentum=0.9, weight_decay=5e-4):\n \"\"\"优化器:ErrorFeedbackSGD 和 SGD\n\n Creates the right optimizer regarding to the parameters and attach it to the net's parameters.\n :param net: The net to optimize.\n :param comp: Bool (True = scaled sign compression, False = no comp)\n :param memory: If there is a compression whether to have a feedback loop or not\n :param noscale: If True the compression operator is unscaled sign (if the compression is existing)\n :param lr: Initial learning rate of the optimizer.\n :param momentum: Momentum of the optimizer.\n :param weight_decay: Weight decay of the optimizer.\n :return: A Pytorch optimizer.\n \"\"\"\n if memory and not comp:\n raise ValueError('The memory option is activated without the compression operator')\n if comp:\n comp = 'scaled_sign'\n if noscale:\n comp = 'sign'\n optimizer = ErrorFeedbackSGD(net.parameters(), lr=lr, momentum=momentum, weight_decay=weight_decay,\n comp=comp, memory=memory)\n else:\n optimizer = optim.SGD(net.parameters(), lr=lr, momentum=momentum, weight_decay=weight_decay)\n return optimizer\n\n\n# -------------------------------------------------------\n\ndef train(net, trainloader, device, optimizer, criterion, memory_back=False):\n \"\"\"One epoch training of a network.\n \n :param net: The given network.\n :param trainloader: Pytorch DataLoader (train set)\n :param device: Either 'cuda' or 'cpu'\n :param optimizer: The used optimizer.\n :param criterion: The loss function.\n :param memory_back: Whether or not for each batch the memory of the optimizer (if it has one) should be \n temporarily added back to the net's parameters to compute the several metrics \n with these new parameters. It doesn't change the final net's parameters.\n \n :return: (train_loss, train_acc, train_loss_with_memory_back, train_acc_with_memory_back, \n L1/L2 norm ratio of the gradients, L1/L2 norm ratio of g)\n \"\"\"\n net.train()\n train_loss = 0\n mback_train_loss = 0\n correct = 0\n mback_correct = 0\n total = 0\n norm_ratio_val = 0\n corrected_norm_ratio_val = 0\n\n # -------------------------------------\n # Loop for training\n # -------------------------------------\n for batch_idx, (inputs, targets) in enumerate(trainloader):\n inputs, targets = inputs.to(device), targets.to(device)\n\n if memory_back:\n with TemporarilyAddMemory(optimizer): # import convex_opt\n outputs = net(inputs)\n loss = criterion(outputs, targets)\n mback_train_loss += loss.item()\n _, predicted = outputs.max(1)\n mback_correct += predicted.eq(targets).sum().item()\n\n # train using optimizer\n optimizer.zero_grad()\n outputs = net(inputs)\n loss = criterion(outputs, targets)\n loss.backward()\n optimizer.step()\n norm_ratio_val += optimizer.gradient_norms_ratio()\n corrected_norm_ratio_val += optimizer.corrected_gradient_norms_ratio()\n\n train_loss += loss.item() # loss value\n _, predicted = outputs.max(1)\n total += targets.size(0)\n correct += predicted.eq(targets).sum().item() # acc value\n\n progress_bar(batch_idx, len(trainloader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)'\n % (train_loss / (batch_idx + 1), 100. * correct / total, correct, total))\n\n loss = train_loss/(batch_idx + 1)\n acc = 100. * correct/total\n\n return loss, acc, mback_train_loss/(batch_idx + 1), 100. * mback_correct/total, norm_ratio_val/(batch_idx + 1), \\\n corrected_norm_ratio_val/(batch_idx + 1)\n\n\ndef test(net, testloader, device, optimizer, criterion, memory_back=False):\n \"\"\"One test evaluation of a network.\n \n :param net: The given network.\n :param testloader: Pytorch DataLoader (train set)\n :param device: Either 'cuda' or 'cpu'\n :param optimizer: The used optimizer.\n :param criterion: The loss function.\n :param memory_back: Whether or not for each batch the memory of the optimizer (if it has one) should be \n temporarily added back to the net's parameters to compute the several metrics \n with these new parameters. It doesn't change the final net's parameters.\n \n :return: (train_loss, train_acc, train_loss_with_memory_back, train_acc_with_memory_back)\n \"\"\"\n net.eval()\n test_loss = 0\n mback_test_loss = 0\n correct = 0\n mback_correct = 0\n total = 0\n\n # -------------------------------------\n # Loop for testing\n # -------------------------------------\n with torch.no_grad():\n for batch_idx, (inputs, targets) in enumerate(testloader):\n inputs, targets = inputs.to(device), targets.to(device)\n\n if memory_back:\n with TemporarilyAddMemory(optimizer):\n outputs = net(inputs)\n loss = criterion(outputs, targets)\n mback_test_loss += loss.item()\n _, predicted = outputs.max(1)\n mback_correct += predicted.eq(targets).sum().item()\n\n outputs = net(inputs)\n loss = criterion(outputs, targets)\n\n test_loss += loss.item()\n _, predicted = outputs.max(1)\n total += targets.size(0)\n correct += predicted.eq(targets).sum().item()\n\n progress_bar(batch_idx, len(testloader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)'\n % (test_loss / (batch_idx + 1), 100. * correct / total, correct, total))\n\n loss = test_loss / (batch_idx + 1)\n acc = 100. * correct / total\n\n return loss, acc, mback_test_loss / (batch_idx + 1), 100. * mback_correct / total\n\n\n# -------------------------------------------------------\n\ndef write_results(args, res):\n \"\"\"Write recorded training metrics to files.\n \n :param args: Training args.\n :param res: Results of the training.\n \"\"\"\n name = args['name']\n directory = './results/' + name\n print('Writing results ({})..'.format(name))\n make_directory(directory)\n\n save_obj(res['train_losses'], directory + '/train_losses')\n save_obj(res['train_accuracies'], directory + '/train_accuracies')\n save_obj(res['test_losses'], directory + '/test_losses')\n save_obj(res['test_accuracies'], directory + '/test_accuracies')\n if args['mback']:\n save_obj(res['memory_back_train_losses'], directory + '/memory_back_train_losses')\n save_obj(res['memory_back_train_accuracies'], directory + '/memory_back_train_accuracies')\n save_obj(res['memory_back_test_losses'], directory + '/memory_back_test_losses')\n save_obj(res['memory_back_test_accuracies'], directory + '/memory_back_test_accuracies')\n if args['mnorm']:\n save_obj(res['memory_norms'], directory + '/memory_norms')\n if args['norm_ratio']:\n save_obj(res['gradient_norm_ratios'], directory + '/gradient_norm_ratios')\n save_obj(res['corrected_norm_ratios'], directory + '/corrected_norm_ratios')\n\n open_mode = 'a' if args['resume'] else 'w'\n with open(directory + '/README.md', open_mode) as file:\n if args['resume']:\n file.write('\\n')\n for arg, val in args.items():\n file.write(str(arg) + ': ' + str(val) + '\\\\\\n')\n\n\ndef construct_and_train(name='last_model', dataset='cifar10', model='vgg', resume=False, epochs=100,\n lr=0.1, batch_size=128, momentum=0.9, weight_decay=5e-4,\n comp=False, noscale=False, memory=False, mnorm=False, mback=False, norm_ratio=False):\n \n \"\"\"Constructs a network, trains it, and optionally saves the results.\n \n :param name: Model name (using for saving)\n :param dataset: Either 'cifar10' or 'cifar100'\n :param model: Either 'vgg' or 'resnet'\n :param resume: Reload and resume a model whose training was stopped\n :param epochs: Number of epochs to train\n :param lr: Initial learning rate\n :param batch_size: Batch size\n :param momentum: Momentum of the optimizer\n :param weight_decay: Weight decay of the optimizer\n :param comp: Compression operator\n :param noscale: Doesn't scale the compression\n :param memory: Whether or not to add a memory (feedback loop) to the optimizer\n :param mnorm: Whether or not to save the memory norm\n :param mback: Whether or not to save metrics when the memory is added back to the net params\n :param norm_ratio: Whether or not to save norms ratios\n \"\"\"\n args = dict(name=name, dataset=dataset, model=model, resume=resume, epochs=epochs,\n lr=lr, batch_size=batch_size, momentum=momentum, weight_decay=weight_decay,\n comp=comp, noscale=noscale, memory=memory, mnorm=mnorm, mback=mback, norm_ratio=norm_ratio)\n\n trainloader, testloader, num_classes = load_data(dataset, batch_size)\n device = 'cuda' if torch.cuda.is_available() else 'cpu'\n net = build_model(device, model, num_classes)\n start_epoch = 0\n best_acc = 0\n if resume:\n start_epoch, best_acc = load_checkpoint(net, name)\n\n # 创建 优化器 和 损失函数\n optimizer = create_optimizer(net, comp, memory, noscale, lr=lr, momentum=momentum, weight_decay=weight_decay)\n criterion = nn.CrossEntropyLoss()\n\n res = dict(train_losses=[],\n train_accuracies=[],\n test_losses=[],\n test_accuracies=[],\n memory_norms=[],\n memory_back_train_losses=[],\n memory_back_train_accuracies=[],\n memory_back_test_losses=[],\n memory_back_test_accuracies=[],\n gradient_norm_ratios=[],\n corrected_norm_ratios=[])\n if resume: # 恢复备份\n path = './results/' + name\n res['train_losses'] = load_obj(path + '/train_losses')\n res['train_accuracies'] = load_obj(path + '/train_accuracies')\n res['test_losses'] = load_obj(path + '/test_losses')\n res['test_accuracies'] = load_obj(path + '/test_accuracies')\n if mback: # default = False\n res['memory_back_train_losses'] = load_obj(path + '/memory_back_train_losses')\n res['memory_back_train_accuracies'] = load_obj(path + '/memory_back_train_accuracies')\n res['memory_back_test_losses'] = load_obj(path + '/memory_back_test_losses')\n res['memory_back_test_accuracies'] = load_obj(path + '/memory_back_test_accuracies')\n if mnorm: # default = False\n res['memory_norms'] = load_obj(path + '/memory_norms')\n if norm_ratio: # default = False\n res['gradient_norm_ratios'] = load_obj(path + '/gradient_norm_ratios')\n res['corrected_norm_ratios'] = load_obj(path + '/corrected_norm_ratios')\n try:\n for epoch in range(start_epoch, start_epoch + epochs): # 默认 epochs 为 200\n print('\\nEpoch: %d' % epoch)\n\n # -------------------------------------\n # train and test\n # -------------------------------------\n train_loss, train_acc, mback_train_loss,\\\n mback_train_acc, norm_ratio_val, corrected_norm_ratio_val = train(net, trainloader, device, optimizer,\n criterion, memory_back=mback)\n test_loss, test_acc, mback_test_loss, mback_test_acc = test(net, testloader, device, optimizer,\n criterion, memory_back=mback)\n # -------------------------------------\n # save some variables\n # -------------------------------------\n res['train_losses'].append(train_loss)\n res['train_accuracies'].append(train_acc)\n res['test_losses'].append(test_loss)\n res['test_accuracies'].append(test_acc)\n if mback: # default = False\n res['memory_back_train_losses'].append(mback_train_loss)\n res['memory_back_train_accuracies'].append(mback_train_acc)\n res['memory_back_test_losses'].append(mback_test_loss)\n res['memory_back_test_accuracies'].append(mback_test_acc)\n if mnorm: # default = False\n res['memory_norms'].append(optimizer.memory_norm())\n if norm_ratio: # default = False\n res['gradient_norm_ratios'].append(norm_ratio_val)\n res['corrected_norm_ratios'].append(corrected_norm_ratio_val)\n \n # -------------------------------------\n # save best 'net' and 'acc' 'epoch'\n # -------------------------------------\n if test_acc > best_acc:\n print('Saving..')\n state = {\n 'net': net.state_dict(),\n 'acc': test_acc,\n 'epoch': epoch,\n }\n make_directory('./checkpoints/' + name)\n torch.save(state, './checkpoints/' + name + '.t7')\n best_acc = test_acc\n except KeyboardInterrupt:\n print('Interrupting..')\n finally:\n write_results(args, res)\n return res\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='PyTorch ef-signSGD experiments')\n parser.add_argument('--name', default='last_model', type=str, help='checkpoint name (default last_model)')\n parser.add_argument('--dataset', default='cifar10', type=str, help='Dataset (cifar 10 or 100)')\n parser.add_argument('--model', default='vgg', type=str, help='Model architecture')\n parser.add_argument('--resume', '-r', action='store_true', help='resume from checkpoint')\n parser.add_argument('--epochs', default=200, type=int, help='number of epochs')\n parser.add_argument('--lr', default=0.1, type=float, help='learning rate')\n parser.add_argument('--bs', default=128, type=int, help='batch size')\n parser.add_argument('--momentum', default=0.9, type=float, help='SGD momentum')\n parser.add_argument('--weight_decay', default=5e-4, type=float, help='SGD weight decay')\n parser.add_argument('--comp', action='store_true', help='apply the scaled sign compression operator')\n parser.add_argument('--noscale', action='store_true', help='apply only the sign compression operator')\n parser.add_argument('--memory', action='store_true', help='add a memory to the optimizer')\n parser.add_argument('--mnorm', action='store_true', help='computes the norm of the memory at each epoch')\n parser.add_argument('--mback', action='store_true', help='computes the train/test losses/accuracies by adding the'\n 'memory back')\n args = parser.parse_args()\n construct_and_train(name=args.name, dataset=args.dataset, model=args.model, resume=args.resume, epochs=args.epochs,\n lr=args.lr, batch_size=args.bs, momentum=args.momentum, weight_decay=args.weight_decay,\n comp=args.comp, noscale=args.noscale, memory=args.memory, mnorm=args.mnorm, mback=args.mback)"
] |
[
[
"torch.nn.CrossEntropyLoss",
"torch.load",
"torch.utils.data.DataLoader",
"torch.no_grad",
"torch.cuda.is_available",
"torch.nn.DataParallel",
"torch.save"
]
] |
lucasperin/WOTS
|
[
"88f09cf070839595190a3a495c4af8b0b8358172"
] |
[
"benchmark/gen_plot_bench.py"
] |
[
"from math import factorial as fac, sqrt, floor, log\nfrom functools import reduce, lru_cache\nfrom multiprocessing import Pool\nfrom itertools import product, chain\nfrom random import getrandbits\nfrom scipy.special import comb\n\n\nmyfile = \"src/Plot_Encoding_bench.cpp\"\nheader = \"\"\"\n#include <benchmark/benchmark.h>\n#include \"wots/ClassicWots.h\"\n#include \"wots/ConstantSumWots.h\"\n#include \"wots/VariantConstantSumWots.h\"\n#include \"wots/MConstantSumWots.h\"\n#include \"wots/BSConstantSumWots.h\"\n#include \"primitives/OpenSSLSha256.h\"\n#include \"primitives/OpenSSLSha512.h\"\n\n\ntemplate<class OTS>\nclass OTSFixture : public benchmark::Fixture, protected OpenSSLSha256 {\npublic:\n\tByteArray data;\n\tOTS ots;\n\tvirtual void SetUp(benchmark::State& state) {\n\t\tdata = hstoba(\"0102030F\");\n\t}\n};\n\"\"\"\n\ntemplate = \"\"\"\nBENCHMARK_TEMPLATE_F(OTSFixture, plot_{},{}<{}, {}, {}, {}>)(benchmark::State& state) {{ \n\tstd::vector<unsigned int> a;\n\tfor (auto _ : state){{\n\t\tdata = digest(data);\n\t\tbenchmark::DoNotOptimize(a = ots.genFingerprint(data));\n\t}}\n}}\n\n\"\"\"\n\ntail = \"BENCHMARK_MAIN();\"\n\n@lru_cache(maxsize=2**30)\ndef binomial(n, k):\n return comb(n, k, exact=True)\n\n\ndef T_len(blocks, maxi, block_sum=None):\n if block_sum is None:\n block_sum = maxi\n\n kmax = min(blocks, floor(block_sum / (maxi + 1)))\n t = 0\n\n for k in range(kmax + 1):\n t += (\n (-1) ** k\n * binomial(blocks, k)\n * binomial(block_sum - (maxi + 1) * k + blocks - 1, blocks - 1)\n )\n\n return t\n\ndef wrap2(t, n):\n res = []\n for s in range(n, 4000):\n tlen = T_len(t, n, s)\n if tlen < 1:\n break\n elif 257 > log(tlen, 2) > 256:\n res.append((t, n, s, t * n, log(tlen, 2)))\n return res\n\n\n\ndef gen_all(to_write, case=\"ConstantSumWots\", h=\"OpenSSLSha256\"):\n tn = product(range(16, 256), [(1 << w) - 1 for w in range(2, 10)])\n with Pool(processes=4) as pool:\n results = pool.starmap(wrap2, tn)\n for t, n, s, tsn, tlog in chain.from_iterable(results):\n to_write += template.format(str(t)+str(n)+str(s), case, h, n, t, s)\n return to_write\n\ndef gen_set(to_write, cases, params): \n for p in params:\n t = p[0]\n n = p[1]\n s = p[2]\n m = p[4]\n if(m==512):\n h=\"OpenSSLSha512\"\n else:\n h=\"OpenSSLSha256\"\n to_write += template.format(str(t)+str(n)+str(s), \"ConstantSumWots\", h, s, t, s)\n for c in cases:\n to_write += template.format(str(t)+str(n)+str(s)+c, c, h, n, t, s)\n return to_write\n\ndef gen_set(to_write, params): \n for p in params:\n t = p[0]\n n = p[1]\n s = p[2]\n m = p[4]\n if(m==512):\n h=\"OpenSSLSha512\"\n else:\n h=\"OpenSSLSha256\"\n to_write += template.format(str(t)+str(n)+str(s)+\"_0\", \"ConstantSumWots\", h, s, t, s)\n to_write += template.format(str(t)+str(n)+str(s)+\"_V\", \"VariantConstantSumWots\", h, int(n*1.2), t, s)\n to_write += template.format(str(t)+str(n)+str(s)+\"_G\", \"ConstantSumWots\", h, n, t, s)\n to_write += template.format(str(t)+str(n)+str(s)+\"_BS\", \"BSConstantSumWots\", h, n, t, s)\n to_write += template.format(str(t)+str(n)+str(s)+\"_M\", \"MConstantSumWots\", h, n, t, s)\n return to_write\n\nif __name__ == \"__main__\":\n \"\"\"\n Filter results with\n $ sort -k1n -k3n -k4n results.txt > filtered\n $ for i in {30..80}; do for j in {512..15}; do cat filtered | grep -i \"^ *$i *$j \" | head -1 | sed -e 's/\\..*//g' >> temp ; done; done\n \"\"\"\n\n CASES=[\n \"VariantConstantSumWots\",\n \"BSConstantSumWots\",\n \"MConstantSumWots\"\n ]\n\n PARAMS=[\n [ 30, 511 , 6008, 15330, 256 ],\n [ 31, 511 , 4626, 15841, 256 ],\n [ 32, 511 , 3840, 16352, 256 ],\n [ 33, 511 , 3274, 16863, 256 ],\n [ 34, 511 , 2836, 17374, 256 ],\n [ 34, 255 , 3106, 8670, 256 ],\n [ 35, 511 , 2485, 17885, 256 ],\n [ 35, 255 , 2582, 8925, 256 ],\n [ 36, 511 , 2196, 18396, 256 ],\n [ 36, 255 , 2235, 9180, 256 ],\n [ 37, 511 , 1956, 18907, 256 ],\n [ 37, 255 , 1972, 9435, 256 ],\n [ 38, 511 , 1755, 19418, 256 ],\n [ 38, 255 , 1761, 9690, 256 ],\n [ 38, 127 , 2167, 4826, 256 ],\n [ 39, 511 , 1584, 19929, 256 ],\n [ 39, 255 , 1586, 9945, 256 ],\n [ 39, 127 , 1722, 4953, 256 ],\n [ 40, 511 , 1437, 20440, 256 ],\n [ 40, 255 , 1438, 10200, 256 ],\n [ 40, 127 , 1502, 5080, 256 ],\n [ 41, 511 , 1312, 20951, 256 ],\n [ 41, 255 , 1312, 10455, 256 ],\n [ 41, 127 , 1344, 5207, 256 ],\n [ 42, 511 , 1203, 21462, 256 ],\n [ 42, 255 , 1203, 10710, 256 ],\n [ 42, 127 , 1219, 5334, 256 ],\n [ 43, 511 , 1108, 21973, 256 ],\n [ 43, 255 , 1108, 10965, 256 ],\n [ 43, 127 , 1116, 5461, 256 ],\n [ 44, 511 , 1025, 22484, 256 ],\n [ 44, 255 , 1025, 11220, 256 ],\n [ 44, 127 , 1029, 5588, 256 ],\n [ 45, 511 , 952, 22995, 256 ],\n [ 45, 255 , 952, 11475, 256 ],\n [ 45, 127 , 954, 5715, 256 ],\n [ 45, 63 , 1070, 2835, 256 ],\n [ 46, 511 , 887, 23506, 256 ],\n [ 46, 255 , 887, 11730, 256 ],\n [ 46, 127 , 888, 5842, 256 ],\n [ 46, 63 , 951, 2898, 256 ],\n [ 47, 511 , 829, 24017, 256 ],\n [ 47, 255 , 829, 11985, 256 ],\n [ 47, 127 , 830, 5969, 256 ],\n [ 47, 63 , 867, 2961, 256 ],\n [ 48, 511 , 778, 24528, 256 ],\n [ 48, 255 , 778, 12240, 256 ],\n [ 48, 127 , 778, 6096, 256 ],\n [ 48, 63 , 801, 3024, 256 ],\n [ 49, 511 , 732, 25039, 256 ],\n [ 49, 255 , 732, 12495, 256 ],\n [ 49, 127 , 732, 6223, 256 ],\n [ 49, 63 , 746, 3087, 256 ],\n [ 50, 511 , 690, 25550, 256 ],\n [ 50, 255 , 690, 12750, 256 ],\n [ 50, 127 , 690, 6350, 256 ],\n [ 50, 63 , 699, 3150, 256 ],\n [ 51, 511 , 653, 26061, 256 ],\n [ 51, 255 , 653, 13005, 256 ],\n [ 51, 127 , 653, 6477, 256 ],\n [ 51, 63 , 658, 3213, 256 ],\n [ 52, 511 , 619, 26572, 256 ],\n [ 52, 255 , 619, 13260, 256 ],\n [ 52, 127 , 619, 6604, 256 ],\n [ 52, 63 , 622, 3276, 256 ],\n [ 53, 511 , 588, 27083, 256 ],\n [ 53, 255 , 588, 13515, 256 ],\n [ 53, 127 , 588, 6731, 256 ],\n [ 53, 63 , 590, 3339, 256 ],\n [ 53, 31 , 722, 1643, 256 ],\n [ 54, 511 , 560, 27594, 256 ],\n [ 54, 255 , 560, 13770, 256 ],\n [ 54, 127 , 560, 6858, 256 ],\n [ 54, 63 , 561, 3402, 256 ],\n [ 54, 31 , 633, 1674, 256 ],\n [ 55, 511 , 534, 28105, 256 ],\n [ 55, 255 , 534, 14025, 256 ],\n [ 55, 127 , 534, 6985, 256 ],\n [ 55, 63 , 535, 3465, 256 ],\n [ 55, 31 , 581, 1705, 256 ],\n [ 56, 511 , 511, 28616, 256 ],\n [ 56, 255 , 510, 14280, 256 ],\n [ 56, 127 , 510, 7112, 256 ],\n [ 56, 63 , 511, 3528, 256 ],\n [ 56, 31 , 543, 1736, 256 ],\n [ 57, 255 , 488, 14535, 256 ],\n [ 57, 127 , 488, 7239, 256 ],\n [ 57, 63 , 489, 3591, 256 ],\n [ 57, 31 , 511, 1767, 256 ],\n [ 58, 255 , 468, 14790, 256 ],\n [ 58, 127 , 468, 7366, 256 ],\n [ 58, 63 , 469, 3654, 256 ],\n [ 58, 31 , 485, 1798, 256 ],\n [ 59, 255 , 450, 15045, 256 ],\n [ 59, 127 , 450, 7493, 256 ],\n [ 59, 63 , 450, 3717, 256 ],\n [ 59, 31 , 462, 1829, 256 ],\n [ 60, 255 , 433, 15300, 256 ],\n [ 60, 127 , 433, 7620, 256 ],\n [ 60, 63 , 433, 3780, 256 ],\n [ 60, 31 , 441, 1860, 256 ],\n [ 61, 255 , 417, 15555, 256 ],\n [ 61, 127 , 417, 7747, 256 ],\n [ 61, 63 , 417, 3843, 256 ],\n [ 61, 31 , 423, 1891, 256 ],\n [ 62, 255 , 402, 15810, 256 ],\n [ 62, 127 , 402, 7874, 256 ],\n [ 62, 63 , 402, 3906, 256 ],\n [ 62, 31 , 407, 1922, 256 ],\n [ 63, 255 , 388, 16065, 256 ],\n [ 63, 127 , 388, 8001, 256 ],\n [ 63, 63 , 388, 3969, 256 ],\n [ 63, 31 , 392, 1953, 256 ],\n [ 64, 255 , 375, 16320, 256 ],\n [ 64, 127 , 375, 8128, 256 ],\n [ 64, 63 , 375, 4032, 256 ],\n [ 64, 31 , 378, 1984, 256 ],\n [ 65, 255 , 363, 16575, 256 ],\n [ 65, 127 , 363, 8255, 256 ],\n [ 65, 63 , 363, 4095, 256 ],\n [ 65, 31 , 365, 2015, 256 ],\n [ 66, 255 , 352, 16830, 256 ],\n [ 66, 127 , 352, 8382, 256 ],\n [ 66, 63 , 352, 4158, 256 ],\n [ 66, 31 , 353, 2046, 256 ],\n [ 66, 15 , 442, 990, 256 ],\n [ 67, 255 , 341, 17085, 256 ],\n [ 67, 127 , 341, 8509, 256 ],\n [ 67, 63 , 341, 4221, 256 ],\n [ 67, 31 , 342, 2077, 256 ],\n [ 67, 15 , 400, 1005, 256 ],\n [ 68, 255 , 331, 17340, 256 ],\n [ 68, 127 , 331, 8636, 256 ],\n [ 68, 63 , 331, 4284, 256 ],\n [ 68, 31 , 332, 2108, 256 ],\n [ 68, 15 , 374, 1020, 256 ],\n [ 69, 255 , 322, 17595, 256 ],\n [ 69, 127 , 322, 8763, 256 ],\n [ 69, 63 , 322, 4347, 256 ],\n [ 69, 31 , 323, 2139, 256 ],\n [ 69, 15 , 354, 1035, 256 ],\n [ 70, 255 , 313, 17850, 256 ],\n [ 70, 127 , 313, 8890, 256 ],\n [ 70, 63 , 313, 4410, 256 ],\n [ 70, 31 , 314, 2170, 256 ],\n [ 70, 15 , 339, 1050, 256 ]\n]\n\n# [ 71, 255 , 305, 18105, 256 ],\n# [ 71, 127 , 305, 9017, 256 ],\n# [ 71, 63 , 305, 4473, 256 ],\n# [ 71, 31 , 305, 2201, 256 ],\n# [ 71, 15 , 325, 1065, 256 ],\n# [ 72, 255 , 297, 18360, 256 ],\n# [ 72, 127 , 297, 9144, 256 ],\n# [ 72, 63 , 297, 4536, 256 ],\n# [ 72, 31 , 297, 2232, 256 ],\n# [ 72, 15 , 313, 1080, 256 ],\n# [ 73, 255 , 290, 18615, 256 ],\n# [ 73, 127 , 290, 9271, 256 ],\n# [ 73, 63 , 290, 4599, 256 ],\n# [ 73, 31 , 290, 2263, 256 ],\n# [ 73, 15 , 303, 1095, 256 ],\n# [ 74, 255 , 283, 18870, 256 ],\n# [ 74, 127 , 283, 9398, 256 ],\n# [ 74, 63 , 283, 4662, 256 ],\n# [ 74, 31 , 283, 2294, 256 ],\n# [ 74, 15 , 293, 1110, 256 ],\n# [ 75, 255 , 276, 19125, 256 ],\n# [ 75, 127 , 276, 9525, 256 ],\n# [ 75, 63 , 276, 4725, 256 ],\n# [ 75, 31 , 276, 2325, 256 ],\n# [ 75, 15 , 285, 1125, 256 ],\n# [ 76, 255 , 270, 19380, 256 ],\n# [ 76, 127 , 270, 9652, 256 ],\n# [ 76, 63 , 270, 4788, 256 ],\n# [ 76, 31 , 270, 2356, 256 ],\n# [ 76, 15 , 277, 1140, 256 ],\n# [ 77, 255 , 264, 19635, 256 ],\n# [ 77, 127 , 264, 9779, 256 ],\n# [ 77, 63 , 264, 4851, 256 ],\n# [ 77, 31 , 264, 2387, 256 ],\n# [ 77, 15 , 270, 1155, 256 ],\n# [ 78, 255 , 258, 19890, 256 ],\n# [ 78, 127 , 258, 9906, 256 ],\n# [ 78, 63 , 258, 4914, 256 ],\n# [ 78, 31 , 258, 2418, 256 ],\n# [ 78, 15 , 263, 1170, 256 ],\n# [ 79, 127 , 252, 10033, 256 ],\n# [ 79, 63 , 252, 4977, 256 ],\n# [ 79, 31 , 252, 2449, 256 ],\n# [ 79, 15 , 257, 1185, 256 ],\n# [ 80, 127 , 247, 10160, 256 ],\n# [ 80, 63 , 247, 5040, 256 ],\n# [ 80, 31 , 247, 2480, 256 ],\n# [ 80, 15 , 251, 1200, 256 ]\n# ]\n\n\n to_write = header\n to_write = gen_set(to_write, PARAMS)\n to_write += tail\n print(to_write)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
] |
[
[
"scipy.special.comb"
]
] |
OdincoGaming/Text-Posting
|
[
"56e4102644f02837d68d13d9e05922c8e559ce57"
] |
[
"main.py"
] |
[
"'''\n code by TaeHwan Jung(@graykode)\n Original Paper and repository here : https://github.com/openai/gpt-2\n GPT2 Pytorch Model : https://github.com/huggingface/pytorch-pretrained-BERT\n'''\nimport os\nimport sys\nimport torch\nimport random\nimport argparse\nimport numpy as np\nfrom GPT2.model import (GPT2LMHeadModel)\nfrom GPT2.utils import load_weight\nfrom GPT2.config import GPT2Config\nfrom GPT2.sample import sample_sequence\nfrom GPT2.encoder import get_encoder\nimport modules\n\ndef text_generator(state_dict):\n filepath = modules.getfile(\"txt\", 'generatedtext.txt')\n file = open(filepath, \"w+\")\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--text\", type=str, required=True)\n parser.add_argument(\"--quiet\", type=bool, default=False)\n parser.add_argument(\"--nsamples\", type=int, default=1)\n parser.add_argument('--unconditional', action='store_true', help='If true, unconditional generation.')\n parser.add_argument(\"--batch_size\", type=int, default=-1)\n parser.add_argument(\"--length\", type=int, default=-1)\n parser.add_argument(\"--temperature\", type=float, default=0.7)\n parser.add_argument(\"--top_k\", type=int, default=40)\n parser.add_argument(\"--include\", type=bool, default=False)\n args = parser.parse_args()\n\n if args.quiet is False:\n print(args)\n\n if args.batch_size == -1:\n args.batch_size = 1\n assert args.nsamples % args.batch_size == 0\n\n seed = random.randint(0, 2147483647)\n np.random.seed(seed)\n torch.random.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n # Load Model\n enc = get_encoder()\n config = GPT2Config()\n model = GPT2LMHeadModel(config)\n model = load_weight(model, state_dict)\n model.to(device)\n model.eval()\n\n if args.length == -1:\n args.length = config.n_ctx // 2\n elif args.length > config.n_ctx:\n raise ValueError(\"Can't get samples longer than window size: %s\" % config.n_ctx)\n\n print(args.text)\n context_tokens = enc.encode(args.text)\n\n generated = 0\n for _ in range(args.nsamples // args.batch_size):\n out = sample_sequence(\n model=model, length=args.length,\n context=context_tokens if not args.unconditional else None,\n start_token=enc.encoder['<|endoftext|>'] if args.unconditional else None,\n batch_size=args.batch_size,\n temperature=args.temperature, top_k=args.top_k, device=device\n )\n out = out[:, len(context_tokens):].tolist()\n for i in range(args.batch_size):\n generated += 1\n text = enc.decode(out[i])\n if args.quiet is False:\n print(\"=\" * 40 + \" SAMPLE \" + str(generated) + \" \" + \"=\" * 40)\n if(args.include == True): \n file.write(args.text + text)\n else:\n file.write(text)\n print(text)\n\nif __name__ == '__main__':\n if os.path.exists('gpt2-pytorch_model.bin'):\n state_dict = torch.load('gpt2-pytorch_model.bin', map_location='cpu' if not torch.cuda.is_available() else None)\n text_generator(state_dict)\n else:\n print('Please download gpt2-pytorch_model.bin')\n sys.exit()\n"
] |
[
[
"torch.cuda.manual_seed",
"torch.random.manual_seed",
"numpy.random.seed",
"torch.cuda.is_available"
]
] |
XiangLi1999/transformers
|
[
"3e62aadd98366c975530986c05e1fc605fa8d928"
] |
[
"tests/test_tokenization_common.py"
] |
[
"# coding=utf-8\n# Copyright 2019 HuggingFace 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\nimport os\nimport pickle\nimport re\nimport shutil\nimport tempfile\nfrom collections import OrderedDict\nfrom typing import TYPE_CHECKING, Dict, List, Tuple, Union\n\nfrom tests.utils import require_tf, require_torch, slow\nfrom transformers import PreTrainedTokenizer, PreTrainedTokenizerBase, PreTrainedTokenizerFast\n\n\nif TYPE_CHECKING:\n from transformers import (\n PretrainedConfig,\n PreTrainedModel,\n TFPreTrainedModel,\n )\n\n\ndef merge_model_tokenizer_mappings(\n model_mapping: Dict[\"PretrainedConfig\", Union[\"PreTrainedModel\", \"TFPreTrainedModel\"]],\n tokenizer_mapping: Dict[\"PretrainedConfig\", Tuple[\"PreTrainedTokenizer\", \"PreTrainedTokenizerFast\"]],\n) -> Dict[\n Union[\"PreTrainedTokenizer\", \"PreTrainedTokenizerFast\"],\n Tuple[\"PretrainedConfig\", Union[\"PreTrainedModel\", \"TFPreTrainedModel\"]],\n]:\n configurations = list(model_mapping.keys())\n model_tokenizer_mapping = OrderedDict([])\n\n for configuration in configurations:\n model = model_mapping[configuration]\n tokenizer = tokenizer_mapping[configuration][0]\n tokenizer_fast = tokenizer_mapping[configuration][1]\n\n model_tokenizer_mapping.update({tokenizer: (configuration, model)})\n if tokenizer_fast is not None:\n model_tokenizer_mapping.update({tokenizer_fast: (configuration, model)})\n\n return model_tokenizer_mapping\n\n\nclass TokenizerTesterMixin:\n\n tokenizer_class = None\n test_rust_tokenizer = False\n\n def setUp(self):\n self.tmpdirname = tempfile.mkdtemp()\n\n def tearDown(self):\n shutil.rmtree(self.tmpdirname)\n\n def get_input_output_texts(self, tokenizer):\n input_txt = self.get_clean_sequence(tokenizer)[0]\n return input_txt, input_txt\n\n def get_clean_sequence(self, tokenizer, with_prefix_space=False, max_length=20) -> Tuple[str, list]:\n toks = [(i, tokenizer.decode([i], clean_up_tokenization_spaces=False)) for i in range(len(tokenizer))]\n toks = list(filter(lambda t: re.match(r\"^[ a-zA-Z]+$\", t[1]), toks))\n toks = list(filter(lambda t: [t[0]] == tokenizer.encode(t[1], add_special_tokens=False), toks))\n if max_length is not None and len(toks) > max_length:\n toks = toks[:max_length]\n # toks_str = [t[1] for t in toks]\n toks_ids = [t[0] for t in toks]\n\n # Ensure consistency\n output_txt = tokenizer.decode(toks_ids, clean_up_tokenization_spaces=False)\n if \" \" not in output_txt and len(toks_ids) > 1:\n output_txt = (\n tokenizer.decode([toks_ids[0]], clean_up_tokenization_spaces=False)\n + \" \"\n + tokenizer.decode(toks_ids[1:], clean_up_tokenization_spaces=False)\n )\n if with_prefix_space:\n output_txt = \" \" + output_txt\n output_ids = tokenizer.encode(output_txt, add_special_tokens=False)\n return output_txt, output_ids\n\n def get_tokenizers(self, fast=True, **kwargs) -> List[PreTrainedTokenizerBase]:\n if fast and self.test_rust_tokenizer:\n return [self.get_tokenizer(**kwargs), self.get_rust_tokenizer(**kwargs)]\n return [self.get_tokenizer(**kwargs)]\n\n def get_tokenizer(self, **kwargs) -> PreTrainedTokenizer:\n return self.tokenizer_class.from_pretrained(self.tmpdirname, **kwargs)\n\n def get_rust_tokenizer(self, **kwargs) -> PreTrainedTokenizerFast:\n raise NotImplementedError\n\n # def get_input_output_texts(self) -> Tuple[str, str]:\n # \"\"\"Feel free to overwrite\"\"\"\n # # TODO: @property\n # return (\n # \"This is a test\",\n # \"This is a test\",\n # )\n\n @staticmethod\n def convert_batch_encode_plus_format_to_encode_plus(batch_encode_plus_sequences):\n # Switch from batch_encode_plus format: {'input_ids': [[...], [...]], ...}\n # to the list of examples/ encode_plus format: [{'input_ids': [...], ...}, {'input_ids': [...], ...}]\n return [\n {value: batch_encode_plus_sequences[value][i] for value in batch_encode_plus_sequences.keys()}\n for i in range(len(batch_encode_plus_sequences[\"input_ids\"]))\n ]\n\n def test_tokenizers_common_properties(self):\n tokenizers = self.get_tokenizers()\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n attributes_list = [\n \"bos_token\",\n \"eos_token\",\n \"unk_token\",\n \"sep_token\",\n \"pad_token\",\n \"cls_token\",\n \"mask_token\",\n ]\n for attr in attributes_list:\n self.assertTrue(hasattr(tokenizer, attr))\n self.assertTrue(hasattr(tokenizer, attr + \"_id\"))\n\n self.assertTrue(hasattr(tokenizer, \"additional_special_tokens\"))\n self.assertTrue(hasattr(tokenizer, \"additional_special_tokens_ids\"))\n\n attributes_list = [\n \"model_max_length\",\n \"init_inputs\",\n \"init_kwargs\",\n ]\n if not isinstance(tokenizer, PreTrainedTokenizerFast):\n attributes_list += [\n \"added_tokens_encoder\",\n \"added_tokens_decoder\",\n ]\n for attr in attributes_list:\n self.assertTrue(hasattr(tokenizer, attr))\n\n def test_save_and_load_tokenizer(self):\n # safety check on max_len default value so we are sure the test works\n tokenizers = self.get_tokenizers()\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n self.assertNotEqual(tokenizer.max_len, 42)\n\n # Now let's start the test\n tokenizers = self.get_tokenizers()\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n # Isolate this from the other tests because we save additional tokens/etc\n tmpdirname = tempfile.mkdtemp()\n\n sample_text = \" He is very happy, UNwant\\u00E9d,running\"\n before_tokens = tokenizer.encode(sample_text, add_special_tokens=False)\n before_vocab = tokenizer.get_vocab()\n tokenizer.save_pretrained(tmpdirname)\n\n after_tokenizer = tokenizer.__class__.from_pretrained(tmpdirname)\n after_tokens = after_tokenizer.encode(sample_text, add_special_tokens=False)\n after_vocab = after_tokenizer.get_vocab()\n self.assertListEqual(before_tokens, after_tokens)\n self.assertDictEqual(before_vocab, after_vocab)\n\n shutil.rmtree(tmpdirname)\n\n # Now let's start the test\n tokenizers = self.get_tokenizers(model_max_length=42)\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n # Isolate this from the other tests because we save additional tokens/etc\n tmpdirname = tempfile.mkdtemp()\n\n sample_text = \" He is very happy, UNwant\\u00E9d,running\"\n tokenizer.add_tokens([\"bim\", \"bambam\"])\n additional_special_tokens = tokenizer.additional_special_tokens\n additional_special_tokens.append(\"new_additional_special_token\")\n tokenizer.add_special_tokens({\"additional_special_tokens\": additional_special_tokens})\n before_tokens = tokenizer.encode(sample_text, add_special_tokens=False)\n before_vocab = tokenizer.get_vocab()\n tokenizer.save_pretrained(tmpdirname)\n\n after_tokenizer = tokenizer.__class__.from_pretrained(tmpdirname)\n after_tokens = after_tokenizer.encode(sample_text, add_special_tokens=False)\n after_vocab = after_tokenizer.get_vocab()\n self.assertListEqual(before_tokens, after_tokens)\n self.assertDictEqual(before_vocab, after_vocab)\n self.assertIn(\"bim\", after_vocab)\n self.assertIn(\"bambam\", after_vocab)\n self.assertIn(\"new_additional_special_token\", after_tokenizer.additional_special_tokens)\n self.assertEqual(after_tokenizer.model_max_length, 42)\n\n tokenizer = tokenizer.__class__.from_pretrained(tmpdirname, model_max_length=43)\n self.assertEqual(tokenizer.model_max_length, 43)\n\n shutil.rmtree(tmpdirname)\n\n def test_pickle_tokenizer(self):\n \"\"\"Google pickle __getstate__ __setstate__ if you are struggling with this.\"\"\"\n tokenizers = self.get_tokenizers()\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n self.assertIsNotNone(tokenizer)\n\n text = \"Munich and Berlin are nice cities\"\n subwords = tokenizer.tokenize(text)\n\n filename = os.path.join(self.tmpdirname, \"tokenizer.bin\")\n with open(filename, \"wb\") as handle:\n pickle.dump(tokenizer, handle)\n\n with open(filename, \"rb\") as handle:\n tokenizer_new = pickle.load(handle)\n\n subwords_loaded = tokenizer_new.tokenize(text)\n\n self.assertListEqual(subwords, subwords_loaded)\n\n def test_added_tokens_do_lower_case(self):\n # TODO(thom) activate fast tokenizer tests once Rust tokenizers accepts white spaces in added tokens\n tokenizers = self.get_tokenizers(fast=False, do_lower_case=True)\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n special_token = tokenizer.all_special_tokens[0]\n\n text = special_token + \" aaaaa bbbbbb low cccccccccdddddddd l \" + special_token\n text2 = special_token + \" AAAAA BBBBBB low CCCCCCCCCDDDDDDDD l \" + special_token\n\n toks0 = tokenizer.tokenize(text) # toks before adding new_toks\n\n new_toks = [\"aaaaa bbbbbb\", \"cccccccccdddddddd\", \"AAAAA BBBBBB\", \"CCCCCCCCCDDDDDDDD\"]\n added = tokenizer.add_tokens(new_toks)\n self.assertEqual(added, 2)\n\n toks = tokenizer.tokenize(text)\n toks2 = tokenizer.tokenize(text2)\n\n self.assertEqual(len(toks), len(toks2))\n self.assertListEqual(toks, toks2)\n if not isinstance(tokenizer, PreTrainedTokenizerFast):\n # Python tokenizers can have added tokens with spaces inside them\n # cf https://github.com/huggingface/tokenizers/issues/302\n self.assertNotEqual(len(toks), len(toks0)) # toks0 should be longer\n\n # Check that none of the special tokens are lowercased\n sequence_with_special_tokens = \"A \" + \" yEs \".join(tokenizer.all_special_tokens) + \" B\"\n tokenized_sequence = tokenizer.tokenize(sequence_with_special_tokens)\n\n for special_token in tokenizer.all_special_tokens:\n self.assertTrue(special_token in tokenized_sequence)\n\n tokenizers = self.get_tokenizers(fast=False, do_lower_case=False)\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n special_token = tokenizer.all_special_tokens[0]\n\n text = special_token + \" aaaaa bbbbbb low cccccccccdddddddd l \" + special_token\n text2 = special_token + \" AAAAA BBBBBB low CCCCCCCCCDDDDDDDD l \" + special_token\n\n new_toks = [\"aaaaa bbbbbb\", \"cccccccccdddddddd\", \"AAAAA BBBBBB\", \"CCCCCCCCCDDDDDDDD\"]\n\n toks0 = tokenizer.tokenize(text) # toks before adding new_toks\n\n added = tokenizer.add_tokens(new_toks)\n self.assertEqual(added, 4)\n\n toks = tokenizer.tokenize(text)\n toks2 = tokenizer.tokenize(text2)\n\n self.assertEqual(len(toks), len(toks2)) # Length should still be the same\n self.assertNotEqual(toks[1], toks2[1]) # But at least the first non-special tokens should differ\n if not isinstance(tokenizer, PreTrainedTokenizerFast):\n # Python tokenizers can have added tokens with spaces inside them\n # cf https://github.com/huggingface/tokenizers/issues/302\n self.assertNotEqual(len(toks), len(toks0)) # toks0 should be longer\n\n def test_add_tokens_tokenizer(self):\n tokenizers = self.get_tokenizers(do_lower_case=False)\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n vocab_size = tokenizer.vocab_size\n all_size = len(tokenizer)\n\n self.assertNotEqual(vocab_size, 0)\n\n # We usually have added tokens from the start in tests because our vocab fixtures are\n # smaller than the original vocabs - let's not assert this\n # self.assertEqual(vocab_size, all_size)\n\n new_toks = [\"aaaaa bbbbbb\", \"cccccccccdddddddd\"]\n added_toks = tokenizer.add_tokens(new_toks)\n vocab_size_2 = tokenizer.vocab_size\n all_size_2 = len(tokenizer)\n\n self.assertNotEqual(vocab_size_2, 0)\n self.assertEqual(vocab_size, vocab_size_2)\n self.assertEqual(added_toks, len(new_toks))\n self.assertEqual(all_size_2, all_size + len(new_toks))\n\n tokens = tokenizer.encode(\"aaaaa bbbbbb low cccccccccdddddddd l\", add_special_tokens=False)\n\n self.assertGreaterEqual(len(tokens), 4)\n self.assertGreater(tokens[0], tokenizer.vocab_size - 1)\n self.assertGreater(tokens[-2], tokenizer.vocab_size - 1)\n\n new_toks_2 = {\"eos_token\": \">>>>|||<||<<|<<\", \"pad_token\": \"<<<<<|||>|>>>>|>\"}\n added_toks_2 = tokenizer.add_special_tokens(new_toks_2)\n vocab_size_3 = tokenizer.vocab_size\n all_size_3 = len(tokenizer)\n\n self.assertNotEqual(vocab_size_3, 0)\n self.assertEqual(vocab_size, vocab_size_3)\n self.assertEqual(added_toks_2, len(new_toks_2))\n self.assertEqual(all_size_3, all_size_2 + len(new_toks_2))\n\n tokens = tokenizer.encode(\n \">>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l\", add_special_tokens=False\n )\n\n self.assertGreaterEqual(len(tokens), 6)\n self.assertGreater(tokens[0], tokenizer.vocab_size - 1)\n self.assertGreater(tokens[0], tokens[1])\n self.assertGreater(tokens[-2], tokenizer.vocab_size - 1)\n self.assertGreater(tokens[-2], tokens[-3])\n self.assertEqual(tokens[0], tokenizer.eos_token_id)\n self.assertEqual(tokens[-2], tokenizer.pad_token_id)\n\n def test_add_special_tokens(self):\n tokenizers = self.get_tokenizers(do_lower_case=False)\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n input_text, ids = self.get_clean_sequence(tokenizer)\n\n special_token = \"[SPECIAL_TOKEN]\"\n\n tokenizer.add_special_tokens({\"cls_token\": special_token})\n encoded_special_token = tokenizer.encode(special_token, add_special_tokens=False)\n self.assertEqual(len(encoded_special_token), 1)\n\n text = tokenizer.decode(ids + encoded_special_token, clean_up_tokenization_spaces=False)\n encoded = tokenizer.encode(text, add_special_tokens=False)\n\n input_encoded = tokenizer.encode(input_text, add_special_tokens=False)\n special_token_id = tokenizer.encode(special_token, add_special_tokens=False)\n self.assertEqual(encoded, input_encoded + special_token_id)\n\n decoded = tokenizer.decode(encoded, skip_special_tokens=True)\n self.assertTrue(special_token not in decoded)\n\n def test_internal_consistency(self):\n tokenizers = self.get_tokenizers()\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n input_text, output_text = self.get_input_output_texts(tokenizer)\n\n tokens = tokenizer.tokenize(input_text)\n ids = tokenizer.convert_tokens_to_ids(tokens)\n ids_2 = tokenizer.encode(input_text, add_special_tokens=False)\n self.assertListEqual(ids, ids_2)\n\n tokens_2 = tokenizer.convert_ids_to_tokens(ids)\n self.assertNotEqual(len(tokens_2), 0)\n text_2 = tokenizer.decode(ids)\n self.assertIsInstance(text_2, str)\n\n self.assertEqual(text_2, output_text)\n\n def test_encode_decode_with_spaces(self):\n tokenizers = self.get_tokenizers(do_lower_case=False)\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n\n new_toks = [\"[ABC]\", \"[DEF]\"] # TODO(thom) add this one back when Rust toks are ready: , \"GHI IHG\"]\n tokenizer.add_tokens(new_toks)\n input = \"[ABC] [DEF] [ABC] [DEF]\" # TODO(thom) add back cf above: \"[ABC] [DEF] [ABC] GHI IHG [DEF]\"\n encoded = tokenizer.encode(input, add_special_tokens=False)\n decoded = tokenizer.decode(encoded)\n self.assertEqual(decoded, input)\n\n def test_pretrained_model_lists(self):\n weights_list = list(self.tokenizer_class.max_model_input_sizes.keys())\n weights_lists_2 = []\n for file_id, map_list in self.tokenizer_class.pretrained_vocab_files_map.items():\n weights_lists_2.append(list(map_list.keys()))\n\n for weights_list_2 in weights_lists_2:\n self.assertListEqual(weights_list, weights_list_2)\n\n def test_mask_output(self):\n tokenizers = self.get_tokenizers(fast=False, do_lower_case=False)\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n\n if (\n tokenizer.build_inputs_with_special_tokens.__qualname__.split(\".\")[0] != \"PreTrainedTokenizer\"\n and \"token_type_ids\" in tokenizer.model_input_names\n ):\n seq_0 = \"Test this method.\"\n seq_1 = \"With these inputs.\"\n information = tokenizer.encode_plus(seq_0, seq_1, add_special_tokens=True)\n sequences, mask = information[\"input_ids\"], information[\"token_type_ids\"]\n self.assertEqual(len(sequences), len(mask))\n\n def test_number_of_added_tokens(self):\n tokenizers = self.get_tokenizers(do_lower_case=False)\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n\n seq_0 = \"Test this method.\"\n seq_1 = \"With these inputs.\"\n\n sequences = tokenizer.encode(seq_0, seq_1, add_special_tokens=False)\n attached_sequences = tokenizer.encode(seq_0, seq_1, add_special_tokens=True)\n\n # Method is implemented (e.g. not GPT-2)\n if len(attached_sequences) != 2:\n self.assertEqual(\n tokenizer.num_special_tokens_to_add(pair=True), len(attached_sequences) - len(sequences)\n )\n\n def test_maximum_encoding_length_single_input(self):\n tokenizers = self.get_tokenizers(do_lower_case=False, model_max_length=100)\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n seq_0, ids = self.get_clean_sequence(tokenizer, max_length=20)\n\n sequence = tokenizer.encode(seq_0, add_special_tokens=False)\n total_length = len(sequence)\n\n assert total_length > 1, \"Issue with the testing sequence, please update it it's too short\"\n\n # Test with max model input length\n model_max_length = tokenizer.model_max_length\n self.assertEqual(model_max_length, 100)\n seq_1 = seq_0 * model_max_length\n\n sequence1 = tokenizer(seq_1, add_special_tokens=False)\n total_length1 = len(sequence1[\"input_ids\"])\n assert (\n total_length1 > model_max_length\n ), \"Issue with the testing sequence, please update it it's too short\"\n\n # Simple\n padding_strategies = (\n [False, True, \"longest\"] if tokenizer.pad_token and tokenizer.pad_token_id >= 0 else [False]\n )\n for padding_state in padding_strategies:\n with self.subTest(f\"Padding: {padding_state}\"):\n for truncation_state in [True, \"longest_first\", \"only_first\"]:\n with self.subTest(f\"Truncation: {truncation_state}\"):\n output = tokenizer(seq_1, padding=padding_state, truncation=truncation_state)\n self.assertEqual(len(output[\"input_ids\"]), model_max_length)\n\n output = tokenizer([seq_1], padding=padding_state, truncation=truncation_state)\n self.assertEqual(len(output[\"input_ids\"][0]), model_max_length)\n\n # Simple with no truncation\n output = tokenizer(seq_1, padding=padding_state, truncation=False)\n self.assertNotEqual(len(output[\"input_ids\"]), model_max_length)\n\n output = tokenizer([seq_1], padding=padding_state, truncation=False)\n self.assertNotEqual(len(output[\"input_ids\"][0]), model_max_length)\n\n # Overflowing tokens\n stride = 2\n information = tokenizer(\n seq_0,\n max_length=total_length - 2,\n add_special_tokens=False,\n stride=stride,\n truncation=\"longest_first\",\n return_overflowing_tokens=True,\n # add_prefix_space=False,\n )\n\n # Overflowing tokens are handled quite differently in slow and fast tokenizers\n if isinstance(tokenizer, PreTrainedTokenizerFast):\n truncated_sequence = information[\"input_ids\"][0]\n overflowing_tokens = information[\"input_ids\"][1]\n self.assertEqual(len(information[\"input_ids\"]), 2)\n\n self.assertEqual(len(truncated_sequence), total_length - 2)\n self.assertEqual(truncated_sequence, sequence[:-2])\n\n self.assertEqual(len(overflowing_tokens), 2 + stride)\n self.assertEqual(overflowing_tokens, sequence[-(2 + stride) :])\n else:\n truncated_sequence = information[\"input_ids\"]\n overflowing_tokens = information[\"overflowing_tokens\"]\n\n self.assertEqual(len(truncated_sequence), total_length - 2)\n self.assertEqual(truncated_sequence, sequence[:-2])\n\n self.assertEqual(\n len(overflowing_tokens), 0\n ) # No overflowing tokens when using 'longest' in python tokenizers\n\n def test_maximum_encoding_length_pair_input(self):\n tokenizers = self.get_tokenizers(do_lower_case=False, model_max_length=100)\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n # Build a sequence from our model's vocabulary\n stride = 2\n seq_0, ids = self.get_clean_sequence(tokenizer, max_length=20)\n if len(ids) <= 2 + stride:\n seq_0 = (seq_0 + \" \") * (2 + stride)\n ids = None\n\n seq0_tokens = tokenizer.encode(seq_0, add_special_tokens=False)\n assert len(seq0_tokens) > 2 + stride\n\n seq_1 = \"This is another sentence to be encoded.\"\n seq1_tokens = tokenizer.encode(seq_1, add_special_tokens=False)\n if abs(len(seq0_tokens) - len(seq1_tokens)) <= 2:\n seq1_tokens = seq1_tokens + seq1_tokens\n seq_1 = tokenizer.decode(seq1_tokens, clean_up_tokenization_spaces=False)\n seq1_tokens = tokenizer.encode(seq_1, add_special_tokens=False)\n\n assert len(seq1_tokens) > 2 + stride\n\n smallest = seq1_tokens if len(seq0_tokens) > len(seq1_tokens) else seq0_tokens\n\n # We are not using the special tokens - a bit too hard to test all the tokenizers with this\n # TODO try this again later\n sequence = tokenizer.encode(seq_0, seq_1, add_special_tokens=False) # , add_prefix_space=False)\n\n # Test with max model input length\n model_max_length = tokenizer.model_max_length\n self.assertEqual(model_max_length, 100)\n seq_2 = seq_0 * model_max_length\n\n sequence1 = tokenizer(seq_1, add_special_tokens=False)\n total_length1 = len(sequence1[\"input_ids\"])\n sequence2 = tokenizer(seq_2, seq_1, add_special_tokens=False)\n total_length2 = len(sequence2[\"input_ids\"])\n assert total_length1 < model_max_length - 10, \"Issue with the testing sequence, please update it.\"\n assert total_length2 > model_max_length, \"Issue with the testing sequence, please update it.\"\n\n # Simple\n padding_strategies = (\n [False, True, \"longest\"] if tokenizer.pad_token and tokenizer.pad_token_id >= 0 else [False]\n )\n for padding_state in padding_strategies:\n with self.subTest(f\"Padding: {padding_state}\"):\n for truncation_state in [True, \"longest_first\", \"only_first\"]:\n with self.subTest(f\"Truncation: {truncation_state}\"):\n output = tokenizer(seq_2, seq_1, padding=padding_state, truncation=truncation_state)\n self.assertEqual(len(output[\"input_ids\"]), model_max_length)\n\n output = tokenizer(\n [seq_2], [seq_1], padding=padding_state, truncation=truncation_state\n )\n self.assertEqual(len(output[\"input_ids\"][0]), model_max_length)\n\n # Simple\n output = tokenizer(seq_1, seq_2, padding=padding_state, truncation=\"only_second\")\n self.assertEqual(len(output[\"input_ids\"]), model_max_length)\n\n output = tokenizer([seq_1], [seq_2], padding=padding_state, truncation=\"only_second\")\n self.assertEqual(len(output[\"input_ids\"][0]), model_max_length)\n\n # Simple with no truncation\n output = tokenizer(seq_1, seq_2, padding=padding_state, truncation=False)\n self.assertNotEqual(len(output[\"input_ids\"]), model_max_length)\n\n output = tokenizer([seq_1], [seq_2], padding=padding_state, truncation=False)\n self.assertNotEqual(len(output[\"input_ids\"][0]), model_max_length)\n\n truncated_first_sequence = tokenizer.encode(seq_0, add_special_tokens=False)[:-2] + tokenizer.encode(\n seq_1, add_special_tokens=False\n )\n truncated_second_sequence = (\n tokenizer.encode(seq_0, add_special_tokens=False)\n + tokenizer.encode(seq_1, add_special_tokens=False)[:-2]\n )\n truncated_longest_sequence = (\n truncated_first_sequence if len(seq0_tokens) > len(seq1_tokens) else truncated_second_sequence\n )\n\n overflow_first_sequence = tokenizer.encode(seq_0, add_special_tokens=False)[\n -(2 + stride) :\n ] + tokenizer.encode(seq_1, add_special_tokens=False)\n overflow_second_sequence = (\n tokenizer.encode(seq_0, add_special_tokens=False)\n + tokenizer.encode(seq_1, add_special_tokens=False)[-(2 + stride) :]\n )\n overflow_longest_sequence = (\n overflow_first_sequence if len(seq0_tokens) > len(seq1_tokens) else overflow_second_sequence\n )\n\n information = tokenizer.encode_plus(\n seq_0,\n seq_1,\n max_length=len(sequence) - 2,\n add_special_tokens=False,\n stride=stride,\n truncation=\"longest_first\",\n return_overflowing_tokens=True,\n # add_prefix_space=False,\n )\n # Overflowing tokens are handled quite differently in slow and fast tokenizers\n if isinstance(tokenizer, PreTrainedTokenizerFast):\n truncated_sequence = information[\"input_ids\"][0]\n overflowing_tokens = information[\"input_ids\"][1]\n self.assertEqual(len(information[\"input_ids\"]), 2)\n\n self.assertEqual(len(truncated_sequence), len(sequence) - 2)\n self.assertEqual(truncated_sequence, truncated_longest_sequence)\n\n self.assertEqual(len(overflowing_tokens), 2 + stride + len(smallest))\n self.assertEqual(overflowing_tokens, overflow_longest_sequence)\n else:\n truncated_sequence = information[\"input_ids\"]\n overflowing_tokens = information[\"overflowing_tokens\"]\n\n self.assertEqual(len(truncated_sequence), len(sequence) - 2)\n self.assertEqual(truncated_sequence, truncated_longest_sequence)\n\n self.assertEqual(\n len(overflowing_tokens), 0\n ) # No overflowing tokens when using 'longest' in python tokenizers\n\n information_first_truncated = tokenizer.encode_plus(\n seq_0,\n seq_1,\n max_length=len(sequence) - 2,\n add_special_tokens=False,\n stride=stride,\n truncation=True,\n return_overflowing_tokens=True,\n # add_prefix_space=False,\n )\n # Overflowing tokens are handled quite differently in slow and fast tokenizers\n if isinstance(tokenizer, PreTrainedTokenizerFast):\n truncated_sequence = information_first_truncated[\"input_ids\"][0]\n overflowing_tokens = information_first_truncated[\"input_ids\"][1]\n self.assertEqual(len(information_first_truncated[\"input_ids\"]), 2)\n\n self.assertEqual(len(truncated_sequence), len(sequence) - 2)\n self.assertEqual(truncated_sequence, truncated_first_sequence)\n\n self.assertEqual(len(overflowing_tokens), 2 + stride + len(seq1_tokens))\n self.assertEqual(overflowing_tokens, overflow_first_sequence)\n else:\n truncated_sequence = information_first_truncated[\"input_ids\"]\n overflowing_tokens = information_first_truncated[\"overflowing_tokens\"]\n\n self.assertEqual(len(truncated_sequence), len(sequence) - 2)\n self.assertEqual(truncated_sequence, truncated_first_sequence)\n\n self.assertEqual(len(overflowing_tokens), 2 + stride)\n self.assertEqual(overflowing_tokens, seq0_tokens[-(2 + stride) :])\n\n information_second_truncated = tokenizer.encode_plus(\n seq_0,\n seq_1,\n max_length=len(sequence) - 2,\n add_special_tokens=False,\n stride=stride,\n truncation=\"only_second\",\n return_overflowing_tokens=True,\n # add_prefix_space=False,\n )\n # Overflowing tokens are handled quite differently in slow and fast tokenizers\n if isinstance(tokenizer, PreTrainedTokenizerFast):\n truncated_sequence = information_second_truncated[\"input_ids\"][0]\n overflowing_tokens = information_second_truncated[\"input_ids\"][1]\n self.assertEqual(len(information_second_truncated[\"input_ids\"]), 2)\n\n self.assertEqual(len(truncated_sequence), len(sequence) - 2)\n self.assertEqual(truncated_sequence, truncated_second_sequence)\n\n self.assertEqual(len(overflowing_tokens), 2 + stride + len(seq0_tokens))\n self.assertEqual(overflowing_tokens, overflow_second_sequence)\n else:\n truncated_sequence = information_second_truncated[\"input_ids\"]\n overflowing_tokens = information_second_truncated[\"overflowing_tokens\"]\n\n self.assertEqual(len(truncated_sequence), len(sequence) - 2)\n self.assertEqual(truncated_sequence, truncated_second_sequence)\n\n self.assertEqual(len(overflowing_tokens), 2 + stride)\n self.assertEqual(overflowing_tokens, seq1_tokens[-(2 + stride) :])\n\n # def test_encode_input_type(self):\n # tokenizers = self.get_tokenizers(do_lower_case=False)\n # for tokenizer in tokenizers:\n # with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n # sequence = \"Let's encode this sequence\"\n\n # tokens = sequence.split() # tokenizer.tokenize(sequence)\n # # input_ids = tokenizer.convert_tokens_to_ids(tokens)\n # formatted_input = tokenizer.encode(sequence, add_special_tokens=True, add_prefix_space=False)\n\n # self.assertEqual(\n # tokenizer.encode(tokens, is_pretokenized=True, add_special_tokens=True), formatted_input\n # )\n # # This is not supported with the Rust tokenizers\n # # self.assertEqual(tokenizer.encode(input_ids, add_special_tokens=True), formatted_input)\n\n def test_swap_special_token(self):\n tokenizers = self.get_tokenizers(do_lower_case=False)\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n mask = \"<mask>\"\n sequence = \"Encode this sequence\"\n sequence_masked_0 = \"Encode <mask> sequence\"\n sequence_masked_1 = \"<mask> this sequence\"\n\n # Add tokens so that masked token isn't split\n tokenizer.add_tokens(sequence.split())\n tokenizer.add_special_tokens({\"mask_token\": mask})\n mask_ind = tokenizer.convert_tokens_to_ids(mask)\n encoded = tokenizer.encode(sequence, add_special_tokens=False)\n\n # Test first masked sequence\n encoded_masked = tokenizer.encode(sequence_masked_0, add_special_tokens=False)\n mask_loc = encoded_masked.index(mask_ind)\n encoded_masked[mask_loc] = encoded[mask_loc]\n\n self.assertEqual(encoded_masked, encoded)\n\n # Test second masked sequence\n encoded_masked = tokenizer.encode(sequence_masked_1, add_special_tokens=False)\n mask_loc = encoded_masked.index(mask_ind)\n encoded_masked[mask_loc] = encoded[mask_loc]\n\n self.assertEqual(encoded_masked, encoded)\n\n def test_special_tokens_mask(self):\n tokenizers = self.get_tokenizers(do_lower_case=False)\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n sequence_0 = \"Encode this.\"\n # Testing single inputs\n encoded_sequence = tokenizer.encode(sequence_0, add_special_tokens=False)\n encoded_sequence_dict = tokenizer.encode_plus(\n sequence_0, add_special_tokens=True, return_special_tokens_mask=True # , add_prefix_space=False\n )\n encoded_sequence_w_special = encoded_sequence_dict[\"input_ids\"]\n special_tokens_mask = encoded_sequence_dict[\"special_tokens_mask\"]\n self.assertEqual(len(special_tokens_mask), len(encoded_sequence_w_special))\n\n filtered_sequence = [x for i, x in enumerate(encoded_sequence_w_special) if not special_tokens_mask[i]]\n self.assertEqual(encoded_sequence, filtered_sequence)\n\n def test_special_tokens_mask_input_pairs(self):\n tokenizers = self.get_tokenizers(do_lower_case=False)\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n sequence_0 = \"Encode this.\"\n sequence_1 = \"This one too please.\"\n encoded_sequence = tokenizer.encode(sequence_0, add_special_tokens=False)\n encoded_sequence += tokenizer.encode(sequence_1, add_special_tokens=False)\n encoded_sequence_dict = tokenizer.encode_plus(\n sequence_0,\n sequence_1,\n add_special_tokens=True,\n return_special_tokens_mask=True,\n # add_prefix_space=False,\n )\n encoded_sequence_w_special = encoded_sequence_dict[\"input_ids\"]\n special_tokens_mask = encoded_sequence_dict[\"special_tokens_mask\"]\n self.assertEqual(len(special_tokens_mask), len(encoded_sequence_w_special))\n\n filtered_sequence = [\n (x if not special_tokens_mask[i] else None) for i, x in enumerate(encoded_sequence_w_special)\n ]\n filtered_sequence = [x for x in filtered_sequence if x is not None]\n self.assertEqual(encoded_sequence, filtered_sequence)\n\n def test_right_and_left_padding(self):\n tokenizers = self.get_tokenizers(do_lower_case=False)\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n sequence = \"Sequence\"\n padding_size = 10\n\n # check correct behaviour if no pad_token_id exists and add it eventually\n self._check_no_pad_token_padding(tokenizer, sequence)\n\n padding_idx = tokenizer.pad_token_id\n\n # RIGHT PADDING - Check that it correctly pads when a maximum length is specified along with the padding flag set to True\n tokenizer.padding_side = \"right\"\n encoded_sequence = tokenizer.encode(sequence)\n sequence_length = len(encoded_sequence)\n padded_sequence = tokenizer.encode(\n sequence, max_length=sequence_length + padding_size, padding=\"max_length\"\n )\n padded_sequence_length = len(padded_sequence)\n assert sequence_length + padding_size == padded_sequence_length\n assert encoded_sequence + [padding_idx] * padding_size == padded_sequence\n\n # LEFT PADDING - Check that it correctly pads when a maximum length is specified along with the padding flag set to True\n tokenizer.padding_side = \"left\"\n encoded_sequence = tokenizer.encode(sequence)\n sequence_length = len(encoded_sequence)\n padded_sequence = tokenizer.encode(\n sequence, max_length=sequence_length + padding_size, padding=\"max_length\"\n )\n padded_sequence_length = len(padded_sequence)\n assert sequence_length + padding_size == padded_sequence_length\n assert [padding_idx] * padding_size + encoded_sequence == padded_sequence\n\n # RIGHT & LEFT PADDING - Check that nothing is done for 'longest' and 'no_padding'\n encoded_sequence = tokenizer.encode(sequence)\n sequence_length = len(encoded_sequence)\n\n tokenizer.padding_side = \"right\"\n padded_sequence_right = tokenizer.encode(sequence, padding=True)\n padded_sequence_right_length = len(padded_sequence_right)\n assert sequence_length == padded_sequence_right_length\n assert encoded_sequence == padded_sequence_right\n\n tokenizer.padding_side = \"left\"\n padded_sequence_left = tokenizer.encode(sequence, padding=\"longest\")\n padded_sequence_left_length = len(padded_sequence_left)\n assert sequence_length == padded_sequence_left_length\n assert encoded_sequence == padded_sequence_left\n\n tokenizer.padding_side = \"right\"\n padded_sequence_right = tokenizer.encode(sequence)\n padded_sequence_right_length = len(padded_sequence_right)\n assert sequence_length == padded_sequence_right_length\n assert encoded_sequence == padded_sequence_right\n\n tokenizer.padding_side = \"left\"\n padded_sequence_left = tokenizer.encode(sequence, padding=False)\n padded_sequence_left_length = len(padded_sequence_left)\n assert sequence_length == padded_sequence_left_length\n assert encoded_sequence == padded_sequence_left\n\n def test_padding_to_max_length(self):\n \"\"\" We keep this test for backward compatibility but it should be remove when `pad_to_max_length` will e deprecated\n \"\"\"\n tokenizers = self.get_tokenizers(do_lower_case=False)\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n sequence = \"Sequence\"\n padding_size = 10\n\n # check correct behaviour if no pad_token_id exists and add it eventually\n self._check_no_pad_token_padding(tokenizer, sequence)\n\n padding_idx = tokenizer.pad_token_id\n\n # Check that it correctly pads when a maximum length is specified along with the padding flag set to True\n tokenizer.padding_side = \"right\"\n encoded_sequence = tokenizer.encode(sequence)\n sequence_length = len(encoded_sequence)\n padded_sequence = tokenizer.encode(\n sequence, max_length=sequence_length + padding_size, pad_to_max_length=True\n )\n padded_sequence_length = len(padded_sequence)\n assert sequence_length + padding_size == padded_sequence_length\n assert encoded_sequence + [padding_idx] * padding_size == padded_sequence\n\n # Check that nothing is done when a maximum length is not specified\n encoded_sequence = tokenizer.encode(sequence)\n sequence_length = len(encoded_sequence)\n\n tokenizer.padding_side = \"right\"\n padded_sequence_right = tokenizer.encode(sequence, pad_to_max_length=True)\n padded_sequence_right_length = len(padded_sequence_right)\n assert sequence_length == padded_sequence_right_length\n assert encoded_sequence == padded_sequence_right\n\n def test_encode_plus_with_padding(self):\n tokenizers = self.get_tokenizers(do_lower_case=False)\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n sequence = \"Sequence\"\n\n # check correct behaviour if no pad_token_id exists and add it eventually\n self._check_no_pad_token_padding(tokenizer, sequence)\n\n padding_size = 10\n padding_idx = tokenizer.pad_token_id\n token_type_padding_idx = tokenizer.pad_token_type_id\n\n encoded_sequence = tokenizer.encode_plus(sequence, return_special_tokens_mask=True)\n input_ids = encoded_sequence[\"input_ids\"]\n special_tokens_mask = encoded_sequence[\"special_tokens_mask\"]\n sequence_length = len(input_ids)\n\n # Test 'longest' and 'no_padding' don't do anything\n tokenizer.padding_side = \"right\"\n\n not_padded_sequence = tokenizer.encode_plus(sequence, padding=True, return_special_tokens_mask=True,)\n not_padded_input_ids = not_padded_sequence[\"input_ids\"]\n\n not_padded_special_tokens_mask = not_padded_sequence[\"special_tokens_mask\"]\n not_padded_sequence_length = len(not_padded_input_ids)\n\n assert sequence_length == not_padded_sequence_length\n assert input_ids == not_padded_input_ids\n assert special_tokens_mask == not_padded_special_tokens_mask\n\n not_padded_sequence = tokenizer.encode_plus(sequence, padding=False, return_special_tokens_mask=True,)\n not_padded_input_ids = not_padded_sequence[\"input_ids\"]\n\n not_padded_special_tokens_mask = not_padded_sequence[\"special_tokens_mask\"]\n not_padded_sequence_length = len(not_padded_input_ids)\n\n assert sequence_length == not_padded_sequence_length\n assert input_ids == not_padded_input_ids\n assert special_tokens_mask == not_padded_special_tokens_mask\n\n # Test right padding\n tokenizer.padding_side = \"right\"\n\n right_padded_sequence = tokenizer.encode_plus(\n sequence,\n max_length=sequence_length + padding_size,\n padding=\"max_length\",\n return_special_tokens_mask=True,\n )\n right_padded_input_ids = right_padded_sequence[\"input_ids\"]\n\n right_padded_special_tokens_mask = right_padded_sequence[\"special_tokens_mask\"]\n right_padded_sequence_length = len(right_padded_input_ids)\n\n assert sequence_length + padding_size == right_padded_sequence_length\n assert input_ids + [padding_idx] * padding_size == right_padded_input_ids\n assert special_tokens_mask + [1] * padding_size == right_padded_special_tokens_mask\n\n # Test left padding\n tokenizer.padding_side = \"left\"\n left_padded_sequence = tokenizer.encode_plus(\n sequence,\n max_length=sequence_length + padding_size,\n padding=\"max_length\",\n return_special_tokens_mask=True,\n )\n left_padded_input_ids = left_padded_sequence[\"input_ids\"]\n left_padded_special_tokens_mask = left_padded_sequence[\"special_tokens_mask\"]\n left_padded_sequence_length = len(left_padded_input_ids)\n\n assert sequence_length + padding_size == left_padded_sequence_length\n assert [padding_idx] * padding_size + input_ids == left_padded_input_ids\n assert [1] * padding_size + special_tokens_mask == left_padded_special_tokens_mask\n\n if \"token_type_ids\" in tokenizer.model_input_names:\n token_type_ids = encoded_sequence[\"token_type_ids\"]\n left_padded_token_type_ids = left_padded_sequence[\"token_type_ids\"]\n right_padded_token_type_ids = right_padded_sequence[\"token_type_ids\"]\n\n assert token_type_ids + [token_type_padding_idx] * padding_size == right_padded_token_type_ids\n assert [token_type_padding_idx] * padding_size + token_type_ids == left_padded_token_type_ids\n\n if \"attention_mask\" in tokenizer.model_input_names:\n attention_mask = encoded_sequence[\"attention_mask\"]\n right_padded_attention_mask = right_padded_sequence[\"attention_mask\"]\n left_padded_attention_mask = left_padded_sequence[\"attention_mask\"]\n\n assert attention_mask + [0] * padding_size == right_padded_attention_mask\n assert [0] * padding_size + attention_mask == left_padded_attention_mask\n\n def test_separate_tokenizers(self):\n # This tests that tokenizers don't impact others. Unfortunately the case where it fails is when\n # we're loading an S3 configuration from a pre-trained identifier, and we have no way of testing those today.\n\n tokenizer = self.get_tokenizer(random_argument=True)\n assert tokenizer.init_kwargs[\"random_argument\"] is True\n new_tokenizer = self.get_tokenizer(random_argument=False)\n assert tokenizer.init_kwargs[\"random_argument\"] is True\n assert new_tokenizer.init_kwargs[\"random_argument\"] is False\n\n def test_get_vocab(self):\n tokenizers = self.get_tokenizers(do_lower_case=False)\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n vocab = tokenizer.get_vocab()\n\n self.assertIsInstance(vocab, dict)\n self.assertEqual(len(vocab), len(tokenizer))\n\n for word, ind in vocab.items():\n self.assertEqual(tokenizer.convert_tokens_to_ids(word), ind)\n self.assertEqual(tokenizer.convert_ids_to_tokens(ind), word)\n\n tokenizer.add_tokens([\"asdfasdfasdfasdf\"])\n vocab = tokenizer.get_vocab()\n self.assertIsInstance(vocab, dict)\n self.assertEqual(len(vocab), len(tokenizer))\n\n def test_conversion_reversible(self):\n tokenizers = self.get_tokenizers(do_lower_case=False)\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n vocab = tokenizer.get_vocab()\n for word, ind in vocab.items():\n self.assertEqual(tokenizer.convert_tokens_to_ids(word), ind)\n self.assertEqual(tokenizer.convert_ids_to_tokens(ind), word)\n\n def test_call(self):\n # Tests that all call wrap to encode_plus and batch_encode_plus\n tokenizers = self.get_tokenizers(do_lower_case=False)\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n sequences = [\n \"Testing batch encode plus\",\n \"Testing batch encode plus with different sequence lengths\",\n \"Testing batch encode plus with different sequence lengths correctly pads\",\n ]\n\n # Test not batched\n encoded_sequences_1 = tokenizer.encode_plus(sequences[0])\n encoded_sequences_2 = tokenizer(sequences[0])\n self.assertEqual(encoded_sequences_1, encoded_sequences_2)\n\n # Test not batched pairs\n encoded_sequences_1 = tokenizer.encode_plus(sequences[0], sequences[1])\n encoded_sequences_2 = tokenizer(sequences[0], sequences[1])\n self.assertEqual(encoded_sequences_1, encoded_sequences_2)\n\n # Test batched\n encoded_sequences_1 = tokenizer.batch_encode_plus(sequences)\n encoded_sequences_2 = tokenizer(sequences)\n self.assertEqual(encoded_sequences_1, encoded_sequences_2)\n\n # Test batched pairs\n encoded_sequences_1 = tokenizer.batch_encode_plus(list(zip(sequences, sequences)))\n encoded_sequences_2 = tokenizer(sequences, sequences)\n self.assertEqual(encoded_sequences_1, encoded_sequences_2)\n\n def test_batch_encode_plus_batch_sequence_length(self):\n # Tests that all encoded values have the correct size\n tokenizers = self.get_tokenizers(do_lower_case=False)\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n sequences = [\n \"Testing batch encode plus\",\n \"Testing batch encode plus with different sequence lengths\",\n \"Testing batch encode plus with different sequence lengths correctly pads\",\n ]\n\n encoded_sequences = [tokenizer.encode_plus(sequence) for sequence in sequences]\n encoded_sequences_batch = tokenizer.batch_encode_plus(sequences, padding=False)\n self.assertListEqual(\n encoded_sequences, self.convert_batch_encode_plus_format_to_encode_plus(encoded_sequences_batch)\n )\n\n maximum_length = len(\n max([encoded_sequence[\"input_ids\"] for encoded_sequence in encoded_sequences], key=len)\n )\n\n # check correct behaviour if no pad_token_id exists and add it eventually\n self._check_no_pad_token_padding(tokenizer, sequences)\n\n encoded_sequences_padded = [\n tokenizer.encode_plus(sequence, max_length=maximum_length, padding=\"max_length\")\n for sequence in sequences\n ]\n\n encoded_sequences_batch_padded = tokenizer.batch_encode_plus(sequences, padding=True)\n self.assertListEqual(\n encoded_sequences_padded,\n self.convert_batch_encode_plus_format_to_encode_plus(encoded_sequences_batch_padded),\n )\n\n # check 'longest' is unsensitive to a max length\n encoded_sequences_batch_padded_1 = tokenizer.batch_encode_plus(sequences, padding=True)\n encoded_sequences_batch_padded_2 = tokenizer.batch_encode_plus(\n sequences, max_length=maximum_length + 10, padding=\"longest\"\n )\n for key in encoded_sequences_batch_padded_1.keys():\n self.assertListEqual(\n encoded_sequences_batch_padded_1[key], encoded_sequences_batch_padded_2[key],\n )\n\n # check 'no_padding' is unsensitive to a max length\n encoded_sequences_batch_padded_1 = tokenizer.batch_encode_plus(sequences, padding=False)\n encoded_sequences_batch_padded_2 = tokenizer.batch_encode_plus(\n sequences, max_length=maximum_length + 10, padding=False\n )\n for key in encoded_sequences_batch_padded_1.keys():\n self.assertListEqual(\n encoded_sequences_batch_padded_1[key], encoded_sequences_batch_padded_2[key],\n )\n\n def test_batch_encode_plus_padding(self):\n # Test that padded sequences are equivalent between batch_encode_plus and encode_plus\n\n # Right padding tests\n tokenizers = self.get_tokenizers(do_lower_case=False)\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n sequences = [\n \"Testing batch encode plus\",\n \"Testing batch encode plus with different sequence lengths\",\n \"Testing batch encode plus with different sequence lengths correctly pads\",\n ]\n\n max_length = 100\n\n # check correct behaviour if no pad_token_id exists and add it eventually\n self._check_no_pad_token_padding(tokenizer, sequences)\n\n encoded_sequences = [\n tokenizer.encode_plus(sequence, max_length=max_length, padding=\"max_length\")\n for sequence in sequences\n ]\n encoded_sequences_batch = tokenizer.batch_encode_plus(\n sequences, max_length=max_length, padding=\"max_length\"\n )\n self.assertListEqual(\n encoded_sequences, self.convert_batch_encode_plus_format_to_encode_plus(encoded_sequences_batch)\n )\n\n # Left padding tests\n tokenizers = self.get_tokenizers(do_lower_case=False)\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n tokenizer.padding_side = \"left\"\n sequences = [\n \"Testing batch encode plus\",\n \"Testing batch encode plus with different sequence lengths\",\n \"Testing batch encode plus with different sequence lengths correctly pads\",\n ]\n\n max_length = 100\n\n # check correct behaviour if no pad_token_id exists and add it eventually\n self._check_no_pad_token_padding(tokenizer, sequences)\n\n encoded_sequences = [\n tokenizer.encode_plus(sequence, max_length=max_length, padding=\"max_length\")\n for sequence in sequences\n ]\n encoded_sequences_batch = tokenizer.batch_encode_plus(\n sequences, max_length=max_length, padding=\"max_length\"\n )\n self.assertListEqual(\n encoded_sequences, self.convert_batch_encode_plus_format_to_encode_plus(encoded_sequences_batch)\n )\n\n def test_pretokenized_inputs(self):\n # Test when inputs are pretokenized\n\n tokenizers = self.get_tokenizers(do_lower_case=False) # , add_prefix_space=True)\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n\n # Prepare a sequence from our tokenizer vocabulary\n sequence, ids = self.get_clean_sequence(tokenizer, with_prefix_space=True, max_length=20)\n # sequence = \" \" + sequence # To be sure the byte-level tokenizers are feeling good\n token_sequence = sequence.split()\n # sequence_no_prefix_space = sequence.strip()\n\n # Test encode for pretokenized inputs\n output = tokenizer.encode(token_sequence, is_pretokenized=True, add_special_tokens=False)\n output_sequence = tokenizer.encode(sequence, add_special_tokens=False)\n self.assertEqual(output, output_sequence)\n\n output = tokenizer.encode(token_sequence, is_pretokenized=True, add_special_tokens=True)\n output_sequence = tokenizer.encode(sequence, add_special_tokens=True)\n self.assertEqual(output, output_sequence)\n\n # Test encode_plus for pretokenized inputs\n output = tokenizer.encode_plus(token_sequence, is_pretokenized=True, add_special_tokens=False)\n output_sequence = tokenizer.encode_plus(sequence, add_special_tokens=False)\n for key in output.keys():\n self.assertEqual(output[key], output_sequence[key])\n output = tokenizer.encode_plus(token_sequence, is_pretokenized=True, add_special_tokens=True)\n output_sequence = tokenizer.encode_plus(sequence, add_special_tokens=True)\n for key in output.keys():\n self.assertEqual(output[key], output_sequence[key])\n\n # Test batch_encode_plus for pretokenized inputs\n sequence_batch = [sequence.strip()] * 2 + [sequence.strip() + \" \" + sequence.strip()]\n token_sequence_batch = [s.split() for s in sequence_batch]\n sequence_batch_cleaned_up_spaces = [\" \" + \" \".join(s) for s in token_sequence_batch]\n\n output = tokenizer.batch_encode_plus(\n token_sequence_batch, is_pretokenized=True, add_special_tokens=False\n )\n output_sequence = tokenizer.batch_encode_plus(\n sequence_batch_cleaned_up_spaces, add_special_tokens=False\n )\n for key in output.keys():\n self.assertEqual(output[key], output_sequence[key])\n output = tokenizer.batch_encode_plus(\n token_sequence_batch, is_pretokenized=True, add_special_tokens=True\n )\n output_sequence = tokenizer.batch_encode_plus(\n sequence_batch_cleaned_up_spaces, add_special_tokens=True\n )\n for key in output.keys():\n self.assertEqual(output[key], output_sequence[key])\n\n # Test encode for pretokenized inputs pairs\n output = tokenizer.encode(\n token_sequence, token_sequence, is_pretokenized=True, add_special_tokens=False\n )\n output_sequence = tokenizer.encode(sequence, sequence, add_special_tokens=False)\n self.assertEqual(output, output_sequence)\n output = tokenizer.encode(\n token_sequence, token_sequence, is_pretokenized=True, add_special_tokens=True\n )\n output_sequence = tokenizer.encode(sequence, sequence, add_special_tokens=True)\n self.assertEqual(output, output_sequence)\n\n # Test encode_plus for pretokenized inputs pairs\n output = tokenizer.encode_plus(\n token_sequence, token_sequence, is_pretokenized=True, add_special_tokens=False\n )\n output_sequence = tokenizer.encode_plus(sequence, sequence, add_special_tokens=False)\n for key in output.keys():\n self.assertEqual(output[key], output_sequence[key])\n output = tokenizer.encode_plus(\n token_sequence, token_sequence, is_pretokenized=True, add_special_tokens=True\n )\n output_sequence = tokenizer.encode_plus(sequence, sequence, add_special_tokens=True)\n for key in output.keys():\n self.assertEqual(output[key], output_sequence[key])\n\n # Test batch_encode_plus for pretokenized inputs pairs\n sequence_pair_batch = [(sequence.strip(), sequence.strip())] * 2 + [\n (sequence.strip() + \" \" + sequence.strip(), sequence.strip())\n ]\n token_sequence_pair_batch = [tuple(s.split() for s in pair) for pair in sequence_pair_batch]\n sequence_pair_batch_cleaned_up_spaces = [\n tuple(\" \" + \" \".join(s) for s in pair) for pair in token_sequence_pair_batch\n ]\n\n output = tokenizer.batch_encode_plus(\n token_sequence_pair_batch, is_pretokenized=True, add_special_tokens=False\n )\n output_sequence = tokenizer.batch_encode_plus(\n sequence_pair_batch_cleaned_up_spaces, add_special_tokens=False\n )\n for key in output.keys():\n self.assertEqual(output[key], output_sequence[key])\n output = tokenizer.batch_encode_plus(\n token_sequence_pair_batch, is_pretokenized=True, add_special_tokens=True\n )\n output_sequence = tokenizer.batch_encode_plus(\n sequence_pair_batch_cleaned_up_spaces, add_special_tokens=True\n )\n for key in output.keys():\n self.assertEqual(output[key], output_sequence[key])\n\n @require_torch\n @require_tf\n def test_batch_encode_plus_tensors(self):\n tokenizers = self.get_tokenizers(do_lower_case=False)\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n sequences = [\n \"Testing batch encode plus\",\n \"Testing batch encode plus with different sequence lengths\",\n \"Testing batch encode plus with different sequence lengths correctly pads\",\n ]\n\n # A Tensor cannot be build by sequences which are not the same size\n self.assertRaises(ValueError, tokenizer.batch_encode_plus, sequences, return_tensors=\"pt\")\n self.assertRaises(ValueError, tokenizer.batch_encode_plus, sequences, return_tensors=\"tf\")\n\n if tokenizer.pad_token_id is None:\n self.assertRaises(\n ValueError, tokenizer.batch_encode_plus, sequences, padding=True, return_tensors=\"pt\",\n )\n self.assertRaises(\n ValueError, tokenizer.batch_encode_plus, sequences, padding=\"longest\", return_tensors=\"tf\",\n )\n else:\n pytorch_tensor = tokenizer.batch_encode_plus(sequences, padding=True, return_tensors=\"pt\")\n tensorflow_tensor = tokenizer.batch_encode_plus(sequences, padding=\"longest\", return_tensors=\"tf\")\n encoded_sequences = tokenizer.batch_encode_plus(sequences, padding=True)\n\n for key in encoded_sequences.keys():\n pytorch_value = pytorch_tensor[key].tolist()\n tensorflow_value = tensorflow_tensor[key].numpy().tolist()\n encoded_value = encoded_sequences[key]\n\n self.assertEqual(pytorch_value, tensorflow_value, encoded_value)\n\n def _check_no_pad_token_padding(self, tokenizer, sequences):\n # if tokenizer does not have pad_token_id, an error should be thrown\n if tokenizer.pad_token_id is None:\n with self.assertRaises(ValueError):\n if isinstance(sequences, list):\n tokenizer.batch_encode_plus(sequences, padding=\"longest\")\n else:\n tokenizer.encode_plus(sequences, padding=True)\n\n # add pad_token_id to pass subsequent tests\n tokenizer.add_special_tokens({\"pad_token\": \"<PAD>\"})\n\n @slow\n @require_torch\n def test_torch_encode_plus_sent_to_model(self):\n import torch\n from transformers import MODEL_MAPPING, TOKENIZER_MAPPING\n\n MODEL_TOKENIZER_MAPPING = merge_model_tokenizer_mappings(MODEL_MAPPING, TOKENIZER_MAPPING)\n\n tokenizers = self.get_tokenizers(do_lower_case=False)\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n\n if tokenizer.__class__ not in MODEL_TOKENIZER_MAPPING:\n return\n\n config_class, model_class = MODEL_TOKENIZER_MAPPING[tokenizer.__class__]\n config = config_class()\n\n if config.is_encoder_decoder or config.pad_token_id is None:\n return\n\n model = model_class(config)\n\n # Make sure the model contains at least the full vocabulary size in its embedding matrix\n is_using_common_embeddings = hasattr(model.get_input_embeddings(), \"weight\")\n assert (\n (model.get_input_embeddings().weight.shape[0] >= len(tokenizer))\n if is_using_common_embeddings\n else True\n )\n\n # Build sequence\n first_ten_tokens = list(tokenizer.get_vocab().keys())[:10]\n sequence = \" \".join(first_ten_tokens)\n encoded_sequence = tokenizer.encode_plus(sequence, return_tensors=\"pt\")\n batch_encoded_sequence = tokenizer.batch_encode_plus([sequence, sequence], return_tensors=\"pt\")\n # This should not fail\n\n with torch.no_grad(): # saves some time\n model(**encoded_sequence)\n model(**batch_encoded_sequence)\n\n # if self.test_rust_tokenizer:\n # fast_tokenizer = self.get_rust_tokenizer()\n # encoded_sequence_fast = fast_tokenizer.encode_plus(sequence, return_tensors=\"pt\")\n # batch_encoded_sequence_fast = fast_tokenizer.batch_encode_plus([sequence, sequence], return_tensors=\"pt\")\n # # This should not fail\n # model(**encoded_sequence_fast)\n # model(**batch_encoded_sequence_fast)\n\n @slow\n @require_tf\n def test_tf_encode_plus_sent_to_model(self):\n from transformers import TF_MODEL_MAPPING, TOKENIZER_MAPPING\n\n MODEL_TOKENIZER_MAPPING = merge_model_tokenizer_mappings(TF_MODEL_MAPPING, TOKENIZER_MAPPING)\n\n tokenizers = self.get_tokenizers(do_lower_case=False)\n for tokenizer in tokenizers:\n with self.subTest(f\"{tokenizer.__class__.__name__}\"):\n if tokenizer.__class__ not in MODEL_TOKENIZER_MAPPING:\n return\n\n config_class, model_class = MODEL_TOKENIZER_MAPPING[tokenizer.__class__]\n config = config_class()\n\n if config.is_encoder_decoder or config.pad_token_id is None:\n return\n\n model = model_class(config)\n\n # Make sure the model contains at least the full vocabulary size in its embedding matrix\n assert model.config.vocab_size >= len(tokenizer)\n\n # Build sequence\n first_ten_tokens = list(tokenizer.get_vocab().keys())[:10]\n sequence = \" \".join(first_ten_tokens)\n encoded_sequence = tokenizer.encode_plus(sequence, return_tensors=\"tf\")\n batch_encoded_sequence = tokenizer.batch_encode_plus([sequence, sequence], return_tensors=\"tf\")\n\n # This should not fail\n model(encoded_sequence)\n model(batch_encoded_sequence)\n\n # TODO: Check if require_torch is the best to test for numpy here ... Maybe move to require_flax when available\n @slow\n @require_torch\n def test_np_encode_plus_sent_to_model(self):\n from transformers import MODEL_MAPPING, TOKENIZER_MAPPING\n\n MODEL_TOKENIZER_MAPPING = merge_model_tokenizer_mappings(MODEL_MAPPING, TOKENIZER_MAPPING)\n\n tokenizer = self.get_tokenizer()\n if tokenizer.__class__ not in MODEL_TOKENIZER_MAPPING:\n return\n\n config_class, model_class = MODEL_TOKENIZER_MAPPING[tokenizer.__class__]\n config = config_class()\n\n if config.is_encoder_decoder or config.pad_token_id is None:\n return\n\n # Build sequence\n first_ten_tokens = list(tokenizer.get_vocab().keys())[:10]\n sequence = \" \".join(first_ten_tokens)\n encoded_sequence = tokenizer.encode_plus(sequence, return_tensors=\"np\")\n batch_encoded_sequence = tokenizer.batch_encode_plus([sequence, sequence], return_tensors=\"np\")\n\n # TODO: add forward through JAX/Flax when PR is merged\n # This is currently here to make flake8 happy !\n if encoded_sequence is None:\n raise ValueError(\"Cannot convert list to numpy tensor on encode_plus()\")\n\n if batch_encoded_sequence is None:\n raise ValueError(\"Cannot convert list to numpy tensor on batch_encode_plus()\")\n\n if self.test_rust_tokenizer:\n fast_tokenizer = self.get_rust_tokenizer()\n encoded_sequence_fast = fast_tokenizer.encode_plus(sequence, return_tensors=\"np\")\n batch_encoded_sequence_fast = fast_tokenizer.batch_encode_plus([sequence, sequence], return_tensors=\"np\")\n\n # TODO: add forward through JAX/Flax when PR is merged\n # This is currently here to make flake8 happy !\n if encoded_sequence_fast is None:\n raise ValueError(\"Cannot convert list to numpy tensor on encode_plus() (fast)\")\n\n if batch_encoded_sequence_fast is None:\n raise ValueError(\"Cannot convert list to numpy tensor on batch_encode_plus() (fast)\")\n"
] |
[
[
"torch.no_grad"
]
] |
whigg/ICESat_data_analysis_tools
|
[
"46f4132d2b34efe9a21470cdbaddf195301cfcd3"
] |
[
"get_columns.py"
] |
[
"#get_columns.py\nimport numpy as np\nimport pandas as pd\nimport glob\nimport os\nimport sys\n\ndef save_csv (file, columns):\n # saves selected columns of file into a new csv.\n # file is a string, and columns is a list of integers.\n # returns saved dataframe and new filename\n\n if os.path.getsize(file) == 0: # checks if file is empty\n print (\"File is empty. Skipping file\")\n return pd.DataFrame(), os.path.splitext(file)[0] + \"_column_restricted.csv\" # returns default dataframe and default filename\n\n df = pd.read_csv(file, header=None) #fills dataframe with info from csv file\n column_restricted_df = df.iloc[:,columns] #selects columns\n\n new_name = os.path.splitext(file)[0] + \"_column_restricted.csv\" #modifies original filename\n\n column_restricted_df.to_csv(new_name, index=False) #saves csv to file of name new_name\n return column_restricted_df, new_name # returns saved dataframe and new filename\n\n\ndef main():\n input_length = len(sys.argv) #saves length of command line input\n if input_length <= 1:\n print (\"please input a filename and/or column\") #gives error message for lack of input\n else:\n regex = sys.argv[1] #saves filename regex\n file_list = glob.glob(regex) #saves list of filenames\n\n columns = list(map(int, sys.argv[2:input_length])) #saves list of selected columns\n\n i = 1 #variable for saving current position in list\n print (file_list)\n print (regex)\n for file in file_list:\n output = save_csv(file, columns) #saves new csv file and saves method output\n print (\"Saved new csv file with path: \" + output[1])\n print (\"output {0} of {1}\".format(i, len(file_list)))\n i+=1 #increases i to new index\n\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"pandas.read_csv",
"pandas.DataFrame"
]
] |
IrvanDimetrio/Hipertensi-Classification-NearestNeighboard
|
[
"fa59fcf7dfd4a112e085c160e9a5e00a7a382b0c"
] |
[
"Step3_HipertensiPredictionKNN.py"
] |
[
"\"\"\"\r\n@author : Muhamad Irvan Dimetrio\r\nNIM : 18360018\r\nTeknik Informatika\r\nInstitut Sains dan Teknologi Nasional\r\n\"\"\"\r\nimport pandas as pd\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\n\r\n# Meload Dataset dari file csv dan mengekstrak fitur dan label classnya\r\nhipertensiDataset = pd.read_csv('hipertensi.csv', names=['Umur', 'Kegemukan', 'class'], header=0)\r\nfitur = hipertensiDataset.iloc[:, 0:2].values\r\nlabel = hipertensiDataset.iloc[:, -1].values\r\n\r\n# Mengambil algoritma K Nearest Neigbor sebagai model\r\nmodel = KNeighborsClassifier(n_neighbors=3)\r\n\r\n# Latih model menggunakan dataset\r\nmodel.fit(fitur, label)\r\n\r\n#Prediksi dengan data yang dimasukkan\r\numurInput = input(\"Umur anda ? \\n\"+ \">>>\")\r\nberatInput = input(\"Berat badan anda ? \\n\"+\">>>\")\r\numurData = float(umurInput)\r\nberatData = float(beratInput)\r\n\r\nprediksinya = model.predict([[umurData, beratData]])\r\nif prediksinya == 0:\r\n print(\"Anda Sehat\")\r\nelif prediksinya == 1:\r\n print(\"Anda Terkena Hipertensi\")\r\nelse:\r\n print(\"Maaf tidak tau. Masukin data yang bener dongg\")"
] |
[
[
"pandas.read_csv",
"sklearn.neighbors.KNeighborsClassifier"
]
] |
JonaBecher/spektral
|
[
"ad2d96549c00f68ce992a7d29e2c3fd025fb529b"
] |
[
"spektral/layers/convolutional/gcs_conv.py"
] |
[
"from tensorflow.keras import backend as K\n\nfrom spektral.layers import ops\nfrom spektral.layers.convolutional.conv import Conv\nfrom spektral.utils import normalized_adjacency\n\n\nclass GCSConv(Conv):\n r\"\"\"\n A `GraphConv` layer with a trainable skip connection.\n\n **Mode**: single, disjoint, mixed, batch.\n\n This layer computes:\n $$\n \\Z' = \\D^{-1/2} \\A \\D^{-1/2} \\X \\W_1 + \\X \\W_2 + \\b\n $$\n where \\( \\A \\) does not have self-loops.\n\n **Input**\n\n - Node features of shape `([batch], n_nodes, n_node_features)`;\n - Normalized adjacency matrix of shape `([batch], n_nodes, n_nodes)`; can be computed\n with `spektral.utils.convolution.normalized_adjacency`.\n\n **Output**\n\n - Node features with the same shape as the input, but with the last\n dimension changed to `channels`.\n\n **Arguments**\n\n - `channels`: number of output channels;\n - `activation`: activation function;\n - `use_bias`: bool, add a bias vector to the output;\n - `kernel_initializer`: initializer for the weights;\n - `bias_initializer`: initializer for the bias vector;\n - `kernel_regularizer`: regularization applied to the weights;\n - `bias_regularizer`: regularization applied to the bias vector;\n - `activity_regularizer`: regularization applied to the output;\n - `kernel_constraint`: constraint applied to the weights;\n - `bias_constraint`: constraint applied to the bias vector.\n\n \"\"\"\n\n def __init__(\n self,\n channels,\n activation=None,\n use_bias=True,\n kernel_initializer=\"glorot_uniform\",\n bias_initializer=\"zeros\",\n kernel_regularizer=None,\n bias_regularizer=None,\n activity_regularizer=None,\n kernel_constraint=None,\n bias_constraint=None,\n **kwargs\n ):\n super().__init__(\n activation=activation,\n use_bias=use_bias,\n kernel_initializer=kernel_initializer,\n bias_initializer=bias_initializer,\n kernel_regularizer=kernel_regularizer,\n bias_regularizer=bias_regularizer,\n activity_regularizer=activity_regularizer,\n kernel_constraint=kernel_constraint,\n bias_constraint=bias_constraint,\n **kwargs\n )\n self.channels = channels\n\n def build(self, input_shape):\n assert len(input_shape) >= 2\n input_dim = input_shape[0][-1]\n\n self.kernel_1 = self.add_weight(\n shape=(input_dim, self.channels),\n initializer=self.kernel_initializer,\n name=\"kernel_1\",\n regularizer=self.kernel_regularizer,\n constraint=self.kernel_constraint,\n )\n self.kernel_2 = self.add_weight(\n shape=(input_dim, self.channels),\n initializer=self.kernel_initializer,\n name=\"kernel_2\",\n regularizer=self.kernel_regularizer,\n constraint=self.kernel_constraint,\n )\n if self.use_bias:\n self.bias = self.add_weight(\n shape=(self.channels,),\n initializer=self.bias_initializer,\n name=\"bias\",\n regularizer=self.bias_regularizer,\n constraint=self.bias_constraint,\n )\n self.built = True\n\n def call(self, inputs, mask=None):\n x, a = inputs\n\n output = K.dot(x, self.kernel_1)\n output = ops.modal_dot(a, output)\n skip = K.dot(x, self.kernel_2)\n output += skip\n\n if self.use_bias:\n output = K.bias_add(output, self.bias)\n if mask is not None:\n output *= mask[0]\n output = self.activation(output)\n\n return output\n\n @property\n def config(self):\n return {\"channels\": self.channels}\n\n @staticmethod\n def preprocess(a):\n return normalized_adjacency(a)\n"
] |
[
[
"tensorflow.keras.backend.dot",
"tensorflow.keras.backend.bias_add"
]
] |
bm2-lab/X-MOL
|
[
"a64cd4222ab819326767224d91fa8605f52f4fc4"
] |
[
"FT_to_generation/pt_build_optfile.py"
] |
[
"from rdkit import Chem\nfrom rdkit import DataStructs\nfrom random import shuffle\nimport numpy as np\nimport time\nfrom rdkit.Chem import Descriptors\nfrom tqdm import tqdm\nfrom multiprocessing import Process\nimport os\nimport subprocess\n\ndef get_(similarity_lib, scale, to_file=False, n_dev=10000, show=True, ids=None):\n if type(similarity_lib) == str:\n with open(similarity_lib,'r') as f:\n libm = []\n libs = []\n for l in f:\n m, sm = l.strip().split(':')\n libm.append(m)\n libs.append(sm.split(','))\n else:\n libm = [i[0] for i in similarity_lib]\n libs = [i[1] for i in similarity_lib]\n libmq = []\n print('cal ref QEDs')\n with tqdm(total=len(libm)) as ref_pbar:\n for i in libm:\n libmq.append(Descriptors.qed(Chem.MolFromSmiles(i)))\n if show:\n ref_pbar.update()\n libsq = []\n libss = []\n print('cal candidate QEDs')\n with tqdm(total=len(libs)) as cdd_pbar:\n for lidx,i in enumerate(libs):\n temp_ = []\n k = 0\n tp = libm[lidx]\n while len(temp_)<scale and k<len(i):\n if i[k] != tp:\n temp_.append(i[k])\n k += 1\n libss.append(temp_)\n libsq.append([Descriptors.qed(Chem.MolFromSmiles(j)) for j in temp_])\n if show:\n cdd_pbar.update()\n opt = []\n optv = []\n print('build pair')\n with tqdm(total=len(libm)) as bd_pbar:\n for midx in range(len(libm)):\n diff = [abs(libmq[midx]-libsq[midx][cidx]) for cidx in range(len(libsq[midx]))]\n sel = np.argmax(diff)\n optv.append(max(diff))\n if libmq[midx]<libsq[midx][sel]:\n opt.append([libm[midx], libss[midx][sel]])\n else:\n opt.append([libss[midx][sel], libm[midx]])\n if show:\n bd_pbar.update()\n print('remove repeats')\n opt = ['&'.join(i) for i in opt]\n opt = list(set(opt))\n opt = [i.split('&') for i in opt]\n \n if to_file:\n with open(to_file,'w') as f:\n for r in opt:\n f.write(','.join([str(i) for i in r])+'\\n')\n simv = []\n print('cal pair similarity')\n with tqdm(total=len(libm)) as sv_pbar:\n for r in opt:\n simv.append(DataStructs.TanimotoSimilarity(Chem.RDKFingerprint(Chem.MolFromSmiles(r[0])),Chem.RDKFingerprint(Chem.MolFromSmiles(r[1]))))\n if show:\n sv_pbar.update()\n optv = np.mean(optv)\n simv = np.mean(simv)\n print('split data')\n idx= list(range(len(opt)))\n shuffle(idx)\n train_idx = idx[:-10000]\n dev_idx = idx[-10000:]\n train_opt = [opt[i] for i in train_idx]\n dev_opt = [opt[i] for i in dev_idx]\n\n if ids == None:\n return train_opt, dev_opt, optv, simv\n else:\n with open('train_subprocess_{0}.tsv'.format(ids), 'w') as f:\n for r in train_opt:\n f.write('{0}\\t{1}\\n'.format(r[0], r[1]))\n with open('dev_subprocess_{0}.tsv'.format(ids), 'w') as f:\n for r in dev_opt:\n f.write('{0}\\t{1}\\n'.format(r[0], r[1]))\n with open('rec_subprocess_{0}'.format(ids),'w') as f:\n f.write('{0}\\n'.format(optv))\n f.write('{0}\\n'.format(simv))\n\n\ndef get_s(similarity_lib, scale, to_file=False, n_dev=10000, show=True, ids=None):\n if type(similarity_lib) == str:\n with open(similarity_lib,'r') as f:\n libm = []\n libs = []\n for l in f:\n m, sm = l.strip().split(':')\n libm.append(m)\n libs.append(sm.split(','))\n else:\n libm = [i[0] for i in similarity_lib]\n libs = [i[1] for i in similarity_lib]\n libmq = []\n libmfp = []\n print('cal ref QEDs')\n with tqdm(total=len(libm)) as ref_pbar:\n for i in libm:\n rmol = Chem.MolFromSmiles(i)\n libmfp.append(Chem.RDKFingerprint(rmol))\n libmq.append(Descriptors.qed(rmol))\n if show:\n ref_pbar.update()\n opt = []\n optv = []\n simv = []\n print('build pair')\n with tqdm(total=len(libm)) as bd_pbar:\n for midx in range(len(libm)):\n rfp = libmfp[midx]\n rq = libmq[midx]\n max_d = 0\n csmi = 'C1CCCCC1'\n sim_v = 0\n for cdd in libs[midx]:\n cmol = Chem.MolFromSmiles(cdd)\n cfp = Chem.RDKFingerprint(cmol)\n sim = DataStructs.TanimotoSimilarity(rfp, cfp)\n if sim<scale[1] and sim>scale[0]:\n cq = Descriptors.qed(cmol)\n diff = cq - rq\n if diff > max_d:\n csmi = cdd\n max_d = diff\n sim_v = sim\n if max_d > 0:\n opt.append([libm[midx], csmi])\n optv.append(max_d)\n simv.append(sim_v)\n if show:\n bd_pbar.update()\n if to_file:\n with open(to_file,'w') as f:\n for r in opt:\n f.write(','.join([str(i) for i in r])+'\\n')\n\n print('split data')\n idx= list(range(len(opt)))\n shuffle(idx)\n if len(opt)<n_dev:\n n = len(str(len(opt)))-1\n kn = '1'+'0'*n\n kn = int(int(kn)/10)\n else:\n kn = n_dev\n train_idx = idx[:-kn]\n dev_idx = idx[-kn:]\n train_opt = [opt[i] for i in train_idx]\n dev_opt = [opt[i] for i in dev_idx]\n\n if ids == None:\n return train_opt, dev_opt, optv, simv\n else:\n with open('train_subprocess_{0}.tsv'.format(ids), 'w') as f:\n for r in train_opt:\n f.write('{0}\\t{1}\\n'.format(r[0], r[1]))\n with open('dev_subprocess_{0}.tsv'.format(ids), 'w') as f:\n for r in dev_opt:\n f.write('{0}\\t{1}\\n'.format(r[0], r[1]))\n optv = np.array(optv)\n simv = np.array(simv)\n np.save('simv_subprocess_{0}.npy'.format(ids), simv)\n np.save('optv_subprocess_{0}.npy'.format(ids), optv)\n\n\ndef multi(similarity_lib, n_jobs, scale, n_dev=10000):\n lib = []\n with open(similarity_lib,'r') as f:\n for l in f:\n m, sm = l.strip().split(':')\n lib.append([m, sm.split(',')])\n n_jobs = max(n_jobs, 1)\n recn_per_job = round(len(lib)/n_jobs)\n rec_lists = [lib[i*recn_per_job:(i+1)*recn_per_job] for i in range(n_jobs-1)]\n rec_lists.append(lib[(n_jobs-1)*recn_per_job:])\n n_dev = int(n_dev/n_jobs)\n \n sub_process = []\n for sp in range(n_jobs):\n sub_process.append(Process(target=get_s, args=(rec_lists[sp], scale, False, n_dev, False, sp)))\n for sp in sub_process:\n sp.start()\n for sp in sub_process:\n sp.join()\n # merge files and remove temporary files\n train_opt = []\n dev_opt = []\n simv = []\n optv = []\n\n for spf in range(n_jobs):\n with open('train_subprocess_{0}.tsv'.format(spf)) as f:\n train_sp = f.readlines()\n train_sp = [i.strip().split('\\t') for i in train_sp]\n train_opt += train_sp\n with open('dev_subprocess_{0}.tsv'.format(spf)) as f:\n dev_sp = f.readlines()\n dev_sp = [i.strip().split('\\t') for i in dev_sp]\n dev_opt += dev_sp\n simv_sp = np.load('simv_subprocess_{0}.npy'.format(spf))\n simv += list(simv_sp)\n optv_sp = np.load('optv_subprocess_{0}.npy'.format(spf))\n optv += list(optv_sp)\n subprocess.call('rm train_subprocess_{0}.tsv'.format(spf), shell=True)\n subprocess.call('rm dev_subprocess_{0}.tsv'.format(spf), shell=True)\n subprocess.call('rm simv_subprocess_{0}.npy'.format(spf), shell=True)\n subprocess.call('rm optv_subprocess_{0}.npy'.format(spf), shell=True)\n\n return train_opt, dev_opt, optv, simv\n"
] |
[
[
"numpy.array",
"numpy.mean",
"numpy.argmax"
]
] |
jayliu99/bcbn
|
[
"6ec0977299c66c224877ec953b64d34f9b74c6f6"
] |
[
"learning.py"
] |
[
"import sys, csv\nimport random\nimport pandas as pd\nimport numpy as np\n\nimport itertools as it\nimport time\nimport networkx as nx\nfrom matplotlib import pyplot as plt\nimport scipy.special as sc\nimport math\n\nimport scipy.sparse as sps\nfrom collections import defaultdict\n\nfrom pomegranate import *\n\n\ndef naive_bayes(X):\n\t\"\"\"\n\tTakes the data to fit the structure too, where each \n row is a sample and each column corresponds to the associated variable.\n Builds a naive bayes network, calculates probabilities according to MLE,\n and returns the resulting network.\n\n\t:param X: numpy array, shape (n_samples, n_nodes)\n\t:returns model: Pomegranate Bayesian network object\n\n\t\"\"\"\n\t# NODES IN NETWORK:\n\t# s0 = State( diagnosis, name=\"diagnosis\" )\n\t# s1 = State( symmetry_se, name=\"symmetry_se\" )\n\t# s2 = State( compactness_worst, name=\"compactness_worst\" )\n\t# s3 = State( radius_worst, name=\"radius_worst\" )\n\t# s4 = State( smoothness_worst, name=\"smoothness_worst\" )\n\t# s5 = State( radius_mean, name=\"radius_mean\" )\n\t# s6 = State( concavity_mean, name=\"concavity_mean\" )\n\t# s7 = State( concavePoints_worst, name=\"concavePoints_worst\" )\n\t# s8 = State( texture_se, name=\"texture_se\" )\n\t# s9 = State( area_worst, name=\"area_worst\" )\n\t# s10 = State( area_se, name=\"area_se\" )\n\t# s11 = State( concavePoints_se, name=\"concavePoints_se\" )\n\t# s12 = State( compactness_se, name=\"compactness_se\" )\n\t# s13 = State( texture_mean, name=\"texture_mean\" )\n\t# s14 = State( symmetry_worst, name=\"symmetry_worst\" )\n\t# s15 = State( compactness_mean, name=\"compactness_mean\" )\n\t# s16 = State( concavity_se, name=\"concavity_se\" )\n\t# s17 = State( perimeter_se, name=\"perimeter_se\" )\n\t# s18 = State( fractalDimension_mean, name=\"fractalDimension_mean\" )\n\t# s19 = State( concavePoints_mean, name=\"concavePoints_mean\" )\n\t# s20 = State( smoothness_se, name=\"smoothness_se\" )\n\t# s21 = State( smoothness_mean, name=\"smoothness_mean\" )\n\t# s22 = State( concavity_worst, name=\"concavity_worst\" )\n\t# s23 = State( symmetry_mean, name=\"symmetry_mean\" )\n\t# s24 = State( radius_se, name=\"radius_se\" )\n\t# s25 = State( perimeter_worst, name=\"perimeter_worst\" )\n\t# s26 = State( area_mean, name=\"area_mean\" )\n\t# s27 = State( fractalDimension_worst, name=\"fractalDimension_worst\" )\n\t# s28 = State( texture_worst, name=\"texture_worst\" )\n\t# s29 = State( fractalDimension_se, name=\"fractalDimension_se\" )\n\t# s30 = State( perimeter_mean, name=\"perimeter_mean\" )\n\n\n\tnetwork = BayesianNetwork( \"Breast Cancer Biopsies\" )\n\n\t# Add nodes to the network\n\tfor col in range(X.shape[1]):\n\t\tnetwork.add_node(col)\n\n\tdiagnosis_state = [0]\n\tsymptom_states = [i for i in range(1, X.shape[1])]\n\n\t# BUILD MODEL USING FROM_SAMPLES FUNCTION WITH SPEED UP ARGUMENTS.\n\t# ----------------------------------------------------------------------\n\t# Add edges to the network\n\tfor edge in list(it.product(symptom_states, diagnosis_state)):\n\t\tnetwork.add_edge(edge[0], edge[1])\n\n\t# Fit data to Naive Bayes structure\n\t# Algorithm options: 'chow-liu' (fast), ‘greedy’, ‘exact’, ‘exact-dp’ \n\tALGORITHM = 'greedy'\t\t\n\t# Root options: For algorithms which require a single root (‘chow-liu’), this is the root for which all edges point away from. \n\t# \t\t\t\tUser may specify which column to use as the root. Default is the first column.\n\tROOT = 2\n\t# n_jobs options: The number of threads to use when learning the structure. Will parallelize if constraint graph provided.\n\tN_JOBS = 5\n\tmodel = network.from_samples(X, algorithm=ALGORITHM, constraint_graph=network, name=\"Breast Cancer Biopsy Model\", n_jobs=N_JOBS)\n\n\n\t# BUILD MODEL USING FROM_STRUCTURE FUNCTION --- SEEMS SLOW.\n\t# ----------------------------------------------------------------------\n\t# Define parents for each node:\n\t# Naive Bayes structure: node 0 (diagnosis) has 30 parents, other nodes\n\t# have no parents.\n\t# parents = (tuple(symptom_states), )\n\t# for state in symptom_states:\n\t# \tparents = parents + ((), )\n\n\t# # Fit data to Naive Bayes structure\n\t# model = network.from_structure(X, structure=parents, name=\"Breast Cancer Naive Bayesian\")\n\t\n\n\treturn model\n\n\ndef struct_learning(X):\n\t\"\"\"\n\tTakes the data to fit the structure too, where each \n row is a sample and each column corresponds to the associated variable.\n Constructs a probable network\n and returns the resulting network.\n\n\t:param X: numpy array, shape (n_samples, n_nodes)\n\t:returns model: Pomegranate Bayesian network object\n\n\t\"\"\"\n\tnetwork = BayesianNetwork( \"Breast Cancer Biopsies\" )\n\t# Learn structure from data.\n\t# Algorithm options: 'chow-liu' (fast), ‘greedy’, ‘exact’, ‘exact-dp’\n\tALGORITHM = 'chow-liu'\t \n\t# Max parents options: Set to a lower number if you want to speed up learning. (Default: total number of nodes - 1)\n\tMAX_PARENTS = X.shape[1] - 1\t\t\n\t#MAX_PARENTS = 1\n\t# Root options: For algorithms which require a single root (‘chow-liu’), this is the root for which all edges point away from. \n\t# \t\t\t\tUser may specify which column to use as the root. Default is the first column.\n\tROOT = 2\n\tmodel = network.from_samples(X, algorithm=ALGORITHM, max_parents=MAX_PARENTS, root=ROOT, name=\"Breast Cancer Biopsy Model\")\n\treturn model\n\n\ndef plot(network):\n\t\"\"\"\n\tPlots the network found by the model as a directed graph\n\tRequires user to install matplolib and pygraphviz\n\n\tpygraphviz install commands (if you're having trouble):\n\t\n\tbrew install graphviz\n\tpip install --install-option=\"--include-path=/usr/local/include/\" --install-option=\"--library-path=/usr/local/lib/\" pygraphviz\n\n\t:param network: Pomegranate Bayesian network model\n\t\"\"\"\n\tplt.figure(figsize=(16, 8))\n\tnetwork.plot()\n\tplt.show()\n\n\ndef score_learning_strategy(predicted, true):\n\n\tdata = {'y_Actual': true, 'y_Predicted': predicted}\n\n\tdf = pd.DataFrame(data, columns=['y_Actual','y_Predicted'])\n\tconfusion_matrix = pd.crosstab(df['y_Actual'], df['y_Predicted'], rownames=['Actual'], colnames=['Predicted'])\n\tprint (confusion_matrix)\n\n\ndef main():\n\n\tdata = pd.read_csv('p_data.csv').to_numpy()\n\tX = data[:, 1:]\n\n\t# Keep track of these values for accuracy metrics.\n\taccuracies = list()\n\ttrue_diagnoses = list(data[:, 1])\n\tpredicted_diagnoses = list()\n\n\tt0 = time.time()\n\n\t# Due to dataset size, we will perform leave one out cross validation:\n\tfor r in range(X.shape[0]):\n\n\t\tprint(\"Building model %s... \" %r)\n\n\t\ttrain = np.copy(X) \n\t\ttrain = np.delete(train, r, axis=0)\n\t\ttest_X = np.copy(X[r,:]).reshape((1, X.shape[1]))\n\t\tactual_diagnosis = test_X[0, 0]\n\n\t\t# Remove the actual diagnosis from the test sample\n\t\ttest_X[0, 0] = np.nan\n\n\t\t# Option 1: Naive Bayes\n\t\t#network = naive_bayes(train)\n\n\t\t# Option 2: Structure learning\n\t\tnetwork = struct_learning(train)\n\n\t\t# Plot learned network\n\t\t#plot(network)\n\n\t\t# Used learned network to make a prediction\n\t\tpredicted_diagnosis = network.predict(test_X)[0][0]\n\t\tpredicted_diagnoses.append(predicted_diagnosis)\n\n\t# Score final learning strategy\n\tscore_learning_strategy(predicted_diagnoses, true_diagnoses)\n\n\tt1 = time.time()\n\n\t# Print total runtime.\n\t#print(\"TOTAL RUNTIME: \", t1-t0)\n\n\nif __name__ == '__main__':\n\tmain()\n"
] |
[
[
"pandas.crosstab",
"pandas.read_csv",
"pandas.DataFrame",
"numpy.copy",
"numpy.delete",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] |
microbial-pangenomes-lab/2021_ecoli_pathogenicity
|
[
"f25925c21679e2f89692ae3cfa512060c8bc04bf"
] |
[
"workflow/scripts/mapped_summary.py"
] |
[
"#!/usr/bin/env python\n\n\nimport sys\nimport argparse\nimport numpy as np\nimport pandas as pd\n\n\ndef get_options():\n description = 'Make a summary of mapped unitigs'\n parser = argparse.ArgumentParser(description=description)\n\n parser.add_argument('mapped',\n help='Mapped unitigs table (all strains)')\n parser.add_argument('phenotypes',\n help='Phenotypes table')\n parser.add_argument('phenotype',\n help='Phenotype to use (column name; should be binary)')\n parser.add_argument('filtered',\n help='Filtered variants table')\n\n parser.add_argument('--unique',\n default=False,\n action='store_true',\n help='Only look at uniquely-mapping unitigs (default: false)')\n parser.add_argument('--length',\n type=int,\n default=30,\n help='Minimum unitig length (default: %(default)d)')\n parser.add_argument('--minimum-hits',\n type=int,\n default=1,\n help='Minimum number of strains (default: %(default)d)')\n parser.add_argument('--maximum-genes',\n type=int,\n default=10,\n help='Maximum number of genes to which '\n 'a unitig can map to (default: %(default)d)')\n parser.add_argument('--pangenome',\n default=None,\n help='Panaroo Rtab output '\n 'to single out core genes (default: do not provide this)')\n\n return parser.parse_args()\n\n\nif __name__ == \"__main__\":\n options = get_options()\n\n # read phenotypes\n p = pd.read_csv(options.phenotypes, sep='\\t', index_col=0)\n p = p[options.phenotype]\n p.name = 'phenotype'\n # not checking if binary\n\n pangenome = {}\n if options.pangenome is not None:\n df = pd.read_csv(options.pangenome, sep='\\t', index_col=0)\n df = df.T.sum() / df.shape[1]\n pangenome = df.to_dict()\n\n m = pd.read_csv(options.mapped, sep='\\t', index_col=0)\n # check empty\n if m.shape[0] == 0:\n sys.exit(0)\n # remove duplicated rows (?!)\n m = m.drop_duplicates(keep='first')\n #\n if options.unique:\n #singletons = m.groupby(['unitig', 'strain'])['start'].count().reset_index().groupby('unitig')['start'].max()\n singletons = m.groupby(['unitig', 'strain'])['start'].count()\n singletons = singletons[singletons <= 1]\n #m = m[m['unitig'].isin(singletons.index)]\n m = m[m['unitig'].isin({x[0] for x in singletons.index})]\n # remove unitigs that map to multiple genes across strains\n u = m.groupby('unitig')['gene'].nunique()\n m = m[m['unitig'].isin(u[u <= options.maximum_genes].index)]\n # remove short unitigs\n m['length'] = [len(x) for x in m['unitig'].values]\n m = m[m['length'] >= options.length]\n # check empty\n if m.shape[0] == 0:\n sys.exit(0)\n n = m.join(p.to_frame(), how='left').reset_index().rename(columns={'index':\n 'strain'})\n\n n = n.groupby(['phenotype',\n 'gene'])['strain'\n ].nunique().reset_index().pivot_table(index='gene',\n columns='phenotype', values='strain')\n # check missing columns\n if 1 not in n.columns:\n n[1] = 0\n if 0 not in n.columns:\n n[0] = 0\n n = n.sort_values(1, ascending=False)\n n[np.isnan(n)] = 0\n\n f = pd.read_csv(options.filtered, sep='\\t', index_col=0)\n # ugly hack\n if 'lineage' not in f.columns:\n try:\n f.columns = ['af', 'filter-pvalue', 'lrt-pvalue', 'beta', 'lineage', 'notes']\n except:\n pass\n #\n v = m.reset_index().set_index('unitig').join(f, how='left')\n c = v.groupby('gene')[['af']].count().rename(columns={'af': 'unitigs'})\n if 'variant_h2' not in v.columns:\n v['variant_h2'] = np.nan\n v = v.groupby('gene')[['af', 'lrt-pvalue', 'beta', 'variant_h2']].mean()\n v = v.rename(columns={'af': 'avg-af',\n 'lrt-pvalue': 'avg-lrt-pvalue',\n 'beta': 'avg-beta'})\n\n a = n.join(v).join(c).sort_values('avg-lrt-pvalue')\n # check missing columns\n if 1 not in a.columns:\n a[1] = 0\n if 0 not in a.columns:\n a[0] = 0\n #\n a = a[[0, 1, 'unitigs',\n 'avg-af', 'avg-lrt-pvalue',\n 'avg-beta', 'variant_h2']]\n # remove genes that are present in few strains total\n a = a[(a[0] + a[1]) >= options.minimum_hits]\n # add pangenome info\n a['pangenome-frequency'] = [pangenome.get(x, np.nan)\n for x in a.index]\n a['pangenome-category'] = np.nan\n a.loc[a[a['pangenome-frequency'] >= 0.99].index,\n 'pangenome-category'] = 'core'\n a.loc[a[(a['pangenome-frequency'] < 0.99) &\n (a['pangenome-frequency'] >= 0.95)].index,\n 'pangenome-category'] = 'soft-core'\n a.loc[a[(a['pangenome-frequency'] < 0.95) &\n (a['pangenome-frequency'] >= 0.15)].index,\n 'pangenome-category'] = 'shell'\n a.loc[a[a['pangenome-frequency'] < 0.15].index,\n 'pangenome-category'] = 'cloud'\n a.to_csv(sys.stdout, sep='\\t')\n"
] |
[
[
"numpy.isnan",
"pandas.read_csv"
]
] |
akashlevy/NEM-Relay-CGRA
|
[
"13aa2b7c2a7a583ec35e7ee6af424075d6e8a8f4"
] |
[
"gls/results/delayplot.py"
] |
[
"import glob, re\nimport altair as alt, numpy as np, matplotlib.pyplot as plt, pandas as pd\n\nCLK_PER = 5\nHEADER = ['Hinst Name', 'Module Name', 'Inst Count', 'Total Area', 'Buffer', 'Inverter', 'Combinational', 'Flop', 'Latch', 'Clock Gate', 'Macro', 'Physical']\nMODULES = ['PE Core', 'CBs', 'SB', 'Other']\nDESIGNMAP = {\n 'vanilla': 'CMOS',\n 'nems_invd1': 'NEMS'\n }\n\n# Read power reports and convert into organized pandas DataFrame\ndef read_power_to_df(path='*/report_timing_pba.report'):\n # Data\n data = []\n\n # Search in path\n for powfname in glob.glob(path):\n # Get app name from file name\n typ = powfname.split('/')[0]\n\n # Read power files\n lines = open(powfname).read()\n critpath = lines.split('Path Type: max\\n\\n''')[1]\n critpath = critpath.split('\\n data arrival time')[0]\n # print(critpath)\n\n for i, line in enumerate(critpath.split('\\n')[4:]):\n if line[-1] not in 'rf':\n continue\n vals = line.split()\n data.append({\n 'Name' : 'input external delay' if i == 0 else vals[0],\n 'Cell' : '' if i == 0 else vals[1],\n 'Cell Delay' : float(vals[-3]) if i == 0 else float(vals[-4]),\n 'Path Delay' : float(vals[-2]),\n 'Type' : vals[-1],\n 'Design' : typ, \n 'Clk' : 5 if typ[0] == 'n' else 4.3\n })\n \n # Convert to DataFrame\n return pd.DataFrame(data)\n\nif __name__ == '__main__':\n # Get data\n data = read_power_to_df()\n\n # Use only one set of results\n data = data[data['Design'].isin(DESIGNMAP.keys())]\n\n # Data replacement\n data.replace(DESIGNMAP, inplace=True)\n\n # Rename high-level components and filter the rest\n data['Module'] = data['Name']\n data['Module'].replace(re.compile(r'cb_data\\d+.*'), 'CB', inplace=True)\n data['Module'].replace(re.compile(r'test_pe.*'), 'PE Core', inplace=True)\n data['Module'].replace(re.compile(r'sb_wide.*'), 'SB', inplace=True)\n data['Module'].replace(re.compile(r'sb_1b.*'), 'SB', inplace=True)\n data['Module'].replace(re.compile(r'cb_cg_en.*'), 'CB', inplace=True)\n data['Module'].replace(re.compile(r'cb_bit.*'), 'CB', inplace=True)\n data['Module'].replace(re.compile(r'in.*'), 'I/O', inplace=True)\n data['Module'].replace(re.compile(r'out.*'), 'I/O', inplace=True)\n # print(data)\n\n # Plot the delay: comparison\n areadata = data.copy()\n areadata['CellDelay'] = areadata['Cell Delay']\n areadata = areadata.groupby(['Module', 'Design']).sum().reset_index()\n print(areadata)\n chart = alt.Chart(areadata).mark_bar().encode(\n # tell Altair which field to group columns on\n x=alt.X('Design:N', title=None),\n\n # tell Altair which field to use as Y values and how to calculate\n y=alt.Y('sum(CellDelay):Q', axis=alt.Axis(title=\"Path Delay (ns)\")),\n\n # tell Altair which field to use for color segmentation \n color=alt.Color('Module:N')\n ).configure_view(\n # remove grid lines around column clusters\n strokeOpacity=0 \n ).properties(width=160, height=100)\n chart.show()\n"
] |
[
[
"pandas.DataFrame"
]
] |
mahdihosseini/HistoKT
|
[
"0d23d4210a14f2f227e129cb7deec78d483ea8f5"
] |
[
"dataset_processing/preprocessing/BCSSProcessing.py"
] |
[
"from pathlib import Path\n\nfrom torchvision.datasets.folder import default_loader\nimport numpy as np\nimport pandas as pd\nimport os\nimport csv\nfrom transforms import ProcessImages\nfrom skimage import io\nimport pickle\nimport random\n\n\nclass BCSSLoader:\n \"\"\"loader to return tuples of pillow images and metadata, as well as a class to idx dictionary\"\"\"\n folder = \"0_Public-data-Amgad2019_0.25MPP\"\n MPP = 0.25\n image_dir = \"rgbs_colorNormalized\"\n masks_dir = \"masks\"\n g_truths = \"meta/gtruth_codes.tsv\"\n\n def __init__(self, root):\n self.root = root\n self.class_to_value = {}\n with open(os.path.join(root, self.folder, self.g_truths)) as classes_tsv:\n classes = csv.DictReader(classes_tsv, dialect='excel-tab')\n self.class_to_value = {row[\"label\"]: int(row[\"GT_code\"]) for row in classes}\n\n self.file_names = []\n for root_dir, _, files in os.walk(os.path.join(root, self.folder, self.image_dir)):\n for file in files:\n self.file_names.append(file)\n\n self.samples = [(os.path.join(root, self.folder, self.image_dir, image_name),\n os.path.join(root, self.folder, self.masks_dir, image_name))\n for image_name in self.file_names]\n\n def __getitem__(self, item):\n return self.samples[item]\n\n def __len__(self):\n return len(self.samples)\n\n\ndef process_BCSS(root,\n class_list,\n target_folder,\n scale=0.25,\n target_dim=(272, 272),\n percent_overlap=0.5,\n intensity_threshold=0.8,\n occurrence_threshold=0.975,\n show_imgs=False,\n low_contrast=True,\n lower_percentile=5,\n upper_percentile=99,\n label_threshold=0.5,\n split_dict={\"train\": 100}):\n new_samples = []\n image_dataset = BCSSLoader(root)\n\n class_to_idx = {cls: i for i, cls in enumerate(class_list)}\n for i in range(len(image_dataset)):\n image_path, mask_path = image_dataset[i]\n image = np.array(default_loader(image_path))\n mask = np.array(default_loader(mask_path))\n\n rescaled_img = ProcessImages.scale_img(image, scale)\n rescaled_mask = ProcessImages.scale_img(mask, scale)\n\n if rescaled_img.shape[0] > target_dim[0] and \\\n rescaled_img.shape[1] > target_dim[1]:\n # handle larger image cropping here\n out_images = ProcessImages.crop(rescaled_img, target_dim, percent_overlap)\n out_masks = ProcessImages.crop(rescaled_mask, target_dim, percent_overlap)\n\n else:\n\n out_img = ProcessImages.reflection_wrap(rescaled_img,\n dim=target_dim)\n out_mask = ProcessImages.reflection_wrap(rescaled_mask,\n dim=target_dim)\n\n out_images = ProcessImages.crop(out_img, target_dim, percent_overlap)\n out_masks = ProcessImages.crop(out_mask, target_dim, percent_overlap)\n\n # remove images containing too much background\n filtered_images = ProcessImages.remove_background(out_images,\n intensity_threshold,\n occurrence_threshold,\n low_contrast,\n lower_percentile,\n upper_percentile)\n\n # save out_img with the same file structure as the dataset in\n # different folder\n\n image_path = Path(image_path)\n image_path = image_path.relative_to(root)\n image_path = Path(os.path.join(target_folder, image_path))\n\n for j, (image2save, mask2save) in enumerate(zip(filtered_images, out_masks)):\n if type(image2save) is tuple:\n print(image_path.stem + f\"-{j}\" + \".png\" + \" is a background image because\", image2save[1])\n if show_imgs:\n io.imshow(image2save[0])\n io.show()\n continue\n\n labels = mask_to_vec(mask2save,\n class_to_value=image_dataset.class_to_value,\n class_list=class_list,\n norm=True)\n\n if sum(labels) < label_threshold:\n print(image_path.stem + f\"-{j}\" + \".png\" + \" is a background image because not enough label\")\n if show_imgs:\n io.imshow(image2save)\n io.show()\n continue\n\n filename = image_path.stem + f\"-{j}\" + \".png\"\n save_path = str(image_path).replace(image_path.name, filename)\n save_path = Path(save_path)\n new_samples.append((str(save_path.relative_to(target_folder)), labels))\n save_path.parent.mkdir(parents=True, exist_ok=True)\n io.imsave(str(save_path), image2save)\n split_and_save_samples(new_samples, target_folder, split_dict=split_dict)\n save_class_to_idx({cls: i for i, cls in enumerate(class_list)}, target_folder)\n return\n\n\ndef mask_to_vec(mask, class_to_value, class_list, norm=True, RGB_mask=True):\n \"\"\"takes in a numpy array for the mask image, and returns a normalized class distribution\"\"\"\n if RGB_mask:\n mask = mask[:, :, 0]\n unique, counts = np.unique(mask, return_counts=True)\n\n value_to_num = {value: num for value, num in zip(unique, counts)}\n\n output = [value_to_num[class_to_value[cls]] if class_to_value[cls] in value_to_num else 0.0 for cls in class_list ]\n\n if norm:\n output /= sum(counts)\n\n return output\n\n\ndef split_and_save_samples(samples, target_folder, split_dict) -> None:\n \"\"\"\n splits samples into folds specified by self.split_dict\n saves splits in the target folder as {split_name}.pickle\n Args:\n samples: list\n list of (path, label) to be saved\n\n Returns:\n None\n \"\"\"\n random.shuffle(samples)\n dataset_length = len(samples)\n\n cumulative_percentage = 0\n for split_name, percentage in split_dict.items():\n start_index = int(cumulative_percentage / 100 * dataset_length)\n end_index = int((cumulative_percentage + percentage) / 100 * dataset_length)\n end_index = end_index if end_index < dataset_length else dataset_length\n split_samples = samples[start_index:end_index]\n\n # saving split samples:\n with open(os.path.join(target_folder, split_name + \".pickle\"), \"wb\") as f:\n pickle.dump(split_samples, f)\n cumulative_percentage += percentage\n\n\ndef save_class_to_idx(class_to_index, target_folder):\n with open(os.path.join(target_folder, \"class_to_idx.pickle\"), \"wb\") as f:\n pickle.dump(class_to_index, f)\n\n\nif __name__ == \"__main__\":\n root = \"C:\\\\Users\\\\ryanr\\\\Desktop\\\\Summer_Research\\\\HistoKT\\\\.adas-data\"\n target_folder = \"BCSS_transformed\"\n target_folder = os.path.join(root, target_folder)\n\n class_list = ['tumor',\n 'stroma',\n 'lymphocytic_infiltrate',\n 'necrosis_or_debris',\n 'glandular_secretions',\n 'blood',\n 'metaplasia_NOS',\n 'fat',\n 'plasma_cells',\n 'blood_vessel']\n process_BCSS(root,\n class_list,\n target_folder,\n scale=0.25,\n target_dim=(272, 272),\n percent_overlap=0.75,\n intensity_threshold=0.8,\n occurrence_threshold=0.975,\n show_imgs=False,\n low_contrast=True,\n lower_percentile=5,\n upper_percentile=99,\n label_threshold=0.2,\n split_dict={\"train\": 80, \"valid\": 10, \"test\": 10})\n"
] |
[
[
"numpy.unique"
]
] |
OpenXAIProject/Real-time-Financial-Data
|
[
"f94ddd3bb58e0b4bfdb95b366dddf49d30567741"
] |
[
"web_crawler_01_22_2018_github_v1.py"
] |
[
"#Copyright 2018 UNIST under XAI Project supported by Ministry of Science and ICT, Korea\n\n#Licensed under the Apache License, Version 2.0 (the \"License\"); \n#you may not use this file except in compliance with the License.\n#You may obtain a copy of the License at\n\n# https://www.apache.org/licenses/LICENSE-2.0\n\n#Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.\n\n# coding: utf-8\n\n# In[1]:\n\nimport os\nimport sys\nfrom bs4 import BeautifulSoup\nimport requests\nfrom __future__ import print_function, unicode_literals\nimport pandas as pd\nimport numpy as np\nimport csv\n\n\n# In[3]:\n\n#get webpage\ndef get_web(url):\n r=requests.get(url)\n c=r.content\n decoded=BeautifulSoup(c, 'html.parser')\n return decoded\n\n\n# In[5]:\n\n#get Naver Finance web page\nexchange_address='http://finance.naver.com/marketindex/?tabSel=exchange#tab_section'\ncontent=get_web(exchange_address)\n\n\n# In[6]:\n\n#find currency exchange rate\ncurrent_exchange=[]\nfor table in content.findAll('div', {'class':'data'}):\n for body in table.findAll('span', {'class':'value'}):\n current_exchange.append(body.string)\n\n\n# In[8]:\n\n#get web page2\nrate_address='http://www.global-rates.com/interest-rates/central-banks/central-banks.aspx'\ncontent2=get_web(rate_address)\n\n\n# In[9]:\n\n#find base interest rate\nbase_rate=[]\nfor table in content2.findAll('tr'):\n for body in table.findAll('tr', {'class':'tabledata1'}):\n for number in body.findAll('td'):\n base_rate.append(number.string)\n\nbase_rate2=[]\nfor table in content2.findAll('tr'):\n for body in table.findAll('tr', {'class':'tabledata2'}):\n for number in body.findAll('td'):\n base_rate2.append(number.string) \n \nusd=base_rate[2].replace('\\xa0','')\neur=base_rate[32].replace('\\xa0','')\nkrw=base_rate2[8].replace('\\xa0','')\ncny=base_rate2[20].replace('\\xa0','')\njpy=base_rate2[44].replace('\\xa0','')\n\n\n# In[10]:\n\nexchange_rate_total=[current_exchange[0], current_exchange[2], current_exchange[1], current_exchange[3],'-']\nbase_rate_total=[usd, eur, jpy, cny, krw]\ntotal=[exchange_rate_total, base_rate_total]\n\narray=np.array(total)\ndf=pd.DataFrame(array, columns=['미국','유럽','일본','중국', '한국'])\n\n\n# In[11]:\n\ndf.rename(index={0:\"환전 고시 환율\", 1:\"기준 금리\"})\n\n"
] |
[
[
"numpy.array",
"pandas.DataFrame"
]
] |
mtrazzi/gomoku
|
[
"5a83da929ebba902ef9992ff0706b1a6f8948026"
] |
[
"src/gomoku/utils.py"
] |
[
"import numpy as np\n\nSLOPES = np.array([[1, 0], [-1, 1], [0, 1], [1, 1]])\n\n\ndef coordinates(x, y, dx, dy, nb_consecutive=5):\n \"\"\"Coordinates of consecutive intersections from (x,y) directed by (dx,dy).\"\"\"\n return [(x + i * dx, y + i * dy) for i in range(nb_consecutive)]\n\n\ndef boundaries(coord):\n x_0, y_0, x_1, y_1 = coord[0][0], coord[0][1], coord[-1][0], coord[-1][1]\n return min(x_0, x_1), max(x_0, x_1), min(y_0, y_1), max(y_0, y_1)\n\n\ndef all_equal(coord, pos, color):\n \"\"\"Check if all the given coordinates are equal to color in pos.\"\"\"\n x_min, x_max, y_min, y_max = boundaries(coord)\n if not (x_min >= 0 and x_max <= len(pos) - 1 and\n y_min >= 0 and y_max <= len(pos) - 1):\n return False\n colors = [pos[p[0]][p[1]] for p in coord]\n return (colors[1:] == colors[:-1] and colors[0] == color)\n\n\ndef is_there_stones_around(position, x, y):\n size = position.shape[0]\n return (((x > 0) and\n ((y > 0 and position[x - 1][y - 1] > 0) or\n position[x - 1][y] > 0 or\n (y < size - 1 and position[x - 1][y + 1]))) or\n ((y > 0 and position[x][y - 1] > 0) or\n (position[x][y] > 0) or\n (y < size - 1 and position[x][y + 1])) or\n ((x < size - 1) and\n ((y > 0 and position[x + 1][y - 1] > 0) or\n position[x + 1][y] > 0 or\n (y < size - 1 and position[x + 1][y + 1]))))\n\n\ndef opposite(color):\n return 3 - color\n\n\ndef move(x, y):\n return x - 1, y - 1\n\n\ndef human_move(move):\n return move[0] + 1, move[1] + 1\n\n\ndef count_stones(position, color):\n unique, counts = np.unique(color, return_counts=True)\n return dict(zip(unique, counts))[color]\n\n\ndef indefensible_four(board, coords, color):\n indefensibles = 0\n for i in range(1, 6):\n v, w = coords[i]\n if not board.is_empty(v, w):\n continue\n board.place(v, w, color)\n same = 0\n empty = 0\n for x, y in coords:\n if board.is_empty(x, y):\n if same == 0:\n empty = 1\n continue\n elif same == 4:\n empty += 1\n break\n elif board.is_stone(x, y, color):\n same += 1\n elif not board.is_stone(x, y, color) and same == 0:\n continue\n else:\n break\n if same >= 4 and empty >= 2:\n indefensibles += 1\n board.remove(v, w)\n return indefensibles\n\n\ndef get_player(gameHandler, color, maximizingPlayer):\n players = gameHandler.players\n player = players[0] if players[0].color == color else players[1]\n opponent = players[1] if players[0].color == color else players[0]\n return player if maximizingPlayer else opponent\n\n\ndef impact(stone, x, y):\n dx, dy = abs(stone[0] - x), abs(stone[1] - y)\n return (dx < 6 and dy == 0) or (dy < 6 and dx == 0) or (dx == dy and dx < 6)\n\n\ndef were_impacted(stones, x, y):\n return np.any([impact(move, x, y) for move in stones])\n\n\ndef impact_slope(stone, x, y, dx, dy):\n delta_x, delta_y = np.sign(stone[0] - x), np.sign(stone[1] - y)\n return impact(stone, x, y) and dx == delta_x and dy == delta_y\n\n\ndef were_impacted_slope_aux(dx_stone, dy_stone, dx, dy):\n if dx_stone == 0 and dy_stone == 0:\n return True\n if (dx_stone == 0 and not (dx == 0)) or (dy_stone == 0 and not (dy == 0)):\n return False\n if abs(dx) == abs(dy) and not (abs(dx_stone) == abs(dy_stone)):\n return False\n if dx > 0:\n return -4 <= dx_stone <= 4\n elif dx < 0:\n return -4 <= dx_stone <= 4\n else:\n return -4 <= dy_stone <= 4\n\n\ndef were_impacted_slope(stones, x, y, dx, dy):\n for stone in stones:\n dx_stone, dy_stone = x - stone[0], y - stone[1]\n if were_impacted_slope_aux(dx_stone, dy_stone, dx, dy):\n return True\n return False\n\n\ndef nearby_stones(move, board):\n x, y = move\n size = board.size\n nearby = []\n for dx in [-1, 0, 1]:\n for dy in [-1, 0, 1]:\n x_p, y_p = x + dx, y + dy\n if 0 <= x_p < size and 0 <= y_p < size and board.is_empty(x_p, y_p):\n nearby.append((x_p, y_p))\n if (x, y) in nearby:\n nearby.remove((x, y))\n return nearby\n\n\ndef update_child_after_move(game_handler, captures, last_move):\n game_handler.child_list = list(set(game_handler.child_list +\n nearby_stones(last_move, game_handler.board)))\n if (last_move[0], last_move[1]) in game_handler.child_list:\n game_handler.child_list.remove((last_move[0], last_move[1]))\n for capture in captures:\n for stone in nearby_stones(capture, game_handler.board):\n if (not is_there_stones_around(game_handler.board.board, *stone) and\n stone in game_handler.child_list):\n game_handler.child_list.remove(stone)\n for capture in captures:\n if capture not in game_handler.child_list:\n game_handler.child_list.append(capture)\n\n\ndef get_player_name(player):\n from gomoku.mcts import MCTSAgent\n from gomoku.minimax import MiniMaxAgent\n from gomoku.agent import Agent\n if isinstance(player, MCTSAgent):\n return \"mcts\"\n if isinstance(player, MiniMaxAgent):\n return player.algorithm_name\n elif isinstance(player, Agent):\n return \"not the best minimax agent\"\n else:\n return \"human\"\n\n\ndef best_values(values, depth, i):\n return values[depth - 1] if i < 2 else values[depth][:i]\n\n\ndef ucb(val, parent_visits, n_visits, ucb_constant=2):\n win_ratio = val / (n_visits + 1)\n exploration = (ucb_constant *\n np.sqrt(np.log(parent_visits + 1) / (n_visits + 1)))\n return win_ratio + exploration\n\n\ndef get_attr(attr_name):\n def get_attr_node(node):\n return getattr(node, attr_name)\n return get_attr_node\n\n\ndef dist_sort(move_0, move_list):\n dist = [np.linalg.norm(np.subtract(move_0, move)) for move in move_list]\n return [move for _, move in sorted(zip(dist, move_list))]\n"
] |
[
[
"numpy.log",
"numpy.unique",
"numpy.subtract",
"numpy.sign",
"numpy.array"
]
] |
vishalbelsare/TCN
|
[
"2f8c2b817050206397458dfd1f5a25ce8a32fe65"
] |
[
"TCN/char_cnn/utils.py"
] |
[
"import unidecode\nimport torch\nfrom torch.autograd import Variable\nfrom collections import Counter\nimport observations\nimport os\nimport pickle\n\n\ncuda = torch.cuda.is_available()\n\n\ndef data_generator(args):\n file, testfile, valfile = getattr(observations, args.dataset)('data/')\n file_len = len(file)\n valfile_len = len(valfile)\n testfile_len = len(testfile)\n corpus = Corpus(file + \" \" + valfile + \" \" + testfile)\n\n #############################################################\n # Use the following if you want to pickle the loaded data\n #\n # pickle_name = \"{0}.corpus\".format(args.dataset)\n # if os.path.exists(pickle_name):\n # corpus = pickle.load(open(pickle_name, 'rb'))\n # else:\n # corpus = Corpus(file + \" \" + valfile + \" \" + testfile)\n # pickle.dump(corpus, open(pickle_name, 'wb'))\n #############################################################\n\n return file, file_len, valfile, valfile_len, testfile, testfile_len, corpus\n\n\ndef read_file(filename):\n file = unidecode.unidecode(open(filename).read())\n return file, len(file)\n\n\nclass Dictionary(object):\n def __init__(self):\n self.char2idx = {}\n self.idx2char = []\n self.counter = Counter()\n\n def add_word(self, char):\n self.counter[char] += 1\n\n def prep_dict(self):\n for char in self.counter:\n if char not in self.char2idx:\n self.idx2char.append(char)\n self.char2idx[char] = len(self.idx2char) - 1\n\n def __len__(self):\n return len(self.idx2char)\n\n\nclass Corpus(object):\n def __init__(self, string):\n self.dict = Dictionary()\n for c in string:\n self.dict.add_word(c)\n self.dict.prep_dict()\n\n\ndef char_tensor(corpus, string):\n tensor = torch.zeros(len(string)).long()\n for i in range(len(string)):\n tensor[i] = corpus.dict.char2idx[string[i]]\n return Variable(tensor).cuda() if cuda else Variable(tensor)\n\n\ndef batchify(data, batch_size, args):\n \"\"\"The output should have size [L x batch_size], where L could be a long sequence length\"\"\"\n # Work out how cleanly we can divide the dataset into batch_size parts (i.e. continuous seqs).\n nbatch = data.size(0) // batch_size\n # Trim off any extra elements that wouldn't cleanly fit (remainders).\n data = data.narrow(0, 0, nbatch * batch_size)\n # Evenly divide the data across the batch_size batches.\n data = data.view(batch_size, -1)\n if args.cuda:\n data = data.cuda()\n return data\n\n\ndef get_batch(source, start_index, args):\n seq_len = min(args.seq_len, source.size(1) - 1 - start_index)\n end_index = start_index + seq_len\n inp = source[:, start_index:end_index].contiguous()\n target = source[:, start_index+1:end_index+1].contiguous() # The successors of the inp.\n return inp, target\n\n\ndef save(model):\n save_filename = 'model.pt'\n torch.save(model, save_filename)\n print('Saved as %s' % save_filename)\n\n\n"
] |
[
[
"torch.autograd.Variable",
"torch.cuda.is_available",
"torch.save"
]
] |
DITEP/prescreen-prediction
|
[
"216870c085db1515e02d62274802921f4d89bba7"
] |
[
"prescreen/simbad/load_targets.py"
] |
[
"\"\"\"\nscript to load SF patients that are not in VCare into the database\n\n\"\"\"\nimport pandas as pd\n\nfrom clintk.utils.connection import get_engine\n\nimport argparse\n\n\ndef load():\n # patient_id to start iterate\n description = 'Load targets from file into the sql server'\n parser = argparse.ArgumentParser(description=description)\n\n parser.add_argument(['-p', '--path'],\n help='path to file that contains the patients info')\n parser.add_argument(['--id', '-I'],\n help='id to connect to sql server')\n parser.add_argument(['--ip', '-a'],\n help='ip adress of the sql server')\n parser.add_argument(['--db', '-d'],\n help='name of the database on the sql server')\n parser.add_argument(['--output', '-o'],\n help='name of the new table on the server')\n # PATH = \"/home/v_charvet/workspace/data/cr/cr_rad_tronc.xlsx\"\n\n args = parser.parse_args()\n LAST_ID = 3300\n\n engine = get_engine(args.I, args.a, args.d)\n\n path = args.p\n # input = 'data/cr_sfditep_2012.xlsx'\n df = pd.read_excel(path).loc[:, ['N° Dossier patient IGR', 'LC',\n 'DATE_SIGN_OK']]\n\n df.drop_duplicates(inplace=True)\n\n # normalize nip\n df['nip'] = df['N° Dossier patient IGR'].astype(str) + df['LC']\n df['nip'] = df.loc[:, 'nip']\\\n .apply(lambda s: s[:4] + '-' + s[4:-2] + ' ' + s[-2:])\n\n new_ids = [LAST_ID + i for i in range(df.shape[0])]\n screenfail = [1] * df.shape[0]\n\n target = {'nip': df.loc[:, 'nip'],\n 'id': new_ids,\n 'prescreen': df['DATE_SIGN_OK'],\n 'screenfail': screenfail}\n\n df_target = pd.DataFrame(target)\n\n df_target.to_sql(args.o, engine, if_exists='replace')\n\n print('done')\n\n return df_target\n\n\nif __name__ == \"__main__\":\n load()\n"
] |
[
[
"pandas.read_excel",
"pandas.DataFrame"
]
] |
marcospiau/pytrends
|
[
"6bc4a16acdd1e72a0bd93bee3f6ee85e1446d6f6"
] |
[
"pytrends/request.py"
] |
[
"import json\nimport sys\nimport time\nfrom datetime import datetime, timedelta\n\nimport pandas as pd\nimport requests\n\nfrom pandas.io.json._normalize import nested_to_record\nfrom requests.adapters import HTTPAdapter\nfrom requests.packages.urllib3.util.retry import Retry\n\nfrom pytrends import exceptions\n\nfrom urllib.parse import quote\n\n\nclass TrendReq(object):\n \"\"\"\n Google Trends API\n \"\"\"\n GET_METHOD = 'get'\n POST_METHOD = 'post'\n GENERAL_URL = 'https://trends.google.com/trends/api/explore'\n INTEREST_OVER_TIME_URL = 'https://trends.google.com/trends/api/widgetdata/multiline'\n INTEREST_BY_REGION_URL = 'https://trends.google.com/trends/api/widgetdata/comparedgeo'\n RELATED_QUERIES_URL = 'https://trends.google.com/trends/api/widgetdata/relatedsearches'\n TRENDING_SEARCHES_URL = 'https://trends.google.com/trends/hottrends/visualize/internal/data'\n TOP_CHARTS_URL = 'https://trends.google.com/trends/api/topcharts'\n SUGGESTIONS_URL = 'https://trends.google.com/trends/api/autocomplete/'\n CATEGORIES_URL = 'https://trends.google.com/trends/api/explore/pickers/category'\n TODAY_SEARCHES_URL = 'https://trends.google.com/trends/api/dailytrends'\n REALTIME_TRENDING_SEARCHES_URL = 'https://trends.google.com/trends/api/realtimetrends'\n ERROR_CODES = (500, 502, 504, 429)\n\n def __init__(self, hl='en-US', tz=360, geo='', timeout=(2, 5), proxies='',\n retries=0, backoff_factor=0, requests_args=None):\n \"\"\"\n Initialize default values for params\n \"\"\"\n # google rate limit\n self.google_rl = 'You have reached your quota limit. Please try again later.'\n self.results = None\n # set user defined options used globally\n self.tz = tz\n self.hl = hl\n self.geo = geo\n self.kw_list = list()\n self.timeout = timeout\n self.proxies = proxies # add a proxy option\n self.retries = retries\n self.backoff_factor = backoff_factor\n self.proxy_index = 0\n self.requests_args = requests_args or {}\n self.cookies = self.GetGoogleCookie()\n # intialize widget payloads\n self.token_payload = dict()\n self.interest_over_time_widget = dict()\n self.interest_by_region_widget = dict()\n self.related_topics_widget_list = list()\n self.related_queries_widget_list = list()\n\n def GetGoogleCookie(self):\n \"\"\"\n Gets google cookie (used for each and every proxy; once on init otherwise)\n Removes proxy from the list on proxy error\n \"\"\"\n while True:\n if \"proxies\" in self.requests_args:\n try:\n return dict(filter(lambda i: i[0] == 'NID', requests.get(\n 'https://trends.google.com/?geo={geo}'.format(\n geo=self.hl[-2:]),\n timeout=self.timeout,\n **self.requests_args\n ).cookies.items()))\n except:\n continue\n else:\n if len(self.proxies) > 0:\n proxy = {'https': self.proxies[self.proxy_index]}\n else:\n proxy = ''\n try:\n return dict(filter(lambda i: i[0] == 'NID', requests.get(\n 'https://trends.google.com/?geo={geo}'.format(\n geo=self.hl[-2:]),\n timeout=self.timeout,\n proxies=proxy,\n **self.requests_args\n ).cookies.items()))\n except requests.exceptions.ProxyError:\n print('Proxy error. Changing IP')\n if len(self.proxies) > 1:\n self.proxies.remove(self.proxies[self.proxy_index])\n else:\n print('No more proxies available. Bye!')\n raise\n continue\n\n def GetNewProxy(self):\n \"\"\"\n Increment proxy INDEX; zero on overflow\n \"\"\"\n if self.proxy_index < (len(self.proxies) - 1):\n self.proxy_index += 1\n else:\n self.proxy_index = 0\n\n def _get_data(self, url, method=GET_METHOD, trim_chars=0, **kwargs):\n \"\"\"Send a request to Google and return the JSON response as a Python object\n :param url: the url to which the request will be sent\n :param method: the HTTP method ('get' or 'post')\n :param trim_chars: how many characters should be trimmed off the beginning of the content of the response\n before this is passed to the JSON parser\n :param kwargs: any extra key arguments passed to the request builder (usually query parameters or data)\n :return:\n \"\"\"\n s = requests.session()\n # Retries mechanism. Activated when one of statements >0 (best used for proxy)\n if self.retries > 0 or self.backoff_factor > 0:\n retry = Retry(total=self.retries, read=self.retries,\n connect=self.retries,\n backoff_factor=self.backoff_factor,\n status_forcelist=TrendReq.ERROR_CODES,\n method_whitelist=frozenset(['GET', 'POST']))\n s.mount('https://', HTTPAdapter(max_retries=retry))\n\n s.headers.update({'accept-language': self.hl})\n if len(self.proxies) > 0:\n self.cookies = self.GetGoogleCookie()\n s.proxies.update({'https': self.proxies[self.proxy_index]})\n if method == TrendReq.POST_METHOD:\n response = s.post(url, timeout=self.timeout,\n cookies=self.cookies, **kwargs,\n **self.requests_args) # DO NOT USE retries or backoff_factor here\n else:\n response = s.get(url, timeout=self.timeout, cookies=self.cookies,\n **kwargs, **self.requests_args) # DO NOT USE retries or backoff_factor here\n # check if the response contains json and throw an exception otherwise\n # Google mostly sends 'application/json' in the Content-Type header,\n # but occasionally it sends 'application/javascript\n # and sometimes even 'text/javascript\n if response.status_code == 200 and 'application/json' in \\\n response.headers['Content-Type'] or \\\n 'application/javascript' in response.headers['Content-Type'] or \\\n 'text/javascript' in response.headers['Content-Type']:\n # trim initial characters\n # some responses start with garbage characters, like \")]}',\"\n # these have to be cleaned before being passed to the json parser\n content = response.text[trim_chars:]\n # parse json\n self.GetNewProxy()\n return json.loads(content)\n else:\n # error\n raise exceptions.ResponseError(\n 'The request failed: Google returned a '\n 'response with code {0}.'.format(response.status_code),\n response=response)\n\n def build_payload(self, kw_list, cat=0, timeframe='today 5-y', geo='',\n gprop=''):\n \"\"\"Create the payload for related queries, interest over time and interest by region\"\"\"\n if gprop not in ['', 'images', 'news', 'youtube', 'froogle']:\n raise ValueError('gprop must be empty (to indicate web), images, news, youtube, or froogle')\n self.kw_list = kw_list\n self.geo = geo or self.geo\n self.token_payload = {\n 'hl': self.hl,\n 'tz': self.tz,\n 'req': {'comparisonItem': [], 'category': cat, 'property': gprop}\n }\n\n # build out json for each keyword\n for kw in self.kw_list:\n keyword_payload = {'keyword': kw, 'time': timeframe,\n 'geo': self.geo}\n self.token_payload['req']['comparisonItem'].append(keyword_payload)\n # requests will mangle this if it is not a string\n self.token_payload['req'] = json.dumps(self.token_payload['req'])\n # get tokens\n self._tokens()\n return\n\n def _tokens(self):\n \"\"\"Makes request to Google to get API tokens for interest over time, interest by region and related queries\"\"\"\n # make the request and parse the returned json\n widget_dicts = self._get_data(\n url=TrendReq.GENERAL_URL,\n method=TrendReq.GET_METHOD,\n params=self.token_payload,\n trim_chars=4,\n )['widgets']\n # order of the json matters...\n first_region_token = True\n # clear self.related_queries_widget_list and self.related_topics_widget_list\n # of old keywords'widgets\n self.related_queries_widget_list[:] = []\n self.related_topics_widget_list[:] = []\n # assign requests\n for widget in widget_dicts:\n if widget['id'] == 'TIMESERIES':\n self.interest_over_time_widget = widget\n if widget['id'] == 'GEO_MAP' and first_region_token:\n self.interest_by_region_widget = widget\n first_region_token = False\n # response for each term, put into a list\n if 'RELATED_TOPICS' in widget['id']:\n self.related_topics_widget_list.append(widget)\n if 'RELATED_QUERIES' in widget['id']:\n self.related_queries_widget_list.append(widget)\n return\n\n def interest_over_time_json(self):\n \"\"\"Request data from Google's Interest Over Time section and returns\n json data.\n \"\"\"\n over_time_payload = {\n # convert to string as requests will mangle\n 'req': json.dumps(self.interest_over_time_widget['request']),\n 'token': self.interest_over_time_widget['token'],\n 'tz': self.tz\n }\n # make the request and parse the returned json\n req_json = self._get_data(\n url=TrendReq.INTEREST_OVER_TIME_URL,\n method=TrendReq.GET_METHOD,\n trim_chars=5,\n params=over_time_payload,\n )\n return req_json\n\n def interest_over_time(self):\n \"\"\"Request data from Google's Interest Over Time section and return a dataframe\"\"\"\n req_json = self.interest_over_time_json()\n df = pd.DataFrame(req_json['default']['timelineData'])\n if (df.empty):\n return df\n\n df['date'] = pd.to_datetime(df['time'].astype(dtype='float64'),\n unit='s')\n df = df.set_index(['date']).sort_index()\n # split list columns into seperate ones, remove brackets and split on comma\n result_df = df['value'].apply(lambda x: pd.Series(\n str(x).replace('[', '').replace(']', '').split(',')))\n # rename each column with its search term, relying on order that google provides...\n for idx, kw in enumerate(self.kw_list):\n # there is currently a bug with assigning columns that may be\n # parsed as a date in pandas: use explicit insert column method\n result_df.insert(len(result_df.columns), kw,\n result_df[idx].astype('int'))\n del result_df[idx]\n\n if 'isPartial' in df:\n # make other dataframe from isPartial key data\n # split list columns into seperate ones, remove brackets and split on comma\n df = df.fillna(False)\n result_df2 = df['isPartial'].apply(lambda x: pd.Series(\n str(x).replace('[', '').replace(']', '').split(',')))\n result_df2.columns = ['isPartial']\n # Change to a bool type.\n result_df2.isPartial = result_df2.isPartial == 'True'\n # concatenate the two dataframes\n final = pd.concat([result_df, result_df2], axis=1)\n else:\n final = result_df\n final['isPartial'] = False\n\n return final\n\n\n def interest_by_region(self, resolution='COUNTRY', inc_low_vol=False,\n inc_geo_code=False):\n \"\"\"Request data from Google's Interest by Region section and return a dataframe\"\"\"\n\n # make the request\n region_payload = dict()\n if self.geo == '':\n self.interest_by_region_widget['request'][\n 'resolution'] = resolution\n elif self.geo == 'US' and resolution in ['DMA', 'CITY', 'REGION']:\n self.interest_by_region_widget['request'][\n 'resolution'] = resolution\n\n self.interest_by_region_widget['request'][\n 'includeLowSearchVolumeGeos'] = inc_low_vol\n\n # convert to string as requests will mangle\n region_payload['req'] = json.dumps(\n self.interest_by_region_widget['request'])\n region_payload['token'] = self.interest_by_region_widget['token']\n region_payload['tz'] = self.tz\n\n # parse returned json\n req_json = self._get_data(\n url=TrendReq.INTEREST_BY_REGION_URL,\n method=TrendReq.GET_METHOD,\n trim_chars=5,\n params=region_payload,\n )\n df = pd.DataFrame(req_json['default']['geoMapData'])\n if (df.empty):\n return df\n\n # rename the column with the search keyword\n df = df[['geoName', 'geoCode', 'value']].set_index(\n ['geoName']).sort_index()\n # split list columns into separate ones, remove brackets and split on comma\n result_df = df['value'].apply(lambda x: pd.Series(\n str(x).replace('[', '').replace(']', '').split(',')))\n if inc_geo_code:\n result_df['geoCode'] = df['geoCode']\n\n # rename each column with its search term\n for idx, kw in enumerate(self.kw_list):\n result_df[kw] = result_df[idx].astype('int')\n del result_df[idx]\n\n return result_df\n\n def related_topics(self):\n \"\"\"Request data from Google's Related Topics section and return a dictionary of dataframes\n\n If no top and/or rising related topics are found, the value for the key \"top\" and/or \"rising\" will be None\n \"\"\"\n\n # make the request\n related_payload = dict()\n result_dict = dict()\n for request_json in self.related_topics_widget_list:\n # ensure we know which keyword we are looking at rather than relying on order\n try:\n kw = request_json['request']['restriction'][\n 'complexKeywordsRestriction']['keyword'][0]['value']\n except KeyError:\n kw = ''\n # convert to string as requests will mangle\n related_payload['req'] = json.dumps(request_json['request'])\n related_payload['token'] = request_json['token']\n related_payload['tz'] = self.tz\n\n # parse the returned json\n req_json = self._get_data(\n url=TrendReq.RELATED_QUERIES_URL,\n method=TrendReq.GET_METHOD,\n trim_chars=5,\n params=related_payload,\n )\n\n # top topics\n try:\n top_list = req_json['default']['rankedList'][0][\n 'rankedKeyword']\n df_top = pd.DataFrame(\n [nested_to_record(d, sep='_') for d in top_list])\n except KeyError:\n # in case no top topics are found, the lines above will throw a KeyError\n df_top = None\n\n # rising topics\n try:\n rising_list = req_json['default']['rankedList'][1][\n 'rankedKeyword']\n df_rising = pd.DataFrame(\n [nested_to_record(d, sep='_') for d in rising_list])\n except KeyError:\n # in case no rising topics are found, the lines above will throw a KeyError\n df_rising = None\n\n result_dict[kw] = {'rising': df_rising, 'top': df_top}\n return result_dict\n\n def related_queries(self):\n \"\"\"Request data from Google's Related Queries section and return a dictionary of dataframes\n\n If no top and/or rising related queries are found, the value for the key \"top\" and/or \"rising\" will be None\n \"\"\"\n\n # make the request\n related_payload = dict()\n result_dict = dict()\n for request_json in self.related_queries_widget_list:\n # ensure we know which keyword we are looking at rather than relying on order\n try:\n kw = request_json['request']['restriction'][\n 'complexKeywordsRestriction']['keyword'][0]['value']\n except KeyError:\n kw = ''\n # convert to string as requests will mangle\n related_payload['req'] = json.dumps(request_json['request'])\n related_payload['token'] = request_json['token']\n related_payload['tz'] = self.tz\n\n # parse the returned json\n req_json = self._get_data(\n url=TrendReq.RELATED_QUERIES_URL,\n method=TrendReq.GET_METHOD,\n trim_chars=5,\n params=related_payload,\n )\n\n # top queries\n try:\n top_df = pd.DataFrame(\n req_json['default']['rankedList'][0]['rankedKeyword'])\n top_df = top_df[['query', 'value']]\n except KeyError:\n # in case no top queries are found, the lines above will throw a KeyError\n top_df = None\n\n # rising queries\n try:\n rising_df = pd.DataFrame(\n req_json['default']['rankedList'][1]['rankedKeyword'])\n rising_df = rising_df[['query', 'value']]\n except KeyError:\n # in case no rising queries are found, the lines above will throw a KeyError\n rising_df = None\n\n result_dict[kw] = {'top': top_df, 'rising': rising_df}\n return result_dict\n\n def trending_searches(self, pn='united_states'):\n \"\"\"Request data from Google's Hot Searches section and return a dataframe\"\"\"\n\n # make the request\n # forms become obsolete due to the new TRENDING_SEARCHES_URL\n # forms = {'ajax': 1, 'pn': pn, 'htd': '', 'htv': 'l'}\n req_json = self._get_data(\n url=TrendReq.TRENDING_SEARCHES_URL,\n method=TrendReq.GET_METHOD,\n **self.requests_args\n )[pn]\n result_df = pd.DataFrame(req_json)\n return result_df\n\n def today_searches(self, pn='US'):\n \"\"\"Request data from Google Daily Trends section and returns a dataframe\"\"\"\n forms = {'ns': 15, 'geo': pn, 'tz': '-180', 'hl': 'en-US'}\n req_json = self._get_data(\n url=TrendReq.TODAY_SEARCHES_URL,\n method=TrendReq.GET_METHOD,\n trim_chars=5,\n params=forms,\n **self.requests_args\n )['default']['trendingSearchesDays'][0]['trendingSearches']\n result_df = pd.DataFrame()\n # parse the returned json\n sub_df = pd.DataFrame()\n for trend in req_json:\n sub_df = sub_df.append(trend['title'], ignore_index=True)\n result_df = pd.concat([result_df, sub_df])\n return result_df.iloc[:, -1]\n\n def realtime_trending_searches(self, pn='US', cat='all', count =300):\n \"\"\"Request data from Google Realtime Search Trends section and returns a dataframe\"\"\"\n # Don't know what some of the params mean here, followed the nodejs library\n # https://github.com/pat310/google-trends-api/ 's implemenration\n\n\n #sort: api accepts only 0 as the value, optional parameter\n\n # ri: number of trending stories IDs returned,\n # max value of ri supported is 300, based on emperical evidence\n\n ri_value = 300\n if count < ri_value:\n ri_value = count\n\n # rs : don't know what is does but it's max value is never more than the ri_value based on emperical evidence\n # max value of ri supported is 200, based on emperical evidence\n rs_value = 200\n if count < rs_value:\n rs_value = count-1\n\n forms = {'ns': 15, 'geo': pn, 'tz': '300', 'hl': 'en-US', 'cat': cat, 'fi' : '0', 'fs' : '0', 'ri' : ri_value, 'rs' : rs_value, 'sort' : 0}\n req_json = self._get_data(\n url=TrendReq.REALTIME_TRENDING_SEARCHES_URL,\n method=TrendReq.GET_METHOD,\n trim_chars=5,\n params=forms\n )['storySummaries']['trendingStories']\n\n # parse the returned json\n wanted_keys = [\"entityNames\", \"title\"]\n\n final_json = [{ key: ts[key] for key in ts.keys() if key in wanted_keys} for ts in req_json ]\n\n result_df = pd.DataFrame(final_json)\n\n return result_df\n\n def top_charts(self, date, hl='en-US', tz=300, geo='GLOBAL'):\n \"\"\"Request data from Google's Top Charts section and return a dataframe\"\"\"\n\n try:\n date = int(date)\n except:\n raise ValueError(\n 'The date must be a year with format YYYY. See https://github.com/GeneralMills/pytrends/issues/355')\n\n # create the payload\n chart_payload = {'hl': hl, 'tz': tz, 'date': date, 'geo': geo,\n 'isMobile': False}\n\n # make the request and parse the returned json\n req_json = self._get_data(\n url=TrendReq.TOP_CHARTS_URL,\n method=TrendReq.GET_METHOD,\n trim_chars=5,\n params=chart_payload,\n **self.requests_args\n )\n try:\n df = pd.DataFrame(req_json['topCharts'][0]['listItems'])\n except IndexError:\n df = None\n return df\n\n def suggestions(self, keyword):\n \"\"\"Request data from Google's Keyword Suggestion dropdown and return a dictionary\"\"\"\n\n # make the request\n kw_param = quote(keyword)\n parameters = {'hl': self.hl}\n\n req_json = self._get_data(\n url=TrendReq.SUGGESTIONS_URL + kw_param,\n params=parameters,\n method=TrendReq.GET_METHOD,\n trim_chars=5,\n **self.requests_args\n )['default']['topics']\n return req_json\n\n def categories(self):\n \"\"\"Request available categories data from Google's API and return a dictionary\"\"\"\n\n params = {'hl': self.hl}\n\n req_json = self._get_data(\n url=TrendReq.CATEGORIES_URL,\n params=params,\n method=TrendReq.GET_METHOD,\n trim_chars=5,\n **self.requests_args\n )\n return req_json\n\n def get_historical_interest(self, keywords, year_start=2018, month_start=1,\n day_start=1, hour_start=0, year_end=2018,\n month_end=2, day_end=1, hour_end=0, cat=0,\n geo='', gprop='', sleep=0, frequency='hourly'):\n \"\"\"Gets historical hourly data for interest by chunking requests to 1 week at a time (which is what Google allows)\"\"\"\n\n # construct datetime objects - raises ValueError if invalid parameters\n initial_start_date = start_date = datetime(year_start, month_start,\n day_start, hour_start)\n end_date = datetime(year_end, month_end, day_end, hour_end)\n\n # Timedeltas:\n # 7 days for hourly\n # ~250 days for daily (270 seems to be max but sometimes breaks?)\n # For weekly can pull any date range so no method required here\n \n if frequency == 'hourly':\n delta = timedelta(days=7)\n elif frequency == 'daily':\n delta = timedelta(days=250)\n else:\n raise(ValueError('Frequency must be hourly or daily'))\n\n df = pd.DataFrame()\n\n date_iterator = start_date\n date_iterator += delta\n\n while True:\n # format date to comply with API call (different for hourly/daily)\n\n if frequency == 'hourly':\n start_date_str = start_date.strftime('%Y-%m-%dT%H')\n date_iterator_str = date_iterator.strftime('%Y-%m-%dT%H')\n elif frequency == 'daily':\n start_date_str = start_date.strftime('%Y-%m-%d')\n date_iterator_str = date_iterator.strftime('%Y-%m-%d')\n\n tf = start_date_str + ' ' + date_iterator_str\n\n try:\n self.build_payload(keywords, cat, tf, geo, gprop)\n week_df = self.interest_over_time()\n df = df.append(week_df)\n except Exception as e:\n print(e)\n pass\n\n start_date += delta\n date_iterator += delta\n\n if (date_iterator > end_date):\n # Run more days to get remaining data that would have been truncated if we stopped now\n if frequency == 'hourly':\n start_date_str = start_date.strftime('%Y-%m-%dT%H')\n date_iterator_str = date_iterator.strftime('%Y-%m-%dT%H')\n elif frequency == 'daily':\n start_date_str = start_date.strftime('%Y-%m-%d')\n date_iterator_str = date_iterator.strftime('%Y-%m-%d')\n\n tf = start_date_str + ' ' + date_iterator_str\n\n try:\n self.build_payload(keywords, cat, tf, geo, gprop)\n week_df = self.interest_over_time()\n df = df.append(week_df)\n except Exception as e:\n print(e)\n pass\n break\n\n # just in case you are rate-limited by Google. Recommended is 60 if you are.\n if sleep > 0:\n time.sleep(sleep)\n\n # Return the dataframe with results from our timeframe\n return df.loc[initial_start_date:end_date]\n"
] |
[
[
"pandas.concat",
"pandas.io.json._normalize.nested_to_record",
"pandas.DataFrame"
]
] |
iamwendellbalagot/water-hammer-app
|
[
"04e54ef34a99da550493c24f84590723b4ce4eda"
] |
[
"processSerialData/processSerialData.py"
] |
[
"import serial\nimport numpy as np\nimport sqlite3\nimport pandas as pd\nfrom tqdm import tqdm\n\nprocess = True\n\ndef get_dataframe(table='test', path='database/whDB.db'):\n conn = sqlite3.connect(path)\n df = pd.read_sql('SELECT * FROM {}'.format(table), con=conn)\n conn.close()\n return df\n\n\ndef get_serial(req = True):\n\tn = 100\n\tpath = 'database/whDB.db'\n\tarduino = serial.Serial('COM16', 9600)\n\n\tconn = sqlite3.connect(path)\n\treadings = []\n\n\tfor i in tqdm(range(n)):\n\t\tdata = arduino.readline()[:-2].decode('utf-8')\n\t\tdata = [float(i) for i in data.split('\\t')]\n\t\treadings.append(data)\n\tarduino.close()\n\tdf = pd.DataFrame(readings)\n\tdf.columns = ['S1', 'S2']\n\tdf.to_sql(name='Test', con = conn)\n\treturn df\n\ndef upload_generate(port='', baud=9600, n=200,\n table = 'test',\n path='database/whDB.db'):\n arduino = serial.Serial(port, baud)\n try:\n conn = sqlite3.connect(path)\n c = conn.cursor()\n readings = []\n \n while process:\n data = arduino.readline()[:-2].decode('utf-8')\n data = [float(i) for i in data.split('\\t')]\n readings.append(data)\n \n c.execute('INSERT INTO '+ table +' VALUES(?,?);',tuple(data));\n conn.commit()\n if process == False:\n \tbreak\n df = pd.DataFrame(readings, columns=['S1', 'S2'])\n return df\n conn.close()\n except:\n conn.close()\n query = '''CREATE TABLE IF NOT EXISTS {0} (\n S1 REAL,\n S2 REAL\n );'''.format(table)\n conn = sqlite3.connect(path)\n c = conn.cursor()\n c.execute(query)\n readings = []\n while process:\n data = arduino.readline()[:-2].decode('utf-8')\n data = [float(i) for i in data.split('\\t')]\n readings.append(data)\n \n c.execute('INSERT INTO '+ table +' VALUES(?,?);',tuple(data));\n conn.commit()\n if process == False:\n \tbreak\n df = pd.DataFrame(readings, columns=['S1', 'S2'])\n return df\n conn.close()\n\n"
] |
[
[
"pandas.DataFrame"
]
] |
rjtsg/StockExchangeAI
|
[
"3ec6bb415c73018933aa091d26e34fffc3cb3ef8"
] |
[
"RoyStatesDev.py"
] |
[
"\"\"\" \nSo here I try to build the StockSimPlay.py for-loop into a function, which should give outputs like\ngym.openai.com environments does. Then implement the greedy epsilon deep Q learning from RLtutMLadventuries.py\nto see if anything interesting happens. We still use 1 stock for 1 year.\n\"\"\"\n\n#Import packages:\nimport numpy as np \nimport pandas as pd \nimport sys \nimport os\nimport random\nimport time\nfrom keras.models import Sequential\nfrom keras.layers import Dense, InputLayer\nimport matplotlib.pylab as plt\n\nimport RoyStates\n#load in the AXP data and select data from 2000 to 2001:\nMainDirectory = os.getcwd()\nos.chdir('DataFiles')\ndf = pd.read_excel('AXPData.xlsx')\nos.chdir(MainDirectory)\n\n#So now we only want to have the data of 2000-01-01 to 2000-12-31 roughly\nnum_states = 144\ndf1 = pd.DataFrame(data=None, columns=df.columns)\ncounter = 0\nfor i in range(len(df)):\n datecheck = str(df.Date[i])\n for j in range(1995,2002):\n if datecheck[0:4] == str(j):\n df1.loc[datecheck] = df.iloc[i]\n \n#now we will have to flip it in order to make it easier for ourselfs (2000-01-01 is not the start date)\ndf1 = df1.iloc[::-1]\n\n\n\"\"\"\nBuilt here below the function that mimics the N-chain game and give the observation, reward, step?/done?\nDefine the reward table as a 3x3 matrix where State 1 is 2nd day ago closing price is higher,\nstate 2 is yesterdays closing price is higher and state 3 they are equal\nbeing able to buy anymore shares. The reward should be something like the Net worth (cash+shares).\nFurther build it like the q_learning_keras function in RLtutMLadventuries.py\n\"\"\"\n# create the keras model\nmodel = Sequential() \nmodel.add(InputLayer(batch_input_shape=(1, num_states))) #should thus be the 3x1 vector (1,0,0) state0 state1 = (0,1,0) ...\nmodel.add(Dense(150, activation='relu'))\nmodel.add(Dense(150, activation='relu'))\nmodel.add(Dense(150, activation='relu'))\nmodel.add(Dense(150, activation='relu'))\nmodel.add(Dense(3, activation='linear')) #3 possible actions to be taken\nmodel.compile(loss='mse', optimizer='adam', metrics=['mae'])\n\ndef q_learning_keras(num_episodes=500): #Number of training runs\n \n \n # now execute the q learning\n y = 0.25 \n eps = 0.5\n decay_factor = 0.999\n r_avg_list = []\n NumberSharesList = []\n NetWorthList = []\n CashList = []\n for i in range(num_episodes): #start the training\n eps *= decay_factor\n s = 0 #always start from state 0 (no shares)\n days = 0 #keeps track of the days\n Storage = {'AXPShares': 0, #Storage for other stuff\n 'Cash': 1000,\n 'Old_NetWorth': 1000}\n if i == 0:\n start = time.time() #start timer on first run\n if i % 10 == 0:\n end = time.time()\n TimeLeft = ((num_episodes-i)/10)*(end-start) #Calculates the estimated time until completion\n hours, rem = divmod(TimeLeft, 3600)\n minutes, seconds = divmod(rem, 60)\n print(\"Episode {} of {}. Estimated time left {:0>2}:{:0>2}:{:0>2}\".format(i + 1, num_episodes, int(hours),int(minutes),int(seconds)))\n start = time.time()\n done = False\n r_sum = 0 #total reward for 1 training\n while not done: #This plays the game untill it is done\n if np.random.random() < eps: #this decides the action\n a = np.random.randint(0, 3) #random action\n else:\n a = np.argmax(model.predict(np.identity(num_states)[s:s + 1]))\n new_s, r, Storage = TradeAction(a,Storage,days,df1) #This does the action So here the function must be called \n target = r + y * np.max(model.predict(np.identity(num_states)[new_s:new_s + 1]))\n target_vec = model.predict(np.identity(num_states)[s:s + 1])[0]\n target_vec[a] = target\n model.fit(np.identity(num_states)[s:s + 1], target_vec.reshape(-1, 3), epochs=1, verbose=0)\n s = new_s\n r_sum += r\n days += 1 \n if days == len(df1): #This stops the While loop\n done = True\n #From here we save end values to plot and visualize:\n r_avg_list.append(r_sum)\n NumberSharesList.append(Storage['AXPShares'])\n NetWorthList.append(Storage['Old_NetWorth'])\n CashList.append(Storage['Cash'])\n\n plt.plot(r_avg_list)\n plt.ylabel('Average reward per game')\n plt.xlabel('Number of games')\n plt.show()\n fig, (ax1, ax2, ax3) = plt.subplots(3,1,sharex=True)\n ax1.plot(NumberSharesList)\n ax1.set_ylabel('# shares')\n ax1.set_title('# of shares at the end of a game')\n ax2.plot(NetWorthList)\n ax2.set_ylabel('$')\n ax2.set_title('NetWorth at the end of a game')\n ax3.plot(CashList)\n ax3.set_ylabel('$')\n ax3.set_title('Cash at the end of a game')\n plt.show()\n AgentRL = np.ndarray((num_states,3))\n for i in range(num_states):\n print(\"State {} - action {}\".format(i, model.predict(np.identity(num_states)[i:i + 1])))\n AgentRL[i] = model.predict(np.identity(num_states)[i:i + 1])\n #print(AgentRL)\n return AgentRL\n \n \ndef TradeAction(action,Storage,days,DataFrame): #action is the action the agent chooses, while Storage is a dictionary which stores Trading process?\n #action 0 is buying\n #action 1 is selling\n #action 2 is holding on\n\n if action == 0 and (Storage['Cash']-DataFrame['Close'].iloc[days])>0:\n Storage['AXPShares'] += 1 #for now it only buys one share at a time\n Storage['Cash'] -= DataFrame['Close'].iloc[days] #removing money from cash\n exreward = 0\n elif action == 1 and Storage['AXPShares'] > 0:\n Storage['AXPShares'] -= 1 #selling 1 share\n Storage['Cash'] += DataFrame['Close'].iloc[days] #adding money to cash\n exreward = 0\n else:\n if action == 0 or action == 1:\n exreward = -10 #stops it from trading with no cash???\n if action == 2:\n exreward = 0\n\n \n #Now the state has to be defined:\n #state0 = 2 days ago price is higher\n #state1 = 1 day ago price is higher\n #state2 = prices are equal\n #if DataFrame['Close'].iloc[days-2] > DataFrame['Close'].iloc[days-1] and days >= 2:\n # state = 0\n #elif DataFrame['Close'].iloc[days-2] < DataFrame['Close'].iloc[days-1] and days >= 2:\n # state = 1\n #else:\n # state = 2\n state = RoyStates.ShortLongTermCash(Storage,days,DataFrame)\n #defining hte reward:\n #reward will be given as the difference between previousday networth and thisday networth\n NetWorth = Storage['Cash'] + Storage['AXPShares']*DataFrame['Close'].iloc[days]\n reward = NetWorth - Storage['Old_NetWorth'] #+ exreward\n Storage['Old_NetWorth'] = NetWorth\n\n return state, reward, Storage\n\nAgentRL = q_learning_keras()\n#print(AgentRL)\n\"\"\"\ngenerate the test year (2001) and see how the model performs on this and compare to anual return of that \nyear for the stock\n\"\"\"\nTestYear = pd.DataFrame(data=None, columns=df.columns)\ncounter = 0\nfor i in range(len(df)):\n datecheck = str(df.Date[i])\n if datecheck[0:4] == '2002':\n TestYear.loc[datecheck] = df.iloc[i]\n\nTestYear = TestYear.iloc[::-1]\n\n#eventually make this into an evaluation function, to make it callable\n\nPlotAction = []\nPlotNetWorth = []\nPlotShares = []\nSimulationYears = 1\ndays = 0 #keeps track of the days\nTestStorage = {'AXPShares': 0, #Storage for other stuff\n 'Cash': 1000,\n 'Old_NetWorth': 1000}\ndone = False\ns = 0 #always start from state 0 (no shares), wierd: how are we gonna do this\nwhile not done: #This plays the game untill it is done\n a = np.argmax(model.predict(np.identity(num_states)[s:s + 1]))\n print(a,s)\n new_s, r, TestStorage = TradeAction(a,TestStorage,days,TestYear) #This does the action So here the function must be called \n s = new_s\n days += 1 \n PlotAction.append(a)\n PlotNetWorth.append(TestStorage['Old_NetWorth'])\n PlotShares.append(TestStorage['AXPShares'])\n \n if days == len(TestYear): #This stops the While loop\n done = True\n\nStartNetWorth = 1000\nTestNetWorth = TestStorage['Old_NetWorth']\nStartClose = TestYear['Close'][0]\nEndClose = TestYear['Close'][-1]\nCAGRAXP = (EndClose/StartClose)**(1/SimulationYears) - 1 #Annual return: https://www.investopedia.com/terms/a/annual-return.asp\nCAGRAgent = (TestNetWorth/StartNetWorth)**(1/SimulationYears) - 1 #annual return of the agent\nprint('The annual return of the axp is %.2f percent and the agents annaul return is %.2f percent' % (CAGRAXP, CAGRAgent))\n\n\"\"\"\nDifferent states can apperently increase computational time pretty hard.\n\"\"\"\n\n\"\"\"\nJust quickly checking what the current training end testing year looks like:\n\"\"\"\n\n\n\nBuyY = []\nBuyX = []\nSellY = []\nSellX = []\ndays = []\nfor i in range(len(PlotAction)):\n if PlotAction[i] == 0:\n BuyY.append(TestYear['Close'][i]) \n BuyX.append(i)\n if PlotAction[i] == 1:\n SellY.append( TestYear['Close'][i])\n SellX.append(i)\n days.append(i)\n\npdays = []\nfor i in range(len(df1)):\n pdays.append(i)\n\nplt.plot(pdays,df1['Close'])\nplt.show()\n\nfig, ax = plt.subplots()\n\nax.plot(days,TestYear['Close'],'b-',BuyX,BuyY,'g.',SellX,SellY,'r.')\nplt.show()\n\nfig, (ax1, ax2) = plt.subplots(2,1,sharex=True)\nax1.plot(PlotNetWorth)\nax2.plot(PlotShares)\nax1.set_ylabel('Net Worth')\nax2.set_ylabel('# shares')\nplt.show()"
] |
[
[
"pandas.read_excel",
"matplotlib.pylab.show",
"numpy.random.random",
"numpy.ndarray",
"pandas.DataFrame",
"numpy.identity",
"matplotlib.pylab.subplots",
"matplotlib.pylab.ylabel",
"matplotlib.pylab.plot",
"matplotlib.pylab.xlabel",
"numpy.random.randint"
]
] |
santapresent/plotly.py
|
[
"96967d7937fed1777f737f8c3302af48252b4e7a"
] |
[
"packages/python/plotly/plotly/tests/test_core/test_px/test_px.py"
] |
[
"import plotly.express as px\nimport numpy as np\n\n\ndef test_scatter():\n iris = px.data.iris()\n fig = px.scatter(iris, x=\"sepal_width\", y=\"sepal_length\")\n assert fig.data[0].type == \"scatter\"\n assert np.all(fig.data[0].x == iris.sepal_width)\n assert np.all(fig.data[0].y == iris.sepal_length)\n # test defaults\n assert fig.data[0].mode == \"markers\"\n\n\ndef test_custom_data_scatter():\n iris = px.data.iris()\n # No hover, no custom data\n fig = px.scatter(iris, x=\"sepal_width\", y=\"sepal_length\", color=\"species\")\n assert fig.data[0].customdata is None\n # Hover, no custom data\n fig = px.scatter(\n iris,\n x=\"sepal_width\",\n y=\"sepal_length\",\n color=\"species\",\n hover_data=[\"petal_length\", \"petal_width\"],\n )\n for data in fig.data:\n assert np.all(np.in1d(data.customdata[:, 1], iris.petal_width))\n # Hover and custom data, no repeated arguments\n fig = px.scatter(\n iris,\n x=\"sepal_width\",\n y=\"sepal_length\",\n hover_data=[\"petal_length\", \"petal_width\"],\n custom_data=[\"species_id\", \"species\"],\n )\n assert np.all(fig.data[0].customdata[:, 0] == iris.species_id)\n assert fig.data[0].customdata.shape[1] == 4\n # Hover and custom data, with repeated arguments\n fig = px.scatter(\n iris,\n x=\"sepal_width\",\n y=\"sepal_length\",\n hover_data=[\"petal_length\", \"petal_width\", \"species_id\"],\n custom_data=[\"species_id\", \"species\"],\n )\n assert np.all(fig.data[0].customdata[:, 0] == iris.species_id)\n assert fig.data[0].customdata.shape[1] == 4\n assert (\n fig.data[0].hovertemplate\n == \"sepal_width=%{x}<br>sepal_length=%{y}<br>petal_length=%{customdata[2]}<br>petal_width=%{customdata[3]}<br>species_id=%{customdata[0]}\"\n )\n\n\ndef test_px_templates():\n import plotly.io as pio\n import plotly.graph_objects as go\n\n tips = px.data.tips()\n\n # use the normal defaults\n fig = px.scatter()\n assert fig.layout.template == pio.templates[pio.templates.default]\n\n # respect changes to defaults\n pio.templates.default = \"seaborn\"\n fig = px.scatter()\n assert fig.layout.template == pio.templates[\"seaborn\"]\n\n # special px-level defaults over pio defaults\n pio.templates.default = \"seaborn\"\n px.defaults.template = \"ggplot2\"\n fig = px.scatter()\n assert fig.layout.template == pio.templates[\"ggplot2\"]\n\n # accept names in args over pio and px defaults\n fig = px.scatter(template=\"seaborn\")\n assert fig.layout.template == pio.templates[\"seaborn\"]\n\n # accept objects in args\n fig = px.scatter(template={})\n assert fig.layout.template == go.layout.Template()\n\n # read colorway from the template\n fig = px.scatter(\n tips,\n x=\"total_bill\",\n y=\"tip\",\n color=\"sex\",\n template=dict(layout_colorway=[\"red\", \"blue\"]),\n )\n assert fig.data[0].marker.color == \"red\"\n assert fig.data[1].marker.color == \"blue\"\n\n # default colorway fallback\n fig = px.scatter(tips, x=\"total_bill\", y=\"tip\", color=\"sex\", template=dict())\n assert fig.data[0].marker.color == px.colors.qualitative.D3[0]\n assert fig.data[1].marker.color == px.colors.qualitative.D3[1]\n\n # pio default template colorway fallback\n pio.templates.default = \"seaborn\"\n px.defaults.template = None\n fig = px.scatter(tips, x=\"total_bill\", y=\"tip\", color=\"sex\")\n assert fig.data[0].marker.color == pio.templates[\"seaborn\"].layout.colorway[0]\n assert fig.data[1].marker.color == pio.templates[\"seaborn\"].layout.colorway[1]\n\n # pio default template colorway fallback\n pio.templates.default = \"seaborn\"\n px.defaults.template = \"ggplot2\"\n fig = px.scatter(tips, x=\"total_bill\", y=\"tip\", color=\"sex\")\n assert fig.data[0].marker.color == pio.templates[\"ggplot2\"].layout.colorway[0]\n assert fig.data[1].marker.color == pio.templates[\"ggplot2\"].layout.colorway[1]\n\n # don't overwrite top margin when set in template\n fig = px.scatter(title=\"yo\")\n assert fig.layout.margin.t is None\n\n fig = px.scatter()\n assert fig.layout.margin.t == 60\n\n fig = px.scatter(template=dict(layout_margin_t=2))\n assert fig.layout.margin.t is None\n\n # don't force histogram gridlines when set in template\n pio.templates.default = \"none\"\n px.defaults.template = None\n fig = px.scatter(\n tips, x=\"total_bill\", y=\"tip\", marginal_x=\"histogram\", marginal_y=\"histogram\"\n )\n assert fig.layout.xaxis2.showgrid\n assert fig.layout.xaxis3.showgrid\n assert fig.layout.yaxis2.showgrid\n assert fig.layout.yaxis3.showgrid\n\n fig = px.scatter(\n tips,\n x=\"total_bill\",\n y=\"tip\",\n marginal_x=\"histogram\",\n marginal_y=\"histogram\",\n template=dict(layout_yaxis_showgrid=False),\n )\n assert fig.layout.xaxis2.showgrid\n assert fig.layout.xaxis3.showgrid\n assert fig.layout.yaxis2.showgrid is None\n assert fig.layout.yaxis3.showgrid is None\n\n fig = px.scatter(\n tips,\n x=\"total_bill\",\n y=\"tip\",\n marginal_x=\"histogram\",\n marginal_y=\"histogram\",\n template=dict(layout_xaxis_showgrid=False),\n )\n assert fig.layout.xaxis2.showgrid is None\n assert fig.layout.xaxis3.showgrid is None\n assert fig.layout.yaxis2.showgrid\n assert fig.layout.yaxis3.showgrid\n"
] |
[
[
"numpy.all",
"numpy.in1d"
]
] |
Vincent-Vercruyssen/anomatools
|
[
"aef8698fb0d5ad709dc911ea5a4972e2cb98cefc"
] |
[
"anomatools/models/ssdo.py"
] |
[
"# -*- coding: UTF-8 -*-\n\"\"\"\n\nSemi-Supervised Detection of Anomalies.\n\nReference:\n V. Vercruyssen, W. Meert, G. Verbruggen, K. Maes, R. Baumer, J. Davis.\n Semi-supervised anomaly detection with an application to water analytics.\n In IEEE International Conference on Data Mining, Singapore, 2018, pp. 527–536.\n\n:author: Vincent Vercruyssen (2019)\n:license: Apache License, Version 2.0, see LICENSE for details.\n\"\"\"\n\nimport copy\nimport numpy as np\nimport scipy.stats as sps\n\nfrom collections import Counter\nfrom sklearn.neighbors import BallTree\nfrom sklearn.utils.validation import check_X_y\nfrom sklearn.base import BaseEstimator\n\nfrom .base import BaseDetector\nfrom ..utils.copkmeans import COPKMeans\n\n\n# ----------------------------------------------------------------------------\n# SSDO class\n# ----------------------------------------------------------------------------\n\nclass SSDO(BaseEstimator, BaseDetector):\n \"\"\"\n Parameters\n ----------\n k : int (default=30)\n Controls how many instances are updated by propagating the label of a\n single labeled instance.\n\n alpha : float (default=2.3)\n User influence parameter that controls the weight given to the\n unsupervised and label propragation components of an instance's\n anomaly score. Higher = more weight to supervised component.\n\n n_clusters : int (default=10)\n Number of clusters used for the COP k-means clustering algorithm.\n\n metric : string (default=euclidean)\n Distance metric for constructing the BallTree.\n Can be any of sklearn.neighbors.DistanceMetric methods or 'dtw'\n\n unsupervised_prior : str (default='ssdo')\n Unsupervised prior:\n 'ssdo' --> SSDO baseline (based on constrained k-means clustering)\n 'other' --> use a different prior passed to SSDO\n\n Attributes\n ----------\n scores_ : np.array of shape (n_samples,)\n The anomaly scores of the training data (higher = more abnormal).\n \n threshold_ : float\n The cutoff threshold on the anomaly score separating the normals\n from the anomalies. This is based on the `contamination` parameter.\n\n labels_ : np.array of shape (n_samples,)\n Binary anomaly labels (-1 = normal, +1 = anomaly).\n \"\"\"\n\n def __init__(self,\n k=30,\n alpha=2.3,\n n_clusters=10,\n unsupervised_prior='ssdo',\n contamination=0.1,\n metric='euclidean',\n tol=1e-8,\n verbose=False):\n super().__init__(\n contamination=contamination,\n metric=metric,\n tol=tol,\n verbose=verbose)\n\n # instantiate the parameters\n self.nc = int(n_clusters)\n self.alpha = float(alpha)\n self.k = int(k)\n self.unsupervised_prior = str(unsupervised_prior).lower()\n\n def fit(self, X, y=None, prior=None):\n \"\"\" Fit the model on data X.\n\n Parameters\n ----------\n X : np.array of shape (n_samples, n_features)\n The input instances. \n y : np.array of shape (n_samples,), optional (default=None)\n The ground truth of the input instances.\n prior : np.array of shape (n_samples,), optional (default=None)\n Unsupervised prior of the input instances.\n\n Returns\n -------\n self : object\n \"\"\"\n\n # check the inputs\n if y is None:\n y = np.zeros(len(X))\n X, y = check_X_y(X, y)\n\n # store label information\n ixl = np.where(y != 0)[0]\n self.feedback_ = y[ixl].copy()\n self.X_feedback_ = X[ixl, :].copy()\n\n # compute the prior\n if self.unsupervised_prior == 'ssdo':\n self._fit_prior_parameters(X, self.feedback_)\n prior = self._compute_prior(X)\n elif self.unsupervised_prior == 'other':\n if prior is None:\n raise ValueError('Prior cannot be None when `other` is selected')\n else:\n raise ValueError(self.unsupervised_prior,\n 'is not in [ssdo, other]')\n self.prior_threshold_ = np.percentile(prior, 100*(1.0-self.c)) + self.tol\n\n # compute eta parameter\n self.eta_ = self._compute_eta(X)\n\n # feedback available\n if self.feedback_.any():\n self.scores_ = self._compute_posterior(X, prior, self.eta_)\n \n else:\n self.scores_ = prior.copy()\n \n self._process_anomaly_scores()\n\n return self\n \n def decision_function(self, X, prior=None):\n \"\"\" Compute the anomaly scores of X.\n \n Parameters\n ----------\n X : np.array of shape (n_samples, n_features)\n The input instances.\n prior : np.array of shape (n_samples,), optional (default=None)\n Unsupervised prior of the input instances.\n\n Returns\n -------\n scores : np.array of shape (n_samples,)\n The anomaly scores of the input instances.\n \"\"\"\n\n # check the inputs\n X, _ = check_X_y(X, np.zeros(X.shape[0]))\n\n # compute the prior\n if self.unsupervised_prior == 'ssdo':\n prior = self._compute_prior(X)\n elif self.unsupervised_prior == 'other':\n if prior is None:\n raise ValueError('Prior cannot be None when `other` is selected')\n else:\n raise ValueError(self.unsupervised_prior,\n 'is not in [ssdo, other]')\n\n # if no labels are available, reduce to unsupervised\n if not(self.feedback_.any()):\n return prior\n\n # compute posterior (includes squashing prior)\n posterior = self._compute_posterior(X, prior, self.eta_)\n\n return posterior\n \n def _compute_prior(self, X):\n \"\"\" Compute the constrained-clustering-based outlier score.\n\n Parameters\n ----------\n X : np.array of shape (n_samples, n_features)\n The input instances.\n\n Returns\n -------\n prior : np.array of shape (n_samples,)\n Unscaled unsupervised prior\n \"\"\"\n\n n, _ = X.shape\n\n # predict the cluster labels + distances to the clusters\n _, labels, distances = self.clus.predict(X.astype(np.double), include_distances=True)\n\n # compute the prior\n prior = np.zeros(n, dtype=float)\n for i, l in enumerate(labels):\n if self.max_intra_cluster[l] < self.tol:\n point_deviation = 1.0\n else:\n point_deviation = distances[i] / self.max_intra_cluster[l]\n prior[i] = (point_deviation * self.cluster_deviation[l]) / self.cluster_sizes[l]\n\n return prior\n\n def _compute_posterior(self, X, prior, eta):\n \"\"\" Update the prior score with label propagation.\n\n Parameters\n ----------\n X : np.array of shape (n_samples, n_features)\n The input instances.\n prior : np.array of shape (n_samples,), optional (default=None)\n Unsupervised prior of the input instances.\n eta : float\n Eta parameter is the harmonic mean of the k-distances.\n\n Returns\n -------\n posterior : np.array of shape (n_samples)\n Posterior anomaly score between 0 and 1.\n \"\"\"\n\n n, _ = X.shape\n\n # squash the prior\n prior = self._squashing_function(prior, self.prior_threshold_)\n\n # labeled examples\n ixa = np.where(self.feedback_ == 1.0)[0]\n ixn = np.where(self.feedback_ == -1.0)[0]\n\n # compute limited distance matrices (to normals, to anomalies)\n Dnorm = self.dist.pairwise_multiple(X, self.X_feedback_[ixn, :])\n Danom = self.dist.pairwise_multiple(X, self.X_feedback_[ixa, :])\n\n # compute posterior\n posterior = np.zeros(n, dtype=float)\n for i in range(n):\n # weighted distance to anomalies & normals\n da = np.sum(self._ssdo_squashing_function(Danom[i, :], eta))\n dn = np.sum(self._ssdo_squashing_function(Dnorm[i, :], eta))\n # posterior\n z = 1.0 / (1.0 + self.alpha * (da + dn))\n posterior[i] = z * (prior[i] + self.alpha * da)\n\n return posterior\n\n def _fit_prior_parameters(self, X, y):\n \"\"\" Fit the parameters for computing the prior score:\n \n Parameters\n ----------\n X : np.array of shape (n_samples, n_features)\n The input instances.\n prior : np.array of shape (n_samples,), optional (default=None)\n Unsupervised prior of the input instances.\n\n Returns\n -------\n self : object\n \"\"\"\n\n # construct cannot-link constraints + remove impossible cannot-links\n ixn = np.where(y == -1.0)[0]\n ixa = np.where(y == 1.0)[0]\n cl = np.array(np.meshgrid(ixa, ixn)).T.reshape(-1,2)\n\n # cluster\n self.clus = COPKMeans(n_clusters=self.nc, metric=self.dist.metric_name)\n centroids, labels = self.clus.fit_predict(X, cannot_link=cl)\n self.nc = self.clus.n_clusters\n\n # cluster sizes (Counter sorts by key!)\n self.cluster_sizes = np.array(list(Counter(labels).values())) / max(Counter(labels).values())\n\n # compute the max intra-cluster distance\n self.max_intra_cluster = np.zeros(self.nc, dtype=np.float)\n for i, l in enumerate(labels):\n c = centroids[l, :]\n d = self.dist.pairwise_single(X[i, :], c)\n if d > self.max_intra_cluster[l]:\n self.max_intra_cluster[l] = d\n\n # compute the inter-cluster distances\n if self.nc == 1:\n self.cluster_deviation = np.array([1])\n else:\n inter_cluster = np.ones(self.nc, dtype=np.float) * np.inf\n for i in range(self.nc):\n for j in range(self.nc):\n if i != j:\n d = self.dist.pairwise_single(centroids[i, :], centroids[j, :])\n if not(d < self.tol) and d < inter_cluster[i]:\n inter_cluster[i] = d\n self.cluster_deviation = inter_cluster / max(inter_cluster)\n\n return self\n\n def _compute_eta(self, X):\n \"\"\" Compute the eta parameter.\n\n Parameters\n ----------\n X : np.array of shape (n_samples, n_features)\n The input instances.\n \n Returns\n -------\n eta : float\n Eta parameter is the harmonic mean of the k-distances.\n \"\"\"\n\n n, _ = X.shape\n\n # construct KD-tree\n self.dist.fit(X)\n D, _ = self.dist.search_neighbors(X, k=self.k, exclude_first=True)\n d = D[:, -1].flatten()\n\n # compute eta as the harmonic mean of the k-distances\n filler = min(d[d > 0.0])\n d[d == 0.0] = filler\n eta = sps.hmean(d)\n\n if eta < self.tol:\n eta = self.tol\n\n return eta\n\n def _ssdo_squashing_function(self, x, gamma):\n \"\"\" Compute the value of x under squashing function.\n \"\"\"\n \n return np.exp(np.log(0.5) * np.power(x / gamma, 2))\n"
] |
[
[
"numpy.log",
"numpy.meshgrid",
"numpy.power",
"scipy.stats.hmean",
"numpy.percentile",
"numpy.ones",
"sklearn.utils.validation.check_X_y",
"numpy.array",
"numpy.where",
"numpy.zeros"
]
] |
Jeffrey-Ede/One-Shot
|
[
"27696c0886b8d6b5f088ff1a93fadf5c3115b856",
"27696c0886b8d6b5f088ff1a93fadf5c3115b856"
] |
[
"wavefunctions/defocusor.py",
"wavefunctions/33/one-shot.py"
] |
[
"\"\"\"\r\nPropagate exit wavefunction to various focuses.\r\n\r\nBased on C++ code from https://github.com/morawatur/PyEWRecRepo\r\n\"\"\"\r\n\r\nimport tensorflow as tf\r\nimport sonnet as snt\r\n\r\nimport numpy as np\r\n\r\ndef fft_to_diff(self, x):\r\n \"\"\"Change diffraction pattern to fft layout or vice versa.\"\"\"\r\n w = x.get_shape()[0]\r\n h = x.get_shape()[1]\r\n\r\n #Cut into four segments\r\n tl = x[w - w//2:, h - h//2:]\r\n tr = x[:w//2, h - h//2:]\r\n br = x[:w//2, :h//2]\r\n bl = x[w - w//2:, :h//2]\r\n\r\n #Concatenate\r\n x = tf.concat(\r\n [tf.concat([tl, tr], axis=0), tf.concat([bl, br], axis=0)], \r\n axis=1\r\n )\r\n\r\n return x\r\n\r\n\r\nclass DefocusWave(snt.AbstractModule):\r\n \"\"\"Defocus square wavefunction.\"\"\"\r\n\r\n def __init__(\r\n self, \r\n wavelength,\r\n name=\"defocus_wave\"\r\n ):\r\n\r\n self._wavelength = wavelength\r\n self._px_size = px_size\r\n\r\n def _build(self, wave, defocus):\r\n\r\n \r\n\r\n return amplitudes\r\n\r\n def calc_transfer_fn(self, wave_size, px_size, defocus):\r\n \"\"\"Contrast transfer function for defocus.\"\"\"\r\n\r\n #Distances on image\r\n rec_px_size = 1. / (wave_size*px_size)\r\n rec_origin = -1. / (2.*px_size)\r\n line = tf.linspace(\r\n start=rec_origin,\r\n stop=rec_origin+rec_px_size*wave_size,\r\n num=wave_size\r\n )\r\n rec_x_dist, rec_y_dist = tf.meshgrid(line, line)\r\n \r\n rec_square_dist = rec_x_dist**2 + rec_y_dist**2\r\n\r\n ctf_coeff = np.pi*self._wavelenght*defocus\r\n\r\n phase = ctf_coeff*rec_square_dist\r\n ctf = tf.complex(\r\n real=tf.cos(phase),\r\n imag=tf.sin(phase)\r\n )\r\n\r\n return ctf\r\n\r\n def propagate_wave(self, wave, ctf):\r\n \r\n fft = tf.fft2d(wave)\r\n ctf = fft_to_diff(ctf)\r\n\r\n fft_prop = fft*ctf\r\n wave = tf.ifft2d(wave)\r\n\r\n return wave\r\n\r\n def propagate_to_defocus(wave, defocus):\r\n\r\n ctf = self.calc_transfer_fn(wave.get_shape()[1:3], defocus)\r\n wave = self.propagate_wave(wave, ctf)\r\n\r\n return wave\r\n",
"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nDeep learning supersampling network for scanning transmission electron microscopy.\r\n\r\nThis is a standard convolutional network i.e. with batch norm and L2 regularization.\r\n\r\nAcknowledgement: Initial testing of this network was performed with CIFAR-10 \r\nin Google Colab\r\n\"\"\"\r\n\r\nimport tensorflow as tf\r\nimport numpy as np\r\nimport cv2\r\nimport matplotlib.pyplot as plt\r\n\r\nfrom tensorflow.contrib.layers.python.layers import initializers\r\n\r\nimport itertools\r\n\r\nimport time\r\n\r\nfrom PIL import Image\r\n\r\nimport queue\r\n\r\n\r\nEXPER_NUM = 33\r\ncropsize = 144#192#224#256\r\nuse_batch_norm = True\r\nbatch_norm_decay = 0.999\r\nuse_vbn = False\r\nuse_instance_norm = False#True\r\nadversarial = True\r\nuse_spectral_norm = True#True\r\nuse_gradient_penalty = False#True]\r\nstandard_wass = False\r\nuse_l2_loss = False\r\n\r\n\r\n## Load data\r\ndef flip_rotate(img):\r\n \"\"\"Applies a random flip || rotation to the image, possibly leaving it unchanged\"\"\"\r\n\r\n choice = np.random.randint(0, 8)\r\n \r\n if choice == 0:\r\n return img\r\n if choice == 1:\r\n return np.rot90(img, 1)\r\n if choice == 2:\r\n return np.rot90(img, 2)\r\n if choice == 3:\r\n return np.rot90(img, 3)\r\n if choice == 4:\r\n return np.flip(img, 0)\r\n if choice == 5:\r\n return np.flip(img, 1)\r\n if choice == 6:\r\n return np.flip(np.rot90(img, 1), 0)\r\n if choice == 7:\r\n return np.flip(np.rot90(img, 1), 1)\r\n\r\n\r\ndef load_image(addr):\r\n \"\"\"Read an image and make sure it is of the correct type. Optionally resize it\"\"\"\r\n\r\n if type(addr) == bytes:\r\n addr = addr.decode()\r\n\r\n img = np.load(addr)\r\n\r\n off_x = np.random.randint(0, 320-cropsize)\r\n off_y = np.random.randint(0, 320-cropsize)\r\n img = img[off_x:off_x+cropsize, off_y:off_y+cropsize]\r\n\r\n img = flip_rotate(img)\r\n\r\n return img\r\n\r\ndef scale0to1(img):\r\n \"\"\"Rescale image between 0 and 1\"\"\"\r\n\r\n img = img.astype(np.float32)\r\n\r\n min = np.min(img)\r\n max = np.max(img)\r\n\r\n if np.absolute(min-max) < 1.e-6:\r\n img.fill(0.5)\r\n else:\r\n img = (img-min) / (max-min)\r\n\r\n return img.astype(np.float32)\r\n\r\ndef norm_img(img, min=None, max=None, get_min_and_max=False):\r\n \r\n if min == None:\r\n min = np.min(img)\r\n if max == None:\r\n max = np.max(img)\r\n\r\n if np.absolute(min-max) < 1.e-6:\r\n img.fill(0.)\r\n else:\r\n a = 0.5*(min+max)\r\n b = 0.5*(max-min)\r\n\r\n img = (img-a) / b\r\n\r\n if get_min_and_max:\r\n return img.astype(np.float32), (min, max)\r\n else:\r\n return img.astype(np.float32)\r\n\r\ndef preprocess(img):\r\n\r\n img[np.isnan(img)] = 0.\r\n img[np.isinf(img)] = 0.\r\n\r\n return img\r\n\r\nhistory = queue.Queue()\r\ndef record_parser(record):\r\n \"\"\"Parse files and generate lower quality images from them.\"\"\"\r\n\r\n if np.random.randint(0,2) and history.qsize() > 100:\r\n\r\n try: \r\n (lq, img) = history.get()\r\n return lq, img\r\n except:\r\n pass\r\n\r\n img = flip_rotate(preprocess(load_image(record)))\r\n lq = np.abs(img).astype(np.float32)\r\n\r\n #img = np.angle(img).astype(np.float32)\r\n #img = np.where(\r\n # img < 0,\r\n # 2*img/np.pi + 1,\r\n # 1 - 2*img/np.pi\r\n # )\r\n #img = (img.real/lq).astype(np.float32)\r\n\r\n angle = np.angle(img)\r\n img = np.stack((np.cos(angle), np.sin(angle)), axis=-1).astype(np.float32)\r\n\r\n if np.sum(np.isfinite(img)) != np.product(img.shape) or np.sum(np.isfinite(lq)) != np.product(lq.shape):\r\n img = np.zeros((cropsize,cropsize,2))\r\n lq = np.zeros((cropsize,cropsize))\r\n\r\n try:\r\n history.put( (lq, img) )\r\n except:\r\n pass\r\n \r\n return lq, img\r\n\r\ndef shaper(lq, img):\r\n\r\n lq = tf.reshape(lq, [cropsize, cropsize, 1])\r\n img = tf.reshape(img, [cropsize, cropsize, 2])\r\n\r\n return lq, img\r\n\r\n\r\ndef load_data(dir, subset, batch_size):\r\n \"\"\"Create a dataset from a list of filenames and shard batches from it\"\"\"\r\n\r\n with tf.device('/cpu:0'):\r\n\r\n dataset = tf.data.Dataset.list_files(dir+subset+\"/\"+\"*.npy\")\r\n dataset = dataset.shuffle(buffer_size=5000)\r\n dataset = dataset.repeat()\r\n dataset = dataset.map(\r\n lambda file: tf.py_func(record_parser, [file], [tf.float32, tf.float32])\r\n )\r\n dataset = dataset.map(shaper)\r\n dataset = dataset.batch(batch_size=batch_size)\r\n dataset = dataset.prefetch(buffer_size=10)\r\n\r\n iters = dataset.make_one_shot_iterator().get_next()\r\n\r\n #Add batch dimension size to graph\r\n for iter in iters:\r\n iter.set_shape([batch_size]+iter.get_shape().as_list()[1:])\r\n\r\n return iters\r\n\r\n# Utility\r\n\r\ndef flip_and_rotate(x):\r\n \"\"\"Random combination of flips and rotations.\"\"\"\r\n\r\n for augmentator in [flip, rotate]:\r\n x = augmentator(x)\r\n\r\n return x\r\n\r\n\r\ndef rotate(x: tf.Tensor) -> tf.Tensor:\r\n \"\"\"Rotation augmentation\r\n\r\n Args:\r\n x: Image\r\n\r\n Returns:\r\n Augmented image\r\n \"\"\"\r\n\r\n # Rotate 0, 90, 180, 270 degrees\r\n return tf.image.rot90(x, tf.random_uniform(shape=[], minval=0, maxval=4, dtype=tf.int32))\r\n\r\ndef flip(x: tf.Tensor) -> tf.Tensor:\r\n \"\"\"Flip augmentation\r\n\r\n Args:\r\n x: Image to flip\r\n\r\n Returns:\r\n Augmented image\r\n \"\"\"\r\n x = tf.image.random_flip_left_right(x)\r\n x = tf.image.random_flip_up_down(x)\r\n\r\n return x\r\n\r\ndef auto_name(name):\r\n \"\"\"Append number to variable name to make it unique.\r\n \r\n Inputs:\r\n name: Start of variable name.\r\n\r\n Returns:\r\n Full variable name with number afterwards to make it unique.\r\n \"\"\"\r\n\r\n scope = tf.contrib.framework.get_name_scope()\r\n vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=scope)\r\n\r\n names = [v.name for v in vars]\r\n \r\n #Increment variable number until unused name is found\r\n for i in itertools.count():\r\n short_name = name + \"_\" + str(i)\r\n sep = \"/\" if scope != \"\" else \"\"\r\n full_name = scope + sep + short_name\r\n if not full_name in [n[:len(full_name)] for n in names]:\r\n return short_name\r\n\r\n\r\ndef alrc(\r\n loss, \r\n num_stddev=3, \r\n decay=0.997, \r\n mu1_start=5, \r\n mu2_start=7**2, \r\n in_place_updates=True\r\n ):\r\n \"\"\"Adaptive learning rate clipping (ALRC) of outlier losses.\r\n \r\n Inputs:\r\n loss: Loss function to limit outlier losses of.\r\n num_stddev: Number of standard deviation above loss mean to limit it\r\n to.\r\n decay: Decay rate for exponential moving averages used to track the first\r\n two raw moments of the loss.\r\n mu1_start: Initial estimate for the first raw moment of the loss.\r\n mu2_start: Initial estimate for the second raw moment of the loss.\r\n in_place_updates: If False, add control dependencies for moment tracking\r\n to tf.GraphKeys.UPDATE_OPS. This allows the control dependencies to be\r\n executed in parallel with other dependencies later.\r\n Return:\r\n Loss function with control dependencies for ALRC.\r\n \"\"\"\r\n\r\n #Varables to track first two raw moments of the loss\r\n mu = tf.get_variable(\r\n auto_name(\"mu1\"), \r\n initializer=tf.constant(mu1_start, dtype=tf.float32))\r\n mu2 = tf.get_variable(\r\n auto_name(\"mu2\"), \r\n initializer=tf.constant(mu2_start, dtype=tf.float32))\r\n\r\n #Use capped loss for moment updates to limit the effect of outlier losses on the threshold\r\n sigma = tf.sqrt(mu2 - mu**2+1.e-8)\r\n loss = tf.where(loss < mu+num_stddev*sigma, \r\n loss, \r\n loss/tf.stop_gradient(loss/(mu+num_stddev*sigma)))\r\n\r\n #Update moment moving averages\r\n mean_loss = tf.reduce_mean(loss)\r\n mean_loss2 = tf.reduce_mean(loss**2)\r\n update_ops = [mu.assign(decay*mu+(1-decay)*mean_loss), \r\n mu2.assign(decay*mu2+(1-decay)*mean_loss2)]\r\n if in_place_updates:\r\n with tf.control_dependencies(update_ops):\r\n loss = tf.identity(loss)\r\n else:\r\n #Control dependencies that can be executed in parallel with other update\r\n #ops. Often, these dependencies are added to train ops e.g. alongside\r\n #batch normalization update ops.\r\n for update_op in update_ops:\r\n tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, update_op)\r\n \r\n return loss\r\n \r\n\r\ndef spectral_norm(w, iteration=1, in_place_updates=True):\r\n \"\"\"Spectral normalization. It imposes Lipschitz continuity by constraining the\r\n spectral norm (maximum singular value) of weight matrices.\r\n\r\n Inputs:\r\n w: Weight matrix to spectrally normalize.\r\n iteration: Number of times to apply the power iteration method to \r\n enforce spectral norm.\r\n\r\n Returns:\r\n Weight matrix with spectral normalization control dependencies.\r\n \"\"\"\r\n\r\n if not use_spectral_norm:\r\n return w\r\n\r\n w0 = w\r\n w_shape = w.shape.as_list()\r\n w = tf.reshape(w, [-1, w_shape[-1]])\r\n\r\n\r\n u = tf.get_variable(auto_name(\"u\"), \r\n [1, w_shape[-1]], \r\n initializer=tf.random_normal_initializer(mean=0.,stddev=0.03), \r\n trainable=False)\r\n\r\n u_hat = u\r\n v_hat = None\r\n for i in range(iteration):\r\n \"\"\"\r\n power iteration\r\n Usually iteration = 1 will be enough\r\n \"\"\"\r\n v_ = tf.matmul(u_hat, tf.transpose(w))\r\n v_hat = tf.nn.l2_normalize(v_)\r\n\r\n u_ = tf.matmul(v_hat, w)\r\n u_hat = tf.nn.l2_normalize(u_)\r\n\r\n u_hat = tf.stop_gradient(u_hat)\r\n v_hat = tf.stop_gradient(v_hat)\r\n\r\n sigma = tf.matmul(tf.matmul(v_hat, w), tf.transpose(u_hat))\r\n\r\n if in_place_updates:\r\n #In-place control dependencies bottlenect training\r\n with tf.control_dependencies([u.assign(u_hat)]):\r\n w_norm = w / sigma\r\n w_norm = tf.reshape(w_norm, w_shape)\r\n else:\r\n #Execute control dependency in parallel with other update ops\r\n tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, u.assign(u_hat))\r\n\r\n w_norm = w / sigma\r\n w_norm = tf.reshape(w_norm, w_shape)\r\n\r\n return w_norm\r\n\r\n\r\ndef spectral_norm_dense(\r\n inputs, \r\n num_outputs,\r\n biases_initializer=tf.zeros_initializer()\r\n ):\r\n\r\n w = tf.get_variable(auto_name(\"weights\"), shape=[inputs.get_shape()[-1], num_outputs])\r\n\r\n x = tf.matmul(inputs, spectral_norm(w))\r\n\r\n if biases_initializer != None:\r\n b = tf.get_variable(auto_name(\"bias\"), [num_outputs], initializer=biases_initializer)\r\n x = tf.nn.bias_add(x, b)\r\n\r\n return x\r\n\r\ndef spectral_norm_conv(inputs,\r\n num_outputs, \r\n stride=1, \r\n kernel_size=3, \r\n padding='VALID',\r\n biases_initializer=tf.zeros_initializer()):\r\n \"\"\"Convolutional layer with spectrally normalized weights.\"\"\"\r\n\r\n w = tf.get_variable(auto_name(\"kernel\"), shape=[kernel_size, kernel_size, inputs.get_shape()[-1], num_outputs])\r\n\r\n x = tf.nn.conv2d(input=inputs, filter=spectral_norm(w), \r\n strides=[1, stride, stride, 1], padding=padding)\r\n\r\n if biases_initializer != None:\r\n b = tf.get_variable(auto_name(\"bias\"), [num_outputs], initializer=biases_initializer)\r\n x = tf.nn.bias_add(x, b)\r\n\r\n return x\r\n\r\n\r\nstd_actv = lambda x: tf.nn.leaky_relu(x, alpha=0.1)\r\n\r\ndef conv(\r\n inputs, \r\n num_outputs, \r\n kernel_size=3, \r\n stride=1, \r\n padding='SAME',\r\n data_format=\"NHWC\",\r\n actv_fn=std_actv, \r\n is_batch_norm=True,\r\n is_spectral_norm=False,\r\n is_depthwise_sep=False,\r\n extra_batch_norm=False,\r\n biases_initializer=tf.zeros_initializer,\r\n weights_initializer=initializers.xavier_initializer,\r\n transpose=False,\r\n is_training=True\r\n ):\r\n \"\"\"Convenience function for a strided convolutional or transpositional \r\n convolutional layer.\r\n \r\n Intro: https://towardsdatascience.com/intuitively-understanding-convolutions-for-deep-learning-1f6f42faee1.\r\n\r\n The order is: Activation (Optional) -> Batch Normalization (optional) -> Convolutions.\r\n\r\n Inputs: \r\n inputs: Tensor of shape `[batch_size, height, width, channels]` to apply\r\n convolutions to.\r\n num_outputs: Number of feature channels to output.\r\n kernel_size: Side lenth of square convolutional kernels.\r\n stride: Distance between convolutional kernel applications.\r\n padding: 'SAME' for zero padding where kernels go over the edge.\r\n 'VALID' to discard features where kernels go over the edge.\r\n activ_fn: non-linearity to apply after summing convolutions. \r\n is_batch_norm: If True, add batch normalization after activation.\r\n is_spectral_norm: If True, spectrally normalize weights.\r\n is_depthwise_sep: If True, depthwise separate convolutions into depthwise\r\n spatial convolutions, then 1x1 pointwise convolutions.\r\n extra_batch_norm: If True and convolutions are depthwise separable, implement\r\n batch normalization between depthwise and pointwise convolutions.\r\n biases_initializer: Function to initialize biases with. None for no biases.\r\n weights_initializer: Function to initialize weights with. None for no weights.\r\n transpose: If True, apply convolutional layer transpositionally to the\r\n described convolutional layer.\r\n is_training: If True, use training specific operations e.g. batch normalization\r\n update ops.\r\n\r\n Returns:\r\n Output of convolutional layer.\r\n \"\"\"\r\n\r\n x = inputs\r\n\r\n num_spatial_dims = len(x.get_shape().as_list()) - 2\r\n\r\n if biases_initializer == None:\r\n biases_initializer = lambda: None\r\n if weights_initializer == None:\r\n weights_initializer = lambda: None\r\n\r\n if not is_spectral_norm:\r\n #Convolutional layer without spectral normalization\r\n\r\n if transpose:\r\n stride0 = 1\r\n if type(stride) == list or is_depthwise_sep or stride % 1:\r\n #Apparently there is no implementation of transpositional \r\n #depthwise separable convolutions, so bilinearly upsample then \r\n #depthwise separably convolute\r\n if kernel_size != 1:\r\n x = tf.image.resize_bilinear(\r\n images=x,\r\n size=stride if type(stride) == list else \\\r\n [int(stride*d) for d in x.get_shape().as_list()[1:3]],\r\n align_corners=True\r\n )\r\n stride0 = stride \r\n stride = 1\r\n\r\n if type(stride0) == list and not is_depthwise_sep:\r\n layer = tf.contrib.layers.conv2d\r\n elif is_depthwise_sep:\r\n layer = tf.contrib.layers.separable_conv2d\r\n else:\r\n layer = tf.contrib.layers.conv2d_transpose\r\n\r\n x = layer(\r\n inputs=x,\r\n num_outputs=num_outputs,\r\n kernel_size=kernel_size,\r\n stride=stride,\r\n padding=padding,\r\n data_format=data_format,\r\n activation_fn=None,\r\n weights_initializer=weights_initializer(),\r\n biases_initializer=biases_initializer())\r\n \r\n if type(stride0) != list:\r\n if (is_depthwise_sep or stride0 % 1) and kernel_size == 1:\r\n x = tf.image.resize_bilinear(\r\n images=x,\r\n size=[int(stride0*d) for d in x.get_shape().as_list()[1:3]],\r\n align_corners=True\r\n ) \r\n else:\r\n if num_spatial_dims == 1:\r\n layer = tf.contrib.layers.conv1d\r\n elif num_spatial_dims == 2:\r\n if is_depthwise_sep:\r\n layer = tf.contrib.layers.separable_conv2d\r\n else:\r\n layer = tf.contrib.layers.conv2d\r\n x = layer(\r\n inputs=x,\r\n num_outputs=num_outputs,\r\n kernel_size=kernel_size,\r\n stride=stride,\r\n padding=padding,\r\n data_format=data_format,\r\n activation_fn=None,\r\n weights_initializer=weights_initializer(),\r\n biases_initializer=biases_initializer())\r\n else:\r\n #Weights are spectrally normalized\r\n x = spectral_norm_conv(\r\n inputs=x, \r\n num_outputs=num_outputs, \r\n stride=stride, \r\n kernel_size=kernel_size, \r\n padding=padding, \r\n biases_initializer=biases_initializer())\r\n\r\n if actv_fn:\r\n x = actv_fn(x)\r\n\r\n if is_batch_norm and use_batch_norm:\r\n x = tf.contrib.layers.batch_norm(x, is_training=is_training)\r\n\r\n return x\r\n\r\n\r\ndef residual_block(inputs, skip=3, is_training=True):\r\n \"\"\"Residual block whre the input is added to the signal after skipping some\r\n layers. This architecture is good for learning purturbative transformations. \r\n If no layer is provided, it defaults to a convolutional layer.\r\n\r\n Deep residual learning: https://arxiv.org/abs/1512.03385.\r\n\r\n Inputs:\r\n inputs: Tensor to apply residual block to. Outputs of every layer will \r\n have the same shape.\r\n skip: Number of layers to skip before adding input to layer output.\r\n layer: Layer to apply in residual block. Defaults to convolutional \r\n layer. Custom layers must support `inputs`, `num_outputs` and `is_training`\r\n arguments.\r\n\r\n Returns:\r\n Final output of residual block.\r\n \"\"\"\r\n\r\n x = x0 = inputs\r\n\r\n def layer(inputs, num_outputs, is_training, is_batch_norm, actv_fn):\r\n \r\n x = conv(\r\n inputs=inputs, \r\n num_outputs=num_outputs,\r\n is_training=is_training,\r\n actv_fn=actv_fn\r\n )\r\n\r\n return x\r\n\r\n for i in range(skip):\r\n x = layer(\r\n inputs=x, \r\n num_outputs=x.get_shape()[-1], \r\n is_training=is_training,\r\n is_batch_norm=i < skip - 1,\r\n actv_fn=tf.nn.relu\r\n )\r\n\r\n x += x0\r\n\r\n if use_batch_norm:\r\n x = tf.contrib.layers.batch_norm(x, is_training=is_training)\r\n\r\n return x\r\n \r\n \r\ndef transpose_Xception(\r\n inputs, \r\n num_outputs, \r\n stride=2, \r\n actv_fn=tf.nn.relu,\r\n is_batch_norm=True,\r\n is_training=True\r\n ):\r\n \"\"\"Transpositional Xception block for upsampling; rather than downsampling.\"\"\"\r\n \r\n x = inputs\r\n \r\n if actv_fn:\r\n x = actv_fn(x)\r\n\r\n if is_batch_norm:\r\n x = tf.contrib.layers.batch_norm(x, is_training=is_training)\r\n \r\n x0 = conv(\r\n inputs=x, \r\n num_outputs=num_outputs, \r\n kernel_size=1,\r\n stride=stride,\r\n is_batch_norm=False,\r\n is_depthwise_sep=True,\r\n transpose=True\r\n )\r\n \r\n x = conv(\r\n inputs=x, \r\n num_outputs=num_outputs, \r\n kernel_size=3,\r\n stride=stride,\r\n is_batch_norm=False,\r\n is_depthwise_sep=True,\r\n transpose=True\r\n )\r\n \r\n x = conv(\r\n inputs=x, \r\n num_outputs=num_outputs,\r\n is_depthwise_sep=True,\r\n )\r\n x = conv(\r\n inputs=x, \r\n num_outputs=num_outputs,\r\n is_depthwise_sep=True,\r\n )\r\n print(x0, x)\r\n x += x0\r\n \r\n return x\r\n\r\n\r\ndef generator(inputs, num_outputs, is_training, is_depthwise_sep=False):\r\n \"\"\"Convolutional neural network (CNN) for image supersampling.\r\n \r\n Args:\r\n Inputs: Images tensor with shape [batch_size, heigh, width, channels].\r\n num_outputs: Number of channels in network output.\r\n is_training: Bool indicating whether to use training operations\r\n \r\n Returns:\r\n Super-sampled images\r\n \"\"\"\r\n\r\n base_size = 32\r\n\r\n x = inputs\r\n\r\n x = tf.contrib.layers.batch_norm(x, is_training=is_training)\r\n\r\n x = conv(\r\n x, \r\n num_outputs=32,\r\n is_training=is_training\r\n )\r\n \r\n #Encoder\r\n for i in range(1, 4):\r\n\r\n x = conv(\r\n x, \r\n num_outputs=base_size*2**i, \r\n stride=2,\r\n is_depthwise_sep=is_depthwise_sep,\r\n is_training=is_training,\r\n actv_fn=std_actv\r\n )\r\n\r\n if i == 2:\r\n low_level = x\r\n\r\n #Residual blocks\r\n for _ in range(6): #Number of blocks\r\n x = residual_block(\r\n x, \r\n skip=3,\r\n is_training=is_training\r\n )\r\n\r\n\r\n #Decoder\r\n for i in range(2, -1, -1):\r\n\r\n x = conv(\r\n x, \r\n num_outputs=base_size*2**i, \r\n stride=2,\r\n is_depthwise_sep=is_depthwise_sep,\r\n is_training=is_training,\r\n transpose=True,\r\n actv_fn=std_actv\r\n )\r\n\r\n #if x.get_shape().as_list() == low_level.get_shape().as_list(): #Easy way to find concat level!\r\n # x = tf.concat([x, low_level], axis=-1)\r\n\r\n # for _ in range(3):\r\n # x = conv(\r\n # x, \r\n # num_outputs=base_size*2**i, \r\n # is_depthwise_sep=is_depthwise_sep,\r\n # is_training=is_training,\r\n # )\r\n\r\n x = conv(\r\n x, \r\n num_outputs=32, \r\n is_depthwise_sep=is_depthwise_sep,\r\n is_training=is_training,\r\n )\r\n\r\n \r\n #Project features onto output image\r\n x = conv(\r\n x,\r\n num_outputs=num_outputs,\r\n biases_initializer=None,\r\n actv_fn=None,\r\n is_batch_norm=True,\r\n is_training=is_training\r\n )\r\n\r\n x /= tf.sqrt(1.e-8 + tf.reduce_sum(x**2, axis=-1, keepdims=True))\r\n x0 = x\r\n x *= inputs\r\n\r\n return x, x0\r\n\r\n\r\n\r\ndef res_block(x, num_outputs, s=1):\r\n\r\n x0 = x\r\n start_channels = x.get_shape().as_list()[-1]\r\n\r\n if num_outputs != start_channels:\r\n x0 = conv(\r\n inputs=x0, \r\n num_outputs=num_outputs, \r\n kernel_size=1, \r\n stride=1,\r\n actv_fn=None,\r\n is_batch_norm=False,\r\n is_spectral_norm=True\r\n )\r\n\r\n x = conv(\r\n inputs=x, \r\n num_outputs=start_channels, \r\n kernel_size=3, \r\n stride=1,\r\n actv_fn=tf.nn.relu,\r\n is_batch_norm=False,\r\n is_spectral_norm=True\r\n )\r\n\r\n x = conv(\r\n inputs=x, \r\n num_outputs=num_outputs, \r\n kernel_size=3, \r\n stride=1,\r\n actv_fn=tf.nn.relu,\r\n is_batch_norm=False,\r\n is_spectral_norm=True\r\n )\r\n\r\n x += x0\r\n\r\n if s > 1:\r\n #x0 = tf.layers.average_pooling2d(x0, s, s)\r\n x = tf.layers.average_pooling2d(x, s, s)\r\n\r\n return x\r\n\r\ndef large_discriminator(inputs):\r\n #Based on https://arxiv.org/pdf/1802.05637.pdf\r\n\r\n x = inputs\r\n\r\n for i in range(4):\r\n\r\n #x = res_block(x, 64*2**i, s=2)\r\n x = conv(\r\n inputs=x, \r\n num_outputs=40*2**i, \r\n kernel_size=4, \r\n stride=1,\r\n actv_fn=tf.nn.leaky_relu,\r\n is_batch_norm=False,\r\n is_spectral_norm=True,\r\n biases_initializer=None\r\n )\r\n\r\n x = conv(\r\n inputs=x, \r\n num_outputs=40*2**i, \r\n kernel_size=4, \r\n stride=2,\r\n actv_fn=tf.nn.leaky_relu,\r\n is_batch_norm=False,\r\n is_spectral_norm=True,\r\n biases_initializer=None\r\n )\r\n\r\n #for _ in range(4):\r\n # x = res_block(x, 512)\r\n\r\n #for _ in range(3):\r\n # x = conv(\r\n # inputs=x, \r\n # num_outputs=400, \r\n # kernel_size=4, \r\n # stride=1,\r\n # actv_fn=tf.nn.leaky_relu,\r\n # is_batch_norm=False,\r\n # is_spectral_norm=True\r\n # )\r\n\r\n ##x = res_block(x, 1024, s=2)\r\n\r\n #x = conv(\r\n # inputs=x, \r\n # num_outputs=800, \r\n # kernel_size=4, \r\n # stride=2,\r\n # actv_fn=tf.nn.leaky_relu,\r\n # is_batch_norm=False,\r\n # is_spectral_norm=True\r\n #)\r\n\r\n x = conv(\r\n inputs=x, \r\n num_outputs=500, \r\n kernel_size=4, \r\n stride=2,\r\n actv_fn=tf.nn.leaky_relu,\r\n is_batch_norm=False,\r\n is_spectral_norm=True,\r\n biases_initializer=None\r\n )\r\n\r\n #x = tf.layers.flatten(x)\r\n #x = tf.expand_dims(tf.reduce_sum(x, axis=[1,2,3]), axis=-1)\r\n\r\n x = tf.reduce_sum(x, axis=[1,2])\r\n\r\n #x = tf.contrib.layers.fully_connected(x, 1)\r\n #x = tf.contrib.layers.fully_connected(x, 1, activation_fn=None, biases_initializer=None)\r\n\r\n #x = spectral_norm_dense(x, 2048, biases_initializer=None)\r\n #x = spectral_norm_dense(x, 1024, biases_initializer=None)\r\n\r\n\r\n #x = tf.expand_dims(tf.reduce_mean(x, axis=[1,2,3]), axis=-1)\r\n\r\n x = spectral_norm_dense(x, 1, biases_initializer=None)\r\n\r\n #x += 0.5\r\n\r\n #x = 0.5 - 0.1 + 1.1*tf.sigmoid(x)\r\n\r\n #x = 1 + tf.nn.elu(x)\r\n\r\n return x\r\n\r\n\r\ndef configure(\r\n inputs, \r\n batch_size,\r\n target_outputs, \r\n is_training, \r\n learning_rate, \r\n beta1,\r\n is_depthwise_sep,\r\n decay,\r\n gen_scale\r\n ):\r\n \"\"\"Operations to calculate network losses and run training operations.\"\"\"\r\n\r\n target_outputs0 = target_outputs\r\n\r\n with tf.variable_scope(\"gen\"):\r\n output0, phase_components = generator(\r\n inputs=inputs, \r\n num_outputs=target_outputs.get_shape().as_list()[-1], \r\n is_training=is_training,\r\n is_depthwise_sep=is_depthwise_sep\r\n )\r\n output = output0\r\n \r\n if adversarial:\r\n #Theoretical argument for EMA tracking is in https://openreview.net/pdf?id=SJgw_sRqFQ\r\n\r\n #with tf.variable_scope(\"tracking/gen\"):\r\n # tracking_output = generator(\r\n # inputs=inputs, \r\n # num_outputs=target_outputs.get_shape().as_list()[-1], \r\n # is_training=is_training,\r\n # is_depthwise_sep=is_depthwise_sep\r\n # )\r\n\r\n\r\n def amp(x):\r\n return 1 + tf.sqrt(1.e-8 + tf.reduce_sum(x**2, axis=-1, keepdims=True))\r\n\r\n output = inputs*phase_components#tf.concat([inputs, phase_components], axis=-1)\r\n target_outputs = inputs*target_outputs#tf.concat([inputs, target_outputs], axis=-1)\r\n\r\n if use_gradient_penalty:\r\n x_hat = output + tf.random_uniform(output.get_shape().as_list())*(target_outputs-output)\r\n discr_batch = tf.concat([output, target_outputs, x_hat], axis=0)\r\n else:\r\n discr_batch = tf.concat([output, target_outputs], axis=0)\r\n\r\n with tf.variable_scope(\"main/discr\"):\r\n preds = large_discriminator(discr_batch)\r\n\r\n #with tf.variable_scope(\"tracking/discr\"):\r\n # track_pred = large_discriminator(output)\r\n\r\n fake_pred = preds[:batch_size]\r\n real_pred = preds[batch_size:2*batch_size]\r\n\r\n if use_gradient_penalty:\r\n x_hat_pred = preds[2*batch_size:3*batch_size]\r\n\r\n if use_gradient_penalty:\r\n grad = tf.gradients(x_hat_pred, [x_hat])[0]\r\n grad_norm2 = tf.sqrt(1.e-6 + tf.reduce_sum(tf.square(grad), axis=[1,2,3]))\r\n gradient_penalty = tf.reduce_mean( (grad_norm2 - 1.)**2 )\r\n\r\n if use_gradient_penalty or standard_wass:\r\n discr_loss = tf.reduce_mean(fake_pred - real_pred) \r\n gen_loss = -tf.reduce_mean(fake_pred) \r\n else:\r\n #noise = tf.random_uniform(real_pred.get_shape().as_list(), maxval=0.05)\r\n discr_loss = tf.reduce_mean( (real_pred - 1)**2 + (fake_pred)**2 )\r\n gen_loss = tf.reduce_mean( (fake_pred - 1)**2 )\r\n \r\n if standard_wass:\r\n for v in tf.trainable_variables(\"main/discr\"):\r\n tf.add_to_collection(\"clip_weights\", v.assign(tf.clip_by_value(v, -0.01, 0.01)))\r\n\r\n #mu = tf.get_variable(\r\n # auto_name(\"avg_loss\"), \r\n # initializer=tf.constant(0.707, dtype=tf.float32), \r\n # trainable=False\r\n # )\r\n\r\n #mu_op = mu.assign(0.999*mu + 0.001*tf.sqrt(discr_loss))\r\n #tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, mu_op)\r\n\r\n #mu_scaled = mu/0.707\r\n #discr_lr_scale = tf.cond(mu_scaled > 0.6, lambda: 1., lambda: (mu_scaled/0.6)**2 )\r\n\r\n if use_gradient_penalty:\r\n discr_loss += 10*gradient_penalty\r\n #discr_loss /= 100\r\n #gen_loss /= 100\r\n \r\n if use_l2_loss:\r\n gen_l2_loss = tf.add_n([tf.nn.l2_loss(v) for v in tf.trainable_variables(\"gen\")])\r\n discr_l2_loss = tf.add_n([tf.nn.l2_loss(v) for v in tf.trainable_variables(\"main/discr\")])\r\n\r\n discr_loss += 5.e-5*discr_l2_loss\r\n gen_loss += 5.e-5*gen_l2_loss\r\n\r\n\r\n #discr_loss = tf.reduce_mean( tf.nn.relu(1-real_pred) + tf.nn.relu(1+fake_pred), axis=-1 ) + 10*gradient_penalty #+ 1.e-5*discr_l2_loss\r\n #gen_loss = -tf.reduce_mean( fake_pred, axis=-1 )# + 5.e-5*gen_l2_loss\r\n\r\n #discr_loss = tf.reduce_mean(fake_pred - real_pred) / 1 + 10*gradient_penalty + 1.e-5*discr_l2_loss\r\n #gen_loss = -tf.reduce_mean(fake_pred) / 1 + 1.e-5*gen_l2_loss\r\n \r\n #Create optimizer for stochastic gradient descent (SGD)\r\n discr_optimizer = tf.train.AdamOptimizer(\r\n learning_rate=0.0002,\r\n beta1=0.5\r\n )\r\n #discr_optimizer = tf.train.RMSPropOptimizer(learning_rate=0.00005, decay=0.5)\r\n\r\n #l2_loss = tf.add_n([tf.nn.l2_loss(v) for v in tf.trainable_variables()])\r\n\r\n #total_loss = gen_loss + discr_loss + 10*gradient_penalty + 5.e-5*l2_loss\r\n\r\n ##Tracking\r\n #for v, t in zip(tf.trainable_variables(\"main\"), tf.trainable_variables(\"tracking\")):\r\n # tf.add_to_collection( tf.GraphKeys.UPDATE_OPS, t.assign(decay*t+(1-decay)*v) )\r\n\r\n #Mean squared errors\r\n mse = 10*tf.reduce_mean( tf.square(output - target_outputs), axis=[1,2,3] )\r\n \r\n alrc_mse = mse#alrc(mse)\r\n alrc_mse = tf.reduce_mean(alrc_mse)\r\n \r\n mse_gen_loss = alrc_mse\r\n\r\n #Create optimizer for stochastic gradient descent (SGD)\r\n gen_optimizer = tf.train.AdamOptimizer(\r\n learning_rate=learning_rate,\r\n beta1=0.5\r\n )\r\n #gen_optimizer = tf.train.RMSPropOptimizer(learning_rate=0.0001, decay=0.5)\r\n\r\n\r\n #(\r\n # learning_rate=learning_rate,\r\n # beta1=beta1,\r\n # beta2=0.9\r\n # )\r\n\r\n #Update ops for batch normalisation\r\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\r\n \r\n with tf.control_dependencies(update_ops):\r\n if adversarial:\r\n #train_op = gen_optimizer.minimize(total_loss)\r\n gen_train_op = gen_optimizer.minimize(gen_loss, var_list=tf.trainable_variables(\"gen\"))\r\n mse_gen_train_op = gen_optimizer.minimize(mse_gen_loss, var_list=tf.trainable_variables(\"gen\"))\r\n discr_train_op = discr_optimizer.minimize(discr_loss, var_list=tf.trainable_variables(\"main/discr\"))\r\n train_op = [gen_train_op, discr_train_op, mse_gen_train_op]\r\n else:\r\n train_op = gen_optimizer.minimize(gen_loss)\r\n \r\n output_loss = {\r\n \"Loss\": tf.reduce_mean( tf.abs(phase_components - target_outputs0) ),\r\n \"pred_real\": tf.reduce_mean(real_pred),\r\n \"pred_fake\": tf.reduce_mean(fake_pred)\r\n }\r\n\r\n return train_op, output_loss, output0\r\n\r\n\r\ndef experiment(report_every_n=100):\r\n \"\"\"Run training operations, then validate.\r\n \r\n Args:\r\n report_every_n: Print loss every n training operations. 0 for no printing.\r\n \r\n Returns:\r\n Validation top-1 accuracy and a numpy array of training losses\r\n \"\"\"\r\n \r\n #Placeholders to feed hyperparameters into graph\r\n learning_rate_ph = tf.placeholder(tf.float32, name=\"learning_rate\")\r\n beta1_ph = tf.placeholder(\r\n tf.float32, \r\n shape=(),\r\n name=\"beta1\")\r\n decay_ph = tf.placeholder(\r\n tf.float32, \r\n shape=(),\r\n name=\"decay\")\r\n gen_scale_ph = tf.placeholder(\r\n tf.float32, \r\n shape=(),\r\n name=\"gen_scale\")\r\n is_training_ph = tf.placeholder(\r\n tf.bool, \r\n name=\"is_training\")\r\n mode_ph = tf.placeholder(\r\n tf.int32, \r\n name=\"mode\")\r\n\r\n #data_dir = \"//Desktop-sa1evjv/h/wavefunctions/\"\r\n data_dir = \"//Desktop-sa1evjv/f/wavefunctions_single/wavefunctions/\"\r\n batch_size = 24\r\n\r\n def load_data_subset(subset):\r\n return load_data(\r\n dir=data_dir,\r\n subset=subset, \r\n batch_size=batch_size\r\n )\r\n\r\n inputs, target_outputs = tf.case(\r\n {tf.equal(mode_ph, 0): lambda: load_data_subset(\"train\"),\r\n tf.equal(mode_ph, 1): lambda: load_data_subset(\"val\"),\r\n tf.equal(mode_ph, 2): lambda: load_data_subset(\"test\")}\r\n )\r\n \r\n #Describe learning policy\r\n grace_iter = 4_000\r\n pretrain_iter = 100_000\r\n start_iter = 0#100_000-grace_iter#0\r\n train_iters = 500_000\r\n val_iters = 1_000\r\n \r\n learning_rate = 0.001\r\n beta1 = 0.9\r\n \r\n #Configure operations\r\n train_op0, loss, output = configure(\r\n inputs=inputs,\r\n batch_size=batch_size,\r\n target_outputs=target_outputs,\r\n is_training=is_training_ph,\r\n learning_rate=learning_rate_ph, \r\n beta1=beta1_ph,\r\n is_depthwise_sep=False,\r\n decay=decay_ph,\r\n gen_scale=gen_scale_ph\r\n )\r\n \r\n clip_op = tf.get_collection(\"clip_weights\")\r\n\r\n #Tensors to dump as visual output\r\n first_image = inputs[0]\r\n first_target_output = target_outputs[0]\r\n first_output = output[0]\r\n\r\n #Session configuration\r\n config = tf.ConfigProto()\r\n config.gpu_options.allow_growth = True #Only use required GPU memory\r\n config.gpu_options.force_gpu_compatible = True\r\n\r\n model_dir = f\"//flexo.ads.warwick.ac.uk/Shared41/Microscopy/Jeffrey-Ede/models/wavefunctions/{EXPER_NUM}/\"\r\n\r\n saver = tf.train.Saver(max_to_keep=1)\r\n noteable_saver = tf.train.Saver(max_to_keep=10)\r\n\r\n log_filepath = model_dir + \"log.txt\"\r\n save_period = 1; save_period *= 3600\r\n with tf.Session(config=config) as sess, open(log_filepath, \"a\") as log_file:\r\n\r\n #Initialize network parameters\r\n feed_dict = {\r\n is_training_ph: np.bool(True),\r\n learning_rate_ph: np.float32(learning_rate),\r\n beta1_ph: np.float32(beta1),\r\n mode_ph: np.int32(0),\r\n decay_ph: np.float32(0.),\r\n gen_scale_ph: np.float32(0.)\r\n }\r\n \r\n if False:\r\n sess.run(tf.global_variables_initializer(), feed_dict=feed_dict)\r\n\r\n saver_mse = tf.train.Saver(max_to_keep=1, var_list=tf.trainable_variables(\"gen\"))\r\n saver_mse.restore(\r\n sess, \r\n tf.train.latest_checkpoint(model_dir+\"noteable_ckpt/\")\r\n )\r\n else:\r\n if start_iter:\r\n saver.restore(\r\n sess, \r\n tf.train.latest_checkpoint(model_dir+\"model/\")\r\n )\r\n else:\r\n sess.run(tf.global_variables_initializer(), feed_dict=feed_dict)\r\n\r\n #Finalize graph to prevent additional nodes from being added\r\n #sess.graph.finalize()\r\n\r\n #Training\r\n avg_pred_fake = 0.4\r\n beta_pred_fake = 0.9\r\n time0 = time.time()\r\n for iter in range(start_iter, train_iters):\r\n \r\n if iter < pretrain_iter-grace_iter:\r\n train_op = train_op0[-1]\r\n lr = learning_rate #* 0.5**( iter//(100_000//7) )\r\n elif iter < pretrain_iter:\r\n lr = learning_rate #* 0.5**( iter//(100_000//7) )\r\n train_op = train_op0[1:]\r\n else:\r\n lr = 0.0002\r\n train_op = train_op0[:-1]\r\n\r\n is_halfway = iter >= train_iters // 2\r\n\r\n decay = 0.997 if iter else 0.\r\n \r\n is_training = True#iter < 1_000 #not is_halfway\r\n beta1 = 0.9 if iter < 200_000 else 0.5\r\n \r\n gen_scale = 1.#0 if iter < 50 else 1.\r\n\r\n #Feed values into training operations\r\n feed_dict = {\r\n is_training_ph: np.bool(is_training),\r\n learning_rate_ph: np.float32(lr),\r\n beta1_ph: np.float32(beta1),\r\n mode_ph: np.int32(0),\r\n decay_ph: np.float32(decay),\r\n gen_scale_ph: np.float32(gen_scale)\r\n }\r\n\r\n if iter in [0, 100, 500] or not iter % 25_000 or (0 <= iter < 10_000 and not iter % 1000) or iter == start_iter:\r\n _, step_loss, [step_image, step_target_output, step_output] = sess.run([\r\n train_op, \r\n loss,\r\n [first_image, first_target_output, first_output]\r\n ],\r\n feed_dict=feed_dict\r\n )\r\n \r\n save_input_loc = model_dir+\"input-\"+str(iter)+\".tif\"\r\n save_truth_loc = model_dir+\"truth-\"+str(iter)+\".tif\"\r\n save_output_loc = model_dir+\"output-\"+str(iter)+\".tif\"\r\n target_angle = np.angle(step_target_output[...,0] + 1j*step_target_output[...,1])\r\n output_angle = np.angle(step_output[...,0] + 1j*step_output[...,1])\r\n Image.fromarray(step_image.reshape(cropsize, cropsize).astype(np.float32)).save( save_input_loc )\r\n Image.fromarray(np.cos(target_angle).astype(np.float32)).save( save_truth_loc )\r\n Image.fromarray(np.cos(output_angle).astype(np.float32)).save( save_output_loc )\r\n else:\r\n _, step_loss = sess.run([train_op, loss], feed_dict=feed_dict)\r\n\r\n if standard_wass:\r\n sess.run(clip_op)\r\n \r\n avg_pred_fake = beta_pred_fake*avg_pred_fake + (1-beta_pred_fake)*step_loss[\"pred_fake\"]\r\n\r\n output = f\"Iter: {iter}\"\r\n for k in step_loss:\r\n output += f\", {k}: {step_loss[k]}\"\r\n\r\n if report_every_n:\r\n if not iter % report_every_n:\r\n print(output)\r\n\r\n if \"nan\" in output:\r\n saver.restore(\r\n sess, \r\n tf.train.latest_checkpoint(model_dir+\"model/\")\r\n )\r\n #quit()\r\n\r\n log_file.write(output)\r\n\r\n if iter in [99_500, train_iters//2-1, train_iters-1]:\r\n noteable_saver.save(sess, save_path=model_dir+\"noteable_ckpt/model\", global_step=iter)\r\n time0 = time.time()\r\n start_iter = iter\r\n elif time.time() >= time0 + save_period:\r\n saver.save(sess, save_path=model_dir+\"model/model\", global_step=iter)\r\n time0 = time.time()\r\n \r\n #Validation - super important!\r\n val_loss = 0.\r\n for iter in range(val_iters):\r\n \r\n feed_dict = {\r\n is_training_ph: np.bool(False),\r\n mode_ph: np.int32(1),\r\n decay_ph: np.float32(decay)\r\n }\r\n \r\n step_loss = sess.run(loss, feed_dict=feed_dict)\r\n val_loss += step_loss\r\n \r\n val_loss /= val_iters\r\n \r\n return val_loss\r\n\r\nif __name__ == \"__main__\":\r\n #Reset so graph nodes to not accumulate in ipynb session memory.\r\n tf.reset_default_graph()\r\n\r\n #Run your experiment!\r\n val_loss = experiment(report_every_n=1)\r\n\r\n #Report performance on validation set\r\n print(f\"Validation loss: {val_loss}\")\r\n with open(model_dir+\"val_loss.txt\", \"w\") as f:\r\n f.write(f\"Val Loss: {val_loss}\")"
] |
[
[
"tensorflow.sin",
"tensorflow.concat",
"tensorflow.cos",
"tensorflow.ifft2d",
"tensorflow.fft2d",
"tensorflow.meshgrid",
"tensorflow.linspace"
],
[
"tensorflow.device",
"numpy.product",
"tensorflow.concat",
"tensorflow.control_dependencies",
"numpy.bool",
"tensorflow.reduce_sum",
"tensorflow.equal",
"numpy.max",
"tensorflow.data.Dataset.list_files",
"tensorflow.nn.l2_loss",
"tensorflow.contrib.framework.get_name_scope",
"tensorflow.train.AdamOptimizer",
"tensorflow.py_func",
"numpy.random.randint",
"tensorflow.image.random_flip_left_right",
"tensorflow.get_collection",
"tensorflow.gradients",
"tensorflow.stop_gradient",
"tensorflow.ConfigProto",
"numpy.sin",
"tensorflow.reset_default_graph",
"tensorflow.Session",
"numpy.float32",
"tensorflow.train.Saver",
"numpy.load",
"tensorflow.trainable_variables",
"tensorflow.random_normal_initializer",
"numpy.zeros",
"tensorflow.square",
"tensorflow.sqrt",
"tensorflow.nn.l2_normalize",
"numpy.rot90",
"tensorflow.matmul",
"numpy.min",
"numpy.isnan",
"tensorflow.zeros_initializer",
"tensorflow.identity",
"tensorflow.placeholder",
"tensorflow.global_variables_initializer",
"tensorflow.image.random_flip_up_down",
"tensorflow.contrib.layers.batch_norm",
"numpy.flip",
"tensorflow.add_to_collection",
"tensorflow.nn.leaky_relu",
"tensorflow.nn.bias_add",
"tensorflow.clip_by_value",
"numpy.absolute",
"tensorflow.transpose",
"numpy.abs",
"tensorflow.constant",
"tensorflow.reduce_mean",
"numpy.isfinite",
"tensorflow.train.latest_checkpoint",
"tensorflow.reshape",
"numpy.int32",
"numpy.cos",
"tensorflow.layers.average_pooling2d",
"tensorflow.variable_scope",
"numpy.angle",
"tensorflow.random_uniform",
"numpy.isinf",
"tensorflow.abs"
]
] |
wuzuowuyou/ogre-magi
|
[
"8b5da1f43fdfd2a1b3fb1d3ae91d8c551e21b9b4"
] |
[
"net/loss/l1_loss.py"
] |
[
"import torch\nimport torch.nn as nn\n\nclass MaskL1Loss(nn.Module):\n def __init__(self):\n super(MaskL1Loss, self).__init__()\n\n def forward(self, pred: torch.Tensor, gt, mask):\n mask_sum = mask.sum()\n if mask_sum.item() == 0:\n return mask_sum, dict(l1_loss=mask_sum)\n else:\n loss = (torch.abs(pred[:, 0] - gt) * mask).sum() / mask_sum\n return loss, dict(l1_loss=loss)\n\n\nclass BalanceL1Loss(nn.Module):\n def __init__(self, negative_ratio=3.):\n super(BalanceL1Loss, self).__init__()\n self.negative_ratio = negative_ratio\n\n def forward(self, pred: torch.Tensor, gt, mask):\n '''\n Args:\n pred: (N, 1, H, W).\n gt: (N, H, W).\n mask: (N, H, W).\n '''\n loss = torch.abs(pred[:, 0] - gt)\n positive = loss * mask\n negative = loss * (1 - mask)\n positive_count = int(mask.sum())\n negative_count = min(\n int((1 - mask).sum()),\n int(positive_count * self.negative_ratio))\n negative_loss, _ = torch.topk(negative.view(-1), negative_count)\n negative_loss = negative_loss.sum() / negative_count\n positive_loss = positive.sum() / positive_count\n return positive_loss + negative_loss,\\\n dict(l1_loss=positive_loss, nge_l1_loss=negative_loss)\n"
] |
[
[
"torch.abs"
]
] |
uwon0625/prudential
|
[
"2466495bd07e0774b74d27ec0ca856f22d23b5e6"
] |
[
"src/models/test.py"
] |
[
"import pandas as pd \n\nfile_path = '../submissions/submission.csv'\ndf = pd.read_csv(file_path)\ndf['Response']+=1\ndf.to_csv(file_path.replace('.csv','_adj.csv'), index=False)\n"
] |
[
[
"pandas.read_csv"
]
] |
simpeg/aurora
|
[
"1c81c464fb2e01da58e2c6b361b406b117100dcf",
"1c81c464fb2e01da58e2c6b361b406b117100dcf"
] |
[
"aurora/transfer_function/regression/helper_functions.py",
"aurora/sandbox/io_helpers/emtf_band_setup.py"
] |
[
"import numpy as np\n\n\ndef rme_beta(r0):\n \"\"\"\n This is an RME specific property.\n It represents a bias in the calculation of residual_variance\n which we correct for in TRME and TRME_RR.\n\n The implemented formula is an approximation. This is approximately equal to 1/beta\n where beta is defined by Equation A3 in Egbert & Booker 1986.\n\n for r0=1.5 the correction factor is ~1.28 and beta ~0.78\n\n Some notes from a discussion with Gary:\n In the regression esimtate you downweight things with large errors, but\n you need to define what's large. You estimate the standard devation\n (sigma) of the errors from the residuals BUT with this cleaned data\n approach (Yc) sigma is smaller than it should be, you need to\n compensate for this by using a correction_factor. It's basically the\n expectation, if the data really were Gaussian, and you estimated from\n the corrected data. This is how much too small the estimate would be.\n\n If you change the penalty functional you may need a pencil, paper and\n some calculus. The relationship between the corrected-data-residuals\n and the gaussin residauls could change if you change the penalty\n\n Parameters\n ----------\n r0 : float\n The number of standard errors at which the RME method transitions from\n quadratic weighting to linear\n\n Returns\n -------\n beta : float\n correction factor = 1/beta\n \"\"\"\n beta = 1.0 - np.exp(-r0)\n return beta\n",
"import pandas as pd\n\n\nclass EMTFBandSetupFile:\n def __init__(self, **kwargs):\n \"\"\"\n\n Parameters\n ----------\n sample_rate: float\n this is the sampling rate of the un-decimated data,\n aka decimation level 1 in EMTF (and probably zero in the\n aurora nomenclature)\n kwargs\n \"\"\"\n self.filepath = kwargs.get(\"filepath\", None)\n self.df = None\n self.n_bands = None\n self.sample_rate = None\n\n def load(self, filepath=None):\n if filepath is None:\n filepath = self.filepath\n print(filepath)\n f = open(str(filepath), \"r\")\n n_bands = f.readline()\n self.n_bands = int(n_bands)\n f.close()\n df = pd.read_csv(\n filepath,\n skiprows=1,\n sep=\"\\s+\",\n names=[\"decimation_level\", \"lower_bound_index\", \"upper_bound_index\"],\n )\n if len(df) != self.n_bands:\n print(f\"unexpected number of bounds read in from {filepath}\")\n raise Exception\n self.df = df\n\n def get_decimation_level(self, decimation_level, order=\"ascending_frequency\"):\n if self.df is None:\n self.load()\n decimation_level_df = self.df[self.df[\"decimation_level\"] == decimation_level]\n if order == \"ascending_frequency\":\n decimation_level_df = decimation_level_df.sort_values(\n by=\"lower_bound_index\"\n )\n\n return decimation_level_df\n\n def to_band_averaging_scheme(self):\n \"\"\"\n probably better to give band averaging scheme a \"from emtf\"\n method\n Returns\n -------\n\n \"\"\"\n pass\n"
] |
[
[
"numpy.exp"
],
[
"pandas.read_csv"
]
] |
anshulbshah/MMCL
|
[
"d6f747ae0e7f3f244a5dc6ceb6034976eacd1dce"
] |
[
"CIFAR100/linear.py"
] |
[
"import argparse\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader\nfrom tqdm import tqdm\n\nimport os\nimport pickle\n\nimport utils\nfrom model import Model\nfrom warmup_scheduler import GradualWarmupScheduler\nimport wandb\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nprint('Home device: {}'.format(device))\n\nclass Net(nn.Module):\n def __init__(self, num_class, pretrained_path):\n super(Net, self).__init__()\n\n # encoder\n model = Model().to(device)\n model = nn.DataParallel(model)\n model.load_state_dict(torch.load(pretrained_path, map_location='cuda:0'))\n # self.f=model.f\n self.f = model.module.f\n # classifier\n self.fc = nn.Linear(2048, num_class, bias=True)\n\n def forward(self, x):\n x = self.f(x)\n feature = torch.flatten(x, start_dim=1)\n out = self.fc(feature)\n return out\n\ndef get_lr(optimizer):\n for param_group in optimizer.param_groups:\n return param_group['lr']\n\n# train or test for one epoch\ndef train_val(net, data_loader, train_optimizer):\n is_train = train_optimizer is not None\n net.train() if is_train else net.eval()\n\n total_loss, total_correct_1, total_correct_5, total_num, data_bar = 0.0, 0.0, 0.0, 0, tqdm(data_loader)\n with (torch.enable_grad() if is_train else torch.no_grad()):\n for data, target in data_bar:\n data, target = data.to(device,non_blocking=True), target.to(device,non_blocking=True)\n out = net(data)\n loss = loss_criterion(out, target)\n\n if is_train:\n train_optimizer.zero_grad()\n loss.backward()\n train_optimizer.step()\n\n total_num += data.size(0)\n total_loss += loss.item() * data.size(0)\n prediction = torch.argsort(out, dim=-1, descending=True)\n total_correct_1 += torch.sum((prediction[:, 0:1] == target.unsqueeze(dim=-1)).any(dim=-1).float()).item()\n total_correct_5 += torch.sum((prediction[:, 0:5] == target.unsqueeze(dim=-1)).any(dim=-1).float()).item()\n\n data_bar.set_description('{} Epoch: [{}/{}] Loss: {:.4f} ACC@1: {:.2f}% ACC@5: {:.2f}%'\n .format('Train' if is_train else 'Test', epoch, epochs, total_loss / total_num,\n total_correct_1 / total_num * 100, total_correct_5 / total_num * 100))\n return total_loss / total_num, total_correct_1 / total_num * 100, total_correct_5 / total_num * 100\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Linear Evaluation')\n parser.add_argument('--model_path', type=str, default='',\n help='The pretrained model path')\n parser.add_argument('--batch_size', type=int, default=512, help='Number of images in each mini-batch')\n parser.add_argument('--epochs', type=int, default=100, help='Number of sweeps over the dataset to train')\n parser.add_argument('--dataset_name', default='cifar100', type=str, help='Choose loss function')\n parser.add_argument('--dataset_location', default='../data', type=str, help='Choose loss function')\n parser.add_argument('--num_workers', default=8, type=int, help='Choose loss function')\n parser.add_argument('--learning_rate', default=1e-3, type=float, help='Choose loss function')\n parser.add_argument('--weight_decay', default=1e-6, type=float, help='Choose loss function')\n\n\n args = parser.parse_args()\n model_path, batch_size, epochs = args.model_path, args.batch_size, args.epochs\n dataset_name = args.dataset_name\n \n train_data, _, test_data = utils.get_dataset(dataset_name, args.dataset_location, pair=False)\n\n train_loader = DataLoader(train_data, batch_size=batch_size, shuffle=True, num_workers=args.num_workers, pin_memory=True)\n test_loader = DataLoader(test_data, batch_size=batch_size, shuffle=False, num_workers=args.num_workers, pin_memory=True)\n\n model = Net(num_class=len(train_data.classes), pretrained_path=model_path).to(device)\n for param in model.f.parameters():\n param.requires_grad = False\n model = nn.DataParallel(model)\n\n optimizer = optim.Adam(model.module.fc.parameters(), lr=args.learning_rate, weight_decay=args.weight_decay)\n\n loss_criterion = nn.CrossEntropyLoss()\n results = {'train_loss': [], 'train_acc@1': [], 'train_acc@5': [],\n 'test_loss': [], 'test_acc@1': [], 'test_acc@5': []}\n\n best_top1 = (-10,-1)\n for epoch in range(1, epochs + 1):\n train_loss, train_acc_1, train_acc_5 = train_val(model, train_loader, optimizer)\n if epoch % 5 == 0:\n test_loss, test_acc_1, test_acc_5 = train_val(model, test_loader, None)\n if test_acc_1 > best_top1[0]:\n best_top1 = (test_acc_1,epoch)\n\n metrics = {\n 'test_loss':test_loss,\n 'test_acc_1':test_acc_1,\n 'test_acc_5':test_acc_5,\n 'lr':get_lr(optimizer),\n 'best_top1':best_top1[0],\n 'epoch':epoch\n }\n if not os.path.exists('../results/'):\n os.mkdir('../results/')\n try:\n results=pickle.load( open( '../results/summary.pkl', \"rb\" ))\n except:\n results={}\n results[model_path]=test_acc_1\n pickle.dump(results, open( '../results/summary.pkl', \"wb\" ) )\n print('best top1',best_top1)"
] |
[
[
"torch.nn.CrossEntropyLoss",
"torch.enable_grad",
"torch.load",
"torch.argsort",
"torch.utils.data.DataLoader",
"torch.nn.Linear",
"torch.no_grad",
"torch.cuda.is_available",
"torch.flatten",
"torch.nn.DataParallel"
]
] |
ds3300/adl_final_project
|
[
"49e7e6bf9190e6c56bd950ccd9bee7a39606dd13"
] |
[
"pdf_text_extraction.py"
] |
[
"from pdf2image import convert_from_path, convert_from_bytes\r\nfrom IPython.display import display, Image\r\nimport matplotlib.pyplot as plt\r\nimport os\r\nimport pandas as pd\r\nimport s3fs\r\nimport boto3\r\nimport sys\r\nfrom PIL import Image\r\nimport numpy as np\r\nimport tensorflow as tf\r\nimport cv2\r\nfrom google.colab.patches import cv2_imshow\r\nimport cv2\r\nimport re\r\n\r\ndef convert_pdf_to_jpegs(pdf_file_name):\r\n\r\n if \"pdf_sheets\" not in os.listdir(\"/content\"):\r\n print('Making directory /content/pdf_sheets')\r\n os.mkdir(\"/content/pdf_sheets\")\r\n else:\r\n print('Removing and making directory /content/pdf_sheets')\r\n os.system(\"rm -r /content/pdf_sheets\")\r\n os.mkdir(\"/content/pdf_sheets\")\r\n\r\n print('Converting PDF sheets to JPEGs')\r\n images = convert_from_bytes(open(pdf_file_name,'rb').read(), \r\n fmt='jpeg',\r\n size = (8800, 6800), \r\n #first_page=0, last_page=5,\r\n output_folder=\"/content/pdf_sheets/\",\r\n output_file='pdf_sheet',\r\n paths_only=True)\r\n\r\ndef convert_pdf_to_image(fn, width, height):\r\n \"\"\"\r\n Take in a file name and convert the PDF into a \r\n list of grayscale images\r\n \"\"\"\r\n images = convert_from_bytes(open(fn,'rb').read(), size = (width, height))\r\n \r\n for i in range(len(images)):\r\n images_i = images[i].convert('L')\r\n images[i] = images_i\r\n\r\n return images\r\n\r\ndef convert_image_to_array(image_list):\r\n \"\"\"\r\n Convert PIL Image to list of numpy arrays\r\n \"\"\"\r\n\r\n array_list = []\r\n\r\n for i in range(len(image_list)):\r\n array_i = np.array(image_list[i])\r\n array_list.append(array_i)\r\n\r\n return array_list\r\n\r\ndef get_row_starts(img_raw, cutoff):\r\n \"\"\"\r\n Identify the darker pixel rows, which indicate a line\r\n Return the start of the rows\r\n \"\"\"\r\n\r\n dark_rows = np.where(np.mean(img_raw, 1) <= cutoff)[0]\r\n dark_row_starts = np.ediff1d(dark_rows, to_begin=dark_rows[0]-1) - 1\r\n dark_row_starts = dark_row_starts>0\r\n return dark_rows[dark_row_starts]\r\n\r\ndef crop_img_rows(img_raw, row_starts):\r\n\r\n \"\"\"\r\n Take in a numpy array and crop the array based on the \r\n supplied array of indicies that determine the start\r\n of a new property row.\r\n \"\"\"\r\n assert isinstance(img_raw, (np.ndarray))\r\n start_idx = 0\r\n stop_idx = 1\r\n \r\n # calculate the median row height, add this value to the last\r\n # value in row_starts, and append to row_start in order\r\n # to crop the last row in the sheet\r\n med_row_height = np.median((np.ediff1d(row_starts)))\r\n final_crop_end = med_row_height + row_starts[-1]\r\n \r\n row_starts=np.append(row_starts, final_crop_end.astype(int))\r\n \r\n img_crop_l = []\r\n \r\n for i in range(len(row_starts)-1):\r\n crop_start = row_starts[start_idx]\r\n # Determine which pixel row is completeley blank, which \r\n # represents the end of the horizontal line.\r\n if crop_start+25 <= img_raw.shape[0]:\r\n for h in range(crop_start, crop_start+25):\r\n if np.mean(img_raw[h,:]) >= 250:\r\n crop_start = h\r\n crop_end = row_starts[stop_idx] - 1\r\n img_crop_i = img_raw[crop_start:crop_end,:]\r\n \r\n # Ensure that the horizontal bar has been cropped out\r\n #assert np.mean(img_crop_i,1)[0] == 255.0\r\n\r\n img_crop_l.append(img_crop_i)\r\n start_idx += 1\r\n stop_idx += 1\r\n \r\n return img_crop_l\r\n\r\ndef identify_header_row(row_starts):\r\n header_idx = 0\r\n diff = np.Inf\r\n for i in range(1, len(row_starts)):\r\n diff_i = row_starts[i]-row_starts[i-1]\r\n if diff_i <= diff:\r\n diff = diff_i\r\n header_idx = i-1\r\n return header_idx\r\n\r\ndef extract_img_rows(img_raw, cutoff):\r\n\r\n \"\"\"\r\n Take in a single image as a numpy array and extract the rows\r\n corresponding to property records.\r\n \"\"\"\r\n\r\n row_starts=get_row_starts(img_raw=img_raw, cutoff=cutoff)\r\n img_rows=crop_img_rows(img_raw=img_raw, row_starts=row_starts)\r\n \r\n return row_starts, img_rows\r\n\r\ndef get_col_starts(header_row_raw, cutoff, window_width=100, lpad=100,\r\n use_row_midsection=False):\r\n \"\"\"\r\n Do a moving n-pixel wide moving average of the header's\r\n intensity to determine when a new column of data has begun.\r\n \"\"\"\r\n\r\n # Specifiy whether you should only consider the midsection of the \r\n # array when determinint the means, thus avoiding potential text\r\n # overhanging from the line above that could make it seem like\r\n # there was text\r\n if use_row_midsection == False:\r\n header_row_mean = np.mean(np.array(header_row_raw), 0)\r\n else:\r\n vertical_crop=np.floor(header_row_raw.shape[0]*0.1).astype(int)\r\n header_row_mean = np.mean(np.array(header_row_raw)[vertical_crop:-vertical_crop, :], 0)\r\n \r\n col_start_l = []\r\n\r\n prev_window_mean = cutoff\r\n\r\n for i in range(lpad+1, len(header_row_mean)):\r\n window_start = i-window_width\r\n window_end = i\r\n window_mean = np.mean(header_row_mean[window_start:window_end])\r\n if window_mean < cutoff and prev_window_mean >= cutoff:\r\n col_start_l.append(window_end)\r\n prev_window_mean = window_mean\r\n \r\n return col_start_l\r\n\r\ndef tighten_img_crop(row_col_cell):\r\n\r\n \"\"\"\r\n Take in a single cell and tighten the crop \r\n by eliminating empty whitespace.\r\n \"\"\"\r\n\r\n # Crop pixel columns\r\n right_crop_idx = row_col_cell.shape[1]\r\n col_mean=np.mean(row_col_cell,0)\r\n for i in range(len(col_mean)-1,0,-1):\r\n if col_mean[i] != 255.0:\r\n right_crop_idx = i + 2\r\n right_crop_idx = np.amin([right_crop_idx, row_col_cell.shape[1]])\r\n break\r\n\r\n left_crop_idx = 0\r\n col_mean=np.mean(row_col_cell,0)\r\n for i in range(len(col_mean)):\r\n if col_mean[i] != 255.0:\r\n left_crop_idx = i - 2\r\n left_crop_idx = np.amax([left_crop_idx, 0])\r\n break \r\n \r\n # Crop pixel rows\r\n bottom_crop_idx = row_col_cell.shape[0]\r\n row_mean=np.mean(row_col_cell,1)\r\n for i in range(len(row_mean)-1,0,-1):\r\n if row_mean[i] != 255.0:\r\n bottom_crop_idx = i + 2\r\n bottom_crop_idx = np.amin([bottom_crop_idx, row_col_cell.shape[0]])\r\n break\r\n\r\n top_crop_idx = 0\r\n row_mean=np.mean(row_col_cell,1)\r\n for i in range(len(row_mean)):\r\n if row_mean[i] != 255.0:\r\n top_crop_idx = i - 2\r\n top_crop_idx = np.amax([top_crop_idx, 0])\r\n break\r\n\r\n # Ensure that all new crop indices are within the bounds of\r\n # the original image\r\n assert left_crop_idx >= 0\r\n assert top_crop_idx >= 0\r\n assert right_crop_idx <= row_col_cell.shape[1]\r\n assert bottom_crop_idx <= row_col_cell.shape[0]\r\n \r\n cropped_cell = row_col_cell[top_crop_idx:bottom_crop_idx, \r\n left_crop_idx:right_crop_idx]\r\n\r\n return cropped_cell\r\n\r\ndef get_line_starts(img_raw, cutoff):\r\n \"\"\"\r\n Identify the darker pixel rows, which indicate a line\r\n Return the start of the rows\r\n \"\"\"\r\n\r\n light_rows = np.where(np.mean(img_raw, 1) >= cutoff)[0]\r\n light_row_starts = np.ediff1d(light_rows, to_begin=light_rows[0]-1) - 1\r\n light_row_starts = light_row_starts>0\r\n return light_rows[light_row_starts]\r\n\r\ndef split_cell_into_lines(row_col_cell, cutoff=250):\r\n\r\n # Determine mean row pixel value to figure out where the line starts\r\n line_starts = get_line_starts(img_raw=row_col_cell, cutoff=cutoff)\r\n print(type(line_starts[0]))\r\n \r\n # Append the first and last rows of the row/col cell and sort\r\n line_starts=np.append(line_starts, [0, row_col_cell.shape[0]])\r\n line_starts.sort()\r\n print(line_starts)\r\n \r\n # Determine the distance between each of the line starts to determine\r\n # which are really valid\r\n line_starts_diffs = np.ediff1d(line_starts, to_begin=line_starts[0])\r\n print(line_starts_diffs)\r\n\r\n # Filter the diffs and the starts by those diffs that are too small\r\n line_starts = line_starts[line_starts_diffs>10]\r\n line_starts_diffs = line_starts_diffs[line_starts_diffs>10]\r\n\r\n # Calculate the median diff, and only keep those line starts\r\n # that are close to the median diff\r\n median_line_start_diff = np.median(line_starts_diffs)\r\n print(line_starts_diffs)\r\n print(line_starts)\r\n bool_mask=np.abs(line_starts_diffs-median_line_start_diff)<=10\r\n\r\n #TODO this logic needs to be reworked.\r\n for i in range(len(bool_mask)-1):\r\n if bool_mask[i] == False and bool_mask[i+1] == True:\r\n bool_mask[i] = True\r\n \r\n line_starts = line_starts[bool_mask]\r\n line_starts = np.append(line_starts, [0])\r\n line_starts.sort()\r\n\r\n # Split up row/cell by line starts\r\n\r\n line_dict = {}\r\n print('len(line_starts)-1 :',len(line_starts)-1)\r\n for i in range(len(line_starts)-1):\r\n start = line_starts[i]\r\n end = line_starts[i+1]\r\n end +=1\r\n key = \"line\"+str(i)\r\n print(key)\r\n line = row_col_cell[start:end, :]\r\n line_dict.update({key : line})\r\n\r\n return line_dict\r\n\r\ndef crop_img_cols(img_rows, col_starts, left_buffer):\r\n \"\"\"\r\n Take in a numpy array and crop the array based on the \r\n supplied array of indicies that determine the start\r\n of a row's new column.\r\n \"\"\"\r\n\r\n row_l = []\r\n\r\n for r in range(len(img_rows)): \r\n start_idx = 0\r\n stop_idx = 1\r\n\r\n row_r = img_rows[r]\r\n row_r_dict = {}\r\n\r\n for i in range(len(col_starts)):\r\n crop_start = col_starts[start_idx]-left_buffer\r\n \r\n if stop_idx > len(col_starts)-1:\r\n crop_end = row_r.shape[1]\r\n else:\r\n crop_end = col_starts[stop_idx]\r\n \r\n row_col_i = row_r[:,crop_start-1:crop_end-1]\r\n\r\n # Crop the row/col cell\r\n row_col_i = tighten_img_crop(row_col_cell=row_col_i)\r\n \r\n col_i_name = 'col'+str(i)\r\n\r\n row_r_dict.update({col_i_name : row_col_i})\r\n\r\n start_idx += 1\r\n stop_idx += 1\r\n \r\n row_l.append(row_r_dict)\r\n\r\n return row_l\r\n\r\ndef extract_row_cols(img_rows, row_starts):\r\n \r\n \"\"\"\r\n Take in a list of rows, identify the column starts,\r\n crop the images based on those indices, and\r\n return a list of dictionaries\r\n \"\"\"\r\n\r\n # Determine the header row\r\n header_idx=identify_header_row(row_starts=row_starts)\r\n\r\n # Determine the column starts based on the pixels of the header row\r\n # Add a buffer to cut out the horizontal line\r\n\r\n col_starts=get_col_starts(header_row_raw=img_rows[header_idx][40:-20,:], cutoff=255)\r\n\r\n # Return a list of dictionaries, representing a row and its columns\r\n img_cols = crop_img_cols(img_rows=img_rows, col_starts=col_starts, left_buffer=15)\r\n\r\n return img_cols\r\n\r\ndef remove_footer(img_raw):\r\n \"\"\"\r\n Remove the footer from the page image. The footer is a standard size\r\n for each page\r\n \"\"\"\r\n crop_height = np.floor(img_raw.shape[0]*0.955).astype(int)\r\n img_mod = img_raw[0:crop_height, :]\r\n return(img_mod)\r\n\r\ndef extract_img_rows_and_cols(pdf_sheet_dir, cutoff):\r\n\r\n \"\"\"\r\n Take in a list of images and return:\r\n - a list of images composed of\r\n - a list of rows composed of \r\n - a dictionary of columns\r\n \"\"\"\r\n img_raw_l = []\r\n pdf_sheets = os.listdir(pdf_sheet_dir)\r\n pdf_sheets.sort()\r\n\r\n for i in range(len(pdf_sheets)):\r\n progress_msg = '\\rReading in and converting JPEGs ('+str(i+1)+'/'+str(len(pdf_sheets))+')'\r\n sys.stdout.write(progress_msg)\r\n sys.stdout.flush()\r\n sheet_fn = os.path.join(pdf_sheet_dir, pdf_sheets[i])\r\n sheet = Image.open(sheet_fn).convert('L')\r\n sheet = np.array(sheet)\r\n img_raw_l.append(sheet)\r\n \r\n print('\\n')\r\n \r\n image_l = []\r\n\r\n for i in range(len(img_raw_l)):\r\n progress_msg = '\\rExtracting image rows and columns ('+str(i+1)+'/'+str(len(img_raw_l))+')'\r\n sys.stdout.write(progress_msg)\r\n sys.stdout.flush()\r\n img_raw_i = img_raw_l[i]\r\n img_raw_i = remove_footer(img_raw_i)\r\n row_starts, img_rows = extract_img_rows(img_raw_i, cutoff)\r\n\r\n img_rows = extract_row_cols(img_rows=img_rows, row_starts=row_starts)\r\n image_l.append(img_rows)\r\n\r\n return image_l\r\n\r\ndef get_char_contours(img):\r\n \r\n \"\"\"\r\n Return the coutours of the images\r\n source: https://stackoverflow.com/questions/50777688/finding-contours-with-lines-of-text-in-opencv\r\n \"\"\"\r\n\r\n ret,thresh = cv2.threshold(img, 0, 255,cv2.THRESH_OTSU|cv2.THRESH_BINARY_INV)\r\n \r\n contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL,\r\n cv2.CHAIN_APPROX_TC89_KCOS)\r\n\r\n return contours[0]\r\n\r\ndef get_bb_coord(contour, img, IMG_HEIGHT):\r\n\r\n \"\"\"\r\n Take in a single countour array generated by cv2.findContours\r\n and return the four corners of a bounding box that covers\r\n all of the coordinates.\r\n \"\"\"\r\n\r\n # Get the height of the array and reshape the array into a hx2 array\r\n h = contour.shape[0]\r\n c = np.reshape(contour, (h, 2))\r\n min = np.argmin(c, 0)\r\n max = np.argmax(c, 0)\r\n left = np.max([c[min[0], 0]-1, 0])\r\n top = np.max([c[min[1], 1]-1, 0])\r\n right = np.min([c[max[0], 0]+1, img.shape[1]])\r\n bottom = np.min([c[max[1], 1]+1, img.shape[0]])\r\n coords = (left, top, right, bottom)\r\n \r\n # Check for overlapping characters between lines\r\n if bottom-top > 1.2*IMG_HEIGHT:\r\n mid_point = np.floor((bottom-top)/2).astype(int)+top\r\n coord_top = (left, top, right, mid_point)\r\n coord_bottom = (left, mid_point, right, bottom)\r\n coords = [coord_top, coord_bottom]\r\n assert left < right\r\n assert top < bottom\r\n return coords\r\n\r\ndef make_bb_coord_l(contour_l, img, IMG_HEIGHT):\r\n \r\n \"\"\"\r\n Take in a list of contour arrays and return a list of four coordinates\r\n of a bounding box for each contour array.\r\n \"\"\"\r\n \r\n assert isinstance(contour_l, list)\r\n\r\n coord_l = []\r\n\r\n for i in range(len(contour_l)):\r\n c = contour_l[i]\r\n bb = get_bb_coord(contour=c, img=img, IMG_HEIGHT=IMG_HEIGHT)\r\n \r\n # extend if bb is a list (i.e. a split bounding box)\r\n if isinstance(bb, list):\r\n coord_l.extend(bb)\r\n else:\r\n coord_l.append(bb)\r\n \r\n return coord_l\r\n\r\ndef inspect_bb_coords(bb_coords):\r\n None\r\n\r\ndef char_max_height(bb_coords, IMG_HEIGHT):\r\n \"\"\"\r\n Take a list of bounding box coordinates and determine the greatest height\r\n among all of the boxes\r\n \"\"\"\r\n l = []\r\n\r\n for i in range(len(bb_coords)):\r\n c = bb_coords[i]\r\n c_top, c_bottom = c[1], c[3]\r\n c_height = c_bottom - c_top\r\n l.append(c_height)\r\n \r\n l.sort()\r\n \r\n max_height = np.amin([l[-1], IMG_HEIGHT])\r\n\r\n return max_height\r\n\r\ndef char_max_width(bb_coords, IMG_WIDTH):\r\n \"\"\"\r\n Take a list of bounding box coordinates and determine the greatest height\r\n among all of the boxes\r\n \"\"\"\r\n l = []\r\n\r\n for i in range(len(bb_coords)):\r\n c = bb_coords[i]\r\n c_left, c_right = c[0], c[2]\r\n c_width = c_right - c_left\r\n l.append(c_width)\r\n \r\n l.sort()\r\n \r\n max_width = np.amin([l[-1], IMG_WIDTH])\r\n\r\n return max_width\r\n\r\ndef resize_img_letter(letter_img, img_height, img_width):\r\n\r\n \"\"\"\r\n Get the image to as close to the specified dimensions as possible\r\n by adding/subtracting whitespace along the borders.\r\n \"\"\"\r\n\r\n letter_img_h, letter_img_w = letter_img.shape[0], letter_img.shape[1]\r\n\r\n letter_img_mod = letter_img\r\n\r\n if letter_img_h > img_height:\r\n nrows_to_remove = letter_img_h - img_height\r\n nrows_to_remove_top = int(np.floor(nrows_to_remove/2))\r\n nrows_to_remove_bottom = int(np.ceil(nrows_to_remove/2))\r\n letter_img_mod = letter_img_mod[nrows_to_remove_top:(-1*nrows_to_remove_bottom), :]\r\n elif letter_img_h < img_height:\r\n nrows_to_add = img_height - letter_img_h\r\n nrows_to_add_top = int(np.floor(nrows_to_add/2))\r\n nrows_to_add_bottom = int(np.ceil(nrows_to_add/2))\r\n letter_img_mod = np.concatenate((np.full(shape=(nrows_to_add_top, letter_img_w), fill_value=255.0),\r\n letter_img_mod,\r\n np.full(shape=(nrows_to_add_bottom, letter_img_w), fill_value=255.0)),\r\n axis = 0)\r\n\r\n if letter_img_w > img_width:\r\n ncols_to_remove = letter_img_w - img_width\r\n ncols_to_remove_left = int(np.floor(ncols_to_remove/2))\r\n ncols_to_remove_right = int(np.ceil(ncols_to_remove/2))\r\n letter_img_mod = letter_img_mod[:, ncols_to_remove_left:(-1*ncols_to_remove_right)]\r\n elif letter_img_w < img_width:\r\n ncols_to_add = img_width - letter_img_w\r\n ncols_to_add_left = int(np.floor(ncols_to_add/2))\r\n ncols_to_add_right = int(np.ceil(ncols_to_add/2))\r\n letter_img_mod = np.concatenate((np.full(shape=(img_height, ncols_to_add_left), fill_value=255.0),\r\n letter_img_mod,\r\n np.full(shape=(img_height, ncols_to_add_right), fill_value=255.0)),\r\n axis = 1)\r\n\r\n return letter_img_mod\r\n\r\ndef sort_bb_coords(bb_coords, img, max_height, max_width, \r\n IMG_HEIGHT, dist_coords=(0,0)):\r\n \"\"\"\r\n Assign all of the bb_coords to a list, unassigned_bb.\r\n\r\n Identify the bounding box that is closest to the upper lefthand corner\r\n of the frame. This is the first letter.\r\n\r\n Separate out the bounding boxes where the top coordinate is above the bottom\r\n coordinate of the first letter into a list line_0. Also remove these \r\n bounding boxes from unassigned_bb. This should identify all of the letters \r\n that are in the same line as the first letter.\r\n\r\n Sort each bounding box in line_0 by the lefthand coordinate to order the \r\n letters correctly.\r\n\r\n Repeat this process until all unassigned_bb have been assigned to a \r\n line list.\r\n \"\"\"\r\n\r\n # Calculate distance from each bounding box's top-left corner to the\r\n # specified coordinates. This parameter is modified for cells\r\n # that with text that isn't left aligned. Otherwise, some rows of text\r\n # might be missed\r\n distance_l = []\r\n for i in range(len(bb_coords)):\r\n d = np.sqrt(np.power(np.abs(bb_coords[i][0]-dist_coords[0]),2) + \r\n np.power(np.abs(bb_coords[i][1]-dist_coords[1]),2))\r\n distance_l.append(d)\r\n\r\n # Create a list of coordinate/distance dictionaries\r\n unassigned_bb = []\r\n for i in range(len(bb_coords)):\r\n coord_dict = {\"coord\":bb_coords[i], 'dist':distance_l[i]}\r\n unassigned_bb.append(coord_dict)\r\n # Initialize the dictionary to store all of the lines\r\n line_dict = {}\r\n key_idx=0\r\n counter = 0\r\n\r\n while len(unassigned_bb) > 0:\r\n counter += 1\r\n if counter >= 100:\r\n break\r\n # Identify which of the remaining items in unassigned_bb has the \r\n # shortest distance to (0,0)\r\n shortest_dist = np.Inf\r\n shortest_dist_idx = None\r\n\r\n for i in range(len(unassigned_bb)):\r\n dist = unassigned_bb[i].get('dist')\r\n if dist < shortest_dist:\r\n shortest_dist = dist\r\n shortest_dist_idx = i\r\n\r\n first_letter = unassigned_bb[shortest_dist_idx].get('coord')\r\n \r\n line_i = []\r\n remove_idxs = []\r\n\r\n # Determine which bounding boxes are in the same line as the first \r\n # letter\r\n # Get boxes in line 1\r\n for i in range(len(unassigned_bb)):\r\n coord = unassigned_bb[i].get(\"coord\")\r\n # If the top coordinate (1) of the unassigned bb is less than the \r\n # bottom coordinate (3) of the first bb (i.e. 'above' in the image)\r\n # then append it to the list\r\n\r\n if coord[1] <= first_letter[3]:\r\n line_i.append(coord)\r\n remove_idxs.append(i)\r\n\r\n # Sort and reverse the list to remove items going from the back of \r\n # the list to the front.\r\n remove_idxs.sort()\r\n remove_idxs.reverse()\r\n\r\n # Remove boxes in line 1 from unassigned_bb\r\n for i in remove_idxs:\r\n #print(i)\r\n unassigned_bb.pop(i)\r\n \r\n # Sort the bounding boxes by the lefthand coordinate (0) in \r\n # a data frame.\r\n line_df = pd.DataFrame(np.array(line_i))\r\n line_df = line_df.sort_values(by=0)\r\n\r\n if line_df.shape[0] < 1:\r\n continue\r\n \r\n # Get the coordinates that cover the whole line\r\n # - The smallest lefthand and top coordinates plus \r\n # the largest righthand and bottom coordinates\r\n whole_line_bb = (line_df.iloc[:,0].min(), line_df.iloc[:,1].min(),\r\n line_df.iloc[:,2].max(), line_df.iloc[:,3].max())\r\n whole_line_array = img[whole_line_bb[1]:whole_line_bb[3],\r\n whole_line_bb[0]:whole_line_bb[2]]\r\n line_word_starts = get_col_starts(whole_line_array, cutoff=255, \r\n window_width=40,lpad=0, \r\n use_row_midsection=True)\r\n line_word_starts.append(0)\r\n\r\n # Append the largest lower boundary coordinate (i.e. the lowest on the page)\r\n # so that the final stop_idx has a value\r\n line_word_starts.append(line_df.iloc[:,2].max())\r\n line_word_starts.sort()\r\n\r\n # Crop each word in each line and append to a list\r\n line_words = []\r\n for i in range(len(line_word_starts)-1):\r\n start_idx = line_word_starts[i]\r\n stop_idx = line_word_starts[i+1]\r\n line_word = tighten_img_crop(whole_line_array[:, start_idx:stop_idx-1])\r\n line_words.append(line_word)\r\n\r\n # Extract each letter from each word in each line and maintain sort\r\n # Data structure: [[A,l,a,n], [B,r,o,d,y]]\r\n \r\n line_words_letters = []\r\n for i in range(len(line_words)):\r\n word_i = line_words[i]\r\n contour_l = get_char_contours(img=word_i)\r\n bb_coord_l = make_bb_coord_l(contour_l=contour_l, img=word_i,\r\n IMG_HEIGHT=IMG_HEIGHT)\r\n bb_array = np.array(bb_coord_l)\r\n if bb_array.shape[0] < 1:\r\n continue\r\n bb_array=bb_array[np.where((abs(bb_array[:,0]-bb_array[:,2])*abs(bb_array[:,1]-bb_array[:,3])>= 900))]\r\n bb_array=pd.DataFrame(bb_array)\r\n bb_array=bb_array.sort_values(by=0)\r\n line_word_i_letters = []\r\n\r\n for i in range(bb_array.shape[0]):\r\n line_word_i_letters_i = resize_img_letter(\r\n letter_img=word_i[bb_array.iloc[i,1]:bb_array.iloc[i,3],\r\n bb_array.iloc[i,0]:bb_array.iloc[i,2]], \r\n img_height=IMG_HEIGHT, img_width=50) #fixed\r\n line_word_i_letters.append(line_word_i_letters_i)\r\n line_words_letters.append(line_word_i_letters)\r\n\r\n cropped_list = []\r\n\r\n # Crop each bounding box and append to list in the same order\r\n for i in range(line_df.shape[0]):\r\n bb = tuple(line_df.iloc[i,:])\r\n # Append a cropped image array to the list\r\n bb = crop_text(img=img, max_height=max_height, \r\n max_width=max_width, bb=bb)\r\n cropped_list.append(bb)\r\n\r\n key = 'line'+str(key_idx)\r\n line_dict.update({key:cropped_list})\r\n key2 = 'whole_line'+str(key_idx)\r\n line_dict.update({key2:whole_line_array})\r\n key3 = 'line_words'+str(key_idx)\r\n line_dict.update({key3:line_words})\r\n key4 = 'line_words_letters'+str(key_idx)\r\n line_dict.update({key4:line_words_letters})\r\n key_idx += 1\r\n\r\n return line_dict\r\n\r\ndef crop_text(img, max_height, max_width, bb):\r\n \"\"\"\r\n Take in one bounding box and a numpy array representing an images and \r\n crop the text within the bounding box to a maximum height \r\n \"\"\"\r\n bb_top, bb_bottom, bb_left, bb_right = bb[1], bb[3], bb[0], bb[2]\r\n bb_top = bb_bottom - max_height\r\n bb_right = bb_left + max_width\r\n if bb_top <= 0:\r\n bb_top = 0\r\n if bb_right >= img.shape[1]:\r\n bb_right = img.shape[1]\r\n \r\n crop_section = img[bb_top:bb_bottom, bb_left:bb_right]\r\n\r\n return crop_section\r\n\r\ndef extract_and_sort_chars(img, IMG_HEIGHT, IMG_WIDTH, dist_coords):\r\n \r\n \"\"\"\r\n Take in a row-col cell and return a dictionary where each key is a\r\n list of images, corresponding to the lines of text in the image.\r\n \"\"\"\r\n\r\n contour_l = get_char_contours(img=img)\r\n bb_coord_l = make_bb_coord_l(contour_l=contour_l, img=img, IMG_HEIGHT=IMG_HEIGHT)\r\n max_height = np.amin([char_max_height(bb_coords=bb_coord_l, IMG_HEIGHT=IMG_HEIGHT),\r\n IMG_HEIGHT])\r\n max_width = np.amin([char_max_width(bb_coords=bb_coord_l, IMG_WIDTH=IMG_WIDTH),\r\n IMG_WIDTH])\r\n sorted_bb_coords = sort_bb_coords(bb_coords=bb_coord_l, img=img, \r\n max_height=max_height, max_width=max_width, \r\n IMG_HEIGHT=IMG_HEIGHT,\r\n dist_coords=dist_coords)\r\n \r\n return sorted_bb_coords\r\n\r\ndef prep_extracted_img_for_pred(extracted_img, IMG_HEIGHT, IMG_WIDTH):\r\n array_from_img = tf.keras.preprocessing.image.img_to_array(extracted_img)\r\n array_from_img = np.array(Image.fromarray(extracted_img).convert('RGB'))\r\n array_from_img = tf.expand_dims(array_from_img, 0)\r\n\r\n array_from_img = tf.image.resize(array_from_img, size = [IMG_HEIGHT, IMG_WIDTH])\r\n \r\n return array_from_img\r\n\r\ndef assemble_pred_batch(img_list, IMG_HEIGHT, IMG_WIDTH):\r\n\r\n \"\"\"\r\n Take in a list of image arrays, convert them to the formate\r\n expected by the model, and makes a dataset from the list.\r\n \"\"\"\r\n\r\n batch_l = []\r\n\r\n for img_array in img_list:\r\n batch_l.append(prep_extracted_img_for_pred(\r\n extracted_img=img_array, IMG_HEIGHT=IMG_HEIGHT, IMG_WIDTH=IMG_WIDTH\r\n ))\r\n \r\n batch_dataset=tf.data.Dataset.from_tensor_slices(batch_l)\r\n\r\n return batch_dataset\r\n\r\ndef get_image_text(processed_imgs, IMG_HEIGHT, IMG_WIDTH, model, labels):\r\n\r\n \"\"\"\r\n Take in a list of processed images generated by extract_img_rows_and_cols.\r\n Return\r\n \"\"\"\r\n # Ensure that the model and the labels have the same number of outputs\r\n # Otherwise, they might be from separate experiments\r\n assert model.outputs[0].shape[1]==labels.shape[0]\r\n\r\n doc_text = []\r\n for sheet_idx, sheet in enumerate(processed_imgs):\r\n progress_msg = '\\rExtracting image text ('+str(sheet_idx+1)+'/'+str(len(processed_imgs))+')'\r\n sys.stdout.write(progress_msg)\r\n sys.stdout.flush()\r\n \r\n sheet_text = []\r\n for idx, row in enumerate(sheet):\r\n #print('len(sheet):')\r\n if idx==0:\r\n continue\r\n row_text = []\r\n for key, cell in row.items():\r\n #display(Image.fromarray(cell))\r\n if np.mean(cell) >= 254.0:\r\n continue\r\n key_text_l=[]\r\n cell_img = Image.fromarray(cell)\r\n #display(cell_img)\r\n if key == 'col2':\r\n dist_coords=(300,0)\r\n else:\r\n dist_coords=(0,0)\r\n\r\n sorted_text_img = extract_and_sort_chars(\r\n img=cell, IMG_HEIGHT=IMG_HEIGHT, IMG_WIDTH=IMG_WIDTH, \r\n dist_coords=dist_coords\r\n )\r\n keys_df=pd.DataFrame({'key':list(sorted_text_img.keys())})\r\n keys_df=keys_df.loc[keys_df.key.str.match(pat='line_words_letters\\d')]\r\n #print(keys_df)\r\n \r\n for k in keys_df.key:\r\n #print(k)\r\n line_words_img_l = sorted_text_img.get(k)\r\n #print(len(line_words_img_l))\r\n line_words_txt_l = []\r\n for w in range(len(line_words_img_l)):\r\n word_img_l = line_words_img_l[w]\r\n letters_txt_l = []\r\n word_img_batch = assemble_pred_batch(word_img_l, IMG_HEIGHT=IMG_HEIGHT, IMG_WIDTH=IMG_WIDTH)\r\n if len(word_img_batch) == 0:\r\n continue\r\n preds = model.predict(word_img_batch)\r\n scores = tf.nn.softmax(preds)\r\n pred_labels=labels.class_names.str.extract('(\\w$)').loc[np.argmax(scores, axis=1)]\r\n pred_concat=''.join(list((pred_labels.iloc[:,0])))\r\n line_words_txt_l.append(pred_concat)\r\n key_text_l.append(line_words_txt_l)\r\n row_text.append(key_text_l)\r\n sheet_text.append(row_text)\r\n doc_text.append(sheet_text)\r\n return doc_text\r\n\r\ndef reorganize_doc_text(doc_text):\r\n col_list = []\r\n for sheet in doc_text:\r\n for row in sheet:\r\n row_dict = {}\r\n for c in range(len(row)):\r\n col = row[c]\r\n # col0: Name and Address of Last Reputed Owner\r\n n_lines = len(col)\r\n if c == 0 and n_lines > 1:\r\n col0={}\r\n # Determine if there is a address in this column or if there\r\n # are only owner names\r\n city_state_zip_idx = None\r\n \r\n for i, line in enumerate(col):\r\n concat_line = ' '.join(line)\r\n if re.search('\\w{2}\\s+\\w{5}$', concat_line)!=None:\r\n city_state_zip_idx = i\r\n \r\n # If there is an address line, extract the components\r\n if city_state_zip_idx != None:\r\n city_state_zip = col[city_state_zip_idx].copy()\r\n city_state_zip_full = ' '.join(col[city_state_zip_idx].copy())\r\n state_zip_set = set()\r\n for word_i in city_state_zip:\r\n if re.search(pattern='(\\w{5}$)', string=word_i)!=None:\r\n col0.update({'owner_zip':word_i})\r\n state_zip_set.add(word_i)\r\n elif re.search(pattern='^\\w{2}$', string=word_i)!=None:\r\n col0.update({'owner_state':word_i})\r\n state_zip_set.add(word_i)\r\n\r\n # Assume anything else in this line is the city\r\n city = []\r\n for i in city_state_zip:\r\n if 'owner_state' and 'owner_zip' in col0.keys() and i not in [col0.get('owner_state'),col0.get('owner_zip')]:\r\n city.append(i) \r\n col0.update({'owner_city':' '.join(city)})\r\n # Assume the line immediately above is the street address\r\n col0.update({'owner_street_addr':' '.join(col[city_state_zip_idx-1])})\r\n owner_line_end = city_state_zip_idx-1\r\n else: \r\n owner_line_end=len(col)\r\n \r\n for i, owner in enumerate(col[0:owner_line_end]):\r\n key = 'owner_name'+str(i+1) \r\n val = ' '.join(owner)\r\n col0.update({key:val}) \r\n row_dict.update({'col0':col0})\r\n # col1: County tax map, address, and account identifier\r\n if c == 1 and n_lines > 1:\r\n col1={}\r\n \r\n for i, line in enumerate(col):\r\n concat_line = ' '.join(line)\r\n if re.search(pattern='ITEM\\s+NO', string=concat_line, flags=re.IGNORECASE)!=None:\r\n item_no_idx = i\r\n col1.update({'item_no': re.findall(pattern = '\\w+$', string = concat_line)[0]})\r\n if re.search(pattern='\\w{6}\\s+\\w{16}', string=concat_line)!=None:\r\n account_idx = i\r\n col1.update({'account': concat_line})\r\n if re.search(pattern='TAX\\s+CODE', string=concat_line, flags=re.IGNORECASE)!=None:\r\n tax_code_idx = i\r\n addr_l = []\r\n for i, line in enumerate(col):\r\n concat_line = ' '.join(line)\r\n if i not in [item_no_idx, account_idx, tax_code_idx]:\r\n addr_l.append(concat_line)\r\n addr = ' '.join(addr_l)\r\n col1.update({'property_addr':addr})\r\n row_dict.update({'col1':col1})\r\n \r\n # col2: Assessed land/Assessed total/market value\r\n if c == 2 and n_lines > 1:\r\n col2={}\r\n for i, line in enumerate(col):\r\n concat_line = ' '.join(line)\r\n if i == 0:\r\n col2.update({'assessed_land':concat_line})\r\n if i == 1:\r\n col2.update({'assessed_total':concat_line})\r\n if i == 2:\r\n col2.update({'total_market_value':concat_line})\r\n if re.search(pattern='^SCH', string=concat_line)!=None:\r\n col2.update({'school_no': re.findall(pattern = '\\w+$', string = concat_line)[0]})\r\n if re.search(pattern='^CLASS', string=concat_line)!=None:\r\n col2.update({'class_no': re.findall(pattern = '\\w+$', string = concat_line)[0]})\r\n if re.search(pattern='^ACRES', string=concat_line)!=None:\r\n col2.update({'acres': re.findall(pattern = '\\w+$', string = concat_line)[0]})\r\n row_dict.update({'col2':col2})\r\n \r\n # col5: Net taxable\r\n if c == 5 and n_lines > 1:\r\n col5={}\r\n for i, line in enumerate(col):\r\n concat_line = ' '.join(line)\r\n if re.search(pattern='^County', string=concat_line, flags=re.IGNORECASE)!=None:\r\n col5.update({'net_taxable_county':re.findall(pattern = '\\w+$', string = concat_line)[0]})\r\n elif re.search(pattern='^Town', string=concat_line, flags=re.IGNORECASE)!=None:\r\n col5.update({'net_taxable_town':re.findall(pattern = '\\w+$', string = concat_line)[0]}) \r\n else:\r\n col5.update({'net_taxable_school':re.findall(pattern = '\\w+$', string = concat_line)[0]})\r\n row_dict.update({'col5':col5})\r\n\r\n col_list.append(row_dict)\r\n return col_list\r\n\r\ndef doc_text_to_dataframe(reorganized_doc_text):\r\n flat_df_l = []\r\n for i, row in enumerate(reorganized_doc_text):\r\n flat_col_l = []\r\n for key, col in row.items():\r\n df = pd.DataFrame(col, index=[0])\r\n flat_col_l.append(df)\r\n if len(flat_col_l)>=1:\r\n flat_df = pd.concat(flat_col_l, axis=1)\r\n flat_df_l.append(flat_df)\r\n combined_df = pd.concat(flat_df_l, axis=0, ignore_index=True)\r\n combined_df=combined_df[['owner_name1','owner_name2',\r\n 'owner_name3','owner_name4',\r\n 'owner_street_addr','owner_city',\r\n 'owner_state','owner_zip',\r\n 'account','item_no','property_addr',\r\n 'assessed_land','assessed_total','total_market_value',\r\n 'school_no','class_no','acres',\r\n 'net_taxable_county','net_taxable_town',\r\n 'net_taxable_school']]\r\n return combined_df\r\n"
] |
[
[
"numpy.amax",
"pandas.DataFrame",
"numpy.max",
"numpy.mean",
"numpy.argmin",
"numpy.reshape",
"numpy.full",
"numpy.ceil",
"numpy.argmax",
"tensorflow.keras.preprocessing.image.img_to_array",
"pandas.concat",
"numpy.min",
"numpy.amin",
"numpy.median",
"numpy.append",
"numpy.floor",
"numpy.array",
"tensorflow.nn.softmax",
"numpy.abs",
"numpy.ediff1d",
"tensorflow.data.Dataset.from_tensor_slices",
"tensorflow.expand_dims",
"tensorflow.image.resize"
]
] |
dmitry-s-danilov/kaggle-customer-churn-prediction-2020
|
[
"e7ada73a6f413d7de9bfd18fa2af7e74aa9f6bc3"
] |
[
"src/models/level_1/transformer.py"
] |
[
"from sklearn.compose import ColumnTransformer\nfrom sklearn.preprocessing import MinMaxScaler, OneHotEncoder\n\ntransformer = ColumnTransformer(\n [\n # Numeric columns - minmax scaler.\n (\n 'minmax_scaler',\n MinMaxScaler(),\n [\n 'account_length',\n 'number_vmail_messages',\n 'number_customer_service_calls',\n\n 'total_day_calls',\n 'total_eve_calls',\n 'total_night_calls',\n 'total_intl_calls',\n\n 'total_day_minutes',\n 'total_eve_minutes',\n 'total_night_minutes',\n 'total_intl_minutes',\n\n 'total_day_charge',\n 'total_eve_charge',\n 'total_night_charge',\n 'total_intl_charge',\n ]\n ),\n\n # Binary columns - label binarizer.\n (\n 'label_binarizer',\n OneHotEncoder(\n categories=[\n ['no', 'yes'],\n ['no', 'yes'],\n ],\n drop='if_binary',\n dtype=int\n ),\n [\n 'international_plan',\n 'voice_mail_plan',\n ]\n ),\n\n # Categorical columns - dummy encoder.\n (\n 'dummy_encoder',\n OneHotEncoder(dtype=int),\n [\n 'area_code',\n 'state',\n ]\n ),\n ]\n)\n"
] |
[
[
"sklearn.preprocessing.OneHotEncoder",
"sklearn.preprocessing.MinMaxScaler"
]
] |
ClaudiuCreanga/kaggle
|
[
"49ed31cd12040a7996611d9aa5379acfb61c0192"
] |
[
"tensorflow/tensorboard/mnist_with_summaries.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\"\"\"A simple MNIST classifier which displays summaries in TensorBoard.\n\nThis is an unimpressive MNIST model, but it is a good example of using\ntf.name_scope to make a graph legible in the TensorBoard graph explorer, and of\nnaming summary tags so that they are grouped meaningfully in TensorBoard.\n\nIt demonstrates the functionality of every TensorBoard dashboard.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport os\nimport sys\n\nimport tensorflow as tf\n\nfrom tensorflow.examples.tutorials.mnist import input_data\n\nFLAGS = None\n\n\ndef train():\n # Import data\n mnist = input_data.read_data_sets(FLAGS.data_dir,\n fake_data=FLAGS.fake_data)\n\n sess = tf.InteractiveSession()\n # Create a multilayer model.\n\n # Input placeholders\n with tf.name_scope('input'):\n x = tf.placeholder(tf.float32, [None, 784], name='x-input')\n y_ = tf.placeholder(tf.int64, [None], name='y-input')\n\n with tf.name_scope('input_reshape'):\n image_shaped_input = tf.reshape(x, [-1, 28, 28, 1])\n tf.summary.image('input', image_shaped_input, 10)\n\n # We can't initialize these variables to 0 - the network will get stuck.\n def weight_variable(shape):\n \"\"\"Create a weight variable with appropriate initialization.\"\"\"\n initial = tf.truncated_normal(shape, stddev=0.1)\n return tf.Variable(initial)\n\n def bias_variable(shape):\n \"\"\"Create a bias variable with appropriate initialization.\"\"\"\n initial = tf.constant(0.1, shape=shape)\n return tf.Variable(initial)\n\n def variable_summaries(var):\n \"\"\"Attach a lot of summaries to a Tensor (for TensorBoard visualization).\"\"\"\n with tf.name_scope('summaries'):\n mean = tf.reduce_mean(var)\n tf.summary.scalar('mean', mean)\n with tf.name_scope('stddev'):\n stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))\n tf.summary.scalar('stddev', stddev)\n tf.summary.scalar('max', tf.reduce_max(var))\n tf.summary.scalar('min', tf.reduce_min(var))\n tf.summary.histogram('histogram', var)\n\n def nn_layer(input_tensor, input_dim, output_dim, layer_name, act=tf.nn.relu):\n \"\"\"Reusable code for making a simple neural net layer.\n\n It does a matrix multiply, bias add, and then uses ReLU to nonlinearize.\n It also sets up name scoping so that the resultant graph is easy to read,\n and adds a number of summary ops.\n \"\"\"\n # Adding a name scope ensures logical grouping of the layers in the graph.\n with tf.name_scope(layer_name):\n # This Variable will hold the state of the weights for the layer\n with tf.name_scope('weights'):\n weights = weight_variable([input_dim, output_dim])\n variable_summaries(weights)\n with tf.name_scope('biases'):\n biases = bias_variable([output_dim])\n variable_summaries(biases)\n with tf.name_scope('Wx_plus_b'):\n preactivate = tf.matmul(input_tensor, weights) + biases\n tf.summary.histogram('pre_activations', preactivate)\n activations = act(preactivate, name='activation')\n tf.summary.histogram('activations', activations)\n return activations\n\n hidden1 = nn_layer(x, 784, 500, 'layer1')\n\n with tf.name_scope('dropout'):\n keep_prob = tf.placeholder(tf.float32)\n tf.summary.scalar('dropout_keep_probability', keep_prob)\n dropped = tf.nn.dropout(hidden1, keep_prob)\n\n # Do not apply softmax activation yet, see below.\n y = nn_layer(dropped, 500, 10, 'layer2', act=tf.identity)\n\n with tf.name_scope('cross_entropy'):\n # The raw formulation of cross-entropy,\n #\n # tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(tf.softmax(y)),\n # reduction_indices=[1]))\n #\n # can be numerically unstable.\n #\n # So here we use tf.losses.sparse_softmax_cross_entropy on the\n # raw logit outputs of the nn_layer above, and then average across\n # the batch.\n with tf.name_scope('total'):\n cross_entropy = tf.losses.sparse_softmax_cross_entropy(\n labels=y_, logits=y)\n tf.summary.scalar('cross_entropy', cross_entropy)\n\n with tf.name_scope('train'):\n train_step = tf.train.AdamOptimizer(FLAGS.learning_rate).minimize(\n cross_entropy)\n\n with tf.name_scope('accuracy'):\n with tf.name_scope('correct_prediction'):\n correct_prediction = tf.equal(tf.argmax(y, 1), y_)\n with tf.name_scope('accuracy'):\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n tf.summary.scalar('accuracy', accuracy)\n\n # Merge all the summaries and write them out to\n # /tmp/tensorflow/mnist/logs/mnist_with_summaries (by default)\n merged = tf.summary.merge_all()\n train_writer = tf.summary.FileWriter(FLAGS.log_dir + '/train', sess.graph)\n test_writer = tf.summary.FileWriter(FLAGS.log_dir + '/test')\n tf.global_variables_initializer().run()\n\n # Train the model, and also write summaries.\n # Every 10th step, measure test-set accuracy, and write test summaries\n # All other steps, run train_step on training data, & add training summaries\n\n def feed_dict(train):\n \"\"\"Make a TensorFlow feed_dict: maps data onto Tensor placeholders.\"\"\"\n if train or FLAGS.fake_data:\n xs, ys = mnist.train.next_batch(100, fake_data=FLAGS.fake_data)\n k = FLAGS.dropout\n else:\n xs, ys = mnist.test.images, mnist.test.labels\n k = 1.0\n return {x: xs, y_: ys, keep_prob: k}\n\n for i in range(FLAGS.max_steps):\n if i % 10 == 0: # Record summaries and test-set accuracy\n summary, acc = sess.run([merged, accuracy], feed_dict=feed_dict(False))\n test_writer.add_summary(summary, i)\n print('Accuracy at step %s: %s' % (i, acc))\n else: # Record train set summaries, and train\n if i % 100 == 99: # Record execution stats\n run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)\n run_metadata = tf.RunMetadata()\n summary, _ = sess.run([merged, train_step],\n feed_dict=feed_dict(True),\n options=run_options,\n run_metadata=run_metadata)\n train_writer.add_run_metadata(run_metadata, 'step%03d' % i)\n train_writer.add_summary(summary, i)\n print('Adding run metadata for', i)\n else: # Record a summary\n summary, _ = sess.run([merged, train_step], feed_dict=feed_dict(True))\n train_writer.add_summary(summary, i)\n train_writer.close()\n test_writer.close()\n\n\ndef main(_):\n if tf.gfile.Exists(FLAGS.log_dir):\n tf.gfile.DeleteRecursively(FLAGS.log_dir)\n tf.gfile.MakeDirs(FLAGS.log_dir)\n train()\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--fake_data', nargs='?', const=True, type=bool,\n default=False,\n help='If true, uses fake data for unit testing.')\n parser.add_argument('--max_steps', type=int, default=1000,\n help='Number of steps to run trainer.')\n parser.add_argument('--learning_rate', type=float, default=0.001,\n help='Initial learning rate')\n parser.add_argument('--dropout', type=float, default=0.9,\n help='Keep probability for training dropout.')\n parser.add_argument(\n '--data_dir',\n type=str,\n default=os.path.join(os.getenv('TEST_TMPDIR', '/tmp'),\n 'tensorflow/mnist/input_data'),\n help='Directory for storing input data')\n parser.add_argument(\n '--log_dir',\n type=str,\n default=os.path.join(os.getenv('TEST_TMPDIR', '/tmp'),\n 'tensorflow/mnist/logs/mnist_with_summaries'),\n help='Summaries log directory')\n FLAGS, unparsed = parser.parse_known_args()\n tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)"
] |
[
[
"tensorflow.gfile.DeleteRecursively",
"tensorflow.gfile.Exists",
"tensorflow.RunMetadata",
"tensorflow.cast",
"tensorflow.gfile.MakeDirs",
"tensorflow.train.AdamOptimizer",
"tensorflow.summary.scalar",
"tensorflow.Variable",
"tensorflow.summary.image",
"tensorflow.name_scope",
"tensorflow.square",
"tensorflow.argmax",
"tensorflow.examples.tutorials.mnist.input_data.read_data_sets",
"tensorflow.nn.dropout",
"tensorflow.app.run",
"tensorflow.matmul",
"tensorflow.truncated_normal",
"tensorflow.InteractiveSession",
"tensorflow.losses.sparse_softmax_cross_entropy",
"tensorflow.RunOptions",
"tensorflow.placeholder",
"tensorflow.global_variables_initializer",
"tensorflow.summary.merge_all",
"tensorflow.summary.histogram",
"tensorflow.reduce_max",
"tensorflow.summary.FileWriter",
"tensorflow.constant",
"tensorflow.reduce_mean",
"tensorflow.reshape",
"tensorflow.reduce_min"
]
] |
OmneyaEssam/iti_ds_live
|
[
"78f004dff6dea6c0b08d4c14733273ae98d69643"
] |
[
"scripts/JobPrediction.py"
] |
[
"LOG_DATA_PKL = \"data.pkl\"\nLOG_MODEL_PKL = \"model.pkl\"\n\n#-------------------------------------------------------------\n\nimport os \nimport sklearn\nimport pickle\nimport yaml\n\nimport pandas as pd\n\nimport mlflow\nfrom mlflow.tracking import MlflowClient\n\n#-------------------------------------------------------------\n\n\nclass JobPrediction:\n \"\"\"Production Class for predicting the probability of a job from skills\"\"\"\n # Class attributes \n path_clusters_config = None\n skills_clusters_df = None\n \n tracking_uri = None\n experiment_id = None\n run_id = None\n \n model = None\n all_features = None \n all_jobs = None \n \n # Constructor\n def __init__(self, tracking_uri, experiment_id, run_id, clusters_yaml_path):\n # Store variables\n self.tracking_uri = tracking_uri\n self.experiment_id = experiment_id\n self.run_id = run_id\n \n # Retrieve model and features\n mlflow_objs = self.load_mlflow_objs(tracking_uri, \n experiment_id, \n run_id)\n self.model = mlflow_objs[0]\n self.all_features = mlflow_objs[1]\n self.all_jobs = mlflow_objs[2]\n \n # Load clusters config \n self.path_clusters_config = clusters_yaml_path\n self.skills_clusters_df = self.load_clusters_config(clusters_yaml_path)\n \n # -------------------------------------------\n \n # Constructor helper functions \n \n def load_mlflow_objs(self, tracking_uri, experiment_id, run_id):\n \"\"\"Load objects from the MLflow run\"\"\"\n \n # Get artifact path\n artifact_path = os.path.join(tracking_uri.replace(\"file://\", \"\"), \n experiment_id, \n run_id, \n 'artifacts')\n \n # Load data pkl\n data_path = os.path.join(artifact_path, LOG_DATA_PKL)\n with open(data_path, 'rb') as handle:\n data_pkl = pickle.load(handle)\n \n # Load model pkl\n model_path = os.path.join(artifact_path, LOG_MODEL_PKL)\n with open(model_path, 'rb') as handle:\n model_pkl = pickle.load(handle)\n\n # Return model and data labels \n return model_pkl[\"model_object\"], data_pkl[\"features_names\"], data_pkl[\"targets_names\"]\n \n \n def load_clusters_config(self, path_clusters_config):\n \"\"\"Load skills clusters developed in 03_feature_engineering.ipynb\"\"\"\n \n # Read YAML\n with open(path_clusters_config, \"r\") as stream:\n clusters_config = yaml.safe_load(stream)\n \n # Format into dataframe\n clusters_df = [(cluster_name, cluster_skill)\n for cluster_name, cluster_skills in clusters_config.items()\n for cluster_skill in cluster_skills]\n \n clusters_df = pd.DataFrame(clusters_df, \n columns=[\"cluster_name\", \"skill\"])\n return clusters_df\n\n \n # ========================================================\n # ************** Prediction Functions ************** \n # ========================================================\n \n def create_features_array(self, available_skills):\n \"\"\"Create the features array from a list of the available skills\"\"\"\n \n # Method's helper functions \n def create_clusters_features(self, available_skills):\n sample_clusters = self.skills_clusters_df.copy()\n sample_clusters[\"available_skills\"] = sample_clusters[\"skill\"].isin(available_skills)\n cluster_features = sample_clusters.groupby(\"cluster_name\")[\"available_skills\"].sum()\n return cluster_features\n \n def create_skills_features(self, available_skills, exclude_features):\n all_features = pd.Series(self.all_features.copy())\n skills_names = all_features[~all_features.isin(exclude_features)]\n ohe_skills = pd.Series(skills_names.isin(available_skills).astype(int).tolist(), \n index=skills_names)\n return ohe_skills\n \n # -------------------------\n \n # Method's main\n clusters_features = create_clusters_features(self, available_skills)\n skills_features = create_skills_features(self, available_skills, \n exclude_features=clusters_features.index)\n # ... Combine features and sort \n features = pd.concat([skills_features, clusters_features])\n features = features[self.all_features]\n return features.values \n \n \n def predict_jobs_probabilities(self, available_skills):\n '''Returns probabilities of the different jobs according to the skills'''\n # Create features array \n features_array = self.create_features_array(available_skills)\n \n # Predict and format\n predictions = self.model.predict_proba([features_array])\n predictions = [prob[0][1] for prob in predictions] # Keep positive probs \n predictions = pd.Series(predictions, index=self.all_jobs)\n \n return predictions\n\n \n # ==============================================================\n "
] |
[
[
"pandas.concat",
"pandas.Series",
"pandas.DataFrame"
]
] |
rfriedman22/selene
|
[
"a972fbf650664b8d955bb54e1737484131895b09"
] |
[
"selene_sdk/interpret/vis.py"
] |
[
"\"\"\"\nThis module provides the methods for visualizing different ouputs\nfrom selene analysis methods.\n\n\"\"\"\nfrom collections import defaultdict\nfrom copy import deepcopy\nimport os\nimport re\nimport warnings\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import transforms\nfrom matplotlib.path import Path\nfrom matplotlib.patches import PathPatch\nimport matplotlib.patheffects\nfrom matplotlib.text import TextPath\nimport pkg_resources\nfrom plotly.offline import download_plotlyjs, plot\nimport plotly.graph_objs as go\nimport seaborn as sns\nimport tabix\n\nfrom ..sequences import Genome\n\n\n_SVG_PATHS = {'T': \"M 0,100 l 100, 0 l 0,-25 l -37.5, 0 l 0,-75 l -25, 0 \" +\n \"l 0,75 l -37.5,0 l 0,25 z\",\n 'C': (\"M 100,12.5 l 0,25 c 0,0 -25,-15 -50,-12.5 \" +\n \"c 0,0 -25,0 -25,25 c 0,0 0,25 25,25 c 0,0 25,2.5 50,-15\" +\n \" l 0, 25 C 100,87.5 75,100 50,100 C 50,100 0,100 0,50 \" +\n \"C 0,50 0,0 50,0 C 50,0 75,0 100,12.5 z\"),\n 'G': (\"M 100,12.5 l 0,25 c 0,0 -25,-15 -50,-12.5 \" +\n \"c 0,0 -25,0 -25,25 c 0,0 0,25 25,25 c 0,0 25,2.5 50,-15\" +\n \" l 0, 25 C 100,87.5 75,100 50,100 C 50,100 0,100 0,50 \" +\n \"C 0,50 0,0 50,0 C 50,0 75,0 100,12.5 M 100,37.5 \" +\n \"l 0,17.5 l -50,0 l 0,-17 l 25,0 l 0,-25 l 25,0 z\"),\n 'A': (\"M 0,0 l 37.5,100 l 25,0 l 37.5,-100 l -25,0 l -9.375,25\" +\n \" l -31.25,0 l -9.375,-25 l -25,0 z 0,0 M 43.75, 50 \" +\n \"l 12.5,0 l -5.859375,15.625 l -5.859375,-15.625 z\"),\n 'U': (\"M 0,100 l 25,0 l 0,-50 C 25,50 25,25 50,25\" +\n \" C 50,25 75,25 75,50 l 0,50 l 25,0 L 100,50 \" +\n \"C 100,50 100,0, 50,0 C 50,0 0,0 0,50 l 0,50 z\")}\n\n\ndef _svg_parse(path_string):\n \"\"\"Functionality for parsing a string from source vector graphics.\n\n Source is from `matplotlib.org/2.1.1/gallery/showcase/firefox.html`\n with minor modifications.\n\n Parameters\n ----------\n path_string : str\n String containing the path code from an SVG file.\n\n Returns\n -------\n list(numpy.uint8), numpy.ndarray, dtype=np.float32\n A 2-tuple containing code types and coordinates for a matplotlib\n path.\n\n \"\"\"\n commands = {'M': (Path.MOVETO,),\n 'L': (Path.LINETO,),\n 'Q': (Path.CURVE3,)*2,\n 'C': (Path.CURVE4,)*3,\n 'Z': (Path.CLOSEPOLY,)}\n path_re = re.compile(r'([MLHVCSQTAZ])([^MLHVCSQTAZ]+)', re.IGNORECASE)\n float_re = re.compile(r'(?:[\\s,]*)([+-]?\\d+(?:\\.\\d+)?)')\n vertices = []\n codes = []\n last = (0, 0)\n for cmd, values in path_re.findall(path_string):\n points = [float(v) for v in float_re.findall(values)]\n points = np.array(points).reshape((len(points)//2, 2))\n if cmd.islower():\n points += last\n cmd = cmd.capitalize()\n if len(points) > 0:\n last = points[-1]\n codes.extend(commands[cmd])\n vertices.extend(points.tolist())\n return np.array(vertices), codes\n\n\nfor k in _SVG_PATHS.keys():\n _SVG_PATHS[k] = _svg_parse(_SVG_PATHS[k])\n\n\nclass _TextPathRenderingEffect(matplotlib.patheffects.AbstractPathEffect):\n \"\"\"This class provides an effect for continuously rendering a text\n path over another path.\n\n \"\"\"\n def __init__(self, bar, x_translation=0., y_translation=0.,\n x_scale=1., y_scale=1.):\n \"\"\"This is a class for re-rendering text paths and preserving\n their scale.\n\n Parameters\n ----------\n bar : matplotlib.patches.Patch\n The patch where the letter is.\n x_translation : float, optional\n Default is 0. Amount by which to translate the x coordinate.\n y_translation : float, optional\n Default is 0. Amount by which to translate the y coordinate.\n x_scale : float, optional\n Default is 1. Amount by which to scale the width.\n y_scale : float, optional\n Default is 1. Amount by which to scale the height.\n\n \"\"\"\n self._bar = bar\n self._x_translation = x_translation\n self._y_translation = y_translation\n self._x_scale = x_scale\n self._y_scale = y_scale\n\n def draw_path(self, renderer, gc, tpath, affine, rgbFace=None):\n \"\"\"Redraws the path.\n\n \"\"\"\n b_x, b_y, b_w, b_h = self._bar.get_extents().bounds\n t_x, t_y, t_w, t_h = tpath.get_extents().bounds\n translation = [b_x - t_x, b_y - t_y]\n translation[0] += self._x_translation\n translation[1] += self._y_translation\n scale = [b_w / t_w, b_h / t_h]\n scale[0] *= self._x_scale\n scale[1] *= self._y_scale\n affine = affine.identity().scale(*scale).translate(*translation)\n renderer.draw_path(gc, tpath, affine, rgbFace)\n\n\ndef sequence_logo(score_matrix, order=\"value\", width=1.0, ax=None,\n sequence_type=Genome, font_properties=None,\n color_scheme=None,\n **kwargs):\n \"\"\"Plots a sequence logo for visualizing motifs.\n\n Parameters\n ----------\n score_matrix : np.ndarray\n An :math:`L \\\\times N` array (where :math:`L` is the length of\n the sequence, and :math:`N` is the size of the alphabet)\n containing the scores for each base occuring at each position.\n order : {'alpha', 'value'}\n The manner by which to sort the bases stacked at each position\n in the sequence logo plot.\n\n * 'alpha' - Bases go in the order they are found in the\\\n sequence alphabet.\n * 'value' - Bases go in the order of their value, with the\\\n largest at the bottom.\n width : float, optional\n Default is 1. The width of each character in the plotted logo.\n A value of 1 will mean that there is no gap between each the\n characters at each position. A value of 0 will not draw any\n characters.\n ax : matplotlib.pyplot.Axes or None, optional\n Default is `None`. The axes to plot on. If left as `None`, a new\n axis will be created.\n sequence_type : class, optional\n Default is `selene_sdk.sequences.Genome`. The type of sequence that\n the *in silico* mutagenesis results are associated with. This\n should generally be a subclass of `selene_sdk.sequences.Sequence`.\n font_properties : matplotlib.font_manager.FontProperties or None, optional\n Default is `None`. A `matplotlib.font_manager.FontProperties`\n object that specifies the properties of the font to use for\n plotting the motif. If `None`, no font will be used, and the\n text will be rendered by a path. This method of rendering paths\n is preferred, as it ensures all character heights correspond to\n the actual values, and that there are no extra gaps between\n the tops and bottoms of characters at each position in the\n sequence logo. If the user opts to use a value other\n than `None`, then no such guarantee can be made.\n color_scheme : list(str) or None, optional\n Default is `None`. A list containing the hex codes or names of\n colors to use, appearing in the order of the bases of the\n sequence type. If left as `None`, a default palette will be made\n with `seaborn.color_palette`, and will have as many\n colors as there are characters in the input sequence alphabet.\n\n Returns\n -------\n matplotlib.pyplot.Axes\n The axes containing the sequence logo plot.\n\n Raises\n ------\n ValueError\n If the number of columns in `score_matrix` does not match the\n number of characters in the alphabet of `sequence_type`.\n\n ValueError\n If the number of colors in `color_palette` does not match the\n number of characters in the alphabet of `sequence_type`.\n\n Examples\n --------\n We have included an example of the output from a `sequence_logo`\n plot below:\n\n .. image:: ../../docs/source/_static/img/sequence_logo_example.png\n\n \"\"\"\n # Note that everything will break if we do not deepcopy.\n score_matrix = deepcopy(score_matrix)\n\n score_matrix = score_matrix.transpose()\n if font_properties is not None:\n warnings.warn(\n \"Specifying a value for `font_properties` (other than `None`) \"\n \"will use the `matplotlib`-based character paths, and causes \"\n \"distortions in the plotted motif. We recommend leaving \"\n \"`font_properties=None`. See the documentation for details.\",\n UserWarning)\n\n if color_scheme is None:\n color_scheme = sns.color_palette(\"Set1\",\n n_colors=len(sequence_type.BASES_ARR))\n color_scheme = color_scheme.as_hex()\n if len(color_scheme) < len(sequence_type.BASES_ARR):\n raise ValueError(\n \"Color scheme is shorter than number of bases in sequence.\")\n\n if score_matrix.shape[0] != len(sequence_type.BASES_ARR):\n raise ValueError(\n \"Got score with {0} bases for sequence with {1} bases.\".format(\n score_matrix.shape[0], len(sequence_type.BASES_ARR)))\n if ax is None:\n _, ax = plt.subplots(figsize=score_matrix.shape)\n\n # Determine offsets depending on sort order.\n positive_offsets = np.zeros_like(score_matrix)\n negative_offsets = np.zeros_like(score_matrix)\n bases = np.empty(score_matrix.shape, dtype=object)\n bases[:, :] = \"?\" # This ensures blanks are visually obvious.\n\n # Change ordering of things based on input arguments.\n if order == \"alpha\":\n for i in range(score_matrix.shape[0]):\n bases[i, :] = np.array(sequence_type.BASES_ARR)[i]\n\n elif order == \"value\":\n if np.sum(score_matrix < 0) != 0:\n sorted_scores = np.zeros_like(score_matrix)\n for j in range(score_matrix.shape[1]):\n # Sort the negative values and put them at bottom.\n div = np.sum(score_matrix[:, j] < 0.)\n negative_idx = np.argwhere(score_matrix[:, j] < 0.).flatten()\n negative_sort_idx = np.argsort(score_matrix[negative_idx, j],\n axis=None)\n sorted_scores[:div, j] = score_matrix[\n negative_idx[negative_sort_idx], j]\n bases[:div, j] = np.array(sequence_type.BASES_ARR)[\n negative_idx[negative_sort_idx]].flatten()\n\n # Sort the positive values and stack atop the negatives.\n positive_idx = np.argwhere(score_matrix[:, j] >= 0.).flatten()\n positive_sort_idx = np.argsort(score_matrix[positive_idx, j],\n axis=None)\n sorted_scores[div:, j] = score_matrix[\n positive_idx[positive_sort_idx], j]\n bases[div:, j] = np.array(sequence_type.BASES_ARR)[\n positive_idx[positive_sort_idx]].flatten()\n score_matrix = sorted_scores\n else:\n for j in range(score_matrix.shape[1]):\n sort_idx = np.argsort(score_matrix[:, j], axis=None)[::-1]\n bases[:, j] = np.array(sequence_type.BASES_ARR)[sort_idx]\n score_matrix[:, j] = score_matrix[sort_idx, j]\n\n # Create offsets for each bar.\n for i in range(score_matrix.shape[0] - 1):\n y_coords = score_matrix[i, :]\n if i > 0:\n negative_offsets[i + 1, :] = negative_offsets[i, :]\n positive_offsets[i + 1, :] = positive_offsets[i, :]\n neg_idx = np.argwhere(y_coords < 0.)\n pos_idx = np.argwhere(y_coords >= 0.)\n negative_offsets[i + 1, neg_idx] += y_coords[neg_idx]\n positive_offsets[i + 1, pos_idx] += y_coords[pos_idx]\n\n for i in range(score_matrix.shape[0]):\n x_coords = np.arange(score_matrix.shape[1]) + 0.5\n y_coords = score_matrix[i, :]\n\n # Manage negatives and positives separately.\n offsets = np.zeros(score_matrix.shape[1])\n negative_idx = np.argwhere(y_coords < 0.)\n positive_idx = np.argwhere(y_coords >= 0.)\n offsets[negative_idx] = negative_offsets[i, negative_idx]\n offsets[positive_idx] = positive_offsets[i, positive_idx]\n bars = ax.bar(x_coords, y_coords, color=\"black\", width=width,\n bottom=offsets)\n for j, bar in enumerate(bars):\n base = bases[i, j]\n bar.set_color(color_scheme[sequence_type.BASE_TO_INDEX[base]])\n bar.set_edgecolor(None)\n\n # Iterate over the barplot's bars and turn them into letters.\n new_patches = []\n for i, bar in enumerate(ax.patches):\n base_idx = i // score_matrix.shape[1]\n seq_idx = i % score_matrix.shape[1]\n base = bases[base_idx, seq_idx]\n # We construct a text path that tracks the bars in the barplot.\n # Thus, the barplot takes care of scaling and translation,\n # and we just copy it.\n if font_properties is None:\n text = Path(_SVG_PATHS[base][0], _SVG_PATHS[base][1])\n else:\n text = TextPath((0., 0.), base, fontproperties=font_properties)\n b_x, b_y, b_w, b_h = bar.get_extents().bounds\n t_x, t_y, t_w, t_h = text.get_extents().bounds\n scale = (b_w / t_w, b_h / t_h)\n translation = (b_x - t_x, b_y - t_y)\n text = PathPatch(text, facecolor=bar.get_facecolor(), lw=0.)\n bar.set_facecolor(\"none\")\n text.set_path_effects([_TextPathRenderingEffect(bar)])\n transform = transforms.Affine2D().translate(*translation).scale(*scale)\n text.set_transform(transform)\n new_patches.append(text)\n\n for patch in new_patches:\n ax.add_patch(patch)\n ax.set_xlim(0, score_matrix.shape[1])\n ax.set_xticks(np.arange(score_matrix.shape[1]) + 0.5)\n ax.set_xticklabels(np.arange(score_matrix.shape[1]))\n return ax\n\n\ndef rescale_score_matrix(score_matrix, base_scaling=\"identity\",\n position_scaling=\"identity\"):\n \"\"\"Performs base-wise and position-wise scaling of a score matrix for a\n feature, usually produced from an *in silico* mutagenesis experiment.\n\n Parameters\n ----------\n score_matrix : numpy.ndarray\n An :math:`L \\\\times N` matrix containing the scores for each\n position, where :math:`L` is the length of the sequence, and\n :math:`N` is the number of characters in the alphabet.\n base_scaling : {'identity', 'probability', 'max_effect'}\n The type of scaling performed on each base at a given position.\n\n * 'identity' - No transformation will be applied to the\\\n data.\n * 'probability' - The relative sizes of the bases will be\\\n the original input probabilities.\n * 'max_effect' - The relative sizes of the bases will be\\\n the max effect of the original input\\\n values.\n position_scaling : {'identity', 'probability', 'max_effect'}\n The type of scaling performed on each position.\n\n * 'identity' - No transformation will be applied to the data.\n * 'probability' - The sum of values at a position will be\\\n equal to the sum of the original input\\\n values at that position.\n * 'max_effect' - The sum of values at a position will be\\\n equal to the sum of the max effect values\\\n of the original input values at that\\\n position.\n\n Returns\n -------\n numpy.ndarray\n The transformed score matrix.\n\n Raises\n ------\n ValueError\n If an unsupported `base_scaling` or `position_scaling` is\n entered.\n\n \"\"\"\n # Note that things can break if we do not deepcopy.\n score_matrix = deepcopy(score_matrix)\n\n score_matrix = score_matrix.transpose()\n rescaled_scores = score_matrix\n\n # Scale individual bases.\n if base_scaling == \"identity\" or base_scaling == \"probability\":\n pass\n elif base_scaling == \"max_effect\":\n rescaled_scores = score_matrix - np.min(score_matrix, axis=0)\n else:\n raise ValueError(\n \"Could not find base scaling \\\"{0}\\\".\".format(base_scaling))\n\n # Scale each position\n if position_scaling == \"max_effect\":\n max_effects = np.max(score_matrix, axis=0) - np.min(score_matrix,\n axis=0)\n rescaled_scores /= rescaled_scores.sum(axis=0)[np.newaxis, :]\n rescaled_scores *= max_effects[np.newaxis, :]\n elif position_scaling == \"probability\":\n rescaled_scores /= np.sum(score_matrix, axis=0)[np.newaxis, :]\n elif position_scaling != \"identity\":\n raise ValueError(\n \"Could not find position scaling \\\"{0}\\\".\".format(\n position_scaling))\n return rescaled_scores.transpose()\n\n\ndef heatmap(score_matrix, mask=None, sequence_type=Genome, **kwargs):\n \"\"\"Plots the input matrix of scores, generally those produced by an\n *in silico* mutagenesis experiment, on a heatmap.\n\n Parameters\n ----------\n score_matrix : numpy.ndarray\n An :math:`L \\\\times N` array (where :math:`L` is the length of\n the sequence, and :math:`N` is the size of the alphabet)\n containing the scores for each base change at each position.\n mask : numpy.ndarray, dtype=bool or None, optional\n Default is `None`. An :math:`L \\\\times N` array (where :math:`L`\n is the length of the sequence, and :math:`N` is the size of the\n alphabet) containing `True` at positions in the heatmap to\n mask. If `None`, no masking will occur.\n sequence_type : class, optional\n Default is `selene_sdk.sequences.Genome`. The class of sequence that\n the *in silico* mutagenesis results are associated with. This is\n generally a sub-class of `selene_sdk.sequences.Sequence`.\n **kwargs : dict\n Keyword arguments to pass to `seaborn.heatmap`. Some useful ones\n to remember are:\n\n * cbar_kws - Keyword arguments to forward to the colorbar.\n * yticklabels - Manipulate the tick labels on the y axis.\n * cbar - If `False`, hide the color bar. If `True`, show\\\n the colorbar.\n * cmap - The color map to use for the heatmap.\n\n Returns\n -------\n matplotlib.pyplot.Axes\n The axes containing the heatmap plot.\n\n \"\"\"\n # Note that some things can break if we do not deepcopy.\n score_matrix = deepcopy(score_matrix)\n\n # This flipping is so that ordering is consistent with ordering\n # in the sequence logo.\n if mask is not None:\n mask = mask.transpose()\n mask = np.flip(mask, axis=0)\n score_matrix = score_matrix.transpose()\n score_matrix = np.flip(score_matrix, axis=0)\n\n if \"yticklabels\" in kwargs:\n yticklabels = kwargs.pop(\"yticklabels\")\n else:\n yticklabels = sequence_type.BASES_ARR[::-1]\n if \"cbar_kws\" in kwargs:\n cbar_kws = kwargs.pop(\"cbar_kws\")\n else:\n cbar_kws = dict(use_gridspec=False, location=\"bottom\", pad=0.2)\n if \"cmap\" in kwargs:\n cmap = kwargs.pop(\"cmap\")\n else:\n cmap = \"Blues\"\n ret = sns.heatmap(score_matrix, mask=mask, yticklabels=yticklabels,\n cbar_kws=cbar_kws, cmap=cmap, **kwargs)\n ret.set_yticklabels(labels=ret.get_yticklabels(), rotation=0)\n return ret\n\n\ndef load_variant_abs_diff_scores(input_path):\n \"\"\"\n Loads the variant data, labels, and feature names from a diff scores\n file output from variant effect prediction.\n\n TODO: should we move this out of `vis.py`?\n\n Parameters\n ----------\n input_path : str\n Path to the input file.\n\n Returns\n -------\n tuple(np.ndarray, list(tuple(str)), list(str))\n\n * `tuple[0]` is the matrix of absolute difference scores. The rows\\\n are the variants and the columns are the features for which the\\\n model makes predictions.\n * `tuple[1]` is the list of variant labels. Each tuple contains\\\n (chrom, pos, name, ref, alt).\n * `tuple[2]` is the list of features.\n\n \"\"\"\n features = []\n labels = []\n diffs = []\n with open(input_path, 'r') as file_handle:\n colnames = file_handle.readline()\n features = colnames.strip().split('\\t')[5:]\n for line in file_handle:\n cols = line.strip().split('\\t')\n scores = [float(f) for f in cols[5:]]\n label = tuple(cols[:5])\n diffs.append(scores)\n labels.append(label)\n diffs = np.array(diffs)\n return (diffs, labels, features)\n\n\ndef sort_standard_chrs(chrom):\n \"\"\"\n Returns the value on which the\n standard chromosomes can be sorted.\n\n Parameters\n ----------\n chrom : str\n The chromosome\n\n Returns\n -------\n int\n The value on which to sort\n\n \"\"\"\n chrom = chrom[3:]\n if chrom.isdigit():\n return int(chrom)\n if chrom == 'X':\n return 23\n elif chrom == 'Y':\n return 24\n elif chrom == 'M':\n return 25\n else: # unknown chr\n return 26\n\n\ndef ordered_variants_and_indices(labels):\n \"\"\"\n Get the ordered variant labels, where the labels are sorted by chromosome\n and position, and the indices corresponding to the sort,\n\n Parameters\n ----------\n labels : list(tuple(str))\n The list of variant labels. Each label is a tuple of\n (chrom, pos, name, ref, alt).\n\n Returns\n -------\n tuple(list(tuple), list(int))\n The first value is the ordered list of labels. Each label\n is a tuple of (chrom, pos, ref, alt). The second value\n is the ordered list of label indices.\n\n \"\"\"\n labels_dict = defaultdict(list)\n for i, l in enumerate(labels):\n chrom, pos, name, ref, alt = l\n pos = int(pos)\n info = (i, pos, ref, alt)\n labels_dict[chrom].append(info)\n for chrom, labels_list in labels_dict.items():\n labels_list.sort(key=lambda tup: tup[1:])\n ordered_keys = sorted(labels_dict.keys(),\n key=sort_standard_chrs)\n\n ordered_labels = []\n ordered_label_indices = []\n for chrom in ordered_keys:\n for l in labels_dict[chrom]:\n index, pos, ref, alt = l\n ordered_label_indices.append(index)\n ordered_labels.append((chrom, pos, ref, alt))\n return (ordered_labels, ordered_label_indices)\n\n\ndef _label_tuple_to_text(label, diff, genes=None):\n \"\"\"\n Converts the variant label tuple to a string.\n\n Parameters\n ----------\n label : tuple(str)\n A tuple of (chrom, pos, ref, alt).\n diff : float\n The max difference score across some or all features in the model.\n genes : list(str) or None, optional\n Default is None. If the closest protein-coding `genes` are specified,\n will display them in the label text.\n\n Returns\n -------\n str\n The label text.\n\n \"\"\"\n chrom, pos, ref, alt = label\n if genes is not None:\n if len(genes) == 0:\n genes_str = \"none found\"\n else:\n genes_str = ', '.join(genes)\n text = (\"max diff score: {0}<br />{1} {2}, {3}/{4}<br />\"\n \"closest protein-coding gene(s): {5}\").format(\n diff, chrom, pos, ref, alt, genes_str)\n else:\n text = \"max diff score: {0}<br />{1} {2}, {3}/{4}\".format(\n diff, chrom, pos, ref, alt)\n return text\n\n\ndef _variant_closest_genes(label, tabix_fh, chrs_gene_intervals):\n chrom = label[0]\n pos = label[1]\n closest_genes = []\n try:\n overlaps = tabix_fh.query(chrom, pos, pos + 1)\n for o in overlaps:\n closest_genes.append(o[-1])\n except tabix.TabixError:\n pass\n if len(closest_genes) != 0:\n return closest_genes\n gene_intervals = chrs_gene_intervals[chrom]\n closest = None\n for (start, end, strand, gene) in gene_intervals:\n if start < pos and closest and closest == pos - end:\n closest_genes.append(gene)\n elif start < pos and (closest is None\n or closest > pos - end):\n closest = pos - end\n closest_genes = [gene]\n elif start > pos and closest and closest == start - pos:\n closest_genes.append(gene)\n elif start > pos and (closest is None\n or closest > start - pos):\n closest = start - pos\n closest_genes = [gene]\n return closest_genes\n\n\ndef _load_chrs_gene_intervals(gene_intervals_bed):\n chrs_gene_intervals = defaultdict(list)\n with open(gene_intervals_bed, 'r') as file_handle:\n for line in file_handle:\n cols = line.strip().split('\\t')\n chrom = cols[0]\n start = int(cols[1])\n end = int(cols[2])\n strand = cols[3]\n gene = cols[4]\n chrs_gene_intervals[chrom].append((start, end, strand, gene))\n return chrs_gene_intervals\n\n\ndef _variants_closest_protein_coding_gene(labels, version=\"hg38\"):\n gene_intervals_tabix = pkg_resources.resource_filename(\n \"selene_sdk\",\n (\"interpret/data/gencode_v28_{0}/\"\n \"protein_coding_l12_genes.bed.gz\").format(version))\n gene_intervals_bed = pkg_resources.resource_filename(\n \"selene_sdk\",\n (\"interpret/data/gencode_v28_{0}/\"\n \"protein_coding_l12_genes.bed\").format(version))\n\n tabix_fh = tabix.open(gene_intervals_tabix)\n chrs_gene_intervals = _load_chrs_gene_intervals(gene_intervals_bed)\n\n labels_gene_information = []\n for l in labels:\n labels_gene_information.append(_variant_closest_genes(\n l, tabix_fh, chrs_gene_intervals))\n\n return labels_gene_information\n\n\ndef variant_diffs_scatter_plot(data,\n labels,\n features,\n output_path,\n filter_features=None,\n labels_sort_fn=ordered_variants_and_indices,\n nth_percentile=None,\n hg_reference_version=None,\n threshold_line=None,\n auto_open=False):\n \"\"\"\n Displays each variant's max probability difference across features\n as a point in a scatter plot. The points in the scatter plot are\n ordered by the variant chromosome and position by default. Variants can\n be sorted differently by passing in a new `labels_sort_fn`.\n\n Parameters\n ----------\n data : np.ndarray\n Absolute difference scores for variants across all features that a\n model predicts. This is the first value in the tuple returned by\n `load_variant_abs_diff_scores`.\n labels : list(tuple(str))\n A list of variant labels. This is the second value in the tuple\n returned by `load_variant_abs_diff_scores`.\n features : list(str)\n A list of the features the model predicts. This is the third value\n in the tuple returned by `load_variant_abs_diff_scores`.\n output_path : str\n Path to output file. Must have '.html' extension.\n filter_features : types.FunctionType or None, optional\n Default is None. A function that takes in a `list(str)` of features\n and returns the `list(int)` of feature indices over which we would\n compute the max(probability difference) for each variant. For example,\n a user may only want to visualize the max probability difference\n for TF binding features. If `None`, uses all the features.\n labels_sort_fn : types.FunctionType, optional\n Default is `ordered_variants_and_indices`. A function that takes\n in a `list(tuple(str))` of labels corresponding to the rows in `data`\n and returns a `tuple(list(tuple), list(int))`, where the first value\n is the ordered list of variant labels and the second value is the\n ordered list of indices for those variant labels. By default,\n variants are sorted by chromosome and position.\n nth_percentile : int [0, 100] or None, optional\n Default is None. If `nth_percentile` is not None, only displays the\n variants with a max absolute difference score within the\n `nth_percentile` of scores.\n hg_reference_version : str {\"hg19\", \"hg38\"} or None, optional\n Default is None. On hover, we can display the gene(s) closest to\n each variant if `hg_reference_version` is not None, where closest\n can be a variant within a gene interval (where genes and\n their coordinates are taken from level 1 & 2 protein-coding genes\n in gencode v28) or near a gene. In the future, we will allow users\n to specify their own genome file so that this information can\n be annotated to variants from other organisms, other genome versions,\n etc.\n threshold_line : float or None, optional\n Default is None. If `threshold_line` is not None, draws a horizontal\n line at the specified threshold. Helps focus the visual on variants\n above a certain threshold.\n auto_open : bool, optional\n Default is False. If `auto_open`, will automatically open a web\n browser that displays the plotted HTML file.\n\n Returns\n -------\n plotly.graph_objs.graph_objs.Figure\n The generated Plotly figure.\n\n \"\"\"\n labels_ordered, label_indices = labels_sort_fn(labels)\n variant_closest_genes = None\n if hg_reference_version is not None:\n variant_closest_genes = _variants_closest_protein_coding_gene(\n labels_ordered, version=hg_reference_version)\n ordered_data = data[label_indices, :]\n\n feature_indices = None\n if filter_features is not None:\n feature_indices = filter_features(features)\n ordered_data = data[:, feature_indices]\n variants_max_diff = np.amax(ordered_data, axis=1)\n\n display_labels = None\n if nth_percentile:\n p = np.percentile(variants_max_diff, nth_percentile)\n keep = np.where(variants_max_diff >= p)[0]\n print(\"{0} variants with max abs diff score above {1} are in the \"\n \"{2}th percentile.\".format(\n len(keep), p, nth_percentile))\n variants_max_diff = variants_max_diff[keep]\n display_labels = []\n for i, l in enumerate(labels_ordered):\n if i not in keep:\n continue\n display_labels.append(l)\n else:\n display_labels = labels_ordered\n\n if variant_closest_genes:\n text_labels = [\n _label_tuple_to_text(l, d, g) for l, d, g in\n zip(display_labels, variants_max_diff, variant_closest_genes)]\n else:\n text_labels = [_label_tuple_to_text(l, d) for l, d in\n zip(display_labels, variants_max_diff)]\n\n label_x = [' '.join([l[0], str(l[1])]) for l in display_labels]\n data = [go.Scatter(x=label_x,\n y=variants_max_diff,\n mode='markers',\n marker = dict(\n color = \"#39CCCC\",\n line = dict(width = 1)),\n text=text_labels,\n hoverinfo=\"text\")]\n\n go_layout = {\n \"title\": \"Max probability difference scores\",\n \"hovermode\": \"closest\",\n \"hoverlabel\": {\n \"font\": {\"size\": 16}\n },\n \"xaxis\": {\n \"title\": \"Genome coordinates\",\n \"showticklabels\": True,\n \"tickangle\": 35,\n \"titlefont\": {\"family\": \"Arial, sans-serif\",\n \"size\": 16},\n \"nticks\": 25,\n \"tickmode\": \"auto\",\n \"automargin\": True\n },\n \"yaxis\": {\n \"title\": \"Absolute difference\",\n \"titlefont\": {\"family\": \"Arial, sans-serif\",\n \"size\": 16}\n }\n }\n if isinstance(threshold_line, float):\n layout = go.Layout(\n **go_layout,\n shapes=[\n {\"type\": \"line\",\n \"x0\": label_x[0],\n \"y0\": threshold_line,\n \"x1\": label_x[-1],\n \"y1\": threshold_line,\n \"line\": {\n \"color\": \"rgba(255, 99, 71, 1)\",\n \"width\": 2\n }\n }\n ])\n else:\n layout = go.Layout(**go_layout)\n fig = go.Figure(data=data, layout=layout)\n path, filename = os.path.split(output_path)\n os.makedirs(path, exist_ok=True)\n plot(fig, filename=output_path, auto_open=auto_open)\n return fig\n"
] |
[
[
"numpy.amax",
"numpy.sum",
"numpy.min",
"numpy.arange",
"matplotlib.transforms.Affine2D",
"matplotlib.path.Path",
"matplotlib.pyplot.subplots",
"numpy.percentile",
"numpy.argwhere",
"numpy.max",
"numpy.zeros_like",
"numpy.zeros",
"numpy.argsort",
"matplotlib.text.TextPath",
"numpy.array",
"numpy.flip",
"numpy.where",
"numpy.empty"
]
] |
cglacet/robotarium_python_simulator
|
[
"b58ad6b201f404d0b079dc695f68d916260cc9d1"
] |
[
"rps/examples/go_to_pose/uni_go_to_pose_hybrid.py"
] |
[
"import rps.robotarium as robotarium\nfrom rps.utilities.transformations import *\nfrom rps.utilities.barrier_certificates import *\nfrom rps.utilities.misc import *\nfrom rps.utilities.controllers import *\n\nimport numpy as np\nimport time\n\n# Instantiate Robotarium object\nN = 5\ninitial_conditions = np.array(np.mat('1 0.5 -0.5 0 0.28; 0.8 -0.3 -0.75 0.1 0.34; 0 0 0 0 0'))\nr = robotarium.Robotarium(number_of_robots=N, show_figure=True, initial_conditions=initial_conditions,sim_in_real_time=True)\n\n# Define goal points by removing orientation from poses\ngoal_points = generate_initial_conditions(N)\n\n# Create unicycle pose controller\nunicycle_pose_controller = create_hybrid_unicycle_pose_controller()\n\n# Create barrier certificates to avoid collision\nuni_barrier_cert = create_unicycle_barrier_certificate()\n\n# define x initially\nx = r.get_poses()\nr.step()\n\n# While the number of robots at the required poses is less\n# than N...\nwhile (np.size(at_pose(x, goal_points)) != N):\n\n # Get poses of agents\n x = r.get_poses()\n\n # Create unicycle control inputs\n dxu = unicycle_pose_controller(x, goal_points)\n\n # Create safe control inputs (i.e., no collisions)\n dxu = uni_barrier_cert(dxu, x)\n\n # Set the velocities\n r.set_velocities(np.arange(N), dxu)\n\n # Iterate the simulation\n r.step()\n\n#Call at end of script to print debug information and for your script to run on the Robotarium server properly\nr.call_at_scripts_end()\n"
] |
[
[
"numpy.arange",
"numpy.mat"
]
] |
ag-gipp/NLPLand
|
[
"a614f83de50b516a452bced6287a4391a54ffd55"
] |
[
"tests/test_dataset.py"
] |
[
"import os\nfrom collections import defaultdict\nfrom typing import List\nfrom urllib.error import HTTPError\n\nimport numpy as np\nimport pandas as pd\nimport pytest\nfrom _pytest.capture import CaptureFixture\nfrom _pytest.monkeypatch import MonkeyPatch\nfrom mock import MagicMock\nfrom pytest_mock import MockerFixture\n\nfrom nlpland.constants import (\n ABSTRACT_SOURCE_ANTHOLOGY,\n ABSTRACT_SOURCE_RULE,\n COLUMN_ABSTRACT,\n COLUMN_ABSTRACT_SOURCE,\n MISSING_PAPERS,\n)\nfrom nlpland.data import dataset\n\ndf_missing = pd.DataFrame([[\"c\", \"http://abc/c.pdf\"]])\n\n\[email protected]()\ndef mock_env_papers(monkeypatch: MonkeyPatch) -> None:\n monkeypatch.setenv(\"PATH_PAPERS\", \"papers\")\n\n\[email protected]()\ndef readcsv(mocker: MockerFixture) -> MagicMock:\n yield mocker.patch(\"pandas.read_csv\", return_value=df_missing)\n\n\[email protected]()\ndef makedirs(mocker: MockerFixture) -> MagicMock:\n yield mocker.patch(\"os.makedirs\")\n\n\[email protected]()\ndef urlretrieve(mocker: MockerFixture) -> MagicMock:\n yield mocker.patch(\"urllib.request.urlretrieve\")\n\n\ndef test_download_papers(\n mocker: MockerFixture,\n mock_env_papers: pytest.fixture,\n readcsv: MagicMock,\n makedirs: MagicMock,\n urlretrieve: MagicMock,\n) -> None:\n df_papers = pd.DataFrame(\n {\n \"AA year of publication\": [2010, 2011],\n \"NS venue name\": [\"ACL\", \"EMNLP\"],\n \"AA url\": [\"https://www.aclweb.org/anthology/a\", \"https://abc/b.pdf\"],\n },\n index=[\"a\", \"b\"],\n )\n dataset.download_papers(df_papers)\n readcsv.assert_called()\n\n makedirs_calls = [\n mocker.call(\"papers/2010/ACL\", exist_ok=True),\n mocker.call(\"papers/2011/EMNLP\", exist_ok=True),\n ]\n makedirs.assert_has_calls(makedirs_calls)\n urlretrieve_calls = [\n mocker.call(\"https://www.aclweb.org/anthology/a.pdf\", \"papers/2010/ACL/a.pdf\"),\n mocker.call(\"https://abc/b.pdf\", \"papers/2011/EMNLP/b.pdf\"),\n ]\n urlretrieve.assert_has_calls(urlretrieve_calls)\n\n\ndef test_download_papers_skip_request(\n mocker: MockerFixture,\n mock_env_papers: MagicMock,\n readcsv: MagicMock,\n makedirs: MagicMock,\n urlretrieve: MagicMock,\n) -> None:\n df_paper = pd.DataFrame(\n {\n \"AA year of publication\": [2010],\n \"NS venue name\": [\"EMNLP\"],\n \"AA url\": [\"http://abc/a.pdf\"],\n },\n index=[\"a\"],\n )\n df_paper.index = [\"c\"]\n dataset.download_papers(df_paper)\n urlretrieve.assert_not_called()\n\n mocker.patch(\"os.path.isfile\", return_value=True)\n df_paper.index = [\"a\"]\n dataset.download_papers(df_paper)\n urlretrieve.assert_not_called()\n\n\ndef test_download_papers_error(\n mocker: MockerFixture, mock_env_papers: MagicMock, readcsv: MagicMock, makedirs: MagicMock\n) -> None:\n df_paper = pd.DataFrame(\n {\n \"AA year of publication\": [2010],\n \"NS venue name\": [\"EMNLP\"],\n \"AA url\": [\"http://abc/a.pdf\"],\n },\n index=[\"a\"],\n )\n urlretrieve = mocker.patch(\n \"urllib.request.urlretrieve\",\n side_effect=[HTTPError(\"http://url.com\", 404, \"\", {}, None)], # type: ignore\n )\n open_ = mocker.mock_open(mock=mocker.patch(\"builtins.open\"))\n\n dataset.download_papers(df_paper)\n\n urlretrieve.assert_called_once()\n open_.assert_called_once_with(MISSING_PAPERS, \"a+\", encoding=\"utf-8\")\n open_().write.assert_called_once_with(\"a\\thttp://abc/a.pdf\\n\")\n\n\ndef test_save_load_dataset(monkeypatch: MonkeyPatch) -> None:\n df_paper = pd.DataFrame(\n {\n \"NS venue name\": [np.nan],\n \"AA url\": [\"http://abc/a.pdf\"],\n },\n index=[\"a\"],\n )\n path_old = \"tests/old.txt\"\n path_new = \"tests/new.txt\"\n monkeypatch.setenv(\"PATH_DATASET\", path_old)\n monkeypatch.setenv(\"PATH_DATASET_EXPANDED\", path_new)\n\n df_paper.to_csv(os.getenv(\"PATH_DATASET\"), sep=\"\\t\", na_rep=\"NA\")\n df_paper_loaded = dataset.load_dataset(original_dataset=True)\n assert df_paper_loaded.equals(df_paper)\n\n df_paper_loaded.at[\"a\", COLUMN_ABSTRACT] = \"test\"\n dataset.save_dataset(df_paper_loaded)\n df_paper_loaded2 = dataset.load_dataset(original_dataset=False)\n assert df_paper_loaded2.equals(df_paper_loaded)\n\n os.remove(path_old)\n os.remove(path_new)\n\n\[email protected](\n \"text, possible_strings, earliest_pos, earliest_string\",\n [\n (\"1232\", [\"2\", \"3\"], 1, \"2\"),\n (\"cb ad\", [\"a\", \"c\"], 0, \"c\"),\n ],\n)\ndef test_determine_earliest_string(\n text: str, possible_strings: List[str], earliest_pos: int, earliest_string: str\n) -> None:\n assert (earliest_pos, earliest_string) == dataset.determine_earliest_string(\n text, possible_strings\n )\n\n\ndef test_print_results_extract_abstracts_rulebased(capfd: CaptureFixture) -> None:\n duration = (1, 2, 3, 4, 5, 6, 7, 8, 9)\n count_dict: dict = defaultdict(int)\n count_dict[\"searched\"] += 3\n\n dataset.print_results_extract_abstracts_rulebased(count_dict, duration)\n capture = capfd.readouterr()\n assert \"3 abstracts searched\" in capture.out\n assert \"05m 06s\" in capture.out\n\n\[email protected](\n \"text, expected\",\n [\n (\"Abstract\\ntext\\n\\n1 Introduction\", \"text\"),\n (\"ABSTRACT\\ntext\\n\\n1. Introduction\", \"text\"),\n (\"Abstract text\\nKeywords:\", \"text\\n\"),\n (\"A b s t r a c t\\ntext\\nKeywords :\", \"text\\n\"),\n (\"Abstract\\ntext\\n\\nIntroduction\\n\\n\", \"text\"),\n ],\n)\ndef test_helper_abstracts_rulebased(mocker: MockerFixture, text: str, expected: str) -> None:\n df_paper = pd.DataFrame(\n {\"NS venue name\": [\"ACL\"], \"AA year of publication\": [2010]}, index=[\"a\"]\n )\n\n mocker.patch(\"os.path.isfile\", return_value=True)\n mocker.patch(\"tika.parser.from_file\", return_value={\"content\": text})\n\n count_dict: dict = defaultdict(int)\n index = df_paper.index[0]\n df_result = dataset.helper_abstracts_rulebased(index, count_dict, \"papers\", df_paper)\n assert df_result.at[index, COLUMN_ABSTRACT] == expected\n\n\[email protected](\n \"overwrite, calls\",\n [(False, 1), (True, 2)],\n)\ndef test_extract_abstracts_rulebased(\n mocker: MockerFixture, monkeypatch: MonkeyPatch, overwrite: bool, calls: int\n) -> None:\n df_full = pd.DataFrame({})\n df_return = pd.DataFrame({}, index=[\"z\"])\n df_select = pd.DataFrame(\n {\n COLUMN_ABSTRACT_SOURCE: [\n ABSTRACT_SOURCE_RULE,\n ABSTRACT_SOURCE_ANTHOLOGY,\n ABSTRACT_SOURCE_RULE,\n ],\n COLUMN_ABSTRACT: [\"text\", \"text\", None],\n },\n index=[\"a\", \"b\", \"c\"],\n )\n\n monkeypatch.setenv(\"PATH_PAPERS\", \"papers\")\n init = mocker.patch(\"tika.initVM\")\n save = mocker.patch(\"nlpland.data.dataset.save_dataset\")\n helper = mocker.patch(\"nlpland.data.dataset.helper_abstracts_rulebased\", return_value=df_return)\n mocker.patch(\"nlpland.data.dataset.print_results_extract_abstracts_rulebased\")\n\n dataset.extract_abstracts_rulebased(df_select, df_full, overwrite_rule=overwrite)\n init.assert_called_once()\n save.assert_called_once_with(df_return)\n assert helper.call_count == calls\n\n\ndef test_extract_abstracts_anthology(monkeypatch: MonkeyPatch) -> None:\n xml1 = \"\"\"\n <collection id=\"2010.abc\">\n <volume id=\"1\">\n <paper id=\"1\">\n <abstract>In this paper ...</abstract>\n <url>2010.abc.1</url>\n </paper>\n <paper id=\"2\">\n </paper>\n </volume>\n </collection>\"\"\"\n xml2 = \"\"\"\n <collection id=\"L01\">\n <volume id=\"1\">\n <paper id=\"1\">\n <abstract>In the field ...</abstract>\n <url>http://abc/a.pdf</url>\n </paper>\n </volume>\n </collection>\"\"\"\n file1 = \"tests/xml1.xml\"\n file2 = \"tests/xml2.xml\"\n with open(file1, \"w+\", encoding=\"utf-8\") as file:\n file.write(xml1)\n with open(file2, \"w+\", encoding=\"utf-8\") as file:\n file.write(xml2)\n\n index = [\"2010.abc.1\", \"L01-1-1\"]\n monkeypatch.setenv(\"PATH_ANTHOLOGY\", \"tests\")\n df_papers = pd.DataFrame({}, index=index)\n\n dataset.extract_abstracts_anthology(df_papers)\n expected = pd.Series([\"In this paper ...\", \"In the field ...\"], index=index)\n assert df_papers[COLUMN_ABSTRACT].equals(expected)\n\n os.remove(file1)\n os.remove(file2)\n"
] |
[
[
"pandas.Series",
"pandas.DataFrame"
]
] |
chenj209/TensorFlowOnSpark
|
[
"df468ffba500c2254b2310aa1b30dbad8d5fb162"
] |
[
"tensorflowonspark/TFSparkNode.py"
] |
[
"# Copyright 2017 Yahoo Inc.\n# Licensed under the terms of the Apache 2.0 license.\n# Please see LICENSE file in the project root for terms.\n\"\"\"This module provides low-level functions for managing the TensorFlowOnSpark cluster.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import nested_scopes\nfrom __future__ import print_function\n\nimport json\nimport logging\nimport multiprocessing\nimport os\nimport platform\nimport socket\nimport subprocess\nimport sys\nimport uuid\nimport time\nimport traceback\nfrom threading import Thread\n\nfrom . import TFManager\nfrom . import TFNode\nfrom . import gpu_info\nfrom . import marker\nfrom . import reservation\nfrom . import util\n\nlogger = logging.getLogger(__name__)\n\n\nclass TFNodeContext:\n \"\"\"Encapsulates unique metadata for a TensorFlowOnSpark node/executor and provides methods to interact with Spark and HDFS.\n\n An instance of this object will be passed to the TensorFlow \"main\" function via the `ctx` argument.\n To simply the end-user API, this class now mirrors the functions of the TFNode module.\n\n Args:\n :executor_id: integer identifier for this executor, per ``nodeRDD = sc.parallelize(range(num_executors), num_executors).``\n :job_name: TensorFlow job name (e.g. 'ps' or 'worker') of this TF node, per cluster_spec.\n :task_index: integer rank per job_name, e.g. \"worker:0\", \"worker:1\", \"ps:0\".\n :cluster_spec: dictionary for constructing a tf.train.ClusterSpec.\n :defaultFS: string representation of default FileSystem, e.g. ``file://`` or ``hdfs://<namenode>:8020/``.\n :working_dir: the current working directory for local filesystems, or YARN containers.\n :mgr: TFManager instance for this Python worker.\n \"\"\"\n def __init__(self, executor_id=0, job_name='', task_index=0, cluster_spec={}, defaultFS='file://', working_dir='.', mgr=None):\n self.worker_num = executor_id # for backwards-compatibility\n self.executor_id = executor_id\n self.job_name = job_name\n self.task_index = task_index\n self.cluster_spec = cluster_spec\n self.num_workers = sum([len(v) for k, v in cluster_spec.items() if k == 'master' or k == 'chief' or k == 'worker'])\n self.defaultFS = defaultFS\n self.working_dir = working_dir\n self.mgr = mgr\n\n def absolute_path(self, path):\n \"\"\"Convenience function to access ``TFNode.hdfs_path`` directly from this object instance.\"\"\"\n return TFNode.hdfs_path(self, path)\n\n def start_cluster_server(self, num_gpus=1, rdma=False):\n \"\"\"Convenience function to access ``TFNode.start_cluster_server`` directly from this object instance.\"\"\"\n return TFNode.start_cluster_server(self, num_gpus, rdma)\n\n def export_saved_model(self, sess, export_dir, tag_set, signatures):\n \"\"\"Convenience function to access ``TFNode.export_saved_model`` directly from this object instance.\"\"\"\n TFNode.export_saved_model(sess, export_dir, tag_set, signatures)\n\n def get_data_feed(self, train_mode=True, qname_in='input', qname_out='output', input_mapping=None):\n \"\"\"Convenience function to access ``TFNode.DataFeed`` directly from this object instance.\"\"\"\n return TFNode.DataFeed(self.mgr, train_mode, qname_in, qname_out, input_mapping)\n\n\nclass TFSparkNode(object):\n \"\"\"Low-level functions used by the high-level TFCluster APIs to manage cluster state.\n\n **This class is not intended for end-users (see TFNode for end-user APIs)**.\n\n For cluster management, this wraps the per-node cluster logic as Spark RDD mapPartitions functions, where the RDD is expected to be\n a \"nodeRDD\" of the form: ``nodeRDD = sc.parallelize(range(num_executors), num_executors)``.\n\n For data feeding, this wraps the feeding logic as Spark RDD mapPartitions functions on a standard \"dataRDD\".\n\n This also manages a reference to the TFManager \"singleton\" per executor. Since Spark can spawn more than one python-worker\n per executor, this will reconnect to the \"singleton\" instance as needed.\n \"\"\"\n mgr = None #: TFManager instance\n cluster_id = None #: Unique ID for a given TensorFlowOnSpark cluster, used for invalidating state for new clusters.\n\n\ndef _get_manager(cluster_info, host, executor_id):\n \"\"\"Returns this executor's \"singleton\" instance of the multiprocessing.Manager, reconnecting per python-worker if needed.\n\n Args:\n :cluster_info: cluster node reservations\n :host: host IP address\n :executor_id: unique id per executor (created during initial call to run())\n\n Returns:\n TFManager instance for this executor/python-worker\n \"\"\"\n for node in cluster_info:\n if node['host'] == host and node['executor_id'] == executor_id:\n addr = node['addr']\n authkey = node['authkey']\n TFSparkNode.mgr = TFManager.connect(addr, authkey)\n break\n\n if TFSparkNode.mgr is None:\n msg = \"No TFManager found on this node, please ensure that:\\n\" + \\\n \"1. Spark num_executors matches TensorFlow cluster_size\\n\" + \\\n \"2. Spark cores/tasks per executor is 1.\\n\" + \\\n \"3. Spark dynamic allocation is disabled.\"\n raise Exception(msg)\n\n logger.info(\"Connected to TFSparkNode.mgr on {0}, executor={1}, state={2}\".format(host, executor_id, str(TFSparkNode.mgr.get('state'))))\n return TFSparkNode.mgr\n\n\ndef run(fn, tf_args, cluster_meta, tensorboard, log_dir, queues, background):\n \"\"\"Wraps the user-provided TensorFlow main function in a Spark mapPartitions function.\n\n Args:\n :fn: TensorFlow \"main\" function provided by the user.\n :tf_args: ``argparse`` args, or command line ``ARGV``. These will be passed to the ``fn``.\n :cluster_meta: dictionary of cluster metadata (e.g. cluster_id, reservation.Server address, etc).\n :tensorboard: boolean indicating if the chief worker should spawn a Tensorboard server.\n :log_dir: directory to save tensorboard event logs. If None, defaults to a fixed path on local filesystem.\n :queues: *INTERNAL_USE*\n :background: boolean indicating if the TensorFlow \"main\" function should be run in a background process.\n\n Returns:\n A nodeRDD.mapPartitions() function.\n \"\"\"\n def _mapfn(iter):\n import tensorflow as tf\n\n # Note: consuming the input iterator helps Pyspark re-use this worker,\n for i in iter:\n executor_id = i\n\n # check that there are enough available GPUs (if using tensorflow-gpu) before committing reservation on this node\n if tf.test.is_built_with_cuda():\n num_gpus = tf_args.num_gpus if 'num_gpus' in tf_args else 1\n gpus_to_use = gpu_info.get_gpus(num_gpus)\n\n # assign TF job/task based on provided cluster_spec template (or use default/null values)\n job_name = 'default'\n task_index = -1\n cluster_id = cluster_meta['id']\n cluster_template = cluster_meta['cluster_template']\n for jobtype in cluster_template:\n nodes = cluster_template[jobtype]\n if executor_id in nodes:\n job_name = jobtype\n task_index = nodes.index(executor_id)\n break\n\n # get unique key (hostname, executor_id) for this executor\n host = util.get_ip_address()\n util.write_executor_id(executor_id)\n port = 0\n\n # check for existing TFManagers\n if TFSparkNode.mgr is not None and str(TFSparkNode.mgr.get('state')) != \"'stopped'\":\n if TFSparkNode.cluster_id == cluster_id:\n # raise an exception to force Spark to retry this \"reservation\" task on another executor\n raise Exception(\"TFManager already started on {0}, executor={1}, state={2}\".format(host, executor_id, str(TFSparkNode.mgr.get(\"state\"))))\n else:\n # old state, just continue with creating new manager\n logger.warn(\"Ignoring old TFManager with cluster_id {0}, requested cluster_id {1}\".format(TFSparkNode.cluster_id, cluster_id))\n\n # start a TFManager and get a free port\n # use a random uuid as the authkey\n authkey = uuid.uuid4().bytes\n addr = None\n if job_name in ('ps', 'evaluator'):\n # PS nodes must be remotely accessible in order to shutdown from Spark driver.\n TFSparkNode.mgr = TFManager.start(authkey, ['control', 'error'], 'remote')\n addr = (host, TFSparkNode.mgr.address[1])\n else:\n # worker nodes only need to be locally accessible within the executor for data feeding\n TFSparkNode.mgr = TFManager.start(authkey, queues)\n addr = TFSparkNode.mgr.address\n\n # initialize mgr state\n TFSparkNode.mgr.set('state', 'running')\n TFSparkNode.cluster_id = cluster_id\n\n # expand Hadoop classpath wildcards for JNI (Spark 2.x)\n if 'HADOOP_PREFIX' in os.environ:\n classpath = os.environ['CLASSPATH']\n hadoop_path = os.path.join(os.environ['HADOOP_PREFIX'], 'bin', 'hadoop')\n hadoop_classpath = subprocess.check_output([hadoop_path, 'classpath', '--glob']).decode()\n logger.debug(\"CLASSPATH: {0}\".format(hadoop_classpath))\n os.environ['CLASSPATH'] = classpath + os.pathsep + hadoop_classpath\n\n # start TensorBoard if requested\n tb_pid = 0\n tb_port = 0\n if tensorboard and job_name == 'worker' and task_index == 0:\n tb_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n tb_sock.bind(('', 0))\n tb_port = tb_sock.getsockname()[1]\n tb_sock.close()\n logdir = log_dir if log_dir else \"tensorboard_%d\" % executor_id\n\n # search for tensorboard in python/bin, PATH, and PYTHONPATH\n pypath = sys.executable\n pydir = os.path.dirname(pypath)\n sys_path = os.pathsep.join(sys.path)\n search_path = os.pathsep.join([pydir, sys_path, os.environ['PATH'], os.environ['PYTHONPATH']])\n\n tb_path = util.find_in_path(search_path, 'tensorboard') # executable in PATH\n if not tb_path:\n tb_path = util.find_in_path(search_path, 'tensorboard/main.py') # TF 1.3+\n if not tb_path:\n tb_path = util.find_in_path(search_path, 'tensorflow/tensorboard/__main__.py') # TF 1.2-\n if not tb_path:\n raise Exception(\"Unable to find 'tensorboard' in: {}\".format(search_path))\n\n # launch tensorboard\n tb_proc = subprocess.Popen([pypath, tb_path, \"--logdir=%s\" % logdir, \"--port=%d\" % tb_port], env=os.environ)\n tb_pid = tb_proc.pid\n\n # check server to see if this task is being retried (i.e. already reserved)\n client = reservation.Client(cluster_meta['server_addr'])\n cluster_info = client.get_reservations()\n tmp_sock = None\n node_meta = None\n for node in cluster_info:\n (nhost, nexec) = (node['host'], node['executor_id'])\n if nhost == host and nexec == executor_id:\n node_meta = node\n port = node['port']\n\n # if not already done, register everything we need to set up the cluster\n if node_meta is None:\n # first, find a free port for TF\n tmp_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n tmp_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n tmp_sock.bind(('', port))\n port = tmp_sock.getsockname()[1]\n\n node_meta = {\n 'executor_id': executor_id,\n 'host': host,\n 'job_name': job_name,\n 'task_index': task_index,\n 'port': port,\n 'tb_pid': tb_pid,\n 'tb_port': tb_port,\n 'addr': addr,\n 'authkey': authkey\n }\n # register node metadata with server\n logger.info(\"TFSparkNode.reserve: {0}\".format(node_meta))\n client.register(node_meta)\n # wait for other nodes to finish reservations\n cluster_info = client.await_reservations()\n client.close()\n\n # construct a TensorFlow clusterspec from cluster_info\n sorted_cluster_info = sorted(cluster_info, key=lambda k: k['executor_id'])\n cluster_spec = {}\n last_executor_id = -1\n for node in sorted_cluster_info:\n if (node['executor_id'] == last_executor_id):\n raise Exception(\"Duplicate worker/task in cluster_info\")\n last_executor_id = node['executor_id']\n logger.info(\"node: {0}\".format(node))\n (njob, nhost, nport) = (node['job_name'], node['host'], node['port'])\n hosts = [] if njob not in cluster_spec else cluster_spec[njob]\n hosts.append(\"{0}:{1}\".format(nhost, nport))\n cluster_spec[njob] = hosts\n\n # update TF_CONFIG if cluster spec has a 'master' node (i.e. tf.estimator)\n if 'master' in cluster_spec or 'chief' in cluster_spec:\n tf_config = json.dumps({\n 'cluster': cluster_spec,\n 'task': {'type': job_name, 'index': task_index},\n 'environment': 'cloud'\n })\n logger.info(\"export TF_CONFIG: {}\".format(tf_config))\n os.environ['TF_CONFIG'] = tf_config\n\n # reserve GPU(s) again, just before launching TF process (in case situation has changed)\n if tf.test.is_built_with_cuda():\n # compute my index relative to other nodes on the same host (for GPU allocation)\n my_addr = cluster_spec[job_name][task_index]\n my_host = my_addr.split(':')[0]\n flattened = [v for sublist in cluster_spec.values() for v in sublist]\n local_peers = [p for p in flattened if p.startswith(my_host)]\n my_index = local_peers.index(my_addr)\n\n num_gpus = tf_args.num_gpus if 'num_gpus' in tf_args else 1\n gpus_to_use = gpu_info.get_gpus(num_gpus, my_index)\n gpu_str = \"GPUs\" if num_gpus > 1 else \"GPU\"\n logger.debug(\"Requested {} {}, setting CUDA_VISIBLE_DEVICES={}\".format(num_gpus, gpu_str, gpus_to_use))\n os.environ['CUDA_VISIBLE_DEVICES'] = gpus_to_use\n\n # create a context object to hold metadata for TF\n ctx = TFNodeContext(executor_id, job_name, task_index, cluster_spec, cluster_meta['default_fs'], cluster_meta['working_dir'], TFSparkNode.mgr)\n\n # release port reserved for TF as late as possible\n if tmp_sock is not None:\n tmp_sock.close()\n\n # Background mode relies reuse of python worker in Spark.\n if background:\n # However, reuse of python worker can't work on Windows, we need to check if the current\n # script runs on Windows or not.\n if os.name == 'nt' or platform.system() == 'Windows':\n raise Exception(\"Background mode is not supported on Windows.\")\n # Check if the config of reuse python worker is enabled on Spark.\n if not os.environ.get(\"SPARK_REUSE_WORKER\"):\n raise Exception(\"Background mode relies reuse of python worker on Spark. This config 'spark.python.worker.reuse' is not enabled on Spark. Please enable it before using background.\")\n\n def wrapper_fn(args, context):\n \"\"\"Wrapper function that sets the sys.argv of the executor.\"\"\"\n if isinstance(args, list):\n sys.argv = args\n fn(args, context)\n\n def wrapper_fn_background(args, context):\n \"\"\"Wrapper function that signals exceptions to foreground process.\"\"\"\n errq = TFSparkNode.mgr.get_queue('error')\n try:\n wrapper_fn(args, context)\n except Exception:\n errq.put(traceback.format_exc())\n\n if job_name in ('ps', 'evaluator') or background:\n # invoke the TensorFlow main function in a background thread\n logger.info(\"Starting TensorFlow {0}:{1} as {2} on cluster node {3} on background process\".format(\n job_name, task_index, job_name, executor_id))\n\n p = multiprocessing.Process(target=wrapper_fn_background, args=(tf_args, ctx))\n if job_name in ('ps', 'evaluator'):\n p.daemon = True\n p.start()\n\n # for ps and evaluator nodes, wait indefinitely in foreground thread for a \"control\" event (None == \"stop\")\n if job_name in ('ps', 'evaluator'):\n queue = TFSparkNode.mgr.get_queue('control')\n equeue = TFSparkNode.mgr.get_queue('error')\n done = False\n while not done:\n while (queue.empty() and equeue.empty()):\n time.sleep(1)\n if (not equeue.empty()):\n e_str = equeue.get()\n raise Exception(\"Exception in \" + job_name + \":\\n\" + e_str)\n msg = queue.get(block=True)\n logger.info(\"Got msg: {0}\".format(msg))\n if msg is None:\n logger.info(\"Terminating {}\".format(job_name))\n TFSparkNode.mgr.set('state', 'stopped')\n done = True\n queue.task_done()\n else:\n # otherwise, just run TF function in the main executor/worker thread\n logger.info(\"Starting TensorFlow {0}:{1} on cluster node {2} on foreground thread\".format(job_name, task_index, executor_id))\n wrapper_fn(tf_args, ctx)\n logger.info(\"Finished TensorFlow {0}:{1} on cluster node {2}\".format(job_name, task_index, executor_id))\n\n return _mapfn\n\n\ndef train(cluster_info, cluster_meta, feed_timeout=600, qname='input'):\n \"\"\"Feeds Spark partitions into the shared multiprocessing.Queue.\n\n Args:\n :cluster_info: node reservation information for the cluster (e.g. host, executor_id, pid, ports, etc)\n :cluster_meta: dictionary of cluster metadata (e.g. cluster_id, reservation.Server address, etc)\n :feed_timeout: number of seconds after which data feeding times out (600 sec default)\n :qname: *INTERNAL_USE*\n\n Returns:\n A dataRDD.mapPartitions() function\n \"\"\"\n def _train(iter):\n # get shared queue, reconnecting if necessary\n mgr = _get_manager(cluster_info, util.get_ip_address(), util.read_executor_id())\n try:\n queue = mgr.get_queue(qname)\n equeue = mgr.get_queue('error')\n except (AttributeError, KeyError):\n msg = \"Queue '{}' not found on this node, check for exceptions on other nodes.\".format(qname)\n raise Exception(msg)\n\n state = str(mgr.get('state'))\n logger.info(\"mgr.state={0}\".format(state))\n terminating = state == \"'terminating'\"\n if terminating:\n logger.info(\"mgr is terminating, skipping partition\")\n count = sum(1 for item in iter)\n logger.info(\"Skipped {0} items from partition\".format(count))\n else:\n logger.info(\"Feeding partition {0} into {1} queue {2}\".format(iter, qname, queue))\n count = 0\n for item in iter:\n count += 1\n queue.put(item, block=True)\n\n # wait for consumers to finish processing all items in queue before \"finishing\" this iterator\n joinThr = Thread(target=queue.join)\n joinThr.start()\n timeout = feed_timeout\n while (joinThr.isAlive()):\n if (not equeue.empty()):\n e_str = equeue.get()\n raise Exception(\"Exception in worker:\\n\" + e_str)\n time.sleep(1)\n timeout -= 1\n if timeout <= 0:\n raise Exception(\"Timeout while feeding partition\")\n\n logger.info(\"Processed {0} items in partition\".format(count))\n\n # check if TF is terminating feed after this partition\n if not terminating:\n state = str(mgr.get('state'))\n terminating = state == \"'terminating'\"\n if terminating:\n try:\n logger.info(\"TFSparkNode: requesting stop\")\n client = reservation.Client(cluster_meta['server_addr'])\n client.request_stop()\n client.close()\n except Exception as e:\n # ignore any errors while requesting stop\n logger.debug(\"Error while requesting stop: {0}\".format(e))\n\n return [terminating]\n\n return _train\n\n\ndef inference(cluster_info, feed_timeout=600, qname='input'):\n \"\"\"Feeds Spark partitions into the shared multiprocessing.Queue and returns inference results.\n\n Args:\n :cluster_info: node reservation information for the cluster (e.g. host, executor_id, pid, ports, etc)\n :feed_timeout: number of seconds after which data feeding times out (600 sec default)\n :qname: *INTERNAL_USE*\n\n Returns:\n A dataRDD.mapPartitions() function\n \"\"\"\n def _inference(iter):\n # get shared queue, reconnecting if necessary\n mgr = _get_manager(cluster_info, util.get_ip_address(), util.read_executor_id())\n try:\n queue_in = mgr.get_queue(qname)\n equeue = mgr.get_queue('error')\n except (AttributeError, KeyError):\n msg = \"Queue '{}' not found on this node, check for exceptions on other nodes.\".format(qname)\n raise Exception(msg)\n\n logger.info(\"Feeding partition {0} into {1} queue {2}\".format(iter, qname, queue_in))\n count = 0\n for item in iter:\n count += 1\n queue_in.put(item, block=True)\n\n # signal \"end of partition\"\n queue_in.put(marker.EndPartition())\n\n # skip empty partitions\n if count == 0:\n return []\n\n # wait for consumers to finish processing all items in queue before \"finishing\" this iterator\n joinThr = Thread(target=queue_in.join)\n joinThr.start()\n timeout = feed_timeout\n while (joinThr.isAlive()):\n if (not equeue.empty()):\n e_str = equeue.get()\n raise Exception(\"Exception in worker:\\n\" + e_str)\n time.sleep(1)\n timeout -= 1\n if timeout <= 0:\n raise Exception(\"Timeout while feeding partition\")\n\n logger.info(\"Processed {0} items in partition\".format(count))\n\n # read result queue\n results = []\n queue_out = mgr.get_queue('output')\n while count > 0:\n result = queue_out.get(block=True)\n results.append(result)\n count -= 1\n queue_out.task_done()\n\n logger.info(\"Finished processing partition\")\n return results\n\n return _inference\n\n\ndef shutdown(cluster_info, grace_secs=0, queues=['input']):\n \"\"\"Stops all TensorFlow nodes by feeding ``None`` into the multiprocessing.Queues.\n\n Args:\n :cluster_info: node reservation information for the cluster (e.g. host, executor_id, pid, ports, etc).\n :queues: *INTERNAL_USE*\n\n Returns:\n A nodeRDD.mapPartitions() function\n \"\"\"\n def _shutdown(iter):\n host = util.get_ip_address()\n executor_id = util.read_executor_id()\n\n # reconnect to shared queue\n mgr = _get_manager(cluster_info, host, executor_id)\n\n # send SIGTERM to Tensorboard proc (if running)\n for node in cluster_info:\n if node['host'] == host and node['executor_id'] == executor_id:\n tb_pid = node['tb_pid']\n if tb_pid != 0:\n logger.info(\"Stopping tensorboard (pid={0})\".format(tb_pid))\n subprocess.Popen([\"kill\", str(tb_pid)])\n\n # terminate any listening queues\n logger.info(\"Stopping all queues\")\n for q in queues:\n if q != 'error':\n try:\n queue = mgr.get_queue(q)\n logger.info(\"Feeding None into {0} queue\".format(q))\n queue.put(None, block=True)\n except (AttributeError, KeyError):\n msg = \"Queue '{}' not found on this node, check for exceptions on other nodes.\".format(q)\n raise Exception(msg)\n\n # wait for grace period (after terminating feed queues)\n if grace_secs > 0:\n logger.info(\"Waiting for {} second grace period\".format(grace_secs))\n time.sleep(grace_secs)\n\n # then check for any late exceptions\n equeue = mgr.get_queue('error')\n if (not equeue.empty()):\n # note: \"peek\" this queue, since otherwise Spark might retry this \"failed\" task, find no errors in queue, and finish the job with SUCCESS\n e_str = equeue.get()\n equeue.put(e_str)\n raise Exception(\"Exception in worker:\\n\" + e_str)\n\n logger.info(\"Setting mgr.state to 'stopped'\")\n mgr.set('state', 'stopped')\n return [True]\n\n return _shutdown\n"
] |
[
[
"tensorflow.test.is_built_with_cuda"
]
] |
WangXinglin/BIT_framework
|
[
"1484874fcd00d052c7536789dec95050b480b25d"
] |
[
"BIT_DL/pytorch/core/cell_wrappers.py"
] |
[
"# Copyright 2019 The Texar 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\"\"\"\nTensorFlow-style RNN cell wrappers.\n\"\"\"\n\nimport sys\nfrom typing import Callable, Generic, List, Optional, Tuple, TypeVar, Union\n\nimport torch\nimport torch.nn.functional as F\nfrom torch import nn\n\nfrom BIT_DL.pytorch.core.attention_mechanism import (\n AttentionMechanism, AttentionWrapperState, compute_attention)\nfrom BIT_DL.pytorch.utils import utils\nfrom BIT_DL.pytorch.utils.types import MaybeList\n\n__all__ = [\n 'RNNState',\n 'LSTMState',\n 'HiddenState',\n 'wrap_builtin_cell',\n 'RNNCellBase',\n 'RNNCell',\n 'GRUCell',\n 'LSTMCell',\n 'DropoutWrapper',\n 'ResidualWrapper',\n 'HighwayWrapper',\n 'MultiRNNCell',\n 'AttentionWrapper',\n]\n\nState = TypeVar('State')\nRNNState = torch.Tensor\nLSTMState = Tuple[torch.Tensor, torch.Tensor]\n\nHiddenState = MaybeList[Union[RNNState, LSTMState]]\n\n\ndef wrap_builtin_cell(cell: nn.RNNCellBase):\n r\"\"\"Convert a built-in :torch_nn:`RNNCellBase` derived RNN cell to\n our wrapped version.\n\n Args:\n cell: the RNN cell to wrap around.\n\n Returns:\n The wrapped cell derived from\n :class:`texar.torch.core.cell_wrappers.RNNCellBase`.\n \"\"\"\n # convert cls to corresponding derived wrapper class\n if isinstance(cell, nn.RNNCell):\n self = RNNCellBase.__new__(RNNCell)\n elif isinstance(cell, nn.GRUCell):\n self = RNNCellBase.__new__(GRUCell)\n elif isinstance(cell, nn.LSTMCell):\n self = RNNCellBase.__new__(LSTMCell)\n else:\n raise TypeError(f\"Unrecognized class {type(cell)}.\")\n RNNCellBase.__init__(self, cell)\n return self\n\n\nclass RNNCellBase(nn.Module, Generic[State]):\n r\"\"\"The base class for RNN cells in our framework. Major differences over\n :torch_nn:`RNNCell` are two-fold:\n\n 1. Holds an :torch_nn:`Module` which could either be a built-in\n RNN cell or a wrapped cell instance. This design allows\n :class:`RNNCellBase` to serve as the base class for both vanilla\n cells and wrapped cells.\n\n 2. Adds :meth:`zero_state` method for initialization of hidden states,\n which can also be used to implement batch-specific initialization\n routines.\n \"\"\"\n\n def __init__(self, cell: Union[nn.RNNCellBase, 'RNNCellBase']):\n super().__init__()\n if not isinstance(cell, nn.Module):\n raise ValueError(\"Type of parameter 'cell' must be derived from\"\n \"nn.Module, and has 'input_size' and 'hidden_size'\"\n \"attributes.\")\n self._cell = cell\n\n @property\n def input_size(self) -> int:\n r\"\"\"The number of expected features in the input.\"\"\"\n return self._cell.input_size\n\n @property\n def hidden_size(self) -> int:\n r\"\"\"The number of features in the hidden state.\"\"\"\n return self._cell.hidden_size\n\n @property\n def _param(self) -> nn.Parameter:\n r\"\"\"Convenience method to access a parameter under the module. Useful\n when creating tensors of the same attributes using `param.new_*`.\n \"\"\"\n return next(self.parameters())\n\n def init_batch(self):\n r\"\"\"Perform batch-specific initialization routines. For most cells this\n is a no-op.\n \"\"\"\n pass\n\n def zero_state(self, batch_size: int) -> State:\n r\"\"\"Return zero-filled state tensor(s).\n\n Args:\n batch_size: int, the batch size.\n\n Returns:\n State tensor(s) initialized to zeros. Note that different subclasses\n might return tensors of different shapes and structures.\n \"\"\"\n self.init_batch()\n if isinstance(self._cell, nn.RNNCellBase):\n state = self._param.new_zeros(\n batch_size, self.hidden_size, requires_grad=False)\n else:\n state = self._cell.zero_state(batch_size)\n return state\n\n def forward(self, # type: ignore\n input: torch.Tensor, state: Optional[State] = None) \\\n -> Tuple[torch.Tensor, State]:\n r\"\"\"\n Returns:\n A tuple of (output, state). For single layer RNNs, output is\n the same as state.\n \"\"\"\n if state is None:\n batch_size = input.size(0)\n state = self.zero_state(batch_size)\n return self._cell(input, state)\n\n\nclass BuiltinCellWrapper(RNNCellBase[State]):\n r\"\"\"Base class for wrappers over built-in :torch_nn:`RNNCellBase`\n RNN cells.\n \"\"\"\n\n def forward(self, # type: ignore\n input: torch.Tensor, state: Optional[State] = None) \\\n -> Tuple[torch.Tensor, State]:\n if state is None:\n batch_size = input.size(0)\n state = self.zero_state(batch_size)\n new_state = self._cell(input, state)\n return new_state, new_state\n\n\nclass RNNCell(BuiltinCellWrapper[RNNState]):\n r\"\"\"A wrapper over :torch_nn:`RNNCell`.\"\"\"\n\n def __init__(self, input_size, hidden_size, bias=True, nonlinearity=\"tanh\"):\n cell = nn.RNNCell(\n input_size, hidden_size, bias=bias, nonlinearity=nonlinearity)\n super().__init__(cell)\n\n\nclass GRUCell(BuiltinCellWrapper[RNNState]):\n r\"\"\"A wrapper over :torch_nn:`GRUCell`.\"\"\"\n\n def __init__(self, input_size, hidden_size, bias=True):\n cell = nn.GRUCell(input_size, hidden_size, bias=bias)\n super().__init__(cell)\n\n\nclass LSTMCell(BuiltinCellWrapper[LSTMState]):\n r\"\"\"A wrapper over :torch_nn:`LSTMCell`, additionally providing the\n option to initialize the forget-gate bias to a constant value.\n \"\"\"\n\n def __init__(self, input_size, hidden_size, bias=True,\n forget_bias: Optional[float] = None):\n if forget_bias is not None and not bias:\n raise ValueError(\"Parameter 'forget_bias' must be set to None when\"\n \"'bias' is set to False.\")\n cell = nn.LSTMCell(input_size, hidden_size, bias=bias)\n if forget_bias is not None:\n with torch.no_grad():\n cell.bias_ih[hidden_size:(2 * hidden_size)].fill_(forget_bias)\n cell.bias_hh[hidden_size:(2 * hidden_size)].fill_(forget_bias)\n super().__init__(cell)\n\n def zero_state(self, batch_size: int) -> LSTMState:\n r\"\"\"Returns the zero state for LSTMs as (h, c).\"\"\"\n state = self._param.new_zeros(\n batch_size, self.hidden_size, requires_grad=False)\n return state, state\n\n def forward(self, # type: ignore\n input: torch.Tensor, state: Optional[LSTMState] = None) \\\n -> Tuple[torch.Tensor, LSTMState]:\n if state is None:\n batch_size = input.size(0)\n state = self.zero_state(batch_size)\n new_state = self._cell(input, state)\n return new_state[0], new_state\n\n\nclass DropoutWrapper(RNNCellBase[State]):\n r\"\"\"Operator adding dropout to inputs and outputs of the given cell.\"\"\"\n\n def __init__(self, cell: RNNCellBase[State],\n input_keep_prob: float = 1.0,\n output_keep_prob: float = 1.0,\n state_keep_prob: float = 1.0,\n variational_recurrent=False):\n r\"\"\"Create a cell with added input, state, and/or output dropout.\n\n If `variational_recurrent` is set to `True` (**NOT** the default\n behavior), then the same dropout mask is applied at every step, as\n described in:\n\n Y. Gal, Z Ghahramani. \"A Theoretically Grounded Application of Dropout\n in Recurrent Neural Networks\". https://arxiv.org/abs/1512.05287\n\n Otherwise a different dropout mask is applied at every time step.\n\n Note, by default (unless a custom `dropout_state_filter` is provided),\n the memory state (`c` component of any `LSTMStateTuple`) passing through\n a `DropoutWrapper` is never modified. This behavior is described in the\n above article.\n\n Args:\n cell: an RNNCell.\n input_keep_prob: float between 0 and 1, input keep probability;\n if it is constant and 1, no input dropout will be added.\n output_keep_prob: float between 0 and 1, output keep probability;\n if it is constant and 1, no output dropout will be added.\n state_keep_prob: float between 0 and 1, output keep probability;\n if it is constant and 1, no output dropout will be added.\n State dropout is performed on the outgoing states of the cell.\n variational_recurrent: bool. If `True`, then the same dropout\n pattern is applied across all time steps for one batch. This is\n implemented by initializing dropout masks in :meth:`zero_state`.\n \"\"\"\n super().__init__(cell)\n\n for prob, attr in [(input_keep_prob, \"input_keep_prob\"),\n (state_keep_prob, \"state_keep_prob\"),\n (output_keep_prob, \"output_keep_prob\")]:\n if prob < 0.0 or prob > 1.0:\n raise ValueError(\n f\"Parameter '{attr}' must be between 0 and 1: {prob:d}\")\n\n self._input_keep_prob = input_keep_prob\n self._output_keep_prob = output_keep_prob\n self._state_keep_prob = state_keep_prob\n\n self._variational_recurrent = variational_recurrent\n self._recurrent_input_mask: Optional[torch.Tensor] = None\n self._recurrent_output_mask: Optional[torch.Tensor] = None\n self._recurrent_state_mask: Optional[torch.Tensor] = None\n\n def _new_mask(self, batch_size: int, mask_size: int,\n prob: float) -> torch.Tensor:\n return self._param.new_zeros(batch_size, mask_size).bernoulli_(prob)\n\n def init_batch(self):\n r\"\"\"Initialize dropout masks for variational dropout.\n\n Note that we do not create dropout mask here, because the batch size\n may not be known until actual input is passed in.\n \"\"\"\n self._recurrent_input_mask = None\n self._recurrent_output_mask = None\n self._recurrent_state_mask = None\n\n def _dropout(self, tensor: torch.Tensor, keep_prob: float,\n mask: Optional[torch.Tensor] = None) -> torch.Tensor:\n r\"\"\"Decides whether to perform standard dropout or recurrent dropout.\"\"\"\n if keep_prob == 1.0 or not self.training:\n return tensor\n if mask is not None:\n return tensor.mul(mask).mul(1.0 / keep_prob)\n return F.dropout(tensor, 1.0 - keep_prob, self.training)\n\n def forward(self, # type: ignore\n input: torch.Tensor, state: Optional[State] = None) \\\n -> Tuple[torch.Tensor, State]:\n if self.training and self._variational_recurrent:\n # Create or check recurrent masks.\n batch_size = input.size(0)\n for name, size in [('input', self.input_size),\n ('output', self.hidden_size),\n ('state', self.hidden_size)]:\n prob = getattr(self, f'_{name}_keep_prob')\n if prob == 1.0:\n continue\n mask = getattr(self, f'_recurrent_{name}_mask')\n if mask is None:\n # Initialize the mask according to current batch size.\n mask = self._new_mask(batch_size, size, prob)\n setattr(self, f'_recurrent_{name}_mask', mask)\n else:\n # Check that size matches.\n if mask.size(0) != batch_size:\n raise ValueError(\n \"Variational recurrent dropout mask does not \"\n \"support variable batch sizes across time steps\")\n\n input = self._dropout(input, self._input_keep_prob,\n self._recurrent_input_mask)\n output, new_state = super().forward(input, state)\n output = self._dropout(output, self._output_keep_prob,\n self._recurrent_output_mask)\n new_state = utils.map_structure(\n lambda x: self._dropout(\n x, self._state_keep_prob, self._recurrent_state_mask),\n new_state)\n return output, new_state\n\n\nclass ResidualWrapper(RNNCellBase[State]):\n r\"\"\"RNNCell wrapper that ensures cell inputs are added to the outputs.\"\"\"\n\n def forward(self, # type: ignore\n input: torch.Tensor, state: Optional[State] = None) \\\n -> Tuple[torch.Tensor, State]:\n output, new_state = super().forward(input, state)\n output = input + output\n return output, new_state\n\n\nclass HighwayWrapper(RNNCellBase[State]):\n r\"\"\"RNNCell wrapper that adds highway connection on cell input and output.\n\n Based on: `R. K. Srivastava, K. Greff, and J. Schmidhuber, \"Highway\n networks\", arXiv preprint arXiv:1505.00387, 2015.`\n https://arxiv.org/pdf/1505.00387.pdf\n \"\"\"\n\n def __init__(self, cell: RNNCellBase[State],\n carry_bias_init: Optional[float] = None,\n couple_carry_transform_gates: bool = True):\n r\"\"\"Constructs a `HighwayWrapper` for `cell`.\n\n Args:\n cell: An instance of `RNNCell`.\n carry_bias_init: float, carry gates bias initialization.\n couple_carry_transform_gates: boolean, should the Carry and\n Transform gate be coupled.\n \"\"\"\n super().__init__(cell)\n\n self.carry = nn.Linear(self.input_size, self.input_size)\n if not couple_carry_transform_gates:\n self.transform = nn.Linear(self.input_size, self.input_size)\n\n self._coupled = couple_carry_transform_gates\n if carry_bias_init is not None:\n nn.init.constant_(self.carry.bias, carry_bias_init)\n if not couple_carry_transform_gates:\n nn.init.constant_(self.transform.bias, -carry_bias_init)\n\n def forward(self, # type: ignore\n input: torch.Tensor, state: Optional[State] = None) \\\n -> Tuple[torch.Tensor, State]:\n output, new_state = super().forward(input, state)\n carry = torch.sigmoid(self.carry(input))\n if self._coupled:\n transform = 1 - carry\n else:\n transform = torch.sigmoid(self.transform(input))\n output = input * carry + output * transform\n return output, new_state\n\n\nclass MultiRNNCell(RNNCellBase[List[State]]):\n r\"\"\"RNN cell composed sequentially of multiple simple cells.\n\n .. code-block:: python\n\n sizes = [128, 128, 64]\n cells = [BasicLSTMCell(input_size, hidden_size)\n for input_size, hidden_size in zip(sizes[:-1], sizes[1:])]\n stacked_rnn_cell = MultiRNNCell(cells)\n \"\"\"\n\n _cell: nn.ModuleList # type: ignore\n\n def __init__(self, cells: List[RNNCellBase[State]]):\n r\"\"\"Create a RNN cell composed sequentially of a number of RNNCells.\n\n Args:\n cells: list of RNNCells that will be composed in this order.\n\n Raises:\n ValueError: if cells is empty (not allowed).\n \"\"\"\n if len(cells) == 0:\n raise ValueError(\"Parameter 'cells' should not be empty.\")\n cell = nn.ModuleList(cells)\n super().__init__(cell) # type: ignore\n\n @property\n def input_size(self):\n return self._cell[0].input_size\n\n @property\n def hidden_size(self):\n return self._cell[-1].hidden_size\n\n def init_batch(self):\n for cell in self._cell:\n cell.init_batch()\n\n def zero_state(self, batch_size: int) -> List[State]:\n states = [cell.zero_state(batch_size) # type: ignore\n for cell in self._cell]\n return states\n\n def forward(self, # type: ignore\n input: torch.Tensor,\n state: Optional[List[State]] = None) \\\n -> Tuple[torch.Tensor, List[State]]:\n r\"\"\"Run this multi-layer cell on inputs, starting from state.\"\"\"\n if state is None:\n batch_size = input.size(0)\n state = self.zero_state(batch_size)\n new_states = []\n output = input\n for cell, hx in zip(self._cell, state):\n output, new_state = cell(output, hx)\n new_states.append(new_state)\n return output, new_states\n\n\nclass AttentionWrapper(RNNCellBase[AttentionWrapperState]):\n r\"\"\"Wraps another `RNNCell` with attention.\"\"\"\n\n def __init__(self,\n cell: RNNCellBase,\n attention_mechanism: MaybeList[AttentionMechanism],\n attention_layer_size: Optional[MaybeList[int]] = None,\n alignment_history: bool = False,\n cell_input_fn: Optional[Callable[[torch.Tensor, torch.Tensor],\n torch.Tensor]] = None,\n output_attention: bool = True):\n r\"\"\"Wraps RNN cell with attention.\n Construct the `AttentionWrapper`.\n\n Args:\n cell: An instance of RNN cell.\n attention_mechanism: A list of\n :class:`~texar.torch.core.AttentionMechanism` instances or a\n single instance.\n attention_layer_size: A list of Python integers or a single Python\n integer, the depth of the attention (output) layer(s). If None\n (default), use the context as attention at each time step.\n Otherwise, feed the context and cell output into the attention\n layer to generate attention at each time step. If\n attention_mechanism is a list, attention_layer_size must be a\n list of the same length.\n alignment_history (bool): whether to store alignment\n history from all time steps in the final output state.\n cell_input_fn (optional): A `callable`. The default is:\n `lambda inputs, attention: array_ops.concat([inputs, attention],\n -1)`.\n output_attention (bool): If `True` (default), the output at\n each time step is the attention value. This is the behavior of\n Luong-style attention mechanisms. If `False`, the output at\n each time step is the output of `cell`. This is the behavior\n of Bahdanau-style attention mechanisms. In both cases, the\n `attention` tensor is propagated to the next time step via the\n state and is used there. This flag only controls whether the\n attention mechanism is propagated up to the next cell in an RNN\n stack or to the top RNN output.\n\n Raises:\n TypeError: :attr:`attention_layer_size` is not None and\n `attention_mechanism` is a list but\n :attr:`attention_layer_size` is not; or vice versa.\n ValueError: if `attention_layer_size` is not None,\n :attr:`attention_mechanism` is a list, and its length does not\n match that of :attr:`attention_layer_size`; if\n :attr:`attention_layer_size` and `attention_layer` are set\n simultaneously.\n \"\"\"\n super().__init__(cell)\n\n self._is_multi: bool\n if isinstance(attention_mechanism, (list, tuple)):\n self._is_multi = True\n attention_mechanisms = attention_mechanism\n for mechanism in attention_mechanisms:\n if not isinstance(mechanism, AttentionMechanism):\n raise TypeError(\n \"attention_mechanism must contain only instances of \"\n \"AttentionMechanism, saw type: %s\" %\n type(mechanism).__name__)\n else:\n self._is_multi = False\n if not isinstance(attention_mechanism, AttentionMechanism):\n raise TypeError(\n \"attention_mechanism must be an AttentionMechanism or list \"\n \"of multiple AttentionMechanism instances, saw type: %s\" %\n type(attention_mechanism).__name__)\n attention_mechanisms = [attention_mechanism]\n\n if cell_input_fn is None:\n cell_input_fn = (\n lambda inputs, attention: torch.cat((inputs, attention),\n dim=-1))\n else:\n if not callable(cell_input_fn):\n raise TypeError(\n \"cell_input_fn must be callable, saw type: %s\" %\n type(cell_input_fn).__name__)\n\n self._attention_layers: Optional[nn.ModuleList]\n\n if attention_layer_size is not None:\n if isinstance(attention_layer_size, (list, tuple)):\n attention_layer_sizes = tuple(attention_layer_size)\n else:\n attention_layer_sizes = (attention_layer_size,)\n\n if len(attention_layer_sizes) != len(attention_mechanisms):\n raise ValueError(\n \"If provided, attention_layer_size must contain exactly \"\n \"one integer per attention_mechanism, saw: %d vs %d\"\n % (len(attention_layer_sizes), len(attention_mechanisms)))\n\n self._attention_layers = nn.ModuleList(\n nn.Linear(attention_mechanisms[i].encoder_output_size +\n cell.hidden_size,\n attention_layer_sizes[i],\n False) for i in range(len(attention_layer_sizes)))\n self._attention_layer_size = sum(attention_layer_sizes)\n else:\n self._attention_layers = None\n self._attention_layer_size = sum(\n attention_mechanism.encoder_output_size\n for attention_mechanism in attention_mechanisms)\n\n self._cell = cell\n self.attention_mechanisms = attention_mechanisms\n self._cell_input_fn = cell_input_fn\n self._output_attention = output_attention\n self._alignment_history = alignment_history\n self._initial_cell_state = None\n\n def _item_or_tuple(self, seq):\n r\"\"\"Returns `seq` as tuple or the singular element.\n Which is returned is determined by how the AttentionMechanism(s) were\n passed to the constructor.\n\n Args:\n seq: A non-empty sequence of items or generator.\n\n Returns:\n Either the values in the sequence as a tuple if\n AttentionMechanism(s) were passed to the constructor as a sequence\n or the singular element.\n \"\"\"\n t = tuple(seq)\n if self._is_multi:\n return t\n else:\n return t[0]\n\n @property\n def output_size(self) -> int:\n r\"\"\"The number of features in the output tensor.\"\"\"\n if self._output_attention:\n return self._attention_layer_size\n else:\n return self._cell.hidden_size\n\n def zero_state(self,\n batch_size: int) -> AttentionWrapperState:\n r\"\"\"Return an initial (zero) state tuple for this\n :class:`AttentionWrapper`.\n\n .. note::\n Please see the initializer documentation for details of how\n to call :meth:`zero_state` if using an\n :class:`~texar.torch.core.AttentionWrapper` with a\n :class:`~texar.torch.modules.BeamSearchDecoder`.\n\n Args:\n batch_size: `0D` integer: the batch size.\n\n Returns:\n An :class:`~texar.torch.core.AttentionWrapperState` tuple containing\n zeroed out tensors and Python lists.\n \"\"\"\n cell_state: torch.Tensor = super().zero_state(batch_size) # type:ignore\n\n initial_alignments = [None for _ in self.attention_mechanisms]\n\n alignment_history: List[List[Optional[torch.Tensor]]]\n alignment_history = [[] for _ in initial_alignments]\n\n return AttentionWrapperState(\n cell_state=cell_state,\n time=0,\n attention=self._param.new_zeros(batch_size,\n self._attention_layer_size,\n requires_grad=False),\n alignments=self._item_or_tuple(initial_alignments),\n attention_state=self._item_or_tuple(initial_alignments),\n alignment_history=self._item_or_tuple(alignment_history))\n\n def forward(self, # type: ignore\n inputs: torch.Tensor,\n state: Optional[AttentionWrapperState],\n memory: torch.Tensor,\n memory_sequence_length: Optional[torch.LongTensor] = None) -> \\\n Tuple[torch.Tensor, AttentionWrapperState]:\n r\"\"\"Perform a step of attention-wrapped RNN.\n\n - Step 1: Mix the :attr:`inputs` and previous step's `attention` output\n via `cell_input_fn`.\n - Step 2: Call the wrapped `cell` with this input and its previous\n state.\n - Step 3: Score the cell's output with `attention_mechanism`.\n - Step 4: Calculate the alignments by passing the score through the\n `normalizer`.\n - Step 5: Calculate the context vector as the inner product between the\n alignments and the attention_mechanism's values (memory).\n - Step 6: Calculate the attention output by concatenating the cell\n output and context through the attention layer (a linear layer with\n `attention_layer_size` outputs).\n\n Args:\n inputs: (Possibly nested tuple of) Tensor, the input at this time\n step.\n state: An instance of\n :class:`~texar.torch.core.AttentionWrapperState` containing\n tensors from the previous time step.\n memory: The memory to query; usually the output of an RNN encoder.\n This tensor should be shaped `[batch_size, max_time, ...]`.\n memory_sequence_length: (optional) Sequence lengths for the batch\n entries in memory. If provided, the memory tensor rows are\n masked with zeros for values past the respective sequence\n lengths.\n\n Returns:\n A tuple `(attention_or_cell_output, next_state)`, where\n\n - `attention_or_cell_output` depending on `output_attention`.\n - `next_state` is an instance of\n :class:`~texar.torch.core.AttentionWrapperState` containing the\n state calculated at this time step.\n\n Raises:\n TypeError: If `state` is not an instance of\n :class:`~texar.torch.core.AttentionWrapperState`.\n \"\"\"\n if state is None:\n state = self.zero_state(batch_size=memory.shape[0])\n elif not isinstance(state, AttentionWrapperState):\n raise TypeError(\"Expected state to be instance of \"\n \"AttentionWrapperState. Received type %s instead.\"\n % type(state))\n\n # Step 1: Calculate the true inputs to the cell based on the\n # previous attention value.\n cell_inputs = self._cell_input_fn(inputs, state.attention)\n cell_state = state.cell_state\n\n cell_output, next_cell_state = self._cell(cell_inputs, cell_state)\n\n if self._is_multi:\n previous_attention_state = state.attention_state\n previous_alignment_history = state.alignment_history\n else:\n previous_attention_state = [state.attention_state] # type: ignore\n previous_alignment_history = \\\n [state.alignment_history] # type: ignore\n\n all_alignments = []\n all_attentions = []\n all_attention_states = []\n maybe_all_histories = []\n for i, attention_mechanism in enumerate(self.attention_mechanisms):\n if previous_attention_state[i] is not None:\n attention_state = previous_attention_state[i]\n else:\n attention_state = attention_mechanism.initial_state(\n memory.shape[0], memory.shape[1], self._param.dtype,\n self._param.device)\n\n attention, alignments, next_attention_state = compute_attention(\n attention_mechanism=attention_mechanism,\n cell_output=cell_output,\n attention_state=attention_state,\n attention_layer=(self._attention_layers[i]\n if self._attention_layers else None),\n memory=memory,\n memory_sequence_length=memory_sequence_length)\n\n if self._alignment_history:\n alignment_history = previous_alignment_history[i] + [alignments]\n else:\n alignment_history = previous_alignment_history[i]\n\n all_attention_states.append(next_attention_state)\n all_alignments.append(alignments)\n all_attentions.append(attention)\n maybe_all_histories.append(alignment_history)\n\n attention = torch.cat(all_attentions, 1)\n next_state = AttentionWrapperState(\n time=state.time + 1,\n cell_state=next_cell_state,\n attention=attention,\n attention_state=self._item_or_tuple(all_attention_states),\n alignments=self._item_or_tuple(all_alignments),\n alignment_history=self._item_or_tuple(maybe_all_histories))\n\n if self._output_attention:\n return attention, next_state\n else:\n return cell_output, next_state\n"
] |
[
[
"torch.nn.functional.dropout",
"torch.cat",
"torch.nn.init.constant_",
"torch.nn.ModuleList",
"torch.nn.LSTMCell",
"torch.nn.Linear",
"torch.no_grad",
"torch.nn.RNNCell",
"torch.nn.GRUCell"
]
] |
Derek-Xiao/LightGBM
|
[
"1b7643ba60e0add0d8ddf55d4baaedca1f6362b5"
] |
[
"examples/python-guide/advanced_example.py"
] |
[
"# coding: utf-8\n# pylint: disable = invalid-name, C0111\nimport lightgbm as lgb\nimport pandas as pd\nimport numpy as np\n\n# load or create your dataset\nprint('Load data...')\ndf_train = pd.read_csv('../binary_classification/binary.train', header=None, sep='\\t')\ndf_test = pd.read_csv('../binary_classification/binary.test', header=None, sep='\\t')\nW_train = pd.read_csv('../binary_classification/binary.train.weight', header=None)[0]\nW_test = pd.read_csv('../binary_classification/binary.test.weight', header=None)[0]\n\ny_train = df_train[0]\ny_test = df_test[0]\nX_train = df_train.drop(0, axis=1)\nX_test = df_test.drop(0, axis=1)\n\nnum_train, num_feature = X_train.shape\n\n# create dataset for lightgbm\n# if you want to re-use data, remember to set free_raw_data=False\nlgb_train = lgb.Dataset(X_train, y_train,\n weight=W_train, free_raw_data=False)\nlgb_eval = lgb.Dataset(X_test, y_test, reference=lgb_train,\n weight=W_test, free_raw_data=False)\n\n# specify your configurations as a dict\nparams = {\n 'boosting_type': 'gbdt',\n 'objective': 'binary',\n 'metric': 'binary_logloss',\n 'num_leaves': 31,\n 'learning_rate': 0.05,\n 'feature_fraction': 0.9,\n 'bagging_fraction': 0.8,\n 'bagging_freq': 5,\n 'verbose': 0\n}\n\n# generate a feature name\nfeature_name = ['feature_' + str(col) for col in range(num_feature)]\n\nprint('Start training...')\n# feature_name and categorical_feature\ngbm = lgb.train(params,\n lgb_train,\n num_boost_round=10,\n valid_sets=lgb_train, # eval training data\n feature_name=feature_name,\n categorical_feature=[21])\n\n# check feature name\nprint('Finish first 10 rounds...')\nprint('7th feature name is:', repr(lgb_train.feature_name[6]))\n\n# save model to file\ngbm.save_model('model.txt')\n\n# continue training\n# init_model accepts:\n# 1. model file name\n# 2. Booster()\ngbm = lgb.train(params,\n lgb_train,\n num_boost_round=10,\n init_model='model.txt',\n valid_sets=lgb_eval)\n\nprint('Finish 10 - 20 rounds with model file...')\n\n# decay learning rates\n# learning_rates accepts:\n# 1. list/tuple with length = num_boost_round\n# 2. function(curr_iter)\ngbm = lgb.train(params,\n lgb_train,\n num_boost_round=10,\n init_model=gbm,\n learning_rates=lambda iter: 0.05 * (0.99 ** iter),\n valid_sets=lgb_eval)\n\nprint('Finish 20 - 30 rounds with decay learning rates...')\n\n# change other parameters during training\ngbm = lgb.train(params,\n lgb_train,\n num_boost_round=10,\n init_model=gbm,\n valid_sets=lgb_eval,\n callbacks=[lgb.reset_parameter(bagging_fraction=[0.7] * 5 + [0.6] * 5)])\n\nprint('Finish 30 - 40 rounds with changing bagging_fraction...')\n\n\n# self-defined objective function\n# f(preds: array, train_data: Dataset) -> grad: array, hess: array\n# log likelihood loss\ndef loglikelood(preds, train_data):\n labels = train_data.get_label()\n preds = 1. / (1. + np.exp(-preds))\n grad = preds - labels\n hess = preds * (1. - preds)\n return grad, hess\n\n\n# self-defined eval metric\n# f(preds: array, train_data: Dataset) -> name: string, value: array, is_higher_better: bool\n# binary error\ndef binary_error(preds, train_data):\n labels = train_data.get_label()\n return 'error', np.mean(labels != (preds > 0.5)), False\n\n\ngbm = lgb.train(params,\n lgb_train,\n num_boost_round=10,\n init_model=gbm,\n fobj=loglikelood,\n feval=binary_error,\n valid_sets=lgb_eval)\n\nprint('Finish 40 - 50 rounds with self-defined objective function and eval metric...')\n\nprint('Start a new training job...')\n\n\n# callback\ndef reset_metrics():\n def callback(env):\n lgb_eval_new = lgb.Dataset(X_test, y_test, reference=lgb_train)\n if env.iteration - env.begin_iteration == 5:\n print('Add a new valid dataset at iteration 5...')\n env.model.add_valid(lgb_eval_new, 'new valid')\n callback.before_iteration = True\n callback.order = 0\n return callback\n\n\ngbm = lgb.train(params,\n lgb_train,\n num_boost_round=10,\n valid_sets=lgb_train,\n callbacks=[reset_metrics()])\n\nprint('Finish first 10 rounds with callback function...')\n"
] |
[
[
"numpy.exp",
"pandas.read_csv",
"numpy.mean"
]
] |
rizwandel/haystack
|
[
"892ce4a760c6b7d7d108aa01eee985ab6ecf8483"
] |
[
"haystack/nodes/reader/table.py"
] |
[
"from typing import List, Optional, Tuple, Dict\n\nimport logging\nfrom statistics import mean\nimport torch\nimport numpy as np\nimport pandas as pd\nfrom quantulum3 import parser\nfrom transformers import pipeline, TapasTokenizer, TapasForQuestionAnswering, BatchEncoding\n\nfrom haystack.schema import Document, Answer, Span\nfrom haystack.nodes.reader.base import BaseReader\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass TableReader(BaseReader):\n \"\"\"\n Transformer-based model for extractive Question Answering on Tables with TaPas\n using the HuggingFace's transformers framework (https://github.com/huggingface/transformers).\n With this reader, you can directly get predictions via predict()\n\n Example:\n ```python\n from haystack import Document\n from haystack.reader import TableReader\n import pandas as pd\n\n table_reader = TableReader(model_name_or_path=\"google/tapas-base-finetuned-wtq\")\n data = {\n \"actors\": [\"brad pitt\", \"leonardo di caprio\", \"george clooney\"],\n \"age\": [\"57\", \"46\", \"60\"],\n \"number of movies\": [\"87\", \"53\", \"69\"],\n \"date of birth\": [\"7 february 1967\", \"10 june 1996\", \"28 november 1967\"],\n }\n table = pd.DataFrame(data)\n document = Document(content=table, content_type=\"table\")\n query = \"When was DiCaprio born?\"\n prediction = table_reader.predict(query=query, documents=[document])\n answer = prediction[\"answers\"][0].answer # \"10 june 1996\"\n ```\n \"\"\"\n def __init__(\n self,\n model_name_or_path: str = \"google/tapas-base-finetuned-wtq\",\n model_version: Optional[str] = None,\n tokenizer: Optional[str] = None,\n use_gpu: bool = True,\n top_k: int = 10,\n max_seq_len: int = 256,\n\n ):\n \"\"\"\n Load a TableQA model from Transformers.\n Available models include:\n\n - ``'google/tapas-base-finetuned-wtq`'``\n - ``'google/tapas-base-finetuned-wikisql-supervised``'\n\n See https://huggingface.co/models?pipeline_tag=table-question-answering\n for full list of available TableQA models.\n\n :param model_name_or_path: Directory of a saved model or the name of a public model e.g.\n See https://huggingface.co/models?pipeline_tag=table-question-answering for full list of available models.\n :param model_version: The version of model to use from the HuggingFace model hub. Can be tag name, branch name, or commit hash.\n :param tokenizer: Name of the tokenizer (usually the same as model)\n :param use_gpu: Whether to make use of a GPU (if available).\n :param top_k: The maximum number of answers to return\n :param max_seq_len: Max sequence length of one input table for the model. If the number of tokens of\n query + table exceed max_seq_len, the table will be truncated by removing rows until the\n input size fits the model.\n \"\"\"\n self.model = TapasForQuestionAnswering.from_pretrained(model_name_or_path, revision=model_version)\n if use_gpu and torch.cuda.is_available():\n self.model.to(\"cuda\")\n if tokenizer is None:\n self.tokenizer = TapasTokenizer.from_pretrained(model_name_or_path)\n else:\n self.tokenizer = TapasTokenizer.from_pretrained(tokenizer)\n self.top_k = top_k\n self.max_seq_len = max_seq_len\n self.return_no_answers = False\n\n def predict(self, query: str, documents: List[Document], top_k: Optional[int] = None) -> Dict:\n \"\"\"\n Use loaded TableQA model to find answers for a query in the supplied list of Documents\n of content_type ``'table'``.\n\n Returns dictionary containing query and list of Answer objects sorted by (desc.) score.\n WARNING: The answer scores are not reliable, as they are always extremely high, even if\n a question cannot be answered by a given table.\n\n :param query: Query string\n :param documents: List of Document in which to search for the answer. Documents should be\n of content_type ``'table'``.\n :param top_k: The maximum number of answers to return\n :return: Dict containing query and answers\n \"\"\"\n if top_k is None:\n top_k = self.top_k\n\n answers = []\n for document in documents:\n if document.content_type != \"table\":\n logger.warning(f\"Skipping document with id {document.id} in TableReader, as it is not of type table.\")\n continue\n\n table: pd.DataFrame = document.content\n # Tokenize query and current table\n inputs = self.tokenizer(table=table,\n queries=query,\n max_length=self.max_seq_len,\n return_tensors=\"pt\",\n truncation=True)\n inputs.to(self.model.device)\n # Forward query and table through model and convert logits to predictions\n outputs = self.model(**inputs)\n inputs.to(\"cpu\")\n predicted_answer_coordinates, predicted_aggregation_indices = self.tokenizer.convert_logits_to_predictions(\n inputs,\n outputs.logits.cpu().detach(),\n outputs.logits_aggregation.cpu().detach()\n )\n\n # Get cell values\n current_answer_coordinates = predicted_answer_coordinates[0]\n current_answer_cells = []\n for coordinate in current_answer_coordinates:\n current_answer_cells.append(table.iat[coordinate])\n\n # Get aggregation operator\n current_aggregation_operator = self.model.config.aggregation_labels[predicted_aggregation_indices[0]]\n \n # Calculate answer score\n current_score = self._calculate_answer_score(outputs.logits.cpu().detach(), inputs, current_answer_coordinates)\n\n if current_aggregation_operator == \"NONE\":\n answer_str = \", \".join(current_answer_cells)\n else:\n answer_str = self._aggregate_answers(current_aggregation_operator, current_answer_cells)\n\n answer_offsets = self._calculate_answer_offsets(current_answer_coordinates, table)\n\n answers.append(\n Answer(\n answer=answer_str,\n type=\"extractive\",\n score=current_score,\n context=table,\n offsets_in_document=answer_offsets,\n offsets_in_context=answer_offsets,\n document_id=document.id,\n meta={\"aggregation_operator\": current_aggregation_operator,\n \"answer_cells\": current_answer_cells}\n )\n )\n\n # Sort answers by score and select top-k answers\n answers = sorted(answers, reverse=True)\n answers = answers[:top_k]\n\n results = {\"query\": query,\n \"answers\": answers}\n\n return results\n \n def _calculate_answer_score(self, logits: torch.Tensor, inputs: BatchEncoding,\n answer_coordinates: List[Tuple[int, int]]) -> float:\n \"\"\"\n Calculates the answer score by computing each cell's probability of being part of the answer\n and taking the mean probability of the answer cells.\n \"\"\"\n # Calculate answer score\n # Values over 88.72284 will overflow when passed through exponential, so logits are truncated.\n logits[logits < -88.7] = -88.7\n token_probabilities = 1 / (1 + np.exp(-logits)) * inputs.attention_mask\n\n segment_ids = inputs.token_type_ids[0, :, 0].tolist()\n column_ids = inputs.token_type_ids[0, :, 1].tolist()\n row_ids = inputs.token_type_ids[0, :, 2].tolist()\n all_cell_probabilities = self.tokenizer._get_mean_cell_probs(token_probabilities[0].tolist(), segment_ids,\n row_ids, column_ids)\n # _get_mean_cell_probs seems to index cells by (col, row). DataFrames are, however, indexed by (row, col).\n all_cell_probabilities = {(row, col): prob for (col, row), prob in all_cell_probabilities.items()}\n answer_cell_probabilities = [all_cell_probabilities[coord] for coord in answer_coordinates]\n \n return np.mean(answer_cell_probabilities)\n\n @staticmethod\n def _aggregate_answers(agg_operator: str, answer_cells: List[str]) -> str:\n if agg_operator == \"COUNT\":\n return str(len(answer_cells))\n\n # No aggregation needed as only one cell selected as answer_cells\n if len(answer_cells) == 1:\n return answer_cells[0]\n\n # Parse answer cells in order to aggregate numerical values\n parsed_answer_cells = [parser.parse(cell) for cell in answer_cells]\n # Check if all cells contain at least one numerical value and that all values share the same unit\n if all(parsed_answer_cells) and all(cell[0].unit.name == parsed_answer_cells[0][0].unit.name\n for cell in parsed_answer_cells):\n numerical_values = [cell[0].value for cell in parsed_answer_cells]\n unit = parsed_answer_cells[0][0].unit.symbols[0] if parsed_answer_cells[0][0].unit.symbols else \"\"\n\n if agg_operator == \"SUM\":\n answer_value = sum(numerical_values)\n elif agg_operator == \"AVERAGE\":\n answer_value = mean(numerical_values)\n else:\n return f\"{agg_operator} > {', '.join(answer_cells)}\"\n\n if unit:\n return f\"{str(answer_value)} {unit}\"\n else:\n return str(answer_value)\n\n # Not all selected answer cells contain a numerical value or answer cells don't share the same unit\n else:\n return f\"{agg_operator} > {', '.join(answer_cells)}\"\n\n @staticmethod\n def _calculate_answer_offsets(answer_coordinates: List[Tuple[int, int]], table: pd.DataFrame) -> List[Span]:\n \"\"\"\n Calculates the answer cell offsets of the linearized table based on the\n answer cell coordinates.\n \"\"\"\n answer_offsets = []\n n_rows, n_columns = table.shape\n for coord in answer_coordinates:\n answer_cell_offset = (coord[0] * n_columns) + coord[1]\n answer_offsets.append(Span(start=answer_cell_offset, end=answer_cell_offset + 1))\n \n return answer_offsets\n\n def predict_batch(self, query_doc_list: List[dict], top_k: Optional[int] = None, batch_size: Optional[int] = None):\n raise NotImplementedError(\"Batch prediction not yet available in TableReader.\")\n"
] |
[
[
"numpy.exp",
"numpy.mean",
"torch.cuda.is_available"
]
] |
donaldrauscher/etf-portfolio
|
[
"c85e8d1af376a14f845948754329b1f65fd4d59b"
] |
[
"steps/summary.py"
] |
[
"import luigi, abc, math\nimport pandas as pd\nimport numpy as np\n\n# calculate summary statistics for portfolios\nclass CalcSummary(luigi.Task):\n\n @abc.abstractproperty\n def requires(self):\n pass\n\n @abc.abstractproperty\n def output(self):\n pass\n\n def run(self):\n # bring in inputs\n returns = pd.read_csv(self.input()['etf-returns'].path)\n portfolios = pd.read_csv(self.input()['portfolios'].path)\n\n # aggregate returns for each portfolio-month\n returns2 = portfolios.merge(returns, how=\"left\", on=[\"Ticker\"])\n returns2['Return'] = returns2.Weight * returns2.Return\n returns2 = returns2.groupby(['Portfolio','Month'], as_index = False).agg({'Return':np.sum})\n returns2.column =[x[0] for x in returns2.columns.ravel()]\n returns2.rename(columns = {'Portfolio':'Ticker'}, inplace = True)\n\n # create summary\n keep = ['Portfolio', 'Portfolio_Expected_Return', 'Portfolio_Expected_Var', 'Portfolio_Expected_SD', 'Portfolio_Expected_Sharpe']\n portfolios2 = portfolios[keep].groupby(keep, as_index = False).first()\n portfolios2.rename(columns = {'Portfolio_Expected_Return':'Expected_Return', 'Portfolio_Expected_Var':'Expected_Var', 'Portfolio_Expected_SD':'Expected_SD', 'Portfolio_Expected_Sharpe':'Expected_Sharpe'}, inplace = True)\n\n portfolios3 = returns2.sort_values(by = ['Ticker', 'Month'], ascending = True)\n portfolios3['Cumulative_Return'] = portfolios3.groupby('Ticker')['Return'].transform(lambda x: (1 + x/100).cumprod())\n portfolios3['Cumulative_Return_Max'] = portfolios3.groupby('Ticker')['Cumulative_Return'].cummax()\n portfolios3['Draw_Down'] = 100*(1 - portfolios3.Cumulative_Return / portfolios3.Cumulative_Return_Max)\n\n portfolios3 = portfolios3.groupby('Ticker', as_index = False)\n aggegations = {\n 'Return': {\n 'Actual_Return': lambda x: 100*(np.prod((1 + x/100))**(12/x.size) - 1),\n 'Actual_SD': lambda x: math.sqrt(12) * np.std(x)\n },\n 'Draw_Down': {\n 'Max_Draw_Down': np.max\n }\n }\n portfolios3 = portfolios3.agg(aggegations)\n portfolios3.columns = ['Portfolio'] + [x[1] for x in portfolios3.columns.ravel()[1:]]\n\n portfolios3['Actual_Var'] = portfolios3.Actual_SD**2\n portfolios3['Actual_Sharpe'] = portfolios3.Actual_Return / portfolios3.Actual_SD\n\n summary = portfolios2.merge(portfolios3, how=\"inner\", on=[\"Portfolio\"])\n\n # export\n returns2.to_csv(self.output()['returns-output'].path, index = False)\n summary.to_csv(self.output()['summary-output'].path, index = False)\n"
] |
[
[
"numpy.std",
"numpy.prod"
]
] |
AntonisCSt/jads_kaggle
|
[
"a9f67d6779957d30425de8ff16bfd574a4dcd332"
] |
[
"earthquakes/engineering.py"
] |
[
"import os\nimport gc\nimport numpy as np\nimport pandas as pd\nimport pickle\n\nfrom scipy import signal, stats\nfrom sklearn.linear_model import LinearRegression\nfrom obspy.signal.trigger import classic_sta_lta\n\nfrom common.utils import progress\n\n\ndef find_earthquakes(data, ycol=\"time_to_failure\", chunks=3):\n \"\"\"Find the indices at which an earthquake occurs.\n\n Note, the returned indices indicate the location of the first observation\n that is part of a new cycle. This means it can be used directly for indexing\n to obtain the exact cycles.\n\n data: pd.DataFrame\n The earthquake training data.\n ycol: str, optional, default=\"time_to_failure\"\n The column representing the time until the next failure.\n chunks: int, optional, default=3\n In how many chunks the earthquakes should be found in order to prevent\n memory issues. If the default (3) still leads to problems, try increasing this.\n \"\"\"\n chunk_size = len(data) / chunks\n chunk_indices = [int(chunk_size*i) for i in range(chunks)] + [len(data)]\n\n all_indices = []\n for i in range(chunks):\n progress(\"Finding earthquakes in chunk {}/{}\".format(i + 1, chunks))\n subset = data[ycol].iloc[chunk_indices[i]:chunk_indices[i+1]]\n indices = np.asarray(subset.diff() > 0).nonzero()\n indices = np.array(indices) + i * chunk_size\n all_indices = np.append(all_indices, indices)\n del subset\n gc.collect()\n\n return np.sort([int(x) for x in all_indices])\n\n\ndef save_earthquake_cycles(data, xcol=\"acoustic_data\", ycol=\"time_to_failure\", data_dir=\"../data\"):\n \"\"\"Save the training data as chunks representing one cycle (earthquake to earthquake).\n\n Parameters\n ----------\n data: pd.DataFrame,\n The data with all observations. Must have two columns: one with the measurement\n of the signal and one with the target, i.e., time to the next earthquake.\n xcol: str, optional, default: \"acoustic_data\"\n The column referring to the the signal data.\n ycol: str, optional, default: \"time_to_failure\"\n The column referring to the target value.\n data_dir: str\n Where to save the files.\n \"\"\"\n progress(\"Finding earthquake locations..\")\n indx = find_earthquakes(data, ycol=ycol)\n indx = np.insert(indx, 0, [0])\n indx = np.append(indx, len(data))\n for i in range(len(indx) - 1):\n cycle = data.iloc[indx[i]:indx[i + 1], :]\n cycle.to_pickle(os.path.join(data_dir, \"earthquake_{}.pkl\".format(i)))\n progress(\"Cycle {} saved.\".format(i))\n\n\ndef get_cycle(cycle_nr, xcol=\"acoustic_data\", ycol=\"time_to_failure\", data_dir=\"../data\"):\n \"\"\"Load one earthquake cycle from disk.\n\n cycle_nr: int\n The number of the earthquake you want to load.\n xcol, ycol: str, optional\n The column names of the signal (xcol) and target (ycol). Default to\n xcol=\"acoustic_data\", ycol=\"time_to_failure\".\n data_dir: str, optional, default='../data'\n The directory where the earthquake cycles are stored.\n \"\"\"\n train = pickle.load(open(os.path.join(data_dir, \"earthquake_{}.pkl\".format(cycle_nr)), \"rb\"))\n train_x = train[xcol].values.reshape((len(train), 1))\n train_y = train[ycol].values.reshape((len(train), 1))\n return train_x, train_y\n\n\ndef sequence_generator(data, xcol=\"acoustic_data\", ycol=\"time_to_failure\", size=150000):\n \"\"\"Generator that extracts segments of the signal from the data.\n\n Parameters\n ----------\n data: pd.DataFrame,\n The data with all observations. Must have two columns: one with the measurement\n of the signal and one with the target, i.e., time to the next earthquake.\n xcol: str, optional (default: \"acoustic_data\"),\n The column referring to the the signal data.\n ycol: str, optional (default: \"time_to_failure\"),\n The column referring to the target value.\n size: int, optional (default: 150,000),\n The number of observations to include in a single sequence. Should be left at\n its default to generate sequences similar to the test data.\n\n Returns\n -------\n A generator object that generates tuples like:\n (sequence of 'size' observations of xcol, last corresponding value of ycol).\n \"\"\"\n while True:\n indices = np.random.randint(0, len(data) - size - 1, 10000)\n for idx in indices:\n y = data[ycol].iloc[idx + size - 1]\n x = data[idx:(idx + size)][xcol].values\n yield x, y\n\n\nclass FeatureComputer():\n \"\"\"Class that computes features over a given array of observations.\n\n This is done in a class so that it can be initialized once and can then be used throughout the\n train-validate-test sequence without specifying all the parameters everytime.\n\n Parameters\n ----------\n minimum, maximum, mean, median, std: boolean, optional (default: True),\n Whether to include the corresponding feature.\n quantiles: list of floats,\n The quantiles to compute.\n abs_min, abs_max, abs_mean, abs_median, abs_std: boolean, optional (default: True),\n The same features as above, but calculated over the absolute signal.\n abs_quantiles: list of floats,\n The quantiles to compute over the absolute signal.\n mean_abs_delta, mean_rel_delta: boolean, optional (default: True),\n Whether to compute the average change per observation. For 'mean_rel_delta' it is divided\n by the value of the previous observation, which leads to a change proportion.\n max_to_min: boolean, optional (default: True),\n Whether to compute the rate between the absolute maximum and the absolute minimum.\n count_abs_big: list of floats,\n The thresholds for which it is counted how many times the absolute signal\n exceeds the threshold.\n abs_trend: boolean, optional (default: True),\n Whether to calculate the linear trend of the time series.\n mad: boolean, optional (default: True),\n Whether to calculate the mean absolute deviation of the time series.\n skew: boolean, optional (default: True),\n Whether to calculate the skewness of the time series.\n abs_skew: boolean, optional (default: True),\n Whether to calculate the skewness of the absolute values of the time series.\n kurtosis: boolean, optional (default: True),\n Whether to calculate the kurosis of the time series. The kurtosis\n measures the tailedness of a time series\n abs_kurtosis: boolean, optional (default: True),\n Whether to calculate the kurosis of the absolute values of the time series.\n The kurtosis measures the tailedness of a time series\n hilbert: boolean, optional (default: True),\n Whether to calculate the abs mean in hilbert tranformed space.\n hann: boolean, optional (default: True),\n Whether to calculate the abs mean in hann window.\n corr_length: boolean, optional (default: True),\n Whether to calculate the correlation length based on the first 100 points of autocorrelation function.\n stalta: list of floats,\n The short time average and the long time average over which the short time\n average over long time average is calculated.\n stalta_window: list of floats,\n The short time average and the long time average over which the short time\n average over long time average is calculated per window.\n exp_mov_ave: list of floats,\n The time windows over which the mean of the mean of the exponential\n moving average is calculated.\n exp_mov_ave_window: list of floats,\n The time windows over which the mean of the mean of the exponential\n moving average is calculated per window.\n window: int or None, optional (default: None),\n If given, calculates the features over subsequences of size 'window'.\n array_length: int, optional (default: 150000),\n The array length to expect. Only needed if window is not None.\n\n Returns\n -------\n result: np.array,\n The specified features of the given array.\n\n Notes\n -----\n In order to see which value in the result refers to which feature, see 'self.feature_names'.\n \"\"\"\n feats = [\"minimum\", \"maximum\", \"mean\", \"median\", \"std\", \"abs_min\", \"abs_max\", \"abs_mean\",\n \"abs_median\", \"abs_std\", \"mean_abs_delta\", \"mean_rel_delta\", \"max_to_min\", \"abs_trend\",\n \"mad\", \"skew\", \"abs_skew\", \"kurtosis\", \"abs_kurtosis\", \"hilbert\", \"hann\", \"corr_length\"]\n\n def __init__(self, minimum=True, maximum=True, mean=True, median=True, std=True, quantiles=None,\n abs_min=True, abs_max=True, abs_mean=True, abs_median=True, abs_std=True, abs_quantiles=None,\n mean_abs_delta=True, mean_rel_delta=True, max_to_min=True, count_abs_big=None,\n abs_trend=True, mad=True, skew=True, abs_skew=True, kurtosis=True, abs_kurtosis=True,\n hilbert=True, hann=True, corr_length=True, stalta=None, stalta_window=None, exp_mov_ave=None, exp_mov_ave_window=None,\n window=None, array_length=150000):\n\n self.minimum = minimum\n self.maximum = maximum\n self.mean = mean\n self.median = median\n self.std = std\n self.abs_min = abs_min\n self.abs_max = abs_max\n self.abs_mean = abs_mean\n self.abs_median = abs_median\n self.abs_std = abs_std\n self.mean_abs_delta = mean_abs_delta\n self.mean_rel_delta = mean_rel_delta\n self.max_to_min = max_to_min\n self.abs_trend = abs_trend\n self.mad = mad\n self.skew = skew\n self.abs_skew = abs_skew\n self.kurtosis = kurtosis\n self.abs_kurtosis = abs_kurtosis\n self.hilbert = hilbert\n self.hann = hann\n self.corr_length = corr_length\n\n if quantiles is None:\n self.quantiles = []\n else:\n self.quantiles = quantiles\n\n if abs_quantiles is None:\n self.abs_quantiles = []\n else:\n self.abs_quantiles = abs_quantiles\n\n self.window = window\n\n if count_abs_big is None:\n self.count_abs_big = []\n else:\n self.count_abs_big = count_abs_big\n\n if stalta is None:\n self.stalta = []\n else:\n self.stalta = stalta\n\n if stalta_window is None:\n self.stalta_window = []\n else:\n self.stalta_window = stalta_window\n\n if exp_mov_ave is None:\n self.exp_mov_ave = []\n else:\n self.exp_mov_ave = exp_mov_ave\n\n if exp_mov_ave_window is None:\n self.exp_mov_ave_window = []\n else:\n self.exp_mov_ave_window = exp_mov_ave_window\n\n if self.window is not None:\n self.indicators = np.array(([np.ones(window)*i for i in range(int(np.ceil(array_length/window)))]),\n dtype=int).flatten()\n self.indicators = self.indicators[:array_length]\n assert len(self.indicators) == array_length, \"Lengths do not match\"\n\n self.feature_names = self._infer_names()\n self.n_features = len(self.feature_names)\n\n def _infer_names(self):\n \"\"\"Infer the names of the features that will be calculated.\"\"\"\n quantile_names = [str(q) + \"-quantile\" for q in self.quantiles]\n abs_quantile_names = [str(q) + \"-abs_quantile\" for q in self.abs_quantiles]\n count_abs_big_names = [str(q) + \"-count_big\" for q in self.count_abs_big]\n stalta_names = [\"all_stalta-\" + str(q[0]) + \"-\" + str(q[1]) for q in self.stalta]\n exp_mov_ave_names = [\"all_exp_mov_ave-\" + str(q) for q in self.exp_mov_ave]\n if self.window is not None:\n stalta_names_window = [\"stalta-\" + str(q[0]) + \"-\" + str(q[1]) for q in self.stalta_window]\n exp_mov_ave_names_window = [\"exp_mov_ave-\" + str(q) for q in self.exp_mov_ave_window]\n names = np.array(self.feats)[[self.minimum, self.maximum, self.mean, self.median, self.std,\n self.abs_min, self.abs_max, self.abs_mean, self.abs_median,\n self.abs_std, self.mean_abs_delta, self.mean_rel_delta,\n self.max_to_min, self.abs_trend, self.mad, self.skew, self.abs_skew,\n self.kurtosis, self.abs_kurtosis, self.hilbert, self.hann, self.corr_length]]\n names = names.tolist() + quantile_names + abs_quantile_names + count_abs_big_names\n\n if self.window is not None:\n all_names = [str(i) + \"_\" + name for i in np.unique(self.indicators) for name in names + stalta_names_window + exp_mov_ave_names_window]\n self.result_template_window = np.zeros(int(len(all_names) / len(np.unique(self.indicators))))\n all_names = all_names + [\"all_\" + name for name in names] + stalta_names + exp_mov_ave_names\n self.result_template = np.zeros(len(names + stalta_names + exp_mov_ave_names))\n return all_names\n else:\n all_names = names + stalta_names + exp_mov_ave_names\n self.result_template = np.zeros(len(all_names))\n return all_names\n\n def compute(self, arr):\n if self.window is None:\n return self._compute_features(arr)\n else:\n df = pd.DataFrame({\"arr\": arr, \"indicator\": self.indicators})\n values = (df.groupby(\"indicator\")[\"arr\"]\n .apply(lambda x: self._compute_features(x, window=True))\n .apply(pd.Series)\n .values\n .flatten())\n\n # include values over the whole segment\n overall_values = self._compute_features(arr)\n\n return np.concatenate([values, overall_values])\n\n def _autocorr_length(self, x, num_of_points=80):\n \"\"\"Calculates the correlation length in the\n the first \"num_of_points\" of the autocorrelation function of the x signal.\n correlation length indicates if theere is any correlation between the points of the signal\n low correlation values indicate a very random hight sequence, while\n high correaltion excactly the opposite\n \"\"\"\n x_mean = x.mean()\n x_std = x.std()\n acf = []\n for rx in range(num_of_points):\n ac = 0\n for k in range(num_of_points-rx):\n ac = ac + (x[k] - x_mean) * (x[k+rx] - x_mean)\n acf.append(ac / (num_of_points - rx))\n\n z2 = np.array(acf) / (x_std**2)\n\n def find_y_point(xa, xb, ya, yb, yc):\n m = (ya - yb) / (xa - xb)\n xc = yc / m - yb / m + xb\n return xc\n\n x1 = np.where(z2[0:num_of_points] == z2[0:num_of_points][z2[0:num_of_points] < 0.368][0])[0][0] - 1\n x2 = np.where(z2[0:num_of_points] == z2[0:num_of_points][z2[0:num_of_points] < 0.368][0])[0][0]\n return find_y_point(x1, x2, z2[0:num_of_points][x1], z2[0:num_of_points][x2], 0.368)\n\n def _compute_features(self, arr, window=False):\n if window:\n result = np.zeros_like(self.result_template_window)\n else:\n result = np.zeros_like(self.result_template)\n i = 0\n if self.minimum:\n result[i] = np.min(arr)\n i += 1\n if self.maximum:\n result[i] = np.max(arr)\n i += 1\n if self.mean:\n result[i] = np.mean(arr)\n i += 1\n if self.median:\n result[i] = np.median(arr)\n i += 1\n if self.std:\n result[i] = np.std(arr)\n i += 1\n if self.abs_min:\n result[i] = np.min(np.abs(arr))\n i += 1\n if self.abs_max:\n result[i] = np.max(np.abs(arr))\n i += 1\n if self.abs_mean:\n result[i] = np.mean(np.abs(arr))\n i += 1\n if self.abs_median:\n result[i] = np.median(np.abs(arr))\n i += 1\n if self.abs_std:\n result[i] = np.std(np.abs(arr))\n i += 1\n if self.mean_abs_delta:\n result[i] = np.mean(np.diff(arr))\n i += 1\n if self.mean_rel_delta:\n result[i] = np.mean(np.nonzero((np.diff(arr) / arr[:-1]))[0])\n i += 1\n if self.max_to_min:\n result[i] = np.max(arr) / np.abs(np.min(arr))\n i += 1\n if self.abs_trend:\n idx = np.array(range(len(arr)))\n lr = LinearRegression()\n lr.fit(idx.reshape(-1, 1), np.abs(arr))\n result[i] = lr.coef_[0]\n i += 1\n if self.mad: # mean absolute deviation\n result[i] = np.mean(np.abs(arr - np.mean(arr)))\n i += 1\n if self.skew:\n result[i] = stats.skew(arr)\n i += 1\n if self.abs_skew:\n result[i] = stats.skew(np.abs(arr))\n i += 1\n if self.kurtosis: # measure of tailedness\n result[i] = stats.kurtosis(arr)\n i += 1\n if self.abs_kurtosis: # measure of tailedness\n result[i] = stats.kurtosis(np.abs(arr))\n i += 1\n if self.hilbert: # abs mean in hilbert tranformed space\n result[i] = np.mean(np.abs(signal.hilbert(arr)))\n i += 1\n if self.hann: # mean in hann window\n result[i] = np.mean(signal.convolve(arr, signal.hann(150), mode='same') / np.sum(signal.hann(150)))\n i += 1\n if self.corr_length:\n result[i] = self._autocorr_length(pd.Series(arr).reset_index(drop=True))\n i += 1\n if self.quantiles is not None:\n result[i:i + len(self.quantiles)] = np.quantile(arr, q=self.quantiles)\n i += len(self.quantiles)\n if self.abs_quantiles is not None:\n result[i:i + len(self.abs_quantiles)] = np.quantile(np.abs(arr), q=self.abs_quantiles)\n i += len(self.abs_quantiles)\n if self.count_abs_big is not None:\n result[i: i + len(self.count_abs_big)] = np.array([len(arr[np.abs(arr) > q]) for q in self.count_abs_big])\n i += len(self.count_abs_big)\n if self.stalta:\n if window:\n result[i:i + len(self.stalta_window)] = np.array(\n [np.mean(classic_sta_lta(arr, q[0], q[1])) for q in self.stalta_window])\n i += len(self.stalta_window)\n else:\n result[i:i + len(self.stalta)] = np.array(\n [np.mean(classic_sta_lta(arr, q[0], q[1])) for q in self.stalta])\n i += len(self.stalta)\n if self.exp_mov_ave:\n if window:\n result[i:i + len(self.exp_mov_ave_window)] = np.array(\n [np.mean(pd.Series.ewm(pd.Series(arr), span=q).mean()) for q in self.exp_mov_ave_window])\n i += len(self.exp_mov_ave_window)\n else:\n result[i:i + len(self.exp_mov_ave)] = np.array(\n [np.mean(pd.Series.ewm(pd.Series(arr), span=q).mean()) for q in self.exp_mov_ave])\n i += len(self.exp_mov_ave)\n\n return result\n\n\ndef create_feature_dataset(data, feature_computer, xcol=\"acoustic_data\", ycol=\"time_to_failure\", n_samples=100,\n stft=False, stft_feature_computer=None):\n \"\"\"Samples sequences from the data, computes features for each sequence, and stores the result\n in a new dataframe.\n\n Parameters\n ----------\n data: pd.DataFrame,\n The data with all observations. Must have two columns: one with the measurement\n of the signal and one with the target, i.e., time to the next earthquake.\n feature_computer: FeatureComputer object or similar,\n A class that implements a method '.compute()' that takes an array and returns\n features. It must also have an attribute 'feature_names' that shows the corresponding\n names of the features.\n xcol: str, optional (default: \"acoustic_data\"),\n The column referring to the the signal data.\n ycol: str, optional (default: \"time_to_failure\"),\n The column referring to the target value.\n n_samples: int, optional (default: 100),\n The number of sequences to process and return.\n stft: bool, optional (default: False),\n Whether to calculate the Short Time Fourier Transform.\n stft_feature_computer: FeatureComputer object or None,\n The computer for stft features.\n\n Returns\n -------\n feature_data: pd.DataFrame,\n A new dataframe of shape (n_samples, number of features) with the new features per sequence.\n \"\"\"\n if (stft is True) and (stft_feature_computer is None):\n assert feature_computer.window is None, (\"If stft is True, feature_computer must have window=None or\"\n \"a separate stft_feature_computer must be provided.\")\n stft_feature_computer = feature_computer\n\n new_data = pd.DataFrame({feature: np.zeros(n_samples) for feature in feature_computer.feature_names})\n targets = np.zeros(n_samples)\n data_gen = sequence_generator(data, xcol=xcol, ycol=ycol, size=150000)\n\n if stft:\n new_data_stft = pd.DataFrame({feature + '_stft': np.zeros(n_samples) for feature in stft_feature_computer.feature_names})\n\n for i in range(n_samples):\n x, y = next(data_gen)\n new_data.iloc[i, :] = feature_computer.compute(x)\n targets[i] = y\n\n if stft:\n _, _, zxx = signal.stft(x)\n x_stft = np.sum(np.abs(zxx), axis=0)\n new_data_stft.iloc[i, :] = stft_feature_computer.compute(x_stft)\n\n if stft:\n new_data = pd.concat([new_data, new_data_stft], axis=1)\n\n new_data[ycol] = targets\n return new_data\n"
] |
[
[
"pandas.Series",
"scipy.signal.stft",
"pandas.DataFrame",
"numpy.concatenate",
"numpy.max",
"numpy.zeros_like",
"numpy.mean",
"numpy.where",
"scipy.signal.hilbert",
"numpy.unique",
"numpy.ceil",
"numpy.std",
"numpy.diff",
"numpy.insert",
"scipy.stats.skew",
"numpy.zeros",
"pandas.concat",
"numpy.min",
"numpy.median",
"numpy.quantile",
"numpy.append",
"scipy.stats.kurtosis",
"numpy.array",
"numpy.abs",
"numpy.ones",
"sklearn.linear_model.LinearRegression",
"scipy.signal.hann"
]
] |
kylevedder/Open3D-ML
|
[
"87ec50ed81d531377b1bb27e5c16f964201eadb0"
] |
[
"ml3d/datasets/customdataset.py"
] |
[
"import numpy as np\nimport os, sys, glob, pickle\nfrom pathlib import Path\nfrom os.path import join, exists, dirname, abspath\nimport random\nfrom sklearn.neighbors import KDTree\nfrom tqdm import tqdm\nimport logging\n\nfrom .base_dataset import BaseDataset, BaseDatasetSplit\nfrom ..utils import make_dir, DATASET\n\nlogging.basicConfig(\n level=logging.INFO,\n format='%(levelname)s - %(asctime)s - %(module)s - %(message)s',\n)\nlog = logging.getLogger(__name__)\n\n# Expect point clouds to be in npy format with train, val and test files in separate folders.\n# Expected format of npy files : ['x', 'y', 'z', 'class', 'feat_1', 'feat_2', ........,'feat_n'].\n# For test files, format should be : ['x', 'y', 'z', 'feat_1', 'feat_2', ........,'feat_n'].\n\n\nclass Custom3DSplit(BaseDatasetSplit):\n \"\"\"This class is used to create a custom dataset split.\n\n Initialize the class.\n\n Args:\n dataset: The dataset to split.\n split: A string identifying the dataset split that is usually one of\n 'training', 'test', 'validation', or 'all'.\n **kwargs: The configuration of the model as keyword arguments.\n\n Returns:\n A dataset split object providing the requested subset of the data.\n \"\"\"\n\n def __init__(self, dataset, split='training'):\n super().__init__(dataset, split=split)\n self.cfg = dataset.cfg\n path_list = dataset.get_split_list(split)\n log.info(\"Found {} pointclouds for {}\".format(len(path_list), split))\n\n self.path_list = path_list\n self.split = split\n self.dataset = dataset\n\n def __len__(self):\n return len(self.path_list)\n\n def get_data(self, idx):\n pc_path = self.path_list[idx]\n data = np.load(pc_path)\n points = np.array(data[:, :3], dtype=np.float32)\n\n if (self.split != 'test'):\n labels = np.array(data[:, 3], dtype=np.int32)\n feat = data[:, 4:] if data.shape[1] > 4 else None\n else:\n feat = np.array(data[:, 3:],\n dtype=np.float32) if data.shape[1] > 3 else None\n labels = np.zeros((points.shape[0],), dtype=np.int32)\n\n data = {'point': points, 'feat': feat, 'label': labels}\n\n return data\n\n def get_attr(self, idx):\n pc_path = Path(self.path_list[idx])\n name = pc_path.name.replace('.npy', '')\n\n attr = {'name': name, 'path': str(pc_path), 'split': self.split}\n\n return attr\n\n\nclass Custom3D(BaseDataset):\n \"\"\"A template for customized dataset that you can use with a dataloader to\n feed data when training a model. This inherits all functions from the base\n dataset and can be modified by users. Initialize the function by passing the\n dataset and other details.\n\n Args:\n dataset_path: The path to the dataset to use.\n name: The name of the dataset.\n cache_dir: The directory where the cache is stored.\n use_cache: Indicates if the dataset should be cached.\n num_points: The maximum number of points to use when splitting the dataset.\n ignored_label_inds: A list of labels that should be ignored in the dataset.\n test_result_folder: The folder where the test results should be stored.\n \"\"\"\n\n def __init__(self,\n dataset_path,\n name='Custom3D',\n cache_dir='./logs/cache',\n use_cache=False,\n num_points=65536,\n ignored_label_inds=[],\n test_result_folder='./test',\n **kwargs):\n\n super().__init__(dataset_path=dataset_path,\n name=name,\n cache_dir=cache_dir,\n use_cache=use_cache,\n num_points=num_points,\n ignored_label_inds=ignored_label_inds,\n test_result_folder=test_result_folder,\n **kwargs)\n\n cfg = self.cfg\n\n self.dataset_path = cfg.dataset_path\n self.label_to_names = self.get_label_to_names()\n\n self.num_classes = len(self.label_to_names)\n self.label_values = np.sort([k for k, v in self.label_to_names.items()])\n self.label_to_idx = {l: i for i, l in enumerate(self.label_values)}\n self.ignored_labels = np.array(cfg.ignored_label_inds)\n\n self.train_dir = str(Path(cfg.dataset_path) / cfg.train_dir)\n self.val_dir = str(Path(cfg.dataset_path) / cfg.val_dir)\n self.test_dir = str(Path(cfg.dataset_path) / cfg.test_dir)\n\n self.train_files = [f for f in glob.glob(self.train_dir + \"/*.npy\")]\n self.val_files = [f for f in glob.glob(self.val_dir + \"/*.npy\")]\n self.test_files = [f for f in glob.glob(self.test_dir + \"/*.npy\")]\n\n @staticmethod\n def get_label_to_names():\n \"\"\"Returns a label to names dictionary object.\n\n Returns:\n A dict where keys are label numbers and\n values are the corresponding names.\n \"\"\"\n label_to_names = {\n 0: 'Unclassified',\n 1: 'Ground',\n 2: 'Road_markings',\n 3: 'Natural',\n 4: 'Building',\n 5: 'Utility_line',\n 6: 'Pole',\n 7: 'Car',\n 8: 'Fence'\n }\n return label_to_names\n\n def get_split(self, split):\n \"\"\"Returns a dataset split.\n\n Args:\n split: A string identifying the dataset split that is usually one of\n 'training', 'test', 'validation', or 'all'.\n\n Returns:\n A dataset split object providing the requested subset of the data.\n \"\"\"\n return Custom3DSplit(self, split=split)\n\n def get_split_list(self, split):\n \"\"\"Returns a dataset split.\n\n Args:\n split: A string identifying the dataset split that is usually one of\n 'training', 'test', 'validation', or 'all'.\n\n Returns:\n A dataset split object providing the requested subset of the data.\n\n Raises:\n ValueError: Indicates that the split name passed is incorrect. The\n split name should be one of 'training', 'test', 'validation', or\n 'all'.\n \"\"\"\n if split in ['test', 'testing']:\n random.shuffle(self.test_files)\n return self.test_files\n elif split in ['val', 'validation']:\n random.shuffle(self.val_files)\n return self.val_files\n elif split in ['train', 'training']:\n random.shuffle(self.train_files)\n return self.train_files\n elif split in ['all']:\n files = self.val_files + self.train_files + self.test_files\n return files\n else:\n raise ValueError(\"Invalid split {}\".format(split))\n\n def is_tested(self, attr):\n \"\"\"Checks if a datum in the dataset has been tested.\n\n Args:\n dataset: The current dataset to which the datum belongs to.\n attr: The attribute that needs to be checked.\n\n Returns:\n If the dataum attribute is tested, then return the path where the\n attribute is stored; else, returns false.\n \"\"\"\n cfg = self.cfg\n name = attr['name']\n path = cfg.test_result_folder\n store_path = join(path, self.name, name + '.npy')\n if exists(store_path):\n print(\"{} already exists.\".format(store_path))\n return True\n else:\n return False\n\n def save_test_result(self, results, attr):\n \"\"\"Saves the output of a model.\n\n Args:\n results: The output of a model for the datum associated with the attribute passed.\n attr: The attributes that correspond to the outputs passed in results.\n \"\"\"\n cfg = self.cfg\n name = attr['name']\n path = cfg.test_result_folder\n make_dir(path)\n\n pred = results['predict_labels']\n pred = np.array(self.label_to_names[pred])\n\n store_path = join(path, name + '.npy')\n np.save(store_path, pred)\n\n\nDATASET._register_module(Custom3D)\n"
] |
[
[
"numpy.load",
"numpy.array",
"numpy.zeros",
"numpy.save"
]
] |
tacaswell/mplcairo
|
[
"d9bd1bee87e403d484b6b9ccef8013e7dcb1fb5d"
] |
[
"lib/mplcairo/_backports.py"
] |
[
"import functools\nimport re\n\nfrom matplotlib import dviread\nfrom matplotlib.dviread import PsfontsMap\n\n\[email protected]_cache()\ndef _parse_enc(path):\n r\"\"\"\n Parses a \\*.enc file referenced from a psfonts.map style file.\n The format this class understands is a very limited subset of PostScript.\n\n Parameters\n ----------\n path : os.PathLike\n\n Returns\n -------\n encoding : list\n The nth entry of the list is the PostScript glyph name of the nth\n glyph.\n \"\"\"\n with open(path, encoding=\"ascii\") as file:\n no_comments = \"\\n\".join(line.split(\"%\")[0].rstrip() for line in file)\n array = re.search(r\"(?s)\\[(.*)\\]\", no_comments).group(1)\n return re.findall(r\"(?<=/)[A-za-z0-9._]+\", array)\n\n\ndef get_glyph_name(dvitext):\n tex_font_map = PsfontsMap(dviread.find_tex_file(\"pdftex.map\"))\n ps_font = tex_font_map[dvitext.font.texname]\n return (_parse_enc(ps_font.encoding)[dvitext.glyph]\n if ps_font.encoding is not None else None)\n"
] |
[
[
"matplotlib.dviread.find_tex_file"
]
] |
CMPUT455-Yogo/assignment4
|
[
"88ff8eeef6f35beca79e3bc3fa9eaf283b68ea1e"
] |
[
"random_player/simple_board.py"
] |
[
"\"\"\"\nsimple_board.py\n\nImplements a basic Go board with functions to:\n- initialize to a given board size\n- check if a move is legal\n- play a move\n\nThe board uses a 1-dimensional representation with padding\n\"\"\"\n\nimport numpy as np\nfrom board_util import GoBoardUtil, BLACK, WHITE, EMPTY, BORDER, \\\n is_black_white, coord_to_point, where1d, \\\n MAXSIZE, NULLPOINT\n\nclass SimpleGoBoard(object):\n\n def get_color(self, point):\n return self.board[point]\n\n def pt(self, row, col):\n return coord_to_point(row, col, self.size)\n\n def get_empty_points(self):\n \"\"\"\n Return:\n The empty points on the board\n \"\"\"\n return where1d(self.board == EMPTY)\n\n def __init__(self, size):\n \"\"\"\n Creates a Go board of given size\n \"\"\"\n assert 2 <= size <= MAXSIZE\n self.reset(size)\n\n def reset(self, size):\n \"\"\"\n Creates a start state, an empty board with the given size\n The board is stored as a one-dimensional array\n See GoBoardUtil.coord_to_point for explanations of the array encoding\n \"\"\"\n self.size = size\n self.NS = size + 1\n self.WE = 1\n self.current_player = BLACK\n self.maxpoint = size * size + 3 * (size + 1)\n self.board = np.full(self.maxpoint, BORDER, dtype = np.int32)\n self.liberty_of = np.full(self.maxpoint, NULLPOINT, dtype = np.int32)\n self._initialize_empty_points(self.board)\n self._initialize_neighbors()\n\n def copy(self):\n b = SimpleGoBoard(self.size)\n assert b.NS == self.NS\n assert b.WE == self.WE\n b.current_player = self.current_player\n assert b.maxpoint == self.maxpoint\n b.board = np.copy(self.board)\n return b\n\n def row_start(self, row):\n assert row >= 1\n assert row <= self.size\n return row * self.NS + 1\n \n def _initialize_empty_points(self, board):\n \"\"\"\n Fills points on the board with EMPTY\n Argument\n ---------\n board: numpy array, filled with BORDER\n \"\"\"\n for row in range(1, self.size + 1):\n start = self.row_start(row)\n board[start : start + self.size] = EMPTY\n\n def _on_board_neighbors(self, point):\n nbs = []\n for nb in self._neighbors(point):\n if self.board[nb] != BORDER:\n nbs.append(nb)\n return nbs\n \n def _initialize_neighbors(self):\n \"\"\"\n precompute neighbor array.\n For each point on the board, store its list of on-the-board neighbors\n \"\"\"\n self.neighbors = []\n for point in range(self.maxpoint):\n if self.board[point] == BORDER:\n self.neighbors.append([])\n else:\n self.neighbors.append(self._on_board_neighbors(point))\n \n def _stone_has_liberty(self, stone):\n lib = self.find_neighbor_of_color(stone, EMPTY)\n return lib != None\n\n def _get_liberty(self, block):\n \"\"\"\n Find any liberty of the given block.\n Returns None in case there is no liberty.\n block is a numpy boolean array\n \"\"\"\n for stone in where1d(block):\n lib = self.find_neighbor_of_color(stone, EMPTY)\n if lib != None:\n return lib\n return None\n\n def _has_liberty(self, block):\n \"\"\"\n Check if the given block has any liberty.\n Also updates the liberty_of array.\n block is a numpy boolean array\n \"\"\"\n lib = self._get_liberty(block)\n if lib != None:\n assert self.get_color(lib) == EMPTY\n for stone in where1d(block):\n self.liberty_of[stone] = lib\n return True\n return False\n\n def _block_of(self, stone):\n \"\"\"\n Find the block of given stone\n Returns a board of boolean markers which are set for\n all the points in the block \n \"\"\"\n marker = np.full(self.maxpoint, False, dtype = bool)\n pointstack = [stone]\n color = self.get_color(stone)\n assert is_black_white(color)\n marker[stone] = True\n while pointstack:\n p = pointstack.pop()\n neighbors = self.neighbors_of_color(p, color)\n for nb in neighbors:\n if not marker[nb]:\n marker[nb] = True\n pointstack.append(nb)\n return marker\n\n def _fast_liberty_check(self, nb_point):\n lib = self.liberty_of[nb_point]\n if lib != NULLPOINT and self.get_color(lib) == EMPTY:\n return True # quick exit, block has a liberty \n if self._stone_has_liberty(nb_point):\n return True # quick exit, no need to look at whole block\n return False\n \n def _detect_capture(self, nb_point):\n \"\"\"\n Check whether opponent block on nb_point is captured.\n Returns boolean.\n \"\"\"\n if self._fast_liberty_check(nb_point):\n return False\n opp_block = self._block_of(nb_point)\n return not self._has_liberty(opp_block)\n \n # def is_legal(self, point, color):\n # \"\"\"\n # Check whether it is legal for color to play on point\n # \"\"\"\n # board_copy = self.copy()\n # # Try to play the move on a temporary copy of board\n # # This prevents the board from being messed up by the move\n # try:\n # legal = board_copy.play_move(point, color)\n # except:\n # return False\n \n # return legal\n\n def is_legal(self, point, color):\n \"\"\"\n Check if the move is legal\n \"\"\"\n assert is_black_white(color)\n # Special cases\n if self.board[point] != EMPTY:\n return False \n \n # General case: deal with captures, suicide\n opp_color = GoBoardUtil.opponent(color)\n self.board[point] = color\n neighbors = self.neighbors[point]\n # Captur \n for nb in neighbors:\n if self.board[nb] == opp_color:\n if self._detect_capture(nb):\n self.board[point] = EMPTY\n return False \n # Sucide\n if not self._stone_has_liberty(point):\n # check suicide of whole block\n block = self._block_of(point)\n if not self._has_liberty(block): # undo suicide move\n self.board[point] = EMPTY\n return False \n # Undo \n self.board[point] = EMPTY\n return True\n\n def play_move(self, point, color):\n \"\"\"\n Play a move of color on point\n Returns boolean: whether move was legal\n \"\"\"\n assert is_black_white(color)\n # Special cases\n if self.board[point] != EMPTY:\n return False\n \n # General case: deal with captures, suicide\n opp_color = GoBoardUtil.opponent(color)\n self.board[point] = color\n neighbors = self.neighbors[point]\n for nb in neighbors:\n if self.board[nb] == opp_color and \\\n self._detect_capture(nb):\n self.board[point] = EMPTY # undo capture move\n return False\n if not self._stone_has_liberty(point):\n # check suicide of whole block\n block = self._block_of(point)\n if not self._has_liberty(block):\n self.board[point] = EMPTY # undo suicide move\n return False\n self.current_player = GoBoardUtil.opponent(color)\n return True\n\n def neighbors_of_color(self, point, color):\n \"\"\" List of neighbors of point of given color \"\"\"\n nbc = []\n for nb in self.neighbors[point]:\n if self.get_color(nb) == color:\n nbc.append(nb)\n return nbc\n \n def find_neighbor_of_color(self, point, color):\n \"\"\" Return one neighbor of point of given color, or None \"\"\"\n for nb in self.neighbors[point]:\n if self.get_color(nb) == color:\n return nb\n return None\n \n def _neighbors(self, point):\n \"\"\" List of all four neighbors of the point \"\"\"\n return [point - 1, point + 1, point - self.NS, point + self.NS]\n"
] |
[
[
"numpy.copy",
"numpy.full"
]
] |
dhb2128/pybasicbayes
|
[
"61f65ad6c781288605ec5f7347efcc5dbd73c4fc"
] |
[
"examples/robust_regression.py"
] |
[
"# Demo of a robust regression model with multivariate-t distributed noise\n\nimport numpy as np\nimport numpy.random as npr\nnp.random.seed(0)\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set_style(\"white\")\n\nfrom pybasicbayes.util.text import progprint_xrange\nfrom pybasicbayes.distributions import Regression, RobustRegression\n\nD_out = 1\nD_in = 2\nN = 100\n\n# Make a regression model and simulate data\nA = npr.randn(D_out, D_in)\nb = npr.randn(D_out)\nSigma = 0.1 * np.eye(D_out)\n\ntrue_reg = Regression(A=np.column_stack((A, b)), sigma=Sigma, affine=True)\nX = npr.randn(N, D_in)\ny = true_reg.rvs(x=X, return_xy=False)\n\n# Corrupt a fraction of the data\ninds = npr.rand(N) < 0.1\ny[inds] = 3 * npr.randn(inds.sum(), D_out)\n\n# Make a test regression and fit it\nstd_reg = Regression(nu_0=D_out + 2,\n S_0=np.eye(D_out),\n M_0=np.zeros((D_out, D_in+1)),\n K_0=np.eye(D_in+1),\n affine=True)\n\nrobust_reg = RobustRegression(nu_0=D_out+2,\n S_0=np.eye(D_out),\n M_0=np.zeros((D_out, D_in+1)),\n K_0=np.eye(D_in+1),\n affine=True)\n\ndef _collect(r):\n ll = r.log_likelihood((X, y))[~inds].sum()\n err = ((y - r.predict(X))**2).sum(1)\n mse = np.mean(err[~inds])\n return r.A.copy(), ll, mse\n\ndef _update(r):\n r.resample([(X,y)])\n return _collect(r)\n\n# Fit the standard regression\nsmpls = [_collect(std_reg)]\nfor _ in progprint_xrange(100):\n smpls.append(_update(std_reg))\nsmpls = zip(*smpls)\nstd_As, std_lls, std_mses = tuple(map(np.array, smpls))\n\n# Fit the robust regression\nsmpls = [_collect(robust_reg)]\nfor _ in progprint_xrange(100):\n smpls.append(_update(robust_reg))\nsmpls = zip(*smpls)\nrobust_As, robust_lls, robust_mses = tuple(map(np.array, smpls))\n\n\n# Plot the inferred regression function\nplt.figure(figsize=(8, 4))\nxlim = (-3, 3)\nylim = abs(y).max()\nnpts = 50\nx1, x2 = np.meshgrid(np.linspace(*xlim, npts), np.linspace(*xlim, npts))\n\nplt.subplot(131)\nmu = true_reg.predict(np.column_stack((x1.ravel(), x2.ravel())))\nplt.imshow(mu.reshape((npts, npts)),\n cmap=\"RdBu\", vmin=-ylim, vmax=ylim,\n alpha=0.8,\n extent=xlim + tuple(reversed(xlim)))\nplt.scatter(X[~inds,0], X[~inds,1], c=y[~inds, 0], cmap=\"RdBu\", vmin=-ylim, vmax=ylim, edgecolors='gray')\nplt.scatter(X[inds,0], X[inds,1], c=y[inds, 0], cmap=\"RdBu\", vmin=-ylim, vmax=ylim, edgecolors='k', linewidths=1)\nplt.xlim(xlim)\nplt.ylim(xlim)\nplt.title(\"True\")\n\nplt.subplot(132)\nmu = std_reg.predict(np.column_stack((x1.ravel(), x2.ravel())))\nplt.imshow(mu.reshape((npts, npts)),\n cmap=\"RdBu\", vmin=-ylim, vmax=ylim,\n alpha=0.8,\n extent=xlim + tuple(reversed(xlim)))\nplt.scatter(X[~inds,0], X[~inds,1], c=y[~inds, 0], cmap=\"RdBu\", vmin=-ylim, vmax=ylim, edgecolors='gray')\nplt.scatter(X[inds,0], X[inds,1], c=y[inds, 0], cmap=\"RdBu\", vmin=-ylim, vmax=ylim, edgecolors='k', linewidths=1)\nplt.xlim(xlim)\nplt.ylim(xlim)\nplt.title(\"Standard Regression\")\n\nplt.subplot(133)\nmu = robust_reg.predict(np.column_stack((x1.ravel(), x2.ravel())))\nplt.imshow(mu.reshape((npts, npts)),\n cmap=\"RdBu\", vmin=-ylim, vmax=ylim,\n alpha=0.8,\n extent=xlim + tuple(reversed(xlim)))\nplt.scatter(X[~inds,0], X[~inds,1], c=y[~inds, 0], cmap=\"RdBu\", vmin=-ylim, vmax=ylim, edgecolors='gray')\nplt.scatter(X[inds,0], X[inds,1], c=y[inds, 0], cmap=\"RdBu\", vmin=-ylim, vmax=ylim, edgecolors='k', linewidths=1)\nplt.xlim(xlim)\nplt.ylim(xlim)\nplt.title(\"Robust Regression\")\n\n\nprint(\"True A: {}\".format(true_reg.A))\nprint(\"Std A: {}\".format(std_As.mean(0)))\nprint(\"Robust A: {}\".format(robust_As.mean(0)))\n\n# Plot the log likelihoods and mean squared errors\nplt.figure(figsize=(8, 4))\nplt.subplot(121)\nplt.plot(std_lls)\nplt.plot(robust_lls)\nplt.xlabel(\"Iteration\")\nplt.ylabel(\"Log Likelihood\")\n\nplt.subplot(122)\nplt.plot(std_mses, label=\"Standard\")\nplt.plot(robust_mses, label=\"Robust\")\nplt.legend(loc=\"upper right\")\nplt.xlabel(\"Iteration\")\nplt.ylabel(\"Mean Squared Error\")\n\nplt.show()\n"
] |
[
[
"matplotlib.pyplot.legend",
"numpy.linspace",
"matplotlib.pyplot.plot",
"numpy.random.randn",
"numpy.mean",
"numpy.eye",
"matplotlib.pyplot.subplot",
"numpy.column_stack",
"numpy.zeros",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.title",
"matplotlib.pyplot.ylim",
"numpy.random.rand",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.scatter",
"numpy.random.seed",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.xlabel"
]
] |
duyetdev/api.duyetdev.com
|
[
"4c33cc2cfb43ad6c4089873230e7b657659bff15"
] |
[
"lib/gensim/test/test_logentropy_model.py"
] |
[
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2010 Radim Rehurek <[email protected]>\n# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html\n\n\"\"\"\nAutomated tests for checking transformation algorithms (the models package).\n\"\"\"\n\n\nimport logging\nimport unittest\nimport os\nimport os.path\nimport tempfile\n\nimport six\nimport numpy as np\nimport scipy.linalg\n\nfrom gensim.corpora import mmcorpus, Dictionary\nfrom gensim.models import logentropy_model\nfrom gensim import matutils\n\nmodule_path = os.path.dirname(__file__) # needed because sample data files are located in the same folder\ndatapath = lambda fname: os.path.join(module_path, 'test_data', fname)\n\n\n# set up vars used in testing (\"Deerwester\" from the web tutorial)\ntexts = [['human', 'interface', 'computer'],\n ['survey', 'user', 'computer', 'system', 'response', 'time'],\n ['eps', 'user', 'interface', 'system'],\n ['system', 'human', 'system', 'eps'],\n ['user', 'response', 'time'],\n ['trees'],\n ['graph', 'trees'],\n ['graph', 'minors', 'trees'],\n ['graph', 'minors', 'survey']]\ndictionary = Dictionary(texts)\ncorpus = [dictionary.doc2bow(text) for text in texts]\n\n\ndef testfile():\n # temporary data will be stored to this file\n return os.path.join(tempfile.gettempdir(), 'gensim_models.tst')\n\n\nclass TestLogEntropyModel(unittest.TestCase):\n def setUp(self):\n self.corpus_small = mmcorpus.MmCorpus(datapath('test_corpus_small.mm'))\n self.corpus_ok = mmcorpus.MmCorpus(datapath('test_corpus_ok.mm'))\n\n\n def testTransform(self):\n # create the transformation model\n model = logentropy_model.LogEntropyModel(self.corpus_ok, normalize=False)\n\n # transform one document\n doc = list(self.corpus_ok)[0]\n transformed = model[doc]\n\n expected = [(0, 0.3748900964125389),\n (1, 0.30730215324230725),\n (3, 1.20941755462856)]\n self.assertTrue(np.allclose(transformed, expected))\n\n\n def testPersistence(self):\n fname = testfile()\n model = logentropy_model.LogEntropyModel(self.corpus_ok, normalize=True)\n model.save(fname)\n model2 = logentropy_model.LogEntropyModel.load(fname)\n self.assertTrue(model.entr == model2.entr)\n tstvec = []\n self.assertTrue(np.allclose(model[tstvec], model2[tstvec]))\n\n def testPersistenceCompressed(self):\n fname = testfile() + '.gz'\n model = logentropy_model.LogEntropyModel(self.corpus_ok, normalize=True)\n model.save(fname)\n model2 = logentropy_model.LogEntropyModel.load(fname, mmap=None)\n self.assertTrue(model.entr == model2.entr)\n tstvec = []\n self.assertTrue(np.allclose(model[tstvec], model2[tstvec]))\n#endclass TestLogEntropyModel\n\n\nif __name__ == '__main__':\n logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.DEBUG)\n unittest.main()\n"
] |
[
[
"numpy.allclose"
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.